예제 #1
0
    def plot_r_z_plane(self):

        fig = plt.figure()
        cax = plt.pcolormesh(self.zeta_array,
                             self.r_array,
                             self.r_z_slice,
                             cmap=plt.get_cmap('magma'))

        cbar = fig.colorbar(cax)
        cbar.ax.set_ylabel(r'$\rho$', fontsize=14)

        ax = plt.gca()
        ax.set_ylabel(r'$k_p r$', fontsize=14)
        ax.set_xlabel(r'$k_p \zeta$', fontsize=14)

        filesuffix = '_t_%06.f' % (np.floor(self.g3d.get_time()))
        fileprefix = 'plasma_charge'
        saveformat = 'png'
        savepath = self.args.savepath

        mkdirs_if_nexist(savepath)

        savename = fileprefix + filesuffix + '.' + saveformat

        fig.savefig(savepath + '/' + savename, format=saveformat, dpi=600)
        plt.close(fig)

        if self.args.verbose:
            print('Saved "' + savename + '" at: ' + self.args.savepath)
예제 #2
0
    def plot_rb(self):

        fig = plt.figure()
        plt.plot(self.zeta_array, self.rb)
        plt.plot(self.zeta_array, self.rb_maxrho)

        ax = plt.gca()
        ax.set_ylabel(r'$k_p r_b$', fontsize=14)
        ax.set_xlabel(r'$k_p \zeta$', fontsize=14)
        ax.legend([r'$r_b$ from zero crossing', r'$r_b$ from global maximum'])

        filesuffix = '_t_%06.f' % (np.floor(self.g3d.get_time()))
        fileprefix = 'plasma_charge_rb'
        saveformat = 'eps'
        savepath = self.args.savepath

        mkdirs_if_nexist(savepath)

        savename = fileprefix + filesuffix + '.' + saveformat

        fig.savefig(savepath + '/' + savename, format=saveformat)

        if self.args.h5plot:
            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(ax)
            h5lp.write(savepath + '/' + fileprefix + filesuffix + '.h5')

        if self.args.verbose:
            print('Saved "' + savename + '" at: ' + self.args.savepath)
        plt.close(fig)
예제 #3
0
def main():

    parser = ps_parseopts()

    args = parser.parse_args()

    file = args.path

    slm = SliceMoms()
    slm.read(file)

    if slm.get_h5order(file) > 0:
        if args.mom_order != None:
            mom_order = args.mom_order
        else:
            mom_order = slm.get_h5order(file)
    else:
        print('Error:\tMoment order in file <= 0!')
        sys.exit(1)                 

    if args.zeta_range != None:
        slm.truncate_zeta_region(args.zeta_range[0], args.zeta_range[1])

    slm.shift_time(args.time_offset)

    mkdirs_if_nexist(args.savepath)

    if args.latexon:
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif') 

    plot_curr_profile(slm, args.savepath, time = args.time, h5plot=args.h5plot)

    plot_save_slice_ene(slm, args.savepath, h5plot=args.h5plot)

    plot_save_slice_centroids(slm, args.savepath, h5plot=args.h5plot, zeta_pos=args.zeta_pos)
    
    plot_save_slice_ene_spread(slm, args.savepath, h5plot=args.h5plot, zeta_pos=args.zeta_pos)
    
    if mom_order > 1:
        plot_save_slice_rms(slm, args.savepath)
        plot_save_proj_rms( slm, \
                            args.savepath, \
                            axdir=args.axis, \
                            h5plot=args.h5plot,\
                            versus_gamma=args.versus_gamma)        
        plot_save_slice_rms_lines(slm, args.savepath, time = args.time, axdir=args.axis, h5plot=args.h5plot)
        plot_save_ene_ene_spread(slm, args.savepath, t_is_z=args.t_is_z)

    if slm.get_if_xterms():
        plot_xterms(slm, args.savepath, time = args.time, h5plot=args.h5plot)

    if mom_order > 3:
        plot_save_slice_exkurtosis_lines(slm, args.savepath, time = args.time, axdir=args.axis, h5plot=args.h5plot)
        plot_save_slice_quad_corr_lines(slm, args.savepath, time = args.time, axdir=args.axis, h5plot=args.h5plot)
예제 #4
0
def saveas_png(fig, savepath, savename, verbose=True, dpi=600):

    fformat = 'png'
    if savepath != None:
        mkdirs_if_nexist(savepath)
        fig.savefig(savepath + '/' + savename + '.' + fformat,
                    format=fformat,
                    dpi=dpi)

        if verbose:
            sys.stdout.write('Saved "%s.%s" at: %s/\n' %
                             (savename, fformat, savepath))
            sys.stdout.flush()
예제 #5
0
    def plot_r_lines(self):

        if not hasattr(self, 'r_z_slice_model'):
            self.gen_model_sheath()

        z_inds = np.int16(np.linspace(0, self.Nzeta - 1, 10))

        fig = plt.figure()
        for z_ind in z_inds:
            p = plt.plot(self.r_array, self.r_z_slice[:, z_ind])
            plt.plot(self.r_array,
                     self.r_z_slice_model[:, z_ind],
                     color=p[0].get_color(),
                     linestyle='--')
            plt.plot(self.r_array,
                     self.r_z_slice_model_flocmax[:, z_ind],
                     color=p[0].get_color(),
                     linestyle='-.')

        ax = plt.gca()
        ax.set_ylabel(r'$\rho$', fontsize=14)
        ax.set_xlabel(r'$k_p r$', fontsize=14)

        filesuffix = '_t_%06.f' % (np.floor(self.g3d.get_time()))
        fileprefix = 'plasma_charge_r'
        saveformat = 'eps'
        savepath = self.args.savepath

        mkdirs_if_nexist(savepath)

        savename = fileprefix + filesuffix + '.' + saveformat

        fig.savefig(savepath + '/' + savename, format=saveformat)
        plt.close(fig)

        if self.args.h5plot:
            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(ax)
            h5lp.write(savepath + '/' + fileprefix + filesuffix + '.h5')

        if self.args.verbose:
            print('Saved "' + savename + '" at: ' + self.args.savepath)
