% !TEX root = ../thesis.tex % !TEX useTabs %% LaTeX2e class for student theses %% sections/processes.tex %% %% Karlsruhe Institute of Technology %% Institute for Program Structures and Data Organization %% Chair for Software Design and Quality (SDQ) %% %% Dr.-Ing. Erik Burger %% burger@kit.edu %% %% Version 1.3.3, 2018-04-17 \chapter{The Karl Code} \label{ch:cod} The \textbf{KARL} - \textbf{KA}trin WGTS elect\textbf{R}on and ion spectrum Monte Car\textbf{L}o simulation code was developed from scratch within this thesis to simulate the electron and ion distributions of the \ac{wgts} (\autoref{sec:kat:sts}). The resulting distributions of charged particles are a key factor in the plasma studies of the KATRIN experiment (\autoref{sec:kat:plasma}). The current overall plasma simulation strategy for the KATRIN experiment is summarized in \autoref{sec:cod:intention}. The entire KARL code is implemented in C\texttt{++} and uses several libraries for optimizing efficiency. These and further technical concepts used in KARL are presented in \autoref{sec:cod:tech}. The basic concept of the simulation is the repetitive physical simulation of single particles. The general simulation strategy is covered in \autoref{sec:cod:strat} and the simulation of a single kinetic particle with focus on physics is treated in \autoref{sec:cod:phys}. For better comprehensibility in the further discussion the single particle, that is being actively simulated, will be abbreviated by \ac{csp}. The KARL code only simulates one \ac{csp} at a time. Hence interactions between particles can not be directly simulated. The implementation of \acp{rdf} allows self consistent treatment of particle interactions. These \acp{rdf} indicate the density for each particle species and are calculated within the physical simulation of each \ac{csp} of the respective species. The calculation and implementation of \acp{rdf} is presented in \autoref{sec:cod:dens}. \acp{rdf} only indicate the number of target particles. The overall interaction probability is measured by \acfp{mcs}. The calculation of the \acp{mcs} for interactions of \acp{csp} with \acp{rdf} is covered in \autoref{sec:cod:macro}. The final electron and ion distributions are obtained using the logging barrier strategy. Therefore virtual barriers are implemented throughout the \ac{wgts}. Particles passing these barriers are logged. The link between this logged data and the desired electron and ion distribution is presented in \autoref{sec:cod:log}. Statistically significant results can only be gained when a large number of particles is simulated. Thus parallel computation is inevitable. The parallelization strategy of the KARL code is presented in \autoref{sec:cod:parallel}. Prior to every simulation with KARL a number of simulation parameters allows for adjusting the simulation to one's needs. Throughout this and the subsequent chapter (\autoref{ch:cod} and \autoref{ch:mod}) the function of each individual parameter will be explained in detail in the respective section. An overall overview of the parameters and details on setting them is given in \autoref{sec:cod:parameters}. \section{Code intention} \label{sec:cod:intention} \begin{figure}[tb] \centering \includestandalone{pics/code/logic} \caption{Scheme of the twofold plasma simulation strategy. The KARL code calculates electron and ion distributions in a given electric field configuration and passes these distributions to the \ac{pic} code. The \ac{pic} code calculates an electric field configuration from electron and ion distributions and passes these electric fields to the KARL code.} \label{fig:cod:logic} \end{figure} In order for the KATRIN experiment to reach the target sensitivity of \SI{0.2}{\eV}, all systematic effects must be well understood. In terms of plasma effects the arising spatial electric fields are of interest (\autoref{sec:kat:plasma}). Experimental observation and analytical modeling of plasma effects is only partly possible and not sufficient for final quantification of plasma effects. Thus simulations are needed to gain a extensive understanding of the plasma. Due to the complexity of the system a full plasma simulation, where electric field calculations and particle chemical process are combined, is not feasible. Hence a twofold simulation strategy is chosen (\autoref{fig:cod:logic}). A \acf{pic} simulation based on the ACRONYM code \cite{Kilian:2012aa}, which will be presented in the scope of a PhD thesis by J. Kellerer, calculates the electric fields arising from charged particles in the \acs{wgts}. Electrons are implemented from an initial distribution and are modeled fully kinetically. Ions can not be resolved kinetically due the much larger mass. Since ions are moving much slower than electrons, kinematics of ions on plasma time scales are negligible. Thus ions are implemented as time constant fluxes of charge. The initial electron distribution and constant ion fluxes for the \ac{pic} simulation are provided by simulations using the KARL code. The KARL code simulates all relevant particle chemical interactions in the \ac{wgts} to obtain the electron and ion distribution throughout the \ac{wgts}. In contrast to the \ac{pic} simulation, the KARL code cannot calculate electric and magnetic fields from asymmetries in particle distribution, as each particle is simulated individualy. Thus the KARL code implements constant electric and magnetic fields prior to simulation. These fields are provided from the \ac{pic} simulation. By iterative combination of both simulations, where electric fields from the \ac{pic} simulation are implemented into the KARL simulation and in return electron and ion distributions from the KARL simulation are implemented into the \ac{pic} simulation, a equilibrium state will be reached. This equilibrium state yields a detailed map of electric fields due to plasma effects throughout the \ac{wgts}. These fields can be taken into account in the neutrino mass deduction. \section{Technical details} \label{sec:cod:tech} The entire KARL code is implemented in C\texttt{++11}. C\texttt{++} provides high computation efficiency, allows for easy optimizations and has many libraries specialized on scientific tasks. Additionally C\texttt{++} allows for runtime and compile time polymorphism. This allows for very efficient implementation of various interactions and proper handling of different particle species at runtime. Vector operations and \ac{rng} are handled using the Blitz\texttt{++} \cite{Veldhuizen:2000aa} library. For the \ac{rng}, Blitz\texttt{++} uses an adaption of the Mersenne-Twister 19937 algorithm (\autoref{sec:mon:rng}). Output is written in HDF5 format \cite{The-HDF-Group:1997aa} using the Table API of the corresponding library. This allows for efficient memory usage and optimized writing speed. Additionally the KARL code buffers output internally to optimize IO-speed. The parallelization strategy of KARL (\autoref{sec:cod:parallel}) uses a distributed memory system. This is realized using Open MPI \cite{Gabriel:2004aa}, allowing for communication between cores (\autoref{sec:mon:mpi}). The parallelization strategy is covered in \autoref{sec:cod:parallel}. Throughout the entire KARL code linear and logarithmic binning of physical quantities are used. Efficient memory access is only possible if each quantity is directly mapped to an address. For a linear scale of a quantity $x$, that is binned into $n_x$ bins on $[x_\mathrm{min},x_\mathrm{max})$ the corresponding index of the memory address can than be calculated from \begin{equation} i_x = ceil\big(\frac{x-x_\mathrm{min}}{\Delta x} \big) - 1 \, , \end{equation} where $\Delta x = \frac{x_\mathrm{max} - x_\mathrm{min}}{n_x}$ is the width of each bin. Logarithmic binning is obtained from logarithmizing $x$, $x_\mathrm{min}$ and $x_\mathrm{max}$. Internally the KARL codes uses a Cartesian coordinate system with coordinates $x, y, z$. The $z$-axis is aligned along the magnetic field lines. Positive $z$- direction points towards the spectrometers and negative $z$-direction towards the rear wall. For the exact definition of the Cartesian coordinate system see \autoref{sec:mod:wgts}. For certain application the use of cylindric coordinates $r, \varphi, z$ is handy. These are linked to the Cartesian coordinate system by \begin{equation} \label{eq1} \begin{split} x &= r \cdot \cos(\varphi) \\ y &= r \cdot \sin(\varphi) \\ z &= z \, . \end{split} \end{equation} The entire Karl code uses classical energy-velocity relation $E=\frac{m}{2} v^2$, as particles of interest are non relativistic. Thus transformation of coordinate systems is calculated using Galileo transformation. \section{Simulation strategy} \label{sec:cod:strat} \begin{figure}[tb] \centering \includestandalone{pics/code/algorithm} \caption{Flowchart of the simulation algorithm. Algorithm starts with injection of $\upbeta$-\ce{e-}. Consecutively the $\upbeta$-\ce{e-} and all arising particles are being simulated. New $\upbeta$-decays are performed until the number of target decays is reached. \mbox{\acs{pq}: \acl{pq}}.} \label{fig:cod:algo} \end{figure} KARL simulates the electron and ion distribution in the \ac{wgts} (\autoref{sec:kat:sts}) by repetitive kinetic simulation of single particles. As explained in \autoref{sec:cod:intention} electric and magnetic fields are implemented prior to simulation as time constant numeric fields. The density and velocity profile of molecular tritium \ce{T2} is implemented as time constant because kinetic simulation exceeds the computation budget and variations of \ce{T2}-distribution caused by effects treated in the simulation are negligible. For details on the implementation of the \ac{wgts} and \ce{T2} see \autoref{sec:mod:wgts}. The starting point of the simulation are $\upbeta$-decays injecting kinetic $\upbeta$-\ce{e-} into the simulation (\autoref{fig:cod:algo}). By processes such as ionization new particles are created within the physical simulation of the $\upbeta$-\ce{e-}. This actual physical simulation is covered in \autoref{sec:cod:phys}. Particles created within the physical simulation are stored in the \ac{pq} and are processed subsequently. Implemented particle species that are simulated kinetically are \ce{e-}, \ce{T+}, \ce{T2+}, \ce{T3+}, \ce{T5+}. Higher order of tritium ion clusters are not implemented as their properties resemble \ce{T5+} (\autoref{sec:mod:ions}). Further particle species can be easily added in further version of KARL if found necessary. As long as the \ac{pq} is filled, particles from the \ac{pq} are physically processed one by one. New \acp{csp} are selected from the \ac{pq} randomly to reduce correlation effects. Once all particles emerging from one $\upbeta$-\ce{e-}, including particles from secondary and higher order particles, are processed, a new $\upbeta$-\ce{e-} is injected and the algorithm is repeated. This process is repeated until the target number of $\upbeta$-decays is reached. The target number of $\upbeta$-decays is set by the DECAYS parameter. By repeating the process a time integration is performed. The total simulation time $T_\text{sim}$ is linked to the $\upbeta$-decay activity $A_\upbeta$ and the total number of $\upbeta$-decays $N_\upbeta$ performed in the simulation and calculates to \begin{equation} T_\text{sim} = \frac{N_\upbeta} {A_\upbeta} \, . \end{equation} \section{Simulation of the \acf{csp}} \label{sec:cod:phys} \begin{figure}[tb] \centering \includestandalone{pics/code/physsim} \caption{Flowchart of the physical simulation algorithm for a \ac{csp}. Particles simulation alternates between propagation by a \acf{mfp} and performing interactions until a termination condition is met.} \label{fig:cod:particle_flow} \end{figure} For the physical simulation of the \acf{csp} a semi classical approach is chosen. An overview of the algorithm is displayed in \autoref{fig:cod:particle_flow}. Particles for the physical processing emerge from either $\upbeta$-decay or are created within this physical simulation from another \ac{csp} by processes such as ionization. The semi classical approach processes propagation and interactions separately. In alternation the \ac{csp} is propagated classically by one \ac{mfp} and interacts afterwards with one \ac{rdf}. Between and during each step the \ac{csp}'s properties are checked for physical and simulational termination. In the subsequent subsections all relevant processes are described in detail with focus on the realization of physical laws. \subsection*{$\upbeta$-Injection} The probability for a $\upbeta$-decay scales linear with the \ce{T2}-density. The implemented \ce{T2}-density is only dependent on the longitudinal position $z$ and is independent from the polar coordinates $r$, $\varphi$ (\autoref{sec:mod:wgts}). Thus $r$ and $\varphi$ are sampled using the inverse sampling theorem for uniform distributions (\autoref{eq:mon:inversion}) resulting in \begin{align} \label{eq:cod:iso} r &= \eta_1 \cdot r_\text{WGTS} \, , \\ \varphi &= \eta_2 \cdot 2\pi \, , \end{align} where $\eta_{1,2}$ are uniform random numbers on $[0,1)$ and $r_\text{WGTS}$ is the radius of the \ac{wgts}. The longitudinal position $z$ is sampled from the implemented \ce{T2}-density using rejection method (\autoref{sec:mon:sample}). The energy of the $\upbeta$-\ce{e-} is sampled from the $\upbeta$-decay spectrum (\autoref{eq:neu:beta}) also using rejection method (\autoref{sec:mon:sample}). The effect of the neutrino mass on the entire $\upbeta$-spectrum is negligible. The initial direction of motion is assumed to be isotropic. Thus it is sampled analogous to \autoref{eq:cod:iso}. The usage of rejection method at this point does not reduce efficiency, since $\upbeta$-injection is only performed scarce in comparison to the number of operation for each \ac{csp} simulation times the number of secondary particles. Ions emerging from $\upbeta$-decays are implemented as thermal \ce{T2+}. Thus the initial momentum is sampled from the \ce{T2}-distribution. Kinetic ions and other decay channels are not included in the simulation (\autoref{sec:mod:ions}). Further injection methods beside $\upbeta$-injection are implemented in KARL for testing purposes. The injection of the tritium ions can be muted with the INJ\_TI parameter, where 0 deactivates and 1 activates the injection. By specifying the INJECTION and INJ\_E parameter further energy spectra for the initial \ce{e-} are definable. The default method for sampling from the $\upbeta$-spectrum is \mbox{INJECTION = 0}. In this case the INJ\_E parameter is ignored. For INJECTION = 1 all \ce{e-} are injected with constant energy. Here the INJ\_E specifies the energy in \si{\eV}. INJECTION = 2 injected the \ce{e-} from a Maxwell Boltzmann distribution. The temperature $T$ of the distribution is linked to the energy specified by the INJ\_E in \si{\eV} through $E = k_\mathrm{B} T$. $k_\mathrm{B}$ is the Boltzmann constant. \subsection*{Propagation} Propagation of \acp{csp} is performed classically by one \acf{mfp} $\lambda$. The \ac{mfp} specifies the average length of propagation between interactions and is calculated from the total \ac{mcs} (\autoref{eq:mon:lambda}). The calculation of \ac{mcs} is covered in \autoref{sec:cod:macro} and depends on the implemented \aclp{ic}. These are presented in \autoref{ch:mod}. For calculating propagation the Boris Push algorithm (\autoref{sec:mon:boris}) and the Drift Approximation (\autoref{sec:mon:drift}) are implemented in KARL. Drift Approximation is recommended, as the computation efficiency is drastically increased and the simulation is performed in a constant magnetic field. Both solvers allow for propagation of charged particles in electric and magnetic fields. The solver can be specified using the PROPAGATION parameter. For PROPAGATION = 0 the Drift Approximation is used and for PROPAGATION = 1 Boris Push is used. If Boris Push is chosen additionally the parameter BORIS\_T needs to be set. This specifies the time stepping of the Boris Push algorithm. Particles reaching the rear wall or radial walls of the \ac{wgts} during propagation are passed to the terminator and terminated from physical simulation. The boundary condition in positive $z$ direction differ for electrons and ions. Ions are removed from the simulation at this point (\autoref{sec:kat:sts}), whereas electrons are reflected. The number electrons that surpass the spectrometers and reach the detector during operation of the KATRIN experiment is negligible. During each propagation step the \acp{rdf} are updated (\autoref{sec:cod:dens}) and \acp{csp} passing a logging barrier are tracked (\autoref{sec:cod:log}). \subsection*{Interaction} At every interaction step only one interaction is performed. Thus in the first step a \ac{ic} must be sampled. The probability for each \ac{ic} is \begin{equation} w_i(E) = \frac{\Sigma_i(E)}{\Sigma_\mathrm{tot}(E)} \, , \end{equation} where $\Sigma_i(E)$ is the \ac{mcs} of corresponding \ac{ic} and $\Sigma_\mathrm{tot}(E)$ the total \ac{mcs}. Since each $w_i(E)$ represents the probability of observing a discrete \ac{ic} a resulting \ac{ic} is sampled using numerical evolution (\autoref{sec:mon:sample}). Calculation of \acp{mcs} is covered in \autoref{sec:cod:macro}. Once an \ac{ic} is sampled the interaction is performed by sampling an interaction partner from the corresponding \ac{rdf} and by sampling the physical properties of the interaction from the corresponding \acp{dcs}. From these data the final state of the \ac{csp} after interaction is calculated and set. Detailed information on the implemented models for each \ac{ic} is given in \autoref{ch:mod}. Here an overview of mathematical and simulational methods is given. \paragraph{Elastic scattering} For elastic scattering the scattering angles $\vartheta$, $\varphi$ and the initial momenta of the two interaction partners specify the kinematics of the process. The initial momentum of the active particle is well known and the momentum of the secondary particle is sampled from the corresponding population. The scattering angles are sampled from the corresponding \acp{dcs}. The calculation of final kinematics is performed following \cite{Landau:2011aa} and \autoref{eq:mon:dir}. \paragraph{Ionization} In case of electron impact ionization, the primary electron transfers enough energy to a bound secondary electron, so that it can overcome the binding energy of its atom or molecule. Thus impact ionization is only possible if the primary electron's initial energy $E_\mathrm{tot}$ exceeded the binding energy $B$. Following the process a second free electron and an ion is created, which are are appended to the \ac{pq}. Due to the sheer number of degrees of freedom the process can not be fully specified by \acp{dcs}. It is assumed that the ion adopts the properties of the atom/molecule. The energy of the secondary electron $E_2$ is sampled from the corresponding \ac{dcs}. Generally conversation of energy must be satisfied: \begin{equation} E_\text{tot} = E_1 + E_2 + B \, , \end{equation} where $E_1$ is the energy of the initial electron after the interaction. Direction of momenta of primary and secondary electron after interaction are sampled from the corresponding \acp{dcs}. \paragraph{Excitation} A very efficient \ac{ic} for cooling electrons are excitations of the atoms or molecules. In these processes the \ac{csp}-\ce{e-} loses a quantized amount of energy in order to excite a certain excitation level of the atom/molecules. Generally it is assumed that no further energy is being transfered. Thus the electron's final energy is specified by the initial energy and the excitation level. The final direction of motion is sampled from the corresponding \ac{dcs}. \paragraph{Recombination} Low energetic electrons and ions can recombine to form neutral atoms or molecules. This leads to the termination of physical simulation. Since electrons and ions are simulated kinetically the process must be implemented for both species symmetrically. \paragraph{Cluster formation} Low energetic ions can cluster up with neutral molecules and form cluster ions. Since ions and molecules are only implemented thermally (\autoref{sec:mod:ions}) the resulting cluster can be initialized from the \ac{csp}. \subsection*{Termination} Physical termination by wall interactions or particle interactions are handled during the processing of propagation and interaction. Additional simutational termination conditions are implemented in order to prevent continuous loops and excessive computational effort. The TERM\_E parameter allows for specifying a minimum threshold energy in \si{\eV} removing \ac{csp} with lower energies. The TERM\_MAX parameter defines a maximum number of interactions before each \ac{csp} is terminated. The TERM\_DI\_E parameter allows to set a threshold energy in \si{eV} for termination at positive $z$-direction. In normal operation \ce{e-} are reflected at this point. Electrons with lower energies than this threshold are terminated. In high quality simulations the number of non physical terminations should be negligible. To guarantee this, statistics about the termination channels is tracked. All possible loss channels and corresponding labels are summarized in \autoref{tab:cod:term}. \begin{table}[t] \caption{Overview of termination channels.} \label{tab:cod:term} \centering \begin{tabular}{ll} \toprule label & description \\ \midrule n\_rw & Termination at rear wall (negative $z$) \\ n\_dipole & Termination at dipoles (positive $z$) \\ n\_radial & Termination at \ac{wgts} walls (radial) \\ n\_max & Termination due to maximum interaction \\ n\_energy & Termination due to too low energy \\ n\_reaction & Termination by interaction \\ \bottomrule \end{tabular} \end{table} \section{\acf{rdf}} \label{sec:cod:dens} \acfp{rdf} are implemented to indicate the densities of all particles. The \acp{rdf} are calculated during simulation of each \ac{csp} and therefore make the simulation self consistent. Only the \ce{T2}-\ac{rdf} is implemented as a constant prior to simulation (\autoref{sec:mod:wgts}). The runtime calculation of \acp{rdf} during the \ac{csp} simulation is done by accumulation of time spend within each bin of the corresponding \ac{rdf}. The density of that bin then calculates to \begin{equation} \label{eq:cod:dens} n = \frac{1}{V} \cdot \frac{t_\mathrm{c}}{t_\mathrm{sim}(n_\upbeta)} \, , \end{equation} where $V$ is the volume of the bin, $t_\mathrm{c}$ the cumulated time spend in the bin and $t_\mathrm{sim}$ the current simulation time. The current simulation time is calculated by the decay activity $A_\upbeta$ and the current number of $\upbeta$-decays $n_\upbeta$ using \begin{equation} t_\mathrm{sim}(n_\upbeta) = \frac{n_\upbeta}{A_\upbeta} \end{equation} The \acp{rdf} are spliced into multiple spatial bins using cylindric coordinates. Setting of the POP\_N\_Z, POP\_N\_R, POP\_N\_PHI parameters allows for specifying the number of bins in $z$, $r$ and $\varphi$. Ion \acp{rdf} are implemented without energy resolution. They adapt the velocity-distribution of \ce{T2}. This is a superposition of a constant drift speed $\vec{v}_\mathrm{drift}$ and an isotropic Maxwell-Boltzmann distribution specified by \ac{wgts} temperature and mass of species particle (\autoref{sec:mod:wgts}). The electron \ac{rdf} is additionally sliced into energy bins. Here logarithmic binning is used. The number of energy bins is specified by the POP\_N\_E parameter, the lower end of the scale is specified by the POP\_E\_START parameter and the upper limit by POP\_E\_END. A number of pre-run decays to reach equilibrium before taking statistics can be set using the POP\_DECAYS and POP\_STEP parameters. POP\_DECAYS is the total number of decays to perform before the actual run. The POP\_STEP parameters specifies the number of $\upbeta$-injections to performe on each core before synchronizing the density fields across all cores (\autoref{sec:cod:parallel}). \section{Macroscopic cross section (MCS) calculation} \label{sec:cod:macro} \begin{figure}[tb] \centering \includestandalone{pics/code/theta_int} \caption{Sketch of shift from simulation coordinate system to laboratory frame. $\vec{v}_1$ is the velocity of bombarding particle in the simulation system. $\vec{v}_2(\vartheta, \varphi)$ is the velocity of the target particle in the simulation system. In the simulation integration over all possible $\vartheta$ and $\varphi$ is performed. The integration is independent of $\varphi$. $\vartheta$ is displayed in blue. The resulting velocity of the bombarding particle is displayed in red and labeled as $\vec{v}_\mathrm{lab}$.} \label{fig:cod:theta_int} \end{figure} The \acf{mcs} $\Sigma_\mathrm{tot}(E)$ is a measure for the interaction probability of a \ac{csp}. In the simulation \acp{mcs} determine the distance of free propagation between each interaction and are essential for performing interactions (\autoref{sec:cod:phys}). The total \ac{mcs} is obtained by summation over the \acp{mcs} $\Sigma_i(E)$ of all possible \acfp{ic} connected to the \ac{csp}: \begin{equation} \Sigma_\mathrm{tot}(E) = \sum_i \Sigma_i(E) \, . \end{equation} The \ac{mcs} of one specific \ac{ic} is defined as product of the corresponding microscopic \ac{tcs} $\sigma_i$ and density of interaction partner $n_i$ for this \ac{ic}: \begin{equation} \Sigma_i(E) = \sigma_i(\Elab) \cdot n_i (\vec{x})\, , \end{equation} where $\Elab$ is the energy in the laboratory frame and $\vec{x}$ the position of the \ac{csp}. The density of interaction partners $n_i (\vec{x})$ are obtained from the \ac{rdf} and the \ac{tcs} $\sigma_i(\Elab)$ from the implemented theory. Generally \acp{tcs} are described in the laboratory system, where a kinetic bombarding particle with energy $\Elab$ approaches a fixed target particle. In the \ac{mcs} calculation it must be differentiated whether the \ac{csp} is bombarding or target particle in the \ac{tcs} definition. The actual models implemented for specific \acp{tcs} are presented in \autoref{ch:mod}. In the following methods for calculating the \ac{tcs} for different matches of \acp{csp} and \acp{rdf} with consideration of the laboratory frame definition are discussed. This calculation of the \ac{tcs} is nontrivial, as the \acp{rdf} do not exactly specify a direction of motion and thus integration must be performed. The drift speed of thermal \acp{rdf} has a well defined direction. This can be considered, by transformation to a frame, where the target \ac{rdf} is at rest. This transformation is done prior the further calculations is therefore not explicitly stated in the following. Then neither thermal nor kinetic \acp{rdf} specify the direction of their particles. Thus an isotropic distribution is assumed. For the calculation of the \ac{tcs} the possible constellations between the velocity of a \ac{csp} $\vec{v_1} = \hat{n}_1 \cdot v_1$ and the velocity $\vec{v_2}$ of a interaction partner from \ac{rdf} must be considered. $\vec{v_2}$ can be parameterized using $\vartheta = [0,\pi)$ and $\varphi = [0,2\pi)$ in respect to $\hat{n}_1$ (\autoref{fig:cod:theta_int}), which results in \begin{equation} \vec{v_2} (\vartheta, \varphi) = v_2 \cdot \hat{n}_1 \cdot \begin{pmatrix}\sin(\vartheta) \cos(\varphi)\\ \sin(\vartheta) \sin(\varphi) \\ \cos(\vartheta)\end{pmatrix} \, . \end{equation} Shifting to the laboratory frame, where the \ac{csp} is the bombarding particle yields \begin{align} \vec{v}_\mathrm{lab}(\vartheta, \varphi) &= \vec{v}_1 - \vec{v_2} (\vartheta, \varphi) \, ,\\ \Elab (\vartheta) = \frac{m}{2} \cdot |\vec{v}_\mathrm{lab}(\vartheta, \varphi)|^2 &= \frac{m}{2} \cdot \Big(v_1^2 + v_2^2 - 2 v_1 v_2 \cos(\vartheta) \Big) \label{eq:cod:Elab} \, , \end{align} where $m$ is the mass of the \ac{csp}. Since \autoref{eq:cod:Elab} is independent of $\varphi$ the \ac{tcs} results in \begin{equation} \label{eq:cod:sigone} \sigma(v_1, v_2) = \frac{1}{\pi} \int_0^\pi \upd \vartheta \sigma\big(\Elab (v_1, v_2, \vartheta)\big) \, . \end{equation} In the KARL code this one dimensional integral is solved numerically using Simpson's rule following \cite{Press:1992aa}. Opposite laboratory frame definition, where the \ac{csp} is the target particle, can be easily adjusted by redefinition of $m$ due to the symmetry of \autoref{eq:cod:Elab}. In that case $m$ is the mass of a \ac{rdf} particle. For interactions of the \ac{csp} with a kinetic \ac{rdf}, the absolute velocity $v_2$ is determined by the energy bin. Thus the \ac{mcs} of a particular energy bin is obtained using \autoref{eq:cod:sigone} and multiplying with the density of corresponding energy bins. The total \ac{mcs} for that \ac{ic} is obtained by summation over all energy bins. For interactions with thermal density fields the sub lying Maxwell Boltzmann distribution must be considered. Integration over the $v_2$ distribution must be performed and the \ac{tcs} results in \begin{equation} \sigma(v_1) = \frac{1}{\pi} \int_0^\pi \upd \vartheta \int_0^\infty \upd v_2 \, f_\mathrm{MB}(v_2) \cdot \sigma\big(\Elab (v_1, v_2, \vartheta)\big) \, . \end{equation} This two dimensional integration is solved using Simpson's rule on a rectangular grid following \cite{Press:1992aa}. The infinite upper bound of the velocity integral is approximated using \begin{equation} v_{2,\mathrm{up}} = 3\cdot \sqrt{\frac{2 k_\mathrm{B} T}{m_t}} \, , \end{equation} which represents \SI{99.96}{\percent} of the integral. For higher computation efficiency, integration is ignored, if either one of the velocities is much larger than the other. In that case \autoref{eq:cod:Elab} can be replaced using the classical energy-velocity relationship. In the simulation this condition was formulated as \begin{equation} v_\mathrm{u} > \num{2000} \cdot v_\mathrm{l} \, , \end{equation} where $v_\mathrm{u}$ is the velocity of the fast particle and $v_\mathrm{l}$ of the slow. The factor \num{2000} represents a \textasciitilde \SI{1}{\percent} variation of the laboratory energy during $\vartheta$ integration in \autoref{eq:cod:Elab}. For comparison with thermal \acp{rdf} the velocity corresponding to $k_\mathrm{B} T$ was used. The integration precision can be increased by splitting the integration range into equal sized bins. The INT\_N\_INTPOINTS parameter specifies the number of bins. The integration is then performed in each bin and totaled up afterwards. This parameter also specifies the number of points in each direction of the rectangular grid used for the two dimensional integration. Calculation of the \ac{mcs} is among the most performed operations in the KARL code. Runtime calculation of integrals is very costly. Hence KARL provides the option to precompute the integrals. Since temperature of \ac{wgts} and properties of energy bins of kinetic \acp{rdf} are set prior to simulation the integral only depends on the energy of the \ac{csp}. Setting INT\_PRE\_START and INT\_PRE\_END parameter define the lower and upper end for the precomputed energy scale and the INT\_PRE\_N specifies the number of precomputed points. The precomputed energies are calculated on a logarithmic scale. \section{Logging barrier method} \label{sec:cod:log} \begin{figure}[tb] \centering \includestandalone{pics/code/log_bar_time} \caption{Sketch of a particle with longitudinal speed $v_z$ passing a logging barrier. The particle is displayed in blue. The logging barrier is displayed as thick red line. Dashed box with surface $A$ and thickness $\upd l$ represent volume the particle passes with constant speed $v_z$. Velocity components of the particle parallel to the logging barrier are not displayed in this sketch.} \label{fig:cod:log} \end{figure} Using logging barriers, particle densities and fluxes with high energy resolution are obtained at predefined $z$-positions in the \ac{wgts}. The positions are specified by the LOG\_BARS parameter, which indicate the number of logging barriers. The barriers are evenly spaced in the \ac{wgts} including the minimum and maximum $z$-value. If LOG\_BARS = 1 only particles reaching the minimum $z$-value (rear wall) are logged. During each propagation step of a particle the simulation checks whether a logging barrier was passed and if a barrier was passed the phase-space coordinates $(\vec{x}, \vec{v})$ of the particle are written to the output. From this data detailed particle densities and particle fluxes can be calculated in the post processing. This calculation will be shown in the following. The contribution of a single particle to the total density $n_i$ can be calculated from its longitudinal speed $v_{z,i}$. When treating a logging barrier as a three dimensional disk with thickness $\upd l$ and surface $A$, the particle spends the time $\upd t_i = \frac{\upd l}{v_{z,i}}$ in the volume $\upd V = \upd l \cdot A$ (\autoref{fig:cod:log}). Thus the density in respect to the total simulation time $T_\mathrm{sim}$ of one particle results in \begin{equation} \label{eq:cod:log} n_i = \frac{t_i}{V \cdot T_\mathrm{sim}} = \frac{1}{A \cdot T_\mathrm{sim} \cdot v_{z, i}} \end{equation} The total density is obtained by summing over all density contributions. The differential spectrum in energy $\frac{\upd n}{\upd E}$ is obtained by grouping the data in energy bins prior summation and normalizing by the bin width. For better statistics logarithmic binning is recommended. The longitudinal particle flux $j_z$ is obtained by counting the number of particles passing the barrier with respect to the passing direction. The total flux results in \begin{equation} j_z = \frac{N_+ - N_-}{A \cdot t_\mathrm{sim}} \, , \end{equation} where $N_+$ is the number of particles with positive $v_z$ and $N_-$ with negative $v_z$. The differential particle flux $\frac{\upd j_z}{\upd E}$ is obtained analogous to the differential density $\frac{\upd n}{\upd E}$ calculation. Additionally radial effects can be examined by subdividing the logging barrier into several sub discs. In that case the the surface $A$ must be adjusted accordingly. \section{Parallelization strategy} \label{sec:cod:parallel} \begin{figure}[tb] \centering \includestandalone{pics/code/parallel} \caption{Flowchart of the parallelization strategy of the KARL code. $n_\mathrm{left}$ is the number $\upbeta$-decays left until reaching the number of target decays. $n_\mathrm{step}$ is the number $\upbeta$-decays that are simulated on each core before synchronizing the \ac{rdf} and $n_\mathrm{cores}$ is the number of cores used for the simulation. } \label{fig:cod:para} \end{figure} A high number of $\upbeta$-decays is needed to obtain statistically significant results. Therefore parallelization of the KARL code is inevitable. Classical Monte Carlo parallelization strategy is not feasible for KARL, since the simulation of \ac{csp} depends on the \ac{rdf}. Thus an adaption to the classical parallelization strategy is used for KARL. Here the \acp{rdf} are averaged over all cores after a fix number of $\upbeta$-decays on each core (\autoref{fig:cod:para}) before continuing the simulation. This stepping size before synchronizing is specified by the STEP parameter. The actual communication in KARL is performed using MPI\_ALLGATHER commands (\autoref{sec:mon:mpi}). For statistically uncorrelated results the \acp{rng} of each core must be initialed with different seeds. Each core initializes its seed depending on the SEED parameter and its MPI rank. Thus same SEED parameters and same number of cores yields the same simulation results. \section{Simulation parameters} \label{sec:cod:parameters} Setting simulation parameters allow for adjustment of the simulation. The function of each parameter is discussed in this and the subsequent chapter (\autoref{ch:cod} and \autoref{ch:mod}) in the respective sections. An overview of all simulation parameters is displayed in \autoref{tab:cod:para}. Parameters are passed to the simulation using a parameter file. The location of the file is passed by setting the environment variables "parpath" and "parfile", where "parpath" is the path to the directory containing the file and "parfile" specifies the name of the file. A parameter is set in the file by starting a row with the name of the parameter and specifying the parameter value with whitespace delimiter. Empty rows or rows starting with '\#' are ignore. Also '=' and ';' are ignored. A sample parameter file using recommended parameters is displayed in \autoref{lst:app:para}. \begin{table}[tp] \caption{Overview of simulation parameters with recommendation for KATRIN parameters in measurement mode.} \label{tab:cod:para} \centering \begin{tabular}{p{3cm} p{1.3cm} p{10cm}} \toprule Parameter & Rec. & Description \\ \midrule SEED & & Seed of \acs{prng} (\autoref{sec:mon:rng}) \\ POP\_DECAYS & & Number of decays for initial population calculation \\ POP\_STEP & & Stepwidth for initial population calculation \\ DECAYS & & Number of target $\upbeta$-decays \\ STEP & 14 & Stepwidth before synchronizing densities across cores \\ LOG\_BARS & & Number logging barriers \\ PROPAGATION & 0 & 0 = Drift app. (\autoref{sec:mon:drift}), 1 = Boris Push (\autoref{sec:mon:boris}) \\ BORIS\_T & \num{{}e-9} & Step width for Boris Push in \si{\second} \\ \midrule BFIELD & 2.5 & $B$ in T in $z$ \\ T2\_MAXDENS & \num{5e21} & Peak density at $z=5$ \\ TEMP & 30 & Constant temperature of the \ac{wgts} \\ T2\_VELO & -1 & -1 = data from \cite{Kuckert:2018aa}, else const $v$ in $z$ in \si{\meter \per \second} \\ \midrule INJECTION & 0 & 0 = $\upbeta$-decay, 1 = Delta, 2 = MB \\ INJ\_E & & Injection energy in \si{\eV} \\ INJ\_TI & 1 & ion generation by decay, 0= off, 1= on \\ \midrule TERM\_E & \num{{}e-7} & Energy threshold for terminating particles \\ TERM\_DI\_E & 0 & Energy threshold for electron termination at $z=10$ \\ TERM\_MAX & \num{{}e6} & Maximum number of interactions before termination \\ \midrule eT2\_ELA & 1& elastic scattering - 0: off, 1: on \\ INT\_ELA\_DIR & 0 & \acs{dcs} model for ela. sca. - 0: from \cite{Salvat:2005aa}, 1: $4\pi$, 2: $0 \pi$ \\ eT2\_ION & 1& ionization - 0: off, 1: model from \cite{Janev:2003aa}, 2: model from \cite{Kim:1994aa} \\ eT2\_ROT & 1& rot. exc. - 0: off, 1: unimplemented, 2: from \cite{Yoon:2008aa} \\ eT2\_VIB & 1& vib. exc. -0: off, 1: from \cite{Janev:2003aa}, 2: from \cite{Yoon:2008aa} \\ eT2\_EL & 1 & \ce{T2} el. exc. - 0: off, 1: from \cite{Janev:2003aa}, 2: from \cite{Yoon:2008aa} \\ eT2\_REC & 1 & recombination - 0: off, 1: on \\ \midrule INT\_N & 100& Number of points for numeric integration \\ INT\_PRE\_START & \num{{}e-7} & Start energy for precomputed \ac{tcs} in \si{\eV} \\ INT\_PRE\_END & \num{{}e0} & End energy for precomputed \ac{tcs} in \si{\eV} \\ INT\_PRE\_N & \num{{5}e3} & Number of precomputed \ac{tcs} values \\ \midrule POP\_N\_R & 5 & Number of $r$-bins for density fields \\ POP\_N\_PHI & 1 & Number of $\varphi$-bins for density fields \\ POP\_N\_Z & 13 & Number of $z$-bins for density fields \\ POP\_N\_E & 50 & Number of energy bins for density fields \\ POP\_E\_START & \num{{}e-7} & Minimum energy for kinetic density fields \\ POP\_E\_END & \num{{2}e4} & Maximum energy for kinetic density fields \\ \bottomrule \end{tabular} \end{table} %\begin{equation} %w_{v_1}(v2, \vartheta) = \frac {\sigma(v2, \vartheta)} {\int \upd v_2 \int_0^\pi f(v_2, \vartheta) \sigma(v_2, \vartheta)} %\end{equation}