\subsection{Dynamic Time Warping} \label{dynamic_time_warping}

Dynamic Time Warping (DTW) is a widely used and robust distance measure for time series, \textit{allowing similar shapes to match even if they are out of phase in the time axis} \cite{keogh2002exact}. Traditionally DTW computes a full distance matrix to find an optimal warping path, where possible nonlinear alignments between a pair of time series include matches of early time points of the first sequence with late time points of the second sequence. To prevent pathological alignments, the size of the warping window can be constraint, for instance, by the Sakoe-Chiba band \cite{sakoe1978dynamic} or the Itakura parallelogram \cite{itakura1975minimum}. Figure \ref{fig:scb} illustrates the DTW distance measure using a Sakoe-Chiba band of 10\%, where the percentage of the warping window refers to the length of the compared time series.

\begin{figure}
    \begin{center}
        \resizebox {\textwidth} {!} {
            \begin{tabular}{cc}
                \resizebox* {!} {0.3\textwidth} {
                    \begin{tikzpicture}
                        \begin{axis}[
                            xmin=0,
                            xmax=47,
                            xlabel=time,
                            ylabel=acceleration,
                            width=\axisdefaultwidth,
                            height=0.7*\axisdefaultheight,
                            reverse legend,
                            legend pos=south east]
                            \addplot[gray, quiver={u=\thisrow{u}, v=\thisrow{v}}] table {../data/fig/scb/path.dat};
                            \addplot[red, thick, mark=none] table {../data/fig/scb/q.dat};
                            \addlegendentry{Q}
                            \addplot[blue, thick, mark=none] table {../data/fig/scb/c.dat};
                            \addlegendentry{C}
                        \end{axis}
                    \end{tikzpicture}
                } & \quad
                \resizebox* {!} {0.3\textwidth} {
                    \begin{tabular}[b]{ll}
                        \adjustbox{valign=t}{
                        \begin{turn}{90}
                            \begin{tikzpicture}
                                \begin{axis}[
                                    xmin=0,
                                    xmax=47,
                                    ymin=-100,
                                    ymax=0,
                                    hide x axis,
                                    hide y axis,
                                    width=\axisdefaultwidth,
                                    height=0.7*\axisdefaultheight]
                                    \addplot[red, ultra thick, mark=none] table {../data/fig/scb/q.dat};
                                \end{axis}
                            \end{tikzpicture}
                        \end{turn}} \hspace*{1em} &
                        \adjustbox{valign=t}{
                        \begin{tikzpicture} {\LARGE
                            \begin{axis}[
                                enlargelimits=false,
                                ymin=0,
                                ymax=47,
                                colorbar,
                                hide x axis,
                                hide y axis,
                                width=\axisdefaultwidth,
                                height=\axisdefaultwidth,
                                colormap/viridis high res]
                                \addplot[matrix plot*,
                                    shader=flat,
                                    mesh/cols=48,
                                    point meta=explicit] table[meta=C] {../data/fig/scb/matrix.dat};
                                \addplot[white, ultra thick, mark=*, mark size=1] table {../data/fig/scb/matrix_path.dat};
                            \end{axis}}
                        \end{tikzpicture}}\\
                        &
                        \\[1em]
                        &
                        \begin{tikzpicture}
                            \begin{axis}[
                                xmin=0,
                                xmax=47,
                                ymin=-100,
                                ymax=0,
                                hide x axis,
                                hide y axis,
                                width=\axisdefaultwidth,
                                height=0.7*\axisdefaultheight]
                                \addplot[blue, ultra thick, mark=none] table {../data/fig/scb/c.dat};
                            \end{axis}
                        \end{tikzpicture}
                    \end{tabular}
                }
            \end{tabular}
        }
    \end{center}
    \caption{Time series $Q$ and $C$ compared by DTW with a Sakoe-Chiba band of 10\% time series length.
        The left plot illustrates the nonlinear alignment between the two sequences and the right plot shows the optimal warping path within the specified band.}
    \label{fig:scb}
\end{figure}

\input{background_and_notation/dynamic_time_warping/time_series_normalization.tex}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CS630: Database Management Systems
% Copyright 2014 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/beacon
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section*{Question 3}

Write a PL/SQL module that takes as input a \texttt{zipcode} and returns the mean and the variance of order values (i.e. dollar amount) for all orders corresponding to suppliers in that \texttt{zipcode}.
You are not allowed to use any predefined Oracle functions for computing statistics.

\subsection*{Solution}

\lstset{language=SQL}
\lstinputlisting[firstline=8]{
	\topDirectory/src/pls/hw05/hw05q03.pls
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Modelling}

During the modelling phase the models are applied to the dataset constructed in
the data preparation phase, and parameters are adjusted to give the best results
possible. Some models might require that the data is in a specific form, so it
might be necessary to step back to the data preparation phase.

