\section{Simultaneous Localization and Mapping}
\label{slam}

In this section, we cover SLAM, and the different concepts related to SLAM such as Visual Odometry. We then explore the two different approaches to SLAM mentioned in the paper. We briefly cover filter based SLAM called MonoSLAM~\cite{davison2007monoslam} and a key-frame based SLAM called Parallel Tracking and Mapping (PTAM)~\cite{klein2007parallel}. A comprehensive analysis of filtering based SLAM is given in~\cite{strasdatavisual}. Simultaneous Localization and Mapping (SLAM) is a technique for estimating the motion of the robot and reconstructing the map/structure of the unknown environment. SLAM using visual information only is specifically referred to as visual SLAM (vSLAM). The SLAM problem can be stated as follows:\\

\textbf{\emph{How can a body navigate in a previously unknown environment while constantly building and updating a map of its workspace using onboard sensors only?} ~\cite{chli2017}}\\

Mathematically, this can be expressed as~\cite{cyrillslam}

Input:\
\begin{equation}
Control\ input:\ u_{1:T} = {u_1, u_2, ...., u_T}
\end{equation}
\begin{equation}
Observations:\ z_{1:T} = {z_1, z_2, ...., z_T}
\end{equation}

Output:\
\begin{equation}
Map\ of\ Environment:\ m
\end{equation}
\begin{equation}
Path\ of\ robot:\ x_{0:T} = {x_0, x_1, ...., x_T}
\end{equation}

From the problem statement above, we notice that the robot has no a priori knowledge of the workspace or environment that it is in. This makes SLAM a very challenging problem in probabilistic robotics. This is also referred to as a chicken-egg problem in that we need to map the environment to get an accurate pose, but at the same time we also need an accurate pose to build a correct map. Therefore, it is an iterative process of estimating pose and building a map simultaneously. Accurate pose estimation is critical for many applications in computer vision, autonomous robotics and augmented reality. A survey of SLAM implementations is given in ~\cite{bresson2017simultaneous,cadena2016past,taketomi2017visual}. The basic modules for a vSLAM system are
\begin{itemize}
\item Initialization
\item Tracking
\item Mapping
\item Relocalization
\item Global Map optimization
\end{itemize}

According to~\cite{scaramuzza2011visual}, the relationship between vSLAM and VO can be represented as follows\\

$vSLAM = VO + global\ map\ optimization$\\

% For one-column wide figures use
\begin{figure}
% Use the relevant command to insert your figure file.
% For example, with the graphicx package use
  \includegraphics[width=\textwidth]{./figures/slam_model.png}
% figure caption is below the figure
\caption{SLAM architecture~\cite{cadena2016past}}
\label{fig:slammodel}       % Give a unique label
\end{figure}

From Fig~\ref{fig:slammodel} we see that a typical SLAM system consists of a front-end and a back-end. The front-end is responsible for feature extraction while the back-end is responsible for map estimation. Both the methods (MonoSLAM \& PTAM) are feature based implementations as they have a camera input.

\subsection{Visual Odometry}

Odometry is the technique of estimating the position of a robot over time using sensors such as cameras,  wheel encoders or any sensor measuring relative movement. Compared to SLAM which maintains a global consistent map, visual odometry (VO) maintains a local consistent map optimized over the last n frames. A generalized VO pipeline can be summarized as follows

% For one-column wide figures use
\begin{figure}[!htb]
% Use the relevant command to insert your figure file.
% For example, with the graphicx package use
  \includegraphics[width=\textwidth,height=5cm,keepaspectratio]{./figures/vo.png}
% figure caption is below the figure
\caption{Generalized Visual Odometry Pipeline~\cite{scaramuzza2011visual}}
\label{fig:vo}       % Give a unique label
\end{figure}

Different algorithms exist due to the different type of cameras available such as Stereo, Mono, RGB-D~\cite{fraundorfer2012visual,scaramuzza2011visual}. As we use a monocular setup in our research paper, we would be going through the visual odometry algorithm from 2D to 2D correspondences for a monocular sensor. The algorithm is summarized as follows~\cite{scaramuzza2011visual}.

\begin{algorithm}[H]
    \caption{Monocular Visual Odometry}
	\begin{algorithmic}[1]
		\STATE Capture a new image frame $I_k$
    	\STATE Extract and match features between frames $I_k$ and $I_{k-1}$
    	\STATE Compute the essential matrix $E$ from the matched feature points
    	\STATE Decompose $E$ into $R_k$ and $t_k$ to form $T_k$
    	\STATE Choose the correct $T_k$ matrix and scale $t_k$ accordingly from scale factor
    	\STATE Compute $C_k$ = $C_{k-1}*T_k$
    	\STATE Goto step 1.
	\end{algorithmic}
\end{algorithm}

Since we are using a monocular sensor, we always compare the image $I_k$ captured at time instant $k$ with the image $I_{k-1}$ capture at time instant $k-1$. In a stereo setup, we would compare images from the left and right part of the stereo. Once an image is captured, we compute the features for image $I_k$ and $I_{k-1}$. In the feature detection step, the image is searched for key-points called features  which are likely to be present in successive images. Features can be defined as image patterns that differ from its immediate neighborhood in terms of intensity, color and texture. There exist a variety of feature detectors in literature which vary in performance and properties. Some of the properties of feature detectors are rotation, scale and affine invariant, repeatability, localization accuracy, robustness and efficiency.  Heitanen et al. present a comparison of feature detectors and descriptors for object class matching in~\cite{hietanen2016comparison}. Once we detect features, we then need to compute a descriptor such that features detected in two images can be compared with each other. The easiest approach would be to form a patch of pixels and compare using a sum of squared distances (SSD) or normalized cross correlation (NCC) metric. Such descriptors are not invariant to any of the above mentioned properties and perform poorly in practical applications. One of the popular descriptors called SIFT~\cite{lowe2004distinctive} uses gradient orientations as its descriptors. This forms a 128-element descriptor that is invariant to most of the above mentioned properties such as rotation, scale and illumination which makes it widely applicable in practical real-time applications. For extracting features from two images there are two paths with one being to detect and match features independently in two frames and the other being to track features in subsequent frames an example of which is a KLT Tracker~\cite{tomasi1991detection}. There are various methods employed to match features accurately such a RANSAC which stands for Random Sample Consensus and is used to remove outliers among feature matches. Once we detect and match features in $I_k$ and $I_{k-1}$, we calculate the essential matrix $E$ which describes the geometric relationship between two images. We can use Nister’s five point algorithm~\cite{nister2004efficient} or Longuet-Higgins eight point algorithm~\cite{longuet1981computer} to get the essential matrix $E$. Once we get the essential matrix $E$, we decompose it to extract the rotation and translation parts. Four different solutions are obtained of which the correct pair can be found out by triangulation. The solutions are given as

\begin{equation}
	R = U(\pm W^T)V^T
\end{equation}
\begin{equation}
	t = U(\pm W^T)SV^T
\end{equation}

where R is the rotation matrix and t is the translation vector.

\subsection{MonoSLAM}

MonoSLAM was developed by Davison et al.~\cite{davison2003real,davison2007monoslam}. It uses EKF as an estimator. In EKFSLAM, the state \textbf{x} space is represented by the robot state $\hat{x_\nu}$ along with the position of the different landmarks $\hat{y_i}$ that the robot observes. The state vector along with the covariance matrix can be represented as follows

\begin{equation}
\hat{x} =
\begin{pmatrix}
  \hat{x_\nu} \\
  \hat{y_1} \\
  \hat{y_2} \\
  : 	\\
 \end{pmatrix}
P =
\begin{pmatrix}
  P_{xx} & P_{xy1} & P_{xy2} & \cdots \\
  P_{y1x} & P_{y1y1} & P_{y1y2} & \cdots \\
  P_{y2x} & P_{y2y1} & P_{y1y2} & \cdots \\
  : & :     &     :     & \cdots \\
 \end{pmatrix}
\end{equation}

The covariance matrix is used to represent the first order uncertainty. As the robot moves around, new features are added to the state vector. It is important to note that the robot initialization is done by using a known object. The prediction and correction steps are performed as mentioned in the EKF algorithm in section~\ref{ekf_section}. One of the problems with this method is that the state vector becomes large when the number of land marks or key-points tracked increases. This increases the computation time.

\subsection{Parallel Tracking and Mapping (PTAM)}
\label{ptamtheory}

PTAM is a SLAM system specifically designed to track a hand-held camera in a small AR workspace. For real-time operation, PTAM splits the tracking and mapping threads into two separate tasks running in parallel. The tracking thread robustly tracks hand-held motion and the mapping thread produces a 3D map of the features. Although developed specific to AR applications, the concept of running operations on multiple threads was incorporated into future SLAM algorithms.

The map consists of a collection of key-points/features that are located in a world frame $W$. They are represented in the homogeneous form. The map also contains key-frames which a instances of the frames taken from the hand-held camera. Each point is stored with a source key-frame. Unlike earlier methods which process each and every frame, this method only processes frames when there is sufficient information. Thus incremental mapping is replaced with a more computationally expensive batch method called bundle adjustment.

The tracking algorithm can be summarized as follows.

\begin{algorithm}
    \caption{PTAM - Tracking Algorithm}
    \begin{algorithmic}[1]
		\STATE A new frame is captured and a prior pose estimate is generated from motion model.
    	\STATE Map points are projected into the image based on prior pose.
    	\STATE Small number of features (50) are searched in the image.
    	\STATE The camera pose is updated from the feature matches.
    	\STATE Large number of points is re-projected and searched in the image.
    	\STATE Final pose estimate is computed from all matched found.
    	\STATE Goto step 1.
    \end{algorithmic}
\end{algorithm}

PTAM is initialized by a lateral offset movement of the hand-held camera. This can be assumed as a stereo image for starting the mapping. The initial map is constructed using the 5 point algorithm~\cite{nister2004efficient} with arbitrary scale. As the camera moves, the key-frames increase from an initial two. Here, we only add key-frames if the tracking quality is good and a minimum of twenty frames has passed from the last keyframe. Bundle adjustemnt is iteratively performed to adjust the map based on a cost function. The mapping algorithm can then be summarized as.

\begin{algorithm}
    \caption{PTAM - Mapping Algorithm}
	\begin{algorithmic}[1]
		\REQUIRE \mbox{Stereo Initialization}
		\IF {New Keyframe}
			\STATE Update key-frame
			\STATE Integrate key-frame
			\STATE Add new features
		\ELSIF {Locally Converged}
			\IF {Globally Converged}
				\STATE Update data association
			\ELSE
				\STATE Global bundle adjust
			\ENDIF
		\ELSE
			\STATE Locally bundle adjust
		\ENDIF
		\STATE Sleep 5ms
		\STATE Goto step 1.
	\end{algorithmic}
\end{algorithm}

Finally when compared with Filter based SLAM, PTAM can handle thousands of features by splitting the tracking and mapping onto different threads on the CPU. We see that SLAM algorithms built now-a-days have used this philosophy to great success.

\subsection{Results}
\subsubsection{Simulated and Real Data}

In the paper, the Kalman filter was simulated offline with simulated data from the spline fitting section. The two inputs to the Kalman filter were the position from the vision sensor and acceleration from the IMU. Three different approaches were taken. The first method is same as Eq. 7, the second method only uses the Z-axis which gives the states as $[\overrightarrow{x}_z, \overrightarrow{\nu}_z, \overrightarrow{\alpha}_z, \lambda]$ and the third uses only the X and Y-axis.

% For one-column wide figures use
\begin{figure}
% Use the relevant command to insert your figure file.
% For example, with the graphicx package use
  \includegraphics[width=\textwidth]{./figures/ekfTest.png}
% figure caption is below the figure
\caption{Offline simulation results with simulated and real data. Fewer directions (X,Y,Z) included in Kalman filter gives us a better estimate of $\lambda$.~\cite{nutzi2011fusion}}
\label{fig:ekf1}       % Give a unique label
\end{figure}

