Implemented pitch angle resolution.

Still includes (and uses) the non-pitch angle
resolved fields as well; have to be either removed
completely or refactored s.t. one of the two options
is chosen.
Pitch angle distribution has a hardcoded number of
bins for now, and exists in 'energy_binning.h'
This commit is contained in:
2024-10-28 15:00:19 +01:00
parent b4cbd8c44c
commit 5fc227e1b1
24 changed files with 1126 additions and 42 deletions
+2
View File
@@ -9,12 +9,14 @@ class Hdf5Reader {
Hdf5Reader(std::string directory, std::string filename);
Hdf5Reader(std::string absolute_filename);
blitz::Array<double, 5> readD5Double(std::string path);
blitz::Array<double, 4> readD4Double(std::string path);
blitz::Array<double, 3> readD3Double(std::string path);
blitz::Array<double, 2> readD2Double(std::string path);
blitz::Array<double, 1> readD1Double(std::string path);
double readDouble(std::string path);
blitz::Array<long int, 5> readD5LongInt(std::string path);
blitz::Array<long int, 4> readD4LongInt(std::string path);
std::stringstream readEngineString(std::string path);
+2
View File
@@ -14,7 +14,9 @@ class Hdf5Writer {
void write(const blitz::Array<double, 2>& data, std::string path);
void write(const blitz::Array<double, 3>& data, std::string path);
void write(const blitz::Array<double, 4>& data, std::string path);
void write(const blitz::Array<double, 5>& data, std::string path);
void write(const blitz::Array<long int, 4>& data, std::string path);
void write(const blitz::Array<long int, 5>& data, std::string path);
void write(const blitz::TinyVector<double, 3>& data, std::string path);
void write(const blitz::TinyVector<int, 3>& data, std::string path);
void write(const std::vector<double>& data, std::string path);
+3
View File
@@ -13,6 +13,7 @@ namespace species {
}; // namespace species
class DynamicDensityField;
class DynamicDensityFieldWithPitchAngle;
class PoissonSolver;
class RandomNumbers;
@@ -32,6 +33,8 @@ class Restart {
private:
void restartTimer(species::TrackedSpecie* reference_specie);
void restartDrawingDensityField(DynamicDensityField* field, std::string path); // only necc densityfield for the one that is drawn from
void restartDrawingDensityField(DynamicDensityFieldWithPitchAngle* field,
std::string path);
void restartPoissonSolver(PoissonSolver* solver); // only load in the potential and calc the electric field
void restartRandomNumbers(RandomNumbers* random);
+13
View File
@@ -9,6 +9,7 @@
#include "IO/hdf5_writer.h"
class DynamicDensityField;
class DynamicDensityFieldWithPitchAngle;
class CurrentBorder;
class Parameter;
class CurrentCollector;
@@ -61,12 +62,23 @@ class SimulationOutput {
int cpu_sync,
bool overwrite_last);
void writeSimulationData(DynamicDensityFieldWithPitchAngle* density_field,
std::string species_path,
int cpu_sync,
bool overwrite_last);
void writeSpectrum(DynamicDensityField* density_field, std::string path);
void writeSpectrum(DynamicDensityFieldWithPitchAngle* density_field, std::string path);
void writeDensity(DynamicDensityField* density_field, std::string path);
void writeDensity(DynamicDensityFieldWithPitchAngle* density_field, std::string path);
void writeTimeInBin(DynamicDensityField* density_field, std::string path);
void writeTimeInBin(DynamicDensityFieldWithPitchAngle* density_field, std::string path);
void writeDeletedParticles(DynamicDensityField* density_field,
std::string path);
void writeDeletedParticles(DynamicDensityFieldWithPitchAngle* density_field,
std::string path);
void writePhysicalTime(DynamicDensityField* density_field, std::string path);
void writePhysicalTime(DynamicDensityFieldWithPitchAngle* density_field, std::string path);
void writeSimulationData(CurrentCollector* current_collector,
std::string species_path,
@@ -94,6 +106,7 @@ class SimulationOutput {
void writeMetaData(DynamicDensityField* density_field, std::string path);
void writeMetaData(CurrentCollector* current_collector, std::string path);
void writeMetaData(PoissonSolver* poisson_solver, std::string path);
void writeMetaData(DynamicDensityFieldWithPitchAngle* density_field, std::string path);
// void writeParameterFile(Parameter* parameter);
void writeCollectorAreas(CurrentCollector* current_collector,
@@ -15,6 +15,11 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
const json_path& path_to_field,
std::shared_ptr<Timer>& timer);
std::shared_ptr<DynamicDensityFieldWithPitchAngle> buildDynamicDensityFieldWithPitchAngle(
Parameter& parameter,
const json_path& path_to_field,
std::shared_ptr<Timer>& timer);
}; // namespace generator
#endif /* DENSITY_FIELD_GENERATOR_H */
+2
View File
@@ -25,6 +25,8 @@ struct TrackedSpeciesBuilderInfo {
std::shared_ptr<DriftVelocity> drift_velocity;
std::shared_ptr<DynamicDensityField> last_sync_density_field;
std::shared_ptr<DynamicDensityField> density_drawing_field;
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_field_pitch_angle;
std::shared_ptr<DynamicDensityFieldWithPitchAngle> pitch_angle_drawing;
double mass_kg;
double charge_C;
+8
View File
@@ -7,6 +7,7 @@
#include "blitz/array.h"
class DynamicDensityField;
class DynamicDensityFieldWithPitchAngle;
class Timer;
class CurrentCollector;
class DeletionLogger;
@@ -26,6 +27,9 @@ class CpuSynchronizer {
void synchronize(DynamicDensityField* field,
DynamicDensityField* density_for_drawing,
bool reset);
void synchronize(DynamicDensityFieldWithPitchAngle* field,
DynamicDensityFieldWithPitchAngle* density_for_drawing,
bool reset);
void synchronize(CurrentCollector* collector);
void synchronize(DeletionLogger* logger);
void synchronize(Timer* timer, Timer* last_sync_timer);
@@ -36,10 +40,14 @@ class CpuSynchronizer {
*/
void sumToAll(blitz::Array<double, 4>& 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,
blitz::Array<double, 3>& last_sync_array);
void sumToAll(blitz::Array<long int, 4>& array,
blitz::Array<long int, 4>& last_sync_array);
void sumToAll(blitz::Array<long int, 5>& array,
blitz::Array<long int, 5>& last_sync_array);
void sumToAll(double& value, double& last_sync_value);
void sumToAll(long int& value, long int& last_sync_value);
};
+85
View File
@@ -105,6 +105,91 @@ class DynamicDensityField : public DensityField {
bool timer_restarted_ = false;
};
// includes a resolution of the pitch angle (i.e. cos(angle(\vec{v}, \vec{B})))
class DynamicDensityFieldWithPitchAngle : public DensityField {
public:
DynamicDensityFieldWithPitchAngle(const CylinderBinning& positionBinning,
const EnergyBinning& energy_binning,
const PitchAngleBinning& pitch_angle_binning,
std::shared_ptr<Timer> timer);
double density(const Coordinate& position);
double density(const Coordinate& position, double energy_eV);
bool changedPositionBin(const Coordinate& old_position,
const Coordinate& new_position) const;
bool changedEnergyBin(double old_energy_eV, double new_energy_eV) const;
void logMovement(const Coordinate& position,
double energy_eV,
double pitch_angle,
double time_in_bin_s);
void logDeletion(const Coordinate& position,
double energy_eV,
double pitch_angle);
double particleNumber();
blitz::TinyVector<double, 5> draw(std::mt19937* engine);
bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const;
blitz::Array<double, 3> densityArray();
blitz::Array<double, 4> spectrumArray();
blitz::Array<double, 5> timeInBinArray() const;
blitz::Array<long int, 5> deletedParticlesArray() const;
blitz::Array<double, 3> binVolumeArray() const;
const EnergyBinning* energyBinning() const;
const CylinderBinning* positionBinning() const;
const PitchAngleBinning* pitchAngleBinning() const;
double physicalTime() const;
double timeResolution() const;
void resetDynamicDensityField();
friend class CpuSynchronizer;
void setDensityDistribution();
void restartTimer(double time, double delta_t);
void restartTimeInBin(blitz::Array<double, 5> time_in_bin);
void restartDeletedParticlesArray(blitz::Array<long int, 5> deleted_particles);
private:
// BinCoordinate densityBin(const CylinderCoordinate& position) const;
void recalculateDensityArray();
void initPositionDistributions();
// use ordering r, phi, z, pitch_angle, E
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<long int, 5> sync_deleted_particles_;
blitz::Array<double, 4> density_per_m3_;
blitz::Array<double, 3> bin_volume_m3_;
const CylinderBinning position_binning_;
const EnergyBinning energy_binning_;
// random distributions for drawing from
std::uniform_real_distribution<double> r_dist_;
std::uniform_real_distribution<double> phi_dist_;
std::uniform_real_distribution<double> z_dist_;
std::uniform_real_distribution<double> density_dist_;
const PitchAngleBinning pitch_angle_binning_;
std::shared_ptr<Timer> timer_;
bool timer_restarted_ = false;
};
class ConstantDensityField : public DensityField {
public:
ConstantDensityField(std::shared_ptr<ScalarField> density);
+18
View File
@@ -18,4 +18,22 @@ class EnergyBinning {
const std::vector<double> energy_bin_borders_;
};
// do a seperate class for the pitchangles now (questionable if it's
// sensible to have it in here)
// might become unneccessary in the future once the option for a linear
// binning in the EnergyBinning class is implemented
class PitchAngleBinning {
public:
PitchAngleBinning(int num_bins);
int bin(double pitch_angle) const;
int numBins() const;
std::vector<double> binBorders() const;
int binIndexMin() const;
int binIndexMax() const;
private:
const std::vector<double> pitch_angle_bin_borders_;
};
#endif /* ENERGY_BINNING_H */
+8
View File
@@ -11,6 +11,7 @@
class DriftVelocity;
class VelocityDistribution;
class DynamicDensityField;
class MagneticField;
namespace particle {
class Particle;
@@ -45,6 +46,13 @@ class Injector {
std::vector<particle::Particle>& queue,
const double weight,
const double injection_time);
void rollNewParticleFromDensityField(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> field,
const double weight,
const double injection_time);
void initInjectionTimeDistribution(double delta_t);
+9 -1
View File
@@ -13,6 +13,7 @@ class Reflector;
class Injector;
class DensityField;
class DynamicDensityField;
class DynamicDensityFieldWithPitchAngle;
class ConstantDensityField;
class DeletionLogger;
class CurrentCollector;
@@ -62,7 +63,9 @@ class TrackedSpecie : public Specie {
std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity,
std::shared_ptr<DynamicDensityField> density_for_drawing);
std::shared_ptr<DynamicDensityField> density_for_drawing,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_field_pitch_angle,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_mu_for_drawing);
DensityField* densityField();
VelocityDistribution* velocityDistibution();
@@ -78,6 +81,9 @@ class TrackedSpecie : public Specie {
DynamicDensityField* densityForDrawing();
DynamicDensityFieldWithPitchAngle* dynamicDensityFieldWithPitchAngle();
DynamicDensityFieldWithPitchAngle* dynamicDensityFieldWithPitchAngleForDrawing();
CurrentCollector* currentCollector();
void currentCollector(std::shared_ptr<CurrentCollector> new_collector);
@@ -86,6 +92,7 @@ class TrackedSpecie : public Specie {
private:
std::shared_ptr<DynamicDensityField> density_field_;
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_field_pitch_angle_;
std::shared_ptr<VelocityDistribution> velocity_distribution_;
std::shared_ptr<DriftVelocity> drift_velocity_;
@@ -98,6 +105,7 @@ class TrackedSpecie : public Specie {
std::vector<std::shared_ptr<interaction::Interaction>> interactions_;
std::shared_ptr<DynamicDensityField> density_for_drawing_;
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_with_pitch_angle_for_drawing;
};
class BackgroundSpecie : public Specie {
+59
View File
@@ -162,6 +162,36 @@ blitz::Array<double, 4> Hdf5Reader::readD4Double(std::string path) {
return data.copy();
}
blitz::Array<double, 5> Hdf5Reader::readD5Double(std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset;
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) {
ERROR("The given dataset could not be opened");
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
const int ndims = H5Sget_simple_extent_ndims(dataspace);
hsize_t dims[ndims];
if (ndims != 5) {
ERROR("The given dataset is not five-dimensional. It has dims: " + ndims);
}
H5Sget_simple_extent_dims(dataspace, dims, NULL);
blitz::Array<double, 5> data(dims[0], dims[1], dims[2], dims[3], dims[4]);
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Fclose(file);
return data.copy();
}
blitz::Array<long int, 4> Hdf5Reader::readD4LongInt(std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
@@ -192,6 +222,35 @@ blitz::Array<long int, 4> Hdf5Reader::readD4LongInt(std::string path) {
return data.copy();
}
blitz::Array<long int, 5> Hdf5Reader::readD5LongInt(std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset;
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
hid_t dataspace = H5Dget_space(dataset);
if (dataset < 0) {
ERROR("The given dataset could not be opened");
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
const int ndims = H5Sget_simple_extent_ndims(dataspace);
hsize_t dims[ndims];
if (ndims != 5) {
ERROR("The given dataset is not five-dimensional. It has dims: " + ndims);
}
H5Sget_simple_extent_dims(dataspace, dims, NULL);
blitz::Array<long int, 5> data(dims[0], dims[1], dims[2], dims[3], dims[4]);
H5Dread(dataset, H5T_NATIVE_LONG, H5S_ALL, H5S_ALL, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Fclose(file);
return data.copy();
}
// reads the engine stringstream with the correct size from the file, such that it should be able
// to be used for the initialization of the random engine without any further modification
+65
View File
@@ -165,6 +165,38 @@ void Hdf5Writer::write(const blitz::Array<double, 4>& data, std::string path) {
H5Fclose(file);
}
void Hdf5Writer::write(const blitz::Array<double, 5>& data, std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
blitz::TinyVector<int, 5> size = data.extent();
blitz::TinyVector<int, 5> start(0, 0, 0, 0, 0);
hid_t filespace =
H5Screate_simple(5, blitz::TinyVector<hsize_t, 5>(size).data(), NULL);
hid_t lcpl = H5Pcreate(H5P_LINK_CREATE);
H5Pset_create_intermediate_group(lcpl, 1);
// turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset;
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
if (dataset < 0) {
dataset = H5Dcreate2(file, path.c_str(), H5T_NATIVE_DOUBLE, filespace, lcpl,
H5P_DEFAULT, H5P_DEFAULT);
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, filespace, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Pclose(lcpl);
H5Sclose(filespace);
H5Fclose(file);
}
void Hdf5Writer::write(const blitz::Array<long int, 4>& data,
std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
@@ -198,6 +230,39 @@ void Hdf5Writer::write(const blitz::Array<long int, 4>& data,
H5Fclose(file);
}
void Hdf5Writer::write(const blitz::Array<long int, 5>& data,
std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
blitz::TinyVector<int, 5> size = data.extent();
blitz::TinyVector<int, 5> start(0, 0, 0, 0, 0);
hid_t filespace =
H5Screate_simple(5, blitz::TinyVector<hsize_t, 5>(size).data(), NULL);
hid_t lcpl = H5Pcreate(H5P_LINK_CREATE);
H5Pset_create_intermediate_group(lcpl, 1);
// turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset;
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
if (dataset < 0) {
dataset = H5Dcreate2(file, path.c_str(), H5T_NATIVE_LONG, filespace, lcpl,
H5P_DEFAULT, H5P_DEFAULT);
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
H5Dwrite(dataset, H5T_NATIVE_LONG, H5S_ALL, H5S_ALL, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Pclose(lcpl);
H5Sclose(filespace);
H5Fclose(file);
}
void Hdf5Writer::write(const blitz::TinyVector<double, 3>& data,
std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
+37 -3
View File
@@ -35,9 +35,19 @@ void Restart::restart(std::map<std::string, std::shared_ptr<species::TrackedSpec
restartTimer(species.begin()->second.get());
for(const auto& pair: species) {
std::string path = pair.second->name() + "/DensityField/SimulationData/" +
restart_identifier_;
restartDrawingDensityField(pair.second->densityForDrawing(), path);
{
std::string path = pair.second->name() + "/DensityField/SimulationData/" +
restart_identifier_;
restartDrawingDensityField(pair.second->densityForDrawing(), path);
}
{
std::string path = pair.second->name() +
"/DensityFieldWithPitchAngle/SimulationData/" +
restart_identifier_;
restartDrawingDensityField(pair.second->dynamicDensityFieldWithPitchAngleForDrawing(),
path);
}
}
}
@@ -121,6 +131,30 @@ void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string
return;
}
void Restart::restartDrawingDensityField(DynamicDensityFieldWithPitchAngle* field, std::string path) {
// restart TimeInBin field
{
std::string path_to_data = path + "/TimeInBin";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<double, 5> time_in_bin = reader_.readD5Double(path_to_data);
field->restartTimeInBin(time_in_bin);
}
// restart deleted particles
{
std::string path_to_data = path + "/DeletedParticles";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<long int, 5> deleted_particles = reader_.readD5LongInt(path_to_data);
field->restartDeletedParticlesArray(deleted_particles);
}
// set the density distribution and calculate the density
{
field->setDensityDistribution();
}
return;
}
// could be removed, but then the potential has to be calculated
// as in the normal simulation cycle
void Restart::restartPoissonSolver(PoissonSolver* solver) {
+107 -3
View File
@@ -46,6 +46,8 @@ void SimulationOutput::writeMetaData(
std::string specie_path = "/" + task.specie_name;
writeMetaData(species.at(task.specie_name)->dynamicDensityField(),
specie_path);
writeMetaData(species.at(task.specie_name)->dynamicDensityFieldWithPitchAngle(),
specie_path);
}
for (auto& task : tasks_current_collector_) {
@@ -60,6 +62,7 @@ void SimulationOutput::writeMetaData(
}
}
}
void SimulationOutput::writeSimulationData(
int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
@@ -70,6 +73,8 @@ void SimulationOutput::writeSimulationData(
for (auto& task : tasks_density_fields_) {
if (cpu_sync % task.intervall == 0) {
std::string specie_path = "/" + task.specie_name;
writeSimulationData(species.at(task.specie_name)->dynamicDensityFieldWithPitchAngle(),
specie_path, cpu_sync, task.overwrite_last);
writeSimulationData(species.at(task.specie_name)->dynamicDensityField(),
specie_path, cpu_sync, task.overwrite_last);
}
@@ -99,7 +104,7 @@ void SimulationOutput::writeSimulationData(
}
// if the rng intervall = 0 (no neg. intervalls allowed) -> no output,
// otherwise the intervall used the same as for the other output
// otherwise the intervall used the same as for the other outputs
if((task_rng_.intervall > 0) && (cpu_sync%task_rng_.intervall == 0)) {
writeRestartData(engine, cpu_sync, task_rng_.overwrite_last);
}
@@ -127,6 +132,28 @@ void SimulationOutput::writeSimulationData(DynamicDensityField* density_field,
writePhysicalTime(density_field, path);
}
void SimulationOutput::writeSimulationData(DynamicDensityFieldWithPitchAngle* density_field,
std::string species_path,
int cpu_sync,
bool overwrite_last) {
std::string sync_path = "SyncPeriod_" + std::to_string(cpu_sync);
if (overwrite_last) {
sync_path = "LastSyncPeriod";
}
std::string path = species_path + "/DensityFieldWithPitchAngle/SimulationData/" + sync_path;
DEBUG_LEVEL_3("Write spectrum.");
writeSpectrum(density_field, path);
DEBUG_LEVEL_3("Write density.");
writeDensity(density_field, path);
DEBUG_LEVEL_3("Write time in bin.");
writeTimeInBin(density_field, path);
DEBUG_LEVEL_3("Write deleted particles.");
writeDeletedParticles(density_field, path);
DEBUG_LEVEL_3("Write physical time.");
writePhysicalTime(density_field, path);
}
void SimulationOutput::writeSimulationData(CurrentCollector* current_collector,
std::string species_path,
int cpu_sync,
@@ -188,8 +215,6 @@ void SimulationOutput::writeRestartData(std::mt19937* engine, int cpu_sync,
void SimulationOutput::writeRandomEngineState(std::mt19937* engine, std::string path) {
std::ostringstream engine_state;
engine_state << (*engine);
DEBUG_LEVEL_0(std::to_string(engine_state.str().size()));
DEBUG_LEVEL_0(std::to_string(sizeof(*engine)));
writer.writeRNG(engine_state.str(), path);
}
@@ -248,23 +273,55 @@ void SimulationOutput::writeSpectrum(DynamicDensityField* density_field,
writer.write(density_field->spectrumArray(), path + "/Spectrum");
}
void SimulationOutput::writeSpectrum(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
writer.write(density_field->spectrumArray(), path + "/Spectrum");
}
void SimulationOutput::writeDensity(DynamicDensityField* density_field,
std::string path) {
writer.write(density_field->densityArray(), path + "/Density");
}
void SimulationOutput::writeDensity(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
writer.write(density_field->densityArray(), path + "/Density");
}
void SimulationOutput::writeTimeInBin(DynamicDensityField* density_field,
std::string path) {
writer.write(density_field->timeInBinArray(), path + "/TimeInBin");
}
void SimulationOutput::writeTimeInBin(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
writer.write(density_field->timeInBinArray(), path + "/TimeInBin");
}
void SimulationOutput::writeDeletedParticles(DynamicDensityField* density_field,
std::string path) {
writer.write(density_field->deletedParticlesArray(),
path + "/DeletedParticles");
}
void SimulationOutput::writeDeletedParticles(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
writer.write(density_field->deletedParticlesArray(),
path + "/DeletedParticles");
}
void SimulationOutput::writePhysicalTime(DynamicDensityField* density_field,
std::string path) {
writer.write(density_field->physicalTime(), path + "/PhysicalTime");
}
void SimulationOutput::writePhysicalTime(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
writer.write(density_field->physicalTime(), path + "/PhysicalTime");
}
void SimulationOutput::writePotential(PoissonSolver* poisson_solver, std::string path) {
writer.write(poisson_solver->potential(), path + "/Potential");
}
@@ -285,6 +342,53 @@ void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
writeNumBins(density_field, path_to_field);
}
void SimulationOutput::writeMetaData(DynamicDensityFieldWithPitchAngle* density_field,
std::string path) {
std::string path_to_field = path + "/DensityFieldWithPitchAngle";
// write bin volumes
{
std::string path_to_volume = path_to_field + "/BinVolumes";
writer.write(density_field->binVolumeArray(), path_to_volume);
}
// write bin borders
{
std::string path_to_bin_borders = path_to_field + "/BinBorders";
std::vector<double> energy_bin_borders =
density_field->energyBinning()->binBorders();
writer.write(energy_bin_borders, path_to_bin_borders + "/energy");
std::vector<double> mu_bin_borders =
density_field->pitchAngleBinning()->binBorders();
writer.write(mu_bin_borders, path_to_bin_borders + "/pitchAngle");
std::vector<double> radial_bin_borders =
density_field->positionBinning()->radial_binning.binBorders();
writer.write(radial_bin_borders, path_to_bin_borders + "/radial");
std::vector<double> azimuth_bin_borders =
density_field->positionBinning()->azimuth_binning.binBorders();
writer.write(azimuth_bin_borders, path_to_bin_borders + "/azimuth");
std::vector<double> longitudinal_bin_borders =
density_field->positionBinning()->longitudinal_binning.binBorders();
writer.write(longitudinal_bin_borders, path_to_bin_borders + "/longitudinal");
}
// write num bins
{
std::string path_to_num_bins = path_to_field + "/NumBins";
blitz::TinyVector<int, 4> num_bins = density_field->spectrumArray().extent();
writer.write(num_bins(0), path_to_num_bins + "/energy");
writer.write(num_bins(1), path_to_num_bins + "/radial");
writer.write(num_bins(2), path_to_num_bins + "/azimuthal");
writer.write(num_bins(3), path_to_num_bins + "/longitudinal");
}
}
void SimulationOutput::writeMetaData(CurrentCollector* current_collector,
std::string path) {
std::string path_to_collector = path + "/CurrentCollector";
@@ -33,4 +33,25 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
new DynamicDensityField(position_binning, energy_binning, timer));
}
std::shared_ptr<DynamicDensityFieldWithPitchAngle> buildDynamicDensityFieldWithPitchAngle(
Parameter& parameter,
const json_path& path_to_field,
std::shared_ptr<Timer>& timer) {
DEBUG_LEVEL_2("Creating dynamic density field with pitch angle.");
json_path path_binning = json_path_append(path_to_field, {"PositionBinning"});
CylinderBinning position_binning =
buildPositionBinningIncludingRedirection(parameter, path_binning);
json_path path_energy_binning =
json_path_append(path_to_field, {"EnergyBinning"});
EnergyBinning energy_binning =
buildEnergyBinningIncludingRedirection(parameter, path_energy_binning);
// TBD: make a function to build the pitchangle binning
PitchAngleBinning pitch_angle_binning =
PitchAngleBinning(10);
return std::shared_ptr<DynamicDensityFieldWithPitchAngle>(
new DynamicDensityFieldWithPitchAngle(position_binning, energy_binning,
pitch_angle_binning, timer));
}
}; // namespace generator
+14 -1
View File
@@ -250,6 +250,7 @@ void SpeciesBuilder::fillReflector(Parameter& parameter) {
}
}
// TBD: Fill and create dynamic density fields with pitch angle distribution
void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
DEBUG_LEVEL_2("Fill tracked density.");
for (auto& b : tracked_species_info) {
@@ -265,6 +266,16 @@ void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
json_path_append(b.second.path_in_json,
{"DensityField", "DynamicDensityField"}),
timer_);
b.second.density_field_pitch_angle = buildDynamicDensityFieldWithPitchAngle(
parameter,
json_path_append(b.second.path_in_json, {"DensityField", "DynamicDensityField"}),
timer_);
b.second.pitch_angle_drawing = buildDynamicDensityFieldWithPitchAngle(
parameter,
json_path_append(b.second.path_in_json, {"DensityField", "DynamicDensityField"}),
timer_);
}
}
@@ -284,7 +295,9 @@ void SpeciesBuilder::buildSpecies() {
b.second.type, b.second.name, b.second.mass_kg, b.second.charge_C,
b.second.mover, b.second.terminator, b.second.reflector,
b.second.density_field, b.second.velocity_distribution,
b.second.drift_velocity, b.second.density_drawing_field));
b.second.drift_velocity, b.second.density_drawing_field,
b.second.density_field_pitch_angle,
b.second.pitch_angle_drawing));
}
}
+39 -4
View File
@@ -17,6 +17,16 @@ void CpuSynchronizer::sumToAll(blitz::Array<double, 4>& array,
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<double, 5>& array,
blitz::Array<double, 5>& last_sync_array) {
int size = array.size();
blitz::Array<double, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_DOUBLE,
MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
blitz::Array<long int, 4>& last_sync_array) {
int size = array.size();
@@ -27,6 +37,16 @@ void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<long int, 5>& array,
blitz::Array<long int, 5>& last_sync_array) {
int size = array.size();
blitz::Array<long int, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_LONG,
MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<double, 3>& array,
blitz::Array<double, 3>& last_sync_array) {
int size = array.size();
@@ -86,6 +106,22 @@ void CpuSynchronizer::synchronize(DynamicDensityField* field,
}
}
void CpuSynchronizer::synchronize(DynamicDensityFieldWithPitchAngle* field,
DynamicDensityFieldWithPitchAngle* density_for_drawing,
bool reset) {
if (field) {
sumToAll(field->time_in_bin_s_, field->sync_time_in_bin_s_);
field->time_in_bin_s_ = field->sync_time_in_bin_s_;
sumToAll(field->deleted_particles_, field->sync_deleted_particles_);
field->deleted_particles_ = field->sync_deleted_particles_;
}
if (reset) {
density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_;
density_for_drawing->deleted_particles_ = field->deleted_particles_;
density_for_drawing->setDensityDistribution();
}
}
void CpuSynchronizer::synchronize(CurrentCollector* collector) {
if (collector) {
sumToAll(collector->z_negative_crossings,
@@ -139,15 +175,14 @@ void CpuSynchronizer::synchronize(
tracked_species, bool reset) {
MPI_Barrier(MPI_COMM_WORLD);
auto it = tracked_species.begin();
// drops due to time being a global variable now
//DEBUG_LEVEL_3("Timer Synchronization.");
//synchronize(it->second->dynamicDensityField()->timer_.get(),
// it->second->lastSyncDensityField()->timer_.get());
for (auto& pair : tracked_species) {
// DEBUG_LEVEL_3("dynden Synchronization.");
synchronize(pair.second->dynamicDensityField(),
pair.second->densityForDrawing(), reset);
synchronize(pair.second->dynamicDensityFieldWithPitchAngle(),
pair.second->dynamicDensityFieldWithPitchAngleForDrawing(),
reset);
// DEBUG_LEVEL_3("cc Synchronization.");
synchronize(pair.second->currentCollector());
// DEBUG_LEVEL_3("dellogger Synchronization.");
+420
View File
@@ -4,6 +4,7 @@
#include "simulation/errors.h"
#include "simulation/event_position_distribution.h"
#include "simulation/scalar_field.h"
#include "simulation/kinematic.h"
template <class T>
blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
@@ -15,6 +16,17 @@ blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
return data.copy();
}
template<class T>
blitz::Array<T, 5> initiate5DArray(blitz::Range radial,
blitz::Range phi,
blitz::Range longitudinal,
blitz::Range pitch_angle,
blitz::Range energy) {
blitz::Array<T, 5> data(radial, phi, longitudinal, pitch_angle, energy);
data = static_cast<T>(0);
return data.copy();
}
blitz::Array<double, 3> initiateVolumeArray(
blitz::Range radial,
blitz::Range phi,
@@ -131,6 +143,11 @@ void DynamicDensityField::logMovement(const Coordinate& position,
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
// std::stringstream out;
// out << "Energy bin " << energy_bin << "\n";
// out << "time in bin" << time_in_bin_s;
// DEBUG_LEVEL_3(out.str());
time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
energy_bin) += time_in_bin_s;
}
@@ -364,6 +381,409 @@ void DynamicDensityField::restartDeletedParticlesArray(
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// TBD
DynamicDensityFieldWithPitchAngle::DynamicDensityFieldWithPitchAngle(
const CylinderBinning& position_binning,
const EnergyBinning& energy_binning,
const PitchAngleBinning& pitch_angle_binning,
std::shared_ptr<Timer> timer) :
position_binning_(position_binning),
energy_binning_(energy_binning),
pitch_angle_binning_(pitch_angle_binning),
timer_(timer),
time_in_bin_s_(initiate5DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
sync_time_in_bin_s_(initiate5DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
deleted_particles_(initiate5DArray<long int>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
sync_deleted_particles_(initiate5DArray<long int>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
density_per_m3_(initiate4DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))),
bin_volume_m3_(initiateVolumeArray(
blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
position_binning.stepsize())) {
if(!timer) {
ERROR("Timer is necessary for calculation of density field");
}
initPositionDistributions();
}
double DynamicDensityFieldWithPitchAngle::density(const Coordinate& position) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const double t = timer_->getDeltaT();
const double time_in_bin = blitz::sum(time_in_bin_s_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), blitz::Range::all()));
const long int deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), blitz::Range::all()));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
double DynamicDensityFieldWithPitchAngle::density(const Coordinate& position,
double energy_eV) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
const double t = timer_->getDeltaT();
const double time_in_bin = blitz::sum(time_in_bin_s_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), energy_bin));
const long deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), energy_bin));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
bool DynamicDensityFieldWithPitchAngle::changedPositionBin(
const Coordinate& old_position,
const Coordinate& new_position) const {
const blitz::TinyVector<int, 3> old_bin =
position_binning_.bin(old_position.cylinderEntries());
const blitz::TinyVector<int, 3> new_bin =
position_binning_.bin(new_position.cylinderEntries());
return !((old_bin(0) == new_bin(0)) && (old_bin(1) == new_bin(1)) &&
(old_bin(2) == new_bin(2)));
}
bool DynamicDensityFieldWithPitchAngle::changedEnergyBin(
double old_energy_eV,
double new_energy_eV) const {
const int old_bin = energy_binning_.bin(old_energy_eV);
const int new_bin = energy_binning_.bin(new_energy_eV);
return !(old_bin == new_bin);
}
bool DynamicDensityFieldWithPitchAngle::changedPitchAngleBin(
double old_mu,
double new_mu) const {
const int old_bin = pitch_angle_binning_.bin(old_mu);
const int new_bin = pitch_angle_binning_.bin(new_mu);
if(!(old_bin == new_bin)) {
DEBUG_LEVEL_3("old mu: " + std::to_string(old_mu));
DEBUG_LEVEL_3("old bin: " + std::to_string(old_bin));
DEBUG_LEVEL_3("new mu: " + std::to_string(new_mu));
DEBUG_LEVEL_3("new bin: " + std::to_string(new_bin));
}
return !(old_bin == new_bin);
}
void DynamicDensityFieldWithPitchAngle::logMovement(
const Coordinate& position,
double energy_eV,
double pitch_angle,
double time_in_bin_s) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle);
// std::stringstream out;
// out << "Energy bin " << energy_bin << "\n";
// out << "Pitch angle: " << pitch_angle << "\n";
// out << "Pitch angle bin: " << pitch_angle_bin << "\n";
// out << "time in bin " << time_in_bin_s;
// DEBUG_LEVEL_3(out.str());
time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
pitch_angle_bin, energy_bin) += time_in_bin_s;
}
void DynamicDensityFieldWithPitchAngle::logDeletion(
const Coordinate& position,
double energy_eV,
double pitch_angle) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV);
const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle);
deleted_particles_(position_bin(0), position_bin(1), position_bin(2), pitch_angle_bin,
energy_bin) += 1;
return;
}
blitz::Array<double, 3> DynamicDensityFieldWithPitchAngle::densityArray() {
DEBUG_LEVEL_3("recalc Density array");
recalculateDensityArray();
blitz::Array<double, 3> density(density_per_m3_(
blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0));
blitz::fourthIndex iE;
DEBUG_LEVEL_3("density sum");
density = blitz::sum(density_per_m3_, iE);
return density.copy();
}
blitz::Array<double, 4> DynamicDensityFieldWithPitchAngle::spectrumArray() {
recalculateDensityArray();
return density_per_m3_;
}
blitz::Array<double, 5> DynamicDensityFieldWithPitchAngle::timeInBinArray() const {
return time_in_bin_s_;
}
blitz::Array<long int, 5> DynamicDensityFieldWithPitchAngle::deletedParticlesArray() const {
return deleted_particles_;
}
blitz::Array<double, 3> DynamicDensityFieldWithPitchAngle::binVolumeArray() const {
return bin_volume_m3_;
}
const EnergyBinning* DynamicDensityFieldWithPitchAngle::energyBinning() const {
return &energy_binning_;
}
const CylinderBinning* DynamicDensityFieldWithPitchAngle::positionBinning() const {
return &position_binning_;
}
const PitchAngleBinning* DynamicDensityFieldWithPitchAngle::pitchAngleBinning() const {
return &pitch_angle_binning_;
}
double DynamicDensityFieldWithPitchAngle::physicalTime() const {
return timer_->time();
}
double DynamicDensityFieldWithPitchAngle::timeResolution() const {
return timer_->getDeltaT();
}
void DynamicDensityFieldWithPitchAngle::recalculateDensityArray() {
blitz::firstIndex ir;
blitz::secondIndex iphi;
blitz::thirdIndex iz;
blitz::fourthIndex ipitch;
blitz::fifthIndex iE;
const double t = timer_->getDeltaT();
// reduction only seems to work for the last dimension (iE)
// -> first reorder (by exchanging iE and ipitch) and afterwards doing
// the reduction over iE (which now contains the pitch dimension)
// blitz::Array<double, 5> temp((time_in_bin_s_(ir, iphi, iz, ipitch, iE)));
density_per_m3_ = blitz::sum((time_in_bin_s_(ir, iphi, iz, iE, ipitch) / t -
deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) /
bin_volume_m3_(ir, iphi, iz);
}
void DynamicDensityFieldWithPitchAngle::setDensityDistribution() {
density_dist_ =
std::uniform_real_distribution<double>(0., blitz::max(densityArray()));
}
double DynamicDensityFieldWithPitchAngle::particleNumber() {
blitz::Array<double, 3> density = densityArray();
double particleNumber = blitz::sum(density * bin_volume_m3_);
DEBUG_LEVEL_3("particle number: " + std::to_string(particleNumber));
return particleNumber;
}
void DynamicDensityFieldWithPitchAngle::initPositionDistributions() {
double rmin, rmax;
double phimin, phimax;
double zmin, zmax;
auto rbins = position_binning_.radial_binning.binBorders();
auto zbins = position_binning_.longitudinal_binning.binBorders();
auto phibins = position_binning_.azimuth_binning.binBorders();
rmin = rbins.front();
rmax = rbins.back();
DEBUG_LEVEL_3("rmax: " + std::to_string(rmax));
zmin = zbins.front();
zmax = zbins.back();
DEBUG_LEVEL_3("zmax: " + std::to_string(zmax));
phimin = phibins.front();
phimax = phibins.back();
DEBUG_LEVEL_3("phimax: " + std::to_string(phimax));
r_dist_ = std::uniform_real_distribution<double>(rmin*rmin, rmax*rmax);
phi_dist_ = std::uniform_real_distribution<double>(phimin, phimax);
z_dist_ = std::uniform_real_distribution<double>(zmin, zmax);
}
// don't know if it's even good to have the drawing stuff in the
// density distributions...
blitz::TinyVector<double, 5> DynamicDensityFieldWithPitchAngle::
draw(std::mt19937* engine) {
recalculateDensityArray();
if (isEqual(blitz::max(density_per_m3_), 0.)) {
DEBUG_LEVEL_3("Density is empty");
return blitz::TinyVector<double, 5> (0,0,0,0,0);
}
// setDensityDistribution();
double random_r, random_z, random_phi, random_E, random_n;
double density_in_random_cell;
do {
DEBUG_LEVEL_3("Missed.");
random_r = std::sqrt(r_dist_(*engine));
random_phi = phi_dist_(*engine);
random_z = z_dist_(*engine);
random_n = density_dist_(*engine);
density_in_random_cell = density(CylinderCoordinate(
blitz::TinyVector<double, 3> (random_r, random_phi, random_z)));
DEBUG_LEVEL_3("Density in drawn cell: " + std::to_string(density_in_random_cell));
DEBUG_LEVEL_3("drawn density: " + std::to_string(random_n));
} while (random_n >= density_in_random_cell);
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(CylinderCoordinate(
blitz::TinyVector<double, 3> (random_r, random_phi, random_z))
.cylinderEntries());
std::vector<double> energyBins = energy_binning_.binBorders();
energyBins.insert(energyBins.begin(), 0.);
blitz::Array<double, 1> densityAtPosition = density_per_m3_(position_bin(0),
position_bin(1),
position_bin(2),
blitz::Range::all());
std::piecewise_constant_distribution<double> E_dist_(energyBins.begin(),
energyBins.end(),
densityAtPosition.begin());
random_E = E_dist_(*engine);
DEBUG_LEVEL_3("energy: " + std::to_string(random_E));
const int energy_bin = energy_binning_.bin(random_E);
std::vector<double> mu_bins = pitch_angle_binning_.binBorders();
DEBUG_LEVEL_3("Size pitchangle binning: " + std::to_string(mu_bins.size()));
DEBUG_LEVEL_3("Size timeinbin: " + std::to_string(time_in_bin_s_.extent(3)));
auto test = time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range(0, pitch_angle_binning_.binIndexMax()-1),
energy_bin);
// remove the under- and overflow bins for the constant distribution
// for now use only the time_in_bin_s_ array (should make no difference but might be worse?)
std::piecewise_constant_distribution<double> mu_distribution(
mu_bins.begin(), mu_bins.end(), test.begin());
double random_mu = mu_distribution(*engine);
return blitz::TinyVector<double, 5> (random_r, random_phi, random_z, random_mu, random_E);
}
void DynamicDensityFieldWithPitchAngle::resetDynamicDensityField() {
//timer_->resetTime(); // time stays global
time_in_bin_s_ = 0.;
deleted_particles_ = 0.;
density_per_m3_ = 0.;
sync_time_in_bin_s_ = 0.;
sync_deleted_particles_ = 0.;
}
void DynamicDensityFieldWithPitchAngle::restartTimer(double time, double delta_t) {
// make sure that the timer can only be restarted once (per dynamicDensityField object)
// probably not necessary, but whatever...
if(timer_restarted_) {
return;
}
timer_restarted_ = true;
timer_->setTime(time);
timer_->setDeltaT(delta_t);
}
void DynamicDensityFieldWithPitchAngle::restartTimeInBin(blitz::Array<double, 5> time_in_bin) {
if(!blitz::all(time_in_bin_s_.length() == time_in_bin.length())) {
std::stringstream out;
out << "Expected a size of " << time_in_bin_s_.length();
out << ", received a length of " << time_in_bin.length();
out << " for time_in_bin array";
ERROR(out.str());
}
time_in_bin_s_ = time_in_bin.copy().reindex(time_in_bin_s_.lbound());
}
void DynamicDensityFieldWithPitchAngle::restartDeletedParticlesArray(
blitz::Array<long int, 5> deleted_particles) {
if(!blitz::all(deleted_particles_.length() == deleted_particles.length())) {
std::stringstream out;
out << "Expected a size of " << deleted_particles_.length();
out << ", received a length of " << deleted_particles.length();
out << " for deleted_particles array";
ERROR(out.str());
}
deleted_particles_ = deleted_particles.copy().reindex(deleted_particles_.lbound());
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
ConstantDensityField::ConstantDensityField(std::shared_ptr<ScalarField> density)
: density_(density) {}
+43 -3
View File
@@ -2,8 +2,7 @@
#include <math.h>
#include <algorithm>
// probably rename to indicate what type of borders are created
std::vector<double> generateBinBorders(double bin_min,
std::vector<double> generateLogBinBorders(double bin_min,
double bin_max,
int num_bins) {
const double min_bin_log = log10(bin_min);
@@ -18,11 +17,25 @@ std::vector<double> generateBinBorders(double bin_min,
return bin_borders;
}
std::vector<double> generateLinearBinBorders(double bin_min,
double bin_max,
int num_bins) {
const double bin_size = (bin_max - bin_min) / num_bins;
std::vector<double> bin_borders;
for (int i = 0; i <= num_bins; ++i) {
const double bin_border = bin_size * i + bin_min;
bin_borders.push_back(bin_border);
}
return bin_borders;
}
EnergyBinning::EnergyBinning(double minimal_energy,
double maximal_energy,
int num_bins)
: energy_bin_borders_(
generateBinBorders(minimal_energy, maximal_energy, num_bins)) {}
generateLogBinBorders(minimal_energy, maximal_energy, num_bins)) {}
EnergyBinning::EnergyBinning(std::vector<double> energy_bin_borders)
: energy_bin_borders_(energy_bin_borders) {}
@@ -48,3 +61,30 @@ int EnergyBinning::binIndexMin() const {
int EnergyBinning::binIndexMax() const {
return numBins();
}
PitchAngleBinning::PitchAngleBinning(int num_bins) :
pitch_angle_bin_borders_(generateLinearBinBorders(-1, 1, num_bins)) {}
int PitchAngleBinning::bin(double pitch_angle) const {
auto const it = std::lower_bound(pitch_angle_bin_borders_.begin(),
pitch_angle_bin_borders_.end(),
pitch_angle);
return (it - pitch_angle_bin_borders_.begin()) - 1;
}
int PitchAngleBinning::numBins() const {
return pitch_angle_bin_borders_.size() - 1;
}
std::vector<double> PitchAngleBinning::binBorders() const {
return pitch_angle_bin_borders_;
}
int PitchAngleBinning::binIndexMin() const {
return -1;
}
int PitchAngleBinning::binIndexMax() const {
return numBins();
}
+63 -3
View File
@@ -8,8 +8,20 @@
#include "simulation/species.h"
#include "simulation/density_field.h"
#include "simulation/velocity_distribution.h"
#include "simulation/electromagnetic_field.h"
#include <sstream>
blitz::TinyVector<double, 3> perpendicularNormalVector(blitz::TinyVector<double, 3> vector) {
blitz::TinyVector<double, 3> result(0,0,0);
result[0] = std::copysign(vector[2], vector[0]);
result[1] = std::copysign(vector[2], vector[1]);
result[2] = - std::copysign(std::fabs(vector[0] + std::fabs(vector[1])), vector[2]);
// DEBUG_LEVEL_3("dot product: " + std::to_string(blitz::dot(result, vector)));
return result / kinematic::norm(result);
}
Injector::Injector(
std::vector<InjectorInfo>& injector_info,
double activity,
@@ -104,9 +116,57 @@ void Injector::rollNewParticleFromDensityField(std::mt19937* engine,
std::cos(phi));
particle::Particle drawn_particle(specie, CylinderCoordinate(
blitz::TinyVector<double, 3>(particle_specs[0],
particle_specs[1], particle_specs[2])),
CartesianVector(v_normal*v_abs), injection_time, weight);
blitz::TinyVector<double, 3>(particle_specs[0],
particle_specs[1], particle_specs[2])),
CartesianVector(v_normal*v_abs), injection_time, weight);
queue.push_back(drawn_particle);
}
void Injector::rollNewParticleFromDensityField(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> magnetic_field,
const double weight,
const double injection_time) {
blitz::TinyVector<double, 5> particle_specs =
specie->dynamicDensityFieldWithPitchAngleForDrawing()->draw(engine);
// check if density was empty (i.e. Energy component is 0)
if (particle_specs[4] == 0) {
DEBUG_LEVEL_3(specie->name() + ": has zero density");
return;
}
DEBUG_LEVEL_3("Injected z position: " + std::to_string(particle_specs(2)));
DEBUG_LEVEL_3("Injected r position: " + std::to_string(particle_specs(0)));
CylinderCoordinate position(blitz::TinyVector<double, 3>(particle_specs[0],
particle_specs[1],
particle_specs[2]));
const double v_abs = kinematic::velocity(particle_specs[4], specie->mass_kg());
std::uniform_real_distribution<double> distribution(0.0, 1.0);
const double theta = distribution(*engine) * 2 * M_PI;
const double mu = particle_specs[3];
DEBUG_LEVEL_3("mu: " + std::to_string(mu));
blitz::TinyVector<double, 3> magnetic_field_value = magnetic_field->
value(position).cartesianEntries(position);
const double abs_B = kinematic::norm(magnetic_field_value);
blitz::TinyVector<double, 3> perpendicular_vector =
perpendicularNormalVector(magnetic_field_value);
blitz::TinyVector<double, 3> v_normal = mu*magnetic_field_value/abs_B +
std::sqrt(1-mu*mu)*kinematic::rotateVector(perpendicular_vector,
magnetic_field_value,
theta);
particle::Particle drawn_particle(specie, position,
CartesianVector(v_normal*v_abs), injection_time, weight);
queue.push_back(drawn_particle);
}
+26 -1
View File
@@ -13,6 +13,12 @@
#include "tools/simulation_time.h"
double cosAngleBetweenVectors(blitz::TinyVector<double, 3> vector_1,
blitz::TinyVector<double, 3> vector_2) {
const double divisor = kinematic::norm(vector_1) * kinematic::norm(vector_2);
return blitz::dot(vector_1, vector_2)/divisor;
}
BorisMover::BorisMover(double maximal_time_step_s)
: maximal_time_step_s_(maximal_time_step_s) {
ASSERT_POSITIVE(&maximal_time_step_s_,
@@ -180,9 +186,13 @@ void DriftMover::move(particle::Particle* particle,
auto old_position = particle->position();
auto old_velocity = particle->velocity();
double old_kinetic_energy = particle->kineticEnergy_eV();
double old_mu = cosAngleBetweenVectors(
magnetic_field->value(old_position).cartesianEntries(old_position),
old_velocity.cartesianEntries(old_position));
bool changed_position_bin = false;
bool changed_energy_bin = false;
bool changed_mu_bin = false;
bool left_simulation_domain = false;
// if particle too slow -> timestep > maximum time the particle lives
// -> add maximal timestep to time in bin and stop moving the particle
@@ -193,7 +203,8 @@ void DriftMover::move(particle::Particle* particle,
particle->timeAlive();
while (
!(changed_position_bin || changed_energy_bin || left_simulation_domain) &&
!(changed_position_bin || changed_energy_bin || changed_mu_bin
|| left_simulation_domain) &&
(leftover_distance > 0.) && !(died_in_bin)) {
old_position = particle->position();
old_velocity = particle->velocity();
@@ -342,6 +353,18 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->changedEnergyBin(
old_kinetic_energy, particle->kineticEnergy_eV());
const double new_mu = cosAngleBetweenVectors(magnetic_field
->value(new_position).cartesianEntries(new_position),
particle->velocity().cartesianEntries(new_position));
changed_mu_bin = particle->specie()->dynamicDensityFieldWithPitchAngle()
->changedPitchAngleBin(old_mu, new_mu);
if(changed_mu_bin) {
DEBUG_LEVEL_3("cos(pitch old): " + std::to_string(old_mu));
DEBUG_LEVEL_3("cos(pitch new): " + std::to_string(new_mu));
}
left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle);
@@ -350,6 +373,8 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, particle->timeInBin());
particle->specie()->dynamicDensityFieldWithPitchAngle()->logMovement(
old_position, old_kinetic_energy, old_mu, particle->timeInBin());
particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position);
}
+62 -19
View File
@@ -109,21 +109,44 @@ void Simulation::start() {
const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
const int total_simulated_events =
parameter_.intValue(json_path({"Simulation", "SimulatedEvents"}), 1);
// const int total_simulated_events =
// parameter_.intValue(json_path({"Simulation", "SimulatedEvents"}), 1);
const int number_timesteps = parameter_.intValue(json_path({"Simulation",
"NumberTimesteps"}), 1);
const int time_resolution_events =
parameter_.intValue(json_path({"Simulation", "TimeResolutionEvents"}),
total_simulated_events);
MpiCommunication::mpiSize());
const int density_events =
parameter_.intValue(json_path({"Simulation", "DensityEventsPerCPU"}), 0);
DEBUG_LEVEL_0("Density events per cpu: " + std::to_string(density_events));
SIM_INFO("Total simulated events: " + std::to_string(total_simulated_events));
// if(total_simulated_events % MpiCommunication::mpiSize() != 0) {
// ERROR("total simulated events are not divisible by the number of mpi procs");
// }
// if(time_resolution_events % MpiCommunication::mpiSize() != 0) {
// ERROR("time resolution events are not divisible by the number of mpi procs");
// }
// SIM_INFO("Total simulated events: " + std::to_string(total_simulated_events));
SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps));
SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride));
const int events_this_cpu = eventsThisCpu(total_simulated_events);
// const int events_this_cpu = eventsThisCpu(total_simulated_events);
const int time_resolution_this_cpu = eventsThisCpu(time_resolution_events);
SIM_INFO("Events per cpu (approx.): " + std::to_string(events_this_cpu));
int leftover_events = events_this_cpu;
if(time_resolution_events % MpiCommunication::mpiSize() != 0) {
if(time_resolution_events % MpiCommunication::mpiSize() <= MpiCommunication::mpiRank() &&
time_resolution_this_cpu % event_stride == 0) {
ERROR("Code will not terminate! The event stride: " + std::to_string(event_stride) +
", the number of CPUs: " + std::to_string(MpiCommunication::mpiSize()) +
" and the number of events per timestep: " + std::to_string(time_resolution_events) +
" create at least one CPU for which the number of CPU syncs for one timestep " +
" differs from the rest of the CPUs.");
}
}
SIM_INFO("Events per cpu (approx.) per timestep: " +
std::to_string(time_resolution_this_cpu));
// int leftover_events = events_this_cpu;
int leftover_events_time_resolution = time_resolution_this_cpu;
const double delta_t = time_resolution_events*injector_->timePassed();
@@ -154,25 +177,34 @@ void Simulation::start() {
int num_cpu_syncs = 0;
bool reset = true;
int timesteps = 0;
queue_.reserve(100);
timer_->increaseTimestep(delta_t);
while (leftover_events > 0) {
while (timesteps < number_timesteps) {
std::stringstream out;
out << "Timeinterval: " << timer_->time() << "s.";
// out << "\n size of particle: " << sizeof(particle::Particle);
DEBUG_LEVEL_3(out.str());
int events_of_cylcle = eventsOfCycle(event_stride, leftover_events_time_resolution);
SIM_INFO("Leftover events on first cpu: " +
std::to_string(leftover_events));
SIM_INFO("Leftover timesteps this CPU: " + std::to_string(number_timesteps - timesteps));
SIM_INFO("Leftover events this timestep this CPU: " +
std::to_string(leftover_events_time_resolution));
processEvents(events_of_cylcle, density_events, num_cpu_syncs);
DEBUG_LEVEL_1("Leftover events: " + std::to_string(leftover_events));
leftover_events -= events_of_cylcle;
DEBUG_LEVEL_1("Leftover timesteps: " + std::to_string(number_timesteps - timesteps));
DEBUG_LEVEL_1("Leftover events this timestep: " +
std::to_string(leftover_events_time_resolution));
// leftover_events -= events_of_cylcle;
leftover_events_time_resolution -= events_of_cylcle;
// Problem: proc 0: simuliert erst 2 dann 1
// proc 1: simuliert nur 2
// timestep besteht aus (2+1) + 2, aber die jetzt wird es noch zu
// 2 + 2, 1 + 2, in den syncs, das führt dazu, dass jede sync von proc 1
// als timestep gezählt wird, während proc 0 nur jede 2. sync eine timestep ist
reset = !(leftover_events_time_resolution > 0);
SIM_INFO("Cpu sync.");
@@ -208,6 +240,7 @@ void Simulation::start() {
timer_->increaseTimestep(delta_t);
for(auto& pair : tracked_species_) {
pair.second->dynamicDensityField()->resetDynamicDensityField();
pair.second->dynamicDensityFieldWithPitchAngle()->resetDynamicDensityField();
// questionable if they need to be reset:
// + time res in current
@@ -219,6 +252,7 @@ void Simulation::start() {
// pair.second->deletionLogger()->resetDeletionLogger();
}
leftover_events_time_resolution = time_resolution_this_cpu;
timesteps++;
}
}
}
@@ -263,7 +297,8 @@ void Simulation::processEvents(int events, int density_events, int cpu_syncs) {
std::to_string(current_density_event));
//maybe use a different event name?
SimulationTimer::eventStartPoint(std::string("DensityParticleInjection"));
new_particles = determineInjectedDensityParticles(random_.get(), density_events, current_density_event);
new_particles = determineInjectedDensityParticles(random_.get(), density_events,
current_density_event);
SimulationTimer::eventStopPoint(std::string("DensityParticleInjection"));
#if defined debug_level3
for(auto& particle : new_particles) {
@@ -456,19 +491,27 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
// which does not change except after a timestep, but think the rejection method is
// much more time consuming anyways... might optimize in the future
// particle number of the denstiy, i.e. the integral over the density
const double particleNumberDensity =
const double particleNumberFromDensity =
pair.second->densityForDrawing()->particleNumber();
if (particleNumberDensity == 0) {
const double particleNumberFromDensity_ =
pair.second->dynamicDensityFieldWithPitchAngleForDrawing()->particleNumber();
if (particleNumberFromDensity == 0) {
DEBUG_LEVEL_3("No particles in density of species: " + pair.second->name());
continue;
}
if (current == 0) {
DEBUG_LEVEL_0("particle number " + pair.second->name() + ": " + std::to_string(particleNumberDensity));
if (current == 0 || true) {
std::stringstream out;
out << pair.second->name();
out << "difference: ";
out << std::fabs(particleNumberFromDensity_ - particleNumberFromDensity)/particleNumberFromDensity;
DEBUG_LEVEL_0(out.str());
}
injector_->rollNewParticleFromDensityField(random->engine(),
pair.second,
new_particles,
particleNumberDensity/numberParticlesToDraw/MpiCommunication::mpiSize(),
new_particles,
magnetic_field_,
particleNumberFromDensity/numberParticlesToDraw/MpiCommunication::mpiSize(),
injection_time);
}
return new_particles;
+15 -4
View File
@@ -41,9 +41,10 @@ TrackedSpecie::TrackedSpecie(
std::shared_ptr<Reflector> reflector,
std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity,
// std::shared_ptr<DynamicDensityField> last_sync_density_field,
std::shared_ptr<DynamicDensityField> density_for_drawing)
std::shared_ptr<DriftVelocity> drift_velocity,
std::shared_ptr<DynamicDensityField> density_for_drawing,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_field_pitch_angle,
std::shared_ptr<DynamicDensityFieldWithPitchAngle> density_mu_for_drawing)
: Specie(type, name, mass_kg, charge_C),
mover_(mover),
terminator_(terminator),
@@ -53,7 +54,9 @@ TrackedSpecie::TrackedSpecie(
current_collector_(std::shared_ptr<CurrentCollector>(nullptr)),
velocity_distribution_(velocity_distribution),
drift_velocity_(drift_velocity),
density_for_drawing_(density_for_drawing) {}
density_for_drawing_(density_for_drawing),
density_field_pitch_angle_(density_field_pitch_angle),
density_with_pitch_angle_for_drawing(density_mu_for_drawing) {}
DensityField* TrackedSpecie::densityField() {
return density_field_.get();
@@ -74,6 +77,14 @@ DynamicDensityField* TrackedSpecie::densityForDrawing() {
return density_for_drawing_.get();
}
DynamicDensityFieldWithPitchAngle* TrackedSpecie::dynamicDensityFieldWithPitchAngle() {
return density_field_pitch_angle_.get();
}
DynamicDensityFieldWithPitchAngle* TrackedSpecie::dynamicDensityFieldWithPitchAngleForDrawing() {
return density_with_pitch_angle_for_drawing.get();
}
Mover* TrackedSpecie::mover() {
return mover_.get();
}