\subsubsection{Tree Type}

While researching R, two distinct type of decision trees came up; an
implementation of regular decision trees that closely follow the method
described in \cite{breiman1984classification}, as well as conditional inference
trees\cite{hothorn2006unbiased}, which I will shorten to \textit{ctree} in this
report.

Both models produce binary trees that can be used to solve classification
problems. Each node in the tree represents a variable and each edge out of the
node contains a ``case'' that tells something about the variable (is it
true/false, $\geq 5$, and so forth). Each leaf of the tree is representing a
class, and there can be several leafs with the same class, they just represent
different characteristics of the same class.

The main difference between a regular decision tree and a ctree is how it is
created. A regular decision tree will choose to split using information measures
such as seen in Quinlan et. al.\cite[p. 89]{quinlan1986induction}, whereas the
ctree framework will split based on the relationship between the target feature
and the covariates based on conditional distribution. Given a fresh dataset, a
regular decision tree will make the first split on the attribute where the
resulting split gives the two largest possible subsets on each edge. A
conditional inferance tree on the other hand will split on the
covariate/attribute with the strongest relation to the target variable.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Model Type Precision}
\label{sec:treetypeprecision}

In order to select which tree type to use I performed an experiment that used
5-fold cross validation\cite[p. 32]{bishop2006pattern} to test the accuracy of
the models for different depths. The dataset used for this experiment was the
combination of the \textit{EngagementData} and \textit{CustomerJourney}
datasets, as described in Section \ref{sec:datasetpruning} (excluding the
customerid column.) The code for this test can be seen in Appendix
\ref{app:treecompare} Figure \ref{app:code:treecompare}.

\begin{table}[H]
    \centering
    \begin{tabular}{l|l|l}
        \textbf{Max Depth} & \textbf{\texttt{rpart} Accuracy} & \textbf{\texttt{ctree} Accuracy} \\ \hline
        \textit{4}         & $94.2799$ \%                     & $94.27990$ \%                    \\
        \textit{8}         & $94.2799$ \%                     & $94.31958$ \%                    \\
        \textit{12}        & $94.2799$ \%                     & $94.36638$ \%
    \end{tabular}
    \caption{The mean accuracy for the different 5-fold cross validation runs.}
    \label{tab:treecompare}
\end{table}

The results shown in Table \ref{tab:treecompare} indicates that for our
particular dataset, the accuracy difference for the two models is very
insignificant. They both predict correctly in around $94,3\%$ of the cases with
a difference of less that $0,1\%$ between the best and worst performer.

An interesting observation from the data above is that the \texttt{rpart} model
have the same accuracy for all three runs indicating that the model created does
not change even when it is allowed to grow more complex. After plotting the
models from each step, I discovered that it did not grow beyond a depth of 2 and
based itself solely on the \texttt{logins14} variable.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Choosing a Model}

Based on the two criteria highlighted in in Section \ref{sec:treetypeprecision},
I selected to go with the \texttt{ctree} package, due to the better accuracy in
the experiment and the fact that the model seem to present more options when you
allow it to grow more complex. This is a desirable feature since the project is
not just about creating a model in the computer, but also to let Simplesite
learn about their customers behaviour.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{Formula and Tree Depth}
\label{sec:formcompare}

In section \ref{sec:datasetpruning} I discarded a number of features in the
dataset and reasoned about why they would not be usable for our purpose. This
leaves 14 features as well as the target variable, \texttt{iscjretained}.
Initial work with the trees showed that the algorithm used for construction of
the ctrees based a lot of splits on the \textit{edits14} and \textit{logins14}
features. This makes sense because they are the only numeric variables in the
dataset, the rest of the variables are booleans that indicate if some event
transpired. This allows the algorithm to make splits based on whether or not the
variable is within some range (\texttt{logins14} $\geq 5$ for example.), these
splits can be performed repeatedly to partition the set into more granular
partitions based on a single variable. On the other hand with a boolean
attribute you cannot partition more than once (is it true/false) since
repartioning the true group based on weither the attribute is true or false
again does not make a difference.

In order to test the impact that these two features have on the accuracy on the
model I performed a number of 5-fold cross validation runs using different
formulas (See the formulas in Table \ref{tab:formulacompare}) for the tree
creation as well as different maximum depths for the ctrees. The code for the
experiment can be seen in Appendix \ref{app:formulacomparison} Figure
\ref{app:code:formulacomparison}. The results of the experiment can be seen in
Table \ref{tab:formulacompare}. The formulas are read as \texttt{target\_varible
\~{} features\_to\_predict\_from}, the topmost formula with a dot instead of the
feature list simply means ``all features''.

