Example #1
0
def plt_2_trajectories(data,
                       labels,
                       xyt,
                       savepath,
                       usemeans=True,
                       mid=0,
                       plttype='scatter',
                       **kwargs):
    plt.figure(figsize=(30, 10))
    vals = {}
    assert len(data) == len(labels)
    ylims = kwargs.pop('ylims', (0, 1))
    if usemeans:
        means = [np.mean(line) for line in data]
    else:
        means = [mid] * len(data)
    vals['up'] = [
        np.array([x for x in line if x >= means[i]])
        for i, line in enumerate(data)
    ]
    vals['down'] = [
        np.array([x for x in line if x < means[i]])
        for i, line in enumerate(data)
    ]
    cols = {'up': 'green', 'down': 'red'}
    plt.plot(range(len(labels)), means, lw=4, c=cm.Oranges(0.8))
    plt.axhline(y=mid, c=cm.Greys(0.8), alpha=0.7)
    for x in range(0, len(means), 12):
        plt.axvline(x=x, c=cm.Greys(0.8), alpha=0.7, lw=1.5)
    if 'scatter' in plttype:
        for k, v in vals.items():
            ys = [y for line in v for y in line]
            xs = [xval for xval, line in enumerate(v) for y in line]
            plt.scatter(xs, ys, alpha=0.25, c=cols[k], label=k)
    if 'mean' in plttype:
        for k, v in vals.items():
            ys = [np.mean(line) for line in v]
            xs = range(len(v))
            plt.plot(xs, ys, alpha=0.8, lw=2, c=cols[k], label=k)
    if 'box' in plttype:
        for k, v in vals.items():
            plt.boxplot(v, positions=range(len(data)), boxprops={'c': cols[k]})
    plt.legend()
    plt.xlabel(xyt[0], fontsize=20)
    plt.xticks(ticks=range(len(v)),
               labels=labels,
               rotation=45,
               fontsize=10,
               ha='center')
    plt.ylabel(xyt[1], fontsize=20)
    plt.title(xyt[2], fontsize=24)
    plt.ylim(*ylims)
    plt.savefig(savepath + '.png', bbox_inches='tight')
    plt.close('all')
Example #2
0
    def __init__(
        self,
        df,
        var1,
        var2,
        classvar,
        nn_range=range(1, 101),
        granularity=50.,
        buffer_denom=15.,
        figsize=(20, 20),
        dotsize=70,
        point_colors=cm.Greys(
            [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),
        #point_colors=sns.xkcd_palette(['windows blue', 'amber']),
        mesh_colors=cm.jet([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,
                            0.9])):
        #mesh_colors=['#8FCCFF', '#FFED79']):

        self.df = df
        self.var1 = var1
        self.var2 = var2
        self.classvar = classvar
        self.nn_range = nn_range
        self.granularity = granularity
        self.buffer_denom = buffer_denom
        self.figsize = figsize
        self.dotsize = dotsize
        self.point_colors = point_colors
        self.mesh_colors = mesh_colors
Example #3
0
    def __init__(self, values=None, limits=None, zero_point=0):
        normal_map = cm.viridis(np.linspace(0, 1, 256))
        zero_map = cm.Greys(np.linspace(0, 0.01, 256))
        all_colors = np.vstack((zero_map, normal_map))
        self.cmap = colors.LinearSegmentedColormap.from_list(
            "special_zero", all_colors)

        self.zero_point = zero_point
        if values is not None:
            self.vmin = np.min(values)
            self.vmax = np.max(values)
        elif limits:
            self.vmin, self.vmax = limits
        else:
            raise ValueError(
                "colormap_special_zero needs either `values` or `limits`")
        if self.vmin == 0:
            self.vmin = -self.vmax * 0.05
        if zero_point == 0:
            zero_point = min(0.01 * self.vmax, 0.1)

        if zero_point <= self.vmin:  # white colormap isn't needed
            self.norm = None
            self.cmap = cm.viridis
        else:
            self.norm = colors.DivergingNorm(vmin=self.vmin,
                                             vcenter=zero_point,
                                             vmax=self.vmax)
def plot_points(xarray, yarray):
    # Make array of colors
    colors = cm.Greys(np.linspace(0, 1, len(xarray)))
    # Plot graph
    for i in range(len(xarray)):
        plt.scatter(xarray[i], yarray[i], c=colors[i], s=100)
    plt.show()
Example #5
0
def draw_vapor(init, end):
    for f in td_files[init:end]:
        print(f)
        ##### retrieve variables #####
        dt = netCDF4.Dataset(f)
        t = int(np.array(dt['Time']))
        qc = dt['qc'][0, :len(z), y_prof, xslice]
        #qv = dt['qv'][0, :len(z), y_prof, :]
        qr = dt['qr'][0, :len(z), y_prof, xslice]
        ##### draw qv #####
        #qv = np.ma.masked_array(qv, qv<1e-10)
        #contourf(x, z, qv, levels=50, vmin=0., vmax=0.02, cmap='Blues')
        #colorbar(extend='max')
        ##### draw qc #####
        colors = cm.Greys(
            np.hstack([np.array([0.] * 5),
                       np.linspace(0.5, 0.75, 95)]))
        cmap = LinearSegmentedColormap.from_list('name', colors)
        #cmap.set_bad('white')
        qc = np.ma.masked_array(qc, qc < 0.0)
        contourf(x, z, qc, cmap=cmap, vmin=0, vmax=0.001, levels=100)
        colorbar()
        ##### draw qr #####
        cmap = nclcmap('BrownBlue12')
        colors = cm.Blues(np.linspace(0.5, 1))
        cmap = LinearSegmentedColormap.from_list('name', colors)
        qr = np.ma.masked_array(qr, qr <= 1e-6)  #5e-6)
        contourf(x, z, qr, cmap=cmap, vmin=0., vmax=0.01, alpha=.5, levels=20)
        ##### figure setting #####
        title('Vapor Distribution @ t = ' + str(t) + ' min')
        xlabel('X (m)')
        ylabel('Z (m)')
        savefig('vapor' + f[-9:-3] + '.png', dpi=300)
        clf()
Example #6
0
    def time_of_emergence(self,
                          start_time,
                          times=np.arange(10, 76),
                          noisestart=None,
                          plot=True,
                          solver=None,
                          uncertainty="lines",
                          **kwargs):
        if noisestart is None:
            noisestart = cmip5.start_time(self.obs)
        if not hasattr(self, "P"):
            self.model_projections()
        nmod, nyears = self.get_forced(solver=solver).shape
        self.TOE = MV.zeros((nmod, len(times)))
        for i in range(len(times)):
            L = times[i]
            modslopes, noiseterm = self.sn_at_time(start_time,
                                                   L,
                                                   noisestart=noisestart)
            sns = modslopes / np.std(noiseterm)
            self.TOE[:, i] = sns
        self.TOE.setAxis(0, self.get_forced(solver=solver).getAxis(0))
        if plot:
            endyears = start_time.year + times
            if uncertainty == "lines":
                for ind_model in self.TOE.asma():
                    plt.plot(endyears,
                             ind_model,
                             alpha=.3,
                             color=cm.Greys(.5),
                             lw=1)
            elif uncertainty == "bounds":
                plt.plot(endyears,
                         np.ma.min(self.TOE.asma(), axis=0),
                         linestyle="--",
                         **kwargs)
                plt.plot(endyears,
                         np.ma.max(self.TOE.asma(), axis=0),
                         linestyle="--",
                         **kwargs)

            else:
                plt.fill_between(endyears,
                                 np.ma.min(self.TOE.asma(), axis=0),
                                 np.ma.max(self.TOE.asma(), axis=0),
                                 alpha=.2,
                                 **kwargs)
            plt.plot(endyears,
                     np.ma.average(self.TOE.asma(), axis=0),
                     label=self.name + " model mean signal",
                     **kwargs)
            #plt.fill_between(endyears,np.ma.min(self.TOE.asma(),axis=0),np.ma.max(self.TOE.asma(),axis=0),alpha=.3,**kwargs)

            #plt.axhline(stats.norm.interval(.9)[-1],c="r",lw=3)
            plt.xlabel("Trend end year")
            plt.ylabel("Signal-to-noise ratio")
def make_shadow_cmap() -> colors.ListedColormap:
    shadow_colors = cm.Greys(np.arange(cm.Greys.N))
    mid_idx = int(cm.Greys.N * 0.8)
    shadow_colors[:mid_idx, 3] = 0.0  # avoid shadows at low values
    shadow_colors[mid_idx:, 3] = np.linspace(0.0,
                                             1.0,
                                             num=(cm.Greys.N - mid_idx),
                                             endpoint=True)
    # logger.debug("shadow colors: %s" % shadow_colors[:, 3])

    return colors.ListedColormap(shadow_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)]
Example #9
0
def plot_color(df_tmp, plot_col, item, **kwargs):
    '''
    This plotter will make the polygons if you input
    colors into the plot. The input is a dataframe.
    A minimum of the input numbers, a maximum, the column
    name that is going to be plotted, and a list of items
    that is missing. (Usually these items are colors that
    are not in the dataframe when they are expected to be.
    '''
    missing = []
    df_tmp.reset_index(inplace=True)
    color = df_tmp[plot_col][0]
    # The edgecolor of the polygon.
    if 'edgecolor' in kwargs:
        edgecolor = kwargs['edgecolor']
    else:
        edgecolor = 'black'
    # Check if the color is defined and adjust color if it is not.
    if not isinstance(color, str):
        if np.isnan(color):
            missing.append(item)
            color = cm.Greys(0.3)
    # Define the polygon and add it to the plot.
    if df_tmp['type'].ix[0] == 'MultiPolygon':
        i = 0
        for j in range(len(df_tmp)):
            if (df_tmp['X'].ix[j] == df_tmp['X'].ix[i]) and (
                    df_tmp['Y'].ix[j] == df_tmp['Y'].ix[i]) and (j > i):
                df_tmp2 = df_tmp.ix[range(i, j + 1)]
                i = j + 1
                # Plot the polygons.
                poly = plt.Polygon(df_tmp2[['X', 'Y']],
                                   facecolor=color,
                                   edgecolor=edgecolor,
                                   zorder=0)
                poly.set_linewidth(0.1)
                if 'linewidth' in kwargs:
                    poly.set_linewidth(kwargs['linewidth'])
                plt.gca().add_patch(poly)
    elif df_tmp['type'].ix[0] == 'Polygon':
        # Plot the polygons.
        poly = plt.Polygon(df_tmp[['X', 'Y']],
                           facecolor=color,
                           edgecolor=edgecolor,
                           zorder=0)
        poly.set_linewidth(0.1)
        if 'linewidth' in kwargs:
            poly.set_linewidth(kwargs['linewidth'])
        plt.gca().add_patch(poly)
    return missing
Example #10
0
def plot_roc_auc_profile(dm_df,
                         dmz,
                         accs,
                         num_solvers,
                         title=None,
                         plot_legend=False):
    colors = [
        cm.Set1(0) if x.find('gpc') != -1 else
        (cm.Set1(1) if x.find('xgb') != -1 else
         (cm.Set1(2) if x.find('logit') != -1 else cm.Greys(0.5)))
        for x in dm_df.columns
    ]
    linestyles = [
        '--' if x.find('stacking') != -1 else
        ('-.' if x.find('oncatenation') != -1 else
         ('-' if x.find('major_vote') != -1 else ':')) for x in dm_df.columns
    ]

    plt.figure(figsize=(5, 5))
    for cnt_solver in range(num_solvers):
        if dm_df.columns[cnt_solver].find('ss_mf_gpc') == -1 and dm_df.columns[
                cnt_solver].find('hetmogp') == -1:
            plt.plot(accs,
                     dmz[cnt_solver],
                     label=dm_df.columns[cnt_solver],
                     color=colors[cnt_solver],
                     linestyle=linestyles[cnt_solver])
    if 'ss_mf_gpc:multi-fidelity' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('ss_mf_gpc:multi-fidelity')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='k')
    if 'hetmogp:multi-fidelity' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('hetmogp:multi-fidelity')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='orange')
    if 'GPMA' in dm_df.columns:
        cnt_solver = dm_df.columns.tolist().index('GPMA')
        plt.plot(accs,
                 dmz[cnt_solver],
                 label=dm_df.columns[cnt_solver],
                 color='magenta')
    plt.xlim([0.4, 1])
    if plot_legend:
        plt.legend(loc=2, bbox_to_anchor=(1, 1))
    if title is not None:
        plt.title(title)
Example #11
0
    def plot_scatter(s2pl, scatter=None, top=None, annotate=False, title=None):
        """ Plot a series of scatter points.

        Args:
            s2points: series of points.
        """
        num_series = len(list(s2pl.keys()))
        colors = cm.rainbow(np.linspace(0, 1, num_series))
        marker = itertools.cycle(
            ('o', 'v', '^', '<', '>', 'D', 's', '*', 'x', '+', 'H'))

        for series, points, c in zip(
                list(s2pl.keys())[:top],
                list(s2pl.values())[:top], colors):
            x = [point.perf for point in points]
            y = [point.risk for point in points]
            designs = [point.design for point in points]
            legend = '(' + str(series[0])[:3] + ',' + str(series[1])[:3] + ')'
            plt.plot(x,
                     y,
                     color=cm.Greys(series[0] + series[1]),
                     marker=next(marker),
                     alpha=.5,
                     label=legend)
            if annotate:
                for i in range(len(designs)):
                    plt.annotate(designs[i], (x[i], y[i]), fontsize=8)
                    plt.annotate(series, (x[i], y[i] + .01), fontsize=8)
        if scatter:
            for series, points, c in zip(
                    list(scatter.keys())[:top],
                    list(scatter.values())[:top], colors):
                x = [point.perf for point in points]
                y = [point.risk for point in points]
                designs = [point.design for point in points]
                legend = '(' + str(series[0])[:3] + ',' + str(
                    series[1])[:3] + ')'
                plt.scatter(x, y, color='black', marker='o', alpha=.5)

        plt.xlabel('Normalized Performance', fontsize=20)
        plt.ylabel('Normalized Risk', fontsize=20)
        #plt.xlim([0.8, 1.2])
        #plt.ylim([0, 1.1])
        plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=12)
        if title:
            plt.savefig(title + '.png')
        else:
            plt.show()
        plt.clf()
