The PENELOPE Physics Models and Transport Mechanics. Implementation into Geant4

A translation of the penelope physics subroutines to C++, designed as an extension of the Geant4 toolkit, is presented. The Fortran code system penelope performs Monte Carlo simulation of coupled electron-photon transport in arbitrary materials for a wide energy range, nominally from 50 eV up to 1 GeV. Penelope implements the most reliable interaction models that are currently available, limited only by the required generality of the code. In addition, the transport of electrons and positrons is simulated by means of an elaborate class II scheme in which hard interactions (involving deflection angles or energy transfers larger than pre-defined cutoffs) are simulated from the associated restricted differential cross sections. After a brief description of the interaction models adopted for photons and electrons/positrons, we describe the details of the class-II algorithm used for tracking electrons and positrons. The C++ classes are adapted to the specific code structure of Geant4. They provide a complete description of the interactions and transport mechanics of electrons/positrons and photons in arbitrary materials, which can be activated from the G4ProcessManager to produce simulation results equivalent to those from the original penelope programs. The combined code, named PenG4, benefits from the multi-threading capabilities and advanced geometry and statistical tools of Geant4.


INTRODUCTION
Monte Carlo simulation has become the tool of choice for describing the transport of radiation through matter. The general-purpose code system PENELOPE 1 [1,2] provides a reliable description of the coupled transport of electrons and photons in a wide energy range, nominally, from 50 eV up to 1 GeV, which are the lower and upper limits of the interval covered by the interaction database. However, the approximations underlying the interaction models and the tracking algorithm are expected to be valid only for energies larger than about 1 keV. Therefore, the results from simulations of particles with energies less than this value should be considered as semi-quantitative. The code has been used in a variety of applications, including dosimetry, radiation metrology, radiotherapy, detector characterization, electron microscopy and microanalysis, and x-ray fluorescence. After more than 25 years of development guided by user needs and physics improvements, PENELOPE has become a robust and versatile simulation tool with unique capabilities in electron transport. Direct evidence of the reliability of the code was given by a series of benchmark comparisons of simulation results with a variety of absolute measurement data from the literature [3].
The PENELOPE code is programmed in Fortran, mostly in Fortran 77 with a few extensions of Fortran 90. The original programs are readable and well documented, with abundance of comments, and are accompanied by a detailed manual [2] where the physics models, particle tracking scheme, and numerical sampling methods are described. However the Fortran programs do not allow running parallel simulations (only a manual process is provided to run independent simulations in different processing units, with a summing program to collect the results in a single set of output files). In addition, the Fortran subroutines are difficult to link to other simulation codes. The C++ code presented here is a strict translation of the original Fortran subroutines, which can be linked to GEANT4 [4][5][6] so as to make the PENELOPE physics available as part of the GEANT4 toolkit, and to take advantage of the multi-threading capabilities and advanced geometry and statistical tools of GEANT4.
The subroutine package PENELOPE is designed as a generator of random electron-photon showers in material media of infinite extent. In the simulations, all position and direction vectors refer to a fixed orthogonal frame, the laboratory frame, which is implicitly set through the geometry definition. Lengths and energies are given in cm and eV, respectively. Occasionally, directions (unit vectors,d) are specified by giving their polar and azimuthal angles, θ and ϕ, respectively. We havê d (u, v, w) (sin θ cos ϕ, sin θ sin ϕ, cos θ), where u, v, w are the Cartesian components (direction cosines) of the vectord. The state of a transported particle is determined by its energy E, position coordinates, r (x, y, z), and the unit vector d in the direction of flight. The physics simulation subroutines generate each particle history as a random sequence of free flights and interactions. The length s of the free flight, the kind of interaction that occurs at the end of the flight, as well as the energy loss W and the angular deflection Ω (θ, ϕ) caused by that interaction, are sampled randomly from appropriate probability density functions determined by the differential cross sections of the active interaction processes. The type of particles that are transported is identified by the value of the integer label KPAR ( 1, electron; 2, photon; 3, positron). Each particle trajectory is simulated from its initial state (r, E,d) until its energy becomes less than the corresponding absorption energy E abs (KPAR) selected by the user, where the simulation of the trajectory terminates. Secondary particles with energies larger than E abs (KPAR) may be released in interactions (other than Rayleigh scattering of photons and elastic scattering of electrons and positrons), as well as in the relaxation of atoms following inner-shell ionization (x-rays and Auger electrons). Secondary particles are initially stored in a LIFO (last-in-first-out) stack, and they are simulated after completion of the current particle trajectory.
The present article is organized as follows. The physics interaction models implemented in PENELOPE are briefly described in Section 2. Section 3 deals with the generation of electron-photon showers. Photons are simulated by means of the conventional detailed (i.e., interaction-by-interaction) method. The tracking of electrons and positrons is performed by means of a flexible class-II (mixed) algorithm, which is tuned by a small number of user-defined simulation parameters. The algorithm is tailored to optimize accuracy (i.e., consistency with detailed simulation) and stability under variations of the simulation parameters. Since the PENELOPE approach has clear advantages in front of the condensed multiplescattering schemes adopted in most general-purpose Monte Carlo codes, we present a detailed formulation of the class-II algorithm, which is extensible to simulate the transport of charged particles other than electrons and positrons. The C++ version of the PENELOPE classes and their linking to GEANT4 are described in Section 4. Sample simulation results are presented in Section 5, where we also verify the consistency of the integration of PENELOPE into GEANT4 with the original Fortran programs. Finally, in Section 6 we give a few concluding comments.

