Beispiel #1
0
def show_class_name_plt(pos, class_str, ax, bg_color='red', font_size=8):
    """
    Visualizes the class names using matplotlib on a given ax
    """

    x0, y0 = int(pos[0]), int(pos[1])
    # y_lim = ax.get_ylim()[0]
    # x_lim = ax.get_xlim()[1]

    boxstyle = BoxStyle("Round")
    props = {'boxstyle': boxstyle, 'facecolor': bg_color, 'alpha': 0.5}
    t = ax.text(abs(x0 + 2),
                abs(y0 - 8),
                class_str,
                fontsize=font_size,
                bbox=props)
    x_t = abs(x0 + 2)
    y_t = abs(y0 - 8)

    # r = ax.get_figure().canvas.get_renderer()
    # bb = t.get_window_extent(renderer=r)
    # x_t = min(abs(x0+2), x_lim-bb.width)
    # y_t = min(abs(y0-8), y_lim-bb.height)

    t = ax.text(x_t,
                y_t,
                class_str,
                fontsize=font_size,
                bbox=dict(facecolor=bg_color, boxstyle='round', alpha=0.5))
Beispiel #2
0
def draw_compartments(compartments, fig, sf):
    """Create a list of FancyBbox Patches, one for each compartment.

    Args:
        compartments (iterable collection of Compartment): collection of
        compartments

    Returns: list of matplotlib.patches.FancyBboxPatch
    """
    compartment_patches = []

    for compartment in compartments:

        fbbp = FancyBboxPatch(
            #            compartment.lower_left_point,
            [
                sf * compartment.lower_left_point[0] / 72 + WIDTH_SHIFT,
                sf * compartment.lower_left_point[1] / 72 + HEIGHT_SHIFT
            ],
            sf * compartment.width / 72,
            sf * compartment.height / 72,
            edgecolor=compartment.edge_color,
            facecolor=compartment.fill_color,
            linewidth=compartment.line_width,
            boxstyle=BoxStyle("round", pad=0, rounding_size=.6),
            #            mutation_scale=10,
            transform=fig.dpi_scale_trans)

        compartment_patches.append(fbbp)

    return compartment_patches
Beispiel #3
0
def get_node_patch(node_center_x, node_center_y):

    width = get_length(12 * 5)
    height = get_length(12 * 1)

    node_patch = FancyBboxPatch(
        [node_center_x - width / 2, node_center_y - height / 2],
        width,
        height,
        edgecolor="blue",
        facecolor="lightblue",
        linewidth=1,
        boxstyle=BoxStyle("round", pad=0.4, rounding_size=.8),
        mutation_scale=10)

    return node_patch
Beispiel #4
0
def draw_nodes(nodes, node_padding, node_mutation_scale, fig, sf):
    """Create a list of FancyBbox Patches, one for each node.

    Args:
        nodes (iterable collection of _Node): collection of nodes

    Returns: list of matplotlib.patches.FancyBboxPatch
    """

    node_patches = []

    print("WIDTH_SHIFT, HEIGHT_SHIFT: ", WIDTH_SHIFT, HEIGHT_SHIFT)

    for node in nodes:

        #        width = len(node.name)*node.font_size/72
        #        height = node.font_size/72
        #        node_center_x = node.center.x/72 + .5
        #        node_center_y = node.center.y/72 + .5
        #        lower_left_point_x = node_center_x - node.width/2
        #        lower_left_point_y = node_center_y - node.height/2

        fbbp = FancyBboxPatch(
            #            node.lower_left_point,
            #            node.width,
            #            node.height,
            [
                sf * node.lower_left_point[0] / 72 + WIDTH_SHIFT,
                sf * node.lower_left_point[1] / 72 + HEIGHT_SHIFT
            ],
            sf * node.width / 72,
            sf * node.height / 72,
            edgecolor=node.edge_color,
            facecolor=node.fill_color,
            linewidth=node.edge_width,
            boxstyle=BoxStyle(
                "round",
                pad=0,
                #                              pad=node_padding if node_padding else 0.1,
                rounding_size=.1),
            #            mutation_scale=node_mutation_scale if node_mutation_scale else 1,
            transform=fig.dpi_scale_trans)

        node_patches.append(fbbp)

    return node_patches
    def draw_graph(
        self
    ):  # note that when there's no edges, drawing might look a little off
        fig, ax = plt.subplots()
        coords = {}

        # set coordinates coords = [[x, y]]
        for r in range(self.dimensions[0]):
            for c in range(self.dimensions[1]):
                coords[str(r) + ', ' + str(c)] = [1 * c, -1 * r]

        # draw edges
        for r in range(self.dimensions[0]):
            for c in range(self.dimensions[1]):
                coordinate = str(r) + ', ' + str(c)
                if self.edges.get(coordinate):
                    for e in self.edges[coordinate]:
                        src = coords[coordinate]
                        dest = coords[str(e[0][0]) + ', ' + str(e[0][1])]
                        ax.plot([src[0], dest[0]], [src[1], dest[1]],
                                linewidth=1,
                                color="k")

        # draw nodes
        for coord in coords:
            ax.text(coords[coord][0],
                    coords[coord][1],
                    coord,
                    size=50 // (max(self.dimensions)),
                    ha="center",
                    va="center",
                    bbox=dict(facecolor='w',
                              boxstyle=BoxStyle("Round", pad=.4)))

        ax.set_aspect(1.0)
        ax.axis('off')
