\chapter{Simple Machines}
\label{chap:compound}

In this chapter, we build and verify simple machines using the primitive machines from Chapter~\ref{chap:basic}, the operators developed in
Chapter~\ref{chap:combining}, and the tapes-lift from Chapter~\ref{chap:lifting}.  The machines in this chapter will be useful in the next chapter.
We do not use the alphabet-lift yet.  First we show how we prove correctness and termination of machines from now on.

When we prove $M \Realise R$ for a machine $M$ and its correctness relation $R$, we first find a relation $R'$ that $M$ realises.  We derive this
relation by applying the correctness lemmas of the control-flow operators, lifts, and concrete machines.  This process is mechanical and does in
general not depend on arbitrary choices (with a few exceptions).  The derived relation respects the ``structure'' of the machine.  For example, the
relation of a sequential composition is the relational composition of two relations.  Using the monotonicity Lemma~\ref{lem:Realise_monotone}, it
remains to show $R' \subseteq R$.  Because the structure of $R'$ respects the structure of $M$, the proof of the inclusion also follows its structure.
For example, the relation for a conditional is $(R_1 \at \true \circ R_2) \cup (R_1 \at \false \circ R_3)$.  From that it follows that we do a
case-distinction for both branches in the proof.  Note that we do not have to reason about machine states at all, because the correctness relations
are only relations between tapes and labels.

% So the main part of the proof is showing the inclusion.  The ``canonical relation'' of Section~\ref{sec:canonical} is for that reason not suited for
% the choice of $R'$.

When $M$ always terminates in constant time $k$, we show $M \RealiseIn{k} R$ instead.  Using the monotonicity Lemma~\ref{lem:RealiseIn_monotone}, we
can prove correctness and constant time at once.  For non-constant running time, we show $M \TerminatesIn T$ for a running time relation~$T$.  For
that, we use the dual approach and apply the anti-monotonicity Lemma~\ref{lem:TerminatesIn_monotone}.

\section{$\Nop$}
\label{sec:Nop}
\setCoqFilename{ProgrammingTuringMachines.TM.Compound.Multi}%

Using the tapes-lift (Definition~\ref{def:LiftTapes}) and $\MS{Null}$ (Definition~\ref{def:Null}), it is easy to define an $n$-tape machine
$\Nop : \TM_\Sigma^n$ that does nothing.  Asperti and Ricciotti~\cite{asperti2015} define this machine directly:
\begin{definition}[$\Nop$][Nop]
  $\Nop \defop \LiftTapes{\MS{Null}}{\nil}$.
\end{definition}
Note that because $\MS{Null}$ is a 0-tape machine, and $\Nop$ is supposed to be an $n$-tape machine, the index-vector must be the vector
$\nil : \Fin_n^0$.

\begin{lemma}[Correctness of $\Nop$][Nop_Sem]
  \label{lem:Nop_Sem}
  $\Nop \RealiseIn0 NopRel$ with $NopRel := \lambda t~t'.~t'=t$.
