Esempio n. 1
0
    def _add_north_east(self, fig):

        if self.obs_mode == 'LIFU':
            origin_x = 0.66
            origin_y = 0.09
        elif self.obs_mode == 'mIFU':
            origin_x = 0.81
            origin_y = 0.07

        lenght = 0.05
        width = 0.001
        head_width = 3 * width
        head_length = 1.5 * head_width
        text_factor = 1.2

        north_arrow = FancyArrow(
            origin_x, origin_y, 0, lenght,
            width=width, head_width=head_width, head_length=head_length,
            transform=fig.transFigure, figure=fig)

        east_arrow = FancyArrow(
            origin_x, origin_y, -self.figaspect * lenght, 0,
            width=(width / self.figaspect),
            head_width=(head_width / self.figaspect),
            head_length=(head_length * self.figaspect),
            transform=fig.transFigure, figure=fig)

        fig.lines.extend([north_arrow, east_arrow])

        fig.text(origin_x, origin_y + text_factor * lenght,
                 'N', ha='right')
        fig.text(origin_x - text_factor * self.figaspect * lenght, origin_y,
                 'E', ha='right')
    def show(self):
        """Plot out the trial."""
        ax = plt.axes(xlim=(-30, 300), ylim=(-30, 300))
        line, = ax.plot([], [])

        ax.add_patch(FancyArrow(0, 0, 300, 0, color='black'))
        ax.add_patch(FancyArrow(0, 0, 0, 300, color='black'))
        ax.add_patch(FancyArrow(270, 270, 0, -300, color='black'))
        ax.add_patch(FancyArrow(270, 270, -300, 0, color='black'))

        # add targets
        for target in self.env.targets:
            ax.add_patch(Circle(target[0], target[1], color='gray'))

        for a in self.env.agents:
            for i in range(self.iteration):
                ax.add_patch(Circle(a.loc_data[-i], a.r, color=a.color))
                ax.add_patch(
                    FancyArrow(a.loc_data[-i][0],
                               a.loc_data[-i][1],
                               find_dx(a.loc_data[-i][0], a.ang_data[-i], a.r),
                               find_dy(a.loc_data[-i][1], a.ang_data[-i], a.r),
                               color='black',
                               length_includes_head=True,
                               head_width=0.2))

        ax.set_aspect('equal')
        ax.figure.set_size_inches(6, 6)
Esempio n. 3
0
def main():
    R = np.array([[0, 0], [1, 0], [0, 2], [1.5, 2]])

    P = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])

    Q, r, _ = convex_solution(R, P)

    ax: plt.Axes
    fig, ax = plt.subplots()

    R_scat = ax.scatter(*R.T, c="black")
    Q_scat = ax.scatter(*Q.T, c="green")

    vecs = Q - R

    arrows = [
        FancyArrow(0, 0, *vec, color="black", head_width=0.02) for vec in vecs
    ]
    arrows.append(
        FancyArrow(0, 0, *(vecs[0] + vecs[1]), color="green", head_width=0.02))
    for arrow in arrows:
        ax.add_patch(arrow)

    for p in P[2:]:
        tri = Triangle(PlanarTriangle([*P[:2], p]).angles)
        c = tri.trivial_replication_point(*P[:2])
        ax.scatter(*c, color="blue")

    ax.axis("square")
    plt.show()
Esempio n. 4
0
 def drawNode(node, prv):
     if node.code == 'nivvie':
         return
     prev = prv + 0
     val = node.vals[0]
     bot = prev
     for child in node.children:
         drawNode(child, prev)
         prev += child.vals[0]
     if (val != 0) and node.visible and node.code != 'root':
         r, g, b = node.color
         a = FancyArrow(number[0] + barwidth / 2,
                        bot,
                        0,
                        val,
                        width=barwidth,
                        fc=(r / 255, g / 255, b / 255),
                        linewidth=0.5,
                        edgecolor='black',
                        label=node.desc,
                        picker=True,
                        length_includes_head=True,
                        head_width=barwidth,
                        head_length=abs(val / 15))
         a.top = bot + max(0, val)
         a.absci = number[0] + 0
         #            a = Rectangle((number[0], bot), barwidth, val, fc = node.color, linewidth = 0.5, edgecolor = 'black', label = node.desc, picker = True)
         a.value = round(val)
         patches.append(a)
         codes.append(node.code)
         shortnames.append(node.shortname)
         number[0] += 1
Esempio n. 5
0
    def drawNode(node, prv):
        prev = prv + 0
        val = node.vals[0]
        bot = prev
        for child in node.children:
            drawNode(child, prev)
            prev += child.vals[0]
        if (val != 0) and node.visible:
            r, g, b = node.color
            arrow = FancyArrow(
                number[0] + barwidth / 2, bot, 0, val,
                width = barwidth,
                fc = (r / 255, g / 255, b / 255), linewidth = 0.5, edgecolor = 'black',
                label = node.desc, picker = True, length_includes_head = True,
                head_width = barwidth,
                head_length = abs(val / 15),
                )
            arrow.top = bot + max(0, val)
            arrow.absci = number[0] + 0
