Esempio n. 1
0
def plot_allan_variance(xs: np.ndarray, ys: np.ndarray) -> plt.axes:
    from mpl_toolkits.axes_grid.inset_locator import (inset_axes,
                                                      InsetPosition,
                                                      mark_inset)
    _, _ax = plt.subplots()
    _ax.plot(xs, ys, '.')
    _ax.set_ylabel(f'Variance' +
                   r' $\langle [x(t + \delta t) - x(t)]^2 \rangle$ $[nm^2]$',
                   fontsize=font_size)
    # _ax.set_ylabel(f'Distance' + r' $abs(x(t + \delta t) - x(t))$ $[nm]$', fontsize=font_size)
    _ax.set_xlabel(f'Time step' + r' $\delta t[s]$', fontsize=font_size)
    _ax.set_yscale('log')
    # _ax.set_xscale('log')
    _ax.grid(True)

    # Inset
    _ax2 = plt.axes([0, 0, 1, 1])
    # Manually set the position and relative size of the inset axes within ax1
    ip = InsetPosition(_ax, [0.6, 0.1, 0.3, 0.3])
    _ax2.set_axes_locator(ip)
    # Mark the region corresponding to the inset axes on ax1 and draw lines
    # in grey linking the two axes.
    mark_inset(_ax, _ax2, loc1=2, loc2=4, fc="none", ec='0.5')
    xs2 = []
    ys2 = []
    for i, x in enumerate(xs):
        if x < 0.007:
            xs2.append(xs[i])
            ys2.append(ys[i])
    _ax2.plot(xs2, ys2, '.')
    _ax2.set_yscale('log')
    _ax2.set_xscale('log')
    _ax2.set_ylim(_ax.get_ylim())
    _ax2.grid(True)
    return _ax
Esempio n. 2
0
def zoommap(vals, title, label):
    fig =  plt.figure(figsize=(12,8))    
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,
                        wspace=0.15,hspace=0.05)
    ax = plt.subplot(211)
    m = Basemap(projection = 'mill', llcrnrlat = -45, llcrnrlon = -160, 
                urcrnrlat= 82, urcrnrlon = 170, resolution = 'c')

    m.drawcoastlines(linewidth = 0.5)
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,
                        wspace=0.15,hspace=0.05)
    for row in vals:
        x,y = m(vals.lon.values, vals.lat.values)
        m.scatter(x,y, s = 20, color = vals.color.values)
    ax.text(0.03,0.95, label, size = 12,  horizontalalignment='center', 
    verticalalignment='center', transform=ax.transAxes)
    plt.title(title, fontsize = 12)
     
    #Zoom Europe
    axins_1 = zoomed_inset_axes(ax, 2, loc=2, bbox_to_anchor=(0.42, 0.48),
                         bbox_transform=ax.figure.transFigure)
    axins_1.scatter(x, y, s = 20, c = vals.color.values)
    m.drawcoastlines(linewidth = 0.5)
    x2,y2 = m(-12,35) 
    x3,y3 = m(40,65)
    axins_1.set_xlim(x2,x3) 
    axins_1.set_ylim(y2,y3) 
    axes = mark_inset(ax, axins_1, loc1=1, loc2=2, linewidth=1)
    #Zoom Australia
    axins_2 = zoomed_inset_axes(ax, 2.2, loc=3, bbox_to_anchor=(0.61, 0.255),
                         bbox_transform=ax.figure.transFigure)
    axins_2.scatter(x, y, s = 20, c = vals.color.values)
    m.drawcoastlines(linewidth = 0.5)
    x2,y2 = m(110,-43) 
    x3,y3 = m(155,-10)
    axins_2.set_xlim(x2,x3) 
    axins_2.set_ylim(y2,y3) 
    axes = mark_inset(ax, axins_2, loc1=1, loc2=2,linewidth=1)
    #Zoom US
    axins_3 = zoomed_inset_axes(ax, 1.6, loc=3, bbox_to_anchor=(0.21, 0.25),
                         bbox_transform=ax.figure.transFigure)
    axins_3.scatter(x, y, s = 20, c = vals.color.values)
    m.drawcoastlines(linewidth = 0.5)
    x2,y2 = m(-130,22) 
    x3,y3 = m(-60,63)
    axins_3.set_xlim(x2,x3) 
    axins_3.set_ylim(y2,y3) 
    axes = mark_inset(ax, axins_3, loc1=1, loc2=2, linewidth=1)
    return(fig, axes)
Esempio n. 3
0
#%%
# Plot all the baselines
sns.set_style("white")
sns.set_context("paper", font_scale=3)

fig, ax1 = plt.subplots(figsize=(15, 10))
pt_colors = ["r", "b", "g", "k", "m", "c"]

ax2 = plt.axes([0, 0, 1, 1])
# Manually set the position and relative size of the inset axes within ax1
ip = InsetPosition(ax1, [0.1, 0.1, 0.7, 0.4])
ax2.set_axes_locator(ip)
# Mark the region corresponding to the inset axes on ax1 and draw lines
# in grey linking the two axes.
mark_inset(ax1, ax2, loc1=2, loc2=4, fc="none", ec="0.5", linestyle="dotted")

for pp, pt in enumerate(pt_list):
    do_condit = do_presence[pt][0]
    do_rec_side = do_presence[pt][1]
    stim_side = "Bilateral"

    print(f"{pt} with {condit}")
    t_vect = SGs[pt][condit][do_rec_side]["T"]
    f_vect = SGs[pt][condit][do_rec_side]["F"]
    sg_data = SGs[pt][do_condit][do_rec_side]["SG"]

    # find indices for times
    baseline_start_idx = ephys_meta[pt][do_condit]["Configurations"][stim_side][
        "Baseline"
    ][0]
Esempio n. 4
0
        data /= 8.
    data = data ** .25
    data[np.isnan(data)] = 0
    extent = [0., 192., 0., 192.]
    im = grid[i].imshow(data, extent=extent, interpolation="nearest")
    grid[i].text(10, 170, letters[i], fontsize=20, color="white")
    data_zoom = data[135:155, 80:100,]
    axins = zoomed_inset_axes(grid[i], 2, loc=3) # zoom = 6
    extent = [80., 100., 192. - 155., 192. - 135, ]
    im2 = axins.imshow(data_zoom, extent=extent, interpolation="nearest")
    im2.set_clim([data.min(), data.max()])
    plt.xticks(visible=False)
    plt.yticks(visible=False)
    im.set_clim([0., .3])
    im2.set_clim([0., .15])
    mark_inset(grid[i], axins, loc1=2, loc2=4, fc="none", ec="0.5")

fontsize=20
posx = 10
posy = 170
grid[-1].text(posx, posy, "(a): PL", fontsize=fontsize, color="black")
posy -= 25
grid[-1].text(posx, posy, "(b): PLI", fontsize=fontsize, color="black")
posy -= 25
grid[-1].text(posx, posy, "(c): ACI", fontsize=fontsize, color="black")
posy -= 25
grid[-1].text(posx, posy, "(d): HCI", fontsize=fontsize, color="black")
posy -= 25
grid[-1].text(posx, posy, "(e): NOC", fontsize=fontsize, color="black")

grid[0].set_xticks(())
Esempio n. 5
0
            axis.text(i + subextent[0] + 0.5, j + subextent[2] + 0.5, c,
                      weight='demibold',
                      horizontalalignment='center',
                      verticalalignment='center',
                      color=_determine_ideal_value(c, ma=array.max()))


if __name__ == '__main__':
    tux = skimage.io.imread('./tux_icon-33px.png')

    fig, ax = plt.subplots(figsize=(5, 5))

    extent0 = [0, 33, 0, 36]
    ax.imshow(tux, extent=extent0, interpolation='nearest')
    axins = zoomed_inset_axes(ax, 3.4, loc=3)
    extent1 = [18, 23, 18, 23]
    overlay_numbers(axins, tux, extent0, extent1, interpolation='none')
    axins.set_xlim(*extent1[:2])
    axins.set_ylim(*extent1[2:])
    plt.xticks(visible=False)
    plt.yticks(visible=False)
    plt.gca().xaxis.set_major_locator(plt.NullLocator())
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    ax.axis('off')
    fig.tight_layout()
    fig.savefig('./tux_inset.png', dpi=150)

    # plt.show()
Esempio n. 6
0
def show_coord_topo_zoom(windpark, show = True):
    """Plot the topology of a given windpark

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------

    windpark : Windpark
               A given windpark to show the topology.
    """

    plt.clf()

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    for row in turbines:
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    graddiff = (800/111.0) + 0.5  # degree in km... 800km

    fig = plt.figure(figsize=(11.7,8.3))
    plt.title("Location of the farm")

    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
    ax = plt.subplot(111)

    m = Basemap(projection='lcc', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff*2, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = None, area_thresh=1000)

    # Target
    x_target,y_target = m(targetcoord[1],targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(targetcoord[0]-7), int(targetcoord[0]+7), 2.)
    m.drawparallels(parallels,labels=[False,True,True,False])
    meridians = np.arange(int(targetcoord[1]-7), int(targetcoord[1]+7), 2.)
    m.drawmeridians(meridians,labels=[True,False,False,True])


    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    # m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()

    # we define the inset_axes, with a zoom of 2 and at location 2 (upper left corner)
    # axins = zoomed_inset_axes(ax, 40, loc=2)
    axins = inset_axes(ax,
                        width="65%", # width = 30% of parent_bbox
                        height="65%", # height : 1 inch
                        loc=3)

    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()
    #m.etopo()
    #m.drawcoastlines()

    graddiff_park = (radius/(111.0*0.7))  # degree in km
    x,y = m(targetcoord[1]-graddiff_park,targetcoord[0]-graddiff_park)
    x2,y2 = m(targetcoord[1]+graddiff_park,targetcoord[0]+graddiff_park)

    axins.set_xlim(x,x2) # and we apply the limits of the zoom plot to the inset axes
    axins.set_ylim(y,y2) # idem
    plt.xticks(visible=False) # we hide the ticks
    plt.yticks(visible=False)
    mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.9", linewidth = 3) # we draw the "zoom effect" on the main map (ax), joining cornder 1 & 3

    plt.title("Selected Wind Farms")
    if(show):
        plt.show()