Figure~\ref{fig:ekf1} shows the scale estimation $\lambda(t)$ for a simulated 3D path on left and actual path on right. The standard deviation for the acceleration noise for simulation was chosen same as real data($\sigma_{SLAM} = 0.01, \sigma_{IMU} = 0.2 m/s^2$) with initial velocity and acceleration set to zero. Plots in Fig.~\ref{fig:ekf1}a and Fig.~\ref{fig:ekf1}c do not differ significantly due to simulating the acceleration from the spline ideally in world frame. The estimate becomes more accurate when we use less number of directions (X,Y,Z).  Wrong measurements in acceleration influence $\lambda$ and make the scale estimation sensitive as seen in Fig.~\ref{fig:ekf1}b. Hence only using a single axis (Z-axis) gives us the best result.

\subsubsection{Online Implementation}

For the online implementation, the third setup was incorporated into the PTAM code~\cite{ptamcode}. As mentioned in section~\ref{ptamtheory} PTAM employs two parallel threads called Tracker for tracking and MapMaker for mapping. Two additional threads for IMU and Kalman we added. The IMU thread provides the acceleration measurements. The Kalman thread starts with $\lambda$ calculated from integrating acceleration values, position from SLAM algorithm and acceleration and velocity set to zero. Values for covariance matrix \textbf{Q} is time-varied which provides control over the sensitivity of the Kalman filter. For our report we have not incorporated the online implementation and have reported results from the paper.

% For one-column wide figures use
\begin{figure}
% Use the relevant command to insert your figure file.
% For example, with the graphicx package use
  \includegraphics[width=\textwidth]{./figures/onlineEKF.png}
% figure caption is below the figure
\caption{Online implementation with PTAM work flow.Blue color boxes are original PTAM threads. Yellow boxes are added threads for scale estimation $\lambda$.~\cite{nutzi2011fusion}}
\label{fig:ekf2}       % Give a unique label
\end{figure}


\subsubsection{Mixed Cell Radionuclide Mass Balance Model}\label{sec:mixed_cell}

Slightly more complex, the Mixed Cell model incorporates the influence of
porosity, elemental solubility limits, and sorption in addition to the
degradation behavior of the Degradation Rate model. A graphical representation
of the discrete sub-volumes in the mixed cell model is given in Figure
\ref{fig:deg_sorb_volumes}.

\input{./nuclide_models/mass_balance/mixed_cell/deg_sorb_volumes}

After some time degrading, the total volume in the degraded region $(V_d)$ can be
expressed as in equation \eqref{deg_volumes}. Additionally, given a volumetric
porosity, $\theta$, the intact and degraded volumes can also be described in
terms of their constituent solid matrix $(V_{is} + V_{ds})$ and pore fluid
volumes $(V_{if} + V_{df})$,

\begin{align}
V_d(t_n) &= \mbox{ degraded volume at time }t_n [m^3]\nonumber\\
          &= V_{df}(t_n) + V_{ds}(t_n)
\intertext{where}
V_{df}(t_n) &= \mbox{ degraded fluid volume at time }t_n[m^3]\nonumber\\
       &= \theta V_d(t_n)\\
       &= \theta d(t_n) V_T
\end{align}
\begin{align}
V_{ds}(t_n) &= \mbox{ degraded solid volume at time }t_n [m^3]\nonumber\\
       &= (1-\theta) V_d(t_n)\\
       &= (1-\theta) d(t_n) V_T
\end{align}
\begin{align}
V_i(t_n) &= \mbox{ intact volume at time }t_n [m^3]\nonumber\\
       &= V_{if}(t_n) + V_{is}(t_n)
\end{align}
\begin{align}
V_{if}(t_n) &= \mbox{ intact fluid volume at time }t_n [m^3]\nonumber\\
       &= \theta V_i(t_n)\\
       &= \theta (1-d(t_n))V_T
\intertext{and}
V_{is}(t_n) &= \mbox{ intact solid volume at time }t_n [m^3]\nonumber\\
       &= (1-\theta) V_i(t_n)\\
       &= (1-\theta) (1-d(t_n))V_T.
\end{align}

This model distributes contaminant masses throughout each sub-volume of the
component. Contaminant
masses and concentrations can therefore be expressed with notation indicating
in which volume they reside, such that

\begin{align}
C_{df} &= \frac{m_{df}}{V_{df}} \label{c_df}\\
C_{ds} &= \frac{m_{ds}}{V_{ds}} \label{c_ds}\\
C_{if} &= \frac{m_{if}}{V_{if}} \label{c_if}\\
C_{is} &= \frac{m_{is}}{V_{is}}.  \label{c_is}
\intertext{where}
        df = \mbox{degraded fluid}\\
        ds = \mbox{degraded solid}\\
        if = \mbox{intact fluid}\\
        is = \mbox{intact solid.}
\end{align}

The contaminant mass in the degraded fluid ($m_{df}$) is the contaminant mass that is
treated as ``available'' to adjacent components. That is, $m_{df}$ is the mass
vector $m_{ij}$ which has been released by component $i$ and can be transferred
to component $j$ in the following mass transfer phase.

\paragraph{Sorption}

The mass in all volumes exists in both sorbed and non-sorbed phases. The
relationship between the sorbed mass concentration in the solid phase (e.g. the
pore walls),

\begin{align}
s &=\frac{\mbox{ mass of sorbed contaminant} }{ \mbox{mass of total solid phase }}
\label{solid_conc}
\end{align}
and the dissolved liquid concentration,
\begin{align}
C &=\frac{\mbox{ mass of dissolved contaminant} }{ \mbox{volume of total liquid phase }}
\label{liquid_conc}
\end{align}
can be characterized by a sorption ``isotherm'' model. A sorption isotherm
describes the equilibrium relationship between the amount of material bound to
surfaces and the amount of material in the solution. The Mixed Cell mass
balance model uses a linear isotherm model.

With the linear isotherm model, the mass of contaminant sorbed onto the
solid phase, also referred to as the solid concentration, can be found
\cite{schwartz_fundamentals_2004}, according to the relationship
\begin{align}
s_p &= K_{dp} C_{p}
\label{linear_iso}
\intertext{where}
s_p &= \mbox{ the solid concentration of isotope p }[kg/kg]\nonumber\\
K_{dp} &= \mbox{ the distribution coefficient of isotope p}[m^3/kg]\nonumber\\
C_p &= \mbox{ the liquid concentration of isotope p }[kg/m^3].\nonumber
\end{align}

Thus, from \eqref{solid_conc},

\begin{align}
s_{dsp} &= K_{dp} C_{dfp}\nonumber\\
         &= \frac{K_{dp}m_{dfp}}{V_{df}}\nonumber
\intertext{where}
s_{dsp} &= \mbox{ isotope p concentration in degraded solids } [kg/kg] \nonumber\\
C_{dfp} &= \mbox{ isotope p concentration in degraded fluids } [kg/m^3]. \nonumber
\end{align}

In this model, sorption is taken into account throughout the volume. In the
intact matrix, the contaminant mass is distributed between the pore walls and
the pore fluid by sorption.  So too, contaminant mass released from the intact
matrix by degradation is distributed between dissolved mass in the free fluid
and sorbed mass in the degraded and precipitated solids. Note that this model is
agnostic to the mechanism of degradation. It simulates degradation purely from
a rate and release is accordingly congruent \cite{kawasaki_congruent_2004} with
that degradation.

To begin solving for the boundary conditions in this model, the amount of non-sorbed
contaminant mass in the degraded fluid volume must be found. Dropping the
isotope subscripts and beginning with equations \eqref{c_df} and \eqref{linear_iso},

\begin{align}
m_{df} &= C_{df}V_{df}
\intertext{and assuming the sorbed material is in the degraded solids}
m_{df} &= \frac{s_{ds}V_{df}}{K_d},\nonumber\\
\intertext{then applying the definition of $s_{ds}$ and $m_{ds}$}
m_{df} &= \frac{\frac{m_{ds}}{m_T}V_{df}}{K_d}\nonumber\\
       &= \frac{(dm_T-m_{df})V_{df}}{K_dm_T}.\nonumber
\intertext{This can be rearranged to give}
m_{df} &= \frac{dV_{df}}{K_d}\frac{1}{\left( 1+ \frac{V_{df}}{K_dm_T}\right)}\nonumber\\
       &= \frac{dV_{df}}{\left( K_d+ \frac{V_{df}}{m_T}\right)}.
\intertext{Finally, using the definition of $V_{df}$ in terms of total volume,}
m_{df} &= \frac{d^2 \theta V_T}{K_d + \frac{d \theta V_T}{m_T}}.
       \label{sorption}
\end{align}

\paragraph{Solubility}
Dissolution of the contaminant into the
available fluid volume is constrained by the
elemental solubility limit.
The reduced mobility of radionuclides with lower
solubilities can be modeled \cite{hedin_integrated_2002} as a reduction in the
amount of solute available for transport, thus:

\begin{align}
  m_{i}(t)&\le V(t)C_{sol, i}\label{sol_lim}
  \intertext{where}
  m_{i} &= \mbox{ mass of isotope i in volume }V [kg]\nonumber\\
  V &= \mbox{ a distinct volume of fluid } [m^3]\nonumber\\
  C_{sol, i} &= \mbox{ the maximum concentration of i } [kg\cdot m^{-3}].\nonumber
\end{align}

That is, the mass $m_{i}$ in  kg of a radionuclide $i$ dissolved into the waste package
void volume $V_1$ in m$^3$, at a time t, is limited by the solubility limit,
the maximum concentration, $C_{sol}$ in kg/m$^3$ at which that radionuclide is
soluble \cite{hedin_integrated_2002}.

The final available mass is therefore the $m_{df}$ from equation
\eqref{sorption} constrained by:
    \begin{align}
      m_{df,i} &\leq V_{df} C_{sol,i}
      \label{solubility}
    \intertext{where}
      m_{df,i} &= \mbox{ solubility limited mass of isotope i in volume }V_{df} [kg]\nonumber\\
      C_{sol,i} &= \mbox{ the maximum dissolved concentration limit of i }[kg/m^3].\nonumber
    \end{align}


% Example taken from the InfO(1)Cup contest 2022.
\documentclass[en]{problem}

\title{Aplusb}

\date{11}{2}{2022}
\contest{InfO(1) Cup, Practice Round}
\location{Ploiești, Romania}
\logo{logo.png}

\begin{document}

\maketitle

In order to solve the great \textfrak{Millenium Puzzle}, Yugi must first solve an incredibly difficult mathematical problem! Given two integers $\mathfrak{A}$ and $\mathfrak{B}$, he must compute $\mathfrak{A} + \mathfrak{B}$. Unfortunately he spent all his time at school learning how to play card games, and doesn't know how to do this --- can you help him?

\section{Input data}

The only line of the input contains the two integers $\mathfrak{A}$ and $\mathfrak{B}$.

\section{Output data}

Output $\mathfrak{A} + \mathfrak{B}$ on the first line of the output.

\begin{restrictions}[
\item $1 \leq \mathfrak{A}, \mathfrak{B} \leq \np{1000000000}$.
]
\restr{50}{$1 \leq \mathfrak{A}, \mathfrak{B} \leq 1000$}
\restr{50}{No further restrictions.}
\end{restrictions}

\begin{examples}
\exmp{1 2}{3}%
\exmp{100 200}{300}%
\end{examples}

\end{document}


\documentclass[a4paper,10pt]{article}

\usepackage{amsthm,amsfonts,amsmath,amssymb,amscd}
\usepackage{indentfirst}
\usepackage[usenames]{color}
\usepackage{color}
\usepackage{colortbl}

\usepackage[singlelinecheck=off,center]{caption}
\usepackage{soul}

\usepackage{cite}

\usepackage[plainpages=false,pdfpagelabels=false]{hyperref}
\definecolor{linkcolor}{rgb}{0.9,0,0}
\definecolor{citecolor}{rgb}{0,0.6,0}
\definecolor{urlcolor}{rgb}{0,0,1}
\hypersetup{
    colorlinks, linkcolor={linkcolor},
    citecolor={citecolor}, urlcolor={urlcolor}
}

\usepackage{graphicx}
\graphicspath{{images/}}