\end{lemma}
\begin{proof}
  We apply the monotonicity Lemma~\ref{lem:RealiseIn_monotone} of $\RealiseIn\cdot$, the correctness Lemma~\ref{lem:Null_Sem} of $\MS{Null}$, and the
  correctness Lemma~\ref{lem:LiftTapes_Realise} of the tapes-lift.  It remains to show:
  \[
    \left( \lambda t~t'.~ NullRel~t~t' \land \left(\forall i:\Fin_n.~i \notin \nil \rightarrow t'[i] = t[i] \right)\right)
    \subseteq NopRel
  \]
  Let $t,t' : \Tape_\Sigma^n$.  To show the equality $t'=t$ we show $t'[i]=t[i]$ for all $i:\Fin_n$.  This follows with the equality part of the
  relation $\LiftTapes{NullRel}{\nil}$, since $i \notin \nil$.
\end{proof}

Note that the correctness relation of $\Nop$ can also be expressed using the identity relation $Id$:
\[
  NopRel \equiv Id.
\]
We have the convention to define relations of concrete machines in $\lambda$-notation, i.e.\ not using relational operators.  Also note that the tape
$t'$ is, per convention, always on the left side of the equality.  These conventions make rewriting of tapes uniform; therefore, rewriting of tapes
can be automated in Coq.

\section{$\MS{WriteString}$}
\label{sec:WriteString}
\setCoqFilename{ProgrammingTuringMachines.TM.Compound.WriteString}%

The machine $\MS{WriteString}~d~str$ writes a fixed string $str:\List(\Sigma)$ in the direction $d$.  It is defined by recursion over the string:
\begin{definition}[$\MS{WriteString}$][WriteString]
  \begin{alignat*}{3}
    &\MS{WriteString}~d~&&(\nil)         &~:=~& \Nop \\
    &\MS{WriteString}~d~&&(s \cons \nil) &~:=~& \MS{Write}~s \\
    &\MS{WriteString}~d~&&(s \cons str') &~:=~& \MS{WriteMove}~s~d \Seq \MS{WriteString}~d~str'.
  \end{alignat*}
\end{definition}

Note that this is our only machine we define per recursion.  The way we prove correctness in constant time (depending on the length of $str$) is still
the same.

The machine writes all symbols of the string $str$ to the tape and moves in the tape in direction $d$ after each (but the last) symbol.  When it
terminates, the head of the tape is under the last written symbol, which is the last symbol of $str$.  It terminates in constant time, after
$2\cdot\length{str}-1$ steps.

The derived relation for $\MS{WriteString}$ is also defined per recursion over the string:
\begin{lemma}[][WriteString_fix_Sem]
  $\MS{WriteString}~d~str \RealiseIn{2 \cdot \length{str} - 1} R'~d~str$ with
  \begin{alignat*}{3}
    &\MS{R'}~d~&&(\nil        ) &~:=~& NopRel \\
    &\MS{R'}~d~&&(s \cons \nil) &~:=~& DoActRel(\Some{s}, \MS{N}) \\
    &\MS{R'}~d~&&(s \cons str') &~:=~& DoActRel(\Some{s}, d) \circ \MS{R'}~d~str'.
  \end{alignat*}
\end{lemma}
\begin{proof}
  By induction on $str:\List(\Sigma)$, using the monotonicity Lemma~\ref{lem:RealiseIn_monotone}, the correctness of $\Nop$ (Lemma~\ref{lem:Nop_Sem}),
  the correctness of $\MS{Write}$ and $\MS{WriteMove}$ (which are defined using $\MS{DoAct}$; Lemma~\ref{lem:DoAct_Sem}), and correctness of
  sequential composition for constant time (Lemma~\ref{lem:Seq_RealiseIn}).
\end{proof}

We define the actual relation of $\MS{WriteString}$ in terms of a function on tapes that is also defined by recursion over $str$:
\begin{lemma}[Correctness of $\MS{WriteString}$][WriteString_Sem]
  \label{lem:WriteString_Sem}
  Let $d:\Move$ and $str:\List(\Sigma)$.
  \[ \MS{WriteString}~d~str \RealiseIn{2\cdot\length{str}-1} WriteStringRel~d~str \]
  with
  $WriteStringRel~d~str := \lambda t~t'.~t' = writeStringFun~d~t~str$ and
  \begin{alignat*}{3}
    &writeStringFun~d~t~&&(\nil        ) &~:=~& t \\
    &writeStringFun~d~t~&&(s \cons \nil) &~:=~& \MS{wr}~t~(\Some{s}) \\
    &writeStringFun~d~t~&&(s \cons str') &~:=~& writeStringFun~d~\bigl(\MS{doAct}~t~(\Some{s}, d)\bigr)~str'
  \end{alignat*}
\end{lemma}
\begin{proof}
  We apply the monotonicity Lemma~\ref{lem:RealiseIn_monotone} and have to show:
  \[
    R'~d~str \subseteq WriteStringRel~d~str
  \]
  This can be shown by induction on $str$.
\end{proof}

Note that we could as well use the $\MS{Mirror}$ operator instead of parametrising the machine $\MS{WritingString}$ over the direction.  In this
particular example the parametrising approach seems to be easier.

\section{$\MS{MovePar}$}
\label{sec:MovePar}
\setCoqFilename{ProgrammingTuringMachines.TM.Compound.Multi}%

The two-tape machine $\MS{MovePar}~d_0~d_1$ combines two $\MS{Move}$ machines.  It first moves the $0$th tape in direction $d_0$ and after that the
$1$st tape in direction $d_1$.\footnote{To avoid confusion with zero-based indices used throughout this thesis, we write ``the $0$th or $1$st tape'',
  instead of ``the first or second tape.''}
\begin{definition}[$\MS{MovePar}$][MovePar]
  \label{def:MovePar}
  $\MS{MovePar}~d_0~d_1 \defop \LiftTapes{(\MS{Move}~d_0)}{\Vector{0}} \Seq \LiftTapes{(\MS{Move}~d_1)}{\Vector{1}}$.
\end{definition}
\begin{lemma}[Correctness of $\MS{MovePar}$][MovePar_Sem]
  \label{lem:MovePar_Sem}
  $\MS{MovePar}~d_0~d_1 \RealiseIn3 MoveParRel~d_0~d_1$ with
  \[
    MoveParRel~d_0~d_1 := \lambda t~t'.~t'[0]=\MS{mv}~d_0~t[0] ~\land~ t'[1]=\MS{mv}~d_1~t[1]
  \]
\end{lemma}
\begin{proof}
  We have to show:
  \[
    \LiftTapes{(DoActRel(\None,d_0))}{\Vector{0}} \circ
    \LiftTapes{(DoActRel(\None,d_1))}{\Vector{1}} \subseteq
    MovePairRel~d_0~d_1
  \]
  We assume tape vectors $t, t', t'' : \Tape_\Sigma^2$, such that $(\LiftTapes{(DoActRel(\None,d_0))}{\Vector{0}})~t~t'$ and \\
  $(\LiftTapes{(DoActRel(\None,d_1))}{\Vector{1}})~t'~t''$.  We have to show $t''[0]=\MS{mv}~d_0~t[0]$ and $t''[1]=\MS{mv}~d_1~t[1]$.  By definition,
  we know $t'[0]=\MS{mv}~d_0~t[0]$ and $t'[1]=t[1]$ (because $1 \notin \Vector{0}$).  We also know $t''[1]=\MS{mv}~d_1~t'[1]$ and $t''[0]=t'[0]$
  (because $0 \notin \Vector{1}$).  The goal follows trivially.
\end{proof}
Note that this kind of proof is very mechanical: We only need to unfold the relations and rewrite tapes.  Indeed, these steps are automated in Coq.
Thus, we also do not present more proofs of this kind on paper.

\section{$\MS{CopySymbols}$}
\label{sec:CopySymbols}
\setCoqFilename{ProgrammingTuringMachines.TM.Compound.CopySymbols}%

The machine $\MS{CopySymbols}~h : \TM_\Sigma^2$, where $h:\Sigma\to\Bool$, is a compound machine involving a $\While$-loop.  It reads a symbol on tape
$0$, writes it to tape $1$, and moves both tapes to right, until the read symbol satisfies $h$.  If there was no current symbol on tape $0$, it also
terminates.

We first define the machine for the step.  Since we want to apply the $\While$ operator on the step machine, it must be labelled over
$\Option(\Unit)$.  $\Some\unit$ means to break out of the loop and $\None$ means to repeat the loop.
\begin{definition}[$\MS{CopySymbolsStep}$][CopySymbols_Step]
  \label{CopySymbols_Step}
\begin{lstlisting}[style=semicoqstyle]
$\MS{CopySymbolsStep}~h :=$
  Switch$(\LiftTapes{\MS{Read}}{\Vector{0}})$
       $(\lambda (s:\Option(\Sigma)).$
          $\MS{match}~s$
          [$\Some{x}$=>
            $\MS{if}~h(x)$
            $\pthen$ $\Return{\bigl(\LiftTapes{(\MS{Write}~x)}{\Vector{1}}\bigr)}{\Some\unit}$
            $\pelse$ $\Return{\bigl(\LiftTapes{(\MS{Write}~x)}{\Vector{1}} \Seq \MS{MovePar}~\MS{R}~\MS{R}\bigr)}{\None}$
          |$\None$ => $\Return{\Nop}{\Some\unit}$
          ])
\end{lstlisting}
\end{definition}

Note that ``$\MS{match}~[~\cdots~]$'' denotes pattern matching our type theory.

\begin{lemma}[Correctness of $\MS{CopySymbolsStep}$][CopySymbols_Step_Sem]
  \label{lem:CopySymbols_Step_Sem}
  ~
  \[
    \MS{CopySymbolsStep} \RealiseIn{7} CopySymbolsStepRel
  \]
  with
  \small
  \begin{align*}
    &CopySymbolsStepRel := \lambda t~(l, t').~\\
    &\quad\begin{cases}
      t'[0] = t[0]           \land t'[1]=\MS{wr}~t[1]~\Some{x}              \land l=\Some\unit & \MS{current}~t[0]=\Some{x} \land       h(x) \\
      t'[0] = \MS{mv}~\MS{R}~t[0] \land t'[1]=\MS{doAct}~t[1]~(\Some{x}, \MS{R}) \land l=\None & \MS{current}~t[0]=\Some{x} \land \lnot h(x) \\
      t' = t \land l=\Some\unit                                                                & \text{else}
    \end{cases}
  \end{align*}
\end{lemma}
\begin{proof}
  Mechanical, with case-analysis over $\MS{current}~t[0]$.
\end{proof}

We define $\MS{CopySymbol}$ by applying the $\While$ operator to $\MS{CopySymbolsStep}$:
\begin{definition}[$\MS{CopySymbols}$][CopySymbols]
  \label{def:CopySymbols}
  $\MS{CopySymbols}~h := \While(\MS{CopySymbolsStep}~h)$.
\end{definition}

The correctness of $\MS{CopySymbols}$ can be expressed using a recursive function on tapes:
\begin{lemma}[Correctness of $\MS{CopySymbols}$][CopySymbols_Realise]
  \label{lem:CopySymbols_Realise}
  $\MS{CopySymbols}~h \Realise CopySymbolsRel~h$
  with $CopySymbolsRel~h := \lambda t~t'.~t' = copySymbolsFun~h~t$ and
  {
    \small
    \begin{align*}
      &copySymbolsFun~h~t :=\\
      &\quad\begin{cases}
        \Vector{t[0];~ \MS{wr}~t[1]~\Some{x}}                                         & \MS{current}~t[0]=\Some{x} \land h(x) \\
        copySymbolsFun~h~\Vector{\MS{mv}~R~t[0];~ \MS{doAct}~t[1]~(\Some{x}, \MS{R})} & \MS{current}~t[0]=\Some{x} \land \lnot h(x) \\
        t                                                                             & \MS{current}~t[0]=\None
      \end{cases}
    \end{align*}
  }
  Note that the function $copySymbolsFun$ is not structural recursive.  It terminates because tapes have only finitely many symbols.
\end{lemma}
\begin{proof}
  To show: $WhileRel~CopySymbolsStepRel \subseteq CopySymbolsRel$.  By $\While$-induction (Lemma~\ref{lem:WhileInduction}).
\end{proof}

We observe that the running time of $\MS{CopySymbols}$ only depends on the $0$th tape.  Therefore, we define a function
$copySymbolsSteps : \Tape_\Sigma \to \Nat$ that overestimates the number of steps needed for the loop, depending on the $0$th tape.  Note that
$\While$ requires one additional step for each repeat of the loop.
\begin{lemma}[Running time of $\MS{CopySymbols}$][CopySymbols_Terminates]
  $\MS{CopySymbols} \TerminatesIn CopySymbolsT$ with \\
  $CopySymbolsT := \lambda t~k.~copySymbolsSteps(t) \leq k$ and
  \begin{align*}
    &copySymbolsSteps (t) := \\
    &\quad\begin{cases}
      8 + copySymbolsSteps(\MS{mv}~\MS{R}~t) & \MS{current}~t=\Some{x} \land \lnot h(x) \\
      8                                      & \text{otherwise}
    \end{cases}
  \end{align*}
\end{lemma}
\begin{proof}
  We have to show $CopySymbolsT \subseteq WhileT~CopySymbolsStepRel~(\lambda \_~k.~7 \leq k)$, using the co-induction
  Lemma~\ref{lem:WhileCoInduction}.  Let $copySymbolsSteps~t[0] \leq k$.  We choose $k_1 := 7$.  We have two cases.
  \begin{enumerate}
  \item We assume $CopySymbolsStepRel~t~(\Some\unit, t')$.  Therefore, we know that either $\MS{current}~t[0]=\Some{x}$ with $h(x)=\true$, or
    $\MS{current}~t[0]=\None$.  In both cases, we have $copySymbolsSteps~t[0] = 8$.  Thus, we have:
    $$k_1 \leq copySymbolsSteps~t[0] = 8 \leq k$$
  \item We assume $CopySymbolsStepRel~t~(\None, t')$.  Therefore, we have $\MS{current}~t[0]=\Some{x}$ with $h(x)=\false$, and
    $t'[0]=\MS{mv}~\MS{R}~t[0]$.  Then, we have:
    % \[ ... \] doesn't work here. $$ ... $$ doesn't place \qed at the right spot.
    \begin{equation*}
      1+k_1+copySymbolsSteps~t'[0] = copySymbolsSteps~t[0] \leq k
    \end{equation*}
  \end{enumerate}
\end{proof}
% Note that we see in the proof that we could replace the $8$s in the non-recursive parts of the running time functions with $7$s.

Using the $\MS{Mirror}$ operator, we can define a machine $\MS{CopySymbolsL}$ that copies and goes to the left instead.  We also have to ``mirror''
the correctness relations and their respective functions.  We do not repeat the definitions here.
\begin{definition}[$\MS{CopySymbolsL}$][CopySymbols_L]
  $\MS{CopySymbolsL}~h := \MS{Mirror}(\MS{CopySymbols}~h).$
\end{definition}

\section{$\MS{MoveToSymbol}$}
\label{sec:MoveToSymbol}
\setCoqFilename{ProgrammingTuringMachines.TM.Compound.MoveToSymbol}%

\enlargethispage{0.5cm}

We can define a machine $\MS{MoveToSymbol}~h~f : \TM_\Sigma^1$, where $h:\Sigma\to\Bool$ and $f:\Sigma\to\Sigma$.  This machine behaves similar as
$\MS{CopySymbols}~h$.  Instead of copying the symbols from one tape to another tape, it ``translates'' the symbols it reads, until it reads a symbol
that satisfies the boolean predicate $h$.  We leave out the correctness and running time statements, as they can be derived from the statements about
$\MS{CopySymbols}$ above.

\begin{definition}[$\MS{MoveToSymbol}$][MoveToSymbol]
  ~
\begin{lstlisting}[style=semicoqstyle]
$\MS{MoveToSymbolStep}~h~f :=$
  Switch$(\MS{Read})$
       $(\lambda (s:\Option(\Sigma)).~\MS{match}~s$
          [$\Some{x}$=>
            if $h(x)$
            $\pthen$ $\Return{\bigl(\MS{Write}~(f~x)       \bigr)}{\Some\unit}$
            $\pelse$ $\Return{\bigl(\MS{WriteMove}~(f~x)~R \bigr)}{\None}$
          |$\None$ => $\Return{\Nop}{\Some\unit}$
          ])
\end{lstlisting}
  \begin{align*}
    \MS{MoveToSymbol }~h~f &:= \While(\MS{MoveToSymbolStep}~h~f) \\
    \MS{MoveToSymbolL}~h~f &:= \MS{Mirror}(\MS{MoveToSymbol}~h~f)
  \end{align*}
\end{definition}

%%% Local Variables:
%%% TeX-master: "thesis"
%%% End:


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

\subsection{Polarization of synchrotron radiation}

\marginpar{Saturday\\ 2020-8-29, \\ compiled \\ \today}

Measuring polarization is in general difficult, but still it is important to be able to provide an estimate of how much radiation is actually polarized.

In order to describe synchrotron radiation we will need some reference unit vectors. Let us define \(\vec{\epsilon}_{\perp}\) and \(\vec{\epsilon}_{\parallel}\) such that, given the observation direction \(\vec{n}\) and the magnetic field \(\vec{B}\), \(\vec{\epsilon}_\perp\) is perpendicular to both, while \(\vec{\epsilon}_\parallel\) is perpendicular to \(\vec{n}\) only, while being in the plane defined by \(\vec{n}\) and \(\vec{B}\).

These two unit vectors define a basis for the radiation seen in the direction \(\vec{n}\), since as we recall the polarization of electromagnetic radiation is always transverse.

It can be shown that the power spectrum emitted in each polarization is given by
%
\begin{align}
\eval{\frac{ \dd{w}}{ \dd{t} \dd{\omega }}}_{\perp} &= \frac{\sqrt{3} q^3 B \sin \alpha }{4 \pi m c^2} \qty(F + G) \\
\eval{\frac{ \dd{w}}{ \dd{t} \dd{\omega }}}_{\parallel} &= \frac{\sqrt{3} q^3 B \sin \alpha }{4 \pi m c^2} \qty(F - G)
\,,
\end{align}
%
where \(F\) is the function of \(\omega / \omega _c\) we defined earlier,
%
\begin{align}
F \qty(\frac{\omega }{\omega _c}) = \frac{\omega}{\omega _c} \int_{\omega / \omega _c}^{\infty } K_{5/3} (z) \dd{z}
\,,
\end{align}
%
while the new function \(G\) is defined by
%
\begin{align}
G \qty(\frac{\omega }{\omega _c}) = \frac{\omega}{\omega _c} K_{2/3} \qty( \frac{\omega}{\omega _c})
\,.
\end{align}

The total emitted power per unit frequency is given by the sum of the two contributions in each polarization; so the terms containing \(G\) simplify, and we are left with the \(F\) term only, the result we found earlier.

The polarization fraction at each frequency for a single electron will be given by
%
\begin{align}
\Pi (\omega )
= \frac{P_\perp (\omega ) - P_\parallel (\omega )}{P_\perp (\omega ) + P_\parallel (\omega )}
= \frac{G( \omega / \omega _c) }{F(\omega / \omega _c)}
\,,
\end{align}
%
while the polarization fraction for a whole family of electrons whose energies are distributed according to a powerlaw will be given by the ratio of the integrals of \(G\) and \(F\) weighted by the electron distributions:
%
\begin{align}
\Pi &= \frac{\int_0^{\infty } G (\omega / \omega _c) \gamma^{-P} \dd{\gamma }}{\int_0^{\infty } F(\omega  / \omega _c) \gamma^{-P} \dd{\gamma }}  \\
&= \frac{\int_0^{\infty } G (x) \gamma^{-P} \dd{\gamma }}{\int_0^{\infty } F(x) \gamma^{-P} \dd{\gamma }}
\,,
\end{align}
%
where we must be careful, since \(x\) is a function of \(\gamma \) in the integral. Specifically, \(x = \omega / \omega _c \sim 1/ \gamma^2\), so \(\gamma \sim x^{-1/2}\), therefore \(\dd{\gamma } \propto -1/2 x^{-3/2} \dd{x}\). This yields, up to multiplicative factors which cancel out in the ratio:
%
\begin{align}
\Pi = \frac{\int_0^{\infty } G(x) x^{(P-3) / 2} \dd{x}}{\int_0^{\infty } F(x) x^{(P-3) / 2} \dd{x}}
\,.
\end{align}

These integrals of special functions are evaluated in the literature, we have general explicit expressions for expressions like \(\int x^{\mu } F(x) \dd{x}\) and similarly for \(G\).

Substituting these in, we find
%
\begin{align}
\Pi = \frac{1 + P}{P + 7/3}
\,.
\end{align}

This is always \(<1\) as it should be, however with very steep powerlaws (high \(P\)) we can reach values of \(\Pi \) which are arbitrarily close to 1.

If, on the other hand, we are only considering one electron, we can compute the \emph{frequency-integrated} polarization fraction
%
\begin{align}
\Pi
= \frac{\int_0^{\infty } G(x) \dd{\omega }}{\int_0^{\infty } F(x) \dd{\omega }}
= \frac{\int_0^{\infty } G(x) \dd{x}}{\int_0^{\infty } F(x) \dd{x }}
\,,
\end{align}
%
which coincides with the polarization fraction from a population of electrons if we take \(P = 3\). Therefore, we find \(\Pi = (1+3) / (3 + 7/3) = 3/4\).

\section{Einstein coefficients}

In order to understand what the absorption from synchrotron radiation looks like we need to take a step back and consider the Einstein coefficients.

Let us reconsider Kirkhoff's law: if emitters and absorbers are in thermal equilibrium, then the following relation holds:
%
\begin{align}
j_\nu = \alpha _\nu B_\nu
\,.
\end{align}

This law holds at the macroscopic level: however, the process giving rise to it have a microscopic origin, so we should be able to give a microscopic version of this law.

Let us consider an atom with two energy levels, at \(E\) and \(E + h \nu_0\) respectively.
In the population these will have a different statistical weight: let us call these weights \(g_1 \) and \(g_2 \).

Einstein identified the three main processes which can occur when such an atom interacts with radiation:
\begin{enumerate}
    \item spontaneous emission, where the system starts off in the higher energy level and decays to the lower one, emitting a photon of energy \(h \nu_0 \). This can happen regardless of the presence of an external radiation field.
    The Einstein \(A\) coefficient describes this: \(A_{21} \) is the transition probability per unit time connected to this process.
    \item Absorption, where the atom starts off in the lower energy state and absorbs a photon of energy \(h \nu_0 \), going to the higher energy level.
    It should be stressed that the absorption is not actually monochromatic; because of several effects it is described by a distribution \(\phi (\nu )\) which is sharply peaked around \(\nu_0\), and which is normalized so that \(\int \phi (\nu ) \dd{\nu } = 1\).
    Then, the absorption probability per unit time is given by
    %
    \begin{align}
    B_{12} \int_0^{\infty } J_\nu \phi (\nu ) \dd{\nu }
    \,,
    \end{align}
    %
    where \(J_\nu \) is the mean intensity of the external radiation field.
    \item Stimulated emission, which is a consequence of the quantum nature of light. Planck's law only holds if this is included. This corresponds to the fact that the emission probability is enhanced by the presence of a radiation field. This is similar to how absorption occurs, in that the transition probability per unit time is
    %
    \begin{align}
    B_{21} \int_0^{\infty } J_\nu \phi (\nu ) \dd{\nu }
    \,.
    \end{align}
\end{enumerate}

Let us consider a system of many two-level atoms, whose number density is \(n\). Some of them will be in level 1 and some will be in level 2; let us call the corresponding number densities \(n_1 \) and \(n_2 \).

If we are in thermodynamic equilibrium, then the transition rate from 1 to 2 must equal that from 2 to 1. This can be written as
%
\begin{align}
\underbrace{n_1 B_{12} \overline{J}}_{\text{absorption}} &= \underbrace{n_2 A_{21}}_{\text{emission}} + \underbrace{n_2 B_{21} \overline{J}}_{\text{stimulated emission}}  \\
\overline{J} &= \int_0^{\infty } J_\nu \phi (\nu ) \dd{\nu }
\,.
\end{align}

We can solve this equation for \(\overline{J}\): it comes out to be
%
\begin{align}
\overline{J} = \frac{A_{21} / B_{21} }{ (n_1 / n_2 ) (B_{12} / B_{21} ) - 1}
\,.
\end{align}

Since we know that the system is in thermodynamic equilibrium, we can also write that the ratio of the number densities of the two populations will be
%
\begin{align}
\frac{n_1}{n_2 } = \frac{g_1  \exp( - E / k_B T)}{g_2 \exp(- E / k_B T - h \nu_0 / k_B T)} = \frac{g_1}{g_2 } \exp( \frac{h \nu_0}{k_B T})
\,.
\end{align}

Inserting this in the previous relation we find
%
\begin{align}
\overline{J} = \frac{A_{12} / B_{21} }{(g_1 B_{12} /  g_2 B_{21} ) \exp(h \nu_0 / k_B T) - 1 }
\,.
\end{align}

Also, we know that the mean intensity \(J_\nu \) will be equal to the Planck function \(B_\nu \). The Planckian is quite slowly varying while \(\phi (\nu )\) is very peaked around \(\nu_0 \): therefore, it is safe to say that
%
\begin{align}
\overline{J} = \int_0^{\infty } B_\nu \phi (\nu ) \dd{\nu } \approx B_{\nu_0 }
\,,
\end{align}
%
since \(\phi (\nu )\) is normalized. Equating this to the expression we found above, we get
%
\begin{align}
\overline{J} =  B_{\nu_0 } = \frac{2 h \nu^3}{c^2} \frac{1}{\exp( \frac{h \nu_0 }{k_B T }) - 1} &= \frac{A_{12} / B_{21} }{(g_1 B_{12} /  g_2 B_{21} ) \exp(h \nu_0 / k_B T) - 1 }
\,.
\end{align}

This must hold for any temperature \(T\), so we can identify the terms in the two similar expressions: this tells us that
%
\begin{align}
\frac{g_1 B_{12} }{g_2 B_{21} } = 1
\qquad \text{and} \qquad
\frac{2 h \nu^3}{c^2} = \frac{A_{12} }{B_{21} }
\,.
\end{align}

These are called the \textbf{detailed balance relations}. They must be satisfied even if the system is outside of thermal equilibrium, since the temperature \(T\) does not appear in them.

\todo[inline]{What? How? Why? We used the hypothesis of thermal equilibrium a lot\dots}

\subsubsection{The emission and absorption coefficients}

Let us assume that radiation which is emitted in the transition \(2 \to 1\) has the same frequency as the radiation which is absorbed in the transition \(1 \to 2\), so that both processes are be characterized by the function \(\phi (\nu )\), like we assumed before.

With this, we can express the energy emitted per unit volume, solid angle, frequency and time as
%
\begin{align}
j_\nu \dd{V} \dd{t} \dd{\Omega } \dd{\nu } &= \frac{h \nu_0}{4 \pi } \phi (\nu ) n_2 A_{21} \dd{\Omega } \dd{V} \dd{t} \dd{\nu }  \\
j_\nu &= \frac{h \nu_0}{4 \pi } \phi (\nu ) n_2 A_{21}
\,.
\end{align}

For absorption, we can apply a similar line of reasoning:
the energy absorbed per unit volume and time is
%
\begin{align}
\dd{w}_\nu =
\dd{V} \dd{t} h \nu_0 n_1 B_{12} \frac{1}{4 \pi } \int \dd{\Omega } \dd{\nu } I_\nu \phi (\nu )
\,,
\end{align}
%
which we can specify to the energy taken out of the beam in the specific frequency and solid angle unit range by removing the integral.
If we write the volume element as \(\dd{V} = \dd{A} \dd{s}\), where \(\dd{s}\) is the distance travelled along the path of the radiation, and if we remember the radiative absorption law \(\dd{I_\nu } = - \alpha _\nu I_\nu \dd{s}\), we can write
%
\begin{align}
- \dd{I_\nu } = -\frac{ \dd{w}_\nu }{ \dd{A} \dd{t} \dd{\Omega } \dd{\nu }}
&= \underbrace{h \nu_0 n_1 \frac{B_{12}}{4 \pi } \phi(\nu )}_{\alpha _\nu } I_\nu  \dd{s} \\
\alpha_\nu &= \frac{h \nu_0  }{4 \pi } n_1 B_{12} \phi (\nu )
\,.
\end{align}

We could also write \(h \nu\) instead of \(h \nu_0\) if we were to approximate \(\phi (\nu )\)  as a delta function \(\phi (\nu ) = \delta (\nu - \nu_0 )\).

Now, since stimulated emission depends on \(\overline{J}\), it is convenient to treat it as a kind of ``negative absorption'': with the same steps as before we find that its coefficient is
%
\begin{align}
\alpha_\nu^{(s)} = - \frac{h \nu_0 }{4 \pi } n_2 B_{21} \phi (\nu )
\,.
\end{align}

The total absorption coefficient will then be the sum of these:
%
\begin{align}
\alpha _\nu = \frac{h \nu_0 }{4 \pi } \phi (\nu ) \qty(n_1 B_{12} - n_2 B_{21} )
\,.
\end{align}

In general, when we talk about absorption we always mean absorption minus stimulated emission.

\end{document}


%!TEX root = ../Main.tex
In this section, the basics of the tight-binding approximation for electron transport will be explained. This motivates the use of numerical routines using NumPy.
\subsection{Ballistic quantum transport}
As graphene is a two dimensional material that consists of carbon atoms arranged in a hexagonal pattern. Features in such a material can approach nano meter and sub nano meter scales. Because of the small scale the electrical properties of the material is vastly different from normal materials. Usually when describing the electrical properties of a material, drift-diffusion current models are used. They describe electric charges per area and current per area. This is usually a good description in systems where electron-electron and electron-atom scattering frequently occurs. The distance an electron travels before such an event is called its \textit{mean free path}. However, in small systems as those of NPG-devices, the mean free path can be longer than the system itself. Experiments have shown that electrons can move ballistically in graphene\cite{mayorov_micrometer-scale_2011,baringhaus_exceptional_2014}, that is, without phonon scattering and even at room temperature. Therefore, we model electron transport in NPG using the \textit{ballistic model}. In this model the electrons move through the material as waves. The fact that the electrons moves as waves will prove important later on because it gives rise to \textit{Quantum Interference} which can be exploited as a tool when engineering graphene-based devices\cite{markussen_relation_2010}. Furthermore the model looks at only one electron at a time in the presence of an electron gas. The ballistic model has been used with big success for regular graphene and it seems that it also gives a good approximation for NPGs.
\subsection{\mathinhead{\pi}{\pi}-orbitals and \mathinhead{\pi}{\pi}-electrons}
When modelling the electron transport in graphene one needs to address the orbital structure of carbon lattices. The orbital structure is exactly what motivate the use of tight-binding approximation and Green's functions. The two concepts of tight-binding approximation and Green's functions will be elaborated further in the coming sections.
In its basic form graphene can be divided into rings of carbon atoms as shown in \cref{ring}. In the (\(x,y\))-plane the carbon atoms are bound in \(sp^2\) orbitals as shown in \cref{sp2}.
\begin{figure}[ht]
	\centering
	\begin{subfigure}[b]{0.3\textwidth}
		\begin{tikzpicture}
			\chemfig{C*6(-C-C-C-C-C-)}
		\end{tikzpicture}
		\caption{Graphene lattices consists of hexagonal arrangements of carbon atoms.}\label{ring}
	\end{subfigure}
	~
	\begin{subfigure}[b]{0.3\textwidth}
		\centering
		\resizebox{\textwidth}{!}{
			\begin{tikzpicture}
				\node (x) at (-1,-3) {x};
				\node (y) at (-2,-2) {y};
				\draw[->] (-2,-3) -- (x);
				\draw[->] (-2,-3) -- (y);
				\satom[name=C, color=blue, pos={(0,0)}]{
					blue/60/north east/2/1,
					blue/180/west/1,
					blue/300/south east/2/1
				}
				\satom[name=C, color=blue, pos={(1,1.4)}]{
					blue/0/east/2/1,
					blue/120/north west/1,
					blue/240/south west/2/1
				}
				\satom[name=C, color=blue, pos={(2.74,1.4)}]{
					blue/60/north east/1,
					blue/180/west/2/1,
					blue/300/south east/2/1
				}
				\satom[name=C, color=blue, pos={(3.74,0)}]{
					blue/0/east/1,
					blue/120/north west/2/1,
					blue/240/south west/2/1
				}
				\satom[name=C, color=blue, pos={(2.74,-1.4)}]{
					blue/60/north east/2/1,
					blue/180/west/2/1,
					blue/300/south east/1
				}
				\satom[name=C, color=blue, pos={(1,-1.4)}]{
					blue/0/east/2/1,
					blue/120/north west/2/1,
					blue/240/south west/1
				}
			\end{tikzpicture}}
		\caption{Carbon atoms in a hexagonal lattice are \(sp^2\) hybridised in the (\(x,y\))-plane.}\label{sp2}
	\end{subfigure}
	\caption{Benzene ring and its \(sp^2\) hybridised orbitals.}\label{Benz}
\end{figure}
This hybridisation lock all but one valence electron for the carbon atoms. These electrons exists in a p-orbital in the \(z\)-direction.
\cref{p} shows the valence orbitals of carbon.
\begin{figure}[ht]
	\centering
	\begin{tikzpicture}
		\orbital[pos = {(0,3)}] {s}
		\node[above] at (0,4) {s};
		\orbital[pos = {(2,3)}]{px}
		\node[above] at (2,4) {p$_x$};
		\orbital[pos = {(4,3)}]{py}
		\node[above] at (4,4) {p$_y$};
		\orbital[pos = {(6,3)}]{pz}
		\node[above] at (6,4) {p$_z$};
	\end{tikzpicture}
	\caption{The valence orbitals of carbon.}
	\label{p}
\end{figure}
The last electron in the p\(_z\) orbital does not mix with the tightly bound s, p\(_x\) and p\(_y\) electrons and moves freely. Thus these electrons have higher energies compared to the \(sp^2\) electrons and occupy states at the Fermi level. These electrons dominates transport in the graphene lattice. The p\(_z\) orbital is also known as the \(\pi\)-orbital and as such the electron lying there is called a \(\pi\)-electron. Through a carbon lattice the \(\pi\)-electrons will travel through \(\pi\)-orbitals. For a benzene ring the \(\pi\)-electrons at the highest occupied molecular state will travel through the \(\pi\)-orbitals switching sign as they travel as shown in \cref{sign}.
\begin{figure}[ht]
	\centering
	\pgfdeclarelayer{background}
	\pgfdeclarelayer{middle}
	\pgfdeclarelayer{foreground}
	\pgfsetlayers{background,middle,main,foreground}
	\begin{tikzpicture}
		\begin{pgfonlayer}{background}
			\orbital[pos = {(6,6)}]{-pz}
			\node[above] at (6,7) {-p$_\pi$};
			\orbital[pos = {(4,6)}]{pz}
			\node[above] at (4,7) {p$_\pi$};
			\draw[dashed, very thick] (6,6) -- (4,6);
			\draw[dashed, very thick] (7,4.73) -- (6,6);
			\draw[dashed, very thick] (4,6) -- (3,4.73);
		\end{pgfonlayer}
		\orbital[pos = {(7,4.73)}]{pz}
		\node[above] at (7,5.73) {p$_\pi$};
		\orbital[pos = {(3,4.73)}]{-pz}
		\node[above] at (3,5.73) {-p$_\pi$};
		\begin{pgfonlayer}{foreground}
			\orbital[pos = {(4,3.46)}]{pz}
			\node[above] at (4,4.46) {p$_\pi$};
			\orbital[pos = {(6,3.46)}]{-pz}
			\node[above] at (6,4.46) {-p$_\pi$};
			\draw[dashed, very thick] (4,3.46) -- (6,3.46);
		\end{pgfonlayer}
		\draw[dashed, very thick] (6,3.46) -- (7,4.73);
		\draw[dashed, very thick] (3,4.73) -- (4,3.46);
	\end{tikzpicture}
	\caption{When jumping from one carbon atom to another, the \(\pi\)-electron goes between p\(_\pi\)-orbitals. Such a jump is described by two matrix elements in the system's Hamiltonian.}
	\label{sign}
\end{figure}
\subsection{Tight-binding}\label{tbtheory}
Now that the transport carrying electrons are defined the next step is describing the transport itself. For this purpose we employ the \textit{tight-binding} approximation. In this approximation the electrons are considered being tightly bound to the atoms. Contrary to a free electron gas approximation, the electrons does not spend time in between orbitals, but jump from orbital in atom \(a\) to orbital in atom \(b\). The Hamiltonian is represented as a matrix of hopping elements for a collection of neighbouring atomic orbitals, i.e. molecular orbitals, as well as the energy contained within each orbital (which will be addressed later on). This can be done by describing the orbitals as a Linear Combination of Atomic Orbitals (LCAO). The solution to the Schrödinger equation is then:
\begin{align}
	\Psi_{\mathrm{MO}} = \sum_{\alpha,R}c_{\alpha,R}\phi_{\alpha}(R)
\end{align}
where \(\phi_{\alpha}(R)\) is an atomic orbital at position \(R\), with \(\alpha\) denoting the valence of the orbital (\(2s,2p_x,2p_y,2p_z\)). In electron transport the states close to the Fermi level is of interest. These are namely the highest occupied molecular orbitals (HOMO), or the lowest unoccupied molecular orbitals (LUMO). As stated earlier only the \(\pi\)-electrons is then of interest.
The electrons' motion can be described with the hopping matrix of elements:
\begin{align}
	V_{pp\pi} = \bra{\phi_{\pi}(m)}\hat{H}\ket{\phi_{\pi}(n)}\label{V}
\end{align}
Physically this means that there is a potential \(\pqty{V_{pp\pi}}\) between the \(\pi\) orbitals of neighbouring atoms \(i\) and \(j\). In our tight-binding approximation we consider only hop between nearest neighbours. Furthermore we do not take account for out of plane carbon atoms. The element
\begin{align}
	\epsilon_0 = \bra{\phi_{\pi}(i)}\hat{H}\ket{\phi_{\pi}(i)}
\end{align}
is the average energy of the electron on atom \(i\) and, it is common to define the hopping energy relative to this, i.e. \(\epsilon_0 = 0\).
If the atoms or their environment differs, so does the on-site potential.\newline
\cref{benzex} contains an illuminating example of how the tight-binding approximation can be used to describe the benzene molecule.


\subsection{Example \#5: single time series analysis with interventions}
\label{S:Example_DISP_intervention}
\subsubsection{Data description}
This case is based on Example \#1 (see \ref{S:Example_DISP}) where we removed some part of the data and introduce discrete shifts into it. This example illustrates what typically happens a sensor fails; when a sensor fails, the data start to be missing (i.e. \lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!NaN!) and it often takes from several weeks to several months before the sensor is replaced. When the sensor is replaced, it is in most cases re-initialized at a different initial value than the previous sensor which lead to a discrete shift in the time series, as depicted in Figure~\ref{fig:DataSummary1}. Here in addition to the components employed for Example \#1, we also employ a Local intervention in order to estimate the magnitude of the corrections require to eliminate the discrete shifts created by sensor replacement.

Note that again, in this example, we choose to resample the original data in order to have a timesteps of 6h instead of 1h.

\begin{figure*}[h]
\centering
\begin{subfigure}{\linewidth}
\includegraphics[width=0.95\linewidth]{./docfigs/Example_DISP_INTERVENTION/ALL_AMPLITUDES.pdf}
\caption{Amplitude}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/ALL_TIMESTEPS.pdf}
\caption{Timestep}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/AVAILABILITY.pdf}
\caption{Availability}
\end{subfigure}
\caption{Raw data in the example \#1 where the reference timestep is 1h.}
\label{fig:DataSummary1}
\end{figure*}

\subsubsection{Model description}
\label{SS:ModelConstructionExample1}
The model includes one model class, and the hidden states variables are
\begin{gather*}
\textbf{x}=[x^{\mathtt{LL}}, x^{\mathtt{P1}\text{,yearly}}, x^{\mathtt{P2}\text{,yearly}}, x^{\mathtt{P1}\text{,daily}}, x^{\mathtt{P2}\text{,daily}}, x^{\mathtt{AR}}, x^{\mathtt{LI}}].
\end{gather*}
When using a Level intervention component, the user must provide discrete timestamps where it is required to estimate the magnitude of a discrete shift in the dataset (see \S\ref{SSS:LI}). A user can do so by specifying in the configuration file \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!data.interventions=[t_{1}, t_{2}, ... , t_{n}]!}. The configuration file for this problem is presented in the Listing \ref{LST:CFGFileExampleInt} where the timestamps where the shift occur are \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!data.interventions=[735929.875, 736099.875];!}.

\begin{lstlisting}[linewidth=\linewidth, style=Matlab-editor,  basicstyle = \mlttfamily \tiny, backgroundcolor = \color{matlab-yellow}, caption = {Configuration file for the example \#5}, label=LST:CFGFileExampleInt, captionpos=b, float=h!]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% A - Project name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
misc.ProjectName='Example_DISP_INTERVENTION';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% B - Data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dat=load('DATA_Example_DISP_INTERVENTION.mat');
data.values=dat.values;
data.timestamps=dat.timestamps;
data.labels={'DISP'};
data.interventions=[735929.875, 736099.875];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% C - Model structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Components reference numbers
% 11: Local level
% 12: Local trend
% 13: Local acceleration
% 21: Local level compatible with local trend
% 22: Local level compatible with local acceleration
% 23: Local trend compatible with local acceleration
% 31: Periodic
% 41: Autoregressive
% 51: Kernel regression
% 61: Level Intervention

% Model components
model.components.block{1}={[11 31 31 41 61 ] };

% Model inter-components dependence | {[components form dataset_i depends on components from  dataset_j]_i,[...]}
model.components.ic={[ ] };
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% D - Model parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
model.param_properties={
     % #1           #2             #3      #4    #5               #6           #7       #8              #9              #10
     % Param name   Block name     Model   Obs   Bound            Prior        Mean     Std             Values          Ref
     '\sigma_w',   'LL',           '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            0,              1      %#1
     'p',          'PD1',          '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            365.2422,       2      %#2
     '\sigma_w',   'PD1',          '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            0,              3      %#3
     'p',          'PD2',          '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            1,              4      %#4
     '\sigma_w',   'PD2',          '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            0,              5      %#5
     '\phi',       'AR',           '1',   '1',   [0  1      ],    'N/A',       NaN,     NaN,            0.90399,        6      %#6
     '\sigma_w',   'AR',           '1',   '1',   [0  Inf    ],    'N/A',       NaN,     NaN,            0.035428,       7      %#7
     '\mu_b',      'LI',           '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            0,              8      %#8
     '\sigma_b',   'LI',           '1',   '1',   [NaN  NaN  ],    'N/A',       NaN,     NaN,            0.16276,        9      %#9
     '\sigma_v',   '',             '1',   '1',   [0  Inf    ],    'N/A',       NaN,     NaN,            6.193e-06,      10     %#10
};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% E - Initial states values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initial hidden states mean for model 1:
model.initX{ 1 }=[	25.9  	-0.194	-0.01 	-0.00411	0.0551	-0.0127	0     ]';
% Initial hidden states variance for model 1:
model.initV{ 1 }=diag([ 	8.26E-05	0.000143	0.000106	4.86E-07	4.86E-07	0.00167	1E-20  ]);
% Initial probability for model 1
model.initS{1}=[1     ];

\end{lstlisting}

The model parameters associated with this model are
\begin{gather*}
\bm\theta=[\sigma_{w}^{\mathtt{LL}}, p^{\mathtt{P}, \text{yearly}}, \sigma_{w}^{\mathtt{P}, \text{yearly}} , p^{\mathtt{P}, \text{daily}}, \sigma_{w}^{\mathtt{P}, \text{daily}}, \phi^{\mathtt{AR}}, \sigma_{w}^{\mathtt{AR}}, \mu_{b}^{\mathtt{LI}}, \sigma_{b}^{\mathtt{LI}}, \sigma_{v}].
\end{gather*}
The optimized model parameters values computed using the Newton-Raphson algorithm (see~\ref{SS:THModelParameterEstimation}) with a training period of 180 days  are
\begin{gather*}
\bm\theta^{\text{*}}=[0, 365.2422, 0, 1, 0, 0.903, 0.035, 0, 0.16 6.19\times10^{-6} ].
\end{gather*}
The estimated initial hidden states mean and covariance values are
\begin{align*}
\bm \mu^{*}_{0} & = [	25.9,-0.194,-0.01	,-0.004,0.055,-0.013,0]^{\intercal}, \text{and} \\
\bm\Sigma^{*}_{0} & = \text{diag}([8.26\times10^{-5},	1.4\times10^{-4},	1.1\times10^{-4},	4.86\times10^{-7},	4.86\times10^{-7},	1.67\times10^{-3}  1E-20 ]).
 \end{align*}
The hidden states computed using the estimated model parameters and initial hidden states are presented in Figure~\ref{fig:Example_DISP_INTERVENTIONOptimizedOptimizedExample1}. You can see in Figure \ref{fig:Example_DISP_INTERVENTIONOptimizedOptimizedExample1}b that the level remains constant throughout the entire time series despite the jumps. This is because the discrete shift are estimated by the Level intervention component displayed in Figure \ref{fig:Example_DISP_INTERVENTIONOptimizedOptimizedExample1}e.

\subsubsection{Run the example from the pre-existing configuration file}
\label{SS:LoadConfigFileEx1}
There is a configuration file CFG\_Example\_DISP\_INTERVENTION\_optim.m which is located in the ``config\_files'' folder of the OpenBDLM package.
CFG\_Example\_DISP\_INTERVENTION\_optim.m contains the optimized model parameters and estimated initial hidden states values (see Listing \ref{LST:CFGFileExampleInt}).
There is also a data file DATA\_Example\_DISP\_INTERVENTION\_optim.mat that is located in the ``data/mat'' subfolder.
Therefore, it is possible to run the example \#1 by following the steps below while interacting with the \MATLAB{} command line:
\begin{enumerate}
\item Start OpenBDLM. Type \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!OpenBDLM_main('CFG_Example_DISP_INTERVENTION_optim.m');!}.
\item Access hidden states estimation menu. Type \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!3!}.
\item Run the Kalman smoother to estimate the hidden states. Type \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!1!}.
\item Save and quit. Type \colorbox{light-gray}{\lstinline[basicstyle = \mlttfamily \small, backgroundcolor = \color{light-gray}]!Q!}.
\end{enumerate}

\begin{figure*}[h!]
\begin{center}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/DISP_ObservedPredicted.pdf}
\caption{Observed and estimated displacement data}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/DISP_LL_1.pdf}
\caption{Estimated displacement local level component.}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/DISP_S1_2.pdf}
\caption{Estimated displacement yearly periodic component (first hidden state)}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/DISP_AR_6.pdf}
\caption{Estimated displacement autoregressive component}
\end{subfigure}
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=0.9\linewidth]{./docfigs/Example_DISP_INTERVENTION/DISP_LI_7.pdf}
\caption{Estimated displacement daily periodic component (first hidden state)}
\end{subfigure}
\caption{Estimated results using OpenBDLM with the optimized model parameters and estimated initial hidden states. The hidden states are estimated from the data presented in Figure~\ref{fig:DataSummary1}a. The solid line and shaded area represent the mean and standard deviation of the estimated hidden states.}
\label{fig:Example_DISP_INTERVENTIONOptimizedOptimizedExample1}
\end{center}
\end{figure*}


%!TEX root = ../thesis.tex
% ******************************* Thesis Appendix A ****************************

\ifpdf
    \graphicspath{{Appendix1/Figs/Raster/}{Appendix1/Figs/PDF/}{Appendix1/Figs/}}
\else
    \graphicspath{{Appendix1/Figs/Vector/}{Appendix1/Figs/}}
\fi

\chapter{Methods}
\section{Measuring focal length of scan lens}\label{appendix:scanlens}

The focal length of the scan lens was initially unknown but its position for collimation was, and so a reasonable assumption of its focal length was possible.
To compound certainty the focal length was found experimentally.
To accurately measure the focal length of an unknown lens the focal length of a lens of known focal length is needed to collimate the light.
In this experiment the tube lens of focal length \SI{200}{\milli\meter} was used.
By measuring the width of a laser beam prior ($w_{before}$) to and after ($w_{after}$) the collimating lens pair, the magnification is calculated very accurately and the unknown focal length is found by:

\begin{align}
	M=\frac{f_2}{f_1}=\frac{w_{before}}{w_{after}}  \rightarrow \frac{f_2}{M} =f_{1}
\end{align}

To measure a beam width very accurately a straight sharp edge is placed in the beam path and slowly iterated through, the resultant beam power is then measured using a power meter.
To ensure there is no beam cropping on the power meter another lens was used to focus the intensity correctly, the same lens and its position was used in each measurement to keep with consistency.
The beam power was measured and plotted which produces an integrated Gaussian profile (see \eqref{eq:guass_prop}) otherwise known as an error function.
Mathematically this is described by equation~\eqref{eq:knife}.

\begin{align}
	I(x,y) &= I_0 e^{\frac{-2x^2}{w_x^2}}e^{\frac{-2y^2}{w_y^2}}\label{eq:guass_prop}\\\nonumber
	P_{TOT} &= I_0 \int_{\infty}^{\infty}e^{\frac{-2x^2}{w_x^2}} dx \int_{\infty}^{\infty}e^{\frac{-2y^2}{w_y^2}} dy\\\nonumber
	P(X) &= P_{TOT} - \int_{\infty}^{X}e^{\frac{-2x^2}{w_x^2}} dx I_0 \int_{\infty}^{\infty}e^{\frac{-2x^2}{w_x^2}} \\\nonumber
	&= \frac{P_{TOT}}{2} - \sqrt{\frac{\pi}{2}} I_0 \omega_y \int_{\infty}^{X}e^{\frac{-2x^2}{w_x^2}}\\
	& = \frac{P_{TOT}}{2} \left[1 - erf\left(\frac{\sqrt{2}X}{\omega_x}\right) \right] \label{eq:knife}
\end{align}

Fitting of this curve was implemented using MatLAB's curve fitting package which utilises the method of least squares fitting, see Figure \ref{fig:laser_width}.
The fit result produced values of laser beam width as $w_{before} = \SI{3.76\pm0.04}{\milli\meter}$ and $w_{after} = \SI{0.71\pm0.1}{\milli\meter}$.
% The value of $w_{after}$ was supplied in Table \ref{table:laser} however, for posterity is was remeasured locally in case the value had changed or was incorrect.
This gives a magnification $M$ of \SI{5.37 \pm 0.1}{} therefore the focal length of the scan lens is \SI{37.3\pm0.1}{\milli\meter}.
This also showed that the fill of the \SI{12}{\milli\meter} back aperture was \SI{3.76\pm0.04}{\milli\meter} hence the NA of the \num{0.3} objective used would be \SI{\approx 0.094}{}.

\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{./laser_width}
\caption[Laser Width Fitting]{Plot showing the fitting of two error functions based on the knife edge translation through a laser beam propagation, producing laser beam widths of $w_{after} = \SI{0.71\pm0.1}{\milli\meter}$ and $w_{before} = \SI{3.76\pm0.04}{\milli\meter}$}
\label{fig:laser_width}
\end{figure}

% \section{System alignments protocol}

%Stationary back apeture.
\chapter{Useful derivations}
\section{Convolution theorem}\label{appendix:convolution_theorem}

Convolution is a mathematical operation between two functions, say $g(t)$ and $f(t)$, with the resultant function being an expression of the overlap of $g$ as it is shifted over $f$ \cite{bracewellFourierAnalysisImaging2004}. Mathematically it can be expressed as an integral over a finite range $\tau$:
\begin{equation}
[f(*g](t) = \int_{-\infty}^{\infty} f(\tau) g(t-\tau)d\tau
\end{equation}

If a Fourier transform is then applied to the convolution of two functions:
\begin{align}
\mathcal{F}([f*g](t)) &= \int_{-\infty}^{\infty} \left[{\int_{-\infty}^{\infty} f(\tau)} g(t-\tau)d\tau\right] e^{-i2 \pi kt} dt \\
\text{and then reverse}&\text{ the order:}\nonumber\\
\mathcal{F}([f*g](t)) &= \int_{-\infty}^{\infty}f(\tau) \left[{\int_{-\infty}^{\infty} } g(t-\tau) e^{-i2 \pi kt} dt\right]   d\tau
\\
\text{From the shift theorem}& \text{ seen in equation \eqref{shift_ivariance}:} \nonumber
\\
\left[{\int_{-\infty}^{\infty} } g(t-\tau) e^{-i2 \pi kt} dt\right] &= \mathcal{F}(g(t-\tau)) = \mathcal{F}(g(t)) e^{-i2 \pi k \tau}\\
\implies \mathcal{F}([f*g](t)) &= \mathcal{F}(g(t)) \int_{-\infty}^{\infty}f(\tau) e^{-i2 \pi k \tau}    d\tau
\\&= \mathcal{F}(g(t)) \mathcal{F}(f(\tau)) \label{convolv}
\end{align}

Showing that \textbf{Convolution} in real space is \textbf{Multiplication} is Fourier space.

\section{Fourier transform}

Any continuous function can be decomposed into a linear summation of harmonic weighted sinusoidal functions. A Fourier transform is a mechanism by which the weightings of this series can be derived. Fourier space uses this transform to represent a function or a signal in frequency space (sometimes known as $k$-space or reciprocal space); it can be seen as a coordinate change from $x$ to $k$ denoted mathematically as~\cite{bloomfieldFourierAnalysisTime2000}:
\begin{equation}
F(k) \equiv\mathcal{F}  \{f(x)\} \equiv \int_{-\infty}^{\infty}f(x) e^{-i2 \pi kx} dx \label{fourier trans}
\end{equation}

This process is also reversible by:

\begin{equation}
f(x) \equiv\mathcal{F}^{-1}  \{F(k)\} \equiv \frac{1}{2 \pi} \int_{-\infty}^{\infty}F(k) e^{-i2 \pi kx} dk
\end{equation}

Fourier transforms have a valuable property in that a shift in real space becomes a complex phase term in $k$ space. This is shown by substituting $x = x-a$ and $dx = dx$ into \eqref{fourier trans}:
\begin{align}
F(k') &=  \int_{-\infty}^{\infty}f(x) e^{-i2 \pi k(x-a)} dx \nonumber\\
&=  e^{-i2 \pi ka} \underbrace{\int_{-\infty}^{\infty}f(x) e^{-i2 \pi kx}dx}_{F(k)}   \label{shift_ivariance}
\end{align}

Hence the additional real space shift only adds a multiplicative factor to the final Fourier transform. This is known as the Shift theorem.

\section{Huygens wavelet theory}

Diffraction is the spreading of light rays after an interaction with an object. Coincident light waves may interfere when diffracted such that the superposition of their resultant waves is constructive or destructive dependent on their relative phase difference. Light incident on an aperture $A(x,y)$ in the plane $S$ can be assumed to be of a plane wave nature. When passing through the aperture, light can then be modelled as being a series of $dS$ spaced point sources that radiate spherical wavefronts under Huygens' principle:

\begin{quote}
``Every point on a propagating wavefront serves as the source of secondary spherical wavelets, such that the wavefront at some later time is the envelope of these wavelets.''~\cite{goodmanIntroductionFourierOptics1996}
\end{quote}

%
% \begin{figure}
% \centering
% \includegraphics[width=0.7\linewidth]{./Diagrams/coordsys}
% \caption{Diagram depicting the coordinate system discussed Section \ref{diffraction}.}
% \label{fig:coordsys}
% \end{figure}

The superposition and hence summation of these emitting wavelets when only travelling forward ($+z$ direction) and contained in a cone of small angles from the optical axis can be evaluated in terms of $dE$, the change in the field at some point in front of the aperture. The change in field goes with $\frac{1}{r}$ where $r$ represents the distance to an arbitrary point and for a real wave can be expressed as:

\begin{equation}
dE = \frac{A(x,y)dS}{r} cos(\omega t -kr)
\end{equation}

Using the coordinates $\alpha,\beta$ to represent the two dimensional plane of the projection of the light passing through the aperture $A(x,y)$ then $r$ and $R$ can be written as:
\begin{align}
R^2 &= \alpha ^2 + \beta ^ 2+ z^2  \\
r^2 &= (\alpha - x)^2 + (\beta - y)^2 + z^2
\end{align}
Where $R$ represents the distance from the optical centre of the aperture to the arbitrary point at $\alpha,\beta$, which can be rewritten as:

\begin{equation}
r = R \sqrt{1 - \frac{2 \alpha x + 2 \beta y}{R^2} + \frac{x^2 + y^2}{R^2}}  \label{r = R}
\end{equation}

Which can be approximated using a binomial expansion to:

\begin{equation}
r = R - \frac{(\alpha x + \beta y)}{R}
\end{equation}

Provided the cone of angles is small, then $r \approx R$ and when only considering the case where $R^2 >> x^2 + y^2$ equation \eqref{r = R} tends to:
\begin{equation}
dE = \frac{A(x,y)}{R} e^{i \omega t - kr} e^{ik \left(\frac{\alpha x + \beta y}{R}\right)} dxdy
\end{equation}

Integrating across the entire aperture (wavefronts are entirely rejected elsewhere):

\begin{align}
E(\alpha,\beta) &= \frac{e^{i \omega t - kr}}{R} \int\int_{A}^{} A(x,y) e^{ik \left(\frac{\alpha x + \beta y}{R}\right)} dxdy
\\  \text{After a normalised } &\text{coordinate switch:} \nonumber \\
u &= \frac{k \alpha}{2 \pi R}  \text{ and }   v = \frac{k \beta}{2 \pi R}
\\ E(u,v)&=\frac{e^{i \omega t - kr}}{R} \int\int_{A}^{} A(x,y) e^{i2 \pi k \left(ux + vy\right)} dxdy
\end{align}

This form is well known and defined as a Fourier transform (with a weighting term) and hence the far field diffraction pattern of an aperture is the Fourier transform of that aperture~\cite{goodmanIntroductionFourierOptics1996}.

\section{Bragg conditons}

%Bragg conditions
Proof of Abbe limit from diffraction theory:

\begin{align}
    \intertext{We define the separation of two diffractive orders through an aperture}
    d \sin \alpha_n = n \lambda \\
    \intertext{We then use the equation of a lens}
    \sin\alpha_n = \frac{p_n}{f} \\
    p_n = \frac{n\lambda f}{d} \\
    \intertext{In the extreme of the limit of resolution, \(p_n\) becomes unity}
    d \le = \frac{\lambda}{\sin\alpha_{\text{max}}} \\
    \intertext{We rearrange to show the classic Abbe limit:}
    d \le = \frac{\lambda_0}{n\sin\alpha_{\text{max}}} = \frac{2\lambda_0}{NA}
\end{align}

\section{Fourier slice theorem}\label{appendix:fourierslice}
From~\cite{kakPrinciplesComputerizedTomographic2001}:

\begin{quotation}
``We derive the Fourier Slice Theorem by taking the one-dimensional Fourier transform of a parallel projection and noting that it is equal to a slice of the two-dimensional Fourier transform of the original object.
It follows that given the projection data, it should then be possible to estimate the object by simply performing a two-dimensional inverse Fourier transform.
We start by defining the two-dimensional Fourier transform of the object function as

\begin{align}
  F(u,v) = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} f(x, y)e^{-i2\pi(ux+uy)}dx dy.
  \intertext{ Likewise define a projection at an angle  \(\theta \), \(P_{\theta}(t)\), and its Fourier transform by}
S_{\theta}(w) =  \int_{-\infty}^{\infty} P_\theta9t) e^{-i2\pi w t} dt
\end{align}
\begin{align}
\intertext{The simplest example of the Fourier Slice Theorem is given for a projection at \(\theta = 0\).
First, consider the Fourier transform of the object along
the line in the frequency domain given by u = 0.
The Fourier transform integral now simplifies to}
F(u,0) = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} f(x, y)e^{-i2\pi(ux)}dx dy.
\intertext{ but because the phase factor is no longer dependent on y we can split the integral into two parts,}
F(u,0) =  \int_{-\infty}^{\infty} \left[  \int_{-\infty}^{\infty} f(x,y,) dy \right] e^{-i2\pi(ux)} dx \label{eq:f(u,0)}
\intertext{ From the definition of a parallel projection, the reader will recognise the term in brackets as the equation for a projection along lines of constant \(x\) or}
P_{\theta = 0} (x) = \int_{-\infty}^{\infty} f(x,y) dy
\intertext{Substituting this in \eqref{eq:f(u,0)} we find:}
F(u,0) =  \int_{-\infty}^{\infty} P_{\theta = 0} (x) e^{-i2\pi(ux)} dx
\intertext{ The right-hand side of this equation represents the one-dimensional Fourier transform of the projection \(P_{\theta = 0}\);
thus we have the following relationship between the vertical projection and the 2-D transform of the object function:}
F(u,0) = S_{\theta=0}(u)
\end{align}

\begin{quotation}
  ``The Fourier transform of a parallel projection of an image \(f(x, y)\) taken at angle \(\theta \) gives a slice of the two-dimensional transform, \(F(u, v)\), subtending an angle \(\theta \) with the \(u\)-axis.''
\end{quotation}
''
\end{quotation}

\chapter{Particle tracking}
\section{Failed quantifications of motion induced error}

Introduced in Section~\ref{sec:spt_maths}, attempts at quantify the error seen due to motion blur that failed.

\subsection{Cross correlation}
\begin{align*}
  \intertext{To analytically compare the expected and real results, the respective functions were cross-correlated using the analytical function:}
%\text{Cross correlation} =
(f \star g)(t)\ \stackrel{\mathrm{def}}{=} \int_{-\infty}^{\infty} &f(x)^* g(x+t) \mathop{dx}
\end{align*}
\begin{align*}
\intertext{The integral of the result across all space gives a single value signifying the quality of correlation between the two functions:}
\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} &f(t)^* g(x+t) \mathop{dx}\mathop{dt}
\intertext{This value will reach unity when $f(x) = g(x)$}
\end{align*}
\begin{align*}
\intertext{The expected PSF was given the additional $t$ parameter as it was more likely that this integral would solve, though, this only solves across all space for unnormalised PSFs:}
\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} &\text{PSF}_{\text{Reality}} (x)^* \text{PSF}_{\text{Expected}} (x+t) \mathop{dx}\mathop{dt} \\
=& \frac{\pi  c (a L+L_{\text{end}})^2}{a L_{\text{end}} L \sqrt{\frac{L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}}} +\frac{2 \pi  c^2 (a L+L_{\text{end}})^2}{L_{\text{end}}^2}\\
+&\frac{\pi  c L_{\text{end}}}{a L \sqrt{\frac{L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}}}-\frac{2 \pi  L_{\text{end}}}{a \sqrt{\frac{1}{c^2}} L \sqrt{\frac{L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}}}\\
+&\frac{2 \pi  c^2 (a L+L_{\text{end}})^2}{a L_{\text{end}} L}
\end{align*}
\begin{align*}
  \intertext{By correlating the normalised functions across a small window $u$ an analytical solution was produced.}