Esempio n. 7
0
def displacement(ofile, timestep, Natoms, matrix0, Type, Time, frontname,
                 pathtodatabase, systemsize):
    '''
    timestep,system_size,matrix0 contain the initial information about the system.
    we have to go through sortedfiles to find information about the particles at
    later timesteps.
    '''
    factor = 10**(-8)  # conversionfactor from [A^2/ps] -> [m^2/s]

    Lx = systemsize[1] - systemsize[0]
    Ly = systemsize[3] - systemsize[2]
    Lz = systemsize[5] - systemsize[4]
    halfsystemsize = 0.5 * (Lx + Ly + Lz) / 3.0  # half of average system size

    time = []
    for t in Time:
        time.append(timestep * t / 1000.0)  # to picoseconds
        #time.append(t)

    MSDX = []
    MSDY = []
    MSDZ = []
    MSD = []
    D_local = []
    dt = (time[1] - time[0])
    for T in Time:
        path = frontname + '.%r.txt' % (T)
        print path
        msdx = 0
        msdy = 0
        msdz = 0
        msd = 0
        filename = os.path.abspath(os.path.join(pathtodatabase, path))
        t, Natoms, system_size, matrix, readstructure, entries, types = readfile(
            filename)
        counter = 0
        for i in range(Natoms):
            if (matrix['type'][i] == Type):
                ID = matrix['id'][i]
                initial_index = None
                for j in range(Natoms):
                    k = matrix0['id'][j]
                    if (k == ID):
                        initial_index = j
                        break

                dx = matrix['x'][i] - matrix0['x'][initial_index]
                dy = matrix['y'][i] - matrix0['y'][initial_index]
                dz = matrix['z'][i] - matrix0['z'][initial_index]
                msdx += (dx)**2
                msdy += (dy)**2
                msdz += (dz)**2
                ########################################
                #        MINIMUM IMAGE CONVENTION      #
                if (dx < -halfsystemsize): dx = dx + Lx
                if (dx > halfsystemsize): dx = dx - Lx
                if (dy < -halfsystemsize): dy = dy + Ly
                if (dy > halfsystemsize): dy = dy - Ly
                if (dz < -halfsystemsize): dz = dz + Lz
                if (dz > halfsystemsize): dz = dz - Lz
                ########################################
                msd += dx**2 + dy**2 + dz**2
                counter += 1

        D_local.append((msd / (counter * 6 * T)))
        MSDX.append(msdx / (6 * counter))
        MSDY.append(msdy / (6 * counter))
        MSDZ.append(msdz / (6 * counter))
        MSD.append(msd / (6 * counter))

    # ballistic_end = 100ps
    degree = 1
    start = int(round(len(MSD) / 5.0))
    p = np.polyfit(time[start:], MSD[start:],
                   degree)  # last 4/5 of the dataset
    f = np.polyval(p, time)
    d_mean_lastpart = p[
        0]  #*10**(-8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p1 = np.polyfit(time[0:start], MSD[0:start], degree)
    f1 = np.polyval(p1, time)
    d_mean_firstpart = p1[
        0]  #*10**(8)       # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p2 = np.polyfit(time[0:int(round(start / 2.0))],
                    MSD[0:int(round(start / 2.0))], degree)
    f2 = np.polyval(p2, time)
    d_mean_initpart = p2[
        0]  #*10**(8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p3 = np.polyfit(time[0:100], MSD[0:100], degree)
    f3 = np.polyval(p3, time)
    d_mean_actual = p3[
        0]  #*10**(8)          # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    print "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
    print " Nvalues in estimate 1 = 100"
    print " Nvalues in estimate 2 = %g" % (int(round(start / 2.0)))
    print " Nvalues in estimate 3 = %g" % (int(round(start)))
    print " Nvalues in estimate 4 = %g" % (len(time[start:]))

    ###############################################################################
    #                             plotting
    #plt.close('all')
    plt.figure()  # Figure 1
    Title = 'Mean square displacement'
    legends = ['$msd_{x}$', '$msd_{y}$', '$msd_{z}$', '$msd$']  #['$msd$']#
    Ylabel = 'mean square displacement $ [A^2] $'
    Xlabel = 'time $ [ps] $'
    pltname = 'MSD_bulkwater'
    linestyles = ['--r', '--y', '--k', 'o-b']  #['--r'] #
    plt.hold(True)
    plt.plot(time, MSDX, linestyles[0])
    plt.plot(time, MSDY, linestyles[1])
    plt.plot(time, MSDZ, linestyles[2])
    plt.plot(time, MSD, linestyles[3], markevery=10)
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends, loc='lower right')
    plt.hold(False)
    write_to_file(ofile, Title, Xlabel, Ylabel, pltname, legends, linestyles,
                  [time], [MSDX, MSDY, MSDZ, MSD])

    from mpl_toolkits.axes_grid.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

    plt.figure()
    ax = plt.axes()  # Figure 2
    Title = 'Mean square displacement'
    legends = [
        'MSD',
        '$f_1 %.3f $' % (d_mean_actual),
        '$f_2 %.3f $' % (d_mean_initpart),
        '$f_3 %.3f $' % (d_mean_firstpart),
        '$f_4 %.3f $' % (d_mean_lastpart)
    ]
    pltname = 'MSD_bulkwater_mean'
    Xlabel = 'time $ [ps] $'
    Ylabel = 'mean square displacement $ [A^2] $'
    linestyles = ['b-', '--y', '--r', '--m', '--y']

    plt.hold(True)
    plt.plot(time, MSD, linestyles[0])
    plt.plot(time[0:int(round(len(f) / 8.0))], f3[0:int(round(len(f) / 8.0))],
             linestyles[1])  # very first part
    plt.plot(time[0:int(round(len(f) / 6.0))], f2[0:int(round(len(f) / 6.0))],
             linestyles[2])  # initpart
    plt.plot(time[0:int(round(len(f) / 5.0))], f1[0:int(round(len(f) / 5.0))],
             linestyles[3])  # firstpart
    plt.plot(time, f, linestyles[4])  # lastpart

    plt.hold(False)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends, loc='lower right')
    plt.title(Title)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    axin = inset_axes(ax, width="30%", height="35%", loc=8)
    plt.hold(True)
    axin.plot(time, MSD, linestyles[0])
    axin.plot(time, f3, linestyles[1], linewidth=3.0)
    axin.plot(time, f2, linestyles[2])
    #axin.plot(time,f1,linestyles[3])
    plt.hold(False)
    axin.set_xlim(500, 520)
    ya = 0.0
    yb = 4.0
    Npoints = 4
    points = np.linspace(ya, yb, Npoints)
    axin.set_ylim(ya, yb)
    axin.set_xticks([])
    axin.set_yticks(points)
    mark_inset(ax, axin, loc1=3, loc2=4, fc="none", ec="0.5")

    write_to_file(ofile, Title, Xlabel, Ylabel, pltname, legends, linestyles,
                  [time], [MSD, f])

    print "#################################################################"
    print "# Diffusion estimate f1   : D = %.10f " % (d_mean_actual)
    print "# Diffusion estimate f2   : D = %.10f " % (d_mean_initpart)
    print "# Diffusion estimate f3   : D = %.10f " % (d_mean_firstpart)
    print "# Diffusion estimate f4   : D = %.10f " % (d_mean_lastpart)

    plt.figure()  # Figure 3
    Title = 'Time evolution of the local diffusion constant. $ D=(msd/6dt) $'
    legends = ['$D(t)$']
    linestyles = ['-y']
    pltname = 'Diffusion_bulkwater'
    Ylabel = 'displacement $ [ %g m^2/s]$' % factor
    plt.hold(True)
    plt.plot(time, D_local, linestyles[0])
    plt.hold(False)
    plt.legend(legends, loc='upper right')
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    write_to_file(ofile, Title, Xlabel, Ylabel, pltname, legends, linestyles,
                  [time], [D_local])

    plt.show()
    fontsize=12,
    color='black',
    transform=plt.gcf().transFigure,
    bbox=dict(facecolor='white', edgecolor='blue', pad=8.0),
    ha='center',
    va='center')

# Create a set of inset Axes: these should fill the bounding box allocated to
# them.
ax2 = plt.axes([0, 0, 1, 1])
# Manually set the position and relative size of the inset axes within ax1
ip = InsetPosition(ax1, [0.75, 0.7, 0.3, 0.4])
ax2.set_axes_locator(ip)
# Mark the region corresponding to the inset axes on ax1 and draw lines
# in grey linking the two axes.
mark_inset(ax1, ax2, loc1=2, loc2=4, fc="none", ec='0.5')

# The data into the ax2
ax2.hist(data_14_degrees['M'][condition_mass_14],
         bins=1000,
         weights=None,
         histtype='step',
         align='mid',
         orientation='vertical',
         color='r',
         label='M measured')
