Exemple #1
0
def plot_airport_risks(df, wuhan_R0=3, kappa=1):
    fig = plt.figure(figsize=MAP_SIZE)
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    norm = mpl.colors.Normalize(vmin=0, vmax=1, clip=True)
    ax.scatter(df.Lon,
               df.Lat,
               color=cmap(norm(df.p_outbreak_from_one)),
               s=(DOT_SIZE * df.p_outbreak_from_one)**2)
    _add_features(ax)
    plt.tight_layout()
    plt.savefig(
        f'./pix/airports_p_outbreak_from_one_wuhan{wuhan_R0}_kappa{kappa}.jpg',
        quality=QUALITY,
        dpi=DPI)
    plt.close('all')

    fig = plt.figure(figsize=H_CB_SIZE)
    ax = fig.add_subplot()
    ax.yaxis.set_tick_params(labelsize=20)
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    sm._A = []
    cbar = plt.colorbar(sm, orientation='horizontal', cax=ax)
    cbar.ax.tick_params(labelsize=35)
    plt.tight_layout()
    plt.savefig(
        f'./pix/airports_p_outbreak_from_one_wuhan{wuhan_R0}_kappa{kappa}_cb.jpg',
        quality=QUALITY,
        dpi=DPI)
    plt.close('all')
 def draw(self, func, scaling=1, segfunc=False, clim=None, cmap=None):
     """ Draw cell in matplotlib line plot collection
     """
     from numpy import array, linspace
     from matplotlib.collections import LineCollection
     from matplotlib import pyplot
     self.build_tree(func, segfunc)
     pts = self.xyzdv[:, :2]
     edges = self.connections
     diam = self.xyzdv[:, 3]
     data = self.xyzdv[:, 4]
     print("DATA RANGE: ", data.min(), data.max())
     # Define colors
     if not cmap:
         from matplotlib.cm import jet as cmap
     if not clim:
         clim = [data.min(), data.max()]
     a = (data - clim[0]) / (clim[1] - clim[0])
     # Define line segments
     segments = []
     for edge in edges:
         segments.append([pts[edge[0], :], pts[edge[1], :]])
     # Build Line Collection
     collection = LineCollection(segments=array(segments),
                                 linewidths=diam * scaling,
                                 colors=cmap(a))
     collection.set_array(data)
     collection.set_clim(clim[0], clim[1])
     pyplot.gca().add_collection(collection, autolim=True)
     pyplot.axis('equal')
     return collection
Exemple #3
0
    def make_it(ax, df, month):

        ax.scatter(df.origin_lon,
                   df.origin_lat,
                   color=cmap(norm(df.risk_i)),
                   s=(DOT_SIZE * norm(df.risk_i)**2))
        _add_features(ax)
        _annotate(ax, text=month, color='k', region='global')
def plot_band_matrix(M, pos_map=None, upper=False):
    non_zero = np.where(M)
    coords = []
    for pi1, pi2 in zip(non_zero[0], non_zero[1]):
        p1 = pi1 if pos_map is None else pos_map[pi1]
        p2 = pi2 if pos_map is None else pos_map[pi2]
        if upper and p1 > p2:
            continue
        px = 0.5 * (p1 + p2)
        py = (p2 - p1) * np.sqrt(0.5)
        coords.append([px, py, M[pi1, pi2], p1, p2])

    coords = np.array(coords)

    from matplotlib.cm import RdBu_r as cmap
    #plt.scatter(coords[:,0], coords[:,1], c=coords[:,2])
    for px, py, v, p1, p2 in coords:
        plt.plot([p1, p2], [py, py], c=cmap((v + 1) / 2.0))
