Exemple #1
0
def rainbowArrow(ax, start, end, cmap="viridis", n=50, lw=3, headFac=350):
    lwpt = lw * headFac
    colmap = plt.get_cmap(cmap, n)
    # Arrow shaft: LineCollection
    x = np.linspace(start[0], end[0], n)
    y = np.linspace(start[1], end[1] + lw, n)
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap=colmap, linewidth=lwpt, clip_on=False)
    lc.set_array(np.linspace(0, 1, n))
    ax.add_collection(lc)
    lc.set_edgecolor("face")
    # Arrow head: Triangle
    tricoords = [(0, -0.4), (0.5, 0), (0, 0.4), (0, -0.4)]
    angle = np.arctan2(end[1] - start[1], end[0] - start[0])
    rot = matplotlib.transforms.Affine2D().rotate(angle)
    tricoords2 = rot.transform(tricoords)
    tri = matplotlib.path.Path(tricoords2, closed=True)
    ax.scatter(
        np.reshape(end[0], -1),
        np.reshape(end[1] + lw, -1),
        c=np.reshape(1, -1),
        s=(2 * lwpt)**2,
        marker=tri,
        cmap=cmap,
        vmin=0,
        clip_on=False,
    )
    ax.autoscale_view()
Exemple #2
0
def plot_MDS(Data, cmap="viridis"):
    Fmax = max(Data.log_den)
    Rho_bord_m = np.copy(Data.log_den_bord)
    d_dis = np.zeros((Data.N_clusters, Data.N_clusters), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=None,
                         dissimilarity="precomputed")
    for i in range(Data.N_clusters):
        for j in range(Data.N_clusters):
            d_dis[i][j] = Fmax - Rho_bord_m[i][j]
    for i in range(Data.N_clusters):
        d_dis[i][i] = 0.0
    out = model.fit_transform(d_dis)
    fig, ax = plt.subplots(nrows=1, ncols=1)
    s = []
    col = []
    for i in range(Data.N_clusters):
        s.append(20.0 * np.sqrt(len(Data.cluster_indices[i])))
        col.append(i)
    plt.scatter(out[:, 0], out[:, 1], s=s, c=col, cmap=cmap)
    cmal = cm.get_cmap(cmap, Data.N_clusters)
    colors = cmal(np.arange(0, cmal.N))
    for i in range(Data.N_clusters):
        cc = "k"
        r = colors[i][0]
        g = colors[i][1]
        b = colors[i][2]
        luma = (0.2126 * r + 0.7152 * g + 0.0722 * b) * 255
        if luma < 156:
            cc = "w"
        plt.annotate(
            i,
            (out[i, 0], out[i, 1]),
            horizontalalignment="center",
            verticalalignment="center",
            c=cc,
            weight="bold",
        )
    #    for i in range(Data.N_clusters):
    #        ax.annotate(i, (out[i, 0], out[i, 1]))
    # Add edges
    rr = np.amax(Rho_bord_m)
    if rr > 0.0:
        Rho_bord_m = Rho_bord_m / rr * 100.0
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(Rho_bord_m)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(Rho_bord_m.flatten())
    # lc.set_linewidths(np.full(len(segments),0.5))
    lc.set_edgecolor(np.full(len(segments), "black"))
    lc.set_facecolor(np.full(len(segments), "black"))
    lc.set_linewidths(0.02 * Rho_bord_m.flatten())
    ax.add_collection(lc)
    # fig.savefig('2D.png')
    plt.show()
