\chapter{Many-body basics and wave function expansion methods}\label{ch:many_body}

The goal of many-body quantum mechanics is to solve
the $A$-body time-independent Sch\"{o}dinger equation.
This requires, among other things, the construction of a set of states that span
the $A$-body Hilbert space.
For distinguishable particles, taking a set of single-particle states $\ket{p}$
and building $A$-body product states $\ket{p_1}\ldots\ket{p_A}$ would be a reasonable approach.
However, the wave function of a system of $A$ nucleons,
which are indistinguishable fermions,
must be antisymmetric under the exchange of any two particle labels.
The explicit antisymmetrization of states going from naive product states
quickly becomes unwieldy with growing $A$.

Second quantization offers an alternative that bakes the required antisymmetry
into the formalism.
This formalism is the basis for a class of many-body methods
called wave function expansion methods, which includes the IM-SRG.\@
These methods have the benefit that,
instead of scaling combinatorially in $A$ like exact diagonalization approaches,
they scale polynomially,
taking advantage of knowledge of a good approximate solution to the ground state
to reduce the task to finding corrections to this zeroth-order ansatz.
In this chapter, we introduce the basics of second quantization and normal ordering,
focusing on the case of fermions.
Then we discuss some of the more traditional wave function expansion methods
before discussing the IM-SRG in detail in the next chapter.

\section{Second quantization}\label{sec:second_quantization}

To consider second quantization, one starts by constructing the Fock space,
the direct sum of all $A$-body antisymmetric Hilbert spaces.
As a concrete example, for the zero-, one-, and two-body Hilbert spaces, we have the bases
\begin{align}
  A = 0 & \rightarrow \ket{0}\,, \\
  A = 1 & \rightarrow \{\ket{p}\}\,, \\
  A = 2 & \rightarrow \left\{\frac{\ket{p}_{1}\ket{q}_{2} - \ket{q}_{1}\ket{p}_2}{\sqrt{2}} \, \Big| \, q > p \right\}\,.
\end{align}
These states (and many more) are all in the Fock space,
related to one another via field operators.

The field operators are particle creation and annihilation operators
that connect states in the $A$-body antisymmetric Hilbert space
to states in the $A+1$-body and $A-1$-body antisymmetric Hilbert spaces.
The creation operator \crea{p} creates a particle in the single-particle state $\ket{p}$.
Operating on an $A$-body state with it creates an $A+1$-body state
with an additional particle in state $\ket{p}$,
\begin{equation}
  \crea{p} \ket{p_1 \ldots p_{A}}_a = (1 - n_{p}) \ket{p p_1 \ldots p_{A}}_a\,,
\end{equation}
where we have explicitly denoted that the states are antisymmetrized.
Here, $n_p$ is the occupation number of state $\ket{p}$ in the $A$-body state,
which for fermions, due to the Pauli exclusion principle, can only be 0 or 1.
Attempting to create a second particle in an already occupied state annihilates the state.

The annihilation operator \annih{p} annihilates a particle in the single-particle state $\ket{p}$.
Operating on an $A$-body state with it creates an $A-1$-body state
with a particle in state $\ket{p}$ removed,
\begin{equation}
  \annih{p} \ket{p p_2 \ldots p_A}_a = n_p \ket{p_2 \ldots p_A}_a\,.
\end{equation}
If no particle with the single-particle state $\ket{p}$ exists in the state,
the annihilation operator annihilates the state.

With the field operators, an antisymmetric $A$-body state can very efficiently be written as
\begin{equation}
  \ket{p_1 p_2 \ldots p_A}_a = \crea{p_1} \crea{p_2} \ldots \crea{p_A} \ket{0}\,.
\end{equation}
This antisymmetrized product of $A$ particles in $A$ unique single-particle states
is frequently referred to as a Slater determinant,
owing to the fact that it can be, in its explicitly antisymmetrized form,
written as an appropriately normalized determinant~\cite{Slat29sladet}.

Since these states should be antisymmetric under exchange of particle indices, that is,
\begin{equation}
  \ket{p_1 p_2 \ldots p_A}_a = - \ket{p_2 p_1 \ldots p_A}_a\,,
\end{equation}
the creation and annihilation operators must anti-commute with themselves,
\begin{align}
  \anticomm{\crea{p}}{\crea{q}} = 0\,,\\
  \anticomm{\annih{p}}{\annih{q}} = 0\,.
\end{align}
Similarly, one can arrive at the anti-commutation relation
between creation and annihiliation operators,
\begin{equation}
  \anticomm{\annih{p}}{\crea{q}} = \delta_{pq}\,.
\end{equation}

With this formalism in place,
we are now in a position to discuss the representation of many-body operators
in the Fock space.
Operators are classified as $A$-body operators if they can at most couple $A$ particles.
We have used this language frequently so far,
but we make it very precise in the following discussion.

Zero-body operators are simple scalars,
\begin{equation}
  \zerobodyop{O} = o\,.
\end{equation}
They have, among other things, in general a non-zero vacuum expectation value.

One-body operators are of the form
\begin{equation}\label{eq:onebody_op_definition}
  \onebodyop{O} = \sum_{pq} \onebodyop{O}_{pq} \crea{p} \annih{q}\,,
\end{equation}
where $\onebodyop{O}_{pq}$ are the matrix elements of $\onebodyop{O}$.
One-body operators have two useful properties.
First, their vacuum expectation value is 0:
\begin{equation}
  \braket{0 | \onebodyop{O} | 0} = 0\,.
\end{equation}
Second, they do not contribute to processes
where the incoming (bra) and outgoing (ket) states differ
in more than one single-particle state.
Some examples of one-body operators are the kinetic energy and an external potential.

Two-body operators are of the form
\begin{equation}
  \twobodyop{O} = \frac{1}{{(2!)}^2} \sum_{pqrs} \twobodyop{O}_{pqrs} \crea{p} \crea{q} \annih{s} \annih{r}\,.\label{eq:twobody_op_definition}
\end{equation}
Here $\twobodyop{O}_{pqrs}$ is an antisymmetrized matrix element, with the property
\begin{equation}
  \twobodyop{O}_{pqrs} = - \twobodyop{O}_{qprs} = - \twobodyop{O}_{pqsr} = \twobodyop{O}_{qpsr}\,.
\end{equation}
We note that in Eq.~\ref{eq:twobody_op_definition}
the order of the annihilation operators is reversed
relative to the indices on the matrix element.
The indices $p$ and $r$ and the indices $q$ and $s$ are ``paired,''
and the product of creation and annihilation operators is structured
such that the pairs are nested inside of eachother,
not adjacent to eachother.
However, by the antisymmetry of the matrix elements,
the matrix element for one pairing determines it
for all other pairings of the same creation and annihilation operators.
Two-body operators have the properties
\begin{align}
  \braket{0 | \twobodyop{O} | 0} & = 0\,,\\
  \braket{p | \twobodyop{O} | q} & = 0\,,
\end{align}
and they do not contribute to processes where incoming and outgoing states
differ in more than two single-particle states.
A typical example of a two-body operator is any pairwise interaction,
such as the Coulomb interaction or NN nuclear forces.

Three-body operators are of the form
\begin{equation}\label{eq:threebody_op_definition}
  \threebodyop{O} = \frac{1}{{(3!)}^2} \sum_{pqrstu} \threebodyop{O}_{pqrstu} \crea{p} \crea{q} \crea{r} \annih{u} \annih{t} \annih{s}\,.
\end{equation}
Here, $\threebodyop{O}_{pqrstu}$ are also antisymmetrized matrix elements, with the property
\begin{equation}
  \threebodyop{O}_{pqrstu} = {(-1)}^{\sigma_1}{(-1)}^{\sigma_2}\threebodyop{O}_{\sigma_1(pqr)\sigma_2(stu)}\,,
\end{equation}
where $\sigma_1$ and $\sigma_2$ are permutations
and the ${(-1)}^{\sigma}$ prefactors account for the signs of the permutations.
Three-body operators have the properties
\begin{align}
  \braket{0 | \threebodyop{O} | 0} & = 0\,,\\
  \braket{p | \threebodyop{O} | q} & = 0\,, \\
  \braket{p q| \threebodyop{O} |r s} & = 0\,,
\end{align}
and they do not contribute to processes where incoming and outgoing states
differ in more than three single-particle states.
Examples of three-body operators are 3N nuclear forces.
These definitions can be generalized to get the general representation of any $A$-body operator,
and the properties follow analogously.

\section{Normal ordering}

A product of creation and annihilation operators is in normal order
if all creation operators appear to the left of all annihilation operators.
The normal ordering operation on $c A$,
where c is a scalar coefficient and $A$ is a product of creation and annihilation operators,
can be written as
\begin{equation}
  \nogen{c A} = {(-1)}^{\sigma} c \sigma(A)\,
\end{equation}
where $\sigma$ is a permutation that rearranges the product $A$ into normal order.
This rearrangement is not unique,
but, since each change in the permutation is accompanied by a change in the exchange prefactor,
all normal-ordered products resulting from different permutations used in normal ordering
are equivalent.
Also, note that in general $\nogen{A} \neq A$,
since anti-commuting creation and annihilation operators past eachother
will leave a residual $\delta_{pq}$ from their anti-commutation relation.

\subsection{General properties}\label{sec:normal_ordering_properties}

Suppose the product of creation and annihilation operators $A$
contains $p$ creation operators and $q$ annihilation operators.
Then, unless $p$ and $q$ are both 0,
$\nogen{A}$ has a vacuum expectation value of 0.
Additionally, $\nogen{A}$ does not contribute to processes
where the incoming state has less than $q$ particles
or the outgoing state has less than $p$ particles.

We are now interested in considering products of normal-ordered products
of creation and annihilation operators.
Ultimately, we will use Wick's theorem to systematically evaluate these products~\cite{Wick50wickthm}.
To introduce the theorem, we first need to introduce the notion of a Wick contraction,
which for adjacent operators $\alpha$ and $\beta$ is defined as
\begin{equation}
  \acontraction{}{\alpha}{}{\beta}
  \alpha \beta = \alpha \beta - \nogen{\alpha \beta}\,.
\end{equation}
The value of the contraction is the vacuum expectation value of $\alpha \beta$.
Note that for two operators that are already in normal order their contraction vanishes.
This provides an alternative definition of normal ordering,
namely a product of two operators is in normal order
if its vacuum expectation value is 0
and so its contraction vanishes.
This leads to an extension of normal ordering
that works for many different vacuum choices,
including multi-reference vacuums
which we don't consider any further in this work~\cite{Kutz97mrno}.

We are now equipped to use Wick's theorem
to rewrite a general product of creation and annihilation operators
in terms of sums of normal-ordered products and contractions:
\begin{equation}\label{eq:wicks_theorem}
  \begin{split}
    ABCDEF\ldots =& \nogen{ABCDEF\ldots} \\
    & + \acontraction{}{A}{}{B} AB \,\nogen{CDEF\ldots} - \acontraction{}{A}{}{C} AC \,\nogen{BDEF\ldots} + \text{singles}\\
    &+ \left(\acontraction{}{A}{}{B} AB \acontraction{}{C}{}{D} CD
    - \acontraction{}{A}{}{C} AC \acontraction{}{B}{}{D} BD
    + \acontraction{}{A}{}{D} AD \acontraction{}{B}{}{C} BC\right) \, \nogen{EF\ldots} + \text{doubles} \\
    &+ \cdots + \text{full contractions}\,.
  \end{split}
\end{equation}
The minus signs arise due to the fact that in order to simplify the contraction
and pull it out of the normal-ordered product,
we must anti-commute the contracted operators such that they are adjacent.

The generalized Wick's theorem states that
for a product of two normal-ordered products of creation and annihilation operators,
$A=\nogen{A_1 A_2 \ldots A_N}$ and $B=\nogen{B_1 B_2 \ldots B_M}$,
the resulting expression in terms of normal-ordered products
is the sum of all normal-ordered terms with 0 to $\text{min}(N, M)$ contractions
between the operators in $A$ and $B$, that is,
\begin{equation}\label{eq:gen_wicks_theorem}
  \begin{split}
    \nogen{A_1 A_2 \ldots A_N} \nogen{B_1 B_2 \ldots B_M} = &
    \nogen{A_1 A_2 \ldots A_N B_1 B_2 \ldots B_M} \\
    & + {(-1)}^{N-1} \acontraction{}{A_1}{}{B_1} A_1 B_1 \nogen{A_2 \ldots A_N B_2 \ldots B_M} \\
    & + {(-1)}^{N-2} \acontraction{}{A_2}{}{B_1} A_2 B_1 \nogen{A_1 \ldots A_N B_2 \ldots B_M} \\
    & + {(-1)}^{N} \acontraction{}{A_1}{}{B_2} A_1 B_2 \nogen{A_2 \ldots A_N B_1 \ldots B_M} \\
    & + {(-1)}^{N-1} \acontraction{}{A_2}{}{B_2} A_2 B_2 \nogen{A_1 \ldots A_N B_1 \ldots B_M} \\
    & + \text{singles} + \text{doubles} + \cdots\,.
  \end{split}
