def distFunc_pxX_plot(filelist, timesteps, inpath, savepath): #============================================================================== # Create a dist function for all timesteps #============================================================================== for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) indivual_distF(inData, time, inpath, savepath)
def mass(*args, **kwargs): """Self-sufficient routine that determines the mass of each cell in the starting grid and plots it. """ dat=sh.getdata(0, verbose=False) fac = 1.0 if dat.Logical_flags.use_rz: fac = 2*np.pi vol=dat.Fluid_Volume.data * fac mass=rho[:,:]*vol[:,:] # The linout is abitrarily taken at halfway through the domain. half = round(np.shape(dat.Fluid_Volume.data)[1] / 2) cross_section = kwargs.get('cross_section', half) print("Total mass is: ", np.sum(np.sum(mass))) X=x[:,:] Y=y[:,:] fig1=plt.figure() plt.pcolormesh(X,Y,mass,edgecolor='none') cbar = plt.colorbar() cbar.set_label('Mass (kg)') #plt.gca().set_aspect('equal', adjustable='box') fig2=plt.figure() plt.plot(xc[:,cross_section],mass[:,cross_section]) plt.plot(xc[:,cross_section],mass[:,cross_section],'*') plt.xlabel('Radius (m)') plt.ylabel('Mass (kg)') plt.show()
def charge_ene_vs_x_3D_N(files): # normalization factor norm = 2.73092449e-22 x_at_ene_max = list() ene_max = list() charge = list() for _, fname in files.items(): print('processing {}'.format(fname)) d = sh.getdata(fname, verbose=False) px = d.Particles_Px_N_ele.data / norm py = d.Particles_Py_N_ele.data / norm pz = d.Particles_Pz_N_ele.data / norm w = d.Particles_Weight_N_ele.data (x, _, _) = d.Grid_Particles_N_ele.data mask = (px > 30.) px, py, pz, w, x = [arr[mask] for arr in (px, py, pz, w, x)] ene = .511 * (np.sqrt(1. + px**2 + py**2 + pz**2) - 1.) charge.append(np.sum(w) * 1.6e-19) ene_max.append(np.max(ene)) x_at_ene_max.append(x[np.argmax(ene)]) return x_at_ene_max, ene_max, charge
def __init__(self, path, savePath): self.d = sh.getdata(path) self.savePath = savePath self.count = int(path[-8:-4]) #Create folder to save into if not os.path.exists(self.savePath): os.makedirs(self.savePath)
def numberDens(filelist, timesteps, inpath, savepath, vMin, vMax): #============================================================================== # Creates the plot of the number density, #============================================================================== setup_figure_fontAttributes(size=11) #For each time step create plot and then save that with its simstep position for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) indivual_numDens(inData, time, inpath, savepath, vMin, vMax)
def produceSpectrum(sdf): # Load the last sdf file print scratchPath + sdf d = sh.getdata(scratchPath + sdf) px = d.dist_fn_x_px_electron.data grid = d.dist_fn_x_px_electron.grid.data t = d.Header['time'] if len(np.shape(px)) == 3: print 'ERROR IN PX FILE ---- Too many dimensions' spectrum = np.sum(px, axis=0) spectrumPlot(grid[1], spectrum, t, savePath, sdf[:-4]) np.savetxt(savePath + sdf[:-4] + 'spectrum.txt', np.c_[grid[1], spectrum])
def numD_and_Dist_for_all_time(filelist, timesteps, inpath, savepath, vMin, vMax): #Creating the color map with transparency cmap1 = mpl.colors.LinearSegmentedColormap.from_list( 'my_cmap2', ['orange', 'red'], 256) cmap1._init() # create the _lut array, with rgba values alphas = np.linspace( 0, 1.0, cmap1.N + 3 ) # create your alpha array and fill the colormap with them. here it is progressive, but you can create whathever you want cmap1._lut[:, -1] = alphas #For each time step create plot and then save that with its simstep position for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) indivual_numDens_with_laser(inData, time, inpath, savepath, cmap1, vMin, vMax) indivual_distF(inData, time, inpath, savepath)
def numberDens_with_laser_pulse(filelist, timesteps, inpath, savepath, vMin, vMax): #============================================================================== # Creates the plot of the number density, with the laser pulse # thresholded to be greater than 10x the median value laid over the top #============================================================================== #Creating the color map with transparency cmap1 = mpl.colors.LinearSegmentedColormap.from_list( 'my_cmap2', ['orange', 'red'], 256) cmap1._init() # create the _lut array, with rgba values alphas = np.linspace( 0, 1.0, cmap1.N + 3 ) # create your alpha array and fill the colormap with them. here it is progressive, but you can create whathever you want cmap1._lut[:, -1] = alphas #For each time step create plot and then save that with its simstep position for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) indivual_numDens_with_laser(inData, time, inpath, savepath, cmap1, vMin, vMax)
def densityVsTime(filelist, inpath, savepath): #============================================================================== # Convert the 2D arrays of the distfunc into 1D for each file by histogramming # the different rows into the px values. # This then forms a 2D array for the whole simulation showing the evolution #============================================================================== plt.close() all_N_integrated = [] all_Pos = [] for f in filelist: inData = sh.getdata(inpath + f) try: all_N_integrated.append( np.average(inData.Derived_Number_Density.data)) all_Pos.append( np.average([ inData.dist_fn_x_px_electron.grid.data[0][0], inData.dist_fn_x_px_electron.grid.data[0][-1] ])) except: print 'Reading error for: ' + f #Convert into np arrays for ease of use all_Pos = np.array(all_Pos) all_N_integrated = np.array(all_N_integrated) #Create folder to save into if not os.path.exists(savePath + 'Dist_evo/'): os.makedirs(savePath + 'Dist_evo/') #Save the files incase the plotting fails np.savetxt(savepath + 'Dist_evo/' + 'densityEvolution.txt', np.c_[all_Pos, all_N_integrated]) all_Pos = all_Pos * 1e6 # Convert into mu m plt.plot(all_Pos, all_N_integrated) plt.xlabel("Distance (mu m)") plt.ylabel('Number Density (m^-3)') plt.savefig(savepath + 'Dist_evo/' + 'densityEvolution.png')
def plot_particles(t): with contextlib.redirect_stdout(None): data = sh.getdata(t, '1dexample') sh.plot1d(data.Particles_Px_Left, 'o', markersize=2) sh.oplot1d(data.Particles_Px_Right, 'o', markersize=2)
def plot_field(t): with contextlib.redirect_stdout(None): data = sh.getdata(t, 'test') sh.plot_auto(data.Electric_Field_Ey)
import matplotlib.pyplot as plt import contextlib plt.rcParams['figure.figsize'] = [13, 13] def plot_particles(t): with contextlib.redirect_stdout(None): data = sh.getdata(t, '1dexample') sh.plot1d(data.Particles_Px_Left, 'o', markersize=2) sh.oplot1d(data.Particles_Px_Right, 'o', markersize=2) def plot_field(t): with contextlib.redirect_stdout(None): data = sh.getdata(t, 'test') sh.plot_auto(data.Electric_Field_Ey) for i in range(0,101): plot_particles(i) plt.show() for i in range(0,5): plot_field(i) plt.show() %pwd data = sh.getdata("epoch/budriga2017/2dcone_i21/0001.sdf") sh.plot_auto(data.Electric_Field_Ey) sh.plot_auto(data.Particles_Ek_electron) plt.show()
def load_datafile(self, filename): full_data = sh.getdata(filename, verbose=False) self.current_data = self.get_valid_keys(full_data) self.populate_listbox(self.current_data) return self.current_data
def laser(dat, *args, **kwargs): """Analysis of variables that are linked to the laser """ call_basic = kwargs.get('call_basic', True) laser_change = kwargs.get('laser_change', False) sdf_num = kwargs.get('sdf_num', 0) istart = kwargs.get('istart', 0) pathname = kwargs.get('pathname', os.path.abspath(os.getcwd())) if call_basic: dat = basic(dat) radius = dat.Radius_mid.data[0] laser_wavelength = 351.0e-9 laser_k = 2 * np.pi / laser_wavelength n_crit = 8.8e14 / laser_wavelength**2 laser_dir = -1 laser_dep = dat.Fluid_Energy_deposited_laser.data var_name = "Critical_Density" setattr(dat, var_name, new_variable(data = n_crit, units_new = "#/m^3", unit_conversion = 1, name = "Critical density")) ne_density = dat.Fluid_Number_density_electron.data crit_crossing = ne_density - n_crit quart_crit_crossing = ne_density - n_crit / 4.0 nx, ny = ne_density.shape crit_surf_ind = np.zeros(ny, dtype=int) crit_rad = np.zeros(ny) quart_crit_surf_ind = np.zeros(ny, dtype=int) quart_crit_rad = np.zeros(ny) # critical surface is chosen based on direction of laser propagation # This needs upgrading to use the output laser direction. for iy in range(0,ny): zero_crossings = np.where(np.diff(np.sign(crit_crossing[:,iy])))[0] zero_crossings = np.append(0, zero_crossings) crit_surf_ind[iy] = int(zero_crossings[laser_dir]) crit_rad[iy] = radius[crit_surf_ind[iy],iy] zero_crossings = np.where(np.diff(np.sign(quart_crit_crossing[:,iy])))[0] zero_crossings = np.append(0, zero_crossings) quart_crit_surf_ind[iy] = int(zero_crossings[laser_dir]) quart_crit_rad[iy] = radius[quart_crit_surf_ind[iy],iy] var_list = dat.track_surfaces var_name = "Critical_Surface" var_list.append(var_name) setattr(dat, var_name, new_variable(data = crit_rad, index = crit_surf_ind, units_new = dat.Grid_Grid.units_new, unit_conversion = dat.Grid_Grid.unit_conversion, name = "Location of critical surface")) var_name = "Critical_Surface_quarter" var_list.append(var_name) setattr(dat, var_name, new_variable(data = quart_crit_rad, index = quart_crit_surf_ind, units_new = dat.Grid_Grid.units_new, unit_conversion = dat.Grid_Grid.unit_conversion, name = "Location of quarter critical surface")) setattr(dat, "track_surfaces", var_list) # Variables that change in time and space var_list = dat.variables var_name = "Laser_Energy_per_step" var_list.append(var_name) if sdf_num == istart: las_dep_step = laser_dep elif sdf_num >= istart: SDFName=pathname+'/'+str(sdf_num-1).zfill(4)+'.sdf' dat2 = sh.getdata(SDFName,verbose=False) las_dep_step = laser_dep - dat2.Fluid_Energy_deposited_laser.data else: print('Error with laser change calculation') print('sdf_num = ', sdf_num, ' and the minimum = ', istart) setattr(dat, var_name, new_variable(data = las_dep_step, grid = dat.Grid_Grid, units_new = "J/kg", unit_conversion = 1, name = "Laser Energy Deposited")) var_name = "Fluid_Number_density_electron_per_critical" var_list.append(var_name) ne_per_crit = ne_density / n_crit setattr(dat, var_name, new_variable(data = ne_per_crit, grid = dat.Grid_Grid, units_new = '$n_{crit}$', unit_conversion = 1, name = "Electron number density")) var_name = "Fluid_Density_scale_length" var_list.append(var_name) grad_ne_density = gradient_function(ne_density, dat.Grid_Grid_mid.data) density_scale_length = np.zeros(dat.Grid_Grid_mid.data[0].shape) density_scale_length[1:-1,1:-1] = abs(ne_density[1:-1,1:-1] \ / (grad_ne_density[1:-1,1:-1] + small_number)) # Remeber unit conversions are applied after!! max_val = 1e-2 density_scale_length = np.where(density_scale_length < max_val, density_scale_length, 0.0) setattr(dat, var_name, new_variable(data = density_scale_length, grid = dat.Grid_Grid, units_new = dat.Grid_Grid.units_new, unit_conversion = dat.Grid_Grid.unit_conversion, name = "Density Scale length $l_n$")) setattr(dat, "variables", var_list) # variables that only change in time var_list = dat.variables_time var_name = "Laser_Energy_Total_Deposited" var_list.append(var_name) tot_laser_dep = np.sum(np.sum(dat.Cell_Mass.data * laser_dep)) setattr(dat, var_name, new_variable(data = tot_laser_dep, units_new = 'kJ', unit_conversion = 1.0e-3, name = "Total laser energy deposited")) setattr(dat, "variables_time", var_list) return dat
import sdf_helper as sh import matplotlib.pyplot as plt import numpy as np from collections import OrderedDict # %% {"attributes": {"classes": [], "id": "", "n": "2"}} # home-grown module import utilities as util # %% {"attributes": {"classes": [], "id": "", "n": "3"}} # show plots in the notebook # %matplotlib inline # %% {"attributes": {"classes": [], "id": "", "n": "4"}} fname = '3d.sdf' data_3d = sh.getdata(fname, verbose=False) # %% {"attributes": {"classes": [], "id": "", "n": "5"}} # look at all the data stored in the .sdf file sh.list_variables(data_3d) # %% {"attributes": {"classes": [], "id": "", "n": "68"}} head = data_3d.Header for k, v in head.items(): print(k, v) # %% {"attributes": {"classes": [], "id": "", "n": "6"}} # normalization factor norm = 2.73092449e-22 # %% {"attributes": {"classes": [], "id": "", "n": "7"}}
def momentumEvo_and_numD_with_laser(filelist, timesteps, inpath, savepath, vMin, vMax): #============================================================================== # Convert the 2D arrays of the distfunc into 1D for each file by histogramming # the different rows into the px values. # This then forms a 2D array for the whole simulation showing the evolution #============================================================================== plt.close() allPx_integrated = [] all_Times = [] all_Pos = [] laserField_mag = [] #Creating the color map with transparency cmap1 = mpl.colors.LinearSegmentedColormap.from_list( 'my_cmap2', ['orange', 'red'], 256) cmap1._init() # create the _lut array, with rgba values alphas = np.linspace( 0, 1.0, cmap1.N + 3 ) # create your alpha array and fill the colormap with them. here it is progressive, but you can create whathever you want cmap1._lut[:, -1] = alphas for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) if f == filelist[0]: yaxis = inData.dist_fn_x_px_electron.grid.data[1] px_eV = (((yaxis**2) / (2 * m_e))) * q_e # px_MeV = px_eV / 1e6 # px_GeV = px_eV / 1e9 try: px = inData.dist_fn_x_px_electron.data.T intPx = [] for i in range(len(px[:, 0])): intPx.append(np.average(px[i])) allPx_integrated.append(intPx) all_Times.append(inData.Header.values()[9] * 1e12) all_Pos.append( np.average([ inData.dist_fn_x_px_electron.grid.data[0][0], inData.dist_fn_x_px_electron.grid.data[0][-1] ])) laserField_mag.append(np.sum(abs(inData.Electric_Field_Ez.data))) indivual_numDens_with_laser(inData, time, inpath, savepath, cmap1, vMin, vMax) except: print 'Reading error for: ' + f #Convert into np arrays for ease of use allPx_integrated = np.array(allPx_integrated) all_Times = np.array(all_Times) all_Pos = np.array(all_Pos) laserField_mag = np.array(laserField_mag) #Create folder to save into if not os.path.exists(savePath + 'Dist_evo/'): os.makedirs(savePath + 'Dist_evo/') #Save the files incase the plotting fails np.savetxt(savepath + 'Dist_evo/' + 'px_vs_t.txt', allPx_integrated, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'xaxis_t.txt', all_Times, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'yaxis_p_eV.txt', px_eV, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'xaxis_x.txt', all_Pos, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'laserField_mag.txt', laserField_mag, fmt='%.5e') createPlot_dist_evo(allPx_integrated, all_Times, yaxis, savepath, xAxis=1) createPlot_dist_evo(allPx_integrated, all_Pos, yaxis, savepath, xAxis=2) createPlot_dist_evo(allPx_integrated, np.array(range(len(all_Pos))), yaxis, savepath, xAxis=0) plotLaserFieldStrength_evo(laserField_mag, all_Times, all_Pos, savepath)
def momentumVsTime(filelist, inpath, savepath): #============================================================================== # Convert the 2D arrays of the distfunc into 1D for each file by histogramming # the different rows into the px values. # This then forms a 2D array for the whole simulation showing the evolution #============================================================================== plt.close() allPx_integrated = [] all_Times = [] all_Pos = [] laserField_mag = [] getAxis = 0 for f in filelist: inData = sh.getdata(inpath + f) if f == filelist[getAxis]: try: # 181026:: This step can fail causing the saving of # px_eV to not occur. yaxis = inData.dist_fn_x_px_electron.grid.data[1] px_eV = (((yaxis**2) / (2 * m_e))) * q_e # px_MeV = px_eV / 1e6 # px_GeV = px_eV / 1e9 except: print 'failed to get axis data from sdf: ', getAxis getAxis += 1 try: px = inData.dist_fn_x_px_electron.data.T intPx = [] for i in range(len(px[:, 0])): intPx.append(np.average(px[i])) allPx_integrated.append(intPx) all_Times.append(inData.Header.values()[9] * 1e12) all_Pos.append( np.average([ inData.dist_fn_x_px_electron.grid.data[0][0], inData.dist_fn_x_px_electron.grid.data[0][-1] ])) laserField_mag.append(np.sum(abs(inData.Electric_Field_Ez.data))) except: print 'Reading error for: ' + f #Convert into np arrays for ease of use allPx_integrated = np.array(allPx_integrated) all_Times = np.array(all_Times) all_Pos = np.array(all_Pos) laserField_mag = np.array(laserField_mag) #Create folder to save into if not os.path.exists(savePath + 'Dist_evo/'): os.makedirs(savePath + 'Dist_evo/') #Save the files incase the plotting fails np.savetxt(savepath + 'Dist_evo/' + 'px_vs_t.txt', allPx_integrated, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'xaxis_t.txt', all_Times, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'yaxis_p_eV.txt', yaxis, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'xaxis_x.txt', all_Pos, fmt='%.5e') np.savetxt(savepath + 'Dist_evo/' + 'laserField_mag.txt', laserField_mag, fmt='%.5e') createPlot_dist_evo(allPx_integrated, all_Times, yaxis, savepath, xAxis=1) createPlot_dist_evo(allPx_integrated, all_Pos, yaxis, savepath, xAxis=2) createPlot_dist_evo(allPx_integrated, np.array(range(len(all_Pos))), yaxis, savepath, xAxis=0) plotLaserFieldStrength_evo(laserField_mag, all_Times, all_Pos, savepath)
def hot_electron(dat, *args, **kwargs): """ """ laser_change = kwargs.get('laser_change', False) sdf_num = kwargs.get('sdf_num', 0) istart = kwargs.get('istart', 0) pathname = kwargs.get('pathname', os.path.abspath(os.getcwd())) electron_dep = dat.Fluid_Energy_deposited_hot_electron.data # Variables that change in time and space var_list = dat.variables var_name = "Electron_energy_per_step" var_list.append(var_name) if sdf_num == istart: electron_dep_step = electron_dep dt = dat.Header.get('time') elif sdf_num >= istart: SDFName=pathname+'/'+str(sdf_num-1).zfill(4)+'.sdf' dat2 = sh.getdata(SDFName,verbose=False) electron_dep_step = electron_dep \ - dat2.Fluid_Energy_deposited_hot_electron.data dt = dat.Header.get('time') - dat2.Header.get('time') else: print('Error with electron change calculation') print('sdf_num = ', sdf_num, ' and the minimum = ', istart) setattr(dat, var_name, new_variable(data = electron_dep_step, grid = dat.Grid_Grid, units_new = "J/kg", unit_conversion = 1, name = "Hot Electron Energy Deposited")) var_name = "Electron_Energy_per_cell" var_list.append(var_name) electron_dep_cell = electron_dep_step * dat.Cell_Mass.data setattr(dat, var_name, new_variable(data = electron_dep_cell, grid = dat.Grid_Grid, units_new = "J", unit_conversion = 1, name = "Hot Electron Energy per Cell")) var_name = "Electron_Power_per_volume" var_list.append(var_name) if dt < small_number: dt = 1.0 electron_pwr_per_vol = electron_dep_step * dat.Cell_Mass.data \ / dat.Fluid_Volume_rz.data / dt setattr(dat, var_name, new_variable(data = electron_pwr_per_vol, grid = dat.Grid_Grid, units_new = "W/m$^3$", unit_conversion = 1, name = "Hot Electron Power Per Volume")) setattr(dat, "variables", var_list) # variables that only change in time var_list = dat.variables_time var_name = "Hot_Electron_Power_Total_Deposited" var_list.append(var_name) tot_ele_dep = np.sum(np.sum(electron_dep_step * dat.Cell_Mass.data)) / dt setattr(dat, var_name, new_variable(data = tot_ele_dep, units_new = 'TW', unit_conversion = 1.0e-12, name = "Total Hot Electron Power Deposited")) var_name = "Hot_Electron_Energy_Total_Deposited" var_list.append(var_name) tot_electron_dep = np.sum(np.sum(dat.Cell_Mass.data * electron_dep)) setattr(dat, var_name, new_variable(data = tot_electron_dep, units_new = 'kJ', unit_conversion = 1.0e-3, name = "Total Hot Electron Energy Deposited")) setattr(dat, "variables_time", var_list) return dat
def pxpySpectrum(sdf_list, simTimeSteps, scratchPath, savePath): for f, time in zip(sdf_list, simTimeSteps): inData = sh.getdata(scratchPath + f) create_pxpy_plot(inData, time, scratchPath, savePath)
def electricField(filelist, timesteps, inpath, savepath): for f, time in zip(filelist, timesteps): inData = sh.getdata(inpath + f) indivual_eField(inData, time, inpath, savepath)