#            a = Rectangle((number[0], bot), barwidth, val, fc = node.color, linewidth = 0.5, edgecolor = 'black', label = node.desc, picker = True)
            arrow.value = round(val)
            patches.append(arrow)
            codes.append(node.code)
            shortnames.append(node.shortname)
            number[0] += 1
Esempio n. 6
0
def plot_vectors(axes, image_geo_extents, vector_file, user_scale_factor):

    with open(vector_file) as json_file:
        origins_vectors = json.load(json_file)
    origins_vectors_numpy = np.asarray(origins_vectors)

    plot_width_in_pixels = axes.get_window_extent().width
    plot_width_in_ground_units = image_geo_extents[1] - image_geo_extents[0]
    pixels_per_ground_unit = plot_width_in_pixels / plot_width_in_ground_units
    ground_units_per_pixel = plot_width_in_ground_units / plot_width_in_pixels

    vector_lengths_ground = np.linalg.norm(origins_vectors_numpy[:, 2:],
                                           axis=1)
    vector_lengths_pixels = vector_lengths_ground * pixels_per_ground_unit

    arrow_scale_factor = (
        30 * ground_units_per_pixel) / np.median(vector_lengths_ground)
    arrow_head_scale_factor = 8 * ground_units_per_pixel

    for i in range(len(origins_vectors)):
        arrow = FancyArrow(
            origins_vectors[i][0],
            origins_vectors[i][1],
            origins_vectors[i][2] * arrow_scale_factor * user_scale_factor,
            -origins_vectors[i][3] * arrow_scale_factor *
            user_scale_factor,  # Negative sign converts from dV (positive down) to dY (positive up)
            length_includes_head=True,
            head_width=arrow_head_scale_factor,
            overhang=0.8,
            fc='yellow',
            ec='yellow')
        axes.add_artist(arrow)

    geo_height = image_geo_extents[3] - image_geo_extents[2]
    legend_background = Rectangle((image_geo_extents[0] + geo_height / 50,
                                   image_geo_extents[2] + geo_height / 50),
                                  geo_height / 7,
                                  geo_height / 7,
                                  fc='silver',
                                  clip_on=False,
                                  alpha=0.75)
    axes.add_artist(legend_background)
    plt.text(image_geo_extents[0] + geo_height / 50 + geo_height / 14,
             image_geo_extents[2] + geo_height / 7,
             '{0:.3f}'.format(
                 np.median(vector_lengths_ground) / user_scale_factor),
             horizontalalignment='center',
             verticalalignment='top')
    arrow = FancyArrow(image_geo_extents[0] + geo_height / 50 +
                       (geo_height / 7 - 30 * ground_units_per_pixel) / 2,
                       image_geo_extents[2] + geo_height / 14,
                       30 * ground_units_per_pixel,
                       0,
                       length_includes_head=True,
                       head_width=arrow_head_scale_factor,
                       overhang=0.8,
                       fc='yellow',
                       ec='yellow')
    axes.add_artist(arrow)
Esempio n. 7
0
    def show(self):
        """Show network."""
        ax = plt.axes(xlim=(0, max(self.i, self.h, self.o) * 25 + 25),
                      ylim=(0, 200))
        line, = ax.plot([], [])
        ax.set_aspect('equal')
        ax.figure.set_size_inches(5, 2)

        i_nodes = []
        h_nodes = []
        o_nodes = []

        x = 25
        y = 150
        for t in range(self.i):
            ax.add_patch(Circle((x, y), 10, color='green'))
            i_nodes.append((x, y))
            x += 25

        y -= 50
        x = (max(self.i, self.h, self.o) - self.h) / 2 * 25 + 25
        for t in range(self.h):
            ax.add_patch(Circle((x, y), 10, color='purple'))
            h_nodes.append((x, y))
            x += 25

        y -= 50
        x = (max(self.i, self.h, self.o) - self.o) / 2 * 25 + 25
        for t in range(self.o):
            ax.add_patch(Circle((x, y), 10, color='blue'))
            o_nodes.append((x, y))
            x += 25

        for t in i_nodes:
            for j in h_nodes:
                ax.add_patch(
                    FancyArrow(t[0],
                               t[1],
                               j[0] - t[0],
                               j[1] - t[1],
                               width=0.00000001,
                               color='black',
                               length_includes_head=True,
                               head_width=3))
        for t in h_nodes:
            for j in o_nodes:
                ax.add_patch(
                    FancyArrow(t[0],
                               t[1],
                               j[0] - t[0],
                               j[1] - t[1],
                               width=0.00000001,
                               color='black',
                               length_includes_head=True,
                               head_width=3))
