diff --git a/src/mcelectron-analysis/.DS_Store b/src/mcelectron-analysis/.DS_Store new file mode 100644 index 0000000..39ff1a2 Binary files /dev/null and b/src/mcelectron-analysis/.DS_Store differ diff --git a/src/mcelectron-analysis/._.DS_Store b/src/mcelectron-analysis/._.DS_Store new file mode 100644 index 0000000..9ad849c Binary files /dev/null and b/src/mcelectron-analysis/._.DS_Store differ diff --git a/src/mcelectron-analysis/._science.mplstyle b/src/mcelectron-analysis/._science.mplstyle new file mode 100644 index 0000000..b326a5c Binary files /dev/null and b/src/mcelectron-analysis/._science.mplstyle differ diff --git a/src/mcelectron-analysis/.gitignore b/src/mcelectron-analysis/.gitignore new file mode 100644 index 0000000..93d9728 --- /dev/null +++ b/src/mcelectron-analysis/.gitignore @@ -0,0 +1,7 @@ +*.pyc +**/.ipynb_checkpoints + + +__pycache__/ +kalinka/ +local/ diff --git a/src/mcelectron-analysis/README.md b/src/mcelectron-analysis/README.md new file mode 100644 index 0000000..cf68596 --- /dev/null +++ b/src/mcelectron-analysis/README.md @@ -0,0 +1,3 @@ +# mcelectron analysis + +Toolbox for analysing output of monte carlo simulation program mcelectron. \ No newline at end of file diff --git a/src/mcelectron-analysis/data/.DS_Store b/src/mcelectron-analysis/data/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/src/mcelectron-analysis/data/.DS_Store differ diff --git a/src/mcelectron-analysis/data/._.DS_Store b/src/mcelectron-analysis/data/._.DS_Store new file mode 100644 index 0000000..9ad849c Binary files /dev/null and b/src/mcelectron-analysis/data/._.DS_Store differ diff --git a/src/mcelectron-analysis/data/rw_measurement_data.csv b/src/mcelectron-analysis/data/rw_measurement_data.csv new file mode 100644 index 0000000..cb3a4c2 --- /dev/null +++ b/src/mcelectron-analysis/data/rw_measurement_data.csv @@ -0,0 +1,41 @@ +,U,I,I_std +1,-1.9991091937935344,1.2166203931623782e-08,6.36303454713155e-10 +2,-1.876298068477256,6.3068156199526765e-09,2.120461759353077e-09 +3,-1.7564608660221521,9.626794416391017e-09,2.68274333378029e-09 +4,-1.6567380680485375,7.608550384682487e-09,2.6044187318808874e-09 +5,-1.5335977850461564,7.534252744070361e-09,3.2518391830280467e-09 +6,-1.4990061307758156,1.0004679319071542e-08,5.339021006533564e-10 +7,-1.3366297661347852,6.920656490420737e-09,1.865070796023936e-09 +8,-1.2435487078195941,7.399433351621499e-09,1.1311354967346132e-09 +9,-1.1987629681432306,7.417486610702171e-09,5.17494846227362e-10 +10,-1.098761425146385,6.076986623313511e-09,8.279563121951735e-10 +11,-0.9731874472594995,4.310479581644101e-09,7.975915838128017e-10 +12,-0.8731437874982264,2.818882747946249e-09,8.102684198698743e-10 +13,-0.7731030275467783,1.3274100596203526e-09,5.31766769725636e-10 +14,-0.6733122580560585,-2.289944119908189e-10,6.029046655271179e-10 +15,-0.5736243719797962,-2.0041152867954264e-09,7.361081440308373e-10 +16,-0.47339005622649943,-3.808601326045721e-09,9.537590819978387e-10 +17,-0.3734552722715769,-5.3275657997260266e-09,8.011045941185899e-10 +18,-0.273933897891733,-6.3863252101392635e-09,6.488354377990981e-10 +19,-0.17367006243848632,-5.616675112049569e-09,1.3986807564980629e-09 +20,-0.07362819687976675,-1.1426986924270514e-08,2.6300619297719786e-09 +21,0.02671888696714803,-1.837966300059994e-08,2.106062816970831e-09 +22,0.12637500975309027,-2.3085353008963608e-08,1.5247376943871127e-09 +23,0.22626576445514812,-2.5364324512536667e-08,1.601967948170824e-09 +24,0.32572339188253635,-2.853927736988043e-08,1.7100408734106387e-09 +25,0.42575558679063613,-3.078163687580569e-08,1.990341426230099e-09 +26,0.5016042244177643,-3.234834034011377e-08,1.7907337024113099e-09 +27,0.6012651450774272,-3.422500481591576e-08,1.7437337489994397e-09 +28,0.7494934921920171,-3.604843880457521e-08,1.6707994780449173e-09 +29,0.8967653629540302,-3.704051065509184e-08,1.8346688222531996e-09 +30,0.9988023143222509,-3.7959550405806046e-08,1.7415665828162883e-09 +31,1.058887818980386,-3.654372522297646e-08,2.8658599359223354e-09 +32,1.1020411865556796,-3.9100482635030964e-08,1.861155990499635e-09 +33,1.2017259985052957,-3.9772119927207205e-08,2.2453655491995256e-09 +34,1.3019179240233507,-4.034956169912558e-08,1.904710006492966e-09 +35,1.4019058448502388,-4.11301634650381e-08,2.1174743895635936e-09 +36,1.5013101248468452,-4.2193420777181695e-08,2.172082124017618e-09 +37,1.6753394055803505,-3.782596777678172e-08,3.78253160941066e-09 +38,1.7522850140218245,-4.517073796320607e-08,1.5983887580492326e-09 +39,1.830937535777858,-4.141280707626774e-08,4.8948978206484686e-09 +40,2.001046343389321,-4.6674566031331524e-08,2.243214871448842e-09 diff --git a/src/mcelectron-analysis/functions/.DS_Store b/src/mcelectron-analysis/functions/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/src/mcelectron-analysis/functions/.DS_Store differ diff --git a/src/mcelectron-analysis/functions/._.DS_Store b/src/mcelectron-analysis/functions/._.DS_Store new file mode 100644 index 0000000..9ad849c Binary files /dev/null and b/src/mcelectron-analysis/functions/._.DS_Store differ diff --git a/src/mcelectron-analysis/functions/IO/h5_load_particles.py b/src/mcelectron-analysis/functions/IO/h5_load_particles.py new file mode 100644 index 0000000..b8a2e6c --- /dev/null +++ b/src/mcelectron-analysis/functions/IO/h5_load_particles.py @@ -0,0 +1,76 @@ +import h5py +import os +import glob + +import pandas as pd +import numpy as np + +def load_part(h5_file, species=None, z=None): + if z is None: + if species is None: + return load_part2(h5_file) + else: + return load_part1(h5_file, species) + else: + return load_part0(h5_file, species, z) + +def load_part2(h5_file): + dfs = dict() + for species in list(h5_file['Particles'].keys()): + dfs.update({species:load_part1(h5_file, species)}) + return (dfs) + +def load_part1(h5_file, species): + dfs = dict() + for z in list(h5_file['Particles'][species].keys()): + dfs.update({z:load_part(h5_file, species, z)}) + return (dfs) + +def load_part0(h5_file, species, z): + df = pd.DataFrame(h5_file['Particles'][species][z][:]) + append_vAbs_ms(df) + append_Ekin_eV(df, species) + return (df) + +def load_from_h5 (h5path): + groupname = 'Particles' + typename = 'e-' + f = h5py.File(h5path,'r') + g = f[groupname] + keys = list(g.keys())[1:] + dfs = dict() + for key in keys: + z = float(key) + df = pd.DataFrame(g[key][typename][:]) + df = append_Ekin_eV(df) + df = append_vAbs_ms(df) + dfs.update({z:df}) + return dfs + + +def append_vAbs_ms(df): + vAbs_ms = np.sqrt(df['vx_ms']**2+df['vy_ms']**2+df['vz_ms']**2) + df.insert(len(df.columns),'vAbs_ms',vAbs_ms) + return df + +def get_mass_eV(species): + mT_eV = 2.8094320212e9 + if species == 'e-': + return 0.510999e6 + if species == 'T+': + return mT_eV + if species == 'T2+': + return 2*mT_eV + if species == 'T3+': + return 3*mT_eV + +def append_Ekin_eV(df, species): + c_ms = 3e8 + m_eV = get_mass_eV(species) + gamma = (1-(df['vAbs_ms']/c_ms)**2)**(-0.5) + Ekin_eV = (gamma-1)*m_eV + df.insert(len(df.columns),'Ekin_eV',Ekin_eV) + return df + +def stackedDf_from_dfs(datas): + return pd.concat(list(datas.values()), ignore_index=True) diff --git a/src/mcelectron-analysis/functions/IO/h5_merge.py b/src/mcelectron-analysis/functions/IO/h5_merge.py new file mode 100644 index 0000000..39fe7a5 --- /dev/null +++ b/src/mcelectron-analysis/functions/IO/h5_merge.py @@ -0,0 +1,77 @@ +import numpy as np +import pandas as pd +import os +import glob +import h5py + +# Merges all h5_files to new h5_file +def merge_h5s(import_path, out_file_path): + in_paths = get_h5paths(import_path) + h5_ins = get_h5_in(in_paths) + h5_out = h5py.File(out_file_path,'w-') + merge_particles(h5_ins, h5_out) + merge_populations(h5_ins, h5_out) + close_h5_ins(h5_ins) + h5_out.close() + +def get_h5paths(import_path): + if not (os.path.isdir(import_path)): + raise NotADirectoryError('import_path is not a valid path. \n rdPath = %s ' % (import_path)) + if not import_path.endswith('/'): + import_path = import_path + '/' + h5paths = glob.glob(import_path + '*.h5') + h5paths.sort() + return h5paths + +def get_h5_in(in_paths): + h5_in = [] + for file_path in in_paths: + h5_in.append (h5py.File(file_path,'r')) + return h5_in + +def merge_particles(h5_ins, h5_out): + h5g_part = h5_ins[0]['Particles'] + h5_out.create_group('Particles') + print ('Status: Started merging Particles.') + for species in list(h5g_part.keys()): + h5_out.create_group('/Particles/' + species) + h5g_spec = h5g_part[species] + for z in list(h5g_spec.keys()): + path_to_ds = '/Particles/' + species + '/' + z + initialized = False + for h5_in in h5_ins: + if initialized == False: + data = h5_ins[0][path_to_ds][:] + if data.shape[0] != 0: + ds = h5_out.create_dataset(path_to_ds, data=data, compression="gzip", chunks=True, maxshape=(None,)) + initialized = True + else: + data = h5_in[path_to_ds][:] + if data.shape[0] != 0: + ds.resize(ds.shape[0] + data.shape[0], axis = 0) + ds[-data.shape[0]:] = data + +def get_cpu_num(in_path): + l_pos = in_path.rfind('_')+1 + r_pos = in_path.rfind('.') + return (in_path[l_pos:r_pos]) + +def merge_populations(h5_ins, h5_out): + h5g_pop = h5_ins[0]['Populations'] + h5_out.create_group('Populations') + print ('Status: Started merging Populations.') + + for species in list(h5g_pop.keys()): + h5_out.create_group('/Populations/' + species) + h5g_spec = h5g_pop[species] + #for h5_in in h5_ins: + h5_in = h5_ins[0] + path_to_group = '/Populations/' + species + '/' + get_cpu_num(h5_in.filename) + h5_out.create_group(path_to_group) + for ds in list(h5g_spec.keys()): + data = h5_in['/Populations/' + species + '/' + ds] + h5_out.create_dataset(path_to_group + '/' + ds, data=data, compression="gzip", chunks=True, maxshape=(None,)) + +def close_h5_ins(h5_ins): + for h5_in in h5_ins: + h5_in.close() diff --git a/src/mcelectron-analysis/functions/archive/calc_current.py b/src/mcelectron-analysis/functions/archive/calc_current.py new file mode 100644 index 0000000..710b0cb --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/calc_current.py @@ -0,0 +1,84 @@ +import pandas as pd +import numpy as np +import os + +def get_Z(species): + return species.count('+') - species.count('-') + +def calc_dfs_curs(dfs_part, n_rbins, time_s): + e_C = 1.602176462e-19 + dfs_curs = dict() + for species in list(dfs_part.keys()): + dfs_spec = dfs_part[species] + if (dfs_spec): + Q_C = get_Z(species)*e_C + dfs_curs.update({species : calc_df_cur(dfs_spec, Q_C, n_rbins, time_s)}) + return dfs_curs + +def calc_df_cur(dfs_spec, Q_C, n_rbins, time_s): + df_cur = pd.DataFrame(columns=['z_m', 'r_mid_m', 'r_low_m', 'r_up_m', 'j_Am2', 'jpos_Am2', 'jneg_Am2']) + for z_str in list(dfs_spec.keys()): + df_z = dfs_spec[z_str] + z = float(z_str) + r_max = 0.045 + r_edges_m = np.linspace(0, r_max, n_rbins+1) + r_mids_m = (r_edges_m[:-1] + r_edges_m[1:])/2 + As_m2 = np.pi*(pow(r_edges_m[1:],2) - pow(r_edges_m[:-1],2)) + + r_m = np.sqrt(df_z.x_m**2 + df_z.y_m**2) + for i in np.arange(r_mids_m.shape[0]): + cond = (r_m > r_edges_m[i]) & (r_m < r_edges_m[i+1]) + df_temp = df_z[cond] + N_pos = df_temp[df_temp.vz_ms > 0].shape[0] + N_neg = df_temp[df_temp.vz_ms < 0].shape[0] + j_pos = Q_C*N_pos/As_m2[i]/time_s + j_neg = Q_C*N_neg/As_m2[i]/time_s + j = j_pos - j_neg + df_cur = df_cur.append({'z_m':z, 'r_mid_m':r_mids_m[i], 'r_low_m':r_edges_m[i], 'r_up_m':r_edges_m[i+1], \ + 'j_Am2':j, 'jpos_Am2':j_pos, 'jneg_Am2':j_neg}, ignore_index=True) + return df_cur + +def get_max_cur(dfs_curs): + max_cur = 0 + for species in dfs_curs: + df_temp = dfs_curs[species] + if df_temp.j_Am2.abs().max() > max_cur: + max_cur = df_temp.j_Am2.abs().max() + return max_cur + +def plot_cur_means(dfs_curs, ax): + if type(dfs_curs) == dict: + for species in dfs_curs: + df_mean = dfs_curs[species].groupby('z_m', as_index=False).mean() + ax.plot(df_mean['z_m'], df_mean['j_Am2'], label = species) + ax.legend(loc = 'best') + else: + df_mean = dfs_curs.groupby('z_m', as_index=False).mean() + ax.plot(df_mean['z_m'], df_mean['j_Am2']) + + ax.set_xscale('linear') + ax.set_yscale('linear') + ax.set_xlabel('z (m)') + ax.set_ylabel(r'$j_z \mathrm{(Am^{-2})}$') + return + +def calc_mesh_data(df_cur): + df_cur = df_cur.sort_values(['z_m', 'r_mid_m'], axis=0, + ascending=True) + z = np.unique(df_cur.z_m) + r = np.unique(df_cur.r_mid_m) + j = np.array(df_cur['j_Am2']).reshape((len(z), len(r))) + j = np.swapaxes(j,0,1) + z_step = np.mean((z[1:] - z[:-1])/2) + z_edges = np.concatenate((np.array([z[0]]), z+z_step)) + r_step = np.mean((r[1:] - r[:-1])/2) + r_edges = np.concatenate((np.array([r[0]]), r+r_step)) + return [z_edges, r_edges, j] + +def plot_mesh(z, r, j, max_cur, ax, fig): + c = ax.pcolormesh(z, r, j, cmap='seismic', vmin = -max_cur, vmax = max_cur) + ax.set_xlabel('z (m)') + ax.set_ylabel('r (m)') + cbar = fig.colorbar(c) + cbar.ax.set_ylabel(r'$j_z \mathrm{(Am^{-2})}$') + return \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/archive/calc_histogram.py b/src/mcelectron-analysis/functions/archive/calc_histogram.py new file mode 100644 index 0000000..4c5bf53 --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/calc_histogram.py @@ -0,0 +1,121 @@ +import pandas as pd +import numpy as np + +from h5_loadpart import load_part + +# Histograms +me_eV = 0.511e6 +c_ms = 3e8 +A_m2 = np.pi*0.045**2 +lower_edge = 1e-5 +upper_edge = 2e4 + +def calc_histogram(dfs_part, simulation_time_s, number_points = 200, binning = 'log'): + if type(dfs_part) == dict: + if type(dfs_part[list(dfs_part.keys())[0]]) == dict: + hists = dict() + for species in dfs_part: + dfs_z = dfs_part[species] + z_dict = dict() + for z in dfs_z: + df = dfs_z[z] + hist = calc_histogram0(df, simulation_time_s, number_points, binning) + z_dict.update({z:hist}) + hists.update({species:z_dict}) + return hists + else: + hists = dict() + for z in dfs_part: + df = dfs_part[z] + hist = calc_histogram0(df, simulation_time_s, number_points, binning) + hists.update({z:hist}) + return hists + else: + return calc_histogram0(dfs_part, simulation_time_s, number_points, binning) + +def calc_histogram0(df, simulation_time_s, number_points = 200, binning = 'log'): + if binning == 'log': + bins = 10**np.linspace(np.log10(lower_edge), np.log10(upper_edge), number_points) + E_pot = -1.5 + def calc_bin_mid(bin_edges): + return np.exp ( (np.log(bin_edges[1:]) + np.log(bin_edges[:-1]))/2) + if binning == 'linear': + bins = np.linspace(lower_edge, upper_edge, number_points) + E_pot = -0.5 + def calc_bin_mid(bin_edges): + return (bin_edges[1:] + bin_edges[:-1])/2 + + + dNdEscale, bin_edges = np.histogram(df.Ekin_eV, bins=bins) + bin_mids = calc_bin_mid(bin_edges) + + const1 = np.sqrt(me_eV/2)/A_m2/simulation_time_s/c_ms + dn_dE_m = const1*pow(bin_mids, E_pot)*dNdEscale + res = pd.DataFrame({'lower_edge_eV' : bin_edges[0:-1], 'upper_edge_eV' : bin_edges[1:], 'bin_mid_eV' : bin_mids, 'dn_dE_m3eV' : dn_dE_m}) + return res + +def calc_simulation_time_s (number_decays, max_density_mid_m3 = 1e21): + r_m = 0.045 + l_m = 10 + decay_const_s = np.log(2)/3.88524e+8 + + V_m3 = np.pi*r_m**2*l_m + number_molecules = max_density_mid_m3*V_m3/2 + activity_s = number_molecules*decay_const_s + return (number_decays/activity_s) + +def plot_hist(hist, ax): + if type(hist) == dict: + for z in hist: + ax.plot(hist[z].bin_mid_eV, hist[z].dn_dE_m3eV, label = z) + ax.legend(loc = 'best') + else: + ax.plot(hist.bin_mid_eV, hist.dn_dE_m3eV) + + ax.set_xscale('log') + ax.set_yscale('log') + ax.set_xlabel('energy (eV)') + ax.set_ylabel(r'density ($m^{-3}$)') + return + +def plot_fermi(ax, scale): + me_eV = 0.511e6 + decay_constant = 1.2072343416696292e-47 + end_point_eV = 18.574e3 + Z = 2 + normation = 1.2078059173513103e-24 + + def beta_dist(E_eV): + if E_eV > end_point_eV: + return 0. + gamma = 1+E_eV/me_eV + beta = np.sqrt(1 - pow(gamma,-2)) + eta =Z/beta/137. + fermi_function = 2*np.pi*eta/(1-np.exp(-2*np.pi*eta)); + + p_eV = np.sqrt(E_eV*E_eV + 2 * E_eV * me_eV) + return decay_constant*fermi_function*p_eV*(E_eV+me_eV)*pow(end_point_eV-E_eV,2)/normation + beta_dist = np.vectorize(beta_dist) + + E_eV = bins = 10**np.linspace(np.log10(1e1), np.log10(2e4), 1000) + n = beta_dist(E_eV)*scale + ax.plot(E_eV, n, label = 'beta decay') + return + +def calc_generations(df): + id_string = 'Id' + pid_string = 'ParentId' + level_string = 'Level' + + Id_data = df[[id_string,pid_string]] + Id_data = Id_data.drop_duplicates() + Id_data = Id_data.reset_index(drop=True) + Id_data.insert(len(Id_data.columns),level_string,-1) + Id_data.loc[Id_data[id_string] == Id_data[pid_string],level_string] = 0 + + level = 0 + while not( Id_data[Id_data[level_string] == level].empty): + parentsatlevel = Id_data[Id_data[level_string] == level][id_string] + Id_data.loc[(Id_data[pid_string].isin(parentsatlevel)) & (Id_data[pid_string] != Id_data[id_string]),level_string] = level + 1 + level = level + 1 + return Id_data \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/archive/calc_rwcurrent.py b/src/mcelectron-analysis/functions/archive/calc_rwcurrent.py new file mode 100644 index 0000000..0a1f2de --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/calc_rwcurrent.py @@ -0,0 +1,87 @@ +import pandas as pd +import numpy as np +import os + +from h5_loadpart import load_part + +def calc_rwcurrents(h5_file, n_decays = None, time_s = None, Vrange = [-2,2], number_points = 500): + if (n_decays == None and time_s == None): + raise TypeError('No time specified') + elif time_s == None: + time_s = calc_simulation_time_s(n_decays) + + rwdata = load_rwdata(h5_file) + temp = dict() + for species in rwdata: + Z = get_Z(species) + cur = calcCurrent(rwdata[species], time_s, Vrange, Z, number_points = number_points) + temp.update({species:cur}) + + U = temp[list(temp.keys())[0]]['U'] + currents = pd.DataFrame({'U': U}) + for key in temp: + currents[key] = temp[key].I + currents['tot'] = currents.iloc[:,1:].sum(axis=1) + return currents + +def calc_simulation_time_s (number_decays, max_density_mid_m3 = 1e21): + r_m = 0.045 + l_m = 10 + decay_const_s = np.log(2)/3.88524e+8 + + V_m3 = np.pi*r_m**2*l_m + number_molecules = max_density_mid_m3*V_m3/2 + activity_s = number_molecules*decay_const_s + return (number_decays/activity_s) + +def load_rwdata(h5_file): + h5_file['Particles'] + rwdata = dict() + for species in list(h5_file['Particles'].keys()): + try: + df = load_part(h5_file, species=species, z='-3.000000') + rwdata.update({species:df}) + except: + pass + return rwdata + +def get_Z(species): + return species.count('+') - species.count('-') + +def calcCurrent(df, simulation_time_s, Vrange, Z, number_points = 500): + Q_C = Z*1.602176462e-19 + + minV = Vrange[0] + maxV = Vrange[1] + + U = np.linspace(minV, maxV, number_points) + I = np.array([]) + + for u in U: + condition = Z*u < df.Ekin_eV + number_hitting = df[condition].shape[0] + I = np.append(I, number_hitting*Q_C/simulation_time_s) + return pd.DataFrame({'U':U,'I':I}) + +def plot_exp_rw(ax): + data_path = os.path.dirname(__file__) + '/../../data/rw_measurement_data.csv' + meas_df = pd.read_csv(data_path).iloc[:,1:] + ax.errorbar(meas_df.U, meas_df.I*1e9, yerr=meas_df.I_std*1e9, label = 'measurement') + return + +def plot_rw_df(rw_df, ax): + species_list = ['T+', 'T2+', 'T3+', 'e-', 'tot'] + for species in species_list: + try: + ax.plot(rw_df.U, rw_df[species]*1e9, label = species) + except: + pass + + ax.set_xscale('linear') + ax.set_yscale('linear') + ax.set_xlabel('voltage (V)') + ax.set_ylabel('current (nA)') + ax.legend(loc = 'best') + return + + diff --git a/src/mcelectron-analysis/functions/archive/h5_loadpop.py b/src/mcelectron-analysis/functions/archive/h5_loadpop.py new file mode 100644 index 0000000..a4217e0 --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/h5_loadpop.py @@ -0,0 +1,81 @@ +import h5py +import numpy as np +import pandas as pd + +def load_pop(h5_file, typename = None, cpu = None): + if cpu == None: + cpu = list(h5_file['Populations'][list(h5_file['Populations'].keys())[0]].keys())[0] + + if typename == None: + return load_pop1(h5_file, cpu = cpu) + else: + return load_pop0(h5_file, typename = typename, cpu = cpu) + +def load_pop1(h5_file, cpu = None): + if cpu == None: + cpu = list(h5_file['Populations'][list(h5_file['Populations'].keys())[0]].keys())[0] + + dfs = dict() + for species in list(h5_file['Populations'].keys()): + df = load_pop0(h5_file, species, cpu = cpu) + dfs.update({species:df}) + + if species == list(h5_file['Populations'].keys())[0]: + n_tot_m3 = np.zeros(df.shape[0]) + if '+' in species: + last_plus_species = species + n_tot_m3 = n_tot_m3 + df.n_m3.copy() + + df = dfs[last_plus_species] + df.n_m3 = n_tot_m3 + dfs.update({'tot':df}) + return dfs + +def load_pop0(h5_file, typename, cpu = None): + if cpu == None: + cpu = list(h5_file['Populations'][list(h5_file['Populations'].keys())[0]].keys())[0] + + df = pd.DataFrame(h5_file['Populations'][typename][cpu][typename][:]) + df_meta = pd.DataFrame(h5_file['Populations'][typename][cpu][typename + '_meta_data'][:]) + df_meta = append_V_m3(df_meta) + V_m3 = get_V_m3(df_meta) + df = append_n_m3(df, V_m3) + df = append_from_meta(df, df_meta) + return (df) + +def append_V_m3 (df_meta): + V_m3 = (df_meta.r_max_m**2-df_meta.r_min_m**2)*np.pi*(df_meta.z_max_m-df_meta.z_min_m) + df_meta.insert(len(df_meta.columns),'V_m3',V_m3) + return df_meta + +def get_V_m3(df_meta): + r_bins = np.unique(df_meta.r_bin) + V_m3 = np.zeros(r_bins.size) + for i in np.arange(r_bins.size): + V_m3[i] = np.mean (df_meta[df_meta.r_bin==r_bins[i]].V_m3) + return V_m3 + +def append_n_m3 (df, V_m3): + n_m3 = df.cum_time/df.phys_time_s/V_m3[df.r_bin]-df.offset + df['n_m3'] = n_m3 + df['n_m3'].fillna(0., inplace=True) + return df + +def append_from_meta(df, df_meta): + df_length = df.shape[0] + bin_list = ['z_bin','r_bin','phi_bin','E_bin'] + min_list = ['z_min_m', 'r_min_m', 'phi_min', 'E_min_eV'] + max_list = ['z_max_m', 'r_max_m', 'phi_max', 'E_max_eV'] + for i in np.arange(4): + i_bin = bin_list[i] + i_min = min_list[i] + i_max = max_list[i] + info_df = df_meta.groupby(i_bin, as_index=False).mean() + mins = np.zeros(df_length) + maxs = np.zeros(df_length) + for row in range(0, info_df.shape[0]): + mins[df[i_bin] == info_df[i_bin][row]] = info_df[i_min][row] + maxs[df[i_bin] == info_df[i_bin][row]] = info_df[i_max][row] + df[i_min] = mins + df[i_max] = maxs + return df \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/archive/old_plot_script.ipynb b/src/mcelectron-analysis/functions/archive/old_plot_script.ipynb new file mode 100644 index 0000000..b028545 --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/old_plot_script.ipynb @@ -0,0 +1,558 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import os as os\n", + "\n", + "import scipy.optimize as optimization\n", + "import glob as glob\n", + "import h5py as h5py\n", + "import numpy as np\n", + "from scipy.signal import argrelextrema" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "import seaborn as sns\n", + "\n", + "NEJM = sns.color_palette(palette = ['#bc3c29',\n", + " '#0072bf',\n", + " '#e18727',\n", + " '#20854e',\n", + " '#7876b1',\n", + " '#6f99ad',\n", + " '#ffdc91',\n", + " '#ee4c97'])\n", + "sns.set(\n", + " context='paper', \n", + " style='white', \n", + " palette=NEJM, \n", + " font='sans-serif', \n", + " font_scale=1, \n", + " color_codes=False, \n", + " rc = {'figure.dpi' : 100,\n", + " 'text.usetex' : True,\n", + " 'axes.labelsize' : 10,\n", + " 'xtick.labelsize' : 10, \n", + " 'ytick.labelsize' : 10,\n", + " 'legend.fontsize' : 10,\n", + " 'xtick.bottom' : True, \n", + " 'xtick.minor.bottom' : False,\n", + " 'ytick.left' : True,\n", + " 'ytick.minor.left' : False\n", + " })" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "ERROR:root:File `'../functions/particles/load_histograms.py'` not found.\n", + "ERROR:root:File `'../functions/populations/h5_loadpop.py'` not found.\n" + ] + } + ], + "source": [ + "%run \"../functions/particles/load_histograms.py\"\n", + "%run \"../functions/populations/h5_loadpop.py\"" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'load_pop' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Load dfs with population data and create df with sum over E_bins\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdfs_pop\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mload_pop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'load_pop' is not defined" + ] + } + ], + "source": [ + "# Load dfs with population data and create df with sum over E_bins\n", + "dfs_pop = load_pop(f)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'sum_E_bins' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdfs_pop_E_summed\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msum_E_bins\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_pop\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'sum_E_bins' is not defined" + ] + } + ], + "source": [ + "dfs_pop_E_summed = sum_E_bins(dfs_pop)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'calc_time_means' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Load df with meaned for each time step\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdfs_time_means\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcalc_time_means\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_pop_E_summed\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'calc_time_means' is not defined" + ] + } + ], + "source": [ + "# Load df with meaned for each time step\n", + "dfs_time_means = calc_time_means(dfs_pop_E_summed)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'plot_time_means' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Plot time expansion\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mplot_time_means\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_time_means\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Averaged densities time development.'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;31m#ax.axvline(x=calc_simulation_time_s(1000),linewidth=2, color='black')\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'plot_time_means' is not defined" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXgAAAD8CAYAAAB9y7/cAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9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39HR+64+blxvcvHUG/NUposrl0n+keTXqur8W+6cuW8Y+OwxA/+grzloZte/63n3k82Zvzp6UVUXU8xazztn/nXxITfTFZl+dj7pPLcvXiX5+/T++EuS7+4fu/t8g8BjBt7XHNya2xepqlfruHc+ybrD1dG/TScVn+fmjd7Z3Ovi6s74v466dcc1+x5ZW5+IPd6mHd90gPPDnd/a9v4GgUf9HPz00b/rbHysqar+f30l7JfGu9q2L6b/Uf/Mzdzi8yR/MU3xfdjxPfJpGm/9290O++L1NP68ey8OxYVOAE05yQrQlMADNCXwAE0JPEBTAg/QlMADNCXwAE0JPEBT/wEb9i76q/ukGwAAAABJRU5ErkJggg==\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "# Plot time expansion\n", + "fig, ax = plt.subplots()\n", + "plot_time_means(dfs_time_means, ax)\n", + "ax.set_title('Averaged densities time development.')\n", + "#ax.axvline(x=calc_simulation_time_s(1000),linewidth=2, color='black')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'calc_z_means' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Load df with meaned values for each z_bin\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdfs_z_means\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcalc_z_means\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_pop_E_summed\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'calc_z_means' is not defined" + ] + } + ], + "source": [ + "# Load df with meaned values for each z_bin\n", + "dfs_z_means = calc_z_means(dfs_pop_E_summed)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'plot_z_means' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Plot z expansion\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mplot_z_means\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_z_means\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0maxvline\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mlinewidth\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcolor\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'black'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlinestyle\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m':'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Densities over z'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'plot_z_means' is not defined" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXgAAAD8CAYAAAB9y7/cAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAKYElEQVR4nO3cwXEb2bmG4Y+3FABLygBe/Ht6JgOGQJcykDOQl8O7co0y8EwEKk8GQ0Xge7U/CzEDycgAXrAhwiwJDZAgqPn1PFVTROM0hFYP8Kp5Go2T1WoVAPr5n6feAAAeh8ADNCXwAE0JPEBTOwW+qs62jF1U1XlVvT7cZgHwULOBr6rzJL9+ZewsScYYV0mW2/4hAOC4ZgM/xfvTV4ZfJllOt6+TnB9ouwB4oIfOwZ/mv+P/4oF/HgAH4iQrQFPPHvj4ZZLn0+3TJB83B6vqMslPD3wOAJKMMU72Wf9ega+q0zHGMsnbJD9Mdy+SXN3ZmMskl3ceuxpj3OdpAb5bVbX3Y3b5FM1Fkh+mn2vvkmSM8X5a5zzJcr0MwNM7OfaXjTmCB9hfVe09ReMkK0BTAg/QlMADNCXwAE0JPEBTAg/QlMADNCXwAE0JPEBTAg/QlMADN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PwROYCf5rk08byiz3HAXgis3PwD1FVl0l++sL9j/m0AGQ+8Mskz6fbp0k+7jM+xrhMcrl5X1Wtxhgn99jWduyLW/bFLfviln1xq6pW+z5mbormbZLFdHuR5Gp6otNt4wA8va2BH2O8T5KqOk+yXC8neTczDsATm52DH2P88oX7/rxtHICn9xRXsv7vEzznt8q+uGVf3LIvbtkXt/beFyer1d7z9vAgu179XFWvXR3N96qqzr427b3re+ixPybpaw4mO+yLV9PNP40x/nbUjTuizaufq2rxtRfxdF7nx6Nv4JHt8Lo4y/RBhjHGb0fevKPaoxeL7lPD0+v/5yR//sLYTu+h5BGnaHzNwa0d9sV5kqvpRbuYlrty9fNkx/fAX6ewL77z98hZkutp/Lrzvkg+74dPXxne+T30mHPwvubg1tzfdbFx33VuP3ra0ezVz9MRyffwkdutr4vpiPVDkowx3jT/lNouPfh5+rlovi/m7PwNAo8ZeF9zcGvr33WM8cvGr5xnSf7vWBv2jXo+v0oLc++BH5O8qKqzqnp9vM16EnPvkfe5OXL/kK8f2XKH74P/hky/dv7e/Ohk69XP39HR+64+blxvcvHUG/NUposrl0n+keTXqur8W+6cuW8Y+OwxA/+grzloZte/63n3k82Zvzp6UVUXU8xazztn/nXxITfTFZl+dj7pPLcvXiX5+/T++EuS7+4fu/t8g8BjBt7XHNya2xepqlfruHc+ybrD1dG/TScVn+fmjd7Z3Ovi6s74v466dcc1+x5ZW5+IPd6mHd90gPPDnd/a9v4GgUf9HPz00b/rbHysqar+f30l7JfGu9q2L6b/Uf/Mzdzi8yR/MU3xfdjxPfJpGm/9290O++L1NP68ey8OxYVOAE05yQrQlMADNCXwAE0JPEBTAg/QlMADNCXwAE0JPEBT/wEb9i76q/ukGwAAAABJRU5ErkJggg==\n", + "text/plain": [ + "
" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "# Plot z expansion\n", + "fig, ax = plt.subplots()\n", + "plot_z_means(dfs_z_means, ax)\n", + "ax.axvline(x=5,linewidth=1, color='black', linestyle = ':')\n", + "ax.set_title('Densities over z')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Load rw_df \n", + "rw_df = calc_rwcurrents(f, n_decays = n_decays)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%run '../functions/particles/calc_rwcurrent.py'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Plot rw current\n", + "fig, ax = plt.subplots()\n", + "plot_exp_rw(ax)\n", + "plot_rw_df(rw_df, ax)\n", + "ax.set_title('Rear wall current vs voltage')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'calc_pop_spectrum' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Load df_spec\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdf_spec\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcalc_pop_spectrum\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_pop\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'calc_pop_spectrum' is not defined" + ] + } + ], + "source": [ + "# Load df_spec\n", + "df_spec = calc_pop_spectrum(dfs_pop)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Plot Spectrum from populations data\n", + "fig, ax = plt.subplots()\n", + "plot_pop_spectrum(df_spec, ax)\n", + "ax.set_title('Energy Spectrum from Population data')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "dfs_part = load_part(f)\n", + "hists = calc_histogram(dfs_part, calc_simulation_time_s(10000))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Plot histograms\n", + "hist = hists['e-']\n", + "fig, ax = plt.subplots()\n", + "plot_fermi(ax, n_decays)\n", + "plot_hist(hist, ax)\n", + "ax.set_title('Histograms')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Calc df_curs\n", + "time_s = calc_simulation_time_s(n_decays)\n", + "n_rbins = 9\n", + "dfs_curs = calc_dfs_curs(dfs_part, n_rbins, time_s)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Plot current_means\n", + "fig, ax = plt.subplots()\n", + "plot_cur_means(dfs_curs, ax)\n", + "ax.axvline(x=5,linewidth=1, color='black', linestyle = ':')\n", + "ax.set_title('Particle density current')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "max_cur = get_max_cur(dfs_curs)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'get_max_cur' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Plot current maps\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mmax_cur\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mget_max_cur\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_curs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0ms\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdfs_curs\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mz\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mj\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcalc_mesh_data\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_curs\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'get_max_cur' is not defined" + ] + } + ], + "source": [ + "# Plot current maps\n", + "max_cur = get_max_cur(dfs_curs)\n", + "for s in dfs_curs:\n", + " [z, r, j] = calc_mesh_data(dfs_curs[s])\n", + " fig, ax = plt.subplots()\n", + " plot_mesh(z, r, j, max_cur, ax, fig)\n", + " ax.axvline(x=5,linewidth=1, color='black', linestyle = ':')\n", + " ax.set_title(s + ' current density spatially resolved')\n", + " fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'get_max_cur' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Plot ion currents\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mmax_cur\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mget_max_cur\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdfs_curs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mz_all\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mr_all\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mj_all\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'get_max_cur' is not defined" + ] + } + ], + "source": [ + "# Plot ion currents\n", + "max_cur = get_max_cur(dfs_curs)\n", + "z_all = []\n", + "r_all = []\n", + "j_all = []\n", + "for s in dfs_curs:\n", + " if s != 'e-':\n", + " [z, r, j] = calc_mesh_data(dfs_curs[s])\n", + " z_all.append(z)\n", + " r_all.append(r)\n", + " j_all.append(j)\n", + "z_mean = np.mean(z_all,axis=0)\n", + "r_mean = np.mean(r_all,axis=0)\n", + "j_sum = np.sum(j_all,axis=0)\n", + "\n", + "fig, ax = plt.subplots()\n", + "plot_mesh(z_mean, r_mean, j_sum, max_cur, ax, fig)\n", + "ax.axvline(x=5,linewidth=1, color='black', linestyle = ':')\n", + "ax.set_title('Summed Ion current density spatially resolved')\n", + "fig.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def load_rwdata(h5_file):\n", + " h5_file['Particles']\n", + " rwdata = dict()\n", + " for species in list(h5_file['Particles'].keys()):\n", + " try:\n", + " df = load_part(h5_file, species=species, z='-3.000000')\n", + " rwdata.update({species:df})\n", + " except:\n", + " pass\n", + " return rwdata" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'f' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mrw_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mload_rwdata\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mf\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'f' is not defined" + ] + } + ], + "source": [ + "rw_data = load_rwdata(f)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'rw_data' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mion_cur\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0ms\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrw_data\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mget_Z\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mion_cur\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mion_cur\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mget_Z\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mrw_data\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0ms\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'rw_data' is not defined" + ] + } + ], + "source": [ + "ion_cur = 0\n", + "for s in rw_data:\n", + " if get_Z(s) > 0:\n", + " ion_cur = ion_cur + get_Z(s)*rw_data[s].shape[0]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/src/mcelectron-analysis/functions/archive/pop_calc_mean.py b/src/mcelectron-analysis/functions/archive/pop_calc_mean.py new file mode 100644 index 0000000..43b24f3 --- /dev/null +++ b/src/mcelectron-analysis/functions/archive/pop_calc_mean.py @@ -0,0 +1,115 @@ +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt + + +def sum_E_bins(dfs): + if type(dfs) == dict: + dfs_res = dict() + for species in dfs: + df = dfs[species] + dfs_res.update({species:sum_E_bins_df(df)}) + return dfs_res + else: + return sum_E_bins_df(dfs) + +def sum_E_bins_df(df): + group_groups = ['z_bin','r_bin','phi_bin','phys_time_s'] + mean_groups = ['z_min_m','z_max_m','r_min_m','r_max_m','phi_min','phi_max'] + drop_groups = ['E_bin','E_min_eV','E_max_eV'] + + df_res = df.groupby(group_groups, as_index=False).sum() + df_res[mean_groups] = df.groupby(group_groups, as_index=False).mean()[mean_groups] + df_res = df_res.drop(drop_groups, axis = 1) + return df_res + + +def calc_time_means(dfs): + dfs_mean = dict() + for species in dfs: + df = dfs[species] + df = calc_time_mean(df) + dfs_mean.update({species:df}) + dfs_mean.update({'tot':df}) + return dfs_mean + +def calc_time_mean(df): + df_new = df.groupby('phys_time_s', as_index=False).mean() + df_new = df_new.drop(['z_bin', 'r_bin', 'phi_bin'], axis=1) + return df_new + +def plot_time_means(dfs_time_means, ax): + if type(dfs_time_means) == dict: + for species in dfs_time_means: + df = dfs_time_means[species] + ax.plot(df.phys_time_s, df.n_m3,label = species) + ax.legend(loc = 'best') + else: + ax.plot(dfs_time_means.phys_time_s, dfs_time_means.n_m3) + + ax.set_yscale('log') + ax.set_xlabel("time (s)") + ax.set_ylabel("density ($1/m^3$)") + return + + +def calc_z_means(dfs): + dfs_z_means = dict() + for species in dfs: + df = dfs[species] + dfs_z_means.update({species:calc_z_mean(df)}) + return dfs_z_means + +def calc_z_mean(df): + max_time = df.phys_time_s.max() + df_z_mean = df[df.phys_time_s == max_time].groupby('z_bin', as_index=False).mean() + df_z_mean['z_mid_m'] = (df_z_mean['z_max_m'] + df_z_mean['z_min_m'])/2 + df_z_mean = df_z_mean.drop(['r_bin','r_min_m','r_max_m','phi_bin','phi_min','phi_max'], axis = 1) + return df_z_mean + +def plot_z_means(dfs_z_means, ax): + if type(dfs_z_means) == dict: + for species in dfs_z_means: + df = dfs_z_means[species] + ax.plot(df.z_mid_m, df.n_m3, label = species) + ax.legend(loc = 'best') + else: + ax.plot(dfs_z_means.z_mid_m, dfs_z_means.n_m3) + + ax.set_yscale('log') + ax.set_xlabel("z (m)") + ax.set_ylabel("density ($1/m^3$)") + return + +def calc_pop_spectrum(dfs_pop): + df = dfs_pop['e-'] + max_time = df.phys_time_s.max() + group_groups = ['E_bin','z_bin'] + drop_groups = ['r_bin','r_min_m','r_max_m','phi_bin','phi_min','phi_max', 'offset', 'cum_time', 'phys_time_s'] + df_res = df[df.phys_time_s == max_time] + df_res = df_res.groupby(group_groups, as_index=False).mean() + df_res = df_res.drop(drop_groups, axis = 1) + df_res['E_eV'] = pow(10, np.log10(df_res['E_max_eV']) + np.log10(df_res['E_min_eV'])/2) + return df_res + +def plot_pop_spectrum(df_spec, ax, z_bin=None): + if z_bin==None or type(z_bin) == list: + if z_bin == None: + z_list = df_spec['z_bin'].unique() + else: + z_list = z_bin + + for z_bin in z_list: + df = df_spec[df_spec['z_bin']==z_bin] + zlabel = str( np.round(df.z_min_m.unique()[0],2)) + '..' + str( np.round(df.z_max_m.unique()[0],2)) + ax.plot(df.E_eV, df.n_m3/df.E_eV, label = zlabel) + ax.legend(loc = 'best',prop={'size': 6}) + else: + df = df_spec[df_spec['z_bin']==z_bin] + ax.plot(df.E_eV, df.n_m3) + + ax.set_xscale('log') + ax.set_yscale('log') + ax.set_xlabel("E (eV)") + ax.set_ylabel("density ($1/m^3$)") + return \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/particles/._get_df_part.py b/src/mcelectron-analysis/functions/particles/._get_df_part.py new file mode 100644 index 0000000..035a30b Binary files /dev/null and b/src/mcelectron-analysis/functions/particles/._get_df_part.py differ diff --git a/src/mcelectron-analysis/functions/particles/._plot_df_part.py b/src/mcelectron-analysis/functions/particles/._plot_df_part.py new file mode 100644 index 0000000..cbd95bc Binary files /dev/null and b/src/mcelectron-analysis/functions/particles/._plot_df_part.py differ diff --git a/src/mcelectron-analysis/functions/particles/get_df_part.py b/src/mcelectron-analysis/functions/particles/get_df_part.py new file mode 100644 index 0000000..e9ef315 --- /dev/null +++ b/src/mcelectron-analysis/functions/particles/get_df_part.py @@ -0,0 +1,231 @@ +import pandas as pd +import numpy as np +import h5py as h5py + + +def get_df_part_e(file_path, sim_time, num_E, num_r, Erange = [1e-5, 2e4]): + # def some constants + me_eV = 511e3 + c_ms = 3e8 + rrange = [0, 0.045] + + # calc bin properties + Ebins = pow(10, np.linspace(np.log10(Erange[0]), np.log10(Erange[1]), (num_E+1))) + Emids = (Ebins[1:] + Ebins[:-1]/2) + Emids = pow(10, (np.log10(Ebins[1:]) + np.log10(Ebins[:-1]))/2) + rbins = np.linspace(0, 0.045, (num_r+1)) + rmids = (rbins[1:] + rbins[:-1])/2 + As = np.pi*rbins[1:]**2 - np.pi*rbins[:-1]**2 + + # open h5 file + f = h5py.File(file_path, 'r') + g = f['Particles']['e-'] + df = pd.DataFrame() + + # iterate over all zs and append to df + zs = list(g.keys()) + for z in zs: + print (z) + # calc properties and calculate categories + df_z = pd.DataFrame(g[z][:]) + df_z['E_eV'] = 0.5*me_eV*(df_z.vx_ms**2 + df_z.vy_ms**2 + df_z.vz_ms**2)/c_ms**2 + df_z['r_m'] = np.sqrt(df_z['x_m']**2 + df_z['y_m']**2) + df_z['inv_v_z'] = 1/df_z['vz_ms'].abs() + df_z['v_sign'] = np.sign(df_z['vz_ms']) + df_z['E_cut'] = pd.cut(df_z['E_eV'], bins=Ebins, labels = False) + df_z['r_cut'] = pd.cut(df_z['r_m'], bins=rbins, labels = False, include_lowest = True) + + # apply categories and fill empty with 0 + #t = df_z['inv_v_z'].groupby([df_z['E_cut'], df_z['r_cut']]).agg(N=np.size,inv_v_sum=np.sum) + t = df_z.groupby([df_z['E_cut'], df_z['r_cut']])['inv_v_z'].agg([('N','size'), ('inv_v_sum','sum')]) + t['v_sign'] = df_z.groupby([df_z['E_cut'], df_z['r_cut']])['v_sign'].sum() + t = t.reindex( pd.MultiIndex.from_product([np.arange(num_E), + np.arange(num_r)], names=['E_bin', 'r_bin']) ,fill_value=0) + t = t.reset_index() + t['z'] = float(z) + + # transform to df form + a = pd.DataFrame({ + 'z' : t['z'], + 'Emin' : Ebins[t['E_bin']], + 'Emax' : Ebins[t['E_bin']+1], + 'Emid' : Emids[t['E_bin']], + 'rmin' : rbins[t['r_bin']], + 'rmax' : rbins[t['r_bin']+1], + 'rmid' : rmids[t['r_bin']], + 'N' : t['N'], + 'dndE' : 0, + 'djzabsdE' : 0, + 'djzdE' : 0, + }) + a['dndE'] = t['inv_v_sum']/As[t['r_bin']]/sim_time/(a['Emax']-a['Emin']) + a['dndE'] = a['dndE'].replace(np.inf, 0) + a['djzabsdE'] = t['N']/As[t['r_bin']]/sim_time/(a['Emax']-a['Emin']) + a['djzdE'] = t['v_sign']/As[t['r_bin']]/sim_time/(a['Emax']-a['Emin']) + df = df.append(a) #append to final + return df + +def get_df_part_all(file_path, sim_time, num_r): + # def some constants + c_ms = 3e8 + rrange = [0, 0.045] + + # calc bin properties + rbins = np.linspace(0, 0.045, (num_r+1)) + rmids = (rbins[1:] + rbins[:-1])/2 + As = np.pi*rbins[1:]**2 - np.pi*rbins[:-1]**2 + + # open h5 file + f = h5py.File(file_path, 'r') + + df = pd.DataFrame() + for s in list(f['Particles'].keys()): + print (s) + g = f['Particles'][s] + + # iterate over all zs and append to df + zs = list(g.keys()) + for z in zs: + # calc properties and calculate categories + df_z = pd.DataFrame(g[z][:]) + df_z['r_m'] = np.sqrt(df_z['x_m']**2 + df_z['y_m']**2) + df_z['inv_v_z'] = 1/df_z['vz_ms'].abs() + df_z['v_sign'] = np.sign(df_z['vz_ms']) + df_z['r_cut'] = pd.cut(df_z['r_m'], bins=rbins, labels = False, include_lowest = True) + + # apply categories and fill empty with 0 + #t = df_z['inv_v_z'].groupby(df_z['r_cut']).agg(N=np.size,inv_v_sum=np.sum) + t = df_z.groupby(df_z['r_cut'])['inv_v_z'].agg([('N','size'), ('inv_v_sum','sum')]) + t['v_sign'] = df_z.groupby([df_z['r_cut']])['v_sign'].sum() + t = t.reindex(np.arange(num_r) ,fill_value=0) + t.index.name = 'r_bin' + t = t.reset_index() + t['z'] = float(z) + + # transform to df form + a = pd.DataFrame({ + 'species' : s, + 'z' : t['z'], + 'rmin' : rbins[t['r_bin']], + 'rmax' : rbins[t['r_bin']+1], + 'rmid' : rmids[t['r_bin']], + 'N' : t['N'], + 'n' : 0, + 'jzabs' : 0, + 'jz' : 0, + }) + a['n'] = t['inv_v_sum']/As[t['r_bin']]/sim_time + a['n'] = a['n'].replace(np.inf, 0) + a['jzabs'] = t['N']/As[t['r_bin']]/sim_time + a['jz'] = t['v_sign']/As[t['r_bin']]/sim_time + + df = df.append(a) #append to final + return df + +def get_df_part_rw(file_path, sim_time, Vmax = 5, number_points = 100): + def get_rw_hits(f, s, sim_time): + def get_mass(s): + m_T = 2.81e9 + if s=='e-': + return 511e3 + elif s=='T+': + return m_T + elif s=='T2+': + return 2*m_T + elif s=='T3+': + return 3*m_T + elif s=='T5+': + return 5*m_T + else: + raise ('Species invalid') + def get_Z(species): + return species.count('+') - species.count('-') + + try: + df_temp = pd.DataFrame(f['Particles'][s]['-3.000000'][:]) + except: + return np.zeros(2*number_points-1) + E = get_mass(s)/2*(df_temp['vx_ms']**2 + df_temp['vy_ms']**2 + df_temp['vz_ms']**2)/3e8/3e8 + N_tot = len(E) + N_hits = N_tot - np.cumsum(np.histogram(E, E_boarders)[0]) + N_hits = np.concatenate((N_tot*np.ones(number_points), N_hits)) + if (get_Z(s) < 0): + N_hits = np.flip(N_hits, axis=0) + I = N_hits * 1.602176462e-19 * get_Z(s) / sim_time * 1e9 + return I + + f = h5py.File(file_path, 'r') + E_boarders = np.linspace(0, Vmax, number_points) + f = h5py.File(file_path, 'r') + + species = list(f['Particles'].keys()) + df_rw = pd.DataFrame() + df_rw['E'] = np.concatenate((-np.flip(E_boarders, axis = 0),E_boarders[1:])) + for s in species: + I = get_rw_hits(f, s, sim_time) + df_rw[s] = I + df_rw.insert (1, 'total', df_rw.iloc[:,1:].sum(axis = 1)) + return df_rw.melt(id_vars = 'E', var_name = 'species', value_name = 'I') + + +def get_df_part_e_vz(file_path, sim_time, num_vz, num_r, vzrange = [1e-5, 1e9]): + # def some constants + me_eV = 511e3 + c_ms = 3e8 + rrange = [0, 0.045] + + # calc bin properties + vzbins = pow(10, np.linspace(np.log10(vzrange[0]), np.log10(vzrange[1]), (num_vz+1))) + vzmids = (vzbins[1:] + vzbins[:-1]/2) + vzmids = pow(10, (np.log10(vzbins[1:]) + np.log10(vzbins[:-1]))/2) + rbins = np.linspace(0, 0.045, (num_r+1)) + rmids = (rbins[1:] + rbins[:-1])/2 + As = np.pi*rbins[1:]**2 - np.pi*rbins[:-1]**2 + + # open h5 file + f = h5py.File(file_path, 'r') + g = f['Particles']['e-'] + df = pd.DataFrame() + + # iterate over all zs and append to df + zs = list(g.keys()) + for z in zs: + print (z) + # calc properties and calculate categories + df_z = pd.DataFrame(g[z][:]) + df_z['vz_abs'] = df_z['vz_ms'].abs() + df_z['r_m'] = np.sqrt(df_z['x_m']**2 + df_z['y_m']**2) + df_z['inv_v_z'] = 1/df_z['vz_ms'].abs() + df_z['v_sign'] = np.sign(df_z['vz_ms']) + df_z['vz_cut'] = pd.cut(df_z['vz_ms'], bins=vzbins, labels = False) + df_z['r_cut'] = pd.cut(df_z['r_m'], bins=rbins, labels = False, include_lowest = True) + + # apply categories and fill empty with 0 + #t = df_z['inv_v_z'].groupby([df_z['vz_cut'], df_z['r_cut']]).agg(N=np.size,inv_v_sum=np.sum) + t = df_z.groupby([df_z['vz_cut'], df_z['r_cut']])['inv_v_z'].agg([('N','size'), ('inv_v_sum','sum')]) + t['v_sign'] = df_z.groupby([df_z['vz_cut'], df_z['r_cut']])['v_sign'].sum() + t = t.reindex( pd.MultiIndex.from_product([np.arange(num_vz), + np.arange(num_r)], names=['vz_bin', 'r_bin']) ,fill_value=0) + t = t.reset_index() + t['z'] = float(z) + + # transform to df form + a = pd.DataFrame({ + 'z' : t['z'], + 'vzmin' : vzbins[t['vz_bin']], + 'vzmax' : vzbins[t['vz_bin']+1], + 'vzmid' : vzmids[t['vz_bin']], + 'rmin' : rbins[t['r_bin']], + 'rmax' : rbins[t['r_bin']+1], + 'rmid' : rmids[t['r_bin']], + 'N' : t['N'], + 'dndvz' : 0, + 'djzabsdvz' : 0, + 'djzdvz' : 0, + }) + a['dndE'] = t['inv_v_sum']/As[t['r_bin']]/sim_time/(a['vzmax']-a['vzmin']) + a['dndE'] = a['dndE'].replace(np.inf, 0) + a['djzabsdvz'] = t['N']/As[t['r_bin']]/sim_time/(a['vzmax']-a['vzmin']) + a['djzdvz'] = t['v_sign']/As[t['r_bin']]/sim_time/(a['vzmax']-a['vzmin']) + df = df.append(a) #append to final + return df \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/particles/plot_df_part.py b/src/mcelectron-analysis/functions/particles/plot_df_part.py new file mode 100644 index 0000000..4be9880 --- /dev/null +++ b/src/mcelectron-analysis/functions/particles/plot_df_part.py @@ -0,0 +1,181 @@ +import numpy as np +import pandas as pd + +import matplotlib.pyplot as plt +import matplotlib.colors as colors +import seaborn as sns + +NEJM = sns.color_palette(palette = ['#bc3c29', + '#0072bf', + '#e18727', + '#20854e', + '#7876b1', + '#6f99ad', + '#ffdc91', + '#ee4c97']) +sns.set( + context='paper', + style='white', + palette=NEJM, + font='sans-serif', + font_scale=1, + color_codes=False, + rc = {'figure.dpi' : 100, + 'text.usetex' : True, + 'axes.labelsize' : 10, + 'xtick.labelsize' : 10, + 'ytick.labelsize' : 10, + 'legend.fontsize' : 10, + 'xtick.bottom' : True, + 'xtick.minor.bottom' : False, + 'ytick.left' : True, + 'ytick.minor.left' : False + }) + + +def plot_part_e_dndE_z3(df_part_e, ax): + df_plot = df_part_e[(df_part_e['z']== -3) | (df_part_e['z']== 5) | (df_part_e['z']== 10)] + df_plot['zstr'] = '' + + df_plot['zstr'][df_plot.z == -3] = 'rearwall' + df_plot['zstr'][df_plot.z == 5] = 'WGTS mid' + df_plot['zstr'][df_plot.z == 10] = 'WGTS end' + + sns.lineplot(ax = ax, x="Emid", y="dndE", data=df_plot, + style = 'zstr', style_order = ['WGTS mid', 'rearwall', 'WGTS end'], + hue = 'zstr', hue_order = ['WGTS mid', 'rearwall', 'WGTS end'], + err_style=None, legend = 'full') + ax.set_xscale('log') + ax.set_yscale('log') + ax.set_xlabel ('Electron energy (eV)') + ax.set_ylabel (r'Diff. e$^-$ density dn/dE (m$^{-3}$ eV$^{-1}$)') + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_part_e_dndE_zmid(df_part_e, ax): + df_plot = df_part_e[(df_part_e['z']== 5)] + + sns.lineplot(ax = ax, x="Emid", y="dndE", data=df_plot, err_style=None, legend = None) + ax.set_xscale('log') + ax.set_yscale('log') + ax.set_xlabel ('Electron energy (eV)') + ax.set_ylabel (r'Diff. e$^-$ density dn/dE (m$^{-3}$ eV$^{-1}$)') + + +def plot_part_e_dndE_hm(df_part_e, fig, ax): + df_temp = df_part_e[['z','Emid', 'dndE']].groupby(['z', 'Emid'], as_index = False).mean() + z = np.unique(df_temp.z) + z = np.concatenate([[z[0]], (z[1:] + z[:-1])/2, [z[-1]]]) + E = np.unique(np.concatenate([df_part_e.Emin, df_part_e.Emax])) + E = np.sort(E)[::-1] + df_temp = df_temp.pivot(index='Emid', columns='z', values='dndE') + df_temp = df_temp.replace(-np.inf, 0) + df_temp = df_temp.sort_index(ascending = False) + dndE = np.array(df_temp) + + hm = ax.pcolor(z, E, dndE, + norm=colors.LogNorm(vmin=1e0, vmax=1e16), + cmap='viridis') + + cbar = fig.colorbar(hm, ax=ax) + cbar.outline.set_visible(False) + cbar.set_label(r'Diff. e$^-$ density dn/dE (m$^{-3}$ eV$^{-1}$)') + + fig.patch.set_visible(False) + ax.set_xscale('linear') + ax.set_yscale('log') + + ax.set_xlabel('Longitudinal position z (m)') + ax.set_ylabel('Electron energy E (eV)') + + ax.spines['top'].set_visible(False) + ax.spines['bottom'].set_visible(False) + ax.spines['right'].set_visible(False) + ax.spines['left'].set_visible(False) + + +def plot_part_e_djzdE_z3(df_part_e, ax): + df_plot = df_part_e[(df_part_e['z']== -3) | (df_part_e['z']== 5) | (df_part_e['z']== 10)] + df_plot['zstr'] = '' + df_plot['zstr'][df_plot.z == -3] = 'rearwall' + df_plot['zstr'][df_plot.z == 5] = 'WGTS mid' + df_plot['zstr'][df_plot.z == 10] = 'WGTS end' + + sns.lineplot(ax = ax, x="Emid", y="djzdE", style = 'zstr', hue = 'zstr', data=df_plot, err_style=None, legend = 'full') + ax.set_xscale('log') + ax.set_yscale('linear') + ax.set_xlabel ('Electron energy (eV)') + ax.set_ylabel (r'Diff. e$^-$ flux dj$_\mathrm{z}$/dE (m$^{-2}$ s$^{-1}$ eV$^{-1}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_part_n_z(df_part_all, ax): + sns.lineplot(ax = ax, x="z", y="n", style = 'species', hue = 'species', data=df_part_all, err_style=None) + + ax.set_xscale('linear') + ax.set_yscale('log') + ax.set_xlabel ('Longitudinal position z (m)') + ax.set_ylabel (r'Particle density n (m$^{-3}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_part_jz_z(df_part_all, ax): + sns.lineplot(ax = ax, x="z", y="jz", style = 'species', hue = 'species', data=df_part_all, err_style=None) + ax.set_xscale('linear') + ax.set_yscale('linear') + + ax.set_xlabel ('Longitudinal position z (m)') + ax.set_ylabel (r'Particle flux j$_\mathrm{z}$ (m$^{-2}$ s$^{-1}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_part_iz_z(df_part_all, ax): + def get_charge(species): + return 1.602176634e-19*(species.count('+') - species.count('-')) + get_charge = np.vectorize(get_charge, otypes = [float]) + df_plot = df_part_all + df_plot['i'] = get_charge(df_plot.species)*df_plot['jz'] + total_temp = df_plot.groupby(['z', 'rmin', 'rmid'], as_index = False).sum() + total_temp.insert(0,'species', 'total') + df_plot = pd.concat([total_temp, df_plot], sort=False) + + sns.lineplot(ax = ax, x="z", y="i", style = 'species', hue = 'species', data=df_plot, err_style=None) + + ax.set_xscale('linear') + ax.set_yscale('linear') + + ax.set_xlabel('Longitudinal position z (m)') + ax.set_ylabel('Current density i$_\mathrm{z}$ (A m$^{-2}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_part_rw(df_part_rw, ax): + sns.lineplot(ax = ax, x="E", y="I", style = 'species', hue = 'species', data=df_part_rw, err_style=None) + ax.set_xscale('linear') + ax.set_yscale('linear') + + ax.set_xlabel('Rearwall voltage E$_\mathrm{rw}$ (V)') + ax.set_ylabel('Rearwall current I$_\mathrm{rw}$ (nA)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + +def plot_part_rw_zoom(df_part_rw_zoom, ax): + sns.lineplot(ax = ax, x="E", y="I", style = 'species', hue = 'species', data=df_part_rw_zoom, err_style=None) + ax.set_xscale('linear') + ax.set_yscale('linear') + + ax.set_xlabel('Rearwall voltage E$_\mathrm{rw}$ (V)') + ax.set_ylabel('Rearwall current I$_\mathrm{rw}$ (nA)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) diff --git a/src/mcelectron-analysis/functions/populations/._get_df_pop.py b/src/mcelectron-analysis/functions/populations/._get_df_pop.py new file mode 100644 index 0000000..632fdda Binary files /dev/null and b/src/mcelectron-analysis/functions/populations/._get_df_pop.py differ diff --git a/src/mcelectron-analysis/functions/populations/get_df_pop.py b/src/mcelectron-analysis/functions/populations/get_df_pop.py new file mode 100644 index 0000000..a32c786 --- /dev/null +++ b/src/mcelectron-analysis/functions/populations/get_df_pop.py @@ -0,0 +1,76 @@ +import pandas as pd +import numpy as np +import h5py as h5py + +def get_df_pop(file_path): + def append_V_m3 (df_meta): + A_m2 = np.pi*(df_meta.r_max_m**2-df_meta.r_min_m**2)*(df_meta.phi_max-df_meta.phi_min)/2/np.pi + V_m3 = A_m2*(df_meta.z_max_m-df_meta.z_min_m) + df_meta.insert(len(df_meta.columns),'V_m3',V_m3) + return df_meta + + def get_V_m3(df_meta): + r_bins = np.unique(df_meta.r_bin) + V_m3 = np.zeros(r_bins.size) + for i in np.arange(r_bins.size): + V_m3[i] = np.mean (df_meta[df_meta.r_bin==r_bins[i]].V_m3) + return V_m3 + + def append_n_m3 (df, V_m3): + n_m3 = df.cum_time/df.phys_time_s/V_m3[df.r_bin] + df['n_m3'] = n_m3 + df['n_m3'].fillna(0., inplace=True) + return df + + def append_from_meta(df, df_meta): + df_length = df.shape[0] + bin_list = ['z_bin','r_bin','phi_bin','E_bin'] + min_list = ['z_min_m', 'r_min_m', 'phi_min', 'E_min_eV'] + max_list = ['z_max_m', 'r_max_m', 'phi_max', 'E_max_eV'] + for i in np.arange(4): + i_bin = bin_list[i] + i_min = min_list[i] + i_max = max_list[i] + info_df = df_meta.groupby(i_bin, as_index=False).mean() + mins = np.zeros(df_length) + maxs = np.zeros(df_length) + for row in range(0, info_df.shape[0]): + mins[df[i_bin] == info_df[i_bin][row]] = info_df[i_min][row] + maxs[df[i_bin] == info_df[i_bin][row]] = info_df[i_max][row] + df[i_min] = mins + df[i_max] = maxs + return df + + f = h5py.File(file_path, 'r') + df = pd.DataFrame() + species = list(f['Populations'].keys()) + for s in species: + try: # If has been merged + pop_key = list(f['Populations'][s].keys())[0] + df_data = pd.DataFrame(f['Populations'][s][pop_key][s][:]) + df_meta = pd.DataFrame(f['Populations'][s][pop_key][s + '_meta_data'][:]) + except: # If not merged + df_data = pd.DataFrame(f['Populations'][s][s][:]) + df_meta = pd.DataFrame(f['Populations'][s][s + '_meta_data'][:]) + + df_meta = append_V_m3(df_meta) + V_m3 = get_V_m3(df_meta) + df_data = append_n_m3(df_data, V_m3) + df_data = append_from_meta(df_data, df_meta) + + a = pd.DataFrame({ + 'species' : s, + 't' : df_data['phys_time_s'], + 'zmin' : df_data['z_min_m'], + 'zmax' : df_data['z_max_m'], + 'rmin' : df_data['r_min_m'], + 'rmax' : df_data['r_max_m'], + 'phimin' : df_data['phi_min'], + 'phimax' : df_data['phi_max'], + 'Emin' : df_data['E_min_eV'], + 'Emax' : df_data['E_max_eV'], + 'n': df_data['n_m3'] + }) + df = df.append(a) #append to final + + return (df) \ No newline at end of file diff --git a/src/mcelectron-analysis/functions/populations/plot_df_pop.py b/src/mcelectron-analysis/functions/populations/plot_df_pop.py new file mode 100644 index 0000000..3375d3c --- /dev/null +++ b/src/mcelectron-analysis/functions/populations/plot_df_pop.py @@ -0,0 +1,118 @@ +import numpy as np +import pandas as pd + +import matplotlib.pyplot as plt +import seaborn as sns + +NEJM = sns.color_palette(palette = ['#bc3c29', + '#0072bf', + '#e18727', + '#20854e', + '#7876b1', + '#6f99ad', + '#ffdc91', + '#ee4c97']) +sns.set( + context='paper', + style='white', + palette=NEJM, + font='sans-serif', + font_scale=1, + color_codes=False, + rc = {'figure.dpi' : 100, + 'text.usetex' : True, + 'axes.labelsize' : 10, + 'xtick.labelsize' : 10, + 'ytick.labelsize' : 10, + 'legend.fontsize' : 10, + 'xtick.bottom' : True, + 'xtick.minor.bottom' : False, + 'ytick.left' : True, + 'ytick.minor.left' : False + }) + + +def plot_pop_n_t(df_pop, ax): + df_plot = df_pop.groupby(['species', 't'], as_index = False).n.mean() + df_plot['t'] = df_plot['t']*1e9 + + sns.lineplot(ax = ax, x="t", y="n", style = 'species', hue = 'species', data=df_plot, err_style=None) + ax.set_xscale('linear') + ax.set_yscale('log') + + ax.set_xlabel('Simulation time t (ns)') + ax.set_ylabel(r'Particle density n (m$^{-3}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_pop_n_z(df_pop, ax): + t_max = np.sort(df_pop.t.unique())[-1] + df_plot = df_pop[df_pop.t == t_max] + df_plot = df_plot.groupby(['species', 'zmin', 'zmax', 'rmin', 'rmax', 'phimin', 'phimax'], as_index = False).sum() + df_plot['zmid'] = (df_plot['zmin'] + df_plot['zmax'])/2 + df_plot = df_plot.groupby(['species', 'zmid'], as_index = False).n.mean() + + sns.lineplot(ax = ax, x="zmid", y="n", style = 'species', hue = 'species', data=df_plot, err_style=None) + ax.set_xscale('linear') + ax.set_yscale('log') + + ax.set_xlabel('Longitudinal position z (m)') + ax.set_ylabel(r'Particle density n (m$^{-3}$)') + + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_pop_e_dndE_z3(df_pop, ax): + t_max = np.sort(df_pop.t.unique())[-1] + df_plot = df_pop[(df_pop.species == 'e-') & (df_pop.t == t_max)] + df_plot['zmid'] = (df_plot['zmin']+df_plot['zmax'])/2 + df_plot['Emid'] = (df_plot['Emin']+df_plot['Emax'])/2 + df_plot['dndE'] = df_plot['n']/(df_plot['Emax'] - df_plot['Emin']) + df_plot = df_plot.groupby(['zmid','Emid'], as_index = False).dndE.mean() + df_plot = df_plot[ + (abs(df_plot['zmid'] - -2.675) < 1e-1) | + (abs(df_plot['zmid'] - 5.125) < 1e-1) | + (abs(df_plot['zmid'] - 9.675) < 1e-1)] + def make_z_string(s): + rounded = "{:.1f}".format(s) + return 'z=' + rounded + make_z_string = np.vectorize(make_z_string, otypes = [str]) + + df_plot['zstr'] = make_z_string(df_plot['zmid']) + + df_plot['zstr'][abs(df_plot['zmid'] - -2.675) < 1e-1] = 'rearwall' + df_plot['zstr'][abs(df_plot['zmid'] - 5.125) < 1e-1] = 'WGTS mid' + df_plot['zstr'][abs(df_plot['zmid'] - 9.675) < 1e-1] = 'WGTS end' + + sns.lineplot(ax = ax, x="Emid", y="dndE", + style = 'zstr', style_order = ['WGTS mid', 'rearwall', 'WGTS end'], + hue = 'zstr', hue_order = ['WGTS mid', 'rearwall', 'WGTS end'], + data=df_plot, err_style=None, legend='full') + ax.set_xscale('log') + ax.set_yscale('log') + + ax.set_xlabel ('Electron energy (eV)') + ax.set_ylabel (r'Diff. e$^-$ density dn/dE (m$^{-3}$ eV$^{-1}$)') + handles, labels = ax.get_legend_handles_labels() + ax.legend(handles=handles[1:], labels=labels[1:]) + + +def plot_pop_e_dndE_zmid(df_pop, ax): + t_max = np.sort(df_pop.t.unique())[-1] + df_plot = df_pop[(df_pop.species == 'e-') & (df_pop.t == t_max)] + df_plot['zmid'] = (df_plot['zmin']+df_plot['zmax'])/2 + df_plot['Emid'] = (df_plot['Emin']+df_plot['Emax'])/2 + df_plot['dndE'] = df_plot['n']/(df_plot['Emax'] - df_plot['Emin']) + df_plot = df_plot.groupby(['zmid','Emid'], as_index = False).dndE.mean() + df_plot = df_plot[abs(df_plot['zmid'] - 5.125) < 1e-1] + + + sns.lineplot(ax = ax, x="Emid", y="dndE", data=df_plot, err_style=None, legend=None) + ax.set_xscale('log') + ax.set_yscale('log') + + ax.set_xlabel ('Electron energy (eV)') + ax.set_ylabel (r'Diff. e$^-$ density dn/dE (m$^{-3}$ eV$^{-1}$)') diff --git a/src/mcelectron-analysis/science.mplstyle b/src/mcelectron-analysis/science.mplstyle new file mode 100644 index 0000000..ebfd4a7 --- /dev/null +++ b/src/mcelectron-analysis/science.mplstyle @@ -0,0 +1,36 @@ +axes.titlesize : 24 +axes.labelsize : 12 +lines.linewidth : 2 +lines.markersize : 5 +xtick.labelsize : 12 +ytick.labelsize : 12 +figure.figsize : 10,8 +axes.grid: True +grid.linestyle: - +grid.color: 0.75 +font.size: 12 +font.family : sans-serif +font.sans-serif: DejaVu Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif +legend.fontsize: 20 +legend.frameon: False +legend.numpoints: 1 +legend.scatterpoints: 1 +lines.solid_capstyle: round + +text.color: .15 +xtick.color: .15 +ytick.color: .15 +xtick.direction: out +ytick.direction: out + +axes.axisbelow: True + +# these are tableau20 colors +#axes.color_cycle: 1f77b4, aec7e8,ff7f0e,ffbb78,2ca02c,98df8a,d62728,ff9896,9467bd,c5b0d5,8c564b,c49c94,e377c2,f7b6d2,7f7f7f,c7c7c7,bcbd22,dbdb8d,17becf,9edae5 + + +#axes.prop_cycle : cycler('color',['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf']) + +#axes.prop_cycle : cycler('color', ['1f77b4', 'aec7e8','ff7f0e','ffbb78','2ca02c',#'98df8a','d62728','ff9896','9467bd','c5b0d5','8c564b','c49c94','e377c2','f7b6d2',#'7f7f7f','c7c7c7','bcbd22','dbdb8d','17becf','9edae5']) + +axes.prop_cycle : cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf']) \ No newline at end of file diff --git a/src/mcelectron-analysis/scripts/merge.py b/src/mcelectron-analysis/scripts/merge.py new file mode 100644 index 0000000..b14ebdc --- /dev/null +++ b/src/mcelectron-analysis/scripts/merge.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +import sys +import os +import glob + +import h5py + +base_dir = os.path.dirname(os.path.realpath(__file__)) + '/..' +sys.path.append(base_dir + '/functions/IO') + +# get import_dir +if (len(sys.argv) != 3): + print ('Error: Too many or too few number of arguments.') + sys.exit() + +import_dir = sys.argv[1] +out_file = sys.argv[2] + +# merge h5_files +import h5_merge +h5_merge.merge_h5s(import_dir, out_file) diff --git a/src/mcelectron-analysis/scripts/plot.py b/src/mcelectron-analysis/scripts/plot.py new file mode 100644 index 0000000..d91ebfb --- /dev/null +++ b/src/mcelectron-analysis/scripts/plot.py @@ -0,0 +1,151 @@ +#!/usr/bin/python + +import sys +import os +import glob + +import numpy as np +import pandas as pd +import h5py + +print('Started Plotting') + +# plot settings +import matplotlib +matplotlib.use('Agg') +import seaborn as sns +import matplotlib.pyplot as plt + +NEJM = sns.color_palette(palette = ['#bc3c29', + '#0072bf', + '#e18727', + '#20854e', + '#7876b1', + '#6f99ad', + '#ffdc91', + '#ee4c97']) +sns.set( + context='paper', + style='white', + palette=NEJM, + font='sans-serif', + font_scale=1, + color_codes=False, + rc = {'figure.dpi' : 150, + 'text.usetex' : True, + 'axes.labelsize' : 10, + 'xtick.labelsize' : 10, + 'ytick.labelsize' : 10, + 'legend.fontsize' : 10, + 'xtick.bottom' : True, + 'xtick.minor.bottom' : False, + 'ytick.left' : True, + 'ytick.minor.left' : False + }) + +base_dir = os.path.dirname(os.path.realpath(__file__)) + '/..' +sys.path.append(base_dir + '/functions/particles') +import get_df_part +import plot_df_part + +sys.path.append(base_dir + '/functions/populations') +import get_df_pop +import plot_df_pop + +# get import_dir +if (len(sys.argv) != 3): + print ('Error: Too many or too few number of arguments.') + sys.exit(1) + +sim_time = float(sys.argv[1]) +import_file = sys.argv[2] + +# make plots dir +plot_dir = os.path.dirname(os.path.realpath(import_file)) + '/plots' +try: + os.mkdir(plot_dir) +except: + pass + +### Plot from particles data +# Electron energy density spectrum +num_E = 100 +num_r = 1 +file_path = import_file +dpi = 150 + + +# df_part_e +df_part_e = get_df_part.get_df_part_e(file_path, sim_time, num_E, num_r) +df_part_e.to_csv(plot_dir + '/df_part_e.csv') + +fig, ax = plt.subplots() +plot_df_part.plot_part_e_dndE_z3(df_part_e, ax) +fig.savefig(plot_dir + '/plot_part_e_dndE_z3.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_part.plot_part_e_dndE_zmid(df_part_e, ax) +fig.savefig(plot_dir + '/plot_part_e_dndE_zmid.png', dpi = dpi, bbox_inches='tight') + +#fig, ax = plt.subplots(figsize=[21/2.54, 7/2.54]) +#plot_df_part.plot_part_e_dndE_hm(df_part_e, fig, ax) +#fig.savefig(plot_dir + '/plot_part_e_dndE_hm.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_part.plot_part_e_djzdE_z3(df_part_e, ax) +fig.savefig(plot_dir + '/plot_part_e_djzdE_z3.png', dpi = dpi, bbox_inches='tight') + + +# df_part_all +df_part_all = get_df_part.get_df_part_all(file_path, sim_time, num_r) +df_part_all.to_csv(plot_dir + '/df_part_all.csv') + +fig, ax = plt.subplots() +plot_df_part.plot_part_n_z(df_part_all, ax) +fig.savefig(plot_dir + '/plot_part_n_z.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_part.plot_part_jz_z(df_part_all, ax) +fig.savefig(plot_dir + '/plot_part_jz_z.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_part.plot_part_iz_z(df_part_all, ax) +fig.savefig(plot_dir + '/plot_part_iz_z.png', dpi = dpi, bbox_inches='tight') + + +# df_part_rw +df_part_rw = get_df_part.get_df_part_rw(file_path, sim_time, Vmax = 5, number_points = 100) +df_part_rw.to_csv(plot_dir + '/df_part_rw.csv') + +fig, ax = plt.subplots() +plot_df_part.plot_part_rw(df_part_rw, ax) +fig.savefig(plot_dir + '/plot_part_rw.png', dpi = dpi, bbox_inches='tight') + +#df_part_rw_zoom +df_part_rw_zoom = get_df_part.get_df_part_rw(file_path, sim_time, Vmax = 0.03, number_points = 100) +df_part_rw_zoom.to_csv(plot_dir + '/df_part_rw_zoom.csv') + +fig, ax = plt.subplots() +plot_df_part.plot_part_rw_zoom(df_part_rw_zoom, ax) +fig.savefig(plot_dir + '/plot_part_rw_zoom.png', dpi = dpi, bbox_inches='tight') + +### Plot from population data +# df_pop +df_pop = get_df_pop.get_df_pop(file_path) +df_pop.to_csv(plot_dir + '/df_pop.csv') + +fig, ax = plt.subplots() +plot_df_pop.plot_pop_n_t(df_pop, ax) +fig.savefig(plot_dir + '/plot_pop_n_t.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_pop.plot_pop_n_z(df_pop, ax) +fig.savefig(plot_dir + '/plot_pop_n_z.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_pop.plot_pop_e_dndE_z3(df_pop, ax) +fig.savefig(plot_dir + '/plot_pop_e_dndE_z3.png', dpi = dpi, bbox_inches='tight') + +fig, ax = plt.subplots() +plot_df_pop.plot_pop_e_dndE_zmid(df_pop, ax) +fig.savefig(plot_dir + '/plot_pop_e_dndE_zmid.png', dpi = dpi, bbox_inches='tight') diff --git a/src/mcelectron-analysis/scripts/process.py b/src/mcelectron-analysis/scripts/process.py new file mode 100644 index 0000000..1bc39a2 --- /dev/null +++ b/src/mcelectron-analysis/scripts/process.py @@ -0,0 +1,70 @@ +#!/usr/bin/python + +import sys +import os +import glob + +import h5py + +#base_dir = '/Users/ChristianReiling/Documents/Masterarbeit/mcelectron-analysis' +#base_dir = '/kalinka/home/reiling/mcelectron-analysis' + +base_dir = os.path.dirname(os.path.realpath(__file__)) + '/..' + +sys.path.append(base_dir + '/functions') +sys.path.append(base_dir + '/functions/populations') +sys.path.append(base_dir + '/functions/particles') + + +# get import_dir +if (len(sys.argv) == 3): # use (pwd) check for proper folder ... + import_dir = os.getcwd() +elif (len(sys.argv) == 4): # use third argument as input folder + import_dir = sys.argv[3] +else: + print ('Error: Too many or too few number of arguments.') + sys.exit(1) + +number_decays = float(sys.argv[1]) +print(sys.argv[2]) +cd_fac = float(sys.argv[2]) # correction factor of column density +A0 = 1e11 # Number decays/s +sim_time = number_decays/(float(A0*cd_fac)) + +export_dir = import_dir + '_out' + +print ('import_dir:\t' + import_dir) +print ('number_decays:\t' + str(number_decays)) +print ('cd_fac:\t' + str(cd_fac)) + +# check if already merged -> goto plotting +if os.path.exists(export_dir): + _ = glob.glob(export_dir + '/*.h5') + if len(_) == 1: + out_file = _[0] + os.system('python3 ' + base_dir + '/scripts/plot.py ' + str(sim_time) + ' ' + out_file) + sys.exit(0) + +# check number of h5 files and check names. +h5_files = glob.glob(import_dir + '/*.h5') +if len(h5_files) < 2: + print ('Error: Less than 2 .h5 files in input path.') + sys.exit(1) + +digits = len(str(len(h5_files))) +end_digits = -(digits+4) +check_name = h5_files[0][:end_digits] +for file in h5_files: + if file[:end_digits] != check_name: + print ('Error: Output names not consistent.') + sys.exit() + +os.mkdir(export_dir) +out_file = export_dir + '/' + os.path.basename(check_name) + '.h5' + +# Merge h5 files +os.system('python3 ' + base_dir + '/scripts/merge.py ' + import_dir + ' ' + out_file) + +# Plot diagrams +os.system('python3 ' + base_dir + '/scripts/plot.py ' + str(sim_time) + ' ' + out_file) +