INTERACTION MODELS
The materials where radiation propagates are assumed to be amorphous, homogeneous and isotropic. PENELOPE describes the relevant interactions of transported particles by means of the corresponding differential cross sections (DCSs). In a typical collision measurement, projectile particles with energy E moving in the directiond ẑ impinge on the target and, after the interaction, they emerge with energy E − W in the direction d′ defined by the polar and azimuthal scattering angles θ and ϕ, respectively. The quantity W is the energy transfer in the interaction. Each interaction process (int) is defined by its "molecular" DCS per unit energy transfer and per unit solid angle, where σ int (E) is the total cross section, and p int (E; W, θ, ϕ) is the normalized joint probability density function of the energy transfer and the scattering angles θ and ϕ. Because of the assumed isotropy of the medium, the DCSs are generally independent of the azimuthal angle; the only exceptions are the DCSs for interactions of polarized photons. For simulation purposes, it is convenient to replace the polar angle θ with the variable which varies from 0 (θ 0) to 1 (θ π). Notice that the element of solid angle is dΩ sin θ dθ dϕ 2 dμ dϕ. The DCS, per unit energy transfer and per unit deflection is then The last expression is valid only when scattering is axially symmetric, in which case the azimuthal angle is a random variable uniformly distributed in [0, 2π). The mean free path between interactions is N is the number of molecules per unit volume, given by where N A 6.022 141 29 × 10 23 g/mol is Avogadro's number, ρ is the mass density (g/cm 3 ), and A m is the molar mass (g/mol) of the material. The inverse mean free path λ −1 int N σ int gives the interaction probability per unit path length of the projectile.
The interaction models implemented in PENELOPE combine results from first-principles calculations, semi-empirical formulas and evaluated databases. The DCS of each interaction mechanism is either defined numerically or given by an analytical formula with parameters fitted to relevant theoretical or experimental information. PENELOPE uses the most accurate physics models available that are compatible with the intended generality of the code.
Most of the physics models pertain to interactions with free atoms or with single-element materials. In the case of a compound (or mixture), the molecular DCS is obtained by means of the independent-atom approximation (i.e., as the sum of DCSs of the atoms in a molecule). This approximation is expected to be valid whenever the de Broglie wave length of the radiation is much shorter than typical inter-atomic distances in the material. Inelastic collisions of charged particles are peculiar in that they are dominated by excitations of weakly bound electrons and, hence, they are strongly affected by the state of aggregation of the material. The DCS for inelastic collisions is obtained from an analytical model with parameters determined by the mass density ρ and the mean excitation energy I of the material, the central parameter in the Bethe stopping power formula [7,8]. Empirical I values of materials [9] are used, so as to account approximately for the aggregation state of the material. The PENELOPE code system includes an extensive database of atomic DCSs and total (integrated) cross sections, for all elements in the periodic system, from hydrogen (Z 1) to einsteinium (Z 99), covering the energy range from 50 eV to 1 GeV. In the following Subsections we give a brief description of the interaction models adopted for photons and electrons/positrons. Further details on the physics models, and a thorough description of sampling methods for the different interaction mechanisms, are given in the PENELOPE manual [2]. References to the underlying theory and calculations can also be found in the review article by Salvat and Fernández-Varea [10].

Photon Interactions
The considered interactions of photons and the corresponding physics models are: • Rayleigh scattering (Ra). The DCS for the coherent scattering of unpolarized photons by atoms is a function of the polar angle θ of the direction of the scattered photon. It is expressed as the product of the Thomson DCS (which describes the scattering of electromagnetic waves by free electrons at rest) and the squared modulus of the atomic form factor plus angle-independent anomalous scattering factors [11]. The atomic form factors and the total (integrated) atomic cross sections are taken from the LLNL Evaluated Photon Data Library [12]. The direction of the scattered photon is sampled from the DCS in the form-factor approximation, i.e., disregarding the anomalous scattering factors. • Compton scattering (Co). The atomic DCS for the incoherent scattering of photons by atoms depends on the direction and energy E′ of the scattered photon. It is calculated from the relativistic impulse approximation with analytical one-electron Compton profiles [13] that approach the numerical Hartree-Fock Compton profiles given by Biggs et al. [14]. This approximation accounts for the effect of electron binding and Doppler broadening in a consistent way. The total atomic cross section is obtained as the sum of contributions of the various electron subshells.
In the case of conductors, conduction electrons are assumed to behave as a degenerate electron gas having the electron density of the conduction band. The DCS for Compton scattering is a function of the energy transfer W E − E′ and the polar angle θ of the direction of the scattered photon. • Photoelectric absorption (ph). The photoelectric effect is described by using total atomic cross sections, and partial cross sections for the K shell and L, M, and N subshells of neutral atoms, which were calculated by using conventional first-order perturbation theory [15]. In these calculations (as well as in those of impact ionization by electron and positron impact, see below), atomic wave functions are represented as single Slater determinants built with oneelectron orbitals that are solutions of the Dirac equation for the Dirac-Hartree-Fock-Slater self-consistent potential [16,17]. The cross sections in the database account only for ionization, i.e., contributions from excitations of atoms to discrete bound energy levels are disregarded. Additionally, the photon energy was shifted slightly so that the shell ionization thresholds coincide with the electron binding energies recommended by Carlson [18], which were obtained from a combination of experimental data and theoretical calculations. Our cross sections practically coincide with those in the LLNL Evaluated Photon Data Library [12], although they are tabulated in a denser grid of energies to accurately describe the structure of the cross section near absorption edges. A screening normalization correction, initially proposed by Pratt [19] is included. The initial direction of photoelectrons is sampled from Sauter's K-shell hydrogenic DCS [20], which is a function of the polar angle θ of the direction of the emitted photoelectron. • Electron-positron pair production (pp). The total atomic cross sections for pair (and triplet) production were obtained from the XCOM program of Berger et al. [21]. The initial kinetic energies of the produced particles are sampled from the Bethe-Heitler DCS for pair production, with exponential screening and Coulomb correction, empirically modified to improve its reliability for energies near the pair-production threshold. This DCS is a function of the kinetic energy of the electron, E − ; the energy of the positron is determined by energy conservation.
The total cross section for each of these processes is obtained by integration of its DCS, over the corresponding variables. The total molecular cross section, σ tot , is the sum of contributions, The length s of each photon free flight is sampled from the familiar exponential distribution where is the attenuation coefficient (i.e., the inverse mean free path) for photons of energy E. Partial and total mass attenuation coefficients, μ at /ρ, of carbon and mercury are displayed in Figure 1. PENELOPE can also simulate Rayleigh and Compton scattering of polarized photons, with the state of polarization described by means of the Stokes parameters [2]. The polarization of photons does not alter neither the total cross sections nor the distributions of polar angles (see, e.g., Ref. [2]), but the distribution of azimuthal angles ceases to be uniform. Characteristic x rays and bremsstrahlung photons emitted by electrons or positrons, as well as positron annihilation quanta, are assumed to be unpolarized.