def draw_infinite(state1=0, state2=1, text=0.1):
    radius = 0.5
    x1 = state1 * delta + radius
    diff_state = abs(state2 - state1)
    x2 = delta * diff_state - 2 * radius
    y = 0
    ellipse = Arc([x1 + x2 / 2, y],
                  x2,
                  almost_zero,
                  angle=0,
                  theta1=0,
                  theta2=180.0,
                  color='k',
                  linewidth='1',
                  ls='dotted')
    arrow2 = FancyArrow(x1 + x2 / 2 - 0.01,
                        0,
                        0.01,
                        0,
                        width=arrow_width,
                        length_includes_head=False,
                        head_width=None,
                        head_length=None,
                        shape='full',
                        overhang=0,
                        head_starts_at_zero=False,
                        color='k')
    plt.gca().add_patch(ellipse)
    plt.gca().add_patch(arrow2)

    y = 0
    ellipse = Arc([1, y],
                  x2,
                  almost_zero,
                  angle=0,
                  theta1=0,
                  theta2=180.0,
                  color='k',
                  linewidth='1',
                  ls='dotted')
    plt.gca().add_patch(ellipse)
    arrow2 = FancyArrow(1 - 0.01,
                        0,
                        0.01,
                        0,
                        width=arrow_width,
                        length_includes_head=False,
                        head_width=None,
                        head_length=None,
                        shape='full',
                        overhang=0,
                        head_starts_at_zero=False,
                        color='k')
    plt.gca().add_patch(arrow2)
Esempio n. 9
0
def directed_flow(coords, flow, color, area_factor=1, cmap=None):
    """
    Helper function to generate arrows from flow data.
    """
    # this funtion is used for diplaying arrows representing the network flow
    data = pd.DataFrame({
        'arrowsize':
        flow.abs().pipe(np.sqrt).clip(lower=1e-8),
        'direction':
        np.sign(flow),
        'linelength':
        (np.sqrt((coords.x1 - coords.x2)**2. + (coords.y1 - coords.y2)**2))
    })
    data = data.join(coords)
    if area_factor:
        data['arrowsize'] = data['arrowsize'].mul(area_factor)
    data['arrowtolarge'] = (1.5 * data.arrowsize > data.linelength)
    # swap coords for negativ directions
    data.loc[data.direction == -1., ['x1', 'x2', 'y1', 'y2']] = \
        data.loc[data.direction == -1., ['x2', 'x1', 'y2', 'y1']].values
    if ((data.linelength > 0.) & (~data.arrowtolarge)).any():
        data['arrows'] = (
            data[(data.linelength > 0.) & (~data.arrowtolarge)].apply(
                lambda ds: FancyArrow(ds.x1,
                                      ds.y1,
                                      0.6 *
                                      (ds.x2 - ds.x1) - ds.arrowsize * 0.75 *
                                      (ds.x2 - ds.x1) / ds.linelength,
                                      0.6 *
                                      (ds.y2 - ds.y1) - ds.arrowsize * 0.75 *
                                      (ds.y2 - ds.y1) / ds.linelength,
                                      head_width=ds.arrowsize),
                axis=1))
    data.loc[(data.linelength > 0.) & (data.arrowtolarge), 'arrows'] = \
        (data[(data.linelength > 0.) & (data.arrowtolarge)]
         .apply(lambda ds:
                FancyArrow(ds.x1, ds.y1,
                           0.001*(ds.x2 - ds.x1),
                           0.001*(ds.y2 - ds.y1),
                           head_width=ds.arrowsize), axis=1))
    data = data.dropna(subset=['arrows'])
    arrowcol = PatchCollection(data.arrows,
                               color=color,
                               edgecolors='k',
                               linewidths=0.,
                               zorder=4,
                               alpha=1)
    return arrowcol
Esempio n. 10
0
def draw_promoter(feature, x, y, width, height, figure, loc_index, style_dict):
    from matplotlib.patches import Rectangle
    from matplotlib.patches import Wedge
    from matplotlib.patches import FancyArrow
    from matplotlib.text import Text

    base_width = 4
    head_width = 8
    curve_radius = 10

    y_center = y + height/2
    y_curve_max = y + height - head_width/2 + base_width/2
    y_curve_min = y_curve_max - curve_radius
    y_tip = y + height - head_width/2

    vertical = Rectangle((x, y_center), base_width, y_curve_min-y_center,
                         color="black", linewidth=0)
    figure.patches.append(vertical)
    curve = Wedge(center=(x+curve_radius, y_curve_min), r=curve_radius,
                  theta1=90, theta2=180, width=base_width,
                  color="black", linewidth=0)
    figure.patches.append(curve)
    horizontal = FancyArrow(
        x+curve_radius, y_tip, dx=width-curve_radius, dy=0,
        width=base_width, head_width=head_width, head_length=head_width,
        length_includes_head=True, color="black", linewidth=0
    )
    figure.patches.append(horizontal)
    if "note" in feature.qual:
        text = Text(x + width/2, y + height/4, feature.qual["note"],
                    color="black", ha="center", va="center",
                    size=9, figure=figure)
        figure.texts.append(text)