예제 #6
0
def saveas_eps_pdf(fig,
                   savepath,
                   savename,
                   h5plot=True,
                   verbose=True,
                   fformat='pdf',
                   transparent=True):

    fformat_list = ['eps', 'pdf']

    if fformat not in fformat_list:
        print("Error: fformat must be one of: " + fformat_list)

    if savepath != None:
        if savepath == '':
            savepath = '.'
        else:
            mkdirs_if_nexist(savepath)
        fig.savefig(savepath + '/' + savename + '.' + fformat,
                    format=fformat,
                    transparent=transparent)

        if verbose:
            sys.stdout.write('Saved "%s.%s" at: %s/\n' %
                             (savename, fformat, savepath))
            sys.stdout.flush()

        if h5plot:
            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(plt.gca())
            h5lp.write(savepath + '/' + savename + '.h5')

            if verbose:
                sys.stdout.write('Saved "%s.h5" at: %s/\n' %
                                 (savename, savepath))
                sys.stdout.flush()
예제 #7
0
def calc_transversal_probability_density(r_max, nx, nb, ni, rbunch, lbunch):
    ELECTRON_CHARGE_IN_COUL = 1.60217657e-19
    ELECTRON_MASS_IN_KG = 9.10938291e-31
    VAC_PERMIT_FARAD_PER_M = 8.854187817e-12
    SPEED_OF_LIGHT_IN_M_PER_S = 299792458
    omega_alpha = 4.13e16
    # [s^-1]
    E_alpha = 5.1e11
    # [V/m]
    elec_density = 1e+23  # [1/m^3]
    omega_p = np.sqrt(4 * np.pi * elec_density * (ELECTRON_CHARGE_IN_COUL**2) /
                      (VAC_PERMIT_FARAD_PER_M * ELECTRON_MASS_IN_KG))
    E_0 = omega_p * ELECTRON_MASS_IN_KG * SPEED_OF_LIGHT_IN_M_PER_S / ELECTRON_CHARGE_IN_COUL
    #Use zeta array in order to calculate delta t

    savepath = './plots/g3d-line/'
    mkdirs_if_nexist(savepath)

    bunch_array = np.arange(0, lbunch + lbunch / 10, lbunch / 10)
    bunch_array_sum = np.cumsum(bunch_array)

    deltat = np.abs(bunch_array_sum) / omega_p

    vcalc_ion_rate = np.vectorize(calc_ion_rate)

    r_array = np.arange(0, r_max + r_max / nx, r_max / nx)

    c1prime = -1 / 2 * nb
    c3prime = -1 / 2 * rbunch**2 * (nb)

    savename = 'Ex_analytic'

    E = np.zeros(shape=np.shape(r_array))
    for i in range(len(r_array)):
        if (r_array[i] <= rbunch):
            E[i] = np.real(c1prime) * r_array[i]
        else:
            E[i] = np.real(c3prime) / r_array[i]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(np.append(-r_array[::-1], r_array), np.append(-(E[::-1]), E[:]))
    x, Ex = plot_hipace_Ex(-0.2)  # input = zeta pos
    ax.plot(x, Ex)

    h5lp = H5Plot()
    h5lp.inherit_matplotlib_line_plots(ax)
    h5lp.write(savepath + '/' + savename + '.h5')
    plt.show()
    #use zeta array for shaping the elctric field to get the same spacing etc.
    #print(Earray)

    ionization_rate = np.zeros(shape=np.shape(r_array))
    ionization_rate[:] = vcalc_ion_rate(E * E_0, 1, 13.659843449, 13.659843449,
                                        0, 0)  # complete formulae for hydrogen
    #print(ionization_rate[1])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    #print('Deltat is %0.3e' %deltat)
    #computing the ionization probability

    savename = 'ion_probability_test'
    ion_probability = np.zeros(shape=(len(bunch_array) - 1,
                                      len(ionization_rate)))
    for i in range(1, 2):  #len(bunch_array)):
        ion_probability[i -
                        1, :] = 1.0 - np.exp(-ionization_rate[:] * deltat[i])
        ax.plot(np.append(-r_array[::-1], r_array),
                np.append((ion_probability[i - 1, ::-1]),
                          ion_probability[i - 1, :]),
                label=('prob at lb: ' +
                       str(np.around(bunch_array[i], decimals=1))))
        #ax.legend()

    h5lp = H5Plot()
    h5lp.inherit_matplotlib_line_plots(ax)
    h5lp.write(savepath + '/' + savename + '.h5')
    plt.show()
