示例#1
0
    def initiate_plot(self, averagereward, transparency='on'):

        self.exparr_x = self.explode(self.bm)
        self.exparr = np.where(
            self.exparr_x - averagereward < 0, 0,
            self.exparr)  #turns values below cutoff to 0 invisible waste
        normarr = self.normalize(self.exparr)
        self.facecolours = cm.plasma(normarr)  # facecolours [x,y,z, (r,g,b,a)]
        #ceilarr=np.ceil(normarr)
        #normarr[normarr<=0.05]=0 #hide voxels less than 0.05
        if transparency == 'on':
            self.facecolours[:, :, :,
                             -1] = normarr  #matches transperancy to normarr intensity
            normarr_x = self.normalize(self.exparr_x)
            self.facecolours_x = cm.plasma(
                normarr_x)  # facecolours [x,y,z, (r,g,b,a)]
            #ceilarr=np.ceil(normarr)
            #normarr[normarr<=0.05]=0 #hide voxels less than 0.05

            self.facecolours_x[:, :, :,
                               -1] = normarr  #matches transperancy to normarr intensity

        else:

            notransp = np.where(self.exparr_x - averagereward < 0, 0, 1)
            self.facecolours[:, :, :, -1] = notransp

            normarr_x = self.normalize(self.exparr_x)
            self.facecolours_x = cm.plasma(
                normarr_x)  # facecolours [x,y,z, (r,g,b,a)]
            #ceilarr=np.ceil(normarr)
            #normarr[normarr<=0.05]=0 #hide voxels less than 0.05

            self.facecolours_x[:, :, :,
                               -1] = notransp  #matches transperancy to 1 for ore 0 for waste
示例#2
0
def test_gumbel():
    n_classes = 4
    logits = tf.random.normal((1, n_classes))
    temperatures = [0.1, 0.5, 1., 5., 10.]
    M = 128  # number of samples used to approximate distribution mean

    fig, axes = plt.subplots(nrows=2,
                             ncols=len(temperatures),
                             figsize=(14, 6),
                             subplot_kw={
                                 'xticks': range(n_classes),
                                 'yticks': [0., 0.5, 1.]
                             })
    axes[0, 0].set_ylabel('Expectation')
    axes[1, 0].set_ylabel('Gumbel Softmax Sample')

    for n, t in enumerate(temperatures):
        dist = RelaxedOneHotCategorical(logits, t)
        mean = tf.zeros_like(logits)
        for _ in range(M):
            mean += dist.sample() / M
        sample = dist.sample()

        axes[0, n].set_title('T = {}'.format(t))
        axes[0, n].set_ylim((0, 1.1))
        axes[1, n].set_ylim((0, 1.1))
        axes[0, n].bar(np.arange(n_classes),
                       mean.numpy().reshape(n_classes),
                       color=cm.plasma(0.75 * t / max(temperatures)))
        axes[1, n].bar(np.arange(n_classes),
                       sample.numpy().reshape(n_classes),
                       color=cm.plasma(0.75 * t / max(temperatures)))
    plt.show()
示例#3
0
def updateHist(writer,model_id,outDictEpochs,targDictEpochs):

    firstEpoch = list(outDictEpochs.keys())[0]

    for i,vidName in enumerate(outDictEpochs[firstEpoch].keys()):

        fig = plt.figure()

        targBounds = np.array(utils.binaryToSceneBounds(targDictEpochs[firstEpoch][vidName][0]))

        cmap = cm.plasma(np.linspace(0, 1, len(targBounds)))

        width = 0.2*len(outDictEpochs.keys())
        off = width/2

        plt.bar(len(outDictEpochs.keys())+off,targBounds[:,1]+1-targBounds[:,0],width,bottom=targBounds[:,0],color=cmap,edgecolor='black')

        for j,epoch in enumerate(outDictEpochs.keys()):

            predBounds = np.array(utils.binaryToSceneBounds(outDictEpochs[epoch][vidName][0]))
            cmap = cm.plasma(np.linspace(0, 1, len(predBounds)))

            plt.bar(epoch-1,predBounds[:,1]+1-predBounds[:,0],1,bottom=predBounds[:,0],color=cmap,edgecolor='black')

        writer.add_figure(model_id+"_val"+"_"+vidName,fig,firstEpoch)
示例#4
0
def PlotModelsOverTime_DuskAndDawn(base_model,shifts,parameter_dict,null_model="None",reset=True):
    
    # Setup of the base model
    def base_newpars():
        base_model.model['shift_hour'] = 0.0
    base_model_out = update_and_sim_model(base_model,base_newpars)
    
    base_dawn_time = base_model.model['dawn_time']
    base_dusk_time = base_model.model['prev_dusk']
    
    base_time_idxs_middle = GetTimeIdxs(base_model_out,base_model.model['dawn_time']+(9.5*(3/8)),base_model.model['dawn_time']+(9.5*(11/8)))
    
    color_num = 1.0
    index=0
    for shift in shifts:
        
        index = index + 1
        
        #shift = 2.0 # TEMP
        def shift_newpars():
            base_model.model['shift_hour'] = shift
            if reset == True:
                update_model_woReset(base_model,parameter_dict)
        shift_model_out = update_and_sim_model(base_model,shift_newpars)
    
        # Find shifted dawn and dusk times
        shift_dawn = base_dawn_time -9.5*(shift/24.0)
        shift_dawn_time = shift_dawn*(24/9.5)-264
        
        shift_dusk = base_dusk_time +9.5*(shift/24.0)
        shift_dusk_time = shift_dusk*(24/9.5)-264
    
        # Base 
        plt.plot(correct_time(shift_model_out['time'][base_time_idxs_middle],24/9.5,-264), shift_model_out['RPS6p'][base_time_idxs_middle], c=cm.plasma(color_num),linewidth=2.5)

        plt.xticks([-12,-6,0,6,12])
        if null_model == "Dusk":
            plt.axvline(x=-12,ymin=0.0,ymax=0.075-shift*0.01,color=cm.plasma(color_num),alpha=0.1*index)
        else:
            plt.axvline(x=-12+shift,ymin=0.0,ymax=0.075-shift*0.01,color=cm.plasma(color_num),alpha=0.1*index)
        if null_model == "Dawn":
            plt.axvline(x=0,ymin=0.0,ymax=0.075-shift*0.01,color=cm.plasma(color_num),alpha=0.1*index)
        else:
            plt.axvline(x=0-shift,ymin=0.0,ymax=0.075-shift*0.01,color=cm.plasma(color_num),alpha=0.1*index)
        plt.ylim(0.05,0.30)
        
        # Shift Color
        color_num = color_num - 1.0/len(shifts)
    
    # Labels
    plt.xlabel("Time")
    plt.xlim([-15.0,9.0])
    plt.ylabel("eS6-P")
示例#5
0
def amp_xs_compute_true_u(cb,
                          nsamples,
                          amp_line,
                          pi_line,
                          kc=1,
                          plot=False,
                          write=False):
    X = np.zeros((n_inputs))
    y = np.zeros((1))
    colors = iter(cm.plasma(np.arange(len(amp_line))))

    for amp in amp_line:
        for n in range(nsamples):
            filename = "%.2f_init_kc%d_%d" % (amp, kc, n)
            uu = cb.init_u(amp, phase=np.random.choice(pi_line))
            _, abs_work = LW_solver(uu,
                                    cb.itmax,
                                    filename=filename,
                                    write=write,
                                    plot=plot)

            for it in range(1, cb.itmax):
                u_curr = np.load(
                    osp.join(abs_work, filename + "_it%d.npy" % (it)))
                u_next = np.load(
                    osp.join(abs_work, filename + "_it%d.npy" % (it + 1)))

                for j in range(1, len(uu) - 1):
                    X = np.block([[X], add_block(u_curr, cb.line_x, j)])
                    y = np.block([[y], [u_next[j]]])

    X = np.delete(X, 0, axis=0)
    y = np.delete(y, 0, axis=0)

    return X, y
示例#6
0
    def animate(i):
        plt.title( str(timedelta(seconds=i * 30) + start_date) )

        lons = []
        lats = []
        vals = []
        for station in stations:
            for prn in ['G%02d' % x for x in range(1, 33)]:
                if prn not in vtec[station] or i >= len(vtec[station][prn][0]):
                    continue
                try:
                    ecef = vtec[station][prn][0][i]
                except IndexError:
                    print(station, prn, i)
                    raise
                if ecef is None:
                    continue
                lat, lon, _ = coordinates.ecef2geodetic(ecef)
                lon = lon if lon > 0 else lon + 360
                lons.append(lon)
                lats.append(lat)

                vals.append(vtec[station][prn][1][i])

        scatter.set_offsets(numpy.array(globe(lons, lats)).T)
        max_tec = 60
        scatter.set_color( cm.plasma(numpy.array(vals) / max_tec) )
示例#7
0
文件: wandb.py 项目: Ares2013/coreml
def plot2d(
    X: [torch.Tensor, np.ndarray],
    targets: List[Any],
    classes: List[str],
) -> List[wandb.Image]:
    """Returns a list of wandb.Image objects

    :param X: 2D array to visualize
    :type X: List[str]
    :param targets: ground truth integers used to color each point
    :type targets: List[Any]
    :param classes: list of classes representing ground truth
    :type classes: List[str]
    """
    targets = np.array([classes[target] for target in targets])
    unique_targets = np.unique(targets)
    colors = cm.plasma(np.linspace(0, 1, len(unique_targets)))

    f, ax = plt.subplots(1, figsize=(10, 10))

    for (i, target), color in zip(enumerate(unique_targets), colors):
        indices = np.where(targets == target)
        num = len(indices[0])
        ax.scatter(X[indices, 0],
                   X[indices, 1],
                   label='{} : {}'.format(target, num),
                   color=color)

    ax.set_ylabel('Component 2')
    ax.set_xlabel('Component 1')
    ax.grid()
    ax.legend(loc='best')
    image = wandb.Image(plt)
    plt.close()
    return image
示例#8
0
def plotModified(reference, histo, color=1):

    # plot original histogram (reference) with ones resampled from it (histo),
    # histo is either an array of histograms or a single histogram.
    # reference is a dataframe element.
    if color == 1:
        colors = [cm.viridis(i) for i in np.linspace(0, 1, len(histo))]
    elif color == 2:
        colors = [cm.plasma(i) for i in np.linspace(0, 1, len(histo))]
    else:
        colors = [cm.inferno(i) for i in np.linspace(0, 1, len(histo))]
    name = reference['hname']
    vmin = reference['Xmin']
    vmax = reference['Xmax']

    # create an array with x values, from x_min to x_max and length as input histogram
    x = vmin + (np.arange(len(histo[0]))) * float(
        (vmax - vmin) / float(len(histo[0])))
    x = x[1:-1]

    for i in range(len(histo)):
        plt.xlim(vmin, vmax)

        histo_todraw = histo[i][1:-1]

        #srun=df_plot.index.get_level_values('fromrun')[num]
        #slumi=df_plot.index.get_level_values('fromlumi')[num]

        plt.step(x,
                 histo_todraw,
                 where='mid',
                 label=(name + " LS " + str(reference['fromlumi']) + " Run " +
                        str(reference['fromrun'])),
                 color=colors[i])
示例#9
0
def dist2A(Apos, data, percentile, plot=False, histtype="step"):
    """
    Compute the of all points to each archetype
    in: 1.Apos[j,k] = position of all j archetypes and k dimensions
        2.data[i,k] = all i- sample points in k- dimensions
        3.Do you want to plot: True
        4. Which type of histogram: "bar", "stepfilled"
    out: dists[j,i] = distance of the i´th data point to the j´th archetype
    """
    #loop over all samples
    samples = np.shape(data)[0]
    n_a = np.shape(Apos)[0]
    dists = np.zeros((n_a, samples))
    archColors = cm.plasma(np.arange(n_a).astype(float) / (n_a))
    for j in range(0, n_a):
        for i in range(0, samples):
            dists[j, i] = np.linalg.norm(np.abs(data[i, :] - Apos[j, :]))
        dists[j, :] = dists[j, :] / max(dists[j, :])
    if plot == True:
        plt.figure()
        plt.title("Amount of points vs distance to archetype", fontsize=18)
        plt.xlabel("Normalized distance", fontsize=16)
        plt.ylabel("Amount of sample points", fontsize=16)
        for k in range(0, n_a):
            plt.hist(dists[k, :],
                     int(percentile * np.shape(dists)[1]),
                     color=archColors[k, :],
                     histtype=histtype,
                     label="A" + str(k))
        plt.legend()
        plt.tight_layout()
        plt.show()
    return (dists)
