Exemplo n.º 1
0
    def _add_notch(self, layer, wire, extra_width, box_options):
        """Add a wire used marker to both sides of a box.

        Args:
            layer (int): x coordinate for the box center
            wire (int): y cordinate for the notches
            extra_width (float): extra box width
            box_options (dict): styling options
        """
        y = wire - self._notch_height / 2
        x1 = layer - self._box_length / 2.0 - extra_width / 2.0 - self._notch_width
        x2 = layer + self._box_length / 2.0 + extra_width / 2.0

        box1 = patches.FancyBboxPatch(
            (x1, y),
            self._notch_width,
            self._notch_height,
            boxstyle=self._notch_style,
            **box_options,
        )
        self._ax.add_patch(box1)
        box2 = patches.FancyBboxPatch(
            (x2, y),
            self._notch_width,
            self._notch_height,
            boxstyle=self._notch_style,
            **box_options,
        )
        self._ax.add_patch(box2)
Exemplo n.º 2
0
    def plot_diff_driver(self,
                         x,
                         y,
                         yaw,
                         steer=0.0,
                         robot_length=0.1,
                         wheel_radius=0.05):
        # plot diff driver as a circle
        robot = mpatches.Circle((x, y), robot_length, color='red', zorder=0)
        self.ax.add_patch(robot)
        # plot wheels
        wheel_1 = mpatches.FancyBboxPatch((-robot_length / 2, 0),
                                          wheel_radius / 2,
                                          wheel_radius,
                                          boxstyle=mpatches.BoxStyle("Round",
                                                                     pad=0.01),
                                          color='black',
                                          zorder=0)

        wheel_2 = mpatches.FancyBboxPatch((robot_length / 2, 0),
                                          wheel_radius / 2,
                                          wheel_radius,
                                          boxstyle=mpatches.BoxStyle("Round",
                                                                     pad=0.01),
                                          color='black',
                                          zorder=0)

        t1 = mpl.transforms.Affine2D().rotate_deg(math.degrees(yaw) - 90.0)
        t2 = mpl.transforms.Affine2D().translate(x, y)
        t = t1 + t2 + self.ax.transData
        wheel_1.set_transform(t)
        wheel_2.set_transform(t)

        self.ax.add_patch(wheel_1)
        self.ax.add_patch(wheel_2)
Exemplo n.º 3
0
def plot_ax2_rejected(ax2):
    ax2.set_title('Points per\nrejected-cloud', pad=5, fontsize=SMALL_SIZE + 1)
    ax2.set_xlim(-0.1, 2.1)
    ax2.set_ylim(-0.1, 1.1)
    x_coord = np.linspace(0.0, 2.0, num=nrejected + 1)
    widths = x_coord[1:] - x_coord[:-1]
    patches = []

    for i in range(nrejected):
        x_patch = x_coord[i]
        patches.append(
            mpatches.FancyBboxPatch(
                (x_patch, 0.0),
                widths[i],
                1.0,
                boxstyle=mpatches.BoxStyle("Round", pad=0.0,
                                           rounding_size=0.2)))
        add_label(ax2, (x_patch + 0.5 * widths[i], 0.5),
                  data_size[~ids_bool][i],
                  color='white')
    if nrejected == 0:
        patches.append(
            mpatches.FancyBboxPatch(
                (0.0, 0.0),
                2.0,
                1.0,
                boxstyle=mpatches.BoxStyle("Round", pad=0.0,
                                           rounding_size=0.2)))
        add_label(ax2, (1.0, 0.5), 'None', color='black')

    collection = PatchCollection(patches, alpha=1.0)
    collection.set_edgecolor('k')
    collection.set_facecolor(colors_all[~ids_bool])
    ax2.add_collection(collection)
    ax2.axis('off')
    def play(self, logger_folder=None, no_iter=-1):
        """ If logger_folder exists and the result file is saved, then the specific iteration can be chosen to play the animation. \\

            Parameter
            ----------
            logger_folder : string
                The name of the logger folder
            no_iter : int
                The number of iteration to play the animation
        """
        fig, ax = super().create_plot(xlim=(-4, 4), ylim=(-4, 4))
        trajectory = np.asarray(
            logger.read_from_json(logger_folder, no_iter)["trajectory"])
        pole1 = patches.FancyBboxPatch((0, 0), 0.04, self.l1, "round,pad=0.02")
        pole1.set_color('C0')
        pole2 = patches.FancyBboxPatch((0, 0), 0.04, self.l2, "round,pad=0.02")
        pole2.set_color('C1')
        ax.add_patch(pole1)
        ax.add_patch(pole2)
        self._is_interrupted = False
        for i in range(self.T):
            self.play_trajectory_current = trajectory[i, :, 0]
            # draw pole1
            t_start = ax.transData
            x1 = -0.02 * np.cos(self.play_trajectory_current[0])
            y1 = 0.02 * np.sin(self.play_trajectory_current[0])
            rotate_center = t_start.transform([x1, y1])
            pole1.set_x(x1)
            pole1.set_y(y1)
            t = mpl.transforms.Affine2D().rotate_around(
                rotate_center[0], rotate_center[1],
                -self.play_trajectory_current[0])
            t_end = t_start + t
            pole1.set_transform(t_end)
            # draw pole2
            x2 = self.l1 * np.sin(self.play_trajectory_current[
                0]) - 0.02 * np.cos(self.play_trajectory_current[0] +
                                    self.play_trajectory_current[2])
            y2 = self.l1 * np.cos(self.play_trajectory_current[
                0]) + 0.02 * np.sin(self.play_trajectory_current[0] +
                                    self.play_trajectory_current[2])
            rotate_center = t_start.transform([x2, y2])
            pole2.set_x(x2)
            pole2.set_y(y2)
            t = mpl.transforms.Affine2D().rotate_around(
                rotate_center[0], rotate_center[1],
                -self.play_trajectory_current[0] -
                self.play_trajectory_current[2])
            t_end = t_start + t
            pole2.set_transform(t_end)
            fig.canvas.draw()
            plt.pause(0.001)
            if self._is_interrupted:
                return
        self._is_interrupted = True
