% !TEX root = ../bachlor-arbeit.tex
To implement the desired algorithm we need to be able to calculate the optical behavior of stacked metasurfaces. The mathematical framework we will use is called scattering matrix calculus and this section will give some insight into its physical origin and how to use it. We will start with Maxwell's equations in matter.
\paragraph{Maxwell Equations}~\\

\begin{tabular*}{\textwidth}{ll}
\begin{minipeqn}
    \curl{\vb{E}(\vb{r}, t)} = - \pdv{t} \vb{B}(\vb{r}, t)
\end{minipeqn}&
\begin{minipeqn}[c]
    \div \vb{D}(\vb{r}, t) = \rho_\s{ext}(\vb r, t)
\end{minipeqn}\\
\begin{minipeqn}
    \curl \vb H(\vb r, t) = \vb j(\vb r, t) + \pdv{t} \vb D(\vb r, t)
\end{minipeqn}&
\begin{minipeqn}[c]
    \div \vb B(\vb r, t) = 0
\end{minipeqn}
\end{tabular*}
\\
\\

The four involved fields are:
$\vb E$ electric field, $\vb B$ magnetic flux density, $\vb D$ electric flux density and $\vb H$ magnetic field and the sources are the external charges $\rho_\s{ext}$ and the macroscopic currents $\vb j$. All the material properties are captured by the $\vb D$ and $\vb H$ fields which are defined as

\begin{equation}\label{eq:bg:D}
\begin{aligned}
    \vb D(\vb r, t) &= \varepsilon_0 \vb E (\vb r, t) + \vb P (\vb r, t)
    \qq{and}\\
    \vb H(\vb r, t) &= \frac{1}{\mu_0} \qty[\vb B(\vb r, t) - \vb M(\vb r, t)],
\end{aligned}
\end{equation}

where $\vb P$ is the dielectric polarization and $\vb M$ is the magnetic polarization. One can read equation \eqref{eq:bg:D} in the following way:
when the electric field $\vb E$ interacts with matter, it exerts a force on all its charges and displaces them by a small amount. This separation of charges results in a counter field $\vb P$ and the total field $\vb D$ is now a superposition of $\vb E$ and $\vb P$.
This set of equations describes the whole electromagnetic spectrum. However, in this work we are only interested in visible (VIS) and near infrared (NIR) light where we can make some simplifications. Generally in optics, materials are non-magnetizable so $\vb M = 0$ and there are no free charges $\rho_\s{ext}$ = 0. Inserting these assumptions into maxwell's equation gives
\\

\noindent
\begin{tabular*}{\textwidth}{ll}
\begin{minipeqn}\label{eq:bg:M1}
    \curl{\vb{E}(\vb{r}, t)} = - \mu_0 \pdv t \vb H(\vb r, t)
\end{minipeqn}&
\begin{minipeqn}[c]\label{eq:bg:M2}
    \varepsilon_0 \div \vb{E}(\vb{r}, t) = - \div \vb P(\vb r, t)
\end{minipeqn}\\
\begin{minipeqn}\label{eq:bg:M3}
    \curl \vb H(\vb r, t) = \vb j(\vb r, t) + \pdv{t} \vb P(\vb r, t)
    + \varepsilon_0 \pdv{t} \vb E(\vb r, t)
\end{minipeqn}&
\begin{minipeqn}[c]
    \div \vb H(\vb r, t) = 0
\end{minipeqn}
\end{tabular*}

\paragraph{Light in Vacuum}~\\
Now we can derive the wave equation by applying $\curl$ to \eqref{eq:bg:M1} which yields

\begin{equation}
\hspace{3cm}
\begin{aligned}
    \phantom{\Longleftrightarrow} \quad
    \curl \bigg [\curl \vb E \bigg ] &= \curl[- \mu_0 \pdv t \vb H]
    \\
    \Longleftrightarrow \quad
    \grad(\div \vb E) - \Delta \vb E &=
    - \mu_0 \pdv t \curl \vb H
    \qquad \bigg | \qq{subs. \eqref{eq:bg:M3} and \eqref{eq:bg:M2}}
    \\
    \Longleftrightarrow \quad \ \
    \frac{1}{c^2} \pdv[2] t \vb E - \Delta \vb E
    &= -\mu_0 \pdv t \vb j - \mu_0 \pdv[2] t \vb P +
    \frac{1}{\varepsilon_0} \grad(\div \vb P)
\end{aligned}
\end{equation}

In vacuum ($\vb P = 0$ and $\vb j = 0$), the right side of this equation vanishes and we are left with\\
$\frac{1}{c^2} \pdv[2] t \vb E - \Delta \vb E = 0$ which is solved by the plane wave $\vb E = \vb E_0 e^{i(\vb k \vb r - \omega t)}$ where $\frac{\omega}{k} = c$. This describes the propagation of light through empty space: a sinusoidal oscillation in time and space along the $\vb k$ direction where $\vb E, \, \vb B$ and $\vb k$ are all perpendicular to each other.

\paragraph{Light in homogeneous isotropic materials}~\\
\label{par:light_in_materials}The next question we can answer is how light propagates through a homogeneous and isotropic material. For us, the dielectric polarization is some linear function of the electric field so $\vb P(\vb r, t) = \hat{\chi}(\omega, \vb r) \vb E(\vb r, t)$. An isotropic material behaves the same for all orientations of $\vb E$ therefor $\hat{\chi}(\omega, \vb r)$ becomes a scalar function $\chi(\omega, \vb r)$. If the material is additionally homogeneous, that is the same everywhere independent of $\vb r$, then $\grad \chi(\omega, \vb r) = 0$. With equation \eqref{eq:bg:M2} this gives us $\div \vb P = 0$
and the wave equation simplifies to
\begin{equation}
\begin{aligned}
    &\frac{\varepsilon}{c^2} \pdv[2] t \vb E - \Delta \vb E = 0,\\
    \qq*{where} &\varepsilon \, \vb E := \qty(1 + \chi) \vb E = \vb E + \vb P.
\end{aligned}
\end{equation}

This implies that light behaves in these materials exactly as it would in vacuum, we only have to account for a decreased speed of light
$c = {c_0} / {\sqrt{\varepsilon}} =: {c_0} / {n}$
with the refractive index $n$.
This is equivalent to a decreased wavelength
$\lambda =: {\lambda_0} / {n}$
or an increased wave number
$k = {2 \pi} / {\lambda} = n \, k_0$,
where $c_0$, $\lambda_0$ and $k_0$ are the quantities in vacuum.
The wave equation is also solved by a complex valued $n := \eta + i \kappa$ which describes the behavior of the exponentially decaying field commonly found in metals

\begin{equation}
    \vb E = \vb E_0 e^{i(n \vb k \vb r - \omega t)}
    = \vb E_0 \
    \underbrace{e^{-\kappa \vb k \vb r}}_\s{
    decay} \
    \underbrace{e^{i(\eta \vb k \vb r - \omega t)}}_\s{
    oscillation}
\end{equation}

\paragraph{Interfaces}~\\
The metasurface stacks we want to understand are obviously not one homogeneous material. Rather, they contain many interfaces between different materials and we can again use the maxwell equations to predict how light will behave at such an interface.
\\

\begin{figure}[H]
    \centering
    \includegraphics[width=.7\linewidth]{bg_interface}
    \caption{An interface of two materials with different refractive indices $n_1$ and $n_2$ and a closed contour $C$ which is tangent to the interface between the points $a$ and $b$. A field vector within the depicted plane can be decomposed into a tangential and a orthogonal component to the interface,
    $\vb E^\parallel$ and $\vb E^\bot$, respectively.}
    \label{fig:bg:interface}
\end{figure}