Esempio n. 11
0
    def showOccl(self, occl, img):
        """
        Show occlusion data
        """
        img = self.getImgs(img)[0]

        fig, ax = plt.subplots(1)
        if img is not None and not self.waiting:
            self.showImg(img, wait=True, ax=ax)

        bounds = np.zeros(occl['imsize'])
        for i in range(occl['ne']):  # ne = "number of edges"

            pixel_indices = occl['edges']['indices'][i]
            num_pixels = len(pixel_indices)
            pixel_coords = np.unravel_index(pixel_indices,
                                            occl['imsize'],
                                            order='F')
            edgelabel = occl['edges']['edgelabel'][i]
            bounds[pixel_coords] = 1

            for j in range(num_pixels - OCCLUSION_ARROW_DISTANCE):
                if j % OCCLUSION_ARROW_DISTANCE == 0:
                    # draw arrow
                    a = [pixel_coords[0][j], pixel_coords[1][j]]
                    b = [
                        pixel_coords[0][j + OCCLUSION_ARROW_DISTANCE],
                        pixel_coords[1][j + OCCLUSION_ARROW_DISTANCE]
                    ]

                    # midpoint
                    mid = (np.array(a) + np.array(b)) / 2

                    d0 = b[0] - a[0]
                    d1 = b[1] - a[1]

                    # point towards b if edgelabel is 1,
                    # else (edgelabel is 2), point away
                    if edgelabel != 1:
                        d0 *= -1
                        d1 *= -1

                    # normalize direction vector
                    norm = np.sqrt(d0 * d0 + d1 * d1)
                    d0 /= norm
                    d1 /= norm

                    ax.add_patch(
                        FancyArrow(mid[1],
                                   mid[0],
                                   d0,
                                   -d1,
                                   width=0.0,
                                   head_width=2.5,
                                   head_length=5.0,
                                   facecolor='white',
                                   edgecolor='none'))

        # show mask
        self.showMask(bounds, img)
Esempio n. 12
0
def _draw_sheet(feature, x, y, width, height, figure, loc_index, style_dict):
    from matplotlib.patches import FancyArrow

    head_height = 0.8 * height
    tail_height = 0.5 * height
    head_width = 0.4 * height

    tail_x = x
    arrow_y = y + height / 2
    dx = width
    dy = 0
    if head_width > width:
        # If fteaure is to short, draw only narrowed head
        head_width = width
    loc = feature.locs[loc_index]
    if loc.defect & seq.Location.Defect.MISS_RIGHT:
        head_width = 0
        head_height = tail_height

    arrow = FancyArrow(tail_x,
                       arrow_y,
                       dx,
                       dy,
                       width=tail_height,
                       head_width=head_height,
                       head_length=head_width,
                       length_includes_head=True,
                       color=biotite.colors["orange"],
                       linewidth=0)
    figure.patches.append(arrow)
Esempio n. 13
0
def draw_edge(sheet, coords, ax, **draw_spec_kw):
    """
    """
    draw_spec = sheet_spec()["edge"]
    draw_spec.update(**draw_spec_kw)

    x, y = coords
    dx, dy = ("d" + c for c in coords)
    app_length = np.hypot(sheet.edge_df[dx], sheet.edge_df[dy])

    patches = []
    arrow_specs, collections_specs = parse_edge_specs(draw_spec, sheet)

    for idx, edge in sheet.edge_df[app_length > 1e-6].iterrows():
        srce = int(edge["srce"])
        arrow = FancyArrow(
            sheet.vert_df.loc[srce, x],
            sheet.vert_df.loc[srce, y],
            sheet.edge_df.loc[idx, dx],
            sheet.edge_df.loc[idx, dy],
            **arrow_specs,
        )
        patches.append(arrow)
    ax.add_collection(PatchCollection(patches, False, **collections_specs))
    return ax
def draw_self_transition(state=0, text='0.55'):
    x_pos = state * delta
    y_pos = 0.7
    height = 0.60
    width = 0.55
    ellipse = Arc([x_pos, y_pos],
                  width,
                  height,
                  angle=0,
                  theta1=-50,
                  theta2=230.0,
                  color='k',
                  linewidth='1')
    plt.gca().add_patch(ellipse)
    arrow2 = FancyArrow(x_pos - 0.01,
                        y_pos + height / 2,
                        0.01,
                        -0.002,
                        width=arrow_width,
                        length_includes_head=False,
                        head_width=None,
                        head_length=None,
                        shape='full',
                        overhang=0,
                        head_starts_at_zero=False,
                        color='k')
    plt.gca().add_patch(arrow2)
    plt.text(x_pos,
             y_pos + 1.1 * height / 2,
             text,
             fontsize=12,
             horizontalalignment='center',
             verticalalignment='bottom')
Esempio n. 15
0
def plot(src: PlanarTriangle,
         dst: PlanarTriangle,
         color="black") -> Tuple[plt.Figure, plt.Axes]:
    fig: plt.Figure
    ax: plt.Axes
    fig, ax = plt.subplots()
    ax.set_xlim([0.1, .9])
    ax.set_ylim([0.1, .8])
    ax.axis("square")

    ax.scatter(*(src.points.T), c="black")
    dst.plot(fig, ax, color=color)

    patches = PatchCollection([
        FancyArrow(*s,
                   *(d - s),
                   length_includes_head=True,
                   width=0.005,
                   head_width=0.025,
                   color="k") for s, d in zip(src.points, dst.points)
    ],
                              edgecolors="k",
                              facecolors="k")
    ax.add_collection(patches)

    plt.axis("off")
    return fig, ax
