% !TEX root=/home/tavant/these/manuscript/src/manuscript.tex

\section{Dielectrics boundary condition}
  \label{sec-diel}

  \Cref{fig-2dschemat} shows the simulation of the radial-azimuthal domain with metallic grounded walls.
  \Cref{fig-2D} illustrates the configuration in the radial-azimuthal plane highlighting the more realistic radial boundary conditions.
  The plasma is bounded in the radial direction by dielectric layers isolating the magnetic circuit.
  The magnetic circuit can be considered electrically grounded.

  The particles are absorbed when touching the dielectric wall, and we neglect the diffusion of the charge in the dielectric.
  Hence, we obtain a surface charge $\sigma$ at a time $t$ with
  \begin{equation} \label{eq-sigmaintegrate}
    \sigma(t) = e \int_0^t (J_i - J_e) dt
  \end{equation}
  with $J_i$ and $J_e$ the ion and electron flux respectively, $e$ is the elementary charge, and assuming that there is no surface charge at the interface at the beginning.

  \begin{figure}[hbt]
    \centering
    \includegraphics[width=\defaultwidth]{2D_diel_Rtheta}
    \caption{Schematic representation of the dielectric layers between the plasma in the \acs{2D} radial-azimuthal plane. Are present the dielectric in yellow, the plasma in blue, the surface charges in red, and the grounded magnetic circuit in black.}
    \label{fig-2D}
  \end{figure}

  A common approach is to assume that the electric field inside the dielectric is zero \citep{taccogna2019}.
  Therefore, the dielectric layer does not need to be included in the simulation domain.
  Using Gauss theorem, we obtain a Neumann boundary condition at the plasma-wall interface for the potential
  \begin{equation} \label{eq-gauss}
    \norm{\partial_r \phi} = \frac{\norm{\sigma}}{\epsilon_0}
  \end{equation}
  with $\sigma$ the surface charge and $\epsilon_0$ the vacuum permittivity.
  However, the electric field in a dielectric material is not zero but depends on the global system and the material permittivity.
  Hence, in order to model the dielectric wall of the \ac{HET} correctly, we choose to include the whole dielectric layers inside of the simulation domain.

  In this section, we derive the discretization of the Poisson equation with a non-uniform permittivity in the \ac{2D} radial azimuthal plane using the finite volume approach.

  \subsection{Non-uniform mesh}

    In the dielectric layers, there is no particle nor charge.
    Hence, the numerical constraints on the cell size are not applicable, and the cell size can be increased.
    In order to reduce the cell size difference between two neighboring cells, we use an exponential growth of the cell size in the radial direction.
    The cell size in the azimuthal direction $\dy$ is kept constant.
    The resulting non-uniform mesh can be seen in \cref{fig-2D}.

  \subsection{Poisson equation discretization}

  The dielectric permittivity is $\epsilon= \epsr \epsilon_0$ with $\epsr$ the relative permittivity of the dielectric.
  The Poisson equation with a not-constant permittivity is
  \begin{equation} \label{eq-poissondiel}
    - \grad \cdot \epsilon \grad \phi = \rho
  \end{equation}
  with $\rho$ the charge density.
  We note $\vect{D}=\epsilon \vect{E} = \epsilon \grad \phi$ the electric flux.
  \Cref{fig-decompo1} shows the Cartesian decomposition of the \ac{2D} domain.
  The cell $(i,j)$ has four direct neighbors\string:
  \begin{itemize}
    \item the east $E$ in $(i+1,j)$
    \item the west $W$ in $(i-1, j)$
    \item the north $N$ in $(i, j+1)$
    \item the south $S$ in $(i, j-1)$
  \end{itemize}
  The cell dimensions are $\dx_{i,j}$ and $\dy_{i,j}$, and $\V=\dx_{i,j} \dy_{i,j}$ is the cell volume.
  As the mesh is Cartesian, we have for a given $j$ $\dx_{i,j} = cst$ for all $i$. Hence, we note $\dx_{i,j} = d_i$ and $\dy_{i,j} = d_j$

  The boundaries are noted $S^s_{i,j}$ with $s=E,W,N$ or $S$.
  We can see that $S^W_{i,j}=S^E_{i-1,j}$, and the same goes for the other borders.
  We note $\C = S^E_{i,j} \cup S^W_{i,j} \cup S^N_{i,j} \cup S^S_{i,j}$ the cell surface boundary.
  The center of the cell is located at ($i,j$) and the borders are located at $i\pm 1/2$ in the East-West direction and $j\pm 1/2$ in the North-South direction.
  \begin{figure}[hbt]
    \centering
    \includegraphics[width=\defaultwidth]{discrect1.pdf}
    \caption{Illustration of the Cartesian decomposition of the \acs{2D} domain}
    \label{fig-decompo1}
  \end{figure}

    We start the discretization by positioning the plasma-dielectric interface on the surface between two cells.
    This means that the permittivity $\epsilon = \epsilon_0 \epsr$ is  constant over a cell.
    In order to discretize the Poisson equation, we integrate \cref{eq-poissondiel} over the cell volume

    \begin{equation}
    \int_{\V} - \grad \cdot (\epsilon \grad \phi) dv= \int_{\V} \rho dv.
    \end{equation}
    Using Gauss (also known as Green-Ostrogradsky) theorem, we obtain
    \begin{equation}
    \oint_{\C} ( - \epsilon \grad \phi) \cdot \vect{n} dS = Q_{tot} =  \V \bar{\rho},
    \end{equation}
    with $\vect{n}$ the normal vector directed outward, $Q_{tot}$ is the total charge of the cell and $\bar{\rho}$ is the mean value of $\rho$ in the cell.
    We can decompose the integration over the cell boundary with the four surfaces $S^s_{i,j}$ as
    \begin{equation}
      \label{eq-poissonsum}
    \oint_{\C} (-\epsilon \grad \phi) \cdot \vect{n} dS = \sum_{k\in(E,W,N,S)} S^k_{i,j} \vect{D}^k_{i,j} \cdot \vect{n}
    \end{equation}
    with $\vect{D}^k_{i,j}$ the flux through the surface $k$ of the cell $(i,j)$.

    \paragraph*{Electric flux \\}
    Let us define the electric flux through the East border  $\vect{D}^E_{i,j}$.
    We assume there is no surface charge on $S^E$.
    We can hence write the electric flux as
    \begin{align} \label{eq-flux1}
      \vect{D}^E_{i,j} \cdot \vect{n} &= \epsilon_{i,j} E_{x, i+1/2,j}^-\\
                                      &= - \epsilon_{i,j} \frac{\phi_{i+1/2,j} - \phi_{i,j}}{d_i/2}, \label{eq-flux12}
    \end{align}
    with $E_{x, i+1/2,j}^-$ the electric field at the left of the border (respectively $E_{x, i+1/2,j}^+$ the electric field on the right of the border.
    In \cref{eq-flux12}, we used an off-center discretization of the electric field $E_{x, i+1/2,j}^-$.
    Using Gauss law, we have the jump relation between the electric fields on the left on the right of the border
    \begin{equation} \label{eq-gausslaw}
      \epsilon_{i,j}E_{x, i+1/2,j}^- - \epsilon_{i+1,j}E_{x, i+1/2,j}^+ =0,
    \end{equation}
    we have
    \begin{equation}
      \epsilon_{i,j} \frac{\phi_{i+1/2,j} - \phi_{i,j}}{d_i/2} = \epsilon_{i+1,j} \frac{\phi_{i+1,j} - \phi_{i+1/2,j}}{d_{i+1}/2}.
    \end{equation}
    Hence
    \begin{equation} \label{eq-phidemi1}
      \phi_{i+1/2,j} = \frac{\epsilon_{i,j} d_{i+1} \phi_{i,j} + \epsilon_{i+1,j} d_{i} \phi_{i+1,j} }{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_{i} },
    \end{equation}
    which corresponds to the usual discretization \citep{croes2017} when $\epsilon$ and $d_i$ are both constant.
    Using \cref{eq-phidemi1} in \cref{eq-flux1} we obtain
    \begin{align}
      \label{eq-nosc}
    \vect{D}^E_{i,j} \cdot \vect{n} &=& 2\frac{\epsilon_{i,j}\epsilon_{i+1,j}}{\epsilon_{i,j}d_{i+1} + \epsilon_{i+1,j} d_i} (\phi_{i,j}-\phi_{i+1,j})
    &=& 2\epsilon_0 \frac{\epsr{}_{i,j}\epsr{}_{i+1,j}}{\epsr{}_{i,j}d_{i+1} + \epsr{}_{i+1,j} d_i} (\phi_{i,j}-\phi_{i+1,j})
    \end{align}

    We note $Q^E_{i,j} \equiv 2\frac{\epsilon_{i,j} \epsilon_{i+1,j}}{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_i}$.
    Reproducing the same decomposition on the other borders, we obtain
    \begin{equation}
      \label{eq-descretPoisson1}
    S^E_{i,j} Q^E_{i,j} \phi_{i+1,j} + S^W_{i,j} Q^W_{i,j} \phi_{i-1,j} + S^N_{i,j} Q^N_{i,j} \phi_{i,j+1} + S^S_{i,j} Q^S_{i,j} \phi_{i,j-1} - Q^C_{i,j} \phi_{i,j} = - \V \bar{\rho_{i,j}}
    \end{equation}
    with
    \begin{center}
      $\begin{dcases}
     Q^E_{i,j} &= 2\frac{\epsilon_{i,j} \epsilon_{i+1,j}}{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_i} \\
     Q^W_{i,j} &= Q^E_{i-1,j} \\
     Q^N_{i,j} &= 2\frac{\epsilon_{i,j} \epsilon_{i,j+1}}{\epsilon_{i,j} d_{j+1} + \epsilon_{i,j+1} d_{j}}\\
     Q^S_{i,j} &= Q^N_{i-1,j} \\
     Q^C_{i,j} &= Q^E_{i,j}S^E_{i,j}+Q^W_{i,j}S^W_{i,j}+Q^N_{i,j}S^N_{i,j}+Q^S_{i,j}S^S_{i,j}
     \end{dcases}$
    \end{center}

    as well as $S^E_{i,j} = S^W_{i,j} =d_id_z, S^N_{i,j} = S^S_{i,j}= d_jd_z$ et $\V = d_jd_id_z$.
    We observe that the evolution of the relative permittivity and the cell size affects the coefficients to be used, but the system remains symmetric as we have $Q^S_{i,j} = Q^N_{i-1,j}$ and $ Q^W_{i,j} = Q^E_{i-1,j}$.

    A symmetric system is a linear system of equation $A \cdot X = B$  which matrix $A$ is equal to its transpose\string: $A = A^T$.
    It allows reducing by a factor of two the memory needed to store the matrix.
    It also allows to use algorithms exploiting this property.
    For instance, the eigenvalues are real-valued, and the matrix factorization only need to store one factor using Cholesky decomposition, which gives $A = L L^T$ with $L$ a lower-triangular matrix.

    \subsection{Including surfaces charges}
    Let us now consider the presence of surface charges on the surface $S^E_{i,j}$.
    Gauss's law now reads
    \begin{equation} \label{eq-gausslawsc}
      -\epsilon_{i,j}E_{x, i+1/2,j}^- + \epsilon_{i+1,j}E_{x, i+1/2,j}^+ =\sigma^E,
    \end{equation}
    with $\sigma^E$ the surface charge on the surface.
    The surface charge is not taken into account when computing the total charge in a cell.
    Using the same discretization as before, we obtain
    \begin{equation}
    \epsilon_{i,j} \frac{\phi_{i+1/2,j} - \phi_{i,j}}{d_i/2} - \epsilon_{i+1,j} \frac{\phi_{i+1,j} - \phi_{i+1/2,j}}{d_{i+1}/2} = \sigma^E
    \end{equation}
    so that
    \begin{equation}
      \label{eq-phidemi}
    \phi_{i+1/2,j} = \frac{\epsilon_{i,j} d_{i+1} \phi_{i,j} + \epsilon_{i+1,j} d_{i} \phi_{i+1,j} }{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_{i} } + \frac{1}{2}\sigma^E \frac{d_i d_{i+1}}{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_{i}}
    \end{equation}
    hence
    \begin{align*}
    \vect{D}^E_{i,j} \cdot \vect{n} &= 2\frac{\epsilon_{i,j}\epsilon_{i+1,j}}{\epsilon_{i,j}d_{i+1} + \epsilon_{i+1,j} d_i} (\phi_{i,j}-\phi_{i+1,j}) - \sigma^E \frac{\epsilon_{i,j}d_{i+1}}{\epsilon_{i,j}d_{i+1}+\epsilon_{i+1,j}d_{i}}
    \end{align*}
    We obtain the same relation as \cref{eq-nosc} updated by $- \sigma^E \frac{\epsilon_{i,j}d_{i+1}}{\epsilon_{i,j}d_{i+1}+\epsilon_{i+1,j}d_{i}}$

    Hence, we finally obtain
    \begin{equation}
    S^E_{i,j} Q^E_{i,j} \phi_{i+1,j} + S^W_{i,j} Q^W_{i,j} \phi_{i-1,j} + S^N_{i,j} Q^N_{i,j} \phi_{i,j+1} + S^S_{i,j} Q^S_{i,j} \phi_{i,j-1} - Q^C_{i,j} \phi_{i,j} = - \V \bar{\rho_{i,j}} + Q^W_{\sigma} \sigma^W
    \end{equation}
    with $Q^W_{\sigma} =  S^W_{i,j} \frac{\epsilon_{i,j}d_{i-1}}{\epsilon_{i,j}d_{i-1}+\epsilon_{i-1,j}d_{i}}$.

  \subsection{Verification of the Poisson solver} \label{subsec-poisson_validation}
    We verify the discretization by modeling a \ac{1D} capacitor.
    The length of system is $L=1\,\meter$.
    The relative permittivity of the dielectric inside the capacitor (from $x=0.475$ to $0.525\,\meter$) is set to $\epsr = 8$, and a surface charge of  $\sigma = 8$~nC.cm$^{-2}$ is imposed on one side, and $-8$~nC.cm$^{-2}$ on the other side.
    The expected electric field in the capacitor using the infinite plane approximation is $E = \sigma/(\epsilon_0\epsr) = 1.15$~kV.mm$^{-1}$.

    \Cref{fig-surface} shows the electric field computed using the obtained decomposition
    We see that we obtain the expected jump for the electric field due to the surface charge ($\Delta E = 1.15$~kV/m).
    The difference with the theoretical value is due to the Dirichlet conditions $\phi=0$ used in $x=0$ and $x=1\,\meter$.

    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{validation_dielectric_field.pdf}
      \caption{Electric field of the capacitor configuration calculated by the Poisson solver in order to validate the discretization and the solver developed. }
      \label{fig-surface}
    \end{figure}

  \subsection{Interface at the cell center}
    In the previous section, we supposed that the plasma-dielectric boundary was at the interface between the cells.
    However, this means that the electric field close to the interface is unknown, as it is defined at the cell center.
    Moreover, the Dirichlet condition for the potential is better defined at the cell center, and for the sake of simplicity, changing the boundary conditions should not change the particle domain.
    Hence, we chose to position the plasma-wall interface at the center of the cell as shown in \cref{fig-2D,fig-decompo2}.
    This means that the permittivity is not constant over a cell.

    Because the wall boundaries are only in the radial direction, we consider only an interface in the North-South direction.
    \Cref{fig-decompo2} shows the domain decomposition.
    The decomposition is the same as previously, except for the permittivity that can have two different values\string: one in the North half-plane ${\epsr}_{, i,j}^n$ and another in the South half plane ${\epsr}_{, i,j}^s$.

    \begin{figure}[hbt]
      \centering
      \includegraphics[width=\defaultwidth]{discrect2.pdf}
      \caption{Cartesian decomposition of the \acs{2D} domain. The dash lines represent discontinuities in the permittivity value.}
      \label{fig-decompo2}
    \end{figure}

    The discretization of the Poisson (\Cref{eq-poissonsum}) follows the same path as previously, except that the electric flux in not constant anymore so that \cref{eq-poissonsum} becomes
    \begin{equation}
    \oint_{\C} (-\epsilon \grad \phi) \cdot \vect{n} dS = \sum_{k\in(E,W,N,S)} S^k_{i,j} <\vect{D}^k_{i,j} \cdot \vect{n}>.
    \end{equation}

    We can define
    \begin{align}
    <\vect{D}^E_{i,j} \cdot \vect{n} >&= \frac{1}{2} \epsilon_{i,j}^N E_{x, i+1/2,j}^- + \frac{1}{2} \epsilon_{i,j}^S E_{x, i+1/2,j}^-\\
     &= \frac{-1}{2} (\epsilon_{i,j}^N + \epsilon_{i,j}^S) \frac{\phi_{i+1/2,j} - \phi_{i,j}}{d_i/2}
     \label{eq-flux}
    \end{align}
    so that in the East-West direction, the flux behaves as if the cell permittivity is the average of the North and South half-planes  $$\epsilon_{i,j} = \frac{1}{2} (\epsilon_{i,j}^N + \epsilon_{i,j}^S).$$
    Hence, the rest of the computation is similar.
    For the North and South boundaries, the permittivity is constant, hence there is no modification.
    Consequently, we obtain the discretization
    \begin{equation}
    S^E_{i,j} Q^E_{i,j} \phi_{i+1,j} + S^W_{i,j} Q^W_{i,j} \phi_{i-1,j} + S^N_{i,j} Q^N_{i,j} \phi_{i,j+1} + S^S_{i,j} Q^S_{i,j} \phi_{i,j-1} - Q^C_{i,j} \phi_{i,j} = - \V \bar{\rho_{i,j}}
    \label{eq-descretPoissoncentered}
    \end{equation}
    with
    \begin{center}
     $\begin{dcases}
     Q^E_{i,j} &= 2\frac{\epsilon_{i,j} \epsilon_{i+1,j}}{\epsilon_{i,j} d_{i+1} + \epsilon_{i+1,j} d_i} \\
     Q^W_{i,j} &= Q^E_{i-1,j} \\
     Q^N_{i,j} &= 2\frac{\epsilon_{i,j}^N \epsilon_{i,j+1}^S}{\epsilon_{i,j}^N d_{j+1} + \epsilon_{i,j+1}^S d_{j}}\\
     Q^S_{i,j} &= 2\frac{\epsilon_{i,j}^S \epsilon_{i,j-1}^N}{\epsilon_{i,j}^S d_{j+1} + \epsilon_{i,j-1}^N d_{j}} \\
     Q^C_{i,j} &= Q^E_{i,j}S^E_{i,j}+Q^W_{i,j}S^W_{i,j}+Q^N_{i,j}S^N_{i,j}+Q^S_{i,j}S^S_{i,j}
     \end{dcases}$
    \end{center}

    As well as $S^E_{i,j} = S^W_{i,j} =d_id_z, S^N_{i,j} = S^S_{i,j}= d_jd_z$ et $\V = d_jd_id_z$.
    Here, the system is no more symmetric.
    However, we can assume that the only permittivity jump happens at the cell center, so that  $\epsilon_{i,j}^S = \epsilon_{i,j-1}^N$.
    Hence, $Q^N_{i,j} = 2\frac{\epsilon_{i,j}^N}{ d_{j+1} + d_{j}}$ and the system is symmetric.

  \subsection{Surface charges for centered interface}
    In the case of centered plasma-wall interface, we have surface charges at the center of the cell.
    Hence
    \begin{equation}
    \int_{\Omega_{i,j}} \rho dv = \Omega_{i,j}\bar{\rho} + S_{i,j}^N \sigma_{i,j}.
    \end{equation}
    The surface charges behave like volume charges.
    Hence, we obtain
    \begin{equation}
    S^E_{i,j} Q^E_{i,j} \phi_{i+1,j} + S^W_{i,j} Q^W_{i,j} \phi_{i-1,j} + S^N_{i,j} Q^N_{i,j} \phi_{i,j+1} + S^S_{i,j} Q^S_{i,j} \phi_{i,j-1} - Q^C_{i,j} \phi_{i,j} = - \V \bar{\rho_{i,j}} - S^N_{i,j} \sigma_{i,j}
    \end{equation}

    The discretization obtained for the cell-centered plasma-wall interface  is very similar to the one obtained for the interface at the cell interface.
    However, it conserves the particle domain when the dielectric layer is not modeled, and that Dirichlet conditions are applied, and the electric field at the plasma-wall interface is better defined.
    Hence, the cell-centered interface will be used.

    \vspace{1em}
    This decomposition has been validated with the same test than presented in \cref{subsec-poisson_validation}.
    We observed no difference between the two decompositions in term of precision.

  \subsection{Electric field computation}

    The resolution of the Poisson equation returns the value of the plasma potential $\phi$ at the cell center.
    The electric field is computed by taking the first derivative of the potential at the cell interface, as in \cref{eq-flux1},
    \begin{equation} \label{eq-E_ihalf}
      E_{x, i+1/2,j}^- = - \epsilon_{i,j} \frac{\phi_{i+1/2,j} - \phi_{i,j}}{d_i/2},
    \end{equation}
    with $\phi_{i+1/2,j}$ defined with \cref{eq-phidemi1}.
    However, in order to have consistent data, the electric field is also computed at the cell center by interpolation
    \begin{equation} \label{eq-E_mean}
      E_{x, i, j} = \frac{1}{2} \lp E_{x, i-1/2,j} + E_{x, i+1/2,j} \rp =  - \epsilon_{i,j} \frac{\phi_{i+1/2,j} - \phi_{i-i/2,j}}{d_i}.
    \end{equation}

    In the cells along to the plasma-wall interface, the effect of the surface charge must be taken into account, as previously described.

    % \improvement{Can be more explicit here. Add exact expression of $E$ with $\phi_{i,j}$ and the effect of the surface charge.}
    %


%\documentclass[12pt]{article}
\documentclass[12pt,landscape]{article}

\include{preamble}

\newcommand{\instr}{\small Your answer will consist of a lowercase string (e.g. \texttt{aebgd}) where the order of the letters does not matter. \normalsize}

\title{Math 368 / 621 Fall \the\year{} \\ Midterm Examination Two}
\author{Professor Adam Kapelner}

\date{Wednesday, November 4, \the\year{}}

\begin{document}
\maketitle

%\noindent Full Name \line(1,0){410}

\thispagestyle{empty}

\section*{Code of Academic Integrity}

\footnotesize
Since the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.

Activities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:

\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.
\\

\noindent By taking this exam, you acknowledge and agree to uphold this Code of Academic Integrity. \\

%\begin{center}
%\line(1,0){250} ~~~ \line(1,0){100}\\
%~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date
%\end{center}

\normalsize

\section*{Instructions}

This exam is 75 minutes (variable time per question) and closed-book. You are allowed \textbf{one} page (front and back) of a \qu{cheat sheet}, blank scrap paper and a graphing calculator. Please read the questions carefully. No food is allowed, only drinks. %If the question reads \qu{compute,} this means the solution will be a number otherwise you can leave the answer in \textit{any} widely accepted mathematical notation which could be resolved to an exact or approximate number with the use of a computer. I advise you to skip problems marked \qu{[Extra Credit]} until you have finished the other questions on the exam, then loop back and plug in all the holes. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \fbox{Box} in your final answers. Good luck!

\pagebreak

\problem\timedsection{4} Let $Y_1, ..., Y_n \iid \poisson{\lambda_Y}$ be the discrete rv that models the number of runs the Yankees score in $n$ individual games and $M_1, ..., M_n \iid \poisson{\lambda_M}$ be the discrete rv that models the number of runs the Mets score in $n$ individual games. Let the difference in scores for any game $i$ be $D_i := Y_i - M_i$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{5}

\begin{enumerate}[(a)]
\item Any $D_i$ follows a Skellam distribution without additional assumption(s). \\

If you marked (a) false, for the rest of this problem assume the assumption(s) needed so that $D_i$ is Skellam.

\item $D_i \sim \text{Skellam}(Y, M)$
\item $D_1, ..., D_n$ are $\iid$
\item $D_1 + \ldots + D_n$ follows a Skellam distribution
\item $M_i - M_j$ where $i \neq j$ follows a Skellam distribution.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{7} Let $X \sim U(\braces{1,4,9,16,25,36})$ and $Y = \sqrt{X}$ and $Z$ = mod$(X, 2)$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{8}

\begin{enumerate}[(a)]
\item $X$ is a discrete rv
\item $Y$ is a continuous rv
\item $p_Y(y) = p_X(y^2)$
\item $p^{old}_Y(y) = 1/6$
\item $\exists h$ such that $p_Z(z) = p_X(h(z))$
\item $Z$ is a Bernoulli rv
\item $p^{old}_Z(z) = 1/2$
\item The rv's $Y$ and $Z$ are independent.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{11} Let $X \sim \text{Gamma}(\alpha, \beta) := f_X(x)$ and $Y = 1/X \sim f_Y(y)$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{15}

\begin{enumerate}[(a)]
\item $F_X(x) = \int_\reals \frac{\beta^\alpha}{\Gammaf{\alpha}} x^{\alpha - 1} e^{-\beta x}dx$
\item $F_X(x) = \frac{\beta^\alpha}{\Gammaf{\alpha}}  \int_0^{x} u^{\alpha - 1} e^{-\beta u}du$
\item $F_X(x) =  \frac{\beta^\alpha}{\Gammaf{\alpha}} \gamma\parens{x, \alpha}$
\item $F_X(x) =  P(x,\alpha)$
\item $F_X(x) =  P(\alpha,\beta x)$
\item $F_Y(y) =  1 - F_x(1/y)$
\item $F_Y(y) =  F_x(1/y)$
\item When doing the kernel decompositions $f_X(x) = c_X k_X(x)$ and $f_Y(y) = c_Y k_Y(y)$ we see that $c_X = c_Y$.
\item When doing the kernel decompositions $f_X(x) = c_X k_X(x)$ and $f_Y(y) = c_Y k_Y(y)$ we see that $k_X(x) = k_Y(y)$.
\item $XY$ is distributed as a standard uniform.
\item The support of $Y$ is all real numbers.
\item $f_Y^{old}(y) = \frac{\Gammaf{\alpha}}{\beta^\alpha} (1/y)^{\alpha + 1} e^{-\beta / y}$.
\item $f_Y^{old}(y) = \frac{\Gammaf{\alpha}}{\beta^\alpha} (1/y)^{\alpha - 1} e^{-\beta / y}$.
\item $f_Y^{old}(y) = \frac{\beta^\alpha}{\Gammaf{\alpha}} (1/y)^{\alpha + 1} e^{-\beta / y}$.
\item $f_Y^{old}(y) = \frac{\beta^\alpha}{\Gammaf{\alpha}} (1/y)^{\alpha - 1} e^{-\beta / y}$.

\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{10} Let $X_1, X_2, ... \iid \exponential{\lambda}$ and $N \sim \poisson{\lambda}$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{12}

\begin{enumerate}[(a)]
\item $\int_\reals p_N(t) dt = 1$.
\item $\int_\reals f_{X_1}(t) dt = 1$.
\item $\int_\reals f_{X_1 + X_2 + \ldots + X_k}(t) dt = 1$ for all $k \in \naturals$.
\item $X_1$ is distributed as an Erlang rv.
\item $X_1$ is distributed as a Gamma rv.
\item $X_1 + X_2 + \ldots $ is distributed as an Erlang rv.
\item $X_1, X_2, ...$ and $N$ are related by the Poisson Process without further assumptions.\\

If you marked (g) false, for the rest of this problem assume whatever is necessary so that $X_1, X_2, ...$ and $N$ are related by the Poisson Process.

\item $\prob{X_1 + X_2 + \ldots + X_k < t} = P(k, \lambda t)$
\item $\prob{N < t} = P(k, \lambda t)$ %false
\item $\prob{X_1 + X_2 + \ldots + X_k \geq 1} = \prob{N < k}$.
\item $\prob{X_1 + X_2 + \ldots + X_k \leq 1} = \prob{N \geq k}$.
\item $\prob{X_1 + X_2 + \ldots + X_k \leq 1} + \prob{N < k}$ = 1.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{6} Let $X \sim \text{Logistic}(\mu, \sigma)$ and let $Z = \frac{X - \mu}{\sigma}$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{8}

\begin{enumerate}[(a)]
\item $f_{X,Z}(x,z) = f_X(x) f_Z(z)$
\item $Z$ has support of all the real numbers.
\item $\var{Z} = 1$
\item $\expe{X} = \sigma$
\item $X$ could be an \emph{error distribution}
\item $F_X(1/2) = \mu$
\item The 50\%ile of $Z$ is $\natlog{1}$
\item The 90\%ile of $Z$ is $\natlog{9}$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{4} Let $X_1, X_2, ..., X_n \iid \text{Laplace}(0, 1)$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{5}

\begin{enumerate}[(a)]
\item $f_{X_1, X_2, ..., X_n}(x_1, x_2, \ldots, x_n) = \frac{1}{2^n} e^{-|x_1 + \ldots + x_n|}$
\item $Q[X_1, q] = 1 - Q[X_1, 1 - q]$
\item $X_1$ could be an \emph{error distribution}
\item $X_1 + X_2 + \ldots + X_n$ could be an \emph{error distribution}
\item $X_1 + X_2 + \ldots + X_n$ is Laplace distributed
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{8} Let $X \sim \text{Weibull}(k, \lambda)$ and $Y = \natlog{X}$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{6}

\begin{enumerate}[(a)]
\item $X$ could be a memoryless rv.
\item The kernel of $f_X(x)$ is $k \lambda^k$.
\item if $k = 1.00001$ then $\cprob{X \geq x + c}{X \geq c} < \prob{X \geq x}$ for all $c > 0$.
\item Since $X$ is a waiting time / survival distribution, $Y$ is also a waiting time / survival distribution.
\item $f_Y(y)^{old} = e^{k\lambda (\lambda y)^{k-1} e^{-(\lambda y)^k}}$
\item $f_Y(y)^{old} = k\lambda^k e^{ky} e^{-\lambda^k e^{ky}}$
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{11} Let $X_1, X_2, \ldots, X_{17} \iid U(0, 1)$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{12}

\begin{enumerate}[(a)]
\item $X_1, X_2, \ldots, X_{17}$ are called \qu{order statistics}.
\item The third largest realization is denoted $x_{(3)}$.
\item The third largest realization is denoted $X_{(3)}$.
\item $\support{X_{(k)}} = [0, k)$.
\item The probability that the third largest is less than 0.3 can be computed via the function $\oneover{B(3, 15)}x^2 (1-x)^{14}$ by plugging in $x=0.3$.
\item In the density of the rv modeling the maximum of $X_1, X_2, \ldots, X_{17}$, most of the mass is located near zero.
\item In the density of the rv modeling the maximum of $X_1, X_2, \ldots, X_{17}$, most of the mass is located near 0.5.
\item In the density of the rv modeling $X_{(9)}$, most of the mass is located near zero.
\item In the density of the rv modeling $X_{(9)}$, most of the mass is located near 0.5.
\item If $Y_1 = aX_1, Y_2 = aX_2, \ldots, Y_{17} = aX_{17}$ where $a$ is a positive constant, the density of the minimum of $Y_1, Y_2, \ldots, Y_{17}$ is $\frac{17}{a}\tothepow{\frac{y}{a}}{16}\indic{y \in [0,a]}$.
\item If $a < 1$, $b > 1$, $c > 2$, then $B(a,b,c) < B(b,c)$.
\item If $a = 0$, $b > 1$, $c > 2$, then $I_a(b,c) > B(b,c)$.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{9} Let $X_1, X_2 \iid \exponential{\lambda}$ and $Y_1 = \natlog{X_1 / X_2}$. And let $\bv{g}$ denote a vector valued function from two input $x$'s to two output $y$'s, $\reals^2 \rightarrow \reals^2$ and $\bv{h}$ denote the multivariate inverse function for $\bv{g}$ which is thus also a vector valued function from two input $y$'s to two output $x$'s, $\reals^2 \rightarrow \reals^2$. Let $g_1(x_1, x_2) = \natlog{x_1 / x_2}$ and $g_2(x_1, x_2) = x_2$.

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{8}

\begin{enumerate}[(a)]
\item $h_1(y_1, y_2) = \natlog{y_1 / y_2}$ and $h_2(y_1, y_2) = y_2$ fits the above definition of $\bv{h}$.
\item $f_{Y_1, Y_2}(y_1, y_2) = f_{X_1, X_2}(y_2 e^{y_1}, y_2) y_2e^{y_1}$
\item $f_{Y_1, Y_2}(y_1, y_2) = f_{X}(y_2 e^{y_1})f_X(y_2) y_2e^{y_1}$
\item $f_{Y_1, Y_2}(y_1, y_2) = \lambda^2 y_2 e^{-\lambda y_2(1+e^{y_1})}$
\item There is one nuisance dimension in the jdf of $\Y$ when we wish to find the density of $Y_1$.
\item $f_{Y_1}(y) = \lambda^2 ye^{-\lambda y} \int_\reals e^{-\lambda y e^{u} } du$
\item $f_{Y_1}(y) = \lambda^2 \int_\reals u e^{-\lambda u(1+e^{y})} du$
\item $Y_1$ will be BetaPrime distributed.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\problem\timedsection{5} Let $X\,|\,N=n \sim \binomial{n}{1/2} := \binom{n}{x} \oneover{2^n}$ and let $n$ be a realization from $N \sim$ ExtNegBin($\alpha, p$).

\vspace{-0.2cm}\benum\truefalsesubquestionwithpoints{7}

\begin{enumerate}[(a)]
\item The rv $X\,|\,N$ is discrete.
\item The rv $X$ (unconditional on $N$) is discrete.
\item The rv $X$ is a compound distribution.
\item The rv $X$ (unconditional on $N$) will have two parameters.
\item The rv $X$ (unconditional on $N$) will have three parameters.
\item The old-style PDF or PMF for $X$ (unconditional on $N$) can be expressed $\int_\reals \binom{n}{x} \oneover{2^n}   \frac{\Gammaf{\alpha + n}}{\Gammaf{\alpha} n!} (1-p)^n p^\alpha dn$.
\item The old-style PDF or PMF for $X$ (unconditional on $N$) can be expressed $\sum_{n=0}^\infty \binom{n}{x} \oneover{2^n} \frac{\Gammaf{\alpha + n}}{\Gammaf{\alpha} n!} (1-p)^n p^\alpha$.
\end{enumerate}
\eenum\instr\pagebreak

%%%%%%%%%%%%%%%%%%%%%%%%

\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%


\chapter{   Computer Vision}

% CHAPTER SETTINGS
\graphicspath{{./images/computer_vision/}}

\section{Edge Detection}

\subsection{Describe canny edge detection algorithm?}
Here are the steps, which are needed to implement canny edge detection algorithm:
\begin{enumerate}
    \item Grayscale conversion
    \item Gaussian Blur
    \item Determine the Intensity Gradients
    \item Non Maximum Suppression
    \item Double Thresholding
    \item Edge Tracking by Hysteresis
\end{enumerate}

\subsubsection{Step 1: Convert the image to grayscale}
Convert 3 channels into 1.

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        \includegraphics[width=40mm]{canny_original.jpg}
        \caption{Original}
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        \includegraphics[width=40mm]{canny_grayscale.jpg}
        \caption{Grayscaled}
    \end{minipage}
\end{figure}

\subsubsection{Step 2: Apply Gaussian filter to smooth the image in order to remove the noise}
Since all edge detection results are easily affected by image noise, it is essential to filter out the noise to prevent false detection caused by noise. To smooth the image, a Gaussian filter is applied to convolve with the image.

\begin{figure}[!htb]
    \centering
    \includegraphics[width=40mm]{canny_grayscale.jpg}
    \caption{Gaussian blurred}
\end{figure}

\subsubsection{Step 3: Find the intensity gradients of the image}
An edge in an image may point in a variety of directions, so the Canny algorithm uses four filters to detect horizontal, vertical and diagonal edges in the blurred image. The edge detection operator (such as Roberts, Prewitt, or Sobel) returns a value for the first derivative in the horizontal direction ($G_{x}$) and the vertical direction ($G_{y}$). From this the edge gradient and direction can be determined. Here is an example of the sobel operator:

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{x} = S_{x} * A =
        \left[ \begin{array}{rrr}
        1 & 0 & -1 \\
        2 & 0 & -2 \\
        1 & 0 & -1 \\
        \end{array}\right] $
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{y} = S_{y} * A =
        \left[ \begin{array}{rrr}
        1 & 2 & 1 \\
        0 & 0 & 0 \\
        -1 & -2 & -1 \\
        \end{array}\right] $
    \end{minipage}
\end{figure}

\vspace{5mm}
\noindent Using the two operators you can then calculate the magnitude and the directional gradients of the image as follows:

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $|G| = \sqrt(G^{2}_{x} + G^{2}_{y})$
        \caption{Magnitude}
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $\Theta = arctan(G_{x}/G_{y})$
        \caption{Directinal gradients}
    \end{minipage}
\end{figure}

\vspace{5mm}
\noindent The resulting magnitude looks like:
\begin{figure}[!htb]
    \centering
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=40mm]{canny_sobel_x.jpg}
        \caption{$Sobel_{x}$}
    \end{minipage}%
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=40mm]{canny_sobel_y.jpg}
        \caption{$Sobel_{y}$}
    \end{minipage}
    \begin{minipage}{.33\textwidth}
        \centering
        \includegraphics[width=40mm]{canny_magnitude.jpg}
        \caption{$Magnitude$}
    \end{minipage}
