Beispiel #1
0
def plot_U_surface(sim, scale=20):
    sim['umag'] = np.sqrt(sim.uc ** 2 + sim.vc ** 2)

    fig = plt.figure(figsize=(15, 8))
    ax = fig.add_subplot(111, projection='3d')

    ax = fix_3D_axes(ax)

    norm = plt.Normalize()

    veg = sim.veg.copy()
    veg[-1, 0] = -0.3
    veg[-1, -1] = 1.5
    veg_colors = cm.Greens(norm(veg))

    h_norm = colors.Normalize(vmin=10 * sim.umag.ravel().min() - .01,
                              vmax=10 * sim.umag.ravel().max())
    h_colors = cm.Blues(h_norm(sim.umag[sim.i_tr] * 10.))

    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax.plot_surface(sim.xc, sim.yc + 1, sim.zc * 0, facecolors=veg_colors,
                    rstride=1, cstride=1, alpha=0.9,
                    linewidth=0, antialiased=True, shade=False)

    ax.plot_surface(sim.xc, sim.yc + 1, sim.zc + sim.hc[sim.i_tr] * scale,
                    facecolors=h_colors, rstride=1, cstride=1,
                    linewidth=0, antialiased=True, shade=False, alpha=0.8)

    ax.view_init(25, 285)
    return fig, ax
Beispiel #2
0
 def plot_scope_records(scope_records,
                        scope_input_channel,
                        scope_time=0):
     """
     Helper function to plot scope records.
     """
     colors = [
         cm.Blues(np.linspace(0, 1, len(scope_records))),
         cm.Greens(np.linspace(0, 1, len(scope_records)))
     ]
     for index, record in enumerate(scope_records):
         totalsamples = record[0]['totalsamples']
         wave = record[0]['wave'][scope_input_channel, :]
         if not record[0]['channelmath'][scope_input_channel] & 2:
             # We're in time mode: Create a time array relative to the trigger time.
             dt = record[0]['dt']
             # The timestamp is the timestamp of the last sample in the scope segment.
             timestamp = record[0]['timestamp']
             triggertimestamp = record[0]['triggertimestamp']
             t = np.arange(-totalsamples, 0) * dt + (
                 timestamp - triggertimestamp) / float(clockbase)
             plt.plot(1e6 * t,
                      wave,
                      color=colors[scope_input_channel][index])
         elif record[0]['channelmath'][scope_input_channel] & 2:
             # We're in FFT mode.
             scope_rate = clockbase / 2**scope_time
             f = np.linspace(0, scope_rate / 2, totalsamples)
             plt.semilogy(f / 1e6,
                          wave,
                          color=colors[scope_input_channel][index])
     plt.draw()
     plt.grid(True)
     plt.ylabel('Amplitude [V]')
     plt.autoscale(enable=True, axis='x', tight=True)
Beispiel #3
0
def scale_colors(sizes, shapes):
    """
    Scales colors so they aren't all faded out. Returns R/G/B scales.

    :param sizes: List of sizes
    :param shapes: List of shapes

    :return: Colormap object
    """
    size_set = sorted(list(set(sizes)))
    linspace = np.linspace(0.2, 1, len(size_set))
    redmap = cm.Reds(linspace)
    greenmap = cm.Greens(linspace)
    bluemap = cm.Blues(linspace)

    colors = []

    for size, shape in zip(sizes, shapes):
        if shape == "icosahedron":
            # Red
            colors.append(redmap[size_set.index(size)])
        elif shape == "elongated-pentagonal-bipyramid":
            # Green
            colors.append(greenmap[size_set.index(size)])
        elif shape == "cuboctahedron":
            # Blue
            colors.append(bluemap[size_set.index(size)])
        else:
            raise ValueError

    return colors
Beispiel #4
0
def da_colors(typ):
    d = {}
    d["h85"] = cm.Oranges(.8)  #cm.Dark2(0.)
    d["piC"] = cm.Greens(.7)  #cm.Dark2(.2)
    d["gpcp"] = cm.Purples(.5)  #cm.Dark2(.4)
    d["cmap"] = cm.Reds(.8)
    d["precl"] = cm.Purples(.9)
    return d[typ]
Beispiel #5
0
def plot_compare_phi_psi(neurons, epsilon_values, tau_y_values, psi_values):

    '''This only works for summary type saves.'''

    fig, axs = plt.subplots(1, len(psi_values), sharey=True, figsize=(5*len(psi_values)+2, 5))
    cm_section = np.linspace(0.3, 1, len(tau_y_values))
    colours = []
    colours.append([ cm.Blues(x) for x in cm_section ])
    colours.append([ cm.Oranges(x) for x in cm_section ])
    colours.append([ cm.Purples(x) for x in cm_section ])
    colours.append([ cm.Greens(x) for x in cm_section ])


    for j, epsilon in enumerate(epsilon_values):

        for k, tau_y in enumerate(tau_y_values):

            label = "$\\tau_y={}$, $\epsilon={}$".format(tau_y,epsilon)

            E = []
            phi_values = []

            for i in range(len(psi_values)):
                E.append([])
                phi_values.append([])

            for neuron in neurons:
                
                if neuron.hyper['psi'] in psi_values:

                    phi_values[psi_values.index(neuron.hyper['psi'])].append(neuron.hyper['phi'])

                    for log in neuron.logs:
                        
                        if log[0]['tau_y'] == tau_y and log[0]['epsilon'] == epsilon:
                    
                            E[psi_values.index(neuron.hyper['psi'])].append(log[2]-log[3])

            for i in range(len(psi_values)):
                
                if i == 0:
                    axs[i].plot(phi_values[i], E[i], label=label, color=colours[j][k])
                    axs[i].set_ylabel('$E$')
                else:
                    axs[i].plot(phi_values[i], E[i], color=colours[j][k])
                axs[i].set_title('$\psi={}$'.format(psi_values[i]))
                axs[i].set_xlabel('$\phi$')

            
    fig.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    # fig.legend(loc='upper center', bbox_to_anchor=(0.5, -0.02), fancybox=True, shadow=True, ncol=6)

    fig.tight_layout()
    plt.show()

    return fig
Beispiel #6
0
def threeColorScales(number_of_lines, start=0.2, stop=1.0):

    cm_subsection = np.linspace(start, stop, number_of_lines)

    colorsBlue = [cm.Blues(x) for x in cm_subsection]
    colorsRed = [cm.Reds(x) for x in cm_subsection]
    colorsGreen = [cm.Greens(x) for x in cm_subsection]

    allColors = [colorsBlue, colorsRed, colorsGreen]
    return allColors
