From 753cbe31f553ad72e5be6b83aca130d87c19329f Mon Sep 17 00:00:00 2001 From: csendlinger Date: Wed, 15 Oct 2025 14:46:27 +0200 Subject: [PATCH] Corrections to drawing the velocity of a tracked species (dynamic density field of previous timestep); some optimization changes --- include/simulation/density_field.h | 4 +- include/simulation/velocity_distribution.h | 7 +- src/IO/restart.cpp | 1 + src/IO/simulation_output.cpp | 2 + src/interactions/recombination.cpp | 43 ++++--- src/simulation/cpu_synchronizer.cpp | 6 +- src/simulation/density_field.cpp | 53 ++++---- src/simulation/species.cpp | 5 +- src/simulation/velocity_distribution.cpp | 135 ++++++++++++++++++--- 9 files changed, 188 insertions(+), 68 deletions(-) diff --git a/include/simulation/density_field.h b/include/simulation/density_field.h index acfbca1..712912f 100755 --- a/include/simulation/density_field.h +++ b/include/simulation/density_field.h @@ -75,10 +75,10 @@ class DynamicDensityField : public DensityField { void restartTimer(double time, double delta_t); void restartTimeInBin(blitz::Array time_in_bin); - private: - void recalculateDensityArray(); + private: + // use ordering r, phi, z, pitch_angle, E // time in bin now contains the physical particle number per bin // (not renamed, since that would require many, many changes due to diff --git a/include/simulation/velocity_distribution.h b/include/simulation/velocity_distribution.h index 2f9fe40..026dbc3 100755 --- a/include/simulation/velocity_distribution.h +++ b/include/simulation/velocity_distribution.h @@ -52,8 +52,7 @@ class VelocityDistributionFromDensityField : public VelocityDistribution { // use the given magnetic field at the provided position to determine the // direction of velocity from the pitch angle // the direction of the perpendicular part of the velocity vector is drawn isotropically - CartesianVector rollVelocity( - const Coordinate& position, std::mt19937* engine, + CartesianVector rollVelocity(const Coordinate& position, std::mt19937* engine, std::shared_ptr magnetic_field); private: @@ -62,8 +61,8 @@ class VelocityDistributionFromDensityField : public VelocityDistribution { std::shared_ptr density_field_; - blitz::Array energy_values; - blitz::Array mu_values; + // blitz::Array energy_values; + // blitz::Array mu_values; std::vector energyBinBorders_; std::vector pitchAngleBinBorders_; diff --git a/src/IO/restart.cpp b/src/IO/restart.cpp index 675c399..cad6969 100644 --- a/src/IO/restart.cpp +++ b/src/IO/restart.cpp @@ -141,6 +141,7 @@ void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string #endif blitz::Array time_in_bin = reader_.readD5Double(path_to_data); field->restartTimeInBin(time_in_bin); + field->recalculateDensityArray(); } // // restart deleted particles diff --git a/src/IO/simulation_output.cpp b/src/IO/simulation_output.cpp index f27a6e3..cd498f0 100755 --- a/src/IO/simulation_output.cpp +++ b/src/IO/simulation_output.cpp @@ -315,6 +315,8 @@ void SimulationOutput::writeSpectrum(DynamicDensityField* density_field, void SimulationOutput::writeDensity(DynamicDensityField* density_field, std::string path) { + // precaution, shouldn't be necessary due to calculation after cpu sync + density_field->recalculateDensityArray(); writer.write(density_field->densityArray(), path + "/Density"); } diff --git a/src/interactions/recombination.cpp b/src/interactions/recombination.cpp index 10cf075..de6eadd 100755 --- a/src/interactions/recombination.cpp +++ b/src/interactions/recombination.cpp @@ -169,20 +169,26 @@ double Recombination::macroscopicCrossSection(const Coordinate& position, double Recombination::drawCollisionTime(particle::Particle& particle, RandomNumbers* generator) { CartesianVector particle_velocity = particle.velocity(); - + // const double density = target_->densityField()->density(particle.cylinderPosition()); + // Use the density for drawing field, since it contains the density of the earlier + // timestep + const double density = recombination_target_->densityForDrawing() + ->density(particle.cylinderPosition()); + + // recombination_target_->densityForDrawing()->recalculateDensityArray(); + // if(density != recombination_target_->densityForDrawing() + // ->density(particle.cylinderPosition())) { + // ERROR("density changes after recalculation of density array!"); + // } + // density effectively 0 + if(density <= SimConstants::compare_epsilon) { + return std::numeric_limits::max(); + } + // Assumes that B || z, which is obviously not necessarily the case !!! target_velocity_ = recombination_target_->velocityDistributionFromDensityField() ->rollVelocity(particle.cylinderPosition(), generator->engine()); -// // if no drift velocity is present, then assume target at rest otherwise -// // use the drift velocity - if(target_->driftVelocity()) { - // auto tmp = target_->driftVelocity()->driftVelocity(particle.position()); - target_velocity_.add(target_->driftVelocity()->driftVelocity( - particle.cartesianPosition(), particle.cylinderPosition()), - particle.cartesianPosition()); - } - // for testing purposes // target_velocity_ = CartesianVector(blitz::TinyVector(0.,0.,0.)); @@ -212,11 +218,18 @@ double Recombination::drawCollisionTime(particle::Particle& particle, const double crosssection = microscopicCrossSection(energy_eV, particle.cylinderPosition()); - // const double density = target_->densityField()->density(particle.cylinderPosition()); - // Use the density for drawing field, since it contains the density of the earlier - // timestep - const double density = recombination_target_->densityForDrawing() - ->density(particle.cylinderPosition()); + +#if defined(debug) + if(density > 0 && std::isnan(crosssection)) { + std::stringstream msg; + msg << particle.specie()->name() << particle.cartesianPosition().cartesianEntries(); + msg << " " << recombination_target_->densityForDrawing()->positionBinning()->bin(particle.cylinderPosition().cylinderEntries()); + msg << ": Recombination: density is not nan but the cross section is "; + msg << density << ", " << crosssection; + msg << recombination_target_->densityForDrawing()->sliceSpectrumArray(particle.cylinderPosition()); + ERROR(msg.str()); + } +#endif const double random_number = generator->rollUniform(0.,1.); if (random_number == 0) { diff --git a/src/simulation/cpu_synchronizer.cpp b/src/simulation/cpu_synchronizer.cpp index 2d0f4e0..d9337b0 100755 --- a/src/simulation/cpu_synchronizer.cpp +++ b/src/simulation/cpu_synchronizer.cpp @@ -91,11 +91,11 @@ void CpuSynchronizer::synchronize(DynamicDensityField* field, sumToAll(field->time_in_bin_s_, field->sync_time_in_bin_s_); field->time_in_bin_s_ = field->sync_time_in_bin_s_; - // sumToAll(field->deleted_particles_, field->sync_deleted_particles_); - // field->deleted_particles_ = field->sync_deleted_particles_; + // has to be moved somewhere else i think if (reset) { + field->recalculateDensityArray(); density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_; - // density_for_drawing->deleted_particles_ = field->deleted_particles_; + density_for_drawing->density_per_m3_ = field->density_per_m3_; } } } diff --git a/src/simulation/density_field.cpp b/src/simulation/density_field.cpp index 0e086a4..ff1aabf 100755 --- a/src/simulation/density_field.cpp +++ b/src/simulation/density_field.cpp @@ -109,6 +109,18 @@ double DynamicDensityField::density(const Coordinate& position) { const blitz::TinyVector position_bin = position_binning_.bin(position.cylinderEntries()); +#ifdef debug_level1 + blitz::Array check = density_per_m3_.copy(); + recalculateDensityArray(); + if(!blitz::all(check == density_per_m3_)) { + ERROR("Density changes after recalculateDensityArray!"); + } +#endif + + return blitz::sum(density_per_m3_(position_bin(0), position_bin(1), position_bin(2), + blitz::Range::all())); + +/*/ // const double t = timer_->getDeltaT(); const double time_in_bin = blitz::sum(time_in_bin_s_( position_bin(0), position_bin(1), position_bin(2), @@ -119,6 +131,7 @@ double DynamicDensityField::density(const Coordinate& position) { return (time_in_bin) / //- deleted_particles) / bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2)); +*/ } double DynamicDensityField::density(const Coordinate& position, @@ -190,25 +203,12 @@ void DynamicDensityField::logMovement(const Coordinate& position, pitch_angle_bin, energy_bin) += weight; } -// void DynamicDensityField::logDeletion(const Coordinate& position, -// double energy_eV, -// double pitch_angle) { - -// const blitz::TinyVector position_bin = -// position_binning_.bin(position.cylinderEntries()); -// const int energy_bin = energy_binning_.bin(energy_eV); -// const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle); - -// deleted_particles_(position_bin(0), position_bin(1), position_bin(2), pitch_angle_bin, -// energy_bin) += 1; -// return; -// } - blitz::Array DynamicDensityField::densityArray() { #ifdef debug_level3 DEBUG_LEVEL_3("recalc Density array"); #endif - recalculateDensityArray(); +// recalculated after a timestep reset (as of now hope that's enough and works correctly) + // recalculateDensityArray(); blitz::TinyVector lowerbound(density_per_m3_.lbound(0), density_per_m3_.lbound(1), @@ -269,8 +269,6 @@ void DynamicDensityField::recalculateDensityArray() { blitz::fourthIndex ipitch; blitz::fifthIndex iE; - // const double t = timer_->getDeltaT(); - // reduction only seems to work for the last dimension (iE) // -> first reorder (by exchanging iE and ipitch) and afterwards doing // the reduction over iE (which now contains the pitch dimension) @@ -278,29 +276,36 @@ void DynamicDensityField::recalculateDensityArray() { density_per_m3_ = blitz::sum((time_in_bin_s_(ir, iphi, iz, iE, ipitch)), iE) / bin_volume_m3_(ir, iphi, iz); -//deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) / // SimulationTimer::eventStopPoint("recalcDensityArray"); } -blitz::Array DynamicDensityField:: - sliceSpectrumArray(const Coordinate& position) const { +// in a specific bin the "density" across E is proportional to the +// particle number +blitz::Array DynamicDensityField::sliceSpectrumArray( + const Coordinate& position) const { blitz::TinyVector position_bin = position_binning_.bin(position.cylinderEntries()); + + // blitz::Array check = density_per_m3_.copy(); + // recalculateDensityArray(); + // if(!blitz::all(check == density_per_m3_)) { + // ERROR("splice specturm array: check failed."); + // } return density_per_m3_(position_bin(0), position_bin(1), position_bin(2), blitz::Range(energy_binning_.binIndexMin(), - energy_binning_.binIndexMax()-1)).copy(); + energy_binning_.binIndexMax()-1)); } -blitz::Array DynamicDensityField:: - sliceTimeInBinArray(const Coordinate& position, double energy_eV) const { +blitz::Array DynamicDensityField::sliceTimeInBinArray( + const Coordinate& position, double energy_eV) const { blitz::TinyVector position_bin = position_binning_.bin(position.cylinderEntries()); int energy_bin = energy_binning_.bin(energy_eV); return time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), blitz::Range(0, pitch_angle_binning_.binIndexMax()-1), - energy_bin).copy(); + energy_bin); } void DynamicDensityField::resetDynamicDensityField() { diff --git a/src/simulation/species.cpp b/src/simulation/species.cpp index f2e647f..b343458 100755 --- a/src/simulation/species.cpp +++ b/src/simulation/species.cpp @@ -59,7 +59,10 @@ TrackedSpecie::TrackedSpecie( density_for_drawing, mass_kg)) {} DensityField* TrackedSpecie::densityField() { - return density_field_.get(); + // return the density field storing the previous timestep, since + // that density is the only one that makes sense for the calculation + // of e.g. MFP for Tracked-Tracked interactions + return density_for_drawing_.get(); } VelocityDistribution* TrackedSpecie::velocityDistribution() { diff --git a/src/simulation/velocity_distribution.cpp b/src/simulation/velocity_distribution.cpp index 5342c14..9369487 100755 --- a/src/simulation/velocity_distribution.cpp +++ b/src/simulation/velocity_distribution.cpp @@ -30,6 +30,60 @@ CartesianVector VelocityDistributionFromFunction::rollVelocity( return fv_->rollVelocity(engine); } +double drawPiecewiseConstant(const std::vector& intervals, const blitz::Array& weights, + std::mt19937* engine) { + std::uniform_real_distribution<> dist(0.,1.); + // std::stringstream out; + // out << "intervals: [ "; + // out << "]\n"; + + // out << "\nweights: " << weights; + // out << "\ninterval sizes: " << interval_sizes; + double normalization = blitz::sum(weights); +#if defined(debug) + if(intervals.size() != weights.length(0) + 1) { + std::stringstream msg; + msg << "Interval size ( " << intervals.size() << " ) are not compatible "; + msg << "with the weight size ( " << weights.length(0) << " )"; + ERROR(msg.str()); + } +#endif + + // out << "\nnormalization: " << normalization; +// if there are not particles in the considered interval return NaN as an +// indicator for that + if(normalization == 0) { + // SIM_INFO(out.str()); + return NAN; + } + + double sum = 0; + int interval = -1; + double check = dist(*engine)*normalization; + + for(int i = weights.lbound(0); i <= weights.ubound(0); i++) { + sum += weights(i); + if(check < sum) { + interval = i-weights.lbound(0); + break; + } + } + + if(interval==-1) { + std::stringstream msg; + msg << "no interval found: " << weights << " [ "; + for(auto value : intervals) { + msg << value << " "; + } + msg << "]"; + ERROR(msg.str()); + } + + // SIM_INFO(out.str()); + + return (intervals[interval+1] - intervals[interval])*dist(*engine) + intervals[interval]; +} + VelocityDistributionFromDensityField::VelocityDistributionFromDensityField( std::shared_ptr density_field, double mass_kg): density_field_(density_field), @@ -39,6 +93,8 @@ VelocityDistributionFromDensityField::VelocityDistributionFromDensityField( mass_kg_(mass_kg) { // necessary to include the underflow bin in the energy domain energyBinBorders_.insert(energyBinBorders_.begin(), 0); + // energy_values.resize(density_field->energyBinning()->numBins() + 1); + // mu_values.resize(density_field->pitchAngleBinning()->numBins()); } // not important as of now since it's meant for drawing a velocity from the @@ -53,29 +109,72 @@ CartesianVector VelocityDistributionFromDensityField::driftVelocity_ms( CartesianVector VelocityDistributionFromDensityField::rollVelocity( const Coordinate& position, std::mt19937* engine) { - + // SIM_INFO("set energy values"); // draw energy from DynamicDensityField - blitz::Array energyValues = density_field_-> - sliceSpectrumArray(position); + // energy_values = density_field_->sliceSpectrumArray(position); + const blitz::Array energy_values = density_field_->sliceSpectrumArray(position); - std::piecewise_constant_distribution energy_dist( - energyBinBorders_.begin(), - energyBinBorders_.end(), - energyValues.begin()); + // std::piecewise_constant_distribution energy_dist( + // energyBinBorders_.begin(), + // energyBinBorders_.end(), + // energy_values.begin()); - double energy_eV = energy_dist(*engine); + // SIM_INFO("draw energy value"); + double energy_eV = drawPiecewiseConstant(energyBinBorders_, energy_values, engine);//energy_dist(*engine); // + + // if(std::isnan(energy_eV)) { + // std::stringstream msg; + // msg << "\nenergy is nan: " << position.cartesianEntries(); + // msg << energy_values; + // density_field_->recalculateDensityArray(); + // msg << "recalculated: " << density_field_->sliceSpectrumArray(position); + // msg << "density in bin: " << density_field_->density(position); + // msg << "\nbin: " << density_field_->positionBinning()->bin(position.cylinderEntries()); + // msg << "\n"; + // std::cerr << msg.str(); + // } // draw pitch angle from DynamicDensityField - blitz::Array pitchAngleValues = density_field_-> - sliceTimeInBinArray(position, energy_eV); + // SIM_INFO("set mu values"); - std::piecewise_constant_distribution pitchAngle_dist( - pitchAngleBinBorders_.begin(), - pitchAngleBinBorders_.end(), - pitchAngleValues.begin()); + const blitz::Array mu_values = density_field_->sliceTimeInBinArray(position, energy_eV); + + // std::cout << mu_values; + + // SIM_INFO("\nset mu dist"); + + // std::piecewise_constant_distribution pitchAngle_dist( + // pitchAngleBinBorders_.begin(), + // pitchAngleBinBorders_.end(), + // mu_values.begin()); + + // SIM_INFO("draw mu value"); + + double pitchAngle = drawPiecewiseConstant(pitchAngleBinBorders_, mu_values, engine);//pitchAngle_dist(*engine); // + // if(std::isnan(pitchAngle)) { + // std::stringstream msg; + // msg << "\npitchangle is nan: " << position.cartesianEntries(); + // msg << mu_values; + // density_field_->recalculateDensityArray(); + // msg << "recalculated: " << density_field_->sliceTimeInBinArray(position, energy_eV); + // msg << "density in bin: " << density_field_->density(position); + // msg << "\nbin: " << density_field_->positionBinning()->bin(position.cylinderEntries()); + // msg << "\nenergy value: " << energy_eV; + // msg << "\nenergy bin: " << density_field_->energyBinning()->bin(energy_eV); + // // msg << "\nenergy bin borders: [ "; + // // for(auto value : energyBinBorders_) { + // // msg << " " << value; + // // } + // // msg << "]"; + // std::cerr << msg.str(); + // } +#ifdef debug + if(!isnan(energy_eV) && isnan(pitchAngle)) { + ERROR("Energy is not nan, but pitchangle is."); + } +#endif - double pitchAngle = pitchAngle_dist(*engine); // construct the velocity @@ -85,12 +184,10 @@ CartesianVector VelocityDistributionFromDensityField::rollVelocity( const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_); -// vector perpendicular to e_z - blitz::TinyVector v_perp(1,0,0); - blitz::TinyVector v_direction = pitchAngle * zDirection + std::sqrt(1 - pitchAngle*pitchAngle) - * kinematic::rotateVector(v_perp, zDirection, theta); + * kinematic::rotateVector(blitz::TinyVector(1,0,0), + zDirection, theta); return CartesianVector(v_direction * vMagnitude); }