def gridworlddrawagent(x,y,a,colour,f,ax):
    overlap = 0
    w = 1+(overlap)*0.5
    if (a == 0):
       circle = patches.FancyBboxPatch(xy = (x-0.5,y-0.5),width=0.000000008,height=0.000000008, boxstyle='circle', facecolor=colour, linewidth= w) #create circle patches
       ax.add_patch(circle) # Add the patch to the Axes
    else:
        if a == 4:
            nx = x-1
            ny = y
        elif a == 3:
            nx = x
            ny = y-1
        elif a == 2:
            nx = x+1
            ny=y
        elif a == 1:
            nx = x
            ny = y+1
        vec = np.array([[(nx-x)*0.25],[(ny-y)*0.25]])
        norm1 = np.array([vec[1], -vec[0]])
        norm2 = -norm1
        xv = np.array([x-0.5+vec[0], x-0.5+norm1[0], x-0.5+norm2[0]])
        yv = np.array([y-0.5+vec[1], y-0.5+norm1[1], y-0.5+norm2[1]])
        xv = np.append(xv, xv[0])
        yv = np.append(yv, yv[0])
        ax.fill(xv, yv, colour, linewidth=w)
Exemplo n.º 6
0
def addpatch(x,y,r,tex,node,color="white",fill=True):
  
  # print("radius",r)
  
  # exit()

  lw=None
  if not fill:lw=2
  # plt.plot([x],[y],"o",color=color)
  
  # return
  # toa=patches.FancyBboxPatch((-r1/2/alpha2,-r2/2/alpha),r1/alpha2,r2/alpha,fill=fill,color=color,boxstyle="round",zorder=1,lw=lw)
  toa=patches.FancyBboxPatch((x-r*0.5,y-r*0.5),r,r,fill=fill,color=color,boxstyle="round",zorder=1,lw=lw)
  ax.add_patch(toa)
  
  
  if not tex is None:
    # toa2=patches.Rectangle((x-r,y-r),2*r,2*r,color="grey")
    
# xy : float, float The lower left corner of the box.  width : float The width of the box.  height : float The 
    
    q=plt.text(x,y, tex[:10],
           ha="center", va="center",fontsize=200/node["looplen"]
           # bbox={"xy":(x-r,y-r),"width":2*r,"height":2*r}
  #         bbox=dict(boxstyle="square",
  #                   ec=(1., 0.5, 0.5),
  #                   fc=(1., 0.8, 0.8),
  #                   )
           )
