Electrons are explicitly stored between timesteps

and can be dumped using MPI-IO.
Restarts read particles from earlier output.
This commit is contained in:
2025-08-11 09:18:51 +02:00
parent 0dd65d38f3
commit 76a93f5aa4
16 changed files with 781 additions and 81 deletions
+123
View File
@@ -0,0 +1,123 @@
#ifndef MPI_PARTICLE_FORMAT_H
#define MPI_PARTICLE_FORMAT_H
#include <cstdint>
#include "mpi.h"
/* File format (as in ACRONYM):
*
* mpi_io_header
* <padding>
* cpu_header[n_cpus]
* <padding>
* data_of_cpu_1 <padding>
* data_of_cpu_2 <padding>
* ...
*/
/* file header*/
struct mpi_io_header_t {
std::uint64_t magic;
std::uint64_t cpu_header_offset;
std::uint32_t num_cpus;
double dt;
bool verify() {
// Sanity Check if file is the right format
if(magic != ((std::uint64_t)'KA'<<32) + 'RL') {
return false;
}
if(dt < 0) {
return false;
}
return true;
}
};
/* per-CPU header */
struct cpu_header_t {
std::uint64_t num_particles;
std::uint64_t file_offset;
};
// seems to work only if alignment is a power of 2
static std::uint64_t pad_to_blocksize(std::uint64_t size, std::uint64_t alignment) {
size &= ~(alignment - 1);
size += alignment;
return size;
}
#ifdef MPI_VERSION
#ifndef MPI_UINT32_T
#define MPI_UNIT32_T MPI_UNSIGNED
#endif
#ifndef MPI_UINT64_T
#define MPI_UNIT64_T MPI_UNSIGNED_LONG_LONG
#endif
/* Custom MPI data types for the header structs */
static MPI_Datatype build_file_header_type() {
int status;
MPI_Datatype type;
int blocklengths[4];
MPI_Aint disps[4];
MPI_Datatype types[4];
disps[0] = offsetof(mpi_io_header_t, magic);
types[0] = MPI_UINT64_T;
blocklengths[0] = 1;
disps[1] = offsetof(mpi_io_header_t, cpu_header_offset);
types[1] = MPI_UINT64_T;
blocklengths[1] = 1;
disps[2] = offsetof(mpi_io_header_t, num_cpus);
types[2] = MPI_UINT32_T;
blocklengths[2] = 1;
disps[3] = offsetof(mpi_io_header_t, dt);
types[3] = MPI_DOUBLE;
blocklengths[3] = 1;
status = MPI_Type_create_struct(4, blocklengths, disps, types, &type);
status |= MPI_Type_commit(&type);
if(status) {
fprintf(stderr, "Creation of the data type \"file_header\" failed!\n");
return 0;
}
return type;
}
static MPI_Datatype build_cpu_header_type() {
int status;
MPI_Datatype type;
int blocklengths[2];
MPI_Aint disps[2];
MPI_Datatype types[2];
disps[0] = offsetof(cpu_header_t, num_particles);
types[0] = MPI_UINT64_T;
blocklengths[0] = 1;
disps[1] = offsetof(cpu_header_t, file_offset);
types[1] = MPI_UINT64_T;
blocklengths[1] = 1;
status = MPI_Type_create_struct(2, blocklengths, disps, types, &type);
status |= MPI_Type_commit(&type);
if(status) {
fprintf(stderr, "Creation of the data type \"cpu_header\" failed!\n");
return 0;
}
return type;
}
#endif /* MPI_VERSION */
#endif /* MPI_PARTICLE_FORMAT_H */
+23
View File
@@ -0,0 +1,23 @@
#ifndef MPI_PARTICLE_READER_H
#define MPI_PARTICLE_READER_H
#include <string>
#include <vector>
namespace particle {
class SerializedParticle;
}
class MpiParticleReader {
public:
MpiParticleReader(std::string directory, std::string filename, int restart_at);
MpiParticleReader(std::string absolute_filename);
MpiParticleReader(std::string abs_filename_without_extension, int restart_at);
void readParticles(std::vector<particle::SerializedParticle>& storage_queue);
private:
std::string absolute_filename_;
};
#endif /* MPI_PARTICLE_READER_H */
+27
View File
@@ -0,0 +1,27 @@
#ifndef MPI_PARTICLE_WRITER_H
#define MPI_PARTICLE_WRITER_H
#include <string>
#include <vector>
namespace particle {
class SerializedParticle;
}
class MpiParticleWriter {
public:
MpiParticleWriter(std::string directory = "./output",
std::string filename = "output",
int fs_blocksize = 4096);
void output_particles(std::vector<particle::SerializedParticle>& particles,
int cpu_sync, double dt);
private:
std::string directory_;
std::string filename_;
void createFolder(std::string directory);
int fs_blocksize_;
};
#endif /* MPI_PARTICLE_WRITER_H */
+14 -3
View File
@@ -4,14 +4,20 @@
#include <string>
#include <map>
#include <memory>
#include <vector>
#include "IO/hdf5_reader.h"
#include "IO/mpi_particle_reader.h"
namespace species {
class TrackedSpecie;
enum class ImplementedSpecies;
}; // namespace species
namespace particle {
class SerializedParticle;
};
class DynamicDensityField;
class PoissonSolver;
class RandomNumbers;
@@ -23,11 +29,14 @@ class RandomNumbers;
// 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);
// Restart(bool do_restart, std::string absolute_filename,
// std::string restart_identifier);
Restart(bool do_restart, std::string absolute_filename_without_extension,
std::string restart_identifier, int particle_restart_at);
void restart(std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, RandomNumbers* random_numbers);
PoissonSolver* poisson_solver, RandomNumbers* random_numbers,
std::vector<particle::SerializedParticle>& storage_queue);
private:
void restartTimer(species::TrackedSpecie* reference_specie);
@@ -36,9 +45,11 @@ class Restart {
// only load in the potential and calc the electric field
void restartPoissonSolver(PoissonSolver* solver);
void restartRandomNumbers(RandomNumbers* random);
void restartParticles(std::vector<particle::SerializedParticle>& storage_queue);
bool do_restart_;
std::string restart_identifier_; // i.e. "LastSyncPeriod" or "SyncPeriod_*"
Hdf5Reader reader_;
MpiParticleReader particle_reader_;
};
#endif /* RESTART_H */
+11 -2
View File
@@ -7,6 +7,7 @@
#include <vector>
#include <random>
#include "IO/hdf5_writer.h"
#include "IO/mpi_particle_writer.h"
class DynamicDensityField;
class CurrentBorder;
@@ -30,13 +31,15 @@ struct OutputTask {
class SimulationOutput {
public:
SimulationOutput(const std::string& output_folder,
const std::string& output_filename);
const std::string& output_filename,
int fs_blocksize=4096);
void addDensityFieldOutput(OutputTask task);
void addCurrentBorderOutput(OutputTask task);
void addDeletionLoggerOutput(OutputTask task);
void setPotentialOutput(OutputTask task);
void setRestartInfoOutput(OutputTask task);
void setParticleOutput(OutputTask task);
void writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
@@ -45,7 +48,8 @@ class SimulationOutput {
void writeSimulationData(
int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver, std::mt19937* engine);
PoissonSolver* poisson_solver, std::mt19937* engine,
std::vector<particle::SerializedParticle>& storage_queue);
private:
std::vector<OutputTask> tasks_density_fields_;
@@ -53,8 +57,10 @@ class SimulationOutput {
std::vector<OutputTask> tasks_deletion_logger_;
OutputTask task_potential_;
OutputTask task_rng_;
OutputTask task_particles_;
Hdf5Writer writer;
MpiParticleWriter particle_writer;
void writeSimulationData(DynamicDensityField* density_field,
std::string species_path,
@@ -109,6 +115,9 @@ class SimulationOutput {
void writeRestartData(std::mt19937* engine, int cpu_sync,
bool overwrite_last);
void writeRandomEngineState(std::mt19937* engine, std::string path);
void writeParticles(std::vector<particle::SerializedParticle>& particles,
int cpu_sync, double dt);
};
#endif /* SIMULATION_OUTPUT_H */
+33 -1
View File
@@ -5,8 +5,35 @@
#include "simulation/coordinates.h"
#include "simulation/species.h"
#include <map>
class MpiParticleReader;
namespace particle {
class SerializedParticle {
public:
SerializedParticle(double time_birth, double weight,
blitz::TinyVector<double, 3> cart_pos,
blitz::TinyVector<double, 3> cart_vel,
std::string spec_name);
SerializedParticle() {};
double timeBirth();
double weight();
blitz::TinyVector<double, 3> cartesianPosition();
blitz::TinyVector<double, 3> cartesianVelocity();
std::string specieName();
private:
double time_birth_;
blitz::TinyVector<double, 3> cartesian_position_;
blitz::TinyVector<double, 3> cartesian_velocity_;
// has to be null terminated
std::array<char, 16> specie_name_;
double weight_;
};
class Particle {
public:
// Particle(std::shared_ptr<species::TrackedSpecie> specie,
@@ -18,6 +45,9 @@ class Particle {
const double time_birth,
const double weight);
Particle(particle::SerializedParticle sparticle, std::map<std::string,
std::shared_ptr<species::TrackedSpecie>>& tracked_species);
void position(const Coordinate& new_position);
CartesianCoordinate cartesianPosition() const;
CylinderCoordinate cylinderPosition() const;
@@ -52,9 +82,11 @@ class Particle {
void indexNextInteration(const int index) { index_next_interaction_ = index; };
int indexNextInteraction() { return index_next_interaction_; };
void deposited();
void deposited(bool truthValue=true);
bool wasDeposited();
particle::SerializedParticle serialize();
private:
double weight_;
bool deposited_ = false;
+1 -1
View File
@@ -90,7 +90,7 @@ class Simulation {
std::shared_ptr<CpuSynchronizer> cpu_synchronizer_;
std::vector<particle::Particle> queue_;
std::vector<particle::Particle> storage_queue_[2];
std::vector<particle::SerializedParticle> storage_queue_[2];
int active_storage = 0;
int inactive_storage = 1;
+148
View File
@@ -0,0 +1,148 @@
#include "IO/mpi_particle_reader.h"
#include "IO/mpi_particle_format.h"
#include "simulation/mpi_communication.h"
#include "simulation/particle.h"
#include "mpi.h"
// filename has to NOT include the ".mpi" component!
MpiParticleReader::MpiParticleReader(std::string directory, std::string filename,
int restart_at):
absolute_filename_(directory + "/" + filename + "-CPUSync-"
+ std::to_string(restart_at) + ".mpi") {}
MpiParticleReader::MpiParticleReader(std::string absolute_filename):
absolute_filename_(absolute_filename) {}
MpiParticleReader::MpiParticleReader(std::string abs_filename_without_extension,
int restart_at):
absolute_filename_(abs_filename_without_extension + "-CPUSync-" +
std::to_string(restart_at) + ".mpi") {}
void MpiParticleReader::readParticles(
std::vector<particle::SerializedParticle>& storage_queue) {
MPI_Comm io_comm;
int io_rank;
io_comm = MPI_COMM_WORLD;
io_rank = MpiCommunication::mpiRank();
#ifdef debug
DEBUG_LEVEL_0("Reading particles from: " + absolute_filename_);
#endif
int status;
MPI_Datatype particle_type;
if(sizeof(particle::SerializedParticle) % sizeof(double) != 0) {
ERROR("Size of SerializedParticle is not a multiple of the size of double!");
}
status = MPI_Type_contiguous(sizeof(particle::SerializedParticle)/sizeof(double),
MPI_DOUBLE, &particle_type);
status |= MPI_Type_commit(&particle_type);
if(status) {
ERROR("Particle data type could not be defined!");
}
MPI_Info info;
MPI_Info_create(&info);
// open file
MPI_File file;
MPI_Status mstatus;
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reading particles from: " + absolute_filename_);
#endif
status = MPI_File_open(io_comm, (char*)absolute_filename_.c_str(),
MPI_MODE_RDONLY, info, &file);
if(status) {
ERROR("Particle file \'" + absolute_filename_ + "\' could not be opened!");
}
//read file header
MPI_Datatype file_header_type = build_file_header_type();
mpi_io_header_t file_header;
status = MPI_File_set_view(file, 0, file_header_type, file_header_type,
(char*)"native", info);
if(status) {
ERROR("View for file header could not be set!");
}
status = MPI_File_read_all(file, &file_header, 1, file_header_type, &mstatus);
if(status) {
ERROR("File header could not be read (status: " + std::to_string(status) +
")!");
}
if(!file_header.verify()) {
ERROR("File header does not verify!");
}
// read CPU header
std::uint64_t headeroffset = file_header.cpu_header_offset +
sizeof(cpu_header_t)*io_rank;
MPI_Datatype cpu_header_type = build_cpu_header_type();
cpu_header_t cpu_header;
status = MPI_File_set_view(file, headeroffset, cpu_header_type, cpu_header_type,
(char*)"native", info);
if(status) {
ERROR("File view for the CPU header could not be set!");
}
status = MPI_File_read_all(file, &cpu_header, 1, cpu_header_type, &mstatus);
if(status) {
ERROR("CPU header could not be read!");
}
storage_queue.reserve(cpu_header.num_particles);
#if defined(debug_level1)
{
std::stringstream out;
out << io_rank << ": trying to read " << cpu_header.num_particles;
out << " many particles";
DEBUG_LEVEL_1(out.str());
}
#endif
// set file view to the part where the particles are stored
status = MPI_File_set_view(file, cpu_header.file_offset, MPI_DOUBLE,
particle_type, (char*)"native", info);
if(status) {
ERROR("File view for the Particles could not be set!");
}
storage_queue.resize(cpu_header.num_particles);
// read the particles
status = MPI_File_read_all(file, storage_queue.data(), cpu_header.num_particles,
particle_type, &mstatus);
if(status) {
ERROR("Particles could not be read (status: " + std::to_string(status) +
")!");
}
#ifdef debug_level1
{
std::stringstream out;
out << io_rank << ": number of particles in queue: " << storage_queue.size();
out << "\nposition of first serialized particle: " << storage_queue[0].cartesianPosition();
out << "\nvelocity of first serialized particle: " << storage_queue[0].cartesianVelocity();
out << "\nweight of first serialized particle: " << storage_queue[0].weight();
out << "\nspecname of first serialized particle: " << storage_queue[0].specieName();
out << "\ntbirth of fisrt serialized particle: " << storage_queue[0].timeBirth();
DEBUG_LEVEL_1(out.str());
}
#endif
// close everything
MPI_File_close(&file);
MPI_Type_free(&particle_type);
MPI_Type_free(&file_header_type);
MPI_Type_free(&cpu_header_type);
MPI_Info_free(&info);
}
+178
View File
@@ -0,0 +1,178 @@
#include <sys/stat.h>
#include "IO/mpi_particle_writer.h"
#include "IO/mpi_particle_format.h"
#include "simulation/particle.h"
#include "simulation/mpi_communication.h"
#include "simulation/errors.h"
void MpiParticleWriter::createFolder(std::string directory) {
mkdir(directory.c_str(), 0755);
}
MpiParticleWriter::MpiParticleWriter(std::string directory,
std::string filename,
int fs_blocksize) :
directory_(directory),
filename_(filename),
fs_blocksize_(fs_blocksize) {
createFolder(directory_);
}
void MpiParticleWriter::output_particles(
std::vector<particle::SerializedParticle>& particles,
int cpu_sync, double dt) {
int status;
std::stringstream path;
path << directory_ << "/" << filename_ << "-CPUSync-" << cpu_sync << ".mpi";
int io_rank = MpiCommunication::mpiRank();
int total_procs = MpiCommunication::mpiSize();
MPI_Comm io_comm = MPI_COMM_WORLD;
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Starting MPI particle output: " + path.str());
#endif
// size of headers
std::uint64_t file_header_size = pad_to_blocksize(sizeof(mpi_io_header_t),
fs_blocksize_);
std::uint64_t cpu_headers_size = pad_to_blocksize(file_header_size
+ sizeof(cpu_header_t), fs_blocksize_);
// commnicate the number of particles on all cpus
std::uint64_t* part_bytes_in = new uint64_t[total_procs];
std::uint64_t* part_bytes = new uint64_t[total_procs];
for(int i = 0; i < total_procs; i++) {
part_bytes_in[i] = 0;
}
part_bytes_in[io_rank] = particles.size() * sizeof(particle::SerializedParticle);
part_bytes_in[io_rank] = pad_to_blocksize(part_bytes_in[io_rank], fs_blocksize_);
MPI_Allreduce(part_bytes_in, part_bytes, total_procs,
MPI_LONG_LONG, MPI_SUM, io_comm);
delete[] part_bytes_in;
// Calculate the offset from the prefix sum
std::uint64_t tmp = 0;
std::uint64_t prev = 0;
for(int i = 0; i < total_procs; i++) {
tmp += part_bytes[i];
part_bytes[i] = prev;
prev = tmp;
}
// data type of a single particle
MPI_Datatype particle_type;
if(sizeof(particle::SerializedParticle) % sizeof(double) != 0) {
// since type is created as a set of MPI_DOUBLES
ERROR("Size of particle is not a multiple of the size of double!");
}
status = MPI_Type_contiguous(sizeof(particle::SerializedParticle)/sizeof(double),
MPI_DOUBLE, &particle_type);
status |= MPI_Type_commit(&particle_type);
if(status) {
delete[] part_bytes;
ERROR("Mpi particle data type could not be created!");
}
// enable collective buffering
MPI_Info info;
// most rudamentary usage, might need to be improved
MPI_Info_create(&info);
// open the file
MPI_File file;
MPI_Status mstatus;
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Writing particles to " + path.str());
#endif
status = MPI_File_open(io_comm, (char*)path.str().c_str(),
MPI_MODE_WRONLY|MPI_MODE_CREATE, info, &file);
if(status) {
ERROR("File could not be opened or created! " + path.str());
}
// collectively write file header
MPI_Datatype file_header_type = build_file_header_type();
mpi_io_header_t file_header;
file_header.magic = ((std::uint64_t)'KA' << 32) + (uint64_t)'RL';
file_header.num_cpus = total_procs;
file_header.cpu_header_offset = file_header_size;
file_header.dt = dt;
status = MPI_File_set_view(file, 0, file_header_type, file_header_type,
(char*)"native", info);
if(status) {
ERROR("View fo rthe file header could not be set!");
}
status = MPI_File_write_all(file, &file_header, 1, file_header_type, &mstatus);
if(status) {
ERROR("File header could not be written (status: " + std::to_string(status) + ")");
}
MPI_Type_free(&file_header_type);
// calculate where the header of this cpu starts
std::uint64_t headeroffset = file_header_size + sizeof(cpu_header_t)*io_rank;
// calcualte the offset to the data
std::uint64_t dataoffset = cpu_headers_size + part_bytes[io_rank];
// Write per-CPU header
cpu_header_t our_cpu_header;
our_cpu_header.num_particles = particles.size();
our_cpu_header.file_offset = dataoffset;
MPI_Datatype cpu_header_type = build_cpu_header_type();
int typesize;
MPI_Type_size(cpu_header_type, &typesize);
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Rank " + std::to_string(io_rank) + "has its header at offset" +
std::to_string(headeroffset));
#endif
status = MPI_File_set_view(file, headeroffset, cpu_header_type, cpu_header_type,
(char*)"native", info);
if(status) {
ERROR("File view for the cpu header could not be set!");
}
status = MPI_File_write_all(file, &our_cpu_header, 1, cpu_header_type, &mstatus);
if(status) {
ERROR("Cpu header could not be written!");
}
// set file view for the particles
// the offset is the offset of all headers plus the particles of all prior CPUs
status = MPI_File_set_view(file, dataoffset, MPI_DOUBLE, particle_type,
(char*)"native", info);
if(status) {
delete[] part_bytes;
ERROR("File view for the particles could not be set!");
}
// dump all particles like they are in memory (problematic due to the shared_ptr memeber variable...)
status = MPI_File_write_all(file, particles.data(), particles.size(),
particle_type, &mstatus);
if(status) {
ERROR("Particles could not be written! status: " + std::to_string(status));
}
// close everything
delete[] part_bytes;
MPI_File_close(&file);
MPI_Type_free(&particle_type);
MPI_Type_free(&cpu_header_type);
MPI_Info_free(&info);
}
+29 -7
View File
@@ -15,14 +15,25 @@
// 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)) {}
// 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) {
Restart::Restart(bool do_restart, std::string absolute_filename_without_extension,
std::string restart_idenitfier, int particle_restart_at):
do_restart_(do_restart),
restart_identifier_(restart_idenitfier),
reader_(absolute_filename_without_extension + ".h5"),
particle_reader_(absolute_filename_without_extension,
particle_restart_at) {}
void Restart::restart(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver,
RandomNumbers* random_numbers,
std::vector<particle::SerializedParticle>& storage_queue) {
if(!do_restart_) {
return;
@@ -31,6 +42,7 @@ void Restart::restart(std::map<std::string, std::shared_ptr<species::TrackedSpec
DEBUG_LEVEL_1("Restarting rng");
#endif
restartRandomNumbers(random_numbers);
#ifdef debug_level1
DEBUG_LEVEL_1("Restarting poisson solver.");
#endif
@@ -47,6 +59,11 @@ void Restart::restart(std::map<std::string, std::shared_ptr<species::TrackedSpec
restartDrawingDensityField(pair.second->densityForDrawing(), path);
pair.second->positionDistributionFromDensity()->setMaximumDensity();
}
#if defined(debug_level1) || defined(debug_level2) || defined(debug_level3)
DEBUG_LEVEL_1("Reloading particles.");
#endif
particle_reader_.readParticles(storage_queue);
}
void Restart::restartRandomNumbers(RandomNumbers* random) {
@@ -141,4 +158,9 @@ void Restart::restartPoissonSolver(PoissonSolver* solver) {
#endif
blitz::Array<double, 3> potential = reader_.readD3Double(path);
solver->setPotential(potential);
}
void Restart::restartParticles(
std::vector<particle::SerializedParticle>& storage_queue) {
particle_reader_.readParticles(storage_queue);
}
+23 -3
View File
@@ -11,8 +11,11 @@
#include "poisson_solver/poisson_solver.h"
SimulationOutput::SimulationOutput(const std::string& output_folder,
const std::string& output_filename)
: writer(Hdf5Writer(output_folder, output_filename)) {}
const std::string& output_filename,
int fs_blocksize)
: writer(Hdf5Writer(output_folder, output_filename)),
particle_writer(MpiParticleWriter(output_folder,
output_filename, fs_blocksize)) {}
void SimulationOutput::addDensityFieldOutput(OutputTask task) {
tasks_density_fields_.push_back(task);
@@ -34,6 +37,10 @@ void SimulationOutput::setRestartInfoOutput(OutputTask task) {
task_rng_ = task;
}
void SimulationOutput::setParticleOutput(OutputTask task) {
task_particles_ = task;
}
void SimulationOutput::writeMetaData(
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
const std::shared_ptr<PoissonSolver>& poisson_solver) {
@@ -70,7 +77,8 @@ void SimulationOutput::writeSimulationData(
int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species,
PoissonSolver* poisson_solver,
std::mt19937* engine) {
std::mt19937* engine,
std::vector<particle::SerializedParticle>& storage_queue) {
if (MpiCommunication::mpi_rank == 0) {
#ifdef debug_level2
@@ -119,6 +127,11 @@ void SimulationOutput::writeSimulationData(
if((task_rng_.intervall > 0) && (cpu_sync%task_rng_.intervall == 0)) {
writeRestartData(engine, cpu_sync, task_rng_.overwrite_last);
}
if((task_particles_.intervall > 0) && (cpu_sync%task_particles_.intervall == 0)) {
writeParticles(storage_queue, cpu_sync,
species.begin()->second->dynamicDensityField()->timeResolution());
}
}
void SimulationOutput::writeSimulationData(DynamicDensityField* density_field,
@@ -450,3 +463,10 @@ void SimulationOutput::writeBinBorders(DynamicDensityField* density_field,
density_field->positionBinning()->longitudinal_binning.binBorders();
writer.write(longitudinal_bin_borders, path_to_bin_borders + "/longitudinal");
}
void SimulationOutput::writeParticles(
std::vector<particle::SerializedParticle>& particles,
int cpu_sync,
double dt) {
particle_writer.output_particles(particles, cpu_sync, dt);
}
+11 -4
View File
@@ -10,21 +10,28 @@ namespace generator {
#ifdef debug
DEBUG_LEVEL_0("No Restart desired.");
#endif
return Restart(false, "", "");
return Restart(false, "", "", 0);
}
std::string filepath = readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}))
+ ".h5";
// no file extensions!!! Those get added in the constructor of the hdf5 and mpi
// reader classes
std::string filepath =
readAbsoluteFilename(json_object_by_path(object, {"PathToH5"}));
#ifdef debug_level3
DEBUG_LEVEL_3("Restart: file path:" + filepath);
#endif
std::string identifier;
int sync_period = json_int(json_object_by_path(object, {"SyncPeriod"}));
int part_restart_at = sync_period;
if(sync_period == 0 && json_string(json_object_by_path(object, {"SyncPeriod"}))
== "LastSyncPeriod") {
identifier = "LastSyncPeriod";
part_restart_at = json_int(json_object_by_path(object, {"ParticleSyncPeriod"}));
ASSERT_POSITIVE(&part_restart_at, "The ParticleSyncPeriod has to be positive!");
} else {
ASSERT_POSITIVE(&sync_period, "The SyncPeriod for the restart has to be either"
" positive or \"LastSyncPeriod\".");
@@ -35,7 +42,7 @@ namespace generator {
DEBUG_LEVEL_3("Restart: SyncPeriod to be started from: " + identifier);
#endif
return Restart(do_restart, filepath, identifier);
return Restart(do_restart, filepath, identifier, part_restart_at);
}
Restart buildRestart(Parameter& parameter) {
@@ -178,6 +178,31 @@ std::shared_ptr<SimulationOutput> buildSimulationOutput(
output->setRestartInfoOutput(task);
}
// Particles
{
int intervall =
json_int(json_object_by_path(object, {"Particles", "Intervall"}), -1);
// DEBUG_LEVEL_2("Try value of Intervall as string");
if (intervall == -1 && json_string(json_object_by_path(
object, {"Particles", "Intervall"})) == "EachSync") {
intervall = 1;
} else if (intervall == -1) {
intervall = 0;
}
ASSERT_NOTNEGATIVE(&intervall, "The intervall for Particles output has to be either 0"
",if no output is required or positive otherwise");
#ifdef debug_level3
DEBUG_LEVEL_3("Particles output interval: " + std::to_string(intervall));
#endif
// could be done, but then the naming of the mpi file would need to be adjusted
bool overwrite_last = false;
OutputTask task = {"Particles", overwrite_last, intervall};
output->setParticleOutput(task);
}
return output;
}
+5
View File
@@ -137,6 +137,11 @@ void SpeciesBuilder::initTrackedSpecies(Parameter& parameter) {
json_t* value;
json_object_foreach(parameter.jsonObjectFromBase({"Species", "Tracked"}), key,
value) {
if(std::string(key).size() >= 16) {
std::stringstream out;
out << std::string(key) << ": name is to long, has to be 15 chars or less!";
ERROR(out.str());
}
tracked_species_info[std::string(key)] = TrackedSpeciesBuilderInfo();
tracked_species_info[std::string(key)].name = std::string(key);
tracked_species_info[std::string(key)].path_in_json = {"Species", "Tracked",
+59 -2
View File
@@ -18,6 +18,43 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
}
*/
// requires the name of a species "spec_name" to be smaller than 16 characters
// this is not! checked here and will lead to undefined behaviour if this
// requirement is not fulfilled
SerializedParticle::SerializedParticle(double time_birth, double weight,
blitz::TinyVector<double, 3> cartPos,
blitz::TinyVector<double, 3> cartVel,
std::string spec_name) :
time_birth_(time_birth), weight_(weight),
cartesian_position_(cartPos),
cartesian_velocity_(cartVel) {
std::copy(spec_name.begin(), spec_name.end(), specie_name_.data());
specie_name_[spec_name.length()] = '\0';
}
double SerializedParticle::timeBirth() {
return time_birth_;
}
double SerializedParticle::weight() {
return weight_;
}
blitz::TinyVector<double, 3> SerializedParticle::cartesianPosition() {
return cartesian_position_;
}
blitz::TinyVector<double, 3> SerializedParticle::cartesianVelocity() {
return cartesian_velocity_;
}
std::string SerializedParticle::specieName() {
return std::string (specie_name_.data());
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
const Coordinate& position,
const Vector& velocity,
@@ -34,6 +71,20 @@ Particle::Particle(std::shared_ptr<species::TrackedSpecie> specie,
last_id_++;
}
Particle::Particle(particle::SerializedParticle sparticle, std::map<std::string,
std::shared_ptr<species::TrackedSpecie>>& tracked_species) :
specie_(tracked_species[sparticle.specieName()]),
position_cart_(sparticle.cartesianPosition()),
position_cyl_(blitz::TinyVector<double, 3>(0,0,0)),
velocity_(sparticle.cartesianVelocity()),
id_(this->last_id_),
time_alive_s_(sparticle.timeBirth()),
interaction_counter_(0),
weight_(sparticle.weight()) {
last_id_++;
position_cyl_ = CylinderCoordinate(position_cart_);
}
long int Particle::last_id_ = 0;
double Particle::mass_kg() const {
@@ -115,12 +166,18 @@ double Particle::weight() const {
return weight_;
}
void Particle::deposited() {
deposited_ = true;
void Particle::deposited(bool truthValue) {
deposited_ = truthValue;
}
bool Particle::wasDeposited() {
return deposited_;
}
particle::SerializedParticle Particle::serialize() {
return particle::SerializedParticle(time_alive_s_, weight_,
position_cart_.cartesianEntries(), velocity_.cartesianEntries(),
specie_->name());
}
} // namespace particle
+71 -58
View File
@@ -46,14 +46,25 @@ Simulation::Simulation(std::string parameter_filename)
}
void Simulation::init(Parameter& parameter) {
// reserve some size for the different particle queues
queue_.reserve(100);
storage_queue_[0].reserve(1000);
storage_queue_[1].reserve(1000);
if(MpiCommunication::mpiSize() == 1) {
std::ofstream file;
file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
std::ios_base::out);
file << "#type(0:drawing,1:interaction)\tx\ty\tz\tvx\tvy\tvz\n";
file.close();
}
#ifdef debug
std::stringstream out;
out << "Size of a Particle: " << sizeof(particle::Particle);
out << "\nSize of a Serialized Particle: " << sizeof(particle::SerializedParticle);
DEBUG_LEVEL_0(out.str());
#endif
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::out);
// file << "#type(0:drawing,1:interaction)\tx\ty\tz\tvx\tvy\tvz\n";
// file.close();
// }
magnetic_field_ = generator::magneticField(parameter);
electric_field_ = generator::electricField(parameter);
@@ -97,7 +108,8 @@ void Simulation::init(Parameter& parameter) {
#endif
Restart restarter = generator::buildRestart(parameter);
restarter.restart(tracked_species_, poisson_solver_.get(), random_.get());
restarter.restart(tracked_species_, poisson_solver_.get(), random_.get(),
storage_queue_[active_storage]);
// poisson solver is restarted -> set the electric field from the potential
electric_field_->updateDynamicField(poisson_solver_->staticElectricField());
@@ -208,10 +220,6 @@ void Simulation::start() {
int num_cpu_syncs = 0;
bool reset = true;
queue_.reserve(100);
storage_queue_[0].reserve(1000);
storage_queue_[1].reserve(1000);
timer_->increaseTimestep(delta_t);
while (timestep < number_timesteps) {
@@ -245,7 +253,7 @@ void Simulation::start() {
processEvents(events_of_cycle, beta_particle_weight);
#ifdef debug_level1
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timesteps));
DEBUG_LEVEL_1("Processing timestep: " + std::to_string(timestep));
DEBUG_LEVEL_1("Leftover events this timestep: " +
std::to_string(leftover_events_time_resolution));
#endif
@@ -276,8 +284,9 @@ void Simulation::start() {
SIM_INFO("Perform output.");
SimulationTimer::eventStartPoint(std::string("Output"));
// only write inactive queue, obvi not correct if written between timesteps
output_->writeSimulationData(num_cpu_syncs, tracked_species_, poisson_solver_.get(),
random_->engine());
random_->engine(), storage_queue_[inactive_storage]);
SimulationTimer::eventStopPoint(std::string("Output"));
SimulationTimer::eventStartPoint("Reset");
@@ -359,19 +368,19 @@ void Simulation::processEvents(int events, const double beta_particle_weight) {
SimulationTimer::eventStartPoint(std::string("ParticleInjection"));
new_particles = determineInjectedParticles(random_.get(),
beta_particle_weight);
if(MpiCommunication::mpiSize() == 1) {
std::ofstream file;
file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
std::ios_base::app);
for(auto part: new_particles) {
auto pos = part.cartesianPosition().cartesianEntries();
auto vel = part.velocity().cartesianEntries();
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// for(auto part: new_particles) {
// auto pos = part.cartesianPosition().cartesianEntries();
// auto vel = part.velocity().cartesianEntries();
file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
}
file.close();
}
// file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// }
// file.close();
// }
// 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
@@ -448,19 +457,19 @@ void Simulation::processDensityEvents(int particles_per_bin, const double weight
all_bins_done);
SimulationTimer::eventStopPoint(std::string("DensityInjection"));
if(MpiCommunication::mpiSize() == 1) {
std::ofstream file;
file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
std::ios_base::app);
for(auto part: new_particles) {
auto pos = part.cartesianPosition().cartesianEntries();
auto vel = part.velocity().cartesianEntries();
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// for(auto part: new_particles) {
// auto pos = part.cartesianPosition().cartesianEntries();
// auto vel = part.velocity().cartesianEntries();
file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
}
file.close();
}
// file << 0 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// }
// file.close();
// }
#if defined debug_level3
for(auto& particle : new_particles) {
@@ -553,15 +562,6 @@ void Simulation::processUntilTermination(
DEBUG_LEVEL_3("Terminate particle " + particle.specie()->name() +
". Reached timeresolution.");
#endif
// particle terminated due to reaching time resolution alone -> needs
// to be stored (if it's an electron)
if(particle.specie()->type() == species::ImplementedSpecies::electron) {
storage_queue_[inactive_storage].push_back(particle);
}
if(particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.cylinderPosition(),
DeletionType::max_time_alive);
#ifdef debug
if(!particle.wasDeposited()) {
std::stringstream out;
@@ -571,6 +571,15 @@ void Simulation::processUntilTermination(
ERROR(out.str());
}
#endif
// particle terminated due to reaching time resolution alone -> needs
// to be stored (if it's an electron)
if(particle.specie()->type() == species::ImplementedSpecies::electron) {
storage_queue_[inactive_storage].push_back(particle.serialize());
}
if(particle.specie()->deletionLogger()) {
particle.specie()->deletionLogger()->logDeletion(particle.cylinderPosition(),
DeletionType::max_time_alive);
}
break;
} else if (particle.specie()->terminator()->leftSimulationDomain(
@@ -597,6 +606,8 @@ void Simulation::processUntilTermination(
std::stringstream out;
out << "particle " << particle.specie()->name();
out << " left simulation domain but still contributes to the density";
out << "\nposition: " << particle.cylinderPosition().cylinderEntries();
out << "\nvelocity: " << particle.velocity().cartesianEntries();
ERROR(out.str());
}
#endif
@@ -623,17 +634,17 @@ void Simulation::processUntilTermination(
SimulationTimer::eventStartPoint(std::string("Interaction"));
interaction::InteractionOutput output = interact(particle, random_.get());//,
// macroscopic_cross_sections_m);
if(MpiCommunication::mpiSize() == 1) {
std::ofstream file;
file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
std::ios_base::app);
auto pos = particle.cartesianPosition().cartesianEntries();
auto vel = particle.velocity().cartesianEntries();
// if(MpiCommunication::mpiSize() == 1) {
// std::ofstream file;
// file.open("/home/christian/Documents/Heidelberg/karl/test_cases/thermalization/data.txt",
// std::ios_base::app);
// auto pos = particle.cartesianPosition().cartesianEntries();
// auto vel = particle.velocity().cartesianEntries();
file << 1 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
file.close();
}
// file << 1 << "," << pos(0) << ',' << pos(1) << ',' << pos(2) << ',';
// file << vel(0) << "," << vel(1) << ',' << vel(2) << '\n';
// file.close();
// }
SimulationTimer::eventStopPoint(std::string("Interaction"));
// particle has reached time resolution, but was not deposited due to
@@ -802,8 +813,10 @@ std::vector<particle::Particle> Simulation::determineInjectedDensityParticles(
all_bins_done = false;
}
// take the first particle from the storage queue and extract it
particle::Particle new_particle = *(storage_queue_[active_storage].begin());
particle::SerializedParticle new_sparticle =
*(storage_queue_[active_storage].begin());
storage_queue_[active_storage].erase(storage_queue_[active_storage].begin());
particle::Particle new_particle(new_sparticle, tracked_species_);
// "draw" the actual particle
new_particles.push_back(new_particle);
continue;