\section{\label{sec:sim_tools} Simulation Tools}

\subsection{\label{sec:g4beamline} G4beamline}
\textcolor{orange}{Diktys}
\medskip

The performance of the Muon Campus beamlines was simulated using G4beamline~\cite{g4beamline}, a scripting tool for the GEANT4 Monte Carlo program. Using the GEANT4~\cite{Agostinelli:2002hh} package, the code incorporates key particle-matter physical processes (e.g. energy loss, straggling, multiple scattering) as well as includes muon decays and precession of the muon spin. In the simulation, virtual detectors where placed at various locations along the beamline. As a result, it was possible to evaluate the population of secondaries, their 6D phase space distribution as well as the beam profiles over long distances. The code is also properly modified so that it fully incorporates all magnetic apertures according to the latest engineering specifications~\cite{Stratakis:2019sun}.

\subsection{\label{sec:phase_space} Phase Space Models}
\textcolor{orange}{Mike}
\medskip

Analyses of particle distributions in phase space are performed for many expedient calculations and predictions pertaining to numerous run conditions. Matrices describing linear transverse particle motion are obtained based upon running conditions such as quadrupole high voltage setting, misalignments, and so on, and waveforms for the injection kicker can be superimposed upon the time distribution of an incoming beam pulse as well. Initial phase space distributions derived from Monte Carlo calculations of the beam production can be quickly analyzed by finding each particle's betatron oscillation amplitude about its ideal equilibrium orbit (horizontal and vertical) and determining immediately whether that particle can survive long term within the transverse aperture.
With such information estimates of injection efficiencies, equilibrium momentum distributions, potential ``lost muon'' distributions and other phase space variable correlations can be quickly estimated and optimized for a variety of operational scenarios.

\subsection{\label{sec:bmad} Bmad}
\textcolor{orange}{David R.}
\medskip

BMAD refers to a subroutine library~\cite{Sagan:2006sy} for simulating the dynamics of relativistic beams of charged particles, and an associated format for defining beam line components. As long as the guide field components are defined according to BMAD conventions, the full complement of the analysis tools of the library can be used to investigate the particle dynamics, including various tracking methods, (Taylor maps, symplectic integration, Runge Kutta), construction of maps from tracking, evaluation of Twiss parameters, tracking through maps defined by maps or multipoles, etc. (For details see \href{https://www.classe.cornell.edu/bmad/manual.html}{Bmad-Manual}).

The BMAD formatted representation of the g-2 experiment is comprised of three distinct branches, 1)M5 beam line, 2)the injection channel through the back-leg iron and inflector, and the 3)storage ring including DC magnetic field, time dependent quadrupole electric fields and kicker magnetic fields, and collimator apertures. In the language of BMAD, 'branches' are joined at 'fork' elements and offsets with 'patches'.

The beam lines are assembled as a sequence of elements with fixed length. The electro-magnetic fields in each element are defined by field maps,  multipole expansions, or analytic expressions. Time dependence for pulsed kickers and ramped quadrupoles requires custom code (as there is no appropriate standard BMAD module). Specialized custom routines can apply  arbitrary kicker pulse shapes or quadrupole voltage time dependence.

Particle phase space and spin are tracked through the guide field using Runge-Kutta integration.

The program is equipped with a module to generate an initial distribution of muons, or to read a distribution from a file or both. For example, it is possible to generate a distribution gaussian in transverse phase space, with longitudinal distribution read from a file. (This is useful for imprinting the 'W' shaped longitudinal distribution on an otherwise gaussian transverse distribution.)

Lattice and phase space parameters are computed with standard BMAD routines, including Twiss parameters, beam moments, closed orbits, betatron tunes, chromaticity, synchrotron radiation, spin tunes, etc. The Jacobian matrices required to determine
tunes and Twiss parameters are based on tracking.

Scattering is somewhat ad hoc. Muons entering the storage volume on trajectories that pass through quad plates, multiple scatter in the plates. Muons that are already inside the storage volume are lost if their trajectory subsequently intercepts a quad plate or collimator. If fiber monitors are active, muons multiply scatter in the fibers with energy loss consistent with measurements.

If the muon decay is turned on, then muons decay with lifetime assigned at birth. The phase space, spin coordinates and time of the decay at the decay point are recorded. A positron is created with momentum four-vector appropriately correlated with muon spin. The positron is tracked until  it strikes a calorimeter plane, where phase space coordinates and time are recorded, or otherwise leaves the storage volume.

The walls of the inflector are defined as continuous apertures. Particles that hit the walls are lost. The ends of the inflector are treated as scattering planes.

\subsubsection{\label{sec:bmad_quads} Quadrupoles}
The quadrupole plates are curved to preserve a fixed radial offset with respect to the central on momentum design orbit. The curvilinear coordinate system can be represented by beginning with a full 3-dimensional map, and then extracting an azimuthal
slice of the map (in $r,z$ at fixed $\phi$) or with a fitted multipole expansion of McMillan functions. The curvature necessarily introduces nonlinearities that are not faithfully included in a 2 dimensional cartesian expansion. The BMAD code allows several possible ways to specify the quadrupole electric field.
\begin{enumerate}
\item Field map. The field map that is currently incorporated is based on a $\rho, z$ azimuthal slice of of a 3 dimensional OPERA map. The quad map can be optionally defined as the sum of individual maps for each of the four plates, thus providing the flexibility to set the voltage independently on each plate, to model voltage errors, or the scraping configuration.
\item Multipole expansion. The multipole expansion in McMillan functions is derived as a fit to the azimuthal slice of the 3 dimensional map. An expansion in cartesian coordinates (that is inconsistent with Maxwell in the curved geometry) is another option. The multipole representations are convenient for exploring dependence on nonlinearity.
\end{enumerate}