Exemplo n.º 7
0
def textRectangled(ax,
                   x,
                   y,
                   text,
                   font_size,
                   color=None,
                   rect_width=8,
                   fontweight="bold"):
    """
        x,y: center of the text location
    """
    t = ax.text(x,
                y,
                text,
                fontsize=font_size,
                fontweight=fontweight,
                horizontalalignment='center',
                verticalalignment='center')
    h = 0.05 * font2mm(font_size)
    x_rect = x - rect_width / 2.0
    y_rect = y - font2mm(font_size) / 2 + 0.4 * font2mm(font_size)
    ecolor = color if color else "gray"
    fcolor = color if color else "none"
    rect = mpatches.FancyBboxPatch((x_rect, y_rect),
                                   width=rect_width,
                                   height=h,
                                   alpha=0.4,
                                   facecolor=fcolor,
                                   edgecolor=ecolor,
                                   boxstyle='round,pad=1.5')
    ax.add_artist(rect)
Exemplo n.º 8
0
def makeFancyBox(x, y, width, height):
    fancybox = mpatches.FancyBboxPatch([x, y],
                                       width,
                                       height,
                                       boxstyle=mpatches.BoxStyle("Round",
                                                                  pad=1))
    patches.append(fancybox)
Exemplo n.º 9
0
    def init_fig(self, num):
        self.spots = []
        self.spots_text_num = []
        h_interval = 0.2
        v_interval = 0.2

        for i in range(16):
            x = 0.03 + int(i % 4) * h_interval
            y = 0.64 - int(i // 4) * v_interval
            s = mpatches.FancyBboxPatch([x, y],
                                        0.15,
                                        0.15,
                                        facecolor="white",
                                        boxstyle=mpatches.BoxStyle("square",
                                                                   pad=0.01))

            self.spots.append(s)
            t = self.ax.text(x + 0.02,
                             y + 0.04,
                             str(num[i]),
                             fontsize=14,
                             fontweight="bold")
            self.spots_text_num.append(t)

        self.ax.set_xlim(0, 0.8)
        self.ax.set_ylim(0, 0.8)
        collection = PatchCollection(self.spots)
        self.spots = self.ax.add_collection(collection)
        self.spots.set_facecolors('white')
        self.spots.set_edgecolors('gray')
Exemplo n.º 10
0
    def animation(self):
        for obstacle in self.obstacles:
            obs = mpatches.FancyBboxPatch(
                (obstacle[0] - obstacle[2] / 2, obstacle[1] - obstacle[2] / 2),
                obstacle[2],
                obstacle[2],
                boxstyle=mpatches.BoxStyle("Round", pad=0.01),
                color='red')
            self.ax.add_patch(obs)

        self.ax.plot(self.goal[0], self.goal[1], "xr")
        self.ax.plot(self.start[0, 0], self.start[1, 0], "ob")

        for node in self.nodes:
            if node[3] != None:
                plt.plot([node[0], self.nodes[node[3]][0]],
                         [node[1], self.nodes[node[3]][1]], "-k")

#        self.ax.axis('equal')

        self.ax.set_xlim(-20, 20)
        self.ax.set_ylim(-20, 20)

        plt.xlabel('x [m]')
        plt.ylabel('y [m]')
        plt.title('RRT* Planner')
        #        if self.itr%5 == 0:
        #        plt.savefig("images/"+ str(self.itr) +".png")
        self.itr += 1
        plt.pause(0.001)
Exemplo n.º 11
0
    def play(self, logger_folder=None, no_iter = -1):
        """ If logger_folder exists and the result file is saved, then the specific iteration can be chosen to play the animation. \\

            Parameter
            ----------
            logger_folder : string
                The name of the logger folder
            no_iter : int
                The number of iteration to play the animation
        """
        fig, ax = super().create_plot(figsize=(8, 2), xlim=(-5,75), ylim=(-15,5))
        trajectory = np.asarray(logger.read_from_json(logger_folder, no_iter)["trajectory"])
        car = patches.FancyBboxPatch((0, 0), 3, 2, "round,pad=0.02")
        car.set_color('C0')
        ax.add_patch(car)
        plt.plot(trajectory[:,0], trajectory[:,1])
        self._is_interrupted=False
        for i in range(self.T):
            angle = trajectory[i,2,0]
            t_start = ax.transData
            x = trajectory[i,0,0] + 1*np.sin(angle)
            y = trajectory[i,1,0] - 1*np.cos(angle)
            rotate_center = t_start.transform([x, y])
            car.set_x(x)
            car.set_y(y)
            t = mpl.transforms.Affine2D().rotate_around(rotate_center[0], rotate_center[1], angle)
            t_end = t_start + t
            car.set_transform(t_end)
            fig.canvas.draw()
            plt.pause(0.01)
            if self._is_interrupted:
                return
        self._is_interrupted = True
Exemplo n.º 12
0
def Grid(build, variant, amount, totalScore):
    """Places the created houses visually on a grid."""

    # Grid initialization
    fig, ax = plt.subplots()
    plt.axis('scaled')
    plt.xlabel('180 meter')
    plt.ylabel('160 meter')
    ax.grid(which='major', axis='both', color ='silver', linestyle='--')
    intervals = 10
    loc = plticker.MultipleLocator(base=intervals)
    ax.xaxis.set_major_locator(loc)
    ax.yaxis.set_major_locator(loc)
    ax.set_xlim(0, theGrid.xMAX)
    ax.set_ylim(0, theGrid.yMAX)
    ax.set_axisbelow(True)
    plt.suptitle(variant + ' - ' + str(amount) + ' buildings')
    plt.title('score: ${:,.2f}'.format(totalScore))

    # static waterbody placement
    water = Waterbody(20, 104, 40, 36)
    water2 = Waterbody(120, 104, 40, 36)
    water3 = Waterbody(20, 20, 40, 36)
    water4 = Waterbody(120, 20, 40, 36)

    water = patches.Rectangle((water.x, water.y), water.width,
            water.length, facecolor=Waterbody.color, \
            edgecolor = Waterbody.edgecolor)
    ax.add_artist(water)

    water2 = patches.Rectangle((water2.x, water2.y), water2.width,
            water2.length, facecolor=Waterbody.color, \
            edgecolor = Waterbody.edgecolor)
    ax.add_artist(water2)

    water3 = patches.Rectangle((water3.x, water3.y), water3.width,
            water3.length, facecolor=Waterbody.color, \
            edgecolor = Waterbody.edgecolor)
    ax.add_artist(water3)

    water4 = patches.Rectangle((water4.x, water4.y), water4.width,
            water4.length, facecolor=Waterbody.color, \
            edgecolor = Waterbody.edgecolor)
    ax.add_artist(water4)

    # iterate over each house in the build array build and place house on grid
    for i in build:
        meters = i.mtr_clearance

        # temp variable with building information
        temp = patches.Rectangle((i.x, i.y), i.width, i.length,
                facecolor=i.color, edgecolor = 'black')

        clearance = patches.FancyBboxPatch((i.x, i.y), i.width, i.length, \
                    boxstyle = patches.BoxStyle('round', pad = meters),
                    color = i.color, alpha = 0.4)

        # add building to visual grid
        ax.add_artist(temp)
        ax.add_artist(clearance)
Exemplo n.º 13
0
 def draw(self, ax, facecolor, alpha=1., text_size="small"):
     L = []
     
     L.append(patches.FancyBboxPatch(
         self.box_xy,
         width=self.width,
         height=self.height,
         boxstyle="round,pad=0.1",
         facecolor=facecolor,
         alpha=alpha
     ))
     L.append(text.Text(self.xy[0], self.xy[1], self.text,
         ha="center", va="center", size=text_size, alpha=alpha))
     if self.parent:
         L.append(common.arrow_by_start_end(
             self.father_a_xy,
             self.a_xy,
             length_includes_head=True,
             color="black",
             head_width=0.1,
             alpha=alpha))
     
     for a in L:
         ax.add_artist(a)
     self.patches[ax] = L
Exemplo n.º 14
0
def draw_bbox(img_path):
    img_id = img_path.split('/')[-1].split('.')[0]
    img = mpimg.imread(img_path)
    detections = df_detections[df_detections.id == img_id].detections.values[0]
    annotation = df_train_annotations[df_train_annotations.image_id == img_id]

    count = annotation['count'].values
    cat_id = annotation.category_id
    cat = df_cat[df_cat.id == int(cat_id)].name.values[0]

    _ = plt.figure(figsize=(15, 20))
    _ = plt.axis('off')
    ax = plt.gca()
    ax.text(10, 100, f'{cat} {count}', fontsize=20, color='fuchsia')

    for detection in detections:
        # ref - https://github.com/microsoft/CameraTraps/blob/e530afd2e139580b096b5d63f0d7ab9c91cbc7a4/visualization/visualization_utils.py#L392
        x_rel, y_rel, w_rel, h_rel = detection['bbox']
        img_height, img_width, _ = img.shape
        x = x_rel * img_width
        y = y_rel * img_height
        w = w_rel * img_width
        h = h_rel * img_height

        cat = 'animal' if detection['category'] == "1" else 'human'
        bbox = patches.FancyBboxPatch((x, y), w, h, alpha=0.8, linewidth=6, capstyle='projecting', edgecolor='fuchsia',
                                      facecolor="none")

        ax.text(x + 1.5, y - 8, f'{cat} {detection["conf"]}', fontsize=10,
                bbox=dict(facecolor='fuchsia', alpha=0.8, edgecolor="none"))
        ax.add_patch(bbox)

    _ = plt.imshow(img)
    plt.show()
Exemplo n.º 15
0
    def __init__(self, ll_point, ur_point, fc, ec, boxstyle, mplprops, figure):
        #ll_point - lower left Point
        #ur_point - upper right Point
        """
		Box style:
				class 			Name 			Attrs
				----------------------------------------
				Circle		|	circle		|	pad=0.3
				DArrow		|	darrow		|	pad=0.3
				LArrow		|	larrow		|	pad=0.3
				RArrow		|	rarrow		|	pad=0.3
				Round		|	round		|	pad=0.3,rounding_size=None
				Round4		|	round4		|	pad=0.3,rounding_size=None
				Roundtooth	|	roundtooth	|	pad=0.3,tooth_size=None
				Sawtooth	|	sawtooth	|	pad=0.3,tooth_size=None
				Square		|	square		|	pad=0.3
		"""
        self.figure = figure
        bb = mtransforms.Bbox([ll_point, ur_point])
        self.matplotlib_obj = patches.FancyBboxPatch((bb.xmin, bb.ymin),
                                                     abs(bb.width),
                                                     abs(bb.height),
                                                     boxstyle=boxstyle,
                                                     fc=fc,
                                                     ec=ec,
                                                     **mplprops)
        self.patch = self.figure.ax.add_patch(self.matplotlib_obj)
Exemplo n.º 16
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)
    expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)"
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True)
    p = mpatches.PathPatch(path)
    assert str(p) == "PathPatch3((1, 2) ...)"

    p = mpatches.Polygon(np.empty((0, 2)))
    assert str(p) == "Polygon0()"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=path)
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"
Exemplo n.º 17
0
def generate_fig1(width=4):
    fig = Figure(figsize=(width, 4))
    canvas = FigureCanvas(fig)
    ax = fig.add_axes((0.01, 0.01, 0.98, 0.98))
    common.set_ax_params(ax)
    ax.axis([0., 1., 0., 1.])

    for i, w in enumerate([0.1, 0.3, 0.5, 0.7, 0.9]):
        ax.add_patch(
            patches.FancyBboxPatch((0.5 - w / 2., 0.5 - w / 2.),
                                   width=w,
                                   height=w,
                                   boxstyle="round,pad=0.01",
                                   facecolor="blue",
                                   edgecolor="None",
                                   alpha=0.3))

    for i, w in enumerate([0.1, 0.3, 0.5, 0.7, 0.9]):
        ax.add_patch(
            patches.FancyBboxPatch(
                (0.5 - w / 2., 0.5 - w / 2.),
                width=w,
                height=w,
                boxstyle="round,pad=0.01",
                facecolor="None",
                edgecolor="black",
            ))

        if i > 0:
            ax.text(0.5 - w / 2.,
                    0.5 - w / 2.,
                    "$\\pi_{}=$MCTS$(\\pi_{})$".format(i, i - 1),
                    ha="left",
                    va="bottom",
                    size="small",
                    color="yellow")
        else:
            ax.text(0.5 - w / 2.,
                    0.5 - w / 2.,
                    "$\\pi_0$",
                    ha="left",
                    va="bottom",
                    size="small",
                    color="yellow")

    common.save_next_fig(PART_NUM, fig)