Electron and Positron Interactions
The interactions of electrons and positrons considered in PENELOPE are: • Elastic collisions (el). The DCSs for elastic collisions of electrons and positrons were calculated numerically by running the program ELSEPA [22,23] which uses the relativistic Dirac partial-wave expansion method for the electrostatic potential of the target atom obtained from Dirac-Fock atomic electron densities [24,25], with the exchange potential of Furness and McCarthy [26] for electrons. Figure 2 displays DCSs from the ELSEPA database for elastic scattering of electrons and positrons by carbon and mercury atoms. These plots illustrate the variation of the DCS with the atomic number Z, the charge of the projectile, and the energy E. • Inelastic collisions (in). Interactions involving electronic excitations of the medium are simulated on the basis of the plane-wave Born approximation with the Sternheimer-Liljequist generalized oscillator strength model [27,28]. The model is designed to simplify the simulation of inelastic collisions and to facilitate the calculation of the densityeffect correction. The excitation spectrum is modeled as a discrete set of delta oscillators. Each oscillator represents excitations of an electron subshell, its strength is set equal to the number of electrons in that subshell and its resonance energy is proportional to the subshell binding energy. The proportionality constant is the same for all subshells, and it is determined from the requirement that the generalized oscillator strength model reproduces the empirical value of the mean excitation energy I recommended in the ICRU Report 37 [9]. This procedure ensures that the stopping powers calculated from this model agree closely with the tabulated values in the ICRU Report 37. To smear out the  [29] by means of the distorted-wave (first) Born approximation with the Dirac-Hartree-Fock-Slater self-consistent potential (see also Ref. [30]), multiplied by an energy-dependent factor that accounts for the densityeffect correction. The energy loss and the momentum transfer in ionizing collisions are sampled from the distribution given by the Liljequist-Sternheimer model. The total cross sections of outer subshells are renormalized to keep the value of the stopping power unaltered. This approach yields the correct number of ionizations per unit path length, without altering substantially the modeling of inelastic collisions. • Bremsstrahlung emission (br). The energy W of the emitted photon is set equal to the energy loss of the projectile. It is sampled from numerical energy-loss spectra obtained from the scaled cross-section tables of Seltzer and Berger [31,32]. The intrinsic angular distribution of emitted photons is described by an analytical expression -an admixture of two "boosted" dipole distributions- [33] with parameters determined by fitting a set of 910 angular distributions calculated with the program of Poškus [34], which extends the previously available calculation of Kissel et al. [35]. PENELOPE assumes that elastic collisions account for all angular deflections of the particle trajectory caused by the atomic field and, consequently, that radiative events do not modify the direction of the electron or positron. • Positron annihilation (an). In the simulation of positron annihilation the target electrons are assumed to be at rest. The process is described by the Heitler DCS [36,37] for inflight annihilation with emission of two photons of energies E − and E + , with E − ≤ E + , which add to E + 2m e c 2 , where m e is the rest mass of the electron and m e c 2 ≃ 511 keV its rest energy. The Heitler DCS is a function of the energy E − of the less energetic photon. The directions of the two photons are determined by energy and momentum conservation. When the energy of a positron is less than its absorption energy, E abs (3), it is assumed to annihilate with emission of two photons of energy equal to m e c 2 with opposite directions.
The DCSs for these interaction mechanisms, are functions of the angular deflection μ (1 − cos θ)/2 and/or the energy loss W, or the photon energy E − . The corresponding total cross sections are obtained by integration of these DCSs over the allowed intervals of the relevant variables. The mean free path λ of electrons and positrons is where with the annihilation term present only for positrons. Elastic scattering is characterized by the mean free path, and the transport mean free paths, λ el,ℓ , defined by where P ℓ ( cos θ) are Legendre polynomials with the argument cos θ 1 − 2μ. The inverse first and second transport mean free paths can be expressed as and where the notation 〈. . . 〉 1 indicates the average value in a single collision. λ −1 el,1 gives a measure of the average angular deflection per unit path length; by analogy with the stopping power (see below), the quantity 2λ el,1 is sometimes called the scattering power 2 . Figure 3 shows elastic mean free paths and transport mean free paths for electrons in carbon and mercury. For energies larger than about 10 keV, when E increases the DCS becomes strongly peaked in the forward direction. In the high-energy limit, scattering is preferentially at small angles (with sin θ ≃θ) and λ el,2 ≃ λ el,1 /3.
The mean free path λ in between inelastic collisions is The total cross section for bremsstrahlung emission is infinite because the corresponding DCS diverges as W −1 at W 0 (see Ref. [10] and references therein). A fundamental quantity in transport studies is the stopping power S ( average energy loss per unit path length), given by where the terms in square brackets are the energy-loss DCSs for inelastic collisions and bremsstrahlung emission, respectively. Relatively small energy transfers also occur in elastic collisions, which manifest as the recoil of the target atom or as phonon excitations, and give rise to the so-called nuclear stopping power. PENELOPE disregards the energy loss in elastic events because the nuclear stopping power is typically four orders of magnitude smaller than S. Another relevant quantity is the energy-straggling parameter ( increase of the variance of the energy distribution per unit path length) given by We notice that the contributions from inelastic collisions to the stopping power and to the energy-straggling parameter can be expressed as respectively, where 〈W n 〉 1 denotes the average value of W n in a collision. Figure 4 displays the mean free path of inelastic FIGURE 3 | Elastic mean free path, λ el , and first and second transport mean free paths, λ el,1 and λ el,2 , for electrons scattered in carbon and mercury as functions of the kinetic energy of the projectile.
collisions and the stopping power for electrons in carbon and mercury, together with the collision and radiative contributions to the stopping power.

Atomic Relaxation
PENELOPE simulates the emission of characteristic x rays and Auger electrons with energies larger than E abs (KPAR) that result from vacancies produced in the inner subshells of atoms by photoelectric absorption and Compton scattering of photons and by electron or positron impact. The relaxation of excited ions is simulated as a sequence of transitions in which vacancies move towards the outer subshells by emission of Auger electrons and x rays; the relaxation process is followed until all vacancies have moved to subshells with binding energies less than a certain value E cut , which is determined by the absorption energies of electrons and photons. The adopted transition probabilities, as well as the energies of Auger electrons, were extracted from the LLNL Evaluated Atomic Data Library [38]. The energies of K and L x-ray lines are taken from the review of Deslattes et al. [39], while those of M and N lines are from Bearden's compilation [40]. X rays and electrons are emitted in random directions sampled from the isotropic distribution.

GENERATION OF RANDOM ELECTRON-PHOTON SHOWERS
A detailed description of the sampling algorithms used to simulate the various interactions from their associated DCSs is given in the PENELOPE manual [2]. Most continuous distributions are sampled numerically by means of the adaptive algorithm RITA (Rational Inverse Transform with Aliasing); Walker's aliasing method [41] is utilized to sample discrete distributions with large numbers of possible outcomes. The adopted sampling methods are both fast and robust. The simulation of photons follows the usual detailed procedure, where all interaction events in a photon history are simulated in chronological succession. The physics simulation subroutines set the distance s from the current position r to the next interaction, assuming the medium is infinite, by random sampling from the exponential distribution defined in Eq. 10. The program then propagates the photon the distance s along the ray, i.e., to a position r + sd, where the next interaction takes place. In Rayleigh and Compton scattering, the photon is absorbed and a second photon is emitted with energy E′ (equal to or less than E). When E ′ > E abs (2), the surviving photon is followed by repeating these steps. That is, a photon history represents the evolution of the primary photon and its descendants resulting from Compton and Rayleigh interactions. Photoabsorption and pair production terminate the photon history. Each photon history consists of a sequence of a relatively small number ( ≲ 10) of free flights and interactions, which can be simulated rapidly.
The simulation of electron and positron histories is more difficult because of the large number of interactions these particles undergo before being brought to rest. On average, an electron looses a few tens of eV at each individual interaction. Therefore, detailed simulation of electrons and positrons is feasible only in situations where the number of interactions is sufficiently small, that is, for energies up to about 50 keV, and for particles with higher energies traveling through thin material foils. To cope with this difficulty, charged particles are usually tracked by using condensed simulation schemes (class-I schemes in the terminology of Berger [42]) which consist in decomposing each particle trajectory into a number of steps (either of fixed or random lengths), and the global effect of all the interactions that occur along each step is described approximately by using Frontiers in Physics | www.frontiersin.org December 2021 | Volume 9 | Article 738735 multiple scattering theories. Because these theories apply to homogeneous infinite media, a limitation of class-I schemes occurs when a particle is close to a material interface: the step length must then be kept smaller than the distance to the nearest interface, to prevent the particle from entering the next medium. Therefore, in class-I simulations the geometry subroutines must keep control of the proximity of interfaces. The practical alternative are class-II schemes [42], also called mixed schemes, which take advantage of the fact that the DCSs for interactions of high-energy charged particles are rapidly decreasing functions of the energy loss W and the polar scattering angle θ. Consequently, cutoffs W c and θ c can be set so that the number of "hard" interactions (i.e., interactions with energy loss or polar scattering angle larger than the corresponding cutoffs) that occur along each particle history is small enough to allow their individual simulation by random sampling from the corresponding restricted DCSs. The accumulated angular deflection caused by all soft interactions (with sub-cutoff energy transfers or angular deflections) that occur along a trajectory step between two successive hard interactions can be described by means of a multiplescattering approach consistent with the DCSs restricted to soft events. The energy loss caused by soft interactions along the step can be obtained from a simple distribution having the exact first and second moments, as calculated from the energy-loss DCS restricted to soft interactions.
Class-II schemes are more accurate than purely condensed simulation because: 1) hard events are simulated exactly from the corresponding restricted DCSs, and 2) multiple scattering approximations have a milder effect when applied to soft interactions only. A further advantage of these schemes is that the tracking algorithm only requires computing intersections of particle rays (straight lines) with interfaces, instead of having to control the distances to the interfaces. In addition, class-II schemes allow verifying the stability of simulation results under variations of the cutoffs, as well as the accuracy of the multiple-scattering approximations adopted for describing the soft interactions. The only disadvantage of class-II schemes is that they require a more elaborate coding of the simulation program, and somewhat larger look-up tables.