\begin{table}[H]
    \centering
    \begin{tabular}{l|l|l}
        \textbf{Formula}                              & \textbf{Max Depth} & \textbf{Mean Accuracy} \\ \hline
        \texttt{iscjretained \~{} .}                  & $4$                & $94.27990$ \%          \\
                                                      & $6$                & $94.29672$ \%          \\ % <-- second highest accuracy
                                                      & $8$                & $94.31958$ \%          \\ \hline % <-- highest accuracy
        \texttt{iscjretained \~{} edits14}            & $4$                & $93.50055$ \%          \\
                                                      & $6$                & $93.50227$ \%          \\
                                                      & $8$                & $93.50119$ \%          \\ \hline
        \texttt{iscjretained \~{} logins14}           & $4$                & $94.27990$ \%          \\
                                                      & $6$                & $94.27990$ \%          \\
                                                      & $8$                & $94.27990$ \%          \\ \hline
        \texttt{iscjretained \~{} edits14 + logins14} & $4$                & $94.27990$ \%          \\
                                                      & $6$                & $94.28465$ \%          \\
                                                      & $8$                & $94.29414$ \%
    \end{tabular}
    \caption{Mean accuracy of different formulas and tree depths using 5-fold cross
        validation.}
    \label{tab:formulacompare}
\end{table}

The results show that while it makes a small positive difference percentage wise
to include all the features, it is less than 1\% which as a percentage is not
too much, but the model is supposed to be applied to all new users once it is
fully implemented, which is more than 400.000 users monthly (Simplesite
confirmed that the september dataset I have been using is representative of the
number of new pages), where 1\% is still 400 potential customers that could've
been helped to stay active but might now be lost, it might also be 400 customers
that indended to pay, but due to extra email might now consider to find a
provider that sends less unsolicited\footnote{The email is not strictly
requested, but the customer have agreed to recieve emails from time to time.}
emails.

Furthermore using all the features also lets Simplesite learn more about what
actions (apart form logins and edits) that the models show to be related to
retaining customers.

From the results in Table \ref{tab:formulacompare} also shows that increasing
the maximum tree depth with $2$ raises the accuracy by approximately $0.02$\%.
plotting out the trees in question shows that it is because the
\textit{logins14} and \textit{edits14} features dominate the first many levels
of the tree, so the remaining boolean features only show on the lower levels.


\chapter{PARTICLE SWARM OPTIMIZATION (PSO)}