Esempio n. 16
0
    def render(self, ctx):
        """
        Render the edge in the given axes.

        :param ctx:
            The :class:`_rendering_context` object.

        """
        ax = ctx.ax()

        plot_params = self.plot_params
        plot_params["linewidth"] = _pop_multiple(plot_params, ctx.line_width, "lw", "linewidth")

        plot_params["linestyle"] = plot_params.get("linestyle", "-")

        # Add edge annotation.
        if self.label is not None:
            x, y, dx, dy = self._get_coords(ctx)
            ax.annotate(
                self.label,
                [x + 0.5 * dx + self.xoffset, y + 0.5 * dy + self.yoffset],
                xycoords="data",
                xytext=[0, 3],
                textcoords="offset points",
                ha="center",
                va="center",
                **self.label_params
            )

        if self.directed:
            plot_params["ec"] = _pop_multiple(plot_params, "k", "ec", "edgecolor")
            plot_params["fc"] = _pop_multiple(plot_params, "k", "fc", "facecolor")
            plot_params["head_length"] = plot_params.get("head_length", 0.25)
            plot_params["head_width"] = plot_params.get("head_width", 0.1)

            # Build an arrow.
            args = self._get_coords(ctx)

            # zero lengh arrow produce error
            if not (args[2] == 0.0 and args[3] == 0.0):
                ar = FancyArrow(
                    *self._get_coords(ctx), width=0, length_includes_head=True, **plot_params
                )

                # Add the arrow to the axes.
                ax.add_artist(ar)
                return ar

            else:
                print(args[2], args[3])

        else:
            plot_params["color"] = plot_params.get("color", "k")

            # Get the right coordinates.
            x, y, dx, dy = self._get_coords(ctx)

            # Plot the line.
            line = ax.plot([x, x + dx], [y, y + dy], **plot_params)
            return line
    def draw_token(cls, token, r, c, ax, height, width, token_scale=1.0):
        if token == EMPTY:
            return None

        if 'arrow' in token:
            edge_color = '#888888'
            face_color = '#AAAAAA'

            drawing = RegularPolygon((c + 0.5, (height - 1 - r) + 0.5),
                                     numVertices=4,
                                     radius=0.5 * np.sqrt(2),
                                     orientation=np.pi / 4,
                                     ec=edge_color,
                                     fc=face_color)
            ax.add_patch(drawing)

        if token == LEFT_ARROW:
            arrow_drawing = FancyArrow(c + 0.75,
                                       height - 1 - r + 0.5,
                                       -0.25,
                                       0.0,
                                       width=0.1,
                                       fc='green',
                                       head_length=0.2)
            ax.add_patch(arrow_drawing)

        elif token == RIGHT_ARROW:
            arrow_drawing = FancyArrow(c + 0.25,
                                       height - 1 - r + 0.5,
                                       0.25,
                                       0.0,
                                       width=0.1,
                                       fc='green',
                                       head_length=0.2)
            ax.add_patch(arrow_drawing)

        else:
            im = TOKEN_IMAGES[token]
            oi = OffsetImage(im,
                             zoom=cls.fig_scale *
                             (token_scale / max(height, width)**0.5))
            box = AnnotationBbox(oi, (c + 0.5, (height - 1 - r) + 0.5),
                                 frameon=False)

            ax.add_artist(box)

            return box
Esempio n. 18
0
    def draw(self, tail_coords, head_coords, node_radius, **kwargs):
        self.edge_width = process_width(self.edge_width, kwargs)
        self.head_width_to_edge_width = process_head_width_to_width(
            self.head_width_to_edge_width, kwargs)
        self.head_length_to_head_width = process_head_length_to_head_width(
            self.head_length_to_head_width, kwargs)
        self.overhang = process_overhang(self.overhang, kwargs)
        self.alpha = process_alpha(self.alpha, kwargs)
        self.face_color = process_face_color(self.face_color, kwargs)

        if self.angle == None:
            self.get_angle(tail_coords, head_coords)

        node_delta = Point(node_radius * cos(self._angle_radians),
                           node_radius * sin(self._angle_radians))

        if tail_coords.draw_bool:
            tail_delta = Point(node_delta.x, node_delta.y)
        else:
            tail_delta = Point()

        head_delta = Point(-1.0 * node_delta.x, -1.0 * node_delta.y)

        if self.directional:
            head_width = self.head_width_to_edge_width * self.edge_width
            head_length = self.head_length_to_head_width * head_width
            if not head_coords.draw_bool:
                head_delta = Point()

        else:
            head_width = 0.0
            head_length = 0.0
            if not head_coords.draw_bool:
                head_delta = Point(
                    0.5 * self.edge_width * cos(self._angle_radians),
                    0.5 * self.edge_width * sin(self._angle_radians))

        tail_coords = tail_coords + tail_delta
        head_coords = head_coords + head_delta

        delta = head_coords - tail_coords

        if self.draw_bool:
            patch = FancyArrow(tail_coords.x,
                               tail_coords.y,
                               delta.x,
                               delta.y,
                               width=self.edge_width,
                               length_includes_head=True,
                               head_width=head_width,
                               head_length=head_length,
                               shape='full',
                               overhang=self.overhang,
                               head_starts_at_zero=False,
                               fc=self.face_color,
                               alpha=self.alpha)
            return patch
        else:
            return None