Beispiel #6
0
def test_boxstyle_errors(fmt, match):
    with pytest.raises(ValueError, match=match):
        BoxStyle(fmt)
Beispiel #7
0
def vis_img(img,
            *label_datas,
            class_names=[],
            conf_threshold=0.5,
            show_conf=True,
            nms_mode=0,
            nms_threshold=0.5,
            nms_sigma=0.5,
            version=1,
            figsize=None,
            dpi=None,
            axis="off",
            savefig_path=None,
            connection=None,
            fig_ax=None,
            point_radius=5,
            point_color="r",
            box_linewidth=2,
            box_color="auto",
            text_color="w",
            text_padcolor="auto",
            text_fontsize=12):
    """Visualize the images and annotaions by pyplot.

    Args:
        img: A ndarray of shape(img_heights, img_widths, channels).
        *label_datas: Ndarrays,
            shape: (grid_heights, grid_widths, info).
            Multiple label data can be given at once.
        class_names: A list of string,
            containing all label names.
        conf_threshold: A float,
            threshold for quantizing output.
        show_conf: A boolean, whether to show confidence score.
        nms_mode: An integer,
            0: Not use NMS.
            1: Use NMS.
            2: Use Soft-NMS.
        nms_threshold: A float,
            threshold for eliminating duplicate boxes.
        nms_sigma: A float,
            sigma for Soft-NMS.
        version: An integer,
            specifying the decode method, yolov1、v2 or v3.
        figsize: (float, float), optional, default: None
            width, height in inches. If not provided, defaults to [6.4, 4.8].
        dpi: float, default: rcParams["figure.dpi"] (default: 100.0)
            The resolution of the figure in dots-per-inch.
            Set as 1.325, then 1 inch will be 1 dot. 
        axis: bool or str
            If a bool, turns axis lines and labels on or off.
            If a string, possible values are:
            https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.axis.html
        savefig_path: None or string or PathLike or file-like object
            A path, or a Python file-like object.
        connection: A string,
            one of "head"、"tail",
            connect visualization of ground truth and prediction.
        fig_ax: (matplotlib.pyplot.figure, matplotlib.pyplot.axes),
            This argument only works
            when the connection is specified as "tail".
        point_radius: 5.
        point_color: A string or list, defalut: "r".
        box_linewidth: 2.
        box_color: A string or list, defalut: "auto".
        text_color: A string or list, defalut: "w".
        text_padcolor: A string or list, defalut: "auto".
        text_fontsize: 12.
    """
    class_num = len(class_names)

    if isinstance(point_color, str):
        point_color = [point_color] * class_num
    if box_color == "auto":
        box_color = point_color
    if text_padcolor == "auto":
        text_padcolor = point_color
    if isinstance(box_color, str):
        box_color = [box_color] * class_num
    if isinstance(text_color, str):
        text_color = [text_color] * class_num
    if isinstance(text_padcolor, str):
        text_padcolor = [text_padcolor] * class_num

    nimg = np.copy(img)

    xywhcp = decode(*label_datas,
                    class_num=class_num,
                    threshold=conf_threshold,
                    version=version)
    if nms_mode > 0 and len(xywhcp) > 0:
        if nms_mode == 1:
            xywhcp = nms(xywhcp, nms_threshold)
        elif nms_mode == 2:
            xywhcp = soft_nms(xywhcp, nms_threshold, conf_threshold, nms_sigma)

    xywhc = xywhcp[..., :5]
    prob = xywhcp[..., -class_num:]

    if connection == "tail":
        fig, ax = fig_ax
    else:
        fig, ax = plt.subplots(1, figsize=figsize, dpi=dpi)
        ax.imshow(img)
        ax.axis(axis)

    for i in range(len(xywhc)):
        x = xywhc[i][0] * nimg.shape[1]
        y = xywhc[i][1] * nimg.shape[0]

        w = xywhc[i][2] * nimg.shape[1]
        h = xywhc[i][3] * nimg.shape[0]

        label_id = prob[i].argmax()
        label = class_names[label_id]

        point_min = int(x - w / 2), int(y - h / 2)
        # point_max = int(x + w/2), int(y + h/2)

        cir = Circle((x, y), radius=point_radius, color=point_color[label_id])

        rect = Rectangle(point_min,
                         w,
                         h,
                         linewidth=box_linewidth,
                         edgecolor=box_color[label_id],
                         facecolor="none")
        if show_conf:
            conf = xywhc[i][4] * prob[i][label_id]
            text = "%s:%.2f" % (label, conf)
        else:
            text = label
        if text_fontsize > 0:
            ax.text(
                *point_min,
                text,
                color=text_color[label_id],
                bbox=dict(boxstyle=BoxStyle.Square(pad=0.2),
                          color=text_padcolor[label_id]),
                fontsize=text_fontsize,
            )

        ax.add_patch(cir)
        ax.add_patch(rect)
    if savefig_path is not None:
        fig.savefig(savefig_path, bbox_inches='tight', pad_inches=0)

    if connection == "head":
        return fig, ax
    else:
        plt.show()
                      path=cubic_bezier_curve_path,
                      transform=fig.dpi_scale_trans)