Simulation of Electron and Positron Trajectories
PENELOPE describes the transport of electrons and positrons by means of an elaborate class-II scheme, with fixed energy-loss cutoffs and an energy-dependent angular cutoff θ c for elastic collisions, which is set internally by the program in terms of two user-defined simulation parameters. Particle trajectories are generated by using the random-hinge method [53], which operates similarly to detailed simulations, i.e., the transported particle is moved in straight "jumps," and the energy and direction of movement change only through discrete events (hard interactions and hinges). With the appropriate set of DCSs, the method is applicable to any charged particle; class-II simulations of protons with the random-hinge method have been reported by Salvat and Quesada [54,55].

Interactions With Energy Loss
Electrons and positrons lose energy through inelastic collisions and bremsstrahlung emission. These interactions are classified by the respective cutoff energy-loss values, W cc and W cr , which are assumed to be independent of the energy of the projectile. Interactions with energy loss W larger than the corresponding cutoff are considered as hard interactions and are simulated individually by sampling from the corresponding restricted DCSs. The slowing down caused by soft interactions is described by the restricted stopping power, and the restricted energy straggling parameter, A difficulty of class-II algorithms arises from the fact that the energy of the particle decreases along the step between two consecutive hard interactions. Because the cutoff energies W cc and W cr do not change with E, we can assume that, at least for small fractional energy losses, the DCSs for soft energy-loss events vary linearly with E. Under this assumption we can calculate the first moments of the distribution of the energy loss W s of a particle with initial energy E 0 after traveling a path length s under only the influence of soft events [2]. The mean and variance of this distribution are, respectively, where the factors in curly braces account for the global effect of the energy dependence of the soft energy-loss DCS, within the linear approximation.
In practical simulations, the energy loss W s due to soft interactions along a path length s is sampled from a distribution, P(W s ), that has the mean and variance of the actual energy-loss distribution, as given by Eqs. 25 〈W s 〉 2 ≫ var(W s ), and the cutoff energy losses W cc and W cr are much smaller than 〈W s 〉, the central limit theorem implies that the actual energy-loss distribution is nearly Gaussian. Unfortunately, this is not true for small path lengths, which correspond to small W s , and one must rely on artificial distributions. In PENELOPE the distribution P(W s ) has different forms, depending on the ratio where σ [var(W s )] 1/2 is the standard deviation of W s . Specifically, we consider the following cases.
• Case I. If X > 3, the energy loss is sampled from the truncated Gaussian distribution (normalisation is irrelevant here), where the numerical factor 1.015387 corrects the standard deviation for the effect of the truncation. Notice that the shape of this distribution is very similar to that of the "true" energy-loss distribution.
• Case II. When 3 1/2 < X < 3, we use the uniform distribution 3 and • Case III. Finally, when X < 3 1/2 , the adopted distribution is an admixture of a delta distribution and a uniform distribution, W s,max is normally much less than the kinetic energy E 0 of the transported particle. Energy losses larger than E 0 might be generated only when the step length s has a value of the order of the continuous slowing down approximation (CSDA) range, but this never happens in practical simulation. Despite the artificial shapes of the distributions given by Eqs 26, after a moderately large number of short steps, the distribution of the accumulated energy loss has the correct first and second moments and is similar in shape to the "true" distribution for soft interactions only, which is nearly Gaussian. Further improvements of the distribution of soft-energy losses would require considering higher order moments of the energy-loss in single interaction events.

