Author SHA1 Message Date
csendlinger 53f0d0d86a adjusted Boris mover to use the cartesian position for the calculation of the B field 2026-06-09 09:34:59 +02:00
csendlinger ca7b637577 Added the analytical approximation for the magnetic
field in the P8 LFA scenario:
Ioffe: infinite wire approximations
Bottle: Gaussian profile in Bz
2026-06-09 09:29:21 +02:00
csendlinger 46277ae340 Added new deletion logger type to count elastic
scattering events that upscatter the neutral
particle by an energy of 5mK*k_B (for now hard-coded);
Type is only used if DeletionLogger is se=pecified as
"all" in the parameter file
2026-06-09 09:20:55 +02:00
csendlinger 9e9c9ac174 Changes to the Cone+Cylinder Geometry; cutting off the
tip of the cone is now supported
2026-06-09 09:13:20 +02:00
csendlinger a6a9ac388c Added a half-cylinder with a cone end as a geometry.
The cone starts at z=0 and has a height H_cone, the
cylinder starts at H_cone and ends at H_cone + H_cyl.
The radii of the cone and the cylinder are matched.
It's important to note that the injector still injects particles
across the whole "bounding cylinder", but particles
outside of the actual region are removed after their
first movement step without being deposited.
2026-04-28 14:00:10 +02:00
23 changed files with 293 additions and 352 deletions
+7 -64
View File
@@ -7,7 +7,6 @@ import argparse
import glob
import re
import os
import plot_standards as pst
def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow=False):
times = []
@@ -53,46 +52,6 @@ def get_time_and_total_charge_(files, considered_keys=['All'], exclude_underflow
return times, total_charges
def get_time_and_wall_losses(files, considered_keys=['All']):
times = []
phys_wall_loss = []
for file in files:
with h5py.File(file, 'r') as cfile:
time = 0
for key in cfile.keys():
if(key == "PoissonSolver" or key == "RestartInfo" or key == 'NumberProcesses'):
continue
if (not considered_keys[0] == 'All') and (not key in considered_keys):
continue
cfile_specieslogger = cfile[key]['DeletionLogger']
for time_key in cfile_specieslogger.keys():
time = cfile[key]['DensityField/SimulationData'][time_key]['PhysicalTime'][0]
deltat = cfile[key]['CurrentCollector/SimulationData'][time_key]['PhysicalTime'][0]
try:
index = times.index(time)
try:
phys_wall_loss[index] += cfile_specieslogger[time_key]\
['NumDeletions/Wall(physical)'][0]/deltat
except:
pass
except:
times.append(time)
try:
phys_wall_loss.append(cfile_specieslogger[time_key]\
['NumDeletions/Wall(physical)'][0]/deltat)
except:
phys_wall_loss.append(-1)
times = np.array(times)
phys_wall_loss = np.array(phys_wall_loss)
sorting_mask = np.argsort(times)
times = times[sorting_mask]
phys_wall_loss = phys_wall_loss[sorting_mask]
return times, phys_wall_loss
def getFiles(dir:str, base_name:str, pattern:str) :
if dir[-1] == '/':
pathname = dir + base_name
@@ -105,10 +64,7 @@ if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Program to create a plot of the charge against time from the output of KARL")
parser.add_argument("dir", type = str, help="directory where the files are stored in")
parser.add_argument("basename", type = str, help = 'identifying pattern of the files (i.e. basename[0-9]*\\.h5])')
parser.add_argument('--losses', action='store_true', help = 'create wall loss rate plot instead')
parser.add_argument("--pattern", type = str, nargs = '?', help = 'Regular expression pattern, that specifies the naming of the files (by default [0-9]*). Gets added to dir+basename+pattern+".h5".', default = '[0-9]*')
parser.add_argument("--width", type = str, nargs = '?', default="thesis", help = "Either \'thesis\' or \'beamer\' as defined in plot_standards.py")
parser.add_argument("--fraction", type = float, default=1, nargs="?", help= "the fraction of width that the plot should occupy, as defined in plot_standards.py")
parser.add_argument("species", action='extend', nargs='+', help = 'Names of the Species in the KARL output or \'All\' if all species should be summed. If name does not exist it will be ignored.')
args = parser.parse_args()
@@ -118,17 +74,10 @@ if __name__ == '__main__':
print(files)
if(files == []):
print(f"No files found in {args.dir}, which match '{args.basename}{args.pattern}\\.h5'")
print(f"No files found in {args.dir}, which match '{args.basename}[0-9]*\\.h5'")
exit(1)
if (not args.width == 'thesis') and (not args.width == 'beamer'):
print(f"{args.width} is not a valid parameter for width; fall back to \'thesis\'")
args.width = 'thesis'
if args.losses:
times, charges = get_time_and_wall_losses(files, args.species)
else:
times, charges = get_time_and_total_charge_(files, args.species)
times, charges = get_time_and_total_charge_(files, args.species)
legstr = ''
for val in args.species:
@@ -136,13 +85,10 @@ if __name__ == '__main__':
legstr = legstr[:-3]
plt.rcParams.update({'font.size': 10})
fig = plt.figure(figsize=pst.set_size(args.width))
plt.rcParams.update({'font.size': 14})
fig = plt.figure(figsize=(10,6))
plt.plot(times, charges, marker = 'x', label = legstr)
if args.losses:
plt.ylabel('loss rate (1/s)')
else:
plt.ylabel('charge (C)')
plt.ylabel('charge (C)')
plt.xlabel('time (s)')
plt.legend()
plt.grid()
@@ -156,14 +102,11 @@ if __name__ == '__main__':
os.makedirs(outname, exist_ok=True)
if args.losses:
outname += args.basename + "_wallLossRateAgainstTime_species-"
else:
outname += args.basename + "_chargeAgainstTime_species-"
outname += args.basename + "_chargeAgainstTime_species-"
for value in args.species:
outname += value
outname += '_test.pdf'
outname += '.pdf'
# print(outname)
plt.savefig(outname, format='pdf', bbox_inches = 'tight')
-5
View File
@@ -52,11 +52,6 @@ class SimulationOutput {
std::vector<particle::SerializedParticle>& storage_queue,
int injectionGroupOffset);
#ifdef GENRICHCURRENT
void setResetCurrentCollector(int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species);
#endif
private:
std::vector<OutputTask> tasks_density_fields_;
std::vector<OutputTask> tasks_current_collector_;
+2 -17
View File
@@ -13,29 +13,14 @@ class ElasticScattering : public Interaction {
std::shared_ptr<species::Specie> target,
std::shared_ptr<ScatteringAngleDistribution> theta_distrib);
virtual InteractionOutput performInteraction(particle::Particle& particle,
InteractionOutput performInteraction(particle::Particle& particle,
RandomNumbers* generator);
virtual double drawCollisionTime(particle::Particle& particle,
RandomNumbers* generator);
protected:
private:
std::shared_ptr<ScatteringAngleDistribution> theta_distrib_;
};
// Full elastic scattering in the sense that both particles after scattering
// become tracked
class ElasticScatteringFull : public ElasticScattering {
public:
ElasticScatteringFull(std::function<double(double)> cross_section,
std::shared_ptr<species::Specie> target,
std::shared_ptr<ScatteringAngleDistribution> theta_distrib,
std::shared_ptr<species::TrackedSpecie> product);
InteractionOutput performInteraction(particle::Particle& particle,
RandomNumbers* generator);
protected:
std::shared_ptr<species::TrackedSpecie> product_;
};
}; // namespace interaction
#endif /* ELASTIC_SCATTERING_H */
+1 -3
View File
@@ -39,8 +39,7 @@ class ElectronIonization : public Interaction {
std::shared_ptr<species::TrackedSpecie> ion,
std::shared_ptr<IonizationEnergyDistribution> distribution,
std::shared_ptr<IonizationScatteringAngleDistribution> angle_distribution,
double ionization_energy_eV,
double ion_energy);
double ionization_energy_eV);
InteractionOutput performInteraction(particle::Particle& particle,
RandomNumbers* generator);
@@ -49,7 +48,6 @@ class ElectronIonization : public Interaction {
std::shared_ptr<IonizationEnergyDistribution> energy_distribution_;
std::shared_ptr<IonizationScatteringAngleDistribution> angle_distribution_;
const double ionization_energy_eV_;
const double ion_energy_;
std::shared_ptr<species::TrackedSpecie> electron_;
std::shared_ptr<species::TrackedSpecie> ion_;
+9 -19
View File
@@ -29,14 +29,6 @@ class CurrentCollector {
blitz::Array<double, 2> areaInZ() const;
blitz::Array<double, 2> currentInZ() const;
#ifdef GENRICHCURRENT
blitz::Array<double, 2> sampleNegativeCrossings() const;
std::vector<double> energyBinBorders() const;
void needsReset() { needs_reset = true; };
bool getNeedsReset() const { return needs_reset; };
double timeSinceReset() const {return time_since_reset;};
#endif //GENRICHCURRENT
double physicalTime() const;
void resetCurrentCollector();
@@ -49,9 +41,6 @@ class CurrentCollector {
const double weight);
void collectLongitudinalMovement(const blitz::TinyVector<int, 2>& bin_old,
const blitz::TinyVector<int, 2>& bin_new,
#ifdef GENRICHCURRENT
const double energy_eV,
#endif
const double weight);
void collectAzimuthalMovement(const blitz::TinyVector<double, 3>& old_pos_cart,
const blitz::TinyVector<double, 3>& new_pos_cart,
@@ -82,18 +71,19 @@ class CurrentCollector {
blitz::Array<double, 2> r_negative_crossings;
blitz::Array<double, 2> 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, 2> collector_areas_r;
blitz::Array<double, 2> collector_areas_phi;
blitz::Array<double, 2> collector_areas_z;
#ifdef GENRICHCURRENT
blitz::Array<double, 2> sample_z_negative_crossings;
EnergyBinning energy_binning_;
bool needs_reset = false;
double time_since_reset = 0;
#endif //GENRICHCURRENT
CylinderBinning position_binning_;
std::shared_ptr<Timer> timer_;
};
+34
View File
@@ -26,4 +26,38 @@ class Cylinder : public Geometry {
const double height_;
};
/*
/|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾\ ‾‾‾
/ | | \ ^
/ | | \ |
/ | | \ | R_cylinder
/ | | \ ⌄
|<-->|<------------------>|<------------------><---> ---
z=0 ^ ^ |
| | |
H_cone H_cylinder symmetry axis
The geometry will only know 3 regions, "inside", "hull", "top". Meaning the
cone will always have the same boundary condition as the cylinder boundary.
*/
/*
Geometry of a cylinder with a cone as the end with its tip at z=0.
*/
class HalfCylinderWithCone : public Geometry {
public:
HalfCylinderWithCone(double radiusCylinder, double heightCylinder,
double heightCone, double zfrustum);
bool isInside(const Coordinate& position) const;
GeometryPositioning isWhere(const Coordinate& position) const;
private:
const double cylinder_radius_;
const double cylinder_height_;
const double cone_height_;
const double z_frustum_;
double localRadius(double z) const;
};
#endif /* GEOMETRY_H */
+2
View File
@@ -46,6 +46,8 @@ class Interaction {
std::function<double(double)> cross_section_;
std::shared_ptr<species::Specie> target_;
CartesianVector target_velocity_;
double threshold_increase_J = 6.9032515e-26; // J (5 mK)
};
}; // namespace interaction
+3 -1
View File
@@ -16,8 +16,10 @@ enum class DeletionType {
// to count physical particle deletion
enum class PhysicalDeletionType {
wall
wall,
large_energy_transfer
};
class Coordinate;
class DeletionLogger {
+31
View File
@@ -6,6 +6,7 @@
#include "simulation/coordinates.h"
#include "simulation/position_binning.h"
#include "constants/physical_constants.h"
class VectorField {
public:
@@ -50,4 +51,34 @@ class VectorFieldFunctionInZ : public VectorField {
std::function<double(double, double, double)> F_z_;
};
// Vector field implementing the analytical approximation to the
// magnetic field in the Project 8 LFA case, all parameters are hard-coded for now
// Note that only one half of the whole system is considered -> only one Gaussian peak
class PredefinedMagneticVectorFieldLFA : public VectorField {
public:
PredefinedMagneticVectorFieldLFA();
// Important: coordinate has to be a Cartesian Coordinate in oder for the calculation to be correct
CylinderVector value(const Coordinate& coordinate) const;
private:
// half opening angle of the cones = 35 deg, I_Ioffe = 5kA
const double cosa = std::cos(M_PI*35./180.);
const double sina = std::sin(M_PI*35./180.);
const double B0Ioffe = SI::mu0*5000/(2*M_PI); // Tm
// background field
const double Bbg = 0.0207; // T
// radius of ioffe wires
const double RIoffe = 0.3326; // m
// steepness of transition functions, currently not used
const double c1 = 10.; // 1/m
const double c2 = 100.; // 1/m
blitz::Array<double, 1> cosktheta{128};
blitz::Array<double, 1> sinktheta{128};
// z1, z2 in the system, where the Ioffe cone tip is in the origin,
// zoffset the distance between ioffe cone tip and cavity cone tip,
// z1 is the start of the ioffe frustum and z2 the transition from cone to cylinder
double z1, z2, zoffset;
};
#endif /* VECTOR_FIELD_H */
-6
View File
@@ -35,8 +35,6 @@ LIBS =#-static
CXXFLAGS += -DHOMEBASE=$(HOMEBASE)
#CXXFLAGS += -Ddebug_timedist
# Blitz
CXXFLAGS += $(BLITZ_INCLUDES)
LIBS += $(BLITZ_LIBS)
@@ -57,10 +55,6 @@ ifeq ($(DO_DEBUGGING),true)
CXXFLAGS += -Ddebug_level$(DEBUG_LEVEL)
endif
ifeq ($(DO_GENRICHCURRENT),true)
CXXFLAGS += -DGENRICHCURRENT #-Ddebug_genrich
endif
# Catch2
CXXFLAGS += $(CATCH_INCLUDES)
+4 -25
View File
@@ -81,6 +81,7 @@ void SimulationOutput::writeSimulationData(
std::vector<particle::SerializedParticle>& storage_queue,
int injectionGroupOffset) {
if (MpiCommunication::mpi_rank == 0) {
#ifdef debug_level2
DEBUG_LEVEL_2("Write density field data.");
#endif
@@ -272,6 +273,8 @@ void SimulationOutput::writeNumDeletions(DeletionLogger* logger,
for (auto& pair : physDeletions) {
if (pair.first == PhysicalDeletionType::wall) {
writer.write(pair.second, path_to_deletions + "/Wall(physical)");
} else if (pair.first == PhysicalDeletionType::large_energy_transfer) {
writer.write(pair.second, path_to_deletions + "/LargeEnergyTransfer");
}
}
}
@@ -293,11 +296,6 @@ void SimulationOutput::writeCurrentCrossings(
path + "/PositiveCrossingsInZ");
writer.write(current_collector->negativeCrossingsInZ(),
path + "/NegativeCrossingsInZ");
#ifdef GENRICHCURRENT
writer.write(current_collector->sampleNegativeCrossings(),
path + "/SampleNegativeCrossings");
#endif
}
void SimulationOutput::writeCurrent(CurrentCollector* current_collector,
@@ -310,10 +308,6 @@ void SimulationOutput::writeCurrent(CurrentCollector* current_collector,
void SimulationOutput::writePhysicalTime(CurrentCollector* current_collector,
std::string path) {
writer.write(current_collector->physicalTime(), path + "/PhysicalTime");
#ifdef GENRICHCURRENT
// write the time over which the "sample" current has been accumulated during
writer.write(current_collector->timeSinceReset(), path + "/TimeSinceReset");
#endif
}
void SimulationOutput::writeSpectrum(DynamicDensityField* density_field,
@@ -436,10 +430,6 @@ void SimulationOutput::writeCollectorAreas(CurrentCollector* current_collector,
writer.write(current_collector->areaInR(), path + "/AreaInR");
writer.write(current_collector->areaInPhi(), path + "/AreaInPhi");
writer.write(current_collector->areaInZ(), path + "/AreaInZ");
#ifdef GENRICHCURRENT
writer.write(current_collector->energyBinBorders(), path + "/EnergyBinBorders");
#endif
}
void SimulationOutput::writeBinVolumes(DynamicDensityField* density_field,
@@ -480,15 +470,4 @@ void SimulationOutput::writeParticles(
int cpu_sync,
double dt) {
particle_writer.output_particles(particles, cpu_sync, dt);
}
#ifdef GENRICHCURRENT
void SimulationOutput::setResetCurrentCollector(int cpu_sync,
std::map<std::string, std::shared_ptr<species::TrackedSpecie>>& species) {
for(auto& task : tasks_current_collector_) {
if(cpu_sync % task.intervall == 0)
species.at(task.specie_name)->currentCollector()->needsReset();
}
}
#endif
}
+30
View File
@@ -23,6 +23,36 @@ std::shared_ptr<Geometry> buildGeometry(Parameter& parameter,
DEBUG_LEVEL_3("with height: " + std::to_string(height) + " m");
#endif
return std::shared_ptr<Geometry>(new Cylinder(radius, height));
} else if(parameter.jsonObjectFromBase(
json_path_append(path_to_geometry, {"HalfCylinderWithCone"}))) {
#ifdef debug
DEBUG("Creating geometry: half cylinder with cone.");
#endif
double radius =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"HalfCylinderWithCone", "Radius"})),
"m");
double heightcylinder =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"HalfCylinderWithCone", "HeightCylinder"})),
"m");
double heightcone =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"HalfCylinderWithCone", "HeightCone"})),
"m");
double z_frustum =
json_read_length(parameter.jsonObjectFromBase(json_path_append(
path_to_geometry, {"HalfCylinderWithCone", "FrustumStartZ"})),
"m");
#ifdef debug
std::stringstream out;
out << "height cyl: " << heightcylinder << ", height cone: " << heightcone << ", radius: " << radius << ", zfrustum: " << z_frustum << "\n";
DEBUG(out.str());
#endif
return std::shared_ptr<Geometry>(
new HalfCylinderWithCone(radius, heightcylinder, heightcone, z_frustum));
} else {
ERROR("This geometry is not implemented.");
return nullptr;
+4 -29
View File
@@ -56,30 +56,6 @@ void addInteractions(
new interaction::ElasticScattering(cross_section, target,
scattering_angle_distribution)));
} else if (type == "ElasticScatteringFull") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: ElasticScatteringFull");
#endif
std::function<double(double)> cross_section =
buildTotalCrossSection(json_object_by_path(value, {"CrossSection"}));
std::string target_name =
json_string(json_object_by_path(value, {"Target"}));
std::string product_name =
json_string(json_object_by_path(value, {"Product"}));
#ifdef debug_level3
DEBUG("with target " + target_name);
DEBUG("and product " + product_name);
#endif
std::shared_ptr<species::Specie> target =
findTarget(target_name, tracked_species, background_species);
std::shared_ptr<species::TrackedSpecie> product =
findTracked(product_name, tracked_species);
specie->addInteraction(std::shared_ptr<interaction::Interaction>(
new interaction::ElasticScatteringFull(cross_section, target,
nullptr, product)));
} else if (type == "FreeMovement") {
#ifdef debug_level2
DEBUG_LEVEL_2("Adding interactions: FreeMovement");
@@ -107,7 +83,6 @@ void addInteractions(
std::string ionization_model =
json_string(json_object_by_path(value, {"IonizationModel"}));
if (ionization_model == "JanevNonDiss") {
std::function<double(double)> cross_section =
interaction::totalCrossSection::eT2_ionization_janev_non_diss();
@@ -133,7 +108,7 @@ void addInteractions(
std::make_shared<interaction::ElectronIonization>(
cross_section, target, electron, ion,
ionization_energy_distribution, scattering_angle_distribution,
ionization_energy_eV, 0.));
ionization_energy_eV));
} else if (ionization_model == "JanevDissToGround") {
std::function<double(double)> cross_section =
interaction::totalCrossSection::eT2_ionization_janev_diss_ground();
@@ -159,7 +134,7 @@ void addInteractions(
std::make_shared<interaction::ElectronIonization>(
cross_section, target, electron, ion,
ionization_energy_distribution, scattering_angle_distribution,
ionization_energy_eV, 9.));
ionization_energy_eV));
} else if (ionization_model == "JanevDissToFirstExcited") {
std::function<double(double)> cross_section =
interaction::totalCrossSection::eT2_ionization_janev_diss_first();
@@ -187,7 +162,7 @@ void addInteractions(
std::make_shared<interaction::ElectronIonization>(
cross_section, target, electron, ion,
ionization_energy_distribution, scattering_angle_distribution,
ionization_energy_eV, 9.));
ionization_energy_eV));
} else if (ionization_model == "JanevAtomic") {
std::function<double(double)> cross_section =
interaction::totalCrossSection::eT_ionization_from_ground_janev();
@@ -211,7 +186,7 @@ void addInteractions(
std::make_shared<interaction::ElectronIonization>(
cross_section, target, electron, ion,
ionization_energy_distribution, scattering_angle_distribution,
ionization_energy_eV, 0.));
ionization_energy_eV));
} else {
ERROR("This ionization model is not implemented: " + ionization_model);
}
+1
View File
@@ -39,6 +39,7 @@ std::shared_ptr<DeletionLogger> buildDeletionLogger(json_t* object) {
used_types.push_back(DeletionType::max_time_alive);
used_types.push_back(DeletionType::cluster_formation);
used_phys_types.push_back(PhysicalDeletionType::wall);
used_phys_types.push_back(PhysicalDeletionType::large_energy_transfer);
}
}
@@ -95,6 +95,9 @@ std::shared_ptr<VectorField> buildVectorField(json_t* object) {
return std::make_shared<VectorFieldFromArray>(
v_radial, v_azimuthal, v_longitudinal, radius, length);
} else if (json_object_by_path(object, {"PredefinedLFAMagneticField"})) {
SIM_INFO("Warn: The predefined function is a magnetic field!!!");
return std::shared_ptr<VectorField>(new PredefinedMagneticVectorFieldLFA());
} else {
ERROR("This vector field is not implemented");
return nullptr;
+10 -51
View File
@@ -8,6 +8,7 @@
#include "simulation/velocity_distribution.h"
#include "constants/sim_constants.h"
#include "simulation/density_field.h"
#include "simulation/logger.h"
namespace interaction {
ElasticScattering::ElasticScattering(
@@ -24,6 +25,8 @@ InteractionOutput ElasticScattering::performInteraction(
#endif
const blitz::TinyVector<double, 3> v_impact =
particle.velocity().cartesianEntries();
double E_i = kinematic::kineticEnergy(v_impact, particle.mass_kg());
// const auto x_impact = particle.position();
// const blitz::TinyVector<double, 3> v_target =
// target_->driftVelocity()->driftVelocity(x_impact).cartesianEntries() +
@@ -48,6 +51,13 @@ InteractionOutput ElasticScattering::performInteraction(
v_impact, target_velocity_.cartesianEntries(), particle.mass_kg(),
target_->mass_kg(), theta, phi);
double E_iprime = kinematic::kineticEnergy(v_impact_new, particle.mass_kg());
// energy conservation: Ei + Et = Ei' + Et' <==> Et' - Et = Ei - Ei' (lab frame)
if(E_i - E_iprime >= threshold_increase_J) {
particle.specie()->deletionLogger()->logDeletion(particle, PhysicalDeletionType::large_energy_transfer);
}
particle.velocity(CartesianVector(v_impact_new));
return InteractionOutput();
@@ -126,55 +136,4 @@ double ElasticScattering::drawCollisionTime(particle::Particle& particle,
return time;
}
ElasticScatteringFull::ElasticScatteringFull(
std::function<double(double)> cross_section,
std::shared_ptr<species::Specie> target,
std::shared_ptr<ScatteringAngleDistribution> theta_distrib,
std::shared_ptr<species::TrackedSpecie> product) :
ElasticScattering(cross_section, target, theta_distrib),
product_(product) {}
// always assumes an isotropic angle distribution in the CoM frame
InteractionOutput ElasticScatteringFull::performInteraction(particle::Particle& particle,
RandomNumbers* generator) {
#ifdef debug
DEBUG_LEVEL_0("Perform full elastic scattering.");
#endif
const blitz::TinyVector<double, 3> v_impact =
particle.velocity().cartesianEntries();
// fprintf(stdout, "<%d>: Ekin T+ %e \n", MpiCommunication::mpiRank(), particle.kineticEnergy_eV());
const blitz::TinyVector<double, 3> v_com =
kinematic::velocityOfCenterOfMass(v_impact, target_velocity_.cartesianEntries(),
particle.mass_kg(), target_->mass_kg());
const double theta = std::acos(1. - 2*generator->rollUniform(0.,1.));
const double phi = generator->rollUniform(0., 2 * M_PI);
double vi_com_abs = kinematic::norm(v_impact - v_com);
// isotropic in CoM
blitz::TinyVector<double, 3> vi_com_scat(std::sin(theta)*std::cos(phi),
std::sin(theta)*std::sin(phi),
std::cos(theta));
vi_com_scat *= vi_com_abs;
blitz::TinyVector<double, 3> vt_com_scat = -particle.mass_kg()/target_->mass_kg() * vi_com_scat;
particle.velocity(CartesianVector(vi_com_scat + v_com));
// double Ekin = kinematic::kineticEnergy(vt_com_scat, product_->mass_kg())*UnitConversion::JouleToeV;
// fprintf(stdout, "<%d>: Ekin T2scat %f\n", MpiCommunication::mpiRank(), Ekin);
// Ekin = kinematic::kineticEnergy(vi_com_scat, particle.mass_kg())*UnitConversion::JouleToeV;
// fprintf(stdout, "<%d>: Ekin T+scat %f\n", MpiCommunication::mpiRank(), Ekin);
InteractionOutput output;
output.add(particle::Particle(product_, particle.cartesianPosition(),
CartesianVector(vt_com_scat+v_com),
particle.timeAlive(), particle.weight()));
return output;
}
}; // namespace interaction
+4 -13
View File
@@ -18,14 +18,13 @@ ElectronIonization::ElectronIonization(
std::shared_ptr<species::TrackedSpecie> ion,
std::shared_ptr<IonizationEnergyDistribution> distribution,
std::shared_ptr<IonizationScatteringAngleDistribution> angle_distribution,
double ionization_energy_eV, double ion_energy)
double ionization_energy_eV)
: Interaction(cross_section, target),
electron_(electron),
ion_(ion),
energy_distribution_(distribution),
angle_distribution_(angle_distribution),
ionization_energy_eV_(ionization_energy_eV),
ion_energy_(ion_energy) {}
ionization_energy_eV_(ionization_energy_eV) {}
InteractionOutput ElectronIonization::performInteraction(
particle::Particle& particle,
@@ -115,12 +114,6 @@ InteractionOutput ElectronIonization::performInteraction(
particle.velocity(v_impact_new);
blitz::TinyVector<double, 3> v_ion = v_target;
if(ion_energy_ > 0) {
v_ion *= std::sqrt(ion_energy_*UnitConversion::eVToJoule/(kinematic::kineticEnergy(v_target, ion_->mass_kg())));
}
const double time_birth = particle.timeAlive();
const double weight_parent = particle.weight();
@@ -128,10 +121,8 @@ InteractionOutput ElectronIonization::performInteraction(
output.add(
particle::Particle(electron_, x_impact, CartesianVector(v_ejected),
time_birth, weight_parent));
if(ion_energy_ > 0) {
output.add(particle::Particle(ion_, x_impact, CartesianVector(v_ion),
time_birth, weight_parent));
}
output.add(particle::Particle(ion_, x_impact, CartesianVector(v_target),
time_birth, weight_parent));
return output;
}
-5
View File
@@ -157,11 +157,6 @@ void CpuSynchronizer::synchronize(CurrentCollector* collector) {
// collector->r_positive_crossings =
// collector->sync_r_positive_crossings;
sumToRoot(collector->r_positive_crossings);
#ifdef GENRICHCURRENT
if(collector->getNeedsReset())
sumToRoot(collector->sample_z_negative_crossings);
#endif //GENRICHCURRENT
}
}
+16 -63
View File
@@ -12,20 +12,14 @@ CurrentCollector::CurrentCollector(const CylinderBinning& position_binning,
collector_areas_r(createAreaRadial(position_binning)),
phi_negative_crossings(createCrossingsAzimuthal(position_binning)),
phi_positive_crossings(createCrossingsAzimuthal(position_binning)),
collector_areas_phi(createAreaAzimuthal(position_binning))
#ifdef GENRICHCURRENT
// Hard coded values, not ideal, but it didn't work using defines...
, energy_binning_(0.1, 10, 100)
, sample_z_negative_crossings(
blitz::Range(position_binning.binIndexMin()(0),
position_binning.binIndexMax()(0)),
blitz::Range(-1, 100))
#endif //GENRICHCURRENT
{
#ifdef GENRICHCURRENT
sample_z_negative_crossings = 0;
#endif
}
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, 2> CurrentCollector::createAreaLongitudinal(
const CylinderBinning& position_binning) {
@@ -144,24 +138,8 @@ void CurrentCollector::collect(particle::Particle* particle,
const double weight = particle->weight();
#ifdef debug_genrich
if(particle->specie()->type() == species::ImplementedSpecies::Tplus &&
bin_new(1) == -1) {
std::stringstream out;
out << "Energy " << particle->kineticEnergy_eV() << " \n\t";
out << "Bin old " << bin_old << "; Bin new " << bin_new;
out << "; energy bin " << energy_binning_.bin(particle->kineticEnergy_eV());
out << "\n";
std::cout << out.str();
}
#endif
collectRadialMovement(bin_old, bin_new, weight);
collectLongitudinalMovement(bin_old, bin_new,
#ifdef GENRICHCURRENT
particle->kineticEnergy_eV(),
#endif
weight);
collectLongitudinalMovement(bin_old, bin_new, weight);
collectAzimuthalMovement(old_position.cartesianEntries(),
particle->cartesianPosition().cartesianEntries(),
bin_old, weight);
@@ -180,21 +158,9 @@ void CurrentCollector::collectRadialMovement(
void CurrentCollector::collectLongitudinalMovement(
const blitz::TinyVector<int, 2>& bin_old,
const blitz::TinyVector<int, 2>& bin_new,
#ifdef GENRICHCURRENT
const double energy_eV,
#endif
const double weight) {
if (bin_new(1) < bin_old(1)) {
z_negative_crossings(bin_old(0), bin_new(1) + 1) += weight;
#ifdef GENRICHCURRENT
if(bin_new(1) == -1) {
int ebin = energy_binning_.bin(energy_eV);
// #ifdef debug_genrich
// // fprintf(stdout, "Energybin: %d, energy: %f\n", ebin, energy_eV);
// #endif
sample_z_negative_crossings(bin_old(0), ebin) += weight;
}
#endif
} else if (bin_new(1) > bin_old(1)) {
z_positive_crossings(bin_old(0), bin_new(1)) += weight;
}
@@ -291,25 +257,12 @@ void CurrentCollector::resetCurrentCollector() {
r_negative_crossings = 0.;
r_positive_crossings = 0.;
#ifdef GENRICHCURRENT
if(needs_reset) {
sample_z_negative_crossings = 0.;
needs_reset = false;
time_since_reset = timer_->getDeltaT();
} else {
time_since_reset += timer_->getDeltaT();
}
#endif
}
// sync_z_negative_crossings = 0.;
// sync_z_positive_crossings = 0.;
#ifdef GENRICHCURRENT
// sync_phi_negative_crossings = 0.;
// sync_phi_positive_crossings = 0.;
blitz::Array<double, 2> CurrentCollector::sampleNegativeCrossings() const {
return sample_z_negative_crossings;
}
std::vector<double> CurrentCollector::energyBinBorders() const {
return energy_binning_.binBorders();
}
#endif
// sync_r_negative_crossings = 0.;
// sync_r_positive_crossings = 0.;
}
+36
View File
@@ -23,3 +23,39 @@ GeometryPositioning Cylinder::isWhere(const Coordinate& position) const {
return GeometryPositioning::inside;
}
}
HalfCylinderWithCone::HalfCylinderWithCone(double radiusCylinder, double heightCylinder,
double heightCone, double z_frustum) :
cylinder_height_(heightCylinder),
cylinder_radius_(radiusCylinder),
cone_height_(heightCone),
z_frustum_(z_frustum) {}
bool HalfCylinderWithCone::isInside(const Coordinate& coordinate) const {
const blitz::TinyVector<double, 3> cylinder_position = coordinate.cylinderEntries();
return (cylinder_position(2) > z_frustum_) &&
(cylinder_position(2) < (cylinder_height_ + cone_height_)) &&
(cylinder_position(0) < localRadius(cylinder_position(2)));
}
GeometryPositioning HalfCylinderWithCone::isWhere(const Coordinate& coordinate) const {
const blitz::TinyVector<double, 3> cylinder_position = coordinate.cylinderEntries();
if(cylinder_position(2) <= z_frustum_ || cylinder_position(0) >= localRadius(cylinder_position(2))) {
return GeometryPositioning::hull;
} else if (cylinder_position(2) >= (cone_height_ + cylinder_height_)) {
return GeometryPositioning::top;
} else {
return GeometryPositioning::inside;
}
}
double HalfCylinderWithCone::localRadius(double z) const {
if(z >= cone_height_) {
return cylinder_radius_;
} else {
// can potentially be negative, but that should be fine for a check if
// the position is inside the geometry
return z/cone_height_*cylinder_radius_;
}
}
+3 -17
View File
@@ -45,7 +45,7 @@ CylinderCoordinate BorisMover::move(particle::Particle* particle,
double old_kinetic_energy = particle->kineticEnergy_eV();
blitz::TinyVector<double, 3> B =
magnetic_field->value(old_position_cyl).cartesianEntries(old_position_cart);
magnetic_field->value(old_position_cart).cartesianEntries(old_position_cart);
blitz::TinyVector<double, 3> E;
if(particle->areLocalFieldsSet()) {
// In case of spatially variable magnetic fields use the one at the "actual" particle
@@ -53,25 +53,11 @@ CylinderCoordinate BorisMover::move(particle::Particle* particle,
// B = particle->getLocalB();
E = particle->getLocalE();
} else {
B = magnetic_field->value(old_position_cyl).cartesianEntries(old_position_cart);
B = magnetic_field->value(old_position_cart).cartesianEntries(old_position_cart);
E = electric_field->value(old_position_cyl).cartesianEntries(old_position_cart);
particle->setLocalFields(E, B);
}
// double old_mu;
// double new_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) == 0) {
// old_mu = kinematic::cosPitchAngle(
// blitz::TinyVector<double, 3>(0,0,1),
// particle->velocity().cartesianEntries(old_position_cart));
// } else {
// old_mu = kinematic::cosPitchAngle(
// B, particle->velocity().cartesianEntries(old_position_cart));
// }
// new_mu = old_mu;
double timestep = 0;
bool changed_position_bin = false;
@@ -104,7 +90,7 @@ CylinderCoordinate BorisMover::move(particle::Particle* particle,
auto new_position_cart = particle->cartesianPosition();
auto new_velocity = particle->velocity();
B = magnetic_field->value(particle->cylinderPosition()).
B = magnetic_field->value(new_position_cart).
cartesianEntries(new_position_cart);
// if (kinematic::norm(B) == 0) {
+5 -34
View File
@@ -38,11 +38,6 @@
#include "tools/simulation_time.h"
// #ifdef debug_timedist
// #include <fstream>
// #include <iomanip>
// #endif
Simulation::Simulation(std::string parameter_filename)
: parameter_(parameter_filename) {
init(parameter_);
@@ -169,7 +164,7 @@ void Simulation::start() {
timer_->setDeltaT(delta_t);
injector_->initInjectionTimeDistribution(delta_t);
// timer_->increaseTimestep(delta_t);
timer_->increaseTimestep(delta_t);
while (timestep < number_timesteps) {
#if defined(debug_level3)
@@ -197,10 +192,6 @@ void Simulation::start() {
// std::to_string(leftover_events_time_resolution));
#endif
#ifdef GENRICHCURRENT
output_->setResetCurrentCollector(timestep + 1, tracked_species_);
#endif
#ifdef debug
SIM_INFO("Cpu sync.");
#endif
@@ -413,7 +404,8 @@ void Simulation::processUntilTermination(particle::Particle& particle) {
SimulationTimer::eventStopPoint(std::string("Mover"));
bool was_reflected = false;
if (particle.specie()->reflector()->needsReflectionBackToDomain(&particle)) {
if (particle.specie()->reflector()->needsReflectionBackToDomain(
&particle)) {
#ifdef debug_level3
DEBUG_LEVEL_3("Reflect particle.");
#endif
@@ -483,21 +475,13 @@ void Simulation::processUntilTermination(particle::Particle& particle) {
}
#endif
break;
} else if ((particle.specie()->type() == species::ImplementedSpecies::electron) && (particle.kineticEnergy_eV() < 10.) ||
(particle.kineticEnergy_eV() < 0.05)) {
// delete electrons once they can definitely no longer ionize the background particles and delete ions once they fell into the thermal region
if(particle.specie()->deletionLogger()) {
// abuse the "max deletion" deletion type to count the number of particles that are deleted due to falling out of the energy region of interest
particle.specie()->deletionLogger()->logDeletion(particle.cylinderPosition(), DeletionType::max_interactions);
}
break;
}
if ((!(particle.specie()->dynamicDensityField()->changedPositionBin(
if (!(particle.specie()->dynamicDensityField()->changedPositionBin(
old_position, particle.cylinderPosition())) &&
!(particle.specie()->dynamicDensityField()->changedEnergyBin(
old_energy, particle.kineticEnergy_eV())) &&
!was_reflected) || particle.timeUntilCollision() <= 0.) {
!was_reflected) {
#ifdef debug_level3
DEBUG_LEVEL_3("Perform interaction.");
DEBUG_LEVEL_3("Number of Interactions: " +
@@ -597,19 +581,6 @@ void Simulation::collisionTime(particle::Particle& particle, RandomNumbers* rand
interaction::InteractionOutput Simulation::interact(
particle::Particle& particle, RandomNumbers* random) {
// #ifdef debug_timedist
// if(particle.kineticEnergy_eV() > 20 && particle.specie()->type() == species::ImplementedSpecies::electron) {
// std::ofstream file;
// std::stringstream filename;
// filename << MpiCommunication::mpi_rank << "_collisionTimeDistribution.dat";
// file.open(filename.str(), std::ios_base::app);
// file << std::setprecision(16) << particle.timeSinceCollision() << "\n";
// file.close();
// }
// particle.resetTimeSinceCollision();
// #endif
return particle.specie()->interactions().at(particle.indexNextInteraction())
->performInteraction(particle, random);
}
+88
View File
@@ -58,4 +58,92 @@ CylinderVector VectorFieldFunctionInZ::value(
return CylinderVector(blitz::TinyVector<double, 3>(
0., 0.,
F_z_(cylinder_position(0), cylinder_position(1), cylinder_position(2))));
}
PredefinedMagneticVectorFieldLFA::PredefinedMagneticVectorFieldLFA() {
double theta = M_PI/64.;
for(int i = 0; i < 128; ++i) {
cosktheta(i) = std::cos(i*theta);
sinktheta(i) = std::sin(i*theta);
}
z1 = 0.1;
z2 = RIoffe*cosa/sina;
zoffset = 6e-3/sina;
}
// does not make use of the transition functions!!!
CylinderVector PredefinedMagneticVectorFieldLFA::value(const Coordinate& coordinate) const {
// Important that coordinate is a CartesianCoordinate since the transformation from
// CylinderCoordinate to CartesianCoordinate does not work, since phi is not tracked
blitz::TinyVector<double, 3> cartPos = coordinate.cartesianEntries();
double x = cartPos(0); double y = cartPos(1); double z = cartPos(2) + zoffset;
double r = std::sqrt(x*x + y*y);
double Bx, By, Bz;
Bx = 0;
By = 0;
Bz = 0;
double Dp = x*x + y*y + z*z;
double D0 = x*x + y*y + RIoffe*RIoffe;
double Dpk_plus, Dpk_minus, D0k;
// loop to gather cylinder Ioffe contribution
double sign = -1;
for(int i = 0; i < 128; ++i) {
sign *= -1;
D0k = 2*RIoffe*(x*cosktheta(i) + y*sinktheta(i));
Bx += sign*(y - RIoffe*sinktheta(i))/(D0 - D0k);
By += sign*(RIoffe*cosktheta(i) - x)/(D0 - D0k);
}
// only consider the cone contibution close to the cone
if(z < 1.2*z1) {
// loop to gather the cone Ioffe contribution
for(int i = 0; i < 128; i+=4) {
// positive current contribution at index i
Dpk_plus = x*sina*cosktheta(i) + y*sina*sinktheta(i) + z*cosa;
// negative current contribution at index i+1
Dpk_minus = x*sina*cosktheta(i+1) + y*sina*sinktheta(i+1) + z*cosa;
Bx += (z*sina*sinktheta(i) - y*cosa)/(Dp - Dpk_plus*Dpk_plus) -
(z*sina*sinktheta(i+1) - y*cosa)/(Dp - Dpk_minus*Dpk_minus);
By += (x*cosa - z*sina*cosktheta(i) )/(Dp - Dpk_plus*Dpk_plus) -
(x*cosa - z*sina*cosktheta(i+1))/(Dp - Dpk_minus*Dpk_minus);
Bz += (y*sina*cosktheta(i) - x*sina*sinktheta(i) )/(Dp - Dpk_plus*Dpk_plus) -
(y*sina*cosktheta(i+1) - x*sina*sinktheta(i+1))/(Dp - Dpk_minus*Dpk_minus);
}
}
Bx *= B0Ioffe;
By *= B0Ioffe;
Bz *= B0Ioffe;
// Magnetic Bottle
// assume the peak is located 2m away from the transition from cone to cylinder
double zg0 = z1 + 2; // m
double sig2 = 0.211954; // m^2
double B0g = 3.07e-4; // T
double Bzg = std::exp(-(z - zg0)*(z - zg0)/sig2)*B0g;
double Bxg = x*(z-zg0)/sig2*Bzg;
double Byg = y*(z-zg0)/sig2*Bzg;
// add all contributions
Bx += Bxg;
By += Byg;
Bz += Bzg + Bbg;
// transformation into cylinder vector
double Br = Bx*x/r + By*y/r;
double Bphi = By*x/r - Bx*y/r;
return CylinderVector(blitz::TinyVector<double, 3>(Br, Bphi, Bz));
}