Author SHA1 Message Date
csendlinger 2f68d8e3b1 Added more deletionLogger elements (for debugging) 2025-06-16 09:44:51 +02:00
csendlinger 9d170336b8 changes from double to float to check if
error is indeed cancellation error
2025-06-11 11:03:23 +02:00
csendlinger 05125a3fc1 Added debug to check density deposition and
deletion alignment
2025-06-10 09:23:43 +02:00
csendlinger 024fe59410 corrected mistake in reader 2025-06-03 11:39:50 +02:00
csendlinger d621932172 fix ion velocity ionization 2025-06-02 13:13:44 +02:00
csendlinger d6578e540d reduction of std::pow calls; stronger usage of
Cartesian- and CylinderCoordinate objects
2025-06-02 11:09:57 +02:00
csendlinger f510d0a39a preprocessor now filters debug output 2025-05-28 15:27:00 +02:00
csendlinger e2167fb75b reduced number of calls to atan2 (in mover only
for the Boris push algo), changed drawing of
uniformly distributed unit vector
2025-05-28 15:18:13 +02:00
csendlinger a33e97187e removed std::pow usage in d2CrossSections 2025-05-28 15:14:52 +02:00
csendlinger 0af4959fa0 Added functions to directly calculate sin(phi) and
cos(phi) instead of having to fully transform vectors
first
2025-05-28 15:08:16 +02:00
csendlinger 59f4041238 Added underflow bin (energy) to indices that are
drawn from
2025-05-23 16:58:42 +02:00
csendlinger 786cb6d877 changed drawing of r-position in bin from uniform to linear distribution 2025-05-23 11:07:03 +02:00
csendlinger 1194dba918 Hotfix Drift Mover 2025-05-20 16:47:30 +02:00
csendlinger 5179869039 Removed deleted particles array;
resturctured debug output a bit
2025-05-19 09:38:12 +02:00
csendlinger 1a7931bbea Bugfix Driftmover 2025-05-14 16:42:39 +02:00
csendlinger b28245f1a8 Bin based drawing implemented (debug output not
yet removed)
2025-05-14 16:41:19 +02:00
csendlinger 60430abcba Changed distance drawing procedure;
Changed mover to work with times instead of distance;
Changed how interactions are done (recombination still tbd)
2025-05-08 09:56:25 +02:00
csendlinger 2c79c567d8 removed infrastructure only needed for the old
density calculation scheme
2025-05-06 09:53:18 +02:00
csendlinger 89e0a0eb2a Changed density calculation to only log particle
in the bin its movement ends; timestep changed to double
2025-04-23 14:37:55 +02:00
csendlinger d17602e1fa Fixed bug with mu=-1; added nan-check in
drawing velocity from density if DO_DEBUG
is true in the config file
2025-03-15 09:09:21 +01:00
csendlinger 5bc545ac99 hotfix: changed a <= b to !(a > b) 2025-03-13 15:20:56 +01:00
csendlinger d62c49a15d Bugfix drawing from density 2025-02-27 11:32:17 +01:00
csendlinger 62e3c27ba4 Added adapted example json script; small bugfix 2025-02-24 15:12:54 +01:00
csendlinger 3396d810a2 Fixed calculation of currents (included particle weights) 2025-02-19 15:53:46 +01:00
csendlinger 154bf41bf0 Bugfix: delta t default value at construction 2025-02-19 09:34:16 +01:00
csendlinger 9cd7db4e05 Bug fixes and formatting 2025-02-18 11:17:24 +01:00
csendlinger 24b2c2f2ed Decoupled timestep from number of beta events 2025-02-13 10:03:15 +01:00
csendlinger 047cfa8491 Decoupled the number of events simulated from
the timestep;
Bug with density drawing present
(if CPU syncs don't line up with the timestep)
2025-02-12 14:07:43 +01:00
csendlinger e205e7469e Adapted changes to compilation of
external libraries (blitz and jansson)
from the karl_paper branch
2025-02-05 16:13:00 +01:00
csendlinger 299dfa6fc4 Updated Boris mover to include gravity fields and
in case B=0 use z-direction for mu calculation;
correction of units in analysis script
2025-02-05 14:17:10 +01:00
csendlinger 57ef99a57b Moved drawing from density to seperate classes 2025-02-05 10:31:56 +01:00
csendlinger b529021149 Some optimizations (mfp: vector instead of recalc,
reduced number of density recalculations);
Default gravity field of 0;
adjusted error output
2025-01-29 16:59:10 +01:00
csendlinger 5dffc0c102 removed the 4d density field 2024-11-04 16:08:40 +01:00
csendlinger b1519cb4ca Included pitch angle binning in the json file;
minor changes to debug output
2024-10-29 14:55:14 +01:00
csendlinger 5fc227e1b1 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'
2024-10-28 15:00:19 +01:00
csendlinger b4cbd8c44c Bugfixes;
Restarts now reproduce longer Sims
2024-09-11 14:56:14 +02:00
csendlinger 75bb2e4d85 small fixes and cosmetic changes 2024-09-05 09:33:12 +02:00
csendlinger 9c45fce644 built restart utilities 2024-09-03 16:02:40 +02:00
csendlinger c33629cb88 Added new reading routines (engine state,
4d double, 4d int); fixed error in RestartInfo
output; added the maximum length of the engine
state string into sim_constants.h
2024-08-27 14:46:48 +02:00
csendlinger c14a5245b1 added failsafe in case the value read by json_string_value is not a string 2024-08-26 11:01:46 +02:00
csendlinger f6aae32288 added basic parallel output for the
string representation of the rng engine state
2024-08-23 16:39:03 +02:00
csendlinger 2e5923ab6f restructured fields for cpu sync;
no longer whole object in species but additional
fields in the corresponding classes
2024-08-13 15:00:13 +02:00
csendlinger 9dda12b60a Fixed to state that drawing from density works.
Some debugging elements not removed.
2024-08-12 14:20:45 +02:00
csendlinger b57f6ff201 Basic neccessities to draw from a density field;
does not yet work correctly since the neccessary
density field is reset after a time resolution
step
2024-08-08 10:10:50 +02:00
csendlinger 4301c4453b Added option for initial weights in the injector 2024-07-31 10:35:14 +02:00
csendlinger 961f1a2a8e updated makefile 2024-07-30 14:24:10 +02:00
csendlinger 21edce8f92 added 1GHz magnetic fieldmap 2024-07-22 09:43:45 +02:00
csendlinger 844c0dfcc3 fix in current calculation 2024-07-12 16:45:12 +02:00
csendlinger 531ace797a Merge branch 'time_resolution' of masterduck.fspanier.de:katrin/karl into time_resolution 2024-07-01 10:12:20 +02:00
csendlinger f529804ee6 corrected units in the magnetic Bottle approximations 2024-07-01 10:05:07 +02:00
csendlinger d08407c773 added function for id of a particle 2024-06-27 10:12:07 +02:00
csendlinger 204b2817da added approximations for the magnetic Bottle in P8 2024-06-27 09:38:52 +02:00
csendlinger 095dd6eb3d Merge branch 'time_resolution' of masterduck.fspanier.de:katrin/karl into time_resolution 2024-06-25 10:49:38 +02:00
csendlinger 03321880d8 inclusion gradB in DriftMover 2024-06-25 10:49:22 +02:00
csendlinger a1444bceaa inclusion gradB field and quickfix reading from array 2024-06-25 10:08:12 +02:00
csendlinger f097f2b7ff small corrections in check if particle died 2024-06-17 09:15:38 +02:00
csendlinger f82cbf4c47 fix in density calculation 2024-05-27 11:00:52 +02:00
csendlinger fea00f9a0a minor corrections, added example json file 2024-05-16 09:43:29 +02:00
csendlinger d6ee7e8be8 optimized queue and backup queue a bit 2024-05-15 09:57:31 +02:00
csendlinger fcbff96f17 Poisson step and resets only after time resolution 2024-05-15 09:12:43 +02:00
csendlinger 77fa8d175a Basic changes for time resolution.
Input from json still suboptimal.
2024-05-14 09:23:52 +02:00
csendlinger cac5e6ff5d added exponential into predefined functions 2024-05-10 14:36:49 +02:00
108 changed files with 5233 additions and 720 deletions
+1 -1
View File
@@ -256,7 +256,7 @@ def plotLongitudinalParticleCurrentVsZ(filename, path_to_species, plot_axis, out
z_bins = zBinsDensityField(filename, path_to_species)
plot_axis.plot(z_bins, current_in_z, label=str(path_to_species))
plot_axis.set_xlabel(r"Distance to rear wall $z$ (m)")
plot_axis.set_ylabel(r"Particle current $j$ ($m^{-3}s^{-1}$)")
plot_axis.set_ylabel(r"Particle current $j$ ($m^{-2}s^{-1}$)")
def plotAllLongitudinalParticleCurrentVsZ(filename, output_period, specie_keys, output_folder):
+18 -10
View File
@@ -12,9 +12,15 @@ CATCH_INCLUDES = -I$(CATCH_DIR)
# Blitz
MAKE_BLITZ = false
BLITZ_DIR = $(HOMEBASE)/external/blitz/build/
BLITZ_INC_DIR = $(BLITZ_DIR)include/
BLITZ_LIB_DIR = $(BLITZ_DIR)lib/
ifeq ($(MAKE_BLITZ), true)
BLITZ_DIR = $(HOMEBASE)/external/blitz/build
BLITZ_INC_DIR = $(BLITZ_DIR)/include
BLITZ_LIB_DIR = $(BLITZ_DIR)/lib
else
BLITZ_INC_DIR = /usr/include
BLITZ_LIB_DIR = /usr/lib/x86_64-linux-gnu
endif
BLITZ_INCLUDES = -I$(BLITZ_INC_DIR)
BLITZ_LIBS = -L$(BLITZ_LIB_DIR) -lblitz -lm
@@ -32,11 +38,13 @@ HDF5P_LIBRARIES = -L$(HDF5P_LIB_DIR) -lz -lhdf5_hl -lhdf5
# Janson
MAKE_JANSSON = false
JANSON_DIR = $(HOMEBASE)/external/jansson/
JANSON_INC_DIR = $(JANSON_DIR)
JANSSON_LIBRARIES = -ljansson
JANSSON_INCLUDES = -I$(JANSON_INC_DIR)
ifeq ($(MAKE_JANSSON), true)
JANSSON_INC_DIR = $(HOMEBASE)/external/jansson/build/include
JANSSON_LIB_DIR = $(HOMEBASE)/external/jansson/build/lib
else
JANSSON_INC_DIR = /usr/include
JANSSON_LIB_DIR = /usr/lib/x86_64-linux-gnu
endif
JANSSON_LIBRARIES = -L$(JANSSON_LIB_DIR) -ljansson
JANSSON_INCLUDES = -I$(JANSSON_INC_DIR)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+16 -6
View File
@@ -4,22 +4,32 @@ dummy: all
ZIP = tar
NAME_TAR = blitz-1.0.2.tar.gz
NAME = blitz-1.0.2
BLITZ_VERSION = 1.0.2
NAME_TAR = blitz-$(BLITZ_VERSION).tar.gz
NAME = blitz-$(BLITZ_VERSION)
BLITZ_FOLDER=external/blitz
BLITZ_FOLDER=/external/blitz/
all:
ifneq ("$(wildcard $(NAME_TAR))","")
@echo "Archive already present"
else
@echo "Downloading"
wget https://github.com/blitzpp/blitz/archive/refs/tags/$(BLITZ_VERSION).tar.gz
mv $(BLITZ_VERSION).tar.gz $(NAME_TAR)
endif
$(ZIP) -xf $(NAME_TAR)
mkdir -p build
mkdir -p build/include
mkdir -p build/lib
cd $(NAME) && autoreconf -fiv && autoconf && automake --add-missing
cd $(NAME) && ./configure --prefix=$(HOMEBASE)$(BLITZ_FOLDER)build/ --includedir=$(HOMEBASE)$(BLITZ_FOLDER)build/include/ --libdir=$(HOMEBASE)$(BLITZ_FOLDER)build/lib/
cd $(NAME) && ./configure --prefix=$(HOMEBASE)/$(BLITZ_FOLDER)/build/ --includedir=$(HOMEBASE)/$(BLITZ_FOLDER)/build/include/ --libdir=$(HOMEBASE)/$(BLITZ_FOLDER)/build/lib/
cd $(NAME) && $(MAKE)
cd $(NAME) && $(MAKE) lib
cd $(NAME) && $(MAKE) install
clean:
-rm -rf $(HOMEBASE)$(BLITZ_FOLDER)blitz-1.0.2
-rm -rf $(HOMEBASE)$(BLITZ_FOLDER)build
-rm -rf $(HOMEBASE)/$(BLITZ_FOLDER)/$(NAME)
-rm -rf $(HOMEBASE)/$(BLITZ_FOLDER)/build
Binary file not shown.
+14 -6
View File
@@ -4,21 +4,29 @@ dummy: all
ZIP = tar
NAME_TAR = jansson-2.13.tar.gz
NAME = jansson-2.13
JANSSON_VERSION = 2.14
JANSSON_FOLDER=/external/jansson/
NAME = jansson-$(JANSSON_VERSION)
NAME_TAR = $(NAME).tar.gz
JANSSON_FOLDER=external/jansson
all:
ifneq ("$(wildcard $(NAME_TAR))","")
@echo "Archive already present"
else
@echo "Downloading"
wget https://github.com/akheron/jansson/releases/download/v$(JANSSON_VERSION)/$(NAME_TAR)
endif
$(ZIP) -xf $(NAME_TAR)
mkdir -p build
mkdir -p build/include
mkdir -p build/lib
#cd $(NAME) && autoreconf -fiv && automake --add-missing
cd $(NAME) && ./configure --prefix=$(HOMEBASE)$(JANSSON_FOLDER)build/ --includedir=$(HOMEBASE)$(JANSSON_FOLDER)build/include/ --libdir=$(HOMEBASE)$(JANSSON_FOLDER)build/lib/
cd $(NAME) && ./configure --prefix=$(HOMEBASE)/$(JANSSON_FOLDER)/build/ --includedir=$(HOMEBASE)/$(JANSSON_FOLDER)/build/include/ --libdir=$(HOMEBASE)/$(JANSSON_FOLDER)/build/lib/
cd $(NAME) && $(MAKE)
cd $(NAME) && $(MAKE) install
clean:
-rm -rf $(HOMEBASE)$(JANSSON_FOLDER)$(NAME)
-rm -rf $(HOMEBASE)$(JANSSON_FOLDER)build
-rm -rf $(HOMEBASE)/$(JANSSON_FOLDER)/$(NAME)
-rm -rf $(HOMEBASE)/$(JANSSON_FOLDER)/build
Binary file not shown.
+8
View File
@@ -9,9 +9,17 @@ 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);
private:
std::string absolute_filename_;
+5
View File
@@ -14,7 +14,10 @@ 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<float, 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);
@@ -22,6 +25,8 @@ class Hdf5Writer {
void write(long int data, std::string path);
void write(double data, std::string path);
void write(const std::string& data, std::string path);
void writeRNG(const std::string& data, std::string path_base);
std::string AbsoluteFileName() const;
private:
std::string absolute_filename_;
+44
View File
@@ -0,0 +1,44 @@
#ifndef RESTART_H
#define RESTART_H
#include <string>
#include <map>
#include <memory>
#include "IO/hdf5_reader.h"
namespace species {
class TrackedSpecie;
enum class ImplementedSpecies;
}; // namespace species
class DynamicDensityField;
class PoissonSolver;
class RandomNumbers;
// Note: The restarts for the DensityField and the PoissonSolver require that the
// partitioning of the simulation space does not change between the original and
// the restarted simulation
// Note: think if it's better (or more consistent) to set the dynamic electric field
// here after the potential is loaded; would need the electric field class to be included
class Restart {
public:
Restart(bool do_restart, std::string absolute_filename,
std::string restart_identifier);
void restart(std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, RandomNumbers* random_numbers);
private:
void restartTimer(species::TrackedSpecie* reference_specie);
// only necessary for densityfield that is drawn from
void restartDrawingDensityField(DynamicDensityField* field, std::string path);
// only load in the potential and calc the electric field
void restartPoissonSolver(PoissonSolver* solver);
void restartRandomNumbers(RandomNumbers* random);
bool do_restart_;
std::string restart_identifier_; // i.e. "LastSyncPeriod" or "SyncPeriod_*"
Hdf5Reader reader_;
};
#endif /* RESTART_H */
+11 -4
View File
@@ -5,6 +5,7 @@
#include <memory>
#include <string>
#include <vector>
#include <random>
#include "IO/hdf5_writer.h"
class DynamicDensityField;
@@ -35,6 +36,7 @@ class SimulationOutput {
void addCurrentBorderOutput(OutputTask task);
void addDeletionLoggerOutput(OutputTask task);
void setPotentialOutput(OutputTask task);
void setRestartInfoOutput(OutputTask task);
void writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
@@ -43,13 +45,14 @@ class SimulationOutput {
void writeSimulationData(
int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver);
PoissonSolver* poisson_solver, std::mt19937* engine);
private:
std::vector<OutputTask> tasks_density_fields_;
std::vector<OutputTask> tasks_current_collector_;
std::vector<OutputTask> tasks_deletion_logger_;
OutputTask task_potential_; // no meta data written for now
OutputTask task_potential_;
OutputTask task_rng_;
Hdf5Writer writer;
@@ -61,8 +64,8 @@ class SimulationOutput {
void writeSpectrum(DynamicDensityField* density_field, std::string path);
void writeDensity(DynamicDensityField* density_field, std::string path);
void writeTimeInBin(DynamicDensityField* density_field, std::string path);
void writeDeletedParticles(DynamicDensityField* density_field,
std::string path);
// void writeDeletedParticles(DynamicDensityField* density_field,
// std::string path);
void writePhysicalTime(DynamicDensityField* density_field, std::string path);
void writeSimulationData(CurrentCollector* current_collector,
@@ -102,6 +105,10 @@ class SimulationOutput {
std::string path_to_field);
void writeBinBorders(DynamicDensityField* density_field,
std::string path_to_field);
void writeRestartData(std::mt19937* engine, int cpu_sync,
bool overwrite_last);
void writeRandomEngineState(std::mt19937* engine, std::string path);
};
#endif /* SIMULATION_OUTPUT_H */
+5
View File
@@ -10,6 +10,11 @@ static const double minimal_macroscopic_cross_section =
std::numeric_limits<double>::min() * 1E5;
static const double random_lower_limit = 1E-15;
static const double compare_epsilon = 1E-10;
// engine state of mt19973 engine consists of 624 numbers (output seems to write 625)
// (assumed to be constant); each number is represented by a 32 bit word (2^32 = 4294967296)
// i.e. each number needs at most 10 digits; the numbers are seperated by whitespaces
// -> max length = 10*625 + 624 = 6874 (add one more digit to be on the safe side)
static const size_t engine_string_length_max = 6875;
} // namespace SimConstants
+2
View File
@@ -12,6 +12,8 @@ std::function<double(double)> Constant(double constant);
std::function<double(double)> Product(
std::vector<std::function<double(double)>> functions);
std::function<double(double)> Exponential(double prefactor, double scale);
}; // namespace D1ToD1
namespace D3ToD1 {
+5
View File
@@ -19,6 +19,11 @@ EnergyBinning buildEnergyBinningIncludingRedirection(
Parameter& parameter,
json_path& path_to_binning);
PitchAngleBinning buildPitchAngleBinning(json_t* object);
PitchAngleBinning buildPitchAngleBinningIncludingRedirection(
Parameter& parameter,
json_path& path_to_binning);
}; // namespace generator
#endif /* BINNING_GENERATOR_H */
+15
View File
@@ -0,0 +1,15 @@
#ifndef RESTART_GENERATOR_H
#define RESTART_GENERATOR_H
#include "jansson.h"
#include "simulation/parameter.h"
class Restart;
namespace generator{
Restart buildRestart(json_t* object);
Restart buildRestart(Parameter& parameter);
}; // namespace generator
#endif /* RESTART_GENERATOR_H */
+1
View File
@@ -24,6 +24,7 @@ struct TrackedSpeciesBuilderInfo {
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_drawing_field;
double mass_kg;
double charge_C;
+2
View File
@@ -15,6 +15,8 @@ class FreeMovement : public Interaction {
double microscopicCrossSection(double energy_eV);
double macroscopicCrossSection(particle::Particle& particle);
double drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator);
};
}; // namespace interaction
+5 -7
View File
@@ -55,16 +55,16 @@ class PoissonSolver {
std::vector<std::shared_ptr<Electrode>> electrodes,
double target_accuracy,
int num_cycles,
int solver_intervall,
int solver_offset,
bool reset_after_solving);
bool do_solver);
void solvePotential(const blitz::Array<double, 3> charge_density,
int cpu_sync, bool& reset);
const bool solve);
blitz::Array<double, 3> potential();
std::shared_ptr<VectorField> staticElectricField();
const CylinderBinning* densityBinning();
void setPotential(blitz::Array<double, 3>& potential);
private:
GlobalBoundary bottom_boundary_;
GlobalBoundary top_boundary_;
@@ -74,9 +74,7 @@ class PoissonSolver {
const CylinderBinning density_binning_;
const double target_accuracy_;
const int num_cycles_;
const int solver_intervall_;
const int solver_offset_;
const bool reset_after_solving_;
const bool do_solver_;
// density binning defined on the cell centers, potential defined
// such that it exists on the cell edges so that the azimuthal
+1 -1
View File
@@ -3,7 +3,7 @@
#include "constants/sim_constants.h"
bool isEqual(double a, double b) {
inline bool isEqual(double a, double b) {
return std::abs(a - b) < SimConstants::compare_epsilon;
}
+9
View File
@@ -27,6 +27,9 @@ class Coordinate {
virtual blitz::TinyVector<double, 3> cartesianEntries() const = 0;
virtual blitz::TinyVector<double, 3> cylinderEntries() const = 0;
virtual double cosAzimuth() const = 0;
virtual double sinAzimuth() const = 0;
virtual void add(const Coordinate& coordinate) = 0;
};
@@ -38,6 +41,9 @@ class CartesianCoordinate : public Coordinate {
blitz::TinyVector<double, 3> cartesianEntries() const;
blitz::TinyVector<double, 3> cylinderEntries() const;
double cosAzimuth() const;
double sinAzimuth() const;
void add(const Coordinate& coordinate);
private:
@@ -52,6 +58,9 @@ class CylinderCoordinate : public Coordinate {
blitz::TinyVector<double, 3> cartesianEntries() const;
blitz::TinyVector<double, 3> cylinderEntries() const;
double cosAzimuth() const;
double sinAzimuth() const;
void add(const Coordinate& coordinate);
private:
+11 -6
View File
@@ -21,14 +21,13 @@ class CpuSynchronizer {
void synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species);
tracked_species, bool reset);
void synchronize(DynamicDensityField* field,
DynamicDensityField* last_sync_field);
void synchronize(CurrentCollector* collector,
CurrentCollector* last_sync_collector);
void synchronize(DeletionLogger* logger,
DeletionLogger* last_sync_logger);
DynamicDensityField* density_for_drawing,
bool reset);
void synchronize(CurrentCollector* collector);
void synchronize(DeletionLogger* logger);
void synchronize(Timer* timer, Timer* last_sync_timer);
@@ -37,10 +36,16 @@ class CpuSynchronizer {
*/
void sumToAll(blitz::Array<double, 4>& array,
blitz::Array<double, 4>& last_sync_array);
void sumToAll(blitz::Array<float, 5>& array,
blitz::Array<float, 5>& 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);
};
+15 -3
View File
@@ -37,11 +37,14 @@ class CurrentCollector {
private:
void collectRadialMovement(const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new);
const blitz::TinyVector<int, 3>& bin_new,
const double weight);
void collectLongitudinalMovement(const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new);
const blitz::TinyVector<int, 3>& bin_new,
const double weight);
void collectAzimuthalMovement(const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new);
const blitz::TinyVector<int, 3>& bin_new,
const double weight);
blitz::Array<double, 3> createAreaLongitudinal(
const CylinderBinning& position_binning);
@@ -67,6 +70,15 @@ class CurrentCollector {
blitz::Array<double, 3> r_negative_crossings;
blitz::Array<double, 3> r_positive_crossings;
blitz::Array<double, 3> sync_z_negative_crossings;
blitz::Array<double, 3> sync_z_positive_crossings;
blitz::Array<double, 3> sync_phi_negative_crossings;
blitz::Array<double, 3> sync_phi_positive_crossings;
blitz::Array<double, 3> sync_r_negative_crossings;
blitz::Array<double, 3> sync_r_positive_crossings;
blitz::Array<double, 3> collector_areas_r;
blitz::Array<double, 3> collector_areas_phi;
blitz::Array<double, 3> collector_areas_z;
+54 -24
View File
@@ -2,7 +2,9 @@
#define DENSITY_FIELD_H
#include <memory>
#include <random>
#include "simulation/compare.h"
#include "simulation/coordinates.h"
#include "simulation/cpu_synchronizer.h"
#include "simulation/energy_binning.h"
@@ -18,12 +20,18 @@ class DensityField {
virtual double density(const Coordinate& position, double energy_eV) = 0;
};
// includes a resolution of the pitch angle (i.e. cos(angle(\vec{v}, \vec{B})))
class DynamicDensityField : public DensityField {
public:
DynamicDensityField(const CylinderBinning& position_binning,
DynamicDensityField(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;
@@ -31,54 +39,76 @@ class DynamicDensityField : public DensityField {
void logMovement(const Coordinate& position,
double energy_eV,
double time_in_bin_s);
double pitch_angle,
double weight);
void logDeletion(const Coordinate& position, double energy_eV);
// void logDeletion(const Coordinate& position,
// double energy_eV,
// double pitch_angle);
double density(const Coordinate& position);
double density(const Coordinate& position, double energy_eV);
// return the particle number stored in the density of this object
double particleNumber();
// return the particle number at the given index
double particleNumber(blitz::TinyVector<int, 5> index);
void resetDynamicDensityField();
// returns true if the old pitch angle and the new pitch angle are in different bins
// of the pitch angle binning
bool changedPitchAngleBin(double old_pitch_angle, double new_pitch_angle) const;
blitz::Array<double, 3> densityArray();
blitz::Array<double, 4> spectrumArray();
blitz::Array<double, 4> timeInBinArray() const;
blitz::Array<long int, 4> deletedParticlesArray() const;
blitz::Array<float, 5> timeInBinArray() const;
// blitz::Array<long int, 5> deletedParticlesArray() const;
blitz::Array<double, 3> binVolumeArray() const;
// return an array of the density values at the Coordinate position (only energy
// direction left); over and underflow bin are removed
// (might not be good, since then the underflow particles are lost...)
blitz::Array<double, 1> sliceSpectrumArray(const Coordinate& position) const;
// return an array of the time in bin at the Coordinate position and the energy
// energy_eV (only pitch angle direction left); over and underflow bin are removed
blitz::Array<float, 1> sliceTimeInBinArray(const Coordinate& position,
double energy_eV) 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 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:
// coordinate ordering: r, phi, z, E
// bin numbering
// radial:
// 0, ..., num_bin_r-1: r < r_max
// num_bin_r: r >= r_max
//
// azimuthal:
// 0, ..., num_bin_phi: all
//
// longitudinal:
// -1: z < 0
// 0, ..., num_bin_z-1: 0 <= z < z_max
// num_bin_z: z >= z_max
BinCoordinate densityBin(const CylinderCoordinate& position) const;
void recalculateDensityArray();
blitz::Array<double, 4> time_in_bin_s_;
blitz::Array<long int, 4> deleted_particles_;
// use ordering r, phi, z, pitch_angle, E
// time in bin now contains the physical particle number per bin
// (not renamed, since that would require many, many changes due to
// renaming of the functions)
blitz::Array<float, 5> time_in_bin_s_;
// blitz::Array<long int, 5> deleted_particles_;
blitz::Array<float, 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_;
const PitchAngleBinning pitch_angle_binning_;
std::shared_ptr<Timer> timer_;
bool timer_restarted_ = false;
};
class ConstantDensityField : public DensityField {
+2
View File
@@ -11,6 +11,8 @@ class DriftVelocity {
DriftVelocity(std::shared_ptr<VectorField> drift_velocity);
CartesianVector driftVelocity(const Coordinate& position);
CartesianVector driftVelocity(const CartesianCoordinate& cartCoord,
const CylinderCoordinate& cylCoord);
private:
std::shared_ptr<VectorField> drift_velocity_;
+4 -1
View File
@@ -23,12 +23,15 @@ class ElectricField {
class MagneticField {
public:
MagneticField(std::shared_ptr<VectorField> field);
MagneticField(std::shared_ptr<VectorField> field,
std::shared_ptr<VectorField> gradient);
CylinderVector value(const Coordinate& position) const;
CylinderVector gradientValue(const Coordinate& position) const;
private:
std::shared_ptr<VectorField> field_;
std::shared_ptr<VectorField> gradient_;
};
class GravityField {
+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 */
@@ -6,6 +6,7 @@
#include "simulation/coordinates.h"
#include "simulation/scalar_field.h"
#include "simulation/density_field.h"
struct Limit {
Limit() : min(0), max(0){};
@@ -14,6 +15,9 @@ struct Limit {
double max;
};
// Might be possible to generalize the distributions (i.e. create parent class
// and let the two that are defined now inherit from it)
class EventPositionDistribution {
public:
EventPositionDistribution(std::shared_ptr<ScalarField> mother_density,
@@ -33,4 +37,37 @@ class EventPositionDistribution {
std::uniform_real_distribution<double> density_values;
};
// Class to draw a position from the density provided by a pointer
// to a DynamicDensityField object
class PositionDistributionFromDensity {
public:
// Constructor taking a pointer to a DynamicDensityField object
PositionDistributionFromDensity(std::shared_ptr<DynamicDensityField> density);
// draw a position from the density provided at construction using the rejection method
CylinderCoordinate drawPosition(std::mt19937* engine);
// draw a position uniformly distributed within the bin of the given index
// (note that the r-dependence of the particle number in a uniform density distribution
// is not incorporated)
CylinderCoordinate drawPosition(std::mt19937* engine, int r_idx, int phi_idx,
int z_idx);
// sets the maximum density value needed for the rejection method
// should not be called frequently, since during each call the density field is
// recalculated from scratch by the DynamicDensityField object
void setMaximumDensity();
private:
// variable storing the maximum value of the density
double maximum_density_ = 1.;
std::shared_ptr<DynamicDensityField> density_;
// distributions for the spatial directions and for the density
std::uniform_real_distribution<double> r_values;
std::uniform_real_distribution<double> phi_values;
std::uniform_real_distribution<double> z_values;
std::uniform_real_distribution<double> density_values;
};
#endif /* EVENT_POSITION_DISTRIBUTION_H */
+27 -2
View File
@@ -10,6 +10,8 @@
class DriftVelocity;
class VelocityDistribution;
class DynamicDensityField;
class MagneticField;
namespace particle {
class Particle;
@@ -26,6 +28,7 @@ struct InjectorInfo {
public:
std::shared_ptr<species::TrackedSpecie> created_specie;
std::shared_ptr<VelocityDistribution> creation_velocity_distribution;
// int multiplicity;
};
class Injector {
@@ -35,7 +38,26 @@ class Injector {
std::shared_ptr<EventPositionDistribution> position_distribution,
std::shared_ptr<DriftVelocity> mother_drift_velocity);
std::vector<particle::Particle> rollNewParticles(std::mt19937* engine);
std::vector<particle::Particle> rollNewParticles(std::mt19937* engine,
const double current_time,
const double beta_particle_weight);
// draw new particles from the DynamicDensityField of the provided specie
// the new particles are then appened to the vector queue
// the magnetic field is necessary for the determination of the direction of the
// injected particles
// the weight_factor scales the time a particle contributes to a certain bin
// and the injection time specifies the time the particle is injected (has to be
// between T, T+\DeltaT)
void drawNewParticleFromDensityField(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> field,
const double weight_factor,
const double injection_time);
void initInjectionTimeDistribution(double delta_t);
double timePassed() const;
private:
@@ -43,12 +65,15 @@ class Injector {
const double activity_;
std::shared_ptr<EventPositionDistribution> position_distribution_;
std::shared_ptr<DriftVelocity> mother_drift_velocity_;
std::uniform_real_distribution<double> injection_time_distribution_;
particle::Particle rollNewParticle(
std::mt19937* engine,
const Coordinate& position,
std::shared_ptr<species::TrackedSpecie> created_specie,
std::shared_ptr<VelocityDistribution> creation_velocity_distribution);
std::shared_ptr<VelocityDistribution> creation_velocity_distribution,
const double time_birth,
const double weight);
};
#endif /* INJECTOR_H */
+7
View File
@@ -33,12 +33,19 @@ class Interaction {
virtual double microscopicCrossSection(double energy_eV);
virtual double macroscopicCrossSection(particle::Particle& particle);
// return the time the given particle can travel in the laboratory frame
// before this specific interaction occurs (also stores the velocity of the
// target particle)
virtual double drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator);
virtual InteractionOutput performInteraction(particle::Particle& particle,
RandomNumbers* generator) = 0;
protected:
std::function<double(double)> cross_section_;
std::shared_ptr<species::Specie> target_;
CartesianVector target_velocity_;
};
}; // namespace interaction
+4
View File
@@ -38,10 +38,14 @@ inline int json_int(json_t* object, int default_value = 0) {
inline std::string json_string(json_t* object, std::string default_value = "") {
if (object) {
if (json_string_value(object)) {
return std::string(json_string_value(object));
} else {
return default_value;
}
} else {
return default_value;
}
}
inline bool json_bool(json_t* object, bool default_value = false) {
+3
View File
@@ -65,6 +65,9 @@ blitz::TinyVector<double, 3> velocityVector(
const blitz::TinyVector<double, 3>& random_unit_vector,
double mass_kg);
double cosPitchAngle(blitz::TinyVector<double, 3> vector1,
blitz::TinyVector<double, 3> vector2);
}; // namespace kinematic
#endif /* KINEMATIC_H */
+7 -1
View File
@@ -10,7 +10,12 @@ enum class DeletionType {
recombination,
max_interactions,
max_time_alive,
cluster_formation
cluster_formation,
creation_beta,
creation_density,
creation_interaction,
creation_above_2keV,
loss_above_2keV
};
class DeletionLogger {
@@ -29,6 +34,7 @@ class DeletionLogger {
private:
std::map<DeletionType, long int> num_deletions;
std::map<DeletionType, long int> sync_num_deletions;
};
#endif /* LOGGER_H */
+11 -4
View File
@@ -4,10 +4,15 @@
#include "simulation/electromagnetic_field.h"
#include "simulation/particle.h"
/*
change the mfp_m variable to a time_s variable!
*/
class Mover {
public:
virtual void move(particle::Particle* particle,
double mfp_m,
double collision_time_s,
ElectricField* electric_field,
MagneticField* magnetic_field,
GravityField* gravity_field) = 0;
@@ -18,7 +23,7 @@ class BorisMover : public Mover {
BorisMover(double maximal_time_step_s);
void move(particle::Particle* particle,
double mfp_m,
double collision_time_s,
ElectricField* electric_field,
MagneticField* magnetic_field,
GravityField* gravity_field);
@@ -29,7 +34,9 @@ class BorisMover : public Mover {
void movementStep(particle::Particle* particle,
const blitz::TinyVector<double, 3>& electric_field,
const blitz::TinyVector<double, 3>& magnetic_field,
double& moved_distance) const;
const blitz::TinyVector<double, 3>& gravity_field,
// double& moved_distance,
double timestep) const;
};
class DriftMover : public Mover {
@@ -37,7 +44,7 @@ class DriftMover : public Mover {
DriftMover(double maximal_distance);
void move(particle::Particle* particle,
double mfp_m,
double collision_time_s,
ElectricField* electric_field,
MagneticField* magnetic_field,
GravityField* gravity_field);
+23 -7
View File
@@ -14,10 +14,13 @@ class Particle {
// Vector* velocity);
Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position,
const Vector& velocity);
const Vector& velocity,
const double time_birth,
const double weight);
void position(const Coordinate& new_position);
CartesianCoordinate position() const;
CartesianCoordinate cartesianPosition() const;
CylinderCoordinate cylinderPosition() const;
void velocity(const CartesianVector& new_velocity);
CartesianVector velocity() const;
@@ -42,18 +45,31 @@ class Particle {
void increaseTimeAlive(double time_s);
double timeAlive() const;
void increaseTimeInBin(double time_s);
void resetTimeInBin();
double timeInBin() const;
long int ID() const;
double weight() const;
void indexNextInteration(const int index) { index_next_interaction_ = index; };
int indexNextInteraction() { return index_next_interaction_; };
void deposited();
bool wasDeposited();
private:
double weight_;
bool deposited_ = false;
CartesianVector velocity_;
CartesianCoordinate position_;
CartesianCoordinate position_cart_;
CylinderCoordinate position_cyl_;
double time_alive_s_;
double time_in_bin_s_;
// double time_in_bin_s_;
long int interaction_counter_;
// index of the interaction with the sortest distance (-1 if that's none of them)
int index_next_interaction_ = -1;
std::shared_ptr<species::TrackedSpecie> specie_;
long int id_;
+29
View File
@@ -5,6 +5,8 @@
#include <memory>
#include <random>
#include "blitz/array.h"
class RandomNumbers {
public:
RandomNumbers(int seed);
@@ -19,4 +21,31 @@ class RandomNumbers {
std::uniform_real_distribution<double> real_distribution_;
};
// class to handle a random walk through a density field, where every
// bin is visited exactly once
class RandomIndex {
public:
// num_bins: contains the number of bins of all dimensions of a
// density binning (order: radial, azimuthal, longitudinal,
// pitch angle, energy)
RandomIndex(blitz::TinyVector<int, 5> num_bins);
// get the next index
blitz::TinyVector<int, 5> index();
// check if all bins have been visited
bool visited_all();
// create a new random order and reset the check if all bins have been visited
void reshuffle(std::mt19937* engine);
private:
const blitz::TinyVector<int, 5> num_bins_;
std::vector<size_t> one_dimensional_indices_;
size_t total_bin_number_;
size_t current_index_in_vector_;
};
#endif /* RANDOM_NUMBERS_H */
+27 -6
View File
@@ -34,19 +34,38 @@ class Simulation {
void init(Parameter& parameter);
void start();
void finalize();
void processEvents(int events);
void processUntilTermination(particle::Particle& particle,
std::vector<particle::Particle>& particle_queue);
// cpu_syncs only included for debug purposes, e.g. only drawing decay particles
// at the 0th timestep
void processEvents(int events, const double beta_particle_weight);
void processDensityEvents(int particles_per_bin, const double weight_factor);
void processUntilTermination(particle::Particle& particle);
private:
std::vector<particle::Particle> determineInjectedParticles(
RandomNumbers* random);
std::vector<particle::Particle> determineInjectedParticles(RandomNumbers* random,
const double beta_particle_weight);
std::vector<particle::Particle> determineInjectedDensityParticles(
RandomNumbers* random,
const double weight_factor,
const int current,
std::map<std::string, double>& particleNumbers,
bool& all_bins_done);
double meanFreePath(particle::Particle& particle, RandomNumbers* random);
double meanFreePath(particle::Particle& particle, RandomNumbers* random,
std::vector<double>& macroscopic_cross_sections_m);
// draw the individual collision times of the possible interactions and return the
// minimum of them. Also sets the "nextInteractionIndex" in the particle to the
// interaction of the chosen time.
double collisionTime(particle::Particle& particle, RandomNumbers* random);
interaction::InteractionOutput interact(particle::Particle& particle,
RandomNumbers* random);
interaction::InteractionOutput interact(particle::Particle& particle,
RandomNumbers* random,
std::vector<double>& macroscopic_cross_sections_m);
blitz::Array<double,3> chargedensity();
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>
@@ -69,6 +88,8 @@ class Simulation {
std::shared_ptr<SimulationOutput> output_;
std::shared_ptr<CpuSynchronizer> cpu_synchronizer_;
std::vector<particle::Particle> queue_;
};
#endif /* SIMULATION_H */
+23 -17
View File
@@ -7,6 +7,7 @@
#include "simulation/parameter.h"
class RandomIndex;
class Mover;
class Terminator;
class Reflector;
@@ -18,6 +19,8 @@ class DeletionLogger;
class CurrentCollector;
class VelocityDistribution;
class DriftVelocity;
class PositionDistributionFromDensity;
class VelocityDistributionFromDensityField;
namespace interaction {
class Interaction;
@@ -40,7 +43,7 @@ class Specie {
std::string name() const;
virtual DensityField* densityField() = 0;
virtual VelocityDistribution* velocityDistibution() = 0;
virtual VelocityDistribution* velocityDistribution() = 0;
virtual DriftVelocity* driftVelocity() = 0;
protected:
@@ -62,14 +65,13 @@ 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> last_sync_density_field);
std::shared_ptr<DynamicDensityField> density_for_drawing);
DensityField* densityField();
VelocityDistribution* velocityDistibution();
VelocityDistribution* velocityDistribution();
DriftVelocity* driftVelocity();
DynamicDensityField* dynamicDensityField();
DynamicDensityField* lastSyncDensityField();
Mover* mover();
Terminator* terminator();
Reflector* reflector();
@@ -77,19 +79,22 @@ class TrackedSpecie : public Specie {
DeletionLogger* deletionLogger();
void deletionLogger(std::shared_ptr<DeletionLogger> new_logger);
DeletionLogger* lastSyncDeletionLogger();
void lastSyncDeletionLogger(std::shared_ptr<DeletionLogger> new_logger);
DynamicDensityField* densityForDrawing();
CurrentCollector* currentCollector();
void currentCollector(std::shared_ptr<CurrentCollector> new_collector);
CurrentCollector* lastSyncCurrentCollector();
void lastSyncCurrentCollector(
std::shared_ptr<CurrentCollector> new_collector);
std::vector<std::shared_ptr<interaction::Interaction>> interactions();
void addInteraction(std::shared_ptr<interaction::Interaction> interaction);
// getter for the raw pointer to the positionDistributionFromDensity object
PositionDistributionFromDensity* positionDistributionFromDensity();
// getter for the raw pointer to the VelocityDistributionFromDensityField object
VelocityDistributionFromDensityField* velocityDistributionFromDensityField();
// getter for the raw pointer to the RandomIndex object
RandomIndex* randomIndex();
private:
std::shared_ptr<DynamicDensityField> density_field_;
std::shared_ptr<VelocityDistribution> velocity_distribution_;
@@ -103,12 +108,13 @@ class TrackedSpecie : public Specie {
std::shared_ptr<CurrentCollector> current_collector_;
std::vector<std::shared_ptr<interaction::Interaction>> interactions_;
// fields to store the date of the last synchronization
// (after a synchronization the last_sync field and the non-last_sync field
// contain the same data)
std::shared_ptr<DynamicDensityField> last_sync_density_field_;
std::shared_ptr<DeletionLogger> last_sync_deletion_logger_;
std::shared_ptr<CurrentCollector> last_sync_current_collector_;
std::shared_ptr<DynamicDensityField> density_for_drawing_;
std::shared_ptr<PositionDistributionFromDensity>
position_distribution_from_density_;
std::shared_ptr<VelocityDistributionFromDensityField>
velocity_distribution_from_density_;
std::shared_ptr<RandomIndex> random_index_;
};
class BackgroundSpecie : public Specie {
@@ -122,7 +128,7 @@ class BackgroundSpecie : public Specie {
std::shared_ptr<DriftVelocity> drift_velocity);
DensityField* densityField();
VelocityDistribution* velocityDistibution();
VelocityDistribution* velocityDistribution();
DriftVelocity* driftVelocity();
private:
+1 -1
View File
@@ -4,7 +4,7 @@
#include "simulation/particle.h"
class Geometry;
class DynamicDensityField;
class Terminator {
public:
Terminator(long int max_interactions,
+3
View File
@@ -11,9 +11,12 @@ class Timer {
void increaseTimestep(double time_s);
void setTime(double time_s);
void resetTime();
void setDeltaT(double deltaT);
double getDeltaT() const;
private:
double current_time_s_;
double delta_t_time_resolution_;
};
#endif /* TIMER_H */
+47 -10
View File
@@ -25,22 +25,59 @@ class VelocityDistributionFromFunction : public VelocityDistribution {
std::shared_ptr<VelocityDistributionFunction> fv_;
};
/*
todo: implement this for direct interactions of simulated particles
class DensityField;
// only applicable to TrackedSpecies (i.e. only for DynamicDensityFields)
// other density don't have any information about the velocity direction
class DynamicDensityField;
class MagneticField;
// Class to draw a velocity from the pitch angle resolved density
class VelocityDistributionFromDensityField : public VelocityDistribution {
public:
// Constructor: takes shared ptr to the DynamicDensityField object from which
// should be drawn and the mass of the species to which the density
// field belongs
VelocityDistributionFromDensityField(
std::shared_ptr<DensityField> density_field);
std::shared_ptr<DynamicDensityField> density_field, double mass_kg);
// stub: can be implemented to return the drift velocity of the particles
// at the CylinderVector position of the density field
CartesianVector driftVelocity_ms(const CylinderVector& position);
CartesianVector rollVelocity_ms(
const CylinderVector& position, std::mt19937* engine);
// returns a velocity vector drawn from the energy and pitch angle distributions
// since no magnetic field is given use e_z as the direction wrt the definition
// of the pitch angle
CartesianVector rollVelocity(const Coordinate& position, std::mt19937* engine);
// returns a velocity vector drawn from the energy and pitch angle distributions
// use the given magnetic field at the provided position to determine the
// direction of velocity from the pitch angle
// the direction of the perpendicular part of the velocity vector is drawn isotropically
CartesianVector rollVelocity(
const Coordinate& position, std::mt19937* engine,
std::shared_ptr<MagneticField> magnetic_field);
// return a velocity vector drawn uniformly in the bin specifed by index
CartesianVector drawVelocity(const blitz::TinyVector<int, 5> index,
std::mt19937* engine);
CartesianVector drawVelocity(const blitz::TinyVector<int, 5> index,
std::mt19937* engine,
const Coordinate& position,
std::shared_ptr<MagneticField> magnetic_field);
private:
std::shared_ptr<DensityField> density_field_;
// mass of the species of which the density field is a part of
const double mass_kg_;
std::shared_ptr<DynamicDensityField> density_field_;
blitz::Array<double, 1> energy_values;
blitz::Array<double, 1> mu_values;
std::vector<double> energyBinBorders_;
std::vector<double> pitchAngleBinBorders_;
std::uniform_real_distribution<double> theta_distribution_;
};
*/
#endif /* VELOCITY_DISTRIBUTION_H */
+4 -8
View File
@@ -47,8 +47,10 @@ LIBS += $(HDF5P_LIBRARIES)
CXXFLAGS += $(JANSSON_INCLUDES)
LIBS += $(JANSSON_LIBRARIES)
CXXFLAGS += -g
ifeq ($(DO_DEBUGGING),true)
CXXFLAGS += -ftemplate-depth-30 -g -DBZ_DEBUG
CXXFLAGS += -ftemplate-depth-30 -DBZ_DEBUG
CXXFLAGS += -Ddebug
CXXFLAGS += -Ddebug_level$(DEBUG_LEVEL)
endif
@@ -81,7 +83,7 @@ TARGET_TEST=$(BIN_DIR)/karl_test
# Compile logic
all: blitz hdf5 jansson karl
all: blitz jansson karl
check_homebase:
ifeq ($(HOMEBASE),)
@@ -99,12 +101,6 @@ endif
blitz: check_homebase
ifeq ($(MAKE_BLITZ), true)
$(MAKE) -C external/blitz
$(MAKE) -C external/blitz install
endif
hdf5: check_homebase
ifeq ($(MAKE_H5), true)
$(MAKE) -C external/h5
endif
jansson: check_homebase
+912
View File
@@ -0,0 +1,912 @@
{
"GlobalPositionBinning": {
"CylinderBinning": {
"Radial": {
"NumberOfBins": 5,
"MaxRadius": {
"value": 4.5,
"unit": "cm"
}
},
"Longitudinal": {
"NumberOfBins": 50,
"MaxLength": {
"value": 1657,
"unit": "cm"
}
},
"Azimuthal": {
"NumberOfBins": 1
}
}
},
"SourceGeometry": {
"Cylinder": {
"Radius": {
"value": 4.5,
"unit": "cm"
},
"Height": {
"value": 1657,
"unit": "cm"
}
}
},
"Species": {
"Background": {
"TritiumGas": {
"ParticleType": "T2",
"ConstantDensityField": {
"ScalarField": {
"ScalarFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinearFromFile": {
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "data/densityDistributions/T2",
"Filename": "T2_n_vs_z_kuckert_approximated_relative.h5"
},
"xValuesKey": "/z_position(m)",
"yValuesKey": "/n(m3)",
"prefactor": 1E20
}
}
}
}
}
}
},
"VelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"IsotropicDistribution": {
"EnergyDistributionFunction": {
"MaxwellBoltzmann": {
"Temperature": {
"value": 80,
"unit": "K"
}
}
},
"Mass": {
"FromParticleType": "T2"
}
}
}
}
},
"DriftVelocity": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinearFromFile": {
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "data/velocityDistributions/T2_vz/KuckertPaper",
"Filename": "T2_vz_vs_z_kuckert_approximated.h5"
},
"xValuesKey": "/z_position(m)",
"yValuesKey": "/vz(ms)",
"prefactor": 1
}
}
}
}
}
}
}
}
},
"Tracked": {
"e-": {
"ParticleType": "electron",
"Mover": {
"Drift": {
"MaximalMovedDistance": {
"value": 1E-3,
"unit": "m"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 4.5,
"unit": "cm"
},
"Height": {
"value": 1657,
"unit": "cm"
}
}
}
},
"Reflector": {
"ReflectorDPS": {
"position_z": {
"value": 1657,
"unit": "cm"
}
}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 10,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 20E3,
"unit": "eV"
}
},
"PitchAngleBinning": {
"Type": "Linear",
"NumberOfBins": 15
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"elastic": {
"Type": "ElasticScattering",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "eT2_elastic_scattering"
},
"ScatteringAngleDistribution": {
"CompositeAngleDistribution": {
"LowerDistribution": {
"Isotropic": {}
},
"HigherDistribution": {
"AngleDistributionFromFile": {
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "data/crossSections/eT2_elastic_scattering",
"Filename": "eT2_elastic_cross_section_scattering_angle.h5"
}
}
},
"DeciderEnergy": {
"value": 10,
"unit": "eV"
}
}
}
},
"ionization1": {
"Type": "ElectronIonization",
"IonizationModel": "JanevNonDiss",
"Target": "TritiumGas",
"OutgoingElectron": "e-",
"OutgoingIon": "T2+"
},
"ionization2": {
"Type": "ElectronIonization",
"IonizationModel": "JanevDissToGround",
"Target": "TritiumGas",
"OutgoingElectron": "e-",
"OutgoingIon": "T+"
},
"ionization3": {
"Type": "ElectronIonization",
"IonizationModel": "JanevDissToFirstExcited",
"Target": "TritiumGas",
"OutgoingElectron": "e-",
"OutgoingIon": "T+"
},
"excitation0": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_B1"
},
"excitation1": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_B1prime"
},
"excitation2": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_B1primeprime"
},
"excitation3": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_C1"
},
"excitation4": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_D1"
},
"excitation5": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_D1prime"
},
"excitation6": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_symmetry_forbidden_EF1"
},
"excitation7": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_symmetry_forbidden_HHb"
},
"excitation8": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_symmetry_forbidden_GK1"
},
"excitation9": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_singlet_symmetry_forbidden_I1"
},
"excitation10": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_triplet_A3"
},
"excitation11": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_triplet_B3"
},
"excitation12": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_triplet_C3"
},
"excitation13": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_triplet_E3"
},
"excitation14": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_triplet_D3"
},
"excitation15": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_vibrational_first"
},
"excitation16": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "janev_vibrational_second"
},
"excitation17": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "england_rotational_j0_to_j2"
},
"excitation18": {
"Type": "Excitation",
"Target": "TritiumGas",
"ExcitationState": "england_rotational_j1_to_j3"
}
}
},
"T2+": {
"ParticleType": "T2+",
"Mover": {
"Drift": {
"MaximalMovedDistance": {
"value": 1E-3,
"unit": "m"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 4.5,
"unit": "cm"
},
"Height": {
"value": 1657,
"unit": "cm"
}
}
}
},
"Reflector": {
"NoReflector": {}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 10,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 1E3,
"unit": "eV"
}
},
"PitchAngleBinning": {
"Type": "Linear",
"NumberOfBins": 15
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"charge exchange": {
"Type": "ChargeExchange",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "T2pT2_charge_exchange_janev"
}
},
"clustering": {
"Type": "Clustering",
"Target": "TritiumGas",
"Product": "T3+",
"CrossSection": {
"PredefinedFunction": "T2pT2_clustering_janev"
}
},
"free_movement_example": {
"Type": "FreeMovement"
}
}
},
"T+": {
"ParticleType": "T+",
"Mover": {
"Boris": {
"BorisStepsPerMovementCylce": 10,
"MaximalTimestepLength": {
"value": 1E-8,
"unit": "s"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 4.5,
"unit": "cm"
},
"Height": {
"value": 1657,
"unit": "cm"
}
}
}
},
"Reflector": {
"NoReflector": {}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 10,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 1E3,
"unit": "eV"
}
},
"PitchAngleBinning": {
"Type": "Linear",
"NumberOfBins": 15
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"elastic scattering": {
"Type": "ElasticScattering",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "TpT2_elastic_scattering_tabata"
},
"ScatteringAngleDistribution": {
"Isotropic": {}
}
},
"clustering1": {
"Type": "Clustering",
"Target": "TritiumGas",
"Product": "T3+",
"CrossSection": {
"PredefinedFunction": "TpT2_clustering_radiative_ascendion_pasil"
}
},
"clustering2": {
"Type": "Clustering",
"Target": "TritiumGas",
"Product": "T3+",
"CrossSection": {
"PredefinedFunction": "TpT2_clustering_tertiary_ascendion_pasil"
}
},
"free_movement_example": {
"Type": "FreeMovement"
}
}
},
"T3+": {
"ParticleType": "T3+",
"Mover": {
"Drift": {
"MaximalMovedDistance": {
"value": 1E-3,
"unit": "m"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 4.5,
"unit": "cm"
},
"Height": {
"value": 1657,
"unit": "cm"
}
}
}
},
"Reflector": {
"NoReflector": {}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 10,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 1E3,
"unit": "eV"
}
},
"PitchAngleBinning": {
"Type": "Linear",
"NumberOfBins": 15
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"elastic scattering": {
"Type": "ElasticScattering",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "T3pT2_elastic_scattering_tabata"
},
"ScatteringAngleDistribution": {
"Isotropic": {}
}
},
"free_movement_example": {
"Type": "FreeMovement"
}
}
}
}
},
"Injector": {
"CreatedSpecies": {
"specie1": {
"TrackedSpecieName": "e-",
"CreationVelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"IsotropicDistribution": {
"EnergyDistributionFunction": {
"TritiumBetaDecay": {}
},
"Mass": {
"FromParticleType": "electron"
}
}
}
}
}
},
"specie2": {
"TrackedSpecieName": "T2+",
"CreationVelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"IsotropicDistribution": {
"EnergyDistributionFunction": {
"MaxwellBoltzmann": {
"Temperature": {
"value": 80,
"unit": "K"
}
}
},
"Mass": {
"FromParticleType": "T2"
}
}
}
}
}
}
},
"EventPositionDistribution": {
"ScalarField": {
"ScalarFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinearFromFile": {
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "data/densityDistributions/T2",
"Filename": "T2_n_vs_z_kuckert_approximated_relative.h5"
},
"xValuesKey": "/z_position(m)",
"yValuesKey": "/n(m3)",
"prefactor": 1
}
}
}
}
}
},
"DensityLimit": {
"min": 0,
"max": 1
},
"PositionLimits": {
"rPosition": {
"min": 0,
"max": 0.045
},
"phiPosition": {
"min": 0,
"max": 6.28318530718
},
"zPosition": {
"min": 0,
"max": 16.57
}
}
},
"MotherDriftVelocity": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinearFromFile": {
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "data/velocityDistributions/T2_vz/KuckertPaper",
"Filename": "T2_vz_vs_z_kuckert_approximated.h5"
},
"xValuesKey": "/z_position(m)",
"yValuesKey": "/vz(ms)",
"prefactor": 1
}
}
}
}
}
}
},
"Activity": {
"value": 1E7,
"unit": "Bq"
}
},
"ElectricField": {
"Background": {
"VectorField": {
"VectorFieldConstant": {
"constant": {
"vector": [
0,
0,
0
]
},
"unit": "V/m"
}
}
},
"Dynamic": {
"VectorField": {
"VectorFieldConstant": {
"constant": {
"vector": [
0,
0,
0
]
},
"unit": "V/m"
}
}
}
},
"MagneticField": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 2.5
}
}
}
},
"GradientField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 0
}
}
}
}
},
"GravityField": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 0
}
}
}
}
},
"PoissonSolver": {
"BoundaryGeometry": {
"CreateSameAs": ["SourceGeometry"]
},
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"Boundary": {
"Top": {
"type": "neumann",
"value": 0
},
"Bottom": {
"type": "dirichlet",
"value": 0
},
"Hull": {
"type": "dirichlet",
"value": 0
}
},
"TargetAccuracy": 1e-6,
"NumCycles": 2e4,
"DoSolver": "false"
},
"Simulation": {
"NumberTimesteps": 10,
"EventStride": 1000,
"TimeResolutionEvents": 10,
"DensityEventsPerCPU": 1000,
"BetaDecayEventsPerCPU": 1000
},
"Output": {
"folder": "output",
"filename": "katrin_drawing",
"DensityFields": {
"Species": "all",
"Intervall": 1,
"OverwriteLast": "false"
},
"CurrentBorders": {
"Species": "all",
"Intervall": "EachSync",
"OverwriteLast": "false"
},
"DeletionLogger": {
"Species": "all",
"Intervall": "EachSync",
"OverwriteLast": "false"
},
"PoissonSolver": {
"Intervall": 1,
"OverwriteLast": "false"
},
"RestartInfo": {
"Intervall": 1,
"OverwriteLast": "false"
}
},
"Restart" : {
"Do": "false",
"SyncPeriod": 2,
"PathToH5": {
"Type": "RelativeToHomebase",
"RelativePath": "output",
"Filename": "breakInMover3",
"comment": "if the restarted file and the output file are the same, the data that is restarted from is overwritten!"
}
},
"RandomNumbers": {
"Seed": 1337
}
}
+536
View File
@@ -0,0 +1,536 @@
{
"GlobalPositionBinning": {
"CylinderBinning": {
"Radial": {
"NumberOfBins": 10,
"MaxRadius": {
"value": 5,
"unit": "cm"
}
},
"Longitudinal": {
"NumberOfBins": 75,
"MaxLength": {
"value": 300,
"unit": "cm"
}
},
"Azimuthal": {
"NumberOfBins": 1
}
}
},
"SourceGeometry": {
"Cylinder": {
"Radius": {
"value": 5,
"unit": "cm"
},
"Height": {
"value": 300,
"unit": "cm"
}
}
},
"Species": {
"Background": {
"TritiumGas": {
"ParticleType": "T",
"ConstantDensityField": {
"ScalarField": {
"ScalarFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"Exponential": {
"scale": -7.1307e-4,
"prefactor": 1E17
}
}
}
}
}
}
},
"VelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"IsotropicDistribution": {
"EnergyDistributionFunction": {
"MaxwellBoltzmann": {
"Temperature": {
"value": 5,
"unit": "K"
}
}
},
"Mass": {
"FromParticleType": "T"
}
}
}
}
},
"DriftVelocity": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinear": {
"xValues": [
0,
16
],
"yValues": [
0,
0
],
"prefactor": 1
}
}
}
}
}
}
}
}
},
"Tracked": {
"e-": {
"ParticleType": "electron",
"Mover": {
"Drift": {
"MaximalMovedDistance": {
"value": 1e-3,
"unit": "m"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 5,
"unit": "cm"
},
"Height": {
"value": 300,
"unit": "cm"
}
}
}
},
"Reflector": {
"NoReflector": {}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 100,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 20E3,
"unit": "eV"
}
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"freeMovement": {
"Type": "FreeMovement"
},
"elastic": {
"Type": "ElasticScattering",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "eT2_elastic_scattering_constant"
},
"ScatteringAngleDistribution": {
"Isotropic": {}
}
}
}
},
"T+": {
"ParticleType": "T+",
"Mover": {
"Drift":{
"MaximalMovedDistance": {
"value": 1e-3,
"unit": "m"
}
}
},
"Terminator": {
"MaximumInteractions": 1E6,
"MaxTimeAlive": {
"value": 1,
"unit": "s"
},
"BoundaryGeometry": {
"Cylinder": {
"Radius": {
"value": 5,
"unit": "cm"
},
"Height": {
"value": 300,
"unit": "cm"
}
}
}
},
"Reflector": {
"NoReflector": {}
},
"DensityField": {
"DynamicDensityField": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"EnergyBinning": {
"Type": "Logarithmic",
"NumberOfBins": 100,
"MinEnergy": {
"value": 1E-6,
"unit": "eV"
},
"MaxEnergy": {
"value": 1E3,
"unit": "eV"
}
}
}
},
"VelocityDistribution": {
"null": {}
},
"DriftVelocity": {
"null": {}
},
"Loggers": {
"Deletion": {
"Type": "all"
}
},
"CurrentCollector": {
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
}
},
"Interactions": {
"name1": {
"Type": "FreeMovement"
},
"elastic": {
"Type": "ElasticScattering",
"Target": "TritiumGas",
"CrossSection": {
"PredefinedFunction": "eT2_elastic_scattering_constant"
},
"ScatteringAngleDistribution": {
"Isotropic": {}
}
}
}
}
}
},
"Injector": {
"CreatedSpecies": {
"specie1": {
"TrackedSpecieName": "e-",
"CreationVelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"DirectedDistribution": {
"EnergyDistributionFunction": {
"Constant": {
"constant": {
"value": 4.30867e-4,
"unit": "eV"
}
}
},
"Mass": {
"FromParticleType": "electron"
},
"Direction":{
"vector": [1, 0, 1]
}
}
}
}
}
},
"specie2": {
"TrackedSpecieName": "T+",
"CreationVelocityDistribution": {
"VelocityDistributionFromFunction": {
"VelocityDistributionFunction": {
"DirectedDistribution": {
"EnergyDistributionFunction": {
"Constant": {
"constant": {
"unit": "eV",
"value": 4.30867e-4
}
}
},
"Mass": {
"FromParticleType": "T"
},
"Direction": {
"vector": [1, 0, 1]
}
}
}
}
}
}
},
"EventPositionDistribution": {
"ScalarField": {
"ScalarFieldFunctionInZ": {
"zFunction": {
"Product": {
"fi": {
"Constant": {
"constant": 1
}
},
"fj": {
"Constant": {
"constant": 1
}
},
"fk": {
"PiecewiseLinear": {
"xValues": [0.0, 3.0],
"yValues": [1.0, 1.0],
"prefactor": 1E15
}
}
}
}
}
},
"DensityLimit": {
"min": 0,
"max": 1E15
},
"PositionLimits": {
"rPosition": {
"min": 0,
"max": 0.05
},
"phiPosition": {
"min": 0,
"max": 6.28318530718
},
"zPosition": {
"min": 0,
"max": 0.3
}
}
},
"MotherDriftVelocity": {
"VectorField": {
"VectorFieldConstant": {
"constant": {
"vector": [
0,
0,
0
]
},
"unit": "m/s"
}
}
},
"Activity": {
"value": 1e7,
"unit": "Bq"
}
},
"ElectricField": {
"Background": {
"VectorField": {
"VectorFieldConstant": {
"constant": {
"vector": [
0,
0,
0
]
},
"unit": "V/m"
}
}
},
"Dynamic": {
"VectorField": {
"VectorFieldConstant": {
"constant": {
"vector": [
0,
0,
0
]
},
"unit": "V/m"
}
}
}
},
"MagneticField": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 2.5
}
}
}
},
"GradientField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 0
}
}
}
}
},
"GravityField": {
"VectorField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": -9.81
}
}
}
}
},
"PoissonSolver": {
"BoundaryGeometry": {
"CreateSameAs": ["SourceGeometry"]
},
"PositionBinning": {
"CreateSameAs": [
"GlobalPositionBinning"
]
},
"Boundary": {
"Top": {
"type": "neumann",
"value": 0
},
"Bottom": {
"type": "dirichlet",
"value": 0
},
"Hull": {
"type": "dirichlet",
"value": 0
}
},
"TargetAccuracy": 1e-6,
"NumCycles": 2e4,
"DoSolver": "true"
},
"Simulation": {
"SimulatedEvents": 200000,
"EventStride": 5000,
"TimeResolutionEvents": 20000,
"commentTimeRes": "number of events over all cpus defining the timeresolution"
},
"Output": {
"folder": "output",
"filename": "timerestest3",
"DensityFields": {
"Species": "all",
"Intervall": 1,
"OverwriteLast": "false"
},
"CurrentBorders": {
"Species": [
"e-",
"T+"
],
"Intervall": "EachSync",
"OverwriteLast": "false"
},
"DeletionLogger": {
"Species": "all",
"Intervall": "EachSync",
"OverwriteLast": "false"
},
"PoissonSolver": {
"Intervall": "EachSync",
"OverwriteLast": "false"
}
},
"RandomNumbers": {
"Seed": 1337
}
}
+233
View File
@@ -4,6 +4,7 @@
#include <hdf5_hl.h>
#include "simulation/errors.h"
#include "constants/sim_constants.h"
Hdf5Reader::Hdf5Reader(std::string directory, std::string filename)
: absolute_filename_((directory + "/" + filename + ".h5").c_str()) {}
@@ -100,3 +101,235 @@ blitz::Array<double, 1> Hdf5Reader::readD1Double(std::string path) {
H5Fclose(file);
return data.copy();
}
double Hdf5Reader::readDouble(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 = 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 != 1) {
ERROR("The given dataset is not one dimensional. It has dims: " + ndims);
}
H5Sget_simple_extent_dims(dataspace, dims, NULL);
double data;
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,
&data);
H5Sclose(dataspace);
H5Dclose(dataset);
H5Fclose(file);
return data;
}
blitz::Array<double, 4> Hdf5Reader::readD4Double(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 != 4) {
ERROR("The given dataset is not four-dimensional. It has dims: " + ndims);
}
H5Sget_simple_extent_dims(dataspace, dims, NULL);
blitz::Array<double, 4> data(dims[0], dims[1], dims[2], dims[3]);
H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Fclose(file);
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);
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 != 4) {
ERROR("The given dataset is not four-dimensional. It has dims: " + ndims);
}
H5Sget_simple_extent_dims(dataspace, dims, NULL);
blitz::Array<long int, 4> data(dims[0], dims[1], dims[2], dims[3]);
H5Dread(dataset, H5T_NATIVE_LONG, H5S_ALL, H5S_ALL, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Fclose(file);
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
// path has to only be the path to the group that contains the two dataset "string" and "length"
std::stringstream Hdf5Reader::readEngineString(std::string path) {
std::stringstream out;
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
// H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset = H5Dopen2(file, (path + "/string").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);
// might be beneficial to check if the datatype
// is the expected one (H5T_STRING)
hid_t dtype = H5Dget_type(dataset);
size_t size = H5Tget_size(dtype);
if(size != SimConstants::engine_string_length_max) {
ERROR("Size of the string is not the required size of " +
std::to_string(SimConstants::engine_string_length_max) +
", size of string: " + std::to_string(size));
}
#ifdef debug_level3
DEBUG_LEVEL_3("RestartInfo: " + std::to_string(H5Tdetect_class(dtype, H5T_STRING)));
#endif
const int ndims = H5Sget_simple_extent_ndims(dataspace);
hsize_t dims[ndims];
if (ndims != 1) {
ERROR("The given dataset is not one dimensional. It has dims: " + ndims);
}
#ifdef debug_level3
DEBUG_LEVEL_3(std::to_string(ndims));
DEBUG_LEVEL_3("RestartInfo: " + std::to_string(size));
#endif
H5Sget_simple_extent_dims(dataspace, dims, NULL);
char data[SimConstants::engine_string_length_max];
H5Dread(dataset, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT,
&data);
H5Tclose(dtype);
H5Sclose(dataspace);
H5Dclose(dataset);
dataset = H5Dopen2(file, (path + "/length").c_str(), H5P_DEFAULT);
dataspace = H5Dget_space(dataset);
if(dataspace < 0) {
ERROR("Dataspace for length could not be opened");
}
const int ndimsL = H5Sget_simple_extent_ndims(dataspace);
hsize_t dimsL[ndimsL];
if(ndimsL != 1) {
ERROR("length dataset is not 1-dimensional");
}
H5Sget_simple_extent_dims(dataspace, dimsL, NULL);
size_t length;
H5Dread(dataset, H5T_NATIVE_HSIZE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &length);
#ifdef debug_level3
DEBUG_LEVEL_3("RestartInfo: read length from file: " + std::to_string(length));
#endif
H5Sclose(dataspace);
H5Dclose(dataset);
H5Fclose(file);
std::stringstream temp;
temp << data;
out << temp.str().substr(0, length);
#ifdef debug_level3
DEBUG_LEVEL_3(std::to_string(out.str().size()));
#endif
return out;
}
+216
View File
@@ -4,6 +4,8 @@
#include <hdf5_hl.h>
#include <sys/stat.h>
#include <iostream>
#include "simulation/errors.h"
#include "constants/sim_constants.h"
#include "simulation/mpi_communication.h"
@@ -21,6 +23,7 @@ void Hdf5Writer::createFile(std::string absolute_filename) {
if (MpiCommunication::mpi_rank == 0) {
hid_t file = H5Fcreate(absolute_filename.c_str(), H5F_ACC_TRUNC,
H5P_DEFAULT, H5P_DEFAULT);
H5Fclose(file);
}
}
@@ -162,6 +165,70 @@ 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<float, 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_FLOAT, 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_FLOAT, 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);
@@ -195,6 +262,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);
@@ -387,6 +487,8 @@ void Hdf5Writer::write(const std::string& data, std::string path) {
hid_t dtype;
dtype = H5Tcreate(H5T_STRING, data.size());
// see:https://stackoverflow.com/questions/581209/how-to-best-write-out-a-stdvector-stdstring-container-to-a-hdf5-dataset
// for the way to create a variable length dtype and how to write it
// turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
@@ -402,7 +504,121 @@ void Hdf5Writer::write(const std::string& data, std::string path) {
H5Dwrite(dataset, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data.c_str());
H5Dclose(dataset);
H5Tclose(dtype);
H5Pclose(lcpl);
H5Sclose(filespace);
H5Fclose(file);
}
// maybe split into a function that writes a string in parallel and one that writes an
// int in parallel. Would be a bit more effort but it would be more consistent with the
// way the rest of the writer functions work
// writes a string-representation of an random numbers engine (right now assumed mt19973)
// written output: input string padded with 0 at the end to achieve a fixed length
// and the size of the input string
void Hdf5Writer::writeRNG(const std::string& data, std::string path_base) {
/*
* Note:
* Writing the string representation of the std::mt19973 engine might not be the best option.
* (see comment for statStringSizeMax_ in hdf5_writer.h)
* The potential issues are: de-serialization using '>>' not platform independent (i.e. can not be
* restarted), length of the max size uncertain, relatively large storage space usage (>6370 bytes/cpu/output)
* (comparision: HAWK: size of file ~ 3.4MB/sync, RestartInfo Size (estimate) ~ 81MB/sync (12800 procs))
*
* Second option: wrapper for the engine and count the times its been used and store that number.
* Also has an issue with restarts on a different platform (since engine implementation is platform dependent).
* Signigicantly lower storage space usage. Restoring the engine state would easy in implementation
* (potentially a bit more expensive in execution time: discard() function).
*/
MPI_Info info;
MPI_Info_create(&info);
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_fapl_mpio(fapl, MPI_COMM_WORLD, info);
// MPI_Info_free(&info);
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, fapl);
if(file < 0) {
SIM_INFO("file could not be opened");
}
hsize_t scalar = 1;
hid_t filespace = H5Screate_simple(1, &scalar, NULL);
hid_t lcpl = H5Pcreate(H5P_LINK_CREATE);
H5Pset_create_intermediate_group(lcpl, 1);
int mpi_rank = MpiCommunication::mpiRank();
std::string out{data};
size_t stateStringSize = out.size();
if(stateStringSize > SimConstants::engine_string_length_max) {
ERROR("Max Size (" + std::to_string(SimConstants::engine_string_length_max) + ") too small. String size: " + std::to_string(stateStringSize));
}
out.insert(out.end(), (SimConstants::engine_string_length_max - stateStringSize), '0');
// apparently it's not possible to use 'H5T_VARIABLE' with the MPI-I/O file driver
// (since it doesn't allow for variable size objects to be created, see: https://davis.lbl.gov/Manuals/HDF5-1.8.7/TechNotes/VLTypes.html)
hid_t dtype = H5Tcreate(H5T_STRING, SimConstants::engine_string_length_max);
// store old error stack info
H5E_auto2_t oldfunc;
void* old_client_data;
H5Eget_auto2(H5E_DEFAULT, &oldfunc, &old_client_data);
// turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
for(int i = 0; i < MpiCommunication::mpiSize(); ++i) {
std::string path = path_base + std::to_string(i);
#ifdef debug_level3
DEBUG_LEVEL_3(path);
#endif
hid_t dataset_string = H5Dcreate2(file, (path + "/string").c_str(), dtype, filespace, lcpl, H5P_DEFAULT, H5P_DEFAULT);
// this sadly seems to be the option that takes the least amount of effort.
// H5Lexits() would be an option but (!) each group would need to be checked for existance first, which sucks
if(dataset_string < 0) {
#ifdef debug_level3
DEBUG_LEVEL_3("Dataset could not be created");
#endif
dataset_string = H5Dopen2(file, (path + "/string").c_str(), H5P_DEFAULT);
if(dataset_string < 0) {
ERROR("Dataset for string can neither be created nor opened");
}
}
hid_t dataset_length = H5Dcreate2(file, (path + "/length").c_str(), H5T_NATIVE_HSIZE, filespace, lcpl, H5P_DEFAULT, H5P_DEFAULT);
if(dataset_length < 0) {
#ifdef debug_level3
DEBUG_LEVEL_3("Dataset could not be created");
#endif
dataset_length = H5Dopen2(file, (path + "/length").c_str(), H5P_DEFAULT);
if(dataset_length < 0) {
ERROR("Dataset for length can neither be created nor opened");
}
}
if(i == mpi_rank) {
H5Dwrite(dataset_string, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, out.c_str());
H5Dwrite(dataset_length, H5T_NATIVE_HSIZE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &stateStringSize);
}
H5Dclose(dataset_string);
H5Dclose(dataset_length);
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, oldfunc, old_client_data);
H5Tclose(dtype);
H5Pclose(lcpl);
H5Sclose(filespace);
H5Fclose(file);
H5Pclose(fapl);
}
// Debug utility
std::string Hdf5Writer::AbsoluteFileName() const {
return absolute_filename_;
}
+144
View File
@@ -0,0 +1,144 @@
#include <sstream>
#include <random>
#include "IO/restart.h"
#include "simulation/random_numbers.h"
#include "simulation/mpi_communication.h"
#include "simulation/errors.h"
#include "simulation/species.h"
#include "simulation/density_field.h"
#include "poisson_solver/poisson_solver.h"
#include "simulation/timer.h"
#include "simulation/event_position_distribution.h"
// Note: error handling is a bit messy. Sometimes it's dealt with in the
// called reset function (e.g. in the density field) and sometimes it's
// handled here
Restart::Restart(bool do_restart, std::string absolute_filename,
std::string restart_identifier):
do_restart_(do_restart),
restart_identifier_(restart_identifier),
reader_(Hdf5Reader(absolute_filename)) {}
void Restart::restart(std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, RandomNumbers* random_numbers) {
if(!do_restart_) {
return;
}
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting rng");
#endif
restartRandomNumbers(random_numbers);
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting poisson solver.");
#endif
restartPoissonSolver(poisson_solver);
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting timer.");
#endif
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);
pair.second->positionDistributionFromDensity()->setMaximumDensity();
}
}
void Restart::restartRandomNumbers(RandomNumbers* random) {
std::string path = "/RestartInfo/" + restart_identifier_
+ "/CPU_" + std::to_string(MpiCommunication::mpiRank());
std::stringstream engine_state = reader_.readEngineString(path);
std::mt19937* engine = random->engine();
engine_state >> *engine;
std::stringstream check;
check << *engine;
if(check.str() != engine_state.str()) {
ERROR("Something went wrong in the initialization of the "
"random engine.");
}
}
// only restart the time from which the simulation is restarted.
void Restart::restartTimer(species::TrackedSpecie* reference_specie) {
double time;
double delta_t;
// physical time
{
std::string path = reference_specie->name() + "/DensityField/SimulationData/" +
restart_identifier_ + "/PhysicalTime";
#ifdef debug_level3
DEBUG_LEVEL_3(path);
#endif
// probably add a function in the reader to read a single double value instead of
// an 1d array of doubles
blitz::Array<double, 1> restart_time = reader_.readD1Double(path);
if(restart_time.size() != 1) {
ERROR("Physical time should be a single double value but " +
std::to_string(restart_time.size()) +
" was read by the hdf5 reader.");
}
time = restart_time(0);
}
// delta t
{
std::string path = reference_specie->name() + "/CurrentCollector/SimulationData/" +
restart_identifier_ + "/PhysicalTime";
#ifdef debug_level3
DEBUG_LEVEL_3(path);
#endif
// probably add a function in the reader to read a single double value instead of
// a 1d array of doubles
blitz::Array<double, 1> time_resolution = reader_.readD1Double(path);
if(time_resolution.size() != 1) {
ERROR("Physical time should be a single double value but " +
std::to_string(time_resolution.size()) +
" was read by the hdf5 reader.");
}
delta_t = time_resolution(0);
}
reference_specie->dynamicDensityField()->restartTimer(time, delta_t);
return;
}
void Restart::restartDrawingDensityField(DynamicDensityField* field, std::string path) {
// restart TimeInBin field
{
std::string path_to_data = path + "/TimeInBin";
#ifdef debug_level3
DEBUG_LEVEL_3(path_to_data);
#endif
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);
// }
return;
}
// could be removed, but then the potential has to be calculated
// as in the normal simulation cycle
void Restart::restartPoissonSolver(PoissonSolver* solver) {
std::string path = "PoissonSolver/SimulationData/" + restart_identifier_ +
"/Potential/";
#ifdef debug_level3
DEBUG_LEVEL_3(path);
#endif
blitz::Array<double, 3> potential = reader_.readD3Double(path);
solver->setPotential(potential);
}
+140 -8
View File
@@ -1,3 +1,4 @@
#include "mpi.h"
#include "IO/simulation_output.h"
#include "IO/hdf5_writer.h"
@@ -29,6 +30,10 @@ void SimulationOutput::setPotentialOutput(OutputTask task) {
task_potential_ = task;
}
void SimulationOutput::setRestartInfoOutput(OutputTask task) {
task_rng_ = task;
}
void SimulationOutput::writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
const std::shared_ptr<PoissonSolver>& poisson_solver) {
@@ -53,14 +58,25 @@ void SimulationOutput::writeMetaData(
std::string specie_path = "/" + task_potential_.specie_name;
writeMetaData(poisson_solver.get(), specie_path);
}
// write the number of mpi processes used in the current simulation
{
writer.write(MpiCommunication::mpiSize(), "/NumberProcesses");
}
}
}
void SimulationOutput::writeSimulationData(
int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver) {
PoissonSolver* poisson_solver,
std::mt19937* engine) {
if (MpiCommunication::mpi_rank == 0) {
#ifdef debug_level2
DEBUG_LEVEL_2("Write density field data.");
#endif
for (auto& task : tasks_density_fields_) {
if (cpu_sync % task.intervall == 0) {
std::string specie_path = "/" + task.specie_name;
@@ -68,7 +84,9 @@ void SimulationOutput::writeSimulationData(
specie_path, cpu_sync, task.overwrite_last);
}
}
#ifdef debug_level2
DEBUG_LEVEL_2("Write current collector data.");
#endif
for (auto& task : tasks_current_collector_) {
if (cpu_sync % task.intervall == 0) {
std::string specie_path = "/" + task.specie_name;
@@ -76,7 +94,9 @@ void SimulationOutput::writeSimulationData(
specie_path, cpu_sync, task.overwrite_last);
}
}
#ifdef debug_level2
DEBUG_LEVEL_2("Write deletion logger data.");
#endif
for (auto& task : tasks_deletion_logger_) {
if (cpu_sync % task.intervall == 0) {
std::string specie_path = "/" + task.specie_name;
@@ -84,13 +104,21 @@ void SimulationOutput::writeSimulationData(
specie_path, cpu_sync, task.overwrite_last);
}
}
#ifdef debug_level2
DEBUG_LEVEL_2("Write PoissonSolver data.");
#endif
if (cpu_sync % task_potential_.intervall == 0) {
std::string poisson_path = "/" + task_potential_.specie_name;
writeSimulationData(poisson_solver, poisson_path, cpu_sync,
task_potential_.overwrite_last);
}
}
// if the rng intervall = 0 (no neg. intervalls allowed) -> no 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);
}
}
void SimulationOutput::writeSimulationData(DynamicDensityField* density_field,
@@ -103,15 +131,23 @@ void SimulationOutput::writeSimulationData(DynamicDensityField* density_field,
}
std::string path = species_path + "/DensityField/SimulationData/" + sync_path;
#ifdef debug_level3
DEBUG_LEVEL_3("Write spectrum.");
#endif
writeSpectrum(density_field, path);
#ifdef debug_level3
DEBUG_LEVEL_3("Write density.");
#endif
writeDensity(density_field, path);
#ifdef debug_level3
DEBUG_LEVEL_3("Write time in bin.");
#endif
writeTimeInBin(density_field, path);
DEBUG_LEVEL_3("Write deleted particles.");
writeDeletedParticles(density_field, path);
// DEBUG_LEVEL_3("Write deleted particles.");
// writeDeletedParticles(density_field, path);
#ifdef debug_level3
DEBUG_LEVEL_3("Write physical time.");
#endif
writePhysicalTime(density_field, path);
}
@@ -125,11 +161,17 @@ void SimulationOutput::writeSimulationData(CurrentCollector* current_collector,
}
std::string path =
species_path + "/CurrentCollector/SimulationData/" + sync_path;
#ifdef debug_level3
DEBUG_LEVEL_3("Write current crossings.");
#endif
writeCurrentCrossings(current_collector, path);
#ifdef debug_level3
DEBUG_LEVEL_3("Write current.");
#endif
writeCurrent(current_collector, path);
#ifdef debug_level3
DEBUG_LEVEL_3("Write physical time.");
#endif
writePhysicalTime(current_collector, path);
}
@@ -142,7 +184,9 @@ void SimulationOutput::writeSimulationData(DeletionLogger* logger,
sync_path = "LastSyncPeriod";
}
std::string path = species_path + "/DeletionLogger/" + sync_path;
#ifdef debug_level3
DEBUG_LEVEL_3("Write number of deletions.");
#endif
writeNumDeletions(logger, path);
}
@@ -155,10 +199,34 @@ void SimulationOutput::writeSimulationData(PoissonSolver* poisson_solver,
sync_path = "/LastSyncPeriod";
}
std::string path = poisson_path + "/SimulationData" + sync_path;
#ifdef debug_level3
DEBUG_LEVEL_3("Write potential.");
#endif
writePotential(poisson_solver, path);
}
void SimulationOutput::writeRestartData(std::mt19937* engine, int cpu_sync,
bool overwrite_last) {
std::string path_base = "/RestartInfo/SyncPeriod_" +
std::to_string(cpu_sync) +
"/CPU_";
if (overwrite_last) {
path_base = "/RestartInfo/LastSyncPeriod/CPU_";
}
#ifdef debug_level3
DEBUG_LEVEL_3(path_base);
DEBUG_LEVEL_3("Write restart info.");
#endif
writeRandomEngineState(engine, path_base);
// DEBUG_LEVEL_3("Done");
}
void SimulationOutput::writeRandomEngineState(std::mt19937* engine, std::string path) {
std::ostringstream engine_state;
engine_state << (*engine);
writer.writeRNG(engine_state.str(), path);
}
void SimulationOutput::writeNumDeletions(DeletionLogger* logger,
std::string path) {
std::string path_to_deletions = path + "/NumDeletions";
@@ -174,6 +242,16 @@ void SimulationOutput::writeNumDeletions(DeletionLogger* logger,
writer.write(pair.second, path_to_deletions + "/MaxTimeAlive");
} else if (pair.first == DeletionType::cluster_formation) {
writer.write(pair.second, path_to_deletions + "/ClusterFormation");
} else if (pair.first == DeletionType::creation_beta) {
writer.write(pair.second, path_to_deletions + "/CreationBeta");
} else if (pair.first == DeletionType::creation_density) {
writer.write(pair.second, path_to_deletions + "/CreationDensity");
} else if (pair.first == DeletionType::creation_interaction) {
writer.write(pair.second, path_to_deletions + "/CreationInteraction");
} else if (pair.first == DeletionType::creation_above_2keV) {
writer.write(pair.second, path_to_deletions + "/CreationAbove2keV");
} else if (pair.first == DeletionType::loss_above_2keV) {
writer.write(pair.second, path_to_deletions + "/LossAbove2keV");
}
}
}
@@ -218,19 +296,23 @@ void SimulationOutput::writeDensity(DynamicDensityField* 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::writeDeletedParticles(DynamicDensityField* density_field,
std::string path) {
writer.write(density_field->deletedParticlesArray(),
path + "/DeletedParticles");
}
// void SimulationOutput::writeDeletedParticles(DynamicDensityField* 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::writePotential(PoissonSolver* poisson_solver, std::string path) {
writer.write(poisson_solver->potential(), path + "/Potential");
}
@@ -242,6 +324,7 @@ void SimulationOutput::writeMetaData(species::TrackedSpecie* specie) {
writer.write(specie->charge_C(), specie_path + "/Charge");
}
/*
void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
std::string path) {
std::string path_to_field = path + "/DensityField";
@@ -250,6 +333,55 @@ void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
writeBinBorders(density_field, path_to_field);
writeNumBins(density_field, path_to_field);
}
*/
// Todo: use the functions again (as in the method thats uncommented above)
void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
std::string path) {
std::string path_to_field = path + "/DensityField";
// 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) {
+4
View File
@@ -55,6 +55,10 @@ std::function<double(double)> Product(
return product;
};
}
std::function<double(double)> Exponential(double prefactor, double scale) {
return [=](double x) { return prefactor * std::exp(scale * x); };
}
}; // namespace D1ToD1
namespace D3ToD1 {
+69
View File
@@ -10,7 +10,9 @@ namespace generator {
CylinderBinning buildPositionBinning(json_t* object) {
if (json_object_by_path(object, {"CylinderBinning"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating position binning: cylinder binning.");
#endif
object = json_object_by_path(object, {"CylinderBinning"});
json_t* radial = json_object_by_path(object, {"Radial"});
@@ -36,6 +38,7 @@ CylinderBinning buildPositionBinning(json_t* object) {
json_read_length(json_object_by_path(longitudinal, {"MaxLength"}), "m");
ASSERT_POSITIVE(&max_length, "Radius must be positive");
#ifdef debug_level3
DEBUG_LEVEL_3("with number of bins radial: " +
std::to_string(number_of_bins_radial));
DEBUG_LEVEL_3("with number of bins azimuthal: " +
@@ -44,6 +47,7 @@ CylinderBinning buildPositionBinning(json_t* object) {
std::to_string(number_of_bins_longitudinal));
DEBUG_LEVEL_3("with radius: " + std::to_string(max_radius) + " m");
DEBUG_LEVEL_3("with height: " + std::to_string(max_length) + " m");
#endif
return CylinderBinning(number_of_bins_radial, max_radius,
number_of_bins_azimuthal,
@@ -59,14 +63,18 @@ CylinderBinning buildPositionBinningIncludingRedirection(
json_path& path_to_binning) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating position binning: CreateSameAs.");
#endif
json_path path_to_same = json_path_get(parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"})));
std::stringstream path;
for (auto& p : path_to_same) {
path << p << " ";
}
#ifdef debug_level3
DEBUG_LEVEL_3("From path: " + path.str());
#endif
return buildPositionBinningIncludingRedirection(parameter, path_to_same);
} else {
return buildPositionBinning(parameter.jsonObjectFromBase(path_to_binning));
@@ -76,7 +84,9 @@ CylinderBinning buildPositionBinningIncludingRedirection(
EnergyBinning buildEnergyBinning(json_t* object) {
std::string energy_type = json_string(json_object_by_path(object, {"Type"}));
if (energy_type == "Logarithmic") {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy binning: logarithmic.");
#endif
int number_of_bins =
json_int(json_object_by_path(object, {"NumberOfBins"}));
ASSERT_POSITIVE(&number_of_bins, "Number of Bins must be positive");
@@ -87,9 +97,11 @@ EnergyBinning buildEnergyBinning(json_t* object) {
json_read_energy(json_object_by_path(object, {"MaxEnergy"}), "eV");
ASSERT_POSITIVE(&max_energy, "Max Energy must be positive");
#ifdef debug_level3
DEBUG_LEVEL_3("with number of bins: " + std::to_string(number_of_bins));
DEBUG_LEVEL_3("with min energy: " + std::to_string(min_energy));
DEBUG_LEVEL_3("with max energy: " + std::to_string(max_energy));
#endif
return EnergyBinning(min_energy, max_energy, number_of_bins);
@@ -104,18 +116,75 @@ EnergyBinning buildEnergyBinningIncludingRedirection(
json_path& path_to_binning) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy binning: CreateSameAs.");
#endif
json_path path_to_same = json_path_get(parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"})));
#ifdef debug_level3
std::stringstream path;
for (auto& p : path_to_same) {
path << p << " ";
}
DEBUG_LEVEL_3("From path: " + path.str());
#endif
return buildEnergyBinningIncludingRedirection(parameter, path_to_same);
} else {
return buildEnergyBinning(parameter.jsonObjectFromBase(path_to_binning));
}
}
PitchAngleBinning buildPitchAngleBinning(json_t* object) {
std::string pitch_angle_type = json_string(json_object_by_path(object, {"Type"}));
if (pitch_angle_type == "Linear") {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating pitch angle binning: linear.");
#endif
int number_of_bins =
json_int(json_object_by_path(object, {"NumberOfBins"}));
ASSERT_POSITIVE(&number_of_bins, "Number of Bins must be positive");
#ifdef debug_level3
DEBUG_LEVEL_3("with number of bins: " + std::to_string(number_of_bins));
#endif
return PitchAngleBinning(number_of_bins);
} else {
ERROR("This pitch angle binning is not implemented: " + pitch_angle_type);
return PitchAngleBinning(0);
}
}
PitchAngleBinning buildPitchAngleBinningIncludingRedirection(
Parameter& parameter,
json_path& path_to_binning) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy binning: CreateSameAs.");
#endif
json_path path_to_same = json_path_get(parameter.jsonObjectFromBase(
json_path_append(path_to_binning, {"CreateSameAs"})));
#ifdef debug_level3
std::stringstream path;
for (auto& p : path_to_same) {
path << p << " ";
}
DEBUG_LEVEL_3("From path: " + path.str());
#endif
return buildPitchAngleBinningIncludingRedirection(parameter, path_to_same);
} else {
return buildPitchAngleBinning(parameter.jsonObjectFromBase(path_to_binning));
}
}
}; // namespace generator
@@ -9,7 +9,9 @@ std::shared_ptr<CurrentCollector> buildCurrentCollector(
Parameter& parameter,
const json_path& path_to_collector,
std::shared_ptr<Timer>& timer) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating current collector.");
#endif
json_path path_binning =
json_path_append(path_to_collector, {"PositionBinning"});
CylinderBinning position_binning =
+13 -2
View File
@@ -10,7 +10,9 @@ namespace generator {
std::shared_ptr<ConstantDensityField> buildConstantDensityField(
json_t* object) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating constant density field.");
#endif
json_path path = {"ScalarField"};
std::shared_ptr<ScalarField> field =
buildScalarField(json_object_by_path(object, path));
@@ -21,7 +23,10 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
Parameter& parameter,
const json_path& path_to_field,
std::shared_ptr<Timer>& timer) {
DEBUG_LEVEL_2("Creating dynamic density field.");
#ifdef debug_level2
DEBUG_LEVEL_2("Creating dynamic density field with pitch angle.");
#endif
json_path path_binning = json_path_append(path_to_field, {"PositionBinning"});
CylinderBinning position_binning =
buildPositionBinningIncludingRedirection(parameter, path_binning);
@@ -29,8 +34,14 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
json_path_append(path_to_field, {"EnergyBinning"});
EnergyBinning energy_binning =
buildEnergyBinningIncludingRedirection(parameter, path_energy_binning);
// TBD: make a function to build the pitchangle binning
json_path path_pitch_angle_binning =
json_path_append(path_to_field, {"PitchAngleBinning"});
PitchAngleBinning pitch_angle_binning =
buildPitchAngleBinningIncludingRedirection(parameter, path_pitch_angle_binning);
return std::shared_ptr<DynamicDensityField>(
new DynamicDensityField(position_binning, energy_binning, timer));
new DynamicDensityField(position_binning, energy_binning,
pitch_angle_binning, timer));
}
}; // namespace generator
@@ -9,14 +9,18 @@ std::shared_ptr<DriftVelocity> buildDriftVelocity(
const json_path& path_to_drift_velocity) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_drift_velocity, {"VectorField"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating drift velocity: Vector field.");
#endif
std::shared_ptr<VectorField> field =
buildVectorField(parameter.jsonObjectFromBase(
json_path_append(path_to_drift_velocity, {"VectorField"})));
return std::shared_ptr<DriftVelocity>(new DriftVelocity(field));
} else if (parameter.jsonObjectFromBase(
json_path_append(path_to_drift_velocity, {"null"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating drift velocity: null.");
#endif
return nullptr;
} else {
ERROR("No drift velocity given.");
@@ -29,14 +33,18 @@ std::shared_ptr<DriftVelocity> buildDriftVelocityIncludingRedirection(
std::stringstream cpath;
if (parameter.jsonObjectFromBase(
json_path_append(path_to_drift_velocity, {"CreateSameAs"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating drift velocity: CreateSameAs.");
#endif
json_path path_to_same = json_path_get(parameter.jsonObjectFromBase(
json_path_append(path_to_drift_velocity, {"CreateSameAs"})));
#ifdef debug_level3
std::stringstream path;
for (auto& p : path_to_same) {
path << p << " ";
}
DEBUG_LEVEL_3("From path: " + path.str());
#endif
return buildDriftVelocityIncludingRedirection(parameter, path_to_same);
} else {
return buildDriftVelocity(parameter, path_to_drift_velocity);
@@ -6,12 +6,16 @@
namespace generator {
std::shared_ptr<ElectricField> electricField(json_t* object) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating electric field.");
#endif
std::shared_ptr<VectorField> background;
std::shared_ptr<VectorField> dynamic;
if (json_object_by_path(object, {"Background"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating background electric field.");
#endif
background = buildVectorField(
json_object_by_path(object, {"Background", "VectorField"}));
} else {
@@ -19,7 +23,9 @@ std::shared_ptr<ElectricField> electricField(json_t* object) {
}
if (json_object_by_path(object, {"Dynamic"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating dynamic electric field.");
#endif
dynamic = buildVectorField(
json_object_by_path(object, {"Dynamic", "VectorField"}));
} else {
@@ -11,21 +11,31 @@ std::shared_ptr<EnergyDistributionFunction> buildEnergyDistributionFunction(
json_t* object = parameter.jsonObjectFromBase(path_to_function);
if (json_object_by_path(object, {"TritiumBetaDecay"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy distribution function: tritium beta decay.");
#endif
return std::shared_ptr<EnergyDistributionFunction>(new TritiumBetaDecay());
} else if (json_object_by_path(object, {"MaxwellBoltzmann"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy distribution function: Maxwell Boltzmann.");
#endif
double temperature_K = json_double(json_object_by_path(
object, {"MaxwellBoltzmann", "Temperature", "value"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with temperature: " + std::to_string(temperature_K) + " K");
#endif
return std::shared_ptr<EnergyDistributionFunction>(
new MaxwellBoltzmann(temperature_K));
} else if (json_object_by_path(object, {"Constant"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating energy distribution function: Constant.");
#endif
double constant_eV = json_double(
json_object_by_path(object, {"Constant", "constant", "value"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with constant: " + std::to_string(constant_eV) + " eV");
#endif
return std::shared_ptr<EnergyDistributionFunction>(
new Constant(constant_eV));
}
+27
View File
@@ -11,14 +11,20 @@ namespace generator {
std::function<double(double)> function1D(json_t* object) {
if (json_object_by_path(object, {"Constant"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function1d: constant.");
#endif
double constant =
json_double(json_object_by_path(object, {"Constant", "constant"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with constant: " + std::to_string(constant));
#endif
return D1ToD1::Constant(constant);
} else if (json_object_by_path(object, {"PiecewiseLinear"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function1d: PiecewiseLinear.");
#endif
std::vector<double> x_values = json_vector(
json_object_by_path(object, {"PiecewiseLinear", {"xValues"}}));
std::vector<double> y_values = json_vector(
@@ -31,11 +37,15 @@ std::function<double(double)> function1D(json_t* object) {
return D1ToD1::PiecewiseLinear(x_values, y_values);
} else if (json_object_by_path(object, {"PiecewiseLinearFromFile"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function1d: PiecewiseLinear from file.");
#endif
std::string absolute_filename = readAbsoluteFilename(
json_object_by_path(object, {"PiecewiseLinearFromFile", "PathToH5"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with filename: " + absolute_filename);
#endif
Hdf5Reader reader(absolute_filename);
std::string x_values_key = json_string(
@@ -53,7 +63,9 @@ std::function<double(double)> function1D(json_t* object) {
double prefactor = json_double(json_object_by_path(
object, {"PiecewiseLinearFromFile", {"prefactor"}}));
#ifdef debug_level3
DEBUG_LEVEL_3("with prefactor: " + std::to_string(prefactor));
#endif
for (int i = 0; i < y_values.size(); ++i) {
y_values[i] = y_values[i] * prefactor;
@@ -61,7 +73,9 @@ std::function<double(double)> function1D(json_t* object) {
return D1ToD1::PiecewiseLinear(x_values, y_values);
} else if (json_object_by_path(object, {"Product"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function1d: Product.");
#endif
json_t* function_array = json_object_by_path(object, {"Product"});
std::vector<std::function<double(double)>> functions;
size_t index;
@@ -71,6 +85,15 @@ std::function<double(double)> function1D(json_t* object) {
}
return D1ToD1::Product(functions);
} else if (json_object_by_path(object, {"Exponential"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function1d: Exponential.");
#endif
double prefactor = json_double(json_object_by_path(
object, {"Exponential", {"prefactor"}}));
double scale = json_double(json_object_by_path(
object, {"Exponential", {"scale"}}));
return D1ToD1::Exponential(prefactor, scale);
} else {
ERROR("This 1d to 1d function is not implemented.");
return nullptr;
@@ -79,12 +102,16 @@ std::function<double(double)> function1D(json_t* object) {
std::function<double(double, double, double)> function3D(json_t* object) {
if (json_object_by_path(object, {"Constant3D"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function3d: Constant3D.");
#endif
double constant =
json_double(json_object_by_path(object, {"Constant3D", "constant"}));
return D3ToD1::Constant(constant);
} else if (json_object_by_path(object, {"Product"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating function3d: Product.");
#endif
std::function<double(double)> fi =
function1D(json_object_by_path(object, {"Product", "fi"}));
std::function<double(double)> fj =
+8
View File
@@ -7,7 +7,9 @@ std::shared_ptr<Geometry> buildGeometry(Parameter& parameter,
const json_path& path_to_geometry) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_geometry, {"Cylinder"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating geometry: cylinder.");
#endif
double radius =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"Cylinder", "Radius"})),
@@ -16,8 +18,10 @@ std::shared_ptr<Geometry> buildGeometry(Parameter& parameter,
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"Cylinder", "Height"})),
"m");
#ifdef debug_level3
DEBUG_LEVEL_3("with radius: " + std::to_string(radius) + " m");
DEBUG_LEVEL_3("with height: " + std::to_string(height) + " m");
#endif
return std::shared_ptr<Geometry>(new Cylinder(radius, height));
} else {
ERROR("This geometry is not implemented.");
@@ -29,14 +33,18 @@ std::shared_ptr<Geometry> buildGeometryIncludingRedirection(
Parameter& parameter, const json_path& path_to_geometry) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_geometry, {"CreateSameAs"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating geometry: CreateSameAs.");
#endif
json_path path_to_same = json_path_get(parameter.jsonObjectFromBase(
json_path_append(path_to_geometry, {"CreateSameAs"})));
std::stringstream path;
for (auto& p : path_to_same) {
path << p << " ";
}
#ifdef debug_level3
DEBUG_LEVEL_3("From path: " + path.str());
#endif
return buildGeometryIncludingRedirection(parameter, path_to_same);
} else {
return buildGeometry(parameter, path_to_geometry);
@@ -5,14 +5,23 @@
namespace generator {
std::shared_ptr<GravityField> gravityField(json_t* object) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating gravity field.");
#endif
return std::shared_ptr<GravityField>(new GravityField(
buildVectorField(json_object_by_path(object, {"VectorField"}))));
}
std::shared_ptr<GravityField> gravityField(Parameter& parameter) {
if(json_object_by_path(parameter.jsonFile(), {"GravityField"})) {
return gravityField(
json_object_by_path(parameter.jsonFile(), {"GravityField"}));
} else {
SIM_INFO("No \"GravityField\" object in the json file. Use default of (0,0,0).");
return std::shared_ptr<GravityField>( new GravityField(
std::shared_ptr<VectorField>( new VectorFieldConstant(
CylinderVector(blitz::TinyVector<double, 3> (0,0,0))))));
}
}
};
+10
View File
@@ -25,7 +25,9 @@ std::shared_ptr<Injector> buildInjector(
json_object_foreach(array, key, value) {
std::string specie_name =
json_string(json_object_by_path(value, {"TrackedSpecieName"}));
#ifdef debug_level3
DEBUG_LEVEL_3("Injected specie: " + specie_name);
#endif
InjectorInfo info;
info.created_specie = tracked_species[specie_name];
@@ -33,11 +35,17 @@ std::shared_ptr<Injector> buildInjector(
parameter,
json_path_append(path_to_injector, {"CreatedSpecies", std::string(key),
"CreationVelocityDistribution"}));
// info.multiplicity = json_int(json_object_by_path(value, {"Multiplicity"}), 1);
// ASSERT_POSITIVE(&info.multiplicity, "The multiplicity has to be positive. " +
// specie_name + " multiplicity: " + std::to_string(info.multiplicity));
injector_infos.push_back(info);
}
// EventPositionDistribution
#ifdef debug_level2
DEBUG_LEVEL_2("Creating event distribution.");
#endif
std::shared_ptr<ScalarField> field = buildScalarField(json_object_by_path(
object, {"EventPositionDistribution", "ScalarField"}));
@@ -76,7 +84,9 @@ std::shared_ptr<Injector> buildInjector(
position_limit_phi, position_limit_z));
// MotherDriftVelocity
#ifdef debug_level2
DEBUG_LEVEL_2("Creating mother drift velocity.");
#endif
std::shared_ptr<DriftVelocity> drift_velocity = buildDriftVelocity(
parameter, json_path_append(path_to_injector, {"MotherDriftVelocity"}));
+22
View File
@@ -33,7 +33,9 @@ void addInteractions(
std::string type = json_string(json_object_by_path(value, {"Type"}));
if (type == "ElasticScattering") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: ElasticScattering");
#endif
std::function<double(double)> cross_section =
buildTotalCrossSection(json_object_by_path(value, {"CrossSection"}));
@@ -43,7 +45,9 @@ void addInteractions(
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with target " + target_name);
#endif
std::shared_ptr<species::Specie> target =
findTarget(target_name, tracked_species, background_species);
@@ -53,11 +57,15 @@ void addInteractions(
scattering_angle_distribution)));
} else if (type == "FreeMovement") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: FreeMovement");
#endif
specie->addInteraction(std::shared_ptr<interaction::Interaction>(
new interaction::FreeMovement()));
} else if (type == "ElectronIonization") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: Ionization");
#endif
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::shared_ptr<species::Specie> target =
@@ -183,7 +191,9 @@ void addInteractions(
ERROR("This ionization model is not implemented: " + ionization_model);
}
} else if (type == "Excitation") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: Excitation");
#endif
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::shared_ptr<species::Specie> target =
@@ -201,7 +211,9 @@ void addInteractions(
cross_section, target, excitation_energy)));
} else if (type == "Clustering") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: Clustering");
#endif
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::shared_ptr<species::Specie> target =
@@ -217,7 +229,9 @@ void addInteractions(
specie->addInteraction(std::shared_ptr<interaction::Interaction>(
new interaction::ClusterFormation(cross_section, target, product)));
} else if (type == "ChargeExchange") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: ChargeExchange");
#endif
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::shared_ptr<species::Specie> target =
@@ -228,7 +242,9 @@ void addInteractions(
specie->addInteraction(std::shared_ptr<interaction::Interaction>(
new interaction::ChargeExchange(cross_section, target)));
} else if (type == "Recombination") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: Recombination");
#endif
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::shared_ptr<species::TrackedSpecie> target =
@@ -471,18 +487,24 @@ std::function<double(double, double)> build2DCrossSection(json_t* object) {
std::shared_ptr<ScatteringAngleDistribution> buildScatteringAngleDistribution(
json_t* object) {
if (json_object_by_path(object, {"Isotropic"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding ScatteringAngleDistribution: Isotropic");
#endif
return std::shared_ptr<ScatteringAngleDistribution>(
new IsotropicAngleDistribution());
} else if (json_object_by_path(object, {"AngleDistributionFromFile"})) {
#ifdef debug_level2
DEBUG_LEVEL_2(
"Adding ScatteringAngleDistribution: AngleDistributionFromFile");
#endif
std::string absolute_filepath = readAbsoluteFilename(
json_object_by_path(object, {"AngleDistributionFromFile", "PathToH5"}));
return std::make_shared<AngleDistributionFromFile>(absolute_filepath);
} else if (json_object_by_path(object, {"CompositeAngleDistribution"})) {
#ifdef debug_level2
DEBUG_LEVEL_2(
"Adding ScatteringAngleDistribution: CompositeAngleDistribution");
#endif
json_t* object_composite =
json_object_by_path(object, {"CompositeAngleDistribution"});
const double decider_energy = json_read_energy(
+9
View File
@@ -35,6 +35,13 @@ std::shared_ptr<DeletionLogger> buildDeletionLogger(json_t* object) {
used_types.push_back(DeletionType::max_interactions);
used_types.push_back(DeletionType::max_time_alive);
used_types.push_back(DeletionType::cluster_formation);
// Debugging types, not yet able to be specified on their own, just
// in when "all" is used
used_types.push_back(DeletionType::creation_beta);
used_types.push_back(DeletionType::creation_density);
used_types.push_back(DeletionType::creation_interaction);
used_types.push_back(DeletionType::creation_above_2keV);
used_types.push_back(DeletionType::loss_above_2keV);
}
}
@@ -43,7 +50,9 @@ std::shared_ptr<DeletionLogger> buildDeletionLogger(json_t* object) {
std::shared_ptr<DeletionLogger> buildDeletionLogger(
Parameter& parameter,
const json_path& path_to_loggers) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating deletion logger.");
#endif
json_path path_logger = json_path_append(path_to_loggers, {"Deletion"});
json_t* object = parameter.jsonObjectFromBase(path_logger);
+4 -1
View File
@@ -5,9 +5,12 @@
namespace generator {
std::shared_ptr<MagneticField> magneticField(json_t* object) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating magnetic field.");
#endif
return std::shared_ptr<MagneticField>(new MagneticField(
buildVectorField(json_object_by_path(object, {"VectorField"}))));
buildVectorField(json_object_by_path(object, {"VectorField"})),
buildVectorField(json_object_by_path(object, {"GradientField"}))));
}
std::shared_ptr<MagneticField> magneticField(Parameter& parameter) {
+4
View File
@@ -7,13 +7,17 @@ std::shared_ptr<Mover> buildMover(Parameter& parameter,
const json_path& path_to_mover) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_mover, {"Boris"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating mover: Boris.");
#endif
double max_timestep_length = parameter.doubleValue(json_path_append(
path_to_mover, {"Boris", "MaximalTimestepLength", "value"}));
return std::shared_ptr<Mover>(new BorisMover(max_timestep_length));
} else if (parameter.jsonObjectFromBase(
json_path_append(path_to_mover, {"Drift"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating mover: Drift.");
#endif
double maximal_moved_distance =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_mover, {"Drift", "MaximalMovedDistance"})));
+11 -18
View File
@@ -10,7 +10,9 @@ namespace generator {
std::shared_ptr<PoissonSolver> buildPoissonSolver(
Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Generating Poisson solver.");
#endif
std::shared_ptr<Geometry> geometry;
json_t* object = json_object_by_path(
@@ -30,20 +32,6 @@ namespace generator {
auto boundaries = buildBoundaries(parameter, {"PoissonSolver", "Boundary"});
int solver_intervall = json_int(json_object_by_path(object, {"Intervall"}));
if (solver_intervall == 0 &&
json_string(json_object_by_path(
object, {"Intervall"})) == "EachSync") {
solver_intervall = 1;
}
ASSERT_POSITIVE(&solver_intervall,
"The intervall for poisson solver stride must be positive"
" or 'EachSync'");
int solver_offset = json_int(json_object_by_path(object, {"Offset"}));
ASSERT_NOTNEGATIVE(&solver_offset,
"The offset for poisson solver has to be non-negative");
std::vector<std::shared_ptr<Electrode>> electrodes{};
double target_accuracy = parameter.doubleValue(
@@ -52,18 +40,19 @@ namespace generator {
int num_cycles = parameter.intValue(json_path_append({"PoissonSolver"},
{"NumCycles"}));
bool reset_after_solving = parameter.boolValue(
json_path_append({"PoissonSolver"}, {"ResetAfterSolving"}), false);
bool do_solver = parameter.boolValue(
json_path_append({"PoissonSolver"}, {"DoSolver"}), false);
return std::shared_ptr<PoissonSolver>(new PoissonSolver(boundaries.at("Bottom"),
boundaries.at("Top"), boundaries.at("Hull"), geometry, position_binning,
electrodes, target_accuracy, num_cycles, solver_intervall, solver_offset,
reset_after_solving));
electrodes, target_accuracy, num_cycles, do_solver));
}
std::map<std::string, GlobalBoundary> buildBoundaries(Parameter& parameter,
const json_path& path_to_boundaries) {
#ifdef debug_level3
DEBUG_LEVEL_3("Creating Boundaries.");
#endif
std::map<std::string, GlobalBoundary> boundary_map {
{"Bottom", {0., BoundaryType::dirichlet}},
{"Top", {0., BoundaryType::dirichlet}},
@@ -78,7 +67,9 @@ namespace generator {
json_t* value;
json_object_foreach(parameter.jsonObjectFromBase(path_to_boundaries),
key, value) {
#ifdef debug_level3
DEBUG_LEVEL_3("Creating " + std::string(key) + ": ");
#endif
if(!(boundary_map.find(std::string(key)) == boundary_map.end())) {
double boundary_value =
json_double(json_object_by_path(value, {"value"}));
@@ -97,8 +88,10 @@ namespace generator {
". Using default boundary (dirichtlet, value 0)");
continue;
}
#ifdef debug_level3
DEBUG_LEVEL_3("with type: " + boundary_type);
DEBUG_LEVEL_3("with value: " + std::to_string(boundary_value));
#endif
} else {
SIM_INFO(std::string(key) + ": unknown location. Is ignored.");
+4
View File
@@ -8,7 +8,9 @@ std::shared_ptr<Reflector> buildReflector(Parameter& parameter,
const json_path& path_to_reflector) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_reflector, {"ReflectorDPS"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Create reflector: ReflectorDPS");
#endif
double position_z = json_read_length(
parameter.jsonObjectFromBase(json_path_append(
path_to_reflector, {"ReflectorDPS", "position_z"})),
@@ -16,7 +18,9 @@ std::shared_ptr<Reflector> buildReflector(Parameter& parameter,
return std::shared_ptr<Reflector>(new ReflectorDPS(position_z));
} else if (parameter.jsonObjectFromBase(
json_path_append(path_to_reflector, {"NoReflector"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Create reflector: NoReflector");
#endif
return std::shared_ptr<Reflector>(new NoReflector());
} else {
ERROR("This reflector is not implemented.");
+45
View File
@@ -0,0 +1,45 @@
#include "generators/restart_generator.h"
#include "IO/restart.h"
#include "generators/vector_field_generator.h"
namespace generator {
Restart buildRestart(json_t* object) {
DEBUG_LEVEL_3("Build Restart.");
bool do_restart = json_bool(json_object_by_path(object, {"Do"}));
if (!do_restart) {
#ifdef debug
DEBUG_LEVEL_0("No Restart desired.");
#endif
return Restart(false, "", "");
}
std::string filepath = readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}))
+ ".h5";
#ifdef debug_level3
DEBUG_LEVEL_3("Restart: file path:" + filepath);
#endif
std::string identifier;
int sync_period = json_int(json_object_by_path(object, {"SyncPeriod"}));
if(sync_period == 0 && json_string(json_object_by_path(object, {"SyncPeriod"}))
== "LastSyncPeriod") {
identifier = "LastSyncPeriod";
} else {
ASSERT_POSITIVE(&sync_period, "The SyncPeriod for the restart has to be either"
" positive or \"LastSyncPeriod\".");
identifier = "SyncPeriod_" + std::to_string(sync_period);
}
#ifdef debug_level3
DEBUG_LEVEL_3("Restart: SyncPeriod to be started from: " + identifier);
#endif
return Restart(do_restart, filepath, identifier);
}
Restart buildRestart(Parameter& parameter) {
return buildRestart(
json_object_by_path(parameter.jsonFile(), {"Restart"}));
}
} // namespace generator
@@ -153,6 +153,31 @@ std::shared_ptr<SimulationOutput> buildSimulationOutput(
output->setPotentialOutput(task);
}
// RestartInfo
{
int intervall =
json_int(json_object_by_path(object, {"RestartInfo", "Intervall"}), -1);
// DEBUG_LEVEL_2("Try value of Intervall as string");
if (intervall == -1 && json_string(json_object_by_path(
object, {"RestartInfo", "Intervall"})) == "EachSync") {
intervall = 1;
} else if (intervall == -1) {
intervall = 0;
}
ASSERT_NOTNEGATIVE(&intervall, "The intervall for RestartInfo has to be either 0"
",if no output is required or positive otherwise");
#ifdef debug_level3
DEBUG_LEVEL_3("Restart output interval: " + std::to_string(intervall));
#endif
bool overwrite_last = json_bool(
json_object_by_path(object, {"RestartInfo", "OverwriteLast"}));
OutputTask task = {"RestartInfo", overwrite_last, intervall};
output->setRestartInfoOutput(task);
}
return output;
}
+47 -15
View File
@@ -107,13 +107,17 @@ std::shared_ptr<Timer> SpeciesBuilder::lastSyncTimer() {
}
void SpeciesBuilder::initTimer() {
#ifdef debug_level2
DEBUG_LEVEL_2("Init timer.");
#endif
timer_ = std::shared_ptr<Timer>(new Timer());
last_sync_timer_ = std::shared_ptr<Timer>(new Timer());
}
void SpeciesBuilder::initBackgroundSpecies(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Init background species info.");
#endif
const char* key;
json_t* value;
json_object_foreach(parameter.jsonObjectFromBase({"Species", "Background"}),
@@ -126,7 +130,9 @@ void SpeciesBuilder::initBackgroundSpecies(Parameter& parameter) {
}
void SpeciesBuilder::initTrackedSpecies(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Init tracked species info.");
#endif
const char* key;
json_t* value;
json_object_foreach(parameter.jsonObjectFromBase({"Species", "Tracked"}), key,
@@ -139,11 +145,15 @@ void SpeciesBuilder::initTrackedSpecies(Parameter& parameter) {
}
void SpeciesBuilder::fillBackgroundSpecieType(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill background species type.");
#endif
for (auto& b : background_species_info) {
std::string type = json_string(parameter.jsonObjectFromBase(
json_path_append(b.second.path_in_json, {"ParticleType"})));
#ifdef debug_level3
DEBUG_LEVEL_3("Type: " + type);
#endif
if (SpeciesAlias::isAlias(type)) {
b.second.type = SpeciesAlias::alias(type);
} else {
@@ -153,11 +163,15 @@ void SpeciesBuilder::fillBackgroundSpecieType(Parameter& parameter) {
}
void SpeciesBuilder::fillTrackedSpecieType(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill tracked species type.");
#endif
for (auto& b : tracked_species_info) {
std::string type = json_string(parameter.jsonObjectFromBase(
json_path_append(b.second.path_in_json, {"ParticleType"})));
#ifdef debug_level3
DEBUG_LEVEL_3("Type: " + type);
#endif
if (SpeciesAlias::isAlias(type)) {
b.second.type = SpeciesAlias::alias(type);
} else {
@@ -167,7 +181,9 @@ void SpeciesBuilder::fillTrackedSpecieType(Parameter& parameter) {
}
void SpeciesBuilder::fillBackgroundDensity(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill background density.");
#endif
for (auto& b : background_species_info) {
b.second.density = buildConstantDensityField(parameter.jsonObjectFromBase(
json_path_append(b.second.path_in_json, {"ConstantDensityField"})));
@@ -175,7 +191,9 @@ void SpeciesBuilder::fillBackgroundDensity(Parameter& parameter) {
}
void SpeciesBuilder::fillVelocityDistribution(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill velocity distributions.");
#endif
for (auto& b : background_species_info) {
b.second.velocity_distribution = buildVelocityDistribution(
parameter,
@@ -189,7 +207,9 @@ void SpeciesBuilder::fillVelocityDistribution(Parameter& parameter) {
}
void SpeciesBuilder::fillDriftVelocity(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill drift velocity.");
#endif
for (auto& b : background_species_info) {
b.second.drift_velocity = buildDriftVelocityIncludingRedirection(
parameter, json_path_append(b.second.path_in_json, {"DriftVelocity"}));
@@ -201,7 +221,9 @@ void SpeciesBuilder::fillDriftVelocity(Parameter& parameter) {
}
void SpeciesBuilder::fillMass() {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill masses.");
#endif
for (auto& b : background_species_info) {
b.second.mass_kg = SpeciesMasses::mass(b.second.type);
}
@@ -211,7 +233,9 @@ void SpeciesBuilder::fillMass() {
}
void SpeciesBuilder::fillCharge() {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill charges.");
#endif
for (auto& b : background_species_info) {
b.second.charge_C = SpeciesCharges::charge(b.second.type);
}
@@ -221,7 +245,9 @@ void SpeciesBuilder::fillCharge() {
}
void SpeciesBuilder::fillMover(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill movers.");
#endif
for (auto& b : tracked_species_info) {
if ((b.second.mover == nullptr)) {
b.second.mover = buildMover(
@@ -231,7 +257,9 @@ void SpeciesBuilder::fillMover(Parameter& parameter) {
}
void SpeciesBuilder::fillTerminator(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill terminators.");
#endif
for (auto& b : tracked_species_info) {
if ((b.second.terminator == nullptr)) {
b.second.terminator = buildTerminator(
@@ -241,7 +269,9 @@ void SpeciesBuilder::fillTerminator(Parameter& parameter) {
}
void SpeciesBuilder::fillReflector(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill reflectors.");
#endif
for (auto& b : tracked_species_info) {
if ((b.second.reflector == nullptr)) {
b.second.reflector = buildReflector(
@@ -250,8 +280,11 @@ void SpeciesBuilder::fillReflector(Parameter& parameter) {
}
}
// TBD: Fill and create dynamic density fields with pitch angle distribution
void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill tracked density.");
#endif
for (auto& b : tracked_species_info) {
b.second.density_field = buildDynamicDensityField(
parameter,
@@ -259,16 +292,19 @@ void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
{"DensityField", "DynamicDensityField"}),
timer_);
b.second.last_sync_density_field = buildDynamicDensityField(
// not the optimal solution! (has to be optimized)
b.second.density_drawing_field = buildDynamicDensityField(
parameter,
json_path_append(b.second.path_in_json,
{"DensityField", "DynamicDensityField"}),
last_sync_timer_);
timer_);
}
}
void SpeciesBuilder::buildSpecies() {
#ifdef debug_level2
DEBUG_LEVEL_2("Build species from info.");
#endif
for (auto& b : background_species_info) {
background_species[b.first] = std::shared_ptr<species::BackgroundSpecie>(
new species::BackgroundSpecie(
@@ -283,50 +319,46 @@ 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.last_sync_density_field));
b.second.drift_velocity, b.second.density_drawing_field));
}
}
void SpeciesBuilder::fillCurrentCollector(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill current collectors.");
#endif
for (auto& b : tracked_species) {
auto current_collector = buildCurrentCollector(
parameter,
json_path_append(tracked_species_info.at(b.first).path_in_json,
{"CurrentCollector"}),
timer_);
// has to be recreated, if it would be copied the timer_ pointer would
// point to the same object -> could not get updated during synchronization
auto last_sync_current_collector = buildCurrentCollector(
parameter,
json_path_append(tracked_species_info.at(b.first).path_in_json,
{"CurrentCollector"}),
last_sync_timer_);
b.second->currentCollector(current_collector);
b.second->lastSyncCurrentCollector(last_sync_current_collector);
}
}
void SpeciesBuilder::fillLoggers(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill loggers.");
#endif
for (auto& b : tracked_species) {
auto deletion_logger = buildDeletionLogger(
parameter,
json_path_append(tracked_species_info.at(b.first).path_in_json,
{"Loggers"}));
b.second->deletionLogger(deletion_logger);
b.second->lastSyncDeletionLogger(
std::make_shared<DeletionLogger>(*deletion_logger));
}
}
void SpeciesBuilder::fillInteractions(Parameter& parameter) {
#ifdef debug_level2
DEBUG_LEVEL_2("Fill interactions.");
#endif
for (auto& b : tracked_species) {
json_path path = tracked_species_info[b.first].path_in_json;
path = json_path_append(path, {"Interactions"});
addInteractions(b.second, tracked_species, background_species, parameter,
path);
addInteractions(b.second, tracked_species, background_species,
parameter, path);
}
}
+4
View File
@@ -7,13 +7,17 @@ namespace generator {
std::shared_ptr<Terminator> buildTerminator(
Parameter& parameter,
const json_path& path_to_terminator) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating terminator.");
#endif
long int max_interactions = static_cast<long int>(parameter.doubleValue(
json_path_append(path_to_terminator, {"MaximumInteractions"})));
double max_time_alive = parameter.doubleValue(
json_path_append(path_to_terminator, {"MaxTimeAlive", "value"}));
#ifdef debug_level3
DEBUG_LEVEL_3("with max interactions: " + std::to_string(max_interactions));
DEBUG_LEVEL_3("with max time alive: " + std::to_string(max_time_alive));
#endif
std::shared_ptr<Geometry> geometry = buildGeometryIncludingRedirection(
parameter, json_path_append(path_to_terminator, {"BoundaryGeometry"}));
+8 -2
View File
@@ -20,7 +20,7 @@ std::string readAbsoluteFilename(json_t* object) {
json_string(json_object_by_path(object, {"Filename"}));
return homebase + "/" + relative_path_to_homebase + "/" + filename;
} else if (path_type == "AbsolutPath") {
} else if (path_type == "AbsolutePath") {
std::string absolute_path =
json_string(json_object_by_path(object, {"AbsoluteFolderPath"}));
std::string filename =
@@ -45,7 +45,7 @@ blitz::Array<double, 3> readComponentFromFile(json_t* object, int component) {
std::string absolute_filename =
readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}));
std::string key = json_string(
json_array_get(json_object_by_path(object, {"PathToH5"}), component));
json_array_get(json_object_by_path(object, {"Keys"}), component));
Hdf5Reader reader(absolute_filename);
return reader.readD3Double(key);
@@ -53,7 +53,9 @@ blitz::Array<double, 3> readComponentFromFile(json_t* object, int component) {
std::shared_ptr<VectorField> buildVectorField(json_t* object) {
if (json_object_by_path(object, {"VectorFieldConstant"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating Vector field: VectorFieldConstant");
#endif
blitz::TinyVector<double, 3> constant = json_blitz_vector<3>(
json_object_by_path(object, {"VectorFieldConstant", "constant"}));
@@ -61,13 +63,17 @@ std::shared_ptr<VectorField> buildVectorField(json_t* object) {
new VectorFieldConstant(CylinderVector(constant)));
} else if (json_object_by_path(object, {"VectorFieldFunctionInZ"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating Vector field: VectorFieldFunctionInZ");
#endif
std::function<double(double, double, double)> z_function = function3D(
json_object_by_path(object, {"VectorFieldFunctionInZ", "zFunction"}));
return std::shared_ptr<VectorField>(new VectorFieldFunctionInZ(z_function));
} else if (json_object_by_path(object, {"VectorFieldFromArray"})) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating Vector field: VectorFieldFromArray");
#endif
blitz::Array<double, 3> v_radial = readComponentFromFile(
json_object_by_path(object,
@@ -11,8 +11,10 @@ std::shared_ptr<VelocityDistributionFunction> buildVelocityDistributionFunction(
const json_path& path_to_distribution) {
if (parameter.jsonObjectFromBase(
json_path_append(path_to_distribution, {"IsotropicDistribution"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2(
"Creating velocity distribution function: IsotropicDistribution");
#endif
std::shared_ptr<EnergyDistributionFunction> fE =
buildEnergyDistributionFunction(
parameter, json_path_append(path_to_distribution,
@@ -26,8 +28,10 @@ std::shared_ptr<VelocityDistributionFunction> buildVelocityDistributionFunction(
} else if (parameter.jsonObjectFromBase(json_path_append(
path_to_distribution, {"DirectedDistribution"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2(
"Creating velocity distribution function: DirectedDistribution");
#endif
std::shared_ptr<EnergyDistributionFunction> fE =
buildEnergyDistributionFunction(
parameter, json_path_append(path_to_distribution,
@@ -10,8 +10,10 @@ std::shared_ptr<VelocityDistribution> buildVelocityDistribution(
const json_path& path_to_distribution) {
if (parameter.jsonObjectFromBase(json_path_append(
path_to_distribution, {"VelocityDistributionFromFunction"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2(
"Creating velocity distribution: VelocityDistributionFromFunction");
#endif
std::shared_ptr<VelocityDistributionFunction> v =
buildVelocityDistributionFunction(
parameter, json_path_append(path_to_distribution,
@@ -21,7 +23,9 @@ std::shared_ptr<VelocityDistribution> buildVelocityDistribution(
new VelocityDistributionFromFunction(v));
} else if (parameter.jsonObjectFromBase(
json_path_append(path_to_distribution, {"null"}))) {
#ifdef debug_level2
DEBUG_LEVEL_2("Creating velocity distribution: null");
#endif
return nullptr;
} else {
ERROR("This velocity distribution is not implemented.");
+9 -7
View File
@@ -13,16 +13,18 @@ ChargeExchange::ChargeExchange(std::function<double(double)> cross_section,
InteractionOutput ChargeExchange::performInteraction(
particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform charge exchange.");
#endif
const auto x_impact = particle.position();
const blitz::TinyVector<double, 3> v_target =
target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
target_->velocityDistibution()
->rollVelocity(x_impact, generator->engine())
.cartesianEntries();
// const auto x_impact = particle.position();
// const blitz::TinyVector<double, 3> v_target =
// target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
// target_->velocityDistribution()
// ->rollVelocity(x_impact, generator->engine())
// .cartesianEntries();
particle.velocity(CartesianVector(v_target));
particle.velocity(CartesianVector(target_velocity_));
return InteractionOutput();
}
};
+16 -9
View File
@@ -17,20 +17,25 @@ ClusterFormation::ClusterFormation(
InteractionOutput ClusterFormation::performInteraction(
particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform cluster formation.");
const auto x_impact = particle.position();
const blitz::TinyVector<double, 3> v_target =
target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
target_->velocityDistibution()
->rollVelocity(x_impact, generator->engine())
.cartesianEntries();
#endif
const auto x_impact = particle.cartesianPosition();
// const blitz::TinyVector<double, 3> v_target =
// target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
// target_->velocityDistribution()
// ->rollVelocity(x_impact, generator->engine())
// .cartesianEntries();
const double energy_eV =
kinematic::kineticEnergy(v_target, target_->mass_kg()) *
kinematic::kineticEnergy(target_velocity_.cartesianEntries(), target_->mass_kg()) *
UnitConversion::JouleToeV;
const blitz::TinyVector<double, 3> v_cluster =
kinematic::velocity(energy_eV, product_->mass_kg()) *
v_target / kinematic::norm(v_target);
particle::Particle cluster(product_, x_impact, CartesianVector(v_cluster));
target_velocity_.cartesianEntries() / kinematic::norm(target_velocity_.cartesianEntries());
// product inherits weight of the main particle (not the target, which is
// assumed to be just a density, i.e. has no weight of its own)
particle::Particle cluster(product_, x_impact, CartesianVector(v_cluster),
particle.timeAlive(), particle.weight());
InteractionOutput output;
output.add(cluster);
@@ -41,6 +46,8 @@ InteractionOutput ClusterFormation::performInteraction(
x_impact, DeletionType::cluster_formation);
}
product_->deletionLogger()->logDeletion(x_impact, DeletionType::creation_interaction);
return output;
}
+43 -18
View File
@@ -28,14 +28,20 @@ std::function<double(double, double)> eT2_ionization_bed() {
} else {
const double t = impact_energy / ionization_energy;
const double w = energy_after_collision / ionization_energy;
double y = 1 / (w + 1);
double ysq = y*y;
double invtmw = 1. / (t - w);
const double factor = S_m2 / ionization_energy / (t + u + 1);
const double summand_1 =
(Ni / N - 2) / (t + 1) * (1 / (w + 1) + 1 / (t - w));
(Ni / N - 2) / (t + 1) * (y + invtmw);
const double summand_2 =
(2 - Ni / N) * (std::pow(w + 1, -2) + std::pow(t - w, -2));
double y = 1 / (w + 1);
const double dfdw = c[0] * std::pow(y, 3) + c[1] * std::pow(y, 4) +
c[2] * std::pow(y, 5) + c[3] * std::pow(y, 6);
(2 - Ni / N) * (ysq + invtmw*invtmw);
// const double dfdw = c[0] * std::pow(y, 3) + c[1] * std::pow(y, 4) +
// c[2] * std::pow(y, 5) + c[3] * std::pow(y, 6);
const double dfdw = ysq*(y*c[0] + ysq*(c[1] + y*(c[2] + y*c[3])));
const double summand_3 = std::log(t) / (N * (w + 1)) * dfdw;
return factor * (summand_1 + summand_2 + summand_3);
}
@@ -57,14 +63,20 @@ std::function<double(double, double)> eT_ionization_bed() {
} else {
const double t = impact_energy / ionization_energy;
const double w = energy_after_collision / ionization_energy;
double y = 1 / (w + 1);
double ysq = y*y;
double invtmw = 1. / (t - w);
const double factor = S_m2 / ionization_energy / (t + u + 1);
const double summand_1 =
(Ni / N - 2) / (t + 1) * (1 / (w + 1) + 1 / (t - w));
(Ni / N - 2) / (t + 1) * (y + invtmw);
const double summand_2 =
(2 - Ni / N) * (std::pow(w + 1, -2) + std::pow(t - w, -2));
double y = 1 / (w + 1);
const double dfdw = c[0] * std::pow(y, 2) + c[1] * std::pow(y, 3) +
c[2] * std::pow(y, 4) + c[3] * std::pow(y, 5);
(2 - Ni / N) * (ysq + invtmw*invtmw);
// const double dfdw = c[0] * std::pow(y, 2) + c[1] * std::pow(y, 3) +
// c[2] * std::pow(y, 4) + c[3] * std::pow(y, 5);
const double dfdw = ysq * (c[0] + y*(c[1] + y*(c[2] + y*c[3])));
const double summand_3 = std::log(t) / (N * (w + 1)) * dfdw;
return factor * (summand_1 + summand_2 + summand_3);
}
@@ -161,7 +173,8 @@ std::function<double(double)> eT_elastic_scattering() {
std::function<double(double)> T2pT2_charge_exchange_janev() {
return [=](double energy) {
const double sig_ll =
6.59 / (std::pow(energy, 0.5) * (1 + 2.29 * std::pow(energy, 1.78))) +
// 6.59 / (std::pow(energy, 0.5) * (1 + 2.29 * std::pow(energy, 1.78))) +
6.59 / (std::sqrt(energy) * (1 + 2.29 * std::pow(energy, 1.78))) +
12.85 * std::exp(-1.84 * std::pow(energy, -1.55)) /
(std::pow(energy, 0.0673) * (1 + 2.6E-3 * std::pow(energy, 0.97) +
1.63E-10 * std::pow(energy, 2.76)));
@@ -196,9 +209,13 @@ std::function<double(double)> eT2_ionization_bed() {
const double t = energy / ionization_energy;
const double factor = S_m2 / (t + u + 1);
const double yh = 2. / (t + 1);
const double yh2 = yh*yh;
// const double D =
// c[0] / 3 * (1 - std::pow(yh, 3)) + c[1] / 4 * (1 - std::pow(yh, 4)) +
// c[2] / 5 * (1 - std::pow(yh, 5)) + c[3] / 6 * (1 - std::pow(yh, 6));
const double D =
c[0] / 3 * (1 - std::pow(yh, 3)) + c[1] / 4 * (1 - std::pow(yh, 4)) +
c[2] / 5 * (1 - std::pow(yh, 5)) + c[3] / 6 * (1 - std::pow(yh, 6));
(c[0]/3 + c[1]/4 + c[2]/5 + c[3]/6) -
yh2 * (yh*(c[0]/3 + c[2]/5 * yh2) + yh2 * (c[1]/4 + c[3]/6 * yh2));
const double summand_1 = D * std::log(t);
const double summand_2 =
(2 - Ni / N) * ((t - 1) / t - std::log(t) / (t + 1));
@@ -560,8 +577,12 @@ std::function<double(double)> eT2_excitation_vibrational_janev_first() {
return 0.;
}
const double rel = energy / deltaE_eV;
return 5.78 * std::pow(deltaE_eV, -4) * std::pow(rel, -2) *
std::pow(1 - 1 / rel, 6.11 * std::pow(deltaE_eV, -0.5)) * 1E-20;
// return 5.78 * std::pow(deltaE_eV, -4) * std::pow(rel, -2) *
// std::pow(1 - 1 / rel, 6.11 * std::pow(deltaE_eV, -0.5)) * 1E-20;
// change calculation of deltaE_eV^{-4} to a simple constant? (don't know
// it the compiler already changes that)
return 5.78 * std::pow(deltaE_eV, -4) * 1/(rel*rel) *
std::pow(1 - 1 / rel, 6.11 / std::sqrt(deltaE_eV)) * 1E-20;
};
}
@@ -572,8 +593,11 @@ std::function<double(double)> eT2_excitation_vibrational_janev_second() {
return 0.;
}
const double rel = energy / deltaE_eV;
return 5.78 * 0.628 * std::pow(deltaE_eV, -4) * std::pow(rel, -2) *
std::pow(1 - 1 / rel, 6.11 * std::pow(deltaE_eV, -0.5)) * 1E-20;
// return 5.78 * 0.628 * std::pow(deltaE_eV, -4) * std::pow(rel, -2) *
// std::pow(1 - 1 / rel, 6.11 * std::pow(deltaE_eV, -0.5)) * 1E-20;
// same comment as for the function above
return 5.78 * 0.628 * std::pow(deltaE_eV, -4) / (rel*rel) *
std::pow(1 - 1 / rel, 6.11 / std::sqrt(deltaE_eV)) * 1E-20;
};
}
@@ -628,7 +652,8 @@ std::function<double(double)> eT2p_recombination_janev() {
(1 + 1.1 * std::pow(energy, 0.512) +
0.011 * std::pow(energy, 3.10)),
-1) +
0.133 * std::exp(-0.35 * std::pow(energy - 6.05, 2)));
// 0.133 * std::exp(-0.35 * std::pow(energy - 6.05, 2)));
0.133 * std::exp(-0.35 * (energy - 6.05)*(energy - 6.05)));
};
}
std::function<double(double)> eT3p_recombination_janev() {
+12 -9
View File
@@ -18,18 +18,21 @@ ElasticScattering::ElasticScattering(
InteractionOutput ElasticScattering::performInteraction(
particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform elastic scattering.");
#endif
const blitz::TinyVector<double, 3> v_impact =
particle.velocity().cartesianEntries();
const auto x_impact = particle.position();
const blitz::TinyVector<double, 3> v_target =
target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
target_->velocityDistibution()
->rollVelocity(x_impact, generator->engine())
.cartesianEntries();
// const auto x_impact = particle.position();
// const blitz::TinyVector<double, 3> v_target =
// target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
// target_->velocityDistribution()
// ->rollVelocity(x_impact, generator->engine())
// .cartesianEntries();
const blitz::TinyVector<double, 3> v_laboratory =
kinematic::velocityTargetFixed(v_impact, v_target, particle.mass_kg(),
kinematic::velocityTargetFixed(v_impact, target_velocity_.cartesianEntries(),
particle.mass_kg(),
target_->mass_kg());
const double E_kin =
@@ -41,8 +44,8 @@ InteractionOutput ElasticScattering::performInteraction(
const blitz::TinyVector<double, 3> v_impact_new =
kinematic::rotateVelocityInCenterOfMassFrame(
v_impact, v_target, particle.mass_kg(), target_->mass_kg(), theta,
phi);
v_impact, target_velocity_.cartesianEntries(), particle.mass_kg(),
target_->mass_kg(), theta, phi);
particle.velocity(CartesianVector(v_impact_new));
// no Gyrocentrum movement because boris push is used;
+2
View File
@@ -18,7 +18,9 @@ Excitation::Excitation(std::function<double(double)> cross_section,
InteractionOutput Excitation::performInteraction(particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform excitation.");
#endif
const blitz::TinyVector<double, 3> v_impact =
particle.velocity().cartesianEntries();
const blitz::TinyVector<double, 3> n_impact =
+6
View File
@@ -10,7 +10,9 @@ FreeMovement::FreeMovement()
InteractionOutput FreeMovement::performInteraction(particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform free movement.");
#endif
// do nothing
return InteractionOutput();
}
@@ -23,4 +25,8 @@ double FreeMovement::macroscopicCrossSection(particle::Particle& particle) {
// returns a very small number, so the interaction will only be
return SimConstants::minimal_macroscopic_cross_section;
}
double FreeMovement::drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator) {
return std::numeric_limits<double>::max();
}
}; // namespace interaction
+42 -18
View File
@@ -8,6 +8,7 @@
#include "simulation/kinematic.h"
#include "simulation/particle.h"
#include "simulation/velocity_distribution.h"
#include "simulation/logger.h"
namespace interaction {
@@ -29,28 +30,41 @@ ElectronIonization::ElectronIonization(
InteractionOutput ElectronIonization::performInteraction(
particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform ionization.");
#endif
const blitz::TinyVector<double, 3> v_impact =
particle.velocity().cartesianEntries();
const auto x_impact = particle.position();
const auto x_impact = particle.cartesianPosition();
blitz::TinyVector<double, 3> v_target;
blitz::TinyVector<double, 3> v_laboratory;
double E_impact;
do {
v_target =
target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
target_->velocityDistibution()
->rollVelocity(x_impact, generator->engine())
blitz::TinyVector<double, 3> v_target = target_->velocityDistribution()->
rollVelocity(particle.cylinderPosition(),
generator->engine()).cartesianEntries();
if(target_->driftVelocity()) {
v_target += target_->driftVelocity()
->driftVelocity(x_impact, particle.cylinderPosition())
.cartesianEntries();
}
blitz::TinyVector<double, 3> v_laboratory = kinematic::velocityTargetFixed(
v_impact, target_velocity_.cartesianEntries(), particle.mass_kg(), target_->mass_kg()
);
v_laboratory = kinematic::velocityTargetFixed(
v_impact, v_target, particle.mass_kg(), target_->mass_kg());
E_impact = kinematic::kineticEnergy(v_laboratory, particle.mass_kg()) *
double E_impact = kinematic::kineticEnergy(v_laboratory, particle.mass_kg()) *
UnitConversion::JouleToeV;
} while (E_impact <= ionization_energy_eV_);
// do {
// v_target =
// target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
// target_->velocityDistribution()
// ->rollVelocity(x_impact, generator->engine())
// .cartesianEntries();
// v_laboratory = kinematic::velocityTargetFixed(
// v_impact, v_target, particle.mass_kg(), target_->mass_kg());
// E_impact = kinematic::kineticEnergy(v_laboratory, particle.mass_kg()) *
// UnitConversion::JouleToeV;
// } while (E_impact <= ionization_energy_eV_);
const double E_impact_new =
energy_distribution_->rollImpactParticleEnergyAfterCollision(E_impact,
@@ -83,20 +97,30 @@ InteractionOutput ElectronIonization::performInteraction(
kinematic::rotateVector(v_lab_norm, azimuth_angle_impact_new,
polar_angle_impact_new) *
v_lab_impact_new +
v_target;
target_velocity_.cartesianEntries();
const blitz::TinyVector<double, 3> v_ejected =
kinematic::rotateVector(v_lab_norm, azimuth_angle_ejected,
polar_angle_ejected) *
v_lab_ejected +
v_target;
target_velocity_.cartesianEntries();
particle.velocity(v_impact_new);
const double time_birth = particle.timeAlive();
const double weight_parent = particle.weight();
InteractionOutput output;
output.add(
particle::Particle(electron_, x_impact, CartesianVector(v_ejected)));
output.add(particle::Particle(ion_, x_impact, CartesianVector(v_target)));
particle::Particle(electron_, x_impact, CartesianVector(v_ejected),
time_birth, weight_parent));
output.add(particle::Particle(ion_, x_impact, CartesianVector(v_target),
time_birth, weight_parent));
ion_->deletionLogger()->logDeletion(x_impact, DeletionType::creation_interaction);
electron_->deletionLogger()
->logDeletion(x_impact, DeletionType::creation_interaction);
return output;
}
+83 -52
View File
@@ -6,6 +6,7 @@
#include "simulation/kinematic.h"
#include "constants/physical_constants.h"
#include "simulation/drift_velocity.h"
#include "simulation/electromagnetic_field.h"
namespace interaction {
@@ -16,77 +17,107 @@ Recombination::Recombination(std::function<double(double)> cross_section,
InteractionOutput Recombination::performInteraction(
particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform recombination.");
#endif
std::vector<double> macroscopic_bin_cross_sections_m;
const int number_energy_bins = recombination_target_->dynamicDensityField()
->energyBinning()->binIndexMax();
std::vector<double> energyBinBorders = recombination_target_->
dynamicDensityField()->energyBinning()->binBorders();
// std::vector<double> macroscopic_bin_cross_sections_m;
// const int number_energy_bins = recombination_target_->dynamicDensityField()
// ->energyBinning()->binIndexMax();
// std::vector<double> energyBinBorders = recombination_target_->
// dynamicDensityField()->energyBinning()->binBorders();
if(recombination_target_->type() == species::ImplementedSpecies::electron) {
for (int bin = 0; bin < number_energy_bins - 1; ++bin) {
macroscopic_bin_cross_sections_m.push_back(
macroscopicCrossSection(particle.position(), bin));
}
} else {
const blitz::TinyVector<double, 3> v_particle =
particle.velocity().cartesianEntries();
// if(recombination_target_->type() == species::ImplementedSpecies::electron) {
// for (int bin = 0; bin < number_energy_bins - 1; ++bin) {
// macroscopic_bin_cross_sections_m.push_back(
// macroscopicCrossSection(particle.position(), bin));
// }
// } else {
// const blitz::TinyVector<double, 3> v_particle =
// particle.velocity().cartesianEntries();
if(!recombination_target_->driftVelocity()) {
ERROR(recombination_target_->name() + ": does not have a drift velocity!");
}
// if(!recombination_target_->driftVelocity()) {
// ERROR(recombination_target_->name() + ": does not have a drift velocity!");
// }
const blitz::TinyVector<double, 3> v_partner =
recombination_target_->driftVelocity()
->driftVelocity(particle.position()).cartesianEntries();
// const blitz::TinyVector<double, 3> v_partner =
// recombination_target_->driftVelocity()
// ->driftVelocity(particle.position()).cartesianEntries();
const blitz::TinyVector<double, 3> velocity_target_fixed =
kinematic::velocityTargetFixed(v_particle, v_partner, particle.mass_kg(),
recombination_target_->mass_kg());
// const blitz::TinyVector<double, 3> velocity_target_fixed =
// kinematic::velocityTargetFixed(v_particle, v_partner, particle.mass_kg(),
// recombination_target_->mass_kg());
const double kinetic_energy_eV =
kinematic::kineticEnergy(velocity_target_fixed, particle.mass_kg()) *
UnitConversion::JouleToeV;
// const double kinetic_energy_eV =
// kinematic::kineticEnergy(velocity_target_fixed, particle.mass_kg()) *
// UnitConversion::JouleToeV;
double energy_eV_bin_center;
for (int bin = 0; bin < number_energy_bins - 1; ++bin) {
energy_eV_bin_center = (energyBinBorders[bin] + energyBinBorders[bin+1])/2.;
macroscopic_bin_cross_sections_m.push_back(
microscopicCrossSection(kinetic_energy_eV) *
recombination_target_->dynamicDensityField()
->density(particle.position(), energy_eV_bin_center));
}
}
// double energy_eV_bin_center;
// for (int bin = 0; bin < number_energy_bins - 1; ++bin) {
// energy_eV_bin_center = (energyBinBorders[bin] + energyBinBorders[bin+1])/2.;
// macroscopic_bin_cross_sections_m.push_back(
// microscopicCrossSection(kinetic_energy_eV) *
// recombination_target_->dynamicDensityField()
// ->density(particle.position(), energy_eV_bin_center));
// }
// }
const double total_macroscopic_cross_section_m =
std::accumulate(macroscopic_bin_cross_sections_m.begin(),
macroscopic_bin_cross_sections_m.end(), 0.0);
// const double total_macroscopic_cross_section_m =
// std::accumulate(macroscopic_bin_cross_sections_m.begin(),
// macroscopic_bin_cross_sections_m.end(), 0.0);
if(total_macroscopic_cross_section_m <= 0.) {
ERROR("Total cross section is " +
std::to_string(total_macroscopic_cross_section_m) +
". But recombination was chosen.");
}
// if(total_macroscopic_cross_section_m <= 0.) {
// ERROR("Total cross section is " +
// std::to_string(total_macroscopic_cross_section_m) +
// ". But recombination was chosen.");
// }
std::discrete_distribution<int> energy_bin_decider(
macroscopic_bin_cross_sections_m.begin(),
macroscopic_bin_cross_sections_m.end());
// std::discrete_distribution<int> energy_bin_decider(
// macroscopic_bin_cross_sections_m.begin(),
// macroscopic_bin_cross_sections_m.end());
const int energy_bin = energy_bin_decider(*(generator->engine()));
const double energy_eV = (energyBinBorders[energy_bin] +
energyBinBorders[energy_bin+1]) / 2.;
// const int energy_bin = energy_bin_decider(*(generator->engine()));
// const double energy_eV = (energyBinBorders[energy_bin] +
// energyBinBorders[energy_bin+1]) / 2.;
recombination_target_->dynamicDensityField()->logDeletion(particle.position(),
energy_eV);
// blitz::TinyVector<double, 3> position_bins = recombination_target_->dynamicDensityField()
// ->positionBinning()->bin(particle.position().cylinderEntries());
// const blitz::Array<double, 1> mu_distribution =
// recombination_target_->dynamicDensityField()
// ->timeInBinArray()(position_bins(0),
// position_bins(1),
// position_bins(2),
// blitz::Range::all(),
// energy_bin);
// std::vector<double> mu_borders = recombination_target_->dynamicDensityField()
// ->pitchAngleBinning()->binBorders();
// std::discrete_distribution<int> mu_bin_decider(mu_distribution.begin(),
// mu_distribution.end());
// const int mu_bin = mu_bin_decider(*(generator->engine()));
// if((mu_bin == 0) || (mu_bin == mu_distribution.size()-1)) {
// ERROR("Recombination: drawn mu is from over- or underflow bin!");
// std::stringstream out;
// out << "mu distribution values: n";
// out << mu_distribution;
// DEBUG_LEVEL_3(out.str());
// }
// const double mu = (mu_borders[mu_bin - 1] + mu_borders[mu_bin])/2.;
// recombination_target_->dynamicDensityField()->logDeletion(particle.position(),
// energy_eV, mu);
InteractionOutput output;
output.deleteCurrentParticle(true);
if (particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(
particle.position(), DeletionType::recombination);
particle.cartesianPosition(), DeletionType::recombination);
}
return output;
@@ -97,7 +128,7 @@ double Recombination::macroscopicCrossSection(particle::Particle& particle) {
const int numBins = recombination_target_->dynamicDensityField()->
energyBinning()->binIndexMax();
double macroscopic_cross_section = 0.;
const auto position = particle.position();
const auto position = particle.cylinderPosition();
for (int bin = 0; bin < numBins - 1; ++bin) {
macroscopic_cross_section += macroscopicCrossSection(position, bin);
}
+55 -27
View File
@@ -16,9 +16,7 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
std::vector<std::shared_ptr<Electrode>> electrodes,
double target_accuracy,
int num_cycles,
int solver_intervall,
int solver_offset,
bool reset_after_solving)
bool do_solver)
: bottom_boundary_(bottom_boundary),
top_boundary_(top_boundary),
hull_boundary_(hull_boundary),
@@ -34,9 +32,7 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
electrodes_(electrodes),
target_accuracy_(target_accuracy),
num_cycles_(num_cycles),
solver_intervall_(solver_intervall),
solver_offset_(solver_offset),
reset_after_solving_(reset_after_solving) {
do_solver_(do_solver) {
blitz::TinyVector<double, 3> stepsize = density_binning_.stepsize();
for (int i = potential_.lbound(0); i <= potential_.ubound(0); ++i) {
@@ -81,41 +77,40 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
blitz::Range(density_binning.binIndexMin()(2),
density_binning.binIndexMax()(2)));
zero_chargedensity = 0.;
bool reset;
solvePotential(zero_chargedensity, 0, reset);
solvePotential(zero_chargedensity, true);
}
void PoissonSolver::solvePotential(
const blitz::Array<double, 3> charge_density, int cpu_sync,
bool& reset) {
if ((cpu_sync % solver_intervall_ != 0) || ((cpu_sync <= solver_offset_)
&& (cpu_sync > 0))) {
reset = false;
const blitz::Array<double, 3> charge_density, const bool solve) {
if (!(do_solver_) || !(solve)) {
return;
}
#ifdef debug_level3
DEBUG_LEVEL_3("Interpolating chargedensity.");
#endif
blitz::Array<double, 3> interpolated_density =
interpolateDensityToPotentialGrid(charge_density);
int it = 1;
do {
solverIteration(interpolated_density);
if (it % 1000 == 0) {
#ifdef debug_level3
DEBUG_LEVEL_3("Poisson solver, iteration: " + std::to_string(it));
#endif
if (converged(interpolated_density)) {
break;
};
}
++it;
} while (it < num_cycles_);
reset = reset_after_solving_;
}
void PoissonSolver::solverIteration(
const blitz::Array<double, 3>& interpolated_density) {
blitz::TinyVector<double, 3> stepsize = density_binning_.stepsize();
const double dr_sq = std::pow(stepsize(0), 2); // shorthand
const double dth_sq = std::pow(stepsize(1), 2); // shorthand
const double dz_sq = std::pow(stepsize(2), 2); // shorthand
const double dr_sq = stepsize(0)*stepsize(0); // shorthand
const double dth_sq = stepsize(1)*stepsize(1); // shorthand
const double dz_sq = stepsize(2)*stepsize(2); // shorthand
for (int i = potential_.lbound(0); i <= potential_.ubound(0); ++i) {
for (int j = potential_.lbound(1); j <= potential_.ubound(1); ++j) {
@@ -154,13 +149,13 @@ void PoissonSolver::solverIteration(
: j - 1; // j-1 with periodic guard
const double scaling_factor = 2 / dr_sq + 2 / dz_sq +
2 / (std::pow(i, 2) * dr_sq * dth_sq);
2 / (i*i * dr_sq * dth_sq);
potential_(i, j, k).value =
(1 / scaling_factor) *
((1 / dr_sq * (1 + 1. / (2. * i))) * potential_(i + 1, j, k).value +
(1 / dr_sq * (1 - 1. / (2. * i))) * potential_(i - 1, j, k).value +
(1 / (std::pow(i, 2) * dr_sq * dth_sq)) *
(1 / (i*i * dr_sq * dth_sq)) *
(potential_(i, jp1, k).value + potential_(i, jm1, k).value) +
(1 / dz_sq) * (potential_(i, j, k + 1).value +
potential_(i, j, k - 1).value) +
@@ -176,9 +171,9 @@ void PoissonSolver::solverIteration(
bool PoissonSolver::converged(
const blitz::Array<double, 3>& interpolated_density) {
blitz::TinyVector<double, 3> stepsize = density_binning_.stepsize();
const double dr_sq = std::pow(stepsize(0), 2); // shorthand
const double dth_sq = std::pow(stepsize(1), 2); // shorthand
const double dz_sq = std::pow(stepsize(2), 2); // shorthand
const double dr_sq = stepsize(0)*stepsize(0); // shorthand
const double dth_sq = stepsize(1)*stepsize(1); // shorthand
const double dz_sq = stepsize(2)*stepsize(2); // shorthand
double cumulated_quadradic_difference = 0.;
double normalized_difference = 0.;
@@ -205,7 +200,7 @@ bool PoissonSolver::converged(
(potential_(i,j,k+1).value - 2*potential_(i,j,k).value +
potential_(i,j,k-1).value)/dz_sq;
cumulated_quadradic_difference += std::pow(difference, 2);
cumulated_quadradic_difference += difference*difference;
if(fabs(difference) > maximum_difference) {
maximum_difference = fabs(difference);
@@ -225,11 +220,11 @@ bool PoissonSolver::converged(
(potential_(i+1,j,k).value - potential_(i-1,j,k).value)/
(2*i*dr_sq) +
(potential_(i,jp1,k).value - 2*potential_(i,j,k).value +
potential_(i,jm1,k).value)/(std::pow(i,2)*dr_sq*dth_sq) +
potential_(i,jm1,k).value)/(i*i*dr_sq*dth_sq) +
(potential_(i,j,k+1).value - 2*potential_(i,j,k).value +
potential_(i,j,k-1).value)/dz_sq;
cumulated_quadradic_difference += std::pow(difference, 2);
cumulated_quadradic_difference += difference*difference;
if(fabs(difference) > maximum_difference) {
maximum_difference = fabs(difference);
@@ -244,14 +239,18 @@ bool PoissonSolver::converged(
normalized_difference =
std::sqrt(cumulated_quadradic_difference / (nr * nth * nz));
#ifdef debug
DEBUG_LEVEL_0("Poisson solver reached a normalized difference of: " +
std::to_string(normalized_difference));
#endif
double normalized_maximum =
maximum_difference*SI::eps0/(fabs(blitz::max(interpolated_density)) + 1e-12);
#ifdef debug_level1
std::ostringstream message;
message << "Maximum Difference normalized by order of magnitude: "
<< normalized_difference;
DEBUG_LEVEL_0(message.str());
DEBUG_LEVEL_1(message.str());
#endif
return normalized_difference < target_accuracy_;
}
@@ -259,7 +258,9 @@ blitz::Array<double, 3> PoissonSolver::potential() {
// there might be a better way to do this... (if one can do array.memberValue without
// explicitely looping)
blitz::Array<double, 3> potentialValues(potential_.lbound(), potential_.extent());
#ifdef debug_level3
DEBUG_LEVEL_3("Extracting potential values");
#endif
for(int i = potential_.lbound(0); i <= potential_.ubound(0); ++i) {
for(int j = potential_.lbound(1); j <= potential_.ubound(1); ++j) {
for(int k = potential_.lbound(2); k <= potential_.ubound(2); ++k) {
@@ -302,9 +303,10 @@ blitz::Array<double, 3> PoissonSolver::interpolateDensityToPotentialGrid(
//might not work that way (if not needs a loop)
interpolatedDensity(fixedIndex, blitz::Range::all(), blitz::Range::all()) /=
potential_.extent(1);
#ifdef debug_level3
DEBUG_LEVEL_3("Max Value in interpolated density array: " +
std::to_string(blitz::max(interpolatedDensity)));
#endif
//for r=r_max, k=k_min and k=k_max do not use an interpolation,
//since no boundary cell needs the information about its density value
return interpolatedDensity;
@@ -364,6 +366,32 @@ const CylinderBinning* PoissonSolver::densityBinning() {
return &density_binning_;
}
void PoissonSolver::setPotential(blitz::Array<double, 3>& potential) {
// check if the loaded potential has the same size as the potential
// specified by the json file
if(!blitz::all(potential.length() == potential_.length())) {
std::stringstream out;
out << "The size of the potential is " << potential.length();
out << ". But expected a size of " << potential_.length();
ERROR(out.str());
}
// necessary since it's not guaranteed (or even likely) that both arrays
// are indexed the same (i.e. potential_ is most likely starting from -1,
// while the parameter array is most likely starting from 0)
const int i_offset = potential.lbound(0) - potential_.lbound(0);
const int j_offset = potential.lbound(1) - potential_.lbound(1);
const int k_offset = potential.lbound(2) - potential_.lbound(2);
for(int i = potential_.lbound(0); i <= potential_.ubound(0); ++i) {
for(int j = potential_.lbound(1); j <= potential_.ubound(1); ++j) {
for(int k = potential_.lbound(2); k <= potential_.ubound(2); ++k) {
potential_(i,j,k).value = potential(i + i_offset,j + j_offset,k + k_offset);
}
}
}
}
Electrode::Electrode(double potential): potential_(potential) {};
double Electrode::electrodePotential() {
+33 -6
View File
@@ -56,9 +56,23 @@ blitz::TinyVector<double, 3> CartesianCoordinate::cartesianEntries() const {
return cartesian_position;
}
double CartesianCoordinate::sinAzimuth() const {
double rad = std::sqrt(cartesian_position(0)*cartesian_position(0) +
cartesian_position(1)*cartesian_position(1));
return cartesian_position(1)/rad;
}
double CartesianCoordinate::cosAzimuth() const {
double rad = std::sqrt(cartesian_position(0)*cartesian_position(0) +
cartesian_position(1)*cartesian_position(1));
return cartesian_position(0)/rad;
}
blitz::TinyVector<double, 3> CartesianCoordinate::cylinderEntries() const {
const double radius = std::sqrt(std::pow(cartesian_position(0), 2) +
std::pow(cartesian_position(1), 2));
// const double radius = std::sqrt(std::pow(cartesian_position(0), 2) +
// std::pow(cartesian_position(1), 2));
const double radius = std::sqrt(cartesian_position(0)*cartesian_position(0) +
cartesian_position(1)*cartesian_position(1));
const double phi = std::atan2(cartesian_position(1), cartesian_position(0));
const double z = cartesian_position(2);
return blitz::TinyVector<double, 3>(radius, phi, z);
@@ -83,6 +97,14 @@ CylinderCoordinate::CylinderCoordinate(const Coordinate& coordinate)
// limitPhi();
}
double CylinderCoordinate::cosAzimuth() const {
return std::cos(cylinder_position(1));
}
double CylinderCoordinate::sinAzimuth() const {
return std::sin(cylinder_position(1));
}
blitz::TinyVector<double, 3> CylinderCoordinate::cartesianEntries() const {
return blitz::TinyVector<double, 3>(
cylinder_position(0) * std::cos(cylinder_position(1)),
@@ -134,12 +156,16 @@ CylinderVector CylinderVector::operator+(const CylinderVector& vector) {
blitz::TinyVector<double, 3> CylinderVector::cartesianEntries(
const Coordinate& coordinate) const {
// double phi = coordinate.cylinderEntries()(1);
double cosphi = coordinate.cosAzimuth();
double sinphi = coordinate.sinAzimuth();
const double A_x =
std::cos(coordinate.cylinderEntries()(1)) * cylinder_vector(0) -
std::sin(coordinate.cylinderEntries()(1)) * cylinder_vector(1);
cosphi * cylinder_vector(0) -
sinphi * cylinder_vector(1);
const double A_y =
std::sin(coordinate.cylinderEntries()(1)) * cylinder_vector(0) +
std::cos(coordinate.cylinderEntries()(1)) * cylinder_vector(1);
cosphi * cylinder_vector(0) +
sinphi * cylinder_vector(1);
const double A_z = cylinder_vector(2);
return blitz::TinyVector<double, 3>(A_x, A_y, A_z);
}
@@ -153,6 +179,7 @@ blitz::TinyVector<double, 3> CylinderVector::cylinderEntries() const {
return cylinder_vector;
}
// think that function is wrong
void CylinderVector::add(const Vector& vector, const Coordinate& coordinate) {
cylinder_vector += vector.cylinderEntries(coordinate);
}
+63 -41
View File
@@ -17,6 +17,26 @@ 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<float, 5>& array,
blitz::Array<float, 5>& last_sync_array) {
int size = array.size();
blitz::Array<float, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_FLOAT,
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 +47,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();
@@ -65,87 +95,79 @@ void CpuSynchronizer::synchronize(Timer* timer, Timer* last_sync_timer) {
}
void CpuSynchronizer::synchronize(DynamicDensityField* field,
DynamicDensityField* last_sync_field) {
if (field && last_sync_field) {
if(field == last_sync_field) {
ERROR("The way last_sync_field is created does not work as intended.");
}
sumToAll(field->time_in_bin_s_, last_sync_field->time_in_bin_s_);
field->time_in_bin_s_ = last_sync_field->time_in_bin_s_;
DynamicDensityField* 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_, last_sync_field->deleted_particles_);
field->deleted_particles_ = last_sync_field->deleted_particles_;
// sumToAll(field->deleted_particles_, field->sync_deleted_particles_);
// field->deleted_particles_ = field->sync_deleted_particles_;
if (reset) {
density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_;
// density_for_drawing->deleted_particles_ = field->deleted_particles_;
}
}
}
void CpuSynchronizer::synchronize(CurrentCollector* collector,
CurrentCollector* last_sync_collector) {
if (collector && last_sync_collector) {
void CpuSynchronizer::synchronize(CurrentCollector* collector) {
if (collector) {
sumToAll(collector->z_negative_crossings,
last_sync_collector->z_negative_crossings);
collector->sync_z_negative_crossings);
collector->z_negative_crossings =
last_sync_collector->z_negative_crossings;
collector->sync_z_negative_crossings;
sumToAll(collector->z_positive_crossings,
last_sync_collector->z_positive_crossings);
collector->sync_z_positive_crossings);
collector->z_positive_crossings =
last_sync_collector->z_positive_crossings;
collector->sync_z_positive_crossings;
sumToAll(collector->phi_negative_crossings,
last_sync_collector->phi_negative_crossings);
collector->sync_phi_negative_crossings);
collector->phi_negative_crossings =
last_sync_collector->phi_negative_crossings;
collector->sync_phi_negative_crossings;
sumToAll(collector->phi_positive_crossings,
last_sync_collector->phi_positive_crossings);
collector->sync_phi_positive_crossings);
collector->phi_positive_crossings =
last_sync_collector->phi_positive_crossings;
collector->sync_phi_positive_crossings;
sumToAll(collector->r_negative_crossings,
last_sync_collector->r_negative_crossings);
collector->sync_r_negative_crossings);
collector->r_negative_crossings =
last_sync_collector->r_negative_crossings;
collector->sync_r_negative_crossings;
sumToAll(collector->r_positive_crossings,
last_sync_collector->r_positive_crossings);
collector->sync_r_positive_crossings);
collector->r_positive_crossings =
last_sync_collector->r_positive_crossings;
collector->sync_r_positive_crossings;
}
}
void CpuSynchronizer::synchronize(DeletionLogger* logger,
DeletionLogger* last_sync_logger) {
if (logger && last_sync_logger) {
void CpuSynchronizer::synchronize(DeletionLogger* logger) {
if (logger) {
for (auto& pair : logger->num_deletions) {
long int num_deletion = pair.second;
long int last_sync_num_deletion = last_sync_logger->num_deletions[pair.first];
long int last_sync_num_deletion = logger->sync_num_deletions[pair.first];
sumToAll(num_deletion, last_sync_num_deletion);
// last_sync_num_deletion now contains the total number of deletions
// across all cpus -> update the values in the objects
pair.second = last_sync_num_deletion;
last_sync_logger->num_deletions[pair.first] = last_sync_num_deletion;
logger->sync_num_deletions[pair.first] = last_sync_num_deletion;
}
}
}
void CpuSynchronizer::synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species) {
tracked_species, bool reset) {
MPI_Barrier(MPI_COMM_WORLD);
auto it = tracked_species.begin();
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->lastSyncDensityField());
// DEBUG_LEVEL_3("cc Synchronization.");
synchronize(pair.second->currentCollector(),
pair.second->lastSyncCurrentCollector());
// DEBUG_LEVEL_3("dellogger Synchronization.");
synchronize(pair.second->deletionLogger(),
pair.second->lastSyncDeletionLogger());
pair.second->densityForDrawing(), reset);
synchronize(pair.second->currentCollector());
synchronize(pair.second->deletionLogger());
}
}
+38 -16
View File
@@ -12,7 +12,13 @@ CurrentCollector::CurrentCollector(const CylinderBinning& position_binning,
collector_areas_r(createAreaRadial(position_binning)),
phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
phi_positive_crossings(createCrossingsAzimuthal(position_binning)),
collector_areas_phi(createAreaAzimuthal(position_binning)) {}
collector_areas_phi(createAreaAzimuthal(position_binning)),
sync_z_negative_crossings(createCrossingsLongitudinal(position_binning)),
sync_z_positive_crossings(createCrossingsLongitudinal(position_binning)),
sync_r_negative_crossings(createCrossingsRadial(position_binning)),
sync_r_positive_crossings(createCrossingsRadial(position_binning)),
sync_phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
sync_phi_positive_crossings(createCrossingsAzimuthal(position_binning)) {}
blitz::Array<double, 3> CurrentCollector::createAreaLongitudinal(
const CylinderBinning& position_binning) {
@@ -30,8 +36,10 @@ blitz::Array<double, 3> CurrentCollector::createAreaLongitudinal(
const double dr = position_binning.stepsize()(0);
const double r1 = ir * dr;
const double r2 = (ir + 1) * dr;
// const double area_element =
// (std::pow(r2, 2) - std::pow(r1, 2)) * M_PI / (area_z.extent(1));
const double area_element =
(std::pow(r2, 2) - std::pow(r1, 2)) * M_PI / (area_z.extent(1));
(r2*r2 - r1*r1) * M_PI / (area_z.extent(1));
area_z(ir, blitz::Range::all(), blitz::Range::all()) = area_element;
}
return area_z;
@@ -130,42 +138,47 @@ void CurrentCollector::collect(particle::Particle* particle,
blitz::TinyVector<int, 3> bin_old =
position_binning_.bin(old_position.cylinderEntries());
blitz::TinyVector<int, 3> bin_new =
position_binning_.bin(particle->position().cylinderEntries());
position_binning_.bin(particle->cylinderPosition().cylinderEntries());
collectRadialMovement(bin_old, bin_new);
collectLongitudinalMovement(bin_old, bin_new);
collectAzimuthalMovement(bin_old, bin_new);
const double weight = particle->weight();
collectRadialMovement(bin_old, bin_new, weight);
collectLongitudinalMovement(bin_old, bin_new, weight);
collectAzimuthalMovement(bin_old, bin_new, weight);
}
void CurrentCollector::collectRadialMovement(
const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new) {
const blitz::TinyVector<int, 3>& bin_new,
const double weight) {
if (bin_new(0) < bin_old(0)) {
r_negative_crossings(bin_new(0), bin_old(1), bin_old(2)) += 1;
r_negative_crossings(bin_new(0), bin_old(1), bin_old(2)) += weight;
} else if (bin_new(0) > bin_old(0)) {
r_positive_crossings(bin_new(0) - 1, bin_old(1), bin_old(2)) += 1;
r_positive_crossings(bin_new(0) - 1, bin_old(1), bin_old(2)) += weight;
}
}
void CurrentCollector::collectLongitudinalMovement(
const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new) {
const blitz::TinyVector<int, 3>& bin_new,
const double weight) {
if (bin_new(2) < bin_old(2)) {
z_negative_crossings(bin_old(0), bin_old(1), bin_new(2) + 1) += 1;
z_negative_crossings(bin_old(0), bin_old(1), bin_new(2) + 1) += weight;
} else if (bin_new(2) > bin_old(2)) {
z_positive_crossings(bin_old(0), bin_old(1), bin_new(2)) += 1;
z_positive_crossings(bin_old(0), bin_old(1), bin_new(2)) += weight;
}
}
void CurrentCollector::collectAzimuthalMovement(
const blitz::TinyVector<int, 3>& bin_old,
const blitz::TinyVector<int, 3>& bin_new) {
const blitz::TinyVector<int, 3>& bin_new,
const double weight) {
if ((bin_new(1) < bin_old(1)) ||
((bin_old(1) == 0) &&
(bin_new(1) == position_binning_.binIndexMax()(1)))) {
phi_negative_crossings(bin_old(0), bin_new(1), bin_old(2)) += 1;
phi_negative_crossings(bin_old(0), bin_new(1), bin_old(2)) += weight;
} else if ((bin_new(1) > bin_old(1)) ||
((bin_old(1) == position_binning_.binIndexMax()(1)) &&
(bin_new(1) == 0))) {
phi_positive_crossings(bin_old(0), bin_new(1) - 1, bin_old(2)) += 1;
phi_positive_crossings(bin_old(0), bin_new(1) - 1, bin_old(2)) += weight;
}
}
@@ -238,7 +251,7 @@ blitz::Array<double, 3> CurrentCollector::currentInR() const {
return current_in_r;
}
double CurrentCollector::physicalTime() const {
return timer_->time();
return timer_->getDeltaT();
}
void CurrentCollector::resetCurrentCollector() {
@@ -250,4 +263,13 @@ void CurrentCollector::resetCurrentCollector() {
r_negative_crossings = 0.;
r_positive_crossings = 0.;
sync_z_negative_crossings = 0.;
sync_z_positive_crossings = 0.;
sync_phi_negative_crossings = 0.;
sync_phi_positive_crossings = 0.;
sync_r_negative_crossings = 0.;
sync_r_positive_crossings = 0.;
}
+237 -68
View File
@@ -4,6 +4,9 @@
#include "simulation/errors.h"
#include "simulation/event_position_distribution.h"
#include "simulation/scalar_field.h"
#include "simulation/kinematic.h"
#include "tools/simulation_time.h"
template <class T>
blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
@@ -15,6 +18,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,
@@ -30,7 +44,7 @@ blitz::Array<double, 3> initiateVolumeArray(
const double z2 = (iz + 1) * position_spacing(2);
const double bin_volume =
M_PI * (std::pow(r2, 2) - std::pow(r1, 2)) * (z2 - z1) / phi.length();
M_PI * ((r2*r2) - (r1*r1)) * (z2 - z1) / phi.length();
volume(ir, blitz::Range::all(), iz) = bin_volume;
}
@@ -41,28 +55,56 @@ blitz::Array<double, 3> initiateVolumeArray(
DynamicDensityField::DynamicDensityField(
const CylinderBinning& position_binning,
const EnergyBinning& energy_binning,
std::shared_ptr<Timer> timer)
: position_binning_(position_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_(initiate4DArray<double>(
time_in_bin_s_(initiate5DArray<float>(
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_(initiate4DArray<long int>(
sync_time_in_bin_s_(initiate5DArray<float>(
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()),
@@ -80,11 +122,45 @@ DynamicDensityField::DynamicDensityField(
blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()),
position_binning.stepsize())) {
if (!timer) {
if(!timer) {
ERROR("Timer is necessary for calculation of density field");
}
}
double DynamicDensityField::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) / //- deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
double DynamicDensityField::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) / // - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
bool DynamicDensityField::changedPositionBin(
const Coordinate& old_position,
const Coordinate& new_position) const {
@@ -105,63 +181,67 @@ bool DynamicDensityField::changedEnergyBin(double old_energy_eV,
return !(old_bin == new_bin);
}
bool DynamicDensityField::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);
#ifdef debug_level3
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));
}
#endif
return !(old_bin == new_bin);
}
void DynamicDensityField::logMovement(const Coordinate& position,
double energy_eV,
double time_in_bin_s) {
double pitch_angle,
double weight) {
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);
time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
energy_bin) += time_in_bin_s;
pitch_angle_bin, energy_bin) += static_cast<float>(weight);
}
void DynamicDensityField::logDeletion(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);
// void DynamicDensityField::logDeletion(const Coordinate& position,
// double energy_eV,
// double pitch_angle) {
deleted_particles_(position_bin(0), position_bin(1), position_bin(2),
energy_bin) += 1;
}
// 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);
double DynamicDensityField::density(const Coordinate& position) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const double t = timer_->time();
const double time_in_bin = blitz::sum(time_in_bin_s_(
position_bin(0), position_bin(1), position_bin(2), blitz::Range::all()));
const long int deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2), blitz::Range::all()));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
double DynamicDensityField::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_->time();
const double time_in_bin = time_in_bin_s_(position_bin(0), position_bin(1),
position_bin(2), energy_bin);
const long deleted_particles = deleted_particles_(
position_bin(0), position_bin(1), position_bin(2), energy_bin);
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
// deleted_particles_(position_bin(0), position_bin(1), position_bin(2), pitch_angle_bin,
// energy_bin) += 1;
// return;
// }
blitz::Array<double, 3> DynamicDensityField::densityArray() {
#ifdef debug_level3
DEBUG_LEVEL_3("recalc Density array");
#endif
recalculateDensityArray();
blitz::Array<double, 3> density(density_per_m3_(
blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0));
blitz::TinyVector<int,3> lowerbound(density_per_m3_.lbound(0),
density_per_m3_.lbound(1),
density_per_m3_.lbound(2));
blitz::TinyVector<int,3> extent(density_per_m3_.extent(0),
density_per_m3_.extent(1),
density_per_m3_.extent(2));
blitz::Array<double, 3> density(lowerbound, extent);
blitz::fourthIndex iE;
// DEBUG_LEVEL_3("density sum");
density = blitz::sum(density_per_m3_, iE);
return density.copy();
}
@@ -171,24 +251,14 @@ blitz::Array<double, 4> DynamicDensityField::spectrumArray() {
return density_per_m3_;
}
void DynamicDensityField::recalculateDensityArray() {
blitz::firstIndex ir;
blitz::secondIndex iphi;
blitz::thirdIndex iz;
blitz::fourthIndex iE;
const double t = timer_->time();
density_per_m3_ = (time_in_bin_s_(ir, iphi, iz, iE) / t -
deleted_particles_(ir, iphi, iz, iE)) /
bin_volume_m3_(ir, iphi, iz);
}
blitz::Array<double, 4> DynamicDensityField::timeInBinArray() const {
blitz::Array<float, 5> DynamicDensityField::timeInBinArray() const {
return time_in_bin_s_;
}
blitz::Array<long int, 4> DynamicDensityField::deletedParticlesArray() const {
return deleted_particles_;
}
// blitz::Array<long int, 5> DynamicDensityField::deletedParticlesArray() const {
// return deleted_particles_;
// }
blitz::Array<double, 3> DynamicDensityField::binVolumeArray() const {
return bin_volume_m3_;
}
@@ -201,17 +271,116 @@ const CylinderBinning* DynamicDensityField::positionBinning() const {
return &position_binning_;
}
const PitchAngleBinning* DynamicDensityField::pitchAngleBinning() const {
return &pitch_angle_binning_;
}
double DynamicDensityField::physicalTime() const {
return timer_->time();
}
void DynamicDensityField::resetDynamicDensityField() {
timer_->resetTime(); // reductive since shared between species
time_in_bin_s_ = 0.;
deleted_particles_ = 0.;
density_per_m3_ = 0.;
double DynamicDensityField::timeResolution() const {
return timer_->getDeltaT();
}
void DynamicDensityField::recalculateDensityArray() {
// SimulationTimer::eventStartPoint("recalcDensityArray");
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)), iE) /
bin_volume_m3_(ir, iphi, iz);
//deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) /
// SimulationTimer::eventStopPoint("recalcDensityArray");
}
double DynamicDensityField::particleNumber() {
blitz::Array<double, 3> density = densityArray();
double particleNumber = blitz::sum(density * bin_volume_m3_);
#ifdef debug_level3
DEBUG_LEVEL_3("particle number: " + std::to_string(particleNumber));
#endif
return particleNumber;
}
double DynamicDensityField::particleNumber(blitz::TinyVector<int, 5> index) {
return time_in_bin_s_(index);
}
blitz::Array<double, 1> DynamicDensityField::
sliceSpectrumArray(const Coordinate& position) const {
blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
return density_per_m3_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range(energy_binning_.binIndexMin(),
energy_binning_.binIndexMax()-1)).copy();
}
blitz::Array<float, 1> DynamicDensityField::
sliceTimeInBinArray(const Coordinate& position, double energy_eV) const {
blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
int energy_bin = energy_binning_.bin(energy_eV);
return time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
blitz::Range(0, pitch_angle_binning_.binIndexMax()-1),
energy_bin).copy();
}
void DynamicDensityField::resetDynamicDensityField() {
//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 DynamicDensityField::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 DynamicDensityField::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 DynamicDensityField::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());
// }
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
+5
View File
@@ -8,3 +8,8 @@ DriftVelocity::DriftVelocity(std::shared_ptr<VectorField> drift_velocity)
CartesianVector DriftVelocity::driftVelocity(const Coordinate& position) {
return CartesianVector(drift_velocity_->value(position), position);
}
CartesianVector DriftVelocity::driftVelocity(const CartesianCoordinate& cartPos,
const CylinderCoordinate& cylPos) {
return CartesianVector(drift_velocity_->value(cylPos), cartPos);
}
+7 -2
View File
@@ -16,13 +16,18 @@ void ElectricField::updateDynamicField(std::shared_ptr<VectorField> field) {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
MagneticField::MagneticField(std::shared_ptr<VectorField> field)
: field_(field) {}
MagneticField::MagneticField(std::shared_ptr<VectorField> field,
std::shared_ptr<VectorField> gradient)
: field_(field), gradient_(gradient) {}
CylinderVector MagneticField::value(const Coordinate& position) const {
return field_->value(position);
}
CylinderVector MagneticField::gradientValue(const Coordinate& position) const {
return gradient_->value(position);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
+52 -3
View File
@@ -1,9 +1,10 @@
#include "simulation/energy_binning.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
// 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 +19,26 @@ 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);
}
bin_borders.push_back(bin_max);
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 +64,36 @@ 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);
// otherwise the valid mu-value of -1 is assigned to the underflow
// bin which can lead to a segfault in the drawing of the pitch
// angle in "velocity_distribution.cpp"
if(!(pitch_angle < pitch_angle_bin_borders_.front()) &&
(it == pitch_angle_bin_borders_.begin())) {
return (it - pitch_angle_bin_borders_.begin());
}
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();
}
+8 -1
View File
@@ -37,7 +37,14 @@ MaxwellBoltzmann::MaxwellBoltzmann(double temperature_K)
}
double MaxwellBoltzmann::rollEnergy(std::mt19937* engine) {
return distribution_(*engine);
double value = distribution_(*engine);
// this makes (the test case) reproduceable through restart
// but it does impact the efficiency of the drawing (simple test
// resultet in about an increase of 50% for the function call)
// however, i think that that time increse is almost negligible
// compared to the rest of the operations in the simulation
distribution_.reset();
return value;
}
Constant::Constant(double constant_eV) : constant_eV_(constant_eV) {
@@ -39,3 +39,79 @@ CylinderCoordinate EventPositionDistribution::rollPosition(
return CylinderCoordinate(blitz::TinyVector<double, 3>(
random_numer_r, random_number_phi, random_number_z));
}
PositionDistributionFromDensity::PositionDistributionFromDensity(
std::shared_ptr<DynamicDensityField> density):
density_(density),
density_values(std::uniform_real_distribution<double>(0.,1.)) {
// get the extent of the domain of the DynamicDensityField object to be used for
// the rejection method
double rmin = density->positionBinning()->radial_binning.binBorders().front();
double rmax = density->positionBinning()->radial_binning.binBorders().back();
double phimin = 0;
double phimax = 2*M_PI;
double zmin = density->positionBinning()->longitudinal_binning.binBorders().front();
double zmax = density->positionBinning()->longitudinal_binning.binBorders().back();
// initialize the distributions
r_values = std::uniform_real_distribution<double>(rmin*rmin, rmax*rmax);
phi_values = std::uniform_real_distribution<double>(phimin, phimax);
z_values = std::uniform_real_distribution<double>(zmin, zmax);
}
void PositionDistributionFromDensity::setMaximumDensity() {
maximum_density_ = blitz::max(density_->densityArray());
}
CylinderCoordinate PositionDistributionFromDensity::drawPosition(std::mt19937* engine) {
if(isEqual(maximum_density_, 0.)) {
// abuse the phi coordinate as a check if the density was zero
// only works if phi \in (0, 2pi)
return CylinderCoordinate(blitz::TinyVector<double,3>(0,-1,0));
}
double random_r, random_phi, random_z, random_n;
do {
random_r = std::sqrt(r_values(*engine));
random_phi = phi_values(*engine);
random_z = z_values(*engine);
random_n = density_values(*engine);
// might be bad that the value gets recalculated for each call of density_->density(...)
} while (random_n*maximum_density_ >= density_->density(CylinderCoordinate(
blitz::TinyVector<double,3>(random_r, random_phi, random_z))));
return CylinderCoordinate(
blitz::TinyVector<double, 3>(random_r, random_phi, random_z));
}
CylinderCoordinate PositionDistributionFromDensity::drawPosition(std::mt19937* engine,
int r_idx, int phi_idx, int z_idx) {
double left_bin_border_radial = density_->positionBinning()
->radial_binning.binBorders()[r_idx];
double left_bin_border_azimuthal = density_->positionBinning()
->azimuth_binning.binBorders()[phi_idx];
double left_bin_border_longitudinal = density_->positionBinning()
->longitudinal_binning.binBorders()[z_idx];
auto stepsize = density_->positionBinning()->stepsize();
double r_rndm, phi_rndm, z_rndm;
r_rndm = density_values(*engine);
phi_rndm = density_values(*engine);
z_rndm = density_values(*engine);
double radius = std::sqrt(left_bin_border_radial*left_bin_border_radial +
(2*left_bin_border_radial + stepsize(0))
*stepsize(0)*r_rndm);
return CylinderCoordinate(blitz::TinyVector<double, 3>
(radius,
left_bin_border_azimuthal + stepsize(1) * phi_rndm,
left_bin_border_longitudinal + stepsize(2) * z_rndm));
}
+105 -6
View File
@@ -6,7 +6,13 @@
#include "simulation/kinematic.h"
#include "simulation/particle.h"
#include "simulation/species.h"
#include "simulation/density_field.h"
#include "simulation/velocity_distribution.h"
#include "simulation/electromagnetic_field.h"
#include "simulation/random_numbers.h"
#include "simulation/logger.h"
#include "constants/physical_constants.h"
#include <sstream>
Injector::Injector(
std::vector<InjectorInfo>& injector_info,
@@ -26,7 +32,9 @@ particle::Particle Injector::rollNewParticle(
std::mt19937* engine,
const Coordinate& position,
std::shared_ptr<species::TrackedSpecie> created_specie,
std::shared_ptr<VelocityDistribution> creation_velocity_distribution) {
std::shared_ptr<VelocityDistribution> creation_velocity_distribution,
const double time_birth,
const double weight) {
blitz::TinyVector<double, 3> velocity =
creation_velocity_distribution->rollVelocity(position, engine)
.cartesianEntries();
@@ -35,24 +43,115 @@ particle::Particle Injector::rollNewParticle(
velocity,
mother_drift_velocity_->driftVelocity(position).cartesianEntries());
}
#if defined debug_level3
std::stringstream out;
out << created_specie->name() << " created at time: " << time_birth << "s.";
DEBUG_LEVEL_3(out.str());
#endif
created_specie->deletionLogger()->logDeletion(position, DeletionType::creation_beta);
if(kinematic::kineticEnergy(velocity, created_specie->mass_kg())
*UnitConversion::JouleToeV > 2000) {
created_specie->deletionLogger()->logDeletion(position, DeletionType::creation_above_2keV);
}
return particle::Particle(created_specie, position,
CartesianVector(velocity));
CartesianVector(velocity), time_birth, weight);
}
void Injector::initInjectionTimeDistribution(double delta_t) {
injection_time_distribution_ =
std::uniform_real_distribution<double>(0., delta_t);
}
std::vector<particle::Particle> Injector::rollNewParticles(
std::mt19937* engine) {
std::mt19937* engine, const double current_time,
const double beta_particle_weight) {
// pull drawing from the position distribution into the "multiplicity" loop?
// (would improve resolution stuff in space as well as just in velocity direction
// especially for slow particles, i.e. ions)
std::vector<particle::Particle> new_particles;
const double time_birth = current_time - injection_time_distribution_(*engine);
for (auto& injector_info : injector_infos_) {
CylinderCoordinate position = position_distribution_->rollPosition(engine);
#ifdef debug_level3
DEBUG_LEVEL_3("Injected z position: " +
std::to_string(position.cylinderEntries()(2)));
std::vector<particle::Particle> new_particles;
for (auto& injector_info : injector_infos_) {
#endif
// for (int i = 0; i < injector_info.multiplicity; i++) {
new_particles.push_back(
rollNewParticle(engine, position, injector_info.created_specie,
injector_info.creation_velocity_distribution));
injector_info.creation_velocity_distribution,
time_birth, beta_particle_weight));
// }
}
return new_particles;
}
void Injector::drawNewParticleFromDensityField(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::vector<particle::Particle>& queue,
std::shared_ptr<MagneticField> magnetic_field,
const double weight_factor,
const double injection_time) {
blitz::TinyVector<int, 5> index = specie->randomIndex()->index();
const double num_part_in_bin = specie->densityForDrawing()->particleNumber(index);
if(num_part_in_bin == 0) {
return;
}
// draw the position
CylinderCoordinate position =
specie->positionDistributionFromDensity()->drawPosition(engine,
index(0), index(1), index(2));
#ifdef debug_level3
DEBUG_LEVEL_3("Injected z position: " +
std::to_string(position.cylinderEntries()(2)));
DEBUG_LEVEL_3("Injected r position: " +
std::to_string(position.cylinderEntries()(0)));
#endif
// draw the velocity
CartesianVector velocity(blitz::TinyVector<double, 3>(0,0,0));
// in case the magnetic field is 0 at the current position draw the velocity
// with respect to the z-axis otherwise use the magnetic field
if(kinematic::norm(magnetic_field->value(position).
cartesianEntries(position)) == 0) {
velocity = specie->velocityDistributionFromDensityField()->
drawVelocity(index, engine);
} else {
velocity = specie->velocityDistributionFromDensityField()->
drawVelocity(index, engine, position, magnetic_field);
}
#ifdef debug_level2
std::stringstream out;
out << "drawn index: " << index;
out << "\nnumber of particles (" << specie->name() << ") at index: " << num_part_in_bin;
out << "\ndrawn position: " << position.cylinderEntries();
out << "\ndrawn velocity: " << velocity.cartesianEntries();
DEBUG_LEVEL_2(out.str());
#endif
particle::Particle drawn_particle(specie, position,
velocity, injection_time, weight_factor*num_part_in_bin);
// debugging
specie->deletionLogger()->logDeletion(position, DeletionType::creation_density);
if(drawn_particle.kineticEnergy_eV() > 2000) {
specie->deletionLogger()->logDeletion(position, DeletionType::creation_above_2keV);
}
queue.push_back(drawn_particle);
}
double Injector::timePassed() const {
return 1 / activity_;
}
+83 -2
View File
@@ -29,11 +29,12 @@ std::vector<particle::Particle> InteractionOutput::newParticles() {
Interaction::Interaction(std::function<double(double)> cross_section,
std::shared_ptr<species::Specie> target)
: cross_section_(cross_section), target_(target) {}
: cross_section_(cross_section), target_(target),
target_velocity_(blitz::TinyVector<double, 3> (0,0,0)) {};
// assumes that v_particle >> v_target
double Interaction::macroscopicCrossSection(particle::Particle& particle) {
const auto x_particle = particle.position();
const auto x_particle = particle.cylinderPosition();
const blitz::TinyVector<double, 3> v_particle =
particle.velocity().cartesianEntries();
if(!target_->driftVelocity()) {
@@ -61,4 +62,84 @@ double Interaction::microscopicCrossSection(double energy_eV) {
return cross_section_(energy_eV);
}
// think i need to include the magnetic field for it to be really correct
double Interaction::drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator) {
CartesianVector particle_velocity = particle.velocity();
// approximation for electrons: v_e >> v_t
if(particle.specie()->type() == species::ImplementedSpecies::electron) {
target_velocity_ = CartesianVector(blitz::TinyVector<double, 3>(0,0,0));
} else {
target_velocity_ = target_->velocityDistribution()->
rollVelocity(particle.cylinderPosition(),
generator->engine());
// // if no drift velocity is present, then assume target at rest otherwise
// // use the drift velocity
if(target_->driftVelocity()) {
// auto tmp = target_->driftVelocity()->driftVelocity(particle.position());
target_velocity_.add(target_->driftVelocity()->driftVelocity(
particle.cartesianPosition(), particle.cylinderPosition()),
particle.cartesianPosition());
}
}
// target_velocity_ = CartesianVector(blitz::TinyVector<double, 3>(0.,0.,0.));
// masses are irrelevant for the transformation
const blitz::TinyVector<double, 3> velocity_target_fixed =
kinematic::velocityTargetFixed(particle_velocity.cartesianEntries(),
target_velocity_.cartesianEntries(), 0, 0);
const double relative_velocity = kinematic::norm(velocity_target_fixed);
// std::stringstream out;
// out << "particle "<< particle.specie()->name() <<" velocity: "
// << particle_velocity.cartesianEntries();
// out << "\ntarget "<< target_->name() <<" velocity: "
// << target_velocity_.cartesianEntries();
// out << "\nabsolute relative velocity: " << relative_velocity;
// check if the relative velocity is smaller than an epsilon compared to the larger
// of the two present velocities (to avoid division by 0 if either is 0) probably
// a better version possible
if(relative_velocity/std::max(
kinematic::norm(particle_velocity.cartesianEntries()),
kinematic::norm(target_velocity_.cartesianEntries())
) < SimConstants::compare_epsilon) {
return std::numeric_limits<double>::max();
}
const double energy_eV =
kinematic::kineticEnergy(velocity_target_fixed, particle.mass_kg())*
UnitConversion::JouleToeV;
// out << "energy collision time: " << energy_eV;
const double crosssection = microscopicCrossSection(energy_eV);
// out << "\ncross section: " << crosssection;
const double density = target_->densityField()->density(particle.cylinderPosition());
// out << "\ninverse mfp: " << crosssection*density << ", sigma: " << crosssection;
// out << ", density: " << density;
const double random_number = generator->rollUniform(0.,1.);
if (random_number == 0) {
return std::numeric_limits<double>::max();
}
const double distance_target_fixed =
- 1./(crosssection * density) * log(random_number);
// out << "\ndistance in target fixed frame: " << distance_target_fixed;
const double time = distance_target_fixed / relative_velocity;
// out << "\ntime before collision: " << time;
// if(density != 0)
// DEBUG_LEVEL_1(out.str());
return time;
}
}; // namespace interaction
+9 -2
View File
@@ -92,7 +92,7 @@ double velocity(double energy_eV, double mass_kg) {
}
double relativisticGamma(const blitz::TinyVector<double, 3>& velocity) {
return std::sqrt(1. + blitz::dot(velocity, velocity) / std::pow(SI::c, 2));
return std::sqrt(1. + blitz::dot(velocity, velocity) / (SI::c*SI::c));
}
double relativisticGamma(double kin_energy_eV, double mass_eV) {
@@ -105,7 +105,8 @@ double relativisticBeta(double velocity_ms) {
double relativisticBeta(double kin_energy_eV, double mass_eV) {
const double gamma = relativisticGamma(kin_energy_eV, mass_eV);
return std::sqrt(1 - std::pow(1 / gamma, 2));
// return std::sqrt(1 - std::pow(1 / gamma, 2));
return std::sqrt(1 - 1 / (gamma*gamma));
}
double relativisticMomentum(double energy_eV, double mass_eV) {
@@ -166,4 +167,10 @@ blitz::TinyVector<double, 3> rotateVector(
std::sin(angle) * cross;
}
double cosPitchAngle(blitz::TinyVector<double, 3> vector1,
blitz::TinyVector<double, 3> vector2) {
const double divisor = kinematic::norm(vector1) * kinematic::norm(vector2);
return blitz::dot(vector1, vector2)/divisor;
}
}; // namespace kinematic
+4
View File
@@ -3,6 +3,7 @@
DeletionLogger::DeletionLogger(std::vector<DeletionType> used_types) {
for (auto& type : used_types) {
num_deletions[type] = 0;
sync_num_deletions[type] = 0;
}
}
@@ -35,4 +36,7 @@ void DeletionLogger::resetDeletionLogger() {
for(auto& pair : num_deletions) {
pair.second = 0;
}
for (auto& pair : sync_num_deletions) {
pair.second = 0;
}
}
+251 -66
View File
@@ -19,48 +19,113 @@ BorisMover::BorisMover(double maximal_time_step_s)
"The maximal timestep for boris push must be positive.");
}
// TBD: include F_g (simply add to electric force)
void BorisMover::move(particle::Particle* particle,
double mfp_m,
double collision_time_s,
ElectricField* electric_field,
MagneticField* magnetic_field,
GravityField* gravity_field) {
double leftover_distance = mfp_m;
auto old_position = particle->position();
// only useful if the timescale defined by the gyro frequency allows fast particles
// to move too far
// keep hard coded for now; has to be decided to be either kept (new field for Boris
// mover in json file) or removed again
const double max_distance = 1e-4;
const double delta_timeresolution = particle->specie()->
dynamicDensityField()->timeResolution();
// in order to try to minimize the overshoot in the time domain (i.e. if particle
// can only life a time dt < min(distance/v, maximal_timestep), which might even be
// a lot larger than dt, which would increase the influence of the particle on the
// density)
double max_time_alive = particle->specie()->dynamicDensityField()->physicalTime() -
particle->timeAlive();
double leftover_time = collision_time_s;
// auto old_position = particle->position();
CartesianCoordinate old_position_cart = particle->cartesianPosition();
CylinderCoordinate old_position_cyl = particle->cylinderPosition();
double old_kinetic_energy = particle->kineticEnergy_eV();
if (old_kinetic_energy < 1E-9) {
// Guard against small enegies taking up much time without contributing to
// density
return;
blitz::TinyVector<double, 3> B_old =
magnetic_field->value(old_position_cyl).cartesianEntries(old_position_cart);
double old_mu;
// if magnetic field is 0 use e_z as a reference for the pitch angle
// calculation (don't know if best approach, probably not...)
if (kinematic::norm(B_old) == 0) {
old_mu = kinematic::cosPitchAngle(
blitz::TinyVector<double, 3>(0,0,1),
particle->velocity().cartesianEntries(old_position_cart));
} else {
old_mu = kinematic::cosPitchAngle(
B_old, particle->velocity().cartesianEntries(old_position_cart));
}
double timestep = 0;
// if (old_kinetic_energy < 1E-9) {
// // Guard against small enegies taking up much time without contributing to
// // density
// SIM_INFO("particle skipped due to energy.");
// return;
// }
bool changed_position_bin = false;
bool changed_energy_bin = false;
bool left_simulation_domain = false;
bool changed_mu_bin = false;
bool died_in_bin = false;
while (
!(changed_position_bin || changed_energy_bin || left_simulation_domain) &&
(leftover_distance > 0.)) {
old_position = particle->position();
!(changed_position_bin || changed_energy_bin || left_simulation_domain ||
changed_mu_bin || died_in_bin) && (leftover_time > 0.)) {
old_position_cart = particle->cartesianPosition();
old_position_cyl = particle->cylinderPosition();
old_kinetic_energy = particle->kineticEnergy_eV();
double moved_distance = 0.;
double old_velocity = particle->absoluteVelocity();
timestep = std::min(maximal_time_step_s_, leftover_time);
timestep = std::min(timestep, max_distance / old_velocity);
timestep = std::min(timestep, max_time_alive);
// can probably be removed
// double moved_distance = 0.;
const blitz::TinyVector<double, 3> E =
electric_field->value(old_position).cartesianEntries(old_position);
electric_field->value(old_position_cyl).cartesianEntries(old_position_cart);
const blitz::TinyVector<double, 3> B =
magnetic_field->value(old_position).cartesianEntries(old_position);
magnetic_field->value(old_position_cyl).cartesianEntries(old_position_cart);
const blitz::TinyVector<double, 3> g =
gravity_field->value(old_position_cyl).cartesianEntries(old_position_cart);
movementStep(particle, E, B, moved_distance);
particle->increaseTimeAlive(maximal_time_step_s_);
particle->increaseTimeInBin(maximal_time_step_s_);
movementStep(particle, E, B, g, timestep);
particle->increaseTimeAlive(timestep);
// particle->increaseTimeInBin(timestep);
auto new_position = particle->position();
auto new_position_cart = particle->cartesianPosition();
auto new_velocity = particle->velocity();
const blitz::TinyVector<double, 3> B_new =
magnetic_field->value(particle->cylinderPosition()).
cartesianEntries(new_position_cart);
double new_mu;
if (kinematic::norm(B_new) == 0) {
new_mu = kinematic::cosPitchAngle(
blitz::TinyVector<double, 3>(0,0,1), new_velocity.cartesianEntries());
} else {
new_mu = kinematic::cosPitchAngle(
B_new, new_velocity.cartesianEntries());
}
changed_mu_bin =
particle->specie()->dynamicDensityField()->changedPitchAngleBin(
old_mu, new_mu);
changed_position_bin =
particle->specie()->dynamicDensityField()->changedPositionBin(
old_position, new_position);
old_position_cyl, particle->cylinderPosition());
changed_energy_bin =
particle->specie()->dynamicDensityField()->changedEnergyBin(
@@ -69,41 +134,62 @@ void BorisMover::move(particle::Particle* particle,
left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle);
leftover_distance -= moved_distance;
}
died_in_bin =
particle->specie()->terminator()->reachedMaxTimeAlive(particle);
leftover_time -= timestep;
// if max_time_alive == 0 but the difference between the time alive and
// the endtime > 0 (think can happen due to numerical accuracy)
// an infinite loop is created. Therefore catch that case and
// allow for a small overshoot in the timedomain (see comment in drift mover)
max_time_alive = ((max_time_alive - timestep) <= 0)
? delta_timeresolution*SimConstants::compare_epsilon
: (max_time_alive - timestep);
}
if(died_in_bin) {
particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, particle->timeInBin());
particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position);
old_position_cyl, old_kinetic_energy, old_mu, particle->weight());
#ifdef debug
particle->deposited();
#endif
}
// particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position_cyl);
}
void BorisMover::movementStep(
particle::Particle* particle,
const blitz::TinyVector<double, 3>& electric_field,
const blitz::TinyVector<double, 3>& magnetic_field,
double& moved_distance) const {
const blitz::TinyVector<double, 3>& gravity_field,
// double& moved_distance,
double timestep) const {
const blitz::TinyVector<double, 3> v =
particle->velocity().cartesianEntries();
const double m = particle->mass_kg();
const double q = particle->charge_C();
/*
const double u_minus_x =
v(0) + (q * electric_field(0) * maximal_time_step_s_) / (2. * m);
v(0) + (q * electric_field(0) * timestep) / (2. * m)
+ (gravity_field(0) * timestep) / 2.;
const double u_minus_y =
v(1) + (q * electric_field(1) * maximal_time_step_s_) / (2. * m);
v(1) + (q * electric_field(1) * timestep) / (2. * m)
+ (gravity_field(1) * timestep) / 2.;
const double u_minus_z =
v(2) + (q * electric_field(2) * maximal_time_step_s_) / (2. * m);
v(2) + (q * electric_field(2) * timestep) / (2. * m)
+ (gravity_field(2) * timestep) / 2.;
const double gamma = kinematic::relativisticGamma(
blitz::TinyVector<double, 3>(u_minus_x, u_minus_y, u_minus_z));
const double temp_1_x =
(q * magnetic_field(0) * maximal_time_step_s_) / (2 * m * gamma);
(q * magnetic_field(0) * timestep) / (2 * m * gamma);
const double temp_1_y =
(q * magnetic_field(1) * maximal_time_step_s_) / (2 * m * gamma);
(q * magnetic_field(1) * timestep) / (2 * m * gamma);
const double temp_1_z =
(q * magnetic_field(2) * maximal_time_step_s_) / (2 * m * gamma);
(q * magnetic_field(2) * timestep) / (2 * m * gamma);
const double u_prime_x =
u_minus_x + (u_minus_y * temp_1_z - u_minus_z * temp_1_y);
@@ -130,17 +216,23 @@ void BorisMover::movementStep(
u_minus_z + (u_prime_x * temp_2_y - u_prime_y * temp_2_x);
const double u_new_x =
u_plus_x + (q * electric_field(0) * maximal_time_step_s_) / (2. * m);
u_plus_x + (q * electric_field(0) * timestep) / (2. * m)
+ (gravity_field(0) * timestep) / 2.;
const double u_new_y =
u_plus_y + (q * electric_field(1) * maximal_time_step_s_) / (2. * m);
u_plus_y + (q * electric_field(1) * timestep) / (2. * m)
+ (gravity_field(1) * timestep) / 2.;
const double u_new_z =
u_plus_z + (q * electric_field(2) * maximal_time_step_s_) / (2. * m);
u_plus_z + (q * electric_field(2) * timestep) / (2. * m)
+ (gravity_field(2) * timestep) / 2.;
const blitz::TinyVector<double, 3> u_new(u_new_x, u_new_y, u_new_z);
*/
blitz::TinyVector<double, 3> acceleration = q * electric_field / m +
gravity_field;
/*
Might be slower, but essentially the same code
Might be slower, but essentially the same code */
const blitz::TinyVector<double, 3> u_minus =
v + (q * electric_field * maximal_time_step_s_) / (2. * m);
v + (acceleration * maximal_time_step_s_) / (2.);
const double gamma = kinematic::relativisticGamma(u_minus);;
const blitz::TinyVector<double, 3> temp_1 =
(q * magnetic_field * maximal_time_step_s_) / (2. * m * gamma);
@@ -151,16 +243,15 @@ void BorisMover::movementStep(
const blitz::TinyVector<double, 3> u_plus =
u_minus + (blitz::cross(u_prime, temp_2));
const blitz::TinyVector<double, 3> u_new =
u_plus + (q * electric_field * maximal_time_step_s_) / (2. * m);
*/
u_plus + (acceleration * maximal_time_step_s_) / (2.);
particle->velocity(CartesianVector(u_new));
const CartesianCoordinate distance(u_new * maximal_time_step_s_);
const CartesianCoordinate distance(u_new * timestep);
particle->move(distance);
moved_distance += std::sqrt(
blitz::dot(distance.cartesianEntries(), distance.cartesianEntries()));
// moved_distance += std::sqrt(
// blitz::dot(distance.cartesianEntries(), distance.cartesianEntries()));
}
////////////////////////////////////////////////////////////////////////////////
@@ -171,33 +262,40 @@ DriftMover::DriftMover(double maximal_distance)
: maximal_distance_m_(maximal_distance){};
void DriftMover::move(particle::Particle* particle,
double mfp_m,
double collision_time_s,
ElectricField* electric_field,
MagneticField* magnetic_field,
GravityField* gravity_field) {
double leftover_distance = mfp_m;
double leftover_time = collision_time_s;
auto old_position = particle->position();
auto old_position = particle->cartesianPosition();
auto old_velocity = particle->velocity();
double old_kinetic_energy = particle->kineticEnergy_eV();
double old_mu = kinematic::cosPitchAngle(
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
bool died_in_bin = false;
const double max_time_alive = particle->specie()->terminator()->maxTimeAlive();
double max_time_alive =
particle->specie()->dynamicDensityField()->physicalTime() -
particle->timeAlive();
while (
!(changed_position_bin || changed_energy_bin || left_simulation_domain) &&
(leftover_distance > 0.) && !(died_in_bin)) {
old_position = particle->position();
!(changed_position_bin || changed_energy_bin || changed_mu_bin
|| left_simulation_domain) &&
(leftover_time > 0.) && !(died_in_bin)) {
old_position = particle->cartesianPosition();
old_velocity = particle->velocity();
old_kinetic_energy = particle->kineticEnergy_eV();
const blitz::TinyVector<double, 3> force_over_charge =
blitz::TinyVector<double, 3> force_over_charge =
electric_field->value(old_position).cartesianEntries(old_position) +
gravity_field->value(old_position).cartesianEntries(old_position) *
particle->mass_kg() / particle->charge_C();
@@ -205,6 +303,9 @@ void DriftMover::move(particle::Particle* particle,
const blitz::TinyVector<double, 3> B =
magnetic_field->value(old_position).cartesianEntries(old_position);
const double B_norm = kinematic::norm(B);
const blitz::TinyVector<double, 3> gradB =
magnetic_field->gradientValue(old_position).cartesianEntries(old_position);
// Todo: add calculation of divB here
// use Kassiopeia paper for reference
@@ -216,15 +317,31 @@ void DriftMover::move(particle::Particle* particle,
kinematic::perpendicularVector(old_velocity.cartesianEntries(), B);
const double v_perp_norm = kinematic::norm(v_perp);
const blitz::TinyVector<double, 3> v_drift = driftVelocity(force_over_charge, B);
// magnetic moment
const double magnetic_moment =
(particle->mass_kg()*(v_perp_norm*v_perp_norm)/2)/B_norm;
force_over_charge += -(magnetic_moment / particle->charge_C() * gradB);
// curvature force
force_over_charge += -(particle->mass_kg()/particle->charge_C() *
(v_parallel_norm*v_parallel_norm) *
kinematic::perpendicularVector(gradB, B) /
B_norm);
const blitz::TinyVector<double, 3> v_drift =
driftVelocity(force_over_charge, B);
const double v_drift_norm = kinematic::norm(v_drift);
const double stepsize = std::min(leftover_distance, maximal_distance_m_);
// const double stepsize = std::min(leftover_distance, maximal_distance_m_);
// guard against very large timesteps i.e. v ~ 0 -> timestep = Inf
// should be a very rare case (but has happend)
const double timestep = std::min(
stepsize / (v_parallel_norm + v_perp_norm + v_drift_norm),
double timestep = std::min(
maximal_distance_m_ / std::sqrt(v_parallel_norm*v_parallel_norm +
v_perp_norm*v_perp_norm +
v_drift_norm*v_drift_norm),
max_time_alive);
timestep = std::min(timestep, collision_time_s);
const blitz::TinyVector<double, 3> movement_parallel =
v_parallel * timestep;
@@ -232,12 +349,13 @@ void DriftMover::move(particle::Particle* particle,
const blitz::TinyVector<double, 3> force_over_charge_parallel =
kinematic::parallelVector(force_over_charge, B);
const blitz::TinyVector<double, 3> dv_electric =
timestep * particle->charge_C() * force_over_charge_parallel / particle->mass_kg();
if (v_perp_norm > SimConstants::compare_epsilon) {
const blitz::TinyVector<double, 3> dv_electric = timestep *
particle->charge_C() * force_over_charge_parallel / particle->mass_kg();
if (v_perp_norm/v_parallel_norm > SimConstants::compare_epsilon) {
const double gyro_radius = particle->mass_kg() * v_perp_norm /
(B_norm * std::abs(particle->charge_C()));
(B_norm * particle->charge_C());
const blitz::TinyVector<double, 3> velocity_normal =
(-1) * blitz::cross(B, v_perp);
@@ -247,32 +365,83 @@ void DriftMover::move(particle::Particle* particle,
const double gyro_frequency =
particle->charge_C() * B_norm / particle->mass_kg();
const double total_rotation_angle = gyro_frequency * timestep;
const double total_rotation_angle = -gyro_frequency * timestep;
const blitz::TinyVector<double, 3> movement_around_gyro_center =
offset_to_gyro_center -
kinematic::rotateVector(offset_to_gyro_center, B,
total_rotation_angle) -
offset_to_gyro_center;
total_rotation_angle);
const blitz::TinyVector<double, 3> v_perp_rotated =
kinematic::rotateVector(v_perp, B, total_rotation_angle);
const double v_parallel_norm_new =
kinematic::norm(v_parallel + dv_electric);
// might be better to do after the actual movement and then just extract
// the position again from the particle
const blitz::TinyVector<double, 3> new_position =
old_position.cartesianEntries() + movement_parallel
+ movement_drift + movement_around_gyro_center;
const blitz::TinyVector<double, 3> B_new =
magnetic_field->value(CartesianCoordinate(new_position)).
cartesianEntries(CartesianCoordinate(new_position));
const double v_perp_norm_new =
sqrt(2*magnetic_moment*kinematic::norm(B_new)/particle->mass_kg());
particle->move(CartesianCoordinate(movement_parallel + movement_drift +
movement_around_gyro_center));
particle->velocity(
CartesianVector(v_parallel + v_perp_rotated + dv_electric));
const blitz::TinyVector<double, 3> v_parallel_new =
kinematic::parallelVector(v_parallel + dv_electric, B_new);
const blitz::TinyVector<double, 3> v_perp_new =
kinematic::perpendicularVector(v_perp_rotated, B_new);
// calculation might be an issue if v_parallel_norm = 0
// using just B does not work, since then the information about the velocity
// being parallel or anti-parallel is lost
const blitz::TinyVector<double, 3> v_new =
v_parallel_new/kinematic::norm(v_parallel_new)*v_parallel_norm_new +
v_perp_new/kinematic::norm(v_perp_new)*v_perp_norm_new;
particle->velocity(CartesianVector(v_new));
} else {
particle->move(CartesianCoordinate(movement_parallel + movement_drift));
particle->velocity(CartesianVector(v_parallel + dv_electric));
}
particle->increaseTimeAlive(timestep);
particle->increaseTimeInBin(timestep);
// particle->increaseTimeInBin(timestep);
// if instead of eps*deltaT 0.0 is used the integral would be conserved
// if no particles are lost at a boundary. however in that case the terminator does not
// return the correct value if the time the particle is alive is identical
// to the physical time... -> increases computation time alot
// The version below means that each timestep the density can grow by
// (at most) a factor of (1 + eps) (if no particles are lost)
// TODO:
// - check if it's not better to change the terminator such that is uses the
// compare function from /include/simulation/compare.h
max_time_alive = ((max_time_alive - timestep) <= 0)
? particle->specie()->dynamicDensityField()
->timeResolution()*SimConstants::compare_epsilon
: (max_time_alive - timestep);
#ifdef debug_level3
if (max_time_alive == 0) {
DEBUG_LEVEL_3("Mover: max_time_alive is 0.");
DEBUG_LEVEL_3("Mover: particle time alive: " +
std::to_string(particle->timeAlive()));
}
#endif
const auto new_position = particle->position();
const auto new_position = particle->cartesianPosition();
died_in_bin =
particle->specie()->terminator()->reachedMaxTimeAlive(particle);
#ifdef debug_level3
if(died_in_bin) {
DEBUG_LEVEL_3("Mover: particle died in bin.");
}
#endif
changed_position_bin =
particle->specie()->dynamicDensityField()->changedPositionBin(
@@ -282,15 +451,31 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->changedEnergyBin(
old_kinetic_energy, particle->kineticEnergy_eV());
const double new_mu = kinematic::cosPitchAngle(magnetic_field
->value(new_position).cartesianEntries(new_position),
particle->velocity().cartesianEntries(new_position));
changed_mu_bin = particle->specie()->dynamicDensityField()
->changedPitchAngleBin(old_mu, new_mu);
#ifdef debug_level3
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));
}
#endif
left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle);
leftover_distance -= stepsize;
leftover_time -= timestep;
}
// only log a particle in the bin where its movement ends, i.e. if
// the particle reached the end of the timestep
if(died_in_bin)
particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, particle->timeInBin());
particle->resetTimeInBin();
old_position, old_kinetic_energy, old_mu, particle->weight());
particle->specie()->currentCollector()->collect(particle, old_position);
}
+28 -15
View File
@@ -20,14 +20,17 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position,
const Vector& velocity)
const Vector& velocity,
const double time_birth,
const double weight)
: specie_(specie),
position_(position),
position_cart_(position),
position_cyl_(position),
velocity_(velocity, position),
id_(this->last_id_),
time_alive_s_(0.),
time_in_bin_s_(0.),
interaction_counter_(0) {
time_alive_s_(time_birth),
interaction_counter_(0),
weight_(weight) {
last_id_++;
}
@@ -61,15 +64,21 @@ species::TrackedSpecie* Particle::specie() const {
}
void Particle::position(const Coordinate& new_position) {
position_ = CartesianCoordinate(new_position);
position_cart_ = CartesianCoordinate(new_position);
position_cyl_ = CylinderCoordinate(new_position);
}
CartesianCoordinate Particle::position() const {
return position_;
CartesianCoordinate Particle::cartesianPosition() const {
return position_cart_;
}
CylinderCoordinate Particle::cylinderPosition() const {
return position_cyl_;
}
void Particle::move(const Coordinate& distance) {
position_.add(distance);
position_cart_.add(distance);
position_cyl_ = CylinderCoordinate(position_cart_);
}
double Particle::kineticEnergy_eV() const {
@@ -98,16 +107,20 @@ double Particle::timeAlive() const {
return time_alive_s_;
}
void Particle::increaseTimeInBin(double time_s) {
time_in_bin_s_ += time_s;
long int Particle::ID() const {
return id_;
}
void Particle::resetTimeInBin() {
time_in_bin_s_ = 0.;
double Particle::weight() const {
return weight_;
}
double Particle::timeInBin() const {
return time_in_bin_s_;
void Particle::deposited() {
deposited_ = true;
}
bool Particle::wasDeposited() {
return deposited_;
}
} // namespace particle
+58
View File
@@ -1,4 +1,5 @@
#include "simulation/random_numbers.h"
#include <algorithm>
RandomNumbers::RandomNumbers(int seed)
: engine_(std::make_shared<std::mt19937>(seed)),
@@ -15,3 +16,60 @@ double RandomNumbers::rollUniform(double min, double max) {
std::mt19937* RandomNumbers::engine() {
return engine_.get();
}
// does NOT shuffle the indices!
// num bins for the energy binning should include the underflow bin!
RandomIndex::RandomIndex(blitz::TinyVector<int, 5> num_bins) :
num_bins_(num_bins){
total_bin_number_ = blitz::product(num_bins_);
one_dimensional_indices_.reserve(total_bin_number_);
for(size_t i = 0; i < total_bin_number_; ++i) {
one_dimensional_indices_.push_back(i);
}
current_index_in_vector_ = 0;
}
void RandomIndex::reshuffle(std::mt19937* engine) {
current_index_in_vector_ = 0;
std::shuffle(std::begin(one_dimensional_indices_),
std::end(one_dimensional_indices_), *engine);
}
bool RandomIndex::visited_all() {
return current_index_in_vector_ == total_bin_number_;
}
// return the next index in the shuffled index vector. Returns the last
// index if all bins have been visited. Reshuffling resets this.
// Note that the underflow bin for the energy is included, i.e. min index for E
// is -1 not 0
blitz::TinyVector<int, 5> RandomIndex::index() {
size_t tmp_one_dimensional_idx = one_dimensional_indices_[current_index_in_vector_];
blitz::TinyVector<int, 5> return_index{0,0,0,0,0};
int tmp = 0;
size_t current_prod = total_bin_number_;
for(int d = 4; d >= 0; d--) {
current_prod /= num_bins_(d);
tmp = tmp_one_dimensional_idx / current_prod;
return_index(d) = tmp;
tmp_one_dimensional_idx -= tmp * current_prod;
}
return_index(4) -= 1;
if(!visited_all())
current_index_in_vector_++;
return return_index;
}
+2 -2
View File
@@ -5,12 +5,12 @@ ReflectorDPS::ReflectorDPS(double z_position_dps)
bool ReflectorDPS::needsReflectionBackToDomain(
const particle::Particle* particle) const {
return particle->position().cylinderEntries()(2) > z_position_dps_;
return particle->cylinderPosition().cylinderEntries()(2) > z_position_dps_;
}
void ReflectorDPS::reflectBackToDomain(particle::Particle* particle) const {
blitz::TinyVector<double, 3> old_position =
particle->position().cylinderEntries();
particle->cylinderPosition().cylinderEntries();
old_position(2) = 2 * z_position_dps_ - old_position(2);
particle->position(CylinderCoordinate(old_position));
blitz::TinyVector<double, 3> old_velocity =

Some files were not shown because too many files have changed in this diff Show More