Exemplo n.º 1
0
def sdf_getdata(sdf_file):
    try:
        sdf_handle = sdf.read(sdf_file)
    except Exception as err:
        print("Warning: Unreadable sdf file {}".format(sdf_file))
        return((np.nan,np.nan,np.nan))
    try:
        ey = getattr(sdf_handle, "Electric_Field_Ey").data
        x = getattr(sdf_handle, "Grid_Grid").data[0]

        eyargmax = np.unravel_index(np.argmax(ey), ey.shape)[0]
        eymax = np.max(ey)
        xmax = x[eyargmax]

        try:
            las_lambda = get_lambda(x, ey)
        except Exception as e:
            print(type(e))
            print(e)
            las_lambda = np.nan
    except Exception as e:
        print(e)
        print("Warning: Missing field data in {}".format(sdf_file))
        return((np.nan,np.nan,np.nan,np.nan))
    if xmax == 0:
        return((np.nan,np.nan,np.nan,np.nan))
    try: 
        bmax = np.max(getattr(sdf_handle, "Particles_Px_electron").data /
                      getattr(sdf_handle, "Particles_Gamma_electron").data)
        bmax = bmax / (sc.m_e * sc.c)
    except Exception as err:
        bmax = np.nan

    return((xmax,eymax,bmax, las_lambda))
Exemplo n.º 2
0
 def __init__(self, sdffile, **kwargs):
     super(self.__class__, self).__init__(sdffile, **kwargs)
     import os.path
     import sdf
     try:
         sdfversion = sdf.__version__
     except(AttributeError):
         sdfversion = '0.0.0'
     if sdfversion < '2.2.0':
         raise ImportError('Upgrade sdf package to 2.2.0 or higher.')
     if not os.path.isfile(sdffile):
         raise IOError('File "' + str(sdffile) + '" doesnt exist.')
     self._data = sdf.read(sdffile, dict=True)
Exemplo n.º 3
0
def get_time(time=0, wkd=None):
    global data, wkdir

    if wkd is not None:
        wkdir = wkd

    flist = glob.glob(wkdir + "/[0-9]*.sdf")
    if len(flist) == 0:
        flist = glob.glob("./[0-9]*.sdf")
        if len(flist) == 0:
            print("No SDF files found")
            return
        wkdir = '.'

    t = None
    t_old = -1
    jobid = None
    fname = None
    for f in sorted(flist):
        dat_tmp = sdf.read(f)
        jobid_tmp = dat_tmp.Header['jobid1']
        if jobid is None:
            jobid = jobid_tmp
        elif jobid != jobid_tmp:
            continue

        t = dat_tmp.Header['time']
        if time is None:
            if t > t_old:
                fname = f
                t_old = t
        else:
            if t >= time - 1e-30:
                fname = f
                break

    if fname is None:
        raise Exception("No valid file found in directory: " + wkdir)

    data = getdata(fname, verbose=False)
    return data
Exemplo n.º 4
0
def read(*args, **kwargs):
    """Reads an SDF file and returns a dictionary of NumPy arrays containing
       the file data."""

    data = sdf.read(*args, **kwargs)

    sdfdict = {}
    for key, value in data.__dict__.items():
        if hasattr(value, "name"):
            if hasattr(value, "data"):
                sdfdict[value.name] = value.data
            else:
                sdfdict[value.name] = value
        else:
            if hasattr(value, "data"):
                sdfdict[key] = value.data
            else:
                sdfdict[key] = value

        # Add separate grid variables
        t = type(value)
        if t == sdf.BlockPlainMesh or t == sdf.BlockPointMesh \
                or t == sdf.BlockLagrangianMesh:
            base = value.name
            if value.id == "grid":
                base += "_node"
            elif value.id == "grid_mid":
                base = base[:-4]
            for n in range(len(value.dims)):
                newkey = base + '/' + value.labels[n]
                sdfdict[newkey] = value.data[n]

        # Add material block
        if t == sdf.BlockStitchedMaterial:
            sdfdict["Materials"] = value.material_names

    return sdfdict
import sys
import sdf
import matplotlib.pyplot as plt

fname = sys.argv[1]
radius = float(sys.argv[2])
varname = "Fluid_Energy"

try:
    d = sdf.read(fname)
except:
    print 'File "%s" not found' % fname
    sys.exit()

# print d.__dict__

if not hasattr(d, varname):
    print 'Variable "%s" not found in file' % varname
    sys.exit()

var = d.__dict__[varname]

x = var.grid.data[0][:-1]
y = var.grid.data[1][:-1]

for i, slice1 in enumerate(var.data):
    for j, slice2 in enumerate(slice1):
        for k, val in enumerate(slice2):
            if (x[i]**2 + y[j]**2) < radius:
                print val
Exemplo n.º 6
0
def getdata(fname, wkd=None, verbose=True):
    global data, t, step, p, ppi, ppe, rho, ei, ee, vx, vy, vz, bx, by, bz
    global x, y, z, xc, yc, zc, grid, grid_mid
    global old_mtime, old_filename, old_size, cached
    global wkdir

    if wkd is not None:
        wkdir = wkd

    if isinstance(fname, int):
        filename = wkdir + "/%0.4i.sdf" % fname
    else:
        filename = fname

    try:
        st = os.stat(filename)
    except OSError as e:
        filename = "./%0.4i.sdf" % fname
        try:
            st = os.stat(filename)
            wkdir = '.'
        except OSError as e:
            print("ERROR opening file {0}: {1}".format(filename, e.strerror))
            raise

    if st.st_mtime != old_mtime or st.st_size != old_size \
            or filename != old_filename:
        if verbose:
            print("Reading file " + filename)
        data = sdf.read(filename)
        old_mtime = st.st_mtime
        old_size = st.st_size
        old_filename = filename
    else:
        cached = True
        return data

    cached = False
    fdict = {}

    sdfdict = {}
    for key, value in data.__dict__.items():
        if hasattr(value, "id"):
            sdfdict[value.id] = value
        else:
            sdfdict[key] = value

    table = {'time': 't'}
    k = 'Header'
    if k in sdfdict:
        h = sdfdict[k]
        k = list(table.keys())[0]
        if k in h:
            key = table[k]
            var = h[k]
            if verbose:
                print(key + str(np.shape(var)) + ' = ' + k)
            fdict[key] = var
            globals()[key] = var
            builtins.__dict__[key] = var

    table = {'Pressure': 'p',
             'Pressure_ion': 'ppi',
             'Pressure_electron': 'ppe',
             'Rho': 'rho',
             'Energy_ion': 'ei',
             'Energy_electron': 'ee',
             'Vx': 'vx',
             'Vy': 'vy',
             'Vz': 'vz',
             'Vr': 'vx',
             'VTheta': 'vz',
             'Bx': 'bx',
             'By': 'by',
             'Bz': 'bz',
             'Br': 'bx',
             'Bt': 'bz',
             'bx': 'bx',
             'by': 'by',
             'bz': 'bz',
             'ex': 'ex',
             'ey': 'ey',
             'ez': 'ez',
             'jx': 'jx',
             'jy': 'jy',
             'jz': 'jz'}

    rz = False
    if 'Vr' in sdfdict:
        rz = True

    if rz:
        table['Vz'] = 'vy'
        table['Bz'] = 'by'

    inv_table = {}
    for k, v in table.items():
        inv_table[v] = inv_table.get(v, [])
        inv_table[v].append(k)

    for k in table:
        if k in sdfdict:
            key = table[k]
            if hasattr(sdfdict[k], "data"):
                var = sdfdict[k].data
            else:
                var = sdfdict[k]
            dims = str(tuple(int(i) for i in sdfdict[k].dims))
            if verbose:
                print(key + dims + ' = ' + k)
            fdict[key] = var
            globals()[key] = var
            builtins.__dict__[key] = var

    k = 'grid'
    if k in sdfdict:
        vargrid = sdfdict[k]
        grid = vargrid
        keys = 'x', 'y', 'z'
        for n in range(np.size(vargrid.dims)):
            key = keys[n]
            var = vargrid.data[n]
            dims = str(tuple(int(i) for i in sdfdict[k].dims))
            if verbose:
                print(key + dims + ' = ' + k)
            fdict[key] = var
            globals()[key] = var
            builtins.__dict__[key] = var

    k = 'grid_mid'
    if k in sdfdict:
        vargrid = sdfdict[k]
        grid_mid = vargrid
        keys = 'xc', 'yc', 'zc'
        for n in range(np.size(vargrid.dims)):
            key = keys[n]
            var = vargrid.data[n]
            dims = str(tuple(int(i) for i in sdfdict[k].dims))
            if verbose:
                print(key + dims + ' = ' + k)
            fdict[key] = var
            globals()[key] = var
            builtins.__dict__[key] = var

    # Export particle arrays
    for k, value in data.__dict__.items():
        if type(value) != sdf.BlockPointVariable \
                and type(value) != sdf.BlockPointMesh:
            continue
        key = re.sub(r'[^a-z0-9]', '_', value.id.lower())
        if hasattr(value, "data"):
            var = value.data
        else:
            var = value
        dims = str(tuple(int(i) for i in value.dims))
        if type(value) == sdf.BlockPointVariable:
            if verbose:
                print(key + dims + ' = ' + value.name)
            fdict[key] = var
            globals()[key] = var
            builtins.__dict__[key] = var
        else:
            vargrid = value
            grid = vargrid
            keys = 'x', 'y', 'z'
            for n in range(np.size(value.dims)):
                gkey = keys[n] + '_' + key
                var = value.data[n]
                dims = str(tuple(int(i) for i in value.dims))
                if verbose:
                    print(gkey + dims + ' = ' + k + ' ' + keys[n])
                fdict[gkey] = var
                globals()[gkey] = var
                builtins.__dict__[gkey] = var

    # X, Y = np.meshgrid(x, y)
    return data
        c('springgreen'),
        c('yellow'), 0.6,
        c('yellow'),
        c('red'), 0.8,
        c('red'),
        c('firebrick')
    ])

    color_list = ['blue', 'limegreen', 'red']

if __name__ == '__main__':
    from_path = './cannon_a190_v484/'
    to_path = './cannon_a190_v484_fig/'
    ######### Script code drawing figure ################
    for n in range(11, 23, 1):
        data = sdf.read(from_path + 'q' + str(n).zfill(4) + ".sdf", dict=True)
        header = data['Header']
        time = header['time']
        x = data['Grid/Grid_mid'].data[0] / 1.0e-6
        y = data['Grid/Grid_mid'].data[1] / 1.0e-6
        z = data['Grid/Grid_mid'].data[2] / 1.0e-6
        X, Z = np.meshgrid(x, z)
        data = sdf.read(from_path + 'e_fields' + str(n).zfill(4) + ".sdf",
                        dict=True)
        ey1 = data['Electric Field/Ez_averaged'].data / exunit * 3.5
        ey = np.sum(ey1[:, 179:181, :], axis=1) / 2

        data = sdf.read('../alex_ion_acc/uniform_a190_n30/e_fields' +
                        str(n).zfill(4) + ".sdf",
                        dict=True)
        ey1 = data['Electric Field/Ez_averaged'].data / exunit * 3.5
def processplot(n):
    to_path='./cannon_a190_bulk200/'
    from_path = './cannon_a190_bulk200/'
    ######### Parameter you should set ###########
    n0=30.0
    R=1.8e-6
    L=15e-6
    Ntot = np.pi*R*R*L*n0*denunit
    V=(1.0/20.0)*(1.0/15.0)*(1.0/15.0)*1.0e-18
    weight = V*denunit*n0/50.0 
  #  weight = Ntot/(1200*360*360*50)
  
    set_relativistic =1 
    if 1 > 0:
     
        data = sdf.read(from_path+"i_tot_loc"+str(n).zfill(4)+".sdf",dict=True)
        header=data['Header']
        time1=header['time']
        if set_relativistic == 1:
            px = data['Particles/Px/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
            py = data['Particles/Py/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
            pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
            gg = (px**2+py**2+pz**2+1)**0.5
            theta = np.arctan2((py**2+pz**2)**0.5,px)*180.0/np.pi
      
            ek_1 = (gg - 1.0)*0.51*1836
            ww_1 = np.zeros_like(ek_1) + weight
            dist_x1, den1 = pxpy_to_energy(ek_1,ww_1)
      
            ek_2 = (gg[abs(theta)<10.0] - 1.0)*0.51*1836
            ww_2 = np.zeros_like(ek_2) + weight
            dist_x2, den2 = pxpy_to_energy(ek_2,ww_2)
            print('set_relativistic 1'+str(n).zfill(4))
        elif set_relativistic == 0: 
            px = data['Particles/Px/subset_Only_Ions0/Ion'].data
            py = data['Particles/Py/subset_Only_Ions0/Ion'].data
            pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data
            pp = (px**2+py**2+pz**2)**0.5
            theta = np.arctan2((py**2+pz**2)**0.5,px)*180.0/np.pi
      
            ek_1 = pp**2/2.0/1836/m0/(1.6e-13)
            ww_1 = np.zeros_like(ek_1) + weight
            dist_x1, den1 = pxpy_to_energy(ek_1,ww_1)
      
            ek_2 = (pp[abs(theta)<10.0])**2/2.0/1836/m0/(1.6e-13)
            ww_2 = np.zeros_like(ek_2) + weight
            dist_x2, den2 = pxpy_to_energy(ek_2,ww_2)
            print('set_relativistic 0'+str(n).zfill(4))
            
      
        plt.plot(dist_x1,den1,':b',linewidth=4, label=str(round(time1/1e-15,0))+'; total')
        plt.plot(dist_x2,den2,':r',linewidth=4, label=str(round(time1/1e-15,0))+'; '+r'$\theta$'+'< 10$^o$')
      
        #### manifesting colorbar, changing label and axis properties ####
        plt.xlabel('Energy [MeV]',fontdict=font)
        plt.ylabel('dN/dE [per MeV]',fontdict=font)
        plt.xticks(fontsize=20); plt.yticks(fontsize=20);
        plt.yscale('log')
        #plt.ylim(2e7,8e9)
        plt.xlim(5,1000)
        plt.grid(which='major',color='k', linestyle='--', linewidth=0.3)
        plt.grid(which='minor',color='k', linestyle='--', linewidth=0.1)
  
        plt.legend(loc='best',fontsize=20,framealpha=1.0)
        plt.subplots_adjust(left=None, bottom=0.15, right=0.95, top=0.95,
                  wspace=None, hspace=None)
      #        plt.text(250,6e9,'t='+str(round(time/1.0e-15,0))+' fs',fontdict=font)
        fig = plt.gcf()
        fig.set_size_inches(10.0, 6.0)
        fig.savefig(to_path+'proton_spectrum_'+str(n).zfill(4)+'.png',format='png',dpi=80)
        plt.close("all")
        print('finished!'+str(n).zfill(4))      
Exemplo n.º 9
0
gg = (px**2 + py**2 + 1)**0.5
R = gg - px
theta = np.arctan2(py, px)

number = 400

plt.subplot(2, 1, 1)
#axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left')
#axin2 = inset_axes(ax, width='15%', height='5%', loc='upper center')

grid_t = np.zeros(130)
grid_x = np.linspace(10, 14.9833, 150)
grid_data = np.zeros([130, 150])
index = 68
for n in range(5, 130, 1):
    data = sdf.read("./Data_a20_130_2/" + str(n).zfill(4) + ".sdf", dict=True)
    header = data['Header']
    grid_t[n] = header['time'] / 1e-15
    y = data['Grid/Grid_mid'].data[1] / 1.0e-6
    name = 'ex'
    ex = data['Electric Field/' + str.capitalize(name)].data / exunit
    yi = np.min(np.where(yy[index, (n - 5) * 10] < y))
    print(np.shape(ex[0 + (n - 5) * 30:150 + (n - 5) * 30, yi]))
    grid_data[n, :] = (ex[0 + (n - 5) * 30:150 +
                          (n - 5) * 30, yi] + ex[0 + (n - 5) * 30:150 +
                                                 (n - 5) * 30, yi - 1]) * 0.5

X, Y = np.meshgrid(grid_t, grid_x)
levels = np.linspace(-2.1, 2.1, 50)
grid_data[grid_data < -2] = -2
grid_data[grid_data > 2] = 2
Exemplo n.º 10
0
  class MidpointNormalize(colors.Normalize):
    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        colors.Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y)) 