Elastic collisions
Angular deflections of the particle trajectories are mostly caused by elastic collisions with the atoms of the material. To analyze the cumulative effect of multiple interactions, let us consider an electron that starts from the origin of coordinates moving in the direction of the z axis with energy E. Let θ m and (x, y, z) denote the polar angle of the direction of motion and the position coordinates of the electron after traveling a path length s. Under the assumption that energy losses are negligible, the multiple-scattering theories of Goudsmit and Saunderson [56] and Lewis [57] provide exact expressions for the angular distribution, p(μ m ) with μ m (1 − cos θ m )/2, which are determined by the so-called transport mean free paths λ el,ℓ , Eq. 16. In addition, the Lewis theory for pure elastic scattering gives exact analytical expressions for the average values 〈 cos θ m 〉, 〈 cos 2 θ m 〉, 〈z〉, 〈z cos θ m 〉, 〈z 2 〉, and 〈x 2 + y 2 〉. These quantities are completely determined by the values of the transport mean free paths λ el,1 and λ el,2 .
In PENELOPE the cutoff deflection μ c , which separates hard and soft elastic collisions, varies with the energy E in a way that ensures that the simulation becomes purely detailed at low energies, where elastic scattering is more intense. The cutoff deflection is determined by two energy-independent user parameters, C 1 and C 2 , which typically should be given small values, between 0 and 0.1. These two parameters are used to fix the mean free path between hard elastic events (i.e., the average step length between consecutive hard elastic collisions), which is defined as where λ el,1 is the first transport mean free path, and S is the stopping power due to both inelastic collisions and bremsstrahlung emission, Eq. 20. The equation then fixes the cutoff μ c as a function of the energy E of the projectile. The average angular deflection of the electron 3 The normalized uniform distribution in the interval (a, b), with a < b, is Frontiers in Physics | www.frontiersin.org December 2021 | Volume 9 | Article 738735 trajectory at the end of a step of length λ (h) el can be evaluated from Lewis' theory [57] which, ignoring energy losses along the step, gives That is, C 1 defines an approximate upper limit for the cumulative average angular deflection along step. On the other hand, the average energy loss along the step is so that C 2 sets a limit to the average fractional energy loss along the step. An increase of C 1 or C 2 leads to increased values of both the mean free path between hard events, λ (h) el , and the cutoff deflection, μ c , in certain energy ranges [2]. Of course, an increase of λ (h) el implies a reduction in the number of hard events along a particle track with an accompanying reduction of the simulation time.
It should be noted that C 1 and C 2 act within different energy domains. This is illustrated in Figure 5, where the lengths λ el , λ el,1 and E/S for electrons in carbon and mercury are represented as functions of the kinetic energy. The mean free path λ (h) el for hard elastic events, determined from the formula (28) with C 1 C 2 0.05 is also plotted. For low energies, λ (h) el λ el and the simulation is purely detailed (μ c 0). For intermediate energies, λ (h) el C 1 λ el,1 , whereas λ (h) el C 2 E/S in the high-energy domain. From Figure 5 it is clear that increasing the value of C 2 does not have any effect on the simulation of electron tracks with initial energies that are less than about 1 and 10 MeV for carbon and mercury, respectively.
The justification for the recipe (28) is that it automatically forces detailed simulation (μ c 0) at low energies, where elastic scattering dominates. In addition, when the energy increases, the portion of elastic collisions that are hard, ∝ λ el /λ (h) el , reduces gradually, being much less than unity at high energies, where scattering is preferentially at small-angles. Assuming negligible energy losses, the angular distribution produced by the soft elastic collisions along a path length s is [57] where μ s ≡ (1 − cos θ s )/2 is the accumulated deflection, and λ (s) el,ℓ are the transport mean free paths for the soft interactions, The DCS for soft elastic events has a discontinuity at μ c , which implies that for small path lengths the Legendre series (32) does not converge with a finite number of terms. Therefore, it is impractical to sample the multiple-scattering deflection μ s from the distribution F s (s; μ s ).
It is important to notice that soft inelastic collisions also cause a small deflection of the projectile. The scattering effect of these interactions is accounted for by considering their contributions to the soft transport mean free paths, The combined (elastic plus inelastic) soft scattering process is then described by the transport mean free paths Assuming that the energy loss is small, the first and second moments of the angular deflection after a path length s, under In practical simulations the angular deflection μ s after a path length s is sampled from an artificial distribution, P(μ s ), which is required to have the same moments, of orders n 1 and 2 as the real distribution, Eqs 36, but is otherwise arbitrary. In our programs we use the following where U(a, b; x) denotes the normalised uniform distribution in the interval (a, b). The parameters obtained by requiring the aforesaid conditions are and This simple distribution is flexible enough to reproduce the combinations of first and second moments encountered in the simulations [notice that 〈μ s 〉, Eq. (36a), is always less than 0.5] and allows fast random sampling of the deflection μ s .

Random-Hinge Method
As indicated above, hard interactions are simulated individually according to their restricted DCSs. Assuming that the energy loss due to soft collisions is small, the distance s traveled by an electron with initial energy E from its current position r to the next hard collision can be sampled from the familiar exponential distribution, with the total mean free path λ (h) T given by 1 That is, random values of s can be generated by using the sampling formula where ξ is a random number uniformly distributed in (0,1). Because of the effect of soft interactions, the kinetic energy of the transported particle varies along the step between two hard interactions. The accumulated angular deflection caused by all soft interactions that occur along a trajectory step is simulated as if it were caused by a single artificial event (a hinge), which occurs at a random position within the step. The energy loss along the step and the polar angular deflection at the hinge are sampled from approximate multiple-scattering distributions that have the correct means and variances, Eqs 25, 36, which are calculated beforehand from the DCSs restricted to soft interactions [2]. Unfortunately, the multiple-scattering theories do not provide enough information to determine the spatial distribution and the correlation between the direction and the position of the electron at the end of a step. The only characteristics readily available are the low-order moments given by the theory of Lewis.
The energy loss W s and the angular deflection μ s caused by multiple soft interactions along the step are sampled from artificial distributions, which are required to preserve the moments given by Eqs 25 and 36. Other details of these distributions are irrelevant, provided only that the fractional energy loss, 〈W s 〉/E, and the average soft deflection, 〈μ s 〉, in each step are small [1,2]. A convenient feature of the adopted energy-loss distributions, which will be helpful below, is that they permit energy transfers up to a well defined maximum value W s,max , Eq. 27, determined by the kinetic energy E of the projectile and the step length s.
In PENELOPE, the angular deflection and the space displacement due to multiple soft collisions along the path length s are described by means of the random-hinge method [53], which operates as follows ( Figure 6). Thus, each step s is simulated as a sequence of two trajectory segments. With this tracking algorithm, the code operates as in detailed simulations, i.e., the transported particle moves freely in straight trajectory segments, and the energy and direction of movement change only through discrete events (hard interactions and hinges). This strategy simplifies the simulation of transport in complex material structures consisting of homogeneous bodies with welldefined interfaces. When the electron crosses an interface, we only have to halt it at the crossing point, and resume the simulation in the new material. Because the distance τ to the hinge is distributed uniformly in (0, s), the particle reaches the interface with nearly correct average energy and direction [2]. We point out that this tracking scheme only requires computing intersections of particle rays and interfaces. In the case of a generic quadric surface, this is accomplished by solving a quadratic equation. The easiness of the ray-tracing method is at variance with class-I schemes, which require calculating the distance to the nearest interface at the beginning of each step; in the case of a quadric surface the calculation of that distance involves finding a root of a polynomial of up to 6th degree [58].
In spite of its simplicity, the random-hinge method competes in accuracy and speed with other, more sophisticated transport algorithms [59,60]. Comparison of results from detailed and class-II simulations of electrons in an infinite medium [2] shows that the randomness of the hinge position leads to correlations between the angular deflection and the displacement that are close to the actual correlations. It is also worth noting that the possible positions of the next hard interaction fill the sphere of radius s centered at r, the beginning of the step.
It is convenient to consider that the energy W s is lost at a constant rate along the step, i.e., as in the CSDA with an effective stopping power S soft W s /s. In previous versions of PENELOPE, the energy loss W s was deposited at the hinge. This yielded an artifact in the depthdose distribution, which does not occur when the energy loss is distributed uniformly along the step [2]. The use of the CSDA instead of assuming a discrete loss at the hinge also reduces statistical uncertainties in the simulated distributions of fluence with respect to energy. In addition, the CSDA permits accounting for the reduced energy loss in segments that are truncated at interfaces: the energy of the electron at the intersection is E 0 − s′S soft , where E 0 denotes the energy at the beginning of the segment and s′ is the length of the segment before the interface.
A further advantage of considering that soft energy-loss interactions slow down electrons with constant stopping power is that the calculation of flight times is trivial. Consider an electron with initial energy E 0 , subject to the stopping power S soft . The time in which the electron moves along a trajectory segment of length s′ is given by Inserting the relativistic expression of the velocity, The integral is elementary and gives where c is the speed of light in vacuum.