\end{figure}

\subsubsection{Step 4: Apply non-maximum suppression to get rid of spurious response to edge detection}
Non-maximum suppression is an edge thinning technique. After applying gradient calculation, the edge extracted from the gradient value is still quite blurred. Ideally, the final image should have only thin edges. Thus non-maximum suppression can help to suppress all the gradient values (by setting them to 0) except the local maxima, which indicate locations with the sharpest change of intensity value. The algorithm for each pixel in the gradient image is:

\begin{figure}[!htb]
    \centering
    \includegraphics[width=40mm]{canny_nms_example.png}
\end{figure}

\noindent Non maximum suppression works by finding the pixel with the maximum value in an edge. In the above image, it occurs when pixel q has an intensity that is larger than both p and r where pixels p and r are the pixels in the gradient direction of q. If this condition is true, then we keep the pixel, otherwise we set the pixel to zero (make it a black pixel). Non maximum suppression can be achieved by interpolating the pixels for greater accuracy:

\begin{figure}[!htb]
    \centering
    $r = \alpha * b + (1 − \alpha) * a$
\end{figure}

\vspace{5mm}
\noindent Here is a resulting image:
\begin{figure}[!htb]
    \centering
    \includegraphics[width=45mm]{canny_nms.jpg}
    \caption{Non maximum suppression}