##end for norm colorbar####

 
  
#if __name__ == '__main__':
  ######### Parameter you should set ###########
  #start   =  210  # start time
  #stop    =  210  # end time
  #step    =  1  # the interval or step

  
#  youwant = ['electron_x_px','electron_density','electron_en','electron_theta_en','ey'] #,'electron_ekbar']
  #youwant field  ex,ey,ez,bx,by,bz,ex_averaged,bx_averaged...
  #youwant Derived electron_density,electron_ekbar...
  #youwant dist_fn electron_x_px, electron_py_pz, electron_theta_en...
  #if (os.path.isdir('jpg') == False):
  #  os.mkdir('jpg')
    #from_path = './uniform_a190_n30/'
    n  = 4
    dim = '2d'
    from_path = './one_20/'
    to_path   = from_path
    ######### Script code drawing figure ################
    #for n in range(start,stop+step,step):
    #### header data ####
    data = sdf.read(from_path+'ekbar'+str(n).zfill(4)+".sdf",dict=True)
    header=data['Header']
    time=header['time']
    x  = data['Grid/Grid_mid'].data[0]/1.0e-6
    print('ok')
    y  = data['Grid/Grid_mid'].data[1]/1.0e-6
    if dim == '3d':
        z  = data['Grid/Grid_mid'].data[2]/1.0e-6
    X, Y = np.meshgrid(x, y) 
    name='Electron_ekbar' 
    #den = data['Derived/EkBar_averaged/'+name[0:-6]].data/(0.51*q0*1.0e6)
    ekbar = data['Derived/EkBar/'+name[0:-6]].data/(0.51*q0*1.0e6)
    if dim == '3d':
        n3d = len(ekbar[0,0,:])
        ekbar = (ekbar[:,:,n3d//2-1]+ekbar[:,:,n3d//2])/2.0
    eee = 600.0
    levels_ek = np.linspace(0, eee, 101)
    ekbar.T[ekbar.T > eee]=eee 
 
    data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
    den = (data['Derived/Number_Density/Electron'].data+data['Derived/Number_Density/E_1'].data)/denunit
    if dim == '3d':
        n3d = len(den[0,0,:])
        den = (den[:,:,n3d//2-1]+den[:,:,n3d//2])/2.0
    eee = 6.0
    levels = np.linspace(0, eee, 101)
    den.T[den.T > eee]=eee 

    data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
    den_a = (data['Derived/Number_Density_averaged/Electron'].data+data['Derived/Number_Density_averaged/E_1'].data)/denunit
    if dim == '3d':
        n3d = len(den_a[0,0,:])
        den_a = (den_a[:,:,n3d//2-1]+den_a[:,:,n3d//2])/2.0
    #den_a.T[den_a.T > eee_a]=eee_a



    #ax=plt.subplot(3,2,1)
    ax=plt.subplot2grid((3, 3), (0, 0))
    #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2)
    #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2)
    #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #### manifesting colorbar, changing label and axis properties ####
    image1=ax.contourf(X, Y, den.T, levels=levels, norm=mcolors.Normalize(vmin=levels.min(), vmax=levels.max()), cmap=mycolor_viridis)
#    ax.contour(X, Y, den_a.T, levels=[0.9], colors='limegreen', linewidths=3.5,origin='lower')
#    cbar=plt.colorbar(image1,pad=0.01,ticks=np.linspace(0.0, eee, 5),orientation="vertical")
#    cbar.set_label('$n_e$ [$n_c$]', fontdict=font2)
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        

    #### manifesting colorbar, changing label and axis properties ####
#    cbar=plt.colorbar(image2,pad=0.01,ticks=np.linspace(-eee, eee, 5),orientation="vertical")
#    cbar.set_label(r'$E_y\ [m_ec\omega_0/e]$',fontdict=font2)        
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
#    plt.title('Ey_den_e at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
    ax.text(2.,4.5,'t = '+str(round(time/1.0e-15,0))+' fs',fontdict=font,color='black')
    #ax.text(21.,1.75,'t = 70 fs',fontdict=font)
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(-5,15)
#    ax.set_xlabel('X [$\lambda$]',fontdict=font)
    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=25) 
    ax.tick_params(axis='x',labelsize=0.0) 
#    ax.tick_params(axis='both',labelsize=25) 
    ax.set_xticks(ticks=[0,10])
    ax.set_yticks(ticks=[-5,0,5])

    
    #ax=plt.subplot(3,1,1)
    ax=plt.subplot2grid((3, 3), (1, 0))
    #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2)
    #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2)
    #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #### manifesting colorbar, changing label and axis properties ####
    image1=ax.contourf(X, Y, ekbar.T, levels=levels_ek, norm=mcolors.Normalize(vmin=levels_ek.min(), vmax=levels_ek.max()), cmap=mycolor_jet)
    image1=ax.contour(X, Y, den_a.T, levels=[19.5], colors='k', linewidths=2,origin='lower')
#    cbar=plt.colorbar(image1,pad=0.01,ticks=np.linspace(0.0, eee, 5),orientation="vertical")
#    cbar.set_label('$n_e$ [$n_c$]', fontdict=font2)
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(-5,15)
#    ax.set_xlabel('X [$\lambda$]',fontdict=font)
    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=25) 
    ax.tick_params(axis='x',labelsize=0.0) 
#    ax.tick_params(axis='both',labelsize=25) 
    ax.set_xticks(ticks=[0,10])
    ax.set_yticks(ticks=[-5,0,5])


    #ax=plt.subplot(3,1,2)
    ax=plt.subplot2grid((3, 3), (2, 0))
    data = sdf.read(from_path+'current'+str(n).zfill(4)+".sdf",dict=True)
    ex = data['Current/Jx_averaged'].data/jalf/4/np.pi
    if dim == '3d':
        ex = (ex[:,:,n3d//2-1]+ex[:,:,n3d//2])/2.0
    eee = 0.2
    levels = np.linspace(-eee, eee, 51)
    ex.T[ex.T < -eee]=-eee
    ex.T[ex.T >  eee]= eee
    image2=ax.contourf(X, Y, ex.T, levels=levels, cmap='bwr')
    #### manifesting colorbar, changing label and axis properties ####
#    cbar=plt.colorbar(image2,pad=0.01,ticks=np.linspace(-eee, eee, 5),orientation="vertical")
#    cbar.set_label(r'$\alpha=j_x/[4\pi I_A/\lambda^2]$',fontdict=font2)        
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
#    plt.title('Jx_averaged at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = '+str(round(time/1.0e-15,0))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = 70 fs',fontdict=font)
#    ax.contour(X, Y, den_a.T, levels=[0.9], colors='limegreen', linewidths=2,origin='lower')
    image1=ax.contour(X, Y, den_a.T, levels=[19.5], colors='k', linewidths=2,origin='lower')
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(-5,15)
    ax.set_xlabel('X [$\mu m$]',fontdict=font)
    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=25) 
    ax.tick_params(axis='x',labelsize=25) 
    ax.set_xticks(ticks=[0,10])
    ax.set_yticks(ticks=[-5,0,5])


    n  = 13
    dim = '2d'
    ######### Script code drawing figure ################
    #for n in range(start,stop+step,step):
    #### header data ####
    data = sdf.read(from_path+'ekbar'+str(n).zfill(4)+".sdf",dict=True)
    header=data['Header']
    time=header['time']
    x  = data['Grid/Grid_mid'].data[0]/1.0e-6
    print('ok')
    y  = data['Grid/Grid_mid'].data[1]/1.0e-6
    if dim == '3d':
        z  = data['Grid/Grid_mid'].data[2]/1.0e-6
    X, Y = np.meshgrid(x, y) 
    name='Electron_ekbar' 
    #den = data['Derived/EkBar_averaged/'+name[0:-6]].data/(0.51*q0*1.0e6)
    ekbar = data['Derived/EkBar/'+name[0:-6]].data/(0.51*q0*1.0e6)
    if dim == '3d':
        n3d = len(ekbar[0,0,:])
        ekbar = (ekbar[:,:,n3d//2-1]+ekbar[:,:,n3d//2])/2.0
    eee = 600.0
    levels_ek = np.linspace(0, eee, 101)
    ekbar.T[ekbar.T > eee]=eee 

    data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
    den = (data['Derived/Number_Density/Electron'].data+data['Derived/Number_Density/E_1'].data)/denunit
    if dim == '3d':
        n3d = len(den[0,0,:])
        den = (den[:,:,n3d//2-1]+den[:,:,n3d//2])/2.0
    eee = 6.0
    levels = np.linspace(0, eee, 101)
    den.T[den.T > eee]=eee 

    data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
    den_a = (data['Derived/Number_Density_averaged/Electron'].data+data['Derived/Number_Density_averaged/E_1'].data)/denunit
    if dim == '3d':
        n3d = len(den_a[0,0,:])
        den_a = (den_a[:,:,n3d//2-1]+den_a[:,:,n3d//2])/2.0
    #den_a.T[den_a.T > eee]=eee
    den_a.T[Y>4] = 20.0 



    #ax=plt.subplot(3,2,1)
    ax=plt.subplot2grid((3, 3), (0, 1), colspan=2)
    #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2)
    #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2)
    #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #### manifesting colorbar, changing label and axis properties ####
    image1=ax.contourf(X, Y, den.T, levels=levels, norm=mcolors.Normalize(vmin=levels.min(), vmax=levels.max()), cmap=mycolor_viridis)
#    ax.contour(X, Y, den_a.T, levels=[0.9], colors='limegreen', linewidths=3.5,origin='lower')
#    cbar=plt.colorbar(image1,pad=0.01,ticks=np.linspace(0.0, eee, 5),orientation="vertical")
#    cbar.set_label('$n_e$ [$n_c$]', fontdict=font2)
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        

    #### manifesting colorbar, changing label and axis properties ####
#    cbar=plt.colorbar(image2,pad=0.01,ticks=np.linspace(-eee, eee, 5),orientation="vertical")
#    cbar.set_label(r'$E_y\ [m_ec\omega_0/e]$',fontdict=font2)        
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
#    plt.title('Ey_den_e at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
    ax.text(42.,4.5,'t = '+str(round(time/1.0e-15,0))+' fs',fontdict=font,color='black')
    #ax.text(21.,1.75,'t = 70 fs',fontdict=font)
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(15,55)
#    ax.set_xlabel('X [$\lambda$]',fontdict=font)
#    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=0.0) 
    ax.tick_params(axis='x',labelsize=0.0) 
#    ax.tick_params(axis='both',labelsize=25) 
    ax.set_xticks(ticks=[20,30,40,50])
    ax.set_yticks(ticks=[-5,0,5])

    
    #ax=plt.subplot(3,1,1)
    ax=plt.subplot2grid((3, 3), (1, 1), colspan=2)
    #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2)
    #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2)
    #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #### manifesting colorbar, changing label and axis properties ####
    image1=ax.contourf(X, Y, ekbar.T, levels=levels_ek, norm=mcolors.Normalize(vmin=levels_ek.min(), vmax=levels_ek.max()), cmap=mycolor_jet)
    image1=ax.contour(X, Y, den_a.T, levels=[19.5], colors='k', linewidths=2,origin='lower')
#    cbar=plt.colorbar(image1,pad=0.01,ticks=np.linspace(0.0, eee, 5),orientation="vertical")
#    cbar.set_label('$n_e$ [$n_c$]', fontdict=font2)
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(15,55)
#    ax.set_xlabel('X [$\lambda$]',fontdict=font)
#    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=0.0) 
    ax.tick_params(axis='x',labelsize=0.0) 
#    ax.tick_params(axis='both',labelsize=25) 
    ax.set_xticks(ticks=[20,30,40,50])
    ax.set_yticks(ticks=[-5,0,5])


    #ax=plt.subplot(3,1,2)
    ax=plt.subplot2grid((3, 3), (2, 1), colspan=2)
    data = sdf.read(from_path+'current'+str(n).zfill(4)+".sdf",dict=True)
    ex = data['Current/Jx_averaged'].data/jalf/4/np.pi
    if dim == '3d':
        ex = (ex[:,:,n3d//2-1]+ex[:,:,n3d//2])/2.0
    print(np.max(abs(ex)))
    eee = 0.2
    levels = np.linspace(-eee, eee, 51)
    ex.T[ex.T < -eee]=-eee
    ex.T[ex.T >  eee]= eee
    image2=ax.contourf(X, Y, ex.T, levels=levels, cmap='bwr')
    #### manifesting colorbar, changing label and axis properties ####
#    cbar=plt.colorbar(image2,pad=0.01,ticks=np.linspace(-eee, eee, 5),orientation="vertical")
#    cbar.set_label(r'$\alpha=j_x/[4\pi I_A/\lambda^2]$',fontdict=font2)        
#    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
#    plt.title('Jx_averaged at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = '+str(round(time/1.0e-15,0))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = 70 fs',fontdict=font)
#    ax.contour(X, Y, den_a.T, levels=[0.9], colors='limegreen', linewidths=2,origin='lower')
    image1=ax.contour(X, Y, den_a.T, levels=[19.5], colors='k', linewidths=2,origin='lower')
    ax.set_ylim(-6.5,6.5)
    ax.set_xlim(15,55)
    ax.set_xlabel('X [$\mu m$]',fontdict=font)
#    ax.set_ylabel('Y [$\mu m$]',fontdict=font)
    ax.tick_params(axis='y',labelsize=0) 
    ax.tick_params(axis='x',labelsize=25) 
    ax.set_xticks(ticks=[20,30,40,50])
    ax.set_yticks(ticks=[-5,0,5])
##    ax=plt.subplot(3,1,3)
##    if dim == '3d':
##        Y, Z = np.meshgrid(y, z)
##        R = (Y**2+Z**2)**0.5 
##    elif dim == '2d':
##        R = abs(y)
##    x1 = np.linspace(-5,75,600)
##    J1 = 0.3*(2*np.pi)**2*3.2**2 
##    J2 = 0.056*(2*np.pi)**2*3.2**2 
##    y1 = np.zeros_like(x1)
##    y1[(x1>10)&(x1<45)] = J1
##    y2 = np.zeros_like(x1)+J2
##    
##    ax.plot(x1, y2, '--r', linewidth=3,label=r'$-J_x=\alpha^*(2\pi r/\lambda)^2J_A,\ \alpha^*=0.056$',zorder=0)
###    ax.plot(x1, y1, '--b', linewidth=3,label=r'$-J_x=\alpha(2\pi r/\lambda)^2J_A,\ \ \ \alpha=0.30$',zorder=1)
##    data = sdf.read(from_path+'current'+str(n).zfill(4)+".sdf",dict=True)
##    ex = data['Current/Jx_averaged'].data
##    Jx = np.sum(ex[:,R<2.5],1)*3.14*(1e-6/30)*5.0e-6/17e3
##    ax.plot(x, -Jx, '-b', linewidth=3,label='3D-PIC simulation')
##    ax.set_xlim(-5,75)
##    ax.set_xlabel('X [$\mu m$]',fontdict=font)
##    ax.set_ylabel('$-J_x$ [$J_A$]',fontdict=font)
##    ax.tick_params(axis='y',labelsize=25) 
##    ax.tick_params(axis='x',labelsize=25) 
##    ax.legend(loc='best',fontsize=16,framealpha=0.0)





    plt.subplots_adjust(left=0.08, bottom=0.14, right=0.99, top=0.95, wspace=0.055, hspace=0.025)
    #ax.set_xticklabels(xticklabels,fontdict=font)
    #ax.set_yticklabels(yticklabels,fontdict=font)

#    plt.subplot(gs[0])
#    plt.scatter(ppp_x[abs(ppp_y)<=3.2],ppp_px[abs(ppp_y)<=3.2],s=10,c='green',edgecolors='None',alpha=0.5)
#    plt.xlim(0,30)
#    plt.ylabel('p$_x$ [m$_e$c]', fontdict=font)
#    plt.xticks([])
#    plt.yticks(fontsize=20)
#  
#    plt.subplot(gs[3])
#    plt.scatter(ppp_py[abs(ppp_y)<=3.2],ppp_y[abs(ppp_y)<=3.2],s=10,c='green',edgecolors='None',alpha=0.5)
#    plt.ylim(-6.5,6.5)
#    plt.xlabel('p$_y$ [m$_e$c]', fontdict=font)
#    plt.yticks([])
#    plt.xticks(fontsize=20)
#
#    
#    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.011, hspace=0.051)
#

    #fig=plt.subplot(gs[1])
    #ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.10])
    #ax2 = fig.add_axes([0.05, 0.35, 0.9, 0.10])
    #cmap = mpl.cm.rainbow
    #norm = mpl.colors.Normalize(vmin=0.0, vmax=50)
    #cb1 = mpl.colorbar.ColorbarBase(ax1, cmap='Greys',
    #                            norm=norm,
    #                            orientation='horizontal',ticks=np.linspace(0.00, 50, 6))
    #cb1.set_label('n$_e$ [n$_c$]')
    #cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
    #cmap.set_over('0.25')
    #cmap.set_under('0.75')

    #cmap = mpl.cm.BrBG
    #Bz = 22.5
    #norm = mpl.colors.Normalize(vmin=-abs(Bz), vmax=abs(Bz))
    #cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_br,
    #                            norm=norm,
    #                            orientation='horizontal',ticks=np.linspace(-abs(Bz), abs(Bz), 5),alpha=0.7)
    #cb2.set_label(r'E$_y$ [m$_e\omega$/e]')
    #cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
    #cmap.set_over('0.25')
    #cmap.set_under('0.75')
    fig = plt.gcf()
    fig.set_size_inches(14, 14.)
    fig.savefig(to_path+'wrap_current.png',format='png',dpi=160)
    plt.close("all")
def processplot(n):
    ######### Parameter you should set ###########
    #start   =  23  # start time
    #stop    =  30  # end time
    #step    =  1  # the interval or step
    #youwant =  ['ey','ex','ey_averaged','bz','bz_averaged'] #,'electron_en','electron_ekbar','electron_density']
    #youwant.append('Ion_ekbar')
    #youwant.append('positron_ekbar')
    #youwant.append('electron_en')
    #youwant.append('photon_en')
    #youwant field  ex,ey,ez,bx,by,bz,ex_averaged,bx_averaged...
    #youwant Derived electron_density,electron_ekbar...
    #youwant dist_fn electron_x_px...

    from_path = './cannon_a190/'
    to_path = from_path

    n0 = 30.0
    R = 1.8e-6
    L = 15e-6
    Ntot = np.pi * R * R * L * n0 * denunit
    V = (1.0 / 20.0) * (1.0 / 15.0) * (1.0 / 15.0) * 1.0e-18
    weight = V * denunit * n0 / 50.0

    data = sdf.read(from_path + "i_tot_loc" + str(n).zfill(4) + ".sdf",
                    dict=True)
    header = data['Header']
    time1 = header['time']
    px = data['Particles/Px/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    py = data['Particles/Py/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    gg = (px**2 + py**2 + pz**2 + 1)**0.5
    theta = np.arctan2((py**2 + pz**2)**0.5, px) * 180.0 / np.pi

    grid_x = data['Grid/Particles/subset_Only_Ions0/Ion'].data[0] / 1.0e-6
    temp_id = data['Particles/ID/subset_Only_Ions0/Ion'].data

    px = px[theta < 10]
    grid_x = grid_x[theta < 10]
    theta = theta[theta < 10]

    if np.size(px) == 0:
        return 0
    theta[theta < -10] = -10
    theta[theta > 10] = 10

    color_index = abs(theta)

    print('hehe1')
    weight = np.zeros_like(grid_x) + weight
    print(max(weight), min(weight))
    ######### Script code drawing figure ################
    #for n in range(start,stop+step,step):
    #### header data ####
    #data = sdf.read(from_path+str(n).zfill(4)+".sdf",dict=True)
    #header=data['Header']
    #time=header['time']
    #x  = data['Grid/Grid_mid'].data[0]/1.0e-6
    #y  = data['Grid/Grid_mid'].data[1]/1.0e-6
    #X, Y = np.meshgrid(x, y)
    from_path_2 = './cannon_a190_e_div/'
    data = sdf.read(from_path_2 + 'q' + str(n).zfill(4) + ".sdf", dict=True)
    header = data['Header']
    time = header['time']
    x = data['Grid/Grid_mid'].data[0] / 1.0e-6
    y = data['Grid/Grid_mid'].data[1] / 1.0e-6
    z = data['Grid/Grid_mid'].data[2] / 1.0e-6

    X, Y, Z = np.meshgrid(x, y, z, sparse=False, indexing='ij')
    RR = (Y**2 + Z**2)**0.5

    data_ne_in = data['Derived/Number_Density/E_in'].data / denunit + data[
        'Derived/Number_Density/E_in_1'].data / denunit
    data_ne_out = data['Derived/Number_Density/E_out'].data / denunit + data[
        'Derived/Number_Density/E_out_1'].data / denunit
    data_np = data['Derived/Number_Density/Ion'].data / denunit + data[
        'Derived/Number_Density/Ion_1'].data / denunit
    data_nc = data['Derived/Number_Density/Carbon'].data / denunit + data[
        'Derived/Number_Density/Carbon_1'].data / denunit

    data_1 = sdf.read(from_path + 'e_fields' + str(n).zfill(4) + ".sdf",
                      dict=True)
    data_ex = data_1['Electric Field/' +
                     str.capitalize('ex_averaged')].data / exunit

    for R_lim in range(5, 45, 5):
        eexx = data_ex[:, RR[0, :, :] < R_lim / 10.]
        #  print(eexx.shape)
        n_size = eexx[-1, :].size
        value_ex = np.sum(eexx, axis=1) / n_size

        eexx = data_ne_in[:, RR[0, :, :] < R_lim / 10.]
        #      print(eexx.shape)
        n_size = eexx[-1, :].size
        value_n_e_in = np.sum(eexx, axis=1) / n_size

        eexx = data_ne_out[:, RR[0, :, :] < R_lim / 10.]
        #      print(eexx.shape)
        n_size = eexx[-1, :].size
        value_n_e_out = np.sum(eexx, axis=1) / n_size

        eexx = data_np[:, RR[0, :, :] < R_lim / 10.]
        #      print(eexx.shape)
        n_size = eexx[-1, :].size
        value_n_p = np.sum(eexx, axis=1) / n_size

        eexx = data_nc[:, RR[0, :, :] < R_lim / 10.]
        #      print(eexx.shape)
        n_size = eexx[-1, :].size
        value_n_c = np.sum(eexx, axis=1) / n_size
        #    plt.subplot()
        #  plt.scatter(grid_x, px, c=color_index, s=0.03, cmap='rainbow_r', edgecolors='None', alpha=0.66)
        #plt.hist2d(grid_x, px, bins=(50, 50), range=[[10,50],[0,1.5]], cmap=plt.cm.jet, weights=weight, norm=mcolors.Normalize(vmin=-2.0, vmax=2.0))
        fig, host = plt.subplots()
        plt.hist2d(grid_x,
                   px,
                   bins=(100, 100),
                   range=[[15, 45], [0, 1.5]],
                   cmap='cubehelix_r',
                   weights=weight,
                   normed=False,
                   norm=colors.Normalize(vmin=0, vmax=1e9))
        cbar = plt.colorbar(pad=0.1)
        cbar.set_label(r'$dN/(dxdp_x)$' + ' [A.U.]', fontdict=font)
        cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
        #plt.plot(np.linspace(-500,900,1001), np.zeros([1001]),':k',linewidth=2.5)
        #plt.plot(np.zeros([1001]), np.linspace(-500,900,1001),':k',linewidth=2.5)
        #plt.plot(np.linspace(-500,900,1001), np.linspace(-500,900,1001),'-g',linewidth=3)
        #plt.plot(np.linspace(-500,900,1001), 200-np.linspace(-500,900,1001),'-',color='grey',linewidth=3)
        #   plt.legend(loc='upper right')
        plt.xlim(15, 45)
        plt.ylim(0., 1.5)
        plt.xlabel('X [$\mu m$]', fontdict=font)
        plt.ylabel('$p_x$ [m$_i$c$^2$]', fontdict=font)
        plt.xticks([15, 25, 35, 45], fontsize=25)
        plt.yticks([0, 0.5, 1.0, 1.5], fontsize=25)
        #  plt.text(-100,650,' t = '++' fs',fontdict=font)
        plt.subplots_adjust(left=0.16,
                            bottom=None,
                            right=0.97,
                            top=None,
                            wspace=None,
                            hspace=None)
        plt.title('At ' + str(round(time1 / 1.0e-15, 2)) + ' fs',
                  fontdict=font)
        print('hehe')
        #plt.show()
        #lt.figure(figsize=(100,100))

        par1 = host.twinx()
        #par2 = host.twinx()
        #par3 = host.twinx()

        #par2.spines["right"].set_position(("axes", 1.05))
        #make_patch_spines_invisible(par2)
        #par2.spines["right"].set_visible(True)

        #par3.spines["right"].set_position(("axes", 1.1))
        #make_patch_spines_invisible(par3)
        #par3.spines["right"].set_visible(True)

        tkw = dict(size=25, width=2.)

        p1, = par1.plot(x,
                        value_ex,
                        "-",
                        color='lime',
                        label="$E_x$",
                        linewidth=3)
        par1.set_ylim(0, 5)

        p1, = par1.plot(x,
                        value_n_e_in + value_n_e_out,
                        "-b",
                        label="$n_e$",
                        linewidth=3)
        p1, = par1.plot(x, value_n_e_in, "-c", label="$n_e-in$", linewidth=3)
        p1, = par1.plot(x,
                        value_n_e_out,
                        "-",
                        color='orange',
                        label="$n_e-out$",
                        linewidth=3)

        p1, = par1.plot(x,
                        value_n_p + value_n_c * 6,
                        "-r",
                        label="$Z_in_i$",
                        linewidth=3)
        #  p3, = par3.plot(x,iden, "-r", label="Ion")
        #  p3, = par3.plot(x,iden, "-y", label="Ion")
        #  p3, = par3.plot(x,cden*6, "-g", label="Ion")
        #  par3.set_ylabel('$n^+\ [n_c]$')

        par1.legend(loc='middle right', fontsize=20, framealpha=1.0)
        par1.set_ylim(0, 5)
        par1.set_ylabel('$E_x$ [$m_ec\omega/|e|$] & $n_e$($Z_in_i$) [$n_c$]',
                        fontdict=font,
                        color='r')
        par1.tick_params(axis='y', labelsize=25, colors='r')

        fig = plt.gcf()
        fig.set_size_inches(12, 7.5)
        fig.savefig(from_path_2 + 'new_cut_px_x_phase_' + str(n).zfill(4) +
                    '_r' + str(R_lim).zfill(2) + '.png',
                    format='png',
                    dpi=160)
        plt.close("all")
        print('finised cut_px_x_phase_' + str(n).zfill(4) + '_r' +
              str(R_lim).zfill(2) + '.png')
    return 0
Exemplo n.º 12
0
# fs = 16

grid_min_x = 500
grid_max_x = 2999
grid_min_y = 500
grid_max_y = 2499

Gx = np.linspace(0, lx, nx)
Gy = np.linspace(0, ly, ny)
gx = Gx[grid_min_x:grid_max_x + 1]
gy = Gy[grid_min_y:grid_max_y + 1]

file = '/Volumes/yaowp2016/flow-n1-q/'
ii = 15
fname = file + str(ii).zfill(4) + '.sdf'
datafile = sdf.read(fname)
nbe = datafile.Derived_Number_Density_ele_bm.data / n0
nae = datafile.Derived_Number_Density_ele_e.data / n0
nqe = datafile.Derived_Number_Density_ele_qed.data / n0
nph = datafile.Derived_Number_Density_pho.data / n0

NBE = nbe[grid_min_x:grid_max_x + 1, grid_min_y:grid_max_y + 1].transpose()
NAE = nae[grid_min_x:grid_max_x + 1, grid_min_y:grid_max_y + 1].transpose()
NQE = nqe[grid_min_x:grid_max_x + 1, grid_min_y:grid_max_y + 1].transpose()
NPH = nph[grid_min_x:grid_max_x + 1, grid_min_y:grid_max_y + 1].transpose()

file = '/Volumes/yaowp2016/flow-n/'
ii = 15
fname = file + str(ii).zfill(4) + '.sdf'
datafile = sdf.read(fname)
nbe1 = datafile.Derived_Number_Density_ele_bm.data / n0
exunit    =     m0*v0*frequency/q0
bxunit    =     m0*frequency/q0
denunit    =     frequency**2*epsilon0*m0/q0**2
print('electric field unit: '+str(exunit))
print('magnetic field unit: '+str(bxunit))
print('density unit nc: '+str(denunit))

font = {'family' : 'monospace',  
        'style'  : 'normal',
        'color'  : 'black',  
	    'weight' : 'normal',  
        'size'   : 20,  
       }  


data = sdf.read('./Data/'+str(12).zfill(4)+".sdf",dict=True)
header=data['Header']
time=header['time']

px = data['Particles/Px/subset_high_e/electron'].data/(m0*v0)
py = data['Particles/Py/subset_high_e/electron'].data/(m0*v0)
grid_x = data['Grid/Particles/subset_high_e/electron'].data[0]/wavelength
grid_y = data['Grid/Particles/subset_high_e/electron'].data[1]/wavelength
work_x = data['Particles/Time_Integrated_Work_x/subset_high_e/electron'].data
work_y = data['Particles/Time_Integrated_Work_y/subset_high_e/electron'].data
#field_ex = data['Particles/field_ex/subset_high_e/electron'].data/exunit
#field_ey = data['Particles/field_ey/subset_high_e/electron'].data/exunit
#field_bz = data['Particles/field_bz/subset_high_e/electron'].data/bxunit
gg = (px**2+py**2+1)**0.5

px = px [(abs(grid_y) < 3.2) & (gg > 200.0)]
  mycolor_binary = matplotlib.colors.ListedColormap(cmap, name='myColorMap', N=cmap.shape[0])

  upper = matplotlib.cm.Oranges(np.arange(256))
  lower = np.ones((int(256/4),4))
  for i in range(3):
      lower[:,i] = np.linspace(1, upper[0,i], lower.shape[0])
  cmap = np.vstack(( lower, upper ))
  mycolor_orange = matplotlib.colors.ListedColormap(cmap, name='myColorMap', N=cmap.shape[0])


  ######### Parameter you should set ###########
  from_path = './cannon_a190_v484/'
  to_path   = './cannon_a190_v484_fig/' 
  if not os.path.exists(to_path):
         os.mkdir(to_path)  
  data = sdf.read(from_path+"i_tot_loc0027.sdf",dict=True)
  px = data['Particles/Px/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
  py = data['Particles/Py/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
  pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
  theta = np.arctan2((py**2+pz**2)**0.5,px)*180.0/np.pi
  gg = (px**2+py**2+pz**2+1)**0.5
  Ek = (gg-1)*1836*0.51
  part13_id = data['Particles/ID/subset_Only_Ions0/Ion'].data
  part13_id = part13_id[ (Ek>220) & (abs(theta)<10) & (Ek<240)]
  print('part13_id size is ',part13_id.size,' max ',np.max(part13_id),' min ',np.min(part13_id))

  x_start = 460
  x_stop  = 520
  quiver_space = 5
  ######### Script code drawing figure ################
  n=17        
Exemplo n.º 15
0
font = {
    'family': 'monospace',
    'color': 'black',
    'weight': 'normal',
    'size': 20,
}
######### Parameter you should set ###########
start = 1  # start time
stop = 49  # end time
step = 1  # the interval or step

#  if (os.path.isdir('jpg') == False):
#    os.mkdir('jpg')
######### Script code drawing figure ################
for n in range(start, stop + step, step):
    #### header data ####
    data = sdf.read("./Data/" + str(n).zfill(4) + ".sdf", dict=True)
    header = data['Header']
    time = header['time']
    #    if ( n==start ):
    #        part_id = data['Particles/ID/subset_high_e/electron'].data
    #    else:
    #        part_id = np.intersect1d(data['Particles/ID/subset_high_e/electron'].data, part_id)
    part_id = data['Particles/ID/subset_high_e/electron'].data
    print('Particle_ID size is ', part_id.size, ' max ', np.max(part_id),
          ' min ', np.min(part_id))
    print('finised ' +
          str(round(100.0 * (n - start + step) /
                    (stop - start + step), 4)) + '%')
Exemplo n.º 16
0
def processplot(n): 
    from_path='./uniform_a190_n30/'
    to_path=from_path
    x_start=100; x_stop=700; y_start=60; y_stop=300; z_start=60; z_stop=300;
    x_size = x_stop-x_start; y_size = y_stop-y_start; z_size = z_stop-z_start
    name = 'Er_averaged'

    data = sdf.read(from_path+'e_fields'+str(n).zfill(4)+'.sdf',dict=True)
    header=data['Header']
    time =header['time']
    x    = data['Grid/Grid_mid'].data[0]/1.e-6
    y    = data['Grid/Grid_mid'].data[1]/1.e-6
    z    = data['Grid/Grid_mid'].data[2]/1.e-6
    var1  = data['Electric Field/Ey_averaged'].data/exunit
    var2  = data['Electric Field/Ez_averaged'].data/exunit
    var  = (var1**2+var2**2)**0.5
   

    X, Y, Z = np.meshgrid(x, y, z, sparse=False, indexing='ij')
    var  = var[x_start:x_stop,y_start:y_stop,z_start:z_stop]
    X    =  X[x_start:x_stop,y_start:y_stop,z_start:z_stop]
    Y    =  Y[x_start:x_stop,y_start:y_stop,z_start:z_stop]
    Z    =  Z[x_start:x_stop,y_start:y_stop,z_start:z_stop]
   
    var = rebin3d(var, (x_size//2, y_size//2, z_size//2))
    X = rebin3d(X, (x_size//2, y_size//2, z_size//2))
    Y = rebin3d(Y, (x_size//2, y_size//2, z_size//2))
    Z = rebin3d(Z, (x_size//2, y_size//2, z_size//2))

    var  = var.reshape(np.size(var))
    var[var>20] = 20
    X    = X.reshape(np.size(X))
    Y    = Y.reshape(np.size(Y))
    Z    = Z.reshape(np.size(Z))

    plotkws = {'marker':'.','edgecolors':'none'}
    norm = None

    index = 4.0
    _abs  = False # True is for ex; Flase is for density
    log   = False
    elev  = None
    azim  = None

    if _abs:
        norm = 0
        _min = max(np.max(var),np.min(var))**(0.002**(1.0/index)) if log else max(np.max(var),np.min(var))*0.002**(1.0/index)
        plt.set_cmap(reg_cmap_transparent('bwr',create_alpha(lambda x:abs(x/127.5-1)**index)))
    else:
        _min = np.max(var)**(0.002**(1.0/index)) if log else np.max(var)*0.002**(1.0/index)
        plt.set_cmap(reg_cmap_transparent('hsv_r',create_alpha(lambda x:abs(x/255.0)**index)))

        #special code
        _min = max(_min,1.1e27*0.8)
    #    var._cutrange(lambda x : x[1] < 3)

    if log:
        plotkws['norm'] = matplotlib.colors.LogNorm()

    #var.cutrange(_min=_min,_abs=_abs)
    #point_scatter3D(var,norm=norm,plotkws=plotkws)
    #def point_scatter3D(var,elev=None,azim=None,hold=False,iso=False,norm=None,plotkws={}):
    cmap = plt.get_cmap()
    if norm is not None:
        v0 = np.min(var) - norm
        v1 = np.max(var) - norm
        if abs(v0/v1) > 1:
            low = 0
            high = 0.5 * (1 - v1/v0)
        else:
            low = 0.5 * (1 + v0/v1)
            high = 1.0

        cmap = plt.cm.colors.LinearSegmentedColormap.from_list('tr',
                cmap(np.linspace(low,high,256)))

#    print('here1')
    fig = plt.figure()
    ax  = plt.axes(projection='3d')
    ax.view_init(elev=elev, azim=azim)
#    print('here2')
    im = ax.scatter(X, Y, Z, c=var, cmap=cmap, **plotkws)
#    print('here3')
    ax.set_xlabel('\n\nX'+ '[$\mu m$]',fontdict=font)
    ax.set_ylabel('\n\ny'+ '[$\mu m$]',fontdict=font)
    ax.set_zlabel('\n\nZ'+ '[$\mu m$]',fontdict=font)

    ax.set_xlim([x_start/20-5,x_stop/20-5])
    ax.set_ylim([-(y_stop-y_start)/2/15-5,(y_stop-y_start)/2/15+5])
    ax.set_zlim([-(z_stop-z_start)/2/15-5,(z_stop-z_start)/2/15+5])

    
    #cbar=plt.colorbar(im, ticks=np.linspace(np.min(color_index), np.max(color_index), 5) ,pad=0.01)
    cbar=plt.colorbar(im, pad=0.01)
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
    cbar.set_label(name+r'$[m_ec\omega/|e|]$',fontdict=font)
    #cbar.set_clim(300,600)

    #print('here4')

    for t in ax.xaxis.get_major_ticks(): t.label.set_fontsize(font_size)
    for t in ax.yaxis.get_major_ticks(): t.label.set_fontsize(font_size)
    for t in ax.zaxis.get_major_ticks(): t.label.set_fontsize(font_size)


    #plot for y_z plane
    Y,Z  = np.meshgrid(y,z,indexing='ij')
    eexx = (var1**2+var2**2)**0.5
    ex = (eexx[420-1,:,:]+eexx[420,:,:])/2
    ex = ex[y_start:y_stop,z_start:z_stop]
    eee = 10.0 #np.max([np.max(ex),abs(np.min(ex))])
    ex[ex>eee] = eee 
    Y  = Y[y_start:y_stop,z_start:z_stop]
    Z  = Z[y_start:y_stop,z_start:z_stop]
    levels = np.linspace(0, eee, 40)
    im2=ax.contourf(ex.T, Y.T, Z.T, levels=levels, norm=mcolors.Normalize(vmin=0, vmax=eee), cmap=cm.gray_r, zdir='x', offset=x_start/20-5)
#    ax.set_xlim([x_start/20-5,x_stop/20-5])
#    ax.set_xlim([-(y_stop-y_start)/2/12,(y_stop-y_start)/2/12])
#    ax.set_ylim([-(z_stop-z_start)/2/12,(z_stop-z_start)/2/12])
    cbar = plt.colorbar(im2,  ticks=np.linspace(0, eee, 3))
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
    cbar.set_label(name+r'$[m_e\omega/|e|]$',fontdict=font)
    

    #plot for x_z plane
    X,Z = np.meshgrid(x,z,indexing='ij')
    eexx = data['Electric Field/Ez_averaged'].data/exunit
    ex = (eexx[:,(y_start+y_stop)//2-1,:]+eexx[:,(y_start+y_stop)//2,:])/2
    ex = ex[x_start:x_stop,z_start:z_stop]
    X  = X[x_start:x_stop,z_start:z_stop]
    Z  = Z[x_start:x_stop,z_start:z_stop]
    if np.min(ex.T) == np.max(ex.T):
         #continue
         return
    eee = 10
    levels = np.linspace(-eee, eee, 40)
    ex[ex>eee] = eee
    ex[ex<-eee] = -eee
    ax.contourf(X.T, ex.T, Z.T, levels=levels, norm=mcolors.Normalize(vmin=-eee, vmax=eee), cmap=cm.bwr, zdir='y', offset=(y_stop-y_start)/2/15+5)
#    ax.set_xlim([x_start/20-5,x_stop/20-5])
#    ax.set_ylim([-(y_stop-y_start)/2/12,(y_stop-y_start)/2/12])
#    ax.set_ylim([-(z_stop-z_start)/2/12,(z_stop-z_start)/2/12])

    #plot for x_y plane
    X,Y = np.meshgrid(x,y,indexing='ij')
    eexx = data['Electric Field/Ey_averaged'].data/exunit
    ex = (eexx[:,:,(z_start+z_stop)//2-1]+eexx[:,:,(z_start+z_stop)//2])/2
    ex = ex[x_start:x_stop,y_start:y_stop]
    X  = X[x_start:x_stop,y_start:y_stop]
    Y  = Y[x_start:x_stop,y_start:y_stop]
    if np.min(ex.T) == np.max(ex.T):
         #continue
         return
    eee = 10
    levels = np.linspace(-eee, eee, 40)
    ex[ex>eee] = eee
    ex[ex<-eee] = -eee
    im2=ax.contourf(X.T, Y.T, ex.T, levels=levels, norm=mcolors.Normalize(vmin=-eee, vmax=eee), cmap=cm.bwr, zdir='z', offset=-(z_stop-z_start)/2/15-5)
#    ax.set_xlim([x_start/20-5,x_stop/20-5])
#    ax.set_ylim([-(y_stop-y_start)/2/12,(y_stop-y_start)/2/12])
#    ax.set_zlim([-(z_stop-z_start)/2/12,(z_stop-z_start)/2/12])
    cbar = plt.colorbar(im2,  ticks=np.linspace(-eee, eee, 5))
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
    cbar.set_label(r'$E_r\ [m_ec\omega/|e|]$',fontdict=font)

    plt.show()
    ax.grid(False)
    ax.xaxis.pane.set_edgecolor('black')
    ax.yaxis.pane.set_edgecolor('black')
    ax.zaxis.pane.set_edgecolor('black')
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False
    #ax.grid(linestyle='None', linewidth='0.5', color='white')
    plt.subplots_adjust(left=0.16, bottom=None, right=0.97, top=None,
                    wspace=None, hspace=None)
  #  plt.title('At '+str(round(time/1.0e-15,2))+' fs',fontdict=font)

    fig = plt.gcf()
    fig.set_size_inches(20, 10.5)
    fig.savefig(to_path+'3d_'+name+str(n).zfill(4)+'.png',format='png',dpi=160)
    plt.close("all")
    print('finised '+str(n).zfill(4))
Exemplo n.º 17
0
import sdf
import numpy as np
import constant as const
from mayavi import mlab
data = sdf.read('Documents/data/2800.sdf', dict=True)
var1 = data['Electric Field/Ey'].data
bz = var1
k_bz = np.fft.fft(bz, axis=0)
delta_k = 3.14 / const.delta_x / (const.Nx / 2)
k_bz2 = k_bz * 1
k_n = []
for n in range(0, const.Nx):
    mi = 3e8 / 0.1e12  #limit_min
    ma = 3e8 / 10e12  #limit_max
    if 2 * 3.14 / ma > n * delta_k and n * delta_k > 2 * 3.14 / mi:
        k_n.append(n)
k_bz2[0:k_n[0], :, :] = 0  #k_bz.argmin()
k_bz2[k_n[-1]:-k_n[-1], :, :] = 0  #k_bz.argmin()
k_bz2[-k_n[0]:, :, :] = 0  #k_bz.argmin()
var1 = np.fft.ifft(k_bz2, axis=0).real
mlab.contour3d(var1)
mlab.show()
Exemplo n.º 18
0
import sys
import sdf
import matplotlib.pyplot as plt
import os
import re

a = r'^tp\d{4}.sdf$'

for root, dirs, files in os.walk(os.getcwd()):
    print(files)
'''above read file'''

for filename in files:
    if (re.match(a, filename)):
        ff = sdf.read(filename)
        '''read sdf'''
        keys = ff.__dict__.keys()
        print(keys)
        print('Next--------------')
        dataname = r'^\w+_Gamma_\w+$'
        for key in keys:
            if (re.match(dataname, key)):
                print(key)
                data = ff.__dict__[key]
Exemplo n.º 19
0
        'size'   : 20,  
        }  



######### Parameter you should set ###########
start   =  1  # start time
stop    =  400  # end time
step    =  1  # the interval or step

Data = 'Data0/'
name = 'electron scattering plot'
amplitude = '250'
######### Script code drawing figure ################

data0 = sdf.read("./Dataa"+amplitude+"no/0000.sdf",dict=True)
#data1 = sdf.read("./Dataa350rr/"+str(n).zfill(4)+".sdf",dict=True)
header=data0['Header']
time=header['time']
x0  = data0['Grid/Particles/electron'].data[0]/1.0e-6
y0  = data0['Grid/Particles/electron'].data[1]/1.0e-6
id0 = data0['Particles/ID/electron'].data
pos0= np.zeros(5000)
print(np.max(id0-1),np.min(id0-1),x0[id0-1])
for i in range(5000):
    pos0[id0[i]-1]=y0[i]

data0 = sdf.read("./Dataa"+amplitude+"rr/0000.sdf",dict=True)
#data1 = sdf.read("./Dataa350rr/"+str(n).zfill(4)+".sdf",dict=True)
header=data0['Header']
time=header['time']
Exemplo n.º 20
0
def use_sdf(sdf_num, pathname, *args, **kwargs):
  """The basic routine for taking data from an sdf file and putting it in
  [dat]. The varaibles are put into lists depending on type so they can be
  easily plotted later, the lists are cleaned of certain variables that
  cannot easily be plotted. Finally the data is labelled with new units
  and passed to the analysis functions for post-processing.
  """
  istart = kwargs.get('istart', 0)
  use_analysis = kwargs.get('use_analysis', False)

  SDFName=pathname+'/'+str(sdf_num).zfill(4)+'.sdf'
  dat = sdf.read(SDFName)

  # Get all variables
  dat_names = list(dat.__dict__.keys())
  variable_type = sdf.BlockPlainVariable
  grid_type = sdf.BlockLagrangianMesh
  beam_type = sdf.BlockStitchedPath

  # Create lists of certain types of variable for plotting
  dat_grid_names = []
  dat_variable_names = []
  dat_variable_time_names = []
  dat_track_surfaces = []
  dat_beam_names = []
  dat_burst_names = []
  for n in range(0, len(dat_names)):
    var = getattr(dat, dat_names[n])
    if type(var) == variable_type:
      dat_variable_names.append(dat_names[n])
    elif type(var) == grid_type:
      dat_grid_names.append(dat_names[n])
    elif type(var) == beam_type:
      dat_beam_names.append(dat_names[n])

  # Clean grid list of things that require special effort to plot
  bad_var_list = []
  for var in dat_grid_names:
    if ('Ray' in var):
      bad_var_list.append(var)
    if ('Electrons_Electron' in var):
      bad_var_list.append(var)
  for var in bad_var_list:
    dat_grid_names.remove(var)

  # Clean variable list of things that require special effort to plot
  bad_var_list = []
  for var in dat_variable_names:
    if ('Ray' in var):
      bad_var_list.append(var)
    if ('Electrons_Electron' in var):
      bad_var_list.append(var)
  for var in bad_var_list:
    dat_variable_names.remove(var)

  # Clean beams list of individual rays
  bad_var_list = []
  for var in dat_beam_names:
    if ('_' in var):
      bad_var_list.append(var)
    else:
      if ('Burst' in var):
        dat_burst_names.append(var)
        bad_var_list.append(var)
  for var in bad_var_list:
    dat_beam_names.remove(var)

  # Clean Epoch list of CPU and particle distributions that I cannot plot yet
  if (dat.Header['code_name'] == 'Epoch2d'):
    dat_grid_names = ['Grid_Grid', 'Grid_Grid_mid']
    bad_var_list = []
    for var in dat_variable_names:
      if ('CPU' in var):
        bad_var_list.append(var)
      if ('dist' in var):
        bad_var_list.append(var)
    for var in bad_var_list:
      dat_variable_names.remove(var)

  # Add lists to dat
  setattr(dat, "grids", dat_grid_names)
  setattr(dat, "track_surfaces", dat_track_surfaces)
  setattr(dat, "variables", dat_variable_names)
  setattr(dat, "variables_time", dat_variable_time_names)
  setattr(dat, "beams", dat_beam_names)
  setattr(dat, "bursts", dat_burst_names)

  # Save time variable
  var_list = dat.variables_time
  var_name = "Times"
  var_list.append(var_name)
  setattr(dat, var_name, afunc.new_variable(data = dat.Header["time"],
                                            units_new = "ns",
                                            unit_conversion = 1.0e9,
                                            name = "Time"))
  setattr(dat, "variables_time", var_list)

  dat = add_label(dat)

  # Analysis functions are applied to SDF data
  if use_analysis:
    dat = afunc.basic(dat)
    if ("Fluid_Energy_deposited_laser" in dat.variables
        and hasattr(dat, "Fluid_Number_density_electron")):
      dat = afunc.laser(dat, call_basic = False, laser_change = True,
          sdf_num = sdf_num, istart = istart, pathname = pathname)
    if "Fluid_Energy_deposited_hot_electron" in dat.variables:
      dat = afunc.hot_electron(dat,
          sdf_num = sdf_num, istart = istart, pathname = pathname)
    dat = afunc.adiabat(dat, call_basic = False)
    dat = afunc.energy(dat, call_basic = False)

  return dat
Exemplo n.º 21
0
def main(from_path, to_path):
  for n in range(start,stop+step,step):
    if n < 40:
        x_min,x_max=45,55
        y_min,y_max=500,1100
    elif n < 50:
        x_min,x_max=45,55
        y_min,y_max=0,1100
    elif n < 70: 
        x_min,x_max=45,55
        y_min,y_max=-600,1100
    elif n < 90: 
        x_min,x_max=40,60
        y_min,y_max=-1000,1100
    elif n < 125: 
        x_min,x_max=40,60
        y_min,y_max=-1000,1100
    elif n < 180: 
        x_min,x_max=35,65
        y_min,y_max=-1000,1100
    elif n < 235: 
        x_min,x_max=30,70
        y_min,y_max=-400,400
    elif n < 290: 
        x_min,x_max=25,75
        y_min,y_max=-400,400
    else:
        x_min,x_max=25-(n*1.0-290.0)*0.1,75+(n*1.0-290.0)*0.1
        y_min,y_max=-300,300
    #plt.xlim(x_min,x_max)
    #plt.ylim(y_min,y_max)

    datalaser = sdf.read("./Datalaser/"+str(n).zfill(4)+".sdf",dict=True)
    laser_x   = datalaser['Grid/Grid_mid'].data[0]/1.0e-6
    laser_y   = datalaser['Grid/Grid_mid'].data[1]/1.0e-6
    X,Y = np.meshgrid(laser_x,laser_y)
    ex  = datalaser['Electric Field/Ey'].data/exunit/250.0
    if np.min(ex.T) == np.max(ex.T):
          continue
    eee=np.max([-np.min(ex.T),np.max(ex.T)])
    levels = np.linspace(-eee, eee, 24)
    #### header data ####
    plt.subplots_adjust(left=0.05,right=0.9,bottom=0.1,top=0.95,wspace=0.15,hspace=0.2)

    plt.subplot(1,3,1)
    data0 = sdf.read("./Dataa"+amplitude+"no/"+str(n).zfill(4)+".sdf",dict=True)
    #data1 = sdf.read("./Dataa350rr/"+str(n).zfill(4)+".sdf",dict=True)
    header=data0['Header']
    time=header['time']
    x0  = data0['Grid/Particles/electron'].data[0]/1.0e-6
    y0  = data0['Grid/Particles/electron'].data[1]/1.0e-6
    px0 = data0['Particles/Px/electron'].data/(m0*v0)
    id0 = data0['Particles/ID/electron'].data

#    x   = data0['Grid/Grid_mid'].data[0]/1.0e-6
#    y   = data0['Grid/Grid_mid'].data[1]/1.0e-6
#  X,Y = np.meshgrid(x,y)
#  ex  = data0['Electric Field/Ey'].data/exunit
#  if np.min(ex.T) == np.max(ex.T):
#        continue
#  eee=np.max([-np.min(ex.T),np.max(ex.T)])
#  levels = np.linspace(-eee, eee, 24)
#  plt.contourf(X, Y, ex.T, levels=levels, cmap=cm.RdGy)
    plt.scatter(x0,px0,s=20,c=abs(pos0[id0-1]),cmap=cm.rainbow,label='No RR',edgecolors='None') 
    plt.legend(loc='upper right',framealpha=1.0,markerscale=2,fontsize=20.0)
    plt.xlim(40,90)
    plt.ylim(-50,1100)
    #plt.text(x_min+0.1*(x_max-x_min),y_max-0.1*(y_max-y_min),r'$\xi_0$='+amplitude+'   No RR',fontsize=25)
    plt.xlabel('X [$\mu m$]',fontdict=font)
    plt.ylabel('Px [$m_ec$]',fontdict=font)
    plt.xticks(fontsize=20); plt.yticks(fontsize=12);
    plt.title(name+' at '+str(round(time/3.333e-15,2))+' $T_0$',fontdict=font)

    plt.subplot(1,3,2)
    data0 = sdf.read("./Dataa"+amplitude+"rr/"+str(n).zfill(4)+".sdf",dict=True)
#    data1 = sdf.read("./epoch2drr/Data1/"+str(n).zfill(4)+".sdf",dict=True)
#    data2 = sdf.read("./epoch2dqe/Data1/"+str(n).zfill(4)+".sdf",dict=True)
    header=data0['Header']
    time=header['time']
    x0  = data0['Grid/Particles/electron'].data[0]/1.0e-6
    y0  = data0['Grid/Particles/electron'].data[1]/1.0e-6
    px0 = data0['Particles/Px/electron'].data/(m0*v0)
    id0 = data0['Particles/ID/electron'].data
#    plt.scatter(x1,y1,s=8,c=(0,192.0/255.0,0),label='LL RR',edgecolors='None') 
    #plt.contourf(X, Y, ex.T, levels=levels, cmap=cm.bwr)
    plt.scatter(x0,px0,s=20,c=abs(pos1[id0-1]),cmap=cm.rainbow,label='LL RR',edgecolors='None') 
    plt.legend(loc='upper right',framealpha=1.0,markerscale=2,fontsize=20.0)
    plt.xlim(40,90)
    plt.ylim(-50,1100)
    #plt.text(x_min+0.1*(x_max-x_min),y_max-0.1*(y_max-y_min),r'$\xi_0$='+amplitude+'   LL RR',fontsize=25)    
    #plt.text(5,45,r'$\xi_0=350$',fontsize=20)
    plt.xlabel('X [$\mu m$]',fontdict=font)
    plt.ylabel('Px [$m_ec$]',fontdict=font)    
    plt.xticks(fontsize=20); plt.yticks(fontsize=12);
    plt.title(name+' at '+str(round(time/3.333e-15,2))+' $T_0$',fontdict=font)

    plt.subplot(1,3,3)
    data0 = sdf.read("./Dataa"+amplitude+"qe/"+str(n).zfill(4)+".sdf",dict=True)
    header=data0['Header']
    time=header['time']
    x0  = data0['Grid/Particles/electron'].data[0]/1.0e-6
    y0  = data0['Grid/Particles/electron'].data[1]/1.0e-6
    px0 = data0['Particles/Px/electron'].data/(m0*v0)
    id0 = data0['Particles/ID/electron'].data
#    plt.scatter(x1,y1,s=8,c=(0,192.0/255.0,0),label='LL RR',edgecolors='None') 
    #plt.contourf(X, Y, ex.T, levels=levels, cmap=cm.bwr)
    plt.scatter(x0,px0,s=20,c=abs(pos2[id0-1]),cmap=cm.rainbow,label='QED RR',edgecolors='None') 
    plt.legend(loc='upper right',framealpha=1.0,markerscale=2,fontsize=20.0)
    #plt.text(x_min+0.1*(x_max-x_min),y_max-0.1*(y_max-y_min),r'$\xi_0$='+amplitude+'   QED RR',fontsize=25)
    plt.xlim(40,90)
    plt.ylim(-50,1100)
    #plt.text(5,45,r'$\xi_0=350$',fontsize=20)
    plt.xlabel('X [$\mu m$]',fontdict=font)
    plt.ylabel('Px [$m_ec$]',fontdict=font)    
    plt.xticks(fontsize=20); plt.yticks(fontsize=12);
    plt.title(name+' at '+str(round(time/3.333e-15,2))+' $T_0$',fontdict=font)
    
    
    #plt.subplots_adjust(left=0.05,right=0.85,bottom=0.1,top=0.95,wspace=0.15,hspace=0.2)
    cbar=plt.colorbar(ticks=[0.5, 1.0, 1.5, 2.0],cax=plt.axes([0.94,0.1,0.01,0.85]))
    cbar.set_label('Initial transverse position $y_0$',fontdict=font) 
    fig = plt.gcf()
    fig.set_size_inches(33, 9)
    fig.savefig('./jpg_x_px250/gif'+str(n).zfill(4)+'.png',format='png',dpi=45)
    plt.close("all")
    fig.show()
    print 'finised '+str(round(100.0*(n-start+step)/(stop-start+step),4))+'%'
font = {
    'family': 'monospace',
    'style': 'normal',
    'color': 'black',
    'weight': 'normal',
    'size': 30,
}
######### Parameter you should set ###########
start = 12  # start time
stop = 12  # end time
step = 1  # the interval or step

n = 12

for n in range(start, stop + step, step):
    data = sdf.read("./Data_a20_fine/" + str(n).zfill(4) + ".sdf", dict=True)
    header = data['Header']
    time = header['time']
    work_x = data[
        'Particles/Time_Integrated_Work_x/subset_high_e/electron'].data
    work_y = data[
        'Particles/Time_Integrated_Work_y/subset_high_e/electron'].data
    px = data['Particles/Px/subset_high_e/electron'].data / (m0 * v0)
    py = data['Particles/Py/subset_high_e/electron'].data / (m0 * v0)
    grid_x = data['Grid/Particles/subset_high_e/electron'].data[0] / wavelength
    grid_y = data['Grid/Particles/subset_high_e/electron'].data[1] / wavelength

    gg = (px**2 + py**2 + 1.0)**0.5  # relativistic factor gamma

    work_x = work_x[gg > 5]
    work_y = work_y[gg > 5]
                 y_y * 100,
                 width,
                 bottom=y_x * 100,
                 color='deepskyblue',
                 edgecolor='black',
                 linewidth=1)


if __name__ == "__main__":
    ######### Script code drawing figure ################
    n = 18
    mass = 1836.
    name = 'proton'
    plt.subplot(1, 1, 1)

    data = sdf.read('./PW_w010/' + str(n).zfill(4) + ".sdf", dict=True)
    time = data['Header']['time']
    px = data['Particles/Px/' + name].data / (mass * m0 * v0)
    py = data['Particles/Py/' + name].data / (mass * m0 * v0)
    grid_y = data['Grid/Particles/' + name].data[1] / 1e-6
    gg = (px**2 + py**2 + 1.0)**0.5
    ek = (gg - 1.) * mass * m0 * v0**2 / 1.6e-13
    ww = data['Particles/Weight/' + name].data * 4e-6
    theta = np.arctan2(py, px) * 180.0 / np.pi
    ek = ek[(px > 0) & (abs(grid_y) < 2) & (abs(theta) < 30)]
    ww = ww[(px > 0) & (abs(grid_y) < 2) & (abs(theta) < 30)]
    dist_x1, den1 = pxpy_to_energy(ek, ww)
    plt.plot(dist_x1,
             den1,
             color='crimson',
             linewidth=3,
Exemplo n.º 24
0
def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)


if __name__ == '__main__':
    start = 10  # start time
    stop = 27  # end time
    step = 1  # the interval or step

    from_path = './cannon_a190_v484/'
    to_path = './cannon_a190_v484_fig/'

    data = sdf.read(from_path + "i_tot_loc0027.sdf", dict=True)
    #grid_x = data['Grid/Particles/subset_high_e/electron'].data[0]/wavelength
    px = data['Particles/Px/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    py = data['Particles/Py/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    theta = np.arctan2((py**2 + pz**2)**0.5, px) * 180.0 / np.pi
    gg = (px**2 + py**2 + pz**2 + 1)**0.5
    Ek = (gg - 1) * 1836 * 0.51

    part13_id = data['Particles/ID/subset_Only_Ions0/Ion'].data
    part13_id = part13_id[(Ek > 225) & (abs(theta) < 10) & (Ek < 245)]

    print('part13_id size is ', part13_id.size, ' max ', np.max(part13_id),
          ' min ', np.min(part13_id))

    fig, ax = plt.subplots()
Exemplo n.º 25
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)
                                               name='myColorMap',
                                               N=cmap.shape[0])

if __name__ == '__main__':
    start = 1  # start time
    stop = 19  # end time
    step = 1  # the interval or step

    from_path = './PW_w020/'
    to_path = './PW_w020_fig/'
    part_name = 'electron'
    mass = 1.0

    for n in range(start, stop + step, step):

        data = sdf.read(from_path + str(n).zfill(4) + ".sdf", dict=True)
        header = data['Header']
        time1 = header['time']
        px = data['Particles/Px/' + part_name].data / (mass * m0 * v0)
        py = data['Particles/Py/' + part_name].data / (mass * m0 * v0)
        work_x = data['Particles/Time_Integrated_Work_x/' +
                      part_name].data * 0.51
        work_y = data['Particles/Time_Integrated_Work_y/' +
                      part_name].data * 0.51
        gg = (px**2 + py**2 + 1)**0.5
        theta = np.arctan2(py, px) * 180.0 / np.pi
        grid_x = data['Grid/Particles/' + part_name].data[0] / 1.0e-6
        grid_y = data['Grid/Particles/' + part_name].data[1] / 1.0e-6
        temp_id = data['Particles/ID/' + part_name].data
        weight = data['Particles/Weight/' + part_name].data * 4e-6
bxunit    =     m0*frequency/q0
denunit    =     frequency**2*epsilon0*m0/q0**2
print 'electric field unit: '+str(exunit)
print 'magnetic field unit: '+str(bxunit)
print 'density unit nc: '+str(denunit)

font = {'family' : 'Helvetic',
        'color'  : 'black',
        'weight' : 'normal',
        'size'   : 16,
        }

plt.rc('text', usetex=True)
plt.rc('font', family='serif')

data1 = sdf.read("./Datan2w33p/0029.sdf",dict=True)
data2 = sdf.read("./Datan5w33p/0029.sdf",dict=True)
data3 = sdf.read("./Datan10w33p/0029.sdf",dict=True)
data4 = sdf.read("./Datan20w33p/0029.sdf",dict=True)
header=data1['Header']
time=header['time']


plt.subplots_adjust(left=0.05,right=0.95,bottom=0.1,top=0.95,wspace=0.25,hspace=0.3)

plt.subplot(1,3,1)
name='electron'
en_Z1 = data1['dist_fn/en/'+name].data[:,0,0]
dist_x1  = data1['Grid/en/'+name].data[0]/(q0*1.0e6)
en_Z2 = data2['dist_fn/en/'+name].data[:,0,0]
dist_x2  = data2['Grid/en/'+name].data[0]/(q0*1.0e6)
Exemplo n.º 28
0
  #youwant Derived electron_density,electron_ekbar...
  #youwant dist_fn electron_x_px, electron_py_pz, electron_theta_en...
  #if (os.path.isdir('jpg') == False):
  #  os.mkdir('jpg')
  ######### Script code drawing figure ################
  n0=30.0
  R=1.8e-6
  L=15e-6
  Ntot = np.pi*R*R*L*n0*denunit
  V=(1.0/20.0)*(1.0/15.0)*(1.0/15.0)*1.0e-18
  weight = V*denunit*n0/20.0 
#  weight = Ntot/(1200*360*360*50)

  set_relativistic =1 
  for n in np.arange(start,stop+step,step):
      data = sdf.read(from_path+"i_tot_loc"+str(n).zfill(4)+".sdf",dict=True)
      header=data['Header']
      time1=header['time']
      if set_relativistic == 1:
          px = data['Particles/Px/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
          py = data['Particles/Py/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
          pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data/(1836*m0*v0)
          gg = (px**2+py**2+pz**2+1)**0.5
          theta = np.arctan2((py**2+pz**2)**0.5,px)*180.0/np.pi
    
          ek_1 = (gg - 1.0)*0.51*1836
          ww_1 = np.zeros_like(ek_1) + weight
          dist_x1, den1 = pxpy_to_energy(ek_1,ww_1)
    
          ek_2 = (gg[abs(theta)<10.0] - 1.0)*0.51*1836
          ww_2 = np.zeros_like(ek_2) + weight
def processplot(n): 
  ######### Parameter you should set ###########
  #start   =  23  # start time
  #stop    =  30  # end time
  #step    =  1  # the interval or step
  
  youwant = ['Electron_density','Ion_density','Electron_ekbar','Ion_ekbar','ex','ey','bz','ex_averaged','ez_averaged','by_averaged']
  #youwant =  ['ey','ex','ey_averaged','bz','bz_averaged'] #,'electron_en','electron_ekbar','electron_density']
  #youwant.append('Ion_ekbar')
  #youwant.append('positron_ekbar')
  #youwant.append('electron_en')
  #youwant.append('photon_en')
  #youwant field  ex,ey,ez,bx,by,bz,ex_averaged,bx_averaged...
  #youwant Derived electron_density,electron_ekbar...
  #youwant dist_fn electron_x_px...
  
  from_path = './cannon_a190_bulk200/'
  to_path   = './cannon_a190_bulk200/'
  
  
  ######### Script code drawing figure ################
  #for n in range(start,stop+step,step):
  #### header data ####
  #data = sdf.read(from_path+str(n).zfill(4)+".sdf",dict=True)
  #header=data['Header']
  #time=header['time']
  #x  = data['Grid/Grid_mid'].data[0]/1.0e-6
  #y  = data['Grid/Grid_mid'].data[1]/1.0e-6
  #X, Y = np.meshgrid(x, y)
  
  for name in youwant:
    if (name[0:2] == 'ex') or (name[0:2] == 'ey') or (name[0:2] == 'ez'):
              data = sdf.read(from_path+'e_fields'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']
              x  = data['Grid/Grid_mid'].data[0]/1.0e-6
              y  = data['Grid/Grid_mid'].data[2]/1.0e-6
              X, Y = np.meshgrid(x, y)
              eexx = data['Electric Field/'+str.capitalize(name)].data/exunit
              n3d=len(eexx[0,:,0])
              ex = (eexx[:,n3d//2-1,:]+eexx[:,n3d//2,:])/2 
              if np.min(ex.T) == np.max(ex.T):
                  continue
              eee=np.max([-np.min(ex.T),np.max(ex.T)])
              #if (name == 'ex'):
              #    eee = 50
              #elif (name == 'ex_averaged'):
              #    eee = 30
              #elif (name == 'ey') or (name == 'bz'):
              #    eee = 380 
              #elif (name == 'ey_averaged') or (name == 'ez_averaged'):
              #    eee = 30
              levels = np.linspace(-eee, eee, 40)
              plt.contourf(X, Y, ex.T, levels=levels, norm=mcolors.Normalize(vmin=-eee, vmax=eee), cmap=cm.jet)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=[-eee, -eee/2, 0, eee/2, eee])
              cbar.set_label('Normalized electric field',fontdict=font)
              cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=15)        
              plt.xlabel('X [$\mu m$]',fontdict=font)
              plt.ylabel('Z [$\mu m$]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[0:2] == 'bx') or (name[0:2] == 'by') or (name[0:2] == 'bz'):
              data = sdf.read(from_path+'b_fields'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']
              x  = data['Grid/Grid_mid'].data[0]/1.0e-6
              y  = data['Grid/Grid_mid'].data[2]/1.0e-6
              X, Y = np.meshgrid(x, y)
              eexx = data['Magnetic Field/'+str.capitalize(name)].data/bxunit
              n3d=len(eexx[0,:,0])
              ex = (eexx[:,n3d//2-1,:]+eexx[:,n3d//2,:])/2
              if np.min(ex.T) == np.max(ex.T):
                  continue
              eee=np.max([-np.min(ex.T),np.max(ex.T)])
              #if (name == 'ey') or (name == 'bz'):
              #    eee = 380 
              #elif (name == 'by_averaged') or (name == 'bz_averaged'):
              #    eee = 30
              levels = np.linspace(-eee, eee, 40)
              plt.contourf(X, Y, ex.T, levels=levels, norm=mcolors.Normalize(vmin=-eee, vmax=eee), cmap=cm.jet)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=[-eee, -eee/2, 0, eee/2, eee])
              cbar.set_label('Normalized magnetic field',fontdict=font)        
              cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=15)        
              plt.xlabel('X [$\mu m$]',fontdict=font)
              plt.ylabel('Z [$\mu m$]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[-7:] == 'density'):
              data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']
              x  = data['Grid/Grid_mid'].data[0]/1.0e-6
              y  = data['Grid/Grid_mid'].data[2]/1.0e-6
              X, Y = np.meshgrid(x, y)
              ddeen = data['Derived/Number_Density/'+name[0:-8]].data/denunit
              n3d=len(ddeen[0,:,0])
              den = (ddeen[:,n3d//2-1,:]+ddeen[:,n3d//2,:])/2
              if np.min(den.T) == np.max(den.T):
                  continue
              eee=np.max(den.T)
              #if (name == 'Ion_density'):
              #    eee = 200
              #elif (name == 'Electron_density'):
              #    eee = 200
              levels = np.logspace(-1, np.log10(eee), 40) 
              plt.contourf(X, Y, den.T, levels=levels,norm=colors.LogNorm(vmin=0.1, vmax=eee), cmap=cm.nipy_spectral)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=np.logspace(-1, 2, 4))
              cbar.set_label(name+'[$n_c$]', fontdict=font)
              cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=15)        
              plt.xlabel('X [$\mu m$]',fontdict=font)
              plt.ylabel('Z [$\mu m$]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[-5:] == 'ekbar'):
              data = sdf.read(from_path+'ekbar'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']
              x  = data['Grid/Grid_mid'].data[0]/1.0e-6
              y  = data['Grid/Grid_mid'].data[2]/1.0e-6
              X, Y = np.meshgrid(x, y)
              ddeen = data['Derived/EkBar_averaged/'+name[0:-6]].data/(q0*1.0e6)
              n3d=len(ddeen[0,:,:])
              den = (ddeen[:,n3d//2-1,:]+ddeen[:,n3d//2,:])/2
              if np.min(den.T) == np.max(den.T):
                  continue
              eee=np.max(den.T)
              #if (name == 'Ion_ekbar_averaged'):
              #    eee = 400
              #elif name == 'Electron_ekbar_averaged':
              #    eee = 800
              levels = np.logspace(-1, np.log10(eee), 40) 
              plt.contourf(X, Y, den.T, levels=levels,norm=colors.LogNorm(vmin=0.1, vmax=eee), cmap=cm.nipy_spectral)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=np.logspace(-1, 2, 4))
              cbar.set_label(name+'[MeV]', fontdict=font)
              cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=15)        
              plt.xlabel('X [$\mu m$]',fontdict=font)
              plt.ylabel('Z [$\mu m$]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[-4:] == 'x_px'):
              data = sdf.read(from_path+'dist'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']

              den = data['dist_fn/x_px/'+name[0:-5]].data[:,:,0]
              den = np.log(den+1.0)
              if np.min(den.T) == np.max(den.T):
                  continue
              levels = np.linspace(np.min(den.T), np.max(den.T), 40)
              dist_x  = data['Grid/x_px/'+name[0:-5]].data[0]/1.0e-6
              dist_y  = data['Grid/x_px/'+name[0:-5]].data[1]/(m0*v0)
              dist_X, dist_Y = np.meshgrid(dist_x, dist_y)
              plt.contourf(dist_X, dist_Y, den.T, levels=levels, cmap=cm.nipy_spectral)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=np.linspace(np.min(den.T), np.max(den.T), 5))
              cbar.set_label(name+'[$log_{10}(A.U.)$]', fontdict=font)
              plt.xlabel('X [$\mu m$]',fontdict=font)
              plt.ylabel('$P_x$ [$m_ec$]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[-8:] == 'theta_en'):
              denden = data['dist_fn/theta_en/'+name[0:-9]].data[:,:,0]
              den = np.log(denden+1.0)
              if np.min(den.T) == np.max(den.T):
                  continue
              levels = np.linspace(np.min(den.T), np.max(den.T), 40)
              dist_x  = data['Grid/theta_en/'+name[0:-9]].data[0]
              dist_y  = data['Grid/theta_en/'+name[0:-9]].data[1]/(q0*1.0e6)
              dist_X, dist_Y = np.meshgrid(dist_x, dist_y)
              plt.contourf(dist_X, dist_Y, den.T, levels=levels, cmap=cm.nipy_spectral)
              #### manifesting colorbar, changing label and axis properties ####
              cbar=plt.colorbar(ticks=np.linspace(np.min(den.T), np.max(den.T), 5))
              cbar.set_label(name+'[$log_{10}(A.U.)$]', fontdict=font)
              plt.xlabel('$\Psi$ [rad]',fontdict=font)
              plt.ylabel('$Energy$ [MeV]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              plt1 = plt.twinx()
              plt1.plot(dist_x,np.sum(denden,axis=1),'-y',linewidth=2.5)
              #plt1.set_ylabel('Normalized '+name)  
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
    elif (name[-2:] == 'en'):
              data = sdf.read(from_path+'dist'+str(n).zfill(4)+".sdf",dict=True)
              header=data['Header']
              time=header['time']

              den = data['dist_fn/en/'+name[0:-3]].data[:,0,0]
              dist_x  = data['Grid/en/'+name[0:-3]].data[0]/(q0*1.0e6)
              plt.plot(dist_x,den,'-r',linewidth=3)
              #### manifesting colorbar, changing label and axis properties ####
              plt.xlabel('Energy [MeV]',fontdict=font)
              plt.ylabel('dN/dE [A.U.]',fontdict=font)
              plt.xticks(fontsize=20); plt.yticks(fontsize=20);
              plt.yscale('log')
              plt.title(name+' at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
              fig = plt.gcf()
              fig.set_size_inches(12, 7)
              fig.savefig(to_path+'_c'+name+str(n).zfill(4)+'.png',format='png',dpi=100)
              plt.close("all")
  print('finised '+str(round(100.0*(n-start+step)/(stop-start+step),4))+'%')
  return 0
def processplot(n): 
  ######### Parameter you should set ###########
  #start   =  210  # start time
  #stop    =  210  # end time
  #step    =  1  # the interval or step

  
#  youwant = ['electron_x_px','electron_density','electron_en','electron_theta_en','ey'] #,'electron_ekbar']
  #youwant field  ex,ey,ez,bx,by,bz,ex_averaged,bx_averaged...
  #youwant Derived electron_density,electron_ekbar...
  #youwant dist_fn electron_x_px, electron_py_pz, electron_theta_en...
  #if (os.path.isdir('jpg') == False):
  #  os.mkdir('jpg')
    #from_path = './uniform_a190_n30/'
    from_path = './cannon_a190/'
    to_path   = from_path
    ######### Script code drawing figure ################
    #for n in range(start,stop+step,step):
    #### header data ####
    data = sdf.read(from_path+'q'+str(n).zfill(4)+".sdf",dict=True)
    header=data['Header']
    time=header['time']
    x  = data['Grid/Grid_mid'].data[0]/1.0e-6
    print('ok')
    y  = data['Grid/Grid_mid'].data[1]/1.0e-6
    X, Y = np.meshgrid(x, y) 
    
    den = data['Derived/Number_Density/Electron'].data/denunit
    n3d = len(den[0,0,:])
    den = (den[:,:,n3d//2-1]+den[:,:,n3d//2])/2.0
    eee = 50.0
    levels = np.linspace(0, eee, 101)
    den.T[den.T > eee]=eee 

    #gs = gridspec.GridSpec(2, 2, width_ratios=[6, 1], height_ratios=[1, 3])

    
    ax=plt.subplot(1,1,1)
    #axin1 = inset_axes(ax, width='15%', height='5%', loc='upper left',pad=0.2)
    #axin2 = inset_axes(ax, width='15%', height='5%', loc='lower left',pad=0.2)
    #axin1 = inset_axes(ax,width="5%",height="45%",loc='upper right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #axin2 = inset_axes(ax,width="5%",height="45%",loc='lower right', bbox_to_anchor=(1.05, 0., 1, 1), bbox_transform=ax.transAxes, borderpad=0,)
    #### manifesting colorbar, changing label and axis properties ####
    image1=ax.contourf(X, Y, den.T, levels=levels, norm=mcolors.Normalize(vmin=levels.min(), vmax=levels.max()), cmap='pink_r')
    cbar=plt.colorbar(image1,ticks=np.linspace(0.0, eee, 5),orientation="vertical")
    cbar.set_label('$n_e$ [$n_c$]', fontdict=font2)
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        

    name = 'ey'
    data = sdf.read(from_path+'e_fields'+str(n).zfill(4)+".sdf",dict=True)
    ex = data['Electric Field/'+str.capitalize(name)].data/exunit
    ex = (ex[:,:,n3d//2-1]+ex[:,:,n3d//2])/2.0
    eee = 300.0
    levels = np.linspace(-eee, eee, 51)
    ex.T[ex.T < -eee]=-eee
    ex.T[ex.T >  eee]= eee
    image2=ax.contourf(X, Y, ex.T, levels=levels, cmap=cmap_br)
    #### manifesting colorbar, changing label and axis properties ####
    cbar=plt.colorbar(image2,ticks=np.linspace(-eee, eee, 5),orientation="vertical")
    cbar.set_label(r'$E_y\ [m_ec\omega_0/e]$',fontdict=font2)        
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(),fontsize=font2['size'])        
    plt.title('Ey_den_e at '+str(round(time/1.0e-15,6))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = '+str(round(time/1.0e-15,0))+' fs',fontdict=font)
    #ax.text(21.,1.75,'t = 70 fs',fontdict=font)
    
    ax.set_ylim(-8.,8.)
    ax.set_xlim(-5,25)
    ax.set_xlabel('X [$\lambda$]',fontdict=font)
    ax.set_ylabel('Y [$\lambda$]',fontdict=font)
    ax.tick_params(axis='both',labelsize=25) 
    #ax.set_xticklabels(xticklabels,fontdict=font)
    #ax.set_yticklabels(yticklabels,fontdict=font)

#    plt.subplot(gs[0])
#    plt.scatter(ppp_x[abs(ppp_y)<=3.2],ppp_px[abs(ppp_y)<=3.2],s=10,c='green',edgecolors='None',alpha=0.5)
#    plt.xlim(0,30)
#    plt.ylabel('p$_x$ [m$_e$c]', fontdict=font)
#    plt.xticks([])
#    plt.yticks(fontsize=20)
#  
#    plt.subplot(gs[3])
#    plt.scatter(ppp_py[abs(ppp_y)<=3.2],ppp_y[abs(ppp_y)<=3.2],s=10,c='green',edgecolors='None',alpha=0.5)
#    plt.ylim(-6.5,6.5)
#    plt.xlabel('p$_y$ [m$_e$c]', fontdict=font)
#    plt.yticks([])
#    plt.xticks(fontsize=20)
#
#    
#    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.011, hspace=0.051)
#

    #fig=plt.subplot(gs[1])
    #ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.10])
    #ax2 = fig.add_axes([0.05, 0.35, 0.9, 0.10])
    #cmap = mpl.cm.rainbow
    #norm = mpl.colors.Normalize(vmin=0.0, vmax=50)
    #cb1 = mpl.colorbar.ColorbarBase(ax1, cmap='Greys',
    #                            norm=norm,
    #                            orientation='horizontal',ticks=np.linspace(0.00, 50, 6))
    #cb1.set_label('n$_e$ [n$_c$]')
    #cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
    #cmap.set_over('0.25')
    #cmap.set_under('0.75')

    #cmap = mpl.cm.BrBG
    #Bz = 22.5
    #norm = mpl.colors.Normalize(vmin=-abs(Bz), vmax=abs(Bz))
    #cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap_br,
    #                            norm=norm,
    #                            orientation='horizontal',ticks=np.linspace(-abs(Bz), abs(Bz), 5),alpha=0.7)
    #cb2.set_label(r'E$_y$ [m$_e\omega$/e]')
    #cmap = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
    #cmap.set_over('0.25')
    #cmap.set_under('0.75')
    fig = plt.gcf()
    fig.set_size_inches(18, 6.)
    fig.savefig(to_path+'ey_e_density'+str(n).zfill(4)+'.png',format='png',dpi=160)
    plt.close("all")
    return 0
        if not os.path.exists(to_path):
            os.mkdir(to_path)
        n0 = 30.0
        #    n0=float(dir_n[-2:])
        R = 1.8e-6
        L = 15e-6
        Ntot = np.pi * R * R * L * n0 * denunit
        V = (1.0 / 20.0) * (1.0 / 15.0) * (1.0 / 15.0) * 1.0e-18
        ######### Script code drawing figure ################
        for n in range(start, stop + step, step):
            weight = V * denunit * n0 / 50.0
            name = 'ex_averaged'
            if not os.path.exists(from_path + 'e_fields' + str(n).zfill(4) +
                                  ".sdf"):
                continue
            data = sdf.read(from_path + 'e_fields' + str(n).zfill(4) + ".sdf",
                            dict=True)
            header = data['Header']
            time = header['time']
            x = data['Grid/Grid_mid'].data[0] / 1.0e-6
            y = data['Grid/Grid_mid'].data[1] / 1.0e-6
            z = data['Grid/Grid_mid'].data[2] / 1.0e-6

            X, Y, Z = np.meshgrid(x, y, z, sparse=False, indexing='ij')
            RR = (Y**2 + Z**2)**0.5

            eexx = data['Electric Field/' + str.capitalize(name)].data / exunit
            eexx = eexx[:, RR[0, :, :] < 1.5]
            print(eexx.shape)
            n_size = eexx[-1, :].size
            ex = np.sum(eexx, axis=1) / n_size
            np.savetxt(
Exemplo n.º 32
0
import sys
import sdf
import matplotlib.pyplot as plt

fname = "Data/0010.sdf"
varname = "Electric_Field_Ex"

try:
    d = sdf.read(fname)
except:
    print 'File "%s" not found' % fname
    sys.exit()

if not hasattr(d, varname):
    print 'Variable "%s" not found in file' % varname
    sys.exit()

var = d.__dict__[varname]

if len(var.dims) != 2:
    print 'File "%s" is not from a 2D run' % fname
    sys.exit()

iy = var.dims[1] / 2
grid = var.grid_mid
x = grid.data[0]

fig = plt.figure()
plt.plot(x, var.data[:, iy], 'r+-')
plt.xlabel(grid.labels[0] + r' $(' + grid.units[0] + ')$')
plt.ylabel(var.name + r' $(' + var.units + ')$')
def composite_field_plot(varname, vmin=None, vmax=None, directory='Data'):
    global verbose, dpi

    file_list = get_files(wkdir=directory)
    file_list = clean_file_list(file_list, varname)

    file_list.remove(directory + '00000.sdf')
    file_list.remove(directory + '00002.sdf')
    file_list.remove(directory + '00003.sdf')
    file_list.remove(directory + '00004.sdf')
    file_list.remove(directory + '00005.sdf')
    file_list.remove(directory + '00006.sdf')
    file_list.remove(directory + '00007.sdf')
    file_list.remove(directory + '00008.sdf')
    file_list.remove(directory + '00009.sdf')
    file_list.remove(directory + '00010.sdf')
    file_list.remove(directory + '00011.sdf')
    file_list.remove(directory + '00012.sdf')
    file_list.remove(directory + '00013.sdf')
    file_list.remove(directory + '00014.sdf')
    file_list.remove(directory + '00015.sdf')
    file_list.remove(directory + '00016.sdf')
    file_list.remove(directory + '00017.sdf')
    file_list.remove(directory + '00018.sdf')
    file_list.remove(directory + '00019.sdf')
    file_list.remove(directory + '00020.sdf')
    file_list.remove(directory + '00021.sdf')
    file_list.remove(directory + '00022.sdf')
    file_list.remove(directory + '00023.sdf')
    file_list.remove(directory + '00024.sdf')
    file_list.remove(directory + '00025.sdf')
    file_list.remove(directory + '00027.sdf')
    file_list.remove(directory + '00028.sdf')
    file_list.remove(directory + '00029.sdf')
    file_list.remove(directory + '00030.sdf')
    file_list.remove(directory + '00031.sdf')
    file_list.remove(directory + '00032.sdf')
    file_list.remove(directory + '00033.sdf')
    file_list.remove(directory + '00034.sdf')
    file_list.remove(directory + '00035.sdf')
    file_list.remove(directory + '00037.sdf')
    file_list.remove(directory + '00038.sdf')
    file_list.remove(directory + '00039.sdf')
    file_list.remove(directory + '00040.sdf')
    file_list.remove(directory + '00041.sdf')
    file_list.remove(directory + '00042.sdf')
    file_list.remove(directory + '00043.sdf')
    file_list.remove(directory + '00044.sdf')
    file_list.remove(directory + '00045.sdf')
    file_list.remove(directory + '00047.sdf')
    file_list.remove(directory + '00048.sdf')
    file_list.remove(directory + '00049.sdf')
    file_list.remove(directory + '00050.sdf')
    file_list.remove(directory + '00051.sdf')
    file_list.remove(directory + '00052.sdf')
    file_list.remove(directory + '00053.sdf')
    file_list.remove(directory + '00054.sdf')
    file_list.remove(directory + '00055.sdf')

    if verbose > 0:
        print('Found {} files to plot'.format(len(file_list)))

    data = []
    for f in file_list:
        d = sdf.read(f)
        var = d.__dict__[varname]
        data.append(var.data)
    data = np.asarray(data)
    data = data.T

    tmin = sdf.read(file_list[0]).Header['time']
    tmax = sdf.read(file_list[-1]).Header['time']
    grid = var.grid_mid
    xmin = np.min(grid.data[0])
    xmax = np.max(grid.data[0])

    shape = data.shape
    extent = [tmin, tmax, xmax, xmin]

    xmult, xsym = get_si_prefix(xmax - xmin)  # y axis
    tmult, tsym = get_si_prefix(tmax - tmin)  # x axis

    if vmin is None and vmax is None:
        vmin, vmax = get_var_range_from_sdf_files(file_list, varname)
    elif vmin is None:
        vmin = get_var_range_from_sdf_files(file_list, varname)[0]
    elif vmax is None:
        vmax = get_var_range_from_sdf_files(file_list, varname)[1]
    mult, sym = get_si_prefix(vmax - vmin)

    fig, ax = plt.subplots()
    im = ax.imshow(data,
                   extent=extent,
                   aspect=calculate_aspect(shape, extent),
                   interpolation='none',
                   cmap=cm.plasma,
                   vmin=vmin,
                   vmax=vmax)

    ax.xaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * tmult)))
    ax.yaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * xmult)))
    plt.xlabel('t $(' + tsym + 's)$')
    plt.ylabel(grid.labels[0] + ' $(' + xsym + grid.units[0] + ')$')
    # data_label = var.name + ' $(' + sym + var.units + ')$'
    data_label = 'Argon$^{+8}$ Number Density $(' + sym + var.units + ')$'
    plt.title('Electron Density Evolution')

    cbar = fig.colorbar(im,
                        label=data_label,
                        format=FuncFormatter(lambda x, y: x * mult))
    plt.tight_layout()
    plt.savefig('electron_comp_thermal_nocoll.png',
                dpi=600,
                bbox_inches="tight")
Exemplo n.º 34
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)
Exemplo n.º 35
0
def main():
    species = "Electron"
    path = "/scratch/lsa_flux/diiorios/2d_run/"
    fnums = ["0100", "0200", "0400"]
    fname = []
    for n in fnums:
        fname.append(path + n + ".sdf")

    x_axis_num = 0
    y_axis_num = 1
    # z_axis_num = 2

    fig, axarr = plt.subplots(len(fname), sharex=True)#, sharey=True)
    fig.set_facecolor("w")
    # only have a single file to plot, so we so this little hack since
    # axarr does not come out in an array in this case
    if not isinstance(axarr, np.ndarray):
        axarr = np.array([axarr])

    # axarr[0].set_title(species + " files " + str(fnums))
    # axarr[0].set_title('Contribution to E Field')

    limit = 8E9

    for i in range(len(fname)):
        sdfdata = sdf.read(fname[i])

        print(sdfdata.Header['time'])

        e_var_x = sdfdata.Electric_Field_Ex
        e_var_y = sdfdata.Electric_Field_Ey
        x_grid = e_var_x.grid_mid.data[0]
        y_grid = e_var_y.grid_mid.data[1]
        x_grid_cent = e_var_x.grid.data[0]
        y_grid_cent = e_var_y.grid.data[1]

        e_avg, dummy_e_r, dummy_e_t = __radial_average(x_grid, y_grid, e_var_x.data, e_var_y.data)

        dummy_temp_grid_x, temp_data_x = Temp_Field(sdfdata,
                                                    x_axis_num,
                                                    species='Electron')
        dummy_temp_grid_y, temp_data_y = Temp_Field(sdfdata,
                                                    y_axis_num,
                                                    species='Electron')
        temp_avg, dummy_temp_r, dummy_temp_t = __radial_average(x_grid, y_grid,
                                                                temp_data_x,
                                                                temp_data_y)

        dummy_res_mhd_grid_x, res_mhd_data_x = Resistive_MHD_Field(sdfdata,
                                                                   x_axis_num)
        dummy_res_mhd_grid_y, res_mhd_data_y = Resistive_MHD_Field(sdfdata,
                                                                   y_axis_num)
        rmhd_avg, dummy_rmhd_r, dummy_rmhd_t = __radial_average(x_grid, y_grid,
                                                                res_mhd_data_x,
                                                                res_mhd_data_y)

        dummy_hall_grid_x, hall_data_x = Hall_Field(sdfdata, x_axis_num)
        dummy_hall_grid_y, hall_data_y = Hall_Field(sdfdata, y_axis_num)
        hall_avg, dummy_hall_r, dummy_hall_t = __radial_average(x_grid, y_grid, hall_data_x, hall_data_y)

        gen_data_x = Generalized_Ohm(sdfdata,
                                     x_axis_num,
                                     species='Electron')
        gen_data_y = Generalized_Ohm(sdfdata,
                                     y_axis_num,
                                     species='Electron')
        gen_avg, dummy_gen_r, dummy_gen_t = __radial_average(x_grid, y_grid, gen_data_x, gen_data_y)

        gen_avg2 = Generalized_Ohm_radavg(sdfdata,
                                          species='Electron')

        high_order = higher_order(sdfdata, species='Electron')

        cart_high_x = cart_higher_order_x(sdfdata, species='Electron')
        cart_high_y = cart_higher_order_y(sdfdata, species='Electron')
        cart_high_avg, dummy_high_r, dummy_high_t = __radial_average(x_grid_cent, y_grid_cent, cart_high_x, cart_high_y)

        # ideal_mhd_grid_x, ideal_mhd_data_x = Ideal_MHD_Field(sdfdata,
        #                                                      x_axis_num,
        #                                                      species='Electron')
        # ideal_mhd_grid_y, ideal_mhd_data_y = Ideal_MHD_Field(sdfdata,
        #                                                      y_axis_num,
        #                                                      species='Electron')
        # imhd_avg, imhd_r, imhd_t = __radial_average(x_grid, y_grid, ideal_mhd_data_x, ideal_mhd_data_y)


        l1, = axarr[i].plot(#e_r,
                            e_avg,
                            'k-',
                            label='Simulation')
        l2, = axarr[i].plot(#temp_r,
                            np.clip(temp_avg, -limit, limit),
                            'r--',
                            label='Pressure Tensor Gradient')
        # l3, = axarr[i].plot(#rmhd_r,
        #                     np.clip(rmhd_avg, -limit, limit),
        #                     'b-.',
        #                     label='Resistive MHD')
        # l4, = axarr[i].plot(#hall_r,
        #                     np.clip(hall_avg, -limit, limit),
        #                     'g:',
        #                     label='Hall Term')
        # l5, = axarr[i].plot(#imhd_r,
        #                    np.clip(imhd_avg,
        #                            -limit, limit),
        #                    'm-.',
        #                    label='Ideal MHD Term')
        # l6, = axarr[i].plot(np.clip(gen_avg, -limit, limit),
        #                     'm-.',
        #                     label='Generalized Ohm',
        #                     alpha=0.2)
        l7, = axarr[i].plot(np.clip(gen_avg2, -limit, limit),
                            'b-.',
                            label='Ohm Law 1st Term')
        l8, = axarr[i].plot(np.clip(high_order, -limit, limit),
                            'g:',
                            label='Ohm Law 2nd Term')
        # l9, = axarr[i].plot(np.clip(cart_high_avg, -limit, limit),
        #                     'b:',
        #                     label='Cart Higher Order')

    ls = [l1, l2, l7, l8]  #l3, l4, l5]
    labels = [l.get_label() for l in ls]
    lgd = fig.legend(ls, labels, bbox_to_anchor=(1.05, 1.0), loc=1)
    fig.subplots_adjust(hspace=0)
    plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
    # plt.xlim(-6.5e-6, 6.5e-6)
    # plt.ylim(-limit, limit)

    # xmult, xsym = get_si_prefix(np.max(e_r) - np.min(e_r))
    ymult, ysym = get_si_prefix(limit - (-limit))
    # axarr[0].xaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * xmult)))
    axarr[0].yaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * ymult)))
    axarr[1].yaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * ymult)))
    axarr[2].yaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * ymult)))

    axarr[0].set_ylim([-limit, limit])
    axarr[1].set_ylim([-limit, limit])
    axarr[2].set_ylim([-limit, limit])

    xmult, xsym = get_si_prefix(dummy_e_r.max() - dummy_e_r.min())
    # axarr[2].xaxis.set_major_formatter(FuncFormatter(lambda x, y: (x * xmult)))
    # axarr[2].set_xlim([dummy_e_r.min(), dummy_e_r.max()])
    plt.xlabel('r' + ' $(' + xsym + 'm)$')

    axarr[1].set_ylabel('$E_{r}$ $(' + ysym + 'V/m)$')
    # plt.show()

    axarr[0].get_yaxis().set_tick_params(direction='in')
    axarr[1].get_yaxis().set_tick_params(direction='in')
    axarr[2].get_yaxis().set_tick_params(direction='in')
    axarr[2].get_xaxis().set_tick_params(direction='in')

    plt.savefig('ohm_rad.png', dpi=600, bbox_extra_artists=(lgd,), bbox_inches = "tight", pad_inches=0.2)
    plt.close(fig)
Exemplo n.º 36
0
def sdfr(filename):
    return sdf.read(filename)
Exemplo n.º 37
0
import numpy as np
import matplotlib.pyplot as plt
import sdf
plt.switch_backend('agg')
x = 18000
sdfdir = "../Data/acceleration/"
savefigdir = "./acceleration/fig/" + str(x)
data = sdf.read(sdfdir + str(x) + ".sdf", dict=True)
data
Bz = data['Magnetic Field/Bz']
bz = Bz.data
density = data['Derived/Number_Density/electron'].data
bz = bz.T
dengsity = density.T
fig, ax = plt.subplots()
fig2, ax2 = plt.subplots()
im = ax.pcolormesh(bz, cmap=plt.get_cmap('rainbow'))
im2 = ax2.pcolormesh(density, cmap=plt.get_cmap('gray'))
fig.savefig(savefigdir + "bz.png", dpi=200)

fig2.savefig(savefigdir + "density.png", dpi=200)
    grid_x = grid_x[np.in1d(temp_id, part13_id)]
    grid_z = grid_z[np.in1d(temp_id, part13_id)]
    plt.scatter(grid_x,
                grid_z,
                c='lime',
                s=0.03,
                edgecolors='None',
                alpha=0.8,
                zorder=2)


if __name__ == '__main__':
    from_path = './cannon_a190_v484/'
    to_path = './cannon_a190_v484_fig/'
    ######### Script code drawing figure ################
    data = sdf.read(from_path + "i_tot_loc0027.sdf", dict=True)
    px = data['Particles/Px/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    py = data['Particles/Py/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    theta = np.arctan2((py**2 + pz**2)**0.5, px) * 180.0 / np.pi
    gg = (px**2 + py**2 + pz**2 + 1)**0.5
    Ek = (gg - 1) * 1836 * 0.51
    part13_id = data['Particles/ID/subset_Only_Ions0/Ion'].data
    part13_id = part13_id[(Ek > 220) & (abs(theta) < 10) & (Ek < 240)]
    print('part13_id size is ', part13_id.size, ' max ', np.max(part13_id),
          ' min ', np.min(part13_id))

    plt.subplot(1, 1, 1)
    one_procedure(n=17)
    #         plt.contour(X, Z, den_e.T,levels=[30.0], colors='white', linewidths=2.,origin='lower')
    plt.xlim(8, 24)
Exemplo n.º 39
0
def processplot(n):

    to_path = './cannon_a190_bulk200/'
    from_path = './cannon_a190_bulk200/'

    data = sdf.read(from_path + "i_tot_loc0027.sdf", dict=True)
    #grid_x = data['Grid/Particles/subset_high_e/electron'].data[0]/wavelength
    px = data['Particles/Px/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    py = data['Particles/Py/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    theta = np.arctan2((py**2 + pz**2)**0.5, px) * 180.0 / np.pi
    gg = (px**2 + py**2 + pz**2 + 1)**0.5
    Ek = (gg - 1) * 1836 * 0.51

    part13_id = data['Particles/ID/subset_Only_Ions0/Ion'].data
    part13_id = part13_id[(Ek > 225) & (abs(theta) < 10) & (Ek < 245)]

    #choice = np.random.choice(range(part13_id.size), 20000, replace=False)
    #part13_id = part13_id[choice]
    print('part13_id size is ', part13_id.size, ' max ', np.max(part13_id),
          ' min ', np.min(part13_id))

    ######### Script code drawing figure ################
    #for n in range(start,stop+step,step):
    #### header data ####
    #data = sdf.read(from_path+str(n).zfill(4)+".sdf",dict=True)
    #header=data['Header']
    #time=header['time']
    #x  = data['Grid/Grid_mid'].data[0]/1.0e-6
    #y  = data['Grid/Grid_mid'].data[1]/1.0e-6
    #X, Y = np.meshgrid(x, y)

    data = sdf.read(from_path + "i_tot_loc" + str(n).zfill(4) + ".sdf",
                    dict=True)
    header = data['Header']
    time1 = header['time']
    px = data['Particles/Px/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    py = data['Particles/Py/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    pz = data['Particles/Pz/subset_Only_Ions0/Ion'].data / (1836 * m0 * v0)
    gg = (px**2 + py**2 + pz**2 + 1)**0.5
    theta = np.arctan2((py**2 + pz**2)**0.5, px) * 180.0 / np.pi

    grid_x = data['Grid/Particles/subset_Only_Ions0/Ion'].data[0] / 1.0e-6
    temp_id = data['Particles/ID/subset_Only_Ions0/Ion'].data

    px = px[theta < 20]
    grid_x = grid_x[theta < 20]
    theta = theta[theta < 20]

    if np.size(px) == 0:
        return 0
    theta[theta < -20] = -20
    theta[theta > 20] = 20

    color_index = abs(theta)

    fig, host = plt.subplots()
    #    plt.subplot()
    plt.scatter(grid_x,
                px,
                c=color_index,
                s=0.03,
                cmap='rainbow_r',
                edgecolors='None',
                alpha=0.66)
    cbar = plt.colorbar(ticks=np.linspace(np.min(color_index),
                                          np.max(color_index), 5),
                        pad=0.01)
    cbar.ax.set_yticklabels(cbar.ax.get_yticklabels(), fontsize=20)
    cbar.set_label(r'$|\theta|$' + ' [degree]', fontdict=font)

    #plt.plot(np.linspace(-500,900,1001), np.zeros([1001]),':k',linewidth=2.5)
    #plt.plot(np.zeros([1001]), np.linspace(-500,900,1001),':k',linewidth=2.5)
    #plt.plot(np.linspace(-500,900,1001), np.linspace(-500,900,1001),'-g',linewidth=3)
    #plt.plot(np.linspace(-500,900,1001), 200-np.linspace(-500,900,1001),'-',color='grey',linewidth=3)
    #   plt.legend(loc='upper right')
    plt.xlim(-5, 55)
    plt.ylim(0., 1.6)
    plt.xlabel('X [$\mu m$]', fontdict=font)
    plt.ylabel('$p_x$ [m$_i$c$^2$]', fontdict=font)
    plt.xticks(fontsize=20)
    plt.yticks(fontsize=20)
    #  plt.text(-100,650,' t = '++' fs',fontdict=font)
    plt.subplots_adjust(left=0.16,
                        bottom=None,
                        right=0.97,
                        top=None,
                        wspace=None,
                        hspace=None)
    plt.title('At ' + str(round(time1 / 1.0e-15, 2)) + ' fs', fontdict=font)
    #plt.show()
    #lt.figure(figsize=(100,100))

    par1 = host.twinx()
    par2 = host.twinx()
    par3 = host.twinx()

    par2.spines["right"].set_position(("axes", 1.05))
    make_patch_spines_invisible(par2)
    par2.spines["right"].set_visible(True)

    par3.spines["right"].set_position(("axes", 1.1))
    make_patch_spines_invisible(par3)
    par3.spines["right"].set_visible(True)

    tkw = dict(size=20, width=1.)

    x = np.loadtxt(from_path + 'ex_lineout_x.txt')
    ex = np.loadtxt(from_path + 'ex_lineout_r15_' + str(n).zfill(4) + '.txt')
    p1, = par1.plot(x, ex, "-k", label="Ex")
    par1.set_ylabel(r'$E_x\ [m_ec\omega/|e|]$')
    par1.yaxis.label.set_color(p1.get_color())
    par1.tick_params(axis='y', colors=p1.get_color(), **tkw)
    par1.set_ylim(-10, 15)

    x = np.loadtxt(from_path + 'eden_lineout_x.txt')
    eden = np.loadtxt(from_path + 'eden_lineout_r15_' + str(n).zfill(4) +
                      '.txt')  #*exunit/denunit
    p2, = par2.plot(x, eden, "-b", label="Electron")
    par2.set_ylabel('$n_e\ [n_c]$')
    par2.yaxis.label.set_color(p2.get_color())
    par2.tick_params(axis='y', colors=p2.get_color(), **tkw)
    par2.set_ylim(0, 30)

    x = np.loadtxt(from_path + 'iden_lineout_x.txt')
    iden = np.loadtxt(from_path + 'iden_lineout_r15_' + str(n).zfill(4) +
                      '.txt')  #*exunit/denunit
    p3, = par3.plot(x, iden, "-r", label="Ion")
    par3.set_ylabel('$n_i\ [n_c]$')
    par3.yaxis.label.set_color(p3.get_color())
    par3.tick_params(axis='y', colors=p3.get_color(), **tkw)
    par3.set_ylim(0, 30)

    fig = plt.gcf()
    fig.set_size_inches(12, 7.5)
    fig.savefig(to_path + 'r15_comb_proton' + str(n).zfill(4) + '.png',
                format='png',
                dpi=80)
    plt.close("all")
    print('finised ' + str(n).zfill(4))
    return 0