\section{Introduction to PSO.}PSO is a robust stochastic optimization technique based on the movement and intelligence of swarms.PSO applies the concept of social interaction to problem solving.It was developed in 1995 by James Kennedy (social-psychologist) and Russell Eberhart (electrical engineer).It is developed from swarm intelligence and is based on the research of bird and fish flock movement behaviour.\\
While searching for food, the birds are either scattered or go together before they locate the place where they can find the food.While the birds are searching for food from one place to another, there is always a bird that can smell the food very well, that is, the bird is perceptible of the place where the food can be found, having the better food resource information.Because they are transmitting the information, especially the good information at any time while searching the food from one place to another, conducted by the good information, the birds will eventually flock to the place where food can be found.\\
As far as particle swam optimization algorithm is concerned, solution swarm is compared to the bird swarm, the birds moving from one place to another is equal to the development of the solution swarm, good information is equal to the most optimist solution, and the food resource is equal to the most optimist solution during the whole course. The most optimist solution can be worked out in particle swarm optimization algorithm by the cooperation of each individual.The particle without quality and volume serves as each individual, and the simple behavioural pattern is regulated for each particle to show the complexity of the whole particle swarm. This algorithm can be used to work out the complex optimist problems.\\
\section{Why PSO?}
1. SIMPLICITY- PSO is a very simple algorithm.Simple in the sense of implementation and calculations performed using it. Compared with the other developing or developed EAs, it occupies the bigger optimization ability and it can be completed easily.\\
2. ROBUST- PSO is robust. As it can be applied to a huge range of diverse problems, PSO can be considered as one of the most robust algorithm.\\
3. ADAPATABILITY- PSO is based on the intelligence and social behaviour of birds. So, it is easily adaptable and understandable by everyone.It can be applied into both scientific research and engineering use.\\
4. PSO have no overlapping and mutation calculation. The search can be carried out by the speed of the particle. During the development of several generations, only the most optimist particle can transmit information onto the other particles, and the speed of the researching is very fast.\\
5. EFFICIENCY- Derivative free with few algorithm parameters, so highly efficient global search algorithm.\\
\section{Basic PSO.}It uses a number of agents (particles) that constitute a swarm moving around in the search space looking for the best solution. Each particle is treated as a point in a N-dimensional space which adjusts its “flying” according to its own flying experience as well as the flying experience of other particles.This means the particles change its condition (position) according to the following principles: (1) change the condition according to its most optimist position (2) change the condition according to the swarm’s most optimist position. The position of each particle in the swarm is affected both by the most optimist position during its movement(individual experience) and the position of the most optimist particle in its surrounding (neighbour experience)\\.Mathematically,Each particle keeps track of its coordinates in the solution space which are associated with the best solution (fitness) that has achieved so far by that particle. This value is called personal best,pbest.\\
Another best value that is tracked by the PSO is the best value obtained so far by any particle in the neighborhood of that particle. This value is called gbest.\\
The basic concept of PSO lies in accelerating each particle toward its pbest and the gbest locations, with a random weighted acceleration at each time step.\\
1. Each particle tries to modify its position using the following information:\\
i) the current positions\\
ii)	the current velocities\\
iii) the distance between the current position and pbest\\
iv) the distance between the current position and the gbest. \\
2. Each particle can be shown by its current speed and position, the most optimist position of each individual and the most optimist position of  the swarm according the following  equation :\\
\textbf{Velocity equation:-}\\
\textbf{$V_i^{k+1}=wV_i^k+c_1 rand_1(..)x (pbest_i-s_i^k+c_2 rand_2(..)x(gbest-s_i^k)$}....(1) \\
where, \\
$V_{i}^{k}$: velocity of  agent i at iteration k\\                                                                                w: weightage\\                                                                                cj : weighting factor\\                                                                                rand : uniformly distributed random number between 0 and 1\\                                                                             $s_{i}^{k}$: current position of agent i at iteration k\\                                                                                $pbest_{i}$: pbest of agent i\\                                                                                gbest: gbest of the group.\\ \\
Thefollowing weighting function is usually utilized in (1)
w = wMax-[(wMax-wMin) x iter]/maxIter ....(2)\\
where,\\
wMax= initial weight\\
wMin = final weight\\
maxIter = maximum iteration number\\
iter = current iteration number\\
Larger w ----------- greater global search ability\\
Smaller w ----------- greater local search ability\\
\textbf{Position equation:- }    \\
$S_{i}^{k+1} = S_{i}^{k} + V_{i}^{k+1}$ .....(3)\\
where,\\
$S_{i}^{k+1}$ is the next position of agent at k+1 iteration.
\section{Basic PSO algorithm.}Initialization:
All required parameters like w, c1, c2, maxIter, etc. for each particle initialize particle’s position, velocity, personal best (pBest) and gBest.\\
% End initialization
Do\\
For each particle\\
Calculate fitness value\\
If the fitness value is better than its personal best\\
set current value as the new pBest\\
End\\
Choose the particle with the best fitness value of all as gBest for each particle\\
Calculate particle velocity according equation (1)\\
Update particle position according equation (3)\\
End\\
While ( maximum iterations or minimum error criteria is not attained.)\\
\section{Flowchart depicting general PSO.}
\includegraphics[width=1.4\textwidth]{./psalgo}\\[1cm]
\section{Advantages and Disadvantages of PSO.}\textbf{ADVANTAGES OF PSO}\\
(1)PSO is based on the intelligence. It can be applied into both scientific research and engineering use.\\
(2)PSO have no overlapping and mutation calculation. The search can be carried out by the speed of the particle.During the development of several generations, only the most optimist particle can transmit information onto the other particles,and the speed of the researching is very fast.\\
(3)The calculation in PSO is very simple. Compared with the other developing calculations, it occupies the bigger optimization ability and it can be completed easily.\\
(4) PSO adopts the real number code, and it is decided directly by the solution.\\
\textbf{DISADVANTAGES OF PSO}\\
(1)The method easily suffers from the partial optimism, which causes the less exact at the regulation of its speed and the direction.\\
(2)The method cannot work out the problems of non-coordinate system, such as the solution to the energy field and the moving rules of the particles in the energy field.\\
\section{Applications of PSO.}Kennedy and Eberhart established the first practical application of Particle Swarm Optimization in 1995. It was in the field of neural network training and was reported together with the algorithm itself. PSO have been successfully used across a wide range of applications, for instance,\\
\textbf{ANTENNAS DESIGN:}The optimal control and design of phased arrays, broadband antenna design and modeling, reflector antennas, optimization of a reflect array antenna, far-field radiation pattern reconstruction, antenna modeling, design of planar antennas, conformal antenna array design, design of patch antennas, design of a periodic antenna arrays, near-field antenna measurements, design of implantable antennas. \\
\textbf{SIGNAL PROCESSING:}Pattern recognition of flatness signal, design of IIR filters, 2D IIR filters, speech coding, analogue filter tuning, particle filter optimization, nonlinear adaptive filters, Costas arrays, wavelets, blind detection, blind source separation, localization of acoustic sources, distributed odour source localization, and so on.\\
\textbf{BIOMEDICAL:}Human tremor analysis for the diagnosis of Parkinson’s disease, inference of gene regulatory networks, human movement biomechanics optimization, RNA secondary structure determination, cancer classification, and survival prediction, DNA motif detection, biomarker selection, protein structure prediction and docking, drug design, radiotherapy planning, analysis of brain magneto encephalography data, electroencephalogram analysis, biometrics and so on.\\
\textbf{ROBOTICS:} Control of robotic manipulators and arms, motion planning and control, odour source localization, soccer playing, robot running, robot vision, collective robotic search, transport robots, unsupervised robotic learning, path planning, obstacle avoidance, swarm robotics, unmanned vehicle navigation, environment mapping, voice control of robots, and so forth.\\
\textbf{PREDICTION AND FORECASTING:} Water quality prediction and classification, prediction of chaotic systems, stream flow forecast, ecological models, meteorological predictions, prediction of the flow stress in steel, time series prediction, electric load forecasting, battery pack state of charge estimation, predictions of elephant migrations, prediction of surface roughness in end milling, urban traffic flow forecasting, and so on.\\


\subsection{3D Cylinders}
\noindent
Although we normally think of cylinders as being extruded circles (circular cylinders), we can create other types of cylinders by extruding curves into 3D space.

\input{./differentialMultivariableCalculus/circularCylinder}
\input{./differentialMultivariableCalculus/parabolicCylinder}


%\section{Code}

\begin{algorithm}
    \caption{Implementation of the hash-based inversion method (Part 1)}
    \label{alg:inv_hash}
    \begin{algorithmic}

        \Input
        \Desc{N}{Size of the hash table}
        \Desc{f\_inv}{inverse function for this table}
        \EndInput
        \Function{\_\_init\_\_}{$self$, N, $f\_inv$}
            \State $self.T \gets [\,]$ \Comment{hash table}
            \State $self.PS \gets$ np.array$([\,])$ \Comment{list of partial sums}
            \State $self.N \gets$ N
            \State $self.f\_inv \gets$
            \For{$i$ in range$(0, self.N)$}
                \State $self.T.$append$(self.f\_inv(\frac{i}{self.N}))$
            \EndFor
            \State $self.T \gets$ np.array$(self.T)$
        \EndFunction
        \State

        \Input
        \Desc{f}{inverse function of $self.f\_inv$}
        \Desc{max}{amount of partial sums}
        \EndInput
        \Function{setup\_partial\_sums\_uniform}{$self$, f, max}
            \State $ps \gets [\,]$
            \State $i \gets 0.0$
            \State $step \gets \frac{\textrm{max}}{self.N}$
            \While{$i < \textrm{max}$}
                \If{$i == 0.0$}
                    \State $ps.\textrm{append}(\textrm{f}(0))$
                \Else
                    \State $ps.\textrm{append}(ps[-1] + \textrm{f}(i))$
                \EndIf
                \State $i \gets i + step$
            \EndWhile
            \State $self.PS \gets \textrm{np.array}(ps)$
        \EndFunction
        \State

        \algstore{bkbreak}
    \end{algorithmic}
\end{algorithm}

\begin{algorithm}
    \caption{Implementation of the hash-based inversion method (Part 2)}
    \begin{algorithmic}
        \algrestore{bkbreak}
        \Input
        \Desc{U}{random variate}
        \EndInput
        \Output
        \Desc{h}{hashed value of $U$}
        \EndOutput
        \Function{hash}{$self$, U}
            \State\Return $\lfloor self.N * \textrm{U} \rfloor$
        \EndFunction
        \State

        \Input
        \Desc{U}{random variate}
        \EndInput
        \Output
        \Desc{X}{from hash table calculated value corresponding to $U$, so that $\mathrm{f^{-1}}(U) = X$}
        \EndOutput
        \Function{search\_single}{$self$, U}
            \State $Z \gets self.hash(\textrm{U})$
            \While{$self.PS[Z] \le \textrm{U}$}
                $Z \gets Z + 1$
            \EndWhile
            \State\Return $self.T[Z]$
        \EndFunction
    \end{algorithmic}
\end{algorithm}


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

\section{Phase estimation algorithm}

Take a unitary transformation \(U\) such that \(U \ket{u}  = \exp(i \varphi) \ket{u} \), where \(0 \leq \varphi \leq 2 \pi \).

\paragraph{Hypotheses}

We can prepare \(\ket{u} \), and \(\exists \text{ a black box } \qty(C-U ^{2^J}) \forall J \geq 0\): that is, a "control - \(U\) applied \(2^J\) times", such that \(\qty(C-U ^{2^J})\ket{0}\ket{u} = \ket{0} \ket{u}  \) and \(\qty(C-U ^{2^J})\ket{1}\ket{u} = \exp(i 2^J \varphi)  \ket{1} \ket{u}  \).

We want to estimate \(\varphi\).

We write it as

\begin{equation}
  \varphi = 2 \pi \qty(\frac{a}{2^n} + \delta) = \overline{\varphi} + \delta \varphi
\end{equation}

with \(0 \leq \delta \leq 2 ^{-n-1} \)
and \(a = a _{n-1} a _{n-2} a _{n-3} \dots a_1 a_0 \).

\paragraph{Method}

We introduce an ancillary registry of \(n\) qubits initialized to \(\ket{0} \), while our main registry is made of \(m\) quibits, in which we encode \(\ket{u} \). Their product is \(\ket{\psi_0} \)

[Scheme]

the result of the first operation is \(\ket{\psi_1} \).
We apply a QFT to the \(n\) control bits, and the result is \(\ket{\psi_2} \).

What is the result of applying \(C-U ^{2^J} = W\)?

\begin{subequations}
\begin{align}
  \qty(C-U ^{2^J}) \qty[\frac{1}{\sqrt{2}} (\ket{0} + \ket{1} ) \otimes \ket{u} ]
  &= \frac{1}{\sqrt{2}} \qty[W \ket{0} \ket{u} + W \ket{1} \ket{u} ]  \\
  &= \frac{1}{\sqrt{2}} \qty[\ket{0} \ket{u} + \exp(i 2^J \varphi)  \ket{1} \ket{u} ]  \\
  &=   \frac{1}{\sqrt{2}} \qty[\ket{0} + \exp(i 2^J \varphi) \ket{1}  ] \otimes \ket{u}
\end{align}
\end{subequations}

Now we can see what is the phase by measuring the ancillary qubits, for example if the phase was just \(-1\) we could apply a Hadamard gate and measure along the \(\pm\) .

So the state \(\ket{\psi_1}\) is

\begin{equation}
  \ket{ \psi_1} = \frac{1}{\sqrt{2^n}} \qty(\bigotimes_{J=0}^{n-1} \qty(\ket{0} + \exp(i \varphi 2^J) \ket{1} ) ) \otimes \ket{u}
\end{equation}

We recall

\begin{equation}
  \text{QFT} ^{-1} = \frac{1}{\sqrt{2^n}} \sum _{x=0}   ^{2^n-1} \exp(\frac{2 \pi ixy}{2^n})
\end{equation}

therefore

\begin{subequations}
\begin{align}
  \ket{\psi_2} = \text{QFT} ^{-1} \ket{\psi_1} &= \frac{1}{2^n} \sum _{x=0}   ^{2^n-1} \sum _{y=0}   ^{2^n-1} \exp(2 \pi i (a-x) \frac{y}{2^n}) \exp(2 \pi i \delta y ) \ket{x} \ket{u}
\end{align}
\end{subequations}

so

\begin{subequations}
\begin{align}
  \P{b} &= \abs{\bra{b}  \frac{1}{2^n} \sum _{x} \sum _{y}  \exp(2 \pi i (a-x) \frac{y}{2^n}) \exp(2 \pi i \delta y ) \ket{x} }^2  \\
  &= \abs{\frac{1}{2^n} \sum _{y}  \exp(\frac{-2 \pi i y (a-b)}{2^n}) \exp(2 \pi i \delta y)   }^2
\end{align}
\end{subequations}

where \(\bra{b} = 011101...\) from the computational basis.

Now, if the potential error \(\delta =0\), the probability of measuring "\(b=a\)" is just 1.

If, instead, \(\delta \neq 0\), we can ask the probability of measuring \(b=a\).

\begin{subequations}
\begin{align}
  \P{a} &= \frac{1}{2^{2n}} \abs{\sum _{y}  \exp(2 \pi i \delta y)}^2  \\
  &= \frac{1}{2^{2n}} \abs{\sum _{y} \qty(\exp(2 \pi i \delta))^y }^2  \\
  &= \frac{1}{2^{2n}} \abs{\frac{1-\alpha^{2n}}{1-\alpha}}^2  \\
  &= \frac{1}{2^{2n}} \abs{\frac{1-\exp(2 \pi i \delta)^{2n}}{1-\exp(2 \pi i \delta)}}^2  \\
  &= \frac{1}{2^{2n}} \abs{ \frac{\sin(\pi 2^n \delta)}{\sin(\pi \delta)}}^2
\end{align}
\end{subequations}

So, since \(\forall z \in [0, 1/2]: 2z \leq \sin(\pi z) \leq \pi z\), then \(\P {a} \geq 4/ \pi^2 \approx 0.4\).

Actually we can achieve \(\P{a} > 1-\varepsilon\) with \(n = l + O(\log(1/\varepsilon))\).

\section{Eigensolver}

We want to solve the Schrödinger equation

\begin{equation}
  i \hbar \pdv{\psi}{t} = H \psi
\end{equation}

with our time evolution operator being \(U(t) = \exp(\frac{-i H t}{\hbar} ) \).

The eigenvalues evolve like

\begin{equation}
  \exp(\frac{-iE_\alpha t}{\hbar}) \ket{E_\alpha}
\end{equation}

This is a phase! we can apply the methods from before.

\paragraph{Spectroscopic method}

This is a classical  method, implemented on a classical computer. There is no measurement involved, this is all done on a computer, our Hamiltonian is just a black box program.

Starting from any state \(\ket{\psi_0} \), the eigenvalue equation is \(H \phi_\alpha = E_\alpha \phi_\alpha\).

We can decompose our state like \(\psi_0(x )= \sum _{\alpha} a_\alpha \phi_\alpha \). Then it evolves like

\begin{equation}
  \psi_0 (t) = \sum _{\alpha}  a_\alpha \exp(\frac{-i E_\alpha t}{\hbar}) \phi_\alpha (x)
\end{equation}

We can do a Fourier transform, defining \(\omega_\alpha \hbar = E_\alpha\):

\begin{subequations}
\begin{align}
  \widetilde{\psi_0}(x_0, \omega) &= \int \exp(i \omega t) \sum  a_\alpha \exp(-i \omega_\alpha t)  \dd{t}  \\
  &= \sum _{\alpha}  a_\alpha \int _{0} ^{T} \exp(i (\omega - \omega_\alpha) t) \phi_\alpha (x) \dd{t}  \\
  &\approx a _{\overline{\alpha} } \phi _{\overline{\alpha} } T + \dots
\end{align}
\end{subequations}

but this is peaked only at \(\omega = \omega _{\overline{\alpha} } \) for large \(T\). We can measure \(a _{\overline{\alpha} } \phi _{\overline{\alpha} } T\) at different \(x\) positions, and find the eigenfunction at any point:

\begin{equation}
  \phi _{\overline{\alpha} }(x_2) = \frac{\widetilde{\psi}(x_2, \omega _{\overline{\alpha} } )}{\widetilde{\psi}(x_1, \omega _{\overline{\alpha} } )} \phi _{\overline{\alpha} }(x_1)
\end{equation}

In some cases doing this is easier than diagonalizing the Hamiltonian.

\paragraph{Quantizing it}

How to quantum-digitalize the problem? We start  with a \(\psi(x)\) with \(x \in [-L, L]\). We can discretize the points: we divide the interval into \(\Delta x = 2L / (2^n -1)\) steps.

Our function will then be \(\psi(i) = \psi(-L + i \Delta x)\), \(i \in \N\).

\begin{equation}
  \ket{\psi} = \sum _{i=0}   ^{2^n-1} \psi(i) \ket{i}
\end{equation}

We can already see that we will have exponentially less memory usage than in the classical case.

We prepare \(\ket{\psi_{0}} = \overline{J} \). We need our infinitesimal evolution operator \(U = \exp(-i H \Delta t / \hbar) \).

Our ancilla qubits are initialized to

\begin{equation}
  \sum _{J}  \frac{\ket{J}}{\sqrt{2^n}} = \ket{+} ^{\otimes n}
\end{equation}

(mapping to times \(0, \Delta t, 2\Delta t, \dots 2^{n-1}\Delta t\) with the algorythm from before).

\begin{subequations}
\begin{align}
  \frac{1}{\sqrt{2^n}} \sum \ket{J} U^J \ket{\psi_0}
  &= \frac{1}{\sqrt{2^n}} \sum  \ket{J} \ket{\psi (J\Delta t)}  \\
  &= \frac{1}{\sqrt{2^n}} \sum  \ket{J} \sum a_\alpha \exp(-i \omega_\alpha J \Delta t) \ket{\phi_\alpha}
\end{align}
\end{subequations}

We apply \( \text{QFT}^{-1}\), measure the ancillary registry, and get \(\phi_\alpha\).

\section{Error mitigation}

Redundancy is the key to error mitigation: if the probability of error is \(\varepsilon \ll 1\), if we have a duplicate the probability they both fail is proportional to \(\varepsilon^2 \ll \varepsilon\).

\paragraph{Classical error correction}

Redundancy + votation.

Alice wants to send a bit of information to Bob. To prevent mistakes, she sends three. If there is a probability \(\varepsilon\) of error, and that error happens, Bob gets two equal bits and a third different bit: so he can assume that the different bit is wrong.

We have several cases, if the sent message is \(0 \rightarrow 000\), shown in figure \ref{fig:error-correction}.

\begin{figure}[H]
  \centering
  \begin{tabular}{c|c|c|c}
    Number & Received message & Probability & Failure \\
    \hline
    1 & 000 & \((1-\varepsilon)^3\) & No \\
    2 & 001, 010, 100 & \(3\varepsilon (1-\varepsilon)^2\) & No \\
    3 & 011, 101, 110  & \(3 \varepsilon ^2 (1-\varepsilon)\) & Yes \\
    4 & 111 & \(\varepsilon^3\) & Yes
  \end{tabular}
  \caption{Error correction probabilities}
  \label{fig:error-correction}
\end{figure}

The probability of failure is then \(O(\varepsilon^2)\).

\paragraph{Trying to quantize it}

\begin{enumerate}
  \item We wish to do \(\ket{\psi} \rightarrow \ket{\psi}\ket{\psi}\ket{\psi}\): this is not allowed; it can be done if we can prepare the state \(\ket{\psi}\) (say, it is one of the base states), but we cannot do so in general.
  \item We want to do a votation: but this means we have to measure it. Maybe we can do a projection?
  \item For classical bits we want to correct \(\ket{0} \leftrightarrow \ket{1}\), but this is not the only possibility for quantum states.
\end{enumerate}

\subsection{3-qubit bit-flip code}

We encode

\begin{subequations}
\begin{align}
  \ket{0} \rightarrow \ket{\widetilde{0}} &= \ket{0}\ket{0}\ket{0} \\
  \ket{1} \rightarrow \ket{\widetilde{1}} &= \ket{1}\ket{1}\ket{1}
\end{align}
\end{subequations}

and in general do

\begin{equation}
  \ket{\psi_1} = \alpha \ket{0} + \beta \ket{1} \rightarrow \alpha \ket{\widetilde{0}} + \beta \ket{\widetilde{1}} = \alpha \ket{0}\ket{0}\ket{0} + \beta \ket{1}\ket{1}\ket{1}
\end{equation}

We did not clone the state! That would have been \(\qty(\alpha \ket{0}+\beta \ket{1})^{\otimes 3}\).

\begin{figure}[H]
  \centering
  \begin{tabular}{c|c|c|c}
    Number & Received message & Probability & Final state \\
    \hline
    1 & \(\alpha \ket{0}\ket{0}\ket{0} + \beta \ket{1}\ket{1}\ket{1}\) & \((1-\varepsilon)^3\) & \(\alpha \ket{0}\ket{0}\ket{0} + \beta \ket{1}\ket{1}\ket{1}\) \\
    2 & perms. of \(\alpha \ket{1}\ket{0}\ket{0} + \beta \ket{0}\ket{1}\ket{1}\) & \(3\varepsilon (1-\varepsilon)^2\) & \(\alpha \ket{0}\ket{0}\ket{0} + \beta \ket{1}\ket{1}\ket{1}\) \\
    3 & perms. of \(\alpha \ket{1}\ket{1}\ket{0} + \beta \ket{0}\ket{0}\ket{1}\)  & \(3 \varepsilon ^2 (1-\varepsilon)\) & \(\alpha \ket{1}\ket{1}\ket{1} + \beta \ket{0}\ket{0}\ket{0}\) \\
    4 & \(\alpha \ket{1}\ket{1}\ket{1} + \beta \ket{0}\ket{0}\ket{0}\) & \(\varepsilon^3\) & \(\alpha \ket{1}\ket{1}\ket{1} + \beta \ket{0}\ket{0}\ket{0}\)
  \end{tabular}
  \caption{Error correction probabilities for the quantum version}
  \label{fig:quantum-error-correction}
\end{figure}

We can do the correction by measuring correlations, without doing a projective measurement: \(x_0 = \expval{\sigma_z^1 \sigma_z^2}\), \(x_1 = \expval{\sigma_z^1 \sigma_z^3}\).

We also get \(x_0 x_1 = 00\) for the case where all the bits are flipped, but it is all right since it is \(O(\varepsilon^3)\).

\subsection{3-qubit phase-flip code}

What if our error is a phase flip  instead of a bit flip? Something like that could be caused by an unknown magnetic field making our state rotate, like \(\ket{0} \rightarrow \ket{0}\), \(\ket{1} \rightarrow -\ket{1}\).
This can be corrected with a Hadamard gate, and then applying the 3 qubit-flip code.

\subsection{9-qubit Shor code}

To account for all kinds of (unitary) errors, we can use

\begin{subequations}
\begin{align}
  \ket{0} &\rightarrow \ket{\widetilde{0}} = \frac{1}{\sqrt{8}} \qty(\ket{000} + \ket{111}) ^{\otimes 3} \\
  \ket{1} &\rightarrow \ket{\widetilde{1}} = \frac{1}{\sqrt{8}} \qty(\ket{000} - \ket{111}) ^{\otimes 3}
\end{align}
\end{subequations}

This of course is very resource-heavy.

Experts think we should be able to achieve fault-free computation with \(\varepsilon \sim 10 ^{-3 \divisionsymbol 4} \).

\paragraph{Example}

We have an error like \(\ket{0} \rightarrow \ket{0}\), \(\ket{1} \rightarrow \exp(i \varphi) \ket{1}\).

We encode 1 of these qubits with two qubits, like \(\ket{01} \equiv \ket{0}\) and \(\ket{10} \equiv \ket{1}\): now these both take a phase of \(\exp(i \varphi) \): we moved to a smaller subspace which is invariant under this transformation.

\end{document}