Let us consider a closed contour $C$ around an interface as seen in Figure \ref{fig:bg:interface} and integrate the first maxwell equation \eqref{eq:bg:M1} over the surface $A$ enclosed by that contour

\begin{equation}
\begin{aligned}
    \int_A \curl \vb E(\vb r, t) \, \dd \vb A
    &= - \mu_0 \pdv t \int_A \vb H(\vb r, t) \dd \vb A\\
    \overset{\s{Stokes}}{\Longleftrightarrow} \hspace{3em}
    \int_{C = \partial A} \vb E(\vb r, t) \dd \vb r
    &= - \mu_0 \pdv t \int_A \vb H(\vb r, t) \dd \vb A\\
\end{aligned}
\end{equation}

But now we can bring the contour infinitesimally close to the interface and thus reduce the right hand side of the equation, the total magnetic flux through the surface, to zero. That leaves us with

\begin{equation}
\begin{aligned}
    \int_a^b \vb E_1 \, \dd \vb r \ &+ \int_b^a \vb E_2 \,  \dd \vb r = 0\\
    \Longleftrightarrow \hspace{3em}
    \int_a^b \vb E_1 \, \dd \vb r &= \int_a^b \vb E_2 \,  \dd \vb r \\
\end{aligned}
\end{equation}

Because $a$ and $b$ were chosen arbitrarily, that means that the transverse field components along the path need to be continuous so
$\vb E_1^{\parallel} = \vb E_2^{\parallel}$.
The analog expression
$\vb H_1^{\parallel} = \vb H_2^{\parallel}$
can be shown by starting with the third maxwell equation \eqref{eq:bg:M3} instead. We can now use these continuity conditions to learn more about the behavior of light at these interfaces.

\begin{figure}[H]
    \centering
    \includegraphics[width=.7\linewidth]{bg_fresnel}
    \caption{Interface between two materials of different refractive indices $n_1$ and $n_2$. The incident light has a wave vector $\vb k^\s{i}$ and is partially transmitted and partially reflected. The fields are shown in transverse electric (TE) polarization where $\vb H$ is in the $x$-$z$ plane and $\vb E$ oscillates in the $y$ direction.
    In this polarization state the $\vb E$ field is fully tangential to the interface and therefor
    $\vb E = \vb E^\parallel$ and $\vb E^\bot = 0$.
    For the $\vb H$ field only the $x$ component is tangential to the interface and the $z$ component is orthogonal to it, so
    $\vb H_x = \vb H^\parallel$ and $\vb H_z = \vb H^\bot$.}
    \label{fig:bg:fresnel}
\end{figure}

Let us consider the same interface from before and have an incident field
$\vb E^\s{i}$ interact with it. From figure \ref{fig:bg:fresnel} we can see

\begin{equation} \label{eq:bg:k}
    \vb k^\s{i} = k_0 n_1
    \begin{pmatrix}
        -\sin \varphi_\s{i}\\ 0\\ -\cos \varphi_\s{i}
    \end{pmatrix}
    , \
    \vb k^\s{r} = k_0 n_1
    \begin{pmatrix}
        \phantom{-} \sin \varphi_\s{r} \\ 0\\ -\cos \varphi_\s{r}
    \end{pmatrix}
    \qq{and}
    \vb k^\s{t} = k_0 n_2
    \begin{pmatrix}
        \sin \varphi_\s{t}\\ 0\\ \cos \varphi_\s{t}
    \end{pmatrix}.
\end{equation}
\\

For the derivation it is useful to decompose the fields into orthogonal polarization components. Here we are going to use the transversal electric (TE) and transversal magnetic (TM) polarizations. The TE component can be seen in figure \ref{fig:bg:fresnel} and in TM polarization $\vb E$ and $\vb H$ fields are simply interchanged.
If we apply the continuity condition from before to the TE component, we get that $\vb E_1 = \vb E_2$ at $z = 0$ therefor

\begin{equation}
\begin{aligned}
    &\vb E^\s{i} + \vb E^\s{r} = \vb E^\s{t} \\
    \Longleftrightarrow \quad
    &E^\s{i} e^{i(k^\s{i}_x x)} \, \va e_y +
    E^\s{r} e^{i(k^\s{r}_x x)} \, \va e_y =
    E^\s{t} e^{i(k^\s{t}_x x)} \, \va e_y,
\end{aligned}
\end{equation}

where $E^\s i, E^\s r, E^\s t \in \mathds R$ are the measurable real field magnitudes. This is only possible for all $x$ if

\begin{equation} \label{eq:bg:x}
    E^\s{i} + E^\s{r} = E^\s{t} \qq{and}
    k^\s{i}_x = k^\s{r}_x = k^\s{t}_x.
\end{equation}

Two basic laws of optics lie in this relation: The law of reflection

\begin{equation}
    k^\s{i}_x = k^\s{r}_x
    \quad \Rightarrow \quad
    k_0 n_1 \sin \varphi_i =  k_0 n_1 \sin \varphi_r
    \quad \Rightarrow \quad
    \varphi_i = \varphi_r := \varphi_1
\end{equation}

and the Snells law of refraction

\begin{equation}
    k^\s{i}_x = k^\s{t}_x, \
    \varphi_t := \varphi_2
    \quad \Rightarrow \quad
    k_0 n_1 \sin \varphi_1 =  k_0 n_2 \sin \varphi_2
    \quad \Rightarrow \quad
    n_1 \sin \varphi_1 = n_2 \sin \varphi_2.
\end{equation}

\paragraph{Fresnel Equations}~\\
To fully describe an interface we also need to know the transmitted and the reflected field amplitudes,
$t := E^t / E^i$
and
$r := E^r / E^i$,
respectively.
Again using the TE polarization shown in figure \ref{fig:bg:fresnel} we see

\begin{equation} \label{eq:bg:H}
    \vb H^\s{i} = H^\s{i}
    \begin{pmatrix}
        -\cos \varphi_\s{i}\\ 0\\ -\sin \varphi_\s{i}
    \end{pmatrix}
    , \
    \vb H^\s{r} = H^\s{r}
    \begin{pmatrix}
        \cos \varphi_\s{r} \\ 0\\ \sin \varphi_\s{r}
    \end{pmatrix}
    \qq{and}
    \vb H^\s{t} = H^\s{t}
    \begin{pmatrix}
        -\cos \varphi_\s{t}\\ 0\\ \sin \varphi_\s{t}
    \end{pmatrix}.
\end{equation}

The $H_x$ component is tangent to the interface, so it also needs to be continuous across the boundary

\begin{equation}\label{eq:bg:Hx}
\begin{aligned}
     H^\s{i}_x +  H^\s{r}_x &=  H^\s{t}_x \\
    \Longleftrightarrow \qquad
    H^\s i \cos \varphi_1 - H^\s r \cos \varphi_1 &= H^\s t \cos \varphi_2
    \qquad  \qquad
\end{aligned}
\end{equation}

If we assume the described plane waves to be
$\vb E = \vb E_0 e^{i(n \vb k \vb r - \omega t)}$
and
$\vb H = \vb H_0 e^{i(n \vb k \vb r - \omega t)}$,
Maxwell's first equation \eqref{eq:bg:M1} allows us to connect the magnitudes of $\vb H$ and $\vb E$ via the refractive index $H \sim n \, E$. This changes \eqref{eq:bg:Hx} to
\begin{equation}
    n_1 \, E^\s i \cos \varphi_1 - n_1 \, E^\s r \cos \varphi_1 =
    n_2 \, E^\s t \cos \varphi_2.
\end{equation}

Substituting $E^\s r$ or $E^\s i$ with \eqref{eq:bg:x} and rearranging we get

