Files
karl/src/simulation/simulation.cpp
T
2025-02-18 11:17:24 +01:00

597 lines
22 KiB
C++
Executable File

#include "simulation/simulation.h"
#include "mpi.h"
#include <numeric>
#include <random>
#include <vector>
#include "constants/sim_constants.h"
#include "simulation/cpu_synchronizer.h"
#include "simulation/current_collector.h"
#include "simulation/density_field.h"
#include "simulation/electromagnetic_field.h"
#include "simulation/errors.h"
#include "simulation/injector.h"
#include "simulation/interaction.h"
#include "simulation/logger.h"
#include "simulation/mover.h"
#include "simulation/mpi_communication.h"
#include "simulation/particle.h"
#include "simulation/random_numbers.h"
#include "simulation/reflector.h"
#include "simulation/terminator.h"
#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"
#include "generators/magnetic_field_generator.h"
#include "generators/random_numbers_generator.h"
#include "generators/simulation_output_generator.h"
#include "generators/species_generator.h"
#include "generators/poisson_solver_generator.h"
#include "generators/gravity_field_generator.h"
#include "generators/restart_generator.h"
#include "simulation/event_position_distribution.h"
#include "tools/simulation_time.h"
Simulation::Simulation(std::string parameter_filename)
: parameter_(parameter_filename) {
init(parameter_);
}
void Simulation::init(Parameter& parameter) {
magnetic_field_ = generator::magneticField(parameter);
electric_field_ = generator::electricField(parameter);
gravity_field_ = generator::gravityField(parameter);
DEBUG_LEVEL_0("Creating species.");
generator::SpeciesBuilder builder(parameter);
tracked_species_ = builder.trackedSpecies();
background_species_ = builder.backgroundSpecies();
timer_ = builder.timer();
DEBUG_LEVEL_0("Creating injector.");
injector_ = generator::buildInjector(tracked_species_, background_species_,
parameter);
DEBUG_LEVEL_0("Init random numbers.");
random_ = generator::buildRandomNumbers(parameter);
DEBUG_LEVEL_0("Init poisson solver.");
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_);
}
int eventsThisCpu(int events_all_cpus) {
int events = events_all_cpus / MpiCommunication::mpi_size;
int overflow = events_all_cpus % MpiCommunication::mpi_size;
if (MpiCommunication::mpi_rank < overflow) {
events += 1;
}
return events;
}
int eventsOfCycle(int stride, int leftover_events) {
if ((leftover_events - stride) >= 0) {
return stride;
} else {
return leftover_events;
}
}
void Simulation::finalize() {
SIM_INFO("Simulation ended.");
}
void Simulation::start() {
SIM_INFO("Starting Simulation.");
// stride wrt the number of beta decay events per CPU
const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
// number of timesteps to be simulated
const int number_timesteps = parameter_.intValue(json_path({"Simulation",
"NumberTimesteps"}), 1);
// number of physical beta events defining the timescale through
// time_resolution_events/Activity
const int time_resolution_events =
parameter_.intValue(json_path({"Simulation", "TimeResolutionEvents"}),
MpiCommunication::mpiSize());
// number of beta decay events per timestep and CPU (will get normalized s.t.
// the physical number of particles is correct)
const int beta_decay_events =
parameter_.intValue(json_path{"Simulation", "BetaDecayEventsPerCPU"}, 1);
// weight of a particle created through beta decay wrt a physical particle
const double beta_particle_weight = time_resolution_events/
static_cast<double>(beta_decay_events*MpiCommunication::mpiSize());
// number of density events per timestep and CPU
const int density_events =
parameter_.intValue(json_path({"Simulation", "DensityEventsPerCPU"}), 0);
// calculate a 'stride' for the density events s.t. the same number of syncs
// would be performed
const int density_stride = std::ceil(density_events *
(static_cast<double>(event_stride)/beta_decay_events));
// calculate the scaling factor for the particle weight for particles
// drawn from the density
const double density_weight_factor =
1./(MpiCommunication::mpiSize()*density_events);
DEBUG_LEVEL_0("Density events per cpu: " + std::to_string(density_events));
SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps));
SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride));
int leftover_events_time_resolution = beta_decay_events;
int leftover_density_events = density_events;
const double delta_t = time_resolution_events*injector_->timePassed();
// if delta_t of the timer after creation and potential restart is 0, then
// it's indicative of no restart having occured (a simulation with a delta_t
// of 0 would not be sensible)
if(timer_->getDeltaT() != 0 && 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);
int num_cpu_syncs = 0;
bool reset = true;
int timesteps = 0;
queue_.reserve(100);
timer_->increaseTimestep(delta_t);
while (timesteps < number_timesteps) {
#if defined debug_level3
std::stringstream out;
out << "Timeinterval: " << timer_->time() << "s.";
DEBUG_LEVEL_3(out.str());
#endif
// calculate the number of beta events to be simulated before a
// cpu sync is done
int events_of_cycle =
eventsOfCycle(event_stride, leftover_events_time_resolution);
int density_events_of_cycle =
eventsOfCycle(density_stride, leftover_density_events);
DEBUG_LEVEL_1("Events of cycle: " + std::to_string(events_of_cycle));
DEBUG_LEVEL_1("Density Events of cycle: " +
std::to_string(density_events_of_cycle));
SIM_INFO("Processing timestep: " + std::to_string(timesteps));
SIM_INFO("Leftover events this timestep this CPU: " +
std::to_string(leftover_events_time_resolution));
SIM_INFO("Leftover density events this timestep this CPU: " +
std::to_string(leftover_density_events));
// process both density and beta events before a cpu synchronization
processDensityEvents(density_events_of_cycle, density_weight_factor);
processEvents(events_of_cycle, beta_particle_weight);
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timesteps));
DEBUG_LEVEL_1("Leftover events this timestep: " +
std::to_string(leftover_events_time_resolution));
leftover_events_time_resolution -= events_of_cycle;
leftover_density_events -= density_events_of_cycle;
reset = !(leftover_events_time_resolution > 0);
SIM_INFO("Cpu sync.");
SimulationTimer::eventStartPoint(std::string("CpuSync"));
// 'reset' necessary as parameter to set the density for drawing
// otherwise it would be more difficult to set it... (cpu synchronizer
// is a friend class of the density field, i.e. has access to the
// private members)
cpu_synchronizer_->synchronize(tracked_species_, reset);
num_cpu_syncs += 1;
SimulationTimer::eventStopPoint(std::string("CpuSync"));
// can probably be moved into the reset section and therefore
// the parameter 'reset' could probably be removed
SIM_INFO("Poisson step.");
SimulationTimer::eventStartPoint(std::string("PoissonStep"));
// only solves the potential anew if 'reset' is true
poisson_solver_->solvePotential(chargedensity(), reset);
electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
SimulationTimer::eventStopPoint(std::string("PoissonStep"));
SIM_INFO("Perform output.");
SimulationTimer::eventStartPoint(std::string("Output"));
output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get(),
random_->engine());
SimulationTimer::eventStopPoint(std::string("Output"));
SimulationTimer::eventStartPoint("Reset");
if(reset) {
SIM_INFO("Do resets and increase the timestep for timeresolution.");
for(auto& pair : tracked_species_) {
pair.second->dynamicDensityField()->resetDynamicDensityField();
pair.second->currentCollector()->resetCurrentCollector();
pair.second->deletionLogger()->resetDeletionLogger();
// the density from which new particles are drawn is only updated after a timestep
pair.second->positionDistributionFromDensity()->setMaximumDensity();
}
leftover_events_time_resolution = beta_decay_events;
leftover_density_events = density_events;
timer_->increaseTimestep(delta_t);
timesteps++;
}
SimulationTimer::eventStopPoint("Reset");
}
}
int particleNumberFromQueue(int queue_length, RandomNumbers* random) {
return random->rollUniform(0, queue_length);
}
void Simulation::processEvents(int events, const double beta_particle_weight) {
DEBUG_LEVEL_0("Processing events.");
int current_event = 0;
while ((current_event < events) || (!queue_.empty())) {
DEBUG_LEVEL_2("Current event: " + std::to_string(current_event));
if (queue_.empty()) {
std::vector<particle::Particle> new_particles;
current_event += 1;
DEBUG_LEVEL_2("Inject particles to queue.");
SimulationTimer::eventStartPoint(std::string("ParticleInjection"));
new_particles = determineInjectedParticles(random_.get(),
beta_particle_weight);
// construction of stringstream can take up a lot of computation time
// even if the debug output performs nothing therefore use the if defined
// preprocessor directive
#if defined debug_level3
for(auto& particle : new_particles) {
std::stringstream output_ss;
output_ss << particle.specie()->name() << " with velocity (cart): ";
output_ss << particle.velocity().cartesianEntries();
output_ss << " and position (cart)";
output_ss << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str());
}
#endif
SimulationTimer::eventStopPoint(std::string("ParticleInjection"));
DEBUG_LEVEL_2("Injected particles to queue.");
queue_.insert(queue_.end(), new_particles.begin(),
new_particles.end());
}
DEBUG_LEVEL_2("Particles in queue: " +
std::to_string(queue_.size()));
const int particle_number =
particleNumberFromQueue(queue_.size(), random_.get());
// extract particle from queue here, so that an extension of the queue does
// not mess up the reference
particle::Particle particle = queue_.at(particle_number);
queue_.erase(queue_.begin() + particle_number);
processUntilTermination(particle);
}
}
void Simulation::processDensityEvents(int events, const double weight_factor) {
DEBUG_LEVEL_0("Processing density events.");
int current_event = 0;
// calculate the number of particles currently contained within the densities
// of the different tracked species before injection in order to avoid
// the expensive recalculateDensityField funtion being calculated for every
// new injection event
std::map<std::string, double> particleNumbers;
for(auto& pair: tracked_species_) {
particleNumbers[pair.first] = (pair.second->densityForDrawing()->particleNumber());
}
while ((current_event < events) || (!queue_.empty())) {
DEBUG_LEVEL_2("Current event: " + std::to_string(current_event));
if (queue_.empty()) {
std::vector<particle::Particle> new_particles;
DEBUG_LEVEL_2("Current density event: " + std::to_string(current_event));
SimulationTimer::eventStartPoint(std::string("DensityInjection"));
new_particles = determineInjectedDensityParticles(random_.get(),
weight_factor, current_event, particleNumbers);
SimulationTimer::eventStopPoint(std::string("DensityInjection"));
#if defined debug_level3
for(auto& particle : new_particles) {
std::stringstream output_ss;
output_ss << particle.specie()->name() << " with velocity (cart): ";
output_ss << particle.velocity().cartesianEntries();
output_ss << " and position (cart)";
output_ss << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str());
}
#endif
// if no new particles could be injected from the density, it is not possible
// that during another iteration cycle new particles will be injected
// (drawing field only changes after timesteps)
if(new_particles.empty()) {
return;
}
current_event += 1;
queue_.insert(queue_.end(), new_particles.begin(), new_particles.end());
}
DEBUG_LEVEL_2("Particles in queue: " +
std::to_string(queue_.size()));
const int particle_number =
particleNumberFromQueue(queue_.size(), random_.get());
// extract particle from queue here, so that an extension of the queue does
// not mess up the reference
particle::Particle particle = queue_.at(particle_number);
queue_.erase(queue_.begin() + particle_number);
processUntilTermination(particle);
}
}
void Simulation::processUntilTermination(
particle::Particle& particle) {
DEBUG_LEVEL_3("Process particle until termination");
DEBUG_LEVEL_3("Weight of the particle: " + std::to_string(particle.weight()));
while (particle.specie()->terminator()->isAlive(&particle)) {
auto old_position = particle.position();
double old_energy = particle.kineticEnergy_eV();
std::vector<double> macroscopic_cross_sections_m;
SimulationTimer::eventStartPoint(std::string("MFP calculation"));
const double mfp_m = meanFreePath(particle, random_.get(),
macroscopic_cross_sections_m);
SimulationTimer::eventStopPoint(std::string("MFP calculation"));
SimulationTimer::eventStartPoint(std::string("Mover"));
particle.specie()->mover()->move(&particle, mfp_m, electric_field_.get(),
magnetic_field_.get(), gravity_field_.get());
SimulationTimer::eventStopPoint(std::string("Mover"));
bool was_reflected = false;
if (particle.specie()->reflector()->needsReflectionBackToDomain(
&particle)) {
DEBUG_LEVEL_3("Reflect particle.");
old_position = particle.position();
particle.specie()->reflector()->reflectBackToDomain(&particle);
particle.specie()->currentCollector()->collect(&particle, old_position);
was_reflected = true;
}
if (particle.specie()->terminator()->reachedMaxTimeAlive(
&particle)) {
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name() +
". Reached timeresolution.");
if(particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.position(),
DeletionType::max_time_alive);
}
break;
} else if (particle.specie()->terminator()->leftSimulationDomain(
&particle)) {
#if defined debug_level3
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name()
+ ". Left simulation domain.");
std::stringstream output_ss;
output_ss << "Position (cyl): " << particle.position().cylinderEntries();
output_ss << " (cart): " << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str());
#endif
if (particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.position(),
DeletionType::wall);
}
break;
}
if (!(particle.specie()->dynamicDensityField()->changedPositionBin(
old_position, particle.position())) &&
!(particle.specie()->dynamicDensityField()->changedEnergyBin(
old_energy, particle.kineticEnergy_eV())) &&
!was_reflected) {
DEBUG_LEVEL_3("Perform interaction.");
DEBUG_LEVEL_3("Number of Interactions: " +
std::to_string(particle.interactionCounter()));
DEBUG_LEVEL_3("Ekin before interact: " +
std::to_string(particle.kineticEnergy_eV()));
#if defined debug_level3
std::stringstream output_ss;
output_ss << "Position (cyl): " << particle.position().cylinderEntries();
// output_ss << "\n (cart): " << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str());
#endif
SimulationTimer::eventStartPoint(std::string("Interaction"));
interaction::InteractionOutput output = interact(particle, random_.get(),
macroscopic_cross_sections_m);
SimulationTimer::eventStopPoint(std::string("Interaction"));
particle.increaseInteractionCounter();
for (auto& new_particle : output.newParticles()) {
queue_.push_back(new_particle);
}
if (output.deleteCurrentParticle()) {
DEBUG_LEVEL_3(particle.specie()->name() + " removed due to interaction.");
break;
}
if (particle.specie()->terminator()->reachedMaxInteractions(&particle)) {
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name()
+ ". Reached max interactions.");
if (particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(
particle.position(), DeletionType::max_interactions);
}
break;
}
}
}
}
double Simulation::meanFreePath(particle::Particle& particle,
RandomNumbers* random,
std::vector<double>& macroscopic_cross_sections_m) {
double total_macroscopic_cross_section_m = 0.;
for (auto& interaction : particle.specie()->interactions()) {
double cross_section_tmp = interaction->macroscopicCrossSection(particle);
total_macroscopic_cross_section_m += cross_section_tmp;
macroscopic_cross_sections_m.push_back(cross_section_tmp);
}
if (total_macroscopic_cross_section_m <= 0.) {
return std::numeric_limits<double>::max();
} else {
const double rnd_number = random->rollUniform(0., 1.);
if (rnd_number <= 0) {
return std::numeric_limits<double>::max();
} else {
return 1. / total_macroscopic_cross_section_m * log(1. / rnd_number);
}
}
}
interaction::InteractionOutput Simulation::interact(
particle::Particle& particle,
RandomNumbers* random,
std::vector<double>& macroscopic_cross_sections_m) {
const double total_macroscopic_cross_section_m =
std::accumulate(macroscopic_cross_sections_m.begin(),
macroscopic_cross_sections_m.end(), 0.0);
if (total_macroscopic_cross_section_m <= 0.) {
// do nothing
SIM_INFO("total mcs <= 0");
return interaction::InteractionOutput();
} else {
std::discrete_distribution<int> interaction_decider(
macroscopic_cross_sections_m.begin(),
macroscopic_cross_sections_m.end());
const int interaction_index = interaction_decider(*(random->engine()));
return particle.specie()
->interactions()
.at(interaction_index)
->performInteraction(particle, random);
}
}
std::vector<particle::Particle> Simulation::determineInjectedParticles(
RandomNumbers* random, const double beta_particle_weight) {
return injector_->rollNewParticles(random->engine(), timer_->time(),
beta_particle_weight);
}
// weight_factor has to be such that particleNumber * weight_factor = weight
std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
RandomNumbers* random, const double weight_factor, const int current,
std::map<std::string, double>& particleNumbers) {
std::vector<particle::Particle> new_particles{};
if(!new_particles.empty()) {
ERROR("In drawing particles from the density:"
" the new particles vector is not empty at initialization");
}
const double injection_time = timer_->time() - timer_->getDeltaT();
for(auto& pair: tracked_species_) {
if (particleNumbers[pair.first] == 0) {
DEBUG_LEVEL_3("No particles in density of species: " + pair.second->name());
continue;
}
#if defined debug_level3
if (current == 0) {
std::stringstream out;
out << pair.second->name();
out << "particle number from density: ";
out << particleNumbers[pair.first];
DEBUG_LEVEL_3(out.str());
}
#endif
double weight = particleNumbers[pair.first]*weight_factor;
injector_->drawNewParticleFromDensityField(random->engine(),
pair.second, new_particles, magnetic_field_,
weight, injection_time);
}
return new_particles;
}
//maybe put that into the poisson solver
blitz::Array<double,3> Simulation::chargedensity() {
DEBUG_LEVEL_3("Initialize chargedensity Array");
//not great but the size and bounds of the density arrays are needed...
std::shared_ptr<species::TrackedSpecie> firstTracked =
tracked_species_.begin()->second;
DEBUG_LEVEL_3("shared pointer extracted, key: "
+ tracked_species_.begin()->first);
if(!firstTracked)
ERROR("Extracted pointer is null.");
blitz::Array<double,3> init = firstTracked->
dynamicDensityField()->densityArray();
blitz::Array<double, 3> chargeden(init.lbound(), init.extent());
chargeden = 0.;
DEBUG_LEVEL_3("Collect chargedensity");
for (auto& pair : tracked_species_) {
chargeden += pair.second->charge_C() * pair.second->dynamicDensityField()->
densityArray();
}
DEBUG_LEVEL_3("Maximum value in the chargedensity: " +
std::to_string(blitz::max(chargeden)));
return chargeden;
}