Variation of λ (h) T With Energy
Due to soft energy-loss interactions, the energy of the transported particle decreases along the step in an essentially unpredictable way. This implies that the mean free path λ (h) T (E) also changes along a single step. Consequently, the sampling formula (40) is incorrect (this formula is valid only when the energy remains constant along the step). Figure 7 shows the inverse mean free path (interaction probability per unit path length) for hard interactions of electrons in carbon and mercury evaluated by PENELOPE for various values of the simulation parameters C 1 and C 2 , all with W cc W cr 100 eV. Generally, when the energy increases, the inverse mean free path for hard events decreases monotonically at low energies, has a broad minimum, and then increases slowly to saturate at high energies. Note that, by varying the values of C 1 and C 2 , the inverse mean free path cannot be made smaller than the contributions from hard inelastic and radiative events. Hence, at high energies, the value λ (h) (E) is determined by the cutoff energies W cc and W cr .
To account for the variation of λ (h) T (E) with energy, and also to facilitate the simulation of electrons and positrons in electromagnetic fields, the user may set a maximum step length, s max . By default PENELOPE uses the value s max 4λ (h) T . Let E 0 be the kinetic energy of the electron at the beginning of the step. As the adopted energy-loss distributions are such that the energy loss W s in steps of length s ≤ s max has an upper bound W s,max [see Eq. 27], the energy of the particle decreases along the step from E 0 to a value that is never less than E 0 − W s,max at the end of the step. We can then determine the minimum value λ T, min of λ (h) T (E) in the energy interval between E 0 − W s, max and E 0 , and consider that the particle can undergo delta interactions (i.e., fictitious events in which the energy and direction of the electron remain unchanged) with a mean free path λ δ (E) such that an (E) Because this sum is constant with E, we can sample the step length s from the exponential distribution with the mean free path λ T,min . When the sampled step length is larger than s max , the particle is moved a length s s max and a delta interaction is assumed to occur at the end of the step. The introduction of delta interactions does not affect the reliability of the simulation results because of the Markovian character of the transport process. Once the step length is determined, the soft energy loss W s is sampled from the distribution defined by Eqs 26, with the moments given by Eqs 25. The soft angular deflection μ s at the hinge is sampled from the distribution (38) with the moments (36) calculated at the energy E hinge E 0 − τS soft corresponding to the hinge (within the CSDA). On average, this is equivalent Frontiers in Physics | www.frontiersin.org December 2021 | Volume 9 | Article 738735 to assuming that the transport mean free paths λ (s) el,1 and λ (s) el,2 vary linearly with energy. When the sampled step length s is less than s max , the kind of event (hard or delta interaction) that occurs at the end of the step is sampled from the corresponding partial inverse mean free paths. The angular deflection and/or the energy loss at hard interactions is sampled from the corresponding restricted DCSs. The simulation of a particle ends when either its energy becomes lower than the predefined absorption energy, E abs (KPAR), or when it leaves the entire geometry.

Selecting the Simulation Parameters
The speed and accuracy of the simulation of coupled electronphoton transport is determined by the values of the simulation parameters E abs (KPAR), C 1 , C 2 , W cc , and W cr , which are selected by the user for each material in the simulated structure. Here we summarize the rules for assigning "safe" values to these parameters. The absorption energies E abs (KPAR) should be estimated from either the characteristics of the experiment or the required space resolution. The quantities to be considered are the desired resolution of energy-deposition spectra and the penetration distances of particles with these energies (i.e., photon mean free path and the residual ranges of electrons/ positrons). PENELOPE prints tables of mean free paths and particle ranges when the initialization method PEINIT is invoked with the input parameter INFO 3 or larger. For example, to calculate spatial dose distributions, the values E abs (KPAR) should be such that the penetration distances of particles with these energies are less than the typical dimensions of the volume bins used to tally the dose map. In other cases, it is advisable to run short simulations with increasing values of E abs (KPAR) (starting from 50 eV) to study the effect of these parameters on the results.
The use of different absorption energies in neighboring bodies may create visible artifacts in the space distribution of absorbed dose. For instance, if the values of E abs (1) for electrons in bodies 1 and 2 are, respectively, 10 and 100 keV, electrons entering body 2 from body 1 with E less than 100 keV will be absorbed at the first interaction, giving an excess of dose at the border of body 2. When the spatial distribution of absorbed dose is important, absorption energies should be given similar values over the region of interest. If the absorption energies of the three types of transported particles are given the same value in all the materials present, the simulated dose distribution is continuous when there is effective equilibrium of radiation with energy less than E abs (KPAR).
The random-hinge method for electrons and positrons is expected to work well when the accumulated effect (energy loss and angular deflection) of the soft interactions along a step is small. The cutoff energies W cc and W cr have a weak influence on the accuracy of the results provided that they are both smaller than the width of the bins used to tally energy distributions. It is worth recalling that the DCSs for inelastic collisions and bremsstrahlung emission decrease rapidly with the energy loss W (roughly as W −2 and W −1 , respectively). As a consequence, for particles with energies larger than about 100 keV, when W cc and W cr are increased, the simulation speed tends to a saturation value. For these high energies, the gain in speed is small when the cutoffs are made larger than about 5 keV. On the other hand, these cutoff energies have an effect on the energy-straggling distributions, which are faithfully described only when the number of hard interactions is "statistically sufficient." Therefore, the cutoff energies should not be too large. Our recommendation is to set the cutoff energies equal to one 100th of the typical energy of primary particles, or 5 keV, whichever is the smallest. Note that, for the sake of consistency, W cc should be smaller than the absorption energy of electrons in the material, E abs (1); otherwise, we would miss secondary electrons that have energies larger than E abs (1). Similarly, W cr should be less than the photon absorption energy E abs (2).
The allowed values of the elastic-scattering parameters C 1 and C 2 are limited to the interval [0,0.2]. Because the energy dependence of the cross sections for soft interactions and of the hard mean free paths is effectively accounted for (see Section 3.1), these two parameters have a very weak influence on the results. The recommended practice is to set C 1 C 2 0.05, which is fairly conservative. Before increasing the value of any of these parameters, it is advisable to perform short test simulations to verify that the results remain essentially unaltered when using the augmented parameter value (and that the simulation runs faster; if there is no gain in speed, keep the conservative values).
The parameter s max is the maximum allowed step length. Limiting the step length is necessary to account for the variation of the mean free path for hard events, λ (h) T , with the energy of the particle. The value of s max should be about, or less than one 10th of the characteristic thickness of the body where the particle is transported. This ensures that, on average, there will be more than 10 hinges along a typical electron/positron track through that body, which is enough to "wash out" the details of the artificial distributions used to sample these events. We recall that PENELOPE internally forces the step length to be less than 4λ (h) T . Therefore, for thick bodies (thicker than ∼ 10λ (h) T ), the average number of hinges along each track is larger than about 10, and it is not necessary to limit the length of the steps. If the slowing-down of the particle due to soft events is described as a continuous stopping process, external step control is not critical.
It is interesting to observe that when the parameters C 1 , C 2 , and W cc are set to zero, our class-II scheme becomes purely detailed (i.e., nominally exact) simulation of elastic and inelastic collisions. Bremsstrahlung emission cannot be simulated detailedly because its DCS diverges at zero photon energy (and, hence, the total cross section is infinite), although the radiative stopping power is finite. When the input value of W cr is negative, PENELOPE sets W cr 10 eV and disregards the emission of photons with lower energies, thus performing an almost detailed simulation of radiative events. A clear advantage of our class-II scheme is that its accuracy and stability under variations of the user parameters can be numerically verified by simply comparing the simulation results with those of a detailed simulation.