\end{figure}

\subsubsection{Step 5: Apply double threshold to determine potential edges}
After application of non-maximum suppression, remaining edge pixels provide a more accurate representation of real edges in an image. However, some edge pixels remain that are caused by noise and color variation. In order to account for these spurious responses, it is essential to filter out edge pixels with a weak gradient value and preserve edge pixels with a high gradient value. This is accomplished by selecting high and low threshold values. If an edge pixel’s gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixel’s gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. The two threshold values are empirically determined and their definition will depend on the content of a given input image.

\begin{figure}[!htb]
    \centering
    \includegraphics[width=40mm]{canny_double_thresholding.jpg}
    \caption{Double thresholding}
\end{figure}

\subsubsection{Step 6: Track edge by hysteresis: Finalize the detection of edges by suppressing all the other edges that are weak and not connected to strong edges}
So far, the strong edge pixels should certainly be involved in the final edge image, as they are extracted from the true edges in the image. However, there will be some debate on the weak edge pixels, as these pixels can either be extracted from the true edge, or the noise/colour variations. To achieve an accurate result, the weak edges caused by the latter reasons should be removed. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. To track the edge connection, blob analysis is applied by looking at a weak edge pixel and its 8-connected neighbourhood pixels. As long as there is one strong edge pixel that is involved in the blob, that weak edge point can be identified as one that should be preserved.