示例#10
0
    def animate(i):
        plt.title( str(timedelta(seconds=i * 30) + start_date) )

        lons = []
        lats = []
        vals = []
        for station in stations:
            for prn in get_data.satellites:
                if prn not in vtec[station] or i >= len(vtec[station][prn][0]):
                    continue
                try:
                    ecef = vtec[station][prn][0][i]
                except IndexError:
                    print(station, prn, i)
                    raise
                if ecef is None:
                    continue
                lat, lon, _ = coordinates.ecef2geodetic(ecef)
                lon = lon if lon > 0 else lon + 360
                lons.append(lon)
                lats.append(lat)

                vals.append(filtered[station][prn][i])

        scatter.set_offsets(numpy.array((lons, lats)).T)
        max_tec = 0.1
        min_tec = -0.1
        scatter.set_color( cm.plasma(numpy.maximum(numpy.array(vals) - min_tec, 0) / (max_tec - min_tec)) )
def generational_histogram(
    rootdir: Path,
    n_bins: int = 20,
    min_gen: int = 0,
    show: bool = True,
):
    # OPTIMIZE: only scrape the ones with gen > min_gen
    data: Dict[GeneRunID, float] = scrape_extracted_cache(rootdir)

    # first make bins based on all data
    bins, bin_centers = get_bins(data, n_bins)

    # sort by generation
    data_sorted: DefaultDict[int, List[float]] = sort_by_generation(data)

    # plot each generation
    gen_count: int = max(data_sorted.keys())
    colors = cm.plasma(np.linspace(0, 1, gen_count - min_gen))  # type: ignore

    for gen_k in range(min_gen, gen_count):
        lst_v: List[float] = data_sorted[gen_k]

        hist, _ = np.histogram(lst_v, bins)
        plt.plot(
            bin_centers,
            hist,
            '-',
            label=f"gen_{gen_k}",
            color=colors[gen_k - min_gen],
        )

    plt.legend()

    if show:
        plt.show()
示例#12
0
def plotme(regression, ytypes, y, h=0.2):
    if regression[0].canPlot():
        new_x = regression[0].get_x()
        x_min, x_max = new_x[:, 1].min() - .5, new_x[:, 1].max() + .5
        y_min, y_max = new_x[:, 2].min() - .5, new_x[:, 2].max() + .5
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                             np.arange(y_min, y_max, h))

        fig1 = plt.figure("multi class")

        Z = [
            regression[i].predict(np.c_[xx.ravel(), yy.ravel()], scale=False)
            for i in range(ytypes.size)
        ]

        colors = cm.plasma(np.linspace(0, 1, ytypes.size))

        for i in range(ytypes.size):
            Z[i] = Z[i].reshape(xx.shape)
            plt.contour(xx,
                        yy,
                        Z[i],
                        levels=[0.5],
                        colors=(tuple(colors[i]), 0))

        plt.scatter(new_x[:, 1], new_x[:, 2], c=y, cmap=cm.plasma)
        plt.xlim(xx.min(), xx.max())
        plt.ylim(yy.min(), yy.max())
        plt.xticks(())
        plt.yticks(())

        fig1.show()
示例#13
0
    def run_Model(self, reef, input_vector):
        reef.convert_vector(self.communities, input_vector, self.sedsim,
                            self.flowsim)  #model.py
        self.initial_sed, self.initial_flow = reef.load_xml(
            self.input, self.sedsim, self.flowsim)

        if self.vis[0] == True:
            reef.core.initialSetting(size=(8, 2.5),
                                     size2=(8, 3.5))  # View initial parameters
        reef.run_to_time(self.simtime, showtime=100.)
        if self.vis[1] == True:
            from matplotlib.cm import terrain, plasma
            nbcolors = len(reef.core.coralH) + 10
            colors = terrain(np.linspace(0, 1.8, nbcolors))
            nbcolors = len(reef.core.layTime) + 3
            colors2 = plasma(np.linspace(0, 1, nbcolors))
            reef.plot.drawCore(lwidth=3,
                               colsed=colors,
                               coltime=colors2,
                               size=(9, 8),
                               font=8,
                               dpi=300)
        output_core = reef.plot.core_timetodepth(
            self.communities, self.core_depths)  #modelPlot.py
        # predicted_core = reef.convert_core(self.communities, output_core, self.core_depths) #model.py
        # return predicted_core
        print('output_core_shape', output_core.shape)
        return output_core
示例#14
0
def show_multi_output_mpl(df):
    register_matplotlib_converters()
    cols_list = []
    for column in df.columns:
        if 'raw' in column or 'treated' in column:
            cols_list.append(column)
    fig, axes = plt.subplots(figsize=(20, 10),
                             nrows=len(cols_list) + 1,
                             ncols=1)
    plt.rc('lines', linewidth=0.5)
    color = iter(cm.plasma(np.linspace(0.05, 0.8, len(cols_list) + 1)))

    fig.subplots_adjust(hspace=0.5)
    fig.suptitle('Output of multivariate filter')
    axes_array = np.array(axes).flatten()
    for ax, feature in zip(axes_array, cols_list):

        ax.plot(df.index, df[feature], c=next(color))
        ax.set(ylabel=feature.split(' ')[0].upper())
        ax.tick_params(axis='x', which='both', bottom=False, labelbottom=False)

    ax = axes_array[-1]
    ax.plot(df.index, df['fault_count'], c='k')
    ax.set(ylabel='fault count', xlabel='Date')
    ax.set_xticklabels(df.index, rotation=45)
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %y'))
    plt.show()
示例#15
0
 def solve(self):
     gui = ti.GUI('lbm solver', (self.nx, 2 * self.ny))
     self.init()
     for i in range(self.steps):
         self.collide_and_stream()
         self.update_macro_var()
         self.apply_bc()
         ##  code fragment displaying vorticity is contributed by woclass
         vel = self.vel.to_numpy()
         ugrad = np.gradient(vel[:, :, 0])
         vgrad = np.gradient(vel[:, :, 1])
         vor = ugrad[1] - vgrad[0]
         vel_mag = (vel[:, :, 0]**2.0 + vel[:, :, 1]**2.0)**0.5
         ## color map
         colors = [(1, 1, 0), (0.953, 0.490, 0.016), (0, 0, 0),
                   (0.176, 0.976, 0.529), (0, 1, 1)]
         my_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
             'my_cmap', colors)
         vor_img = cm.ScalarMappable(norm=matplotlib.colors.Normalize(
             vmin=-0.02, vmax=0.02),
                                     cmap=my_cmap).to_rgba(vor)
         vel_img = cm.plasma(vel_mag / 0.15)
         img = np.concatenate((vor_img, vel_img), axis=1)
         gui.set_image(img)
         gui.show()
         if (i % 1000 == 0):
             print('Step: {:}'.format(i))
示例#16
0
def show_pca_mpl(df, limits):
    fig, ax = plt.subplots(figsize=(10, 10), nrows=1, ncols=1)
    plt.rc('lines', linewidth=1)
    color = iter(cm.plasma(np.linspace(0, 1, 4)))
    start = limits['start_cal']
    end = limits['end_cal']
    ax.plot(df['pc_1'], df['pc_2'], 'o', markersize=0.5, c=next(color))
    ax.plot(df['pc_1'].loc[start:end],
            df['pc_2'].loc[start:end],
            'o',
            markersize=0.5,
            c=next(color))
    ax.set(ylabel='PC 2',
           xlabel='PC 1',
           title='Principal components of calibration and complete data sets')
    # ### drawing the ellipse

    ellipse_a = np.sqrt(limits['T2']) * limits['pc_std'][0]
    ellipse_b = np.sqrt(limits['T2']) * limits['pc_std'][1]
    t = np.linspace(0, 2 * np.pi, 100)

    ax.plot(ellipse_a * np.cos(t), ellipse_b * np.sin(t), c=next(color))
    ax.grid(which='major', axis='both')
    ax.legend(['complete', 'calibration', 'limit {}'.format(limits['alpha'])])
    plt.gca().set_aspect('equal')
    plt.show()
示例#17
0
    def solve(self):
        gui = ti.GUI('lbm solver', (self.nx, self.ny * 2))
        self.init()
        for i in range(self.steps):
            self.collide_and_stream()
            self.update_macro_var()
            self.apply_bc()
            self.get_display_var()

            ## vor
            vel = self.vel.to_numpy()
            ugrad = np.gradient(vel[:, :, 0])
            vgrad = np.gradient(vel[:, :, 1])
            du_dy = ugrad[1]
            dv_dx = vgrad[0]
            ## vor = dv/dx - du/dy
            vor = dv_dx - du_dy
            ## 颜色映射
            colors = [(1, 1, 0), (0.953, 0.490, 0.016), (0, 0, 0),
                      (0.176, 0.976, 0.529), (0, 1, 1)]
            my_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
                'my_cmap', colors)
            vor_img = cm.ScalarMappable(cmap=my_cmap).to_rgba(vor)
            vel_img = cm.plasma(self.display_var.to_numpy() / 0.15)

            # numpy 的 y 方向貌似和 taichi 相反
            img = np.concatenate((vor_img, vel_img), axis=1)
            gui.set_image(img)

            # gui.show()
            gui.show(f'frame/{i:04d}.png')

            if (i % 1000 == 0):
                print('Step: {:}'.format(i))
示例#18
0
def blocked_feature_decay(decay, blocks, dists, gene_names, i_max, atype,
                          featuretype, plot):
    """
    Block averaging of an input vector.
    IN:
     decay[2,n_samples] = array to block average (decay[0,:]=x-Axis, decay[1,:]=y-Axis)
     blocks = Number of blocks to block average the input vector
     For plotting:atype (0-noc) archetype to which the task decays
                  featuretype(0-m_tasks) decay of feature under consideration
    OUT:
     blockvec[blocks] = block averaged input vector y-Axis elements
     blocktt[blocks]  = x-Axis elements according to blockvec 
     error = statistical error in every block
     sigmaB
     bdata = number of elements compressed in every block
    """
    blockvec, blocktt, error, sigmaB, bdata = blocking(decay[0, :],
                                                       decay[1, :],
                                                       blocks=blocks)

    if (plot == True):
        n_a = np.shape(dists)[0]
        name = gene_names.iloc[i_max[atype, featuretype]]
        archColors = cm.plasma(np.arange(n_a).astype(float) / (n_a))
        plt.figure()
        plt.plot(blocktt, blockvec, '-*', c=archColors[atype, :])
        plt.suptitle(f"Blocked decay with respect to distance of A{atype}",
                     fontsize=14)
        plt.title(f"{name}", fontsize=8)
        plt.xlabel(f"Normalized distance of samples to A{atype}", fontsize=14)
        plt.ylabel(f"Amount in samples", fontsize=14)
        plt.show()
    return blockvec, blocktt, error, sigmaB, bdata
示例#19
0
    def __init__(self,
                 board_size: int,
                 num_players: int,
                 window_size: Tuple[int, int] = (600, 600),
                 outside_border: int = 25,
                 grid_space_ratio: float = 6,
                 winner_player: int = None):
        self.board_size = board_size
        self.window_size = window_size
        self.outside_border = outside_border
        self.grid_space_ratio = grid_space_ratio

        self.winner_player = winner_player
        if winner_player is not None:
            self.other_players = (np.arange(num_players - 1) + winner_player +
                                  1) % num_players

        self.colors = cm.plasma(np.linspace(0.1, 0.9, num_players))
        self.colors = np.minimum(self.colors * 1.3, 1.0)

        # Rendering Objects
        self.viewer = None
        self.grid = None
        self.flat_grid = None
        self.background = None
示例#20
0
文件: display.py 项目: gkbxs/Parakeet
def add_multi_attention_plots(writer, tag, attention_weights, global_step):
    attns = [attn[0].numpy() for attn in attention_weights]
    for i, attn in enumerate(attns):
        img = pack_attention_images(attn)
        writer.add_image(f"{tag}/{i}",
                         cm.plasma(img),
                         global_step=global_step,
                         dataformats="HWC")
示例#21
0
    def animate(i):
        plt.title(str("%0.2f" % (24 * i / 2880)))
        lon = lons[i]
        lat = lats[i]
        val = values[i]

        scatter.set_offsets(numpy.array(globe(lon, lat)).T)

        scatter.set_color(cm.plasma(numpy.array(val) / 8))
示例#22
0
def twoDimRepr(exp_id, model_id, start_epoch, paramPlot, plotRange):
    ''' Plot parameters trajectory across training epochs of a model.

    The trajectories are ploted using t-sne and PCA representation

    Args:
        exp_id (str): the experience name
        model_id (str): the model id
        start_epoch (int): the epoch at which to start the plot
        paramPlot (list): the parameters to plot (can be \'trueScores\', \'bias\', \'incons\' or \'diffs\'.)
        plotRange (list): the axis limits to use. It should be a list of values like this (xMin,xMax,yMin,yMax).
    '''
    def getEpoch(path):
        return findNumbers(
            os.path.basename(path).replace("model{}".format(model_id), ""))

    cleanNamesDict = {
        "trueScores": "True Scores",
        "bias": "Biases",
        "diffs": "Ambiguities",
        "incons": "Inconsistencies"
    }

    for key in paramPlot:
        paramFiles = sorted(glob.glob(
            "../results/{}/model{}_epoch*_{}.csv".format(
                exp_id, model_id, key)),
                            key=findNumbers)

        paramFiles = list(
            filter(lambda x: getEpoch(x) > start_epoch, paramFiles))
        colors = cm.plasma(np.linspace(0, 1, len(paramFiles)))

        params = list(map(lambda x: np.genfromtxt(x)[:, 0], paramFiles))

        repr_tsne = TSNE(n_components=2,
                         init='pca',
                         random_state=1,
                         learning_rate=20).fit_transform(params)
        repr_pca = PCA(n_components=2).fit_transform(params)

        plt.figure()
        plt.title("model " + str(model_id) + " : " + cleanNamesDict[key])
        plt.scatter(repr_tsne[:, 0], repr_tsne[:, 1], color=colors, zorder=2)
        plt.savefig("../vis/{}/model{}_{}_tsne.png".format(
            exp_id, model_id, key))

        plt.figure()
        plt.xlabel("First principal component")
        plt.ylabel("Second principal component")
        plt.title("model " + str(model_id) + " : " + cleanNamesDict[key])
        plt.scatter(repr_pca[:, 0], repr_pca[:, 1], color=colors, zorder=2)
        if plotRange:
            plt.xlim(plotRange[0], plotRange[1])
            plt.ylim(plotRange[2], plotRange[3])
        plt.savefig("../vis/{}/model{}_{}_pca.png".format(
            exp_id, model_id, key))
示例#23
0
def plotArch(red_data, XC, noc):
    """
    Visualize the position of archetypes and sample points in 3PC- projection
    Note: For noc > 5 the verts_list(XC) function might has to be updated
    in:     1. red_data[i,j]; i = samples, j = principle components (coordinates)
            2. XC = output of PCHA Position of Archetypes
            3. Number of components >= 6
    """
    n_archetypes = np.shape(XC)[1]
    dim = np.shape(XC)[0]
    archColors = cm.plasma(
        np.arange(n_archetypes).astype(float) / (n_archetypes))

    if dim == 3:
        verts = verts_list(XC)
        srf = Poly3DCollection(verts, alpha=.25, facecolor='#800000')
        fig = plt.figure()
        #if np.shape(red_data)[1] == 3:
        ax = fig.add_subplot(111, projection='3d')
        ax.scatter(red_data[:, 0], red_data[:, 1], red_data[:, 2], c="k", s=5)
        #ax.scatter(XC[0,:],XC[1,:],XC[2,:],c = "k",s=70)
        for i in range(0, noc):
            ax.scatter(XC[0, i],
                       XC[1, i],
                       XC[2, i],
                       s=70,
                       c=archColors[i, :],
                       label="A" + str(i))
        ax.add_collection3d(srf)
        ax.set_xlabel('1st pca component', fontsize=14)
        ax.set_ylabel('2nd pca component', fontsize=14)
        ax.set_zlabel('3rd pca component', fontsize=14)
        ax.legend()
        plt.tight_layout()
        plt.show()
    if dim == 2 and n_archetypes == 3:
        verts = np.squeeze(np.asarray(verts_list(XC)))
        verts = np.reshape(verts, (-1, 2))
        verts = list(verts)

        surf = plt.Polygon(XC.T, color='#800000', alpha=.25)
        fig = plt.figure()
        #if np.shape(red_data)[1] == 3:
        ax = fig.add_subplot(111)
        ax.scatter(red_data[:, 0], red_data[:, 1], c="k", s=5)
        for i in range(0, noc):
            ax.scatter(XC[0, i],
                       XC[1, i],
                       s=70,
                       c=archColors[i, :],
                       label="A" + str(i))
        plt.gca().add_patch(surf)
        ax.set_xlabel('1st pca component', fontsize=14)
        ax.set_ylabel('2nd pca component', fontsize=14)
        ax.legend()
        plt.tight_layout()
        plt.show()
示例#24
0
def sradcmap():
    # This function returns the colormap and bins for the PM spatial plots
    # this is designed to have a vmin =0 and vmax = 140
    # return cmap,bins
    colors1 = cm.viridis(linspace(0, 1, 128))
    colors2 = cm.plasma(linspace(.2, 1, 128))
    colors = vstack((colors1, colors2))
    return mcolors.LinearSegmentedColormap.from_list('sradcmap',
                                                     colors), arange(
                                                         0, 1410., 10)
示例#25
0
 def color_within_01(vals):
     # vals is Nx1 in [-1, 1] (but could be larger)
     vals = np.clip(vals, -1, 1)
     # make [0, 1]
     vals = (vals + 1) / 2.
     # Append dummy end vals for consistent coloring
     weights = np.hstack([vals, np.array([0, 1])])
     # Drop the dummy colors
     colors = cm.plasma(weights)[:-2, :3]
     return colors
示例#26
0
def load_mydelta_and_strat(fname, accel):
    if np.isclose(accel, 5.):
        Q_in = Q_options[0]
    elif np.isclose(accel, 10.):
        Q_in = Q_options[1]
    elif np.isclose(accel, 20.):
        Q_in = Q_options[2]
    else:
        raise NameError

    if np.isclose(accel, 20.):
        len_drift = 400.
    else:
        len_drift = 600.
    drift_up = np.arange(len_drift, dtype=float) / len_drift * (
        accel * Uinit - Q_in[-1]) + Q_in[-1]
    Q_real = np.concatenate((Uinit * np.ones(400), Q_in, drift_up))
    Q_real *= flux_scaling
    # ^does this need adjusting for dt?

    # add the subsidence curve. Same idea
    SL_rate = np.concatenate(
        (Uinit * np.ones(400), accel * Uinit * np.ones(1200)))
    SL_trajectory = np.cumsum(SL_rate)
    # DO NOT multiply by dt. Let's just scale everything to dt = 1 for now.
    # add an initial water depth if necessary here:
    SL_trajectory += 0.1

    # load it up
    f = open(fname, 'rb')
    mydelta = pickle.load(f)
    f.close()

    # do the plot
    color = [item / Q_real.max() for item in Q_real]
    for i in xrange(num_pres_strata):
        plot(mydelta.radial_distances,
             mydelta.strata[i, :],
             c=cm.plasma(color[i]))

    # pick the rollovers & add them to the fig:
    for i in xrange(num_pres_strata):
        # fit a (SF-ST) angle line to each point. rollover is point with
        # largest intersect
        # remove unmodified floor:
        notfloor = np.where(
            np.logical_not(np.isclose(mydelta.strata[i, :], 0.)))[0]
        c = ((SF - ST) * mydelta.radial_distances[notfloor] +
             mydelta.strata[i, notfloor])
        diff = np.diff(c)
        rollover_subindexes = np.where(
            np.diff((diff < 0.).astype(int)) == 1)[0]
        rollover_index = notfloor[rollover_subindexes]
        plot(mydelta.radial_distances[rollover_index],
             mydelta.strata[i, rollover_index], 'k,')
示例#27
0
def gene_expr_A(A_gene_space,
                gene_names,
                percentile,
                plot=False,
                rows=2,
                cols=2):
    """
    Finding the maxima in gene expressions, i.e. where in the gene space
    do we find maxima, if we look at the Archetypes
    in:     1. A_gene_space[i,k]; i = number of archetype; k = gene space
            2. Names of all the gene expressions
            3. Percentile <=1; which percentile of the maximum is considered
            4. Do you want to plot the histogram?
            5.Number of rows in the figure
            6.Number of columns in the figure
    out:    A_i_maxd[i,k]: For archetype i, which genes k are over represented
            This matrix has zeros, to match dimensions!
    """
    g_dim = np.shape(A_gene_space)[1]
    n_A = np.shape(A_gene_space)[0]
    i_max = np.zeros((n_A, 30))
    A_i_max = np.zeros((n_A, 30))
    A_i_names = [
    ]  #Output the names of the corresponding attributes with gne_names
    #Minus because we want the biggest first and argsort(.) is in ascending order
    sorted_expressions = np.argsort(-A_gene_space, axis=1)
    archColors = cm.plasma(np.arange(n_A).astype(float) / (n_A))
    #Evaluate maxima
    for i in range(0, n_A):
        i_max = np.where(
            A_gene_space[i, :] >= percentile * max(A_gene_space[i, :]))[0]
        #Put maxima in a list
        for k in range(0, len(i_max)):
            A_i_max[i, k] = i_max[k]
        non0 = A_i_max[i, np.nonzero(A_i_max[i, :])][0]
        non0 = non0.astype(int)
        for j in range(0, len(non0)):
            gene_index = non0[j]
            A_i_names = np.append(A_i_names,
                                  (gene_names.iloc[gene_index], "\t"))
        A_i_names = np.append(A_i_names, "\n")
    if plot == True:
        g_space = np.arange(0, g_dim)
        fig = plt.figure()
        for i in range(0, n_A):
            non0 = A_i_max[i, np.nonzero(A_i_max[i, :])][0]
            non0 = non0.astype(int)
            ax = fig.add_subplot(rows, cols, i + 1)
            ax.scatter(g_space, A_gene_space[i, :], c="k")
            ax.scatter(non0, A_gene_space[i, non0], c=archColors[i, :])
            ax.set_xlabel("Expression Spectrum")
            ax.set_ylabel("Amount")
            ax.set_title(f"Archetype {i}")
        fig.tight_layout()
    return (A_i_max.astype(int), A_i_names, sorted_expressions)
示例#28
0
def feature_decay(gene_data_m,
                  gene_names,
                  dists,
                  i_max,
                  atype,
                  featuretype,
                  plot=False):
    """
    Decay of a specific feature in the samples, that is maximally represented in the position
    of the Archetype, with respect to the normalized distance to the Archetype. 
    In:     1. gene_data_m[i,j] matrix of gene data. i = samples; j = characteristics
            2. gene_names[j] list of the gene names
            3. dists is output of dist2A(.)- function, i.e. for each sample point the distance to respective archetype
            4. i_max is output of gene_expr_A(.), i.e array of indices of maximally expressed gene characteristics of archetypes
            5. atype = n = integer. Which archetype to look at (0,1,2,...)
            6. featuretype = which of the maximized features to look at. Which of the indices m from i_max[n,m]
            7. Do you want to plot? True
    Out: decay[2,i]: A list of sample points where decay[1,i] are the distances to archetype n and decay[2,i] is the decay of the feature under investigation  
    """
    n_a = np.shape(dists)[0]
    archColors = cm.plasma(np.arange(n_a).astype(float) / (n_a))
    a_sorted = np.zeros_like(dists)
    for i in range(0, n_a):
        a_sorted[i, :] = np.argsort(dists[i, :])
    a_sorted = a_sorted.astype(int)
    featuredecay = gene_data_m[a_sorted[atype, :], i_max[atype, featuretype]]
    featuredist = dists[atype, a_sorted[atype, :]]
    name = gene_names.iloc[i_max[atype, featuretype]]
    decay = np.concatenate((featuredist, featuredecay), axis=0)
    decay = np.reshape(decay, (2, len(featuredecay)))
    #print(f"Decay of gene feature {name} with respect to normalized distance from archetype {atype} is under consideration.")
    if plot == True:
        archColors = cm.plasma(np.arange(n_a).astype(float) / (n_a))
        plt.figure()
        plt.plot(featuredist, featuredecay, "*-", c=archColors[atype, :])
        plt.suptitle(f"Decay with respect to distance of A{atype}",
                     fontsize=14)
        plt.title(f"{name}", fontsize=8)
        plt.xlabel(f"Normalized distance of samples to A{atype}", fontsize=14)
        plt.ylabel(f"Amount task/gene in samples", fontsize=14)
        plt.show()
    return (decay)
示例#29
0
def index():

    df = pd.read_csv('300_5000.csv')
    lst1 = df['7'].abs()

    df = pd.read_csv('300_5000.csv')
    lst2 = df['8']

    df = pd.read_csv('300_5000.csv')
    lst3 = df['9']

    fig = plt.figure
    fig, ax = plt.subplots()
    ax.set_xlim(lst2.min(), lst2.max() + 0.8)

    ims = []

    for i, n, g in zip(lst3, lst1, lst2):
        x1 = 3
        y1 = i
        x2 = 1
        y2 = n
        x3 = 2
        y3 = g

        im3 = plt.barh(x3, y3, color=cm.plasma(g / lst1.max()))
        im2 = plt.barh(x2, y2, color=cm.plasma(n / lst1.max()))
        im = plt.barh(x1, y1, color=cm.plasma(i / lst1.max()))

        ims.append(im3 + im2 + im)
        plt.title("D")

    anim = animation.ArtistAnimation(fig, ims)

    FPS = 30

    anim.save('static/img/anim' + str(FPS) + '.gif',
              writer="imagemagick",
              fps=FPS)

    return render_template("index.html",
                           image='static/img/anim' + str(FPS) + '.gif')
def decode_confidence_map_sequence(confidence_maps):
    conf_maps = []
    confidence_maps = confidence_maps.transpose([0, 2, 3, 1])
    for conf in confidence_maps:
        conf = conf.reshape(conf.shape[0], conf.shape[1])
        colored_image = cm.plasma(conf)
        colored_image = Image.fromarray(
            (colored_image[:, :, :3] * 255).astype(np.uint8))
        conf_maps.append(np.array(colored_image))
    conf_maps = torch.from_numpy(np.array(conf_maps).transpose([0, 3, 1, 2]))
    return conf_maps
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Feb  5 20:47:15 2018