Beispiel #7
0
def get_eth_config():
    nodes = [4, 8, 16, 32]
    fpaths, tags, legends, colors = [], [], [], []
    ar_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv'
    ar_eth_tags = [
        'AR-DPSGD-CPUCOMM-4ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-8ETH-SCRATCH',
        'AR-DPSGD-CPUCOMM-16ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-32ETH-SCRATCH'
    ]
    ar_eth_legends = [
        'AR-SGD 4 nodes', 'AR-SGD 8 nodes', 'AR-SGD 16 nodes',
        'AR-SGD 32 nodes'
    ]
    ar_eth_colors = [
        cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_eth_tags))
    ]
    fpaths.append(ar_eth_fpath)
    tags.append(ar_eth_tags)
    legends.append(ar_eth_legends)
    colors.append(ar_eth_colors)

    ds_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv'
    ds_eth_tags = [
        'SDS-SGD-4ETH', 'SDS-SGD-8ETH', 'SDS-SGD-16ETH', 'SDS-SGD-32ETH'
    ]
    ds_eth_legends = [
        'D-PSGD 4 nodes', 'D-PSGD 8 nodes', 'D-PSGD 16 nodes',
        'D-PSGD 32 nodes'
    ]
    ds_eth_colors = [
        cm.Greens(x) for x in np.linspace(0.3, 0.8, len(ds_eth_tags))
    ]
    fpaths.append(ds_eth_fpath)
    tags.append(ds_eth_tags)
    legends.append(ds_eth_legends)
    colors.append(ds_eth_colors)

    ps_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv'
    ps_eth_tags = [
        'PS-SGD-4ETH-CHORD', 'PS-SGD-8ETH-CHORD', 'PS-SGD-16ETH-CHORD',
        'PS-SGD-32ETH-SCRATCH-CHORD'
    ]
    ps_eth_legends = [
        'SGP 4 nodes', 'SGP 8 nodes', 'SGP 16 nodes', 'SGP 32 nodes'
    ]
    ps_eth_colors = [
        cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_eth_tags))
    ]
    fpaths.append(ps_eth_fpath)
    tags.append(ps_eth_tags)
    legends.append(ps_eth_legends)
    colors.append(ps_eth_colors)

    # return nodes, fpaths[::-1], tags[::-1], legends[::-1], colors[::-1]
    return nodes, fpaths, tags, legends, colors
def get_colors(color_c=3, color_step=100):
    cmap_colors = np.vstack((
        cm.Oranges(np.linspace(0.4, 1, color_step)),
        cm.Reds(np.linspace(0.4, 1, color_step)),
        cm.Greys(np.linspace(0.4, 1, color_step)),
        cm.Purples(np.linspace(0.4, 1, color_step)),
        cm.Blues(np.linspace(0.4, 1, color_step)),
        cm.Greens(np.linspace(0.4, 1, color_step)),
        cm.pink(np.linspace(0.4, 1, color_step)),
        cm.copper(np.linspace(0.4, 1, color_step)),
    ))
    return cmap_colors[np.arange(color_c * color_step) % (color_step * 8)]
Beispiel #9
0
    def obs_SN(self,start_time,stop_time=None,overlapping=True,include_dai=False):
        if stop_time is None:
            stop_time=cmip5.stop_time(self.projection)
        target_obs = self.projection(time=(start_time,stop_time))
        L=len(target_obs)
        modslopes,noiseterm = self.sn_at_time(start_time,L,overlapping=True)
        ns=np.std(noiseterm)
        signal = float(cmip5.get_linear_trends(target_obs))/ns
        plt.hist(modslopes/ns,20,normed=True,color=cm.Oranges(.8),alpha=.5)
        lab = str(start_time.year)+"-"+str(stop_time.year)
        da.fit_normals_to_data(modslopes/ns,color=cm.Oranges(.9),label=lab+" Model projections")

        plt.hist(noiseterm/ns,20,normed=True,color=cm.Greens(.8),alpha=.5)
        da.fit_normals_to_data(noiseterm/ns,color=cm.Greens(.9),label="Pre-1850 tree-ring reconstructions")
        plt.axvline(signal,color=cm.Blues(.8),lw=3,label=lab+" Tree-ring reconstructions")
        print signal
        if include_dai:
            dai_proj = self.project_dai_on_solver(start=start_time)
            daitrend = cmip5.get_linear_trends(dai_proj(time=(start_time,stop_time)))
            
            
            
        plt.legend(loc=0)
Beispiel #10
0
def plot_3D_fhU(sim, h_scale=None, ind=None):
    """

    """
    if not h_scale:
        h_scale = int(sim.zc.max() / sim.hc.max() / 3.)
    if not ind:
        ind = sim.i_tr

    fig = plt.figure(figsize=(11, 6))

    ax = fig.add_subplot(111, projection='3d', )
    ax = fix_3D_axes(ax)

    veg = sim.veg.copy()
    veg[0, -1] = -0.2
    veg[1, -1] = 1.5

    norm = plt.Normalize()
    veg_colors = cm.Greens(norm(veg))

    f_norm = colors.Normalize(vmin=sim.infl_2d.ravel().min() - .01,
                              vmax=sim.infl_2d.ravel().max())

    f_colors = cmocean.cm.deep(f_norm(sim.infl_2d))

    U = np.sqrt(sim.uc ** 2 + sim.vc ** 2)
    U_norm = colors.Normalize(vmin=10 * U[ind].ravel().min() - .01,
                              vmax=10 * U[ind].ravel().max())

    U_colors = cm.Blues(U_norm(U[ind] * 10.))

    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

    ax.plot_surface(sim.xc, sim.yc, sim.zc, facecolors=veg_colors,
                    rstride=1, cstride=1, linewidth=0, antialiased=True,
                    shade=False, alpha=0.5)

    ax.plot_surface(sim.xc, sim.yc, sim.zc * 0, facecolors=f_colors,
                    rstride=1, cstride=1, linewidth=0, antialiased=True,
                    shade=False, alpha=0.8)

    ax.plot_surface(sim.xc, sim.yc, sim.zc + sim.hc[ind] * h_scale,
                    facecolors=U_colors, rstride=1, cstride=1,
                    linewidth=0, antialiased=True, shade=False, alpha=0.8)

    ax.view_init(25, 295)
    return fig, ax
Beispiel #11
0
def getProbDisplay1(contextlist, probabilitylist, file_name="test"):
    y_pos = np.arange(len(contextlist))
    colours = cm.Greens(probabilitylist / max(probabilitylist))
    p = plt.scatter(y_pos,
                    probabilitylist,
                    alpha=0.5,
                    c=probability,
                    cmap='Greens')
    plt.clf()
    plt.colorbar(p)
    plt.bar(range(len(probabilitylist)), [1] * len(contextlist), color=colours)

    plt.xticks(y_pos, contextlist)
    #plt.ylabel('probability')
    #plt.title('Category probabilities')
    plt.savefig(file_name + str(int(time.time())))  # save the figure to file
Beispiel #12
0
def plot_3D_veg(sim, plot_infl=False):
    """
    Plot veg pattern as surface
    """
    fig = plt.figure(figsize=(11, 6))
    ax = fig.add_subplot(111, projection='3d')

    ax = fix_3D_axes(ax)

    norm = plt.Normalize()
    isveg = sim.veg.copy()
    isveg = isveg.astype(float)

    isveg[isveg == 0] = 0.1
    isveg[isveg == 1] = 0.9
    isveg[0, -1] = 0
    isveg[1, -1] = 1
    veg_colors = cm.Greens(norm(isveg))

    xc = sim.xc
    yc = sim.yc
    topo = sim.zc

    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
    ax.plot_surface(xc, yc, topo,
                    facecolors=veg_colors,
                    rstride=1, cstride=1,
                    linewidth=0,
                    antialiased=True,
                    shade=False,
                    alpha=0.8)

    ax.view_init(25, 295)

    if plot_infl:
        norm = plt.Normalize(vmin=0)
        colors = cm.Blues(norm(sim.infl_2d))
        ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

        ax.plot_surface(xc, yc, topo, facecolors=colors,
                        rstride=1, cstride=1, linewidth=0,
                        antialiased=True, shade=False)
    return fig, ax