Exemplo n.º 18
0
def rounded_rect_patch(x, y, width, height):
    fancybox = mpatches.FancyBboxPatch((x, y),
                                       width,
                                       height,
                                       boxstyle=mpatches.BoxStyle("Round",
                                                                  pad=0.02))

    return fancybox
Exemplo n.º 19
0
def fancybox(ax,loc,heigt,width,color,alpha):
    patches=[]
    fancybox = mpatches.FancyBboxPatch(
        loc, height, width,
        boxstyle=mpatches.BoxStyle("square", pad=0))
    patches.append(fancybox)
    collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=alpha,edgecolor="none",facecolor=color)
    ax.add_collection(collection)
Exemplo n.º 20
0
Arquivo: lv.py Projeto: roualdes/bplot
 def vert_perc_box(x, b, i, k, w):
     rect = Patches.FancyBboxPatch(
         (x - widths * w / 2, b[0]),
         widths * w,
         height(b),
         fill=True,
         boxstyle="round,pad=0.05",
     )
     return rect
Exemplo n.º 21
0
def plotAngMomTotal_mat(impactDir, impactName, dobrFname, saveDir):
    # Integrate the Angular momentum from the
    # data-out-binary-reader file (dobrDat)
    dobrDat = dor.DataOutBinReader()
    cycs, numCycs = dobrDat.getCycles(dobrFname, impactDir + impactName)
    AMmat1 = np.zeros(numCycs)
    AMmat2 = np.zeros(numCycs)
    print "Number of dumps to analyze: {}".format(len(cycs))
    dobrTs = np.zeros(numCycs)
    for i, cyc in enumerate(cycs):
        dobrDat = dor.DataOutBinReader()
        dobrDat.readSev(dobrFname, cyc, impactDir + impactName)
        print "Time of this data dump: {}".format(dobrDat.times[0] / 3600)
        dobrTs[i] = dobrDat.times[0] / 3600

        AMmat1[i] = 1e-7 * (np.power(
            np.power(np.asarray(dobrDat.LX[0]), 2) +
            np.power(np.asarray(dobrDat.LY[0]), 2) +
            np.power(np.asarray(dobrDat.LZ[0]), 2), 0.5) *
                            np.asarray(dobrDat.M1[0])).sum()
        AMmat2[i] = 1e-7 * (np.power(
            np.power(np.asarray(dobrDat.LX[0]), 2) +
            np.power(np.asarray(dobrDat.LY[0]), 2) +
            np.power(np.asarray(dobrDat.LZ[0]), 2), 0.5) *
                            np.asarray(dobrDat.M2[0])).sum()

    colors = parula_map(np.linspace(0, 1, 2))

    fig, ax_AM = plt.subplots()
    '''
    dobrTs = dobrTs[:2]
    AMmat1 = AMmat1[:2]
    AMmat2 = AMmat2[:2]
    '''
    ax_AM.fill_between(dobrTs, 0, AMmat1, color=colors[0])
    ax_AM.fill_between(dobrTs, AMmat1, AMmat1 + AMmat2, color=colors[1])

    ax_AM.set_ylabel("Angular Momentum (kg m^2/s)")
    ax_AM.set_xlabel("Time (hr)")

    x1, x2, y1, y2 = plt.axis()
    ax_AM.set_ylim([AMmat1.min(), (AMmat1 + AMmat2).max()])
    ax_AM.set_xlim([0, dobrTs[-1]])

    # make proxy artists for legend entries
    boxes = []
    for c in colors:
        boxes.append(mpatches.FancyBboxPatch((0, 0), 1, 1, fc=c))

    fig.legend(boxes, ("Mantle", "Core"))

    # make sure saveDir has '/' before saving
    if saveDir[-1] != '/':
        saveDir = saveDir + '/'
    fig.savefig(saveDir + "angMomTotal_mat.png")

    return dobrTs, AMmat1, AMmat2