Example #12
0
def map_val_colors(img, v_min=0.0, v_max=1.0, cmap='hot'):
    fun = {
        'hot':
        lambda t: cm.afmhot(colors.Normalize(vmin=v_min, vmax=v_max)(t),
                            bytes=True),
        'jet':
        lambda t: cm.jet(colors.Normalize(vmin=v_min, vmax=v_max)(t),
                         bytes=True),
        'Greys':
        lambda t: cm.Greys(colors.Normalize(vmin=v_min, vmax=v_max)(t),
                           bytes=True),
        'Blues':
        lambda t: cm.Blues(colors.Normalize(vmin=v_min, vmax=v_max)(t),
                           bytes=True),
    }
    return fun[cmap](img)
Example #13
0
def plot_PC1s(pcs, evs, mean, faxes=None, title=False, ylabel=None):
    if pcs.ndim > 3:
        pcs = pcs.reshape(-1, 3, 40)
        mean = mean.reshape(-1, 40)
        evs = evs.reshape(-1, 3)
    freqs = bands.chang_lab['cfs']
    if faxes is None:
        faxes = plt.subplots(1, 2, figsize=(2.5, 12))
    f, (ax0, ax1) = faxes
    ratios = evs[:, 1:] / evs[:, [0]]
    beta_weights = np.zeros(pcs.shape[0])
    beta_weights = (pcs[:, 0, 14:20]).sum(axis=-1)
    beta_weights -= beta_weights.min()
    beta_weights /= beta_weights.max()
    for ii, pc in enumerate(pcs):
        ax0.plot(freqs, pcs[ii, 0], c=cm.Greys(beta_weights[ii]), alpha=1.)
    ax0.plot(freqs, np.median(pcs[:, 0], axis=0), c='r')
    ax0.axhline(0, 0, 1, c='blue', ls='--')
    ax1.errorbar([0, 1],
                 ratios.mean(axis=0),
                 yerr=ratios.std(axis=0),
                 c='k',
                 ls='none',
                 marker='.')
    ax1.axhline(1, 0, 1, linestyle='--', c='gray')
    pc0s = pcs[:, 0] / np.linalg.norm(pcs[:, 0], axis=1, keepdims=True)
    if mean is not None:
        mean = mean / np.linalg.norm(mean, axis=1, keepdims=True)
        ips = abs(np.sum(pc0s * mean, axis=1))
        ax1.errorbar(2, ips.mean(), yerr=ips.std(), c='k', marker='.')
    #ax0.set_xscale('log')
    if mean is None:
        ax1.set_xticks([0, 1])
        ax1.set_xticklabels([r'$\frac{e_2}{e_1}$', r'$\frac{e_3}{e_1}$'])
        ax1.set_xlim(-1, 2)
    else:
        ax1.set_xticks([0, 1, 2])
        ax1.set_xticklabels(
            [r'$\frac{e_2}{e_1}$', r'$\frac{e_3}{e_1}$', r'$|\mu\cdot PC1|$'])
        ax1.set_xlim(-1, 3)
    ax1.set_ylim(0, 1.1)
    ax1.set_yticks([0, 1])
    if ylabel is not None:
        ax0.set_ylabel(ylabel)
    return
Example #14
0
def gray_to_cm_pil(gray_np, log=False, fftshift=False, cmap='viridis'):

  if log:
    gray_np = 20 * np.log(np.abs(gray_np))

  if fftshift:
    gray_np = np.fft.fftshift(gray_np)

  gray_np_norm = (gray_np - gray_np.min()) / (gray_np.max() - gray_np.min())
  # img_pil = Image.fromarray(np.uint8(cm.gist_earth(gray_np_norm) * 255))

  if cmap == 'viridis':
    img_cmap = cm.viridis(gray_np_norm)
  elif cmap.lower() in ['greys', 'grey', 'gray']:
    img_cmap = cm.Greys(1 - gray_np_norm)

  img_pil = Image.fromarray(np.uint8(img_cmap * 255))
  return img_pil