# Create the node boxes

node_patch_ABCDEFG = FancyBboxPatch([
    lower_left_corner_ABCDEFG[0] + WIDTH_SHIFT,
    lower_left_corner_ABCDEFG[1] + HEIGHT_SHIFT
],
                                    node_width_ABCDEFG,
                                    node_height_ABCDEFG,
                                    edgecolor="blue",
                                    facecolor="lightblue",
                                    linewidth=1,
                                    boxstyle=BoxStyle("round",
                                                      pad=0,
                                                      rounding_size=.1),
                                    transform=fig.dpi_scale_trans)

node_patch_C = FancyBboxPatch([
    lower_left_corner_C[0] + WIDTH_SHIFT, lower_left_corner_C[1] + HEIGHT_SHIFT
],
                              node_width_C,
                              node_height_C,
                              edgecolor="blue",
                              facecolor="lightblue",
                              linewidth=1,
                              boxstyle=BoxStyle("round",
                                                pad=0,
                                                rounding_size=.1),
                              transform=fig.dpi_scale_trans)
vc2 = np.array(control_point_2)
ve = np.array(end_point)

cubic_bezier_curve_path = Path(
    [vs, vc1, vc2, ve], [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])

fap = FancyArrowPatch(path=cubic_bezier_curve_path,
                      arrowstyle="-|>",
                      clip_on=False,
                      linewidth=3,
                      color="red",
                      mutation_scale=100)

ax.add_patch(fap)

lower_left_point = [1.6, .2]
width = 0.2
height = 0.2

fbbp = FancyBboxPatch(lower_left_point,
                      width,
                      height,
                      boxstyle=BoxStyle("Round", pad=0.02))