Exemplo n.º 22
0
    def get_patch(self):
        """
        Draw of a matplotlib patch to be added to the graph plot.

        Returns:
            Matplotlib.Patch
        """
        rect = patches.FancyBboxPatch(self.center-np.array([self.a,self.b]),2*self.a,2*self.b,boxstyle='round, pad=%f'%self.rad,**self.plot_parameters)
        return(rect)
Exemplo n.º 23
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"
Exemplo n.º 24
0
    def draw_chromosome(self, side):
        tmp=self.ch_graph_start_coord
        if side=='3':
            self.ch_graph_start_coord=self.ch_graph_start_coord+1.0
        if side=='4':
            self.ch_graph_start_coord=self.ch_graph_start_coord+0.5

        #changed add /scale make it shorter
        scale = 1.0
        if side =='5':
            scale = scale_5
        else:
            scale = scale_3

        acen_start = int(next(region for region in self.ch_regions if region[4] == 'acen')[1])
        acen_end = int(next(region for region in list(reversed(self.ch_regions)) if region[4] == 'acen')[2])

        self.arm_length_left = float(acen_start)/self.ch_length/scale
        self.arm_length_right = (self.ch_length - float(acen_end))/self.ch_length/scale

        #changed
        if side =='5':
            self.acen_length_5 = acen_end - acen_start
        else:
            self.acen_length_3 = acen_end - acen_start

        self.centrolmere_x = self.ch_graph_start_coord + self.arm_length_left + self.centrolmere_radius + self.pad_size

        centrolmere = patches.Circle((self.centrolmere_x, self.centrolmere_y), self.centrolmere_radius, ec="none", color = "black")

        chrom_arm_1 = patches.FancyBboxPatch(
            (self.centrolmere_x + 0.05, self.centrolmere_y - self.arm_width/2), self.arm_length_right, self.arm_width,
            facecolor= "gray", ec = "black",
            boxstyle=patches.BoxStyle("Round", pad = self.pad_size))

        chrom_arm_2 = patches.FancyBboxPatch(
            (self.centrolmere_x - 0.05 - self.arm_length_left, self.centrolmere_y - self.arm_width/2), self.arm_length_left, self.arm_width,
            facecolor= "gray", ec = "black",
            boxstyle=patches.BoxStyle("Round", pad = self.pad_size))

        self.ax.add_patch(chrom_arm_1)
        self.ax.add_patch(chrom_arm_2)
        self.ax.add_patch(centrolmere)
        self.ch_graph_start_coord=tmp
