\chapter{Variables and Class}

\section{The Basics}
\begingroup
\imb[1][4]{\cpp/01_varandclass.cpp}
\imb[29][30]{\cpp/01_varandclass.cpp}[Printing \texttt{Hello, World!} with C++]
\endgroup
C++ is the younger, more powerful and versatile form of what C was meant to be.
C++ utilises features such as object-orientated programming not supported by C.

\subsection{Commenting}
Single-line comments use two forward slashes: \imc{// Comment 1}\\
Multi-line comments use forward slash and star at each end to denote beginning
and end: \imc{/* Comment 2 */}

\subsection{Types and Variables}
\begin{enumerate}
\item Primitive, built-in types:
    \begin{enumerate}
    \item \imc{void} is used to determine functions and variables of no return
        value.
    \item \imc{bool, char, int, float, double} and et cetra are used to return
        certain values.
    \item \imc{unsigned} is prepended to targets that are always of positive
        value.
    \end{enumerate}
\item Enumerations: \imc{enum} is used to define groups of integer constants.
    \begingroup
    \imb[5]{\cpp/01_varandclass.cpp}[An example declaration of \imc{enum}]
    \endgroup
\item Variable Scopes: Varaibles are defined only up to the level of their own
    declaration.
    \begin{enumerate}
    \item Global Variables: Variables that are declared outside functions and
        classes. Global variables can be defined as \imc{static} to make its
        scope local to one file.
    \item Local Variables: Variables that are declared within a function, class,
        or otherwise enclosed snippets of code. Variables can only be used and
        memoized within that specific snippet. However, these variables can also
        be defined as \imc{static} to retain its value from previous uses and
        bypass re-initialisation.
    \end{enumerate}
\item Constant Qualifier: Variables preceded by the keyword \imc{const} cannot
    be altered by the program. \begingroup
    \imb[6]{\cpp/01_varandclass.cpp}[An example declaration of constant integer]
    \endgroup
\end{enumerate}

\section{Basic Expressions and Statements}
\begin{enumerate}
\item Basic Expressions: Expressions are combinations of iterated variables
    and operators that portray a new value or meaning.
    \begin{enumerate}
    \item Arithmetic Expressions: Like most other programming languages, C++
        features arithmetic operators \verb|+, -, *, /, %| which each perform
        additions, subtractions, multiplications, truncating divisions and
        modular calculations. \begingroup
        \imb[7][8]{\cpp/01_varandclass.cpp}[Arithmetic operators in C++]
        \endgroup
    \item Relational Expressions: Like most other programming languages, C++
        features relational operators \imc{==, !=, <, >, <=, >=} which each mean
        equality, inequality, less-than, greater-than, less-than-or-equal and
        greater-than-or-equal. \begingroup
        \imb[9][10]{\cpp/01_varandclass.cpp}[Relational operators in C++]
        \endgroup
    \end{enumerate}
\item Basic Statements: Statements are combinations of expressions and snippets
    of code that portray the actions to be taken by the program itself.
    \begin{enumerate}
    \item Conditional Statements: Like most other programming languages, C++
        features selective execution of code with keywords \imc{if...else} and
        \imc{switch}. \imc{if...else} are used for extensive description of the
        determining criteria, while \imc{switch} is used for multiple possible
        outcomes of the same, relatively simple value. \begingroup
        \imb[11][17]{\cpp/01_varandclass.cpp}[Conditional Statements in C++]
        \endgroup
    \item Ternary Conditional Operator: The only operator of the C++ language to
        feature three operands, conditional operator \imc{expr1 ? expr2 : expr3}
        evaluates the boolean value of \imc{expr1}, and if it is true executes
        \imc{expr2}, else \imc{expr3}. \begingroup
        \imb[18][19]{\cpp/01_varandclass.cpp}[The Ternary Operator of C++]
        \endgroup
    \item Iterative Statements: Like other programming languages, C++ features
        iterative execution of code with keywords \imc{for} and \imc{while}.
        \begingroup
        \imb[20][26]{\cpp/01_varandclass.cpp}[Iterative Statements in C++]
        \endgroup
    \end{enumerate}
\item Memory Management: Keywords \imc{new} and \imc{delete} each process the
    allocation and deallocation of memory in C++. \begingroup
    \imb[27][28]{\cpp/01_varandclass.cpp}[Allocation of Memory in C++]
    \endgroup
\end{enumerate}


\documentclass[10pt, oneside, letterpaper]{article}
\usepackage[margin=1in]{geometry}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\usepackage{listings}
\lstset{
  backgroundcolor=\color{white}, % choose the background color
  basicstyle=\footnotesize\ttfamily, % size of fonts used for the code
  breaklines=true, % automatic line breaking only at whitespace
  frame=single, % add a frame
  captionpos=b, % sets the caption-position to bottom
  commentstyle=\color{mygreen}, % comment style
  escapeinside={\%*}{*)}, % if you want to add LaTeX within your code
  keywordstyle=\color{blue}, % keyword style
  stringstyle=\color{mymauve}, % string literal style
}
\usepackage{enumitem}
\usepackage{blindtext}
\usepackage{datetime2}
\usepackage{fancyhdr}
\usepackage{amsmath}
\usepackage{arydshln} % dash line package for matrices
\usepackage{mathtools} % for things like \Aboxed
\usepackage{float}
\usepackage{pgf}
\usepackage{enumitem} % to easily change style of counters in item lists
\usepackage{xurl} % to easily insert URLs in the LaTeX source
\usepackage{braket} % for bra-ket notation
\usepackage{bm} % for bold vector variables
\usepackage{cases} % for piecewise definitions
\usepackage[makeroom]{cancel} % for crossing out terms
\usepackage{graphicx} % for \scalebox
  \newcommand\scalemath[2]{\scalebox{#1}{\mbox{\ensuremath{\displaystyle #2}}}}

\setcounter{MaxMatrixCols}{32} % increase the maximum number of matrix columns

\title{Assignment 1}
\author{Introduction: Infinite Potential Well}
\date{Due: 2022/01/28}

\pagestyle{fancy}
\setlength{\headheight}{23pt}
\setlength{\parskip}{1em}
\fancyhf{}
\chead{Assignment 1}
\rhead{Michel Kakulphimp \\ Student \#63542880}
\lhead{ELEC542 \\ UBC MEng}
\cfoot{\thepage}

\begin{document}
\maketitle
\thispagestyle{fancy}

\section{Directions}

Neglect spin in this problem.

\begin{enumerate}[label=(\alph*)]
  \item Consider one electron in a one-dimensional, infinitely-deep potential well, with a width of 10 in atomic units. Find the electron wavefunctions and allowed energy levels by analytically solving the Schrödinger equation. Plot the first six wave functions and give their associated eigenvalues.
  \item Same as (a), but this time solve the equation numerically using a language of your choice (Python, Matlab, Maple, Mathematica, Basic, C, Pascal, Fortran, assembly, machine code, etc.). Discretize the width of the potential well into at least 10 segments. Finite difference is preferred for solving the equation numerically.
  \item Same as (b), but this time assume that there are two non-interacting electrons in the well. Note that in this case the wave function will have two variables (the positions of the two electrons).
  \item Same as (c), but this time include the Coulomb interaction between the two electrons. Comment on the solutions and their difference with those obtained in part (c).
\end{enumerate}

\section{Solution}

For this assignment, we need to find the solutions of the following one-dimensional, time-independent Schr\"{o}dinger's equation:

\begin{align*}
  \hat{H}\Phi_n(x_i) &= {E_n}\Phi_n(x_i)
\end{align*}

For this assignment, $\hat{H}$ is the Hamiltonian operator for a system of electrons described by their position $x_{i}$, $E_n$ is the energy eigenvalue, and $\Phi_n(x_i)$ is the wavefunction that we want to solve for. Note that we will have multiple solutions and we are tasked to obtain the first six. Nuclei are ignored for this problem as only electrons and their interactions are involed, so their contribution is not included in the operator. The expanded form of this Hamiltonian operator for N electrons is as follows (in Hartree atomic units where $\hbar = m_e = e^2 = 1$):

\begin{align*}
  \hat{H} &= \hat{T} + \hat{U} + \hat{V} & \text{total energy of the system}\\
  \hat{H} &= -\sum_{i=1}^{N}\frac{1}{2}\nabla^{2}_i + \sum_{i=1}^{N}\sum_{j>i}^{N}\frac{1}{x_{ij}} + \sum_{i=1}^{N}v(x_i)\\
  \hat{T} &= -\sum_{i=1}^{N}\frac{1}{2}\nabla^{2}_i & \text{kinetic energy of each electron}\\
  \hat{U} &= \sum_{i=1}^{N}\sum_{j>i}^{N}\frac{1}{x_{ij}} & \text{Coulomb repulsion between electrons}\\
  \hat{V} &= \sum_{i=1}^{N}v(x_i) & \text{potential energy of each electron}
\end{align*}

Our one-dimensional, infinitely-deep potential well with a width of 10 atomic units gives us the following boundary conditions for each electron's potential energy $v(x_i)$:

\begin{align*}
  v(x_i) &= \begin{cases}
          0       \quad \, & |x| < 5a \\
          \infty  \quad \, & |x| > 5a \\
     \end{cases}
\end{align*}

\subsection{Analytical Solution: Single Electron}

For the first two steps, we will analytically solve the Schr\"{o}dinger equation for a single electron bounded within the 10 atomic unit infinite well to obtain the first six wavefunctions and the associated eigenvalues. For a single electron, the Hamiltonian shown above is simplied as follows:

\begin{align*}
  \hat{H} &= -\frac{1}{2}\nabla^{2}_i + v(x_i)\\
\end{align*}

We only have one electron, so the summations are dropped and there is no Coulomb interaction to consider. We can then plug this new Hamiltonian into Schr\"{o}dinger's equation:

\begin{align*}
  \hat{H}\Phi_n(x) &= {E_n}\Phi_n(x) \\
  -\frac{1}{2}\Phi^{''}_n(x) + v(x)\Phi_n(x) &= {E_n}\Phi_n(x)
\end{align*}

With the following boundary conditions:

\begin{align*}
  v(x_i) &= \begin{cases}
          0       \quad \, & |x| < 5a \\
          \infty  \quad \, & |x| > 5a \\
     \end{cases}
\end{align*}

We know that the wave function will have the following value at the boundaries of the well (the walls):

\begin{align*}
  \Phi_n(\pm5a) = 0
\end{align*}

Which leaves us with the following equation to solve for within the well:

\begin{align*}
  -\frac{1}{2}\Phi^{''}_n(x) &= {E_n}\Phi_n(x)
\end{align*}

This is a second order linear differential equation. The general solution to this form of the second order linear differential equation is as follows:

\begin{align*}
  \Phi_n(x) = Ae^{ikx} + Be^{-ikx}
\end{align*}

Plugging in our boundary conditions, we get the following relationships:

\begin{align*}
  \Phi_n(-5a) &= Ae^{-ik5a} + Be^{ik5a} = 0 \\
  \Phi_n(5a) &= Ae^{ik5a} + Be^{-ik5a} = 0
\end{align*}

With some algebra, we can then get the following relationships:

\begin{align*}
  A + Be^{2ik5a} &= 0 \Longrightarrow A = -Be^{i10ka} \\
  A + Be^{-2ik5a} &= 0 \Longrightarrow A = -Be^{-i10ka} \\
  -Be^{i10ka} &= -Be^{-i10ka} \\
  e^{i10ka} &= e^{-i10ka} \\
  e^{i20ka} &= 1
\end{align*}

Using Euler's identity, we know that:

\begin{align*}
  e^{i2\pi n} &= 1
\end{align*}

Therefore our possible values for k are as follows:

\begin{align*}
  2\pi n &= 20ka \\
  k &= \frac{\pi n}{10a}
\end{align*}

Where $n$ is an integer. With this result, we can progress further into defining the wave function as follows:

\begin{align*}
  A &= -Be^{i10ka} \\
  A &= -Be^{i\pi n} \\
  A &= -B(e^{i\pi})^n \\
  A &= -B(-1)^n \\
  \Aboxed{A &= -B} & \text{for even n} \\
  \Aboxed{A &= B} & \text{for odd n} \\
  \Phi_n(x) &= Ae^{-ikx} - Ae^{ikx} = 2iA\sin(kx) \\
  \Aboxed{\Phi_n(x) &= 2iA\sin(\frac{\pi nx}{10a})} &\text{for even n} \\
  \Phi_n(x) &= Ae^{-ikx} + Ae^{ikx} = 2A\cos(kx) \\
  \Aboxed{\Phi_n(x) &= 2A\cos(\frac{\pi nx}{10a})} &\text{for odd n}
\end{align*}

We are left with finding the value for the constant $A$. We can normalize the wavefunction to calculate this value. This represents the fact that the probability of finding the wave function in all space is equal to 1.

\begin{align*}
  1 = \int_{-\infty}^{\infty}\left|\Phi_n(x)\right|^2dx
\end{align*}

Since the problem defines the bounds of the wavefunction to within an infinitely-deep potential well of a fixed size, we can use the bounds of the box as the integration limits.

\begin{align*}
  1 = \int_{-5a}^{5a}\left|\Phi_n(x)\right|^2dx
\end{align*}

We can now evaluate the integral for both even and odd cases as follows.

For the even case:

\begin{align*}
  1 &= \int_{-5a}^{5a}\left|\Phi_n(x)\right|^2dx \\
  1 &= 4\left|A\right|^2\int_{-5a}^{5a}\sin^2\left(\frac{\pi nx}{10a}\right)dx \\
  1 &= 4\left|A\right|^2\int_{-5a}^{5a}\frac{1}{2}\left[1-\cos\left(\frac{\pi nx}{5a}\right)\right]dx \\
  1 &= 2\left|A\right|^2\int_{-5a}^{5a}\left[1-\cos\left(\frac{\pi nx}{5a}\right)\right]dx \\
  1 &= 2\left|A\right|^2\left[x\cancel{-\frac{5a}{\pi n}\sin\left(\frac{\pi nx}{5a}\right)}\right]_{-5a}^{5a} \\
  1 &= 2\left|A\right|^2 10a \\
  \left|A\right|^2 &= \frac{1}{20a} \\
  A &= \frac{1}{\sqrt{20a}}, \frac{-i}{\sqrt{20a}} \\
  \Aboxed{\Phi_n(x) &= \frac{2}{\sqrt{20a}}\sin\left(\frac{\pi nx}{10a}\right)} &\text{for even n}
\end{align*}

We choose the imaginary value for A so that we can cancel out the imaginary value in the wave equation to obtain a real result. We can perform the same steps for the odd case as follows:

\begin{align*}
  1 &= \int_{-5a}^{5a}\left|\Phi_n(x)\right|^2dx \\
  1 &= 4\left|A\right|^2\int_{-5a}^{5a}\cos^2\left(\frac{\pi nx}{10a}\right)dx \\
  1 &= 4\left|A\right|^2\int_{-5a}^{5a}\frac{1}{2}\left[1+\cos\left(\frac{\pi nx}{5a}\right)\right]dx \\
  1 &= 2\left|A\right|^2\int_{-5a}^{5a}\left[1+\cos\left(\frac{\pi nx}{5a}\right)\right]dx \\
  1 &= 2\left|A\right|^2\left[x\cancel{+\frac{5a}{\pi n}\sin\left(\frac{\pi nx}{5a}\right)}\right]_{-5a}^{5a} \\
  1 &= 2\left|A\right|^2 10a \\
  \left|A\right|^2 &= \frac{1}{20a} \\
  A &= \frac{1}{\sqrt{20a}}, \frac{-i}{\sqrt{20a}} \\
  \Aboxed{\Phi_n(x) &= \frac{2}{\sqrt{20a}}\cos\left(\frac{\pi nx}{10a}\right)} &\text{for odd n}
\end{align*}

In this case, we choose the real value for A so that the wave equation remains real. We can now plot the first six wave functions for $n = 1, 2, 3, 4, 5, 6$ as follows:

\begin{figure}[H]
  \begin{center}
    \input{analytical-wave-function-plot.pgf}
  \end{center}
  \caption{Wave functions for the analytical solution of the one-dimensional, time-independent Schr\"{o}dinger's describing one electron in an infinitely-deep potential well of width $10a$}
  \label{analytical-plot}
\end{figure}

For the energy eigenvalues for each of these wavefunctions, we'll need to relate the energy eigenvalue term $E_n$ back to the constant term k that was derived. We can do this by substituting the wave function derived and plug it into the Schr\"{o}dinger equation that is valid for within the well (where potential energy is equal to 0: $v(x) = 0$) as follows:

\begin{align*}
  -\frac{1}{2}\Phi^{''}_n(x) &= {E_n}\Phi_n(x) \\
  -\frac{1}{2}\left[ \frac{2}{\sqrt{20a}}\sin\left(\frac{\pi nx}{10a}\right) \right]\frac{d^2\Phi_n(x)}{dx^2} &= E_n\frac{2}{\sqrt{20a}}\sin\left(\frac{\pi nx}{10a}\right) \\
  -\frac{1}{2}\left[ \cancel{\frac{2}{\sqrt{20a}}} \left(-\frac{n^2\pi^2}{100a^2}\right) \cancel{\sin\left(\frac{\pi nx}{10a}\right)} \right] &= E_n\cancel{ \frac{2}{\sqrt{20a}}\sin\left(\frac{\pi nx}{10a}\right) } \\
  \frac{n^2\pi^2}{200a^2} &= E_n \\
  E_o &= \frac{\pi^2}{200a^2} \\
  \Aboxed{E_n &= n^2E_o & }
\end{align*}
We started off with the even $n$ wavefunction, but the odd $n$ wavefunction results in the same energy eigenvalues. Therefore our result is valid for both even and odd $n$. Our first six eigenvalues are as follows:

\begin{table}
\begin{center}
\begin{tabular}{l|llllll}\hline
$n$    & $1$    & $2$     & $3$     & $4$      & $5$      & $6$      \\\hline
$E_n$  & $E_o$  & $4E_o$  & $9E_o$  & $16E_o$  & $25E_o$  & $36E_o$ \\\hline
\end{tabular}
\end{center}
  \caption{The first six energy levels calculated for this problem through the analytical method. This will be compared to the following problem's results.}
  \label{analytical-energies}
\end{table}

\subsection{Numerical Solution 1: Single Electron}

In order to solve the single electron problem numerically, we must discretize the following equation:

\begin{align*}
  -\frac{1}{2}\Phi^{''}_n(x) + v(x)\Phi_n(x) &= {E_n}\Phi_n(x)
  & v(x_i) = \begin{cases}
          0       \quad \, & |x| < 5a \\
          \infty  \quad \, & |x| > 5a \\
     \end{cases}
\end{align*}

To accomplish this, we can replace the second derivative of the wave function in the one-dimensional, time-independent Schr\"{o}dinger's with a second-order centered difference approximation which has the following form:

\begin{align*}
  \frac{d^2f(x)}{dx^2} &\approx \frac{f(x + \Delta x) - 2f(x) + f(x - \Delta x)}{\Delta x^2}
\end{align*}

Schr\"{o}dinger's equation then transforms into a discretized version as follows:

\begin{align*}
  -\frac{1}{2}\left[\frac{\Phi_n(x + \Delta x) - 2\Phi_n(x) + \Phi_n(x - \Delta x)}{\Delta x^2}\right] + v(x)\Phi_n(x) &= {E_n}\Phi_n(x)
\end{align*}

This solution relies on a step size $\Delta x$ with the second derivative approximation requiring a previous value ($x - \Delta x$) and the next value ($x + \Delta x$) along with the current value $x$. By taking into account the entire well, sliced into $N$ segments of size $\Delta x$, each segment will represent a different set of the discretized Schr\"{o}dinger's equation to solve, which together forms a linear set of equations which can be solved with the help of linear algebra. For a discretization of $N=10$, we have the following matrices involved:

The kinetic energy matrix:

\begin{align*}
\bm{T_{N=10}} = -\frac{1}{2\Delta x^2}
\begin{bmatrix}
-2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
 1 &-2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & 1 &-2 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & 1 &-2 & 1 & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 1 &-2 & 1 & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & 1 &-2 & 1 & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & 1 &-2 & 1 & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & 1 &-2 & 1 & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 &-2 & 1\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 &-2\\
\end{bmatrix}
\end{align*}

And the potential energy matrix:

\begin{align*}
\bm{V_{N=10}} =
\begin{bmatrix}
 v(x) & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & v(x) & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & v(x) & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & v(x) & 0 & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & v(x) & 0 & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & v(x) & 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & v(x) & 0 & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & v(x) & 0 & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & v(x) & 0\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & v(x)\\
\end{bmatrix}
\end{align*}

where

\begin{align*}
  v(x) &= \begin{cases}
          0       \quad \, & |x| < 5a \\
          \infty  \quad \, & |x| > 5a \\
     \end{cases}
\end{align*}

Which results in the following system to solve for:

\begin{align*}
\bm{T}\ket{\Phi} + \bm{V}\ket{\Phi} = \bm{E}\ket{\Phi}
\end{align*}

or simply:

\begin{align*}
\bm{H}\ket{\Phi} = \bm{E}\ket{\Phi}
\end{align*}

where $\ket{\Phi}$ is the column vector representing each step of the wave function's discretization:

\begin{align*}
\ket{\Phi} =
\begin{bmatrix}
 \Phi_1 \\
 \Phi_2 \\
 \Phi_3 \\
 \Phi_4 \\
 \Phi_5 \\
 \Phi_6 \\
 \Phi_7 \\
 \Phi_8 \\
 \Phi_9 \\
 \Phi_{10} \\
\end{bmatrix}
\end{align*}

and $\bm{H}$ is the Hamiltonian matrix composed of $\bm{T} + \bm{V}$. By diagonalizing $\bm{H}$, we will obtain the eigenvectors as well as the eigenvalues of the system. The eigenvalues will provide the energies and the eigenvectors will provide the associated functions for the discretization chosen for the problem.

When simulating using $N=10$, we obtain the following wavefunctions and energies:

\begin{figure}[H]
  \begin{center}
    \input{numerical-solution-1-wave-function-plot.pgf}
  \end{center}
  \caption{Wave functions for the numerical solution of the one-dimensional, time-independent Schr\"{o}dinger's describing one electron in an infinitely-deep potential well of width $10a$ and discretization of $N=10$}
  \label{numerical-plot}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{l|llllll}\hline
$n$    & $1$    & $2$     & $3$     & $4$      & $5$      & $6$      \\\hline
$E_n$  & $1$  & $3.91898595$  & $8.52047896$  & $14.43169344$  & $21.17373795$  & $28.20041213$ \\\hline
\end{tabular}
\end{center}
  \caption{The first six energy levels calculated for this problem. They roughly match the coefficients that were obtained and listed in Table \ref{analytical-energies}}
  \label{numerical-energies-1}
\end{table}

\subsection{Numerical Solution 2: Two Non-Interacting Electrons}

When an additional, non-interacting electron is introduced, the Hamiltonian changes as follows:

\begin{align*}
  \hat{H} &= -\frac{1}{2}\nabla^{2}_1 -\frac{1}{2}\nabla^{2}_2 + v(x_1) + v(x_2)\\
\end{align*}

A second electron is introduced into the system, meanining that the wave function will also be composed of two coordinates $x_1$ and $x_2$: $\Phi(x_1, x_2)$ The second order differentiation will now have to occur for the wave function with respect to $x_1$ as well as a second time with respect to $x_2$. Therefore, using the work outlined previously, the version of the two, non-interacting electron Schr\"{o}dinger equation is equal to:

\begin{align*}
  -\frac{1}{2}\frac{d^2\Phi(x_1, x_2)}{dx_1^2} + -\frac{1}{2}\frac{d^2\Phi(x_1, x_2)}{dx_2^2} + v(x_1)\Phi(x_1, x_2) + v(x_2)\Phi(x_1, x_2) &= {E}\Phi(x_1, x_2)
  \\ v(x_1) = v(x_2) = v(x) =
  \begin{cases}
          0       \quad \, & |x| < 5a \\
          \infty  \quad \, & |x| > 5a \\
  \end{cases}
\end{align*}

Which discretizes as follows:

\begin{align*}
  -\frac{1}{2}\left[\frac{\Phi(x_1 + \Delta x, x_2) - 2\Phi(x_1, x_2) + \Phi(x_1 - \Delta x, x_2)}{\Delta x^2}\right] + -\frac{1}{2}\left[\frac{\Phi(x1, x_2 + \Delta x) - 2\Phi(x1, x_2) + \Phi(x1, x_2 - \Delta x)}{\Delta x^2}\right] \\ + 2v(x)\Phi(x_1, x_2) = {E}\Phi(x_1, x_2) \\
  -\frac{1}{2}\frac{\Phi(x_1 + \Delta x, x_2) + \Phi(x1, x_2 + \Delta x) - 4\Phi(x_1, x_2) + \Phi(x_1 - \Delta x, x_2) + \Phi(x1, x_2 - \Delta x)}{\Delta x^2} + 2v(x)\Phi(x_1, x_2) = {E}\Phi(x_1, x_2)
\end{align*}

Numerically solving this problem is more complicated than the previous case because now we are solving for two variables: $x_1$ and $x_2$. This bears resemblance to solving the one-dimensional problem in two dimensions. To solve this problem, we construct the wave equation column vector as follows:

\begin{align*}
\ket{\Phi} =
\begin{bmatrix}
\Phi_{0,0}    \\
\Phi_{1,0}    \\
\vdots        \\
\Phi_{N-1,0}  \\
\Phi_{N,0}    \\
\Phi_{0,1}    \\
\Phi_{1,1}    \\
\vdots        \\
\Phi_{N-1,1}  \\
\Phi_{N,1}    \\
\vdots        \\
\Phi_{0,N}    \\
\Phi_{1,N}    \\
\vdots        \\
\Phi_{N-1,N}  \\
\Phi_{N,N}    \\
\end{bmatrix}
\end{align*}

The problem must now take into account the independent positions of the two electrons in the system. This means that we now have $N \times N$ systems of equations to solve for. Using the equation above, the kinetic energy matrix will take the following general form:

\begin{align*}
\left[\scalemath{0.6}{\begin{array}{c c c c c | c c c c c | c c c c c | c | c c c c c | c c c c c | c c c c c}
   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        & \ddots &        &        &        &        & \ddots &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
\hline
    1   &        &        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &    1   &        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        & \ddots &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
\hline
        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
\hline
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        & \ddots &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        \\
\hline
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        &        &        \\
\hline
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        &    1   &        &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        &        &    1   &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        &    1   &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        &        &    1   \\
\hline
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   &        &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        & \ddots &        &        &        &        & \ddots &        &        \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &        &   -4   &    1   \\
        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &        &    1   &        &        &        &    1   &   -4   \\
\end{array}}\right]
\end{align*}

This general form is also known as the sparse matrix for the Laplacian differential operator. Obtaining the eigenvalues and the eigenvectors of the system will provide us with the solutions for the equation. Unfortunately, since we now have two electrons with two different possibilities for their current energy levels, it isn't obvious how to discern between the two. For the following numerical answers, the first six energy levels are calculated from lowest to highest, but the specific values for n for each of the electrons is not evident.

\begin{figure}[H]
  \begin{center}
    \input{numerical-solution-2-wave-function-plot.pgf}
  \end{center}
  \caption{Wave functions for the numerical solution of the one-dimensional, time-independent Schr\"{o}dinger's describing two non-interacting electrons in an infinitely-deep potential well of width $10a$ and discretization of $N=25$. Each plot represents two electrons, with the x and y axis corresponding to the position of each electron in the well: $\Phi_n{x_1,x_2}$.}
  \label{numerical-plot-2}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{l|llllll}\hline
$n$    & $1$    & $2$     & $3$     & $4$      & $5$      & $6$      \\\hline
$E_n$  & $1$  & $3.97946748$  & $5.26546441$  & $5.27606611$  & $8.17405936$  & $8.27969253$ \\\hline
\end{tabular}
\end{center}
  \caption{The first six energy levels calculated for this problem, normalized to the first level. All of the solution energies were computed and these are the first six to come out of the sorting process. The associated plots are related to these values through their $n$ values, although the $n$ value doesn't correlate exactly to the actual $n$ for each electron.}
  \label{numerical-energies-2}
\end{table}

\subsection{Numerical Solution 3: Two Electrons using Coulomb Interaction}

For this last problem, we will now introduce the Coulomb repulsion between the two electrons in the system. This adds a third term to the Hamiltonian as follows:

\begin{align*}
  \hat{H} &= -\frac{1}{2}\nabla^{2}_1 -\frac{1}{2}\nabla^{2}_2 + \frac{1}{\left|\left|\bf{x_1} - \bf{x_2}\right|\right|} + v(x_1) + v(x_2)\\
\end{align*}

This is straightforward to implement. The magnitude of the distance between the two electrons is computed as follows:

\begin{align*}
  \frac{1}{\left|\left|\bf{x_1} - \bf{x_2}\right|\right|} &= \frac{1}{\sqrt{(x_2 - x_1)^2}}
\end{align*}

In the numerical solution, this is implemented as a matrix with a diagonal, where every element of the diagonal computes the Coulomb repulsion for the given $x_1$ and $x_2$ coordinates of each electron. For each row of the matrix, we know what discretization slice is assigned to it.

\begin{figure}[H]
  \begin{center}
    \input{numerical-solution-3-wave-function-plot.pgf}
  \end{center}
  \caption{Wave functions for the numerical solution of the one-dimensional, time-independent Schr\"{o}dinger's describing two interacting electrons (Coulomb repulsion taken into account) in an infinitely-deep potential well of width $10a$ and discretization of $N=25$. Each plot represents two electrons, with the x and y axis corresponding to the position of each electron in the well: $\Phi_n(x_1,x_2)$.}
  \label{numerical-plot-3}
\end{figure}

\begin{table}
\begin{center}
\begin{tabular}{l|llllll}\hline
$n$    & $1$    & $2$     & $3$     & $4$      & $5$      & $6$      \\\hline
$E_n$  & $1$  & $1.36143053$  & $8.65467932$  & $1.93060894$  & $2.30840873$  & $2.60201186$ \\\hline

\end{tabular}
\end{center}
  \caption{The first six energy levels calculated for this problem, normalized to the first level. All of the solution energies were computed and these are the first six to come out of the sorting process. The associated plots are related to these values through their $n$ values, although the $n$ value doesn't correlate exactly to the actual $n$ for each electron.}
  \label{numerical-energies-2}
\end{table}

\section{Discussion}

\begin{itemize}
    \item The analytical solution obtains exact answers, but the problem has been greatly simplified. I don't believe exact answers can be easily obtained for more complicated.
    \item I am unsure of what causes the discretized solution to switch the orientation of the wave function, however, I do recognize that the inverse of the wavefunction is a valid solution to the problem that is presented. By modifying the value for N, I was able to get both orientations of the wavefunction. The likely culprit is the diagonalization algorithm on the Hermitian matrix settling on one solution versus another.
    \item In the two electron case, it makes sense that the electrons would each have their own energy level, which would lead to NxM different possibilities for the first N=M energy levels of each. However, I am unsure how to extract a specific combination of energy levels from the numerical data. When sorting the energy values from low to high, we are sorting the combination of N and M electrons for both electrons.
    \item In the two electron case, I expected there to be symmetry in both axes. Especially in the lowest energy case, where I expected a dome-shaped response. I am unsure why we see a linear gradient type of response. This response was evident as the discretization level was increased, so there is likely an error in the implementation or the Hamiltonian.
    \item When comparing the wavefunctions between the last two numerical solutions, we see that the Coulomb repulsion between the two electrons is highest at $x_1 = x_2$. This manifests as a diagonal line along $x_1 = x_2$ which splits the original wavefunction. Ignoring the sign change between the two wavefunctions, the original wavefunction shape is preserved except for the diagonal where the Coulomb attraction is highest.
\end{itemize}

\newpage
\section{Code Listings and Data}

\subsection{Python Code Listing}
\label{code-listing-python}
The following is the code written in Python to generate the solutions and plots used in this report.
\lstinputlisting[language=Python]{plots.py}

\newpage
\section{References}

These aren't citing anything, but they were useful in helping me figure out this assignment.

\begin{itemize}
    \item\url{https://medium.com/modern-physics/finite-difference-solution-of-the-schrodinger-equation-c49039d161a8}
    \item\url{https://www.12000.org/my_notes/mma_matlab_control/KERNEL/KEse82.htm}
    \item\url{https://digitalcommons.calpoly.edu/cgi/viewcontent.cgi?article=1119&context=physsp}
\end{itemize}

\end{document}


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

% \section*{Fri Oct 18 2019}
\marginpar{Friday\\ 2010-10-18, \\ compiled \\ \today}

% From yesterday: other consequences of inserting \(\Lambda \).
\subsection{Evolution of a dark energy dominated universe}

% Now we have a different approach from Einstein's: we insert the constant not in order to get a static universe but just as a measurable parameter of our theory.
In order to find out how this parameter affects the universe's expansion, we consider a universe in which the only fluid behaves like the cosmological constant.
So, we take the first Friedmann equation \eqref{eq:friedmann-1-cosmological-constant} in the absence of ordinary matter (\(\rho = \rho _\Lambda \)) and with negligible spatial curvature (\(k= 0\)). This yields:

\begin{equation}
  \qty(\frac{\dot{a} }{a})^2 = \frac{\Lambda}{3}
\,.
\end{equation}

This is actually a good approximation for the asymptotic state of the universe, since the cosmological constant term is the only one which does not decay with the scale factor (and so, with time).

The solution to this differential equation is, as we mentioned in section \ref{sec:solutions-to-friedmann-equations}:
%
\begin{equation}
  a(t) = a_{*} \exp(\sqrt{\frac{\Lambda}{3}} \qty(t-t_{*}))
\,,
\end{equation}
%
which can also be written as \(a \propto e^{Ht}\), since \(H = \dot{a} / a = \sqrt{\Lambda / 3}\).
This is called a steady-state solution, since the Hubble parameter is constant.
It is also called a \emph{de Sitter} solution: it belongs to the maximally symmetric 4D spacetime solutions to the Einstein Equations: Minkowski, de Sitter and Anti de Sitter: the latter has \(\Lambda < 0\), the former has \(\Lambda >0\).

This actually seems to model the observed expansion of the universe well, and until recently it competed with the Big Bang theory.

The fraction of the cosmic fluid which behaves like dark energy is bound to increase with time, since as we saw it is the only component which does not decrease in density over time.

% The two other solutions are also called \emph{de Sitter} and look like cosines (?): they can be mapped into each other.

% \todo[inline]{How?}/

This is expressed formally using the so-called \emph{no-hair cosmic theorem}, which is actually a conjecture if it is meant to describe the universe: it states that asymptotically only the dark energy contribution is relevant, all the matter and everything else is forgotten.
In order to interpolate between the current --- matter dominated, or in which at least matter has a sizeable contribution --- universe and the asymptotic one we can use a solution in the form
%
\begin{equation}
  a \propto \qty(\sinh(At))^{2/3}
\,,
\end{equation}
%
where we define \(2A/3 = \sqrt{\Lambda /3} \), since the hyperbolic sine is asymptotically close to an exponential.

\section{Curved models}

We seek solutions to the Friedmann equations for nonzero spatial curvature \(k\), for a universe containing nonrelativistic matter (\(w=0\)) without dark energy.
We make these assumptions since with them we can find an analytic solution; they do not match our observations of the whole universe, but the model we will derive will find an application in chapter \ref{chap:structure-formation}, we will use it to model the collapse of a dark matter halo.

We can rewrite the two independent Friedmann equations as
%
\begin{align}
  \dot{a}^2 &=  \frac{8 \pi G}{3} \rho a^2 - k  \\
  \rho  &= \rho_0 \qty(\frac{a}{a_0 })^{-3}
\,,
\end{align}
%
and now we will solve them with \(k = \pm 1\).

\medskip

\paragraph{Solutions to parametric ODEs}
In general, for an ODE like \(y = f(y')\) for the function \(y=y(x)\) with \(f'\) continuous we introduce \(y' \equiv p\), assuming  \(p \neq 0\): then \(y = f(p)\), which implies
%
\begin{equation}
  y' = \dv{f}{p} p'
  \marginnote{Differentiated both sides of \(y = f(p)\)}
\,,
\end{equation}
%
which we can manipulate to get
%
\begin{equation}
  p = \dv{f}{p} p' \implies \dv{x}{p} = \frac{1}{p} \dv{f}{p}
\,,
\end{equation}
%
so we can get the solution by integration: we get an expression for \(x \) in terms of \(p\), which we will be able to invert since by assumption \(p' \neq 0\): so, we get
%
\begin{equation}
  x = \int   \frac{1}{p} \dv{f}{p}\dd{p}
  \qquad \text{and} \qquad
  y = f(p)
\,.
\end{equation}

\medskip

We use this for our problem: our differential equation looks like
%
\begin{align}
\dot{a}^2 &= \frac{8 \pi G}{3} \rho a^2 - k  \\
\dot{a}^2 &= \frac{8 \pi G}{3} \rho_0 \frac{a_0^3}{a^3}a^2 - k \marginnote{Substituted \(\rho = \rho_0 a_0^3 / a^3\) from the third Friedmann equation.} \\
\dot{a}^2 &=  A a^{-1} - k
\,,
\end{align}
%
where we defined \(A \equiv 8 \pi G a_0^3 \rho_0 /3\).
We can rewrite this as
%
\begin{equation} \label{eq:curved-models-general-ODE}
  a = \frac{A}{p^2+k} = f(p)
  \qquad \text{where} \qquad
  p = \dot{a}
\,.
\end{equation}

Then, using the general formula we get:
%
\begin{align}
t &= \int \frac{1}{p} \dv{f}{p} \dd{p}
\qquad \text{where} \qquad
\dv{f}{p} = -\frac{2Ap}{(p^2+k)^2}  \\
&= \int \frac{-2A}{(p^2+k)^2} \dd{p}
\,.
\end{align}

\subsection{Positive curvature: a closed universe}

If \(k = +1\), then we can make the substitution \(p = \tan(\theta ) \), which is helpful since \(1 + p^2= \sec^2 \theta \); for the change of variable we have \(\dd{p} = \dd{\theta } \sec^2 \theta  \).
So, for the time we find:
%
\begin{align}
  t &= -2A \int \frac{\sec^2\theta \dd{\theta }}{\sec^4\theta } \\
  &= -2A  \int \cos^2(\theta ) \dd{\theta }  = -A \qty(\theta + \sin(\theta ) \cos(\theta ) ) + \const
\,,
\end{align}
%
and we can apply the trigonometric identity \(\sin(\theta ) \cos(\theta ) = \sin(2 \theta ) \):
%
\begin{equation}
  t = -\frac{A}{2} \qty(2 \theta  + \sin(2 \theta ) ) + \const
\,.
\end{equation}

Now we can define \(2 \theta  = \pi - \alpha \), which allows for the simplification \(\sin(2\theta ) = \sin(\alpha )  \); also, we can express \(p=\tan \theta \) in terms of \(\alpha \).
This gives us
%
\begin{align}
t = \frac{A}{2} \qty(\alpha - \sin(\alpha ) ) + \const
\qquad \text{and} \qquad
p = \tan(\frac{\pi}{2} - \frac{\alpha}{2})
\marginnote{Absorbed factor \(-A \pi /2\) into the constant}
\,.
\end{align}
%

We almost have our solution: inserting \(p(\alpha )\) into the main equation for \(a\) \eqref{eq:curved-models-general-ODE} we get
%
\begin{align}
  a &= \frac{A}{1 + \tan^2(\pi /2 - \alpha /2)} = A \cos^2 \qty(\frac{\pi}{2} - \frac{\alpha}{2})
  \marginnote{Used \(1 + \tan^2x = 1/\cos^2x\).}
  \\
  &= \frac{A}{2} \qty(1+\cos(\pi - \alpha ) ) = \frac{A}{2} \qty(1- \cos(\alpha ) )
  \marginnote{Used \(\cos^2(x/2) = (1+\cos x) /2 \) and \(\cos x = - \cos(\pi -x)\).}
\,,
\end{align}
which should be complemented with the equation we found for \(t\): in the end, our solution looks like
%
\begin{align}
t &= \frac{A}{2} \qty(\alpha - \sin \alpha ) + \const  \\
a &= \frac{A}{2} \qty(1 - \cos \alpha )
\,,
\end{align}
%
so, in order to interpret this physically we fix \(t=0 \iff \alpha = 0\), which sets ``const'' to zero, and we reinsert the constants.
In order to do so, we wish to express the constant \(A / 2\) in term of observables such as \(H_0 \) and \(\Omega_0 = \rho_0  / \rho_{0c}\).
We have:
%
\begin{align}
\Omega_0 = \frac{8 \pi G \rho_0 }{3 H_0^2}
\qquad \implies \qquad
A = \frac{8 \pi G a_0^3 \rho_0 }{3} = \Omega_0 H_0^2 a_0^3
\,,
\end{align}
%
which we can simplify by making use of the first Friedmann equation, which reads:
%
\begin{align}
H_0^2 = \frac{8 \pi G}{3} \rho_0 - \frac{k}{a_0 ^2}
\qquad \implies \qquad
1 = \Omega_0 - \frac{1}{a_0^2 H_0^2}
\marginnote{We are treating the case \(k=1\)}
\qquad \implies \qquad
a_0^2H_0^2 = \frac{1}{1 - \Omega_0 }
\,,
\end{align}
%
so we can write \(A/2\) in two different ways:
%
\begin{align}
\frac{A}{2} = \frac{a_0}{2} \frac{\Omega_0 }{1 - \Omega_0 }
= \frac{1}{2 H_0 } \frac{\Omega_0 }{(1-\Omega_0 )^{3/2}}
\,.
\end{align}

We use one of these for \(a\) and the other for \(t\): this is done because it makes the prefactor of the expression manifestly dimensionally consistent with the quantity we are expressing --- this is not always the case when working with \(c=1\).
Then, the expressions for \(a\) and \(t\) become:
%
\begin{align}
  a &= a_0 \frac{\Omega_0}{2 (\Omega_0 -1)} \qty(1- \cos(\alpha ) ) = \widetilde{a}_{0} \frac{1 - \cos \alpha }{2} \\
  t &= \frac{1}{H_0 } \frac{\Omega_0}{2 (\Omega_0 -1)^{3/2}}(\alpha - \sin(\alpha ) )
  = \widetilde{t}_{0} \frac{\alpha - \sin \alpha }{2}
\,.
\end{align}

For the discussion of these results we rename the angle variable from \(\alpha \) to \(\theta \) for historical reasons.
\begin{figure}[ht]
\centering
\includegraphics[width=\textwidth]{figures/positive_curvature_a.pdf}
\caption{A plot of \(a(\theta )\) and \(t(\theta )\).}
\label{fig:positive_curvature_a}
\end{figure}

\begin{figure}[ht]
\centering
\includegraphics[width=\textwidth]{figures/positive_curvature_a_vs_t.pdf}
\caption{A plot of the reparametrization \(a(t)\).}
\label{fig:positive_curvature_a_vs_t}
\end{figure}

We have \(\dot{a} > 0 \)   when \(0 \leq \theta \leq \theta_m = \pi \), while \(\dot{a} < 0\) when \(\theta _m \leq \theta \leq 2 \pi \): so, we call \(\theta_{m}\) the \emph{turn-around} angle.
The angles \(0\) and \(2 \pi \) correspond to the Big Bang and the Big Crunch.

At \(\theta _m\) we have:
%
\begin{align}
  a_m &= \widetilde{a}_{0} =  a_0 \frac{\Omega_0}{\Omega_0 -1}  \\
  t_m &= \frac{\pi}{2} \widetilde{t}_0 = \frac{\pi}{2 H_0 } \frac{\Omega_0}{(\Omega_0 -1)^{3/2}}
\,.
\end{align}

\subsubsection{The age of a closed universe}

The total lifetime of the universe, in this scenario, is equal to \(2 t_m = \pi \widetilde{t}_{0}\). How does this compare to the result we found for a flat universe, namely \(t_0 = 2 / (3 H_0 )\) (equation \eqref{eq:einstein-de-sitter-age} with \(w=0\))?

We set \(a(t) = a_0 \), which means we are normalizing the scale factor to the current one: this yields
%
\begin{align}
1= \frac{\Omega_0}{1-\Omega_0 } \frac{1 - \cos \theta }{2}
\qquad \implies \qquad
\cos \theta = 1 - \frac{2 (\Omega_0 -1)}{\Omega_0 } = \frac{2}{\Omega_0 }-1
\,,
\end{align}
%
so we can invert the cosine (assuming we are in the expanding phase: it is not invertible globally) and insert our expression for \(\theta \) into the expression for the time, to get\footnote{We need to use the expression \(\sin(
\arccos(x)) = \sqrt{1- \cos^2(\arccos x)} = \sqrt{1- x^2}\) with \(x = 2/ \Omega_0 -1\), and then the following manipulation:
%
\begin{align}
\sqrt{1 - \qty(\frac{2}{\Omega_0 }-1)^2} = \sqrt{1 - \frac{4}{\Omega_0^2} + \frac{4}{\Omega_0} -1}
= \frac{2}{\Omega_0 } \sqrt{\Omega_0 -1 }
\,.
\end{align}}
%
\begin{equation} \label{eq:positive-curvature-age}
  t_0 = \frac{1}{2H_0 } \frac{\Omega_0  }{(\Omega_0 -1)^{3/2}} \qty(\arccos (\frac{2}{\Omega_0 }-1) - \frac{2}{\Omega_0 } \sqrt{\Omega_0 -1 })
\,.
\end{equation}

\begin{figure}[ht]
\centering
\includegraphics[width=\textwidth]{figures/curved_universe_age}
\caption{Universe age at the current time as a function of \(\Omega_0 \). For \(\Omega_0>1\) we use the positive curvature model in equation \eqref{eq:positive-curvature-age}: the age is lower than \(2/(3H_0 )\); for \(\Omega_0 <1\) we use the negative curvature model \eqref{eq:negative-curvature-age}: the age is greater than \(2/(3H_0 )\).
The flat model is plotted with a horizontal line for clarity, but if the universe is spatially flat then we must have \(\Omega_0 =1\).}
\label{fig:curved_universe_age}
\end{figure}

As we can see in figure \ref{fig:curved_universe_age}, this means that the estimated age of the universe is lower than \(2/(3H_0 ) \approx \SI{9.6}{Gyr}\), while the measured age of the universe is around \SI{14}{Gyr}.

\subsection{Negative curvature: an open universe}

For \(k = -1\) we do exactly the same steps with hyperbolic functions instead of trigonometric ones, calling the argument of these functions \(\psi \) instead of \(\theta \): we get
%
\begin{align}
  a ( \psi ) &= a \frac{\Omega_0 }{2 (1-\Omega_0)} \qty(\cosh \psi -1) \\
  t (\psi ) &=  \frac{1}{H_0 } \frac{\Omega_0}{2 (\Omega_0 -1)^{3/2}}(\sinh \psi - \psi  )
\,,
\end{align}
%
and as before we can calculate the independent variable with \(\cosh\psi = 2/\Omega_0 -1\).\footnote{A doubt one might have: where does the sign change from \(\theta  - \sin(\theta )\) to \(\sinh(\psi ) - \psi \)?

The difference between the calculations with the trigonometric functions and the hyperbolic functions lies in the substitution \(2 \theta = \pi - \alpha \): in the hyperbolic case we cannot do it this way, since the hyperbolic functions do not have any periodicity like this. Instead, the right substitution looks like \(2 \psi = i \pi + u\), since \(\sinh(i \pi + u) = -\sinh(u)\).

Then, we have the same expressions as before, but their sign is flipped.}

An analogous reasoning to the one before gives us
%
\begin{align} \label{eq:negative-curvature-age}
t_0 = \frac{1}{2H_0 } \frac{\Omega_0}{(1-\Omega_0 )^{3/2}} \qty(\frac{2}{\Omega_0 } \sqrt{1 - \Omega_0 } - \operatorname{arccosh} \qty(\frac{2}{\Omega_0 } -1))
\marginnote{Now \(\sinh(\operatorname{arccossh}(x)) = \sqrt{x^2-1}\)}
\,,
\end{align}
%
which is plotted, again, in figure \ref{fig:curved_universe_age}: in this case \(t_0 > 2 / (3 H_0 )\)! This is then more attractive.

% \todo[inline]{In Pacciani's notes \cite[pag. 26]{paccianiAppuntiCorsoPhysical2018} this is reported with an incorrect global sign.}

\subsection{Considerations on curvature}

The experimental fact that \(t_0 > 2/(3H_0 )\) seems to favour an open universe.
However, the age of the universe is \(t_0 \approx \num{.96} H_0^{-1}\): looking at figure \ref{fig:curved_universe_age} it is clear that in order to account for it with spatial curvature only we would need \(\Omega_0 \ll 1\), and actually \(\Omega_0 < \Omega_{0m}\), where \(\Omega_{0m}\) is the current measured ratio of the density of matter to the critical density.

In fact, in the current \(\Lambda \)CDM model of cosmology this is accounted for using dark energy, which means a positive cosmological constant.

From the second Friedmann equation
%
\begin{align}
\frac{\ddot{a}}{a} =- \frac{4 \pi G}{3} \rho (1+3w)
\,
\end{align}
%
we know that \(\ddot{a} < 0\), that is, the expansion of the universe decelerates if \(w > - 1/3\).
A singular instant at which \(a =0\) must be reached if \(w>-1/3\), while this is not necessarily the case for \(w<-1/3\).
As we will discuss in the next chapter, this will be one of the motivations behind the theory of inflation, which does not require the presence of an initial singularity.

% \todo[inline]{Comment on inflationary theory}

\chapter{The thermal history of the universe}

In the study of the early stages of the universe the variation of the temperature, which determines the distribution of the energies of the collisions of the particles, plays a central role.
It makes sense to talk about temperature when the particles are actually in thermal equilibrium, as they were in the early universe: photons and electrons were continuously Compton-scattering off each other.
After the particles stop continuously interacting we say that they \emph{decoupled}, and each component evolves independently.

The fact that the universe's temperature was much higher in the past is need to explain \emph{primordial nucleosynthesis}: Helium-4 is the outcome of Hydrogen burning but in stellar evolution it is burned into heavier elements after it is formed, so we would expect to see small amounts of it.
Instead, we see a relatively large amount of Helium-4: it makes up about a quarter of the universe by mass.
The primordial universe being very hot helps account for this.
This was first predicted in 1948, in the notorious \(\alpha \beta \gamma \) paper \cite[]{alpherOriginChemicalElements1948}.

\section{Radiation energy density and the equality redshift}

In section \ref{sec:common-equations-of-state} we discussed the evolution of the energy density of matter and radiation, showing that for radiation \(\rho _r (z ) = \rho _{0r} (1+z)^{4}\) while for matter
\(\rho _m (z) = \rho_{0m} (1+z)^{3}\).
We discussed this in the context of electromagnetic radiation, but it describes well the behavior of very relativistic particles, such as neutrinos.

We can define a moment called the \emph{equality redshift} \(z _{\text{eq}}\).
This is when the energy density of radiation and that of matter were equal: \(\rho _r (z _{\text{eq}}) = \rho _m (z _{\text{eq}})\).
This means that
%
\begin{equation}
\rho_{0,r} (1+z _{\text{eq}})^{4} = \rho_{0,m} (1+z _{\text{eq}})^{3} \implies
(1+z _{\text{eq}}) = \frac{\rho _{0,m}}{\rho _{0,r}}
  = \frac{\Omega_{0,m}}{\Omega_{0,r}}
\,,
\end{equation}
%
where we divided and multiplied by the critical density today.

We know that \(\Omega_{0,m}\) is around \num{0.3}, while for the radiation we can deduce the density from the spectrum of the CMB.

Accounting for everything, we think that
%
\begin{equation}
  1 + z _{\text{eq}} \simeq \num{2.3e4} \Omega_{0, m} h^2
  \approx 3370
\,.
\end{equation}

The value is that obtained from the Planck Collaboration \cite[]{adePlanck2015Results2016}.

This means that the recombination of electrons and protons into Hydrogen, which occurred around redshift \(z _{\text{CMB}} \approx 1090\), happened when the universe was already \emph{matter dominated} --- specifically, the density of matter was \(\approx 3\) times that of radiation.

Another interesting time is \(z_\Lambda \), when the energy density due to the cosmological constant equalled that of matter:  \(\rho _m (z_{\Lambda }) = \rho _\Lambda (z_\Lambda )\), which is calculated with the same reasoning as \(z _{\text{eq}}\), recalling that \(\rho_{\Lambda }\) is a constant with respect to the redshift:
\begin{equation}
1+ z_\Lambda = \qty(\frac{\rho_{0, \Lambda }}{\rho_{0,m}})^{1/3} \simeq \qty(\frac{0.7}{0.3})^{1/3} \approx \num{0.33}
\,.
\end{equation}

This is relatively close, in cosmological terms: the comoving distance corresponding to this redshift is around \SI{1350}{Mpc}, less than \SI{10}{\percent} of the comoving distance to the CMB.

% The model which won out is the \emph{hot Big Bang} model.

What is the temperature of a radiation-dominated universe?
From the Stefan-Boltzmann law we know that \(\rho _r \propto T^{4}\), while as we have discussed previously \(\rho _r \propto a^{-4}\).
Therefore, we expect \(T \propto 1/a\) to hold: this is known as \emph{Tolman's law}.
In this chapter we will discuss how this does approximately hold, but we need to make some corrections due to the annihilation of ultrarelativistic particles.

We know that in a radiation dominated universe \(a \propto t^{1/2}\), which means that \(T \propto t^{-1/2}\).

We shall describe the pressure \(P\), number density \(n\) and energy density \(\rho  \) in the universe, as functions of the chemical potentials \(\mu \) and of  the temperature \(T\).
We will use natural units, so that \(c= \hbar = k_B = 1\): so, temperatures and masses will be measured in electronVolts.

This is very convenient, since it allows us to make the following consideration: when the temperature will larger than the mass of a certain elementary particle, statistically that type of particle will usually be ultra-relativistic.

This section will mostly follow Weinberg's book \cite[page 538, section 15.6]{weinbergGravitationCosmologyPrinciples1972}.

\section{Thermodynamics in the early universe}

We will express the quantities mentioned above: \(P\), \(\rho \) and \(n\) in terms of the distribution of particles in phase space: in general the phase space for a single particle in 3D is six-dimensional, but we operate under the assumption that the cosmological principle holds, so by homogeneity the spatial dependence of the distribution function can be neglected.
Thus, we can talk of densities,\footnote{Also, as a general rule, one should avoid talking about ``global quantities'': the universe is, in principle, infinite, so we should refer at most to what is or could be inside our light cone. It is better to work in terms of densities.} neglecting the spatial position, and integrating over momentum space to gather all the information there is to know about the particles in that position.

\subsection{Number density, energy density and pressure}

\subsubsection{Number density}

If \(f(\vec{q})\) is the distribution density of particles with three-dimensional momentum \(\vec{q}\), the number density of particles is given by:
%
\begin{equation}\label{eq:number-density-momentum-space}
  n = \frac{g}{(2 \pi )^3} \int \dd[3]{q} f(\vec{q}, T, \mu )
\,,
\end{equation}
%
where the parameter \(g\) is the number of helicity states: it is the number of particles we can have with different quantum numbers, after fixing momentum and position.

This essentially is our choice for the normalization of the distribution function.
We include the factor \((2\pi)^3 \) in order to normalize the integral: the number of particles, a pure number, is given by
%
\begin{align}
N \propto \int \dd[3]{q} \dd[3]{x}  f(\vec{q}, \vec{x})
\,,
\end{align}
%
so the right hand side's differentials have the dimensions of an action cubed: we need to normalize them, and the conventional action used to do so is \(h = 2 \pi \hbar\).
So, when we set \(\hbar = 1\) we get a factor \((2\pi )^3\) on the denominator.
Do note that the \(\dd[3]{x}\) integral, giving a volume, is brought to the left in our expression to give a number density.

\subsubsection{The number of helicity states}

The only quantum number which can vary after fixing those if we are considering an elementary particle is the spin component \(s_z\); therefore if the total spin is \(s\) we should have \(2s+1\) possible spin states.
For example  electrons, which have spin \(1/2\), will have \(g = 2s+1 = 2\).

% We will have to integrate  over position and momentum: the metric we will get in the end must not depend on anything but time, by the cosmological principle.

Things, however, are more complicated than this: for photons, we only have two spin states (\(g=2\)) even though they have \(s=1\), since \(s_z=0\) is unphysical for a photon.
Gravitons also have \(g=2\) even though their total spin is \(s=2\): this is because \(\abs{s_z} \leq 1 \) is unphysical for a graviton.
In general for massless particles Lorentz invariance guarantees the fact that transverse modes cannot exist, since we cannot go in the rest frame of the particle.\footnote{Some more details on this: if we measure the spin component \(s_z\) to be equal to some value in a certain reference frame, then this will mean: (1) if \(s_z \neq 0 \) we need a rotation of at least \(2 \pi / s_z\) around the \(z\) axis in order to recover the system we started with, while (2) if \(s_z=0\) the system is symmetric with respect to rotations around the \(z\) axis.

So, for a photon to have \(s_z=0\) we would need to be in a frame in which its wavefunction was cylindrically symmetric. This cannot be the case if the photon is travelling in the \(z\) direction, so we must be in the rest frame of the photon, which does not exist.

Similarly, for gravitons the argument as to why \(s_z \neq 0\) still applies, and we can exclude the spins \(\abs{s_z} = 1\) by the following argument: in full generality we can remove all the gauge freedom in a gravitational wave by going to TT gauge, and we can show that in TT gauge the wave is symmetric under rotations of angle \(\pi \) about the \(z\) axis.
Therefore, the spin of the graviton must be at least \(2\) in magnitude.}

Even for massive particles we do not always have \(g = 2s+1\): \(g\) accounts for all internal degrees of freedom, and as the temperature drops below a certain value we need to consider composite particles as well: for atoms we also have vibration, rotation and such. These all contribute to \(g\).

\subsubsection{Energy density}

The energy density is given by
%
\begin{equation} \label{eq:energy-density-momentum-space}
  \rho = \frac{g}{(2 \pi )^3} \int \dd[3]{q} E(q) f(\vec{q}, T, \mu )
\,,
\end{equation}
%
where \(E^2 = q^2 + m^2\)\footnote{Particles are on-shell, that is they obey the equations of motion (which is not mandatory, and this is what Quantum Mechanics is all about).}.
For photons \(E = q\), for nonrelativistic particles \(E \approx m + q^2 / 2m\).
Here we are denoting the modulus of the momentum vector as \(q = \abs{\vec{q}}\).

This formula is a weighted average of the energies on the distribution function on the momenta.

\subsubsection{Pressure}

The adiabatic pressure is
%
\begin{equation}\label{eq:pressure-momentum-space}
  P = \frac{g}{(2 \pi )^3} \int \dd[3]{q} \frac{q^2 f(\vec{q}, T, \mu )}{3E(q)}
\,.
\end{equation}

\begin{bluebox}
This comes from a consideration of the diagonal components of the stress energy tensor of an ideal fluid: we know that
%
\begin{align}
T^{\mu \nu }
= \left[\begin{array}{cccc}
\rho  & 0 & 0 & 0 \\
0 & P & 0 & 0 \\
0 & 0 & P & 0 \\
0 & 0 & 0 & P
\end{array}\right]
= \frac{g}{(2\pi )^3} \expval{ \int \frac{\dd[3]{q}}{E(\vec{q})} f(\vec{q}) p^{\mu } (\vec{q}) p^{\nu } (\vec{q})}
\,,
\end{align}
%
where \(p^{\mu } = (E(q), \vec{q})\) is the momentum vector.
Although it may not look like it, this formula is covariant.\footnote{we are integrating a tensorial expression (\(f p^{\mu } p^{\nu }\) is a tensor) with respect to a covariant integration element: \(\dd[3]{q} / E(q)\) is a scalar with respect to Lorentz transformations, since it can be obtained as
%
\begin{align}
\dd[4]{q} \delta (E^2 - p^2 - m^2) = \frac{ \dd[3]{q}}{2E} \delta (E - \sqrt{m^2+p^2})
\,.
\end{align}
}
The average sign is meant to indicate a spatial average, across volumes which are wide enough for homogeneity to hold.

This formula reproduces equation \eqref{eq:energy-density-momentum-space} for \(\mu = \nu = 0\): indeed, in this case \(p^{0} (q) = E(q)\).
The off-diagonal components are zero by isotropy: if they were not, we would see heat and particle flow in specific directions.

So, for the diagonal components spatial components the integrand looks like \(q^{i} q^{j} / E(q)\).

The formula for the pressure then follows by isotropy: the total force per unit area to go around is \(q^2 / E\), and it must be distributed equally in the three spatial directions, so if we want to switch from the directional integral \(T^{ii} = P \propto \int q^{i} q^{i} / E\) (not summed over \(i\)) to an integral of the modulus of the momentum, \(P \propto \int q^2 / E\) we must divide by 3.
\end{bluebox}

% Alternatively, we can say that this comes from imposing \(\dd{E} = P \dd{V} + \dd{Q} \).

This definition gives us \(P = \rho /3\) for photons directly, which can be seen by substituting \(E = q\).

\subsubsection{The distribution function}

If the particles are in thermal equilibrium, the distribution in momentum space will be given by the following expression:
%
\begin{equation}
  f(\vec{q}) = \qty(\exp(\frac{E(q)- \mu }{T}) \pm 1 )^{-1}
\,,
\end{equation}
%
where we have a plus for fermions, and a minus for bosons. Here, \(\mu = \pdv*{\rho }{n}\) is the chemical potential, the derivative of the energy (density) with respect to a change in the number (density) of particles: is becomes relevant when the gas becomes hot and dense, if it is sparse then adding particles does not affect the energy.

% It can be introduced as a Lagrange multiplier for changes in number of particles.

The Planck distribution, which describes the statistics of photons, is consistent with this, since it is given by:
%
\begin{equation}
  f_k(\vec{q}) = \qty(\exp(\frac{q}{T}) -1 )^{-1}
\,,
\end{equation}
%
since they are bosons with no chemical potential.\footnote{This may seem weird at first: is the Planck function not
%
\begin{align}
B_{\nu } (T) = \frac{2\nu^3}{e^{ 2 \pi \nu / T} -1 }
\,
\end{align}
%
in natural units?
Well, these two are actually equivalent formulations. To see this, recall that in natural units \(q = E = \omega = 2 \pi \nu \) for a photon. First of all, they describe different physical quantities: the Planck function describes the \emph{spectral radiance}, \(\dd{E} = B_\nu (T) \dd{t} \dd{A} \dd{\nu } \dd{\Omega }\), while the distribution \(f(q)\) describes the number density of particles per unit momentum volume: \(\dd{N} = f(q) \dd[3]{q}\).

To check their equivalence, let us compute the energy density with both:
%
\begin{align}
\rho &=  \frac{g}{(2\pi )^3} \int \frac{q}{e^{q/T}-1} \dd{\Omega } q^2 \dd{q} = \frac{2}{(2\pi )^3}\int \frac{ \omega^3}{e^{q/T}-1} \dd{\Omega } \dd{q}
= \int \frac{2 \nu^3}{e^{2 \pi \nu /T}-1} \dd{\Omega } \dd{q}
\\
\text{but also}\quad\rho &= \dv{E}{V} = \int \frac{ \dd{E}}{ \dd{t} \dd{A} \dd{q} \dd{\Omega }} \dd{q} \dd{\Omega } = \int B_q(T) \dd{\Omega } \dd{q}
\,,
\end{align}
%
where we used the fact that, in natural units \(\dd{V} = \dd{t} \dd{A}\).
}
The fact that the distribution of photons is indeed described by this distribution with \(\mu =0\) is a way to experimentally determine the fact that the chemical potential of photons is indeed zero. If we observed the distribution for physical blackbodies to have \(\mu \neq 0\) this would be called a \emph{spectral distortion}. The CMB is wonderfully consistent with \(\mu =0\), it is actually the best Planckian in Nature.

It is a fact that the chemical potential \(\mu \) can be neglected when dealing with the early universe. Let us justify this.

In general, we can say that if for some chemical species we have the reaction \(i+j \leftrightarrow k+l\), and we reach chemical equilibrium, then the chemical potentials of the species will be connected by \(\mu _i + \mu _j = \mu _k + \mu _l\): this is called the \textbf{Saha equation}.

Assuming that we are in thermal equilibrium is not in general valid, we will do so in our discussion for simplicity, but non-equilibrium dynamics must be considered when dealing with CMB anisotropies.
Although the assumption does not perfectly hold, this is quite instructive: the CMB spectrum is very close to an equilibrium blackbody spectrum, the deviations from equilibrium are small.

By enumerating all the possible chemical reactions between the various particle types we will get a system of equations for their chemical potentials, complemented with some known facts, such as the fact that photons have \(\mu_{\gamma }=0\), which is the case since they do not interact with each other.

For example, from the annihilation of electron and positron \(e^{+}+ e^{-} \leftrightarrow 2 \gamma \) we can derive a relation between the chemical potentials of \(e^{+}\) and \(e^{-}\):  \(\mu _{e^{+}} = - \mu_{e^{-}}\).

% This rule is not trivial; it is an ansatz of thermodynamical equilibrium to get a solution of the Boltzmann equation which allows us to write the Saha equations.

\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2003-2018 by The University of Queensland
% http://www.uq.edu.au
%
% Primary Business: Queensland, Australia
% Licensed under the Apache License, version 2.0
% http://www.apache.org/licenses/LICENSE-2.0
%
% Development until 2012 by Earth Systems Science Computational Center (ESSCC)
% Development 2012-2013 by School of Earth Sciences
% Development from 2014 by Centre for Geoscience Computing (GeoComp)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Steady-state Heat Refraction}
\label{STEADY-STATE HEAT REFRACTION}

In this chapter we demonstrate how to handle more complex geometries.

Steady-state heat refraction will give us an opportunity to investigate some of
the richer features that the \esc package has to offer. One of these is \pycad .
The advantage of using \pycad is that it offers an easy method for developing
and manipulating complex domains. In conjunction with \gmsh we can generate
finite element meshes that conform to our domain's shape providing accurate
modelling of interfaces and boundaries. Another useful function of \pycad is
that we can tag specific areas of our domain with labels as we construct them.
These labels can then be used in \esc to define properties like material
constants and source locations.

We proceed in this chapter by first looking at a very simple geometry. Whilst a
simple rectangular domain is not very interesting the example is elaborated upon
later by introducing an internal curved interface.

\section{Example 4: Creating the Domain with \pycad}
\label{example4}
\sslist{example04a.py}
We modify the example in Chapter~\ref{CHAP HEAT 2a} in two ways: we look at the
steady state case with slightly modified boundary conditions and use a more
flexible tool to generate the geometry. Let us look at the geometry first.

We want to define a rectangular domain of width $5 km$ and depth $6 km$ below
the surface of the Earth. The domain is subject to a few conditions. The
temperature is known at the surface and the basement has a known heat flux. Each
side of the domain is insulated and the aim is to calculate the final
temperature distribution.

In \pycad there are a few primary constructors that build upon each other to
define domains and boundaries. The ones we use are:
\begin{python}
from esys.pycad import *
Point() #Create a point in space.
Line() #Creates a line from a number of points.
CurveLoop() #Creates a closed loop from a number of lines.
PlaneSurface() #Creates a surface based on a CurveLoop
\end{python}
So to construct our domain as shown in \reffig{fig:pycad rec}, we first need to
create the corner points. From the corner points we build the four edges of the
rectangle. The four edges then form a closed loop which defines our domain as a
surface. We start by inputting the variables we need to construct the model.
\begin{python}
width=5000.0*m   #width of model
depth=-6000.0*m  #depth of model
\end{python}

\begin{figure}[ht]
\centerline{\includegraphics[width=4.in]{figures/pycadrec}}
\caption{Example 4: Rectangular Domain for \pycad}
\label{fig:pycad rec}
\end{figure}

The variables are then used to construct the four corners of our domain, which
from the origin has the dimensions of $5000$ meters width and $-6000$ meters
depth. This is done with the \verb|Point()| function which accepts x, y and z
coordinates. Our domain is in two dimensions so z should always be zero.
\begin{python}
# Overall Domain
p0=Point(0.0,      0.0, 0.0)
p1=Point(0.0,    depth, 0.0)
p2=Point(width, depth, 0.0)
p3=Point(width,   0.0, 0.0)
\end{python}
Now lines are defined using our points. This forms a rectangle around our
domain:
\begin{python}
l01=Line(p0, p1)
l12=Line(p1, p2)
l23=Line(p2, p3)
l30=Line(p3, p0)
\end{python}
Note that lines have a direction. These lines form the basis for our domain
boundary, which is a closed loop.
\begin{python}
c=CurveLoop(l01, l12, l23, l30)
\end{python}
Be careful to define the curved loop in an \textbf{anti-clockwise} manner
otherwise the meshing algorithm may fail.
Finally we can define the domain as
\begin{python}
rec = PlaneSurface(c)
\end{python}
At this point the introduction of the curved loop seems to be unnecessary but
this concept plays an important role if holes are introduced.

Now we are ready to hand over the domain \verb|rec| to a mesher which
subdivides the domain into triangles (or tetrahedra in 3D). In our case we use
\gmsh. We create an instance of the \verb|Design| class which will handle the
interface to \gmsh:
\begin{python}
from esys.pycad.gmsh import Design
d=Design(dim=2, element_size=200*m)
\end{python}
The argument \verb|dim| defines the spatial dimension of the domain\footnote{If
\texttt{dim}=3 the rectangle would be interpreted as a surface in the three
dimensional space.}. The second argument \verb|element_size| defines the element
size which is the maximum length of a triangle edge in the mesh. The element
size needs to be chosen with care in order to avoid very dense meshes. If the
mesh is too dense, the computational time will be long but if the mesh is too
sparse, the modelled result will be poor. In our case with an element size of
$200$m and a domain length of $6000$m we will end up with about $\frac{6000m}{200m}=30$
triangles in each spatial direction. So we end up with about $30 \times 30 =
900$ triangles which is a size that can be handled easily.
The domain \verb|rec| can simply be added to the \verb|Design|;
\begin{python}
d.addItem(rec)
\end{python}
We have the plan to set a heat flux on the bottom of the domain. One can use
the masking technique to do this but \pycad offers a more convenient technique
called tagging. With this technique items in the domain are named using the
\verb|PropertySet| class. We can then later use this name to set values
specifically for those sample points located on the named items. Here we name
the bottom face of the domain where we will set the heat influx
\footnote{In some applications, eg.
when dealing with influxes,
it is required to have the surface being meshed without the need of explicitly
name the surface. In this case the line forming the surface of the domain need to be
added to the \texttt{Design}
using \texttt{d.addItem(rec, l01, l12, l23, l30)}}:
\begin{python}
ps=PropertySet("linebottom",l12))
d.addItem(ps)
\end{python}
Now we are ready to hand over the \verb|Design| to \FINLEY:
\begin{python}
from esys.finley import MakeDomain
domain=MakeDomain(d)
\end{python}
The \verb|domain| object can now be used in the same way like the return object
of the \verb|Rectangle| object we have used previously to generate a mesh. It
is common practice to separate the mesh generation from the PDE solution.
The main reason for this is that mesh generation can be computationally very
expensive in particular in 3D. So it is more efficient to generate the mesh
once and write it to a file. The mesh can then be read in every time a new
simulation is run. \FINLEY supports this in the following
way\footnote{An alternative is using the \texttt{dump} and \texttt{load}
functions. They work with a binary format and tend to be much smaller.}:
\begin{python}
# write domain to a text file
domain.write("example04.fly")
\end{python}
and then for reading in another script:
\begin{python}
# read domain from text file
from esys.finley import ReadMesh
domain =ReadMesh("example04.fly")
\end{python}

Before we discuss how to solve the PDE for this problem, it is useful to
present two additional options of the \verb|Design| class.
These allow the user to access the script which is used by \gmsh to generate
the mesh as well as the generated mesh itself. This is done by setting specific
names for these files:
\begin{python}
d.setScriptFileName("example04.geo")
d.setMeshFileName("example04.msh")
\end{python}
Conventionally the extension \texttt{geo} is used for the script file of the
\gmsh geometry and the extension \texttt{msh} for the mesh file. Normally these
files are deleted after usage.
Accessing these files can be helpful to debug the generation of more complex
geometries. The geometry and the mesh can be visualised from the command line
using
\begin{verbatim}
gmsh example04.geo  # show geometry
gmsh example04.msh  # show mesh
\end{verbatim}
The mesh is shown in \reffig{fig:pycad rec mesh}.

\begin{figure}[ht]
\centerline{\includegraphics[width=4.in]{figures/simplemesh}}
\caption{Example 4a: Mesh over rectangular domain, see \reffig{fig:pycad rec}}
\label{fig:pycad rec mesh}
\end{figure}
\clearpage

\section{The Steady-state Heat Equation}
\sslist{example04b.py, cblib}
A temperature equilibrium or steady state is reached when the temperature
distribution in the model does not change with time. To calculate the steady
state solution the time derivative term in \refEq{eqn:Tform nabla} needs to be
set to zero;
\begin{equation}\label{eqn:Tform nabla steady}
-\nabla \cdot \kappa \nabla T = q_H
\end{equation}
This PDE is easier to solve than the PDE in \refEq{eqn:hdgenf2}, as no time
steps (iterations) are required. The \verb|D| term from \refEq{eqn:hdgenf2} is
simply dropped in this case.
\begin{python}
mypde=LinearPDE(domain)
mypde.setValue(A=kappa*kronecker(model), Y=qH)
\end{python}
The temperature at the top face of the domain is known as \verb|Ttop|~($=20 C$).
In \refSec{Sec:1DHDv0} we have already discussed how this constraint is added
to the PDE:
\begin{python}
x=Solution(domain).getX()
mypde.setValue(q=whereZero(x[1]-sup(x[1])),r=Ttop)
\end{python}
Notice that we use the \verb|sup| function to calculate the maximum of $y$
coordinates of the relevant sample points.

In all cases so far we have assumed that the domain is insulated which
translates into a zero normal flux $-n \cdot \kappa \nabla T$, see
\refEq{eq:hom flux}. In the modelling set-up of this chapter we want to set
the normal heat flux at the bottom to \verb|qin| while still maintaining
insulation at the left and right face. Mathematically we can express this as
\begin{equation}
-n \cdot \kappa \nabla T = q_{S}
\label{eq:inhom flux}
\end{equation}
where $q_{S}$ is a function of its location on the boundary. Its value
becomes zero for locations on the left or right face of the domain while it has
the value \verb|qin| at the bottom face.
Notice that the value of $q_{S}$ at the top face is not relevant as we
prescribe the temperature here.
We could define $q_{S}$ by using the masking techniques demonstrated
earlier. The tagging mechanism provides an alternative and in many cases more
convenient way of defining piecewise constant functions such as
$q_{S}$. Recall now that the bottom face was denoted with the name
\verb|linebottom| when we defined the domain.
We can use this now to create $q_{S}$;
\begin{python}
qS=Scalar(0,FunctionOnBoundary(domain))
qS.setTaggedValue("linebottom",qin)
\end{python}
In the first line \verb|qS| is defined as a scalar value over the sample points
on the boundary of the domain. It is initialised to zero for all sample points.
In the second statement the values for those sample points which are located on
the line marked by \verb|linebottom| are set to \verb|qin|.

The Neumann boundary condition assumed by \esc has the form
\begin{equation}\label{NEUMAN 2b}
n\cdot A \cdot\nabla u = y
\end{equation}
In comparison to the version in \refEq{NEUMAN 2} we have used so far the right
hand side is now the new PDE coefficient $y$. As we have not specified $y$ in
our previous examples, \esc has assumed the value zero for $y$. A comparison of
\refEq{NEUMAN 2b} and \refEq{eq:inhom flux} reveals that one needs to choose
$y=-q_{S}$;
\begin{python}
qS=Scalar(0,FunctionOnBoundary(domain))
qS.setTaggedValue("linebottom",qin)
mypde.setValue(y=-qS)
\end{python}
To plot the results we use the \modmpl library as shown in
\refSec{Sec:2DHD plot}. For convenience the interpolation of the temperature to
a rectangular grid for contour plotting is made available via the
\verb|toRegGrid| function in the \verb|cblib| module. Your result should look
similar to \reffig{fig:steady state heat}.

\begin{figure}[ht]
\centerline{\includegraphics[width=4.in]{figures/simpleheat}}
\caption{Example 4b: Result of simple steady state heat problem}
\label{fig:steady state heat}
\end{figure}
\clearpage