Esempio n. 19
0
def draw_orientation(ax, centers, sizes, angles, colors, mode):

    if mode == 'front':
        length = 5
        fill = False
        alpha = 0.6
        zorder_circle = 0.5
        zorder_arrow = 5
        linewidth = 1.5
        edgecolor = 'k'
        radiuses = [s / 1.2 for s in sizes]
    else:
        length = 1.3
        head_width = 0.3
        linewidth = 2
        radiuses = [0.2] * len(centers)
        fill = True
        alpha = 1
        zorder_circle = 2
        zorder_arrow = 1

    for idx, theta in enumerate(angles):
        color = colors[idx]
        radius = radiuses[idx]

        if mode == 'front':
            x_arr = centers[idx][0] + (length + radius) * math.cos(theta)
            z_arr = length + centers[idx][1] + (length +
                                                radius) * math.sin(theta)
            delta_x = math.cos(theta)
            delta_z = math.sin(theta)
            head_width = max(10, radiuses[idx] / 1.5)

        else:
            edgecolor = color
            x_arr = centers[idx][0]
            z_arr = centers[idx][1]
            delta_x = length * math.cos(theta)
            delta_z = -length * math.sin(
                theta)  # keep into account kitti convention

        circle = Circle(centers[idx],
                        radius=radius,
                        color=color,
                        fill=fill,
                        alpha=alpha,
                        zorder=zorder_circle)
        arrow = FancyArrow(x_arr,
                           z_arr,
                           delta_x,
                           delta_z,
                           head_width=head_width,
                           edgecolor=edgecolor,
                           facecolor=color,
                           linewidth=linewidth,
                           zorder=zorder_arrow)
        ax.add_patch(circle)
        ax.add_patch(arrow)
Esempio n. 20
0
def plot(mag, bearingDeg, fname):
    """Make a single wind direction image."""
    print(f"plotting {mag} {bearingDeg}")
    fig, ax = plt.subplots(figsize=(6, 6))
    for rad in [0.33, 0.66, 1.0]:
        circle = Circle((0, 0),
                        rad,
                        fill=False,
                        ec="black",
                        color="b",
                        alpha=0.1)
        ax.add_patch(circle)

    # Add lines
    for angleI in range(NUM_DIRS):
        theta = angleI * 2 * math.pi / NUM_DIRS
        x = math.cos(theta)
        y = math.sin(theta)
        plt.plot(
            (0, x),
            (0, y),
            color="k",
            alpha=0.1,
        )

    # arrow
    theta = bearingDeg * math.pi / 180.0
    # rotate 90° to have north be up.
    y = math.cos(theta)
    x = math.sin(theta)
    color = colormap(mag)
    # Wind directions are always reported by the bearing of the wind (i.e. where it's
    # coming from)
    # Make a length-2 arrow pointing toward where the wind is coming from.
    # Make bigger and different colors if the wind is extra windy.
    # Tail is specified reflected through the origin
    arrow = FancyArrow(
        -x,
        -y,
        2 * x,
        2 * y,
        color=color,
        width=0.05 + 0.20 * mag,
        length_includes_head=True,
        head_length=2.0,
        ec="black",
        alpha=1.00,
        zorder=100,
    )
    ax.add_patch(arrow)

    plt.axis("equal")
    plt.axis("off")
    # plt.tight_layout()
    plt.margins(0)
    plt.savefig(fname)
    plt.close()
Esempio n. 21
0
    def __init__(self, ax, flowcollection, frange=2, normalized=True, scale_arrows=True, **kwargs):
        self.ax = ax
        self.flowcollection = flowcollection
        self.normalized = normalized
        self.frange = frange
        self.scale_arrows = scale_arrows
        self.MaxFlow = flowcollection.getMaxFlow()
        self.MinFlow = flowcollection.getMinFlow()

        if frange == 'all':
            if normalized:
                self.norm = kwargs.pop('norm', LogNorm(self.MinFlow/self.MaxFlow, 1, clip=True))
            else:
                self.norm = kwargs.pop('norm', LogNorm(self.MinFlow, self.MaxFlow, clip=True))
        else:
            if normalized:
                self.norm = kwargs.pop('norm', LogNorm(10**(-frange), 1, clip=True))
            else:
                self.norm = kwargs.pop('norm', LogNorm(self.MaxFlow*10**(-frange), self.MaxFlow, clip=True))
        self.cmap = cm.get_cmap(kwargs.pop('cmap', 'jet'))

        self.ax.axis(self.flowcollection.getBounds())
        kwargs.setdefault('lw', .3)

        Arrows = []
        Acol = []
        if normalized:
            flows = np.vectorize(lambda f: f.flow / self.MaxFlow)(self.flowcollection.flows)
        else:
            flows = np.vectorize(lambda f: f.flow)(self.flowcollection.flows)

        for fl, flow in zip(flows, self.flowcollection.flows):
            if frange != 'all' and self.norm(fl) <= 0:
                continue

            if scale_arrows:
                width = .2*self.norm(fl) + 0.01
            else:
                width = .15
            st = {"ec": 'k',
                  "width": width,
                  "head_width": 2.5*width,
                  "head_length": .5}
            nkwargs = kwargs.copy()
            for kv in st.items():
                nkwargs.setdefault(*kv)

            ar = FancyArrow(flow.N0, flow.Z0, flow.dN, flow.dZ,
                            length_includes_head=True,
                            **nkwargs)
            Arrows.append(ar)
            Acol.append(fl)
        Arrows = np.array(Arrows)
        Acol = np.array(Acol)
        self.Patches = PatchCollection(Arrows, norm=self.norm, cmap=self.cmap, match_original=True)
        self.Patches.set_array(Acol)
        self.ax.add_collection(self.Patches, )
 def addArrow(self, x, y, dx, dy, nh_value):
     arr = FancyArrow(x=x, y=y, dx=dx, dy=dy,
                      edgecolor='y',
                      facecolor='y',
                      length_includes_head=True,
                      linewidth=0.2,
                      head_width=0.05,
                      head_length=0.05)
     self.axes.add_patch(arr)