\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\ket}[1]{|#1\rangle}
\newcommand{\bra}[1]{\langle#1|}
\newcommand{\ketbra}[2]{\ket{#1}\langle#2|}
\newcommand{\tr}{\ensuremath{{\rm Tr}}}

\begin{document}

\begin{center}
\Large{{\bf Self-check problems on\\  Quantum information processing}\\{\it Part 2: Measurements and evolution}}\\
\vspace{5pt}
\large{Last update: \today}
\end{center}

\subsection*{Problem 1}
Consider a qubit, called ``system'', in some pure state $\ket{\psi_{0}}$, and another qubit, called ``probe'', in the initial state $\ket{0}$.
Let the system and the probe interact according to a Hamiltonian
\begin{equation}
	V=\frac{1}{2}\sigma_{z}\otimes\sigma_{y}
\end{equation}
for time period $t$ (the first tensor factor corresponds to the first qubit, the second factor -- to the probe).
Let then the probe be measured in $\{\ket{+}, \ket{-}\}$ basis (remember, that it corresponds to projective $\sigma_{x}$measurement).
\begin{enumerate}
	\item Find evolution of the initial state for cases $\ket{\psi_{0}}=\ket{0}$ and $\ket{\psi_{0}}=\ket{1}$.
	Draw pictures of evolution of Bloch vectors for the system and the probe for the both cases.
	\item Consider the general case of $\ket{\psi_{0}}=\alpha\ket{0}+\beta\ket{1}$. Find the reduced state of the system and probe.
	How do the Bloch vectors of the system and the probe evolve in this general case?
	What we can say about entanglement between the system and the probe? (Remember, that entanglement of a pure bipartite state is characterized by mixedness of its parties.)
	\item Consider the case $\ket{\psi_{0}}=\ket{0}$ and find probabilities of obtaining outcomes $+1$ and $-1$ in the $\sigma_{x}$-measurement of the probe as function of time $t$.
	What about the case $\ket{\psi_{0}}=\ket{1}$?
	\item Let's consider the general case $\ket{\psi_{0}}=\alpha\ket{0}+\beta\ket{1}$ again. Let at time $t=\frac{\pi}{2}$ the probe be measured in the state $\ket{+}$ (with a corresponding outcome +1). What will be the resulting ``collapsed'' state of the system in this case? Consider the same story but with $t=\frac{\pi}{4}$. How the collapsed state changed?
	\item Consider the case $\ket{\psi_{0}}=\ket{+}$ and $t=\frac{\pi}{2}$. Let the system be given to Alice, and the probe -- to Bob. Remember what is the state of Alice's particle (you have calculated it already).
	Let Bob measure $\sigma_{x}$ of the probe, but keep the result of his measurement in a secret from Alice.
	What is an ``effective'' state of Alice's particle (the system) without this information?
	Let then Bob phone Alice and tell that he obtained +1 outcome in his measurement (we assume that Bot is honest).
	What is the state of Alice's particle now?
	\item Think a bit about the statement ``Information is physical'' :-)
	\item Find POVM realized on the system by projective measurement of the probe for $t=\frac{\pi}{2}$, $t=\frac{\pi}{4}$.
\end{enumerate}

\subsection*{Problem 2}
Consider a qubit POVM
\begin{equation}
	M = \left\{\frac{1}{2}\ket{0}\bra{0}, \frac{1}{2}\ket{1}\bra{1}, \frac{1}{2}{\bf 1}\right\}
\end{equation}
(here ${\bf 1}$ is a $2\times 2$ identity matrix).
\begin{enumerate}
	\item Check that $M$ is a valid POVM.
	\item Design a projective measurement, which corresponds to the given POVM, in an extended space obtained by considering qubit states as states of some 4-level system.
	\item Design a projective measurement, which corresponds to the given POVM, on a two qubit state $\rho\otimes\ket{0}\bra{0}$ (here $\rho$ is a states measured with POVM).
\end{enumerate}

\subsection*{Problem 3}
Consider a realistic single-photon detector.
Let the input state coming to detector live in the two-dimensional Hilbert space spanned by vectors $\ket{0}$ (no photon) and $\ket{1}$ (one photon).
Our detector is characterized by two parameters: efficiency $\eta\in [0,1]$ (probability that incoming photon will be observed by the detector), and dark-count probability $p_{\rm dark}\in[0,1]$ (probability that in a given time-window the detector will ``click'' regardless presence of photon in the input channel).
Write down POVM elements corresponding to outcomes ``click'' and ``no click'' of the detector.
How the POVM will change if we extend the space of input states to higher photon numbers ($\ket{2}, \ket{3}, \ldots$)?

\subsection*{Problem 4}
Design a construction of SIC-POVM elements for arbitrary $d$-dimensional Hilbert space ($d>2$).

\subsection*{Problem 5}
Consider a three-qubit system where the first qubit is prepared in an arbitrary state $\rho$ and two other qubits in the fixed state $\ket{00}_{2,3}$.
Let the initial state of qubits be affected by unitary operator
\begin{equation}
	U = \ket{000}_{1,2,3}\bra{000} +  \ket{111}_{1,2,3}\bra{100} + \ldots.
\end{equation}
Find Kraus operators of a map $\Phi_{1\rightarrow 3}[\cdot]$ which outputs the resulting state of the third qubit depending on the initial state of the first qubit $\rho$.
Find Kraus operators of a dual map $\Phi_{1\rightarrow (1,2)}[\cdot]$ which outputs the resulting state of the first and the second qubits depending on the initial state of the first qubit $\rho$.
Check that the obtained operators satisfy normalization condition.

\subsection*{Problem 6}
Let $\Phi[\rho]=\sum_{i}A_{i}\rho A_{i}^{\dagger}$ be a CPTP map.
Let $u_{i,j}$ be elements of some unitary matrix $U$, and $B_{i}=\sum_{i}u_{ij}A_{j}$.
Show that $\Phi[\rho]=\sum_{i}B_{i}\rho B_{i}^{\dagger}$.

\subsection*{Problem 7}
Consider a CPTP map $\Phi[\cdot]$ and a corresponding Choi state
\begin{equation}
	\rho_{\rm Choi} = \sum_{i,j} \ket{i}_{1}\bra{j}\otimes\Phi[\ket{i}_{2}\bra{j}]
\end{equation}
(here $\{\ket{i}\}$ is a orthonormal basis for the Hilbert space of inputs).
Show that the action of $\Phi[\cdot]$ on some input state $\rho$ is given by
\begin{equation}
	\Phi[\rho]=\tr_{1}(\rho\otimes {\bf 1} \rho_{\rm Choi}^{\rm T_{1}})=
	\tr_{1}(\rho^{\rm T_{1}}\otimes {\bf 1} \rho_{\rm Choi}),
\end{equation}
where ${\rm T}_{1}$ stands for a partial transpose in ``the first space''.

\subsection*{Problem 8}
Consider a single-qubit Pauli transformation
\begin{equation}
	\rho\rightarrow \sigma_{\alpha}\rho\sigma_{\alpha}, \quad \alpha\in\{x,y,z\}.
\end{equation}
How this transformation affects the Bloch vector of $\rho$?

Show that
\begin{equation}
	\frac{1}{4}\left({\bf 1}\rho{\bf 1}+\sum_{\alpha\in\{x,y,z\}}\sigma_{\alpha}\rho\sigma_{\alpha}\right) = \frac{\bf 1}{2}
\end{equation}
for any $\rho$.

{\bf Hint}: decompose $\rho$ in sum of terms with Pauli matrices.

\subsection*{Problem 9}
Write Choi matrices for dephasing, depolarizing, and damping channels.

\end{document}


\documentclass[a4paper,12pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{bm}
\usepackage{extarrows}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{indentfirst}
\usepackage{fancyhdr}
\usepackage{verbatim}
\usepackage{booktabs}
\usepackage[dvipdfm,colorlinks,linkcolor=blue,citecolor=blue]{hyperref}
\usepackage{natbib}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%defining the bra and ket
\newcommand{\bra}[1]{\langle #1| }
\newcommand{\ket}[1]{|#1 \rangle }

%here the definition used in text
\newcommand{\brat}[1]{$\langle #1|$ }
\newcommand{\kett}[1]{$|#1 \rangle $}

%here define the math bold font for the vector operator:
\newcommand{\hei}[1]{\mathbf{\hat{#1}} }
\newcommand{\heit}[1]{$\mathbf{\hat{#1}}$}
\newcommand{\heiti}[1]{\mathbf{#1} }

%% define the mathbf type of characters
\newcommand{\vect}[1]{$\mathbf{#1}$}

%% define the theorem enviroment for the whole text
\theoremstyle{definition}\newtheorem{law}{Law}
\theoremstyle{plain}\newtheorem{theorem}{Theorem}
\theoremstyle{remark}\newtheorem{remark}{Remark}
\theoremstyle{axiom}\newtheorem{axiom}{Axiom}

%opening
\title{Matrix Element}

\begin{document}

\maketitle
Let's start by considering the equation 10 in Yihan's note, there we generally
have:
\begin{equation}
 \label{eq:1}
\langle\Psi_{I}|\Psi_{J}^{[x]}\rangle = T_{I}T_{J}^{[x]} +
\sum_{ia}\sum_{jb}T_{I,ia}T_{J,jb}\langle\Phi^{a}_{i}|\Phi^{b[x]}_{j}\rangle
\end{equation}
Here in this expression, we follow the general convention that to use $T$ to
represent the Slater determinant coefficients in CIS state, to use $C$ to
designate the MO coefficients, $\Psi$ is used to refer to CIS state, and $\Phi$
means the Slater determinants, $\varphi$ is MO.

For the index, all the capital letters such as $I,J,K,L$ etc. indicates it's
CIS states, and the lowercase letter is used to refer to MO. $\Phi^{a}_{i}$
means the electron is excited from occupied orbital $i$ to virtual orbital $a$.
For simplicity, here in this derivation we omit the spin state.

In (\ref{eq:1}), the first term $T_{I}T_{J}^{[x]}$ generally needs to solve the
CP-CIS equation to get the response for CIS amplitude, now all the remaining
problems now concentrates on $\langle\Phi^{a}_{i}|\Phi^{b[x]}_{j}\rangle$.

\section{The first step: general consideration}
%
%
%
%
For some general Slater determinant, we have:
\begin{equation}
 \label{eq:2}
\Phi = \frac{1}{\sqrt{n!}}
\begin{vmatrix}
   \varphi_{1}(1) & \varphi_{2}(1) & \cdots & \varphi_{n}(1) \\
  \varphi_{1}(2) & \varphi_{2}(2) & \cdots & \varphi_{n}(2) \\
  \cdots & \cdots & \cdots & \cdots                                \\
  \varphi_{1}(n) & \varphi_{2}(n) & \cdots & \varphi_{n}(n) \\
\end{vmatrix}
\end{equation}
For it's derivatives, from mathematical derivation we know that:
\begin{equation}
 \label{eq:3}
\Phi^{[x]} = \sum_{p=1}^{n}\frac{1}{\sqrt{n!}}
\begin{vmatrix}
   \varphi_{1}(1) & \varphi_{2}(1) & \cdots &
  \frac{\partial \varphi_{p}(1)}{\partial \bm{x}} &
   \cdots & \varphi_{n}(1) \\
   \varphi_{1}(2) & \varphi_{2}(2) & \cdots &
   \frac{\partial \varphi_{p}(2)}{\partial \bm{x}} &
   \cdots  & \varphi_{n}(2) \\
   \cdots & \cdots & \cdots & \cdots  & \cdots   & \cdots     \\
   \varphi_{1}(n) & \varphi_{2}(n) & \cdots &
   \frac{\partial \varphi_{p}(n)}{\partial \bm{x}}
   &\cdots & \varphi_{n}(n) \\
\end{vmatrix}
\end{equation}

Firstly, let's think about the second order Slater
determinants. After calculation, it turns out that
$\langle\Phi|\Phi^{[x]}\rangle$ equals to
$\sum_{p}^{2}\langle\varphi_{p}|\varphi^{[x]}_{p}\rangle$. Hence we can suggest
some hypothesis below:
\begin{theorem}
\begin{equation}
\label{eq:8}
 \langle\Phi|\Phi^{[x]}\rangle =
\sum_{p}^{n}\langle\varphi_{p}|\varphi^{[x]}_{p}
\rangle
\end{equation}
establishes for the $nth$ order Slater determinants.
\end{theorem}

Now let's go to prove it by starting from the definition of determinant:
\begin{equation}
 \label{eq:4}
\Phi = \sum_{1\leq i1<i2\cdots<in\leq n}(-1)^{P( i1, i2, \cdots,
in)}\varphi_{i1}(1)\varphi_{i2}(2)\cdots\varphi_{in}(n)
\end{equation}
$P$ is the permutation operator.

Accordingly, for $\Phi^{[x]}$, we have similar expansion:
\begin{equation}
 \label{eq:5}
\Phi^{[x]} = \sum_{p}\sum_{1\leq i1<i2\cdots<in\leq n}(-1)^{P( i1, i2, \cdots,
in)}\varphi_{i1}(1)\varphi_{i2}(2)\cdots\varphi_{p}^{'}(k)\cdots\varphi_{in}(n)
\end{equation}
We use $\varphi_{p}^{'}(n)$ to designate the MO derivatives.

For $\langle\Phi|\Phi^{[x]}\rangle$, we can see; there's always have MO
derivatives in the ket. So generally we have have two cases:
\begin{itemize}
 \item $\ket{\varphi_{p}^{'}}$ and $\bra{\varphi_{p}}$ have same electron
residing on
 \item $\ket{\varphi_{p}^{'}}$ and $\bra{\varphi_{p}}$ have different electron
residing on
\end{itemize}
For the second situation, it's easy to see that $\bra{\varphi_{p}}$ is
impossible to find ``correct'' MO to make the integral equal to $1$. Hence the
whole expression, in the second situation will goes to zero.

For the first situation, it's easy to know that (below $p$ is fixed):
\begin{align}
 \label{eq:6}
&\frac{1}{n!}
\begin{vmatrix}
   \varphi_{1}(1) & \varphi_{2}(1) & \cdots & \varphi_{n}(1) \\
  \varphi_{1}(2) & \varphi_{2}(2) & \cdots & \varphi_{n}(2) \\
  \cdots & \cdots & \cdots & \cdots                                \\
  \varphi_{1}(n) & \varphi_{2}(n) & \cdots & \varphi_{n}(n) \\
\end{vmatrix}
\begin{vmatrix}
   \varphi_{1}(1) & \varphi_{2}(1) & \cdots &
  \frac{\partial \varphi_{p}(1)}{\partial \bm{x}} &
   \cdots & \varphi_{n}(1) \\
   \varphi_{1}(2) & \varphi_{2}(2) & \cdots &
   \frac{\partial \varphi_{p}(2)}{\partial \bm{x}} &
   \cdots  & \varphi_{n}(2) \\
   \cdots & \cdots & \cdots & \cdots  & \cdots   & \cdots     \\
   \varphi_{1}(n) & \varphi_{2}(n) & \cdots &
   \frac{\partial \varphi_{p}(n)}{\partial \bm{x}}
   &\cdots & \varphi_{n}(n) \\
\end{vmatrix} \nonumber \\
&= \frac{1}{n!}\sum_{i}^{n}\langle\varphi_{p}(i)|\frac{\partial
\varphi_{p}(i)}{\partial \bm{x}}\rangle
\times\langle\bigtriangleup^{(p, i)}|\bigtriangleup^{(p,
i)}\rangle \nonumber \\
&= \frac{1}{n}\sum_{i}^{n}\langle\varphi_{p}(i)|\frac{\partial
\varphi_{p}(i)}{\partial \bm{x}}\rangle \nonumber \\
&=  \langle\varphi_{p}|\frac{\partial
\varphi_{p}}{\partial \bm{x}}\rangle
\end{align}
Here we have used the Laplace theorem to expand the Slater determinant, and
in deriving the final conclusion we have used the relation that
electrons are indistinguishable.

Finally, combined with expression in (\ref{eq:3}), we get:
\begin{equation}
 \label{eq:7}
\langle\Phi|\Phi^{[x]}\rangle =
\sum_{p}^{n}\langle\varphi_{p}|\varphi^{[x]}_{p}\rangle
\end{equation}

\section{The second step: considering the CIS Slater determinants}
%
%
%
%
So far what we have demonstrated, is only for two identical determinants; the
only difference is that the one in the ket has MO derivatives.
Generally, for the CIS case, the integration of Slater determinants can have
following four
choices:
\begin{itemize}
\item $\langle\Phi^{a}_{i}|\Phi^{a[x]}_{i}\rangle$, which has been proved
\item $\langle\Phi^{a}_{i}|\Phi^{b[x]}_{i}\rangle$, $a \neq b$
\item $\langle\Phi^{a}_{i}|\Phi^{a[x]}_{j}\rangle$, $i \neq j$
\item $\langle\Phi^{a}_{i}|\Phi^{b[x]}_{j}\rangle$, $i \neq j$ and $a \neq
b$
\end{itemize}
We can analyze each of the situation in the similar way.

For the second case, we may have the following possibilities:
 \begin{itemize}
 \item $\ket{\varphi_{b}^{'}}$, MO derivatives is on orbital b
 \item $\ket{\varphi_{i}^{'}}$, MO derivatives is on orbital i
 \item $\ket{\varphi_{p}^{'}}$, $p \neq i$ and $p \neq b$
\end{itemize}
In the third situation, it's easy to see the integral of
$\langle\Phi^{a}_{i}|\Phi^{b[x]}_{i}\rangle$ definitely goes to
zero. Since the orbital b in the ket can not find its ``pair'' to make the
integral equal to 1. In the second situation,  while the MO derivatives is on
orbital i; for the same reason the integral will go to zero, too. Hence the MO
derivatives can be only on orbital b.

Next, let's consider the bra corresponds to $\ket{\varphi_{b}^{'}}$. It's easy
to see only the integral below is not zero:
\begin{equation}
 \label{eq:10}
\langle\varphi_{a}|\varphi_{b}^{'}\rangle
\end{equation}
Since if we have $\bra{\varphi_{p}}$ ($p \neq a$), then the orbital a in the
bra can not find its corresponding orbital in ket so that to make integral
equal to 1.Hence finally, we see:
\begin{equation}
\label{eq:11}
 \langle\Phi^{a}_{i}|\Phi^{b[x]}_{i}\rangle =
\langle\varphi_{a}|\varphi_{b}^{'}\rangle
\end{equation}
Similarly, for the $\langle\Phi^{a}_{i}|\Phi^{a[x]}_{j}\rangle$ we have:
\begin{align}
\label{eq:12}
 \langle\Phi^{a}_{i}|\Phi^{a[x]}_{j}\rangle &=
\langle\varphi_{i}|\varphi_{j}^{'}\rangle
\end{align}
and by applying the same technique, for the
$\langle\Phi^{a}_{i}|\Phi^{b[x]}_{j}\rangle$ we can see it's always zero.

Finally, we can express (\ref{eq:1}) as:
\begin{equation}
 \label{eq:13}
\begin{split}
 \langle\Psi_{I}|\Psi_{J}^{[x]}\rangle &= T_{I}T_{J}^{[x]} +
\sum_{ia}T_{I,ia}\sum_{p}T_{J,ia}\langle\varphi_{p}|\varphi^{[x]}_{p}\rangle
\nonumber \\
&+\sum_{iab}T_{I,ia}T_{J,ib}\langle\varphi_{a}|\varphi_{b}^{[x]}\rangle
+\sum_{ija}T_{I,ia}T_{J,ja}\langle\varphi_{i}|\varphi_{j}^{[x]}\rangle
\end{split}
\end{equation}

So far we do not consider how to express the response the MO, what we do here
is just to find a way converting the Sater determinants into the MO expression.
In the next step, we will begin to consider the detailed expression of
$\varphi^{[x]}$.

\section{Detailed discussion for $\varphi^{[x]}$}
%
%
%
Generally, the MO can be expressed as:
\begin{equation}
 \label{eq:14}
\varphi_{p} = \sum_{\mu}C_{\mu p}\phi_{\mu}
\end{equation}
Hence the MO derivatives can be expressed as:
\begin{equation}
 \label{eq:15}
\varphi_{p}^{[x]} = \sum_{\mu}C^{[x]}_{\mu p}\phi_{\mu} + \sum_{\mu}C_{\mu
p}\phi^{[x]}_{\mu}
\end{equation}
The $C^{[x]}_{\mu p}$ characterizes the MO response to the external Hamiltonian
change, and as we know; for occupied orbitals virtual part is added in, and for
virtual orbitals the occupied part added in. Hence determining from the
expression of (\ref{eq:13}), it's clear that there will be no MO response terms
appearing in the expression. Hence we can re-express the (\ref{eq:15}) as:
\begin{equation}
 \label{eq:16}
\varphi_{p}^{[x]} = \sum_{\mu}C_{\mu p}\phi^{[x]}_{\mu}
\end{equation}

Now we can bring in the (\ref{eq:16}) into the (\ref{eq:13}) to get the final
expression:
\begin{equation}
 \label{eq:17}
\begin{split}
 \langle\Psi_{I}|\Psi_{J}^{[x]}\rangle &= T_{I}T_{J}^{[x]} +
\sum_{ia}T_{I,ia}T_{J,ia}\sum_{p}^{ALL MO}
\sum_{\mu}\sum_{\nu}C_{\mu p}C_{\nu p}
\langle\phi_{\mu}|\phi^{[x]}_{\nu}\rangle
\nonumber \\
&+\sum_{iab}T_{I,ia}T_{J,ib}\sum_{\mu}\sum_{\nu}C_{\mu a}C_{\nu
b}\langle\phi_{\mu}|\varphi_{\nu}^{[x]}\rangle \nonumber \\
&+\sum_{ija}T_{I,ia}T_{J,ja}\sum_{\mu}\sum_{\nu}C_{\mu i}C_{\nu
j}\langle\phi_{\mu}|\varphi_{\nu}^{[x]}\rangle
\end{split}
\end{equation}

\end{document}


%General Suggestion: Ideally, the documentation of a style checker should
%be around one page.
\section{Paper: Cyclomatic Complexity}

This is a checker to detect functions with high complexity.
High complexity is defined by Mc Cabe's cyclomatic complexity metric.
This metric measures the amount of branches in a function, i.e.
through if and switch conditions.

\subsection{Non-Compliant Code Examples}
\begin{verbatim}
void fail() {
  int x;
  x=5;
  if (x>3) {
  }
  if (x>3) {
  }
  if (x>3) {
  }
}
\end{verbatim}

\subsection{Compliant Solution}
\begin{verbatim}
void pass() {
  int x;
  x=5;
  if (x>3) {
  }
}
\end{verbatim}

\subsection{Parameter Requirements}

CyclomaticComplexity.maxComplexity defines the max value for the complexity analysis.

\subsection{Implementation}

The algorithm searches for each function the number of occurances of:

\begin{verbatim}
  if (isSgIfStmt(node) || isSgCaseOptionStmt(node) || isSgForStatement(node) || isSgDoWhileStmt(node) || isSgWhileStmt(node)) {
    complexity++;
  }
\end{verbatim}

\subsection{References}

\htmladdnormallink{McCabe}{} , ``Thomas McCabe, A Complexity Measure - IEEE Transactions on Software Engineering, Vol SE-2, No.4, December 1976.''


\documentclass [11pt, proquest] {thesis}[2015/03/03]

\setcounter{tocdepth}{1}  % Print the chapter and sections to the toc

\include{macros}

%\usepackage{fullpage}
\usepackage{hyperref}
\usepackage{microtype}
\usepackage{mathtools}
\usepackage[usenames,dvipsnames]{color}
\usepackage[pdftex]{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{url}
%\usepackage{thmtools}
%\usepackage{thm-restate}

\includeonly{
chapters/1_introduction,
chapters/2_outline_and_results,
chapters/3_background,
chapters/4_main_theorem,
chapters/5_zero_sums,
chapters/6_remarks_future_work,
}

\newcommand{\NN}{\mathbb{N}}
\newcommand{\B}{\mathcal{B}}
\newcommand{\qedb}{\hfill $\blacksquare$}
\newcommand{\nrm}[1]{\left\|#1\right\|}
\newcommand{\pr}{^{\prime}}
\newcommand{\Les}{L_E(s)}
\newcommand{\Lams}{\Lambda_E(s)}
\newcommand{\Lfs}{L(f,s)}
\newcommand{\ldLes}{\frac{L_E\pr}{L_E}(s)}
\newcommand{\ldLfs}{\frac{L_f\pr}{L_f}(s)}
\newcommand{\ldLe}[1]{\frac{L_E\pr}{L_E}\left(#1\right)}
\newcommand{\ldLf}[1]{\frac{L_f\pr}{L_f}\left(#1\right)}
\newcommand{\ldLam}[1]{\frac{\Lambda_E\pr}{\Lambda_E}\left(#1\right)}
\newcommand{\ldatzero}{\frac{L\pr(E,0)}{L(E,0)}}
\newcommand{\xbar}{\overline{x}}
\newcommand{\ybar}{\overline{y}}
\newcommand{\AGM}{\text{AGM}}
\newcommand{\conj}[1]{\overline{#1}}
\newcommand{\EQ}{E(\QQ)}
\newcommand{\EFp}{E(\Fp)}
\newcommand{\Ensfpe}{E_{\text{ns}}(\FF_{p^e})}
\newcommand{\softO}{\tilde{O}}
\newcommand{\en}[1]{\lVert #1 \rVert}

\DeclareMathOperator{\Li}{Li}
\DeclareMathOperator{\sinc}{sinc}

\usepackage{alltt}  %
\newenvironment{demo}
  {\begin{alltt}\leftskip3em
     \def\\{\ttfamily\char`\\}%
     \def\{{\ttfamily\char`\{}%
     \def\}{\ttfamily\char`\}}}
  {\end{alltt}}

\newtheorem{innercustomthm}{Theorem}
\newenvironment{quotedtheorem}[1]
  {\renewcommand\theinnercustomthm{#1}\innercustomthm}
  {\endinnercustomthm}

\newtheorem{innercustomcor}{Corollary}
\newenvironment{quotedcorollary}[1]
  {\renewcommand\theinnercustomcor{#1}\innercustomcor}
  {\endinnercustomcor}

\newtheorem{innercustomconj}{Conjecture}
\newenvironment{quotedconjecture}[1]
  {\renewcommand\theinnercustomconj{#1}\innercustomconj}
  {\endinnercustomconj}

% metafont font.  If logo not available, use the second form
%
% \font\mffont=logosl10 scaled\magstep1
\let\mffont=\sf
% --- end-of-sample-stuff ---

\begin{document}

% ==========   Preliminary pages
\prelimpages

%
% ----- copyright and title pages
%
\Title{The Zeros of Elliptic Curve $L$-functions: \\
Analytic Algorithms with Explicit Time Complexity}
\Author{Simon Spicer}
\Year{2015}
\Program{UW Mathematics}

\Chair{William Stein}{Professor}{Mathematics}
\Signature{Ralph Greenberg}
\Signature{Neal Koblitz}
\Signature{Bernard Deconinck, GSR}

\copyrightpage

% \titlepage

% --- sample stuff only -----
% unusual footnote not found in a real thesis
% You just use the \titlepage as commented out above

{\Degreetext{A dissertation submitted in partial fulfillment \\of the requirements for the degree of}
 \def\thefootnote{\fnsymbol{footnote}}
 \let\footnoterule\relax
 \titlepage
 }
\setcounter{footnote}{0}

% --- end-of-sample-stuff ---

%
% ----- signature and quoteslip are gone
%

%
% ----- abstract
%
\setcounter{page}{-1}
\abstract{%
Elliptic curves are central objects of study in modern-day algebraic number theory. The problem of how to determine the rank of a rational elliptic curve is a difficult one, and at the time of the writing of this thesis an unconditional general method for doing so is not known. \\

It has been known for decades that contingent on the Birch and Swinnerton-Dyer Conjecture, an algorithm to compute rank exists, but this algorithm has unknown time complexity. In the first part of this thesis we prove that, assuming standard conjectures, an {\it effective} algorithm exists to compute rank with time complexity  that is polynomial in the curve's conductor. This method involves evaluating the $L$-function of the curve in question, and as such is practical for curves with conductors up to $\sim 10^{16}$ on current computer architecture. \\

The second part of this work addresses the question of what can be done when the conductor is too large for the above method to be practical. To this end we exhibit an analytic method to bound rank from above that doesn't rely on directly evaluating an elliptic curve's $L$-function, and as such can be used on curves with very large conductors. Because this method involves sums over the imaginary parts of the zeros of an elliptic curve $L$-function, we also include results concerning the locations thereof, and an exposition of related quantities.
}

\chapter*{Preface}
I have attempted to emphasize accessibility and readability throughout this work. Specifically, no knowledge beyond standard graduate-level complex analysis and algebra is assumed, and advanced knowledge of number theoretic topics is {\it not} required. As such, I hope that the results in this dissertation are accessible to a wide audience, even those at the advanced undergraduate level. Chapter 1 was written specifically to be a gentle introduction to the subject matter of this thesis. \\

For the expert I recommend skipping straight to Chapter 2, wherein the main results are stated. Proofs for these results can be found in Chapters 4 and 5 (from 5.2 onwards). \\

Finally, a note on conjecture dependencies. Many of the results in this work are contingent on the validity of three of the major open conjectures in number theory: the Birch and Swinnerton-Dyer conjecture (BSD), the Generalized Riemann Hypothesis (GRH) and the ABC conjecture (ABC). For ease of exposition, instead of stating explicitly in a result which of the above conjectures are assumed, we will list the three-letter initial of each assumed conjecture after the heading of each result. For example, the following result:
\begin{proposition}[BSD]
A rational elliptic curve with odd parity has a point of infinite order.
\end{proposition}
means that this proposition follows under the assumption that BSD is true.

%
% ----- contents & etc.
%
\tableofcontents
%\listoffigures
%\listoftables  % I have no tables

%%
%% ----- glossary
%%
%\chapter*{Glossary}      % starred form omits the `chapter x'
%\addcontentsline{toc}{chapter}{Glossary}
%\thispagestyle{plain}
%%
%\begin{glossary}
%\item[argument] replacement text which customizes a \LaTeX\ macro for
%each particular usage.
%\item[back-up] a copy of a file to be used when catastrophe strikes
%the original.  People who make no back-ups deserve
%no sympathy.
%\item[control sequence] the normal form of a command to \LaTeX.
%\item[delimiter] something, often a character, that indicates
%the beginning and ending of an argument.
%More generally, a delimiter is a field separator.
%\item[document class] a file of macros that tailors \LaTeX\ for
%a particular document.  The macros described by this thesis
%constitute a document class.
%\item[document option] a macro or file of macros
%that further modifies \LaTeX\ for
%a particular document.  The option {\tt[chapternotes]}
%constitutes a document option.
%\item[figure] illustrated material, including graphs,
%diagrams, drawings and photographs.
%\item[font] a character set (the alphabet plus digits
%and special symbols) of a particular size and style.  A couple of fonts
%used in this thesis are twelve point roman and {\sl twelve point roman
%slanted}.
%\item[footnote] a note placed at the bottom of a page, end of a chapter,
%or end of a thesis that comments on or cites a reference
%for a designated part of the text.
%\item[formatter] (as opposed to a word-processor) arranges printed
%material according to instructions embedded in the text.
%A word-processor, on the other hand, is normally controlled
%by keyboard strokes that move text about on a display.
%\item[\LaTeX] simply the ultimate in computerized typesetting.
%\item[macro]  a complex control sequence composed of
%other control sequences.
%\item[pica] an archaic unit of length.  One pica is twelve points and
%six picas is about an inch.
%\item[point] a unit of length.  72.27 points equals one inch.
%\item[roman]  a conventional printing typestyle using serifs.
%the decorations on the ends of letter strokes.
%This thesis is set in roman type.
%\item[rule] a straight printed line; e.g., \hrulefill.
%\item[serif] the decoration at the ends of letter strokes.
%\item[table] information placed in a columnar arrangement.
%\item[thesis] either a master's thesis or a doctoral dissertation.
%This document also refers to itself as a thesis, although it
%really is not one.
%
%\end{glossary}

%
% ----- acknowledgments
%
\acknowledgments{
By no means did I produce this dissertation in a vacuum. Many individuals have provided critical contributions over the course of my studies, and I am thankful to all of them. However, some I must mention specifically. Sincere thanks must be given to my advisor William Stein, who for many years has provided the patient mentorship and guidance needed to make this dissertation a reality; thank you too to the other members of my dissertation reading committee: Ralph Greenberg, Neal Koblitz and Bernard Deconinck. I would also like to extend a heartfelt thanks to the University of Washington department of Mathematics as a whole, and to the graduate student coordinator Brooke Miller in particular, for supporting me throughout my studies at UW. \\

Beyond this, a number of mathematicians have given valuable advice. I am grateful for the correspondence with Barry Mazur on the explicit formula for elliptic curves, which was my entry point into the whole topic of elliptic curve $L$-functions; moreover I thank Peter Sarnak for his input on low-lying zeros of elliptic curve $L$-functions, and helping spur the formulation of the central idea of this thesis. John Cremona and Noam Elkies gave sage insight on the topics of the real period and regulator respectively. And I am grateful to John Voight, who used an early version of my rank estimation code and highlighted some significant bugs. And thanks must be given to Wei Ho, Jen Balakrishnan, Jamie Weigandt and Nathan Kaplan for putting up with my less-than-expert attempts to compute the ranks of large databases of elliptic curves. \\

And last but not least, a huge thank you to my wife Kimberly for her constant unwavering support throughout.
}

%
% ----- dedication
%
\dedication{\begin{center}To Kimberly and Bram, who comprise two thirds of the Spicer Theorem.\end{center}}

%
% end of the preliminary pages

%
% ==========      Text pages
%
\textpages

% ========== Chapter 1
\chapter{Introduction}
\input{chapters/1_introduction}

% ========== Chapter 2
\chapter{Problem Outline and Major Results}\label{sec:outline_results}
\input{chapters/2_outline_and_results}

% ========== Chapter 3
\chapter{Notation, Definitions and Background}\label{sec:defs_background}
\input{chapters/3_background}

% ========== Chapter 4
\chapter{An Algorithm to Compute Rank}\label{chap:main_theorem}
\input{chapters/4_main_theorem}

% ========== Chapter 5
\chapter{Zero Sums}
\input{chapters/5_zero_sums}

% ========== Chapter 6
\chapter{Remarks and Future Work}
\input{chapters/6_remarks_future_work}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\printendnotes

%
% ==========   Bibliography
%
\nocite{*}   % include everything in the thesis.bib file
\bibliographystyle{acm}
\bibliography{bibliography}
%
% ==========   Appendices
%
\appendix
\raggedbottom\sloppy

% ========== Appendix A

\chapter{Code Repo and Blog Posts}

The analytic rank estimation code mentioned in this thesis is hosted on GitHub, and is accessible to all free of charge under the GNU General Public License.

\begin{itemize}
\item The repo can be found at
\begin{description}
\item[] \verb%https://github.com/haikona/GSoC_2014%
\end{description}
The relevant Sage Trac ticket is
\begin{description}
\item[]\verb%http://trac.sagemath.org/ticket/16773%
\end{description}

\item Moreover, as it was being written the code was blogged about extensively; the posts on various aspects of the code's functionality can be found at
\begin{description}
\item[]  \verb%http://mathandhats.blogspot.com/%
\end{description}

\end{itemize}

\vita{Simon Spicer was born and raised in Johannesburg, South Africa, but has spent the past six years in Seattle pursuing his mathematics PhD at the University of Washington. At the time of completing this thesis he and his wife Kimberly have just welcomed their first child, Bramwell, into the world. In his spare time Simon enjoys writing code, piloting airplanes and attempting to teach his family Afrikaans.}

\end{document}


%!TEX root = ../main.tex

This chapter covers the steps needed to produce the wanted results. The input needed is a fiducial marker $M$ to provide the object position in the real world; and a 3D mesh $O$ which will be rendered in Augmented Reality. The output is a set of light sources $L_i$, each one having a position, orientation, intensity, color, type and size. In order to complete the luminance ($L()$) analysis a 360 panoramic image is required, but it will be generated as a previous step, it is not necessary to have one beforehand. The entirety of the process is layed out in the flowchart in Figure 1, and each step is described in more detail afterwards.

\begin{figure}[H]
  \centering
  \setlength{\unitlength}{\textwidth}
    \begin{picture}(1,0.5)
       \put(-0.1,0){\includegraphics[width=1.3\unitlength]{Figures/Flowchart.png}}

    \end{picture}
    \caption{The method in a nutshell}
\end{figure}

\section{Capture 360 panoramic image}
In this work panoramic images are used as a tool, therefore it's not within the scope of the method to define a new way of capturing 360 images. The implementation will be based on the one by Chuang et al. \cite{ThreeSixty}
$M$ will provide the origin of the virtual world for placing and orienting $O$ within it. In order for the lights to be mapped to the same position as $M$ the user will be asked to place the marker in the desired position and start capturing the environment while the marker is centered in frame. This will also simplify calculations of light orientations later on.

\section{Image processing}
Once the panoramic image exist the first step in order to be able to analyze the luminance is to get rid of the chromatic information. This is achieved with the following equation:

\begin{equation}
    L(R_{ij},G_{ij},B_{ij}) = 0,2126 \times R_{ij} + 0,7152 \times G_{ij} + 0,0722 \times B_{ij}; \quad \forall \  P_{ij}
\end{equation}

Where $L$ is the luminance obtained at D65 white point and $P$ is the pixel in the $i,j$ position of the image \newline
The contrast ratio has to be adjusted, so that the regions with high luminance are more clearly differentiable.

\begin{equation}
     g(i,j) = \alpha \times f(i,j) + \beta
\end{equation}

Where $g(i,j)$ is the adjusted image, $f(i,j)$ is the original grayscale image and $\alpha$ and $\beta$ are the brightness and contrast constants, determined by parameter tuning. The parameter tuning will be carried out in a trial and error way, propose initial extreme values and run the program, changing the values in order to achieve the best result.
In order to prevent outlier pixels and noise from causing false positives, let $g(i,j)$ be normalized like so:

\begin{equation}
    L(P_{ij}) = \frac{ 2 \times P_{ij} }{min(L) + max(L)}
\end{equation}

Where $min(L)$ and $max(L)$ are the overall minimum and maximum luminance values in the image.
\newline
The result of these steps is a black and white image with the rough shape of the light source. If the image ends up completely black it means there are no important visible light sources and ambient illumination alone would give a good enough result on the rendered model. A region of high luminance is defined as follows:

\begin{equation}
    R(H) = \{p_{00}, p_{01}, ... , p_{mn}\}
\end{equation}
 Where $p_{ij}$ is the pixel in the i,j position of the image. Such that
\[
    L(p_{ij}) > 0.9 \times max(L(p_{ij}))
\]

The region must also be continuous, so the pixels must be adjacent.\newline
If there are regions of high luminance in the image, they would be discovered with a fair amount of noise and artifacts, caused by clear objects, reflections of light sources on highly reflective surfaces, or even light sources that are so far away in the distance that don't really contribute an important amount of light to the area of interest. Therefore it's necessary to also add a relative size constraint to the definition. What constitutes an acceptable region size to deem the light source is not an easy question to answer. The best approach to face this problem is to define it as a percentage of the width and height of the overall image and tune the parameter in search for the best solution. The size constraint would therefore be:

\begin{equation}
    width(R(H)) \times height(R(H)) \geq k \times W \times H
\end{equation}

Where $k$ is the parameter to be tuned; $W$ and $H$ are the total image width and height.\newline

These constraints also help keep the amount of lights to be processed within an acceptable range for a real-time application, even if the real environment has many light sources a simplification of them is necessary when modelling them to keep the application feasible. Once the relevant light sources have been identified their properties need to be calculated.

\section{Calculate light properties}
The properties needed to calculate for each light are position, orientation, intensity, size and color. In the real world it is not trivial to calculate the position and size at the same time, because at least one of them would have to be known. Fortunately in the virtual world this is not necessary, as long as it is consistent, for the area size of the light the pixel measures can be used. With this in mind all the other properties can be calculated.

\begin{enumerate}
\item Width and height: The pixel measures will be used for this, they can me determined from the size constraint in the previous step.
\item Position: It is possible to calculate the distance from and object to a camera lens knowing a few parameters from the lens, namely the focal length and the sensor size. In Android these values are easily obtainable through the ExifInterface class. In iOS the values are publicly known per device family, so it's possible to create a lookup table with the values and have the application ask what device it's running on to match the necessary set of values. The calculation is then done as follows:

\begin{equation}
    d(L_i) = \frac{ f \times h_i}{sensorHeight}
\end{equation}

\item  Orientation: Since the user was enforced to capture the environment starting from the north and the environment is the entire 360 degrees it is easy to map the pixel width to the angle of incidence of the light source. We can for example define the following ratio to calculate the angle:

\begin{equation}
    \phi = \frac{pos(L_i)_x \times 180}{imageWidth \times 0.5}
\end{equation}

\item Color: Storing both versions of the panorama, one in full color and another one after processing will allow us to have both the color and the luminance information. Once a light source is detected, the equivalent area in the color image can be averaged to determine the color of the light source.
\item Type: There are two main shapes of lamps in the real world, quadrilateral and elliptical. It is indeed possible to find lights with more complex shapes, however, as long as the area of emission is the same, simplifying it to a quadrilateral or elliptical shape yields the same result for the purposes of the method.
\newline
Determining if the light is a spotlight or an area light will be done through the shape. Elliptical lights will be tagged spotlights and quadrilateral lights area light. Shape detection will be carried out using OpenCV contour detection and counting the vertices of the contour. Even if in the real world the light is a perfect square and the camera is facing it with no parallax it is expected that,  due to artifacts and noise, the function may not find exactly 4 vertices. This is not a big problem, because the number of vertices needed to create smooth circle range in the dozens. So adjusting a threshold value is a simple and acceptable solution.
\end{enumerate}

\section{Calculate ambient light}
Environment mapping is an image-based technique to approximate the appearance of the overall light conditions of an environment. This is accomplished by means of a precomputed texture image mapped as a far-away environment surrounding. Said surrounding is usually a geometric surface, when Blinn first introduced the method\cite{Blinn76} a sphere was used. Nowadays there are other alternatives, such as cube, paraboloid, pyramid or cylinder maps. The principle for each surface is the same, but the way to map a planar image onto the surface varies per surface.\newline
Since a panoramic image of the environment is already available using it to implement environment mapping would be an adequate use of resources. In order to generate an environment map it is necessary that the panorama is made into a High Dynamic Range image. This is because the Low Dynamic Range image captured directly from the device camera fails to capture the information necessary to simulate correct color balance, shadows, and highlights of the lighting environment; ultimately producing both inaccurate and less visually pleasing results. This has been illustrated by Paul Debevec.\cite{DebevecRSO}\newline
A relatively easy and effective way to make an image into an HDR version is a technique called Tone Mapping, in which versions with different exposure values of the same image are blended together to include the full range of highlights and shadows of the overexposed and underexposed versions in a single image. Since asking the user to capture the environment more than once would have a bad impact on user friendliness, and also it's highly unlikely that the produced image would have the exact same framing every time, the different exposure values for the Tone Mapping will be produced altering the brightness and contrast values of the base image using equation 2 once again. After that the HDR image is produced using Debevec's weighting algorithm\cite{Debevec}.\newline
It's important to disclaim that the Tone Mapping process will not yield an actual HDR image. In the first place, it will be a standard 24 bit image in the $0...255$ range, with highlight and shadow valued clipped. The upside to still going through this process nonetheless is that the environment will be described in a richer way, capturing the bright areas and the shadows better than the standard exposure image.\newline
After the HDR version of the panorama is created it can be used to have an actual ground truth about the environment light color and intensity at any given point in the virtual space. This will be detailed in the Real-time Phase step subsection.

\section{Real-time Phase}
Everything proposed in the method may be accurate and could theoretically yield more convincing AR rendering, but it has to be tested in order to determine for sure if that is the case. That is the motivation for implementing a tailor made AR application where all actors come into play to prove or disprove the accuracy and feasibility of the composited virtual objects in the camera feed.\newline
The system is intended to work with ARToolkit, which already has implemented an OpenGL ES 2.0 and an OpenSceneGraph context. OpenGL ES 2.0 allows for great flexibility for lighting, due to the fact that it doesn't have a fixed functionality way to make lighting, a custom made shader has to be made. All the fixed functionality variables from OpenGL, such as the gl\_LightSource array are gone, left for every developer to implement the shader inputs and outputs however they see fit. So there won't be any concerns about getting the light parameters that OpenGL understands, the shader will just read an array of data and as long as the logic is well implemented everything will just work.\newline
The virtual side of the application will have the set of lights, the model $O$ to display and the HDR environment mapped into a cylinder. For the object, a matte diffuse shader, a shiny plastic-like shader and a reflective metal-like shader will be implemented. For performance concerns a refractive glass-like shader or Fresnel effect will not be present. The cylinder with the environment will not be rendered as such, but it will be used to calculate the environment lighting and reflections on the shaders that have reflectivity, to emulate the effect of a raytracer within the OpenGL rasterizer. This effect is achieved with a per-vertex lighting shader.  The reflected color is calculated with the normal vector at a vertex of the surface, and the view vector. The reflection is calculated like so:
\begin{equation}
    R = I - 2\times dot(N,I) \times N
\end{equation}
Where $I$ is the view vector and $N$ is the current vertex normal. GLSL has a shorthand method for equation 8 called reflect().
The light ray that is reflected by the object at the current point of the surface is same as R vector, so using it the color from the environment can be obtained and finally the reflected color is mixed with diffuse color of the object in the proportion defined in the material parameters. \newline
After the color of $O$ the influence of the light sources calculated on the pre-calculation phase on the current vertex will be calculated using Lambert's cosine law.


\documentclass[10pt,a4paper]{book}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\newcommand\tab[1][1cm]{\hspace*{#1}}
\author{Daniel Frederico Lins Leite}
\title{Probability}
\begin{document}
	\section{Introduction}
	\subsection{Subset}

	\subsection{Population}
	A \textbf{population} is defined as a collection of statistical units of the same nature whose quantifiable information we are interested in. The 	population constitutes the reference universe during the study of a given statistical problem.
	\subsection {Sample}
	A \textbf{sample} is a \textit{subset} of a \textit{population} on which statistical studies are made in order to draw conclusions relative to the \textit{population}.
	$w$ is a "sample point".\\
	$S$ is a "sample space" if\\
		\tab $w$ is a "sample point and $w \in S$;\\
		\tab and $\forall_{i,j}{(w_i \cap w_j = \emptyset \text{, if } i \neq j)}$;\\
		\tab and $w_1 \cup w_2 \cup ... \cup w_n = S$.\\
		A is a "family of events" if is a set of "sample points"\\
		\tab $A = \{w\}$ where $w$ is a "sample point"\\
		\tab $A^\complement = \{w : w \notin A\}$\\
		\tab $A \cup B = \{w: w \in A \lor w \in B\}$\\
		\tab $A \cap B = \{w: w \in A \land w \in B\}$\\
		\tab $S^\complement = \emptyset$\\
		\tab $A \cup A^\complement = S$\\
		\tab $A \cap A^\complement = \emptyset$\\
		\tab $A \cap S = A$\\
		\tab $A \cup S = S$\\
		\tab $A \cup \emptyset = A$\\
		\tab $\cup$ is commutative, associative, distributive\\
		\tab $\cap$ is commutative, associative, distributive\\
		P is a "probability measure" if is a mapping between S and the "real numbers" with the following properties:\\
		\tab $P = f: S \mapsto {\rm I\!R}$\\
		\tab $P(A) = f(A)$\\
		\tab $f(S) = \sum_{\forall i}{f(A_i)} = 1$\\
		\tab $0 <= f(A) <= 1$\\
		\tab if $A \cap B = \emptyset$ then $f(A \cup B) = f(A) + f(B).$\\
		\\
		The triplet (S,A,P) defines a "probability system", a consistent axiomatic theory of probability of finite "sample spaces".
		\\
		"Conditional probability" is the probability of "family of events" A, given that the "family of events B" occurred.\\
		$$P(A|B) \triangleq \frac{P(A \cap B)}{P(B)}$$\\
		$A$ and $B$ are "statistical independent" if:\\
		$$P(A \cap B) = P(A)*P(B)$$
		wich can be extended to:\\
		$$ P\big(\bigcap_{\forall i}{ A_i}\big) = \prod_{\forall i}{P(A_i)} $$\\
		Given the last two properties we have that the "conditional property" of two "statistical independent" "family of events" is:\\
		$$ P(A|B) = \frac{P(A \cap B)}{P(B)} = \frac{P(A)*P(B)}{P(B)} = P(A) $$.
		The "Theorem of total probability" states that:\\
		$$P(B) = \sum_{\forall i}{P(A_i|B)}$$

		\section{Reference}
		\begin{enumerate}
			\item {The Concise Encyclopedia of Statistics - Yadolah Dodge}
		\end{enumerate}

\end{document}


\section{Test Plan}
In order to verify the correctness of the system the following tests were made:
\begin{enumerate}
	\item \textbf{Unit Tests}: following the \textbf{bottom-up} strategy, each sub-module (Parallel Multiplier, Ripple Carry Adder Pipelined...), after completing the implementation, has a dedicated testbench in order to check the correctness of the single sub-module in isolation. Considering the fact that this test are \textbf{trivial} (just checking if the sum or the product of some numbers is correct) the single modules were not separately implemented in python. So this part will not be showed in this documentation.
	\item \textbf{System Estimation Test}: in this phase, some testbenches were written with particular inputs. The aim of this test is only to check if the result will resemble the sigmoid curve by varying the inputs in time in an increasing way.
	\item \textbf{System Aimed Test}: after checking that the system is \textit{likely} correct by the latter test, through a python script will be made a test with different inputs in the range considered and check, with an additional testbench, if the outputs are equal.
\end{enumerate}
\subsection{System Estimation Test}
Even before checking the correctness of the output of the system by a given input, three "estimation tests" were made. The aim of these tests is just to obtain a sigmoid curve by setting each $x_{i}$ and $w_{i}$ and varying the bias $b$ in the range of $[-1; +1]$.
\subsubsection{Estimation Test 1}
In this case we have the \textbf{following inputs}:
\begin{equation}
	x_{1} \dots x_{10} = 0, w_{1} \dots w_{10} = 0
\end{equation}
The bias b will vary in the whole range of $[-1, +1]$. Just to remind the sigmoid function curve, we \textbf{expect to obtain a curve with an odd symmetry and a "linear" behaviour}, due to the fact that we are considering the values near zero of the curve:
\begin{figure}[H]
	\centering
	\caption{Sigmoid Function Plot}
	\includegraphics[width=8cm]{img/sigmoid.png}
\end{figure}
The output of the system is the following:
\begin{figure}[H]
	\centering
	\caption{Output of the System 1}
	\includegraphics[width=\textwidth]{img/est_test_1.png}
\end{figure}
There are different replication of the system due to the fact that the bias b will "turn back" when he will get to his maximum. We can state that, by comparing the two figures, the \textbf{first estimation test is passed}.
\subsubsection{Estimation Test 2}
\begin{equation}
	x_{1} \dots x_{10} \approx 1, w_{1} \dots w_{10} \approx 1
\end{equation}
The bias b will vary in the whole range of $[-1, +1]$. \textbf{We expect to obtain a likely flat curve with some "high values"} due to the fact that the summation of the ten product is 10 and the sigmoid at that value tends to 1.
\begin{figure}[H]
	\centering
	\caption{Output of the System 2}
	\includegraphics[width=\textwidth]{img/est_test_2.png}
\end{figure}
The output of the system is similar to a flat curve. We can state that, by comparing the system output with what we expected, the \textbf{second estimation test is passed}.
\subsubsection{Estimation Test 3}
\begin{equation}
	x_{1} \dots x_{10} \approx -1, w_{1} \dots w_{10} \approx 1
\end{equation}
The bias b will vary in the whole range of $[-1, +1]$.\textbf{ We expect to obtain a likely flat curve with some "low values"} due to the fact that the summation of the ten product is -10.
\begin{figure}[H]
	\centering
	\caption{Output of the System 3}
	\includegraphics[width=\textwidth]{img/est_test_3.png}
\end{figure}
The curve is flat with low values but we can notice some \textit{noise}. This is due to the fact that to obtain a proper output some clock cycles are needed: this will lead to obtain intermediate results that are not good. But we can state that, by comparing the system output with what we expected, the \textbf{third estimation test is passed}.
\subsection{System Aimed Test}
At this point will be carried out some tests with the same inputs using the \textbf{Perceptron} architecture realized at this point and a \textit{python script} which will simulate the desired behaviour of the \textbf{Perceptron}. The latter is described through the following script:

\begin{lstlisting}[language=python]
import math

def get_outputs(i, x, w, b):
	print(f"################### TEST #{i} ###################")
	print(f"X: {x}")
	print(f"W: {w}")
	print(f"b: {b}")

	sum = summation(x, w, b)
	print(f"Sum result:\t\t\t\t {sum}")

	f_z = sigmoid_output(sum)
	print(f"Sigmoid output:\t\t\t {f_z}")

	#the sum with 12 bits
	sum_in_circuit = round(sum/lsb_in)
	print(f"Sum value quantized:\t {sum_in_circuit}")

	f_z_in_circuit = round(f_z/lsb_out)
	print(f"Output value quantized:\t {f_z_in_circuit}")

def summation(x, w, b):
	sum = 0
	for i in range(0, 10):
		sum += x[i]*w[i]
	sum += b
	return sum

def sigmoid_output(s):
	res = (1)/(1 + math.exp(-s))
	return res

lsb_out = (1)/(2**15 - 1)
lsb_in = (32)/(2**11 - 1)
#Test #1
x = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
w = [1,1,1,1,1,1,1,1,1,1]
b = 0
get_outputs(1, x, w, b)
...
#Other tests
...
\end{lstlisting}

By running the python script the following output has been displayed in the console:

\begin{lstlisting}
################### TEST #1 ###################
X: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 -10
Sigmoid output:			 4.5397868702434395e-05
Sum value quantized:	 -640
Output value quantized:	 1
################### TEST #2 ###################
X: [-0.75, -0.75, -0.75, -0.75, -0.75, -0.75, -0.75, -0.75, -0.75, -0.75]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 -7.5
Sigmoid output:			 0.0005527786369235996
Sum value quantized:	 -480
Output value quantized:	 18
################### TEST #3 ###################
X: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 -5.0
Sigmoid output:			 0.0066928509242848554
Sum value quantized:	 -320
Output value quantized:	 219
################### TEST #4 ###################
X: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]
W: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
b: 0
Sum result:				 -2.5
Sigmoid output:			 0.07585818002124355
Sum value quantized:	 -160
Output value quantized:	 2486
################### TEST #5 ###################
X: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]
W: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
b: 0
Sum result:				 0.0
Sigmoid output:			 0.5
Sum value quantized:	 0
Output value quantized:	 16384
################### TEST #6 ###################
X: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]
W: [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]
b: 0
Sum result:				 2.5
Sigmoid output:			 0.9241418199787566
Sum value quantized:	 160
Output value quantized:	 30281
################### TEST #7 ###################
X: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 5.0
Sigmoid output:			 0.9933071490757153
Sum value quantized:	 320
Output value quantized:	 32548
################### TEST #8 ###################
X: [0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 7.5
Sigmoid output:			 0.9994472213630764
Sum value quantized:	 480
Output value quantized:	 32749
################### TEST #9 ###################
X: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 0
Sum result:				 10
Sigmoid output:			 0.9999546021312976
Sum value quantized:	 640
Output value quantized:	 32766
################### TEST #10 ###################
X: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: 1
Sum result:				 11
Sigmoid output:			 0.999983298578152
Sum value quantized:	 704
Output value quantized:	 32766
################### TEST #11 ###################
X: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
W: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b: -1
Sum result:				 -11
Sigmoid output:			 1.670142184809518e-05
Sum value quantized:	 -704
Output value quantized:	 1
\end{lstlisting}

By running a new testbench with \textbf{likely} the same inputs the following results were displayed in \textbf{Modelsim}:
\begin{figure}[H]
	\centering
	\caption{Output of the System 3}
	\includegraphics[width=\textwidth]{img/aimed_test.png}
\end{figure}

A comparison with the outputs can be seen in the following table:
\begingroup
\setlength{\tabcolsep}{10pt} % Default value: 6pt
\renewcommand{\arraystretch}{2} % Default
\begin{center}
	\begin{tabular}{|p{2cm}||p{2.4cm}|p{2.4cm}|p{2.4cm}|p{2.4cm}|}
		\hline
		\multirow{2}{*}{\textbf{Test}}  & \multicolumn{2}{|p{3cm}|}{\textbf{Python Script}} & \multicolumn{2}{|p{3cm}|}{\textbf{Modelsim}} \\
		\cline{2-5}
		 & $round\left(\dfrac{z}{LSB}\right)$ & $round\left(\dfrac{f(z)}{LSB}\right)$ &  $round\left(\dfrac{z}{LSB}\right)$ & $round\left(\dfrac{f(z)}{LSB}\right)$ \\
		\hline
		Test $\#$1 & -640 & 1 & -638 (+2) & 1 (=)\\
		Test $\#$2 & -480 & 18 & -479 (+1) & 18 (=)\\
		Test $\#$3 & -320 & 219 & -319 (+1) & 225 (+5)\\
		Test $\#$4 & -160 & 2486 & -160 (=) & 2482 (-4)\\
		Test $\#$5 & 0 & 16384 & 0 (=) & 16384 (=)\\
		Test $\#$6 & 160 & 30281 & 160 (=) & 30284 (+3)\\
		Test $\#$7 & 320 & 32548 & 318 (-2) & 32541 (-7)\\
		Test $\#$8 & 480 & 32749 & 478 (-2) & 32748 (-1)\\
		Test $\#$9 & 640 & 32766 & 632 (-8) & 32765 (-1)\\
		Test $\#$10 & 704 & 32766 & 696 (-8) & 32766 (=)\\
		Test $\#$11 & -704 & 1 & -702 (+2) & 0 (-1)\\
		\hline
	\end{tabular}
\end{center}
\endgroup

In the latter table are compared the z and f(z) (See Equation (1) and (2) for further details) as they are represented in the architecture: with a C2 representation.\\
As we can see in the latter table the outputs are \textbf{likely} the same, with some few differences that can be ignored. These differences can be easily explained: \textbf{Python's float} number will use \textbf{64 bits} instead of 12 or 16 as in our case. This difference will change the outputs, in fact, in our case, the number $+1$ ("01111111" in base of $x_{i}$ with 8 bits), for example, can't be represented precisely with a finite number of bits: so, the higher number of bits are available, the higher precision will be granted. All things considered, we can state \textbf{the system has passed the System Aimed Test} and, for our purpose, \textbf{can be considered verified.}


%\documentclass{article}
%\usepackage{amsmath}
%\begin{document}

\section{Boundary layer turbulence model}
{\bf \Large
\begin{tabular}{ccc}
\hline
  Corresponding author & : & Seiya Nishizawa\\
\hline
\end{tabular}
}

\def\half{\frac{1}{2}}

\subsection{Mellor-Yamada Nakanishi-Niino model}
level 2.5

\begin{align}
  \frac{\partial \rho u}{\partial t}
  &= -\frac{\partial}{\partial z} \rho \overline{u'w'}, \\
  \frac{\partial \rho v}{\partial t}
  &= -\frac{\partial}{\partial z} \rho \overline{v'w'}, \\
  \frac{\partial \rho \theta_l}{\partial t}
  &= -\frac{\partial}{\partial z} \rho \overline{\theta_l'w'}, \\
  \frac{\partial \rho q_a}{\partial t}
  &= -\frac{\partial}{\partial z} \rho \overline{q_a'w'}, \\
  \frac{\partial }{\partial t}\rho q^2
  &= -2\left(\rho\overline{u'w'}\frac{\partial u}{\partial z}+\rho\overline{v'w'}\frac{\partial v}{\partial z}\right)
  +2\frac{g}{\theta_0}\rho\overline{\theta_v' w'}
  -\frac{\partial}{\partial z}\rho\overline{q^2w'}
  -2\rho\epsilon, \label{eq: q2}
\end{align}
where:
\begin{equation}
  q_a = q_v + q_c + q_r + q_i + q_s + q_g,
\end{equation}
and $q^2$ is doubled turbulence kinetic energy:
\begin{equation}
  q^2 = u'^2 + v'^2 + w'^2.
\end{equation}

The higher order moments and the dissipation term are parameterized as follows:
\begin{align}
  \overline{u'w'} &= -LqS_M\frac{\partial u}{\partial z}, \\
  \overline{v'w'} &= -LqS_M\frac{\partial v}{\partial z}, \\
  \overline{\theta_l'w'} &= -LqS_H\frac{\partial \theta_l}{\partial z}, \\
  \overline{q_a'w'} &= -LqS_H\frac{\partial q_a}{\partial z}, \\
  \overline{q^2w'} &= -3LqS_M\frac{\partial q^2}{\partial z}, \\
  \overline{\theta_v' w'} &= \beta_\theta\overline{\theta_l'w}'+\beta_q\overline{q_a'w'}, \\
  \epsilon &= \frac{q^3}{B_1L},
\end{align}
where:
\begin{align}
  S_M &= \alpha_cA_1\frac{\Phi_3-3C_1\Phi_4}{D_{2.5}}, \\
  S_H &= \alpha_cA_2\frac{\Phi_2+3C_1\Phi_5}{D_{2.5}}, \\
  \beta_\theta &= 1 + 0.61 q_a - 1.61 Q_l - \tilde{R} abc, \\
  \beta_q &= 0.61\theta + \tilde{R} ac.
\end{align}

\begin{align}
  D_{2.5} &= \Phi_2\Phi_4 + \Phi_5\Phi_3, \\
  \Phi_1 &= 1-3\alpha_c^2A_2B_2(1-C_3)G_H, \\
  \Phi_2 &= 1-9\alpha_c^2A_1A_2(1-C_2)G_H, \\
  \Phi_3 &= \Phi_1+9\alpha_c^2A_2^2(1-C_2)(1-C_5)G_H, \\
  \Phi_4 &= \Phi_1-12\alpha_c^2A_1A_2(1-C_2)G_H, \\
  \Phi_5 &= 6\alpha_c^2A_1^2G_M, \\
  \alpha_c &= \left\{
  \begin{array}{ll}
    q/q_2, & q<q_2 \\
    1, & q \ge q_2
  \end{array}
  \right. , \\
  G_M &= \frac{L^2}{q^2}\left\{\left(\frac{\partial u}{\partial z}\right)^2 + \left(\frac{\partial v}{\partial z}\right)^2\right\}, \\
  G_H &= -\frac{L^2}{q^2}N^2, \\
  R &= \frac{1}{2}\left\{1+\mathrm{erf}\left(\frac{Q_1}{\sqrt{2}}\right)\right\}, \\
  \tilde{R} &= R - \frac{Q_l}{2\sigma_s}\frac{1}{\sqrt{2\pi}}\exp\left(-\frac{q_1^2}{2}\right), \\
  Q_l &= 2\sigma_s\left\{RQ_1+\frac{1}{\sqrt{2\pi}}\exp\left(-\frac{Q_1^2}{2}\right)\right\}, \\
  Q_1 &= \frac{a}{2\sigma_s}(q_a-Q_{sl}), \\
  \sigma_s^2 &= \frac{1}{4}a^2L^2\alpha_cB_2S_H\left(\frac{\partial q_a}{\partial z} -b\frac{\partial \theta_l}{\partial z}\right)^2, \\
  \delta Q_{sl} &= \left.\frac{\partial Q_s}{\partial T}\right|_{T=T_l}, \\
  a &= \left(1+\frac{L}{C_p}\delta Q_{sl}\right)^{-1}, \\
  b &= \frac{T}{\theta}\delta Q_{sl}, \\
  c &= (1+0.61q_a - 1.61Q_l)\frac{\theta}{T}\frac{L_v}{C_p} - 1.61\theta,
\end{align}
and $Q_{sl}$ is the saturation-specific humidity at temperature $T_l (=\theta_l T/\theta)$.

The buoyancy flux term, which is the third term on the left hand side of eq. \ref{eq: q2} is:
\begin{align}
  2\frac{g}{\theta_0}\overline{\theta_v' w'}
  &= 2\frac{g}{\theta_0}\left(-\beta_\theta LqS_H\frac{\partial \theta_l}{\partial z} - \beta_q LqS_H\frac{\partial q_a}{\partial z}\right) \nonumber \\
  &= -2LqS_H\frac{g}{\theta_0}\left(\beta_\theta\frac{\partial \theta_l}{\partial z}+\beta_q\frac{\partial q_a}{\partial z}\right) \nonumber \\
  &= -2LqS_H\frac{g}{\theta_0}\frac{\partial \theta_v}{\partial z} \nonumber \\
  &= -2LqS_HN^2,
\end{align}
where $N^2$ is the square of the Brunt-Vaisala frequency.

\begin{align}
  \frac{\partial }{\partial t}\rho q^2
  &= 2\rho LqS_M\left\{\left(\frac{\partial u}{\partial z}\right)^2
                +\left(\frac{\partial v}{\partial z}\right)^2\right\} \nonumber\\
  &-2\rho LqS_HN^2
  +\frac{\partial}{\partial z}\left(3\rho LqS_M\frac{\partial}{\partial z}q^2\right)
  -2\rho\frac{q^3}{B_1L}
\end{align}

$S_{M2}, S_{H2}$, and $q_2$ are for level 2 schemes corresponding to $S_M, S_H$, and $q$, respectively:
\begin{align}
  S_{M2} &= \frac{A_1F_1}{A_2F_2}\frac{R_{f1}-Rf}{R_{f2}-Rf} S_{H2}, \\
  S_{H2} &= 3 A_2 (\gamma_1 + \gamma_2) \frac{Rf_c - Rf}{1-Rf}, \\
  q_2^2 &= B_1 L^2 S_{M2} (1-Rf) \left\{\left(\frac{\partial u}{\partial z}\right)^2+\left(\frac{\partial v}{\partial z}\right)^2\right\}.
\end{align}
$Rf$ and $Rf_c$ are the flux Richardson number and the critical flux Richardson number, respectively.
The gradient Richardson number, $Ri$, is:
\begin{equation}
  Ri = Rf \frac{S_{M2}}{S_{H2}}.
\end{equation}
$Rf$ is then:
\begin{align}
  Rf &= \frac{1}{2}\frac{A_2F_2}{A_1F_1}
  \left\{ Ri + \frac{A_1F_1}{A_2F_2}R_{f1}
        -\sqrt{Ri^2+2\frac{A_1F_1}{A_2F_2}(R_{f1}-2R_{f2})Ri+\left(\frac{A_1F_1}{A_2F_2}R_{f1}\right)^2} \right\}, \\
  Rf_C &= \frac{\gamma_1}{\gamma_1+\gamma_2}, \\
\end{align}
where:
\begin{align}
  R_{f1} &= B_1\frac{\gamma_1-C_1}{F_1}, \\
  R_{f2} &= B_1\frac{\gamma_1}{F_2}.
\end{align}

The turbulent length scale, $L$, is determined by the smallest length scale among three scales:
\begin{equation}
  \frac{1}{L} = \frac{1}{L_s} + \frac{1}{L_T} + \frac{1}{L_B}.
\end{equation}
the surface layer scale, $L_s$, the boundary layer scale, $L_T$, and buoyancy length scale, $T_B$:
\begin{align}
  L_S &= \left\{
  \begin{array}{ll}
    kz/3.7, & \zeta \ge 1 \\
    kz/(1+2.7\zeta), & 0 \le \zeta < 1 \\
    kz(1-100\zeta)^{0.2}, & \zeta < 0
  \end{array}
  \right. , \\
  L_T &= 0.23\frac{\int_0^\infty qz dz}{\int_0^\infty q dz}, \\
  L_B &= \left\{
  \begin{array}{ll}
    q/N,                      & \partial \theta_v/\partial z > 0 \;\mathrm{and}\; \zeta \ge 0 \\
    \{1+5(q_c/L_TN)^{1/2}\}q/N, & \partial \theta_v/\partial z > 0 \:\mathrm{and}\; \zeta < 0 \\
    \infty, & \partial \theta_v/\partial z \le 0
  \end{array}
  \right. ,
\end{align}
where $\zeta$ is the dimensionless height:
\begin{equation}
  \zeta = \frac{z}{L_M}.
\end{equation}
$L_M$ is the Monin-Obukhov length:
\begin{equation}
  L_M = -\frac{\theta_0 u_*^3}{kg\overline{\theta_v'w'}_g},
\end{equation}
where $u_*$ is the friction velocity, and the subscript $g$ denotes the ground surface.
$q_c$ is a velocity scale defined in a similar manner to convective velocity $w_*$, except that the depth $z_i$ of the convective boundary layer is replaced by $L_t$:
\begin{equation}
  q_c = \left\{\frac{g}{\theta_0}\overline{\theta_v' w'}_gL_T\right\}^{1/3}
\end{equation}

\begin{align}
  A_1 &= B_1\frac{1-3\gamma_1}{6}, \\
  A_2 &= \frac{1}{3\gamma_1 B_1^{1/3} Pr_N}, \\
  B_1 &= 24.0, \\
  B_2 &= 15.0, \\
  C_1 &= \gamma_1 - \frac{1}{3A_1B_1^{1/3}}, \\
  C_2 &= 0.75, \\
  C_3 &= 0.352, \\
  C_5 &= 0.2, \\
  \gamma_1 &= 0.235, \\
  \gamma_2 &= \frac{2A_1(3-2C_2)+B_2(1-C_3)}{B_1}, \\
  F_1 &= B_1(\gamma_1-C_1)+2A_1(3-2C_2)+3A_2(1-C_2)(1-C_5), \\
  F_2 &= B_1(\gamma_1+\gamma_2)-3A_1(1-C_2), \\
  Pr_N &= 0.74.
\end{align}

\subsubsection{Discretization}
The diffusion equations for $q^2a$ are solved implicitly:
\begin{align}
  \rho_k \frac{(q^2_k)^{n+1}-(q^2_k)^n}{\Delta t}
  &=
  2\rho_k \left[ (LqS_M)_k\left\{\left(\frac{\partial u}{\partial z}\right)^2+\left(\frac{\partial v}{\partial z}\right)^2\right\} + (LqS_HN^2)_k \right] \nonumber \\
  &+ \frac{1}{\Delta z_k}\left\{ (3\rho LqS_M)_{k+\half} \frac{(q^2_{k+1})^{n+1}-(q^2_k)^{n+1}}{\Delta z_{k+\half}} - (3\rho LqS_M)_{k-\half} \frac{(q^2_k)^{n+1}-(q^2_{k-1})^{n+1}}{\Delta z_{k-\half}} \right\} \nonumber \\
  &-\frac{2\rho_k q_k}{B_1L_k}(q^2_k)^{n+1}.
\end{align}
\begin{equation}
  a_k (q^2_{k+1})^{n+1} + b_k (q^2_k)^{n+1} + c_k (q^2_{k-1})^{n+1} = d_k,
\end{equation}
where:
\begin{align}
  a_k &= -\frac{\Delta t}{\Delta z_{k+\half}\Delta z_k\rho_k}(3\rho LqS_M)_{k+\half}, \\
  b_k &= -a_k - c_k + 1 + \frac{2\Delta tq_k}{B_1L}, \\
  c_k &= -\frac{\Delta t}{\Delta z_k\Delta z_{k-\half}\rho_k}(3\rho LqS_M)_{k-\half}, \\
  d_k &= (q^2_k)^n + 2\Delta t \left[ LqS_M\left\{\left(\frac{\partial u}{\partial z}\right)^2+\left(\frac{\partial v}{\partial z}\right)^2\right\} - LqS_HN^2 \right]
\end{align}
\begin{equation}
  (q^2_k)^{n+1} = e_k (q^2_{k+1})^{n+1} + f_k,
\end{equation}
where:
\begin{align}
  e_k &= -\frac{a_k}{b_k+c_ke_{k-1}}, \\
  f_k &= \frac{d_k-c_kf_{k-1}}{b_k+c_ke_{k-1}}.
\end{align}

Vertical fluxes for $\rho u, \rho v, \rho\theta, \rho q_x$ are also solved implicitly.
For instance, the flux for $\rho u$, $F_u$ is calculated by:
\begin{equation}
  F_{u,k+\half} = (\rho LqSM)_{k+\half}\frac{u^{n+1}_{k+1}-u^{n+1}_k}{\Delta z_{k+\half}}.
\end{equation}
$u^{n+1}$ is calculated as the same way with $q^2$, but:
\begin{align}
  a_k &= -\frac{\Delta t}{\Delta z_{k+\half}\Delta z_k\rho_k}(\rho LqS_M)_{k+\half}, \\
  b_k &= -a_k - c_k + 1, \\
  c_k &= -\frac{\Delta t}{\Delta z_k\Delta z_{k-\half}\rho_k}(\rho LqS_M)_{k-\half}, \\
  d_k &= u_k^n.
\end{align}

%\end{document}