\end{equation}
Despite the name, this is a special case of Eq.~\ref{eq:wicks_theorem}.

\subsection{Vacuum normal ordering}

In Section~\ref{sec:normal_ordering_properties},
we discussed the properties of normal ordering in general,
and while we referenced ``the vacuum'' several times
(for example, in the context of vacuum expectation values),
we never specified the specific vacuum involved.
Indeed, normal ordering is dependent on the vacuum with respect to which it is done,
and there are multiple options for this vacuum.
In the following, we focus on normal ordering
with respect to the \textit{physical} vacuum $\ket{0}$,
that is, the state with no particles present.

The fermion creation and annihilation operators \crea{p} and \annih{p}
are the \textit{physical} creation and annihilation operators,
so normal ordering with respect to the physical vacuum,
which we denote by \novac{\ldots},
produces products with all creation operators to the left of annihilation operators.
Concretely, one can consider adjacent Wick contractions,
which should be 0 for pairs of operators already in normal order.
Applying the definition that a contraction of two adjacent operators
is the vacuum expectation value of the operator product,
we find
\begin{equation}
  \bcontraction{}{\annih{p}}{}{\crea{q}} \annih{p}\crea{q} = \braket{0|\annih{p} \crea{q} | 0} = \delta_{pq}\,,
\end{equation}
where we use the contraction \textit{below}
to indicate that we are normal ordering with respect to the physical vacuum.
Similarly, we find
\begin{align}
  \bcontraction{}{\annih{p}}{}{\annih{q}} \annih{p}\annih{q} &= 0\,, \\
  \bcontraction{}{\crea{p}}{}{\crea{q}} \crea{p}\crea{q} &= 0\,, \\
  \bcontraction{}{\crea{p}}{}{\annih{q}} \crea{p}\annih{q} &= 0\,,
\end{align}
indicating that these products are already in normal order, as expected.

As a brief aside,
the definitions for the second-quantized form of one-, two-, and three-body operators
in Eqs.~\ref{eq:onebody_op_definition},~\ref{eq:twobody_op_definition}, and~\ref{eq:threebody_op_definition}
are clearly already in normal order with respect to the physical vacuum.
This is no longer the case when we normal order with respect to some other vacuum.

\subsection{In-medium normal ordering}

One alternative is normal ordering with respect to an $A$-body reference state,
also called the Fermi vacuum,
given by
\begin{equation}\label{eq:ref_state_defintion}
  \refgnd = \prod_{i=1}^A \crea{p_i} \ket{0}\,.
\end{equation}
The frequently used occupation numbers for single-particle states in the reference state $n_p$
are then
\begin{equation}
  n_p =
  \begin{cases}
    1 & p \in \{p_i\}\,, \\
    0 & p \not\in \{p_i\}\,.
  \end{cases}
\end{equation}
When calculating operator matrix elements for an $A$-body system,
every bra or ket state comes with $A$ annihilation or creation operators
along with the physical vacuum.
A more practical, but equivalent way to go about this is constructing
$A$-body states from the reference state \refgnd,
annihilating states occupied in the reference state but unoccupied in the state of interest
and creating in their place particles occupied in the state of interest.
As an example, an $A$-body state that differs from the reference state
by one single-particle state is given by
\begin{equation}
  \crea{a} \annih{i} \refgnd \equiv \refhp{i}{a}\,.
\end{equation}

One thing to note is that with respect to the reference state,
the fermion creation and annihilation operators no longer have certain useful properties.
For example, the annihilation operator no longer always annihilates the Fermi vacuum,
and the creation operator in some cases \textit{does} annihilate the Fermi vacuum.
However, one can define quasiparticle creation and annihiliation operators
that recover these properties with respect to the reference state,
with the annihilation operator given by
\begin{equation}
  \qpannih{p} =
  \begin{cases}
    \annih{p} & \text{if $p$ is unoccupied in the reference state,} \\
    \crea{p} & \text{if $p$ is occupied in the reference state,}
  \end{cases}
\end{equation}
and the creation operator being related by conjugation.

These quasiparticle field operators obey all the typical anti-commutation relations
and have the usual properties, just with respect to the reference state:
\begin{align}
  \anticomm{\qpannih{p}}{\qpcrea{q}} &= \delta_{pq}\,,\\
  \anticomm{\qpannih{p}}{\qpannih{q}} & = 0 \,, \\
  \anticomm{\qpcrea{q}}{\qpcrea{q}} &= 0\,, \\
  \qpannih{p} \refgnd &= 0\,, \\
  \qpcrea{p} \refgnd & \neq 0\,.
\end{align}
The quasiparticle creation operator $\qpcrea{p}$
annihilates a particle in the reference state if the state $p$ is occupied,
producing a so-called \text{hole} state.
But when $p$ is unoccupied in the reference state,
$\qpcrea{p}$ creates a particle.
This gives this formalism its name, the particle-hole formalism.

In this thesis so far,
we have used indices $p$, $q$, $r$, \ldots\ to indicate that
the indices run over all single-particle states.
Here we introduce the convention that the indices $i$, $j$, $k$, \ldots\
only run over hole states, that is, states that are occupied in the reference state,
and the indices $a$, $b$, $c$, \ldots\ only run over particle states,
that is, states that are unoccupied in the reference state.

We are now interested in normal ordering with respect to our reference state,
which we denote by \noref{\ldots} and with contractions above the operators.
This can be accomplished via Wick's theorem (see Eq.~\ref{eq:wicks_theorem}).
We only need to know the values of different Wick contractions.
For our quasiparticle field operators, we find
\begin{align}
  \acontraction{}{\qpannih{p}}{}{\qpcrea{q}} \qpannih{p}\qpcrea{q} & =  \delta_{pq}\,, \\
  \acontraction{}{\qpannih{p}}{}{\qpannih{q}} \qpannih{p}\qpannih{q} &= 0\,, \\
  \acontraction{}{\qpcrea{p}}{}{\qpcrea{q}} \qpcrea{p}\qpcrea{q} &= 0\,, \\
  \acontraction{}{\qpcrea{p}}{}{\qpannih{q}} \qpcrea{p}\qpannih{q} &= 0\,,
\end{align}
exactly the same as for the physical field operators
when normal ordering with respect to the physical vacuum.

The case of physical field operators is more relevant to us,
since our operators are given in terms of physical creation and annihilation operators.
For the physical field operators, we find
\begin{align}
  \acontraction{}{\annih{p}}{}{\crea{q}} \annih{p}\crea{q} & = (1 - n_p) \delta_{pq}\,, \\
  \acontraction{}{\annih{p}}{}{\annih{q}} \annih{p}\annih{q} &= 0\,, \\
  \acontraction{}{\crea{p}}{}{\crea{q}} \crea{p}\crea{q} &= 0\,, \\
  \acontraction{}{\crea{p}}{}{\annih{q}} \crea{p}\annih{q} &= n_p \delta_{pq}\,.
\end{align}

Assuming we have a Hamiltonian with one-, two-, and three-body operators,
\begin{equation}\label{eq:standard_threebody_free_hamiltonian}
  H = \onebodyop{H} + \twobodyop{H} + \threebodyop{H}\,,
\end{equation}
we can normal order it with respect to our reference state
by making use of Eq.~\ref{eq:wicks_theorem} and the contractions above.
Doing this yields the following expression for our normal-ordered Hamiltonian:
\begin{align}
  \hnozero &= \sum_i \onebodyop{H}_{ii} + \frac{1}{2}\sum_{ij} \twobodyop{H}_{ijij} + \frac{1}{6} \sum_{ijk} \threebodyop{H}_{ijkijk}\,, \\
  \hnoone_{pq} &= \onebodyop{H}_{pq} + \sum_i \twobodyop{H}_{piqi} + \frac{1}{2} \sum_{ij} \threebodyop{H}_{pijqij} \,, \\
  \hnotwo_{pqrs} &= \twobodyop{H}_{pqrs} + \sum_i \threebodyop{H}_{pqirsi} \,,  \\
  \hnothree_{pqrstu} &= \threebodyop{H}_{pqrstu} \,.
\end{align}
With this we have normal ordered our Hamiltonian with respect to our reference state,
obtaining our normal-ordered Hamiltonian.
Additionally, we can bring any products of normal-ordered operators to a normal-ordered form
by applying the generalized Wick's theorem.

At this point, a few comments are in order about the choice of our reference state \refgnd.
The choice of reference state corresponds to a partitioning of our Hamiltonian
into a part that is exactly solved by the reference state
and a part that contributes corrections to this zeroth-order solution,
schematically
\begin{equation}
  H = H_0 + H_1\,,
\end{equation}
as in perturbation theory.
A reasonable choice for the reference state corresponds to a choice
that solves a problem ``approximately'' like the problem of interest,
for example a spherical harmonic oscillator for spherical bound systems.
The normal-ordered zero-body part of the Hamiltonian \hnozero{}
is the expectation value of the ground-state energy as a result of the partitioning.
\hnoone, \hnotwo, and \hnothree{} do not contribute to this expectation value by construction.
To improve the approximation of the physical ground state,
one can:
\begin{enumerate}
  \item improve the reference state, as is discussed in Section~\ref{sec:hartree_fock},
  \item and/or include corrections to the ground-state wave function,
    for example admixtures of one-particle one-hole excited states \refhp{i}{a},
    as is discussed in Section~\ref{sec:mbpt}.
\end{enumerate}

\section{The Hartree-Fock method}\label{sec:hartree_fock}

The variational principle states that the true ground state $\ket{\psi}$
globally minimizes the energy functional
\begin{equation}
  E[\ket{\psi}] = \frac{\braket{\psi | H | \psi}}{\braket{\psi|\psi}}\,.
\end{equation}
However, the ground state will in general not be describable by a single Slater determinant,
meaning that cannot hope to get the exact ground-state energy
by normal ordering our Hamiltonian with respect to some optimized reference state.
Still, one can optimize the reference state
within a space restricted to Slater determinants
to get the best possible single Slater determinant approximation to the ground state.

