built restart utilities

This commit is contained in:
2024-09-03 16:02:40 +02:00
parent c33629cb88
commit 9c45fce644
11 changed files with 341 additions and 7 deletions
+3 -1
View File
@@ -13,9 +13,11 @@ class Hdf5Reader {
blitz::Array<double, 3> readD3Double(std::string path);
blitz::Array<double, 2> readD2Double(std::string path);
blitz::Array<double, 1> readD1Double(std::string path);
std::stringstream readEngineString(std::string path);
blitz::Array<long int, 4> readD4LongInt(std::string path);
std::stringstream readEngineString(std::string path);
private:
std::string absolute_filename_;
};
+42
View File
@@ -0,0 +1,42 @@
#ifndef RESTART_H
#define RESTART_H
#include <string>
#include <map>
#include <memory>
#include "IO/hdf5_reader.h"
namespace species {
class TrackedSpecie;
enum class ImplementedSpecies;
}; // namespace species
class DynamicDensityField;
class PoissonSolver;
class RandomNumbers;
// Note: The restarts for the DensirtField and the PoissonSolver require that the
// partitioning of the simulation space does not change between the original and
// the restarted simulation
// Note: think if it's better (or more consistent) to set the dynamic electric field
// here after the potential is loaded; would need the electric field class to be included
class Restart {
public:
Restart(bool do_restart, std::string absolute_filename,
std::string restart_identifier);
void restart(std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, RandomNumbers* random_numbers);
private:
void restartTimer(species::TrackedSpecie* reference_specie);
void restartDrawingDensityField(DynamicDensityField* field, std::string path); // only necc densityfield for the one that is drawn from
void restartPoissonSolver(PoissonSolver* solver); // only load in the potential and calc the electric field
void restartRandomNumbers(RandomNumbers* random);
bool do_restart_;
std::string restart_identifier_; // i.e. "LastSyncPeriod" or "SyncPeriod_*"
Hdf5Reader reader_;
};
#endif /* RESTART_H */
+15
View File
@@ -0,0 +1,15 @@
#ifndef RESTART_GENERATOR_H
#define RESTART_GENERATOR_H
#include "jansson.h"
#include "simulation/parameter.h"
class Restart;
namespace generator{
Restart buildRestart(json_t* object);
Restart buildRestart(Parameter& parameter);
}; // namespace generator
#endif /* RESTART_GENERATOR_H */
+2
View File
@@ -63,6 +63,8 @@ class PoissonSolver {
std::shared_ptr<VectorField> staticElectricField();
const CylinderBinning* densityBinning();
void setPotential(blitz::Array<double, 3>& potential);
private:
GlobalBoundary bottom_boundary_;
GlobalBoundary top_boundary_;
+6 -1
View File
@@ -42,7 +42,6 @@ class DynamicDensityField : public DensityField {
double particleNumber();
blitz::TinyVector<double, 4> drawPositionAndEnergy(std::mt19937* engine);
void setDensityDistribution();
void resetDynamicDensityField();
@@ -58,6 +57,10 @@ class DynamicDensityField : public DensityField {
double physicalTime() const;
double timeResolution() const;
void restartTimer(double time, double delta_t);
void restartTimeInBin(blitz::Array<double, 4> time_in_bin);
void restartDeletedParticlesArray(blitz::Array<long int, 4> deleted_particles);
friend class CpuSynchronizer;
private:
@@ -77,6 +80,7 @@ class DynamicDensityField : public DensityField {
BinCoordinate densityBin(const CylinderCoordinate& position) const;
void recalculateDensityArray();
void initPositionDistributions();
void setDensityDistribution();
blitz::Array<double, 4> time_in_bin_s_;
blitz::Array<long int, 4> deleted_particles_;
@@ -97,6 +101,7 @@ class DynamicDensityField : public DensityField {
const EnergyBinning energy_binning_;
std::shared_ptr<Timer> timer_;
bool timer_restarted_ = false;
};
class ConstantDensityField : public DensityField {
+133
View File
@@ -0,0 +1,133 @@
#include <sstream>
#include <random>
#include "IO/restart.h"
#include "simulation/random_numbers.h"
#include "simulation/mpi_communication.h"
#include "simulation/errors.h"
#include "simulation/species.h"
#include "simulation/density_field.h"
#include "poisson_solver/poisson_solver.h"
#include "simulation/timer.h"
// Note: error handling is a bit messy. Sometimes it's dealt with in the
// called reset function (e.g. in the density field) and sometimes it's
// handled here
Restart::Restart(bool do_restart, std::string absolute_filename,
std::string restart_identifier):
do_restart_(do_restart),
restart_identifier_(restart_identifier),
reader_(Hdf5Reader(absolute_filename)) {}
void Restart::restart(std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, RandomNumbers* random_numbers) {
if(!do_restart_) {
return;
}
DEBUG_LEVEL_3("Restarting rng");
restartRandomNumbers(random_numbers);
DEBUG_LEVEL_3("Restarting poisson solver.");
restartPoissonSolver(poisson_solver);
DEBUG_LEVEL_3("Restarting timer.");
restartTimer(species.begin()->second.get());
for(const auto& pair: species) {
std::string path = pair.second->name() + "/DensityField/SimulationData/" +
restart_identifier_;
restartDrawingDensityField(pair.second->densityForDrawing(), path);
}
}
void Restart::restartRandomNumbers(RandomNumbers* random) {
std::string path = "/RestartInfo/" + restart_identifier_
+ "/CPU_" + std::to_string(MpiCommunication::mpiRank());
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.");
}
// DEBUG_LEVEL_3("Restart of random engine worked");
// std::uniform_real_distribution<double> dist(0,1);
// DEBUG_LEVEL_3("first value after loading rng: " + std::to_string(dist(*engine)));
}
// only restart the time from which the simulation is restarted.
// The "timestep" is calculated from the json input data (same as no restart).
void Restart::restartTimer(species::TrackedSpecie* reference_specie) {
double time;
double delta_t;
// physical time
{
std::string path = reference_specie->name() + "/DensityField/SimulationData/" +
restart_identifier_ + "/PhysicalTime";
DEBUG_LEVEL_3(path);
// probably add a function in the reader to read a single double value instead of
// a 1d array of doubles
blitz::Array<double, 1> restart_time = reader_.readD1Double(path);
if(restart_time.size() != 1) {
ERROR("Physical time should be a single double value but " +
std::to_string(restart_time.size()) +
" was read by the hdf5 reader.");
}
time = restart_time(0);
}
// delta t
{
std::string path = reference_specie->name() + "/CurrentCollector/SimulationData/" +
restart_identifier_ + "/PhysicalTime";
DEBUG_LEVEL_3(path);
// probably add a function in the reader to read a single double value instead of
// a 1d array of doubles
blitz::Array<double, 1> time_resolution = reader_.readD1Double(path);
if(time_resolution.size() != 1) {
ERROR("Physical time should be a single double value but " +
std::to_string(time_resolution.size()) +
" was read by the hdf5 reader.");
}
delta_t = time_resolution(0);
}
reference_specie->dynamicDensityField()->restartTimer(time, delta_t);
return;
}
void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string path) {
// restart TimeInBin-field
{
std::string path_to_data = path + "/TimeInBin";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<double, 4> time_in_bin = reader_.readD4Double(path_to_data);
field->restartTimeInBin(time_in_bin);
}
// restart deleted particles
{
std::string path_to_data = path + "/DeletedParticles";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<long int, 4> deleted_particles = reader_.readD4LongInt(path_to_data);
field->restartDeletedParticlesArray(deleted_particles);
}
return;
}
// could be removed, but then the potential has to be calculated
// as in the normal simulation cycle
void Restart::restartPoissonSolver(PoissonSolver* solver) {
std::string path = "PoissonSolver/SimulationData/" + restart_identifier_ +
"/Potential/";
DEBUG_LEVEL_3(path);
blitz::Array<double, 3> potential = reader_.readD3Double(path);
if(!blitz::all(potential.length() == solver->potential().length())) {
DEBUG_LEVEL_3("Restart Poissonsolver: wrong sizes of the potential");
}
solver->setPotential(potential);
}
+38
View File
@@ -0,0 +1,38 @@
#include "generators/restart_generator.h"
#include "IO/restart.h"
#include "generators/vector_field_generator.h"
namespace generator {
Restart buildRestart(json_t* object) {
DEBUG_LEVEL_3("Build Restart.");
bool do_restart = json_bool(json_object_by_path(object, {"Do"}));
if (!do_restart) {
DEBUG_LEVEL_3("No Restart desired");
return Restart(false, "", "");
}
std::string filepath = readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}));
DEBUG_LEVEL_3("Restart: file path:" + filepath);
std::string identifier;
int sync_period = json_int(json_object_by_path(object, {"SyncPeriod"}));
if(sync_period == 0 && json_string(json_object_by_path(object, {"SyncPeriod"}))
== "LastSyncPeriod") {
identifier = "LastSyncPeriod";
} else {
ASSERT_POSITIVE(&sync_period, "The SyncPeriod for the restart has to be either"
" positive or \"LastSyncPeriod\".");
identifier = "SyncPeriod_" + std::to_string(sync_period);
}
DEBUG_LEVEL_3("Restart: SyncPeriod to be started from: " + identifier);
return Restart(do_restart, filepath, identifier);
}
Restart buildRestart(Parameter& parameter) {
return buildRestart(
json_object_by_path(parameter.jsonFile(), {"Restart"}));
}
} // namespace generator
@@ -166,7 +166,7 @@ std::shared_ptr<SimulationOutput> buildSimulationOutput(
}
ASSERT_NOTNEGATIVE(&intervall, "The intervall for RestartInfo has to be either 0"
",if no output is required or positive otherwise");
DEBUG_LEVEL_3("Restart Interval: " + std::to_string(intervall));
DEBUG_LEVEL_3("Restart output interval: " + std::to_string(intervall));
bool overwrite_last = json_bool(
json_object_by_path(object, {"RestartInfo", "OverwriteLast"}));
+18
View File
@@ -355,6 +355,24 @@ const CylinderBinning* PoissonSolver::densityBinning() {
return &density_binning_;
}
void PoissonSolver::setPotential(blitz::Array<double, 3>& potential) {
// check if the loaded potential has the same size as the potential
// specified by the json file
if(!blitz::all(potential.length() == potential_.length())) {
std::stringstream out;
out << "The size of the potential is " << potential.length();
out << ". But expected a size of " << potential_.length();
ERROR(out.str());
}
for(int i = potential_.lbound(0); i <= potential_.ubound(0); ++i) {
for(int j = potential_.lbound(1); j <= potential_.ubound(1); ++j) {
for(int k = potential_.lbound(2); k <= potential_.ubound(2); ++k) {
potential_(i,j,k).value = potential(i,j,k);
}
}
}
}
Electrode::Electrode(double potential): potential_(potential) {};
double Electrode::electrodePotential() {
+39
View File
@@ -232,6 +232,7 @@ blitz::TinyVector<double, 4> DynamicDensityField::drawPositionAndEnergy(
DEBUG_LEVEL_3("Density is empty");
return blitz::TinyVector<double, 4> (0,0,0,0);
}
setDensityDistribution();
double random_r, random_z, random_phi, random_E, random_n;
double density_in_random_cell;
@@ -324,6 +325,44 @@ void DynamicDensityField::resetDynamicDensityField() {
sync_deleted_particles_ = 0.;
}
void DynamicDensityField::restartTimer(double time, double delta_t) {
// make sure that the timer can only be restarted once (per dynamicDensityField object)
// probably not necessary, but whatever
if(timer_restarted_) {
return;
}
timer_restarted_ = true;
timer_->setTime(time);
timer_->setDeltaT(delta_t);
}
void DynamicDensityField::restartTimeInBin(blitz::Array<double, 4> time_in_bin) {
if(!blitz::all(time_in_bin_s_.length() == time_in_bin.length())) {
std::stringstream out;
out << "Expected a size of " << time_in_bin_s_.length();
out << ", received a length of " << time_in_bin.length();
out << " for time_in_bin array";
ERROR(out.str());
}
std::stringstream out;
out << "Before: " << time_in_bin_s_;
time_in_bin_s_ = time_in_bin.copy();
out << "After: " << time_in_bin_s_;
// DEBUG_LEVEL_0(out.str());
}
void DynamicDensityField::restartDeletedParticlesArray(
blitz::Array<long int, 4> deleted_particles) {
if(!blitz::all(deleted_particles_.length() == deleted_particles.length())) {
std::stringstream out;
out << "Expected a size of " << deleted_particles_.length();
out << ", received a length of " << deleted_particles.length();
out << " for deleted_particles array";
ERROR(out.str());
}
deleted_particles_ = deleted_particles.copy();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
+44 -4
View File
@@ -1,4 +1,5 @@
#include "simulation/simulation.h"
#include "mpi.h"
#include <numeric>
#include <random>
#include <vector>
@@ -20,6 +21,7 @@
#include "poisson_solver/poisson_solver.h"
#include "IO/simulation_output.h"
#include "IO/restart.h"
#include "generators/electric_field_generator.h"
#include "generators/injector_generator.h"
@@ -29,6 +31,7 @@
#include "generators/species_generator.h"
#include "generators/poisson_solver_generator.h"
#include "generators/gravity_field_generator.h"
#include "generators/restart_generator.h"
#include "tools/simulation_time.h"
@@ -59,16 +62,25 @@ void Simulation::init(Parameter& parameter) {
poisson_solver_ = generator::buildPoissonSolver(parameter);
electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
DEBUG_LEVEL_0("Init cpu synchronizer.");
cpu_synchronizer_ = std::make_shared<CpuSynchronizer>();
DEBUG_LEVEL_3("Init done.");
Restart restarter = generator::buildRestart(parameter);
restarter.restart(tracked_species_, poisson_solver_.get(), random_.get());
// poisson solver is restarted -> set the electric field from the potential
electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
// make sure every proc is done with loading its restart info before
// writing the metadata
MPI_Barrier(MPI_COMM_WORLD);
DEBUG_LEVEL_0("Init output.");
output_ = generator::buildSimulationOutput(
parameter.jsonObjectFromBase({"Output"}), tracked_species_);
DEBUG_LEVEL_0("Output meta data.");
output_->writeMetaData(tracked_species_, poisson_solver_);
DEBUG_LEVEL_0("Init cpu synchronizer.");
cpu_synchronizer_ = std::make_shared<CpuSynchronizer>();
DEBUG_LEVEL_3("Init done.");
}
int eventsThisCpu(int events_all_cpus) {
@@ -115,9 +127,28 @@ void Simulation::start() {
int leftover_events_time_resolution = time_resolution_this_cpu;
const double delta_t = time_resolution_events*injector_->timePassed();
if(delta_t != timer_->getDeltaT()) {
std::stringstream out;
out << "Old delta t: " << timer_->getDeltaT();
out << "; new delta t: " << delta_t;
out << ". Currently not supported (leads to errors in the density calculated from "
"the loaded data)";
ERROR(out.str());
}
timer_->setDeltaT(delta_t);
injector_->initInjectionTimeDistribution(delta_t);
// // debugging(
// for(auto& pair : tracked_species_) {
// std::stringstream out;
// out << pair.second->name() << ": ";
// out << pair.second->densityForDrawing()->particleNumber();
// DEBUG_LEVEL_0(out.str());
// }
// // )debugging
int num_cpu_syncs = 0;
bool reset = true;
@@ -147,6 +178,15 @@ void Simulation::start() {
num_cpu_syncs += 1;
SimulationTimer::eventStopPoint(std::string("CpuSync"));
// // debugging(
// for(auto& pair : tracked_species_) {
// std::stringstream out;
// out << pair.second->name() << ": ";
// out << pair.second->densityForDrawing()->particleNumber();
// DEBUG_LEVEL_0(out.str());
// }
// // )debugging
SIM_INFO("Poisson step.");
SimulationTimer::eventStartPoint(std::string("PoissonStep"));
poisson_solver_->solvePotential(chargedensity(), reset);