Exemplo n.º 25
0
def generate_fig1():
    fig = Figure(figsize=(6, 4))
    canvas = FigureCanvas(fig)
    ax = fig.add_axes((0.01, 0.01, 0.98, 0.98))
    common.set_ax_params(ax)
    ax.axis([0., 1.5, 0., 1.])

    r = 0.05
    ax.add_patch(patches.FancyBboxPatch(
        (0.1 - r, 0.5 - r),
        width=2 * r,
        height=2 * r,
        boxstyle="round,pad=0.01",
        facecolor="lightblue"
    ))
    ax.text(0.1, 0.5, "$s$", ha="center", va="center", size="large")
    heights = np.linspace(0.8, 0.2, 3)
    x = np.linspace(0.3 + r + 0.01, 1.4, 10)

    for i in range(3):
        h = heights[i]
        
        for j in range(3):
            base = h + (j - 1) / 12.
            y = base + np.random.uniform(-1., 1., 10) / 30.
            y[0] = h + (j - 1) / 24.
            ax.add_artist(lines.Line2D(x, y, color="black"))
            ax.add_patch(patches.Circle((x[-1], y[-1]), 0.01, color="black"))
        
        ax.add_patch(patches.FancyBboxPatch(
            (0.3 - r, h - r),
            width=2 * r,
            height=2 * r,
            boxstyle="round,pad=0.01",
            facecolor="lightgreen"
        ))
        ax.text(0.3, h, "$a_{}$".format(i),
            ha="center", va="center", size="large")

        ax.add_patch(common.arrow_by_start_end(
            (0.1 + r + 0.01, 0.5 + r * (1 - i) / 3.), (0.3 - r - 0.01, h),
            length_includes_head=True, color="black", head_width=0.02))

    common.save_next_fig(PART_NUM, fig)