\begin{equation}
    t = \frac{2 n_1 \cos \varphi_1}{n_1 \cos \varphi_1 + n_2 \cos \varphi_2}
    \qq{and}
    r = \frac{n_1 \cos \varphi_1 - n_2 \cos \varphi_2}{
    n_1 \cos \varphi_1 + n_2 \cos \varphi_2}.
\end{equation}

These are called the Fresnel coefficients for the TE component. The TM component can be treated analog which yields

\begin{equation}
    t = \frac{2 n_1 \cos \varphi_1}{n_2 \cos \varphi_1 + n_1 \cos \varphi_2}
    \qq{and}
    r = \frac{n_2 \cos \varphi_1 - n_1 \cos \varphi_2}{
    n_2 \cos \varphi_1 + n_1 \cos \varphi_2}.
\end{equation}

For perpendicular incident light at $\varphi = 90^\circ$ these should describe the same situation as we can no longer differentiate between TE and TM components and indeed for this angle they are equivalent if we consider that the TE coefficients describe the electric field and the TM coefficients describe the magnetic field. The TE coefficients become

\begin{equation}
    t = \frac{2 n_1}{n_1 + n_2} \qq{and} r = \frac{n_1 - n_2}{n_1 + n_2}.
\end{equation}

\paragraph{Stacking}~\\
We can take this one step further by including interfaces which have incident light from both sides. Let $\vb E_\s{out}$ be the light coming out of the interface and $\vb E_\s{in}$ be the light going into the interface as seen in figure \ref{fig:bg:both}. Using the factors from the Fresnel equations we get

\begin{equation}
    E^b_\s{out} = E^f_\s{in} \, t^f + E^b_\s{in} \, r^b
    \qq{and}
    E^f_\s{out} = E^b_\s{in} \, t^b + E^f_\s{in} \, r^f
\end{equation}
\vspace{0.5mm}

and this can be expressed more concisely using matrices and vectors

\begin{equation}
\begin{pmatrix}
    E^f_\s{out} \\
    E^b_\s{out}
\end{pmatrix} =
\underbrace{
\begin{pmatrix}
    t^f & r^b \\
    r^f & t^b
\end{pmatrix}
}_{
 =: \hat{S}
}
\begin{pmatrix}
    E^f_\s{in} \\
    E^b_\s{in}
\end{pmatrix}.
\end{equation}

\begin{figure}[H]
    \centering
    \includegraphics[width=.6\linewidth]{bg_both_directions}
    \caption{Interface between two materials of different refractive indices $n_1$ and $n_2$ where incident light is coming from the front and the back.}
    \label{fig:bg:both}
\end{figure}

We call these matrices, that map field-in to field-out, scattering matrices or short $S$-matrices. They can be used to describe more than just interfaces. As shown in the paragraph \hyperref[par:light_in_materials]{Light in materials} when light propagates through homogeneous isotropic material just the phase changes by a factor of $e^{i k_0 n d}$, where $d$ is the distance traveled and $\vb k_0$ the wave vector in vacuum. We can express this propagation by allowing complex valued $t$ and $r$

\begin{equation}
    \hat S_{n, d} =
    \begin{pmatrix}
        e^{i k_0 n d} & 0 \\
        0 & e^{i k_0 n d}
    \end{pmatrix}
\end{equation}

and analog the $S$-matrix for an interface from $n_1$ to $n_2$ is

\begin{equation}
    \hat S_{n_1, n_2} =
    %increase matrix spacing for the fractions
    \begingroup
    \renewcommand*{\arraystretch}{1.5}
        \begin{pmatrix}
            \frac{2 n_1}{n_1 + n_2} & \frac{n_2 - n_1}{n_1 + n_2} \\
            \frac{n_1 - n_2}{n_1 + n_2} & \frac{2 n_1}{n_1 + n_2}
        \end{pmatrix}
    \endgroup.
\end{equation}
\\

Say we have a stack of different homogeneous isotropic materials. We are now able to write down an $S$-matrix for every part of the stack, that is for every interface and every propagation between interfaces as seen in figure \ref{fig:bg:star_prod}, but we cannot predict the behavior of the stack as a whole.
\\

\indent
The combined $S$-matrix $\hat S$ consisting of $\hat S_1$ and $\hat S_2$ cannot be obtained by simply using the matrix product. The result would be

\begin{equation}
    \hat S_1 \, \hat S_2 =
    \begin{pmatrix}
        t^f_1 \, t^f_2 + r^b_1 \, r^f_2 & t^f_1 \, r^b_2 + r^b_1 \, t^b_2 \\
        r^f_1 \, t^f_2 + t^b_1 \, r^f_2 & r^f_1 \, r^b_2 + t^b_1 \, t^b_2
    \end{pmatrix} \neq
    \begin{pmatrix}
        t^f & r^b \\
        r^f & t^b
    \end{pmatrix} =
    \hat S
\end{equation}

and this would imply that the transmission from the front $t^f$ increases when the internal reflections of the system $r^b_1$ and $r^f_2$ increase which is the opposite of the behavior we expect. In the 1960s Redheffer \cite{Redheffer1960} developed a linear transformation called \textit{star product} $\star$ which yields the correct combined $S$-matrix

\begin{equation}\label{eq:bg:star}
    \hat S_1 \star \hat S_2 :=
    \begin{pmatrix}
        t^f_2 (1 - r^b_1 r^f_2)^{-1} t^f_1 &
        r^b_2 + t^f_2 r^b_1 (1 - r^f_2 r^b_1)^{-1} t^b_2\\
        r^f_1 + t^b_1 r^f_2 (1 - r^b_1 r^f_2)^{-1} t^f_1 &
        t^b_1 (1 - r^f_2 r^b_1)^{-1} t^b_2
    \end{pmatrix}.
\end{equation}
\\

\begin{figure}[H]
    \centering
    \includegraphics[width=.6\linewidth]{bg_starprod}
    \caption{A slab of one homogeneous isotropic material with thickness $d$ in air $(n_0)$. This setup is fully described by two interface $S$-matrices
    $\hat S_{n_0,n}, \, \hat S_{n,n_0}$
    and one propagation $S$-matrices
    $\hat S_{n,d}$.}
    \label{fig:bg:star_prod}
\end{figure}

For this operation to produce physically valid results, certain conditions have to be met. We will discuss these in detail in the paragraph \hyperref[par:conditions]{Conditions} of section \ref{sec:SASA}.
Applied to the example of figure \ref{fig:bg:star_prod}, the star product gives

\begin{equation}
    \hat S = \hat S_{n_0, n} \star \hat S_{n, d} \star \hat S_{n, n_0}.
\end{equation}

\paragraph{Polarization}~\\
Up to this point the $S$-matrix is made of the four complex numbers $t^f$, $r^b$, $r^f$ and $t^b$. This means when a $S$-matrix is applied to the input vector containing the total incoming light
$
\begin{pmatrix}
    E^f_\s{in} \\
    E^b_\s{in}
\end{pmatrix}
$,
$E^f_\s{in}$ and $E^b_\s{in}$ are also restricted to the complex plane and can only describe linear polarized light in one direction. The last generalization we want to make is to extend the scattering matrix calculus to all polarizations. As shown in the paragraph \hyperref[par:light_in_materials]{Light in materials} a planar light wave propagating along the $z$ axis through a homogeneous isotropic material can be described as

\begin{equation}
   \vb E =
   \begin{pmatrix}
       E_x e^{i(kz - \omega t + \varphi_x)}\\
       E_y e^{i(kz - \omega t + \varphi_y)}\\
       0\\
   \end{pmatrix}
   =
   \qty(E_x \, e^{i \varphi_x} \, \va{e_x} +
        E_y \, e^{i \varphi_y} \, \va{e_y})
       e^{i(kz - \omega t)}.
