\section{Arbitrage theory in continuous markets}

We now develop an heuristic model for continuous-time markets. We shall omit most technical definitions, details and proofs. It is an amalgam of the presentations found in \textcite{bjork2004arbitrage}, \textcite{brigo2007interest}, \textcite{duffie2010dynamic}, \textcite{jameswebber2000interest}, \textcite{musielarutkowski2005martingale} and \textcite{wu2009interest}. A rigorous treatment for the subject can be found, for example, in \textcite{musielarutkowski2005martingale}. The fundamentals of this model are the same as the simple discrete model introduced earlier, but due to technicalities, it is not as intuitive.

We consider a probability space $(\Omega, \F, \Pf)$ and a finite time interval $\left[ 0, T' \right]$. Here $\Pf$ is the physical probability measure on $(\Omega, \F)$, $\Omega$ is the sample path space with a $\sigma$-algebra $\F$. The flow of new information is handled with a filtration\footnote{A filtration $(\F_t)$ is a collection $\sigma$-sub-algebras of $\F$ with $\F_s \subseteq \F_t$ for all $0 \leq s \leq t \leq T$.} $(\F_t)$. We also assume some technical conditions for the filtrations. Every $\Pf$-null set\footnote{$\Pf$-null set is a set $A \in \F$ with $\Pf (A) = 0$.} must be a member of $\F_0$ and
  \begin{align}
    \F_t = \bigcap_{t < s} \F_s
  \end{align}
for all $t \geq 0$.

We assume that the price $S_i$ of a market assets are modeled with It\'{o}-processes\footnote{See \ref{sec:itoprocess}}, so
  \begin{align}
    \label{generalassetpriceprocess}
    S_i(t,\omega) = S_i (0) + \int_0^t \mu (t,\omega) \dx t + \int_0^t \sigma(t, \omega ) \dx W_i (t, \omega),
  \end{align}
where $S_i(0)$ is a deterministic constant and $W_i$ is a Brownian motion. The second integral is an It\'{o}-integral and the functions $\mu$ and $\sigma$ are assumed to be $\F_t$-adapted and to satisfy technical conditions so that integrability and the existence of solutions are always guaranteed\footnote{It is usually assumed, for example, that $\int_0^{T^*} \left| \mu(t, \omega) \right| \dx t < \infty$ and $\int_0^{T^*} \sigma(t, \omega)^2 \dx t < \infty$ almost surely}. We usually write the Equation \ref{generalassetpriceprocess} as
  \begin{align}
    \dx S_i(t, \omega) = \mu (t,\omega) \dx t + \sigma(t, \omega ) \dx W_i (t, \omega),
  \end{align}
but we note that Brownian motions are $\Pf$-surely not differentiable. We assume that the assets all these assets can be bought and sold freely, and the trading shall not affect price process.

We also shall omit $\omega$ from the argument of functions for readability, when it is not absolutely necessary.

Suppose that there are $n$ tradable assets and let $S = (S_1, S_2, \ldots, S_n)$ be the price vector for these assets. The trading strategy (or a portfolio) $w$ is a predictable stochastic process $w(t,\omega) \in \R^n$. This means that while the strategy is a random variable, it is not omniscient and uses only information available up to that point. It is left-continuous, so given the history up to that point, it is deterministic. The corresponding portfolio value process is given by
  \begin{align}
    V^w (t) = (w(t))^{\top} S(t)
  \end{align}
and a self-financing trading strategy satisfies
	\begin{align}
		V^w(t) - V^w(0) = \int_0^t w^{\top}(u) \ \dx S(u),
	\end{align}
or
  \begin{align}
    \dx V^w = (w(t))^{\top} \dx S(t) .
  \end{align}
This means that for self-financing portfolio, there is no inflow or outflow of money from the portfolio and all the value changes are due to changes of prices. An arbitrage\footnote{We note that this type of arbitrage is not strong enough to disallow doubling strategies.} is a self-financing portfolio with a value process $V^w (t)$ such that
  \begin{align}
    V^w(0) &= 0, \\
    \Pf (V^w(t) \geq 0 ) &= 1 \textup{ and } \\
    \Pf (V^w(t) > 0 ) &> 0.
  \end{align}
 for some $0 \leq t \leq T'$. An arbitrage is an opportunity to gain without any associated risk. A market without arbitrage opportunities is arbitrage-free.

A contingent claim (or $T$-derivative or $T$-claim) is a $\F_T$-measurable random variable $X$. We say that the is attainable if there is such self-financing trading strategy $w$ that
  \begin{align}
    V^w(T) = X(T)
  \end{align}
almost surely. The strategy $w$ is thus replicating the pay-off of $X$. As usually, we say that the market is complete if every contingent claim is attainable.

As earlier, a deflator is strictly positive It\^{o}-process and a num\'{e}raire is an asset with always positive price process. If $D$ is deflator, then the relative (or discounted) market price process is
  \begin{align}
    S^D(t) = ( S_i(t) / D(t) )
  \end{align}
for all $0 \leq t \leq T'$. A measure $\Pm$ on the space $(\Omega, \F)$ is an equivalent martingale measure (EMM) with respect to the deflator $D$ if it is equivalent\footnote{Meaning that the measures have the same null sets.} to $\Pf$ and if
  \begin{align}
    S^D(s) = \E_{\Pm} ( \ S^D(t) \ | \ \F_s \ )
  \end{align}
for all $0 \leq s < t$. This means that discounted price processes are martingales under an EMM.  A weaker condition is an equivalent local martingale measure (ELMM) which requires only that the measures are equivalent and discounted price process are local martingale under the ELMM.

We will only consider trading strategies that will satisfy the condition that
  \begin{align}
    \int_0^t w(s)^{\top} \dx S^D(s)
  \end{align}
are martingales under the the measure $\Pm$ as this guarantees that no doubling strategies are permissable\footnote{Thus the expected values of portfolios are always bounded.}.

The first fundamental theorem of asset pricing says that if an equivalent martingale measure exists, then the market is arbitrage-free. As we have seen, in discrete time model, these are equivalent conditions. But in continuous models, this in not true. \textcite{delbaenschachermayer1994general} showed that under certain conditions, the absence of arbitrage implies that an equivalent local martingale measure exists. We shall not delve in these technicalities further in this thesis.

The second fundamental theorem of asset pricing ties the uniqueness of this EMM to the ability to hedge every derivative contract. If we assume that the market is arbitrage free and an equivalent martingale measure exists for a deflator $D$, then the market is complete if and only if the equivalent martingale measure for deflator $D$ is unique.

As in discrete setting, we have three distinct cases: the model has no EMM, it has several EMMs or the EMM is unique.

Ideally the EMM is unique and the model is complete and it allows no arbitrage. Traditionally the discounting in the EMM has been done with respect to the risk-free rate, but \textcite{gemanelkarouirochet1995changes} showed that the choice of the so-called num\'{e}raire is actually arbitrary as long as it is strictly positive non-dividend paying asset process. Different num\'{e}raires produces different EMMs, but if we assume that payoffs are square integrable random variables, then the change of num\'{e}raire does not change replicating portfolios. Thus the price is unique as long as the derivative can be hedged. If $S_0$ is the num\'{e}raire, $X$ is a $T$-derivate with replicating self-financing portfolio's value process given by $V^w(t)$, then we have that $X(T) = V^w(T)$ and every discounted value processes of self-financing portfolio is martingale under the EMM $\Pm_0$ associated with discounting process $S_0$. Thus
  \begin{align}
    \frac{V^w(t) }{ S_0(t) } = \E_{\Pm_0} \left( \frac{V^w(T)}{S_0(T)} | \F_t \right) = \E_{\Pm_0} \left( \frac{X(T)}{S_0(T)} | \F_t \right)
  \end{align}
meaning that
  \begin{align}
    \label{discountedexpectedvalue}
    V^w(t) = S_0(t) \E_{\Pm_0} \left( \frac{V^w(T)}{S_0(T)} | \F_t \right) = S_0(t) \E_{\Pm_0} \left( \frac{X(T)}{S_0(T)} | \F_t \right) .
  \end{align}
Since there are no arbitrage opportunities, $X(t) = V^w(t)$, where $V^w(t)$ is given by the equation (\ref{discountedexpectedvalue}). This has to hold even if the replicating portfolio is not unique.

If the model has several EMMs, then arbitrage is not possible but there are derivatives that may not be hedged. In this model, a claim that can be replicated has a unique price. Claims that may not be replicated may have multiple prices corresponding to different EMMs.

This usually means that calibrating prices are taken carefully selected from the most liquid instruments. We can also use more generalized versions of hedging. We could take the set of all sensible portfolio strategies that promise almost surely a payoff that is equal or greater than the contingent claim. A reasonable price candidate for a derivative is the minimum maintenance price of these portfolio strategies.

The worst case is the absence of EMM. This means that the model has arbitrage and pricing cannot be done.

The num\'{e}raire can be freely chosen. \cite{gemanelkarouirochet1995changes} showed that if the market is arbitrage-free, $M$ and $N$ are arbitrary num\'{e}raires, then there exists such EMMs $\Pm_M$ and $\Pm_n$ that
	\begin{align}
		\frac{X(t)}{M(t)} &= \E_{\Pm_M} \left( \frac{X(T)}{M(T)} | \F_t \right), \\
		\frac{X(t)}{N(t)} &= \E_{\Pm_N} \left( \frac{X(T)}{N(T)} | \F_t \right)
	\end{align}
for any asset $X$ and $0 \leq t \leq T$. The Radon-Nikod\'{y}m derivate\footnote{See \ref{sec:radonnikodymtheorem}} is
	\begin{align}
		\xi(t) = \frac{\dx \Pm_M}{\dx \Pm_N} = \frac{M(t) N(0)}{M(0) N(t)} .
	\end{align}
This implies that
	\begin{align}
		X(t) &= M(t) \E_{\Pm_M} \left( \frac{X(T)}{M(T)} | \F_t \right) \\
		&= N(t) \E_{\Pm_N} \left( \frac{X(T)}{N(T)} | \F_t \right)
\end{align}
and the price is unique, if the claim can be replicated. Also
	\begin{align}
		\label{expectationbyradonnikodymderivative}
		\E_{\Pm_M} \left( Y(T) | \F_t \right) = \frac{\E_{\Pm_N} \left( Y(T) \xi(T)  | \F_t \right)}{\xi(t)}
	\end{align}
holds for any random variable $Y$.

\subsection{Risk-free measure}

The bank account $\Bank(t) > 0$ is a common num\'{e}raire and the EMM $\Pm_0$ induced by it is often called as the risk-free measure. If $X$ is a portfolio and the market is arbitrage-free, then
	\begin{align}
		\label{pricingunderriskneutralmeasure}
		X(t) &= \Bank(t) \E_{\Pm_0} \left( \frac{X(T)}{B(T)} | \F_t \right) \\
			&= \E_{\Pm_0} \left( \frac{B(t)}{B(T) } X(T) | \F_t \right) \\
			&= \E_{\Pm_0} \left( D(t,T) X(T)  | \F_t \right),
	\end{align}
where $D(t,T)$ is the stochastic discount factor. If $X(t) = \Bond(t,T)$, then $\Bond(T,T)=1$ and we note that
	\begin{align}
		\Bond(t,T) = \E_{\Pm_0} \left( D(t,T) \ | \ \F_t \right) .
	\end{align}
This shows that price of a bond is expected value of the corresponding stochastic discount factor under the risk-free measure (or any other EMM). Also if
	\begin{align}
		\Bank(t) = \e^{ \int_0^t r(s) \ \dx s },
	\end{align}
then
	\begin{align}
		D(t,T) = \frac{\Bank(t)}{\Bank(T)} = \e^{ - \int_t^T r(s) \ \dx s },
	\end{align}
hence
	\begin{align}
		X(t) &= \E_{\Pm_0} \left( \e^{ - \int_t^T r(s) \ \dx s } X(T)  | \F_t \right) .
\end{align}

Under the risk-neutral measure, the discounted process $X(t) / B(t)$ will be a martingale.

\subsection{Black-Scholes--model}

In the celebrated Black-Scholes--model there are two assets, a stock and a bank account, with given dynamics
  \begin{align}
    \label{stockprocessinblackscholes}
    \dx S(t) &= \mu S(t) \dx t + \sigma S(t) \dx W(t) \\
    \dx \Bank (t) &= r \Bank(t) \dx t,
  \end{align}
under the physical measure $\Pf$, where $\mu, r$ and $\sigma > 0$ are given constants and the Brownian motion $W(t)$ is the sole source of uncertainty. This means that the stock price follows geometric Brownian motion and $\Bank (t) = \Bank (0) \e^{rt}$. To simplify the notation we assume that $\Bank (0) = 1$. We denote the discounted stock price as $S^\Bank(t) = S(t) / \Bank (t)$ and the discount factor is deterministic $\DF (t,T) = \e^{r(T-t)}$. Now $g(t,x) = \e^{-rt} x$ and a simple application of It\^{o}'s lemma\footnote{See \ref{sec:itoprocess}.} yields that
  \begin{align}
    \dx S^\Bank(t) &= ( \frac{\partial g}{\partial t} + \mu \frac{\partial g}{\partial x} + \frac{1}{2} \sigma^2 \frac{\partial^2 g}{\partial x^2} ) \dx t + \sigma \frac{\partial g}{\partial x} \dx W(t) \\
      &= ( -r \e^{-rt} S(t) + \e^{-rt} \mu S(t) + 0 ) \dx t + \sigma \e^{-rt} S(t) \dx W(t) \\
      &= ( \mu - r ) S^\Bank(t) \dx t + \sigma S^\Bank(t) \dx W(t) .
  \end{align}
We can now use Girsanov's theorem\footnote{See \ref{sec:girsanov}.} to change the probability measure in order to make the discounted stock price process driftless. We note the bank account discounted by itself is trivially driftless under any measure. Now the market price of risk
	\begin{align}
		\lambda = \frac{r - \mu}{\sigma}
	\end{align}
is the only possible Girsanov kernel that makes the new measure an equivalent martingale measure. So there is an unique EMM $\Pm$ for the deflator $B(t)$. hence Black-Scholes model is arbitrage-free and complete. Under this measure $\dx W^{\Pm}(t) = \dx W(t) - \frac{r - \mu}{\sigma} \dx t$ is a Brownian motion. Therefore
  \begin{align}
    \dx S^\Bank(t) &= \sigma S^\Bank(t) \dx W^{\Pm}(t), \\
    \dx \Bank (t) &= r \Bank (t) \dx t, \\
    \label{BlackScholesProcessesUnderEMM}
    \dx S(t) &= r S(t) \dx t + \sigma S(t) \dx W^{\Pm}(t)
  \end{align}
under the EMM $\Pm$. In other words, the discounted stock price is a martingale and under this measure the drift of the stock price is changed to the risk-free rate $r$. Since the bank account is deterministic, the change of measure does not affect it. The arbitrage-free price of the derivate is at time $0$ is given by
  \begin{align}
    X(0) &= \E_{\Pm} \left( X(T) / \Bank (0,T) | \F_0 \right) \\ &= \e^{-rT} \E_{\Pm} \left( X(T) | \F_0 \right) .
  \end{align}
Since the stock price process under the risk-free measure is a geometric Brownian motion, we know that
  \begin{align}
    \log (S(T) ) &= \log (S(0) ) + \left( r  - \frac{1}{2} \sigma^2 \right) T + \sigma W^{\Pm}(T) \\ &\sim N \left( \log (S(0) ) + \left( r  - \frac{1}{2} \sigma^2 \right), \sigma^2 T \right)
  \end{align}
under the measure $\Pm$. Similarly, we could use the stock price $S(t)$ as the numerator.

If we pick $X(T) = (S(T)-K)^+$, the price of a call option on the stock at the time $T$, then
	\begin{align}
		\E_{\Pm} \left( (S(T)-K)^+ | \F_0 \right) &= \E_{\Pm} \left( (S(T)-K) \1_{ \{ S(T) > K\} } | \F_0 \right) \\
		&= \E_{\Pm} \left( S(T) \1_{ \{ S(T) > K\} } | \F_0 \right) - K \Pm \left( S(T) > K | \F_0 \right)
	\end{align}
and the standard calculations will yield that
  \begin{align}
    X(T) &= S(0) N(d_+)  -  \e^{-rT} K N(d_-) , \\
    d_{\pm} &= \frac{\log S/K + (r \pm \sigma^2/2 )T }{\sigma \sqrt{T}},
  \end{align}
which is the celebrated Black-Scholes formula.

We shall also give a heuristic derivation of the Black-Scholes differential equation. If $X(t,S(t))$ is a smooth value process of a derivative, then by It\'{o}'s lemma, we have that
  \begin{align}
    \label{itolemmatoderivateinblackscholes}
    \dx X = \left( \frac{\partial X}{\partial t} + \mu S \frac{\partial X}{\partial S} + \frac{1}{2} \sigma^2 S^2 \frac{\partial X^2}{\partial S^2} \right) \dx t + \sigma S \frac{\partial X}{\partial S} \dx W .
  \end{align}
Now we assume that we can replicate this derivative with a combination of $\delta_S(t,S)$ stocks and $\delta_B(t,S)$ bonds. This portfolio has a value
	\begin{align}
		V(t,S) = \delta_S S(t) + \delta_B B(t)
	\end{align}
and the value follows the process
	\begin{align}
		\dx V &= \delta_S \dx S + \delta_B \dx B \\
			&= \delta_S (\mu S \dx t + \sigma S \dx W ) + \delta_B r B \dx t \\
			&= (\delta_S \mu S + \delta_B rB) \dx t + \delta_S \sigma S \dx W \\
			&= (\delta_S \mu S + r (V - \delta_S S)) \dx t + \delta_S \sigma S \dx W
	\end{align}
As $\dx V = \dx X$, then the coefficients of $\dx W$ terms must coincide. Thus
	\begin{align}
		\label{replicating_delta}
		\delta_S \sigma S = \sigma S \frac{\partial X}{\partial S},
	\end{align}
which implies that $\delta_S = \frac{\partial X}{\partial S}$.

Now we consider a portfolio of one derivative and $-\frac{\partial X}{\partial S}$ stocks. The value of this portfolio is
  \begin{align}
    V = X - \frac{\partial X}{\partial S} S
  \end{align}
and if the portfolio is self-financing, then
  \begin{align}
    \dx V &= \dx X - \frac{\partial X}{\partial S} \dx S \\
      &= \left( \frac{\partial X}{\partial t} + \frac{1}{2} \sigma^2 S^2 \frac{\partial X^2}{\partial S^2} \right) \dx t
  \end{align}
after substitution of equations \ref{stockprocessinblackscholes} and \ref{itolemmatoderivateinblackscholes}. Since there is no diffusion, the portfolio is riskless and the absence of arbitrage implies that
  \begin{align}
    \dx V = rV \dx t = \left( rX - r S\frac{\partial X}{\partial S} \right) \dx t .
  \end{align}
By equating these, we get the Black-Scholes differential equation
  \begin{align}
  	\label{BlackScholesDifferentialEquation}
    \frac{\partial X}{\partial t} + r S\frac{\partial X}{\partial S} + \frac{1}{2} \sigma^2 S^2 \frac{\partial X^2}{\partial S^2} - r X = 0
  \end{align}
or equivalently
 	\begin{align}
		\frac{\partial X}{\partial t} + \frac{1}{2} \sigma^2 S^2 \frac{\partial X^2}{\partial S^2} = r ( X - S\frac{\partial X}{\partial S}) .
	\end{align}
The left side is a linear combination of "theta", the time decay of the value, and "gamma", the second derivative of the value with respect to the price of the underlying. The right side of the equation contains the replicating portfolio.

The derivative with pay-out $h(S(T))$ satisfies Equation \ref{BlackScholesDifferentialEquation}. In order to apply Feynman-Kac theorem\footnote{See \ref{sec:faynmankac}.}, we need to find a process with drift $rS(t)$ and diffusion $\sigma S(t)$ under some measure. Under the EMM, the discounted asset price is a martingale, so it grows with the rate risk-free rate $r$. So the price process under the EMM is process we need in order to use Feynman-Kac theorem. We have the EMM $\Pm$ and, by Equation \ref{BlackScholesProcessesUnderEMM},
	\begin{align}
		\dx S(t) &= r S(t) \dx t + \sigma S(t) \dx W^{\Pm}(t) ,
	\end{align}
where $W^{\Pm}(t)$ is a Brownian motion under $\Pm$. We may now apply Feynman-Kac theorem and it follows that
	\begin{align}
		h(S(t)) = \e^{ -r(T-t) } \E_{\Pm} ( h(S_T) \ | \ \F_t) .
	\end{align}

\iffalse

\subsubsection{Black-Scholes--model with continuous dividend yield}

If $X(t)$ is the price of call option on stock $S(t)$ with strike $K$ at the time $T$ that pays continuous dividend yield $q$, then the extension of Black-Scholes--model gives the price
	\begin{align}
		X(t) &= \e^{-r(T-t)} \left( F(t)N(d_+) - KN(d_-) \right), \\
		F(t) &= S(t)  \e^{(r-q)(T-t)}, \\
		d_{\pm} &= \frac{\log \frac{S(t)}{K} + (r-q \pm \frac{1}{2} \sigma^2)(T-t)}{\sigma \sqrt{T-t}}
	\end{align}

Suppose now that assets $S_i(t)$ pay continuous dividend yields $q_i$. Suppose that an option gives right to swap asset $S_1$ with asset $S_2$ at the time $T$.

\fi

\subsection{Black-76--model}
\label{blackformula}

Black model (or Black-76--model) is an extension of Black-Scholes--model (\cite{black1976pricing}) and it is used to price futures. It also assumes that the risk-free interest rate is a constant. The model assumes that futures price of an asset follows log-normal distribution with constant volatility parameter. The price of a call option on a future contract has price at time $t$ is given by the Black's formula
\begin{align}
\e^{-r(T-t)} \left( F N(d_+) - K N(d_-) \right)
\end{align}
with
\begin{align}
d_{\pm} = \frac{\log \frac{F}{K} \pm \frac{\sigma^2}{2} (T-t) }{ \sigma \sqrt(T-t) } .
\end{align}
Here $K$ is the strike price at the maturity $T$, $r$ is the risk-free rate and $\sigma$ is the constant volatility of the log-normal distribution. The futures price process is $F(t)$. The Black's formula is used to price interest rate caps, floors and swaptions and the market practice is to quite these instruments in terms of Black's volatilities.

\subsection{$T$-forward measure}

Since $\Bond(t,T) > 0$, $T$-bond is a num\'{e}raire. The EMM induced by this as called $T$-forward measure $\Pm_T$. Since $\Bond(T,T) = 1$, we have that
\begin{align}
X(t) = \Bond(t,T) \E_{\Pm_T} \left( X(T) | \F_t \right)
\end{align}
for every $0 \leq t \leq T$ and attainable claim $X$. The forward rate was defined as
\begin{align}
\Rflt(t,T,S) &= \frac{1}{\dayc(T,S)} \left( \frac{\Bond(t,T)}{\Bond(t,S)} - 1 \right) .
\end{align}
Thus
\begin{align}
\Rflt(t,T,S) \Bond(t,S)  &= \frac{\Bond(t,T)-\Bond(t,S)}{\dayc(T,S)}  ,
\end{align}
where the right side is a bond portfolio. As $\Bond(T,T) = 1$, we know that
\begin{align}
\frac{\Bond(t,T)-\Bond(t,S)}{\dayc(T,S)} &= \Bond(t,T) \E_{\Pm_T} \left( \Rflt(T,T,S) | \F_t \right)
\end{align}
Now we have that shown that
\begin{align}
\Rflt(t,T,S) &= \E_{\Pm_T} \left( \Rflt(T,S) | \F_t \right)
\end{align}
meaning that the forward rate is expected value of spot rate under the $T$-forward measure.

Similarly
\begin{align}
P(t,T) \E_{\Pm_T} \left( r(T) | \F_t \right) &= \E_{\Pm_0} \left( D(t,T) r(T) | \F_t \right) \\
&= \E_{\Pm_0} \left( r(T) \e^{-\int_t^T r(s) \dx s} | \F_t \right) \\
&= \E_{\Pm_0} \left( \frac{\partial}{\partial T} \e^{-\int_t^T r(s)} | \F_t \right) \\
&= \frac{\partial}{\partial T} \E_{\Pm_0} \left( \e^{-\int_t^T r(s)} | \F_t \right) \\
&= \frac{\partial}{\partial T} P(t,T) ,
\end{align}
which implies that
\begin{align}
f(t,T) = \E_{\Pm_T} \left( r(T) | \F_t \right)
\end{align}
meaning that the instantaneous forward rate is the expected value of the short-rate under $T$-forward measure.

The Equation \ref{expectationbyradonnikodymderivative} implies that
\begin{align}
\xi (t) = \frac{\Bond(t,T)}{\Bond(0,T) \Bank(t)}
\end{align}
is the Radon-Nikod\'{y}m-derivative of $T$-forward measure $\Pm_T$ with respect to risk-free measure $\Pm_0$.

\subsection{Change of num\'{e}raire}

Now we consider an arbitrage free market model with assets $N$ and $M$, which are num\'{e}raires. If $X$ is a contingent $T$-claim, then we know that arbitrage free price of $X$ at the time $t$ must be
  \begin{align}
    V_t (X) &= N(t) \E_{\Pm_N} \left( \frac{X(T)}{N(T)} | \F_t \right) \\
            &= M(t) \E_{\Pm_M} \left( \frac{X(T)}{M(T)} | \F_t \right)
  \end{align}
where $\Pm_N, \Pm_M$ are the martingale measure corresponding to the num\'{e}raires $N$ and $M$. Thus
  \begin{align}
    \E_{\Pm_N} \left( \frac{X(T)}{N(T)} | \F_t \right) &= \E_{\Pm_M} \left( \frac{M(t)}{N(t)} \frac{X(T)}{M(T)} | \F_t \right) \\
      &= \E_{\Pm_M} \left( L_T(t) \frac{X(T)}{N(T)} | \F_t \right),
  \end{align}
where
  \begin{align}
    L_T(t) = \frac{N(T) / N(t)}{ M(T) / M(t) } = \frac{M(t)}{N(t)} \frac{N(T)}{M(T)} .
  \end{align}
Now $L_T(t)$ is a $\Pm_N$-martingale
Since $X$ is an arbitrary $\F_T$-measurable random variable, we have heuristically shown the following fundamental result. For the proof, see \cite{gemanelkarouirochet1995changes}.

\begin{thm}
Let $\Pm_N$ be the EMM associated with num\'{e}raire $N$ and $\Pm_M$ be the EMM associated with num\'{e}raire $M$. Under some technical conditions, the Radon-Nikod\'{y}m derivate of $\Pm_M$ with respect to $\Pm_N$ is
  \begin{align}
    \frac{\dx \Pm_N}{\dx \Pm_M} = \frac{N(T) / N(t)}{ M(T) / M(t) } .
  \end{align}
\end{thm}

Since $Z(t,T) > 0$ for all pairs $(t,T)$ we may use zero-coupon bonds as num\'{e}raire. We denote $\Pm_T$ as the equivalent martingale measure given by the $T$-bond. Thus if $X$ is a contingent $T$-claim, then we know that arbitrage free price of $X$ at the time $t$ must be
  \begin{align}
    V_t (X) &= Z(t,T) \E_{\Pm_T} \left( X(T) \right) .
  \end{align}

\iffalse

Tähän jotakin siitä, että Björk s. 357.

If $X(T) = (S(T) - K)^+$ is a final pay-out of a contingent claim $X$ for some asset $S$ and fixed $K$, then
  \begin{align}
    V_t (X) &= \E_{\Pm} \left( \frac{X(T)}{B(T)} | \F_t \right) \\
            &= \E_{\Pm} \left( \frac{ (S(T) - K) \1_{ \{S_T > K \} } }{B(T)} | \F_t \right) \\
            &= \E_{\Pm} \left( \frac{ S(T) }{ B(T) } \1_{ \{S_T > K \} } | \F_t \right) - K \E_{\Pm} \left( \frac{\1_{ \{S_T > K \} } }{B(T)} | \F_t \right) .
  \end{align}
If $S$ is also a num\'{e}raire we may write
  \begin{align}
    \E_{\Pm} \left( \frac{ S(T) }{ B(T) } \1_{ \{S_T > K \} } | \F_t \right) &= \E_{\Pm_S} \left( L_S(T) \frac{ S(T) }{ B(T) } \1_{ \{S_T > K \} } | \F_t \right) \\
    &= \E_{\Pm_S} \left( \frac{ S(t) }{ B(t) } \1_{ \{S_T > K \} } | \F_t \right) \\
    &= \frac{ S(t) }{ B(t) } \Pm_S ( S_T > K )
  \end{align}
where we used likelihood ratio
  \begin{align}
    L_S (T) = \frac{ S(t) }{ B(t) } \frac{ B(T) }{ S(T) }
  \end{align}
to change measure from risk-free measure $\Pm$ to the martingale measure $\Pm_S$ with num\'{e}raire $S$. The second term is
  \begin{align}
    \E_{\Pm} \left( \frac{\1_{ \{S_T > K \} } }{B(T)} | \F_t \right) &= \E_{\Pm_T} \left( L_T(T) \frac{\1_{ \{S_T > K \} } }{B(T)} | \F_t \right) \\
    &= \E_{\Pm_T} \left( \frac{ Z(t,T) }{ B(t) } \1_{ \{S_T > K \} } | \F_t \right) \\
    &= \frac{ Z(t,T) }{ B(t) } \Pm_T ( S_T > K )
  \end{align}
where we used $Z(T,T) = 1$ and likelihood ratio
  \begin{align}
    L_T (t) = \frac{ Z(t,T) }{ B(t) } \frac{ B(T) }{ Z(T,T) }
  \end{align}
to change measure from risk-free measure $\Pm$ to the $T$-forward measure $\Pm_T$. Thus
  \begin{align}
    V_t (X) &= \frac{ S(t) }{ B(t) } \Pm_S ( S_T > K ) - K \frac{ Z(t,T) }{ B(t) } \Pm_T ( S_T > K )
  \end{align}
and especially
  \begin{align}
    V_0 (X) &= S(0) \Pm_S ( S_T > K ) - K Z(0,T) \Pm_T ( S_T > K ) .
  \end{align}

 \fi


% !TEX root=../main.tex

\begin{comment}
Consider a feature matrix $\X \in \Real^{N \times D}$,
where $N$ denotes the number of data points and $D$ the number of features for each point.
For example, $N$ could be the number of images in some photo collection, and $D$ the number of pixels used to represent each image.
The goal of anomaly detection is to determine which rows of $\X$ are anomalous, in the sense of being dissimilar to all other rows. We will use $\X_{n :}$ to denote the $n$th row of $\X$.
\end{comment}

%\subsection{A tour of anomaly detection methods}

Anomaly detection is a well-studied topic in Data Science~\cite{chandola2007outlier,charubook}. Unsupervised anomaly detection aims at discovering
rules to separate normal and anomalous data in the absence of labels. One-Class SVM (OC-SVM) is a popular unsupervised approach to detect anomalies, which constructs
a smooth boundary around the majority of probability mass of data~\cite{Scholkopf:2001}. OC-SVM will be  described in detail in Section~\ref{sec:ocsvm}.
In recent times, several approaches of feature selection and feature extraction methods have been proposed for complex, high-dimensional
data for use with OC-SVM ~\cite{cao2003comparison,neumann2005combined}.
Following the unprecedented success of using deep autoencoder networks, as feature extractors, in tasks as diverse as visual, speech anomaly detection~\cite{chong2017abnormal,marchi2017deep}, several hybrid models that combine feature extraction using deep learning and OC-SVM
have appeared~\cite{sohaib2017hybrid,erfani2016high}. The benefits of leveraging pre-trained transfer learning  representations for anomaly detection in hybrid models was made evident by the results obtained, using two publicly available~\footnote{Pretrained-models:http://www.vlfeat.org/matconvnet/pretrained/.} pre-trained CNN models: ImageNet-MatConvNet-VGG-F (VGG-F) and  ImageNet-MatConvNet-VGG-M (VGG-M)~\cite{andrews2016transfer}. However, these hybrid OC-SVM approaches are decoupled in the sense that the feature learning is task agnostic and not customized for anomaly detecion. Recently a deep model which trains a neural network by minimizing the volume of a hypersphere that encloses the network representations of the data is proposed ~\cite{pmlrv80ruff18a}, our approach differs from this approach by combining the ability of deep networks to extract progressively rich representation of data alongwith the one-class objective, which obtains the hyperplane to separate all the normal data points from the origin.
 %In this paper, we formulate and evaluate a new architecture for anomaly detection in complex, high-dimensional domains by integrating the one-class objective into neural network arhitecture. The proposed one-class neural network (OC-NN) model is trained using standard back-propogation algorithm to learn, rich differentiable features customized for anomaly detection. To the best of our knowledge, this is the first method proposed which
%combines the ability of deep networks to extract progressively rich representation of data
%with the one-class objective of creating a tight envelope around normal data to improve the performance
%for anomaly detection.

\begin{comment}
\subsection{Deep hybrid OC-SVM Models.}
A popular hybrid approach followed in unsupervised anomaly detection is to couple feature reduction and extraction methods alongwith SVMs~\cite{cao2003comparison,neumann2005combined,shen2008feature,widodo2007combination}. Several hybrid models have been proposed to leverage the representational power of deep learning to address scalability issues of SVMs~\cite{song2017hybrid,you2017hybrid,sohaib2017hybrid}. Deep learning architectures such as sparse stacked autoencoder (SAE)-based deep neural networks (DNNs)~\cite{sohaib2017hybrid}, deep belief networks (DBNs)~\cite{erfani2016high} are adopted for extracting robust features. DBNs are generative models consisting of multiple layers of latent variables ("hidden units"). The advantages of using DBNs are two-fold: (a) their ability to perform non-linear dimensionality reduction (b) learn high dimensional data representations. A DBN can be trained efficiently in a greedy layer-wise fashion by using a Restricted Boltzmann Machine (RBM)~\cite{hinton2010practical}. A Restricted Boltzmann machine model can be defined by joint energy function on the hidden variable $h_k$ with $K$ dimension and visible input variable $x_d$ with $D$ dimension as seen in Equation~\ref{energy}. The model parameters $W^P_{dk}$ encode the pairwise compatibility between $x_d$ and $h_k$ while the  parameters $W^B_k$ and $W^C_d$ are biases which, selectively activates either $h_k$ or $x_d$.

\begin{align}
\label{energy}
    E_W(\mbf{x},\mbf{h})&=
-\sum_{d=1}^D\sum_{k=1}^K W^P_{dk}x_dh_k - \sum_{k=1}^KW^B_k h_k - \sum_{d=1}^D W^C_d x_d
\end{align}

In the context of anomaly detection for images, the $\mbf{x}$ variables may represent (e.g  pixels of the image). The hidden units are binary vector of length $K$ less than original dimension of image $D$. Training an RBM implies finding the values of the parameters such that the energy is minimised. One possible approach is to maximise the log-likelihood of $x$ that is estimated by its gradient with respect to the model parameters using Contrastive Divergence (CD). The DBN consisting of stack of RBMs model encodes rich feature representations of the input within hidden units. While a hybrid model consisting of DBN, trained to extract generic underlying features, as inputs to one-class SVM trained are shown to be effective~\cite{erfani2016high}. The experiments in the aforementioned work were performed on real-datasets comprising 1D inputs, synthetic data or texture images, which have lower dimensionality and different data distribution compared to colour images or long protein sequences.
\end{comment}

%%%%%
\subsection{Robust Deep Autoencoders for anomaly detection}
Besides the hybrid approaches which use OC-SVM with deep learning features another approach for anomaly detection is to use deep autoencoders.
Inspired by RPCA~\cite{xu2010robust}, unsupervised anomaly detection techniques such as robust deep autoencoders can be used to separate
normal from anomalous data~\cite{zhou2017anomaly,chalapathy2017robust}.
Robust Deep Autoencoder (RDA) or Robust Deep Convolutional Autoencoder (RCAE) decompose input data $X$ into two parts $X = L_D + S$, where $L_D$ represents the latent representation the hidden layer of the autoencoder. The matrix  $S$ captures noise and outliers which are hard to reconstruct as shown in Equation~\ref{eqn:robust-ae}. The decomposition is carried out by optimizing the objective function shown in Equation~\ref{eqn:robust-ae}.

\begin{equation}
	\label{eqn:robust-ae}
	\min_{\theta, S} + ||L_D - D_{\theta}(E_{\theta}(L_D)) ||_{2}+ \lambda \cdot \| S^T \|_{2,1}
\end{equation}
 \hspace{1.8cm}   $s.t. \hspace{0.2cm} X - L_D -S = 0 $

The above optimization problem is solved using a combination of backpropagation and Alternating Direction Method of Multipliers (ADMM) approach~\cite{boyd2004convex}. In our experiments  we have carried out a detailed comparision between OC-NN and approaches based on robust autoencoders.

\begin{comment}
Notice that in the constraint of Equation~\ref{eqn:robust-ae} we split the input data X into two
parts, $L_D$ and $S$. $L_D$ is the input to an autoencoder $D_{\theta}(E_{\theta}(L_D))$ and
we train this autoencoder by minimizing the reconstruction error
 $||L_D - D_{\theta}(E_{\theta}(L_D)) ||_{2}$ through back-propagation. $S$, on the other
hand, contains noise and outliers which are learnt applying proximal methods following Alternating Direction Method of Multipliers (ADMM) ~\cite{boyd2004convex}. While $\lambda$ tuning parameter is selected in a semi-supervised fashion through grid-search for optimal $F1$ score.
RDA could be leveraged to detect anomalies similar to OC-SVM setting. The results obtained using our proposed approach of OC-NN are comparable to the results obtained on anomaly detection task on both MNIST and Cifar-10 datasets, as illustrated in Table~\ref{tbl:mnist-usps-anomaly-results-summary} and Table~\ref{tbl:cifar-10-pfam-anomaly-results-summary}.
\end{comment}

\subsection{One-Class SVM for anomaly detection}
\label{sec:ocsvm}

One-Class SVM (OC-SVM) is a widely used approach to discover anomalies in an unsupervised fashion~\cite{scholkopf2002support}. OC-SVMs are a special case of support vector machine, which learns a  hyperplane to separate all the data points from the origin in a reproducing kernel Hilbert space (RKHS) and maximises the distance from this hyperplane to the origin. Intuitively in OC-SVM all the data points are considered as positively labeled instances and the origin
as the only negative labeled instance. More specifically, given a training data $\X$, a set without any class information, and $\Phi(\X)$  a RKHS map function
from the input space to the feature space $F$,  a
hyper-plane or linear decision function $f(\X_{n :})$ in the feature space $F$ is constructed as
$f( \X_{n :} ) = w^T \Phi(\X_{n :}) - \bias$,  to separate as many as possible of the mapped vectors
${ \Phi(\X_{n :}), n: 1,2,...,N}$ from the origin. Here  $w$ is the norm perpendicular to the hyper-plane and $\bias$ is the bias of the hyper-plane. In order to
obtain $w$ and $\bias$, we need to solve the
following optimization problem,

\begin{equation}
\label{eqn:ocsvm-objective}
 \min_{w,\bias} \frac{1}{2} \| w \|_{2}^2+ \frac{1}{\nu} \cdot \frac{1}{N} \sum_{n = 1}^N \max( 0, \bias - \langle w, \Phi(\X_{n :}) \rangle ) - \bias.
\end{equation}

where $\nu \in (0,1)$, is a parameter that
controls a trade off between maximizing the distance of the
hyper-plane from the origin and the number of data points
that are allowed to cross the hyper-plane (the false positives).
%When $\nu$ is small, fewer data fall on the same side of the hyper-plane as the origin in the
%feature space $F$.


\section{Poisson and Laplace Equations}
\subsection{The Boundary Value Problem}
Many problems in mathematical physics can be reduced to the form:
$$\nabla^2\phi=F$$
where $F$ is known.
This form of equations are called Poisson's Equation.
In particular, if $F\equiv 0$, this is called Laplace's Equation.
We would want to solve them in either all of $\mathbb R^n$ or on some domain $\Omega\subset\mathbb R^n$.
We are, sometimes, only interested in the cases $n=2,3$.
Note that we require $\phi$ to be well-defined and smooth on all of $\Omega$.
For example, it is true that $\nabla^2(1/|\underline{x}|)=0$ for $\underline{x}\neq\underline{0}$, however it is not true for any domain containing $\underline{0}$.
We would want to solve this PDE subject to some boundary conditions, so $\phi$ will have predetermined behaviour in $\partial\Omega$ or as $|\underline{x}|\to\infty$ when working in $\mathbb R^n$.\\
Two widely studied boundary conditions are the Dirichlet Problem
$$\begin{cases}
    \nabla^2\phi=F\text{, on $\Omega$}\\
    f\text{, on $\partial\Omega$}
\end{cases}$$
and the Neumann Problem
$$\begin{cases}
    \nabla^2\phi=F\text{, on $\Omega$}\\
    \partial\phi/\partial\underline{n}=\underline{n}\cdot\nabla\phi=g\text{, on $\partial\Omega$}
\end{cases}$$
Beware that we must interpret boundary data (or boundary conditions) correctly.
We want $\phi$ or $\partial\phi/\partial\underline{n}$ to approach the boundary data continuously as $\underline{x}$ tends towards the boundary.
So apart from requiring $\phi$ to be $C^2$ in $\Omega$, it must also extend to $\partial\Omega$ continuously.
\begin{example}[Non-example]
    If we want to solve the Navier-Stokes Equation
    $$\frac{\partial\underline{u}}{\partial t}+(\underline{u}\cdot\nabla)\underline{u}-\nu\nabla^2\underline{u}=-\nabla p,\nabla\cdot\underline{u}=0,\underline{u}(\underline{x},0)=\underline{u_0}(\underline{x})$$
    but ignore the condition on continuous extension we said earlier, then the following solution satisfies the equation
    $$\underline{u}=\begin{cases}
        0\text{, if $t>0$}\\
        \underline{u_0}\text{, if $t=0$}
    \end{cases},p\equiv 0$$
    But obviously we are not getting a million for it.
\end{example}
\begin{example}
    Let $r=|\underline{x}|$, we consider the Dirichlet Problem
    $$\begin{cases}
        \nabla^2\phi=r\text{, for $r<a$}\\
        \phi=1\text{, for $r=a$}
    \end{cases}$$
    By symmetry, we want to write $\phi=\phi(r)$, so
    $$r=\nabla^2\phi=\frac{1}{r^2}\frac{\mathrm d}{\mathrm dr}\left( r^2\frac{\mathrm d\phi}{\mathrm dr} \right)\implies \phi=\frac{r^3}{12}-\frac{A}{r}+B$$
    The boundary condition then implies
    $$\phi(r)=1+\frac{r}{12}(r^2-a^2)$$
\end{example}
Consider now a generic linear problem, say $L\phi=F$ in $\Omega$ and $B\phi=f$ on $\partial\Omega$ where $L,B$ are linear differential operators.
Suppose $\phi_1,\phi_2$ are solutions to the system, then if we let $\psi=\phi_1-\phi_2$, we have $L\psi=B\psi=0$.
If we can show that this solves to $\psi=0$, then we know the uniqueness of the solution to our original equation.
So solution to a linear problem is unique iff the only solution to the corresponding homogeneous problem is $0$.
\begin{proposition}
    Solution to the Dirichlet Problem is unique.
    Solution to the Neumann Problem is unique up to a constant.
\end{proposition}
\begin{proof}
    Consider the homogeneous problem
    $$\begin{cases}
        \nabla^2\psi=0\text{, in $\Omega$}\\
        B\psi=0\text{, in $\partial\Omega$}
    \end{cases}$$
    where $B\psi=\psi$ in the Dirichlet case and $B\psi=\partial\psi/\partial\underline{n}$ in the Neumann case.
    Consider
    $$I[\phi]=\int_\Omega|\nabla\psi|^2\,\mathrm dV\ge 0$$
    But we have
    \begin{align*}
        I[\phi]&=\int_\Omega\nabla\cdot(\psi\nabla\psi)-\psi\nabla^2\psi\,\mathrm dV\\
        &=\int_\Omega\nabla\cdot(\psi\nabla\psi)\,\mathrm dV\\
        &=\int_{\partial\Omega}\psi\nabla\psi\cdot\mathrm d\underline{S}\\
        &=\int_{\partial\Omega}\psi\frac{\partial\phi}{\partial\underline{n}}\,\mathrm dS\\
        &=0
    \end{align*}
    in both cases, $\nabla\psi=0$ thoughout $\Omega$, so $\psi$ is continuous throughout $\Omega$.
    So for the Dirichlet Problem we have $\psi\equiv 0$ and $\psi$ is constant in the Neumann Problem.
\end{proof}
\begin{example}
    Consider the charge distribution (where $r=\underline{\underline{x}}$),
    $$\rho(\underline{x})=\begin{cases}
        0\text{, if $r<a$}\\
        F(r)\text{, if $r\ge a$}
    \end{cases}$$
    The corresponding potential $\phi$ for electric field $\underline{E}=-\nabla\phi$ would have
    $$\nabla^2\phi=-\epsilon_0^{-1}\rho$$
    On $r<a$, we have $\nabla^2\phi=0$, so by symmetry, we write $\phi=\phi(r)$.
    Note that on $r=a$, $\phi=\phi(a)$ is a constant.
    We can see that $\phi(r)=\phi(a)$ on $r<a$ actually works, but by the preceding proposition, it is the solution on $r<a$, so $\underline{E}\equiv \underline{0}$ on $r<a$.\\
    This looks like the Newton's Shell Theorem.
\end{example}
\subsection{Gauss's Flux Method}
There is a clever way to get particular solutions to Poisson's Equation when the forcing term has spherical symmetry.
Suppose the forcing term is in the form $F(r)$ where $r=|\underline{x}|$, and we are interested in a particular solution of the equation $\nabla^2\phi=F(r)$.
We want to look for solutions of the form $\phi=\phi(r)$, in which case $\nabla\phi=\phi^\prime(r)\underline{e_r}$.
If we integrate this over the ball $|\underline{x}|\le R$, then since $\nabla^2=\nabla\cdot\nabla$,
$$\int_{|\underline{x}|\le R}F\,\mathrm dV=\int_{|\underline{x}|\le R}\nabla^2\phi\,\mathrm dV=\int_{|\underline{x}|=R}\nabla\phi\cdot\mathrm d\underline{S}$$
by Divergence Theorem.
Note that $\mathrm d\underline{S}=\underline{e_r}\mathrm dS$, so
$$\int_{|\underline{x}|=R}\nabla\phi\cdot\mathrm d\underline{S}=\int_{|\underline{x}|=R}\phi^\prime(r)\,\mathrm dS=\phi^\prime(R)\int_{|\underline{x}|=R}\mathrm dS=4\pi R^2\phi^\prime(R)$$
Define
$$Q(R)=\int_{|\underline{x}|\le R}F(r)\,\mathrm dV$$
then $Q(R)=4\pi R^2\phi^\prime(R)$.
If $F$ is interpreted as the charge density, then we can interpret $Q(R)$ as total charge (or other stuff) inside the ball of radius $R$.
We can integrate this to get a particular solution.
In particular, we observe that $\phi^\prime(R)=Q(R)/(4\pi R^2)$, which is just the inverse square law.
\begin{example}
    Consider charge density
    $$\rho(r)=\begin{cases}
        \rho_0\text{, if $r\le a$}\\
        0\text{, otherwise}
    \end{cases}$$
    The electric field corresponding to $\rho$ satisfies $\nabla\cdot\underline{E}=\epsilon_0^{-1}\rho$.
    In electrostatics, $\underline{E}=-\nabla\phi$ for a potential $\phi$, so we have
    $$\nabla^2\phi=-\frac{\rho}{\epsilon_0}$$
    By previous calculations
    $$\phi^\prime(R)=-\frac{1}{4\pi\epsilon_0}\frac{Q(R)}{R^2},Q(R)=\begin{cases}
        4\pi R^3\rho_0/3\text{, if $R\le a$}\\
        Q=Q(a)=4\pi a^3\rho_0/3\text{, otherwise}
    \end{cases}$$
    So for $r>a$, we have
    $$\phi^\prime(r)=-\frac{1}{4\pi\epsilon_0}\frac{Q}{r^2}\implies\underline{E}(r)=\frac{1}{4\pi\epsilon_0}\frac{Q}{r^2}\underline{e_r}$$
    Let $a\to 0$ in such a way that $a^3\rho_0$ remains constant (so we change $\rho_0$), so $Q$ remains constant.
    Therefore the electric field induced by a point charge $Q$ at $\underline{x}=\underline{0}$ would have
    $$\underline{E}(\underline{x})=\frac{1}{4\pi\epsilon_0}\frac{Q}{r^2}\underline{e_r}=\frac{1}{4\pi\epsilon_0}\frac{Q}{|\underline{x}|^3}\underline{x},\phi(\underline{x})=\frac{1}{4\pi\epsilon_0}\frac{Q}{|\underline{x}|}$$
    for $r>0$ and $\phi(\infty)=0$.
\end{example}
Just an aside, if we want the existece of solutions to $-\nabla^2\phi=\epsilon_0^{-1}\rho(\underline{x})$, Gauss proved that it suffices to consider equations of the form $K\sigma=f$ which looks like linear algebra, but in a infinite dimensional vector spaces, where we no longer have sequential compactness.
This induces the study of functional analysis and operator theory.\\
Suppose we have $F=F(\rho)$ where $\rho=x^2+y^2$.
To solve $\nabla^2\varphi=F(\rho)$, it is natural to try solutions of the form $\varphi=\varphi(\rho)$.
In this case, $\nabla\varphi=\varphi^\prime(\rho)\underline{e_\rho}$, so obviously we want to integrate it over a cylinder $V$ of height $1$, $V=\{0\le\rho\le R,0\le\phi\le 2\pi,z_0\le z\le z_0+1\}$, as $\underline{e_\rho}\perp\underline{e_z}$,
$$Q(R)=\int_VF\,\mathrm dV=\int_{\partial V}\nabla\varphi\cdot\mathrm d\underline{S}=\varphi^\prime(R)2\pi R\implies\varphi^\prime(R)=\frac{Q(R)}{2\pi R}$$
Note that by calculation we have
$$Q(R)=2\pi\int_0^RF(\rho)\rho\,\mathrm d\rho\implies\varphi^\prime(\rho)=\frac{1}{R}\int_0^RF(\rho)\rho\,\mathrm d\rho$$
\begin{example}
    Due to conflicts of notation we write $s^2=x^2+y^2$ instead of $\rho$ (as we want to do electromagnetism).
    Suppose we have charge density
    $$\rho(s)=\begin{cases}
        \rho_0\text{, for $s\le a$}\\
        0\text{, otherwise}
    \end{cases}$$
    For electrostatic potential $\varphi$, we still have $-\nabla^2\varphi=\epsilon_0^{-1}\rho$, so
    $$\varphi^\prime(R)=-\frac{1}{\epsilon_0R}\int_0^R\rho(s)s\,\mathrm ds=\begin{cases}
        -\epsilon_0^{-1}R^{-1}\rho_0R^2/2\text{, if $R\le a$}\\
        -\epsilon_0^{-1}R^{-1}\rho_0a^2/2\text{, otherwise}\\
    \end{cases}$$
    Then shrink $a\to 0$ with $\rho_0a^2$ fixed, then we have $\underline{E}\propto s^{-1}\underline{e_s}$, which is similar to the superposition a bunch of point charges in a line.
\end{example}
\subsection{The Superposition Principle}
For a linear problem, we can (most of the time) solve them by their defining property of being linear.
Say if we have $L\psi_n=F_n$, then $L(\sum_n\psi_n)=\sum_nF_n$.
This allows us to superpose solutions.
If we write a forcing term $F$ as $\sum_nF_n$ and solve for $\psi_n$ individually, then we can obtain the required solution by summing up all of them.
\begin{example}
    1. Recall the solutions for an electric potential $\phi$ and electric field $\underline{E}=-\nabla\phi$.
    For charge distribution with spherical symmetry, can be found by e.g. Gauss's flux method.
    If we shrink the radius to $0$, we obtain a point charge $Q_{\underline{a}}$ for at $\underline{a}$ where
    $$\phi(\underline{x})=\frac{Q_{\underline{a}}}{4\pi\epsilon_0}\frac{1}{|\underline{x}-\underline{a}|}$$
    and $\rho(\underline{x})=Q_{\underline{a}}\delta(\underline{x}-\underline{a})$.
    For consistency with Gauss's Law, we shall (and indeed can) obtain
    $$\nabla^2\left( -\frac{1}{4\pi}\frac{1}{|\underline{x}-\underline{a}|} \right)=\delta(\underline{x}-\underline{a})$$
    Now consider the electric potential due to $2$ charges $Q_{\underline{a}},Q_{\underline{b}}$ at $\underline{x}=\underline{a},\underline{b}$.
    The charge distribution would be $Q_{\underline{a}}\delta(\underline{x}-\underline{a})+Q_{\underline{b}}\delta(\underline{x}-\underline{b})$, so we can superpose the solutions correspondingly in Gauss's Law to get the potential
    $$\phi(\underline{x})=\frac{Q_{\underline{a}}}{4\pi\epsilon_0}\frac{1}{|\underline{x}-\underline{a}|}+\frac{Q_{\underline{b}}}{4\pi\epsilon_0}\frac{1}{|\underline{x}-\underline{b}|}$$
    2. We want to find the potential outside the solid sphere $|\underline{x}|\le R$ of uniform charge density $\rho_0$, from which several spheres $|\underline{x}-\underline{a_i}|\le R_i$ with $i=1,2,\ldots,n$ are removed (given that the spheres do not cross the boundary).
    To find the solution, we can superpose the solution for the charge distribution $\rho_0$ for $|\underline{x}|\le R$ and the solutions for the charge distribution $-\rho_0$ for $|\underline{x}-\underline{a_i}|\le R_i$.
    So
    $$\phi(\underline{x})=\frac{1}{4\pi\epsilon_0}\left( \frac{Q}{|\underline{x}|}-\sum_{i=1}^n\frac{Q_i}{|\underline{x}-\underline{a_i}|} \right),Q=\frac{4}{3}\pi R^3\rho_0,Q_i=\frac{4}{3}\pi R_i^3\rho_0$$
    for $|\underline{x}|>R$.
\end{example}
\subsection{Integral Solutions}
In the examples above, we found solutions by superposing (or superimposing) potentials corresponding to charges in different points, which gives solutions of the form
$$\sum_i\frac{Q_i}{4\pi\epsilon_0}\frac{1}{|\underline{x}-\underline{a_i}|}$$
This leads to a more general form of superposition of potentials, by thinking of each infinitesimal part as individual point charges, which is just a integral in the following form:
$$\int_{\mathbb R^3}\frac{F(\underline{y})}{|\underline{x}-\underline{y}|}\,\mathrm dV(\underline{y})$$
Up to some factor.
\begin{proposition}
    The unique solution to the Dirichlet problem
    $$\begin{cases}
        \nabla^2\phi=F\text{, in $\mathbb R^3$}\\
        \phi(\underline{x})\to 0\text{ as $|\underline{x}|\to\infty$}
    \end{cases}$$
    (Assuming $F$ decreases sufficiently rapidly as $|\underline{x}|\to\infty$) is
    $$\phi(\underline{x})=-\frac{1}{4\pi}\int_{\mathbb R^3}\frac{F(\underline{y})}{|\underline{x}-\underline{y}|}\,\mathrm dV$$
\end{proposition}
\begin{proof}
    The solution can be verified by using
    $$\nabla\left( -\frac{1}{4\pi}\frac{1}{|\underline{x}-\underline{a}|} \right)=\delta(\underline{x}-\underline{a})$$
    And differentiating under the integral sign.
\end{proof}
To justify (in an applied way, of course) the identity used above, we use the divergence theorem,
\begin{align*}
    \int_{|\underline{x}|\le R}\nabla^2\left( \frac{1}{|\underline{x}|} \right)\,\mathrm dV&=\int_{|\underline{x}|=R}\nabla\left( \frac{1}{r} \right)\cdot\mathrm d\underline{S}\\
    &=-\frac{1}{R^2}\int_{|\underline{x}|=R}\underline{e_r}\cdot\underline{e_r}\,\mathrm dS\\
    &=\frac{1}{R^2}4\pi R^2\\
    &=4\pi
\end{align*}
which is true for any $R>0$, so it is natural (or maybe not) to write the identity.\\
The solution can be regarded as the sum of contributions to the potential to any possible volume elements (that actually contribute).
\subsection{Harmonic Functions}
If $\phi=\phi(\underline{x})$ satisfies Laplace's Equation $\nabla^2\phi=0$, then $\phi$ is harmonic.
\begin{proposition}[Mean-Value Property]
    If $\varphi$ is harmonic on some open $\Omega\subset\mathbb R^3$, then
    $$\varphi(\underline{a})=\frac{1}{4\pi r^2}\int_{|\underline{x}-\underline{a}|=r}\varphi(\underline{x})\,\mathrm dS$$
    where $\underline{a}\in\Omega$ and the ball centered at $\underline{a}$ with radius $r$ is contained in $\Omega$.
\end{proposition}
\begin{proof}
    Define a function
    \begin{align*}
        f(r)&=\frac{1}{4\pi r^2}\int_{|\underline{x}-\underline{a}|=r}\varphi(\underline{x})\,\mathrm dS\\
        &=\frac{1}{4\pi r^2}\int_{|\underline{x}|=r}\varphi(\underline{x}+\underline{a})\,\mathrm dS\\
        &=\frac{1}{4\pi r^2}\int_0^{2\pi}\int_0^\pi \varphi(\underline{a}+r\underline{e_r})r^2\sin\theta\,\mathrm d\theta\,\mathrm d\phi\\
        &=\frac{1}{4\pi}\int_0^{2\pi}\int_0^\pi \varphi(\underline{a}+r\underline{e_r})\sin\theta\,\mathrm d\theta\,\mathrm d\phi
    \end{align*}
    So differentiating this gives
    \begin{align*}
        f^\prime(r)&=\frac{1}{4\pi}\int_0^{2\pi}\int_0^\pi \nabla\varphi(\underline{a}+r\underline{e_r})\cdot\underline{e_r}\sin\theta\,\mathrm d\theta\,\mathrm d\phi\\
        &=\frac{1}{4\pi r^2}\int_{|\underline{x}|=r}\nabla\varphi(\underline{a}+\underline{x})\cdot\mathrm d\underline{S}\\
        &=\frac{1}{4\pi r^2}\int_{|\underline{x}|\le r}\nabla^2\varphi(\underline{a}+\underline{x})\,\mathrm dV\\
        &=0
    \end{align*}
    So $f$ is constant.
    Let $r\to 0$ gives $f\equiv \varphi(\underline{a})$.
\end{proof}
\begin{proposition}
    For a smooth function $\varphi$
    $$\nabla^2\varphi=\lim_{r\to 0}\frac{6}{r^2}\left(\frac{1}{4\pi r^2}\int_{|\underline{x}-\underline{a}|=r}\varphi(\underline{x})\,\mathrm dS-\varphi(\underline{a})\right)$$
\end{proposition}
\begin{proof}
    Consider the function
    $$g(r)=\frac{1}{4\pi r^2}\int_{|\underline{x}-\underline{a}|=r}\varphi(\underline{x})\,\mathrm dS-\varphi(\underline{a})$$
    then use the same trick as above, we have
    $$g^\prime(r)=\frac{1}{4\pi r^2}\int_{|\underline{x}|\le r}\nabla^2\varphi(\underline{x})\,\mathrm dV$$
    But
    \begin{align*}
        \int_{|\underline{x}|\le r}\nabla^2\varphi(\underline{x})\,\mathrm dV&=\int_{|\underline{x}|\le r}\nabla^2\varphi(\underline{a})\,\mathrm dV+\left( \int_{|\underline{x}|\le r}\nabla^2\varphi(\underline{x})-\nabla^2\varphi(\underline{a})\,\mathrm dV \right)\\
        &=\frac{4\pi r^3}{3}\nabla^2\varphi(\underline{a})+o(r^3)
    \end{align*}
    as $r\to 0$.
    So
    $$g^\prime(r)=\frac{r}{3}\nabla^2\varphi(\underline{a})+o(r)$$
    But then $g^\prime(r)=g^\prime(0)+rg^\prime(0)+o(r)$ by Taylor's Theorem, so $g^\prime(0)=0,g^{\prime\prime}(0)=3^{-1}\nabla^2\varphi(\underline{a})$.
    So
    $$g(r)=g(0)+rg^\prime(0)+r^2\frac{g^{\prime\prime}(0)}{2}+o(r^2)=\frac{r^2}{6}\nabla^2\varphi(\underline{a})+o(r^2)$$
    So taking the stated limit gives the solution.
\end{proof}
So the Laplacian measures how much the value of the function at the point differs from the average of the values on the infinitesimal sphere centered at the same point.
\begin{proposition}[Maximum Principle]
    If $\varphi$ is harmonic on an open, path-connected $\Omega\in\mathbb R^3$, then there is an $\underline{a}\in\Omega$ such that $\varphi(\underline{x})\le\varphi(\underline{a})$ throughout $\Omega$, then $\varphi$ is constant.
\end{proposition}
\begin{proof}
    If $\varphi$ is harmonic, then the mean-value property holds, so
    $$\varphi(\underline{a})=\frac{1}{4\pi\epsilon^2}\int_{|\underline{x}-\underline{a}|=\epsilon}\varphi(\underline{x})\,\mathrm dS$$
    for $\epsilon$ sufficiently small.
    If $\varphi(\underline{x})\le\varphi(\underline{a})$ throughout $\Omega$, then
    $$0=\frac{1}{4\pi\epsilon^2}\int_{|\underline{x}-\underline{a}|=\epsilon}\varphi(\underline{a})-\varphi(\underline{x})\,\mathrm dS$$
    But the integrand is nonnegative, so we must have $\varphi(\underline{x})=\varphi(\underline{a})$ for any $\underline{x}$ in the sphere we are integrating, hence the ball enclosed.
    Now take any $\underline{y}\in\Omega$ and consider a path joining $\underline{a}$ and $\underline{y}$.
    Then by compactness, there is a finite collection of spheres in $\Omega$ whose interior covers the path.
    But then each adjascent two of them will share at least one interior points, and if $f$ achieve $f(\underline{a})$ at that point, then $f(\underline{x})\le f(\underline{a})$ for any $\underline{x}$ in each ball, so use the argument inductively gives $f(\underline{y})=f(\underline{a})$.
\end{proof}
One can also prove the last part without introducing compactness:
Assuming that we have already shown that for any $\underline{b}\in\Omega$ with $\varphi(\underline{b})=\alpha=\varphi(\underline{a})$, there is some $\epsilon>0$ such that $\varphi(\underline{x})=\varphi(\underline{b})=\alpha$ for any $|\underline{x}-\underline{b}|<\epsilon$ (by e.g. the first part of our proof above).
Consider the set $\varphi^{-1}(\{\alpha\})$, which is closed by continuity and open by above, which contradicts the path-connectedness (hence connectedness) of $\Omega$.


\documentclass[12pt]{article}
\newcommand{\m}{\mathrm{m}}
\newcommand{\cm}{\mathrm{cm}}
\newcommand{\s}{\mathrm{s}}
\newcommand{\dd}{\mathrm{d}}
\newcounter{problem}
\begin{document}\thispagestyle{empty}

\section*{NYU General Physics 1---Problem set 10}

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
Consider a function $$x(t) = A\,\sin(\omega\,t + \phi) \quad,$$ where
$A$, $\omega$, and $\phi$ are constants.  Now consider the
``differential equation'' $$m\,\frac{\dd^2 x}{\dd t^2} = -k\,x
\quad.$$ Take two derivatives of $x(t)$ and plug the answer into the left-hand
side of the differential equation.  Under what conditions will the
given $x(t)$ satisfy the differential equation?  That is, what needs
to be true about $A$, $\omega$, and $\phi$?  How is the story
different if you have $\cos$ instead of $\sin$?

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
Consider a string stretched in the $x$ direction, waving transversely
(look it up), with the $y$ displacement being a function of position
$x$ and time $t$ according to
$$ y(x,t) = A\,\cos(\frac{2\pi\,x}{\lambda} - \frac{2\pi\,t}{T}) $$
where $A$ is an amplitude, $\lambda$ is the wavelength, and $T$ is
the period.  For definiteness, set $A=1\,\cm$, $\lambda=0.75\,\m$, and
$T=0.25\,\s$.

\textsl{(a)} Draw a picture of $y(t)$ over the time period $0<t<1\,\s$
for the position $x=0.0\,\m$

\textsl{(b)} Draw a picture of $y(x)$ over the spatial interval $0<x<3\,\m$
for the time $t=0.00\,\s$

\textsl{(c)} Draw a picture of $y(x)$ over the spatial interval $0<x<3\,\m$
for the time $t=0.05\,\s$.

\textsl{(c)} Draw a picture of $y(x)$ over the spatial interval $0<x<3\,\m$
for the time $t=0.10\,\s$.

\textsl{(d)} Which way is the wave moving, and how fast?

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
\textsl{(a)}~For an ideal gas, find out what the ``intensive''
properties are.  What combinations of them have units of speed?  Can
you find more than one?  Find the true speed of sound on the internet
and check your dimensional answer(s) for standard temperature and
pressure.  How far off are you and are you upset by that?

\textsl{(b)} An organ pipe of length $L$ (filled with air at STP)
supports a standing wave (like the standing wave on the string done in
lecture) but with $L$ being one-quarter wavelength.  What length $L$
do you need to make a pipe that plays the note middle C?  Use the
Wikipedia-reported value for the speed of sound $c_s$ in air at STP,
and use the fact that frequency $f$ and wavelength $\lambda$ are
related to the speed of sound $c_s$ in the most trivial way possible
given their dimensions!

\end{document}


\section{Bedrock Erosion}\label{erosion.sec.hb}
Sediments are produced at the ice base by eroding the hard bedrock. Here, sediment production depends on basal velocities (and thus basal thermal regime) and ice thickness:
\begin{equation}
  \dot{E} = -f|\vec{u}_{\text{bas}}|H
\end{equation}
As an alternative, sediment production could also be proportional to the product of basal velocities and basal shear stresses, $\vec{\tau}$, i.e.
\begin{equation}
  \dot{E} = f\vec{u}_{\text{bas}}\cdot\vec{\tau}.
\end{equation}
The total amount of eroded bedrock is then
\begin{equation}
  E=\int_{0}^t\dot{E}dt'
\end{equation}

\section{Basic Transport Parameterisation}\label{erosion.sec.basic_trans}
The simple parameterisation assumes that sediment velocities are proportional to the basal ice velocities and that the maximum thickness of the deforming bed is a linear function of basal shear stress:
\begin{equation}
  z_{\text{max}} = a+b|\vec{\tau}_b|.
\end{equation}

\input{\dir/transport.tex}

\section{Isostatic Adjustment}
Sediment movement affects isostatic adjustment. This isostatic effect is taken into account by modifying the unloaded (no ice sheet) equilibrium bedrock topography. $h_0$:
\begin{equation}
  h_0=h_0^\ast+E-w_{\text{seds}}
\end{equation}
where $w_{\text{seds}}$ is the equilibrium bedrock depression due to erosion. $w_{\text{seds}}$ can be calculated using either the local or elastic lithosphere approximation (see my thesis).


\section{Advection} \label{sec:adv}
Advection is a fluid flow transporting something with it as it flows. This can be temperature, gas, solids or other fluids. In our case we will be looking at temperature.

\subsection{Thermal Diffusion}
As of this time, what you notice if you run the model is that the winds only get stronger and stronger (and the model is hence blowing up, which means that the numbers increase so dramatically
that it is no longer realistic). This is because there is no link yet between the velocities of the atmosphere and the temperature. Currently, any air movement does not affect the temperature
in the atmosphere of our model while it does in reality. So we need to change some calculations to account for that. Thermal diffusion helps with spreading out the temperatures and tempering
the winds a bit.

The diffusion equation, as written in \autoref{eq:diffusion}, describes how the temperature spreads out over time\cite{diffusion}. The symbols in the equation represent:

\begin{itemize}
    \item $u$: A vector consisting out of 4 elements: $x, y, z, t$. $x, y, z$ are the local coordinates and $t$ is time.
    \item $\alpha$: The thermal diffusivity constant.
    \item $\nabla^2$: The Laplace operator, more information in \autoref{sec:laplace}.
    \item $\bar{u}$: The time derivative of $u$, or in symbols $\frac{\delta u}{\delta t}$.
\end{itemize}

\begin{equation}
    \label{eq:diffusion}
    \bar{u} = \alpha \nabla^2 u
\end{equation}

Now to get this into code we need the following algorithms \autoref{alg:laplacian} and \autoref{alg:diffusion}. \autoref{alg:laplacian} implements the laplacian operator, whereas
\autoref{alg:diffusion} implements the diffusion calculations.  $\nabla^2$ in \autoref{alg:diffusion} represents the call to \autoref{alg:laplacian}.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of diffusion}
    \label{alg:diffusion}
    $T_a \leftarrow T_a + \delta t \alpha_a \nabla^2(T_a)$ \;
    $T_p \leftarrow T_p + \delta t \alpha_p \nabla^2(T_p)$ \;
\end{algorithm}

\subsection{Adding in Advection}
With thermal diffusion in place, the temperature will spread out a bit, however air is not transported yet. This means that the winds we simulate are not actually moving any air. Advection is
going to change that. The advection equation is shown in \autoref{eq:advection}. The symbols are:

\begin{itemize}
    \item $\psi$: What is carried along (in our case temperature, \si{K}).
    \item $t$: The time (\si{s}).
    \item $u$: The fluid velocity vector (\si{ms^{-1}}).
    \item $\nabla$: The divergence operator (as explained in \autoref{sec:laplace}).
\end{itemize}

\begin{equation}
    \label{eq:advection}
    \frac{\delta \psi}{\delta t} + \nabla \cdot (\psi u) = 0
\end{equation}

With the divergence functon defined in \autoref{alg:divergence}, we now need to adjust \autoref{alg:diffusion} to incorporate this effect. The resulting algorithm can be found in
\autoref{alg:advection}. Here $\nabla$ represents the function call to \autoref{alg:divergence}.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of advection}
    \label{alg:advection}
    $T_{add} \leftarrow T_a + \delta t \alpha_a \nabla^2(T_a) + \nabla(T_a)$ \;
    $T_a \leftarrow T_a + T_{add}[5:-5, :] \text{ //Only add } T_{add} \text{ to } T_a \text{ for indices in the interval } [-nlat + 5, nlat - 5]$. \;
    $T_p \leftarrow T_p + \delta t \alpha_p \nabla^2(T_p)$ \;
\end{algorithm}

Now that we have the air moving, we also need to account for the moving of the density. This is because moving air to a certain place will change the air density at that place if the air at that
place does not move away at the same rate. Say we are moving air to $x$ at $y \ ms^{-1}$. If air at $x$ moves at a rate $z \ ms^{-1}$ and $z \neq y$ then the air density at $x$ will change.
The equation we will need for that is the mass continuity equation as shown in \autoref{eq:mass continuity} \cite{masscontinue}.

\begin{equation}
    \label{eq:mass continuity}
    \frac{\delta \rho}{\delta t} + \nabla \cdot (\rho v) = 0
\end{equation}

Using this equation means that we will no longer assume that the atmosphere is incompressible. Therefore we need to change a few things in the code. First we need to change the $\rho$ in
\autoref{alg:stream3}. Since $\rho$ is no longer constant we need to access the right value of $\rho$ by specifying the indices. So $\rho$ will change to $\rho[lat, lon]$. Furthermore we need
to calculate $\rho$ after the movement of air has taken place, so we need to change \autoref{alg:advection} as well to include the calculations for $\rho$. The new version can be found in
\autoref{alg:advectionv2}. Again the $\nabla$ represents the call to \autoref{alg:divergence}.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of advection}
    \label{alg:advectionv2}
    $T_{add} \leftarrow T_a + \delta t \alpha_a \nabla^2(T_a) + \nabla(T_a)$ \;
    $T_a \leftarrow T_a + T_{add}[5:-5, :] \text{ //Only add } T_{add} \text{ to } T_a \text{ for indices in the interval } [-nlat + 5, nlat - 5]$. \;
    $\rho \leftarrow \rho + \delta t \nabla \rho$ \;
    $T_p \leftarrow T_p + \delta t \alpha_p \nabla^2(T_p)$ \;
\end{algorithm}

Currently the advection does not work like it should. This is probably due to boundary issues, where we get too close to the poles and it starts freaking out there \cite{simon}. So to fix this
we are going to define boundaries and assume that the advection only works within those boundaries. We only let it change by half of the values. The changes are incorporated in
\autoref{alg:advectionfix}. The reason why we mention this seperately, in contrast to the other fixes that we have incorporated throughout the manual already, is the accompanying change with the
boundary.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of advection}
    \label{alg:advectionfix}
    $T_{add} \leftarrow T_a + \delta t \alpha_a \nabla^2(T_a) + \nabla(T_a)$ \;
    $T_a \leftarrow T_a - 0.5T_{add}[adv\_bound:-adv\_boun, :] \text{ //Only subtract } T_{add} \text{ to } T_a \text{ for indices in the interval } [-nlat + adv\_boun, nlat - adv\_boun]$. \;
    $\rho[adv\_boun: -adv\_boun, :] \leftarrow \rho - 0.5(\delta t \nabla \rho) \text{ //Only change the density for indices in the interval } [-nlat + adv\_boun, nlat - adv\_boun]$ \;
    $T_p \leftarrow T_p + \delta t \alpha_p \nabla^2(T_p)$ \;
\end{algorithm}

\subsection{Layers, layers and layers}
With the atmospheric layers, and all matrices that have an extra dimension to account for it, we need to add the correct indices to the advection algorithm \autoref{alg:advectionfix}. Let us
add it, with \autoref{alg:advection layer} as a result. Here the ':' means all indices of the 3 dimensional matrix. Also keep in mind that the potential temperature is described and discussed in
\autoref{sec:thermal pot}.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of advection}
    \label{alg:advection layer}
    $T_{add} \leftarrow T_a + \delta t \alpha_a \nabla^2(T_{pot}) + \nabla(T_{pot})$ \;
    $T_{add} \leftarrow 0.5T_{add}[adv\_boun:-adv\_boun, :, :] \text{ //Only halve } T_{add} \text{ for indices in the interval } [-nlat + adv\_boun, nlat - adv\_boun]$. \;
    $T_{add}[-adv\_boun:, :, :] \leftarrow 0 \text{//Only replace by 0 in the interval [0, adv\_boun]}$ \;
    $T_{add}[:adv\_boun, :, :] \leftarrow 0 \text{//Only replace by 0 in the interval [nlat - adv\_boun, nlat]}$ \;
    $T_{pot} \leftarrow T_{pot} - T_{add}[adv\_boun:-adv\_boun, :, :] \text{ //Only subtract } T_{add} \text{ from } T_{pot} \text{ for indices in the interval }$
        $[-nlat + adv\_boun, nlat - adv\_boun]$. \;
\end{algorithm}

\subsection{Adiabatic Motion} \label{sec:thermal pot}
Up until now, we have been moving air and the density of the atmosphere. However we have not transported any temperature yet. What this means is that if we have a packet of air (see it as a box
filled with air, but the box is invisible) $P$ which is at the planet surface. There $P$ has temperature $T_1$. If we then move $P$ to a layer higher up in the atmosphere, $P$ will still have
the same temperature, which is wrong because the density differs. Due to this difference, there is either more or less pressure applied to the box of air which means that $P$ will contract or
expand. This obviously changes it's temperature as the air molecules are closer together/further away from each other. Therefore the energy spread is different which affects the temperature.
For a visual representation, please consult \autoref{fig:thermal potential}.

\begin{figure}
    \label{fig:thermal potential}
    \centering
    \includegraphics[width=0.9\textwidth]{figures/potential_temperature.jpg}
    \caption{Visual representation of why we need Thermal Potential \cite{simon}.}
\end{figure}

As seen in \autoref{fig:thermal potential}, the packet of air (next to $T_1$) moves up into a higher layer of the atmosphere and ends up at the top (next to $T_2$). The packet has grown bigger,
as the density in that atmospheric layer is lower and hence the air expands. Because the same energy is in that packet, but it has expanded, the temperature of that packet drops which gives us
$T_2 < T_1$. The light blue graph in the background shows how the density behaves the higher you go, meaning at the far right (when we are at the highest point) the density is quite low and at
the far left (when we are at the planet surface) the density is quite high. The yellow graph shows the temperature of the air at that height, which behaves similarly to the density graph.

Thermal potential or potential temperature, is the temperature that the packet of air would be if it is at the planet surface. So take the packet at $T_2$ in \autoref{fig:thermal potential}. If we move that down to the
surface, then it would be temperature $T$ which is then equal to the thermal potential. The equation corresponding to thermal potential is shown in \autoref{eq:thermal potential}
\cite{thermalPotential}. The symbols in \autoref{eq:thermal potential} mean:

\begin{itemize}
    \item $T$: The temperature of the packet of air (\si{K}).
    \item $p_0$: Reference pressure, usually the pressure at the planet surface (\si{Pa}).
    \item $p$: Pressure of the packet of air (\si{Pa}).
    \item $R$: Gas constant as defined in \autoref{sec:gas constant} (\si{JK^{-1}mol^{-1}}).
    \item $C_a$: Specific heat capacity of air at a constant pressure (\si{Jkg^{-1}K^{-1}}).
\end{itemize}

\begin{subequations}
    \begin{equation}
        \label{eq:thermal potential}
        \theta = T(\frac{p_0}{p})^{\frac{R}{C_a}}
    \end{equation}
    \begin{equation}
        \label{eq:potential temp}
        T = \theta(\frac{p}{p_0})^{\frac{R}{C_a}}
    \end{equation}
\end{subequations}

If we now re-arrange \autoref{eq:thermal potential} so that we have $T$ on one side and the rest on the other side, we get \autoref{eq:potential temp}. With this we can convert temperature into
potential temperature and vice versa. The whole process of moving temperature around is called adiabatic motion. Now it is time to get this into code. For this to work we need to translate both
\autoref{eq:thermal potential} and \autoref{eq:potential temp} into code and create an overarching function that calls the previously mentioned equations. Let us start with
\autoref{eq:thermal potential} which is described in \autoref{alg:temp to pot}. Note that $\frac{R}{C_a}$ does not change as they are constants, therefore we can precompute them which saves
a bit of time (namely $O(n)$ divisions, where $n$ is the length of $p$). Also note that we can inverse the process by inserting a minus in the exponent and swapping $T_a$
and $\theta$, which can easily be done in the call to \autoref{alg:temp to pot}.

\begin{algorithm}
    \caption{Converting temperature into potential temperature}
    \label{alg:temp to pot}
    \SetKwInOut{Input}{Input}
    \SetKwInOut{Output}{Output}
    \Input{temperature of the atmosphere (or potential temperature) $T_a$, air pressure $p$, boolean $back$}
    \Output{potential temperature $\theta$}
    \uIf{$back$}{
        $\kappa \leftarrow \frac{R}{C_a}$ \;
    }\uElse{
        $\kappa \leftarrow -\frac{R}{C_a}$ \;
    }
    \For{$k \leftarrow 0$ \KwTo $p.length$}{
        $\theta[:, :, k] \leftarrow T_a[:, :, k] (\frac{p_z[k]}{p_z[0]})^{\kappa}$
    }
    \Return{$\theta$}
\end{algorithm}

Now we only need to do one more thing, replace the algorithm that calculates $T_{pot}$ as a result of advection. Let us do that in \autoref{alg:advection pot}, where \texttt{ThermalAdv} is the
call to \autoref{alg:divergence}.

\begin{algorithm}
    \caption{The main calculations for calculating the effects of advection}
    \label{alg:advection pot}
    $T_{add} \leftarrow T_{pot} + \nabla(T_{pot}, p_z)$\;
    $T_{add} \leftarrow 0.5T_{add}[adv\_boun:-adv\_boun, :, :] \text{ //Only halve } T_{add} \text{ for indices in the interval } [-nlat + adv\_boun, nlat - adv\_boun]$. \;
    $T_{add}[-adv\_boun:, :, :] \leftarrow 0 \text{//Only replace by 0 in the interval [0, adv\_boun]}$ \;
    $T_{add}[:adv\_boun, :, :] \leftarrow 0 \text{//Only replace by 0 in the interval [nlat - adv\_boun, nlat]}$ \;
    $T_{pot} \leftarrow T_{pot} - T_{add}[adv\_boun:-adv\_boun, :, :] \text{ //Only subtract } T_{add} \text{ from } T_{pot} \text{ for indices in the interval }$
        $[-nlat + adv\_boun, nlat - adv\_boun]$. \;
\end{algorithm}


% This section contains the content for the Terms and Definitions
\numberedformat
\chapter{Terms and Definitions}
The following terms and definitions are used in this document.
%% Modify below this line %%
\label{sec:termsanddefs}

\term{LUT definition}
Look-up tables are an array of size n where each entry has an index associated with it starting from $0$ and ending at $(n-1)$, (e.g. $lut[0], lut[1], \ldots , lut[n-1]$). Each entry contains the output value of the LUT for a particular input value. In a fully enumerated LUT, there is an entry for each possible input code. With a particular input bit depth $b$, the size $n$ equals $2^b$.

\term{Sampled LUT}
In a sampled LUT, there is a smaller set of entries representing sampled positions of the input code range.  By default, the minimum input code value is looked up in $lut[0]$ and the maximum input code value is looked up in $lut[n-1]$.  Other output code values are found directly if the input code is one of the sampled positions, otherwise the output values are interpolated between the two nearest sample entries in the LUT.

\term{Interpolation}
When an input value falls between two sampled positions in a LUT, the output value must be calculated as a proportion of the distance along some function that connects the two nearest values in the LUT. Multiple interpolation types are possible, and higher-order interpolations such as piece-wise cubic interpolation use more than just the adjacent entry to determine the shape of the function. The simplest interpolation type, linear, is a straight line between the points. An example of linear interpolation is provided below.

Ex: with a table of the sampled input values in $inValue[i]$ where $i$ ranges from $0$ to $(n-1)$, and a table of the corresponding output values in $outValue[j]$ where $j$ is equal to $i$,

\begin{center}
\begin{tabularx}{3in}{ccXcc}
	index $i$ & inValue && index $j$ & outValue \\ \hline
	0 & 0 && 0 & 0 \\
	$\vdots$ & $\vdots$ && $\vdots$ & $\vdots$ \\
	$n-1$ & 1 && $n-1$ & 1000 \\
\end{tabularx}
\end{center}

the $output$ resulting from $input$ can be calculated after finding the nearest $inValue[i] < input$.

When $inValue[i] = input$, the result is evaluated directly.

\begin{center}
$output = \dfrac{input-inValue[i]}{inValue[i+1]-inValue[i]} \times (outValue[j+1]-outValue[j])+outValue[j]$
\end{center}

\term{Tetrahedral Interpolation}
This is a type of interpolation for 3D LUTs in which the color space is subdivided by tetrahedra arranged to cover the entire 3D volume.  There are multiple ways to subdivide this space, however for color processing, this specification uses the form where each cube is split along the main (and usually neutral) diagonal into 6 tetrahedra.

\term{\texttt{IndexMap} definition}
The mapping of input code values to indexes of the table is modifiable allowing for remapping the range of applicable input values, changing the spacing of the input sampling function, and reshaping of the index function for lookups into the LUT. An \texttt{IndexMap} in its simplest form allows the definition of the range of input and output floating-point values that are normalized to 0 to 1.0 for accessing a 1DLUT or a 3DLUT. This extension to the LUT format is fully described in Appendix C. The \texttt{IndexMap} is primarily intended for improved implementation of floating-point LUTs and is not necessary for integer LUTs.

\term{1D LUT definition}
A color transform using a 1D LUT has as input a 1-component color value from which it finds the nearest index position whose $inValue$ is less than or equal to the implicit input values for the table. The transform algorithm then calculates the output value by interpolation between $outValue$ entries in the table. A 1DLUT shall be applied equally to all channels in a 3-component color calculation.

\term{3by1D LUT definition}
A 3by1DLUT is a particular case of a 1DLUT in which a 3-component pixel is the input value, and each component is looked up separately in its own 1DLUT which may differ from each other.

\term{3DLUT definition}
In a 3D LUT, the value range of the 3 color components defines the coordinate system of a 3D cube. A single position is found within the volume of the cube from the 3 input values, and a set of the nearest corresponding table entries are identified (between 4 to 8 table entries, depending on the interpolation algorithm). The 3-component output value is calculated by interpolating those nearest table entries from the 3DLUT.

\note{For examples of 3D cube interpolation, look at ``Efficient color transformation implementation'' by Bala and Klassen in Digital Color Imaging Handbook, ed: Sharma, CRC Press, 2003, pg 694-702}

\term{MATRIX definition}
A matrix can be used for linear conversion of 3 color component pixels from one color space to another.

The 3-component input value vector is multiplied by the matrix to create the new 3-component output value vector. Matrix color transforms in this format use the column vector convention:

\begin{equation}
    \begin{bmatrix*}
        a_{11} & a_{12} & a_{13} \\
        a_{21} & a_{22} & a_{23} \\
        a_{31} & a_{32} & a_{33} \\
    \end{bmatrix*} \\
    \begin{bmatrix}
        r\\
        g\\
        b
    \end{bmatrix}
    =
    \begin{bmatrix}
        R\\
        G\\
        B
    \end{bmatrix}
\end{equation}

where $[R, G, B]$ is the result of multiplying input $[r, g, b]$ by the matrix $[a]$.

\term{ASC CDL}
The American Society of Cinematographers' Color Decision List (ASC CDL). This provides a universal method of exchanging basic color correction parameters and specifies a particular color processing equation.


\section{Conclusion}

In this study, we provide a theoretical review of measurement-based quantum computing. We provide the definition and essential properties of graph states essential to measurement-based quantum computing. Using these mathematical objects, we define a cluster and build an abstract machine called a one-way quantum computer on top of it. We show how this machine can be used to perform universal quantum computation. In order to prove this, we define a procedure for simulating any circuit-based quantum algorithm using the one-way computer up to a unitary transformation, composed of Pauli x and z operations, called the by-product operator. Lastly, we provide  Deutsch's algorithm as an example to demonstrate this procedure. Our simulation outcomes using Paddle Quantum show that the procedure indeed works.


\documentclass[13pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage[braket, qm]{qcircuit}
\usepackage{physics}
\usepackage{pgfplots}
\usepgfplotslibrary{units}
\usetikzlibrary{patterns}
\usepackage{siunitx}
\usetikzlibrary{angles, quotes}
\usepackage{amssymb}
\usetikzlibrary{angles, arrows.meta, quotes}
\pgfplotsset{compat=1.17}

\usepackage{minted}
\usepackage[most]{tcolorbox}
\definecolor{lightgreen}{rgb}{0.56, 0.93, 0.56}
\definecolor{moonstoneblue}{rgb}{0.45, 0.66, 0.76}

\newtcblisting{myminted}{%
    listing engine=minted,
    minted language=c,
    listing only,
    breakable,
    enhanced,
    minted options = {
        linenos,
        breaklines=true,
        breakbefore=.,
        fontsize=\footnotesize,
        numbersep=2mm
    },
    overlay={%
        \begin{tcbclipinterior}
            \fill[gray!25] (frame.south west) rectangle ([xshift=4mm]frame.north west);
        \end{tcbclipinterior}
    }
}

\title{Simons's Algorithm Tutorial}
\author{Ishaan Shah}
\date{November 2020}

\begin{document}

\maketitle

\section{The Problem}
\indent Given a function (implemented as a black box) $f: \{0, 1\}^n \rightarrow \{0, 1\}^n$, promised to satisfy the property that, for some non zero binary string $s \in \{0, 1\}^n$
$$f(x) = f(y) \Leftrightarrow x = y\ \text{or}\ x = y \oplus s$$
Find the secret string $s$ in least possible queries. It is important to note that the function $f(x)$ given to us is in the form of a black box which means we cannot extract the bit string by looking at the circuit inside.

For example consider the following truth table for $n = 2$ and $s=10$
\begin{center}
    \begin{tabular}{|c|c|}
        \hline
        x & $f(x)$ \\
        \hline
        00 & 10 \\
        01 & 01 \\
        10 & 10 \\
        11 & 01 \\
        \hline
    \end{tabular}
\end{center}

\section{Algorithm}
\subsection{The classical way}
\indent The classical algorithm is pretty straightforward. We find the output for $0^n$ and store it. Then we find outputs of successive binary strings until we find the output we got for $0^n$. The input for which this is true will be the secret bit string. We can easily see that the time complexity for this is $\mathcal{O}(2^n)$ and space complexity is $\mathcal{O}(1)$.

\subsection{The quantum way}
Before we begin to understand how Simon's algorithm works, we have to look at a smaller sub-algorithm namely the \textbf{Fourier Sampling}.

\subsubsection*{Fourier Sampling}
Fourier sampling is the process of applying $n$ Hadamard Gates to a system of $n$ qubits and measuring the result.

If the input to the circuit is denoted by $\ket{\psi}$ and then the output $\ket{\psi'}$ is given by
$$\ket{\psi'} = \sum_{y \in \{0, 1\}^n}\frac{(-1)^{y\cdot\psi}}{2^{n/2}}\ket{y}$$

Now that we know how Fourier sampling works lets move on to the actual algorithm. The actual algorithm consists of three steps

\subsubsection{Step 1 - Superposition}
In the first step, we create an equal superposition of all the possible bit strings of length $n$. This can easily be done by initialising $n$ qubits to $0$ and  passing them through $n$ Hadamard gates. So now the state of our $n$ qubits will be given by
$$ \ket{\psi} = \sum_{y \in \{0, 1\}^n}\frac{1}{2^{n/2}}\ket{y}$$

\subsubsection{Step 2 - Apply $f(x)$ and measure}
After creating the superposition described below, we pass the vector $\ket{\psi}$ into the black box provided to us. Now we measure the output qubits that we get from the black box which causes the input vector $\ket{\psi}$ to collapse to the following state
$$ \ket{\psi} = \frac{1}{\sqrt{2}}\ket{z} + \frac{1}{\sqrt{2}}\ket{z \oplus s} \qquad \text{...where} \ z \in \{0, 1\}^n$$

\subsubsection{Step 3 - Fourier sampling}
Now we apply the Fourier sampling algorithm to the input which is in the above mentioned state. After applying $n$ Hadamard gates to the $n$ input bits the state of the vector $\ket{\psi}$ becomes
\begin{align*}
    \ket{\psi} &= \sum_{y \in \{0, 1\}^n}\left(\frac{(-1)^{y\cdot z} + (-1)^{y\cdot(z \oplus s)}}{2^{(n+1)/2}}\right)\ket{y} \\
    &= \sum_{y \in \{0, 1\}^n}\left(\frac{(-1)^{y\cdot z}[1 + (-1)^{y\cdot s}]}{2^{(n+1)/2}}\right)\ket{y}s
\end{align*}

When we measure the input register $\ket{\psi}$ after Fourier sampling we will get a vector $\ket{y}$ such that $y\cdot s = 0\ \text{mod}\ 2$. This will happen because the probability all $y\text{s}$ which have an odd dot product will become 0.

Now we have a way to find some vector $\ket{y}$ such that,
$$y_n s_n \oplus y_{n-1} s_{n-1} \oplus \cdots \oplus y_1 s_1 = 0$$
To find the secret bit string $s$ we have to get $n-1$ independent linear equations as above. It can be shown that the probability of finding these $n-1$ equations in $n$ tries is $\frac{1}{4}$. So if we perform the measurements $10n$ times the probability that we don't get independent equations is $0.05$ which is very less. After getting the equations they can be solved to find the secret string $s$ using Gaussian elimination, which takes $\mathcal{O}(n^3)$ time.

\section{Implementation}
\subsection{Implementing the Oracle}
\indent There are many ways in which we can implement the oracle for Simon's Algorithm, here we look at one such implementation. Our basic goal is to create a 2-1 mapping from domain to range of $f(x)$. This can be realised by the following procedure -
\begin{itemize}
    \item Encode the secret string using the $X$ gate wherever there is a 1.
    \item Copy the input register to output register using $CNOT$ gates.
    \item We know that $s \neq 0^n$, so there exists at least one bit in $s$ which has the value 1. Let us call this bit as the \textbf{MSB} bit. We now apply $CCNOT$ gate on output bit which is controlled by the corresponding secret bit and the input \textbf{MSB} bit. This creates a 2-1 mapping.
    \item Now we randomly flip some of the output qubits to further obfuscate the oracle. This step is optional and can be made even more complex so to make it harder to guess the secret string $s$.
\end{itemize}
\vspace{1pt}
\begin{equation*}
    \Qcircuit @C=1.0em @R=0.0em @!R {
	 	\lstick{ {input}_{0} :  } & \qw \barrier[0em]{8} & \qw & \ctrl{3} & \qw & \qw \barrier[0em]{8} & \qw & \ctrl{6} & \ctrl{7} & \ctrl{8} \barrier[0em]{8} & \qw & \qw \barrier[0em]{8} & \qw & \qw & \qw\\
	 	\lstick{ {input}_{1} :  } & \qw & \qw & \qw & \ctrl{3} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {input}_{2} :  } & \qw & \qw & \qw & \qw & \ctrl{3} & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {output}_{0} :  } & \qw & \qw & \targ & \qw & \qw & \qw & \targ & \qw & \qw & \qw & \gate{X} & \qw & \qw & \qw\\
	 	\lstick{ {output}_{1} :  } & \qw & \qw & \qw & \targ & \qw & \qw & \qw & \targ & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {output}_{2} :  } & \qw & \qw & \qw & \qw & \targ & \qw & \qw & \qw & \targ & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{0} :  } & \gate{X} & \qw & \qw & \qw & \qw & \qw & \ctrl{-3} & \qw & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{1} :  } & \gate{X} & \qw & \qw & \qw & \qw & \qw & \qw & \ctrl{-3} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{2} :  } & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \qw & \ctrl{-3} & \qw & \qw & \qw & \qw & \qw\\
	 }
\end{equation*}
\vspace{1pt}
\begin{center}
\footnotesize{Circuit for Simon's oracle for $s=110$}
\end{center}

\subsubsection*{Qiskit implementation}
Following is the code for the Oracle using IBM's Qiskit library. The complete source along with the test function can be found in the Github repository.
\begin{tcolorbox}[
    enhanced,
    attach boxed title to top left={xshift=6mm,yshift=-3mm},
    title=Oracle Code,
    boxed title style={size=small,sharp corners},
    sharp corners,
]
\begin{minted}{python}
import itertools
import random
import time
from typing import List, Tuple

from qiskit import (Aer, ClassicalRegister,
                    QuantumCircuit, QuantumRegister,
                    execute)
from qiskit.circuit import Gate

random.seed(time.monotonic())

def simons_oracle(size: int, secret_input: List[int] = None):
    """ Returns a quantum gate which acts as
        an Oracle for Simon's Algorithm
    """
    # Register holding the secret string
    secret = QuantumRegister(size, "secret")

    # Input and Output registers
    input = QuantumRegister(size, "input")
    output = QuantumRegister(size, "output")

    # Initialize circuit
    oracle = QuantumCircuit(input, output, secret)

    # Generate random secret string
    if not secret_input:
        secret_input = [0 for i in range(size)]
        while secret_input.count(0) == size:
            secret_input = [
                random.choice([0, 1]) for i in range(size)
            ]

    # Encode it in the quantum register
    for i in range(size):
        if secret_input[i]:
            oracle.x(secret[i])

\end{minted}
\end{tcolorbox}
\begin{tcolorbox}[
    enhanced,
    attach boxed title to top left={xshift=6mm,yshift=-3mm},
    title=Oracle Code,
    boxed title style={size=small,sharp corners},
    sharp corners,
]
\begin{minted}{python}
    # Copy input register to output register
    for i in range(size):
        oracle.cx(input[i], output[i])

    # Find msb of secret string
    msb = secret_input.index(1)

    # Create 2-1 mapping
    for i in range(size):
        oracle.ccx(input[msb], secret[i], output[i])

    # Randomly flip qubits for further obfuscation
    for i in range(size):
        if i % 3 == 0:
            oracle.x(output[i])

    return oracle.to_gate(label="oracle"), secret_input
\end{minted}
\end{tcolorbox}
\subsection{Implementing the algorithm}
The implementation of actual Simon's algorithm is pretty straightforward. After we get the set of equations we need, we use Gaussian elimination to solve them and find the secret string.
\vspace{1pt}
\begin{equation*}
    \Qcircuit @C=1.0em @R=0.0em @!R {
	 	\lstick{ {input}_{0} :  } & \gate{H} & \multigate{8}{Oracle} & \gate{H} & \meter & \qw & \qw & \qw & \qw\\
	 	\lstick{ {input}_{1} :  } & \gate{H} & \ghost{Oracle} & \gate{H} & \qw & \meter & \qw & \qw & \qw\\
	 	\lstick{ {input}_{2} :  } & \gate{H} & \ghost{Oracle} & \gate{H} & \qw & \qw & \meter & \qw & \qw\\
	 	\lstick{ {output}_{0} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {output}_{1} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {output}_{2} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{0} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{1} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{ {secret}_{2} :  } & \qw & \ghost{Oracle} & \qw & \qw & \qw & \qw & \qw & \qw\\
	 	\lstick{c0:} & {/_{_{3}}} \cw & \cw & \cw & \dstick{0} \cw \cwx[-9] & \dstick{1} \cw \cwx[-8] & \dstick{2} \cw \cwx[-7] & \cw & \cw\\
	 }
\end{equation*}
\vspace{1pt}
\begin{center}
\footnotesize{Simon's Algorithm circuit for $n=3$}
\end{center}
\subsubsection*{Qiskit implementation}
Following is the code for the the actual algorithm using IBM's Qiskit library. The complete source can be found in the Github repository.
\begin{tcolorbox}[
    enhanced,
    attach boxed title to top left={xshift=6mm,yshift=-3mm},
    title=Simon's Algorithm Code,
    boxed title style={size=small,sharp corners},
    sharp corners,
]
\begin{minted}{python}
import sys

from qiskit import (Aer, ClassicalRegister,
                    QuantumCircuit, QuantumRegister,
                    execute)
from qiskit.visualization import plot_histogram

from simons_oracle import simons_oracle

# Get backend
backend = Aer.get_backend('qasm_simulator')

# Length of input
n = None
try:
    n = int(sys.argv[1])
except IndexError:
    n = 4
except ValueError:
    print("Invalid size")
    sys.exit(1)

# Secret input (optional)
secret_input = None
try:
    secret_input = sys.argv[2]
    secret_input = [int(bit) for bit in secret_input]
    if len(secret_input) != n:
        print("Length of secret string and size "
              "of input should be the same")
        exit(1)
except IndexError:
    pass

# Initialise input, output and secret registers
input = QuantumRegister(n, "input")
output = QuantumRegister(n, "output")
secret = QuantumRegister(n, "secret")
result = ClassicalRegister(n)
\end{minted}
\end{tcolorbox}

\begin{tcolorbox}[
    enhanced,
    attach boxed title to top left={xshift=6mm,yshift=-3mm},
    title=Simon's Algorithm Code,
    boxed title style={size=small,sharp corners},
    sharp corners,
]
\begin{minted}{python}
(oracle, secret_input) = simons_oracle(n, secret_input)
print(f"Secret string - "
      f"{''.join([str(bit) for bit in secret_input])}")

# Initialize circuit
circuit = QuantumCircuit(input, output, secret, result)

# Actual circuit
circuit.h(input)
circuit.append(oracle, [*input, *output, *secret])
circuit.h(input)

# Perform measurement
circuit.measure(input, result)

print(circuit.draw())

# Take the top results and create a matrix out
# of it to solve the equations
res = execute(circuit, backend).result().get_counts()
res = sorted(res, key=lambda k: res[k])[:2**(n-1)]

# Convert to proper integer matrix
mat = [[int(bit) for bit in bit_string] for bit_string in res]
for row in mat:
    row.reverse()

# Perform Gaussian Elimination
x, y = len(mat), n
cur_row, cur_col = 0, 0
while cur_row < x and cur_col < y:
    if mat[cur_row][cur_col] == 0:
        non_zero_row = -1
        for j in range(cur_row+1, x):
            if mat[j][cur_col] == 1:
                non_zero_row = j
                break
        if non_zero_row == -1:
            cur_col += 1
            continue
        else:
            (mat[cur_col], mat[non_zero_row]) =
                (mat[non_zero_row], mat[cur_row])
\end{minted}
\end{tcolorbox}
\begin{tcolorbox}[
    enhanced,
    attach boxed title to top left={xshift=6mm,yshift=-3mm},
    title=Simon's Algorithm Code,
    boxed title style={size=small,sharp corners},
    sharp corners,
]
\begin{minted}{python}
    for j in range(cur_row+1, x):
        if mat[j][cur_col] == 1:
            for k in range(y):
                mat[j][k] = mat[j][k] ^ mat[cur_row][k]

    cur_row += 1

mat = list(filter(lambda row: row.count(0) < y, mat))

# Solve the reduced matrix
sol = [-1 for i in range(n)]
for i in range(n-1):
    if not mat[i][i]:
        sol[i] = 1
        for j in range(i+1, n):
            sol[j] = 0
        break

if sol.count(-1) == n:
    sol[-1] = 1

start = sol.index(1)-1
for i in range(start, -1, -1):
    cnt = 0
    for j in range(n):
        if sol[j] == 1 and mat[i][j] == 1:
            cnt += 1
    sol[i] = cnt % 2

print(f'Calculated Secret String: '
      f'{"".join([str(bit) for bit in sol])}')
\end{minted}
\end{tcolorbox}
\section{Conclusion}
Hence we have devised an algorithm which can solve a problem in polynomial time ($\mathcal{O}(n^3)$) with the help of quantum computers for which the best known solution is exponential time ($\mathcal{O}(2^n)$) using classical computer. This disproves the \textbf{Church-Turing Hypothesis} and shows the potential power of quantum computers.
\end{document}.


\subsection{The reduce operator}
\label{reduce_operator}
Consider the case where we want to perform many different reductions (e.g. min,
max, sum, \ldots) over the same vector. The simple way to do this is
\begin{verbatim}
x = Q.sum(w); y = Q.min(w); z = Q.max(w)
\end{verbatim}
However, this necessitates several scans over the vector \(w\). It is more
efficient to evaluate the vector \(w\) a chunk at a time, perform all the
reductions on the chunk, store the partial results and then repeat over
successive chunks. So, we can re-write the above as
{\tt x, y, z = Q.reduce({ "sum", "min", "max" }, w)}
where {\tt Q.reduce} is described in Figure~\ref{fig_reduce}

\begin{figure}
\centering
\fbox{
\begin{minipage}{14 cm}
\centering
\verbatiminput{reduce.lua}
\caption{The ``reduce'' operator}
\label{fig_reduce}
\end{minipage}
}
\end{figure}
We try to avoid memo-izing vectors when we don't have to because
of the cost of flushing to disk. In our experiments, for \(n > 2^{25}\),
memo-izing the input \(w\) and computing min/max/sum sequentially
is {\ul six} times slower than using the reduce operator.


\hypertarget{values}{%
\section{Values}\label{values}}

Values are the basic unit of information in morpho: All functions in
morpho accept values as arguments and return values.

\hypertarget{int}{%
\section{Int}\label{int}}

Morpho provides integers, which work as you would expect in other
languages, although you rarely need to worry about the distinction
between floats and integers.

Convert a floating point number to an Integer:

\begin{lstlisting}
print Int(1.3) // expect: 1
\end{lstlisting}

Convert a string to an integer:

\begin{lstlisting}
print Int("10")+1 // expect: 11
\end{lstlisting}

\hypertarget{float}{%
\section{Float}\label{float}}

Morpho provides double precision floating point numbers.

Convert a string to an floating point number:

\begin{lstlisting}
print Float("1.2e2")+1 // expect: 121
\end{lstlisting}

\hypertarget{ceil}{%
\section{Ceil}\label{ceil}}

Returns the smallest integer larger than or equal to its argument:

\begin{lstlisting}
print ceil(1.3) // expect: 2
\end{lstlisting}

\hypertarget{floor}{%
\section{Floor}\label{floor}}

Returns the largest integer smaller than or equal to its argument:

\begin{lstlisting}
print floor(1.3) // expect: 1
\end{lstlisting}


\section{Task 1}
Using List-Homomorphism promotions listed below (from \cite[Slide 40]{l1intro})
prove the following invariant:
\begin{verbatim}
(reduce myop e) . (map f)
          ==
(reduce myop e) . (map ( (reduce myop e) . (map f) ) ) . distr_p
\end{verbatim}

\noindent The promotions are as follows:
\begin{enumerate*}
  \item (map $f$) . (map $g$) $\equiv$ map($f$ . $g$)
  \item (map $f$) . (reduce (++) []) $\equiv$ (reduce (++) []) . (map (map $f$))
  \item (reduce $\odot$ $e_\odot$) . (reduce (++) []) $\equiv$ (reduce $\odot$ $e_\odot$) . (map (reduce $\odot$ $e_\odot$))
\end{enumerate*}

\begin{verbatim}
(reduce myop e) . (map f)

(reduce myop e) . (map f)               . (reduce (++) []) . distr_p # From assignment tip

(reduce myop e) . (reduce (++) [])      . (map (map f))    . distr_p # By 2

(reduce myop e) . (map (reduce myop e)) . (map (map f))    . distr_p # By 3

(reduce myop e) . (map ((reduce myop e) . (map f)) )       . distr_p # By 1
\end{verbatim}

\noindent The last line is the form that we wished to create and we have proven
that the invariant holds.