import numpy as np import matplotlib # matplotlib.use("agg") import matplotlib.pyplot as plt import h5py import argparse import glob import re import os import plot_standards as pst def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow=False): times = [] total_charges = [] for file in files: with h5py.File(file, 'r') as cfile: total_charge = 0 time = 0 for key in cfile.keys(): if(key == "PoissonSolver" or key == "RestartInfo" or key == 'NumberProcesses'): continue if (not considered_keys[0] == 'All') and (not key in considered_keys): continue charge = cfile[f'{key}/Charge'][()] cfile_speciesDensity = cfile[key]['DensityField'] # binVolumes = cfile_speciesDensity['BinVolumes'][()] cfile_simData = cfile_speciesDensity['SimulationData'] for time_key in cfile_simData.keys(): time = cfile_simData[time_key]['PhysicalTime'][()] density = cfile_simData[time_key]['TimeInBin'][()] if not exclude_underflow: total_charge = np.sum(density)*charge else: total_charge = np.array([np.sum(density[:,:,:,:,1:-1])])*charge # print(total_charge) try: index = times.index(time) total_charges[index] += total_charge except: times.append(time) total_charges.append(total_charge) times = np.array(times)[:,0] # print(total_charge) total_charges = np.array(total_charges)[:,0] sorting_mask = np.argsort(times) times = times[sorting_mask] total_charges = total_charges[sorting_mask] return times, total_charges def get_time_and_wall_losses(files, considered_keys=['All']): times = [] phys_wall_loss = [] for file in files: with h5py.File(file, 'r') as cfile: time = 0 for key in cfile.keys(): if(key == "PoissonSolver" or key == "RestartInfo" or key == 'NumberProcesses'): continue if (not considered_keys[0] == 'All') and (not key in considered_keys): continue cfile_specieslogger = cfile[key]['DeletionLogger'] for time_key in cfile_specieslogger.keys(): time = cfile[key]['DensityField/SimulationData'][time_key]['PhysicalTime'][0] deltat = cfile[key]['CurrentCollector/SimulationData'][time_key]['PhysicalTime'][0] try: index = times.index(time) try: phys_wall_loss[index] += cfile_specieslogger[time_key]\ ['NumDeletions/Wall(physical)'][0]/deltat except: pass except: times.append(time) try: phys_wall_loss.append(cfile_specieslogger[time_key]\ ['NumDeletions/Wall(physical)'][0]/deltat) except: phys_wall_loss.append(-1) times = np.array(times) phys_wall_loss = np.array(phys_wall_loss) sorting_mask = np.argsort(times) times = times[sorting_mask] phys_wall_loss = phys_wall_loss[sorting_mask] return times, phys_wall_loss def get_time_and_scatter_losses(files, considered_keys=['All']): times = [] scatter_loss = [] for file in files: with h5py.File(file, 'r') as cfile: time = 0 for key in cfile.keys(): if(key == "PoissonSolver" or key == "RestartInfo" or key == 'NumberProcesses'): continue if (not considered_keys[0] == 'All') and (not key in considered_keys): continue cfile_specieslogger = cfile[key]['DeletionLogger'] for time_key in cfile_specieslogger.keys(): time = cfile[key]['DensityField/SimulationData'][time_key]['PhysicalTime'][0] deltat = cfile[key]['CurrentCollector/SimulationData'][time_key]['PhysicalTime'][0] try: index = times.index(time) try: scatter_loss[index] += cfile_specieslogger[time_key]\ ['NumDeletions/LargeEnergyTransfer'][0]/deltat except: pass except: times.append(time) try: scatter_loss.append(cfile_specieslogger[time_key]\ ['NumDeletions/LargeEnergyTransfer'][0]/deltat) except: scatter_loss.append(-1) times = np.array(times) scatter_loss = np.array(scatter_loss) sorting_mask = np.argsort(times) times = times[sorting_mask] scatter_loss = scatter_loss[sorting_mask] return times, scatter_loss def getFiles(dir:str, base_name:str, pattern:str) : if dir[-1] == '/': pathname = dir + base_name else: pathname = dir + '/' + base_name # print(glob.glob(pathname + "*.h5")) return [file for file in glob.glob(pathname + "*.h5") if re.match(rf"{pathname}{pattern}+\.h5", str(file))] if __name__ == '__main__': parser = argparse.ArgumentParser(description="Program to create a plot of the charge against time from the output of KARL") parser.add_argument("dir", type = str, help="directory where the files are stored in") parser.add_argument("basename", type = str, help = 'identifying pattern of the files (i.e. basename[0-9]*\\.h5])') parser.add_argument('--losses', nargs='?', choices=['Wall', 'Scattering'], help = 'choose to create loss rate plot (either from wall losses or due to scatterings)') parser.add_argument("--pattern", type = str, nargs = '?', help = 'Regular expression pattern, that specifies the naming of the files (by default [0-9]*). Gets added to dir+basename+pattern+".h5".', default = '[0-9]*') parser.add_argument("--width", type = str, nargs = '?', default="thesis", help = "Either \'thesis\' or \'beamer\' as defined in plot_standards.py") parser.add_argument("--fraction", type = float, default=1, nargs="?", help= "the fraction of width that the plot should occupy, as defined in plot_standards.py") parser.add_argument("species", action='extend', nargs='+', help = 'Names of the Species in the KARL output or \'All\' if all species should be summed. If name does not exist it will be ignored.') args = parser.parse_args() # print(args.dir, args.basename, args.species) files = getFiles(args.dir, args.basename, args.pattern) print(files) if(files == []): print(f"No files found in {args.dir}, which match '{args.basename}{args.pattern}\\.h5'") exit(1) if (not args.width == 'thesis') and (not args.width == 'beamer'): print(f"{args.width} is not a valid parameter for width; fall back to \'thesis\'") args.width = 'thesis' if args.losses in ['Wall', 'Scattering']: if args.losses == 'Wall': times, charges = get_time_and_wall_losses(files, args.species) else: times, charges = get_time_and_scatter_losses(files, args.species) else: times, charges = get_time_and_total_charge_(files, args.species) legstr = '' for val in args.species: legstr += val + " + " legstr = legstr[:-3] plt.rcParams.update({'font.size': 10}) fig = plt.figure(figsize=pst.set_size(args.width)) plt.plot(times, charges, marker = '.', label = legstr) if args.losses == 'Wall': plt.ylabel('loss rate (1/s)') elif args.losses == 'Scattering': plt.ylabel("upscattering (particles/s)") else: plt.ylabel('charge (C)') plt.xlabel('time (s)') plt.legend() plt.grid() plt.tight_layout() outname = args.dir if not outname[-1] == '/': outname += '/' outname += "plots/" os.makedirs(outname, exist_ok=True) if args.losses == 'Wall': outname += args.basename + "_wallLossRateAgainstTime_species-" elif args.losses == 'Scattering': outname += args.basename + "_scatteringLossRateAgainstTime_species-" else: outname += args.basename + "_chargeAgainstTime_species-" for value in args.species: outname += value outname += '_test.pdf' # print(outname) plt.savefig(outname, format='pdf', bbox_inches = 'tight') # plt.show()