Example #15
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()
Example #16
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()
Example #17
0
def get_cmaps_biasCNN():
    """ 
  Create color maps
  """

    nsteps = 8
    colors_all_1 = np.moveaxis(
        np.expand_dims(cm.Greys(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_2 = np.moveaxis(
        np.expand_dims(cm.GnBu(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_3 = np.moveaxis(
        np.expand_dims(cm.YlGn(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all_4 = np.moveaxis(
        np.expand_dims(cm.OrRd(np.linspace(0, 1, nsteps)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_all = np.concatenate((colors_all_1[np.arange(2, nsteps, 1), :, :],
                                 colors_all_2[np.arange(2, nsteps, 1), :, :],
                                 colors_all_3[np.arange(2, nsteps, 1), :, :],
                                 colors_all_4[np.arange(2, nsteps, 1), :, :],
                                 colors_all_2[np.arange(2, nsteps, 1), :, :]),
                                axis=1)

    int_inds = [3, 3, 3, 3]
    colors_main = np.asarray(
        [colors_all[int_inds[ii], ii, :] for ii in range(np.size(int_inds))])
    colors_main = np.concatenate((colors_main, colors_all[5, 1:2, :]), axis=0)
    # plot the color map
    #plt.figure();plt.imshow(np.expand_dims(colors_main,axis=0))
    colors_sf = np.moveaxis(
        np.expand_dims(cm.GnBu(np.linspace(0, 1, 8)), axis=2), [0, 1, 2],
        [0, 2, 1])
    colors_sf = colors_sf[np.arange(2, 8, 1), :, :]

    return colors_main, colors_sf
Example #18
0
rspace = np.linspace(rmin, rmax, 100)

# choose energies based on the behavior of the determinant (see cpts_..._RGM.nb)

wfktJ0 = [[psiL(rr, 1, lit_wrels, np.real(litcoeff)) for rr in rspace]
          for litcoeff in litcoeffs00]

f = plt.figure(figsize=(10, 6))
f.suptitle(
    r'$\Psi_{LIT}^{0^-}\;\;\;\;\sigma_i=%2.1f$ MeV $\;\;\;\;\sigma_r\in[%2.1f,%2.1f]$ MeV (dark$\to$light)'
    % (sI, float(sR[0]), float(sR[-1])),
    fontsize=14)

ax1 = f.add_subplot(111)
colormap = cm.Greys(np.linspace(0, 1, len(wfktJ0)))[::-1]

ax1.set_xlabel(r'$r$ [fm]', fontsize=12)
ax1.set_ylabel(r'$\psi_{0^-}(r)$ [MeV$^{-3/2}$]', fontsize=12)

[
    ax1.plot(rspace,
             wfktJ0[wfkt],
             label='$\sigma_r=%4.2f, n=%d$' % (float(sR[wfkt]), nw),
             c=colormap[wfkt]) for wfkt in range(len(wfktJ0))
]

line, = ax1.plot(rspace, wfktJ0[0], 'r-')

energysel = [1, 4, 23, 45, 76, 90]
Example #19
0
def plot_spike_shapes(shape_dict, f_handle, meta, info, my_name):
    """
    Plots spike shapes superimposed, together with the appropriate mean
    :f_handle: list of figure and axes handles
    :param shape_dict: dictionary with spike shape for all selected repros and stimuli
    :return: figure handle, maybe
    """
    color_spread = np.linspace(0.8, 0.4, len(shape_dict))
    cmapGrey = [cm.Greys(x) for x in color_spread]

    counter = 0
    for k, v in shape_dict.items():

        # for spike in range(shape_dict[k].shape[0]):
        # peak_voltage = np.max(shape_dict[k][spike,:])
        #     f_handle[1].plot(shape_dict[k][spike,:]-peak_voltage, color=cmapGrey[counter])

        avg_spike = np.mean(shape_dict[k], 0)
        med_spike = np.median(shape_dict[k], 0)

        peak_avg_voltage = np.max(avg_spike)
        peak_med_voltage = np.max(med_spike)

        q25spike = np.percentile(shape_dict[k], 5, 0)
        q75spike = np.percentile(shape_dict[k], 95, 0)
        std_spike = np.std(shape_dict[k], 0)

        # f_handle[1].fill_between(range(0,med_spike.shape[0]), med_spike-peak_med_voltage-q25spike, med_spike-peak_med_voltage + q75spike, color=cmapGrey[counter], alpha=0.2)
        # f_handle[1].plot(med_spike-peak_med_voltage, color=cmapGrey[counter])

        f_handle[1].fill_between(range(0, avg_spike.shape[0]),
                                 avg_spike - peak_med_voltage - std_spike,
                                 med_spike - peak_med_voltage + std_spike,
                                 color=cmapGrey[counter],
                                 alpha=0.1)
        f_handle[1].plot(avg_spike - peak_avg_voltage, color=cmapGrey[counter])

        if "SyncPulse" in meta[k][0]["Status"].keys():
            f_handle[1].text(35,
                             -5 - counter * 5,
                             "".join([
                                 r'$g_{Vgate}$', ' = ',
                                 meta[k][0]["Status"]["gvgate"].split('.')[0],
                                 ' ns'
                             ]),
                             fontsize=10,
                             color=cmapGrey[counter])
            f_handle[1].text(
                60,
                -5 - counter * 5,
                "".join([
                    r'$\tau_{Vgate}$', ' = ',
                    meta[k][0]["Status"]["vgatetau"].split('.')[0], ' ms'
                ]),
                fontsize=10,
                color=cmapGrey[counter])

        counter += 1

    f_handle[1].set_title(".".join([
        "_".join([info["Cell"]["Location"], expfolder, "spike_shape",
                  my_name]), 'pdf'
    ]))

    f_handle[1].set_ylim(-40, 0)
    f_handle[1].set_xlabel("time [ms]")
    f_handle[1].set_ylabel("relative voltage [mV]")
    f_handle[1].set_xticklabels(['-1', '0', '1', '2', '3', '4'])

    f_handle[0].savefig(ppjoin(
        '../overviewSpikeShape/', ".".join([
            "_".join(
                [info["Cell"]["Location"], expfolder, "spike_shape", my_name]),
            'pdf'
        ])),
                        transparent=True)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# ax.scatter(lon1, lat1, color='black', s=5, label="No rotation")
ax.scatter(lon2, lat2, color='red', s=5, label="Earth's Rotation")
plt.legend()
ax.stock_img()
ax.gridlines()
ax.coastlines()
plt.title("Effect of Earth's rotation on the Ground Track")
""" Several periods """
per = 3
orbit_0 = orbital_elements(h=1000, e=0.0, i=60, raan=0, omega=0)
theta0 = np.linspace(0, 2 * np.pi * per, per * N_points)
lon0, lat0 = compute_track(orbit_1, theta0, periods=per, rotation=True)
colors = cm.Greys(np.linspace(0, 1, len(theta0)))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.scatter(lon0, lat0, color=colors, s=5)
ax.stock_img()
ax.gridlines()
ax.coastlines()
plt.title("%d Periods" % (per))
""" Effect of Inclination """
i2, i3 = 45, 60
orbit_2 = orbital_elements(h=600, e=0.0, i=i2, raan=0, omega=0)
orbit_3 = orbital_elements(h=600, e=0.0, i=i3, raan=0, omega=0)
lon2, lat2 = compute_track(orbit_2, theta, rotation=True)
lon3, lat3 = compute_track(orbit_3, theta, rotation=True)
Example #21
0
def wht_noise(path_to_folder, subfolder, info):
    """
    Main engine, opens the spike files.

    :param path_to_folder:  folder with recordings
    :param subfolder:       folder containing the experiment/cell
    :param info:            experimental data from info.dat
    :return fnames:         list of figure names to be used in the html build

    """

    #   define sample rate
    FS = 20000

    #   define the Gauss kernel width (= 1SD)
    sigma = 0.001  # seconds, from Berman & Maler 1998

    #   define the input data
    filename = ppjoin(path_to_folder, subfolder, "stimulus-whitenoise-spikes.dat")

    #   get the file, extract the three data subunits
    relacs_file = load(filename)

    #   extract RePro indices
    try:
        ReProIx = relacs_file.fields[('ReProIndex',)]

    except:
        return None

    #   convert set objet into a list
    ReProIx = list(ReProIx)
    ReProIx.sort()

    #   define empty list containing figure names
    fnames = []

    for ix in ReProIx:

        #   if relacs file is empty or too short due to aborted RePro presentation
        #   "try:" provides normal termination of the loop instead of error
        try:
            metas, _, datas = relacs_file.select({"ReProIndex": ix})

        except:
            return None

        print("ReProIx", ix, "Iterations", len(metas))

        #   determine figure handles
        fig = figure_handles()

        #   FFT is defined as something + 1, due to mlab reasoning
        nFFT = 2048
        FFT = (nFFT/2)+1

        #   prepare empty variables
        coh = np.zeros([len(metas), FFT], )
        coh_short = np.zeros([len(metas), FFT], )
        P_csd = np.zeros([len(metas), FFT], dtype=complex)
        P_csd_short = np.zeros([len(metas), FFT], dtype=complex)
        P_psd = np.zeros([len(metas), FFT])
        P_psd_short = np.zeros([len(metas), FFT])
        H = np.zeros([len(metas), FFT],)# dtype=complex)
        H_short = np.zeros([len(metas), FFT],)# dtype=complex)
        MI = np.zeros([len(metas), FFT], )
        MI_short = np.zeros([len(metas), FFT], )
        #   number of stimulus iterations

        for i in range(0, len(metas)):

            color_spread = np.linspace(0.35,0.8, len(metas))
            cmap = [ cm.Greys(x) for x in color_spread ]

            #   extract meta infos
            wnFname = metas[i]["envelope"]
            wnDur = float(metas[i]["Settings"]["Waveform"]["duration"].split("m")[0])  # duration in miliseconds

            #   conversions
            spikes = np.array(datas[i])

            #   conversions
            wnDur /= 1000   #   conversion to miliseconds
            spikes /= 1000

            print(spikes.shape)
            convolved_Train, _ = train_convolve(spikes, sigma, FS, wnDur)
            print(sum(convolved_Train)/FS)
            wNoise = process_wn(path_to_folder, wnFname, len(convolved_Train))

            #   compute coherence, mutual information, transfer and the power spectra and cross-spectra density
            freq, coh[i,:], coh_short[i,:], H[i,:], H_short[i,:], MI[i,:], MI_short[i,:], \
                P_csd[i,:], P_csd_short[i,:], P_psd[i,:], P_psd_short[i,:] \
                = cohere_transfere_MI (convolved_Train, wNoise, nFFT, FS)

        #   plot coherence, mutual information etc....
        plot_the_lot(fig, freq, coh, coh_short, MI, MI_short, H, H_short, metas, cmap, np.array(datas))

        avgCoh, avgCoh_short, avgH, avgH_short, mut_inf, mut_inf_short = compute_avgs(coh, coh_short, H, H_short, MI, MI_short)

        plot_the_lot(fig, freq, avgCoh, avgCoh_short, mut_inf, mut_inf_short, avgH, avgH_short, metas, cmap = [cm.Reds(0.6)],raster='empty', annotation=True)

        fig[2].text(0.05, 0.95, " ".join(['Species:', info["Subject"]["Species"]]), transform=fig[1].transAxes,
                fontsize=10)
        fig[2].text(0.05, 0.90, " ".join(['ELL Segment:', info["Cell"]["Location"]]), transform=fig[1].transAxes,
                fontsize=10)

        #   define file name
        filename = "".join([str(metas[i]["ReProIndex"]), '_', 'whitenoise'])
        fnames.append(filename)

        fig[0].savefig(ppjoin(path_to_folder, subfolder, ".".join([filename, 'png'])), transparent=True)
        fig[0].savefig(ppjoin(path_to_folder, subfolder, ".".join([filename, 'svg'])), transparent=True)

        plt.close()

    return fnames
Example #22
0
def noise_transfer(tests, wd, expfolder):
    """"
    Plots the transfer and coherence curve into the graphic file (*.png, *.svg)
        Requires:
    :param tests:   dictionary containing experimental conditions as keys and ReProIx as values
    :param wd: location of the experimental folder
    :param expfolder: name of the experimental folder

    Outputs:
            graphic files containing coherence, MI and transfer
    """

    #   define sample rate
    FS = 20000

    #   define the Gauss kernel width (= 1SD)
    sigma = 0.001  # seconds, from Berman & Maler 1998

    #   define the input data
    filename = ppjoin(wd, expfolder, "stimulus-whitenoise-spikes.dat")

    #   read in some experimental data
    (_, _, filenames) = next(walk(ppjoin(wd, expfolder)))
    if "info.dat" in filenames:
        exp_info = dict(read_info(wd, expfolder)[0])
        print(exp_info)
    else:
        exp_info = {"Cell": {"Location": "UNLABELED"}}

    #   load data
    relacs_file = load(filename)

    #   four panel figure
    FHandles = figure_handles()

    #   define colors
    color_spread = np.linspace(0.5, 0.9, len(tests))
    cmap = [cm.Greys(x) for x in color_spread]
    # cmap = [ cm.viridis(x) for x in color_spread ]

    #   color counter
    col_count = 0

    #   FFT is defined as something + 1, due to mlab reasoning
    nFFT = 1024
    FFT = (nFFT / 2) + 1

    #   define spike dict for the raster plot
    spike_dict = OrderedDict()

    for k, v in tests.items():
        #   get RePro indexes of the same experimental condition
        ReProIx = tests[k]

        #   define empty variables, containing traces of the same experiments, different RePros
        coh_repro = np.zeros([len(ReProIx), FFT])
        coh_repro_short = np.zeros([len(ReProIx), FFT])
        H_repro = np.zeros([len(ReProIx), FFT])
        H_repro_short = np.zeros([len(ReProIx), FFT])
        MI_repro = np.zeros([len(ReProIx), FFT])
        MI_repro_short = np.zeros([len(ReProIx), FFT])

        spike_list = []

        #   define/reset counter
        counter = 0

        #   iteration of same experimental condition
        for ix in ReProIx:

            try:
                metas, _, datas = relacs_file.select({"ReProIndex": ix})

            except:
                return None

            #   define empty variables
            coh = np.zeros([len(metas), FFT])
            coh_short = np.zeros([len(metas), FFT])
            P_csd = np.zeros([len(metas), FFT], dtype=complex)
            P_csd_short = np.zeros([len(metas), FFT], dtype=complex)
            P_psd = np.zeros([len(metas), FFT])
            P_psd_short = np.zeros([len(metas), FFT])
            H = np.zeros([len(metas), FFT])
            H_short = np.zeros([len(metas), FFT])
            MI = np.zeros([len(metas), FFT])
            MI_short = np.zeros([len(metas), FFT])

            meta_repros = []

            #   number of stimulus iterations
            for i in range(0, len(metas)):

                #   extract meta infos
                wnFname = metas[i]["envelope"]
                wnDur = float(
                    metas[i]["Settings"]["Waveform"]["duration"].split(
                        "m")[0])  # duration in miliseconds

                #   spikes
                spikes = np.array(datas[i])

                #   conversions
                wnDur /= 1000  #   conversion to miliseconds
                spikes /= 1000

                print(spikes.shape)
                convolved_Train, _ = train_convolve(spikes, sigma, FS, wnDur)
                print(sum(convolved_Train) / FS)
                wNoise = process_wn(wd, wnFname, len(convolved_Train))

                #   compute coherence, mutual information, transfer and the power spectra and cross-spectra density
                freq, coh[i,:], coh_short[i,:], H[i,:], H_short[i,:], MI[i,:], MI_short[i,:], \
                    P_csd[i,:], P_csd_short[i,:], P_psd[i,:], P_psd_short[i,:] \
                    = cohere_transfere_MI (convolved_Train, wNoise, nFFT, FS)

            #   compute averages over iterations of the *same* repro
            coh_repro[counter,:], coh_repro_short[counter,:], \
                H_repro[counter,:], H_repro_short[counter,:], \
                MI_repro[counter,:], MI_repro_short[counter,:] = compute_avgs(coh, coh_short, H, H_short, MI, MI_short)

            #   store one of the metas
            meta_repros.append(metas[0])
            #   store all the spikes from the same type of experiment
            spike_list.append(datas)
            counter = counter + 1
        #   plot the lot
        plot_the_lot(FHandles,
                     freq,
                     coh_repro,
                     coh_repro_short,
                     MI_repro,
                     MI_repro_short,
                     H_repro,
                     H_repro_short,
                     metas,
                     cmap=[cmap[col_count]],
                     raster='empty',
                     annotation=False,
                     comparison=True)

        #   compute the average of the different repro presentations (with same test conditions)
        avgCoh, avgCoh_short, avgH, avgH_short, avgMI, avgMI_short = compute_avgs(
            coh_repro, coh_repro_short, H_repro, H_repro_short, MI_repro,
            MI_repro_short)

        #   plot the lot
        plot_the_lot(FHandles,
                     freq,
                     avgCoh,
                     avgCoh_short,
                     avgMI,
                     avgMI_short,
                     avgH,
                     avgH_short,
                     meta_repros,
                     cmap=[cmap[col_count]],
                     raster='empty',
                     annotation=False,
                     comparison=True)

        #   provide gVgate values
        FHandles[1].text(0.5,
                         0.8 - 0.05 * col_count,
                         " ".join([
                             r'$g_{Vgate}$', ' = ',
                             meta_repros[0]["Status"]["gvgate"].split(".")[0],
                             'nS'
                         ]),
                         color=cmap[col_count],
                         transform=FHandles[1].transAxes,
                         fontsize=10)
        FHandles[5].text(
            0.5,
            0.8 - 0.05 * col_count,
            " ".join([
                r'$\tau_{Vgate}$', ' = ',
                meta_repros[0]["Status"]["vgatetau"].split(".")[0], 'ms'
            ]),
            color=cmap[col_count],
            transform=FHandles[5].transAxes,
            fontsize=10)

        #   update spike dictionary
        spike_dict[k] = spike_list

        #   update the color counter
        col_count += 1

    #   write FFT value
    FHandles[1].text(0.05,
                     0.90,
                     " ".join(['FFT = ', str(nFFT)]),
                     color='k',
                     transform=FHandles[1].transAxes,
                     fontsize=10)

    #   plot raster plot
    spike_iter_count = 0
    for i, k in enumerate(spike_dict):
        for j in range(len(spike_dict[k])):
            for gnj in range(len(spike_dict[k][j])):
                FHandles[7].plot(spike_dict[k][j][gnj],
                                 np.zeros(len(spike_dict[k][j][gnj])) +
                                 spike_iter_count,
                                 '|',
                                 color=cmap[i],
                                 ms=12)
                spike_iter_count += 1

    FHandles[7].set_title(
        ppjoin(".".join([
            exp_info["Cell"]["Location"], ':', expfolder, "dyn_noise_transfer",
            '_'.join([k for k, v in tests.items()]), '_'.join([
                str(x) for sublist in [v for k, v in tests.items()]
                for x in sublist
            ]), "fft",
            str(nFFT)
        ])))
    #   Save figures
    FHandles[0].savefig(ppjoin(".".join([
        expfolder, "coherence_transfer",
        '.'.join([k for k, v in tests.items()]), '.'.join([
            str(x) for sublist in [v for k, v in tests.items()]
            for x in sublist
        ]), "fft",
        str(nFFT), 'svg'
    ])),
                        transparent=True)
    FHandles[0].savefig(ppjoin(".".join([
        expfolder, "coherence_transfer",
        '.'.join([k for k, v in tests.items()]), ".".join([
            str(x) for sublist in [v for k, v in tests.items()]
            for x in sublist
        ]), "fft",
        str(nFFT), 'png'
    ])),
                        transparent=True)
    #   save figures into dedicated folder if necessary
    FHandles[0].savefig(ppjoin(
        '../overviewTransfer/', ".".join([
            "_".join([
                exp_info["Cell"]["Location"], expfolder, "coherence_transfer",
                "".join([k for k, v in tests.items()]), "_".join([
                    str(x) for sublist in [v for k, v in tests.items()]
                    for x in sublist
                ]), "fft",
                str(nFFT)
            ]), 'pdf'
        ])),
                        transparent=True)
Example #23
0
def plot_final_policy_combined(exp_groups,
                               des_mps,
                               des_speed,
                               min_speed,
                               ax=None,
                               fs=20.,
                               save_path=None):
    dt = 0.5

    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(5, 3.5))
    else:
        f = ax.get_figure()

    exp_groups.insert(0, [{
        'folder': os.path.join(EXP_FOLDER, 'random'),
        'label': 'Random policy',
        'color': cm.Greys(1.0)
    }])

    for exp_group_num, exp_group in enumerate(exp_groups):
        distance_travelled = []
        for exp in exp_group:
            samples_folder = os.path.join(exp['folder'],
                                          'prediction/final_policy/')
            samples_fnames = [
                os.path.join(samples_folder, fname)
                for fname in os.listdir(samples_folder) if fname[-4:] == '.npz'
            ]
            assert (len(samples_fnames) == 1)
            samples_fname = samples_fnames[0]

            samples = Sample.load(samples_fname)
            for sample in samples:
                distance = dt * (des_mps / des_speed) * (sample.get_U()[:, 1] -
                                                         min_speed).sum()
                distance_travelled.append(distance)

        width = 0.8 / len(exp_groups)
        ax.bar([exp_group_num * width], [np.mean(distance_travelled)],
               yerr=[np.std(distance_travelled)],
               width=width * 0.8,
               error_kw=dict(lw=4, capsize=5, capthick=2),
               color=exp_group[0]['color'],
               ecolor=cm.Greys(0.5),
               label=exp_group[0]['label'])

    # for exp_group in exp_groups:
    #     ax.plot([], [], lw=5., label=exp_group[0]['label'], color=exp_group[0]['color'])
    lgd = ax.legend(loc='upper center',
                    fontsize=fs * 0.8,
                    bbox_to_anchor=(1.35, 0.7))

    ax.set_xlim((-0.05, width * len(exp_groups)))
    ax.set_ylim((-0.3, ax.get_ylim()[1]))
    ax.set_ylabel(r'Distance travelled (m)', fontsize=fs)

    for tick in ax.xaxis.get_major_ticks() + ax.xaxis.get_minor_ticks():
        tick.label1.set_visible(False)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(fs)

    if save_path is not None:
        f.savefig(save_path, bbox_extra_artists=(lgd, ), bbox_inches='tight')
Example #24
0
def plot_final_policy(exp_groups,
                      des_mps,
                      des_speed,
                      min_speed,
                      ax=None,
                      fs=20.,
                      save_path=None):
    dt = 0.5

    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(10, 3.5))
    else:
        f = ax.get_figure()

    exp_groups.insert(0, [{
        'folder': os.path.join(EXP_FOLDER, 'random'),
        'label': 'Random policy',
        'color': cm.Greys(0.5)
    }])

    for exp_num, exp in enumerate(flatten_list(exp_groups)):
        samples_folder = os.path.join(exp['folder'],
                                      'prediction/final_policy/')
        samples_fnames = [
            os.path.join(samples_folder, fname)
            for fname in os.listdir(samples_folder) if fname[-4:] == '.npz'
        ]
        assert (len(samples_fnames) == 1)
        samples_fname = samples_fnames[0]

        samples = Sample.load(samples_fname)
        distance_travelled = []
        for sample in samples:
            distance = dt * (des_mps / des_speed) * (sample.get_U()[:, 1] -
                                                     min_speed).sum()
            distance_travelled.append(distance)

        # ax.plot(range(len(distance_travelled)), distance_travelled,
        #         linestyle='',
        #         marker=exp['marker'],
        #         color=exp['color'],
        #         mew=exp['mew'])

        ax.bar(np.arange(len(distance_travelled)) + 0.15 * exp_num + 0.1,
               distance_travelled,
               width=0.15,
               color=exp['color'])

    for exp_group in exp_groups:
        ax.plot([], [],
                lw=5.,
                label=exp_group[0]['label'],
                color=exp_group[0]['color'])
    lgd = ax.legend(loc='upper right', fontsize=fs * 0.8)

    ax.set_xlabel(r'Starting position', fontsize=fs)
    ax.set_ylabel(r'Distance travelled (m)', fontsize=fs)

    N = len(distance_travelled)
    ax.set_xticks(np.arange(N) + 0.5)
    ax.set_xticklabels([str(x) for x in range(N)])
    # Hide major tick labels and customize minor tick labels
    ax.xaxis.set_minor_formatter(ticker.NullFormatter())
    ax.xaxis.set_major_locator(ticker.FixedLocator(np.arange(N) + 0.5))
    ax.xaxis.set_major_formatter(
        ticker.FixedFormatter([r'{0}'.format(str(x)) for x in range(N)]))
    for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(fs)

    if save_path is not None:
        f.savefig(save_path, bbox_extra_artists=(lgd, ), bbox_inches='tight')
Example #25
0
def plot_boxplot_speeds(exp_groups,
                        des_mps,
                        des_speed,
                        min_speed,
                        ax=None,
                        is_legend=True,
                        start_itr=0,
                        save_path=None,
                        ylim=None,
                        fs=20.):
    end_itr = min([len(exp['U']) for exp in flatten_list(exp_groups)])
    itrs_offset = np.linspace(0.35, 0.65, len(exp_groups))
    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(1.5 * (end_itr - start_itr), 5))
    else:
        f = ax.get_figure()

    T = 0
    for exp_group in exp_groups:
        for exp in exp_group:
            for U_itr in exp['U']:
                for U in U_itr:
                    T = max(T, len(U))

    for exp_group_num, exp_group in enumerate(exp_groups):
        xvels_itrs = []
        for itr in xrange(start_itr, end_itr):
            xvels = []
            for exp in exp_group:
                xvels += flatten_list([
                    list((des_mps / des_speed) * (U[:, 1] - min_speed)) + [0] *
                    (T - len(U)) for U in exp['U'][itr]
                ])
            xvels_itrs.append(xvels)

            color = exp_group[0]['color']
            ax.errorbar([itr + itrs_offset[exp_group_num]], [np.mean(xvels)],
                        [[np.mean(xvels) - np.min(xvels)],
                         [np.max(xvels) - np.mean(xvels)]],
                        fmt='.k',
                        ecolor='gray',
                        lw=1.5,
                        capsize=5.,
                        capthick=2.)
            ax.errorbar(itr + itrs_offset[exp_group_num],
                        np.mean(xvels),
                        np.std(xvels),
                        marker='o',
                        color=color,
                        ecolor=color,
                        mec=color,
                        lw=3.)

    des_xvel_handle = ax.plot((start_itr, end_itr), (des_mps, des_mps),
                              color='k',
                              ls=':',
                              lw=2.)[0]

    ax.set_xlim((start_itr, end_itr))
    ax.set_ylim((0, des_mps * 1.1))

    if ylim is not None:
        ax.set_ylim(ylim)
    # background color
    for itr in xrange(start_itr, end_itr):
        ax.axvspan(itr,
                   itr + 1,
                   facecolor=cm.Greys(0.05 + (itr % 2) * 0.1),
                   edgecolor='none')
    ax.set_xticks(np.arange(start_itr, end_itr) + 0.5)
    ax.set_xticklabels([str(x) for x in range(start_itr, end_itr)])
    # Hide major tick labels and customize minor tick labels
    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.xaxis.set_minor_locator(
        ticker.FixedLocator(np.arange(start_itr, end_itr) + 0.5))
    ax.xaxis.set_minor_formatter(
        ticker.FixedFormatter(
            [r'{0}'.format(str(x)) for x in range(start_itr, end_itr)]))
    ax.set_xlabel('Iteration', fontsize=fs)
    ax.set_ylabel('Speed (m/s)', fontsize=fs)
    for tick in ax.xaxis.get_minor_ticks() + ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(fs)

    if is_legend:
        # Create legend
        extra = Rectangle((0, 0),
                          1,
                          1,
                          fc="w",
                          fill=False,
                          edgecolor='none',
                          linewidth=0)
        legend_handles = []
        legend_labels = []

        legend_handles.append(des_xvel_handle)
        legend_labels.append('')
        legend_handles.append(extra)
        legend_labels.append('Desired speed')
        for exp_group in exp_groups:
            legend_handles.append(
                Rectangle((0, 0),
                          1,
                          1,
                          color=exp_group[0]['color'],
                          fill=True,
                          linewidth=1))
            legend_labels.append('')
            legend_handles.append(extra)
            legend_labels.append(exp_group[0]['label'])
        lgd = f.legend(legend_handles,
                       legend_labels,
                       loc='upper center',
                       bbox_to_anchor=(0.45, 1.15),
                       ncol=len(legend_handles),
                       handletextpad=-2,
                       handlelength=3.,
                       fontsize=fs)

    if save_path is not None:
        f.tight_layout()
        f.savefig(save_path, bbox_extra_artists=(lgd, ), bbox_inches='tight')
Example #26
0
def plot_num_successful(exp_groups,
                        ax=None,
                        fs=20.,
                        save_path=None,
                        is_legend=False):
    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(4, 4))
    else:
        f = ax.get_figure()

    end_itr = min([len(exp['U']) for exp in flatten_list(exp_groups)])
    reps = len(exp_groups[0][0]['U'][0])
    T = 10

    for itr in xrange(0, end_itr):
        ax.axvspan(itr,
                   itr + 1,
                   facecolor=cm.Greys(0.05 + (itr % 2) * 0.1),
                   edgecolor='none')

    for exp_group_num, exp_group in enumerate(exp_groups):
        frac_successful_itrs_group = []
        for exp in exp_group:
            num_successful_itrs = np.array([0.] * end_itr)
            for itr in xrange(end_itr):
                for rep in xrange(reps):
                    if exp['stop_rollout'][itr][rep] or len(
                            exp['U'][itr][rep]) == T:
                        num_successful_itrs[itr] += 1.

            frac_successful_itrs = num_successful_itrs / (reps)
            frac_successful_itrs_group.append(frac_successful_itrs)

        frac_successful_itrs_group = 100 * np.array(frac_successful_itrs_group)

        width = 0.8 / len(exp_groups)
        ax.bar(np.arange(end_itr) + exp_group_num * width + width / 4.,
               frac_successful_itrs_group.mean(axis=0),
               yerr=frac_successful_itrs_group.std(axis=0),
               width=width * 0.8,
               error_kw=dict(lw=2, capsize=3, capthick=1),
               color=exp_group[0]['color'],
               ecolor=cm.Greys(0.5),
               label=exp_group[0]['label'])

    ax.set_xlabel(r'Iteration', fontsize=fs)
    ax.set_ylabel(r'\begin{center}Successful\\rollouts (\%)\end{center}',
                  fontsize=fs)

    ax.set_ylim((0, 100))

    N = end_itr
    ax.set_xticks(np.arange(N) + 0.5)
    ax.set_xticklabels([str(x) for x in range(N)])
    # Hide major tick labels and customize minor tick labels
    ax.xaxis.set_minor_formatter(ticker.NullFormatter())
    ax.xaxis.set_major_locator(ticker.FixedLocator(np.arange(N) + 0.5))
    ax.xaxis.set_major_formatter(
        ticker.FixedFormatter([r'{0}'.format(str(x)) for x in range(N)]))
    for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(fs)

    if is_legend:
        leg = ax.legend(loc='upper left',
                        ncol=2,
                        bbox_to_anchor=(-0.5, 1.5),
                        fontsize=fs)
    else:
        leg = None

    if save_path is not None:
        f.tight_layout()
        f.savefig(save_path,
                  bbox_extra_artists=(leg, ),
                  bbox_inches='tight',
                  dpi=200)
# The following histogram shows I vs position. This is a representation of the average value of the number of photons emitted between any two consecutive integral positions along hte tubelight and thus a representation of the average intensity.

# In[50]:

if p!=0:
    plt.figure(1,figsize=size)
    plt.title("Intensity (average) of the tubelight vs position", fontsize=18)
    plt.xlabel("Position", fontsize=18)
    plt.ylabel("Intensity/ Number of photons emitted",fontsize=18)
    plt.grid(True)
    ret=plt.hist(I,np.arange(0,n+1,1),color="white")
    vals=ret[0]
    vals=1-(vals/max(vals))
    norm = colors.Normalize(vals.min(), vals.max())
    for thisfrac, thispatch in zip(vals, ret[2]):
        color = cm.Greys(norm(thisfrac))
        thispatch.set_facecolor(color)
    plt.show()    
    plt.close()  


# We plot the phase space of the electrons and also make a table of the centers of the bins and the intensity (number of photons) values.

# In[53]:


plt.figure(2,figsize=size)
plt.xlabel("X",fontsize=18)
plt.title("Electron phase space",fontsize=18)
plt.ylabel("V",fontsize=18)
plt.grid(True)
pres_41_45['President'].value_counts()
pres_41_45.groupby('President', sort=False).median().round(1)

import matplotlib.pyplot as plt
from matplotlib import cm
fig, ax = plt.subplots(figsize=(16, 6))
styles = ['-.', '-', ':', '-', ':']
colors = [.9, .3, .7, .3, .9]
groups = pres_41_45.groupby('President', sort=False)
for style, color, (pres, df) in zip(styles, colors, groups):
    df.plot('End Date',
            'Approving',
            ax=ax,
            label=pres,
            style=style,
            color=cm.Greys(color),
            title='Presidential Approval Rating')

days_func = lambda x: x - x.iloc[0]
pres_41_45['Days in Office']=pres_41_45.groupby('President')['End Date']\
.transform(days_func)
pres_41_45.head()
pres_41_45.groupby('President').head(3)
pres_41_45.dtypes
pres_41_45['Days in Office'] = pres_41_45['Days in Office'].dt.days
pres_41_45['Days in Office'].head()
pres_pivot = pres_41_45.pivot(index='Days in Office',
                              columns='President',
                              values='Approving')
pres_pivot.head()
plot_kwargs = dict(figsize=(16, 6),
    ax.scatter(lon_rot, lat_rot, color='red', s=5, label="Earth's Rotation")
    plt.legend()
    ax.stock_img()
    ax.gridlines()
    ax.coastlines()
    plt.title("Effect of Earth's rotation on the Ground Track")
    plt.show()

    # ================================================================================== #
    #                                  Several orbital periods                           #
    # ================================================================================== #

    per = 3
    leo_per = orbital_elements(h=1000, e=0.0, i=45, raan=0, omega=0)
    lon_per, lat_per = compute_track(leo, periods=per, rotation=True)
    colors = cm.Greys(np.linspace(0, 1, N_points * per))

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    ax.scatter(lon_per, lat_per, color=colors, s=5)
    ax.stock_img()
    ax.gridlines()
    ax.coastlines()
    plt.title("%d Periods" % (per))

    # ================================================================================== #
    #                                  Effect of Inclination                             #
    # ================================================================================== #

    i1, i2 = 45, 60
    inc1 = orbital_elements(h=600, e=0.0, i=i1, raan=0, omega=0)
Example #30
0
import numpy as np
from matplotlib import cm

r = np.linspace(0, 1, 257)[:256]
cmapInferno = np.array(cm.inferno(r) * 255, dtype=np.uint8)

r = np.linspace(0, 1, 101)
cmapGreys = np.array(cm.Greys(r) * 255, dtype=np.uint8)

print("#pragma once\n\nunsigned int CM_GREYS[101] {")
for r, g, b, a in cmapGreys:
    print("    " + str((r << 24) | (g << 16) | (b << 8) | a) + ",")
print("};")

# print("\n\nunsigned int CM_INFERNO[256] {")
# for r, g, b, a in cmapInferno:
#     print("    " + str((r << 24) | (g << 16) | (b << 8) | a) + ",")
# print("};")

# print("logic [255:0][31:0] CM_INFERNO = {")
# for r, g, b, a in cmapInferno[::-1]:
#     print("    {32'h" + hex((r << 24) | (g << 16) | (b << 8) | a)[2:] + "},")
# print("};\n")