This is the core idea behind the Hartree-Fock method~\cite{Slat28hf,Fock30hf,Hart28hf}.
Working from a known single-particle basis $\ket{p}$,
one wants to find a new single-particle basis $\ket{p'}$
such that our reference state
\begin{equation}
  \refgnd = \ket{p_{1}^{\prime} \ldots p_{A}^{\prime}}
\end{equation}
has the minimal energy expectation value, or Hartree-Fock energy,
\begin{equation}
  \braket{\Phi | H | \Phi} = \hnozero\,.
\end{equation}
Rewriting the optimized basis in terms of our original basis,
\begin{equation}
  \ket{p'} = \sum_{p'p}C_{p'p} \ket{p}\,,
\end{equation}
where $C$ is a unitary matrix giving the basis transformation,
we can expand the Hartree-Fock energy
using our Hamiltonian from Eq.~\ref{eq:standard_threebody_free_hamiltonian} as
\begin{equation}
  \hnozero = \sum_{i'} \onebodyop{H}_{i'i'} + \frac{1}{2}\sum_{i'j'} \twobodyop{H}_{i'j'i'j'}
  + \frac{1}{6}\sum_{i'j'k'} \threebodyop{H}_{i'j'k'i'j'k'}\,,
\end{equation}
where these matrix elements can be connected back to those in our known single-particle basis,
\begin{align}
  \onebodyop{H}_{i'i'} &= \sum_{pq} C_{pi'}^{*} \onebodyop{H}_{pq} C_{q i'}\,,\\
  \twobodyop{H}_{i'j'i'j'} &= \sum_{pqrs} C_{pi'}^{*}C_{qj'}^{*} \twobodyop{H}_{pqrs} C_{r i'}C_{s j'}\,,\\
  \threebodyop{H}_{i'j'k'i'j'k'} &= \sum_{pqrstu} C_{pi'}^{*}C_{qj'}^{*}C_{rk'}^{*} \threebodyop{H}_{pqrstu} C_{s i'}C_{t j'}C_{u k'}\,.
\end{align}
The minimization of $\hnozero$ gives the Hartree-Fock equations,
\begin{equation}
  \sum_{q} F_{pq} C_{qr} = C_{pr} e_{r}\,,
\end{equation}
where $F_{pq}$ is the Fock matrix given by
\begin{equation}\label{eq:fock_matrix_pre}
  F_{pq} = \onebodyop{H}_{pq} + \sum_{rsj'} C_{rj'}^{*} \twobodyop{H}_{prqs} C_{s j'} + \frac{1}{2}\sum_{rstu j'k'} C_{rj'}^{*}C_{sk'}^{*} \threebodyop{H}_{prsqtu} C_{t j'}C_{u k'}\,,
\end{equation}
and $e_i$ are Lagrange multipliers
ensuring orthonormality of the new single-particle basis.
Using that
\begin{equation}\label{eq:hf_density_update}
  \sum C_{p, i'}^{*} C_{q, i'} = \rho_{pq}\,,
\end{equation}
the one-body density in the known single-particle basis,
we can simplify Eq.~\ref{eq:fock_matrix_pre} to
\begin{equation}\label{eq:fock_matrix}
  F_{pq} = \onebodyop{H}_{pq} + \sum_{rs} \rho_{rs} \twobodyop{H}_{prqs} + \frac{1}{2}\sum_{rstu}\rho_{rt} \rho_{su} \threebodyop{H}_{prsqtu}\,.
\end{equation}

These equations are solved self-consistently,
where in each iteration $k$:
the density $\rho^{(k-1)}$ of the previous iteration
is used to construct the new Fock matrix $F^{(k)}$,
$F^{(k)}$ is diagonalized,
a new $C^{(k)}$ is constructed from the eigenvectors of $F^{(k)}$,
and the density $\rho^{(k)}$ is constructed via Eq.~\ref{eq:hf_density_update}.
To start, we choose $\rho^{(0)}_{pq} = n_p \delta_{pq}$.
The iteration terminates when between iterations
the $e_{i}^{(k)}$ change by less than some threshold.
At this point, we can transform all operators to our new optimized single-particle basis
by applying $C$ appropriately.
After this transformation $\hnoone$ is diagonal with diagonal matrix elements $e_i$,
the single-particle energies.

\section{Many-body perturbation theory}\label{sec:mbpt}

Many-body perturbation theory (MBPT) has its formal roots in formal perturbation theory,
which abstractly gives the perturbation theory formalism.
MBPT then specifies certain details about the system
and the starting point for perturbation theory
and translates the formalism into concrete formulas
for order-by-order corrections to the wave function and the energy of a state.
In this section we give the key results from formal perturbation theory,
discuss the setup for MBPT,
and give the formulas for second- and third-order MBPT corrections to the energy.
We refer the interested reader to Refs.~\cite{Shav09mbpt_cc_book,Tich20mbptreview}
for a more comprehensive treatment.

To start, one partitions the Hamiltonian
\begin{equation}
  H = H_0 + H_1\,,
\end{equation}
into $H_0$,
for which the solution to the Schr\"{o}dinger equation is known exactly
with solutions $\ket{\Phi_k}$ and corresponding energies $E^{(0)}_{k}$,
and a perturbation $H_1$.
One is interested in an expansion of the true eigenstate $\ket{\Psi_k}$
in terms of the unperturbed solutions $\ket{\Phi_k}$.
We concentrate our discusion here on an expansion for the ground state,
so the ground state of $H$ is denoted $\ket{\Psi}$
and the ground state of $H_0$,
the starting point of the expansion,
is denoted $\refgnd$ with an unperturbed energy $E^{(0)}$.

The partitioning comes with the definition of the projection operators
\begin{align}
  P &= \ket{\Phi}\bra{\Phi}\,, \\
  Q &= \sum_{k\neq 0}\ket{\Phi_k}\bra{\Phi_k}\,.
\end{align}
Working with the so-called intermediate normalization
\begin{equation}
  \braket{\Psi|\Phi} = 1\,,
\end{equation}
one can write the ground state of $H$ as
\begin{align}
  \ket{\Psi} &= (P + Q)\ket{\Psi} \\
  &= \refgnd + \ket{\chi}\,,
\end{align}
where $\ket{\chi} = Q \ket{\Psi}$ is what needs to be solved for.

The result of formal perturbation theory is that
using the Rayleigh-Schr\"{o}dinger resolvent
\begin{equation}
  R = \sum_{k\neq 0} \frac{\ket{\Phi_k}\bra{\Phi_k}}{E^{(0)} - E^{(0)}_{k}} \,
\end{equation}
the correction to the unperturbed ground state is given by
\begin{equation}
  \ket{\chi} = \sum_{n=1}^{\infty}{(R H_1)}^n \refgnd_c\,,
\end{equation}
where the `$c$' subscript indicates that the expansion is connected,
which ensures its size extensivity,
that is, that calculated observables scale linearly with the size of the system.
The corrections to the energy beyond the standard first-order energy correction
\begin{equation}
  E^{(1)} = \braket{\Phi | H_1 | \Phi}\,,
\end{equation}
are given by
\begin{align}
  \Delta E &= \braket{\Phi | H_1 | \chi} \\
          &= \bra{\Phi}  H_1 \sum_{n=1}^{\infty}{(R H_1)}^n \refgnd_c\,.
\end{align}
As an example, the second-order correction to the energy is
\begin{equation}
  E^{(2)} = \sum_{k\neq 0} \frac{\braket{\Phi | H_1 | \Phi_k}\braket{\Phi_k | H_1 | \Phi}}
  {E^{(0)} - E^{(0)}_k}\,.
\end{equation}
This makes it clear that the corrections to the ground state involve
the perturbation $H_1$ connecting the unperturbed ground state in the $P$-space
to excited states in the $Q$-space before connecting these back to the ground state.

Transitioning to (single-reference) many-body perturbation theory,
we define our $A$-body Hilbert space as comprising our reference state
and $n$-particle $n$-hole excitations of the reference state:
\begin{equation}
  \{\refgnd, \refhp{i}{a}, \refhp{ij}{ab}, \refhp{ijk}{abc}, \ldots \}\,.
\end{equation}
After normal ordering with respect to $\refgnd$,
we have our normal-ordered zero- through three-body operators,
$\hnozero$, $\hnoone$, $\hnotwo$, and $\hnothree$.
This choice of basis corresponds to the following partitioning:
our unperturbed Hamiltonian is
\begin{align}
  H_0 &= \hnozero + \text{diag}(\hnoone) \\
      &= \hnozero + \sum_{p} e_p \noref{\crea{p} \annih{p}}\,,
\end{align}
where $e_p = \hnoone_{pp}$ are the single-particle energies.
The energy of the reference state is given by $\hnozero$.
The energy of an $n$-particle $n$-hole excited state $\refhp{ij\cdots}{ab\cdots}$ is given by
\begin{equation}
  \hnozero + \epsilon_{ij\cdots}^{ab\cdots}
\end{equation}
with
\begin{equation}\label{eq:mp_energy_denom}
  \epsilon_{ij\cdots}^{ab\cdots} = (e_a + e_b + \cdots) - (e_i + e_j + \cdots)\,.
\end{equation}
The perturbation is then
\begin{equation}
  H_1 = \hnoone - \text{diag}(\hnoone) + \hnotwo + \hnothree\,.
\end{equation}
Finally, the many-body resolvent is
\begin{equation}\label{eq:mbpt_resolvent}
  R = -\sum_{ai} \frac{\refhp{i}{a}\bra{\Phi_{i}^{a}}}{\epsilon_{i}^{a}}
      -\frac{1}{{(2!)}^2} \sum_{abij}\frac{\refhp{ij}{ab}\bra{\Phi_{ij}^{ab}}}{\epsilon_{ij}^{ab}}
      -\frac{1}{{(3!)}^2} \sum_{abcijk}\frac{\refhp{ijk}{abc}\bra{\Phi_{ijk}^{abc}}}{\epsilon_{ijk}^{abc}}
      + \ldots \,.
\end{equation}

We are now in a position to discuss the second- and third-order contributions to the ground-state energy.
Using Eq.~\ref{eq:mbpt_resolvent} and the properties of normal-ordered operators,
the second-order correction to the ground-state energy is given by
\begin{equation}
    E^{(2)} = -\sum_{ai} \frac{\hnoone_{ai}\hnoone_{ia}}{\epsilon_{i}^{a}}
      -\frac{1}{{(2!)}^2} \sum_{abij}\frac{\hnotwo_{abij}\hnotwo_{ijab}}{\epsilon_{ij}^{ab}}
      -\frac{1}{{(3!)}^2} \sum_{abcijk}\frac{\hnothree_{abcijk}\hnothree_{ijkabc}}{\epsilon_{ijk}^{abc}}\,.
\end{equation}
The first term in this equation is related to a so-called non-canonical diagram
that vanishes if we choose the Hartree-Fock (HF) reference state to be our determinant.
This is because, as mentioned previously, $\hnoone$ is by definition diagonal in the HF basis.

\begin{figure}[t!]
  \centering
  \includegraphics[width=0.8\textwidth]{proposal/doc/images/external/ho_vs_hf_mbpt.pdf}
  \caption[
    The partial sums (left) and order-by-order contributions (right)
    for an MBPT calculation of the ground-state energy of ${}^{16}\text{O}$
    using a harmonic-oscillator reference state (top)
    and a Hartree-Fock reference state (bottom).
    The red, blue, and yellow points are for $N_{\text{max}}=2$, 4, and 6,
    the basis truncation parameter for the approach used.
  ]{
    The partial sums (left) and order-by-order contributions (right)
    for an MBPT calculation of the ground-state energy of ${}^{16}\text{O}$
    using a harmonic-oscillator reference state (top)
    and a Hartree-Fock reference state (bottom).
    The red, blue, and yellow points are for $N_{\text{max}}=2$, 4, and 6,
    the basis truncation parameter for the approach used.
    Figure taken from Ref.~\cite{Tich16hohfmbpt}.
  }\label{fig:ho_vs_hf_mbpt}
\end{figure}

At the third order, even considering only canonical diagrams,
the number of diagrams possible with two- and three-body operators grows to 17.
The complete list of these diagrams can be found in Ref.~\cite{Hu18mbptthreebody}.
The canonical contributions involving only the normal-ordered two-body Hamiltonian are
\begin{equation}
  \begin{split}
  E^{(3)}_{\text{2-body only}} =
    &\frac{1}{8} \sum_{abcdij} \frac{\hnotwo_{ijab} \hnotwo_{abcd}\hnotwo_{cdij}}{\epsilon_{ij}^{ab}\epsilon_{ij}^{cd}} \\
    &+ \frac{1}{8} \sum_{abijkl} \frac{\hnotwo_{ijab} \hnotwo_{abkl}\hnotwo_{klij}}{\epsilon_{ij}^{ab}\epsilon_{kl}^{ab}} \\
    &- \sum_{abcijk} \frac{\hnotwo_{ijab} \hnotwo_{kbic}\hnotwo_{ackj}}{\epsilon_{ij}^{ab}\epsilon_{kj}^{ac}}\,.
  \end{split}
\end{equation}
The complete set of non-canonical third-order contributions
with only one- and two-body operators
is given, among other places, in Ref.~\cite{Tich17phd}.

The inclusion of additional terms is not the only challenge when dealing with a non-canonical reference state.
Choosing a different reference state than the HF determinant
corresponds to choosing a worse partitioning for $H$,
that is, more information is held in the perturbation $H_1$,
as the the HF determinant is the best possible single Slater determinant approximation
to the ground state.
This less optimal choice can lead to poor convergence behavior of MBPT~\cite{Tich16hohfmbpt}.
For instance, in Fig.~\ref{fig:ho_vs_hf_mbpt}
the ground-state energy of ${}^{16}\text{O}$ was calculated
using a harmonic-oscillator determinant and a Hartree-Fock determinant
for the reference state.
While for the HF reference state MBPT converges nicely,
for the HO reference state the calculation rapidly begins to diverge
when going to higher orders in perturbation theory.
Additionally,
while MBPT benefits strongly from working with SRG-evolved Hamiltonians,
it can have difficulty converging even when using an HF reference state
for bare nuclear Hamiltonians that are too ``hard''~\cite{Tich20mbptreview}.

\section{Non-perturbative techniques}

The convergence challenges of MBPT motivate us to consider non-perturbative many-body methods,
which sum to all orders certain types of diagrams to produce a convergent result.
Coupled cluster theory and the in-medium similarity renormalization group
are two examples of such methods.
Their non-perturbative nature makes them less sensitive to the choice of reference state
(although convergence speed will be affected by a non-canonical choice of reference state)
and better able to deal with ``harder'' nuclear Hamiltonians.
We discuss the IM-SRG in detail in the next chapter.
Here, we aim to briefly introduce the coupled cluster many-body approach
as it shares many similarities with the IM-SRG.\@

The ansatz for the coupled cluster (CC) approach is describing the ground state as
\begin{equation}
  \ket{\Psi} = \exp(T)\ket{\Phi}\,,
\end{equation}
where $T$ is the cluster operator,
which when applied exponentially to the reference state $\refgnd$ yields the ground state~\cite{Hage13ccreview}.
$T$ contains in general one- through $A$-body operators,
\begin{equation}
  T = \onebodyop{T} + \twobodyop{T} + \cdots + \abodyop{T}\,,
\end{equation}
which generate particle-hole excitations of the reference state.

The ground-state energy is then given by
\begin{align}
  E &= \braket{\Psi | H | \Psi} \\
  &= \braket{\Phi | \exp(-T) (\hnoone + \hnotwo + \hnothree) \exp(T) | \Phi} + \hnozero \\
  &\equiv \braket{\Phi | \overline{H} | \Phi} + \hnozero\,,
\end{align}
where we have defined the similarity-transformed Hamiltonian $\overline{H}$.
The task is to solve for matrix elements of the different $A$-body parts of $T$
such that
\begin{equation}
  0 = \braket{\Phi_{ijk\ldots}^{abc\ldots} | \overline{H} | \Phi}\,
\end{equation}
for all $n$-particle $n$-hole excited states of the reference state.
These are the coupled cluster equations.

One computes $\overline{H}$ via the Baker-Campbell-Hausdorff expansion,
\begin{equation}
  \overline{H} = H_N + \comm{H_N}{T} + \frac{1}{2!} \comm{\comm{H_N}{T}}{T} + \ldots \,,
\end{equation}
where $H_N=\hnoone + \hnotwo + \hnothree$.
This commutator expansion ensures that only connected diagrams in the MBPT expansion are generated,
ensuring the size-extensivity of the method.
A standard approach in nuclear physics is to truncate $T$, $H_N$, and the commutator
at the two-body level,
giving two coupled cluster equations
\begin{align}
  0 &= \braket{\Phi_{i}^{a} | \overline{H} | \Phi}\,,\\
  0 &= \braket{\Phi_{ij}^{ab} | \overline{H} | \Phi}\,,
\end{align}
known as CCSD (SD for singles and doubles).
Another variant approximately treats the so-called triples and is denoted CCSD(T).\@
In the next chapter, when discussing the IM-SRG,
the many similarities of the methods will be quite obvious.


\documentclass[ee577b,acmnow]{acmtrans2m}

\usepackage{graphicx}
%\usepackage[margin=1.0in,vmargin={30pt,2cm},nohead]{geometry}
%\usepackage{amsmath, amsthm,  amsfonts, amscd}
\usepackage{url}
%\usepackage{cite}
%\usepackage{fancyhdr}

%\acmVolume{1}
%\acmNumber{1}
\acmYear{07}
\acmMonth{October 10,}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}
\newdef{definition}[theorem]{Definition}
\newdef{remark}[theorem]{Remark}

\markboth{EE 577B Fall 2007: Extra Credit Homework \#1}
{EE 577B Fall 2007: Extra Credit Homework \#1}

\title{EE 577B Fall 2007: Extra Credit Homework \#1}

\author{Zhiyang Ong\\
Ming Hsieh Department of Electrical Engineering,\\
Viterbi School of Engineering,\\
University of Southern California
}

\begin{abstract}
Synthesizable behavorial RTL models for the encoder and decoder
of the (15,11,3) Hamming code were developed in Verilog. They
were synthesized into Verilog netlists, and simulation-based
verification were used to check the behavioral models and the
synthesized Verilog netlists.
\end{abstract}

\category{VLSI}{Digital IC Design}{Communication Electronics}

\terms{Error Correction and Detection, Logic Synthesis, Functional
Verification}

\keywords{Error-Correcting Code, Parity-Check Matrix, Generator Matrix,
Decoder,Encoder}

\begin{document}
\setcounter{page}{1}

\maketitle

\section{Introduction}

The encoder and decoder of the (15,11,3) Hamming code \cite{Weste05} were
developed in Verilog, using synthesizable behavorial RTL models.
They were verified using circuit simulation. Subsequently,
logic synthesis was performed on these models of the encoder
and the decoder. The resultant synthesized Verilog netlists
were verified via simulation again.

Section 1 describes the generation of the generator and parity-check
matrices used for creating the encoder and the error-correcting decoder.
Next, Section 2 indicates the implementation of the encoder and decoder as
synthesizable behavorial RTL models in Verilog. Subseuqently, Section 4
describes how they fit into a pipelined communications channel, which
is simulated. Following that is Section 5 which describes the results
from performing logic synthesis on the behavioral models, and Section
6 which describes how the simulation waveforms differ in the synthesized
Verilog netlists from the behavioral models. Finally, Section 7 draws
conclusion on this brief report.

\section{Generator matrix G and Parity Check Matrix H}

In Table \ref{bitscbp}, the relationship between data bits, $B_{i}$, and parity bits, $P_{i}$, with the encoded data bits, $C_{i}$ is given. This is used to form the relationships between data bits, $B_{i}$, and parity bits, $P_{i}$, as indicated below.\\
\ \\
P1 = B1 + B2 + B4 + B5 + B7 + B9 + B11\\
P2 = B1 + B3 + B4 + B6 + B7 + B10 + B11\\
P3 = B2 + B3 + B4 + B8 + B9 + B10 + B11\\
P4 = B5 + B6 + B7 + B8 + B9 + B10 + B11\\

\begin{table}
\caption{Table representing the relationship between data bits, $B_{i}$, and parity bits, $P_{i}$, with the encoded data bits, $C_{i}$}
\label{bitscbp}
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
C1 & C2 & C3 & C4 & C5 & C6 & C7 & C8 & C9 & C10 & C11 & C12 & C13 & C14 & C15\\
\hline
P1 & P2 & B1 & P3 & B2 & B3 & B4 & P4 & B5 & B6 & B7 & B8 & B9 & B10 & B11\\
\hline
\end{tabular}
\end{table}
\ \\
The parity check matrix H and the generator matrix G for the $m = 4$ Hamming code with $d_{min} = 3$ is given as follows: \\
\ \\
$H = \left [ \begin{array}{ccccccccccccccc}
1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 & 0 & 1 \\
0 & 1 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\
\end{array} \right ] $\\
\ \\
\ \\
\ \\
$G = \left [ \begin{array}{ccccccccccccccc}
1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 1 & 0 & 1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\
1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\
0 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\
1 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{array} \right ] $\\
\ \\
\ \\
\ \\

\section{Implementation of Encoder and Decoder modules in Verilog}
The encoder and decoder modules for encoding and decoding using linear block codes, (15,11,3) Hamming code, are implemented in Verilog, using behavioral RTL design style. The listings for the encoder, single-bit error-correcting decoder, and their testbenches are provided as attachments at the end of this report.

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{preenc}
\caption{Simulation Waveforms for the pre-synthesized Behavioral RTL for the Hamming Encoder.}
\label{preencoder}
\end{center}
\end{figure}

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{predec}
\caption{Simulation Waveforms for the pre-synthesized Behavioral RTL for the Error-Correcting Hamming Decoder.}
\label{predecoder}
\end{center}
\end{figure}

Figure \ref{preencoder} shows the simulation waveforms for the
pre-synthesized behavioral RTL for the Hamming encoder, while
Figure \ref{predecoder} shows the simulation waveforms for the
pre-synthesized behavioral RTL for the error-correcting Hamming
decoder.

\section{Development of the Testbench that Models a Communications Channel}
The testbench for a communications channel with three pipeline stages was developed; see Figure \ref{commch}. The first stage contains the Hamming encoder, while the last stage contains the error-correcting Hamming decoder and a parity-stripper module. The parity-stripper module extracts the parity bits from the encoded data bits, which may be corrupted, transmitted through the communications channel. This results in producing the data bits (qx[10:0]), which may be corrupted, at its output.

The output of the parity-stripper module (qx[10:0]) is compared with that of the error-correcting Hamming decoder (q[10:0]), and the original data bits (rb[10:0]) that has been passed along in the communications channel. The output of the error-correcting Hamming decoder (q[10:0]) should match the original data bits (b[10:0]). If the encoded data bits are corrupted in the communications channel with a single-bit error, the error-correcting Hamming decoder should have detected it, and corrected it. Else, if more than one-bit errors are detected, errors will go uncorrected. Finally, comparing qx[10:0] with q[10:0] and rb[10:0] allows us to determine which data bits are corrupted with errors in the communications channel, and if such errors are corrected.

The second stage consist of a 4-to-16 bit decoder and a 15-bit XOR gate to model. The 4-to-16 bit decoder is used to create a 16-bit random number (err[15:1]) from a 4-bit random number (e[3:0]) that is used to represent the error signal, or noise, that is used to corrupt data bits in the communications channel. The 15-bit XOR gate is used to corrupt the encoded data bits (r\_c[14:0]) with errors (err[15:1]) in the second stage of the communications channel. This models how data can get corrupted during transmission in a communications channel.

\begin{figure}
%\vspace{-2.7cm}
%\centering
%\includegraphics[width=3.5cm,height=3.5cm]{commschannel}
\begin{center}
%\includegraphics[width=7.5cm,height=4.0cm]{commschannel}
\includegraphics[width=12cm]{commschannel}
\caption{Schematic modeling a communications channel.}
\label{commch}
\end{center}
\end{figure}

Figure \ref{predecoder4to16} shows the
simulation waveforms for the behavioral RTL for the 4-to-16 bit
decoder. Lastly, Figure \ref{pref} and Figure \ref{pref1} indicate
the simulation waveforms for the pipelined communications
channel. The former shows all the signals in the three-stage
pipeline, while the latter shows only the input and output signals
of that pipeline. It is noted that the simulation of behavioral
RTL models do not use information pertinent to the interconnect
and device characteristics, and parasitics to capture the delay
through the digital logic. That is, these simulations are
performed on ideal logic components, and cannot capture delays
affecting the logic of the design.

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{predec4to16}
\caption{Simulation Waveforms for the Behavioral RTL for the 4-to-16 bit Decoder.}
\label{predecoder4to16}
\end{center}
\end{figure}

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{prefinal}
\caption{Simulation Waveforms for the Communications Channel.}
\label{pref}
\end{center}
\end{figure}

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{prefinal1}
\caption{Zoomed-in Display of Input and Output Simulation Waveforms for the Communications Channel.}
\label{pref1}
\end{center}
\end{figure}

\section{Logic Synthesis of Hamming Encoder and Decoder}

The area and timing reports from performing logic synthesis on
the Hamming encoder and decoder are found in the attachment. The
total area for the Hamming decoder is 3041 ${\rm units^2}$, while
its delay through its critical path(s) is 2.60 units. Its total
dynamic power consumption is 6.0982 mW, while its cell leakage
power is 6.6074 nW.

Hamming encoder has a total area of 1008 ${\rm units^2}$, while
its delay through its critical path(s) is 0.67 units. Its total
dynamic power consumption is 2.0195 mW, while its cell leakage
power is 2.9028 nW.

\section{Simulation of Synthesized Hamming Encoder and Decoder}

Figure \ref{postencoder} shows the simulation waveforms for the
synthesized Hamming encoder, while Figure \ref{postdecoder} shows
the simulation waveforms for the synthesized error-correcting
Hamming encoder.

The author notes that the simulation of the synthesized Verilog
netlists uses information pertinent to the interconnect
and device characteristics, and parasitics to capture the delay
through the digital logic. These information are provided from
the SDF files, and the technology library used for logic
synthesis. That, these simulations are performed on realistic
logic components, and can capture delays affecting the logic
of the design. For example, the correct values for the encoder
appear after a significant time delay since the encoder and the
decoder has different paths with various delays. Hence, the
values from the input may propagate to the output on certain
paths faster than other paths. Consequently, the output values
are incorrect until the values have propagated from the inputs
to the outputs on the critical path.

\section{Conclusion}

Synthesizable behavorial RTL models for the encoder and decoder
of the (15,11,3) Hamming code were developed in Verilog. They
were verified using circuit simulation. Subsequently, the
encoder and the decoder underwent logic synthesis, and were
verified via simulation again.

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{postenc}
\caption{Simulation Waveforms for the Synthesized Hamming Encoder.}
\label{postencoder}
\end{center}
\end{figure}

\hspace{-2cm}\begin{figure}
\begin{center}
\includegraphics[height=18.5cm]{postdec}
\caption{Simulation Waveforms for the Synthesized Error-Correcting Hamming Decoder.}
\label{postdecoder}
\end{center}
\end{figure}

%This is great \cite{Weste05,Rabaey03,Kang03,Sutherland99}.

%\begin{acks}
%We thank Prof. Rashed Z. Bhatti for teaching us about SRAM design.
% Also, we express gratitude to the following teaching assistants for
% their advice and help: Ehsan Pakbazbia, Jae Chul Cha, Mahta Haghi,
% and Youngki Choe. In addition, we appreciate the graders Hwisung
% Jung and Bhavna Chopra for spending their time to grade our work.
%\end{acks}

\bibliographystyle{acmtrans}
%\bibliography{references.bib}
%\bibliographystyle{plain}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\bibliographystyle{unsrt}
\bibliography{references}
\begin{received}
Submitted November 19, 2007, 1200 hrs
\end{received}
\end{document}


\documentclass[]{article}

\begin{document}
\section{Problem}
An arbitrary electrical system can be described by the following function of the angular frequency $ \omega $ as
\[
    Z(\omega) = R(\omega) + j X(\omega) .
\]
In order that this function satisfy the causal assumption of electromagnetic systems we require that this function be complex-conjugate symmetric in the following way, namely,
\[
    Z^*(\omega) = Z(-\omega)
\]
so that
\[
    R(\omega) - j X(\omega) =  R(-\omega) + j X(-\omega).
\]

\end{document}


%  -----------------------------------------------------------------------------
%  Author         : Bimalka Piyaruwan Thalagala
%  GitHub         : https://github.com/bimalka98
%  Date Created   : 01.09.2020
%  Last Modified  : 13.09.2020
%  -----------------------------------------------------------------------------

\documentclass[a4paper,11pt]{article}%,twocolumn
\input{settings/packages}
\input{settings/page}
\input{settings/macros}
\usepackage[ framed, numbered]{matlab-prettifier}%framed,%
\usepackage{listings}
\usepackage{pythonhighlight}

\begin{document}

\input{content/title_page}
\tableofcontents

\begin{center}
	\textbf{\textit{* PDF is clickable}}
\end{center}

\textit{Note:}\\

\textit{All the executable codes, a simulink model and a voice sample are included in a separate folder named as \textbf{EN2053-Assignment 2-180574K-180631J.rar} which was submitted along with this report.}\\

\textit{Before run the \textbf{VoiceTransmissionBaseband.slx} simulink simulation related to the part 5 of the Task 1 ,(included in a separate folder named as \textbf{Task1-RFPM} inside the above folder) change the directories related to the voice input and output. Voice sample named as \textbf{voice.wav} is also included in the same folder.}\\

\textit{Additionally all the materials related to Task 1 can also be found at \url{https://github.com/bimalka98/RF-Propagation-Model}}

\pagebreak
%%-----------------------------------------------------------------------
\section{Modeling the RF propagation Using Matlab}
%%-----------------------------------------------------------------------
\subsection{Relationship between Free Space Path Loss and Frequency}

\textit{Consider  following meanings for the parameters}\\

\begin{tabular}{l l }
	$P_{RX}$ & = Received Power at the Receiving Antenna\\
	$P_{TX}$ & = Transmitted Power at the Transmitting Antenna\\
	$f$ & = Frequency of the wave in Hz\\
	$f_{GHz}$ & = Frequency of the wave in GHz\\
	$d$& = Distance between the antennas in m\\
	$d_{km}$& = Distance between the antennas in km\\
	$G_{TX}$& = Directive gain of the Transmitter\\
	$G_{RX}$& = Directive gain of the Receiver\\
	$c$& = Velocity of the electromagnetic waves in a vacuum\\

\end{tabular}\\[1cm]

The relationship between above parameters can be given as follows
\[
\begin{split}
P_{RX} & = P_{TX}.\frac{c^2}{(4\pi.f.d)^2}.G_{TX}.G_{RX}
\end{split}
\]
From the above equation, free space path loss, say $L$
\[
\begin{split}
L = \frac{(4\pi.f.d)^2}{c^2}
\end{split}
\]

By considering $\ 10.log_{10}()$ in both sides, Free Space Path Loss in dB, say $L_{dB}$

\[
\begin{split}
10.\log_{10}(L) &= 10.\log_{10}(\frac{(4\pi.f.d)^2}{c^2})\\
L_{dB}& = 10.\log_{10}((4\pi.f.d)^2) - 10.\log_{10}(c^2)\\
&=20.\log_{10}(4\pi.f.d)-20.\log_{10}(c)\\
&=20.\log_{10}(4\pi)-20.\log_{10}(c) + 20.\log_{10}(f) + 20.\log_{10}(d)\\
&=20.\log_{10}(\frac{4\pi}{c}) + 20.\log_{10}(f) + 20.\log_{10}(d)\\
&= -147.5522168 + 20.\log_{10}(f_{GHz}.10^9) + 20.\log_{10}(d_{km}.10^3)\\
& = -147.5522168 + 20.\log_{10}(10^9)+ 20.\log_{10}(f_{GHz}) + 20.\log_{10}(10^3) + 20.\log_{10}(d_{km})\\
&= -147.5522168 + 180+ 20.\log_{10}(f_{GHz}) + 60 + 20.\log_{10}(d_{km})\\
&= -147.5522168 + 240+ 20.\log_{10}(f_{GHz}) + 20.\log_{10}(d_{km})\\
&= +92.44778322+20.\log_{10}(f_{GHz}) + 20.\log_{10}(d_{km})
\end{split}
\]
Since transmitter and receiver are located at distance of 10km apart, by substituting $d_{km}= 10$.\\

Free Space Path Loss in dB, $L_{dB}$ as a function of frequency in Giga Hertz

\[
\begin{split}
L_{dB}(f_{GHz})&=  +112.44778322+20.\log_{10}(f_{GHz})
\end{split}
\]

\textbf{\textit{Note : Axes of the following plots are given in the logarithmic scale and range of frequency was chosen from 50 GHz to 1000 GHz since some of the ITU-R models are only defined in the 10 GHz-1000 GHz range.}}

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/FreeSpacePL.png}
	\caption{Relationship between Free Space Path Loss and Frequency}
\end{figure}

%%-----------------------------------------------------------------------
\pagebreak
\subsection{Rain attenuation, Fog attenuation and Atmospheric gas attenuation with Frequency}

\textit{Note : For the generation of following plots three of the Matlab built-in functions, namely \textbf{rainpl()\cite{matlab}, gaspl()\cite{matlab}, fogpl()\cite{matlab}} which are developed according to the ITU-R P Series recommendations were used and links for their documentations are given at the Reference section.}

\subsubsection{Rain attenuation - Recommendation ITU-R P.838-3, 2005\cite{rain}}
The following plot shows how losses due to rain varies with frequency. The plot assumes the followings in addition to the provided information in the Task 1.\\

\begin{tabular}{l l}
Elevation angle of the propagation path& = 0 \\
Polarization tilt angle of the signal &= 0\\
\end{tabular}\\

In general, horizontal polarization represents the worse case for propagation loss due to rain.

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/RainPL.png}
	\caption{Relationship between Rain attenuation and Frequency}
\end{figure}

\subsubsection{Fog attenuation - Recommendation ITU-R P.840-3, 2013\cite{fog}}
The following plot shows how losses due to fog/cloud varies with frequency. The plot assumes the following provided information in the Task 1.\\

\begin{tabular}{l l}
	Ambient Temperature in Celsius&= 31\\
	Liquid Water Density in $g/m^3$&= 0.5\\
\end{tabular}\\

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/FogPL.png}
	\caption{Relationship between Fog attenuation  and Frequency}
\end{figure}

\subsubsection{Atmospheric gas attenuation - Recommendation ITU-R P.676-10, 2013\cite{gas}}

The plot below shows how the propagation loss due to atmospheric gases varies with the frequency. The plot assumes the followings in addition to the provided information in the Task 1.

\begin{tabular}{l l}
	 Dry air pressure in Pa&= 101325\\
	 Water Vapor Density in $g/m^3$&= 30.4\cite{vapor}\\
\end{tabular}

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/GasPL.png}
	\caption{Relationship between Atmospheric gas attenuation and Frequency}
\end{figure}

%%-----------------------------------------------------------------------
\subsection{Total Path Loss with Frequency}
\textit{Note : Range of frequency was chosen from 50 GHz to 1000 GHz since some of the ITU-R models are only defined in 10 GHz - 1000 GHz range.}
\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/TotalPL.png}
	\caption{Relationship between Total Path Loss and Frequency}
\end{figure}

By inspecting the figure we can conclude that the minimum propagation loss is given at the frequency of 50 GHz in the given range. Therefore from this point onward, for the calculations it will be the frequency for transmission.\\

Minimum Propagation Loss = 214.624 dB\\
Corresponding Frequency = 50 GHz\\

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/AllinOne.png}
	\caption{Relationship between Various Path Losses and Frequency - All in One}
\end{figure}
%\subsection{Link Budget Calculation}
%
%Parameters For the propagation model
%\begin{tabular}{l r}
%Chosen transmission frequency & 10 GHz\\
%Total Path Loss & 136.9 dB\\
%Transmission power & 50 kW or 47 dB\\
%Transmitter Gain & 30 dB\\
%Receiver Gain &24.77 dB\\
%Link margin  &11 dB\\
%Cable loss at Transmitter & 3 dB\\
%Cable loss at Receiver &4 dB\\
%\end{tabular}\\[1cm]
%
%Let's find the actual received power at the receiver\\
%
%\begin{tabular}{|l l| r|}
%	\hline
%Received Power =	&Transmission power & +47 dB\\
%&	Cable loss at Transmitter & -3 dB\\
%&	Transmitter Gain & 30 dB\\
%&	Total Path Loss & -136.9 dB\\
%&	Receiver Gain &+24.77 dB\\
%&	Cable loss at Receiver &-4 dB\\\hline
%Received Power =&&-42.13 dB\\\hline\hline
%\end{tabular}\\[1cm]
%
%
%Therefore,\\
%\begin{center}
%	\begin{tabular}{l c c c}
%Link margin  & =& Received Power& - Receiver Sensitivity\\
%11 dB& = &-42.13 dB& - Receiver Sensitivity\\
%Receiver Sensitivity &= &-53.13 dB& \\\hline\hline
%	\end{tabular}
%\end{center}

\pagebreak
\subsection{Variation of the Signal Power with the Distance}

Parameters For the propagation model\\

\begin{tabular}{l r}
Chosen Carrier frequency & 50 GHz\\
Transmission power & 50 kW or 47 dB\\
Cable loss at Transmitter & 3 dB\\
Transmitter Gain & 30 dB\\
Receiver Gain &24.77 dB\\
Cable loss at Receiver &4 dB\\
Total Path Loss & Varies with Distance\\
\end{tabular}\\[1cm]

According to above values, Let's calculate the Power of the signal when leaving the  Transmission antenna, say $P_{dB}(0~km)$,

\[
\begin{split}
P_{dB}(0~km) & = Transmission~power -  Cable~loss~at~Transmitter + Transmitter~Gain\\
&=47-3+30\\
&=74~dB
\end{split}
\]

Free Space Path Loss in dB, $L_{dB}$ as a function of distance in kilo meters. By substituting $f_{GHz}$ = 50 to the equation derived in part 1.

\[
\begin{split}
L_{dB}(d_{km})&= +92.44778322+20.\log_{10}(50) + 20.\log_{10}(d_{km})\\
&=+92.44778322+ 33.97940009 + 20.\log_{10}(d_{km})\\
&=+126.4271833+ 20.\log_{10}(d_{km})\\
\end{split}
\]

Therefore, \[Total~Path~Loss = L_{dB}(d_{km}) + Rain~Attenuation+Fog~Attenuation+Atmospheric~Gas~Attenuation \]

Therefore the Signal Power when reaching the Receiving Antenna at $d_{km}$ distance,
\[
\begin{split}
P_{dB}(d_{km}) & =74~dB - Total~Path~Loss
\end{split}
\]

\begin{figure}[!h]
	\centering
	\includegraphics[scale=0.35]{figures/sp}
	\caption{Variation of the Signal Power with the Distance}
\end{figure}
\pagebreak

\subsection{Transmitting a voice signal over a noisy channel using the above Transmission frequency and the Propagation model.}
\vspace{5mm}
\subsubsection{Logic and Assumptions Used to implement the Propagation Model}

\begin{figure}[!h]
	\centering
	\includegraphics[scale = 0.36]{figures/voicePL}
	\caption{Variation of the Total Path Loss with the Frequency in modulated Voice Signal}
\end{figure}

By inspecting the above figure, it can be observed that the total Path Loss of the \textbf{Frequency Modulated Voice Signal}, over its frequency range( \textit{from 50e9 - 4e3 to 50e9 + 4e3})Hz changes only by a value less than 0.000025 dB which is almost Zero. Therefore in a real world application it can be assumed that the total path loss of the modulated voice signal is as same as that of the carrier wave(50 GHz) alone. That is, path loss variation due to the frequency variation in the above range can be neglected and can be assumed as a constant of 214.6240 dB which is the total path loss corresponding to the 50 GHz wave. Therefore for the following model, total path loss of the signal was taken as 214.6240 dB and it was included in the \textbf{\textit{Free Space Loss block}} .\\

In addition to that since the attenuation affects only to the amplitude of the signal, actual scenario of the Frequency Modulation of the voice signal was not considered and instead the voice signal was FM modulated using the \textbf{\textit{FM Modulator Baseband block}} which is an ideal option for simulation purposes.
\vspace{2cm}
\subsubsection{RF Propagation Model - Simulink}

Steps of the simulation are as follows:
\begin{enumerate}[1.]
	\item Input the voice.wav file of 8000Hz sampling rate using \textbf{\textit{From Multimedia File block}}.
	\item Normalization of the voice signal using \textbf{\textit{Normalization block}}.
	\item Frequency modulating the signal using \textbf{\textit{FM Modulator Baseband block}}.
	\item Addition of the -3 dB Cable loss at Transmitter using \textbf{\textit{dB Gain block}}.
	\item Addition of the 30 dB transmitter gain using the \textbf{\textit{Transmitter block}}.
	\item Addition of the effect of noise using \textbf{\textit{AWGN channel block}}.
	\item Addition of the -214.6240 dB propagation loss using \textbf{\textit{Free Space Path Loss block}}.
	\item Addition of the 24.77 dB receiver gain using  \textbf{\textit{Receiver Preamp block}}.
	\item Addition of the -4 dB Cable loss at the Receiver using \textbf{\textit{dB Gain block}}.
	\item Demodulating the signal using \textbf{\textit{FM Demodulator Baseband block}}.
	\item Saving the output voice signal using \textbf{\textit{To Multimedia File block}}.
	\item convert the output signal into audio using \textbf{\textit{Audio Device Writer block}}.
\end{enumerate}
\vspace{1cm}
Before run the simulation change the directories related to the voice input and output as mentioned in the page 1.

\begin{figure}[!h]
	\centering
	\includegraphics[scale = 0.43 ]{figures/model} %angle= 90
	\caption{RF Propagation Model - Simulink}
\end{figure}
\vspace{1.5cm}

\begin{figure}[!h]
	\centering
	\includegraphics[scale = 0.42]{figures/spect2}
	\caption{Frequency Spectrum of the signal at Various States}
\end{figure}

\pagebreak

\subsection{Codes for Task 1}

\lstinputlisting[basicstyle = \mlttfamily\scriptsize , style = Matlab-editor]{code/RFPL.m}
\pagebreak

\lstinputlisting[basicstyle = \mlttfamily\scriptsize , style =
Matlab-editor]{code/plotCurve.m}
\vfill

%=================================TASK TWO MANET============================
\pagebreak

\section{Implementing a Simplified Version of the Dynamic Source Routing(DSR) Protocol in Ad Hoc Wireless Networks}
%%-----------------------------------------------------------------------

\subsection{Simulation of a MANET with 6 nodes}
For the simulation of the Dynamic Source Routing(DSR) Protocol, we have implemented a MANET with the aid of the code base provided in the assignment.

\subsubsection{Codes for Task 2}

We were tasked with completing the routing function in ‘node.py’ and the completed routing function is as follows.\\

\begin{python}
	"""
	    ------------------------------------------------------------------------------
	    node.py
	    ------------------------------------------------------------------------------

	"""
	def route(self, pkt):

		 if pkt.type == PKT_TYPE.RREQ:    #checking whether the packet is a
																			#route request
				 if (self.check_in_recent(pkt)) or (pkt.check_id(self.id)):
					#checking whether the packet has already passed through the node
						 self.disregard += 1  #if it has already been processed,
																	#it is counted as a disregarded packet
						 self.forward()   #proceeding onto the next packet
				 else:    #if the packet is received for the first time
						 self.add_to_recent(pkt)      #adding to the recent packet list
																					#of the node
						 if pkt.target == self.id:    #checking whether this node
																					#is the destination of the packet
								 rrepPkt = self.generate_RREP(pkt)    #creating
																											#a route reply packet
								 self.add_to_queue_out(rrepPkt)   #sending the packet
						 else:    #if the packet is not addressed to the considered node
								 pkt.add_id(self.id)     #appending the id of this node
																				 #to the packet route
								 self.add_to_queue_out(pkt)   #sending the packet

		 elif pkt.type == PKT_TYPE.RREP:  #checking whether the packet is a
																			#route reply packet
				 if pkt.source == self.id:    #checking whether the packet
																			#has reached the source
						 self.add_to_cache(pkt)   #getting the route from the packet
																			#into the cache
						 if self.check_in_buffer(pkt):    #checking whether the data
																							#packet is available in buffer
								 dataPkt = self.retrieve_from_buffer(pkt)#getting the data
																												 #packet from the
																												 #buffer(as dataPkt)
								 self.add_path_from_cache(dataPkt)    #adding the route to
																											#the data packet
								 self.add_to_queue_out(dataPkt)   #sending the packet
				 else:
						 self.add_to_queue_out(pkt)   #forwarding the route reply packet
																					#until it reaches the source

		 elif pkt.type == PKT_TYPE.DPKT:  #checking whether the packet is a
																			#data packet
				 if self.id == pkt.source:    #checking whether the packet is
																			#origintaing from the considered node
						 if self.check_in_cache(pkt): #checking for the path for
																					#the packet in the node cache
								 self.add_path_from_cache(pkt)    #adding the path from
																									#the node cache
								 self.add_to_queue_out(pkt)   #sending the packet
						 else:    #if the path for the packet is not available in cache
								 self.add_to_buffer(pkt)  #keep the data packet in a buffer
								 rreqPkt = self.generate_RREQ(pkt)    #creating a route
																											#request packet
								 self.add_to_recent(rreqPkt)  #adding the route request
																							#packet to the recents list
																							#of the node
								 self.add_to_queue_out(rreqPkt)   #sending the packet
				 elif self.id == pkt.target:  #checking whether the data packet
																			#has reached its destination
						 self.received.append(pkt)    #saving the received data packet
				 else:
							self.add_to_queue_out(pkt)
\end{python}
\vspace{1cm}
In addition, we have also created ‘results.py’ which we have used to interpret the final evaluation results of the simulation.\\

\begin{python}
	"""
	    ------------------------------------------------------------------------------
	    results.py
	    ------------------------------------------------------------------------------

	"""

	from .packet import PKT_TYPE

	class Results:
	    def __init__(self):
	        self.dpkt_count = 0
	        self.total_hops = 0
	        self.counted_dpkts = []

	    def counter(self,pkt):
	        """
	        Checking the ID of packets to avoid duplicates
	        and counting the number of data packets
	        """
	        self.total_hops += 1
	        if (pkt.id) not in (self.counted_dpkts):
	            self.counted_dpkts.append(pkt.id)
	            self.dpkt_count += 1

	    def print_results(self):
	        """
	        Printing the results
	        """
	        print ("Number of data packets :",self.dpkt_count)
	        print("Total hops :",self.total_hops)
	        print(
	            "Average no. of hops per data packet :",
	            (self.total_hops/self.dpkt_count)
	            )
\end{python}
\pagebreak
Finally, the ‘demo.py’ file which was used to run the simulation is given below.
We have used a MANET consisting of 6 nodes
We have simulated for the transmission of 4 data packets.\\

\begin{python}
	"""
	    ------------------------------------------------------------------------------
	    demo.py
	    ------------------------------------------------------------------------------

	"""

	from simulator.graph import Graph
	from simulator.visualizer import step
	import cv2

	manet = Graph()

	# initialize network

	tx_range = 200
	dynamic = False  from simulator.graph import Graph
	from simulator.visualizer import step
	import cv2

	manet = Graph()

	# initialize network

	tx_range = 200
	dynamic = False  # True to use mobile model

	no_of_hops =0

	manet.add_node(500, 550, tx_range)  # "Add node 0 at 500,500"
	manet.add_node(690, 600, tx_range)  # "Add node 1 at 690,600"
	manet.add_node(780, 700, tx_range)  # "Add node 2 at 780,700"
	manet.add_node(750, 600, tx_range)  # "Add node 3 at 750,600"
	manet.add_node(790, 500, tx_range)  # "Add node 4 at 790,500"
	manet.add_node(950, 600, tx_range)  # "Add node 5 at 950,600"

	manet.send(0, 5, 1, 'Test')  # send a data packet at time step 1
	                             # from node 0 to 5
	manet.send(4, 0, 1, 'Test')  # send a data packet at time step 1
	                             # from node 4 to 1
	manet.send(2, 0, 3, 'Test')  # send a data packet at time step 3
	                             # from node 2 to 0
	manet.send(4, 2, 7, 'Test')  # send a data packet at time step 7
	                             # from node 4 to 2
	for t in range(15):  # Simulate for 15 time steps
	    step(manet, t, dynamic)

	manet.results.print_results()

	cv2.destroyAllWindows()
\end{python}

\subsubsection{Terminal Output of the Simulation}

\begin{verbatim}
	step 00:  []

	step 01:  [('0', '1', 'REQ', ('0', '5')), ('4', '1', 'REQ', ('4', '0')),
					  ('4', '3', 'REQ', ('4', '0')), ('4', '5', 'REQ', ('4', '0'))]

	step 02:  [('1', '0', 'REQ', ('0', '5')), ('1', '2', 'REQ', ('0', '5')),
					  ('1', '3', 'REQ', ('0', '5')), ('1', '4', 'REQ', ('0', '5')),
					  ('3', '1', 'REQ', ('4', '0')), ('3', '2', 'REQ', ('4', '0')),
					  ('3', '4', 'REQ', ('4', '0')), ('5', '2', 'REQ', ('4', '0')),
					  ('5', '4', 'REQ', ('4', '0'))]

	step 03:  [('1', '0', 'REQ', ('4', '0')), ('1', '2', 'REQ', ('4', '0')),
					  ('1', '3', 'REQ', ('4', '0')), ('1', '4', 'REQ', ('4', '0')),
					  ('2', '1', 'REQ', ('0', '5')), ('2', '3', 'REQ', ('0', '5')),
					  ('2', '5', 'REQ', ('0', '5')), ('3', '1', 'REQ', ('0', '5')),
					  ('3', '2', 'REQ', ('0', '5')), ('3', '4', 'REQ', ('0', '5')),
					  ('4', '1', 'REQ', ('0', '5')), ('4', '3', 'REQ', ('0', '5')),
					  ('4', '5', 'REQ', ('0', '5'))]

	step 04:  [('0', '1', 'REP', ('4', '0')), ('2', '1', 'REQ', ('4', '0')),
					  ('2', '3', 'REQ', ('4', '0')), ('2', '5', 'REQ', ('4', '0')),
					  ('5', '2', 'REP', ('0', '5'))]

	step 05:  [('1', '4', 'REP', ('4', '0')), ('2', '1', 'REQ', ('2', '0')),
					  ('2', '3', 'REQ', ('2', '0')), ('2', '5', 'REQ', ('2', '0'))]

	step 06:  [('1', '0', 'REQ', ('2', '0')), ('1', '2', 'REQ', ('2', '0')),
					  ('1', '3', 'REQ', ('2', '0')), ('1', '4', 'REQ', ('2', '0')),
					  ('2', '1', 'REP', ('0', '5')), ('3', '1', 'REQ', ('2', '0')),
					  ('3', '2', 'REQ', ('2', '0')), ('3', '4', 'REQ', ('2', '0')),
					  ('4', '1', 'DATA', ('4', '0')), ('5', '2', 'REQ', ('2', '0')),
					  ('5', '4', 'REQ', ('2', '0'))]

	step 07:  [('0', '1', 'REP', ('2', '0')), ('1', '0', 'REP', ('0', '5')),
					  ('4', '1', 'REQ', ('2', '0')), ('4', '3', 'REQ', ('2', '0')),
					  ('4', '5', 'REQ', ('2', '0')), ('5', '2', 'REQ', ('5', '2')),
					  ('5', '4', 'REQ', ('5', '2'))]

	step 08:  [('0', '1', 'DATA', ('0', '5')), ('1', '0', 'DATA', ('4', '0')),
					  ('2', '5', 'REP', ('5', '2')), ('4', '1', 'REQ', ('5', '2')),
					  ('4', '3', 'REQ', ('5', '2')), ('4', '5', 'REQ', ('5', '2'))]

	step 09:  [('1', '2', 'REP', ('2', '0')), ('3', '1', 'REQ', ('5', '2')),
					  ('3', '2', 'REQ', ('5', '2')), ('3', '4', 'REQ', ('5', '2')),
					  ('5', '2', 'DATA', ('5', '2'))]

	step 10:  [('1', '2', 'DATA', ('0', '5')), ('2', '1', 'DATA', ('2', '0'))]

	step 11:  [('1', '0', 'REQ', ('5', '2')), ('1', '2', 'REQ', ('5', '2')),
						 ('1', '3', 'REQ', ('5', '2')), ('1', '4', 'REQ', ('5', '2'))]

	step 12:  [('0', '1', 'REQ', ('5', '2')), ('1', '0', 'DATA', ('2', '0')),
					   ('2', '5', 'DATA', ('0', '5'))]

	step 13:  []
	step 14:  []
\end{verbatim}
\pagebreak

\subsubsection{Visualizer Outputs}

\begin{figure}[!h]
	\centering
	\subfigure[Step 0]
	{ \includegraphics[scale=0.165]{figures/outputs/step_0.png}

	}\hfill
	\subfigure[Step 1]
	{ \includegraphics[scale=0.165]{figures/outputs/step_1.png}

	}\hfill
	\subfigure[Step 2]
	{ \includegraphics[scale=0.165]{figures/outputs/step_2.png}
	}\\
	\subfigure[Step 3]
	{ \includegraphics[scale=0.165]{figures/outputs/step_3.png}

	}\hfill
	\subfigure[Step 4]
	{ \includegraphics[scale=0.165]{figures/outputs/step_4.png}

	}\hfill
	\subfigure[Step 5]
	{ \includegraphics[scale=0.165]{figures/outputs/step_5.png}
	}\\

	\subfigure[Step 6]
	{ \includegraphics[scale=0.165]{figures/outputs/step_6.png}

	}\hfill
	\subfigure[Step 7]
	{ \includegraphics[scale=0.165]{figures/outputs/step_7.png}

	}\hfill
	\subfigure[Step 8]
	{ \includegraphics[scale=0.165]{figures/outputs/step_8.png}
	}\\

	\subfigure[Step 9]
	{ \includegraphics[scale=0.165]{figures/outputs/step_9.png}

	}\hfill
	\subfigure[Step 10]
	{ \includegraphics[scale=0.165]{figures/outputs/step_10.png}

	}\hfill
	\subfigure[Step 11]
	{ \includegraphics[scale=0.165]{figures/outputs/step_11.png}

	}\hfill
	\subfigure[Step 12]
	{ \includegraphics[scale=0.165]{figures/outputs/step_12.png}

	}\\
	\caption{The visualizer outputs for each time step}
	%\label{}
\end{figure}

\textbf{The results of the final evaluation is as follows.}\\

Number of data packets : 4\\
Total hops : 8\\
Average no. of hops per data packet : 2.0\\

%---------------------------------------------------------------------------

\subsection{Improving the Efficiency of Protocol by further Exploiting the Route Cache}

\subsubsection{Derestricting route format}
In the existing system, the entries in the route cache contain a specific format as [(target : route), (target : route) ..].
This generates the following inefficiency.
\begin{figure}[!h]
	\centering
	\includegraphics[scale = 0.4]{figures/route}
	\caption{A Route which is already in the Route Cache}
\end{figure}

Consider an instance where a packet has to be sent from node A to node C and also assume that the route to node D also exists in the route cache of A as (D : B, C, D)
The node A is unable to extract the route to node C from this entry as node C is not listed as the target node. Instead another route reply packet has to be initiated to find the path to node C.
If this format is derestricted and used in a manner such that the path to a node inside any entry can be extracted, the number of route request transmissions can be minimized, hence propagation time as well as CPU overhead required to process those packets is reduced.

\subsubsection{Intermediate nodes resolving a route request using their route caches}
In the existing system, once a node receives a route request, it checks to see if it is the target node for that packet and if not, it broadcasts the route request packet again.
As an alternative, once a node receives a route request, the following algorithm can be implemented.

\begin{verbatim}
IF packet ID already processed
   THEN skip packet
ELSE
   add packet ID to the recents list
   IF current node is target node
      THEN append current node ID to path and initiate RREP
   ELSE IF the path to destination exists in the routing cache of current node
      THEN append that route to path and initiate RREP
   ELSE
      append current node ID to path and broadcast
\end{verbatim}

This will enable the system to minimize route request transmissions.
However, steps have to be taken to avoid processing multiple route reply packets from multiple nodes and to select the shortest path among them.

\subsection{Handling Disconnections During Transmission}

To make the process of handling disconnections more robust, we propose that an acknowledgement message be sent during each transmission. For example, in a situation where a data packet is to be sent from node A to node D using the path A-B-C-D,
\begin{enumerate}[1.]
	\item Node A send the packet to node B but still keeps the packet in a buffer
	\item Node B receives the packet and sends an acknowledgement packet back to node A
	\item Node A receives the acknowledgement packet and clears the packet from its buffer
	\item The same process is repeated when the packet is sent from node B to node C and so on.
\end{enumerate}

A description on disconnections handling using this system follows.\\

Scenario : A data packet is to be sent from node A to node D along the pre-discovered path A-B-C-D\\
Error 	: Node C disconnects\\

As per the above sequence of steps, node B sends the data packet to node C but does not receive an acknowledgment packet. Hence, the data packet is retained in the buffer and more attempts are made to resend the data packet to node C in an exponentially decreasing rate. In order to completely terminate the attempt to send the packet to node C, a maximum number of attempts is also specified.If node C does not respond after the maximum number of attempts, node C will initiate the error handling procedure.\\

Node B will initially look into its own route cache and if there are any entries through C present in it, they will be removed. Secondly, a node error packet indicating the unavailability of node C will be transmitted to the source i.e. node A. Upon receiving this packet, node A will check its route cache for any entries containing node C. If such entries are found, they will be truncated at node C.

\subsection{Differences between DSR protocol  and Distance Vector Routing protocol}

Distance vector protocols rely on the information provided by the neighboring nodes. Each node periodically broadcasts the distance to every node within its transmission range. Based on this data, the source of a data packet computes the shortest path to the target by virtue of these distance values. The direction in this ‘vector’ routing protocol is embedded in the form of the nodes it passes\cite{dsr1}\cite{dsr2}.\\

Example : ‘The target 192.168.1.0/24 is 4 hops away in direction of next-hop B’\\

In dynamic source routing protocol, the sender itself decides the complete path that the packet has to take through a route discovery process and embeds the discovered path into the packet and hence the consequent nodes will merely have to check for the next hop and forward it accordingly.\\

\textbf{Advantages of Dynamic source routing}

\begin{itemize}
	\item In a time interval where no data packets are transmitted, a distance vector protocol will continuously broadcast routing advertisement messages whereas in dynamic source routing, route discovery procedure takes place only when data packets are in buffer.
\item These route advertisements employed in distance vector protocol also causes the nodes to process a large number of redundant messages which requires CPU overhead.
\item In dynamic source routing, each node possesses a route cache which contains pre discovered routes to multiple nodes. Therefore in a scenario where there is little to no movement of the nodes, these routes can be easily utilized without a route discovery process.
\item Even in a situation where node movement is significant, the route discovery process employed in dynamic source routing can yield in an effective route much faster than in the case of a distance vector routing protocol.

\end{itemize}

\pagebreak
\bibliographystyle{plain}
\bibliography{refer}

%---------------------------------------------------------------------------
\end{document}

Assignment Template- Including-codes, mathematical equations/Document.tex


% language=uk

% author    : Hans Hagen
% copyright : PRAGMA ADE & ConTeXt Development Team
% license   : Creative Commons Attribution ShareAlike 4.0 International
% reference : pragma-ade.nl | contextgarden.net | texlive (related) distributions
% origin    : the ConTeXt distribution
%
% comment   : Because this manual is distributed with TeX distributions it comes with a rather
%             liberal license. We try to adapt these documents to upgrades in the (sub)systems
%             that they describe. Using parts of the content otherwise can therefore conflict
%             with existing functionality and we cannot be held responsible for that. Many of
%             the manuals contain characteristic graphics and personal notes or examples that
%             make no sense when used out-of-context.
%
% comment   : Some chapters might have been published in TugBoat, the NTG Maps, the ConTeXt
%             Group journal or otherwise. Thanks to the editors for corrections. Also thanks
%             to users for testing, feedback and corrections.

\environment envexamp

\startbuffer[colofon]

This document shows a few formulas coded in \MATHML\ and typeset by \CONTEXT. The
examples are taken from an old copy of \quote {Handbook of Chemistry and Physics}
as well as \quote {Wiskunde voor het HBO (R.~van Asselt et al.)}. We assume no
responsibility for the coding being 100\% all correct.

These examples are typeset using the default settings. There are several ways to
influence the look and feel of a formula. Details on how to process \MATHML\ can
be found in the \XML\ related documentation that comes with \CONTEXT.

You can get more information on \CONTEXT\ at our website, in \TEX\ usergroup
publications and in (the archives of) the \CONTEXT\ mailing list.

\blank[2*big]

\startlines
Hans Hagen
Hasselt, January 2001 / June 2008 / June 2015
\goto{www.pragma-ade.com}[url(http://www.pragma-ade.com)]
\stoplines

\stopbuffer

\startdocument
  [color=darkred,
   columns=2,
   title=MathML in \ConTeXt]

\section{Derivatives}

\showXMLsample {pc-d-001}
\showXMLsample {pc-d-002}
\showXMLsample {pc-d-003}
\showXMLsample {pc-d-004}
\showXMLsample {pc-d-005}
\showXMLsample {pc-d-006}
\showXMLsample {pc-d-007}
\showXMLsample {pc-d-008}
\showXMLsample {pc-d-009}
\showXMLsample {pc-d-010}
\showXMLsample {pc-d-011}
\showXMLsample {pc-d-043}
\showXMLsample {pc-d-051}

\section{Integrals}

\showXMLsample {pc-i-022}
\showXMLsample {pc-i-380}

\section{Series}

\showXMLsample {pc-s-001}
\showXMLsample {pc-s-002}
\showXMLsample {pc-s-003}
\showXMLsample {wh-s-001}
\showXMLsample {wh-s-002}

\section{Logs}

\showXMLsample {wh-l-001}
\showXMLsample {wh-l-002}
\showXMLsample {wh-l-003}
\showXMLsample {wh-l-004}

\section{Goniometrics}

\showXMLsample {wh-g-001}
\showXMLsample {wh-g-002}
\showXMLsample {wh-g-003}
\showXMLsample {wh-g-004}
\showXMLsample {wh-g-005}
\showXMLsample {wh-g-006}
\showXMLsample {wh-g-007}
\showXMLsample {wh-g-008}
\showXMLsample {wh-g-009}
\showXMLsample {wh-g-010}
\showXMLsample {wh-g-011}
\showXMLsample {wh-g-012}
\showXMLsample {wh-g-013}
\showXMLsample {wh-g-014}
\showXMLsample {wh-g-015}
\showXMLsample {wh-g-016}

% \section{Openmath}

% \showXMLsample {openmath-1001}
% \showXMLsample {openmath-1002}
% \showXMLsample {openmath-1003}
% \showXMLsample {openmath-1004}
% \showXMLsample {openmath-1005}
% \showXMLsample {openmath-1006}

% \showXMLsample {openmath-2001}
% \showXMLsample {openmath-2002}
% \showXMLsample {openmath-2003}
% \showXMLsample {openmath-2004}
% \showXMLsample {openmath-2005}
% \showXMLsample {openmath-2006}
% \showXMLsample {openmath-2007}
% \showXMLsample {openmath-2008}

\stopdocument


\section{The \adjacentfind algorithm}
\Label{sec:adjacentfind}

The \adjacentfind
algorithm of the \cxx Standard Library \cite[\S 28.5.8]{cxx-17-draft}

\begin{lstlisting}[style=acsl-block]

  size_type adjacent_find(const value_type* a, size_type n);
\end{lstlisting}

returns the smallest valid index i, such that i+1 is also a valid index
and such that
\begin{lstlisting}[style=acsl-block]

    a[i] == a[i+1]

\end{lstlisting}
holds.
The \adjacentfind algorithm returns \inl{n} if no such index exists.

The arrow in Figure~\ref{fig:adjacentfind} indicates the smallest index
where two adjacent elements are equal.

\begin{figure}[hbt]
\centering
\includegraphics[width=0.60\textwidth]{Figures/adjacent_find.pdf}
\caption{\Label{fig:adjacentfind}A simple example for \adjacentfind}
\end{figure}

\FloatBarrier

\subsection{The predicate \HasEqualNeighbors}

As in the case of other search algorithms, we first define
a predicate
\logicref{HasEqualNeighbors}
that captures
the essence of finding two adjacent indices at which the array holds equal values.

\begin{logic}[hbt]
\begin{minipage}{0.99\textwidth}
\lstinputlisting[style=acsl-block, frame=single]{Source/HasEqualNeighbors.acsl}
\end{minipage}
\caption{\Label{logic:HasEqualNeighbors}The predicate \HasEqualNeighbors}
\end{logic}

\subsection{Formal specification of \adjacentfind}

We use the predicate
\logicref{HasEqualNeighbors}
to define the formal specification
of \specref{adjacentfind}.

\input{Listings/adjacent_find.h.tex}

\subsection{Implementation of \adjacentfind}

In the implementation of \implref{adjacentfind} we check whether the array
contains at least two elements.
Otherwise, there is no point in looking for adjacent neighbors.
Note the use of the predicate \logicref{HasEqualNeighbors}
 in the loop invariant to
match the similar postcondition of behavior \inl{some}.

\input{Listings/adjacent_find.c.tex}


\section*{Exercise 26.2-3}

\begin{figure}[H]
\caption{\textit{Executing the Edmonds-Karp algorithm}}
\vskip .2cm
\centering
\subfloat[The left side shows the residual network $G_f$, along with an augmenting path, and the right side shows the new augmented flow in $G$. After three iterations, there are no more augmenting paths, so the last flow shown in $G$ is then the maximum flow, with the value 23.]{\includegraphics[angle=0,width=12cm]{26-2-3}}
\end{figure}


\chapter{Modeling Mutation}\label{ch:modelingMutation}
In this chapter, we discuss mutation and describe our proposed 2-parameter $\theta = \{ d, c\}$ mutation model.

\section{Repeat Unit Change Per Generation}\label{sec:repeatUnitChangePerGeneration}
Mutation refers to a change in DNA sequence.
For this paper, we refer to mutation as a change in the repeat unit of some locus for a microsatellite variant.
We are also only discussing mutations that are passed on to the next generation, under the neutral (Wright-Fisher)
assumptions.

The simplest model of microsatellite mutation and evolution is the stepwise mutation
model of Ohta and Kimura~\cite{ohtaModelMutationAppropriate2007}.
Let $f : \mathbb{M},\mathbb{V} \rightarrow \mathbb{M}$ represent some function that accepts some repeat unit and random
variables $\mathcal{V} \in \mathbb{V}$, and outputs some repeat unit.
Given a population $\pi^{(t)}$ at generation $t$ and some repeat unit $\ell^{(t)} \in \pi^{(t)}$, there are three
possibilites for the mutated repeat unit in the next generation $f(\ell^{(t)}) = \ell^{(t+1)}$:
\begin{equation}
    f(\ell^{(t)}) \in \{ \ell^{(t)} + 1 , \ell^{(t)}, \ell^{(t)} - 1\}
\end{equation}
Per generation, each microsatellite variant mutates up one repeat unit (expansion), down one repeat unit
(contraction), or stays the same -- all with equal probability.

Let $\mu_u$ represent the probability of upward mutation and $\mu_d$ represent the probability of downward mutation.
We can construct our function $f$ as such:
\begin{enumerate}
    \item We are given some repeat unit $\ell^{(t)}$, an upward mutation rate $\mu_u$, and a
        downward mutation rate $\mu_d$.
    \item Sample two numbers from a uniform random distribution: $x_u, x_d \sim U(0, 1)$.
    \item If $\mu_u > x_u$, then $f(\ell^{(t)}) = \ell^{(t)} + 1$.
        This is the inverse transform sampling method. \label{enum:um}
    \item If $\mu_d > x_d$ but $\mu_u \leq x_u$, then $f(\ell^{(t)}) = \ell^{(t)} - 1$. \label{enum:dm}
    \item If $(\mu_d > x_d \ \land \ \mu_u > x_u) \ \lor \ (\mu_d < x_d \ \land \ \mu_u < x_u)$, then
        $f(\ell^{(t)}) = \ell^{(t)}$.
\end{enumerate}

There does exist evidence that mutations occur at steps greater than one repeat unit.
A model that takes this into account is the two-phase model, which follows the stepwise mutation model with probability
$p$ and mutates up and down with a unit sampled from a geometric distribution, with probability $1-p$
~\cite{dirienzoMutationalProcessesSimplesequence1994}.
This is modeled by the procedure below:
\begin{enumerate}
    \item We are given some repeat unit $\ell^{(t)}$, an upward mutation rate $\mu_u$, a
        downward mutation rate $\mu_d$, the probability of the stepwise mutation model $p$, and the success probability
        for the geometric distribution $m$.
    \item Sample three numbers from a uniform random distribution: $x_u, x_d, x_p \sim U(0, 1)$.
    \item If $p > x_p$, then we set the changes in repeat unit $\Delta_u = 1, \Delta_d = 1$.
        Otherwise, we sample our changes from a geometric distribution:
        $\Delta_u, \Delta_d \sim \mathit{Geom}(m)$.
    \item If $\mu_u > x_u$, then $f(\ell^{(t)}) = \ell^{(t)} + \Delta_u$.
    \item If $\mu_d > x_d \land \mu_u \leq x_u$, then $f(\ell^{(t)}) = \ell^{(t)} - \Delta_d$.
    \item If $(\mu_d > x_d \ \land \ \mu_u > x_u) \ \lor \ (\mu_d < x_d \ \land \ \mu_u < x_u)$,
        then $f(\ell^{(t)}) = \ell^{(t)} + \Delta_u - \Delta_d$.
\end{enumerate}

The two-phase model is more flexible here, but this introduces two new parameters to estimate: $p$ and $m$.
According to Sainudiin, the likelihood of all ``one phase'' models are
not significantly different than their two phase counterparts~\cite{sainudiinMicrosatelliteMutationModels2004}.
For this reason, our model restricts repeat units to mutate by at most one per generation.

\section{Mutation Rate Dependence on Repeat Unit}\label{sec:mutationRateDependenceOnRepeatUnit}
\begin{figure}[t]
    \centering{\input{include/floats/mutation-model.tex}}
    \caption{Our mutation model for $d=0.0025, c=0.03$.
    Our focal length with these parameters is $\hat{\ell}=12$.}\label{fig:mutationModel}
\end{figure}

%Before building a more complex model, we must first ask, ``When does mutation occur?''.
%Does it occur per generation?
%Per every odd generation?
%The answer to this lies with a quantity known as $\mu \in [0, 1]$, or the \emph{mutation rate}.
%From generation to generation we generate a uniformly distributed random variable between 0 and 1, and ask if this draw
%is below our mutation rate.
%If the answer is yes, we mutate up or down one repeat unit.
%Otherwise, our repeat unit remains unchanged.
%\begin{equation}
%    \begin{cases}
%        \text{mutate} & \mu > \ \sim U(0, 1) \\
%        \text{do not mutate} & \mu \leq \ \sim U(0, 1)
%    \end{cases}
%\end{equation}

\begin{algorithm}[t]
    \SetAlgoLined
    \DontPrintSemicolon
    \Fn{MutateFunction \ {$(c, d, \ell^{(t)})$}} {
        \KwIn{an upward constant mutation bias $c$, downward linear mutation bias $d$, current repeat unit $\ell^{(t)}$}
        \KwOut{a repeat unit from the next generation $\ell^{(t+1)}$}
        $\ell^{(t+1)} \gets \ell^{(t)}$ \;
        \If{$\ell^{(t+1)} = \kappa$}{
            \Return $\ell^{(t+1)}$
        }
        \If{$c < \ \sim U(0, 1)$}{
            $\ell^{(t+1)} \gets \ell^{(t+1)} + 1$ \;
        }
        \If{$d\ell < \ \sim U(0, 1)$}{
            $\ell^{(t+1)} \gets \ell^{(t+1)} - 1$ \;
        }
        \Return $\ell^{(t+1)}$ \;
    }
%    \textbf{end} \;
    \caption{The algorithmic description for $f: \mathbb{M},\mathbb{V} \rightarrow \mathbb{M}$.
    To stay consistent with the definition of $f$ we denote $c$ and $d$ as parameters of the model itself.}
    \label{alg:mutateFunction}
\end{algorithm}

An assumption made with stepwise mutation model is that the probability of mutation is equal for all repeat units.
Ellegren showed that allele unit plays a role in how often mutations
occur~\cite{ellegrenHeterogeneousMutationProcesses2000}.
More specifically, longer repeat units mutate more often than shorter repeat units.
To introduce this repeat unit dependence, we use the following equation:
\begin{equation}\label{eq:linearRepeatUnitDependence}
    \mu = s \cdot \ell
\end{equation}
where $s$ represents the strength of this dependence.
There exists evidence for more complex models such as the exponentially increasing mutation rate of Xu et.\ al.\
~\cite{xuDirectionMicrosatelliteMutations2000}.
In this case, our repeat unit dependence would be represented by:
\begin{equation}
    \mu = s \cdot \exp (\ell)
\end{equation}
Following Sainudiin's general model which included only linear dependence, we made the decision to use the first
equation (\autoref{eq:linearRepeatUnitDependence}).

\section{Presence of Mutational Bias}\label{sec:presenceOfMutationalBias}
There now exists a mutation rate dependence on repeat unit, but the probability of mutating up or down is still
equally likely.
Garza's observed that microsatellites tend to mutate toward a \emph{focal
unit}~\cite{garzaMicrosatelliteAlleleFrequencies1995}.
If the repeat unit of interest $\ell$ is below the focal length at some generation $t$, $\ell$ will have a higher
probability of mutating upward than downward in the following generations.
Conversely if $\ell$ is above the focal length at some generation $t$, $\ell$ will have a higher probability of
mutating downward than upward in the following generations.

Sainudiin's general model uses the functions $\beta : \ell, s \mapsto [0, 1]$ and $\alpha : u, v, \ell \mapsto [0, 1]$
to establish these biases:
\begin{align}
    \beta(\ell, s) &= \mu (1 + (\ell - \kappa)s) \\
    \alpha(u, v, \ell) &= \max (0, \min(1, u - v(\ell - \kappa)))
\end{align}
where $\beta$ is the rate of mutation and $\alpha$ is probability that our repeat unit is incremented (expanded).
Here $u$ represents some constant bias applied toward expansion and $v$ represents the linear bias toward expansion.
A focal unit $\hat{\ell} = ((u - 0.5) / v)$ is specified if we have a greater tendency toward
expansion at lower repeat units ($0.5 < u < 1$) and if the following holds:
$(u - 0.5) / (\Omega - \kappa) < v < \infty$~\cite{sainudiinMicrosatelliteMutationModels2004}.
In other words, a focal unit is defined where the probability of expansion equals the probability of contraction.

\section{Proposed Mutation Model}\label{sec:proposedMutationModel}
This now brings us to our complete mutation model.
To introduce a bias toward some focal unit, we define two mutation rates: the upward mutation rate $\mu_u$ and the
downward mutation rate $\mu_d$.
The total mutation rate is the sum of the two: $\mu = \mu_u + \mu_d$.
We define $\mu_d$ to be dependent on repeat unit, and $\mu_u$ to be constant:
\begin{align}
    \mu_u &= c \\
    \mu_d &= d\ell
\end{align}
where $c$ represents a constant bias for the upward mutation (or, the upward mutation rate itself) and $d$ represents a
linear bias for the downward mutation rate.
We constrain $c > 0, d \geq 0$ to ensure that mutation is always occurring.
The focal unit $\hat{\ell}$ is defined as the intersection between the upward and downward mutation rate, where the
probability of expansion equals to the probability of contraction.
\begin{equation}
    \hat{\ell} = \frac{c}{d}
\end{equation}
This differs from Sainudiin's model usage of $\alpha(u, v, \ell)$, but for our purposes is functionally equivalent and
requires two less parameters.
In addition to the three requirements listed in the previous sections, we constrain that any individuals having repeat
unit $\ell = \kappa$ are unable to mutate back up.
If $f$ is given some repeat unit $\ell$ equal to the lower bound of $\mathbb{M}$, $\ell$ is returned.
This is meant to simulate how microsatellites are lost in populations.

Graphically, this is represented in~\autoref{fig:mutationModel}.
We describe the entire mutation function $f$ in~\autoref{alg:mutateFunction}.
We achieve the first state $\ell^{(t)} + 1$ for some $\ell^{(t)}$ by applying our upward mutation first and saving this
to $\ell^{(t+1)}$.
We achieve states $\ell^{(t)} - 1$ \emph{and} $\ell^{(t)}$ by applying our downward mutation second, after performing
our upward mutation.
Only after performing these two in sequence do we return our mutated repeat unit $\ell^{(t + 1)}$.


\section{Task A}
\label{sec:task-a}

In the first task, the plots from \cite{Bonet2008} were reproduced.
In order to achieve that the presence of the second rod in the given
problem needed to be accounted for.
This was done by normalising the force by the total area of the two rods.
At each displacement increment, the vertical force in the top node (DOF 4)
was computed as a sum of the already acting force plus the force
needed to move the top node by the increment of the displacement,
i.e.
\begin{equation}
  F_{n+1} = F_{n} + K^{\text{global}}_{4,j} \Delta u_{j}
\end{equation}

The plots presented in figure 3.8 a-d of \cite{Bonet2008} were reproduced
and are given in figure~\ref{fig:plots-from-book}.
\begin{figure}[th]
  \centering
  % Force - deflection:
  \begin{subfigure}[t]{\textwidth}
    \begin{tikzpicture}
      \begin{axis}[
        width = 0.95\textwidth,
        height=\axisdefaultheight,
        tick label style={/pgf/number format/fixed},
        try min ticks=6,
        minor tick num=1,
        grid=both,
        xlabel = {\( (Y - y) / L \), [-]},
        ylabel = {\( F / (E A) \), [-]},
        xmin = 0,
        xmax = 2,
        ymin = -0.15,
        ymax = 0.2,
        legend cell align=left,
        legend style={anchor=south east, at={(1,0)}}
        ]
        \addplot+ table[skip first n=1] {data/force_deflection_elastic.dat}; % + = same automatically determined styles, but in addition it uses [options]
        \addlegendentry{elastic}
        \addplot+ table[skip first n=1] {data/force_deflection_plastic.dat};
        \addlegendentry{plastic}
      \end{axis}
    \end{tikzpicture}
    \caption{Force - deflection}
  \end{subfigure}

  % Stress - strain:
  \begin{subfigure}[t]{0.48\textwidth}
    \begin{tikzpicture}[baseline,yscale=1.0, xscale=1.0]
      \begin{axis}[
        try min ticks=7,
        minor tick num=1,
        grid=both,
        xlabel = {strain, [-]},
        ylabel = {Kirchhoff stress, [kN/mm\textsuperscript{2}]},
        xmin = -0.4,
        xmax = 0.3,
        xtick={-0.4, -0.2, 0, 0.2},
        ymin = -30,
        ymax = 30,
        legend cell align=left,
        legend style={anchor=south east, at={(1,0)}}
        ]
        \addplot+ table[skip first n=1] {data/stress_strain_elastic.dat};
        \addlegendentry{elastic}
        \addplot+ table[skip first n=1] {data/stress_strain_plastic.dat};
        \addlegendentry{plastic}
      \end{axis}
    \end{tikzpicture}
    \caption{Constitutive behaviour}
  \end{subfigure}
  % Total - plastic strain:
  \begin{subfigure}[t]{0.48\textwidth}
    \begin{tikzpicture}[baseline,yscale=1.0, xscale=1.0]
      \begin{axis}[
        % try min ticks=8,
        minor tick num=1,
        grid=both,
        xlabel = {total strain, [-]},
        ylabel = {plastic strain, [-]},
        xmin = -0.4,
        xmax = 0.3,
        ymin = -0.25,
        ymax = 0.15
        ]
        \addplot+ [mark=none] table[skip first n=1] {data/tot_pl_strain.dat};
        \addplot+  table[skip first n=1] {data/tot_pl_strain.dat}; % Plot again using style of 2nd element in cycle list.
      \end{axis}
    \end{tikzpicture}
    \caption{Plastic - total strain}
  \end{subfigure}
  \caption{Plots of large deflection elasto-plastic behaviour from \cite{Bonet2008}.}
  \label{fig:plots-from-book}
\end{figure}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../main"
%%% End: