%!TEX root = ../main.tex
\section{Checking the Productivity of Corecursive Functions}
\label{sec:productivity}

Before delving into a description of our proposal for a productivity checking algorithm for definitions with copatterns, we will discuss the properties of other approaches, and why they may or may not be desirable.

\subsection{Lazy Evaluation: The Haskell Approach}
It may be compelling to think that we can simply model coinductive data in the same way as it is done in Haskell, by evaluating all expressions lazily. Then any productivity algorithm would work for Haskell as well, making the result more generally applicable. The lazy evaluation approach, however, is insufficient in several aspects.

First and foremost, if we insist on making no distinction between inductive and coinductive data in our type system (Haskell makes no distinction), subject reduction is lost in a dependently typed system\,\citep{Abel13Copatterns}. The problem lies in the fact that coinductive data is modeled as the \emph{construction} of infinite trees, making dependent pattern matching possible on codata. Consider the type \texttt{U} in Figure~\ref{fig:subject_reduction_problem}, with inhabitant \texttt{u}. Even though it should not hold, the equality \texttt{u = C u} in the type of \texttt{eqU} holds when we allow dependent pattern matching on \texttt{x} in \texttt{eq}, since it allows the type system to reduce \texttt{x} to \texttt{C y}. In this case the type of \texttt{refl} in \texttt{eq} becomes \texttt{C y = force (C y)}, which should hold. However, if we replace the right-hand side of \texttt{eqU} with \texttt{refl}, a type error occurs since \texttt{u} is not equal to \texttt{C u}. Consequently, the type of \texttt{eq} changes when we do dependent pattern matching on its input, \texttt{x}, which means that subject reduction is lost. This problem is explained in greater detail by Abel et al.\,\citep{Abel13Copatterns}, and is also discussed in a correspondence initiated by Danielsson on the Agda mailing list\,\citep{OuryCounterexample}. Naturally, we want to preserve subject reduction in the Idris type system. When we are able to distinguish between inductive and coinductive data, one solution to this problem is to not allow dependent pattern matching on coinductive data. This approach, which is also implemented in Idris, is discussed in Section~\ref{sec:copatterns_in_idris}.

\begin{figure}
\begin{alltt}
data U : Type where         -- No distinction between data and codata
  C : U -> U

fix : (a -> a) -> a
fix f = f (fix f)

u : U
u = fix u

force : U -> U
force x = case x of
            C y => C y

eq : (x : U) -> x = force x
eq x = case x of
         C y => refl