Beispiel #13
0
def plot_3D_infl_veg(sim, infl_2d=None, trim_at_outlet=2):
    """
    Infiltration plot on the incline, and veg on the horizontal plane
    """
    fig = plt.figure(figsize=(11, 6))
    ax = fig.add_subplot(111, projection='3d')

    ax = fix_3D_axes(ax)
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

    norm = plt.Normalize()
    isveg = sim.veg.copy()[:, trim_at_outlet:]
    isveg = isveg.astype(float)

    isveg[isveg == 0] = 0.1
    isveg[isveg == 1] = 0.8
    isveg[0, -1] = 0
    isveg[1, -1] = 1
    veg_colors = cm.Greens(norm(isveg))

    xc = sim.xc[:, trim_at_outlet:]
    yc = sim.yc[:, trim_at_outlet:]
    topo = sim.zc[:, trim_at_outlet:]

    if not infl_2d:
        infl_2d = sim.infl_2d

    norm = plt.Normalize(vmin=infl_2d.min(), vmax=infl_2d.max())
    colors = cm.Blues(norm(infl_2d[:, trim_at_outlet:]))
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

    ax.plot_surface(xc, yc, topo, facecolors=colors,
                    rstride=1, cstride=1, linewidth=0,
                    antialiased=False, shade=False)

    ax.plot_surface(xc, yc, topo * 0, facecolors=veg_colors,
                    rstride=1, cstride=1,
                    linewidth=0, antialiased=True, shade=False,
                    alpha=0.8)

    ax.view_init(25, 295)

    return fig
Beispiel #14
0
    def __init__(self,data_pred,data_gt,colors,img,types,gif_name = "test.gif", plot_ = False, save = True):

        self.img = img
        self.xs_pred = data_pred[:,:,0]
        self.ys_pred = data_pred[:,:,1]

        self.xs_gt = data_gt[:,:,0]
        self.ys_gt = data_gt[:,:,1]

        self.types = types 


        self.nb_agents = self.xs_pred.shape[0]
        self.margin = 1

        self.nb_frames = self.xs_pred.shape[1]
        self.gif_name = gif_name
        self.plot_ = plot_
        self.save = save

        self.fps = 1
        self.colors = colors

        self.lin_size = 100

        lin = np.linspace(0.6, 0.8, self.lin_size)
 
        self.color_dict = {
            "bicycle":cm.Blues(lin),
            "pedestrian":cm.Reds(lin),
            "car":cm.Greens(lin),
            "skate":cm.Greys(lin),
            "cart":cm.Purples(lin),
            "bus":cm.Oranges(lin)
        }

        self.colors = [self.color_dict[type_][np.random.randint(self.lin_size)] for type_ in self.types]

        self.history = 4

        self.get_plots()
def plot_3D_veg(sim): 
    """
    3D plot of the vegetation field
    """
    fig = plt.figure( figsize = (15, 7))
    ax = fig.add_subplot(111, projection='3d')

    # Get rid of colored axes planes
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False
    ax.xaxis.pane.set_edgecolor('w')
    ax.yaxis.pane.set_edgecolor('w')
    ax.zaxis.pane.set_edgecolor('w')
    ax.set_xticks([], []);
    ax.set_zticks([], []);
    ax.set_yticks([], []);
    # plt.axis('off')
    ax.grid(False)

    isvegc = sim.isvegc
    dx = sim.dx
    ncol = isvegc.shape[0]
    nrow = isvegc.shape[1]
    xc = np.arange(0, ncol*dx, dx)  + dx/2
    yc = np.arange(0, nrow*dx, dx)  + dx/2
    xc, yc = np.meshgrid(xc, yc)

    xc = xc.T
    yc = yc.T

    #Plot the surface with face colors taken from the array we made.
    norm = plt.Normalize()
    colors = cm.Greens(norm(sim.isvegc ))
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))

    im = ax.scatter(xc[ sim.isvegc == 1], yc[ sim.isvegc == 1],
            yc[ sim.isvegc == 1], c = 'g',  marker='o',  s = 20, alpha =1)

    ax.view_init(20, 195)
Beispiel #16
0
        geojson['properties']['category_distrib'] = list(cat_distr)
        geojson['properties']['category_more'] = list(cat_distinct)
        geojson['properties']['time_distrib'] = list(timeofday_distr)
        geojson['properties']['time_more'] = list(timeofday_distinct)
        geojson['properties']['days_distrib'] = list(dayofweek_distr)
        geojson['properties']['days_more'] = list(dayofweek_distinct)
        geojson['properties']['weight'] = float(theta)
        neighborhoods.append(geojson)

    neighborhoods.sort(key=lambda x: x['properties']['weight'], reverse=True)
    a = pretty_floats({"type": "FeatureCollection", "features": neighborhoods})

    cat_colors = [
        cmlib.Oranges(x) for x in np.linspace(0, 1, len(main_cats_plot))
    ]
    time_colors = [cmlib.Greens(x) for x in np.linspace(0, 1, len(timeOfDay))]
    day_colors = [cmlib.Purples(x) for x in np.linspace(0, 1, len(dayOfWeek))]

    # select top regions based on volume
    MAX_REGIONS = args.max_regions
    results = sorted(enumerate(a['features']),
                     key=lambda x: x[1]['properties']['weight'],
                     reverse=True)[:MAX_REGIONS]

    with zipfile.ZipFile(city + '.zip', 'w') as myzip:
        for region_id, res in results:
            stats = res['properties']

            fig, ax = plt.subplots(1, 4, figsize=(21, 6))
            fig.suptitle("{} - Weight: {}%".format(stats['name'],
                                                   int(100 * stats['weight'])),
# rest
for sym in res.iloc[n_top:-n_top].index:
    plot_dat = dat[dat.index == sym].sort_values('date')
    y = plot_dat.close / plot_dat.open[0]  # normalise to 1
    ax.plot(plot_dat.date, y, markersize=0, marker='o',
            linewidth=1, color=(0, 0, 0, .1))

# top
for i, sym in enumerate(res.iloc[:n_top].index):
    plot_dat = dat[dat.index == sym].sort_values('date')
    y = plot_dat.close / plot_dat.open[0]  # normalise to 1

    intensity = (.5 - .5/n_top * i) + .5
    ax.plot(plot_dat.date, y, markersize=2, marker='o',
            label=sym, linewidth=1, color=cm.Greens(intensity))


# flop
for i, sym in enumerate(res.iloc[-n_top:].index):
    plot_dat = dat[dat.index == sym].sort_values('date')
    y = plot_dat.close / plot_dat.open[0]  # normalise to 1

    intensity = .5/n_top * i + .5
    ax.plot(plot_dat.date, y, markersize=2, marker='o',
            label=sym, linewidth=1, color=cm.Reds(intensity))
ax.legend(loc='upper left')
ax.tick_params(rotation=-20)

fig.show()
    # plt.xlabel("Frequency (in fs$^{-1}$)")

    P_f = ensemble.pol2_freq_matrix
    P_c = ensemble.pol2_comb_matrix
    CB = ensemble.freq2comb_basis
    P_f /= P_f.max()
    P_c /= P_c.max()
    CB /= CB.max()
    Q_f, R_f = np.linalg.qr(P_f, mode='complete')

    def gaussian(x, x_0, sigma):
        return (1. / (sigma * np.sqrt(np.pi))) * np.exp(-(x - x_0)**2 /
                                                        (2 * sigma**2))

    colors1 = cm.Reds(np.linspace(0.5, 1, 3))
    colors2 = cm.Greens(np.linspace(0.5, 1, 3))
    colors3 = cm.Blues(np.linspace(0.5, 1, 3))
    f, ax = plt.subplots(2, 3, sharex=True)
    f.suptitle(
        "$3^{rd}$ order non-linear polarization $P^{(3)}(\\omega)$ and corresponding \n heterodyne fields $E^{het}(\\omega)$ for 3 near-identical atomic systems"
    )
    for i in range(ensemble.N_molecules):
        Q_c, R_c = np.linalg.qr(np.delete(P_c, i, 1), mode='complete')
        het_fields = Q_c[:, ensemble.N_molecules:]
        print(het_fields.shape)
        ax[0, i].plot(ensemble.frequency,
                      CB.dot(P_c[:, i]).real,
                      color=colors1[i])
        ax[0, i].set_ylim(-0.025, 1)
        # ax[1, i].plot(ensemble.frequency, CB.dot(P_c[:, i]).imag, color=colors2[i])
        G = gaussian(np.linspace(0., 1., het_fields.shape[1]), 0.5, .05)
Beispiel #19
0
import numpy as np
from numpy.random import binomial
from scipy.stats import multivariate_normal, norm
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import math
import os
import errno
import seaborn as sns
from matplotlib.colors import ListedColormap
from mpl_toolkits.mplot3d import Axes3D

blue_cmap = ListedColormap(cm.Blues(np.linspace(0, 1, 20))[10:, :-1])
oran_cmap = ListedColormap(cm.Oranges(np.linspace(0, 1, 20))[10:, :-1])
green_cmap = ListedColormap(cm.Greens(np.linspace(0, 1, 20))[10:, :-1])


def setup_plotting():
    """This function sets up Latex-like fonts, font sizes and other
    parameter to make plots look prettier."""
    sns.set_style('darkgrid')
    plt.rcParams['mathtext.fontset'] = 'stix'
    plt.rcParams['font.family'] = 'STIXGeneral'
    plt.rcParams['font.size'] = 14
    plt.rcParams['figure.figsize'] = (12, 6)
    plt.rc("savefig", dpi=300)
    plt.rc('figure', titlesize=16)


def mkdir_p(path):
    """Creates a directory in the specified path."""
Beispiel #20
0
def projection_figure(D,fortalk=False):
    start = cdtime.comptime(1975,8,1)
    trends = cmip5.get_linear_trends(D.ALL.obs(time=(start,'2005-12-31')))
    if fortalk:
        plt.figure()
    else:
        plt.subplot(211)
    m=b.landplot(trends,vmin=-2,vmax=2)
    m.drawcoastlines(color="gray")
    plt.colorbar(orientation='horizontal',label="Trend (PDSI/decade)")
    plt.title("(a): 1975-2005 GDA trends")
    if fortalk:
        plt.figure()
    else:
        plt.subplot(212)
    Plotting.Plotting.time_plot(D.ALL.projection(time=('1100-1-1','1850-12-31')),color=cm.Greens(.9),lw=3,label="pre-industrial noise")
    Plotting.Plotting.time_plot(D.ALL.projection(time=('1851-1-1','1974-12-31')),c=cm.Greys(.5),lw=3)
    Plotting.Plotting.time_plot(D.ALL.projection(time=('1975-1-1','2005-12-31')),c=cm.Blues(.8),label="Target period",lw=3)
    plt.xlabel("Year")
    plt.ylabel("Projection")
    plt.title("(b): GDA projection on fingerprint")
    plt.xlim(1400,2010)
    plt.legend()
Beispiel #21
0
no9 = np.loadtxt(sys.argv[21])
no10 = np.loadtxt(sys.argv[22])
no11 = np.loadtxt(sys.argv[23])
no12 = np.loadtxt(sys.argv[24])
"""

where = []
for i in range(len(ts1)):
    where = np.append(where, i)
where2 = []
#for i in range(len(ts7)):
#   where2 = np.append(where2, i)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(where, ts1, '-o', color=cm.Greens(0.15), linewidth=5.0)  #0.12
ax.plot(where, ts2, '-o', color=cm.Greens(0.3), linewidth=5.0)  #0.2
ax.plot(where, ts3, '-o', color=cm.Greens(0.45), linewidth=5.0)  #0.28
ax.plot(where, ts4, '-o', color=cm.Greens(0.6), linewidth=5.0)  #0.36
ax.plot(where, ts5, '-o', color=cm.Greens(0.75), linewidth=5.0)  #0.44
ax.plot(where, ts6, '-o', color=cm.Greens(0.9), linewidth=5.0)
"""
ax.plot(where2, ts7, '-o', color=cm.Blues(0.15), linewidth=5.0)
ax.plot(where2, ts8, '-o', color=cm.Blues(0.3), linewidth=5.0)
ax.plot(where2, ts9, '-o', color=cm.Blues(0.45), linewidth=5.0)
ax.plot(where2, ts10, '-o', color=cm.Blues(0.6), linewidth=5.0)
ax.plot(where2, ts11, '-o', color=cm.Blues(0.75), linewidth=5.0)
ax.plot(where2, ts12, '-o', color=cm.Blues(0.9), linewidth=5.0)
"""
"""
ax.plot(where, no1, '-o', color=cm.Reds(0.12), linewidth=5.0)
Beispiel #22
0
            (cnt, nx, ny) = dc.expr_contour2(ipath, name, xborder=0, yborder=0)
            #polygon_list.append(dc.contour2polygon(cnt))
            polygon_list += [dc.contour2polygon(c) for c in cnt]
        else:
            (cnt, nx, ny) = dc.expr_contour(ipath, name, xborder=0, yborder=0)
            #polygon_list.append(dc.contour2polygon(cnt))

        i += 1

    HM = dc.polygon_overlap(polygon_list, nx, ny)

    hm_polyg, color_ids = dc.hm2polygons(HM)

    fig = plt.figure()
    ax = plt.subplot(111)
    clrs = cm.Greens(range(256))
    nd = max(color_ids) + 1
    clrs = dc.downsample_matrix(clrs, int(np.floor(256 / nd)))
    plt.set_cmap(cm.Greens)

    i = 0
    for pg in hm_polyg:
        if not (pg == []):
            p = PolygonPatch(pg,
                             ec=clrs[color_ids[i] - 1, :],
                             fc=clrs[color_ids[i] - 1, :])
            p.set_linewidth(3)
            ax.add_patch(p)
        i += 1

    plt.axis('equal')
Beispiel #23
0
    def set_style_expression_mutation(self, model, cell_line='A375_SKIN'):
        """Sets the fill color of each node based on its expression level
        on the given cell line, and the stroke color based on whether it is
        a mutation.

        Parameters
        ----------
        model: list<indra.statements.Statement>
            A list of INDRA statements
        cell_line: str
            A cell line for which we're interested in protein expression level
        """
        labels = self.label_to_glyph_ids.keys()

        label_to_agent = {}
        for label in labels:
            for statement in model:
                for agent in statement.agent_list():
                    if agent is not None and _n(agent.name) == label:
                        label_to_agent[label] = agent

        agent_to_expression_level = {}
        for agent in label_to_agent.values():
            if 'HGNC' not in agent.db_refs and 'FPLX' not in agent.db_refs:
                # This is not a gene
                agent_to_expression_level[agent] = 0
                continue

            if 'FPLX' not in agent.db_refs:
                gene_names = [agent.name]
            else:
                children = bio_ontology.get_children('FPLX',
                                                     agent.db_refs['FPLX'])
                gene_names = [bio_ontology.get_name(*child) for child
                              in children]

            # Compute mean expression level
            expression_levels = []
            logger.info('Getting expression status of proteins: %s' %
                        str(gene_names))
            l = self.get_expression(gene_names, cell_line)
            for line in l:
                for element in l[line]:
                    level = l[line][element]
                    if level is not None:
                        expression_levels.append(l[line][element])
            if len(expression_levels) == 0:
                mean_level = None
            else:
                mean_level = sum(expression_levels) / len(expression_levels)

            agent_to_expression_level[agent] = mean_level

        # Create a normalized expression score between 0 and 1
        # Compute min and maximum levels
        min_level = None
        max_level = None
        for agent, level in agent_to_expression_level.items():
            if level is None:
                continue
            if min_level is None:
                min_level = level
            if max_level is None:
                max_level = level
            if level < min_level:
                min_level = level
            if level > max_level:
                max_level = level
        # Compute scores
        agent_to_score = {}
        if max_level is not None:
            level_span = max_level - min_level
        for agent, level in agent_to_expression_level.items():
            if level is None or level_span == 0:
                agent_to_score[agent] = 0
            else:
                agent_to_score[agent] = (level - min_level) / level_span

        # Map scores to colors and assign colors to labels
        agent_to_color = {}
        for agent, score in agent_to_score.items():
            if 'HGNC' not in agent.db_refs and 'FPLX' not in agent.db_refs:
                color = cm.Blues(0.3)
                color_str = colors.to_hex(color[:3])
            else:
                # color = cm.plasma(score)
                color = cm.Greens(0.6*score + 0.2)
                color_str = colors.to_hex(color[:3])
            assert(len(color_str) == 7)
            stroke_color = \
                    self._choose_stroke_color_from_mutation_status(agent.name,
                                                                   cell_line)
            self.set_style(agent.name, stroke_color, color_str)
Beispiel #24
0
                         width_ratios=[1, 0.075, 1, 0.075])