예제 #8
0
    def plot_deltarho_rhomax_sheathcharge(self):

        if not hasattr(self, 'rb'):
            self.calc_rb()

        if not hasattr(self, 'rho_max'):
            self.calc_deltarho_rhomax_sheathcharge()

        fig_charge = plt.figure()
        plt.plot(self.zeta_array, self.charge)
        ax_charge = plt.gca()
        ax_charge.set_ylabel(r'$\lambda=\int_{r_b}^\infty r \rho(r) dr$',
                             fontsize=14)
        ax_charge.set_xlabel(r'$k_p \zeta$', fontsize=14)
        charge_fileprefix = 'charge'

        fig_rhomax = plt.figure()
        plt.plot(self.zeta_array, self.rho_max)
        plt.plot(self.zeta_array, self.rho_flocmax)
        ax_rhomax = plt.gca()
        ax_rhomax.legend(
            [r'using global maximum', r'using first local maximum'])
        ax_rhomax.set_ylabel(r'$\rho_\mathrm{max}$', fontsize=14)
        ax_rhomax.set_xlabel(r'$k_p \zeta$', fontsize=14)
        rhomax_fileprefix = 'rho_max'

        fig_deltarho = plt.figure()
        plt.plot(self.zeta_array, self.delta_rho)
        plt.plot(self.zeta_array, self.delta_rho_flocmax)
        ax_deltarho = plt.gca()
        ax_deltarho.legend(
            [r'using global maximum', r'using first local maximum'])
        ax_deltarho.set_ylabel(r'$\Delta_\rho$', fontsize=14)
        ax_deltarho.set_xlabel(r'$k_p \zeta$', fontsize=14)
        deltarho_fileprefix = 'delta_rho'

        filesuffix = '_t_%06.f' % (np.floor(self.g3d.get_time()))
        saveformat = 'eps'
        savepath = self.args.savepath

        mkdirs_if_nexist(savepath)

        charge_savename = charge_fileprefix + filesuffix + '.' + saveformat
        rhomax_savename = rhomax_fileprefix + filesuffix + '.' + saveformat
        deltarho_savename = deltarho_fileprefix + filesuffix + '.' + saveformat

        fig_charge.savefig(savepath + '/' + charge_savename, format=saveformat)
        if self.args.verbose:
            print('Saved "' + charge_savename + '" at: ' + self.args.savepath)

        fig_rhomax.savefig(savepath + '/' + rhomax_savename, format=saveformat)
        if self.args.verbose:
            print('Saved "' + rhomax_savename + '" at: ' + self.args.savepath)

        fig_deltarho.savefig(savepath + '/' + deltarho_savename,
                             format=saveformat)
        if self.args.verbose:
            print('Saved "' + deltarho_savename + '" at: ' +
                  self.args.savepath)

        if self.args.h5plot:
            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(ax_charge)
            h5lp.write(savepath + '/' + charge_fileprefix + filesuffix + '.h5')

            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(ax_rhomax)
            h5lp.write(savepath + '/' + rhomax_fileprefix + filesuffix + '.h5')

            h5lp = H5Plot()
            h5lp.inherit_matplotlib_line_plots(ax_deltarho)
            h5lp.write(savepath + '/' + deltarho_fileprefix + filesuffix +
                       '.h5')

        plt.show()
예제 #9
0
def main():

    parser = binSlab_parser() 
    args = parser.parse_args()

    # NHC=2
    slice_suffix_str = '_sl_'


    # grid_info = np.zeros((3, 3))
    
    # with open(args.outsumfile, 'r') as csvfile:
    #     csvread = csv.reader(csvfile, delimiter='\t')
    #     i=0
    #     for line in csvread:
    #         if (i<3):
    #             for j in range(len(line)):
    #                 grid_info[i,j] = float(line[j])
    #         i += 1        

    # print(grid_info)

    # Nx = int(grid_info[1,2])
    # Ny = int(grid_info[2,2])

    # dx=(grid_info[1,1] - grid_info[1,0]) / (Nx - 1) # Check this!!!!
    # dy=(grid_info[2,1] - grid_info[2,0]) / (Ny - 1) # Check this!!!!

    # Nx_incl_halo = Nx + 2*NHC;
    # Ny_incl_halo = Ny + 2*NHC;


    for filepath in args.path:

        # if args.nohalo:
        #     nhc = 0
        # else:
        #     nhc = NHC

        i_sl = np.int(filepath[(filepath.find(slice_suffix_str)+len(slice_suffix_str)):len(filepath)])

        # IDx = np.int(np.floor(slID/args.partition[2]))
        # IDy = slID - args.partition[2] * IDx

        # ix_start = np.int((Nx * IDx/args.partition[1]))
        # ix_end = np.int((Nx * (IDx+1)/args.partition[1]))

        # iy_start = np.int((Ny * IDy/args.partition[2]))
        # iy_end = np.int((Ny * (IDy+1)/args.partition[2]))

        # my_Nx=np.int(Nx/args.partition[1] + 2*nhc )
        # my_Ny=np.int(Ny/args.partition[2] + 2*nhc )
    
        # my_x_array = np.linspace( grid_info[1,0] + ix_start*dx - nhc*dx, 
        #                           grid_info[1,0] + ix_end*dx + nhc*dx,
        #                           my_Nx)
        # my_y_array = np.linspace( grid_info[2,0] + iy_start*dy - nhc*dy,
        #                           grid_info[2,0] + iy_end*dy + nhc*dy,
        #                           my_Ny)

        if i_sl == 0:

            filepath_base = filepath[0:(filepath.find(slice_suffix_str)+len(slice_suffix_str))]
            Nsl = len(glob.glob(filepath_base + '*'))

            array = np.empty(0)
            for i in range(0,Nsl):
                filepath_slice = '%s%04d' % (filepath_base, i )
                print('Reading: %s' % filepath_slice)
                array = np.append(array,np.fromfile(filepath_slice,dtype=np.float32))

            fig = plt.figure()
            cax = plt.plot( array)

            ax = plt.gca()
            ax.set_ylabel(r'$\eta (\zeta)$', fontsize=14)
            ax.set_xlabel(r'$k_p \zeta$', fontsize=14)

            if args.ifshow:
              plt.show()

            head, savename = os.path.split(filepath)

            mkdirs_if_nexist(args.savepath)

            print('Saving: ' + args.savepath + '/' + savename + '.eps')

            fig.savefig( args.savepath + '/' + savename + '.eps',
                    format='eps')
            plt.close(fig) 