ax.add_patch(fbbp)

plt.axis("off")
plt.axis("tight")

plt.show()
Beispiel #10
0
def draw_nodes(nodes, fig, scaling_factor, nw_height_inches):
    """Create a list of FancyBbox Patches, one for each node.

    Args:
        nodes (iterable collection of _Node): collection of nodes
        fig (matplotlib.figure.Figure): the figure of the network
        scaling_factor (float): scaling_factor to decrease or increase the
            figure size
        nw_height_inches (float): height of the network in inches

    Returns: list of matplotlib.patches - FancyBboxPatch, Ellipse, or Polygon
    """

    node_patches = []

    for node in nodes:

        if node.shape == "round_box":
            print(node.lower_left_point)
            print(node.lower_left_point[0] * INCHES_PER_POINT + WIDTH_SHIFT,
                  node.lower_left_point[1] * INCHES_PER_POINT + HEIGHT_SHIFT)

            node_patch = FancyBboxPatch(
                xy=(scaling_factor * node.lower_left_point[0] *
                    INCHES_PER_POINT + WIDTH_SHIFT, scaling_factor *
                    (nw_height_inches - node.lower_left_point[1] *
                     INCHES_PER_POINT - node.height * INCHES_PER_POINT) +
                    HEIGHT_SHIFT),
                width=scaling_factor * node.width * INCHES_PER_POINT,
                height=scaling_factor * node.height * INCHES_PER_POINT,
                edgecolor=node.edge_color,
                facecolor=node.fill_color,
                linewidth=node.edge_width,
                boxstyle=BoxStyle("round",
                                  pad=0,
                                  rounding_size=node.rectangle_rounding),
                transform=fig.dpi_scale_trans)

        elif node.shape == "ellipse":

            node_patch = Ellipse(
                (scaling_factor * node.center.x * INCHES_PER_POINT +
                 WIDTH_SHIFT, scaling_factor *
                 (nw_height_inches - node.center.y * INCHES_PER_POINT) +
                 HEIGHT_SHIFT),
                scaling_factor * node.width * INCHES_PER_POINT,
                scaling_factor * node.height * INCHES_PER_POINT,
                edgecolor=node.edge_color,
                facecolor=node.fill_color,
                linewidth=node.edge_width,
                transform=fig.dpi_scale_trans)

        elif node.shape == "polygon":

            node_points = _adjust_x_and_y_values(node.polygon_points,
                                                 scaling_factor,
                                                 nw_height_inches, node)

            node_points = np.array(node_points)

            # need to adjust the y's
            path = Path(node_points, node.polygon_codes)

            node_patch = PathPatch(path,
                                   facecolor=node.fill_color,
                                   edgecolor=node.edge_color,
                                   linewidth=node.edge_width,
                                   transform=fig.dpi_scale_trans)
        else:
            pass

        node_patches.append(node_patch)

    return node_patches
