\chapter{Holomorphic square roots and logarithms}
\label{ch:complex_log}
In this chapter we'll make sense of a holomorphic square root and logarithm.
The main results are \Cref{thm:nth_root}, \Cref{thm:holomorphic_log},
\Cref{cor:nonvanishing}, and \Cref{cor:principal}.
If you like, you can read just these four results, and skip the discussion of how they came to be.

Let $f : U \to \CC$ be a holomorphic function.
A \vocab{holomorphic $n$th root} of $f$ is a function $g : U \to \CC$
such that $f(z) = g(z)^n$ for all $z \in U$.
A \vocab{logarithm} of $f$ is a function $g : U \to \CC$
such that $f(z) = e^{g(z)}$ for all $z \in U$.
The main question we'll try to figure out is: when do these exist?
In particular, what if $f = \id$?

\section{Motivation: square root of a complex number}
To start us off, can we define $\sqrt z$ for any complex number $z$?

The first obvious problem that comes up is that for any $z$, there are
\emph{two} numbers $w$ such that $w^2 = z$.
How can we pick one to use?
For our ordinary square root function, we had a notion of ``positive'',
and so we simply took the positive root.

Let's expand on this: given
$ z = r \left( \cos\theta + i \sin\theta \right) $
(here $r \ge 0$) we should take the root to be
\[ w = \sqrt{r} \left( \cos \alpha + i \sin \alpha \right). \]
such that $2\alpha \equiv \theta \pmod{2\pi}$;
there are two choices for $\alpha \pmod{2\pi}$, differing by $\pi$.

For complex numbers, we don't have an obvious way to pick $\alpha$.
Nonetheless, perhaps we can also get away with an arbitrary distinction:
let's see what happens if we just choose the $\alpha$ with $-\half\pi < \alpha \le \half\pi$.

Pictured below are some points (in red)
and their images (in blue) under this ``upper-half'' square root.
The condition on $\alpha$ means we are forcing the blue points to lie on the right-half plane.

\begin{center}
	%% First Diagram
	\begin{asy}
		size(7cm);
		cplane();
		draw(origin--(4.2*dir(180)), grey+2);
		pair O = (-2.4, 1.1);
		pair T;
		pair[] A = new pair[8];
		real r = 1.44;
		real[] dirs = {45,45,45,135,175,255,-90,-75};
		for (int i=0; i<8; ++i) {
			A[i] = O + r*dir(i*45);
			dot("$z_{" + (string) i + "}$", A[i], dir(dirs[i]), red);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, red);

		real[] dirs = {-45, -15, 15, 45, 75, 150, 210, 230};
		for (int i=0; i<8; ++i) {
			A[i] = sqrt(abs(A[i]))*dir(degrees(A[i])/2);
			if (degrees(A[i]) > 90) { A[i] *= -1; }
			dot("$w_{" + (string) i + "}$", A[i], dir(dirs[i]), blue);
		}
		draw(A[7]..A[0]..A[1]..A[2]..A[3]..A[4]..A[5], blue);
	\end{asy}
\end{center}

Here, $w_i^2 = z_i$ for each $i$, and we are constraining the $w_i$
to lie in the right half of the complex plane.
We see there is an obvious issue: there is a big discontinuity near
the points $w_5$ and $w_7$!
The nearby point $w_6$ has been mapped very far away.
This discontinuity occurs since the points on the negative real axis are
at the ``boundary''.
For example, given $-4$, we send it to $-2i$, but we have hit the boundary:
in our interval $-\half\pi \le \alpha < \half\pi$, we are at the very left edge.

The negative real axis that we must not touch
is what we will later call a \emph{branch cut},
but for now I call it a \textbf{ray of death}.
It is a warning to the red points: if you cross this line, you will die!
However, if we move the red circle just a little upwards
(so that it misses the negative real axis) this issue is avoided entirely,
and we get what seems to be a ``nice'' square root.

\begin{center}
	%% Second Diagram
	\begin{asy}
		size(7cm);
		cplane();
		draw(origin--(4.2*dir(180)), grey+2);
		pair O = (-2.8, 1.9);
		pair T;
		pair[] A = new pair[8];
		real r = 1.44;
		real[] dirs = {45,45,45,135,175,225,-45,-45};
		for (int i=0; i<8; ++i) {
			A[i] = O + r*dir(i*45);
			dot("$z_{" + (string) i + "}$", A[i], dir(dirs[i]), red);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, red);

		real[] dirs = {-45, -15, 15, 75, 105, 150, 210, 260};
		for (int i=0; i<8; ++i) {
			A[i] = sqrt(abs(A[i]))*dir(degrees(A[i])/2);
			if (degrees(A[i]) > 90) { A[i] *= -1; }
			dot("$w_{" + (string) i + "}$", A[i], dir(dirs[i]), blue);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, blue);
	\end{asy}