\end{equation}
\\

\noindent
The waves polarization is determined by the scaling factors of $\va{e_x}$ and $\va{e_y}$ and can be expressed as a \textit{Jones Vector} $\vb j \in \mathds{C}^2$

\begin{equation}
   \vb j = \frac{1}{\sqrt{E_x^2 + E_y^2}}
   \begin{pmatrix}
       E_x\\
       E_y \, e^{i \delta}
   \end{pmatrix},
   \qq{with}
   \delta := \varphi_y - \varphi_x.
\end{equation}

\noindent
Now all linear operations on the polarization are matrices $\hat{M} \in \mathds{C}^{2 \times 2}$. This means all passive components have a corresponding matrix. Examples for components aligned with the $x$ axis are

\begin{equation}
\begin{split}
   \qq*{linear polarizer:} \hat{M} &=
   \begin{pmatrix}
       1 & 0\\
       0 & 0
   \end{pmatrix},\\
   \qq*{$\lambda / 4$ plate:} \hat{M} &=
   \begin{pmatrix}
       1 & 0\\
       0 & i
   \end{pmatrix}
   e^{-\frac{i \pi}{4}}
   \qq{and}\\
   \qq*{$\lambda / 2$ plate:} \hat{M} &=
   \begin{pmatrix}
       -i & 0\\
       0 & i
   \end{pmatrix}.\\
\end{split}
\end{equation}

We can now generalize the $S$-matrix calculus simply by allowing Jones matrices in place of the Fresnel coefficients: $t \rightarrow \hat T$ and $r \rightarrow \hat R$. The star product of two $S$-matrices becomes

\begin{equation}\label{eq:bg:star}
    \hat S_1 \star \hat S_2 =
    \begin{pmatrix}
        \hat T^f_1 & \hat R^b_1 \\
        \hat R^f_1 & \hat T^b_1
    \end{pmatrix}
    \star
    \begin{pmatrix}
        \hat T^f_2 & \hat R^b_2 \\
        \hat R^f_2 & \hat T^b_2
    \end{pmatrix}
    =
    \begin{pmatrix}
        \hat T^f_2 (\mathds 1 - \hat R^b_1 \hat R^f_2)^{-1} \hat T^f_1 &
        \hat R^b_2 + \hat T^f_2 \hat R^b_1 (\mathds 1 - \hat R^f_2 \hat R^b_1)^{-1} \hat T^b_2\\
        \hat R^f_1 + \hat T^b_1 \hat R^f_2 (\mathds 1 - \hat R^b_1 \hat R^f_2)^{-1} \hat T^f_1 &
        \hat T^b_1 (\mathds 1 - \hat R^f_2 \hat R^b_1)^{-1} \hat T^b_2.
    \end{pmatrix}
\end{equation}

So the generalized $S$-matrix is a $2 \times 2$ block matrix of four Jones matrices and the input vector $\quad $
$
\begin{pmatrix}
    \vb E^f_\s{in} \\
    \vb E^b_\s{in}
\end{pmatrix}
$
is a $2 \times 1$ block vector of two Jones vectors.


For the moment, assume that we are running in comoving coordinates,
with dark matter particles only (no hydro) and that the particles all exist at level 0.   These assumptions are
encapsulated in the following lines in the inputs file: \\

\noindent {\bf nyx.use\_comoving = t} \\
\noindent {\bf nyx.do\_dm\_particles = 1} \\
\noindent {\bf amr.max\_level =  0} \\
\noindent {\bf nyx.do\_hydro = 0} \\
\noindent {\bf nyx.do\_react = 0} \\
\noindent {\bf nyx.do\_grav =  1}

\section{Equations}

If we define ${\mathbf x}_i$ and ${\bf u}_i$ as the location and velocity of particle $i$, respectively, then we wish
to solve
\begin{eqnarray}
\frac{d {\mathbf x}_i}{d t} &=& \frac{1}{a} {\mathbf u}_i \\
\frac{d (a {\mathbf u}_i) }{d t} &=& {\mathbf g}_i
\end{eqnarray}
where ${\mathbf g}_i$ is the gravitational force evaluated at the location of particle $i$, i.e.,
${\mathbf g}_i = {\mathbf g}({\mathbf x}_i,t).$

\section{Initializing the Particles}

\noindent There are several different ways in which particles can currently be initialized:

\subsection{Read from an ASCII file}

To enable this option, set \\

\noindent {\bf nyx.particle\_init\_type = AsciiFile} \\
\noindent {\bf nyx.ascii\_particle\_file =}{\em particle\_file}

Here {\em particle\_file} is the user-specified name of the file.  The first line in this file is
assumed to contain the number of particles.  Each line after that contains  \\

x y z mass xdot ydot zdot \\

Note that the variable that we call the particle velocity, ${\mathbf u} = a {\bf \dot{x}}$,
so we must multiply ${\bf \dot{x}}$, by $a$ when we initialize the particles.

\subsection{Read from a binary file}

To enable this option, set \\

\noindent {\bf nyx.particle\_init\_type = BinaryFile} \\
\noindent {\bf nyx.binary\_particle\_file =}{\em particle\_file} \\

As with the ASCII read, the first line in this file is
assumed to contain the number of particles.  Each line after that contains  \\

x y z mass xdot ydot zdot \\

Note that the variable that we call the particle velocity, ${\mathbf u} = a {\bf \dot{x}}$,
so we must multiply ${\bf \dot{x}}$, by $a$ when we initialize the particles.

\subsection{Read from a binary "meta" file}

This option allows you to read particles from a series of files rather than
just a single file.   To enable this option, set \\

\noindent {\bf nyx.particle\_init\_type = BinaryMetaFile} \\
\noindent {\bf nyx.binary\_particle\_file =}{\em particle\_file} \\

In this case the {\em particle\_file} you specify is an ASCII file specifying a
list of file names with full paths.   Each of the files in this list is assumed
to be binary and is read sequentially (individual files are read in parallel) in
the order listed.

\subsection{Reading SPH particles}

For some applications it is useful to initialize the grid data with SPH-type
particles.   To enable this option, you must set \\

\noindent {\bf nyx.do\_santa\_barbara = 1} \\
\noindent {\bf nyx.init\_with\_sph\_particles = 1} \\

\noindent The SPH-type particles can then be read in by setting \\

\noindent {\bf nyx.sph\_particle\_file =}{\em sph\_particle\_file} \\

\noindent where {\em sph\_particle\_file} is the user-specified name of the file
containing the SPH particles.  The type of {\em sph\_particle\_file}
must be the same (Ascii, Binary or BinaryMeta) as the dark matter particle
file as specified by   \\

\noindent {\bf nyx.particle\_init\_type = } \\

\noindent The SPH particles will be discarded by the code once the grid data has been initialized.

\subsection{Random placement}

To enable this option, set \\

\noindent {\bf nyx.nyx.particle\_init\_type = Random} \\

\noindent There are then a number of parameters to set, for example: \\

\noindent {\bf nyx.particle\_initrandom\_count = 100000}

\noindent {\bf nyx.particle\_initrandom\_mass  = 1}

\noindent {\bf nyx.particle\_initrandom\_iseed = 15}

\subsection{Cosmological}

Using cosmological initial conditions is a three step process:
\begin{enumerate}
	\item Generating a transfer function (e.g. with \texttt{camb})
	\item Generating an initial displacement field (with \texttt{nyx-ic})
	\item Starting nyx
\end{enumerate}

In the following we will look at each step a bit closer.

