diff --git a/include/IO/restart.h b/include/IO/restart.h index 2257fa8..b29a378 100644 --- a/include/IO/restart.h +++ b/include/IO/restart.h @@ -31,8 +31,10 @@ class Restart { 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 +// only necessary for densityfield that is drawn from + void restartDrawingDensityField(DynamicDensityField* field, std::string path); +// only load in the potential and calc the electric field + void restartPoissonSolver(PoissonSolver* solver); void restartRandomNumbers(RandomNumbers* random); bool do_restart_; diff --git a/include/simulation/density_field.h b/include/simulation/density_field.h index c5d6a0a..e2d018c 100755 --- a/include/simulation/density_field.h +++ b/include/simulation/density_field.h @@ -46,9 +46,11 @@ class DynamicDensityField : public DensityField { double energy_eV, double pitch_angle); +// return the particle number stored in the density of this object double particleNumber(); - blitz::TinyVector draw(std::mt19937* engine); +// returns true if the old pitch angle and the new pitch angle are in different bins +// of the pitch angle binning bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const; blitz::Array densityArray(); @@ -57,6 +59,16 @@ class DynamicDensityField : public DensityField { blitz::Array deletedParticlesArray() const; blitz::Array binVolumeArray() const; +// return an array of the density values at the Coordinate position (only energy +// direction left); over and underflow bin are removed +// (might not be good, since then the underflow particles are lost...) + blitz::Array sliceSpectrumArray(const Coordinate& position) const; + +// return an array of the time in bin at the Coordinate position and the energy +// energy_eV (only pitch angle direction left); over and underflow bin are removed + blitz::Array sliceTimeInBinArray(const Coordinate& position, + double energy_eV) const; + const EnergyBinning* energyBinning() const; const CylinderBinning* positionBinning() const; const PitchAngleBinning* pitchAngleBinning() const; @@ -68,19 +80,15 @@ class DynamicDensityField : public DensityField { friend class CpuSynchronizer; - void setDensityDistribution(); - void restartTimer(double time, double delta_t); void restartTimeInBin(blitz::Array time_in_bin); void restartDeletedParticlesArray(blitz::Array deleted_particles); private: - // BinCoordinate densityBin(const CylinderCoordinate& position) const; void recalculateDensityArray(); - void initPositionDistributions(); - // use ordering r, phi, z, pitch_angle, E + // use ordering r, phi, z, pitch_angle, E blitz::Array time_in_bin_s_; blitz::Array deleted_particles_; @@ -92,13 +100,6 @@ class DynamicDensityField : public DensityField { const CylinderBinning position_binning_; const EnergyBinning energy_binning_; - - // random distributions for drawing from - std::uniform_real_distribution r_dist_; - std::uniform_real_distribution phi_dist_; - std::uniform_real_distribution z_dist_; - std::uniform_real_distribution density_dist_; - const PitchAngleBinning pitch_angle_binning_; std::shared_ptr timer_; diff --git a/include/simulation/event_position_distribution.h b/include/simulation/event_position_distribution.h index 608f489..78e469e 100755 --- a/include/simulation/event_position_distribution.h +++ b/include/simulation/event_position_distribution.h @@ -6,6 +6,7 @@ #include "simulation/coordinates.h" #include "simulation/scalar_field.h" +#include "simulation/density_field.h" struct Limit { Limit() : min(0), max(0){}; @@ -14,6 +15,9 @@ struct Limit { double max; }; +// Might be possible to generalize the distributions (i.e. create parent class +// and let the two that are defined now inherit from it) + class EventPositionDistribution { public: EventPositionDistribution(std::shared_ptr mother_density, @@ -33,4 +37,31 @@ class EventPositionDistribution { std::uniform_real_distribution density_values; }; +// Class to draw a position from the density provided by a pointer +// to a DynamicDensityField object +class PositionDistributionFromDensity { + public: + // Constructor taking a pointer to a DynamicDensityField object + PositionDistributionFromDensity(std::shared_ptr density); + +// draw a position from the density provided at construction using the rejection method + CylinderCoordinate drawPosition(std::mt19937* engine); +// sets the maximum density value needed for the rejection method +// should not be called frequently, since during each call the density field is +// recalculated from scratch by the DynamicDensityField object + void setMaximumDensity(); + + private: +// variable storing the maximum value of the density + double maximum_density_ = 1.; + + std::shared_ptr density_; + +// distributions for the spatial directions and for the density + std::uniform_real_distribution r_values; + std::uniform_real_distribution phi_values; + std::uniform_real_distribution z_values; + std::uniform_real_distribution density_values; +}; + #endif /* EVENT_POSITION_DISTRIBUTION_H */ diff --git a/include/simulation/injector.h b/include/simulation/injector.h index 437e1c2..2251da7 100755 --- a/include/simulation/injector.h +++ b/include/simulation/injector.h @@ -41,13 +41,14 @@ class Injector { std::vector rollNewParticles(std::mt19937* engine, const double current_time); - // void rollNewParticleFromDensityField(std::mt19937* engine, - // std::shared_ptr specie, - // std::vector& queue, - // const double weight, - // const double injection_time); - - void rollNewParticleFromDensityField(std::mt19937* engine, +// 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 scales the time a particle contributes to a certain bin +// and the injection time specifies the time the particle is injected (has to be +// between T, T+\DeltaT) + void drawNewParticleFromDensityField(std::mt19937* engine, std::shared_ptr specie, std::vector& queue, std::shared_ptr field, diff --git a/include/simulation/species.h b/include/simulation/species.h index 01111ae..a52b9c7 100755 --- a/include/simulation/species.h +++ b/include/simulation/species.h @@ -18,6 +18,8 @@ class DeletionLogger; class CurrentCollector; class VelocityDistribution; class DriftVelocity; +class PositionDistributionFromDensity; +class VelocityDistributionFromDensityField; namespace interaction { class Interaction; @@ -84,6 +86,11 @@ class TrackedSpecie : public Specie { std::vector> interactions(); void addInteraction(std::shared_ptr interaction); +// getter for the raw pointer to the positionDistributionFromDensity object + PositionDistributionFromDensity* positionDistributionFromDensity(); +// getter for the raw pointer to the VelocityDistributionFromDensityField object + VelocityDistributionFromDensityField* velocityDistributionFromDensityField(); + private: std::shared_ptr density_field_; std::shared_ptr velocity_distribution_; @@ -98,6 +105,10 @@ class TrackedSpecie : public Specie { std::vector> interactions_; std::shared_ptr density_for_drawing_; + std::shared_ptr + position_distribution_from_density_; + std::shared_ptr + velocity_distribution_from_density_; }; class BackgroundSpecie : public Specie { diff --git a/include/simulation/velocity_distribution.h b/include/simulation/velocity_distribution.h index 0144417..0b9efca 100755 --- a/include/simulation/velocity_distribution.h +++ b/include/simulation/velocity_distribution.h @@ -25,22 +25,50 @@ class VelocityDistributionFromFunction : public VelocityDistribution { std::shared_ptr fv_; }; -/* - -todo: implement this for direct interactions of simulated particles - -class DensityField; +// only applicable to TrackedSpecies (i.e. only for DynamicDensityFields) +// other density don't have any information about the velocity direction +class DynamicDensityField; +class MagneticField; +// Class to draw a velocity from the pitch angle resolved density class VelocityDistributionFromDensityField : public VelocityDistribution { - public: - VelocityDistributionFromDensityField( - std::shared_ptr density_field); - CartesianVector driftVelocity_ms(const CylinderVector& position); - CartesianVector rollVelocity_ms( - const CylinderVector& position, std::mt19937* engine); + public: +// Constructor: takes shared ptr to the DynamicDensityField object from which +// should be drawn and the mass of the species to which the density +// field belongs + VelocityDistributionFromDensityField( + std::shared_ptr density_field, double mass_kg); + +// stub: can be implemented to return the drift velocity of the particles +// at the CylinderVector position of the density field + CartesianVector driftVelocity_ms(const CylinderVector& position); + +// returns a velocity vector drawn from the energy and pitch angle distributions +// since no magnetic field is given use e_z as the direction wrt the definition +// of the pitch angle + CartesianVector rollVelocity(const Coordinate& position, std::mt19937* engine); + +// returns a velocity vector drawn from the energy and pitch angle distributions +// 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, + std::shared_ptr magnetic_field); private: - std::shared_ptr density_field_; + // mass of the species of which the density field is a part of + const double mass_kg_; + + std::shared_ptr density_field_; + + blitz::Array energy_values; + blitz::Array mu_values; + + std::vector energyBinBorders_; + std::vector pitchAngleBinBorders_; + + std::uniform_real_distribution theta_distribution_; }; -*/ + #endif /* VELOCITY_DISTRIBUTION_H */ diff --git a/src/IO/restart.cpp b/src/IO/restart.cpp index 8c1e1af..49ee7c5 100644 --- a/src/IO/restart.cpp +++ b/src/IO/restart.cpp @@ -9,6 +9,7 @@ #include "simulation/density_field.h" #include "poisson_solver/poisson_solver.h" #include "simulation/timer.h" +#include "simulation/event_position_distribution.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 @@ -38,6 +39,7 @@ void Restart::restart(std::mapname() + "/DensityField/SimulationData/" + restart_identifier_; restartDrawingDensityField(pair.second->densityForDrawing(), path); + pair.second->positionDistributionFromDensity()->setMaximumDensity(); } } @@ -97,32 +99,6 @@ void Restart::restartTimer(species::TrackedSpecie* reference_specie) { 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 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 deleted_particles = reader_.readD4LongInt(path_to_data); - field->restartDeletedParticlesArray(deleted_particles); - } - - // set the density distribution and calculate the density - { - field->setDensityDistribution(); - } - return; -} -*/ - void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string path) { // restart TimeInBin field { @@ -140,10 +116,6 @@ void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string field->restartDeletedParticlesArray(deleted_particles); } - // set the density distribution and calculate the density - { - field->setDensityDistribution(); - } return; } diff --git a/src/IO/simulation_output.cpp b/src/IO/simulation_output.cpp index d2b3e29..148c786 100755 --- a/src/IO/simulation_output.cpp +++ b/src/IO/simulation_output.cpp @@ -58,6 +58,11 @@ void SimulationOutput::writeMetaData( std::string specie_path = "/" + task_potential_.specie_name; writeMetaData(poisson_solver.get(), specie_path); } + + // write the number of mpi processes used in the current simulation + { + writer.write(MpiCommunication::mpiSize(), "/NumberProcesses"); + } } } diff --git a/src/simulation/cpu_synchronizer.cpp b/src/simulation/cpu_synchronizer.cpp index 440aecd..a23b42b 100755 --- a/src/simulation/cpu_synchronizer.cpp +++ b/src/simulation/cpu_synchronizer.cpp @@ -88,9 +88,6 @@ void CpuSynchronizer::synchronize(DynamicDensityField* field, DynamicDensityField* density_for_drawing, bool reset) { if (field) { - // if(field == last_sync_field) { - // ERROR("The way last_sync_field is created does not work as intended."); - // } sumToAll(field->time_in_bin_s_, field->sync_time_in_bin_s_); field->time_in_bin_s_ = field->sync_time_in_bin_s_; @@ -99,9 +96,6 @@ void CpuSynchronizer::synchronize(DynamicDensityField* field, if (reset) { density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_; density_for_drawing->deleted_particles_ = field->deleted_particles_; - // try setting the distribution for drawing the density here, since ideally it - // the density array and the distribution only have to be set once - density_for_drawing->setDensityDistribution(); } } } @@ -161,12 +155,9 @@ void CpuSynchronizer::synchronize( auto it = tracked_species.begin(); for (auto& pair : tracked_species) { - // DEBUG_LEVEL_3("dynden Synchronization."); synchronize(pair.second->dynamicDensityField(), pair.second->densityForDrawing(), reset); - // DEBUG_LEVEL_3("cc Synchronization."); synchronize(pair.second->currentCollector()); - // DEBUG_LEVEL_3("dellogger Synchronization."); synchronize(pair.second->deletionLogger()); } } \ No newline at end of file diff --git a/src/simulation/density_field.cpp b/src/simulation/density_field.cpp index 712daf8..1417076 100755 --- a/src/simulation/density_field.cpp +++ b/src/simulation/density_field.cpp @@ -125,7 +125,6 @@ DynamicDensityField::DynamicDensityField( if(!timer) { ERROR("Timer is necessary for calculation of density field"); } - initPositionDistributions(); } double DynamicDensityField::density(const Coordinate& position) { @@ -210,13 +209,6 @@ void DynamicDensityField::logMovement( const int energy_bin = energy_binning_.bin(energy_eV); const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle); - // std::stringstream out; - // out << "Energy bin " << energy_bin << "\n"; - // out << "Pitch angle: " << pitch_angle << "\n"; - // out << "Pitch angle bin: " << pitch_angle_bin << "\n"; - // out << "time in bin " << time_in_bin_s; - // DEBUG_LEVEL_3(out.str()); - time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), pitch_angle_bin, energy_bin) += time_in_bin_s; } @@ -240,8 +232,6 @@ blitz::Array DynamicDensityField::densityArray() { DEBUG_LEVEL_3("recalc Density array"); recalculateDensityArray(); - // blitz::Array density(density_per_m3_( - // blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0)); blitz::TinyVector lowerbound(density_per_m3_.lbound(0), density_per_m3_.lbound(1), density_per_m3_.lbound(2)); @@ -314,11 +304,6 @@ void DynamicDensityField::recalculateDensityArray() { // SimulationTimer::eventStopPoint("recalcDensityArray"); } -void DynamicDensityField::setDensityDistribution() { - density_dist_ = - std::uniform_real_distribution(0., blitz::max(densityArray())); -} - double DynamicDensityField::particleNumber() { blitz::Array density = densityArray(); double particleNumber = blitz::sum(density * bin_volume_m3_); @@ -326,99 +311,24 @@ double DynamicDensityField::particleNumber() { return particleNumber; } -void DynamicDensityField::initPositionDistributions() { - double rmin, rmax; - double phimin, phimax; - double zmin, zmax; - - auto rbins = position_binning_.radial_binning.binBorders(); - auto zbins = position_binning_.longitudinal_binning.binBorders(); - auto phibins = position_binning_.azimuth_binning.binBorders(); - - rmin = rbins.front(); - rmax = rbins.back(); - DEBUG_LEVEL_3("rmax: " + std::to_string(rmax)); - - zmin = zbins.front(); - zmax = zbins.back(); - DEBUG_LEVEL_3("zmax: " + std::to_string(zmax)); - - phimin = phibins.front(); - phimax = phibins.back(); - DEBUG_LEVEL_3("phimax: " + std::to_string(phimax)); - - r_dist_ = std::uniform_real_distribution(rmin*rmin, rmax*rmax); - phi_dist_ = std::uniform_real_distribution(phimin, phimax); - z_dist_ = std::uniform_real_distribution(zmin, zmax); +blitz::Array DynamicDensityField:: + sliceSpectrumArray(const Coordinate& position) const { + blitz::TinyVector position_bin = + position_binning_.bin(position.cylinderEntries()); + + return density_per_m3_(position_bin(0), position_bin(1), position_bin(2), + blitz::Range(0, energy_binning_.binIndexMax()-1)).copy(); } -// don't know if it's even good to have the drawing stuff in the -// density distributions... -blitz::TinyVector DynamicDensityField:: - draw(std::mt19937* engine) { - // recalculateDensityArray(); - if (isEqual(blitz::max(density_per_m3_), 0.)) { - DEBUG_LEVEL_3("Density is empty"); - return blitz::TinyVector (0,0,0,0,0); - } - // setDensityDistribution(); - double random_r, random_z, random_phi, random_E, random_n; - double density_in_random_cell; - // SimulationTimer::eventStartPoint("DenDraw rejection"); - do { - DEBUG_LEVEL_3("Missed."); - random_r = std::sqrt(r_dist_(*engine)); - random_phi = phi_dist_(*engine); - random_z = z_dist_(*engine); - random_n = density_dist_(*engine); +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); - density_in_random_cell = density(CylinderCoordinate( - blitz::TinyVector (random_r, random_phi, random_z))); - DEBUG_LEVEL_3("Density in drawn cell: " + std::to_string(density_in_random_cell)); - DEBUG_LEVEL_3("drawn density: " + std::to_string(random_n)); - } while (random_n >= density_in_random_cell); - - // SimulationTimer::eventStopPoint("DenDraw rejection"); - - const blitz::TinyVector position_bin = - position_binning_.bin(CylinderCoordinate( - blitz::TinyVector (random_r, random_phi, random_z)) - .cylinderEntries()); - - - std::vector energyBins = energy_binning_.binBorders(); - energyBins.insert(energyBins.begin(), 0.); - blitz::Array densityAtPosition = density_per_m3_(position_bin(0), - position_bin(1), - position_bin(2), - blitz::Range::all()); - - std::piecewise_constant_distribution E_dist_(energyBins.begin(), - energyBins.end(), - densityAtPosition.begin()); - - random_E = E_dist_(*engine); - - DEBUG_LEVEL_3("energy: " + std::to_string(random_E)); - - const int energy_bin = energy_binning_.bin(random_E); - - std::vector mu_bins = pitch_angle_binning_.binBorders(); - DEBUG_LEVEL_3("Size pitchangle binning: " + std::to_string(mu_bins.size())); - DEBUG_LEVEL_3("Size timeinbin: " + std::to_string(time_in_bin_s_.extent(3))); - - auto values_mu = time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), - blitz::Range(0, pitch_angle_binning_.binIndexMax()-1), - energy_bin); - -// remove the under- and overflow bins for the constant distribution -// for now use only the time_in_bin_s_ array (should make no difference but might be worse?) - std::piecewise_constant_distribution mu_distribution( - mu_bins.begin(), mu_bins.end(), values_mu.begin()); - - double random_mu = mu_distribution(*engine); - - return blitz::TinyVector (random_r, random_phi, random_z, random_mu, random_E); + 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(); } void DynamicDensityField::resetDynamicDensityField() { diff --git a/src/simulation/event_position_distribution.cpp b/src/simulation/event_position_distribution.cpp index 0d85d70..7c0c136 100755 --- a/src/simulation/event_position_distribution.cpp +++ b/src/simulation/event_position_distribution.cpp @@ -39,3 +39,50 @@ CylinderCoordinate EventPositionDistribution::rollPosition( return CylinderCoordinate(blitz::TinyVector( random_numer_r, random_number_phi, random_number_z)); } + +PositionDistributionFromDensity::PositionDistributionFromDensity( + std::shared_ptr density): + density_(density), + density_values(std::uniform_real_distribution(0.,1.)) { + +// get the extent of the domain of the DynamicDensityField object to be used for +// the rejection method + double rmin = density->positionBinning()->radial_binning.binBorders().front(); + double rmax = density->positionBinning()->radial_binning.binBorders().back(); + + double phimin = 0; + double phimax = 2*M_PI; + + double zmin = density->positionBinning()->longitudinal_binning.binBorders().front(); + double zmax = density->positionBinning()->longitudinal_binning.binBorders().back(); + +// initialize the distributions + r_values = std::uniform_real_distribution(rmin*rmin, rmax*rmax); + phi_values = std::uniform_real_distribution(phimin, phimax); + z_values = std::uniform_real_distribution(zmin, zmax); + +} + +void PositionDistributionFromDensity::setMaximumDensity() { + maximum_density_ = blitz::max(density_->densityArray()); +} + +CylinderCoordinate PositionDistributionFromDensity::drawPosition(std::mt19937* engine) { + if(isEqual(maximum_density_, 0.)) { + // abuse the phi coordinate as a check if the density was zero + // only works if phi \in (0, 2pi) + return CylinderCoordinate(blitz::TinyVector(0,-1,0)); + } + + double random_r, random_phi, random_z, random_n; + + do { + random_r = std::sqrt(r_values(*engine)); + random_phi = phi_values(*engine); + random_z = z_values(*engine); +// might be bad that the value gets recalculated for each call of density_->density(...) + } while (random_n*maximum_density_ >= density_->density(CylinderCoordinate( + blitz::TinyVector(random_r, random_phi, random_z)))); + + return CylinderCoordinate(blitz::TinyVector(random_r, random_phi, random_z)); +} \ No newline at end of file diff --git a/src/simulation/injector.cpp b/src/simulation/injector.cpp index f1f585d..45f2fee 100755 --- a/src/simulation/injector.cpp +++ b/src/simulation/injector.cpp @@ -11,17 +11,6 @@ #include "simulation/electromagnetic_field.h" #include -blitz::TinyVector perpendicularNormalVector(blitz::TinyVector vector) { - blitz::TinyVector result(0,0,0); - result[0] = std::copysign(vector[2], vector[0]); - result[1] = std::copysign(vector[2], vector[1]); - result[2] = - std::copysign(std::fabs(vector[0] + std::fabs(vector[1])), vector[2]); - - // DEBUG_LEVEL_3("dot product: " + std::to_string(blitz::dot(result, vector))); - - return result / kinematic::norm(result); -} - Injector::Injector( std::vector& injector_info, double activity, @@ -65,6 +54,9 @@ void Injector::initInjectionTimeDistribution(double delta_t) { std::vector Injector::rollNewParticles( std::mt19937* engine, const double current_time) { +// 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) CylinderCoordinate position = position_distribution_->rollPosition(engine); DEBUG_LEVEL_3("Injected z position: " + std::to_string(position.cylinderEntries()(2))); @@ -85,90 +77,43 @@ std::vector Injector::rollNewParticles( return new_particles; } -/* -void Injector::rollNewParticleFromDensityField(std::mt19937* engine, - std::shared_ptr specie, - std::vector& queue, - const double weight, - const double injection_time) { - blitz::TinyVector particle_specs = - specie->densityForDrawing()->drawPositionAndEnergy(engine); - - // check if density was empty (i.e. Energy component is 0) - if (particle_specs[3] == 0) { - DEBUG_LEVEL_3(specie->name() + ": has zero density"); - return; - } - - DEBUG_LEVEL_3("Injected z position: " + std::to_string(particle_specs(2))); - DEBUG_LEVEL_3("Injected r position: " + std::to_string(particle_specs(0))); - - const double v_abs = kinematic::velocity(particle_specs[3], specie->mass_kg()); - - std::uniform_real_distribution distribution(0.0, 1.0); - const double theta = distribution(*engine) * 2 * M_PI; - const double phi = std::acos(1. - 2.*distribution(*engine)); - - // for now, draw the particles with an isotropic velocity distribution, - // is not realistic but as of now there is no information about the - // velocity vector distribution in the respective cell - blitz::TinyVector v_normal(std::cos(theta) * std::sin(phi), - std::sin(theta) * std::sin(phi), - std::cos(phi)); - - particle::Particle drawn_particle(specie, CylinderCoordinate( - blitz::TinyVector(particle_specs[0], - particle_specs[1], particle_specs[2])), - CartesianVector(v_normal*v_abs), injection_time, weight); - - queue.push_back(drawn_particle); -} -*/ - -void Injector::rollNewParticleFromDensityField(std::mt19937* engine, +void Injector::drawNewParticleFromDensityField(std::mt19937* engine, std::shared_ptr specie, std::vector& queue, std::shared_ptr magnetic_field, const double weight, const double injection_time) { - blitz::TinyVector particle_specs = - specie->densityForDrawing()->draw(engine); +// draw the position + CylinderCoordinate position = + specie->positionDistributionFromDensity()->drawPosition(engine); - // check if density was empty (i.e. Energy component is 0) - if (particle_specs[4] == 0) { +// check if density was empty (i.e. phi value lower than 0) + if (position.cylinderEntries()(1) < 0) { DEBUG_LEVEL_3(specie->name() + ": has zero density"); return; } - DEBUG_LEVEL_3("Injected z position: " + std::to_string(particle_specs(2))); - DEBUG_LEVEL_3("Injected r position: " + std::to_string(particle_specs(0))); + DEBUG_LEVEL_3("Injected z position: " + + std::to_string(position.cylinderEntries()(2))); + DEBUG_LEVEL_3("Injected r position: " + + std::to_string(position.cylinderEntries()(0))); - CylinderCoordinate position(blitz::TinyVector(particle_specs[0], - particle_specs[1], - particle_specs[2])); +// draw the velocity + CartesianVector velocity(blitz::TinyVector(0,0,0)); - const double v_abs = kinematic::velocity(particle_specs[4], specie->mass_kg()); - - std::uniform_real_distribution distribution(0.0, 1.0); - const double theta = distribution(*engine) * 2 * M_PI; - - const double mu = particle_specs[3]; - DEBUG_LEVEL_3("mu: " + std::to_string(mu)); - - blitz::TinyVector magnetic_field_value = magnetic_field-> - value(position).cartesianEntries(position); - const double abs_B = kinematic::norm(magnetic_field_value); - - blitz::TinyVector perpendicular_vector = - perpendicularNormalVector(magnetic_field_value); - - blitz::TinyVector v_normal = mu*magnetic_field_value/abs_B + - std::sqrt(1-mu*mu)*kinematic::rotateVector(perpendicular_vector, - magnetic_field_value, - theta); +// in case the magnetic field is 0 at the current position draw the velocity +// with respect to the z-axis otherwise use the magnetic field + if(kinematic::norm(magnetic_field->value(position). + cartesianEntries(position)) == 0) { + velocity = specie->velocityDistributionFromDensityField()-> + rollVelocity(position, engine); + } else { + velocity = specie->velocityDistributionFromDensityField()-> + rollVelocity(position, engine, magnetic_field); + } particle::Particle drawn_particle(specie, position, - CartesianVector(v_normal*v_abs), injection_time, weight); + velocity, injection_time, weight); queue.push_back(drawn_particle); } diff --git a/src/simulation/simulation.cpp b/src/simulation/simulation.cpp index 10922a6..e1065b0 100755 --- a/src/simulation/simulation.cpp +++ b/src/simulation/simulation.cpp @@ -33,6 +33,8 @@ #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) @@ -185,7 +187,6 @@ void Simulation::start() { while (timesteps < number_timesteps) { std::stringstream out; out << "Timeinterval: " << timer_->time() << "s."; - // out << "\n size of particle: " << sizeof(particle::Particle); DEBUG_LEVEL_3(out.str()); int events_of_cylcle = eventsOfCycle(event_stride, leftover_events_time_resolution); @@ -235,25 +236,24 @@ void Simulation::start() { random_->engine()); SimulationTimer::eventStopPoint(std::string("Output")); + SimulationTimer::eventStartPoint("Reset"); if(reset) { SIM_INFO("Do resets and increase the timestep for timeresolution."); timer_->increaseTimestep(delta_t); for(auto& pair : tracked_species_) { pair.second->dynamicDensityField()->resetDynamicDensityField(); - // pair.second->dynamicDensityFieldWithPitchAngle()->resetDynamicDensityField(); - // questionable if they need to be reset: - // + time res in current - // - ions very slow -> very unlikely that an ion crosses a boundary pair.second->currentCollector()->resetCurrentCollector(); - // do not need to be reset, since the time resolution considers the same - // set of particles 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 = time_resolution_this_cpu; timesteps++; } + SimulationTimer::eventStopPoint("Reset"); } } @@ -281,14 +281,13 @@ void Simulation::processEvents(int events, int density_events, int cpu_syncs) { if (queue_.empty()) { std::vector new_particles; if(current_density_event == density_events) { - // if(cpu_syncs > 0) { - // DEBUG_LEVEL_3("Break while loop."); - // break; - // } current_event += 1; DEBUG_LEVEL_2("Inject particles to queue."); SimulationTimer::eventStartPoint(std::string("ParticleInjection")); new_particles = determineInjectedParticles(random_.get()); +// 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; @@ -390,12 +389,14 @@ void Simulation::processUntilTermination( 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); @@ -413,10 +414,12 @@ void Simulation::processUntilTermination( 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(), @@ -479,6 +482,7 @@ interaction::InteractionOutput Simulation::interact( if (total_macroscopic_cross_section_m <= 0.) { // do nothing + SIM_INFO("total mcs <= 0"); return interaction::InteractionOutput(); } else { std::discrete_distribution interaction_decider( @@ -494,7 +498,6 @@ interaction::InteractionOutput Simulation::interact( std::vector Simulation::determineInjectedParticles( RandomNumbers* random) { - // timer_->increaseTimestep(injector_->timePassed()); return injector_->rollNewParticles(random->engine(), timer_->time()); } @@ -502,15 +505,21 @@ std::vector Simulation::determineInjectedDensityParticles( RandomNumbers* random, const int numberParticlesToDraw, const int current, std::map& particleNumbers) { std::vector new_particles{}; + if(!new_particles.empty()) { - ERROR("In drawing particles from the density: the new particles vector is not empty at initialization"); + 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(); @@ -518,12 +527,14 @@ std::vector Simulation::determineInjectedDensityParticles( out << particleNumbers[pair.first]; DEBUG_LEVEL_3(out.str()); } - injector_->rollNewParticleFromDensityField(random->engine(), - pair.second, - new_particles, - magnetic_field_, - particleNumbers[pair.first]/numberParticlesToDraw/MpiCommunication::mpiSize(), - injection_time); +#endif + + double weight = particleNumbers[pair.first]/numberParticlesToDraw + /MpiCommunication::mpiSize(); + + injector_->drawNewParticleFromDensityField(random->engine(), + pair.second, new_particles, magnetic_field_, + weight, injection_time); } return new_particles; } diff --git a/src/simulation/species.cpp b/src/simulation/species.cpp index e185a3a..7984945 100755 --- a/src/simulation/species.cpp +++ b/src/simulation/species.cpp @@ -9,6 +9,7 @@ #include "simulation/parameter.h" #include "simulation/terminator.h" #include "simulation/velocity_distribution.h" +#include "simulation/event_position_distribution.h" namespace species { @@ -52,7 +53,12 @@ TrackedSpecie::TrackedSpecie( current_collector_(std::shared_ptr(nullptr)), velocity_distribution_(velocity_distribution), drift_velocity_(drift_velocity), - density_for_drawing_(density_for_drawing) {} + density_for_drawing_(density_for_drawing), + position_distribution_from_density_( + std::make_shared(density_for_drawing)), + velocity_distribution_from_density_( + std::make_shared( + density_for_drawing, mass_kg)) {} DensityField* TrackedSpecie::densityField() { return density_field_.get(); @@ -93,6 +99,16 @@ CurrentCollector* TrackedSpecie::currentCollector() { return current_collector_.get(); } +PositionDistributionFromDensity* + TrackedSpecie::positionDistributionFromDensity() { + return position_distribution_from_density_.get(); +} + +VelocityDistributionFromDensityField* + TrackedSpecie::velocityDistributionFromDensityField() { + return velocity_distribution_from_density_.get(); +} + std::vector> TrackedSpecie::interactions() { return interactions_; diff --git a/src/simulation/velocity_distribution.cpp b/src/simulation/velocity_distribution.cpp index 4812e54..c2f8f2a 100755 --- a/src/simulation/velocity_distribution.cpp +++ b/src/simulation/velocity_distribution.cpp @@ -3,6 +3,21 @@ #include "simulation/drift_velocity.h" #include "simulation/kinematic.h" #include "simulation/velocity_distribution_function.h" +#include "simulation/density_field.h" +#include "simulation/electromagnetic_field.h" + +// utility function returning a unit vector perpendicular to the given +// (cartesian) TinyVector +blitz::TinyVector perpendicularNormalVector( + blitz::TinyVector vector) { + blitz::TinyVector result(0,0,0); + result[0] = std::copysign(vector[2], vector[0]); + result[1] = std::copysign(vector[2], vector[1]); + result[2] = -std::copysign(std::fabs(vector[0] + std::fabs(vector[1])), + vector[2]); + + return result / kinematic::norm(result); +} VelocityDistributionFromFunction::VelocityDistributionFromFunction( std::shared_ptr fv) @@ -13,3 +28,113 @@ CartesianVector VelocityDistributionFromFunction::rollVelocity( std::mt19937* engine) { return fv_->rollVelocity(engine); } + +VelocityDistributionFromDensityField::VelocityDistributionFromDensityField( + std::shared_ptr density_field, double mass_kg): + density_field_(density_field), + energyBinBorders_(density_field->energyBinning()->binBorders()), + pitchAngleBinBorders_(density_field->pitchAngleBinning()->binBorders()), + theta_distribution_(std::uniform_real_distribution(0.,1.)), + mass_kg_(mass_kg) {} + +// not important as of now since it's meant for drawing a velocity from the +// pitch angle distribution and not to be used in an interaction context in which +// the drift velocity is necessary for the determination of the cross section +// (might be possible to extract from the pitch angle dist or from the current) +// returns a 0 CartesianVector +CartesianVector VelocityDistributionFromDensityField::driftVelocity_ms( + const CylinderVector& position) { + return CartesianVector(blitz::TinyVector (0,0,0)); +} + +CartesianVector VelocityDistributionFromDensityField::rollVelocity( + const Coordinate& position, std::mt19937* engine) { + + // draw energy from DynamicDensityField + blitz::Array energyValues = density_field_-> + sliceSpectrumArray(position); + + std::piecewise_constant_distribution energy_dist( + energyBinBorders_.begin(), + energyBinBorders_.end(), + energyValues.begin()); + + double energy_eV = energy_dist(*engine); + + // draw pitch angle from DynamicDensityField + + blitz::Array pitchAngleValues = density_field_-> + sliceTimeInBinArray(position, energy_eV); + + std::piecewise_constant_distribution pitchAngle_dist( + pitchAngleBinBorders_.begin(), + pitchAngleBinBorders_.end(), + pitchAngleValues.begin()); + + double pitchAngle = pitchAngle_dist(*engine); + + // construct the velocity + + const double theta = theta_distribution_(*engine)*2*M_PI; + + blitz::TinyVector zDirection(0,0,1); + + 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); + + return CartesianVector(v_direction * vMagnitude); +} + +CartesianVector VelocityDistributionFromDensityField::rollVelocity( + const Coordinate& position, std::mt19937* engine, + std::shared_ptr magnetic_field) { + + // draw energy from DynamicDensityField + blitz::Array energyValues = density_field_-> + sliceSpectrumArray(position); + + std::piecewise_constant_distribution energy_dist( + energyBinBorders_.begin(), + energyBinBorders_.end(), + energyValues.begin()); + + double energy_eV = energy_dist(*engine); + + // draw pitch angle from DynamicDensityField + + blitz::Array pitchAngleValues = density_field_-> + sliceTimeInBinArray(position, energy_eV); + + std::piecewise_constant_distribution pitchAngle_dist( + pitchAngleBinBorders_.begin(), + pitchAngleBinBorders_.end(), + pitchAngleValues.begin()); + + double pitchAngle = pitchAngle_dist(*engine); + + // construct the velocity + + const double theta = theta_distribution_(*engine)*2*M_PI; + + blitz::TinyVector cartesianB_values = + magnetic_field->value(position).cartesianEntries(position); + const double Bmagnitude = kinematic::norm(cartesianB_values); + + const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_); + + blitz::TinyVector v_perp = + perpendicularNormalVector(cartesianB_values); + + blitz::TinyVector v_direction = pitchAngle + * cartesianB_values/Bmagnitude + + std::sqrt(1 - pitchAngle*pitchAngle) + * kinematic::rotateVector(v_perp, cartesianB_values, theta); + + return CartesianVector(v_direction * vMagnitude); +} \ No newline at end of file