Esempio n. 23
0
def animate(i):
    l.set_data(xs[i], ys[i])
    ax.patches.pop()
    arrow = FancyArrow(xs[i],
                       ys[i],
                       orientation[i][0],
                       orientation[i][1],
                       color='r')
    patch = ax.add_patch(arrow)
    def show(self):
        """Show network plot."""
        ax = plt.axes(xlim=(0, max(self.i, self.h, self.o) * 25 + 100),
                      ylim=(0, 200))
        line, = ax.plot([], [])
        ax.set_aspect('equal')
        ax.figure.set_size_inches(5, 2)

        nodes = []

        x = 25
        y = 50
        for t in range(self.i):
            ax.add_patch(Circle((x, y), 10, color='green'))
            nodes.append((t, x, y))
            x += 25

        y += 50
        x = max(self.i, self.h, self.o) * 25 + 25
        for t in range(self.h):
            ax.add_patch(Circle((x, y), 10, color='purple'))
            nodes.append((t + self.i, x, y))
            x += 25

        y += 50
        x = (max(self.i, self.h, self.o) - self.o) / 2 * 25 + 25
        for t in range(self.o):
            ax.add_patch(Circle((x, y), 10, color='blue'))
            nodes.append((t + self.i + self.h, x, y))
            x += 25

        for i in nodes:
            for c in self.connections.keys():
                if self.connections[c]['input'] == i[0]:
                    out = self.connections[c]['output']
                    j = nodes[out]

                    color = 'black'
                    if self.connections[c]['weight'] < 0:
                        color = 'blue'
                    elif self.connections[c]['weight'] > 0:
                        color = 'red'
                    ax.add_patch(
                        FancyArrow(i[1],
                                   i[2],
                                   j[1] - i[1],
                                   j[2] - i[2],
                                   width=0.001,
                                   color=color,
                                   length_includes_head=True,
                                   head_width=5))

        ax.set_aspect('equal')
        ax.figure.set_size_inches(6, 6)
Esempio n. 25
0
 def _draw_loop(self, gv, loop, size, imsize):
     coords = [gv.get_node(n).attr['pos'].split(',') for n in loop['nodes']]
     x = np.mean([float(c[0]) for c in coords])
     y = np.mean([float(c[1]) for c in coords])
     x = x * imsize[0] / size[0]
     y = imsize[1] - y * imsize[1] / size[1]
     head = FancyArrow(x + 15, y, 0, -1, head_width=10, color="k")
     arrow = Arc((x, y), 30, 30, theta1=0, theta2=270)
     plt.gca().add_patch(arrow)
     plt.gca().add_patch(head)
     plt.text(x - 5, y + 4, loop['type'], fontsize=8)
Esempio n. 26
0
def plot_arrow(fig: plt.Figure, ax: plt.Axes, R: PlanarTriangle, P: Triangle,
               i: int, scale: bool):
    triv = get_triv(R, P, i)
    length = triv.points[2] - R.points[i]
    if scale:
        length *= P.sides[(i + 1) % 3]
    arrow = FancyArrow(*R.points[i],
                       *length,
                       length_includes_head=True,
                       head_width=0.035,
                       color="black")
    ax.add_patch(arrow)
Esempio n. 27
0
def reddening_vector_patch(R, mag2_lim=(19, 20), color_start=0.4, **kwargs):
    xs = np.linspace(color_start, 10, 10000)
    ys = xs * R + mag2_lim[0] - xs[0] * R
    plt_inds = np.nonzero(ys < mag2_lim[1])[0]

    x = xs[plt_inds][0]
    y = ys[plt_inds][0]
    dx = xs[plt_inds][-1] - x
    dy = ys[plt_inds][-1] - y
    from matplotlib.patches import FancyArrow
    arr = FancyArrow(x, y, dx, dy, **kwargs)
    return arr
