8 Commits
Author SHA1 Message Date
csendlinger 444ca56108 Bugfix: offset calculation has been corrected 2026-11-24 10:29:48 +01:00
csendlinger 5f866c04b4 Formatting 2026-11-24 10:01:23 +01:00
csendlinger 776de1f593 Forgot the header files... 2026-11-24 09:29:51 +01:00
csendlinger c6687a23c3 Now writing the json file to the output hdf5 2026-11-24 09:28:57 +01:00
csendlinger d82fb6dab8 Restarting now should now work if the number of
procs is larger than the number of procs of the
restarted state. (Debug prints are still in the code)
2026-11-23 15:43:37 +01:00
csendlinger 94f6c78465 hotfix for reflected particles 2026-10-14 13:54:23 +02:00
csendlinger d9877c7993 more changes to plot_charge 2026-09-18 10:55:12 +02:00
csendlinger fbdfe2942c changes to plot_charge script to include upscatterings 2026-09-17 09:21:53 +02:00
10 changed files with 397 additions and 35 deletions
+110 -6
View File
@@ -1,12 +1,13 @@
import numpy as np import numpy as np
import matplotlib import matplotlib
matplotlib.use("agg") # matplotlib.use("agg")
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import h5py import h5py
import argparse import argparse
import glob import glob
import re import re
import os import os
import plot_standards as pst
def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow=False): def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow=False):
times = [] times = []
@@ -52,6 +53,86 @@ def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow
return times, total_charges 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) : def getFiles(dir:str, base_name:str, pattern:str) :
if dir[-1] == '/': if dir[-1] == '/':
pathname = dir + base_name pathname = dir + base_name
@@ -64,7 +145,10 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Program to create a plot of the charge against time from the output of KARL") 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("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("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("--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.') 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() args = parser.parse_args()
@@ -74,9 +158,19 @@ if __name__ == '__main__':
print(files) print(files)
if(files == []): if(files == []):
print(f"No files found in {args.dir}, which match '{args.basename}[0-9]*\\.h5'") print(f"No files found in {args.dir}, which match '{args.basename}{args.pattern}\\.h5'")
exit(1) 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) times, charges = get_time_and_total_charge_(files, args.species)
legstr = '' legstr = ''
@@ -85,9 +179,14 @@ if __name__ == '__main__':
legstr = legstr[:-3] legstr = legstr[:-3]
plt.rcParams.update({'font.size': 14}) plt.rcParams.update({'font.size': 10})
fig = plt.figure(figsize=(10,6)) fig = plt.figure(figsize=pst.set_size(args.width))
plt.plot(times, charges, marker = 'x', label = legstr) 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.ylabel('charge (C)')
plt.xlabel('time (s)') plt.xlabel('time (s)')
plt.legend() plt.legend()
@@ -102,11 +201,16 @@ if __name__ == '__main__':
os.makedirs(outname, exist_ok=True) 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-" outname += args.basename + "_chargeAgainstTime_species-"
for value in args.species: for value in args.species:
outname += value outname += value
outname += '.pdf' outname += '_test.pdf'
# print(outname) # print(outname)
plt.savefig(outname, format='pdf', bbox_inches = 'tight') plt.savefig(outname, format='pdf', bbox_inches = 'tight')
+1
View File
@@ -15,6 +15,7 @@ class MpiParticleReader {
MpiParticleReader(std::string abs_filename_without_extension, int restart_at); MpiParticleReader(std::string abs_filename_without_extension, int restart_at);
void readParticles(std::vector<particle::SerializedParticle>& storage_queue); void readParticles(std::vector<particle::SerializedParticle>& storage_queue);
void readParticles(std::vector<particle::SerializedParticle>& storage_queue, int nold);
private: private:
std::string absolute_filename_; std::string absolute_filename_;
+2
View File
@@ -46,9 +46,11 @@ class Restart {
// only load in the potential and calc the electric field // only load in the potential and calc the electric field
void restartPoissonSolver(PoissonSolver* solver); void restartPoissonSolver(PoissonSolver* solver);
void restartRandomNumbers(RandomNumbers* random); void restartRandomNumbers(RandomNumbers* random);
void restartRandomNumbers(RandomNumbers* random, int nold);
void restartParticles(std::vector<particle::SerializedParticle>& storage_queue); void restartParticles(std::vector<particle::SerializedParticle>& storage_queue);
bool do_restart_; bool do_restart_;
int process_number_old_; // number of processes of the state the simulation is restarted from
std::string restart_identifier_; // i.e. "LastSyncPeriod" or "SyncPeriod_*" std::string restart_identifier_; // i.e. "LastSyncPeriod" or "SyncPeriod_*"
Hdf5Reader reader_; Hdf5Reader reader_;
MpiParticleReader particle_reader_; MpiParticleReader particle_reader_;
+2 -1
View File
@@ -43,7 +43,8 @@ class SimulationOutput {
void writeMetaData( void writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
const std::shared_ptr<PoissonSolver>& poisson_solver); const std::shared_ptr<PoissonSolver>& poisson_solver,
std::string parameter_file_path);
void writeSimulationData( void writeSimulationData(
int cpu_sync, int cpu_sync,
+2
View File
@@ -83,6 +83,8 @@ class Simulation {
int timestep = 0; int timestep = 0;
int injectionGroupOffset = 0; int injectionGroupOffset = 0;
std::string parameter_file_path_;
}; };
#endif /* SIMULATION_H */ #endif /* SIMULATION_H */
+10 -10
View File
@@ -20,7 +20,7 @@ blitz::Array<double, 3> Hdf5Reader::readD3Double(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -50,7 +50,7 @@ blitz::Array<double, 2> Hdf5Reader::readD2Double(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -79,7 +79,7 @@ blitz::Array<double, 1> Hdf5Reader::readD1Double(std::string path) {
hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
// H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); // H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -109,7 +109,7 @@ double Hdf5Reader::readDouble(std::string path) {
hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
// H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); // H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -139,7 +139,7 @@ int Hdf5Reader::readInt(std::string path) {
hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); hid_t dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
// H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); // H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -170,7 +170,7 @@ blitz::Array<double, 4> Hdf5Reader::readD4Double(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -200,7 +200,7 @@ blitz::Array<double, 5> Hdf5Reader::readD5Double(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -230,7 +230,7 @@ blitz::Array<long int, 4> Hdf5Reader::readD4LongInt(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -260,7 +260,7 @@ blitz::Array<long int, 5> Hdf5Reader::readD5LongInt(std::string path) {
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT); dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
@@ -293,7 +293,7 @@ std::stringstream Hdf5Reader::readEngineString(std::string path) {
hid_t dataset = H5Dopen2(file, (path + "/string").c_str(), H5P_DEFAULT); hid_t dataset = H5Dopen2(file, (path + "/string").c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset); hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) { if (dataset < 0) {
ERROR("The given dataset could not be opened"); ERROR("The given dataset could not be opened " + path);
} }
// turn error report back onby hdf5 because of check H5Dopen2 // turn error report back onby hdf5 because of check H5Dopen2
// H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT); // H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
+166
View File
@@ -145,3 +145,169 @@ void MpiParticleReader::readParticles(
MPI_Type_free(&cpu_header_type); MPI_Type_free(&cpu_header_type);
MPI_Info_free(&info); MPI_Info_free(&info);
} }
void MpiParticleReader::readParticles(
std::vector<particle::SerializedParticle>& storage_queue, int nold) {
MPI_Comm io_comm;
// io_group: from which previous process has to be read
// io_rank : the rank of this process within io_group
// io_group_size: the size of the group of processes with a specific io_group
int io_rank, io_group, io_group_size;
io_comm = MPI_COMM_WORLD;
io_group = MpiCommunication::mpiRank() % nold;
io_rank = MpiCommunication::mpiRank() / nold;
io_group_size = MpiCommunication::mpiSize() / nold;
if(io_group < MpiCommunication::mpiSize() % nold) {
io_group_size += 1;
}
#ifdef debug_level3
fprintf(stdout, "<%d>: io_group: %d, io_rank: %d, io_group_size: %d\n",
MpiCommunication::mpiRank(), io_group, io_rank, io_group_size);
#endif
#ifdef debug
DEBUG_LEVEL_0("Reading particles from: " + absolute_filename_);
#endif
int status;
MPI_Datatype particle_type;
if(sizeof(particle::SerializedParticle) % sizeof(double) != 0) {
ERROR("Size of SerializedParticle is not a multiple of the size of double!");
}
status = MPI_Type_contiguous(sizeof(particle::SerializedParticle)/sizeof(double),
MPI_DOUBLE, &particle_type);
status |= MPI_Type_commit(&particle_type);
if(status) {
ERROR("Particle data type could not be defined!");
}
MPI_Info info;
MPI_Info_create(&info);
// open file
MPI_File file;
MPI_Status mstatus;
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reading particles from: " + absolute_filename_);
#endif
status = MPI_File_open(io_comm, (char*)absolute_filename_.c_str(),
MPI_MODE_RDONLY, info, &file);
if(status) {
ERROR("Particle file \'" + absolute_filename_ + "\' could not be opened!");
}
//read file header
MPI_Datatype file_header_type = build_file_header_type();
mpi_io_header_t file_header;
status = MPI_File_set_view(file, 0, file_header_type, file_header_type,
(char*)"native", info);
if(status) {
ERROR("View for file header could not be set!");
}
status = MPI_File_read_all(file, &file_header, 1, file_header_type, &mstatus);
if(status) {
ERROR("File header could not be read (status: " + std::to_string(status) +
")!");
}
if(!file_header.verify()) {
ERROR("File header does not verify!");
}
// read CPU header
std::uint64_t headeroffset = file_header.cpu_header_offset +
sizeof(cpu_header_t)*io_group;
MPI_Datatype cpu_header_type = build_cpu_header_type();
cpu_header_t cpu_header;
status = MPI_File_set_view(file, headeroffset, cpu_header_type, cpu_header_type,
(char*)"native", info);
if(status) {
ERROR("File view for the CPU header could not be set!");
}
status = MPI_File_read_all(file, &cpu_header, 1, cpu_header_type, &mstatus);
if(status) {
ERROR("CPU header could not be read!");
}
storage_queue.reserve(cpu_header.num_particles);
// particle number if they were equally distributed across procs
size_t particle_number = cpu_header.num_particles / io_group_size;
int overflow = cpu_header.num_particles % io_group_size;
// calculate offset from particles read by other processes in this io_group
std::uint64_t this_offset = cpu_header.file_offset;
this_offset += io_rank*particle_number*sizeof(particle::SerializedParticle);
// fprintf(stdout, "<%d>: offset: %ld, numpart: %ld\n", MpiCommunication::mpiRank(), this_offset, particle_number);
this_offset = io_rank < overflow ? this_offset + io_rank*sizeof(particle::SerializedParticle)
: this_offset + overflow*sizeof(particle::SerializedParticle);
// fprintf(stdout, "<%d>: offset: %ld, sizeof(SerializedParticle): %ld\n", MpiCommunication::mpiRank(), this_offset, sizeof(particle::SerializedParticle));
// correct number of particles for this proc
particle_number = (io_rank < overflow) ? particle_number + 1 : particle_number;
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
{
std::stringstream out;
out << io_rank << ": trying to read " << cpu_header.num_particles;
out << " many particles";
DEBUG_LEVEL_1(out.str());
}
#endif
// set file view to the part where the particles are stored
status = MPI_File_set_view(file, this_offset, MPI_DOUBLE,
particle_type, (char*)"native", info);
if(status) {
ERROR("File view for the Particles could not be set!");
}
storage_queue.resize(particle_number);
// read the particles
status = MPI_File_read_all(file, storage_queue.data(), particle_number,
particle_type, &mstatus);
if(status) {
ERROR("Particles could not be read (status: " + std::to_string(status) +
")!");
}
#ifdef debug_level3
{
// print first and last loaded particle to check if the alignment is sensible (i.e. no two processes load the same particle)
std::stringstream out;
out << "group: " << io_group << ", rank: "<< io_rank;
out << ": number of particles in queue: " << storage_queue.size();
out << "\nposition of first serialized particle: " << storage_queue[0].cartesianPosition();
out << "\nvelocity of first serialized particle: " << storage_queue[0].cartesianVelocity();
out << "\nweight of first serialized particle: " << storage_queue[0].weight();
out << "\nspecname of first serialized particle: " << storage_queue[0].specieName();
out << "\n";
out << "group: " << io_group << ", rank: "<< io_rank;
out << "\nposition of last serialized particle: " << storage_queue[particle_number - 1].cartesianPosition();
out << "\nvelocity of last serialized particle: " << storage_queue[particle_number - 1].cartesianVelocity();
out << "\nweight of last serialized particle: " << storage_queue[particle_number - 1].weight();
out << "\nspecname of last serialized particle: " << storage_queue[particle_number - 1].specieName();
DEBUG_LEVEL_1(out.str());
}
#endif
// close everything
MPI_File_close(&file);
MPI_Type_free(&particle_type);
MPI_Type_free(&file_header_type);
MPI_Type_free(&cpu_header_type);
MPI_Info_free(&info);
}
+72 -7
View File
@@ -39,11 +39,47 @@ void Restart::restart(
if(!do_restart_) { if(!do_restart_) {
return; return;
} }
#ifdef debug_level1
SIM_INFO("Reading number of previous processes.");
process_number_old_ = reader_.readInt("NumberProcesses");
if(process_number_old_ > MpiCommunication::mpiSize()) {
ERROR("Number of processes changes between restart! (old: " + std::to_string(process_number_old_)
+ ", new: " + std::to_string(MpiCommunication::mpiSize()) + ")");
}
SIM_INFO("Restarting from earlier state.");
if(process_number_old_ < MpiCommunication::mpiSize()) {
SIM_INFO("Warning: Restarting from a state with fewer processes. (#old: " +
std::to_string(process_number_old_) +
", #now: " +
std::to_string(MpiCommunication::mpiSize()) + ")");
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting rng"); DEBUG_LEVEL_1("Restarting rng");
#endif #endif
restartRandomNumbers(random_numbers, process_number_old_);
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reloading particles.");
#endif
particle_reader_.readParticles(storage_queue, process_number_old_);
} else {
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting rng");
#endif
restartRandomNumbers(random_numbers); restartRandomNumbers(random_numbers);
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reloading particles.");
#endif
particle_reader_.readParticles(storage_queue);
}
#ifdef debug_level1 #ifdef debug_level1
DEBUG_LEVEL_1("Restarting poisson solver."); DEBUG_LEVEL_1("Restarting poisson solver.");
#endif #endif
@@ -65,11 +101,6 @@ void Restart::restart(
std::string path = "/RestartInfo/" + restart_identifier_ + "/InjectionGroupOffset"; std::string path = "/RestartInfo/" + restart_identifier_ + "/InjectionGroupOffset";
injectionGroupOffset = reader_.readInt(path); injectionGroupOffset = reader_.readInt(path);
} }
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reloading particles.");
#endif
particle_reader_.readParticles(storage_queue);
} }
void Restart::restartRandomNumbers(RandomNumbers* random) { void Restart::restartRandomNumbers(RandomNumbers* random) {
@@ -88,6 +119,40 @@ void Restart::restartRandomNumbers(RandomNumbers* random) {
} }
} }
void Restart::restartRandomNumbers(RandomNumbers* random, int nold) {
int io_group, io_rank;
io_group = MpiCommunication::mpiRank() % nold;
io_rank = MpiCommunication::mpiRank() / nold;
std::string path = "/RestartInfo/" + restart_identifier_
+ "/CPU_" + std::to_string(io_group);
std::stringstream engine_state = reader_.readEngineString(path);
std::mt19937* engine = random->engine();
engine_state >> *engine;
std::stringstream check;
check << *engine;
if(check.str() != engine_state.str()) {
ERROR("Something went wrong in the initialization of the "
"random engine.");
}
// discard the first io_rank values
(*engine).discard(io_rank);
// draw the next value of the current engine
size_t seed = (*engine)();
// fprintf(stdout, "<%d>: io_group: %d, seed: %ld\n", MpiCommunication::mpiRank(), io_group, seed);
// use this value as a seed and create a temporary mt19937 object
std::mt19937 tmp(seed);
// serialize and de-serialize it to set the pointer of the actual engine (likely not the best implementation)
engine_state << tmp;
engine_state >> *engine;
}
// only restart the time from which the simulation is restarted. // only restart the time from which the simulation is restarted.
void Restart::restartTimer(species::TrackedSpecie* reference_specie) { void Restart::restartTimer(species::TrackedSpecie* reference_specie) {
double time; double time;
+20 -1
View File
@@ -1,3 +1,4 @@
#include <fstream>
#include "mpi.h" #include "mpi.h"
#include "IO/simulation_output.h" #include "IO/simulation_output.h"
#include "IO/hdf5_writer.h" #include "IO/hdf5_writer.h"
@@ -43,7 +44,8 @@ void SimulationOutput::setParticleOutput(OutputTask task) {
void SimulationOutput::writeMetaData( void SimulationOutput::writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
const std::shared_ptr<PoissonSolver>& poisson_solver) { const std::shared_ptr<PoissonSolver>& poisson_solver,
std::string parameter_file_path) {
if (MpiCommunication::mpi_rank == 0) { if (MpiCommunication::mpi_rank == 0) {
for (auto& pair : species) { for (auto& pair : species) {
writeMetaData(pair.second.get()); writeMetaData(pair.second.get());
@@ -70,6 +72,23 @@ void SimulationOutput::writeMetaData(
{ {
writer.write(MpiCommunication::mpiSize(), "/NumberProcesses"); writer.write(MpiCommunication::mpiSize(), "/NumberProcesses");
} }
// write the json file to the hdf output
{
std::stringstream file;
std::ifstream istream(parameter_file_path.c_str());
istream >> file.rdbuf();
// find occurance of last slash in the path of the parameter
size_t slshidx = parameter_file_path.rfind("/");
// if its a relative path append a slash otherwise use the substring from the last slash onwards
std::string hdf5path = (slshidx == std::string::npos) ?
"/" + parameter_file_path :
parameter_file_path.substr(slshidx);
writer.write(file.str(), hdf5path);
}
} }
} }
+6 -4
View File
@@ -39,7 +39,7 @@
#include "tools/simulation_time.h" #include "tools/simulation_time.h"
Simulation::Simulation(std::string parameter_filename) Simulation::Simulation(std::string parameter_filename)
: parameter_(parameter_filename) { : parameter_(parameter_filename), parameter_file_path_(parameter_filename) {
init(parameter_); init(parameter_);
} }
@@ -112,7 +112,7 @@ void Simulation::init(Parameter& parameter) {
#ifdef debug #ifdef debug
DEBUG_LEVEL_0("Output meta data."); DEBUG_LEVEL_0("Output meta data.");
#endif #endif
output_->writeMetaData(tracked_species_, poisson_solver_); output_->writeMetaData(tracked_species_, poisson_solver_, parameter_file_path_);
} }
int eventsThisCpu(int events_all_cpus) { int eventsThisCpu(int events_all_cpus) {
@@ -378,7 +378,9 @@ void Simulation::processUntilTermination(particle::Particle& particle) {
#endif #endif
auto old_position = particle.cylinderPosition(); auto old_position = particle.cylinderPosition();
double old_energy = particle.kineticEnergy_eV(); double old_energy = particle.kineticEnergy_eV();
while (particle.specie()->terminator()->isAlive(&particle, old_position)) { bool was_reflected = false;
while (particle.specie()->terminator()->isAlive(&particle, old_position) || was_reflected) {
old_position = particle.cylinderPosition(); old_position = particle.cylinderPosition();
old_energy = particle.kineticEnergy_eV(); old_energy = particle.kineticEnergy_eV();
@@ -403,7 +405,7 @@ void Simulation::processUntilTermination(particle::Particle& particle) {
gravity_field_.get()); gravity_field_.get());
SimulationTimer::eventStopPoint(std::string("Mover")); SimulationTimer::eventStopPoint(std::string("Mover"));
bool was_reflected = false; was_reflected = false;
if (particle.specie()->reflector()->needsReflectionBackToDomain( if (particle.specie()->reflector()->needsReflectionBackToDomain(
&particle)) { &particle)) {
#ifdef debug_level3 #ifdef debug_level3