diff --git a/include/IO/hdf5_reader.h b/include/IO/hdf5_reader.h index e341175..b42ef92 100755 --- a/include/IO/hdf5_reader.h +++ b/include/IO/hdf5_reader.h @@ -9,12 +9,14 @@ class Hdf5Reader { Hdf5Reader(std::string directory, std::string filename); Hdf5Reader(std::string absolute_filename); + blitz::Array readD5Double(std::string path); blitz::Array readD4Double(std::string path); blitz::Array readD3Double(std::string path); blitz::Array readD2Double(std::string path); blitz::Array readD1Double(std::string path); double readDouble(std::string path); + blitz::Array readD5LongInt(std::string path); blitz::Array readD4LongInt(std::string path); std::stringstream readEngineString(std::string path); diff --git a/include/IO/hdf5_writer.h b/include/IO/hdf5_writer.h index f69e19b..531533b 100755 --- a/include/IO/hdf5_writer.h +++ b/include/IO/hdf5_writer.h @@ -14,7 +14,9 @@ class Hdf5Writer { void write(const blitz::Array& data, std::string path); void write(const blitz::Array& data, std::string path); void write(const blitz::Array& data, std::string path); + void write(const blitz::Array& data, std::string path); void write(const blitz::Array& data, std::string path); + void write(const blitz::Array& data, std::string path); void write(const blitz::TinyVector& data, std::string path); void write(const blitz::TinyVector& data, std::string path); void write(const std::vector& data, std::string path); diff --git a/include/IO/restart.h b/include/IO/restart.h index 2257fa8..5fae7d7 100644 --- a/include/IO/restart.h +++ b/include/IO/restart.h @@ -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); diff --git a/include/IO/simulation_output.h b/include/IO/simulation_output.h index f94ec83..d363d74 100755 --- a/include/IO/simulation_output.h +++ b/include/IO/simulation_output.h @@ -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, diff --git a/include/generators/density_field_generator.h b/include/generators/density_field_generator.h index 1143ded..7d1d411 100755 --- a/include/generators/density_field_generator.h +++ b/include/generators/density_field_generator.h @@ -15,6 +15,11 @@ std::shared_ptr buildDynamicDensityField( const json_path& path_to_field, std::shared_ptr& timer); +std::shared_ptr buildDynamicDensityFieldWithPitchAngle( + Parameter& parameter, + const json_path& path_to_field, + std::shared_ptr& timer); + }; // namespace generator #endif /* DENSITY_FIELD_GENERATOR_H */ diff --git a/include/generators/species_generator.h b/include/generators/species_generator.h index 62d44b4..b0b6c62 100755 --- a/include/generators/species_generator.h +++ b/include/generators/species_generator.h @@ -25,6 +25,8 @@ struct TrackedSpeciesBuilderInfo { std::shared_ptr drift_velocity; std::shared_ptr last_sync_density_field; std::shared_ptr density_drawing_field; + std::shared_ptr density_field_pitch_angle; + std::shared_ptr pitch_angle_drawing; double mass_kg; double charge_C; diff --git a/include/simulation/cpu_synchronizer.h b/include/simulation/cpu_synchronizer.h index 885bcad..f85198a 100755 --- a/include/simulation/cpu_synchronizer.h +++ b/include/simulation/cpu_synchronizer.h @@ -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& array, blitz::Array& last_sync_array); + void sumToAll(blitz::Array& array, + blitz::Array& last_sync_array); void sumToAll(blitz::Array& array, blitz::Array& last_sync_array); void sumToAll(blitz::Array& array, blitz::Array& last_sync_array); + void sumToAll(blitz::Array& array, + blitz::Array& last_sync_array); void sumToAll(double& value, double& last_sync_value); void sumToAll(long int& value, long int& last_sync_value); }; diff --git a/include/simulation/density_field.h b/include/simulation/density_field.h index 5c4d322..a735778 100755 --- a/include/simulation/density_field.h +++ b/include/simulation/density_field.h @@ -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); + + 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 draw(std::mt19937* engine); + + bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const; + + blitz::Array densityArray(); + blitz::Array spectrumArray(); + blitz::Array timeInBinArray() const; + blitz::Array deletedParticlesArray() const; + blitz::Array 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 time_in_bin); + void restartDeletedParticlesArray(blitz::Array deleted_particles); + + private: + + // BinCoordinate densityBin(const CylinderCoordinate& position) const; + void recalculateDensityArray(); + void initPositionDistributions(); + // use ordering r, phi, z, pitch_angle, E + + blitz::Array time_in_bin_s_; + blitz::Array deleted_particles_; + + blitz::Array sync_time_in_bin_s_; + blitz::Array sync_deleted_particles_; + + blitz::Array density_per_m3_; + blitz::Array bin_volume_m3_; + + const CylinderBinning position_binning_; + const EnergyBinning energy_binning_; + + // random distributions for drawing from + std::uniform_real_distribution r_dist_; + std::uniform_real_distribution phi_dist_; + std::uniform_real_distribution z_dist_; + std::uniform_real_distribution density_dist_; + + const PitchAngleBinning pitch_angle_binning_; + + std::shared_ptr timer_; + bool timer_restarted_ = false; +}; + class ConstantDensityField : public DensityField { public: ConstantDensityField(std::shared_ptr density); diff --git a/include/simulation/energy_binning.h b/include/simulation/energy_binning.h index 777ca50..87ba46e 100755 --- a/include/simulation/energy_binning.h +++ b/include/simulation/energy_binning.h @@ -18,4 +18,22 @@ class EnergyBinning { const std::vector 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 binBorders() const; + int binIndexMin() const; + int binIndexMax() const; + + private: + const std::vector pitch_angle_bin_borders_; +}; + #endif /* ENERGY_BINNING_H */ diff --git a/include/simulation/injector.h b/include/simulation/injector.h index 65c9592..d5e69a3 100755 --- a/include/simulation/injector.h +++ b/include/simulation/injector.h @@ -11,6 +11,7 @@ class DriftVelocity; class VelocityDistribution; class DynamicDensityField; +class MagneticField; namespace particle { class Particle; @@ -45,6 +46,13 @@ class Injector { std::vector& queue, const double weight, const double injection_time); + + void rollNewParticleFromDensityField(std::mt19937* engine, + std::shared_ptr specie, + std::vector& queue, + std::shared_ptr field, + const double weight, + const double injection_time); void initInjectionTimeDistribution(double delta_t); diff --git a/include/simulation/species.h b/include/simulation/species.h index 01111ae..3608d4b 100755 --- a/include/simulation/species.h +++ b/include/simulation/species.h @@ -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 density_field, std::shared_ptr velocity_distribution, std::shared_ptr drift_velocity, - std::shared_ptr density_for_drawing); + std::shared_ptr density_for_drawing, + std::shared_ptr density_field_pitch_angle, + std::shared_ptr 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 new_collector); @@ -86,6 +92,7 @@ class TrackedSpecie : public Specie { private: std::shared_ptr density_field_; + std::shared_ptr density_field_pitch_angle_; std::shared_ptr velocity_distribution_; std::shared_ptr drift_velocity_; @@ -98,6 +105,7 @@ class TrackedSpecie : public Specie { std::vector> interactions_; std::shared_ptr density_for_drawing_; + std::shared_ptr density_with_pitch_angle_for_drawing; }; class BackgroundSpecie : public Specie { diff --git a/src/IO/hdf5_reader.cpp b/src/IO/hdf5_reader.cpp index c5c7afa..28de3dd 100755 --- a/src/IO/hdf5_reader.cpp +++ b/src/IO/hdf5_reader.cpp @@ -162,6 +162,36 @@ blitz::Array Hdf5Reader::readD4Double(std::string path) { return data.copy(); } +blitz::Array 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 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 Hdf5Reader::readD4LongInt(std::string path) { hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); @@ -192,6 +222,35 @@ blitz::Array Hdf5Reader::readD4LongInt(std::string path) { return data.copy(); } +blitz::Array 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 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 diff --git a/src/IO/hdf5_writer.cpp b/src/IO/hdf5_writer.cpp index dee8509..fbdb225 100755 --- a/src/IO/hdf5_writer.cpp +++ b/src/IO/hdf5_writer.cpp @@ -165,6 +165,38 @@ void Hdf5Writer::write(const blitz::Array& data, std::string path) { H5Fclose(file); } +void Hdf5Writer::write(const blitz::Array& data, std::string path) { + hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); + + blitz::TinyVector size = data.extent(); + blitz::TinyVector start(0, 0, 0, 0, 0); + + hid_t filespace = + H5Screate_simple(5, blitz::TinyVector(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& 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& data, H5Fclose(file); } +void Hdf5Writer::write(const blitz::Array& data, + std::string path) { + hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); + + blitz::TinyVector size = data.extent(); + blitz::TinyVector start(0, 0, 0, 0, 0); + + hid_t filespace = + H5Screate_simple(5, blitz::TinyVector(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& data, std::string path) { hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); diff --git a/src/IO/restart.cpp b/src/IO/restart.cpp index ce1cc55..5fad72a 100644 --- a/src/IO/restart.cpp +++ b/src/IO/restart.cpp @@ -35,9 +35,19 @@ void Restart::restart(std::mapsecond.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 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 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) { diff --git a/src/IO/simulation_output.cpp b/src/IO/simulation_output.cpp index 65992fb..ad48cdc 100755 --- a/src/IO/simulation_output.cpp +++ b/src/IO/simulation_output.cpp @@ -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>& 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 energy_bin_borders = + density_field->energyBinning()->binBorders(); + writer.write(energy_bin_borders, path_to_bin_borders + "/energy"); + + std::vector mu_bin_borders = + density_field->pitchAngleBinning()->binBorders(); + writer.write(mu_bin_borders, path_to_bin_borders + "/pitchAngle"); + + std::vector radial_bin_borders = + density_field->positionBinning()->radial_binning.binBorders(); + writer.write(radial_bin_borders, path_to_bin_borders + "/radial"); + + std::vector azimuth_bin_borders = + density_field->positionBinning()->azimuth_binning.binBorders(); + writer.write(azimuth_bin_borders, path_to_bin_borders + "/azimuth"); + + std::vector 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 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"; diff --git a/src/generators/density_field_generator.cpp b/src/generators/density_field_generator.cpp index 5d63d43..e634b34 100755 --- a/src/generators/density_field_generator.cpp +++ b/src/generators/density_field_generator.cpp @@ -33,4 +33,25 @@ std::shared_ptr buildDynamicDensityField( new DynamicDensityField(position_binning, energy_binning, timer)); } +std::shared_ptr buildDynamicDensityFieldWithPitchAngle( + Parameter& parameter, + const json_path& path_to_field, + std::shared_ptr& 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( + new DynamicDensityFieldWithPitchAngle(position_binning, energy_binning, + pitch_angle_binning, timer)); +} + }; // namespace generator \ No newline at end of file diff --git a/src/generators/species_generator.cpp b/src/generators/species_generator.cpp index ac62209..da1eba1 100755 --- a/src/generators/species_generator.cpp +++ b/src/generators/species_generator.cpp @@ -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)); } } diff --git a/src/simulation/cpu_synchronizer.cpp b/src/simulation/cpu_synchronizer.cpp index 2bf51f6..1be07d2 100755 --- a/src/simulation/cpu_synchronizer.cpp +++ b/src/simulation/cpu_synchronizer.cpp @@ -17,6 +17,16 @@ void CpuSynchronizer::sumToAll(blitz::Array& array, last_sync_array += delta; } +void CpuSynchronizer::sumToAll(blitz::Array& array, + blitz::Array& last_sync_array) { + int size = array.size(); + blitz::Array 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& array, blitz::Array& last_sync_array) { int size = array.size(); @@ -27,6 +37,16 @@ void CpuSynchronizer::sumToAll(blitz::Array& array, last_sync_array += delta; } +void CpuSynchronizer::sumToAll(blitz::Array& array, + blitz::Array& last_sync_array) { + int size = array.size(); + blitz::Array 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& array, blitz::Array& 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."); diff --git a/src/simulation/density_field.cpp b/src/simulation/density_field.cpp index 8164a26..af1bd8d 100755 --- a/src/simulation/density_field.cpp +++ b/src/simulation/density_field.cpp @@ -4,6 +4,7 @@ #include "simulation/errors.h" #include "simulation/event_position_distribution.h" #include "simulation/scalar_field.h" +#include "simulation/kinematic.h" template blitz::Array initiate4DArray(blitz::Range radial, @@ -15,6 +16,17 @@ blitz::Array initiate4DArray(blitz::Range radial, return data.copy(); } +template +blitz::Array initiate5DArray(blitz::Range radial, + blitz::Range phi, + blitz::Range longitudinal, + blitz::Range pitch_angle, + blitz::Range energy) { + blitz::Array data(radial, phi, longitudinal, pitch_angle, energy); + data = static_cast(0); + return data.copy(); +} + blitz::Array 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) : + position_binning_(position_binning), + energy_binning_(energy_binning), + pitch_angle_binning_(pitch_angle_binning), + timer_(timer), + time_in_bin_s_(initiate5DArray( + 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( + 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( + 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( + 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( + 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 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 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 old_bin = + position_binning_.bin(old_position.cylinderEntries()); + + const blitz::TinyVector 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 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 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 DynamicDensityFieldWithPitchAngle::densityArray() { + DEBUG_LEVEL_3("recalc Density array"); + recalculateDensityArray(); + + blitz::Array density(density_per_m3_( + blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0)); + blitz::fourthIndex iE; + DEBUG_LEVEL_3("density sum"); + density = blitz::sum(density_per_m3_, iE); + return density.copy(); +} + +blitz::Array DynamicDensityFieldWithPitchAngle::spectrumArray() { + recalculateDensityArray(); + return density_per_m3_; +} + +blitz::Array DynamicDensityFieldWithPitchAngle::timeInBinArray() const { + return time_in_bin_s_; +} + +blitz::Array DynamicDensityFieldWithPitchAngle::deletedParticlesArray() const { + return deleted_particles_; +} + +blitz::Array 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 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(0., blitz::max(densityArray())); +} + +double DynamicDensityFieldWithPitchAngle::particleNumber() { + blitz::Array 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(rmin*rmin, rmax*rmax); + phi_dist_ = std::uniform_real_distribution(phimin, phimax); + z_dist_ = std::uniform_real_distribution(zmin, zmax); +} + +// don't know if it's even good to have the drawing stuff in the +// density distributions... +blitz::TinyVector DynamicDensityFieldWithPitchAngle:: + draw(std::mt19937* engine) { + recalculateDensityArray(); + if (isEqual(blitz::max(density_per_m3_), 0.)) { + DEBUG_LEVEL_3("Density is empty"); + return blitz::TinyVector (0,0,0,0,0); + } + // setDensityDistribution(); + double random_r, random_z, random_phi, random_E, random_n; + double density_in_random_cell; + + 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 (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 position_bin = + position_binning_.bin(CylinderCoordinate( + blitz::TinyVector (random_r, random_phi, random_z)) + .cylinderEntries()); + + std::vector energyBins = energy_binning_.binBorders(); + energyBins.insert(energyBins.begin(), 0.); + blitz::Array densityAtPosition = density_per_m3_(position_bin(0), + position_bin(1), + position_bin(2), + blitz::Range::all()); + + std::piecewise_constant_distribution E_dist_(energyBins.begin(), + energyBins.end(), + densityAtPosition.begin()); + + random_E = E_dist_(*engine); + DEBUG_LEVEL_3("energy: " + std::to_string(random_E)); + + const int energy_bin = energy_binning_.bin(random_E); + + std::vector mu_bins = pitch_angle_binning_.binBorders(); + DEBUG_LEVEL_3("Size pitchangle binning: " + std::to_string(mu_bins.size())); + DEBUG_LEVEL_3("Size timeinbin: " + std::to_string(time_in_bin_s_.extent(3))); + + auto 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 mu_distribution( + mu_bins.begin(), mu_bins.end(), test.begin()); + + double random_mu = mu_distribution(*engine); + + return blitz::TinyVector (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 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 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 density) : density_(density) {} diff --git a/src/simulation/energy_binning.cpp b/src/simulation/energy_binning.cpp index 29a523e..6c2a765 100755 --- a/src/simulation/energy_binning.cpp +++ b/src/simulation/energy_binning.cpp @@ -2,8 +2,7 @@ #include #include -// probably rename to indicate what type of borders are created -std::vector generateBinBorders(double bin_min, +std::vector generateLogBinBorders(double bin_min, double bin_max, int num_bins) { const double min_bin_log = log10(bin_min); @@ -18,11 +17,25 @@ std::vector generateBinBorders(double bin_min, return bin_borders; } +std::vector generateLinearBinBorders(double bin_min, + double bin_max, + int num_bins) { + + const double bin_size = (bin_max - bin_min) / num_bins; + + std::vector 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 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 PitchAngleBinning::binBorders() const { + return pitch_angle_bin_borders_; +} + +int PitchAngleBinning::binIndexMin() const { + return -1; +} + +int PitchAngleBinning::binIndexMax() const { + return numBins(); +} \ No newline at end of file diff --git a/src/simulation/injector.cpp b/src/simulation/injector.cpp index 63d6b7b..af4dc0d 100755 --- a/src/simulation/injector.cpp +++ b/src/simulation/injector.cpp @@ -8,8 +8,20 @@ #include "simulation/species.h" #include "simulation/density_field.h" #include "simulation/velocity_distribution.h" +#include "simulation/electromagnetic_field.h" #include +blitz::TinyVector perpendicularNormalVector(blitz::TinyVector vector) { + blitz::TinyVector result(0,0,0); + result[0] = std::copysign(vector[2], vector[0]); + result[1] = std::copysign(vector[2], vector[1]); + result[2] = - std::copysign(std::fabs(vector[0] + std::fabs(vector[1])), vector[2]); + + // DEBUG_LEVEL_3("dot product: " + std::to_string(blitz::dot(result, vector))); + + return result / kinematic::norm(result); +} + Injector::Injector( std::vector& injector_info, double activity, @@ -104,9 +116,57 @@ void Injector::rollNewParticleFromDensityField(std::mt19937* engine, std::cos(phi)); particle::Particle drawn_particle(specie, CylinderCoordinate( - blitz::TinyVector(particle_specs[0], - particle_specs[1], particle_specs[2])), - CartesianVector(v_normal*v_abs), injection_time, weight); + blitz::TinyVector(particle_specs[0], + particle_specs[1], particle_specs[2])), + CartesianVector(v_normal*v_abs), injection_time, weight); + + queue.push_back(drawn_particle); +} + +void Injector::rollNewParticleFromDensityField(std::mt19937* engine, + std::shared_ptr specie, + std::vector& queue, + std::shared_ptr magnetic_field, + const double weight, + const double injection_time) { + blitz::TinyVector 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(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 distribution(0.0, 1.0); + const double theta = distribution(*engine) * 2 * M_PI; + + const double mu = particle_specs[3]; + DEBUG_LEVEL_3("mu: " + std::to_string(mu)); + + blitz::TinyVector magnetic_field_value = magnetic_field-> + value(position).cartesianEntries(position); + const double abs_B = kinematic::norm(magnetic_field_value); + + blitz::TinyVector perpendicular_vector = + perpendicularNormalVector(magnetic_field_value); + + blitz::TinyVector v_normal = mu*magnetic_field_value/abs_B + + std::sqrt(1-mu*mu)*kinematic::rotateVector(perpendicular_vector, + magnetic_field_value, + theta); + + particle::Particle drawn_particle(specie, position, + CartesianVector(v_normal*v_abs), injection_time, weight); queue.push_back(drawn_particle); } diff --git a/src/simulation/mover.cpp b/src/simulation/mover.cpp index 33cfb32..300a777 100755 --- a/src/simulation/mover.cpp +++ b/src/simulation/mover.cpp @@ -13,6 +13,12 @@ #include "tools/simulation_time.h" +double cosAngleBetweenVectors(blitz::TinyVector vector_1, + blitz::TinyVector 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); } diff --git a/src/simulation/simulation.cpp b/src/simulation/simulation.cpp index a416d54..64496b6 100755 --- a/src/simulation/simulation.cpp +++ b/src/simulation/simulation.cpp @@ -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 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; diff --git a/src/simulation/species.cpp b/src/simulation/species.cpp index 76a878f..3dfd13d 100755 --- a/src/simulation/species.cpp +++ b/src/simulation/species.cpp @@ -41,9 +41,10 @@ TrackedSpecie::TrackedSpecie( std::shared_ptr reflector, std::shared_ptr density_field, std::shared_ptr velocity_distribution, - std::shared_ptr drift_velocity, - // std::shared_ptr last_sync_density_field, - std::shared_ptr density_for_drawing) + std::shared_ptr drift_velocity, + std::shared_ptr density_for_drawing, + std::shared_ptr density_field_pitch_angle, + std::shared_ptr 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(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(); }