Exemple #5
0
def colorplot(ax, X, Y, C, label=None, numlabs=4):
    """Plot data in array X vs. array Y with points colored by C (on axis ax)

    X, Y, and C must be arrays (or lists, tuples) and have the same length;
    C can be matplotlib character colors, names, hex strings, RGB tuples.
    If C is only 1d float values, it will be treated as a z-axis and mapped
    to the default colormap.
    label, if defined, is text to be periodically placed on the line.
    """
    # That means normalizing to 0-1 and using matplotlib.colors.Colormap
    if isinstance(C[0], (float, int)):
        nm = Normalize(min(C), max(C))
        C = cmap(nm(C))
    # TODO : keep nm for all instances, so all lines are colored equivalently
    for x, y, c, n in zip(X, Y, C, count()):
        ax.plot([x], [y], linestyle='', marker='.', ms=1., mfc=c)
        if label is not None and not n % (len(X) // numlabs):
            ax.annotate(label, [x, y])
Exemple #6
0
def colorplot(ax, X, Y, C, label=None, numlabs=4):
    """Plot data in array X vs. array Y with points colored by C (on axis ax)

    X, Y, and C must be arrays (or lists, tuples) and have the same length;
    C can be matplotlib character colors, names, hex strings, RGB tuples.
    If C is only 1d float values, it will be treated as a z-axis and mapped
    to the default colormap.
    label, if defined, is text to be periodically placed on the line.
    """
    # That means normalizing to 0-1 and using matplotlib.colors.Colormap
    if isinstance(C[0], (float, int)):
        nm = Normalize(min(C), max(C))
        C = cmap(nm(C))
    # TODO : keep nm for all instances, so all lines are colored equivalently
    for x, y, c, n in zip(X, Y, C, count()):
        ax.plot([x], [y], linestyle='', marker='.', ms=1., mfc=c)
        if label is not None and not n % (len(X)//numlabs):
            ax.annotate(label, [x, y])
Exemple #7
0
def plot_rep_risks(df, kappa=1, wuhan_R0=3, region='global'):
    fig = plt.figure(figsize=MAP_SIZE)
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    norm = mpl.colors.Normalize(vmin=0, vmax=VMAX.get(region, 0.75), clip=True)
    ax.scatter(df.origin_lon,
               df.origin_lat,
               color=cmap(norm(df.risk_i)),
               s=(DOT_SIZE * norm(df.risk_i))**2)
    _add_features(ax, region=region)
    plt.tight_layout()

    plt.savefig(f'./pix/{region}/risks_rep_wuhan{wuhan_R0}_kappa{kappa}.jpg',
                quality=QUALITY,
                dpi=DPI)
    if kappa == 1 and wuhan_R0 == 3:
        _annotate(ax, text='b', color='k', region=region)
        plt.savefig(
            f'./pix/{region}/risks_rep_wuhan{wuhan_R0}_kappa{kappa}_main.jpg',
            quality=QUALITY,
            dpi=DPI)

    plt.close('all')
Exemple #8
0
import galore
import galore.plot

vasprun = 'test/MgO/vasprun.xml.gz'
xmin, xmax = (-6, 15)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

widths = np.arange(0, 2.01, 0.4)
widths[0] = 0.05  # Use a finite width in smallest case

for g in widths:

    x_values, broadened_data = galore.process_1d_data(input=vasprun,
                                                      gaussian=g,
                                                      xmin=xmin,
                                                      xmax=xmax)

    broadened_data /= g  # Scale values by broadening width to conserve area

    galore.plot.plot_tdos(x_values, broadened_data, ax=ax)
    line = ax.lines[-1]
    line.set_label("{0:2.2f}".format(g))
    line.set_color(cmap(g / max(widths)))

ax.set_ylim(0, 1000)
legend = ax.legend(loc='best')
legend.set_title('Gaussian $\gamma$')
plt.show()
weightings = ('He2', 'Alka', 'Yeh_HAXPES')

for i, weighting in enumerate(weightings):

    plotting_data = galore.process_pdos(input=[vasprun],
                                        gaussian=0.3,
                                        lorentzian=0.2,
                                        xmin=xmin,
                                        xmax=xmax,
                                        weighting=weighting)
    galore.plot.plot_pdos(plotting_data,
                          ax=ax,
                          show_orbitals=False,
                          units='eV',
                          xmin=-xmin,
                          xmax=-xmax,
                          flipx=True)

    line = ax.lines[-1]
    line.set_label(weighting)
    line.set_color(cmap(i / len(weightings)))

    ymax = max(line.get_ydata())
    line.set_data(line.get_xdata(), line.get_ydata() / ymax)

ax.set_ylim((0, 1.2))
legend = ax.legend(loc='best')
legend.set_title('Weighting')
plt.show()
Exemple #10
0
                                resampling=rasterio.warp.Resampling.nearest)
            
                                cax = ax.matshow(np.ma.masked_equal(dst, 0) / 550.0, cmap=cmap,
                                                 extent=extent, transform=ccrs.UTM(16),
                                                 vmin=10, vmax=40)
                                
                                t = ax.text((src_raster.bounds.right + src_raster.bounds.left) / 2,
                                            (src_raster.bounds.top + src_raster.bounds.bottom) / 2,
                                            path_row,
                                            transform=ccrs.UTM(16),
                                            fontsize=20, ha='center', va='top', color='.1',
                                            path_effects=[pe.withStroke(linewidth=3, foreground=".9")])
                                
                                sns.distplot(dst.ravel() / 550.0, ax=hax, axlabel='Reflectance (%)', kde=False, norm_hist=True)
                                hax.set_title(path_row, fontsize=13)
                                hax.set_xlim(0,100); hax.set_ylim(0,.1)
                                
                                [patch.set_color(cmap(plt.Normalize(vmin=10, vmax=40)(patch.xy[0]))) for patch in hax.patches]
                                [patch.set_alpha(1) for patch in hax.patches]
                                
        del dst

fig.colorbar(cax, ax=ax, label='Reflectance (%)')
fig.savefig('./images/11/band-5.png', transparent=True, bbox_inches='tight', pad_inches=0)
hist_fig.savefig('./images/11/hist-band-5.png', transparent=True, bbox_inches='tight', pad_inches=0)





Exemple #11
0
def getEllipses(event, pocas, min_z, max_z, axes, fig):

    trackCount = 0

    #initialize lists needed to plot ellipsoids
    ellsXY = []
    ellsZX = []
    ellsZY = []
    zpoca_vals = []
    alphas = []

    cm = cmap("cool")
    for j in range(len(pocas["x"]["major_axis"][event])):
        #create three vectors corresponding to major axis and the two minor axes
        major_axis = [
            pocas["x"]["major_axis"][event][j],
            pocas["y"]["major_axis"][event][j],
            pocas["z"]["major_axis"][event][j]
        ]
        minor_axis1 = [
            pocas["x"]["minor_axis1"][event][j],
            pocas["y"]["minor_axis1"][event][j],
            pocas["z"]["minor_axis1"][event][j]
        ]
        minor_axis2 = [
            pocas["x"]["minor_axis2"][event][j],
            pocas["y"]["minor_axis2"][event][j],
            pocas["z"]["minor_axis2"][event][j]
        ]

        #calculate magnitude of major axis (used to determine alpha of ellipsoid)
        major_axis_mag = np.sqrt(major_axis[0]**2 + major_axis[1]**2 +
                                 major_axis[2]**2)

        #determine color of ellipsoid (according to depth in z-axis)
        color_scaling = (pocas["z"]["poca"][event][j] - min_z) / (max_z -
                                                                  min_z)
        color = cm(color_scaling)

        #calculate ellipsoid parameters from three-vectors
        A, B, C, D, E, F = six_ellipsoid_parameters(major_axis, minor_axis1,
                                                    minor_axis2)

        #calculate ellipsoid parameters from three-vectors
        A, B, C, D, E, F = six_ellipsoid_parameters(major_axis, minor_axis1,
                                                    minor_axis2)

        #calculate parameters needed for x-y projection of ellipsoid
        alpha_xy, beta_xy, gamma_xy, delta_xy = xy_parallel_projection(
            A, B, C, D, E, F)
        #calculate plotting parameters of ellipsoid
        a_xy, b_xy, theta_xy = ellipse_parameters_for_plotting(
            alpha_xy, beta_xy, gamma_xy, delta_xy, A, C)

        #repeat for x,z
        alpha_zx, beta_zx, gamma_zx, delta_zx = xy_parallel_projection(
            C, A, B, E, D, F)
        a_zx, b_zx, theta_zx = ellipse_parameters_for_plotting(
            alpha_zx, beta_zx, gamma_zx, delta_zx, B, A)

        #repeat for y,z
        alpha_zy, beta_zy, gamma_zy, delta_zy = xy_parallel_projection(
            C, B, A, F, D, E)
        a_zy, b_zy, theta_zy = ellipse_parameters_for_plotting(
            alpha_zy, beta_zy, gamma_zy, delta_zy, C, A)

        #create Ellipse objects corresponding to track
        thisEllipseXY = Ellipse(
            [pocas["x"]["poca"][event][j], pocas["y"]["poca"][event][j]],
            a_xy,
            b_xy,
            theta_xy,
            color=color)
        thisEllipseZX = Ellipse(
            [pocas["z"]["poca"][event][j], pocas["x"]["poca"][event][j]],
            a_zx,
            b_zx,
            theta_zx,
            color=color)
        thisEllipseZY = Ellipse(
            [pocas["z"]["poca"][event][j], pocas["y"]["poca"][event][j]],
            a_zy,
            b_zy,
            theta_zy,
            color=color)

        #add ellipse to list if it falls in the z-range
        if (pocas["z"]["poca"][event][j] >= min_z
                and pocas["z"]["poca"][event][j] <= max_z):
            ellsXY.append(thisEllipseXY)
            ellsZX.append(thisEllipseZX)
            ellsZY.append(thisEllipseZY)
            zpoca_vals.append(pocas["z"]["poca"][event][j])

            #calculate opacity of ellipse
            alpha = 0.3 * major_axis_mag
            alpha = min(alpha, 1)
            alpha = 1 - alpha
            alpha = 0.7 * max(alpha, 0.05)
            alphas.append(alpha)

            trackCount += 1

    #sort ellipses according to depth in z-axis (so that we don't plot in a random order, makes visualization easier)
    ellsXY = [e for _, e in sorted(zip(zpoca_vals, ellsXY), reverse=True)]
    ellsZX = [e for _, e in sorted(zip(zpoca_vals, ellsZX), reverse=True)]
    ellsZY = [e for _, e in sorted(zip(zpoca_vals, ellsZY), reverse=True)]
    alphas = [
        alpha for _, alpha in sorted(zip(zpoca_vals, alphas), reverse=True)
    ]

    if trackCount > 30:
        alphas = np.multiply(alphas, 0.5)

    #plot ellipses
    for j in range(len(alphas)):
        axes[0].add_artist(ellsXY[j])
        ellsXY[j].set_clip_box(axes[0].bbox)
        ellsXY[j].set_alpha(alphas[j])

        axes[1].add_artist(ellsZX[j])
        ellsZX[j].set_clip_box(axes[1].bbox)
        ellsZX[j].set_alpha(alphas[j])

        axes[2].add_artist(ellsZY[j])
        ellsZY[j].set_clip_box(axes[2].bbox)
        ellsZY[j].set_alpha(alphas[j])

    fig.colorbar(ScalarMappable(norm=Normalize(vmin=min_z, vmax=max_z),
                                cmap=cm),
                 ax=axes[0],
                 label='Position in z')
    fig.colorbar(ScalarMappable(norm=Normalize(vmin=min_z, vmax=max_z),
                                cmap=cm),
                 ax=axes[1],
                 label='Position in z')
    fig.colorbar(ScalarMappable(norm=Normalize(vmin=min_z, vmax=max_z),
                                cmap=cm),
                 ax=axes[2],
                 label='Position in z')
Exemple #12
0
def plot_geodesics(df, destinations, region, opacity_s=0.7):
    print("Plotting geodesics")
    df = df.query('Dest in @destinations')
    fig = plt.figure(figsize=MAP_SIZE)
    plateCr = ccrs.PlateCarree()
    plateCr._threshold = plateCr._threshold / 10.
    ax = plt.axes(projection=plateCr)

    ## Plot FSI ###########
    if region == 'global':
        cmap = plt.cm.winter
        shp = shpreader.natural_earth(resolution='10m',
                                      category='cultural',
                                      name='admin_0_countries')
        reader = shpreader.Reader(shp)
        for n in reader.records():

            fsi, name = geography.get_fsi(n, FSI_DF)

            if fsi is None:
                clr = 'grey'
            elif fsi < 30:
                clr = cmap(0)
            elif fsi >= 30 and fsi < 60:
                clr = cmap(0.33)
            elif fsi >= 60 and fsi < 90:
                clr = cmap(0.66)
            else:
                clr = cmap(0.99)
            try:
                ax.add_geometries(n.geometry,
                                  ccrs.PlateCarree(),
                                  facecolor=clr,
                                  alpha=0.5,
                                  linewidth=0.15,
                                  edgecolor="black",
                                  label=n.attributes['ADM0_A3'])
            except:
                ax.add_geometries([n.geometry],
                                  ccrs.PlateCarree(),
                                  facecolor=clr,
                                  alpha=0.5,
                                  linewidth=0.15,
                                  edgecolor="black",
                                  label=n.attributes['ADM0_A3'])

        # Make legend
        handles = [
            mpatches.Patch(color=cmap(0.00), label='Sustainable'),
            mpatches.Patch(color=cmap(0.33), label='Stable'),
            mpatches.Patch(color=cmap(0.66), label='Warning'),
            mpatches.Patch(color=cmap(0.99), label='Alert'),
            mpatches.Patch(color='grey', label='No Data')
        ]
        plt.legend(handles=handles, loc=6, prop={'size': 20})

    ## Plot Geodesix ###########
    if region == 'global':
        cutoff = 0.005
    else:
        cutoff = 0.1
    opacity = np.maximum(df.risk_ij, cutoff)
    lines = plt.plot(df[['origin_lon', 'dest_lon']].T,
                     df[['origin_lat', 'dest_lat']].T,
                     color='r',
                     transform=ccrs.Geodetic())
    [
        line.set_alpha(opacity_scaler(alpha, opacity_s))
        for alpha, line in zip(opacity, lines)
    ]

    _annotate(ax, text='a', color='k', region=region)
    _add_features(ax, region=region)

    plt.tight_layout()
    plt.savefig(f'./pix/{region}/geodesics.jpg', quality=QUALITY, dpi=DPI)
    plt.close('all')
Exemple #13
0
        t1.tree.ladderize()
        t.print_lh()
        print ("Prior branch len: {0}".format((t.tree.total_branch_length())))
        t1.print_lh()
        print ("Posterior branch len: {0}".format((t1.tree.total_branch_length())))

        #traveling_wave(t1.tree, Tc=0.005)
        #t1.init_date_constraints(gtr, slope=slope)
        #t1.ml_t(gtr)
        t1.coalescent_model(optimize_Tc=True)
        t1.print_lh()
        print ("coalescent model branch len: {0}".format((t1.tree.total_branch_length())))

        gtr = GTR.standard()
        t2 = io.treetime_from_newick(gtr, nwk)
        # set alignment to the tree
        io.set_seqs_to_leaves(t2, AlignIO.read(fasta, 'fasta'))
        io.read_metadata(t2, mdf)
        t2.reroot_to_best_root(infer_gtr=True)
        t2.init_date_constraints()
        t2.ml_t()
        t2.tree.ladderize()
        t2.relaxed_clock(slack=.1, coupling=1)
        t2.ml_t()

        from matplotlib.cm import jet as cmap
        for n in t2.tree.find_clades():
            n.color = [int(x*255) for x in cmap(max(0, min(0.5*n.gamma, 1.0)))[:3]]

        Phylo.draw(t2.tree, label_func = lambda x:'', show_confidence=False, branch_labels='')
Exemple #14
0
    #traveling_wave(t1.tree, Tc=0.005)
    #t1.init_date_constraints(gtr, slope=slope)
    #t1.ml_t(gtr)
    t1.coalescent_model(optimize_Tc=True)
    t1.print_lh()
    print("coalescent model branch len: {0}".format(
        (t1.tree.total_branch_length())))

    gtr = GTR.standard()
    t2 = io.treetime_from_newick(gtr, nwk)
    # set alignment to the tree
    io.set_seqs_to_leaves(t2, AlignIO.read(fasta, 'fasta'))
    io.read_metadata(t2, mdf)
    t2.reroot_to_best_root(infer_gtr=True)
    t2.init_date_constraints()
    t2.ml_t()
    t2.tree.ladderize()
    t2.relaxed_clock(slack=.1, coupling=1)
    t2.ml_t()

    from matplotlib.cm import jet as cmap
    for n in t2.tree.find_clades():
        n.color = [
            int(x * 255) for x in cmap(max(0, min(0.5 * n.gamma, 1.0)))[:3]
        ]

    Phylo.draw(t2.tree,
               label_func=lambda x: '',
               show_confidence=False,
               branch_labels='')