\end{center}

In fact, the ray of death is fairly arbitrary:
it is the set of ``boundary issues''
that arose when we picked $-\half\pi < \alpha \le \half\pi$.
Suppose we instead insisted on the interval $0 \le \alpha < \pi$;
then the ray of death would be the \emph{positive} real axis instead.
The earlier circle we had now works just fine.

\begin{center}
	%% Third Diagram
	\begin{asy}
		size(7cm);
		cplane();
		draw(origin--(4.2*dir(0)), grey+2);
		pair O = (-2.4, 1.1);
		pair T;
		pair[] A = new pair[8];
		real r = 1.44;
		real[] dirs = {-5,45,45,135,175,255,-90,-75};
		for (int i=0; i<8; ++i) {
			A[i] = O + r*dir(i*45);
			dot("$z_{" + (string) i + "}$", A[i], dir(dirs[i]), red);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, red);

		real[] dirs = {-45, -15, 15, 45, 75, 150, 180, 230};
		for (int i=0; i<8; ++i) {
			A[i] = sqrt(abs(A[i]))*dir(degrees(A[i])/2);
			dot("$w_{" + (string) i + "}$", A[i], dir(dirs[i]), blue);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, blue);
	\end{asy}
\end{center}

What we see is that picking a particular $\alpha$-interval
leads to a different set of edge cases, and hence a different ray of death.
The only thing these rays have in common is their starting point of zero.
In other words, given a red circle and a restriction of $\alpha$,
I can make a nice ``square rooted'' blue circle as long as the
ray of death misses it.

So, what exactly is going on?

\section{Square roots of holomorphic functions}
To get a picture of what's happening, we would like to consider a more
general problem: let $f: U \to \CC$ be holomorphic.
Then we want to decide whether there is a $g : U \to \CC$
such that \[ f(z) = g(z)^2. \]
Our previous discussion with $f = \id$
tells us we cannot hope to achieve this for $U = \CC$;
there is a ``half-ray'' which causes problems.
However, there are certainly functions $f : \CC \to \CC$ such that a $g$ exists.
As a simplest example, $f(z) = z^2$ should definitely have a square root!

Now let's see if we can fudge together a square root.
Earlier, what we did was try to specify a rule to force one of the two choices at each point.
This is unnecessarily strict.
Perhaps we can do something like:
start at a point in $z_0 \in U$, pick a square root $w_0$ of $f(z_0)$,
and then try to ``fudge'' from there the square roots of the other points.
What do I mean by fudge?
Well, suppose $z_1$ is a point very close to $z_0$,
and we want to pick a square root $w_1$ of $f(z_1)$.
While there are two choices, we also would expect $w_0$ to be close to $w_1$.
Unless we are highly unlucky, this should tell us which choice of $w_1$ to pick.
(Stupid concrete example: if I have taken the square root $-4.12i$ of $-17$
and then ask you to continue this square root to $-16$,
which sign should you pick for $\pm 4i$?)

There are two possible ways we could get unlucky in the scheme above:
first, if $w_0 = 0$, then we're sunk.
But even if we avoid that, we have to worry that
if we run a full loop in the complex plane,
we might end up in a different place from where we started.
For concreteness, consider the following situation, again with $f = \id$:

\begin{center}
	%% Fourth Diagram
	\begin{asy}
		size(7cm);
		cplane();
		pair O = origin;
		pair T;
		pair[] A = new pair[8];
		real r = 3.24;
		real[] dirs = {45,45,45,135,135,255,-45,-45};
		for (int i=0; i<8; ++i) {
			A[i] = O + r*dir(i*45);
			dot("$z_{" + (string) i + "}$", A[i], dir(dirs[i]), red);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..cycle, red);

		real[] dirs = {-65, -15, 15, 45, 45, 135, 143, 135};
		for (int i=0; i<8; ++i) {
			A[i] = sqrt(abs(A[i]))*dir(degrees(A[i])/2);
			dot("$w_{" + (string) i + "}$", A[i], dir(dirs[i]), blue);
		}
		draw(A[0]..A[1]..A[2]..A[3]..A[4]..A[5]..A[6]..A[7]..(-A[0]), blue);
	\end{asy}
\end{center}

We started at the point $z_0$, with one of its square roots as $w_0$.
We then wound a full red circle around the origin, only to find that at the end of it,
the blue arc is at a different place where it started!

The interval construction from earlier doesn't work either:
no matter how we pick the interval for $\alpha$,
any ray of death must hit our red circle.
The problem somehow lies with the fact that we have enclosed the
very special point $0$.

