From 4a11245994ccd715b9620395ad926ca954b9ad61 Mon Sep 17 00:00:00 2001 From: csendlinger Date: Tue, 7 Oct 2025 13:15:15 +0200 Subject: [PATCH] Injection stride on a per injected species basis --- include/simulation/injector.h | 17 +++- include/simulation/simulation.h | 10 +- src/generators/injector_generator.cpp | 13 +++ src/simulation/injector.cpp | 74 ++++++++++---- src/simulation/simulation.cpp | 136 +++++++------------------- 5 files changed, 116 insertions(+), 134 deletions(-) diff --git a/include/simulation/injector.h b/include/simulation/injector.h index 91ee5be..cb4246b 100755 --- a/include/simulation/injector.h +++ b/include/simulation/injector.h @@ -28,7 +28,9 @@ struct InjectorInfo { public: std::shared_ptr created_specie; std::shared_ptr creation_velocity_distribution; - // int multiplicity; + double weight = 0; + int injection_group; + int injection_stride; }; class Injector { @@ -39,11 +41,16 @@ class Injector { std::shared_ptr mother_drift_velocity); std::vector rollNewParticles(std::mt19937* engine, - const double current_time, - const double beta_particle_weight); + const int timestep); -// draw new particles from the DynamicDensityField of the provided specie -// the new particles are then appened to the vector queue + // physical_number: physical number of particles that are injected in one + // timestep + // numerical_number: number of numerical beta particles to be injected on + // a single process + void setWeights(const double physical_number, const int numerical_number); + +// draw new particles from the DynamicDensityField of the provided specie, +// the new particles are then appened to the vector 'queue' // the magnetic field is necessary for the determination of the direction of the // injected particles // the weight_factor scales the time a particle contributes to a certain bin diff --git a/include/simulation/simulation.h b/include/simulation/simulation.h index 4239c5c..aafdb6b 100755 --- a/include/simulation/simulation.h +++ b/include/simulation/simulation.h @@ -34,16 +34,12 @@ class Simulation { void init(Parameter& parameter); void start(); void finalize(); - // cpu_syncs only included for debug purposes, e.g. only drawing decay particles - // at the 0th timestep - void processEvents(int events, const double beta_particle_weight); + void processEvents(int events); void processDensityEvents(int particles_per_bin, const double weight_factor); void processUntilTermination(particle::Particle& particle); private: - std::vector determineInjectedParticles(RandomNumbers* random, - const double beta_particle_weight); std::vector determineInjectedDensityParticles( RandomNumbers* random, const double weight_factor, @@ -51,10 +47,6 @@ class Simulation { std::map& particleNumbers, bool& all_bins_done); - // double meanFreePath(particle::Particle& particle, RandomNumbers* random, - // std::vector& macroscopic_cross_sections_m); - - // draw the individual collision times of the possible interactions and return the // minimum of them. Also sets the "nextInteractionIndex" in the particle to the // interaction of the chosen time. diff --git a/src/generators/injector_generator.cpp b/src/generators/injector_generator.cpp index 3c0bb80..30c24e3 100755 --- a/src/generators/injector_generator.cpp +++ b/src/generators/injector_generator.cpp @@ -4,6 +4,7 @@ #include "generators/velocity_distribution_generator.h" #include "simulation/event_position_distribution.h" #include "simulation/velocity_distribution.h" +#include "simulation/mpi_communication.h" namespace generator { @@ -39,6 +40,18 @@ std::shared_ptr buildInjector( // info.multiplicity = json_int(json_object_by_path(value, {"Multiplicity"}), 1); // ASSERT_POSITIVE(&info.multiplicity, "The multiplicity has to be positive. " + // specie_name + " multiplicity: " + std::to_string(info.multiplicity)); + int injection_stride = json_int(json_object_by_path(value, {"InjectionStride"}), 1); + ASSERT_POSITIVE(&injection_stride, "The injection stride for " + specie_name + + " is not positive! (" + std::to_string(injection_stride) + ")"); + if(injection_stride > MpiCommunication::mpiSize()) { + ERROR("Injection stride for " + specie_name + ": " + + std::to_string(injection_stride) + " is larger than the number" + " of processes (" + std::to_string(MpiCommunication::mpiSize()) + ")"); + } + + info.injection_stride = injection_stride; + info.injection_group = MpiCommunication::mpi_rank % injection_stride; + injector_infos.push_back(info); } diff --git a/src/simulation/injector.cpp b/src/simulation/injector.cpp index 89647c8..a058818 100755 --- a/src/simulation/injector.cpp +++ b/src/simulation/injector.cpp @@ -58,30 +58,61 @@ void Injector::initInjectionTimeDistribution(double delta_t) { } std::vector Injector::rollNewParticles( - std::mt19937* engine, const double current_time, - const double beta_particle_weight) { + std::mt19937* engine, const int timestep) { std::vector new_particles; const double time_birth = injection_time_distribution_(*engine); for (auto& injector_info : injector_infos_) { - - CylinderCoordinate position = position_distribution_->rollPosition(engine); + if((timestep % injector_info.injection_stride) == injector_info.injection_group) { + CylinderCoordinate position = position_distribution_->rollPosition(engine); #ifdef debug_level3 - DEBUG_LEVEL_3("Injected z position: " + - std::to_string(position.cylinderEntries()(2))); + DEBUG_LEVEL_3("Injected z position: " + + std::to_string(position.cylinderEntries()(2))); #endif - - new_particles.push_back( - rollNewParticle(engine, position, injector_info.created_specie, - injector_info.creation_velocity_distribution, - time_birth, beta_particle_weight)); - +#ifdef debug + DEBUG_LEVEL_0(std::to_string(MpiCommunication::mpi_rank) + ": injection " + + injector_info.created_specie->name() + " at " + "timestep " + std::to_string(timestep)); +#endif + new_particles.push_back( + rollNewParticle(engine, position, injector_info.created_specie, + injector_info.creation_velocity_distribution, + time_birth, injector_info.weight)); + } } return new_particles; } +void Injector::setWeights(const double physical_number, const int numerical_number) { +#ifdef debug + std::stringstream out; + out << "Weights:\n"; +#endif + int groupsize; + + for(auto& injector_info : injector_infos_) { + groupsize = MpiCommunication::mpi_size / injector_info.injection_stride; + if((MpiCommunication::mpi_size - groupsize * injector_info.injection_stride) + > injector_info.injection_group) { + groupsize += 1; + } + injector_info.weight = physical_number / static_cast(numerical_number * + groupsize); +#ifdef debug + out << "\t" << injector_info.created_specie->name(); + out << ": " << injector_info.weight; + out << " (group: " << injector_info.injection_group; + out << ", size: " << groupsize; + out << ")\n"; +#endif + } +#ifdef debug + DEBUG(out.str()); +#endif +} + void Injector::drawNewParticleFromDensityField(std::mt19937* engine, std::shared_ptr specie, std::vector& queue, @@ -92,6 +123,11 @@ void Injector::drawNewParticleFromDensityField(std::mt19937* engine, const double num_part_in_bin = specie->densityForDrawing()->particleNumber(index); if(num_part_in_bin == 0) { +#if defined(debug_level2) || defined(debug_level3) + std::stringstream out; + out << "index: "<< index <<" has no particles"; + // DEBUG_LEVEL_2(out.str()); +#endif return; } @@ -99,12 +135,6 @@ void Injector::drawNewParticleFromDensityField(std::mt19937* engine, CylinderCoordinate position = specie->positionDistributionFromDensity()->drawPosition(engine, index(0), index(1), index(2)); -#ifdef debug_level3 - DEBUG_LEVEL_3("Injected z position: " + - std::to_string(position.cylinderEntries()(2))); - DEBUG_LEVEL_3("Injected r position: " + - std::to_string(position.cylinderEntries()(0))); -#endif // draw the velocity CartesianVector velocity(blitz::TinyVector(0,0,0)); @@ -119,13 +149,15 @@ void Injector::drawNewParticleFromDensityField(std::mt19937* engine, drawVelocity(index, engine, position, magnetic_field); } -#ifdef debug_level2 +#if defined(debug_level2) || defined(debug_level3) std::stringstream out; - out << "drawn index: " << index; + out << specie->name() << ":\n"; + out << "\ndrawn index: " << index; out << "\nnumber of particles (" << specie->name() << ") at index: " << num_part_in_bin; out << "\ndrawn position: " << position.cylinderEntries(); out << "\ndrawn velocity: " << velocity.cartesianEntries(); - DEBUG_LEVEL_2(out.str()); + if(num_part_in_bin > 0) + DEBUG_LEVEL_2(out.str()); #endif particle::Particle drawn_particle(specie, position, diff --git a/src/simulation/simulation.cpp b/src/simulation/simulation.cpp index b973be1..13f5e40 100755 --- a/src/simulation/simulation.cpp +++ b/src/simulation/simulation.cpp @@ -146,27 +146,13 @@ 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::mpi_size - injection_stride; - ASSERT_NOTNEGATIVE(&check, "The injection stride has to be smaller or equal" - " to the number of processes!"); - - const int group = MpiCommunication::mpi_rank % injection_stride; - // determine the number of processes that inject at the same timestep - int group_size = MpiCommunication::mpi_size / injection_stride; - group_size = group < (MpiCommunication::mpi_size - group_size * injection_stride) ? - group_size + 1 : group_size; // 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 +// dt = time_resolution_events/Activity const double time_resolution_events = parameter_.doubleValue(json_path({"Simulation", "TimeResolutionEvents"}), MpiCommunication::mpi_size); @@ -176,18 +162,7 @@ void Simulation::start() { 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(beta_decay_events*group_size); - -#ifdef debug - std::stringstream out; - out << "Rank " << MpiCommunication::mpi_rank << ": 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 + injector_->setWeights(time_resolution_events, beta_decay_events); // number of density events per timestep and CPU const int particles_per_bin = @@ -218,23 +193,6 @@ 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) - 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); @@ -244,7 +202,7 @@ void Simulation::start() { timer_->increaseTimestep(delta_t); while (timestep < number_timesteps) { -#if defined debug_level3 +#if defined(debug_level3) std::stringstream out; out << "Timeinterval: " << timer_->time() << "s."; DEBUG_LEVEL_3(out.str()); @@ -262,23 +220,20 @@ void Simulation::start() { std::to_string(density_events_of_cycle)); #endif - SIM_INFO("Processing timestep: " + std::to_string(timestep)); + if(timestep%(std::max(number_timesteps/100, 1)) == 0) + SIM_INFO("Processing timestep: " + std::to_string(timestep)); +#ifdef debug 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)); +#endif // process both density and beta events before a cpu synchronization processDensityEvents(particles_per_bin, density_weight_factor); - if(group == ((timestep + injectionGroupOffset) % injection_stride)) { -#ifdef debug - DEBUG_LEVEL_0(std::to_string(MpiCommunication::mpi_rank) + ": injection at " - "timestep " + std::to_string(timestep)); -#endif - processEvents(events_of_cycle, beta_particle_weight); - } + processEvents(events_of_cycle); -#ifdef debug_level1 +#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3) DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timestep)); DEBUG_LEVEL_1("Leftover events this timestep: " + std::to_string(leftover_events_time_resolution)); @@ -289,7 +244,9 @@ void Simulation::start() { reset = !(leftover_events_time_resolution > 0); +#ifdef debug SIM_INFO("Cpu sync."); +#endif 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 @@ -301,30 +258,36 @@ void Simulation::start() { // can probably be moved into the reset section and therefore // the parameter 'reset' could probably be removed +#ifdef debug SIM_INFO("Poisson step."); +#endif 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")); +#ifdef debug SIM_INFO("Perform output."); +#endif SimulationTimer::eventStartPoint(std::string("Output")); // only write inactive queue, obvi not correct if written between timesteps output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get(), random_->engine(), storage_queue_[inactive_storage], - (timestep + injectionGroupOffset + 1) % injection_stride); - SimulationTimer::eventStopPoint(std::string("Output")); + timestep + 1 + injectionGroupOffset); + SimulationTimer::eventStopPoint(std::string("Output")); SimulationTimer::eventStartPoint("Reset"); if(reset) { #if defined(debug_level2) || defined(debug_level3) - DEBUG_LEVEL_2("Number of particles in active storage queue: " + DEBUG("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: " + DEBUG("Number of particles in inactive storage queue: " + std::to_string(storage_queue_[inactive_storage].size())); #endif +#ifdef debug SIM_INFO("Do resets and increase the timestep for timeresolution."); +#endif active_storage = (active_storage + 1) % 2; inactive_storage = (inactive_storage + 1) % 2; @@ -334,9 +297,6 @@ void Simulation::start() { 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; @@ -353,7 +313,7 @@ int particleNumberFromQueue(int queue_length, RandomNumbers* random) { return random->rollUniform(0, queue_length); } -void Simulation::processEvents(int events, const double beta_particle_weight) { +void Simulation::processEvents(int events) { #ifdef debug DEBUG_LEVEL_0("Processing events."); #endif @@ -373,12 +333,11 @@ void Simulation::processEvents(int events, const double beta_particle_weight) { DEBUG_LEVEL_2("Inject particles to queue."); #endif SimulationTimer::eventStartPoint(std::string("ParticleInjection")); - new_particles = determineInjectedParticles(random_.get(), - beta_particle_weight); + new_particles = injector_->rollNewParticles(random_->engine(), timestep + injectionGroupOffset); // 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 +#if defined(debug_level3) for(auto& particle : new_particles) { std::stringstream output_ss; output_ss << particle.specie()->name() << " with velocity (cart): "; @@ -393,7 +352,14 @@ void Simulation::processEvents(int events, const double beta_particle_weight) { #ifdef debug_level2 DEBUG_LEVEL_2("Injected particles to queue."); #endif - + // if no new particles are injected trying to draw more particles will + // again yield nothing. And since this block is only executed if + // the "main"-queue is empty, this means that there is nothing to be + // done in terms of new beta particles in this timestep + if(new_particles.empty()) { + DEBUG("No new beta particles."); + return; + } queue_.insert(queue_.end(), new_particles.begin(), new_particles.end()); } @@ -568,12 +534,12 @@ void Simulation::processUntilTermination(particle::Particle& particle) { break; } else if (particle.specie()->terminator()->leftSimulationDomain( &particle)) { -#if defined debug_level3 - DEBUG_LEVEL_1("Terminate particle " + particle.specie()->name() +#if defined(debug) + DEBUG("Terminate particle " + particle.specie()->name() + ". Left simulation domain."); - std::stringstream output_ss; - output_ss << "Position (cyl): " << particle.cylinderPosition().cylinderEntries(); - output_ss << " (cart): " << particle.cartesianPosition().cartesianEntries(); + // std::stringstream output_ss; + // output_ss << "Position (cyl): " << particle.cylinderPosition().cylinderEntries(); + // output_ss << " (cart): " << particle.cartesianPosition().cartesianEntries(); // ERROR(output_ss.str()); #endif if (particle.specie()->deletionLogger()) { @@ -665,28 +631,6 @@ void Simulation::processUntilTermination(particle::Particle& particle) { } } -// double Simulation::meanFreePath(particle::Particle& particle, -// RandomNumbers* random, -// std::vector& 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::max(); -// } else { -// const double rnd_number = random->rollUniform(0., 1.); -// if (rnd_number <= 0) { -// return std::numeric_limits::max(); -// } else { -// return 1. / total_macroscopic_cross_section_m * log(1. / rnd_number); -// } -// } -// } - // maybe rewrite to s.t. the min_element part can be removed (together with the // algorithm lib) void Simulation::collisionTime(particle::Particle& particle, RandomNumbers* random) { @@ -748,12 +692,6 @@ interaction::InteractionOutput Simulation::interact( } } -std::vector 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 Simulation::determineInjectedDensityParticles( RandomNumbers* random, const double weight_factor, const int current,