\subsubsection{\label{sec:bmad_mainmag} Main Magnet}
The main magnet is represented as a map or analytic function with uniform field. A uniform radial component can be specified. Measured field errors are incorporated analytically. The azimuthal dependence of the error field is expanded as a solution to Laplace's equation in cylindrical coordinates in order to ensure consistency with Maxwell equations.

\subsubsection{\label{sec:bmad_inj} Injection Channel}
The magnetic field through the hole in the back-leg iron and cryostat and main magnet fringe field is based on a 3 dimensional OPERA map. A distinct map is computed for the field in the inflector. The fringe and inflector maps are superimposed as appropriate.

The BMAD model has been used extensively to explore dependencies (capture efficiency, CBO amplitude, phase space distribution of captured beam, etc.) on injection trajectory, inflector orientation, field and aperture, kicker field amplitude, field profile, pulse shape, and timing, and quad voltage. Effects of quad field errors and misalignment on closed orbit and Twiss parameters have been studied. Simulations informed analysis of measurements with fiber harps. The flexibility to employ various quadrupole field profiles has enabled study of effects of nonlinearities on decoherence and debunching, electric field and pitch corrections. Indeed simulation will play a critical role in evaluation of the electric field and pitch systematics.

\subsection{\label{sec:cosy} COSY INFINITY}
\textcolor{orange}{Martin}
\medskip

\subsection{\label{sec:gm2ringsim} gm2ringsim}
\textcolor{orange}{Renee}
\medskip

In addition to modeling the electromagnetic fields and apertures of the beamlines and storage ring, it is at times  illuminating to fully simulate material interaction effects, especially in the calorimeter, FBM and straw tracker systems. The reproduction in simulation of experimental observables, for example decay positron and lost muon signals in the calorimeters and track extrapolation in the straw trackers, allows for the estimation of systematic uncertainties due to interactions of the beam with storage ring components as well as analysis cuts and reconstruction techniques.  These material effects, along with the static and time dependent electromagnetic fields and two types of beam guns are encapsulated into a GEANT4~\cite{Agostinelli:2002hh} based package of the storage ring called gm2ringsim. 

All ring components that could be traversed by the incoming muon beam have been replicated in gm2ringsim. Starting with the injection line, this includes the start time scintillators, the two IBMS detectors upstream of the inflector in the back-leg hole, the inflector coil and the last retractable IBMS detector installed immediately downstream of the inflector exit. CADMesh \cite{Poole:2011aaa,Poole:2012aaa} was used to accurately render the most complex solids, such as the vacuum chambers, IBMS detectors, trolly rails, quadrupole plates and the straw tracker modules. The CADMesh package ports CAD drawings into GEANT solids which can then be loaded during runtime. The remaining, simpler components, such as the kicker plates, calorimeter stations and fiber harps are constructed from native GEANT volumes. In order to reduce running time the simulation typically utilizes a parameterized shower response in the calorimeter $PbF_{2}$ blocks. The pole-tips, return yoke and service cryostats that surround the vacuum chambers are also included.  

Multiple sets of time and space dependent magnetic fields are included in the gm2ringsim package. The static fields, such as the inflector and  magnetic dipole fringe fields are mapped using OPERA~\textcolor{red}{\textit{[get citation]}} simulations. The magnetic field in the storage region is modeled as pure dipole with the option of turning on precision maps of magnetic multipole and radial fields as measured by the field team.  The time dependence of the magnetic pulse delivered by the kicker plates is extracted from oscilloscope traces \textcolor{red}{\textit{[do we want to include a figure of a trace here? Or should we refer to the kicker paper?]}} and is scaled according to the measured peak delivered magnetic kick. The electric quadrupole fields are implemented with analytical calculations that include measured multipole values in the storage regions, while a map is used for the region between the outside of the quadrupole plates and the inside wall of the vacuum chambers. This field is particularly important for the set of quadrupole plates positioned after the inflector, as a the injected beam is off orbit and traverses the region between the plate and the vacuum chamber. 

The gm2ringsim package includes several types of particle guns, the most commonly used are the  beam gun and the gas gun.  The beam gun is designed to replicate the experimental injection process and is most often utilized to study the motion of injected muons inside the ring. The beam gun allows the user to tune the phase space parameters of the injected beam and provides the option of using as input the distribution of muons at the exit of the M4/M5 line, as determined from g4beamline simulations. The beam gun also has the capability to shoot multiple particles per event and include other particles species, for example protons and positrons, in the beam distributions.  Beam gun simulations are computationally expensive, requiring  stored muons to be tracked as they circulate for up to \SI{700}{\micro\second} around the storage ring. For studies requiring only information about the muon decay point and subsequent positron motion it is more efficient to use the gas gun. The gas gun simulates the spatial distribution, including distortions due to coherent betatron oscillations, of the decay positions of the stored muons in the beam.  The positrons born at these decays positions are then tracked through the ring as they spiral inwards, creating signals in the calorimeters and tracker detectors. 