Exemplo n.º 26
0
def plot_ax4_mean(ax4,
                  fit_pars_portions,
                  fc='none',
                  marker='o',
                  label='clds mean',
                  s=90,
                  ls='--',
                  lw=1,
                  **kwargs):
    #I wanted to draw the mean of the portions as a tiny pie, however it seems to over-saturate the image with info.
    fit_pars = np.asarray(fit_pars_portions)
    center = np.average(fit_pars[:, 0:2], axis=0, weights=data_size[ids_bool])
    std_dv = np.sqrt(
        np.average((fit_pars[:, 0] - center[0])**2,
                   weights=data_size[ids_bool]))
    std_alpha = np.sqrt(
        np.average((fit_pars[:, 1] - center[1])**2,
                   weights=data_size[ids_bool]))

    ax4.scatter(*center,
                facecolors=fc,
                marker=marker,
                s=s,
                edgecolors='black',
                alpha=1.0,
                label=label,
                linestyles=ls,
                linewidths=lw,
                **kwargs)

    add_label(ax4, (0.25, 0.199),
              r'$\sigma_{\upsilon_0}=%.2f$, $\sigma_\alpha=%.2f$ from ' %
              (std_dv, std_alpha),
              fontsize=SMALL_SIZE,
              transform=ax4.transAxes)
    ax4.scatter(0.5,
                0.2105 - 0.15,
                facecolors=fc,
                marker=marker,
                s=s,
                edgecolors='black',
                alpha=1.0,
                linestyles=ls,
                linewidths=lw,
                transform=ax4.transAxes,
                **kwargs)

    patch = mpatches.FancyBboxPatch(
        (0.01, 0.01),
        0.53,
        0.1,
        facecolor='none',
        linewidth=1.4,
        transform=ax4.transAxes,
        boxstyle=mpatches.BoxStyle("Round", pad=0.0, rounding_size=0.03))
    ax4.add_artist(patch)
