Esempio n. 1
0
    def read(self, navg=None):
        g3d = Grid3d(self.__h5file)
        self.__fxy = g3d.read(x0=self.__zeta_pos, navg=navg)
        self.__x_array = g3d.get_x_arr(1)
        self.__y_array = g3d.get_x_arr(2)

        return self.__x_array, self.__y_array, self.__fxy
Esempio n. 2
0
def plot_hipace_Ex(zeta_pos):
    ExmBy_path = './DATA/field_ExmBy_000000.h5'
    By_path = './DATA/field_By_000000.h5'

    ExmBy_g3d2 = Grid3d(ExmBy_path)
    By_g3d2 = Grid3d(By_path)

    ExmBy = np.transpose(ExmBy_g3d2.read(x2=0.0))
    By = np.transpose(By_g3d2.read(x2=0.0))

    Ex = ExmBy + By

    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    idx = np.abs(By_g3d2.get_zeta_arr() - zeta_pos).argmin()

    return By_g3d2.get_x_arr(2), Ex[:, idx]
Esempio n. 3
0
def lvst_Wr(args):
    beam = set_beam(args)
    plasma = set_plasma(args)

    h5flist = H5FList(args.path, 'g3d')
    flist = h5flist.get()

    for file in flist:
        g3d = Grid3d(file)
        if (g3d.name == 'ExmBy' or g3d.name == 'EypBx'):
            cmp_plot_Wr(args, g3d, plasma, beam)
        else:
            print('ERROR: Dataset is no ExmBy or EypBx dataset!')
            sys.exit(1)
Esempio n. 4
0
def main():

    parser = blowout_geo_parser()
    args = parser.parse_args()

    h5flist = H5FList(args.path, 'g3d')
    flist = h5flist.get()

    for file in flist:
        g3d = Grid3d(file)
        if (g3d.name == 'plasma_charge'):
            blowout = Blowout(g3d, args)
            blowout.plot_r_z_plane()
            blowout.plot_r_lines()
            blowout.plot_rb()
            blowout.calc_deltarho_rhomax_sheathcharge()
            blowout.plot_deltarho_rhomax_sheathcharge()
            blowout.plot_model_sheath()

        else:
            print('ERROR: HDF5 file must contain a plasma_charge dataset!')
            sys.exit(1)