C++ CLASSES AND COUPLING TO GEANT4
Linking the PENELOPE physics and tracking subroutines to GEANT4 was not trivial because 1) PENELOPE transports electrons and positrons by using a class-II algorithm which operates differently to the tracking method used by GEANT4, and 2) PENELOPE builds its interaction models from a material database that is different from the one used by GEANT4. To ensure consistency, and to reduce the interference between the two transport modes, the PENELOPE tracking is allowed in a limited energy interval, which by default extends from E min 50 eV to E max 1 GeV. Electrons, positrons, and photons with energies higher than E max are followed by GEANT4 as ordinary particles. The user defines a threshold energy E thr , necessarily less than E max , at which the transported electron, positron or gamma is converted into a PENELOPE-type particle by cloning its state variables, and the remaining part of the history, until its completion, is generated by the PENELOPE classes. To prevent interfering with the GEANT4 logic, electrons, positrons, and photons passed to the PENELOPE classes are considered as particles of a special type (denoted as "pe-", "pe+", and "pgamma", respectively) different from the GEANT4 "ordinary" particles. In addition, secondary electrons, positrons, and photons released with initial energies less than E thr are directly tracked by the PENELOPE classes.
The C++ translation of the PENELOPE physics and transport subroutines is organized in two directories: penG4include and penG4src, which store the corresponding header and source files, respectively. The coupling of the two simulation codes is organized as follows: • The file penG4include/PenelopeDefines.hh includes the definitions of all the constants, global variables and globalscope methods. Similarly, common variables and namespaces are declared in penG4include/common-share.hh. • The C++ PENELOPE classes are organized into shared and thread-local sets according to the multi-thread design of GEANT4. Thus, the PENELOPE methods and data with threadlocal scope are declared in penG4include/local.h and defined in *.cpp files contained in the penG4src/ localSubs directory, whereas methods and data that are shared over threads are declared in penG4include/ share.h and implemented in files named *.cpp and placed in the penG4src/shareSubs/directory. • The classes PenInterface and PenPhys encapsulate the C++ PENELOPE classes. They constitute the "bridge" between PENELOPE and the classes of the GEANT4 application using them. • The class PenPhys encapsulates the PENELOPE physics functions that are called during the tracking of particles, and it works with the thread-local classes mentioned above. Its public methods are issued from the PenEMProcess class, which dictates the physics and tracking models that are applied and proposes changes in the state variables of the particle being tracked. • PenInterface is a singleton class which contains all the methods shared over threads. In the GEANT4 application, this class is used 1) to register each material in the DetectorConstruction class with its corresponding transport parameters EABS(1-3), C1, C2, WCC and WCR for tracking of "pe-", "pe+", and "pgamma" particles, and 2) to define the energy range (E min , E max ) where the PENELOPE tracking is applied. By default the code sets E min 50 eV and E max 1 GeV; these values can be set from the PenelopeEMPhysics constructor as indicated below. In addition, PenInterface is responsible for initializing the PENELOPE classes. The class design also allows the user to create user-interface commands to set the transport parameters for each material. • The remaining classes of the code interface define the PENELOPE-type particles being tracked by the GEANT4 application and the processes modeling their electromagnetic interactions with matter. The code defines three new particle types by using the G4ParticleDefinition constructor, which correspond to electrons, photons, and positrons that are tracked by PENELOPE and clone the static properties (rest mass, charge, etc.) of ordinary GEANT4 particles, • PenElectron for a PENELOPE-type electron, "pe-", • PenGamma for a PENELOPE-type photon, "pgamma", • PenPositron for a PENELOPE-type positron, "pe+".
Thus, during the same simulation we may use either G4Electron, G4Gamma and G4Positron and follow particles with ordinary GEANT4 electromagnetic physics, or PenElectron, PenGamma and PenPositron for tracking them with the PENELOPE physics and tracking.
As mentioned above, particles with energy E higher than E thr are tracked by GEANT4. When a particle (electron, photon, or positron) reaches a kinetic energy below E thr , it must be converted to the corresponding PENELOPE-type particle to switch the tracking to PENELOPE. With this purpose, two classes derived from G4VProcess were defined: • PenEMProcess is the wrapper class for the PENELOPE physics; it is only applicable to PENELOPE-type particles. All the changes of the particle state variables are proposed via the process PostStepDoIt(), i.e., in the same way as for discrete interactions. In addition, the PenInterface singleton is initialized within PenEMProcess::BuildPhysicsTable(), which in multi-thread mode is invoked once the GEANT4 execution gets initialized by, for instance, issuing (blank) run/initialize command in a macro file. • PenPartConvertProcess is the process responsible for converting a GEANT4-type particle into the equivalent PENELOPE-type particle once its kinetic energy falls below the threshold energy E thr . The value of E thr , which must be ≤ E max can be set by passing it as an argument of the PenPartConvertProcess constructor or using the SetThresholdEnergy() method. The class PenEMProcess is derived from G4VDiscreteProcess, it is of type fDecay and is only applicable to particles of types G4Electron, G4Gamma and G4Positron. It works by defining a special "decay" from the GEANT4 ordinary particle to its corresponding PENELOPE particle, keeping its dynamic properties (position, energy, direction of momentum, total time of flight. . .).
Notice that no process is defined to do the inverse conversion, i.e., we assume that once the PENELOPE mode is entered, it remains active until the end of the transported particle history. It is also important to point out that the GEANT4 production thresholds do not apply to the PENELOPE physics and tracking.
Finally, a physics constructor named PenelopeEMPhysics derived from the generic G4VPhysicsConstructor, has been written to ease the inclusion of PENELOPE physics into a GEANT4 application by using a modular physics list. The value E thr 500 keV is assumed by default; it can be modified by passing the desired value as argument of the G4PenelopeEMPhysics constructor. Moreover, E max can be set within the ConstructProcess() method via the PenInterface singleton. The values E thr and E max can also be set by issuing commands from a macro file. The PenelopeEMPhysics constructor registers in the ConstructParticles() method the PENELOPE-type particles (PenElectron, PenGamma, and PenPositron). The ConstructProcess() method has been designed 1) to add PenPartConvertProcess as a discrete process that converts the ordinary GEANT4 electrons, photons, and positrons, when their energies fall below E thr , into PENELOPEtype particles, and 2) to add PenEMProcess as the only discrete process for the PENELOPE-type particles.
In what follows, for the sake of brevity, the combination of GEANT4 and the PENELOPE C++ methods and database will be named PENG4.