@author: reini
"""

from __future__ import print_function
from matplotlib import cm
import numpy as np


def rgb_hex565(red, green, blue):
    # take in the red, green and blue values (0-255) as 8 bit values and then combine
    # and shift them to make them a 16 bit hex value in 565 format. 
    print ("0x%0.4X," % ((int(red * 31) << 11) | (int(green * 63) << 5) | (int(blue * 31))),end='')

rgb = cm.plasma(np.arange(256))
for i in np.arange(rgb.shape[0]):
    rgb_hex565(rgb[i][0],rgb[i][1],rgb[i][2])
示例#32
0
def main():
    dirname = os.path.basename(os.getcwd())

    config_file = parse_input()
    config = loadconfig(config_file)

    sdf_handles = []
    sdf_files = config['sdf_files']
    if type(sdf_files) is not type([]):
        sdf_files = [sdf_files,]

    for sdf_file in sdf_files:
        try:
            sdf_data = sdf.read(sdf_file)
        except:
            print("Warning: Failed to open '{}'".format(sdf_file))
        else:
            sdf_handles.append(sdf_data)

    if len(sdf_handles) < 1:
        print("Error: Unable to open any sdf files")
        print("Exiting....")
        return(-1)

    #load sdf data (needs to be done before we can sanity check input)
    sdf_e_px = getattr_from_any(sdf_handles, 'Particles_Px_electron').data
    sdf_e_x = getattr_from_any(sdf_handles, 'Grid_Particles_electron').data[0]
    sdf_e_y = getattr_from_any(sdf_handles, 'Grid_Particles_electron').data[1]
    sdf_e_w = getattr_from_any(sdf_handles, 'Particles_Weight_electron').data
    sdf_gridx = getattr_from_any(sdf_handles, 'Grid_Grid').data[0]
    sdf_gridy = getattr_from_any(sdf_handles, 'Grid_Grid').data[1]
    sdf_dens = getattr_from_any(sdf_handles, 'Derived_Number_Density_electron').data
    try:
        sdf_gridz = getattr_from_any(sdf_handles, 'Grid_Grid').data[2]
        sdf_e_z = getattr_from_any(sdf_handles, 'Grid_Particles_electron').data[2]
        is3d = True
    except:
        is3d = False

    grids =  {'xgrid':None
                ,'ygrid':None
                ,'zgrid':None
                ,'xbins':None
                ,'ybins':None
                ,'zbins':None}
    for grid in grids:
        try:
            grids[grid] = float(config[grid])
        except:
            pass

    if ((grids['xgrid'] is not None and grids['xbins'] is not None) or
       (grids['ygrid'] is not None and grids['ybins'] is not None) or
       (grids['zgrid'] is not None and grids['zbins'] is not None)):
        print("Both gridsize and numbins are specified... "
              "gridsize will take precedence")

    if ((grids['xgrid'] is None and grids['xbins'] is None) or
       (grids['ygrid'] is None and grids['ybins'] is None)):
        print("Warning no gridsize or numbins specified, defaulting to "
              "100 bins")
        if grids['xbins'] is None:
            grids['xbins'] = 100
        if grids['ybins'] is None:
            grids['ybins'] = 100
    
    if is3d and (grids['zgrid'] is None and grids['zbins'] is None):
        print("Warning no gridsize or numbins specified, defaulting to "
              "100 bins")
        grids['zbins'] = 100
    
    try:
        output_name = config['output_name']
    except:
        output_name = 'out'

    try:
        output_path = config['output_path']
    except:
        output_path = '.'

    try:
        pub_xmin = float(config['pub_xmin'])*1e6
    except:
        pub_xmin = None
    try:
        pub_xmax = float(config['pub_xmax'])*1e6
    except:
        pub_xmax = None
    try:
        pub_ymin = float(config['pub_ymin'])
    except:
        pub_ymin = None
    try:
        pub_ymax = float(config['pub_ymax'])
    except:
        pub_ymax = None

    reset_origin = False
    if 'reset_origin' in config:
        if not 'false'.startswith(config['reset_origin'].lower()):
            reset_origin = True

    lineout_inset = False
    if 'lineout_inset' in config:
        if not 'false'.startswith(config['lineout_inset'].lower()):
            lineout_inset = True
    try:
        lineout_xmin = float(config['lineout_xmin'])*1e6
    except:
        lineout_xmin = None
    try:
        lineout_xmax = float(config['lineout_xmax'])*1e6
    except:
        lineout_xmax = None
    try:
        lineout_ymin = float(config['lineout_ymin'])
    except:
        lineout_ymin = None
    try:
        lineout_ymax = float(config['lineout_ymax'])
    except:
        lineout_ymax = None
 
    cutoff_px = float(config['cutoff_px']) * sc.m_e * sc.c

    extents = {'xmin':sdf_e_x.min()
             ,'xmax':sdf_e_x.max()
             ,'ymin':sdf_e_y.min()
             ,'ymax':sdf_e_y.max()}
    if is3d:
        extents['zmin'] = sdf_e_z.min()
        extents['zmax'] = sdf_e_z.max()
 
    #parse in spatial limits and sanity check
    limits = {}
    for extent in extents:
        try:
            limits[extent] = float(config[extent])
        except:
            limits[extent] = extents[extent]
        
    if limits['xmax'] < limits['xmin']:
        limits['xmin'], limits['xmax'] = limits['xmax'], limits['xmin'] 
    if limits['ymax'] < limits['ymin']:
        limits['ymin'], limits['ymax'] = limits['ymax'], limits['ymin'] 
    if is3d:
        if limits['zmax'] < limits['zmin']:
            limits['zmin'], limits['zmax'] = limits['zmax'], limits['zmin'] 

    for extent in limits:
        if extent.endswith('max'):
            if limits[extent] > extents[extent]:
                limits[extent] = extents[extent]
                print("Warning {} out of range, ignoring".format(extent))
        else:
            if limits[extent] < extents[extent]:
                limits[extent] = extents[extent]
                print("Warning {} out of range, ignoring".format(extent))

    #parse in ellipse parameters and sanity check
    ellipse_sane = False
    ell = {'centerx':None, 'radx':None, 
           'centery':0.0, 'rady':None}
    if is3d:
        ell['centerz'] = 0.0
        ell['radz'] = None
    for arg in ell:
        try:
            ell[arg] = float(config['ell_{}'.format(arg)])
        except:
            pass
    if None not in ell.values():
        ellipse_sane = True

        if ((ell['centerx'] + ell['radx'] < limits['xmin']) 
        or (ell['centerx'] - ell['radx'] > limits['xmax'])
        or (ell['centery'] + ell['rady'] < limits['ymin']) 
        or (ell['centery'] - ell['rady'] > limits['ymax'])):
            print("Error, ellipse is entirely outside of view window")
            return(-1)
        if ((ell['centerx'] - ell['radx'] < limits['xmin']) 
        or (ell['centerx'] + ell['radx'] > limits['xmax'])
        or (ell['centery'] - ell['rady'] < limits['ymin']) 
        or (ell['centery'] + ell['rady'] > limits['ymax'])):
            print("Warning, ellipse is clipped by view window")

        if is3d:
            if ((ell['centerz'] + ell['radz'] < limits['zmin']) 
            or (ell['centerz'] - ell['radz'] > limits['zmax'])):
                print("Error, ellipse is entirely outside of view window")
                return(-1)
            if ((ell['centerz'] - ell['radz'] < limits['zmin']) 
            or (ell['centerz'] + ell['radz'] > limits['zmax'])):
                print("Warning, ellipse is clipped by view window")
                


    #trim grid data to specfied limits
    xargmin = np.argmin(np.abs(sdf_gridx - limits['xmin']))
    xargmax = np.argmin(np.abs(sdf_gridx - limits['xmax']))
    yargmin = np.argmin(np.abs(sdf_gridy - limits['ymin']))
    yargmax = np.argmin(np.abs(sdf_gridy - limits['ymax']))
    if is3d:
        zargmin = np.argmin(np.abs(sdf_gridz - limits['zmin']))
        zargmax = np.argmin(np.abs(sdf_gridz - limits['zmax']))

    sdf_gridx = sdf_gridx[xargmin:xargmax]
    sdf_gridy = sdf_gridy[yargmin:yargmax]
    sdf_dens = sdf_dens[xargmin:xargmax,yargmin:yargmax]
    if is3d:
        sdf_gridz = sdf_gridz[zargmin:zargmax]
        sdf_dens = sdf_dens[:,:,zargmin:zargmax]

    #take on axis density slice for plotting
    if is3d:
        plot_dens_xy = sdf_dens[:,:,int(0.5*sdf_dens.shape[2])]
        plot_dens_xz = sdf_dens[:,int(0.5*sdf_dens.shape[1]),:]
    else:
        plot_dens_xy = sdf_dens


    ### Electron selection magic happens here

    energy_mask = sdf_e_px > cutoff_px
    position_mask = np.full(sdf_e_px.shape, True, dtype=bool)
    if ellipse_sane:
        if is3d:
            position_mask = ( 
            ((sdf_e_x - ell['centerx'])**2 / (ell['radx']**2)) +
            ((sdf_e_y - ell['centery'])**2 / (ell['rady']**2)) +
            ((sdf_e_z - ell['centerz'])**2 / (ell['radz']**2)) < 1 )
        else:
            position_mask = (
            ((sdf_e_x - ell['centerx'])**2 / (ell['radx']**2)) +
            ((sdf_e_y - ell['centery'])**2 / (ell['rady']**2)) < 1 )

    bunch_electron_mask = np.where(np.logical_and(energy_mask,
                                                position_mask))


    bunch_electron_x = sdf_e_x[bunch_electron_mask].reshape(-1)
    bunch_electron_y = sdf_e_y[bunch_electron_mask].reshape(-1)
    bunch_electron_w = sdf_e_w[bunch_electron_mask].reshape(-1)
    if is3d:
        bunch_electron_z = sdf_e_z[bunch_electron_mask].reshape(-1)

    print("Found {} particles meeting criteria".format(len(bunch_electron_w)))


### Histogram Grid creation ###

    if grids['xgrid'] is not None:
        xbins = np.arange(limits['xmin'],limits['xmax']+grids['xgrid'],grids['xgrid'])
    else:
        xbins = np.linspace(limits['xmin'],limits['xmax'],grids['xbins'])

    if grids['ygrid'] is not None:
        if limits['ymin'] * limits['ymax'] < 0:
            ybins = np.sort(np.concatenate((
                np.arange(0,limits['ymin']-grids['ygrid'],-grids['ygrid']),
                np.arange(grids['ymin'],limits['ymax']+grids['ygrid'],grids['ygrid']))))

        else:
            ybins = np.arange(limits['ymin'],limits['ymax']+grids['ygrid'],grids['ygrid'])
    else:
        if limits['ymin'] * limits['ymax'] < 0:
            ybins = np.sort(np.concatenate((
                np.linspace(limits['ymin'],0,grids['ybins']//2),
                np.linspace(0,limits['ymax'],grids['ybins']//2)[1:])))
        else:
            ybins = np.linspace(limits['ymin'],limits['ymax'],grids['ybins'])
    
    if is3d:
        if grids['zgrid'] is not None:
            if limits['zmin'] * limits['zmax'] < 0:
                zbins = np.sort(np.concatenate((
                    np.arange(0,limits['zmin']-grids['zgrid'],-grids['zgrid']),
                    np.arange(grids['zmin'],limits['zmax']+grids['zgrid'],grids['zgrid']))))

            else:
                zbins = np.arange(limits['zmin'],limits['zmax']+grids['zgrid'],grids['zgrid'])
        else:
            if limits['zmin'] * limits['zmax'] < 0:
                zbins = np.sort(np.concatenate((
                    np.linspace(limits['zmin'],0,grids['zbins']//2),
                    np.linspace(0,limits['zmax'],grids['zbins']//2)[1:])))
            else:
                zbins = np.linspace(limits['zmin'],limits['zmax'],grids['ybins'])

    
    
    display_limits = [ limits[l]*1e6 for l in ['xmin','xmax','ymin','ymax'] ]


### Histogram Creation ###

    if is3d:
        pos_data_3d = np.column_stack([bunch_electron_x
                                      ,bunch_electron_y
                                      ,bunch_electron_z])
     
        counts3d, histedges = np.histogramdd(pos_data_3d
                                          ,bins=[xbins,ybins,zbins]
                                          ,weights=bunch_electron_w)

        vols3d = np.einsum('i,j,k',*[np.diff(a) for a in histedges])
        hist_dens3d = counts3d / vols3d

        counts2d_xy = np.sum(counts3d, axis=2)
        counts2d_xz = np.sum(counts3d, axis=1)
        areas2d_xz = np.outer(np.diff(histedges[0]),np.diff(histedges[2]))
        hist_dens2d_xz = counts2d_xz / areas2d_xz
        
        counts1d_z = np.sum(counts3d, axis=(0,1))

        print("max(hist_dens3d): {}".format(hist_dens3d.max()))

    else:
        pos_data_2d = np.column_stack([bunch_electron_x
                                      ,bunch_electron_y])

        counts2d_xy, histedges = np.histogramdd(pos_data_2d
                                             ,bins=[xbins,ybins]
                                             ,weights=bunch_electron_w)

    areas2d_xy = np.outer(np.diff(histedges[0]),np.diff(histedges[1]))
    hist_dens2d_xy = counts2d_xy / areas2d_xy

    counts1d_x = np.sum(counts2d_xy,axis=1)
    counts1d_y = np.sum(counts2d_xy,axis=0)

    print("max(hist_dens2d): {}".format(hist_dens2d_xy.max()))
    print("max(sdf_dens): {}".format(sdf_dens.max()))


### Statistical Calculations

    fwnm_lim = 100

    bin_w_x = np.diff(histedges[0])
    bin_ctr_x = histedges[0][:-1] + bin_w_x 
    bin_w_y = np.diff(histedges[1])
    bin_ctr_y = histedges[1][:-1] + bin_w_y
    if is3d:
        bin_w_z = np.diff(histedges[2])
        bin_ctr_z = histedges[2][:-1] + bin_w_z

    nx_rms = bin_ctr_x[np.where(counts1d_x > counts1d_x.max()/np.e)]
    nx_fwhm = bin_ctr_x[np.where(counts1d_x > counts1d_x.max()/2)]
    nx_fwnm = bin_ctr_x[np.where(counts1d_x > counts1d_x.max()/fwnm_lim)]
    rms_x = nx_rms.max() - nx_rms.min()
    fwhm_x = nx_fwhm.max() - nx_fwhm.min() 
    fwnm_x = nx_fwnm.max() - nx_fwnm.min() 
    x_avg = np.average(bunch_electron_x, weights=bunch_electron_w)
    x_vari = np.average((bunch_electron_x - x_avg)**2, weights=bunch_electron_w)
    x_stdev = np.sqrt(x_vari)
    print("X-avg: {}".format(x_avg))
    print("Bunch RMS(x): {}".format(rms_x))
    print("Bunch FWHM(x): {}".format(fwhm_x))
    print("Bunch FW{}M(x): {}".format(fwnm_lim,fwnm_x))
    print("Bunch pos stdev(x): {}".format(x_stdev))
    print()

    ny_rms = bin_ctr_y[np.where(counts1d_y > counts1d_y.max()/np.e)]
    ny_fwhm = bin_ctr_y[np.where(counts1d_y > counts1d_y.max()/2)]
    ny_fwnm = bin_ctr_y[np.where(counts1d_y > counts1d_y.max()/fwnm_lim)]
    rms_y = ny_rms.max() - ny_rms.min()
    fwhm_y = ny_fwhm.max() - ny_fwhm.min() 
    fwnm_y = ny_fwnm.max() - ny_fwnm.min() 
    y_avg = np.average(bunch_electron_y, weights=bunch_electron_w)
    y_vari = np.average((bunch_electron_y - y_avg)**2, weights=bunch_electron_w)
    y_stdev = np.sqrt(y_vari)
    print("Bunch RMS(y): {}".format(rms_y))
    print("Bunch FWHM(y): {}".format(fwhm_y))
    print("Bunch FW{}M(y): {}".format(fwnm_lim,fwnm_y))
    print("Bunch pos stdev(y): {}".format(y_stdev))
    print()

    if is3d:
        nz_rms = bin_ctr_z[np.where(counts1d_z > counts1d_z.max()/np.e)]
        nz_fwhm = bin_ctr_z[np.where(counts1d_z > counts1d_z.max()/2)]
        nz_fwnm = bin_ctr_z[np.where(counts1d_z > counts1d_z.max()/fwnm_lim)]
        rms_z = nz_rms.max() - nz_rms.min()
        fwhm_z = nz_fwhm.max() - nz_fwhm.min() 
        fwnm_z = nz_fwnm.max() - nz_fwnm.min() 
        z_avg = np.average(bunch_electron_z, weights=bunch_electron_w)
        z_vari = np.average((bunch_electron_z - z_avg)**2, weights=bunch_electron_w)
        z_stdev = np.sqrt(z_vari)
        print("Bunch RMS(z): {}".format(rms_z))
        print("Bunch FWHM(z): {}".format(fwhm_z))
        print("Bunch FW{}M(z): {}".format(fwnm_lim,fwnm_z))
        print("Bunch pos stdev(z): {}".format(z_stdev))
        print()

    if not is3d:
        unscaled_charge = np.sum(counts2d_xy)*sc.e
        print("Unscaled charge: {}".format(unscaled_charge))
        xm, ym, = np.meshgrid(bin_ctr_x, bin_ctr_y, indexing='ij')
        bunch_charge_rad = np.sum(np.abs(ym)*counts2d_xy)*np.pi*sc.e
        bunch_charge_dep = unscaled_charge*fwnm_y
        print("Total charge(rad): {:03g}pc".format(bunch_charge_rad*1e12))
        print("Total charge(depth): {:03g}pc".format(bunch_charge_dep*1e12))
    else:
        unscaled_charge = np.sum(counts3d)*sc.e
        print("Total charge: {:03g}pc".format(unscaled_charge*1e12))


### Debug Plot ####


    fig = mf.Figure(figsize=(12,12))
    canvas = mplbea.FigureCanvasAgg(fig)
    ax1 = fig.add_subplot(331)
    ax1.imshow(plot_dens_xy.T
             ,aspect='auto'
             ,extent=display_limits
             ,origin='upper'
             ,norm=mc.LogNorm(1e23,1e26)
             ,cmap=mcm.plasma)
    ax1.xaxis.set_major_locator(mt.LinearLocator(5))

    if None not in ell.values():
        ax1.add_patch(mpat.Ellipse((ell['centerx']*1e6,ell['centery']*1e6)
                                  ,2*ell['radx']*1e6
                                  ,2*ell['rady']*1e6
                                  ,fill=True
                                  ,fc='blue'
                                  ,alpha=0.2))
    if is3d:
        ax2 = fig.add_subplot(334)
        ax2.imshow(plot_dens_xz.T
                 ,aspect='auto'
                 ,extent=display_limits
                 ,origin='upper'
                 ,norm=mc.LogNorm(1e23,1e26)
                 ,cmap=mcm.plasma)
        ax2.xaxis.set_major_locator(mt.LinearLocator(5))

        if None not in ell.values():
            ax2.add_patch(mpat.Ellipse((ell['centerx']*1e6,ell['centery']*1e6)
                                      ,2*ell['radx']*1e6
                                      ,2*ell['radz']*1e6
                                      ,fill=True
                                      ,fc='blue'
                                      ,alpha=0.2))


    ax3 = fig.add_subplot(332)
    ax3.imshow(hist_dens2d_xy.T
             ,aspect='auto'
             ,extent=display_limits
             ,origin='upper'
             ,norm=mc.LogNorm(np.ma.masked_equal(hist_dens2d_xy,0,copy=False).min()
                          ,np.ma.masked_equal(hist_dens2d_xy,0,copy=False).max())
             ,cmap=mcm.plasma)
    ax3.xaxis.set_major_locator(mt.LinearLocator(5))

    if is3d:
        ax4 = fig.add_subplot(335)
        ax4.imshow(hist_dens2d_xz.T
                 ,aspect='auto'
                 ,extent=display_limits
                 ,origin='upper'
                 ,norm=mc.LogNorm(np.ma.masked_equal(hist_dens2d_xz,0,copy=False).min()
                              ,np.ma.masked_equal(hist_dens2d_xz,0,copy=False).max())
                 ,cmap=mcm.plasma)
        ax4.xaxis.set_major_locator(mt.LinearLocator(5))

    # Charge x-distribution    
    ax5 = fig.add_subplot(337)
    bars = ax5.bar(bin_ctr_x*1e6
                  ,counts1d_x
                  ,width=bin_w_x*1e6
                  ,linewidth=0
                  )
    mask_count = np.ma.masked_equal(counts1d_x, 0, copy=False)
    norm = mc.Normalize(mask_count.min(),mask_count.max())
    for i,patch in enumerate(bars.patches):
        if counts1d_x[i] > 0:
            patch.set_facecolor(mcm.plasma(norm(counts1d_x[i])))

    #Indicate extents of bunch measurements
    ax5.axvline(nx_rms.min()*1e6,alpha=0.5, color='red')
    ax5.axvline(nx_rms.max()*1e6,alpha=0.5, color='red')
    ax5.axvline(nx_fwhm.min()*1e6,alpha=0.5, color='green')
    ax5.axvline(nx_fwhm.max()*1e6,alpha=0.5, color='green')
    ax5.axvline(nx_fwnm.min()*1e6,alpha=0.5, color='blue')
    ax5.axvline(nx_fwnm.max()*1e6,alpha=0.5, color='blue')
    
    #naive attempt to autoscale
    delta = 0.1*(nx_fwnm.max() - nx_fwnm.min())
    ax5.set_xlim((nx_fwnm.min()-delta)*1e6
                ,(nx_fwnm.max()+delta)*1e6)

    ax5.set_xlabel(r'$z\ \mathrm{(\mu m)}$')
    ax5.set_ylabel(r'$\mathrm{d}Q\ \mathrm{(C m^{-3})}$')
    ax5.xaxis.set_major_locator(mt.MaxNLocator(5))


    #Charge y_distribution
    ax6 = fig.add_subplot(333)
    bars = ax6.bar(bin_ctr_y*1e6
                  ,counts1d_y
                  ,width=bin_w_y*1e6
                  ,linewidth=0
                  )
    norm = mc.Normalize(counts1d_y.min(),counts1d_y.max())
    for i,patch in enumerate(bars.patches):
        if counts1d_y[i] > 0:
            patch.set_facecolor(mcm.plasma(norm(counts1d_y[i])))
    
    #Indicate extents of bunch measurements
    ax6.axvline(ny_rms.min()*1e6,alpha=0.5, color='red')
    ax6.axvline(ny_rms.max()*1e6,alpha=0.5, color='red')
    ax6.axvline(ny_fwhm.min()*1e6,alpha=0.5, color='green')
    ax6.axvline(ny_fwhm.max()*1e6,alpha=0.5, color='green')
    ax6.axvline(ny_fwnm.min()*1e6,alpha=0.5, color='blue')
    ax6.axvline(ny_fwnm.max()*1e6,alpha=0.5, color='blue')
    
    #naive attempt to autoscale
    delta = 0.1*(ny_fwnm.max() - ny_fwnm.min())
    ax6.set_xlim((ny_fwnm.min()-delta)*1e6
                ,(ny_fwnm.max()+delta)*1e6)

    ax6.set_xlabel(r'$z\ \mathrm{(\mu m)}$')
    ax6.set_ylabel(r'$\mathrm{d}Q\ \mathrm{(C m^{-3})}$')


    #z-density distribution
    if is3d:
        ax7 = fig.add_subplot(336)
        bars = ax7.bar(bin_ctr_z*1e6
                      ,counts1d_z
                      ,width=bin_w_z*1e6
                      ,linewidth=0
                      )
        norm = mc.Normalize(counts1d_z.min(),counts1d_z.max())
        for i,patch in enumerate(bars.patches):
            if counts1d_z[i] > 0:
                patch.set_facecolor(mcm.plasma(norm(counts1d_z[i])))

        #Indicate extents of bunch measurements
        ax7.axvline(nz_rms.min()*1e6,alpha=0.5, color='red')
        ax7.axvline(nz_rms.max()*1e6,alpha=0.5, color='red')
        ax7.axvline(nz_fwhm.min()*1e6,alpha=0.5, color='green')
        ax7.axvline(nz_fwhm.max()*1e6,alpha=0.5, color='green')
        ax7.axvline(nz_fwnm.min()*1e6,alpha=0.5, color='blue')
        ax7.axvline(nz_fwnm.max()*1e6,alpha=0.5, color='blue')
        
        #naive attempt to autoscale
        delta = 0.1*(nz_fwnm.max() - nz_fwnm.min())
        ax7.set_xlim((nz_fwnm.min()-delta)*1e6
                    ,(nz_fwnm.max()+delta)*1e6)

        ax7.set_xlabel(r'$z\ \mathrm{(\mu m)}$')
        ax7.set_ylabel(r'$\mathrm{d}Q\ \mathrm{(C m^{-3})}$')
    
    #Finally print all the numerical results
    ax8 = fig.add_subplot(338)
    ax8.axis('off')

    # Bunch Charge
    if is3d:
        props_string = r'\noindent$Q = {:.3}\ \mathrm{{pC}}$\\ \\'.format(unscaled_charge*1e12)
    else:   
        props_string = ''.join(
            [r'\noindent$dQ = {:.3}\ \mathrm{{\mu C/m}}$\\'.format(unscaled_charge*1e6)
            ,r'$Q_w = {:.3}\ \mathrm{{pC}}$\\'.format(bunch_charge_dep*1e12)
            ,r'$Q_r = {:.3}\ \mathrm{{pC}}$\\ \\'.format(bunch_charge_rad*1e12)])

    props_string += ''.join(
       [r'$w_x(RMS) = {:.3}\ \mathrm{{\mu m}}$\\'.format(rms_x*1e6)
       ,r'$w_x(FWHM) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwhm_x*1e6)
       ,r'$w_x(FW{}M) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwnm_lim,fwnm_x*1e6)
       ,r'$\sigma_x = {:.3}\ \mathrm{{\mu m}}$\\ \\'.format(x_stdev*1e6)
       ,r'$w_y(RMS) = {:.3}\ \mathrm{{\mu m}}$\\'.format(rms_y*1e6)
       ,r'$w_y(FWHM) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwhm_y*1e6)
       ,r'$w_y(FW{}M) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwnm_lim,fwnm_y*1e6)
       ,r'$\sigma_y = {:.3}\ \mathrm{{\mu m}}$\\ \\'.format(y_stdev*1e6)])

    if is3d:
        props_string += ''.join(
           [r'$w_z(RMS) = {:.3}\ \mathrm{{\mu m}}$\\'.format(rms_z*1e6)
           ,r'$w_z(FWHM) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwhm_z*1e6)
           ,r'$w_z(FW{}M) = {:.3}\ \mathrm{{\mu m}}$\\'.format(fwnm_lim,fwnm_z*1e6)
           ,r'$\sigma_z = {:.3}\ \mathrm{{\mu m}}$\\'.format(z_stdev*1e6)])


    ax8.text(0,0.95
        ,props_string
        ,transform=ax8.transAxes
        ,verticalalignment='top'
        )

    fig.savefig('{}/{}_debug_fwhm.png'.format(output_path,output_name))
    

### Publication Plot

    ax1loc=[0.09,0.15,0.37,0.625] 
    ax2loc=[0.59,0.15,0.37,0.625] 
    ax1cbloc=[0.09,0.8,0.37,0.05] 
    ax2cbloc=[0.59,0.8,0.37,0.05] 
    ax1norm=mc.LogNorm(1e23,1e26)

    if reset_origin:
        origin_offset = display_limits[0]
        display_limits[0] = 0
        display_limits[1] -= origin_offset
    else:
        origin_offset = 0

    mpl.rcParams.update({'font.size': 8})
    fig = mf.Figure(figsize=(3.2,2))
    canvas = mplbea.FigureCanvasAgg(fig)
    ax = fig.add_axes(ax1loc)
    ax.imshow(plot_dens_xy.T
             ,aspect='auto'
             ,extent=display_limits
             ,origin='upper'
             ,norm=ax1norm
             ,cmap=mcm.plasma)

    ax1cba = fig.add_axes(ax1cbloc)
    ax1cb = mplcb.ColorbarBase(ax1cba
                              ,cmap=mcm.plasma
                              ,norm=ax1norm
                              ,orientation='horizontal')
    ax1cba.tick_params(top=True,labelbottom=False,labeltop=True,pad=-1)
    ax1cb.set_ticks((ax1norm.vmin,ax1norm.vmax))
    ax1cba.xaxis.set_label_position('top')
    ax1cb.set_label(r"$n_e\ \mathrm{m^{-3}}$", labelpad=-4)

    ax.xaxis.set_major_locator(mt.LinearLocator(3))
    ax.yaxis.set_major_locator(mt.LinearLocator(3))

    ax.set_xlabel(r'$z\ \mathrm{(\mu m)}$', labelpad=0)
    ax.set_ylabel(r'$y \mathrm{(\mu m)}$', labelpad=-5)

    ax2 = fig.add_axes(ax2loc)
    counts, xbins, patches = ax2.hist(bunch_electron_x*1e6 - origin_offset
                                     ,bins=xbins*1e6 - origin_offset
                                     ,weights=bunch_electron_w*sc.e*1e12
                                     ,linewidth=0)
    
    cnz = counts[np.nonzero(counts)]
    pnz = np.asarray(patches)[np.nonzero(counts)]
    try:
        ax2nmax = float(config['pub_cmax'])
    except:
        ax2nmax = np.power(10,np.ceil(np.log10(cnz.max()))) 
    try:
        ax2nmin = float(config['pub_cmin'])
    except:
        ax2nmin = np.power(10,np.floor(np.log10(cnz.min())))

    ax2norm = mc.LogNorm(ax2nmin, ax2nmax)

    for count, patch in zip(cnz,pnz):
        patch.set_facecolor(mcm.plasma(ax2norm(count))) 
    
    if lineout_inset:
        insax = mil.inset_axes(ax2, width="50%", height="50%", loc=2)
        iap = insax.get_position()
        insax.set_position([iap.xmin + 0.05, iap.ymin, iap.width, iap.height])
        for patch in patches:
            patch_cpy = copy.copy(patch)
            patch_cpy.axes = None
            patch_cpy.figure = None
            patch_cpy.set_transform(insax.transData)
            insax.add_patch(patch_cpy)
        insax.yaxis.set_ticks_position("right")
        insax.autoscale()
        insax.set_xlim(lineout_xmin, lineout_xmax)
        insax.set_ylim(lineout_ymin, lineout_ymax)
        insax.xaxis.set_major_locator(mt.LinearLocator(2))
        insax.yaxis.set_major_locator(mt.LinearLocator(2))
        insax.axes.tick_params(labelsize="small")
#        [tick.label.set_fontsize(6) for tick in insax.xaxis.get_major_ticks()]
#        [tick.label.set_fontsize(6) for tick in insax.yaxis.get_major_ticks()]

    ax2cba = fig.add_axes(ax2cbloc)
    ax2cb = mplcb.ColorbarBase(ax2cba
                              ,cmap=mcm.plasma
                              ,norm=ax2norm
                              ,orientation='horizontal')
    ax2cba.tick_params(top=True,labelbottom=False,labeltop=True,pad=-1)
    ax2cb.set_ticks((ax2norm.vmin,ax2norm.vmax))
    ax2cba.xaxis.set_label_position('top')
    ax2cb.set_label(r"$\mathrm{d}Q/\mathrm{d}z\ \mathrm{nC/m}$", labelpad=-4)

    ax2.set_xlim(pub_xmin, pub_xmax)
    ax2.set_ylim(pub_ymin, pub_ymax)

    ax2.xaxis.set_major_locator(mt.LinearLocator(3))
    ax2.yaxis.set_major_locator(mt.LinearLocator(3))
    
    ax2.set_xlabel(r'$z\ \mathrm{(\mu m)}$',labelpad=0)
    ax2.set_ylabel(r'$\mathrm{d}Q/\mathrm{d}z\ \mathrm{(nC/m)}$',labelpad=0)

    try:
        fig.text(0.05,0.94,'{}'.format(config['title'])
        ,transform=fig.transFigure, fontsize=10)
    except Exception as err:
        print(err)

    fig.savefig('{}/{}_pub_fwhm.png'.format(output_path,output_name) ,dpi=300)
示例#33
0
            import matplotlib.cm as cm
            segment_size, ang = angles[2]
            
            n_range = 301
            start_p = 7000
            delta_f = 30
            for ii in range(start_p, start_p+n_range, delta_f):
                plt.figure(figsize=(3*n_cols,3*n_rows))
                
                for iseg, (segment_size, ang) in enumerate(angles):
                    plt.subplot(2, n_cols, iseg+1)
                    x = wormN.skeleton[ii,:,0]
                    y = wormN.skeleton[ii,:,1]
                    c = (ang[ii]+np.pi)/(2*np.pi)
                    c = np.pad(c, (segment_size,segment_size), 'edge')
                    c = cm.plasma(c)
                    plt.scatter(x, y, c=c)
                    plt.axis('equal')
                    
                    
                    plt.subplot(2,n_cols, iseg+1+n_cols)
                    dd = np.arange(ang[ii].size) + segment_size
                    plt.plot(dd, ang[ii], '.-')
                    
                    plt.xlim(0, x.size)
                    
            
             #%%
            
            
#            plt.figure(figsize = (15, 5))
示例#34
0
文件: x_map.py 项目: mawesi/x_map
def plot(data, min_size_px=512, extend_percentage=10, filename=False,
         markers=True, gradient_lines=True, caption=False,
         show_plot=True):
    """Plot data in a map.

    Parameters
    ----------
    data : array_like
        The input data.  Columns should be latitude, longitude, value.
        If multiple value columns are given, one plot for each value
        column is generated.
    min_size_px : int, optional
        Minimum size of generated plot in pixels.  Defaults to 512.
    extend_percentage : int, float, optional
        Determines how much the shown map is extended around the
        bounding box of the values.  Given in percent of the bounding
        box extents.  Defaults to 10.
    filename : str, list, optional
        Filename of the generated png image.  If `False`, the image is
        not saved.  If multiple value columns are given, this can also
        be a list of filenames.  Defaults to `False`.
    markers : bool, optional
        If `True`, markers for each value are plotted.  Defaults to
        `True`.
    gradient_lines : bool, optional
        If `True` gradient color lines are plotted between the values.
        Defaults to `True`.
    caption : str, list, optional
        Caption printed on the plot if given.  If multiple value
        columns are given, this can also be a list of captions.
        Defaults to `False`.
    show_plot : bool, optional
        If `True`, the generated plot is displayed.  Defaults to
        `True`.

    """
    # Calculate bounding box and zoom.
    lat_long_min, lat_long_max = calculate_bounding_coordinates(data, extend_percentage=extend_percentage)
    zoom = calculate_optimal_zoom(lat_long_min, lat_long_max, min_size_px)

    # Get map data from OpenStreetMaps.
    dpi = 72
    m = smopy.Map((*lat_long_min, *lat_long_max), z=zoom)

    # Calculate resulting figure size.
    size = m.to_pil().size
    print(size)
    figsize = (10/32 + size[0] / dpi, 10/32 + size[1] / dpi)

    # Plot map and data for each value column.
    for value_index in range(2, data.shape[1]):
        # Convert map to matplotlib.
        ax = m.show_mpl(figsize=figsize, dpi=dpi)


        # Plot markers and gradient lines for each value.
        for i, (lat, long, value) in enumerate(data[:,(0, 1, value_index)]):
            loc_px = m.to_pixels(lat, long)

            # Plot markers.
            if markers:
                ax.plot(*loc_px, 'o', color=cm.plasma(float(-value / 100)), markersize=10)

            # Plot gradient lines.
            ## Skip first value and then plot line from last value to current value.
            if i != 0 and gradient_lines:
                # Calculate line length.
                line_length = np.sqrt((last_loc_px[0] - loc_px[0]) ** 2 + (last_loc_px[1] - loc_px[1]) ** 2)
                # Calculate x and y coordinates of line points.
                x = np.linspace(last_loc_px[0], loc_px[0], line_length)
                y = (loc_px[1] - last_loc_px[1]) * ((x - last_loc_px[0]) / (loc_px[0] - last_loc_px[0])) + last_loc_px[1]
                # Generate a gradient color map.
                colors = [cm.plasma(float(-((value - last_value) * i / len(x) + last_value) / 100)) for i in range(len(x))]
                # Gradient lines are generated using scatter plots.
                ax.scatter(x, y, c=colors, marker='o', s=1, edgecolor='face')

            # Store last location and value for next gradient line.
            last_loc_px = loc_px
            last_value = value


        # Get the extended bounding box in pixels.
        x_min, y_min = m.to_pixels(lat_long_max[0], lat_long_min[1])
        x_max, y_max = m.to_pixels(lat_long_min[0], lat_long_max[1])

        # Set the axes limits to show only the extended bounding box.
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_max, y_min)

        # Add caption to the plot.
        if caption is not False:
            if isinstance(caption, str):
                this_caption = caption
            else:
                this_caption = caption[value_index - 2]
            ax.text(10 + x_min, y_max - 10, this_caption, fontsize=48, fontdict={'weight': 'bold'})

        # Save plot if filename is given.
        if filename is not False:
            if isinstance(filename, str):
                this_filename = filename
            else:
                this_filename = filename[value_index - 2]
            plt.savefig(this_filename, pad_inches=0, bbox_inches='tight', dpi=dpi)

        # Show plot if requested.
        if show_plot:
            plt.show()

        # Close plot.
        plt.close()
示例#35
0
    def plot_string(self):
        """self.strings内に格納されているStringを参照し,グラフ上に図示する
        """
        # print self.string.pos, self.string.vec
        i = 0  # to count how many line2D object
        for s in self.strings:
            start = 0
            for j, pos1, pos2 in zip(range(len(s.pos) - 1), s.pos[:-1], s.pos[1:]):
                dist_x = abs(self.lattice_X[pos1[0], pos1[1]] -
                            self.lattice_X[pos2[0], pos2[1]])
                dist_y = abs(self.lattice_Y[pos1[0], pos1[1]] -
                            self.lattice_Y[pos2[0], pos2[1]])
                # print j, pos1, pos2
                # print dist_x, dist_y
                # sqrt(2^{2} + (1/2)^{2}) ~ 2.06
                if dist_x > 2.1 * self.lattice.dx or dist_y > 2.1 * self.lattice.dx:
                    x = s.pos_x[start:j + 1]
                    y = s.pos_y[start:j + 1]
                    X = [self.lattice_X[_x, _y] for _x, _y in zip(x, y)]
                    Y = [self.lattice_Y[_x, _y] for _x, _y in zip(x, y)]
                    self.lines[i].set_data(X, Y)
                    start = j + 1
                    i += 1
            else:
                x = s.pos_x[start:]
                y = s.pos_y[start:]
                X = [self.lattice_X[_x, _y] for _x, _y in zip(x, y)]
                Y = [self.lattice_Y[_x, _y] for _x, _y in zip(x, y)]
                self.lines[i].set_data(X, Y)
                i += 1

        num_plot_surface = 0
        if self.plot_surface:
            if self._num_surface == 1:
                num_plot_surface = 1
                neighbors = []
                for bonding_pairs in self.bonding_pairs.values():
                    # print(bonding_pairs)
                    for pos in bonding_pairs.keys():
                        neighbors.append(pos)
                neighbors = list(np.array(neighbors).T)
                # print(neighbors)
                X, Y = self.lattice_X[neighbors], self.lattice_Y[neighbors]
                # print(X, Y)
                self.lines[-1].set_data(X, Y)

            # === 
            else:
                w = {}
                for bonding_pairs in self.bonding_pairs.values():
                    # print(bonding_pairs)
                    for pos, bps in bonding_pairs.items():
                        for bp, _w in bps:
                            if w.has_key(_w):
                                w[_w].append(pos)
                            else:
                                w[_w] = [pos,]
                num_plot_surface = len(w)
                # W = sorted(w.keys(), reverse=True)
                sum_w = np.sum([len(w[_w]) for _w in w.keys()])
                W = [(_w, (_w * len(w[_w])) / sum_w) for _w in w.keys()]
                ave_W = np.average(W, axis=0)[1] 
                min_W = np.exp(self.beta * (-2.5)) /sum_w
                max_W = np.exp(self.beta * 2.5) /sum_w
                for k, (wi, _w) in enumerate(W):
                    neighbors = list(np.array(w[wi]).T)
                    X, Y = self.lattice_X[neighbors], self.lattice_Y[neighbors]
                    self.lines[-(k + 1)].set_data(X, Y)
                    ## color setting
                    dw = _w - ave_W
                    if min_W == ave_W:
                        _c = 0.5
                    elif dw < 0:
                        _c = (0.5 / (ave_W - min_W)) * (_w - min_W)
                    else:
                        _c = (0.5 / (max_W - ave_W)) * dw + 0.5
                    self.lines[-(k + 1)].set_color(cm.plasma(_c))


        # 最終的に,iの数だけ線を引けばよくなる
        # それ以上のオブジェクトはリセット
        if self.plot_surface:
            max_obj = len(self.lines) - num_plot_surface
        else:
            max_obj = len(self.lines)
        for j in range(i, max_obj):
            self.lines[j].set_data([], [])

        return self.lines
示例#36
0
def main():
    config_file = parse_input()
    config = loadconfig(config_file)

    try:
        sdf_data = sdf.read(config['sdf_file'])
    except:
        raise

    dirname = os.path.basename(os.getcwd())

    grids =  {'xgrid':None
                ,'ygrid':None
                ,'xbins':None
                ,'ybins':None}
    for grid in grids:
        try:
            grids[grid] = float(config[grid])
        except:
            pass

    if ((grids['xgrid'] is not None and grids['xbins'] is not None) or
       (grids['ygrid'] is not None and grids['ybins'] is not None)):
        print("Both gridsize and numbins are specified... "
              "gridsize will take precedence")

    if ((grids['xgrid'] is None and grids['xbins'] is None) or
       (grids['ygrid'] is None and grids['ybins'] is None)):
        print("Warning no gridsize or numbins specified, defaulting to"
              "100 bins")
        if grids['xbins'] is None:
            grids['xbins'] = 100
        if grids['ybins'] is None:
            grids['ybins'] = 100
    
    try:
        output_name = config['output_name']
    except:
        output_name = 'out'

    try:
        output_path = config['output_path']
    except:
        output_path = '.'

    ell = {'center':None, 'width':None, 'height':None}
    for arg in ell:
        try:
            ell[arg] = float(config['ell_{}'.format(arg)])
        except:
            pass
       

    cutoff_px = float(config['cutoff_px']) * sc.m_e * sc.c
    sdf_e_px = getattr(sdf_data, 'Particles_Px_electron').data
    sdf_e_x = getattr(sdf_data, 'Grid_Particles_electron').data[0]
    sdf_e_y = getattr(sdf_data, 'Grid_Particles_electron').data[1]
    sdf_e_w = getattr(sdf_data, 'Particles_Weight_electron').data
    sdf_gridx = getattr(sdf_data, 'Grid_Grid').data[0]
    sdf_gridy = getattr(sdf_data, 'Grid_Grid').data[1]
    sdf_dens = getattr(sdf_data, 'Derived_Number_Density_electron').data
    try:
        sdf_gridz = getattr(sdf_data, 'Grid_Grid').data[2]
        sdf_e_z = getattr(sdf_data, 'Grid_Particles_electron').data[2]
        is3d = True
    except:
        is3d = False

    limits = {'xmin':sdf_e_x.min()
             ,'xmax':sdf_e_x.max()
             ,'ymin':sdf_e_y.min()
             ,'ymax':sdf_e_y.max()}
    if is3d:
        limits['zmin'] = sdf_e_z.min()
        limits['zmax'] = sdf_e_z.max()
 
    for limit in limits:
        try:
            limits[limit] = float(config[limit])
        except:
            pass
    
    hist_limits = {}
    for limit in limits:
        try:
            hist_limits[limit] = float(config['hist_'+limit])
        except:
            hist_limits[limit] = limits[limit]
            
    xargmin = np.argmin(np.abs(sdf_gridx - limits['xmin']))
    xargmax = np.argmin(np.abs(sdf_gridx - limits['xmax']))
    yargmin = np.argmin(np.abs(sdf_gridy - limits['ymin']))
    yargmax = np.argmin(np.abs(sdf_gridy - limits['ymax']))
    if is3d:
        zargmin = np.argmin(np.abs(sdf_gridz - limits['zmin']))
        zargmax = np.argmin(np.abs(sdf_gridz - limits['zmax']))

    sdf_gridx = sdf_gridx[xargmin:xargmax]
    sdf_gridy = sdf_gridy[yargmin:yargmax]
    sdf_dens = sdf_dens[xargmin:xargmax,yargmin:yargmax]
    if is3d:
        sdf_gridz = sdf_gridz[zargmin:zargmax]

    ### Electron selection magic happens here

    energy_mask = sdf_e_px > cutoff_px
    position_mask = np.full(sdf_e_px.shape, True, dtype=bool)
    if None not in ell.values():
        if is3d:
            position_mask = ( 
            ((sdf_e_x - ell['center'])**2 / (0.25*ell['width']**2)) +
            (sdf_e_y**2 / (0.25*ell['height']**2)) +
            (sdf_e_z**2 / (0.25*ell['height']**2)) < 1 )
        else:
            position_mask = (
            ((sdf_e_x - ell['center'])**2 / (0.25*ell['width']**2)) +
            (sdf_e_y**2 / (0.25*ell['height']**2)) < 1 )

        bunch_electron_mask = np.where(np.logical_and(energy_mask,
                                                position_mask))

    bunch_electron_x = sdf_e_x[bunch_electron_mask].reshape(-1)
    bunch_electron_y = sdf_e_y[bunch_electron_mask].reshape(-1)
    bunch_electron_w = sdf_e_w[bunch_electron_mask].reshape(-1)
    if is3d:
        bunch_electron_z = sdf_e_z[bunch_electron_mask].reshape(-1)

    if grids['xgrid'] is not None:
        xbins = np.arange(hist_limits['xmin'],hist_limits['xmax']+grids['xgrid'],grids['xgrid'])
    else:
        xbins = np.linspace(hist_limits['xmin'],hist_limits['xmax'],grids['xbins'])

    if grids['ygrid'] is not None:
        if hist_limits['ymin'] * hist_limits['ymax'] < 0:
            ybins = np.sort(np.concatenate((
                np.arange(0,hist_limits['ymin']-grids['ygrid'],-grids['ygrid']),
                np.arange(grids['ymin'],hist_limits['ymax']+grids['ygrid'],grids['ygrid']))))

        else:
            ybins = np.arange(hist_limits['ymin'],hist_limits['ymax']+grids['ygrid'],grids['ygrid'])
    else:
        if hist_limits['ymin'] * hist_limits['ymax'] < 0:
            ybins = np.sort(np.concatenate((
                np.linspace(hist_limits['ymin'],0,grids['ybins']//2),
                np.linspace(0,hist_limits['ymax'],grids['ybins']//2)[1:])))
        else:
            ybins = np.linspace(hist_limits['ymin'],hist_limits['ymax'],grids['ybins'])

    
    limlist = [ limits[l]*1e6 for l in ['xmin','xmax','ymin','ymax'] ]
    hist_limlist = [ hist_limits[l]*1e6 for l in ['xmin','xmax','ymin','ymax'] ]


### Debug Plot ####


    fig = mf.Figure(figsize=(8.3,11.7))
    canvas = mplbea.FigureCanvasAgg(fig)
    ax = fig.add_subplot(221)
    ax.imshow(sdf_dens.T
             ,aspect='auto'
             ,extent=limlist
             ,origin='upper'
             ,norm=LogNorm(1e23,1e26)
             ,cmap=mcm.plasma)

    if None not in ell.values():
        ax.add_patch(mpat.Ellipse((ell['center']*1e6,0)
                                 ,ell['width']*1e6
                                 ,ell['height']*1e6
                                 ,fill=True
                                 ,fc='blue'
                                 ,alpha=0.2))

    ax2 = fig.add_subplot(222)
    counts, xedges, yedges = np.histogram2d(bunch_electron_x
                                     ,bunch_electron_y
                                     ,bins=[xbins,ybins]
                                     ,weights=bunch_electron_w)

    areas = np.outer(np.diff(xedges),np.diff(yedges))
    hist_dens = counts / areas
    print("max(dens): {}".format(sdf_dens.max()))
    print("max(hist): {}".format(hist_dens.max()))

    ax2.imshow(hist_dens.T
             ,aspect='auto'
             ,extent=limlist
             ,origin='upper'
             ,norm=LogNorm(1e23,1e26)
             ,cmap=mcm.plasma)
    
    ax3 = fig.add_subplot(223)
    zcounts = ax3.hist(bunch_electron_x*1e6
           ,bins=xbins*1e6
           ,weights=bunch_electron_w*sc.e
#           ,log=True
           )[0]
    ax3.set_xlim(limits['xmin']*1e6,limits['xmax']*1e6)
#    ax3.set_ylim(1e11,5e12)

    ax3.set_xlabel(r'$z\ \mathrm{(\mu m)}$')
    ax3.set_ylabel(r'$\mathrm{d}Q\ \mathrm{(C m^{-3})}$')
    ax.xaxis.set_major_locator(mt.MaxNLocator(5))

    ax4 = fig.add_subplot(224)
    ycounts = ax4.hist(bunch_electron_y*1e6
                      ,bins=ybins*1e6
                      ,weights=bunch_electron_w*sc.e
                      )[0]

    ax4.set_xlim(limits['ymin']*1e6,limits['ymax']*1e6)
#    ax3.set_ylim(1e11,5e12)

    ax4.set_xlabel(r'$z\ \mathrm{(\mu m)}$')
    ax4.set_ylabel(r'$\mathrm{d}Q\ \mathrm{(C m^{-3})}$')

    xcentres = xedges[:-1] + np.diff(xedges)
    ycentres = yedges[:-1] + np.diff(yedges)
    xm, ym = np.meshgrid(xcentres, ycentres, indexing='ij')

    nz = xcentres[np.where(zcounts > zcounts.max()/np.e)]
    ax3.axvline(nz.min()*1e6,alpha=0.5)
    ax3.axvline(nz.max()*1e6,alpha=0.5)
    bunch_length = nz.max() - nz.min()
    print("Bunch Length: {}".format(bunch_length))

    nz = ycentres[np.where(ycounts > ycounts.max()/2)]
    ax4.axvline(nz.min()*1e6,alpha=0.5)
    ax4.axvline(nz.max()*1e6,alpha=0.5)
    bunch_width = nz.max() - nz.min()
    print("Bunch Width: {}".format(bunch_width))

    x_avg = np.average(bunch_electron_x, weights=bunch_electron_w)
    x_vari = np.average((bunch_electron_x - x_avg)**2, weights=bunch_electron_w)
    x_stdev = np.sqrt(x_vari)
    print("Bunch stdev: {}".format(x_stdev))
   
    unscaled_charge = np.sum(counts*sc.e)
    bunch_charge_rad = np.sum(np.pi*np.abs(ym)*counts*sc.e)
    bunch_charge_dep = np.sum(bunch_width*counts*sc.e)

    print("Total charge(rad): {}".format(bunch_charge_rad))
    print("Total charge(depth): {}".format(bunch_charge_dep))
    print("Unscaled charge: {}".format(unscaled_charge))


    ax3.text(0.10,0.95,r'$Q_w = {:.3}\ \mathrm{{\mu C/m}}$'.format(unscaled_charge*1e6)
           ,transform=ax3.transAxes
           )
    ax3.text(0.10,0.90,r'$Q_w = {:.3}\ \mathrm{{pC}}$'.format(bunch_charge_dep*1e12)
           ,transform=ax3.transAxes
           )
    ax3.text(0.10,0.85,r'$Q_r = {:.3}\ \mathrm{{pC}}$'.format(bunch_charge_rad*1e12)
           ,transform=ax3.transAxes
           )

    ax4.text(0.55,0.90,r'$W_b = {:.3}\ \mathrm{{\mu m}}$'.format(bunch_width*1e6)
           ,transform=ax4.transAxes
           )
    ax4.text(0.55,0.85,r'$L_b = {:.3}\ \mathrm{{\mu m}}$'.format(bunch_length*1e6)
           ,transform=ax4.transAxes
           )
    ax4.text(0.55,0.80,r'$\sigma_x = {:.3}\ \mathrm{{\mu m}}$'.format(x_stdev*1e6)
           ,transform=ax4.transAxes
           )

    fig.savefig('{}/{}_debug_fwhm.png'.format(output_path,output_name))
    

### Publication Plot

    ax1loc =[0.09,0.15,0.37,0.625] 
    ax2loc =[0.59,0.15,0.37,0.625] 
    ax1cbloc =[0.09,0.8,0.37,0.05] 
    ax2cbloc =[0.59,0.8,0.37,0.05] 
    ax1norm=LogNorm(1e23,1e26)
    ax2norm = LogNorm(1,100)

    if is3d:
        plot_dens = sdf_dens[:,:,int(0.5*sdf_dens.shape[3])]
    else:
        plot_dens = sdf_dens

    mpl.rcParams.update({'font.size': 8})
    fig = mf.Figure(figsize=(3.2,2))
    canvas = mplbea.FigureCanvasAgg(fig)
    ax = fig.add_axes(ax1loc)
    ax.imshow(plot_dens.T
             ,aspect='auto'
             ,extent=limlist
             ,origin='upper'
             ,norm=ax1norm
             ,cmap=mcm.plasma)

    ax1cba = fig.add_axes(ax1cbloc)
    ax1cb = mplcb.ColorbarBase(ax1cba
                              ,cmap=mcm.plasma
                              ,norm=ax1norm
                              ,orientation='horizontal')
    ax1cba.tick_params(top=True,labelbottom=False,labeltop=True,pad=-1)
    ax1cb.set_ticks((ax1norm.vmin,ax1norm.vmax))
    ax1cba.xaxis.set_label_position('top')
    ax1cb.set_label(r"$n_e\ \mathrm{m^{-3}}$", labelpad=-4)

    ax.xaxis.set_major_locator(mt.LinearLocator(3))
    ax.yaxis.set_major_locator(mt.LinearLocator(3))

    ax.set_xlabel(r'$z\ \mathrm{(\mu m)}$', labelpad=0)
    ax.set_ylabel(r'$y \mathrm{(\mu m)}$', labelpad=-8)

    ax2 = fig.add_axes(ax2loc)
    counts, xbins, patches = ax2.hist(bunch_electron_x*1e6
                                     ,bins=xbins*1e6
                                     ,weights=bunch_electron_w*sc.e*1e9
                                     ,linewidth=0
                                     )
    for count, patch in zip(counts,patches):
        patch.set_facecolor(mcm.plasma(ax2norm(count))) 
    
    ax2cba = fig.add_axes(ax2cbloc)
    ax2cb = mplcb.ColorbarBase(ax2cba
                              ,cmap=mcm.plasma
                              ,norm=ax2norm
                              ,orientation='horizontal')
    ax2cba.tick_params(top=True,labelbottom=False,labeltop=True,pad=-1)
    ax2cb.set_ticks((ax2norm.vmin,ax2norm.vmax))
    ax2cba.xaxis.set_label_position('top')
    ax2cb.set_label(r"$\mathrm{d}Q/\mathrm{d}z\ \mathrm{nC/m}$", labelpad=-4)

    ax2.set_xlim(*hist_limlist[:2])
    ax2.set_ylim(0,ax2norm.vmax)

    ax2.xaxis.set_major_locator(mt.LinearLocator(3))
    ax2.yaxis.set_major_locator(mt.LinearLocator(3))
    
    ax2.set_xlabel(r'$z\ \mathrm{(\mu m)}$',labelpad=0)
    ax2.set_ylabel(r'$\mathrm{d}Q/\mathrm{d}x\ \mathrm{(nC/m)}$',labelpad=-2)
    ax2.text(0.05,0.85,'$dQ = {:.3}\mathrm{{\mu C/m}}$'.format(unscaled_charge*1e6)
           ,transform=ax2.transAxes
           )

    try:
        fig.text(0.05,0.94,'{}'.format(config['title'])
        ,transform=fig.transFigure, fontsize=10)
    except Exception as err:
        print(err)

    fig.savefig('{}/{}_pub_fwhm.png'.format(output_path,output_name) ,dpi=300)