Implemented pitch angle resolution.

Still includes (and uses) the non-pitch angle
resolved fields as well; have to be either removed
completely or refactored s.t. one of the two options
is chosen.
Pitch angle distribution has a hardcoded number of
bins for now, and exists in 'energy_binning.h'
This commit is contained in:
2024-10-28 15:00:19 +01:00
parent b4cbd8c44c
commit 5fc227e1b1
24 changed files with 1126 additions and 42 deletions
+39 -4
View File
@@ -17,6 +17,16 @@ void CpuSynchronizer::sumToAll(blitz::Array<double, 4>& array,
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<double, 5>& array,
blitz::Array<double, 5>& last_sync_array) {
int size = array.size();
blitz::Array<double, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_DOUBLE,
MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
blitz::Array<long int, 4>& last_sync_array) {
int size = array.size();
@@ -27,6 +37,16 @@ void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<long int, 5>& array,
blitz::Array<long int, 5>& last_sync_array) {
int size = array.size();
blitz::Array<long int, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_LONG,
MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<double, 3>& array,
blitz::Array<double, 3>& last_sync_array) {
int size = array.size();
@@ -86,6 +106,22 @@ void CpuSynchronizer::synchronize(DynamicDensityField* field,
}
}
void CpuSynchronizer::synchronize(DynamicDensityFieldWithPitchAngle* field,
DynamicDensityFieldWithPitchAngle* density_for_drawing,
bool reset) {
if (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_;
}
if (reset) {
density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_;
density_for_drawing->deleted_particles_ = field->deleted_particles_;
density_for_drawing->setDensityDistribution();
}
}
void CpuSynchronizer::synchronize(CurrentCollector* collector) {
if (collector) {
sumToAll(collector->z_negative_crossings,
@@ -139,15 +175,14 @@ void CpuSynchronizer::synchronize(
tracked_species, bool reset) {
MPI_Barrier(MPI_COMM_WORLD);
auto it = tracked_species.begin();
// drops due to time being a global variable now
//DEBUG_LEVEL_3("Timer Synchronization.");
//synchronize(it->second->dynamicDensityField()->timer_.get(),
// it->second->lastSyncDensityField()->timer_.get());
for (auto& pair : tracked_species) {
// DEBUG_LEVEL_3("dynden Synchronization.");
synchronize(pair.second->dynamicDensityField(),
pair.second->densityForDrawing(), reset);
synchronize(pair.second->dynamicDensityFieldWithPitchAngle(),
pair.second->dynamicDensityFieldWithPitchAngleForDrawing(),
reset);
// DEBUG_LEVEL_3("cc Synchronization.");
synchronize(pair.second->currentCollector());
// DEBUG_LEVEL_3("dellogger Synchronization.");
+420
View File
@@ -4,6 +4,7 @@
#include "simulation/errors.h"
#include "simulation/event_position_distribution.h"
#include "simulation/scalar_field.h"
#include "simulation/kinematic.h"
template <class T>
blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
@@ -15,6 +16,17 @@ blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
return data.copy();
}
template<class T>
blitz::Array<T, 5> initiate5DArray(blitz::Range radial,
blitz::Range phi,
blitz::Range longitudinal,
blitz::Range pitch_angle,
blitz::Range energy) {
blitz::Array<T, 5> data(radial, phi, longitudinal, pitch_angle, energy);
data = static_cast<T>(0);
return data.copy();
}
blitz::Array<double, 3> initiateVolumeArray(
blitz::Range radial,
blitz::Range phi,
@@ -131,6 +143,11 @@ void DynamicDensityField::logMovement(const Coordinate& position,
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
// std::stringstream out;
// out << "Energy bin " << energy_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),
energy_bin) += time_in_bin_s;
}
@@ -364,6 +381,409 @@ void DynamicDensityField::restartDeletedParticlesArray(
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// TBD
DynamicDensityFieldWithPitchAngle::DynamicDensityFieldWithPitchAngle(
const CylinderBinning& position_binning,
const EnergyBinning& energy_binning,
const PitchAngleBinning& pitch_angle_binning,
std::shared_ptr<Timer> timer) :
position_binning_(position_binning),
energy_binning_(energy_binning),
pitch_angle_binning_(pitch_angle_binning),
timer_(timer),
time_in_bin_s_(initiate5DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
sync_time_in_bin_s_(initiate5DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
deleted_particles_(initiate5DArray<long int>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
sync_deleted_particles_(initiate5DArray<long int>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
density_per_m3_(initiate4DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
bin_volume_m3_(initiateVolumeArray(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
position_binning.stepsize())) {
if(!timer) {
ERROR("Timer is necessary for calculation of density field");
}
initPositionDistributions();
}
double DynamicDensityFieldWithPitchAngle::density(const Coordinate& position) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
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),
blitz::Range::all(), blitz::Range::all()));
const long int deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), blitz::Range::all()));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
double DynamicDensityFieldWithPitchAngle::density(const Coordinate& position,
double energy_eV) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
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),
blitz::Range::all(), energy_bin));
const long deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), energy_bin));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
bool DynamicDensityFieldWithPitchAngle::changedPositionBin(
const Coordinate& old_position,
const Coordinate& new_position) const {
const blitz::TinyVector<int, 3> old_bin =
position_binning_.bin(old_position.cylinderEntries());
const blitz::TinyVector<int, 3> new_bin =
position_binning_.bin(new_position.cylinderEntries());
return !((old_bin(0) == new_bin(0)) && (old_bin(1) == new_bin(1)) &&
(old_bin(2) == new_bin(2)));
}
bool DynamicDensityFieldWithPitchAngle::changedEnergyBin(
double old_energy_eV,
double new_energy_eV) const {
const int old_bin = energy_binning_.bin(old_energy_eV);
const int new_bin = energy_binning_.bin(new_energy_eV);
return !(old_bin == new_bin);
}
bool DynamicDensityFieldWithPitchAngle::changedPitchAngleBin(
double old_mu,
double new_mu) const {
const int old_bin = pitch_angle_binning_.bin(old_mu);
const int new_bin = pitch_angle_binning_.bin(new_mu);
if(!(old_bin == new_bin)) {
DEBUG_LEVEL_3("old mu: " + std::to_string(old_mu));
DEBUG_LEVEL_3("old bin: " + std::to_string(old_bin));
DEBUG_LEVEL_3("new mu: " + std::to_string(new_mu));
DEBUG_LEVEL_3("new bin: " + std::to_string(new_bin));
}
return !(old_bin == new_bin);
}
void DynamicDensityFieldWithPitchAngle::logMovement(
const Coordinate& position,
double energy_eV,
double pitch_angle,
double time_in_bin_s) {
const blitz::TinyVector<int, 3> 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);
// 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;
}
void DynamicDensityFieldWithPitchAngle::logDeletion(
const Coordinate& position,
double energy_eV,
double pitch_angle) {
const blitz::TinyVector<int, 3> 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<double, 3> DynamicDensityFieldWithPitchAngle::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::fourthIndex iE;
DEBUG_LEVEL_3("density sum");
density = blitz::sum(density_per_m3_, iE);
return density.copy();
}
blitz::Array<double, 4> DynamicDensityFieldWithPitchAngle::spectrumArray() {
recalculateDensityArray();
return density_per_m3_;
}
blitz::Array<double, 5> DynamicDensityFieldWithPitchAngle::timeInBinArray() const {
return time_in_bin_s_;
}
blitz::Array<long int, 5> DynamicDensityFieldWithPitchAngle::deletedParticlesArray() const {
return deleted_particles_;
}
blitz::Array<double, 3> DynamicDensityFieldWithPitchAngle::binVolumeArray() const {
return bin_volume_m3_;
}
const EnergyBinning* DynamicDensityFieldWithPitchAngle::energyBinning() const {
return &energy_binning_;
}
const CylinderBinning* DynamicDensityFieldWithPitchAngle::positionBinning() const {
return &position_binning_;
}
const PitchAngleBinning* DynamicDensityFieldWithPitchAngle::pitchAngleBinning() const {
return &pitch_angle_binning_;
}
double DynamicDensityFieldWithPitchAngle::physicalTime() const {
return timer_->time();
}
double DynamicDensityFieldWithPitchAngle::timeResolution() const {
return timer_->getDeltaT();
}
void DynamicDensityFieldWithPitchAngle::recalculateDensityArray() {
blitz::firstIndex ir;
blitz::secondIndex iphi;
blitz::thirdIndex iz;
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)
// blitz::Array<double, 5> temp((time_in_bin_s_(ir, iphi, iz, ipitch, iE)));
density_per_m3_ = blitz::sum((time_in_bin_s_(ir, iphi, iz, iE, ipitch) / t -
deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) /
bin_volume_m3_(ir, iphi, iz);
}
void DynamicDensityFieldWithPitchAngle::setDensityDistribution() {
density_dist_ =
std::uniform_real_distribution<double>(0., blitz::max(densityArray()));
}
double DynamicDensityFieldWithPitchAngle::particleNumber() {
blitz::Array<double, 3> density = densityArray();
double particleNumber = blitz::sum(density * bin_volume_m3_);
DEBUG_LEVEL_3("particle number: " + std::to_string(particleNumber));
return particleNumber;
}
void DynamicDensityFieldWithPitchAngle::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);
}
// don't know if it's even good to have the drawing stuff in the
// density distributions...
blitz::TinyVector<double, 5> DynamicDensityFieldWithPitchAngle::
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;
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);
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);
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 test = 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(), test.begin());
double random_mu = mu_distribution(*engine);
return blitz::TinyVector<double, 5> (random_r, random_phi, random_z, random_mu, random_E);
}
void DynamicDensityFieldWithPitchAngle::resetDynamicDensityField() {
//timer_->resetTime(); // time stays global
time_in_bin_s_ = 0.;
deleted_particles_ = 0.;
density_per_m3_ = 0.;
sync_time_in_bin_s_ = 0.;
sync_deleted_particles_ = 0.;
}
void DynamicDensityFieldWithPitchAngle::restartTimer(double time, double delta_t) {
// make sure that the timer can only be restarted once (per dynamicDensityField object)
// probably not necessary, but whatever...
if(timer_restarted_) {
return;
}
timer_restarted_ = true;
timer_->setTime(time);
timer_->setDeltaT(delta_t);
}
void DynamicDensityFieldWithPitchAngle::restartTimeInBin(blitz::Array<double, 5> time_in_bin) {
if(!blitz::all(time_in_bin_s_.length() == time_in_bin.length())) {
std::stringstream out;
out << "Expected a size of " << time_in_bin_s_.length();
out << ", received a length of " << time_in_bin.length();
out << " for time_in_bin array";
ERROR(out.str());
}
time_in_bin_s_ = time_in_bin.copy().reindex(time_in_bin_s_.lbound());
}
void DynamicDensityFieldWithPitchAngle::restartDeletedParticlesArray(
blitz::Array<long int, 5> deleted_particles) {
if(!blitz::all(deleted_particles_.length() == deleted_particles.length())) {
std::stringstream out;
out << "Expected a size of " << deleted_particles_.length();
out << ", received a length of " << deleted_particles.length();
out << " for deleted_particles array";
ERROR(out.str());
}
deleted_particles_ = deleted_particles.copy().reindex(deleted_particles_.lbound());
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ConstantDensityField::ConstantDensityField(std::shared_ptr<ScalarField> density)
: density_(density) {}
+43 -3
View File
@@ -2,8 +2,7 @@
#include <math.h>
#include <algorithm>
// probably rename to indicate what type of borders are created
std::vector<double> generateBinBorders(double bin_min,
std::vector<double> generateLogBinBorders(double bin_min,
double bin_max,
int num_bins) {
const double min_bin_log = log10(bin_min);
@@ -18,11 +17,25 @@ std::vector<double> generateBinBorders(double bin_min,
return bin_borders;
}
std::vector<double> generateLinearBinBorders(double bin_min,
double bin_max,
int num_bins) {
const double bin_size = (bin_max - bin_min) / num_bins;
std::vector<double> bin_borders;
for (int i = 0; i <= num_bins; ++i) {
const double bin_border = bin_size * i + bin_min;
bin_borders.push_back(bin_border);
}
return bin_borders;
}
EnergyBinning::EnergyBinning(double minimal_energy,
double maximal_energy,
int num_bins)
: energy_bin_borders_(
generateBinBorders(minimal_energy, maximal_energy, num_bins)) {}
generateLogBinBorders(minimal_energy, maximal_energy, num_bins)) {}
EnergyBinning::EnergyBinning(std::vector<double> energy_bin_borders)
: energy_bin_borders_(energy_bin_borders) {}
@@ -48,3 +61,30 @@ int EnergyBinning::binIndexMin() const {
int EnergyBinning::binIndexMax() const {
return numBins();
}
PitchAngleBinning::PitchAngleBinning(int num_bins) :
pitch_angle_bin_borders_(generateLinearBinBorders(-1, 1, num_bins)) {}
int PitchAngleBinning::bin(double pitch_angle) const {
auto const it = std::lower_bound(pitch_angle_bin_borders_.begin(),
pitch_angle_bin_borders_.end(),
pitch_angle);
return (it - pitch_angle_bin_borders_.begin()) - 1;
}
int PitchAngleBinning::numBins() const {
return pitch_angle_bin_borders_.size() - 1;
}
std::vector<double> PitchAngleBinning::binBorders() const {
return pitch_angle_bin_borders_;
}
int PitchAngleBinning::binIndexMin() const {
return -1;
}
int PitchAngleBinning::binIndexMax() const {
return numBins();
}
+63 -3
View File
@@ -8,8 +8,20 @@
#include "simulation/species.h"
#include "simulation/density_field.h"
#include "simulation/velocity_distribution.h"
#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,
@@ -104,9 +116,57 @@ void Injector::rollNewParticleFromDensityField(std::mt19937* engine,
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);
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,
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->dynamicDensityFieldWithPitchAngleForDrawing()->draw(engine);
// check if density was empty (i.e. Energy component is 0)
if (particle_specs[4] == 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)));
CylinderCoordinate position(blitz::TinyVector<double, 3>(particle_specs[0],
particle_specs[1],
particle_specs[2]));
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);
particle::Particle drawn_particle(specie, position,
CartesianVector(v_normal*v_abs), injection_time, weight);
queue.push_back(drawn_particle);
}
+26 -1
View File
@@ -13,6 +13,12 @@
#include "tools/simulation_time.h"
double cosAngleBetweenVectors(blitz::TinyVector<double, 3> vector_1,
blitz::TinyVector<double, 3> vector_2) {
const double divisor = kinematic::norm(vector_1) * kinematic::norm(vector_2);
return blitz::dot(vector_1, vector_2)/divisor;
}
BorisMover::BorisMover(double maximal_time_step_s)
: maximal_time_step_s_(maximal_time_step_s) {
ASSERT_POSITIVE(&maximal_time_step_s_,
@@ -180,9 +186,13 @@ void DriftMover::move(particle::Particle* particle,
auto old_position = particle->position();
auto old_velocity = particle->velocity();
double old_kinetic_energy = particle->kineticEnergy_eV();
double old_mu = cosAngleBetweenVectors(
magnetic_field->value(old_position).cartesianEntries(old_position),
old_velocity.cartesianEntries(old_position));
bool changed_position_bin = false;
bool changed_energy_bin = false;
bool changed_mu_bin = false;
bool left_simulation_domain = false;
// if particle too slow -> timestep > maximum time the particle lives
// -> add maximal timestep to time in bin and stop moving the particle
@@ -193,7 +203,8 @@ void DriftMover::move(particle::Particle* particle,
particle->timeAlive();
while (
!(changed_position_bin || changed_energy_bin || left_simulation_domain) &&
!(changed_position_bin || changed_energy_bin || changed_mu_bin
|| left_simulation_domain) &&
(leftover_distance > 0.) && !(died_in_bin)) {
old_position = particle->position();
old_velocity = particle->velocity();
@@ -342,6 +353,18 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->changedEnergyBin(
old_kinetic_energy, particle->kineticEnergy_eV());
const double new_mu = cosAngleBetweenVectors(magnetic_field
->value(new_position).cartesianEntries(new_position),
particle->velocity().cartesianEntries(new_position));
changed_mu_bin = particle->specie()->dynamicDensityFieldWithPitchAngle()
->changedPitchAngleBin(old_mu, new_mu);
if(changed_mu_bin) {
DEBUG_LEVEL_3("cos(pitch old): " + std::to_string(old_mu));
DEBUG_LEVEL_3("cos(pitch new): " + std::to_string(new_mu));
}
left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle);
@@ -350,6 +373,8 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, particle->timeInBin());
particle->specie()->dynamicDensityFieldWithPitchAngle()->logMovement(
old_position, old_kinetic_energy, old_mu, particle->timeInBin());
particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position);
}
+62 -19
View File
@@ -109,21 +109,44 @@ void Simulation::start() {
const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
const int total_simulated_events =
parameter_.intValue(json_path({"Simulation", "SimulatedEvents"}), 1);
// const int total_simulated_events =
// parameter_.intValue(json_path({"Simulation", "SimulatedEvents"}), 1);
const int number_timesteps = parameter_.intValue(json_path({"Simulation",
"NumberTimesteps"}), 1);
const int time_resolution_events =
parameter_.intValue(json_path({"Simulation", "TimeResolutionEvents"}),
total_simulated_events);
MpiCommunication::mpiSize());
const int density_events =
parameter_.intValue(json_path({"Simulation", "DensityEventsPerCPU"}), 0);
DEBUG_LEVEL_0("Density events per cpu: " + std::to_string(density_events));
SIM_INFO("Total simulated events: " + std::to_string(total_simulated_events));
// if(total_simulated_events % MpiCommunication::mpiSize() != 0) {
// ERROR("total simulated events are not divisible by the number of mpi procs");
// }
// if(time_resolution_events % MpiCommunication::mpiSize() != 0) {
// ERROR("time resolution events are not divisible by the number of mpi procs");
// }
// SIM_INFO("Total simulated events: " + std::to_string(total_simulated_events));
SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps));
SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride));
const int events_this_cpu = eventsThisCpu(total_simulated_events);
// const int events_this_cpu = eventsThisCpu(total_simulated_events);
const int time_resolution_this_cpu = eventsThisCpu(time_resolution_events);
SIM_INFO("Events per cpu (approx.): " + std::to_string(events_this_cpu));
int leftover_events = events_this_cpu;
if(time_resolution_events % MpiCommunication::mpiSize() != 0) {
if(time_resolution_events % MpiCommunication::mpiSize() <= MpiCommunication::mpiRank() &&
time_resolution_this_cpu % event_stride == 0) {
ERROR("Code will not terminate! The event stride: " + std::to_string(event_stride) +
", the number of CPUs: " + std::to_string(MpiCommunication::mpiSize()) +
" and the number of events per timestep: " + std::to_string(time_resolution_events) +
" create at least one CPU for which the number of CPU syncs for one timestep " +
" differs from the rest of the CPUs.");
}
}
SIM_INFO("Events per cpu (approx.) per timestep: " +
std::to_string(time_resolution_this_cpu));
// int leftover_events = events_this_cpu;
int leftover_events_time_resolution = time_resolution_this_cpu;
const double delta_t = time_resolution_events*injector_->timePassed();
@@ -154,25 +177,34 @@ void Simulation::start() {
int num_cpu_syncs = 0;
bool reset = true;
int timesteps = 0;
queue_.reserve(100);
timer_->increaseTimestep(delta_t);
while (leftover_events > 0) {
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);
SIM_INFO("Leftover events on first cpu: " +
std::to_string(leftover_events));
SIM_INFO("Leftover timesteps this CPU: " + std::to_string(number_timesteps - timesteps));
SIM_INFO("Leftover events this timestep this CPU: " +
std::to_string(leftover_events_time_resolution));
processEvents(events_of_cylcle, density_events, num_cpu_syncs);
DEBUG_LEVEL_1("Leftover events: " + std::to_string(leftover_events));
leftover_events -= events_of_cylcle;
DEBUG_LEVEL_1("Leftover timesteps: " + std::to_string(number_timesteps - timesteps));
DEBUG_LEVEL_1("Leftover events this timestep: " +
std::to_string(leftover_events_time_resolution));
// leftover_events -= events_of_cylcle;
leftover_events_time_resolution -= events_of_cylcle;
// Problem: proc 0: simuliert erst 2 dann 1
// proc 1: simuliert nur 2
// timestep besteht aus (2+1) + 2, aber die jetzt wird es noch zu
// 2 + 2, 1 + 2, in den syncs, das führt dazu, dass jede sync von proc 1
// als timestep gezählt wird, während proc 0 nur jede 2. sync eine timestep ist
reset = !(leftover_events_time_resolution > 0);
SIM_INFO("Cpu sync.");
@@ -208,6 +240,7 @@ void Simulation::start() {
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
@@ -219,6 +252,7 @@ void Simulation::start() {
// pair.second->deletionLogger()->resetDeletionLogger();
}
leftover_events_time_resolution = time_resolution_this_cpu;
timesteps++;
}
}
}
@@ -263,7 +297,8 @@ void Simulation::processEvents(int events, int density_events, int cpu_syncs) {
std::to_string(current_density_event));
//maybe use a different event name?
SimulationTimer::eventStartPoint(std::string("DensityParticleInjection"));
new_particles = determineInjectedDensityParticles(random_.get(), density_events, current_density_event);
new_particles = determineInjectedDensityParticles(random_.get(), density_events,
current_density_event);
SimulationTimer::eventStopPoint(std::string("DensityParticleInjection"));
#if defined debug_level3
for(auto& particle : new_particles) {
@@ -456,19 +491,27 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
// which does not change except after a timestep, but think the rejection method is
// much more time consuming anyways... might optimize in the future
// particle number of the denstiy, i.e. the integral over the density
const double particleNumberDensity =
const double particleNumberFromDensity =
pair.second->densityForDrawing()->particleNumber();
if (particleNumberDensity == 0) {
const double particleNumberFromDensity_ =
pair.second->dynamicDensityFieldWithPitchAngleForDrawing()->particleNumber();
if (particleNumberFromDensity == 0) {
DEBUG_LEVEL_3("No particles in density of species: " + pair.second->name());
continue;
}
if (current == 0) {
DEBUG_LEVEL_0("particle number " + pair.second->name() + ": " + std::to_string(particleNumberDensity));
if (current == 0 || true) {
std::stringstream out;
out << pair.second->name();
out << "difference: ";
out << std::fabs(particleNumberFromDensity_ - particleNumberFromDensity)/particleNumberFromDensity;
DEBUG_LEVEL_0(out.str());
}
injector_->rollNewParticleFromDensityField(random->engine(),
pair.second,
new_particles,
particleNumberDensity/numberParticlesToDraw/MpiCommunication::mpiSize(),
new_particles,
magnetic_field_,
particleNumberFromDensity/numberParticlesToDraw/MpiCommunication::mpiSize(),
injection_time);
}
return new_particles;
+15 -4
View File
@@ -41,9 +41,10 @@ TrackedSpecie::TrackedSpecie(
std::shared_ptr<Reflector> reflector,
std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity,
// std::shared_ptr<DynamicDensityField> last_sync_density_field,
std::shared_ptr<DynamicDensityField> density_for_drawing)
std::shared_ptr<DriftVelocity> drift_velocity,
std::shared_ptr<DynamicDensityField> density_for_drawing,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_field_pitch_angle,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_mu_for_drawing)
: Specie(type, name, mass_kg, charge_C),
mover_(mover),
terminator_(terminator),
@@ -53,7 +54,9 @@ 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),
density_field_pitch_angle_(density_field_pitch_angle),
density_with_pitch_angle_for_drawing(density_mu_for_drawing) {}
DensityField* TrackedSpecie::densityField() {
return density_field_.get();
@@ -74,6 +77,14 @@ DynamicDensityField* TrackedSpecie::densityForDrawing() {
return density_for_drawing_.get();
}
DynamicDensityFieldWithPitchAngle* TrackedSpecie::dynamicDensityFieldWithPitchAngle() {
return density_field_pitch_angle_.get();
}
DynamicDensityFieldWithPitchAngle* TrackedSpecie::dynamicDensityFieldWithPitchAngleForDrawing() {
return density_with_pitch_angle_for_drawing.get();
}
Mover* TrackedSpecie::mover() {
return mover_.get();
}