Beispiel #11
0
def draw_compartments(compartments, fig, scaling_factor, nw_height_inches):
    """Create a list of FancyBbox Patches, one for each compartment.

    Args:
        compartments (iterable collection of Compartment): collection of
            compartments
        fig (matplotlib.figure.Figure): the figure of the network
        scaling_factor (float): scaling_factor to decrease or increase the
            figure size
        nw_height_inches (float): height of the network in inches

    Returns: list of matplotlib.patches - FancyBboxPatch, Ellipse, or Polygon
    """
    compartment_patch = None
    compartment_patches = []

    for compartment in compartments:

        if compartment.shape == "round_box":
            # todo change the following to reduce padding around species boxes
            compartment_patch = FancyBboxPatch(
                xy=(scaling_factor * compartment.lower_left_point[0] *
                    INCHES_PER_POINT + WIDTH_SHIFT, scaling_factor *
                    (nw_height_inches - compartment.lower_left_point[1] *
                     INCHES_PER_POINT - compartment.height * INCHES_PER_POINT)
                    + HEIGHT_SHIFT),
                width=scaling_factor * compartment.width * INCHES_PER_POINT,
                height=scaling_factor * compartment.height * INCHES_PER_POINT,
                edgecolor=compartment.edge_color,
                facecolor=compartment.fill_color,
                linewidth=compartment.line_width,
                boxstyle=BoxStyle("round", pad=0, rounding_size=0.6),
                transform=fig.dpi_scale_trans)

        elif compartment.shape == "ellipse":

            compartment_patch = Ellipse(
                (scaling_factor * compartment.center_x * INCHES_PER_POINT +
                 WIDTH_SHIFT, scaling_factor *
                 (nw_height_inches - compartment.center_y * INCHES_PER_POINT) +
                 HEIGHT_SHIFT),
                scaling_factor * compartment.width * INCHES_PER_POINT,
                scaling_factor * compartment.height * INCHES_PER_POINT,
                edgecolor=compartment.edge_color,
                facecolor=compartment.fill_color,
                linewidth=compartment.line_width,
                transform=fig.dpi_scale_trans)

        elif compartment.shape == "polygon":

            compartment_points = _adjust_x_and_y_values(
                compartment.polygon_points, scaling_factor, nw_height_inches,
                compartment)

            compartment_points = np.array(compartment_points)

            # need to adjust the y's
            path = Path(compartment_points, compartment.polygon_codes)

            compartment_patch = PathPatch(path,
                                          facecolor=compartment.fill_color,
                                          edgecolor=compartment.edge_color,
                                          linewidth=compartment.line_width,
                                          transform=fig.dpi_scale_trans)
        if compartment_patch is None:
            raise ValueError
        compartment_patches.append(compartment_patch)

    return compartment_patches
Beispiel #12
0
def main():

    errs = []
    fontsize = 12
    linewidth = 2
    offset = 2.5

    for i in range(3):
        dir = dirs[i]
        err_file = os.path.join(dir, 'all_l2.npy')
        errs.append(np.mean(np.load(err_file), 1))

    xvals = np.arange(1, errs[0].shape[0] + 1)

    idx = np.arange(xvals.shape[0])[15:]

    fig, ax = plt.subplots()
    fig.set_size_inches(5, 4)

    line0, = plt.plot(xvals[idx],
                      errs[0][idx],
                      label='Our Method',
                      linewidth=linewidth,
                      color=[0, 0, 1])
    line1, = plt.plot(xvals[idx],
                      errs[1][idx],
                      label='I/O Baseline',
                      linewidth=linewidth,
                      color=[1, 0, 0])
    line2, = plt.plot(xvals[idx],
                      errs[2][idx],
                      label='Naive Baseline',
                      linewidth=linewidth,
                      color=[0, 0, 0])

    #plt.plot(xvals[19:64], errs[0][19:64], color=line0.get_color(), path_effects=[path_effects.SimpleLineShadow(offset=(0, -offset))], linewidth=linewidth)
    #plt.plot(xvals[19:64], errs[1][19:64], color=line1.get_color(), path_effects=[path_effects.SimpleLineShadow(offset=(0, -offset))], linewidth=linewidth)
    #plt.plot(xvals[19:64], errs[2][19:64], color=line2.get_color(), path_effects=[path_effects.SimpleLineShadow(offset=(0, -offset))], linewidth=linewidth)

    plt.axvspan(20, 64, facecolor=[0, 0, 0], alpha=0.15)
    plt.text(31.5,
             0.012,
             'Training',
             fontsize=fontsize,
             bbox=dict(facecolor='white',
                       alpha=1,
                       edgecolor='k',
                       linewidth=linewidth,
                       boxstyle=BoxStyle("Round", pad=1)))

    #plt.ylim(0, 0.0139)

    plt.xlabel('Inference Step Size', fontsize=fontsize)
    plt.ylabel('L2 error', fontsize=fontsize)

    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_fontsize(fontsize)

    plt.legend(fontsize=fontsize)
    plt.tight_layout()
    plt.savefig('result_figs/boids_metric_%s.png' % name)