예제 #10
0
def density_inversion(r_nb,
                      nb,
                      r_psi,
                      psi,
                      zeta_pos,
                      savepath='./plots/equilib',
                      ifplot=True):

    psi_norm = psi - psi[0]

    psi_interp = np.interp(r_nb, r_psi, psi_norm)
    dnb = np.diff(nb)
    dpsi = np.diff(psi_interp)

    x = psi_interp[1:]
    F = -1 * np.divide(dnb, dpsi) / (2 * math.pi)

    popt, pcov = curve_fit(exp_func, x, F)

    if ifplot:
        mkdirs_if_nexist(savepath)

        fig = plt.figure()
        plt.plot(r_nb, nb)
        ax = plt.gca()
        ax.set_xlabel(r'$k_p r$', fontsize=14)
        ax.set_ylabel(r'$n_b/n_0$', fontsize=14)
        saveas_eps_pdf(fig, savepath, 'nb_zeta_%0.2f' % zeta_pos)
        plt.close(fig)

        fig = plt.figure()
        plt.plot(r_nb[:-1], np.divide(dnb, np.diff(r_nb)))
        ax = plt.gca()
        ax.set_xlabel(r'$k_p r$', fontsize=14)
        ax.set_ylabel(r'$d(n_b/n_0)/(k_p dr)$', fontsize=14)
        saveas_eps_pdf(fig, savepath, 'dnb_dr_zeta_%0.2f' % zeta_pos)
        plt.close(fig)

        fig = plt.figure()
        plt.plot(r_nb[:-1], np.divide(dpsi, np.diff(r_nb)))
        ax = plt.gca()
        ax.set_xlabel(r'$k_p r$', fontsize=14)
        ax.set_ylabel(r'$d(e\psi/mc^2)/(k_p dr)$', fontsize=14)
        saveas_eps_pdf(fig, savepath, 'dpsi_dr_zeta_%0.2f' % zeta_pos)
        plt.close(fig)

        fig = plt.figure()
        plt.plot(psi_norm, r_nb)
        ax = plt.gca()
        ax.set_ylabel(r'$k_p r$', fontsize=14)
        ax.set_xlabel(r'$e\psi/mc^2$', fontsize=14)
        saveas_eps_pdf(fig, savepath, 'r_vs_psi_zeta_%0.2f' % zeta_pos)
        plt.close(fig)

        fig = plt.figure()
        plt.plot(r_nb, psi_norm)
        ax = plt.gca()
        ax.set_xlabel(r'$k_p r$', fontsize=14)
        ax.set_ylabel(r'$e\psi/mc^2$', fontsize=14)
        saveas_eps_pdf(fig, savepath, 'psi_zeta_%0.2f' % zeta_pos)
        plt.close(fig)

        fig = plt.figure()
        plt.plot(x, F, '-', label=r'F(x)')
        plt.plot(x,
                 exp_func(x, *popt),
                 '--',
                 label=r'fit: $%0.2f \cdot exp(-%0.2f \cdot x)$' % tuple(popt))
        ax = plt.gca()
        ax.set_xlabel(r'$x$', fontsize=14)
        ax.set_ylabel(r'$F$', fontsize=14)
        plt.legend(frameon=False)
        saveas_eps_pdf(fig, savepath, 'F_zeta_%0.2f' % zeta_pos)
        plt.close(fig)
    return x, F