\int_{-u}^{ u}\int_{-\infty}^{\infty} \hat{\text{PSF}}_{\text{Reality}} (x)^* \hat{\text{PSF}}_{\text{Expected}} (x+t) \mathop{dx}\mathop{dt}
\end{align*}
\begin{align*}
&=-\frac{(a L+L_{\text{end}})}{\sqrt{2 \pi } a L_{\text{end}} L}\sqrt{\frac{L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}}\left(L_{\text{end}} u \left(\text{Ei}\left(-\frac{L_{\text{end}}^2 u^2}{2 c^2 (L_{\text{end}}+a L)^2}\right)+\Gamma \left(0,\frac{u^2}{2 c^2}\right)\right)\right.\\
&-\frac{\sqrt{2 \pi (-c)} (a L+L_{\text{end}}) \left(\text{Erf} \left(\frac{L_{\text{end}} u}{\sqrt{2} (a c L+c L_{\text{end}})}\right)\right)}{\sqrt{2 \pi } a L_{\text{end}} L}-\frac{\sqrt{2 \pi } L_{\text{end}} \left| c\right|  \text{Erf} \left(\frac{u}{\sqrt{2} \left| c\right| } \right)}{\sqrt{2 \pi } a L_{\text{end}} L}
\end{align*}

\begin{figure}
  \centering
  \includegraphics{./mathematica/correlation_analysis}
  \caption{}
  \label{fig:correlation_analysis}
\end{figure}

\subsection{Full width half maximum}

The correlation of two signals is not an absolute error which can be used to make predictions about real-world systems. So, the Full Width at Half Maximum of each of the two signals was considered as this property, in Gaussian-like functions, should provide an analogue for $\sigma(z)$ which may be compared absolutely.
\begin{align*}
\text{PSF}(x,...) &- \lim_{x\to0} \frac{\text{PSF}(x,...)}{2} = 0 \\
\implies \text{FWHM}_{\text{Expected}} &= 2x \\
&= \left|-\frac{\sqrt{2} c \sqrt{\ln{2} +2 i \pi  n} (a L+L_{\text{end}})}{L_{\text{end}}}\right|,n\in \mathbb{Z}
%\text{FWHM}_{\text{Expected}} &= \frac{2 \sqrt{3}}{\sqrt{\frac{a^2 L^2}{c^2 (a L+L_{\text{end}})^2}+\frac{3 L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}+\frac{3 a L_{\text{end}} L}{c^2 (a L+L_{\text{end}})^2}}}
\end{align*}
\begin{align*}
\text{PSF}_{\text{Reality}}(x,...) - \lim_{x\to0} \frac{\text{PSF}_{\text{Reality}}(x,...)}{2} = 0 \\
\intertext{This equation does not solve for $x$ so a Maclaurin expansion was used:}
= -\frac{L_{\text{end}} x^2}{4 \left(c^2 (a L+L_{\text{end}})\right)}+\frac{x^4 \left(a^2 L_{\text{end}} L^2+3 a L_{\text{end}}^2 L+3 L_{\text{end}}^3\right)}{48 c^4 (a L+L_{\text{end}})^3}+O\left(x^5\right)
\end{align*}
\begin{align*}
\implies \text{FWHM}_{\text{Reality}} &= \frac{2 \sqrt{3}}{\sqrt{\frac{a^2 L^2}{c^2 (a L+L_{\text{end}})^2}+\frac{3 L_{\text{end}}^2}{c^2 (a L+L_{\text{end}})^2}+\frac{3 a L_{\text{end}} L}{c^2 (a L+L_{\text{end}})^2}}}\\
\text{FWHM}_\text{Error} &= 2\frac{\text{PSF}_{\text{Expected}} - \text{PSF}_{\text{Reality}}}{\text{PSF}_{\text{Expected}} + \text{PSF}_{\text{Reality}}}\\
& = 2\frac{\sqrt{\ln{2}} \sqrt{a^2 L^2+3 a L_{\text{end}} L+3 L_{\text{end}}^2}-\sqrt{3} L_{\text{end}}}{\sqrt{\ln{2}} \sqrt{a^2 L^2+3 a L_{\text{end}} L+3 L_{\text{end}}^2}+\sqrt{3} L_{\text{end}}}
\end{align*}

When $L\to0$ this result of $\text{FWHM}_\text{Error}$ can be below zero, which would suggest that the result is not an accurate measure of the true error.
This is likely due to the process requiring a series expansion, at $x=0$; as the series expansion is only an approximation of the target function.
Since attaining error from the FWHM fails for small values of $L$ an analysis using area was considered.

\section{Magnetic tweezer alternate proof}\label{appendix:tweezertheory}

%The parameters from \eqref{eq:modelfitting} need to be reviewed and amended if one intends to link them to experimental data as one applies a known force and looks at the displacement of the bead from its initial position and not to stress and strain.

A bead moving through a viscous fluid can be described by Stokes' law \(F = 6 \pi \eta' r \nu \), where \(r\) is the radius of the bead and \(\nu \) is the critical velocity of the bead.
Stokes' law may be written as:

\begin{align}
 F &= 6 \pi \eta' r \frac{dx}{dt} \\
 \implies \frac{F}{\pi r^2} &= 6 \eta' \frac{d}{dt}\frac{x}{r} \\
 \implies \sigma &= 6 \eta' \frac{\epsilon}{dt}
 \intertext{Giving the equation of a dash-pot}
 \dot{\epsilon} = \frac{\sigma}{\eta}
\end{align}

To model the elastic spring, the elastic response of the tissue due to the bead displacement is approximated by the Thomson's solution of a point force in an infinite isotropic medium~\cite{l.d.landaue.m.lifshitzTheoryElasticity1970}.
The displacement (\(\mathbf{u}\)) in cylindrical coordinates (\((p,z)\)) for a point force (\(F_z\)) located at the origin and directed along the (\(z\)) axis is given by:

\begin{align}
 \mathbf{u} = \frac{F_z}{4 \pi \mu r }\left[ \frac{pz}{4(1-v)r^2} \mathbf{\hat{p}}+\left(1- \frac{p^2}{4(1-v)r^2}\right)\mathbf{\hat{z}}\right]\label{eq:thomsons}
\end{align}

Where \(\mathbf{\hat{p}}\) and \(\mathbf{\hat{z}}\) are unit vectors, \(\mu \) is the shear modulus (deformation at constant volume) and \(\nu \) is Poisson's ratio (a negative ratio of transverse to axial strain of a specimen, under an axial force).
As only forces in the \(\mathbf{\hat{z}}\) direction are being considering, Equation~\eqref{eq:thomsons} becomes:

\begin{align}
 u_z &= \frac{F_z}{4 \pi \mu r }\left[\left(1- \frac{p^2}{4(1-v)r^2}\right)\right]
 \intertext{Evaluating the displacement only on the \(z\) axis where \(p=0\), reduces this to:}
 \nabla z &= \frac{F_z}{4\pi \mu r}
 \intertext{In the close proximity to the bead of radius \(r_{\text{bead}} \), the displacement is given by:}
 \frac{\nabla z}{r_{\text{bead}}} = \frac{1}{4 \mu} \frac{F_z}{\pi r_{\text{bead}}^2} & \implies \epsilon = \frac{1}{4\mu} \sigma
\end{align}
Which is equivalent to~\eqref{eq:linearspring} when substituting \(E \) with \(4\mu \).


\documentclass[revision-guide.tex]{subfiles}
%% Current Author: LT / PS

\begin{document}
\chapter{Equations}
\setlength{\LTleft}{0pt}

\section{Equations to be learnt}
\subsection{Equations you need to remember for pre-U}

\renewcommand*{\arraystretch}{2}
\begin{longtable}{ll}
velocity & $v= \frac{\Delta x}{\Delta t}$ \\
acceleration & $a= \frac{\Delta v}{\Delta t}$ \\
resultant force & $F=ma$ \\
momentum & $p=mv$ \\
resultant force & $F=\frac{\Delta p}{\Delta t}$ \\
impulse & Impulse = change in momentum \\
density & Density = mass/volume \\
pressure & Pressure = force/area \\
pressure in a liquid & $P = \rho gh$ \\
weight & $W = mg$ \\
power & $P = Fv$ \\
GPE & $\Delta E = mg \Delta h$ \\
change in gravitational potential & $=g \Delta h $ \\
energy in a spring & $E = \frac{1}{2} Fx$ \\
efficiency & \% efficiency =
$\frac{\text{useful energy or power}}{\text{total energy or power in}}
\times 100$ \\
current & $I = \frac{\Delta Q}{\Delta t}$ \\
potential difference & $V = \frac{W}{Q}$ \\
resistance & $R = \frac{V}{I}$ \\
electrical power & $P = VI$ \\
electrical work done & $W = VIt$\\
resistance & $R = \frac{\rho l}{A}$ \\
resistors in series & $R_T = R_1 + R_2 + \ldots{}$\\
resistors in parallel &
\(\frac{1}{R_{T}} = \frac{1}{R_{1}} + \frac{1}{R_{2}} + \ldots\)\\
frequency & $f = 1/T$\\
wave speed & $v = f\lambda$\\
Malus' law & $\text{Intensity} \propto \cos^2{\theta}$\\
photoelectric equation & \(hf = \phi + \frac{1}{2}mv_{\max}^{2}\)\\
angular velocity & $v = r\omega$ \\
period & $T = 2\pi /\omega$\\
circular motion & $F = mv^2/r$\\
electric field strength & $E = F/Q$\\
capacitance & $C = Q/V$\\
field strength/potential & $E = -\frac{\text{d}V}{\text{d}{X}}$ \\
the ideal gas law & $pV = nRT$\\
Boltzmann factor & $e^{- \frac{E}{kT}}$ \\
activity & $A = -\frac{\ud N}{\ud t}$\\
luminous flux &\(F = \frac{L}{4\pi d^{2}}\)\\

