Moved drawing from density to seperate classes

This commit is contained in:
2025-02-05 10:31:56 +01:00
parent b529021149
commit 57ef99a57b
15 changed files with 376 additions and 280 deletions
+4 -2
View File
@@ -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_;
+14 -13
View File
@@ -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<double, 5> 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<double, 3> densityArray();
@@ -57,6 +59,16 @@ class DynamicDensityField : public DensityField {
blitz::Array<long int, 5> deletedParticlesArray() const;
blitz::Array<double, 3> 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<double, 1> 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<double, 1> 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<double, 5> time_in_bin);
void restartDeletedParticlesArray(blitz::Array<long int, 5> 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<double, 5> time_in_bin_s_;
blitz::Array<long int, 5> 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<double> r_dist_;
std::uniform_real_distribution<double> phi_dist_;
std::uniform_real_distribution<double> z_dist_;
std::uniform_real_distribution<double> density_dist_;
const PitchAngleBinning pitch_angle_binning_;
std::shared_ptr<Timer> timer_;
@@ -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<ScalarField> mother_density,
@@ -33,4 +37,31 @@ class EventPositionDistribution {
std::uniform_real_distribution<double> 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<DynamicDensityField> 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<DynamicDensityField> density_;
// distributions for the spatial directions and for the density
std::uniform_real_distribution<double> r_values;
std::uniform_real_distribution<double> phi_values;
std::uniform_real_distribution<double> z_values;
std::uniform_real_distribution<double> density_values;
};
#endif /* EVENT_POSITION_DISTRIBUTION_H */
+8 -7
View File
@@ -41,13 +41,14 @@ class Injector {
std::vector<particle::Particle> rollNewParticles(std::mt19937* engine,
const double current_time);
// void rollNewParticleFromDensityField(std::mt19937* engine,
// std::shared_ptr<species::TrackedSpecie> specie,
// std::vector<particle::Particle>& 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<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> field,
+11
View File
@@ -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<std::shared_ptr<interaction::Interaction>> interactions();
void addInteraction(std::shared_ptr<interaction::Interaction> 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<DynamicDensityField> density_field_;
std::shared_ptr<VelocityDistribution> velocity_distribution_;
@@ -98,6 +105,10 @@ class TrackedSpecie : public Specie {
std::vector<std::shared_ptr<interaction::Interaction>> interactions_;
std::shared_ptr<DynamicDensityField> density_for_drawing_;
std::shared_ptr<PositionDistributionFromDensity>
position_distribution_from_density_;
std::shared_ptr<VelocityDistributionFromDensityField>
velocity_distribution_from_density_;
};
class BackgroundSpecie : public Specie {
+41 -13
View File
@@ -25,22 +25,50 @@ class VelocityDistributionFromFunction : public VelocityDistribution {
std::shared_ptr<VelocityDistributionFunction> 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<DensityField> 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<DynamicDensityField> 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<MagneticField> magnetic_field);
private:
std::shared_ptr<DensityField> density_field_;
// mass of the species of which the density field is a part of
const double mass_kg_;
std::shared_ptr<DynamicDensityField> density_field_;
blitz::Array<double, 1> energy_values;
blitz::Array<double, 1> mu_values;
std::vector<double> energyBinBorders_;
std::vector<double> pitchAngleBinBorders_;
std::uniform_real_distribution<double> theta_distribution_;
};
*/
#endif /* VELOCITY_DISTRIBUTION_H */
+2 -30
View File
@@ -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::map<std::string, std::shared_ptr<species::TrackedSpec
std::string path = pair.second->name() + "/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<double, 4> 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<long int, 4> 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;
}
+5
View File
@@ -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");
}
}
}
-9
View File
@@ -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());
}
}
+15 -105
View File
@@ -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<double, 3> DynamicDensityField::densityArray() {
DEBUG_LEVEL_3("recalc Density array");
recalculateDensityArray();
// blitz::Array<double, 3> density(density_per_m3_(
// blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0));
blitz::TinyVector<int,3> 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<double>(0., blitz::max(densityArray()));
}
double DynamicDensityField::particleNumber() {
blitz::Array<double, 3> 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<double>(rmin*rmin, rmax*rmax);
phi_dist_ = std::uniform_real_distribution<double>(phimin, phimax);
z_dist_ = std::uniform_real_distribution<double>(zmin, zmax);
blitz::Array<double, 1> DynamicDensityField::
sliceSpectrumArray(const Coordinate& position) const {
blitz::TinyVector<int, 3> 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<double, 5> DynamicDensityField::
draw(std::mt19937* engine) {
// recalculateDensityArray();
if (isEqual(blitz::max(density_per_m3_), 0.)) {
DEBUG_LEVEL_3("Density is empty");
return blitz::TinyVector<double, 5> (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<double, 1> DynamicDensityField::
sliceTimeInBinArray(const Coordinate& position, double energy_eV) const {
blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
int energy_bin = energy_binning_.bin(energy_eV);
density_in_random_cell = density(CylinderCoordinate(
blitz::TinyVector<double, 3> (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<int, 3> position_bin =
position_binning_.bin(CylinderCoordinate(
blitz::TinyVector<double, 3> (random_r, random_phi, random_z))
.cylinderEntries());
std::vector<double> energyBins = energy_binning_.binBorders();
energyBins.insert(energyBins.begin(), 0.);
blitz::Array<double, 1> densityAtPosition = density_per_m3_(position_bin(0),
position_bin(1),
position_bin(2),
blitz::Range::all());
std::piecewise_constant_distribution<double> 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<double> 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<double> mu_distribution(
mu_bins.begin(), mu_bins.end(), values_mu.begin());
double random_mu = mu_distribution(*engine);
return blitz::TinyVector<double, 5> (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() {
@@ -39,3 +39,50 @@ CylinderCoordinate EventPositionDistribution::rollPosition(
return CylinderCoordinate(blitz::TinyVector<double, 3>(
random_numer_r, random_number_phi, random_number_z));
}
PositionDistributionFromDensity::PositionDistributionFromDensity(
std::shared_ptr<DynamicDensityField> density):
density_(density),
density_values(std::uniform_real_distribution<double>(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<double>(rmin*rmin, rmax*rmax);
phi_values = std::uniform_real_distribution<double>(phimin, phimax);
z_values = std::uniform_real_distribution<double>(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<double,3>(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<double,3>(random_r, random_phi, random_z))));
return CylinderCoordinate(blitz::TinyVector<double, 3>(random_r, random_phi, random_z));
}
+26 -81
View File
@@ -11,17 +11,6 @@
#include "simulation/electromagnetic_field.h"
#include <sstream>
blitz::TinyVector<double, 3> perpendicularNormalVector(blitz::TinyVector<double, 3> vector) {
blitz::TinyVector<double, 3> 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<InjectorInfo>& injector_info,
double activity,
@@ -65,6 +54,9 @@ void Injector::initInjectionTimeDistribution(double delta_t) {
std::vector<particle::Particle> 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<particle::Particle> Injector::rollNewParticles(
return new_particles;
}
/*
void Injector::rollNewParticleFromDensityField(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
const double weight,
const double injection_time) {
blitz::TinyVector<double, 4> 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<double> 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<double, 3> 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<double, 3>(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<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> magnetic_field,
const double weight,
const double injection_time) {
blitz::TinyVector<double, 5> 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<double, 3>(particle_specs[0],
particle_specs[1],
particle_specs[2]));
// draw the velocity
CartesianVector velocity(blitz::TinyVector<double, 3>(0,0,0));
const double v_abs = kinematic::velocity(particle_specs[4], specie->mass_kg());
std::uniform_real_distribution<double> 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<double, 3> magnetic_field_value = magnetic_field->
value(position).cartesianEntries(position);
const double abs_B = kinematic::norm(magnetic_field_value);
blitz::TinyVector<double, 3> perpendicular_vector =
perpendicularNormalVector(magnetic_field_value);
blitz::TinyVector<double, 3> 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);
}
+30 -19
View File
@@ -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<particle::Particle> 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<int> interaction_decider(
@@ -494,7 +498,6 @@ interaction::InteractionOutput Simulation::interact(
std::vector<particle::Particle> Simulation::determineInjectedParticles(
RandomNumbers* random) {
// timer_->increaseTimestep(injector_->timePassed());
return injector_->rollNewParticles(random->engine(), timer_->time());
}
@@ -502,15 +505,21 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
RandomNumbers* random, const int numberParticlesToDraw, const int current,
std::map<std::string, double>& particleNumbers) {
std::vector<particle::Particle> new_particles{};
if(!new_particles.empty()) {
ERROR("In drawing particles from the density: the new particles vector is not empty at initialization");
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<particle::Particle> 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;
}
+17 -1
View File
@@ -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<CurrentCollector>(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<PositionDistributionFromDensity>(density_for_drawing)),
velocity_distribution_from_density_(
std::make_shared<VelocityDistributionFromDensityField>(
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<std::shared_ptr<interaction::Interaction>>
TrackedSpecie::interactions() {
return interactions_;
+125
View File
@@ -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<double, 3> perpendicularNormalVector(
blitz::TinyVector<double, 3> vector) {
blitz::TinyVector<double, 3> 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<VelocityDistributionFunction> fv)
@@ -13,3 +28,113 @@ CartesianVector VelocityDistributionFromFunction::rollVelocity(
std::mt19937* engine) {
return fv_->rollVelocity(engine);
}
VelocityDistributionFromDensityField::VelocityDistributionFromDensityField(
std::shared_ptr<DynamicDensityField> 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<double>(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<double, 3> (0,0,0));
}
CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
std::piecewise_constant_distribution<double> energy_dist(
energyBinBorders_.begin(),
energyBinBorders_.end(),
energyValues.begin());
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> 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<double, 3> zDirection(0,0,1);
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_);
// vector perpendicular to e_z
blitz::TinyVector<double, 3> v_perp(1,0,0);
blitz::TinyVector<double, 3> 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<MagneticField> magnetic_field) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
std::piecewise_constant_distribution<double> energy_dist(
energyBinBorders_.begin(),
energyBinBorders_.end(),
energyValues.begin());
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> 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<double, 3> 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<double, 3> v_perp =
perpendicularNormalVector(cartesianB_values);
blitz::TinyVector<double, 3> v_direction = pitchAngle
* cartesianB_values/Bmagnitude
+ std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, cartesianB_values, theta);
return CartesianVector(v_direction * vMagnitude);
}