Particles don't reset interaction between timesteps,

added possibility to stride the injection of new
beta particles
This commit is contained in:
2025-08-20 14:54:03 +02:00
parent ddfa5672df
commit abab8810f3
7 changed files with 160 additions and 166 deletions
+6 -10
View File
@@ -60,13 +60,10 @@ void Injector::initInjectionTimeDistribution(double delta_t) {
std::vector<particle::Particle> Injector::rollNewParticles(
std::mt19937* engine, const double current_time,
const double beta_particle_weight) {
// pull drawing from the position distribution into the "multiplicity" loop?
// (would improve resolution stuff in space as well as just in velocity direction
// especially for slow particles, i.e. ions)
std::vector<particle::Particle> new_particles;
const double time_birth = current_time - injection_time_distribution_(*engine);
const double time_birth = injection_time_distribution_(*engine);
for (auto& injector_info : injector_infos_) {
@@ -76,12 +73,11 @@ std::vector<particle::Particle> Injector::rollNewParticles(
std::to_string(position.cylinderEntries()(2)));
#endif
// for (int i = 0; i < injector_info.multiplicity; i++) {
new_particles.push_back(
rollNewParticle(engine, position, injector_info.created_specie,
injector_info.creation_velocity_distribution,
time_birth, beta_particle_weight));
// }
new_particles.push_back(
rollNewParticle(engine, position, injector_info.created_specie,
injector_info.creation_velocity_distribution,
time_birth, beta_particle_weight));
}
return new_particles;
}
+2 -15
View File
@@ -19,7 +19,6 @@ BorisMover::BorisMover(double maximal_time_step_s)
"The maximal timestep for boris push must be positive.");
}
// TBD: include F_g (simply add to electric force)
void BorisMover::move(particle::Particle* particle,
double collision_time_s,
ElectricField* electric_field,
@@ -37,7 +36,7 @@ void BorisMover::move(particle::Particle* particle,
// can only life a time dt < min(distance/v, maximal_timestep), which might even be
// a lot larger than dt, which would increase the influence of the particle on the
// density)
double max_time_alive = particle->specie()->dynamicDensityField()->physicalTime() -
double max_time_alive = delta_timeresolution -//particle->specie()->dynamicDensityField()->physicalTime() -
particle->timeAlive();
double leftover_time = collision_time_s;
@@ -131,19 +130,6 @@ void BorisMover::move(particle::Particle* particle,
changed_energy_bin =
particle->specie()->dynamicDensityField()->changedEnergyBin(
old_kinetic_energy, particle->kineticEnergy_eV());
// #ifdef debug
// if(changed_energy_bin &&
// particle->specie()->type() == species::ImplementedSpecies::Tplus) {
// std::stringstream out;
// out << "Changed energy bin from: " << particle->specie()->dynamicDensityField()
// ->energyBinning()->bin(old_kinetic_energy);
// out << " (" << old_kinetic_energy << ") to: ";
// out << particle->specie()->dynamicDensityField()->energyBinning()
// ->bin(particle->kineticEnergy_eV());
// out << " (" << particle->kineticEnergy_eV() << ")\n";
// DEBUG(out.str());
// }
// #endif
left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle);
@@ -152,6 +138,7 @@ void BorisMover::move(particle::Particle* particle,
particle->specie()->terminator()->reachedMaxTimeAlive(particle);
leftover_time -= timestep;
particle->reduceTimeUntilCollision(timestep);
// if max_time_alive == 0 but the difference between the time alive and
// the endtime > 0 (think can happen due to numerical accuracy)
+50 -13
View File
@@ -21,19 +21,19 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
// requires the name of a species "spec_name" to be smaller than 16 characters
// this is not! checked here and will lead to undefined behaviour if this
// requirement is not fulfilled
SerializedParticle::SerializedParticle(double time_birth, double weight,
SerializedParticle::SerializedParticle(double weight,
blitz::TinyVector<double, 3> cartPos,
blitz::TinyVector<double, 3> cartVel,
std::string spec_name) :
time_birth_(time_birth), weight_(weight),
std::string spec_name,
int idx_nxt_interaction,
double time_until_collision) :
weight_(weight),
cartesian_position_(cartPos),
cartesian_velocity_(cartVel) {
cartesian_velocity_(cartVel),
idx_nxt_interaction_(idx_nxt_interaction),
time_until_interaction_(time_until_collision) {
std::copy(spec_name.begin(), spec_name.end(), specie_name_.data());
specie_name_[spec_name.length()] = '\0';
}
double SerializedParticle::timeBirth() {
return time_birth_;
specie_name_[spec_name.length()] = '\0';
}
double SerializedParticle::weight() {
@@ -52,6 +52,14 @@ std::string SerializedParticle::specieName() {
return std::string (specie_name_.data());
}
double SerializedParticle::timeUntilCollision() {
return time_until_interaction_;
}
int SerializedParticle::indexNextInteraction() {
return idx_nxt_interaction_;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
@@ -71,6 +79,21 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
last_id_++;
}
Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position,
const Vector& velocity,
const double weight)
: specie_(specie),
position_cart_(position),
position_cyl_(position),
velocity_(velocity, position),
id_(this->last_id_),
time_alive_s_(0.),
interaction_counter_(0),
weight_(weight) {
last_id_++;
}
Particle::Particle(particle::SerializedParticle sparticle, std::map<std::string,
std::shared_ptr<species::TrackedSpecie>>& tracked_species) :
specie_(tracked_species[sparticle.specieName()]),
@@ -78,9 +101,11 @@ Particle::Particle(particle::SerializedParticle sparticle, std::map<std::string,
position_cyl_(blitz::TinyVector<double, 3>(0,0,0)),
velocity_(sparticle.cartesianVelocity()),
id_(this->last_id_),
time_alive_s_(sparticle.timeBirth()),
time_alive_s_(0.),
interaction_counter_(0),
weight_(sparticle.weight()) {
weight_(sparticle.weight()),
index_next_interaction_(sparticle.indexNextInteraction()),
time_until_collision_(sparticle.timeUntilCollision()) {
last_id_++;
position_cyl_ = CylinderCoordinate(position_cart_);
}
@@ -174,10 +199,22 @@ bool Particle::wasDeposited() {
return deposited_;
}
void Particle::timeUntilCollision(const double time_until_collision) {
time_until_collision_ = time_until_collision;
}
double Particle::timeUntilCollision() const {
return time_until_collision_;
}
void Particle::reduceTimeUntilCollision(double delta) {
time_until_collision_ -= delta;
}
particle::SerializedParticle Particle::serialize() {
return particle::SerializedParticle(time_alive_s_, weight_,
return particle::SerializedParticle(weight_,
position_cart_.cartesianEntries(), velocity_.cartesianEntries(),
specie_->name());
specie_->name(), index_next_interaction_, time_until_collision_);
}
} // namespace particle
+72 -113
View File
@@ -38,8 +38,6 @@
#include "tools/simulation_time.h"
#include <fstream>
Simulation::Simulation(std::string parameter_filename)
: parameter_(parameter_filename) {
init(parameter_);
@@ -58,14 +56,6 @@ void Simulation::init(Parameter& parameter) {
DEBUG_LEVEL_0(out.str());
#endif
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::out);
// file << "#type(0:drawing,1:interaction)\tx\ty\tz\tvx\tvy\tvz\n";
// file.close();
// }
magnetic_field_ = generator::magneticField(parameter);
electric_field_ = generator::electricField(parameter);
gravity_field_ = generator::gravityField(parameter);
@@ -156,6 +146,20 @@ void Simulation::start() {
// stride wrt the number of beta decay events per CPU
const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
// determines the timesteps a certain process injects particles from
// beta decay
const int injection_stride =
parameter_.intValue(json_path({"Simulation", "InjectionStride"}), 1);
int check = MpiCommunication::mpiSize() - injection_stride;
ASSERT_NOTNEGATIVE(&check, "The injection stride has to be smaller or equal"
" to the number of processes!");
const int group = MpiCommunication::mpiRank() % injection_stride;
// determine the number of processes that inject at the same timestep
int group_size = MpiCommunication::mpiSize() / injection_stride;
group_size = group < (MpiCommunication::mpiSize() - group_size * injection_stride) ?
group_size + 1 : group_size;
// number of timesteps to be simulated
const int number_timesteps = parameter_.intValue(json_path({"Simulation",
@@ -174,7 +178,16 @@ void Simulation::start() {
// 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());
static_cast<double>(beta_decay_events*group_size);
#ifdef debug
std::stringstream out;
out << "Rank " << MpiCommunication::mpiRank() << ": is part of group ";
out << group << " with size " << group_size;
out << " (injection stride: " << injection_stride << ")";
out << "\n\tweight of beta particle: " << beta_particle_weight;
DEBUG_LEVEL_0(out.str());
#endif
// number of density events per timestep and CPU
const int particles_per_bin =
@@ -183,8 +196,11 @@ void Simulation::start() {
// calculate a 'stride' for the density events s.t. the same number of syncs
// would be performed
const int density_stride = std::ceil(particles_per_bin *
int density_stride = particles_per_bin;
if(beta_decay_events != 0) {
density_stride = std::ceil(particles_per_bin *
(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 =
@@ -202,6 +218,10 @@ void Simulation::start() {
const double delta_t = time_resolution_events*injector_->timePassed();
// timestep does not have to be the same after a restart, since
// the drawing from the density does only depend on the time in bin array
// (i.e. is independent of the timestep)
/*******************************************************************************
// 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)
@@ -213,6 +233,7 @@ void Simulation::start() {
"the loaded data)";
ERROR(out.str());
}
*******************************************************************************/
timer_->setDeltaT(delta_t);
injector_->initInjectionTimeDistribution(delta_t);
@@ -249,8 +270,13 @@ void Simulation::start() {
// process both density and beta events before a cpu synchronization
processDensityEvents(particles_per_bin, density_weight_factor);
// if(timesteps == 0)
if(group == (timestep % injection_stride)) {
#ifdef debug
DEBUG_LEVEL_0(std::to_string(MpiCommunication::mpiRank()) + ": injection at "
"timestep " + std::to_string(timestep));
#endif
processEvents(events_of_cycle, beta_particle_weight);
}
#ifdef debug_level1
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timestep));
@@ -291,46 +317,26 @@ void Simulation::start() {
SimulationTimer::eventStartPoint("Reset");
if(reset) {
#if defined(debug_level2)
DEBUG_LEVEL_2("Number of particles in active storage queue: "
+ std::to_string(storage_queue_[active_storage].size()));
DEBUG_LEVEL_2("Number of particles in inactive storage queue: "
+ std::to_string(storage_queue_[inactive_storage].size()));
#endif
SIM_INFO("Do resets and increase the timestep for timeresolution.");
// SIM_INFO("Number of particles in storage queue: " + std::to_string(storage_queue_[active_storage].size()));
// SIM_INFO("Number of particles in storage queue: " + std::to_string(storage_queue_[inactive_storage].size()));
active_storage = (active_storage + 1) % 2;
inactive_storage = (inactive_storage + 1) % 2;
#ifdef debug
std::stringstream out;
out << "Ions (T+) lost at wall (physical value): " << phyLossAtWallIon;
phyLossAtWallIon = 0.;
double total_tp = 0;
double total_tp_sync = 0.;
#endif
for(auto& pair : tracked_species_) {
#ifdef debug
if(pair.second->type() == species::ImplementedSpecies::Tplus) {
total_tp = blitz::sum(pair.second->dynamicDensityField()->timeInBinArray());
total_tp_sync = blitz::sum(
pair.second->densityForDrawing()->timeInBinArray());
}
#endif
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();
// // the density from which new particles are drawn is only updated after a timestep
// pair.second->positionDistributionFromDensity()->setMaximumDensity();
}
#ifdef debug
out << "\n\ttotal number in tp: " << total_tp;
out << "\n\tdiff to expected: " << (timestep+1)*0.02 - total_tp;
out << "\n\ttotal number created: " << createdDensity;
out << "\n\tdiff to expected: " << (timestep)*0.02/MpiCommunication::mpiSize()
- createdDensity;
out << "\n\ttotal number in density drawing field: " << total_tp_sync;
out << "\n\tdiff to in density: " << total_tp_sync - total_tp;
DEBUG(out.str());
createdDensity = 0;
#endif
leftover_events_time_resolution = beta_decay_events;
leftover_density_events = particles_per_bin;
@@ -368,19 +374,6 @@ void Simulation::processEvents(int events, const double beta_particle_weight) {
SimulationTimer::eventStartPoint(std::string("ParticleInjection"));
new_particles = determineInjectedParticles(random_.get(),
beta_particle_weight);
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// for(auto part: new_particles) {
// auto pos = part.cartesianPosition().cartesianEntries();
// auto vel = part.velocity().cartesianEntries();
// file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// }
// file.close();
// }
// 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
@@ -427,8 +420,6 @@ void Simulation::processDensityEvents(int particles_per_bin, const double weight
int current_event = 0;
// set to true if all grids of all species have been visited
bool all_bins_done = false;
// SIM_INFO("Number of particles in storage queue: " + std::to_string(storage_queue_[active_storage].size()));
// SIM_INFO("Number of particles in storage queue: " + std::to_string(storage_queue_[inactive_storage].size()));
// calculate the number of particles currently contained within the densities
// of the different tracked species before injection in order to avoid
@@ -457,20 +448,6 @@ void Simulation::processDensityEvents(int particles_per_bin, const double weight
all_bins_done);
SimulationTimer::eventStopPoint(std::string("DensityInjection"));
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// for(auto part: new_particles) {
// auto pos = part.cartesianPosition().cartesianEntries();
// auto vel = part.velocity().cartesianEntries();
// file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// }
// file.close();
// }
#if defined debug_level3
for(auto& particle : new_particles) {
std::stringstream output_ss;
@@ -520,7 +497,6 @@ void Simulation::processDensityEvents(int particles_per_bin, const double weight
void Simulation::processUntilTermination(
particle::Particle& particle) {
// SIM_INFO("size of a particle: " + std::to_string(sizeof(particle)));
#ifdef debug_level3
DEBUG_LEVEL_3("Process particle until termination");
DEBUG_LEVEL_3("Weight of the particle: " + std::to_string(particle.weight()));
@@ -529,17 +505,25 @@ void Simulation::processUntilTermination(
auto old_position = particle.cylinderPosition();
double old_energy = particle.kineticEnergy_eV();
std::vector<double> macroscopic_cross_sections_m;
if(!particle.isNextInteractionValid()) {
DEBUG_LEVEL_1("Calculate time until collision");
SimulationTimer::eventStartPoint(std::string("MFP calculation"));
const double collision_time = collisionTime(particle, random_.get());
SimulationTimer::eventStopPoint(std::string("MFP calculation"));
}
SimulationTimer::eventStartPoint(std::string("MFP calculation"));
// const double mfp_m = meanFreePath(particle, random_.get(),
// macroscopic_cross_sections_m);
const double collision_time = collisionTime(particle, random_.get());
SimulationTimer::eventStopPoint(std::string("MFP calculation"));
#ifdef debug
std::stringstream out_;
out_ << "Time until collision: " << particle.timeUntilCollision();
DEBUG_LEVEL_1(out_.str());
#endif
SimulationTimer::eventStartPoint(std::string("Mover"));
particle.specie()->mover()->move(&particle, collision_time, electric_field_.get(),
magnetic_field_.get(), gravity_field_.get());
particle.specie()->mover()->move(&particle,
particle.timeUntilCollision(),
electric_field_.get(),
magnetic_field_.get(),
gravity_field_.get());
SimulationTimer::eventStopPoint(std::string("Mover"));
bool was_reflected = false;
@@ -558,6 +542,7 @@ void Simulation::processUntilTermination(
&particle) &&
!particle.specie()->terminator()->leftSimulationDomain(
&particle)) {
// particle.invalidateNextInteraction();
#ifdef debug_level3
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name() +
". Reached timeresolution.");
@@ -599,9 +584,6 @@ void Simulation::processUntilTermination(
PhysicalDeletionType::wall);
}
#ifdef debug
if(particle.specie()->type() == species::ImplementedSpecies::Tplus) {
phyLossAtWallIon += particle.weight();
}
if(particle.wasDeposited()) {
std::stringstream out;
out << "particle " << particle.specie()->name();
@@ -634,17 +616,6 @@ void Simulation::processUntilTermination(
SimulationTimer::eventStartPoint(std::string("Interaction"));
interaction::InteractionOutput output = interact(particle, random_.get());//,
// macroscopic_cross_sections_m);
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// auto pos = particle.cartesianPosition().cartesianEntries();
// auto vel = particle.velocity().cartesianEntries();
// file << 1 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// file.close();
// }
SimulationTimer::eventStopPoint(std::string("Interaction"));
// particle has reached time resolution, but was not deposited due to
@@ -663,8 +634,7 @@ void Simulation::processUntilTermination(
// }
// remove?
// particle.increaseInteractionCounter();
particle.increaseInteractionCounter();
for (auto& new_particle : output.newParticles()) {
queue_.push_back(new_particle);
@@ -691,6 +661,8 @@ void Simulation::processUntilTermination(
break;
}
}
particle.invalidateNextInteraction();
}
}
@@ -730,6 +702,7 @@ double Simulation::collisionTime(particle::Particle& particle, RandomNumbers* ra
auto min_iterator = std::min_element(collision_times.begin(), collision_times.end());
particle.indexNextInteration((min_iterator - collision_times.begin()));
particle.timeUntilCollision(*min_iterator);
#ifdef debug_level3
std::stringstream out;
@@ -812,10 +785,10 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
} else {
all_bins_done = false;
}
// take the first particle from the storage queue and extract it
// take the last particle from the storage queue and extract it
particle::SerializedParticle new_sparticle =
*(storage_queue_[active_storage].begin());
storage_queue_[active_storage].erase(storage_queue_[active_storage].begin());
storage_queue_[active_storage].back();
storage_queue_[active_storage].pop_back();
particle::Particle new_particle(new_sparticle, tracked_species_);
// "draw" the actual particle
new_particles.push_back(new_particle);
@@ -846,20 +819,6 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
injector_->drawNewParticleFromDensityField(random->engine(),
pair.second, new_particles, magnetic_field_,
weight_factor, injection_time);
#ifdef debug
if(!new_particles.empty()) {
if(new_particles.back().specie()->type() == species::ImplementedSpecies::Tplus
&& pair.second->type() == species::ImplementedSpecies::Tplus) {
// if(createdDensity + new_particles.back().weight() == createdDensity){
// std::stringstream out;
// out << "catastrophic cancellation!\ncreated density: " << createdDensity;
// out << "\n\tweight: " << new_particles.back().weight();
// DEBUG(out.str());
// }
createdDensity += new_particles.back().weight();
}
}
#endif
}
// if species is not done tmp_done && ... = false
+1 -1
View File
@@ -33,7 +33,7 @@ bool Terminator::reachedMaxInteractions(
}
bool Terminator::reachedMaxTimeAlive(const particle::Particle* particle) const {
return particle->timeAlive() >= particle->specie()->dynamicDensityField()
->physicalTime();
->timeResolution();
}
bool Terminator::leftSimulationDomain(