예제 #11
0
def main():

    basic_cols = ['#75b765', '#808080', '#ffd700']
    basic_cols = ['#2020ff', '#808080', '#ff2020']
    basic_cols = ['#0000ff', '#00ffff', '#808080', '#ffff00', '#ff0000']
    my_cmap = LinearSegmentedColormap.from_list('mycmap', basic_cols)

    parser = binSlab_parser()
    args = parser.parse_args()

    modnum = args.modlines

    # NHC=2
    proc_suffix_str = '_proc_'
    ppart_track_str = 'ppart_track'
    bin_fending = '.bin'

    for filepath in args.path:

        filename = ''
        slash = '/'
        if slash in filepath:
            dirname, filename = filepath.split('/')
        else:
            dirname = filepath

        array = np.empty(0)
        for files in os.listdir(dirname):
            if filename != '':
                if filename in files:
                    print('Reading: %s/%s' % (dirname, files))
                    filepath = dirname + slash + files
                    array = np.append(array,
                                      np.fromfile(filepath, dtype=np.float32))
            else:
                print('Reading: %s/%s' % (dirname, files))
                filepath = dirname + slash + files
                array = np.append(array, np.fromfile(filepath,
                                                     dtype=np.float32))
        ''' reshape the binary data to a matrix with particle
        tag information in each row'''
        array = np.reshape(array, (int(len(array) / 11), 11))
        print(np.shape(array))
        ''' set up figure for 3D plotting '''
        ''' In order to simplify the splitting and plotting, the particle
        information matrix is sorted by the plasma species, the proc tag, then by the particle tag
        and finally by zeta '''
        indizes = np.lexsort((array[:, 5], array[:, 6], array[:, 7], array[:,
                                                                           9]))
        array = array[indizes]
        ''' split by different plasma species types '''
        w = np.split(array, np.where(np.diff(array[:, 9]) != 0)[0] + 1)

        for k in range(len(w)):

            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            ''' get min and max value for universal colorbar later '''

            if args.track_color == "u_tot":
                cmin = min(w[k][:, 8])
                cmax = max(w[k][:, 8])
                chosencmap = cm.jet
            elif args.track_color == "beta_z":
                cmin = -1
                cmax = 1
                chosencmap = my_cmap
            elif args.track_color == "beta_y":
                cmin = -1
                cmax = 1
                chosencmap = my_cmap
            elif args.track_color == "none":
                print('no coloring option selected.')
            else:
                print("This attribute doesn't exist or is not implemented yet")
                break
            ''' Splitting the array into each particle trajectory by proc tag'''
            d = np.split(w[k], np.where(np.diff(w[k][:, 7]) != 0)[0] + 1)

            for i in range(len(d)):
                ''' Splitting the array into each particle trajectory by part tag'''
                e = np.split(d[i], np.where(np.diff(d[i][:, 6]) != 0)[0] + 1)

                number = int(np.floor(len(e) / modnum))
                cmap = plt.get_cmap('jet')
                colors = [cmap(i) for i in np.linspace(0, 1, number)]
                colors2 = [cmap(i) for i in np.linspace(0, 1, 10000)]
                start_segments = np.linspace(args.track_range[0],
                                             args.track_range[1], 10000)

                for j in range(int(np.floor(len(e) / modnum))):
                    x = e[modnum * j][:, 0]
                    y = e[modnum * j][:, 1]
                    z = e[modnum * j][:, 5]

                    if args.track_color == "u_tot":
                        c = e[modnum * j][:, 8]
                    elif args.track_color == "beta_z":
                        c = e[modnum *
                              j][:, 4] / np.sqrt(1 + e[modnum * j][:, 8]**2)
                    elif args.track_color == "beta_y":
                        c = e[modnum *
                              j][:, 2] / np.sqrt(1 + e[modnum * j][:, 8]**2)
                    print("laenge track proc tag %i part tag %i ist %i" %
                          (i, modnum * j, len(z)))

                    if args.track_color == "u_tot":
                        plot_3D_colourline(z, x, y, c, cmin, cmax)
                    elif args.track_color == "beta_z":
                        plot_3D_colourline_beta(z, x, y, c)
                    elif args.track_color == "beta_y":
                        plot_3D_colourline_beta(z, x, y, c)
                    else:
                        plot_3D_colourline(z, x, y, c, cmin, cmax)
            ''' Set colorbar '''
            if args.track_color != "none":
                norm = matplotlib.colors.Normalize(vmin=np.min(cmin),
                                                   vmax=np.max(cmax))

                # choose a colormap
                c_m = chosencmap

                # create a ScalarMappable and initialize a data structure
                s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
                s_m.set_array([])

                cbar = plt.colorbar(s_m)

            else:
                # norm = matplotlib.colors.Normalize( vmin= 0, vmax=6)

                # choose a colormap
                c_m = cm.jet

                # create a ScalarMappable and initialize a data structure
                s_m = matplotlib.cm.ScalarMappable(cmap=c_m)
                s_m.set_array([args.track_range[0], args.track_range[1]])

                cbar = plt.colorbar(s_m)

            if args.track_color == "u_tot":
                cbar.ax.set_title(r'$|u|$', fontsize=18)
            elif args.track_color == "beta_z":
                cbar.ax.set_title(r'$\beta_z$', fontsize=18)
            elif args.track_color == "beta_y":
                cbar.ax.set_title(r'$\beta_y$', fontsize=18)
            else:
                cbar.ax.set_title(r'$k_p\,x_0$', fontsize=18)

                #ax.set_xlim(-8, 0)
            # # ax.set_xlim(0, 300)
            #ax.set_ylim(-1/2, 6)
            if args.xlim:
                ax.set_ylim(args.xlim[0], args.xlim[1])
            if args.ylim:
                ax.set_zlim(args.ylim[0], args.ylim[1])

            ax.set_zlabel(r'$k_p\,y$', fontsize=18)
            ax.set_xlabel(r'$k_p\,\zeta$', fontsize=18)
            ax.set_ylabel(r'$k_p\,x$', fontsize=18)

            plt.show()

            savepath = 'plots/g3d-slice'
            mkdirs_if_nexist(savepath)

            save_path_name = savepath + '/ionized_electron_density_tracked' + '.png'
            print('Saving figure...')
            fig.savefig(save_path_name, format='png', dpi=400)
            print('Writing file...')

            if args.verbose:
                sys.stdout.write('Saved: %s\n' % save_path_name)
                sys.stdout.flush()
            plt.close(fig)
            print('Done!')
예제 #12
0
def main():

    parser = binSlab_parser()
    args = parser.parse_args()

    NHC = 2
    slID_str = 'slID_'

    #cblims = [-1e-1 1e-1];

    grid_info = np.zeros((3, 3))

    with open(args.outsumfile, 'r') as csvfile:
        csvread = csv.reader(csvfile, delimiter='\t')
        i = 0
        for line in csvread:
            if (i < 3):
                for j in range(len(line)):
                    grid_info[i, j] = float(line[j])
            i += 1

    print(grid_info)

    Nx = int(grid_info[1, 2])
    Ny = int(grid_info[2, 2])

    dx = (grid_info[1, 1] - grid_info[1, 0]) / (Nx - 1)  # Check this!!!!
    dy = (grid_info[2, 1] - grid_info[2, 0]) / (Ny - 1)  # Check this!!!!

    Nx_incl_halo = Nx + 2 * NHC
    Ny_incl_halo = Ny + 2 * NHC

    for filepath in args.path:

        if args.nohalo:
            nhc = 0
        else:
            nhc = NHC

        slID = np.int(filepath[(filepath.find(slID_str) +
                                len(slID_str)):len(filepath)])

        IDx = np.int(np.floor(slID / args.partition[2]))
        IDy = slID - args.partition[2] * IDx

        ix_start = np.int((Nx * IDx / args.partition[1]))
        ix_end = np.int((Nx * (IDx + 1) / args.partition[1]))

        iy_start = np.int((Ny * IDy / args.partition[2]))
        iy_end = np.int((Ny * (IDy + 1) / args.partition[2]))

        my_Nx = np.int(Nx / args.partition[1] + 2 * nhc)
        my_Ny = np.int(Ny / args.partition[2] + 2 * nhc)

        my_x_array = np.linspace(grid_info[1, 0] + ix_start * dx - nhc * dx,
                                 grid_info[1, 0] + ix_end * dx + nhc * dx,
                                 my_Nx)
        my_y_array = np.linspace(grid_info[2, 0] + iy_start * dy - nhc * dy,
                                 grid_info[2, 0] + iy_end * dy + nhc * dy,
                                 my_Ny)

        array_flat = np.fromfile(filepath, dtype=np.float32)
        M = np.transpose(array_flat.reshape((my_Nx, my_Ny)))

        cblim = [0.0, 0.0]

        if np.amin(M) < 0 and np.amax(M) > 0:
            cblim[0] = -max(abs(np.amin(M)), np.amax(M))
            cblim[1] = max(abs(np.amin(M)), np.amax(M))
            colormap = cm.BrBG
        elif np.amin(M) < 0 and np.amax(M) <= 0:
            cblim[0] = np.amin(M)
            cblim[1] = 0
            colormap = cm.gist_yarg
        elif np.amin(M) >= 0 and np.amax(M) > 0:
            cblim[0] = 0
            cblim[1] = np.amax(M)
            colormap = cm.gist_gray
        else:
            cblim[0] = np.amin(M)
            cblim[1] = np.amax(M)
            colormap = cm.PuBu

        fig = plt.figure()
        cax = plt.pcolormesh(my_x_array,
                             my_y_array,
                             M,
                             vmin=cblim[0],
                             vmax=cblim[1],
                             cmap=colormap)

        ax = plt.gca()
        ax.set_ylabel(r'$k_p y$', fontsize=14)
        ax.set_xlabel(r'$k_p x$', fontsize=14)
        ax.set_aspect('equal')
        cbar = fig.colorbar(cax)

        if args.ifshow:
            plt.show()

        head, savename = os.path.split(filepath)

        mkdirs_if_nexist(args.savepath)
        fig.savefig(args.savepath + '/' + savename + '.png',
                    format='png',
                    dpi=600)