ax2.hist(data_14_degrees['Qi'][condition_mass_14] *
         data_14_degrees['M_Q'][condition_mass_14],
         bins=1000,
         weights=None,
         histtype='step',
Esempio n. 9
0
# formatting the plot
ax.xaxis.set_minor_locator(pylab.MultipleLocator(5))
ax.yaxis.set_minor_locator(pylab.MultipleLocator(0.1))
ax.grid(b=True,which="minor",axis='x')
ax.grid(b=True,which="minor",axis='y')
ax.set_xticks(range(1850,2030,10))
ax.set_xlim(1843,2021)
ax.set_ylim(-1.03,0.89)
ax.set_xlabel("Year")
legend = ax.legend(loc="upper left",fontsize=14)
frame = legend.get_frame()
frame.set_facecolor('1.0')
ax.set_ylabel("Anomaly")

# adding an inset axis to view the downturn at the end better
inset_axes = zoomed_inset_axes(ax, 3, loc=4)
inset_axes.scatter(df2.Date,df2.Anomaly,s=15,marker='o',facecolor="1.0",lw=0.5,edgecolor="0.0")
inset_axes.plot(df2.Date[s12:-e12],yr1LP2,'-y',label='Annual LP')
inset_axes.plot(df2.Date[s152:-e152],yr15LP2,'-g',label='>15 yr LP')
inset_axes.plot(df2.Date[s752:-e752],yr75LP2,'-b',label='>30 yr LP')
inset_axes.plot(df2.Date,yr15SG2,'--r',label='S-G 15 yr')
x1, x2, y1, y2 = 2000, 2015, 0.3, 0.6
inset_axes.set_xlim(x1, x2)
inset_axes.set_ylim(y1, y2)
inset_axes.set_xticks([])
inset_axes.set_yticks([])
inset_axes.set_axis_bgcolor("1.0")
ax.set_title("HadCrut4 Monthly Anomaly Smoothing by CTRM and Savitsky-Golay")
mark_inset(ax, inset_axes, loc1=1, loc2=2, fc="none", ec="0.0");
pylab.show()
def plots(XX, XF, X_update, up_a, xposition, mode, mode_title):

    font_size = 18
    font = {'size': font_size}
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    matplotlib.rc('font', **font)

    plt.rc('xtick', labelsize=30)
    plt.rc('ytick', labelsize=30)

    plt.figure(figsize=(13, 10))
    ax = plt.subplot(111)

    if mode == 'Longitudinal':
        lb = ['$u$', '$w$', '$q$', '$\\theta$']
    elif mode == 'Lateral_directional':
        lb = ['$v$', '$p$', '$r$', '$\phi$']

    line1 = []
    for i in range(4):
        line1.append(0)
        line1[i], = ax.plot(XX[i, :], alpha=0.35, label=lb[i])

    l4, = ax.plot(la.norm(X_update, axis=0),
                  color='b',
                  linewidth=2.5,
                  label='$\|x_t\|$ LQR for $\hat{A}$')
    l1, = ax.plot(la.norm(XX, axis=0),
                  color='k',
                  linewidth=2.5,
                  label='$\|x_t\|$ DGR ON')
    l2, = ax.plot(la.norm(XF, axis=0),
                  color='r',
                  linewidth=2.5,
                  label='$\|x_t\|$ DGR OFF')
    l3, = ax.plot(up_a, color='g', linewidth=2.5, label='Upper Bound')

    box = ax.get_position()

    first_legend = plt.legend(handles=[l1, l2, l3, l4],
                              loc='upper right',
                              prop={'size': 24})
    leg = plt.gca().add_artist(first_legend)

    second_legend = plt.legend(handles=line1,
                               prop={'size': 24},
                               loc='lower right',
                               bbox_to_anchor=(0.98, 0.39),
                               borderaxespad=0)
    leg = plt.gca().add_artist(second_legend)

    ax.axvline(x=xposition, color='gray', linestyle='--', linewidth=3.0)

    plt.xlim(0, 130)
    plt.ylim(-10, 75)
    plt.xlabel('Iteration $t$', fontsize=30)
    plt.title(mode_title, fontsize=30)
    plt.grid()
    plt.show()

    # Inner Plot

    # Create a set of inset Axes: these should fill the bounding box allocated to
    # them.
    ax2 = plt.axes([0, 0, 1, 1])
    # Manually set the position and relative size of the inset axes within ax1
    ip = InsetPosition(ax, [0.32, 0.43, 0.5, 0.2])
    ax2.set_axes_locator(ip)
    # Mark the region corresponding to the inset axes on ax1 and draw lines
    # in grey linking the two axes.
    mark_inset(ax, ax2, loc1=3, loc2=4, fc="none", ec='y', linewidth=2.0)

    ax2.set_title('zoom in', size=25)
    ax2.set(ylim=([-0.5, 3]), xlim=([xposition, 130]))
    ax2.plot(la.norm(X_update, axis=0), color='b', linewidth=2.5)
    ax2.plot(la.norm(XX, axis=0), color='k', linewidth=2.5)
    ax2.plot(up_a, color='g', linewidth=2.5, label='Upper Bound')

    line1 = []
    lb = ['$u$', '$w$', '$q$', '$\\theta$', '$v$', '$p$', '$r$', '$\phi$']
    for i in range(4):
        line1.append(0)
        line1[i], = ax2.plot(XX[i, :], alpha=0.35, label=lb[i])
Esempio n. 11
0
ax2.plot(vtx[2, 0], vtx[2, 1], 'bs', markersize=10)

plt.axis('equal')
plt.axis('off')
# plt.title('Grain %d \n'%grain_id+r' $\Delta$g = %.3f$^\circ$'%(mis_ang_deg[-1]),fontsize=22)

plt.title(r' $\Delta$g = %.3f$^\circ$' % (mis_ang_deg[-1]), fontsize=22)
plt.text(-0.08, -0.08, '(0001)', fontsize=16)
plt.text(0.9, -0.08, r'(10$\bar{1}$0)', fontsize=16)
plt.text(0.65, 0.49, r'(11$\bar{2}$0)', fontsize=16)

ax_in = plt.axes([0, 0, 1, 1])
ip = InsetPosition(ax2, [0.25, -0.5, 0.5, 0.5])
ax_in.set_axes_locator(ip)

for i in range(len(pts)):
    ax_in.plot(pts[i, 0], pts[i, 1], 'o', color=cmaplist[colornums[i]])

# plt.axis([0.29,0.32,0.02,0.035])

mark_inset(ax2, ax_in, loc1=1, loc2=2, fc="none", ec='0.5')

plt.axis('equal')
ax_in.set_xticklabels('')
ax_in.set_yticklabels('')

#%%

# fig2.savefig('/Users/rachellim/Documents/Research/CHESS_Jun17/2020-08-03/figs/ipfs/grain%d_ipf.jpg'%grain_id,
#              bbox_inches='tight',dpi=300)
Esempio n. 12
0
    data[np.isnan(data)] = 0
    extent = [0., 192., 0., 192.]
    im = grid[i].imshow(data, extent=extent, interpolation="nearest")
    grid[i].text(10, 170, letters[i], fontsize=20, color="white")
    data_zoom = data[135:155, 80:100, ]
    axins = zoomed_inset_axes(grid[i], 2, loc=3)  # zoom = 6
    extent = [
        80.,
        100.,
        192. - 155.,
        192. - 135,
    ]
    im2 = axins.imshow(data_zoom, extent=extent, interpolation="nearest")
    im2.set_clim([data.min(), data.max()])
    plt.xticks(visible=False)
    plt.yticks(visible=False)
    im.set_clim([0., .3])
    im2.set_clim([0., .3])
    mark_inset(grid[i], axins, loc1=2, loc2=4, fc="none", ec="0.5")

grid[0].set_xticks(())
grid[0].set_yticks(())
plt.subplots_adjust(left=0.,
                    right=1.,
                    top=.99,
                    bottom=.01,
                    wspace=0.,
                    hspace=0.)
plt.show()
fig.savefig(out_fname)
Esempio n. 13
0
def show_coord_topo_zoom(windpark, show=True):
    """Plot the topology of a given windpark

    Topographic Map with farms
    see: http://matplotlib.org/basemap/users/examples.html
    Basemap

    Parameters
    ----------

    windpark : Windpark
               A given windpark to show the topology.
    """

    plt.clf()

    turbines = windpark.get_turbines()
    target = windpark.get_target()
    radius = windpark.get_radius()

    #pack latitude and longitude in lists
    rel_input_lat = []
    rel_input_lon = []
    for row in turbines:
        rel_input_lat.append(np.float64(row.latitude))
        rel_input_lon.append(np.float64(row.longitude))

    targetcoord = [0.0, 0.0]
    targetcoord[0] = np.float64(target.latitude)
    targetcoord[1] = np.float64(target.longitude)

    graddiff = (800 / 111.0) + 0.5  # degree in km... 800km

    fig = plt.figure(figsize=(11.7, 8.3))
    plt.title("Location of the farm")

    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(111)

    m = Basemap(projection='lcc', lon_0=targetcoord[1], lat_0=targetcoord[0],\
        llcrnrlon = targetcoord[1]-graddiff*2, llcrnrlat = targetcoord[0]-graddiff ,\
        urcrnrlon = targetcoord[1]+graddiff, urcrnrlat = targetcoord[0]+graddiff ,\
        rsphere=6371200., resolution = None, area_thresh=1000)

    # Target
    x_target, y_target = m(targetcoord[1], targetcoord[0])
    # Input Farms
    rel_inputs_lon, rel_inputs_lat = m(rel_input_lon, rel_input_lat)

    # labels = [left,right,top,bottom]
    parallels = np.arange(int(targetcoord[0] - 7), int(targetcoord[0] + 7), 2.)
    m.drawparallels(parallels, labels=[False, True, True, False])
    meridians = np.arange(int(targetcoord[1] - 7), int(targetcoord[1] + 7), 2.)
    m.drawmeridians(meridians, labels=[True, False, False, True])

    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    # m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()

    # we define the inset_axes, with a zoom of 2 and at location 2 (upper left corner)
    # axins = zoomed_inset_axes(ax, 40, loc=2)
    axins = inset_axes(
        ax,
        width="65%",  # width = 30% of parent_bbox
        height="65%",  # height : 1 inch
        loc=3)

    # plot farms in the radius
    m.plot(x_target, y_target, 'bo')
    m.plot(rel_inputs_lon, rel_inputs_lat, 'r*')

    #m.bluemarble()
    m.shadedrelief()
    #m.etopo()
    #m.drawcoastlines()

    graddiff_park = (radius / (111.0 * 0.7))  # degree in km
    x, y = m(targetcoord[1] - graddiff_park, targetcoord[0] - graddiff_park)
    x2, y2 = m(targetcoord[1] + graddiff_park, targetcoord[0] + graddiff_park)

    axins.set_xlim(
        x, x2)  # and we apply the limits of the zoom plot to the inset axes
    axins.set_ylim(y, y2)  # idem
    plt.xticks(visible=False)  # we hide the ticks
    plt.yticks(visible=False)
    mark_inset(
        ax, axins, loc1=1, loc2=4, fc="none", ec="0.9", linewidth=3
    )  # we draw the "zoom effect" on the main map (ax), joining cornder 1 & 3

    plt.title("Selected Wind Farms")
    if (show):
        plt.show()
Esempio n. 14
0
def make_rq(data_dir):   
    # set plotting style
    mpl.rcParams['font.size']=10
    mpl.rcParams['legend.fontsize']='small'
    mpl.rcParams['figure.autolayout']=True
    mpl.rcParams['figure.figsize']=[8.0,6.0]

    # ==================================================================
    # define DAQ and other parameters
    #wsize = 12500             # size of event window in samples. 1 sample = 2 ns.
    #read event window width from the folder name
    if data_dir.find("3us") != -1: 
        event_window = 3
    if data_dir.find("25us") != -1:
        event_window = 25   # in us. 

    wsize = int(500 * event_window)  # samples per waveform # 12500 for 25 us
    vscale = (2000.0/16384.0) # = 0.122 mV/ADCC, vertical scale
    tscale = (8.0/4096.0)     # = 0.002 µs/sample, time scale

    save_avg_wfm = False # get the average waveform passing some cut and save to file

    post_trigger = 0.5 # Was 0.2 for data before 11/22/19
    trigger_time_us = event_window*(1-post_trigger)
    trigger_time = int(trigger_time_us/tscale)

    n_sipms = 8
    n_channels = n_sipms+1 # includes sum

    # define top, bottom channels
    n_top = int((n_channels-1)/2)
    top_channels=np.array(range(n_top),int)
    bottom_channels=np.array(range(n_top,2*n_top),int)

    # sphe sizes in mV*sample
    ns_to_sample = 1024./2000. #convert spe size unit from mV*ns to mV*sample
    spe = {}
    with open(data_dir+"spe.txt", 'r') as file:
        for line in file:
            (key, val) = line.split()
            spe[key] = float(val)*ns_to_sample

    chA_spe_size = spe["ch0"]#29.02
    chB_spe_size = spe["ch1"]#30.61
    chC_spe_size = spe["ch2"]#28.87
    chD_spe_size = spe["ch3"]#28.86*1.25 # scale factor (0.7-1.4) empirical as of Dec 9, 2020
    chE_spe_size = spe["ch4"]#30.4
    chF_spe_size = spe["ch5"]#30.44
    chG_spe_size = spe["ch6"]#30.84
    chH_spe_size = spe["ch7"]#30.3*1.8 # scale factor (1.6-2.2) empirical as of Dec 9, 2020
    spe_sizes = [chA_spe_size, chB_spe_size, chC_spe_size, chD_spe_size, chE_spe_size, chF_spe_size, chG_spe_size, chH_spe_size]

    # ==================================================================

    #load in raw data

    t_start = time.time()

    block_size = 3000
    n_block = 500
    max_evts = n_block*block_size#5000  # 25000 # -1 means read in all entries; 25000 is roughly the max allowed in memory on the DAQ computer
    max_pts = -1  # do not change
    if max_evts > 0:
        max_pts = wsize * max_evts
    load_dtype = "int16"

    # pulse RQs to save

    # RQs to add:
    # Pulse level: channel areas (fracs; max fracs), TBA, rise time? (just difference of AFTs...)
    # Event level: drift time; S1, S2 area
    # Pulse class (S1, S2, other)
    # max number of pulses per event
    max_pulses = 4
    p_start = np.zeros(( max_evts, max_pulses), dtype=int)
    p_end   = np.zeros(( max_evts, max_pulses), dtype=int)
    p_found = np.zeros(( max_evts, max_pulses), dtype=int)

    #center of mass
    center_top_x = np.zeros(( max_evts, max_pulses))
    center_top_y = np.zeros(( max_evts, max_pulses))
    center_bot_x = np.zeros(( max_evts, max_pulses))
    center_bot_y = np.zeros(( max_evts, max_pulses))

    p_area = np.zeros(( max_evts, max_pulses))
    p_max_height = np.zeros(( max_evts, max_pulses))
    p_min_height = np.zeros(( max_evts, max_pulses))
    p_width = np.zeros(( max_evts, max_pulses))

    p_afs_2l = np.zeros((max_evts, max_pulses) )
    p_afs_2r = np.zeros((max_evts, max_pulses) )
    p_afs_1 = np.zeros((max_evts, max_pulses) )
    p_afs_25 = np.zeros((max_evts, max_pulses) )
    p_afs_50 = np.zeros((max_evts, max_pulses) )
    p_afs_75 = np.zeros((max_evts, max_pulses) )
    p_afs_99 = np.zeros((max_evts, max_pulses) )
                
    p_hfs_10l = np.zeros((max_evts, max_pulses) )
    p_hfs_50l = np.zeros((max_evts, max_pulses) )
    p_hfs_10r = np.zeros((max_evts, max_pulses) )
    p_hfs_50r = np.zeros((max_evts, max_pulses) )

    p_mean_time = np.zeros((max_evts, max_pulses) )
    p_rms_time = np.zeros((max_evts, max_pulses) )

    # Channel level (per event, per pulse, per channel)
    p_start_ch = np.zeros((max_evts, max_pulses, n_channels-1), dtype=int)
    p_end_ch = np.zeros((max_evts, max_pulses, n_channels-1), dtype=int )
    p_area_ch = np.zeros((max_evts, max_pulses, n_channels-1) )
    p_area_ch_frac = np.zeros((max_evts, max_pulses, n_channels-1) )

    p_area_top = np.zeros((max_evts, max_pulses))
    p_area_bottom = np.zeros((max_evts, max_pulses))
    p_tba = np.zeros((max_evts, max_pulses))

    p_class = np.zeros((max_evts, max_pulses), dtype=int)

    # Event-level variables
    n_pulses = np.zeros(max_evts, dtype=int)

    n_s1 = np.zeros(max_evts, dtype=int)
    n_s2 = np.zeros(max_evts, dtype=int)
    sum_s1_area = np.zeros(max_evts)
    sum_s2_area = np.zeros(max_evts)
    drift_Time = np.zeros(max_evts)
    drift_Time_AS = np.zeros(max_evts) # for multi-scatter drift time, defined by the first S2. 
    s1_before_s2 = np.zeros(max_evts, dtype=bool)

    n_wfms_summed = 0
    avg_wfm = np.zeros(wsize)

    # Temporary, for testing low area, multiple-S1 events
    dt = np.zeros(max_evts)
    small_weird_areas = np.zeros(max_evts)
    big_weird_areas = np.zeros(max_evts)

    n_golden = 0
    inn=""

    inn="" # used to control hand scan

    empty_evt_ind = np.zeros(max_evts)

    for j in range(n_block):
        ch_data = []
        for ch_ind in range(n_sipms):
            ch_data.append(np.fromfile(data_dir + "wave"+str(ch_ind)+".dat", dtype=load_dtype, offset = block_size*wsize*j, count=wsize*block_size))

        #t_end_load = time.time()
        #print("Time to load files: ", t_end_load-t_start)

        # scale waveforms to get units of mV/sample
        # then for each channel ensure we 
        # have an integer number of events
        array_dtype = "float32" # using float32 reduces memory for big files, otherwise implicitly converts to float64

        # matrix of all channels including the sum waveform
        v_matrix_all_ch = []
        for ch_ind in range(n_sipms):
            V = vscale * ch_data[ch_ind].astype(array_dtype) / spe_sizes[ch_ind]
            V = V[:int(len(V) / wsize) * wsize]
            V = V.reshape(int(V.size / wsize), wsize) # reshape to make each channel's matrix of events
            v_matrix_all_ch.append(V)
            if ch_ind==0: v_sum = np.copy(V)
            else: v_sum += V
        v_matrix_all_ch.append(v_sum)
        
        # create a time axis in units of µs:
        x = np.arange(0, wsize, 1)
        t = tscale*x
        t_matrix = np.repeat(t[np.newaxis,:], V.size/wsize, 0)
        # Note: if max_evts != -1, we won't load in all events in the dataset
        n_events = int(v_matrix_all_ch[0].shape[0])
        if n_events == 0: break
            
        # perform baseline subtraction for full event (separate from pulse-level baseline subtraction):
        baseline_start = int(0./tscale)
        baseline_end = np.min((int(wsize*0.2), 1000))

        # baseline subtracted (bls) waveforms saved in this matrix:
        v_bls_matrix_all_ch = np.zeros( np.shape(v_matrix_all_ch), dtype=array_dtype) # dims are (chan #, evt #, sample #)

        #t_end_wfm_fill = time.time()
        #print("Time to fill all waveform arrays: ", t_end_wfm_fill - t_end_load)

        #print("Events to process: ",n_events)
        for i in range(0, n_events):
            
            sum_baseline = np.mean( v_matrix_all_ch[-1][i,baseline_start:baseline_end] ) #avg ~us, avoiding trigger
            baselines = [ np.mean( ch_j[i,baseline_start:baseline_end] ) for ch_j in v_matrix_all_ch ]
            
            sum_data = v_matrix_all_ch[-1][i,:] - sum_baseline
            ch_data = [ch_j[i,:]-baseline_j for (ch_j,baseline_j) in zip(v_matrix_all_ch,baselines)]
            
            v_bls_matrix_all_ch[:,i,:] = ch_data


        # ==================================================================
        # ==================================================================
        # now setup for pulse finding on the baseline-subtracted sum waveform

        
    #check mark

        #print("Running pulse finder on {:d} events...".format(n_events))

        # use for coloring pulses
        pulse_class_colors = np.array(['blue', 'green', 'red', 'magenta', 'darkorange'])
        pulse_class_labels = np.array(['Other', 'S1-like LXe', 'S1-like gas', 'S2-like', 'Merged S1/S2'])
        pc_legend_handles=[]
        for class_ind in range(len(pulse_class_labels)):
            pc_legend_handles.append(mpl.patches.Patch(color=pulse_class_colors[class_ind], label=str(class_ind)+": "+pulse_class_labels[class_ind]))

        for i in range(j*block_size, j*block_size+n_events):
            if (i)%2000==0: print("Event #",i)
            
            # Find pulse locations; other quantities for pf tuning/debugging
            start_times, end_times, peaks, data_conv, properties = pf.findPulses( v_bls_matrix_all_ch[-1,i-j*block_size,:], max_pulses , SPEMode=False)


            # Sort pulses by start times, not areas
            startinds = np.argsort(start_times)
            n_pulses[i] = len(start_times)
            if (n_pulses[i] < 1):
                #print("No pulses found for event {0}; skipping".format(i))
                empty_evt_ind[i] = i
                #continue
            for m in startinds:
                if m >= max_pulses:
                    continue
                p_start[i,m] = start_times[m]
                p_end[i,m] = end_times[m]

            # Individual channel pulse locations, in case you want this info
            # Can't just ":" the the first index in data, findPulses doesn't like it, so have to loop 
            #for j in range(n_channels-1):
            #    start_times_ch, end_times_ch, peaks_ch, data_conv_ch, properties_ch = pf.findPulses( v_bls_matrix_all_ch[j,i,:], max_pulses )
                # Sorting by start times from the sum of channels, not each individual channel
            #    for k in startinds:
            #        if k >= len(start_times_ch):
            #            continue
            #        p_start_ch[i,k,j] = start_times_ch[k]
            #        p_end_ch[i,k,j] = end_times_ch[k]
                

            # More precisely estimate baselines immediately before each pulse
            baselines_precise = pq.GetBaselines(p_start[i,:n_pulses[i]], p_end[i,:n_pulses[i]], v_bls_matrix_all_ch[:,i-j*block_size,:])

            # Calculate interesting quantities, only for pulses that were found
            for pp in range(n_pulses[i]):
                # subtract out more precise estimate of baseline for better RQ estimates
                baselines_pulse = baselines_precise[pp] # array of baselines per channel, for this pulse
                v_pulse_bls = np.array([ch_j - baseline_j for (ch_j, baseline_j) in zip(v_bls_matrix_all_ch[:,i-j*block_size,:], baselines_pulse)])

                # Version w/o pulse-level baseline subtraction
                #v_pulse_bls = v_bls_matrix_all_ch[:,i-j*block_size,:]

                # copied from above, for reference
                #sum_data = v_matrix_all_ch[-1][i, :] - sum_baseline
                #ch_data = [ch_j[i, :] - baseline_j for (ch_j, baseline_j) in zip(v_matrix_all_ch, baselines)]

                # Area, max & min heights, width, pulse mean & rms
                p_area[i,pp] = pq.GetPulseArea(p_start[i,pp], p_end[i,pp], v_pulse_bls[-1] )
                p_max_height[i,pp] = pq.GetPulseMaxHeight(p_start[i,pp], p_end[i,pp], v_pulse_bls[-1] )
                p_min_height[i,pp] = pq.GetPulseMinHeight(p_start[i,pp], p_end[i,pp], v_pulse_bls[-1] )
                p_width[i,pp] = p_end[i,pp] - p_start[i,pp]
                #(p_mean_time[i,pp], p_rms_time[i,pp]) = pq.GetPulseMeanAndRMS(p_start[i,pp], p_end[i,pp], v_bls_matrix_all_ch[-1,i,:])

                # Area and height fractions      
                (p_afs_2l[i,pp], p_afs_1[i,pp], p_afs_25[i,pp], p_afs_50[i,pp], p_afs_75[i,pp], p_afs_99[i,pp]) = pq.GetAreaFraction(p_start[i,pp], p_end[i,pp], v_pulse_bls[-1] )
                (p_hfs_10l[i,pp], p_hfs_50l[i,pp], p_hfs_10r[i,pp], p_hfs_50r[i,pp]) = pq.GetHeightFractionSamples(p_start[i,pp], p_end[i,pp], v_pulse_bls[-1] )
            
                # Areas for individual channels and top bottom
                p_area_ch[i,pp,:] = pq.GetPulseAreaChannel(p_start[i,pp], p_end[i,pp], v_pulse_bls )
                p_area_ch_frac[i,pp,:] = p_area_ch[i,pp,:]/p_area[i,pp]
                p_area_top[i,pp] = sum(p_area_ch[i,pp,top_channels])
                p_area_bottom[i,pp] = sum(p_area_ch[i,pp,bottom_channels])
                p_tba[i, pp] = (p_area_top[i, pp] - p_area_bottom[i, pp]) / (p_area_top[i, pp] + p_area_bottom[i, pp])
                center_top_x[i,pp] = (p_area_ch[i,pp,1]+p_area_ch[i,pp,3]-p_area_ch[i,pp,0]-p_area_ch[i,pp,2])/p_area_top[i,pp]
                center_top_y[i,pp] = (p_area_ch[i,pp,0]+p_area_ch[i,pp,1]-p_area_ch[i,pp,2]-p_area_ch[i,pp,3])/p_area_top[i,pp]
                center_bot_x[i,pp] = (p_area_ch[i,pp,5]+p_area_ch[i,pp,7]-p_area_ch[i,pp,4]-p_area_ch[i,pp,6])/p_area_bottom[i,pp]
                center_bot_y[i,pp] = (p_area_ch[i,pp,4]+p_area_ch[i,pp,5]-p_area_ch[i,pp,6]-p_area_ch[i,pp,7])/p_area_bottom[i,pp]
                
            # Pulse classifier, work in progress
            p_class[i,:] = pc.ClassifyPulses(p_tba[i, :], (p_afs_50[i, :]-p_afs_2l[i, :])*tscale, n_pulses[i], p_area[i,:])

            # Event level analysis. Look at events with both S1 and S2.
            index_s1 = (p_class[i,:] == 1) + (p_class[i,:] == 2) # S1's
            index_s2 = (p_class[i,:] == 3) + (p_class[i,:] == 4) # S2's
            n_s1[i] = np.sum(index_s1)
            n_s2[i] = np.sum(index_s2)
            
            if n_s1[i] > 0:
                sum_s1_area[i] = np.sum(p_area[i, index_s1])
            if n_s2[i] > 0:
                sum_s2_area[i] = np.sum(p_area[i, index_s2])
            if n_s1[i] == 1:
                if n_s2[i] == 1:
                    drift_Time[i] = tscale*(p_start[i, np.argmax(index_s2)] - p_start[i, np.argmax(index_s1)])
                    drift_Time_AS[i] = tscale*(p_start[i, np.argmax(index_s2)] - p_start[i, np.argmax(index_s1)])
                if n_s2[i] > 1:
                    s1_before_s2[i] = np.argmax(index_s1) < np.argmax(index_s2) 
                    drift_Time_AS[i] = tscale*(p_start[i, np.argmax(index_s2)] - p_start[i, np.argmax(index_s1)]) #For multi-scatter events. 
            
            if drift_Time[i]>0:
                n_golden += 1


            # =============================================================
            # draw the waveform and the pulse bounds found

            # Code to allow skipping to another event index for plotting
            plot_event_ind = i
            try:
                plot_event_ind = int(inn)
                if plot_event_ind < i:
                    inn = ''
                    plot_event_ind = i
                    print("Can't go backwards! Continuing to next event.")
            except ValueError:
                plot_event_ind = i

            # Condition to plot now includes this rise time calc, not necessary
            riseTimeCondition = ((p_afs_50[i,:n_pulses[i]]-p_afs_2l[i,:n_pulses[i]] )*tscale < 0.6)*((p_afs_50[i,:n_pulses[i]]-p_afs_2l[i,:n_pulses[i]] )*tscale > 0.2)
            
            po_test = np.any((p_area[i,:]>5.0e4)*((p_afs_50[i,:]-p_afs_2l[i,:] )*tscale<1.0))
            
            # Condition to skip the individual plotting, hand scan condition
            #plotyn = drift_Time[i]<2 and drift_Time[i]>0 and np.any((p_tba[i,:]>-0.75)*(p_tba[i,:]<-0.25)*(p_area[i,:]<3000)*(p_area[i,:]>1400))#np.any((p_tba[i,:]>-0.91)*(p_tba[i,:]<-0.82)*(p_area[i,:]<2800)*(p_area[i,:]>1000))# True#np.any(p_class[i,:]==4)#False#np.any(p_area[i,:]>1000) and 
            #plotyn = drift_Time[i]>2.5 and (center_bot_y[i,0]**2+center_bot_x[i,0]**2) <0.1
            plotyn = drift_Time[i]>1 #np.any((p_class[i,:] == 3) + (p_class[i,:] == 4))#np.any((p_tba[i,:]>-0.75)*(p_tba[i,:]<-0.25)*(p_area[i,:]<3000)*(p_area[i,:]>1000))
            #plotyn = np.any((p_tba[i,:]>-1)*(p_tba[i,:]<-0.25)*(p_area[i,:]<30000)*(p_area[i,:]>3000))#np.any((np.log10(p_area[i,:])>3.2)*(np.log10(p_area[i,:])<3.4) )#False#
            # Pulse area condition
            areaRange = np.sum((p_area[i,:] < 50)*(p_area[i,:] > 5))
            if areaRange > 0:
                dt[i] = abs(p_start[i,1] - p_start[i,0]) # For weird double s1 data
                weird_areas =[p_area[i,0], p_area[i,1] ]
                small_weird_areas[i] = min(weird_areas)
                big_weird_areas[i] = max(weird_areas)

            # Condition to include a wfm in the average
            add_wfm = np.any((p_area[i,:]>5000)*(p_tba[i,:]<-0.75))*(n_s1[i]==1)*(n_s2[i]==0)
            if add_wfm and save_avg_wfm:
                plotyn = add_wfm # in avg wfm mode, plot the events which will go into the average
                avg_wfm += v_bls_matrix_all_ch[-1,i-j*block_size,:]
                n_wfms_summed += 1

            # Both S1 and S2 condition
            s1s2 = (n_s1[i] == 1)*(n_s2[i] == 1)

            if inn == 's': sys.exit()
            
            if not inn == 'q' and plot_event_ind == i and plotyn:

                fig = pl.figure(1,figsize=(10, 3.5))
                pl.rc('xtick', labelsize=10)
                pl.rc('ytick', labelsize=10)

                ax = pl.subplot()

                ch_labels = ['A','B','C','D','E','F','G','H']
                ch_colors = [pl.cm.tab10(ii) for ii in range(n_channels)]
                #pl.plot(t,v_bls_matrix_all_ch[-1,i,:],'blue')
                #pl.plot( x*tscale, v_bls_matrix_all_ch[-1,i-j*block_size,:],'blue' )
                #pl.xlim([0,wsize])
                #pl.xlim([0,event_window])
                trigger_time_us = 12 # for some reason seems to be consistently closer to 12 than 12.5
                pl.xlim([start_times[0]*tscale-3-trigger_time_us,end_times[1]*tscale+1.5-trigger_time_us])
                #pl.ylim( [-1, 1.01*np.max(v_bls_matrix_all_ch[-1,i-j*block_size,:])])
                pl.ylim( [-1, 1.1*np.max(v_bls_matrix_all_ch[:-1,i-j*block_size,:])])
                pl.xlabel('Time ($\mu$s)')
                #pl.xlabel('Samples')
                pl.ylabel('phd/sample')
                #pl.title("Sum, event "+ str(i))
                pl.grid(b=True,which='major',color='lightgray',linestyle='--')
                #pl.legend(handles=pc_legend_handles)

                dead_channels = [2,7]
                for i_chan in range(n_channels - 1):
                    if i_chan in dead_channels: continue
                    pl.plot(t-trigger_time_us, v_bls_matrix_all_ch[i_chan, i - j * block_size, :], color=ch_colors[i_chan],
                            label=ch_labels[i_chan])
                    # pl.plot( x, v_bls_matrix_all_ch[i_chan,i,:],color=ch_colors[i_chan],label=ch_labels[i_chan] )
                    #pl.xlim([trigger_time_us - 8, trigger_time_us + 8])
                    # pl.xlim([wsize/2-4000,wsize/2+4000])
                    #pl.ylim([-5, 3000 / chA_spe_size])
                    #pl.xlabel('Time (us)')
                    # pl.xlabel('Samples')
                    #pl.ylabel('phd/sample')
                    #pl.legend()

                for pulse in range(len(start_times)):
                    class_name = "S1"
                    if p_class[i,pulse] == 3 or p_class[i,pulse] == 4: class_name = "S2"
                    ax.axvspan(start_times[pulse] * tscale-trigger_time_us, end_times[pulse] * tscale-trigger_time_us, alpha=0.1, color=pulse_class_colors[p_class[i, pulse]])
                    ax.text((end_times[pulse]) * tscale+0.1-trigger_time_us, 0.9 * ax.get_ylim()[1], class_name,
                        fontsize=10, color=pulse_class_colors[p_class[i, pulse]])
                    ax.text((end_times[pulse]) * tscale+0.1-trigger_time_us, 0.84 * ax.get_ylim()[1], 'Area = {:.1f} phd'.format(p_area[i, pulse]),
                            fontsize=10, color=pulse_class_colors[p_class[i, pulse]])
                    ax.text((end_times[pulse]) * tscale+0.1-trigger_time_us, 0.73 * ax.get_ylim()[1], '$A_{{TB}}$ = {:.1f}'.format(p_tba[i, pulse]),
                        fontsize=10, color=pulse_class_colors[p_class[i, pulse]])
                
                #ax.axhline( 0.276, 0, wsize, linestyle='--', lw=1, color='orange')

                # Draw drift time w/ arrow
                arrow_alpha = 0.8
                head_length = 0.1
                pl.arrow(start_times[0] * tscale-trigger_time_us, 0.5 * ax.get_ylim()[1], drift_Time[i]-head_length, 0, head_width=1.2, head_length=head_length, width=0.05, color='b', alpha=arrow_alpha)
                ax.text(start_times[0] * tscale-trigger_time_us + drift_Time[i]/5, 0.57 * ax.get_ylim()[1], r'Drift time={:.1f} $\mu$s'.format(drift_Time[i]),
                        fontsize=10, color='b')

                # Create a set of inset Axes: these should fill the bounding box allocated to
                # them.
                from mpl_toolkits.axes_grid.inset_locator import (inset_axes, InsetPosition,
                                                                  mark_inset)
                ax2 = pl.axes([0, 0, 1, 1])
                # Manually set the position and relative size of the inset axes within ax1
                ip = InsetPosition(ax, [0.05, 0.43, 0.25, 0.5])
                ax2.set_axes_locator(ip)
                #ax2.set_ylabel('phd/sample')
                #ax2.set_xlabel('Time (us)')
                # Mark the region corresponding to the inset axes on ax1 and draw lines
                # in grey linking the two axes.
                mark_inset(ax, ax2, loc1=1, loc2=3, fc="none", ec='0.5')
                ax2.grid(b=True,which='major',color='lightgray',linestyle='--')

                # Plot data in inset
                inset_start = start_times[0]
                inset_end = end_times[0]
                for i_chan in range(n_channels - 1):
                    if i_chan in dead_channels: continue
                    ax2.plot(t[inset_start:inset_end]-trigger_time_us, v_bls_matrix_all_ch[i_chan, i - j * block_size, inset_start:inset_end], color=ch_colors[i_chan],
                            label=ch_labels[i_chan])
                #ax2.plot(t[inset_start:inset_end],v_bls_matrix_all_ch[-1,i,inset_start:inset_end],'blue')
                #ax2.xlim((start_times[0]*tscale-1,end_times[0]*tscale+1))
                #ax2.ylim((start_times[0]*tscale-1,end_times[0]*tscale+1))
                #ax2.legend(loc=0)

                # Debugging of pulse finder
                debug_pf = False
                if debug_pf and n_pulses[i]>0:
                    pl.plot(t_matrix[i-j*block_size, :], data_conv, 'red')
                    pl.plot(t_matrix[i-j*block_size, :], np.tile(0., np.size(data_conv)), 'gray')
                    pl.vlines(x=peaks*tscale, ymin=data_conv[peaks] - properties["prominences"],
                               ymax=data_conv[peaks], color="C1")
                    pl.hlines(y=properties["width_heights"], xmin=properties["left_ips"]*tscale,
                               xmax=properties["right_ips"]*tscale, color="C1")
                    #print("pulse heights: ", data_conv[peaks] )
                    #print("prominences:", properties["prominences"])

                pl.draw()
                pl.show(block=0)
                inn = input("Press enter to continue, q to stop plotting, evt # to skip to # (forward only)")
                fig.clf()
                
        # end of pulse finding and plotting event loop

    if save_avg_wfm:
        avg_wfm /= n_wfms_summed
        np.savetxt(data_dir+'average_waveform.txt',avg_wfm)
        print("Average waveform saved")

    n_events = i
    t_end = time.time()
    print("total number of events processed:", n_events)
    print("Time used: {}".format(t_end-t_start))

    print("empty events: {0}".format(np.sum(empty_evt_ind>0)))
    # pl.hist(empty_evt_ind[empty_evt_ind>0], bins=1000)
    # pl.xlabel('Empty event index')
    # pl.show()

    #create a dictionary with all RQs
    list_rq = {}
    list_rq['center_top_x'] = center_top_x
    list_rq['center_top_y'] = center_top_y
    list_rq['center_bot_x'] = center_bot_x
    list_rq['center_bot_y'] = center_bot_y
    list_rq['n_s1'] = n_s1
    list_rq['n_s2'] = n_s2
    list_rq['s1_before_s2'] = s1_before_s2
    list_rq['n_pulses'] = n_pulses
    list_rq['n_events'] = n_events
    list_rq['p_area'] = p_area
    list_rq['p_class'] = p_class
    list_rq['drift_Time'] = drift_Time
    list_rq['drift_Time_AS'] = drift_Time_AS
    list_rq['p_max_height'] = p_max_height
    list_rq['p_min_height'] = p_min_height
    list_rq['p_width'] = p_width
    list_rq['p_afs_2l'] = p_afs_2l
    list_rq['p_afs_50'] = p_afs_50
    list_rq['p_area_ch'] = p_area_ch
    list_rq['p_area_ch_frac'] = p_area_ch_frac
    list_rq['p_area_top'] = p_area_top
    list_rq['p_area_bottom'] = p_area_bottom
    list_rq['p_tba'] = p_tba
    list_rq['p_start'] = p_start
    list_rq['p_end'] = p_end
    list_rq['sum_s1_area'] = sum_s1_area
    list_rq['sum_s2_area'] = sum_s2_area
    #list_rq[''] =    #add more rq

    #remove zeros in the end of each RQ array. 
    for rq in list_rq.keys():
        if rq != 'n_events':
            list_rq[rq] = list_rq[rq][:n_events]

    rq = open(data_dir + "rq.npz",'wb')
    np.savez(rq, **list_rq)
    rq.close()
Esempio n. 15
0
    figure()
    d = NormalDistr(2, 1) * NormalDistr(2, 1)
    demo_distr(d)
    #show()

    figure()
    d = NormalDistr(3, 1) * NormalDistr(3, 1)
    d.plot()
    d.hist()
    ax = gca()
    axins = zoomed_inset_axes(ax, 6, loc=1)
    d.plot(xmin=-1.5, xmax=1.5)
    axins.set_xlim(-1.5, 1.5)
    xticks(rotation="vertical")
    axins.set_ylim(0, 0.01)
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
    #show()

    figure()
    d = NormalDistr(4, 1) * NormalDistr(4, 1)
    d.plot()
    d.hist()
    ax = gca()
    axins = zoomed_inset_axes(ax, 12000, loc=1)
    d.plot(xmin=-.001, xmax=.001)
    axins.set_xlim(-.001, .001)
    xticks(rotation="vertical")
    axins.set_ylim(0.000072, 0.000075)
    mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

    #show()
 ## just passing transform=ax.transAxes as an argument to add_axes() does nothing.
 ## So you need to do some complicated jugglery
 ## (from http://matplotlib.1069221.n5.nabble.com/Adding-custom-axes-within-a-subplot-td20316.html)
 Bbox = matplotlib.transforms.Bbox.from_bounds(.75, .6, .5, .5) 
 trans = ax1.transAxes + fig.transFigure.inverted() 
 l, b, w, h = matplotlib.transforms.TransformedBbox(Bbox,trans).bounds
 axinset = fig.add_axes([l, b, w, h])
 axinset.plot(timevec,mit_responses[1][0]*1e3,color='r',linewidth=plot_linewidth,label='Lateral')
 ## thin frame
 for loc, spine in axinset.spines.items(): # items() returns [(key,value),...]
     spine.set_linewidth(axes_linewidth)
 axinset.set_xlim(910,975)
 axinset.set_ylim(-71.5,-70)
 axinset.set_xticks([])
 axinset.set_yticks([])
 mark_inset(ax1, axinset, loc1=2, loc2=4, fc="none", ec="0.5", linewidth=axes_linewidth)
 
 ## mitral B
 ax1 = fig.add_subplot(2,2,2)
 ax1.plot((tmin,tmax),(Vrest,Vrest),linestyle='dashed',linewidth=plot_linewidth,color=(0.5,0.5,0.5))
 ax1.plot(timevec,mit_responses[1][1]*1e3,color='g',linewidth=plot_linewidth,label='Lateral')
 beautify_plot(ax1,x0min=False,y0min=False,xticksposn='none',yticksposn='none')
 ax1.set_xlim(tmin,tmax)
 ax1.set_ylim(Vmin,Vmax)
 ax1.set_yticks([])
 axes_labels(ax1,'','')
 ax2 = fig.add_subplot(2,2,4)
 ax2.plot((tmin,tmax),(Vrest,Vrest),linestyle='dashed',linewidth=plot_linewidth,color=(0.5,0.5,0.5))
 ax2.plot(timevec,mit_responses[0][1]*1e3,color='g',linewidth=plot_linewidth,label='Recurrent')
 beautify_plot(ax2,x0min=False,y0min=False,xticksposn='bottom',yticksposn='none')
 ax2.set_xlim(tmin,tmax)
fig, ax = plt.subplots(figsize=(8,6))
axin1 = ax.inset_axes(
        [20, 12, 8, 4], transform=ax.transData)
axin1.plot(col_x_arr,col_y_arr, "r--")
#axin1.plot(col_x_arr,col_y2_arr,'b--')
axin1.set_xlim(0 , 5.0)
axin1.set_ylim(0, 2.0)
axin1.set(facecolor='white')
#axin1.grid(which='major', color='gray',linestyle='-') #Plot Gridlines in Subgrid
axin1.spines['bottom'].set_color('black')
axin1.spines['top'].set_color('black') 
axin1.spines['right'].set_color('black')
axin1.spines['left'].set_color('black')

#Marklines to trace inset
mark_inset(ax, axin1, loc1=2, loc2=4, fc="none", ec='0.5')


#Main Plot
line1=ax.plot(col_x_arr,col_y_arr)
#line2=ax.plot(col_x_arr,col_y2_arr)
ax.set_title('Matplotlib')
ax.set(facecolor='white')
ax.grid(which='major', color='lightgray',linestyle='-')
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_color('black') 
ax.spines['right'].set_color('black')
ax.spines['left'].set_color('black')
#ax.legend(loc=0) #Legend if available
plt.setp(line1, color='r', linewidth=2.0)
#plt.setp(line2, color='b', linewidth=2.0)
Esempio n. 18
0
def zoommap(vals, title, label):
    fig = plt.figure(figsize=(12, 8))
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(211)
    m = Basemap(projection='mill',
                llcrnrlat=-45,
                llcrnrlon=-160,
                urcrnrlat=82,
                urcrnrlon=170,
                resolution='c')
    x, y = m(lons, lats)
    m.drawcoastlines(linewidth=0.5)
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    cmap = matplotlib.colors.ListedColormap(
        ['#d73027', '#fc8d59', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4'])
    bounds = [0, 0.3, 0.5, 0.7, 0.8, 0.9, 1.0]
    norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
    m.scatter(x, y, s=40, c=vals, cmap=cmap, norm=norm)
    plt.colorbar(orientation="vertical",
                 boundaries=bounds,
                 spacing='proportional',
                 ticks=bounds)
    ax.text(0.03,
            0.95,
            label,
            size=12,
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
    plt.title(title, fontsize=14)
    #Zoom Europe
    axins_1 = zoomed_inset_axes(ax,
                                2,
                                loc=2,
                                bbox_to_anchor=(0.396, 0.48),
                                bbox_transform=ax.figure.transFigure)
    axins_1.scatter(x, y, s=20, c=vals, cmap=cmap, norm=norm)
    m.drawcoastlines(linewidth=0.5)
    x2, y2 = m(-12, 35)
    x3, y3 = m(40, 65)
    axins_1.set_xlim(x2, x3)
    axins_1.set_ylim(y2, y3)
    axes = mark_inset(ax, axins_1, loc1=1, loc2=2, linewidth=1)
    #Zoom Australia
    axins_2 = zoomed_inset_axes(ax,
                                2.2,
                                loc=3,
                                bbox_to_anchor=(0.59, 0.255),
                                bbox_transform=ax.figure.transFigure)
    axins_2.scatter(x, y, s=20, c=vals, cmap=cmap, norm=norm)
    m.drawcoastlines(linewidth=0.5)
    x2, y2 = m(110, -43)
    x3, y3 = m(155, -10)
    axins_2.set_xlim(x2, x3)
    axins_2.set_ylim(y2, y3)
    axes = mark_inset(ax, axins_2, loc1=1, loc2=2, linewidth=1)
    #Zoom US
    axins_3 = zoomed_inset_axes(ax,
                                1.6,
                                loc=3,
                                bbox_to_anchor=(0.19, 0.25),
                                bbox_transform=ax.figure.transFigure)
    axins_3.scatter(x, y, s=20, c=vals, cmap=cmap, norm=norm)
    m.drawcoastlines(linewidth=0.5)
    x2, y2 = m(-130, 22)
    x3, y3 = m(-60, 63)
    axins_3.set_xlim(x2, x3)
    axins_3.set_ylim(y2, y3)
    axes = mark_inset(ax, axins_3, loc1=1, loc2=2, linewidth=1)
    return (fig, axes)
Esempio n. 19
0
    ax1 = plt.gca()

    x_max = 4.0
    x_min = 2.0

    ann_mask = numpy.logical_and(r_ann >= x_min, r_ann <= x_max)
    gfmc_mask = numpy.logical_and(r_gfmc >= x_min, r_gfmc <= x_max)

    # bottom, left, width, height
    ax2 = plt.axes([0, 2., 2., 0.2])
    # Manually set the position and relative size of the inset axes within ax1
    ip = InsetPosition(ax1, [0.35, 0.25, 0.5, 0.5])
    ax2.set_axes_locator(ip)
    # Mark the region corresponding to the inset axes on ax1 and draw lines
    # in grey linking the two axes.
    mark_inset(ax1, ax2, loc1=3, loc2=1, fc="black", alpha=0.5, ec='black')

    ax2.fill_between(r_gfmc[gfmc_mask],
                     rho_gfmc[gfmc_mask] - drho_gfmc[gfmc_mask],
                     rho_gfmc[gfmc_mask] + drho_gfmc[gfmc_mask],
                     alpha=0.75)
    ax2.plot(r_gfmc[gfmc_mask], rho_gfmc[gfmc_mask], lw=3)
    ax2.errorbar(
        r_ann[ann_mask],
        rho_ann[ann_mask],
        yerr=drho_ann[ann_mask],
        # label="Error x10",
        ls="none",
        marker='o',
        ms=7,
        # color='orange'
    ## just passing transform=ax.transAxes as an argument to add_axes() does nothing.
    ## So you need to do some complicated jugglery
    ## (from http://matplotlib.1069221.n5.nabble.com/Adding-custom-axes-within-a-subplot-td20316.html)
    Bbox = matplotlib.transforms.Bbox.from_bounds(0.75, 0.6, 0.5, 0.5)
    trans = ax1.transAxes + fig.transFigure.inverted()
    l, b, w, h = matplotlib.transforms.TransformedBbox(Bbox, trans).bounds
    axinset = fig.add_axes([l, b, w, h])
    axinset.plot(timevec, mit_responses[1][0] * 1e3, color="r", linewidth=plot_linewidth, label="Lateral")
    ## thin frame
    for loc, spine in axinset.spines.items():  # items() returns [(key,value),...]
        spine.set_linewidth(axes_linewidth)
    axinset.set_xlim(910, 975)
    axinset.set_ylim(-71.5, -70)
    axinset.set_xticks([])
    axinset.set_yticks([])
    mark_inset(ax1, axinset, loc1=2, loc2=4, fc="none", ec="0.5", linewidth=axes_linewidth)

    ## mitral B
    ax1 = fig.add_subplot(2, 2, 2)
    ax1.plot((tmin, tmax), (Vrest, Vrest), linestyle="dashed", linewidth=plot_linewidth, color=(0.5, 0.5, 0.5))
    ax1.plot(timevec, mit_responses[1][1] * 1e3, color="g", linewidth=plot_linewidth, label="Lateral")
    beautify_plot(ax1, x0min=False, y0min=False, xticksposn="none", yticksposn="none")
    ax1.set_xlim(tmin, tmax)
    ax1.set_ylim(Vmin, Vmax)
    ax1.set_yticks([])
    axes_labels(ax1, "", "")
    ax2 = fig.add_subplot(2, 2, 4)
    ax2.plot((tmin, tmax), (Vrest, Vrest), linestyle="dashed", linewidth=plot_linewidth, color=(0.5, 0.5, 0.5))
    ax2.plot(timevec, mit_responses[0][1] * 1e3, color="g", linewidth=plot_linewidth, label="Recurrent")
    beautify_plot(ax2, x0min=False, y0min=False, xticksposn="bottom", yticksposn="none")
    ax2.set_xlim(tmin, tmax)
Esempio n. 21
0
def displacement(ofile,timestep,Natoms,matrix0,Type,Time,frontname,pathtodatabase,systemsize):
    '''
    timestep,system_size,matrix0 contain the initial information about the system.
    we have to go through sortedfiles to find information about the particles at
    later timesteps.
    '''
    factor = 10**(-8)                                               # conversionfactor from [A^2/ps] -> [m^2/s]

    Lx = systemsize[1] -systemsize[0]    
    Ly = systemsize[3] -systemsize[2]
    Lz = systemsize[5] -systemsize[4]
    halfsystemsize = 0.5*(Lx+Ly+Lz)/3.0   # half of average system size
    
    time = []
    for t in Time:
        time.append(timestep*t/1000.0)   # to picoseconds
        #time.append(t)
        
    MSDX = [];MSDY = [];MSDZ = [];MSD = [];D_local = []
    dt = (time[1]-time[0])
    for T in Time:
        path = frontname + '.%r.txt' % (T)
        print path
        msdx = 0; msdy = 0; msdz = 0; msd = 0
        filename = os.path.abspath(os.path.join(pathtodatabase,path))
        t, Natoms, system_size, matrix, readstructure, entries, types = readfile(filename)
        counter = 0
        for i in range(Natoms):
            if (matrix['type'][i] == Type):
                ID = matrix['id'][i]
                initial_index = None
                for j in range(Natoms):
                    k = matrix0['id'][j]
                    if (k == ID):
                        initial_index = j
                        break
                
                dx = matrix['x'][i] - matrix0['x'][initial_index]
                dy = matrix['y'][i] - matrix0['y'][initial_index]
                dz = matrix['z'][i] - matrix0['z'][initial_index]
                msdx += (dx)**2
                msdy += (dy)**2
                msdz += (dz)**2
                ########################################
                #        MINIMUM IMAGE CONVENTION      #
                if (dx < -halfsystemsize): dx = dx + Lx
                if (dx > halfsystemsize): dx = dx - Lx
                if (dy < -halfsystemsize): dy = dy + Ly
                if (dy > halfsystemsize): dy = dy - Ly
                if (dz < -halfsystemsize): dz = dz + Lz
                if (dz > halfsystemsize): dz = dz - Lz
                ########################################
                msd += dx**2 + dy**2 + dz**2
                counter += 1
    
        D_local.append((msd/(counter*6*T)))
        MSDX.append(msdx/(6*counter));MSDY.append(msdy/(6*counter));MSDZ.append(msdz/(6*counter));MSD.append(msd/(6*counter))
        

    # ballistic_end = 100ps
    degree = 1
    start = int(round(len(MSD)/5.0))
    p = np.polyfit(time[start:],MSD[start:],degree)   # last 4/5 of the dataset
    f = np.polyval(p,time)    
    d_mean_lastpart = p[0]#*10**(-8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p1 = np.polyfit(time[0:start],MSD[0:start],degree)
    f1 = np.polyval(p1,time)    
    d_mean_firstpart = p1[0]#*10**(8)       # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    p2 = np.polyfit(time[0:int(round(start/2.0))],MSD[0:int(round(start/2.0))],degree)
    f2 = np.polyval(p2,time)    
    d_mean_initpart = p2[0]#*10**(8)        # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]
    
    p3 = np.polyfit(time[0:100],MSD[0:100],degree)
    f3 = np.polyval(p3,time)
    d_mean_actual = p3[0]#*10**(8)          # to get [m^2/s]. [A^2/ps] = 10**(-8)[m^2/s]

    print "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#"
    print " Nvalues in estimate 1 = 100"
    print " Nvalues in estimate 2 = %g" % (int(round(start/2.0)))
    print " Nvalues in estimate 3 = %g" % (int(round(start)))
    print " Nvalues in estimate 4 = %g" % (len(time[start:]))
    
    ###############################################################################
    #                             plotting
    #plt.close('all')
    plt.figure()                                                                # Figure 1
    Title = 'Mean square displacement'
    legends = ['$msd_{x}$','$msd_{y}$','$msd_{z}$','$msd$']#['$msd$']#
    Ylabel = 'mean square displacement $ [A^2] $'
    Xlabel = 'time $ [ps] $'
    pltname = 'MSD_bulkwater'
    linestyles = ['--r','--y','--k','o-b']#['--r'] #
    plt.hold(True)
    plt.plot(time,MSDX,linestyles[0])
    plt.plot(time,MSDY,linestyles[1])
    plt.plot(time,MSDZ,linestyles[2])
    plt.plot(time,MSD,linestyles[3],markevery=10)
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends,loc='lower right')
    plt.hold(False)
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[MSDX,MSDY,MSDZ,MSD])
    
    
    from mpl_toolkits.axes_grid.inset_locator import zoomed_inset_axes, inset_axes, mark_inset

    plt.figure()
    ax = plt.axes()                                                             # Figure 2
    Title = 'Mean square displacement'
    legends = ['MSD','$f_1 %.3f $' % (d_mean_actual),'$f_2 %.3f $' % (d_mean_initpart),'$f_3 %.3f $' % (d_mean_firstpart),'$f_4 %.3f $' % (d_mean_lastpart)]
    pltname = 'MSD_bulkwater_mean'
    Xlabel = 'time $ [ps] $'
    Ylabel = 'mean square displacement $ [A^2] $'
    linestyles = ['b-','--y','--r','--m','--y']
    
    plt.hold(True)
    plt.plot(time,MSD,linestyles[0])
    plt.plot(time[0:int(round(len(f)/8.0))],f3[0:int(round(len(f)/8.0))],linestyles[1])  # very first part
    plt.plot(time[0:int(round(len(f)/6.0))],f2[0:int(round(len(f)/6.0))],linestyles[2])  # initpart
    plt.plot(time[0:int(round(len(f)/5.0))],f1[0:int(round(len(f)/5.0))],linestyles[3])  # firstpart
    plt.plot(time,f,linestyles[4])                                                       # lastpart

    plt.hold(False)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    plt.legend(legends,loc='lower right')
    plt.title(Title)
    
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    
    axin = inset_axes(ax, width="30%", height="35%", loc=8)
    plt.hold(True)
    axin.plot(time,MSD,linestyles[0])
    axin.plot(time,f3,linestyles[1],linewidth=3.0)
    axin.plot(time,f2,linestyles[2])
    #axin.plot(time,f1,linestyles[3])
    plt.hold(False)
    axin.set_xlim(500, 520)
    ya = 0.0
    yb = 4.0
    Npoints = 4
    points = np.linspace(ya,yb,Npoints)
    axin.set_ylim(ya, yb)
    axin.set_xticks([])
    axin.set_yticks(points)
    mark_inset(ax, axin, loc1=3, loc2=4, fc="none", ec="0.5")    
    
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[MSD,f])
    
    print "#################################################################"
    print "# Diffusion estimate f1   : D = %.10f " % (d_mean_actual)    
    print "# Diffusion estimate f2   : D = %.10f " % (d_mean_initpart)
    print "# Diffusion estimate f3   : D = %.10f " % (d_mean_firstpart) 
    print "# Diffusion estimate f4   : D = %.10f " % (d_mean_lastpart)

    plt.figure()                                                                # Figure 3
    Title = 'Time evolution of the local diffusion constant. $ D=(msd/6dt) $'
    legends = ['$D(t)$']; linestyles = ['-y']
    pltname = 'Diffusion_bulkwater'
    Ylabel = 'displacement $ [ %g m^2/s]$' % factor
    plt.hold(True)
    plt.plot(time,D_local,linestyles[0])    
    plt.hold(False)
    plt.legend(legends,loc='upper right')
    plt.title(Title)
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)
    write_to_file(ofile,Title,Xlabel,Ylabel,pltname,legends,linestyles,[time],[D_local])

    plt.show()
Esempio n. 22
0
ax.plot(t2, np2, c='k', lineStyle='--', label='$\epsilon_p=0.06$')
ax.plot(t3, np3, c='k', lineStyle='-.', label='$\epsilon_p=0.12$')
ax.plot(t4, np4, c='k', lineStyle=':', label='$\epsilon_p=0.18$')
ax.plot(t5, np5, c='k', lineStyle=(0, (5, 5)), label='$\epsilon_p=0.24$')

ip = InsetPosition(ax, [0.2, 0.2, 0.5, 0.45])
ax2 = plt.axes([0, 0, 1, 1])
ax2.set_axes_locator(ip)
ax2.plot(t1[t1 >= 0.6], np1[t1 >= 0.6], c='k', lineStyle='-')
ax2.plot(t2[t2 >= 0.6], np2[t2 >= 0.6], c='k', lineStyle='--')
ax2.plot(t3[t3 >= 0.6], np3[t3 >= 0.6], c='k', lineStyle='-.')
ax2.plot(t4[t4 >= 0.6], np4[t4 >= 0.6], c='k', lineStyle=':')
ax2.plot(t5[t5 >= 0.6], np5[t5 >= 0.6], c='k', lineStyle=(0, (5, 5)))

# inset plot #
mark_inset(ax, ax2, loc1=1, loc2=3, fc="none", ec='r', lw='0.5')
#ax2.plot
#---------------------------axis control------------------------#

ax.set_xlabel("$t\ (s)$")
ax.set_ylabel("Particle number")

#ax[0,0].set_xlim(0,0.6)
ax2.set_xlim(0.6, 1.0)

ax2.axes.get_xaxis().set_visible(False)
ax2.axes.get_yaxis().set_visible(False)

#ax.set_ylim(0.,0.8)
#majorLocator = MultipleLocator(1)
#majorFormatter = FormatStrFormatter('%d')