Beispiel #13
0
    from figpptx.comparer import Comparer

    styles = [
        "circle",
        "square",
        "round",
        "larrow",
        "rarrow",
        "darrow",
    ]
    # fig = plt.figure()

    fig, ax = plt.subplots()
    for i, style in enumerate(styles):
        ys = 1 / (len(styles)) * (i)
        height = 1 / (2 * len(styles))
        boxstyle = BoxStyle(style, pad=0.01)
        p_bbox = FancyBboxPatch(
            (0.2, ys),
            0.3,
            height,
            boxstyle=boxstyle,
            ec="black",
            fc=f"C{i}",
        )
        ax.add_patch(p_bbox)

    fig.tight_layout()
    comparer = Comparer()
    comparer.compare(fig)
Beispiel #14
0
def plot_3d(stencil, figure=None, axes=None, data=None, textsize='8'):
    """
    Draws 3D stencil into a 3D coordinate system, parameters are similar to :func:`visualize_stencil_2d`
    If data is None, no labels are drawn. To draw the labels as in the 2D case, use ``data=list(range(len(stencil)))``
    """
    from matplotlib.patches import FancyArrowPatch
    from mpl_toolkits.mplot3d import proj3d
    import matplotlib.pyplot as plt
    from matplotlib.patches import BoxStyle
    from itertools import product, combinations
    import numpy as np

    class Arrow3D(FancyArrowPatch):
        def __init__(self, xs, ys, zs, *args, **kwargs):
            FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
            self._verts3d = xs, ys, zs

        def draw(self, renderer):
            xs3d, ys3d, zs3d = self._verts3d
            xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)
            self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
            FancyArrowPatch.draw(self, renderer)

    if axes is None:
        if figure is None:
            figure = plt.figure()
        axes = figure.add_subplot(projection='3d')
        try:
            axes.set_aspect("equal")
        except NotImplementedError:
            pass

    if data is None:
        data = [None] * len(stencil)

    text_offset = 1.25
    text_box_style = BoxStyle("Round", pad=0.3)

    # Draw cell (cube)
    r = [-1, 1]
    for s, e in combinations(np.array(list(product(r, r, r))), 2):
        if np.sum(np.abs(s - e)) == r[1] - r[0]:
            axes.plot(*zip(s, e), color="k", alpha=0.5)

    for d, annotation in zip(stencil, data):
        assert len(d) == 3, "Works only for 3D stencils"
        d = tuple(int(i) for i in d)
        if not (d[0] == 0 and d[1] == 0 and d[2] == 0):
            if d[0] == 0:
                color = '#348abd'
            elif d[1] == 0:
                color = '#fac364'
            elif sum([abs(d) for d in d]) == 2:
                color = '#95bd50'
            else:
                color = '#808080'

            a = Arrow3D([0, d[0]], [0, d[1]], [0, d[2]],
                        mutation_scale=20,
                        lw=2,
                        arrowstyle="-|>",
                        color=color)
            axes.add_artist(a)

        if annotation:
            if isinstance(annotation, sp.Basic):
                annotation = "$" + sp.latex(annotation) + "$"
            else:
                annotation = str(annotation)

            axes.text(x=d[0] * text_offset,
                      y=d[1] * text_offset,
                      z=d[2] * text_offset,
                      s=annotation,
                      verticalalignment='center',
                      zorder=30,
                      size=textsize,
                      bbox=dict(boxstyle=text_box_style,
                                facecolor='#777777',
                                alpha=0.6,
                                linewidth=0))

    axes.set_xlim([-text_offset * 1.1, text_offset * 1.1])
    axes.set_ylim([-text_offset * 1.1, text_offset * 1.1])
    axes.set_zlim([-text_offset * 1.1, text_offset * 1.1])
    axes.set_axis_off()