Exemple #3
0
def generate_boundary_artist(vertices, color):
    if DIM == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif DIM == 3:
        artist = Poly3DCollection(vertices, linewidths=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError(
            "%d dimensions needs special attention for plotting." % int(DIM))
    return artist
Exemple #4
0
class MyCell(matplotlib.table.CustomCell):
    """ Extending matplotlib tables.
        
        Adapted from https://stackoverflow.com/a/53573651/505698
    """
    def __init__(self, *args, visible_edges, **kwargs):
        super().__init__(*args, visible_edges=visible_edges, **kwargs)
        seg = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],
                        [0.0, 0.0]]).reshape(-1, 1, 2)
        segments = np.concatenate([seg[:-1], seg[1:]], axis=1)
        self.edgelines = LineCollection(segments,
                                        edgecolor=kwargs.get("edgecolor"))
        self._text.set_zorder(2)
        self.set_zorder(1)

    def set_transform(self, trans):
        self.edgelines.set_transform(trans)
        super().set_transform(trans)

    def draw(self, renderer):
        c = self.get_edgecolor()
        self.set_edgecolor((1, 1, 1, 0))
        super().draw(renderer)
        self.update_segments(c)
        self.edgelines.draw(renderer)
        self.set_edgecolor(c)

    def update_segments(self, color):
        x, y = self.get_xy()
        w, h = self.get_width(), self.get_height()
        seg = np.array([[x, y], [x + w, y], [x + w, y + h], [x, y + h],
                        [x, y]]).reshape(-1, 1, 2)
        segments = np.concatenate([seg[:-1], seg[1:]], axis=1)
        self.edgelines.set_segments(segments)
        self.edgelines.set_linewidth(self.get_linewidth())
        colors = [
            color if edge in self._visible_edges else (1, 1, 1, 0)
            for edge in self._edges
        ]
        self.edgelines.set_edgecolor(colors)

    def get_path(self):
        codes = [Path.MOVETO] + [Path.LINETO] * 3 + [Path.CLOSEPOLY]
        return Path(
            [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
            codes,
            readonly=True,
        )
Exemple #5
0
def generate_boundary_artist(vertices, color):
    ndim = len(next(iter(vertices[0])))
    vertices = tuple(map(tuple, vertices))
    if ndim == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif ndim == 3:
        artist = Poly3DCollection(vertices, linewidth=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError("{:d} dimensions needs special attention for plotting".format(ndim))
    return artist
Exemple #6
0
def plot_MDS(Data):
    Fmax = max(Data.Rho)
    Rho_bord_m = np.copy(Data.out_bord)
    d_dis = np.zeros((Data.Nclus_m, Data.Nclus_m), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=None,
                         dissimilarity='precomputed')
    for i in range(Data.Nclus_m):
        for j in range(Data.Nclus_m):
            d_dis[i][j] = Fmax - Rho_bord_m[i][j]
    for i in range(Data.Nclus_m):
        d_dis[i][i] = 0.
    out = model.fit_transform(d_dis)
    fig, ax = plt.subplots(nrows=1, ncols=1)
    s = []
    col = []
    for i in range(Data.Nclus_m):
        s.append(20. * np.sqrt(len(Data.clstruct_m[i])))
        col.append(i)
    plt.scatter(out[:, 0], out[:, 1], s=s, c=col)
    for i in range(Data.Nclus_m):
        ax.annotate(i, (out[i, 0], out[i, 1]))
    # Add edges
    rr = np.amax(Rho_bord_m)
    if (rr > 0.):
        Rho_bord_m = Rho_bord_m / rr * 100.
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(Rho_bord_m)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(Rho_bord_m.flatten())
    # lc.set_linewidths(np.full(len(segments),0.5))
    lc.set_edgecolor(np.full(len(segments), 'black'))
    lc.set_facecolor(np.full(len(segments), 'black'))
    lc.set_linewidths(0.02 * Rho_bord_m.flatten())
    ax.add_collection(lc)
    #fig.savefig('2D.png')
    plt.show()
Exemple #7
0
def plot_volume(sim, vol=None, center=None, size=None,
                options=None, plot3D=False, label=None):

    options = options if options else def_plot_options

    fig=plt.gcf()
    ax=fig.gca(projection='3d') if plot3D else fig.gca()

    if vol:
       center, size = vol.center, vol.size
    v0=np.array([center.x, center.y])
    dx,dy=np.array([0.5*size.x,0.0]), np.array([0.0,0.5*size.y])
    if plot3D:
        zmin,zmax = ax.get_zlim3d()
        z0 = zmin + options['zrel']*(zmax-zmin)

    ##################################################
    # add polygon(s) to the plot to represent the volume
    ##################################################
    def add_to_plot(c):
        ax.add_collection3d(c,zs=z0,zdir='z') if plot3D else ax.add_collection(c)

    if size.x==0.0 or size.y==0.0:    # zero thickness, plot as line
        polygon = [ v0+dx+dy, v0-dx-dy ]
        add_to_plot( LineCollection( [polygon], colors=options['line_color'],
                                     linewidths=options['line_width'],
                                     linestyles=options['line_style']
                                   )
                   )
    else:
        if options['fill_color'] != 'none': # first copy: faces, no edges
            polygon = np.array([v0+dx+dy, v0-dx+dy, v0-dx-dy, v0+dx-dy])
            pc=PolyCollection( [polygon], linewidths=0.0)
            pc.set_color(options['fill_color'])
            pc.set_alpha(options['alpha'])
            add_to_plot(pc)
        if options['boundary_width']>0.0: # second copy: edges, no faces
            closed_polygon = np.array([v0+dx+dy, v0-dx+dy, v0-dx-dy, v0+dx-dy, v0+dx+dy])
            lc=LineCollection([closed_polygon])
            lc.set_linestyle(options['boundary_style'])
            lc.set_linewidth(options['boundary_width'])
            lc.set_edgecolor(options['boundary_color'])
            add_to_plot(lc)

    ######################################################################
    # attempt to autodetermine text rotation and alignment
    ######################################################################
    if label:
        x0, y0, r, h, v = np.mean(ax.get_xlim()),np.mean(ax.get_ylim()), 0, 'center', 'center'
        if size.y==0.0:
            v = 'bottom' if center.y>y0 else 'top'
        elif size.x==0.0:
            r, h = (270,'left') if center.x>x0 else (90,'right')
        if plot3D:
            ax.text(center.x, center.y, z0, label, rotation=r,
                    fontsize=options['fontsize'], color=options['line_color'],
                    horizontalalignment=h, verticalalignment=v)
        else:
            ax.text(center.x, center.y, label, rotation=r,
                    fontsize=options['fontsize'], color=options['line_color'],
                    horizontalalignment=h, verticalalignment=v)
Exemple #8
0
def plot_linestring_collection(ax,
                               geoms,
                               colors_or_values,
                               plot_values,
                               vmin=None,
                               vmax=None,
                               cmap=None,
                               linewidth=1.0,
                               **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from matplotlib.collections import LineCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    segments = [np.array(linestring)[:, :2] for linestring in components]
    collection = LineCollection(segments, linewidth=linewidth, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])

        if 'edgecolor' in kwargs:
            collection.set_edgecolor(kwargs['edgecolor'])

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Exemple #9
0
def plots_topography(dpa, ax_dendrogram, ax_project):
    Nclus_m = np.max(dpa.labels_) + 1
    cmap = plt.get_cmap('tab10', Nclus_m)
    # Convert from border densities to distances
    nd = int((Nclus_m * Nclus_m - Nclus_m) / 2)
    Dis = np.empty(nd, dtype=float)
    nl = 0
    Fmax = max(dpa.densities_)
    Rho_bord = np.zeros((Nclus_m, Nclus_m), dtype=float)
    for row in dpa.topography_:
        Rho_bord[row[0]][row[1]] = row[2]
        Rho_bord[row[1]][row[0]] = row[2]
        Dis[nl] = Fmax - row[2]
        nl = nl + 1
    # dendrogram representation
    DD = sp.cluster.hierarchy.single(Dis)
    dn = sp.cluster.hierarchy.dendrogram(DD,
                                         color_threshold=0,
                                         above_threshold_color='k',
                                         ax=ax_dendrogram)
    xlbls = ax_dendrogram.get_xmajorticklabels()
    dorder = []
    for lbl in xlbls:
        dorder.append(int(lbl._text))
        lbl.set_color(cmap(int(lbl._text)))
        lbl.set_weight('bold')


# 2D projection representation of the topography
    pop = np.zeros((Nclus_m), dtype=int)
    for i in range(len(dpa.labels_)):
        pop[dpa.labels_[i]] = pop[dpa.labels_[i]] + 1
    d_dis = np.zeros((Nclus_m, Nclus_m), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=10,
                         dissimilarity='precomputed')
    for i in range(Nclus_m):
        for j in range(Nclus_m):
            d_dis[i][j] = Fmax - Rho_bord[i][j]
    for i in range(Nclus_m):
        d_dis[i][i] = 0.
    out = model.fit_transform(d_dis)
    ax_project.yaxis.set_major_locator(plt.NullLocator())
    ax_project.xaxis.set_major_locator(plt.NullLocator())
    s = []
    col = []
    for i in range(Nclus_m):
        s.append(20. * sqrt(pop[i]))
        col.append(i)
    ax_project.scatter(out[:, 0], out[:, 1], s=s, c=col, cmap=cmap)
    #plt.colorbar(ticks=range(Nclus_m))
    #plt.clim(-0.5, Nclus_m-0.5)
    for i in range(Nclus_m):
        ax_project.annotate(i, (out[i, 0], out[i, 1]))
    for i in range(Nclus_m):
        for j in range(Nclus_m):
            d_dis[i][j] = Rho_bord[i][j]
    rr = np.amax(d_dis)
    if (rr > 0.):
        d_dis = d_dis / rr * 100.
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(d_dis)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(d_dis.flatten())
    lc.set_edgecolor(np.full(len(segments), 'black'))
    lc.set_facecolor(np.full(len(segments), 'black'))
    lc.set_linewidths(0.2 * Rho_bord.flatten())
    ax_project.add_collection(lc)
    return ax_dendrogram, ax_project
Exemple #10
0
def plot_volume(sim,
                vol=None,
                center=None,
                size=None,
                options=None,
                plot3D=False,
                label=None):

    options = options if options else def_plot_options

    fig = plt.gcf()
    ax = fig.gca(projection='3d') if plot3D else fig.gca()

    if vol:
        center, size = vol.center, vol.size
    v0 = np.array([center.x, center.y])
    dx, dy = np.array([0.5 * size.x, 0.0]), np.array([0.0, 0.5 * size.y])
    if plot3D:
        zmin, zmax = ax.get_zlim3d()
        z0 = zmin + options['zrel'] * (zmax - zmin)

    ##################################################
    # add polygon(s) to the plot to represent the volume
    ##################################################
    def add_to_plot(c):
        ax.add_collection3d(c, zs=z0,
                            zdir='z') if plot3D else ax.add_collection(c)

    if size.x == 0.0 or size.y == 0.0:  # zero thickness, plot as line
        polygon = [v0 + dx + dy, v0 - dx - dy]
        add_to_plot(
            LineCollection([polygon],
                           colors=options['line_color'],
                           linewidths=options['line_width'],
                           linestyles=options['line_style']))
    else:
        if options['fill_color'] != 'none':  # first copy: faces, no edges
            polygon = np.array(
                [v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy])
            pc = PolyCollection([polygon], linewidths=0.0)
            pc.set_color(options['fill_color'])
            pc.set_alpha(options['alpha'])
            add_to_plot(pc)
        if options['boundary_width'] > 0.0:  # second copy: edges, no faces
            closed_polygon = np.array([
                v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy,
                v0 + dx + dy
            ])
            lc = LineCollection([closed_polygon])
            lc.set_linestyle(options['boundary_style'])
            lc.set_linewidth(options['boundary_width'])
            lc.set_edgecolor(options['boundary_color'])
            add_to_plot(lc)

    ######################################################################
    # attempt to autodetermine text rotation and alignment
    ######################################################################
    if label:
        x0, y0, r, h, v = np.mean(ax.get_xlim()), np.mean(
            ax.get_ylim()), 0, 'center', 'center'
        if size.y == 0.0:
            v = 'bottom' if center.y > y0 else 'top'
        elif size.x == 0.0:
            r, h = (270, 'left') if center.x > x0 else (90, 'right')
        if plot3D:
            ax.text(center.x,
                    center.y,
                    z0,
                    label,
                    rotation=r,
                    fontsize=options['fontsize'],
                    color=options['line_color'],
                    horizontalalignment=h,
                    verticalalignment=v)
        else:
            ax.text(center.x,
                    center.y,
                    label,
                    rotation=r,
                    fontsize=options['fontsize'],
                    color=options['line_color'],
                    horizontalalignment=h,
                    verticalalignment=v)
Exemple #11
0
    def plot_all_frames(self, coloring_scheme=None):
        fig, (ax0, ax1) = plt.subplots(1,
                                       2,
                                       gridspec_kw={'width_ratios': [3, 5]},
                                       figsize=(14, 6))

        ax0.set_title('LV trace, full cycle'.format(self.id))
        ax0.set_ylim(-10.1, 1.0)
        ax0.set_xlim(-5.0, 5.0)
        ax0.set_xlabel('Short axis $[cm]$')
        ax0.set_ylabel('Long axis $[cm]$')

        ax1.set_title('Geometric point-to-point curvature')
        # ax1.axhline(y=0, c='k', ls='-.', lw=1)
        ax1.axvline(x=00, c='k', ls='-.', lw=1)
        ax1.axvline(x=120, c='k', ls='-.', lw=1)
        ax1.set_ylim(-7, 4)
        ax1.set_xlim(-10, 140)

        # ax1.vlines(self.ed_apex_id+1, 0, max(self.curvature[:, self.ed_apex_id]), color='k', linestyles='-.', lw=1)
        #  Added 1 to ed_apex_id because the plot is moved by one (due to lack of curvature at end points)
        ax1.set_xlabel('Region of interest')
        ax1.set_ylabel('Curvature $[dm^{-1}]$')

        if coloring_scheme == 'curvature':
            xx, yy, _ = self._get_translated_element(self.ed_frame,
                                                     self.ed_apex)
            yy *= -1
            curv = self._append_missing_curvature_values(
                self.curvature[self.ed_frame])
            # ax0.plot(xx, yy, 'k--', lw=3)
            # ax1.plot(curv, '--', c='black', lw=2)

            xx, yy, _ = self._get_translated_element(self.es_frame,
                                                     self.ed_apex)
            yy *= -1
            curv = self._append_missing_curvature_values(
                self.curvature[self.es_frame])
            # ax0.plot(xx, yy, 'k:', lw=3)
            ax1.plot(curv, ':', c='black', lw=2, alpha=0)

            legend_elements0 = \
                [Line2D([0], [0], c='k', ls='--', lw=2, label='End diastole'),
                 Line2D([0], [0], c='k', ls=':', lw=2, label='End systole')]
            legend_elements1 = [
                Line2D([0], [0], c='k', ls='--', lw=2, label='End diastole'),
                Line2D([0], [0], c='k', ls=':', lw=2, label='End systole'),
                Line2D([0], [0], c='b', lw=2, label='Negative curvature'),
                Line2D([0], [0], c='r', lw=2, label='Positive curvature')
            ]
        else:
            legend_elements0 = \
                [Line2D([0], [0], c='b', lw=2, label='Beginnning (end diastole)'),
                 Line2D([0], [0], c='purple', lw=2, label='Contraction'),
                 Line2D([0], [0], c='r', lw=2, label='End systole'),
                 Line2D([0], [0], c='g', lw=2, label='Towrds end diastole'),
                 Line2D([0], [0], c='w', marker='d', markerfacecolor='k', markersize=9, label='Apical point')]
            legend_elements1 = [
                Line2D([0], [0], c='b', lw=2, label='Beginnning'),
                Line2D([0], [0], c='purple', lw=2, label='Contraction'),
                Line2D([0], [0], c='r', lw=2, label='End systole'),
                Line2D([0], [0], c='g', lw=2, label='End'),
                Line2D([0], [0], c='k', ls=':', label='Apical point')
            ]

        for frame_number in range(self.number_of_frames):
            frame_number = self.ed_frame
            xx, yy, _ = self._get_translated_element(frame_number,
                                                     self.ed_apex)
            yy *= -1
            curv = self._append_missing_curvature_values(
                self.curvature[frame_number])[:130]
            norm_curv = self._append_missing_curvature_values(
                self.c_normalized[self.ed_frame])
            if coloring_scheme == 'curvature':
                color_tr = cm.seismic(norm_curv)
                color_tr[:, -1] = 0.9
                color = cm.seismic(norm_curv)
                # color[:, -1] = 0.01
                size = 10
                ax0.plot(xx, yy, c='gray', lw=2, alpha=0.005)
                ax0.scatter(xx,
                            yy,
                            c=color_tr,
                            edgecolor=color,
                            marker='o',
                            s=size,
                            alpha=0.1)

                points = np.array(
                    [np.linspace(0,
                                 len(curv) - 1, len(curv)),
                     curv]).T.reshape(-1, 1, 2)
                segments = np.concatenate([points[:-1], points[1:]], axis=1)
                norm = plt.Normalize(
                    -15, 15
                )  # Arbitrary values, seem to correspond to the ventricle image
                lc = LineCollection(segments,
                                    cmap='seismic',
                                    alpha=1,
                                    norm=norm)
                lc2 = LineCollection(segments,
                                     color='gray',
                                     alpha=0.2,
                                     norm=norm)
                lc.set_array(curv)
                lc.set_linewidth(2)
                lc.set_edgecolor('k')
                ax1.add_collection(lc)
                ax1.add_collection(lc2)
                ext = 'curvature'
                # break
            else:
                color_tr = np.array(
                    cm.brg(frame_number / self.number_of_frames)).reshape(
                        (1, -1))[0]
                color_tr[-1] = 0.2
                ax0.plot(xx, yy, c=color_tr, marker='.')
                ax1.plot(curv, c=color_tr, lw=2)
                ext = 'frame'

        # ax0.scatter(0, 0, c='k', marker='d', s=80, alpha=1, label='Apex at ED')
        ax0.legend(handles=legend_elements0,
                   loc='lower left',
                   title='Cardiac cycle')
        # ax1.legend(handles=legend_elements1, loc='upper right', title='Curvature')
        ax1.set_xticks(ticks=[0, 40, 80, 120])
        ax1.tick_params(
            axis='x',
            which='both',  # both major and minor ticks are affected
            bottom=False,  # ticks along the bottom edge are off
            top=False,  # ticks along the top edge are off
            labelbottom=False)  # labels along the bottom edge are off

        norm = mpl.colors.Normalize(vmin=-2, vmax=2)
        cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.seismic)
        cmap.set_array([norm])
        fig.colorbar(cmap)
        fig.suptitle('Geometric curvature in the trace of LV')
        # fig.tight_layout()
        if '.' in self.id:
            self.id = self.id.replace('.', '_')
        print(
            os.path.join(self.output_path,
                         '{}_colour_by_{}.png'.format(self.id, ext)))
        fig.savefig(fname=os.path.join(
            self.output_path, '{}_colour_by_{}.png'.format(self.id, ext)))
        plt.clf()
        plt.close()
Exemple #12
0
def plot_subregion(sim,
                   vol=None,
                   center=None,
                   size=None,
                   plot3D=False,
                   label=None,
                   section=None,
                   options=None):
    """
    Add polygons representing subregions of meep geometries
    to the current 2D or 3D geometry visualization.
    """

    #---------------------------------------------------------------
    #- fetch values of relevant options for the specified section
    #--------------------------------------------------------------
    keys = [
        'linecolor', 'linewidth', 'linestyle', 'fillcolor', 'alpha',
        'fontsize', 'zmin', 'latex'
    ]
    vals = vis_opts(keys, section=section, overrides=options)
    linecolor, linewidth, linestyle, fillcolor = vals[0:4]
    alpha, fontsize, zbar, latex = vals[4:8]

    fig = plt.gcf()
    ax = fig.gca(projection='3d') if plot3D else fig.gca()

    #--------------------------------------------------------------
    # unpack subregion geometry
    #--------------------------------------------------------------
    if vol:
        center, size = vol.center, vol.size
    v0 = np.array([center[0], center[1]])
    dx, dy = np.array([0.5 * size[0], 0.0]), np.array([0.0, 0.5 * size[1]])
    if plot3D:
        zmin, zmax = ax.get_zlim3d()
        z0 = 0.0

    #--------------------------------------------------------------
    # add polygon(s) to the plot to represent the volume
    #--------------------------------------------------------------
    def add_to_plot(c):
        ax.add_collection3d(c, zs=z0,
                            zdir='z') if plot3D else ax.add_collection(c)

    if size[0] == 0.0 or size[1] == 0.0:
        #========================================
        # region has zero thickness: plot as line
        #========================================
        polygon = [v0 + dx + dy, v0 - dx - dy]
        add_to_plot(
            LineCollection([polygon],
                           colors=linecolor,
                           linewidths=linewidth,
                           linestyles=linestyle))
    else:
        #========================================
        # plot as polygon, with separate passes
        # for the perimeter and the interior
        #========================================
        if fillcolor:  # first copy: faces, no edges
            polygon = np.array(
                [v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy])
            pc = PolyCollection([polygon], linewidths=0.0)
            pc.set_color(fillcolor)
            pc.set_alpha(alpha)
            add_to_plot(pc)
        if linewidth > 0.0:  # second copy: edges, no faces
            closed_polygon = np.array([
                v0 + dx + dy, v0 - dx + dy, v0 - dx - dy, v0 + dx - dy,
                v0 + dx + dy
            ])
            lc = LineCollection([closed_polygon])
            lc.set_linestyle(linestyle)
            lc.set_linewidth(linewidth)
            lc.set_edgecolor(linecolor)
            add_to_plot(lc)

    #####################################################################
    if label and fontsize > 0:
        plt.rc('text', usetex=latex)
        if latex:
            label = label.replace('_', '\_')
        x0, y0, r, h, v = np.mean(ax.get_xlim()), np.mean(
            ax.get_ylim()), 0, 'center', 'center'
        if size[1] == 0.0:
            v = 'bottom' if center[1] > y0 else 'top'
        elif size[0] == 0.0:
            r, h = (270, 'left') if center[0] > x0 else (90, 'right')
        if plot3D:
            ax.text(center[0],
                    center[1],
                    z0,
                    label,
                    rotation=r,
                    fontsize=fontsize,
                    color=linecolor,
                    horizontalalignment=h,
                    verticalalignment=v)
        else:
            ax.text(center[0],
                    center[1],
                    label,
                    rotation=r,
                    fontsize=fontsize,
                    color=linecolor,
                    horizontalalignment=h,
                    verticalalignment=v)
Exemple #13
0
#!/usr/bin/env python3
Exemple #14
0
def plot_linestring_collection(ax, geoms, colors_or_values, plot_values,
                               vmin=None, vmax=None, cmap=None,
                               linewidth=1.0, **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from matplotlib.collections import LineCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    segments = [np.array(linestring)[:, :2] for linestring in components]
    collection = LineCollection(segments,
                                linewidth=linewidth, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])

        if 'edgecolor' in kwargs:
            collection.set_edgecolor(kwargs['edgecolor'])

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection