Author SHA1 Message Date
csendlinger 5c39fb1745 Minor adjustments 2025-10-30 09:43:11 +01:00
csendlinger 5094a1da35 Bug fix in transformation of Cylinder vector to cartesian one 2025-10-29 16:29:03 +01:00
csendlinger 880de9f1ba analysis Script for plotting charge against time 2025-10-22 09:15:36 +02:00
csendlinger f57895bcef Changed Allreduce to Reduce for CurrentCollector
and DeletionLogger; removed sync_ field copies
2025-10-21 14:26:45 +02:00
csendlinger f5ff3d2f7c Removed cpu syncs inbetween a timestep; Changed Density field accordingly 2025-10-21 09:09:50 +02:00
csendlinger 753cbe31f5 Corrections to drawing the velocity of a tracked
species (dynamic density field of previous timestep);
some optimization changes
2025-10-15 14:46:27 +02:00
csendlinger 31c2b230a9 Removed drawing infrastructure 2025-10-13 13:19:23 +02:00
28 changed files with 493 additions and 920 deletions
+113
View File
@@ -0,0 +1,113 @@
import numpy as np
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import h5py
import argparse
import glob
import re
import os
def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow=False):
times = []
total_charges = []
for file in files:
with h5py.File(file, 'r') as cfile:
total_charge = 0
time = 0
for key in cfile.keys():
if(key == "PoissonSolver" or key == "RestartInfo" or key == 'NumberProcesses'):
continue
if (not considered_keys[0] == 'All') and (not key in considered_keys):
continue
charge = cfile[f'{key}/Charge'][()]
cfile_speciesDensity = cfile[key]['DensityField']
# binVolumes = cfile_speciesDensity['BinVolumes'][()]
cfile_simData = cfile_speciesDensity['SimulationData']
for time_key in cfile_simData.keys():
time = cfile_simData[time_key]['PhysicalTime'][()]
density = cfile_simData[time_key]['TimeInBin'][()]
if not exclude_underflow:
total_charge = np.sum(density)*charge
else:
total_charge = np.array([np.sum(density[:,:,:,:,1:-1])])*charge
# print(total_charge)
try:
index = times.index(time)
total_charges[index] += total_charge
except:
times.append(time)
total_charges.append(total_charge)
times = np.array(times)[:,0]
# print(total_charge)
total_charges = np.array(total_charges)[:,0]
sorting_mask = np.argsort(times)
times = times[sorting_mask]
total_charges = total_charges[sorting_mask]
return times, total_charges
def getFiles(dir:str, base_name:str, pattern:str) :
if dir[-1] == '/':
pathname = dir + base_name
else:
pathname = dir + '/' + base_name
# print(glob.glob(pathname + "*.h5"))
return [file for file in glob.glob(pathname + "*.h5") if re.match(rf"{pathname}{pattern}+\.h5", str(file))]
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Program to create a plot of the charge against time from the output of KARL")
parser.add_argument("dir", type = str, help="directory where the files are stored in")
parser.add_argument("basename", type = str, help = 'identifying pattern of the files (i.e. basename[0-9]*\\.h5])')
parser.add_argument("--pattern", type = str, nargs = '?', help = 'Regular expression pattern, that specifies the naming of the files (by default [0-9]*). Gets added to dir+basename+pattern+".h5".', default = '[0-9]*')
parser.add_argument("species", action='extend', nargs='+', help = 'Names of the Species in the KARL output or \'All\' if all species should be summed. If name does not exist it will be ignored.')
args = parser.parse_args()
# print(args.dir, args.basename, args.species)
files = getFiles(args.dir, args.basename, args.pattern)
print(files)
if(files == []):
print(f"No files found in {args.dir}, which match '{args.basename}[0-9]*\\.h5'")
exit(1)
times, charges = get_time_and_total_charge_(files, args.species)
legstr = ''
for val in args.species:
legstr += val + " + "
legstr = legstr[:-3]
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(10,6))
plt.plot(times, charges, marker = 'x', label = legstr)
plt.ylabel('charge (C)')
plt.xlabel('time (s)')
plt.legend()
plt.grid()
plt.tight_layout()
outname = args.dir
if not outname[-1] == '/':
outname += '/'
outname += "plots/"
os.makedirs(outname, exist_ok=True)
outname += args.basename + "_chargeAgainstTime_species-"
for value in args.species:
outname += value
outname += '.pdf'
# print(outname)
plt.savefig(outname, format='pdf', bbox_inches = 'tight')
# plt.show()
-2
View File
@@ -24,7 +24,6 @@ struct TrackedSpeciesBuilderInfo {
std::shared_ptr<VelocityDistribution> velocity_distribution; std::shared_ptr<VelocityDistribution> velocity_distribution;
std::shared_ptr<DriftVelocity> drift_velocity; std::shared_ptr<DriftVelocity> drift_velocity;
std::shared_ptr<DynamicDensityField> last_sync_density_field; std::shared_ptr<DynamicDensityField> last_sync_density_field;
std::shared_ptr<DynamicDensityField> density_drawing_field;
double mass_kg; double mass_kg;
double charge_C; double charge_C;
@@ -110,7 +109,6 @@ class SpeciesBuilder {
void fillTerminator(Parameter& parameter); void fillTerminator(Parameter& parameter);
void fillReflector(Parameter& parameter); void fillReflector(Parameter& parameter);
void fillTrackedDensity(Parameter& parameter); void fillTrackedDensity(Parameter& parameter);
void fillDensityDrawingType(Parameter& parameter);
void initTimer(); void initTimer();
void buildSpecies(); void buildSpecies();
+1 -2
View File
@@ -57,8 +57,7 @@ class PoissonSolver {
int num_cycles, int num_cycles,
bool do_solver); bool do_solver);
void solvePotential(const blitz::Array<double, 3> charge_density, void solvePotential(const blitz::Array<double, 3> charge_density);
const bool solve);
blitz::Array<double, 3> potential(); blitz::Array<double, 3> potential();
std::shared_ptr<VectorField> staticElectricField(); std::shared_ptr<VectorField> staticElectricField();
const CylinderBinning* densityBinning(); const CylinderBinning* densityBinning();
+12 -6
View File
@@ -21,11 +21,9 @@ class CpuSynchronizer {
void synchronize( void synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species, bool reset); tracked_species);
void synchronize(DynamicDensityField* field, void synchronize(DynamicDensityField* field);
DynamicDensityField* density_for_drawing,
bool reset);
void synchronize(CurrentCollector* collector); void synchronize(CurrentCollector* collector);
void synchronize(DeletionLogger* logger); void synchronize(DeletionLogger* logger);
void synchronize(Timer* timer, Timer* last_sync_timer); void synchronize(Timer* timer, Timer* last_sync_timer);
@@ -36,8 +34,6 @@ class CpuSynchronizer {
*/ */
void sumToAll(blitz::Array<double, 4>& array, void sumToAll(blitz::Array<double, 4>& array,
blitz::Array<double, 4>& last_sync_array); blitz::Array<double, 4>& last_sync_array);
void sumToAll(blitz::Array<double, 5>& array,
blitz::Array<double, 5>& last_sync_array);
void sumToAll(blitz::Array<double, 3>& array, void sumToAll(blitz::Array<double, 3>& array,
blitz::Array<double, 3>& last_sync_array); blitz::Array<double, 3>& last_sync_array);
void sumToAll(blitz::Array<long int, 4>& array, void sumToAll(blitz::Array<long int, 4>& array,
@@ -46,6 +42,16 @@ class CpuSynchronizer {
blitz::Array<long int, 5>& last_sync_array); blitz::Array<long int, 5>& last_sync_array);
void sumToAll(double& value, double& last_sync_value); void sumToAll(double& value, double& last_sync_value);
void sumToAll(long int& value, long int& last_sync_value); void sumToAll(long int& value, long int& last_sync_value);
// array has to be the delta of the timestep
void sumToAll(blitz::Array<double, 5>& array);
// collect data to rank 0 functions
void sumToRoot(blitz::Array<double, 3>& array);
void sumToRoot(long int& value);
void sumToRoot(double& value);
const int root = 0;
}; };
#endif /* CPU_SYNCHRONIZER_H */ #endif /* CPU_SYNCHRONIZER_H */
+6 -6
View File
@@ -70,14 +70,14 @@ class CurrentCollector {
blitz::Array<double, 3> r_negative_crossings; blitz::Array<double, 3> r_negative_crossings;
blitz::Array<double, 3> r_positive_crossings; blitz::Array<double, 3> r_positive_crossings;
blitz::Array<double, 3> sync_z_negative_crossings; // blitz::Array<double, 3> sync_z_negative_crossings;
blitz::Array<double, 3> sync_z_positive_crossings; // blitz::Array<double, 3> sync_z_positive_crossings;
blitz::Array<double, 3> sync_phi_negative_crossings; // blitz::Array<double, 3> sync_phi_negative_crossings;
blitz::Array<double, 3> sync_phi_positive_crossings; // blitz::Array<double, 3> sync_phi_positive_crossings;
blitz::Array<double, 3> sync_r_negative_crossings; // blitz::Array<double, 3> sync_r_negative_crossings;
blitz::Array<double, 3> sync_r_positive_crossings; // blitz::Array<double, 3> sync_r_positive_crossings;
blitz::Array<double, 3> collector_areas_r; blitz::Array<double, 3> collector_areas_r;
blitz::Array<double, 3> collector_areas_phi; blitz::Array<double, 3> collector_areas_phi;
+2 -16
View File
@@ -42,15 +42,6 @@ class DynamicDensityField : public DensityField {
double pitch_angle, double pitch_angle,
double weight); double weight);
// void logDeletion(const Coordinate& position,
// double energy_eV,
// double pitch_angle);
// return the particle number stored in the density of this object
double particleNumber();
// return the particle number at the given index
double particleNumber(blitz::TinyVector<int, 5> index);
// returns true if the old pitch angle and the new pitch angle are in different bins // returns true if the old pitch angle and the new pitch angle are in different bins
// of the pitch angle binning // of the pitch angle binning
bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const; bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const;
@@ -58,7 +49,6 @@ class DynamicDensityField : public DensityField {
blitz::Array<double, 3> densityArray(); blitz::Array<double, 3> densityArray();
blitz::Array<double, 4> spectrumArray(); blitz::Array<double, 4> spectrumArray();
blitz::Array<double, 5> timeInBinArray() const; blitz::Array<double, 5> timeInBinArray() const;
// blitz::Array<long int, 5> deletedParticlesArray() const;
blitz::Array<double, 3> binVolumeArray() const; blitz::Array<double, 3> binVolumeArray() const;
// return an array of the density values at the Coordinate position (only energy // return an array of the density values at the Coordinate position (only energy
@@ -84,21 +74,17 @@ class DynamicDensityField : public DensityField {
void restartTimer(double time, double delta_t); void restartTimer(double time, double delta_t);
void restartTimeInBin(blitz::Array<double, 5> time_in_bin); void restartTimeInBin(blitz::Array<double, 5> time_in_bin);
// void restartDeletedParticlesArray(blitz::Array<long int, 5> deleted_particles);
private:
void recalculateDensityArray(); void recalculateDensityArray();
private:
// use ordering r, phi, z, pitch_angle, E // use ordering r, phi, z, pitch_angle, E
// time in bin now contains the physical particle number per bin // time in bin now contains the physical particle number per bin
// (not renamed, since that would require many, many changes due to // (not renamed, since that would require many, many changes due to
// renaming of the functions) // renaming of the functions)
blitz::Array<double, 5> time_in_bin_s_; blitz::Array<double, 5> time_in_bin_s_;
// blitz::Array<long int, 5> deleted_particles_;
blitz::Array<double, 5> sync_time_in_bin_s_; blitz::Array<double, 5> sync_time_in_bin_s_;
// blitz::Array<long int, 5> sync_deleted_particles_;
blitz::Array<double, 4> density_per_m3_; blitz::Array<double, 4> density_per_m3_;
blitz::Array<double, 3> bin_volume_m3_; blitz::Array<double, 3> bin_volume_m3_;
@@ -37,38 +37,4 @@ class EventPositionDistribution {
std::uniform_real_distribution<double> density_values; 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);
// draw a position uniformly distributed within the bin of the given index
// (note that the r-dependence of the particle number in a uniform density distribution
// is not incorporated)
CylinderCoordinate drawPosition(std::mt19937* engine, int r_idx, int phi_idx,
int z_idx);
// // 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;
std::uniform_real_distribution<double> std_unifrm;
};
#endif /* EVENT_POSITION_DISTRIBUTION_H */ #endif /* EVENT_POSITION_DISTRIBUTION_H */
-13
View File
@@ -49,19 +49,6 @@ class Injector {
// a single process // a single process
void setWeights(const double physical_number, const int numerical_number); void setWeights(const double physical_number, const int numerical_number);
// draw new particles from the DynamicDensityField of the provided specie,
// the new particles are then appened to the vector 'queue'
// the magnetic field is necessary for the determination of the direction of the
// injected particles
// the weight_factor scales the time a particle contributes to a certain bin
// 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,
const double weight_factor);
void initInjectionTimeDistribution(double delta_t); void initInjectionTimeDistribution(double delta_t);
double timePassed() const; double timePassed() const;
+2 -2
View File
@@ -40,10 +40,10 @@ class DeletionLogger {
private: private:
std::map<DeletionType, long int> num_deletions; std::map<DeletionType, long int> num_deletions;
std::map<DeletionType, long int> sync_num_deletions; // std::map<DeletionType, long int> sync_num_deletions;
std::map<PhysicalDeletionType, double> num_phys_deletions; std::map<PhysicalDeletionType, double> num_phys_deletions;
std::map<PhysicalDeletionType, double> sync_num_phys_deletions; // std::map<PhysicalDeletionType, double> sync_num_phys_deletions;
}; };
+1 -7
View File
@@ -36,16 +36,10 @@ class Simulation {
void finalize(); void finalize();
void processEvents(int events); void processEvents(int events);
void processDensityEvents(int particles_per_bin, const double weight_factor); void processDensityEvents();
void processUntilTermination(particle::Particle& particle); void processUntilTermination(particle::Particle& particle);
private: private:
std::vector<particle::Particle> determineInjectedDensityParticles(
RandomNumbers* random,
const double weight_factor,
const int current,
std::map<std::string, double>& particleNumbers,
bool& all_bins_done);
// draw the individual collision times of the possible interactions and return the // draw the individual collision times of the possible interactions and return the
// minimum of them. Also sets the "nextInteractionIndex" in the particle to the // minimum of them. Also sets the "nextInteractionIndex" in the particle to the
+2 -23
View File
@@ -59,14 +59,12 @@ class TrackedSpecie : public Specie {
std::string name, std::string name,
double mass_kg, double mass_kg,
double charge_C, double charge_C,
bool explicitly_stored,
std::shared_ptr<Mover> mover, std::shared_ptr<Mover> mover,
std::shared_ptr<Terminator> terminator, std::shared_ptr<Terminator> terminator,
std::shared_ptr<Reflector> reflector, std::shared_ptr<Reflector> reflector,
std::shared_ptr<DynamicDensityField> density_field, std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution, std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity, std::shared_ptr<DriftVelocity> drift_velocity);
std::shared_ptr<DynamicDensityField> density_for_drawing);
DensityField* densityField(); DensityField* densityField();
VelocityDistribution* velocityDistribution(); VelocityDistribution* velocityDistribution();
@@ -80,27 +78,17 @@ class TrackedSpecie : public Specie {
DeletionLogger* deletionLogger(); DeletionLogger* deletionLogger();
void deletionLogger(std::shared_ptr<DeletionLogger> new_logger); void deletionLogger(std::shared_ptr<DeletionLogger> new_logger);
DynamicDensityField* densityForDrawing();
CurrentCollector* currentCollector(); CurrentCollector* currentCollector();
void currentCollector(std::shared_ptr<CurrentCollector> new_collector); void currentCollector(std::shared_ptr<CurrentCollector> new_collector);
std::vector<std::shared_ptr<interaction::Interaction>> interactions(); std::vector<std::shared_ptr<interaction::Interaction>> interactions();
void addInteraction(std::shared_ptr<interaction::Interaction> interaction); 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 // getter for the raw pointer to the VelocityDistributionFromDensityField object
VelocityDistributionFromDensityField* velocityDistributionFromDensityField(); VelocityDistributionFromDensityField* velocityDistributionFromDensityField();
// getter for the raw pointer to the RandomIndex object
RandomIndex* randomIndex();
bool explicitlyStored();
private: private:
std::shared_ptr<DynamicDensityField> density_field_; std::shared_ptr<DynamicDensityField> density_field_;
std::shared_ptr<VelocityDistribution> velocity_distribution_;
std::shared_ptr<DriftVelocity> drift_velocity_; std::shared_ptr<DriftVelocity> drift_velocity_;
std::shared_ptr<Mover> mover_; std::shared_ptr<Mover> mover_;
@@ -111,18 +99,9 @@ class TrackedSpecie : public Specie {
std::shared_ptr<CurrentCollector> current_collector_; std::shared_ptr<CurrentCollector> current_collector_;
std::vector<std::shared_ptr<interaction::Interaction>> interactions_; std::vector<std::shared_ptr<interaction::Interaction>> interactions_;
std::shared_ptr<DynamicDensityField> density_for_drawing_; // necessary for interactions between TrackedSpecies
std::shared_ptr<PositionDistributionFromDensity>
position_distribution_from_density_;
std::shared_ptr<VelocityDistributionFromDensityField> std::shared_ptr<VelocityDistributionFromDensityField>
velocity_distribution_from_density_; velocity_distribution_from_density_;
std::shared_ptr<RandomIndex> random_index_;
// should work if it changes from true -> false (after a restart)
// however, it should not work in the opposite case (in which the
// old density would be lost)
const bool explicitly_stored_;
}; };
class BackgroundSpecie : public Specie { class BackgroundSpecie : public Specie {
+3 -14
View File
@@ -52,28 +52,17 @@ class VelocityDistributionFromDensityField : public VelocityDistribution {
// use the given magnetic field at the provided position to determine the // use the given magnetic field at the provided position to determine the
// direction of velocity from the pitch angle // direction of velocity from the pitch angle
// the direction of the perpendicular part of the velocity vector is drawn isotropically // the direction of the perpendicular part of the velocity vector is drawn isotropically
CartesianVector rollVelocity( CartesianVector rollVelocity(const Coordinate& position, std::mt19937* engine,
const Coordinate& position, std::mt19937* engine,
std::shared_ptr<MagneticField> magnetic_field); std::shared_ptr<MagneticField> magnetic_field);
// return a velocity vector drawn uniformly in the bin specifed by index
CartesianVector drawVelocity(const blitz::TinyVector<int, 5> index,
std::mt19937* engine);
CartesianVector drawVelocity(const blitz::TinyVector<int, 5> index,
std::mt19937* engine,
const Coordinate& position,
std::shared_ptr<MagneticField> magnetic_field);
private: private:
// mass of the species of which the density field is a part of // mass of the species of which the density field is a part of
const double mass_kg_; const double mass_kg_;
double alpha_lower_limit;
double alpha_upper_limit;
std::shared_ptr<DynamicDensityField> density_field_; std::shared_ptr<DynamicDensityField> density_field_;
blitz::Array<double, 1> energy_values; // blitz::Array<double, 1> energy_values;
blitz::Array<double, 1> mu_values; // blitz::Array<double, 1> mu_values;
std::vector<double> energyBinBorders_; std::vector<double> energyBinBorders_;
std::vector<double> pitchAngleBinBorders_; std::vector<double> pitchAngleBinBorders_;
+2 -1
View File
@@ -57,7 +57,7 @@ void Restart::restart(
for(const auto& pair: species) { for(const auto& pair: species) {
std::string path = pair.second->name() + "/DensityField/SimulationData/" + std::string path = pair.second->name() + "/DensityField/SimulationData/" +
restart_identifier_; restart_identifier_;
restartDrawingDensityField(pair.second->densityForDrawing(), path); restartDrawingDensityField(pair.second->dynamicDensityField(), path);
// pair.second->positionDistributionFromDensity()->setMaximumDensity(); // pair.second->positionDistributionFromDensity()->setMaximumDensity();
} }
@@ -141,6 +141,7 @@ void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string
#endif #endif
blitz::Array<double, 5> time_in_bin = reader_.readD5Double(path_to_data); blitz::Array<double, 5> time_in_bin = reader_.readD5Double(path_to_data);
field->restartTimeInBin(time_in_bin); field->restartTimeInBin(time_in_bin);
field->recalculateDensityArray();
} }
// // restart deleted particles // // restart deleted particles
+2
View File
@@ -315,6 +315,8 @@ void SimulationOutput::writeSpectrum(DynamicDensityField* density_field,
void SimulationOutput::writeDensity(DynamicDensityField* density_field, void SimulationOutput::writeDensity(DynamicDensityField* density_field,
std::string path) { std::string path) {
// precaution, shouldn't be necessary due to calculation after cpu sync
// density_field->recalculateDensityArray();
writer.write(density_field->densityArray(), path + "/Density"); writer.write(density_field->densityArray(), path + "/Density");
} }
+1 -22
View File
@@ -82,7 +82,6 @@ SpeciesBuilder::SpeciesBuilder(Parameter& parameter) {
fillTerminator(parameter); fillTerminator(parameter);
fillReflector(parameter); fillReflector(parameter);
fillTrackedDensity(parameter); fillTrackedDensity(parameter);
fillDensityDrawingType(parameter);
buildSpecies(); buildSpecies();
fillInteractions(parameter); fillInteractions(parameter);
@@ -297,20 +296,6 @@ void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
json_path_append(b.second.path_in_json, json_path_append(b.second.path_in_json,
{"DensityField", "DynamicDensityField"}), {"DensityField", "DynamicDensityField"}),
timer_); timer_);
// not the optimal solution! (has to be optimized)
b.second.density_drawing_field = buildDynamicDensityField(
parameter,
json_path_append(b.second.path_in_json,
{"DensityField", "DynamicDensityField"}),
timer_);
}
}
void SpeciesBuilder::fillDensityDrawingType(Parameter& parameter) {
for(auto& b : tracked_species_info) {
b.second.explicitly_stored = parameter.boolValue(
json_path_append(b.second.path_in_json, {"StoreInQueue"}), false);
} }
} }
@@ -327,18 +312,12 @@ void SpeciesBuilder::buildSpecies() {
} }
for (auto& b : tracked_species_info) { for (auto& b : tracked_species_info) {
#ifdef debug
std::stringstream out;
out << b.second.name << ": stored in queue? " << (b.second.explicitly_stored ? "true": "false");
DEBUG_LEVEL_1(out.str());
#endif
tracked_species[b.first] = tracked_species[b.first] =
std::shared_ptr<species::TrackedSpecie>(new species::TrackedSpecie( std::shared_ptr<species::TrackedSpecie>(new species::TrackedSpecie(
b.second.type, b.second.name, b.second.mass_kg, b.second.charge_C, b.second.type, b.second.name, b.second.mass_kg, b.second.charge_C,
b.second.explicitly_stored,
b.second.mover, b.second.terminator, b.second.reflector, b.second.mover, b.second.terminator, b.second.reflector,
b.second.density_field, b.second.velocity_distribution, b.second.density_field, b.second.velocity_distribution,
b.second.drift_velocity, b.second.density_drawing_field)); b.second.drift_velocity));
} }
} }
+27 -14
View File
@@ -169,20 +169,26 @@ double Recombination::macroscopicCrossSection(const Coordinate& position,
double Recombination::drawCollisionTime(particle::Particle& particle, double Recombination::drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator) { RandomNumbers* generator) {
CartesianVector particle_velocity = particle.velocity(); CartesianVector particle_velocity = particle.velocity();
// const double density = target_->densityField()->density(particle.cylinderPosition());
// Use the density for drawing field, since it contains the density of the earlier
// timestep
const double density = recombination_target_->dynamicDensityField()
->density(particle.cylinderPosition());
// recombination_target_->densityForDrawing()->recalculateDensityArray();
// if(density != recombination_target_->densityForDrawing()
// ->density(particle.cylinderPosition())) {
// ERROR("density changes after recalculation of density array!");
// }
// density effectively 0
if(density <= SimConstants::compare_epsilon) {
return std::numeric_limits<double>::max();
}
// Assumes that B || z, which is obviously not necessarily the case !!! // Assumes that B || z, which is obviously not necessarily the case !!!
target_velocity_ = recombination_target_->velocityDistributionFromDensityField() target_velocity_ = recombination_target_->velocityDistributionFromDensityField()
->rollVelocity(particle.cylinderPosition(), generator->engine()); ->rollVelocity(particle.cylinderPosition(), generator->engine());
// // if no drift velocity is present, then assume target at rest otherwise
// // use the drift velocity
if(target_->driftVelocity()) {
// auto tmp = target_->driftVelocity()->driftVelocity(particle.position());
target_velocity_.add(target_->driftVelocity()->driftVelocity(
particle.cartesianPosition(), particle.cylinderPosition()),
particle.cartesianPosition());
}
// for testing purposes // for testing purposes
// target_velocity_ = CartesianVector(blitz::TinyVector<double, 3>(0.,0.,0.)); // target_velocity_ = CartesianVector(blitz::TinyVector<double, 3>(0.,0.,0.));
@@ -212,11 +218,18 @@ double Recombination::drawCollisionTime(particle::Particle& particle,
const double crosssection = microscopicCrossSection(energy_eV, const double crosssection = microscopicCrossSection(energy_eV,
particle.cylinderPosition()); particle.cylinderPosition());
// const double density = target_->densityField()->density(particle.cylinderPosition());
// Use the density for drawing field, since it contains the density of the earlier #if defined(debug)
// timestep if(density > 0 && std::isnan(crosssection)) {
const double density = recombination_target_->densityForDrawing() std::stringstream msg;
->density(particle.cylinderPosition()); msg << particle.specie()->name() << particle.cartesianPosition().cartesianEntries();
msg << " " << recombination_target_->dynamicDensityField()->positionBinning()->bin(particle.cylinderPosition().cylinderEntries());
msg << ": Recombination: density is not nan but the cross section is ";
msg << density << ", " << crosssection;
msg << recombination_target_->dynamicDensityField()->sliceSpectrumArray(particle.cylinderPosition());
ERROR(msg.str());
}
#endif
const double random_number = generator->rollUniform(0.,1.); const double random_number = generator->rollUniform(0.,1.);
if (random_number == 0) { if (random_number == 0) {
+3 -3
View File
@@ -77,12 +77,12 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
blitz::Range(density_binning.binIndexMin()(2), blitz::Range(density_binning.binIndexMin()(2),
density_binning.binIndexMax()(2))); density_binning.binIndexMax()(2)));
zero_chargedensity = 0.; zero_chargedensity = 0.;
solvePotential(zero_chargedensity, true); solvePotential(zero_chargedensity);
} }
void PoissonSolver::solvePotential( void PoissonSolver::solvePotential(
const blitz::Array<double, 3> charge_density, const bool solve) { const blitz::Array<double, 3> charge_density) {
if (!(do_solver_) || !(solve)) { if (!(do_solver_)) {
return; return;
} }
#ifdef debug_level3 #ifdef debug_level3
+3 -3
View File
@@ -132,7 +132,7 @@ void CylinderCoordinate::add(const Coordinate& coordinate) {
const CartesianCoordinate c_cart(new_cart_position); const CartesianCoordinate c_cart(new_cart_position);
const CylinderCoordinate c_cyl(c_cart); const CylinderCoordinate c_cyl(c_cart);
cylinder_position = c_cyl.cylinderEntries(); cylinder_position = c_cyl.cylinderEntries();
limitPhi(); // limitPhi();
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@@ -164,8 +164,8 @@ blitz::TinyVector<double, 3> CylinderVector::cartesianEntries(
cosphi * cylinder_vector(0) - cosphi * cylinder_vector(0) -
sinphi * cylinder_vector(1); sinphi * cylinder_vector(1);
const double A_y = const double A_y =
cosphi * cylinder_vector(0) + sinphi * cylinder_vector(0) +
sinphi * cylinder_vector(1); cosphi * cylinder_vector(1);
const double A_z = cylinder_vector(2); const double A_z = cylinder_vector(2);
return blitz::TinyVector<double, 3>(A_x, A_y, A_z); return blitz::TinyVector<double, 3>(A_x, A_y, A_z);
} }
+73 -52
View File
@@ -17,14 +17,10 @@ void CpuSynchronizer::sumToAll(blitz::Array<double, 4>& array,
last_sync_array += delta; last_sync_array += delta;
} }
void CpuSynchronizer::sumToAll(blitz::Array<double, 5>& array, void CpuSynchronizer::sumToAll(blitz::Array<double, 5>& array) {
blitz::Array<double, 5>& last_sync_array) {
int size = array.size(); int size = array.size();
blitz::Array<double, 5> delta(array.extent()); MPI_Allreduce(MPI_IN_PLACE, array.data(), size, MPI_DOUBLE,
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_DOUBLE,
MPI_SUM, MPI_COMM_WORLD); MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
} }
void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array, void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
@@ -73,6 +69,32 @@ void CpuSynchronizer::sumToAll(long int& value, long int& last_sync_value) {
last_sync_value += delta; last_sync_value += delta;
} }
void CpuSynchronizer::sumToRoot(blitz::Array<double, 3>& array) {
int size = array.size();
if(MpiCommunication::mpi_rank == root)
MPI_Reduce(MPI_IN_PLACE, array.data(), size, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
else
MPI_Reduce(array.data(), nullptr, size, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
}
void CpuSynchronizer::sumToRoot(long int& value) {
int size = 1;
if(MpiCommunication::mpi_rank == root) {
MPI_Reduce(MPI_IN_PLACE, &value, size, MPI_LONG, MPI_SUM, root, MPI_COMM_WORLD);
} else {
MPI_Reduce(&value, nullptr, size, MPI_LONG, MPI_SUM, root, MPI_COMM_WORLD);
}
}
void CpuSynchronizer::sumToRoot(double& value) {
int size = 1;
if(MpiCommunication::mpi_rank == root) {
MPI_Reduce(MPI_IN_PLACE, &value, size, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
} else {
MPI_Reduce(&value, nullptr, size, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
}
}
void CpuSynchronizer::synchronize(Timer* timer, Timer* last_sync_timer) { void CpuSynchronizer::synchronize(Timer* timer, Timer* last_sync_timer) {
if(timer == last_sync_timer) { if(timer == last_sync_timer) {
ERROR("Synchronization of timers cannot work, point to same object."); ERROR("Synchronization of timers cannot work, point to same object.");
@@ -84,53 +106,53 @@ void CpuSynchronizer::synchronize(Timer* timer, Timer* last_sync_timer) {
last_sync_timer->setTime(last_sync_time_s); last_sync_timer->setTime(last_sync_time_s);
} }
void CpuSynchronizer::synchronize(DynamicDensityField* field, // synchronize density field across cpus and set the
DynamicDensityField* density_for_drawing, // array storing the previous timestep
bool reset) { void CpuSynchronizer::synchronize(DynamicDensityField* field) {
if (field) { if (field) {
sumToAll(field->time_in_bin_s_, field->sync_time_in_bin_s_); sumToAll(field->sync_time_in_bin_s_);
field->time_in_bin_s_ = field->sync_time_in_bin_s_; field->time_in_bin_s_ = field->sync_time_in_bin_s_;
field->recalculateDensityArray();
// 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_;
}
} }
} }
void CpuSynchronizer::synchronize(CurrentCollector* collector) { void CpuSynchronizer::synchronize(CurrentCollector* collector) {
if (collector) { if (collector) {
sumToAll(collector->z_negative_crossings, // sumToAll(collector->z_negative_crossings,
collector->sync_z_negative_crossings); // collector->sync_z_negative_crossings);
collector->z_negative_crossings = // collector->z_negative_crossings =
collector->sync_z_negative_crossings; // collector->sync_z_negative_crossings;
sumToRoot(collector->z_negative_crossings);
sumToAll(collector->z_positive_crossings, // sumToAll(collector->z_positive_crossings,
collector->sync_z_positive_crossings); // collector->sync_z_positive_crossings);
collector->z_positive_crossings = // collector->z_positive_crossings =
collector->sync_z_positive_crossings; // collector->sync_z_positive_crossings;
sumToRoot(collector->z_positive_crossings);
sumToAll(collector->phi_negative_crossings, // sumToAll(collector->phi_negative_crossings,
collector->sync_phi_negative_crossings); // collector->sync_phi_negative_crossings);
collector->phi_negative_crossings = // collector->phi_negative_crossings =
collector->sync_phi_negative_crossings; // collector->sync_phi_negative_crossings;
sumToRoot(collector->phi_negative_crossings);
sumToAll(collector->phi_positive_crossings, // sumToAll(collector->phi_positive_crossings,
collector->sync_phi_positive_crossings); // collector->sync_phi_positive_crossings);
collector->phi_positive_crossings = // collector->phi_positive_crossings =
collector->sync_phi_positive_crossings; // collector->sync_phi_positive_crossings;
sumToRoot(collector->phi_positive_crossings);
sumToAll(collector->r_negative_crossings, // sumToAll(collector->r_negative_crossings,
collector->sync_r_negative_crossings); // collector->sync_r_negative_crossings);
collector->r_negative_crossings = // collector->r_negative_crossings =
collector->sync_r_negative_crossings; // collector->sync_r_negative_crossings;
sumToRoot(collector->r_negative_crossings);
sumToAll(collector->r_positive_crossings, // sumToAll(collector->r_positive_crossings,
collector->sync_r_positive_crossings); // collector->sync_r_positive_crossings);
collector->r_positive_crossings = // collector->r_positive_crossings =
collector->sync_r_positive_crossings; // collector->sync_r_positive_crossings;
sumToRoot(collector->r_positive_crossings);
} }
} }
@@ -138,34 +160,33 @@ void CpuSynchronizer::synchronize(DeletionLogger* logger) {
if (logger) { if (logger) {
for (auto& pair : logger->num_deletions) { for (auto& pair : logger->num_deletions) {
long int num_deletion = pair.second; long int num_deletion = pair.second;
long int last_sync_num_deletion = logger->sync_num_deletions[pair.first]; // long int last_sync_num_deletion = logger->sync_num_deletions[pair.first];
sumToAll(num_deletion, last_sync_num_deletion); sumToRoot(num_deletion);//, last_sync_num_deletion
// last_sync_num_deletion now contains the total number of deletions // last_sync_num_deletion now contains the total number of deletions
// across all cpus -> update the values in the objects // across all cpus -> update the values in the objects
pair.second = last_sync_num_deletion; pair.second = num_deletion; //last_sync_num_deletion;
logger->sync_num_deletions[pair.first] = last_sync_num_deletion; // logger->sync_num_deletions[pair.first] = last_sync_num_deletion;
} }
for (auto& pair : logger->num_phys_deletions) { for (auto& pair : logger->num_phys_deletions) {
double num_deletion = pair.second; double num_deletion = pair.second;
double last_sync_num_deletion = logger->sync_num_phys_deletions[pair.first]; // double last_sync_num_deletion = logger->sync_num_phys_deletions[pair.first];
sumToAll(num_deletion, last_sync_num_deletion); sumToRoot(num_deletion);//, last_sync_num_deletion);
// last_sync_num_deletion now contains the total number of deletions // last_sync_num_deletion now contains the total number of deletions
// across all cpus -> update the values in the objects // across all cpus -> update the values in the objects
pair.second = last_sync_num_deletion; pair.second = num_deletion; //last_sync_num_deletion;
logger->sync_num_phys_deletions[pair.first] = last_sync_num_deletion; // logger->sync_num_phys_deletions[pair.first] = last_sync_num_deletion;
} }
} }
} }
void CpuSynchronizer::synchronize( void CpuSynchronizer::synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species, bool reset) { tracked_species) {
MPI_Barrier(MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD);
auto it = tracked_species.begin(); auto it = tracked_species.begin();
for (auto& pair : tracked_species) { for (auto& pair : tracked_species) {
synchronize(pair.second->dynamicDensityField(), synchronize(pair.second->dynamicDensityField());
pair.second->densityForDrawing(), reset);
synchronize(pair.second->currentCollector()); synchronize(pair.second->currentCollector());
synchronize(pair.second->deletionLogger()); synchronize(pair.second->deletionLogger());
} }
+14 -13
View File
@@ -12,13 +12,14 @@ CurrentCollector::CurrentCollector(const CylinderBinning& position_binning,
collector_areas_r(createAreaRadial(position_binning)), collector_areas_r(createAreaRadial(position_binning)),
phi_negative_crossings(createCrossingsAzimuthal(position_binning)), phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
phi_positive_crossings(createCrossingsAzimuthal(position_binning)), phi_positive_crossings(createCrossingsAzimuthal(position_binning)),
collector_areas_phi(createAreaAzimuthal(position_binning)), collector_areas_phi(createAreaAzimuthal(position_binning))//,
sync_z_negative_crossings(createCrossingsLongitudinal(position_binning)), // sync_z_negative_crossings(createCrossingsLongitudinal(position_binning)),
sync_z_positive_crossings(createCrossingsLongitudinal(position_binning)), // sync_z_positive_crossings(createCrossingsLongitudinal(position_binning)),
sync_r_negative_crossings(createCrossingsRadial(position_binning)), // sync_r_negative_crossings(createCrossingsRadial(position_binning)),
sync_r_positive_crossings(createCrossingsRadial(position_binning)), // sync_r_positive_crossings(createCrossingsRadial(position_binning)),
sync_phi_negative_crossings(createCrossingsAzimuthal(position_binning)), // sync_phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
sync_phi_positive_crossings(createCrossingsAzimuthal(position_binning)) {} // sync_phi_positive_crossings(createCrossingsAzimuthal(position_binning))
{}
blitz::Array<double, 3> CurrentCollector::createAreaLongitudinal( blitz::Array<double, 3> CurrentCollector::createAreaLongitudinal(
const CylinderBinning& position_binning) { const CylinderBinning& position_binning) {
@@ -264,12 +265,12 @@ void CurrentCollector::resetCurrentCollector() {
r_negative_crossings = 0.; r_negative_crossings = 0.;
r_positive_crossings = 0.; r_positive_crossings = 0.;
sync_z_negative_crossings = 0.; // sync_z_negative_crossings = 0.;
sync_z_positive_crossings = 0.; // sync_z_positive_crossings = 0.;
sync_phi_negative_crossings = 0.; // sync_phi_negative_crossings = 0.;
sync_phi_positive_crossings = 0.; // sync_phi_positive_crossings = 0.;
sync_r_negative_crossings = 0.; // sync_r_negative_crossings = 0.;
sync_r_positive_crossings = 0.; // sync_r_positive_crossings = 0.;
} }
+32 -66
View File
@@ -83,28 +83,6 @@ DynamicDensityField::DynamicDensityField(
pitch_angle_binning.binIndexMax()), pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(), blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))), 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>( density_per_m3_(initiate4DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(), blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()), position_binning.radial_binning.binIndexMax()),
@@ -131,6 +109,18 @@ double DynamicDensityField::density(const Coordinate& position) {
const blitz::TinyVector<int, 3> position_bin = const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries()); position_binning_.bin(position.cylinderEntries());
#ifdef debug_level1
blitz::Array<double, 4> check = density_per_m3_.copy();
recalculateDensityArray();
if(!blitz::all(check == density_per_m3_)) {
ERROR("Density changes after recalculateDensityArray!");
}
#endif
return blitz::sum(density_per_m3_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all()));
/*/
// const double t = timer_->getDeltaT(); // const double t = timer_->getDeltaT();
const double time_in_bin = blitz::sum(time_in_bin_s_( const double time_in_bin = blitz::sum(time_in_bin_s_(
position_bin(0), position_bin(1), position_bin(2), position_bin(0), position_bin(1), position_bin(2),
@@ -141,6 +131,7 @@ double DynamicDensityField::density(const Coordinate& position) {
return (time_in_bin) / //- deleted_particles) / return (time_in_bin) / //- deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2)); bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
*/
} }
double DynamicDensityField::density(const Coordinate& position, double DynamicDensityField::density(const Coordinate& position,
@@ -208,29 +199,16 @@ void DynamicDensityField::logMovement(const Coordinate& position,
const int energy_bin = energy_binning_.bin(energy_eV); const int energy_bin = energy_binning_.bin(energy_eV);
const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle); const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle);
time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), sync_time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
pitch_angle_bin, energy_bin) += weight; pitch_angle_bin, energy_bin) += weight;
} }
// void DynamicDensityField::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> DynamicDensityField::densityArray() { blitz::Array<double, 3> DynamicDensityField::densityArray() {
#ifdef debug_level3 #ifdef debug_level3
DEBUG_LEVEL_3("recalc Density array"); DEBUG_LEVEL_3("recalc Density array");
#endif #endif
recalculateDensityArray(); // recalculated after a timestep reset (as of now hope that's enough and works correctly)
// recalculateDensityArray();
blitz::TinyVector<int,3> lowerbound(density_per_m3_.lbound(0), blitz::TinyVector<int,3> lowerbound(density_per_m3_.lbound(0),
density_per_m3_.lbound(1), density_per_m3_.lbound(1),
@@ -247,7 +225,7 @@ blitz::Array<double, 3> DynamicDensityField::densityArray() {
} }
blitz::Array<double, 4> DynamicDensityField::spectrumArray() { blitz::Array<double, 4> DynamicDensityField::spectrumArray() {
recalculateDensityArray(); // recalculateDensityArray();
return density_per_m3_; return density_per_m3_;
} }
@@ -291,8 +269,6 @@ void DynamicDensityField::recalculateDensityArray() {
blitz::fourthIndex ipitch; blitz::fourthIndex ipitch;
blitz::fifthIndex iE; blitz::fifthIndex iE;
// const double t = timer_->getDeltaT();
// reduction only seems to work for the last dimension (iE) // reduction only seems to work for the last dimension (iE)
// -> first reorder (by exchanging iE and ipitch) and afterwards doing // -> first reorder (by exchanging iE and ipitch) and afterwards doing
// the reduction over iE (which now contains the pitch dimension) // the reduction over iE (which now contains the pitch dimension)
@@ -300,51 +276,41 @@ void DynamicDensityField::recalculateDensityArray() {
density_per_m3_ = blitz::sum((time_in_bin_s_(ir, iphi, iz, iE, ipitch)), iE) / density_per_m3_ = blitz::sum((time_in_bin_s_(ir, iphi, iz, iE, ipitch)), iE) /
bin_volume_m3_(ir, iphi, iz); bin_volume_m3_(ir, iphi, iz);
//deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) /
// SimulationTimer::eventStopPoint("recalcDensityArray"); // SimulationTimer::eventStopPoint("recalcDensityArray");
} }
double DynamicDensityField::particleNumber() { // in a specific bin the "density" across E is proportional to the
blitz::Array<double, 3> density = densityArray(); // particle number
double particleNumber = blitz::sum(density * bin_volume_m3_); blitz::Array<double, 1> DynamicDensityField::sliceSpectrumArray(
#ifdef debug_level3 const Coordinate& position) const {
DEBUG_LEVEL_3("particle number: " + std::to_string(particleNumber));
#endif
return particleNumber;
}
double DynamicDensityField::particleNumber(blitz::TinyVector<int, 5> index) {
return time_in_bin_s_(index);
}
blitz::Array<double, 1> DynamicDensityField::
sliceSpectrumArray(const Coordinate& position) const {
blitz::TinyVector<int, 3> position_bin = blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries()); position_binning_.bin(position.cylinderEntries());
// blitz::Array<double, 4> check = density_per_m3_.copy();
// recalculateDensityArray();
// if(!blitz::all(check == density_per_m3_)) {
// ERROR("splice specturm array: check failed.");
// }
return density_per_m3_(position_bin(0), position_bin(1), position_bin(2), return density_per_m3_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range(energy_binning_.binIndexMin(), blitz::Range(energy_binning_.binIndexMin(),
energy_binning_.binIndexMax()-1)).copy(); energy_binning_.binIndexMax()-1));
} }
blitz::Array<double, 1> DynamicDensityField:: blitz::Array<double, 1> DynamicDensityField::sliceTimeInBinArray(
sliceTimeInBinArray(const Coordinate& position, double energy_eV) const { const Coordinate& position, double energy_eV) const {
blitz::TinyVector<int, 3> position_bin = blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries()); position_binning_.bin(position.cylinderEntries());
int energy_bin = energy_binning_.bin(energy_eV); int energy_bin = energy_binning_.bin(energy_eV);
return time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), return time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range(0, pitch_angle_binning_.binIndexMax()-1), blitz::Range(0, pitch_angle_binning_.binIndexMax()-1),
energy_bin).copy(); energy_bin);
} }
// resets the field that logs the new density
void DynamicDensityField::resetDynamicDensityField() { void DynamicDensityField::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_time_in_bin_s_ = 0.;
// sync_deleted_particles_ = 0.;
} }
void DynamicDensityField::restartTimer(double time, double delta_t) { void DynamicDensityField::restartTimer(double time, double delta_t) {
+1 -80
View File
@@ -16,8 +16,7 @@ EventPositionDistribution::EventPositionDistribution(
density_values( density_values(
std::uniform_real_distribution<double>(density.min, density.max)) {} std::uniform_real_distribution<double>(density.min, density.max)) {}
CylinderCoordinate EventPositionDistribution::rollPosition( CylinderCoordinate EventPositionDistribution::rollPosition(std::mt19937* engine) {
std::mt19937* engine) {
double random_number_z; double random_number_z;
double random_numer_r; double random_numer_r;
double random_number_phi; double random_number_phi;
@@ -39,81 +38,3 @@ CylinderCoordinate EventPositionDistribution::rollPosition(
return CylinderCoordinate(blitz::TinyVector<double, 3>( return CylinderCoordinate(blitz::TinyVector<double, 3>(
random_numer_r, random_number_phi, random_number_z)); random_numer_r, random_number_phi, random_number_z));
} }
PositionDistributionFromDensity::PositionDistributionFromDensity(
std::shared_ptr<DynamicDensityField> density):
density_(density),
std_unifrm(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);
random_n = density_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));
}
***************************************************************************/
CylinderCoordinate PositionDistributionFromDensity::drawPosition(std::mt19937* engine,
int r_idx, int phi_idx, int z_idx) {
double left_bin_border_radial = density_->positionBinning()
->radial_binning.binBorders()[r_idx];
double left_bin_border_azimuthal = density_->positionBinning()
->azimuth_binning.binBorders()[phi_idx];
double left_bin_border_longitudinal = density_->positionBinning()
->longitudinal_binning.binBorders()[z_idx];
auto stepsize = density_->positionBinning()->stepsize();
double r_rndm, phi_rndm, z_rndm;
r_rndm = std_unifrm(*engine);
phi_rndm = std_unifrm(*engine);
z_rndm = std_unifrm(*engine);
double radius = std::sqrt(left_bin_border_radial*left_bin_border_radial +
(2*left_bin_border_radial + stepsize(0))
*stepsize(0)*r_rndm);
return CylinderCoordinate(blitz::TinyVector<double, 3>
(radius,
left_bin_border_azimuthal + stepsize(1) * phi_rndm,
left_bin_border_longitudinal + stepsize(2) * z_rndm));
}
-54
View File
@@ -113,60 +113,6 @@ void Injector::setWeights(const double physical_number, const int numerical_numb
#endif #endif
} }
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_factor) {
blitz::TinyVector<int, 5> index = specie->randomIndex()->index();
const double num_part_in_bin = specie->densityForDrawing()->particleNumber(index);
if(num_part_in_bin == 0) {
#if defined(debug_level2) || defined(debug_level3)
std::stringstream out;
out << "index: "<< index <<" has no particles";
// DEBUG_LEVEL_2(out.str());
#endif
return;
}
// draw the position
CylinderCoordinate position =
specie->positionDistributionFromDensity()->drawPosition(engine,
index(0), index(1), index(2));
// draw the velocity
CartesianVector velocity(blitz::TinyVector<double, 3>(0,0,0));
// 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()->
drawVelocity(index, engine);
} else {
velocity = specie->velocityDistributionFromDensityField()->
drawVelocity(index, engine, position, magnetic_field);
}
#if defined(debug_level2) || defined(debug_level3)
std::stringstream out;
out << specie->name() << ":\n";
out << "\ndrawn index: " << index;
out << "\nnumber of particles (" << specie->name() << ") at index: " << num_part_in_bin;
out << "\ndrawn position: " << position.cylinderEntries();
out << "\ndrawn velocity: " << velocity.cartesianEntries();
if(num_part_in_bin > 0)
DEBUG_LEVEL_2(out.str());
#endif
particle::Particle drawn_particle(specie, position,
velocity, weight_factor*num_part_in_bin);
queue.push_back(drawn_particle);
}
double Injector::timePassed() const { double Injector::timePassed() const {
return 1 / activity_; return 1 / activity_;
} }
+8 -8
View File
@@ -5,11 +5,11 @@ DeletionLogger::DeletionLogger(std::vector<DeletionType> used_types,
std::vector<PhysicalDeletionType> used_phys_types) { std::vector<PhysicalDeletionType> used_phys_types) {
for (auto& type : used_types) { for (auto& type : used_types) {
num_deletions[type] = 0; num_deletions[type] = 0;
sync_num_deletions[type] = 0; // sync_num_deletions[type] = 0;
} }
for (auto& type: used_phys_types) { for (auto& type: used_phys_types) {
num_phys_deletions[type] = 0.; num_phys_deletions[type] = 0.;
sync_num_phys_deletions[type] = 0.; // sync_num_phys_deletions[type] = 0.;
} }
} }
@@ -53,13 +53,13 @@ void DeletionLogger::resetDeletionLogger() {
for(auto& pair : num_deletions) { for(auto& pair : num_deletions) {
pair.second = 0; pair.second = 0;
} }
for (auto& pair : sync_num_deletions) { // for (auto& pair : sync_num_deletions) {
pair.second = 0; // pair.second = 0;
} // }
for(auto& pair : num_phys_deletions) { for(auto& pair : num_phys_deletions) {
pair.second = 0; pair.second = 0;
} }
for (auto& pair : sync_num_phys_deletions) { // for (auto& pair : sync_num_phys_deletions) {
pair.second = 0; // pair.second = 0;
} // }
} }
+8 -1
View File
@@ -150,6 +150,13 @@ void BorisMover::move(particle::Particle* particle,
} }
#ifdef debug_level3 #ifdef debug_level3
double new_mu;
if (kinematic::norm(B) == 0) {
new_mu = kinematic::cosPitchAngle(
blitz::TinyVector<double, 3>(0,0,1), particle->velocity().cartesianEntries());
} else {
new_mu = kinematic::cosPitchAngle(B, particle->velocity().cartesianEntries());
}
if((changed_energy_bin || changed_position_bin) && !left_simulation_domain && !died_in_bin && (leftover_time > 0)) { if((changed_energy_bin || changed_position_bin) && !left_simulation_domain && !died_in_bin && (leftover_time > 0)) {
std::stringstream out; std::stringstream out;
out << "move(...) interrupted by change in "; out << "move(...) interrupted by change in ";
@@ -163,7 +170,7 @@ void BorisMover::move(particle::Particle* particle,
// out << "mu bin: "; // out << "mu bin: ";
// out << old_mu << " (old), " << new_mu; // out << old_mu << " (old), " << new_mu;
} else { } else {
out <<"unknown bin... " << changed_energy_bin << changed_position_bin << changed_mu_bin << left_simulation_domain << died_in_bin << leftover_time; out <<"unknown bin... " << changed_energy_bin << changed_position_bin << left_simulation_domain << died_in_bin << leftover_time;
} }
out << "\n(gyroradius = " << particle->mass_kg()*std::sqrt(1-new_mu*new_mu)*particle->absoluteVelocity()/(particle->specie()->charge_C()*kinematic::norm(B)) << " m"; out << "\n(gyroradius = " << particle->mass_kg()*std::sqrt(1-new_mu*new_mu)*particle->absoluteVelocity()/(particle->specie()->charge_C()*kinematic::norm(B)) << " m";
out << " energy: " << particle->kineticEnergy_eV() <<" eV)"; out << " energy: " << particle->kineticEnergy_eV() <<" eV)";
+55 -213
View File
@@ -79,10 +79,6 @@ void Simulation::init(Parameter& parameter) {
#endif #endif
random_ = generator::buildRandomNumbers(parameter); random_ = generator::buildRandomNumbers(parameter);
for(auto& tracked_specie : tracked_species_) {
tracked_specie.second->randomIndex()->reshuffle(random_->engine());
}
#ifdef debug #ifdef debug
DEBUG_LEVEL_0("Init poisson solver."); DEBUG_LEVEL_0("Init poisson solver.");
#endif #endif
@@ -143,10 +139,6 @@ void Simulation::finalize() {
void Simulation::start() { void Simulation::start() {
SIM_INFO("Starting Simulation."); SIM_INFO("Starting Simulation.");
// stride wrt the number of beta decay events per CPU
const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
// number of timesteps to be simulated // number of timesteps to be simulated
const int number_timesteps = parameter_.intValue(json_path({"Simulation", const int number_timesteps = parameter_.intValue(json_path({"Simulation",
"NumberTimesteps"}), 1); "NumberTimesteps"}), 1);
@@ -164,41 +156,14 @@ void Simulation::start() {
injector_->setWeights(time_resolution_events, beta_decay_events); injector_->setWeights(time_resolution_events, beta_decay_events);
// number of density events per timestep and CPU
const int particles_per_bin =
parameter_.intValue(json_path({"Simulation",
"NumberDensityParticlesPerBinPerCPU"}), 0);
// calculate a 'stride' for the density events s.t. the same number of syncs
// would be performed
int density_stride = particles_per_bin;
if(beta_decay_events != 0) {
density_stride = std::ceil(particles_per_bin *
(static_cast<double>(event_stride)/beta_decay_events));
}
// calculate the scaling factor for the particle weight for particles
// drawn from the density
const double density_weight_factor =
1./(MpiCommunication::mpi_size*particles_per_bin);
#ifdef debug
DEBUG_LEVEL_0("Number of particles per bin per CPU: " + std::to_string(particles_per_bin));
#endif
SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps)); SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps));
SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride)); SIM_INFO("Number of injected particles per timestep: " + std::to_string(beta_decay_events));
int leftover_events_time_resolution = beta_decay_events;
int leftover_density_events = particles_per_bin;
const double delta_t = time_resolution_events*injector_->timePassed(); const double delta_t = time_resolution_events*injector_->timePassed();
timer_->setDeltaT(delta_t); timer_->setDeltaT(delta_t);
injector_->initInjectionTimeDistribution(delta_t); injector_->initInjectionTimeDistribution(delta_t);
int num_cpu_syncs = 0;
bool reset = true;
timer_->increaseTimestep(delta_t); timer_->increaseTimestep(delta_t);
while (timestep < number_timesteps) { while (timestep < number_timesteps) {
@@ -207,12 +172,6 @@ void Simulation::start() {
out << "Timeinterval: " << timer_->time() << "s."; out << "Timeinterval: " << timer_->time() << "s.";
DEBUG_LEVEL_3(out.str()); DEBUG_LEVEL_3(out.str());
#endif #endif
// calculate the number of beta events to be simulated before a
// cpu sync is done
int events_of_cycle =
eventsOfCycle(event_stride, leftover_events_time_resolution);
int density_events_of_cycle =
eventsOfCycle(density_stride, leftover_density_events);
#ifdef debug_level1 #ifdef debug_level1
DEBUG_LEVEL_1("Events of cycle: " + std::to_string(events_of_cycle)); DEBUG_LEVEL_1("Events of cycle: " + std::to_string(events_of_cycle));
@@ -222,16 +181,10 @@ void Simulation::start() {
if(timestep%(std::max(number_timesteps/100, 1)) == 0) if(timestep%(std::max(number_timesteps/100, 1)) == 0)
SIM_INFO("Processing timestep: " + std::to_string(timestep)); SIM_INFO("Processing timestep: " + std::to_string(timestep));
#ifdef debug
SIM_INFO("Leftover events this timestep this CPU: " +
std::to_string(leftover_events_time_resolution));
SIM_INFO("Leftover density events this timestep this CPU: " +
std::to_string(leftover_density_events));
#endif
// process both density and beta events before a cpu synchronization // process both density and beta events before a cpu synchronization
processDensityEvents(particles_per_bin, density_weight_factor); processDensityEvents();
processEvents(events_of_cycle); processEvents(beta_decay_events);
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3) #if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timestep)); DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timestep));
@@ -239,11 +192,6 @@ void Simulation::start() {
std::to_string(leftover_events_time_resolution)); std::to_string(leftover_events_time_resolution));
#endif #endif
leftover_events_time_resolution -= events_of_cycle;
leftover_density_events -= density_events_of_cycle;
reset = !(leftover_events_time_resolution > 0);
#ifdef debug #ifdef debug
SIM_INFO("Cpu sync."); SIM_INFO("Cpu sync.");
#endif #endif
@@ -252,59 +200,53 @@ void Simulation::start() {
// otherwise it would be more difficult to set it... (cpu synchronizer // otherwise it would be more difficult to set it... (cpu synchronizer
// is a friend class of the density field, i.e. has access to the // is a friend class of the density field, i.e. has access to the
// private members) // private members)
cpu_synchronizer_->synchronize(tracked_species_, reset); cpu_synchronizer_->synchronize(tracked_species_);
num_cpu_syncs += 1; timer_->increaseTimestep(delta_t);
timestep++;
SimulationTimer::eventStopPoint(std::string("CpuSync")); SimulationTimer::eventStopPoint(std::string("CpuSync"));
// can probably be moved into the reset section and therefore
// the parameter 'reset' could probably be removed
#ifdef debug #ifdef debug
SIM_INFO("Poisson step."); SIM_INFO("Poisson step.");
#endif #endif
SimulationTimer::eventStartPoint(std::string("PoissonStep")); SimulationTimer::eventStartPoint(std::string("PoissonStep"));
// only solves the potential anew if 'reset' is true
poisson_solver_->solvePotential(chargedensity(), reset); poisson_solver_->solvePotential(chargedensity());
electric_field_->updateDynamicField(poisson_solver_->staticElectricField()); electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
SimulationTimer::eventStopPoint(std::string("PoissonStep")); SimulationTimer::eventStopPoint(std::string("PoissonStep"));
#ifdef debug #ifdef debug
SIM_INFO("Perform output."); SIM_INFO("Perform output.");
#endif #endif
SimulationTimer::eventStartPoint(std::string("Output")); SimulationTimer::eventStartPoint(std::string("Output"));
// only write inactive queue, obvi not correct if written between timesteps
output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get(), output_->writeSimulationData(timestep, tracked_species_, poisson_solver_.get(),
random_->engine(), storage_queue_[inactive_storage], random_->engine(), storage_queue_[inactive_storage],
timestep + 1 + injectionGroupOffset); timestep + injectionGroupOffset);
SimulationTimer::eventStopPoint(std::string("Output")); SimulationTimer::eventStopPoint(std::string("Output"));
SimulationTimer::eventStartPoint("Reset"); SimulationTimer::eventStartPoint("Reset");
if(reset) {
#if defined(debug_level2) || defined(debug_level3) #if defined(debug_level2) || defined(debug_level3)
DEBUG("Number of particles in active storage queue: " DEBUG("Number of particles in active storage queue: "
+ std::to_string(storage_queue_[active_storage].size())); + std::to_string(storage_queue_[active_storage].size()));
DEBUG("Number of particles in inactive storage queue: " DEBUG("Number of particles in inactive storage queue: "
+ std::to_string(storage_queue_[inactive_storage].size())); + std::to_string(storage_queue_[inactive_storage].size()));
#endif #endif
#ifdef debug #ifdef debug
SIM_INFO("Do resets and increase the timestep for timeresolution."); SIM_INFO("Do resets and increase the timestep for timeresolution.");
#endif #endif
active_storage = (active_storage + 1) % 2; active_storage = (active_storage + 1) % 2;
inactive_storage = (inactive_storage + 1) % 2; inactive_storage = (inactive_storage + 1) % 2;
for(auto& pair : tracked_species_) { for(auto& pair : tracked_species_) {
pair.second->dynamicDensityField()->resetDynamicDensityField(); pair.second->dynamicDensityField()->resetDynamicDensityField();
pair.second->currentCollector()->resetCurrentCollector(); pair.second->currentCollector()->resetCurrentCollector();
pair.second->deletionLogger()->resetDeletionLogger(); pair.second->deletionLogger()->resetDeletionLogger();
}
leftover_events_time_resolution = beta_decay_events;
leftover_density_events = particles_per_bin;
timer_->increaseTimestep(delta_t);
timestep++;
} }
SimulationTimer::eventStopPoint("Reset"); SimulationTimer::eventStopPoint("Reset");
} }
} }
@@ -367,95 +309,63 @@ void Simulation::processEvents(int events) {
DEBUG_LEVEL_2("Particles in queue: " + DEBUG_LEVEL_2("Particles in queue: " +
std::to_string(queue_.size())); std::to_string(queue_.size()));
#endif #endif
const int particle_number = particle::Particle particle = queue_.back();
particleNumberFromQueue(queue_.size(), random_.get()); queue_.pop_back();
// extract particle from queue here, so that an extension of the queue does
// not mess up the reference
particle::Particle particle = queue_.at(particle_number);
queue_.erase(queue_.begin() + particle_number);
processUntilTermination(particle); processUntilTermination(particle);
} }
} }
void Simulation::processDensityEvents(int particles_per_bin, const double weight_factor) { void Simulation::processDensityEvents() {
#ifdef debug #ifdef debug
DEBUG_LEVEL_0("Processing density events."); DEBUG_LEVEL_0("Processing density events.");
#endif #endif
// number of full grid traversions // number of full grid traversions (legacy variable)
int current_event = 0; int current_event = 0;
// set to true if all grids of all species have been visited
bool all_bins_done = false;
// calculate the number of particles currently contained within the densities while ((!queue_.empty()) || (!storage_queue_[active_storage].empty())) {
// of the different tracked species before injection in order to avoid
// the expensive recalculateDensityField funtion being calculated for every
// new injection event
std::map<std::string, double> particleNumbers;
for(auto& pair: tracked_species_) {
particleNumbers[pair.first] = (pair.second->densityForDrawing()->particleNumber());
}
while ((current_event < particles_per_bin) || (!queue_.empty())) {
#ifdef debug_level2 #ifdef debug_level2
DEBUG_LEVEL_2("Current event: " + std::to_string(current_event)); DEBUG_LEVEL_2("Current event: " + std::to_string(current_event));
#endif #endif
if (queue_.empty()) { if (queue_.empty()) {
std::vector<particle::Particle> new_particles;
#ifdef debug_level2 #ifdef debug_level2
DEBUG_LEVEL_2("Current density event: " + std::to_string(current_event)); DEBUG_LEVEL_2("Current density event: " + std::to_string(current_event));
#endif #endif
SimulationTimer::eventStartPoint(std::string("DensityInjection")); SimulationTimer::eventStartPoint(std::string("DensityInjection"));
new_particles = determineInjectedDensityParticles(random_.get(), particle::Particle newParticle(storage_queue_[active_storage].back(),
weight_factor, current_event, particleNumbers, tracked_species_);
all_bins_done); storage_queue_[active_storage].pop_back();
SimulationTimer::eventStopPoint(std::string("DensityInjection")); SimulationTimer::eventStopPoint(std::string("DensityInjection"));
#if defined debug_level3 #if defined debug_level3
for(auto& particle : new_particles) { std::stringstream output_ss;
std::stringstream output_ss; output_ss << newParticle.specie()->name() << " with velocity (cart): ";
output_ss << particle.specie()->name() << " with velocity (cart): "; output_ss << newParticle.velocity().cartesianEntries();
output_ss << particle.velocity().cartesianEntries(); output_ss << " and position (cart)";
output_ss << " and position (cart)"; output_ss << newParticle.cartesianPosition().cartesianEntries();
output_ss << particle.cartesianPosition().cartesianEntries(); DEBUG_LEVEL_3(output_ss.str());
DEBUG_LEVEL_3(output_ss.str());
}
#endif #endif
// if no new particles could be injected from the density, it is not possible // if no new particles could be injected from the density, it is not possible
// that during another iteration cycle new particles will be injected // that during another iteration cycle new particles will be injected
// (drawing field only changes after timesteps) // (drawing field only changes after timesteps)
if(all_bins_done) { current_event += 1;
current_event += 1;
for(auto& element : tracked_species_) {
if(element.second->explicitlyStored()) {
continue;
}
element.second->randomIndex()->reshuffle(random_->engine());
}
}
if(!new_particles.empty()) {
queue_.insert(queue_.end(), new_particles.begin(), new_particles.end());
} else {
continue;
}
queue_.push_back(newParticle);
} }
#ifdef debug_level2 #ifdef debug_level2
DEBUG_LEVEL_2("Particles in queue: " + DEBUG_LEVEL_2("Particles in queue: " +
std::to_string(queue_.size())); std::to_string(queue_.size()));
#endif #endif
const int particle_number = // const int particle_number =
particleNumberFromQueue(queue_.size(), random_.get()); // particleNumberFromQueue(queue_.size(), random_.get());
// extract particle from queue here, so that an extension of the queue does // extract particle from queue here, so that an extension of the queue does
// not mess up the reference // not mess up the reference
particle::Particle particle = queue_.at(particle_number); particle::Particle particle = queue_.back();// queue_.at(particle_number);
queue_.erase(queue_.begin() + particle_number); // queue_.erase(queue_.begin() + particle_number);
queue_.pop_back();
processUntilTermination(particle); processUntilTermination(particle);
} }
@@ -521,11 +431,11 @@ void Simulation::processUntilTermination(particle::Particle& particle) {
ERROR(out.str()); ERROR(out.str());
} }
#endif #endif
// particle terminated due to reaching time resolution alone -> needs
// to be stored (if it's an electron) storage_queue_[inactive_storage].push_back(particle.serialize());
if(particle.specie()->explicitlyStored()) { #ifdef debug_level3
storage_queue_[inactive_storage].push_back(particle.serialize()); DEBUG_LEVEL_3(particle.specie()->name() + " pushed back into storage.");
} #endif
if(particle.specie()->deletionLogger()) { if(particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.cylinderPosition(), particle.specie()->deletionLogger()->logDeletion(particle.cylinderPosition(),
@@ -647,9 +557,10 @@ void Simulation::collisionTime(particle::Particle& particle, RandomNumbers* rand
particle.indexNextInteration((min_iterator - collision_times.begin())); particle.indexNextInteration((min_iterator - collision_times.begin()));
particle.timeUntilCollision(*min_iterator); particle.timeUntilCollision(*min_iterator);
#ifdef debug_level3 #ifdef debug
std::stringstream out; std::stringstream out;
out << "collision times:\n[ "; out << "collision times ";
out << particle.specie()->name() <<":\n[ ";
for(auto& element : collision_times) { for(auto& element : collision_times) {
out << element << " "; out << element << " ";
@@ -658,7 +569,7 @@ void Simulation::collisionTime(particle::Particle& particle, RandomNumbers* rand
out << "\nmin value: " << *min_iterator; out << "\nmin value: " << *min_iterator;
out << "\nindexNextInteraction: " << particle.indexNextInteraction(); out << "\nindexNextInteraction: " << particle.indexNextInteraction();
DEBUG_LEVEL_3(out.str()); DEBUG(out.str());
#endif #endif
} }
@@ -692,75 +603,6 @@ interaction::InteractionOutput Simulation::interact(
} }
} }
// weight_factor has to be such that particleNumber * weight_factor = weight
std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
RandomNumbers* random, const double weight_factor, const int current,
std::map<std::string, double>& particleNumbers, bool& all_bins_done) {
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");
}
bool tmp_done = false;
all_bins_done = true;
for(auto& pair: tracked_species_) {
// Note: takes the next particle in the storage queue regardless if
// that particle is a member of the current tracked_specie
if(pair.second->explicitlyStored()) {
// if the storage queue does not contain any more particles
// no new particles can be drawn
if(storage_queue_[active_storage].empty()) {
all_bins_done = all_bins_done && true;
continue;
} else {
all_bins_done = false;
}
// take the last particle from the storage queue and extract it
particle::SerializedParticle new_sparticle =
storage_queue_[active_storage].back();
storage_queue_[active_storage].pop_back();
particle::Particle new_particle(new_sparticle, tracked_species_);
// "draw" the actual particle
new_particles.push_back(new_particle);
continue;
}
tmp_done = pair.second->randomIndex()->visited_all();
if (particleNumbers[pair.first] == 0) {
all_bins_done = all_bins_done && true;
#ifdef debug_level3
DEBUG_LEVEL_3("No particles in density of species: " + pair.second->name());
#endif
continue;
}
#if defined debug_level3
if (current == 0) {
std::stringstream out;
out << pair.second->name();
out << "particle number from density: ";
out << particleNumbers[pair.first];
DEBUG_LEVEL_3(out.str());
}
#endif
if(!tmp_done) {
injector_->drawNewParticleFromDensityField(random->engine(),
pair.second, new_particles, magnetic_field_,
weight_factor);
}
// if species is not done tmp_done && ... = false
all_bins_done = all_bins_done && tmp_done;
}
return new_particles;
}
//maybe put that into the poisson solver //maybe put that into the poisson solver
blitz::Array<double,3> Simulation::chargedensity() { blitz::Array<double,3> Simulation::chargedensity() {
#ifdef debug_level3 #ifdef debug_level3
+5 -36
View File
@@ -38,14 +38,12 @@ TrackedSpecie::TrackedSpecie(
std::string name, std::string name,
double mass_kg, double mass_kg,
double charge_C, double charge_C,
bool explicitly_stored,
std::shared_ptr<Mover> mover, std::shared_ptr<Mover> mover,
std::shared_ptr<Terminator> terminator, std::shared_ptr<Terminator> terminator,
std::shared_ptr<Reflector> reflector, std::shared_ptr<Reflector> reflector,
std::shared_ptr<DynamicDensityField> density_field, std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution, std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity, std::shared_ptr<DriftVelocity> drift_velocity)
std::shared_ptr<DynamicDensityField> density_for_drawing)
: Specie(type, name, mass_kg, charge_C), : Specie(type, name, mass_kg, charge_C),
mover_(mover), mover_(mover),
terminator_(terminator), terminator_(terminator),
@@ -53,31 +51,15 @@ TrackedSpecie::TrackedSpecie(
density_field_(density_field), density_field_(density_field),
deletion_logger_(std::shared_ptr<DeletionLogger>(nullptr)), deletion_logger_(std::shared_ptr<DeletionLogger>(nullptr)),
current_collector_(std::shared_ptr<CurrentCollector>(nullptr)), current_collector_(std::shared_ptr<CurrentCollector>(nullptr)),
velocity_distribution_(velocity_distribution),
drift_velocity_(drift_velocity), drift_velocity_(drift_velocity),
density_for_drawing_(density_for_drawing),
position_distribution_from_density_(
std::make_shared<PositionDistributionFromDensity>(density_for_drawing)),
velocity_distribution_from_density_( velocity_distribution_from_density_(
std::make_shared<VelocityDistributionFromDensityField>( std::make_shared<VelocityDistributionFromDensityField>(
density_for_drawing, mass_kg)), density_field, mass_kg)) {}
explicitly_stored_(explicitly_stored) {
blitz::TinyVector<int, 5> num_bins;
auto tmp = density_field->positionBinning()->numBins();
num_bins(0) = tmp(0); num_bins(1) = tmp(1); num_bins(2) = tmp(2);
num_bins(3) = density_field->pitchAngleBinning()->numBins();
// include underflow bin in the energy direction only
num_bins(4) = density_field->energyBinning()->numBins() + 1;
random_index_ = std::make_shared<RandomIndex> (RandomIndex(num_bins));
}
RandomIndex* TrackedSpecie::randomIndex() {
return random_index_.get();
}
DensityField* TrackedSpecie::densityField() { DensityField* TrackedSpecie::densityField() {
// return the density field storing the previous timestep, since
// that density is the only one that makes sense for the calculation
// of e.g. MFP for Tracked-Tracked interactions
return density_field_.get(); return density_field_.get();
} }
@@ -96,10 +78,6 @@ DynamicDensityField* TrackedSpecie::dynamicDensityField() {
return density_field_.get(); return density_field_.get();
} }
DynamicDensityField* TrackedSpecie::densityForDrawing() {
return density_for_drawing_.get();
}
Mover* TrackedSpecie::mover() { Mover* TrackedSpecie::mover() {
return mover_.get(); return mover_.get();
} }
@@ -120,11 +98,6 @@ CurrentCollector* TrackedSpecie::currentCollector() {
return current_collector_.get(); return current_collector_.get();
} }
PositionDistributionFromDensity*
TrackedSpecie::positionDistributionFromDensity() {
return position_distribution_from_density_.get();
}
VelocityDistributionFromDensityField* VelocityDistributionFromDensityField*
TrackedSpecie::velocityDistributionFromDensityField() { TrackedSpecie::velocityDistributionFromDensityField() {
return velocity_distribution_from_density_.get(); return velocity_distribution_from_density_.get();
@@ -149,10 +122,6 @@ void TrackedSpecie::currentCollector(
current_collector_ = new_collector; current_collector_ = new_collector;
} }
bool TrackedSpecie::explicitlyStored() {
return explicitly_stored_;
}
BackgroundSpecie::BackgroundSpecie( BackgroundSpecie::BackgroundSpecie(
ImplementedSpecies type, ImplementedSpecies type,
std::string name, std::string name,
+116 -228
View File
@@ -30,6 +30,60 @@ CartesianVector VelocityDistributionFromFunction::rollVelocity(
return fv_->rollVelocity(engine); return fv_->rollVelocity(engine);
} }
double drawPiecewiseConstant(const std::vector<double>& intervals, const blitz::Array<double, 1>& weights,
std::mt19937* engine) {
std::uniform_real_distribution<> dist(0.,1.);
// std::stringstream out;
// out << "intervals: [ ";
// out << "]\n";
// out << "\nweights: " << weights;
// out << "\ninterval sizes: " << interval_sizes;
double normalization = blitz::sum(weights);
#if defined(debug)
if(intervals.size() != weights.length(0) + 1) {
std::stringstream msg;
msg << "Interval size ( " << intervals.size() << " ) are not compatible ";
msg << "with the weight size ( " << weights.length(0) << " )";
ERROR(msg.str());
}
#endif
// out << "\nnormalization: " << normalization;
// if there are not particles in the considered interval return NaN as an
// indicator for that
if(normalization == 0) {
// SIM_INFO(out.str());
return NAN;
}
double sum = 0;
int interval = -1;
double check = dist(*engine)*normalization;
for(int i = weights.lbound(0); i <= weights.ubound(0); i++) {
sum += weights(i);
if(check < sum) {
interval = i-weights.lbound(0);
break;
}
}
if(interval==-1) {
std::stringstream msg;
msg << "no interval found: " << weights << " [ ";
for(auto value : intervals) {
msg << value << " ";
}
msg << "]";
ERROR(msg.str());
}
// SIM_INFO(out.str());
return (intervals[interval+1] - intervals[interval])*dist(*engine) + intervals[interval];
}
VelocityDistributionFromDensityField::VelocityDistributionFromDensityField( VelocityDistributionFromDensityField::VelocityDistributionFromDensityField(
std::shared_ptr<DynamicDensityField> density_field, double mass_kg): std::shared_ptr<DynamicDensityField> density_field, double mass_kg):
density_field_(density_field), density_field_(density_field),
@@ -37,12 +91,10 @@ VelocityDistributionFromDensityField::VelocityDistributionFromDensityField(
pitchAngleBinBorders_(density_field->pitchAngleBinning()->binBorders()), pitchAngleBinBorders_(density_field->pitchAngleBinning()->binBorders()),
theta_distribution_(std::uniform_real_distribution<double>(0.,1.)), theta_distribution_(std::uniform_real_distribution<double>(0.,1.)),
mass_kg_(mass_kg) { mass_kg_(mass_kg) {
double maxAbsExponent = std::max(std::abs(std::log10(energyBinBorders_.front())),
std::abs(std::log10(energyBinBorders_.back())));
alpha_lower_limit = -300/maxAbsExponent;
alpha_upper_limit = 300/maxAbsExponent;
// necessary to include the underflow bin in the energy domain // necessary to include the underflow bin in the energy domain
energyBinBorders_.insert(energyBinBorders_.begin(), 0); energyBinBorders_.insert(energyBinBorders_.begin(), 0);
// energy_values.resize(density_field->energyBinning()->numBins() + 1);
// mu_values.resize(density_field->pitchAngleBinning()->numBins());
} }
// not important as of now since it's meant for drawing a velocity from the // not important as of now since it's meant for drawing a velocity from the
@@ -57,29 +109,72 @@ CartesianVector VelocityDistributionFromDensityField::driftVelocity_ms(
CartesianVector VelocityDistributionFromDensityField::rollVelocity( CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine) { const Coordinate& position, std::mt19937* engine) {
// SIM_INFO("set energy values");
// draw energy from DynamicDensityField // draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_-> // energy_values = density_field_->sliceSpectrumArray(position);
sliceSpectrumArray(position); const blitz::Array<double, 1> energy_values = density_field_->sliceSpectrumArray(position);
std::piecewise_constant_distribution<double> energy_dist( // std::piecewise_constant_distribution<double> energy_dist(
energyBinBorders_.begin(), // energyBinBorders_.begin(),
energyBinBorders_.end(), // energyBinBorders_.end(),
energyValues.begin()); // energy_values.begin());
double energy_eV = energy_dist(*engine); // SIM_INFO("draw energy value");
double energy_eV = drawPiecewiseConstant(energyBinBorders_, energy_values, engine);//energy_dist(*engine); //
// if(std::isnan(energy_eV)) {
// std::stringstream msg;
// msg << "\nenergy is nan: " << position.cartesianEntries();
// msg << energy_values;
// density_field_->recalculateDensityArray();
// msg << "recalculated: " << density_field_->sliceSpectrumArray(position);
// msg << "density in bin: " << density_field_->density(position);
// msg << "\nbin: " << density_field_->positionBinning()->bin(position.cylinderEntries());
// msg << "\n";
// std::cerr << msg.str();
// }
// draw pitch angle from DynamicDensityField // draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_-> // SIM_INFO("set mu values");
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> pitchAngle_dist( const blitz::Array<double, 1> mu_values = density_field_->sliceTimeInBinArray(position, energy_eV);
pitchAngleBinBorders_.begin(),
pitchAngleBinBorders_.end(), // std::cout << mu_values;
pitchAngleValues.begin());
// SIM_INFO("\nset mu dist");
// std::piecewise_constant_distribution<double> pitchAngle_dist(
// pitchAngleBinBorders_.begin(),
// pitchAngleBinBorders_.end(),
// mu_values.begin());
// SIM_INFO("draw mu value");
double pitchAngle = drawPiecewiseConstant(pitchAngleBinBorders_, mu_values, engine);//pitchAngle_dist(*engine); //
// if(std::isnan(pitchAngle)) {
// std::stringstream msg;
// msg << "\npitchangle is nan: " << position.cartesianEntries();
// msg << mu_values;
// density_field_->recalculateDensityArray();
// msg << "recalculated: " << density_field_->sliceTimeInBinArray(position, energy_eV);
// msg << "density in bin: " << density_field_->density(position);
// msg << "\nbin: " << density_field_->positionBinning()->bin(position.cylinderEntries());
// msg << "\nenergy value: " << energy_eV;
// msg << "\nenergy bin: " << density_field_->energyBinning()->bin(energy_eV);
// // msg << "\nenergy bin borders: [ ";
// // for(auto value : energyBinBorders_) {
// // msg << " " << value;
// // }
// // msg << "]";
// std::cerr << msg.str();
// }
#ifdef debug
if(!isnan(energy_eV) && isnan(pitchAngle)) {
ERROR("Energy is not nan, but pitchangle is.");
}
#endif
double pitchAngle = pitchAngle_dist(*engine);
// construct the velocity // construct the velocity
@@ -89,12 +184,10 @@ CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_); 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 blitz::TinyVector<double, 3> v_direction = pitchAngle * zDirection
+ std::sqrt(1 - pitchAngle*pitchAngle) + std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, zDirection, theta); * kinematic::rotateVector(blitz::TinyVector<double,3>(1,0,0),
zDirection, theta);
return CartesianVector(v_direction * vMagnitude); return CartesianVector(v_direction * vMagnitude);
} }
@@ -164,208 +257,3 @@ CartesianVector VelocityDistributionFromDensityField::rollVelocity(
return CartesianVector(v_direction * vMagnitude); return CartesianVector(v_direction * vMagnitude);
} }
// if valid is false after function, the number of particles in the cell at the given index
// is 0
CartesianVector VelocityDistributionFromDensityField::drawVelocity(
const blitz::TinyVector<int, 5> index, std::mt19937* engine) {
// const double number_particles_in_bin = density_field_->particleNumber(index);
const double energy_step = energyBinBorders_[index(4) + 1]
- energyBinBorders_[index(4)];
const double pitch_angle_step = pitchAngleBinBorders_[index(3) + 1]
- pitchAngleBinBorders_[index(3)];
double energy_eV = energyBinBorders_[index(4)]
+ theta_distribution_(*engine)*energy_step;
double pitchAngle = pitchAngleBinBorders_[index(3)]
+ theta_distribution_(*engine)*pitch_angle_step;
// 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::drawVelocity(
const blitz::TinyVector<int, 5> index, std::mt19937* engine,
const Coordinate& position,
std::shared_ptr<MagneticField> magnetic_field) {
// since a 0 is included in the bin borders for the energy
const double energy_step = energyBinBorders_[index(4) + 2]
- energyBinBorders_[index(4) + 1];
const double pitch_angle_step = pitchAngleBinBorders_[index(3) + 1]
- pitchAngleBinBorders_[index(3)];
// double energy_eV = energyBinBorders_[index(4) + 1]
// + theta_distribution_(*engine)*energy_step;
double energy_eV;
double alpha = 1;
if(index(4) == -1) {
// linear drawing inbetween E=0, N(0)=0 to E=Er and N(Er)=Nr
energy_eV = energyBinBorders_[index(4) + 2]*
std::sqrt(theta_distribution_(*engine));
// #ifdef debug
// std::stringstream out;
// out << "underflow bin.\n\tdrawn energy: " << energy_eV;
// out << "\n\tenergy value left: " << energyBinBorders_[index(4)+1];
// out << "\n\tenergy value right: " << energyBinBorders_[index(4)+2];
// DEBUG(out.str());
// #endif
} else {
double nl = density_field_->particleNumber(index);
double nr = density_field_->particleNumber(index +
blitz::TinyVector<int, 5>(0,0,0,0,1));
// double alpha;
// no reason for specific values, just to avoid these cases
if(nl == 0) {
alpha = 1;
} else if (nr == 0) {
alpha = -1;
} else if (nr == 0 && nl == 0) {
alpha = 0;
} else {
alpha = std::log(nr/nl)/std::log(energyBinBorders_[index(4) + 2]/
energyBinBorders_[index(4) + 1]);
}
// alpha = std::abs(alpha) > 100 ?(alpha/std::abs(alpha))*100 : alpha;
alpha = std::min(std::max(alpha, alpha_lower_limit), alpha_upper_limit);
if(alpha == -1) {
energy_eV = std::pow(energyBinBorders_[index(4) + 2]
/ energyBinBorders_[index(4) + 1], theta_distribution_(*engine)) *
energyBinBorders_[index(4) + 1];
// energy_eV = (std::pow(2, theta_distribution_(*engine)) - 1)*energy_step
// + energyBinBorders_[index(4) + 1];
// #ifdef debug
// std::stringstream out;
// out << "alpha = -1\n\tdrawn energy: " << energy_eV;
// out << "\n\tenergy value left: " << energyBinBorders_[index(4)+1];
// out << "\n\tenergy value right: " << energyBinBorders_[index(4)+2];
// DEBUG(out.str());
// #endif
} else {
double xl_alphap1 = std::pow(energyBinBorders_[index(4) + 1], alpha + 1);
double xr_alphap1 = std::pow(energyBinBorders_[index(4) + 2], alpha + 1);
energy_eV = std::pow((xr_alphap1 - xl_alphap1)*
theta_distribution_(*engine) + xl_alphap1, 1/(alpha + 1));
// #ifdef debug
// if(std::abs(alpha) > 100) {
// std::stringstream out;
// out << "alpha: " << alpha;
// out << "\nxl_alphap1: " << xl_alphap1;
// out << "\nxr_alphap1: " << xr_alphap1;
// DEBUG(out.str());
// }
// #endif
// #ifdef debug
// std::stringstream out;
// out << "alpha = "<< alpha << "\n\tdrawn energy: " << energy_eV;
// out << "\n\tenergy value left: " << energyBinBorders_[index(4)+1];
// out << "\n\tenergy value right: " << energyBinBorders_[index(4)+2];
// DEBUG(out.str());
// #endif
}
}
double pitchAngle = pitchAngleBinBorders_[index(3)]
+ theta_distribution_(*engine)*pitch_angle_step;
#ifdef debug
if((std::isnan(pitchAngle)) || (std::isnan(energy_eV))) {
std::stringstream out;
out << "pitchAngle: " << pitchAngle;
out << "\nenergy value: " << energy_eV;
out << "\nalpha: " << alpha;
out << "\ncurrent index: " << index;
out << "\nNl: " << density_field_->particleNumber(index);
out << "\nNl: " << density_field_->particleNumber(index +
blitz::TinyVector<int, 5>(0,0,0,0,1));
out << "\nEl: " << energyBinBorders_[index(4) + 1];
out << "\nEr: " << energyBinBorders_[index(4) + 2];
out << "\nEl^(alpha+1): " << std::pow(energyBinBorders_[index(4) + 1], alpha + 1);
out << "\nEr^(alpha+1): " << std::pow(energyBinBorders_[index(4) + 2], alpha + 1);
// out << "\nenergy values: " << energyValues;
// out << "\npitch angle values: " << pitchAngleValues;
out << "\nenergy bin borders: [ ";
for(auto element : energyBinBorders_) {
out << element << " ";
}
out << "]";
ERROR(out.str());
}
// if(std::isinf(energy_eV)) {
// std::stringstream out;
// out << "pitchAngle: " << pitchAngle;
// out << "\nenergy value: " << energy_eV;
// out << "\ncurrent index: " << index;
// out << "\nalpha: " << alpha;
// out << "\nNl: " << density_field_->particleNumber(index);
// out << "\nNl: " << density_field_->particleNumber(index +
// blitz::TinyVector<int, 5>(0,0,0,0,1));
// out << "\nEl: " << energyBinBorders_[index(4) + 1];
// out << "\nEr: " << energyBinBorders_[index(4) + 2];
// // out << "\nenergy values: " << energyValues;
// // out << "\npitch angle values: " << pitchAngleValues;
// out << "\nenergy bin borders: [ ";
// for(auto element : energyBinBorders_) {
// out << element << " ";
// }
// out << "]";
// ERROR(out.str());
// }
#endif
#ifdef debug_level2
std::stringstream out;
out << "left Pitchangle value: "<< pitchAngleBinBorders_[index(3)];
out << "\nright Pitchangle value: " << pitchAngleBinBorders_[index(3)+1];
out << "\npitchAngle: " << pitchAngle;
out << "\nleft energy value: "<< energyBinBorders_[index(4) + 1];
out << "\nright energy value: " << energyBinBorders_[index(4)+2];
out << "\nenergy value: " << energy_eV;
DEBUG_LEVEL_2(out.str());
#endif
// 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);
}