def draw_tree(draw_info):
    patches = []

    fig, ax = plt.subplots(figsize=(18, 12))

    timer = fig.canvas.new_timer(
        interval=10000
    )  # creating a timer object and setting an interval of 10 sec
    timer.add_callback(close_event)
    lines = []
    text_size = 14
    box_width = 10
    for node in draw_info.values():
        x_coord = node[1]
        y_coord = node[2]
        text = node[0]
        if len(node) > 3:
            l1_x_coord = node[3]
            l1_y_coord = node[4]
            l2_x_coord = node[5]
            l2_y_coord = node[6]
        this_node = mpatches.FancyBboxPatch(xy=[x_coord, y_coord],
                                            width=box_width,
                                            height=1,
                                            boxstyle=mpatches.BoxStyle("Round",
                                                                       pad=4))
        patches.append(this_node)
        # last_node = last_node_coords[node//2]
        line = mlines.Line2D(
            [l1_x_coord + (box_width // 2), l2_x_coord + (box_width // 2)],
            [l1_y_coord, l2_y_coord + 1])
        lines.append(line)
        plt.text(x_coord + 5,
                 y_coord,
                 text,
                 ha="center",
                 family='sans-serif',
                 size=text_size)

    colors = np.linspace(0, 1, len(patches))
    collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
    collection.set_array(np.array(colors))
    ax.add_collection(collection)
    for line in lines:
        ax.add_line(line)

    plt.axis('equal')
    plt.axis('off')
    plt.tight_layout()
    plt.ion()
    # timer.start()
    plt.savefig(f'{DOMAIN}_expert_policy.png')

    plt.show()
    # timer.stop()
    plt.pause(0.01)
Exemplo n.º 28
0
    def init_figure(self):
        ''' initial drawing '''

        common_keys = dict(va='baseline', ha="center")
        kwargs = dict(fc=self.bg, ec=self.normal, lw=1.5)

        # 10W Label
        self.axes.text(0.1,
                       0.3,
                       "10W",
                       common_keys,
                       size=11,
                       color=self.normal)

        # 10W frame
        bs = mpatches.BoxStyle("Round4", pad=0.05)
        self.frame_10w = mpatches.FancyBboxPatch((0.046, 0.2), 0.11, 0.6, \
                                          boxstyle=bs, **kwargs)
        self.axes.add_patch(self.frame_10w)

        # 600W Label
        self.axes.text(0.36,
                       0.3,
                       "600W",
                       common_keys,
                       size=11,
                       color=self.normal)

        # 600# frame
        self.frame_600w = mpatches.FancyBboxPatch((0.3, 0.2), 0.11, 0.6, \
                                          boxstyle=bs, **kwargs)
        self.axes.add_patch(self.frame_600w)

        self.axes.set_ylim(min(self.y_scale), max(self.y_scale))
        self.axes.set_xlim(min(self.x_scale), max(self.x_scale))
        # # disable default x/y axis drawing
        #self.axes.set_xlabel(False)
        #self.axes.apply_aspect()
        self.axes.set_axis_off()

        #self.axes.set_xscale(10)
        #self.axes.axison=False
        self.draw()
Exemplo n.º 29
0
def draw_box(ax, bb):

    # a fancy box with round corners. pad=0.1
    box = mpatches.FancyBboxPatch((bb['xmin'] + 10, bb['ymin'] + 10),
                                  abs(bb['width'] - 20),
                                  abs(bb['height'] - 20),
                                  boxstyle="round,pad=10.0",
                                  fc=(0.9, 0.9, 0.9),
                                  ec=(0.1, 0.1, 0.1))

    ax.add_patch(box)
Exemplo n.º 30
0
def basepatch(color="white", fill=True):
    lw = None
    if not fill: lw = 2
    toa = patches.FancyBboxPatch((-r1 / 2 / alpha2, -r2 / 2 / alpha),
                                 r1 / alpha2,
                                 r2 / alpha,
                                 fill=fill,
                                 color=color,
                                 boxstyle="round",
                                 zorder=1,
                                 lw=lw)
    ax.add_patch(toa)