ax7 = fig.add_subplot(gspec[0, 0])
xx, yy = SOM_DTLZ2.get_euclidean_coordinates()
umatrix = SOM_DTLZ2.distance_map()
weights = SOM_DTLZ2.get_weights()

for i in range(weights.shape[0]):
    for j in range(weights.shape[1]):

        wy = yy[(i, j)] * 2 / np.sqrt(3) * 3 / 4

        hex = RegularPolygon((xx[(i, j)], wy),
                             numVertices=6,
                             radius=.95 / np.sqrt(3),
                             facecolor=cm.Greens(umatrix[i, j]),
                             alpha=.8,
                             edgecolor='gray')
        ax7.add_patch(hex)
ax7.set_xlim([-1, 14])
ax7.set_ylim([-1, 13])
ax7.set_title('SOM: 4 Obj DTLZ 2')

ax_cb = fig.add_subplot(gspec[0, 1])
cb1 = colorbar.ColorbarBase(ax_cb,
                            cmap=cm.Greens,
                            orientation='vertical',
                            alpha=.4)
cb1.ax.get_yaxis().set_ticks_position('left')
cb1.ax.get_yaxis().set_label_position('left')
cb1.ax.get_yaxis().labelpad = 12
Beispiel #25
0
def periodradius(epos, color='C4', alpha=1):
    gs = gridspec.GridSpec(nrows=9, ncols=3)
    f = plt.figure()
    f.set_size_inches(13, 7)  # default 7, 5
    f.subplots_adjust(wspace=0.5, hspace=0.0)

    ax1 = f.add_subplot(gs[3:6, 0])
    ax2 = f.add_subplot(gs[0:3, 1], sharex=ax1, sharey=ax1)
    ax3 = f.add_subplot(gs[6:9, 1], sharex=ax1, sharey=ax1)
    ax4 = f.add_subplot(gs[3:6, 2], sharex=ax1, sharey=ax1)

    if True:
        #f.suptitle(epos.name)
        f.suptitle(
            "Compare Planet Formation Models to Observed Exoplanets with epos",
            bbox=dict(boxstyle='round', fc='w', ec='k'))
    else:
        words = [
            'Compare', 'Planet Formation Models', 'to', 'Observed Exoplanets',
            'with', 'epos'
        ]
        colors = ['C0', color, '0.5', 'C3', '0.5', 'C2']

        helpers.rainbow_text(0.1, 0.95, words, colors, size=20, f=f, fudge=1.5)
        #helpers.rainbow_text(0.05, 1.1, words, colors, size=18, ax=axes[0,0])
    ''' Left: model '''
    ax = ax1
    helpers.set_axes(ax, epos, Trim=True)
    ax.set_xlabel('')

    ax.set_title('Formation Model: {}'.format(epos.name))
    pfm = epos.pfm
    ax.plot(pfm['P'],
            pfm['R'],
            ls='',
            marker='.',
            ms=5.0,
            color=color,
            alpha=alpha)
    ''' Top middle: synthetic obs'''
    ax = ax2
    ax.set_title('Simulated Observations')
    if epos.MonteCarlo:
        sim = epos.synthetic_survey
        ax.plot(sim['P'],
                sim['Y'],
                ls='',
                marker='.',
                mew=0,
                ms=5.0,
                color='C2',
                alpha=0.5)
    else:
        levels = np.linspace(0, np.max(sim['pdf']))
        ax.contourf(epos.MC_xvar,
                    epos.MC_yvar,
                    sim['pdf'].T,
                    cmap='Greens',
                    levels=levels)
    ''' Bottom middle: occurrnce rates'''
    ax = ax3
    ax.set_title('Occurrence Rates')
    ax.set_xlabel('Orbital Period [days]')

    occbin = epos.occurrence['bin']
    maxocc = np.max(occbin['occ'])
    for k, (xbin, ybin, n, inbin, occ) in enumerate(
            zip(occbin['x'], occbin['y'], occbin['n'], occbin['i'],
                occbin['occ'])):

        # box
        ax.add_patch(
            patches.Rectangle((xbin[0], ybin[0]),
                              xbin[1] - xbin[0],
                              ybin[1] - ybin[0],
                              fill=True,
                              ls='-',
                              fc=cm.Greens(occ / maxocc)))

        #xnudge=1.01
        #ynudge=1.02
        #ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top',
        #	size=8)

    # colored dots
    #ax.plot(epos.obs_xvar, epos.obs_yvar,
    #	ls='', marker='.', mew=0, ms=2.0, color='k')
    ''' right: observations '''
    ax = ax4
    ax.set_title('Observed Planets')
    ax.plot(epos.obs_xvar,
            epos.obs_yvar,
            ls='',
            marker='.',
            mew=0,
            ms=5.0,
            color='C3')
    ''' 
	Draw horizontal bars
	'''
    xl = 0.07
    xw, dy = 0.85, 0.08
    yb, yt = 0.22, 0.75
    props = dict(transform=f.transFigure, alpha=0.3, zorder=-10)
    bar_fw = patches.Rectangle((xl, yt - dy), xw, 2 * dy, color='C1', **props)
    bar_occ = patches.Rectangle((xl, yb - dy), xw, 2 * dy, color='C6', **props)

    bbox = dict(boxstyle='round', fc='w', ec='k')
    props = dict(rotation=0,
                 ha='left',
                 va='center',
                 transform=f.transFigure,
                 bbox=bbox)

    f.patches.extend([bar_fw, bar_occ])
    f.text(xl - 0.03, yt, 'Forward Model', color='k', **props)
    f.text(xl - 0.03, yb, 'Inverse Model', color='k', **props)
    ''' Draw arrows between plots'''
    props = dict(transform=f.transFigure,
                 arrowstyle='simple',
                 connectionstyle='arc3,rad=-0.3',
                 alpha=0.3,
                 fc='g',
                 mutation_scale=50.)
    xl, xr = 0.3, 0.62
    yt, yb = 0.7, 0.2
    xw, yw = 0.1, 0.1
    arrow1 = patches.FancyArrowPatch((xl, yt), (xl + xw, yt + yw), **props)
    arrow2 = patches.FancyArrowPatch((xr + xw, yb + yw), (xr, yb), **props)

    f.text(xl - 0.05,
           yt + 0.06,
           'Apply Survey\nDetection Bias',
           color='g',
           ha='center',
           va='center',
           transform=f.transFigure)
    f.text(xr + xw + 0.07,
           yb,
           'Account for\nSurvey Completeness',
           color='g',
           ha='center',
           va='center',
           transform=f.transFigure)

    # and top-bottom
    props['connectionstyle'] = 'arc3,rad=0.0'
    props['mutation_scale'] = 30.
    props['fc'] = 'b'
    #props['shape']= 'full'
    #props['arrowstyle']='darrow'

    xl, xr = 0.33, 0.63
    yt, yb = 0.7, 0.25

    xw, yw = 0.005, 0.01
    dy = 0.04
    xs, ys = 0.05, 0.03

    arrow3 = patches.FancyArrowPatch((xl - xw, yb + dy),
                                     (xl - xw + xs, yb - dy), **props)
    arrow4 = patches.FancyArrowPatch((xl + xw + xs, yb - dy + ys),
                                     (xl + xw, yb + dy + ys), **props)
    #for x,y in zip([xl-0.04, xr+xs+0.04],[yb-dy,yt+dy]):
    #	f.text(x,y,'Compare',color='b',
    #		ha='center', va='center', transform=f.transFigure)
    f.text(xr + xs + 0.1,
           yt + dy,
           'Compare Distribution\nof Detections',
           color='b',
           ha='center',
           va='center',
           transform=f.transFigure)

    f.text(xl - 0.07,
           yb - dy,
           'Compare Intrinsic\n Planet Population',
           color='b',
           ha='center',
           va='center',
           transform=f.transFigure)

    arrow5 = patches.FancyArrowPatch((xr - xw, yt + dy),
                                     (xr - xw + xs, yt - dy), **props)
    arrow6 = patches.FancyArrowPatch((xr + xw + xs, yt - dy + ys),
                                     (xr + xw, yt + dy + ys), **props)

    f.patches.extend([arrow1, arrow2, arrow3, arrow4, arrow5, arrow6])
    ''' Draw crossed out arrow '''
    props['mutation_scale'] = 50.
    props['fc'] = 'w'
    props['zorder'] = -1
    xc, yc = 0.5, 0.5
    xw = 0.15
    if False:
        arrow_left = patches.FancyArrowPatch((xc, yc), (xc - xw, yc), **props)
        arrow_right = patches.FancyArrowPatch((xc, yc), (xc + xw, yc), **props)
    else:
        yw = 0.02
        arrow_left = patches.FancyArrowPatch((xc + xw - 0.01, yc + yw),
                                             (xc - xw, yc + yw), **props)
        arrow_right = patches.FancyArrowPatch((xc - xw + 0.01, yc - yw),
                                              (xc + xw, yc - yw), **props)

    f.patches.extend([arrow_left, arrow_right])

    dx, dy = 0.05, 0.05
    redcross = plt.scatter(xc,
                           yc,
                           s=2000,
                           c='red',
                           transform=f.transFigure,
                           marker='x',
                           lw=7,
                           clip_on=False)
    ax.add_artist(redcross)

    #f.tight_layout()
    helpers.save(plt, epos.plotdir + 'workflow/arrows')