eqU : u = C u
eqU = eq u
\end{alltt}
\caption{Oury's counterexample\,\citep{OuryCounterexample} in a dependently typed language with Haskell-like syntax. Here, \texttt{=} denotes propositional equality, with the sole constructor \texttt{refl}. Dependent pattern matching happens with \texttt{case} expressions.}
\label{fig:subject_reduction_problem}
\end{figure}

Another argument against the Haskell approach is that the core type theory underlying Idris is intended to have the Church-Rosser property\,\citep{BradyIdrisImpl13}, meaning that distinct reduction strategies lead to the same normal form. Furthermore, the total part of Idris is intended to be strongly normalizing, such that it enjoys the \emph{strong} Church-Rosser property\,\citep{Turner04totalfunctional}. This means that not only will every reduction strategy leading to a normal form lead to the same normal form, but \emph{any} reduction strategy must lead to a normal form. In Haskell, many definitions will lead to a normal form under lazy evaluation, while eager evaluation would lead to infinite recursion. Therefore, exploiting lazy evaluation in the total part of Idris would mean that it would no longer have the strong Church-Rosser property.

\subsection{Productivity Checking with Sized Types}
As shown by Abel and Pientka\,\citep{Abel13Wellfounded}, verifying the productivity of coinductive definitions with copatterns is indeed possible using sized types. Thus, the main argument against using sized types is one of usability, from the point of view of the Idris user. Thibodeau\,\citep{Thibodeau11} emphasizes that size annotations generally make the code harder to read and seem unnecessary (see Section~\ref{sec:related_work}). In our own experience, size annotations place quite a burden of bookkeeping upon the user, as they have a tendency to become a tool that is used to satisfy the productivity checker, instead of leading to clearer type specifications. Because totality is optional in Idris for definitions that to not appear in types (as opposed to in Agda, for instance), this means that in a practical programming setting, some users would most likely be inclined to switch off productivity checking for coinductive definitions, or refrain from using them entirely.

This argument is only valid as long as we have no way to fully reconstruct all size annotations. Once we do (if ever), the burden of sized types can be placed entirely upon the compiler. At such point, totality checking with sized types would become a practical approach.

\subsection{Guarded Corecursion}
\label{sec:guarded_cored}
In its original form presented by Coquand\,\citep{Coquand94} and Gim\'{e}nez\,\citep{Gimenez95}, the guardedness condition is generally too restrictive, as discussed in Section~\ref{sec:related_work}. The work done on the ESFP system by Telford and Turner\,\citep{Telford97ensuringstreams,Telford98ensuringthe} makes the guardedness criterion more generally applicable, even though some problems still remain, such as handling indirect application of corecursive functions. An example of this problem is the \texttt{g} function in Figure~\ref{fig:TelfordTurnerProblems}, the guardedness of which cannot be determined due to the indirect call to another function. In this case, this other function is the identity function, but the point is that the result of \texttt{(fst~funPair)} could have been any function. The function \texttt{f} is not considered guarded within their system because forward references may not be made to the rest of the process, i.e. the head of \texttt{f} cannot refer to the tail of \texttt{f}.

\begin{figure}
\begin{alltt}
-- f = 1 :: 1 :: \ldots                            -- g = 1 :: 1 :: \ldots
f = (head (tail f)) :: (1 :: f)                 g = 1 :: ((fst funPair) g)
                                                where funPair = (id, id)
\end{alltt}
\caption{Two types of corecursive functions not deemed productive by the extended guardedness criterion by Telford and Turner\,\citep[Section~6.3]{Telford98ensuringthe}. Here, \texttt{::} is the cons operator for a hypothetical definition of streams without copatterns, and \texttt{id} is the identity function. The functions \texttt{head} and \texttt{tail} are defined by pattern matching.}
\label{fig:TelfordTurnerProblems}
\end{figure}

Abel\,\citep{Abel99terminationchecking} argues that termination analysis should abstract from the syntactic structure of the program being analyzed to avoid making the outcome of the analysis susceptible to small changes in program structure. While this is true, non-syntactic checks can require the user to pay more attention to the productivity checker, which might not always be advantageous.

\paragraph{}
What we ultimately seek is a productivity checking algorithm for definitions with copatterns that covers as many realistic cases as possible, without burdening the user too much. In the following, we will provide a detailed description of our proposal.
%An explanation of our proposal for productivity checking in collaboration with size-change termination.
% Why not guardedness?
% Why not sized types?
% Why not the haskell way?
\subsection{Proposed Solution}
The basic idea of our proposal is \textit{time measurement}. We wish to always know how many observations we can safely make on a given recursive reference. To do so, we use time as an analogy. When defining what happens at a given time, we can only refer to what has happened earlier. Since anything we observe must exist before we can observe it, any observation on a coinductive instance happens after this instance is created. We will explain this using days as our time unit. To define what happens on any given day, we can only refer to what has happened on previous days. If we translate the days to numbers, where later days are given higher numbers, we can express this idea of only being able to reference back in time with an inequality.

If a given function \texttt{f} ``is created'' on day $\tau$, then the first observation on \texttt{f} is takes place on day $\tau+1$, the second observation on day $\tau+2$ etc. If we wish to define the result of an observation on any given day $\tau+n$ we can only refer to observations made on an earlier day $\phi$. We know that $\phi$ is an earlier day if $\tau+n\, \textgreater \,\phi$ holds. Any observation that complies with this definition is said to be \emph{time consistent}, as it makes no references to something that has not yet happened. If we think of observations as places in time, if we cannot refer to something that has not yet happened, we cannot refer to an observation that is unsafe to make. Therefore, any observation that is time consistent is also safe. As such, we can see time consistency as equivalent to productivity.

In Figure~\ref{fig:zeros} we decorate a definition \texttt{zeros} with \emph{time measures}. Since \texttt{zeros} is the starting point, we give it a base measure $\tau$. Any \texttt{head} or \texttt{tail} observations happens one day later than \texttt{zeros}, so they both get time measure $\tau+1$. To determine if \texttt{zeros} is productive, we examine the right hand sides of the observations. The \texttt{head} observation is simple to establish, as there are no corecursive calls. Therefore it gets the time measure $stable$, because we assume that \texttt{Z} is always known. We use this measure for any reference that is known not to be corecursive. The numeric value $stable$ can thus be thought of as negative infinity. In the \texttt{tail} observation we have a corecursive reference to \texttt{zeros}. This gets the time measure $\tau$ which is the time at which \texttt{zeros} is ``created''. To determine productivity, we must ensure that observations are only defined by what has already happened. Defining this notion as an inequality, we can see that \texttt{zeros} is productive because in the \texttt{head} case $\tau+1\,\textgreater\,stable$ holds, and in the \texttt{tail} case $\tau+1\,\textgreater\,\tau$ holds. Note that all of these annotations can be inferred.

\begin{figure}
\begin{tabular}{l c}

\begin{minipage}{3in}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
zeros : Stream Nat
head zeros = Z
tail zeros = zeros
\end{Verbatim}
\end{minipage} &
\begin{minipage}{3in}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
zeros$_{\tau}$ : Stream Nat
head$_{\tau+1}$ zeros$_{\tau}$ = Z$_{stable}$
tail$_{\tau+1}$ zeros$_{\tau}$ = zeros$_{\tau}$
\end{Verbatim}
\end{minipage}

\end{tabular}
\caption{An infinite stream of zeros. To the left is the implementation, and to the right is the implementation decorated with time measures.}
\label{fig:zeros}
\end{figure}

In Figure~\ref{fig:zerosprime} a diverging implementation of \texttt{zeros}, called \texttt{zeros'}, is shown. To establish that \texttt{zeros'} is not productive, we decorate the program in the same fashion as above. This time the recursive reference in the \texttt{tail} case has time measure $\tau+1$ rather than $\tau$, because we make an observation on \texttt{zeros'} on the right-hand side of the \texttt{tail} observation. For this to be productive, $\tau+1\,\textgreater\,\tau+1$ must hold, which it clearly does not. Therefore we can say that \texttt{zeros'} is not productive, since the definition of \texttt{tail zeros'} is not complete at the time when the \texttt{tail} observation is made on \texttt{zeros'} on the right-hand side.

\begin{figure}
\begin{tabular}{l c}

\begin{minipage}{3in}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
zeros' : Stream Nat
head zeros' = Z
tail zeros' = tail zeros'
\end{Verbatim}
\end{minipage} &
\begin{minipage}{3in}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
zeros'$_{\tau}$ : Stream Nat
head$_{\tau+1}$ zeros'$_{\tau}$ = Z$_{stable}$
tail$_{\tau+1}$ zeros'$_{\tau}$ = tail$_{\tau+1}$ zeros'$_{\tau}$
\end{Verbatim}
\end{minipage}

\end{tabular}
\caption{A non-productive implementation of \texttt{zeros}.}
\label{fig:zerosprime}
\end{figure}

\subsubsection{Coinductive Definitions with Coinductive Parameters}

Sometimes we want to write definitions that depend on other functions with coinductive parameters. When decorating \texttt{nats} in Figure~\ref{fig:nats_productivity}, we cannot give the right-hand side of the \texttt{tail} observation an accurate time measure since we do not know what \texttt{map} does to \texttt{nats}. We must first analyze \texttt{map} to see the effect it has on its coinductive argument.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
nats$_{\tau}$ : Stream Nat
head$_{\tau+1}$ nats$_{\tau}$ = Z$_{stable}$
tail$_{\tau+1}$ nats$_{\tau}$ = (map S nats)$_{?}$
\end{Verbatim}
\caption{A \texttt{Stream} of all the natural numbers, annotated with time measures.}
\label{fig:nats_productivity}
\end{figure}

When analysing \texttt{map}, a new time measure is introduced for each coinductive argument to the function. This measure is not used for checking the productivity \texttt{map} itself, but is used for callers of \texttt{map} to see how many observations \texttt{map} makes on a given argument. Consequently, in addition to checking the productivity of \texttt{map}, we also create a \textit{specification} for \texttt{map} which other functions can use to determine whether a call to \texttt{map} would lead to a productive definition. A specification can be saved in an internal hidden type for later use by the productivity checker.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
map$_{\phi, \upsilon}$ : (a -> b) -> Stream a -> Stream b
head$_{\phi+1}$ (map f s)$_{\phi}$ = f (head$_{\upsilon+1}$ s$_{\upsilon}$)$_{stable}$
tail$_{\phi+1}$ (map f s)$_{\phi}$ = map f (tail$_{\upsilon+1}$ s$_{\upsilon}$)$_{\phi}$
\end{Verbatim}
\caption{The map function for Streams.}
\label{fig:map}
\end{figure}

Making the specification is fairly simple. Since we are interested in knowing how many new observations \texttt{map} possibly makes on an argument, the greatest number of observations made on each coinductive argument must be identified. In the case of \texttt{map}, the greatest number of observations made on the stream argument (which is given time measure $\upsilon$) is $\upsilon+1$, which tells us that \texttt{map} performs at most one observation on this argument. This does not finish the specification, however. While it is true that \texttt{map} does make one observation on its stream argument, it does not do so until \texttt{map} itself is observed. This means that any reference to \texttt{map} would need one more observation on its left-hand side to invoke the observations \texttt{map} makes. So even though \texttt{map} adds one observation, it does so one day later. This delay of the observation counteracts the observation map makes. We model this counteraction by subtracting one from the time measure given to $\upsilon$ in the specification.

This gives us $\upsilon+1-1$ or just $\upsilon$, which means that according to its specification, \texttt{map} does not perform any additional observations on its input. We can now complete the annotation of \texttt{nats} from Figure~\ref{fig:nats_productivity}. As the specification of \texttt{map} tells us that any input remains unchanged, we know that the time measure of the call to \texttt{map} with \texttt{nats} as input in Figure~\ref{fig:natsComplete} is $\tau$. We can therefore conclude that \texttt{nats} is productive, as $\tau+1\,\textgreater\,\tau$.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
nats$_{\tau}$ : Stream Nat
head$_{\tau+1}$ nats$_{\tau}$ = Z$_{stable}$
tail$_{\tau+1}$ nats$_{\tau}$ = (map S nats$_{\tau}$)$_{\tau}$
\end{Verbatim}
\caption{A \texttt{Stream} of all the natural numbers, fully annotated with time measures.}
\label{fig:natsComplete}
\end{figure}

\subsubsection{Mutual Recursion}
For checking the productivity of mutually recursive coinductive definitions, we assume that we know which definitions refer to each other. Similar to the previous example, a specification is made for each function that can then be used to check the productivity of the callers. These specifications do not specify what happens to the input, but what happens to a specific call. Consider the two mutually recursive definitions \texttt{f} and \texttt{g} in Figure~\ref{fig:mutRec1}. For \texttt{f} we define specification $\tau_{g}$ saying what happens to the time measure $\tau$ in \texttt{g}, and vice versa we define $\upsilon_{f}$ for \texttt{g}. For the \texttt{tail} case in \texttt{f} to be productive we need that $\tau+1\,\textgreater\,\tau_{g}$ and for \texttt{g} we need $\upsilon+1\,\textgreater\,\upsilon_{f}+1$ to hold.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
f$_{\tau,\upsilon_{f}}$ : Stream Nat
head$_{\tau+1}$ f$_{\tau}$ = Z$_{stable}$
tail$_{\tau+1}$ f$_{\tau}$ = g$_{\tau_{g}}$

g$_{\upsilon,\tau_{g}}$  : Stream Nat
head$_{\upsilon+1}$ g$_{\upsilon}$ = Z$_{stable}$
tail$_{\upsilon+1}$ g$_{\upsilon}$ = tail$_{\upsilon_{f}+1}$ f$_{\upsilon_{f}}$
\end{Verbatim}
\caption{Two mutually corecursive definitions.}
\label{fig:mutRec1}
\end{figure}

Creating these specifications is again simple, and inferrable. To find $\upsilon_{f}$ we examine the references to \texttt{g} in \texttt{f}. The \texttt{tail} observation has one observation on the left-hand side and none on the right-hand side. For the same reason as with \texttt{map}, we subtract one for the left-hand side observations and add one for the right-hand side observations. This means that $\upsilon_{f} = \upsilon - 1$. Using the same approach for finding $\tau_{g}$ we get that $\tau_{g} = \tau$. We can now substitute these values into the inequalities from earlier and get that $\tau+1\,\textgreater\,\tau$ and $\upsilon+1\,\textgreater\,\upsilon - 1$. Therefore \texttt{f} and \texttt{g} are productive.

\subsubsection{Known Limitations}
We have discovered a few limitations to this approach. In this section we will present them and discuss possible solutions.

Our approach does not solve the problems discussed in Section~\ref{sec:guarded_cored} directly. The first is if an observation refers to something that is trivially productive, but under more observations. Consider the example in Figure~\ref{fig:forwardRef}. This definition is productive, but will be discarded by our approach as it does not hold that $\tau+1\,\textgreater\,\tau+2$. It is, however, easily solvable due to our use of copatterns. Since \texttt{head tail h} is directly defined, \texttt{head h} can be said to be productive if \texttt{head tail h} is productive.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
h$_{\tau}$ : Stream Nat
head$_{\tau+1}$ h$_{\tau}$         = head$_{\tau+2}$ tail$_{\tau+1}$ h$_{\tau}$
head$_{\tau+2}$ tail$_{\tau+1}$ h$_{\tau}$ = Z$_{stable}$
tail$_{\tau+2}$ tail$_{\tau+1}$ h$_{\tau}$ = tail$_{\tau+1}$ h$_{\tau}$
\end{Verbatim}
\caption{An example of a productive definition our productivity checking algorithm would discard.}
\label{fig:forwardRef}
\end{figure}

Another limitation is functions returning arbitrary functions. In Figure~\ref{fig:funList}, we cannot give an accurate time measure to \texttt{(funPair) i} because we do not know anything about what \texttt{fst funPair} does to \texttt{i}. A possible solution is estimating a worst case scenario for \texttt{funPair}. This, however, involves a lot of unfolding, at the risk of making the productivity checker very slow, while still not providing a very accurate analysis. We have not been able to find a desirable solution to this problem.

\begin{figure}
\begin{Verbatim}[commandchars=\\\{\},codes={\catcode`$=3\catcode`_=8}]
i$_{\tau}$ : Stream Nat
head$_{\tau+1}$ (i)$_{\tau}$ = Z$_{\tau-1}$
tail$_{\tau+1}$ (i)$_{\tau}$ = (fst funPair) i$_{?}$

funPair : (Stream a, Stream a)
funPair = (id, id)
\end{Verbatim}
\caption{Another example of a productive definition discarded by our productivity checking algorithm.}
\label{fig:funList}
\end{figure}

\subsubsection{Possible Algorithm}
We are convinced that time consistency is determinable by a machine. All analysis is syntactical which means that the user of the language does not have to annotate anything. To support this claim, we have made a natural language description of a possible algorithm.

A specification is considered a function from a time measure to a new time measure, reflecting the changes described by the specification. Note that destructors can be considered to be coinductive functions with a specification saying that one observation is made on its input, thus increasing the time by one. For ease of reading, we define the following function which will be referred to several times as \textit{calculate}:

\paragraph{
Given a coinductive definition with time measure $\phi$, if the definition is passed as an argument to any other coinductive definitions, apply the specifications of these definitions to $\phi$ and return the result. If it is not passed to any other coinductive definitions, just return $\phi$.}
\paragraph{f: Coinductive Definition}
\begin{enumerate}
\item Create a time measure $\tau$ for the definition.
\item For each observation in the definition do:
\begin{enumerate}
\item Count the number of left-hand side destructors and add this number to $\tau$. This is the time of this observation.
\item Find all corecursive references on the right-hand side. Calculate the time measure of all these references using \textit{calculate}.
\item Find all non-corecursive references on the right-hand side. Assign them the time measure $stable$.
\item The time of the observation (from (a)) must be greater than the greatest time measure on the right-hand side.
\end{enumerate}
\item If 2.(d) holds for all observations, the definition is time consistent.
\end{enumerate}

\paragraph{g: Coinductive Definitions with Coinductive Parameters}
\begin{enumerate}
\item Check the productivity of the definition itself using $f$, ignoring the coinductive parameters.
\item For each input parameter create a time measure.
\item For each observation in the definition do:
\begin{enumerate}
\item Count the number of left-hand side destructors. This is the time offset.
\item For each reference to the coinductive input do:
\begin{enumerate}
\item Calculate the time measure of the reference using \textit{calculate}.
\item Subtract the offset from the result.
\end{enumerate}
\item For each input, find the greatest time measure.
\end{enumerate}
\item The specification of the definition is made up of the greatest time measure for each coinductive parameter.
\end{enumerate}
\paragraph{h: Mutually Corecursive Definition}
\begin{enumerate}
\item For each mutually corecursive definition $k$ do:
\begin{enumerate}
\item Check the productivity of $k$ itself using $f$, ignoring the mutually corecursive references.
\item Create a time measure for every definition with which $k$ is mutually corecursive.
\item For each observation on $k$ with mutually corecursive references do:
\begin{enumerate}
\item Count the number of left-hand side destructors. This is the time offset.
\item Calculate the time measure of each reference using $calculate$.
\item Subtract the offset from these time measures.
\end{enumerate}
\item For each definition with which $k$ is mutually corecursive, find the greatest time measure. These are the local time measures of other definitions within $k$, indicating the effect $k$ has on these other definitions.
\item For each observation on $k$ with mutually corecursive references do:
\begin{enumerate}
\item Count the number of left-hand side destructors. This is the time of this observation.
\item Look up the time measure for $k$ in the specification for the function defining each mutually corecursive reference.
\item Calculate the time measures of the mutually corecursive references using $calculate$ with the time measure for $k$ as input in each case.
\item The time of the observation must be greater than the greatest time measure given on the right-hand side.
\end{enumerate}
\item If the condition in 1.e.iv. holds for all observations this definition is time consistent.
\end{enumerate}
\end{enumerate}


\documentclass[main.tex]{subfiles}
\begin{document}

\marginpar{Thursday\\ 2021-2-11, \\ compiled \\ \today}

% We have seen that there are two possibilities: either the accretion flow reaches the surface, or a shock forms.
If we consider accretion onto a NS we must account for the fact that the \(B\) field shapes the trajectories of the particles, making them not straight lines anymore.

The typical stopping length is \(y_0 \approx \rho \lambda _s \sim \SI{50}{g cm^{-2}}\) typically.
The magnetic field of a NS is typically strong enough to even curve the trajectories of protons, which become helixes. This means that \(\lambda _s\) decreases: the distance travelled between interactions is shorter, therefore \(y_0\) also decreases, reaching \(30 \divisionsymbol \SI{40}{g cm^{-2}}\) typically.

The thing we want to calculate is the \textbf{flux escaping the column}: how much energy per unit area and unit time is escaping? This will dictate the luminosity.

The column depth is defined as
%
\begin{align}
y(z) = \int_{z}^{\infty } \rho (z' ) \dd{z'} \leq y_0
\,,
\end{align}
%
where \(z\) is the vertical axis along the accretion column (which is parallel to the local normal to the surface).

Let us also define \(\Gamma _{\text{coul}}\), the heat released per unit time and volume by Coulomb collisions. We assume that this is uniform in the stopping region --- it does not depend on \(z\) --- and that it is zero elsewhere: if we are in a steady state, in which the heat introduced by \(\Gamma _{\text{coul}}\) is balanced by radiative losses (mostly due free-free emission and Compton scattering of electrons), then the following holds:
%
\begin{align}
\Gamma _{\text{coul}} = \begin{cases}
    \frac{L _{\text{acc}} \rho }{A y_0 } & y \leq y_0   \\
    0 & y > y_0
\,,
\end{cases}
\end{align}
%
where, as usual, \(L _{\text{acc}} \approx \eta \dot{M} c^2\), while \(A\) is the cross-sectional area of the accretion region. Since \(y_0 / \rho = \lambda _S\), the expression just amounts to a normalized luminosity per unit volume.

We should also consider magnetic effects on the cross-section: the main one is a resonance at the cyclotron energy
%
\begin{align}
E_c = \hbar \frac{e B}{m_e} \approx \frac{B}{\SI{e12}{G}} \times \SI{11.6}{keV}
\,.
\end{align}

It is a fact that the stopping layer the optical depth is quite large,  --- this is mostly due to electron scattering, which dominates among the radiative processes.
Therefore, we can use the diffusion approximation to relate the radiative flux to the radiative energy density \(U_{\text{rad}} = a T _{\text{rad}}^{4}\):\footnote{We are not actually assuming that the radiation is distributed as a blackbody: we are using the relation \(U _{\text{rad}} = aT _{\text{rad}}^{4}\) as a \emph{definition} for the parameter \(T _{\text{rad}}\), which is the equivalent temperature that a blackbody spectrum with the same energy density would be described by. }
%
\begin{align}
F _{\text{rad}} = - \frac{c}{3} \dv{U _{\text{rad}}}{\tau }
\,.
\end{align}

Since scattering dominates, the differential optical depth element is
%
\begin{align}
\dd{\tau } = \frac{\sigma _T}{m_p} \dd{y}
\,.
\end{align}

In the diffusion equation we can write a simple expression for the radiative flux at a height \(y\) if we assume that it is equal to all the heat released by collisions up to that height:
%
\begin{align}
F _{\text{rad}} (y) = \int_{y_0 }^{y} \Gamma _{\text{coul}} \dd{z}
= \frac{L _{\text{acc}} \rho }{A y_0 } \qty(y - y_0 )
\,,
\end{align}
%
from which we can integrate in order to calculate the energy density: expressing everything as a function of \(y\) we have
%
\begin{align}
- \frac{c}{3} \dv{U _{\text{rad}}}{y } = F _{\text{rad}} = \frac{\sigma _T}{m_p} \frac{L _{\text{acc}} \rho }{A y_0 } \qty(y - y_0 )
\,.
\end{align}

The flux changes linearly, so the energy density will change quadratically.
Once we compute \(U _{\text{rad}}\) we can solve the energy equation --- Compton cooling depends on \(U _{\text{rad}}\) --- and calculate the electron temperature \(T_e\), which in general will be different from the ``fictional'' \(T _{\text{rad}}\).

In order to compute the pressure we make the assumption that the electrons form an ideal gas in \emph{hydrostatic equilibrium}: then
%
\begin{align}
P(y) = \frac{k_B \rho T_e}{\mu m_p} =
\begin{cases}
    \frac{GM}{R^2} y + \frac{\rho_0 v^2}{y_0 } y & 0 < y \leq y_0  \\
    \frac{GM}{R^2} y + \rho_0 v^2 & y > y_0
\,.
\end{cases}
\end{align}

The term \(\rho_0 v^2 (y/y_0 )\) describes the \emph{ram pressure} of the gas.

\subsection{Shocks}

If the accretion rate is high enough (typically we need to require \(\dot{M} \gtrsim \SI{2e16}{g /s}\)) then protons are stopped above the photosphere and a shock forms.
The flow is cool and supersonic above the shock; hot and subsonic below the shock.

Let us start with a toy model for a 1D shock: we consider a fluid with a pressure \(P\), velocity \(v\) and density \(\rho \) moving in one dimension, along the \(x\) axis. We assume that at \(x = 0\) there is a shock; we label quantities pertaining to \(x < 0\) with a ``1'', and ones for \(x > 0\) with a ``2''.
The continuity equation tells us
%
\begin{align}
\dv{}{x} \qty(\rho v)
= 0 \implies \rho_1 v_1 = \rho_2 v_2
\overset{\text{def}}{=} J
\,.
\end{align}

The Euler equation tells us that
%
\begin{align}
\rho v \dv{v}{x} + \dv{P}{x} = f_x \implies \dv{}{x} \qty(P + \rho v^2) = f_x
\marginnote{Using the continuity equation, \(\rho v \partial v = \partial (\rho v^2) -v \partial (\rho v) = \partial (\rho v^2)\).}
\,,
\end{align}
%
where \(f_x\) is the force per unit volume.
This equation can be integrated in a small region around the shock: \([- \dd{x}, \dd{x}]\).
In reality the shock is not infinitesimal, but it can be typically approximated as such since it is very small compared to other characteristic length scales.
The integral of \(f_x\) is of the order of \(2 f_x \dd{x}\), which is vanishingly small:\footnote{We make the assumption that \(f_x\) does not diverge, that is, we assume that there are no impulsive forces. } therefore, we find
%
\begin{align}
P_1 + \rho_1 v_1^2 = P_2 + \rho_2 v_2^2 \overset{\text{def}}{=} I
\,.
\end{align}

The energy equation, under the assumption that the shock be \textbf{adiabatic} (no heat is conduced across it) reads, in terms of the internal energy \(\epsilon \):
%
\begin{align}
\dv{}{x} \qty(v \qty(\frac{\rho v^2}{2} + \rho \epsilon + P)) = f_x v
\,,
\end{align}
%
which can be simplified if we consider an ideal monoatomic gas: with these assumptions we can use the equations \(\rho \epsilon = \frac{3}{2} n k_B T\) and \(P = n k_B T = \frac{2}{3} \rho \epsilon \), therefore the energy equation becomes
%
\begin{align}
\dv{}{x} \qty[ \rho v \qty( \frac{v^2}{2} + \frac{5}{2} \frac{P}{\rho } )] &= f_x v  \\
\rho v \dv{}{x} \qty[ \frac{v^2}{2} + \frac{5}{2} \frac{P}{\rho }]&= f_x v
\marginnote{Continuity equation.}
\,.
\end{align}

We integrate this across the shock as well: this yields
%
\begin{align}
\frac{1}{2} v_1^2 + \frac{5}{2} P_1 =
\frac{1}{2} v_2^2 + \frac{5}{2} P_2
\overset{\text{def}}{=} E
\,.
\end{align}

These three conservation equations for \(J\), \(I\) and \(E\) are known as the \textbf{Rankine-Hugoniot} equations.

Since the flow is adiabatic we have the relation \(P = K \rho^{\gamma }\): then, the adiabatic sound speed is given by
%
\begin{align}
c_s^2 = \eval{\dv{P}{\rho }}_{\text{adiabatic}} = \gamma K \rho^{\gamma -1} = \frac{5}{3} \frac{P}{\rho }
\,.
\end{align}

We can get some interesting quantities in terms of the Rankine-Hugoniot invariants: the first is
%
\begin{align}
\frac{I}{Jv} = \frac{P}{\rho v^2} + 1 = \frac{3}{5 M^2} + 1
\,,
\end{align}
%
where \(M = v / c_s\) is the Mach number of the flow.

Also, the energy invariant can be written as
%
\begin{align}
E &= \frac{v^2}{2} + \frac{5}{2} \qty(\frac{Iv}{J} - v^2)  \\
v^2 - \frac{5I}{4J} v + \frac{E}{2} &= 0
\,.
\end{align}

The two roots of this equation, \(v_{1, 2}\), correspond to the flow speed up- and downstream of the shock.
\todo[inline]{I believe this can be justified by saying that this might well not be the case and the up and downstream are both regulated by the same velocity, only then we would not have a shock but just a regular point in the flow.}

The sum of the two roots of a quadratic equation \(\alpha v^2 + \beta v + \gamma = 0 \) is given by \(v_1 + v_2 = - \beta / 2 \alpha \), therefore
%
\begin{align}
v_1 + v_2 = \frac{5I}{4J}
\,.
\end{align}

Dividing through by \(v_1 \) and using the relation for the Mach number we found before, we get
%
\begin{align}
1 + \frac{v_2}{v_1 } = \frac{5}{4} \frac{I}{J v_1 }
= \frac{5}{4} \qty( \frac{3}{5 M_1^2}  + 1)
\,.
\end{align}

If we suppose that \(x<0\) is a hypersonic region, so that \(M_1 \gg 1\) (we have a \textbf{strong shock}), we can neglect the \(M_1^{-2}\) term and see that
%
\begin{align}
1 + \frac{v_2}{v_1 } \approx \frac{5}{4} \implies 4 v_2 = v_1
\,.
\end{align}

With the continuity equation and the energy equation we can see that this also means \(\rho_2 = 4 \rho_1 \) and \(P_2 = \frac{3}{4} \rho_1 v_1^2\).
The temperature in the shock region can be calculated from the ideal gas law:
%
\begin{align}
T_2 = \frac{\mu m_p P_2 }{k_B \rho_2 } = \frac{3}{16} \frac{\mu m_p}{k_B} v_1^2
\,.
\end{align}

In the case of column accretion, typically the velocity will be of the order of the free-fall velocity: \(v_1 \sim \sqrt{ 2GM / R}\), and the temperature below the shock will then be of the order
%
\begin{align}
T_2 \sim \SI{4e11}{K} \times \qty( \frac{M}{M_{\odot}} ) \qty( \frac{R}{\SI{e6}{cm}})^{-1}
\,.
\end{align}

An important fact to note is that the shock is collisionless, so the electron and proton temperatures are not equalized: because of this, in the previous expression we must replace \(m_p\) with \(m_e\) if we are looking for the electron temperature, and we find a value \(\sim 2000\) times smaller.
In a collisionless shock, the mediators of the interaction are photons, as opposed to particle-particle collisions.

We expect to see very hard radiation coming from the protons in the accretion region as long as this region is optically thin; if it is thick and radiation pressure dominates over gas pressure the picture changes: in the latter case the electron temperature is even lower than what this model provides, and the radiation becomes near-thermal.

\end{document}


\section{Helicity amplitudes}
\label{sect:helampconventions}
\index{helicity amplitudes}

This section will deal with some details related to helicity amplitudes
and their relations to partial wave amplitudes. In particular
the sign conventions are described and
the relations between the Jackson~\cite{Jack64} and the
Jackob-Wick~\cite{Jaco59} conventions
for the helicity formalism is explained.

This section is not meant as a complete guide to the use of
helicity amplitudes. There are several references that gives a
good introduction to the use of helicity amplitudes for describing
the dynamics of particle decays. Richman~\cite{Rich84} gives
a pedagogical introduction following the conventions of
Jacob and Wick~\cite{Jaco59}. Jackson~\cite{Jack64} uses a slightly
different choice of conventions. One of the main purposes of this section is
to describe these conventions and establish a map between the two
conventions. Both of these conventions are used in the literature
and, unfortunately, it is not always clear which convention is used.

The origin of the choice of conventions comes from how the
Euler angles are chosen. To make sure that there is no ambiguity
about definitions and conventions the next section provides definitions
for the terminology used.

\subsection{Preliminaries and definitions}

A few definitions are stated explicitly here as to avoid
confusion about what conventions are used.

First, the basis vectors $\hat x$, $\hat y$, and $\hat z$ are
said to form a right handed coordinate system if rotating the
$\hat x$-axis 90 degrees counter-clockwise, as seen from the positive
$\hat z$ directions, will take it to the direction of the $\hat y$
directions. It is assumed that $\hat x$, $\hat y$, and $\hat z$ are
mutually orthogonal. If the coordinate system is not right handed it is
left handed -- there is no other alternative. In the discussion
below all coordinate systems considered are right handed.

The Euler angles, $\alpha$, $\beta$, and $\gamma$ defines a
rotation $R(\alpha,\beta,\gamma)$ by
\begin{equation}
R(\alpha,\beta,\gamma)\equiv R_{z'}(\gamma)R_{y'}(\beta)R_{z}(\alpha)
\end{equation}
where this means that a rotation by $\alpha$ is first performed around the
$z$-axis. Then a rotation by $\beta$ around the $y'$-axis is done. Where
the $y'$-axis is the new axis as obtained after the first rotation.
Last the rotation around the new $z$-axis, $z'$, is performed by an
amount given by $\gamma$. Note that these rotations are not according to
a fixed set of rotation axis. This is inconvenient as the rotation operators
that we have are with respect to a fixed coordinate system. However,
there is a simple way of rewriting the Euler rotation in terms of
rotations around a fixed coordinate system,
\begin{equation}
R(\alpha,\beta,\gamma)=R_{z}(\alpha)R_{y}(\beta)R_{z}(\gamma).
\end{equation}
See e.g. Sakurai~\cite{Sakurai} page 171-174 for illustrations of the
rotations.

The $D^{J}_{m,m'}(\alpha,\beta,\gamma)$ functions are defined by
\begin{equation}
D^{J}_{m,m'}(\alpha,\beta,\gamma)\equiv
             \langle Jm|R(\alpha,\beta,\gamma)|Jm'\rangle.
\end{equation}
Using $d^{J}_{m,m'}(\beta)\equiv \langle Jm|e^{-i\beta J_y}|Jm'\rangle$\$ we
can write
\begin{equation}
D^{J}_{m,m'}(\alpha,\beta,\gamma)=
       e^{-im\alpha}d^{J}_{m,m'}(\beta)e^{-im'\gamma}.
\end{equation}

\subsection{Plane wave states}

The state $\Psi_{p\lambda}$ denotes a state with momentum $p$
along the $z$-axis with helicity $\lambda$. This state is obtained
by applying a boost $L(p)$ along the $z$-axis to the state
$|J=s\quad m=\lambda\rangle$, where $|J m\rangle$ are the
canonical angular momentum states. The total angular momentum,
$s$, is suppressed in the notation below.

Following Jacob and Wick~\cite{Jaco59} we define the states $\chi_{p\lambda}$
which have momentum $p$ along the negative $z$-direction
\begin{equation}
\chi_{p\lambda}=(-1)^{s-\lambda}e^{-i\pi J_y}\Psi_{p\lambda}.
\end{equation}

First we will verify that this state has the properties that
we expect;

\begin{eqnarray}
J_z\chi_{p\lambda} & = & J_z(-1)^{s-\lambda}e^{-i\pi J_y}\Psi_{p\lambda}\nonumber\\
                   & = & (-1)^{s-\lambda}e^{-i\pi J_y} e^{i\pi J_y}
                          J_z e^{-i\pi J_y}\Psi_{p\lambda}\nonumber\\
                   & = & (-1){s-\lambda}e^{-i\pi J_y}(-1)J_z\Psi_{p\lambda}\nonumber\\
                   & = & -\lambda \chi_{p\lambda}
\end{eqnarray}
shows that the eigen value of $J_z$ is $-\lambda$ as expected. Further, we look
at the application of the lowering operator, $J_{-}=J_x-iJ_y$, on the
state $\chi_{p\lambda}$
\begin{eqnarray}
J_-\chi_{p\lambda} & = & (-1)^{s-\lambda}(J_x-iJ_y)e^{-i\pi J_y}\Psi_{p\lambda}\nonumber\\
                   & = & (-1)^{s-\lambda}e^{-i\pi J_y}e^{i\pi J_y}(J_x-iJ_y)
                                         e^{-i\pi J_y}\Psi_{p\lambda}\nonumber\\
                   & = & (-1)^{s-\lambda}e^{-i\pi J_y}(-J_x-iJ_y)\Psi_{p\lambda}\nonumber\\
                   & = & -(-1)^{s-\lambda}e^{-i\pi J_y}J_+\Psi_{p\lambda}\nonumber\\
                   & = & -(-1)^{s-\lambda}e^{-i\pi J_y}\sqrt{(s-\lambda)(s+\lambda+1)}
                            \Psi_{p\lambda+1}\nonumber\\
	           & = & \sqrt{(s-\lambda)(s+\lambda+1)}(-1)^{s-(\lambda+1)}
                         e^{-i\pi J_y}\Psi_{p\lambda+1}
\end{eqnarray}
which shows that the application of $J_-$ on $\Psi_{p\lambda}$ behaves
as expected for a particle with helicity $\lambda$ along the
negative $z$-direction. Note in particular that the factor $(-1)^{\lambda}$
is important to ensure the right phase when applying the lowering
operators.
In fact, the properties that we have demonstrated above almost shows
the following property. If $p=0$, i.e. the particle is at rest, then
\begin{equation}
\chi_{0\lambda}=\Psi_{0-\lambda}.
\label{eq:statesame}
\end{equation}
The properties of the lowering
and raising operators and $J_z$ that we have shown above shows that the
states $\chi_{0\lambda}$ and $\Psi_{0-\lambda}$ differs at most by a
phase and that this phase is independent of $\lambda$. However, it
is easiest to show Eq.~\ref{eq:statesame} using the Wigner
$d$-functions
\begin{equation}
\chi_{0\lambda}=(-1)^{s-\lambda}e^{-i\pi J_y}\Psi_{0\lambda}
 = (-1)^{s-\lambda}\sum_{\lambda'}d^s_{\lambda'\lambda}(\pi)\Psi_{0\lambda'}
 = \Psi_{0-\lambda}
\end{equation}
since
\begin{equation}
d^s_{mm'}(\pi)=(-1)^{s-\lambda}\delta_{m,-m'}.
\end{equation}

An alternative way to define the states $\chi_{p\lambda}$ is by
\begin{equation}
\chi_{p\lambda}=(-i)^{2s}e^{-i\pi J_x}\Psi_{p\lambda}.
\label{eq:newdef}
\end{equation}
we find that
\begin{equation}
\chi_{0\lambda}=(-i)^{2s}e^{-i\pi J_x}\Psi_{0\lambda}=
(-i)^{2s}\sum_{\lambda'}\tilde d^s_{\lambda'\lambda}(\pi)\Psi_{0\lambda'}=\Psi_{0-\lambda}
\end{equation}
where
\begin{equation}
\tilde d^s_{m'm}(\theta)=\langle j m'|e^{-i\theta J_x}|j m\rangle.
\end{equation}
The $\tilde d$ function is similar to the standard Wigner $d$ function
except that it refers to expectation values for rotations around the
$x$-axis instead of the $y$-axis. An explicit formula for the
$\tilde d$ function is given by
\begin{eqnarray}
\tilde d^j_{m'm}(\theta)& = & \nonumber
\sum {\sqrt{(j+m)!(j-m)!(j+m')!(j-m')!}\over (m+m'+k)!(j-m'-k)!k!(j-m-k)!}\times\\
& &\left(\cos{\theta\over 2}\right)^{m'+m+2k}
\left(-i\sin{\theta\over 2}\right)^{2j-2k-m'-m}
\end{eqnarray}
from which it is easy to show that
\begin{equation}
\tilde d^j_{m'm}(\pi)=(-1)^{2j}\delta_{m',-m}
\end{equation}

It is straight forward to show that the application of the raising and
lowering operators as well as the operators $J_z$ on the state defined
by Eq.~\ref{eq:newdef} is what is expected.
Note in particular that there is no longer any need for phase factors
to get the right phase on the different helicity states. This is
particularly useful because it allows us to simply interpret
the states $\chi_{p\lambda}$ in the rest frame of the particle with the
momentum $p$ along the negative $z$ direction. That is, the state
$\chi_{p\lambda}$ is equal to $|J=s\quad m=\lambda\rangle$
in a coordinate system that
has been rotated by $\pi$ around the $x$ axis. This is very important
because it tells us how to construct the coordinates systems in
sequential decays when applying the helicity formalism, this will
be discussed further below.

We now define the two particle plane wave states when particle
A is along the positive $z$-direction by
\begin{equation}
|p\lambda_{A}\lambda_{B}\rangle=\Psi_{p\lambda_{A}}\chi_{p\lambda_{B}}.
\end{equation}
Applying $J_z$ to this state we find
\begin{equation}
J_z|p\lambda_{A}\lambda_{B}\rangle=
(\lambda_A-\lambda_B)|p\lambda_{A}\lambda_{B}\rangle
\end{equation}
States where the relative momentum, $p$, is not along the $z$-axis are
obtained by rotating the state $|p\lambda_{A}\lambda_{B}\rangle$.
Let $\theta$ and $\phi$ denote the polar coordinates for particle A, then
the we define the state $|p\theta\phi\lambda_{A}\lambda_{B}\rangle$ by
\begin{eqnarray}
|p\theta\phi\lambda_{A}\lambda_{B}\rangle=R(\alpha,\beta,\gamma)
             |p\lambda_{A}\lambda_{B}\rangle
\end{eqnarray}
where $R(\alpha,\beta,\gamma)$ is an Euler rotation. Here there is a
choice of conventions. Jackson~\cite{Jack64} takes
$\alpha=\phi$, $\beta=\theta$, and $\gamma=0$ while Jacob
and Wick~\cite{Jaco59} uses $\alpha=\phi$, $\beta=\theta$, and $\gamma=-\phi$.
The choice of the angle $\gamma$ is arbitrary but has to be used
consistently.

We have now defined the state $|p\theta\phi\lambda_A\lambda_B\rangle$
and explored its properties in some detail. This state is used as the
final state in the two body decays in the helicity formalism.

Before we are ready to use these states we need to construct a set
of states that are labeled by $p$, $\lambda_A$, and $\lambda_B$ and
have definite values of $J$ and $m$, i.e., are eigenstates of
$J^2$ and $J_z$. That such states exists is obvious since $p$,
$\lambda_A$, and $\lambda_B$ are invariant under rotations. We
denote these states by $|pJM\lambda_A\lambda_B\rangle$. The relation
between these states and the plane wave states created above is given by
\begin{equation}
|pJM\lambda_A\lambda_B\rangle=\sqrt{{2J+1}\over{ 4\pi}}
\int_{d\Omega}D^{*J}_{M\lambda_A-\lambda_B}(\phi,\theta,-\phi)
|p\theta\phi\lambda_A\lambda_B\rangle.
\label{eq:planewaveexpansion}
\end{equation}
Note that the states $|pJM\lambda_A\lambda_B\rangle$ are independent
of the choice of Euler angles.

\subsection{Helicity amplitudes}

We will now consider the decay $C\rightarrow A+B$. The initial
particle, $C$, is assumed to be in the state $|J M\rangle$ and the
final state, $A+B$, is $|pJM\lambda_A\lambda_B\rangle$. We will assume
that the interaction $U$ that causes this transition is invariant
under rotation, but is otherwise arbitrary. We which to evaluate
the matrix element
\begin{equation}
M=\langle pJM\lambda_A\lambda_B\rangle | U | J M \rangle.
\end{equation}
To do this we insert the identity written as
\begin{equation}
I=\sum_{p'J'M'\lambda_A'\lambda_B'}
|p'J'M'\lambda_A'\lambda_B'\rangle\langle p'J'M'\lambda_A'\lambda_B'|
\end{equation}
and use Eq.~\ref{eq:planewaveexpansion}.
\begin{eqnarray}
M & = & \langle p\theta\phi \lambda_A \lambda_B | U | J M \rangle\nonumber \\
  & = & \sum_{p'J'M' \lambda_A' \lambda_B'}
        \langle p\theta\phi \lambda_A \lambda_B |
        p'J'M'\lambda_A'\lambda_B'\rangle\langle p'J'M'\lambda_A'\lambda_B'|
        U | J M \rangle \nonumber\\
  & = & \langle p\theta\phi \lambda_A \lambda_B |
        pJM\lambda_A\lambda_B\rangle\langle pJM\lambda_A\lambda_B|
        U | J M \rangle \nonumber\\
  & = & \sqrt{2J+1\over 4\pi}\langle p\theta\phi \lambda_A \lambda_B |
       \int_{d\Omega'}D^{*J}_{M,\lambda_A-\lambda_B}(\phi',\theta',-\phi')
       |p\theta'\phi'\lambda_A\lambda_B\rangle
       \langle pJM\lambda_A\lambda_B|U | J M \rangle\nonumber \\
  & = & \sqrt{2J+1\over 4\pi}D^{*J}_{M,\lambda_A-\lambda_B}(\phi,\theta,-\phi)
        H_{\lambda_A\lambda_B}
\label{eq:helicityformula}
\end{eqnarray}
where the helicity amplitudes are defined by
\begin{equation}
H_{\lambda_A\lambda_B}=\langle pJM\lambda_A\lambda_B|U | J M \rangle.
\end{equation}

\subsection{Helicity amplitudes and sequential decays}

The previous section explained how the helicity formalism
is used to calculate the amplitudes for a two body decay, $A\rightarrow B+C$.
It is straight forward to now to use this in sequential decays.
The only thing that requires a it of care is the construction
of the coordinate systems in which the decay angles are measured.

To explain how to use the helicity formalism in sequential decays
we will consider the decay chain $A\rightarrow B+C$, $B\rightarrow D+E$,
and $C\rightarrow F+G$. The initial particle, $A$, is in the
state $|J=J_A\quad m=\lambda_A\rangle$. The amplitudes for
the decay $A\rightarrow B+C$ is now given by
\begin{equation}
A^{A\rightarrow B+C}_{\lambda_A\lambda_B\lambda_C}=
\sqrt{2J_A+1\over 4\pi} D^{*J_A}_{\lambda_A,\lambda_B-\lambda_C}
(\phi_B,\theta_B,-\phi_B)H^{A}_{\lambda_B\lambda_C}
\end{equation}
where $\theta_B$ and $\phi_B$ are the polar angles of particle
$B$ in the rest frame of particle $A$.

Similarly, we can write the amplitude for the decay of particle $B$
\begin{equation}
A^{B\rightarrow D+E}_{\lambda_B\lambda_D\lambda_E}=
\sqrt{2J_B+1\over 4\pi} D^{*J_B}_{\lambda_B,\lambda_D-\lambda_E}
(\phi_D,\theta_D,-\phi_D)H^{B}_{\lambda_D\lambda_E}.
\end{equation}
The coordinate system in which the angles $\theta_D$ and $\phi_D$
are measured is obtained by rotating the coordinate system of the
parent particle, $A$, using the same Euler angles as was used
when calculating the amplitude for the decay of particle $A$.
This means that the coordinate system for particle $B$ is obtained
by doing the rotation $R(\phi_B,\theta_B,\phi_B)$ of the
coordinate system of particle $A$.

In the same way we obtain the amplitude for the decay of particle
$C$,
\begin{equation}
A^{C\rightarrow F+G}_{\lambda_C\lambda_F\lambda_G}=
\sqrt{2J_C+1\over 4\pi} D^{*J_C}_{\lambda_C,\lambda_F-\lambda_G}
(\phi_F,\theta_F,-\phi_F)H^{C}_{\lambda_F\lambda_G}.
\end{equation}
As discussed above the coordinate system for the second particle,
here particle $C$ in the decay of particle $A$, is obtained by rotating
the coordinates system of the first particle, $B$, by $\pi$ around
its $x$ axis. I.e. the $x$-axis of particles $B$ and $C$ frames are
parallel.

\subsubsection{Jackson convention}

In the Jackson convention the Euler rotation is taken to be
$R(\phi,\theta,0)$ where the angles $(\theta,\phi)$ are the
polar coordinates for $\vec p$. This is a
rotation first by $\phi$ around the
$z$-axis and then a rotation by $\theta$ around the new $y$-axis.
The new $y$-axis is in the direction of $z\times \vec p$ and
the new $x$-axis is therefore in the direction $(z\times \vec p)\times \vec p$.

This is a simple geometrical construction that allows the construction
of the coordinate system used with the Jackson convention for the
Euler rotations.

\subsubsection{Jacob-Wick convention}

The coordinate system used in the Jacob-Wick convention is obtained by
performing an additional rotation of $-\phi$ around the new $z$-axis
as obtained in the Jackson conventions.

In the sense that there is a simple geometrical construction for the
coordinate system in the Jackson convention if might be argued that
this convention is somewhat simpler to use.

%Consider the decay $A\rightarrow BC$. The particle $A$ is
%described by the state $|J,m_z=\lambda_A\rangle$ in the
%coordinate system $x$, $y$, and $z$. As conventional, the
%$z$ axis has been chosen as the quantization axis.
%
%\begin{figure}
%\begin{center}
%\psfig{figure=helamp.eps,height=2.5in}
%\caption{The state of the initial particle, A, with total angular
%momentm $J$ and spin projection $\lambda_A=m_z$ along the
%$z$-axis is labeled by $|J,m_z=\lambda_A\rangle$ in the
%coordinate system shown in the figure. The decay products, B and C,
%are back to back in the rest frame of particle A and the
%angles $(\theta_A,\phi_A)$ and $(\pi-\theta_A,\pi+\phi_A)$
%gives the polar coordinates for B and C respectively.
%\label{fig:helamp}}
%\end{center}
%\end{figure}
%
%Particle $B$, produced in the decay, will have a direction
%which will be labeled $\hat p$. The polar coordinates for
%this direction, as measured in $A$'s coordinate system will
%be labeled $\theta_A$ and $\phi_A$, see Figure~\ref{fig:helamp}.
%To write down the
%amplitude for this decay a choice of Euler angles has to be
%made that rotates the original $z$ axis to the directions $\hat p$.
%This can be accomplished by chosing $\alpha=\phi_A$ and
%$\beta=\theta_A$. However, the azimuthal angle $\gamma$ around
%the new $z$ axis, $z'$, is arbitrary. This is the source
%of conventions for the helicity formalism. The two common
%conventions are the Jackson convention which takes $\gamma=0$
%and the Jacob-Wick convention which takes $\gamma=-\phi_A$.
%
%Given the choice of the Euler angels, $\alpha$, $\beta$, and $\gamma$
%the amplitude for the decay can be written as
%\begin{eqnarray}
%A_{\lambda_A\lambda_B\lambda_C}&=&
%\sqrt{2J+1 \over 4\pi}H_{\lambda_B\lambda_C}
%D^{J*}_{\lambda_A,\lambda_B-\lambda_C}(\alpha,\beta,\gamma)\nonumber\\
%&=&\sqrt{2J+1 \over 4\pi}H_{\lambda_B\lambda_C}
%e^{i\lambda_A\alpha+i(\lambda_B-\lambda_C)\gamma}
%d^{J}_{\lambda_A,\lambda_B-\lambda_C}(\beta)\label{eq:helamp}
%\end{eqnarray}
%Using the explicit choices for the Euler angles according to the
%conventions we obtain the amplitudes according to the two
%different conventions
%\begin{eqnarray}
%A^{\rm Jack}_{\lambda_A\lambda_B\lambda_C}&=&
%\sqrt{2J+1 \over 4\pi}H^{\rm Jack}_{\lambda_B\lambda_C}
%e^{i\lambda_A\phi_A}
%d^{J}_{\lambda_A,\lambda_B-\lambda_C}(\beta) \label{eq:helampjackson}\\
%A^{\rm JW}_{\lambda_A\lambda_B\lambda_C}&=&
%\sqrt{2J+1 \over 4\pi}H^{\rm JW}_{\lambda_B\lambda_C}
%e^{i\phi_A(\lambda_A-(\lambda_B-\lambda_C))}
%d^{J}_{\lambda_A,\lambda_B-\lambda_C}(\beta)\label{eq:helampJacobwick}
%\end{eqnarray}
%Since both of these amplitudes describe the same physics
%process it is tempting to equate the two amplitudes and
%determine the relation between $H^{Jack}_{\lambda_B\lambda_C}$
%and $H^{JW}_{\lambda_B\lambda_C}$. But this in not correct
%since, they don't in fact describe the same system! This is
%due to different phases that has been picked up by different
%rotations in the two conventions.
%
%The Euler angles describes how the coordinate system that particle
%A is at ret in is related to coordinate systems for the
%particles B and C. To derive the relation between the Jackson
%and Jacob-Wick conventions it is sufficient to study the
%simple case of $\theta_A=\phi_A=0$. First we consider the
%Jackson convention. For particle B the Euler angles will
%be $\alpha=0$, $\beta=0$, and $\gamma=0$. This means that
%the cordinate system in the rest frame of particle B has
%$z_B$ parallel to $z$ and that $x_B$ and $y_B$ are also
%parallel to the orixinal $x$ and $y$ axis. However, for
%particle B the angles are $\alpha=\pi$, $\beta=\pi$, and $\gamma=0$..
%This means that the new $z$-axis, $z_C$ is in the direction oposite
%to the original $z$ axis. The new $x$-axis, $x_C$ is parallel to the
%old and the new $y$ axis, $y_C$, is in the oposite direction
%to the old $y$-axis. This is illustrated in
%Figure~\ref{fig:helampjackson}.
%
%\begin{figure}
%\begin{center}
%\psfig{figure=helampjackson.eps,height=1.5in}
%\caption{The coordinate systems in the Jackson convention for the
%case of $\theta_A=\phi_A=0$.
%\label{fig:helampjackson}}
%\end{center}
%\end{figure}
%
%Next consider the Jacob-Wick convention. Here the difference it that
%$\gamma$ is taken to $-\alpha$. This will not affect the coordinate system for
%particle B since $\alpha=0$. However, for particle C $\alpha=\pi$
%so here there is an additional rotation of $\pi$ around the new
%$z$ axis. This means that the new $y$-axis $y_C$ is parallel to the
%old $y$ axis, and that $x_C$ is anti-parallel to original $x$
%axis, see Figure~\ref{fig:helampJacobwick}.
%
%\begin{figure}
%\begin{center}
%\psfig{figure=helampjacobwick.eps,height=1.5in}
%\caption{The coordinate systems in the Jacob-Wick convention for the
%case of $\theta_A=\phi_A=0$.
%\label{fig:helampJacobwick}}
%\end{center}
%\end{figure}
%
%Since the coordinate systems for the particles in the
%final states are not the same in the Jackson and the Jacob-Wick
%convention it is clear that the amplitudes in
%Eq.~\ref{eq:helampjackson} and Eq.~\ref{eq:helampJacobwick}
%don't describe the same reaction. But it is straight
%forward to relate the to conventions. In fact, all we have to do
%to compare the two conventions is to rotate particle C by
%an angle of $\pi$ around the $x_C$ axis. This rotation simply
%picks up a phase of $e^{i\pi\lambda_C}$ which allows us to relate
%the helicity ampitudes of the Jackson and the Jacob-Wick conventions
%according to
%\begin{equation}
%H^{\rm Jack}_{\lambda_B\lambda_C}=e^{i\pi\lambda_C}H^{\rm JW}_{\lambda_B\lambda_C}.
%\end{equation}
%This shows that there are phase differences between the two conventions.
%Note that this phase difference is easily observable in decays. E.g.
%in the decay of a scalar to two vector particles where each of the
%vectors decays to a pair of scalars this phase difference leads
%to angular distributions that has the wrong sign of the angle
%$\chi$\footnote{$\chi$ is the azimuthal angle between the decay planes
%of the two vector mesons.}
%if the phases are picked according to the wrong convention.
%
%Also care has to be taken when converting from the helicty
%basis to the partial wave basis using the Jacob Wick transformation.
%If the helicity ampitudes are given in the Jackson convention
%the Jacob Wick formula needs to be modified with the
%appropriate phases. (Actually, I still have to convince myself that
%the Jacob Wick transformation is correct for the Jacob-Wick convention
%for helicity amplitudes.)
%
%Now consider the case of non zero angles $\theta_A$ and $\phi_A$ for
%the direction, $\hat p$, of particle B. With a little thought
%it is easy to convince oneself that the direction of the $y_B$ is
%along $z\times\hat p$ an consequently that the direction of
%$y_B$ is $(z\times\hat p)\times \hat p$. Now applying this to
%particle C which is in the direction of $-\hat p$ we find that
%$x_C$ is parallel to $x_B$. This is just in agreement with what we
%saw in the special case studied above.
%
%In the Jacob-Wick convention an additional rotation of $-\phi_A$
%is applied around the $z_B$ as comapred to the Jackson conventions.
%For particle C this rotation is $-\pi-\phi_A$ around the $x_C$
%axis. This gives an relative rotation of $\pi$ as compared to the
%Jackson convention, which shows that $y_B$ and $y_C$ are
%parallel. Again this is consistent with the special case studied
%above.
%
%It is now simple to explain in words exactly what the helicity amplitude
%$A_{\lambda_A\lambda_B\lambda_C}$ means. (Note that we have suppresed
%the dependence on the Euler angles to simplify the notation.)
%Intuitively it is simply the amplitude for a state with spin
%projection $\lambda_A$ along the $z$ axis to decay to two
%particles with helicity $\lambda_B$ and $\lambda_C$ respectively.
%As we have noticed above this leaves important phases
%unspecified. But it is easy to specify these phase by noting that
%state of the final state particle is nothing but the canonical
%state $|J_B,m_z=\lambda_B\rangle$ and $|J_C,m_z=\lambda_C\rangle$
%repectively for particle B and C. These states are defined in the
%local coordinate system as specified by the Euler angels.
%
%\subsection{Example.}
%
%The have a concrete example to discuss, the decay
%$B\rightarrow D^{*+}D^{*-}$ with $D^{*+}\rightarrow D^0\pi^+$ and
%$D^{*-}\rightarrow \bar D^0\pi^-$ is considered.
%
%First we discuss how the coordinate systems are set up in the
%two different conventions. This is shown in
%figures~\ref{fig:jackson} and~\ref{fig:jacobwick}.
%In both conventions the z axis of the coordinate system that
%describes the decay of the $D^*$'s is along the direction of
%the flight of the $D^*$. But in the Jacob-Wick convention the
%direction of the y axises are parallel while in the Jackson convention the
%direction of the x axises are parallel.
%
%\begin{figure}
%\begin{center}
%\psfig{figure=jackson.eps,height=2.0in}
%\caption{The coordinate systems in the Jackson convention. The two
%x axises are parallel.
%\label{fig:jackson}}
%\end{center}
%\end{figure}
%
%\begin{figure}
%\begin{center}
%\psfig{figure=jacobwick.eps,height=2.0in}
%\caption{The coordinate systems in the Jacob-Wick convention. The two
%y axises are parallel.
%\label{fig:jacobwick}}
%\end{center}
%\end{figure}

\subsection{Explicit representations of SU(2)}

This section describes the explicit representations of SU(2) that
are used in the generator. As usual $\hbar=1$.

\subsubsection{$J=1/2$}

\begin{equation}
S_n={1\over 2}\gamma_0\gamma_5 n\!\!\!/.
\end{equation}

\subsubsection{$J=1$}

We will consider the representation of spin 1.
\begin{equation}
J_x=\left[\begin{array}{rrr}
          0 & 0 & 0  \\
          0 & 0 &-i  \\
          0 & i & 0  \\
          \end{array}\right],\quad
J_y=\left[\begin{array}{rrr}
          0 & 0 & i  \\
          0 & 0 & 0  \\
          -i& 0 & 0  \\
          \end{array}\right],\quad
J_z=\left[\begin{array}{rrr}
          0 &-i & 0  \\
          i & 0 & 0  \\
          0 & 0 & 0  \\
          \end{array}\right]
\end{equation}

From these explicit representations it is trivial to show that they
obey the standard commutation relations, e.g.,
\begin{equation}
[J_x,J_y]=iJ_z
\end{equation}
Further we find, as expected, that
\begin{equation}
J^2=J_x^2+J_y^2+J_z^2=2I
\end{equation}
such that $J^2=j(j+1)$ which shows that this in fact is a
representation of spin 1. The raising and lowering operators
are as usual given by

\begin{equation}
J_+=J_x+iJ_y=\left[\begin{array}{rrr}
          0 & 0 &-1  \\
          0 & 0 &-i  \\
          1 & i & 0  \\
          \end{array}\right],\quad
J_-=J_x-iJ_y\left[\begin{array}{rrr}
          0 & 0 & 1  \\
          0 & 0 &-i  \\
          -1& i & 0  \\
          \end{array}\right]
\end{equation}
It is also convenient to evaluate the expression for a finite rotation
\begin{equation}
R_z(\theta)=e^{-i\theta J_z}=\left[\begin{array}{ccc}
	\cos\theta & -\sin\theta & 0 \\
	\sin\theta &  \cos\theta & 0 \\
	 0         &  0          & 1 \\
	\end{array}\right].
\end{equation}
Of course we could have guessed the form of $R_z(\theta)$, but an
explicit evaluation of $e^{-i\theta J_z}$ is possible through
direct evaluation of the series expansion, but is more elegantly
done using Cayley-Hamilton's theorem.\footnote{Cayley-Hamilton's
theorem states that if $P_A(\lambda)=det(\lambda I-A)$ then $P_A(A)=0$
for any symmetric matrix $A$. This means that if $A$ has dimension
$n$ then $A^k$ can be written as a linear combination of $A^i$ for
$i<n$. In particular it can be shown that $f(A)=q(A)$ where $q$
is a polynomial of degree $<n$. The polynomial $q(A)$ is defined
by
\begin{equation}
{d^jf\over dz^j}(\lambda_k)={d^jq\over dz^j}(\lambda_k)
\end{equation}
where $\lambda_k$ are the eigen values of $A$, with multiplicity
$n_k$ and $j=0..n_k-1$.
}

The states
\begin{equation}
\epsilon_+={1\over\sqrt{2}}\left[\begin{array}{r}
          -1  \\
          -i  \\
          0  \\
          \end{array}\right],\quad
\epsilon_0=\left[\begin{array}{r}
          0  \\
          0  \\
          1  \\
          \end{array}\right],\quad
\epsilon_-={1\over\sqrt{2}}\left[\begin{array}{r}
          1  \\
          -i  \\
          0  \\
          \end{array}\right]
\label{eq:spinonestates}
\end{equation}

are easily seen to satisfy
\begin{equation}
J_z\epsilon_{\lambda}=\lambda\epsilon_{\lambda}
\end{equation}
and therefore form a helicity eigenstate basis for a particle
with $J=1$ moving in the direction of the positive $z$-axis.

\subsection{Projections of helicity amplitudes}

This section shows how the helicity amplitudes are related to the
invariant amplitudes. Consider the decay of a scalar to two
vector particles. Let the final states of the two vector particles
be denoted by $\epsilon^1_{s_1}$ and $\epsilon^2_{s_2}$ and $\vec p$
be the relative momentum of the two particles in the parents
rest frame. The amplitude for this process is then written as
\begin{equation}
A_{s_1s_2}=\epsilon^{1*}_{is_1}\epsilon^{2*}_{js_2}M_{ij}(\vec p)
\end{equation}
where $M_{ij}(p)$ is a rank 2 tensor as a function of the available
momenta in the process, i.e., a function of $\vec p$. The most
general form of M is given by
\begin{equation}
M_{ij}=a\delta_{ij}+b\epsilon_{ijk}p_k+cp_ip_j.
\end{equation}
The coefficients $a$, $b$, and $c$ are the invariant amplitudes, we
wand to relate them to helicity amplitudes. First we note that there
are three invariant amplitudes, this is the same as the number of
helicity amplitudes.

From Eq.~\ref{eq:helicityformula} the amplitude is given by
\begin{equation}
A_{\lambda_1\lambda_2}=\sqrt{2J+1\over 4\pi}H_{\lambda_1\lambda_2}
D^{*J}_{M\lambda_1-\lambda_2}(\phi,\theta,-\phi).
\end{equation}

When relating the helicity amplitudes to the invariant amplitudes
it is sufficient to look at one kinematic configuration, we chose
the simplest possible in which $\theta=\phi=0$. From the
definition of the $D$ function it is obvious that
$D^{*J}_{M\lambda_1-\lambda_2}(0,0,0)=\delta_{M,\lambda_1-\lambda_2}$.
This gives
\begin{equation}
H_{\lambda_1\lambda_2}=\sqrt{4\pi\over 2J+1}A_{\lambda_1\lambda_2}.
\end{equation}
This allows us to simply evaluate the helicity amplitudes from the
invariant amplitudes if we chose the states, $\epsilon^1$ and $\epsilon^2$,
to correspond to the states in the helicity formalism.
For $\epsilon^1$ we take the states given by~\ref{eq:spinonestates}
\begin{equation}
\epsilon^1_+={1\over\sqrt{2}}\left[\begin{array}{r}
          -1  \\
          -i  \\
          0  \\
          \end{array}\right],\quad
\epsilon^1_0=\left[\begin{array}{r}
          0  \\
          0  \\
          1  \\
          \end{array}\right],\quad
\epsilon^1_-={1\over\sqrt{2}}\left[\begin{array}{r}
          1  \\
          -i  \\
          0  \\
          \end{array}\right].
\end{equation}
The states for the second particle have to satisfy
$\chi_{0\lambda}=\Psi_{0-\lambda}$ which gives
\begin{equation}
\epsilon^2_+={1\over\sqrt{2}}\left[\begin{array}{r}
          1  \\
          -i  \\
          0  \\
          \end{array}\right],\quad
\epsilon^2_0=\left[\begin{array}{r}
          0  \\
          0  \\
          1  \\
          \end{array}\right],\quad
\epsilon^2_-={1\over\sqrt{2}}\left[\begin{array}{r}
          -1  \\
          -i  \\
          0  \\
          \end{array}\right].
\end{equation}
Note that this is consistent with Eq.~\ref{eq:newdef}.
Now it is straight forward to evaluate the helicity amplitudes
\begin{eqnarray}
 H_{++} & = & \sqrt{4\pi\over 3}(-a-ib), \\
 H_{00} & = & \sqrt{4\pi\over 3}(a+c),\\
 H_{--} & = & \sqrt{4\pi\over 3}(-a+ib).
\end{eqnarray}
These equations are easily inverted to give
\begin{eqnarray}
 a & = & -{1\over2}\sqrt{3\over 4\pi}(H_{++}+H_{--}), \\
 b & = & \phantom{-}{i\over2}\sqrt{3\over 4\pi}(H_{++}-H_{--}), \\
 c & = & \phantom{-{1\over2}}\sqrt{3\over 4\pi}(H_{00}+{1\over 2}(H_{++}+H_{--})), \\
\end{eqnarray}

\subsection{Jacob-Wick transformation}
\index{Jacob-Wick transformation}
\index{partial wave amplitudes}
\label{sect:jacobwick}

This section derives the relation between partial wave amplitudes
and helicity amplitudes.

The amplitude for a decay, given the partial wave amplitudes $M_{Ls}$,
is given by
$$A(\Omega,m1,m2,m3)=\sum_{L,s}C_{s_2s_3}(s\ m_s;m_2\ m_3)
                               C_{Ls}(s_1\ m_1;m_L\ m_s)Y^{m_L}_L(\Omega)
                               M_{Ls}.$$

\subsection{{\tt HELAMP} and {\tt PARTWAVE} model implementations}
\index{HELAMP}
\index{PARTWAVE}

The two models {\tt HELAMP} and {\tt PARTWAVE} implements generic
two body decays where the amplitudes are specified by the
helicity and partial wave amplitudes respectively. The partial
wave model uses the translation to helicity amplitudes as given in
Sect.~\ref{sect:jacobwick}. Henceforth, this section will focus
in the description of the evalution of helicity amplitudes.

 EvtGen uses a set of states, that are not the same as the helicity
states. In this section it is important to distinguish between these two
sets of states. The basis states used by EvtGen will be called
$|n\rangle$ and the helicity states will be denoted $|\lambda, s\rangle$,
or simply $|\lambda\rangle>$.

 We consider the decay of the form $A\rightarrow B C$ where the state
of the initial particle is given by $|n_A\rangle$ and the two particles
in the final state are labeled by $|n_B\rangle$ and $|n_C\rangle$.
For convenience we label the final state $|n_B, n_C\rangle=|n_B\rangle
\otimes |n_C\rangle$. Given this notation we write the amplitude that
we need to implement as
$$A^{B\rightarrow BC}_{n_A,n_B,n_C}=\langle n_B, n_C|H|n_A\rangle.$$
Using the completeness of the basis states we write
\begin{eqnarray}
A^{B\rightarrow BC}_{n_A,n_B,n_C}&=&\sum_{\lambda_A,\lambda_B,\lambda_C}\langle n_B, n_C|\lambda_B\rangle\langle\lambda_B|\lambda_C\rangle\langle\lambda_C|H|\lambda_A\rangle\langle\lambda_A|n_A\rangle\\
                                 &=&\sum_{\lambda_A,\lambda_B,\lambda_C}\langle n_B|\lambda_B\rangle \langle n_C|\lambda_C\rangle\langle\lambda_B|\langle\lambda_C|H|\lambda_A\rangle\langle\lambda_A|n_A\rangle\\
                                 &=&\sum_{\lambda_A,\lambda_B,\lambda_C}R^{*}_{n_B\lambda_B} R^{*}_{n_C\lambda_C}\langle\lambda_B|\langle\lambda_C|H|\lambda_A\rangle R_{\lambda_A n_A}
\end{eqnarray}
Where
\begin{eqnarray}
R_{n_A\lambda_A} & = & \langle \lambda_A | n_A \rangle \\
R_{n_B\lambda_B} & = & \langle \lambda_B | n_B \rangle \\
R_{n_C\lambda_C} & = & \langle \lambda_C | n_C \rangle
\end{eqnarray}