Esempio n. 5
0
def main():

    #### Defining constants as in HiPACE
    #define M_ELEC_PER_M_NUCL         5.4857990946e-4
    #define E_MUON_MASS_RATIO         4.83633170e-3 /* from NIST database */
    ELECTRON_CHARGE_IN_COUL = 1.60217657e-19
    ELECTRON_MASS_IN_KG = 9.10938291e-31
    SPEED_OF_LIGHT_IN_M_PER_S = 299792458
    VAC_PERMIT_FARAD_PER_M = 8.854187817e-12
    HYDROGEN_IONIZATION_ENERGIE_EV = 13.659843449

    omega_alpha = 4.13e16
    # [s^-1]
    E_alpha = 5.1e11
    # [V/m]
    elec_density = 5e+22  # [1/m^3]
    omega_p = np.sqrt(elec_density * (ELECTRON_CHARGE_IN_COUL**2) /
                      (VAC_PERMIT_FARAD_PER_M * ELECTRON_MASS_IN_KG))
    # calculation of the plasma frequency
    #print('omega_p is %0.3e' %omega_p)
    E_0 = omega_p * ELECTRON_MASS_IN_KG * SPEED_OF_LIGHT_IN_M_PER_S / ELECTRON_CHARGE_IN_COUL
    #calculation of the denormalization factor for the electric field
    #print('E_0 is %0.3e' %E_0)

    #home path Path definitions
    Ez_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/field_Ez_000000.h5'
    ExmBy_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/field_ExmBy_000000.h5'
    EypBx_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/field_EypBx_000000.h5'
    Bx_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/field_Bx_000000.h5'
    By_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/field_By_000000.h5'

    #neutral_density_path = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs/DATA/density_plasma_neutral_000000.h5'
    neutral_density_path1 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs_new4/DATA/density_ionized_electrons_plasma_Cs_000000.h5'

    #home path Path definitions
    # Ez_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/field_Ez_000000.h5'
    # ExmBy_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/field_ExmBy_000000.h5'
    # EypBx_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/field_EypBx_000000.h5'
    # Bx_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/field_Bx_000000.h5'
    # By_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/field_By_000000.h5'
    #
    # #neutral_density_path = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs/DATA/density_plasma_neutral_000000.h5'
    # neutral_density_path2 = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/cs5/DATA/density_ionized_electrons_plasma_Cs_000000.h5'

    #home path Path definitions
    Ez_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/field_Ez_000000.h5'
    ExmBy_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/field_ExmBy_000000.h5'
    EypBx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/field_EypBx_000000.h5'
    Bx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/field_Bx_000000.h5'
    By_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/field_By_000000.h5'

    #neutral_density_path = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs/DATA/density_plasma_neutral_000000.h5'
    neutral_density_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test6/DATA/density_ionized_electrons_plasma_H_000000.h5'

    #home path Path definitions
    Ez_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/field_Ez_000000.h5'
    ExmBy_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/field_ExmBy_000000.h5'
    EypBx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/field_EypBx_000000.h5'
    Bx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/field_Bx_000000.h5'
    By_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/field_By_000000.h5'

    #neutral_density_path = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs/DATA/density_plasma_neutral_000000.h5'
    neutral_density_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/return_of_e2/rp_1_rb_1_2/DATA/density_ionized_electrons_plasma_H_000000.h5'
    if not os.path.exists('plots'):
        os.makedirs('plots')
    if not os.path.exists('plots/pp-ionization/'):
        os.makedirs('plots/pp-ionization/')

    #vektorized function for calc ion rate
    vectorfunc = np.vectorize(calc_ion_rate)

    #Ez_g3d = Grid3d(Ez_path)
    #ExmBy_g3d = Grid3d(ExmBy_path)
    #EypBx_g3d = Grid3d(EypBx_path)
    #Bx_g3d = Grid3d(Bx_path)
    By_g3d1 = Grid3d(By_path1)

    neutral_density_g3d1 = Grid3d(neutral_density_path1)
    By_g3d2 = Grid3d(By_path2)
    Ez_g3d2 = Grid3d(Ez_path2)
    ExmBy_g3d2 = Grid3d(ExmBy_path2)
    EypBx_g3d2 = Grid3d(EypBx_path2)
    Bx_g3d2 = Grid3d(Bx_path2)
    neutral_density_g3d2 = Grid3d(neutral_density_path2)

    #Reading in the data
    Ez = np.transpose(Ez_g3d2.read(x2=0.0))
    ExmBy = np.transpose(ExmBy_g3d2.read(x2=0.0))
    EypBx = np.transpose(EypBx_g3d2.read(x2=0.0))
    Bx = np.transpose(Bx_g3d2.read(x2=0.0))
    By = np.transpose(By_g3d2.read(x2=0.0))

    # neutral_density1 = np.transpose(neutral_density_g3d1.read(x1=0.0))
    # plt.pcolormesh(By_g3d1.get_zeta_arr(), By_g3d1.get_x_arr(2), neutral_density1, cmap=cm.Blues_r) #
    # cb = plt.colorbar()
    # plt.clim(0,-3)
    # #plt.imshow(neutral_density)
    # plt.show()

    neutral_density2 = np.transpose(neutral_density_g3d2.read(x1=0.0))
    plt.pcolormesh(By_g3d2.get_zeta_arr(),
                   By_g3d2.get_x_arr(2),
                   np.log(np.abs(neutral_density2)),
                   cmap=cm.Blues)  #
    cb = plt.colorbar()
    #plt.clim(-2,-25)
    #plt.imshow(neutral_density)
    plt.show()

    # difference_parallel = neutral_density1 - neutral_density2
    # plt.pcolormesh(By_g3d1.get_zeta_arr(), By_g3d1.get_x_arr(2), difference_parallel, cmap=cm.seismic) #
    # cb = plt.colorbar()
    # #plt.clim(3,-3)
    # #plt.imshow(neutral_density)
    # plt.show()

    E_magnitude = np.sqrt((ExmBy + By)**2 + (EypBx - Bx)**2 + Ez**2) * E_0

    print('The maximum magnitude of the electric field is %0.3e' %
          np.max(E_magnitude))
    ### Plotting the magnitude
    plt.contourf(By_g3d2.get_zeta_arr(),
                 By_g3d2.get_x_arr(2),
                 E_magnitude,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ |E|$', fontsize=14)
    plt.savefig('plots/pp-ionization/E_magnitude.png')
    plt.show()

    vmax1 = np.max(ExmBy + By)
    vmin1 = np.min(ExmBy + By)
    midpoint1 = 1 - vmax1 / (vmax1 + np.abs(vmin1))
    shifted_cmap1 = shiftedColorMap(cm.seismic,
                                    midpoint=midpoint1,
                                    name='shifted')

    ### Plotting the magnitude
    plt.contourf(
        By_g3d2.get_zeta_arr(),
        By_g3d2.get_x_arr(2),
        ExmBy + By,
        200,
        cmap=shifted_cmap1)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ Ex $', fontsize=14)
    plt.savefig('plots/pp-ionization/E_x.png')
    plt.show()

    vmax = np.max(EypBx - Bx)
    vmin = np.min(EypBx - Bx)
    midpoint = 1 - vmax / (vmax + np.abs(vmin))
    shifted_cmap = shiftedColorMap(cm.seismic,
                                   midpoint=midpoint,
                                   name='shifted')

    ### Plotting the magnitude
    plt.contourf(By_g3d2.get_zeta_arr(),
                 By_g3d2.get_x_arr(2),
                 EypBx - Bx,
                 200,
                 cmap=shifted_cmap)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ Ey$', fontsize=14)
    plt.savefig('plots/pp-ionization/E_y.png')
    plt.show()
Esempio n. 6
0
def main():

    #### Defining constants as in HiPACE
    #define M_ELEC_PER_M_NUCL         5.4857990946e-4
    #define E_MUON_MASS_RATIO         4.83633170e-3 /* from NIST database */
    ELECTRON_CHARGE_IN_COUL = 1.60217657e-19
    ELECTRON_MASS_IN_KG = 9.10938291e-31
    SPEED_OF_LIGHT_IN_M_PER_S = 299792458
    VAC_PERMIT_FARAD_PER_M = 8.854187817e-12
    HYDROGEN_IONIZATION_ENERGIE_EV = 13.659843449

    omega_alpha = 4.13e16
    # [s^-1]
    E_alpha = 5.1e11
    # [V/m]
    elec_density = 1e+23  # [1/m^3]
    omega_p = np.sqrt(elec_density * (ELECTRON_CHARGE_IN_COUL**2) /
                      (VAC_PERMIT_FARAD_PER_M * ELECTRON_MASS_IN_KG))
    # calculation of the plasma frequency
    #print('omega_p is %0.3e' %omega_p)
    E_0 = omega_p * ELECTRON_MASS_IN_KG * SPEED_OF_LIGHT_IN_M_PER_S / ELECTRON_CHARGE_IN_COUL
    #calculation of the denormalization factor for the electric field
    #print('E_0 is %0.3e' %E_0)
    kp = SPEED_OF_LIGHT_IN_M_PER_S / omega_p

    vectorfunc = np.vectorize(calc_ion_rate)
    ionization_rate_crit = vectorfunc(3.2e10, 1, 13.659843449, 13.659843449, 0,
                                      0)
    print('ionization rate at crit field: %f' % ionization_rate_crit)
    #home path Path definitions
    Ez_path = './DATA/field_Ez_000000.0.h5'
    ExmBy_path = './DATA/field_ExmBy_000000.0.h5'
    EypBx_path = './DATA/field_EypBx_000000.0.h5'
    Bx_path = './DATA/field_Bx_000000.0.h5'
    By_path = './DATA/field_By_000000.0.h5'

    #neutral_density_path = '/Users/diederse/desy/PIC-sim/HiPACE/tests/interaction_tests2/Cs/DATA/density_plasma_neutral_000000.h5'
    neutral_density_path = './DATA/density_plasma_H_000000.0.h5'
    ### nersc path HAS TO BE MOUNTED

    #Ez_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_Ez_000000.h5'
    #ExmBy_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_ExmBy_000000.h5'
    #EypBx_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_EypBx_000000.h5'
    #Bx_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_Bx_000000.h5'
    #By_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_By_000000.h5'

    #neutral_density_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/density_plasma_neutral_000000.h5'

    #vektorized function for calc ion rate

    Ez_g3d = Grid3d(Ez_path)
    ExmBy_g3d = Grid3d(ExmBy_path)
    EypBx_g3d = Grid3d(EypBx_path)
    Bx_g3d = Grid3d(Bx_path)
    By_g3d = Grid3d(By_path)

    neutral_density_g3d = Grid3d(neutral_density_path)

    if not os.path.exists('./plots'):
        os.makedirs('./plots')
    if not os.path.exists('./plots/pp-ionization/'):
        os.makedirs('./plots/pp-ionization/')

    #Reading in the data
    Ez = np.transpose(Ez_g3d.read(x2=0.0))
    ExmBy = np.transpose(ExmBy_g3d.read(x2=0.0))
    EypBx = np.transpose(EypBx_g3d.read(x2=0.0))
    Bx = np.transpose(Bx_g3d.read(x2=0.0))
    By = np.transpose(By_g3d.read(x2=0.0))

    neutral_density = np.transpose(neutral_density_g3d.read(x2=0.0))
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.pcolormesh(By_g3d.get_zeta_arr(),
                   By_g3d.get_x_arr(2),
                   neutral_density,
                   cmap=cm.Blues)  #
    cb = plt.colorbar()
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar()
    cb.set_label(label=r'$n_p/n_0$', fontsize=16)
    plt.savefig('./plots/pp-ionization/charge_density.png')
    #plt.clim(0,3)
    #plt.imshow(neutral_density)
    plt.show()
    plt.close(fig)
    '''
  #### Test to plot the By field 
  print(By_g3d.get_x_arr(0)) #'zeta array limits are %f' % 
  plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), By, 200, cmap=cm.seismic)
  plt.ylabel(r'$k_p x$', fontsize =14)
  #plt.xlim(By_g3d.get_zeta_arr)
  #plt.ylim(By_g3d.get_x_arr)
  plt.xlabel(r'$k_p \zeta$', fontsize =14)
  cb = plt.colorbar()
  cb.set_label(label = r'$B_y/E_0$', fontsize = 14)
  plt.show()
  '''

    #check for directory

    ## computing the Magnitude of E:

    E_magnitude = np.sqrt((ExmBy + By)**2 + (EypBx - Bx)**2 + Ez**2) * E_0

    number_above_5_6_e10 = np.where(E_magnitude > 5.7e10)
    number = E_magnitude[number_above_5_6_e10]
    print(number)
    print(
        'the number of grid points with an electric field above 5.6e10 is %0.3e'
        % len(number))
    #print(number_above_5_6_e10)
    print('The maximum magnitude of the electric field is %0.3e' %
          np.max(E_magnitude))
    ### Plotting the magnitude
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 E_magnitude / E_0,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar()
    cb.set_label(label=r'$ |E|/E_0$', fontsize=16)
    plt.savefig('./plots/pp-ionization/E_magnitude.png')
    plt.show()
    plt.close(fig)

    ## Computing the ionization rate:
    #ionization_rate = np.nan_to_num(omega_alpha / (2.0 * np.pi) *4.0 * E_alpha/ E_magnitude * np.exp (-2.0/3.0 * E_alpha/ E_magnitude ) )# this is just correct for hydrogen!
    ionization_rate = vectorfunc(E_magnitude, 1, 13.659843449, 13.659843449, 0,
                                 0)  # complete formulae for hydrogen
    #ionization_rate = vectorfunc(E_magnitude, 2, 54.4177650, 24.58738880, 0,0 )

    #print('The maximum ionization rate is %0.3e' % np.max(ionization_rate))
    ### Plotting the ionization rate:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 ionization_rate,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar()
    cb.set_label(label='Ionization rate [1/s]', fontsize=16)
    plt.savefig('./plots/pp-ionization/ion_rate.png')
    plt.show()
    plt.close(fig)

    #plotting the rate vs electric field in general
    #E_magnitude2 = 10**np.array(list(range(10, 15)))
    #ionization_rate_plot = np.nan_to_num(omega_alpha / (2.0 * np.pi) *4.0 * E_alpha/ E_magnitude2 * np.exp (-2.0/3.0 * E_alpha/ E_magnitude2 ) )
    #plt.plot(E_magnitude2, ionization_rate_plot)
    #plt.show()

    cbarvektor = np.linspace(0, 1, 11, endpoint=True)
    #print(By_g3d.get_zeta_arr())
    #print(np.abs(By_g3d.get_zeta_arr()[1] -By_g3d.get_zeta_arr()[0]))
    deltat = np.abs(By_g3d.get_zeta_arr()[1] -
                    By_g3d.get_zeta_arr()[0]) / omega_p
    print('Deltat is %0.3e' % deltat)
    #computing the ionization probability
    ion_probability = 1.0 - np.exp(-ionization_rate * deltat)

    ionization_prob_crit = 1.0 - np.exp(-ionization_rate_crit * deltat)
    print('ionization prob  at crit field: %f' % ionization_prob_crit)
    crit_ionization = ion_probability
    crit_ionization[:, :] = ionization_prob_crit
    #print('The maximum ionization probability is %0.3e' % np.max(ion_probability))
    ### Plotting the ionization probability:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 ion_probability,
                 200,
                 cmap=cm.Reds
                 )  # here cmap reds, since it is not divering  vmin=0, vmax=1,
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)

    cb = plt.colorbar(ticks=cbarvektor)
    #cb.set_clim(vmin=0,vmax=1)
    #cb.set_ticks(cbarvektor)
    #plt.clim(0,1)
    cb.set_label(label='Ionization probability', fontsize=16)
    plt.show()
    plt.close(fig)

    #calculate the cumulative probability:
    cum_prob = (1 - np.cumprod(1 - ion_probability[:, ::-1], axis=1)
                )[:, ::-1]  #np.flip(np.flip(ion_probability, 1).cumsum(), 1) #

    ### Plotting the ionization probability:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 cum_prob,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar(ticks=cbarvektor)
    #plt.clim(0,1.01)
    cb.set_label(label=r'$P_{ADK}$', fontsize=16)
    plt.savefig('./plots/pp-ionization/cum_ion_prob.png')
    plt.show()
    plt.close(fig)
    '''START  ONLY FOR CRITICAL IONIZATION PROBABILITY CHECK '''
    #calculate the cumulative probability:
    cum_prob_crit = (
        1 - np.cumprod(1 - crit_ionization[:, ::-1], axis=1)
    )[:, ::-1]  #np.flip(np.flip(ion_probability, 1).cumsum(), 1) #

    ### Plotting the ionization probability:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 cum_prob_crit,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar(ticks=cbarvektor)
    #plt.clim(0,1.01)
    cb.set_label(label=r'$P_{ADK}$', fontsize=16)
    plt.savefig('./plots/pp-ionization/cum_ion_prob_crit.png')
    plt.show()
    plt.close(fig)
    ''' END ONLY FOR CRITICAL IONIZATION PROBABILITY CHECK '''

    ### Plotting the ionization probability:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.pcolormesh(By_g3d.get_zeta_arr(),
                   By_g3d.get_x_arr(2),
                   ion_probability,
                   cmap=cm.Reds)  #here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar(ticks=cbarvektor)
    plt.clim(0, 1)
    cb.set_label(label='Ionization probability', fontsize=16)
    plt.savefig('./plots/pp-ionization/ion_prob.png')
    plt.show()
    plt.close(fig)

    #Plotting the differences between HiPACE and analytical model
    differenz = (
        cum_prob
    ) - neutral_density  # cum prob + 1 because it is preionized to level 1

    #producing a asymmetric Colorbar
    vmax = np.max(differenz)
    vmin = np.min(differenz)
    midpoint = 1 - vmax / (vmax + np.abs(vmin))
    shifted_cmap = shiftedColorMap(cm.seismic,
                                   midpoint=midpoint,
                                   name='shifted')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 differenz,
                 200,
                 cmap=shifted_cmap
                 )  # cm.seismic) # here cmap reds, since it is not diverging
    plt.ylabel(r'$k_p x$', fontsize=16)
    plt.xlabel(r'$k_p \zeta$', fontsize=16)
    cb = plt.colorbar()
    plt.clim(vmin, vmax)
    cb.set_label(label=r'$P_{ADK} - n_p/n_0$', fontsize=16)
    plt.savefig('./plots/pp-ionization/diff_ion_prob.png')
    plt.show()
    plt.close(fig)
    print('summed absolut difference: %f' % (np.sum(abs(differenz))))
    '''
Esempio n. 7
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!')
Esempio n. 8
0
def main():

    #### Defining constants as in HiPACE
    #define M_ELEC_PER_M_NUCL         5.4857990946e-4
    #define E_MUON_MASS_RATIO         4.83633170e-3 /* from NIST database */
    ELECTRON_CHARGE_IN_COUL = 1.60217657e-19
    ELECTRON_MASS_IN_KG = 9.10938291e-31
    SPEED_OF_LIGHT_IN_M_PER_S = 299792458
    VAC_PERMIT_FARAD_PER_M = 8.854187817e-12
    HYDROGEN_IONIZATION_ENERGIE_EV = 13.659843449

    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))
    # calculation of the plasma frequency
    #print('omega_p is %0.3e' %omega_p)
    E_0 = omega_p * ELECTRON_MASS_IN_KG * SPEED_OF_LIGHT_IN_M_PER_S / ELECTRON_CHARGE_IN_COUL
    #calculation of the denormalization factor for the electric field
    #print('E_0 is %0.3e' %E_0)
    kp = SPEED_OF_LIGHT_IN_M_PER_S / omega_p
    print('kp = ' + str(kp))

    #home path Path definitions
    Ez_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/field_Ez_000000.h5'
    ExmBy_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/field_ExmBy_000000.h5'
    EypBx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/field_EypBx_000000.h5'
    Bx_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/field_Bx_000000.h5'
    By_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/field_By_000000.h5'

    # neutral_density_path2 = '/Users/diederse/desy/PIC-sim/HiPACE/tests/the_return_of_the_local_electron/theo_test/DATA/density_ionized_electrons_plasma_H_000000.h5'

    #Ez_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_Ez_000000.h5'
    #ExmBy_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_ExmBy_000000.h5'
    #EypBx_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_EypBx_000000.h5'
    #Bx_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_Bx_000000.h5'
    #By_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/field_By_000000.h5'

    #neutral_density_path = '/Users/diederse/mountpoints/ed_scratch/simulations/hipace/tests/neutral1/DATA/density_plasma_neutral_000000.h5'

    #vektorized function for calc ion rate
    vectorfunc = np.vectorize(calc_ion_rate)

    Ez_g3d = Grid3d(Ez_path2)
    ExmBy_g3d = Grid3d(ExmBy_path2)
    EypBx_g3d = Grid3d(EypBx_path2)
    Bx_g3d = Grid3d(Bx_path2)
    By_g3d = Grid3d(By_path2)

    # neutral_density_g3d = Grid3d(neutral_density_path2)

    #Reading in the data
    Ez = np.transpose(Ez_g3d.read(x2=0.0))
    ExmBy = np.transpose(ExmBy_g3d.read(x2=0.0))
    EypBx = np.transpose(EypBx_g3d.read(x2=0.0))
    Bx = np.transpose(Bx_g3d.read(x2=0.0))
    By = np.transpose(By_g3d.read(x2=0.0))

    # neutral_density = np.transpose(neutral_density_g3d.read(x2=0.0))
    # plt.pcolormesh(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), neutral_density, cmap=cm.Blues_r) #
    # cb = plt.colorbar()
    # plt.clim(0,-3)
    # #plt.imshow(neutral_density)
    # plt.show()
    '''
  #### Test to plot the By field 
  print(By_g3d.get_x_arr(0)) #'zeta array limits are %f' % 
  plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), By, 200, cmap=cm.seismic)
  plt.ylabel(r'$k_p x$', fontsize =14)
  #plt.xlim(By_g3d.get_zeta_arr)
  #plt.ylim(By_g3d.get_x_arr)
  plt.xlabel(r'$k_p \zeta$', fontsize =14)
  cb = plt.colorbar()
  cb.set_label(label = r'$B_y/E_0$', fontsize = 14)
  plt.show()
  '''

    #check for directory

    if not os.path.exists('plots'):
        os.makedirs('plots')
    if not os.path.exists('plots/pp-ionization/'):
        os.makedirs('plots/pp-ionization/')

    ## computing the Magnitude of E:

    E_magnitude = np.sqrt((ExmBy + By)**2 + (EypBx - Bx)**2 + Ez**2) * E_0

    # vmax1 = np.max(ExmBy + By)
    # vmin1 = np.min(ExmBy + By)
    # midpoint1 = 1 - vmax1/(vmax1 + np.abs(vmin1))
    # shifted_cmap1 = shiftedColorMap(cm.seismic, midpoint=midpoint1, name='shifted')
    #
    # ### Plotting Ex from HiPACE
    # plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), ExmBy + By, 200, cmap=shifted_cmap1) # here cmap reds, since it is not divering
    # plt.ylabel(r'$k_p x$', fontsize =14)
    # plt.xlabel(r'$k_p \zeta$', fontsize =14)
    # cb = plt.colorbar()
    # cb.set_label(label = r'$ Ex$ HiPACE', fontsize = 14)
    # plt.savefig('plots/pp-ionization/E_x.png')
    # plt.show()

    # Plotting Ey from HiPACE
    # vmax = np.max(EypBx - Bx)
    # vmin = np.min(EypBx - Bx)
    # midpoint = 1 - vmax/(vmax + np.abs(vmin))
    # shifted_cmap = shiftedColorMap(cm.seismic, midpoint=midpoint, name='shifted')
    #
    # ### Plotting the magnitude
    # print('length By_g3d.get_x_arr(2) = ' + str(len(By_g3d.get_x_arr(2))))
    # plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), EypBx - Bx, 200, cmap=shifted_cmap) # here cmap reds, since it is not divering
    # plt.ylabel(r'$k_p x$', fontsize =14)
    # plt.xlabel(r'$k_p \zeta$', fontsize =14)
    # cb = plt.colorbar()
    # cb.set_label(label = r'$ Ey$', fontsize = 14)
    # plt.savefig('plots/pp-ionization/E_y.png')
    # plt.show()

    nb = 1.2
    ni = 1
    can_field = np.zeros(shape=(256, 300))
    can_field2 = np.zeros(shape=(256, 300))

    length_x_step = 24 / 256

    for i in range(0, 128):
        can_field[127 - i,
                  150:200] = (63 / 64)**2 * nb * 0.5 / (length_x_step *
                                                        (i + 0.5))
        can_field[128 + i,
                  150:200] = -(63 / 64)**2 * nb * 0.5 / (length_x_step *
                                                         (i + 0.5))
        # Rp needs to be adjusted here as well:
        can_field2[127 - i,
                   0:200] = -(63 / 64)**2 * ni * 0.5 / (length_x_step *
                                                        (i + 0.5))
        can_field2[128 + i,
                   0:200] = +(63 / 64)**2 * ni * 0.5 / (length_x_step *
                                                        (i + 0.5))

        #can_field2[127-i, 0:200] = -(255/64)**2 * ni * 0.5 / (0.09375 * (i + 0.5))
        #can_field2[128+i, 0:200] = +(255/64)**2 * ni * 0.5 / (0.09375 * (i + 0.5))

        ### FOR Rp = 2
        can_field[127 - i,
                  150:200] = (129 / 64)**2 * nb * 0.5 / (length_x_step *
                                                         (i + 0.5))
        can_field[128 + i,
                  150:200] = -(129 / 64)**2 * nb * 0.5 / (length_x_step *
                                                          (i + 0.5))
        # Rp needs to be adjusted here as well:
        can_field2[127 - i,
                   0:200] = -(129 / 64)**2 * ni * 0.5 / (length_x_step *
                                                         (i + 0.5))
        can_field2[128 + i,
                   0:200] = +(129 / 64)**2 * ni * 0.5 / (length_x_step *
                                                         (i + 0.5))

        ### for rp=rb=2
    for i in range(0, 22):
        can_field[127 - i, 150:200] = (length_x_step * (i + 0.5)) * nb * 0.5
        can_field[128 + i, 150:200] = -length_x_step * (i + 0.5) * nb * 0.5
        can_field2[127 - i, 0:200] = -(length_x_step * (i + 0.5)) * ni * 0.5
        can_field2[128 + i, 0:200] = +length_x_step * (i + 0.5) * ni * 0.5

    # for i in range(0,11):
    #     can_field[127-i, 150:200] = (length_x_step * (i + 0.5)) * nb * 0.5
    #     can_field[128+i, 150:200] = -length_x_step * (i + 0.5) * nb  * 0.5

    #for Rp = 255/64
    # for i in range(0, 43):
    #     can_field2[127-i, 0:200] = -(0.09375 * (i + 0.5)) * ni * 0.5
    #     can_field2[128+i, 0:200] = +0.09375 * (i + 0.5) * ni  * 0.5

    #for Rp = 63/64
    # for i in range(0, 11):
    #     can_field2[127-i, 0:200] = -(length_x_step * (i + 0.5)) * ni * 0.5
    #     can_field2[128+i, 0:200] = +length_x_step * (i + 0.5) * ni  * 0.5

    #for Rp = 33/64
    # for i in range(0, 6):
    #    can_field2[127-i, 0:200] = -(0.09375 * (i + 0.5)) * ni * 0.5
    #    can_field2[128+i, 0:200] = +0.09375 * (i + 0.5) * ni  * 0.5

    can_field += can_field2

    plt.plot(np.arange(-12, 12, length_x_step), can_field[:, 175])
    plt.show()

    vmax = np.max(can_field)
    vmin = np.min(can_field)
    midpoint = 1 - vmax / (vmax + np.abs(vmin))
    shifted_cmap = shiftedColorMap(cm.seismic,
                                   midpoint=midpoint,
                                   name='shifted')
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 can_field,
                 200,
                 cmap=shifted_cmap)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ E_r/E_0$ analytical', fontsize=14)
    plt.axvline(x=-2, color='black')
    plt.axhline(y=129 / 64, color='black')
    plt.text(-7.5, 11, 'IV', fontsize=16)
    plt.text(-1, 11, 'III', fontsize=16)
    plt.text(-1, 0.5, 'I', fontsize=16)
    plt.text(-7.5, 0.5, 'II', fontsize=16)
    plt.xlim(-8, 0)
    plt.ylim(0, 12)
    plt.show()

    ## Computing the ionization rate:
    #ionization_rate = np.nan_to_num(omega_alpha / (2.0 * np.pi) *4.0 * E_alpha/ E_magnitude * np.exp (-2.0/3.0 * E_alpha/ E_magnitude ) )# this is just correct for hydrogen!
    ionization_rate = vectorfunc(
        abs(can_field) * E_0, 1, 13.659843449, 13.659843449, 0,
        0)  # complete formulae for hydrogen
    #ionization_rate = vectorfunc(E_magnitude, 2, 54.4177650, 24.58738880, 0,0 )

    potential = np.zeros(shape=(256, 300))
    #potential[0:128, :] = -np.cumsum(can_field[0:128, :], axis=0)
    potential[128:, :] = -np.cumsum(can_field[128:, :] * 0.09375, axis=0)
    # for i in range(128):
    #     potential[128+i] = potential[127-i,:]

    startradius = 63 / 63
    endradius = 1.57

    def calc_pot_at_x_within_bunch(x):
        return potential[int(128 + np.floor(x / 0.09375)), 190]

    def calc_pot_at_x_behind_bunch(x):
        return -potential[int(128 + np.floor(x / 0.09375)), 10]

    print('potential at 1.567:')
    print(calc_pot_at_x_within_bunch(endradius))

    print('potential at 63/64:')
    print(calc_pot_at_x_within_bunch(startradius))

    print('therefore the total kinetic energy the electron gained is: ')
    print(
        calc_pot_at_x_within_bunch(endradius) -
        calc_pot_at_x_within_bunch(startradius) +
        calc_pot_at_x_behind_bunch(endradius))

    plt.plot(By_g3d.get_x_arr(2)[128:],
             -potential[128:, 10],
             label=r'$E_{pot}$ behind beam analytical')
    plt.plot(By_g3d.get_x_arr(2)[128:],
             potential[128:, 190],
             label=r'$-E_{pot}$ within beam analytical')
    #plt.plot(By_g3d.get_x_arr(2)[128:], can_field[128:,10], label=r'$E_r/E_0$ analytical')
    plt.legend()
    plt.grid()
    plt.show()

    vmax = np.max(potential)
    vmin = np.min(potential)
    midpoint = 1 - vmax / (vmax + np.abs(vmin))
    shifted_cmap = shiftedColorMap(cm.seismic,
                                   midpoint=midpoint,
                                   name='shifted')
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 potential,
                 200,
                 cmap=shifted_cmap)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ V$ analytical', fontsize=14)

    plt.show()

    ekin_at_r1 = -(potential - potential[133, 190])
    vmax = np.max(ekin_at_r1)
    vmin = np.min(ekin_at_r1)
    midpoint = 1 - vmax / (vmax + np.abs(vmin))
    shifted_cmap = shiftedColorMap(cm.seismic,
                                   midpoint=midpoint,
                                   name='shifted')
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 ekin_at_r1,
                 200,
                 cmap=shifted_cmap)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ epot @ r = 1 $ analytical', fontsize=14)

    plt.show()

    ### Plotting the magnitude
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 E_magnitude,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ |E|$ HiPACE', fontsize=14)
    plt.savefig('plots/pp-ionization/E_magnitude.png')
    plt.show()

    #print('The maximum ionization rate is %0.3e' % np.max(ionization_rate))
    ### Plotting the ionization rate:
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 can_field,
                 200,
                 cmap=cm.seismic)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label=r'$ |E| analytical$', fontsize=14)
    plt.savefig('plots/pp-ionization/can_field.png')
    plt.show()

    plt.plot(By_g3d.get_x_arr(2), (ExmBy + By)[:, 190],
             label=r'$Ex/E_0$ HiPACE')
    plt.plot(By_g3d.get_x_arr(2),
             can_field[:, 190],
             label=r'$Ex/E_0$ analytical')
    plt.legend()
    plt.show()

    print('E at roughly 0.5 within beam: %f ' % can_field[122, 190])
    print('E at roughly 0.5 behind beam : %f ' % can_field[122, 1])
    print('E at roughly 4 within beam: %f ' % can_field[85, 190])
    print('E at roughly 4 behind beam : %f ' % can_field[85, 1])
    print('E at roughly 4 within beam: %f ' % can_field[85, 190])
    print('E at roughly 4 behind beam : %f ' % can_field[85, 1])
    #print('The maximum ionization rate is %0.3e' % np.max(ionization_rate))
    ### Plotting the ionization rate:
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 ionization_rate,
                 200,
                 cmap=cm.Reds)  # here cmap reds, since it is not divering
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)
    cb = plt.colorbar()
    cb.set_label(label='Ionization rate [1/s]', fontsize=14)
    plt.savefig('plots/pp-ionization/ion_rate.png')
    plt.show()

    cbarvektor = np.linspace(0, 1, 11, endpoint=True)
    #print(By_g3d.get_zeta_arr())
    #print(np.abs(By_g3d.get_zeta_arr()[1] -By_g3d.get_zeta_arr()[0]))
    deltat = np.abs(By_g3d.get_zeta_arr()[1] -
                    By_g3d.get_zeta_arr()[0]) / omega_p
    print('Deltat is %0.3e' % deltat)
    #computing the ionization probability
    ion_probability = 1.0 - np.exp(-ionization_rate * deltat)
    #print('The maximum ionization probability is %0.3e' % np.max(ion_probability))
    ## Plotting the ionization probability:
    plt.contourf(By_g3d.get_zeta_arr(),
                 By_g3d.get_x_arr(2),
                 ion_probability,
                 200,
                 cmap=cm.Reds
                 )  # here cmap reds, since it is not divering  vmin=0, vmax=1,
    plt.ylabel(r'$k_p x$', fontsize=14)
    plt.xlabel(r'$k_p \zeta$', fontsize=14)

    cb.set_label(label='Ionization probability', fontsize=14)
    plt.show()

    # cbarvektor = np.linspace(0,1,11, endpoint = True)
    # #print(By_g3d.get_zeta_arr())
    # #print(np.abs(By_g3d.get_zeta_arr()[1] -By_g3d.get_zeta_arr()[0]))
    # deltat = np.abs(By_g3d.get_zeta_arr()[1] -By_g3d.get_zeta_arr()[0]) / omega_p
    # print('Deltat is %0.3e' %deltat)
    # #computing the ionization probability
    # ion_probability = 1.0 - np.exp(-ionization_rate * deltat )
    # #print('The maximum ionization probability is %0.3e' % np.max(ion_probability))
    # ### Plotting the ionization probability:
    # plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), ion_probability, 200,cmap=cm.Reds) # here cmap reds, since it is not divering  vmin=0, vmax=1,
    # plt.ylabel(r'$k_p x$', fontsize =14)
    # plt.xlabel(r'$k_p \zeta$', fontsize =14)
    #
    # cb = plt.colorbar(ticks = cbarvektor)
    # #cb.set_clim(vmin=0,vmax=1)
    # #cb.set_ticks(cbarvektor)
    # #plt.clim(0,1)
    # cb.set_label(label = 'Ionization probability', fontsize = 14)
    # plt.show()
    '''
  #calculate the cumulative probability:
  cum_prob = (1 - np.cumprod(1-ion_probability[:,::-1], axis=1))[:,::-1] #np.flip(np.flip(ion_probability, 1).cumsum(), 1) #
  
  
  ### Plotting the ionization probability:
  plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), cum_prob, 200, cmap=cm.Reds) # here cmap reds, since it is not divering
  plt.ylabel(r'$k_p x$', fontsize =14)
  plt.xlabel(r'$k_p \zeta$', fontsize =14)
  cb = plt.colorbar(ticks = cbarvektor) 
  #plt.clim(0,1.01)
  cb.set_label(label = 'Ionization probability', fontsize = 14)
  plt.savefig('plots/pp-ionization/cum_ion_prob.png')
  plt.show()

  
  ### Plotting the ionization probability:
  plt.pcolormesh(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), ion_probability, cmap=cm.Reds) #here cmap reds, since it is not divering
  plt.ylabel(r'$k_p x$', fontsize =14)
  plt.xlabel(r'$k_p \zeta$', fontsize =14)
  cb = plt.colorbar(ticks = cbarvektor) 
  plt.clim(0,1)
  cb.set_label(label = 'Ionization probability', fontsize = 14)
  plt.savefig('plots/pp-ionization/ion_prob.png')
  plt.show()

  
  
  

  
  #Plotting the differences between HiPACE and analytical model 
  differenz = ( cum_prob + 1 ) - neutral_density # cum prob + 1 because it is preionized to level 1
  
  
  #producing a asymmetric Colorbar
  vmax = np.max(differenz)
  vmin = np.min(differenz)
  midpoint = 1 - vmax/(vmax + np.abs(vmin))
  shifted_cmap = shiftedColorMap(cm.seismic, midpoint=midpoint, name='shifted')
  
  
  plt.contourf(By_g3d.get_zeta_arr(), By_g3d.get_x_arr(2), differenz, 200, cmap=shifted_cmap ) # cm.seismic) # here cmap reds, since it is not diverging
  plt.ylabel(r'$k_p x$', fontsize =14)
  plt.xlabel(r'$k_p \zeta$', fontsize =14)
  cb = plt.colorbar() 
  plt.clim(vmin,vmax)
  cb.set_label(label = r'$N_{H^+ analyt} - N_{H^+ HiPace}$', fontsize = 14)
  plt.savefig('plots/pp-ionization/diff_ion_prob.png')
  plt.show()

  '''
    '''