diff --git a/src/karl/CurrentHistogram.cpp b/src/karl/CurrentHistogram.cpp new file mode 100644 index 0000000..647a5a8 --- /dev/null +++ b/src/karl/CurrentHistogram.cpp @@ -0,0 +1,122 @@ +#include "CurrentHistogram.h" + +#include +#include +#include + +double binWidth(int num_bins, double min, double max) +{ + return (max-min)/num_bins; +} + +std::vector createEnergyBins(int decade_min, int decade_max) +{ + std::vector bins; + for(int power = decade_min; power < decade_max; ++power){ + for(int num = 1; num < 10; ++num){ + bins.push_back(num*std::pow(10,power)); + } + } + bins.push_back(std::pow(10,decade_max)); + return bins; +} + +int numEnergyBins(int energy_decade_min, int energy_decade_max){ + return (energy_decade_max-energy_decade_min)*9 + 1; +} + +CurrentHistogram::CurrentHistogram( + int num_bin_z, double z_min, double z_max, + int num_bin_r, double r_max, + int energy_decade_min, int energy_decade_max): + dr_(binWidth(num_bin_r, 0., r_max)), + dz_(binWidth(num_bin_z, z_min, z_max)), + z_min_(z_min), + r_min_(0.), + num_bin_z_(num_bin_z), + num_bin_r_(num_bin_r), + energy_bins_(createEnergyBins(energy_decade_min, energy_decade_max)), + hist_data_( + blitz::Range(0, num_bin_r), + blitz::Range(-1, num_bin_z), + blitz::Range(-1, numEnergyBins(energy_decade_min, energy_decade_max)-1)) +{ + hist_data_=0; +} + +int CurrentHistogram::findRadialBin ( + const blitz::TinyVector& position_cart) const +{ + const double r = std::sqrt(position_cart(0)*position_cart(0) + position_cart(1)*position_cart(1)); + const int bin_r = std::floor(r/dr_); + return std::min(bin_r, num_bin_r_); +} + +int CurrentHistogram::findLongitudinalBin ( + const blitz::TinyVector& position_cart) const +{ + const int bin_z = std::floor((position_cart(2)-z_min_)/dz_); + return std::min(std::max(-1,bin_z),num_bin_z_); +} + +int CurrentHistogram::findEnergyBin(double energy) const +{ + auto const it = std::lower_bound(energy_bins_.begin(), energy_bins_.end(), energy); + //if (it == energy_bins_.end()) { return energy_bins_.size(); } + //if (it == energy_bins_.begin()){ return -1;}; + return (it-energy_bins_.begin())-1; +} + +void CurrentHistogram::fill( + const blitz::TinyVector& position_cart, + double energy) +{ + const int bin_z = findLongitudinalBin(position_cart); + const int bin_r = findRadialBin(position_cart); + const int bin_E = findEnergyBin(energy); + hist_data_(bin_r, bin_z, bin_E) += static_cast(1); +} + +void CurrentHistogram::fill(int bin_r, int bin_z, double energy) +{ + const int bin_E = findEnergyBin(energy); + if(hist_data_.isInRange(bin_r, bin_z, bin_E)){ + hist_data_(bin_r, bin_z, bin_E) += static_cast(1); + } +} + +blitz::TinyVector CurrentHistogram::binDifference( + const blitz::TinyVector& new_position_cart, + const blitz::TinyVector& old_position_cart) +{ + const int bin_z_old = findLongitudinalBin(old_position_cart); + const int bin_r_old = findRadialBin(old_position_cart); + + const int bin_z_new = findLongitudinalBin(new_position_cart); + const int bin_r_new = findRadialBin(new_position_cart); + + return blitz::TinyVector(bin_r_new-bin_r_old, bin_z_new-bin_z_old); +} + +std::vector CurrentHistogram::binBordersR() const +{ + std::vector bin_border_r; + for(int i = 0; i <= num_bin_r_; ++i){ + const double border = r_min_ + i*dr_; + bin_border_r.push_back(border); + } + return bin_border_r; +} +std::vector CurrentHistogram::binBordersZ() const +{ + std::vector bin_border_z; + for(int i = 0; i <= num_bin_z_; ++i){ + const double border = z_min_ + i*dz_; + bin_border_z.push_back(border); + } + return bin_border_z; +} +std::vector CurrentHistogram::binBordersE() const +{ + return energy_bins_; +} \ No newline at end of file diff --git a/src/karl/CurrentHistogram.h b/src/karl/CurrentHistogram.h new file mode 100644 index 0000000..09bc394 --- /dev/null +++ b/src/karl/CurrentHistogram.h @@ -0,0 +1,52 @@ +#ifndef CURRENTHISTOGRAM_H +#define CURRENTHISTOGRAM_H + +#include "blitz/array.h" +#include + +class CurrentHistogram { + public: + CurrentHistogram( + int num_bin_z, double z_min, double z_max, + int num_bin_r, double r_max, + int energy_decade_min, int energy_decade_max); + + void fill( + const blitz::TinyVector& position_cart, + double energy); + + void fill(int bin_r, int bin_z, double energy); + + int findRadialBin( + const blitz::TinyVector& position_cart) const; + + int findLongitudinalBin( + const blitz::TinyVector& position_cart) const; + + int findEnergyBin( + double energy) const; + + blitz::TinyVector binDifference( + const blitz::TinyVector& new_position_cart, + const blitz::TinyVector& old_position_cart); + + blitz::Array hist_data_; + + std::vector binBordersR() const; + std::vector binBordersZ() const; + std::vector binBordersE() const; + private: + + const std::vector energy_bins_; + + const double dz_; + const double dr_; + + const double z_min_; + const double r_min_; + + const int num_bin_z_; + const int num_bin_r_; +}; + +#endif /* CURRENTHISTOGRAM_H */ diff --git a/src/karl/CurrentLogger.cpp b/src/karl/CurrentLogger.cpp new file mode 100644 index 0000000..72e6143 --- /dev/null +++ b/src/karl/CurrentLogger.cpp @@ -0,0 +1,191 @@ +#include "CurrentLogger.h" +#include "particle.hpp" + +#include "highfive/H5File.hpp" +#include "highfive/H5DataSet.hpp" + +#include + +CurrentLogger::CurrentLogger( + species this_species, + int num_planes_z, double z_min, double z_max, + int num_planes_r, double r_max, + int energy_decade_min, int energy_decade_max, + std::string output_filename): + Particle_Logger_Base(this_species), + N_pos_r( + num_planes_z, z_min, z_max, + num_planes_r, r_max, + energy_decade_min, energy_decade_max ), + N_neg_r( + num_planes_z, z_min, z_max, + num_planes_r, r_max, + energy_decade_min, energy_decade_max ), + N_pos_z( + num_planes_z, z_min, z_max, + num_planes_r, r_max, + energy_decade_min, energy_decade_max ), + N_neg_z( + num_planes_z, z_min, z_max, + num_planes_r, r_max, + energy_decade_min, energy_decade_max ), + output_filename_(output_filename) +{ + writeBinBorderData(); +} + +void CurrentLogger::log(const Particle& logPart, const vec3& old_loc_m) +{ + if (!logging) { + return; + } + + const vec3 new_loc_m = logPart.get_x_m(); + + const int bin_r_new = N_pos_r.findRadialBin(new_loc_m); + const int bin_z_new = N_pos_r.findLongitudinalBin(new_loc_m); + + const int bin_r_old = N_pos_r.findRadialBin(old_loc_m); + const int bin_z_old = N_pos_r.findLongitudinalBin(old_loc_m); + + const int delta_bin_r = bin_r_new - bin_r_old; + const int delta_bin_z = bin_z_new - bin_z_old; + + //std::cout << "bin_z_new " << bin_z_new << std::endl; + //std::cout << "bin_z_old " << bin_z_old << std::endl; + + //if(std::abs(delta_bin_z) > 1){ + // std::cout << "Moved bins: " << delta_bin_z << std::endl; + //} + + if((delta_bin_r ==0) && (delta_bin_z == 0)){ + // do nothing + } + else{ + const double energy = logPart.get_E_eV(); + + if(delta_bin_z >= 1){ + for(int i = 0; i < delta_bin_z; ++i){ + N_pos_z.fill(bin_r_old, bin_z_old+i, energy); + } + //N_pos_z.fill(bin_r_old, bin_z_old, energy); + } + else if(delta_bin_z <= -1) { + for(int i = 0; i < std::abs(delta_bin_z); ++i){ + N_neg_z.fill(bin_r_old, bin_z_old-i, energy); + } + //N_neg_z.fill(bin_r_old, bin_z_old, energy); + } + + if(delta_bin_r == 1){ + N_pos_r.fill(bin_r_old, bin_z_old, energy); + } + else if(delta_bin_r == -1) { + N_neg_r.fill(bin_r_old, bin_z_old, energy); + } + } +} +void CurrentLogger::flush() +{ + // do nothing +} + +void CurrentLogger::writeBinBorderData() +{ + std::string filename = output_filename_+"_currents.h5"; + std::string group = "/" + get_species_string(this->get_species()) + "/current_bin_borders"; + + HighFive::File file( + filename, + HighFive::File::ReadWrite | HighFive::File::Create); + + if(!file.exist(group)){ + file.createGroup(group); + } + + auto bin_borders_E = N_pos_z.binBordersE(); + std::string path_E = group + "/bin_borders_E"; + + if(file.exist(path_E)){ + HighFive::DataSet dataset = file.getDataSet(path_E); + dataset.write(bin_borders_E); + } else{ + HighFive::DataSet dataset = + file.createDataSet(path_E, HighFive::DataSpace::From(bin_borders_E)); + dataset.write(bin_borders_E); + } + + + auto bin_borders_r = N_pos_z.binBordersR(); + std::string path_r = group + "/bin_borders_r"; + if(file.exist(path_r)){ + HighFive::DataSet dataset = file.getDataSet(path_r); + dataset.write(bin_borders_r); + } else{ + HighFive::DataSet dataset = + file.createDataSet(path_r, HighFive::DataSpace::From(bin_borders_r)); + dataset.write(bin_borders_r); + } + + auto bin_borders_z = N_pos_z.binBordersZ(); + std::string path_z = group + "/bin_borders_z"; + if(file.exist(path_z)){ + HighFive::DataSet dataset = file.getDataSet(path_z); + dataset.write(bin_borders_z); + } else{ + HighFive::DataSet dataset = + file.createDataSet(path_z, HighFive::DataSpace::From(bin_borders_z)); + dataset.write(bin_borders_z); + } +} + +void CurrentLogger::output() +{ + output("N_pos_z", N_pos_z.hist_data_); + output("N_neg_z", N_neg_z.hist_data_); + output("N_pos_r", N_pos_r.hist_data_); + output("N_neg_r", N_neg_r.hist_data_); +} + +void CurrentLogger::output( + std::string dataname, const blitz::Array& data) +{ + std::string filename = output_filename_+"_currents.h5"; + std::string group = "/" + get_species_string(this->get_species()); + std::string path = group+"/"+dataname; + + HighFive::File file( + filename, + HighFive::File::ReadWrite | HighFive::File::Create); + + if(!file.exist(group)){ + file.createGroup(group); + } + + blitz::TinyVector start = data.lbound(); + blitz::TinyVector end = data.ubound(); + + std::vector>> data_v; + for(int i = start(0); i<=end(0); ++i){ + std::vector> zs; + for(int j = start(1); j<=end(1); ++j){ + std::vector energies; + for(int k = start(2); k<=end(2); ++k){ + energies.push_back(data(i,j,k)); + } + zs.push_back(energies); + } + data_v.push_back(zs); + } + + if(file.exist(path)){ + HighFive::DataSet dataset = file.getDataSet(path); + dataset.write(data_v); + } else{ + HighFive::DataSet dataset = + file.createDataSet(path, HighFive::DataSpace::From(data_v)); + dataset.write(data_v); + } +} + + diff --git a/src/karl/CurrentLogger.h b/src/karl/CurrentLogger.h new file mode 100644 index 0000000..8c1740f --- /dev/null +++ b/src/karl/CurrentLogger.h @@ -0,0 +1,36 @@ +#ifndef CURRENTLOGGER_H +#define CURRENTLOGGER_H + +#include "particle_logger_base.h" +#include "CurrentHistogram.h" + +class CurrentLogger : public Particle_Logger_Base { + public: + CurrentLogger( + species this_species, + int num_planes_z, double z_min, double z_max, + int num_planes_r, double r_max, + int energy_decade_min, int energy_decade_max, + std::string output_filename); + + void log(const Particle& logPart, const vec3& old_loc_m); + void flush(); + void output(); + + private: + CurrentHistogram N_pos_r; + CurrentHistogram N_neg_r; + + CurrentHistogram N_pos_z; + CurrentHistogram N_neg_z; + + const std::string output_filename_; + + void output( + std::string dataname, + const blitz::Array& data); + + void writeBinBorderData(); +}; + +#endif /* CURRENTLOGGER_H */ diff --git a/src/karl/Ion_Mover_Boris.cpp b/src/karl/Ion_Mover_Boris.cpp new file mode 100644 index 0000000..dd273f1 --- /dev/null +++ b/src/karl/Ion_Mover_Boris.cpp @@ -0,0 +1,115 @@ +#include "Ion_Mover_Boris.h" + +Ion_Mover_Boris::Ion_Mover_Boris( + species this_species, + Particle_Logger_Base *Logger, + Population_Base *Population, + double B_max): + Mover_Base(this_species, Logger, Population) +{ + if(B_max == 0.){ + dt_s = 1.; + } else{ + dt_s = Population->get_m_eV()/(B_max*c_ms*c_ms); + } +}; + + +void Ion_Mover_Boris::move(Particle *movePart, const double ¯o_sigma_m) +{ + // Prepare detection for change of z direction for logging + double oldzDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; + vec3 oldLoc_m = movePart->get_x_m(); + + if (macro_sigma_m == 0) { // If infinite movement distance let electron leave at only exit... Prob extremly faulty, but also impossible. + movePart->set_x_m(z_RW_m); + Logger->log(*movePart,oldLoc_m); + return; + } + + double distance_m = 1/macro_sigma_m; + + double traveledDistance_m = 0; + vec3 loc_m, E_Vm ,B_T; + while (traveledDistance_m < distance_m) { + loc_m = movePart->get_x_m(); + E_Vm = Katrin_Fields::getElField_Vm(loc_m); + B_T = Katrin_Fields::getMagField_T(loc_m); + + traveledDistance_m += doBoris_singleStep_m(movePart, E_Vm, B_T); + if (doBoris_WallInteraction(movePart) == true) { + Logger->log(*movePart, oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + return; + } + doBoris_LogzDirChange(movePart, &oldzDir, &oldLoc_m); // Log if z direction changes, and adapt quantities + } + Logger->log(*movePart,oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + return; +} + +double Ion_Mover_Boris::doBoris_singleStep_m(Particle *movePart, const vec3 &E_Vm , const vec3 &B_T) +{ + double distance_m; + vec3 x_m = movePart->get_x_m(); + vec3 v_ms = movePart->get_v_ms(); + x_m += dt_s/2 * v_ms; + distance_m = dt_s/2 * calc_vec3_abs(v_ms); + doBoris_speedChange(movePart, E_Vm , B_T); + x_m += dt_s/2 * v_ms; + distance_m += dt_s/2 * calc_vec3_abs(v_ms); + movePart->set_x_m(x_m); + return distance_m; +} + +void Ion_Mover_Boris::doBoris_speedChange(Particle *movePart, const vec3 &E_Vm, const vec3 &B_T) { + double q_C = movePart->get_Z() * e_C; + double m_kg = movePart->get_m_eV() * e_C/c_ms/c_ms; + vec3 v_ms = movePart->get_v_ms(); + + vec3 t = q_C*dt_s/(2*m_kg) * B_T; + vec3 s = (2*t)/(1+dot(t,t)); + vec3 vMinus_ms = v_ms + (q_C*E_Vm*dt_s)/(2*m_kg); + vec3 vPrime_ms = vMinus_ms + cross(vMinus_ms,t); + vec3 vPlus_ms = vMinus_ms + cross(vPrime_ms,s); + v_ms = vPlus_ms + q_C/m_kg*E_Vm*0.5*dt_s; + movePart->set_v_ms(v_ms); +} + +bool Ion_Mover_Boris::doBoris_WallInteraction(Particle *movePart) { + vec3 loc_m = movePart->get_x_m(); + double r_m = movePart->get_r_m(); + if (loc_m[2]<=z_RW_m) { // Rear Wall Termination + vec3 newLoc_m = movePart->get_x_m(); + newLoc_m[2] = 0; + movePart->set_x_m(newLoc_m); + return true; + } + if (r_m>=r_WGTS_m) { // WGTS Wall Termination + vec3 newLoc_m = movePart->get_x_m(); + double z_m = newLoc_m[2]; + newLoc_m[2] = 0; + newLoc_m = (r_WGTS_m * 1.01)/calc_vec3_abs(newLoc_m) * newLoc_m; //1.01 to move Particle slightly out of WGTS + newLoc_m[2] = z_m; + return true; + } + if (loc_m[2]>=z_WGTS_end_m) { // DPS Absorption + vec3 newLoc_m = movePart->get_x_m(); + newLoc_m[2] = z_WGTS_end_m; + movePart->set_x_m(newLoc_m); + return true; + } + return false; +} + +void Ion_Mover_Boris::doBoris_LogzDirChange(Particle *movePart, double *oldzDir, vec3 *oldLoc_m) { + double zDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; + if (*oldzDir != zDir) { + Logger->log(*movePart, *oldLoc_m); + Population->increase_density(*movePart, *oldLoc_m); + *oldzDir = zDir; + *oldLoc_m = movePart->get_x_m(); + } + return; +} diff --git a/src/karl/Ion_Mover_Boris.h b/src/karl/Ion_Mover_Boris.h new file mode 100644 index 0000000..6b41513 --- /dev/null +++ b/src/karl/Ion_Mover_Boris.h @@ -0,0 +1,26 @@ +#ifndef ION_MOVER_BORIS_H +#define ION_MOVER_BORIS_H + +#include "mover_base.h" +#include "constants.h" + +class Ion_Mover_Boris : public Mover_Base { + double dt_s; +public: + Ion_Mover_Boris( + species this_species, + Particle_Logger_Base *Logger, + Population_Base *Population, + double B_max); + + void move(Particle *movePart, const double ¯o_sigma_m); + +private: + double doBoris_singleStep_m(Particle *movePart, const vec3 &E_Vm , const vec3 &B_T); + void doBoris_speedChange(Particle *movePart, const vec3 &E_Vm, const vec3 &B_T); + bool doBoris_WallInteraction(Particle *movePart); + void doBoris_LogzDirChange(Particle *movePart, double *oldzDir, vec3 *oldLoc_m); +}; + + +#endif /* ION_MOVER_BORIS_H */ diff --git a/src/karl/T3IT2_elastic.cpp b/src/karl/T3IT2_elastic.cpp new file mode 100644 index 0000000..6ee7a1f --- /dev/null +++ b/src/karl/T3IT2_elastic.cpp @@ -0,0 +1,40 @@ +#include "T3IT2_elastic.h" +#include "katrin_fields.hpp" + + +T3IT2_Elastic::T3IT2_Elastic( + Population_Base *T2Population, + UniRNG *rngUni) + : TI_thermal_binary_Precomputed_Interaction_Base( + T2Population, rngUni, 3*mT_eV), + kinematics(3*mT_eV, 2*mT_eV) +{ + calc_values(); // need to call here, because, constructor can't call pure virtual function +}; + +double T3IT2_Elastic::get_microSigma_m2(const double &E_eV) +{ + return tcs_gen.get_TCS(E_eV); +} + +InteractionOut T3IT2_Elastic::do_Interaction (Particle *interPart) +{ + const vec3 v1_ms = interPart->get_v_ms(); + const vec3 loc_m = interPart->get_x_m(); + const vec3 v2_ms = Population->roll_v_ms(loc_m); + const double theta_lab = rngUni->random() * pi; + const double phi_lab = rngUni->random() * 2 * pi; + const vec3 v_new = kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab); + interPart->set_v_ms(v_new); + + const double v_perp = std::sqrt(v_new(0)*v_new(0) + v_new(1)*v_new(1)); + + const double rG_m = v_perp*interPart->get_m_eV()/(Katrin_Fields::getMagField_T(loc_m)(2)*c_ms*c_ms); + const double gyro_centrum_move_m = 2*rG_m * std::sin(theta_lab); + const double x_new = loc_m(0) + std::sin(phi_lab)*gyro_centrum_move_m; + const double y_new = loc_m(1) + std::cos(phi_lab)*gyro_centrum_move_m; + interPart->set_x_m(vec3(x_new, y_new, loc_m(2))); + + return InteractionOut(); +} + diff --git a/src/karl/T3IT2_elastic.h b/src/karl/T3IT2_elastic.h index 99efa68..9071d94 100644 --- a/src/karl/T3IT2_elastic.h +++ b/src/karl/T3IT2_elastic.h @@ -1,39 +1,21 @@ -// -// T3IT2_elastic.h -// mc_electron -// -// Created by Christian Reiling on 13.09.19. -// Copyright © 2019 Christian Reiling. All rights reserved. -// - #ifndef T3IT2_elastic_h #define T3IT2_elastic_h #include "TI_thermal_binary_base.h" #include "tabata_T3IT2_elastic.h" +#include "kinematics_base.h" class T3IT2_Elastic : public TI_thermal_binary_Precomputed_Interaction_Base { Tabata_T3IT2_Elastic tcs_gen; Elastic_Kinematic_Base kinematics; -public: - T3IT2_Elastic(Population_Base *T2Population, UniRNG *rngUni) : TI_thermal_binary_Precomputed_Interaction_Base(T2Population, rngUni, 3*mT_eV), kinematics(3*mT_eV, 2*mT_eV) { - calc_values(); // need to call here, because, constructor can't call pure virtual function - }; + public: + T3IT2_Elastic(Population_Base *T2Population, UniRNG *rngUni); - double get_microSigma_m2(const double &E_eV) {return tcs_gen.get_TCS(E_eV);} + double get_microSigma_m2(const double &E_eV); InteractionOut do_Interaction (Particle *interPart); }; -inline InteractionOut T3IT2_Elastic::do_Interaction (Particle *interPart) { - vec3 v1_ms = interPart->get_v_ms(); - vec3 v2_ms = Population->roll_v_ms(interPart->get_x_m()); - double theta_lab = rngUni->random() * pi; - double phi_lab = rngUni->random() * 2 * pi; - interPart->set_v_ms(kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab)); - return InteractionOut(); -} - #endif /* T3IT2_elastic_h */ diff --git a/src/karl/TIT2_elastic.cpp b/src/karl/TIT2_elastic.cpp new file mode 100644 index 0000000..16dd825 --- /dev/null +++ b/src/karl/TIT2_elastic.cpp @@ -0,0 +1,39 @@ +#include "TIT2_elastic.h" +#include "katrin_fields.hpp" + + +TIT2_Elastic::TIT2_Elastic( + Population_Base *T2Population, + UniRNG *rngUni) + : TI_thermal_binary_Precomputed_Interaction_Base(T2Population, rngUni, mT_eV), + kinematics(mT_eV, 2*mT_eV) +{ + calc_values(); // need to call here, because, constructor can't call pure virtual function +}; + +double TIT2_Elastic::get_microSigma_m2(const double &E_eV) +{ + return tcs_gen.get_TCS(E_eV); +} + +InteractionOut TIT2_Elastic::do_Interaction (Particle *interPart) +{ + const vec3 v1_ms = interPart->get_v_ms(); + const vec3 loc_m = interPart->get_x_m(); + const vec3 v2_ms = Population->roll_v_ms(loc_m); + const double theta_lab = rngUni->random() * pi; + const double phi_lab = rngUni->random() * 2 * pi; + const vec3 v_new = kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab); + interPart->set_v_ms(v_new); + + const double v_perp = std::sqrt(v_new(0)*v_new(0) + v_new(1)*v_new(1)); + + const double rG_m = v_perp*interPart->get_m_eV()/(Katrin_Fields::getMagField_T(loc_m)(2)*c_ms*c_ms); + const double gyro_centrum_move_m = 2*rG_m * std::sin(theta_lab); + const double x_new = loc_m(0) + std::sin(phi_lab)*gyro_centrum_move_m; + const double y_new = loc_m(1) + std::cos(phi_lab)*gyro_centrum_move_m; + interPart->set_x_m(vec3(x_new, y_new, loc_m(2))); + + return InteractionOut(); +} + diff --git a/src/karl/TIT2_elastic.h b/src/karl/TIT2_elastic.h index 345167f..32e8f88 100644 --- a/src/karl/TIT2_elastic.h +++ b/src/karl/TIT2_elastic.h @@ -1,39 +1,20 @@ -// -// TIT2_elastic.h -// mc_electron -// -// Created by Christian Reiling on 13.09.19. -// Copyright © 2019 Christian Reiling. All rights reserved. -// - #ifndef TIT2_elastic_h #define TIT2_elastic_h #include "TI_thermal_binary_base.h" #include "tabata_TIT2_elastic.h" - +#include "kinematics_base.h" class TIT2_Elastic : public TI_thermal_binary_Precomputed_Interaction_Base { Tabata_TIT2_Elastic tcs_gen; Elastic_Kinematic_Base kinematics; public: - TIT2_Elastic(Population_Base *T2Population, UniRNG *rngUni) : TI_thermal_binary_Precomputed_Interaction_Base(T2Population, rngUni, mT_eV), kinematics(mT_eV, 2*mT_eV) { - calc_values(); // need to call here, because, constructor can't call pure virtual function - }; + TIT2_Elastic(Population_Base *T2Population, UniRNG *rngUni); - double get_microSigma_m2(const double &E_eV) {return tcs_gen.get_TCS(E_eV);} + double get_microSigma_m2(const double &E_eV); InteractionOut do_Interaction (Particle *interPart); }; -inline InteractionOut TIT2_Elastic::do_Interaction (Particle *interPart) { - vec3 v1_ms = interPart->get_v_ms(); - vec3 v2_ms = Population->roll_v_ms(interPart->get_x_m()); - double theta_lab = rngUni->random() * pi; - double phi_lab = rngUni->random() * 2 * pi; - interPart->set_v_ms(kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab)); - return InteractionOut(); -} - #endif /* TIT2_elastic_h */ diff --git a/src/karl/TI_kinetic_base.h b/src/karl/TI_kinetic_base.h index 81d91b6..521ffa6 100644 --- a/src/karl/TI_kinetic_base.h +++ b/src/karl/TI_kinetic_base.h @@ -71,7 +71,7 @@ inline double TI_e_Interaction_Base::calc_microSigma_m2(const double &E2_eV, con double E_eV = m1_eV/2 * (pow(v1_ms,2) + pow(v2_ms,2) - 2*v1_ms*v2_ms*cos(theta)) * pow(c_ms, -2); return get_microSigma_m2(E_eV); }; - return integrate(integrand, 0., pi, INT_N, simpson())/pi; + return integrate(integrand, pi/8., 7*pi/8., INT_N, simpson())/pi; } } diff --git a/src/karl/TI_thermal_binary_base.h b/src/karl/TI_thermal_binary_base.h index f97217d..eda62d3 100644 --- a/src/karl/TI_thermal_binary_base.h +++ b/src/karl/TI_thermal_binary_base.h @@ -52,7 +52,7 @@ inline double TI_thermal_binary_Interaction_Base::calc_microSigma_m2(const doubl double E_eV = m1_eV/2 * (pow(v1_ms,2) + pow(v2_ms,2) - 2*v1_ms*v2_ms*cos(theta)) * pow(c_ms, -2); return Population->get_v_pdf(v2_ms)*get_microSigma_m2(E_eV)/pi; }; - return double_simpson_integrate(integrand, 0., 3*v_therm, 0., pi, INT_N, INT_N); // 3*v_therm equals 99% of the integral + return double_simpson_integrate(integrand, 0., 3*v_therm, pi/8., 7.*pi/8., INT_N, INT_N); // 3*v_therm equals 99% of the integral /* // Integration over theta auto integrand = [&](double theta) { double E_eV = m1_eV/2 * (pow(v1_ms,2) + pow(v_therm,2) - 2*v1_ms*v_therm*cos(theta)) * pow(c_ms, -2); diff --git a/src/karl/TI_thermal_tenary_base.h b/src/karl/TI_thermal_tenary_base.h index c80110f..97ee2a8 100644 --- a/src/karl/TI_thermal_tenary_base.h +++ b/src/karl/TI_thermal_tenary_base.h @@ -51,7 +51,7 @@ inline double TI_thermal_tenary_Interaction_Base::calc_microSigma_divbyn_m2(cons double E_eV = m1_eV/2 * (pow(v1_ms,2) + pow(v_therm,2) - 2*v1_ms*v_therm*cos(theta)) * pow(c_ms, -2); return get_microSigma_m2(E_eV); }; - return integrate(integrand, 0., pi, INT_N, simpson())/pi; + return integrate(integrand, pi/8., 7.*pi/8., INT_N, simpson())/pi; } class TI_thermal_tenary_Precomputed_Interaction_Base : public TI_thermal_tenary_Interaction_Base { // Precomputed Interactions of electrons with thermal Populations diff --git a/src/karl/current_histogram_test.cpp b/src/karl/current_histogram_test.cpp new file mode 100644 index 0000000..53fecbe --- /dev/null +++ b/src/karl/current_histogram_test.cpp @@ -0,0 +1,151 @@ +#include "catch.hpp" + +#include "CurrentHistogram.h" + +#include +#include +#include + +TEST_CASE("Current Histogram", "[CurrentHistogram]"){ + + + SECTION("Bins are calculated correctly"){ + int decade_min = -1; + int decade_max = 0; + int num_bin_z = 2; + int num_bin_r = 2; + double z_min = -3; + double z_max = 10; + double r_max = 0.045; + CurrentHistogram hist( + num_bin_z, z_min, z_max, + num_bin_r, r_max, + decade_min, decade_max); + SECTION("Radial bins outside"){ + REQUIRE(hist.findRadialBin( + blitz::TinyVector(1., 0., 0.)) + == 2); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(-1., 0., 0.)) + == 2); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0., 1., 0.)) + == 2); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(-0., -1., 0.)) + == 2); + } + + SECTION("Radial bins inside"){ + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0.04, 0., 0.)) + == 1); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(-0.04, 0., 0.)) + == 1); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0., 0.04, 0.)) + == 1); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0., -0.04, 0.)) + == 1); + + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0.02, 0., 0.)) + == 0); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(-0.02, 0., 0.)) + == 0); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0., 0.02, 0.)) + == 0); + REQUIRE(hist.findRadialBin( + blitz::TinyVector(0., -0.02, 0.)) + == 0); + } + + SECTION("Longitudinal bins outside"){ + REQUIRE(hist.findLongitudinalBin( + blitz::TinyVector(0., 0., 13.)) + == 2); + REQUIRE(hist.findLongitudinalBin( + blitz::TinyVector(0., 0., -4.)) + == -1); + } + + SECTION("Longitudinal bins inside"){ + REQUIRE(hist.findLongitudinalBin( + blitz::TinyVector(0.04, 0., -2.9)) + == 0); + REQUIRE(hist.findLongitudinalBin( + blitz::TinyVector(-0.04, 0., 9.5)) + == 1); + } + + SECTION("Energy bins outside"){ + REQUIRE(hist.findEnergyBin(1E-2) == -1); + REQUIRE(hist.findEnergyBin(1E1) == 9); + } + + SECTION("Energy bins at boundary"){ + REQUIRE(hist.findEnergyBin(1E-1) == 0); + REQUIRE(hist.findEnergyBin(0.99999999999) == 8); + } + + SECTION("Energy bins inside"){ + REQUIRE(hist.findEnergyBin(1.1E-1) == 0); + REQUIRE(hist.findEnergyBin(2.2E-1) == 1); + REQUIRE(hist.findEnergyBin(3.9E-1) == 2); + REQUIRE(hist.findEnergyBin(8.5E-1) == 7); + REQUIRE(hist.findEnergyBin(9.5E-1) == 8); + } + } + + SECTION("Correct value in array is filled"){ + int decade_min = -5; + int decade_max = -4; + int num_bin_z = 2; + int num_bin_r = 2; + double z_min = -3; + double z_max = 10; + double r_max = 0.045; + + CurrentHistogram hist( + num_bin_z, z_min, z_max, + num_bin_r, r_max, + decade_min, decade_max); + + hist.fill(blitz::TinyVector(0.04, 0., 0.5), 3.1E-5); + hist.fill(blitz::TinyVector(0.02, 0., 9.5), 4.1E-5); + REQUIRE(hist.hist_data_(1,0,2) == 1); + REQUIRE(hist.hist_data_(0,1,3) == 1); + } + SECTION("Bin Borders"){ + int decade_min = -5; + int decade_max = -3; + int num_bin_z = 2; + int num_bin_r = 2; + double z_min = -3; + double z_max = 10; + double r_max = 0.045; + + CurrentHistogram hist( + num_bin_z, z_min, z_max, + num_bin_r, r_max, + decade_min, decade_max); + + auto e_bins = hist.binBordersE(); + REQUIRE(e_bins[0] == Approx(std::pow(10,decade_min))); + REQUIRE(e_bins.back() == Approx(std::pow(10,decade_max))); + + auto r_bins = hist.binBordersR(); + REQUIRE(r_bins[0] == 0); + REQUIRE(r_bins[1] == r_max/num_bin_r); + REQUIRE(r_bins.back() == r_max); + + auto z_bins = hist.binBordersZ(); + REQUIRE(z_bins[0] == z_min); + REQUIRE(z_bins[1] == z_min + (z_max-z_min)/num_bin_z); + REQUIRE(z_bins.back() == z_max); + } +} \ No newline at end of file diff --git a/src/karl/current_logger_test.cpp b/src/karl/current_logger_test.cpp new file mode 100644 index 0000000..4ab0b04 --- /dev/null +++ b/src/karl/current_logger_test.cpp @@ -0,0 +1,50 @@ +#include "catch.hpp" + +#include "CurrentHistogram.h" +#include "CurrentLogger.h" +#include "particle.hpp" + +#include +#include +#include + +TEST_CASE("Current Logger", "[CurrentLogger]"){ + + + SECTION("Radial bins are filled"){ + int numberZBins = 14; + int numberRBins = 5; + int energy_decade_min = -5; + int energy_decade_max = 4; + + + CurrentLogger logger( + electron, + numberZBins, z_RW_m, z_WGTS_end_m, + numberRBins, r_WGTS_m, + energy_decade_min, energy_decade_max, + "/home/jonas/new_workspace/Coding/Output/KARL/test/output"); + + SECTION("Radial bins outside"){ + double m_eV = 511E3; + double charge_e = -1*e_C; + vec3 v_ms(0., 0., 1.); + double Id = 1.; + double Pid = 1.; + + vec3 old_loc_m(0.04, 0., -3.); + vec3 loc_m(0.04,0.0,-2.5); + Particle particle(m_eV, charge_e, loc_m, v_ms, Id, Pid, electron); + + logger.log(particle, old_loc_m); + + logger.output(); + + REQUIRE(true); + } + } +} + +TEST_CASE("Code", "[Code]"){ + +} \ No newline at end of file diff --git a/src/karl/data/E_field.h5 b/src/karl/data/E_field.h5 new file mode 100644 index 0000000..1f0f304 Binary files /dev/null and b/src/karl/data/E_field.h5 differ diff --git a/src/karl/data/E_field_zero.h5 b/src/karl/data/E_field_zero.h5 index aff0622..80ec76b 100644 Binary files a/src/karl/data/E_field_zero.h5 and b/src/karl/data/E_field_zero.h5 differ diff --git a/src/karl/drift_base.cpp b/src/karl/drift_base.cpp new file mode 100644 index 0000000..af72384 --- /dev/null +++ b/src/karl/drift_base.cpp @@ -0,0 +1,78 @@ +#include "drift_base.h" +#include "katrin_fields.hpp" +#include +#include "constants.h" + +bool leftSimulation(const vec3& position) +{ + return (position(2) <= z_RW_m) + || (position(2) >= z_WGTS_end_m) + || (position(0)*position(0)+position(1)*position(1) >= r_WGTS_m); +} + +void Drift_Base::move(Particle *movePart, const double ¯o_sigma_m) { + vec3 oldLoc_m = movePart->get_x_m(); + vec3 newLoc_m = oldLoc_m; + + const double dz = std::min(Katrin_Fields::E_field_ptr->stepSize(2),0.5); + + const double distance = 1./macro_sigma_m; + + const int n = std::floor(distance/dz); + + bool left_simulation = false; + + const double part_macro_sigma_m = 1./dz; + for(int step = 0; step < n; ++step){ + double znew_m = get_zNew_m(movePart, part_macro_sigma_m); + doWallInteraction(movePart, &oldLoc_m, &znew_m); + newLoc_m[2] = znew_m; + + movePart->set_x_m(newLoc_m); + do_E_calculus(movePart, oldLoc_m, part_macro_sigma_m); + Logger->log(*movePart, oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + oldLoc_m = newLoc_m; + + left_simulation = leftSimulation(oldLoc_m); + if(left_simulation){ + break; + } + } + if(!left_simulation){ + const double rest = std::fmod(distance,dz); + const double rest_macro_sigma = 1./rest; + + double znew_m = get_zNew_m(movePart, rest_macro_sigma); + doWallInteraction(movePart, &oldLoc_m, &znew_m); + newLoc_m[2] = znew_m; + + movePart->set_x_m(newLoc_m); + do_E_calculus(movePart, oldLoc_m, rest_macro_sigma); + Logger->log(*movePart, oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + } +} + + + +double Drift_Base::get_zNew_m(Particle *movePart, const double ¯o_sigma_m) { + double zold_m = movePart->get_x_m()[2]; + + vec3 v_ms = movePart->get_v_ms(); + double vTotAbs_ms = calc_vec3_abs(v_ms); + double vForwardAbs_ms = calc_vec3_abs(vec3(0,0,v_ms[2])); + double zDir = v_ms[2] <= 0 ? -1 : 1; + double znew_m; + if (macro_sigma_m == 0) { + if (zDir == -1) { + znew_m = z_RW_m - 2*l_WGTS_m; + } else { + znew_m = z_WGTS_end_m + 2*l_WGTS_m; + } + } else { + double distance_m = 1/macro_sigma_m; + znew_m = zold_m + zDir*vForwardAbs_ms/vTotAbs_ms * distance_m; + } + return znew_m; +} \ No newline at end of file diff --git a/src/karl/drift_base.h b/src/karl/drift_base.h index 264bfbc..9a61c65 100644 --- a/src/karl/drift_base.h +++ b/src/karl/drift_base.h @@ -26,41 +26,4 @@ protected: }; -inline void Drift_Base::move(Particle *movePart, const double ¯o_sigma_m) { - vec3 oldLoc_m = movePart->get_x_m(); - vec3 newLoc_m = oldLoc_m; - - double znew_m = get_zNew_m(movePart, macro_sigma_m); - doWallInteraction(movePart, &oldLoc_m, &znew_m); - newLoc_m[2] = znew_m; - - movePart->set_x_m(newLoc_m); - do_E_calculus(movePart, oldLoc_m, macro_sigma_m); - Logger->log(*movePart, oldLoc_m); - Population->increase_density(*movePart, oldLoc_m); -} - -inline double Drift_Base::get_zNew_m(Particle *movePart, const double ¯o_sigma_m) { - double zold_m = movePart->get_x_m()[2]; - - vec3 v_ms = movePart->get_v_ms(); - double vTotAbs_ms = calc_vec3_abs(v_ms); - double vForwardAbs_ms = calc_vec3_abs(vec3(0,0,v_ms[2])); - double zDir = v_ms[2] <= 0 ? -1 : 1; - double znew_m; - if (macro_sigma_m == 0) { - if (zDir == -1) { - znew_m = z_RW_m - 2*l_WGTS_m; - } else { - znew_m = z_WGTS_end_m + 2*l_WGTS_m; - } - } else { - double distance_m = 1/macro_sigma_m; - znew_m = zold_m + zDir*vForwardAbs_ms/vTotAbs_ms * distance_m; - } - return znew_m; -} - - - #endif /* drift_base_h */ diff --git a/src/karl/eT2_elastic.cpp b/src/karl/eT2_elastic.cpp new file mode 100644 index 0000000..7748c1c --- /dev/null +++ b/src/karl/eT2_elastic.cpp @@ -0,0 +1,48 @@ +#include "eT2_elastic.h" +#include "katrin_fields.hpp" + +eT2_Elastic::eT2_Elastic( + Population_Base *T2Population, + UniRNG *rngUni, + DCS_Base *dcs_gen) + : e_thermal_Precomputed_Interaction_Base(T2Population, rngUni, me_eV), + tcs_data(scale_start, scale_end, 1e3, get_data_path() + "eT2_ela_TCS.dat"), + kinematics(me_eV, 2*mT_eV) +{ + this->dcs_gen = dcs_gen; + calc_values(); // need to call here, because, constructor can't call pure virtual function +} + +double eT2_Elastic::get_macro_sigma_m(const Particle &interPart) +{ + return e_thermal_Precomputed_Interaction_Base::get_macro_sigma_m(interPart); +} + +double eT2_Elastic::get_microSigma_m2(const double &E_eV) +{ + return tcs_data.get_value(E_eV); +} + +InteractionOut eT2_Elastic::do_Interaction (Particle *interPart) { + // Here theta and phi are COM-Angles.... prob not correct. For m1 << m2 COM - Angle ~ Lab Angle + const vec3 v1_ms = interPart->get_v_ms(); + const vec3 loc_m = interPart->get_x_m(); + const vec3 v2_ms = Population->roll_v_ms(loc_m); + const vec3 vLab_ms = v1_ms - v2_ms; // P2 fixed + const double T_eV = calc_E_eV_from_v_ms(vLab_ms, me_eV); + const double theta_lab = dcs_gen->get_theta(T_eV); + const double phi_lab = rngUni->random() * 2 * pi; + const vec3 v_new = kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab); + interPart->set_v_ms(v_new); + + const double v_perp = std::sqrt(v_new(0)*v_new(0) + v_new(1)*v_new(1)); + + const double rG_m = v_perp*interPart->get_m_eV()/(Katrin_Fields::getMagField_T(loc_m)(2)*c_ms*c_ms); + const double gyro_centrum_move_m = 2*rG_m * std::sin(theta_lab); + const double x_new = loc_m(0) + std::sin(phi_lab)*gyro_centrum_move_m; + const double y_new = loc_m(1) + std::cos(phi_lab)*gyro_centrum_move_m; + interPart->set_x_m(vec3(x_new, y_new, loc_m(2))); + + return InteractionOut(); +} + diff --git a/src/karl/eT2_elastic.h b/src/karl/eT2_elastic.h index ec59573..b7613d8 100644 --- a/src/karl/eT2_elastic.h +++ b/src/karl/eT2_elastic.h @@ -25,29 +25,10 @@ class eT2_Elastic : public e_thermal_Precomputed_Interaction_Base { Elastic_Kinematic_Base kinematics; public: - eT2_Elastic(Population_Base *T2Population, UniRNG *rngUni, DCS_Base *dcs_gen) : e_thermal_Precomputed_Interaction_Base(T2Population, rngUni, me_eV), - tcs_data(scale_start, scale_end, 1e3, get_data_path() + "eT2_ela_TCS.dat"), - kinematics(me_eV, 2*mT_eV) { - this->dcs_gen = dcs_gen; - calc_values(); // need to call here, because, constructor can't call pure virtual function - } - double get_macro_sigma_m(const Particle &interPart) { - return e_thermal_Precomputed_Interaction_Base::get_macro_sigma_m(interPart); - } - double get_microSigma_m2(const double &E_eV) {return tcs_data.get_value(E_eV);} + eT2_Elastic(Population_Base *T2Population, UniRNG *rngUni, DCS_Base *dcs_gen); + double get_macro_sigma_m(const Particle &interPart); + double get_microSigma_m2(const double &E_eV); InteractionOut do_Interaction (Particle *interPart); }; -inline InteractionOut eT2_Elastic::do_Interaction (Particle *interPart) { - // Here theta and phi are COM-Angles.... prob not correct. For m1 << m2 COM - Angle ~ Lab Angle - vec3 v1_ms = interPart->get_v_ms(); - vec3 v2_ms = Population->roll_v_ms(interPart->get_x_m()); - vec3 vLab_ms = v1_ms - v2_ms; // P2 fixed - double T_eV = calc_E_eV_from_v_ms(vLab_ms, me_eV); - double theta_lab = dcs_gen->get_theta(T_eV); - double phi_lab = rngUni->random() * 2 * pi; - interPart->set_v_ms(kinematics.get_v1_new(v1_ms, v2_ms, theta_lab, phi_lab)); - return InteractionOut(); -} - #endif /* eT2_elastic_h */ diff --git a/src/karl/e_thermal_base.h b/src/karl/e_thermal_base.h index da6fad0..7f4fd17 100644 --- a/src/karl/e_thermal_base.h +++ b/src/karl/e_thermal_base.h @@ -60,7 +60,7 @@ inline double e_thermal_Interaction_Base::calc_microSigma_m2(const double &E_eV) double E_eV = m1_eV/2 * (pow(v1_ms,2) + pow(v2_ms,2) - 2*v1_ms*v2_ms*cos(theta)) * pow(c_ms, -2); return Population->get_v_pdf(v2_ms)*get_microSigma_m2(E_eV)/pi; }; - return double_simpson_integrate(integrand, 0., 3*v_therm, 0., pi, INT_N, INT_N); // 3*v_therm equals 99% of the integral + return double_simpson_integrate(integrand, 0., 3*v_therm, pi/8., 7.*pi/8., INT_N, INT_N); // 3*v_therm equals 99% of the integral } } diff --git a/src/karl/electricField.cpp b/src/karl/electricField.cpp index 484cc6b..389c173 100644 --- a/src/karl/electricField.cpp +++ b/src/karl/electricField.cpp @@ -31,4 +31,14 @@ blitz::TinyVector ElectricField::value( return blitz::TinyVector(0., 0., 0.); } +} + +double ElectricField::stepSize(int cyl_axis) const +{ + return dx_(cyl_axis); +} + +blitz::TinyVector ElectricField::stepSize() const +{ + return dx_; } \ No newline at end of file diff --git a/src/karl/electricField.h b/src/karl/electricField.h index 6305e72..94a1a13 100644 --- a/src/karl/electricField.h +++ b/src/karl/electricField.h @@ -17,6 +17,9 @@ class ElectricField { blitz::TinyVector value(const blitz::TinyVector& bin) const; + double stepSize(int cyl_axis) const; + blitz::TinyVector stepSize() const; + private: // todo: make sure we use fast axis on z to reduce acess time const blitz::Array Er_; diff --git a/src/karl/electricFieldFactory.cpp b/src/karl/electricFieldFactory.cpp index a0f845b..9a90da0 100644 --- a/src/karl/electricFieldFactory.cpp +++ b/src/karl/electricFieldFactory.cpp @@ -1,4 +1,4 @@ -#include "elecrticFieldFactory.h" +#include "electricFieldFactory.h" #include "highfive/H5File.hpp" #include "highfive/H5DataSet.hpp" diff --git a/src/karl/elecrticFieldFactory.h b/src/karl/electricFieldFactory.h similarity index 100% rename from src/karl/elecrticFieldFactory.h rename to src/karl/electricFieldFactory.h diff --git a/src/karl/electric_field_test.cpp b/src/karl/electric_field_test.cpp index 9631afc..4bddbf8 100644 --- a/src/karl/electric_field_test.cpp +++ b/src/karl/electric_field_test.cpp @@ -1,16 +1,16 @@ #include "catch.hpp" #include "electricField.h" -#include "elecrticFieldFactory.h" +#include "electricFieldFactory.h" #include "CoordinateConversion.h" #include #include #include -#include "HighFive/include/highfive/H5File.hpp" -#include "HighFive/include/highfive/H5DataSet.hpp" -#include "HighFive/include/highfive/H5DataSpace.hpp" +#include "highfive/H5File.hpp" +#include "highfive/H5DataSet.hpp" +#include "highfive/H5DataSpace.hpp" TEST_CASE("ElectricField", "[ElectricField]"){ const blitz::TinyVector cyl_origin(0., 0., 1.); diff --git a/src/karl/electron_E_drift.cpp b/src/karl/electron_E_drift.cpp new file mode 100644 index 0000000..144f3cb --- /dev/null +++ b/src/karl/electron_E_drift.cpp @@ -0,0 +1,27 @@ +#include "electron_E_drift.h" + + +void E_Mover_E_Drift::do_E_calculus(Particle *movePart, const vec3 &oldLoc_m, const double ¯o_sigma_m) { + if (macro_sigma_m <= 0) { + return; + } + double t_s = 1/macro_sigma_m/calc_vec3_abs(movePart->get_v_ms()); + vec3 newLoc_m = movePart->get_x_m(); + vec3 E_Vm = 0.5 * (Katrin_Fields::getElField_Vm(oldLoc_m) + Katrin_Fields::getElField_Vm(newLoc_m)); + double B_T = calc_vec3_abs( 0.5 * (Katrin_Fields::getMagField_T(oldLoc_m) + Katrin_Fields::getMagField_T(newLoc_m)) ); + double E_rad_Vm = calc_r_m(E_Vm); + + double v_rad_ms = E_rad_Vm/B_T; + vec3 loc_offset_m = E_Vm; + if((loc_offset_m(0) == 0.) && (loc_offset_m(1) == 0.)){ + loc_offset_m = 0.; + } else{ + loc_offset_m(2) = 0.; + loc_offset_m = loc_offset_m/calc_vec3_abs(loc_offset_m) * v_rad_ms * t_s; + } + movePart->set_x_m(newLoc_m + loc_offset_m); + + vec3 v_boost_ms = vec3(0,0, movePart->get_Z()*e_C/movePart->get_m_eV()*E_Vm[2] * t_s/c_ms/c_ms); + movePart->set_v_ms(movePart->get_v_ms() + v_boost_ms); +} + diff --git a/src/karl/electron_E_drift.h b/src/karl/electron_E_drift.h index fe0b48c..8ffc0ec 100644 --- a/src/karl/electron_E_drift.h +++ b/src/karl/electron_E_drift.h @@ -15,34 +15,13 @@ class E_Mover_E_Drift : public E_Mover_Drift { public: - E_Mover_E_Drift(Particle_Logger_Base *Logger, Population_Base *Population) : E_Mover_Drift(Logger, Population) {}; + E_Mover_E_Drift( + Particle_Logger_Base *Logger, + Population_Base *Population) + : E_Mover_Drift(Logger, Population) + {}; protected: void do_E_calculus(Particle *movePart, const vec3 &oldLoc_m, const double ¯o_sigma_m); }; -inline void E_Mover_E_Drift::do_E_calculus(Particle *movePart, const vec3 &oldLoc_m, const double ¯o_sigma_m) { - if (macro_sigma_m <= 0) { - return; - } - double t_s = 1/macro_sigma_m/calc_vec3_abs(movePart->get_v_ms()); - vec3 newLoc_m = movePart->get_x_m(); - vec3 E_Vm = 0.5 * (Katrin_Fields::getElField_Vm(oldLoc_m) + Katrin_Fields::getElField_Vm(newLoc_m)); - - double B_T = calc_vec3_abs( 0.5 * (Katrin_Fields::getMagField_T(oldLoc_m) + Katrin_Fields::getMagField_T(newLoc_m)) ); - double E_rad_Vm = calc_r_m(E_Vm); - - double v_rad_ms = E_rad_Vm/B_T; - vec3 loc_offset_m = E_Vm; - if((loc_offset_m(0) == 0.) && (loc_offset_m(1) == 0.)){ - loc_offset_m = 0.; - } else{ - loc_offset_m(2) = 0.; - loc_offset_m = loc_offset_m/calc_vec3_abs(loc_offset_m) * v_rad_ms * t_s; - } - movePart->set_x_m(newLoc_m + loc_offset_m); - - vec3 v_boost_ms = vec3(0,0, movePart->get_Z()*e_C/movePart->get_m_eV()*E_Vm[2] * t_s/c_ms/c_ms); - movePart->set_v_ms(movePart->get_v_ms() + v_boost_ms); -} - #endif /* electron_E_drift_h */ diff --git a/src/karl/electron_boris.cpp b/src/karl/electron_boris.cpp new file mode 100644 index 0000000..8b04ccf --- /dev/null +++ b/src/karl/electron_boris.cpp @@ -0,0 +1,119 @@ +#include "electron_boris.h" + + +E_Mover_Boris::E_Mover_Boris( + double dt_s, + Particle_Logger_Base *Logger, + Population_Base *Population) + : Mover_Base(electron, Logger, Population) +{ + this->dt_s = dt_s; +}; + +E_Mover_Boris::E_Mover_Boris( + Particle_Logger_Base *Logger, + Population_Base *Population, + double B_max): + Mover_Base(electron, Logger, Population) +{ + if(B_max == 0.){ + dt_s = 1.; + } else{ + dt_s = Population->get_m_eV()/(B_max*c_ms*c_ms); + } +}; + +void E_Mover_Boris::move(Particle *movePart, const double ¯o_sigma_m) { + // Prepare detection for change of z direction for logging + double oldzDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; + vec3 oldLoc_m = movePart->get_x_m(); + + if (macro_sigma_m == 0) { // If infinite movement distance let electron leave at only exit... Prob extremly faulty, but also impossible. + movePart->set_x_m(z_RW_m); + Logger->log(*movePart,oldLoc_m); + return; + } + + double distance_m = 1/macro_sigma_m; + + double traveledDistance_m = 0; + vec3 loc_m, E_Vm ,B_T; + while (traveledDistance_m < distance_m) { + + loc_m = movePart->get_x_m(); + E_Vm = Katrin_Fields::getElField_Vm(loc_m); + B_T = Katrin_Fields::getMagField_T(loc_m); + + traveledDistance_m += doBoris_singleStep_m(movePart, E_Vm, B_T); + if (doBoris_WallInteraction(movePart) == true) { + Logger->log(*movePart, oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + return; + } + doBoris_LogzDirChange(movePart, &oldzDir, &oldLoc_m); // Log if z direction changes, and adapt quantities + } + Logger->log(*movePart,oldLoc_m); + Population->increase_density(*movePart, oldLoc_m); + return; +} + +double E_Mover_Boris::doBoris_singleStep_m(Particle *movePart, const vec3 &E_Vm , const vec3 &B_T) { + double distance_m; + vec3 x_m = movePart->get_x_m(); + vec3 v_ms = movePart->get_v_ms(); + x_m += dt_s/2 * v_ms; + distance_m = dt_s/2 * calc_vec3_abs(v_ms); + doBoris_speedChange(movePart, E_Vm , B_T); + x_m += dt_s/2 * v_ms; + distance_m += dt_s/2 * calc_vec3_abs(v_ms); + movePart->set_x_m(x_m); + return distance_m; +} + +void E_Mover_Boris::doBoris_speedChange(Particle *movePart, const vec3 &E_Vm, const vec3 &B_T) { + double q_C = movePart->get_Z() * e_C; + double m_kg = movePart->get_m_eV() * e_C/c_ms/c_ms; + vec3 v_ms = movePart->get_v_ms(); + + vec3 t = q_C*dt_s/(2*m_kg) * B_T; + vec3 s = (2*t)/(1+dot(t,t)); + vec3 vMinus_ms = v_ms + (q_C*E_Vm*dt_s)/(2*m_kg); + vec3 vPrime_ms = vMinus_ms + cross(vMinus_ms,t); + vec3 vPlus_ms = vMinus_ms + cross(vPrime_ms,s); + v_ms = vPlus_ms + q_C/m_kg*E_Vm*0.5*dt_s; + movePart->set_v_ms(v_ms); +} + +bool E_Mover_Boris::doBoris_WallInteraction(Particle *movePart) { + vec3 loc_m = movePart->get_x_m(); + double r_m = movePart->get_r_m(); + if (loc_m[2]<=z_RW_m) { // Rear Wall Termination + vec3 newLoc_m = movePart->get_x_m(); + newLoc_m[2] = 0; + movePart->set_x_m(newLoc_m); + return true; + } + if (r_m>=r_WGTS_m) { // WGTS Wall Termination + vec3 newLoc_m = movePart->get_x_m(); + double z_m = newLoc_m[2]; + newLoc_m[2] = 0; + newLoc_m = (r_WGTS_m * 1.01)/calc_vec3_abs(newLoc_m) * newLoc_m; //1.01 to move Particle slightly out of WGTS + newLoc_m[2] = z_m; + return true; + } + if (loc_m[2]>=z_WGTS_end_m) { // Spectrometer Reflection + movePart->set_v_ms( -1*(movePart->get_v_ms()) ); + } + return false; +} + +void E_Mover_Boris::doBoris_LogzDirChange(Particle *movePart, double *oldzDir, vec3 *oldLoc_m) { + double zDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; + if (*oldzDir != zDir) { + Logger->log(*movePart, *oldLoc_m); + Population->increase_density(*movePart, *oldLoc_m); + *oldzDir = zDir; + *oldLoc_m = movePart->get_x_m(); + } + return; +} diff --git a/src/karl/electron_boris.h b/src/karl/electron_boris.h index 58019ab..5ae99bd 100644 --- a/src/karl/electron_boris.h +++ b/src/karl/electron_boris.h @@ -1,24 +1,22 @@ -// -// electron_boris.h -// mc_electron -// -// Created by Christian Reiling on 16.05.19. -// Copyright © 2019 Christian Reiling. All rights reserved. -// - #ifndef electron_boris_h #define electron_boris_h #include "mover_base.h" - +#include "constants.h" class E_Mover_Boris : public Mover_Base { double dt_s; public: - E_Mover_Boris(double dt_s, Particle_Logger_Base *Logger, Population_Base *Population) : Mover_Base(electron, Logger, Population) { - this->dt_s = dt_s; - }; + E_Mover_Boris( + double dt_s, + Particle_Logger_Base *Logger, + Population_Base *Population); + E_Mover_Boris( + Particle_Logger_Base *Logger, + Population_Base *Population, + double B_max); + void move(Particle *movePart, const double ¯o_sigma_m); private: @@ -28,99 +26,7 @@ private: void doBoris_LogzDirChange(Particle *movePart, double *oldzDir, vec3 *oldLoc_m); }; -void E_Mover_Boris::move(Particle *movePart, const double ¯o_sigma_m) { - // Prepare detection for change of z direction for logging - double oldzDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; - vec3 oldLoc_m = movePart->get_x_m(); - - if (macro_sigma_m == 0) { // If infinite movement distance let electron leave at only exit... Prob extremly faulty, but also impossible. - movePart->set_x_m(z_RW_m); - Logger->log(*movePart,oldLoc_m); - return; - } - - double distance_m = 1/macro_sigma_m; - - double traveledDistance_m = 0; - vec3 loc_m, E_Vm ,B_T; - while (traveledDistance_m < distance_m) { - loc_m = movePart->get_x_m(); - E_Vm = Katrin_Fields::getElField_Vm(loc_m); - B_T = Katrin_Fields::getMagField_T(loc_m); - - traveledDistance_m += doBoris_singleStep_m(movePart, E_Vm, B_T); - if (doBoris_WallInteraction(movePart) == true) { - Logger->log(*movePart, oldLoc_m); - Population->increase_density(*movePart, oldLoc_m); - return; - } - doBoris_LogzDirChange(movePart, &oldzDir, &oldLoc_m); // Log if z direction changes, and adapt quantities - } - Logger->log(*movePart,oldLoc_m); - Population->increase_density(*movePart, oldLoc_m); - return; -} -double E_Mover_Boris::doBoris_singleStep_m(Particle *movePart, const vec3 &E_Vm , const vec3 &B_T) { - double distance_m; - vec3 x_m = movePart->get_x_m(); - vec3 v_ms = movePart->get_v_ms(); - x_m += dt_s/2 * v_ms; - distance_m = dt_s/2 * calc_vec3_abs(v_ms); - doBoris_speedChange(movePart, E_Vm , B_T); - x_m += dt_s/2 * v_ms; - distance_m += dt_s/2 * calc_vec3_abs(v_ms); - movePart->set_x_m(x_m); - return distance_m; -} - -void E_Mover_Boris::doBoris_speedChange(Particle *movePart, const vec3 &E_Vm, const vec3 &B_T) { - double q_C = movePart->get_Z() * e_C; - double m_kg = movePart->get_m_eV() * e_C/c_ms/c_ms; - vec3 v_ms = movePart->get_v_ms(); - - vec3 t = q_C*dt_s/(2*m_kg) * B_T; - vec3 s = (2*t)/(1+dot(t,t)); - vec3 vMinus_ms = v_ms + (q_C*E_Vm*dt_s)/(2*m_kg); - vec3 vPrime_ms = vMinus_ms + cross(vMinus_ms,t); - vec3 vPlus_ms = vMinus_ms + cross(vPrime_ms,s); - v_ms = vPlus_ms + q_C/m_kg*E_Vm*0.5*dt_s; - movePart->set_v_ms(v_ms); -} - -bool E_Mover_Boris::doBoris_WallInteraction(Particle *movePart) { - vec3 loc_m = movePart->get_x_m(); - double r_m = movePart->get_r_m(); - if (loc_m[2]<=z_RW_m) { // Rear Wall Termination - vec3 newLoc_m = movePart->get_x_m(); - newLoc_m[2] = 0; - movePart->set_x_m(newLoc_m); - return true; - } - if (r_m>=r_WGTS_m) { // WGTS Wall Termination - vec3 newLoc_m = movePart->get_x_m(); - double z_m = newLoc_m[2]; - newLoc_m[2] = 0; - newLoc_m = (r_WGTS_m * 1.01)/calc_vec3_abs(newLoc_m) * newLoc_m; //1.01 to move Particle slightly out of WGTS - newLoc_m[2] = z_m; - return true; - } - if (loc_m[2]>=z_WGTS_end_m) { // Spectrometer Reflection - movePart->set_v_ms( -1*(movePart->get_v_ms()) ); - } - return false; -} - -void E_Mover_Boris::doBoris_LogzDirChange(Particle *movePart, double *oldzDir, vec3 *oldLoc_m) { - double zDir = movePart->get_v_ms()[2] < 0 ? -1 : 1; - if (*oldzDir != zDir) { - Logger->log(*movePart, *oldLoc_m); - Population->increase_density(*movePart, *oldLoc_m); - *oldzDir = zDir; - *oldLoc_m = movePart->get_x_m(); - } - return; -} #endif /* electron_boris_h */ diff --git a/src/karl/electron_drift.h b/src/karl/electron_drift.h index 799fdf0..c17da1e 100644 --- a/src/karl/electron_drift.h +++ b/src/karl/electron_drift.h @@ -37,7 +37,7 @@ inline void E_Mover_Drift::doWallInteraction(Particle *movePart, vec3 *oldLoc_m, movePart->set_v_ms( -1*(movePart->get_v_ms()) ); } if (*znew_m <= z_RW_m) { - *znew_m = z_RW_m; + *znew_m = z_RW_m-0.0001; } } diff --git a/src/karl/interaction_builder.cpp b/src/karl/interaction_builder.cpp index 77724cf..ab0ebd7 100644 --- a/src/karl/interaction_builder.cpp +++ b/src/karl/interaction_builder.cpp @@ -55,7 +55,7 @@ Interaction_Manager Interaction_Builder::build(Population_Manager *Populations, Interactions.add(build_tritiumI(Populations, rngUni)); Interactions.add(build_tritium2I(Populations, rngUni)); Interactions.add(build_tritium3I(Populations, rngUni)); - Interactions.add(build_tritium5I(Populations, rngUni)); + //Interactions.add(build_tritium5I(Populations, rngUni)); return Interactions; } Interaction_Channel_Base* Interaction_Builder::build_electron(Population_Manager *Populations, UniRNG *rngUni) { @@ -63,7 +63,7 @@ Interaction_Channel_Base* Interaction_Builder::build_electron(Population_Manager Population_Base *T2Population = Populations->find(tritium2); Population_Base *T2IPopulation = Populations->find(tritium2I); Population_Base *T3IPopulation = Populations->find(tritium3I); - Population_Base *T5IPopulation = Populations->find(tritium5I); + //Population_Base *T5IPopulation = Populations->find(tritium5I); DCS_Base *exc_dcs = new ZeroPi_DCS(rngUni); if (load_parameter("eT2_ELA") == 1) { @@ -119,7 +119,7 @@ Interaction_Channel_Base* Interaction_Builder::build_electron(Population_Manager if (load_parameter("e_REC") == 1) { eInteraction->add(new eT2I_Recombination(T2IPopulation, rngUni)); eInteraction->add(new eT3I_Recombination(T3IPopulation, rngUni)); - eInteraction->add(new eT5I_Recombination(T5IPopulation, rngUni)); + //eInteraction->add(new eT5I_Recombination(T5IPopulation, rngUni)); } else if (load_parameter("e_REC") != 0) { throw MyException ("e_REC invalid."); } @@ -197,8 +197,8 @@ Interaction_Channel_Base* Interaction_Builder::build_tritium3I(Population_Manage Population_Base *T2Population = Populations->find(tritium2); Population_Base *ePopulation = Populations->find(electron); T3I_Interaction->add(new T3IT2_Elastic(T2Population, rngUni)); - T3I_Interaction->add(new T3IT2_RadAsc(T2Population, rngUni)); - T3I_Interaction->add(new T3IT2_TerAsc(T2Population, rngUni)); + //T3I_Interaction->add(new T3IT2_RadAsc(T2Population, rngUni)); + //T3I_Interaction->add(new T3IT2_TerAsc(T2Population, rngUni)); if (load_parameter("e_REC") == 1) { T3I_Interaction->add(new T3Ie_Recombination(ePopulation, rngUni)); @@ -209,7 +209,7 @@ Interaction_Channel_Base* Interaction_Builder::build_tritium3I(Population_Manage //T3I_Interaction->add(new T3Ie_DissExc(ePopulation, rngUni)); return T3I_Interaction ; } - +/* Interaction_Channel_Base* Interaction_Builder::build_tritium5I(Population_Manager *Populations, UniRNG *rngUni) { Interaction_Channel_Base *T5I_Interaction = new Interaction_Channel_Base(tritium5I, rngUni); Population_Base *T2Population = Populations->find(tritium2); @@ -224,3 +224,5 @@ Interaction_Channel_Base* Interaction_Builder::build_tritium5I(Population_Manage return T5I_Interaction; } + +*/ \ No newline at end of file diff --git a/src/karl/interaction_builder.hpp b/src/karl/interaction_builder.hpp index ddba86e..3f74d6a 100644 --- a/src/karl/interaction_builder.hpp +++ b/src/karl/interaction_builder.hpp @@ -32,7 +32,7 @@ private: static Interaction_Channel_Base* build_tritiumI(Population_Manager *Populations, UniRNG *rngUni); static Interaction_Channel_Base* build_tritium2I(Population_Manager *Populations, UniRNG *rngUni); static Interaction_Channel_Base* build_tritium3I(Population_Manager *Populations, UniRNG *rngUni); - static Interaction_Channel_Base* build_tritium5I(Population_Manager *Populations, UniRNG *rngUni); + //static Interaction_Channel_Base* build_tritium5I(Population_Manager *Populations, UniRNG *rngUni); }; diff --git a/src/karl/katrin_fields.cpp b/src/karl/katrin_fields.cpp index b916860..e96228f 100644 --- a/src/karl/katrin_fields.cpp +++ b/src/karl/katrin_fields.cpp @@ -2,7 +2,7 @@ #include "read_system.h" #include "CoordinateConversion.h" -#include "elecrticFieldFactory.h" +#include "electricFieldFactory.h" double Katrin_Fields::wgtsMagField_T = 0.; std::shared_ptr Katrin_Fields::E_field_ptr = nullptr; @@ -23,6 +23,7 @@ blitz::TinyVector Katrin_Fields::getElField_Vm( CoordinateConversion::cylinderCoordinate(cartesian_m); const blitz::TinyVector E_cyl = E_field_ptr->value(cylinder); + const blitz::TinyVector E_cart = CoordinateConversion::cartesianBase( E_cyl, diff --git a/src/karl/logger_builder.cpp b/src/karl/logger_builder.cpp index b02b489..f0cf756 100644 --- a/src/karl/logger_builder.cpp +++ b/src/karl/logger_builder.cpp @@ -13,8 +13,10 @@ #include "off_particle_logger.h" #include "population_logger_base.h" +#include "CurrentLogger.h" const int Particle_Logger_Builder::numberZBins = load_parameter("LOG_BARS"); +const int Particle_Logger_Builder::numberRBins = load_parameter("LOG_BARS_R"); Particle_Logger_Manager Particle_Logger_Builder::build(H5_File *h5f) { Particle_Logger_Manager ParticleLogger; @@ -25,18 +27,69 @@ Particle_Logger_Manager Particle_Logger_Builder::build(H5_File *h5f) { ParticleLogger.add(new Off_Particle_Logger(tritiumI)); ParticleLogger.add(new Off_Particle_Logger(tritium2I)); ParticleLogger.add(new Off_Particle_Logger(tritium3I)); - ParticleLogger.add(new Off_Particle_Logger(tritium5I)); + //ParticleLogger.add(new Off_Particle_Logger(tritium5I)); } else if(numberZBins == -1){ ParticleLogger.add(new SF_Particle_Logger(electron, h5f)); ParticleLogger.add(new SF_Particle_Logger(tritiumI, h5f)); ParticleLogger.add(new SF_Particle_Logger(tritium2I, h5f)); ParticleLogger.add(new SF_Particle_Logger(tritium3I, h5f)); - ParticleLogger.add(new SF_Particle_Logger(tritium5I, h5f)); + //ParticleLogger.add(new SF_Particle_Logger(tritium5I, h5f)); } else { build_MultiZ(&ParticleLogger, h5f); } return ParticleLogger; } + +Particle_Logger_Manager Particle_Logger_Builder::build(std::string filename) +{ + Particle_Logger_Manager ParticleLogger; + ParticleLogger.add(new Off_Particle_Logger(tritium)); + + build_histogram(&ParticleLogger, filename); + + return ParticleLogger; +} + +void Particle_Logger_Builder::build_histogram( + Particle_Logger_Manager *ParticleLogger, + std::string filename) +{ + const int energy_decade_min = load_parameter("LOG_BARS_ENERGY_DECADE_MIN"); + const int energy_decade_max = load_parameter("LOG_BARS_ENERGY_DECADE_MAX"); + + //std::cout << "Logging: \n"; + //std::cout << "numberRBins: " << numberRBins << std::endl; + //std::cout << "LOG_BARS: " << numberZBins << std::endl; + + double zmin = z_RW_m; + + ParticleLogger->add(new CurrentLogger( + electron, + numberZBins, zmin, z_WGTS_end_m, + numberRBins, r_WGTS_m, + energy_decade_min, energy_decade_max, + filename)); + ParticleLogger->add(new CurrentLogger( + tritiumI, + numberZBins, zmin, z_WGTS_end_m, + numberRBins, r_WGTS_m, + energy_decade_min, energy_decade_max, + filename)); + ParticleLogger->add(new CurrentLogger( + tritium2I, + numberZBins, zmin, z_WGTS_end_m, + numberRBins, r_WGTS_m, + energy_decade_min, energy_decade_max, + filename)); + ParticleLogger->add(new CurrentLogger( + tritium3I, + numberZBins, zmin, z_WGTS_end_m, + numberRBins, r_WGTS_m, + energy_decade_min, energy_decade_max, + filename)); +} + + void Particle_Logger_Builder::build_MultiZ(Particle_Logger_Manager *ParticleLogger, H5_File *h5f) { double *zValues = new double[numberZBins]; double start_m = z_RW_m; @@ -48,11 +101,12 @@ void Particle_Logger_Builder::build_MultiZ(Particle_Logger_Manager *ParticleLogg z_m = start_m + stepLength_m*i; zValues[i] = z_m; } + ParticleLogger->add(new MultiZ_Particle_Logger(electron, h5f, numberZBins, zValues)); ParticleLogger->add(new MultiZ_Particle_Logger(tritiumI, h5f, numberZBins, zValues)); ParticleLogger->add(new MultiZ_Particle_Logger(tritium2I, h5f, numberZBins, zValues)); ParticleLogger->add(new MultiZ_Particle_Logger(tritium3I, h5f, numberZBins, zValues)); - ParticleLogger->add(new MultiZ_Particle_Logger(tritium5I, h5f, numberZBins, zValues)); + //ParticleLogger->add(new MultiZ_Particle_Logger(tritium5I, h5f, numberZBins, zValues)); delete[] zValues; } @@ -63,6 +117,6 @@ Population_Logger_Manager Population_Logger_Builder::build(H5_File *h5f, Populat Population_Loggers.add (new Population_Logger(populations->find(tritiumI), timer, h5f)); Population_Loggers.add (new Population_Logger(populations->find(tritium2I), timer, h5f)); Population_Loggers.add (new Population_Logger(populations->find(tritium3I), timer, h5f)); - Population_Loggers.add (new Population_Logger(populations->find(tritium5I), timer, h5f)); + //Population_Loggers.add (new Population_Logger(populations->find(tritium5I), timer, h5f)); return Population_Loggers; } diff --git a/src/karl/logger_builder.hpp b/src/karl/logger_builder.hpp index 7c92f46..d9f1a9c 100644 --- a/src/karl/logger_builder.hpp +++ b/src/karl/logger_builder.hpp @@ -22,11 +22,19 @@ typedef Manager_Base Particle_Logger_Manager; class Particle_Logger_Builder { static const int numberZBins; + static const int numberRBins; public: Particle_Logger_Builder() {}; static Particle_Logger_Manager build(H5_File *h5f); - static void build_MultiZ(Particle_Logger_Manager *ParticleLogger, H5_File *h5f); + static Particle_Logger_Manager build(std::string filename); + + static void build_MultiZ( + Particle_Logger_Manager *ParticleLogger, + H5_File *h5f); + static void build_histogram( + Particle_Logger_Manager *ParticleLogger, + std::string filename); }; diff --git a/src/karl/makefile2 b/src/karl/makefile2 index 212c4ec..a85a181 100644 --- a/src/karl/makefile2 +++ b/src/karl/makefile2 @@ -15,6 +15,15 @@ OBJS := particle_looper.o \ electricFieldFactory.o \ CoordinateConversion.o \ simulation_init.o \ + Ion_Mover_Boris.o \ + electron_boris.o \ + drift_base.o \ + electron_E_drift.o \ + eT2_elastic.o \ + T3IT2_elastic.o \ + TIT2_elastic.o \ + CurrentHistogram.o \ + CurrentLogger.o \ CXXFLAGS = $(X_OFLAGS) -I.. $(X_INC) -std=c++11 @@ -47,7 +56,12 @@ ctest: $(TARGETS_TEST) OBJECTS_TEST = electric_field_test.o \ electricField.o \ electricFieldFactory.o \ - CoordinateConversion.o + CoordinateConversion.o \ + CurrentHistogram.o \ + current_histogram_test.o\ + CurrentLogger.o\ + current_logger_test.o\ + particle.o\ catch: test_main.o $(OBJECTS_TEST) $(MPICXX) -o $@ $^ $(LDFLAGS) $(LOADLIBES) diff --git a/src/karl/mover_builder.cpp b/src/karl/mover_builder.cpp index 76eb6ea..9868b85 100644 --- a/src/karl/mover_builder.cpp +++ b/src/karl/mover_builder.cpp @@ -16,6 +16,7 @@ #include "postive_drift.h" #include "postive_E_drift.h" #include "neutral_mover.h" +#include "Ion_Mover_Boris.h" const int Mover_Builder::propagationMethod = load_parameter("PROPAGATION"); @@ -28,7 +29,7 @@ Mover_Manager Mover_Builder::build(Particle_Logger_Manager *Loggers, Population_ Movers.add(build_tritiumI(Loggers, Populations)); Movers.add(build_tritium2I(Loggers, Populations)); Movers.add(build_tritium3I(Loggers, Populations)); - Movers.add(build_tritium5I(Loggers, Populations)); + //Movers.add(build_tritium5I(Loggers, Populations)); return Movers; } @@ -48,7 +49,8 @@ Mover_Base *Mover_Builder::build_electron(Particle_Logger_Manager *Loggers, Popu } else { - electron_Mover = new E_Mover_Boris(dt_s, Logger, Popultation); + //electron_Mover = new E_Mover_Boris(dt_s, Logger, Popultation); + electron_Mover = new E_Mover_Boris(Logger, Popultation, load_parameter("BFIELD")); } return electron_Mover; } @@ -62,43 +64,53 @@ Mover_Base *Mover_Builder::build_tritium(Particle_Logger_Manager *Loggers, Popul Mover_Base *Mover_Builder::build_tritiumI(Particle_Logger_Manager *Loggers, Population_Manager *Populations) { Particle_Logger_Base *Logger = Loggers->find(tritiumI); Population_Base *Popultation = Populations->find(tritiumI); - if (load_parameter("E_FIELD") == 0) { - return new Positive_Mover_Drift(tritiumI, Logger, Popultation); - } else if (load_parameter("E_FIELD") == 1) { - return new Positive_Mover_E_Drift(tritiumI, Logger, Popultation); + if (propagationMethod == 0) { + if (load_parameter("E_FIELD") == 0) { + return new Positive_Mover_Drift(tritiumI, Logger, Popultation); + } else if (load_parameter("E_FIELD") == 1) { + return new Positive_Mover_E_Drift(tritiumI, Logger, Popultation); + } else { + throw MyException("E_FIELD invalid"); + } } else { - throw MyException("E_FIELD invalid"); + return new Ion_Mover_Boris(tritiumI, Logger, Popultation, load_parameter("BFIELD")); } } Mover_Base *Mover_Builder::build_tritium2I(Particle_Logger_Manager *Loggers, Population_Manager *Populations) { Particle_Logger_Base *Logger = Loggers->find(tritium2I); Population_Base *Popultation = Populations->find(tritium2I); - if (load_parameter("E_FIELD") == 0) { - return new Positive_Mover_Drift(tritium2I, Logger, Popultation); - } else if (load_parameter("E_FIELD") == 1) { - return new Positive_Mover_E_Drift(tritium2I, Logger, Popultation); + if (propagationMethod == 0) { + if (load_parameter("E_FIELD") == 0) { + return new Positive_Mover_Drift(tritium2I, Logger, Popultation); + } else if (load_parameter("E_FIELD") == 1) { + return new Positive_Mover_E_Drift(tritium2I, Logger, Popultation); + } else { + throw MyException("E_FIELD invalid"); + } } else { - throw MyException("E_FIELD invalid"); + return new Ion_Mover_Boris(tritium2I, Logger, Popultation, load_parameter("BFIELD")); } - } Mover_Base *Mover_Builder::build_tritium3I(Particle_Logger_Manager *Loggers, Population_Manager *Populations) { Particle_Logger_Base *Logger = Loggers->find(tritium3I); Population_Base *Popultation = Populations->find(tritium3I); - if (load_parameter("E_FIELD") == 0) { - return new Positive_Mover_Drift(tritium3I, Logger, Popultation); - } else if (load_parameter("E_FIELD") == 1) { - return new Positive_Mover_E_Drift(tritium3I, Logger, Popultation); + if (propagationMethod == 0) { + if (load_parameter("E_FIELD") == 0) { + return new Positive_Mover_Drift(tritium3I, Logger, Popultation); + } else if (load_parameter("E_FIELD") == 1) { + return new Positive_Mover_E_Drift(tritium3I, Logger, Popultation); + } else { + throw MyException("E_FIELD invalid"); + } } else { - throw MyException("E_FIELD invalid"); + return new Ion_Mover_Boris(tritium3I, Logger, Popultation, load_parameter("BFIELD")); } - } - +/* Mover_Base *Mover_Builder::build_tritium5I(Particle_Logger_Manager *Loggers, Population_Manager *Populations) { Particle_Logger_Base *Logger = Loggers->find(tritium5I); Population_Base *Popultation = Populations->find(tritium5I); @@ -112,3 +124,4 @@ Mover_Base *Mover_Builder::build_tritium5I(Particle_Logger_Manager *Loggers, Pop } +*/ \ No newline at end of file diff --git a/src/karl/mover_builder.hpp b/src/karl/mover_builder.hpp index f91f1bb..51fe0ce 100644 --- a/src/karl/mover_builder.hpp +++ b/src/karl/mover_builder.hpp @@ -30,7 +30,7 @@ private: static Mover_Base *build_tritiumI(Particle_Logger_Manager *Loggers, Population_Manager *Populations); static Mover_Base *build_tritium2I(Particle_Logger_Manager *Loggers, Population_Manager *Populations); static Mover_Base *build_tritium3I(Particle_Logger_Manager *Loggers, Population_Manager *Populations); - static Mover_Base *build_tritium5I(Particle_Logger_Manager *Loggers, Population_Manager *Populations); + //static Mover_Base *build_tritium5I(Particle_Logger_Manager *Loggers, Population_Manager *Populations); }; diff --git a/src/karl/particle.cpp b/src/karl/particle.cpp index 63c4106..3431746 100644 --- a/src/karl/particle.cpp +++ b/src/karl/particle.cpp @@ -51,7 +51,7 @@ std::vector get_all_species_vector() { all.push_back(tritium2I); all.push_back(tritium2); all.push_back(tritium3I); - all.push_back(tritium5I); + //all.push_back(tritium5I); return all; }; diff --git a/src/karl/particle_logger_base.h b/src/karl/particle_logger_base.h index 1c2fbc6..e54a8d1 100644 --- a/src/karl/particle_logger_base.h +++ b/src/karl/particle_logger_base.h @@ -22,6 +22,7 @@ public: void set_logging(const bool &logging) { this->logging = logging; } + virtual void output(){}; }; diff --git a/src/karl/particle_looper.cpp b/src/karl/particle_looper.cpp index a7c2c1b..daf5e9f 100644 --- a/src/karl/particle_looper.cpp +++ b/src/karl/particle_looper.cpp @@ -1,19 +1,24 @@ -// -// particle_looper.cpp -// mc_electron -// -// Created by Christian Reiling on 16.07.19. -// Copyright © 2019 Christian Reiling. All rights reserved. -// - #include "particle_looper.hpp" using namespace std; +void Particle_Looper::init( + long int seed, long int ID_offset, std::string output_path) +{ + rngUni.seed(seed); + rngNormal.seed(seed); + this->ID_offset = ID_offset; + h5f = H5_File(output_path); + output_filename_without_type_ending=output_path.erase(output_path.length()-3); + init_managers(); + //pop_load_saver.load(); +} + void Particle_Looper::init_managers() { timer = Timer(&local_decays, &global_decays); - part_loggers = Particle_Logger_Builder::build(&h5f); + //part_loggers = Particle_Logger_Builder::build(&h5f); + part_loggers = Particle_Logger_Builder::build(output_filename_without_type_ending); populations = Population_Builder::build(&timer, &rngUni, &rngNormal); injector = Injector_Builder::build(&rngUni, &rngNormal, &populations); @@ -37,6 +42,12 @@ void Particle_Looper::do_loops(int target_decays) { } process_one(&particle_queue); } + Particle_Logger_Base *log_output = part_loggers.find(species::electron); + log_output->output(); + + log_output = part_loggers.find(species::tritium3I); + log_output->output(); + pop_loggers.log(); } @@ -47,19 +58,25 @@ void Particle_Looper::process_one(std::vector *particle_queue) { Mover_Base *moverPtr = movers.find(curPart.get_species()); Interaction_Channel_Base *interactionPtr = interactions.find(curPart.get_species()); Terminator_Base *terminatorPtr = terminators.find(curPart.get_species()); - + Particle_Logger_Base *logger = part_loggers.find(curPart.get_species()); + InteractionOut IntOut; double macro_sigma_m; vec3 oldLoc_m; while (!terminatorPtr->check_terminlization(curPart)) { oldLoc_m = curPart.get_x_m(); macro_sigma_m = interactionPtr->get_macro_sigma_m(curPart); + double rnd_number = rngUni.random(); + rnd_number = (rnd_number == 0.) ? 1E-15 : rnd_number; + double rolled_macro_sigma_m = - macro_sigma_m/log(rnd_number); - moverPtr->move(&curPart, macro_sigma_m); + moverPtr->move(&curPart, rolled_macro_sigma_m); if (terminatorPtr->check_terminlization(curPart)) { break; // Don't double check terminlization, else n_double. } else { + oldLoc_m = curPart.get_x_m(); IntOut = interactionPtr->do_Interaction(&curPart); + logger->log(curPart, oldLoc_m); for (int i=0; ipush_back(IntOut.get_new_particles()[i]); particle_queue->back().set_Id(get_new_id()); @@ -71,8 +88,10 @@ void Particle_Looper::process_one(std::vector *particle_queue) { } } particle_queue->erase(particle_queue->begin() + i); + //std::cout << "Particle: " << i << " of " << particle_queue->size() << " particles\n"; } + long int Particle_Looper::get_new_id() { ID_counter++; return ID_offset + ID_counter; diff --git a/src/karl/particle_looper.hpp b/src/karl/particle_looper.hpp index 5cbbe5b..6edd441 100644 --- a/src/karl/particle_looper.hpp +++ b/src/karl/particle_looper.hpp @@ -47,17 +47,11 @@ class Particle_Looper { long int ID_counter = 0; long int local_decays = 0; long int global_decays = 0; + std::string output_filename_without_type_ending; public: Particle_Looper() {}; - void init(long int seed, long int ID_offset, std::string output_path) { - rngUni.seed(seed); - rngNormal.seed(seed); - this->ID_offset = ID_offset; - h5f = H5_File(output_path); - init_managers(); - //pop_load_saver.load(); - } + void init(long int seed, long int ID_offset, std::string output_path); ~Particle_Looper() { //pop_load_saver.save(); } diff --git a/src/karl/population_builder.cpp b/src/karl/population_builder.cpp index 551d41e..8632a3e 100644 --- a/src/karl/population_builder.cpp +++ b/src/karl/population_builder.cpp @@ -36,14 +36,14 @@ Population_Manager Population_Builder::build(Timer *timer,UniRNG *rngUni, Normal Populations.add(new Thermal_Population(tritiumI, new WGTS_Kinematics(mT_eV, wgtsTemp_K, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new Thermal_Population(tritium2I, new WGTS_Kinematics(2*mT_eV, wgtsTemp_K, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new Thermal_Population(tritium3I, new WGTS_Kinematics(3*mT_eV, wgtsTemp_K, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); - Populations.add(new Thermal_Population(tritium5I, new WGTS_Kinematics(5*mT_eV, wgtsTemp_K, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); + //Populations.add(new Thermal_Population(tritium5I, new WGTS_Kinematics(5*mT_eV, wgtsTemp_K, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new T2_Population(new WGTS_Kinematics(2*mT_eV, wgtsTemp_K, rngUni, rngNormal), rngUni, rngNormal)); } else { Populations.add(new Thermal_Population(tritium, new Lin_Kinematics(mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new Thermal_Population(tritiumI, new Lin_Kinematics(mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new Thermal_Population(tritium2I, new Lin_Kinematics(2*mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new Thermal_Population(tritium3I, new Lin_Kinematics(3*mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); - Populations.add(new Thermal_Population(tritium5I, new Lin_Kinematics(5*mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); + //Populations.add(new Thermal_Population(tritium5I, new Lin_Kinematics(5*mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), timer, rngUni, rngNormal, num_z_bins, num_r_bins, num_phi_bins)); Populations.add(new T2_Population(new Lin_Kinematics(2*mT_eV, wgtsTemp_K, v_flow, rngUni, rngNormal), rngUni, rngNormal)); } /* diff --git a/src/karl/population_container.cpp b/src/karl/population_container.cpp index 3358ebf..df2e37b 100644 --- a/src/karl/population_container.cpp +++ b/src/karl/population_container.cpp @@ -89,7 +89,7 @@ void Population_Container::increase_cum_time_s(const vec3 &loc1_m, const vec3 &l Bins bins_1 = calc_loc_bin(loc1_m); Bins bins_2 = calc_loc_bin(loc2_m); if ((!(bins_1.r == bins_2.r && bins_1.phi == bins_2.phi)) && (bins_1.z == bins_2.z)) { // Movement not in z... just ignore it for now... - cout<<"Population_Container: Movement in r-phi-direction. \n."; + //cout<<"Population_Container: Movement in r-phi-direction. \n."; } else if (bins_1.z == bins_2.z) { // Movement in same bin, most of the times! double d_m = calc_vec3_abs(loc2_m - loc1_m); double cum_time_s = d_m/v_ms; diff --git a/src/karl/postive_drift.h b/src/karl/postive_drift.h index 3c0e86e..e4de27e 100644 --- a/src/karl/postive_drift.h +++ b/src/karl/postive_drift.h @@ -24,10 +24,10 @@ protected: inline void Positive_Mover_Drift::doWallInteraction(Particle *movePart, vec3 *oldLoc_m, double *znew_m) { if (*znew_m >= z_WGTS_end_m) { - *znew_m = z_WGTS_end_m; + *znew_m = z_WGTS_end_m+0.001; } if (*znew_m <= z_RW_m) { - *znew_m = z_RW_m; + *znew_m = z_RW_m-0.001; } } diff --git a/src/karl/simulation_init.cpp b/src/karl/simulation_init.cpp index 3b78130..c6e48ac 100644 --- a/src/karl/simulation_init.cpp +++ b/src/karl/simulation_init.cpp @@ -1,7 +1,7 @@ #include "simulation.hpp" #include "katrin_fields.hpp" -#include "elecrticFieldFactory.h" +#include "electricFieldFactory.h" #include "CoordinateConversion.h" #include "pugixml.hpp" diff --git a/src/karl/terminator_builder.cpp b/src/karl/terminator_builder.cpp index e0b68d0..a84f3c7 100644 --- a/src/karl/terminator_builder.cpp +++ b/src/karl/terminator_builder.cpp @@ -25,6 +25,6 @@ Terminator_Manager Terminator_Builder::build() { Terminator.add(new PosNeu_Terminator(tritiumI, maxInteractions, cutoffEnergy_eV)); Terminator.add(new PosNeu_Terminator(tritium2I, maxInteractions, cutoffEnergy_eV)); Terminator.add(new PosNeu_Terminator(tritium3I, maxInteractions, cutoffEnergy_eV)); - Terminator.add(new PosNeu_Terminator(tritium5I, maxInteractions, cutoffEnergy_eV)); + //Terminator.add(new PosNeu_Terminator(tritium5I, maxInteractions, cutoffEnergy_eV)); return Terminator; } diff --git a/src/tools/analysis_jkellerer/currents/plot_current_vs_r.py b/src/tools/analysis_jkellerer/currents/plot_current_vs_r.py new file mode 100644 index 0000000..575b473 --- /dev/null +++ b/src/tools/analysis_jkellerer/currents/plot_current_vs_r.py @@ -0,0 +1,83 @@ +import numpy as np +import matplotlib +import matplotlib.pyplot as plt + +import functions.calculate_currents_from_karl as cc +import functions.plot_standards as pst + + +def plotCurrentRVsR(filename_current, filename_density, output_folder, z_pos): + #species_keys = ["/e-", "/T+", "/T2+", "/T3+"] + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + e_dict = {"key" : "/e-", "linestyle": '-', "label": "e"} + T3_dict = {"key" : "/T3+", "linestyle": '--', "label": "T3+"} + dicts = [e_dict, T3_dict] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + for d in dicts: + j_total_r = cc.particleCurrentR(filename_current, filename_density, d["key"]) + r_bins = cc.binBordersR(filename_current, d["key"]) + z_bins = cc.binBordersZ(filename_current, d["key"]) + + z_bin = np.abs((z_bins-z_pos)).argmin() + + plot_data = np.sum(j_total_r,2)[:,z_bin] + x_mins = r_bins[:-1] + x_maxs = r_bins[1:] + plot_bins, plot_datas = cc.makeBarPlotData(plot_data, x_mins, x_maxs) + + ax.plot(plot_bins, plot_datas, linestyle=d["linestyle"], label=d["label"]) + + ax.set_xlabel(r"Radius $r$ [m]") + ax.set_ylabel(r"Particle Current $j_r$ [$m^{-2}s^{-1}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend(loc="upper right") + + filename_output = output_folder + 'jr_vs_r.pdf' + fig.savefig(filename_output, format='pdf', bbox_inches='tight') + +def plotCurrentZVsR(filename_current, filename_density, output_folder, z_pos): + #species_keys = ["/e-", "/T+", "/T2+", "/T3+"] + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + e_dict = {"key" : "/e-", "linestyle": '-', "label": "e"} + T3_dict = {"key" : "/T3+", "linestyle": '--', "label": "T3+"} + dicts = [e_dict, T3_dict] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + for d in dicts: + j_total_z = cc.particleCurrentZ(filename_current, filename_density, d["key"]) + r_bins = cc.binBordersR(filename_current, d["key"]) + z_bins = cc.binBordersZ(filename_current, d["key"]) + + z_bin = np.abs((z_bins-z_pos)).argmin() + + plot_data = np.sum(j_total_z,2)[:,z_bin] + x_mins = r_bins[:-1] + x_maxs = r_bins[1:] + plot_bins, plot_datas = cc.makeBarPlotData(plot_data, x_mins, x_maxs) + + ax.plot(plot_bins, plot_datas, linestyle=d["linestyle"], label=d["label"]) + + ax.set_xlabel(r"Radius $r$ [m]") + ax.set_ylabel(r"Particle Current $j_z$ [$m^{-2}s^{-1}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend(loc="upper right") + + filename_output = output_folder + 'jz_vs_r.pdf' + fig.savefig(filename_output, format='pdf', bbox_inches='tight') \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/currents/plot_current_vs_z.py b/src/tools/analysis_jkellerer/currents/plot_current_vs_z.py new file mode 100644 index 0000000..dab0ef4 --- /dev/null +++ b/src/tools/analysis_jkellerer/currents/plot_current_vs_z.py @@ -0,0 +1,71 @@ +import numpy as np +import matplotlib +import matplotlib.pyplot as plt + +import functions.calculate_currents_from_karl as cc +import functions.plot_standards as pst + +def plotTubeCurrentVsZ(filename_current, filename_density, output_folder): + #species_keys = ["/e-", "/T+", "/T2+", "/T3+"] + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + e_dict = {"key" : "/e-", "linestyle": '-', "label": "e"} + T3_dict = {"key" : "/T3+", "linestyle": '--', "label": "T3+"} + dicts = [e_dict, T3_dict] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + for d in dicts: + j_total = cc.particleCurrentR(filename_current, filename_density, d["key"]) + z_bins = cc.binBordersZ(filename_current, d["key"]) + + plot_data = np.sum(j_total,2)[-1,:] + x_mins = z_bins[:-1] + x_maxs = z_bins[1:] + plot_bins, plot_datas = cc.makeBarPlotData(plot_data, x_mins, x_maxs) + + ax.plot(plot_bins, plot_datas, linestyle=d["linestyle"], label=d["label"]) + + ax.set_xlabel(r"Position $z$ [m]") + ax.set_ylabel(r"Particle Current $j_r$ [$m^{-2}s^{-1}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend(loc="upper right") + + filename_output = output_folder + 'tube_current_vs_z.pdf' + fig.savefig(filename_output, format='pdf', bbox_inches='tight') + +def plotLongitudinalCurrentVsZ(filename_current, filename_density, output_folder): + + e_dict = {"key" : "/e-", "linestyle": '-', "label": "e"} + T3_dict = {"key" : "/T3+", "linestyle": '--', "label": "T3+"} + dicts = [e_dict, T3_dict] + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + for d in dicts: + j_total = cc.particleCurrentZ(filename_current, filename_density, d["key"]) + z_bins = cc.binBordersZ(filename_current, d["key"]) + + plot_data = np.sum(np.sum(j_total,2),0) + ax.plot(z_bins, plot_data, linestyle=d["linestyle"], label=d["label"]) + + ax.set_xlabel(r"Position $z$ [m]") + ax.set_ylabel(r"Particle Current $j_z$ [$m^{-2}s^{-1}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend(loc="lower right") + + filename_output = output_folder + 'jz_vs_z.pdf' + fig.savefig(filename_output, format='pdf', bbox_inches='tight') \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/densities/plot_all_density_vs_z.py b/src/tools/analysis_jkellerer/densities/plot_all_density_vs_z.py new file mode 100644 index 0000000..d84cd16 --- /dev/null +++ b/src/tools/analysis_jkellerer/densities/plot_all_density_vs_z.py @@ -0,0 +1,78 @@ +import numpy as np +import h5py as h5py +import os +import sys +import matplotlib +import matplotlib.pyplot as plt + +from functions.calculate_density_from_karl import * +import functions.plot_standards as pst + +def makeBarPlotData(data, mins, maxs): + plot_bins = np.dstack((mins,maxs)).flatten() + plot_datas = np.dstack((data,data)).flatten() + return plot_bins, plot_datas + +def plotAllDensityVsZ(filename, filename_output): + keys = ["/Populations/e-/e-", "/Populations/T+/T+", "/Populations/T2+/T2+", "/Populations/T3+/T3+"] + + density_e = getDensities(filename, keys[0]) + density_T = getDensities(filename, keys[1]) + density_T2 = getDensities(filename, keys[2]) + density_T3 = getDensities(filename, keys[3]) + + zmins = getZBinsMin(filename, keys[0]) + zmaxs = getZBinsMax(filename, keys[0]) + Emins = getEBinsMin(filename, keys[0]) + Emaxs = getEBinsMax(filename, keys[0]) + + total_density_e = np.sum(density_e,3) + total_density_e = np.sum(total_density_e,2) + total_density_e = np.sum(total_density_e,1) + + print("Total density e-: ") + print(total_density_e) + + total_density_T = np.sum(density_T,3) + total_density_T = np.sum(total_density_T,2) + total_density_T = np.sum(total_density_T,1) + + total_density_T2 = np.sum(density_T2,3) + total_density_T2 = np.sum(total_density_T2,2) + total_density_T2 = np.sum(total_density_T2,1) + + total_density_T3 = np.sum(density_T3,3) + total_density_T3 = np.sum(total_density_T3,2) + total_density_T3 = np.sum(total_density_T3,1) + + print("Total density T3+: ") + print(total_density_T3) + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + plot_bins, plot_data = makeBarPlotData(total_density_e, zmins, zmaxs) + ax.plot(plot_bins, plot_data,'-', label="e-") + + plot_bins, plot_data = makeBarPlotData(total_density_T3, zmins, zmaxs) + ax.plot(plot_bins, plot_data, '--', label=r'T$^+_3$') + + plot_bins, plot_data = makeBarPlotData(total_density_T, zmins, zmaxs) + ax.plot(plot_bins, plot_data, '-.', label=r'T$^+_2$') + + plot_bins, plot_data = makeBarPlotData(total_density_T2, zmins, zmaxs) + ax.plot(plot_bins, plot_data, ':', label=r'T$^+$') + + ax.set_yscale("log") + ax.set_xlabel(r"Position $z$ [m]") + ax.set_ylabel(r"Density $n$ [$m^{-3}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend(loc="lower right") + + fig.savefig(filename_output, format='pdf', bbox_inches='tight') \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_energy.py b/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_energy.py new file mode 100644 index 0000000..4421489 --- /dev/null +++ b/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_energy.py @@ -0,0 +1,65 @@ +import numpy as np +import h5py as h5py +import os +import sys +import matplotlib +import matplotlib.pyplot as plt + +from functions.calculate_density_from_karl import * +import functions.plot_standards as pst + +def makeBarPlotData(data, mins, maxs): + plot_bins = np.dstack((mins,maxs)).flatten() + plot_datas = np.dstack((data,data)).flatten() + return plot_bins, plot_datas + + +def plotElectronDensityVsE(filename, z_rearwall, z_mid, z_dps, filename_output): + keys = ["/Populations/e-/e-", "/Populations/T+/T+", "/Populations/T2+/T2+", "/Populations/T3+/T3+"] + + k = keys[0] + density = getDensities(filename, k) + zmins = getZBinsMin(filename, k) + zmaxs = getZBinsMax(filename, k) + Emins = getEBinsMin(filename, k) + Emaxs = getEBinsMax(filename, k) + + rw_z_index = np.where(zmins <= z_rearwall)[-1][-1] + mid_z_index = np.where(zmins <= z_mid)[-1][-1] + dps_z_index = np.where(zmins <= z_dps)[-1][-1] + + density_sum = np.sum(density,2) + density_sum = np.sum(density_sum,1) + + density_rw = density_sum[rw_z_index,:] + density_mid = density_sum[mid_z_index,:] + density_dps = density_sum[dps_z_index,:] + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + plot_bins, plot_data = makeBarPlotData(density_mid, Emins, Emaxs) + ax.plot(plot_bins, plot_data, '-', label="Mid") + + plot_bins, plot_data = makeBarPlotData(density_rw, Emins, Emaxs) + ax.plot(plot_bins, plot_data,'--', label="Rearwall") + + plot_bins, plot_data = makeBarPlotData(density_dps, Emins, Emaxs) + ax.plot(plot_bins, plot_data, '-.', label="DPS") + + ax.set_yscale("log") + ax.set_xscale("log") + ax.set_xlabel(r"Energy $E$ [eV]") + ax.set_ylabel(r"Density $n_e$ [$m^{-3}$]") + + ax.set_xlim(1E-5, 2E4) + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend() + + fig.savefig(filename_output, format='pdf', bbox_inches='tight') \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_z.py b/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_z.py new file mode 100644 index 0000000..6b82d74 --- /dev/null +++ b/src/tools/analysis_jkellerer/densities/plot_electron_density_vs_z.py @@ -0,0 +1,82 @@ +import numpy as np +import h5py as h5py +import os +import sys +import matplotlib +import matplotlib.pyplot as plt + +from functions.calculate_density_from_karl import * +import functions.plot_standards as pst + +def makeBarPlotData(data, mins, maxs): + plot_bins = np.dstack((mins,maxs)).flatten() + plot_datas = np.dstack((data,data)).flatten() + return plot_bins, plot_datas + + +def plotElectronDensityVsZ(filename, E_th_max, E_beta_min, filename_output): + keys = ["/Populations/e-/e-", "/Populations/T+/T+", "/Populations/T2+/T2+", "/Populations/T3+/T3+"] + + k = keys[0] + density = getDensities(filename, k) + zmins = getZBinsMin(filename, k) + zmaxs = getZBinsMax(filename, k) + Emins = getEBinsMin(filename, k) + Emaxs = getEBinsMax(filename, k) + + thermal_energy = E_th_max + thermal_energy_index = np.where(Emins <= thermal_energy)[-1][-1] + thermal_density = np.sum(density[:,:,:,0:thermal_energy_index],3) + thermal_density = np.sum(thermal_density,2) + thermal_density = np.sum(thermal_density,1) + + print("thermal density: ") + print(thermal_density) + + beta_energy = E_beta_min + beta_energy_index = np.where(Emins >= beta_energy)[-1][-1] + beta_density = np.sum(density[:,:,:,beta_energy_index:],3) + beta_density = np.sum(beta_density, 2) + beta_density = np.sum(beta_density, 1) + + print("beta density: ") + print(beta_density) + + secondary_density = np.sum(density[:,:,:,thermal_energy_index+1:beta_energy_index-1],3) + secondary_density = np.sum(secondary_density, 2) + secondary_density = np.sum(secondary_density, 1) + + total_density = np.sum(density,3) + total_density = np.sum(total_density,2) + total_density = np.sum(total_density, 1) + + + pst.setRcParams() + prop_cycle = plt.rcParams['axes.prop_cycle'] + colors = prop_cycle.by_key()['color'] + + fig, ax = plt.subplots(figsize=pst.set_size('thesis')) + + # uncomment if plot with total density + #plot_bins, plot_data = makeBarPlotData(total_density, zmins, zmaxs) + #plt.plot(plot_bins, plot_data) + + plot_bins, plot_data = makeBarPlotData(thermal_density, zmins, zmaxs) + ax.plot(plot_bins, plot_data,'-', label="thermal") + + plot_bins, plot_data = makeBarPlotData(beta_density, zmins, zmaxs) + ax.plot(plot_bins, plot_data, '--', label="beta") + + plot_bins, plot_data = makeBarPlotData(secondary_density, zmins, zmaxs) + ax.plot(plot_bins, plot_data, '-.', label="secondary") + + ax.set_yscale("log") + ax.set_xlabel(r"Position $z$ [m]") + ax.set_ylabel(r"Density $n_e$ [$m^{-3}$]") + + ax.set_facecolor('#e7e7e7ff') + ax.grid(color='white') + + ax.legend() + + fig.savefig(filename_output, format='pdf', bbox_inches='tight') \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/example_scripts/plot_currents_example.py b/src/tools/analysis_jkellerer/example_scripts/plot_currents_example.py new file mode 100644 index 0000000..8419d1a --- /dev/null +++ b/src/tools/analysis_jkellerer/example_scripts/plot_currents_example.py @@ -0,0 +1,34 @@ +import numpy as np +import sys +import os + +homebase = os.getenv('HOMEBASE') +if homebase is None: + homebase = "/home/jonas/new_workspace/Coding/KARL/karl" +sys.path.append(homebase+"/src/tools/analysis_jkellerer") + +import functions.calculate_currents_from_karl as ic +import currents.plot_current_vs_z as pcz +import currents.plot_current_vs_r as pcr + +#filename = "/hppfs/work/pn68gi/di67ham/KARL/CurrentBoundaries/parameter_20210328_1/mc_electron_out_" +#num_cpu = 1392 + + + +#ic.mergeOutputs(filename, num_cpu, "/T3+") +#ic.mergeOutputs(filename, num_cpu, "/T2+") +#ic.mergeOutputs(filename, num_cpu, "/T+") +#ic.mergeOutputs(filename, num_cpu, "/e-") + +folder = "/home/jonas/new_workspace/Coding/Output/KARL/ElectricField/parameter_20210331_11/" +filename_current = folder+"mc_electron_out_0_currents.h5" +filename_density = folder+"mc_electron_out_0.h5" + +output_folder = "/home/jonas/new_workspace/Coding/Output/KARL/ElectricField/plots/" + +pcz.plotTubeCurrentVsZ(filename_current, filename_density, output_folder) +pcz.plotLongitudinalCurrentVsZ(filename_current, filename_density, output_folder) + +pcr.plotCurrentRVsR(filename_current, filename_density, output_folder, 5) +pcr.plotCurrentZVsR(filename_current, filename_density, output_folder, 5) \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/example_scripts/plot_densities_example.py b/src/tools/analysis_jkellerer/example_scripts/plot_densities_example.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tools/analysis_jkellerer/functions/calculate_currents_from_karl.py b/src/tools/analysis_jkellerer/functions/calculate_currents_from_karl.py new file mode 100644 index 0000000..c5066f0 --- /dev/null +++ b/src/tools/analysis_jkellerer/functions/calculate_currents_from_karl.py @@ -0,0 +1,176 @@ +import numpy as np +import h5py as h5py +import os +import sys +import matplotlib +import matplotlib.pyplot as plt + + +def NPosZ(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/N_pos_z" + ar = np.array(file[key],dtype=np.long) + file.close() + return ar + +def NNegZ(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/N_neg_z" + ar = np.array(file[key],dtype=np.long) + file.close() + return ar + +def NPosR(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/N_pos_r" + ar = np.array(file[key],dtype=np.long) + file.close() + return ar + +def NNegR(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/N_neg_r" + ar = np.array(file[key],dtype=np.long) + file.close() + return ar + +def binBordersE(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/current_bin_borders/bin_borders_E" + ar = np.array(file[key]) + file.close() + return ar + +def binBordersZ(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/current_bin_borders/bin_borders_z" + ar = np.array(file[key]) + file.close() + return ar + +def binBordersR(filename, specie_key): + file = h5py.File(filename, 'r') + key = specie_key + "/current_bin_borders/bin_borders_r" + ar = np.array(file[key]) + file.close() + return ar + +def sumEnergyBins(current_data): + return np.sum(current_data,2) + +def sumRadiusBins(current_data): + return np.sum(current_data,0) + +def sumZBins(current_data): + return np.sum(current_data,1) + +def projectionZ(current_data): + return sumRadiusBins(sumEnergyBins(current_data)) + +def projectionR(current_data): + return sumZBins(sumEnergyBins(current_data)) + +def totalCurrentZ(n_pos, n_neg): + return n_pos[:,:-1,:]-n_neg[:,1:,:] + +def totalCurrentR(n_pos, n_neg): + return n_pos[:-1,1:,:]-n_neg[1:,1:,:] + +def binAreasR(bin_borders_r, bin_borders_z): + areas = 2*np.pi* np.outer(bin_borders_r[1:], (bin_borders_z[1:]-bin_borders_z[:-1])) + return areas + +def binAreasZ(bin_borders_r, bin_borders_z): + areas = np.pi * np.outer((bin_borders_r[1:]*bin_borders_r[1:] - bin_borders_r[:-1]*bin_borders_r[:-1]), np.ones_like(bin_borders_z)) + return areas + +def particleCurrentR(filename_current, filename_densities, key): + n_pos = NPosR(filename_current, key) + n_neg = NNegR(filename_current, key) + n_total = totalCurrentR(n_pos, n_neg)[:,1:,:] + + delta_t = lastOutputTime(filename_densities) + particle_current = n_total/delta_t + + bin_borders_r = binBordersR(filename_current, key) + bin_borders_z = binBordersZ(filename_current, key) + bin_areas_r = binAreasR(bin_borders_r, bin_borders_z) + for iz in np.arange(0, particle_current.shape[2], 1): + particle_current[:,:,iz] = particle_current[:,:,iz]/bin_areas_r + + return particle_current + +def particleCurrentZ(filename_current, filename_densities, key): + n_pos = NPosZ(filename_current, key) + n_neg = NNegZ(filename_current, key) + n_total = totalCurrentZ(n_pos, n_neg)[1:, :, :] + + delta_t = lastOutputTime(filename_densities) + particle_current = n_total/delta_t + + bin_borders_r = binBordersR(filename_current, key) + bin_borders_z = binBordersZ(filename_current, key) + bin_areas_z = binAreasZ(bin_borders_r, bin_borders_z) + for iz in np.arange(0, particle_current.shape[2], 1): + particle_current[:,:,iz] = particle_current[:,:,iz]/bin_areas_z + + return particle_current + +def makeBarPlotData(data, mins, maxs): + plot_bins = np.dstack((mins,maxs)).flatten() + plot_datas = np.dstack((data,data)).flatten() + return plot_bins, plot_datas + +def lastOutputTime(filename): + key = "/Populations/e-/e-" + f = h5py.File(filename, 'r') + data = np.array([f[key]]) + f.close() + + data = np.array(data.tolist())[0] + last_output_time = np.unique(data[:,0])[-1] + + return last_output_time + +def cpuString(cpu_number, max_cpu_number): + length_string = len(str(max_cpu_number)) + return str(cpu_number).zfill(length_string) + +def outputFilename(filename_bare, cpu_number, num_cpu): + return filename_bare +cpuString(cpu_number, num_cpu) + "_currents.h5" + +def mergeOutputs(filename, num_cpu, specie_key): + + first_filename = outputFilename(filename, 0, num_cpu) + + N_pos_z = NPosZ(first_filename, specie_key) + N_neg_z = NNegZ(first_filename, specie_key) + N_pos_r = NPosR(first_filename, specie_key) + N_neg_r = NNegR(first_filename, specie_key) + + for i in np.arange(1,num_cpu,1): + N_pos_z += NPosZ(outputFilename(filename, i, num_cpu), specie_key) + N_neg_z += NNegZ(outputFilename(filename, i, num_cpu), specie_key) + N_pos_r += NPosR(outputFilename(filename, i, num_cpu), specie_key) + N_neg_r += NNegR(outputFilename(filename, i, num_cpu), specie_key) + + f = h5py.File(filename+"currents_merged.h5", 'a') + + key = specie_key+"/N_pos_z" + f.create_dataset(key,data=N_pos_z) + + key = specie_key+"/N_neg_z" + f.create_dataset(key,data=N_neg_z) + + key = specie_key+"/N_pos_r" + f.create_dataset(key,data=N_pos_r) + + key = specie_key+"/N_neg_r" + f.create_dataset(key,data=N_neg_r) + + f.close() + + + + + diff --git a/src/tools/analysis_jkellerer/functions/calculate_density_from_karl.py b/src/tools/analysis_jkellerer/functions/calculate_density_from_karl.py new file mode 100644 index 0000000..c2c6851 --- /dev/null +++ b/src/tools/analysis_jkellerer/functions/calculate_density_from_karl.py @@ -0,0 +1,161 @@ +import numpy as np +import h5py as h5py +import os +import sys + +def getCumTimes(filename, key): + f = h5py.File(filename, 'r') + data = np.array([f[key]]) + f.close() + + data = np.array(data.tolist())[0] + last_output_time = np.unique(data[:,0])[-1] + data_last = data[data[:,0] == last_output_time] + + [zbins, rbins, phi_bins, E_bins] = getNumBins(filename, key) + + cum_times = np.zeros((zbins, rbins, phi_bins, E_bins)) + + for iz in np.arange(0,zbins,1): + for ir in np.arange(0,rbins,1): + for iphi in np.arange(0,phi_bins,1): + for iE in np.arange(0,E_bins,1): + mask = np.logical_and(data_last[:,1]==iz, data_last[:,2] == ir) + mask = np.logical_and(mask, data_last[:,3] == iphi) + mask = np.logical_and(mask, data_last[:,4] == iE) + cum_times[iz,ir,iphi,iE] = data_last[mask][0,5] + + return cum_times + +def getDensities(filename, key): + f = h5py.File(filename, 'r') + data = np.array([f[key]]) + f.close() + + data = np.array(data.tolist())[0] + last_output_time = np.unique(data[:,0])[-1] + data_last = data[data[:,0] == last_output_time] + + [zbins, rbins, phi_bins, E_bins] = getNumBins(filename, key) + + cum_times = getCumTimes(filename, key) + densities = np.zeros((zbins, rbins, phi_bins, E_bins)) + + for iz in np.arange(0,zbins,1): + for ir in np.arange(0,rbins,1): + for iphi in np.arange(0,phi_bins,1): + for iE in np.arange(0,E_bins,1): + densities[iz,ir,iphi,iE] = cum_times[iz, ir, iphi, iE]/(last_output_time*getVolume(filename, key, iz, ir, iphi)) + + return densities + +def getZBinsMin(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + z_mins = np.unique(data[:,4]) + f.close() + return z_mins + +def getZBinsMax(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + z_maxs = np.unique(data[:,5]) + f.close() + return z_maxs + +def getRBinsMin(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + r_mins = np.unique(data[:,6]) + f.close() + return r_mins + +def getRBinsMax(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + r_maxs = np.unique(data[:,7]) + f.close() + return r_maxs + +def getPhiBinsMin(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + phi_mins = np.unique(data[:,8]) + f.close() + return phi_mins + +def getPhiBinsMax(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + phi_maxs = np.unique(data[:,9]) + f.close() + return phi_maxs + +def getEBinsMin(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + E_mins = np.unique(data[:,10]) + f.close() + return E_mins + +def getEBinsMax(filename, key): + meta_key = key + "_meta_data" + f = h5py.File(filename, 'r') + data = np.array([f[meta_key]]) + data = np.array(data.tolist())[0] + + E_maxs = np.unique(data[:,11]) + f.close() + return E_maxs + +def getNumBins(filename, key): + + f = h5py.File(filename, 'r') + data = np.array([f[key]]) + f.close() + + data = np.array(data.tolist())[0] + + last_output_time = np.unique(data[:,0])[-1] + + data_last = data[data[:,0] == last_output_time] + + zbins = np.size(np.unique(data_last[:,1])) + rbins = np.size(np.unique(data_last[:,2])) + phi_bins = np.size(np.unique(data_last[:,3])) + E_bins = np.size(np.unique(data_last[:,4])) + + return [zbins, rbins, phi_bins, E_bins] + +def getVolume(filename, key, z_bin, r_bin, phi_bin): + z_min = getZBinsMin(filename, key)[z_bin] + z_max = getZBinsMax(filename, key)[z_bin] + r_min = getRBinsMin(filename, key)[r_bin] + r_max = getRBinsMax(filename, key)[r_bin] + phi_min = getPhiBinsMin(filename, key)[phi_bin] + phi_max = getPhiBinsMax(filename, key)[phi_bin] + + A = (r_max**2 - r_min**2)*(phi_max-phi_min)/2 + h = z_max-z_min + return A*h \ No newline at end of file diff --git a/src/tools/analysis_jkellerer/functions/plot_standards.py b/src/tools/analysis_jkellerer/functions/plot_standards.py new file mode 100644 index 0000000..637cbdc --- /dev/null +++ b/src/tools/analysis_jkellerer/functions/plot_standards.py @@ -0,0 +1,83 @@ +import matplotlib +import matplotlib.colors as clr +import matplotlib.pyplot as plt +from cycler import cycler +from matplotlib.colors import ListedColormap, LinearSegmentedColormap + +def set_size(width, fraction=1, subplots=(1, 1)): + """Set figure dimensions to avoid scaling in LaTeX. + + Parameters + ---------- + width: float or string + Document width in points, or string of predined document type + fraction: float, optional + Fraction of the width which you wish the figure to occupy + subplots: array-like, optional + The number of rows and columns of subplots. + Returns + ------- + fig_dim: tuple + Dimensions of figure in inches + """ + if width == 'thesis': + width_pt = 426.79135 + elif width == 'beamer': + width_pt = 307.28987 + else: + width_pt = width + + # Width of figure (in pts) + fig_width_pt = width_pt * fraction + # Convert from pt to inches + inches_per_pt = 1 / 72.27 + + # Golden ratio to set aesthetic figure height + # https://disq.us/p/2940ij3 + golden_ratio = (5**.5 - 1) / 2 + + # Figure width in inches + fig_width_in = fig_width_pt * inches_per_pt + # Figure height in inches + fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1]) + + return (fig_width_in, fig_height_in) + +def setRcParams(): + #matplotlib.rcParams['text.usetex'] = True + #matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}' + + #matplotlib.rcParams['pcolor.shading'] = 'auto' + + matplotlib.rcParams['font.family'] = "serif" + matplotlib.rcParams['font.size'] = 10 + matplotlib.rcParams['axes.labelsize'] = 10 + + matplotlib.rcParams['legend.fontsize'] = 8 + matplotlib.rcParams['xtick.labelsize'] = 8 + matplotlib.rcParams['ytick.labelsize'] = 8 + matplotlib.rcParams['figure.autolayout'] = True + matplotlib.rcParams['figure.titlesize'] = 4 + matplotlib.rcParams['axes.titlesize'] = 4 + matplotlib.rcParams['lines.markersize'] = 4 + + #matplotlib.rcParams['axes.facecolor'] = '#e7e7e7ff' + #matplotlib.rcParams['axes.grid'] = True + #matplotlib.rcParams['grid.color'] = 'white' + + #matplotlib.rcParams['figure.dpi'] = 240 + + # lines for colorblind + colour_blind_cycle = ['#377eb8', '#ff7f00', '#4daf4a', + '#f781bf', '#a65628', '#984ea3', + '#999999', '#e41a1c', '#dede00'] + matplotlib.rcParams['axes.prop_cycle'] = cycler(color=colour_blind_cycle) + + #colorblind cmap + colorblind_diverging = ['#ca0020','#f4a582','#f7f7f7','#92c5de','#0571b0'] + Cmap_Name="mymap" + mymap = LinearSegmentedColormap.from_list(Cmap_Name,colorblind_diverging) + plt.register_cmap(name=Cmap_Name, cmap=mymap) + matplotlib.rcParams['image.cmap']=Cmap_Name + + diff --git a/src/tools/linkToAcronym/createElectricFieldFromH5.py b/src/tools/linkToAcronym/createElectricFieldFromH5.py index 66e9dbd..dd396e8 100644 --- a/src/tools/linkToAcronym/createElectricFieldFromH5.py +++ b/src/tools/linkToAcronym/createElectricFieldFromH5.py @@ -11,7 +11,7 @@ def createZeroFieldH5(filename_output): zero = np.zeros((1,1)) saveToKarlH5File(filename_output, zero, zero) -def createFieldH5(filename_derived, filename_output, dx, timestep, cylinder_origin, radius, height, z_start, z_end): +def createFieldH5(filename_derived, filename_output, dx, timestep, cylinder_origin, radius, height, z_start=0, z_end=0): L_wgts = 1300 num_cells = int((L_wgts - height*dx)/dx) @@ -111,6 +111,10 @@ def extendValues(data_2d, z_start, z_end, num_cells): return data_ext def copyValues(data_2d, z_start, z_end, num_cells): + if z_start >= z_end: + return data_2d + + (size_x, size_y) = np.shape(data_2d) data_copy = np.zeros((size_x, size_y+num_cells)) data_copy[:,:z_start] = data_2d[:,:z_start]