Hubble's law &\(v \approx H_{0}d\)\\

Hubble time & $t = 1/H_{0}$\\

\end{longtable}

\subsection{Equations you need to remember for paper 3, part B, but not for any other part of the examination.}
\renewcommand*{\arraystretch}{2}
\begin{longtable}{ll}
moment of inertia & \(I = \Sigma mr^{2}\)\\
shm & \(\frac{d^{2}x}{dt^{2}} = - \omega^{2}x\)\\
& $x = A\cos{\omega t}$\\
\end{longtable}

\newpage
\section{Derivations}
\subsection{Equations you need to derive and remember for pre-U}

\renewcommand*{\arraystretch}{2}
\begin{longtable}{ll}
energy in a spring & $E = \frac{1}{2}kx^2$ \\
kinetic energy & $E = \frac{1}{2}mv^{2}$\\
emf & $E = I(R+r)$\\
emf & $E = V + Ir$\\
electrical power & $P = I^{2}R$\\
critical angle & $\sin{c} = 1/n$\\
centripetal acceleration & $a = v^{2}/r$\\
centripetal acceleration & $a = r\omega^2$\\
uniform electric field & $Fd = QV$\\
uniform electric field & $E = V/d$\\
energy in a capacitor & $W = \frac{1}{2}CV^2$\\
energy in a capacitor & $W = \frac{1}{2}\frac{Q^2}{C}$\\
electric field due to a point charge &
\(E = \ \frac{Q}{{4\pi\varepsilon_{0}r}^{2}}\)\\

Kepler's third law & $r^{3} \propto T^{2}$\\
gravitational field strength & \(g = \frac{\text{Gm}}{r^{2}}\)\\

radius of curvature of particle in B-field &
\(r = \frac{\text{mv}}{\text{BQ}}\) \\

Hall effect & $V = Bvd$\\

kinetic theory of gases & $pV = \frac{1}{3}Nm\langle c^2 \rangle$\\

activity of a source & $A = \lambda N$\\

activity at time t & $A = A_0\text{e}^{-\lambda t}$\\
half-life & \(t_{\frac{1}{2}} = \frac{ln2}{\lambda}\)\\
\end{longtable}

\subsection{Equations you need to derive for paper 3, part B, but not for any other part of the examination.}

\renewcommand*{\arraystretch}{2}
\begin{longtable}{ll}

moment of inertia of a ring & $I = mr^2$\\

moment of inertia of a disc & $I = mr^{2}/2$\\

moment of inertia of a rod about one end & $I = ml^2/3$\\

moment of inertia of a rod about its centre & $I = ml^{2}/12$\\