VALIDATION OF THE PENELOPE CLASSES
To verify the correctness of the implementation of the PENELOPE physics and tracking scheme into GEANT4, a series of simulations of monoenergetic pencil beams of electrons, positrons and photons incident on simple material structures have been performed. The considered geometries (see Figure 8) are either a homogeneous cylinder of radius r and thickness t 1 , or a number of stacked cylinders of the same radius and heights t 1 , t 2 , . . .. In all cases the radiation beam impinges along the z axis, which coincides with the symmetry axis of the cylinders.
Simulations were performed by running the PENELOPE Fortran code and the PENG4 C++ code under strictly equivalent conditions, i.e., for the same materials and geometry parameters, the same beam characteristics, and the same set of simulation parameters. As the two codes utilize different random number generators, their results are expected to be consistent (within estimated statistical uncertainties) but not identical. The simulated arrangements were selected so as to evidence the consistency of the two simulations, and to magnify the effect of interfaces in thin structures, which is where the PENELOPE tracking is deemed to be superior. It is worth mentioning that the adopted values of the simulation parameters were set to magnify the relevant processes, rather than ensuring reliability of the results. In the following paragraphs we give a brief description of the various cases considered for validation of PENG4, with plots of sample results. The provided results era expected to be helpful to users of PENG4 as a basic test to confirm that the code is being used correctly. All distributions are normalized per primary particle and thus, for instance, the integral of the depth-dose distribution D(z) over depth z equals the average energy deposited into the target by each incident particle. Each plotted distribution is accompanied with a small plot of the relative difference Δ rel between the PENG4 and PENELOPE values (dots) and its statistical uncertainty (gray bars). Generally, Δ rel is less than its uncertainty, that is, the results from the two codes are statistically consistent.

Electron Beam on a Copper Cylinder
In this example a beam of 1 MeV electrons impinged on a copper cylinder (material ID 29) having radius r 1 cm and thickness t 1 4.25 × 10 -4 cm, about 75 elastic mean free paths of electrons with the initial energy. The parameters used in these simulations were E max E thr 1 MeV (i.e., all particles were of PENELOPE type), C 1 C 2 0.05, W cc W cr 1 keV, E abs (1) E abs (3) 10 keV, E abs (2) 1 keV, s max 2 × 10 -5 cm, and each simulation run involved the generation of 2.0 × 10 9 showers. Figure 9 shows partial results from the simulations: the depth-dose distribution (integrated laterally), the energy distribution of transmitted (upbound) electrons, and the angular distributions of electrons and photons emerging from the material cylinder. The blue histograms are results from PENELOPE; they effectively mask the results from PENG4, represented as red histograms, which are only visible where statistical uncertainties are appreciable. Figure 10 shows partial results from simulations of 125 keV electrons impinging on a tungsten cylinder (material ID 74) with radius r 1 cm and thickness t 1 24 μm, approximately equal to the CSDA range of incident electrons. The adopted Frontiers in Physics | www.frontiersin.org December 2021 | Volume 9 | Article 738735 simulation parameters were E max E thr 125 keV, C 1 C 2 0.05, W cc W cr 1 keV, E abs (1) E abs (3) 5 keV, E abs (2) 1 keV. The variance-reduction techniques of interaction forcing and bremsstrahlung and x-ray splitting were used in the PENELOPE simulation, while PENG4 did an analogue simulation. The displayed results are the depth-dose distribution (integrated laterally) and the energy distribution of photons released with polar angles θ > 90°(lower hemisphere).

Positron Beam on a Copper Foil
Simulations were performed for 1 MeV positrons incident on a copper foil (material ID 29) having radius r 1 cm and thickness t 1 4.25 × 10 -4 cm. The parameters used in these simulations were E max E thr 1.82952 MeV (i.e., 1.21 times the initial total energy of positrons, including their rest mass), C 1 C 2 0.05, W cc W cr 1 keV, E abs (1) E abs (3) 10 keV, E abs (2) 1 keV, s max 2 × 10 -5 cm, and 2.0 × 10 9 showers were generated in each run. Figure 11 shows the calculated energy distributions of transmitted positrons and photons, which are sensitive to both positron and photon transport.

Photons on a 1.5" NaI Detector With Aluminium Backing
In this simulation example a 1.25 MeV photon beam impinges on a NaI cylinder (material ID 253) covered with an aluminium cylinder (material ID 13); the two cylinders have the same radius, r 1.905 cm, and the heights of the NaI and the Al cylinders are t 1 3.810 cm and t 2 2.190 cm, respectively. Simulations were run with the parameters E max E thr 1.25 MeV, C 1 C 2 0.1, W cc W cr 2 keV, E abs (1) E abs (3) 50 keV, E abs (2) 10 keV. Figure 12 shows depth-dose distribution (integrated laterally) with a noteworthy interface discontinuity, and the spectrum of energy deposited in the NaI cylinder, which features scape peaks of positron-annihilation photons and a visible Compton backscattering peak around the position of the double-scape peak.

Photons on a Stack of Three Cylinders of Different Materials
We performed simulations of a 1.25 MeV photon beam incident on a stack of three cylinders of radius 50 cm consisting of two layers of liquid water (t 1 2 cm and t 3 2 cm, material ID 278) separated by a layer of aluminium (t 2 1 cm, material ID 13). The adopted simulation parameters were E max E thr 1.25 MeV, C 1 C 2 0.1, W cc W cr 2 keV, E abs (1) E abs (3) 50 keV, E abs (2) 10 keV. Figure 13 shows the simulated depth-dose distributions (integrated laterally) with characteristic discontinuities at the interfaces, and the energy spectra of downbound photons, i.e., emerging from the irradiated object with polar angles larger than 90°(lower hemisphere).

CONCLUSION
The code system PENELOPE implements reliable interaction models and a robust class-II mixed scheme for tracking electrons and positrons through complex geometrical structures. In the present article we have summarized the interaction models implemented in the code, and provided a concise description of the class-II algorithm used for tracking electrons and positrons, in a way that can be readily applied to other charged particles (see, e.g., Refs. [54,55]). Since there is ample evidence of the reliability of PENELOPE's simulation results for electrons/positrons and photons with energies from about 1 keV up to ∼1 GeV, we have translated the PENELOPE physics and tracking subroutines to C++ and organized them to be accessible from GEANT4 as an additional physics package. The new tool, named PENG4 has been shown to couple correctly to GEANT4 and to yield results equivalent to those from the original PENELOPE code.
Using the two codes, we have performed a set of test simulations with various incident particles and material structures, which were designed to explore different aspects of the transport physics, and we obtained consistent results. Inclusion of PENG4 as part of the GEANT4 toolkit allows taking advantage of the multi-threading capabilities and advanced geometry and statistical tools of GEANT4.  The PENG4 package, including the PENELOPE C++ classes and physics database, is currently available from the authors, and it will soon be distributed through international agencies.

DATA AVAILABILITY STATEMENT
The original contributions presented in the study are included in the article, further inquiries can be directed to the corresponding authors.