analysis Script for plotting charge against time
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import numpy as np
|
||||
import matplotlib
|
||||
matplotlib.use("agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import h5py
|
||||
import argparse
|
||||
import glob
|
||||
import re
|
||||
import os
|
||||
|
||||
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 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("--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("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}[0-9]*\\.h5'")
|
||||
exit(1)
|
||||
|
||||
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': 14})
|
||||
fig = plt.figure(figsize=(10,6))
|
||||
plt.plot(times, charges, marker = 'x', label = legstr)
|
||||
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)
|
||||
|
||||
outname += args.basename + "_chargeAgainstTime_species-"
|
||||
|
||||
for value in args.species:
|
||||
outname += value
|
||||
outname += '.pdf'
|
||||
|
||||
# print(outname)
|
||||
plt.savefig(outname, format='pdf', bbox_inches = 'tight')
|
||||
# plt.show()
|
||||
Reference in New Issue
Block a user