Esempio n. 28
0
def draw_lattice(basis, showfig=False):
    fig, ax = plt.subplots(figsize=(3, 3))
    ax.spines['top'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')

    ax.set_aspect(1)
    plotrange = 2
    ax.set_xlim(-plotrange - 0.2, plotrange + 0.2)
    ax.set_ylim(-plotrange - 0.2, plotrange + 0.2)
    ax.tick_params(labelleft=False, labelbottom=False, labelsize=12)
    ax.set_xticks(np.arange(-plotrange, plotrange + 1, dtype=int))
    ax.set_yticks(np.arange(-plotrange, plotrange + 1, dtype=int))

    points = []
    n = 4
    for i, j in product(np.arange(-n, n + 1, dtype=int), repeat=2):
        points.append(i * basis[0] + j * basis[1])
    points = np.asarray(points)
    print(points.shape)
    ax.scatter(points[:, 0], points[:, 1], color='black', s=15)

    arrow_kw = {
        'head_width': 0.15,
        'head_length': 0.2,
        'width': 0.03,
        'length_includes_head': True
    }
    b1 = FancyArrow(0, 0, *basis[0], **arrow_kw, color='red', zorder=3)
    b2 = FancyArrow(0, 0, *basis[1], **arrow_kw, color='red', zorder=3)
    ax.add_artist(b1)
    ax.add_artist(b2)

    fig.tight_layout()
    if showfig:
        plt.show()
    return fig
Esempio n. 29
0
    def render(self, ctx):
        """
        Render the edge in the given axes.

        :param ctx:
            The :class:`_rendering_context` object.

        """
        ax = ctx.ax()

        p = self.plot_params
        p["linewidth"] = _pop_multiple(p, ctx.line_width, "lw", "linewidth")

        # Add edge annotation.
        if "label" in self.plot_params:
            x, y, dx, dy = self._get_coords(ctx)
            ax.annotate(
                self.plot_params["label"],
                [x + 0.5 * dx + self.xoffset, y + 0.5 * dy + self.yoffset],
                xycoords="data",
                xytext=[0, 3],
                textcoords="offset points",
                ha="center",
                va="center")

        if self.directed:
            p["ec"] = _pop_multiple(p, "k", "ec", "edgecolor")
            p["fc"] = _pop_multiple(p, "k", "fc", "facecolor")
            p["head_length"] = p.get("head_length", 0.25)
            p["head_width"] = p.get("head_width", 0.1)

            # Build an arrow.
            ar = FancyArrow(*self._get_coords(ctx),
                            width=0,
                            length_includes_head=True,
                            **p)

            # Add the arrow to the axes.
            ax.add_artist(ar)
            return ar
        else:
            p["color"] = p.get("color", "k")

            # Get the right coordinates.
            x, y, dx, dy = self._get_coords(ctx)

            # Plot the line.
            line = ax.plot([x, x + dx], [y, y + dy], **p)
            return line
Esempio n. 30
0
 def _draw_region_movements(self,
                            visualizer,
                            image_rgb,
                            region,
                            movements,
                            event_count=None,
                            arrow_size=20):
     ax = visualizer.output.ax
     x0, y0 = region.min(axis=0).astype(int)
     x1, y1 = region.max(axis=0).astype(int)
     roi = image_rgb[y0:y1, x0:x1]
     color = self.color_manager.get_color('region', roi)
     roi = Polygon(region,
                   fill=False,
                   color=color,
                   linewidth=self._linewidth(visualizer))
     ax.add_patch(roi)
     colors = {}
     movements = sorted(movements.items(), key=lambda x: int(x[0]))
     if event_count is not None:
         event_count = event_count.astype(str)
     for label, movement in movements:
         x0, y0 = movement.min(axis=0).astype(int)
         x1, y1 = movement.max(axis=0).astype(int)
         roi = image_rgb[y0:y1, x0:x1]
         color = self.color_manager.get_color(('movement', label), roi)
         colors[label] = color
         if event_count is not None:
             label = '%s: %s' % (label, ', '.join(event_count[label - 1]))
         line = Polygon(movement,
                        closed=False,
                        fill=False,
                        edgecolor=color,
                        label=label,
                        linewidth=self._linewidth(visualizer))
         ax.add_patch(line)
         dxy = movement[-1] - movement[-2]
         dxy = dxy / np.linalg.norm(dxy) * arrow_size
         origin = movement[-1] - dxy
         arrow = FancyArrow(*origin,
                            *dxy,
                            edgecolor=color,
                            facecolor=color,
                            width=2 * self._linewidth(visualizer),
                            head_length=arrow_size,
                            head_width=arrow_size)
         ax.add_patch(arrow)
     ax.legend(loc=0)
     return colors
Esempio n. 31
0
def add_state_space_arrows(ax: matplotlib.axes.Axes):
    """Add arrows representing the axes to the plot.

    These arrows are used to indicate the axes variables
    without plotting a full axis, to give a less busy
    visualisation.
    """

    # Add arrows to represent axis labels
    xarrow = FancyArrow(-1.31,
                        -1.3,
                        0.3,
                        0,
                        width=0.02,
                        edgecolor='k',
                        facecolor='k')
    ax.text(-0.8,
            -1.3,
            r'$p$',
            fontsize='xx-large',
            verticalalignment='center')
    ax.add_patch(xarrow)

    yarrow = FancyArrow(-1.3,
                        -1.31,
                        0,
                        0.3,
                        width=0.02,
                        edgecolor='k',
                        facecolor='k')
    ax.text(-1.3,
            -0.8,
            r'$\dot{p}$',
            fontsize='xx-large',
            horizontalalignment='center')
    ax.add_patch(yarrow)