예제 #13
0
def main():

    basic_cols = ['#75b765', '#808080', '#ffd700']
    basic_cols = ['#2020ff', '#808080', '#ff2020']
    basic_cols = ['#0000ff', '#00ffff', '#808080', '#ffff00', '#ff0000']
    my_cmap = LinearSegmentedColormap.from_list('mycmap', basic_cols)

    parser = binSlab_parser()
    args = parser.parse_args()

    if args.latexfont:
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif')

    modnum = args.modlines
    density_path = args.dens_data

    if not args.tracksoff and not args.track_range:
        print(
            'ERROR: tracks not turned off, but no tracking range given. Provide tracking range with --track_range to get correct colormap.'
        )

    # NHC=2
    proc_suffix_str = '_proc_'
    ppart_track_str = 'ppart_track'
    bin_fending = '.bin'

    for density_files in args.dens_data:

        ionized_density_g3d1 = Grid3d(density_files)
        ionized_density = np.transpose(ionized_density_g3d1.read(x2=0.0))
        print(density_files)
        timestamp = density_files.split("_")[-1].split(".h5")[0]
        if args.old_timestamp:
            timestamp = timestamp.split(".")[0]

        if args.beam_data:
            for beam_density_files in args.beam_data:
                if timestamp in beam_density_files:
                    beam_density_g3d1 = Grid3d(beam_density_files)
                    beam_density = np.transpose(beam_density_g3d1.read(x2=0.0))

        for filepath in args.path:

            filename = ''
            slash = '/'
            if slash in filepath:
                dirname, filename = filepath.split('/')
            else:
                dirname = filepath

            array = np.empty(0)
            for files in os.listdir(dirname):
                if filename != '':
                    if filename in files:
                        if (timestamp in files) or args.manual:
                            print('Reading: %s/%s' % (dirname, files))
                            filepath = dirname + slash + files
                            array = np.append(
                                array, np.fromfile(filepath, dtype=np.float32))
                else:
                    if (timestamp in files) or args.manual:
                        print('Reading: %s/%s' % (dirname, files))
                        filepath = dirname + slash + files
                        array = np.append(
                            array, np.fromfile(filepath, dtype=np.float32))
            ''' reshape the binary data to a matrix with particle
            tag information in each row'''
            array = np.reshape(array, (int(len(array) / 11), 11))
            print(np.shape(array))
            ''' set up figure for 3D plotting '''
            ''' In order to simplify the splitting and plotting, the particle
            information matrix is sorted by the plasma species, the proc tag, then by the particle tag
            and finally by zeta '''
            indizes = np.lexsort(
                (array[:, 5], array[:, 6], array[:, 7], array[:, 9]))
            array = array[indizes]
            ''' split by different plasma species types '''
            w = np.split(array, np.where(np.diff(array[:, 9]) != 0)[0] + 1)

            for k in range(len(w)):

                # if not args.tracksoff and args.dens_data and args.beam_data:
                #     fig = plt.figure(figsize=(9,5))
                # else:
                fig = plt.figure()
                ax = fig.add_subplot(111)
                ''' get min and max value for universal colorbar later '''
                max_density = np.max(np.abs(ionized_density))
                min_density = 0
                if args.clim:
                    levels = MaxNLocator(nbins=512).tick_values(
                        args.clim[0], args.clim[1])
                    max_level = max_density
                    vmin = args.clim[0]
                    vmax = args.clim[1]
                    #selecting correct extend method
                    if min_density < args.clim[0] and max_density > args.clim[
                            1]:
                        extend = 'both'
                    elif min_density < args.clim[
                            0] and max_density <= args.clim[1]:
                        extend = 'min'
                    elif min_density >= args.clim[
                            0] and max_density > args.clim[1]:
                        extend = 'max'
                    elif min_density >= args.clim[
                            0] and max_density <= args.clim[1]:
                        extend = 'neither'
                    else:
                        print(
                            'Error: unexpected case, couldn\'t extend in the correct way!'
                        )
                        extend = 'neither'

                else:
                    levels = MaxNLocator(nbins=512).tick_values(0, max_density)
                    max_level = max_density
                    vmin = min_density
                    vmax = max_density
                    extend = 'neither'
                if args.ptype == 'pcolormesh':
                    plot1 = plt.pcolormesh(ionized_density_g3d1.get_zeta_arr(),
                                           ionized_density_g3d1.get_x_arr(2),
                                           np.abs(ionized_density),
                                           cmap=cm.PuBu,
                                           alpha=1)  #
                elif args.ptype == 'contourf':
                    plot1 = plt.contourf(ionized_density_g3d1.get_zeta_arr(),
                                         ionized_density_g3d1.get_x_arr(2),
                                         np.abs(ionized_density),
                                         cmap=cm.PuBu,
                                         levels=levels,
                                         vmin=vmin,
                                         vmax=vmax,
                                         extend=extend)
                else:
                    print('This type is not implemented yet')

                cbarmap = plt.cm.ScalarMappable(cmap=cm.PuBu)
                cbarmap.set_array(np.abs(ionized_density))
                if args.clim:
                    cbarmap.set_clim(args.clim[0], args.clim[1])
                    cbar1 = plt.colorbar(cbarmap,
                                         boundaries=np.arange(
                                             args.clim[0],
                                             args.clim[1] + 0.0002, 0.0001),
                                         extend=extend,
                                         fraction=0.046,
                                         pad=0.1)
                    ticks = MaxNLocator(5).tick_values(vmin, vmax)
                    cbar1.set_ticks(ticks)
                    plot1.set_clim([args.clim[0], args.clim[1]])

                else:
                    cbarmap.set_clim([0, max_density])
                    cbar1 = plt.colorbar(cbarmap,
                                         boundaries=np.arange(
                                             0, max_density + 0.0002, 0.0001),
                                         extend=extend,
                                         fraction=0.046,
                                         pad=0.1)
                    ticks = MaxNLocator(5).tick_values(vmin, vmax)
                    cbar1.set_ticks(ticks)
                    plot1.set_clim([0, max_density])

                if args.xlim:
                    plt.xlim(args.xlim[0], args.xlim[1])
                if args.ylim:
                    plt.ylim(args.ylim[0], args.ylim[1])

                cbar1.ax.set_title(r'$n_p/n_0$', fontsize=16, pad=args.cbarpad)
                cbar1.ax.tick_params(labelsize=args.axticklabelsize)
                if args.beam_data:
                    max_density = np.max(np.abs(beam_density))

                    cmap = plt.cm.Reds

                    # Get the colormap colors
                    my_cmap = cmap(np.arange(cmap.N))

                    # Set alpha
                    my_cmap[:, -1] = np.linspace(0, 1, cmap.N)
                    # Create new colormap
                    my_cmap = ListedColormap(my_cmap)

                    if args.cblim:
                        levels = MaxNLocator(nbins=512).tick_values(
                            args.cblim[0], args.cblim[1])
                        max_level = max_density
                        vmin = args.cblim[0]
                        vmax = args.cblim[1]
                        #selecting correct extend method
                        if min_density < args.cblim[
                                0] and max_density > args.cblim[1]:
                            extend = 'both'
                        elif min_density < args.cblim[
                                0] and max_density <= args.cblim[1]:
                            extend = 'min'
                        elif min_density >= args.cblim[
                                0] and max_density > args.cblim[1]:
                            extend = 'max'
                        elif min_density >= args.cblim[
                                0] and max_density <= args.cblim[1]:
                            extend = 'neither'
                        else:
                            print(
                                'Error: unexpected case, couldn\'t extend in the correct way!'
                            )
                            extend = 'neither'
                    else:
                        levels = MaxNLocator(nbins=512).tick_values(
                            0, max_density)
                        max_level = max_density
                        vmin = 0
                        vmax = max_density
                        extend = 'neither'
                    if args.ptype == 'pcolormesh':
                        plt.pcolormesh(beam_density_g3d1.get_zeta_arr(),
                                       beam_density_g3d1.get_x_arr(2),
                                       np.abs(beam_density),
                                       cmap=my_cmap,
                                       vmin=vmin,
                                       vmax=vmax)
                    elif args.ptype == 'contourf':
                        plt.contourf(beam_density_g3d1.get_zeta_arr(),
                                     beam_density_g3d1.get_x_arr(2),
                                     np.abs(beam_density),
                                     cmap=my_cmap,
                                     levels=levels,
                                     vmin=vmin,
                                     vmax=vmax,
                                     extend=extend)
                    else:
                        print('This type is not implemented yet')

                    cbarmap = plt.cm.ScalarMappable(cmap=my_cmap)
                    cbarmap.set_array(np.abs(beam_density))
                    if args.cblim:
                        # Note on colorbar: boundaries have to be set manually, because otherwise there will be ugly stripes
                        # afterwards the ticks have to set manually as well, set them at the correct place
                        cbarmap.set_clim(args.cblim[0], args.cblim[1])
                        cbar2 = plt.colorbar(cbarmap,
                                             boundaries=np.arange(
                                                 args.cblim[0],
                                                 args.cblim[1] + 0.0002,
                                                 0.0001),
                                             extend=extend,
                                             fraction=0.046,
                                             pad=0.1)
                        ticks = MaxNLocator(5).tick_values(vmin, vmax)
                        cbar2.set_ticks(ticks)
                        cbar2.set_clim([args.cblim[0], args.cblim[1]])
                    else:
                        #cbarmap.set_clim(0, max_density)
                        cbar2 = plt.colorbar(cbarmap,
                                             boundaries=np.arange(
                                                 0, max_density + 0.0001,
                                                 0.0001),
                                             fraction=0.046,
                                             pad=0.1)
                        ticks = MaxNLocator().tick_values(vmin, vmax)
                        cbar2.set_ticks(ticks)
                        cbar2.set_clim([0, max_density])

                    cbar2.ax.set_title(r'$n_b/n_0$', pad=args.cbarpad)
                    cbar2.ax.tick_params(labelsize=args.axticklabelsize)

                if not args.tracksoff:

                    if args.track_color == "u_tot":
                        cmin = min(w[k][:, 8])
                        cmax = max(w[k][:, 8])
                        chosencmap = cm.jet
                    elif args.track_color == "beta_z":
                        cmin = -1
                        cmax = 1
                        chosencmap = my_cmap
                    elif args.track_color == "beta_y":
                        cmin = -1
                        cmax = 1
                        chosencmap = my_cmap
                    elif args.track_color == "none":
                        print('no coloring option selected.')
                    else:
                        print(
                            "This attribute doesn't exist or is not implemented yet"
                        )
                        break
                    ''' Splitting the array into each particle trajectory by proc tag'''
                    d = np.split(w[k],
                                 np.where(np.diff(w[k][:, 7]) != 0)[0] + 1)

                    for i in range(len(d)):
                        ''' Splitting the array into each particle trajectory by part tag'''
                        e = np.split(d[i],
                                     np.where(np.diff(d[i][:, 6]) != 0)[0] + 1)

                        number = int(np.floor(len(e) / modnum))
                        cmap = plt.get_cmap('jet')
                        colors = [cmap(i) for i in np.linspace(0, 1, number)]
                        colors2 = [cmap(i) for i in np.linspace(0, 1, 10000)]
                        start_segments = np.linspace(args.track_range[0],
                                                     args.track_range[1],
                                                     10000)

                        for j in range(int(np.floor(len(e) / modnum))):
                            x = e[modnum * j][:, 0]
                            y = e[modnum * j][:, 1]
                            z = e[modnum * j][:, 5]

                            if args.track_color == "u_tot":
                                c = e[modnum * j][:, 8]
                            elif args.track_color == "beta_z":
                                c = e[modnum * j][:, 4] / np.sqrt(
                                    1 + e[modnum * j][:, 8]**2)
                            elif args.track_color == "beta_y":
                                c = e[modnum * j][:, 2] / np.sqrt(
                                    1 + e[modnum * j][:, 8]**2)
                            print(
                                "laenge track proc tag %i part tag %i ist %i" %
                                (i, modnum * j, len(z)))

                            if args.track_color == "u_tot":
                                plot_2D_colourline(z, x, c, cmin, cmax,
                                                   args.linewidth)
                            elif args.track_color == "beta_z":
                                plot_2D_colourline_beta(
                                    z, x, c, args.linewidth)
                            elif args.track_color == "beta_y":
                                plot_2D_colourline_beta(
                                    z, x, c, args.linewidth)
                            elif args.track_color == 'none':
                                if len(x) > 0:
                                    index = np.argmin(
                                        abs(start_segments - x[-1]))

                                    # print('index : %i' %index)
                                    # print('x0 ist %f' %x[-1])
                                    ax.plot(z,
                                            x,
                                            color=colors2[index],
                                            linewidth=0.3)
                    ''' Set colorbar '''
                    if args.track_color != "none":
                        norm = matplotlib.colors.Normalize(vmin=np.min(cmin),
                                                           vmax=np.max(cmax))

                        # choose a colormap
                        c_m = chosencmap

                        # create a ScalarMappable and initialize a data structure
                        s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
                        s_m.set_array([])

                        cbar = plt.colorbar(s_m, fraction=0.052, pad=0.06)

                    else:
                        # norm = matplotlib.colors.Normalize( vmin= 0, vmax=6)

                        # choose a colormap
                        c_m = cm.jet

                        # create a ScalarMappable and initialize a data structure
                        s_m = matplotlib.cm.ScalarMappable(cmap=c_m)
                        s_m.set_array(
                            [args.track_range[0], args.track_range[1]])

                        cbar = plt.colorbar(s_m, fraction=0.052, pad=0.06)

                    if args.track_color == "u_tot":
                        cbar.ax.set_title(r'$|u|$', pad=args.cbarpad)
                    elif args.track_color == "beta_z":
                        cbar.ax.set_title(r'$\beta_z$', pad=args.cbarpad)
                    elif args.track_color == "beta_y":
                        cbar.ax.set_title(r'$\beta_y$', pad=args.cbarpad)
                    else:
                        cbar.ax.set_title(r'$k_p\,X_0$',
                                          fontsize=16,
                                          pad=args.cbarpad)

                ax.set_xlabel(r'$k_p\,\zeta$', fontsize=16)
                ax.set_ylabel(r'$k_p\,x$', fontsize=16, labelpad=-5)
                ax.tick_params(labelsize=args.axticklabelsize)
                cbar.ax.tick_params(labelsize=args.axticklabelsize)
                if args.adjust_bottom:
                    fig.subplots_adjust(bottom=args.adjust_bottom)
                savepath = 'plots/g3d-slice'
                mkdirs_if_nexist(savepath)
                if not args.tracksoff:
                    tracked = 'tracked_'
                else:
                    tracked = ''
                if args.savename:
                    savename = '/' + args.savename + '_'
                else:
                    savename = '/ionized_electron_density_'

                if args.file_format == 'eps':
                    save_path_name = savepath + savename + tracked + timestamp + '.eps'
                    print('Saving figure...')
                    fig.savefig(save_path_name, format='eps', dpi=args.dpi)
                    print('Writing file...')
                elif args.file_format == 'pdf':
                    save_path_name = savepath + savename + tracked + timestamp + '.pdf'
                    print('Saving figure...')
                    fig.savefig(save_path_name, format='pdf', dpi=args.dpi)
                    print('Writing file...')
                elif args.file_format == 'png':
                    save_path_name = savepath + savename + tracked + timestamp + '.png'
                    print('Saving figure...')
                    fig.savefig(save_path_name, format='png', dpi=args.dpi)
                    print('Writing file...')
                else:
                    print(
                        'ERROR: unknown file output format. Please choose from eps, pdf or png'
                    )

                if args.verbose:
                    sys.stdout.write('Saved: %s\n' % save_path_name)
                    sys.stdout.flush()
                plt.close(fig)
                print('Done!')