velocity in shm & $v = -A\omega \sin{\omega t}$\\

acceleration in shm & $a = -A\omega^{2}\cos{\omega t}$\\

total energy in shm & $E = \frac{1}{2}mA^2\omega^2$\\

electric potential (from electric force) &
\(W = \frac{Q_{1}Q_{2}}{4\pi\varepsilon_{o}r}\)\\

hydrogen atom energy levels &\(E_{n} = \frac{- 13.6eV}{n^{2}}\)\\
\end{longtable}
\end{document}


\section{Test Description and Success Criteria}
The unit test, test\_orb\_elem\_convert.py,  validates the internal aspects of the Basilisk orb\_elem\_convert module by comparing module output to expected output. The unit test validates the conversions performed between Keplerian orbital elements and Cartesian vectors. This test begins by converting elements to Cartesian and is immediately followed by converting the results back to orbital elements, providing the opportunity to compare the initial input with the final output. This is repeated for a variety of parameters.

Differences between simulated and calculated output are measured, and those that approximately equal zero (typically $\delta < 10^{-9}$) qualify as a successful test. However, since the semimajor axis and the Cartesian vectors are greater than the other parameters by a factor of at least $10^7$, a higher discrepency is more tolerable. These tolerances are more clearly defined with the results.

\subsection{Element to Cartesian}
This test verifies the conversion from orbital elements to Cartesian vectors by comparing position and velocity vectors calculated in Python to those determined in the module. It uses six orbital elements and a gravitational constant as inputs. Also, \textit{Elements2Cart} and \textit{inputsGood} must be set to \textit{True}, which is discussed in more detail in the next section. The \textit{useEphemFormat} parameter is alternated between \textit{True} and \textit{False} to test the use of both spacecraft and planet data. The calculations for this conversion are performed seperately in the test module to compare with the simulated results. Multiple tests were performed, varying semimajor axis and eccentricity inputs.
\subsubsection{Calculation vs. Module}
The first check compares calculated Cartesian vectors to the simulated results and verifies that the discrepancy is less than $10^{-9}$.

\subsection{Cartesian to Element}
This test verifies, via two checks, that the conversion from Cartesian vectors to orbital elements is accurate. This test requires position and velocity vectors, which are obtained through initially converting from orbital elements to Cartesian, as described above. It also needs a gravitational constant input. The \textit{Elements2Cart} is set to \textit{False} and \textit{inputsGood} must be set to \textit{True}. Like in the previous conversion test, \textit{useEphemFormat} is alternated between \textit{True} and \textit{False} to ensure that the Cartesian vectors can use both planet and spacecraft state data identically and accurately. The calculations for this conversion are also performed seperately in the test to compare with the simulated results.
\subsubsection{Calculation vs. Module}
Similar to the first conversion test, this check compares the calculated orbital elements to the elements obtained from the module.
\subsubsection{Input vs. Module}
This second check is performed last and compares the final result, comprised of orbital elements, with the orbital elements initially used as inputs for the first conversion test. This verifies that the two conversion processes can be combined to reattiain the original orbital elements.

\section{Test Parameters}

The previous description only briefly mentions the input parameters required to perform the tests on this module, so this section details the parameters further. In addition to the parameters being converted, the unit test requires inputs that identify which conversion is performed, what type of state data are being used, and whether or not to proceed with the given input.

\begin{enumerate}
	\item \underline{Euler Angles}:\\
	Euler angles, consisting of $i$, $\Omega$, and $\omega$, define the orbit plane orientation and may vary, depending on the orbit type. All non-zero values for these angles were pulled from an existing module and are actually used in many other Basilisk tests in the scenarios directory. This parameter set gives the following inclination, ascending node, and argument of periapses inputs:
	\begin{equation}\label{eq:42}
		i = 33.3^{\circ} = 0.5812 \text{rad}
	\end{equation}
	\begin{equation}\label{eq:43}
		\Omega = 48.2^{\circ} = 0.8412 \text{rad}
	\end{equation}
	\begin{equation}\label{eq:44}
		\omega = 347.8^{\circ} = 6.0703 \text{rad}
	\end{equation}
	Inputs alternate between zero and these given values depending on the orbit type, which is specified in the results section. All angles must be input as radians, so the conversion from degrees is performed as shown in Eq. \ref{eq:42} - \ref{eq:44}.
	\item \underline{True Anomaly}:\\
	The true anomaly input stays the same for each parameter set because the different orbits do not require a unique value, as they may for inclination, ascending node, and argument of periapsis. The true anomaly value, however, is pulled from the same module as those parameters, giving
	\begin{equation} \label{eq:41}
		f = 85.3^\circ = 1.489 \text{rad}
	\end{equation}
	\item \underline{Standard Gravitational Parameter}:\\
	The gravitational parameter $\mu$ is necessary for any conversion between orbital elements and Cartesian vectors. It is the product of a body's gravitational constant and mass, specifying the attracting body in units of $\frac{m^3}{s^2}$. This test specifies Earth as the astronomical body.
	\begin{equation}
		\mu = GM_{Earth}=3.986 \text{e+} 14\quad \frac{m^3}{s^2}
	\end{equation}
	\item \underline{Conversion Identifier}:\\
	In order to specify which conversion to perfom, that is Element to Cartesian or the reverse, an identifier must be set. In the test as well as the c++ file, this is a boolean flag, referred to as \textit{Elements2Cart} and indicating the cases displayed in the table below.
	\begin{table}[htbp]
		\caption{Elements2Cart Cases}
		\centering \fontsize{10}{10}\selectfont
		\begin{tabular}{c|c}
			\hline \textbf{Case} & \textbf{Conversion}\\ \hline True & Element to Cartesian\\ False & Cartesian to Element\\
			\hline
		\end{tabular}
	\end{table}
	\item \underline{Astronomical Body Identifier}\\
	Like the previous identifier, this is a boolean parameter that specifies how to use the module. Since the state data may describe any body in orbit, a value is needed to determine whether the conversions are being performed for a spacecraft or a planet. As stated previously, the test uses \textit{useEphemFormat} for this, providing the following options:
	\begin{table}[htbp]
		\caption{useEphemFormat Cases}
		\centering \fontsize{10}{10}\selectfont
		\begin{tabular}{c|c}
			\hline \textbf{Case} & \textbf{Body}\\ \hline True & Planet State Data\\ False & Spacecraft State Data\\
			\hline
		\end{tabular}
	\end{table}
	\item \underline{Valid Input Identifier}\\
	The last necessary parameter is another boolean flag, this time indicating whether the inputs are valid. This value is read from a message and distinguishes if it is written succesfully. If succesful, this allows the rest of the module to be run, initiating the conversion process. The test uses \textit{inputsGood} to execute this check where \textit{True} lets the module proceed and \textit{False} does not, so this value should always be \textit{True} for the module to execute properly.
\end{enumerate}
The orbital element parameters are varied throughout the test to validate a range of orbits. Since the test performs both conversions consecutively and the Cartesian results depend on the Keplerian inputs, the position and velocity vectors used for the second conversion also vary. These parameters are discussed with the results in the next section.
\begin{table}[H]
	\caption{Error Tolerance-Note: Absolute Tolerance is abs(truth-value)}
	\centering \fontsize{10}{10}\selectfont
	\begin{tabular}{c|c|c}
		\hline \textbf{Test} & \textbf{Calc/Sim Tolerance} & \textbf{Input/Output Tolerance}\\ \hline $a$ & $10^{-9}$ km & $10^{-7}$ km\\ $e$ & $10^{-9}$ & $10^{-9}$\\
		$i$ & $10^{-9}$ rad & $10^{-9}$ rad\\
		$\Omega$ & $10^{-9}$ rad & $10^{-10}$ rad\\
		$\omega$ & $10^{-9}$ rad & $10^{-9}$ rad\\
		$f$ & $10^{-9}$ rad & $10^{-9}$ rad\\
		$\bm{r}$ & $10^{-9}$ km & N/A\\
		$\bm{v}$ & $10^{-9}$ $\frac{\text{km}}{\text{s}}$ & N/A\\
		\hline
	\end{tabular}
\end{table}

\section{Test Results}

All checks within test\_orb\_elem\_convert.py passed as expected with a tolerance limit of about $10^{-9}$. This means all comparisons should have a discrepancy of no more than $10^{-9}$. This may vary depending on the parameters in question, for example, when comparing the semimajor axis, since it is a factor of at least $10^4$ larger than the other parameters. The tables in this section show the results of each test for various parameters followed by descriptions of the parameter sets.

\begin{itemize}
	\item \textbf{Element to Cartesian}
	\begin{table}[H]
	\caption{Element to Cartesian Test Results}
	\label{tab:Cart to Elem results}
	\centering \fontsize{10}{10}\selectfont
	\begin{tabular}{c|c|c}
		\hline
		\textbf{Parameter Sets} & \textbf{Results} & \textbf{Notes} 									\\ \hline
		1 & \input{AutoTex/IncEllip_a_1PassedText1}      	   &\input{AutoTex/IncEllip_a_1PassFailMsg1}\\
		2 & \input{AutoTex/EquEllip_a_1PassedText1}      	   &\input{AutoTex/EquEllip_a_1PassFailMsg1}\\
		3 & \input{AutoTex/IncCirc_1PassedText1}      	   &\input{AutoTex/IncCirc_1PassFailMsg1}\\
		4 & \input{AutoTex/EquCirc_1PassedText1}      	   &\input{AutoTex/EquCirc_1PassFailMsg1}\\
		5 & \input{AutoTex/IncPara_1PassedText1}      	   &\input{AutoTex/IncPara_1PassFailMsg1}\\
		6 & \input{AutoTex/EquPara_1PassedText1}      	   &\input{AutoTex/EquPara_1PassFailMsg1}\\
		7 & \input{AutoTex/IncHyp_a_1PassedText1}      	   &\input{AutoTex/IncHyp_a_1PassFailMsg1}\\
		8 & \input{AutoTex/EquHyp_a_1PassedText1}      	   &\input{AutoTex/EquHyp_a_1PassFailMsg1}\\
		\hline
	\end{tabular}
\end{table}
	Cartesian vectors are tested by comparing the simulated results of the conversion with calculated vectors. The discrepancy is expected to be no greater than $10^{-9}$ for both position and velocity. The two cases presented by the astronomical body identifier (\textit{useEphemFormat}), discussed in the Test Parameters section, produce identical results. Thus, they will not be referred to as seperate cases any further and only the various orbits will be analyzed. Plots comparing the position and velocity vectors are shown for each orbit. Only the upper and lower limits of the tests are displayed, providing insight into the effect of the changing parameters without an overwhelming amount of data.
	\begin{enumerate}
		\item \underline{Inclined Elliptic Orbit ($0<e<1.0$,\quad $a>0$)}\\
		To test elliptic orbtits, a range of semimajor axis inputs from $10-10^7$km is used. The eccentricity is also varied with inputs from $0.01-0.75$. As $a$ changes, $e=0.5$ and as $e$ changes, $a=10^7$km. All parameter sets passed for this case since the difference when comparing simulated and calculated results was always zero, as shown by Fig. \ref{fig:2} and \ref{fig:3}.
		\begin{figure}[H]
	\centering
	\subfloat[$e=0.01$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncEllip_e_1.pdf}}
	\subfloat[$e=0.75$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncEllip_e_2.pdf}}
	\caption{Inclined Elliptical Orbit Varying $e$}\label{fig:2}
\end{figure}
\begin{figure}[H]
	\centering
	\subfloat[$e=0.5$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncEllip_a_1.pdf}}
	\subfloat[$e=0.5$ and $a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncEllip_a_2.pdf}}
	\caption{Inclined Elliptical Orbit Varying $a$}\label{fig:3}
\end{figure}
\pagebreak
		\item \underline{Equatorial Elliptic Orbit ($0<e<1.0$,\quad $a>0$,\quad $i=0$,\quad $\Omega=0$)}\\
		The equatorial elliptic orbit is tested with the same range of $e$ and $a$ inputs as the inclined case. All variations also passed this test with a tolerance of zero, as shown in the following set of figures:
		\begin{figure}[H] \label{fig:4}
	\centering
	\subfloat[$e=0.01$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquEllip_e_1.pdf}}
	\subfloat[$e=0.75$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquEllip_e_2.pdf}}
	\caption{Equatorial Elliptical Orbit Varying $e$}
\end{figure}
\begin{figure}[H] \label{fig:5}
	\centering
	\subfloat[$e=0.5$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquEllip_a_1.pdf}}
	\subfloat[$e=0.5$ and $a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquEllip_a_2.pdf}}
	\caption{Equatorial Elliptical Orbit Varying $a$}
\end{figure}
		\pagebreak
		\item \underline{Inclined Circular Orbit ($e=0$, \quad $a>0$,\quad $\omega=0$)}\\
		Since $e=0$ for a circular orbit, the only varied input is $a$, which is limited to the same range as in the elliptical cases. All variations passed for the inclined circular orbit, again, with no discrepancy.
		\begin{figure}[H] \label{fig:6}
	\centering
	\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncCirc_1.pdf}}
	\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncCirc_2.pdf}}
	\caption{Inclined Circular Orbit Varying $a$}