Beispiel #26
0
hist_data = train_data_10users['start_hour']
s = sns.countplot(hist_data, color='darkgreen', saturation=1, zorder=2)
s.set_xlabel('Час начала сессии')
s.set_ylabel('Количество сессий')
plt.grid(True, alpha=.2, zorder=0, axis='y')
plt.title('Распределение времени начала сессий')
plt.savefig('figs/start_hour_overall.pdf')

# **5. Постройте гистограммы распределения часа начала сессии (*start_hour*) для каждого из 10 пользователей по отдельности. Используйте *subplots*, чтоб разместить все 10 картинок на одной большой. Пометьте легендой каждую картинку, на легенде должно быть написано имя пользователя. Для каждого пользователя раскрасьте гистограмму его/ее цветом (*color_dic*). Подпишите оси по-русски в каждой из 10 гистограмм.**

# In[23]:

import matplotlib.cm as cm

fig, ax = plt.subplots(nrows=3, ncols=4, figsize=(16, 10))
colors = cm.Greens(np.linspace(0, 1, 12))
for idx, (user, sub_df) in enumerate(pd.groupby(train_data_10users,
                                                'user_id')):
    s = sns.countplot(sub_df.start_hour,
                      color=color_dict[user],
                      saturation=.4,
                      ax=ax[idx // 4, idx % 4],
                      label=user,
                      zorder=2)
    ax[idx // 4, idx % 4].grid(True, alpha=.2, zorder=0, axis='y')
    s.set_xlabel('Час начала сессии')
    s.set_ylabel('Количество сессий')
    s.legend()

suptitle = fig.suptitle(
    'Распределение времени старта сессии для всех пользователей',
Beispiel #27
0
            np.asarray(m_PCE) < i + 0.5,
            np.asarray(m_PCE) > i - 0.5))
    p_PCE_bin.append(sum(p_PCE_array[indexmask]))
    indexmask = np.where(
        np.logical_and(
            np.asarray(m_TCE) < i + 0.5,
            np.asarray(m_TCE) > i - 0.5))
    p_TCE_bin.append(sum(p_TCE_array[indexmask]))
    indexmask = np.where(
        np.logical_and(
            np.asarray(m_DCE) < i + 0.5,
            np.asarray(m_DCE) > i - 0.5))
    p_DCE_bin.append(sum(p_DCE_array[indexmask]))
fig1 = plt.figure(figsize=(10, 4))
plt.bar(m_bin, p_PCE_bin, color=cm.Reds(255))
plt.bar(m_bin, p_TCE_bin, color=cm.Greens(255))
plt.bar(m_bin, p_DCE_bin, color=cm.Blues(255))
plt.xlabel('mass (amu)')
plt.ylabel('proportion')
plt.figtext(0.2, 0.90, "cDCE", fontsize='large', color=cm.Blues(255))
plt.figtext(0.5, 0.90, "TCE", fontsize='large', color=cm.Greens(255))
plt.figtext(0.8, 0.90, "PCE", fontsize='large', color=cm.Reds(255))
#plt.figtext(0.28, 0.50, "$p_{^1H}=0.999885$\n$p_{^2H}=0.000115$\n$p_{^{12}C}=0.9893$\n$p_{^{13}C}=0.0107$\n$p_{^{35}Cl}=0.7576$\n$p_{^{37}Cl}=0.2424$", fontsize='large', color='k')
plt.yscale('log')
plt.ylim([1E-6, 1])
plt.show()

filename1 = 'Isotopologue_distributions.xlsx'
xlsxin = pd.ExcelFile(filename1)
datain = {}
for j in xlsxin.sheet_names:
Beispiel #28
0
import pandas as pd
import numpy as np

GDP = pd.read_excel('GDP.xlsx')
GDP = GDP.drop(index=0)
GDP = GDP[::-1]

topuni = pd.read_excel('topuni.xlsx')
topuni = topuni.drop(index=0)
topuni = topuni[::-1]

gdp = GDP['GDP'].tolist()
uni = topuni['Number of Top 100 Universities'].tolist()
diff = [abs(i - 1000000 * j) for i in gdp for j in uni]
color = [
    cm.Greens(abs(x)) if x >= np.mean(diff) else cm.Reds(abs(x)) for x in diff
]

plt.figure(1, figsize=(12, 12))

linegraph = plt.plot(GDP['Provinces'], GDP['GDP'], '-o')
bargraph = plt.bar(topuni['Provinces'],
                   height=topuni['Number of Top 100 Universities'] * 1000000,
                   color=color,
                   alpha=0.5)

for bar in bargraph:
    height = bar.get_height()
    plt.gca().text(bar.get_x() + bar.get_width() / 2,
                   bar.get_height() * 0.8,
                   str(int(height) / 1000000),
def Solution_Discovery_Distance_Lines_n1():
    print('Building Line Charts.')
    #### selecting data for node n1 of Solution 01
    desired_idx = List_of_nodes.index("n1")
    Sol01_TimeStamp = Sol01_Prdsvg_df_list[desired_idx]['TimeStamp'].copy()

    ## n1 distance to neighbors.
    ## I have twenty nodes, but i'm using only the distance to the moving ones (n*)
    Sol01_OthersDist = {}
    Sol01_DistHighlight = {}
    for node in List_of_moving_nodes:
        if node != 'n1':
            column_name = 'Distance_' + node
            #Sol01_OthersDist[node] = Sol01_Prdsvg_df_list[desired_idx][column_name].apply(Till_250)
            Sol01_OthersDist[node] = Sol01_Prdsvg_df_list[desired_idx][
                column_name]
            ## Taking distance values only where there is neighborhood relation
            tmp_df = Sol01_Prdsvg_df_list[desired_idx][[
                'TimeStamp', 'List of Neighbors', column_name
            ]]
            ## some lines have 'nan' as value which makes str.contains impossible
            tmp_df['List of Neighbors'].fillna('-', inplace=True)
            Sol01_DistHighlight[node] = tmp_df[
                tmp_df['List of Neighbors'].str.contains(node)]
        pass
    pass

    ## ******************************************************************** ##
    Sol02_TimeStamp = Sol02_Prdsvg_df_list[desired_idx]['TimeStamp'].copy()

    ## Plotting distance to nodes.
    Sol02_OthersDist = {}
    Sol02_DistHighlight = {}
    for node in List_of_moving_nodes:
        if node != 'n1':
            column_name = 'Distance_' + node
            Sol02_OthersDist[node] = Sol02_Prdsvg_df_list[desired_idx][
                column_name]
            #print (node, Sol02_OthersDist[node])
            ## Taking distance values only where there is neighborhood relation and saving in a
            # second dataframe to highlight the neighborhood relation
            tmp_df = Sol02_Prdsvg_df_list[desired_idx][[
                'TimeStamp', 'List of Neighbors', column_name
            ]]
            tmp_df['List of Neighbors'].fillna('-', inplace=True)
            Sol02_DistHighlight[node] = tmp_df[
                tmp_df['List of Neighbors'].str.contains(node)]
            #print (node, Sol02_DistHighlight[node])
            #quit()
        pass
    pass

    # Two subplots sharing x axis
    f, (ax1, ax2) = plt.subplots(2)
    title = f.suptitle(
        "Bertrand Trace - AND vs ETSI Distance of Discovery - Node n1 - 10km/h - 15% of loss",
        fontsize=20)
    f.set_size_inches(23, 10, forward=True)
    #title.set_y(0.98)

    ###### Node n1 - Solution 01 ###
    ax1.set_title("AND", fontsize=18)
    # building two diff y axes for plotting Delay and Distance

    ## Plotting Distance lines. Distances from n1 to n2, n3 and n4
    # In case of too many nodes, dropping some of them to not polute too much the chart
    node_neighbors = copy.copy(List_of_moving_nodes)
    for idx, node in enumerate(node_neighbors):
        #print (idx, node)
        if node != 'n1':
            label = 'Distance to ' + node
            color = cm.Greens((idx + 1) * 75)
            ## distance line
            line = Sol01_OthersDist[node]
            Dist_line = ax1.plot(Sol01_TimeStamp / 1000000,
                                 line,
                                 c=color,
                                 lw=2,
                                 ls='--',
                                 label=label)
            ## highlighting neighborhood characteristic
            # taking one of twenty elements in all array (diminishing the number of nodes)
            Node_df = Sol01_DistHighlight[node]
            xvalues = Node_df['TimeStamp']
            column_name = 'Distance_' + node
            highlight_line = Node_df[column_name]
            ax1.plot(xvalues / 1000000,
                     highlight_line,
                     c=color,
                     ls='none',
                     marker='o',
                     markersize=6,
                     label='neighborhood')
        pass
    pass

    ## Reference line of communication range (200 meters)
    ax1.axhline(y=200,
                xmin=0,
                xmax=25,
                c="blue",
                linewidth=2,
                zorder=0,
                label='Comm. Range')
    ## Safety line (equals the distance travelled in 2 seconds)
    speed1 = 30  # speed in km/h (one vehicle)
    speed2 = 30  # speed in km/h (another vehicle)
    # computing the safety line (sl) considering two vehicles.
    # transform in meters per second and multiply by 2 seconds
    sl = ((speed1 + speed2) / 3.6) * 2
    ## Plotting
    ax1.axhline(y=sl,
                xmin=0,
                xmax=25,
                c="red",
                linewidth=2,
                zorder=0,
                label='Safety Distance')

    # formating y axis to show Distance between nodes variation
    #ax_Sol01[1].set_ylabel('Distances to other nodes (m)', color='g', fontsize=16)
    #ax1.yaxis.set_ticks(np.arange(0, 250, 20))
    #ax1.set_ylim(0, 250)
    ###### Arranging X axis for the second chart ####
    #start, end = ax2.get_xlim()
    #ax1.xaxis.set_ticks(np.arange(30, 101, 2))
    #ax1.set_xlim(30,100)

    ###### Solution 02  ###
    ax2.set_title("ETSI", fontsize=18)

    ## Plotting Distance lines. Distances from v1 to v2, v3 and v4
    # In case of too many nodes, dropping some of them to not polute too much the chart
    node_neighbors = copy.copy(List_of_moving_nodes)
    for idx, node in enumerate(node_neighbors):
        if node != 'n1':
            label = 'Distance to ' + node
            color = cm.Greens((idx + 1) * 75)
            line = Sol02_OthersDist[node]
            Dist_line = ax2.plot(Sol02_TimeStamp / 1000000,
                                 line,
                                 c=color,
                                 lw=2,
                                 ls='--',
                                 label=label)
            ## highlighting neighborhood characteristic
            # taking one of twenty elements in all array (diminishing the number of nodes)
            Node_df = Sol02_DistHighlight[node]
            xvalues = Node_df['TimeStamp']
            column_name = 'Distance_' + node
            highlight_line = Node_df[column_name]
            ax2.plot(xvalues / 1000000,
                     highlight_line,
                     c=color,
                     ls='none',
                     marker='o',
                     markersize=6,
                     label='neighborhood')
        pass
    pass

    ## Reference line of communication range (200 meters)
    ax2.axhline(y=200,
                xmin=0,
                xmax=25,
                c="blue",
                linewidth=2,
                zorder=0,
                label='Comm. Range')
    ## Safety line (equals the distance travelled in 2 seconds)
    ax2.axhline(y=sl,
                xmin=0,
                xmax=25,
                c="red",
                linewidth=2,
                zorder=0,
                label='Safety Distance')

    # formating y axis to show Distance between nodes variation
    ax2.set_ylabel('Distances to other nodes (m)', fontsize=16)
    #ax2.yaxis.set_ticks(np.arange(0, 250, 20))
    #ax2.set_ylim(0, 250)

    ###### Arranging X axis for the second chart ####
    #start, end = ax2.get_xlim()
    #ax2.xaxis.set_ticks(np.arange(30, 101, 2))
    ax2.set_xlabel('Time', fontsize=17)
    #ax2.xaxis.set_label_coords(0.98, -0.05)
    #ax2.set_xlim(30,100)

    ax1.grid(True)
    ax2.grid(True)

    #### legends ##
    ## Eliminate some lines (legend is too big). First chart.
    chart1_handles, chart1_labels = ax1.get_legend_handles_labels()
    ## cropping undesired legends
    chart1_handle_list, chart1_label_list = [], []
    for handle, label in zip(chart1_handles, chart1_labels):
        #print label
        if "neighborhood" not in label:
            chart1_handle_list.append(handle)
            chart1_label_list.append(label)
        pass
    pass
    ax1.legend(chart1_handle_list,
               chart1_label_list,
               loc='lower left',
               fontsize=12)

    ## Eliminate some lines (legend is too big). Second chart.
    chart2_handles, chart2_labels = ax2.get_legend_handles_labels()
    ## cropping undesired legends
    chart2_handle_list, chart2_label_list = [], []
    for handle, label in zip(chart2_handles, chart2_labels):
        #print label
        if "neighborhood" not in label:
            chart2_handle_list.append(handle)
            chart2_label_list.append(label)
        pass
    pass
    ax2.legend(chart2_handle_list,
               chart2_label_list,
               loc='lower left',
               fontsize=12)

    ## Adding a second legend
    #legend2 =

    return
Beispiel #30
0
def first_last_decade(X, i):
    months = [
        "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
        "NOV", "DEC"
    ]
    WEST_ensemble = X.ensembles["west"]
    EAST_ensemble = X.ensembles["east"]
    DIFF_ensemble = WEST_ensemble - EAST_ensemble
    #models=np.unique([x.split("-")[0] for x in cmip5.models(WEST_ensemble)])
    plt.subplot(131)
    first_west = MV.average(WEST_ensemble[:, :10], axis=1)
    last_west = MV.average(WEST_ensemble[:, -10:], axis=1)
    x = np.arange(12)
    if i != "mma":
        plt.plot(x,
                 first_west[i].asma(),
                 color=cm.Reds(.5),
                 label="W (first decade)")
        plt.plot(x,
                 last_west[i].asma(),
                 color=cm.Reds(.9),
                 label="W (last decade)")
    else:
        plt.plot(x,
                 MV.average(first_west, axis=0).asma(),
                 color=cm.Reds(.5),
                 label="W (first decade)")
        plt.plot(x,
                 MV.average(last_west, axis=0).asma(),
                 color=cm.Reds(.9),
                 label="W (last decade)")
    plt.legend()
    plt.title("WEST")
    plt.xticks(np.arange(12), months)

    plt.subplot(132)
    first_east = MV.average(EAST_ensemble[:, :10], axis=1)
    last_east = MV.average(EAST_ensemble[:, -10:], axis=1)
    x = np.arange(12)
    if i != "mma":
        plt.plot(x,
                 first_east[i].asma(),
                 color=cm.Blues(.5),
                 label="CE (first decade)")
        plt.plot(x,
                 last_east[i].asma(),
                 color=cm.Blues(.9),
                 label="CE (last decade)")
    else:
        plt.plot(x,
                 MV.average(first_east, axis=0).asma(),
                 color=cm.Blues(.5),
                 label="CE (first decade)")
        plt.plot(x,
                 MV.average(last_east, axis=0).asma(),
                 color=cm.Blues(.9),
                 label="CE (last decade)")
    plt.title("EAST")
    plt.xticks(np.arange(12), months)
    plt.legend()
    fig = plt.gcf()
    if i != "mma":
        fig.suptitle(cmip5.models(WEST_ensemble)[i])
    else:
        fig.suptitle("MMA")
    plt.subplot(133)
    first_diff = MV.average(DIFF_ensemble[:, :10], axis=1)
    last_diff = MV.average(DIFF_ensemble[:, -10:], axis=1)
    x = np.arange(12)
    if i != "mma":
        plt.plot(x,
                 first_diff[i].asma(),
                 color=cm.Greens(.5),
                 label="W-CE (first decade)")
        plt.plot(x,
                 last_diff[i].asma(),
                 color=cm.Greens(.9),
                 label="W-CE (last decade)")
    else:
        plt.plot(x,
                 MV.average(first_diff, axis=0).asma(),
                 color=cm.Greens(.5),
                 label="W-CE (first decade)")
        plt.plot(x,
                 MV.average(last_diff, axis=0).asma(),
                 color=cm.Greens(.9),
                 label="W-CE (last decade)")
    plt.legend()
    plt.axhline(0, c='k', ls=":")
    plt.title("DIFF")
    plt.xticks(np.arange(12), months)