\begin{figure}[!htb]
    \centering
    \includegraphics[width=40mm]{canny_final.jpg}
    \caption{Final Result from Canny Edge Detection Algorithm}
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{What are the drawbacks of the original canny edge detector?}
While traditional Canny edge detection provides relatively simple but precise methodology for edge detection problem, with more demanding requirements on the accuracy and robustness on the detection, the traditional algorithm can no longer handle the challenging edge detection task. The main defects of the traditional algorithm can be summarized as follows:

\begin{itemize}
    \item Use an adaptive filter to apply different smoothing for noise and edge
    \item Select an optimal operator
    \item Use dynamic threshold values
    \item Use a better method for morphological detection
\end{itemize}

\begin{enumerate}
    \item A Gaussian filter is applied to smooth out the noise, but it will also smooth the edge, which is considered as the high frequency feature. This will increase the possibility of missing weak edges, and the appearance of isolated edges in the result.

    As both edge and noise will be identified as high frequency signal, simple Gaussian filter will add smooth effect on both of them. However, in order to reach high accuracy of detection of the real edge, it is expected that more smooth effect should be added to noise and less smooth effect should be added to the edge. \cite{wang09} from Changsha University of Science and Technology developed an adaptive filter, where the filter will evaluate discontinuity between greyscale values of each pixel. The higher the discontinuity, the lower the weight value is set for the smooth filter at that point. Contrarily, the lower the discontinuity between the greyscale values, the higher the weight value is set to the filter.

    \item For the gradient amplitude calculation, the old Canny edge detection algorithm uses the Centre in a small 2×2 neighbourhood window to calculate the finite difference mean value to represent the gradient amplitude. This method is sensitive to noise and can easily detect false edges and lose real edges.

    The gradient magnitude and direction can be calculated with a variety of different edge detection operators, and the choice of operator can influence the quality of results. A very commonly chosen one is the 3x3 Sobel filter. However, other filters may be better by, such as a 5x5 Sobel filter which will reduce noise or the Scharr filter which has better rotational symmetry. Other common choices are Prewitt (used by \cite{zhou11}) and Roberts Cross.

    \item In the traditional Canny edge detection algorithm, there will be two fixed global threshold values to filter out the false edges. However, as the image gets complex, different local areas will need very different threshold values to accurately find the real edges. In addition, the global threshold values are determined manually through experiments in the traditional method, which leads to complexity of calculation when a large number of different images need to be dealt with.

    In order to resolve the challenges where it is hard to determine the dual-threshold value empirically, Otsu's method (\cite{otsu79}) can be used on the non-maximum suppressed gradient magnitude image to generate the high threshold. The low threshold is typically set to 1/2 of the high threshold in this case. Since the gradient magnitude image is continuous-valued without a well-defined maximum, Otsu's method has to be adapted to use value/count pairs instead of a complete histogram.

    \item The result of the traditional detection cannot reach a satisfactory high accuracy of single response for each edge - multi-point responses will appear.

    While the traditional canny edge detection have implemented a good detection result to meet with the first two criteria, it does not meet with the single response per edge strictly. A mathematical morphology to thin the detected edge is developed by \cite{mallat92}.
\end{enumerate}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{What filter operators do you know?}
As a rule if you define your custom operator, the sum of all numbers should yield 0.
\subsubsection{Sobel operator}

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{x} = S_{x} * A =
        \left[ \begin{array}{rrr}
        1 & 0 & -1 \\
        2 & 0 & -2 \\
        1 & 0 & -1 \\
        \end{array}\right] $
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{y} = S_{y} * A =
        \left[ \begin{array}{rrr}
        1 & 2 & 1 \\
        0 & 0 & 0 \\
        -1 & -2 & -1 \\
        \end{array}\right] $
    \end{minipage}
\end{figure}

\subsubsection{Roberts cross}

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $\left[ \begin{array}{rr}
        1 & 0 \\
        0 & -1 \\
        \end{array}\right] $
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $\left[ \begin{array}{rr}
        0 & 1 \\
        -1 & 0 \\
        \end{array}\right] $
    \end{minipage}
\end{figure}

\subsubsection{Prewitt operator}

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{x} = S_{x} * A =
        \left[ \begin{array}{rrr}
        1 & 0 & -1 \\
        1 & 0 & -1 \\
        1 & 0 & -1 \\
        \end{array}\right] $
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{y} = S_{y} * A =
        \left[ \begin{array}{rrr}
        1 & 1 & 1 \\
        0 & 0 & 0 \\
        -1 & -1 & -1 \\
        \end{array}\right] $
    \end{minipage}
\end{figure}

\subsubsection{Laplace operator}

\begin{figure}[!htb]
    \centering
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{xy} = S_{xy} * A =
        \left[ \begin{array}{rrr}
        0 & 1 & 0 \\
        1 & -4 & 1 \\
        0 & 1 & 0 \\
        \end{array}\right] $
    \end{minipage}%
    \begin{minipage}{.5\textwidth}
        \centering
        $G_{y} = S_{y} * A =
        \left[ \begin{array}{rrr}
        1 & 1 & 1 \\
        1 & -8 & 1 \\
        1 & 1 & 1 \\
        \end{array}\right] $
    \end{minipage}
    \caption{In addition to the first operator, this one detects 45°-edges}
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{What is blob connected-component labeling?}
Connected-component labeling is applied in the canny edge algorithm and it is an algorithmic application of graph theory, where subsets of connected components are uniquely labelled based on a given heuristic. In other words, it is used to detect connected regions in binary digital images.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\chapter{Analysis}
		For the previous simulations the parameters of every driver were arbitrary chosen. The only constraint was that all of the parameters must be in the range of real values. However it could important that which parameters matter more and which less.
	\section{Effect of the parameters of drivers}
		So all of the important parameters and their effects on the traffic flow should be examined one by one. The tested parameters are the followings: $a_{\rm max}$, $T$ $h_0$ $t_{\rm change} $, $\Delta a_{\rm th}$.
		\subsection{Changing parameters of case 1}
		Let us start with case 1. First increase the parameters by 25 \%. The effect can be seen in Table \ref{tab:vehicle_density_par_pos_case_1} and Figure \ref{fig:vehicle_density_par_pos_case_1}. The most representative figure of the result is where the number of cars passed the target line - 100 meters - is illustrated as a function of time. The original simulation is denoted by $t_0$. As the result shows $\amax$ has the greatest improvement on time however it is still not significant. The greatest regression comes with $T$, the safe headway time. The effect of the other parameters are almost negligible.
		\begin{figure}[ht]
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_par_pos_case1}
			\caption{Increasing the parameters with 25\% in case 1}
			\label{fig:vehicle_density_par_pos_case_1}
		\end{figure}
		\begin{table}[ht]
			\begin{center}
				\begin{tabular}{ |c|c|c|c|c|c|}
				\hline
				\vehicledensitypartable{1}
				\hline
				\end{tabular}
			\end{center}
			\caption{Increasing the parameters with 25\% in case 1}
			\label{tab:vehicle_density_par_pos_case_1}
		\end{table}

		The same analysis can be run on the different direction. Let us decrease the parameters by 25 \%. The effect can be seen in Table \ref{tab:vehicle_density_par_pos_case_2} and Figure \ref{fig:vehicle_density_par_pos_case_2}. The situation is exactly the opposite. Now $\amax$ has the greatest regression while $T$ has the greatest improvement on time.
		\begin{figure}[ht]
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_par_pos_case2}
			\caption{Decreasing the parameters with 25\% in case 1}
			\label{fig:vehicle_density_par_pos_case_2}
		\end{figure}
		\begin{table}[ht]
			\begin{center}
				\begin{tabular}{ |c|c|c|c|c|c|}
				\hline
				\vehicledensitypartable{2}
				\hline
				\end{tabular}
			\end{center}
			\caption{Decreasing the parameters with 25\% in case 1}
			\label{tab:vehicle_density_par_pos_case_2}
		\end{table}
		\subsection{Changing parameters of case 2}
		Let us examine the other case as well. The expectation is that the parameters effect will be the same as for the previous case. First increase the value of the parameters then decrease by 25 \%. The results can be see on Table \ref{tab:vehicle_density_par_pos_case_3}, \ref{tab:vehicle_density_par_pos_case_4} and Figure \ref{fig:vehicle_density_par_pos_case_3}, \ref{fig:vehicle_density_par_pos_case_4}. The results show that only one parameter, the duration of lane change could improve the traffic flow in this case. This is understandable since there are almost three times more lane changes in case 2 then in case 1. However it is interesting to see that even with the increased $\amax$ value the final duration will be greater. On Figure \ref{fig:vehicle_density_par_pos_case_3} it is clear that for the first half of the simulation the increased $\amax$ improves the traffic flow then a lot of lane changes happened and the increased acceleration parameter turned out to be a drawback. A similar phenomena can be experienced on the congested highway traffic. In rush our it is common that the speed limit is lower then usual to avoid traffic jams.
		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_par_pos_case3}
			\caption{Increasing the parameters with 25\% in case 2}
			\label{fig:vehicle_density_par_pos_case_3}
		\end{figure}
		\begin{table}
			\begin{center}
				\begin{tabular}{ |c|c|c|c|c|c|}
				\hline
				\vehicledensitypartable{3}
				\hline
				\end{tabular}
			\end{center}
			\caption{Increasing the parameters with 25\% in case 2}
			\label{tab:vehicle_density_par_pos_case_3}
		\end{table}
		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_par_pos_case4}
			\caption{Decreasing the parameters with 25\% in case 2}
			\label{fig:vehicle_density_par_pos_case_4}
		\end{figure}
		\begin{table}
			\begin{center}
				\begin{tabular}{ |c|c|c|c|c|c|}
				\hline
				\vehicledensitypartable{4}
				\hline
				\end{tabular}
			\end{center}
			\caption{Decreasing the parameters with 25\% in case 2}
			\label{tab:vehicle_density_par_pos_case_4}
		\end{table}
	\section{Model of a self-driving car}
		Nowadays almost every new car has some level of automated driving assistant feature. The automation level is scaled from 0 to 5 where 0 means the absolute human control and 5 means full autonomy. The low level automation like lane keeping or adaptive cruse control systems are quite common in today's car however nobody reached full autonomy yet. So why could an (half)autonomous car matter in a congested traffic. They may be better at deciding which lane to be in helping the every vehicles faster traveling. Another plus for the self-driving cars that they have a better reaction time than humans, and also they cannot be distracted from driving. These are just a few examples why a self-driving car could improve the capacity of a road network and make traffic better.

		So the task is to find a model for the autonomous driver. The key observation is that a self-driven car can be modeled with the same model as used before. The only difference relies on IDM and MOBIL parameters. So the task is to find proper parameters for the model that can be used for autonomous driver simulation.

		There are three main components representing human behavior built in the model currently. The first one is the attention for driving. An autonomous driver always paying attention to the road. The other component is that a self-driving car can always pay attention to both longitudinal and transversal motions. They are not limited to longitudinal motion attention when they have a higher acceleration or deceleration value. The last but not least component that it can have more favorable IDM and MOBIL parameters than most of the non self-driving cars. E.g. an autonomous driver will always accelerate with the greatest possible value which is comfortable, they would not change lanes if the advantage they would get be marginal however would put others significantly worst position.
	\section{Self-driving car variations in case 1}
		To test the effect of autonomous drivers in traffic, the same red traffic light situation was implemented. However in this case one of the driver's parameters have been substituted with an autonomous driver parameters. The most representative figure of the result of this task is where the number of cars passed the target line - 100 meters - is illustrated as a function of time.
		\subsection{Effect of 1 self-driving car}
		Cars one by one have been exchanged and then simulated with the reaming cars. So a total of ten simulations were run. The result can be seen on Figure \ref{fig:vehicle_density}.
		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density}
			\caption{Number of vehicles passes the target line with one self-driving car}
			\label{fig:vehicle_density}
		\end{figure}

		As Figure \ref{fig:vehicle_density} shows the first car reaches the target line in ~13 seconds. The interesting part is at the top right corner of the figure, where it can be seen that depending on which car has been exchanged the overall elapsed time can change up to 10 \%. The minimum, maximum, average and standard deviation values can be found in Table \ref{tab:vehicle_density_minmaxavg_case1}.
		\begin{table}
			\begin{center}
				\begin{tabular}{ |c|c|c|c|}
					\hline
					\vehicledensitytable{1}
					\hline
				\end{tabular}
			\end{center}
			\caption{Time until the last car has reached the target line. 1 autonomous car}
			\label{tab:vehicle_density_minmaxavg_case1}
		\end{table}

		In the hope of a better figure the same simulation results are shown on Figure \ref{fig:vehicle_density_avg} with averaged representation. It is slightly better than previously.

		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_avg}
			\caption{Number of vehicles passes the target line with one self-driving car}
			\label{fig:vehicle_density_avg}
		\end{figure}

		These simulations were run with only one self-driving car but in different positions. It can be seen that one autonomous driver could make the traffic faster. Based on the position of that one car most of the time it will decrease the overall duration.
		\subsection{Effect of 2 self-driving cars}
		Let us try the same simulation but this time run it exchanging two drivers to autonomous driver and see how the situation will improve. The total number of simulation was 45. All unique combinations were simulated. Figure \ref{fig:vehicle_density_case_2} and Table \ref{tab:vehicle_density_minmaxavg_case2} show the result.
		It can be seen that the minimum duration has decreased further.
		\begin{table}
			\begin{center}
				\begin{tabular}{ |c|c|c|c|}
					\hline
					\vehicledensitytable{2}
					\hline
				\end{tabular}
			\end{center}
			\caption{Time until the last car has reached the target line with two autonomous car}
			\label{tab:vehicle_density_minmaxavg_case2}
		\end{table}
		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_case_2}
			\caption{Number of vehicles passes the target line with two self-driving cars}
			\label{fig:vehicle_density_case_2}
		\end{figure}

		\subsection{Effect of 3 self-driving cars}
		The same simulations were run with three self-driving cars as well. The total number of 120 unique combinations were simulated. Figure \ref{fig:vehicle_density_case_2} and Table \ref{tab:vehicle_density_minmaxavg_case2} show the result.
		\begin{table}
			\begin{center}
				\begin{tabular}{ |c|c|c|c|}
					\hline
					\vehicledensitytable{3}
					\hline
				\end{tabular}
			\end{center}
			\caption{Time until the last car has reached the target line with three autonomous car}
			\label{tab:vehicle_density_minmaxavg_case3}
		\end{table}
		\begin{figure}
			\centering
			\includegraphics[width=0.75\textwidth]{eemobil/vehicle_density_case_3}
			\caption{Number of vehicles passes the target line with three self-driving cars}
			\label{fig:vehicle_density_case_3}
		\end{figure}
		\subsection{Analyzing all of the combinations}
		As seen in the previous examples the more self-driving vehicles are in the traffic the better the traffic flow is. So let us investigate all possible combinations to see what is the connection between the time and the number of self-driving cars. The expectation is that until a certain point the connection is almost linear but after that point self-driving cars cannot make traffic situation better.
		So all the possible combinations were simulated from only one exchanged car until all the ten cars exchanged. Table \ref{tab:all_variations} shows the count of the simulations for each exchanged car numbers.
		\begin{table}[ht]
			\begin{center}
				\begin{tabular}{ |c||c|c|c|c|c|c|c|c|c|c| }
					\hline
					Cars exchanged & 1   & 2    & 3    & 4     & 5      & 6     & 7     & 8   & 9   & 10\\
					\hline
					Variations            & 10 & 45 & 120 & 210 & 252 & 210 & 120 & 45 & 10 & 1\\
					\hline
				\end{tabular}
			\end{center}
			\caption{Number of variations}
			\label{tab:all_variations}
		\end{table}
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations_nosize}
			\caption{Variation of autonomous drivers}
			\label{fig:self_variations_nosize}
		\end{figure}

		The result can be seen on Figure \ref{fig:self_variations_nosize}. The horizontal axis represents how many car has been exchanged. The vertical axis shows the duration of the simulation. The red line represents the original elapsed time without autonomous vehicles. Unfortunately most of the points are in the same place - because of the time step - so the figure could be a little bit misleading. To make it more expressive the plot has been modified to show a larger dot where there are more simulation results and smaller where there are just a few. The result of this modification can be seen on Figure \ref{fig:self_variations}. Figures \ref{fig:self_variations_avgminmax} and \ref{fig:self_variations_std} show the average, minimum, maximum and standard deviation for the simulations.

		As the plot shows the vast majority of dots are below the red line. It means that exchanging human driven cars to autonomous vehicles has an effect on the elapsed time, moreover this effect is positive since the time until the last car has reached the target line decreased. Interesting part of Figure \ref{fig:self_variations} is that at $t=27.5\rm s$ there are clearly visible gaps. After some investigation it turned out that above the gap there are only results when Vehicle 2 and Vehicle 7 stayed human driven and below the gap they are always autonomous vehicles.
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations}
			\caption{Variation of autonomous drivers with highlights}
			\label{fig:self_variations}
		\end{figure}
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations_avgminmax}
			\caption{Average, minimum and maximum of elapsed time.}
			\label{fig:self_variations_avgminmax}
		\end{figure}

		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations_std}
			\caption{Standard deviation of elapsed time}
			\label{fig:self_variations_std}
		\end{figure}
	\section{Self-driving car variations in case 2}
		Let us analyze the other case where the target line was 100 meters also, but there was an obstacle just before the line. The first three simulations can be skipped since unfortunately these result plots had no more meaningful information than the plot containing all of the result. The same three plots were created for this case as well. Figure~\ref{fig:self_variations2} shows the elapsed time as the function of exchanged human drivers. Figures~\ref{fig:self_variations_avgminmax2} and \ref{fig:self_variations_std2} show the average, minimum, maximum and standard deviation for the simulations. In this case the self-driving cars are not performing that well as in case 1. The average of the elapsed times for the first four cases is even greater than in the original case. Probably because there were significantly more lane changes in case 2 then case 1. There are no clear gaps which can identify wrong driving behaviors either.
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations2}
			\caption{Time variation of autonomous drivers}
			\label{fig:self_variations2}
		\end{figure}
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations_avgminmax2}
			\caption{Average, minimum and maximum of elapsed time.}
			\label{fig:self_variations_avgminmax2}
		\end{figure}
		\begin{figure}
			\centering
			\includegraphics[width=0.8\textwidth]{eemobil/variations_std2}
			\caption{Standard deviation of elapsed time}
			\label{fig:self_variations_std2}
		\end{figure}
	\section{Conclusion}
		As a conclusion it can be stated that improvement of driver or vehicle parameter will improve the traffic flow as well. However the biggest improvement can be accomplished by exchanging human driven cars to autonomous vehicles. There are some edge cases however when self-driving cars would not improve the traffic situation either.

		The source code of the fully working \textsc{Matlab} implementation of the simulator is publicly available on the web. The link can be found in the appendices for the repository.

		Every case has an own script which can be run separately. These cases were built on a configuration script which defines the initial conditions, the driver parameters and other simulator parameters. Defining different configuration files one can experiment with the simulator. Several interesting cases can be simulated with this code.

		The implemented simulator's goal is to be as realistic as possible. However it is still neglecting some facts that might be important, e.g.: time delay or different driving strategies.