\end{figure}
\item \underline{Equatorial Circular Orbit ($e=0$,\quad $a>0$, \quad $\omega=0$, \quad $i=0$, \quad $\Omega=0$)}\\
Like the inclined case, the only input varied for equatorial circular orbits is $a$. Also, all variations passed with no discrepancy, as shown in Fig. \ref{fig:7}.
\begin{figure}[H]
	\centering
	\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquCirc_1.pdf}}
	\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquCirc_2.pdf}}
	\caption{Equatorial Circular Orbit Varying $a$}\label{fig:7}
\end{figure}
		\pagebreak
		\item \underline{Inclined Parabolic Orbit ($e=1.0$, \quad $a=-r_p$)}\\
		For the parabolic orbit, the input is varied with $-10^5$km $<a < -10$km. As discussed in the model description, it is crucial that $a$ remains negative in the parabolic case. All variations passed for this case with discrepancies equal to zero displayed below.
		\begin{figure}[H] \label{fig:8}
	\centering
	\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncPara_1.pdf}}
	\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncPara_2.pdf}}
	\caption{Inclined Parabolic Orbit Varying $a$}
\end{figure}
\item \underline{Equatorial Parabolic Orbit ($e=1.0$, \quad $a=-r_p$, \quad $i=0$, \quad $\Omega=0$)}\\
The equatorial parabolic orbit is tested with the same range of $a$ as the inclined case. This orbit also passed for all variations and the results are shown in Fig. \ref{fig:9}.
\begin{figure}[H]
	\centering
	\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquPara_1.pdf}}
	\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquPara_2.pdf}}
	\caption{Equatorial Parabolic Orbit Varying $a$}\label{fig:9}
\end{figure}
		\pagebreak
		\item \underline{Inclined Hyperbolic Orbit ($e>1.0$, \quad $a<0$)}\\
		When testing hyperbolic orbits, $e$ and $a$ are both varied. While changing $e$ within the range $1.1<e<1.5$, $a=-10^4$km. While changing $a$ in the range $-10^5$km $<a < -10$km, $e=1.3$. All variations passed the tests, still with no discrepancies. The plots below compare the simulated and calculated results.
		\begin{figure}[H] \label{fig:10}
	\centering
	\subfloat[$e=1.1$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncHyp_e_1.pdf}}
	\subfloat[$e=1.5$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncHyp_e_2.pdf}}
	\caption{Inclined Hyperbolic Orbit Varying $e$}
\end{figure}
\begin{figure}[H] \label{fig:11}
	\centering
	\subfloat[$e=1.3$, $a=-10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncHyp_a_1.pdf}}
	\subfloat[$e=1.3$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/IncHyp_a_2.pdf}}
	\caption{Inclined Hyperbolic Orbit Varying $a$}
\end{figure}
		\pagebreak
		\item \underline{Equatorial Hyperbolic Orbit ($e>1.0$, \quad $a<0$, \quad $i=0$, \quad $\Omega = 0$)}\\
		Equatorial hyperbolic orbits are tested with the same range of $e$ and $a$ inputs as the inclined case. Also, all variations passed without discrepancy, as shown in the following Fig. \ref{fig:12} and \ref{fig:13}:
		\begin{figure}[H]
	\centering
	\subfloat[$e=1.1$,$a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquHyp_e_1.pdf}}
	\subfloat[$e=1.5$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquHyp_e_2.pdf}}
	\caption{Equatorial Hyperbolic Orbit Varying $e$}\label{fig:12}
\end{figure}
\begin{figure}[H]
	\centering
	\subfloat[$e=1.3$, $a=-10$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquHyp_a_1.pdf}}
	\subfloat[$e=1.3$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{AutoTex/EquHyp_a_2.pdf}}
	\caption{Equatorial Hyperbolic Orbit Varying $a$}\label{fig:13}
\end{figure}
	\end{enumerate}
	\pagebreak
	\item \textbf{Cartesian to Element}\\
	\begin{table}[H]
	\caption{Cartesian to Element Test Results}
	\label{tab:Elem to Cart results}
	\centering \fontsize{10}{10}\selectfont
	\begin{tabular}{c|c|c} % Column formatting,
		\hline
		\textbf{Parameter Sets} & \textbf{Results} & \textbf{Notes} 									\\ \hline
		1 & \input{AutoTex/IncEllip_a_1PassedText2}      	   &\input{AutoTex/IncEllip_a_1PassFailMsg2}\\
		2 & \input{AutoTex/EquEllip_a_1PassedText2}      	   &\input{AutoTex/EquEllip_a_1PassFailMsg2}\\
		3 & \input{AutoTex/IncCirc_1PassedText2}      	   &\input{AutoTex/IncCirc_1PassFailMsg2}\\
		4 & \input{AutoTex/EquCirc_1PassedText2}      	   &\input{AutoTex/EquCirc_1PassFailMsg2}\\
		5 & \input{AutoTex/IncPara_1PassedText2}      	   &\input{AutoTex/IncPara_1PassFailMsg2}\\
		6 & \input{AutoTex/EquPara_1PassedText2}      	   &\input{AutoTex/EquPara_1PassFailMsg2}\\
		7 & \input{AutoTex/IncHyp_a_1PassedText2}      	   &\input{AutoTex/IncHyp_a_1PassFailMsg2}\\
		8 & \input{AutoTex/EquHyp_a_1PassedText2}      	   &\input{AutoTex/EquHyp_a_1PassFailMsg2}\\
		\hline
	\end{tabular}
\end{table}
	Orbital elements are tested by making two comparisons. The first compares the simulated output with the calculated output, like in the previous conversion. The second compares elements initially used as inputs for the first conversion with those produced as the output of the second. As observed when testing the previous conversion, the comparison between calculated and simulated elements results in complete agreement. Also, the two cases presented by the astronomical body identifier, once again, produce identical results. Thus, the main focus of the Cartesian to element test results is the input/output comparison.

	Displayed below are explanations of the results after converting Cartesian to elements. Graphical representations of the parameter comparisons for each orbit type are not provided for this test, since the output is already specified above as the input when converting from elements to Cartesian. Figures from above can also be referenced for the Cartesian inputs.

	\begin{enumerate}
		\item \underline{Inclined Elliptic Orbit ($0<e<1.0$,\quad $a>0$)}\\
		All variations passed the tests performed, however, the discrepancy between semimajor axis initial input and simulated result increases as eccentricity approaches 1.0. This is because it approaches the parabolic case, which requires a different conversion method and makes the elliptic calculations less accurate. The discrepancy with the tested parameters never increases past $10^{-7}$km, though, and since the semimajor axis is typically on the scale of at least $10^7$km, this is acceptable. Fig. \ref{fig:aDiff} shows the change in semimajor axis discrepancy as eccentricity reaches 0.999. %and Figures \ref{fig:14} and \ref{fig:15} illustrate the test results.
		\begin{figure} [H]
			\centering
			\includegraphics[width=0.5\textwidth]{Figures/aDiff.png}
			\caption{Input/Output Discrepancy for Semimajor Axis as Eccentricity Approaches 1.0}\label{fig:aDiff}
		\end{figure}
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$e=0.01$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/IncEllipElem_e_1.png}}
		%			\subfloat[$e=0.75$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/IncEllipElem_e_2.png}}
		%			\caption{Inclined Elliptical Orbit Varying $e$}\label{fig:14}
		%		\end{figure}
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$e=0.5$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/IncEllipElem_a_1.png}}
		%			\subfloat[$e=0.5$ and $a=10$km]{\includegraphics[width=0.5\textwidth]{Figures/IncEllipElem_a_2.png}}
		%			\caption{Inclined Elliptical Orbit Varying $a$}\label{fig:15}
		%		\end{figure}
		%\pagebreak
		\item \underline{Equatorial Elliptic Orbit ($0<e<1.0$,\quad $a>0$,\quad $i=0$,\quad $\Omega=0$)}\\
		All variations also passed for this case with much lower discrepancies than the previous one, due to the initial input $e=0.5$. The largest difference still occurs when comparing the semimajor axis, but this time it only reaches $10^{-15}$km. %The figures below display the output parameters.
		%		\begin{figure}[H] \label{fig:16}
		%			\centering
		%			\subfloat[$e=0.01$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/EquEllipElem_e_1.png}}
		%			\subfloat[$e=0.75$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/EquEllipElem_e_2.png}}
		%			\caption{Equatorial Elliptical Orbit Varying $e$}
		%		\end{figure}
		%		\begin{figure}[H] \label{fig:17}
		%			\centering
		%			\subfloat[$e=0.5$ and $a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/EquEllipElem_a_1.png}}
		%			\subfloat[$e=0.5$ and $a=10$km]{\includegraphics[width=0.5\textwidth]{Figures/EquEllipElem_a_2.png}}
		%			\caption{Equatorial Elliptical Orbit Varying $a$}
		%		\end{figure}
		%		\pagebreak
		\item \underline{Inclined Circular Orbit ($e=0$, \quad $a>0$,\quad $\omega=0$)}\\
		All variations passed in the inclined circular orbit tests with the maximum tolerance at about $10^{-9}$. As initial input $a$ decreases, so does the tolerance, resulting in no discrepancy when $a=10$km. %The comparisons are shown below.
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/IncCircElem_1.png}}
		%			\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{Figures/IncCircElem_2.png}}
		%			\caption{Inclined Circular Orbit Varying $a$}
		%		\end{figure}
		\item \underline{Equatorial Circular Orbit ($e=0$,\quad $a>0$, \quad $\omega=0$, \quad $i=0$, \quad $\Omega=0$)}\\
		All variations passed as well, this time resulting in a tolerance of zero for almost all parameters. The only non-zero discrepancy is eccentricity with a difference of $10^{-17}$ between input and output. %Figure \ref{fig:19}  compares the orbital elements for the equatorial circular orbit.
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$a=10^7$km]{\includegraphics[width=0.5\textwidth]{Figures/EquCircElem_1.png}}
		%			\subfloat[$a=10$km]{\includegraphics[width=0.5\textwidth]{Figures/EquCircElem_2.png}}
		%			\caption{Equatorial Circular Orbit Varying $a$}\label{fig:19}
		%		\end{figure}
		%		\pagebreak
		\item \underline{Inclined Parabolic Orbit ($e=1.0$, \quad $a=-r_p$)}\\
		All variations passed for this orbit with tolerances well below the maximum allowed and decreasing as initial input $a$ becomes more negative. %The following figure shows the parameter comparisons.
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$a=-10$km]{\includegraphics[width=0.5\textwidth]{Figures/IncParaElem_1.png}}
		%			\subfloat[$a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/IncParaElem_2.png}}
		%			\caption{Inclined Parabolic Orbit Varying $a$}
		%		\end{figure}
		\item \underline{Equatorial Parabolic Orbit ($e=1.0$, \quad $a=-r_p$, \quad $i=0$, \quad $\Omega=0$)}\\
		This orbit also passed for all variations with discrepancies similar to those seen in the inclined case. %Figure \ref{fig:21} illustrates these results:
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$a=-10$km]{\includegraphics[width=0.5\textwidth]{Figures/EquParaElem_1.png}}
		%			\subfloat[$a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/EquParaElem_2.png}}
		%			\caption{Equatorial Parabolic Orbit Varying $a$}\label{fig:21}
		%		\end{figure}
		%		\pagebreak
		\item \underline{Inclined Hyperbolic Orbit ($e>1.0$, \quad $a<0$)}\\
		All tests passed with discrepancies well below the maximum limit. %as shown in the figures below.
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$e=1.1$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/IncHypElem_e_1.png}}
		%			\subfloat[$e=1.5$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/IncHypElem_e_2.png}}
		%			\caption{Inclined Hyperbolic Orbit Varying $e$}
		%		\end{figure}
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$e=1.3$, $a=-10$km]{\includegraphics[width=0.5\textwidth]{Figures/IncHypElem_a_1.png}}
		%			\subfloat[$e=1.3$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/IncHypElem_a_2.png}}
		%			\caption{Inclined Hyperbolic Orbit Varying $a$}
		%		\end{figure}
		%		\pagebreak
		\item \underline{Equatorial Hyperbolic Orbit ($e>1.0$, \quad $a<0$, \quad $i=0$, \quad $\Omega = 0$)}\\
		Each variation passed when tested, satisfying the tolerance limitation. The equatorial case exhibits lesser discrepancies than the inclined. %and the results are shown in figures \ref{fig:24} and \ref{fig:25}.
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$a=-10$km]{\includegraphics[width=0.5\textwidth]{Figures/EquHypElem_e_1.png}}
		%			\subfloat[$a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/EquHypElem_e_2.png}}
		%			\caption{Equatorial Hyperbolic Orbit Varying $a$}\label{fig:24}
		%		\end{figure}
		%		\begin{figure}[H]
		%			\centering
		%			\subfloat[$e=1.3$, $a=-10$km]{\includegraphics[width=0.5\textwidth]{Figures/EquHypElem_a_1.png}}
		%			\subfloat[$e=1.3$, $a=-10^5$km]{\includegraphics[width=0.5\textwidth]{Figures/EquHypElem_a_2.png}}
		%			\caption{Equatorial Hyperbolic Orbit Varying $e$}\label{fig:25}
		%		\end{figure}
	\end{enumerate}
\end{itemize}
\pagebreak