Beispiel #15
0
def plot_2d(stencil,
            axes=None,
            figure=None,
            data=None,
            textsize='12',
            **kwargs):
    """
    Creates a matplotlib 2D plot of the stencil

    Args:
        stencil: sequence of directions
        axes: optional matplotlib axes
        figure: optional matplotlib figure
        data: data to annotate the directions with, if none given, the indices are used
        textsize: size of annotation text
    """
    from matplotlib.patches import BoxStyle
    import matplotlib.pyplot as plt

    if axes is None:
        if figure is None:
            figure = plt.gcf()
        axes = figure.gca()

    text_box_style = BoxStyle("Round", pad=0.3)
    head_length = 0.1
    max_offsets = [max(abs(int(d[c])) for d in stencil) for c in (0, 1)]

    if data is None:
        data = list(range(len(stencil)))

    for direction, annotation in zip(stencil, data):
        assert len(direction) == 2, "Works only for 2D stencils"
        direction = tuple(int(i) for i in direction)
        if not (direction[0] == 0 and direction[1] == 0):
            axes.arrow(0,
                       0,
                       direction[0],
                       direction[1],
                       head_width=0.08,
                       head_length=head_length,
                       color='k')

        if isinstance(annotation, sp.Basic):
            annotation = "$" + sp.latex(annotation) + "$"
        else:
            annotation = str(annotation)

        def position_correction(d, magnitude=0.18):
            if d < 0:
                return -magnitude
            elif d > 0:
                return +magnitude
            else:
                return 0

        text_position = [
            direction[c] + position_correction(direction[c]) for c in (0, 1)
        ]
        axes.text(x=text_position[0],
                  y=text_position[1],
                  s=annotation,
                  verticalalignment='center',
                  zorder=30,
                  horizontalalignment='center',
                  size=textsize,
                  bbox=dict(boxstyle=text_box_style,
                            facecolor='#00b6eb',
                            alpha=0.85,
                            linewidth=0))

    axes.set_axis_off()
    axes.set_aspect('equal')
    max_offsets = [m if m > 0 else 0.1 for m in max_offsets]
    border = 0.1
    axes.set_xlim([-border - max_offsets[0], border + max_offsets[0]])
    axes.set_ylim([-border - max_offsets[1], border + max_offsets[1]])
Beispiel #16
0
def plot_alt_mappings(options, collection):
    #GenomeDiagram.FeatureSet()
    color_list = plt.cm.Set1(np.linspace(0, 1, 25))
    chroms = [str(x) for x in range(1, 25)]
    chroms[22] = "X"
    chroms[23] = "Y"
    #print len(color_list)

    handles = []
    for j in range(0, 24):
        handles.append(mpatches.Patch(color=color_list[j], label=chroms[j]))

    for read in collection:
        print read

        fig = plt.figure()
        ax = fig.add_subplot(111)

        sortaln = sorted(collection[read], reverse=True)

        if len(sortaln) == 0:
            continue

        # SET plot limits
        ax.set_xlim(0, sortaln[0].aln.totlen)
        ax.set_ylim(-10, 10)

        nr_reads = min(options.nr_align, len(sortaln))
        for i in range(0, nr_reads):
            if i <= 10:
                print(sortaln[i])
            col = color_list[sortaln[i].ref.get_loc()]
            width = sortaln[i].aln.length

            score = log(sortaln[i].score)
            direction = "RArrow"
            xpos = sortaln[i].aln.pos

            if sortaln[i].aln.strand == '-':
                score = score * -1
                direction = "LArrow"
                xpos = sortaln[i].aln.totlen - sortaln[i].aln.pos - width

            xy = (xpos, score - 0.1)
            patch = mpatches.FancyBboxPatch(xy,
                                            width,
                                            0.2,
                                            BoxStyle(direction),
                                            facecolor=col,
                                            edgecolor='black',
                                            alpha=0.7,
                                            label=sortaln[i].ref.loc)
            ax.add_patch(patch)

        # Mark-up of plot
        ax.set_yticks(range(-10, 10, 1))
        ax.grid(True)
        ax.set_xlabel('Location within read')
        ax.set_ylabel('Log(score)')

        # Shrink plot to accomodate legend
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])

        # Add color legend
        ax.legend(bbox_to_anchor=(1.05, 1),
                  loc=2,
                  borderaxespad=0.,
                  ncol=1,
                  prop={'size': 8})
        #handles=handles,

        # SAVE file
        fig.savefig(read + '.pdf')
        plt.close(fig)