Author SHA1 Message Date
csendlinger 18dc3d56bb added 1GHz magnetic fieldmap 2024-07-22 09:47:41 +02:00
csendlinger cc7d57ba9c Merge branch 'poisson_solver' of masterduck.fspanier.de:katrin/karl into poisson_solver 2024-07-01 10:07:41 +02:00
csendlinger d8163516e7 corrected units in the magnetic Bottle approximations 2024-07-01 10:01:25 +02:00
csendlinger f130274ea5 Added option to turn off Poisson solver,
regardless of offset & interval
2024-06-27 11:07:25 +02:00
csendlinger 1e1c84a211 updated exaple json files
(test_parameter & test_poisson_parameter
effectively the same)
2024-06-27 10:44:45 +02:00
csendlinger d98a14f9ea updated analysis script 2024-06-27 09:05:50 +02:00
csendlinger 6c02cac31f added approximations for the magnetic Bottle in P8 2024-06-20 09:45:57 +02:00
csendlinger 12aeead76d adjusted Drift Mover to be able to handle gradB 2024-06-04 11:03:01 +02:00
csendlinger 4cf84d7f9d quick fix for reading a vector field from a file 2024-05-16 10:24:09 +02:00
csendlinger ba84963f96 split addition of magnetic moment and centrifugal term 2024-05-13 09:37:21 +02:00
csendlinger dc226a8d53 Added gradB as input, adjusted drift mover
to include gradB (not yet tested for correctness)
2024-05-10 14:34:03 +02:00
csendlinger 1f4314c527 added exponential into predefined functions 2024-05-10 14:21:07 +02:00
csendlinger 1efcb58d35 Added gravity array to boris push,
minor cosmetic changes
2024-05-02 09:06:40 +02:00
72 changed files with 639 additions and 4397 deletions
+54 -3
View File
@@ -202,14 +202,18 @@ def plotSpectrumAtZ(filename, path_to_species, z_position, plot_axis, output_per
spectrum_at_z = spectrumAtZ( spectrum_at_z = spectrumAtZ(
filename, path_to_species, z_position, output_period) filename, path_to_species, z_position, output_period)
E_bins = energyBinsDensityfield(filename, path_to_species) E_bins = energyBinsDensityfield(filename, path_to_species)
# included to get dn/dE
E_bin_volumes = E_bins[1:] - E_bins[:-1]
plot_bins, plot_datas = makeBarPlotData( plot_bins, plot_datas = makeBarPlotData(
spectrum_at_z[1:-1], E_bins[0:-1], E_bins[1:]) spectrum_at_z[1:-1]/E_bin_volumes, E_bins[0:-1], E_bins[1:])
plot_axis.plot(plot_bins, plot_datas, label=str(path_to_species)) plot_axis.plot(plot_bins, plot_datas, label=str(path_to_species))
plot_axis.set_xscale("log") plot_axis.set_xscale("log")
plot_axis.set_yscale("log") plot_axis.set_yscale("log")
plot_axis.set_xlabel(r"Energy $E$ (eV)") plot_axis.set_xlabel(r"Energy $E$ (eV)")
plot_axis.set_ylabel( plot_axis.set_ylabel(
r"Diff. Density $\frac{\mathrm{d}n_e}{\mathrm{d}\log_{10}E}$ $\left(\frac{1}{\mathrm{m}^{3} \log_{10}(\mathrm{eV})}\right)$") r"Diff. Density $\frac{\mathrm{d}n_e}{\mathrm{d}E}$ $\left(\frac{1}{\mathrm{m}^{3} \mathrm{eV}}\right)$")
# plot_axis.set_ylabel(
# r"Diff. Density $\frac{\mathrm{d}n_e}{\mathrm{d}\log_{10}E}$ $\left(\frac{1}{\mathrm{m}^{3} \log_{10}(\mathrm{eV})}\right)$")
def plotAllSpectrumAtZ(filename, z_position, output_period, specie_keys, output_folder): def plotAllSpectrumAtZ(filename, z_position, output_period, specie_keys, output_folder):
@@ -278,7 +282,7 @@ def plotLongitudinalElectricCurrentVsZ(filename, path_to_species, plot_axis, out
z_bins = zBinsDensityField(filename, path_to_species) z_bins = zBinsDensityField(filename, path_to_species)
plot_axis.plot(z_bins, current_in_z) plot_axis.plot(z_bins, current_in_z)
plot_axis.set_xlabel(r"Distance to rear wall $z$ (m)") plot_axis.set_xlabel(r"Distance to rear wall $z$ (m)")
plot_axis.set_ylabel(r"Electric current $I$ ($A$)") plot_axis.set_ylabel(r"Electric current $I$ ($A$)") # unit should be wrong, think it should be A/m^2
def printDeletionLoggerStats(filename, path_to_species, output_period="LastSyncPeriod"): def printDeletionLoggerStats(filename, path_to_species, output_period="LastSyncPeriod"):
@@ -300,3 +304,50 @@ def printDeletionLoggerStats(filename, path_to_species, output_period="LastSyncP
def printAllDeletionLoggerStats(filename, specie_keys, output_period): def printAllDeletionLoggerStats(filename, specie_keys, output_period):
for key in specie_keys: for key in specie_keys:
printDeletionLoggerStats(filename, key, output_period) printDeletionLoggerStats(filename, key, output_period)
def zBinsPoissonSolver(filename, path_to_poisson_solver):
file = h5py.File(filename, 'r')
path_to_border = path_to_poisson_solver + "/BinBorders/longitudinal"
return np.array(file[path_to_border])
def rBinsPoissonSolver(filename, path_to_poisson_solver):
file = h5py.File(filename, 'r')
path_to_border = path_to_poisson_solver + "/BinBorders/radial"
return np.array(file[path_to_border])
def potential(filename, path_to_poisson_solver, output_period):
file = h5py.File(filename, 'r')
path_to_density = path_to_poisson_solver + "/SimulationData" + \
outputPeriodKey(output_period) + "/Potential"
return np.array(file[path_to_density])
# returns potential averaged over r-direction; assumes only one azimuthal bin
def potentialVsZ(filename, path_to_poisson_solver, output_period="LastSyncPeriod"):
rbinBorders = rBinsPoissonSolver(filename, path_to_poisson_solver)
deltar = rbinBorders[1] - rbinBorders[0] #assumption of linear binning
weights = rbinBorders[1:]**2 - rbinBorders[:-1]**2 + deltar**2
weights = np.append(deltar**2/4, weights)
potentialValues = potential(filename, path_to_poisson_solver, output_period)
weightedPotential = potentialValues*weights[:, np.newaxis, np.newaxis]
return np.sum(weightedPotential, axis=(0,1)) / np.sum(weights)
def plotPotentialVsZ(filename, path_to_poisson_solver, plot_axis, output_period="LastSyncPeriod"):
potential_ = potentialVsZ(filename, path_to_poisson_solver, output_period)
z_bins = zBinsPoissonSolver(filename, path_to_poisson_solver)
plot_bins, plot_datas = makeBarPlotData(
potential_, z_bins, z_bins)
plot_axis.plot(plot_bins, plot_datas)
# plot_axis.set_yscale("log")
plot_axis.set_xlabel(r"Distance to rear wall $z$ (m)")
plot_axis.set_ylabel(r"Potential $\Phi$ ($V$)")
def plotAllPotentialVsZ(filename, output_period, output_folder):
pst.setRcParams()
fig, ax = plt.subplots(figsize=pst.set_size('thesis'))
key = "PoissonSolver"
plotPotentialVsZ(filename, key, ax, output_period)
ax.set_facecolor('#e7e7e7ff')
ax.grid(color='white')
fig.savefig(output_folder + "/potential_vs_z_at_period={}.pdf".format(output_period),
format='pdf', bbox_inches='tight')
+10 -18
View File
@@ -12,15 +12,9 @@ CATCH_INCLUDES = -I$(CATCH_DIR)
# Blitz # Blitz
MAKE_BLITZ = false MAKE_BLITZ = false
ifeq ($(MAKE_BLITZ), true) BLITZ_DIR = $(HOMEBASE)/external/blitz/build/
BLITZ_DIR = $(HOMEBASE)/external/blitz/build BLITZ_INC_DIR = $(BLITZ_DIR)include/
BLITZ_INC_DIR = $(BLITZ_DIR)/include BLITZ_LIB_DIR = $(BLITZ_DIR)lib/
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_INCLUDES = -I$(BLITZ_INC_DIR)
BLITZ_LIBS = -L$(BLITZ_LIB_DIR) -lblitz -lm BLITZ_LIBS = -L$(BLITZ_LIB_DIR) -lblitz -lm
@@ -38,13 +32,11 @@ HDF5P_LIBRARIES = -L$(HDF5P_LIB_DIR) -lz -lhdf5_hl -lhdf5
# Janson # Janson
MAKE_JANSSON = false MAKE_JANSSON = false
ifeq ($(MAKE_JANSSON), true) JANSON_DIR = $(HOMEBASE)/external/jansson/
JANSSON_INC_DIR = $(HOMEBASE)/external/jansson/build/include JANSON_INC_DIR = $(JANSON_DIR)
JANSSON_LIB_DIR = $(HOMEBASE)/external/jansson/build/lib JANSSON_LIBRARIES = -ljansson
else JANSSON_INCLUDES = -I$(JANSON_INC_DIR)
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)
+6 -16
View File
@@ -4,32 +4,22 @@ dummy: all
ZIP = tar ZIP = tar
BLITZ_VERSION = 1.0.2 NAME_TAR = blitz-1.0.2.tar.gz
NAME = blitz-1.0.2
NAME_TAR = blitz-$(BLITZ_VERSION).tar.gz
NAME = blitz-$(BLITZ_VERSION)
BLITZ_FOLDER=external/blitz
BLITZ_FOLDER=/external/blitz/
all: 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) $(ZIP) -xf $(NAME_TAR)
mkdir -p build mkdir -p build
mkdir -p build/include mkdir -p build/include
mkdir -p build/lib mkdir -p build/lib
cd $(NAME) && autoreconf -fiv && autoconf && automake --add-missing 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)
cd $(NAME) && $(MAKE) lib cd $(NAME) && $(MAKE) lib
cd $(NAME) && $(MAKE) install cd $(NAME) && $(MAKE) install
clean: clean:
-rm -rf $(HOMEBASE)/$(BLITZ_FOLDER)/$(NAME) -rm -rf $(HOMEBASE)$(BLITZ_FOLDER)blitz-1.0.2
-rm -rf $(HOMEBASE)/$(BLITZ_FOLDER)/build -rm -rf $(HOMEBASE)$(BLITZ_FOLDER)build
BIN
View File
Binary file not shown.
+6 -14
View File
@@ -4,29 +4,21 @@ dummy: all
ZIP = tar ZIP = tar
JANSSON_VERSION = 2.14 NAME_TAR = jansson-2.13.tar.gz
NAME = jansson-2.13
NAME = jansson-$(JANSSON_VERSION) JANSSON_FOLDER=/external/jansson/
NAME_TAR = $(NAME).tar.gz
JANSSON_FOLDER=external/jansson
all: 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) $(ZIP) -xf $(NAME_TAR)
mkdir -p build mkdir -p build
mkdir -p build/include mkdir -p build/include
mkdir -p build/lib mkdir -p build/lib
#cd $(NAME) && autoreconf -fiv && automake --add-missing #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)
cd $(NAME) && $(MAKE) install cd $(NAME) && $(MAKE) install
clean: clean:
-rm -rf $(HOMEBASE)/$(JANSSON_FOLDER)/$(NAME) -rm -rf $(HOMEBASE)$(JANSSON_FOLDER)$(NAME)
-rm -rf $(HOMEBASE)/$(JANSSON_FOLDER)/build -rm -rf $(HOMEBASE)$(JANSSON_FOLDER)build
BIN
View File
Binary file not shown.
-8
View File
@@ -9,17 +9,9 @@ class Hdf5Reader {
Hdf5Reader(std::string directory, std::string filename); Hdf5Reader(std::string directory, std::string filename);
Hdf5Reader(std::string absolute_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, 3> readD3Double(std::string path);
blitz::Array<double, 2> readD2Double(std::string path); blitz::Array<double, 2> readD2Double(std::string path);
blitz::Array<double, 1> readD1Double(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: private:
std::string absolute_filename_; std::string absolute_filename_;
-4
View File
@@ -14,9 +14,7 @@ class Hdf5Writer {
void write(const blitz::Array<double, 2>& data, std::string path); 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, 3>& data, std::string path);
void write(const blitz::Array<double, 4>& data, std::string path); void write(const blitz::Array<double, 4>& data, std::string path);
void write(const blitz::Array<double, 5>& data, std::string path);
void write(const blitz::Array<long int, 4>& data, std::string path); void write(const blitz::Array<long int, 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<double, 3>& data, std::string path);
void write(const blitz::TinyVector<int, 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); void write(const std::vector<double>& data, std::string path);
@@ -24,8 +22,6 @@ class Hdf5Writer {
void write(long int data, std::string path); void write(long int data, std::string path);
void write(double data, std::string path); void write(double data, std::string path);
void write(const std::string& 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: private:
std::string absolute_filename_; std::string absolute_filename_;
-44
View File
@@ -1,44 +0,0 @@
#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 */
+1 -8
View File
@@ -5,7 +5,6 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include <random>
#include "IO/hdf5_writer.h" #include "IO/hdf5_writer.h"
class DynamicDensityField; class DynamicDensityField;
@@ -36,7 +35,6 @@ class SimulationOutput {
void addCurrentBorderOutput(OutputTask task); void addCurrentBorderOutput(OutputTask task);
void addDeletionLoggerOutput(OutputTask task); void addDeletionLoggerOutput(OutputTask task);
void setPotentialOutput(OutputTask task); void setPotentialOutput(OutputTask task);
void setRestartInfoOutput(OutputTask task);
void writeMetaData( void writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
@@ -45,14 +43,13 @@ class SimulationOutput {
void writeSimulationData( void writeSimulationData(
int cpu_sync, int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, std::mt19937* engine); PoissonSolver* poisson_solver);
private: private:
std::vector<OutputTask> tasks_density_fields_; std::vector<OutputTask> tasks_density_fields_;
std::vector<OutputTask> tasks_current_collector_; std::vector<OutputTask> tasks_current_collector_;
std::vector<OutputTask> tasks_deletion_logger_; std::vector<OutputTask> tasks_deletion_logger_;
OutputTask task_potential_; OutputTask task_potential_;
OutputTask task_rng_;
Hdf5Writer writer; Hdf5Writer writer;
@@ -105,10 +102,6 @@ class SimulationOutput {
std::string path_to_field); std::string path_to_field);
void writeBinBorders(DynamicDensityField* density_field, void writeBinBorders(DynamicDensityField* density_field,
std::string path_to_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 */ #endif /* SIMULATION_OUTPUT_H */
-5
View File
@@ -10,11 +10,6 @@ static const double minimal_macroscopic_cross_section =
std::numeric_limits<double>::min() * 1E5; std::numeric_limits<double>::min() * 1E5;
static const double random_lower_limit = 1E-15; static const double random_lower_limit = 1E-15;
static const double compare_epsilon = 1E-10; 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 } // namespace SimConstants
-5
View File
@@ -19,11 +19,6 @@ EnergyBinning buildEnergyBinningIncludingRedirection(
Parameter& parameter, Parameter& parameter,
json_path& path_to_binning); json_path& path_to_binning);
PitchAngleBinning buildPitchAngleBinning(json_t* object);
PitchAngleBinning buildPitchAngleBinningIncludingRedirection(
Parameter& parameter,
json_path& path_to_binning);
}; // namespace generator }; // namespace generator
#endif /* BINNING_GENERATOR_H */ #endif /* BINNING_GENERATOR_H */
-15
View File
@@ -1,15 +0,0 @@
#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,7 +24,6 @@ struct TrackedSpeciesBuilderInfo {
std::shared_ptr<VelocityDistribution> velocity_distribution; std::shared_ptr<VelocityDistribution> velocity_distribution;
std::shared_ptr<DriftVelocity> drift_velocity; std::shared_ptr<DriftVelocity> drift_velocity;
std::shared_ptr<DynamicDensityField> last_sync_density_field; std::shared_ptr<DynamicDensityField> last_sync_density_field;
std::shared_ptr<DynamicDensityField> density_drawing_field;
double mass_kg; double mass_kg;
double charge_C; double charge_C;
+5 -3
View File
@@ -55,16 +55,16 @@ class PoissonSolver {
std::vector<std::shared_ptr<Electrode>> electrodes, std::vector<std::shared_ptr<Electrode>> electrodes,
double target_accuracy, double target_accuracy,
int num_cycles, int num_cycles,
int solver_intervall,
int solver_offset,
bool do_solver); bool do_solver);
void solvePotential(const blitz::Array<double, 3> charge_density, void solvePotential(const blitz::Array<double, 3> charge_density,
const bool solve); int cpu_sync);
blitz::Array<double, 3> potential(); blitz::Array<double, 3> potential();
std::shared_ptr<VectorField> staticElectricField(); std::shared_ptr<VectorField> staticElectricField();
const CylinderBinning* densityBinning(); const CylinderBinning* densityBinning();
void setPotential(blitz::Array<double, 3>& potential);
private: private:
GlobalBoundary bottom_boundary_; GlobalBoundary bottom_boundary_;
GlobalBoundary top_boundary_; GlobalBoundary top_boundary_;
@@ -74,6 +74,8 @@ class PoissonSolver {
const CylinderBinning density_binning_; const CylinderBinning density_binning_;
const double target_accuracy_; const double target_accuracy_;
const int num_cycles_; const int num_cycles_;
const int solver_intervall_;
const int solver_offset_;
const bool do_solver_; const bool do_solver_;
// density binning defined on the cell centers, potential defined // density binning defined on the cell centers, potential defined
+1 -1
View File
@@ -3,7 +3,7 @@
#include "constants/sim_constants.h" #include "constants/sim_constants.h"
inline bool isEqual(double a, double b) { bool isEqual(double a, double b) {
return std::abs(a - b) < SimConstants::compare_epsilon; return std::abs(a - b) < SimConstants::compare_epsilon;
} }
+6 -9
View File
@@ -21,13 +21,14 @@ class CpuSynchronizer {
void synchronize( void synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species, bool reset); tracked_species);
void synchronize(DynamicDensityField* field, void synchronize(DynamicDensityField* field,
DynamicDensityField* density_for_drawing, DynamicDensityField* last_sync_field);
bool reset); void synchronize(CurrentCollector* collector,
void synchronize(CurrentCollector* collector); CurrentCollector* last_sync_collector);
void synchronize(DeletionLogger* logger); void synchronize(DeletionLogger* logger,
DeletionLogger* last_sync_logger);
void synchronize(Timer* timer, Timer* last_sync_timer); void synchronize(Timer* timer, Timer* last_sync_timer);
@@ -36,14 +37,10 @@ class CpuSynchronizer {
*/ */
void sumToAll(blitz::Array<double, 4>& array, void sumToAll(blitz::Array<double, 4>& array,
blitz::Array<double, 4>& last_sync_array); blitz::Array<double, 4>& last_sync_array);
void sumToAll(blitz::Array<double, 5>& array,
blitz::Array<double, 5>& last_sync_array);
void sumToAll(blitz::Array<double, 3>& array, void sumToAll(blitz::Array<double, 3>& array,
blitz::Array<double, 3>& last_sync_array); blitz::Array<double, 3>& last_sync_array);
void sumToAll(blitz::Array<long int, 4>& array, void sumToAll(blitz::Array<long int, 4>& array,
blitz::Array<long int, 4>& last_sync_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(double& value, double& last_sync_value);
void sumToAll(long int& value, long int& last_sync_value); void sumToAll(long int& value, long int& last_sync_value);
}; };
+3 -17
View File
@@ -31,20 +31,15 @@ class CurrentCollector {
double physicalTime() const; double physicalTime() const;
void resetCurrentCollector();
friend class CpuSynchronizer; friend class CpuSynchronizer;
private: private:
void collectRadialMovement(const blitz::TinyVector<int, 3>& bin_old, 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, 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, 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( blitz::Array<double, 3> createAreaLongitudinal(
const CylinderBinning& position_binning); const CylinderBinning& position_binning);
@@ -70,15 +65,6 @@ class CurrentCollector {
blitz::Array<double, 3> r_negative_crossings; blitz::Array<double, 3> r_negative_crossings;
blitz::Array<double, 3> r_positive_crossings; blitz::Array<double, 3> r_positive_crossings;
blitz::Array<double, 3> sync_z_negative_crossings;
blitz::Array<double, 3> sync_z_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_r;
blitz::Array<double, 3> collector_areas_phi; blitz::Array<double, 3> collector_areas_phi;
blitz::Array<double, 3> collector_areas_z; blitz::Array<double, 3> collector_areas_z;
+22 -56
View File
@@ -2,9 +2,7 @@
#define DENSITY_FIELD_H #define DENSITY_FIELD_H
#include <memory> #include <memory>
#include <random>
#include "simulation/compare.h"
#include "simulation/coordinates.h" #include "simulation/coordinates.h"
#include "simulation/cpu_synchronizer.h" #include "simulation/cpu_synchronizer.h"
#include "simulation/energy_binning.h" #include "simulation/energy_binning.h"
@@ -20,19 +18,12 @@ class DensityField {
virtual double density(const Coordinate& position, double energy_eV) = 0; 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 { class DynamicDensityField : public DensityField {
public: public:
DynamicDensityField(const CylinderBinning& position_binning,
DynamicDensityField(const CylinderBinning& positionBinning,
const EnergyBinning& energy_binning, const EnergyBinning& energy_binning,
const PitchAngleBinning& pitch_angle_binning,
std::shared_ptr<Timer> timer); std::shared_ptr<Timer> timer);
double density(const Coordinate& position);
double density(const Coordinate& position, double energy_eV);
double density(const Coordinate& position, double energy_split, bool above);
bool changedPositionBin(const Coordinate& old_position, bool changedPositionBin(const Coordinate& old_position,
const Coordinate& new_position) const; const Coordinate& new_position) const;
@@ -40,77 +31,52 @@ class DynamicDensityField : public DensityField {
void logMovement(const Coordinate& position, void logMovement(const Coordinate& position,
double energy_eV, double energy_eV,
double pitch_angle,
double time_in_bin_s); double time_in_bin_s);
void logDeletion(const Coordinate& position, void logDeletion(const Coordinate& position, double energy_eV);
double energy_eV,
double pitch_angle);
// return the particle number stored in the density of this object double density(const Coordinate& position);
double particleNumber(); double density(const Coordinate& position, double energy_eV);
// return the particle number stored for energies higher than E_thresh
// (above = true) or for energies below (above = false)
// The energy bin, in which E_thresh is located, will be included in the
// 'above=true' case (and excluded in the other case)
double particleNumber(double E_thresh, bool above);
// 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, 3> densityArray();
blitz::Array<double, 4> spectrumArray(); blitz::Array<double, 4> spectrumArray();
blitz::Array<double, 5> timeInBinArray() const; blitz::Array<double, 4> timeInBinArray() const;
blitz::Array<long int, 5> deletedParticlesArray() const; blitz::Array<long int, 4> deletedParticlesArray() const;
blitz::Array<double, 3> binVolumeArray() const; blitz::Array<double, 3> binVolumeArray() const;
blitz::Array<double, 3> densityArray(double energy_split, bool above);
// return an array of the density values at the Coordinate position (only energy
// direction left); overbin is removed
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<double, 1> sliceTimeInBinArray(const Coordinate& position,
double energy_eV) const;
const EnergyBinning* energyBinning() const; const EnergyBinning* energyBinning() const;
const CylinderBinning* positionBinning() const; const CylinderBinning* positionBinning() const;
const PitchAngleBinning* pitchAngleBinning() const;
double physicalTime() const; double physicalTime() const;
double timeResolution() const;
void resetDynamicDensityField();
friend class CpuSynchronizer; 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: 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(); void recalculateDensityArray();
// use ordering r, phi, z, pitch_angle, E blitz::Array<double, 4> time_in_bin_s_;
blitz::Array<double, 5> time_in_bin_s_; blitz::Array<long int, 4> deleted_particles_;
blitz::Array<long int, 5> deleted_particles_;
blitz::Array<double, 5> sync_time_in_bin_s_;
blitz::Array<long int, 5> sync_deleted_particles_;
blitz::Array<double, 4> density_per_m3_; blitz::Array<double, 4> density_per_m3_;
blitz::Array<double, 3> bin_volume_m3_; blitz::Array<double, 3> bin_volume_m3_;
const CylinderBinning position_binning_; const CylinderBinning position_binning_;
const EnergyBinning energy_binning_; const EnergyBinning energy_binning_;
const PitchAngleBinning pitch_angle_binning_;
std::shared_ptr<Timer> timer_; std::shared_ptr<Timer> timer_;
bool timer_restarted_ = false;
}; };
class ConstantDensityField : public DensityField { class ConstantDensityField : public DensityField {
-18
View File
@@ -18,22 +18,4 @@ class EnergyBinning {
const std::vector<double> energy_bin_borders_; 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 */ #endif /* ENERGY_BINNING_H */
@@ -6,7 +6,6 @@
#include "simulation/coordinates.h" #include "simulation/coordinates.h"
#include "simulation/scalar_field.h" #include "simulation/scalar_field.h"
#include "simulation/density_field.h"
struct Limit { struct Limit {
Limit() : min(0), max(0){}; Limit() : min(0), max(0){};
@@ -15,9 +14,6 @@ struct Limit {
double max; 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 { class EventPositionDistribution {
public: public:
EventPositionDistribution(std::shared_ptr<ScalarField> mother_density, EventPositionDistribution(std::shared_ptr<ScalarField> mother_density,
@@ -37,37 +33,4 @@ class EventPositionDistribution {
std::uniform_real_distribution<double> density_values; std::uniform_real_distribution<double> density_values;
}; };
// Class to draw a position from the density provided by a pointer
// to a DynamicDensityField object
class PositionDistributionFromDensity {
public:
// Constructor taking a pointer to a DynamicDensityField object
PositionDistributionFromDensity(std::shared_ptr<DynamicDensityField> density);
// draw a position from the density provided at construction using the rejection method
CylinderCoordinate drawPosition(std::mt19937* engine);
CylinderCoordinate drawPosition(std::mt19937* engine, double energy_split, bool above);
// 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();
void setMaximumDensityAboveAndBelow(double energy_split);
private:
// variable storing the maximum value of the density
double maximum_density_ = 1.;
double maximum_density_below_ = 1.;
double maximum_density_above_ = 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 */ #endif /* EVENT_POSITION_DISTRIBUTION_H */
+2 -40
View File
@@ -10,8 +10,6 @@
class DriftVelocity; class DriftVelocity;
class VelocityDistribution; class VelocityDistribution;
class DynamicDensityField;
class MagneticField;
namespace particle { namespace particle {
class Particle; class Particle;
@@ -28,7 +26,6 @@ struct InjectorInfo {
public: public:
std::shared_ptr<species::TrackedSpecie> created_specie; std::shared_ptr<species::TrackedSpecie> created_specie;
std::shared_ptr<VelocityDistribution> creation_velocity_distribution; std::shared_ptr<VelocityDistribution> creation_velocity_distribution;
// int multiplicity;
}; };
class Injector { class Injector {
@@ -38,55 +35,20 @@ class Injector {
std::shared_ptr<EventPositionDistribution> position_distribution, std::shared_ptr<EventPositionDistribution> position_distribution,
std::shared_ptr<DriftVelocity> mother_drift_velocity); 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 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,
const double injection_time);
void initInjectionTimeDistribution(double delta_t);
double timePassed() const; double timePassed() const;
void fillParticleNumbers(std::shared_ptr<species::TrackedSpecie> specie);
double energySplit() const;
private: private:
std::vector<InjectorInfo> injector_infos_; std::vector<InjectorInfo> injector_infos_;
const double activity_; const double activity_;
double energySplit_;
std::map<std::string, std::vector<double>> particleNumbersMap_;
std::shared_ptr<EventPositionDistribution> position_distribution_; std::shared_ptr<EventPositionDistribution> position_distribution_;
std::shared_ptr<DriftVelocity> mother_drift_velocity_; std::shared_ptr<DriftVelocity> mother_drift_velocity_;
std::uniform_real_distribution<double> injection_time_distribution_;
particle::Particle rollNewParticle( particle::Particle rollNewParticle(
std::mt19937* engine, std::mt19937* engine,
const Coordinate& position, const Coordinate& position,
std::shared_ptr<species::TrackedSpecie> created_specie, 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);
particle::Particle drawNewDensityParticleAboveOrBelow(std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::shared_ptr<MagneticField> field,
const double weight,
const double injection_time,
const bool above);
}; };
#endif /* INJECTOR_H */ #endif /* INJECTOR_H */
-4
View File
@@ -38,14 +38,10 @@ inline int json_int(json_t* object, int default_value = 0) {
inline std::string json_string(json_t* object, std::string default_value = "") { inline std::string json_string(json_t* object, std::string default_value = "") {
if (object) { if (object) {
if (json_string_value(object)) {
return std::string(json_string_value(object)); return std::string(json_string_value(object));
} else { } else {
return default_value; return default_value;
} }
} else {
return default_value;
}
} }
inline bool json_bool(json_t* object, bool default_value = false) { inline bool json_bool(json_t* object, bool default_value = false) {
-3
View File
@@ -65,9 +65,6 @@ blitz::TinyVector<double, 3> velocityVector(
const blitz::TinyVector<double, 3>& random_unit_vector, const blitz::TinyVector<double, 3>& random_unit_vector,
double mass_kg); double mass_kg);
double cosPitchAngle(blitz::TinyVector<double, 3> vector1,
blitz::TinyVector<double, 3> vector2);
}; // namespace kinematic }; // namespace kinematic
#endif /* KINEMATIC_H */ #endif /* KINEMATIC_H */
-3
View File
@@ -23,13 +23,10 @@ class DeletionLogger {
void numDeletions(long int new_value, DeletionType type); void numDeletions(long int new_value, DeletionType type);
long int numDeletions(DeletionType type) const; long int numDeletions(DeletionType type) const;
void resetDeletionLogger();
friend class CpuSynchronizer; friend class CpuSynchronizer;
private: private:
std::map<DeletionType, long int> num_deletions; std::map<DeletionType, long int> num_deletions;
std::map<DeletionType, long int> sync_num_deletions;
}; };
#endif /* LOGGER_H */ #endif /* LOGGER_H */
+1 -3
View File
@@ -29,9 +29,7 @@ class BorisMover : public Mover {
void movementStep(particle::Particle* particle, void movementStep(particle::Particle* particle,
const blitz::TinyVector<double, 3>& electric_field, const blitz::TinyVector<double, 3>& electric_field,
const blitz::TinyVector<double, 3>& magnetic_field, const blitz::TinyVector<double, 3>& magnetic_field,
const blitz::TinyVector<double, 3>& gravity_field, double& moved_distance) const;
double& moved_distance,
double timestep) const;
}; };
class DriftMover : public Mover { class DriftMover : public Mover {
+1 -9
View File
@@ -14,9 +14,7 @@ class Particle {
// Vector* velocity); // Vector* velocity);
Particle(std::shared_ptr<species::TrackedSpecie> specie, Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position, const Coordinate& position,
const Vector& velocity, const Vector& velocity);
const double time_birth,
const double weight);
void position(const Coordinate& new_position); void position(const Coordinate& new_position);
CartesianCoordinate position() const; CartesianCoordinate position() const;
@@ -48,13 +46,7 @@ class Particle {
void resetTimeInBin(); void resetTimeInBin();
double timeInBin() const; double timeInBin() const;
long int ID() const;
double weight() const;
private: private:
double weight_;
CartesianVector velocity_; CartesianVector velocity_;
CartesianCoordinate position_; CartesianCoordinate position_;
+7 -19
View File
@@ -34,28 +34,18 @@ class Simulation {
void init(Parameter& parameter); void init(Parameter& parameter);
void start(); void start();
void finalize(); void finalize();
// cpu_syncs only included for debug purposes, e.g. only drawing decay particles void processEvents(int events);
// at the 0th timestep void processUntilTermination(particle::Particle& particle,
void processEvents(int events, const double beta_particle_weight); std::vector<particle::Particle>& particle_queue);
void processDensityEvents(int events, const double weight_factor);
void processUntilTermination(particle::Particle& particle);
private: private:
std::vector<particle::Particle> determineInjectedParticles(RandomNumbers* random, std::vector<particle::Particle> determineInjectedParticles(
const double beta_particle_weight); RandomNumbers* random);
std::vector<particle::Particle> determineInjectedDensityParticles(
RandomNumbers* random,
const double weight_factor,
const int current,
std::map<std::string, double>& particleNumbers);
double meanFreePath(particle::Particle& particle, RandomNumbers* random, double meanFreePath(particle::Particle& particle, RandomNumbers* random);
std::vector<double>& macroscopic_cross_sections_m);
interaction::InteractionOutput interact(particle::Particle& particle, interaction::InteractionOutput interact(particle::Particle& particle,
RandomNumbers* random, RandomNumbers* random);
std::vector<double>& macroscopic_cross_sections_m);
blitz::Array<double,3> chargedensity(); blitz::Array<double,3> chargedensity();
@@ -79,8 +69,6 @@ class Simulation {
std::shared_ptr<SimulationOutput> output_; std::shared_ptr<SimulationOutput> output_;
std::shared_ptr<CpuSynchronizer> cpu_synchronizer_; std::shared_ptr<CpuSynchronizer> cpu_synchronizer_;
std::vector<particle::Particle> queue_;
}; };
#endif /* SIMULATION_H */ #endif /* SIMULATION_H */
+14 -14
View File
@@ -18,8 +18,6 @@ class DeletionLogger;
class CurrentCollector; class CurrentCollector;
class VelocityDistribution; class VelocityDistribution;
class DriftVelocity; class DriftVelocity;
class PositionDistributionFromDensity;
class VelocityDistributionFromDensityField;
namespace interaction { namespace interaction {
class Interaction; class Interaction;
@@ -64,13 +62,14 @@ class TrackedSpecie : public Specie {
std::shared_ptr<DynamicDensityField> density_field, std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution, std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity, std::shared_ptr<DriftVelocity> drift_velocity,
std::shared_ptr<DynamicDensityField> density_for_drawing); std::shared_ptr<DynamicDensityField> last_sync_density_field);
DensityField* densityField(); DensityField* densityField();
VelocityDistribution* velocityDistibution(); VelocityDistribution* velocityDistibution();
DriftVelocity* driftVelocity(); DriftVelocity* driftVelocity();
DynamicDensityField* dynamicDensityField(); DynamicDensityField* dynamicDensityField();
DynamicDensityField* lastSyncDensityField();
Mover* mover(); Mover* mover();
Terminator* terminator(); Terminator* terminator();
Reflector* reflector(); Reflector* reflector();
@@ -78,19 +77,19 @@ class TrackedSpecie : public Specie {
DeletionLogger* deletionLogger(); DeletionLogger* deletionLogger();
void deletionLogger(std::shared_ptr<DeletionLogger> new_logger); void deletionLogger(std::shared_ptr<DeletionLogger> new_logger);
DynamicDensityField* densityForDrawing(); DeletionLogger* lastSyncDeletionLogger();
void lastSyncDeletionLogger(std::shared_ptr<DeletionLogger> new_logger);
CurrentCollector* currentCollector(); CurrentCollector* currentCollector();
void currentCollector(std::shared_ptr<CurrentCollector> new_collector); 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(); std::vector<std::shared_ptr<interaction::Interaction>> interactions();
void addInteraction(std::shared_ptr<interaction::Interaction> interaction); void addInteraction(std::shared_ptr<interaction::Interaction> interaction);
// getter for the raw pointer to the positionDistributionFromDensity object
PositionDistributionFromDensity* positionDistributionFromDensity();
// getter for the raw pointer to the VelocityDistributionFromDensityField object
VelocityDistributionFromDensityField* velocityDistributionFromDensityField();
private: private:
std::shared_ptr<DynamicDensityField> density_field_; std::shared_ptr<DynamicDensityField> density_field_;
std::shared_ptr<VelocityDistribution> velocity_distribution_; std::shared_ptr<VelocityDistribution> velocity_distribution_;
@@ -104,11 +103,12 @@ class TrackedSpecie : public Specie {
std::shared_ptr<CurrentCollector> current_collector_; std::shared_ptr<CurrentCollector> current_collector_;
std::vector<std::shared_ptr<interaction::Interaction>> interactions_; std::vector<std::shared_ptr<interaction::Interaction>> interactions_;
std::shared_ptr<DynamicDensityField> density_for_drawing_; // fields to store the date of the last synchronization
std::shared_ptr<PositionDistributionFromDensity> // (after a synchronization the last_sync field and the non-last_sync field
position_distribution_from_density_; // contain the same data)
std::shared_ptr<VelocityDistributionFromDensityField> std::shared_ptr<DynamicDensityField> last_sync_density_field_;
velocity_distribution_from_density_; std::shared_ptr<DeletionLogger> last_sync_deletion_logger_;
std::shared_ptr<CurrentCollector> last_sync_current_collector_;
}; };
class BackgroundSpecie : public Specie { class BackgroundSpecie : public Specie {
+1 -1
View File
@@ -4,7 +4,7 @@
#include "simulation/particle.h" #include "simulation/particle.h"
class Geometry; class Geometry;
class DynamicDensityField;
class Terminator { class Terminator {
public: public:
Terminator(long int max_interactions, Terminator(long int max_interactions,
-4
View File
@@ -10,13 +10,9 @@ class Timer {
double time() const; double time() const;
void increaseTimestep(double time_s); void increaseTimestep(double time_s);
void setTime(double time_s); void setTime(double time_s);
void resetTime();
void setDeltaT(double deltaT);
double getDeltaT() const;
private: private:
double current_time_s_; double current_time_s_;
double delta_t_time_resolution_;
}; };
#endif /* TIMER_H */ #endif /* TIMER_H */
+10 -55
View File
@@ -25,67 +25,22 @@ class VelocityDistributionFromFunction : public VelocityDistribution {
std::shared_ptr<VelocityDistributionFunction> fv_; std::shared_ptr<VelocityDistributionFunction> fv_;
}; };
// only applicable to TrackedSpecies (i.e. only for DynamicDensityFields) /*
// other density don't have any information about the velocity direction
class DynamicDensityField; todo: implement this for direct interactions of simulated particles
class MagneticField;
class DensityField;
// Class to draw a velocity from the pitch angle resolved density
class VelocityDistributionFromDensityField : public VelocityDistribution { class VelocityDistributionFromDensityField : public VelocityDistribution {
public: 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( VelocityDistributionFromDensityField(
std::shared_ptr<DynamicDensityField> density_field, double mass_kg); std::shared_ptr<DensityField> density_field);
// 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 driftVelocity_ms(const CylinderVector& position);
CartesianVector rollVelocity_ms(
// returns a velocity vector drawn from the energy and pitch angle distributions const CylinderVector& position, std::mt19937* engine);
// 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);
// 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
// draw from the distribution below the threshold energy if above = false
// and from above otherwise
CartesianVector rollVelocity(
const Coordinate& position, std::mt19937* engine,
std::shared_ptr<MagneticField> magnetic_field,
const int E_th_bin,
const bool above);
CartesianVector rollVelocity(
const Coordinate& position, std::mt19937* engine,
const int E_th_bin,
const bool above);
private: private:
// mass of the species of which the density field is a part of std::shared_ptr<DensityField> density_field_;
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 */ #endif /* VELOCITY_DISTRIBUTION_H */
+7 -1
View File
@@ -81,7 +81,7 @@ TARGET_TEST=$(BIN_DIR)/karl_test
# Compile logic # Compile logic
all: blitz jansson karl all: blitz hdf5 jansson karl
check_homebase: check_homebase:
ifeq ($(HOMEBASE),) ifeq ($(HOMEBASE),)
@@ -99,6 +99,12 @@ endif
blitz: check_homebase blitz: check_homebase
ifeq ($(MAKE_BLITZ), true) ifeq ($(MAKE_BLITZ), true)
$(MAKE) -C external/blitz $(MAKE) -C external/blitz
$(MAKE) -C external/blitz install
endif
hdf5: check_homebase
ifeq ($(MAKE_H5), true)
$(MAKE) -C external/h5
endif endif
jansson: check_homebase jansson: check_homebase
+7
View File
@@ -54,6 +54,13 @@
"yValuesKey": "/vz(ms)", "yValuesKey": "/vz(ms)",
"prefactor": 1 "prefactor": 1
} }
},
"f5": {
"Exponential": {
"scale": -1,
"prefactor": 1,
"comment": "f5 = prefactor*exp(scale*x)"
}
} }
}, },
"3dto1D examples": { "3dto1D examples": {
@@ -1,912 +0,0 @@
{
"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
}
}
+12 -4
View File
@@ -568,6 +568,15 @@
} }
} }
} }
},
"GradientField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 2.5
}
}
}
} }
}, },
"GravityField": { "GravityField": {
@@ -616,7 +625,8 @@
"TargetAccuracy": 1e-7, "TargetAccuracy": 1e-7,
"NumCycles": 2e4, "NumCycles": 2e4,
"Intervall": 1, "Intervall": 1,
"Offset": 9 "Offset": 9,
"DoSolver": "true"
}, },
"Simulation": { "Simulation": {
"SimulatedEvents": 1, "SimulatedEvents": 1,
@@ -639,9 +649,7 @@
"OverwriteLast": "true" "OverwriteLast": "true"
}, },
"DeletionLogger": { "DeletionLogger": {
"Species": [ "Species": "all",
"all"
],
"Intervall": "EachSync", "Intervall": "EachSync",
"OverwriteLast": "true" "OverwriteLast": "true"
}, },
+28 -2
View File
@@ -565,6 +565,15 @@
} }
} }
} }
},
"GradientField": {
"VectorFieldFunctionInZ": {
"zFunction": {
"Constant3D": {
"constant": 0
}
}
}
} }
}, },
"PoissonSolver": { "PoissonSolver": {
@@ -585,13 +594,30 @@
"GlobalPositionBinning" "GlobalPositionBinning"
] ]
}, },
"Boundary": {
"Top": {
"type": "neumann",
"value": 0
},
"Bottom": {
"type": "dirichlet",
"value": 0
},
"Hull": {
"type": "dirichlet",
"value": 0
}
},
"TargetAccuracy": 1e-7, "TargetAccuracy": 1e-7,
"NumCycles": 2e4 "NumCycles": 2e4,
"Intervall": 1,
"Offset": 0
}, },
"Simulation": { "Simulation": {
"SimulatedEvents": 1, "SimulatedEvents": 1,
"EventStride": 1, "EventStride": 1,
"PoissonOffset": 0 "PoissonOffset": 0,
"DoSolver": "false"
}, },
"Output": { "Output": {
"folder": "output", "folder": "output",
-536
View File
@@ -1,536 +0,0 @@
{
"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
}
}
-226
View File
@@ -4,7 +4,6 @@
#include <hdf5_hl.h> #include <hdf5_hl.h>
#include "simulation/errors.h" #include "simulation/errors.h"
#include "constants/sim_constants.h"
Hdf5Reader::Hdf5Reader(std::string directory, std::string filename) Hdf5Reader::Hdf5Reader(std::string directory, std::string filename)
: absolute_filename_((directory + "/" + filename + ".h5").c_str()) {} : absolute_filename_((directory + "/" + filename + ".h5").c_str()) {}
@@ -101,228 +100,3 @@ blitz::Array<double, 1> Hdf5Reader::readD1Double(std::string path) {
H5Fclose(file); H5Fclose(file);
return data.copy(); 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));
}
DEBUG_LEVEL_3("RestartInfo: " + std::to_string(H5Tdetect_class(dtype, H5T_STRING)));
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);
}
DEBUG_LEVEL_3(std::to_string(ndims));
DEBUG_LEVEL_3("RestartInfo: " + std::to_string(size));
H5Sget_simple_extent_dims(dataspace, dims, NULL);
char data[SimConstants::engine_string_length_max];
H5Dread(dataset, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT,
&data);
std::stringstream temp;
temp << 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);
DEBUG_LEVEL_3("RestartInfo: read length from file: " + std::to_string(length));
H5Sclose(dataspace);
H5Dclose(dataset);
H5Fclose(file);
out << temp.str().substr(0, length);
DEBUG_LEVEL_3(std::to_string(out.str().size()));
return out;
}
-178
View File
@@ -4,8 +4,6 @@
#include <hdf5_hl.h> #include <hdf5_hl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <iostream> #include <iostream>
#include "simulation/errors.h"
#include "constants/sim_constants.h"
#include "simulation/mpi_communication.h" #include "simulation/mpi_communication.h"
@@ -23,7 +21,6 @@ void Hdf5Writer::createFile(std::string absolute_filename) {
if (MpiCommunication::mpi_rank == 0) { if (MpiCommunication::mpi_rank == 0) {
hid_t file = H5Fcreate(absolute_filename.c_str(), H5F_ACC_TRUNC, hid_t file = H5Fcreate(absolute_filename.c_str(), H5F_ACC_TRUNC,
H5P_DEFAULT, H5P_DEFAULT); H5P_DEFAULT, H5P_DEFAULT);
H5Fclose(file);
} }
} }
@@ -165,38 +162,6 @@ void Hdf5Writer::write(const blitz::Array<double, 4>& data, std::string path) {
H5Fclose(file); H5Fclose(file);
} }
void Hdf5Writer::write(const blitz::Array<double, 5>& data, std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
blitz::TinyVector<int, 5> size = data.extent();
blitz::TinyVector<int, 5> start(0, 0, 0, 0, 0);
hid_t filespace =
H5Screate_simple(5, blitz::TinyVector<hsize_t, 5>(size).data(), NULL);
hid_t lcpl = H5Pcreate(H5P_LINK_CREATE);
H5Pset_create_intermediate_group(lcpl, 1);
// turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL);
hid_t dataset;
dataset = H5Dopen2(file, path.c_str(), H5P_DEFAULT);
if (dataset < 0) {
dataset = H5Dcreate2(file, path.c_str(), H5T_NATIVE_DOUBLE, filespace, lcpl,
H5P_DEFAULT, H5P_DEFAULT);
}
// turn error report back onby hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, H5E_DEFAULT, H5E_DEFAULT);
H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, filespace, H5P_DEFAULT,
data.data());
H5Dclose(dataset);
H5Pclose(lcpl);
H5Sclose(filespace);
H5Fclose(file);
}
void Hdf5Writer::write(const blitz::Array<long int, 4>& data, void Hdf5Writer::write(const blitz::Array<long int, 4>& data,
std::string path) { std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
@@ -230,39 +195,6 @@ void Hdf5Writer::write(const blitz::Array<long int, 4>& data,
H5Fclose(file); 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, void Hdf5Writer::write(const blitz::TinyVector<double, 3>& data,
std::string path) { std::string path) {
hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); hid_t file = H5Fopen(absolute_filename_.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
@@ -455,8 +387,6 @@ void Hdf5Writer::write(const std::string& data, std::string path) {
hid_t dtype; hid_t dtype;
dtype = H5Tcreate(H5T_STRING, data.size()); 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 // turn of error report by hdf5 because of check H5Dopen2
H5Eset_auto(H5E_DEFAULT, NULL, NULL); H5Eset_auto(H5E_DEFAULT, NULL, NULL);
@@ -472,115 +402,7 @@ void Hdf5Writer::write(const std::string& data, std::string path) {
H5Dwrite(dataset, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data.c_str()); H5Dwrite(dataset, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data.c_str());
H5Dclose(dataset); H5Dclose(dataset);
H5Tclose(dtype);
H5Pclose(lcpl); H5Pclose(lcpl);
H5Sclose(filespace); H5Sclose(filespace);
H5Fclose(file); 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);
DEBUG_LEVEL_3(path);
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) {
DEBUG_LEVEL_3("Dataset could not be created");
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) {
DEBUG_LEVEL_3("Dataset could not be created");
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_;
}
-136
View File
@@ -1,136 +0,0 @@
#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"
#include "constants/ionization_constants.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;
}
DEBUG_LEVEL_1("Restarting rng");
restartRandomNumbers(random_numbers);
DEBUG_LEVEL_1("Restarting poisson solver.");
restartPoissonSolver(poisson_solver);
DEBUG_LEVEL_1("Restarting timer.");
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();
// ist nicht gut so, weils von der injector version entkoppelt ist...
// muss noch irgendwie geändert werden
pair.second->positionDistributionFromDensity()
->setMaximumDensityAboveAndBelow(
ionization::ionization_energy_janev_atomic);
}
}
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";
DEBUG_LEVEL_3(path);
// 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";
DEBUG_LEVEL_3(path);
// 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";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<double, 5> time_in_bin = reader_.readD5Double(path_to_data);
field->restartTimeInBin(time_in_bin);
}
// restart deleted particles
{
std::string path_to_data = path + "/DeletedParticles";
DEBUG_LEVEL_3(path_to_data);
blitz::Array<long int, 5> deleted_particles = reader_.readD5LongInt(path_to_data);
field->restartDeletedParticlesArray(deleted_particles);
}
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/";
DEBUG_LEVEL_3(path);
blitz::Array<double, 3> potential = reader_.readD3Double(path);
solver->setPotential(potential);
}
+1 -93
View File
@@ -1,4 +1,3 @@
#include "mpi.h"
#include "IO/simulation_output.h" #include "IO/simulation_output.h"
#include "IO/hdf5_writer.h" #include "IO/hdf5_writer.h"
@@ -30,10 +29,6 @@ void SimulationOutput::setPotentialOutput(OutputTask task) {
task_potential_ = task; task_potential_ = task;
} }
void SimulationOutput::setRestartInfoOutput(OutputTask task) {
task_rng_ = task;
}
void SimulationOutput::writeMetaData( void SimulationOutput::writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
const std::shared_ptr<PoissonSolver>& poisson_solver) { const std::shared_ptr<PoissonSolver>& poisson_solver) {
@@ -58,19 +53,12 @@ void SimulationOutput::writeMetaData(
std::string specie_path = "/" + task_potential_.specie_name; std::string specie_path = "/" + task_potential_.specie_name;
writeMetaData(poisson_solver.get(), specie_path); 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( void SimulationOutput::writeSimulationData(
int cpu_sync, int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species, std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, PoissonSolver* poisson_solver) {
std::mt19937* engine) {
if (MpiCommunication::mpi_rank == 0) { if (MpiCommunication::mpi_rank == 0) {
DEBUG_LEVEL_2("Write density field data."); DEBUG_LEVEL_2("Write density field data.");
for (auto& task : tasks_density_fields_) { for (auto& task : tasks_density_fields_) {
@@ -103,12 +91,6 @@ void SimulationOutput::writeSimulationData(
task_potential_.overwrite_last); 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, void SimulationOutput::writeSimulationData(DynamicDensityField* density_field,
@@ -177,26 +159,6 @@ void SimulationOutput::writeSimulationData(PoissonSolver* poisson_solver,
writePotential(poisson_solver, path); 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_";
}
DEBUG_LEVEL_3(path_base);
DEBUG_LEVEL_3("Write restart info.");
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, void SimulationOutput::writeNumDeletions(DeletionLogger* logger,
std::string path) { std::string path) {
std::string path_to_deletions = path + "/NumDeletions"; std::string path_to_deletions = path + "/NumDeletions";
@@ -256,23 +218,19 @@ void SimulationOutput::writeDensity(DynamicDensityField* density_field,
std::string path) { std::string path) {
writer.write(density_field->densityArray(), path + "/Density"); writer.write(density_field->densityArray(), path + "/Density");
} }
void SimulationOutput::writeTimeInBin(DynamicDensityField* density_field, void SimulationOutput::writeTimeInBin(DynamicDensityField* density_field,
std::string path) { std::string path) {
writer.write(density_field->timeInBinArray(), path + "/TimeInBin"); writer.write(density_field->timeInBinArray(), path + "/TimeInBin");
} }
void SimulationOutput::writeDeletedParticles(DynamicDensityField* density_field, void SimulationOutput::writeDeletedParticles(DynamicDensityField* density_field,
std::string path) { std::string path) {
writer.write(density_field->deletedParticlesArray(), writer.write(density_field->deletedParticlesArray(),
path + "/DeletedParticles"); path + "/DeletedParticles");
} }
void SimulationOutput::writePhysicalTime(DynamicDensityField* density_field, void SimulationOutput::writePhysicalTime(DynamicDensityField* density_field,
std::string path) { std::string path) {
writer.write(density_field->physicalTime(), path + "/PhysicalTime"); writer.write(density_field->physicalTime(), path + "/PhysicalTime");
} }
void SimulationOutput::writePotential(PoissonSolver* poisson_solver, std::string path) { void SimulationOutput::writePotential(PoissonSolver* poisson_solver, std::string path) {
writer.write(poisson_solver->potential(), path + "/Potential"); writer.write(poisson_solver->potential(), path + "/Potential");
} }
@@ -284,7 +242,6 @@ void SimulationOutput::writeMetaData(species::TrackedSpecie* specie) {
writer.write(specie->charge_C(), specie_path + "/Charge"); writer.write(specie->charge_C(), specie_path + "/Charge");
} }
/*
void SimulationOutput::writeMetaData(DynamicDensityField* density_field, void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
std::string path) { std::string path) {
std::string path_to_field = path + "/DensityField"; std::string path_to_field = path + "/DensityField";
@@ -293,55 +250,6 @@ void SimulationOutput::writeMetaData(DynamicDensityField* density_field,
writeBinBorders(density_field, path_to_field); writeBinBorders(density_field, path_to_field);
writeNumBins(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, void SimulationOutput::writeMetaData(CurrentCollector* current_collector,
std::string path) { std::string path) {
-36
View File
@@ -118,40 +118,4 @@ EnergyBinning buildEnergyBinningIncludingRedirection(
} }
} }
PitchAngleBinning buildPitchAngleBinning(json_t* object) {
std::string pitch_angle_type = json_string(json_object_by_path(object, {"Type"}));
if (pitch_angle_type == "Linear") {
DEBUG_LEVEL_2("Creating pitch angle binning: linear.");
int number_of_bins =
json_int(json_object_by_path(object, {"NumberOfBins"}));
ASSERT_POSITIVE(&number_of_bins, "Number of Bins must be positive");
DEBUG_LEVEL_3("with number of bins: " + std::to_string(number_of_bins));
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"}))) {
DEBUG_LEVEL_2("Creating energy binning: CreateSameAs.");
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 << " ";
}
DEBUG_LEVEL_3("From path: " + path.str());
return buildPitchAngleBinningIncludingRedirection(parameter, path_to_same);
} else {
return buildPitchAngleBinning(parameter.jsonObjectFromBase(path_to_binning));
}
}
}; // namespace generator }; // namespace generator
+2 -9
View File
@@ -21,8 +21,7 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
Parameter& parameter, Parameter& parameter,
const json_path& path_to_field, const json_path& path_to_field,
std::shared_ptr<Timer>& timer) { std::shared_ptr<Timer>& timer) {
DEBUG_LEVEL_2("Creating dynamic density field.");
DEBUG_LEVEL_2("Creating dynamic density field with pitch angle.");
json_path path_binning = json_path_append(path_to_field, {"PositionBinning"}); json_path path_binning = json_path_append(path_to_field, {"PositionBinning"});
CylinderBinning position_binning = CylinderBinning position_binning =
buildPositionBinningIncludingRedirection(parameter, path_binning); buildPositionBinningIncludingRedirection(parameter, path_binning);
@@ -30,14 +29,8 @@ std::shared_ptr<DynamicDensityField> buildDynamicDensityField(
json_path_append(path_to_field, {"EnergyBinning"}); json_path_append(path_to_field, {"EnergyBinning"});
EnergyBinning energy_binning = EnergyBinning energy_binning =
buildEnergyBinningIncludingRedirection(parameter, path_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>( return std::shared_ptr<DynamicDensityField>(
new DynamicDensityField(position_binning, energy_binning, new DynamicDensityField(position_binning, energy_binning, timer));
pitch_angle_binning, timer));
} }
}; // namespace generator }; // namespace generator
@@ -11,15 +11,8 @@ std::shared_ptr<GravityField> gravityField(json_t* object) {
} }
std::shared_ptr<GravityField> gravityField(Parameter& parameter) { std::shared_ptr<GravityField> gravityField(Parameter& parameter) {
if(json_object_by_path(parameter.jsonFile(), {"GravityField"})) {
return gravityField( return gravityField(
json_object_by_path(parameter.jsonFile(), {"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))))));
}
} }
}; };
-4
View File
@@ -33,10 +33,6 @@ std::shared_ptr<Injector> buildInjector(
parameter, parameter,
json_path_append(path_to_injector, {"CreatedSpecies", std::string(key), json_path_append(path_to_injector, {"CreatedSpecies", std::string(key),
"CreationVelocityDistribution"})); "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); injector_infos.push_back(info);
} }
+1 -1
View File
@@ -33,7 +33,7 @@ double buildMass(json_t* object) {
} else if (json_object_by_path(object, {"value"})) { } else if (json_object_by_path(object, {"value"})) {
return json_double(json_object_by_path(object, {"value"})); return json_double(json_object_by_path(object, {"value"}));
} else { } else {
ERROR("The mass is not given correcty."); ERROR("The mass is not given correctly.");
return 0.; return 0.;
} }
} }
+18 -3
View File
@@ -30,6 +30,20 @@ namespace generator {
auto boundaries = buildBoundaries(parameter, {"PoissonSolver", "Boundary"}); 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{}; std::vector<std::shared_ptr<Electrode>> electrodes{};
double target_accuracy = parameter.doubleValue( double target_accuracy = parameter.doubleValue(
@@ -38,12 +52,13 @@ namespace generator {
int num_cycles = parameter.intValue(json_path_append({"PoissonSolver"}, int num_cycles = parameter.intValue(json_path_append({"PoissonSolver"},
{"NumCycles"})); {"NumCycles"}));
bool do_solver = parameter.boolValue( bool do_solver = parameter.boolValue(json_path_append({"PoissonSolver"},
json_path_append({"PoissonSolver"}, {"DoSolver"}), false); {"DoSolver"}), true);
return std::shared_ptr<PoissonSolver>(new PoissonSolver(boundaries.at("Bottom"), return std::shared_ptr<PoissonSolver>(new PoissonSolver(boundaries.at("Bottom"),
boundaries.at("Top"), boundaries.at("Hull"), geometry, position_binning, boundaries.at("Top"), boundaries.at("Hull"), geometry, position_binning,
electrodes, target_accuracy, num_cycles, do_solver)); electrodes, target_accuracy, num_cycles, solver_intervall, solver_offset,
do_solver));
} }
std::map<std::string, GlobalBoundary> buildBoundaries(Parameter& parameter, std::map<std::string, GlobalBoundary> buildBoundaries(Parameter& parameter,
-39
View File
@@ -1,39 +0,0 @@
#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) {
DEBUG_LEVEL_0("No Restart desired.");
return Restart(false, "", "");
}
std::string filepath = readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}))
+ ".h5";
DEBUG_LEVEL_3("Restart: file path:" + filepath);
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);
}
DEBUG_LEVEL_3("Restart: SyncPeriod to be started from: " + identifier);
return Restart(do_restart, filepath, identifier);
}
Restart buildRestart(Parameter& parameter) {
return buildRestart(
json_object_by_path(parameter.jsonFile(), {"Restart"}));
}
} // namespace generator
+1 -24
View File
@@ -143,7 +143,7 @@ std::shared_ptr<SimulationOutput> buildSimulationOutput(
intervall = 1; intervall = 1;
} }
ASSERT_POSITIVE(&intervall, ASSERT_POSITIVE(&intervall,
"The intervall for the poisson solver output must be positive"); "The output intervall for the poisson solver output must be positive.");
bool overwrite_last = json_bool( bool overwrite_last = json_bool(
json_object_by_path(object, {"PoissonSolver", "OverwriteLast"})); json_object_by_path(object, {"PoissonSolver", "OverwriteLast"}));
@@ -153,29 +153,6 @@ std::shared_ptr<SimulationOutput> buildSimulationOutput(
output->setPotentialOutput(task); 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");
DEBUG_LEVEL_3("Restart output interval: " + std::to_string(intervall));
bool overwrite_last = json_bool(
json_object_by_path(object, {"RestartInfo", "OverwriteLast"}));
OutputTask task = {"RestartInfo", overwrite_last, intervall};
output->setRestartInfoOutput(task);
}
return output; return output;
} }
+15 -7
View File
@@ -250,7 +250,6 @@ void SpeciesBuilder::fillReflector(Parameter& parameter) {
} }
} }
// TBD: Fill and create dynamic density fields with pitch angle distribution
void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) { void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
DEBUG_LEVEL_2("Fill tracked density."); DEBUG_LEVEL_2("Fill tracked density.");
for (auto& b : tracked_species_info) { for (auto& b : tracked_species_info) {
@@ -260,12 +259,11 @@ void SpeciesBuilder::fillTrackedDensity(Parameter& parameter) {
{"DensityField", "DynamicDensityField"}), {"DensityField", "DynamicDensityField"}),
timer_); timer_);
// not the optimal solution! (has to be optimized) b.second.last_sync_density_field = buildDynamicDensityField(
b.second.density_drawing_field = buildDynamicDensityField(
parameter, parameter,
json_path_append(b.second.path_in_json, json_path_append(b.second.path_in_json,
{"DensityField", "DynamicDensityField"}), {"DensityField", "DynamicDensityField"}),
timer_); last_sync_timer_);
} }
} }
@@ -285,7 +283,7 @@ void SpeciesBuilder::buildSpecies() {
b.second.type, b.second.name, b.second.mass_kg, b.second.charge_C, b.second.type, b.second.name, b.second.mass_kg, b.second.charge_C,
b.second.mover, b.second.terminator, b.second.reflector, b.second.mover, b.second.terminator, b.second.reflector,
b.second.density_field, b.second.velocity_distribution, b.second.density_field, b.second.velocity_distribution,
b.second.drift_velocity, b.second.density_drawing_field)); b.second.drift_velocity, b.second.last_sync_density_field));
} }
} }
@@ -297,7 +295,15 @@ void SpeciesBuilder::fillCurrentCollector(Parameter& parameter) {
json_path_append(tracked_species_info.at(b.first).path_in_json, json_path_append(tracked_species_info.at(b.first).path_in_json,
{"CurrentCollector"}), {"CurrentCollector"}),
timer_); 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->currentCollector(current_collector);
b.second->lastSyncCurrentCollector(last_sync_current_collector);
} }
} }
@@ -309,6 +315,8 @@ void SpeciesBuilder::fillLoggers(Parameter& parameter) {
json_path_append(tracked_species_info.at(b.first).path_in_json, json_path_append(tracked_species_info.at(b.first).path_in_json,
{"Loggers"})); {"Loggers"}));
b.second->deletionLogger(deletion_logger); b.second->deletionLogger(deletion_logger);
b.second->lastSyncDeletionLogger(
std::make_shared<DeletionLogger>(*deletion_logger));
} }
} }
@@ -317,8 +325,8 @@ void SpeciesBuilder::fillInteractions(Parameter& parameter) {
for (auto& b : tracked_species) { for (auto& b : tracked_species) {
json_path path = tracked_species_info[b.first].path_in_json; json_path path = tracked_species_info[b.first].path_in_json;
path = json_path_append(path, {"Interactions"}); path = json_path_append(path, {"Interactions"});
addInteractions(b.second, tracked_species, background_species, addInteractions(b.second, tracked_species, background_species, parameter,
parameter, path); path);
} }
} }
+3 -1
View File
@@ -20,7 +20,7 @@ std::string readAbsoluteFilename(json_t* object) {
json_string(json_object_by_path(object, {"Filename"})); json_string(json_object_by_path(object, {"Filename"}));
return homebase + "/" + relative_path_to_homebase + "/" + filename; return homebase + "/" + relative_path_to_homebase + "/" + filename;
} else if (path_type == "AbsolutePath") { } else if (path_type == "AbsolutPath") {
std::string absolute_path = std::string absolute_path =
json_string(json_object_by_path(object, {"AbsoluteFolderPath"})); json_string(json_object_by_path(object, {"AbsoluteFolderPath"}));
std::string filename = std::string filename =
@@ -44,8 +44,10 @@ blitz::Array<double, 3> readFromFile(json_t* object) {
blitz::Array<double, 3> readComponentFromFile(json_t* object, int component) { blitz::Array<double, 3> readComponentFromFile(json_t* object, int component) {
std::string absolute_filename = std::string absolute_filename =
readAbsoluteFilename(json_object_by_path(object, {"PathToH5"})); readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}));
DEBUG_LEVEL_3("path to h5: " + absolute_filename);
std::string key = json_string( std::string key = json_string(
json_array_get(json_object_by_path(object, {"Keys"}), component)); json_array_get(json_object_by_path(object, {"Keys"}), component));
DEBUG_LEVEL_3("key: " + key);
Hdf5Reader reader(absolute_filename); Hdf5Reader reader(absolute_filename);
return reader.readD3Double(key); return reader.readD3Double(key);
+1 -4
View File
@@ -30,10 +30,7 @@ InteractionOutput ClusterFormation::performInteraction(
const blitz::TinyVector<double, 3> v_cluster = const blitz::TinyVector<double, 3> v_cluster =
kinematic::velocity(energy_eV, product_->mass_kg()) * kinematic::velocity(energy_eV, product_->mass_kg()) *
v_target / kinematic::norm(v_target); v_target / kinematic::norm(v_target);
// product inherits weight of the main particle (not the target, which is particle::Particle cluster(product_, x_impact, CartesianVector(v_cluster));
// 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; InteractionOutput output;
output.add(cluster); output.add(cluster);
+2 -8
View File
@@ -93,16 +93,10 @@ InteractionOutput ElectronIonization::performInteraction(
particle.velocity(v_impact_new); particle.velocity(v_impact_new);
const double time_birth = particle.timeAlive();
const double weight_parent = particle.weight();
InteractionOutput output; InteractionOutput output;
output.add( output.add(
particle::Particle(electron_, x_impact, CartesianVector(v_ejected), particle::Particle(electron_, x_impact, CartesianVector(v_ejected)));
time_birth, weight_parent)); output.add(particle::Particle(ion_, x_impact, CartesianVector(v_target)));
output.add(particle::Particle(ion_, x_impact, CartesianVector(v_target),
time_birth, weight_parent));
return output; return output;
} }
+1 -30
View File
@@ -6,7 +6,6 @@
#include "simulation/kinematic.h" #include "simulation/kinematic.h"
#include "constants/physical_constants.h" #include "constants/physical_constants.h"
#include "simulation/drift_velocity.h" #include "simulation/drift_velocity.h"
#include "simulation/electromagnetic_field.h"
namespace interaction { namespace interaction {
@@ -79,36 +78,8 @@ InteractionOutput Recombination::performInteraction(
const double energy_eV = (energyBinBorders[energy_bin] + const double energy_eV = (energyBinBorders[energy_bin] +
energyBinBorders[energy_bin+1]) / 2.; energyBinBorders[energy_bin+1]) / 2.;
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(), recombination_target_->dynamicDensityField()->logDeletion(particle.position(),
energy_eV, mu); energy_eV);
InteractionOutput output; InteractionOutput output;
output.deleteCurrentParticle(true); output.deleteCurrentParticle(true);
+9 -30
View File
@@ -16,6 +16,8 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
std::vector<std::shared_ptr<Electrode>> electrodes, std::vector<std::shared_ptr<Electrode>> electrodes,
double target_accuracy, double target_accuracy,
int num_cycles, int num_cycles,
int solver_intervall,
int solver_offset,
bool do_solver) bool do_solver)
: bottom_boundary_(bottom_boundary), : bottom_boundary_(bottom_boundary),
top_boundary_(top_boundary), top_boundary_(top_boundary),
@@ -32,6 +34,8 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
electrodes_(electrodes), electrodes_(electrodes),
target_accuracy_(target_accuracy), target_accuracy_(target_accuracy),
num_cycles_(num_cycles), num_cycles_(num_cycles),
solver_intervall_(solver_intervall),
solver_offset_(solver_offset),
do_solver_(do_solver) { do_solver_(do_solver) {
blitz::TinyVector<double, 3> stepsize = density_binning_.stepsize(); blitz::TinyVector<double, 3> stepsize = density_binning_.stepsize();
@@ -77,12 +81,13 @@ PoissonSolver::PoissonSolver(GlobalBoundary bottom_boundary,
blitz::Range(density_binning.binIndexMin()(2), blitz::Range(density_binning.binIndexMin()(2),
density_binning.binIndexMax()(2))); density_binning.binIndexMax()(2)));
zero_chargedensity = 0.; zero_chargedensity = 0.;
solvePotential(zero_chargedensity, true); solvePotential(zero_chargedensity, 0);
} }
void PoissonSolver::solvePotential( void PoissonSolver::solvePotential(
const blitz::Array<double, 3> charge_density, const bool solve) { const blitz::Array<double, 3> charge_density, int cpu_sync) {
if (!(do_solver_) || !(solve)) { if ((!do_solver_) || ((cpu_sync % solver_intervall_ != 0) || ((cpu_sync <= solver_offset_)
&& (cpu_sync > 0)))) {
return; return;
} }
DEBUG_LEVEL_3("Interpolating chargedensity."); DEBUG_LEVEL_3("Interpolating chargedensity.");
@@ -240,7 +245,7 @@ bool PoissonSolver::converged(
double normalized_maximum = double normalized_maximum =
maximum_difference*SI::eps0/(fabs(blitz::max(interpolated_density)) + 1e-12); maximum_difference*SI::eps0/(fabs(blitz::max(interpolated_density)) + 1e-12);
std::ostringstream message; std::ostringstream message;
message << "Maximum Difference normalized by order of magnitude: " message << "Maximum Differenece normalized by order of magnitude: "
<< normalized_difference; << normalized_difference;
DEBUG_LEVEL_0(message.str()); DEBUG_LEVEL_0(message.str());
return normalized_difference < target_accuracy_; return normalized_difference < target_accuracy_;
@@ -355,32 +360,6 @@ const CylinderBinning* PoissonSolver::densityBinning() {
return &density_binning_; 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) {}; Electrode::Electrode(double potential): potential_(potential) {};
double Electrode::electrodePotential() { double Electrode::electrodePotential() {
+41 -53
View File
@@ -17,16 +17,6 @@ void CpuSynchronizer::sumToAll(blitz::Array<double, 4>& array,
last_sync_array += delta; last_sync_array += delta;
} }
void CpuSynchronizer::sumToAll(blitz::Array<double, 5>& array,
blitz::Array<double, 5>& last_sync_array) {
int size = array.size();
blitz::Array<double, 5> delta(array.extent());
delta = array - last_sync_array;
MPI_Allreduce(MPI_IN_PLACE, delta.data(), size, MPI_DOUBLE,
MPI_SUM, MPI_COMM_WORLD);
last_sync_array += delta;
}
void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array, void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
blitz::Array<long int, 4>& last_sync_array) { blitz::Array<long int, 4>& last_sync_array) {
int size = array.size(); int size = array.size();
@@ -37,16 +27,6 @@ void CpuSynchronizer::sumToAll(blitz::Array<long int, 4>& array,
last_sync_array += delta; 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, void CpuSynchronizer::sumToAll(blitz::Array<double, 3>& array,
blitz::Array<double, 3>& last_sync_array) { blitz::Array<double, 3>& last_sync_array) {
int size = array.size(); int size = array.size();
@@ -85,79 +65,87 @@ void CpuSynchronizer::synchronize(Timer* timer, Timer* last_sync_timer) {
} }
void CpuSynchronizer::synchronize(DynamicDensityField* field, void CpuSynchronizer::synchronize(DynamicDensityField* field,
DynamicDensityField* density_for_drawing, DynamicDensityField* last_sync_field) {
bool reset) { if (field && last_sync_field) {
if (field) { if(field == last_sync_field) {
sumToAll(field->time_in_bin_s_, field->sync_time_in_bin_s_); ERROR("The way last_sync_field is created does not work as intended.");
field->time_in_bin_s_ = field->sync_time_in_bin_s_;
sumToAll(field->deleted_particles_, field->sync_deleted_particles_);
field->deleted_particles_ = field->sync_deleted_particles_;
if (reset) {
density_for_drawing->time_in_bin_s_ = field->time_in_bin_s_;
density_for_drawing->deleted_particles_ = field->deleted_particles_;
} }
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_;
sumToAll(field->deleted_particles_, last_sync_field->deleted_particles_);
field->deleted_particles_ = last_sync_field->deleted_particles_;
} }
} }
void CpuSynchronizer::synchronize(CurrentCollector* collector) { void CpuSynchronizer::synchronize(CurrentCollector* collector,
if (collector) { CurrentCollector* last_sync_collector) {
if (collector && last_sync_collector) {
sumToAll(collector->z_negative_crossings, sumToAll(collector->z_negative_crossings,
collector->sync_z_negative_crossings); last_sync_collector->z_negative_crossings);
collector->z_negative_crossings = collector->z_negative_crossings =
collector->sync_z_negative_crossings; last_sync_collector->z_negative_crossings;
sumToAll(collector->z_positive_crossings, sumToAll(collector->z_positive_crossings,
collector->sync_z_positive_crossings); last_sync_collector->z_positive_crossings);
collector->z_positive_crossings = collector->z_positive_crossings =
collector->sync_z_positive_crossings; last_sync_collector->z_positive_crossings;
sumToAll(collector->phi_negative_crossings, sumToAll(collector->phi_negative_crossings,
collector->sync_phi_negative_crossings); last_sync_collector->phi_negative_crossings);
collector->phi_negative_crossings = collector->phi_negative_crossings =
collector->sync_phi_negative_crossings; last_sync_collector->phi_negative_crossings;
sumToAll(collector->phi_positive_crossings, sumToAll(collector->phi_positive_crossings,
collector->sync_phi_positive_crossings); last_sync_collector->phi_positive_crossings);
collector->phi_positive_crossings = collector->phi_positive_crossings =
collector->sync_phi_positive_crossings; last_sync_collector->phi_positive_crossings;
sumToAll(collector->r_negative_crossings, sumToAll(collector->r_negative_crossings,
collector->sync_r_negative_crossings); last_sync_collector->r_negative_crossings);
collector->r_negative_crossings = collector->r_negative_crossings =
collector->sync_r_negative_crossings; last_sync_collector->r_negative_crossings;
sumToAll(collector->r_positive_crossings, sumToAll(collector->r_positive_crossings,
collector->sync_r_positive_crossings); last_sync_collector->r_positive_crossings);
collector->r_positive_crossings = collector->r_positive_crossings =
collector->sync_r_positive_crossings; last_sync_collector->r_positive_crossings;
} }
} }
void CpuSynchronizer::synchronize(DeletionLogger* logger) { void CpuSynchronizer::synchronize(DeletionLogger* logger,
if (logger) { DeletionLogger* last_sync_logger) {
if (logger && last_sync_logger) {
for (auto& pair : logger->num_deletions) { for (auto& pair : logger->num_deletions) {
long int num_deletion = pair.second; long int num_deletion = pair.second;
long int last_sync_num_deletion = logger->sync_num_deletions[pair.first]; long int last_sync_num_deletion = last_sync_logger->num_deletions[pair.first];
sumToAll(num_deletion, last_sync_num_deletion); sumToAll(num_deletion, last_sync_num_deletion);
// last_sync_num_deletion now contains the total number of deletions // last_sync_num_deletion now contains the total number of deletions
// across all cpus -> update the values in the objects // across all cpus -> update the values in the objects
pair.second = last_sync_num_deletion; pair.second = last_sync_num_deletion;
logger->sync_num_deletions[pair.first] = last_sync_num_deletion; last_sync_logger->num_deletions[pair.first] = last_sync_num_deletion;
} }
} }
} }
void CpuSynchronizer::synchronize( void CpuSynchronizer::synchronize(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& std::map<std::string, std::shared_ptr<species::TrackedSpecie>>&
tracked_species, bool reset) { tracked_species) {
MPI_Barrier(MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD);
auto it = tracked_species.begin(); auto it = tracked_species.begin();
DEBUG_LEVEL_3("Timer Synchronization.");
synchronize(it->second->dynamicDensityField()->timer_.get(),
it->second->lastSyncDensityField()->timer_.get());
for (auto& pair : tracked_species) { for (auto& pair : tracked_species) {
// DEBUG_LEVEL_3("dynden Synchronization.");
synchronize(pair.second->dynamicDensityField(), synchronize(pair.second->dynamicDensityField(),
pair.second->densityForDrawing(), reset); pair.second->lastSyncDensityField());
synchronize(pair.second->currentCollector()); // DEBUG_LEVEL_3("cc Synchronization.");
synchronize(pair.second->deletionLogger()); synchronize(pair.second->currentCollector(),
pair.second->lastSyncCurrentCollector());
// DEBUG_LEVEL_3("dellogger Synchronization.");
synchronize(pair.second->deletionLogger(),
pair.second->lastSyncDeletionLogger());
} }
} }
+14 -45
View File
@@ -12,13 +12,7 @@ CurrentCollector::CurrentCollector(const CylinderBinning& position_binning,
collector_areas_r(createAreaRadial(position_binning)), collector_areas_r(createAreaRadial(position_binning)),
phi_negative_crossings(createCrossingsAzimuthal(position_binning)), phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
phi_positive_crossings(createCrossingsAzimuthal(position_binning)), phi_positive_crossings(createCrossingsAzimuthal(position_binning)),
collector_areas_phi(createAreaAzimuthal(position_binning)), collector_areas_phi(createAreaAzimuthal(position_binning)) {}
sync_z_negative_crossings(createCrossingsLongitudinal(position_binning)),
sync_z_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( blitz::Array<double, 3> CurrentCollector::createAreaLongitudinal(
const CylinderBinning& position_binning) { const CylinderBinning& position_binning) {
@@ -138,45 +132,40 @@ void CurrentCollector::collect(particle::Particle* particle,
blitz::TinyVector<int, 3> bin_new = blitz::TinyVector<int, 3> bin_new =
position_binning_.bin(particle->position().cylinderEntries()); position_binning_.bin(particle->position().cylinderEntries());
const double weight = particle->weight(); collectRadialMovement(bin_old, bin_new);
collectLongitudinalMovement(bin_old, bin_new);
collectRadialMovement(bin_old, bin_new, weight); collectAzimuthalMovement(bin_old, bin_new);
collectLongitudinalMovement(bin_old, bin_new, weight);
collectAzimuthalMovement(bin_old, bin_new, weight);
} }
void CurrentCollector::collectRadialMovement( void CurrentCollector::collectRadialMovement(
const blitz::TinyVector<int, 3>& bin_old, 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)) { if (bin_new(0) < bin_old(0)) {
r_negative_crossings(bin_new(0), bin_old(1), bin_old(2)) += weight; r_negative_crossings(bin_new(0), bin_old(1), bin_old(2)) += 1;
} else if (bin_new(0) > bin_old(0)) { } else if (bin_new(0) > bin_old(0)) {
r_positive_crossings(bin_new(0) - 1, bin_old(1), bin_old(2)) += weight; r_positive_crossings(bin_new(0) - 1, bin_old(1), bin_old(2)) += 1;
} }
} }
void CurrentCollector::collectLongitudinalMovement( void CurrentCollector::collectLongitudinalMovement(
const blitz::TinyVector<int, 3>& bin_old, 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)) { if (bin_new(2) < bin_old(2)) {
z_negative_crossings(bin_old(0), bin_old(1), bin_new(2) + 1) += weight; z_negative_crossings(bin_old(0), bin_old(1), bin_new(2) + 1) += 1;
} else if (bin_new(2) > bin_old(2)) { } else if (bin_new(2) > bin_old(2)) {
z_positive_crossings(bin_old(0), bin_old(1), bin_new(2)) += weight; z_positive_crossings(bin_old(0), bin_old(1), bin_new(2)) += 1;
} }
} }
void CurrentCollector::collectAzimuthalMovement( void CurrentCollector::collectAzimuthalMovement(
const blitz::TinyVector<int, 3>& bin_old, 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)) || if ((bin_new(1) < bin_old(1)) ||
((bin_old(1) == 0) && ((bin_old(1) == 0) &&
(bin_new(1) == position_binning_.binIndexMax()(1)))) { (bin_new(1) == position_binning_.binIndexMax()(1)))) {
phi_negative_crossings(bin_old(0), bin_new(1), bin_old(2)) += weight; phi_negative_crossings(bin_old(0), bin_new(1), bin_old(2)) += 1;
} else if ((bin_new(1) > bin_old(1)) || } else if ((bin_new(1) > bin_old(1)) ||
((bin_old(1) == position_binning_.binIndexMax()(1)) && ((bin_old(1) == position_binning_.binIndexMax()(1)) &&
(bin_new(1) == 0))) { (bin_new(1) == 0))) {
phi_positive_crossings(bin_old(0), bin_new(1) - 1, bin_old(2)) += weight; phi_positive_crossings(bin_old(0), bin_new(1) - 1, bin_old(2)) += 1;
} }
} }
@@ -249,25 +238,5 @@ blitz::Array<double, 3> CurrentCollector::currentInR() const {
return current_in_r; return current_in_r;
} }
double CurrentCollector::physicalTime() const { double CurrentCollector::physicalTime() const {
return timer_->getDeltaT(); return timer_->time();
}
void CurrentCollector::resetCurrentCollector() {
z_negative_crossings = 0.;
z_positive_crossings = 0.;
phi_negative_crossings = 0.;
phi_positive_crossings = 0.;
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.;
} }
+54 -313
View File
@@ -4,9 +4,6 @@
#include "simulation/errors.h" #include "simulation/errors.h"
#include "simulation/event_position_distribution.h" #include "simulation/event_position_distribution.h"
#include "simulation/scalar_field.h" #include "simulation/scalar_field.h"
#include "simulation/kinematic.h"
#include "tools/simulation_time.h"
template <class T> template <class T>
blitz::Array<T, 4> initiate4DArray(blitz::Range radial, blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
@@ -18,17 +15,6 @@ blitz::Array<T, 4> initiate4DArray(blitz::Range radial,
return data.copy(); 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::Array<double, 3> initiateVolumeArray(
blitz::Range radial, blitz::Range radial,
blitz::Range phi, blitz::Range phi,
@@ -55,54 +41,26 @@ blitz::Array<double, 3> initiateVolumeArray(
DynamicDensityField::DynamicDensityField( DynamicDensityField::DynamicDensityField(
const CylinderBinning& position_binning, const CylinderBinning& position_binning,
const EnergyBinning& energy_binning, const EnergyBinning& energy_binning,
const PitchAngleBinning& pitch_angle_binning, std::shared_ptr<Timer> timer)
std::shared_ptr<Timer> timer) : : position_binning_(position_binning),
position_binning_(position_binning),
energy_binning_(energy_binning), energy_binning_(energy_binning),
pitch_angle_binning_(pitch_angle_binning),
timer_(timer), timer_(timer),
time_in_bin_s_(initiate5DArray<double>( time_in_bin_s_(initiate4DArray<double>(
blitz::Range(position_binning.radial_binning.binIndexMin(), blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()), position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(), blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()), position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(), blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()), position_binning.longitudinal_binning.binIndexMax()),
blitz::Range(pitch_angle_binning.binIndexMin(),
pitch_angle_binning.binIndexMax()),
blitz::Range(energy_binning.binIndexMin(), blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))), energy_binning.binIndexMax()))),
sync_time_in_bin_s_(initiate5DArray<double>( deleted_particles_(initiate4DArray<long int>(
blitz::Range(position_binning.radial_binning.binIndexMin(), blitz::Range(position_binning.radial_binning.binIndexMin(),
position_binning.radial_binning.binIndexMax()), position_binning.radial_binning.binIndexMax()),
blitz::Range(position_binning.azimuth_binning.binIndexMin(), blitz::Range(position_binning.azimuth_binning.binIndexMin(),
position_binning.azimuth_binning.binIndexMax()), position_binning.azimuth_binning.binIndexMax()),
blitz::Range(position_binning.longitudinal_binning.binIndexMin(), blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()), 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(), blitz::Range(energy_binning.binIndexMin(),
energy_binning.binIndexMax()))), energy_binning.binIndexMax()))),
density_per_m3_(initiate4DArray<double>( density_per_m3_(initiate4DArray<double>(
@@ -122,75 +80,11 @@ DynamicDensityField::DynamicDensityField(
blitz::Range(position_binning.longitudinal_binning.binIndexMin(), blitz::Range(position_binning.longitudinal_binning.binIndexMin(),
position_binning.longitudinal_binning.binIndexMax()), position_binning.longitudinal_binning.binIndexMax()),
position_binning.stepsize())) { position_binning.stepsize())) {
if(!timer) { if (!timer) {
ERROR("Timer is necessary for calculation of density field"); 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 / 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_->getDeltaT();
const double time_in_bin = blitz::sum(time_in_bin_s_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), energy_bin));
const long deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), energy_bin));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
double DynamicDensityField::density(const Coordinate& position,
double energy_split,
bool above) {
const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries());
const int energy_split_bin = energy_binning_.bin(energy_split);
blitz::Range range;
if(above) {
range = blitz::Range(energy_split_bin, energy_binning_.binIndexMax());
} else {
if(energy_split_bin == energy_binning_.binIndexMin())
return 0;
range = blitz::Range(energy_binning_.binIndexMin(), energy_split_bin-1);
}
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(), range));
const long deleted_particles = blitz::sum(deleted_particles_(
position_bin(0), position_bin(1), position_bin(2),
blitz::Range::all(), range));
return (time_in_bin / t - deleted_particles) /
bin_volume_m3_(position_bin(0), position_bin(1), position_bin(2));
}
bool DynamicDensityField::changedPositionBin( bool DynamicDensityField::changedPositionBin(
const Coordinate& old_position, const Coordinate& old_position,
const Coordinate& new_position) const { const Coordinate& new_position) const {
@@ -211,114 +105,90 @@ bool DynamicDensityField::changedEnergyBin(double old_energy_eV,
return !(old_bin == new_bin); 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);
if(!(old_bin == new_bin)) {
DEBUG_LEVEL_3("old mu: " + std::to_string(old_mu));
DEBUG_LEVEL_3("old bin: " + std::to_string(old_bin));
DEBUG_LEVEL_3("new mu: " + std::to_string(new_mu));
DEBUG_LEVEL_3("new bin: " + std::to_string(new_bin));
}
return !(old_bin == new_bin);
}
void DynamicDensityField::logMovement(const Coordinate& position, void DynamicDensityField::logMovement(const Coordinate& position,
double energy_eV, double energy_eV,
double pitch_angle,
double time_in_bin_s) { double time_in_bin_s) {
const blitz::TinyVector<int, 3> position_bin = const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries()); position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV); const int energy_bin = energy_binning_.bin(energy_eV);
const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle);
time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2), time_in_bin_s_(position_bin(0), position_bin(1), position_bin(2),
pitch_angle_bin, energy_bin) += time_in_bin_s; energy_bin) += time_in_bin_s;
} }
void DynamicDensityField::logDeletion(const Coordinate& position, void DynamicDensityField::logDeletion(const Coordinate& position,
double energy_eV, double energy_eV) {
double pitch_angle) {
const blitz::TinyVector<int, 3> position_bin = const blitz::TinyVector<int, 3> position_bin =
position_binning_.bin(position.cylinderEntries()); position_binning_.bin(position.cylinderEntries());
const int energy_bin = energy_binning_.bin(energy_eV); const int energy_bin = energy_binning_.bin(energy_eV);
const int pitch_angle_bin = pitch_angle_binning_.bin(pitch_angle);
deleted_particles_(position_bin(0), position_bin(1), position_bin(2), pitch_angle_bin, deleted_particles_(position_bin(0), position_bin(1), position_bin(2),
energy_bin) += 1; energy_bin) += 1;
return; }
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));
} }
blitz::Array<double, 3> DynamicDensityField::densityArray() { blitz::Array<double, 3> DynamicDensityField::densityArray() {
DEBUG_LEVEL_3("recalc Density array");
recalculateDensityArray(); recalculateDensityArray();
blitz::TinyVector<int,3> lowerbound(density_per_m3_.lbound(0), blitz::Array<double, 3> density(density_per_m3_(
density_per_m3_.lbound(1), blitz::Range::all(), blitz::Range::all(), blitz::Range::all(), 0));
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; blitz::fourthIndex iE;
DEBUG_LEVEL_3("density sum");
density = blitz::sum(density_per_m3_, iE); density = blitz::sum(density_per_m3_, iE);
return density.copy(); return density.copy();
} }
blitz::Array<double, 3> DynamicDensityField::densityArray(
double energy_split, bool above) {
DEBUG_LEVEL_3("recalc Density array");
recalculateDensityArray();
const int energy_split_bin = energy_binning_.bin(energy_split);
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);
density = 0;
blitz::Range range;
if(above) {
range = blitz::Range(energy_split_bin, energy_binning_.binIndexMax());
} else {
if(energy_split_bin == energy_binning_.binIndexMin())
return density;
range = blitz::Range(energy_binning_.binIndexMin(), energy_split_bin-1);
}
blitz::Range all = blitz::Range::all();
blitz::fourthIndex iE;
DEBUG_LEVEL_3("density sum");
density = blitz::sum(density_per_m3_(all, all, all, range), iE);
return density.copy();
}
blitz::Array<double, 4> DynamicDensityField::spectrumArray() { blitz::Array<double, 4> DynamicDensityField::spectrumArray() {
recalculateDensityArray(); recalculateDensityArray();
return density_per_m3_; return density_per_m3_;
} }
blitz::Array<double, 5> DynamicDensityField::timeInBinArray() const { 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 {
return time_in_bin_s_; return time_in_bin_s_;
} }
blitz::Array<long int, 4> DynamicDensityField::deletedParticlesArray() const {
blitz::Array<long int, 5> DynamicDensityField::deletedParticlesArray() const {
return deleted_particles_; return deleted_particles_;
} }
blitz::Array<double, 3> DynamicDensityField::binVolumeArray() const { blitz::Array<double, 3> DynamicDensityField::binVolumeArray() const {
return bin_volume_m3_; return bin_volume_m3_;
} }
@@ -331,139 +201,10 @@ const CylinderBinning* DynamicDensityField::positionBinning() const {
return &position_binning_; return &position_binning_;
} }
const PitchAngleBinning* DynamicDensityField::pitchAngleBinning() const {
return &pitch_angle_binning_;
}
double DynamicDensityField::physicalTime() const { double DynamicDensityField::physicalTime() const {
return timer_->time(); return timer_->time();
} }
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) / t -
deleted_particles_(ir, iphi, iz, iE, ipitch)), iE) /
bin_volume_m3_(ir, iphi, iz);
// SimulationTimer::eventStopPoint("recalcDensityArray");
}
double DynamicDensityField::particleNumber() {
blitz::Array<double, 3> density = densityArray();
double particleNumber = blitz::sum(density * bin_volume_m3_);
DEBUG_LEVEL_3("particle number: " + std::to_string(particleNumber));
return particleNumber;
}
double DynamicDensityField::particleNumber(double E_thresh, bool above) {
const int energy_bin = energy_binning_.bin(E_thresh);
double time_in_bin = 0;
double deleted_particles = 0;
blitz::Range range;
if(above) {
range = blitz::Range(energy_bin, energy_binning_.binIndexMax());
} else {
if(energy_bin == energy_binning_.binIndexMin())
return 0;
range = blitz::Range(energy_binning_.binIndexMin(), energy_bin-1);
}
time_in_bin = blitz::sum(time_in_bin_s_(
blitz::Range::all(), blitz::Range::all(), blitz::Range::all(),
blitz::Range::all(), range));
deleted_particles = blitz::sum(deleted_particles_(
blitz::Range::all(), blitz::Range::all(), blitz::Range::all(),
blitz::Range::all(), range));
const double t = timer_->getDeltaT();
return (time_in_bin / t - deleted_particles);
}
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<double, 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());
}
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
+3 -50
View File
@@ -2,7 +2,8 @@
#include <math.h> #include <math.h>
#include <algorithm> #include <algorithm>
std::vector<double> generateLogBinBorders(double bin_min, // probably rename to indicate what type of borders are created
std::vector<double> generateBinBorders(double bin_min,
double bin_max, double bin_max,
int num_bins) { int num_bins) {
const double min_bin_log = log10(bin_min); const double min_bin_log = log10(bin_min);
@@ -17,25 +18,11 @@ std::vector<double> generateLogBinBorders(double bin_min,
return bin_borders; return bin_borders;
} }
std::vector<double> generateLinearBinBorders(double bin_min,
double bin_max,
int num_bins) {
const double bin_size = (bin_max - bin_min) / num_bins;
std::vector<double> bin_borders;
for (int i = 0; i <= num_bins; ++i) {
const double bin_border = bin_size * i + bin_min;
bin_borders.push_back(bin_border);
}
return bin_borders;
}
EnergyBinning::EnergyBinning(double minimal_energy, EnergyBinning::EnergyBinning(double minimal_energy,
double maximal_energy, double maximal_energy,
int num_bins) int num_bins)
: energy_bin_borders_( : energy_bin_borders_(
generateLogBinBorders(minimal_energy, maximal_energy, num_bins)) {} generateBinBorders(minimal_energy, maximal_energy, num_bins)) {}
EnergyBinning::EnergyBinning(std::vector<double> energy_bin_borders) EnergyBinning::EnergyBinning(std::vector<double> energy_bin_borders)
: energy_bin_borders_(energy_bin_borders) {} : energy_bin_borders_(energy_bin_borders) {}
@@ -61,37 +48,3 @@ int EnergyBinning::binIndexMin() const {
int EnergyBinning::binIndexMax() const { int EnergyBinning::binIndexMax() const {
return numBins(); 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();
}
+1 -8
View File
@@ -37,14 +37,7 @@ MaxwellBoltzmann::MaxwellBoltzmann(double temperature_K)
} }
double MaxwellBoltzmann::rollEnergy(std::mt19937* engine) { double MaxwellBoltzmann::rollEnergy(std::mt19937* engine) {
double value = distribution_(*engine); return 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) { Constant::Constant(double constant_eV) : constant_eV_(constant_eV) {
@@ -1,5 +1,4 @@
#include "simulation/event_position_distribution.h" #include "simulation/event_position_distribution.h"
#include "simulation/errors.h"
EventPositionDistribution::EventPositionDistribution( EventPositionDistribution::EventPositionDistribution(
std::shared_ptr<ScalarField> mother_density, std::shared_ptr<ScalarField> mother_density,
@@ -40,94 +39,3 @@ CylinderCoordinate EventPositionDistribution::rollPosition(
return CylinderCoordinate(blitz::TinyVector<double, 3>( return CylinderCoordinate(blitz::TinyVector<double, 3>(
random_numer_r, random_number_phi, random_number_z)); random_numer_r, random_number_phi, random_number_z));
} }
PositionDistributionFromDensity::PositionDistributionFromDensity(
std::shared_ptr<DynamicDensityField> density):
density_(density),
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());
}
void PositionDistributionFromDensity::setMaximumDensityAboveAndBelow(
double energy_split) {
maximum_density_below_ = blitz::max(
density_->densityArray(energy_split, false));
maximum_density_above_ = blitz::max(
density_->densityArray(energy_split, true));
}
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, double energy_split, bool above) {
const double max_density = above ? maximum_density_above_ : maximum_density_below_;
if(isEqual(max_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;
double density_at_position;
// std::stringstream out;
// above ? out << "Above: " : out << "Below: ";
// out << "densities: ";
do {
random_r = std::sqrt(r_values(*engine));
random_phi = phi_values(*engine);
random_z = z_values(*engine);
random_n = density_values(*engine);
density_at_position = density_->density(CylinderCoordinate(
blitz::TinyVector<double,3>(random_r, random_phi, random_z)),
energy_split, above);
// out << density_at_position << "\n";
// might be bad that the value gets recalculated for each call of density_->density(...)
} while (random_n*max_density > density_at_position);
// DEBUG_LEVEL_2(out.str());
return CylinderCoordinate(
blitz::TinyVector<double, 3>(random_r, random_phi, random_z));
}
+7 -192
View File
@@ -6,11 +6,7 @@
#include "simulation/kinematic.h" #include "simulation/kinematic.h"
#include "simulation/particle.h" #include "simulation/particle.h"
#include "simulation/species.h" #include "simulation/species.h"
#include "simulation/density_field.h"
#include "simulation/velocity_distribution.h" #include "simulation/velocity_distribution.h"
#include "simulation/electromagnetic_field.h"
#include "constants/ionization_constants.h"
#include <sstream>
Injector::Injector( Injector::Injector(
std::vector<InjectorInfo>& injector_info, std::vector<InjectorInfo>& injector_info,
@@ -20,8 +16,7 @@ Injector::Injector(
: injector_infos_(injector_info), : injector_infos_(injector_info),
activity_(activity), activity_(activity),
position_distribution_(position_distribution), position_distribution_(position_distribution),
mother_drift_velocity_(mother_drift_velocity), mother_drift_velocity_(mother_drift_velocity) {
energySplit_(ionization::ionization_energy_janev_atomic) {
ASSERT_POSITIVE(&activity_, "Injector: Activity must be positive"); ASSERT_POSITIVE(&activity_, "Injector: Activity must be positive");
ASSERT_EXISTS(&position_distribution_, ASSERT_EXISTS(&position_distribution_,
"Injector: The position distribution is null."); "Injector: The position distribution is null.");
@@ -31,9 +26,7 @@ particle::Particle Injector::rollNewParticle(
std::mt19937* engine, std::mt19937* engine,
const Coordinate& position, const Coordinate& position,
std::shared_ptr<species::TrackedSpecie> created_specie, 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 = blitz::TinyVector<double, 3> velocity =
creation_velocity_distribution->rollVelocity(position, engine) creation_velocity_distribution->rollVelocity(position, engine)
.cartesianEntries(); .cartesianEntries();
@@ -42,202 +35,24 @@ particle::Particle Injector::rollNewParticle(
velocity, velocity,
mother_drift_velocity_->driftVelocity(position).cartesianEntries()); 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
return particle::Particle(created_specie, position, return particle::Particle(created_specie, position,
CartesianVector(velocity), time_birth, weight); CartesianVector(velocity));
}
void Injector::initInjectionTimeDistribution(double delta_t) {
injection_time_distribution_ =
std::uniform_real_distribution<double>(0., delta_t);
} }
std::vector<particle::Particle> Injector::rollNewParticles( std::vector<particle::Particle> Injector::rollNewParticles(
std::mt19937* engine, const double current_time, std::mt19937* engine) {
const double beta_particle_weight) {
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); CylinderCoordinate position = position_distribution_->rollPosition(engine);
DEBUG_LEVEL_3("Injected z position: " + DEBUG_LEVEL_3("Injected z position: " +
std::to_string(position.cylinderEntries()(2))); std::to_string(position.cylinderEntries()(2)));
std::vector<particle::Particle> new_particles;
for (auto& injector_info : injector_infos_) {
new_particles.push_back( new_particles.push_back(
rollNewParticle(engine, position, injector_info.created_specie, 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; 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) {
if(specie->type() == species::ImplementedSpecies::electron) {
if(!(particleNumbersMap_[specie->name()][1] == 0))
queue.push_back(drawNewDensityParticleAboveOrBelow(engine, specie,
magnetic_field, weight_factor, injection_time, true));
if(!(particleNumbersMap_[specie->name()][0] == 0))
queue.push_back(drawNewDensityParticleAboveOrBelow(engine, specie,
magnetic_field, weight_factor, injection_time, false));
return;
}
if(particleNumbersMap_[specie->name()][0] == 0) {
return;
}
// draw the position
CylinderCoordinate position =
specie->positionDistributionFromDensity()->drawPosition(engine);
// check if density was empty (i.e. phi value lower than 0)
if (position.cylinderEntries()(1) < 0) {
DEBUG_LEVEL_3(specie->name() + ": has zero density");
return;
}
DEBUG_LEVEL_3("Injected z position: " +
std::to_string(position.cylinderEntries()(2)));
DEBUG_LEVEL_3("Injected r position: " +
std::to_string(position.cylinderEntries()(0)));
// 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()->
rollVelocity(position, engine);
} else {
velocity = specie->velocityDistributionFromDensityField()->
rollVelocity(position, engine, magnetic_field);
}
particle::Particle drawn_particle(specie, position,
velocity, injection_time, weight_factor*particleNumbersMap_[specie->name()][0]);
queue.push_back(drawn_particle);
}
double Injector::timePassed() const { double Injector::timePassed() const {
return 1 / activity_; return 1 / activity_;
} }
void Injector::fillParticleNumbers(std::shared_ptr<species::TrackedSpecie> specie) {
// std::stringstream out;
// out << specie->name() << ":";
std::vector<double> numbers;
double nTot = 0;
if(specie->type() == species::ImplementedSpecies::electron) {
double numberBelow = specie->densityForDrawing()->particleNumber(
energySplit_, false);
numbers.push_back(numberBelow);
double numberAbove = specie->densityForDrawing()->particleNumber(
energySplit_, true);
numbers.push_back(numberAbove);
// out << "\n\tN( E < " << energySplit_<< ")"
// << " = " << numberBelow;
// out << "\n\tN( E > " << energySplit_<< ")"
// << " = " << numberAbove;
nTot = numberBelow + numberAbove;
} else {
numbers.push_back(specie->densityForDrawing()->particleNumber());
// out << numbers[0];
nTot = numbers[0];
}
particleNumbersMap_[specie->name()] = numbers;
// out << "\n\t N_total = " << nTot;
// DEBUG_LEVEL_2(out.str());
}
particle::Particle Injector::drawNewDensityParticleAboveOrBelow(
std::mt19937* engine,
std::shared_ptr<species::TrackedSpecie> specie,
std::shared_ptr<MagneticField> magnetic_field,
const double weight_factor,
const double injection_time,
const bool above) {
std::string above_string = above ? "Above" : "Below";
// std::stringstream out;
// // draw the position
// out << above_string << "\n";
// out << "\tPosition: ";
CylinderCoordinate position =
specie->positionDistributionFromDensity()
->drawPosition(engine, energySplit_, above);
// out << position.cylinderEntries();
double den_at_pos_below =
specie->densityForDrawing()->density(position, energySplit_, false);
// out << "\n\tDensity At position below: " << den_at_pos_below;
// check if density was empty (i.e. phi value lower than 0)
if (position.cylinderEntries()(1) < 0) {
ERROR(specie->name() + ": has zero density");
}
// DEBUG_LEVEL_3("Injected z position: " +
// std::to_string(position.cylinderEntries()(2)));
// DEBUG_LEVEL_3("Injected r position: " +
// std::to_string(position.cylinderEntries()(0)));
// draw the velocity
CartesianVector velocity(blitz::TinyVector<double, 3>(0,0,0));
const int energy_split_bin =
specie->dynamicDensityField()->energyBinning()->bin(energySplit_);
// out << "\n\tEnergy split bin: " << energy_split_bin;
// 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()->
rollVelocity(position, engine, energy_split_bin, above);
} else {
velocity = specie->velocityDistributionFromDensityField()->
rollVelocity(position, engine, magnetic_field,
energy_split_bin,
above);
}
// out << "\n\tVelocity: " << velocity.cartesianEntries();
int index = above ? 1 : 0;
// out << "\n\tWeight: " << weight_factor*particleNumbersMap_[specie->name()][index];
// out << "particleNumbersMap: ";
// for(auto element : particleNumbersMap_[specie->name()])
// out << element << " ";
particle::Particle drawn_particle(specie, position,
velocity, injection_time, weight_factor*particleNumbersMap_[specie->name()][index]);
// DEBUG_LEVEL_1(out.str());
return drawn_particle;
}
double Injector::energySplit() const {
return energySplit_;
}
-6
View File
@@ -166,10 +166,4 @@ blitz::TinyVector<double, 3> rotateVector(
std::sin(angle) * cross; 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 }; // namespace kinematic
-10
View File
@@ -3,7 +3,6 @@
DeletionLogger::DeletionLogger(std::vector<DeletionType> used_types) { DeletionLogger::DeletionLogger(std::vector<DeletionType> used_types) {
for (auto& type : used_types) { for (auto& type : used_types) {
num_deletions[type] = 0; num_deletions[type] = 0;
sync_num_deletions[type] = 0;
} }
} }
@@ -31,12 +30,3 @@ long int DeletionLogger::numDeletions(DeletionType type) const {
return 0; return 0;
} }
} }
void DeletionLogger::resetDeletionLogger() {
for(auto& pair : num_deletions) {
pair.second = 0;
}
for (auto& pair : sync_num_deletions) {
pair.second = 0;
}
}
+94 -185
View File
@@ -19,74 +19,35 @@ BorisMover::BorisMover(double maximal_time_step_s)
"The maximal timestep for boris push must be positive."); "The maximal timestep for boris push must be positive.");
} }
// TBD: include F_g (simply add to electric force)
void BorisMover::move(particle::Particle* particle, void BorisMover::move(particle::Particle* particle,
double mfp_m, double mfp_m,
ElectricField* electric_field, ElectricField* electric_field,
MagneticField* magnetic_field, MagneticField* magnetic_field,
GravityField* gravity_field) { GravityField* gravity_field) {
// 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_distance = mfp_m; double leftover_distance = mfp_m;
auto old_position = particle->position(); auto old_position = particle->position();
double old_kinetic_energy = particle->kineticEnergy_eV(); double old_kinetic_energy = particle->kineticEnergy_eV();
blitz::TinyVector<double, 3> B_old =
magnetic_field->value(old_position).cartesianEntries(old_position);
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));
} else {
old_mu = kinematic::cosPitchAngle(
magnetic_field->value(old_position).cartesianEntries(old_position),
particle->velocity().cartesianEntries(old_position));
}
double timestep = 0;
// if (old_kinetic_energy < 1E-9) { // if (old_kinetic_energy < 1E-9) {
// DEBUG_LEVEL_2("Particle has too low an energy.");
// // Guard against small enegies taking up much time without contributing to // // Guard against small enegies taking up much time without contributing to
// // density // // density
// SIM_INFO("particle skipped due to energy."); // //return;
// return;
// } // }
bool changed_position_bin = false; bool changed_position_bin = false;
bool changed_energy_bin = false; bool changed_energy_bin = false;
bool left_simulation_domain = false; bool left_simulation_domain = false;
bool changed_mu_bin = false;
bool died_in_bin = false; bool died_in_bin = false;
while ( while (
!(changed_position_bin || changed_energy_bin || left_simulation_domain || !(changed_position_bin || changed_energy_bin
changed_mu_bin || died_in_bin) && (leftover_distance > 0.)) { || left_simulation_domain || died_in_bin) &&
(leftover_distance > 0.)) {
old_position = particle->position(); old_position = particle->position();
old_kinetic_energy = particle->kineticEnergy_eV(); old_kinetic_energy = particle->kineticEnergy_eV();
double old_velocity = particle->absoluteVelocity();
timestep = std::min(maximal_time_step_s_,
(leftover_distance + SimConstants::random_lower_limit) / old_velocity);
timestep = std::min(timestep, max_distance / old_velocity);
timestep = std::min(timestep, max_time_alive);
double moved_distance = 0.; double moved_distance = 0.;
const blitz::TinyVector<double, 3> E = const blitz::TinyVector<double, 3> E =
@@ -96,30 +57,14 @@ void BorisMover::move(particle::Particle* particle,
const blitz::TinyVector<double, 3> g = const blitz::TinyVector<double, 3> g =
gravity_field->value(old_position).cartesianEntries(old_position); gravity_field->value(old_position).cartesianEntries(old_position);
movementStep(particle, E, B, g, moved_distance, timestep); const blitz::TinyVector<double, 3> force_over_q =
particle->increaseTimeAlive(timestep); E + particle->mass_kg()/particle->charge_C()*g;
particle->increaseTimeInBin(timestep);
movementStep(particle, force_over_q, B, moved_distance);
particle->increaseTimeAlive(maximal_time_step_s_);
particle->increaseTimeInBin(maximal_time_step_s_);
auto new_position = particle->position(); auto new_position = particle->position();
auto new_velocity = particle->velocity();
const blitz::TinyVector<double, 3> B_new =
magnetic_field->value(new_position).cartesianEntries(new_position);
double new_mu;
if (kinematic::norm(B_new) == 0) {
new_mu = kinematic::cosPitchAngle(
blitz::TinyVector<double, 3>(0,0,1),
new_velocity.cartesianEntries(new_position));
} else {
new_mu = kinematic::cosPitchAngle(
magnetic_field->value(new_position).cartesianEntries(new_position),
new_velocity.cartesianEntries(new_position));
}
changed_mu_bin =
particle->specie()->dynamicDensityField()->changedPitchAngleBin(
old_mu, new_mu);
changed_position_bin = changed_position_bin =
particle->specie()->dynamicDensityField()->changedPositionBin( particle->specie()->dynamicDensityField()->changedPositionBin(
@@ -136,18 +81,10 @@ void BorisMover::move(particle::Particle* particle,
particle->specie()->terminator()->reachedMaxTimeAlive(particle); particle->specie()->terminator()->reachedMaxTimeAlive(particle);
leftover_distance -= moved_distance; leftover_distance -= moved_distance;
// 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);
} }
particle->specie()->dynamicDensityField()->logMovement( particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, old_mu, particle->timeInBin()); old_position, old_kinetic_energy, particle->timeInBin());
particle->resetTimeInBin(); particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position); particle->specie()->currentCollector()->collect(particle, old_position);
} }
@@ -156,33 +93,28 @@ void BorisMover::movementStep(
particle::Particle* particle, particle::Particle* particle,
const blitz::TinyVector<double, 3>& electric_field, const blitz::TinyVector<double, 3>& electric_field,
const blitz::TinyVector<double, 3>& magnetic_field, const blitz::TinyVector<double, 3>& magnetic_field,
const blitz::TinyVector<double, 3>& gravity_field, double& moved_distance) const {
double& moved_distance,
double timestep) const {
const blitz::TinyVector<double, 3> v = const blitz::TinyVector<double, 3> v =
particle->velocity().cartesianEntries(); particle->velocity().cartesianEntries();
const double m = particle->mass_kg(); const double m = particle->mass_kg();
const double q = particle->charge_C(); const double q = particle->charge_C();
const double u_minus_x = const double u_minus_x =
v(0) + (q * electric_field(0) * timestep) / (2. * m) v(0) + (q * electric_field(0) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(0) * timestep) / 2.;
const double u_minus_y = const double u_minus_y =
v(1) + (q * electric_field(1) * timestep) / (2. * m) v(1) + (q * electric_field(1) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(1) * timestep) / 2.;
const double u_minus_z = const double u_minus_z =
v(2) + (q * electric_field(2) * timestep) / (2. * m) v(2) + (q * electric_field(2) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(2) * timestep) / 2.;
const double gamma = kinematic::relativisticGamma( const double gamma = kinematic::relativisticGamma(
blitz::TinyVector<double, 3>(u_minus_x, u_minus_y, u_minus_z)); blitz::TinyVector<double, 3>(u_minus_x, u_minus_y, u_minus_z));
const double temp_1_x = const double temp_1_x =
(q * magnetic_field(0) * timestep) / (2 * m * gamma); (q * magnetic_field(0) * maximal_time_step_s_) / (2 * m * gamma);
const double temp_1_y = const double temp_1_y =
(q * magnetic_field(1) * timestep) / (2 * m * gamma); (q * magnetic_field(1) * maximal_time_step_s_) / (2 * m * gamma);
const double temp_1_z = const double temp_1_z =
(q * magnetic_field(2) * timestep) / (2 * m * gamma); (q * magnetic_field(2) * maximal_time_step_s_) / (2 * m * gamma);
const double u_prime_x = const double u_prime_x =
u_minus_x + (u_minus_y * temp_1_z - u_minus_z * temp_1_y); u_minus_x + (u_minus_y * temp_1_z - u_minus_z * temp_1_y);
@@ -209,14 +141,11 @@ void BorisMover::movementStep(
u_minus_z + (u_prime_x * temp_2_y - u_prime_y * temp_2_x); u_minus_z + (u_prime_x * temp_2_y - u_prime_y * temp_2_x);
const double u_new_x = const double u_new_x =
u_plus_x + (q * electric_field(0) * timestep) / (2. * m) u_plus_x + (q * electric_field(0) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(0) * timestep) / 2.;
const double u_new_y = const double u_new_y =
u_plus_y + (q * electric_field(1) * timestep) / (2. * m) u_plus_y + (q * electric_field(1) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(1) * timestep) / 2.;
const double u_new_z = const double u_new_z =
u_plus_z + (q * electric_field(2) * timestep) / (2. * m) u_plus_z + (q * electric_field(2) * maximal_time_step_s_) / (2. * m);
+ (gravity_field(2) * timestep) / 2.;
const blitz::TinyVector<double, 3> u_new(u_new_x, u_new_y, u_new_z); const blitz::TinyVector<double, 3> u_new(u_new_x, u_new_y, u_new_z);
/* /*
@@ -238,7 +167,7 @@ void BorisMover::movementStep(
particle->velocity(CartesianVector(u_new)); particle->velocity(CartesianVector(u_new));
const CartesianCoordinate distance(u_new * timestep); const CartesianCoordinate distance(u_new * maximal_time_step_s_);
particle->move(distance); particle->move(distance);
moved_distance += std::sqrt( moved_distance += std::sqrt(
@@ -262,76 +191,82 @@ void DriftMover::move(particle::Particle* particle,
auto old_position = particle->position(); auto old_position = particle->position();
auto old_velocity = particle->velocity(); auto old_velocity = particle->velocity();
double old_kinetic_energy = particle->kineticEnergy_eV(); 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_position_bin = false;
bool changed_energy_bin = false; bool changed_energy_bin = false;
bool changed_mu_bin = false;
bool left_simulation_domain = false; bool left_simulation_domain = false;
// if particle too slow -> timestep > maximum time the particle lives // if particle too slow -> timestep > maximum time the particle lives
// -> add maximal timestep to time in bin and stop moving the particle // -> add maximal timestep to time in bin and stop moving the particle
bool died_in_bin = false; bool died_in_bin = false;
double max_time_alive = const double max_time_alive = particle->specie()->terminator()->maxTimeAlive();
particle->specie()->dynamicDensityField()->physicalTime() -
particle->timeAlive();
while ( while (
!(changed_position_bin || changed_energy_bin || changed_mu_bin !(changed_position_bin || changed_energy_bin || left_simulation_domain) &&
|| left_simulation_domain) &&
(leftover_distance > 0.) && !(died_in_bin)) { (leftover_distance > 0.) && !(died_in_bin)) {
std::stringstream out;
old_position = particle->position(); old_position = particle->position();
old_velocity = particle->velocity(); old_velocity = particle->velocity();
out << "cylinder vector pos: " << old_position.cartesianEntries() <<"\n";
old_kinetic_energy = particle->kineticEnergy_eV(); old_kinetic_energy = particle->kineticEnergy_eV();
// out << " old kinetic Energy: " << old_kinetic_energy << "\n";
blitz::TinyVector<double, 3> force_over_charge = blitz::TinyVector<double, 3> force_over_charge =
electric_field->value(old_position).cartesianEntries(old_position) + electric_field->value(old_position).cartesianEntries(old_position);
gravity_field->value(old_position).cartesianEntries(old_position) *
particle->mass_kg() / particle->charge_C(); // gravity force / q
force_over_charge += gravity_field->value(old_position).cartesianEntries(old_position)
* particle->mass_kg() / particle->charge_C();
const blitz::TinyVector<double, 3> B = const blitz::TinyVector<double, 3> B =
magnetic_field->value(old_position).cartesianEntries(old_position); magnetic_field->value(old_position).cartesianEntries(old_position);
const double B_norm = kinematic::norm(B); const double B_norm = kinematic::norm(B);
const blitz::TinyVector<double, 3> gradB = out << " B(cyli): " << magnetic_field->value(old_position).cylinderEntries()<<"\n";
magnetic_field->gradientValue(old_position).cartesianEntries(old_position);
// Todo: add calculation of divB here
// use Kassiopeia paper for reference
const blitz::TinyVector<double, 3> v_parallel = const blitz::TinyVector<double, 3> v_parallel =
kinematic::parallelVector(old_velocity.cartesianEntries(), B); kinematic::parallelVector(old_velocity.cartesianEntries(), B);
const double v_parallel_norm = kinematic::norm(v_parallel); const double v_parallel_norm = kinematic::norm(v_parallel);
// out << " v_parallel: " << v_parallel << "\n";
const blitz::TinyVector<double, 3> v_perp = const blitz::TinyVector<double, 3> v_perp =
kinematic::perpendicularVector(old_velocity.cartesianEntries(), B); kinematic::perpendicularVector(old_velocity.cartesianEntries(), B);
const double v_perp_norm = kinematic::norm(v_perp); const double v_perp_norm = kinematic::norm(v_perp);
out << " v_perp: " << v_perp << "\n";
// magnetic moment // magnetic moment force / q
const double magnetic_moment = const double magnetic_moment = (particle->mass_kg()*(v_perp_norm*v_perp_norm/2))/B_norm;
(particle->mass_kg()*(v_perp_norm*v_perp_norm)/2)/B_norm; out << " magnetic moment: " << magnetic_moment << "\n";
force_over_charge += -(magnetic_moment / particle->charge_C() * gradB); force_over_charge += -(magnetic_moment / particle->charge_C() *
magnetic_field->gradientValue(old_position).cartesianEntries(old_position));
// curvature force // out << " gradB (cyli): "
// << magnetic_field->gradientValue(old_position).cylinderEntries(old_position)
// << "\n";
// centrifugal force / q
force_over_charge += -(particle->mass_kg()/particle->charge_C() * force_over_charge += -(particle->mass_kg()/particle->charge_C() *
(v_parallel_norm*v_parallel_norm) * (v_parallel_norm*v_parallel_norm) *
kinematic::perpendicularVector(gradB, B) / kinematic::perpendicularVector(magnetic_field->
gradientValue(old_position).cartesianEntries(old_position), B) /
B_norm); B_norm);
// debugging
// const blitz::TinyVector<double, 3> tmpfrc = -(particle->mass_kg()/particle->charge_C() *
// (v_perp_norm*v_perp_norm/2) *
// magnetic_field->gradientValue(old_position).cartesianEntries(old_position) /
// B_norm);
// out << " gradB force/q: " << tmpfrc << "\n";
const blitz::TinyVector<double, 3> v_drift = const blitz::TinyVector<double, 3> v_drift = driftVelocity(force_over_charge, B);
driftVelocity(force_over_charge, B);
const double v_drift_norm = kinematic::norm(v_drift); 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 // guard against very large timesteps i.e. v ~ 0 -> timestep = Inf
// should be a very rare case (but has happend) // should be a very rare case
const double timestep = std::min( const double timestep = std::min(
stepsize / std::sqrt(v_parallel_norm*v_parallel_norm + stepsize / (v_parallel_norm + v_perp_norm + v_drift_norm),
v_perp_norm*v_perp_norm +
v_drift_norm*v_drift_norm),
max_time_alive); max_time_alive);
// out << " timestep: " << timestep << "\n";
const blitz::TinyVector<double, 3> movement_parallel = const blitz::TinyVector<double, 3> movement_parallel =
v_parallel * timestep; v_parallel * timestep;
@@ -340,12 +275,13 @@ void DriftMover::move(particle::Particle* particle,
const blitz::TinyVector<double, 3> force_over_charge_parallel = const blitz::TinyVector<double, 3> force_over_charge_parallel =
kinematic::parallelVector(force_over_charge, B); kinematic::parallelVector(force_over_charge, B);
const blitz::TinyVector<double, 3> dv_electric = timestep * const blitz::TinyVector<double, 3> dv_electric =
particle->charge_C() * force_over_charge_parallel / particle->mass_kg(); timestep * particle->charge_C() * force_over_charge_parallel / particle->mass_kg();
if (v_perp_norm > SimConstants::compare_epsilon) { if (v_perp_norm > SimConstants::compare_epsilon) {
const double gyro_radius = particle->mass_kg() * v_perp_norm / const double gyro_radius = particle->mass_kg() * v_perp_norm /
(B_norm * particle->charge_C()); (B_norm * particle->charge_C());
// out << " gyroradius: " << gyro_radius << "\n";
const blitz::TinyVector<double, 3> velocity_normal = const blitz::TinyVector<double, 3> velocity_normal =
(-1) * blitz::cross(B, v_perp); (-1) * blitz::cross(B, v_perp);
@@ -353,81 +289,67 @@ void DriftMover::move(particle::Particle* particle,
const blitz::TinyVector<double, 3> offset_to_gyro_center = const blitz::TinyVector<double, 3> offset_to_gyro_center =
gyro_radius * velocity_normal / kinematic::norm(velocity_normal); gyro_radius * velocity_normal / kinematic::norm(velocity_normal);
const blitz::TinyVector<double, 3> guiding_center =
(offset_to_gyro_center + old_position.cartesianEntries());
out << " guiding center: " << guiding_center << "\n";
out << " offset gyro: " << offset_to_gyro_center << "\n";
out << " movement parallel:" << movement_parallel << "\n";
const double gyro_frequency = const double gyro_frequency =
particle->charge_C() * B_norm / particle->mass_kg(); particle->charge_C() * B_norm / particle->mass_kg();
const double total_rotation_angle = -gyro_frequency * timestep; const double total_rotation_angle = -gyro_frequency * timestep;
out << " tot rot angle: " << total_rotation_angle << "\n";
const blitz::TinyVector<double, 3> movement_around_gyro_center = const blitz::TinyVector<double, 3> movement_around_gyro_center =
offset_to_gyro_center - offset_to_gyro_center - kinematic::rotateVector(offset_to_gyro_center,
kinematic::rotateVector(offset_to_gyro_center, B, B, total_rotation_angle);
total_rotation_angle); // out << " movement around gyro: " << movement_around_gyro_center << "\n";
const double v_parallel_new_norm = kinematic::norm(v_parallel + dv_electric);
// v_perp by conservation of magn. moment
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_new_norm =
sqrt(2*magnetic_moment*kinematic::norm(B_new)/particle->mass_kg());
const blitz::TinyVector<double, 3> v_perp_rotated = const blitz::TinyVector<double, 3> v_perp_rotated =
kinematic::rotateVector(v_perp, B, total_rotation_angle); kinematic::rotateVector(v_perp, B, total_rotation_angle);
// out << " v_perp,rotated: " << v_perp_rotated << "\n";
const double v_parallel_norm_new = DEBUG_LEVEL_3(out.str());
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 + particle->move(CartesianCoordinate(movement_parallel + movement_drift +
movement_around_gyro_center)); movement_around_gyro_center));
// project v_parallel and v_perp onto the new direction of B
const blitz::TinyVector<double, 3> v_parallel_new = const blitz::TinyVector<double, 3> v_parallel_new =
kinematic::parallelVector(v_parallel + dv_electric, B_new); kinematic::parallelVector(v_parallel + dv_electric, B_new);
const blitz::TinyVector<double, 3> v_perp_new = const blitz::TinyVector<double, 3> v_perpendicular_new =
kinematic::perpendicularVector(v_perp_rotated, B_new); kinematic::perpendicularVector(v_perp_rotated, B_new);
// calculation might be an issue if v_parallel_norm = 0 // use the new direction for the actual velocity (nec. for mu to be const)
// 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 = const blitz::TinyVector<double, 3> v_new =
v_parallel_new/kinematic::norm(v_parallel_new)*v_parallel_norm_new + v_parallel_new/kinematic::norm(v_parallel_new) * v_parallel_new_norm +
v_perp_new/kinematic::norm(v_perp_new)*v_perp_norm_new; v_perpendicular_new/kinematic::norm(v_perpendicular_new) * v_perp_new_norm;
particle->velocity(CartesianVector(v_new)); particle->velocity(CartesianVector(v_new));
} else { } else {
// neccessary to adjust as well? i.e. adjust the direction of v_parallel
particle->move(CartesianCoordinate(movement_parallel + movement_drift)); particle->move(CartesianCoordinate(movement_parallel + movement_drift));
particle->velocity(CartesianVector(v_parallel + dv_electric)); particle->velocity(CartesianVector(v_parallel + dv_electric));
} }
particle->increaseTimeAlive(timestep); 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);
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()));
}
const auto new_position = particle->position(); const auto new_position = particle->position();
died_in_bin = died_in_bin =
particle->specie()->terminator()->reachedMaxTimeAlive(particle); particle->specie()->terminator()->reachedMaxTimeAlive(particle);
if(died_in_bin) {
DEBUG_LEVEL_3("Mover: particle died in bin.");
}
changed_position_bin = changed_position_bin =
particle->specie()->dynamicDensityField()->changedPositionBin( particle->specie()->dynamicDensityField()->changedPositionBin(
@@ -437,28 +359,15 @@ void DriftMover::move(particle::Particle* particle,
particle->specie()->dynamicDensityField()->changedEnergyBin( particle->specie()->dynamicDensityField()->changedEnergyBin(
old_kinetic_energy, particle->kineticEnergy_eV()); 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);
if(changed_mu_bin) {
DEBUG_LEVEL_3("cos(pitch old): " + std::to_string(old_mu));
DEBUG_LEVEL_3("cos(pitch new): " + std::to_string(new_mu));
}
left_simulation_domain = left_simulation_domain =
particle->specie()->terminator()->leftSimulationDomain(particle); particle->specie()->terminator()->leftSimulationDomain(particle);
leftover_distance -= stepsize; leftover_distance -= stepsize;
DEBUG_LEVEL_3(out.str());
} }
// particle->specie()->dynamicDensityField()->logMovement(
// old_position, old_kinetic_energy, particle->timeInBin());
particle->specie()->dynamicDensityField()->logMovement( particle->specie()->dynamicDensityField()->logMovement(
old_position, old_kinetic_energy, old_mu, particle->timeInBin()); old_position, old_kinetic_energy, particle->timeInBin());
particle->resetTimeInBin(); particle->resetTimeInBin();
particle->specie()->currentCollector()->collect(particle, old_position); particle->specie()->currentCollector()->collect(particle, old_position);
} }
+4 -15
View File
@@ -20,17 +20,14 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie, Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position, const Coordinate& position,
const Vector& velocity, const Vector& velocity)
const double time_birth,
const double weight)
: specie_(specie), : specie_(specie),
position_(position), position_(position),
velocity_(velocity, position), velocity_(velocity, position),
id_(this->last_id_), id_(this->last_id_),
time_alive_s_(time_birth), time_alive_s_(0.),
time_in_bin_s_(0.), time_in_bin_s_(0.),
interaction_counter_(0), interaction_counter_(0) {
weight_(weight) {
last_id_++; last_id_++;
} }
@@ -110,15 +107,7 @@ void Particle::resetTimeInBin() {
} }
double Particle::timeInBin() const { double Particle::timeInBin() const {
return time_in_bin_s_*weight_; return time_in_bin_s_;
}
long int Particle::ID() const {
return id_;
}
double Particle::weight() const {
return weight_;
} }
} // namespace particle } // namespace particle
+57 -302
View File
@@ -1,5 +1,4 @@
#include "simulation/simulation.h" #include "simulation/simulation.h"
#include "mpi.h"
#include <numeric> #include <numeric>
#include <random> #include <random>
#include <vector> #include <vector>
@@ -21,7 +20,6 @@
#include "poisson_solver/poisson_solver.h" #include "poisson_solver/poisson_solver.h"
#include "IO/simulation_output.h" #include "IO/simulation_output.h"
#include "IO/restart.h"
#include "generators/electric_field_generator.h" #include "generators/electric_field_generator.h"
#include "generators/injector_generator.h" #include "generators/injector_generator.h"
@@ -31,9 +29,6 @@
#include "generators/species_generator.h" #include "generators/species_generator.h"
#include "generators/poisson_solver_generator.h" #include "generators/poisson_solver_generator.h"
#include "generators/gravity_field_generator.h" #include "generators/gravity_field_generator.h"
#include "generators/restart_generator.h"
#include "simulation/event_position_distribution.h"
#include "tools/simulation_time.h" #include "tools/simulation_time.h"
@@ -64,25 +59,16 @@ void Simulation::init(Parameter& parameter) {
poisson_solver_ = generator::buildPoissonSolver(parameter); poisson_solver_ = generator::buildPoissonSolver(parameter);
electric_field_->updateDynamicField(poisson_solver_->staticElectricField()); electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
DEBUG_LEVEL_0("Init cpu synchronizer.");
cpu_synchronizer_ = std::make_shared<CpuSynchronizer>();
DEBUG_LEVEL_3("Init done.");
Restart restarter = generator::buildRestart(parameter);
restarter.restart(tracked_species_, poisson_solver_.get(), random_.get());
// poisson solver is restarted -> set the electric field from the potential
electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
// make sure every proc is done with loading its restart info before
// writing the metadata
MPI_Barrier(MPI_COMM_WORLD);
DEBUG_LEVEL_0("Init output."); DEBUG_LEVEL_0("Init output.");
output_ = generator::buildSimulationOutput( output_ = generator::buildSimulationOutput(
parameter.jsonObjectFromBase({"Output"}), tracked_species_); parameter.jsonObjectFromBase({"Output"}), tracked_species_);
DEBUG_LEVEL_0("Output meta data."); DEBUG_LEVEL_0("Output meta data.");
output_->writeMetaData(tracked_species_, poisson_solver_); output_->writeMetaData(tracked_species_, poisson_solver_);
DEBUG_LEVEL_0("Init cpu synchronizer.");
cpu_synchronizer_ = std::make_shared<CpuSynchronizer>();
DEBUG_LEVEL_3("Init done.");
} }
int eventsThisCpu(int events_all_cpus) { int eventsThisCpu(int events_all_cpus) {
@@ -109,163 +95,43 @@ void Simulation::finalize() {
void Simulation::start() { void Simulation::start() {
SIM_INFO("Starting Simulation."); SIM_INFO("Starting Simulation.");
// stride wrt the number of beta decay events per CPU
const int event_stride = const int event_stride =
parameter_.intValue(json_path({"Simulation", "EventStride"}), 1); parameter_.intValue(json_path({"Simulation", "EventStride"}), 1);
const int total_simulated_events =
// number of timesteps to be simulated parameter_.intValue(json_path({"Simulation", "SimulatedEvents"}), 1);
const int number_timesteps = parameter_.intValue(json_path({"Simulation", SIM_INFO("Total simulated events: " + std::to_string(total_simulated_events));
"NumberTimesteps"}), 1);
// number of physical beta events defining the timescale through
// time_resolution_events/Activity
const int time_resolution_events =
parameter_.intValue(json_path({"Simulation", "TimeResolutionEvents"}),
MpiCommunication::mpiSize());
// number of beta decay events per timestep and CPU (will get normalized s.t.
// the physical number of particles is correct)
const int beta_decay_events =
parameter_.intValue(json_path{"Simulation", "BetaDecayEventsPerCPU"}, 1);
// weight of a particle created through beta decay wrt a physical particle
const double beta_particle_weight = time_resolution_events/
static_cast<double>(beta_decay_events*MpiCommunication::mpiSize());
// number of density events per timestep and CPU
const int density_events =
parameter_.intValue(json_path({"Simulation", "DensityEventsPerCPU"}), 0);
// calculate a 'stride' for the density events s.t. the same number of syncs
// would be performed
const int density_stride = std::ceil(density_events *
(static_cast<double>(event_stride)/beta_decay_events));
// calculate the scaling factor for the particle weight for particles
// drawn from the density
const double density_weight_factor =
1./(MpiCommunication::mpiSize()*density_events);
DEBUG_LEVEL_0("Density events per cpu: " + std::to_string(density_events));
SIM_INFO("Number of Timesteps: " + std::to_string(number_timesteps));
SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride)); SIM_INFO("Simulated events before cpu sync: " + std::to_string(event_stride));
const int events_this_cpu = eventsThisCpu(total_simulated_events);
int leftover_events_time_resolution = beta_decay_events; SIM_INFO("Events per cpu (approx.): " + std::to_string(events_this_cpu));
int leftover_density_events = density_events; int leftover_events = events_this_cpu;
const double delta_t = time_resolution_events*injector_->timePassed();
// if delta_t of the timer after creation and potential restart is 0, then
// it's indicative of no restart having occured (a simulation with a delta_t
// of 0 would not be sensible)
if(timer_->getDeltaT() != 0 && delta_t != timer_->getDeltaT()) {
std::stringstream out;
out << "Old delta t: " << timer_->getDeltaT();
out << "; new delta t: " << delta_t;
out << ". Currently not supported (leads to errors in the density calculated from "
"the loaded data)";
ERROR(out.str());
}
timer_->setDeltaT(delta_t);
injector_->initInjectionTimeDistribution(delta_t);
for(auto element: tracked_species_)
injector_->fillParticleNumbers(element.second);
int num_cpu_syncs = 0; int num_cpu_syncs = 0;
bool reset = true; while (leftover_events > 0) {
int timesteps = 0; int events_of_cylcle = eventsOfCycle(event_stride, leftover_events);
SIM_INFO("Leftover events on first cpu: " +
std::to_string(leftover_events));
processEvents(events_of_cylcle);
queue_.reserve(100); DEBUG_LEVEL_1("Leftover events: " + std::to_string(leftover_events));
leftover_events -= events_of_cylcle;
timer_->increaseTimestep(delta_t);
while (timesteps < number_timesteps) {
#if defined debug_level3
std::stringstream out;
out << "Timeinterval: " << timer_->time() << "s.";
DEBUG_LEVEL_3(out.str());
#endif
// calculate the number of beta events to be simulated before a
// cpu sync is done
int events_of_cycle =
eventsOfCycle(event_stride, leftover_events_time_resolution);
int density_events_of_cycle =
eventsOfCycle(density_stride, leftover_density_events);
DEBUG_LEVEL_1("Events of cycle: " + std::to_string(events_of_cycle));
DEBUG_LEVEL_1("Density Events of cycle: " +
std::to_string(density_events_of_cycle));
SIM_INFO("Processing timestep: " + std::to_string(timesteps));
SIM_INFO("Leftover events this timestep this CPU: " +
std::to_string(leftover_events_time_resolution));
SIM_INFO("Leftover density events this timestep this CPU: " +
std::to_string(leftover_density_events));
// process both density and beta events before a cpu synchronization
processDensityEvents(density_events_of_cycle, density_weight_factor);
processEvents(events_of_cycle, beta_particle_weight);
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timesteps));
DEBUG_LEVEL_1("Leftover events this timestep: " +
std::to_string(leftover_events_time_resolution));
leftover_events_time_resolution -= events_of_cycle;
leftover_density_events -= density_events_of_cycle;
reset = !(leftover_events_time_resolution > 0);
SIM_INFO("Cpu sync."); SIM_INFO("Cpu sync.");
SimulationTimer::eventStartPoint(std::string("CpuSync")); SimulationTimer::eventStartPoint(std::string("CpuSync"));
// 'reset' necessary as parameter to set the density for drawing cpu_synchronizer_->synchronize(tracked_species_);
// otherwise it would be more difficult to set it... (cpu synchronizer
// is a friend class of the density field, i.e. has access to the
// private members)
cpu_synchronizer_->synchronize(tracked_species_, reset);
num_cpu_syncs += 1; num_cpu_syncs += 1;
SimulationTimer::eventStopPoint(std::string("CpuSync")); SimulationTimer::eventStopPoint(std::string("CpuSync"));
// can probably be moved into the reset section and therefore
// the parameter 'reset' could probably be removed
SIM_INFO("Poisson step."); SIM_INFO("Poisson step.");
SimulationTimer::eventStartPoint(std::string("PoissonStep")); SimulationTimer::eventStartPoint(std::string("PoissonStep"));
// only solves the potential anew if 'reset' is true poisson_solver_->solvePotential(chargedensity(), num_cpu_syncs);
poisson_solver_->solvePotential(chargedensity(), reset);
electric_field_->updateDynamicField(poisson_solver_->staticElectricField()); electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
SimulationTimer::eventStopPoint(std::string("PoissonStep")); SimulationTimer::eventStopPoint(std::string("PoissonStep"));
SIM_INFO("Perform output."); SIM_INFO("Perform output.");
SimulationTimer::eventStartPoint(std::string("Output")); SimulationTimer::eventStartPoint(std::string("Output"));
output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get(), output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get());
random_->engine());
SimulationTimer::eventStopPoint(std::string("Output")); SimulationTimer::eventStopPoint(std::string("Output"));
SimulationTimer::eventStartPoint("Reset");
if(reset) {
SIM_INFO("Do resets and increase the timestep for timeresolution.");
for(auto& pair : tracked_species_) {
pair.second->dynamicDensityField()->resetDynamicDensityField();
pair.second->currentCollector()->resetCurrentCollector();
pair.second->deletionLogger()->resetDeletionLogger();
// the density from which new particles are drawn is only updated after a timestep
pair.second->positionDistributionFromDensity()->setMaximumDensity();
pair.second->positionDistributionFromDensity()
->setMaximumDensityAboveAndBelow(injector_->energySplit());
injector_->fillParticleNumbers(pair.second);
}
leftover_events_time_resolution = beta_decay_events;
leftover_density_events = density_events;
timer_->increaseTimestep(delta_t);
timesteps++;
}
SimulationTimer::eventStopPoint("Reset");
} }
} }
@@ -273,25 +139,20 @@ int particleNumberFromQueue(int queue_length, RandomNumbers* random) {
return random->rollUniform(0, queue_length); return random->rollUniform(0, queue_length);
} }
void Simulation::processEvents(int events, const double beta_particle_weight) { void Simulation::processEvents(int events) {
DEBUG_LEVEL_0("Processing events."); DEBUG_LEVEL_0("Processing events.");
std::vector<particle::Particle> particle_queue;
particle_queue.reserve(100);
int current_event = 0; int current_event = 0;
while ((current_event < events) || (!particle_queue.empty())) {
while ((current_event < events) || (!queue_.empty())) {
DEBUG_LEVEL_2("Current event: " + std::to_string(current_event)); DEBUG_LEVEL_2("Current event: " + std::to_string(current_event));
if (queue_.empty()) { if (particle_queue.empty()) {
std::vector<particle::Particle> new_particles;
current_event += 1; current_event += 1;
DEBUG_LEVEL_2("Inject particles to queue."); DEBUG_LEVEL_2("Inject particles to queue.");
SimulationTimer::eventStartPoint(std::string("ParticleInjection")); SimulationTimer::eventStartPoint(std::string("ParticleInjection"));
new_particles = determineInjectedParticles(random_.get(), std::vector<particle::Particle> new_particles =
beta_particle_weight); determineInjectedParticles(random_.get());
// construction of stringstream can take up a lot of computation time
// even if the debug output performs nothing therefore use the if defined
// preprocessor directive
#if defined debug_level3 #if defined debug_level3
for(auto& particle : new_particles) { for(auto& particle : new_particles) {
std::stringstream output_ss; std::stringstream output_ss;
@@ -303,100 +164,34 @@ void Simulation::processEvents(int events, const double beta_particle_weight) {
} }
#endif #endif
SimulationTimer::eventStopPoint(std::string("ParticleInjection")); SimulationTimer::eventStopPoint(std::string("ParticleInjection"));
DEBUG_LEVEL_2("Injected particles to queue."); DEBUG_LEVEL_2("Injected particles to queue.");
queue_.insert(queue_.end(), new_particles.begin(), particle_queue.insert(particle_queue.end(), new_particles.begin(),
new_particles.end()); new_particles.end());
} }
DEBUG_LEVEL_2("Particles in queue: " + DEBUG_LEVEL_2("Particles in queue: " + std::to_string(particle_queue.size()));
std::to_string(queue_.size()));
const int particle_number = const int particle_number =
particleNumberFromQueue(queue_.size(), random_.get()); particleNumberFromQueue(particle_queue.size(), random_.get());
// extract particle from queue here, so that an extension of the queue does // extract particle here from queue, so that an extension of the queue does
// not mess up the reference // not mess up the reference
particle::Particle particle = queue_.at(particle_number); particle::Particle particle = particle_queue.at(particle_number);
queue_.erase(queue_.begin() + particle_number); particle_queue.erase(particle_queue.begin() + particle_number);
processUntilTermination(particle); processUntilTermination(particle, particle_queue);
}
}
void Simulation::processDensityEvents(int events, const double weight_factor) {
DEBUG_LEVEL_0("Processing density events.");
int current_event = 0;
// calculate the number of particles currently contained within the densities
// of the different tracked species before injection in order to avoid
// the expensive recalculateDensityField funtion being calculated for every
// new injection event
std::map<std::string, double> particleNumbers;
for(auto& pair: tracked_species_) {
particleNumbers[pair.first] = (pair.second->densityForDrawing()->particleNumber());
// injector_->fillParticleNumbers(pair.second);
}
while ((current_event < events) || (!queue_.empty())) {
DEBUG_LEVEL_2("Current event: " + std::to_string(current_event));
if (queue_.empty()) {
std::vector<particle::Particle> new_particles;
DEBUG_LEVEL_2("Current density event: " + std::to_string(current_event));
SimulationTimer::eventStartPoint(std::string("DensityInjection"));
new_particles = determineInjectedDensityParticles(random_.get(),
weight_factor, current_event, particleNumbers);
SimulationTimer::eventStopPoint(std::string("DensityInjection"));
#if defined debug_level3
for(auto& particle : new_particles) {
std::stringstream output_ss;
output_ss << particle.specie()->name() << " with velocity (cart): ";
output_ss << particle.velocity().cartesianEntries();
output_ss << " and position (cart)";
output_ss << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str());
}
#endif
// if no new particles could be injected from the density, it is not possible
// that during another iteration cycle new particles will be injected
// (drawing field only changes after timesteps)
if(new_particles.empty()) {
return;
}
current_event += 1;
queue_.insert(queue_.end(), new_particles.begin(), new_particles.end());
}
DEBUG_LEVEL_2("Particles in queue: " +
std::to_string(queue_.size()));
const int particle_number =
particleNumberFromQueue(queue_.size(), random_.get());
// extract particle from queue here, so that an extension of the queue does
// not mess up the reference
particle::Particle particle = queue_.at(particle_number);
queue_.erase(queue_.begin() + particle_number);
processUntilTermination(particle);
} }
} }
void Simulation::processUntilTermination( void Simulation::processUntilTermination(
particle::Particle& particle) { particle::Particle& particle,
std::vector<particle::Particle>& particle_queue) {
DEBUG_LEVEL_3("Process particle until termination"); DEBUG_LEVEL_3("Process particle until termination");
DEBUG_LEVEL_3("Weight of the particle: " + std::to_string(particle.weight()));
while (particle.specie()->terminator()->isAlive(&particle)) { while (particle.specie()->terminator()->isAlive(&particle)) {
auto old_position = particle.position(); auto old_position = particle.position();
double old_energy = particle.kineticEnergy_eV(); double old_energy = particle.kineticEnergy_eV();
std::vector<double> macroscopic_cross_sections_m;
SimulationTimer::eventStartPoint(std::string("MFP calculation")); SimulationTimer::eventStartPoint(std::string("MFP calculation"));
const double mfp_m = meanFreePath(particle, random_.get(), const double mfp_m = meanFreePath(particle, random_.get());
macroscopic_cross_sections_m);
SimulationTimer::eventStopPoint(std::string("MFP calculation")); SimulationTimer::eventStopPoint(std::string("MFP calculation"));
SimulationTimer::eventStartPoint(std::string("Mover")); SimulationTimer::eventStartPoint(std::string("Mover"));
@@ -416,23 +211,21 @@ void Simulation::processUntilTermination(
if (particle.specie()->terminator()->reachedMaxTimeAlive( if (particle.specie()->terminator()->reachedMaxTimeAlive(
&particle)) { &particle)) {
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name() + DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name()
". Reached timeresolution."); +". Reached max time alive.");
if(particle.specie()->deletionLogger()) { if (particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.position(), particle.specie()->deletionLogger()->logDeletion(
DeletionType::max_time_alive); particle.position(), DeletionType::max_time_alive);
} }
break; break;
} else if (particle.specie()->terminator()->leftSimulationDomain( } else if (particle.specie()->terminator()->leftSimulationDomain(
&particle)) { &particle)) {
#if defined debug_level3
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name() DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name()
+ ". Left simulation domain."); + ". Left simulation domain.");
std::stringstream output_ss; std::stringstream output_ss;
output_ss << "Position (cyl): " << particle.position().cylinderEntries(); output_ss << "Position (cyl): " << particle.position().cylinderEntries();
output_ss << " (cart): " << particle.position().cartesianEntries(); output_ss << " (cart): " << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str()); DEBUG_LEVEL_3(output_ss.str());
#endif
if (particle.specie()->deletionLogger()) { if (particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.position(), particle.specie()->deletionLogger()->logDeletion(particle.position(),
DeletionType::wall); DeletionType::wall);
@@ -450,22 +243,19 @@ void Simulation::processUntilTermination(
std::to_string(particle.interactionCounter())); std::to_string(particle.interactionCounter()));
DEBUG_LEVEL_3("Ekin before interact: " + DEBUG_LEVEL_3("Ekin before interact: " +
std::to_string(particle.kineticEnergy_eV())); std::to_string(particle.kineticEnergy_eV()));
#if defined debug_level3
std::stringstream output_ss; std::stringstream output_ss;
output_ss << "Position (cyl): " << particle.position().cylinderEntries(); output_ss << "Position (cyl): " << particle.position().cylinderEntries();
// output_ss << "\n (cart): " << particle.position().cartesianEntries(); // output_ss << "\n (cart): " << particle.position().cartesianEntries();
DEBUG_LEVEL_3(output_ss.str()); DEBUG_LEVEL_3(output_ss.str());
#endif
SimulationTimer::eventStartPoint(std::string("Interaction")); SimulationTimer::eventStartPoint(std::string("Interaction"));
interaction::InteractionOutput output = interact(particle, random_.get(), interaction::InteractionOutput output = interact(particle, random_.get());
macroscopic_cross_sections_m);
SimulationTimer::eventStopPoint(std::string("Interaction")); SimulationTimer::eventStopPoint(std::string("Interaction"));
particle.increaseInteractionCounter(); particle.increaseInteractionCounter();
for (auto& new_particle : output.newParticles()) { for (auto& new_particle : output.newParticles()) {
queue_.push_back(new_particle); particle_queue.push_back(new_particle);
} }
if (output.deleteCurrentParticle()) { if (output.deleteCurrentParticle()) {
@@ -487,13 +277,11 @@ void Simulation::processUntilTermination(
} }
double Simulation::meanFreePath(particle::Particle& particle, double Simulation::meanFreePath(particle::Particle& particle,
RandomNumbers* random, RandomNumbers* random) {
std::vector<double>& macroscopic_cross_sections_m) {
double total_macroscopic_cross_section_m = 0.; double total_macroscopic_cross_section_m = 0.;
for (auto& interaction : particle.specie()->interactions()) { for (auto& interaction : particle.specie()->interactions()) {
double cross_section_tmp = interaction->macroscopicCrossSection(particle); total_macroscopic_cross_section_m +=
total_macroscopic_cross_section_m += cross_section_tmp; interaction->macroscopicCrossSection(particle);
macroscopic_cross_sections_m.push_back(cross_section_tmp);
} }
if (total_macroscopic_cross_section_m <= 0.) { if (total_macroscopic_cross_section_m <= 0.) {
@@ -510,15 +298,18 @@ double Simulation::meanFreePath(particle::Particle& particle,
interaction::InteractionOutput Simulation::interact( interaction::InteractionOutput Simulation::interact(
particle::Particle& particle, particle::Particle& particle,
RandomNumbers* random, RandomNumbers* random) {
std::vector<double>& macroscopic_cross_sections_m) { std::vector<double> macroscopic_cross_sections_m;
for (auto& interaction : particle.specie()->interactions()) {
macroscopic_cross_sections_m.push_back(
interaction->macroscopicCrossSection(particle));
}
const double total_macroscopic_cross_section_m = const double total_macroscopic_cross_section_m =
std::accumulate(macroscopic_cross_sections_m.begin(), std::accumulate(macroscopic_cross_sections_m.begin(),
macroscopic_cross_sections_m.end(), 0.0); macroscopic_cross_sections_m.end(), 0.0);
if (total_macroscopic_cross_section_m <= 0.) { if (total_macroscopic_cross_section_m <= 0.) {
// do nothing // do nothing
SIM_INFO("total mcs <= 0");
return interaction::InteractionOutput(); return interaction::InteractionOutput();
} else { } else {
std::discrete_distribution<int> interaction_decider( std::discrete_distribution<int> interaction_decider(
@@ -533,45 +324,9 @@ interaction::InteractionOutput Simulation::interact(
} }
std::vector<particle::Particle> Simulation::determineInjectedParticles( std::vector<particle::Particle> Simulation::determineInjectedParticles(
RandomNumbers* random, const double beta_particle_weight) { RandomNumbers* random) {
return injector_->rollNewParticles(random->engine(), timer_->time(), timer_->increaseTimestep(injector_->timePassed());
beta_particle_weight); return injector_->rollNewParticles(random->engine());
}
// weight_factor has to be such that particleNumber * weight_factor = weight
std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
RandomNumbers* random, const double weight_factor, const int current,
std::map<std::string, double>& particleNumbers) {
std::vector<particle::Particle> new_particles{};
if(!new_particles.empty()) {
ERROR("In drawing particles from the density:"
" the new particles vector is not empty at initialization");
}
const double injection_time = timer_->time() - timer_->getDeltaT();
for(auto& pair: tracked_species_) {
if (particleNumbers[pair.first] == 0) {
DEBUG_LEVEL_3("No particles in density of species: " + pair.second->name());
continue;
}
#if defined debug_level2
// if (current == 0) {
std::stringstream out;
out << pair.second->name();
out << "particle number from density: ";
out << particleNumbers[pair.first];
DEBUG_LEVEL_2(out.str());
// }
#endif
injector_->drawNewParticleFromDensityField(random->engine(),
pair.second, new_particles, magnetic_field_,
weight_factor, injection_time);
}
return new_particles;
} }
//maybe put that into the poisson solver //maybe put that into the poisson solver
+21 -18
View File
@@ -9,7 +9,6 @@
#include "simulation/parameter.h" #include "simulation/parameter.h"
#include "simulation/terminator.h" #include "simulation/terminator.h"
#include "simulation/velocity_distribution.h" #include "simulation/velocity_distribution.h"
#include "simulation/event_position_distribution.h"
namespace species { namespace species {
@@ -43,7 +42,7 @@ TrackedSpecie::TrackedSpecie(
std::shared_ptr<DynamicDensityField> density_field, std::shared_ptr<DynamicDensityField> density_field,
std::shared_ptr<VelocityDistribution> velocity_distribution, std::shared_ptr<VelocityDistribution> velocity_distribution,
std::shared_ptr<DriftVelocity> drift_velocity, std::shared_ptr<DriftVelocity> drift_velocity,
std::shared_ptr<DynamicDensityField> density_for_drawing) std::shared_ptr<DynamicDensityField> last_sync_density_field)
: Specie(type, name, mass_kg, charge_C), : Specie(type, name, mass_kg, charge_C),
mover_(mover), mover_(mover),
terminator_(terminator), terminator_(terminator),
@@ -53,12 +52,9 @@ TrackedSpecie::TrackedSpecie(
current_collector_(std::shared_ptr<CurrentCollector>(nullptr)), current_collector_(std::shared_ptr<CurrentCollector>(nullptr)),
velocity_distribution_(velocity_distribution), velocity_distribution_(velocity_distribution),
drift_velocity_(drift_velocity), drift_velocity_(drift_velocity),
density_for_drawing_(density_for_drawing), last_sync_density_field_(last_sync_density_field),
position_distribution_from_density_( last_sync_deletion_logger_(std::shared_ptr<DeletionLogger>(nullptr)),
std::make_shared<PositionDistributionFromDensity>(density_for_drawing)), last_sync_current_collector_(std::shared_ptr<CurrentCollector>(nullptr)) {}
velocity_distribution_from_density_(
std::make_shared<VelocityDistributionFromDensityField>(
density_for_drawing, mass_kg)) {}
DensityField* TrackedSpecie::densityField() { DensityField* TrackedSpecie::densityField() {
return density_field_.get(); return density_field_.get();
@@ -75,8 +71,8 @@ DynamicDensityField* TrackedSpecie::dynamicDensityField() {
return density_field_.get(); return density_field_.get();
} }
DynamicDensityField* TrackedSpecie::densityForDrawing() { DynamicDensityField* TrackedSpecie::lastSyncDensityField() {
return density_for_drawing_.get(); return last_sync_density_field_.get();
} }
Mover* TrackedSpecie::mover() { Mover* TrackedSpecie::mover() {
@@ -95,18 +91,16 @@ DeletionLogger* TrackedSpecie::deletionLogger() {
return deletion_logger_.get(); return deletion_logger_.get();
} }
DeletionLogger* TrackedSpecie::lastSyncDeletionLogger() {
return last_sync_deletion_logger_.get();
}
CurrentCollector* TrackedSpecie::currentCollector() { CurrentCollector* TrackedSpecie::currentCollector() {
return current_collector_.get(); return current_collector_.get();
} }
PositionDistributionFromDensity* CurrentCollector* TrackedSpecie::lastSyncCurrentCollector() {
TrackedSpecie::positionDistributionFromDensity() { return last_sync_current_collector_.get();
return position_distribution_from_density_.get();
}
VelocityDistributionFromDensityField*
TrackedSpecie::velocityDistributionFromDensityField() {
return velocity_distribution_from_density_.get();
} }
std::vector<std::shared_ptr<interaction::Interaction>> std::vector<std::shared_ptr<interaction::Interaction>>
@@ -123,11 +117,20 @@ void TrackedSpecie::deletionLogger(std::shared_ptr<DeletionLogger> new_logger) {
deletion_logger_ = new_logger; deletion_logger_ = new_logger;
} }
void TrackedSpecie::lastSyncDeletionLogger(std::shared_ptr<DeletionLogger> new_logger) {
last_sync_deletion_logger_ = new_logger;
}
void TrackedSpecie::currentCollector( void TrackedSpecie::currentCollector(
std::shared_ptr<CurrentCollector> new_collector) { std::shared_ptr<CurrentCollector> new_collector) {
current_collector_ = new_collector; current_collector_ = new_collector;
} }
void TrackedSpecie::lastSyncCurrentCollector(
std::shared_ptr<CurrentCollector> new_collector) {
last_sync_current_collector_ = new_collector;
}
BackgroundSpecie::BackgroundSpecie( BackgroundSpecie::BackgroundSpecie(
ImplementedSpecies type, ImplementedSpecies type,
std::string name, std::string name,
+1 -3
View File
@@ -2,7 +2,6 @@
#include "simulation/errors.h" #include "simulation/errors.h"
#include "simulation/geometry.h" #include "simulation/geometry.h"
#include "simulation/density_field.h"
Terminator::Terminator(long int max_interactions, Terminator::Terminator(long int max_interactions,
double max_time_alive, double max_time_alive,
@@ -32,8 +31,7 @@ bool Terminator::reachedMaxInteractions(
return particle->interactionCounter() > max_interactions_; return particle->interactionCounter() > max_interactions_;
} }
bool Terminator::reachedMaxTimeAlive(const particle::Particle* particle) const { bool Terminator::reachedMaxTimeAlive(const particle::Particle* particle) const {
return particle->timeAlive() >= particle->specie()->dynamicDensityField() return particle->timeAlive() > max_time_alive_;
->physicalTime();
} }
bool Terminator::leftSimulationDomain( bool Terminator::leftSimulationDomain(
+1 -14
View File
@@ -1,7 +1,6 @@
#include "simulation/timer.h" #include "simulation/timer.h"
Timer::Timer() : current_time_s_(0.), Timer::Timer() : current_time_s_(0.) {}
delta_t_time_resolution_(0.) {}
double Timer::time() const { double Timer::time() const {
return current_time_s_; return current_time_s_;
@@ -14,15 +13,3 @@ void Timer::increaseTimestep(double time_s) {
void Timer::setTime(double time_s) { void Timer::setTime(double time_s) {
current_time_s_ = time_s; current_time_s_ = time_s;
} }
void Timer::resetTime() {
setTime(0.);
}
void Timer::setDeltaT(double deltaT) {
delta_t_time_resolution_ = deltaT;
}
double Timer::getDeltaT() const {
return delta_t_time_resolution_;
}
-280
View File
@@ -3,22 +3,6 @@
#include "simulation/drift_velocity.h" #include "simulation/drift_velocity.h"
#include "simulation/kinematic.h" #include "simulation/kinematic.h"
#include "simulation/velocity_distribution_function.h" #include "simulation/velocity_distribution_function.h"
#include "simulation/density_field.h"
#include "simulation/electromagnetic_field.h"
#include "simulation/errors.h"
// utility function returning a unit vector perpendicular to the given
// (cartesian) TinyVector
blitz::TinyVector<double, 3> perpendicularNormalVector(
blitz::TinyVector<double, 3> vector) {
blitz::TinyVector<double, 3> result(0,0,0);
result[0] = std::copysign(vector[2], vector[0]);
result[1] = std::copysign(vector[2], vector[1]);
result[2] = -std::copysign(std::fabs(vector[0] + std::fabs(vector[1])),
vector[2]);
return result / kinematic::norm(result);
}
VelocityDistributionFromFunction::VelocityDistributionFromFunction( VelocityDistributionFromFunction::VelocityDistributionFromFunction(
std::shared_ptr<VelocityDistributionFunction> fv) std::shared_ptr<VelocityDistributionFunction> fv)
@@ -29,267 +13,3 @@ CartesianVector VelocityDistributionFromFunction::rollVelocity(
std::mt19937* engine) { std::mt19937* engine) {
return fv_->rollVelocity(engine); return fv_->rollVelocity(engine);
} }
VelocityDistributionFromDensityField::VelocityDistributionFromDensityField(
std::shared_ptr<DynamicDensityField> density_field, double mass_kg):
density_field_(density_field),
energyBinBorders_(density_field->energyBinning()->binBorders()),
pitchAngleBinBorders_(density_field->pitchAngleBinning()->binBorders()),
theta_distribution_(std::uniform_real_distribution<double>(0.,1.)),
mass_kg_(mass_kg) {
// necessary to include the underflow bin in the energy domain
energyBinBorders_.insert(energyBinBorders_.begin(), 0);
}
// not important as of now since it's meant for drawing a velocity from the
// pitch angle distribution and not to be used in an interaction context in which
// the drift velocity is necessary for the determination of the cross section
// (might be possible to extract from the pitch angle dist or from the current)
// returns a 0 CartesianVector
CartesianVector VelocityDistributionFromDensityField::driftVelocity_ms(
const CylinderVector& position) {
return CartesianVector(blitz::TinyVector<double, 3> (0,0,0));
}
CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
std::piecewise_constant_distribution<double> energy_dist(
energyBinBorders_.begin(),
energyBinBorders_.end(),
energyValues.begin());
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> pitchAngle_dist(
pitchAngleBinBorders_.begin(),
pitchAngleBinBorders_.end(),
pitchAngleValues.begin());
double pitchAngle = pitchAngle_dist(*engine);
// construct the velocity
const double theta = theta_distribution_(*engine)*2*M_PI;
blitz::TinyVector<double, 3> zDirection(0,0,1);
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_);
// vector perpendicular to e_z
blitz::TinyVector<double, 3> v_perp(1,0,0);
blitz::TinyVector<double, 3> v_direction = pitchAngle * zDirection
+ std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, zDirection, theta);
return CartesianVector(v_direction * vMagnitude);
}
CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine,
std::shared_ptr<MagneticField> magnetic_field) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
std::piecewise_constant_distribution<double> energy_dist(
energyBinBorders_.begin(),
energyBinBorders_.end(),
energyValues.begin());
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> pitchAngle_dist(
pitchAngleBinBorders_.begin(),
pitchAngleBinBorders_.end(),
pitchAngleValues.begin());
double pitchAngle = pitchAngle_dist(*engine);
// construct the velocity
const double theta = theta_distribution_(*engine)*2*M_PI;
blitz::TinyVector<double, 3> cartesianB_values =
magnetic_field->value(position).cartesianEntries(position);
const double Bmagnitude = kinematic::norm(cartesianB_values);
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_);
blitz::TinyVector<double, 3> v_perp =
perpendicularNormalVector(cartesianB_values);
blitz::TinyVector<double, 3> v_direction = pitchAngle
* cartesianB_values/Bmagnitude
+ std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, cartesianB_values, theta);
return CartesianVector(v_direction * vMagnitude);
}
/*
Note: right now assumes that the density (either above or below)
the threshold value is non-zero, i.e. in the case that
that is not the case will create no sensible result
*/
CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine,
std::shared_ptr<MagneticField> magnetic_field,
const int E_th_bin, const bool above) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
auto bordersBeginIterator = energyBinBorders_.begin();
auto bordersEndIterator = energyBinBorders_.end();
auto valuesBeginIterator = energyValues.begin();
if(above) {
bordersBeginIterator += E_th_bin - density_field_->energyBinning()->binIndexMin();
valuesBeginIterator = energyValues(blitz::Range(E_th_bin, blitz::toEnd)).begin();
} else {
if(E_th_bin == density_field_->energyBinning()->binIndexMin()) {
return CartesianVector(blitz::TinyVector<double, 3>(0,0,0));
}
bordersEndIterator = bordersBeginIterator + E_th_bin
- density_field_->energyBinning()->binIndexMin() + 1;
}
std::piecewise_constant_distribution<double> energy_dist(
bordersBeginIterator,
bordersEndIterator,
valuesBeginIterator);
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> pitchAngle_dist(
pitchAngleBinBorders_.begin(),
pitchAngleBinBorders_.end(),
pitchAngleValues.begin());
double pitchAngle = pitchAngle_dist(*engine);
#ifdef debug
if((std::isnan(pitchAngle)) || (std::isnan(energy_eV))) {
std::stringstream out;
above ? out << "Above" : out << "Below";
out << " threshold bin of " << E_th_bin;
out << "\npitchAngle: " << pitchAngle;
out << "\nenergy value: " << energy_eV;
out << "\nenergy values: " << energyValues;
out << "\npitch angle values: " << pitchAngleValues;
out << "\nenergy bin borders: [ ";
for(auto element : energyBinBorders_) {
out << element << " ";
}
out << "]";
ERROR(out.str());
}
#endif
// construct the velocity
const double theta = theta_distribution_(*engine)*2*M_PI;
blitz::TinyVector<double, 3> cartesianB_values =
magnetic_field->value(position).cartesianEntries(position);
const double Bmagnitude = kinematic::norm(cartesianB_values);
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_);
blitz::TinyVector<double, 3> v_perp =
perpendicularNormalVector(cartesianB_values);
blitz::TinyVector<double, 3> v_direction = pitchAngle
* cartesianB_values/Bmagnitude
+ std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, cartesianB_values, theta);
return CartesianVector(v_direction * vMagnitude);
}
CartesianVector VelocityDistributionFromDensityField::rollVelocity(
const Coordinate& position, std::mt19937* engine,
const int E_th_bin, const bool above) {
// draw energy from DynamicDensityField
blitz::Array<double, 1> energyValues = density_field_->
sliceSpectrumArray(position);
auto bordersBeginIterator = energyBinBorders_.begin();
auto bordersEndIterator = energyBinBorders_.end();
auto valuesBeginIterator = energyValues.begin();
if(above) {
bordersBeginIterator += E_th_bin - density_field_->energyBinning()->binIndexMin();
valuesBeginIterator = energyValues(blitz::Range(E_th_bin, blitz::toEnd)).begin();
} else {
if(E_th_bin == density_field_->energyBinning()->binIndexMin()) {
return CartesianVector(blitz::TinyVector<double, 3>(0,0,0));
}
bordersEndIterator = bordersBeginIterator +
E_th_bin - density_field_->energyBinning()->binIndexMin();
}
std::piecewise_constant_distribution<double> energy_dist(
bordersBeginIterator,
bordersEndIterator,
valuesBeginIterator);
double energy_eV = energy_dist(*engine);
// draw pitch angle from DynamicDensityField
blitz::Array<double, 1> pitchAngleValues = density_field_->
sliceTimeInBinArray(position, energy_eV);
std::piecewise_constant_distribution<double> pitchAngle_dist(
pitchAngleBinBorders_.begin(),
pitchAngleBinBorders_.end(),
pitchAngleValues.begin());
double pitchAngle = pitchAngle_dist(*engine);
// construct the velocity
const double theta = theta_distribution_(*engine)*2*M_PI;
blitz::TinyVector<double, 3> cartesianB_values(0,0,1);
const double Bmagnitude = kinematic::norm(cartesianB_values);
const double vMagnitude = kinematic::velocity(energy_eV, mass_kg_);
blitz::TinyVector<double, 3> v_perp(1,0,0);
blitz::TinyVector<double, 3> v_direction = pitchAngle
* cartesianB_values/Bmagnitude
+ std::sqrt(1 - pitchAngle*pitchAngle)
* kinematic::rotateVector(v_perp, cartesianB_values, theta);
return CartesianVector(v_direction * vMagnitude);
}