Nevertheless, we know that if we take $f(z) = z^2$, then we don't run into any problems
with our ``make it up as you go'' procedure.
So, what exactly is going on?

\section{Covering projections}
By now, if you have read the part on algebraic topology,
this should all seem quite familiar.
The ``fudging'' procedure exactly describes the idea of a lifting.

More precisely, recall that there is a covering projection
\[ (-)^2 : \CC \setminus \{0\}
	\to \CC \setminus \{0\}. \]
Let $V = \left\{ z \in U \mid f(z) \neq 0 \right\}$.
For $z \in U \setminus V$, we already have the square root $g(z) = \sqrt{f(z)} = \sqrt 0 = 0$.
So the burden is completing $g : V \to \CC$.

Then essentially, what we are trying to do is construct a lifting $g$ in the diagram
\begin{diagram}
	&&& E = \CC \setminus \{0\} \\
	&& \ruTo(3,2)^{g} & \dTo_{p = (-)^2} \\
	V & \rTo_f && B = \CC \setminus \{0\}.
\end{diagram}

Our map $p$ can be described as ``winding around twice''.
Our \Cref{thm:lifting} now tells us that this lifting exists if and only if
\[ f_\ast\im(\pi_1(V)) \subseteq p_\ast\im(\pi_1(E)) \]
is a subset of the image of $\pi_1(E)$ by $p$.
Since $B$ and $E$ are both punctured planes, we can identify them with $S^1$.
\begin{ques}
	Show that the image under $p$ is
	exactly $2\ZZ$ once we identify $\pi_1(B) = \ZZ$.
\end{ques}

