% Single sided library version
\documentclass[12pt,a4paper,openright]{thesis}

% Double sided version (bound or unbound)
% \documentclass[12pt,twoside,a4paper,openright]{thesis}

\usepackage[T1]{fontenc} % I have no idea what any of this does
\usepackage{ae,aecompl}
\usepackage[pdfborder={0 0 0}]{hyperref} % This has to come before 'ordinals'
\usepackage{a4margins,ordinals,boldfix,appendix,graphicx,amsfonts,color,subfigure,longtable}
% ,amsmath 

\begin{document}

\pagestyle{empty}
\title{\LARGE{Muon Capture Schemes for the Neutrino Factory} \\[3cm]}
\author{\Large{Stephen Brooks} \\ \Large{Trinity College, Oxford} \\[3cm]}
\newcommand{\DPhiltext}{Thesis submitted in fulfilment of the requirements for the degree of Doctor of Philosophy at the University of Oxford}
\newcommand{\DPhildate}{Hilary Term, 2010}
\date{\DPhiltext \\[1cm] \DPhildate}
\maketitle

\cleardoublepage
\cleardoublepage

\newcommand{\comment}[1]{}
\newcommand{\link}[1]{\textcolor{blue}{\underline{\url{#1}}}}
\parskip=1.5ex

\begin{abstract}
The proposed \emph{neutrino factory}, a facility for precision measurements of neutrino oscillations, requires directional neutrino beams to reach the required sensitivities.  Among the few sources of such beams is the decay of muons travelling at relativistic speeds, therefore an intense source of muons and subsequent rapid acceleration must be designed so they can reach the required energy before decaying.

This thesis considers several stages in this process: pions are produced from a proton beam hitting a target and pion yield optima are determined as a function of target design parameters and the proton energy.  Issues related to producing the original proton beam are also discussed.  The pions decay to a beam of muons, confined by a channel of solenoids and other components known as the \emph{muon front end}.  A design for this is found that meets the requirement of $10^{21}$ muons per operational year~\cite{FluxRequirement}.

The computer code MARS15 \cite{MARS15} is used to simulate the target, with benchmarks against GEANT4 \cite{GEANT4} and initial results from the HARP experiment \cite{HARP}.  The author's code Muon1~\cite{Muon1Website} is used for muon tracking, with its techniques also explained in the thesis.

To find the highest-yielding arrangement of magnets and accelerating components from the target onwards, Muon1 incorporates an optimisation feature where almost all parameters of the beamline can be varied.  This produces a high-dimensionality search space where the best muon yield is sought using a genetic algorithm.  As each individual evaluation of a design is itself a time-consuming simulation with tens of thousands of particles, the code has been deployed as a distributed computing project that is able to perform millions of simulations per optimisation.

\comment{%
\vspace{5em}
\begin{tabbing}
[1] \=\emph{GROUP REPORT: Physics at a Neutrino Factory}, C. Albright \emph{et al.} (Eds. S. Geer \\\>and H. Schellman), Report to the Fermilab Directorate, FERMILAB-FN-692, \\\>\texttt{hep-ex/0008064} (2000).\\[1.5ex]

[2] \emph{The MARS Code System} version 15.07, by N.V. Mokhov, available from \\\>\link{http://www-ap.fnal.gov/MARS/}.\\[1.5ex]


[3] \emph{GEANT4---a simulation toolkit}, S. Agostinelli \emph{et al.}, Nuclear Instruments and \\\>Methods A \textbf{506}, pp.250--303 (2003), available from \\\>\link{http://geant4.web.cern.ch/geant4/}.\\[1.5ex]

[4] \emph{Status and prospects of the HARP experiment}, M. Ellis, J. Phys. G \textbf{29}, \\\>pp.1613--1620 (2003).\\[1.5ex]

[5] Muon1 Distributed Particle Accelerator Design project website, \\\>\link{http://stephenbrooks.org/muon1}.
\end{tabbing}
}%

\end{abstract}


%\cleardoublepage
\pagestyle{plain}
\raggedbottom
\pagenumbering{roman}

\parskip=1pt
\tableofcontents % Has incorrect page numbers
\parskip=1.5ex
% \listoffigures % Looks stupid
% \listoftables

%\cleardoublepage
%\cleardoublepage
%\pagestyle{headings} % Puts some of the page numbers at the top with chapter name
\flushbottom

% \setcounter{page}{123} % May be useful for fixing up page numbers

\chapter{Introduction}\label{-intro}
\pagenumbering{arabic}
The following sections describe the problem of detecting the very small mass of neutrinos and experimental methods for doing this, particularly the \emph{neutrino factory} that is studied here.  Attention then focusses on the \emph{muon front end} section, as this is critical to the efficiency of such a facility.  Lastly, the methodology used for the optimisation of front end designs in the rest of this thesis is outlined.

\section{Neutrino Oscillations}\label{-intro-osc}
\newcommand{\wf}[1]{\left|#1\right>}
\newcommand{\ii}{\mathrm{i}}
\newcommand{\mod}[1]{\left|#1\right|}
\newcommand{\wfwf}[2]{\left<#1|#2\right>}
\newcommand{\wfb}[1]{\left<#1\right|}
\newcommand{\pdd}[2]{\frac{\partial #1}{\partial #2}}
The original theory of neutrinos \cite{PauliNeutrino} by Pauli in 1930 formulated them as massless particles with their momentum and energy alone sufficient to explain their interactions.  Originally, these interactions were inferred from the continuous energy spectrum of electrons from beta decay but in 1956 a neutrino from a nuclear reactor was observed being absorbed by an atomic nucleus \cite{NeutrinoNucleus}, confirming its status as a particle.

The first observations that did not agree with the massless neutrino model were early results from the Homestake solar neutrino detector \cite{Homestake}, which from 1968 onwards showed a factor of $\sim$3 deficit in the number of electron neutrinos ($\nu_e$) received on Earth compared with astrophysical models of solar neutrino production.  At this stage it was unclear whether the deficit, referred to as the `solar neutrino problem', was caused by errors in the astrophysical model, oscillation between the neutrino flavours (already proposed theoretically \cite{MNS}), or something else.  The Super-Kamiokande experiment \cite{SuperKamiokande}, operating from 1996, was able to resolve this ambiguity by measuring oscillations in neutrinos produced from the decay of muons in the Earth's atmosphere.  As the production sites of these neutrinos form a spherical shell around the Earth, the zenith angle of the incoming neutrinos at the detector determines how far away they were produced (up to $\sim$13000\,km away) and this range of baseline distances is suitable for observing $\nu_\mu$ oscillations.  Further review of the evidence for neutrino oscillations is available in \cite{RPPnumixing}; this section will now explain the physics behind the process.

For a stationary particle of rest mass $m$ and wavefunction $\wf\psi$, the mass--(total) energy equivalence $E_t=mc^2$ becomes the quantum equation of motion $\hat{E_t}\wf\psi=mc^2\wf\psi$, assuming that `a particle' in this sense is always a pure mass eigenstate.  The quantum energy operator is given by $\hat{E_t}\wf\psi:=\ii\hbar\dot{\wf\psi}$, where dot denotes $\pdd{}{t}$, so the time solution to the equation is $\wf{\psi(t)}=\exp(mc^2t/\ii\hbar)\wf{\psi(0)}$ with the exponential of a pure imaginary number producing a constant rate of phase precession with angular frequency $\omega_m:=-mc^2/\hbar$.

\begin{figure}
\includegraphics[width=160mm]{fig_110_weakdecay.png}
\caption{\label{weakdecay}Decay of a positive muon via the weak nuclear force (left) as occurs in the neutrino factory decay ring.  The neutrino and antineutrino produced may undergo further weak interactions in a distant neutrino detector (right), possibly after oscillating to a different flavour.}
\end{figure}

Assuming that there are three neutrinos $\wf{\nu_i}$ with masses $m_i$ for $i\in\{1,2,3\}$, consider the possible production mechanisms.  A weak reaction such as the muon decay $\mu^+ \rightarrow \bar\nu_\mu e^+\nu_e$ is mediated by the $W^+$ boson as shown on the left in figure \ref{weakdecay}.  The important feature is that a weak vertex for a lepton of flavour $\alpha\in\{e,\mu,\tau\}$ will produce a flavoured neutrino that is a combination of the mass eigenstates $\wf{\nu_\alpha}:=\sum_{i=1}^3 U^*_{\alpha i} \wf{\nu_i}$, where $U^*$ is the complex conjugate of the $3\times3$ \emph{Maki--Nakagawa--Sakata} (MNS) \emph{matrix}.  The equivalent formula with antineutrinos on both sides uses $U$ instead of $U^*$.  $U$ is unitary ($U^{-1}=U^{T*}$), so the inverse relation can be simplified to $\wf{\nu_i} = \sum_\alpha U^{-1*}_{i \alpha} \wf{\nu_\alpha} = \sum_\alpha U_{\alpha i} \wf{\nu_\alpha}$.

We can now model the production and detection of a neutrino in an oscillation experiment that produces $\nu_\alpha$ and detects them using lepton flavour $\beta$.  Transporting $\wf{\nu_\alpha}$ as defined above through proper times $\tau_i$ in the rest frames of the mass eigenstates $\wf{\nu_i}$ will apply independent phase advances to the components as follows:
\[ \wf{\nu_\alpha(\tau)}=\sum_{i=1}^3 U^*_{\alpha i} \exp(\ii\omega_{m_i}\tau_i)\wf{\nu_i}. \]
The detection probability of a $\nu_\beta$ flavoured neutrino is $P_{\alpha\beta}=\mod{\wfwf{\nu_\beta}{\nu_\alpha(\tau)}}^2$.  All observable operators in quantum theory are Hermitian and hence have orthonormal eigenvectors, meaning that $\wfwf{\nu_i}{\nu_j}=\delta_{ij}$ and we can expand the probability formula taking advantage of some of these being zero:
\begin{eqnarray*}
P_{\alpha\beta}&=&\mod{\sum_{i=1}^3 U_{\beta i} \wfb{\nu_i}\sum_{j=1}^3 U^*_{\alpha j} \exp(\ii\omega_{m_j}\tau_j)\wf{\nu_j}}^2 \\
&=&\mod{\sum_{i=1}^3 U_{\beta i}U^*_{\alpha i} \exp(\ii\omega_{m_i}\tau_i)}^2 \\
&=&\sum_{i=1}^3 U^*_{\alpha i}U_{\beta i} \exp(\ii\omega_{m_i}\tau_i)\sum_{j=1}^3 U_{\alpha j}U^*_{\beta j} \exp(-\ii\omega_{m_j}\tau_j) \\
&=&\sum_{i=1}^3 |U^*_{\alpha i}U_{\beta i}|^2 + \sum_{i\ne j} U^*_{\alpha i}U_{\beta i}U_{\alpha j}U^*_{\beta j}\exp(\ii(\omega_{m_i}\tau_i-\omega_{m_j}\tau_j)).
\end{eqnarray*}
At this point, note that 
\[ \mod{\sum_{i=1}^3 U^*_{\alpha i}U_{\beta i}}^2 = \sum_{i=1}^3 |U^*_{\alpha i}U_{\beta i}|^2 + \sum_{i\ne j} U^*_{\alpha i}U_{\beta i}U_{\alpha j}U^*_{\beta j} \]
but because of the unitarity of $U$, the squared item on the left-hand side is the `dot product' of two orthogonal rows: $\sum_{i=1}^3 U^*_{\alpha i}U_{\beta i}=\delta_{\alpha\beta}$.  Using this to replace the first term gives the result
\[ P_{\alpha\beta} = \delta_{\alpha\beta} + \sum_{i\ne j} U^*_{\alpha i}U_{\beta i}U_{\alpha j}U^*_{\beta j}\left(\exp(\ii(\omega_{m_i}\tau_i-\omega_{m_j}\tau_j))-1\right). \]
The three mass eigenstates $\wf{\nu_i}$ are treated as remaining in superposition even though they propagate at slightly different speeds.  By the uncertainty principle, the neutrino $\nu_i$ will not be perfectly confined in its rest-frame coordinates $(c\tau_i,\xi_i)$: there will be a small range $\Delta\xi_i$ around zero containing some amplitude for the neutrino, which all has the same phase $\omega_{m_i}\tau_i$.  In most situations this is larger than the very small classical distance expected between the neutrinos.  If the neutrinos are emitted at the common origin of the coordinate systems and received at $(ct,L)$ in the laboratory frame ($L$ being the \emph{baseline length}), the Lorentz transform gives $\tau_i=\gamma_i t-\beta_i\gamma_i L/c$ for the neutrino $\nu_i$ that has relativistic factors $\beta_i$ and $\gamma_i$ in the laboratory frame.

If $E_t$ is the total energy the neutrino was produced with, then
\begin{eqnarray*}
\omega_{m_i}\tau_i &=& \left(-m_ic^2/\hbar\right)\left(\gamma_i t-\beta_i\gamma_i L/c\right) \\
&=& -\left(m_i c^2\gamma_i t-m_i c \beta_i\gamma_i L\right)/\hbar \\
&=& -\left(E_t t-p_i L\right)/\hbar \\
\Rightarrow \quad \omega_{m_i}\tau_i-\omega_{m_j}\tau_j &=& \left((p_i-p_j) L\right)/\hbar.
\end{eqnarray*}
The truncation of the power series $p_i=\sqrt{E_t^2/c^2-m_i^2c^2}\simeq E_t/c-m_i^2c^3/2E_t$, valid in these ultra-relativistic cases may now be used to get
\[ \omega_{m_i}\tau_i-\omega_{m_j}\tau_j = \frac{1}{\hbar}\left(\frac{m_j^2-m_i^2}{2E_t} c^3L\right) \]
and
\[ P_{\alpha\beta} = \delta_{\alpha\beta} + \sum_{i\ne j} U^*_{\alpha i}U_{\beta i}U_{\alpha j}U^*_{\beta j}\left(\exp(\ii(c^3/\hbar)\Delta m^2_{ji}(L/2E_t))-1\right), \]
where $\Delta m^2_{ij}:=m_i^2-m_j^2$.  This formula reveals the oscillatory nature of these detection probabilities as a function of $L$: each term is either a constant or a multiple of a linearly-advancing phase factor (the sum is real because the imaginary parts cancel on swapping $i$ and $j$).  If one is interested in a particular mass splitting, aiming for a phase advance of $\pi$ for maximum signal in its corresponding term suggests the following baseline:
\newcommand{\eu}[1]{\,\mathrm{[#1]}}
\begin{eqnarray*}
(c^3/\hbar)\Delta m^2_{ji}(L/2E_t) &=& \pi \\
\Rightarrow \quad L &=& \frac{2\pi\hbar}{c^3}\frac{E_t}{\Delta m^2}, \\
\mbox{or} \quad L\eu{km} &\simeq& 1.240\ \frac{E_t\eu{GeV}}{\Delta m^2\eu{(eV/c^2)^2}}.
\end{eqnarray*}

For example, neutrinos from nuclear reactions, either on Earth or in the Sun, have an energy spectrum of the order of a few MeV.  For 3\,MeV neutrinos in particular, $L$ would be $\sim$1.4\,km if $\Delta m_{23}^2$ were used, or $\sim$47\,km in the case of oscillations caused by the $\nu_1$--$\nu_2$ mass difference.  \comment{Both of these values are much smaller than the diameter of the Sun's core, so solar observations only detect rates averaged over the oscillations.}  The $\sim$1.4\,km baseline\comment{, on the other hand,} forms the basis of nuclear reactor neutrino oscillation experiments~\cite{ReactorCHOOZ,Reactor2}.  For experiments through the Earth with much longer baselines, the interaction of neutrinos with electrons in matter must be included \cite{MatterEffect}, which changes the oscillation wavelengths from those given in vacuum by the formula above.

Oscillation experiments measure oscillation probabilities, which depend not just on $\Delta m_{ij}^2$ but also the elements of the MNS matrix $U$.  As $U$ is unitary, the complex equivalent of a rotation matrix, it can be parameterised in terms of angles: the standard way of doing this is given on page 12 of \cite{ISSphysics}.  There are three \emph{mixing angles} $\theta_{12}$, $\theta_{13}$ and $\theta_{23}$, which determine the extent of neutrino mixing, plus one \emph{CP-violating phase} $\delta$ \cite{CPVdelta}.  It is the goal of neutrino oscillation physics to measure all these parameters as well as the  $\Delta m_{ij}^2$, though individual experiments may be sensitive to different subsets of the parameters.

\section{Neutrino Beam Facilities}
Natural sources of neutrinos create an evenly-distributed but fairly weak flux over the entire Earth's surface, whereas nuclear reactors produce a concentrated flux from what is roughly a point source but emit neutrinos evenly in all directions.  The best configuration for an oscillation experiment would be to have as many of the neutrinos as possible going through the detector, which requires a \emph{neutrino beam} that stays concentrated over a long distance from the source, requiring anisotropic emission of neutrinos.

The only known way of practically achieving this is to take an interaction, such as a decay, which emits neutrinos isotropically in the rest frame of the parent particle, then pre-accelerate the parent particle to relativistic speeds so the Lorentz boost transforms the distribution of neutrino emission directions into a forward-directed beam in the experimental frame.  For relativistic $\gamma\gg1$ this produces a beam opening angle proportional to $1/\gamma$ and a flux enhancement factor of $\gamma^2$ relative to an isotropic source.

The source of beamed neutrinos taken together with the detector(s) at the other end of the baseline(s) is referred to as a \emph{neutrino beam facility}.
\clearpage
Three main methods of producing boosted neutrino emission have been proposed.

\begin{itemize}
\item \textbf{Conventional neutrino beams}.  Any experiment in which a beam of GeV-order energy hits a fixed target will generate large numbers of pions ($\pi^+$ and $\pi^-$), which if left alone will decay via $\pi^+ \rightarrow \mu^+ \nu_\mu$, or the charge conjugate $\pi^- \rightarrow \mu^- \bar\nu_\mu$.  The pions are mostly forward-directed because they retain some of the original beam's momentum and, as they are charged, may be focussed using elements such as solenoids or a magnetic horn.  Examples include MINOS \cite{MINOS} and K2K \cite{K2K}.
\begin{itemize}
\item \textbf{Superbeams}.  An obvious way to increase the flux of the conventional beam is to increase the mean power of the primary beam.  The term \emph{superbeam}, for `super-conventional beam', refers to experiments such as \cite{CNGS} that use megawatt-order (or higher) beams on the target.
\end{itemize}
\item \textbf{Beta beams}.  Beta decay and positron emission decay are naturally-occurring process that occur in certain radioisotopes.  At the level of nucleons, these processes are $n \rightarrow p\, e^- \bar\nu_e$ and $p \rightarrow n\, e^+ \nu_e$ respectively, producing electron-flavoured neutrinos complementary to the muon-flavoured ones from superbeams.  A beta beam experiment \cite{BetaBeams} consists of a source of radioactive ions, which are then accelerated to a ring where they decay, emitting neutrino beams in their direction of travel.  The decay ring incorporates straight sections pointing at the desired detector sites.
\item \textbf{Neutrino factories}.  Although muons are discarded in conventional neutrino beams, they also undergo a neutrino-producing decay $\mu^+ \rightarrow \bar\nu_\mu e^+\nu_e$ (and its charge conjugate), which is used in the proposed \emph{neutrino factory} \cite{EarlyNufact}.  This produces neutrinos of two flavours with equal fluxes, which is a useful calibration.  The muons survive for longer than pions, which provides (just) enough time for them to be accelerated, resulting in a more collimated beam from a decay ring similar to beta beams.
\begin{itemize}
\item \textbf{Low-energy neutrino factories}.  Removing some of the muon acceleration system from the conventional neutrino factory gives a smaller, cheaper facility that produces lower-energy neutrinos \cite{LENF}.  Detector technology can be optimised to perform better for these low energy interactions.
\end{itemize}
\end{itemize}

\begin{figure}
\includegraphics[width=160mm]{fig_111_sensitivities.png}
\caption{\label{sensitivities}Sensitivity of neutrino beam facilities to $\delta\ne0$ (top left), the sign of $\Delta m^2_{31}$ (bottom left) and $\theta_{13}\ne0$ (bottom right).  The measurements become more difficult as $\theta_{13}$ approaches zero and for certain values of $\delta$.  Values to the right and below each coloured band can definitely be measured at that facility and within the band it depends on the specific variant of the design used.  The low-energy neutrino factory (not shown) performs comparably to the beta beam, as shown in figure 21 of \cite{EURONU09}.}
\end{figure}

Figure \ref{sensitivities} compares the sensitivities of these different facilities to neutrino oscillation parameters that have not currently been measured to high precision.  The angle $\theta_{13}$ and CP-violating $\delta$ could still be zero consistent with current data and although there are some limits on $|\Delta m^2_{31}|$, it is not known whether the difference between the masses is positive or negative.  A full discussion of the physics reach of the neutrino factory and other experiments is available in the ISS physics report \cite{ISSphysics}.  The neutrino factory provides the best performance but requires the largest and most complex facility.

\clearpage
\section{The Neutrino Factory}
\newcommand{\us}{$\mu$s}
% First two paras here may have to be filtered somewhat into the previous (2) sections
The \emph{neutrino factory} is an accelerator-based neutrino source \cite{EarlyNufact} intended to measure the mass splitting $\Delta m^2_{31}$ and entries of the MNS matrix including $U_{e3}=e^{-\ii\delta}\sin\theta_{13}$, where $\theta_{13}$ is the $\nu_1$--$\nu_3$ mixing angle.  As presented on pages 21--22 of \cite{ISSphysics}, the best fit value of $\Delta m^2_{31}$ using data available at the time of publication was $2.6\times10^{-3}\,\mathrm{(eV/c^2)^2}$.  Using this in the baseline formula derived in section \ref{-intro-osc} (and assuming matter effects are small) gives a length of 477\,km per GeV of neutrino energy, suggesting that neutrinos of up to roughly 27\,GeV can be used with baselines that form a chord across the Earth's interior.
% This para may be shortened to remove duplication with 1.2 (remove some Lorentz stuff?)
The high energy allows a directed neutrino beam to be created by the Lorentz-boosted decay of  $\mu^+ \rightarrow \bar\nu_\mu e^+\nu_e$ (and its charge conjugate), where the decay products acquire 105\,MeV of kinetic energy in the muon rest frame.  We therefore expect a neutrino beam of divergence 2--5\,mrad when a beam of muons decays in-flight at these energies.  This angle is proportional to the relativistic factor $1/\gamma$, so the flux at the detector is a factor of $\gamma^2\sim10^5$ above isotropic emission from sources such as nuclear reactors.  A fast muon beam produces neutrinos with energies almost uniformly distributed between zero and the beam energy, so muons of energy 20--50\,GeV are required.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_120_neutrinofactory.png}
\caption{\label{neutrinofactory}Possible neutrino factory layouts, drawn by C.R. Prior based on the conclusions of the ISS \cite{ISS}.}
\end{figure}

The neutrino factory aims to produce $10^{21}$ muon decays per year \cite{FluxRequirement}, making it sufficiently sensitive to the mixing angle $\theta_{13}$, which is currently constrained only by reactor experiments.  A schematic of a neutrino factory is shown in figure \ref{neutrinofactory}.  So far, the most complete design study of a neutrino factory has been the Muon Collider Collaboration's Feasibility Study~II~\cite{Study2} in 2001, which was updated with international consensus in 2007 by the International Scoping Study~(ISS)~\cite{ISS}.

It is difficult to produce an intense beam of muons at 20--50\,GeV: muons have a mean life of only $\tau_\mu=2.2$\,\us\ and must be produced as secondary particles from another accelerator.  Multi-GeV protons are directed onto a high-Z target to maximise the number of strong interactions that produce pions.  Each pion then decays to a muon ($\pi^+\rightarrow\mu^+\nu_\mu$) in an average time of 26\,ns.  The mean beam power of the proton accelerator must be at least 4\,MW for sufficient flux and additionally it must be pulsed to provide extracted bunches of a few ns duration for the time-dependent muon capture systems downstream.  An accelerator with these properties is referred to as a proton driver \cite{DriverSchool}.

The rate of neutrinos of each flavour produced is equal to the rate of muons decaying in the storage ring, given by
\[ R_\mu = R_p\ e_{\pi/p}\ e_\mathrm{machine}\ e^{-\tau/\tau_\mu} \]
(achieving $10^{21}$ per operational year requires $R_\mu=10^{14}\,\mathrm{s^{-1}}$).  Here $R_p$ is the rate of protons hitting the target, $e_{\pi/p}$ is the number of pions produced per incident proton and $\tau$ is the proper time experienced by a muon while going through the acceleration chain.  The remaining term can be expressed as the product of the muon capture, acceleration and storage efficiencies:
\[ e_\mathrm{machine} = e_\mathrm{front}e_\mathrm{acc}e_\mathrm{store}. \]
The work in this report mainly focusses on improving the efficiency of the target $e_{\pi/p}$ and the muon front end $e_\mathrm{front}$.  However, most terms in the equation cannot be considered in isolation: at constant beam power the proton energy will affect $R_p$ and $e_{\pi/p}$ jointly.  Also, the muon decay in the simulations described in this thesis is not handled in continuum as suggested by the equation.  Instead, each muon decays individually, so the factor $e^{-\tau_\mathrm{front}/\tau_\mu}$ will automatically be included in results from front end simulations.

Particular engineering challenges are involved in:
\begin{itemize}
\item \textbf{The muon front end}.  The target creates a large, high divergence beam and pion decays produce additional momentum variation.  Typically only a few percent can be captured both transversely and longitudinally.  Superconducting solenoids of several Tesla are required for transverse capture, while RF phase rotation systems or magnetic chicanes are options for longitudinal matching.
\item \textbf{Muon acceleration}.  The lifetime of the muon is extended to $\gamma\tau_\mu$ in the laboratory frame, so time spent at low energies should be minimised and acceleration must be rapid.  Conventional synchrotrons typically take at least 10\,ms for the magnetic field to ramp from low to high, so are far too slow.  Therefore fixed-field, multiple-pass machines such as RLA (Recirculating Linac) and FFAG (Fixed-Field Alternating Gradient) accelerators are under consideration.  However, the most rapid acceleration possible is always achieved by a straight linac, which is used as the first stage.
\end{itemize}

\clearpage
\section{Muon Front End Structure}\label{-intro-frontend}
The \emph{muon front end} is normally defined to be the piece of neutrino factory beamline extending from the target (which the protons hit) up to the start of muon acceleration.   Most designs start with a solenoidal focussing channel (the \emph{decay channel}) to capture pions from the target as they decay to muons, including a powerful solenoid of up to 20\,Tesla (20\,T) enclosing the target itself.  Longitudinal (energy vs. time of flight) phase space is then manipulated, normally after pion decay, to have a beam suitable for the muon accelerator.  This second process is known as \emph{phase rotation}.  A typical front end studied in this thesis is shown in figure \ref{frontend}.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_130_frontend.png}
\caption{\label{frontend} Parts of the muon front end as investigated in this thesis, in simulation (top) and schematic form (bottom).  The phase rotator may work in either the bunching or antibunching direction depending on whether a bending chicane or RF cavities are used.}
\end{figure}

Each stage of the front end improves one aspect of the beam distribution, which is initially a multidirectional spray of various particles including pions from the target (see sections \ref{-target-eng-thermal} and \ref{-target-model-grid}).  The steps listed below prepare a beam of muons that can be accelerated to the storage ring with low losses apart from the unavoidable muon decays.
\begin{itemize}
\item \textbf{The decay channel}.  A strong magnetic field causes charged particles to spiral around the field lines instead of continuing in a straight line.  This principle is used to deal with the particles emitted from the target, which can have hundreds of MeV/c of transverse momentum, making angles of tens of degrees with the forward direction.  A field of 20\,T along the accelerator axis can keep a large fraction of the particles within 10\,cm of the axis, although it will not reverse the direction of particles emitted with a backward longitudinal momentum component.  In a constant field the particles would continue on perfect helices with their large transverse momentum being conserved in magnitude.  However, if the field decreases along the axis, the zero divergence property of magnetic fields implies there must be an outward-pointing component of the field vector.  This produces a force on charged particles in the direction opposing their natural direction of spiralling in the solenoid field, decreasing the transverse part of their momentum.  Since particle energy is conserved in magnetic fields, the decrease in transverse momentum must be accompanied by an increase in longitudinal (forward) momentum.  All this means that if the magnetic field decreases significantly following the target, the transverse momentum and angle of travel relative to the accelerator axis will both be reduced.  A magnetic field of some magnitude is still required to confine the particles in later sections, with decay channel fields in this thesis typically reducing to 3--4\,T.\ \ Superconducting solenoids can produce the above sequence of fields.

Out of the charged particles from the target, pions are the primary decay parents of muons, with kaons contributing a few percent when present.  The pions have the longer mean lifetime of the two of roughly 26\,ns \cite{PDG-Review} in their rest frame and the forward pions have relativistic factors of $\gamma\sim3$, making the mean flight distance $\sim$20~metres before decay.  This means that most decay channels are 30 metres long or more, though variation of this was allowed in the design process.  The decay imparts a non-negligible momentum kick (tens of MeV/c) to the daughter muon, causing the beam to diverge while decays are still in progress.  The end product of the decay channel is a beam of predominantly muons, with little decay activity, transversely confined within a channel of solenoids.  Longitudinally the beam has `debunched' since being produced at the target, i.e.\ the particles continue at different forward speeds, spreading out as time progresses.

\item \textbf{Phase rotation}.  Periodic RF systems such as those in the muon linac require the beam to occupy a certain stable region of the energy vs.\ arrival time phase space known as an \emph{RF bucket}.  Particles within this region will oscillate around the centre of the bucket, which follows the acceleration waveform, whereas those outside will lose synchronisation and not be fully accelerated.  The bucket has a time span inversely proportional to the RF frequency and an energy range proportional to the applied voltage, but is always `upright' in the sense that correlation is not desired between time and energy.  The beam from the decay channel has a very strong correlation since the highest energy muons will arrive first: as such, it occupies greater time and energy ranges than its phase space area requires and attempting direct acceleration of it would result in RF voltages higher (and more expensive) than necessary.

The phase rotation section removes this correlation by systematically offsetting the energy or time of arrival of the particles.  Energy offset is achieved by another RF system before the linac that is phased to decelerate the leading muons and accelerate the stragglers in the bunch (schemes exist with one or many bunches), leading to a smaller energy range at the output.  Time-of-arrival offset, known as \emph{reverse} phase rotation, uses magnetic bends to put the higher energy particles on longer paths, reducing the time spread at the output.  Variants of both schemes are studied in this thesis: a reverse phase rotation scheme in section \ref{-results-chicanelinac} and RF phase rotators in section \ref{-results-phaserot} onwards.

The phase rotation channel typically continues the transverse beam confinement using solenoids as in the decay channel, with the RF cavities placed between them.  The resulting beam has the stable transverse optics inherited from the decay channel in addition to a decorrelated longitudinal phase space.

\item \textbf{Ionisation cooling}.  For some proposed muon accelerators, such as FFAGs, the beam from the decay channel is still too large to fit in the \emph{dynamic aperture} of the accelerator's magnets, within which the transverse dynamics are stable.  Scattering of muons through materials placed in the beamline is used to drain transverse momentum, with RF acceleration replenishing forward momentum, leading to a smaller beam.  The interaction is predominantly by knocking electrons from the atoms of the material, hence the name \emph{muon ionisation cooling}.  This technique is not used in the front ends studied herein, though chapter \ref{-cool} explains the principle further and constructs a computer model of this beam scattering.  The resulting transversely smaller beam would be compatible with smaller aperture muon linacs.
\comment{
\item \textbf{Muon linac}.  And yet, the armadillo.}
\end{itemize}

The UK neutrino factory design differs slightly from the ISS baseline \cite{ISS} because the UK team have been investigating the possibility of a solid metal target instead of a mercury jet \cite{SolidTarget,WireTest}.  The performance in terms of pion yield is quite similar between the two approaches, metals such as tungsten and tantalum being close to mercury in the periodic table, though some adaptations of the decay channel are necessary such as locating the residual proton beam dump further downstream (see section \ref{-target-eng-dump}).  Design issues related to this change are discussed throughout chapter \ref{-target-eng}.

The front ends in this thesis also differ from other baselines because they do not assume a muon ionisation cooling channel is used to reduce the beam size before entering the acceleration systems.  A buncher and cooling system \emph{may} be added to make the beam small enough to go through the optics of FFAGs but this is not attempted.  Instead, it is suggested that a linear muon accelerator with a larger acceptance may be a practical option all the way to the decay ring energy (25\,GeV in the ISS).  The reasoning is that the neutrino factory shown in figure \ref{neutrinofactory} requires building an estimated 2.04\,km of beamline from the target to the storage rings, excluding transfer lines (0.87\,km of this is in the eight RLA teardrop arcs).  If the average gradient of the first ISS RLA's accelerating section (8.5\,MV/m) was used to cover the range 0.9--25\,GeV, that would require 2.84\,km of linac to be added to a front end of 0.34\,km given in section \ref{-results-linac}, for a total of 3.18\,km and no internal transfer lines.  The relativistic shrinkage of the beam in the high-energy half of the linac may allow this part to be shortened further, either with compact transverse optics or through high-gradient cavities (see end of section \ref{-results-decay}).  Thus the linac option is not greatly longer than the multi-technique system, while the use of fewer different technologies could potentially lead to higher reliability or cost savings during manufacturing.

\section{Guide to This Thesis}
\newcommand{\czbox}[2]{\parbox{#1\textwidth}{#2}}
\begin{tabular}{lr}
\czbox{0.8}{An automated approach is used to search for good front end designs.  The basis for this is a particle tracking code called Muon1 \cite{Muon1Website}, which calculates the number of muons that survive a given configuration of magnets and RF cavities.}&\vline\quad Chapter \ref{-code}\\ \\
\czbox{0.8}{Tracking requires an initial distribution of pions from the target, which can be calculated with hadronic interaction codes such as MARS15 \cite{MARS15} used here.  The target itself can be varied with a view to improving yields, so after a discussion of the design issues,}&\vline\quad Chapter \ref{-target-eng}\\ \\
\czbox{0.8}{the target parameters are optimised}&\vline\quad Chapter \ref{-target}\\ \\
\czbox{0.8}{and the resulting pion production checked against some experimental data and another code.}&\vline\quad Chapter \ref{-target-bench}\\ \\
\czbox{0.8}{A module for simulating muon cooling in Muon1 is also developed.}&\vline\quad Chapter \ref{-cool}\\ \\
\czbox{0.8}{With the tracking code ready to use, an optimiser is constructed that loops Muon1 to search a specified design space for good muon yields using a genetic algorithm.  This is deployed as a distributed computing project.}&\vline\quad Chapter \ref{-optimiser}\\ \\
\czbox{0.8}{Finally, different approaches for the front end and early muon linac are run as different design spaces in the distributed optimiser and the resulting best lattices discussed.}&\vline\quad Chapter \ref{-results}
\end{tabular}


\chapter{Particle Tracking Code (Muon1)}\label{-code}
This chapter explains the principles of particle tracking as used in the Muon1 code \cite{Muon1Website}, including some analysis of error sources.  Models for magnetic fields are derived, together with algorithms for generating particle decays and locating collisions.  The more specific aspects of specifying the accelerator as input to the code are discussed in section \ref{-optimiser-lattice}.

Muon1 was written beginning in 2001, at a time when two other codes for muon front end simulations, ICOOL \cite{ICOOL} and G4MICE \cite{G4MICE} were in development.  ICOOL had many of the required features but tracked particles with beamline distance as the independent variable.  It was observed that some pions emitted from the target went backwards (see section \ref{-target-model-grid}), so a code that tracked in time was preferred to investigate their behaviour including magnetic bottle or mirror effects around the target solenoids.  G4MICE, a combination of GEANT4 \cite{GEANT4} tracking and materials with magnetic field models for solenoids, did track in time but many of the GEANT4 material models proved not to be as accurate as those in other codes (see sections \ref{-target-geant4} and \ref{-cool-elms}).  It also had many external library dependencies and did not lend itself to a self-contained small distribution that could be downloaded and installed on Windows, as was used for the distributed computing project in chapter \ref{-optimiser}.  Finally, neither of the other two codes had genetic algorithm optimisation capabilities, although these could conceivably have been wrapped around them in some way.  Muon1 provided a more integrated package.

\section{Equations of Motion}\label{-code-motion}

\newcommand{\dd}[2]{\frac{\mathrm d#1}{\mathrm d#2}}
\newcommand{\dtwo}[2]{\frac{\mathrm d^2#1}{\mathrm d{#2}^2}}
\newcommand{\pdtwo}[2]{\frac{\partial^2#1}{\partial{#2}^2}}
\newcommand{\dmixed}[3]{\frac{\mathrm d^2#1}{\mathrm d{#2}\mathrm d{#3}}}
\newcommand{\dn}[3]{\frac{\mathrm d^{#3}#1}{\mathrm d{#2}^{#3}}}
\newcommand{\Dt}[1]{\dd{#1}{t}}
\newcommand{\hd}[2]{\mathrm d#1/\mathrm d#2}
\newcommand{\p}{\mathbf p}
\newcommand{\vv}{\mathbf v}
\newcommand{\E}{\mathbf E}
\newcommand{\Bv}{\mathbf B}
\newcommand{\x}{\mathbf x}
\newcommand{\F}{\mathbf F}

The force on a particle of charge $q$ travelling through electric and magnetic fields $\E(\x,t)$ and $\Bv(\x,t)$ is given by the Lorentz law:
\[ \Dt{\p} = \F = q(\E+\vv\times\Bv), \]
where $\p$ is the particle momentum.  The time integration of this equation is complicated somewhat by the relativistic definition of momentum:
\begin{eqnarray*}
\p &=& m\gamma\vv \\
\gamma &=& \gamma(v) = \frac{1}{\sqrt{1-(v/c)^2}},
\end{eqnarray*}
where $v=|\vv|$ and the particle has rest mass $m$.  Particles must be represented by a \emph{phase space} vector that encodes information about both their position and velocity (or momentum).  There is some choice of how to parameterise the phase space, though it always has $3+3=6$ variables.  The Muon1 tracking code represents position by a cartesian vector $\x$ relative to a fixed origin, the other options being some sort of polar coordinate system and/or changing coordinate system to align with the axis of the accelerator components.  This is in the laboratory rest frame, another choice would have been to move the origin with some ``central particle'' in the beam.  Finally, some codes when in the accelerator-aligned frame use ``$z$'' as the independent variable instead of time and store the arrival times of particles at a particular plane.  These alternative techniques can provide faster tracking codes in some cases (for instance when tracking in $z$ only requires a single component to be considered at a time) with variables that are more physically interpretable.  Because the simulation of the muon front end starts from a pion production target, with particles going in many directions including backwards, a 3D approach that makes no assumptions is favoured for its generality.  The large velocity spreads, even when going forwards, limit the usefulness of taking a frame co-moving with the beam.

For the three other components of the phase space vector, $\gamma\vv$ is chosen.  Early versions of the code used $\vv$ but this started to lose accuracy for higher-energy particles.  Since $E_t=m\gamma c^2$, inverting the expression for $\gamma(v)$ gives the velocity as a function of the particle's total energy:
\[ v = c\sqrt{1-\gamma^{-2}} = c\sqrt{1-(E_t/mc^2)^{-2}}. \]
The $-2$ index on the ratio of the total energy to the rest energy means the amount subtracted from $1$ becomes small at a quadratic rate, after which the square root moves it even closer to unity (and $v$ to $c$).  This closeness results in poor energy resolution when $\vv$ is numerically quantised to triplets of floating point numbers.  The vector $\gamma\vv$ (actually equal to $\p/m$, so proportional to momentum) does not suffer from this problem and tends to infinity for larger energies, maintaining resolution in energy as seen in the ultra-relativistic limit $|\gamma\vv| \simeq \gamma c = E_t/mc$ where the quantities become proportional.  For low speeds $\gamma \simeq 1$ and $\gamma \vv \simeq \vv$ approaches the classical velocity.

It will be useful to have expressions for the derivative of the phase space vector $(\x,\gamma\vv)$ with respect to laboratory time $t$ (the independent variable).  By definition,
\[ \Dt{\x} = \vv = \frac{\gamma\vv}{\gamma} \]
but the $\gamma$ in the denominator must be calculated from the speed information already stored in the phase space vector (i.e. $|\gamma\vv|=\gamma v$) this time, not just from $v$ as before.  Although this can be done purely by algebraic manipulation of the expression for $\gamma(v)$, which produces quite messy formulae that later cancel to something simple, a physics argument can give the result directly.  Start with the (classical, relativistic) total energy equation for a moving particle
\[ E_t^2 = (pc)^2 + (mc^2)^2, \]
where $p=|\p|$ and note that $p=m\gamma v$ and $E_t=m\gamma c^2$.  Substituting and then cancelling $mc$ from within the brackets gives
\begin{eqnarray*}
(m \gamma c^2)^2 &=& (m \gamma v c)^2 + (m c^2)^2 \\
\Rightarrow \quad (\gamma c)^2 &=& (\gamma v)^2 + c^2 \\
\Rightarrow \quad \gamma &=& \frac{\sqrt{(\gamma v)^2 + c^2}}{c},
\end{eqnarray*}
which can be used as the expression for $\gamma$ in
\[ \Dt{\x} = \frac{\gamma\vv}{\gamma} = \frac{\gamma\vv c}{\sqrt{|\gamma \vv|^2 + c^2}}. \]

The rate of change of the other component comes from the force law as opposed to kinematics:
\[ \Dt{(\gamma\vv)} = \Dt{(\p/m)} = \frac{\F}{m} = \frac{q}{m}(\E+\vv\times\Bv). \]
There is again the problem of having $\vv$ instead of $\gamma\vv$.  However, the program can be arranged to calculate $\Dt{\x}$ first and use the stored result in the expression
\[ \Dt{(\gamma\vv)} = \frac{q}{m}\left(\E+\Dt{\x}\times\Bv\right). \]
The complete time derivative of the phase space vector for the tracking problem can now be written out explicitly:
\newcommand{\vectwo}[2]{\left[\begin{array}{c}#1\\#2\end{array}\right]}
\[ \Dt{}\vectwo{\x}{\gamma\vv} = \vectwo
{\frac{\gamma\vv c}{\sqrt{|\gamma \vv|^2 + c^2}}}
{\frac{q}{m}\left(\E(\x,t)+\frac{\gamma\vv c}{\sqrt{|\gamma \vv|^2 + c^2}}\times\Bv(\x,t)\right)}, \]
where the functional dependencies have become unsuppressed to demonstrate how each element of the derivative depends on elements of the phase space vector and only one other variable, $t$.  This last external dependency can be eliminated by making the current laboratory time part of the particle's vector, though in a real program this would not be stored repeatedly for each particle!  As a result, the derivative becomes a proper function of the vector:
\newcommand{\vecthree}[3]{\left[\begin{array}{c}#1\\#2\\#3\end{array}\right]}
\newcommand{\f}{\mathbf f}
\[ \Dt{}\vecthree{\x}{\gamma\vv}{t} = \f\left(\vecthree{\x}{\gamma\vv}{t}\right) = \vecthree
{\frac{\gamma\vv c}{\sqrt{|\gamma \vv|^2 + c^2}}}
{\frac{q}{m}\left(\E(\x,t)+\frac{\gamma\vv c}{\sqrt{|\gamma \vv|^2 + c^2}}\times\Bv(\x,t)\right)}
{1}. \]

\clearpage
\section{Runge--Kutta Methods}\label{-code-rk}
\newcommand{\s}{\mathbf s}
\newcommand{\dt}{\delta t}
The previous section produced a ``time integration'' problem of finding the solution $\s(t)$ of a differential equation with generic form
\[ \dot\s=\f(\s), \]
where $\dot\s$ denotes the time derivative ($\Dt{\s}$) and the initial condition $\s(t_0)$ is specified to make the solution unique.  In cases where there is not an exact analytic solution for the trajectory, as is usually the case for realistic magnetic fields, the calculation can proceed in a series of small timesteps, each of which calculates a numerical approximation to $\s(t+\dt)$ from $\s(t)$.

Note that incremental time-stepping is generally the slowest class of method for trajectory calculation.  In lower dimensionality cases (e.g. the two-dimensional phase space of longitudinal dynamics) the mapping $\s(t_0)\rightarrow\s(t_1)$ can be approximated by evaluating comparatively few tracks and then interpolating, so tracking can be avoided for the majority of the particles.  Additionally, for beams that travel very close to the machine axis, power expansions in deviations from a central trajectory can give good results even for the full phase space (see for instance \cite{TRANSPORT}).  However, the pion beam to be captured in a neutrino factory front end has a very high emittance that is intrinsic to the way it is generated from nuclear interactions in the target, so particles may move into regions far from the central trajectory where a truncated power series is no longer a good approximation.

\subsection{Principle}

\newcommand{\sfrac}[2]{{\textstyle\frac{#1}{#2}}}
Considering a small but finite timestep of length $\dt$, the definition of the derivative as a limit immediately suggests the following approximation:
\begin{eqnarray*}
\frac{\s(t+\dt)-\s(t)}{\dt} &\simeq& \dot\s(t) \\
\Rightarrow \quad \s(t+\dt) &\simeq& \s(t)+\dt\ \dot\s(t) \\
&=& \s(t)+\dt\ \f(\s(t)).
\end{eqnarray*}
This is known as Euler's forward difference method and is the simplest numerical integration method available for these problems.  To obtain information about the error behaviour of this method, Taylor expand $\s(t+\dt)$ about $t$:
\begin{eqnarray*}
Error &=& \s(t)+\dt\ \f(\s(t)) - \s(t+\dt) \\
&=& \s(t) + \dt\ \dot\s(t) - (\s(t) + \dt\ \dot\s(t) + \sfrac12\dt^2\ \ddot\s(t) + O(\dt^3)) \\
&=& -\sfrac12\dt^2\ \ddot\s(t) + O(\dt^3),
\end{eqnarray*}
which shows that the error in a single timestep is proportional to $\dt^2$ (plus terms that are $O(\dt^3)$, i.e. order $\dt^3$ and higher).  Tracking through the entire time interval requires $(t_1-t_0)/\dt$ of these steps, giving a final error proportional to $\dt\ (t_1-t_0)$ provided the errors are additive.  Because the rate of error accumulation is generally proportional to $\dt^1$, Euler integration is known as a \emph{first-order method}.  This means that to increase its tracking accuracy by an order of magnitude, an order of magnitude more computing time is required, which leads to very large compute times to produce accurate results.

Fortunately there are higher-order methods available that cancel more of the Taylor expansion of $\s(t+\dt)$, leaving only higher powers of $\dt$ remaining.  A simple example of how this can work is the method that uses $\dot\s$ from the central location $t+\sfrac12\dt$ instead of from $t$ to determine the direction of the step, which gives it second-order (step error $\propto \dt^3$) accuracy as the $\ddot\s$ term is now taken account of.  The central location itself has to be worked out from an Euler step as shown below.
\begin{eqnarray*}
\s(t+\dt) &=& \s(t)+\dt\ \dot\s(t+\sfrac12\dt) + O(\dt^3)\\
&=& \s(t)+\dt\ \f\Big(\s(t+\sfrac12\dt)\Big) + O(\dt^3)\\
&=& \s(t)+\dt\ \f\Big(\s(t)+\sfrac12\dt\ \dot\s(t) + O(\dt^2)\Big) + O(\dt^3)\\
&=& \s(t)+\dt\ \f\Big(\s(t)+\sfrac12\dt\ \f(\s(t))\Big) + O(\dt^3)
\end{eqnarray*}
Notice how the approximation is expressed in a form that depends only on $\s$ evaluated at the current time (and not any other time, or its derivatives) and evaluations of the known function $\f$.  This ensures that it is computable and leads to the general form of an $N$-step Runge--Kutta method:
\begin{eqnarray*}
\s_0 &=& \s(t); \\
\s_n &=& \s(t)+\dt\ \f\left(\sum_{i=0}^{n-1}\alpha_{ni}\s_i\right) \qquad \mbox{for }1\le n\le N;\\
\s(t+\dt) &\simeq& \sum_{i=0}^{N}\beta_i\s_i,
\end{eqnarray*}
where the coefficients $\alpha_{ni}$ and $\beta_i$ can be carefully chosen to cancel lower powers of $\dt$ in the error expression, leaving a method with a high order of accuracy.  This technique was originally developed at the end of the 19\th century for solving differential equations by hand \cite{OriginalRK} but for a more modern introduction with applications to computer programming, see \cite{NumRecipesRK}.

The Muon1 code uses the fourth-order Runge--Kutta method defined as follows.
\begin{eqnarray*}
\s_0 &=& \s(t) \\
\s_1 &=& \s(t)+\dt\ \f(\s_0) \\
\s_2 &=& \s(t)+\dt\ \f(\sfrac12\s_0+\sfrac12\s_1) \\
\s_3 &=& \s(t)+\dt\ \f(\sfrac12\s_0+\sfrac12\s_2) \\
\s_4 &=& \s(t)+\dt\ \f(\s_3) \\
\s(t+\dt) &\simeq& \sfrac16\s_1+\sfrac13\s_2+\sfrac13\s_3+\sfrac16\s_4
\end{eqnarray*}
This order is chosen because of the relatively rapid convergence with decreasing step size and the fact that increasing to fifth order requires an additional two calculation steps, as opposed to orders up to 4 where only one more step is required for each successive order.

\comment{
\subsection{Achieving Higher Orders of Accuracy}
\newcommand{\shat}{\hat\s}
\newcommand{\ds}{\delta s}
\newcommand{\bds}{\B{\delta}\mathbf\s}
The error analysis of Runge--Kutta methods is complex due to the nesting of function evaluations.  Finding the method with the least steps to achieve a certain order of accuracy is currently an unsolved problem in the general case.  The outline below will define the system of (nonlinear) equations that must be satisfied to guarantee various orders of convergence.  The fourth-order method selected will then be stated explicitly together with the current state of knowledge for other orders.

The order of a method can be determined by comparing the true solution at the next timestep $\s(t+\dt)$ with the numerical solution $\shat(t+\dt)$ generated by the Runge--Kutta method from time $t \rightarrow t+\dt$ starting from the correct value $\s(t)$.  If these are considered as functions of $\dt$, an $N$\th order method will have identical Taylor coefficients up to and including the one in $\dt^N$.

Expressing the true solution in series form as 
\[ \s(t+\dt) = \sum_{n=0}^\infty \frac{1}{n!}\dt^n \s^{(n)}(t), \]
where $\s^{(n)}(t)=\dn{\s}{t}{n}$, allows both sides of $\dot\s(t+\dt)=\f(\s(t+\dt))$ to be expressed similarly to equate terms.  The Taylor expansion for $\f(\s)$ is
\[ \f(\s(t+\dt)) = \sum_{n=0}^\infty \frac{1}{n!}\left(\prod_{i=1}^n\ds^{\mu_i}\right)\f_{\mu_1\cdots\mu_n}(\s(t)), \]
where Einstein summation is used on the Greek indices, $\f$ with subscripts is its multiple derivative in those axes and $\bds$ is the offset in phase space given by:
\[ \bds = \s(t+\dt)-\s(t) = \sum_{n=1}^\infty \frac{1}{n!}\dt^n \s^{(n)}(t). \]
We now have
\[ \f(\s(t+\dt)) = \sum_{n=0}^\infty \frac{1}{n!}\left(\prod_{i=1}^n
\sum_{j=1}^\infty \frac{1}{j!}\dt^j s^{(j)\mu_i}(t)
\right)\f_{\mu_1\cdots\mu_n}(\s(t)), \]
which we can compare with
\begin{eqnarray*}
\dot\s(t+\dt) &=& \sum_{n=1}^\infty \frac{1}{n!}n\dt^{n-1} \s^{(n)}(t) \\
&=& \sum_{n=1}^\infty \frac{1}{(n-1)!}\dt^{n-1} \s^{(n)}(t) \\
&=& \sum_{n=0}^\infty \frac{1}{n!}\dt^n \s^{(n+1)}(t)
\end{eqnarray*}
for each power of $\dt$.  Equating the coefficients of $\dt^n$ gives
\[ \frac{1}{n!}\s^{(n+1)}(t) = \sum_{\mathrm{Sequences\ }a:\atop\Sigma a = n}\frac{1}{|a|!}\left(\prod_{i=1}^{|a|}\frac{1}{a_i!}s^{(a_i)\mu_i}(t)\right)\f_{\mu_1\cdots\mu_{|a|}}(\s(t)), \]
where $|a|\ge0$ is the length of the sequence $a$ consisting of positive integers.  This forms a recurrence that defines $\s^{(n+1)}(t)$ in terms of only lower time derivatives of $\s$ and derivatives of $\f$.  If this relation is used repeatedly, any time derivative of $\s$ and hence any term in the Taylor expansion of $\s(t+\dt)$, can be defined only in terms of various products of multiple derivatives of $\f$ evaluated at $\s(t)$.
% Get some references from http://lec.ugr.es/~julyan/papers/rkpaper/node2.html
}

\subsection{Single Particle Error Study}\label{-code-rk-single}
\newcommand{\grad}{\B{\nabla}}
The two main deviations from the ideal higher-order error behaviour in accelerator applications are that:
\begin{enumerate}
\item The errors are not always additive.  When tracked paths diverge from each other, errors can be amplified on a timescale determined by the field gradients in the machine.  A simple case of this is in a defocusing quadrupole magnet where off-axis distance and hence distances between particles increase exponentially.
\item In a tracking code, $\f(\s)$ is not always analytic.  Often the input for a code will specify $\Bv(\x)$ as a `field map' with values defined at the points of a grid.  The interpolation used to generate field values between these points is generally not completely smooth, so steps that straddle the border will acquire an error of a lower power of $\dt$ than intended.
\end{enumerate}

The first of these in particular makes creating a useful error analysis applicable to the general case impossible.  Instead, some empirical tracking must be done when fixing a timestep, to ensure it is appropriate for the problem at hand.  Below, this is done for two cases: one tracking through a solenoid field and the other tracking through a complex field map extracted from an OPERA \cite{OPERA} model of a muon cooling ring.  In both of these, the final particle position and velocity obtained from timesteps ranging from $10^{-12}$ to $10^{-8}$ seconds is compared to an `accurate' result using $10^{-13}$ seconds.

\subsubsection{Test 1: Solenoid with Fringe Field}

\begin{figure}
\includegraphics[width=160mm]{fig_223_test1image.png}
\caption{\label{test1image}Path of the muon in the solenoid test problem.}
\end{figure}
\begin{figure}
\includegraphics[width=160mm]{fig_223_test1graph.png}
\caption{\label{test1graph}Dependence of errors on timestep size for the solenoid test problem.}
\end{figure}

In this test an 180\,MeV muon enters a $B_\infty$=20\,T solenoid that is 40\,cm long and 10\,cm in radius.  The 20\,T value is only an asymptotic central field for an infinitely long sheet coil solenoid with the same current density.  The actual field calculation starts with the analytic expression for the on-axis field, $B_z=\frac12 B_\infty\left(\frac{a}{\sqrt{a^2+1}}+\frac{b}{\sqrt{b^2+1}}\right)$ where $a=z/R_\mathrm{sol}$ and $b=\frac{L_\mathrm{sol}-z}{R_\mathrm{sol}}$.  This is extrapolated off the central axis by a cubic power expansion in $r$ derived from imposing $\grad\cdot\Bv = \grad\times\Bv = 0$ on a cylindrically symmetric problem (this is fully described in section \ref{-code-magnet-offaxis}).  The muon is tracked for 5\,ns, starting (3\,cm,2\,cm) off-axis at the entrance plane of the solenoid and moving at an angle of 48.5\degree to the central axis, so that it spirals around and then leaves via the other end (see figure \ref{test1image}).
 
Figure \ref{test1graph} shows the errors in the final phase space coordinates for the range of timesteps investigated.  The right-hand side of the figure is blank because the muon hit the solenoid and was lost for those timesteps.  The larger timesteps do not work due to the confined nature of this problem: the muon would travel from one side of the solenoid bore to the other in about 1\,ns, so the timestep must be much smaller than that.  Additionally, it must be much smaller than the Larmor period ($2\pi m_0 \gamma / qB$ = 0.9985\,ns here) of its helical path within the solenoid, which is also short due to the large ~20\,T field.

Most striking is the very simple dependence of the error on the timestep below some initial irregularities.  This comes purely from the $\dt^4$ leading order error term and can be seen from the graph to decrease exactly four orders of magnitude for each order of magnitude in timestep.  This dependency is so clean owing to the completely analytic nature of the $\Bv$ field that was used, for just one solenoid with no cut-offs or other irregularities.

\subsubsection{Test 2: Field Maps from OPERA}
\renewcommand{\thefootnote}{\fnsymbol{footnote}} % Use symbols throughout, use [2] for dagger

\begin{figure}
\includegraphics[width=155mm]{fig_223_test2image.png}
\caption{\label{test2image}Muon path through the cooling ring field maps.}
\end{figure}
\begin{figure}
\includegraphics[width=160mm]{fig_223_test2graph.png}
\caption{\label{test2graph}Dependence of errors on timestep size in the cooling ring field map test problem.}
\end{figure}

Here another 180\,MeV muon is tracked for 50\,ns through roughly one third of a turn in the Rees cooling ring\footnote[2]{Muon1 tracking of this ring showed the optics to be unstable, which is why a full turn is not used and no cooling ring appears in this thesis.} \cite{ReesCoolRing}.  It starts (3\,cm,2\,cm) off-axis, but parallel, to test tracking of the transverse oscillations in the orbit visible in figure \ref{test2image}.  The maps were generated in the magnetostatic code OPERA-3d and sampled at cubic grids of 5\,cm spacing.  Trilinear interpolation was used between the eight grid points at the corners of each cube to obtain the field values in the continuum.  This gives a continuous $\Bv$ field but it is not differentiable at the cube boundaries.

The scale of the problem is larger here (metres) so many of the longer timesteps do work to some extent and now appear on the graph (figure \ref{test2graph}).  An initial steep decrease (possibly $\propto \dt^4$) gives way to a slower decline as the error becomes dominated by lower terms.  A $\dt^2$ term is expected from the fixed number of crossings of field map cube boundaries, each of length $\dt$ and making a mis-estimate of the field proportional to that length, giving $\dt^2$ overall.  However, the final falloff looks even slower than that.  An error of order $\dt$ will come from any field discontinuities, such as edges of the field maps where the field is nonzero.  There, the mis-estimate is of fixed magnitude so the error decreases only as $\dt$, which dominates as $\dt$ tends to zero.

\newcommand{\um}{$\mu$m}
The timestep of $10^{-11}$ seconds (0.01\,ns) has been chosen as the default for Muon1 as this gives position errors of 25\,\um\ in the first test and below 10\,\um\ in the second, which are comparable to magnet alignment tolerances.  The velocity errors decrease in step with the positional ones, demonstrating good convergence in all parameters.  Energy conservation in magnetic fields is not enforced other than by the structure of the Lorentz force law, so small errors in particle energy occur with Runge-Kutta tracking but decrease in the same manner as the velocity errors.

\subsection{Multi-Particle, Full Beamline Error Study}
The previous section studied the error behaviour of a single particle trajectory, whereas there must be thousands of particles in a simulation if yield figures are to be statistically meaningful.  The problem with running a numerical algorithm on a large number of inputs (initial particle positions here) is that it drastically increases the probability that one of those inputs encounters a pathological case, perhaps near a boundary, discontinuity or singularity in some function.  Therefore we cannot believe the convergence behaviour is `good' without also checking it for an entire particle beam.

A particular decay channel setup (roughly 30\,m of beamline) was run for a pion input file consisting of 20936 particles; on one simulation 8963 particles got to the end of the channel.  This number may include multiple decay products from a single particle, as discussed in section \ref{-code-decay-multi} and will vary slightly due to the random nature of the decays unless a fixed seed is used.  Simulations were run for 120\,ns, which is enough time for the majority of particles of interest to reach the end of the channel and then the distributions compared for timesteps of 5, 10, 15 and 20\,ps (recalling that 10\,ps was recommended from the single particle work), giving the results shown in table \ref{beamtimesteps}.

\begin{table}[hb]
\caption{\label{beamtimesteps}Distance errors between particles in pairs of beam distributions produced with different choices of Runge--Kutta timestep in the decay channel simulation.}
\begin{center}
\begin{tabular}{llll}
\hline
Pair of timesteps compared&Maximum error (m)&RMS error (m)&Mean error (m)\\
\hline
10\,ps, 5\,ps&	0.002339&	0.000452&	0.000266\\	   
\hline
15\,ps, 5\,ps&	0.017983&	0.003466&	0.002050\\	   
15\,ps, 10\,ps&	0.015655&	0.003015&	0.001784\\	   
\hline				   
20\,ps, 5\,ps&	0.075524&	0.014397&	0.008522\\	   
20\,ps, 10\,ps&	0.073302&	0.013971&	0.008268\\	   
20\,ps, 15\,ps&	0.058233&	0.011084&	0.006550\\	 
\hline
\end{tabular}
\end{center}
\end{table}

The error measure between two entire distributions can be computed in a number of ways.  Here, the positions of the particles in one distribution were compared with their counterparts in another, yielding a list of distances.  The maximum, root mean square (RMS) and mean of these distances were calculated for lists coming from each possible pair of distributions.  As the method being used is fourth order, in an ideal case each measure of error would be expected to follow the formula
\[Error = K|\dt_1^4-\dt_2^4| = K\dt_\mathrm{eff}^4. \]
Here the `effective timestep' has been defined as
\[\dt_\mathrm{eff} = |\dt_1^4-\dt_2^4|^\frac14, \]
which is the timestep expected to have the same error from the true solution ($\dt\rightarrow0$) as the two compared finite timesteps have from each other, assuming ideal, linearly additive fourth order error scaling.  $\dt_\mathrm{eff}$ may be plotted against the three error measures and power law curves fitted as shown in figure \ref{beamerrorgraph}.

\begin{figure}
\includegraphics[width=160mm]{fig_224_beamerrorgraph.png}
\caption{\label{beamerrorgraph}Power laws fitted to errors between tracking results for an entire beam under different timesteps.}
\end{figure}

These errors would be large for some accelerator applications but the comparison point for the muon front end is that the solenoids have an inner radius typically of the order of 30\,cm.  Thus the sub-millimetre RMS error at $\dt$=10\,ps and maximum error of 2.3\,mm are good enough to evaluate the transmission.  Note that the maximum error is always much larger than the averaged errors because it picks the `worst' particle, with significant chances of initial trajectory errors being amplified in (for example) the rapidly-changing fringe fields of the solenoids.

The fact that the exponents in the power laws fitted to the graph are much closer to 5 than to 4 is a puzzle.  It is possible that errors are not accumulating as $\dt^5(T/\dt)\propto\dt^4$ but instead cancelling for most of the channel as the particle oscillates from one side to the other, leaving only a fixed number of significant erroneous timesteps ($\dt^5N$).

\clearpage
\section{Magnetic Fields}
The tracking algorithm described in sections \ref{-code-motion} and \ref{-code-rk} requires the magnetic field $\Bv(\x)$ to be evaluated at essentially arbitrary points: the Runge--Kutta evaluation nodes near each particle on any given timestep.  There are several ways of providing this information on a computer, the following sections describe an algorithm for computing the field of solenoids and a field map representation for general magnets, requiring external data from a magnet design program.

\subsection{Off-Axis Series Solution}\label{-code-magnet-offaxis}
A useful technique for calculating cylindrically-symmetric magnetic fields (expressed as functions $B^z(z,r)$ and $B^r(z,r)$) is that if the field on the axis $B^z(z,0)$ is known, Maxwell's equations in free space can be used to solve for a power expansion of the field in $r$ up to the first conductor or object:
\[ B^z(z,r) = \sum_{n=0}^\infty B^z_n(z)r^n \qquad B^r(z,r) = \sum_{n=0}^\infty B^r_n(z)r^n. \]
The functions $B^z_n(z)$ and $B^r_n(z)$ are to be determined for $n\ge0$.  Putting $r=0$ in these equations makes $r^n=0$ for $n\ge1$, leaving only the $r^0$ ($n=0$) terms:
\[ B^z(z,0) = B^z_0(z) \qquad B^r(z,0) = B^r_0(z). \]
The $B^r$ component is the magnitude of the field pointing radially outwards but no such direction exists at $r=0$, forcing $B^r(z,0)=0$ to ensure continuity.  Both $B^z_n(z)$ and $B^r_n(z)$ are now determined for $n=0$.

\newcommand{\er}{\mathbf e_r}
\newcommand{\ez}{\mathbf e_z}
\newcommand{\eth}{\mathbf e_\theta}
For a static magnetic field in free space, Maxwell's equations simplify to $\grad\cdot\Bv = 0$, $\grad\times\Bv = \mathbf0$.  Let $\ez$ and $\er$ be the unit vectors in the $z$ and $r$ directions at any point in space.  Taking first the scalar equation,
\begin{eqnarray*}
0 &=& \grad\cdot\Bv \\
&=& \grad\cdot(B^z\ez+B^r\er) \\
&=& \grad B^z\cdot\ez+B^z\grad\cdot\ez + \grad B^r\cdot\er+B^r\grad\cdot\er \\
&=& \partial_z B^z+B^z\grad\cdot\ez + \partial_r B^r+B^r\grad\cdot\er.
\end{eqnarray*}
Note that $\grad\cdot\ez=0$ and $\grad\cdot\er=1/r$.  The series expansion may be substituted in to get
\begin{eqnarray*}
0 &=& \partial_z B^z + \partial_r B^r + \sfrac1r B^r \\
&=& \sum_{n=0}^\infty {B^z_n}'(z)r^n + \sum_{n=0}^\infty B^r_n(z)nr^{n-1} + \sum_{n=0}^\infty B^r_n(z)\sfrac1r r^n \\
&=& \sum_{n=0}^\infty {B^z_n}'(z)r^n + \sum_{n=0}^\infty B^r_n(z)(n+1)r^{n-1},
\end{eqnarray*}
where $'$ is used to represent the derivative for a function of a single variable.

As the previous equation is true for all $r$, coefficients in $r^n$ may be equated:
\begin{eqnarray*}
0 &=& {B^z_n}'(z) + B^r_{n+1}(z)(n+2) \\
&\Rightarrow& B^r_{n+1}(z) = \frac{-1}{n+2}\ {B^z_n}'(z) \qquad \mbox{for }n\ge0.
\end{eqnarray*}
This is one half of a recurrence relation to obtain the $B^{z,r}_n$ functions for $n>0$.  The other half comes from the magnetic vector equation:
\begin{eqnarray*}
\mathbf0 &=& \grad\times\Bv \\
&=& \grad\times(B^z\ez+B^r\er) \\
&=& \grad B^z\times\ez+B^z\grad\times\ez + \grad B^r\times\er+B^r\grad\times\er.
\end{eqnarray*}
Here, $\grad\times\ez=\grad\times\er=\mathbf0$.  The cross product will select only the perpendicular parts of the gradient, so $\grad f(z,r)\times\er = \partial_z f(z,r) \eth$ and $\grad f(z,r)\times\ez = -\partial_r f(z,r) \eth$.  Thus
\begin{eqnarray*}
\mathbf0 &=& \grad B^z\times\ez + \grad B^r\times\er \\
&=& -\partial_r B^z \eth + \partial_z B^r \eth \\
&=& \left(-\sum_{n=0}^\infty B^z_n(z)nr^{n-1} + \sum_{n=0}^\infty {B^r_n}'(z)r^n \right) \eth.
\end{eqnarray*}
This is now in a form to equate coefficients in $r^n\eth$, giving
\begin{eqnarray*}
0 &=& -B^z_{n+1}(z)(n+1) + {B^r_n}'(z) \\
&\Rightarrow& B^z_{n+1}(z) = \frac{1}{n+1}\ {B^r_n}'(z) \qquad \mbox{for }n\ge0,
\end{eqnarray*}
which is the other half of the recurrence relation.  The relations zig-zag between the $r$ and $z$ functions as $n$ increases.

Using these rules repeatedly,
\begin{eqnarray*}
0 &=& B^r_0(z) = B^z_1(z) = B^r_2(z) = B^z_3(z) = \cdots \\
B^r_1(z) &=& -\sfrac12 {B^z_0}'(z) \\
B^z_2(z) &=& -\sfrac12\sfrac12 {B^z_0}''(z) \\
B^r_3(z) &=& \sfrac14\sfrac12\sfrac12 {B^z_0}'''(z) \\
&\cdots& \\
B^z_{2n}(z) &=& \frac{(-1)^n}{2^{2n} n!^2}{B^z_0}^{(2n)}(z) \\
B^r_{2n+1}(z) &=& \frac{(-1)^{n+1}}{2^{2n+1} n!(n+1)!}{B^z_0}^{(2n+1)}(z).
\end{eqnarray*}
Thus the full field can be calculated up to the radius of convergence of the series, provided that the $n$\th derivatives of the on-axis field function $B^z_0(z)$ are also computable.

\clearpage
\subsection{Axial Field of a Sheet Solenoid}\label{-code-magnet-sheet}
\newcommand{\D}{\mathrm{d}}
\newcommand{\rv}{\mathbf r}
\newcommand{\I}{\mathbf I}
The Biot-Savart Law gives the magnetic field generated by a loop carrying current $I=|\I|$ as 
\[ \Bv(\x) = \frac{\mu_0}{4\pi}\oint \frac{\I\times\rv}{|\rv|^3}\ \D s, \]
where $\rv$ is the vector from the point on the loop to $\x$, $\I$ is the vector current (i.e.\ with direction parallel to the curve) and $\D s$ is the element of arc length.
\comment{ Old scalar version
Suppose there is a circular loop of radius $R$ in the $x$--$y$ plane, centred on the origin.  The field value at the location $(0,0,z)$ is of interest, because the on-axis field of the `sheet solenoid' (of zero thickness but finite length) can be constructed by integrating the fields of many such loops.  Parameterising $\s(\theta)=-R(\cos\theta,\sin\theta,0)$ for $\theta\in[0,2\pi]$ gives $\rv(\theta)=(R\cos\theta,R\sin\theta,z)$ and $\D s = R\D\theta$.  The vector current is $\I = I(-\sin\theta,\cos\theta,0)$.  This gives
\begin{eqnarray*}
\Bv(0,0,z) &=& \frac{\mu_0}{4\pi}\int_0^{2\pi} \frac{(R\cos\theta,R\sin\theta,z)\times I(-\sin\theta,\cos\theta,0)}{(R^2+z^2)^{3/2}}\ R\D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\int_0^{2\pi} (R\cos\theta,R\sin\theta,z)\times (-\sin\theta,\cos\theta,0)\ \D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\int_0^{2\pi} (-z\cos\theta,-z\sin\theta,R\cos^2\theta+R\sin^2\theta)\ \D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\int_0^{2\pi} (-z\cos\theta,-z\sin\theta,R)\ \D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\ (0,0,2\pi R) \\
&=& \frac{\mu_0IR^2}{2(R^2+z^2)^{3/2}}\ \ez.
\end{eqnarray*} }

\begin{figure}
\includegraphics[width=160mm]{fig_232_sheetsolenoid.png}
\caption{\label{sheetsolenoid}Geometry of the current loop and sheet solenoid field evalulation.}
\end{figure}

Suppose there is a circular loop of radius $R$ in the $x$--$y$ plane, centred on the origin.  The field value at the location $(0,0,z)$ is of interest, because the on-axis field of the `sheet solenoid' (of zero thickness but finite length) can be constructed by integrating the fields of many such loops.  Parameterising $\s(\theta)=-R(\cos\theta,\sin\theta,0)=-R\,\er$ for $\theta\in[0,2\pi]$ gives $\rv(\theta)=R\,\er+z\,\ez$ and $\D s = R\,\D\theta$.  The vector current is $\I = -I\,\eth$.  Therefore
\begin{eqnarray*}
\Bv(0,0,z) &=& \frac{\mu_0}{4\pi}\int_0^{2\pi} \frac{-I\,\eth\times(R\,\er+z\,\ez)}{(R^2+z^2)^{3/2}}\ R\,\D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\int_0^{2\pi} -\eth\times(R\,\er+z\,\ez)\ \D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\int_0^{2\pi} R\,\ez-z\,\er\ \D\theta \\
&=& \frac{\mu_0IR}{4\pi(R^2+z^2)^{3/2}}\ 2\pi R\,\ez \\
&=& \frac{\mu_0IR^2}{2(R^2+z^2)^{3/2}}\ \ez.
\end{eqnarray*}

For a sheet solenoid of the same radius occupying the interval $[a,b]$ in the $z$-axis, the on-axis field is the integral of the above expression:
\begin{eqnarray*}
B^z_0(z) &=& \int_{z-b}^{z-a}\frac{\mu_0I_\ell R^2}{2(R^2+x^2)^{3/2}}\ \D x \\
&=& \frac{\mu_0I_\ell R^2}{2}\int_{z-b}^{z-a}\frac{1}{(R^2+x^2)^{3/2}}\ \D x, 
\end{eqnarray*}
where $x$ is the offset of the field evaluation point from each infinitesimal current loop and $I_\ell$ is the current per unit length in the sheet.  Integrating gives the final formula
\begin{eqnarray*}
B^z_0(z) &=& \frac{\mu_0I_\ell R^2}{2}\left[\frac{x}{R^2\sqrt{R^2+x^2}}\right]_{x=z-b}^{z-a} \\
&=& \frac{\mu_0I_\ell}{2}\left(\frac{z-a}{\sqrt{R^2+(z-a)^2}} - \frac{z-b}{\sqrt{R^2+(z-b)^2}}\right).
\end{eqnarray*}

\subsubsection{Expression for the $n$\th Derivative}
The axial field and its derivatives may be expressed more succinctly as follows
\begin{eqnarray*}
B^z_0(z) &=& \frac{\mu_0I_\ell}{2}\left(f(z-a)-f(z-b)\right) \\
{B^z_0}^{(n)}(z) &=& \frac{\mu_0I_\ell}{2}\left(f^{(n)}(z-a)-f^{(n)}(z-b)\right),
\end{eqnarray*}
using the function $f(x)=x/\sqrt{R^2+x^2}$.  To find $f^{(n)}(x)$ it simplifies matters to realise that
\[ f^{(n)}(x) = \frac{p_n(x)}{(R^2+x^2)^n\sqrt{R^2+x^2}} \]
with $p_n(x)$ a polynomial and $p_0(x)=x$ for consistency in the $n=0$ case.  The recurrence relation for these polynomials is extracted in the following way.
\begin{eqnarray*}
f^{(n+1)}(x) &=& \dd{}{x} f^{(n)}(x) \\
\frac{p_{n+1}(x)}{(R^2+x^2)^{n+1}\sqrt{R^2+x^2}} &=& \dd{}{x}\left(\frac{p_n(x)}{(R^2+x^2)^n\sqrt{R^2+x^2}}\right) \\
&=& \frac{{p_n}'(x)}{(R^2+x^2)^n\sqrt{R^2+x^2}} + p_n(x)\frac{-(n+\sfrac12)}{(R^2+x^2)^{n+1}\sqrt{R^2+x^2}}2x \\
&=& \frac{{p_n}'(x)}{(R^2+x^2)^n\sqrt{R^2+x^2}} - \frac{(2n+1)xp_n(x)}{(R^2+x^2)^{n+1}\sqrt{R^2+x^2}}.
\end{eqnarray*}
Multiplying both sides by $(R^2+x^2)^{n+1}\sqrt{R^2+x^2}$ gives
\[ p_{n+1}(x) = (R^2+x^2){p_n}'(x) - (2n+1)xp_n(x). \]
A computer would work out the coefficients of these polynomials once per solenoid by filling in a two-dimensional array, then calculate $f^{(n)}$ and hence ${B^z_0}^{(n)}(z)$ to be used in the off-axis series found in section \ref{-code-magnet-offaxis}.

For additional speed, Muon1 has a version of this technique up to and including $n=3$ (cubic terms) hard-coded into its solenoid field evaluation function.  The off-axis series will not converge beyond the radius of the solenoid and high order terms beyond cubic extend the accurate field region by successively smaller amounts.

\comment{
\subsection{Block Solenoid Integral}
\subsubsection{Gaussian Quadrature Method}
}

\subsection{Field Maps}
\newcommand{\dx}{\delta x}
\newcommand{\dy}{\delta y}
\newcommand{\dz}{\delta z}
\newcommand{\floor}[1]{\left\lfloor#1\right\rfloor}
\newcommand{\ceil}[1]{\left\lceil#1\right\rceil}
Sometimes a magnetic (or electric) field cannot be represented analytically, or perhaps the analytic series defining it is prohibitively time-consuming to evaluate.  In these cases it is effective to precalculate a table of values of the field at certain points.  More advanced techniques such as spline interpolation are also possible, improving accuracy at the expense of computation time.

Currently Muon1 includes the method of `trilinear interpolation' on a regular cuboidal grid.  Let the field map have grid spacings of $\dx$, $\dy$ and $\dz$ in the three axes and contain values of $\Bv=(B^x,B^y,B^z)$ for locations from $(0,0,0)$ to $(P\dx,Q\dy,R\dz)$ inclusive.  This requires $3(P+1)(Q+1)(R+1)$ numeric values in total, which shall be labelled $B^x_{000}$ to $B^x_{PQR}$ for the $x$ components and similarly for $y$ and $z$. 

\newcommand{\Xl}{X_0}\newcommand{\Xh}{X_1}
\newcommand{\Yl}{Y_0}\newcommand{\Yh}{Y_1}
\newcommand{\Zl}{Z_0}\newcommand{\Zh}{Z_1}

Let the field value be required at $(x,y,z)$ in coordinates relative to the field map, which may be a rotated or displaced component in the accelerator frame.  This point is in the cuboid between $\Bv_{\Xl\Yl\Zl}$ and $\Bv_{\Xh\Yh\Zh}$ where $\Xl=\floor{x/\dx}$, $\Xh=\ceil{x/\dx}$ and similarly for $Y$ and $Z$.  Trilinear interpolation derives the field at $(x,y,z)$ from the field values at the eight corners of this cuboid, but is best explained by starting with a simpler case.

Simple (uni-)linear interpolation approximates the field value along one of the edges of our cuboid in the following way:
\[ \Bv(x,Y\dy,Z\dz) \simeq (1-p)\Bv_{\Xl Y Z} + p\Bv_{\Xh Y Z}. \]
The fractional value $p \in [0,1]$ is defined as $(x-\Xl\dx)/\dx$ so that it equals zero at $\Bv_{\Xl Y Z}$ and tends to one when approaching $\Bv_{\Xh Y Z}$ (we only allow it to equal one when at the top edge of the last cell in the field map).  So the field is approximated as a linear function in $x$ that varies smoothly between the nodes.  If we consider this equation for $Y=\Yl$ and $\Yh$ in turn, then linearly interpolate on the $y$-axis between those points, we get the \emph{bilinear} approximation
\[ \Bv(x,y,Z\dz) \simeq (1-q)((1-p)\Bv_{\Xl\Yl Z} + p\Bv_{\Xh\Yl Z}) + q((1-p)\Bv_{\Xl\Yh Z} + p\Bv_{\Xh\Yh Z}) \]
on the $x$--$y$ planes of the grid, where $q=(y-\Yl\dy)/\dy$.  The final step should now be obvious, we interpolate in $z$ between any point on two adjacent $x$--$y$ planes, setting $Z$ to $\Zl$ and $\Zh$:
\begin{eqnarray*}
\Bv(x,y,z) \simeq
(1-r)((1-q)((1-p)\Bv_{\Xl\Yl\Zl} + p\Bv_{\Xh\Yl\Zl}) + q((1-p)\Bv_{\Xl\Yh\Zl} + p\Bv_{\Xh\Yh\Zl})) \\
{} + r((1-q)((1-p)\Bv_{\Xl\Yl\Zh} + p\Bv_{\Xh\Yl\Zh}) + q((1-p)\Bv_{\Xl\Yh\Zh} + p\Bv_{\Xh\Yh\Zh})),
\end{eqnarray*}
with $r=(z-\Zl\dz)/\dz$.  This is the formula for trilinear interpolation as used in Muon1.  It may not be obvious from this expression that the order in which the interpolations were taken (here $x$ then $y$, then $z$) does not affect the final result.  The symmetry is revealed by multiplying out into individual terms
\begin{eqnarray*} \Bv(x,y,z) \simeq
p_0q_0r_0\Bv_{\Xl\Yl\Zl} +
p_0q_0r_1\Bv_{\Xl\Yl\Zh} +
p_0q_1r_0\Bv_{\Xl\Yh\Zl} +
p_0q_1r_1\Bv_{\Xl\Yh\Zh} \\
{} + 
p_1q_0r_0\Bv_{\Xh\Yl\Zl} +
p_1q_0r_1\Bv_{\Xh\Yl\Zh} +
p_1q_1r_0\Bv_{\Xh\Yh\Zl} +
p_1q_1r_1\Bv_{\Xh\Yh\Zh},
\end{eqnarray*}
where $p_0=1-p$ and $p_1=p$, with analogous definitions for $q$ and $r$.  All eight possible binary combinations of subscripts (corresponding to the cuboid vertices) are used to generate all the terms, without preference for a particular axis.

\begin{figure}
\includegraphics[width=160mm]{fig_233_fieldmaperror.png}
\caption{\label{fieldmaperror}(Left) Plot of the on-plane magnetic fields in a coarse (10\,cm grid spacing) field map, where the field vectors are perpendicular to the plane of the diagram and the signed magnitude is shown (scales are in Tesla).  (Right) Plot of the error bound derived from second derivatives for each square in this plane.  The desired path of the particles is from the bottom-left of the view to the top-right, through the regions of low error.}
\end{figure}

If $x<0$, $x>P\dx$, or a similar situation on the $y$- or $z$-axes, then the point is outside the range of the field map and $\Bv=\mathbf{0}$ is returned.  This means one must be careful not to introduce discontinuities by having significant field magnitudes at the edges where particles may enter or leave the field map, because these can degrade the convergence of the tracking method (as discussed in section \ref{-code-rk-single}).  However, Muon1 does permit multiple field maps (or other magnetic elements) to overlap with each other, in which case the field values from the different magnets are added together to give the total field.  This field will still be physically valid because Maxwell's equations in free space are linear in $\Bv$ (this is known as the `superposition principle' for magnetic fields).

The accuracy of linear interpolation depends on the second and higher derivatives of the $\Bv$ field and the size of the mesh cells.  It is always true that if there are small features in the field that fall in between grid sampling points, they will not be approximated well, so we assume that the grid is fine enough for the error to be dominated by the leading term in the Taylor series that is different between the approximation and the actual function.  Note that linear interpolation is exact for linear functions, so the terms of interest will be quadratic.  Furthermore, for trilinear interpolation, even the quadratic mixed terms $xy$, $xz$ and $yz$ are approximated exactly because they are linear in $x$, $y$ and $z$ individually at each stage of the multidimensional interpolation procedure given above.  So the quadratic terms of interest are in general:
\[ \mathbf{Q}(x,y,z) = \mathbf{q}_x x^2 + \mathbf{q}_y y^2 + \mathbf{q}_z z^2, \]
where the $\mathbf{q}$ are arbitrary vector coefficients.  The three terms above will be dealt with separately by the algorithm as it interpolates along each axis in turn.  The error for $x^2$ will be a quadratic with the same leading coefficient but the linear interpolation subtracted so that it equals zero at the neighbouring points $X_0\dx$ and $X_1\dx$.  There is only one such function, $(x-X_0\dx)(x-X_1\dx)$, so the leading term error, $\mathbf{Error}(x,y,z)$, is 
\[ \mathbf{q}_x (x-X_0\dx)(x-X_1\dx) + \mathbf{q}_y (y-Y_0\dy)(y-Y_1\dy)+ \mathbf{q}_z (z-Z_0\dz)(z-Z_1\dz). \]
This becomes more informative when we note that, considering the local Taylor series of $\Bv$ truncated to quadratic order, $\mathbf{q}_x \simeq \frac12\pdtwo{\Bv}{x}(x,y,z)$.  Also we are only interested in values of $x \in [X_0\dx,X_1\dx]$, an interval of length $\dx$ with a root of $(x-X_0\dx)(x-X_1\dx)$ at either end.  The extremum of this function is at the centre of this interval, $\frac12\dx$ distant from either root and the function has value $-\frac14\dx^2$ there.  Thus if cubic and higher terms can be neglected, we may bound the error anywhere in the cuboid:
\[ |\mathbf{Error}(x,y,z)| \le \frac18\left(\mod{\pdtwo{\Bv}{x}}\dx^2 + \mod{\pdtwo{\Bv}{y}}\dy^2 +\mod{\pdtwo{\Bv}{z}}\dz^2\right). \]

The results of applying this formula to a field map as used in the Rees bending chicane~\cite{ReesChicane} simulation is shown in figure \ref{fieldmaperror}.  Large errors exist around where the field was sampled inside iron pole pieces of the magnet, but the errors are smaller (1\% level) along the path that the particles are intended to traverse.  The manifestation of field errors as particle position errors is dependent on the optics of the beamline in question, there is no good general-purpose error bound.  More favourably, total bending is proportional to the integrated field $\int\Bv\ \D\ell$ along the particle trajectory, so there is some scope for error cancellation because negative and positive convexity regions, leading to under- and over-estimation in the field components, tend to alternate along the path.

\section{Particle Decays}\label{-code-decay}
The muon front end is unusual in that the particles being transmitted (initially $\pi^\pm$) will decay (mainly into $\mu^\pm$) on a timescale comparable to how long it takes them to traverse parts of the accelerator, specifically the decay channel section.  The mean lifetime of a stationary charged pion is $\tau_{\pi^\pm} = $ 26.033\,ns \cite{PDG-Review}, giving a typical 250\,MeV pion a mean path length of $v\gamma\tau = $ 20.338 metres.

In the rest frame of the particle, decay is quantum mechanically a perfect Poisson process.  Therefore instances of actual decay times, measured as proper times since the particle's creation, can be generated using a probability distribution such that $P(t) \propto e^{-t/\tau}$.  The cumulative distribution function for this is
\[ F(t) = 1-e^{-t/\tau}, \qquad (t\ge0)\]
which can be inverted to give
\[ F^{-1}(x) = -\tau \ln(1-x). \qquad (0\le x<1)\]
The reason $F^{-1}$ is useful is that taking uniformly distributed numbers $x \in [0,1)$ from the computer's (pseudo-)random number generator will ensure that $t=-\tau \ln(1-x)$ has the desired distribution for the decay times \cite{RandomDistribution}.  These times are generated when the particle starts and compared to the particle's internal proper time clock, which is incremented by $\dt/\gamma$ each timestep of the simulation, to determine when a decay is triggered.

\subsection{Statistical Weighting and Multiple Decays}\label{-code-decay-multi}
\newcommand{\Var}{\mathrm{Var}}
Chapter \ref{-target} describes how Muon1 takes output from a hadronic particle showering code as initial data for its tracking.  The (macro-)particles in this sort of output are often `weighted' according to the relative probability of each being produced, so these weights must be retained during tracking and used correctly in evaluating the muon transmission.  For example, if each particle $i$ has weight $w_i$,
\[ \mbox{\% Muon transmission}\ =\ 100\ \frac{\displaystyle\sum_{\mathrm{Transmitted}\atop\mathrm{muons}\ i}w_i}{\displaystyle\sum_{\mathrm{Muons}\ i} w_i}\ =\ 100\ \frac{T_\mu}{W_\mu}. \]

If the indices $i$ are permuted in a random order, then the transmission of muon $i$ is a random event with probability $p\simeq T_\mu/W_\mu$ (strictly this ratio is only an \emph{estimate} of the true value of $p$).  Thus the weight transmitted by this muon is $w_i$ with probability $p$ and 0 with probability $1-p$, giving a mean of $pw_i$ and variance $pw_i^2-(pw_i)^2 = p(1-p)w_i^2$.  Since variances add linearly, the variance of the transmitted weight is
\[ \Var(T_\mu)\ =\ \sum_{\mathrm{Muons}\ i} p(1-p)w_i^2\ \simeq\ \frac{T_\mu(W_\mu-T_\mu)}{W_\mu^2}\sum_{\mathrm{Muons}\ i} w_i^2, \]
which gives the standard deviation of the muon yield from tracking (ignoring pion production uncertainties on $W_\mu$) as
\[ \sigma_\mathrm{\%muons}\ \simeq\ 100\ \frac{\sqrt{T_\mu(W_\mu-T_\mu)}}{W_\mu^2}\sqrt{\sum_{\mathrm{Muons}\ i} w_i^2}. \]
For fixed transmission and total muon weight, the final term is made smaller by having more macro-particles with smaller weights.  Many pions (roughly three quarters) are lost in the very early stages of the simulation before they have time to decay, leaving relatively few pions later on.  If each pion with weight $w$ is instead treated as $N$ pions with weight $w/N$, this will produce a greater number of decay products (muons) with which to evaluate the transmission.  However, as the original pion will remain on the same trajectory unless it decays, there is no reason to actually track $N$ copies of it, so Muon1 treats it as a pion with weight $w$ decreasing to $\frac{N-1}{N}w$, $\frac{N-2}{N}w$, etc. each time it decays.  This does not increase the effective number of particles in the simulation by a full factor of $N$ because the number of original pions is still fixed, but it does help, especially when working under an optimisation in which small differences in yield can give clues as to the direction of better designs.

\subsection{Two-body Algorithm}
The original implementation of particle decays in the Muon1 tracking code only admitted two-body processes.  These can be dealt with by assuming the rest frame of the parent particle and producing two decay products with equal and opposite isotropically-selected momenta and magnitude such as to conserve energy.  This has now been replaced by the more general many-body decay algorithm described in section \ref{-code-decay-mbody}.

\newcommand{\bbeta}{\B{\beta}}
Even the simpler algorithm, however, is not free of implementation details.  To transform the decay products' momenta back to the laboratory frame would be easy in one dimension, by Lorentz boosting the energy-momentum vector by the velocity $v=\beta c$:
\[ \Lambda(\beta)\vectwo{E_t}{pc}
= \left[\begin{array}{cc}\gamma&\beta\gamma\\\beta\gamma&\gamma\end{array}\right]\vectwo{E_t}{pc}
= \vectwo{\gamma E_t + \beta\gamma pc}{\gamma pc + \beta\gamma E_t}. \]
Unfortunately, the decaying particle will not be travelling along a single axis and the boost formula for a general vector velocity $\vv = \bbeta c$ is required.  To avoid dealing with multiple rotation matrices, the momentum can be decomposed into a part perpendicular to $\bbeta$, which remains unchanged, and a parallel part that undergoes the transformation:
\[ \p = \p_\parallel + \p_\perp \qquad\mbox{where}\qquad \p_\parallel = \frac{\p\cdot\bbeta}{\beta^2}\bbeta \qquad\mbox{and}\qquad \p_\perp = \p - \frac{\p\cdot\bbeta}{\beta^2}\bbeta. \]
Here, $\beta=|\bbeta|$ and $\gamma$ is defined from this scalar beta.  Letting only $\p_\parallel$ be transformed, the one dimensional equivalent of $p$ is $(\p\cdot\bbeta)/\beta$, which satisfies $\p_\parallel=p(\bbeta/\beta)$.  The result of the general Lorentz transformation is then
\[ \Lambda(\bbeta)\vectwo{E_t}{\p c}
= \vectwo{\gamma E_t + \gamma(\p\cdot\bbeta)c}{\gamma\p_\parallel c + \bbeta\gamma E_t + \p_\perp c}, \]
where terms like $\beta\gamma E_t$ from the one-dimensional formula have been multiplied by $\bbeta/\beta$ to give them the correct direction.

\newcommand{\phat}{\hat \mathbf p}
All that remains is to calculate the momentum of the decay products in the rest frame of the parent particle.  Suppose they have masses $m_1$ and $m_2$ and will acquire equal and opposite momenta of magnitude $p$ on decay.  As momentum is conserved by construction, the one condition is energy conservation:
\[ mc^2 = \sqrt{(m_1c^2)^2+(pc)^2} + \sqrt{(m_2c^2)^2+(pc)^2}. \]
This may be solved for $p$ using the ``$Q = \sqrt{R}+\sqrt{S}$'' algorithm described in section \ref{-code-decay-probdens}.

A randomised vector direction $\phat$ is needed to generate the momenta $\p_1=p\phat$ and $\p_2=-p\phat$ in the parent particle's rest frame.  In Muon1, $\phat$ is generated uniformly on the surface of a unit sphere by taking random points $\x$ within the cube $[-1,1]^3$ until one falls within the unit sphere (i.e. $|\x|\le1$) and then returning $\phat = \x/|\x|$.

\subsection{Many-body Decay Algorithm}\label{-code-decay-mbody}
The problem of an $n$-body decay imposes four constraints on the $3n$ degrees of freedom found in the momentum of the decay products: three for overall conservation of momentum and one for energy.  The final states can therefore be found on a $(3n-4)$-dimensional manifold in the multi-particle phase space.  This is two-dimensional for two-body decays (and can be made into a sphere by the method and symmetry argument above), but even for three-body decays it is already five-dimensional and rotational symmetry can remove at most three of these.

Faced with this problem of a complicated surface to generate the distribution on, a Monte Carlo routine that covers the right surface with points (at some known density) is obtained first and then the density is corrected afterwards by rejecting a calculated proportion of them and re-running the original routine as necessary (this is known as \textit{rejection sampling}).  Formally, the first routine generates the primal probability density $F(\p_i)$ on the feasible manifold, then any other desired distribution $f(\p_i)$ can be derived from this by only accepting each primal point with probability $\propto f(\p_i)/F(\p_i)$.  Note that this should not be larger than 1, so the ratio must be bounded above and scaled accordingly.  

\subsection{The Probability Density (spin averaged)}\label{-code-decay-probdens}

From the 2004 Particle Physics Booklet, section 38.4, the probability of a particle with 4-momentum $P$ and randomly-selected spin decaying into $n$ particles of 4-momenta $p_1,p_2 \ldots p_n$ is governed by
%
\begin{eqnarray*}
\mathcal P &\propto& \delta^4(P-\sum_{i=1}^n p_i)\prod_{i=1}^n \frac{\D^3 \p_i}{E_i} \\
&=& \delta(E-\sum_{i=1}^n E_i)\delta^3(\mathbf P-\sum_{i=1}^n \p_i)\prod_{i=1}^n \frac{\D^3 \p_i}{E_i}.
\end{eqnarray*}
To simplify the derivation, in this and the next subsection only, the $E$ and $E_i$ will always be total energies ($E_t$ elsewhere) and units will be used such that $c=1$.

The delta functions can be multiplied into the main coefficient using the following rule, where $f$ is a function with one root $f(a)=0$:
%
\[ \delta(f(x))g(x) = \frac{g(a)}{|f'(a)|}\delta(x-a). \]

Applying this three times, considering the probability expression as a function of $p_n^x,p_n^y$ and $p_n^z$ in turn, reduces it to:
%
\[ \frac{\D^{3n} \mathcal P}{\D^3 \p_1 \D^3 \p_2 \ldots \D^3 \p_n} \propto \left[\delta(E-\sum_{i=1}^n E_i)\prod_{i=1}^n \frac{1}{E_i}\right]\delta^3\left(\p_n-(\mathbf P-\sum_{i=1}^{n-1}\p_i)\right), \]
%
which when integrated over $\p_n$ gives
%
\[ \frac{\D^{3n-3} \mathcal P}{\D^3 \p_1 \D^3 \p_2 \ldots \D^3 \p_{n-1}} \propto \delta(E-\sum_{i=1}^n E_i)\prod_{i=1}^n \frac{1}{E_i}, \]
%
after which the substitution $\p_n=\mathbf P-\sum_{i=1}^{n-1}\p_i$ should be used to determine the last momentum and $E_n$.

This needs to be integrated one more time to remove the last delta function, so a degree of freedom will be taken from $\p_{n-1}$.  Let $\p_* = \mathbf P - \sum_{i=1}^{n-2}\p_i$ so that $\p_{n-1}+\p_n = \p_*$ to conserve 3-momentum.  Now perform a Lorentz transformation into a primed frame where $\p'_* = \mathbf 0$, so that $\p'_{n-1} = -\p'_n = p\phat$.  Integrating over $p \ge 0$ will remove the delta function, leaving the two degrees of freedom in $\phat$ parameterising the remaining freedom of these last two momenta.

Starting with the expression written in the primed frame:
%
\[ \frac{\D^{3n-3} \mathcal P}{\D^3 \p'_1 \D^3 \p'_2 \ldots \D^3 \p'_{n-1}} \propto \delta(E'-\sum_{i=1}^n E'_i)\prod_{i=1}^n \frac{1}{E'_i} \]
%
...change $\p'_1$ through $\p'_{n-2}$ back to the original frame using $\D^3\p'_i = (E'_i/E_i)\D^3\p_i$:
%
\[ \frac{\D^{3n-3} \mathcal P}{\D^3 \p_1 \D^3 \p_2 \ldots \D^3 \p_{n-2} \D^3 \p'_{n-1}} \propto \delta(E'-\sum_{i=1}^n E'_i)\frac{1}{E'_{n-1}E'_n}\prod_{i=1}^{n-2} \frac{1}{E_i} \]
%
...and then use the substitution, which implies $\D^3\p'_{n-1} = p^2\D p\D^2\phat$, to get:
%
\[ \frac{\D^{3n-4} \mathcal P}{\D^3 \p_1 \D^3 \p_2 \ldots \D^3 \p_{n-2} \D^2\phat} \propto \delta(E'-\sum_{i=1}^n E'_i)\frac{p^2\D p}{E'_{n-1}E'_n}\prod_{i=1}^{n-2} \frac{1}{E_i}. \]

Now that varying $p$ is the concern, a ``constant'' part may be removed from the argument of the delta function
\[ \delta(E'-\sum_{i=1}^n E'_i) = \delta(E'_*-(E'_{n-1}+E'_n)), \]
where $E'_* = E' - \sum_{i=1}^{n-2} E'_i$.  The modulus of the derivative of this argument:
\begin{eqnarray*}
\dd{}{p}(E'_{n-1}+E'_n) &=& \dd{}{p}\left(\sqrt{p^2+m_{n-1}^2}+\sqrt{p^2+m_n^2}\right) \\
&=& \frac{p}{\sqrt{p^2+m_{n-1}^2}} + \frac{p}{\sqrt{p^2+m_n^2}} \\
&=& p\left(\frac{1}{E'_{n-1}} + \frac{1}{E'_n}\right) = p\frac{E'_{n-1}+E'_n}{E'_{n-1}E'_n},
\end{eqnarray*}
...must be divided out when the argument of the delta function is linearised:
\begin{eqnarray*}
\frac{\D^{3n-4} \mathcal P}{\D^3 \p_1 \D^3 \p_2 \ldots \D^3 \p_{n-2} \D^2\phat} &\propto& \delta(p-p_0)\frac{p\D p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2} \frac{1}{E_i} \\
&=& \left.\frac{p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{1}{E_i}\right|_{p=p_0},
\end{eqnarray*}
with $p_0$ being the value of $p \ge 0$ for which energy is conserved.

$p_0$ is the root of the delta function, so
\[ E'_* = E'_{n-1}+E'_n = \sqrt{p_0^2+m_{n-1}^2}+\sqrt{p_0^2+m_n^2}, \]
which is of the form
\begin{eqnarray*}
& Q = \sqrt{R}+\sqrt{S} &\\
\Rightarrow& Q-\sqrt{R} = \sqrt{S} &\\
\Rightarrow& Q^2-2Q\sqrt{R}+R = S &\qquad (*)\\
\Rightarrow& Q^2+R-S = 2Q\sqrt{R} &\\
\Rightarrow& (Q^2+R-S)^2 = 4Q^2R. &\qquad (*)
\end{eqnarray*}
This may be used on the expression now, but note that in the squaring operations marked (*) the implication goes only one way, so any value of $p_0$ derived using the following must be checked back to make sure the squaring operation did not equate things that originally had opposite signs!  The squared-up expression is
\[ ({E'_*}^2+m_{n-1}^2-m_n^2)^2 = 4{E'_*}^2(p_0^2+m_{n-1}^2), \]
giving the root explicitly as
\[ p_0 = \sqrt{\frac{({E'_*}^2+m_{n-1}^2-m_n^2)^2}{4{E'_*}^2}-m_{n-1}^2}. \]

\subsection{The Primal Distribution}

The previous section gave the probability distribution with respect to an element of the momenta $\p_1 \ldots \p_{n-2}$ and the unit direction $\phat$ governing the last two particles.  Thus if a uniform distribution is used for the $n-2$ momenta and an isotropic one for $\phat$ in the primal distribution, the $(3n-4)$-dimensional probability density will be exactly proportional to the selection probability.

Generating an isotropic $\phat$ is easy; what is not so obvious is how to choose a `domain' in which the $\p_i$ are uniformly spread.  As $|\p_i| \le E_i \le E = m_0$ (i.e.\ the mass of the parent particle), there is at least a crude limit on how large the momenta can be.  Here note that many of these choices for $\p_1 \ldots \p_{n-2}$ miss the manifold entirely, a fact which becomes apparent when attempting to enforce conservation of energy leads to particles with negative energy, or taking square-roots of negative quantities.  In these cases, the sample should be rejected, so in effect there are two levels of rejection sampling, one to get onto the manifold and a second to adjust the density.  The first level does not affect the relative proportions between any of the probabilities within the manifold, so has no adverse consequences other than wasted CPU time.

The final ingredient for a workable implementation of rejection sampling is an upper bound on the probability density derived in the previous section, so that it may be divided out to give selection probabilities of no more than 1.  By noting that $E_i \ge m_i \Rightarrow 1/E_i \le 1/m_i$, one obtains
\[ \frac{p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{1}{E_i} \le \frac{p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{1}{m_i}, \]
leaving only the front term to deal with.  Remembering that $|\p'_{n-1}|=|\p'_n|=p$, it follows that $E'_{n-1} \ge p$ and $E'_n \ge p$ so that the denominator is at least $2p$, resulting in
\[ \frac{p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{1}{E_i} \le \frac{1}{2}\prod_{i=1}^{n-2}\frac{1}{m_i}. \]
The probability to use is therefore
\[ \mathcal P_1 = \frac{2p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{m_i}{E_i}. \]

This is workable for several cases, but when there are particles of small mass (such as electrons or neutrinos) in the decay products, the ratio $m_i/E_i=1/\gamma_i$ becomes very small when these acquire a significant fraction of the mass--energy of the heavier parent particle.  The formula does not select any samples at all when photons are produced!  The problem arises from the choice of a uniform momentum distribution for each of the first $n-2$ particles not being a very good `fit' to the $1/E_i$ in the probability density, particularly when the energy is dominated by momentum rather than rest mass.

With this in mind, the bound can be modified to use the fact that $E_i = \sqrt{\p_i^2+m_i^2} \ge \max\{|\p_i|,m_i\}$ so $1/E_i \le \min\{1/|\p_i|,1/m_i\}$.  However, this is no longer a constant with respect to $\p_i$, so to have it divided out, a primal distribution must be generated with $F(\p_i) \propto \min\{1/|\p_i|,1/m_i\}$.  This is uniform for $|\p_i| \le m_i$, so retaining the previous cutoff of $|\p_i| \le m_0$, the ratio of the uniform part to the outer part is
\[ \frac{4}{3}\pi m_i^3 \frac{1}{m_i} : \int_{m_i}^{m_0} 4\pi|\p_i|^2\frac{\D|\p_i|}{|\p_i|} = \frac{m_i^2}{3} : \frac{m_0^2-m_i^2}{2}. \]
Since $2|\p_i|\D|\p_i| = \D|\p_i|^2$, the outer part corresponds to choosing $|\p_i|^2$ uniformly on $[m_i^2,m_0^2]$.  Generating events from these two parts in the ratio above, for each $i$ up to $n-2$, gives the required primal distribution.

Now dividing out $\min\{1/|\p_i|,1/m_i\}$ instead of just $1/m_i$ gives the new selection probability as 
\[ \mathcal P_2 = \frac{2p}{E'_{n-1}+E'_n}\prod_{i=1}^{n-2}\frac{\max\{|\p_i|,m_i\}}{E_i}, \]
which is clearly better conditioned, as terms in the product part never fall below $1/\sqrt{2}$.

\subsection{Results and Efficiency}

The two versions of the algorithm described above were implemented and tested on a variety of decay modes for the kaon: the results are shown in table \ref{decayeff}.  Note that for 3-body and higher decays, there is sometimes a choice of which particles to associate the `special' momenta $\p_{n-1}$ and $\p_n$ with.  This affects the speed of the algorithms, particularly the first version, so these possibilities are broken down individually in the cases where the particles have different mass.

The second version of the algorithm using $\mathcal P_2$ displays a much more consistent speed across decays with the same number of daughter particles, with no decays in the test set it could not solve.  Time increases rapidly with number of daughter particles but since no more than four are required for the particles in Muon1 and each calculation is fairly fast, the $\sim$650 iterations needed for 4-body decays are not a major problem.

\begin{table}
\caption{\label{decayeff}Mean number of primal samples required to generate one valid decay.  Figures are an average over 10000 successful decays except where another number of decays is indicated in parentheses.  `inf' denotes that it was infeasible to run the algorithm, as no valid decays were generated after $10^7$ samples.}
\begin{center}
\begin{tabular}{lll}
\hline
Decay (special pair)&Using $\mathcal P_1$&Using $\mathcal P_2$\\
\hline
$K^+\rightarrow e^+ \nu_e$&1&1\\
$K^+\rightarrow \mu^+ \nu_\mu$&1.0483&1.0485\\
$K^+\rightarrow \pi^0 e^+ \nu_e$\\
\quad $(\pi^0,e^+)$&inf&6.7499\\
\quad $(\pi^0,\nu_e)$&4123.71 (2425)&6.5441\\
\quad $(e^+,\nu_e)$&15.7419&6.4251\\
$K^+\rightarrow \pi^+ \pi^0 \pi^0$\\
\quad $(\pi^+,\pi^0)$&151.285&60.5826\\
\quad $(\pi^0,\pi^0)$&146.47&61.5364\\
$K^+\rightarrow \pi^+ \pi^+ \pi^-$&184.181&75.1907\\
$K^+\rightarrow \pi^+ \pi^- e^+ \nu_e$\\
\quad $(\pi^+,\pi^-)$&inf&666.969\\
\quad $(\pi,e^+)$&inf&652.936\\
\quad $(\pi,\nu_e)$&$8\times 10^5$ (25)&654.098\\
\quad $(e^+,\nu_e)$&3746.72 (2669)&636.432\\
\hline
\end{tabular}
\end{center}
\end{table}

\subsection{Dalitz Plot Test}

A standard plot that can be used to test the correctness of the routine is the \textit{Dalitz plot} of $m_{12}^2$ against $m_{23}^2$, where $m_{ij}^2 = (m_i+m_j)^2-|\p_i+\p_j|^2$.  The correct phase-space distribution ought to be uniformly spread on the allowed region when projected into this plane.  Such a plot is shown in figure \ref{dalitz} generated from many runs of the $\mathcal P_2$-based version of the algorithm.

\begin{figure}
\includegraphics[width=160mm]{fig_247_dalitz.png}
\caption{\label{dalitz}Dalitz plot for the $K^+\rightarrow \pi^+ \pi^+ \pi^-$ decay, showing uniform coverage of the allowed area.}
\end{figure}

The uniformity of the enclosed area is visually apparent, as is the sharpness of the edge in phase space of feasible decays.  This provides additional confidence that no errors have been made in the coding of this mathematically complicated routine.

\clearpage
\section{Collision Detection}\label{-code-collide}
When a particle goes outside the accelerator aperture, for instance into the coil of a solenoid, it is removed from the simulation and counted as a loss\footnote[2]{In reality, some particles (particularly muons) are not absorbed and can scatter back into the aperture but Muon1 does not include this possibility.  This makes a slightly pessimistic error in yield, but the probability of a muon that scatters out of the walls rejoining the beam for an extended period is minimal.}.  The code should be able to tell, similarly, when a particle has entered a region of scattering material or passed through a surface at which the beam is being logged or an aperture restriction imposed.  Proximity detection is also needed to determine which components contribute significantly to the magnetic field at a given point in space.  More complex collisional algorithms are needed for the scattering calculation itself, but this is presented in sections \ref{-cool-algorithm} and \ref{-cool-integration}.

\subsection{Proximity and Bounding Boxes}\label{-code-collide-bbox}
\newcommand{\num}[1]{\mathrm{\#\ #1}}
For tracking codes that step in $z$, it is often unambiguous which component a particle is inside, so the field and aperture restriction can be applied directly.  For codes that step in~$t$ there will be particles at a range of $z$ that may be in different components.  The simplest method would be to check against every component to determine the field and aperture set (the set containing all allowed locations for particles):
\[ \Bv(\x) = \sum_{n=1}^\num{Components}\Bv_{\mathrm{Component}\ n}(\x) \qquad A = \bigcap_{n=1}^\num{Components} A_{\mathrm{Component}\ n}. \]
A direct implementation of this on a computer unfortunately adds a calculation of length $(\num{Particles})(\num{Components})$ to each timestep.  This is bad scaling behaviour in the majority of situations where only a few components have any significant effect for each particle.  Note that the superposition principle used for the magnetic fields here means that components containing saturating iron or other nonlinear materials must not be placed too far into the fringe fields of others; a solution is to treat `interacting' objects as a single contiguous component using a field map.  Note also that a collision is defined as a particle moving outside the allowed aperture $A$ and hence into its complement $\bar{A} = \mathbb{R}^3 \backslash A$, which means that if the effects of each component are to be localised, the `solid' collision zone $\bar{A}$ must be bounded, as opposed to some codes (particularly in $z$) in which the disallowed region may extend to infinity.

The efficiency problem mainly hinges on the detection of proximity to components.  Once the set of nearby components has been determined, only the $\Bv$ fields from these need to be summed and only collisions with these components need to be checked for.  If this detection is performed by a scan of all components on every timestep, it also risks bad scaling behaviour.  However, the calculation that is being repeated is now just proximity detection rather than the full collision and field calculation; it is therefore desirable to make this as fast to compute as possible.  The approach taken is of bounding cuboids $C$ constructed such that
\begin{eqnarray*}
\{\x:|\Bv(\x)|\le\epsilon_B\} \cup \bar{A} &\subseteq& C = [x_1,x_2]\times[y_1,y_2]\times[z_1,z_2],
\end{eqnarray*}
so only 6 comparisons (and possibly fewer) are required to determine whether a point $(x,y,z)$ is within $C$, which contains all of the collision zone and significant field region.

\subsubsection{Speed-of-Light Optimisation}
\newcommand{\y}{\mathbf y}
An additional optimisation exists so that the scan for nearby components is only necessary on every $N$\th timestep, although there is some tradeoff.  If a list of nearby components is to be valid for $N$ timesteps (a time $N\dt$) from the time it is constructed, it must refer to all components the particle could possibly enter into the bounding cuboid of during that time.  The particle's trajectory is not known in advance but we would hope that it will remain within the light cone given by $\Delta x\le c\Delta t\le cN\dt$.  The set of all points that can reach $C$ as defined above within time $N\dt$ is
\begin{eqnarray*}
&&\mathrm{Expand}_{cN\dt}(C) = \{\x:\exists \y\in C, |\y-\x|\le cN\dt\} \\
&&\subseteq [x_1-cN\dt,x_2+cN\dt]\times[y_1-cN\dt,y_2+cN\dt]\times[z_1-cN\dt,z_2+cN\dt],
\end{eqnarray*}
so we may just use a larger cuboid, $C$ extended by $cN\dt$ outwards in every direction, as a valid bounding box for use on $N$ successive steps.  The tradeoff in this optimisation is that if $N$ is made too large, the cuboids will also become large and time will be spent adding the fields of (and checking for collisions with) components that are far away from the particle but could have been reached by it in the time $N\dt$ since the nearby component list was generated.

\subsubsection{Proximity Grid Optimisation}
The scan can be made even faster by using the principle of a \emph{hash table}, one of the fastest known ways of speeding up search procedures, at the expense of some extra memory usage.  A three dimensional cuboidal grid is constructed, in Muon1's case up to 50 cells on a side, covering the bounding cuboid of the entire accelerator.  In each cell is put a list of the components that have bounding boxes somewhere in the volume of that cell.  Thus when it is time to recalculate the nearby components for a particle, the cell in the grid containing that particle is looked up and the subsequent search for bounding boxes restricted to just those components listed in that cell.

The upshot of these optimisations, applied in Muon1 with $N=10$ for the `speed-of-light' optimisation, is that the time taken by proximity detection is very small compared to the time used for Runge-Kutta stepping.

\subsection{Collision Detection Regions for Components}
Muon1 defines collision regions automatically for certain components.  The collision zone used for a sheet solenoid of length $L$ and radius $R$ is by default
\[ \bar{A}_\mathrm{sol} = \{\x: 0\le z\le L, R\le r\le 5R\}, \]
where $(z,r)$ are $\x$ expressed in cylindrical coordinates coaxial with the solenoid, with origin at the centre of one end.  The factor 5 can be changed by the user by specifying the \texttt{OuterRadius} attribute of the \texttt{Solenoid} component type to be some length other than $5R$, see section \ref{-optimiser-lattice} for how components are input to Muon1 using lattice files.

The other object that is specifically solid in the tracking code is the rod-shaped target, modelled as a solid cylinder that absorbs particles reentering it:
\[ \bar{A}_\mathrm{rod} = \{\x: 0.005L\le z\le 0.995L, r\le 0.99R\}. \]
The coordinates are as before, but the peculiar 1\% shrinkage of the zone is to make sure that particles starting exactly on the surface, which have some rounding in their coordinates as output from the particle production code, are never erroneously destroyed at their start location.

In addition to these two rules, Muon1 has a more general system that allows pure collision regions (or regions of material) to be specified separately from particular accelerator components.  These are known as \texttt{Blockage} components.  As the lattice format supports arbitrary displacements and rotations of objects from any point in the beamline and the beamline location may be left constant by not specifying a \texttt{Length} attribute for these components, complex shapes may be built up from the primitive blockages.  The primitives supported as of Muon1 version 4.44 are cuboids, cylinders, spheroids (including spheres), annuli and toroids.  Cones may have some use in the future.

As well as solid objects it is often desirable to impose a restriction on particles going through a plane in the accelerator, usually a plane perpendicular to the accelerator axis.  Types of \texttt{Aperture} component were introduced for this purpose, which detect when a particle has crossed the plane, calculate the relative coordinates on the plane of the crossing point and check against the aperture restriction.  Currently only circular and rectangular apertures are supported, although additionally the \texttt{MinEnergy} and \texttt{MaxEnergy} attributes may be set to stop particles outside a given energy range.  Apertures are also used as the finishing component, which stops all particles on the plane and flags them as `finished' (unless they were outside the aperture), which is used in figure-of-merit calculation.

\subsection{High-accuracy Isosurface Method}\label{-code-collide-iso}
Detecting exactly where a particle crosses a surface (an aperture plane or the boundary of a collision zone) is a common operation in all of the above mechanisms.  Initial implementations used a simple method that checked whether the particle was inside a collision zone of any nearby component on each timestep and stopped it at its current location if it was.  Apertures were dealt with by waiting for the current and old (previous timestep) positions of a particle to be on opposite sides of the plane and then taking a straight line between them to find the intersection with the aperture itself.

However these simple algorithms suffer from some problems.  The point of using Runge--Kutta integration was to allow accurate tracking with a medium-sized timestep: for the chosen $\dt=10^{-11}$s, $c\dt\simeq 3$\,mm is large enough to jump over the corner of, for instance, a solenoid's annular region in a single step (see figure \ref{isocollision}).  This will change the transmission figure, which is constrained ultimately by the bore sizes, because the bore radius (which has been as small as 15\,cm in simulations) is now up to 2\% larger and 4\% bigger in area.  This becomes worse (up to 8\% effect on transmission) when it is considered that the transverse bores are really clipping the amplitude in 4-dimensional transverse phase space.  The procedure of taking a straight line to detect the collision with an aperture plane is also inaccurate, though this is a second order effect in step length so smaller.

\begin{figure}
\includegraphics[width=160mm]{fig_253_isocollision.png}
\caption{\label{isocollision}Diagram of how a (slightly exaggerated!) timestep may jump a particle over the corner of the collision region (red particle) or miss the collision region (green particle).  The dotted line is the axis of symmetry of the solenoid being considered.}
\end{figure}

The solution is to detect when collisions with surfaces may have occurred and solve iteratively for the collision point.  To detect collisions reliably for a solid object requires more than just checking if the particle is in $\bar{A}$ at each timestep.  Instead, the solid object's surface is defined by smooth isosurfaces that extend outside the object from the corners if necessary: these are the thin lines shown in figure \ref{isocollision}.  An isosurface is the solution set of an equation $f(\x)=0$ where $f$ is some smooth function.  If the particle has crossed \emph{any} of these surfaces during a timestep, which can be easily seen by one of the $f$s changing sign, the intersection points are solved for and checked to see if they fall on the surface of the collision region or on some part of the isosurface extending into empty space.  This method is still not perfect because it will not detect skimming collisions when a particle curves into and then out of an isosurface during a single timestep, but it improves things greatly, making missed collisions a second order (curvature) effect.

Solving for the collision point can be done by a number of standard methods.  Repeated bisection would work even for non-isosurfaces but as $f$ is provided, a faster root finding technique like the secant method can be applied to $f(\x(t))=0$.  In fact, Muon1 uses a combination of these two techniques, reverting to bisection if the secant method becomes divergent.  Note that calculating $\x(t)$ for a general time in the timestep requires the Runge--Kutta step to be called as a subroutine of the collision point finder.  Adding material scattering complicates the process further and the full stack of stepping routines is given in section \ref{-cool-integration}.

\section{RF Components and Phasing}
Muon1 uses a simplified model for an RF cavity where the acceleration or deceleration takes place instantaneously as the particle crosses a plane placed where the midplane of the real cavity would be, usually perpendicular to the beamline.  Cavities are defined by the peak voltage $V_0$ a particle can experience, their angular frequency $\omega=2\pi f$ and an absolute phase $\phi$.  Note that the $V_0$ specified to Muon1 should already be reduced to account for the transit time factor of the cavity, since it is the maximum accelerating voltage given to \emph{a particle} rather a definition of the electric field.  Muon1 actually takes input in the form of the frequency $f$ and relative phase $\phi_r$ and derives $\omega$ and $\phi$ (see below).

\newcommand{\nhat}{\mathbf{\hat n}}
\newcommand{\ang}[1]{\left\langle#1\right\rangle}
If the RF cavity has forward-pointing unit vector $\nhat$ and a particle of charge $q$ and velocity $\vv$ passes through the cavity plane at simulation time $t$ with offset $\Delta\x$ from the cavity centre, the following change in momentum is applied:
\[ \Delta\p = \frac{q V_0}{\vv\cdot\nhat}\left(\cos(\omega t+\phi)\ \nhat + \frac{\omega}{2c^2}\sin(\omega t+\phi)\ \vv\times(\Delta\x\times\nhat)\right). \]
This is derived by assuming that in a cavity of notional length $\ell$ the particle experiences average electric and magnetic fields of
\begin{eqnarray*}
\ang\E &=& \frac{V_0}{\ell} \cos(\omega t+\phi)\ \nhat\\
\mbox{and} \qquad \ang\Bv &=& \frac{V_0\omega}{2\ell c^2}\sin(\omega t+\phi)\ \Delta\x\times\nhat \\
\end{eqnarray*}
during a total transit time of $\ell/\vv\cdot\nhat$ and using $\mathrm{d}\p/\mathrm{d}t = q(\E+\vv\times\Bv)$.  The form of $\ang\Bv$ is the solution of Maxwell's wave equations that has $\Bv=\mathbf{0}$ on the $\nhat$ axis and is consistent with the expression for $\ang\E$.

The absolute phase $\phi$ is calculated from the relative phase $\phi_r$ specified in the Muon1 input files by one of two possible methods.  If a \texttt{Synchronous-particle} component has been defined and inserted at the beginning of the beamline, it is tracked through the simulation before all other particles, with the time that it crosses each RF plane defining the relative phase of zero.  Absolute phases are then calculated from
\[ \omega t+\phi = \omega(t-t_\mathrm{cross})+\phi_r \quad \Rightarrow \quad \phi = \phi_r - \omega t_\mathrm{cross}. \]
If the synchronous particle is lost in the simulation, Muon1 calculates the crossing times from its initial velocity and the arc lengths of the beamline reference axis.  If a synchronous particle is not specified, absolute phases are set equal to the phases in the input file.


\chapter{Target Design Considerations}\label{-target-eng}
The reference proton beam power used in the ISS \cite{ISS} and most other neutrino factory studies is 4\,MW.  This is quoted as the mean beam power during nominal operation of the facility, including all inter-pulse gaps (the pulsed power is at the terawatt level).  Although powers greater than 4\,MW are possible, they would represent an increasingly large leap in proton accelerator technology over that currently demonstrated.  Lower powers would produce so few muons that it would become hard to achieve the $10^{21}$ decays per $10^7$\,s of running time required for physics results in a reasonable timescale.  The figure has perhaps a factor of two of elasticity in either direction but fixing it is essential to define the time and cost scale of the baseline design.

\newcommand{\cbox}[2]{\parbox{#1\textwidth}{\vspace{3pt}#2\vspace{3pt}}}
\begin{table}[b]
\caption{\label{solidvsliquid}Features of a solid pion production target compared with a liquid mercury jet.}
\begin{center}
\begin{tabular}{lll}
\hline
Advantages of solid target&&Disadvantages of solid target\\
\hline
\cbox{0.4}{Does not depend on hydrodynamics No liquid cavitation}&&\cbox{0.4}{Requires mechanical system for changing targets}\\
\cbox{0.4}{Mercury vapour damages vacuum, require beam window}&&\cbox{0.4}{Mechanical joints may produce dust}\\
\cbox{0.4}{No chance of contamination from spillage}&&\cbox{0.4}{Proton pulse intensity must not shatter target}\\
\cbox{0.4}{Targets may be changed sideways at lower velocity than longitudinally}&&\cbox{0.4}{Requires the first solenoid coil to be split}\\
\hline
\end{tabular}
\end{center}
\end{table}

Several constraints mean that the concentration of power in the target becomes a considerable difficulty at the 4\,MW level.  Most of the heat deposition in the target will occur in the first two hadronic interaction lengths (around 20\,cm for heavy metals); however, the radius should be much smaller than an interaction length (a few centimetres) to prevent pions being reabsorbed as they exit the target.  This leaves a very small volume to dissipate the considerable heat load and this cannot be done with a static target as for radiation cooling the powers are a factor of $\ge 12$ too high, as shown in section \ref{-target-eng-thermal}.  Water cooling comes closer to feasibility but falls short due to lack of surface area in the target.  Therefore the target material must be replaced for each pulse, either by moving the target material or steering the beam onto different targets, the former currently being considered more practical.

The UK neutrino factory design proposes a solid pion-production target as opposed to the liquid mercury jet suggested in the US study \cite{Study2}.  The solid `target' would actually be a series of solid targets in a loop that take turns to be hit by the proton beam pulse, whereas the liquid jet vaporises after producing the pions and is flowing at such a rate that new liquid will be in place by the next pulse (which arrives at a 50\,Hz rate in the liquid target baseline).  This changes the set of limitations and challenges in the target as set out in table \ref{solidvsliquid}.

Proof-of-principle experiments in high power targets for the neutrino factory (and other high-power facilities) are being conducted at the time of writing, most notably MERIT \cite{MERIT} for the liquid mercury jet and wire shock test studies \cite{WireTest} for the solid target.  Interested readers are encouraged to follow the references as the detail of these experiments is outside the scope of this thesis.

\begin{figure}
\includegraphics[width=160mm]{fig_310_solidtarget.png}
\caption{\label{solidtarget}Main components of the UK solid target station.}
\end{figure}

\clearpage
\section{Proton Driver Parameters}\label{-target-eng-proton}
With the beam power $P$ fixed, the main remaining parameters are the proton beam kinetic energy ($E_k$) and the pulse repetition frequency $f$.  Given these, the number of particles per pulse ($N$) can be derived from the formula for the mean power $P = fNE_k$\comment{ (all variables in SI units)}.  The energy per pulse will increase as $f$ is decreased, so for a solid target it is unfavourable to use low repetition rates.  Increasing the repetition rate eventually causes the power consumption of the pulsed RF systems in the muon accelerators to become unacceptable, with the ISS recommending a compromise value of $f = 50$\,Hz, which will also be used here.  Given this, the number of protons per pulse is given by
\[ N = \frac{P}{fE_k} = \frac{4\times10^6}{50E_k} = \frac{4\times10^6}{50(10^9e)E_k\eu{GeV}} = \frac{4.9932\times10^{14}}{E_k\eu{GeV}}. \]

There is a threshold for pion production that puts a lower bound on $E_k$.  Pions are produced at low energies by nucleon-on-nucleon collisions of the form $N+N\rightarrow N+N+\pi$ like $p+n\rightarrow p+p+\pi^-$, with other production channels becoming available at higher energies, see section \ref{-target-downstream-kaons} for an example.  This means the centre of mass energy must exceed the masses of two nucleons and a pion (a charged pion for our uses), which is 2.016\,GeV for $p+p+\pi^-$.  The centre of mass energy satisfies
\[ E_{cm}^2=(E_1+E_2)^2-(p_1+p_2)^2, \]
where $E_i$ are the total energies of the two colliding particles and everything is measured in energy equivalents: GeV/c for momenta and GeV/c$^2$ for masses.  The second particle is a nucleus at rest, so $p_2=0$ and $E_2=m_2$.  The incoming particle has total energy $E_1=m_1+E_k$ and momentum $p_1=\sqrt{E_1^2-m_1^2}$.  Some rearrangement gives the required incoming proton energy as
\[ E_k = \frac{E_{cm}^2-(m_1+m_2)^2}{2m_2}. \]
Thus $E_k$ must be at least 286.5\,MeV for the reaction $p+n\rightarrow p+p+\pi^-$ and at least 292.3\,MeV for the reaction $p+p\rightarrow p+n+\pi^+$.  Near to this threshold the cross section will still be very low and the outgoing pions may have such low energy that they become reabsorbed in the target.  Previously \cite{Study2} beam energies of tens of GeV have been found to achieve sufficient pion yield; a detailed investigation of where the optimum energy is can be found in section \ref{-target-energy}.

Dependent on the optimal energy is the choice of proton accelerator technology.  Table \ref{protondrivers} lists examples of machines that have particular energies, together with their current status and beam power.

\begin{table}
\caption{\label{protondrivers}Planned and existing high-power pulsed proton accelerators.  Beam energy figures in brackets are not values on the primary sampling of the energy range in the simulations described in this chapter, which is given by the remaining figures.  Repetition frequencies are 50\,Hz unless otherwise stated.}
\begin{center}
\begin{tabular}{lll}
\hline
Proton driver&$E_k\eu{GeV}$&Power/Schedule\\
\hline
CERN SPL I \cite{SPL1}&2.2&Study, 4\,MW, 75\,Hz, superseded\\
ISIS upgrade RCS 1 \cite{ISISUpgrade}&3&Study, 1\,MW\\
CERN SPL II \cite{SPL2}&(3.5)&\cbox{0.4}{Proposal (first 160\,MeV approved), 4--5\,MW ultimate}\\
&4\\
Green-field RAL synchrotron \cite{MWSynch}&5&Study, 4\,MW\\
ISIS upgrade RCS 2 \cite{ISISUpgrade}&6&Study, 5\,MW\\
FNAL Project X linac \cite{ProjectX}&8&Study, 2\,MW, 10\,Hz\\
Scoping Study FFAG option \cite{ISS}&10&Study, 4\,MW\\
ISR tunnel RAL synchrotron \cite{MWSynch}&15&Study, 4\,MW, 25\,Hz\\
FNAL RCS proton driver \cite{FNAL-PD1}&(16)&Study, 1.2\,MW, 15\,Hz\\
&20\\
BNL/AGS upgrade \cite{Study2}&(24)&Study, 1\,MW, 2.5\,Hz\\
CERN slow-cycling synchrotron \cite{SlowSynch}&30&Study, 4\,MW, 8.33\,Hz\\
&40\\
JPARC main ring \cite{J-PARC}&50&Beam in 2009, 0.75\,MW, 0.3\,Hz\\
&75\\
&100\\
FNAL injector/NuMI \cite{FNAL-MI}&120&\cbox{0.4}{Running at 0.4\,MW, upgradable to 1.2\,MW by 2013, 0.75\,Hz}\\
\hline
\end{tabular}
\end{center}
\end{table}

\begin{table}
\caption{\label{protonIDS}Proton driver specification from the International Design Study for a Neutrino Factory (IDS-NF) baseline, version 1 \cite{IDSproton} in 2008.  Note: that study uses a liquid target.}
\begin{center}
\begin{tabular}{ll}
\hline
\textbf{Proton Driver}&\\
\hline
Proton power&4\,MW\\
Proton kinetic energy&5--15\,GeV\\
Pulses per second&50\\
Bunches per pulse&3\\
Minimum time between bunches&17\,\us\\
Maximum time for all bunches&40\,\us\\
RMS proton bunch length&1--3\,ns\\
\hline
\end{tabular}
\end{center}
\end{table}

At low energies, acceleration can be done with a single-pass linear accelerator, the most ambitious proposal in this class being the 8\,GeV ``Project X'' concept from Fermilab \cite{ProjectX}.  The CERN SPL (Superconducting Proton Linac) design is still ambitious at 3.5\,GeV in its second design report \cite{SPL2} (with the option to upgrade as far as 5\,GeV if necessary) but has been designed to a much higher level of detail.  The main technical disadvantage of using a linac as the neutrino factory proton driver is that the neutrino factory Scoping Study report \cite{ISS} recommends a 1--3\,ns RMS bunch length whereas a linac generally produces a `pulse' of order 1\,ms in length on each repetition.  This means that the pulse must first be \emph{accumulated} in a ring at the end of the linac to reduce its length to the circumference of the ring, corresponding to a time closer to 1\,\us.  Once the beam is in a ring, irrespective of whether that ring is an accumulator for a linac or the acceleration ring of a synchrotron or FFAG, it must be further compressed to the final nanosecond timescale.  This is achieved via careful use of RF systems in the ring to shorten the bunch to less than the natural bunch length during acceleration or accumulation.  The main problem in this phase at low energies is the longitudinal `space charge' repulsion of particles from each other, which is enhanced by shortening the bunch and thus increasing its charge density.  The space charge is also reduced steeply by increasing the beam energy (relativistic time dilation and space contraction allow more charge in the same volume of the laboratory frame) and the decrease of beam current that comes with keeping the power constant at higher energies.  Thus the SPL proposal has the most difficult bunch compression system in table \ref{protondrivers}, with a high voltage of RF in the compression ring.  The advantage of linacs is that their overall intensity can be made higher than an accelerator chain containing rings and the associated injection and extraction, since there is no timing constraint on the acceleration: linacs may even be operated in continuous or ``CW'' mode if the components can cope with the heat loading.  This is the reason that the SPL and Project X proposals are actually multi-use machines where proton intensity over and above that required for the neutrino factory is used for other applications such as nuclear physics experiments or spallation neutron sources.

At higher energies, circular accelerators dominate, as the length (and thus cost) of a linac become prohibitively large.  There is also a trend for the repetition rate of these accelerators to decrease as energy increases, which is for two reasons: the amount of RF voltage around the ring limits the rate at which protons can attain high energies and the constant power requirement means less average current of protons is needed, so bunches can be accelerated less often.  With the highest energy rings, cost is again driven up due to an increase in length, but this time because the available dipole magnetic fields are no longer able to bend the high-energy protons around on a smaller radius of curvature.  At low energies, the main challenge for circular accelerators is the increased beam current and sharply-increased space charge.  Thus there could be said to be an optimum towards the mid-range of options shown in the table.  Finally, note that the circular accelerators come in two types: synchrotrons in which the magnetic fields are varied during the acceleration cycle to scale with the beam momentum and FFAGs in which the variation of magnetic field strength is provided spatially across the accelerating aperture that the beam orbit moves over with energy.  FFAGs are still an active area of research and there is not yet a conclusive cost/benefit comparison of these two ring types.  As of 2009, no FFAG has been demonstrated to work in the same power or space charge regime as existing high-power proton synchrotrons.

\clearpage
\section{Bunch Spacing}
\begin{figure}
\includegraphics[width=160mm]{fig_320_bunchstructure.png}
\caption{\label{bunchstructure}Bunch timing structure of a neutrino factory with a solid target, $f=50$\,Hz and $h=5$ bunches per pulse.}
\end{figure}
The RF system of the final proton acceleration (or storage) ring provides an additional control over the bunch structure of the beam hitting the target.  To make sure the longitudinal dynamics are consistent from turn to turn, the RF system must return to the same phase each time the centre of a bunch comes back to the cavity location, excluding slow adiabatic adjustments to the phase used in the acceleration programme.  This requirement can be satisfied by making the RF frequency equal to the revolution frequency of the ring, but it can also be an integer multiple of this, with the multiplier known as $h$, the harmonic number.  For example in the main ISIS ring \cite{ISIS} $h=2$ and in the upgrade ring for a neutrino factory proton driver, $h=6$ \cite{ISISUpgrade}.  A consequence of having $h>1$ is that another bunch at an angle of $2\pi/h$ behind the first in the ring experiences exactly the same RF programme and the same transverse dynamics too.  It is therefore efficient to use all the stable phase space by filling all these RF `buckets' in a ring if it is possible.

The consequence for the downstream systems is that if the final proton ring is designed with a harmonic number $h>1$, then each machine pulse will produce up to $h$ bunches that will hit the target with some delay from each other.  If the entire turn is extracted at once then the spacing between bunches will be the same it was in the ring, usually less than 1\,\us.  As the rise-time of the extraction kicker must be less than the time between bunches for successful extraction (unless there is an empty bucket used for this purpose), it is usually possible to have the kicker activate for only one of the bunches, which is sent to the target, then wait for a period of time before kicking out another and so on.  Thus the delay between the bunches may be increased from the natural spacing, though in a synchrotron it cannot be increased so far as to make regular bunches at frequency $fh$ because at some point the main magnet field must return to a low value in order pick up low-energy bunches to be accelerated in the next pulse.  A storage ring would make regular spacing possible but at considerable cost; it must also be stressed that with regular extraction the frequency $fh$ essentially becomes the repetition rate, so $fh\simeq 50$\,Hz would then be desirable.  Usually the bunches are extracted close enough together that the resulting muon trains could all go through the muon acceleration system during a single pulse of its RF.

The target will react to this pulse substructure in a different way depending on whether it is solid or liquid.  For a liquid jet, it is preferred that the bunches arrive close together (within 40\,\us\ in table \ref{protonIDS}) before disruption or boiling of the mercury moves it out of the beam path.  For a solid target, if the bunch spacing is sufficiently large to approach the oscillation time of acoustic (or shock) waves in the target rod, then several smaller shocks can be initiated at different phases, reducing or even cancelling the overall shock effect.  This is shown in \cite{TargetShock} where the oscillation time in a simulated 2\,cm diameter tantalum rod is just under 10\,\us\ and the overall stress amplitude is reduced by a factor of $\sim$5 by spreading the input shocks over a period of 10\,\us\ rather than triggering them all at once.  This would give the overall timing structure shown in figure \ref{bunchstructure}.

One final aspect of the proton ring RF system that affects the bunches on the target is the bunch compression scheme that manipulates longitudinal phase space to reduce the duration of each bunch to $\sim$1\,ns RMS.  This is either done with programming of the main RF or an additional higher-frequency system and will act on all the bunches in the ring.  It is required because introducing too much time spread into the distribution of muons from the target will increase their longitudinal emittance.  It also means each proton bunch is virtually instantaneous from the point of view of the target material, meaning that thermal shock occurs, because the temperature has increased (from energy deposition) with no commensurate expansion of the atomic lattice.  The shocks in fact propagate inwards from the target surface, which is able to expand into free space first.

\section{Thermal Effects}\label{-target-eng-thermal}
The management of heating in the target caused by energy deposition from the proton beam and its secondary particles is one of the primary considerations in the target design.  As mentioned earlier, the neutrino factory target cannot be made arbitrarily large in order to spread the heat load, so techniques for dealing with high energy densities are necessary.  Additionally, surrounding the target in a coolant would lead to the reabsorption of pions and additional heat deposition, so radiative cooling schemes are considered.

\begin{figure}
\includegraphics[width=160mm]{fig_313_powerpie2.png}
\caption{\label{powerpie2}Where the energy from a 10\,GeV proton beam goes when it hits a 20\,cm long, 2\,cm diameter tantalum rod target (MARS15 \cite{MARS15} calculation).  For the variation of these figures with proton energy and length of rod, see sections \ref{-target-energy-heat} and \ref{-target-length-heat} respectively.}
\end{figure}

The inner pie chart of figure \ref{powerpie2} shows that the neutrino factory target is quite an efficient target for particle production, with most of the proton beam energy going into secondary particles rather than heat.  The protons emerging at angles within 5 degrees of the rod's forward axis are singled out because they produce a `hot spot' if they hit the target chamber wall at too close a range, with consequences discussed in section \ref{-target-eng-dump}.  These protons mostly consist of those that have been multiply scattered through the high-Z target material without experiencing a nuclear interaction.  As such, they still have most of their original energy, $\sim$9.5\,GeV for the 10\,GeV proton beam example.

There is a terminology issue as to whether the neutrino factory rod is a `stopping target' or not.  The answer is that most of the primary protons undergo a nuclear interaction even in the 20\,cm long case, with the proportion increasing as the rod becomes longer, though not attaining 100\% because a few percent of the protons will always scatter out of the sides of the rod.  However, `stopping' in this sense does not imply that all of the power in the original beam is deposited as heat, as it is in neutron spallation targets, because such a large fraction of energetic secondaries escape permanently from the rod.

The outer pie chart of figure \ref{powerpie2} splits up the kinetic energy of the secondary particles by species.  Positive and negative pions are the desired particles and constitute fairly large segments of the pie, carrying 24\% of the original 4\,MW power.  Kaons also appear that can decay to usable pions later on.  A final histogram by angle of emitted radiation (figure \ref{kineticbyangle}) shows that the target chamber will have to cope both with a diffuse component of the radiation and with the forward-directed `hot spot' mostly coming from the protons.  Apart from the target itself, the radiation will be most intense ($>100$\,W/cm$^2$) on the inner bore of the radiation shielding just inside the initial 20\,T solenoid, meaning this shielding must contain extensive water cooling channels.

\begin{figure}
\includegraphics[width=160mm]{fig_313_kineticbyangle.png}
\caption{\label{kineticbyangle}Graph showing the directionality of emitted power for each particle species, predicted by MARS15 \cite{MARS15} for the same setup as figure \ref{powerpie2}.}
\end{figure}

In the solid target design, the cooling of the target itself is achieved by radiation from the surface.  The formula for thermally radiated power from an object of surface area $A$ and temperature $T$ is
\[ P = \epsilon\sigma A T^4, \]
where $\epsilon$ is the emissivity, which may also depend on temperature, and $\sigma$ is the Stefan-Boltzmann constant.  In the approximation of continuous, volumetrically uniform irradiation and perfect thermal conductivity of the bar (i.e.\ an optimistic scenario), $P$ can be set equal to the mean input power of heat deposited in the target.  With the parameters used for figure \ref{powerpie2} and a 4\,MW proton beam, $P = 514$\,kW and $A = 0.0132$\,m$^2$.  The emissivity of tantalum or tungsten is $\sim$0.32 at high temperatures \cite{TantalumEmissivity} and decreases as $T$ reduces.  By rearrangement of the previous equation, the equilibrium temperature at which power radiated equals power input is
\[ T = \sqrt[4]{\frac{P}{\epsilon\sigma A}} = 6808\,\mbox{K}. \]
The melting point of tantalum is 3290\,K and that of tungsten is 3695\,K, so even under optimistic assumptions, a single bar of this size will not be able to radiatively dissipate the required amount of heat without melting.

It is now clear why the UK neutrino factory solid target design involves multiple bars that are replaced for each pulse.  For $N$ bars the above calculation can be redone with $P = 514/N$ kW, showing that $N\ge 12$ is required for tungsten not to melt and $N\ge 19$ for tantalum.  These figures do not include margins for error and so on, with more realistic scenarios having $N\ge 200$ bars \cite{RogerSlides}.  Tungsten demonstrates greater strength at high temperatures so is currently the preferred material option, though its pion production behaviour is very similar to the tantalum investigated in chapter \ref{-target} due to their proximity in the periodic table.

\section{Geometry of the Solid Target Mechanism}

Figure \ref{targetchain} shows a solid target chain concept in cross section, showing how the solenoid coils would have to be arranged such as to let the chain of rods pass through.  Simulations in this thesis using Muon1 do not model the coils to this level of complexity (as the target design is still under development) but instead assume the magnetic field from a single 20\,T initial coil.

To see how this affects the magnetic field profile, figure \ref{targetcoils} shows how with coils set at 50\,A/mm$^2$, peak fields of 20\,T can be created.  One layout does this with a solid coil and the other splits the coil with enough room for the target and chain to pass through.  The dip in on-axis field between the two coils in the second case goes no lower than 17\,T.\ \ A few pions are tracked in the pictures, with one in the second case becoming trapped in a magnetic bottle in the field dip.  However, that pion has a very small longitudinal momentum as evidenced by the steep pitch angle of its spiralling motion, so falls outside the region of `interesting' pions defined in section \ref{-target-model-grid}.

Although the target station for the solid target mechanism is not yet engineered, we may usefully inherit features from the US Feasibility Study II \cite{Study2} target cross section, reproduced in figure \ref{targetstudy2}, which incorporates the correct amounts of shielding for the radiation fluxes produced.  Any mechanism for removing the targets laterally will require the normal conducting initial coils as well as the superconducting coil and its cryostat to be split and the vacuum area extended to contain the chain or wheel of targets.

There are other options besides a chain for moving the solid target through the interaction area.  Figure \ref{targetwheel} shows the concept of a spokeless wheel or rim, which intersects through holes in the first solenoid and rotates continuously with targets attached so they are lined up with the proton beam for every 50\,Hz pulse.  Another option that is being considered is to have a powdered solid moving through the target station fast enough that each proton pulse hits a fresh volume of material.  Figure \ref{powderjet} shows a tungsten powder jet formed by a proof-of-principle experiment at RAL \cite{PowderJet,PowderJetTech}.  The powder may have advantages because it cannot shatter or fail mechanically in the same ways as a solid rod.

\begin{figure}
\includegraphics[width=160mm]{fig_314_targetchain.png}
\caption{\label{targetchain}Schematic diagram of the solenoid arrangement surrounding the chain of solid targets, from \cite{RogerSlides}.}
\end{figure}

\begin{figure}
\includegraphics[width=153mm]{fig_314_targetcoils.png}
\caption{\label{targetcoils}Cross sections of solid (left) and split (right) coil layouts around the target.  The axial field profile $B_z(0,0,z)$ is superimposed for a coil current of 50\,A/mm$^2$.  The peak field in each case is 20\,T.\ \ The red target rectangle is the 20\,cm length case with the 30\,cm, 3\,cm diameter option shown by a fainter line.}
\end{figure}

\begin{figure}
\includegraphics[width=153mm]{fig_314_targetstudy2.png}
\caption{\label{targetstudy2}A cross section of the US Feasibility Study~II \cite{Study2} target station.  Normal-conducting solenoids are shown in green and superconducting ones in blue.  Water-cooled tungsten carbide shielding is yellow.  The UK targets from figure \ref{targetcoils} are shown to scale in the bottom-left corner.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_314_targetwheel.png}
\caption{\label{targetwheel}Cross-section of the rotating spokeless target wheel.  The shaded annulus (left) is the coil of the first solenoid and target rods are attached to the wheel rim (right) with long axes pointing into the page.  Adapted from \cite{TargetWheel}.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_314_powderjet.png}
\caption{\label{powderjet} Photograph of an unconfined tungsten powder jet produced experimentally \cite{PowderJet,PowderJetTech}.  The jet is flowing leftwards from the nozzle (right) at 3.7\,m/s and the exposed portion of the jet is $\sim$20\,cm long as measured by the 1/5/10\,mm graph paper behind.}
\end{figure}

\clearpage
\section{Beam Dumping}\label{-target-eng-dump}

The UK target station beam dump differs from Study~II, which uses the collection pool of the mercury jet to act as the beam dump for the 974\,kW of forward directed protons (as defined in figure \ref{powerpie2}).  The UK design uses a smaller angle between the incoming protons and the magnetic field axis, meaning that the protons will hit the side further down the muon decay channel.  There a conventional water-cooled beam dump will absorb the energy over a larger area, as the protons impinge at a shallower angle.  The large angle is needed in the liquid mercury design to keep the entire mercury flow loop within the initial cryostat, whereas solid target designs do not have this limitation.

\begin{figure}
\includegraphics[width=160mm]{fig_315_hotspot.png}
\caption{\label{hotspot}The angular distribution of remnant proton beam power within 5\degree of the incoming proton beam axis, from the same situation as in figure \ref{powerpie2} (MARS15 simulation).}
\end{figure}

Calculating the peak areal power density requires knowing something about the angular distribution of the forward-directed protons.  In a given solid angle $\Omega$ (measured in steradians), the heating power $H$ is the sum of the kinetic energies of protons arriving per unit time whose velocities lie within that angle.  The rate of heat deposition will be directly proportional to $P$, the incoming proton beam power, so $H/P$ is a constant independent of $P$.  In the limit of small solid angles the dimensionless quantity $(1/P)\mathrm{d}H/\mathrm{d}\Omega$ evaluated at any given angle describes the concentration of secondary protons there.   Figure \ref{hotspot} is a plot of $(1/P)\mathrm{d}H/\mathrm{d}\Omega$ against deflection angle and the peak of 239\,(W/W)sr$^{-1}$ is used in further calculations.

If the beam dump is situated a distance $L$ from the target and the remnant proton beam hits it with angle of incidence $\theta$, the areal power density on the dump is
\[\dd{P_\mathrm{dump}}{A} = P\left(\frac{1}{P}\dd{H}{\Omega}\right)\frac{\sin\theta}{L^2}.\]
Values calculated using this formula are shown in table \ref{hotspotcomparison}.  This is not entirely accurate as the Study~II figure is calculated using the tantalum rod target rather than the mercury jet, but shows the improvement gained by a larger distance to the dump and shallower incidence angle.  Note that these power deposition figures are also strongly influenced by the target length (which reabsorbs protons), detailed in section \ref{-target-length-heat}.

\begin{table}[hb]
\caption{\label{hotspotcomparison}Comparison of the locations of the beam dump for the forward-directed proton `hot spot' in Study~II and UKNF designs.  Peak areal powers are calculated using the formula given in the main text for a 4\,MW incoming proton beam.}
\begin{center}
\begin{tabular}{llll}
\hline
Parameter&Study~II&UKNF\\
\hline
Angle proton beam to magnetic axis&66.7&14&mrad\\
Distance beam dump downstream&3.75&25&m\\
Distance beam dump off axis&0.25&0.35&m\\
Peak areal power deposition&453&2.14&W/cm$^2$\\
\hline
\end{tabular}
\end{center}
\end{table}


\chapter{Pion Production Simulations}\label{-target}
Muon front end simulations require an initial set of pion coordinates from the target.
\comment{Tracking particles in the muon front end requires an initial set of representative pion coordinates from the target to start the simulation.}  This chapter describes hadronic \comment{generation }simulations that \comment{both }obtain pion distributions and allow these to be compared across different target parameters to find the best solution (sections \ref{-target-model}--\ref{-target-pdist}).  The target optimisation is decoupled from the muon front end in terms of yield, though some choices in the target have indirect effects on the later accelerator (section \ref{-target-downstream}).

\section{Modelling Particle Production in MARS15}\label{-target-model}
\newcommand{\mmmrad}{mm$\cdot$mrad}

The newest available version (15.04) of the MARS particle production code \cite{MARS15,MARS15Paper} was used for the simulations.  Later versions are likely to have updated models based on data from the HARP experiment \cite{HARP}.  As MARS15.04 does not, a benchmark of its results against some experimental data from HARP is given in section \ref{-target-harp} to help gauge the level of accuracy of the current MARS models in the region of interest.  The series of target simulations in the following sections uses the reference simulation in table \ref{targrefsim} as the starting point from which to vary parameters of interest.

\begin{table}[h]
\caption{\label{targrefsim}Parameters of the target reference simulation.  This configuration emerged early on as being somewhere near the optimum for pion production, so served as a starting point for investigations of variations in the parameters.}
\begin{center}
\begin{tabular}{ll}
\hline
Code Used&MARS15\\
Target Material&Tantalum\\
Target Shape&Cylindrical\\
Target Dimensions&20\,cm length $\times$ 1\,cm radius\\
Protons Per Monte Carlo Run&$10^5$\\
Proton Beam Profile&\cbox{0.5}{Parallel beam, radius same as rod, parabolically distributed on circular target endface}\\
Proton Direction&Parallel to target cylinder axis\\
Magnetic Field&None used (simulation only within target)\\
\hline
\end{tabular}
\end{center}
\end{table}

\begin{figure}
\includegraphics[width=160mm]{fig_320_targrefsetup.png}
\caption{\label{targrefsetup}Schematic of the target reference simulation.}
\end{figure}

In the simulation, the proton beam hits the target end-on as shown in figure \ref{targrefsetup}.  MARS was configured to record all $\pi^+$ and $\pi^-$ leaving through any of the target cylinder's surfaces.  See appendix \ref{--MARSINP} for the input file used for these simulations.  The target also produces copious quantities of neutrons; indeed, a stopping tantalum target is sometimes used in dedicated neutron production machines.

A radial parabolic distribution $\rho(r)\propto 1-(r/R)^2$, $0\le r\le R$, was used for the protons, with $R$ the radius of the rod (see appendix \ref{--MARSBeam} for generating routine).  This is preferable to the rectangular and Gaussian beams that are defaults in MARS, as it is the same shape as the rod and does not lead to a proportion of the beam missing the target entirely.  Another option frequently used in target studies is a uniform distribution on the circlular endface, but this is hard to achieve in practice with a proton extraction line.  The parabolic distribution, however, is the projection into the plane of a 4D `waterbag' phase-space distribution, which is often used as a model of proton bunches. 

The incoming beam was assumed to be parallel in the simulation, as typical proton drivers have beams with too small an angular divergence to greatly affect the results of a hadron shower calculation in a block of material.  For instance, the ISS baseline proton driver \cite{ISS} has a beam with a 100\% un-normalised emittance of 175\,\mmmrad\ just after injection at a kinetic energy of 200\,MeV, which becomes 10.3\,\mmmrad\ at the 10\,GeV extraction energy, scaling with $1/(\beta\gamma)$.  At a beam focus or `betatron waist', this emittance is the product of the beam radius and maximum particle angle ($x'$).  Setting the radius to the 1\,cm of the reference rod gives a beam divergence of 1.03\,mrad.  Even at the lowest considered energy of 2.2\,GeV this is only 3.77\,mrad, which would produce a 0.75\,mm transverse offset in a 20\,cm rod and little difference in interacting path length.\comment{ $\Delta l$, as for an inclined path traversing block of length $l$, $\Delta l/l=\sqrt{1+\theta^2}-1=\frac12\theta^2$ plus higher order terms, so $\Delta l/l < 10^{-5}$ here.}

MARS can add a magnetic field as would be present in the rod in this situation.  However, this may change in value if the magnetic design of the front end is to be optimised, so one field would not be correct for all simulations.  The field strength also has little effect on the pion production, since over the width scale of the rod it produces only a slight curvature of the pion trajectories of interest.  For instance, a typical pion spiralling on an $R=5$\,cm radius helix produced at the centre of an $r=1$\,cm radius rod will have its velocity vector rotated about the rod axis by $\theta\simeq r/R$ by the time it exits the rod.  The displacement at the rod's surface will be to leading order $\frac12\theta r$ but the difference in path length $\Delta l$, important in particle production is given by $\Delta l/r = \frac16\theta^2$ plus higher order terms.  Here, $\frac16\theta^2\simeq\frac{1}{150}$ so the differences in interacting path length due to the magnetic field actually fall below the statistical errors in the Monte Carlo simulations.

The above simplifications mean that these pion production results are applicable quite generically for pion production from protons hitting a cylindrical target and the optima and trends discovered may be useful outside the context of the neutrino factory.

\subsection{Pion Capture Probability Grid}\label{-target-model-grid}

To evaluate the number of `useful' pions produced by the target, the pions leaving its surface have their longitudinal and transverse momenta $(p_L,p_T)$ recorded and plots such as figure \ref{fatephaserotator} show this momentum distribution and the later behaviour of the pions in the muon front end.  The MARS code was not available to run on the distributed optimisation network, so it was not practical to run MARS in conjunction with every front end investigated.  Instead, a pion distribution is simulated through two representative muon front ends, each producing a probability function for pion survival as a function of their initial $(p_L,p_T)$ coordinates.

This makes optimisation of the target much quicker since a simple postprocessing step can now turn a target pion distribution into a figure for useful pions, rather than requiring tracking to be performed each time.  The effect is similar to using momentum `cuts' but is based more closely on the actual behaviour of the particles in the representative muon front ends.

Figures \ref{fatephaserotator} and \ref{fatechicanelinac} display the fate of pions as a function of their initial $(p_L,p_T)$ coordinates in two front ends chosen for their contrasting design principles.  Figure \ref{fatephaserotator} uses RF phase rotation to a low energy spread from section \ref{-results-phaserot}, whereas figure \ref{fatechicanelinac} uses a magnetic chicane buncher and linac from section \ref{-results-chicanelinac}.  Since decay to a muon occurs in the front end, the end result is not deterministic: the range of possible decay muons originating from a single pion causes the blurring of the coloured regions in the figures.  An additional small amount of blurring will come from any correlations of the behaviour with the pion's starting position on the target surface because reducing the initial five phase-space variables (assuming axial symmetry) into two $(p_L,p_T)$ idealises the rod as a point source.  However, the plots can still be used to produce a method for counting useful pions if they are treated as showing survival \emph{probability} as a function of initial momentum.

To obtain probability figures, the plots were binned into $30\times 30$\,MeV/c squares and the ratio of survived muons (white points on the plots) to the total number of initial pions was calculated in each one.  In fact, since MARS generates particles with statistical weights, the ratios were calculated between sums of weights for the appropriate pions:
\[ P_{ab} = \frac{\displaystyle\sum_{\mathrm{Transmitted\ muons}\ i: \atop {(p_L,p_T)_i \in \mathrm{Square}(a,b)}}w_i}{\displaystyle\sum_{\mathrm{Original\ pions}\ i: \atop (p_L,p_T)_i \in \mathrm{Square}(a,b)} w_i} = \frac{T_{ab}}{W_{ab}}, \]
where the numerator and denominator of this expression define $T_{ab}$ and $W_{ab}$.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_321_fatephaserotator.png}
\caption{\label{fatephaserotator}Scatter plot of the initial transverse and longitudinal momenta of pions at the target, coloured by their fate in a particular phase rotation front end.  If the pion decays, the fate of its daughter muon determines the colour.}
\end{figure}

\begin{figure}[b]
\includegraphics[width=160mm]{fig_321_fatechicanelinac.png}
\caption{\label{fatechicanelinac}Using a front end with a chicane and pre-acceleration linac in figure \ref{fatephaserotator} instead of a phase rotator gives different loss mechanisms but the white area of pion momenta that decay into transmitted muons is similar, with a slight difference in central energy.}
\end{figure}
\clearpage

The resulting matrices of survival probability $[P_{ab}]$ are shown in graphical form in figure \ref{pgridmanky}.  Both lattices had a few squares with this probability exceeding 90\%, so there is a subpopulation of pions that will nearly always produce successful muons regardless of random decay effects or emission position on the rod.

\begin{figure}
\includegraphics[width=160mm]{fig_321_pgridmanky.png}
\caption{\label{pgridmanky}Probability grids derived from the particle acceptance data in figures \ref{fatephaserotator} and \ref{fatechicanelinac}.  Lighter blocks represent higher probabilities of pions in that block decaying into transmitted muons; black is zero probability, white would be 100\%.}
\end{figure}

Unfortunately the low statistics in some squares, particularly near the $p_T=0$ axis where the true phase space volume represented by the square is smaller, generate unwanted noise and fluctuations in the probability map.  Smoothing the values between adjacent squares appears to be one way of mitigating this.  As it happens, often a square with bad statistics that is by chance nearly empty ($W_{ab}$ is small) has neighbours with comparatively good statistics, which should be given more weight when calculating an average.  Empirically, the following scheme produced a substantial improvement in the probability maps:
\[ \tilde{P}_{ab} = \frac{T_{ab}+0.1(T_{a-1,b}+T_{a+1,b}+T_{a,b-1}+T_{a,b+1})}
{W_{ab}+0.1(W_{a-1,b}+W_{a+1,b}+W_{a,b-1}+W_{a,b+1})}. \]
The resulting smoothed probability matrices $[\tilde{P}_{ab}]$ are plotted in figure \ref{pgridsmooth}.  \comment{Note that although only 10\% of the statistics from each square are allowed to `leak' into each neighbour, if the neighbour in question started with low statistics, the formula results in a much more than 10\% increase in data for that square.  Meanwhile, the high-statistics squares are not overly affected by neighbouring low-statistics ones, something that would have been a problem if a smoothing scheme that used the ratios alone, for instance
\[ \bar{P}_{ab} = P_{ab}+0.1(P_{a-1,b}+P_{a+1,b}+P_{a,b-1}+P_{a,b+1}), \]
was used.  The importance of not allowing too much data to `leak' from square to square is that it reduces the effective blurring radius of the smoothing, which is desirable so as not to introduce systematic errors from changing the underlying shape of the probability window.}

\begin{figure}
\includegraphics[width=160mm]{fig_321_pgridsmooth.png}
\caption{\label{pgridsmooth}The tracking-derived grids in figure \ref{pgridmanky} smoothed to remove some aberrant values originating from statistical noise.}
\end{figure}

Table \ref{pgridtable} gives the numerical values of the probability grid squares for the phase rotation lattice.  This grid is used to define \emph{useful pions} in the remainder of this chapter; that is, if pion $i$ is in square $(a_i,b_i)$, then
\[ \mbox{Useful pion weight} = \sum_i \tilde{P}^\mathrm{phaserot}_{a_ib_i} w_i. \]
The range of pions transmitting muons with more than 50\% probability corresponds roughly to the region with total momentum $250\le|\p|\le450$\,MeV/c and transverse momentum $p_T\le200$\,MeV/c.  The effect of using the chicane/linac grid instead of $[\tilde{P}^\mathrm{phaserot}_{ab}]$ is demonstrated in section \ref{-target-model-gridcompare}

\begin{table}
\setlength{\tabcolsep}{3pt}
\caption{\label{pgridtable}Probability of successfully transmitting a muon through the phase rotation front end, as a function of bins in the $(p_L,p_T)$ space of the original pion emitted from the target surface.  The bins are 30\,MeV/c in size and the lower end values are given in the top table row for $p_L$ and the left-hand column for $p_T$, with zero transmission outside the region shown.  Probability values are in percent.}
\begin{center}
\begin{tabular}{r|*{17}r}
\hline
\small{MeV/c}&0&30&60&90&120&150&180&210&240&270&300&330&360&390&420&450&480\\
\hline
0&\small-&\small-&\small-&\small-&\small-&\small-&\small-&\small6.0&\small58.8&\small54.2&\small91.9&\small92.6&\small92.3&\small92.3&\small76.8&\small15.6&\small-\\	   
30&\small-&\small-&\small-&\small-&\small-&\small-&\small1.1&\small14.2&\small45.2&\small47.6&\small64.6&\small79.9&\small90.5&\small86.3&\small65.7&\small13.0&\small0.8\\	   
60&\small-&\small-&\small-&\small-&\small-&\small-&\small0.8&\small12.2&\small49.3&\small78.7&\small85.3&\small77.5&\small88.5&\small62.7&\small51.4&\small9.2&\small0.5\\	   
90&\small-&\small-&\small-&\small-&\small-&\small0.2&\small6.9&\small28.6&\small49.4&\small74.4&\small74.5&\small77.4&\small80.6&\small39.7&\small17.0&\small1.8&\small-\\	   
120&\small-&\small-&\small-&\small-&\small-&\small1.5&\small14.4&\small19.4&\small42.6&\small64.8&\small70.0&\small66.3&\small67.0&\small41.9&\small20.5&\small1.5&\small-\\	   
150&\small-&\small-&\small-&\small-&\small0.4&\small2.1&\small5.8&\small27.5&\small47.0&\small53.5&\small65.3&\small59.4&\small53.8&\small26.5&\small5.0&\small0.2&\small-\\	   
180&\small-&\small0.1&\small-&\small0.4&\small2.9&\small5.6&\small12.0&\small24.2&\small41.5&\small45.3&\small49.7&\small49.1&\small38.2&\small17.2&\small1.8&\small-&\small-\\	   
210&\small0.1&\small1.4&\small0.3&\small1.7&\small2.6&\small6.6&\small15.0&\small18.5&\small20.9&\small26.3&\small41.4&\small34.9&\small18.6&\small6.7&\small0.5&\small-&\small-\\	   
240&\small-&\small0.2&\small-&\small0.2&\small1.6&\small4.5&\small2.6&\small3.5&\small9.7&\small13.9&\small20.1&\small20.7&\small4.0&\small0.6&\small-&\small-&\small-\\	   
270&\small-&\small-&\small-&\small-&\small0.1&\small0.5&\small0.1&\small0.1&\small1.1&\small3.4&\small1.6&\small1.5&\small1.5&\small0.2&\small-&\small-&\small-\\
\hline
\end{tabular}
\end{center}
\end{table}

\clearpage
In a constant $\Bv$ field and the absence of any other forces, the path of a charged particle will be a helix with a certain (constant) radius that depends on the momentum of the particle transverse to the magnetic field direction and the strength of that field.  This is known as the \emph{Larmor radius} and can be calculated directly from the equations of motion given in section \ref{-code-motion} to be
\[ r_\mathrm{Larmor} = \frac{p_T}{|q| |B_z|}, \]
where $q$ is the charge of the particle.  Using MeV/c and units of the elementary charge gives a handier version of this formula for this sort of calculation:
\begin{eqnarray*}
r_\mathrm{Larmor}\eu{cm} &=& \frac{p_T\eu{MeV/c}\ (10^8/c)}{|q\eu{e}|\ |B_z\eu{T}|} \\[6pt]
&\simeq& \frac{p_T\eu{MeV/c}}{3|B_z\eu{T}|} \qquad \mbox{for a singly-charged particle}.
\end{eqnarray*}
The solenoid containing the target has $|B_z|=20$\,T and $q=\pm e$ for a pion, so the helix radius that the $p_T=200$\,MeV/c cut-off point corresponds to is $r_\mathrm{Larmor} = 3.34$\,cm, using the exact version of the formula above.  This is the largest helix radius at which more than half the pions are transmitted through the first solenoid.  The centre of the helix will not be the solenoid axis: instead, the location the pion was emitted from the target surface will be at one side of the helix and the furthest excursion will be $2r_\mathrm{Larmor} = 6.67$\,cm from this point.  This is approaching, though not equal to, the 10\,cm radius of the solenoid bore but the particles are now sufficiently far off-axis to risk encountering the non-linear fringe field of the solenoid on the way out, in which case the helix follows the diverging field lines to larger radii rather than the solenoid axis, leading to loss.  The largest possible transmittable helix would have a diameter of 11\,cm for the standard 1\,cm radius target (that is, from the far side of the target to the inner bore), so we would expect a complete removal of particles with $r_\mathrm{Larmor}\ge 5.5$\,cm.  This corresponds to $p_T\ge 330$\,MeV/c and the transmitted particles disappear completely just below this value, with $300\le p_T < 330$\,MeV/c being the first empty row of bins, just below those shown in table \ref{pgridtable}.

\subsection{Difference in Yield Between Probability Grids}\label{-target-model-gridcompare}
In the last section, two different probability grids were generated and it was stated that the phase rotation grid would be used for all subsequent yield evaluation rather than the one derived from the chicane/linac design.  As evidence for this choice, some of the yield graphs presented in section \ref{-target-energy} are evaluated here using both grids but with all other attributes kept the same; in fact they come from the same MARS particle output file.  Specifically, the standard target with parameters in table \ref{targrefsim} was used and the proton beam energy varied from 2.2\,GeV to 120\,GeV using the primary values in table \ref{protondrivers}.

\begin{figure}
\includegraphics[width=160mm]{fig_322_pgridcompareplus.png}
\caption{\label{pgridcompareplus} Comparison of useful $\pi^+$ yields calculated with two different probability grids over a range of energies.  $1\sigma$ statistical error bars are shown.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_322_pgridcompareminus.png}
\caption{\label{pgridcompareminus} Comparison of useful $\pi^-$ yields calculated with two different probability grids.  $1\sigma$ statistical error bars are shown.}
\end{figure}

Figure \ref{pgridcompareplus} shows the results for just the positive pions.  The chicane/linac design has an overall lower efficiency than the phase rotator, for reasons discussed in the tracking results of chapter \ref{-results}, which is one reason for it to be excluded.  Another question would be whether the two different designs show different qualitative behaviour: as the purpose of the target optimisation is to find the location of the yield peak in such parameters as proton energy, rod length and so on, the absolute yield matters less than the position (and shape) of the optimum.  To compare the shapes without the yield difference, the dotted line on the graph is a scaled version of the chicane/linac results.  The scaling factor chosen was the average ratio between the two original yield series.

Figure \ref{pgridcompareminus} shows the same three lines for the negative pions, which have a slightly differently-shaped graph to the positives.  In both cases, the scaled chicane/linac line stays very close to the phase rotation line, with a maximum difference of 10\% for low proton energy (and low-yielding) simulations producing negative pions.  These differences are only 2--3$\sigma$ in terms of the statistical error on each data point but are probably systematic because they have the same sign in groups of nearby energies.  However, the overall shapes of the graphs and locations of the optimum ranges are still similar, so the phase rotation grid is used as a representative figure of merit considering it both represents a higher-yield front end and evaluates design choices similarly to the chicane/linac grid.

\section{Proton Energy and Rod Material}\label{-target-energy}

This section contains what are probably the most important findings about pion yield gained from the MARS15 studies.  Section \ref{-target-eng-proton} described how the proton energy is a key parameter that has a large effect on the design of the proton driver, so the optimal energy must be determined before design work can continue.  The proton energy is varied in the simulations here and the results plotted to show the location and shape of this optimum.

Although high-Z ($Z=\mbox{atomic number}$) targets from period 6 of the periodic table have conventionally been the choice for the neutrino factory, this study also tried alternative materials at intermediate and low-Z.\ \ Specifically, at high Z, the tantalum of the standard UK solid target configuration at the time (table \ref{targrefsim}) and the liquid mercury used in US Study~II \cite{Study2} were both run.  For an intermediate-Z target, copper was chosen, more because it was the densest element in period 4 of the periodic table than for its suitability as a real target: it melts at perhaps too low a temperature to be considered for a solid target with radiative cooling.  The objective was to change $Z$ without changing the other parameters affecting the hadronic showering behaviour (primarily density) by too much.  Carbon in the form of graphite is an establised low-Z target material that is finding applications in neutrino superbeam experiments \cite{CNGS}\comment{, which also produce pions from a proton beam}.  Boron is a few percent denser (2.34 vs.\ 2.26\,g/cm$^3$) but is not so commonly used, thus carbon is the element chosen from period 2.

There is still a significant difference in density between these elements so a legitimate comparison must give them each a different length of target so the protons will have the same probability of interacting.  The relevant parameter that determines how frequently protons undergo nuclear interactions with path length in a material is its \emph{hadronic interaction length}.  This is used in table \ref{interactionlengths} to find a reference target length for each material that is used in the simulations of varying proton energy that follow.  The original 20\,cm tantalum rod corresponds to 1.79 hadronic interaction lengths.

\begin{table}[h]
\caption{\label{interactionlengths} Hadronic interaction length data from the Matprop tool at SLAC \cite{MatpropSLAC} allows reference lengths for other materials to be scaled from the 20\,cm tantalum target.}
\begin{center}
\begin{tabular}{lcccc}
\hline
Element&$Z$&Interaction length (cm)&Equivalent to 20\,cm Ta (cm)&Rounded\\
\hline	   
Ta&73&11.18&20&20\,cm\\	   
Hg&80&13.95&24.96&25\,cm\\	   
C&6&36.92&66.05&66\,cm\\	   
Cu&29&15.16&27.12&27\,cm\\	   
W&74&9.54&17.07&17\,cm\\	   
Mo&42&14.96&26.76&27\,cm\\	 
\hline
\end{tabular}
\end{center}
\end{table}

The table also includes molybdenum (a candidate element from period 5 that was not simulated) and tungsten, which later became the preferred solid target due to superior mechanical strength at high temperatures.  Its pion production behaviour will not be very different to the other period 6 elements plotted, which follow each other closely.

\begin{figure}
\includegraphics[width=160mm]{fig_330_yieldsigns.png}
\caption{\label{yieldsigns} Variation of single-sign useful pion yields with incoming proton energy for four different materials.  Note the log scale for proton energy.  Error bars will be omitted from yield graphs from now on for clarity, but errors will be similar to those in figure \ref{pgridcompareplus}.}
\end{figure}

Figure \ref{yieldsigns} plots the useful pion yields (as defined in section \ref{-target-model-grid}) for all four materials over the primary range of energies given in table \ref{protondrivers}, showing each sign of pion separately.  The units are chosen to be proportional to a constant beam power across all energies.  The measure of ``useful pions per incoming proton'' may seem a sensible choice, but a 100\,GeV proton carries much more kinetic energy and thus can create more hadronic particles than a 3\,GeV proton.  This is fixed by using the unit of ``useful pions per proton$\cdot$GeV'', where the fast proton in the previous example would count for 100 p$\cdot$GeV and the slow one for 3 p$\cdot$GeV.  As the denominator is now just a measure of beam kinetic energy, the numerical yield rate of useful pions can be calculated from the proton beam power $P$:
\[ \mbox{Useful pion rate}\eu{s^{-1}} = \frac{P\eu{W}}{10^9 e}\ Y, \]
where $Y$ is yield in these units.

There is an overall decreasing trend on all materials and signs above 10\,GeV, with more marked differences in the low-energy behaviour.  High-Z targets also fall off at low energy, exhibiting an optimum, whereas the carbon target continues to rise almost uninterrupted.  This was naturally of interest, so later plots include an extension of the carbon simulation range to proton energies as low as 800\,MeV.  Unfortunately, as discussed in section \ref{-target-eng-proton}, compressing the proton bunch to the order of nanoseconds becomes infeasibly difficult for energies below about 3.5\,GeV, so this carbon peak must remain of theoretical interest unless breakthroughs are made in proton bunch compression schemes.

\begin{figure}
\includegraphics[width=160mm]{fig_330_yieldsum.png}
\caption{\label{yieldsum} Total useful yield of pions with any sign as a function of energy, for four different target materials.}
\end{figure}

To clarify the optimisation, the pion yields of different signs may be summed to give the total yield as shown in figure \ref{yieldsum} for each material.  An optimal plateau in yield exists for the high-Z elements in the range 5--15\,GeV.  The `interesting' increase of carbon yield at low energy finally reaches a maximum at 1\,GeV before falling off.  The situation for each sign individually, as examined in the NuFact conference paper \cite{OurNuFact05paper} on these results, gives an optimal range (for high-Z targets) of 5--30\,GeV for $\pi^+$ and 5--10\,GeV for $\pi^-$.  The lower end of the plateau at 5\,GeV may not be as sharp in reality since MARS changes between different physics models over the range 3--5\,GeV (see figure \ref{hadronicmodels} and chapter \ref{-target-bench} in general for comparisons between codes and physics models).
\clearpage
\begin{figure}
\includegraphics[width=160mm]{fig_330_yieldcp.png}
\caption{\label{yieldcp} Effective useful yields of pions for CP violation calculations, which are calculated from results of both neutrinos and antineutrinos.}
\end{figure}

When the target produces different numbers of positive and negative useful pions and thus ultimately different numbers of neutrinos and antineutrinos of each flavour, it is sensible to ask what the impact of this lopsided mix of particles will be on the physics results.  Evaluating the mass differences $\Delta m^2_{ij}$ relies on measuring the oscillation length accurately and as particles and antiparticles have the same mass, the statistics from both neutrinos and antineutrinos undergoing the same oscillation channel may be added.  So for this application the summed figure of merit in figure \ref{yieldsum} is appropriate.  However, the CP-violating angle $\delta$ is measured via the relation \cite{CPviolation}
\[ s_{12}c_{12}s_{23}c_{23}s_{13}c_{13}^2\sin\delta \propto P(\bar\nu_\alpha \rightarrow \bar\nu_\beta)-P(\nu_\alpha \rightarrow \nu_\beta), \]
where $s_{ij}=\sin\theta_{ij}$, $c_{ij}=\cos\theta_{ij}$ and $\alpha$ and $\beta$ are some nonequal neutrino flavours.  Thus the parameter $\sin\delta$ is calculated from the difference of two oscillation probabilities, one of which is measured using the neutrinos and the other with the antineutrinos.  The individual statistical errors in these probabilities would be proportional to $1/\sqrt{Y_+}$ and $1/\sqrt{Y_-}$, which add in quadrature to make the statistical error in $\sin\delta$ proportional to $\sqrt{1/Y_++1/Y_-}$.  This is the same scaling behaviour as if the measurement had come from `simple' statistics with an effective yield $Y_\mathrm{eff}=(1/Y_++1/Y_-)^{-1}$, half the harmonic mean of the two signed yields and less than either of them individually.  $Y_\mathrm{eff}$ is plotted in figure \ref{yieldcp}, where although most of the graphs are a similar shape to the yield sum, the low-energy carbon peak is diminished because it was made up of a very uneven balance of positive and negative pions.  Positive pions dominate in the low-energy regime, in part due to the charge excess coming from the incident protons when production of $\pi^+\pi^-$ and similar charged pairs is not completely dominant.

\clearpage
\subsection{Variation of Heat Deposition with Energy}\label{-target-energy-heat}

While figure \ref{powerpie2} showed the division of incoming proton beam power for the standard target in table \ref{targrefsim}, this apportionment will change if the incoming protons have a different kinetic energy.  MARS outputs energy deposition data by default in the file \texttt{MARS.OUT} and this subsection uses that file to examine the results from the energy scan of the tantalum target in the previous section.

\begin{figure}
\includegraphics[width=160mm]{fig_331_powerenergy.png}
\caption{\label{powerenergy} Variation of heating in the 20\,cm-long tantalum target with incoming proton beam energy, which exhibits a minimum around 8\,GeV.  The kinetic energy of protons going to the forward beam dump and other selected secondaries are also plotted.}
\end{figure}

\begin{table}
\caption{\label{powerenergytable} Table of heat depositions in the rod as a function of proton beam energy.  The figures in kilowatts are scaled for a 4\,MW proton source.  The rightmost columns give the power going into the forward-directed protons of concern for the forward beam dump discussed in section \ref{-target-eng-dump}.  Compare with table \ref{powerlengthtable}.}
\begin{center}
\begin{tabular}{lcccc}
\hline
$E\eu{GeV}$&Heat deposited&kW&Protons within 5\degree&kW\\
\hline
2.2&24.7\%&988.7&14.4\%&577.0\\
3&22.8\%&912.4&15.5\%&619.2\\	   
4&18.8\%&750.1&16.2\%&649.8\\	   
5&14.6\%&582.9&18.1\%&724.5\\	   
6&13.1\%&525.1&21.8\%&872.3\\	   
8&12.8\%&512.0&23.2\%&927.0\\	   
10&12.9\%&514.4&24.3\%&974.0\\	   
15&13.6\%&543.7&27.1\%&1085.9\\	   
20&14.7\%&588.3&29.0\%&1160.4\\	   
30&16.6\%&665.2&29.7\%&1187.9\\	   
40&17.3\%&690.5&29.0\%&1160.2\\	   
50&17.8\%&711.7&28.3\%&1133.1\\	   
75&18.2\%&726.3&26.5\%&1059.0\\	   
100&18.5\%&739.7&26.4\%&1054.1\\	   
120&18.6\%&742.7&26.1\%&1043.4\\	 
\hline
\end{tabular}
\end{center}
\end{table}

Figure \ref{powerenergy} plots the results of integrating the energy deposition within the target to get the total heat deposition at each proton energy.  It also shows the variation of the proton power emitted in the forward cone of 5 degrees from the central axis, which was the other part of the energy flux that was separated out in figure \ref{powerpie2}'s inner pie chart.  Table \ref{powerenergytable} has the same results in numerical form.  As section \ref{-target-eng-thermal} described, the amount of heating in the target is a determining factor in the design, so minimising the heat deposited is an important goal when optimising the proton energy.  Fortunately, comparing figure \ref{powerenergy} with figure \ref{yieldsum} reveals that the optima for particle production and low heating lie at almost the same energy.  The range for which the summed useful pion yield for tantalum is within 10\% of the optimum value is 5--15\,GeV, whereas the range for which the rod heating is no more than 10\% above the minimal value is 6--15\,GeV.

\begin{figure}
\includegraphics[width=160mm]{fig_331_heatdistribution.png}
\caption{\label{heatdistribution} MARS15 simulations of heat deposition distributions for the standard tantalum rod with four different incoming proton beam energies.  The grid cells are 1\,mm squares and the proton beam enters from the left.  Heating is measured in Watts per kilogram (of target material) per Watt of incoming beam.}
\end{figure}

Figure \ref{heatdistribution} shows which areas of the rod are heated the most by the incoming proton beam at various energies.  The heating is not uniform, in fact uniform heating would be a fairly bad model of the situation so should only be used as an upper bound on the performance, such as in section \ref{-target-eng-thermal}.  The heating density $\vartheta$ is plotted in units of kg$^{-1}$ because the plots are universal for heating that scales with incoming proton power or energy.  Thus the unit may be thought of as either (J/kg)/J$_\mathrm{pulse}$ or (W/kg)/W$_\mathrm{beam}$.  The real heating power $H$ in a volume $V$ may be recovered using the formula
\[ H=P_\mathrm{beam}\ V\rho_\mathrm{Ta}\ \vartheta. \]
The peak of the heat deposition distribution moves further down the rod as proton energy increases.  At high energies this is because a 120\,GeV proton beam of a fixed power consists of fewer protons each carrying over 100 times its own rest mass in kinetic energy.  This energy is gradually converted into the mass of more hadronic particles in successive interactions forming a shower through the rod, in which the kinetic energy of daughter particles successively decreases as more hadrons are dislodged from nuclei.  This means that the bulk of the energy deposition is delayed in the case of higher-energy protons until a large number of slow ($<$GeV) hadronic secondaries are passing through the rod material.  This happens further down the rod as more generations of the shower are required to break down the energy in this way.  At low energies, the incoming protons are already of an energy where they produce slow secondaries, a significant number of which may even stop in the target, so the 2.2\,GeV heating distribution is intense and has a peak almost at the front end of the rod.  The overall intensity of heating in the rod is lowest for intermediate proton energies, reflecting the minimum in figure \ref{powerenergy} as expected.

The distribution shapes are not so radically different from each other to change the previous conclusion (derived only from the total heating) about which proton energies are preferred from the point of view of providing a favourable thermal environment for the target, however.

\comment{? Maybe even ratio graph of pions per heat deposited?  (Only doable for tantalum)}

\clearpage
\section{Rod Length}\label{-target-length}

The length of the rod can be varied to values other than the standard lengths in table \ref{interactionlengths}.  The optimisation consideration is to increase the rod length so that enough of the protons interact but not so much that the generated pions will spiral in the magnetic field and be reabsorbed by the rod.  This is, however, dependent on the magnetic field value and requires evaluation of the pion production at least at the endplane of the target, which is not what the surface production simulations here with no field give.  Instead, they will show only the production element of the situation, without the reabsorption.

Work on the reabsorption scenario has been done by Harold Kirk \cite{HaroldRodLength} and John Back \cite{JohnBackReabsorption}, giving similar optimal lengths to those assumed in the reference scenario for materials in the previous section, which is in turn similar to the `conventional wisdom' of using 2 interaction lengths for such target.  Varying the length produces a broad optimum with little variation in yield around this point, this is in fact why the author assumed some scaled lengths instead of optimising them first.  Thus the simulations in this section just provide some information about the pion source characteristics along the length of the rod and a `sanity check' on the MARS results compared to theory.

\begin{figure}[b!]
\includegraphics[width=160mm]{fig_340_yieldlength.png}
\caption{\label{yieldlength} Useful pion production from tantalum rods of various lengths, excluding reabsorption, together with inverted exponential fits using the 11.18\,cm hadronic interaction length of tantalum as the decay constant.  All other simulation parameters are as in table \ref{targrefsim}.}
\end{figure}
\clearpage
Figure \ref{yieldlength} shows the simulated production of pions weighted by the usefulness criterion developed in section \ref{-target-model-grid}.  Without reabsorption, these should fit an exponential law that for a rod of length $l$ gives
\[ \mbox{Production} = A(1-e^{-l/B}). \]
This model is derived from assuming the incoming protons have an equal probability of interacting in each length element of material and when they do interact, the same number of pions are produced at exactly that point along the rod.  The number of protons remaining thus decays, as does the pion production at any position going along the rod, so the integrated production becomes an inverted exponential.  A suitable choice for $B$ would be the hadronic interaction length given in table \ref{interactionlengths} and this is used for the fit lines shown on the graph, though $B$ can also be made a free parameter.

With $B$ fixed at 11.18\,cm, the best fit values of $A$ for the two signs are $A_+ = 0.00883$ and $A_- = 0.00948$ useful pions per proton$\cdot$GeV.  The RMS deviations of data values from the fit are 3.87\% for positives and 2.49\% for negatives, expressed as percentages of the relevant $A$ value, which sets the scale of the function.  As the protons are at 10\,GeV, there are roughly 0.076 useful pions per proton (for $l=20$\,cm) and thus the effective statistics are about 7600 pions from the original $10^5$ protons.  Therefore the statistical fit error would be expected to have size $1/\sqrt{7600} = 1.15\%$, which indicates this data has a small systematic deviation from the fit.  This can be seen by carefully examining graph \ref{yieldlength}, which shows the fit lines overestimating production early on but underestimating it later.

Allowing the value of $B$ to also become a parameter in the least squares fit improves the situation somewhat.  The two signs now have parameters $A_+ = 0.00938\,\pi/(\mathrm{p}\cdot\mathrm{GeV}), B_+ = 13.83$\,cm and $A_- = 0.00980, B_- = 12.70$ with RMS errors of 1.70\% and 1.26\% respectively.  This is about as close a fit as the statistics will allow.  It should be noted with caution that this does not mean the nuclear interaction length is `wrong', just that there are other complexities in the pion-generation process taking place in a rod of finite thickness that are not modelled exactly by the simple exponential fit.  For instance there is likely to be a forward emission angle so pions would be offset from their point of production when counted at the rod surface.  For interpolation purposes, the fits with modified $B$ are still useful.

\subsection{Variation of Heat Deposition with Length}\label{-target-length-heat}

The simulations of different length targets in the previous section also generated output files of energy deposition and outgoing particle distributions.  This means that the sectors of the inner pie chart in figure \ref{powerpie2} can be reconstructed for each length and the dependency on target length examined.  Again, these simulations do not include contributions from re-entrant pions that have spiralled back into the target due to the magnetic field, and in a similar way the criterion of `5 degrees angle of emission' is measured for protons at the rod surface assuming they continue in straight lines.

\begin{figure}
\includegraphics[width=160mm]{fig_341_powerlength.png}
\caption{\label{powerlength} Variation of some of the heat loads shown in figure \ref{powerpie2} with length of the tantalum rod.  The 20\,cm point corresponds to the reference simulation, with the points on either side retaining the baseline parameters from table \ref{targrefsim} except for rod length.}
\end{figure}

Figure \ref{powerlength} shows the variation of two energy measures with rod length.  The amount of heat deposited in the target increases with length but levels off, which can be explained if only a few particles penetrate to large distances to deposit heat, with the majority of energy having left the rod in the form of secondaries (corresponding to the inner blue segment in figure \ref{powerpie2}).  It also looks like it follows an inverted exponential curve as the production figures did in the last section.  Using the 11.18\,cm nuclear interaction length to set the exponential scale again, the best fit is achieved for
\[ H=0.1575(1-e^{-l/11.18}), \]
where $l$ is the target length in centimetres and $H$ is the heating in the target as a proportion of incident beam power.  The RMS error in this fit is 7.28\% so it is not particularly good.  Allowing the length scale to vary gives $H=0.1787(1-e^{-l/16.75})$ with an error of 2.52\%, which is better but the increase is still not fitted by a simple decaying exponential.  The reason for this can be found in figure \ref{heatdistribution}: if one of the central plots (there is no plot corresponding exactly to the 10\,GeV used here) is truncated at a certain length, the heating in a rod of that shorter length will be the integral of the heat deposition over that smaller volume.  The heating density takes a few centimetres to reach its peak, unlike an inverted exponential that has the highest rate of change at the beginning.  So there may be no simple model for the heat load as a function of length here.

The other line in figure \ref{powerlength} counts heat from protons at small angles that have not undergone kinematically severe interactions so emerge either from the end or glancingly out of the side of the rod having only been slightly scattered.  For short rods there will be a large contribution from protons that have gone from end to end and these are the `uninteracted' protons used in the exponential model of yield in the last section.  The decrease of this heat measure looks superficially like exponential decay but does not reduce fast enough at large rod lengths because of an accumulated population of protons that have scattered out of the sides of the rod and thus are no longer subject to progressive absorption by the rod material.  A fit will not be attempted for this reason, but the values of this and the other heat measure are tabulated in table \ref{powerlengthtable}.

\begin{table}
\caption{\label{powerlengthtable} Heat deposition in the target and power in the forward proton beam dump for various lengths of tantalum rod.  Kilowatt figures are scaled for a 4\,MW proton source.}
\begin{center}
\begin{tabular}{lcccc}
\hline
Target length (cm)&Heat deposited&kW&Protons within 5\degree&kW\\	   
\hline
5&3.7\%&147.9&69.8\%&2792.9\\	   
10&7.8\%&311.4&48.8\%&1950.1\\	   
15&10.8\%&431.6&33.9\%&1357.3\\	   
20&12.9\%&514.4&24.3\%&974.0\\	   
30&15.3\%&611.1&13.9\%&556.0\\	   
40&16.2\%&648.1&9.7\%&386.6\\	   
50&16.6\%&662.8&8.1\%&325.3\\	 
\hline
\end{tabular}
\end{center}
\end{table}

Both of these heat factors are of concern to the target station design: the heating for the integrity of the rod itself and the forward protons for their beam dump (see section~\ref{-target-eng-thermal} for more detailed discussion).  The amount of heat in the forward protons varies quite steeply with increased rod length, meaning that if the forward beam dump becomes difficult, increasing the target length could reduce its heat load by a factor of 2--3$\times$.  This would not impact pion yield as steeply, though care must be taken with reabsorption effects not included here.  \comment{WHAT IS THIS I DONT EVEN It is also notable that the reduction in forward proton heat is larger than the increase in rod heating for longer lengths, meaning that not all the heat is being absorbed by the target, some is diffused by the scattering angles of the protons increasing.}

\section{Rod Radius}\label{-target-radius}

The radius of the cylindrical target could be other than the 1\,cm used so far.  The advantage of using a wider target is that if the incoming proton beam size expands proportionately, the energy deposition density decreases by the square of the radius, potentially making thermal shock issues much more manageable.  The disadvantage is that the thickened target can absorb more of the pions generated in its interior before they exit.  To take advantage of the former point, the simulations in this section have kept the proton beam radius equal to rod radius as it varies, which also avoids excessive yield loss from absorption because protons will be producing pions all the way to the surface.

\begin{figure}
\includegraphics[width=160mm]{fig_350_yieldradius.png}
\caption{\label{yieldradius} Effect of varying the radius of the cylindrical tantalum target on useful pion yield.  Graphs are plotted for two different incoming proton energies and both pion signs.}
\end{figure}

Output particle sets were obtained from MARS for both low (2.2\,GeV) and high (30\,GeV) proton beam energies, for both pion signs, with all other parameters as in table \ref{targrefsim}.  The useful pion yield was calculated by the formula used throughout this chapter and the results plotted in figure \ref{yieldradius}.  The different energies have different overall levels of yield, with a charge asymmetry in favour of positive pions for the 2.2\,GeV case since at low energies the charge excess from positive protons is still visible above the pion charge-pair production.  For radii of 1\,cm and above, the graphs show a steady reduction as the radius increases (barring some statistical noise), which can be explained by absorption of pions by tantalum nuclei in the target.  A more surprising feature is that the yield also starts to fall off for very thin rods.  This is because tantalum and similar elements are high-Z targets and charged particles passing through a medium experience multiple Coulomb scattering with cross section proportional to $Z^2$ for the material.  This cross section is also multiplied by the material density when calculating the number of interactions, so since tantalum is both high-Z ($Z=73$) and dense ($\rho=16.7$\,g/cm$^3$), it scatters the incoming protons quite strongly.  For thin targets, this scattering is enough to knock a significant number of protons out of the target material by the time they reach the end 20\,cm away, which results in a decrease in pion production.

\begin{figure}
\includegraphics[width=160mm]{fig_350_yieldradiusrel.png}
\caption{\label{yieldradiusrel} Useful pion yield variation with radius as a proportion of the $r=1$\,cm case.}
\end{figure}

Figure \ref{yieldradiusrel} isolates the radius dependence in the four scenarios by taking the ratio with the 1\,cm situation in each case.  It is difficult to optimise further than the 1\,cm radius case; although all points between 0.5 and 1\,cm radius have comparable yields, heat deposition density scaling as the inverse square of radius would be up to 4$\times$ as large.

\comment{? Absorption vs. scattering model (at least mention scattering and model absorption)}

\clearpage
\subsection{Rod with a Hole}\label{-target-radius-hole}

During the investigation of the target yields, it was suggested that boring a hole along the axis of the rod might reduce on average the path length in material for emitted pions and thus decrease reaborption.  This would waste protons that go through the hole, but it was suggested that a hollow phase space distribution could be created for the protons that minimised the number in this area.  Therefore some MARS simulations were run for targets with various sized holes.

\begin{figure}
\includegraphics[width=160mm]{fig_351_yieldhole.png}
\caption{\label{yieldhole} Useful pion yield as an increasingly-large hole is bored along the axis of the target, simulated with a uniform density proton beam (protons going through the hole are lost).}
\end{figure}

The standard target simulation (table \ref{targrefsim}) was modified in one important way aside from drilling a hole: the other simulations so far have used a parabolic proton distribution with a varying density, higher at the centre and decreasing to zero at the edges, used to represent a standard proton beam from a synchrotron.  However, the beam for hollow targets will be optimised for the purpose, so this is no longer relevant.  The simplest way to investigate any improvement from the hole without having to worry about proton accelerator issues is to use a uniform distribution, so the proton flux is the same everywhere on the front face of the target, including the hole where a known proportion $(r_\mathrm{hole}/r)^2$ are wasted and miss the target completely.  Thus in figure \ref{yieldhole} the results for $0\le r_\mathrm{hole}\le 0.8$\,cm are plotted for both signs and the low and high proton energies used in the last section.  This figure on its own is not particularly useful as the curves look similar to scaled graphs of the non-wasted proton beam proportion $1-(r_\mathrm{hole}/r)^2$ and the question is whether the yield per \emph{impacting} proton has been improved.
\clearpage
\begin{figure}
\includegraphics[width=160mm]{fig_351_yieldholerel.png}
\caption{\label{yieldholerel} Useful pions per proton hitting the target rather than the hole, displayed as a ratios to the yield efficiency of the whole-target case.}
\end{figure}

Figure \ref{yieldholerel} shows the same pion yields divided by the proportion of protons hitting the target for each hole radius and normalised to the case with $r_\mathrm{hole}=0$\,cm (a whole target).  It shows that the efficiency of the target is, if anything, made worse by the incorporation of a hole, so this possibility for the target design may be excluded.  The worsening of the efficiency for the targets with the largest holes could be explained by the out-scattering of protons from the remaining target, the same effect that made targets with very small radii inefficient.

\section{Proton Beam Distribution}\label{-target-pdist}

The previous subsection (\ref{-target-radius-hole}) alluded to the fact that the transverse distribution of the incoming proton beam was not in fact fixed but might be tailored to the target, to the extent possible, if this would increase the useful pion yield.  This beam manipulation would probably be done with optical elements in the transfer line taking the extracted beam from the final proton ring to the target.  Quadrupole magnets control the beam focussing in linear terms and can change the proton spot size in both axes (investigated in section \ref{-target-pdist-radius}) and higher order magnets such as octupoles can apply nonlinear distortions to the beam distribution, creating for example a beam with more particles towards the edges than in the circular parabolic case.  A uniform beam is one such example and is compared in section \ref{-target-pdist-uniform}.

\subsection{Proton Beam Radius}\label{-target-pdist-radius}

\begin{figure}
\includegraphics[width=160mm]{fig_361_yieldbeamradius.png}
\caption{\label{yieldbeamradius} Effect (or rather, non-effect) on yield of having the incoming proton beam smaller than the 1\,cm radius of a tungsten target cylinder.  With $1\sigma$ statistical error bars.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_362_yielduniform.png}
\caption{\label{yielduniform} Comparison of pion yields generated by uniform versus parabolic transverse proton beam distributions hitting the tantalum target, at two energies.  $1\sigma$ statistical error bars are shown.}
\end{figure}

Figure \ref{yieldbeamradius} shows the variation in useful pion yield when the target radius is kept at 1\,cm but the proton beam radius is scaled to 3\,mm or 1\,mm as well as the full-size case.  There is very little effect on either pion sign, so statistical error bars of one sigma from the simulation were plotted.  The most significant difference is between the 3\,mm and 1\,cm beam radii for the negative pions and here the difference is $2.9\sigma$ in favour of using a full-sized beam.  This would be consistent with the theory that pions coming from the smaller beam would always have to travel through at least 7\,mm of material (6\% of a hadronic interaction length for tantalum) before leaving the rod, so may be reabsorbed more, but the difference is too small to make a conclusion.

% \subsection{Proton Beam Offset}\label{-target-pdist-offset}

\subsection{Circular Uniform Beam vs. Circular Parabolic}\label{-target-pdist-uniform}

Changing the proton beam distribution from the circular parabolic with density $\rho(r)\propto 1-(r/R)^2$ to a uniform density ($\rho(r)\propto 1$) beam will mean more particles near the edge of the rod, though the difference will not be as dramatic as between the 3\,mm and 1\,cm radii parabolic beams in the last section.  Figure \ref{yielduniform} compares the yields for the two distributions, for both signs of pion and two proton energies, with one sigma statistical error bars shown on each value.  The difference between the bars normally falls within the error bars, the most deviant case being the 30\,GeV positive pions where the circular parabolic distribution yield is larger than the uniform by $3.4\sigma$.  As in the previous subsection, the conclusion is that the difference in yield from changing the proton distribution is too small to be significant in these simulations and is certainly less than 10\%.  Quite possibly this is too small to be significant at all in the design.

\section{Downstream Effects}\label{-target-downstream}

All the other sections in this chapter consider the optimisation of the target decoupled from the rest of the system, based on local variables such as the momenta of the pions at the rod surface.  This section looks at two effects where there is nontrivial coupling between the proton beam energy on the target and the downstream front-end.  Section \ref{-target-downstream-kaons} examines the contribution of the decay chain of kaons, only produced for higher proton energies and mostly decaying outside the target.  Section \ref{-target-downstream-losses} examines how the location of beam losses changes in the front end as the proton energy is varied.

\subsection{Pion Production from Kaons}\label{-target-downstream-kaons}

The charged kaons $K^+$ and $K^-$ can be produced in a target bombarded by a high-energy proton beam and have a mean lifetime of 12.4\,ns (compared to 26.0\,ns for the charged pion).  Since they are produced at relativistic speeds, they will travel several metres before decaying and so will not decay within the MARS target simulation.

\begin{table}[b]
\caption{\label{kaondecays} Principal decay channels of the kaon \cite{PDG-Review}, together with the number of pion and muon products and thus the expected number of eventual muons from each channel.}
\begin{center}
\begin{tabular}{ccccc}
\hline
$K^+$ decay to&Probability&\#$\mu$&\#$\pi$&Mean eventual muons\\
\hline
$\mu^+\nu_\mu$&63.39$\pm$0.18\%&1&0&0.6339$\pm$0.0018\\
$\pi^0e^+\nu_e$&4.93$\pm$0.07\%&0&0&0\\
$\pi^0\mu^+\nu_\mu$&3.30$\pm$0.06\%&1&0&0.0330$\pm$0.0006\\
$\pi^+\pi^0$&21.03$\pm$0.13\%&0&1&0.2103$\pm$0.0013\\
$\pi^+\pi^0\pi^0$&1.757$\pm$0.023\%&0&1&0.0176$\pm$0.0002\\
$\pi^+\pi^+\pi^-$&5.59$\pm$0.05\%&0&3&0.1677$\pm$0.0015\\
\hline
Total&(100\%)&&&1.0624$\pm$0.0028\\
\hline
\end{tabular}
\end{center}
\end{table}

The major decay channels of $K^+$ and their respective probabilities are shown in table \ref{kaondecays}.  Many of the decay channels produce charged pions or muons, which will contribute to the neutrino factory yield.  The charged pion itself has a 99.98770$\pm$0.00004\% probability of decaying into a muon \cite{PDG-Review}, so effectively the numbers of the two are added together, minus a tiny factor.  This arithmetic reveals that on average, a charged kaon will ultimately produce about 1.06 muons and is therefore roughly equivalent to having a pion in the same location.

\begin{figure}
\includegraphics[width=160mm]{fig_371_kaonproduction.png}
\caption{\label{kaonproduction} Comparison of the number of pions and kaons produced by the tantalum rod target at various proton beam energies.}
\end{figure}

Figure \ref{kaonproduction} shows the total number of charged kaons as well as pions produced by the target.  Below 4\,GeV, no kaons are produced at all, whereas at the highest energies the positive kaons are adding another 6\% to the total particle count and the more rarely produced negative kaons contribute 3\%.  There is a slight mixing between the signs introduced by the $K^+\rightarrow\pi^+\pi^+\pi^-$ decay but this will only account for 5.6\% of the decays of the few percent of kaons, so is negligible.  Thus kaons produce a small but systematic increase in yields for higher proton beam energies, particularly for positive particles.

\subsection{Redistribution of Losses}\label{-target-downstream-losses}

While previous sections dealt with beam transmission, the pions and muons that are lost will produce radioactive hot spots in the muon front end due to beam loss.  The dumping of protons was discussed in section \ref{-target-eng-dump} and there will be a large level of general activation around the immediate target area from neutrons and other particles, but losses from pions and muons present a different problem because they are the intended particle for the focussing channel and can thus propagate a long way downstream before being lost.

\begin{figure}
\includegraphics[width=160mm]{fig_372_lossredistrib.png}
\caption{\label{lossredistrib} Losses of pions and muons redistribute themselves through the decay channel as the proton energy on the target is varied.  Values are plotted as a fraction of the initial number of pions from the target; the
total is slightly more than 100\% due to decays such as $K^+\rightarrow\pi^+\pi^+\pi^-$.}
\end{figure}

Therefore the Muon1 code was run on a particular pion decay channel and phase rotation system, specifically the optimal lattice from the \texttt{PhaseRotC} optimisation discussed in section \ref{-results-phaserot}, with a logging mechanism to count the weight of lost particles along the axis of the channel.  Based on their location, the losses were put into categories and plotted as proportions of initial pions in figure \ref{lossredistrib}, which also includes small strips at the bottom to represent on- and off-energy particles reaching the end of the beamline (the off-energy particles will be lost even further downstream).  `Backwards' losses are those from pions travelling in the wrong $z$ direction, so they hit the beam plug before the \texttt{S1} 20\,T solenoid (\texttt{D1} refers to the first drift space before \texttt{S2}, the lower field solenoid that follows).  `Reimpacted' losses are those that are reabsorbed in the tantalum cylinder target according to a simple absorption-length model, though \cite{JohnBackReabsorption} has a full study of this.

This exercise was repeated for all the proton energies for which MARS output particle sets were available (see \cite{MyEPAC06Paper} for the complete report).  Kinematically it might be expected that the pion angular distribution will change as the forward proton momentum increases and this is consistent with the trends appearing in the graph.  At low proton energies more (up to 61\%) of the pions are lost within the first solenoid (\texttt{S1}) and target area, whereas at high energies this decreases to 28\% but the losses in the decay channel excluding \texttt{S1} have more than doubled from 23\% to 55\%.  So the increased boost from the proton is producing pions at more forward angles that are lost further down the decay channel.  Beyond the decay channel, the amount of remaining beam at each stage exhibits a humped shape with an optimum in the mid-energies and this coupling to proton energy no longer changes, indicating that the beam has been cut down to an accepted region where only the magnitude of yield within the region is important and not its precise distribution.

This suggests the beamline beyond the end of the decay channel is decoupled from the choice of proton beam energy other than by the scaling in pion yield, which means optimisation of those later sections can be done independently of the proton driver choice.

\section{Summary of Optimal Target Parameters}\label{-target-summary}

The values in table \ref{targetparams} summarise many considerations about the performance of the target.  The proton energy, target radius and lack of a hole are chosen to optimise pion yield, with the important proton energy checked again with a different code in the next chapter.  The proton beam radius and rod angle have a weak effect on yield (plots for rod angle are shown on the final page of \cite{JohnBackReabsorption}), so the beam radius is chosen to reduce thermal shock and the rod angle to mitigate the proton hot spot on the beam dump.  The proton distribution is likely fixed at roughly circular parabolic by the proton accelerator itself but this was found not to be a disadvantage for pion yield.

There remain many feasible choices for the target material, as the lines in figure~\ref{yieldsum} achieve comparable peak performances for achievable proton energies (this excludes the 1\,GeV carbon peak).  This report assumes a high-Z material similar to tantalum or tungsten, while \cite{HaroldRodLength} examines the optimisation in the carbon target case and figures for carbon are also given.  Section \ref{-target-length} shows the exponential levelling off of yield with increasing number of hadronic interaction lengths in the target but does not account for reabsorption of pions hitting the target for a second time, since this requires tracking of pions outside the target including a magnetic field.  As the magnetic field will be varied in a later optimisation using Muon1, it is unknown at the point of generating the initial pion distribution.  However, other studies including \cite{HaroldRodLength,JohnBackReabsorption} find that the peak yield is for practical purposes very close to the $\sim$1.8 interaction lengths given in table \ref{interactionlengths}.

\begin{table}[h]
\caption{\label{targetparams} Recommended neutrino factory target parameters, assuming a solid target.}
\begin{center}
\begin{tabular}{llll}
\hline
Component&Parameter&Recommended value&Source\\
\hline
&Energy ($E_k$)&5--15\,GeV&\S\ref{-target-energy}, \S\ref{-target-geant4}, \cite{OurNuFact05paper}\\
Proton beam&Radius&Equal to target radius&\S\ref{-target-pdist-radius}\\
&Distribution&Circular parabolic&\S\ref{-target-pdist-uniform}\\
\hline
&Material&Tantalum used here (others possible)&\S\ref{-target-energy}\\
&Length&20\,cm for Ta, $\sim$60\,cm for carbon&Table \ref{interactionlengths}, \cite{HaroldRodLength}\\
Target&Radius&1\,cm for high-Z, 1.25\,cm for carbon&\S\ref{-target-radius}, \cite{HaroldRodLength}\\
&Shape&Solid cylinder with no hole&\S\ref{-target-radius-hole}\\
&Angle&14\,mrad to accelerator axis&\S\ref{-target-eng-dump}, \cite{JohnBackReabsorption}\\
\hline
\end{tabular}
\end{center}
\end{table}

\chapter{Benchmarking Pion Production}\label{-target-bench}
When predicting pion production figures in the regime of the neutrino factory, it is important to realise that before the HARP experiment \cite{HARP}, there was no systematic attempt to measure pion yields in this energy domain.  Thus the MARS15 cross section models had to be fitted to what little data there was available, with some interpolation based on how proton cross sections behave (see the MARS15 manual \cite{MARS15manual} section on hadron production).  GEANT4 was in a similar situation.  Section \ref{-target-geant4} sees how close these different models are to each other and \ref{-target-harp} attempts a comparison of MARS15 with recent HARP data.

\section{Comparison with GEANT4}\label{-target-geant4}

Without a code available that incorporates the HARP data, comparing with the results of another code will roughly gauge the uncertainties present in the current models.  The GEANT4 code \cite{GEANT4} is also commonly used by particle physicists to model the interaction of particles with matter, so it was used as a comparison point for MARS.

Results in this section are from a collaboration with K. Walaron who wrote a more comprehensive report about benchmarking GEANT4 with MARS15 on this problem \cite{KennyGEANT4MARSnote}.  The findings were also presented in a paper \cite{OurNuFact05paper} and the author's talk at the NuFact'05 conference.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_380_yieldg4mars.png}
\caption{\label{yieldg4mars} The results from two different Monte Carlo codes in predicting the yield of useful pions from the target as a function of incoming proton energy.}
\end{figure}

\begin{table}
\caption{\label{optimabycode} The proton energy ranges over which pion yield is near-optimal, as predicted by MARS15 and GEANT4 for each sign of pion.}
\begin{center}
\begin{tabular}{lll}
\hline
Code&Optimal $\pi^+$&Optimal $\pi^-$\\
\hline
MARS15&5--30\,GeV&5--10\,GeV\\
GEANT4&4--10\,GeV&8--10\,GeV\\
\hline
\end{tabular}
\end{center}
\end{table}

The standard target problem specified in table \ref{targrefsim} was reposed as a GEANT4 input data set and run for the same range of energies as the MARS15 simulations in section \ref{-target-energy}.  The generated pions were weighted by the process defined in section \ref{-target-model-grid} and the resulting figure of `useful pions' plotted on the same graph in figure \ref{yieldg4mars}.  Although the form of the graph with an optimum at intermediate proton energies is similar between the two codes, there is a factor of 1.35--3.05 (average 1.85) difference in absolute yield between the two, meaning that the predictive accuracy of these codes is still at a fairly rudimentary level in this situation.  Both codes were run using default hadronic model settings, the effect of changing these in GEANT4 is explored in the next section.

Fortunately, the conclusions relevant to the neutrino factory about the optimal energy for the proton driver are not contradictory between the two codes and are summarised in table \ref{optimabycode}.  The energy range of 8--10\,GeV is safely within the optimal range for both signs, according to both of the codes used here.  This is as good a recommendation as possible using tools at this stage of development and was the one given to the International Scoping Study \cite{ISS} in 2006 when defining their baseline parameter set for the neutrino factory.

\subsection{Energy Cutoffs in Hadronic Models}

GEANT4 provides several modes called `use cases' for selecting the models used at different energies for hadronic particle production models.  Multiple models may be necessary because cross sections involving protons cannot be calculated from first principles and must use either a simplified physical model or a fit from measured data, both of which may only be applicable in a certain energy range.

\begin{figure}
\includegraphics[width=160mm]{fig_381_g4modeldiverge.png}
\caption{\label{g4modeldiverge} Comparison of all the available hadronic modes of GEANT4 together with MARS15 results for the total pion yield from the standard tantalum target.}
\end{figure}

To see the effect of use cases on the results, all the possible choices were run for a range of energies and the total (uncut) pion yield plotted in each case, resulting in figure \ref{g4modeldiverge}.  It shows that the binary cascade (BIC) models diverge from the rest of the predictions, including MARS, as the proton energy decreases.  The Bertini cascade (BERT) models also have a different shaped energy dependence but it is not as severe.  These results are provided for information only here, as a detailed dissection of the GEANT4 code's hadronic sector is beyond the scope of this thesis.

\begin{figure}
\includegraphics[width=160mm]{fig_381_hadronicmodels.png}
\caption{\label{hadronicmodels} Diagram of energy cutoffs between hadronic models used in different GEANT4 `use cases'.  The MARS15 model is linearly mixed from the cascade-exciton model (CEM2003) at 3\,GeV to the MARS inclusive hadron production model at 5\,GeV.}
\end{figure}

Figure \ref{hadronicmodels} shows how MARS15 and the various GEANT4 modes use different models at different energies; the 25\,GeV cutoff in GEANT4 may not be as sharp as depicted because some difference at 10\,GeV was found when changing the high-energy component in figure \ref{g4modeldiverge}.  The ramp between 3 and 5\,GeV in MARS is also noteworthy when interpreting the yield graphs earlier in this chapter, as `corners' in the plots at those values may be an artefact of the random mixing which the code makes between the two models, which uses proportions of each model that vary linearly in energy from zero to 100\% over that energy range.  Extrapolating the pure model lines from $\le 3$\,GeV and $\ge 5$\,GeV in an example such as figure \ref{pgridcompareminus} would probably form two lines that do not meet, showing again that these models are not much better than a factor of 2 accurate in prediction of absolute pion yields.

\clearpage
\section{Comparison with Early HARP Data}\label{-target-harp}

The HARP experiment \cite{HARP} was designed to measure the production cross sections of $\pi^+$ and $\pi^-$ from high-energy protons on various solid targets of different atomic number ($Z$).  The applications for this data include studies of superbeams, neutrino factories and muon colliders, all of which generate a tertiary beam (of muons or neutrinos) from the pions that are produced in large numbers (compared to other possible parent particles) when hadrons hit a solid target.  Importantly, the experiment was also designed to measure the double-differential cross section $\dmixed{\sigma}{p}{\theta}$, which may be integrated across an area in $(p,\theta)$ space to retrieve a partial cross section $\sigma$ for the range of interest.  This level of detail enables a full comparison with the output of Monte Carlo code such as MARS15.

\begin{table}[h]
\caption{\label{harpenergies} The four proton momenta used in the HARP experiment, converted to kinetic energies in GeV used for protons throughout the rest of this chapter.}
\begin{center}
\begin{tabular}{cc}
\hline
$p\eu{GeV/c}$&$E_k\eu{GeV}$\\
\hline
3&2.205\\	   
5&4.149\\	   
8&7.117\\	   
12&11.098\\	 
\hline
\end{tabular}
\end{center}
\end{table}

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpdetectors.png}
\caption{\label{harpdetectors} The pion momentum space plot of figure~\ref{fatephaserotator} with the acceptance ranges of the two HARP detectors superimposed.  The Large Angle Spectrometer (LAS) is the central area and the forward spectrometer extends beyond the right edge of the plot to $|\p|=6500$\,MeV/c.  The density of successful pions (white) leaving the channel is highlighted as grey squares, note this is different from the \emph{probability} of transmission plotted in figure~\ref{pgridsmooth}.}
\end{figure}

HARP used protons of four different energies extracted from the CERN PS (Proton Synchrotron).  The energies used are actually specified exactly in terms of the proton momentum in GeV/c but the GeV kinetic energy equivalents are also listed in table \ref{harpenergies}.  This range is a subset at the low end of the energy range studied in the rest of this chapter.  HARP had two detectors: a forward spectrometer that detects pions of low angle and relatively high energies and a Large Angle Spectrometer (LAS) that detects generally slower pions at higher angles.  The locations of the detectors' apertures in $(p_L,p_T)$ momentum space is plotted in figure \ref{harpdetectors}, which also highlights the region of useful pion yield for the neutrino factory front end.  Results from the forward spectrometer on an aluminium target are reported in \cite{HARP-Al-forward} but this momentum range is of more interest for superbeams and misses the neutrino factory zone completely.  The LAS overlaps with about half of the useful yield region, missing the areas below its lower $\theta$ limit of 0.35 radians.  HARP LAS results have been reported for a tantalum target in \cite{HARP-Ta-LAS}, which is relevant for the solid neutrino factory target (and of a similar $Z$ to a mercury jet) and forms the basis of the comparison with MARS15 in this section.

\begin{table}
\caption{\label{harpsim} Parameters of the MARS15 simulation of the (small) tantalum cylinder used in the HARP 5\% interaction length study.}
\begin{center}
\begin{tabular}{ll}
\hline
Code Used&MARS15\\
Target Material&Tantalum\\
Target Shape&Cylindrical\\
Target Dimensions&5.6\,mm length $\times$ 15.1\,mm\comment{15.07063\,mm\footnotemark[2]} radius\\
Target Mass&66.195\,g ($\rho_\mathrm{Ta}^{harp}=16.59$\,g/cm$^3$ derived)\\
Protons Per Monte Carlo Run&$10^6$\\
Proton Beam Profile&\cbox{0.5}{Parallel pencil beam at centre of target endface, 1\% RMS Gaussian momentum spread.}\\
\hline
\comment{ \multicolumn{2}{l}{\cbox{0.85}{\footnotesize{\footnotemark[2]Exact value used in the simulation.  This is the average of four micrometer measurements and not genuinely accurate to this many decimal places.}}} }
\end{tabular}
\end{center}
\end{table}

The HARP tantalum target is a cylinder and was replicated in a modified MARS simulation using the parameters in table \ref{harpsim}.  The short length of 5.6\,mm is to produce approximately 5\% of a hadronic interaction length in tantalum so that it behaves approximately as a `thin target' (or foil) allowing extraction of the cross section without too much interference from cumulative absorption, energy loss or scattering of protons or pions.  The dimensions were derived from measurements of the target recorded in the data sheet at \link{http://www.hep.shef.ac.uk/research/harp/ta5.html}.
\clearpage

The full range of results across all pion momentum and angular bins, for both pion signs and all four incoming proton energies are plotted in figures \ref{harpmarspositives} and \ref{harpmarsnegatives}.  Converting the MARS output, which is in terms of weighted numbers of pions in various bins for a known number of protons, into a cross section requires knowledge of the number density $\rho_N$ of tantalum nuclei in the simulated target.  The density of tantalum is $\rho_\mathrm{Ta}^{mars}=16.68$\,g/cm$^3$ and its atomic mass is $A=180.9$, so
\[ \rho_N = N_A \frac{\rho_\mathrm{Ta}^{mars}}{A} = 5.551 \times 10^{22}\mbox{\,cm$^{-3}$}, \]
where $N_A$ is Avogadro's number.  Next, given the path length $l$ in centimetres and the observation that a total weight $w$ of pions were produced from $N$ incoming protons in the simulation, the cross section may be estimated as
\[ \sigma\eu{barns} = \frac{w}{Nl\rho_N10^{-24}}. \]
This formula is also correct if $w$ and $\sigma$ are only counted for pions within a particular zone of momentum space.  If the zone is a small region such as one of the HARP momentum bins, the double differential cross section in that bin can be estimated by dividing $\sigma$ by the area of that bin in $(p,\theta)$ space.

Some more consolidated (and easier to interpret!) graphs are presented in figure \ref{harpmarsforwardbackward}, which combines the forward and backward parts of the HARP detector, and in figure \ref{harpmarssignratio}, which looks purely at the ratio between the signs in only the forward hemisphere.  Figure \ref{harpmarsforwardbackward} shows that MARS15 is underestimating the production of pions in backward directions by a factor of 2 or more, whereas the forward direction has a rather better fit, though MARS produces a peculiar kink around $p=200$\,MeV/c in the 3\,GeV/c proton case.  Figure \ref{harpmarssignratio} shows that MARS is producing proportionately more negative pions than the HARP data suggests is the case.  The HARP data shows an excess of positive pions, increasing at low energies, while the MARS15 data is more equal but also tends to include more positives as the proton energy decreases.

Finally, the overall pion cross section may be plotted as a function of proton kinetic energy, to provide a link with the results of section \ref{-target-energy}.  This is not quite a `pion yield' because the target here is much shorter than any neutrino factory would use, but \comment{the relative size of }the cross section in the relevant momentum zone may be compared across proton energies as a guide.  The HARP report \cite{HARP-Ta-LAS} also performed this analysis and chose the zone with $\theta<0.95$\,rad and $250\le|\p|<500$\,MeV/c to represent the neutrino factory, which encompasses the region on figure \ref{harpdetectors} where the acceptance overlaps with the detector.  This is not totally correct because the yield from the most forward pions is missing, but being aware of this caveat, the comparison graph may still be plotted, giving figure \ref{harpmarscutyield} where MARS15 has used the same cut as HARP.  The lines at the top of the graph are total yields in the forward hemisphere of LAS (excluding the $p\ge700$\,MeV/c bin as in the HARP report).

The author's interpretation of figure \ref{harpmarscutyield} is as follows.  In total, MARS produces too many $\pi^-$ (by up to 24\%) and too few $\pi^+$ (by up to 16\%) at all energies, but the agreement at the $\sim$20\% level is encouraging given the large discrepancy with GEANT4 discussed in section \ref{-target-geant4}.  When the cross sections are cut nearer to the domain of interest, the positive pion value never deviates by more than 13\% between MARS and measurements, whereas the situation for $\pi^-$ becomes worse, with MARS always overestimating the yield, sometimes by as much as 44\% in the case of negative pions at 4\,GeV.

\clearpage

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpmarspositives.png}
\caption{\label{harpmarspositives} $\pi^+$ cross sections in all bins of the HARP Large Angle Spectrometer (black) together with MARS15 simulated values (red).  Compare with figure 23 of the HARP report \cite{HARP-Ta-LAS}.  Numbers in the top-right of graphs are the angular bins in milliradians.  MARS error bars are 1$\sigma$ statistical; HARP error bars are 1$\sigma$ but also include systematics.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpmarsnegatives.png}
\caption{\label{harpmarsnegatives} $\pi^-$ cross sections in all bins of the HARP Large Angle Spectrometer (black) together with MARS15 simulated values (red).  Compare with figure 24 of the HARP report \cite{HARP-Ta-LAS}.  MARS error bars are 1$\sigma$ statistical; HARP error bars are 1$\sigma$ but also include systematics.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpmarsforwardbackward.png}
\caption{\label{harpmarsforwardbackward} HARP measurements of forward (left) and backward (right) pion production cross sections for $\pi^+$ (top) and $\pi^-$ (bottom), comparable with figure 26 in \cite{HARP-Ta-LAS}.  MARS15 simulation predictions for the same quantities are in red, with 1$\sigma$ statistical error bars.  HARP 1$\sigma$ error bars also include systematics.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpmarssignratio.png}
\caption{\label{harpmarssignratio} Ratio of negative over positive pions in the forward region of the HARP Large Angle Spectrometer.  HARP measurements are in black and MARS15 simulation results in red.  This is comparable with figure 27 of \cite{HARP-Ta-LAS}.  MARS error bars are 1$\sigma$ statistical; HARP error bars are 1$\sigma$ but also include systematics.}
\end{figure}

\clearpage

\begin{figure}
\includegraphics[width=160mm]{fig_390_harpmarscutyield.png}
\caption{\label{harpmarscutyield} Pion cross section per GeV of proton energy as a function of the proton beam energy.  Results are shown both for the entire forward LAS acceptance with $|\p|<700$\,MeV/c and for a cut with $\theta<0.95$\,rad and $250\le|\p|<500$\,MeV/c in the area of the neutrino factory acceptance.  This plot is comparable to figure 30 of \cite{HARP-Ta-LAS} without the $\theta$-only cut.  MARS error bars are 1$\sigma$ statistical; HARP error bars are 1$\sigma$ but also include systematics.}
\end{figure}

The energy dependence characteristics for both MARS and HARP data suggest that the optimal proton energy is around 5\,GeV, lower than previously concluded, with a slightly faster drop off as the energy increases.  Note however that the exclusion of forward pions with $\theta<0.35$\,rad from the calculation may systematically bias towards lower proton energies where the lack of forward momentum allows more pions to escape with larger angles.  The fact that even the MARS results now favour this lower energy suggests this change may be due to the difference in cuts rather than a difference between the code and reality.  Additionally, the slope between 5\,GeV yields and those at 10\,GeV was not very steep in previous MARS results, so it could be reversed by quite a small effect.  One energy dependence feature that is definitely different between code and reality is how the MARS results fall much more rapidly than HARP when going from 5 to 3\,GeV/c proton momentum.  This is due to the interpolation between hadron models that kick in for MARS at about this energy, as illustrated in figure \ref{hadronicmodels}.

Overall, the agreement between MARS15 and HARP data in the pion momentum and proton energy ranges of interest, with the correct target material, is very encouraging for positive pions (deviations of less than 13\% in these figures of merit), whereas MARS overestimates negative pion production here by about 30\%, which should be taken into account in future.  Later releases of MARS and GEANT will hopefully integrate more sophisticated fits from the HARP data and allow more accurate evaluation, perhaps at the 10\% level or better, of the neutrino factory pion yield.


\chapter{Muon Energy Loss and Scattering Algorithm}\label{-cool}
The beam in the neutrino factory front end is larger and more divergent than those found in conventional accelerators.  The \emph{emittance} of a beam (defined in section \ref{-cool-linear-emittance}) is a measure of the beam size and divergence that is invariant under optical elements such as magnets, so can only be reduced via other means.  D. Neuffer in 1983 therefore proposed \emph{muon ionisation cooling} \cite{CoolingReference,CoolingReference2}, originally intended for muon colliders, that uses the energy loss of muons in a low-Z material to reduce the emittance.  However, the material also causes scattering of the muons, which increases the emittance.  After presenting analytic approximations of the resultant cooling rate along a section of beamline, the main result of this chapter is an accurate computer model of scattering using cross-sections of the muon--$\mathrm{LH_2}$ interaction that can be integrated into tracking codes.

Although this cooling model has been integrated into Muon1, it was found that there exist promising front ends without cooling (see chapter \ref{-results}), provided a muon linac is used for further acceleration.  Thus the main results of this thesis do not include muon cooling but performance of the cooling algorithm on a 30\,cm $\mathrm{LH_2}$ block is presented in this chapter.

\section{Principle of Muon Cooling}\label{-cool-principle}
The muons from the decay channel have transverse momenta of up to 200\,MeV/c, whereas beams in conventional accelerators have particles with much lower $p_T$, which can be handled with weaker magnets.  For example the ISIS \cite{ISIS} proton accelerator covers the energy range 70--800\,MeV (of the same order as the muons) but the $p_T$ of the protons does not exceed 30\,MeV/c.  Optically, $p_T$ can be decreased by defocussing the beam to a larger spatial size but the muon beam is already very large ($\sim$30\,cm width) in the phase rotation channel, so that method of decreasing $p_T$ is not an option.

Liouville's Theorem prohibits a system of pure electric and magnetic fields from reducing the amount of position-momentum phase space occupied by a beam with a very large number of particles.  Without going into detail, this is because these systems can be modelled as a Hamiltonian system and Liouville's Theorem is a mathematical consequence of Hamilton's equations \cite{Goldstein1950}.

For muon cooling and other applications where this phase space volume must be reduced, exceptions to the conditions of this theorem must be found.  One way is to notice a beam is not a continuum of infinitely-many particles and statistical effects may be used.  A famous example of this is stochastic cooling of protons \cite{StochasticCooling}, which relies on the small deviation of the centroid of the beam due to statistical fluctuations to create an opposing electric field, cancelling a small amount of the beam spatial spread and over very many revolutions reducing the beam size in a ring significantly.  This method becomes slower in proportion to the square root of the longitudinal density of particles, typically taking seconds for proton beams, so would be unsuitable for the neutrino factory's high-intensity muon beam given the muon's short lifetime.  \footnote[2]{The statistical exception to Liouville's Theorem can also allow emittance \emph{growth}: repeated nonlinear forces (or dynamical distortions) acting on the beam can eventually cause the continuous volume in phase space containing the beam to become so twisted and intermixed with a larger external volume that it is no longer well-represented by the limited number of particles it contains.  At this point, the beam is considered to have grown in phase space volume and fills a larger region with a lower density.}

Another class of exceptions to Liouville's Theorem is when the dynamics are not fully represented by a Hamiltonian system.  Introducing an additional process, very often an interaction with matter, can give systems of this sort.  One example is `charge-stripping injection' in which an ion such as H$^-$ encounters a thin foil and has its electrons stripped off, giving a proton.  This is an irreversible process as protons reencountering the foil are just scattered slightly.  The effect is that many copies of an original H$^-$ beam may be superimposed on the same phase space for protons because they come from outside the protons' Hamiltonian system using the foil; superimposition of the two different-sign beams is easily done using a dipole magnet because they bend in opposite directions.  Scattering is also a non-Hamiltonian process as the scattering kick given to each particle is random and not a function of its canonical coordinates: this increases the phase space volume and results in beam `heating'.

The primary mechanism used in ionisation cooling is the energy loss of particles as they collide with those of matter, causing the matter to heat up slightly.  This is a member of the class of non-Hamiltonian exceptions to Liouville's Theorem.  It may not seem obvious that deceleration in matter is a non-Hamiltonian system, as it can be described by smooth differential equations under some circumstances.  Assuming the material is homogenous and stationary, the formulae for $\dot{x}$ and $\dot{p}$, that is $\pdd{H}{p}$ and $-\pdd{H}{x}$, must not depend on $x$ or $t$.  If $\pdd{H}{p}$ is only a function of $p$ then $H=f(p)+g(x,t)$.  Now $\dot{p}=-\pdd{H}{x}=-\pdd{g}{x}(x,t)$, but this must also depend only on $p$, thus is a constant, which is inconsistent with deceleration of particles in all directions because $\dot{p}$ must be negative for positive $p$ and \emph{vice versa}.  So energy loss in materials is a possible candidate for non-Liouvillian reduction of the phase space volume (`cooling') of the beam.

\begin{figure}
\includegraphics[width=160mm]{fig_410_coolarrows.png}
\caption{\label{coolarrows} Muon momentum is reduced in magnitude~(step~1) along the direction of travel by some material before being replenished by forward momentum by an RF cavity~(step~3).  This would reduce the $p_T$ of all muons if it were not for scattering in the material~(step~2) that counteracts the reduction when $p_T$ is small enough.  Diagram adapted from \cite{CoolArrowsDiagram}.}
\end{figure}

The reduction of momentum regardless of its direction is the important feature of energy loss in the context of a cooling system.  Removing energy from a nearly-parallel beam is equivalent to putting it through a decelerating electric field, which is known to be Liouvillian, so the important effects can only appear when the beam is put through the energy absorber with a range of angles.  These are shown as effects on the particle's momentum vector in figure \ref{coolarrows}: the particle loses energy in its direction of travel, experiences some scattering (an inevitable material effect that heats the beam) and then can be reaccelerated in a phase-space-conserving way by the electric field of an RF cavity.  Notice that for sufficiently large incident particle angles (relative to the RF axis), or sufficiently small amounts of scattering, this results in a beam in which \emph{all} particles have momentum vectors more parallel to the axis than before.  Because the non-Liouvillian absorber is present, this no longer comes at the cost of an enlarged beam in positional coordinates, though it does come at the cost of magnets to provide \comment{the sufficiently }large angles \comment{whilst going through }in the absorber.

\begin{figure}
\includegraphics[width=160mm]{fig_410_study2coolcell.png}
\caption{\label{study2coolcell} Cross section of the cooling lattice cell from US Study~II \cite{Study2}, containing four-cell RF cavities with liquid hydrogen absorbers between.  The surrounding solenoid coils can be seen as rectangular blocks.}
\end{figure}

\comment{How might such a system be practically realised?}  The US Feasibility Study~II \cite{Study2} performed a detailed investigation of a channel of absorbers, magnets and RF cavities to achieve muon ionisation cooling, resulting in their design of a cooling unit cell shown in figure \ref{study2coolcell}.  As the $Z$ of the absorber material increases, scattering increases faster than the energy loss, meaning that the optimal material to use is liquid hydrogen (gaseous hydrogen not being dense enough to have an effect within a practical length).  This choice implies a complex cryogenic system and containment for the hydrogen, which must also be contained with low-Z (but not liquid) windows, beryllium being chosen there.  To avoid a net deceleration of the beam, the amount of RF must be balanced to that of absorber and the channel must also be relatively short to reduce muon decays.  Finally, the\comment{powerful} focussing magnets must be added, solenoids being used here for their axial symmetry and short focal length for relatively low-energy beams.

The $\mathrm{LH_2}$ design is the one being tested in the MICE experiment \cite{MICE}.  However, the more recent ISS \cite{ISS} and IDS \cite{IDSbaseline} designs have used lithium hydride (LiH) absorbers, trading off some cooling performance in the higher $Z$ material in exchange for a simpler cooling cell with less cryogenics.  It is also possible to reclaim some of the lost performance by having thinner beryllium windows on the RF cavities because the windows are no longer structural: they are supported by the LiH absorber material.

\section{Cooling Rates from Linearised Optics}\label{-cool-linear-rate}
\newcommand{\twiss}[1]{\raisebox{-3.125pt}{\includegraphics[height=12pt]{t#1.png}}}
\newcommand{\talpha}{\twiss{alpha}}
\newcommand{\tbeta}{\twiss{beta}}
\newcommand{\tgamma}{\twiss{gamma}}
\newcommand{\erms}{{\varepsilon^\mathrm{un}_\mathrm{rms}}}
\newcommand{\enrms}{{\varepsilon^\mathrm{n}_\mathrm{rms}}}
The effect of the beam passing through matter may be approximated while staying within the linear optics model described in appendix \ref{-cool-linear}.\ \ A single transverse plane $(x,x')$ will be considered and `emittance' in this section will usually be the normalised RMS emittance of that plane.  As explained in section \ref{-cool-principle}, a cooling channel normally consists of reacceleration after the energy-absorbing material: thus the choice of normalised emittance, which is constant under acceleration.  If the un-normalised emittance had been chosen instead, it would appear to decrease in the accelerating cavities but increase in the material from scattering, though the net effect would be the same as the material-only effect on the normalised value, provided the beam ends the channel with the same energy it started with.

The useful part of material interaction with regard to cooling is the energy loss per unit length of material $\dd{E}{z}<0$, which can be derived from the Bethe--Bloch formula \cite{BetheBloch}.  With pure energy loss, $x'$ stays the same while $x$ continues to evolve as in a drift space, so the only effect on $\enrms$ is via the normalising factor $\beta\gamma$.
\begin{eqnarray*}
\left(\dd{\enrms}{z}\right)_\mathrm{loss} &=& \dd{}{z}\left[\beta\gamma\erms\right] = \erms \dd{(\beta\gamma)}{z} \\
&=& \erms \dd{(\beta\gamma)}{E} \dd{E}{z} = \erms \frac{1}{mc^2} \dd{(\beta\gamma)}{\gamma} \dd{E}{z} \\
&=& \frac{\erms}{\beta mc^2} \dd{E}{z} = \frac{\enrms}{\beta^2\gamma mc^2} \dd{E}{z} \\
&=& \frac{\enrms}{\beta^2(mc^2+E_k)} \dd{E}{z}
\end{eqnarray*}
Here, $E_k$ is the kinetic energy of the particle and $m$ is its rest mass ($\mathrm d E$ is identical for kinetic or total energy).  The formula shows that the negative $\dd{E}{z}$ of the material causes a reduction in emittance, which cannot go below~0 due to the presence of $\enrms$ on the right-hand side.  If the particle were kept at a constant~$E_k$ (and~$\beta$) by compensating acceleration, the predicted cooling \emph{without scattering} in a uniform material can be evaluated by defining the cooling rate $k>0$:
\begin{eqnarray*}
-k &=& \dd{\ln\enrms}{z} = \frac{1}{\enrms}\dd{\enrms}{z} = \frac{\hd{E}{z}}{\beta^2(mc^2+E_k)}\\
&\Rightarrow& \enrms(z) = \enrms(0) e^{-kz}.
\end{eqnarray*}
The Bethe--Bloch curves give a point of minimum energy loss at approximately $\beta\gamma=4$.  This is of interest mainly because the energy loss does not change much with particle energy around this point, so beams with energy spread do not undergo nonuniform deceleration, to first order.  For muons this corresponds to $E_k=330$\,MeV and $\beta=0.970$, a little higher than the energy in the muon front end.  In liquid hydrogen at this point, the energy loss is 3.97\,MeV per gram/cm$^2$ of material \cite{PDG-Review}, or $\dd{E}{z}=-28.2$\,MeV/m given its density of only 0.071\,g/cm$^3$.  For graphite, the energy loss is 1.74\,MeV per g/cm$^2$ \cite{GraphiteEnergyLoss} and the density varies depending on grade but is approximately 2.2\,g/cm$^3$, giving $\dd{E}{z}=-383$\,MeV/m.  The cooling rates are therefore $k_\mathrm{LH_2}=0.0687$\,m$^{-1}$ and $k_\mathrm{graphite}=0.935$\,m$^{-1}$.  At $\beta\gamma=2.5$ in liquid hydrogen the energy loss per unit length is a few percent higher but $k_\mathrm{LH_2}$ increases to 0.120\,m$^{-1}$, mainly through the reduction of $E_k$ to 179\,MeV, so the energy lost is a greater proportion of the muon's kinetic energy.  179\,MeV is very near the front end energy.  Continuing to decrease $E_k$ would theoretically increase the cooling rate arbitrarily, but the benefits are lost from the nonuniform deceleration experienced far from the Bethe--Bloch minimum and scattering in the material, discussed next.

Collisions with the electrons and nuclei in a material cause frequent random changes to the incoming particle's momentum.  In the case of muons, these collisions are almost entirely electromagnetic in nature (as opposed to pions that can also undergo hadronic processes).  For the purposes of the linear model, these will be approximated by a continuous random walk in which $\ang{x'^2}$ increases linearly with distance.  This generates an increase in beam emittance.  By the Central Limit Theorem, the process will produce a Gaussian distribution if continued indefinitely from any starting distribution and a Gaussian distribution is the only one that will emerge unchanged apart from an increase in variance.  It is also a small-angle approximation that neglects large-angle scatters that occur in rare head-on collisions with nuclei and will usually lead to the muon being lost.

The starting point is a formula \cite{ScatteringEqn} for the RMS angular deflection (projected into one transverse plane) of a particle emerging from a thickness $z$ of material with radiation length $X_0$:
\[ \theta_\mathrm{rms} = \frac{13.6\,\mathrm{MeV/c}}{\beta p}(q/e)\sqrt{\frac{z}{X_0}}\left(1+0.038\ln\frac{z}{X_0}\right), \]
where $q/e$ is the charge of the particle in electron units and $p$ is the forward momentum.  This comes from a fit to the more comprehensive Moli\`ere theory of scattering; the logarithmic term in brackets to the right is not compatible with the simple random walk model but fortunately has values within a few per cent of unity for thicknesses of similar order to $X_0$.  For liquid hydrogen, $X_0=8.90$\,m and for graphite, 0.193\,m, which are similar to the characteristic cooling lengths $1/k$ defined previously, so this approximation is likely to be good for cooling systems.  Neglecting this term and using the small-angle approximation $\theta \simeq x'$, the outgoing mean square muon angle is
\[ \ang{x'^2} = \theta_\mathrm{rms}^2 = \frac{(13.6\,\mathrm{MeV/c})^2}{\beta^2 p^2}(q/e)^2\frac{z}{X_0}, \]
which increases linearly with $z$ by
\[ \dd{\ang{x'^2}}{z} = \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2}{\beta^2 p^2 X_0}. \]
Recalling the definition of 2D RMS emittance from section \ref{-cool-linear-twiss}, the normalised emittance under consideration can be written in terms of beam moments
\[ \enrms = \beta\gamma\erms = \beta\gamma\sqrt{\ang{x^2}\ang{x'^2}-\ang{xx'}^2}. \]
The scattering process considered separately to energy loss does not affect the relativistic factors $\beta$ and $\gamma$; nor does it immediately (without drift) affect the beam size $\ang{x^2}$ or the correlation $\ang{xx'}$ because the scatters are uncorrelated with $x$ position.  Only $\ang{x'^2}$ remains as a relevant variable and the effect of scattering on emittance may be evaluated directly using the chain rule:
\begin{eqnarray*}
\left(\dd{\enrms}{z}\right)_\mathrm{scatter} &=& \dd{\enrms}{\ang{x'^2}}\dd{\ang{x'^2}}{z} \\
&=& \beta\gamma\dd{}{\ang{x'^2}}\left[\sqrt{\ang{x^2}\ang{x'^2}-\ang{xx'}^2}\right]\dd{\ang{x'^2}}{z} \\
&=& \beta\gamma\ \frac{\ang{x^2}}{2\sqrt{\ang{x^2}\ang{x'^2}-\ang{xx'}^2}}\ \dd{\ang{x'^2}}{z} = \beta\gamma\frac{\ang{x^2}}{2\erms}\dd{\ang{x'^2}}{z}.
\end{eqnarray*}
Recalling the definition of the Twiss function $\tbeta=\ang{x^2}/\erms$ and using the earlier formula for $\hd{\ang{x'^2}}{z}$,
\begin{eqnarray*}
\left(\dd{\enrms}{z}\right)_\mathrm{scatter} &=& \frac{\beta\gamma\tbeta}{2} \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2}{\beta^2 p^2 X_0} = \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2\gamma\tbeta}{2\beta p^2 X_0} \\
&=& \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2\gamma\tbeta}{2\beta^3 \gamma^2 m^2 c^2 X_0} = \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2\tbeta}{2\beta^3 (mc^2+E_k) m X_0}.
\end{eqnarray*}
Combining these results gives the overall change in emittance in a uniform absorbing material with both scattering and energy loss \cite{CoolFormula}:
\[ \dd{\enrms}{z} = \left(\dd{\enrms}{z}\right)_\mathrm{loss} + \left(\dd{\enrms}{z}\right)_\mathrm{scatter} = \frac{\enrms}{\beta^2(mc^2+E_k)} \dd{E}{z} + \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2\tbeta}{2\beta^3 (mc^2+E_k) m X_0}. \]
This consists of a negative part that is proportional to $\enrms$ and a positive part that is constant.  Ignoring kinematic factors, the negative (cooling) term is maximised by choosing a very negative $\dd{E}{z}$ and the positive (heating) term is minimised by choosing a large $X_0$ and small $\tbeta$ in the cooling medium.  Note that the $\tbeta$ is actually a function of $z$ depending on the optics of the beam in the absorber, but with many absorbers it can be replaced by an averaged constant value.

The cooling equation can be solved to give an offset exponential:
\newcommand{\eeq}{\varepsilon_\mathrm{eq}}
\begin{eqnarray*}
\dd{\enrms}{z} &=& -k\enrms + h \\
\Rightarrow \quad \enrms(z) &=& \left(\enrms(0)-h/k\right) e^{-kz} + h/k \\
&=& \left(\enrms(0)-\eeq\right) e^{-kz} + \eeq,
\end{eqnarray*}
where the cooling rate $k$ is defined as before, $h$ is the heating term and the \emph{equilibrium emittance}
\[ \eeq = h/k = \frac{(13.6\,\mathrm{MeV/c})^2(q/e)^2\tbeta}{2\beta m X_0 (-\hd{E}{z})} \]
is the value that $\enrms$ converges to as $z\rightarrow\infty$.  If $\enrms$ starts below $\eeq$ then the scattering dominates the cooling from energy loss and the beam emittance grows.  Note that $(q/e)^2=1$ for muons.

For solids and liquids, it is the reaccelerating RF systems and not the energy loss in the material that determine how large the average $\dd{E}{z}$ in a channel can be.  It is also possible to cool using a large amount of gas but this time higher pressures ($\sim$100\,atm) are needed to prevent the slow energy loss from making the cooling channel impractically long.  When the beam emittance is much larger than $\eeq$, the average energy loss rate is the dominating factor in how rapidly the cooling progresses, so the channel is optimised for the limited apertures of the RF cavities to allow as much reacceleration as possible.  Liquid hydrogen is often cited as a good cooling material \cite{MICE} because it has the lowest $X_0$ of any solid or liquid, the low scattering allowing beams to have relatively low $x'$ in the absorbers.  To optimise the performance of cooling in the final, low-emittance stages, $\eeq$ can be reduced by choosing materials with the highest possible product $X_0(-\hd{E}{z})$, which favours slightly higher-Z materials such as graphite.  At this point the emittance is assumed to be small enough that optics with high $x'$ (low $\tbeta$) in the absorbers can be produced without the beam later becoming too large for the RF apertures.

\subsection{Example}
\newcommand{\ein}{\varepsilon_\mathrm{in}}
\newcommand{\eout}{\varepsilon_\mathrm{out}}
The best yielding front end from chapter \ref{-results} produces a beam with RMS normalised emittance $\ein=14812$\,\mmmrad\ when projected into either transverse phase space plane (table \ref{emittances}).  Suppose one wishes to add cooling to this front end until the beam can be transmitted by an FFAG-based accelerator that has a normalised acceptance of only $A_\mathrm{out}=15000$\,\mmmrad\ in each plane, instead of a muon linac.  Transverse focussing optics suitable for cooling channels are described in detail in \cite{PennNote}; here the absorber and beta function from the start of the Study II \cite{Study2} cooling channel are used.

The acceptance places a hard cut on particles outside the ellipse of $\pi$ times that area, whereas the ellipse corresponding to the RMS emittance contains only $1-\sqrt{1/e}=39.35$\% of a beam with a Gaussian distribution.  After more than one cooling length in a cooling channel, the beam will become very close to a Gaussian, so that distribution is assumed here.  If 95\% of the beam is required to be within the 2D ellipses of both planes, it is sufficient to ensure that 97.5\% is within each one.  The amount of a 2D Gaussian outside $n$ sigma is $e^{-n^2/2}$ and setting this lost amount to 2.5\% gives $n=2.716$.  Since $A_\mathrm{out}=n^2\eout$, the required normalised RMS output emittance $\eout=2033$\,\mmmrad\ is derived.

The central beam momentum in the channel is 200\,MeV/c, corresponding to a kinetic energy $E_k=120.5$\,MeV.\ \ Each 2.75\,m cell contains a 35\,cm thick liquid hydrogen absorber, plus enough RF cavities to restore the lost beam energy.  The beta function minimum where the absorber is located is $\tbeta=47$\,cm.  Using the data for $\mathrm{LH_2}$ given previously in this section and $X_{0,\mathrm{LH_2}}=8.81$\,m, calculated from Tsai's formula \cite{TsaiRadiationLength}, the equilibrium RMS emittance is
\[ \eeq = \frac{(13.6\,\mathrm{MeV/c})^2\ 0.47\,\mathrm{m}}{2(0.884)(105.7\,\mathrm{MeV/c^2})(8.81\,\mathrm{m})(28.2\,\mathrm{MeV/m})} = 0.001873\,\mathrm{m} = 1873\,\mathrm{mm\cdot mrad}, \]
which is definitely small enough for this example.  The length of cooling material required can be found by setting $\enrms(0)=\ein$ and $\enrms(z)=\eout$:
\[ \enrms(z) = \left(\enrms(0)-\eeq\right) e^{-kz} + \eeq \quad \Rightarrow \quad z=\frac1k\ln\left(\frac{\ein-\eeq}{\eout-\eeq}\right). \]
For the muon energy considered,  $k=0.159$\,m$^{-1}$ and the log term is $\ln(80.7)=4.39$, giving a total material length of $z_\mathrm{LH_2}=27.53$\,m required for cooling.  To get this thickness requires 79 of the 35\,cm Study II absorber units and therefore 79 cooling lattice cells of 2.75\,m length each, giving a total cooling channel length of 217.25\,m.

Finally, note that since $\beta\gamma=1.89$, the input beam's 99\% normalised emittance of 97455\,\mmmrad\ corresponds to an un-normalised emittance $\varepsilon^\mathrm{un}_\mathrm{99}=51485$\,\mmmrad\ at the start of the cooling channel.  The radius of the beam at the absorber may be calculated using the beta function: $r=\sqrt{\tbeta\varepsilon^\mathrm{un}_\mathrm{99}}=15.6$\,cm.  The absorbers specified in Study II have a window diameter of 360\,mm ($r=18$\,cm), which is large enough for the beam from the front end.

\section{Using the ELMS Scattering Model for Liquid Hydrogen}\label{-cool-elms}

\begin{figure}
\subfigure[Magnitudes of the delta function elements shown as colours.]
{\includegraphics[width=160mm]{fig_440_elmsdata(a).png}}
\subfigure[\label{elmsdata-cut} Location of the soft/hard collision cut.]
{\includegraphics[width=160mm]{fig_440_elmsdata(b).png}}
\caption{\label{elmsdata} Elements of the ELMS \cite{ELMS} muon--$\mathrm{LH_2}$ cross-section for a 200\,MeV/c muon on a log-log plot.  The diagonal lines with a sharp downward bend at the end (`nuclear' and `electron') would be half-ellipses on a linear graph.}
\end{figure}

A model of the interaction of muons with matter is required in order to simulate the cooling channel in Muon1.  These interactions consist of different types of collisions by the muons with atomic electrons and nuclei, each of which transfers a certain amount of transverse and a certain amount of (backward) longitudinal momentum to the muon.  These also depend on the incoming muon momentum, so abstractly a material $M$ can be described by a function $F_M(\Delta p_L,\Delta p_T;p)$ where $\int\!\!\int F_M(\Delta p_L,\Delta p_T;p)\D\Delta p_L\D\Delta p_T$ gives the frequency of collisions (in inverse metres) along the path of a muon with momentum $p$.  Integrating over a specific range of $(\Delta p_L,\Delta p_T)$ momentum kicks gives the partial frequency of collisions in that range.  This function is related simply to the double differential cross-section by the molecular number density $\rho_M$ of the material:
\[ F_M = \rho_M \dmixed{\sigma_M}{\Delta p_L}{\Delta p_T}. \]

The ELMS software \cite{ELMSsoftware} was developed at Oxford for the purpose of tracking muons in a realistic manner through a block of $\mathrm{LH_2}$ material.  Previous treatments condensed many physical processes into typically just two: longitudinal momentum loss of the muon as it is retarded by the material and multiple scattering, often modelled in the assumption of a large number of soft collisions, producing a Gaussian random walk in transverse momentum.  ELMS uses photoabsorption cross-sections in conjunction with atomic physics to determine the full form of $F_M$ (reported in \cite{ELMS}), in which scattering and energy loss are no longer independent processes but instead each collision will cause a little of each.

A log-log plot of the function $F_\mathrm{LH_2}$ (for liquid hydrogen) with $p=200$\,MeV/c is shown in figure \ref{elmsdata}.  The dotting in some regions is because $F_M$ is a probability distribution and is approximated in ELMS by a sum of delta functions: colours in the plot represent the magnitude of each of these and are also on a log scale.

Given this input, tracking a muon through the material is just a matter of sampling the probability distribution and applying the momentum kick at each collision.  These occur as a Poisson process along the path, with rate equal to the integral of $F_M$ for the current muon momentum.  Unfortunately, this rate is $9.7\times10^5$\,m$^{-1}$ for a 200\,MeV/c muon, which leads to slow tracking since this is typically 2500 collisions per Muon1 timestep.

\section{Accelerated Scattering Tracking Algorithm}\label{-cool-algorithm}
To increase the speed of the scattering model, Muon1 separates the relatively rare `hard' collisions, in which the muon momentum and direction can change dramatically, from the frequently occurring softer collisions.  For soft collisions, both the paraxial approximation (small angles) and the Central Limit Theorem (frequent collisions with no long tails in distribution) apply, meaning that the evolution of the muon momentum in the intervals \emph{between} successive hard collisions can be treated as a Gaussian continuous random walk.  This is exactly what simpler models such as the one used in section \ref{-cool-linear-rate} do everywhere but here it has higher accuracy because the statistically ill-conditioned events have been removed.  The expected momentum loss, transverse scattering variance and `straggling' variance (statistical variation of $\hd{E}{z}$), which determine the Gaussian $\Delta\p$ distribution, can be reconstructed from 1\st and 2\nd moments of $F_M(\Delta p_L,\Delta p_T;p)$, where the integrals are performed over the soft region below the cut:
\newcommand{\iint}{\int\!\!\!\int}
\begin{eqnarray*}
\frac{1}{v_z}\dd{E}{z} = \dd{\ang{p_L}}{z} &=& \iint \Delta p_L F_M \D\Delta p_L\D\Delta p_T \qquad \mbox{(momentum/energy loss);} \\
\dd{\Var(p_T)}{z} &=& \iint (\Delta p_T)^2 F_M \D\Delta p_L\D\Delta p_T \qquad \mbox{(multiple scattering);} \\
\dd{\Var(p_L)}{z} &=& \iint (\Delta p_L)^2 F_M \D\Delta p_L\D\Delta p_T - \left(\dd{\ang{p_L}}{z}\right)^2 \qquad \mbox{(straggling).}
\end{eqnarray*}
Here, $\Var(x)$ is the variance operator defined as $\ang{(x-\ang{x})^2} = \ang{x^2}-\ang{x}^2$, a quantity that adds linearly when independent random variables such as the $\Delta\p$ from individual scatters are added to each other.  Note that $\mathrm{d}\ang{p_T}/\mathrm{d}z=0$ by symmetry.
 
\begin{figure}
\includegraphics[width=160mm]{fig_440_muonpaths.png}
\caption{\label{muonpaths} A pencil beam of muons is simulated entering an LH$_2$ absorber.
(top)  Transverse view of 100 simulated muon paths, looking into the absorber.  
(bottom)  The same paths seen from the side, on a much larger scale (figures in metres).}
\end{figure}
\begin{figure}
\includegraphics[width=160mm]{fig_440_muondistrib.png}
\caption{\label{muondistrib} Distributions of energy loss and exit angle for 200\,MeV/c muons simulated through 30\,cm of LH$_2$.  The green plot is $10^4$ muons run with individual ELMS collisions, red points are $10^6$ muons using the faster method.  1$\sigma$ statistical error bars are shown.}
\end{figure}

A suitable cut between soft and hard collisions (shown in figure \ref{elmsdata-cut}) was chosen for the integrals.  The tracking algorithm models the occurrence of hard collisions as a Poisson process in path length, calculating those collisions exactly and using the Gaussian momentum changes from soft collisions on the segments between.  The new algorithm performed 1200 times faster than modelling every collision individually.  Muon tracks such as those shown in figure \ref{muonpaths} are produced, with distributions coming out of the absorber that are so far indistinguishable from complete tracking, as shown in figure \ref{muondistrib}.

\comment{OK, some sort of Fourier transform/central limit theorem kind of error bound proof might be possible here but I'm bailing out.}

\subsection{Comparison with ICOOL}

\begin{figure}
\includegraphics[width=160mm]{fig_441_icoolcomparison.png}
\caption{\label{icoolcomparison} Distributions of energy loss and exit angle for one million 200\,MeV/c muons simulated through 30\,cm of LH$_2$.  The red plot uses the faster ELMS-based method developed in this chapter; the blue plot is ICOOL \cite{ICOOL} on default settings.  1$\sigma$ statistical error bars are shown.}
\end{figure}

The same problem with 30\,cm of liquid hydrogen was run using the code ICOOL \cite{ICOOL}, which also includes muon scattering and energy loss models.  Figure \ref{icoolcomparison} shows the result, with ICOOL agreeing with the ELMS-based method for scattering but having a differently-shaped tail in the energy loss distribution.  It should be noted that ICOOL includes several options for these physics models but the defaults were selected here.  The input file for this ICOOL run is listed in appendix \ref{--ICOOL}.

\section{Integration with Muon1}\label{-cool-integration}
The issue of combining sporadic events like collisions with the otherwise smooth Runge--Kutta tracking of a particle curving along its trajectory has been touched on briefly in section \ref{-code-collide-iso}, which gives a procedure for finding the collision point with an isosurface.  The exact intersection point is found by a root-finding algorithm in $t$ but the position of the particle at each of the various $t$ values tested by this algorithm has to be calculated by invoking the Runge--Kutta algorithm for a partial timestep.

Particle decays are another type of sporadic event and the time distribution of these was described in section \ref{-code-decay}, without implementation details.  Here Muon1 takes the easy option: since the timescale of pion decay is much larger than the 0.01\,ns tracking timestep, rounding the decay time to the next timestep is not considered a bad approximation and decays are performed at the end of timesteps for any particles whose internal proper time clock exceeds their next scheduled decay time.  Quantitatively, the error in this method is to increase the average pion lifetime by less than 1 part in 5000.

The reason for this recap about sporadic events is that the scattering tracking algorithm described in previous sections introduces quite frequent ones, which the Muon1 tracking logic must handle properly.  In figure \ref{muonpaths} the hard scatters are just visible as black dots marked along the purple trajectories and they occur with a similar frequency to the $\sim$3\,mm Muon1 timesteps.  The soft scatters also need to be added as a Gaussian perturbation to every substep inside a material.

To describe explicitly the hierarchy of steps and substeps required to take account of all four effects on the particle's motion (the three above plus bending from magnetic fields included in the Runge--Kutta integration), the actual stack of functions called by Muon1 is presented herein.  The stack roughly reflects the size scales at which different phenomena take place, mnemonically: $fields \prec scattering \prec geometry \prec decays$.

\begin{itemize}
\item \texttt{Simulation\_advance} is the top-level function called by the main loop of Muon1 repeatedly during a simulation.  It advances the whole beam by one timestep, including all physics effects.  In fact, because Muon1 detects the number of CPUs present on a computer and splits the beam into an equal number of particles for each, this function is mostly thread-synchronisation and wrapper code, spawning copies of \texttt{Simulation\_advance\_t} in parallel.
\item \texttt{Simulation\_advance\_t} is a single-threaded function that advances a range of particles by one timestep including all physics effects.  For each particle, it calls \texttt{collideparticle} repeatedly if necessary, advancing the particle through one contiguous geometry region at a time until its timestep is over.  At this point, \texttt{decay}\-\texttt{particle} is called on it.
\begin{itemize}
\item \texttt{decayparticle} checks if a particle is due to decay by its internal proper time clock and if so, uses the algorithm described in section \ref{-code-decay-mbody} to generate its decay products.  It calls no further functions.
\end{itemize}
\item \texttt{collideparticle} tracks a particle to the end of its current geometry region, including magnetic fields and scattering but not decays.  The main purpose is to determine the first surface the particle hits, which marks where it leaves the region.  The function loops through all components potentially in the vicinity of the particle (as per section \ref{-code-collide-bbox}) and calls the collision function for each, which varies from component to component; this in turn usually calls \texttt{scatterparticle\_isocd} a number of times to see if the particle's path hits any of the isosurfaces described in section \ref{-code-collide-iso}.
\item \texttt{scatterparticle\_isocd} determines where a particle hits an arbitrary isosurface, supplied as a function pointer argument.  It uses a hybrid algorithm of Newton--Raphson root finding, root bracketing and bisection (in awkward cases) to find the value of $t$ when the particle is on the surface.  It is important to note that every position of the particle used by this algorithm is calculated by a call to \texttt{scatterparticle} over a substep, so it takes full account of magnetic fields and scattering.
\item \texttt{scatterparticle} advances a particle by a given $\dt$ through a known material.  If the material is vacuum, this passes control directly to \texttt{advanceparticle}, otherwise it uses the algorithm described in section \ref{-cool-algorithm} to calculate a sequence of steps between successive `hard' collisions.  The intervening steps are each a call to \texttt{advanceparticle} with the `soft' Gaussian scattering contribution added on to the momentum afterwards.
\item \texttt{advanceparticle} is the core Runge--Kutta routine within Muon1 and tracks a particle through a magnetic field over a specified timestep using the algorithm in section \ref{-code-rk}.  It does not take account of material scattering, geometry or particle decays.  The required $\Bv$ field values at various points are obtained by summing the contributions from components suspected to be near the particle, each calculated by that component's magnetic field function (if any).
\end{itemize}

\comment{The intelligent reader will ask how I can use a "random" procedure as a subroutine of a root-finding algorithm.  Well, I could have gone on about how each particle carries its own deterministic random number generator, but I didn't.}


\chapter{Design and Optimisation System}\label{-optimiser}
The accelerator design must be specified to the Muon1 code so that the components and magnetic fields can be correctly placed in the simulation space and the algorithms described in chapter \ref{-code} applied.  Section \ref{-optimiser-lattice} describes the general format of Muon1 lattice files, which can be used to specify either a single accelerator or an optimisation range of designs.  After simulation, designs are scored with the figures of merit in section \ref{-optimiser-score} and logged in result files described in section \ref{-optimiser-resultfile}, where they can be used as input for the genetic algorithm (section \ref{-optimiser-algorithm}) that selects new designs to simulate.  As this process of repeated simulation takes a large amount of computing time, it has been deployed as a distributed computing project (section \ref{-optimiser-distributed}) where the spare CPU time of volunteers from the Internet is used.

\section{Muon1 Lattice Files}\label{-optimiser-lattice}
Accelerators are specified to Muon1 via `lattice files', which are text files of a special form placed in the \texttt{lattices} directory, located in the same folder as the program \texttt{muon1.exe}.  Lattices are simulated with a command such as \texttt{muon1 -c LatticeName}, which will run \texttt{lattices$\backslash$LatticeName.txt} on the command-line.  A full list of the command-line switches available is displayed by invoking the \texttt{muon1 -?} help switch.

Instead of providing an exhaustive reference to the lattice file format, which may evolve over time, this section will give a series of examples that show the general capabilities of the system.

\subsection{A Simple Beamline of Components}
In its basic form, a lattice file defines a set of components of different types having different physical attributes such as length, magnetic field, etc.  These components are then placed successively along a theoretical reference axis for the accelerator built out of a sequence of straights and circular arcs.  After the components have been defined, the order of the components along the beamline is given, as shown in the lattice file below.

\texttt{\\
\{\\
A Simple Beamline of Components\\
\\
Curly bracket sections may also be used as comments - in this case\\
be careful to respecify the component line format before use.\\
\}\\
\\
\{Drift Length\}\\
D1 0.25\\
D2 0.5\\
RD1 0.32\\
\\
\{Solenoid Field Length Radius\}\\
S0 20 0.45 0.1 \\
S1 -3.97 0.4 0.15\\
\\
\{RF Frequency/MHz Radius Voltage/MV Phase\}\\
BRF1 31.4285 0.15 2.25 -90\degree\\
BRF2 201.14 0.325 0 -90\degree\\
RRFA 3.1428 0.2 0.8562 -180\degree\\
RRFB 201.14 0.2 0.5 -67.633\degree\\
\\
\{Dipole Length Angle Field HalfGap EdgeIn EdgeOut HalfWidth\}\\
IB 1 -8\degree -0.123608 0.325 4\degree 0\degree 0.5\\
\\
\{RodSource Timespread Axial File X Y Z RodAngle\}\\
TantalumRod 3 3 pi\_plus\_2G2eV.csv 0 0 288e-3 0\\
\\
TantalumRod,S0,D1,S1,D2,S1,D1,BRF1,D1,S1,D1,BRF2,D2,IB,\\
\indent RD1,RRFA,RD1,RRFB;}\\[1cm]

Here, blocks of component definitions are introduced by a format line of the form \texttt{\{Type Attrib1 Attrib2}...\texttt{\}}, after which lines of the form \texttt{Name Value1 Value2}... will create a component of type `Type' called `Name' with attribute Attrib1 equal to Value1 and so on.  Importantly, components are not inserted into the beamline when they are defined and the order of definition does not matter.  The beamline order is defined by the comma separated list of component names at the end of the file, which is terminated by a semicolon.  Components may be included multiple times, once, or not at all.

The attributes \texttt{Length} and \texttt{Angle} are special in that, regardless of the type of component they are an attribute of, they determine how the reference axis of the machine is built up.  A length without an angle just extends the axis by that distance each time the component is included.  A length $L$ and angle $\theta$ will include a circular arc of curvature radius $L/\theta$ for that length, with negative angles producing reverse bends.

All values are in SI units by default, but Muon1 recognises values with units written on the end (such as nanoseconds or degrees in this file) as well as scientific `e' notation (\texttt{288e-3}).  The units may also be included in the format definitions to save writing them for each component, as MHz is here.

\subsection{Cell Algebra}
For machines with repeated beamline units, writing a straight list of all the components could be unnecessarily long or just undescriptive.  To eliminate this redundancy, larger cells may be defined as blocks of the existing components with lines such as the ones shown below.

\begin{verbatim}
DFB1:QDT1,CLM,QFT1,DM3,BEND,DM3;
RCS2:8*(2*DFB1,3*DFB2,DFB0,DFB1,DF0,2*DF1);
A1:2*(ACHR,-ACHR);
FlipA1:~A1;
\end{verbatim}

Each line starts with the new cell name, followed by a colon and the semicolon-terminated definition of that cell.  This has the same format as the unprefixed list of machine components at the end of the file.  In both cases, the operators of multiplication (\texttt{*}), negation (\texttt{-}) and mirror reflection (\texttt{\~}) are available and can operate to any level with bracketing on the cells already defined.  Multiplication repeats an identical sequence of cells the specified number of times; negation inserts the cells in reverse order and mirror reflection inserts the cells in the correct order but with the \texttt{Angle} attribute of each component changed in sign.

\subsection{Optimisable Variables}\label{-optimiser-lattice-variables}
The examples so far have specified a single accelerator.  To optimise, the program requires a parameterised range of accelerators.  Optimisation variables may be added by changing the definition of a component in the manner below.

\begin{verbatim}
{Solenoid Length Radius Field}
S1 [0.2,0.45] 0.1 [0,20]
\end{verbatim}

This defines a solenoid \texttt{S1} whose length may be varied from 0.2 to 0.45 metres with a field from 0 to 20 Tesla.  Its radius, however, is fixed at 0.1 metres since this attribute is specified as a single value rather than an interval range in square brackets.  The replacement of a single value by a \texttt{[}$min$\texttt{,}$max$\texttt{]} bracket is all that is required to turn a point design into an optimisation ready for running.

The variables are named automatically and these names will reappear in the result files discussed in section \ref{-optimiser-resultfile}.  The variable name is the component name followed by the first letter of the attribute name, all in lowercase, which would be \texttt{s1l} and \texttt{s1r} here.  More letters from the attribute name are added as necessary if ambiguities arise.

It should be stressed that if multiple copies of \texttt{S1} are included in the beamline, they will all be identical.  To have another solenoid with the same ranges for optimisation but potentially different values, which would generate additional optimisation variables, it would have to be defined separately with a different name like \texttt{S2}.

\subsection{Example with Scripting Language}
In more complex optimisations, the attributes of some components may have to be varied in a correlated way (for example to exclude impractical combinations), or the sequence of components in the beamline may change according to an optimisable parameter.  Muon1 includes a C-like scripting language that can be used within the lattice files, with occurrences of the \texttt{\#} symbol switching in and out of the script language on any given line.  To show the various uses for this, the full lattice file for the \texttt{PhaseRotB} optimisation (a decay channel plus phase rotation system) is explained here.

\begin{verbatim}
{
PhaseRotB/~270
SolenoidsOnly (i.e. decay channel 30m long) plus 31.4MHz phase rotation
Solenoids now allowed up to 90cm long
Bugfix of PhaseRotA
May 21, 2004
}

!MINVER 4.41

{Parameter Value}
t_max 500e-9
n_decays 3
\end{verbatim}

The initial comment block has the explanation and date in it.  \texttt{!MINVER} is an optional control command that states the minimum version of Muon1 needed to run this lattice, important for the distributed project where users might not upgrade their software quickly enough.  If running in distributed computing mode, the program searches for other compatible lattices to run instead.  The last two lines are `parameters', which are defined in the same way as components and determine general features of the simulation.  Here they state that the simulation will terminate after 500\,ns and each unstable particle (pions here) will undergo three multiple decays as described in section \ref{-code-decay-multi}.  The termination time is needed because some slow muons may be created in magnetic bottles near the solenoids and will orbit forever unless the program is stopped.

\begin{verbatim}
{RodSource Timespread Axial File X Y Z RodAngle}
TantalumRod 3 1 'pi_plus_2G2eV.csv' 0 0 [0,0.45] [0,0.5]

{Synchronous-particle t_start Energy Z}
SyncMuon #TantalumRod.Timespread?+5:0#ns 180MeV #TantalumRod.Z#
\end{verbatim}

Two components are defined: a \texttt{RodSource} of pions, with optimisable angle and Z position, and a \texttt{Synchronous-particle} that is tracked to provide reference crossing times for the timing of the RF components.  Note how the \texttt{File} attribute of the \texttt{TantalumRod} is a string, telling Muon1 to load the particles from the file \texttt{datafiles$\backslash$pi\_plus\_2G2eV.csv}.

The attributes of \texttt{SyncMuon} contain the first example of the scripting language in use.  Its start time is set to be +5\,ns if the rod particles have been loaded with a timespread in emission and zero otherwise.  Its Z position is set equal to the Z offset of the rod.

\begin{verbatim}
#z=0; ok=1;
#for (n=1;ok;n++)
#{
   {Solenoid Length Radius Field}
#  if (n==1) #S1 [0.2,0.45] 0.1 [0,20];#;
#  else {S[n]# [0.2,0.9] [0.1,0.4] #if (n<=4) #[-5,5];#; else #[-4,4];#;}
#  z+=S[n].Length;
#  if (z>=30) ok=0;
#  if (ok)
#  {
      {Drift Length Bore}
      #D[n]# [0.5,1] 0.5
#     z+=D[n].Length;
#  }
#}
#MaxSol=n-1;

DecayChannel: #for (n=1;n<=MaxSol;n++) {S[n] if (n<MaxSol) {#,#D[n]#,#}}#;
\end{verbatim}

The construction of the decay channel is a more complex example, with most lines being scripted.  There is a for loop and a \texttt{z} counter that is increased as solenoid and drift components are defined until it reaches 30\,m in length.  Each of the solenoids has optimisable length, field and (with the exception of \texttt{S1}) radius and the drifts have optimisable length too.  The notation \texttt{D[n]} is a crude array implementation and would be equivalent to a variable called \texttt{D3} if $\texttt{n}=3$, for example.  The script variable \texttt{MaxSol} records the number of the last solenoid and then the list of components in the \texttt{DecayChannel} cell is printed by another for loop, putting drifts after all but the last solenoid.

\texttt{\\
\{Parameter Value\}\\
PhaseRotCells [20,40]; \#// 30 in original\\
\#PhaseRotCells=int(PhaseRotCells);\\
\\
\#for (n=1;n<=PhaseRotCells;n++)\\
\#\{\\
\indent   \{Parameter Value\}\\
\indent   PD\#n\# [0.5,1]\\
\indent   \{Drift Length Bore\}\\
\indent   PD\#n\#a \#n==1?PD[n]*2/3-0.25:PD[n]*2/3\# 0.15\\
\indent   PD\#n\#b \#PD[n]/3\# 0.15\\
\indent   \{Solenoid Length Radius Field\}\\
\indent   \#PS[n]\# [0.2,0.9] 0.15 [-4,4]\\
\indent   \{RF Frequency/MHz Radius Voltage/MV Phase\}\\
\indent   \#PRF[n]\# 31.4285 0.15 [0,\#(PD[n]+PS[n].Length)*2.25/1.4\#] [-180$^\circ$,+180$^\circ$]\\
\#\}\\
\\
PhaseRot: \#for (n=1;n<=PhaseRotCells;n++) \{\\
PD\#n\#a,PRF\#n\#,PD\#n\#b,PS\#n if (n<PhaseRotCells) \#,\#;\\
\#\}\#;\\
}

The definition of the phase rotation channel starts with another use of `parameters' in lattice files, that is to create an optimisation variable that is not tied to a specific attribute of a component but becomes a variable in the script that influences other things.  Here, \texttt{PhaseRotCells} determines the number of RF-solenoid periods in the phase rotator and of course has to be rounded to an integer before use.  The `for' loop that follows is similar in principle to the decay channel one, with some additional algebra to position the RF kick component two thirds of the way through the drift, which becomes split into two drifts named like \texttt{PD3a}, \texttt{PD3b}.  Another notable use of scripting is to impose an upper limit on the RF peak voltage of 2.25\,MV per 1.4\,m of drift length available to install the 31.4\,MHz resonator into.  This being based on a CERN design \cite{CERNcavity} where the large resonator also enclosed the solenoid, the solenoid's length is added to the drift available for this purpose.

\begin{verbatim}
{Finish-aperture radius MinEnergy MaxEnergy}
END 0.5 #180-23#MeV #180+23#MeV

TantalumRod,SyncMuon,DecayChannel,PhaseRot,END;
\end{verbatim}

The final component to be defined is a \texttt{Finish-aperture} to collect the successful muons that have finished the channel in the kinetic energy range $180\pm23$\,MeV.  The file ends with the definition of the entire accelerator in terms of the cells defined already.

\section{Figures of Merit}\label{-optimiser-score}
The transmission of muons, as a percentage of the particle weight of the original pions, is used to score an accelerator design once the simulation has finished.  A simulation will finish either when there are no more active particles remaining, or the \texttt{t\_max} time limit has been reached.  In the first of these cases, all the particles will then be either marked as `lost' or `finished', whereas in the second some will still be `active'.  From the point of view of the simulation, `lost' and `finished' particles are treated exactly the same except with a different label: they both have stopped moving.

So how does a particle acquire the special `finished' status?  Currently this is done using the \texttt{Finish-aperture} component as at the end of the example in the previous section.  It produces a disc of the given radius, perpendicular to the beamline, that acts as a blockage.  If energy bounds are not specified, then all particles hitting the disc are stopped and marked `finished'.  If, as in the example, there is an energy range, then particles outside that range are also stopped, but marked as losses.

At the beginning of the simulation, Muon1 normalises all the particle weights so that $\sum_i w_i=1$.  Thus after finishing, the percentage transmission score is simply
\[ T = 100 \sum_{\mathrm{finished\ muons}\ i}w_i. \]
However, for more difficult optimisations, a random element of the design space may be so poor that almost all such designs will give a zero score.  It is useful to be able to distinguish between such designs to see which are nearer to being successful, so that the optimiser may climb out of the area of poor designs on its own without having to be seeded with an already good design.  Thus two additional scores are defined to deal with the cases of beam not being transmitted through the whole design and beam being transmitted but mostly of the wrong energy.

The figure for a design that transmits less than a proportion $\epsilon=0.1\%$ of the beam is defined by finding the distance along the beamline where at least $\epsilon$ weight of muons survived.  That is the largest distance $s$, measured along the beamline axis, for which the weight of stopped muons with $s_i\ge s$ is at least $\epsilon$.  Call this distance $s_\epsilon$ and the total length of the beamline $l$.  Then the distance score is defined as
\[ D=s_\epsilon/l. \]
It ranges from near zero where almost all the particles stop in the early accelerator, to nearly one when the fraction of surviving muons is only reduced to below $\epsilon$ right near the end.

The figure for designs that transmit less than $\epsilon$ of the particles in the right energy range $[E_{min},E_{max}]$ is determined from the energies $E_i$ of the muons that hit the \texttt{Finish-aperture}.  The ratio by which the energies are wrong, as a weighted average, is given by
\[ W = \frac{\displaystyle\sum_{E_i<E_{min}}w_i(1-E_i/E_{min}) + \displaystyle\sum_{E_i>E_{max}}w_i(1-E_{max}/E_i)}{\displaystyle\sum_\mathrm{muons\ on\ aperture} w_i}. \]
This can range from values near zero when most of the muons have almost the correct energy, to values of nearly one when the majority of the energies are very far outside the specified range.

The above figures $T$, $D$ and $W$ are blended together with linear ramps to make a smooth overall score $S$ that increases with the performance of the design.  If $T/100 \ge \epsilon$, the transmission score is assumed to have enough statistics to be used on its own, whereas in the region $\epsilon/2 < T/100 < \epsilon$ it is linearly blended into the `fallback' score $S_1$, as follows:
\[ S = \left\{ \begin{array}{lll}
T &\mbox{when}& T/100\ge\epsilon\\
\frac{T/100-\epsilon/2}{\epsilon/2}\ T + \frac{\epsilon-T/100}{\epsilon/2}\ S_1 && \epsilon/2 < T/100 < \epsilon\\
S_1 && T/100\le\epsilon/2\\
\end{array}\right. \]

If more than $\epsilon$ weight of muons survive the channel, regardless of their energy, the fallback score rates the design between 0 and $-1$ depending on how wrong their energies are.  If fewer than $\epsilon/2$ get to the end, the design is scored as $D-2$, which ranges between $-2$ and $-1$ depending on how far the muons survived down the channel.  In between, linear interpolation is again used.  Let $f$ be the raw transmission fraction of muons, disregarding energies (so $f\ge T/100$).  Then the fallback score is defined as:
\[ S_1 = \left\{ \begin{array}{lll}
-W &\mbox{when}& f\ge\epsilon\\
\frac{f-\epsilon/2}{\epsilon/2}(-W) + \frac{\epsilon-f}{\epsilon/2}(D-2) && \epsilon/2 < f < \epsilon\\
D-2 && f\le\epsilon/2\\
\end{array}\right. \]

The combined score $S$ as defined above is the one used in the Muon1 program when it outputs results.  Note that for any value above 0.1 it is just equal to the muon transmission in percent.  Lower yielding designs are given scores in a range down to $-2$.

\section{Muon1 Result (and Queue) Files}\label{-optimiser-resultfile}
In order for the optimiser to learn from previously simulated designs, the variables and score from each simulation are logged to one or more result files.  Generally these will be \texttt{results.txt} and \texttt{results.dat} in the same directory as the Muon1 executable.  All result files are sequences of records, one added for each simulation, which have the same two-line format as the example below.
\begin{verbatim}
#gen=8;d10l=075;d11l=237;d12l=013;d13l=000;d14l=011;d15l=000;d16l=024;
\end{verbatim}...\begin{verbatim}
s8l=999;s8r=999;s9f=978;s9l=999;s9r=999;tantalumrodr=000;tantalumrodz=660;
0.365180 (368.8 Mpts) [v4.41f] {FD19E68427264FC7F20D451C} <PhaseRotB>
\end{verbatim}
The first line can be very long so has been split for clarity.  It contains a series of $variable$\texttt{=}$value$\texttt{;} pairs with the variable names coming from the lattice file as described in section \ref{-optimiser-lattice-variables}.  The value has been (linearly) normalised to three digits with 000 corresponding to the lowest and 999 the highest allowable value in the range.  Accuracies of more than three significant figures were considered to be difficult to engineer, so by restricting the accuracy this representation prevents some degree of over-optimisation.  Variables whose name begins with a \texttt{\#} character are not from the lattice, they have been added for other logging purposes, for instance \texttt{\#gen} is automatically added to record which genetic algorithm mode produced the design (see section \ref{-optimiser-algorithm} for details).  Hashed variables are standard integers that are not limited to three digits.

The second line always starts with the score that the design specified by the first line achieved.  It must also contain the name of the lattice in angle brackets, \texttt{<PhaseRotB>} here, which specifies that the variables on the first line should be used with the lattice file \texttt{lattices$\backslash$PhaseRotB.txt}.  Other data is also usually supplied: in round brackets the amount of calculation required for the simulation in mega-particle-timesteps (Mpts) and the version of Muon1 in square brackets.  This is useful for logging the overall amount of CPU activity on a distributed network of computers as well as benchmarking, while the version code can be used to filter out erroneous results in the case of a buggy Muon1 release.  The hex code in curly brackets is a checksum produced by the program to make it more difficult to flood the distributed project with `fake' results.  The user may also add their own comments at the end of the second line, which are ignored by the program.

Normally on completion of a simulation, the two-line result is appended to both the files \texttt{results.txt} and \texttt{results.dat}, with the files being created if they do not yet exist.  The reason for this duplication is that when running as part of the distributed computing network, \texttt{results.txt} contains only the buffer of results that have not yet been sent and is deleted after a successful upload.  \texttt{results.dat} contains a complete history of results produced and may even be augmented with extra results generated on other machines, to serve as a knowledge base for the optimiser to generate new designs from.

A third file \texttt{queue.txt} may also contain results in a similar format and this has two purposes.  Firstly, it acts as the method for a user to input specific designs (from a lattice's optimisation range) to test.  These will specify the first line with the normalised values for the variables and the lattice tag on the second line, together with the string \texttt{TEST} in place of the score, since it has not been calculated yet.  This form is shown in the example below, although the first line will often be much longer in reality.
\begin{verbatim}
s8l=916;s8r=896;s9f=895;s9l=909;s9r=976;tantalumrodr=000;tantalumrodz=446;
TEST <ChicaneLinacB>
\end{verbatim}
If a lattice has no optimisable variables, it is not worth preparing a \texttt{queue.txt} file in this way before running Muon1 because specifying the lattice on the command-line will provide sufficient information\footnote[2]{The reader may wonder what happens if an optimisable lattice is run from the command-line without a queue file.  The answer is that Muon1 is always in continuous optimisation mode by default, so will choose either a random design (if \texttt{results.dat} does not exist) or continue optimising the designs based on the work accumulated in \texttt{results.dat} so far.}.  The second purpose for the queue file is to recheck high-scoring results for both statistical accuracy and reliability against computer errors.  Specifically, if a result has the highest score achieved so far for its lattice, Muon1 will run it an additional four times, storing the intermediate results in the \texttt{queue.txt} file and then finally add a result with an averaged score (excluding the highest and lowest) to \texttt{results.txt} and \texttt{results.dat}.  In these cases, the intermediate result may have a comma-separated list of scores in place of the single score normally found at the start of the second line.  Whatever the usage mode, the top result in the queue file is processed first and removed when completed, with the rest of the file being moved up.

\section{Genetic/Evolutionary Algorithms}\label{-optimiser-algorithm}
When given an optimisable lattice, Muon1 has the task of choosing values for a potentially large number (often hundreds) of variables.  Genetic and evolutionary algorithms are suitable for problems of large dimensionality where the optimum can be found without necessarily being given a nearby starting point.  This is because they effectively perform a search on the design space that starts randomly and becomes focussed in higher-yielding areas as accumulated results reveal where these areas are.  `Brute force' searches where a grid in the search space is fully explored are not practical for high-dimensional problems because even if each variable is only sampled at 2 values, there are $2^D$ combinations for a $D$-dimensional grid, which exceeds $10^{30}$ with $D=100$, for example.  This means that `intelligent' forms of brute force searching that subsequently use finer grids on areas with good results also cannot be used because even the initial coarse grid is too time-consuming to search.  Another common optimisation method is to start from an initial design and evaluate the sensitivity of all parameters to small variations, then adjust these in the directions that increase the score.  Unfortunately when the figure of merit is particle yield from a tracking simulation, the score has statistical noise that overwhelms the small differences in score produced by the small variations used to gauge the sensitivity.

The genetic algorithm terminology originated in early computer simulations of biological evolution \cite{GeneticAlgorithm}.  These first examples of genetic algorithms followed a very close analogy with DNA replication, generating a `population' of initially random binary strings (genomes), then performing artificial selection (as opposed to \emph{natural selection}) to eliminate a large proportion of them before the remaining good strings were allowed to `mate' in a process that mixes blocks of the parent binary strings together (genetic crossover) and occasionally inverts some of their bits (mutation).  These offspring then form the population for the next generation and the process repeated many times, with the removal of the least-good designs biasing the distribution of strings towards areas in which the higher scoring designs are to be found.

In Muon1, the `genome' is just the first line of the result as described in section \ref{-optimiser-resultfile}, containing the normalised values for all the variables that specify the particular accelerator design within a lattice's optimisation range.  `Artificial selection' is performed on the grounds of higher scores (calculated as in section \ref{-optimiser-score}) being better and `mating' \comment{is done }by a variety of methods including analogues of the original mutation and genetic crossover. 

However, the original formulation of the genetic algorithm is often inefficient in real engineering problems and requires some adaptation as reviewed in \cite{GAHandbook}.  For Muon1, the presence of discrete generations means the designs and results from each generation are destroyed apart from their influence on the gene pool of the next generation.  When each result is scored on the basis of a simulation that can take an hour or more to complete, this is considered wasteful.  Instead, all the results are logged permanently but operations that generate new designs, such as mutation or crossover, are based on a subselection highly biased towards the higher scoring designs.  This means low-scoring designs remain in the result log but hardly ever procreate.

The biased selection algorithm in Muon1 works as follows.  A real number $\alpha\in[0,1.25]$ is chosen uniformly at random and is used to define the subsample size $s=\floor{N^\alpha}$ where $N$ is the total number of results in the \texttt{results.dat} history file.  Random results are examined from this file $s$ times over and the one having the highest score is selected for use.  Methods such as crossover require two input genomes so will call this algorithm twice, or more if the second genome comes back the same as the first, until two differing ones are selected.  The advantage of allowing values $\alpha>1$ and hence $s\ge N$ is that nearly all of the results will be examined, so there is a finite probability of picking the very highest result in the file, which does not decrease appreciably with $N$.  Allowing values of $\alpha$ near 0 means it is still possible for merely `average' results to get picked, although with a reduced probability.

A second major modification to the binary genetic algorithm is needed because it has no concept of continuously-varying parameters, instead it would treat their floating point representation as just another binary string and produce `corrupt' values that may be nowhere near either of the two parent values after a bit-wise crossover.  Although this could be seen as introducing a little more mutation into the system and therefore harmless, Muon1 takes the approach of using continuous parameters and analogous operations to crossover (where values themselves remain intact, like individual bits) or mutation (where increments are chosen from a continuous distribution of values).  This continuous parameter system also naturally allows other ways of generating new genomes, such as taking a weighted average of two sets of variables, an operation that has no analogue using binary strings.

With these modifications, Muon1's algorithm can more accurately be described as part of the broader class of `evolutionary algorithms', which use the concept of learning from a pool of past results but do not impose a discrete genome analogous to DNA base pairs.

The full implementation contains several ways of generating new results from those selected from the \texttt{results.dat} file.  As mentioned in section \ref{-optimiser-resultfile}, each result is labelled via the \texttt{\#gen} field to denote how it was created.  These different methods (known as `trial types') and their \texttt{\#gen} values are described in the list below.

\begin{itemize}
\item \texttt{Random} (\texttt{\#gen=0}) does not use any previous results and sets all variables to uniform random values.  This is called when no results are in the \texttt{results.dat} history file, or with a decreasing probability $N^{-0.4}$ when it contains $N$ results.
\item \texttt{Mutate} (\texttt{\#gen=1}) and \texttt{Crossover} (\texttt{\#gen=2}) function roughly as described in the original genetic algorithm.
\item \texttt{Interpolate} (\texttt{\#gen=3}) takes two results and produces a weighted average of their parameters.  A random number on the [0,1] interval determines how much weight is given to the first genome with the balance made up by the second.
\item \texttt{Extrapolate} (\texttt{\#gen=4}) is the same but uses numbers outside the [0,1] range to extend beyond one of the results' locations in design space.
\item \texttt{MuSpherical} (\texttt{\#gen=5}) produces a mutation according to a spherically symmetric distribution of offsets, if the variables are considered the axes of the design space with the Euclidean metric.
\item \texttt{MuOne} (\texttt{\#gen=6}) is like \texttt{Mutate} but only changes the value of a single variable.
\item \texttt{Extreme} (\texttt{\#gen=7}) is designed for the common situations when the optimal values of many parameters are at the extremal end of the allowed range (e.g. highest magnetic or accelerating field).  It moves some of the variables towards the end of the range.
\item \texttt{LocalGrad} (\texttt{\#gen=8}) estimates the local gradient of the score function from a cluster of the nearest results to a selected one and produces a suggested improved design by moving `uphill' a certain distance from there.
\item \texttt{TopoSmooth} (\texttt{\#gen=9}) uses the numbering that often appears in variable names to infer which apply to adjacent components (numbers differing by one) and smooths out each variable's value by averaging it with that of its neighbours.
\item \texttt{CellDouble} (\texttt{\#gen=10}), \texttt{CellDelete} (\texttt{\#gen=11}) and \texttt{CellCommute} (\texttt{\#gen=12}) also use the numbering of the variable names to perform the functions of duplicating a beamline cell, deleting a cell and swapping (commuting) two adjacent cells with each other.
\end{itemize}

The effect of adding these extra trial types to the algorithm was investigated with two benchmark problems.

\subsection{Sine Wave Interpolation Test}
The first benchmark problem was designed to have a figure of merit that depends on a large number of variables in a smooth but correlated way.  A suitable problem is the interpolation of a sine wave with a linear spline $L(x)$ using the variables $(x_1,y_1)\ldots(x_{10},y_{10})$ with $x_n\in[0,2\pi]$ and $y_n\in[-1,1]$ as the positions of the interpolating nodes.  The score would then be
\[ 10-\int_0^{2\pi} (\sin(x)-L(x))^2\ \D x, \]
so that better spline approximations increase towards 10.  Since the performance of the optimiser in a single run would depend on the random values chosen during various operations, a program was written to run the optimiser many times (with different random seeds) on the same problem and accumulate statistics on its average behaviour.  Figure \ref{intersinescreen} shows this during operation for the sine interpolation problem.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_540_intersinescreen.png}
\caption{\label{intersinescreen} Genetic algorithm test run of the sine wave interpolation benchmark problem.  The green graphic at the top shows successive best linear spline approximations to the sine wave with high scoring lines ($\ge 9.98$) in yellow and the final result (first above 9.99) in black.  Below is a graph of the generally increasing scores of the results over time.}
\end{figure}

\comment{Mention what the "statistical data" says about random/mutations?}

After running the optimisation test problem 100 times, each of which was terminated either when the score reached 9.99 or when 10000 results had been generated, some average values (including error bars) were derived that show the true performance of the optimiser regardless of the random numbers used.  The two most important statistics collected were the percentage of times the optimisation reached the target score before the 10000 result cutoff and the average number of iterations taken to get there in the cases where it did succeed.  These are plotted in figure \ref{intersine} for all $2^6=64$ combinations of the trial types with \texttt{\#gen=1} through \texttt{6}.  When multiple trial types were used, they were selected with equal probability for every non-random result.  In the case where no trial types were used, only random results were generated, explaining the zero percent success rate in that case (the optimisation problem was \emph{not} so easy that a million random guesses would produce a success!)

\begin{figure}
\includegraphics[width=160mm]{fig_540_intersine.png}
\caption{\label{intersine} Success rate and average convergence time for the optimiser on the sine wave interpolation test problem with all possible combinations of the first six trial types being switched on and off.  Error bars are one standard deviation.}
\end{figure}

The success rate and average convergence time data can be amalgamated into a single figure of merit to represent the number of optimiser convergences expected in a million results ($10^6*(\mbox{success probability})/(\mbox{average time})$) and this is what is shown in figure~\ref{intersinefom}.  The general trend is that optimiser performance is patchy and often failing to converge when only a few trial types are combined and more robust when there are many.  Crossover and interpolation get nowhere without adding other types because they only produce results `between' those few random ones already produced.  Adding a mutate type to anything guarantees at least some level of convergence, though spherical mutation is generally poor and single-parameter mutation is so good it almost beats all other combinations on its own (though with a big error bar).  However, most mutation combinations are moderately enhanced by adding crossover or extrapolation.

\begin{figure}
\includegraphics[width=160mm]{fig_540_intersinefom.png}
\caption{\label{intersinefom} Figure of merit for optimiser performance running on the sine interpolation test problem, for each possible subset of trial types used ($1\sigma$ statistical errors shown).}
\end{figure}

\clearpage
\subsection{Sequential Parameters Test}
A second benchmark problem was devised to test the optimiser in rather less smooth situations, including discontinuities and situations where some parameters become `slack' unless activated by the proper choice of others.  The latter situation of sequential parameters may occur when good choices in the early part of a beamline are required for the particles to propagate far enough to be affected by the variables controlling components further on.  To represent this, some `goal' values $g_1\ldots g_{10}$ are chosen randomly by the computer and kept secret from the optimiser, which will make guesses as vectors $(x_1,\ldots x_{10})$ with $x_n,g_n\in[0,1]$.  If $|x_n-g_n|\le 0.05$ for all $n$, the score is 10 and the successful optimisation is terminated.  Otherwise let $x_k$ be the first value such that $|x_k-g_k|>0.05$ and put the score equal to $k+1-|x_k-g_k|$.  This increases from slightly more than zero for guesses where $x_1$ is totally wrong, increasing fractionally as the guess becomes more accurate and jumping above each integer $n$ once $x_n$ becomes close enough to the goal.  The success rates and average optimisation iterations for this second problem are plotted in figure \ref{comblock} and show a significantly different pattern to that of sine wave test problem, though sharing the same feature that combining more trial types is generally better.

\begin{figure}
\includegraphics[width=160mm]{fig_540_comblock.png}
\caption{\label{comblock} Success rate and average convergence time for the optimiser on the sequential parameters test problem, for each possible subset of trial types used ($1\sigma$ statistical errors shown).}
\end{figure}

A single figure of merit can be produced for the sequential parameters test problem in the same way as for the sine interpolation test.  To show the situations in which the optimiser performs well whichever sort of problem it is given, the geometric mean of the figures of merit for both problems is plotted in figure \ref{geomeanfom}, the geometric mean being chosen so that a complete fail on either problem will ensure a zero score overall.  The high performance of the \texttt{MuOne} trial type alone has become less significant than it was in the sine wave test, with the best overall performance coming from the combination of it with crossover and extrapolation.  However, the mix of all six types still performs three-quarters as well as anything else and comes with the insurance that if another, totally different, sort of problem was attempted that responds well to, for example, \texttt{MuSpherical}, then that algorithm would still be available.  Muon1 by default runs with all these trial types active, together with \texttt{LocalGrad} and some of the `topological' trial types but with a lower probability.  The weighting of each type can also be customised in the \texttt{config.txt} file by the user.

\begin{figure}
\includegraphics[width=160mm]{fig_540_geomeanfom.png}
\caption{\label{geomeanfom} Combined figure of merit for optimiser performance across two different test problems, with $1\sigma$ error bars, as a function of the set of trial types used.}
\end{figure}

An illustration of the distribution of results generated by having all these different methods of evolution active at the same time is figure \ref{tazpca}.  This is projection of one user's \texttt{results.dat} file onto the two principal axes of variation in the design space, when running the \texttt{SolenoidsTo15cm} lattice that optimises of the pion decay channel.  Some diverging evolutionary pathways are clearly visible by virtue of the fact the user had several computers working independently for a period.  The progression of another such evolution will be examined more closely in the next subsection; the resultant accelerator designs for all optimisations will be described in chapter \ref{-results}.

\begin{figure}
\includegraphics[width=160mm]{fig_540_tazpca.png}
\caption{\label{tazpca} Projection of a user's result evolution through the design space.  Principal component analysis (PCA) was performed to determine the two axes of largest variance in the results in the high ($\sim$100) dimensional design space, which were used to plot each result as a point in two dimensions.  Black/purple indicates the highest scoring results, through to blue for the lowest.  Notable features include: clustering around the highest scores; bridging between two particular high scoring points in search of an optimum between; a diffuse blue ball of randomly-generated results at the left; and six separate pathways optimising out from the blue ball, caused by the program being run from scratch on six separate computers for a period, each one going its separate way.}
\end{figure}

\clearpage
\subsection{Example Lattice Optimisation}
The evolution of all the parameters in the \texttt{PhaseRotEb1} lattice is plotted in this subsection.  How all these lattices differ from each other will be discussed in chapter \ref{-results} but for now it suffices to say that \texttt{PhaseRotEb1} optimises the decay channel and phase rotation sections of the muon front end, aiming for muons transmitted into an energy window of $180\pm23$\,MeV.  This optimisation is particularly easy to display because the later sections of the decay channel and the whole phase rotation are made from identical cells, which cuts down the number of variables significantly.  Figure \ref{scorevstime} plots the progress of the optimisation over the two month period it was running on the distributed network.  Only the successive best scores received by the central server are plotted, so the very earliest results with scores between $-2$ and $-1$ are missed out, as by the time the participating computers uploaded their first batch of $\sim$50 results they had already achieved scores above $-1$.

\begin{figure}
\includegraphics[width=160mm]{fig_541_scorevstime.png}
\caption{\label{scorevstime} Progression of successive best scores attained by the \texttt{PhaseRotEb1} lattice.}
\end{figure}

The rate of increase in the muon yield slows down over time because the higher a score already is, the more difficult it is to generate a result that exceeds it.  Despite saving on independent variables in later parts of the channel, \texttt{PhaseRotEb1} is still an optimisation of 48 variables.  This means any sort of exhaustive search or guarantee that the eventual design is the best one in the whole design space is out of the question, since the design space consists of $1000^{48}=10^{144}$ points.  The optimisation only sampled $5.89\times10^5$ of these, while finding a design much better than the same number of random (or systematically spaced) samples would, though it is very much unknown how many points exceed the yield found.

To see how the variables had to be tuned to achieve increases in score, they are all plotted in groups on the seven graphs that follow (figures \ref{rods1vsscore}--\ref{radiivsscore}).  Score is a more significant variable to plot against than time as it does not depend on the speed of computer calculation in any way.

\begin{figure}
\includegraphics[width=160mm]{fig_541_rods1vsscore.png}
\caption{\label{rods1vsscore} Evolution of variables concerning the target rod and its enclosing solenoid (\texttt{S1}) in the \texttt{PhaseRotEb1} lattice.  The 0--999 range represents 0--20\,T for the \texttt{S1} field, 20--45\,cm for the \texttt{S1} length, 0--0.5 radians for the rod rotation angle and 0--45\,cm Z displacements of the rod centre into the solenoid (measured from the front coil face).}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_structurevsscore.png}
\caption{\label{structurevsscore} Evolution of the number of cells in the decay channel and phase rotation sections of the \texttt{PhaseRotEb1} beamline.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_rfvsscore.png}
\caption{\label{rfvsscore} Evolution of the RF parameters in the phase rotation section of the \texttt{PhaseRotEb1} beamline.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_fieldsvsscore.png}
\caption{\label{fieldsvsscore} Evolution of solenoid fields in the \texttt{PhaseRotEb1} lattice.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_lengthsvsscore.png}
\caption{\label{lengthsvsscore} Evolution of solenoid lengths in the \texttt{PhaseRotEb1} lattice.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_driftsvsscore.png}
\caption{\label{driftsvsscore} Evolution of drift lengths in the \texttt{PhaseRotEb1} lattice.}
\end{figure}

\begin{figure}
\includegraphics[width=160mm]{fig_541_radiivsscore.png}
\caption{\label{radiivsscore} Evolution of solenoid radii in the \texttt{PhaseRotEb1} lattice.}
\end{figure}

Different types of variables are optimised while the score is in different ranges.  To achieve a score above zero, at least 0.1\% of the beam must finish within the correct energy range, so the first parameter to become close to its final optimised value is the RF phase used in the phase rotation on figure \ref{rfvsscore}.  For the transmission to reach 1\%, the fields of the solenoids in the late decay channel and phase rotation (purple and black on figure \ref{fieldsvsscore}) were given the same sign and the configuration of the target rod was changed so that the solenoid had a high field and length with the rod being more parallel to its axis.  The discontinuity in many of the parameters at once around a score of 0.9 could be the optimiser jumping out of its current local minimum to another, as the evolution of results in another minimum overtook the first.  Evolutionary algorithms are often put in the category of `global optimisers' for this sort of reason, though as pointed out before, a truly global optimiser for completely general score functions does not exist.

Between 1 and 2\% yield the main adjustments were to the voltage in the RF cavities and the length of the phase rotation section (figure \ref{structurevsscore}), which were both increased.  At a score of about 2.2 on figure \ref{driftsvsscore} another jump occurred in which all the drifts in the decay channel were shortened to the minimum allowed length of 0.5\,m.  From here up to the final high of 3.355\% most of the optimisation is concerned with gradually adjusting various parameters, in ways that appear to become quite correlated above 3\%; one clear example is the anticorrelation of the rod Z offset and rotation in figure \ref{rods1vsscore}.  The only further `global-type' jumps are in solenoid number 4's length at 2.9\% (figure \ref{lengthsvsscore}) and field at 3.2\% (figure \ref{fieldsvsscore}), changes that presumably improve the optics accepting the beam from the target.  These could likely be the result of a \texttt{MuOne} trial type in which only one parameter is changed, in this case to a value with higher yields.

\section{Distributed Computing Project}\label{-optimiser-distributed}
To obtain the computing power required to run a 3D Monte Carlo simulation for each score evaluation within an optimisation, Muon1 can be run on many computers at once in a configuration known as `distributed computing' that does not require particularly fast network connections between them.  In fact, participating in such projects has become a popular pastime for many members of the public, as evidenced by the number listed on hub sites such as \cite{DistributedComputingInfo}.  The additional features required to turn a scientific distributed program into one usable by the public are:
\begin{itemize}
\item A project website where the program can be downloaded (Muon1's is at \cite{Muon1Website}).
\item Availability for a popular operating system, Windows in Muon1's case.
\item Ease of installation: here, Muon1 simply requires extracting from its archive and once run will perform any additional setup by itself, downloading data from the Internet as appropriate.
\item Smooth multi-tasking with other applications.  Most such programs are designed to run at a very low task priority level, so only use `spare' CPU cycles available when the user is not making demands of their computer.  Muon1 also can work invisibly in the background.
\item Some kind of feedback on the user's contribution or progress in the calculation.  This can take the form of an overall scoring system measured in calculation units appropriate to the project and/or a graphical interface while a single calculation is running.  Muon1 supports both of these and the calculation units used are mega-particle-timesteps, or Mpts, measured as $10^6$ Runge-Kutta steps.
\end{itemize}

\begin{figure}
\includegraphics[width=160mm]{fig_550_blocklocal.png}
\caption{\label{blocklocal} Cycle of operation of the Muon1 client program on a user's machine.}
\end{figure}

Once downloaded from \cite{Muon1Website} and installed on a computer, the behaviour of Muon1 (in its default distributed computing mode) is summarised by figure \ref{blocklocal}.  This process combines all the elements described in previous sections of this chapter.  The `results storage' is the \texttt{results.dat} file and the `results buffer' is \texttt{results.txt}.  The reason Muon1 does not require computers to be connected by fast network connections is that individual simulations are run entirely on a single computer and will be so repeatedly until a large enough batch of results has been collected in the results buffer to be sent.  This system also copes with intermittent connectivity by continuing to generate and store results suggested by the optimiser until a connection is available.  Computers periodically check back with the central website to update the list of lattice files they should be working on.

As described so far, this system would be one of separate optimisations happening independently on many computers.  However, another thing that Muon1 tries to download from the website is a `sample file' for each optimisation, which contains a selection (typically 100) of the best results generated throughout the whole network.  This provides a narrow channel of communication between the different installations, but it is effective: new high-scoring results and their variants are propagated across the network within hours because higher scoring results are far more likely to be selected out of \texttt{results.dat} for variation using the genetic algorithm.

\begin{figure}
\includegraphics[width=160mm]{fig_550_graphics.png}
\caption{\label{graphics} Muon1's 3D display of particles and components while running in graphical mode.  This view shows the rod within the first solenoid and the second solenoid (shown as grey wireframe cylinders).  Particles are mostly pions at this point and are coloured according to their energy, red being low and blue high.  The brown annuluses on the left-hand side are additional geometry added to stop backwards pions from flying off into empty space (which wastes simulation time).}
\end{figure}

Although most of Muon1's calculation is done with the program running in invisible mode (it is taking 95\% of the CPU while I am writing this paragraph), a graphical mode is also provided which gives the fullscreen display shown in figure \ref{graphics}.  This was originally written to help with the debugging and monitor the progress of the tracking code but is also now used by many project users as a screensaver.

\begin{figure}
\includegraphics[width=160mm]{fig_550_blocknetwork.png}
\caption{\label{blocknetwork} Flow of data through the Muon1 distributed project network.}
\end{figure}

The project as a whole also needs a `back end' to receive and store results from the many users (typically more than 100 will be running the program at once).  This additional infrastructure is represented in figure \ref{blocknetwork}.  Users have two methods to upload results: earlier versions of Muon1 used an FTP script but since some networks block FTP, an upload via HTTP (the protocol for viewing normal web pages) was added later.  These go to an intermediate stage of a few FTP servers (also operated by volunteer users) that are provided as redundancy so the Muon1 clients always have somewhere to upload to.  Every hour, the database computer at RAL retrieves all new results from these intermediates as part of a script that collects and counts the results submitted by each user.  This script also verifies the checksum of each result and removes any duplicated uploads.  Lastly, the script publishes a table of the total number of results and Mpts that each user has computed on each optimisation, together with their highest result score on each optimisation.  Users are identified by the filename given to their results during upload, which is taken from the \texttt{user.txt} they create in the Muon1 directory (if uploads are switched on and no \texttt{user.txt} file is found, there is a GUI prompt to enter the username).  A second script on the database computer periodically counts through all the results for each active optimisation and generates a `sample file' (as mentioned earlier) that is uploaded to the website.

\begin{figure}
\includegraphics[width=160mm]{fig_550_totalresultsmpts.png}
\caption{\label{totalresultsmpts} Total simulation results received and calculation performed across all optimisations run on the distributed computing network.}
\end{figure}

With hundreds of active users, a considerable number of simulation results can be generated over time.  Log files enabled the cumulative totals over most of the project lifetime to be plotted in figure \ref{totalresultsmpts}.  Observe that the number of results does not increase as smoothly as the amount of calculation.  This is because simulations from different lattices can vary in length depending on how much beamline they simulate.  Even results from the same lattice can vary significantly early on, as a low-scoring result in which most of the beam is lost will require less calculation than one where much of the beam travels further.  A dip in the number of results is visible due to repeat removal and maintenance: the whole database currently stands at 183\,GB and went through several software revisions to cope with the increasing size.

The particle-timesteps axis has much larger figures on it, by a factor of $10^8$--$10^9$.  This can be understood since each simulation has $\sim$$10^4$ active particles undergoing $10^4$--$10^5$ timesteps of 0.01\,ns each, the total 100--1000\,ns time corresponding to beamline lengths of the order of 100\,m.

\begin{figure}
\includegraphics[width=160mm]{fig_550_website.png}
\caption{\label{website} Summary graphs for each optimisation and users' best results are updated hourly on the Muon1 website \cite{Muon1Website}.  From left to right the graphs are: a scatter plot (calculation time against score) for all results of this lattice; history of successive best scores, total results and calculation; and a zoom into the last week of the middle plot.  The scatter plot can be clicked for a more detailed version and the table below shows the current ten users with the highest submitted scores, along with their amounts of calculation and number of results submitted from this lattice.}
\end{figure}

Users' scores and the progress of current optimisations are shown on the Muon1 website, a screenshot of part of this is shown in figure \ref{website}.  The left-hand scatter plot shows result score against the number Mpts used to produce it, with a strong diagonal feature from the correlation of calculation time with result score mentioned earlier.  This plot was originally produced as a curiosity but became part of the site when it was found that plotting Mpts as a second variable to score often separates different `evolutionary tracks' so it becomes clear when a new design branch has been taken.  It also shows up any erroneous results as these will very often have the wrong amount of calculation for a given score.

The distributed optimisation project allowed many different lattice files corresponding to ranges of possible muon front end designs to be uploaded to the project website and subsequently optimised.  When the best muon yield achieved for a particular lattice stopped increasing for a long period of time (over a week), the lattice was retired from the website and the highest-scoring result extracted.  Chapter \ref{-results} analyses the highest-scoring results from eight lattices covering a variety of front end configurations.


\chapter{Results from Optimisation}\label{-results}
This chapter describes the designs resulting from optimisation on the distributed computing network using the Muon1 code.  Several different optimisation ranges of accelerators (`lattices') were submitted to the network, starting with just the decay channel and later including phase rotation and linac sections.  These optimisation ranges are specified in tables and the best designs are shown with plots of beam behaviour and transmission figures.  Full parameters for these designs are listed in appendix \ref{--Listings}.

\begin{figure}[h]
\includegraphics[width=160mm]{fig_600_lattices.png}
\caption{\label{lattices} Lattices described in sections of this chapter, showing output energy criteria.}
\end{figure}

\section{Decay Channel}\label{-results-decay}

The first piece of the muon front end to be optimised consisted of the target and decay channel, with the target enclosed in the first (stronger) solenoid \texttt{S1} and the remaining solenoids centred on the same axis, in the direction the proton beam (and the majority of the pions) will be travelling.  The lattice file for this was named \texttt{SolenoidsOnly} because it contains just the decay channel and no RF.

\begin{table}
\caption{\label{summarysolenoidsonly}Optimisation ranges and best muon yield for the \texttt{SolenoidsOnly} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel (to 30\,m):}\\
\hline
Target&Angle&0--0.5\,radians\\
&Z offset&0--0.45\,m\\
\cline{2-3}
\texttt{S1}&Length&0.2--0.45\,m\\
&Radius&0.1\,m (fixed)\\
&Field&0--20\,T\\
\cline{2-3}
Solenoid&Length&0.2--0.6\,m\\
&Radius&0.1--0.4\,m\\
&Field (\texttt{S2}--\texttt{S4})&$-5$--5\,T\\
&Field (\texttt{S5}--)&$-4$--4\,T\\
\cline{2-3}
Drift&Length&0.5--1\,m\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&2.2\,GeV&Any\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
16.676\%&0.012652&3.16$\times10^{14}$\\
\multicolumn{3}{l}{22.873\% including pions}\\
\hline
\end{tabular}
\end{center}
\end{table}

Table \ref{summarysolenoidsonly} defines the optimisation ranges of all the components in this lattice.  The earlier optimisations, such as this one\comment{ performed in 2004}, used a MARS15 data set of pions generated from a 2.2\,GeV proton beam because this was the energy of the CERN SPL design \cite{SPL1} at the time.  Later on this switched to a 10\,GeV proton beam, primarily because of the findings of the International Scoping Study in 2006 \cite{ISS}.

The target rod may be rotated by up to half a radian (probably an excessive angle but a suitable upper bound) and moved in Z so that its centre could be anywhere from the entrance to the exit of \texttt{S1}.  Most optimisations chose a near-zero angle for the rod and placed it near the centre of \texttt{S1}, which was given the maximal allowed length of 45\,cm.  \texttt{SolenoidsOnly} is unusual in that it is the only optimisation examined that assigned a relatively large angle, 95.6 milliradians, to the rod.  The figure of merit for this lattice is total weight of muons leaving the channel, with no energy cuts at all.  Primarily it is concerned with the transverse focussing and magnetic capture from the target.  However, since the decay channel is only 30\,m long, a significant number ($\sim$27\%) of undecayed pions still remain in the beam, so the decay-channel-only lattices in this section have the transmission including the pions also printed for reference.

Ranges for the variables concerned with solenoids have been chosen to avoid impractically large field volumes.  Only \texttt{S1} may have a field up to 20\,T and the subsequent solenoids are limited to 4 or 5\,T.\ \ Because of its high field a much tighter bore is anticipated for \texttt{S1} (10\,cm radius), which cannot be increased.  The remaining solenoids with only one quarter the field strength can have radii up to four times as big, which keeps the stored energy the same.  Drifts of at least 50\,cm are imposed between solenoids for independent cryostats, diagnostics and maintenance access, this is unlike Study~II \cite{Study2} and others in which the area near the target is a monolithic module.  The solenoid-drift pattern in the channel repeats until a distance of 30\,m is reached, where the channel is terminated and the muons within the final solenoid bore counted.

\newcommand{\linearplot}[3]
{
\begin{figure}
\includegraphics[width=160mm]{fig_#2_plot#3.png}
\caption{\label{plot#3} Longitudinal phase space evolution (top) and beam envelope plot (bottom) for the optimised design from the \texttt{#1} lattice.}
\end{figure}
}
\newcommand{\bothplots}[3]
{
\linearplot{#1}{#2}{#3}
\begin{figure}
\includegraphics[width=160mm]{fig_#2_pimu#3.png}
\caption{\label{pimu#3} Pions (green) decaying to muons (purple) in the optimised design from the \texttt{#1} lattice.}
\end{figure}
}
\newcommand{\nerdyplots}[3]
{
\begin{figure}
\includegraphics[width=160mm]{fig_#2_beta#3.png}
\caption{\label{beta#3} Optical functions in the optimised \texttt{#1} design.}
\end{figure}
\begin{figure}
\includegraphics[width=160mm]{fig_#2_emit#3.png}
\caption{\label{emit#3} Emittance evolution in the optimised \texttt{#1} design.}
\end{figure}
}

\bothplots{SolenoidsOnly}{610}{solenoidsonly}
\nerdyplots{SolenoidsOnly}{610}{solenoidsonly}

Figure \ref{plotsolenoidsonly} shows the behaviour of the beam from the target in this optimised decay channel.  The beam maintains a constant size through most of the channel, coming from a regular focussing structure.  All but two of the solenoids have been assigned the maximum possible radius, field and length and all drifts have been given the shortest allowed length.  This means the technical constraints on the design are the primary limitation and suggests the yield would increase if solenoids were allowed to be larger, longer, higher in field or closer together.  The exceptions are the third solenoid, which is only 48.3\,cm long (60\,cm max) and the fourth solenoid, which has a field of 4.24\,T (5\,T max) and a length of 55.3\,cm.  The effects of these non-regularities are visible in the beam envelope following that point.  It is likely these are genuine optima related to the matching from the initial pion distribution because of these solenoids' proximity to the target and the fact that all the other solenoids have reliably been set at very close to maximal parameters.

Figures \ref{betasolenoidsonly} and \ref{emitsolenoidsonly} show the RMS optical functions and emittances calculated from the beam in this design.  The values are obtained by calculating moments of the particle distribution as it passes through planes of constant $z$ spaced along the accelerator.  Since only a finite number of particles are tracked, there is some statistical error visible for instance between the $x$ and $y$ planes for the $\talpha$ and $\tbeta$ functions: these should be identical for a cylindrically symmetrical machine.  Figure \ref{betasolenoidsonly} also shows very low $\tbeta$ at the location of the target, followed by negative $\talpha$ indicating a diverging beam, as would be expected.  The functions then settle into a periodic cell, with an upward drift of $\tbeta$ that may be explained because $\tbeta$ is not a `normalised' quantity and therefore varies with overall beam energy.  Here, as the slightly higher-energy pions decay into muons, the average energy gradually reduces and unnormalised quantities therefore increase.

Figure \ref{emitsolenoidsonly} shows an artifact of the logging scheme whereby particles caught in magnetic bottles in the gaps between the solenoids are counted multiple times, making the remaining particle weight (and 4D emittance) appear to increase in these regions.  Ignoring this, the normalised 4D emittance increases slightly in the middle section of the channel from pion decays, before becoming invariant as would be expected.  The 2D emittances projected into the $x$ and $y$ planes oscillate above the 4D values because coupling between the planes, which is induced by solenoids, increases the projected emittances (intuitively: the beam appears bigger because information about its correlations has been lost).

\begin{figure}
\includegraphics[width=160mm]{fig_610_dcfateplot.png}
\caption{\label{dcfateplot} Pions in the initial $(p_L,p_T)$ momentum space coloured green if they are transmitted through the decay channel and red otherwise.}
\end{figure}

The longitudinal phase space plots in figure \ref{plotsolenoidsonly} show the drift from the initial near instantaneous (1\,ns RMS) spread of pion energies, with lower energy particles lagging behind more in time.  This lag is nonlinear owing to the large energy spread involved.  Figure \ref{pimusolenoidsonly} shows the same thing only with the beam coloured by composition, with the two particle species given different colours, instead of total intensity.  The overall decay of pions to muons is visible in the transverse plot while the longitudinal plot shows that the pions tend to have slightly higher kinetic energies than their decay products at a given position in the beam.  It also illustrates the time dilation phenomenon with higher-energy pions taking longer to decay than the slow ones near the bottom of the plot.

The decay channel on its own does not attempt to select particles by energy.  Figure~\ref{dcfateplot} shows the momentum distribution of pions from the target, coloured according to whether they survive the decay channel.  The solenoid fields and bores dictate an upper limit on $p_T$ and there is no upper limit on $p_L$ as a particle of high enough speed will always survive through a linear channel if it has a line of sight to the exit.  While the reason for losses with $p_L<0$ (backwards pions) is obvious, the poor survival for $p_L$ less than about 200\,MeV/c is because low forward momentum allows the pion to be reabsorbed in the target rod after spiralling in the 20\,T field.  Particles with very low $p_L$ are also more easily diverted by the radial component of solenoid fringe fields, which can exert a force in the negative Z direction when the particle has a suitable transverse velocity.  The force will reduce the $p_L$ of the particle further, increasing the angle between its direction of motion and the accelerator axis; in extreme cases, particles can be reflected backwards (the magnetic bottle effect); losses become more probable in either situation.

\begin{table}
\caption{\label{summarysolenoidsto15cm}Optimisation ranges and best muon yield for the \texttt{SolenoidsTo15cm} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel (to 30\,m) \emph{as for} \texttt{SolenoidsOnly} \emph{(table \ref{summarysolenoidsonly}) except}:}\\
\hline
Solenoid&Length&0.2--0.6\,m\\
&Radius&0.1--0.4\,m\\
&Radius (final solenoid)&\textbf{0.15\,m (fixed)}\\
&Field (\texttt{S2}--\texttt{S4})&$-5$--5\,T\\
&Field (\texttt{S5}--)&$-4$--4\,T\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&2.2\,GeV&Any\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
11.185\%&0.008486&2.12$\times10^{14}$\\
\multicolumn{3}{l}{15.756\% including pions}\\
\hline
\end{tabular}
\end{center}
\end{table}

\linearplot{SolenoidsTo15cm}{610}{solenoidsto15cm}
\nerdyplots{SolenoidsTo15cm}{610}{solenoidsto15cm}

Because the 40\,cm radius of the decay channel is too large for most acceleration systems, an optimisation named \texttt{SolenoidsTo15cm} was started that forced the final solenoid (and aperture) to be 15\,cm in radius.  Table \ref{summarysolenoidsto15cm} shows the resulting yields, which on first sight appear encouraging given the cross-sectional area of the accelerator is reduced by 86\% but the yield only by 33\%.  However, this lattice is an example of an optimiser finding an inadequacy in the figure of merit.  The final solenoid's length has been reduced to the \emph{minimum} possible here, which means its short length can accommodate a betatron focus of the beam.  That is, although the beam is small in the final solenoid where the figure of merit is counted, the smallness has come at the expense of increased $x'$ values and the beam would blow up again in the next cell.  The formation of the focus can be seen in the transverse plot on figure \ref{plotsolenoidsto15cm}, towards the end of the channel.

Figures \ref{betasolenoidsto15cm} and \ref{emitsolenoidsto15cm} also show the focus preceeded by a region of converging beam with positive $\talpha$ and the effect of beam scraping, which decreases the 4D emittance as the highest amplitude particles are removed.  However, the 4D emittance also exhibits growth between the final two solenoids because the abrupt change in optics means the beam is mismatched there.

Although of limited use otherwise, this optimised design does confirm the nontriviality of the non-regular matching section from the target observed in \texttt{SolenoidsOnly}.  \texttt{SolenoidsTo15cm} has found a different optimum with all of \texttt{S2}--\texttt{S5} deviating from maximal parameters in some way and \texttt{S4} having a flipped field.  The channel then continues with the same regular structure as in \texttt{SolenoidsOnly}, with maximal solenoid fields, until a few cells before the final focus (with solenoid \texttt{S26} being given a flipped field and several non-minimal drift lengths).  It is encouraging that the optimiser has produced `matching sections' in a similar way to a human designer, even though every parameter was separately variable so it was equally possible to put such a section in the middle of the channel away from the boundary conditions at the ends.

\begin{table}
\caption{\label{emittances}Normalised emittances of output beams from all optimised lattices in this chapter when projected into the $x$--$x'$ or $y$--$y'$ plane (choice of plane does not matter as the beam is cylindrically symmetric).}
\begin{center}
\begin{tabular}{lrrrrrr}
\hline
(\mmmrad)&RMS&75\%&90\%&95\%&99\%&100\%\\
\hline
\texttt{SolenoidsOnly}&34076&93666&177399&239913&343130&496991\\
\texttt{SolenoidsTo15cm}&18417&52940&84057&106017&156766&315720\\
\texttt{ChicaneLinacB}&8216&24031&37154&45431&59919&91079\\
\texttt{PhaseRotB}&9972&29677&42770&51120&64029&84877\\
\texttt{PhaseRotC}&10208&30366&44289&52548&65661&98812\\
\texttt{PhaseRotEb6a}&11592&34266&50288&60103&79165&114378\\
\texttt{PhaseRotLinac1}&13108&38696&58298&69791&88635&134122\\
\texttt{Linac900Removable6c2}&14812&44028&66225&78091&97455&140681\\
\hline
\end{tabular}
\end{center}
\end{table}

In front ends with no cooling, the beam emittance will generally increase with the yield, since there is no way to pack more particles into a smaller emittance.  The values for all the designs examined in this chapter are given in table \ref{emittances} with various amounts of the beam contained in the ellipse.  Since the next component after the front end will be a linac using quadrupoles, projected 2D emittances are given here instead of the 4D amplitude used for solenoid channels, as the dynamics of the two planes will become uncoupled after this point.  As energy increases, the un-normalised emittance corresponding to these values will fall, permitting more conventional structures further down the muon linac.  For example, above 8.7\,GeV a beam of normalised emittance 80000\,\mmmrad\ may fit through an ILC 1.3\,GHz module of bore radius 35\,mm and length 1256\,mm.  Lower frequencies with larger bores and shorter modules can fill the gap from 0.9--8.7\,GeV following on from something like the \texttt{Linac900Removable6c2} option.

\clearpage
\section{Chicane and 400\,MeV Muon Linac}\label{-results-chicanelinac}

This section examines an attempt to undo the distance--energy correlation that appears in the decay channel using a bending magnet chicane as shown in figure \ref{reeschicane} and described in \cite{ReesChicane}.  This idea from Grahame Rees was implemented in Muon1 with field maps and put on the distributed optimiser as the lattice \texttt{ChicaneLinacB}.\ \ Once the distance--energy correlation is undone, the rebunched beam is captured in an 88\,MHz RF solenoidal linac to 400\,MeV using cells similar to those in \cite{CERNcavity}.  This frequency is favoured because experimental work at CERN (also described in the reference) has verified operation of such cavities up to the 4\,MV/m gradient used in this optimisation.  It is different to the 201\,MHz used in many other studies \cite{Study2,ISS,IDSbaseline} because it attempts to capture the muons in a single bucket rather than splitting into a train of bunches spaced at a higher RF frequency.

\begin{table}
\caption{\label{summarychicanelinacb}Optimisation ranges and best muon yield for the \texttt{ChicaneLinacB} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel (to 30\,m) \emph{as for} \texttt{SolenoidsOnly} \emph{(table \ref{summarysolenoidsonly}) except}:}\\
\hline
Solenoid&Length&0.2--\textbf{0.9}\,m\\
&Radius&0.1--0.4\,m\\
&Field (\texttt{S2}--\texttt{S4})&$-5$--5\,T\\
&Field (\texttt{S5}--)&$-4$--4\,T\\
\hline
\multicolumn{3}{l}{Chicane: \emph{as specified in \cite{ReesChicane}} (fixed)}\\
\hline
\multicolumn{3}{l}{Linac:}\\
\hline
Structure&Number of cells&60--120\\
\cline{2-3}
Solenoid&Length&0.2--0.9\,m\\
&Radius&0.15\,m (fixed)\\
&Field&$-4$--4\,T\\
\cline{2-3}
Drift&Length&0.5--1\,m\\
\cline{2-3}
RF&Frequency&88\,MHz (fixed)\\
&Voltage&0--$(L_{drift}+L_{sol})\times$4\,MV/m\\
&Phase&$-180$--180\degree\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&2.2\,GeV&400$\pm$100\,MeV\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
1.400\%&0.001062&2.65$\times10^{13}$\\
\hline
\end{tabular}
\end{center}
\end{table}

\begin{figure}
\begin{center}
\includegraphics[width=155mm]{fig_620_reeschicane.png}
\caption{\label{reeschicane} The structure of the magnetic bending chicane lattice (top) and muons of energy 120--270\,MeV tracked through its field maps in Muon1 (bottom), adapted from \cite{ReesChicane}.  Placement relative to the end of the decay channel is also shown.}
\end{center}
\end{figure}

Table \ref{summarychicanelinacb} shows which parameters were optimised in the decay channel and linac either side of the chicane.  The maximum length allowed for solenoids in the decay channel has been increased from 0.6 to 0.9\,m because these solenoids were almost always given the maximal length in the decay channel optimisations.  The field and radius were also maximal but these would present much higher cost and engineering implications to increase than the length.  The result is that \texttt{ChicaneLinacB} has a nontrivial optimum for solenoid length, about 83\,cm, that is no longer at the end of the range, with the field converging to 3.25\,T as well.  Periodic solenoid channels exhibit resonances that cause particles to be lost around certain energies determined by the amount of focussing per cell.  To increase transmission, it is likely that the amount of focussing (solenoid field and length) has been optimised to place these resonance energies far from the bulk of the particle distribution.

\bothplots{ChicaneLinacB}{620}{chicanelinacb}

The linac section has a similar structure to the decay channel only now the solenoid radii are fixed at 15\,cm to not go outside the RF bore.  The drifts of $\ge$50\,cm now become crucial for inserting the RF gaps, with the lattice assuming the RF is capable of 4\,MV/m average gradient along the entire channel.  For the figure of merit, muons are now only counted within a band of 400$\pm$100\,MeV kinetic energy, a range that is chosen to contain the RF bucket of the muon accelerator \cite{ReesChicane}.

Figure \ref{plotchicanelinacb} shows how the RF bucket forms and moves up to within the target energy bands.  It also shows how the optics of the magnetic chicane put a severe cut on the momentum of particles transmitted: compare the drifted (2$^\mathrm{nd}$) longitudinal distribution to the much smaller (3$^\mathrm{rd}$) one after the chicane, which is unwrapped in this plot and appears as a section of large transverse amplitudes.  This\comment{ unfortunately} leads to the chicane/linac design having a low transmission of 2.65$\times10^{13}$ muons per second, approximately one quarter of the $10^{14}$ required for the neutrino factory to make $10^{21}$ neutrinos of each type in a $10^7$ second operating year.  The large loss is caused by the limited acceptance of the chicane, partly longitudinal but more importantly in handling particles with large transverse amplitudes.

Examining the behaviour of undecayed pions in this system (figure \ref{pimuchicanelinacb}) shows that they are mostly lost in the chicane because they have the wrong momentum.  A greener tail of pions can be seen exiting the bottom of the transverse plot immediately after the chicane begins, though a few with similar energies to the muons survive through it.  Almost no pions (one macro-particle in this simulation) remain at the 400\,MeV energy.  This plot also highlights a feature of the decay channel that the losses between the solenoids are almost entirely muons because these have the unpredictable directions resulting from pion decay.  The original pion beam gets scraped into shape within the first ten solenoids meaning almost no pion losses after that. 

\begin{figure}[t]
\includegraphics[width=160mm]{fig_620_transmission.png}
\caption{\label{transmission} Particle transmission as a function of distance for all eight designs discussed in this chapter.}
\end{figure}

Work moved on from the chicane idea after this optimisation because of the large losses.  Figure \ref{transmission} shows how the eight optimised designs discussed in this chapter retain their beam.  Large losses are always present at the end of the wider, 30\,m-long decay channel but the chicane takes the transmission three or four times lower than comparable points in other designs.  Dog legs on the end of these graphs show the final reduction in yield from wrong-energy muons being rejected.

\clearpage
\section{Phase Rotation}\label{-results-phaserot}

The large energy spread of the beam in the decay channel causes problems for a lot of conventional accelerator designs, as focussing varies greatly between particles.  To address this problem, a phase rotation section uses RF cavities to rotate the slanted longitudinal distribution (seen in figure \ref{plotsolenoidsonly}) so that more of the particles finish in a smaller energy band, usable by systems downstream.  It can achieve this mainly because after the drift in the decay channel, there is a correlation between arrival time and velocity, so if the RF voltage is made decelerating for the head of the bunch containing high energies and accelerating for the tail, this will cancel much of the variation.  This is only effective over a limited range because of the sinusoidal nature of the RF voltage variation, thus ideally a phase rotation section is optimised to put this range in the densest region of muons.

It can also be said that phase rotation is doing the opposite of the bending chicane in section \ref{-results-chicanelinac}, which tried to reduce the variation in time of arrival, while the energy spread was kept necessarily the same as a consequence of using a purely magnetic system.  Flight times were varied as a function of energy in the chicane, whereas RF systems can vary energies as a function of time of arrival.

\begin{table}
\caption{\label{summaryphaserotb}Optimisation ranges and best muon yield for the \texttt{PhaseRotB} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel (to 30\,m): \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb})}}\\
\hline
\multicolumn{3}{l}{Phase rotator:}\\
\hline
Structure&Number of cells&20--40\\
\cline{2-3}
Solenoid&Length&0.2--0.9\,m\\
&Radius&0.15\,m (fixed)\\
&Field&$-4$--4\,T\\
\cline{2-3}
Drift&Length&0.5--1\,m\\
\cline{2-3}
RF&Frequency&31.4285\,MHz (fixed)\\
&Voltage&0--$(L_{drift}+L_{sol})\times\frac{45}{28}$\,MV/m\\
&Phase&$-180$--180\degree\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&2.2\,GeV&180$\pm$23\,MeV\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
3.332\%&0.002528&6.31$\times10^{13}$\\
\hline
\end{tabular}
\end{center}
\end{table}

The \texttt{PhaseRotB} optimisation specified in table \ref{summaryphaserotb} has the same decay channel as \texttt{ChicaneLinacB} and a phase rotation section similar to the linac from that lattice except using a lower frequency.  The aim is not to produce an accelerating RF bucket but to have the RF period comparable to the spread in muon time of arrival from the decay channel.  A frequency of 31.4285\,MHz was chosen for compatibility reasons with the Rees cooling ring~\cite{ReesCoolRing} but is a good choice irrespective of the downstream system (the frequency was not optimised because that requires parameterising the RF gradient limit, which is 2.25\,MV per 1.4\,m of beamline here).  The goal kinetic energy spread of 180$\pm$23\,MeV was also inherited from the ring's acceptance but the important point is that it is a lot narrower than that for the 400\,MeV linac in \texttt{ChicaneLinacB} and has a central energy near the mean of the particles in the decay channel.  It provides a figure of merit that rewards narrowness in energy spread without requiring net acceleration or deceleration.
\comment{This paragraph could be expanded, could do some maths here and talk about the size of the bucket vs. wavelength, etc.}

\linearplot{PhaseRotB}{630}{phaserotb}

With the bending chicane removed, the muon transmission increased from 2.65 to 6.31$\times10^{13}$ muons per second into a proportionately narrower energy range.  Figure \ref{plotphaserotb} shows the resulting design and how the RF section flattens the energy distribution to get more muons into the goal range.  In fact, even more can finish in this range if there is some slight over-flattening, resulting in the S-shaped energy distribution in the rightmost plot.  The transverse plot shows that beam sizes in the RF section are similar to those in the \texttt{ChicaneLinacB} linac but many more particles have been retained, the regions of increased density represented by purple and red colours.

\begin{table}
\caption{\label{summaryphaserotc}Optimisation ranges and best muon yield for the \texttt{PhaseRotC} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel (to 30\,m): \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb})}}\\
\hline
\multicolumn{3}{l}{Phase rotator: \emph{as for} \texttt{PhaseRotB} \emph{(table \ref{summaryphaserotb})}}\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&10\,GeV&180$\pm$23\,MeV\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
3.042\%&0.003435&8.57$\times10^{13}$\\
\hline
\end{tabular}
\end{center}
\end{table}

It was at this point that new results regarding the optimal proton beam energy on the target (see section \ref{-target-energy}) became available.  As well as being integrated into the Scoping Study \cite{ISS} recommendations, the new preferred value of 10\,GeV was used in the Muon1 optimisations by replacing the old pion data file by a MARS calculation at that energy instead of 2.2\,GeV.  The data files were both generated with the same version MARS15.

The \texttt{PhaseRotC} lattice changes the proton beam energy to 10\,GeV but leaves everything else from the \texttt{PhaseRotB} optimisation the same, as shown in table \ref{summaryphaserotc}.  It therefore provides a direct comparison of the effect of changing the proton beam energy inclusive of the front end to the end of phase rotation being optimised.  Perhaps surprisingly, the efficiency in terms of muons per original pion has decreased to only 0.913 times of that with the 2.2\,GeV beam but the real yield in $\mu^+$/p$\cdot$GeV has increased by a factor of 1.359.  This difference comes from the fact that more pions were produced per Watt of proton beam power in the target at 10\,GeV, while the decrease in relative efficiency comes from proportionately more pions being produced in areas of the momentum phase space where they are not captured.  The high energy tail is a likely candidate for the location of this wastage, since more kinetic energy is available from the 10\,GeV protons in early collisions to produce high energy (multi-GeV) pions, which will not be captured by the phase rotation system.

The resulting yield of 8.57$\times10^{13}$ muons per second from \texttt{PhaseRotC} is becoming close to the $10^{14}$ neutrino factory requirement, though the later bunching and acceleration systems are at this point unspecified.  The optimised design (listed in appendix \ref{--Listings}) has only subtle differences to that for \texttt{PhaseRotB}, leaving most of the yield improvement accounted for by the proton beam energy change.

\bothplots{PhaseRotC}{630}{phaserotc}

Figure \ref{plotphaserotc} shows that the transverse profile of the beam is very similar to the \texttt{PhaseRotB} channel in figure \ref{plotphaserotb}.  The only visible difference being that \texttt{PhaseRotC} has a greater density of particles present in the first $\sim$5 solenoids of the decay channel near the target, as would be expected if the target produced more pions that were later lost.  The pion/muon breakdown is shown in figure \ref{pimuphaserotc}, with large pion losses visible between solenoids \texttt{S2} and \texttt{S3}; the continuation of pion to muon decay in the phase rotation section is also apparent.

\begin{table}
\caption{\label{summaryphaseroteb6a}Optimisation ranges and best muon yield for the \texttt{PhaseRotEb6a} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb}) except:}}\\
\hline
Structure&Number of cells&15--50\\
&Blocks&6 after \texttt{S9}\\
\hline
\multicolumn{3}{l}{Phase rotator \emph{as for} \texttt{PhaseRotB} \emph{(table \ref{summaryphaserotb}) except:}}\\
\hline
Structure&Number of cells&6--60\\
&Blocks&6\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&10\,GeV&180$\pm$23\,MeV\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
3.480\%&0.003930&9.81$\times10^{13}$\\
\hline
\end{tabular}
\end{center}
\end{table}

Both of the \texttt{PhaseRotB} and \texttt{PhaseRotC} lattices had almost every attribute of each component in the beamline variable in the optimisation.  This led to a large number of variables, 279 in the case of \texttt{PhaseRotB}\comment{247 for C} and also a slow pace of optimisation: these lattices were still increasing in score very gradually after as much as 6 months running on the distributed network while individual components were tuned to gain minor increases in yield.  It was expected, then, that a reduction in the number of variables could quicken the pace of convergence.  This was attempted in the lattice \texttt{PhaseRotEb6a}, presented in table \ref{summaryphaseroteb6a}, using the technique of `blocking' some of the many cells in the late decay channel and phase rotation section together.

The blocking works by observing that long homogenous sections of beamline are usually optimised to regularly repeating cells with almost the same parameters as each other even though they are controlled be independent variables in the optimisation.  Sections with RF may understandably incorporate some variation through the channel as the longitudinal phase space shape of the beam changes, however on local scales (i.e.\ without significant drift) the effects of RF are nearly additive in voltage, so a slow variation in cell parameters is expected to suffice.  Only special sections such as matching near the target require further cell-to-cell adaptation.  So with a blocked lattice, the majority of the beamline will be specified as blocks of identical cells that share the optimisation variables for only one cell.  The \texttt{PhaseRotEb6a} lattice (other lattice variations were tried but it worked the best) splits the late decay channel starting from solenoid \texttt{S10} and the whole of the phase rotation section each into 6 blocks of equal length, the overall length of these sections being controlled by the \texttt{decaycells} and \texttt{phaserotcells} variables.  Allowing the decay channel to vary in length is new but neither section can shorten to the point where each block consists of less than one cell.  The number of optimisation variables was reduced threefold to 93.

\linearplot{PhaseRotEb6a}{630}{phaseroteb6a}

The yield from this lattice was a further improvement to 9.81$\times10^{13}$ muons per second, essentially meeting the required rate.  Figure \ref{plotphaseroteb6a} shows how the optimiser has chosen a decay channel of just under 30\,m long without being forced to this length as in previous lattices.  The only constraint was that the number of solenoids in the decay channel had to be between 15 and 50.  This design also tapers the radii of the solenoids earlier on, something that may be favourable from a cost perspective.  The overall technique of the phase rotation remains similar but with a slightly longer time interval of particles ending up in the goal energy range, leading to the increased yield.

\clearpage
\subsection{Alternative Design for Two Signs}\label{-results-phaserot-dualsign}

As shown in figure \ref{powerpie2} and explained throughout chapter \ref{-target}, both positive and negative pions are produced in the target in similar numbers.  These will decay to both signs of muon in the decay channel, the motion of the negative particles being the mirror image of the positive ones provided the field remains axially symmetric.  This can be proved by inspecting the cross product in the Lorentz magnetic force law $\F = q(\vv\times\Bv)$ under a change of sign in $v_x$, $B_x$ and $q$ and confirming the result is a change in the sign of $F_x$ only.  Thus the decay channel will work similarly on both signs of particle.

\begin{figure}[h]
\includegraphics[width=160mm]{fig_631_dualsignfail.png}
\caption{\label{dualsignfail} Effect of the phase rotator optimised for only one sign of muons (red) on the negative sign (blue).}
\end{figure}

The same is not true of the RF phase rotation sections because these will decelerate negative particles in the time periods when positive particles are accelerated.  The result of a single-bunch phase rotation section (from lattice \texttt{PhaseRotC}) acting on both signs of muon is shown in figure \ref{dualsignfail}.  The positive muons have been rotated to a narrow energy range but the variation in energy of the negative muons has been doubled because the RF rotation has been acting in the wrong sense.  This results in the very poor longitudinal transmission of negative muons (9.4\%) into the goal energy band, as shown at the top of the figure.  The results in this section were calculated with a fast 1D-only code so efficiencies do not include transverse losses.

\begin{figure}[t]
\includegraphics[width=160mm]{fig_631_dualsignidea.png}
\caption{\label{dualsignidea} Proposed system for rotating both signs of muons with the same RF, even though they do not start with a 180\degree phase advance between them.}
\end{figure}

If the negative muons could somehow be delayed by 180\degree of the RF phase, then the $\E$ fields experienced by them would be the exact opposite of those for the positive muons and identical longitudinal dynamics would result, provided only one RF frequency was used in the channel.  Time of flight differences could be produced by a dipole sending one sign of muons onto longer path-length trajectories but this is technically difficult with such a high-emittance beam.  Another option that does not change the transverse dynamics, using purely RF, is illustrated in figure \ref{dualsignidea}.  This technique notices that a time of flight difference between the signs can be obtained after a drift section by accelerating one sign and decelerating the other, which is exactly what an on-peak RF cavity would do to the initial mixed sign beam.  Once the two signs are suitably far apart the RF will no longer produce the opposite effect on each and there exists a phase that will reverse the acceleration and deceleration of the two signs while still rotating each bunch in the correct direction.  This corresponds to a phase difference not equal to 180\degree in which the bunches are on the same sign of the RF voltage waveform but experience opposite slopes (so the effect will be opposite net accelerations with the same rotation direction).

\begin{figure}
\includegraphics[width=160mm]{fig_631_dualsigngood.png}
\caption{\label{dualsigngood} Improved phase rotation forming bunches of both signs of muons.}
\end{figure}

One-dimensional simulations of such a scheme were attempted with the same input distribution of muons from the end of the decay channel and gave results such as shown in figure \ref{dualsigngood}.  In this scheme the longitudinal transmission of the two signs is more equal and the average transmission of both is higher.  The disadvantage is that more complex phase space manipulations require a much longer RF channel, 183\,m instead of the 42\,m for the single-sign design, which would result in increased cost.

\section{Phase Rotation and 400\,MeV Linac}

Using RF phase rotation instead of a chicane and changing the proton beam energy to 10\,GeV improved greatly on the \texttt{ChicaneLinacB} design, but so far the goal energy has been 180$\pm$23\,MeV, which does not include any overall acceleration of the beam.  A more direct comparison could be made if a linac were added and the goal energy range changed back to the 400$\pm$100\,MeV used in the chicane and linac design.

\begin{table}[h]
\caption{\label{summaryphaserotlinac1}Optimisation ranges and best muon yield for the \texttt{PhaseRotLinac1} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb}) except:}}\\
\hline
Structure&Number of cells&10--50\\
&Blocks&1 after \texttt{S9}\\
\hline
\multicolumn{3}{l}{Phase rotator \emph{as for} \texttt{PhaseRotB} \emph{(table \ref{summaryphaserotb}) except:}}\\
\hline
Structure&Number of cells&1--60\\
&Blocks&1\\
\hline
\multicolumn{3}{l}{Linac \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb}) except:}}\\
\hline
Structure&Number of cells&60--120\\
&Blocks&1\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&10\,GeV&400$\pm$100\,MeV\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
6.944\%&0.007840&1.96$\times10^{14}$\\
\hline
\end{tabular}
\end{center}
\end{table}

The \texttt{PhaseRotLinac1} lattice, summarised in table \ref{summaryphaserotlinac1}, simply adds the 88\,MHz linac from \texttt{ChicaneLinacB} onto the end of the existing phase rotation design.  The linac now can inherit the blocking technique from the phase rotation (in \texttt{PhaseRotEb6a}) to reduce the number of variables.  Setting the number of blocks to just one per section proved to be the most successful of various combinations tried, so the late decay channel, phase rotation and linac now each have a single cell that repeats throughout the structure.

\linearplot{PhaseRotLinac1}{640}{phaserotlinac1}

The optimum (printed in appendix \ref{--Listings}) has an intermediate length decay channel with 39 solenoids covering a distance of just over 50\,m, a maximal length 60 cell phase rotator but a minimal length 60 cell linac.  The 88\,MHz linac has become minimal in one additional way: all the RF voltages have been set to zero!  This means that the resulting design, shown in figure \ref{plotphaserotlinac1}, performs all its longitudinal manipulation using the 31.4\,MHz cavities intended for phase rotation.  This is possible because no constraint was ever imposed that theses cavities should be used at bunching phase rather than for net acceleration or deceleration.  The 88\,MHz linac section could therefore be removed to reduce the length of the design shown to under 140\,m and give a marginal increase in yield by avoiding some muon decay.  This rejection of the higher RF frequency is likely because once the hybrid phase rotation/acceleration is able to move the beam into the target energy range on its own, imposing 88\,MHz RF just produces corrugations that overall move beam outside the range.  For a longer linac, having fully formed bunches is a necessity and this happens in the 900\,MeV linac optimisation of section \ref{-results-linac}.

The yield of 1.96$\times10^{14}$ muons per second is nearly twice the requirement for the neutrino factory.  This has come about mainly by widening the energy range to be similar to \texttt{ChicaneLinacB}, which was intended to hold tall 88\,MHz RF bucket(s) that are narrow in time.  By contrast, this optimum has filled the band with a wide distribution of times using the lower frequency; any linac built beyond this design would have to use a similarly low frequency to catch this distribution in a single bunch, the alternative being a rebunching section at a higher frequency (like 201\,MHz as used in \cite{Study2}), which would add costs in terms of muon decays.

\section{Direct 900\,MeV Linacs}\label{-results-linac}

The goal energy range of 400$\pm$100\,MeV, while useful for a comparison with \texttt{ChicaneLinacB}, is \comment{probably too generous }large compared to the energy ranges accepted by the downstream accelerators.  Based on the ISS report \cite{ISS} section 5.2, the first recirculating linac is assumed to accept an input kinetic energy of 0.9\,GeV with a momentum spread $\Delta p/p$ of 7\%.  This translates into a kinetic energy range of 830.41--969.64\,MeV, roughly 140\,MeV wide instead of 200\,MeV.

\begin{table}
\caption{\label{summarylinac900removable6c2}Optimisation ranges and best muon yield for the \texttt{Linac900Removable6c2} lattice.}
\begin{center}
\begin{tabular}{lll}
\hline
\multicolumn{3}{l}{Decay channel \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb}) except:}}\\
\hline
Structure&Number of cells&1--50\\
&Blocks&Up to 6 after \texttt{S9}\\
\hline
\multicolumn{3}{l}{Phase rotator \emph{as for} \texttt{PhaseRotB} \emph{(table \ref{summaryphaserotb}) except:}}\\
\hline
Structure&Number of cells&0--60\\
&Blocks&Up to 6\\
\hline
\multicolumn{3}{l}{Linac \emph{as for} \texttt{ChicaneLinacB} \emph{(table \ref{summarychicanelinacb}) except:}}\\
\hline
Structure&Number of cells&0--240\\
&Blocks&Up to 6\\
\cline{2-3}
RF&Phase&$-360$--360\degree\\
\hline\hline
&Proton beam energy:&Muon energy criterion:\\
&10\,GeV&900MeV (k.e.) $\pm$7\% $\Delta p/p$\\
\hline
Best yield: $\mu^+/\pi$&$\mu^+$/p$\cdot$GeV&$\mu^+$/s (4\,MW proton beam)\\
3.786\%&0.004274&1.07$\times10^{14}$\\
\hline
\end{tabular}
\end{center}
\end{table}

A longer linac with this goal energy is specified in optimisation \texttt{Linac900Removable6c2}, detailed in table \ref{summarylinac900removable6c2}.  The phase rotation at 31.4\,MHz and linac at 88\,MHz are still present \comment{except }but the linac \comment{part }can be made much longer.  All sections of the beamline can now be removed completely by the optimiser (apart from the first solenoid!) in the pursuit of higher yields.

\bothplots{Linac900Removable6c2}{650}{linac900removable6c2}

The result this time is that the decay channel has been reduced to just four solenoids and the phase rotation segment has been removed entirely.  Figure \ref{plotlinac900removable6c2} shows that this design does all the work using the 88\,MHz linac structure, which has been given the maximum allowed number of cells.  Unlike \texttt{PhaseRotLinac1} in the previous section, this linac forms something much more resembling a conventional RF bucket in the longitudinal phase space.  The yield of 1.07$\times10^{14}$ muons per second also meets the neutrino factory requirement, although the linacs beyond this design must have a wider bore to accommodate an uncooled beam with normalised emittance as given in table \ref{emittances}.

This yield is lower than \texttt{PhaseRotLinac1} both because of the stricter final energy criterion and because the muons have to survive a nontrivial amount of acceleration.  However, the 31.4\,MHz combined phase rotation and acceleration approach used in \texttt{PhaseRotLinac1} could likely not be extended to higher energies because a stable RF bucket was never formed.  This is why the entire linac was optimised again with the new energy goal and not extended from the previous system. 

The lack of decay channel means that this accelerator copes with multiple species (pions and muons) at the same time.  Figure \ref{pimulinac900removable6c2} colours the beam by composition and gives an illustration of how this works in practice, with the pions occupying a higher kinetic energy level bucket than the muons.  This is because the charged pions have a rest mass of 139.57\,MeV/$c^2$ compared to the muons' 105.66\,MeV/$c^2$, which means to have the same velocity (equivalently $\beta$ or $\gamma$) they must be given 32\% more kinetic energy.  The velocity is what determines the RF phases when the particles arrive at the cavities so scaling up the kinetic energies in this fashion ensures correct phasing for both species, ignoring transverse path length effects and the fact the RF voltage will be less effective compared to the energy the pions already have in rotating the contents of the bucket.  Fortunately the bucket only undergoes a fraction of a rotation before most of the pions have decayed so the effect of this discrepancy in bucket synchrotron frequency is small.

Removing the decay channel may not be practical to the extent the optimiser has done, since the area in the first few solenoids near the target has particularly high losses and radiation and this may not be conducive to stable operation of the RF cavities.

\begin{figure}
\includegraphics[width=160mm]{fig_650_xprimedlinac900removable6c2.png}
\caption{\label{xprimedlinac900removable6c2} Plot of the $x'$ distribution of the beam against $z$ for the optimised design from the \texttt{Linac900Removable6c2} lattice.}
\end{figure}

It is noticeable in the transverse plot of figure \ref{plotlinac900removable6c2} that the beam does not undergo any adiabatic shrinkage in $x$ as it is accelerated.  Given the relation between un-normalised and normalised emittance, this may seem counterintuitive, but the shrinkage has happened elsewhere: figure \ref{xprimedlinac900removable6c2} shows the distribution of $x'$ in the beam along the length of the linac.  Reduction of $x'_\mathrm{rms}$ is visible from the 10\,m point until the end of the linac, with the change in distribution shape in the 4\th and 6\th sixths of the linac caused by flipped-sign solenoids being used there.  Reduction before about 10\,m is not considered genuinely adiabatic because it is mostly beam losses in the decay channel, where there is no acceleration.

This behaviour comes about because the magnetic field is constant throughout the linac and geometrically the RF acceleration will reduce $x'$ by increasing $p_z$ but leave $x$ and $p_x$ alone.  In synchrotrons the beam shrinks in both $x$ and $x'$ because the focussing structure and Twiss parameters are kept constant by raising magnetic fields in proportion to the beam momentum.  With linacs there is more flexibility and the emittance may be traded off between $x_\mathrm{rms}$ and $x'_\mathrm{rms}$ by varying the focussing field.  Higher focussing, best attained with quadrupoles for higher energies, favours smaller $x_\mathrm{rms}$.

\nerdyplots{Linac900Removable6c2}{650}{linac900removable6c2}

Figure \ref{betalinac900removable6c2} visualises this same effect as an increase in $\tbeta$ along the channel.  Notice the reduction of un-normalised 4D emittance in figure \ref{emitlinac900removable6c2} as the beam is accelerated, while normalised emittance stays constant once all the pions have decayed.  The 2D emittances in this plot oscillate above the 4D values because of $x$--$y$ correlation caused by the periodic solenoid fields.  The sharp decrease of emittance at the beginning is due to losses as the beam enters the narrower linac section very soon after the target.

The component listing in appendix \ref{--Listings} shows that the first four of the six linac blocks have roughly the same RF parameters but the fifth turns off the RF voltage almost entirely.  Then the final block switches it back on but at a completely different phase.  The effect of this is the `lopsided' rotation of the particles in the bucket shown in figure \ref{plotlinac900removable6c2}, with \comment{it being particularly clear that }the different RF phase in the final sixth of the linac \comment{has rotated }rotating particles distributed along a diagonal in phase space into the goal band.  This nonconstant phase could allow a longer bunch of particles to finish in the goal band than would normally be expected, by shearing the distribution to reduce momentum spread and increase time spread.

Overall then, the optimised design from \texttt{Linac900Removable6c2} is a muon front end (without cooling) and initial acceleration system to 900\,MeV, producing over $10^{14}$ muons per second of a single sign.  Optimisation of a two-sign system similar to that in section~\ref{-results-phaserot-dualsign} is possible but not yet attempted with the full Muon1 code, so it is not known how many opposite sign muons can be accelerated.  For comparison, the ISS baseline~\cite{ISS} includes a cooling channel so ends with an RMS emittance of 7400\,\mmmrad, which is about half of the 14812\,\mmmrad\ produced here (see table \ref{emittances} for more data).  The ISS baseline transmits 0.0083\,$\mu^+$/p$\cdot$GeV compared to 0.0043 in this design, though this value varies strongly with the linac energy range: for example \texttt{PhaseRotLinac1} produces 0.0078\,$\mu^+$/p$\cdot$GeV in a range based on an 88\,MHz linac rather than the ISS RLAs.


\chapter{Conclusion}

This thesis has described the design of a pion production target and muon front end for the neutrino factory, which meets the $10^{14}$ muons per second criterion derived from $10^{21}$ muons per operational year \cite{FluxRequirement}.  In the process, the effect of target design variations on useful pion yield has been characterised and a design system using a distributed genetic algorithm has been created to produce entire accelerator designs automatically.  Therefore the work can be interpreted from the viewpoint of the three disciplines below.

\textbf{Accelerator design}.  The baseline neutrino factory design \cite{ISS,Study2} has been well studied but includes components such as the muon cooling channel and a 6\,m long magnet surrounding the target (figure \ref{targetstudy2}) that may prove challenging to build.  The designs in this thesis have no muon cooling and enforce 50\,cm gaps between all solenoids, which sacrifices some muon yield, in exchange for a target area that can be taken apart and fewer beam windows to contain cooling material.  The solid target option has also been used instead of the liquid mercury jet.  The designs presented have taken an acceptable number of muons to 900\,MeV, so it is suggested that the muon linac continues all the way to 25\,GeV, providing a much simpler design than the baseline (figure \ref{neutrinofactory}) at a length and cost that is not necessarily much greater, as explained at the end of section~\ref{-intro-frontend}.

Tracking of this design has been done with the author's Muon1 code that is fully 3D, includes particle decays and uses a particle set generated by MARS15 \cite{MARS15} from the target rather than an idealised beam distribution.  Section \ref{-results-phaserot-dualsign} presents some promising work using a 1D code that shows adaptations of this design can accelerate both signs of muon.

\textbf{Target design}.  The recommended design parameters for the pion production target are given in section \ref{-target-summary}.  However, many of these `optimal' values are surrounded by quite broad ranges in which the pion yield is almost as high.  Thus, readers interested in designing a target station may find the graphs in sections \ref{-target-energy}--\ref{-target-pdist} more useful since they allow other engineering constraints (of which there will be \emph{many}) to be traded off against performance.  The considerations that can be identified at the current level of design detail are discussed in chapter \ref{-target-eng}, including how the proton accelerator interfaces via the target with the rest of the neutrino factory.  However, the chapter can only be an introduction to the problem of target design, which is a field of study in its own right~\cite{HPTworkshop}.

The target designs were compared using calculations from the material interaction code MARS15.  However, hadronic interactions are not yet a `solved problem' in particle physics and large discrepancies can remain between the empirical models available.  Hence chapter~\ref{-target-bench} attempts to quantify the degree of uncertainty by comparing the MARS15 results with GEANT4 \cite{GEANT4} and data available from the HARP experiment \cite{HARP}.  The codes agree quite well on the optimal proton energy for the neutrino factory, though the absolute pion yields from GEANT4 are too high by a factor of two.  MARS15 is shown to have better (25\% level) agreement with the HARP data in the region available for comparison.

\textbf{Scientific computing}.  The search for high-yielding muon front end designs was made as automatic as possible by the use of computer optimisation.  The user necessarily has to specify the figure of merit and boundary conditions such as the particle source, practical range of sizes for components and general structure of the beamline, with the rest of the problem being recast as maximising a function.  The maximisation is done by a genetic algorithm, which requires many simulations, so the code was made to run on a distributed computing network to perform the large amount of work in parallel.  The general description of a range of accelerators can be written in the Muon1 lattice file format and submitted to this network and optimisation will commence.  The optimiser has been relatively successful on problems with hundreds of variables and the designs presented in chapter \ref{-results} are all examples of this.

Notably, the distributed network consisted mostly of volunteers who downloaded the client program from the project's website \cite{Muon1Website}, with a few of the author's computers also running.  The project has more than 100 users active at any one time, with thousands having run the program at some point and over 60 million muon front end designs have been simulated.  This demonstrates the enthusiasm of the public for interacting with scientific projects, even complex ones like the neutrino factory.

\subsubsection{Summary and Implications}
The design of the front end in section \ref{-results-linac} together with a muon linac to 25\,GeV provides a useful complement to the current main thread of neutrino factory design work being pursued in the International Design Study (IDS) \cite{IDSbaseline}.  Neutrino factory design work globally has progressed through several stages, initially concentrating on increasing the muon yield as much as possible, leading to US Feasibility Study II \cite{Study2}, with a relatively aggressive design for a cooling channel using liquid hydrogen.  The next stage focussed more on maintaining an acceptable muon yield while reducing the estimated hardware cost, thus came the lithium hydride cooling channel of the International Scoping Study (ISS) \cite{ISS} and the replacement of the high-energy end of the recirculating linac (RLA) by an FFAG, which provided more turns through the same RF cavities and therefore reduced the number of cavities required to achieve a set level of acceleration.

Unfortunately, yield \emph{vs.}\ cost was not the only trade-off being made during these design revisions.  The rearrangement of the acceleration system to allow more passes per RF cavity has come at the cost of a much more complex machine.  The current IDS baseline contains four muon accelerators of three different types (linac, RLA1, RLA2, FFAG), compared to the two types (linac, RLA) found in Study II.  The RLAs require magnet switchyards at each end, all of which are different from each other, and the FFAG performs an unconventional form of RF acceleration that relies on small time-of-flight differences in the orbit during acceleration.

It is possible that all of the components in the current IDS baseline design will work without major faults.  However, the fact that complexity increases \emph{risk} should not be ignored.  That is partly the motivation of the proof-of-principle experiments MICE \cite{MICE}, EMMA \cite{EMMA}, FETS \cite{FETS} and MERIT \cite{MERIT}, which test various parts or analogous models for the muon cooling channel, FFAG, proton driver linac and target, respectively.  At the present point in time, the risks of the neutrino factory design cannot be addressed properly without admitting the possibility that one or more of those experiments may produce a negative result (or identify problems in scaling up to a full-size or full-power subsystem).

The design in this thesis, while not the best in muon yield or possibly cost, relies on fewer unconventional technologies than the current baseline and is simpler.  No muon cooling or FFAG is involved at any point.  Large, low-frequency RF cavities similar to those in cooling channels are used, but there is no scattering material or cryogenics involved, and the cavities are placed between solenoids rather than at the peak field, which has been shown to reduce cavity performance \cite{RFmagnet}.  Linacs are proven technology and will not differ greatly for muons instead of protons, the only requirement being a larger bore at the low energy end, which other neutrino factory designs also have.  The pion production target is unavoidably difficult because of the high powers involved but this thesis suggests how it could be reduced to the problem of a conventional solid target, provided the solid targets can be moved for each pulse.

In conclusion, achieving the $10^{14}$ muons per second goal with the simplified design presented here provides an important piece of risk management for the neutrino factory project.  If the MICE or EMMA experiments point to problems with their novel technologies, fall-back designs that work without the corresponding subsystems are feasible.  The solid target option provides an alternative to MERIT's liquid target (although it has its own distinct set of challenges) and the range of acceptable proton driver energies in section \ref{-target-energy} provide additional flexibility to evaluate and make use of high-power proton facilities that may be built in the future.

\subsubsection{Future Work}
For the neutrino factory to be realised, a great deal (hundreds of person-years) of detailed engineering will have to be done.  There are also some important conceptual questions that must be resolved first: what sort of target (solid or liquid) is desired?  What are the implications for cost of a simplified design such as the one in this thesis compared to the baseline, which is shorter but more complex?

In terms of the Muon1 code and its associated optimisation work, it would be interesting to put the cooling components into the optimiser, or allow the solenoids near the target to overlap, to see if this produces a muon yield as high as the current IDS baseline.


\begin{thebibliography}{99}
\addcontentsline{toc}{chapter}{\numberline{}Bibliography}
\raggedright
\bibitem{FluxRequirement} \emph{GROUP REPORT: Physics at a Neutrino Factory}, C. Albright \emph{et al.} (Eds. S. Geer and H. Schellman), Report to the Fermilab Directorate, FERMILAB-FN-692, \texttt{hep-ex/0008064} (2000).
\bibitem{MARS15} \emph{The MARS Code System} version 15.07, by N.V. Mokhov, available from \link{http://www-ap.fnal.gov/MARS/}.
\bibitem{GEANT4} \emph{GEANT4---a simulation toolkit}, S. Agostinelli \emph{et al.}, Nuclear Instruments and Methods A \textbf{506}, pp.250--303 (2003), available from \link{http://geant4.web.cern.ch/geant4/}.
\bibitem{HARP} \emph{Status and prospects of the HARP experiment}, M. Ellis, J. Phys. G \textbf{29}, pp.1613--1620 (2003).
\bibitem{Muon1Website} Muon1 Distributed Particle Accelerator Design project website, \link{http://stephenbrooks.org/muon1}.
\bibitem{PauliNeutrino} \emph{Open Letter to Radioactive Persons}, W. Pauli (1930); reprinted in Physics Today \textbf{31}, p.27 (1978).  Note that at the time he calls the new particle a `neutron' rather than a neutrino.
\bibitem{NeutrinoNucleus} \emph{Detection of the Free Neutrino: A Confirmation}, C. L. Cowan Jr., F. Reines, F. B. Harrison, H. W. Kruse and A. D. McGuire, Science \textbf{124}, p.103 (1956).
\bibitem{Homestake} \emph{Measurement of the solar electron neutrino flux with the Homestake chlorine detector}, B.T. Cleveland \emph{et al.}, Astrophys. J. \textbf{496}, pp.505--526 (1998).
\bibitem{MNS} \emph{Remarks on the Unified Model of Elementary Particles}, Z. Maki, M. Nakagawa and S. Sakata, Prog. Th. Phys. \textbf{28}, pp.870--880 (1962).
\bibitem{SuperKamiokande} \emph{Evidence for Oscillation of Atmospheric Neutrinos}, Y. Fukuda \emph{et al.} (Super-Kamiokande Collaboration), Phys. Rev. Lett. \textbf{81}, pp.1562--1567 (1998).
\bibitem{RPPnumixing} \emph{Review of Particle Physics}, Particle Data Group (2008), section 13: Neutrino Mass, Mixing and Flavour Change (pp.163--171).
\bibitem{ReactorCHOOZ} \emph{Letter of Intent for Double-CHOOZ: a Search for the Mixing Angle $\theta_{13}$} (2004).
\bibitem{Reactor2} \emph{A New Nuclear Reactor $\nu$ Experiment to Measure $\theta_{13}$}, International Reactor $\theta_{13}$ Working Group (2004).
\bibitem{MatterEffect} \emph{Neutrino oscillations in matter}, L. Wolfenstein, Phys. Rev. D \textbf{17}, p.2369 (1978).
\bibitem{ISSphysics} \emph{Physics at a future Neutrino Factory and super-beam facility}, The ISS Physics Working Group, RAL-TR-2007-019, available from \link{http://arxiv.org/abs/0710.4947v2}.
\bibitem{CPVdelta} \emph{Search for CP Violation with a Neutrino Factory}, Morimitsu Tanimoto, Phys. Lett. B \textbf{462}, pp.115--120 (1999).
\bibitem{MINOS} \emph{Measurement of Neutrino Oscillations with the MINOS Detectors in the NuMI Beam}, P. Adamson \emph{et al.}, Phys. Rev. Lett. \textbf{101}, p.131802 (2008).
\bibitem{K2K} \emph{Measurement of Neutrino Oscillation by the K2K Experiment}, The K2K collaboration, M. H. Ahn \emph{et al.}, Phys. Rev. D \textbf{74}, 072003, \texttt{hep-ex/0606032} (2006).
\bibitem{CNGS} \emph{First Operational Experience with the CNGS Facility}, E. Gschwendtner, A. Pardons \emph{et al.}, contribution to NuFact'07, 6--11 August 2007, Okayama, Japan.
\bibitem{BetaBeams} \emph{Topical review on `beta-beams'}, Cristina Volpe, J. Phys. G \textbf{34}, R1--R44, \texttt{hep-ph/0605033} (2007).
\bibitem{EarlyNufact} \emph{Neutrino beams from muon storage rings: Characteristics and physics potential}, S.~Geer, Phys. Rev. D \textbf{57}, pp.6989--6997 (1998). 
\bibitem{LENF} \emph{A low energy neutrino factory for large $\theta_{13}$}, Steve Geer, Olga Mena and Silvia Pascoli, Phys. Rev. D \textbf{75}, 093001 (2007). 
\bibitem{EURONU09} \emph{EURONU WP6 2009 yearly report: Update of the physics potential of Nufact, superbeams and betabeams}, J. Bernabeu \emph{et al.}, \texttt{arXiv:1005.3146} (2010).
\bibitem{ISS} \emph{The International Scoping Study of a Neutrino Factory and Superbeam Facility}, The ISS Collaboration, RAL-TR-2007-023.
\bibitem{Study2} \emph{Feasibility Study-II of a Muon-Based Neutrino Source}, ed., S. Ozaki, R. Palmer, M. Zisman, and J. Gallardo, BNL-52623 (2001).
\bibitem{DriverSchool} \emph{Proton Drivers for a Neutrino Factory}, C.R. Prior, talk at the 1\st NuFact Summer School (2002), available from \link{http://hepunx.rl.ac.uk/uknf/wp1/prior-pdriver2002nfschool.doc}.
\bibitem{PDG-Review} \emph{Review of Particle Physics}, W.-M. Yao \emph{et al.} (Particle Data Group), J. Phys. G \textbf{33}, p.1 (2006), available from \link{http://pdg.lbl.gov}.
\bibitem{SolidTarget} \emph{Solid Target for a Neutrino Factory}, G.P. \v{S}koro \emph{et al.}, Proc. PAC 2009.
\bibitem{WireTest} \emph{Solid target studies in the UK}, J.R.J. Bennett \emph{et al.}, Proc. NuFact'05.
\bibitem{ICOOL} \emph{ICOOL: A Simulation Code for Ionization Cooling of Muon Beams}, R.C. Fernow, Proc. PAC 1999.
\bibitem{G4MICE} \emph{Simulation of MICE Using G4MICE}, C. Rogers and R. Sandstrom, Proc. EPAC 2006.
\bibitem{TRANSPORT} \emph{Transport, a Computer Program for Designing Charged Particle Beam Transport Systems}, K.L. Brown, D.C. Carey, Ch. Iselin and F. Rothacker. See yellow reports CERN 73-16 (1973) \& CERN 80-04 (1980).
\bibitem{OriginalRK} Runge, C., \emph{Math. Ann.} \textbf{46}, p.167 (1895); and Kutta, M.W.Z., \emph{f\"ur Math. u. Phys.} \textbf{46}, p.435 (1901).
\bibitem{NumRecipesRK} \emph{Numerical Recipes in C}, W.H. Press, B.P. Flannery, S.A. Teukolsky and W.T. Vettering, chapter 15.1: Integration of Ordinary Differential Equations - Runge--Kutta Method.
\bibitem{OPERA} \emph{Magnet Design Using OPERA}, Vector Fields Inc., \link{http://www.vectorfields.com/content/view/105/0/}.\bibitem{ReesCoolRing} \emph{Features of a Muon Cooling Ring for a Neutrino Factory}, G.H. Rees \emph{et al.}, Proc. NuFact'03.
\bibitem{ReesChicane} \emph{Muon front-end chicane and acceleration}, G.H. Rees \emph{et al.}, Proc. NuFact'02.
\bibitem{RandomDistribution} This technique known as `inverse transform sampling' is described in section II.2 of \emph{Non-Uniform Random Variate Generation} by Luc Devroye (1986), available from \link{http://cg.scs.carleton.ca/~luc/rnbookindex.html}.
\bibitem{MERIT} \emph{Studies of a Target System for a 4-MW, 24-GeV Proton Beam}, H.G. Kirk \emph{et al.}, CERN-INTC-2004-016.
\bibitem{SPL1} \emph{Conceptual design of the SPL, a high-power superconducting H$^-$ linac at CERN}, B. Autin \emph{et al.}, CERN-2000-012.
\bibitem{ISISUpgrade} \emph{ISIS Megawatt Upgrade Plans---Neutrons and Neutrinos for Europe}, C.R. Prior \emph{et al.}, Proc. PAC 2003.
\bibitem{SPL2} \emph{Conceptual design of the SPL II, a high-power superconducting H$^-$ linac at CERN}, F. Gerigk \emph{et al.}, CERN-2006-006.
\bibitem{MWSynch} \emph{The Synchrotron Option for a Multi-Megawatt Proton Driver}, C.R. Prior, Nuclear Physics B (Proc. Suppl.) \textbf{155}, p.312 (2006). 
\bibitem{ProjectX} \emph{Report on Accelerator Physics and Technology Workshop for Project X}, D. McGinniss \emph{et al.}, FNAL Beams-doc-2970-v1 (2007).
\bibitem{FNAL-PD1} \emph{The Proton Driver Design Study}, W. Chou \emph{et al.}, FERMILAB-TM-2136 (2000).
\bibitem{SlowSynch} \emph{A Slow-Cycling Proton Driver for a Neutrino Factory}, H. Sch\"onauer \emph{et al.}, Proc. EPAC 2000.
\bibitem{J-PARC} \emph{Present Status of J-PARC}, F. Naito, Proc. APAC 2007.
\bibitem{FNAL-MI} \emph{Beam Intensity Upgrade at Fermilab}, A. Marchionni, FERMILAB-CONF-06-225-AD (2006).
\bibitem{IDSproton} \link{https://www.ids-nf.org/wiki/FrontPage/Accelerator/Baselines/1} (2008).
\bibitem{ISIS} \emph{Spallation Neutron Source: Description of Accelerator and Target}, ed. B. Boardman, Rutherford Appleton Laboratory technical report RL-82-006 (1982).
\bibitem{TargetShock} \emph{LS-DYNA calculations of shocks in solids}, G.P. \v{S}koro \emph{et al.}, Proc. NuFact'05.
\bibitem{TantalumEmissivity} \emph{Thermophysical Properties of Matter}, Volume 7: Thermal Radiative Properties---Metallic Elements and Alloys, Y.S.Touloukian and D.P. DeWitt (1970).
\bibitem{RogerSlides} \emph{A Neutrino Factory Target Station Design based on Solid Targets}, J.R.J. Bennett, slides presented at the Third High-Power Target Workshop, Bad Zurzach, Switzerland (2007).
\bibitem{PowderJet} \emph{The Potential of Fluidised Powder Target Technology in High Power Accelerator Facilities}, C.J. Densham \emph{et al.}, Proc. PAC 2009.
\bibitem{PowderJetTech} \emph{The production and anatomy of a tungsten powder jet}, T.W. Davies, O. Caretta, C.J. Densham and R. Woods, Powder Technology \textbf{201}, Issue 3, pp. 296--300\comment{ \texttt{doi:10.1016/j.powtec.2010.03.018}} (2010).
\bibitem{TargetWheel} \link{http://hepunx.rl.ac.uk/uknf/wp3/target_eng/}-\link{SpokelessWheelDiscussion.ppt}.
\bibitem{MARS15Paper} \emph{MARS15 Overview}, N.V. Mokhov and S.I. Striganov, Hadronic Shower Simulation Workshop AIP Proceedings 896, Fermilab-Conf-07-008-AD (2007).
\bibitem{MatpropSLAC} \emph{Matprop} web-based tool at \link{http://www.slac.stanford.edu/comp/physics/}\-\link{matprop.html}.
\bibitem{OurNuFact05paper} \emph{Computed Pion Yields from a Tantalum Rod Target: Comparing MARS15 and GEANT4 across Proton Energies}, S.J. Brooks and K.A. Walaron, Proc. NuFact'05.
\bibitem{CPviolation} \emph{Physics at a future Neutrino Factory and super-beam facility}, The ISS Physics Working Group (2007), section 4.4: Leptonic unitarity triangle and CP-violation, equations (205) and (206) involving $J_{CP}$.
\bibitem{HaroldRodLength} \link{http://www.hep.ph.ic.ac.uk/uknfic/iss0406/talks/plenary/}\-\link{2006-04-26-PlenaryParallel-5-Kirk.ppt}, slide 13, optimal length of 60\,cm.
\bibitem{JohnBackReabsorption} \emph{Pion and muon yields from a 10GeV proton beam on various targets}, John Back, Proc. NuFact'08.
\bibitem{MyEPAC06Paper} \emph{Secondary Particle Production and Capture for Muon Accelerator Applications}, S.J. Brooks, Proc. EPAC 2006.
\bibitem{MARS15manual} \emph{The MARS Code System User's Guide Version 15(2006)}, Nikolai V. Mokhov and Catherine C. James, available from \link{http://www-ap.fnal.gov/MARS/intro_manual.htm}.
\bibitem{KennyGEANT4MARSnote} UKNF Note 30: \emph{Simulations of Pion Production in a Tantalum Rod Target using GEANT4 with comparison to MARS}, K.A. Walaron; \link{http://hepunx.rl.ac.uk/uknf/}\-\link{wp3/uknfnote_30.pdf} (2005).
\bibitem{HARP-Al-forward} \emph{Measurement of the production cross section of positive pions in p--Al collisions at 12.9\,GeV/c}, The HARP Collaboration, Nucl.Phys. B \textbf{732}, pp.1--45 (2006).
\bibitem{HARP-Ta-LAS} \emph{Measurement of the production of charged pions by protons on a tantalum target}, The HARP Collaboration (M.G. Catanesi, \emph{et al.}), Eur. Phys. J. C \textbf{51} no.4, pp.787--824 (2007).
\bibitem{CoolingReference} \emph{Principles and Applications of Muon Cooling}, D. Neuffer, Proc. 12th International Conf. on High-Energy Accelerators, p.481 (1983).
\bibitem{CoolingReference2} D. Neuffer, Part. Accel. \textbf{14}, p.75 (1983).
\bibitem{Goldstein1950} \emph{Classical Mechanics}, H. Goldstein, publ. Addison-Wesley (1950).
\bibitem{StochasticCooling} \emph{Stochastic Cooling}, D. M\"ohl, report CERN/PS/DL 78-25, online at \link{http://www.slac.stanford.edu/econf/C781015/pdf/013.pdf} (1978).
\bibitem{MICE} \emph{MICE Technical Reference Document}, The MICE Collaboration, available from \link{http://www.mice.iit.edu/}.
\bibitem{IDSbaseline} IDS-NF Note 002: \emph{Neutrino Factory: specification of baseline}, IDS-NF Steering Group, available from \link{https://www.ids-nf.org/wiki/FrontPage/Documentation} (2008).
\bibitem{CoolArrowsDiagram} \emph{The Physics of Muon Cooling for a Neutrino Factory}, S. Holmes - Ph.D. Thesis (Oxford), chapter 2: Muon ionisation cooling, figure 2.1 (2006).
\bibitem{BetheBloch} \emph{Review of Particle Physics}, Particle Data Group (2008), equation (27.1) on p.268, available from \link{http://pdg.lbl.gov}.
\bibitem{GraphiteEnergyLoss} Value from \link{http://durpdg.dur.ac.uk/HEPDATA/PART/}\-\link{AtomicNuclearProperties/HTML_PAGES/087.html}.
\bibitem{ScatteringEqn} \emph{Review of Particle Physics}, Particle Data Group (2008), equation (27.12) on p.271, available from \link{http://pdg.lbl.gov}.
\bibitem{CoolFormula} \emph{Multi-TeV muon colliders}, D. Neuffer, Advanced Accelerator Concepts '87, AIP Conf. Proc. \textbf{156}, pp.201--208 (1987).
\bibitem{PennNote} \emph{Beam Envelope Equations in a Solenoidal Field}, G. Penn, NFMCC-doc-71-v1 (2000), available from \link{http://nfmcc-docdb.fnal.gov/}.
\bibitem{TsaiRadiationLength}  \emph{Review of Particle Physics}, Particle Data Group (2008), section 27.4.1: Radiation Length, equations (27.20,21) and table 27.2 on p.272, available from \link{http://pdg.lbl.gov}.
\bibitem{ELMS} \emph{Ab initio liquid hydrogen muon cooling simulations with ELMS}, W.W.M. Allison \emph{et al.}, J. Phys. G \textbf{34}, pp.679--685 (2007).
\bibitem{ELMSsoftware} Available from \link{http://www-pnp.physics.ox.ac.uk/~holmess/ELMS/index.htm}.
\bibitem{CERNcavity} \emph{Cavity Design for the CERN Muon Cooling Channel}, Roland Garoby and Frank Gerigk, PS/RF Note 2001-014, CERN-NUFACT-NOTE 2001-087.
\bibitem{GeneticAlgorithm} \emph{Simulation of genetic systems by automatic digital computers}, A.S. Fraser, Aust. J. Biol. Sci. \textbf{10}, pp.484--491 (1957).
\bibitem{GAHandbook} \emph{Handbook of Genetic Algorithms}, L.D. Davis, publ. Van Nostrand Reinhold (1991).
\bibitem{DistributedComputingInfo} Active Distributed Computing Projects, \link{http://distributedcomputing.info/}\-\link{projects.html}
\bibitem{HPTworkshop} 1$^\mathrm{st}$--3\rd Oxford--Princeton High-Power Target Workshops.  2\nd workshop website: \link{http://www.physics.princeton.edu/~bridges/targetworkshop2/}.
\bibitem{EMMA} \emph{EMMA---the World's First Non-Scaling FFAG}, R. Edgecock \emph{et al.}, Proc. EPAC 2008.
\bibitem{FETS} \emph{Status of the RAL Front End Test Stand}, A. Letchford \emph{et al.}, Proc. IPAC 2010.
\bibitem{RFmagnet} \emph{Effect of High Solenoidal Magnetic Fields in Breakdown Voltages of High Vacuum 805\,MHz Cavities}, A. Moretti \emph{et al.}, Proc. LINAC 2004.
\bibitem{Twiss} \emph{Theory of the Alternating-Gradient Synchrotron}, E.D. Courant and H.S. Snyder, Ann.~Phys.~\textbf{3}, p.1 (1958).
\bibitem{TwissCERN} \emph{A Selection of Formulae and Data Useful for the Design of A.G. Synchrotrons}, C. Bovet, R. Gourian, I. Gumowski and K.H. Reich  (1970) CERN/MPS-SI/Int. DL/70/4.
\bibitem{LinearSYLee} \emph{Accelerator Physics}, S.Y. Lee (2004), chapter 2, section II.1: Transfer Matrix and Stability of Betatron Motion.
\bibitem{LinearWiedemann} \emph{Particle Accelerator Physics I, 2nd Edition}, H. Wiedemann (1998), chapter 5.2: Matrix Formalism in Linear Beam Dynamics.
\bibitem{ChrisRogersThesis} C.T. Rogers - Ph.D. Thesis (Imperial College, London), chapter 3 (2007).
\comment{ \bibitem{CoolingReference3} A.N. Skrinsky and V.V. Parchomchuk, Sov. J. Nucl. Phys. \textbf{12}, p.3 (1981). }

\end{thebibliography}

\clearpage % Have to clear page before every appendix to get the table of contents page numbers right
\appendix{MARS.INP Template File}\label{--MARSINP}

The token \texttt{\$energy} in the file below is replaced by a number in GeV for each energy required.  MARS uses kinetic energy and requires that this ends in a decimal point if it is a whole number (for instance \texttt{6.} for 6\,GeV but \texttt{2.2} for 2.2\,GeV).  The token \texttt{\$hole} is always replaced by \texttt{0.} in simulations where the rod is solid.
\begin{verbatim}
Tantalum Rod Pion Production [TEMPLATE] 
/home/csf/brooks/mars15/dat
C GUI switch
CTRL 0

C Generate 100000 events
NEVT 100000

C 0.01mm boundary precision, 2cm initial trial step
SMIN 0.001 2.

C Beam is protons(1), parallel gaussian(2) [now modified in BEG1 subroutine]
IPIB 1 2 
C 0.5cm RMS transversely (so rod is 2sigma), 1ns RMS longitudinally
BEAM 0.5 0.5 5=29.9792458
C Energy in GeV
ENRG $energy

C Two materials used: tantalum and vacuum
NMAT 2
MATR 'TA' 'VAC'

C Use 'R-sandwich' type geometry (default)
INDX 2=F
C Two R-sections: vacuum(#2) to $hole cm radius, tantalum(#1) to 1cm radius,
C ending at z=20cm
NLTR 2
RSEC $hole 1. 51=10 10 101=2 1
ZSEC 20. 1251=200

C We record particles at three surfaces, 1cm out, z=0-20cm;
C and r=0-1cm, z=0cm and z=20cm to fort.83 (81..90)
NSUR 3
RZTS 1. 1.  0. 20.  83.
     0. 1.  0.  0.  83.
     0. 1. 20. 20.  83.

STOP
\end{verbatim}

\clearpage
\appendix{Modification to User Subroutine \texttt{BEG1} in m1504.f}\label{--MARSBeam}

This is the section of the long Fortran file `m1504.f' that has been modified to generate the correct input proton distribution.
\begin{verbatim}
*      PARAMETER (CLIGHT=29979245800.D0)
      PARAMETER (PI=3.141592653589793238D+00) 
C- - - - - - - - - - - - - - - - - - - - - - - - - - - -
C+++ INSERT YOUR SOURCE TERM HERE +++
C      READ()...,W1,...
C      W=W*W1

      R=SQRT(1.D0-SQRT(RAND())) ! SJB: 1cm radius circular parabolic beam
      TH=RAND()*PI*2.D0
      X=R*COS(TH)
      Y=R*SIN(TH)

C++++++++++++++++++++++++++++++++++++
      RETURN
      END
\end{verbatim}

\renewcommand{\thesection}{\Alph{appendix}.\arabic{section}}
\renewcommand{\thefigure}{\Alph{appendix}.\arabic{figure}}
\clearpage
\appendix{The Linearised Beam Optics Model}\label{-cool-linear}
To understand and quantify the performance of cooling channels, it is informative to make the small-angle, or \emph{paraxial} approximation to the transport of the muon beam, in which the optical elements have linear (and thus easy to analyse) effects.  This approach also reveals the \emph{Twiss parameters}\footnote[2]{This name is historically inaccurate and they should be called Courant--Snyder parameters.  However, Twiss is the more common usage and avoids confusion with the `Courant--Snyder invariant'.} \cite{Twiss,TwissCERN} widely used in accelerator lattice design.

\section{Equations of Motion in $z$}
\renewcommand{\u}{\mathbf u}
\newcommand{\g}{\mathbf g}
Section \ref{-code-rk} shows how the transport of particles in the most general case can be described in terms of an augmented phase space vector $\s(t)=(x,y,z,\gamma v_x,\gamma v_y,\gamma v_z,t)$ for each particle and how it changes over time as given by a differential equation of the form $\dot\s=\f(\s)$.  If the particles are assumed to be travelling forwards so that $z$ increases monotonically with $t$, it is possible to restate the problem with $z$ as the independent variable instead of $t$, using a different set of phase-space variables $\u(z)$ including the transverse positions and velocities, forward velocity (or energy) and the time of arrival $t$ as a new dynamical variable that depends on $z$.  For a non-straight accelerator, this treatment uses curvilinear coordinates such that $x=y=0$ represents a specified reference path through the machine, on which $z$ is equal to the path length and the three axes remain orthogonal.  Non-zero $x$ and $y$ are measured on planes of constant $z$ perpendicular to the reference path.  These conventions mean that the mapping $\u(z_0)\rightarrow\u(z_1)$ fully describes the behaviour of the physical piece of accelerator for which $z_0\le z\le z_1$ (rather than the behaviour through a specific time interval).  This mapping can be obtained from solving the new equation of motion in the form $\u'=\g(\u)$, prime denoting differentiation with respect to $z$, noting that cases where $\dot z\le 0$ are outside the scope of this method.

Just as in section \ref{-code-motion}, there is some choice of how to parameterise the phase space, a sensible option being $\u=(x,y,t,x',y',E_k,z)$ where $E_k$ is the kinetic energy of the particle, in place of the peculiar $t'=\dd{t}{z}=\frac{1}{v_z}$ coordinate that would otherwise have been used.  Here, the form of $\g$ will be derived in cartesian coordinates only, because the transformation to the curvilinear coordinates of choice is standard mathematics and would yield very long equations in the general case.  This requires expressing the $z$-derivative of each component of $\u$ in terms of known constants and other components of $\u$.  The constants in this case are the speed of light $c$ and the mass $m$ and charge $q$ of the particle.
\begin{eqnarray*}
\dd{x}{z}&=&x' \\
\dd{y}{z}&=&y' \\
\dd{t}{z}&=&\frac{1}{v_z} \\
&=&\frac{\sqrt{1+x'^2+y'^2}}{v} \\
&=&\frac{(mc^2+E_k)\sqrt{1+x'^2+y'^2}}{c\sqrt{2E_kmc^2+E_k^2}}
\end{eqnarray*}
This final expression will be written as $\frac{1}{v_z}$ as it appears frequently in the other terms.  The derivatives of the primed variables need some manipulation to relate them to the time derivatives of $\gamma\vv$ given in section \ref{-code-motion}.
\begin{eqnarray*}
\dd{x'}{z}&=&\frac{1}{v_z}\dd{x'}{t} \\
&=&\frac{1}{v_z}\dd{}{t}\left[\frac{\gamma v_x}{\gamma v_z}\right] \\
&=&\frac{1}{\gamma v_z^2}\left(\Dt{(\gamma v_x)}-x'\Dt{(\gamma v_z)}\right)
\end{eqnarray*}
\comment{ \newcommand{\cE}{\mathcal E} \newcommand{\CE}{\B{\mathcal E}} }
It is now possible to substitute the Lorentz force law $\dd{}{t}(\gamma v_i)=\frac{q}{m}(E_i+(\vv\times\Bv)_i)$.
\begin{eqnarray*}
\dd{x'}{z}&=&\frac{q}{m\gamma v_z^2}(E_x+v_yB_z-v_zB_y-x'(E_z+v_xB_y-v_yB_x)) \\
&=&\frac{q}{m\gamma v_z^2}(E_x-x'E_z) + \frac{q}{m\gamma v_z}(x'y'B_x-(1+x'^2)B_y+y'B_z) \\
&=&\frac{qc^2}{mc^2+E_k}\left(\frac{1}{v_z^2}(E_x-x'E_z) + \frac{1}{v_z}(x'y'B_x-(1+x'^2)B_y+y'B_z)\right)
\end{eqnarray*}
The derivative of $y'$ can be calculated in a similar way, provided care is taken with the indices.
\[ \dd{y'}{z}=\frac{qc^2}{mc^2+E_k}\left(\frac{1}{v_z^2}(E_y-y'E_z) + \frac{1}{v_z}((1+y'^2)B_x-x'y'B_y-x'B_z)\right) \]
Finally, the rate of change of energy comes only from the electric field.
\begin{eqnarray*}
\dd{E_k}{z}&=&\frac{1}{v_z}\dd{E_k}{t} \\
&=&\frac{1}{v_z}q(\vv\cdot\E) \\
&=&q(x'E_x+y'E_y+E_z)
\end{eqnarray*}
Taken together with $\mathrm dz/\mathrm dz=1$, these expressions define $\u'=\g(\u)$.  The $\E$ and $\Bv$ fields also depend on $z$, which is why the independent variable $z$ was appended to the definition of the vector $\u(z)$ so as to close the system, analogously to the 7-element $\s(t)$.

\section{Transfer Matrices}
\newcommand{\m}{\mathbf m}
\newcommand{\A}{\mathbf A}
Given an initial condition $\u(z_0)$ and a final position in the beamline $z_1\ge z_0$, the first order system of differential equations $\u'=\g(\u)$ derived in the last section may be solved to give $\u(z_1)=\m(\u(z_0))$ for some new function $\m$.  This sort of function is known as a \emph{mapping function} because it can be applied to the initial phase space location to map directly from one point in the accelerator to another.  As $t$ was included in the definition of the phase space vector $\u$, this even works for time-varying electromagnetic fields since $\E$ and $\Bv$ are still uniquely specified by the phase space point.  However, mappings may generally not be used when there are interactions of the particles with each other, such as `space charge' when the Coulomb interaction from other particles in the beam enters the definition of $\E$ to a significant extent.  This is because $\u$ no longer contains all the relevant information about the state of the system.

Differential equations defined by a nonlinear function such as $\g$ will usually produce a nonlinear mapping function $\m$ that is even more complicated.  A key technique for dealing with this complexity is to linearly approximate $\m$ by considering small perturbations from a `central' point $\u_0$ at the beginning of the accelerator section: $\u(z_0)=\u_0+\delta\u_0$, where terms in $(\delta\u_0)^2$ and above may be neglected.  The result of the mapping is now
\begin{eqnarray*}
\u(z_1)&=&\m(\u(z_0))=\m(\u_0+\delta\u_0) \\
&=&\m(\u_0)+(\delta\u_0\cdot\nabla)\m(\u_0)+O((\delta\u_0)^2) \\
&\simeq&\u_1+\delta\u_1, \qquad \u_1=\m(\u_0) \qquad \delta\u_1=(\delta\u_0\cdot\nabla)\m(\u_0)
\end{eqnarray*}
assuming $\m$ is smooth enough to be Taylor expanded and defining the output central point and its perturbation term as shown.  The components of this output perturbation are given by 
\begin{eqnarray*}
(\delta\u_1)_i &=& \sum_j(\delta\u_0)_j\partial_jm_i(\u_0) \\
&=& \sum_j A_{ij}(\delta\u_0)_j, \qquad A_{ij}=\partial_jm_i(\u_0)
\end{eqnarray*}
where the matrix of constants $\A$ is defined so that in matrix product notation,
\[ \delta\u_1 = \A \delta\u_0. \]
This matrix $\A$ is formally known as the Jacobian of the function $\m$ at the point $\u_0$.  Since perturbations in the input or output $z$ are zero by the definition of the problem, the 7\th row and column can be removed and the remaining $6\times6$ matrix is called a \emph{(linear) transfer matrix} in accelerator terminology \cite{LinearSYLee,LinearWiedemann}.  It completely codifies the first order perturbative behaviour of particles near the trajectory that starts at $\u_0$ and ends at $\u_1$.

For beams, the central point is usually chosen to be the barycentre of the beam distribution, for example $\u_0=\ang{\u(z_0)}$, which ensures that the $\delta\u_0$ values are `small' for particles near the centre of the beam, or for the whole beam if it and the nonlinear terms in $\m$ are small enough.

\section{Beam Shape and Covariance Matrices}
\newcommand{\Z}{\B\zeta}
\newcommand{\R}{\mathbf R}
\newcommand{\Sm}{\mathbf S}
\newcommand{\C}{\mathbf C}
Now that the actions of accelerator sections on particles close to the central point have been represented to first order as matrices, it makes sense to find a compatible model of the (sufficiently small) beam itself that these can act on.  Consider first a vector of random variables $\Z$ such that
\[ \ang{\zeta_i^2}=1 \qquad \R\Z \sim \Z \]
for all $1\le i\le6$, where angle brackets take the expected value of a random variable, $\sim$~means `identical in distribution' and $\R$ is any $6\times6$ rotation matrix.  These formulae imply that the $\zeta_i$ all have unit variance and the distribution of $\Z$ is invariant under rotations of the 6-dimensional space, thus the probability density function has the form $f(|\Z|)$.  By symmetry arguments, these also imply that
\[ \ang{\Z}=\mathbf0 \qquad \ang{\zeta_i\zeta_j}=0 \]
for all $i\ne j$, with the first identity coming from considering $\R$ to be various 180\degree rotations that change the sign of some $\zeta_i$ and the second from considering a 90\degree rotation in the $i$--$j$ plane, which changes $\zeta_i\zeta_j$ to $-\zeta_j\zeta_i$.  This means that the $\zeta_i$ are not linearly correlated.  Note that there are many possible choices for the distribution $\Z$ that satisfy the conditions: one is a unit Gaussian distribution, in which case all the $\zeta_i$ are independent and identically distributed; another is a uniform distribution on the interior of a 6-dimensional sphere, in which case they are still identically distributed but no longer independent.

The model of the beam shall be that
\[ \delta\u \sim \Sm\Z \]
for some $6\times6$ matrix $\Sm$ that defines the beam shape, where $\delta\u$ is still the phase space offset from the central point (its 7\th entry is set to zero and removed) but interpreted now as a random variable statistically representing all particles in the beam.  This distribution transforms through the section of the accelerator with transfer matrix $\A$ follows:
\[ \delta\u_0 \sim \Sm_0\Z \qquad \Rightarrow \qquad \delta\u_1 \sim \A\Sm_0\Z, \]
so $\Sm_1 = \A\Sm_0$ is the transformation rule for shape matrices $\Sm$.

Although shape matrices are a natural way of defining beam shape (and useful for generating specific distributions computationally starting from a normalised generator for $\Z$), they are not uniquely determined by the beam itself since
\[ \R\Z \sim \Z \qquad \Rightarrow \qquad \Sm\R\Z \sim \Sm\Z, \]
meaning that the shape matrices $\Sm\R$ and $\Sm$ generate the same beam for any rotation matrix $\R$.  This situation appears elsewhere in physics where there is a gauge group, for example the electromagnetic vector potential $A^\mu$ can be chosen in multiple ways to describe the same physical situation.  It would be useful at this point to find the `beam equivalent' of the physical field $F^{\mu\nu}$ that is uniquely determined by measurable parameters.  The measurable parameters in this case are expectations of functions of the beam $\ang{f(\delta\u)}$.  If the central point is the beam barycentre then $\ang{\delta\u}=\ang{\Sm\Z}=\Sm\ang{\Z}=\mathbf0$, so the next simplest measurables are the quadratic functions, or covariances, equal to
\[ C_{ij} = \ang{\delta u_i \delta u_j}. \]
These may be aggregated into a matrix and as the expectation operator treats matrix elements separately, the right-hand side can be expressed as a vector outer product, allowing some useful manipulation:
\begin{eqnarray*}
\C &=& \ang{\delta\u\delta\u^T} \\
&=& \ang{\Sm\Z(\Sm\Z)^T} = \ang{\Sm\Z\Z^T\Sm^T} \\
&=& \Sm\ang{\Z\Z^T}\Sm^T.
\end{eqnarray*}
The elements of $\Z\Z^T$ are just $\zeta_i\zeta_j$, so by the unit variance and zero linear correlation properties of $\Z$, $\ang{\Z\Z^T}=\I$, the $6\times6$ identity matrix.  This gives the primary relation between $\C$ and $\Sm$:
\[ \C = \Sm\Sm^T. \]
That $\C$ is gauge-invariant can be checked by replacing $\Sm$ by $\Sm\R$ and noting that $\R\R^T=\I$ for rotation matrices.  Using the transformation law $\Sm_1 = \A\Sm_0$ for shape matrices, the action of a section of accelerator on the covariance matrix can be derived.
\[ \C_1 = \Sm_1\Sm_1^T = \A\Sm_0\Sm_0^T\A^T = \A\C_0\A^T \]

\section{Un-normalised and Normalised Emittances}\label{-cool-linear-emittance}
Section \ref{-cool-principle} discussed Liouville's theorem: the fact that Hamiltonian systems conserve phase space volume.  It will be useful to find a measure of phase space volume for the $\delta\u \sim \Sm\Z$ model of the (sufficiently small) beam developed so far.  The distribution may not have a sharp edge in phase space because the random vector $\Z$ could be something such as a Gaussian that never exactly goes to zero.  However, the variances $\ang{\zeta_i^2}$ are defined to be unity, so in this case it is possible to take the distribution of $\Z$ as the definition of `unit phase space volume'.  Thus the distribution of particles $\delta\u$ will have volume $\det\Sm$ in these units, as the determinant of a matrix is the factor by which it scales volumes.  This concept of phase space volume is known as \emph{un-normalised RMS emittance}
\[ \erms=\det\Sm; \]
it can also be defined relative to the measurable covariance matrix using properties of the determinant:
\[ \det\C = \det\Sm\Sm^T = \det\Sm \det\Sm^T = (\det\Sm)^2 = \erms^2 \qquad \Rightarrow \qquad \erms=\sqrt{\det\C}. \]

Note that the number of dimensions of $\delta\u$ in the phase space considered is often reduced to two or four, rather than the full six, in order to see the emittance effects in a subset of the variables of the system.  This works best when coupling between pairs of phase space variables is weak: the longitudinal pair $(t,E_k)$ are often only weakly coupled to the transverse pairs $(x,x')$ and $(y,y')$, so there exist varieties of (2D) \emph{longitudinal emittance}.  In a channel consisting only of quadrupole and dipole magnets, the transverse pairs are also decoupled from each other and 2D \emph{transverse emittances} can be used for each pair of variables (or \emph{phase space plane}).  Solenoids, however, mix the $x$ and $y$ planes, so \emph{4D transverse emittance} better represents the beam.

In cases where a beam without holes has a defined edge in phase space, that is the probability density function $f(\Z)=0$ for $|\Z|>R$ but $f(\Z)>0$ for $|\Z|<R$, the actual volume of phase space occupied by the beam (however diffuse it may be in some regions) can be calculated.  In a $D$-dimensional phase space this is given by
\[ V = S_D R^D \det\Sm, \]
where $S_D$ is the volume of a $D$-dimensional unit sphere, useful values being $S_2=\pi$, $S_4=\pi^2/2$ and $S_6=\pi^3/6$.  By convention, the factor of $S_D$ is usually dropped, leading to the definition of \emph{un-normalised 100\% emittance} (also called \emph{geometric emittance})
\[ \varepsilon^\mathrm{un}_\mathrm{100} = R^D \det\Sm = R^D \sqrt{\det\C}. \]
For a known model distribution such as a uniform or parabolic beam, the value of $R$ may be calculated from the requirement that the $\zeta_i$ have unit variance; note that in these cases the $\zeta_i$ are not independent, so a $D$-dimensional integral is required.  Beams with holes ($f(\Z)=0$ for some $|\Z|<R$) are also possible but there is no convention on whether the holes are counted in the total emittance.

Liouville's theorem states that phase space volume is conserved provided the system is described by a Hamiltonian and the correct measure of phase space volume is used.  The emittances discussed so far use the variables $x'$ and $y'$, which only conserve phase space volume if the beam is not accelerated or decelerated.  To make the theorem valid in general, $x'$ and $y'$ must be replaced by the `canonical conjugate momenta' in the $x$ and $y$ directions.  The end result of this calculation (described in \cite{ChrisRogersThesis}) is a just rescaling of the un-normalised emittances by the relativistic factor $\beta\gamma$ for each transverse plane:
\[
\varepsilon^\mathrm{n}_\mathrm{2D}=\beta\gamma\ \varepsilon^\mathrm{un}_\mathrm{2D} \qquad
\varepsilon^\mathrm{n}_\mathrm{4D}=(\beta\gamma)^2\ \varepsilon^\mathrm{un}_\mathrm{4D},
\]
giving a quantity known as the \emph{normalised emittance}.  This scaling applies to the RMS, 100\% and other percentile variants of the emittance similarly.  Note that if Liouville's theorem is obeyed, the incoming and outgoing emittances of a section of accelerator are the same, so $\det\Sm_1=\det\Sm_0$, which places a restriction on the transfer matrix that $\det\A=1$.

\newcommand{\eVs}{eV$\cdot$s}

The units of emittance depend on the number of phase space dimensions considered.  For a single plane such as $(x,x')$ (2D emittance), $x$ can be measured in millimetres and $x'$ in milliradians, so \mmmrad\ is a commonly used unit.  The basic SI unit would be metre-radians, or even just metres since radians are dimensionless, but this is a very large unit; however, \mmmrad\ is sometimes written as \um.  For the two transverse planes taken together (4D emittance) the unit becomes (\mmmrad)$^2$.  In the longitudinal plane $(t,E_k)$, the two variables are already conjugates in the Hamiltonian sense, so longitudinal emittance is always normalised and is commonly stated in units of \eVs\ (electronvolt-seconds).  This makes the full unit for \emph{6D emittance} (\mmmrad)$^2\cdot$\eVs.  Sometimes when particles are tracked in the time domain, 6D emittances in (\mmmrad)$^3$ appear because now the $z$ direction is treated exactly like the other two.

\section{Twiss Parameters}\label{-cool-linear-twiss}
\newcommand{\mattwo}[4]{\left[\begin{array}{cc}#1&#2\\#3&#4\end{array}\right]}
\newcommand{\smattwo}[3]{\left[\begin{array}{cc}#1&#2\\#2&#3\end{array}\right]}

The covariance matrix $\C$ consists of measurable quantities that determine the shape matrix of the beam up to internal rotations $\Sm\rightarrow\Sm\R$.  It is symmetric because $C_{ij}=C_{ji}=\ang{\delta u_i \delta u_j}$, so in the case of 2D phase space for a single axis ($\delta\u=(x,x')$), there are three, not four, measurables: $\ang{x^2}$, $\ang{xx'}$ and $\ang{x'^2}$.  The overall size of the beam has already been quantified by RMS emittance satisfying
\[ \erms^2=\det\C=\ang{x^2}\ang{x'^2}-\ang{xx'}^2, \]
so it is possible to produce a scale-invariant matrix of the remaining measurable quantities that only relate to the beam shape:
\begin{eqnarray*}
\det(\C/\erms)&=&1 \\
\C/\erms&=&\smattwo{\ang{x^2}/\erms}{\ang{xx'}/\erms}{\ang{x'^2}/\erms}
=\smattwo{\tbeta}{-\talpha}{\tgamma},
\end{eqnarray*}
where the last line defines the \emph{beam Twiss parameters} $\talpha$, $\tbeta$ and $\tgamma$.  Note that these definitions mean $\tbeta,\tgamma\ge0$.  Because $\C$ only had three independent variables and now one has been removed, the Twiss parameters only have two degrees of freedom between them, the unit determinant condition producing the constraint $\tbeta\tgamma-\talpha^2=1$.

An \emph{upright beam} is defined as being one in which $\talpha=0$, or equivalently $\ang{xx'}=0$ and is informative for understanding what the Twiss parameters mean (see figure \ref{twissellipse}).  A beam will pass through this configuration, in which there is (instantaneously) no overall expansion or contraction because the outermost particles have $x'=0$, multiple times in a focussing system.  \comment{If left to drift for a long distance, an upright beam will begin to expand but only because the drift has produced a positive correlation of $x\simeq x'\Delta z$ over that distance, so the expansion is quadratic, not linear, in $z$ as it is at other points.  In fact,} Upright beams typically occur at all the maxima and minima of the beam size $x_\mathrm{rms}=\sqrt{\ang{x^2}}$ within the focussing channel.  In the upright case the Twiss parameters and emittance are
\begin{eqnarray*}
\talpha &=& 0, \hspace{6cm} \mbox{(definition of upright beam)} \\
\erms &=& \sqrt{\ang{x^2}\ang{x'^2}} = x_\mathrm{rms}x'_\mathrm{rms}, \\
\tbeta &=& \frac{\ang{x^2}}{\erms} = \sqrt{\frac{\ang{x^2}}{\ang{x'^2}}} = \frac{x_\mathrm{rms}}{x'_\mathrm{rms}}, \\
\tgamma &=& 1/\tbeta. \hspace{6cm} \mbox{(by $\tbeta\tgamma-\talpha^2=1$)}
\end{eqnarray*}

\begin{figure}
\includegraphics[width=160mm]{fig_425_twissellipse.png}
\caption{\label{twissellipse} RMS ellipse shapes in phase space, showing Twiss parameters.}
\end{figure}

The RMS emittance emerges as the product of the RMS semi-axes of the phase space ellipse, which is consistent with being proportional to area.  The $\tbeta$ function, perhaps the most commonly used Twiss parameter, is the ratio by which the beam RMS size exceeds the RMS angle of a particle $x'_\mathrm{rms}$.  It has dimensions of length and is equal to the distance the beam would have to drift for the RMS change in particle $x$ during the drift to be equal to the original $x_\mathrm{rms}$, after which an elliptical phase space beam would be $\sqrt{2}$ times the original total size.  This is the characteristic length of a focus from optics.

The definition of $\tbeta=\ang{x^2}/\erms$ (regardless of $\talpha$) can be rearranged as $x_\mathrm{rms}=\sqrt{\tbeta\erms}$, meaning that for a constant $\erms$, $\tbeta$ determines spatial beam size.  Thus if a beam is required to be small in a certain region, the only pure optical technique available is to reduce $\tbeta$, as the emittance can only be changed by non-Liouvillian processes.

When the beam is not upright, $\talpha\ne0$, with negative $\talpha$ implying an expanding beam and positive $\talpha$ a contracting one.  If a linear magnetic field is applied such that it reduces $x'$ for positive $x$, this leads to an increase in $\talpha$ and the beam is focussed in that plane; a magnetic gradient of the opposite polarity would reduce $\talpha$ and defocus the beam.  The Twiss parameters can also be used in multidimensional systems, typically by projecting the phase space into a single 2D plane and examining the RMS ellipse shape, though if there is correlation of the distribution between the different axes this may make the beam appear larger than it is.

Note that similar constructions apply to the 100\% sizes of beams that are elliptical in phase space, with the Twiss parameters being the same but $x_\mathrm{max}$, $x'_\mathrm{max}$ being some multiple of the RMS values.  Twiss parameters can also be found as a function of length in a periodic section of accelerator, from the condition that the input and output beam ellipse shapes in phase space must match.  These are known as \emph{matched Twiss parameters} and have the property that a beam with those values of $\talpha$, $\tbeta$ and $\tgamma$ should be \emph{matched} (finish with the same distribution it started with) in that accelerator structure provided its emittance is small enough that the linear paraxial model holds.

\clearpage
\appendix{ICOOL Input File}\label{--ICOOL}
Below is the \texttt{for001.dat} input file for simulating a pencil beam of 200\,MeV/c muons through 30\,cm of $\mathrm{LH_2}$.  It uses the default ICOOL scattering model settings and was adapted from the \texttt{drif.f01} example included in the package.  Particle output is written to \texttt{for009.dat}.  The \texttt{npart} parameter may be reduced from \texttt{1000000} for fewer particles.
\begin{verbatim}
 Drift space example

 &cont npart=1000000 nprnt=3 prlevel=1 /
 &bmt /
1 2 1. 1        
0.    0.0     0.        0.      0.      0.200  !mean: x y z px py pz
0.    0.      0.        0.      0.      0.000  !sigs
0
 &ints /
 &nhs  /
 &nsc  nscat =1 /
-0.10 5e-3 40 1 2   -0.10 10e-3 20 2 2
 &nzh  /
 &nrh  /
 &nem  /
 &ncv  /

SECTION
OUTPUT
SREGION
0.30   1  0.003
1  0.  0.10
NONE
  0. 0. 0. 0. 0.   0. 0. 0. 0. 0.     0. 0. 0. 0. 0.
LH             
CBLOCK
   0. 0. 0. 0. 0.   0. 0. 0. 0. 0.
ENDSECTION
\end{verbatim}

\clearpage
\appendix{Listings of the Optimised Designs}\label{--Listings}

\input{appendices/appendix_c.tex}

\end{document}