\subsection{The true density matrix}

\begin{frame}[fragile]
  \frametitle{The \emph{true} density matrix}
  \framesubtitle{Averaging several contributions}

  \footnotesize
  \begin{block}{Density matrix using non-equilibrium Green functions}
    \vskip -2ex
    \begin{align*}
      \only<2->{\color{gray}}
      \DM &
      \only<2->{\color{gray}}
      =\frac1{2\pi}
      \iint_\BZ\dEBZ\cd \kk \dd\E\, \sum_\idxE\Spec_{\idxE,\kk}(\E) n_{F,\idxE}(\E)
      \eikr
      \\
      \only<2->{\color{gray}}
      \DM^\varsigma &
      \only<2->{\color{gray}}
      =
      {\frac i{2\pi}\iint_\BZ\dEBZ\cd \kk\dd\E%
      \left[\G_\kk  - \G^\dagger_\kk \right]\eikr n_{F,\varsigma}(\E)}
      +
      {\frac1{2\pi}\sum_{\idxE'\neq\varsigma}\iint_\BZ\dEBZ\cd \kk\dd\E\, %
      \G_\kk \Scat_{\idxE',\kk}
      \G^\dagger_\kk\eikr\big[n_{F,\idxE'}(\E)-n_{F,\varsigma}(\E)\big]}
      \\
      \DM^\varsigma &=
      {\DE^\varsigma}
      +
      {\sum_{\idxE'\neq\varsigma}\ncor_{\idxE'}^\varsigma}
      \uncover<2->{=
      \only<2->{\color{ok}}
      % Essentially these
      \langle\dots\rangle n_{F,\varsigma}(\E)
      +
      \sum_{\idxE'\neq\varsigma}\langle\dots\rangle [n_{F,\idxE'}(\E)-n_{F,\varsigma}]}
    \end{align*}
  \end{block}

  \pause
  \pause

  \begin{center}
    \def\eta{0.1}%
    \def\radius{3.25}%
    \def\lineS{-1}%
    \def\poles{4}%
    \def\poleSep{.25}%
    % Calculate alpha angle
    \pgfmathparse{\poleSep*(\poles+.5)/\radius}%
    \edef\betaA{\pgfmathresult}%
    \pgfmathparse{atan(\betaA)}%
    \edef\alphaA{\pgfmathresult}%
    \pgfmathparse{asin(\betaA)}%
    \edef\betaA{\pgfmathresult}%
    \begin{tikzpicture}[scale=.75]

      % The axes
      \begin{scope}[draw=gray!80!black,thick,->]
        \draw (-2*\radius+\lineS-.5,0) -- (\radius+1.5,0) node[text=black,below] {$E$};
        \draw (0,0) -- (0,\radius+.5) node[text=black,left] {$\Im$};
      \end{scope}
      \node[below] (mu-1) at (0,0) {$\mu_1$};

      % The specific coordinates on the path
      \coordinate (EB) at (-2*\radius+\lineS,\eta);
      \coordinate (C-mid) at ({-\radius+\lineS-sin(\alphaA)*\radius},{cos(\alphaA)*\radius});
      \coordinate (C-end) at (\lineS,{\poleSep*(\poles+.5)});
      \coordinate (L-end) at (\radius,{\poleSep*(\poles+.5)});
      \coordinate (L-end-end) at (\radius+1,{\poleSep*(\poles+.5)});
      \coordinate (real-L-end) at (\radius,\eta);
      \coordinate (real-L-end-end) at (\radius+1,\eta);

      \begin{scope}[thick]

        % The path (we draw it backwards)
        \draw[->-=.3,very thick] (L-end) -- node[above right]
        {$\mathcal L$} (C-end);
        \draw[->-=.333,->-=.666,very thick] (C-end) to[out=90+\betaA,in=\alphaA] (C-mid)
        node[above]
        {$\mathcal C$}
        to[out=180+\alphaA,in=90] (EB);
        \draw[->-=.25,->-=.75] (EB) -- (real-L-end) node[above left] {$\mathcal R$};

        % draw the continued lines
        \draw[densely dotted] (real-L-end) -- (real-L-end-end);
        \draw[densely dotted] (L-end) -- (L-end-end);

      \end{scope}

      % Draw the poles
      \foreach \pole in {1,...,14} {
          \ifnum\pole>\poles
          \draw (0,\pole*\poleSep) circle (2pt);
          \else
          \fill (0,\pole*\poleSep) circle (2pt);
          \fi
      }
      \node[left,anchor=east] at (0,{\poleSep*(\poles/2+.5)}) {$z_\nu$};

      % correct size
      \path[use as bounding box] (-8,-.5) rectangle ++(13,4.5);

      \draw[densely dotted] (real-L-end-end) to[out=0,in=0] (L-end-end);
      \draw[densely dotted,thick] (EB) -- ++(-.5,0);

      % Draw the 2nd poles
      \def\muB{1}
      \node[below] (mu-2) at (\muB,0) {$\mu_2$};
      \foreach \pole in {1,...,14} {
          \ifnum\pole>\poles
          \draw[bad] (\muB,\pole*\poleSep) circle (2pt);
          \else
          \fill[bad] (\muB,\pole*\poleSep) circle (2pt);
          \fi
      }

      \def\muC{2}
      \node[below] (mu-3) at (\muC,0) {$\mu_3$};
      \foreach \pole in {1,...,14} {
          \ifnum\pole>\poles
          \draw[ok] (\muC,\pole*\poleSep) circle (2pt);
          \else
          \fill[ok] (\muC,\pole*\poleSep) circle (2pt);
          \fi
      }

      \draw[<->]%decorate,decoration=brace]
      ($(mu-2.south)+(0,0)$) --
      node[below left=6pt] {$\ncor^1_2,\color{bad}\ncor^2_1$}
      ($(mu-1.south)+(0,0)$);

      \draw[<->]%decorate,decoration=brace]
      ($(mu-3.south)+(0,-.4)$) --
      node[below=3pt] {$\color{bad}\ncor^2_3\color{black},\color{ok}\ncor^3_2$}
      ($(mu-2.south)+(0,-.4)$);
      \draw[<->]
      ($(mu-3.south)+(0,-1.3)$) --
      node[below=4pt] {$\ncor^1_3,\color{ok}\ncor^3_1$}
      ($(mu-1.south)+(0,-1.3)$);

      \node at ($(mu-3.south east) + (1.5, -0.5)$) {3 electrodes!};

    \end{tikzpicture}
  \end{center}

\end{frame}

\begin{frame}
  \frametitle{The \emph{true} density matrix}
  \framesubtitle{Methods}

  \begin{block}{Example of numeric integration of equilibrium contour}
    \begin{center}
      \begin{tikzpicture}[scale=.8]
        \begin{axis}[width=14cm,height=8cm,name=circ,only marks,
          ymin=0,ymax=15.5,xmin=-31,xmax=1.5,
          xtick={-28,-24,-20,-16,-12,-8,-4},
          extra x ticks={0.25},extra x tick label={$\mu$},
          xlabel={Real Energy [eV]},
          ylabel={Imaginary Energy [eV]}]
          \addplot table {../data/EQ_circle.dat};
          \addplot table {../data/EQ_fermi.dat};
          \addplot table {../data/EQ_pole.dat};
          \draw[densely dashed,green!50!black,very thick] (axis cs:-30,0.1) --
          (axis cs:2,0.1);
          \draw[->,>=latex] (axis cs:-.5,0) -- (axis cs:-8.75,2.2);
          \draw[->,>=latex] (axis cs:-.5,1.25) -- (axis cs:-8.75,10.75);
          \node[rotate=35] at (axis cs:-21.5,11.5) {Gauss-Legendre};
        \end{axis}
        \begin{axis}[width=6cm,height=5cm,only marks,
          at={($(circ.south)+(0,1cm)$)},anchor=south,
          xtick={-0.5,0,0.5},
          extra x ticks={0.25},extra x tick label={$\mu$},
          xmin=-.5,xmax=.75,ymin=0,ymax=1.3]
          \addplot table {../data/EQ_circle.dat};
          \addplot table {../data/EQ_fermi.dat};
          \addplot table {../data/EQ_pole.dat};
          \draw[<->] (axis cs:.3,0.568494) -- node[sloped,anchor=south] {$2\pi k_BT$} (axis cs:.3,0.406067);
          \draw[densely dashed,green!50!black,very thick]
          (axis cs:-1,0.03) -- (axis cs:1,0.03);
          \node[anchor=south] at (axis cs:0.25,1) {Gauss-Fermi};
          \node[rotate=90,anchor=south] at (axis cs:0.25,.5) {Poles};
        \end{axis}
      \end{tikzpicture}
    \end{center}
  \end{block}

  \begin{block}<2->{Example of numeric integration of non-equilibrium contour, $\delta \E
        \approx 0.01\,\mathrm{eV}$}
    \begin{center}
      \begin{tikzpicture}[scale=.8]
        \begin{axis}[width=15cm,height=3cm,
          ymin=0,ymax=1.5,xmin=-1,xmax=1,gen/.style={only marks,opacity=.7},
          xlabel={Energy [eV]},
          ylabel={Weight}]
          \addplot[gen,bad,domain=-.55:.55,samples=30] {1./(exp((x-0.5)/0.01)
              + 1)- 1./(exp((x+0.5)/0.01) + 1)};
          \draw[<->,bad,very thick] (axis cs:-.5, .1) -- (axis cs:.5,.1) node[midway,above]
          {$n_F(\E+0.5\,\mathrm{eV}) - n_F(\E-0.5\,\mathrm{eV})$};
        \end{axis}
      \end{tikzpicture}
    \end{center}
  \end{block}

\end{frame}

\subsection{Weighing the density matrix}

\begin{frame}[fragile]
  \frametitle{Weighing the density matrix}
  \framesubtitle{Choosing the average}

  \footnotesize
  \begin{block}{Density matrix using non-equilibrium Green functions}
    \vskip -2ex
    \begin{columns}
      \column{.1\textwidth}

      \column{.3\textwidth}

      Equivalent, but different!

      \column{.6\textwidth}
      \begin{align*}
        \DM^\idxE &=
        % {\DE^\idxE}
        % +
        % {\sum_{\idxE'\neq\idxE}\ncor_{\idxE'}^\idxE}
        % =
        % Essentially these
        \langle\dots\rangle n_{F,\idxE}(\E)
        +
        \sum_{\idxE'\neq\idxE}\langle\dots\rangle [n_{F,\idxE'}(\E)-n_{F,\idxE}]
        \\
        \DM^\varsigma &=
%        {\DE^\varsigma}
%        +
%        {\sum_{\idxE|\varsigma_\idxE\neq\varsigma}\ncor_{\idxE'}^\varsigma}
%        =
        \langle\dots\rangle n_{F,\varsigma}(\E)
        +
        \sum_{\idxE|\varsigma_\idxE\neq\varsigma} \langle\dots\rangle[n_{F,\varsigma_\idxE}(\E)-n_{F,\varsigma}]
      \end{align*}
    \end{columns}

  \end{block}

  \begin{block}<2->{Estimating $\DM$}

    \begin{itemize}
      \item<+->
      TranSiesta calculates \emph{all} $\DM^\varsigma$ and estimates the true $\DM$ by an
      average:
      \begin{align*}
        \shortintertext{for $2$ electrodes:}
        w_i & = \frac{(\ncor_i)^2}{(\ncor_1)^2+(\ncor_2)^2}
        & &w_1+w_2=1
    \uncover<+->{
        \\
        \shortintertext{for $N$ electrodes:}
        w_\varsigma &=
        \prod_{\varsigma'\neq\varsigma}
        \big(\smash{\sum_{\idxE|\varsigma_\idxE\neq\varsigma'}}(\ncor^{\varsigma'}_\idxE)^2\big)
        \Big/
        \Big\{
        \sum_{\varsigma'}\prod_{\varsigma''\neq\varsigma'}
        \big(\smash{\sum_{\idxE|\varsigma_\idxE\neq\varsigma''}}(\ncor^{\varsigma''}_\idxE)^2\big)
        \Big\}
        & &\sum_iw_i=1
        \\
        \DM &=\sum_\varsigma \DM^\varsigma w_\varsigma
    }
      \end{align*}

      \item<+->%
      Estimation of the ``error''
      \begin{align*}
        \mathrm e_{\mathrm{max}} &= \max\big[
        \DM^{\varsigma'}-\DM^\varsigma;
        \DM^{\varsigma''}-\DM^{\varsigma};
        \DM^{\varsigma''}-\DM^{\varsigma'};
        \dots\big]
        \\
        \mathrm e_{w} &= \max\big[
        \DM^{\varsigma}-\DM;
        \DM^{\varsigma'}-\DM;
        \dots\big].
      \end{align*}

    \end{itemize}

  \end{block}

  \uncover<4->{%
      \begin{tikzpicture}[remember picture,overlay]
        \node[rotate=30,inner sep=20cm,anchor=mid,
        fill=white,opacity=.7,text width=20cm,align=center,
        text opacity=1] at (current page.center)
        {\huge This is why we need \emph{both} a chemical \emph{and} an electrode block};
      \end{tikzpicture}
  }

\end{frame}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "talk"
%%% End:


\documentclass[12pt]{cdblatex}
\usepackage{fancyhdr}
\usepackage{footer}

\begin{document}

% =================================================================================================
% create checkpoint file

\bgroup
\CdbSetup{action=hide}
\begin{cadabra}
   import cdblib
   checkpoint_file = 'tests/semantic/output/geodesic-lsq.json'
   cdblib.create (checkpoint_file)
   checkpoint = []
\end{cadabra}
\egroup

% =================================================================================================
\section*{Geodesic arc-length}

Give a pair of points $P$ and $Q$ the geodesic arc-length can be computed using
\begin{align}
   L_{PQ} = \int_P^Q\>\left(g_{ab}(x)\frac{dx^a}{ds}\frac{dx^b}{ds}\right)^{1/2}\>ds
\end{align}
Since the path is a geodesic the integrand is constant and thus
\begin{align}
   L^2_{PQ} = \left.g_{ab}(x)\frac{dx^a}{ds}\frac{dx^b}{ds}\right\vert_{P}
\end{align}
where $s$ is a re-scaled parameter (0 at $P$ and 1 at $Q$). The point $P$ has
RNC coordinates $x^{a}$ while the point $Q$ has coordinates $x^{a} + Dx^{a}$.

The vector $dx^a/ds$ at $P$ is given by the solution of the geodesic boundary value
problem. This was found in the previous code ({\tts geodesic-bvp}). That is
\begin{align}
   \left.\frac{dx^b}{ds}\right\vert_{P} = y^{a}
\end{align}
and thus
\begin{align}
   \label{eq:lsq}
   L^2_{PQ} = g_{ab}(x) y^{a} y^{b}
\end{align}

It is possible to directly evaluate the right hand side of (\ref{eq:lsq}) using the results from
the {\tts geodesic-bvp} and {\tts metric} codes. The result would need to be truncated (to an
order consistent with the results form those codes). But doing so would be computationaly
expensive as at least half of the terms will be thrown away. A better approach is compute just
the terms that will survive the truncation. This is done by expanding $g_{ab}(x)$ and $y^{a}$ as
a truncated series in the curvatures and its derivatives.

The $g_{ab}(x)$ and $y^{a}$ are written in a (truncated) formal power series in the curvature and
its derivatives
\begin{align}
   y^{a} &= \ny{0}^a + \ny{2}^a + \ny{3}^a + \ny{4}^a + \ny{5}^a + \BigO{\eps^6}\\
   g_{a b}(x) &=   \ngab{0}_{a b}
                 + \ngab{2}_{a b}
                 + \ngab{3}_{a b}
                 + \ngab{4}_{a b}
                 + \ngab{5}_{a b}
                 + \BigO{\eps^6}
\end{align}
Note that this use of $\ny{i}$ differs from that used in {\tts geodesic-bvp}. Here the
index above $y^{a}$ denotes a particular term in the curvature expansion while in
{\tts geodesic-bvp} the index denoted the iteration number (in the fixed point scheme
used to solve the BVP for $y^{a}$).

% \clarepage

% =================================================================================================
\section*{Stage 1}
The formal curvature expansions are substituted into equation (\ref{eq:lsq}), expanded and
truncated to retain terms of order $\BigO{\eps^5}$ or less. The expansion to 4th order terms is
as follows.

\begin{dgroup*}
   \begin{dmath*} L^2_{PQ} = \cdb{lsq4.002} \end{dmath*}
\end{dgroup*}

\input{rnc2rnc.cdbtex}
\input{metric.cdbtex}

From {\tts geodesic-bvp} (actually from {\tts rnc2rnc which reformatted the results nicely}) we have
% \begin{align*}
%      y^{a} = \ny{0}^{a} + \ny{2}^{a} + \ny{3}^{a} + \ny{4}^{a} + \BigO{\eps^5}
% \end{align*}

\begin{dgroup*}
   \begin{dmath*} \ny{0}^{a} = \cdb{term0.102} \end{dmath*}
   \begin{dmath*} \ny{2}^{a} = \cdb{term2.102} \end{dmath*}
   \begin{dmath*} \ny{3}^{a} = \cdb{term3.102} \end{dmath*}
   \begin{dmath*} \ny{4}^{a} = \cdb{term4.102} \end{dmath*}
\end{dgroup*}

and from {\tts metric} we have

% \begin{align*}
%      g_{a b}(x) =
%      \ngab{0}_{a b}
%    + \ngab{2}_{a b}
%    + \ngab{3}_{a b}
%    + \ngab{4}_{a b}
%    + \BigO{\eps^6}
% \end{align*}
\begin{dgroup*}
   \begin{dmath*}     \ngab{0}_{a b} = \cdb{scaled0.601} \end{dmath*}
   \begin{dmath*}   3 \ngab{2}_{a b} = \cdb{scaled2.601} \end{dmath*}
   \begin{dmath*}   6 \ngab{3}_{a b} = \cdb{scaled3.601} \end{dmath*}
   \begin{dmath*} 180 \ngab{4}_{a b} = \cdb{scaled4.601} \end{dmath*}
\end{dgroup*}

% =================================================================================================
\section*{Stage 2}
The results from the {\tts geodesic-bvp} and {\tts metric} codes are read to provide
values for the $\ny{n}^{a}$ and $\ngab{m}_{ab}$. These are substituted into the result from
Stage 1, et volia, the final answer. To 4th-order terms the result is given by

\Dmath*{ L^2_{PQ} = \cdb{lsq5.301} + \BigO{\eps^5}}

\clearpage

% =================================================================================================
\section*{Shared properties}

\begin{cadabra}
   {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w#}::Indices(position=independent).

   D{#}::Derivative.
   \nabla{#}::Derivative.
   \partial{#}::PartialDerivative.

   g_{a b}::Metric.
   g^{a b}::InverseMetric.
   g_{a}^{b}::KroneckerDelta.
   g^{a}_{b}::KroneckerDelta.
   \delta^{a}_{b}::KroneckerDelta.
   \delta_{a}^{b}::KroneckerDelta.

   R_{a b c d}::RiemannTensor.
   R^{a}_{b c d}::RiemannTensor.
   R_{a b c}^{d}::RiemannTensor.

   \Gamma^{a}_{b c}::TableauSymmetry(shape={2}, indices={1,2}).
   \Gamma^{a}_{b c d}::TableauSymmetry(shape={3}, indices={1,2,3}).
   \Gamma^{a}_{b c d e}::TableauSymmetry(shape={4}, indices={1,2,3,4}).
   \Gamma^{a}_{b c d e f}::TableauSymmetry(shape={5}, indices={1,2,3,4,5}).

   x^{a}::Depends(D{#}).

   g_{a b}::Depends(\partial{#}).
   R_{a b c d}::Depends(\partial{#}).
   R^{a}_{b c d}::Depends(\partial{#}).
   \Gamma^{a}_{b c}::Depends(\partial{#}).

   R_{a b c d}::Depends(\nabla{#}).
   R^{a}_{b c d}::Depends(\nabla{#}).

   g0{#}::LaTeXForm ("\ngab{0}").
   g2{#}::LaTeXForm ("\ngab{2}").
   g3{#}::LaTeXForm ("\ngab{3}").
   g4{#}::LaTeXForm ("\ngab{4}").
   g5{#}::LaTeXForm ("\ngab{5}").

   y0{#}::LaTeXForm ("\ny{0}").
   y2{#}::LaTeXForm ("\ny{2}").
   y3{#}::LaTeXForm ("\ny{3}").
   y4{#}::LaTeXForm ("\ny{4}").
   y5{#}::LaTeXForm ("\ny{5}").

\end{cadabra}

\clearpage

% =================================================================================================
\section*{Stage 1: The formal expansion}

\begin{cadabra}
   g0_{a b}::Symmetric.
   g2_{a b}::Symmetric.
   g3_{a b}::Symmetric.
   g4_{a b}::Symmetric.
   g5_{a b}::Symmetric.

   g0_{a b}::Weight(label=num,value=0).
   g2_{a b}::Weight(label=num,value=2).
   g3_{a b}::Weight(label=num,value=3).
   g4_{a b}::Weight(label=num,value=4).
   g5_{a b}::Weight(label=num,value=5).

   y0^{a}::Weight(label=num,value=0).
   y2^{a}::Weight(label=num,value=2).
   y3^{a}::Weight(label=num,value=3).
   y4^{a}::Weight(label=num,value=4).
   y5^{a}::Weight(label=num,value=5).

   # note: keeping numbering as is (out of order) to ensure R appears before \nabla R etc.
   def product_sort (obj):
       substitute (obj,$ A^{a}                            -> A001^{a}               $)
       substitute (obj,$ x^{a}                            -> A002^{a}               $)
       substitute (obj,$ Dx^{a}                           -> A003^{a}               $)
       substitute (obj,$ g_{a b}                          -> A004_{a b}             $)
       substitute (obj,$ g^{a b}                          -> A005^{a b}             $)
       substitute (obj,$ \nabla_{e f g h}{R_{a b c d}}    -> A010_{a b c d e f g h} $)
       substitute (obj,$ \nabla_{e f g}{R_{a b c d}}      -> A009_{a b c d e f g}   $)
       substitute (obj,$ \nabla_{e f}{R_{a b c d}}        -> A008_{a b c d e f}     $)
       substitute (obj,$ \nabla_{e}{R_{a b c d}}          -> A007_{a b c d e}       $)
       substitute (obj,$ R_{a b c d}                      -> A006_{a b c d}         $)
       sort_product   (obj)
       rename_dummies (obj)
       substitute (obj,$ A001^{a}                  -> A^{a}                         $)
       substitute (obj,$ A002^{a}                  -> x^{a}                         $)
       substitute (obj,$ A003^{a}                  -> Dx^{a}                        $)
       substitute (obj,$ A004_{a b}                -> g_{a b}                       $)
       substitute (obj,$ A005^{a b}                -> g^{a b}                       $)
       substitute (obj,$ A006_{a b c d}            -> R_{a b c d}                   $)
       substitute (obj,$ A007_{a b c d e}          -> \nabla_{e}{R_{a b c d}}       $)
       substitute (obj,$ A008_{a b c d e f}        -> \nabla_{e f}{R_{a b c d}}     $)
       substitute (obj,$ A009_{a b c d e f g}      -> \nabla_{e f g}{R_{a b c d}}   $)
       substitute (obj,$ A010_{a b c d e f g h}    -> \nabla_{e f g h}{R_{a b c d}} $)

       return obj

   def truncate (obj,n):
       ans = Ex(0)

       for i in range (0,n+1):
          foo := @(obj).
          bah = Ex("num = " + str(i))
          keep_weight (foo, bah)
          ans = ans + foo

       return ans

   # expansions wrt the curvature

   defgab := g_{a b} -> g0_{a b} + g2_{a b} + g3_{a b} + g4_{a b} + g5_{a b}.
   defy   := y^{a}   -> y0^{a} + y2^{a} + y3^{a} + y4^{a} + y5^{a}.

   lsq    := g_{a b} y^{a} y^{b}.

   substitute (lsq,defgab)
   substitute (lsq,defy)
   distribute (lsq)

   def tidy (obj):
       foo := @(obj).
       sort_product    (foo)
       rename_dummies  (foo)
       canonicalise    (foo)
       return foo

   lsq0 = tidy ( truncate (lsq,0) )  # cdb (lsq0.002,lsq0)
   lsq2 = tidy ( truncate (lsq,2) )  # cdb (lsq2.002,lsq2)
   lsq3 = tidy ( truncate (lsq,3) )  # cdb (lsq3.002,lsq3)
   lsq4 = tidy ( truncate (lsq,4) )  # cdb (lsq4.002,lsq4)
   lsq5 = tidy ( truncate (lsq,5) )  # cdb (lsq5.002,lsq5)

   d20 := @(lsq2) - @(lsq0).         # cdb (d20.001,d20)   # check, should contain only O(2) terms
   d32 := @(lsq3) - @(lsq2).         # cdb (d32.001,d32)   # check, should contain only O(3) terms
   d43 := @(lsq4) - @(lsq3).         # cdb (d43.001,d43)   # check, should contain only O(4) terms
   d54 := @(lsq5) - @(lsq4).         # cdb (d54.001,d54)   # check, should contain only O(5) terms

   d5 := @(lsq5) - @(lsq).           # cdb (d5.001,d5)
   d5  = tidy (d5)                   # cdb (d5.002,d5)  # all higher order terms, should see no O(5) terms

\end{cadabra}

\clearpage

\begin{dgroup*}
   \begin{dmath*} \cdb*{lsq0.002} \end{dmath*}
   \begin{dmath*} \cdb*{lsq2.002} \end{dmath*}
   \begin{dmath*} \cdb*{lsq3.002} \end{dmath*}
   \begin{dmath*} \cdb*{lsq4.002} \end{dmath*}
   \begin{dmath*} \cdb*{lsq5.002} \end{dmath*}
\end{dgroup*}

\begin{dgroup*}
   \begin{dmath*} \cdb*{d20.001} \end{dmath*}
   \begin{dmath*} \cdb*{d32.001} \end{dmath*}
   \begin{dmath*} \cdb*{d43.001} \end{dmath*}
   \begin{dmath*} \cdb*{d54.001} \end{dmath*}
   \begin{dmath*} \cdb*{d5.002} \end{dmath*}
\end{dgroup*}

\clearpage

% =================================================================================================
\section*{Stage 2: Substution of $\ny{n}^{a}$ and $\ngab{m}_{ab}$}

\begin{cadabra}
   import cdblib

   g0ab = cdblib.get('g_ab_0','metric.json')
   g2ab = cdblib.get('g_ab_2','metric.json')
   g3ab = cdblib.get('g_ab_3','metric.json')
   g4ab = cdblib.get('g_ab_4','metric.json')
   g5ab = cdblib.get('g_ab_5','metric.json')

   defg0ab := g0_{a b} -> @(g0ab).
   defg2ab := g2_{a b} -> @(g2ab).
   defg3ab := g3_{a b} -> @(g3ab).
   defg4ab := g4_{a b} -> @(g4ab).
   defg5ab := g5_{a b} -> @(g5ab).

   y0a = cdblib.get('y50','geodesic-bvp.json')
   y2a = cdblib.get('y52','geodesic-bvp.json')
   y3a = cdblib.get('y53','geodesic-bvp.json')
   y4a = cdblib.get('y54','geodesic-bvp.json')
   y5a = cdblib.get('y55','geodesic-bvp.json')

   defy0a := y0^{a} -> @(y0a).
   defy2a := y2^{a} -> @(y2a).
   defy3a := y3^{a} -> @(y3a).
   defy4a := y4^{a} -> @(y4a).
   defy5a := y5^{a} -> @(y5a).

   def substitute_gab_ya (obj):

      foo := @(obj).

      substitute (foo,defg0ab)
      substitute (foo,defg2ab)
      substitute (foo,defg3ab)
      substitute (foo,defg4ab)
      substitute (foo,defg5ab)

      substitute (foo,defy0a)
      substitute (foo,defy2a)
      substitute (foo,defy3a)
      substitute (foo,defy4a)
      substitute (foo,defy5a)

      distribute     (foo)
      sort_product   (foo)
      rename_dummies (foo)
      canonicalise   (foo)

      substitute     (foo,$g_{a b} g^{c b} -> \delta^{c}_{a}$)
      eliminate_kronecker (foo)
      foo = product_sort  (foo)
      rename_dummies      (foo)
      canonicalise        (foo)

      return foo

   def get_Rterm (obj,n):

   # I would like to assign different weights to \nabla_{a}, \nabla_{a b}, \nabla_{a b c} etc. but no matter
   # what I do it appears that Cadabra assigns the same weight to all of these regardless of the number of subscripts.
   # It seems that the weight is assigned to the symbol \nabla alone. So I'm forced to use the following substitution trick.

       Q_{a b c d}::Weight(label=numR,value=2).
       Q_{a b c d e}::Weight(label=numR,value=3).
       Q_{a b c d e f}::Weight(label=numR,value=4).
       Q_{a b c d e f g}::Weight(label=numR,value=5).

       tmp := @(obj).

       distribute (tmp)

       substitute (tmp, $\nabla_{e f g}{R_{a b c d}} -> Q_{a b c d e f g}$)
       substitute (tmp, $\nabla_{e f}{R_{a b c d}} -> Q_{a b c d e f}$)
       substitute (tmp, $\nabla_{e}{R_{a b c d}} -> Q_{a b c d e}$)
       substitute (tmp, $R_{a b c d} -> Q_{a b c d}$)

       foo := @(tmp).
       bah = Ex("numR = " + str(n))
       keep_weight (foo, bah)

       substitute (foo, $Q_{a b c d e f g} -> \nabla_{e f g}{R_{a b c d}}$)
       substitute (foo, $Q_{a b c d e f} -> \nabla_{e f}{R_{a b c d}}$)
       substitute (foo, $Q_{a b c d e} -> \nabla_{e}{R_{a b c d}}$)
       substitute (foo, $Q_{a b c d} -> R_{a b c d}$)

       return foo

   lsq2 = substitute_gab_ya (lsq2)  # cdb (lsq2.101,lsq2)
   lsq3 = substitute_gab_ya (lsq3)  # cdb (lsq3.101,lsq3)
   lsq4 = substitute_gab_ya (lsq4)  # cdb (lsq4.101,lsq4)
   lsq5 = substitute_gab_ya (lsq5)  # cdb (lsq5.101,lsq5)

   lsq50 = get_Rterm (lsq5,0)
   lsq52 = get_Rterm (lsq5,2)
   lsq53 = get_Rterm (lsq5,3)
   lsq54 = get_Rterm (lsq5,4)
   lsq55 = get_Rterm (lsq5,5)

   cdblib.create ('geodesic-lsq.json')

   cdblib.put ('lsq2',lsq2,'geodesic-lsq.json')
   cdblib.put ('lsq3',lsq3,'geodesic-lsq.json')
   cdblib.put ('lsq4',lsq4,'geodesic-lsq.json')
   cdblib.put ('lsq5',lsq5,'geodesic-lsq.json')

   cdblib.put ('lsq50',lsq50,'geodesic-lsq.json')
   cdblib.put ('lsq52',lsq52,'geodesic-lsq.json')
   cdblib.put ('lsq53',lsq53,'geodesic-lsq.json')
   cdblib.put ('lsq54',lsq54,'geodesic-lsq.json')
   cdblib.put ('lsq55',lsq55,'geodesic-lsq.json')

\end{cadabra}

\clearpage
\begin{dgroup*}
   \begin{dmath*} \cdb*{lsq2.101} \end{dmath*}
   \begin{dmath*} \cdb*{lsq3.101} \end{dmath*}
   \begin{dmath*} \cdb*{lsq4.101} \end{dmath*}
   \begin{dmath*} \cdb*{lsq5.101} \end{dmath*}
\end{dgroup*}

% =================================================================================================
% the remaining code is just for pretty printing

\clearpage

% =================================================================================================
\section*{Stage 3: Reformatting}

\begin{cadabra}
   def reformat (obj,scale):
      foo  = Ex(str(scale))
      bah := @(foo) @(obj).
      distribute     (bah)
      bah = product_sort (bah)
      rename_dummies (bah)
      canonicalise   (bah)
      substitute     (bah,$Dx^{b}->zzz^{b}$)
      factor_out     (bah,$x^{a?},zzz^{b?}$)
      substitute     (bah,$zzz^{b}->Dx^{b}$)
      ans := @(bah) / @(foo).
      return ans

   def rescale (obj,scale):
      foo  = Ex(str(scale))
      bah := @(foo) @(obj).
      distribute  (bah)
      substitute  (bah,$Dx^{b}->zzz^{b}$)
      factor_out  (bah,$x^{a?},zzz^{b?}$)
      substitute  (bah,$zzz^{b}->Dx^{b}$)
      return bah

   Rterm0 := @(lsq50).
   Rterm2 := @(lsq52).
   Rterm3 := @(lsq53).
   Rterm4 := @(lsq54).
   Rterm5 := @(lsq55).

   Rterm0 = reformat (Rterm0,   1)    # cdb(Rterm0.301,Rterm0) # LCB: returns Dx before g, not what I want
   Rterm2 = reformat (Rterm2,   3)    # cdb(Rterm2.301,Rterm2)
   Rterm3 = reformat (Rterm3,  12)    # cdb(Rterm3.301,Rterm3)
   Rterm4 = reformat (Rterm4, 360)    # cdb(Rterm4.301,Rterm4)
   Rterm5 = reformat (Rterm5,1080)    # cdb(Rterm5.301,Rterm5)

   Rterm0 := g_{a b} Dx^{a} Dx^{b}.   # LCB: fixes the order of terms, g before Dx,

   lsq3 := @(Rterm0) + @(Rterm2).                                      # cdb (lsq4.301,lsq3)
   lsq4 := @(Rterm0) + @(Rterm2) + @(Rterm3).                          # cdb (lsq4.301,lsq4)
   lsq5 := @(Rterm0) + @(Rterm2) + @(Rterm3) + @(Rterm4).              # cdb (lsq5.301,lsq5)
   lsq6 := @(Rterm0) + @(Rterm2) + @(Rterm3) + @(Rterm4) + @(Rterm5).  # cdb (lsq5.301,lsq6)

   lsq  := @(lsq6).                   # cdb (lsq.301,lsq)

   scaled0 = rescale (Rterm0,    1)   # cdb (scaled0.301,scaled0) # LCB: returns Dx before g, not what I want
   scaled2 = rescale (Rterm2,    3)   # cdb (scaled2.301,scaled2)
   scaled3 = rescale (Rterm3,   12)   # cdb (scaled3.301,scaled3)
   scaled4 = rescale (Rterm4,  360)   # cdb (scaled4.301,scaled4)
   scaled5 = rescale (Rterm5, 1080)   # cdb (scaled5.301,scaled5)

   scaled0 := g_{a b} Dx^{a} Dx^{b}.  # cdb (scaled0.301,scaled0) # LCB: fixes the order of terms, g before Dx, good

\end{cadabra}

\clearpage

% =================================================================================================
\section*{Geodesic arc-length}

\begin{dgroup*}[spread=5pt]
   % LCB: which of these is correct?
   % \begin{dmath*} \left(\Delta s\right)^2 = \cdb{lsq.301} + \BigO{\eps^6,Dx^6} \end{dmath*}
   % \begin{dmath*} \left(\Delta s\right)^2 = \cdb{lsq.301} + \BigO{\eps^6,Dx^7} \end{dmath*}
   \begin{dmath*} \left(\Delta s\right)^2 = \cdb{lsq.301} + \BigO{\eps^6} \end{dmath*}
\end{dgroup*}

\clearpage

% =================================================================================================
\section*{Geodesic arc-length curvature expansion}

\begin{align*}
   % LCB: which of these is correct?
   % \left(\Delta s\right)^2 = \nD{0} + \nD{2} + \nD{3} + \nD{4} + \nD{5} + \BigO{\eps^6,Dx^6}
   % \left(\Delta s\right)^2 = \nD{0} + \nD{2} + \nD{3} + \nD{4} + \nD{5} + \BigO{\eps^6,Dx^7}
   \left(\Delta s\right)^2 = \nD{0} + \nD{2} + \nD{3} + \nD{4} + \nD{5} + \BigO{\eps^6}
\end{align*}

\begin{dgroup*}[spread=5pt]
   \begin{dmath*}      \nD{0} = \cdb{scaled0.301} \end{dmath*}
   \begin{dmath*}    3 \nD{2} = \cdb{scaled2.301} \end{dmath*}
   \begin{dmath*}   12 \nD{3} = \cdb{scaled3.301} \end{dmath*}
   \begin{dmath*}  360 \nD{4} = \cdb{scaled4.301} \end{dmath*}
   \begin{dmath*} 1080 \nD{5} = \cdb{scaled5.301} \end{dmath*}
\end{dgroup*}

\clearpage

% =================================================================================================
% export selected objects, these will later be imported into a library
% these are the objects that will appear in the paper

\begin{cadabra}
   cdblib.create ('geodesic-lsq.export')

   # 3rd to 6th order lsq
   cdblib.put ('lsq3',lsq3,'geodesic-lsq.export')
   cdblib.put ('lsq4',lsq4,'geodesic-lsq.export')
   cdblib.put ('lsq5',lsq5,'geodesic-lsq.export')
   cdblib.put ('lsq6',lsq6,'geodesic-lsq.export')

   # 6th order lsq terms, scaled
   cdblib.put ('lsq60',scaled0,'geodesic-lsq.export')
   cdblib.put ('lsq62',scaled2,'geodesic-lsq.export')
   cdblib.put ('lsq63',scaled3,'geodesic-lsq.export')
   cdblib.put ('lsq64',scaled4,'geodesic-lsq.export')
   cdblib.put ('lsq65',scaled5,'geodesic-lsq.export')

   checkpoint.append (lsq4)

   checkpoint.append (scaled0)
   checkpoint.append (scaled2)
   checkpoint.append (scaled3)
   checkpoint.append (scaled4)
   checkpoint.append (scaled5)
\end{cadabra}

% =================================================================================================
% export checkpoints in json format

\bgroup
\CdbSetup{action=hide}
\begin{cadabra}
   for i in range( len(checkpoint) ):
      cdblib.put ('check{:03d}'.format(i),checkpoint[i],checkpoint_file)
\end{cadabra}
\egroup

\end{document}


\documentclass[../PHYS306Notes.tex]{subfiles}

\begin{document}
\section{Lecture 19}
\subsection{Lecture Notes - Principle Axes of Inertia \& Euler's Equations}
\subsubsection{Motivation Clickers}
Suppose we calculate a diagonal inertia matrix for an objecct in some coordinate system, with $\lambda_1 > \lambda_2 > \lambda_3$. What are the principle axes?
\begin{s}
$(1, 0, 0)$, $(0, 1, 0)$ and $(0, 0, 1)$. If we calculate the inertia matrix to be diagonal in our coordinate system, then it is just the x/y/z axis that are the principal axes. In general, the principal axes are just the coordinate axes if $\II$ is diagonal!
\end{s}
Next, suppose we calculate the moment of inertia of a second object, and it is not diagonal. What are the principle axes in this case?
\begin{s}
$(\v{e}_1, \v{e}_2, \v{e}_3)$ where $\v{e}_i$ are the eigenvectors of $\II$.
\end{s}

\subsubsection{Linear algebra review}
A real symmetric (nxn) matrix can be diagonalized, i.e.:
\[S^{-1}AS = \m{\lambda_1 &  \cdots &  0 \\ \vdots & \ddots & \vdots \\ 0 & \cdots & \lambda_n}\]
The matrix A has eigenvectors $\v{v}_1, \cdots \v{v}_n$ corresponding to eigenvalues $\lambda_1, \cdots \lambda_n$.

The matrix $S$ has the eigenvectors as its columns, that is, $S = [\v{v}_1, \cdots \v{v}_n]$.

The eigenvectors obey the equation $A\v{v}_i = \lambda_i\v{v}_i$.

The eigenvectors form an orthonormal basis.

Note that $S$ here is an orthogonal matrix, that is, $S^T = S^{-1}$, or $SS^T = SS^{-1} = I$. So we could write the above equivalently as $S^{T}AS$.

Another property is that $\det S = \pm 1$.

A group theoretic property is that Orthogonal matrices with $\det(S) = 1$ form the $SO(n)$ group.
\newline Multiplication of a vector by a matrix $A$ is a linear transformation $\v{v} \mapsto A\v{v}$. What happens to an eigenvector of $A$ under this linear transformation?
\begin{s}
The magnitude of the vector can change (in fact, it is rescaled by the corresponding eigenvalue) but the direction does not change.
\end{s}
The eigenvalue equation can be written as $(A - \lambda I)\v{v} = \v{0}$. What condition must be satisfied for $\lambda$ to be an eigenvalue of $A$?
\begin{s}
$\det(A - \lambda I) = 0$
\end{s}
The matrix A has eigenvectors $\v{v}_1, \cdots \v{v}_n$ corresponding to eigenvalues $\lambda_1, \cdots \lambda_n$. The matrix $S$ has the eigenvectors as its columns, that is, $S = [\v{v}_1, \cdots \v{v}_n]$. What is the product $AS$?
\begin{s}
Recall that:
\[S^{-1}AS = \m{\lambda_1 &  \cdots &  0 \\ \vdots & \ddots & \vdots \\ 0 & \cdots & \lambda_n}\]
Hence:
\[AS = S\m{\lambda_1 &  \cdots &  0 \\ \vdots & \ddots & \vdots \\ 0 & \cdots & \lambda_n}\]
Therefore the answer is:
\[AS = [\lambda_1 \v{v}_1 \cdots \lambda_n\v{v}_n]\]
\end{s}
(Question from last day) Which of the following statements are a consequence of the fact that the inertia tensor is a 3x3 matrix with real positive eigenvalues and orthogonal eigenvectors?
\begin{enumerate}
    \item The matrix can be diagonalized
    \item The matrix of eigenvectors is an orthogonal matrix
    \item The matrix of eigenvectors is a rotation matrix (if properly normalized)
    \item In the coordinate system aligned with the eigenvectors, the tensor is diagonal.
\end{enumerate}
\begin{s}
    All 4 are correct (for (c), recall that when we diagonalize a matrix, we rotate our axes/coordinate system).
\end{s}

\subsubsection{Rotational motion and principal axes}
\begin{center}
    \includegraphics[scale=1]{Lecture-19/l19-img1.png}
\end{center}
We have that the torque is defined as:
\[\bm{\Gamma} = \dot{\v{L}}\]
Where $\bm{\Gamma} = \v{r} \times \v{F}$. We can expand out the time derivative of the angular momentum with:
\[\dot{\v{L}} = \dot{\II}\bm{\omega} + \II\dot{\bm{\omega}}\]
But it is quite nasty to work in a frame where the inertia tensor is constantly changing. Hence, let us work in a coordinate system where $\II$ is fixed and hence $\dot{\II} = 0$.
\newline How is the time derivative of a vector $\v{v}$ in an inertial frame I related to the time derivative of the vector in a rotating frame R, which rotates with angular velocity vector $\bm{\omega}$?
\begin{s}
As we derived previously,
\[\left.\dod{\v{v}}{t}\right|_I = \left.\dod{\v{v}}{t}\right|_R + \bm{\omega} \times \v{v}\]
\end{s}
So, we work in the body frame where $\II$ is fixed. Then, expressing the torque in this frame, we have:
\[\bm{\Gamma} = \left.\dod{\v{L}}{t}\right|_{S_0} = \left.\dod{\v{L}}{t}\right|_{Sbod} + \bm{\omega} \times \v{L} = \II\dot{\bm{\omega}} + \bm{\omega} \times \v{L}\]
Choosing our principal axes such that $\II$ is diagonal, we have that:
\[\bm{\omega} \times \v{L} = \bm{\omega} \times \m{\lambda_1 & 0 & 0 \\ 0 & \lambda_2 & 0 \\ 0 & 0 & \lambda_3}\m{\omega_1 \\ \omega_2 \\ \omega_3} = \det\m{\hat{\v{e}}_1 & \hat{\v{e}}_2 & \hat{\v{e}}_3 \\ \omega_1 & \omega_2 & \omega_3 \\ \lambda_1\omega_1 & \lambda_2\omega_2 & \lambda_3\omega_3 }\]
Hence, Euler's equations in the body frame (expanding out our expression for $\bm{\Gamma}$ above are:
\[\Gamma_1 = \lambda_1\dot{\omega}_1 - (\lambda_2 - \lambda_3)\omega_2\omega_3\]
\[\Gamma_2 = \lambda_2\dot{\omega}_2 - (\lambda_3 - \lambda_1)\omega_1\omega_3\]
\[\Gamma_3 = \lambda_3\dot{\omega}_3 - (\lambda_1 - \lambda_2)\omega_1\omega_2\]

\subsubsection{Torque free tumbling}
Consider a box of side lengths $a, 2a, 3a$ aligned as follows:
\begin{center}
    \includegraphics[scale=0.7]{Lecture-19/l19-img2.png}
\end{center}
We can write the inertia tensor to be diagonal:
\[\II = \m{I_1 & 0 & 0 \\ 0 & I_2 & 0 \\ 0 & 0 & I_3}\]
Where $I_1 > I_2 > I_3$ We can then have rotations around three possible axes:
\begin{center}
    \includegraphics[scale=0.7]{Lecture-19/l19-img3.png}
    \includegraphics[scale=0.7]{Lecture-19/l19-img4.png}
\end{center}
We can now apply Euler's equations to learn something about this tumbling motion. Pick arbitrary axis (3) such that $\omega_3 \gg \omega_2 = \omega_1 \approx 0$, i.e. the body is rotating very fast about one axis and not the others. The Euler equations then give us:
\[\lambda_3\dot{\omega}_3 = (\lambda_1 - \lambda_2)\omega_1\omega_2 \approx 0\]
\[\lambda_1\dot{\omega}_1 = (\lambda_2 - \lambda_3)\omega_3\omega_2\]
\[\lambda_2\dot{\omega}_2 = (\lambda_3 - \lambda_1)\omega_3\omega_1\]
The first equation tells us that $\dot{\omega}_3 \approx 0$ and the angular velocity stays relatively constant. Let us take the time derivative of the second equation to learn more information:
\[\lambda_1\ddot{\omega}_1 = (\lambda_2 - \lambda_3)(\dot{\omega}_3\omega_2 + \omega_3\dot{\omega}_2)\]
By the first equation, $\dot{\omega}_3\omega_2 \approx 0$. We can therefore use the third equation to eliminate $\dot{\omega}_2$, which gives us:
\[\lambda_1 \ddot{\omega}_1 \approx (\lambda_2 - \lambda_3)\omega_3\frac{(\lambda_3 - \lambda_1)\omega_3\omega_1}{\lambda_2}\]
We can rewrite this as:
\[\ddot{\omega}_1 = -k\omega_1\]
Where
\[k = \frac{(\lambda_3 - \lambda_2)(\lambda_3 - \lambda_1)}{\lambda_1\lambda_2}\omega_3\]
This is a very familiar differential equation. The sign of $k$ will tell us about the resulting motion.
\newline (1) In the first case, suppose $\lambda_3 > \lambda_2$ and $\lambda_3 > \lambda_1$, or $\lambda_3 < \lambda_2$ and $\lambda_3 < \lambda_2$. Inn these two cases, we have that $k > 0$, and the above equation of motion for $\omega_1$ corresponds to simple harmonic motion (stable + oscillatory).
\newline (2) In the second case, suppose $\lambda_1 < \lambda_3 < \lambda_2$ or $\lambda_2 < \lambda_3 < \lambda_1$, then $k$ is negative, and the above equation of motion for $\omega_1$ corresponds to real exponential solutions (unstable!)
\newline Our conclusion is that the rotation around the middle axis is unstable. This is a mathematical explanation for the famous intermediate axis theorem/tennis racket theorem, which we can see realized here: \\ \texttt{https://www.youtube.com/watch?v=1n-HMSCDYtM}

\end{document}