\subsubsection{Generating a transfer function}

	The transfer function is used in \texttt{nyx-ic} to generate the power
	spectrum. The usual way is to use \texttt{camb}\footnote{See \url{http://camb.info/}}
	to calculate it for the desired universe. A sample \texttt{camb.ini} is
	provided with \texttt{nyx-ic}. The important options are:
	\begin{itemize}
		\item {\bf transfer\_redshift(1) = 50}
		\item {\bf transfer\_matterpower(1) = tf}
	\end{itemize}

	which determine the initial time for the simulation. You should make sure
	that you catch all necessary wave numbers for the considered box length and
	resolution.

	From the \texttt{camb} output you have to note values for \texttt{sigma\_8}
	for a redshift of zero and the initial redshift. We need this to compute
	the right normalization.

\subsubsection{Setting up the initial displacements}

	We calculate the initial displacements with a stand-alone program called
	\texttt{nyx-ic}. This takes a transfer function and some cosmological parameters
	as an argument and outputs an "init" directory which basically contains initial
	displacements for every grid point in an AMReX MultiFAB. Furthermore the mf
	contains a fourth field containing the density contrast as initial condition
	for the baryonic matter. \\
	\texttt{nyx-ic} is started with an ``inputs``
	file similar to the one from Nyx. A sample one is provided. The options are
\begin{verbatim}
#Omega_{Matter}
cosmo.omegam = 0.272
#Omega_{Lambda}
cosmo.omegax = 0.728

#equation of state paramater omega_{effective}
cosmo.weff = -0.980

#Omega_{baryon}*Hubble^2
cosmo.ombh2 = 0.0226
#Hubble/100km/s
cosmo.hubble = 0.704
#scalar spectral index
cosmo.enn = 0.963
# initial z
cosmo.z_init = 50

#sidelength of the box (in Mpc)
cosmo.boxside = 90.14
#seed of the rng
cosmo.isd = 100
#resolution of the box
cosmo.gridpoints = 256
#the output file name
cosmo.initDirName = init

#choose the source of the transferfunction
cosmo.transferfunction = CAMB

#some tabulated transferfunction generated with camb (compare camb-ini-file)
cosmo.tabulatedTk = tf
# sigma8 for the input tf at z=0 and initial z (to calc the growthfactor)
cosmo.init_sigma8_0 = 0.7891368
cosmo.init_sigma8_init = 2.0463364E-02
\end{verbatim}

	The code solves the equation
	\begin{align}
	P(k,a) = 2\pi^2\delta^2_H \frac{k^n}{H_0^{n+3}}T^2(k)\left( \frac{D(a)}{D(a=1)} \right)^2
	\end{align}
	to calculate $P$ and from that gaussian distributed density perturbations
	$\delta$ following that spectrum. Particle displacements are then calculated
	as Zel'dovich displacements.

	Non-gaussian effects as well as neutrino contributions are planned for the
	future.

\subsubsection{Using Nyx with cosmological initial conditions}
	\begin{itemize}
		\item {\bf nyx.nyx.particle\_init\_type = Cosmological} \\
			set the \emph{right} init type
		\item {\bf cosmo.initDirName = init} \\
			set the name of the displacements directory (amrex format)
		\item {\bf cosmo.particle\_mass = 0.19178304E+10} \\
			sets the mass [$M_\odot$] of each particle
		\item {\bf cosmo.omegam = 0.272} \\
			set $\Omega_{Matter}$
		\item {\bf cosmo.omegax = 0.728} \\
			set $\Omega_\Lambda$
		\item {\bf cosmo.hubble = 0.704} \\
			set the reduced hubble constant $h$
	\end{itemize}

	We will generate a particle of mass \textbf{particle\_mass} in every grid cell
	displaced from the center by the value found in the \textbf{initDirName} for
	that cell. Velocities are calculated in the Zel'dovich approximation by
	\begin{align}
		\vec{v} = \Delta{\vec{x}} \times 100 \text{km/s} \times a \sqrt{\Omega_M/a^3+\Omega_\Lambda} \times L_{\text{box}}
	\end{align}
	where $\Delta{\vec{x}}$ is the displacement of the particle.

\section{Time Stepping}

\noindent There are currently two different ways in which particles can be moved:

\subsection{Random}

\noindent To enable this option, set \\

\noindent {\bf nyx.particle\_move\_type = Random} \\

\noindent Update the particle positions at the end of each coarse time step using a
random number between 0 and 1 multiplied by 0.25 dx.

\subsection{Motion by Self-Gravity}

\noindent To enable this option, set \\

\noindent {\bf nyx.particle\_move\_type = Gravitational} \\

\subsubsection{Move-Kick-Drift Algorithm}

In each time step:
\begin{itemize}
\item Solve for ${\mathbf g}^n$  (only if multilevel, otherwise use ${\mathbf g}^{n+1}$ from previous step)
\item ${\mathbf u}_i^{\nph} = \frac{1}{a^{\nph}} ( (a^n {\mathbf u}^n_i) + \frac{\dt}{2} \; {\mathbf g}^n_i )$
\item ${\mathbf x}_i^{n+1 } = {\mathbf x}^n_i +  \frac{\dt}{a^{\nph}}  {\mathbf u}_i^{\nph}$
\item Solve for ${\mathbf g}^{n+1}$ using ${\mathbf x}_i^{n+1}$
\item ${\mathbf u}_i^{n+1} = \frac{1}{a^{n+1}} ( (a^{\nph} {\mathbf u}^{\nph}_i) + \frac{\dt}{2} \; {\mathbf g}^{n+1}_i )$
\end{itemize}

Note that at the end of the timestep ${\bf x}_i^{n+1}$ is consistent with ${\bf g}^{n+1}$ becasue
we have not advanced the positions after computing the new-time gravity.  This has the benefit that
we perform only one gravity solve per timestep (in a single-level calculation with no hydro) because
the particles are only moved once.

\subsubsection{Computing {\bf g}}

We solve for the gravitational vector as follows:
\begin{itemize}
\item Assign the mass of the particles onto the grid in the form of density, $\rho_{DM}$.
The mass of each particle is assumed to be uniformly distributed over a cube of side $\Delta x$,
centered at what we call the position of the particle.    We distribute the mass of each
particle to the cells on the grid in proportion to the volume of the intersection of each cell
with the particle's cube.   We then divide these cell values by $\Delta x^3$ so that the
right hand side of the Poisson solve will be in units of density rather than mass.
Note that this is the {\it comoving} density.

\item Solve $\nabla^2 \phi = \frac{4 \pi G}{a} \rho_{DM}$.
We discretize with the standard 7-point Laplacian (5-point in 2D)
and use multigrid with Gauss-Seidel red-black relaxation to solve the equation for $\phi$ at cell centers.

\item Compute the normal component of ${\bf g} = -\nabla \phi$ at cell faces by differencing the adjacent values of $\phi,$
e.g. if $\gb = (g_x, g_y, g_z),$ then we define $g_x$ on cell faces with a normal in the x-direction by computing
$g_{x,i-\myhalf,j,k} = -(\phi_{i,j,k} - \phi_{i-1,j,k}) / \Delta x.$

\item  Interpolate each component of ${\bf g}$ from normal cell faces onto each particle position using
linear interpolation in the normal direction.

\end{itemize}

%\subsection{Predictor-Corrector}
%
%An alternative to the above algorithm would be the following predictor-corrector approach:
%
%\begin{itemize}
%\item Solve for ${\bf g}^n$
%\item ${\bf v}_i^{n+1,*} = {\bf v}^n_i + \dt \; {\bf g}^n$
%\item ${\bf x}_i^{n+1,*} = {\bf x}^n_i + \dt \; {\bf v}_i^n$
%\item Solve for ${\bf g}^{n+1}$ using ${\bf x}_i^{n+1,*}$
%\item ${\bf v}_i^{n+1} = {\bf v}^{n+1,*}_i + \frac{\dt}{2} \; ({\bf g}^{n+1} - {\bf g}^n)$
%\item ${\bf x}_i^{n+1} = {\bf x}^{n+1,*}_i + \frac{\dt}{2} \; ({\bf v}_i^{n+1} - {\bf v}_i^n)$
%\end{itemize}
%
%\noindent This has two issues:
%\begin{itemize}
%\item First, the gravity at the end of the timestep is not consistent with the particle positions at the end of the timestep.
%Thus this will require an additional solve per timestep because we move the particles twice per timestep.
%\item Second, this increases the memory required per particle because we would need to keep both ${\bf v}^n_i$
%and ${\bf v}^{n+1,*}_i$ over the course of a timestep.
%\end{itemize}

\section{Output Format}

\subsection{Checkpoint Files}

The particle positions and velocities are stored in a binary file in each checkpoint directory.
This format is designed for being read by the code at restart rather than for diagnostics. \\

We note that the value of $a$ is also written in each checkpoint directory,
in a separate ASCII file called {\em comoving\_a}, containing only the single value. \\

\subsection{Plot Files}

If {\bf particles.write\_in\_plotfile =} 1 in the inputs file
then the particle positions and velocities will be written in a binary file in each plotfile directory.

In addition, we can also
visualize the particle locations as represented on the grid.  There are two ``derived quantities''
which represent the particles.  Setting \\

\noindent {\bf amr.derive\_plot\_vars = particle\_count particle\_mass\_density} \\
\noindent {\bf amr.plot\_vars = NONE} \\

\noindent in the inputs file will generate plotfiles with only two variables.
{\bf particle\_count} represents the number of particles in a grid cell;
{\bf particle\_mass\_density} is the density on the grid resulting from the particles.

We note that the value of $a$ is also written in each plotfile directory,
in a separate ASCII file called {\em comoving\_a}, containing only the single value. \\

\subsection{ASCII Particle Files}

To generate an ASCII file containing the particle positions and velocities,
one needs to restart from a checkpoint
file but doesn't need to run any steps.  For example, if chk00350 exists, then one can set: \\

\noindent {\bf amr.restart = chk00350} \\
\noindent {\bf max\_step = 350} \\
\noindent {\bf particles.particle\_output\_file =} {\em particle\_output} \\

\noindent which would tell the code to restart from chk00350, not to take any further time steps, and to write an ASCII-format
file called {\em particle\_output}. \\

\noindent This file has the same format as the ASCII input file: \\

\noindent number of particles \\
x y z mass xdot ydot zdot \\

\subsection{Run-time Data Logs}

If you set \\

\noindent {\bf amr.data\_log = }{\em log\_file}  \\

\noindent in the inputs file, then at run-time the code will write a log file with entries every coarse
grid time step, containing \\

\noindent nstep  time   dt   redshift   a

\subsection{Run-time Screen Output}

There are a number of flags that control the verbosity written to the screen at run-time.  These are:

\noindent {\bf amr.v } \\
\noindent {\bf nyx.v } \\
\noindent {\bf gravity.v } \\
\noindent {\bf mg.v } \\
\noindent {\bf particles.v } \\

These control printing  about the state of the calculation (time, value of $a$, etc) as well as
timing information.


\subsection{Association rules}

\subsubsection{The data}

We have a transaction dataset, \(D\).

This includes transactions of items in \(I\).

Any subset of \(I\) is an itemset.

A subset of size \(k\) is a \(k\)-itemset.

Transactions are a \(k\)-itemset with a unique id, tid.

The set of all transactions is \(T\).

A tidset is a subset of \(T\).

\subsubsection{Forming a lattice}

We have a total order on the items.

An itemset \(ab\) is greater than \(a\), for examplle.

The two points of the lattice are the nullset, and \(I\).

\subsubsection{Mappings}

We have a mapping from \(I\) to \(T\) called \(t\).

We have another mapping from \(T\) to \(I\) called \(i\).

\subsubsection{Frequency}

We define the frequency of an itemset as the number of transactions it appears in.

We can write the frequency of \(A\) as \(\sum A\).


\documentclass{article}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath, amsthm, verbatim, enumerate, xcolor, mathpartir}

\input{macros}

\title{IIT CS595: Topics \& Applications in Programming Languages\\
  {\large Homework 0: Rule induction, expressions, type safety}}
\author{Dustin Van Tate Testa}

\begin{document}
\maketitle

\section{Logistics}

\paragraph{Writing up Solutions.}
If you're looking at this file, you're probably (at least thinking about)
writing up your solutions in LaTeX. Nice! If you need help, see the writeup
PDF for a link to resources and other options.

\paragraph{Collaboration.}
Please see the collaboration policy on the course website.

\paragraph{Submission.}
Submit your answers as a single .pdf or .doc file (see above) on Blackboard
under
the correct assignment.

\section{Evaluation}
\begin{task}
  Evaluate the following expression using the dynamics semantics from class,
  showing each step:

  (Put your answers in the ... and copy and paste the line to add more lines
  as necessary).

  \[
  \begin{array}{l l}
    &
    \kwlet{x}{\kwn{2}}{x+(\kwlet{x}{\kwn{1}}{\kwlet{y}{x+\kwn{1}}{x+y}})}\\
    \step & \kwn{2}+(\kwlet{x}{\kwn{1}}{\kwlet{y}{x+\kwn{1}}{x+y}})\\
    \step & \kwn{2}+(\kwlet{y}{\kwn{1}+\kwn{1}}{\kwn{1}+y}\\
    \step & \kwn{2}+(\kwlet{y}{\kwn{2}}{\kwn{1}+y}\\
    \step & \kwn{2}+(\kwn{1}+\kwn{2})\\
    \step & \kwn{2}+\kwn{3}\\
    \step & \kwn{5}\\
  \end{array}
  \]
\end{task}

\section{Red-Black Trees}
In data structures, a red-black tree is a binary tree whose nodes are colored
either red or black.
%
Red-black trees must obey the following rules:
\begin{itemize}
\item Leaf nodes must be black.
\item No red node has red children.
\item Any path from the root to a leaf contains the same number of black nodes.
\end{itemize}

We can express red-black trees using the following small language
(note that this syntax doesn't enforce the rules above; we'll do that later).

\[
\begin{array}{r l l l}
  Trees & \tree & \bnfdef & \leaf \bnfalt \bnode{\tree}{\tree} \bnfalt
  \rnode{\tree}{\tree}\\
  Colors & \colr & \bnfdef & \bc \bnfalt \rc\\
\end{array}
\]
where~$\leaf$ is a leaf and~$\bnode{\tree_1}{\tree_2}$
and~$\rnode{\tree_1}{\tree_2}$ represent black and red nodes, respectively,
with children~$\tree_1$ and~$\tree_2$.

We will define a judgment~$\tree\istree{\colr}{n}$, meaning that~$\tree$ is
a valid red-black tree whose root node has the color~$\colr$ (which is
either~$\bc$ or~$\rc$) and all of whose paths from root to leaf have
exactly~$n$ black nodes.

{
  \centering
  \def \MathparLineskip {\lineskip=0.43cm}
  \begin{mathpar}

    \Rule{RBT-1}
         {\strut}
         {\leaf \istree{\bc}{1}}
    \and
    \Rule{RBT-2}
         {\tree_1 \istree{\colr_1}{n}\\
           \tree_2 \istree{\colr_2}{n}}
         {\bnode{\tree_1}{\tree_2} \istree{\bc}{n+1}}
    \and
    \Rule{RBT-3}
         {\tree_1 \istree{\bc}{n}\\
           \tree_2 \istree{\bc}{n}}
         {\rnode{\tree_1}{\tree_2} \istree{\rc}{n}}
  \end{mathpar}
}

Rule~(RBT-1) says that leaves are valid trees as long as they are
black: a leaf by definition has~1 black node on any path from root to leaf.
%
Rule~(RBT-2) allows a black node with two children as long as both
children are valid red-black trees with the same number of black nodes on any
path (regardless of what color their roots are); the result is a tree with a
black root and~$n+1$ black nodes on any path.
%
Rule~(RBT-3) enforces that red nodes do not have red children by
requiring in the premises that both children have black roots.

Define~$\nodes{\tree}$ to be the number of nodes, including leaves, in a
tree:

\[
\begin{array}{l l l}
  \nodes{\leaf} & = & 1\\
  \nodes{\bnode{\tree_1}{\tree_2}} & = & 1 + \nodes{\tree_1} + \nodes{\tree_2}\\
  \nodes{\rnode{\tree_1}{\tree_2}} & = & 1 + \nodes{\tree_1} + \nodes{\tree_2}
\end{array}
\]

\begin{task}
  Prove by rule induction that for any tree~$\tree$,
  color~$\colr \in \{\rc, \bc\}$ and~$n \geq 1$,
  if~$\tree \istree{\colr}{n}$, then~$\nodes{\tree} \geq 2^{n-1}$.

  {\em You must} use rule induction, not any other proof technique.

  \textbf{Note:} This, together with one or two other properties of
  red-black trees, proves that a valid red-black tree is approximately
  balanced.
\end{task}

\textbf{Answer:}

- Notice use of shorthand $\kwlen{\tree}$ to indicate the value of $n$ (black height) for tree \tree \\

Base Case:
\begin{itemize}
    \item all cases when n = 1:
        \begin{itemize}
            \item {\tree = \leaf}: Rule~(RBT-1) confirms that when T is a single black node, n = 1.\\
            The proposition holds for this case as $\nodes{\leaf} = 1 \geq 2^{n-1} = 2^{1-1} = 1$.

            \item {\tree = \rnode{\leaf}{\leaf}}: rule~(RBT-3) confirms that when $\tree$ is a red node,
            n is the same as it's children, which when they're both leaves makes n = 1.\\
            The proposition holds for this case as follows:\\
            LHS: $\nodes{\rnode{\leaf}{\leaf}} = 1 + \nodes{\leaf} + \nodes{\leaf} = 1 + 1 + 1 = 3$\\
            RHS: $2^{n-1} = 2 ^ {1 - 1} = 2^0 = 1$\\
            giving $3 \geq 1$
        \end{itemize}
\end{itemize}

Inductive case assuming $\nodes{\tree} \geq 2^{n-1}$:
\begin{itemize}
    \item Case when $\tree = \bnode{...}{...}$ -- tree's top element is a black node
        \[
        \begin{array}{l l l l}
            \nodes{\bnode{\tree_1}{\tree_2}} & \geq & 2^{\kwlen{\tree}-1} & \text{the proposition for this case}\\
            1 + \nodes{\tree_1} + \nodes{\tree_2} & \geq & 1 + 2 ^ {\kwlen{\tree_1} - 1} + 2 ^ {\kwlen{\tree_2} - 1} & \text{apply rule (RBT-2)}\\
            1 & \geq & 1  & \text{apply inductive hypothesis}\\
        \end{array}
        \]

    \item Case when $\tree = \rnode{...}{...}$ -- tree's top element is a red node
        \[
        \begin{array}{l l l l}
            \nodes{\rnode{\tree_1}{\tree_2}} & \geq & 2^{\kwlen{\tree}-1} & \text{the proposition for this case}\\
            1 + \nodes{\tree_1} + \nodes{\tree_2} & \geq & 2 ^ {\kwlen{\tree_1} - 1} + 2 ^ {\kwlen{\tree_2} - 1} & \text{apply rule (RBT-3)}\\
            1 & \geq & 0  & \text{apply inductive hypothesis}\\
        \end{array}
        \]
\end{itemize}

\section{Booleans}

In this task, you'll extend the {\Elang} language from class with Booleans:

\[
\begin{array}{r l l l}
  \mathit{Types} & \tau & \bnfdef &
  \kwint \bnfalt \kwstring \bnfalt \kwbool\\
  \mathit{Expressions} & e & \bnfdef &
  x \bnfalt
  \kwn{n} \bnfalt
  \kws{s} \bnfalt
  \kwtrue \bnfalt
  \kwfalse \bnfalt
  e = e \bnfalt
  e + e \bnfalt
  e \cat e \bnfalt
  \kwlen{e} \bnfalt
  \kwlet{x}{e}{e} \bnfalt
  \kwif{e}{e}{e}
\end{array}
\]

The expressions~$\kwtrue$ and~$\kwfalse$ are values and have their usual
meanings.
%
The expression~$\kwif{e_1}{e_2}{e_3}$ should evaluate~$e_1$. If it evaluates
to~$\kwtrue$, it should continue evaluating~$e_2$, otherwise it should
continue evaluating~$e_3$.
%
The other branch {\em should not} be evaluated (this isn't possible to express
in {\Elang}, but consider the code $\kwif{x = \kwn{0}}{\kwn{0}}{\kwn{42} / x}$: we certainly
don't want to evaluate the else branch when the condition is true!).
%
We've also added an integer equality test~$e_1 = e_2$ to have an interesting
way of producing Booleans (this is an operation on integers only, not on
Booleans or strings).
%
Recall the dynamic semantics from class, now extended with the rules
for~$e_1 = e_2$.

\textbf{Note:} There's a lot here, but don't panic:
the only new rules here are (S-11) through (S-14). The rest are just there
as a reminder. Your job is only to add Booleans to the language.

{
  \centering
  \def \MathparLineskip {\lineskip=0.43cm}
  \begin{mathpar}
    \Rule{V-1}
         {\strut} % This leaves the proper spacing above the line of an axiom
         {\kwn{n}\val}
    \and
    \Rule{V-2}
         {\strut}
         {\kws{s}\val}
    \and
    \Rule{S-1}
         {\strut}
         {\kwn{n_1} + \kwn{n_2} \step \kwn{n_1 + n_2}}
    \and
    \Rule{S-2}
         {\strut}
         {\kws{s_1} \cat \kws{s_2} \step \kws{s_1s_2}}
    \and
    \Rule{S-3}
         {\strut}
         {\kwlen{\kws{s}} \step \kwn{\kwlen{s}}}
    \and
    \Rule{S-4}
         {e_1 \step e_1'}
         {e_1 + e_2 \step e_1' + e_2}
    \and
    \Rule{S-5}
         {e_2 \step e_2'}
         {\kwn{n_1} + e_2 \step \kwn{n_1} + e_2'}
    \and
    \Rule{S-6}
         {e_1 \step e_1'}
         {e_1 \cat e_2 \step e_1' \cat e_2}
    \and
    \Rule{S-7}
         {e_2 \step e_2'}
         {\kws{s_1} \cat e_2 \step \kws{s_1} \cat e_2'}
    \and
    \Rule{S-8}
         {e \step e'}
         {\kwlen{e} \step \kwlen{e'}}
    \and
    \Rule{S-9}
         {e_1 \step e_1'}
         {\kwlet{x}{e_1}{e_2} \step \kwlet{x}{e_1'}{e_2}}
    \and
    \Rule{S-10}
         {v \val}
         {\kwlet{x}{v}{e_2} \step \sub{v}{x}{e_2}}
    \and
    \Rule{S-11}
         {e_1 \step e_1'}
         {e_1 = e_2 \step e_1' = e_2}
    \and
    \Rule{S-12}
         {e_2 \step e_2'}
         {\kwn{n_1} = e_2 \step \kwn{n_1} = e_2'}
    \and
    \Rule{S-13}
         {\strut}
         {\kwn{n} = \kwn{n} \step \kwtrue}
    \and
    \Rule{S-14}
         {n_1 \neq n_2}
         {\kwn{n_1} = \kwn{n_2} \step \kwfalse}
  \end{mathpar}
}

\begin{task}\label{task:dyn}
  Write the new inference rules for the dynamic semantics of Booleans and the
  if-else construct.
  You should have 2 new rules for the judgment~$e\val$ and 3 new rules
  for the judgment~$e \step e$.\\
  (\textbf{Hint:} only one of these will be a search rule.)
\end{task}

\textbf{Answer:}

{
    \centering
    \def \MathparLineskip{\lineskip=0.43cm}
    \begin{mathpar}
        \Rule{V-3}
            {\strut}
            {\kwfalse \val}
        \and
        \Rule{V-4}
            {\strut}
            {\kwtrue \val}
        \and
        \Rule{S-15}
            {e_1 \step e_1'}
            {\kwif{e_0}{e_1}{e_2} \step \kwif{e_0'}{e_1}{e_2}}
        \and
        \Rule{S-16}
            {\strut}
            {\kwif{\kwtrue}{e_1}{e_2} \step e_1}
        \and
        \Rule{S-17}
            {\strut}
            {\kwif{\kwfalse}{e_1}{e_2} \step e_2}
    \end{mathpar}
}

We also extend the typing rules with the new rule for equality testing and
Booleans.

{
  \centering
  \def \MathparLineskip {\lineskip=0.43cm}
  \begin{mathpar}
    \Rule{T-8}
         {\typed{\ctx}{e_1}{\kwint}\\
           % Use \\ to separate multiple premises
           \typed{\ctx}{e_2}{\kwint}}
         {\typed{\ctx}{e_1 = e_2}{\kwbool}}
    \and
    \Rule{T-9}
         {\strut}
         {\typed{\ctx}{\kwtrue}{\kwbool}}
    \and
    \Rule{T-10}
         {\strut}
         {\typed{\ctx}{\kwfalse}{\kwbool}}
    \and
    \Rule{T-11}
         {\typed{\ctx}{e_1}{\kwbool}\\
           \typed{\ctx}{e_2}{\tau}\\
           \typed{\ctx}{e_3}{\tau}}
         {\typed{\ctx}{\kwif{e_1}{e_2}{e_3}}{\tau}}
  \end{mathpar}
}

Note that rule (T-11) doesn't require that the two branches of the conditional
have a particular type (e.g.~$\kwint$).
%
The use of the same metavariable~$\tau$ {\em does} however, mean that the
two branches~$e_2$ and~$e_3$ must have the {\em same} type, which is then the
type of the whole expression
(this makes sense: how could we possibly give a type to the expression
$\kwif{n = \kwn{0}}{\kwn{42}}{\kws{\text{Oops}}}$?).

\begin{task}
  Prove the cases of the Preservation theorem for the new rules you
  added in Task~\ref{task:dyn}.
\end{task}

\textbf{Answer:}

Proposition: if $\typed{\ctx}{e}{\tau}$ and $e \step e'$ then $\typed{\ctx}{e'}{\tau}$
\begin{itemize}
    \item S-16: When $e = \kwif{\kwtrue}{e_1}{e_2}$\\ \step $e' = e_1$\\
        by inversion on rule (T-11) $\typed{\ctx}{\kwif{e_0}{e_1}{e_2}}{\tau}$
            and  $\typed{\ctx}{e_1}{\tau}$\\
        with induction on $e_1 \step e_1'$ this confirms that the type of the stepped value is preserved.

    \item S-17: When $e = \kwif{\kwfalse}{e_1}{e_2}$\\ \step $e' = e_2$\\
        by inversion on rule (T-11) $\typed{\ctx}{\kwif{e_0}{e_1}{e_2}}{\tau}$
            and  $\typed{\ctx}{e_2}{\tau}$\\
        with induction on $e_2 \step e_2'$ this confirms that the type of the stepped value is preserved.

    \item S-15: When $e = \kwif{e_0}{e_1}{e_2}$\\ \step $e' = \kwif{e_0'}{e_1}{e_2}$\\
        by inversion on rule (T-11), $\typed{\ctx}{e_0}{\kwbool}$, $\typed{\ctx}{e_1}{\tau}$,
            and $\typed{\ctx}{e_2}{\tau}$\\
        by induction we can assume $e_0 \step e_0'$ with $\typed{\ctx}{e_0'}{\kwbool}$\\
        thus we can apply (T-11) to assert that the type is the same.
\end{itemize}

\begin{task}\label{task-cf}
  State (you do not have to prove it) the new case of the Canonical Forms
  lemma for Booleans.
\end{task}

\textbf{Answer:}
if $e \val$ and $\typed{}{e}{\kwbool}$ then $e$ is either $\kwtrue$ or $\kwfalse$.

\begin{task}
  Prove the cases of the Progress theorem for the new rules
  (T-9) through (T-11). You may (and should) use the new case of Canonical
  Forms from Task~\ref{task-cf}.
\end{task}

\textbf{Answer:}

Proposition: if $\typed{}{e}{\tau}$ then $e \val$ or $e \step e'$
\begin{itemize}
    \item T-9: $e = \kwtrue$, $\tau = \kwbool$\\
        by V-4 $e \val$
    \item T-10: $e = \kwfalse$, $\tau = \kwbool$\\
        by V-3 $e \val$
    \item T-11: $e = \kwif{e_1}{e_2}{e_3}$\\
        by inversion on rule T-11 $\typed{}{e_1}{\kwbool}$\\
        by induction, either $e_1 \val$ or $e_1 \step e_1'$\\
        by the Canonical Forms lemma for from Task~\ref{task-cf} $e_1$ can hold either \kwtrue or \kwfalse
        \begin{itemize}
            \item \kwtrue : S-16 confirms that $\kwif{\kwtrue}{e_2}{e_3} \step e_2$ and thus $e' = e_2$
            \item \kwfalse : S-17 confirms that $\kwif{\kwfalse}{e_2}{e_3} \step e_3$ and thus $e' = e_3$
        \end{itemize}

\end{itemize}

\end{document}


\chapter{Governing Equations}
\label{cha:governing:equations}

This chapter presents the solution schemes we use for solving
variations of the elasticity equation using the finite-element
method. In all of our derivations, we use the notation described in
Table \vref{tab:notation}.

\begin{table}[htbp]
  \caption{Mathematical notation}
  \label{tab:notation}
  \begin{tabular}{cp{3in}}
    \toprule
    {\bf Symbol} & {\bf Description} \\
    \midrule
    $\vec{a}$ & Vector field a \\
    $\tensor{a}$ & Second order tensor field a \\
    $\vec{u}$ & Displacement vector field \\
    $\vec{v}$ & Velocity vector field \\
    $\vec{{d}}$ & Fault slip vector field \\
    $\vec{f}$ & Body force vector field \\
    $\vec{\tau}$ & Traction vector field \\
    $\tensor{\sigma}$ & Stress tensor field \\
    $\vec{n}$ & Normal vector field \\
    $\rho$ & Mass density scalar field \\
    \bottomrule
  \end{tabular}
\end{table}

\input{governingeqns/elasticity_derivation.tex}
\input{governingeqns/formulation.tex}

\input{governingeqns/elasticity_infstrain.tex}
\input{governingeqns/elasticity_infstrain_prescribedslip.tex}
\input{governingeqns/incompressible_elasticity.tex}
\input{governingeqns/poroelasticity.tex}