That means that for any loop $\gamma$ in $V$, we need $f \circ \gamma$ to have an
\emph{even} winding number around $0 \in B$.
This amounts to
\[
	\frac{1}{2\pi} \oint_\gamma \frac{f'}{f} \; dz \in 2\ZZ
\]
since $f$ has no poles.

Replacing $2$ with $n$ and carrying over the discussion gives the first main result.
\begin{theorem}
	[Existence of holomorphic $n$th roots]
	\label{thm:nth_root}
	Let $f : U \to \CC$ be holomorphic.
	Then $f$ has a holomorphic $n$th root if and only if
	\[ \frac{1}{2\pi i}\oint_\gamma \frac{f'}{f} \; dz \in n\ZZ \]
	for every contour $\gamma$ in $U$.
\end{theorem}

\section{Complex logarithms}
The multivalued nature of the complex logarithm comes from the fact that
\[ \exp(z+2\pi i) = \exp(z). \]
So if $e^w = z$, then any complex number $w + 2\pi i k$ is also a solution.

We can handle this in the same way as before:
it amounts to a lifting of the following diagram.
\begin{diagram}
	&&& E = \CC \\
	&& \ruTo(3,2)^{g} & \dTo_{p = \exp} \\
	U & \rTo_f && B = \CC \setminus \{0\}
\end{diagram}
There is no longer a need to work with a separate $V$ since:
\begin{ques}
	Show that if $f$ has any zeros then $g$ possibly can't exist.
\end{ques}
In fact, the map $\exp : \CC \to \CC\setminus\{0\}$ is a universal cover,
since $\CC$ is simply connected.
Thus, $p\im(\pi_1(\CC))$ is \emph{trivial}.
So in addition to being zero-free, $f$ cannot have any winding number around $0 \in B$ at all.
In other words:
\begin{theorem}
	[Existence of logarithms]
	\label{thm:holomorphic_log}
	Let $f : U \to \CC$ be holomorphic.
	Then $f$ has a logarithm if and only if
	\[ \frac{1}{2\pi i}\oint_\gamma \frac{f'}{f} \; dz  = 0 \]
	for every contour $\gamma$ in $U$.
\end{theorem}

\section{Some special cases}
The most common special case is
\begin{corollary}
	[Nonvanishing functions from simply connected domains]
	\label{cor:nonvanishing}
	Let $f : \Omega \to \CC$ be continuous, where $\Omega$ is simply connected.
	If $f(z) \neq 0$ for every $z \in \Omega$,
	then $f$ has both a logarithm and holomorphic $n$th root.
\end{corollary}

Finally, let's return to the question of $f = \id$ from the very beginning.
What's the best domain $U$ such that \[ \sqrt{-} : U \to \CC \]
is well-defined?  Clearly $U = \CC$ cannot be made to work,
but we can do almost as well.
For note that the only zero of $f = \id$ is at the origin.
Thus if we want to make a logarithm exist,
all we have to do is make an incision in the complex plane
that renders it impossible to make a loop around the origin.
The usual choice is to delete negative half of the real axis, our very first ray of death;
we call this a \vocab{branch cut}, with \vocab{branch point} at $0 \in \CC$
(the point which we cannot circle around).
This gives
\begin{theorem}[Branch cut functions]
	\label{cor:principal}
	There exist holomorphic functions
	\begin{align*}
		\log &: \CC \setminus (-\infty, 0] \to \CC \\ % chktex 9
		\sqrt[n]{-} &: \CC \setminus (-\infty, 0] \to \CC % chktex 9
	\end{align*}
	satisfying the obvious properties.
\end{theorem}
There are many possible choices of such functions ($n$ choices for the $n$th root
and infinitely many for $\log$);
a choice of such a function is called a \vocab{branch}.
So this is what is meant by a ``branch'' of a logarithm.

The \vocab{principal branch} is the ``canonical'' branch, analogous
to the way we arbitrarily pick the positive branch
to define $\sqrt{-} : \RR_{\ge 0} \to \RR_{\ge 0}$.
For $\log$, we take the $w$ such that $e^w = z$
and the imaginary part of $w$ lies in $(-\pi, \pi]$ % chktex 9
(since we can shift by integer multiples of $2\pi i$).
Often, authors will write $\opname{Log} z$ to emphasize this choice.

\section\problemhead
\begin{problem}
	Show that a holomorphic function $f : U \to \CC$
	has a holomorphic logarithm if and only if it
	has a holomorphic $n$th root for every integer $n$.
\end{problem}

\begin{problem}
	Show that the function $f : U \to \CC$
	by $z \mapsto z(z-1)$ has a holomorphic square root,
	where $U$ is the entire complex plane minus the closed interval $[0,1]$.
\end{problem}


% This file is part of the myspace project.
% Copyright 2019, 2020 the authors. All rights reserved.

% TODO:
% -

\documentclass[modern]{aastex62}
\input{preamble}

% typography
\setlength{\parindent}{1.\baselineskip}

% aastex parameters
% \received{not yet; THIS IS A DRAFT}
%\revised{not yet}
%\accepted{not yet}
% % Adds "Submitted to " the arguement.
% \submitjournal{ApJ}
\shorttitle{TODO}
\shortauthors{Price-Whelan \& Hogg}

\begin{document}\sloppy\sloppypar\raggedbottom\frenchspacing % trust me

\title{\textbf{\texttt{myspace}: action-space is \textsl{over}}}

\author[0000-0003-0872-7098]{Adrian~M.~Price-Whelan}

\author{Jason~A.~S.~Hunt}

\author[0000-0003-2866-9403]{David~W.~Hogg}

\begin{abstract}\noindent % trust me
\end{abstract}

\keywords{Galaxy: kinematics and dynamics}

% \section{Introduction}
% \label{sec:intro}

% Suh.

% \section{Data}
% \label{sec:data}

% We use astrometric data from the \gaia\ mission (\citealt{Prusti:2016}), data
% release 2 (\citealt{Gaia-Collaboration:2018, Lindegren:2018}).

% \begin{figure}
% \begin{center}
% \includegraphics[width=\textwidth]{gd1_sample.pdf}
% \end{center}
% \caption{
% On-sky positions of likely GD-1 members in the GD-1 coordinate system.
% GD-1 is apparent as an overdensity in negative proper motions (top right panel,
% orange box), so selecting on proper motion already reveals the stream in
% positions of individual stars (top left).
% The stream also stands out in the color-magnitude diagram (bottom right) as
% older and more metal poor than the background.
% Selecting the main sequence of GD-1 (orange, shaded region in bottom right)
% along with proper motion cuts unveils the stream in unprecedented detail (bottom
% left).
% }
% \label{fig:selection}
% \end{figure}

\section{Methods}
\label{sec:methods}

Every star has an observed 3-vector velocity $\vec{v}$ and an observed
3-vector position $\vec{x}$.
We transform to a new transformed velocity $\vec{v}'$ according to
\begin{equation}
  \vec{v}' = \vec{v} + \mat{A}\cdot\vec{x} + \mat{B}(\vec{x})\cdot\vec{v} + \mbox{terms}
  ~,
\end{equation}
where
$\mat{A}$ is an arbitrary $3\times 3$ tensor and
$\mat{B}(\vec{x})$ is a position-dependent, unit-determinant $3\times 3$ tensor
of the following form:
\begin{equation}
  \mat{B}(\vec{x}) = \exp\left(\sum_{k=1}^8 (\vec{u}_k^\top\cdot\vec{x})\,\mat{M}_k\right)
  ~,
\end{equation}
where
the exponentiation is \emph{matrix} exponentiation,
the 8 3-vectors $\vec{u}_k$ are free parameters,
and the 8 matrices $\mat{M}_k$ are the following traceless rotation and shear generators (or any 8 independent linear combinations thereof):
\begin{equation}
  \begin{bmatrix} 0 & 1 & 0 \\ -1 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}
  \begin{bmatrix} 0 & 0 & -1 \\ 0 & 0 & 0 \\ 1 & 0 & 0 \end{bmatrix}
  \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & -1 & 0 \end{bmatrix}
\end{equation}
\begin{equation}
  \begin{bmatrix} 1 & 0 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & 0 \end{bmatrix}
  \begin{bmatrix} -1 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}
  \begin{bmatrix} 0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}
  \begin{bmatrix} 0 & 0 & 1 \\ 0 & 0 & 0 \\ 1 & 0 & 0 \end{bmatrix}
  \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \end{bmatrix}
\end{equation}
This model has 9 free parameters in $\mat{A}$ and 24 total across
the 8 vectors $\vec{u}_k$, making for 33 free parameters in total.

In case you have ``forgotten'', matrix exponentiation can be defined as
\begin{equation}
  \exp(\mat{Q}) = I + \mat{Q} + \frac{1}{2!}\,\mat{Q}\cdot\mat{Q}
  + \frac{1}{3!}\,\mat{Q}\cdot\mat{Q}\cdot\mat{Q}
  + \frac{1}{4!}\,\mat{Q}\cdot\mat{Q}\cdot\mat{Q}\cdot\mat{Q}
  + \cdots
  ~,
\end{equation}
or you can just use \code{scipy.linalg.expm()} and avoid thinking about it.

Our objective is the log probability of the suburbs stars given then
GMM fit to the city stars. Say lots more about all that.

We previously imagined doing this:
\begin{equation}
    v_i = v_{i, {\rm obs}} + A_{ij}\,x_j +
        B_{ijl}\,x_j\,v_l + C_{ijl}\,x_j\,x_l +
        D_{ijlm}\,x_j\,x_l\,v_m + F_{ijlm}\,x_j\,v_l\,v_m +
        G_{ijlm}\,x_j\,x_l\,x_m +
        ...
\end{equation}
where $C$ is symmetric in $j, l$, $D$ is symmetric in $j, l$, $F$ is symmetric
in $l, m$, and $G$ is symmetric in $j, l, m$.
I count: 9 + 27 + 18 + 54 + 54 + 30 parameters?
But this is perhaps unstable, because the transformation can collapse the
velocity distribution into a tiny space.

\section{Results}
\label{sec:results}

Huh.

\section{Discussion}
\label{sec:discussion}

Wuh?

\acknowledgements{
It is a pleasure to thank
Kathryn V. Johnston,
Robyn Sanderson,
Lauren Anderson,
and David N. Spergel for useful discussions and feedback.

This work has made use of data from the European Space Agency (ESA) mission {\it
Gaia} (\url{https://www.cosmos.esa.int/gaia}), processed by the {\it Gaia} Data
Processing and Analysis Consortium (DPAC,
\url{https://www.cosmos.esa.int/web/gaia/dpac/consortium}). Funding for the DPAC
has been provided by national institutions, in particular the institutions
participating in the {\it Gaia} Multilateral Agreement.

% KITP shit:
This work was ... KITP...
This research was supported in part by the National Science Foundation under
Grant No. NSF PHY-1748958.
}

\software{
    \package{Astropy} \citep{astropy, astropy:2018},
    % \package{dustmaps}\footnote{\url{https://github.com/gregreen/dustmaps}},
    \package{gala} \citep{gala},
    \package{IPython} \citep{ipython},
    \package{matplotlib} \citep{mpl},
    \package{numpy} \citep{numpy},
    \package{scipy} \citep{scipy}
}

\bibliographystyle{aasjournal}
\bibliography{myspace}

% \clearpage

% \appendix
% \section{Completeness and the \gaia\ scanning pattern}
% \label{sec:completeness}

% \figurename~\ref{fig:XX} (XX panel) shows the $V$-band extinction
% in the region around the GD-1 stream, computed from the
% Schlegel-Finkbeiner-Davis extinction map (\cite{Schlegel:1998}; hereafter SFD).

% % Notebook:
% \begin{figure}[h]
% \begin{center}
% \includegraphics[width=0.7\textwidth]{nvisits.pdf}
% \end{center}
% \caption{%
% TODO
% \label{fig:TODO}
% }
% \end{figure}

\end{document}


% !TeX spellcheck = en_GB
\section{Computing Snow Quantities} \label{sec:data_proc}
%The previous \Cref{sec:retrieval,sec:MEPS} represented the details on retrieving snowfall amounts from the optimal estimation retrieval and the forecast model outputs.
The following section describes how the different model variables where processed to achieve a comparison between the retrieved observed values and the forecast model output.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% THICKNESS IN MEPS %%%%%%%%%%%%%%
\subsection{MEPS}\label{sec:layer_thickness}
Vertical hybrid coordinates are terrain-following and are mass-based, \citep{muller_arome-metcoop:_2017}. %How the vertical hybrid coordinates are transformed into layer thickness or height is described in \Cref{sec:layer_thickness}. Furthermore,
MEPS underlies non-hydrostatic dynamics, \cite{metcoop_wiki_description_2017}.
\\
MEPS has a vertical resolution in hybrid sigma pressure coordinates, which starts at the surface and decreases with height. To calculate the actual vertical pressure in [\SI{}{\hPa}], AROME uses the vertical discretisation based on \citet{simmons_energy_1981}. %, a formula is provided in the OPeNDAP Dataset of \texttt{meps\_full\_2\_5km\_*.nc} by the \citet{norwegian_meteorological_institute_met_2016}.
\begin{align}
p(n,k,j,i) = a_p(k) + b_p(k) \cdot p_s(n,j,i) \qquad [\SI{}{\Pa}].
\label{eq:hybrid_sigma_pressure}
\end{align}
$p_s$ is the surface air pressure in \SI{}{\Pa}, $a_p$, $b_p$ are the vertical coordinate parameters. Prognostic variables are at model level $k$. $n$ is the forecast time, $j$ and $i$ are the latitudal and longitudal grid points, respectively.
\\
The next step was to convert pressure-levels into actual heights with the help of the hypsometric equation. Here, the air temperature in model levels is used to calculate the mean temperature of each thickness layer.
\begin{align}
\overline{T} = \dfrac{\int\limits_{p2}^{p1} T \partial ln p}{\int\limits_{p2}^{p1}\partial ln p} \qquad [\SI{}{\kelvin}]
\label{eq:T_avg}
\end{align}
%For the numerical integration, the Simpson rule was used, which is a build-in function in Python. \\
\citet{martin_mid-latitude_2006} presents steps of differentiating the hypsometric equation by using the virtual air temperature. But when the atmospheric mixing ratio is large, the virtual temperature will only be \SI{1}{\percent} larger than the actual air temperature. Since the error is small, calculations are done with the provided air temperature in model levels.
\\
The thickness, $\Delta z$, of each layer is then calculated by using the hypsometric equation from \citet{martin_mid-latitude_2006} and the previously calculated mean temperature (\Cref{eq:T_avg}):
\begin{equation}
\begin{split}
\Delta z  = z_2 - z_1
& = \frac{R_d \overline{T}}{g} ln\left(\frac{p_1}{p_2} \right) \qquad [\SI{}{\metre}]
\end{split}
\label{eq:hypsometric}
\end{equation}
where $R_d$ is gas constant for dry air with a value of \SI{287}{\joule\per\kilogram\per\kelvin},  standard gravity $g\,=\,$\SI{9.81}{\metre\per\square\second}. $p_1$ and $p_2$ are the pressure levels at lower and higher levels %, respectively
($p_2 < p_1$).
%To gain the respective height of each pressure layer, $\Delta z$ is summed.
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% SWC %%%%%%%%%%%%%%
\subsection{Snow Water Content}
To get a valid comparison between the SWC from the optimal estimation retrieval and the results from MEPS, the SWC is averaged hourly respectively three hourly. Taking the model initialisation of MEPS at \SI{0}{\UTC} the instantaneous model forecast values are saved every hour for the deterministic and first ensemble member. Three hourly data is available for the second to tenth perturbed member. To approach hourly mean values from the retrieved SWC an average over \SI{30}{\minute} prior and \SI{30}{\minute} after each full hour is performed. %This leads to a match of the average value at the same time as from MEPS.
Hence, in \Cref{sec:res:large_scale_vert} and \ref{sec:res:oro_infl} hourly (three-hourly) retrieved averages are compared with instantaneous forecast values.
\\
Since MEPS has a higher vertical resolution than the optimal estimation snowfall retrieval, each vertical profile of SWC is averaged in \SI{200}{\metre} intervals. To accomplish the same vertical resolution only values above \SI{100}{\metre} altitude are used to start at the same range height as given from the MRR (\Cref{sec:MRR}).
\\
Within the output from MEPS snow water content does not exist for each model layer. Hence the calculation of the SWC is performed by using the three solid precipitation categories given in MEPS. Namely the instantaneous mixing ratio of snow ($r_\mathbf{s}$), graupel  ($r_\mathbf{g}$) and the cloud ice ($r_\mathbf{i}$). The mixing ratios are represented in \SI{}{\kg\per\kg} and a transformation to \SI{}{\g\per\cubic\meter} is performed. Densities of each model level ($\rho$) are calculated with \Cref{eq:hybrid_sigma_pressure} and the model level air temperature. These are then multiplied with the sum of the solid precipitation mixing ratio.
\begin{align}
\rho & = \frac{p}{R_d T} & \quad [\SI{}{\kg\per\cubic\meter}]  \\
SWC & = \rho \cdot (r_\mathbf{s} + r_\mathbf{g} + r_\mathbf{i}) \cdot \num{e6} & \quad [\SI{}{\g\per\cubic\meter}].
\label{eq:SWC_ml}
\end{align}
The same is done for liquid water content in the atmosphere, just cloud condensed water and rain amount are summed.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% SWP %%%%%%%%%%%%%%
\subsection{Snow Water Path}\label{sec:SWP}
The snow water path (SWP) is the vertically integrated and averaged SWC (\Cref{eq:SWC,eq:SWC_ml}): %, where the numerical Simpson's integration is applied.
\begin{equation}
\begin{split}
SWP = \int_{h_0}^{h_1=\SI{3000}{\metre}} \text{SWC}(h) \, dh \approx
\frac{h_1 - h_0}{6}  & \left[ \text{SWC}(h_0)    + \text{SWC}(h_1)   \vphantom{\frac{h_0 + h_1}{2}} \right. \\
& \left. + 4 \text{SWC}\left(\frac{h_0 + h1}{2}\right)
\right] \qquad [\SI{}{\g\per\square\meter}]
\end{split}
\label{eq:SWP}
\end{equation}
The snow water path is a measure of the weight of frozen particles per unit area. It indicates the total amount of ice in the atmosphere.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\newpage
\section{Statistics}
For this thesis I calculated ensemble mean, coefficient of variation, mean error, mean absolute error, and percent difference.
%%%%%%%%% Ensemble spread %%%%%%%%%%%%%%
%\subsection{Ensemble Mean and Coefficient of Variation}
\label{sec:ens_mean_spread}
The model ensemble mean ($\bar{f}$) is the average of all ten ensemble members ($f_i$) of MEPS.
\begin{align}
\bar{f} & = \frac{\sum_{i=1}^n f_i}{n} \label{eq:meanMEPS}
\end{align}
%The standard deviation, $\sigma$ of the ten ensemble members is divided by the mean of all ensemble members.
The coefficient of variation (CV) is represented by the standard deviation, $\sigma$  with respect to the ensemble mean.
% \\
%This coefficient gives the possibility to compare the SWC results for different days with different values.
%It follows for even a low ensemble spread of SWC (standard deviation of all ensemble members) then the different members do not need to be less variable.
The standard deviation is defined as:
\begin{align}
\sigma & = \sqrt{\frac{\sum_{i=1}^n (f_i - \bar{f})^2}{n-1}} .\label{eq:stdMEPS}
\end{align}
The CV gives the variability between the individual ensemble member forecast for SWC (\Cref{tab:verification}). Furthermore, the variation around the deterministic forecast shows. Since the CV is normed over the ensemble mean, daily variations can be compared to each other for the Christmas 2016 storm period (\Cref{sec:res:large_scale_vert}).
%which follows for the coefficient of variation:
\begin{align}
CV & = \frac{\sigma}{\bar{f}}
\end{align}
% \\
% To verify how well MEPS performed during the Christmas storm a variation of the SWC is calculated. For this, the standard deviation (\Cref{eq:stdMEPS}) is divided by the ensemble mean (\Cref{eq:meanMEPS}).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% MAE & ME %%%%%%%%%%%%%%
%\subsection{Mean Error and Mean Absolute Error}
In \Cref{sec:res:large_scale_sfc} mean error ($ME$) and mean absolute error ($MAE$) is used. The $ME$ for each model ensemble member and from the observations ($o_i$) is calculated with:
\begin{align}
ME = \frac{\sum_{i=1}^n f_i - o_i}{n}
\end{align}
%where $MEPS_{ens}$ represents the value of each ensemble member and $DoFe_{obs}$ defines the observation from the double fence.
For the mean absolute error ($MAE$) follows then:
\begin{align}
MAE = \frac{\sum_{i=1}^n \left| f_i - o_i\right|}{n} \label{eq:MAE}
\end{align}
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% %Diff, %Avg Diff %%%%%%%%%%%%%%
%\subsection{Percent Difference and Average Difference}
The percentage difference of double fence gauge and retrieved surface accumulation (\Cref{tab:res:ret_sens} and \ref{tab:res:ret_error}) and MEPS forecasts (\Cref{tab:res:MEPS_err} and \ref{tab:res:MEPS_err_10}) are calculated by:
\begin{align}
\SI{}{\percent} \text{Difference} & = \frac{f_i - o_i}{o_i} \times 100
\end{align}
$f_i$ presents the snowfall from the retrieval or the MEPS ensemble forecast. The mean is then taken from all \SI{}{\percent} Difference values to see the average deviation during the Christmas storm 2016.


%%%%%%%%%%%%%%%%%%%%% chapter.tex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% sample chapter
%
% Use this file as a template for your own input.
%
%%%%%%%%%%%%%%%%%%%%%%%% Springer-Verlag %%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter{Chapter Heading}
\label{intro} % Always give a unique label
% use \chaptermark{}
% to alter or adjust the chapter heading in the running head

Your text goes here. Separate text sections with the standard \LaTeX\
sectioning commands.

\section{Section Heading}
\label{sec:1}
% Always give a unique label
% and use \ref{<label>} for cross-references
% and \cite{<label>} for bibliographic references
% use \sectionmark{}
% to alter or adjust the section heading in the running head
Your text goes here. Use the \LaTeX\ automatism for your citations
\cite{monograph}.

\subsection{Subsection Heading}
\label{sec:2}
Your text goes here.

\begin{equation}
\vec{a}\times\vec{b}=\vec{c}
\end{equation}

\subsubsection{Subsubsection Heading}
Your text goes here. Use the \LaTeX\ automatism for cross-references as
well as for your citations, see Sect.~\ref{sec:1}.

\paragraph{Paragraph Heading} %
Your text goes here.

\subparagraph{Subparagraph Heading.} Your text goes here.%
%
\index{paragraph}
% Use the \index{} command to code your index words
%
% For tables use
%
\begin{table}
\centering
\caption{Please write your table caption here}
\label{tab:1}       % Give a unique label
%
% For LaTeX tables use
%
\begin{tabular}{lll}
\hline\noalign{\smallskip}
first & second & third  \\
\noalign{\smallskip}\hline\noalign{\smallskip}
number & number & number \\
number & number & number \\
\noalign{\smallskip}\hline
\end{tabular}
\end{table}
%
%
% For figures use
%
\begin{figure}
\centering
% Use the relevant command for your figure-insertion program
% to insert the figure file.
% For example, with the option graphics use
\includegraphics[height=4cm]{figure.eps}
%
% If not, use
%\picplace{5cm}{2cm} % Give the correct figure height and width in cm
%
\caption{Please write your figure caption here}
\label{fig:1}       % Give a unique label
\end{figure}
%
% For built-in environments use
%
\begin{theorem}
Theorem text goes here.
\end{theorem}
%
% or
%
\begin{lemma}
Lemma text goes here.
\end{lemma}
%
%
% Problems or Exercises should be sorted chapterwise
\section*{Problems}
\addcontentsline{toc}{section}{Problems}
%
% Use the following environment.
% Don't forget to label each problem;
% the label is needed for the solutions' environment
\begin{prob}
\label{prob1}
The problem\footnote{Footnote} is described here. The
problem is described here. The problem is described here.
\end{prob}

\begin{prob}
\label{prob2}
\textbf{Problem Heading}\\
(a) The first part of the problem is described here.\\
(b) The second part of the problem is described here.
\end{prob}

%


\subsection{Infinite state Markov chains}

Markov model description
We can represent the transition matrix as a series of rules to reduce the number of dimensions
\(P(x_t |y_{t-1})=f(x,y)\)

can represent states as number, rather than atomic. could be continuous, or even real.

in more complex, can use vectors.


\section{Compressed encoding of integer values}

\subsection{VLQ encoding}
\label{sec:vlq-encoding}

\begin{verbatim}
public final void putULong(long value) {
    while (true) {
        if ((value & ~0x7FL) == 0) {
            buffer[position++] = (byte) value;
            return;
        } else {
            buffer[position++] = (byte) (((int) value & 0x7F) | 0x80);
            value >>>= 7;
        }
    }
}
\end{verbatim}

\subsection{ZigZag encoding}
\label{sec:zigzag-encoding}

Encode a ZigZag-encoded 64-bit value.  ZigZag encodes signed integers
into values that can be efficiently encoded with varint.  (Otherwise,
negative values must be sign-extended to 64 bits to be varint encoded,
thus always taking 10 bytes in the buffer.

Parameter \lst{n} is a signed 64-bit integer.
This Java method returns an unsigned 64-bit integer, stored in a signed int because Java has no explicit unsigned support.

\begin{verbatim}
 public static long encodeZigZag64(final long n) {
   // Note:  the right-shift must be arithmetic
   return (n << 1) ^ (n >> 63);
 }
\end{verbatim}