\documentclass[]{article}
\usepackage{natbib}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
%opening
\title{\texttt{vsmodel} Derivation}
\author{Matt James}

\begin{document}

\maketitle

This document describes the derivation of the model equations for the \texttt{vsmodel} package.

\section{Derivation of the Model}

In this section we derive the components of the Volland-Stern electric field model \citep{Volland1973,Stern1975} in cylindrical coordinates. The Volland-Stern model starts with an electrostatic potential, $U(r,\phi)$, from which the electric field is obtained using

\begin{equation}
	\mathbf{E} = - \mathbf{\nabla} U, \label{EqEField}
\end{equation}

where

\begin{equation}
	\mathbf{\nabla} U = \frac{\partial U}{\partial r} \mathbf{\hat{r}} + \frac{1}{r} \frac{\partial U}{\partial \phi} \mathbf{\hat{\phi}} + \frac{\partial U}{\partial z}\mathbf{\hat{z}}. \label{EqDelU}
\end{equation}

The coordinate system is such that $z$ lies along the dipole axis of the planet; $x$ points approximately sunward where the magnetic equatorial plane intersects the plane containing both the dipole axis and the Earth-Sun line; the $y$ axis points approximately duskward. In cylindrical coordinates: $r$ is the radial distance from the $z$ axis (i.e. $r = \sqrt{x^2 + y^2}$); $\phi$ is the azimuth, equal to 0 at noon where $\phi = \arctan{y,x}$.

The potential, $U$, is made up of a corotational component, $U_{cor}$, and a convection component, $U_{cnv}$. The corotation component used here is defined by

\begin{equation}
	U_{cor} = -\frac{a}{r},
\end{equation}

where $a=92.4$~keV is the corotation constant used in \citet{Zhao2017}.

The electric field due to corotation, $\mathbf{E_{cor}}$, is given by:
\begin{align}
	E_r &= -\frac{a}{r^2}, \\
	E_\phi &= 0,\\
	E_z &= 0,
\end{align}
where $\mathbf{E_{cor}} = [E_r,E_\phi,E_z]$.

There are two options for the convection component of this model - the simpler option is from \citet{Maynard1975} and is derived in section \ref{SectMC}; the more complicated option described by \citet{Goldstein2005} separates the convection component into solar wind electric field (section \ref{SectSW}) and SAPS (section \ref{SectSAPS}) parts. The overall electric field is simply obtained by adding the separate components of the model, i.e. $\mathbf{E} = \mathbf{E_{cor}} + \mathbf{E_{cnv}}$.

\section{The \citet{Maynard1975} $\mathbf{E}$-field}
\label{SectMC}
This section describes the electric field due to convection as described by \citet{Maynard1975}. The potential used is

\begin{equation}
	U_{mc} = -A_{mc} r^\gamma \sin{\phi}, \label{EqMCPot}
\end{equation}

where

\begin{equation}
	A_{mc} = \frac{0.045}{(1.0 - 0.159 Kp + 0.0093 K_p^2)^3} \text{ (kV $R_E^{-2}$)}
\end{equation}

and $\gamma=2$ is the shielding parameter.

The electric field components become
\begin{align}
	E_r &= \gamma A_{mc} r^{(\gamma-1)}\sin{\phi},\\
	E_\phi &= A_{mc} r^{(\gamma-1)} \cos{\phi},\\
	E_z &= 0.
\end{align}

\section{Solar Wind Electric Field}
\label{SectSW}
This section uses the electric field due to the solar wind propagation past the Earth as described in \citet{Goldstein2005}. The electric field due to the solar wind is given by,

\begin{equation}
	E_{sw} = -V_{sw} B_z,
\end{equation}

where $V_{sw}$ is the $x$ component of the solar wind velocity (negative Sunward), and $B_z$ is the north-south component of the interplanetary magnetic field (IMF). $E_{sw}$ has a minimum value of 0.1~mV~m$^{-1}$, so when the IMF is northward there is still a little bit of a viscous interaction with the magnetosphere.

The potential is given by
\begin{equation}
	U_{sw} = -A_{sw} r^2 \sin{\phi},
\end{equation}
where
\begin{equation}
	A_{sw} = 0.12 E_{sw} (6.6)^{(1-\gamma)}, \text{ (kV $R_E^{-2}$)}
\end{equation}
and $E_{sw}$ in this case should be converted from mV~m$^{-1}$ to kV~$R_E^{-1}$.

The electric field components become
\begin{align}
E_r &= \gamma A_{sw} r^{(\gamma-1)}\sin{\phi},\\
E_\phi &= A_{sw} r^{(\gamma-1)} \cos{\phi},\\
E_z &= 0.
\end{align}

\section{SAPS Electric Field}
	\label{SectSAPS}
	This section uses the electrostatic potential due to SAPS as described in \citet{Goldstein2005},

	\begin{equation}
		U_{saps}(r,\phi,K_p) = -V_s(K_p) F(r,\phi,K_p) G(\phi),
	\end{equation}

	where

	\begin{align}
		V_s(Kp) &= 0.75 K_p^2 \text{ (in kV)}, \\
		F(r,\phi,K_p) &= \frac{1}{2} + \frac{1}{\pi}\arctan{\left[\frac{2}{\alpha(\phi,K_p)}\left\{ r - R_s(\phi,K_p)\right\}\right]}, \\
		G(\phi) &= \sum_{m=0}^{2} \left\{A_m \cos{[m(\phi - \phi_0)]} + B_m \sin{[m(\phi-\phi_0)]} \right\},
	\end{align}

	and

	\begin{align}
		\alpha(\phi,K_p) &= 0.15 + (2.55 - 0.27 K_p)\left[1 + \cos{\left(\phi - \frac{7\pi}{12}\right)}\right], \\
		R_s(\phi,K_p) &= R_0(K_p)\left(\frac{1+\beta}{1 + \beta\cos{(\phi-\pi)}}\right)^\kappa, \\
		R_0(K_p) &= 4.4 - 0.6(K_p - 5) \text{ (in $R_E$)},\\
		A_m &= [0.53,0.37,0.1],\\
		B_m &= [0.0,0.21,-0.1],\\
		\phi_0 &= \frac{\pi}{2}, \\
		\beta &= 0.97,\\
		\kappa &= 0.14.
	\end{align}

	The cylindrical components of the electric field are given by,

	\begin{align}
		E_r &= V_s(K_p)\frac{\partial F(r,\phi,K_p)}{\partial r} G(\phi),\\
		E_\phi &= \frac{1}{r} V_s \left[ F(r,\phi,K_p)\frac{\text{d} G(\phi)}{\text{d} \phi} + \frac{\partial F(r,\phi,K_p)}{\partial \phi} G(\phi) \right],\\
		E_z &= 0.
	\end{align}

	\subsection{Derivatives: $\frac{\partial F}{\partial r}$}
		\begin{align}
			\frac{\partial F}{\partial r} &= \frac{\partial}{\partial r} \left(\frac{1}{2} + \frac{1}{\pi}\arctan{\left[\frac{2}{\alpha}\left\{r - R_s\right\}\right]}\right) \\
			&= \frac{\partial}{\partial r}\left(\frac{1}{2} + \frac{1}{\pi}\arctan\left[f\right]\right) \\
			&= 0 + \frac{1}{\pi}\left(\frac{\partial}{\partial f}\arctan{f}\right)\frac{\partial f}{\partial r},
		\end{align}

		where

		\begin{equation}
			\frac{\partial }{\partial f} \arctan{f} = \frac{1}{1 + f^2},
		\end{equation}

		and

		\begin{equation}
			\frac{\partial f}{\partial r} = \frac{2}{\alpha}.
		\end{equation}

		So,

		\begin{equation}
			\boxed{\frac{\partial F}{\partial r} = \frac{2}{\alpha \pi} \left[\frac{1}{1 + f^2}\right].}
		\end{equation}

	\subsection{Derivatives: $\frac{\partial F}{\partial \phi}$}

		\begin{align}
			\frac{\partial F}{\partial \phi} &= \frac{\partial}{\partial \phi} \left(\frac{1}{2} + \frac{1}{\pi}\arctan{\left[\frac{2}{\alpha}\left\{r - R_s\right\}\right]}\right) \\
			&= \frac{\partial}{\partial \phi}\left(\frac{1}{2} + \frac{1}{\pi}\arctan\left[f\right]\right) \\
			&= 0 + \frac{1}{\pi}\left(\frac{\partial}{\partial f}\arctan{f}\right)\frac{\partial f}{\partial \phi},
		\end{align}

		where

		\begin{align}
			\frac{\partial }{\partial f} \arctan{f} &= \frac{1}{1 + f^2}, \\
			\frac{\partial f}{\partial \phi} &= \frac{\partial }{\partial \phi} (g(\phi,K_p) h(\phi,K_p)), \\
			&= \frac{\partial g}{\partial \phi}h + g\frac{\partial h}{\partial \phi},\\
			\frac{\partial g}{\partial \phi} &= \frac{\partial}{\partial \phi} \left(\frac{2}{\alpha}\right) = \frac{\partial g}{\partial \alpha} \frac{\partial \alpha}{\partial \phi} = -\frac{2}{\alpha^2}\frac{\partial \alpha}{\partial \phi}, \\
			\frac{\partial h}{\partial \phi} &= -\frac{\partial R_s}{\partial \phi}.
		\end{align}

		\begin{equation}
			\boxed{\therefore 	\frac{\partial F}{\partial \phi} = \frac{1}{\pi} \left(\frac{1}{1+f^2}\right) \left[\frac{-2}{\alpha^2}\frac{\partial \alpha}{\partial \phi} h - g \frac{\partial R_s}{\partial \phi} \right].}
		\end{equation}

	\subsection{Derivatives: $\frac{\partial R_s}{\partial \phi}$}

		\begin{align}
			\frac{\partial R_s}{\partial \phi} &= R_0 \frac{\mathrm{d}}{\mathrm{d} \phi} \left\{ \left(\frac{1+\beta}{1 + \beta\cos{(\phi-\pi)}}\right)^\kappa \right\} = R_0 \frac{\mathrm{d}}{\mathrm{d} S} \left\{ S^\kappa \right\} \frac{\mathrm{d} S}{\mathrm{d} \phi}, \\
			S &= \frac{1+\beta}{1 + \beta\cos{(\phi-\pi)}} = \frac{p}{q}, \\
			\frac{\mathrm{d}}{\mathrm{d} S} \left\{ S^\kappa \right\} &= \kappa S^{(\kappa -1)} = \kappa \left(\frac{1+\beta}{1 + \beta\cos{(\phi-\pi)}}\right)^{\kappa-1},\\
			\frac{\mathrm{d} S}{\mathrm{d} \phi} &= \frac{\frac{\text{d} p}{\text{d} \phi}q - p \frac{\mathrm{d} q}{\mathrm{d} \phi}}{q^2} = -\frac{p}{q^2} \frac{\mathrm{d} q}{\mathrm{d} \phi} = \frac{1 + \beta}{(1 + \beta\cos{(\phi - \pi)})^2} \cdot \beta \sin{(\phi - \pi)},
		\end{align}

		\begin{equation}
			\boxed{\therefore \frac{\partial R_s}{\partial \phi} = -R_0\frac{1}{q}\frac{\mathrm{d} q}{\mathrm{d} \phi} \kappa \left( \frac{p}{q} \right)^{\kappa}  = R_0 \frac{(1 + \beta)\beta \sin{(\phi - \pi)}}{(1 + \beta\cos{(\phi - \pi)})^2} \kappa \left(\frac{1+\beta}{1 + \beta\cos{(\phi-\pi)}}\right)^{\kappa-1}.}
		\end{equation}

	\subsection{Derivatives: $\frac{\partial \alpha}{\partial \phi}$}

		\begin{equation}
			\boxed{\frac{\mathrm{d} \alpha}{\mathrm{d} \phi} = -(2.55 - 0.27 K_p)\sin{\left(\phi - \frac{7\pi}{12}\right)}}
		\end{equation}

	\subsection{Derivatives: $\frac{\mathrm{d} G}{\mathrm{d} \phi}$}

		\begin{equation}
			\boxed{\frac{\mathrm{d} G}{\mathrm{d} \phi} = \sum_{m=0}^{2} \left\{-m A_m \sin{[m(\phi - \phi_0)]} + m B_m \cos{[m(\phi-\phi_0)]} \right\}.}
		\end{equation}

\section{SM Model Field}

	The previous section describes the model in cylindrical coordinates, here we convert the model to SM coordinates by rotating about the $z$-axis.

	Considering an Electric field vector $\mathbf{E}(r,\phi)$ with components $E_r$ and $E_\phi$ -- we need to rotate this vector by $\phi$ to transform into SM coordinates.

	Start by expressing the components of $\mathbf{E}$ in terms of some polar coordinates $\rho$ and $\alpha$:

	\begin{align}
		E_r &= \rho \cos{\alpha}, \label{EqEr}\\
		E_\phi &= \rho \sin{\alpha}, \label{EqEp}
	\end{align}

	then rotate by $\phi$,

	\begin{align}
		E_x &= \rho \cos{(\alpha + \phi)}, \label{EqEx0}\\
		E_y &= \rho \sin{(\alpha + \phi)}. \label{EqEy0}
	\end{align}

	Using the trigonometric identities,

	\begin{align}
		\sin{(\alpha \pm \phi)} &= \sin\alpha\cos\phi \pm \cos\alpha\sin\phi, \\
		\cos{(\alpha \pm \phi)} &= \cos\alpha\cos\phi \mp \sin\alpha\sin\phi,
	\end{align}

	equations \ref{EqEx0} and \ref{EqEy0} become

	\begin{align}
		E_x &= \rho\cos\alpha\cos\phi - \rho\sin\alpha\sin\phi, \\
		E_y &= \rho\sin\alpha\cos\phi + \rho\cos\alpha\sin\phi.
	\end{align}

	Then, substituting in equations \ref{EqEr} and \ref{EqEp}, gives

	\begin{align}
		E_x &= E_r\cos\phi - E_\phi\sin\phi, \\
		E_y &= E_r\sin\phi + E_\phi\cos\phi.
	\end{align}

\bibliographystyle{agu08}
\bibliography{references}
\end{document}


\iffalse
Noether's theorem says that continuous symmetries of physical systems gives rise to conservation laws. In this class we'll see some examples of low dimensional Lie groups and how they give rise to various phenomenon in physics like time dilation and length contraction in special relativity, spin states of electrons.

Keywords: bilinear forms, signature, SO(2), SO(3), Spin, SO(1,3), Minkowski space and relativity, Noether's theorem, Lie groups.

Prereqs: Linear algebra, Group theory
Homework: Recommended
\fi

\input{../preamble}
\DeclareMathOperator{\re}{Re}

\begin{document}
\title{Inverses of polynomials}
\author{Apurva Nakade}
\thispagestyle{fancy}
\maketitle

Today's goal is to build Riemann surfaces on which inverses of polynomials $f(z)$ can be well defined.

\section{Riemann surface for $\log z$}
If we try to define $\log z$ naively using polar coordinates we get
\begin{align}
	\log (re^{i \theta}) & = \log r + i \theta
\end{align}
We have a discontinuity at $\theta = 0$ and $\theta = 2 \pi$ so we need to make a branch cut, say at $\theta = 0$, to get a well defined function. For $\theta$ varying in the range $(0,2\pi)$ we get one branch function. We get other (distinct) branches by adding multiples of $2 \pi$ to $\theta$.
\begin{align}
	\log (re^{i \theta}) & = \log r + i (\theta + 2 n \pi)
\end{align}
To create a Riemann surface on which $\log z$ is well defined we need $\Z$ many copies of $\C$, on which we make branch cuts and glue them together.

\section{Winding numbers}
In order to generalize the above situation to more complicated functions we analyze what is happening here. For this we need the notions of winding numbers.

Consider a non-constant complex differentiable function $f:\C \rightarrow \C$. Fix a point $p \in \C$ be a complex number. Let $\gamma:[0,2\pi] \rightarrow \C$ with $\gamma(0) = \gamma(2\pi)$ be an embedded loop in $\C$ (no self intersections) containing $p$ in it's interior that goes counterclockwise. We say that $\gamma$ is \textbf{sufficiently close} to $p$ if there are no points $p' \neq p$ in the interior of $\gamma$ such that $f(p) = f(p')$.

\begin{proposition}
	For all points $p \in \C$ there exists a loop $\gamma$ sufficiently close to $p$.
\end{proposition}
\begin{proof}
	Consider the function $g(z) = f(z) - f(p)$. The zeroes of this complex differentiable function are exactly the points $p'$ such that $f(p') = f(p)$. Complex differentiable functions have isolated zeroes and hence $p$ has a neighborhood $U$ which does not contain any other zero of $g$. Any loop $\gamma$ in $U$ is sufficiently close to $p$.
\end{proof}

\begin{definition}
	Let $\gamma$ be a loop sufficiently close to $p$. The composition $f \circ \gamma$ is a loop around $f(p)$ (not necessarily embedded). The \textbf{winding number} $w_f(p)$ is the number of counterclockwise revolutions made by $f \circ \gamma$ around $f(p')$ minus the number of clockwise revolutions.
\end{definition}

\begin{proposition}
	Without any loss of generality assume that $p=0$ and $f(p) = 0$. Let $\gamma(t)$  be a loop sufficiently close to $p$ then the winding number is given by
	\begin{align}
		\label{eq:winding}
		w_f(0) & = \dfrac{\log(f ( \gamma(2 \pi))) - \log(f ( \gamma(0)))}{2 \pi i}
	\end{align}
	where $\log(z)$ is any branch of the logarithm.
\end{proposition}
\begin{proof}
	For every single counterclockwise revolution $\log(z)$ increases by $2 \pi i$ and for every single counterclockwise revolution $\log(z)$ decreases by $ 2 \pi i$. The result follows.
\end{proof}

\begin{example}
	For the function $f(z) = z^n$ the winding number around 0 is $n$ and the winding number around $p \neq 0$ is 1.
\end{example}

\subsection{Points with winding number $> 1$}
For the function $z^n$ the only complex number $z$ for which the winding number is bigger than 1 is $z=0$ and this is the point where we've to make a branch cut. This suggests that to define inverses of more complicated functions we need to figure out the points at which the winding number is greater than 1.

Let $f(z)$ be a complex differentiable function. Consider a point $p \in \C$ and let $f(z) = \sum \limits_{i=0}^\infty a_i (z-p)^i$ be the Taylor series of near $p$.

\begin{proposition}
	\label{thm:windingNum}
	The winding number of $w_f(p)$ is the smallest non-zero integer $i$ such that $a_i \neq 0$.
\end{proposition}
\begin{proof}
	By shifting origin if necessary assume that $p=0$ and $f(p) = 0$ so that the Taylor expansion looks like $$f(z) = \sum \limits_{i=n}^\infty a_i z^i = z^n \sum \limits_{i=n}^\infty a_i z^{i-n} = z^n g(z) $$ for some $n > 0$ where $a_n \neq 0$ and $g(z) = \sum \limits_{i=n}^\infty a_i z^{i-n}$. The function $g(z)$ has the property that $g(0) \neq 0$. If we choose a loop $\gamma$ sufficiently close to $0$ such that $g(\gamma(t))$ stays very close to $g(0)$ then $g(z)$ is almost constant non-zero number and hence the winding number $w_f(p) = w_{z^n}(p)$ which equals $n$.
\end{proof}

With this proposition the points with winding number bigger than 1 are easily determined.
\begin{cor}
	$w_f(p) > 1$ iff $f'(p) = 0$ i.e. the points with winding number bigger than 1 are exactly the critical points of $f$.
\end{cor}

\section{Covering spaces}
Consider the function $f(z) = z^n$. For any non-zero $p$ the set $f^{-1}(p)$ contains exactly $n$ elements $p_1, \cdots, p_n$. More is true, there exists a neighborhood $U \ni p$ such that $f^{-1}(U)$ is isomorphic to $n$ non-intersecting neighborhoods of the $n$ points $U_1 \ni p_1, \cdots, U_n \ni p_n$. Furthermore the restriction of the map $f|_{U_i}$ is an isomorphism\footnote{homeomorphism}. These properties define what is called a covering space.

\begin{definition}
	A map $p: X \rightarrow Y$ is a \textbf{covering map} if for every point $y \in Y$ there exists a neighborhood $U \ni y$ such that
	\begin{enumerate}
		\item $p^{-1}(U)$ is a disjoint union of subsets $\{ V_i \}_{i \in I}$ of $X$ for some indexing set $I$
		\item The restriction $p|_{V_i} : V_i \rightarrow U$ is an isomorphism for each $i \in I$.
	\end{enumerate}
	$X$ is called a \textbf{covering space} of $Y$.\\
\end{definition}

\begin{center}
	\begin{tabular}{ccc}
		\includegraphics[width=0.35\linewidth]{images/covering_space} & $\qquad \qquad$ &
		\includegraphics[width=0.25\linewidth]{images/branched_covering_space} \\
		$\qquad \qquad \qquad$ Covering Space                         &                 & Branched Covering Space
	\end{tabular}
\end{center}

So the map $z^n : \C \setminus \{ 0\} \rightarrow \C \setminus \{ 0 \}$ is a covering map. A map which is a covering map at all points except some isolate ones is called a \textbf{branched covering}. So $z^n: \C \rightarrow \C$ is a branched covering.

More generally every complex differentiable function $f(z):\C \rightarrow \C$ is a branched covering and it's restriction to the complement of critical points of $f(z)$ is a covering map.

\subsection{Monodromy}
Consider again the function $z^n: \C \rightarrow \C$. Consider a loop around the origin in the \textbf{target} complex plane passing through $z=1$. If we traverse the loop once and try to lift the loop back up to the domain $z$ then the loop does not remain a loop but becomes a path connecting 1 to the root of unity $e^{2 \pi i/n}$. In this we say that the covering $z^n$ has non-trivial \textbf{monodromy}. Monodromy is the mathematical reason why need to glue complex planes to create Riemann surfaces.\footnote{There is in fact a monodromy group that is acting upon the various sheets via permuting them.}

\subsection{Constructing the Riemann surface}

So the strategy to define the inverse of a polynomial $f(z)$ is the following:
\begin{enumerate}
	\item Find the critical points of $f(z)$
	\item On the non-critical points $f(z)$ is a covering map, find the number of \emph{sheets} over each point using winding numbers
	\item Make branch cuts at each critical point and glue the sheets of complex plane to get a Riemann surface.
\end{enumerate}

\section{Exercises}

\begin{exercise}
	Show that the winding number of $f(z) = z^n$ at $p \in \C$ is equal to
	\begin{align}
		w_f(p) = \dfrac{1}{2 \pi i} \int_{\gamma} \dfrac{f(z)}{(z-p)^{n+1}} dz
	\end{align}
	$\gamma$ is a loop sufficiently close to $p$.

	Prove this formula for an arbitrary complex differentiable function $f(z)$.
\end{exercise}

\begin{exercise}
	Fill in the gaps in the proof of Proposition \ref{thm:windingNum}.
\end{exercise}

\begin{exercise}
	Construct Riemann surfaces for the following polynomials:
	\begin{enumerate}
		\item $f(z) = z^2 - 2 z$
		\item $f(z) = z^3 - 3z$
	\end{enumerate}
\end{exercise}

\end{document}


% !TeX spellcheck = en_US
\documentclass[]{report}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{amssymb}

\begin{document}
% TODO: Better section names
\section{Maxwell's Equations as Groundwork}
% TODO: Clarify why we wont look at the other two of Maxwell's equations
As with any problem in the field of electro-magnetics we will start with \textit{Maxwell's equations}. Of interest here are only the time-varying equations, i.e. \textit{Ampere's circuital law} and \textit{Faraday's law of induction}:
\begin{align}
	\nabla \times \mathbf{H} &= \frac{\partial \mathbf{D}}{\partial t} + \mathbf{J} \\
	\nabla \times \mathbf{E} &= -\frac{\partial \mathbf{B}}{\partial t} \text{ .}
\end{align}
It is noticeable that there are five unknown quantities to be determined (electric field \(\mathbf{E}\), magnetic induction \(\mathbf{B}\), electric displacement field \(\mathbf{D}\), magnetic field \(\mathbf{H}\) and current density \(\mathbf{J}\)) with only two equations. The missing three equations are the following \textit{constitutive} relations
\begin{align}
	\mathbf{D} &= \varepsilon \mathbf{E} \\
	\mathbf{B} &= \mu \mathbf{H} \\
	\mathbf{J} &= \sigma \mathbf{E}
\end{align}
% TODO: Explain epsilon, mu, sigma
that lead us to the following formulation of Maxwell's equations:
\begin{align}
	\nabla \times \mathbf{H} &= \varepsilon \frac{\partial \mathbf{E}}{\partial t} + \sigma \mathbf{E} \\
	\nabla \times \mathbf{E} &= -\mu \frac{\partial \mathbf{H}}{\partial t} \text{ .}
\end{align}
% TODO: Describe permittivity and permeability
After unfurling the curl operations we get to the following system of six equations
\begin{align}
	\partial_y E_z - \partial_z E_y &= -\mu \partial_t H_x \\
	\partial_z E_x - \partial_x E_z &= -\mu \partial_t H_y \\
	\partial_x E_y - \partial_y E_x &= -\mu \partial_t H_z \\
	\partial_y H_z - \partial_z H_y &= \varepsilon \partial_t E_x + \sigma E_x \\
	\partial_z H_x - \partial_x H_z &= \varepsilon \partial_t E_y + \sigma E_y \\
	\partial_x H_y - \partial_y H_x &= \varepsilon \partial_t E_z + \sigma E_z
\end{align}
that will function as basis for any of the following discretizations. Note that \(\partial_x\) is a shorthand for the partial derivation operator \(\frac{\partial}{\partial x}\).

\section{Plane Wave as First Example}
To gain an understanding of the \textit{FDTD} (finite-difference time-domain) method, we will work through progressively harder examples starting from a simple one-dimensional plane wave in free space. The electric and magnetic field are perpendicular to the direction of propagation in a plane wave, a property known as \textit{TEM} (transverse electro-magnetic).
% TODO: Image for demonstration

If we pick the \(z\)-axis as direction of propagation and assume a linear polarization of the electric field in the direction of the \(x\)-axis, we can strike any component of the electric field in the \(y,z\)-axis as well as the perpendicular magnetic field in the \(x,z\)-axis. Furthermore, any spatial derivative in another direction than the \(z\)-axis can be discarded and since we're looking at a wave in free space, the conductivity \( \sigma \) is null.

% TODO: Reference
Finally, the large system above can be reduced to just two equations
\begin{align}
	-\partial_z H_y &= \varepsilon \partial_t E_x \\
	\partial_z E_x  &= -\mu \partial_t H_y
\end{align}
which will be discretized in a staggered manner in both space and time by using a finite difference (e.g. central-difference approximation)
% TODO: Reference the approximation
to obtain the discrete equations
\begin{align}
	-\frac{H_y^{n}(k+1/2) - H_y^n(k-1/2)}{\Delta z} &= \varepsilon \frac{E_x^{n+1/2}(k)-E_x^{n-1/2}(k)}{\Delta t} \\
	\frac{E_x^{n+1/2}(k+1)-E_x^{n+1/2}(k)}{\Delta z}  &= -\mu \frac{H_y^{n+1}(k+1/2)-H_y^{n}(k+1/2)}{\Delta t}
\end{align}
where the superscript gives the instant in time \( t = \Delta t \cdot n \) and the function parameter gives the position in the grid \( z = \Delta z \cdot k \). Notice that the calculation of the electric and magnetic field is interleaved in a similar way as you would think about the propagation of an electro-magnetic wave, where a time-varying electric field causes a time-varying magnetic field which again causes a time-varying electric field and so on.

The calculation here will therefore proceed as such: (1) determine the electric field at instant \( n+1/2 \), (2) with that determine the magnetic field at instant \( n+1 \), and so on. The spatial grid is also interleaved between electric and magnetic field but the underlying reasoning will be left to the 3D-formulation, where it can be more easily grasped visually.

Let's rearrange to clarify this approach:
\begin{align}
	E_x^{n+1/2}(k) &= E_x^{n-1/2}(k) - \frac{\Delta t}{\varepsilon \Delta z}\left( H_y^n(k+1/2) - H_y^n(k-1/2) \right) \\
	H_y^{n+1}(k+1/2) &= H_y^n(k+1/2) - \frac{\Delta t}{\mu \Delta z}\left( E_x^{n+1/2}(k+1) - E_x^{n+1/2}(k) \right) \text{ .}
\end{align}
% TODO: Reference
It can be seen that the first equation only depends on field values of the past and that the second equation only depends on the result of the first equation and field values of the past.

The time step \( \Delta t \) is chosen to fulfill the \textit{CFL} (Courant-Friedrichs-Lewy) condition
\begin{equation}
	c \frac{\Delta t}{\Delta z} \leq 1
\end{equation}
which in our case leads to a maximum time step of
\begin{equation}
	\Delta t = \frac{\Delta z}{c}
\end{equation}
where \( c \) is the speed of light. This essentially guarantees that a wave can not pass more than one interval of size \( \Delta z \) in a single time step \( \Delta t \).

% TODO: Reference
Insertion into the relevant part of equations [REF] yields:
\begin{align}
	\frac{\Delta t}{\varepsilon \Delta z} &= \frac{1}{c \cdot \varepsilon} = \sqrt{\frac{\mu_0}{\varepsilon_0}} \frac{1}{\varepsilon_r} = \frac{Z_0}{\varepsilon_r} \\
	\frac{\Delta t}{\mu \Delta z} &= \frac{1}{c \cdot \mu} = \sqrt{\frac{\varepsilon_0}{\mu_0}} \frac{1}{\mu_r} = \frac{1}{Z_0 \mu_r}
\end{align}
where \( Z_0 \approx 376.73 \Omega \) refers to the impedance of free space.

\section{Simulations}
Now we just have to set up a grid of values for permittivity and permeability and one or more sources and we can start doing some examples.

% TODO: do a new section here, and one above

\end{document}


\begin{appendices}

{\let\cleardoublepage\relax}
\appendix
\chapter{}
\section{Estimation}

 \citeauthor*{ac} \cite{ac}
\blindtext

\begin{comment}
\begin{figure}[H]
\begin{center}
  \includegraphics[width=0.2\linewidth]{pixelnb.png}
  \caption{The square neighborhood used for spatial denoising.}
  \label{fig:lbpschem}
\end{center}
\end{figure}
\end{comment}

\begin{equation}
	\bar{\mathbf{c}} = \frac{1}{N}\sum_{c \in Nb(c_{ij}) }c
\end{equation}

\begin{equation}
	\mathbf{K}_{ij} = \frac{1}{N-1}\sum_{c \in Nb(c_{ij})}(c-\bar{c}_{ij})(c-\bar{c}_{ij})^T
\end{equation}
\noindent We denote the noiseless value of the same pixel as $\mathbf{c}_{ij}^{d}$. We can estimate the posterior probability of the noiseless pixel given the observed noise pixel $p(\mathbf{c}_{ij}^{d}|\mathbf{c}_{ij})$ taking into account the Bayesian theorem. Assuming normal distribution for the a priori probability of the noiseless value $p(\mathbf{c}_{ij}^{d})$ as $\mathbf{c}_{ij}^{d}\sim \mathcal{N} (\bar{\mathbf{c}}, \mathbf{K}_{ij})$ and likelihood $p(\mathbf{c}_{ij}|\mathbf{c}_{ij}^{d})$ with mean set as the noisy pixel value and covariance set as the additive noise covariance as $p(\mathbf{c}_{ij}|\mathbf{c}_{ij}^{d}) = \mathcal{N} (\mathbf{c}_{ij}, \mathbf{K}_{n})$, Bayesian theorem gives:
\begin{align}
	p(\mathbf{c}_{ij}^{d}|\mathbf{c}_{ij}) &= \frac{p(\mathbf{c}_{ij}^{d})p(\mathbf{c}_{ij}|\mathbf{c}_{ij}^{d})}{p(\mathbf{c}_{ij})} \nonumber \\
		&= \mathcal{N} (\mathbf{W}_{ij}(\mathbf{c}_{ij}-\bar{\mathbf{c}})+\bar{\mathbf{c}}, \mathbf{K}_{ij} - \mathbf{W}_{ij}\mathbf{K}_{ij})
\end{align}

\blindtext

\section{Skin Conditions Included in the Study}
\blindtext

\begin{table}[h!]
\centering
\caption{The skin conditions included in our dataset.}
\label{tabl:diseases}
	\begin{tabular}{l c c c c}
 		\toprule %\hline
 		 Macropathology Diagnosis & Anatomical Location \\ [0.5ex]
 		\midrule %\hline
 		one & Exposed skin \\
 		one & Exposed skin \\
 		\bottomrule %\hline
	\end{tabular}
\end{table}

\noindent \blindtext

\end{appendices}


\section{Particle Swarm Optimization}
\label{sec:PSOAlg}
Particle Swarm Optimization (PSO) algorithms are population-based
probabilistic optimization algorithms first proposed by
Kennedy and Eberhart~\cite{EberhartKennedy1995,KennedyEberhart1995}
to solve problem $\mathbf P_c$ defined in~\eqref{sub:Proc} with
possibly discontinuous cost function $f \colon \Re^n \to \Re$.
In Section~\ref{sec:PSOBin}, we will present a PSO algorithm
for discrete independent variables
to solve problem $\mathbf P_d$ defined in~\eqref{sub:Prod},
and in Section~\ref{sec:PSOConDis} we will present a PSO algorithm for
continuous and discrete independent variables
to solve problem $\mathbf P_{cd}$ defined in~\eqref{sub:Procd}.
To avoid ambiguous notation, we always denote the dimension of the
continuous independent variable by $n_c \in \Na$
and the dimension of the
discrete independent variable by
$n_d \in \Na$.\\

PSO algorithms exploit a set of potential solutions
to the optimization problem.
Each potential solution is called a {\em particle}, and the set
of potential solutions in each iteration step is called a {\em population}.
PSO algorithms are global optimization algorithms and
do not require nor approximate gradients of the cost function.
The first population is typically initialized using a random number generator to
spread the particles uniformly in a user-defined hypercube.
A particle update equation, which is modeled
on the social behavior of members
of bird flocks or fish schools,
determines the location of each particle in the next generation.\\

A survey of PSO algorithms can be found in
Eberhart and Shi~\cite{EberhartShi2001}.
Laskari et. al. present a PSO algorithm for
minimax problems~\cite{LaskariEtAl2002:1} and for
integer programming~\cite{LaskariEtAl2002:2}.
In~\cite{ParsopoulosVrahatis2002:2}, Parsopoulos and Vrahatis discuss the
implementation of inequality and equality constraints
to solve problem $\mathbf P_{cg}$ defined in~\eqref{sub:Procg}.\\

We first discuss the case where the independent variable is continuous,
i.e., the case of problem $\mathbf P_c$ defined in~\eqref{sub:Proc}.

% --------------------------------------------
\subsection{PSO for Continuous Variables}

We will first present the initial version of the PSO algorithm
which is the easiest to understand.

In the initial version of the PSO
algorithm~\cite{EberhartKennedy1995,KennedyEberhart1995},
the update equation for the particle location is as follows:
Let $k \in \Na$ denote the generation number,
let $n_P \in \Na$ denote the number of particles in each generation,
let $x_i(k) \in \Re^{n_c}$, $i \in \{ 1, \ldots, n_P\}$,
denote the $i$-th particle of the $k$-th generation,
let $v_i(k) \in \Re^{n_c}$ denote its velocity,
let $c_1, c_2 \in \Re_+$ and let
$\rho_1(k), \rho_2(k) \sim U(0,1)$ be uniformly distributed random numbers
between $0$ and $1$.
Then, the update equation is, for all $i \in \{1, \ldots, n_P\}$ and
all $k \in \Na$,
\begin{subequations}
\begin{eqnarray}
  v_i(k+1) & = & v_i(k) + c_1 \, \rho_1(k) \, \bigl( p_{l,i}(k) - x_i(k) \bigr)
 \nonumber \\
&&
  + c_2 \, \rho_2(k) \, \bigr( p_{g,i}(k) - x_i(k) \bigr), \\
  x_i(k+1) & = & x_i(k) + v_i(k+1),
\end{eqnarray}
  \label{sub:psoOriUpdEqn}
\end{subequations}
where $v_i(0) \triangleq 0$ and
\begin{subequations}
  \begin{eqnarray}
    p_{l,i}(k) & \triangleq & \argmin_{x \in \{ x_i(j) \}_{j=0}^k} f(x), \\
    p_{g,i}(k) & \triangleq & \argmin_{x \in \{ \{ x_i(j) \}_{j=0}^k \}_{i=1}^{n_P} } f(x).
\label{eq:PSOGloBesIni}
  \end{eqnarray}
\end{subequations}
Thus, $p_{l,i}(k)$ is the location that for the $i$-th particle yields the lowest
cost over all generations,
and $p_{g,i}(k)$ is the location of the best particle over all generations.
The term $c_1 \,  \, \rho_1(k) \, ( p_{l,i}(k) - x_i(k) )$ is associated
with cognition since it takes into account the particle's own experience,
and the term
$c_2 \, \rho_2(k) \, ( p_{g,i}(k) - x_i(k))$ is associated with
social interaction between the particles.
In view of this similarity, $c_1$ is called
{\it cognitive acceleration constant} and
$c_2$ is called {\it social acceleration constant}.\\

% ----------------------------
\subsubsection{Neighborhood Topology}
\begin{subequations}
The minimum in~\eqref{eq:PSOGloBesIni} need not be taken over all
points in the population.
The set of points over which the minimum is taken is defined by
the {\it neighborhood topology}.
In PSO, the neighborhood topologies are usually defined
using the particle index, and not the particle location.
We will use the {\it lbest}, {\it gbest}, and the {\it von Neumann}
neighborhood topology, which we will now define.\\

In the {\it lbest} topology of size $l \in \Na$, with $l > 1$,
the neighborhood of a particle with index $i \in \{1, \ldots, n_P \}$
consist of all particles whose index are in the set
\begin{equation}
  \mathcal N_i \triangleq \{ i-l, \ldots i, \ldots , i+l \},
\label{eq:defLBestNeiHoo}
\end{equation}
where we assume that the indices wrap around, i.e., we replace
$-1$ by $n_P-1$, replace $-2$ by $n_P-2$, etc.\\

In the {\it gbest} topology, the neighborhood contains all
points of the population, i.e.,
\begin{equation}
\mathcal N_i \triangleq \{ 1, \ldots , n_P \},
\end{equation}
for all $i \in \{1, \ldots, n_P \}$.\\

For the {\it von Neumann} topology,
consider a $2$-dimensional lattice,
with the lattice points enumerated as shown in Figure~\ref{fig:PSOTopology}.
We will use the von Neumann topology of range $1$, which is defined,
for $i,j \in \mathbb Z$, as the set
of points whose indices belong to the set
\begin{equation}
\mathcal N_{(i,j)}^v \triangleq \left\{(k,l) \ \Bigl| \ | k - i | + | l - j | \le 1,
 \ k,l \in \mathbb Z \right\}.
\label{eq:defVonNeuNei}
\end{equation}
The gray points in Figure~\ref{fig:PSOTopology} are $\mathcal N_{(1,2)}^v$.
For simplicity, we round in GenOpt the user-specified number of
particles $n_P' \in \mathbb N$
to the next biggest integer $n_P$ such that
$\sqrt n_P \in \Na$ and $n_P \ge n_P'$.\footnote{In principle,
the lattice need not be a square,
but we do not see any computational disadvantage of selecting a square lattice.}
Then, we can wrap the indices by replacing, for $k \in \mathbb Z$,
$(0,k)$ by $(\sqrt n_P, k)$,
$(\sqrt n_P + 1,k)$ by $(1, k)$, and similarly by replacing
$(k,0)$ by $(k, \sqrt n_P)$ and
$(k, \sqrt n_P + 1)$ by $(k, 1)$.
Then, a particle with indices $(k,l)$,
with $1 \le k \le \sqrt n_P$ and $1 \le l \le \sqrt n_P$,
has in the PSO algorithm the index $i = (k-1) \, \sqrt n_P + l$, and
hence $i \in \{1, \ldots, n_P \}$.\\
\label{sub:PSONeiHooDef}
\end{subequations}

\begin{figure}
\centering
\begin{pspicture}(-1, 1)(7,-5)
%%\psgrid
% draw dots
{\psset{fillcolor=lightgray, fillstyle=solid}
 \multido{\iX=0+1}{3}{%
   \rput(4,-\iX){%
     \rput(0,-\iX){%
       \pscircle(0,0){0.5}%
     }%
   }%
 }%
 \multido{\iX=1+1}{3}{%
   \rput(\iX,-2){%
     \rput(\iX,0){%
       \pscircle(0,0){0.5}%
     }%
   }%
 }%
}
\multido{\iX=1+1}{2}{%
  \multido{\iY=1+1}{3}{%
    \rput(\iY,-\iX){%
      \rput(\iY,-\iX){%
        \pscircle(0,0){0.5}%
        \psline(0,-0.5)(0,-1)%
        \psline(0,0.5)(0,1)%
        \psline(-0.5,0)(-1,0)%
        \psline(0.5,0)(1,0)%
      }%
    }
  }%
}%
\multido{\iX=0+1}{3}{%
  \multido{\iY=0+1}{4}{%
    \rput(\iY,-\iX){%
      \rput(\iY,-\iX){%
        \rput(0,0){\iX,\iY}%
      }%
    }
  }%
}%
 {%
   \psset{linestyle=dashed}%
   \multido{\iX=0+1}{4}{%
     \rput(\iX,0){%
     \rput(\iX,0){%
       \pscircle(0,0){0.5}%
       \psline(0,-0.5)(0,-1)%
       \psline(0,0.5)(0,1)%
       \psline(-0.5,0)(-1,0)%
       \psline(0.5,0)(1,0)%
     }%
   }%
 }%
 \multido{\iX=0+1}{3}{%
   \rput(0,-\iX){%
     \rput(0,-\iX){%
       \pscircle(0,0){0.5}%
       \psline(0,-0.5)(0,-1)%
       \psline(0,0.5)(0,1)%
       \psline(-0.5,0)(-1,0)%
       \psline(0.5,0)(1,0)%
     }%
   }%
 }%
}%
\end{pspicture}
\caption{Section of a $2$-dimensional lattice of particles with $\sqrt n_P \ge 3$.
The particles belonging to the von Neumann neighborhood
$\mathcal N_{(1,2)}^v$ with range $1$,
defined in~\eqref{eq:defVonNeuNei},
are colored gray.
Indicated by dashes are the particles that are generated by wrapping the indices.}
\lab{fig:PSOTopology}
\end{figure}

Kennedy and Mendes~\cite{KennedyMendes2002} show that greater connectivity of
the particles speeds up convergence, but it does not tend to improve
the population's ability to discover the global optimum.
Best performance has been achieved with the von Neumann topology, whereas
neither the {\it gbest} nor the {\it lbest} topology seemed especially good in
comparison with other topologies.

Carlisle and Dozier~\cite{CarlisleDozier2001} achieve on unimodal
and multi-modal functions for the
{\it gbest} topology better results than for the {\it lbest} topology.

% ----------------------------
\subsubsection{Model PSO Algorithm}

We will now present the Model PSO Algorithm that is implemented in GenOpt.

\begin{subequations}
\noindent
\begin{minipage}[b]{\textwidth}
\begin{algorithm}
[Model PSO Algorithm for Continuous Variables]
~\\
{\em
\begin{tabularx}{\headwidth}{m{2cm}l}
\multicolumn{2}{l}{\hspace{\textwidth}~} \\ \\[-8ex]\\
\hline \\[-2ex]
 \textbf{Data}:
     & Constraint set $\mathbf X$, as defined in~\eqref{eq:setXPc},\\
     & but with finite lower and upper bound for each independent variable.\\
     & Initial iterate $x_0 \in \mathbf X$.\\
     & Number of particles $n_P \in \Na$ and number of generations $n_G \in \Na$.\\
  \textbf{Step 0}:
     & Initialize $k=0$, $x_0(0) = x_0$ and
     the neighborhoods $\{ \mathcal N_i \}_{i=1}^{n_P}$ .\\
  \textbf{Step 1}:
     & Initialize $\{ x_i(0) \}_{i=2}^{n_P} \subset \mathbf X$ randomly distributed.\\
  \textbf{Step 2}:
     & For $i \in \{1, \ldots, n_P\}$, determine
     the local best particles
\end{tabularx}
\vspace{-1ex}
\begin{equation}
\hspace{2cm}  p_{l,i}(k) \triangleq \argmin_{x \in \{ x_i(m) \}_{m=0}^k} f(x)
\end{equation}
\vspace{-1ex}
\begin{tabularx}{\headwidth}{m{2cm}l}
\multicolumn{2}{l}{\hspace{\textwidth}~} \\ \\[-8ex]\\
 & and the global best particle
\end{tabularx}
\vspace{-1ex}
\begin{equation}
\hspace{2cm}  p_{g,i}(k) \triangleq \argmin_{x \in \{ x_j(m) \ | \ j \in \mathcal N_i \}_{m=0}^k} f(x).
\end{equation}
\vspace{-1ex}
\begin{tabularx}{\headwidth}{m{2cm}l}
\multicolumn{2}{l}{\hspace{\textwidth}~} \\ \\[-8ex]\\
  \textbf{Step 3}:
     & Update the particle location $\{ x_i(k+1) \}_{i=1}^{n_P}\subset \mathbf X$.\\
  \textbf{Step 4}:
     & If $k = n_G$, stop. Else, go to Step 2.\\
  \textbf{Step 5}:
     & Replace $k$ by $k + 1$, and go to Step 1.\\
    \hline \\
\end{tabularx}
}
~\\ \lab{al:PSOImp}
\end{algorithm}
\end{minipage}
We will now discuss the different implementations of the
Model PSO Algorithm~\ref{al:PSOImp} in GenOpt.\\
\lab{sub:PSOImp}
\end{subequations}

% ---------------------------------
\subsubsection{Particle Update Equation}

% ------------------------------
\paragraph[Inertia Weight]{Version with Inertia Weight}
Eberhart and Shi~\cite{ShiEberhart1998,ShiEberhart1999} introduced
an {\it inertia weight} $w(k)$ which improves the performance of the
original PSO algorithm.
In the version with inertia weight, the particle update equation is,
for all $i \in \{1, \ldots, n_P\}$, for $k \in \Na$ and
$x_i(k) \in \Re^{n_c}$, with $v_i(0) = 0$,
\begin{subequations}
\begin{eqnarray}
 \widehat v_i(k+1) & = &  w(k) \, v_i(k) +
 c_1 \, \rho_1(k) \, \bigl( p_{l,i}(k) - x_i(k) \bigr) \nonumber \\
 &&
  + c_2 \, \rho_2(k) \, \bigr( p_{g,i}(k) - x_i(k) \bigr),
  \label{eq:psoUpdEqn1IneWei} \\
  v_i^j(k+1) & = &  \mathrm{sign}( \widehat v_i^j(k+1) ) \,
  \min\{ | \widehat v_i^j(k+1) | , v_{max}^j \}, \nonumber \\
  && \qquad \qquad j \in \{1, \ldots, n_c \},
\label{eq:psoUpdEqn2IneWei} \\
  x_i(k+1) & = & x_i(k) + v_i(k+1),
\end{eqnarray}
where
\begin{equation}
  v_{max}^j \triangleq \lambda \, (u^j - l^j),
  \label{eq:PSOMaxVelCon}
\end{equation}
with $\lambda \in \Re_+$,
for all $j \in \{1, \ldots, n_c \}$,
and $l,u \in \Re^{n_c}$ are the lower and upper bound of the independent variable.
A common value is $\lambda = 1/2$.
In GenOpt, if $\lambda \le 0$,
then no velocity clamping is used, and hence, $v_i^j(k+1) = \widehat v_i^j(k+1)$,
for all $k \in \Na$, all $i \in \{1, \ldots, n_P \}$ and all
$j \in \{1, \ldots, n_c \}$.

We compute the inertia weight as
\begin{equation}
  w(k) = w_0 - \frac{k}{K} \, ( w_0 - w_1 ),
\label{eq:PSOIneWeiLin}
\end{equation}
where $w_0 \in \Re$ is the initial inertia weight,
$w_1 \in \Re$ is the inertia weight for the last generation,
with $0 \le w_1 \le w_0$,
and $K \in \Na$ is the maximum number of generations.
$w_0 = 1.2$ and $w_1 = 0$ can be considered as
good choices~\cite{ParsopoulosVrahatis2002:1}.
\label{sub:psoUpdEqnIneWei}
\end{subequations}

% ------------------------------
\paragraph[Constriction Coefficient]{Version with Constriction Coefficient}
Clerc and Kennedy~\cite{ClercKennedy2002} introduced
a version with a constriction coefficient that reduces
the velocity.
In their Type 1'' implementation, the particle update equation is,
for all $i \in \{1, \ldots, n_P\}$, for $k \in \Na$
and $x_i(k) \in \Re^{n_c}$, with $v_i(0) = 0$,
\begin{subequations}
\begin{eqnarray}
 \widehat v_i(k+1) & = & \chi(\kappa, \varphi) \, \bigl( v_i(k) +
 c_1 \, \rho_1(k) \, \bigl( p_{l,i}(k) - x_i(k) \bigr) \nonumber \\
 &&
  + c_2 \, \rho_2(k) \, \bigr( p_{g,i}(k) - x_i(k) \bigr) \bigr),
  \label{eq:psoUpdEqn1ConCoe} \\
  v_i^j(k+1) & = &  \mathrm{sign}( \widehat v_i^j(k+1) ) \,
  \min\{ | \widehat v_i^j(k+1) | , v_{max}^j \}, \nonumber \\
  && \qquad \qquad j \in \{1, \ldots, n_c\},
\label{eq:psoUpdEqn2ConCoe} \\
  x_i(k+1) & = & x_i(k) + v_i(k+1),
\end{eqnarray}
where
\begin{equation}
  v_{max}^j \triangleq \lambda \, (u^j - l^j),
  \label{eq:PSOMaxVelConConCoe}
\end{equation}
is as in~\eqref{eq:PSOMaxVelCon}.

In \eqref{eq:psoUpdEqn1ConCoe},
$\chi(\kappa, \varphi)$ is called {\it constriction coefficient}, defined as
\begin{equation}
  \chi(\kappa, \varphi) \triangleq
  \begin{cases}
     \frac{ 2 \, \kappa }{ | 2 - \varphi - \sqrt{\varphi^2 - 4 \, \varphi} |}, &
      \text{if } \varphi > 4, \\
     \kappa , & \text{otherwise},
  \end{cases}
\label{eq:PSOConCoeChi}
\end{equation}
where
$\varphi \triangleq {c_1 + c_2}$
and $\kappa \in (0, 1]$ control how fast the population collapses
into a point. If $\kappa = 1$, the space is thoroughly searched, which
yields slower convergence.

Equation~\eqref{sub:psoUpdEqnConCoe} can be used with or without
velocity clamping~\eqref{eq:psoUpdEqn2ConCoe}.
If velocity clamping~\eqref{eq:psoUpdEqn2ConCoe} is used,
Clerc and Kennedy use
$\varphi = 4.1$, otherwise they use $\varphi = 4$. In either case, they
set $c_1 = c_2 = \varphi / 2$ and a population size of $n_P = 20$.\\

Carlisle and Dozier~\cite{CarlisleDozier2001} recommend the settings
$n_P = 30$, no velocity clamping, $\kappa = 1$, $c_1 = 2.8$
and $c_2 = 1.3$.\\

Kennedy and Eberhart~\cite{KennedyEberhartShi2001} report that
using velocity clamping \eqref{eq:psoUpdEqn2ConCoe}
and a constriction coefficient
shows faster convergence for some test problems compared to using
an inertia weight,
but the algorithm tends to get stuck in local minima.
\label{sub:psoUpdEqnConCoe}
\end{subequations}

% ---------------------------------
\subsection{PSO for Discrete Variables}
\label{sec:PSOBin}
Kennedy and Eberhart~\cite{KennedyEberhart1997} introduced
a binary version of the PSO algorithm to solve problem $\mathbf P_d$
defined in~\eqref{sub:Prod}.\\

The binary PSO algorithm encodes the discrete independent variables in a string of
binary numbers and then operates with this binary string.
For some $i \in \{1, \ldots, n_d\}$,
let $x_i \in \Na$ be the component of a discrete independent variable,
and let $\psi_i \in \{0, 1 \}^{m_i}$ be its
binary representation (with $m_i \in \Na_+$ bits),
obtained using Gray encoding~\cite{Gray1993}, and
let $\pi_{l,i}(k)$ and $\pi_{g,i}(k)$ be the binary
representation of $p_{l,i}(k)$ and $p_{g,i}(k)$, respectively,
where $p_{l,i}(k)$ and $p_{g,i}(k)$ are defined in~\eqref{sub:PSOImp}.

Then, for
$i \in \{1, \ldots, n_d\}$ and $j \in \{1, \ldots, m_i\}$
we initialize randomly
$\psi_i^j(0) \in \{0, 1 \}$,
and compute, for $k \in \Na$,
\begin{subequations}
\begin{eqnarray}
 \widehat v_i^j(k+1) & = & v_i^j(k) +
 c_1 \, \rho_1(k) \, \bigl( \pi_{l,i}^j(k) - \psi_i^j(k) \bigr) \nonumber \\
 &&
  + c_2 \, \rho_2(k) \, \bigr( \pi_{g,i}^j(k) - \psi_i^j(k) \bigr) \bigr),
  \label{eq:psoUpdEqn1Bin} \\
  v_i^j(k+1) & = &  \mathrm{sign}( \widehat v_i^j(k+1) ) \,
  \min\{ | \widehat v_i^j(k+1) | , v_{max} \},
  \label{eq:psoUpdEqn2Bin}
 \\
  \psi_i^j(k+1) & = &
  \begin{cases}
    0, & \text{if } \rho_{i,j}(k) \ge s\bigl( v_i^j(k+1)  \bigr),\\
    1, & \text{otherwise,}
  \end{cases}
\end{eqnarray}
where
\begin{equation}
  s(v) \triangleq \frac{1}{1+e^{-v}}
\end{equation}
is the sigmoid function shown in Fig.~\ref{fig:PSOSigFun}
and $\rho_{i,j}(k) \sim U(0,1)$,
for all $i \in \{1, \ldots, n_d\}$ and for all
$j \in \{1, \ldots, m_i\}$.
\label{sub:psoUpdEqnBin}
\end{subequations}

\begin{figure}
\centering
{\psset{yunit=2.5, arrowscale=2}
\begin{pspicture}(-5, -0.1)(5,1.5)
%\showgrid
\multido{\iX=-4+1}{9}{%
  \rput(\iX,0){\psline[linewidth=0.2pt]{-}(0,0)(0,1)}
  \rput(\iX,0){\psline{-}(0,-2pt)(0,2pt)}
  \uput[-90](\iX,0){$\iX$}
}
{\psset{yunit=0.1}%
  \multido{\iX=2+2}{4}{%
    \rput(0,\iX){\psline[linewidth=0.2pt]{-}(-4,0)(4,0)}
    \rput(0,\iX){\psline{-}(-2pt,0)(2pt,0)}
    \uput[180](0,\iX){$0.\iX$}
  }
}
  \rput(0,1){\psline[linewidth=0.2pt]{-}(-4,0)(4,0)}
  \rput(0,1){\psline{-}(-2pt,0)(2pt,0)}
  \uput[180](0,1){$1$}
\psplot[plotpoints=25]{-4}{4}{ 1 2.71828 x neg exp 1 add div }
\psline{->}(-4.5,0)(4.7,0)
\psline{->}(0,0)(0,1.3)
\uput[-90](4.5,-0.1){$v$}
\uput[0](0,1.3){$s(v) = {1} / {( 1 + e^{-v} )}$}
\end{pspicture}
}
\caption{Sigmoid function.}
\label{fig:PSOSigFun}
\end{figure}

In~\eqref{eq:psoUpdEqn2Bin}, $v_{max} \in \Re_+$ is often set to $4$ to prevent a
saturation of the sigmoid function,
and $c_1,c_2 \in \Re_+$ are often such that $c_1+c_2=4$ (see~\cite{KennedyEberhartShi2001}).

Notice that $s(v) \to 0.5$, as $v \to 0$,
and consequently the probability of flipping a bit goes to $0.5$.
Thus, in the binary PSO, a small $v_{max}$ causes a large exploration, whereas in the
continuous PSO, a small $v_{max}$ causes a small exploration of the search space.\\

Any of the above neighborhood topologies can be used,
and Model Algorithm~\ref{al:PSOImp} applies if we replace
the constraint set $\mathbf X$ by the user-specified set
$\mathbf X_d \subset \mathbb Z^{n_d}$.

% --------------------------------------------
\subsection{PSO for Continuous and Discrete Variables}
\lab{sec:PSOConDis}
For problem $\mathbf P_{cd}$ defined in~\eqref{sub:Procd},
we treat the continuous
independent variables as in~\eqref{sub:psoUpdEqnIneWei}
or~\eqref{sub:psoUpdEqnConCoe}, and the discrete independent variables as
in~\eqref{sub:psoUpdEqnBin}.
Any of the above neighborhood topologies can be used,
and Model Algorithm~\ref{al:PSOImp} applies if we define the constraint
set $\mathbf X$ as in~\eqref{sub:setXd}.

% --------------------------------------------
\subsection{PSO on a Mesh}
\label{sec:PSOMes}
We now present a modification to the previously discussed PSO
algorithms.
For evaluating the cost function, we will modify the continuous
independent variables such that they belong to a fixed mesh in $\Re^{n_c}$.
Since the iterates of PSO algorithms typically cluster during the last
iterations, this reduces in many cases the number of simulation calls
during the optimization. The modification is done by replacing the cost
function $f \colon \Re^{n_c} \times \mathbb Z^{n_d} \to \Re$ in
Model Algorithm~\ref{al:PSOImp} as follows:
Let $x_0 \triangleq (x_{c,0}, x_{d,0} ) \in \Re^{n_c} \times \mathbb Z^{n_c}$
denote the initial iterate,
let $\mathbf X_c$ be the feasible set for the continuous independent variables
defined in~\eqref{eq:feaSetXc},
let $r, s \in \Na$, with $r>1$, be user-specified parameters, let
\begin{equation}
  \Delta \triangleq \frac{1}{r^s}
\label{eq:PSOMeshDiv}
\end{equation}
and let the mesh be defined as
\begin{equation}
  \mathbb M(x_{c,0}, \Delta, s) \triangleq \left\{ x_{c,0} + \Delta \,
  \sum_{i=1}^n m^i \,
  s^i \, e_i \ | \ m \in \mathbb Z^{n_c} \right\},
\label{eq:PSODefMesh}
\end{equation}
where $s \in \Re^{n_c}$ is equal to the value defined by the variable
\texttt{Step} in GenOpt's command file (see page~\pageref{par:comFil}).
Then, we replace $f(\cdot, \cdot)$ by
$\widehat f \colon \Re^{n_c} \times \mathbb Z^{n_d} \times \Re^{n_c} \times \Re  \times \Re^{n_c} \to \Re$, defined by
\begin{equation}
  \widehat f( x_c, x_d; x_{c,0}, \Delta, s) \triangleq
  f( \gamma( x_c ), x_d),
\end{equation}
where $\gamma \colon \Re^{n_c} \to \Re^{n_c}$ is the projection of the
continuous independent variable to the closest feasible mesh point,
i.e., $\gamma(x_c) \in \mathbb M(x_{c,0}, \Delta, s) \cap \mathbf X_c$.
Thus, for evaluating the cost function,
the continuous independent variables are replaced by the closest
feasible mesh point, and the discrete independent variables
remain unchanged.\\

Good numerical results have been obtained by selecting $s \in \Re^{n_c}$ and
$r, s \in \Na$ such that
about $50$ to $100$ mesh points are located
along each coordinate direction.

% --------------------------------------------
\subsection{Population Size and Number of Generations}
Parsopoulos and Vrahatis~\cite{ParsopoulosVrahatis2002:1} use
for $x \in \Re^{n_c}$ a population size of about $5 \, n$ up to $n = 15$.
For $n \approx 10 \ldots 20$, they use $n_P \approx 10 \, n$.
They set the number of generations to $n_G = 1000$ up to $n = 20$ and
to $n_G = 2000$ for $n = 30$.

Van den Bergh and Engelbrecht~\cite{VanDenBerghEngelbrecht2001}
recommend using more than $20$ particles
and $2000$ to $5000$ generations.\\

Kennedy and Eberhart~\cite{KennedyEberhartShi2001} use, for
test cases with the {\it lbest} neighborhood topology of size $l=2$
and $n=2$ and $n=30$,
a population size of $n_P = 20 \ldots 30$. They report that $10 \ldots 50$
particles usually work well.
As a rule of thumb, they recommend for the {\it lbest} neighborhood to
select the neighborhood size such that each neighborhood consists of $10 \ldots 20\%$
of the population.

% --------------------------------------------
\subsection{Keywords}
For the Particle Swarm algorithm,
the command file (see page~\pageref{par:comFil})
can contain continuous and discrete independent variables.\\

The different specifications for the \texttt{Algorithm} section
of the GenOpt command file are as follows:\\

\noindent
PSO algorithm with inertia weight:
\begin{lstlisting}
Algorithm{
  Main                      = PSOIW;
  NeighborhoodTopology      = gbest | lbest | vonNeumann;
  NeighborhoodSize          = Integer;  // 0 < NeighborhoodSize
  NumberOfParticle          = Integer;
  NumberOfGeneration        = Integer;
  Seed                      = Integer;
  CognitiveAcceleration     = Double;   // 0 < CognitiveAcceleration
  SocialAcceleration        = Double;   // 0 < SocialAcceleration
  MaxVelocityGainContinuous = Double;
  MaxVelocityDiscrete       = Double;   // 0 < MaxVelocityDiscrete
  InitialInertiaWeight      = Double;   // 0 < InitialInertiaWeight
  FinalInertiaWeight        = Double;   // 0 < FinalInertiaWeight
}
\end{lstlisting}

\noindent
PSO algorithm with constriction coefficient:
\begin{lstlisting}
Algorithm{
  Main                      = PSOCC;
  NeighborhoodTopology      = gbest | lbest | vonNeumann;
  NeighborhoodSize          = Integer;  // 0 < NeighborhoodSize
  NumberOfParticle          = Integer;
  NumberOfGeneration        = Integer;
  Seed                      = Integer;
  CognitiveAcceleration     = Double;   // 0 < CognitiveAcceleration
  SocialAcceleration        = Double;   // 0 < SocialAcceleration
  MaxVelocityGainContinuous = Double;
  MaxVelocityDiscrete       = Double;   // 0 < MaxVelocityDiscrete
  ConstrictionGain          = Double;   // 0 < ConstrictionGain <= 1
}
\end{lstlisting}

\noindent
PSO algorithm with constriction coefficient and
continuous independent variables
restricted to a mesh:
\label{algSec:PSOCCMesh}
\begin{lstlisting}
Algorithm{
  Main                      = PSOCCMesh;
  NeighborhoodTopology      = gbest | lbest | vonNeumann;
  NeighborhoodSize          = Integer;  // 0 < NeighborhoodSize
  NumberOfParticle          = Integer;
  NumberOfGeneration        = Integer;
  Seed                      = Integer;
  CognitiveAcceleration     = Double;   // 0 < CognitiveAcceleration
  SocialAcceleration        = Double;   // 0 < SocialAcceleration
  MaxVelocityGainContinuous = Double;
  MaxVelocityDiscrete       = Double;   // 0 < MaxVelocityDiscrete
  ConstrictionGain          = Double;   // 0 < ConstrictionGain <= 1
  MeshSizeDivider           = Integer;  // 1 < MeshSizeDivider
  InitialMeshSizeExponent   = Integer;  // 0 <= InitialMeshSizeExponent
}
\end{lstlisting}

\noindent
The entries that are common to all implementations are defined as follows:
\begin{codedescription}
\item [Main]
The name of the main algorithm.
The implementation \texttt{PSOIW} uses the location update
equation~\eqref{sub:psoUpdEqnIneWei}
for the continuous independent variables,
and the implementation \texttt{PSOCC}
uses~\eqref{sub:psoUpdEqnConCoe}
for the continuous independent variables.
All implementations use~\eqref{sub:psoUpdEqnBin} for the discrete independent variables.
\item [NeighborhoodTopology]
This entry defines what neighborhood topology is being used.
\item [NeighborhoodSize]
For the {\it lbest} neighborhood topology,
this entry is equal to $l$ in \eqref{eq:defLBestNeiHoo}.
For the {\it gbest} and the {\it von Neumann} neighborhood topology,
the value of \texttt{NeighborhoodSize} is ignored.
\item [NumberOfParticle]
This is equal to the variable $n_P \in \Na$.
\item [NumberOfGeneration]
This is equal to the variable $n_G \in \Na$ in Algorithm~\ref{al:PSOImp}.
\item [Seed]
This value is used to initialize the random number generator.
\item [CognitiveAcceleration]
This is equal to the variable $c_1 \in \Re_+$.
\item [SocialAcceleration]
This is equal to the variable $c_2 \in \Re_+$.
\item [MaxVelocityGainContinuous]
This is equal to the variable $\lambda \in \Re_+$ in~\eqref{eq:PSOMaxVelCon}
and in~\eqref{eq:PSOMaxVelConConCoe}.
If \texttt{MaxVelocityGainContinuous} is set to zero or to a negative value,
then no velocity clamping is used, and hence, $v_i^j(k+1) = \widehat v_i^j(k+1)$,
for all $k \in \Na$, all $i \in \{1, \ldots, n_P \}$ and all
$j \in \{1, \ldots, n_c \}$.
\item [MaxVelocityDiscrete]
This is equal to the variable $v_{max} \in \Re_+$ in~\eqref{eq:psoUpdEqn2Bin}.
\end{codedescription}

\vspace{2\baselineskip}
\noindent
For the \texttt{PSOIW} implementation, following additional entries must be
specified:
\begin{codedescription}
\item [InitialInertiaWeight]
This is equal to $w_0 \in \Re_+$ in~\eqref{eq:PSOIneWeiLin}.
\item [FinalInertiaWeight]
This is equal to $w_1 \in \Re_+$ in~\eqref{eq:PSOIneWeiLin}.
\end{codedescription}

\vspace{2\baselineskip}
\noindent
For the \texttt{PSOCC} implementation, following additional entries must be
specified:
\begin{codedescription}
\item [ConstrictionGain]
This is equal to $\kappa \in (0, 1]$ in~\eqref{eq:PSOConCoeChi}.
\end{codedescription}
Notice that for discrete independent variables, the entries of
\texttt{InitialInertiaWeight}, \texttt{FinalInertiaWeight}, and \texttt{ConstrictionGain}
are ignored.\\

\vspace{2\baselineskip}
\noindent
For the \texttt{PSOCCMesh} implementation, following additional entries must be
specified:
\begin{codedescription}
\item [MeshSizeDivider]
This is equal to $r \in \Na$, with $r > 1$, used in~\eqref{eq:PSOMeshDiv}.
\item [InitialMeshSizeExponent]
This is equal to $s \in \Na$ used in~\eqref{eq:PSOMeshDiv}.
\end{codedescription}


\LoadClass[notes]{hph}
\setauthor{Hrant P.~Hratchian}
\settitle{Summer Fortran Workshop: Problem 1 -- The Modified Particle in a Box}
\setrunningtitle{Summer Fortran Workshop: Problem 1}
\setdate{\today}
\setcounter{chapter}{1}
%
\begin{document}
\makeheaderfooter{}
\maketitle
%
%
% Section: Introduction and Problem Definition
\section{Introduction and Problem Definition}
Consider a \emph{modified} one-dimensional particle-in-a-box (\emph{m}PIB) where the potential is $\infty$ for $x\le{}0$ and $x\ge{}L$. In the range from $0$ to $L$, let the potential energy be given by
%
\begin{equation}\label{Eq:mPIBPotential}
\displaystyle
  V\left(x\right) = b x\,\,\,\,\,\,\,\,\,\,0<x<L
\end{equation}
%
Using atomic units, write a Fortran program that solves for the eigenfunctions and eigenvalues of the first five states of this system. Use the linear variational method to carry out this numerical problem. The standard one-dimensional PIB eigenfunctions should be used as your basis set.

The PIB problem is a standard model system case studied in quantum mechanics. A brief overview of the model and key results are described below in Section \ref{Section:TheoreticalBackground}. This problem introduces a non-zero potential inside the box. This programming problem solves for this mPIB using the linear variational method, which is also described in Section \ref{Section:TheoreticalBackground}.

The program should take a set of six input arguments from the command line: mass, box length $L$, slope parameter $b$, and the number of basis functions to be used in the calculation.

The program should output the eigenvalues and expansion coefficients for the ground and first excited state.

%
% Section: Theoretical Background
\section{Theoretical Background}\label{Section:TheoreticalBackground}
This coding problem relies on two theoretical background topics: (1) the particle-in-a-box problem; and (2) the linear variational method.

%
% Subsection: Particle-in-a-Box
\subsection{Particle-in-a-Box}
As mentioned above, the one-dimensional particle-in-a-box (PIB) is a model system where the potential is $\infty$ for $x \le{}0$ and $x \ge{} L$. Most derivations begin by dividing the coordinate space into three regions: Region I ($x\le{}0$), Region II ($0<x<L$), and Region III ($x\ge{}L$). Regions I and III the potential energy is $\infty$ and it is trivial to show that the wave function vanishes.

In Region II, a set of discrete quantum states are found. A quantum number, $n$, is determined to have allowed values $1, 2, 3, \cdots{}$.
%
\begin{equation}
\displaystyle
  \braket{x}{n} = \psi(x) = \left(\frac{2}{L}\right)^{\sfrac{1}{2}}\sin{\left(\frac{n \pi}{L}x\right)}
    \,\,\,\,\,\,\,\,\,\,0<x<L\,\,\,\,\,\,\,\,\,\,n=1,2,3,\cdots{}
\end{equation}
%
and the quantized energy levels $\left\{E_n\right\}$ are
%
\begin{equation}\label{Eq:PIBenergies}
\displaystyle{}
  E_n = \frac{\pi^2}{2 m L^2}n^2\,\,\,\,\,\,\,\,\,\,n=1,2,3,\cdots{}
\end{equation}
%
Note that the energies in Eq.~(\ref{Eq:PIBenergies}) are given in atomic units ($\hbar=1$).

%
% Subsection: Linear Variational Method
\subsection{Linear Variational Method}
The linear variational method is used to solve the Schr\"{o}dinger equation numerically and is the central technique used in this coding problem set. It is an especially useful method when a basis set can be well-defined for the physical system of interest, particularly if the basis set can be systematically increased and refined. The basis set used must satisfy three general requirements. First the members of the basis set should satisfy the same boundary conditions expected for the exact solutions of the Schr\"{o}dinger equation being studies. Second, it must be possible to solve matrix elements of the form
%
\begin{equation}
\displaystyle
  H_{\alpha\beta} = \braketop{\alpha}{\mathcal{H}}{\beta}
\end{equation}
%
where \ket{\alpha} and \ket{\beta} are members of the chosen basis set and $\mathcal{H}$ is the Hamiltonian. Third, the basis set should either be formally complete or be systematically expandable such that numerical experimentation can sufficiently establish approximate completeness.

Given these requirements of the basis set, the development of the linear variational method begins with the Schr\"{o}dinger equation
%
\begin{equation}\label{Eq:SchrodingerEquation}
\displaystyle
  \mathcal{H}\ket{\Psi} = E\ket{\Psi}
\end{equation}
%
where $\mathcal{H}$ is the Hamiltonian, \ket{\Psi} is the (ground state) eigen-ket (i.e., the wave function), and $E$ is the energy eigenvalue corresponding to \ket{\Psi}. Using a (numerically) complete basis with obeying the same boundary conditions as model potential, which we denote as $\left\{\chi_1, \chi_2, \cdots{}\right\}$,
%
\begin{equation}\label{Eq:basisExpansion}
\displaystyle
  \ket{\Psi} \approx{} \sum_n{c_n\ket{\chi_n}}
\end{equation}
%
Substituting Eq.~(\ref{Eq:basisExpansion}) into Eq.~(\ref{Eq:SchrodingerEquation}) yields
%
\begin{equation}\label{Eq:SchrodingerEquationExpansion}
\displaystyle
  \mathcal{H}\ket{\sum_n{c_n\chi_n}} = E\ket{\sum_n{c_n\chi_n}}
\end{equation}
%
Multiplying on the left by another member of the complete set and invoking the interchange theorem of summation and integration, Eq.~(\ref{Eq:SchrodingerEquationExpansion}) becomes
%
\begin{equation}\label{Eq:SchrodingerEquationMatrix1}
\displaystyle
  \sum_n{c_n \braketop{m}{\mathcal{H}}{n}} = E\sum_n{c_n\braket{m}{n}}
\end{equation}
%
where index labels $m$ and $n$ have been used to denote \ket{\chi_m} and \ket{\chi_n}.

In the application of the linear variational method used here, the basis set will be the conventional PIB eigenfunctions. Noting that this is an orthonormal basis set, Eq.~(\ref{Eq:SchrodingerEquationMatrix1}) can be written as
%
\begin{equation}\label{Eq:SchrodingerEquationMatrix1}
\displaystyle
  \sum_n{c_n \braketop{m}{\mathcal{H}}{n}} = E\sum_n{c_n\delta_{mn}}
\end{equation}
%
and, in matrix form as
%
\begin{equation}\label{Eq:SchrodingerEquationMatrix2}
\displaystyle
\begin{aligned}
  \sum_n{H_{mn}c_{n}} ={}& Ec_m  \\
  \mathbf{Hc} ={}& E\mathbf{c}
\end{aligned}
\end{equation}
%
Equation (\ref{Eq:SchrodingerEquationMatrix2}) is an eigensystem. Once the Hamiltonian matrix elements are solved, a standard eigenvalue decomposition algorithm can be used to find a set of eigenvectors (the expansion coefficients $\mathbf{c}$) and eigenvalues (the expectation energy corresponding to each eigenvector). The eigenvector with the lowest corresponding eigenvalue is the linear variational ground state solution to Eq.~(\ref{Eq:SchrodingerEquation}). The other eigenvectors (with eigenvalues greater than the lowest) are the linear variational method solutions for excited states. Generally, a well chosen basis set that can be systematically increased will converge in the number of basis functions for the ground state and low energy excited states before converging for higher energy excited states.

%How does the ground state energy vary as a function of the number of basis functions? To explore this point, begin by using the two lowest energy states of the standard particle-in-a-box system as your set of basis functions. Then, use the first three states of the standard particle-in-a-box as your basis set. Follow this by numerical tests using four, five, six, seven, eight, nine, and ten states. Plot the ground state energy as a function of the number of basis functions used.
%
%Repeat the previous experiment with the potential function changed to $V\left(x\right) = 10 m x$.
%
%Plot the ground state wavefunction for the previous two problems using an appropriately converged basis set size. Comment on the effect of the added potential on the shape of the ground state wavefunction.
%
\end{document}


\section{Data Mapping Between Meshes}\label{sec:data_mapping_between_meshes}

% introduction, mapping required for operator splitting, different dimensionalities, source to target mesh
% goal is to construct a mapping in the order of the target mesh
% parallel partitioning -> treat source mesh as point cloud

% target->source is interpolation, construct transposed mapping
After the implementation of various solvers for specific parts of the multi-domain model has been described in the previous sections, we now focus on the data mapping between different meshes that occurs in the coupling schemes between the execution of the coupled solvers.

Data mapping between meshes is required in scenarios that involve both a finely resolved 3D mesh for the electrophysiology model and a coarse 3D mesh for the solid mechanics model. Moreover, data are mapped between the 3D muscle mesh and the embedded 1D fiber meshes in the fiber based electrophysiology model. In these two cases, the mapping has to be carried out in both directions between the involved meshes. The operation can be characterized as \emph{volume mapping}.

We implement a generic mapping scheme between two meshes of any dimensionality and with any relative orientation with respect to each other.
Given is a finite element interpolant on a \emph{source} mesh, defined by the dof values at the nodes. The goal is to set the dof values of the \emph{target} mesh, such that the error between the finite element representations on the common domain of source and target mesh is as low as possible. By using the ansatz functions of the target mesh, the constructed mapping has the same order of accuracy as the target mesh interpolant. For a linear target mesh, the mapping operation is second order accurate, for a quadratic target mesh, the mapping operation is third order accurate.

The considered source and target meshes are possibly partitioned. In order to perform the data mapping directly between two such meshes without communication between the processes, the partitioning of the volumes would have to be identical. However, this is not practical for different meshes and would disallow different orientations of source and target meshes. The only way to allow such a mapping is to consider either the source or the target mesh as a point cloud and construct the mapping between individual points and a mesh.

Considering the case of mapping the activation parameter value $\gamma$, which is stored on multiple 1D fibers, to the value $\bar{\gamma}$ on the 3D muscle mesh, it is natural to consider the source mesh as a point cloud. Then, instead of multiple fibers, we have a set of points, where $\gamma$ is known. This set of source points is mapped to the enclosing 3D target mesh. On every process, the source points have to be located inside the local subdomain of the target mesh.

The reverse mapping in this example is also required: The geometry of the 3D muscle mesh has to be mapped to the fibers points, such that a deformation of the muscle also affects the embedded fibers. This reverse mapping from the target mesh to the source fiber meshes or points is trivial: The source values can be interpolated in the target mesh using the finite element discretization.
We construct the mapping from source to target mesh to be the transpose operation to this interpolation. In the following section, we introduce the method with a graphical example.

\subsection{Construction of the Parallel Data Mapping}

\Cref{fig:mapping_between_meshes_2} shows a scenario, where data mapping is performed from a source mesh to a target mesh. The source mesh is given by the orange points $s_0$ to $s_3$. The target mesh is visualized by the black and gray elements $e_{\text{T},0}$ to $e_{\text{T},3}$  and nodes $t_0$ to $t_3$.

The value at $s_0$ contributes to all nodes $t_0$ to $t_3$ of the target element $e_{\text{T},0}$ as indicated by the red arrows. The relations between the contributions to $t_0,t_1,t_2$ and $t_3$ are determined by the values of the respective target element ansatz functions $\phi_0$ to $\phi_3$, evaluated at the location of $s_0$.
Similarly, the source points $s_1$ to $s_3$ contribute to the nodes of their enclosing target elements $e_{\text{T},1}$ and $e_{\text{T},2}$.

% mapping scheme
\begin{figure}%
  \centering%
  \def\svgwidth{0.4\textwidth}
  \input{images/implementation/mapping_between_meshes_2.pdf_tex}%
  \caption{Data mapping scheme from source points (orange) to a target mesh (black).}%
  \label{fig:mapping_between_meshes_2}%
\end{figure}%

As a consequence, all shown source points $s_0$ to $s_3$ influence the value of the target node $t_0$, as indicated by the red arrows.
The value $\hat{t}_0$ at point $t_0$ is computed using the values $\hat{s}_i$ at the points $s_i$ for $i=1,\dots,4$ as follows:
%
\begin{align}\label{eq:mapping_source_target}
  \hat{t}_0 = \s{i=0}{4} \alpha_i\,\hat{s}_i, \quad \text{with }\alpha_i = \dfrac{\phi_{\noexpand\mkern-4mu t_0}(\bfxi_{s_i})}{\s{i=0}{4} \phi_{\noexpand\mkern-4mu t_0}(\bfxi_{s_i})}.
\end{align}
Here, $\phi_{\noexpand\mkern-4mu t_0}$ is the finite element ansatz function for the node $t_0$. It is evaluated at the locations $\bfxi_{s_i}$ of the source points $s_i$ in the respective target elements. The factors $\alpha_i$ specify the fractions, with which the different contributions to $\hat{t}_0$ are scaled. Their construction ensures the property $\sum_{i=1}^4 \alpha_i = 1$.
Note that the number of summands in the sum over the source points can be different from 4 for other target points.

% reverse mapping scheme
\begin{figure}%
  \centering%
  \begin{subfigure}{0.4\textwidth}
    \centering
    \def\svgwidth{\textwidth}
    \input{images/implementation/mapping_between_meshes_3.pdf_tex}%
    \caption{Mapping from target to source points using the reverse scheme of \cref{fig:mapping_between_meshes_2}.}%
    \label{fig:mapping_between_meshes_3}%
  \end{subfigure}
  \quad
  \begin{subfigure}{0.4\textwidth}
    \centering
    \def\svgwidth{\textwidth}
    \input{images/implementation/mapping_between_meshes_4.pdf_tex}%
    \caption{Inverse mapping scheme where the roles of source and target mesh are swapped.}%
    \label{fig:mapping_between_meshes_4}%
  \end{subfigure}
  \caption{Data mapping from target mesh to source mesh.}%
  \label{fig:mapping_between_meshes_34}%
\end{figure}%

The reverse mapping from target nodes to source points uses the same data dependencies between dofs in the source and in the target meshes. \Cref{fig:mapping_between_meshes_3} shows the scheme for the reverse mapping. It is the same as in \cref{fig:mapping_between_meshes_2}, except that the direction of the arrows has been flipped. As noted earlier, the mapping from the target to the source mesh is simply an interpolation in the target mesh. The value $\hat{s}_0$ is computed from $\hat{t}_0$ to $\hat{t}_3$ using the finite element interpolation formula in element $e_{\text{T},0}$:%
\begin{align*}
  \hat{s}_0 = \s{i=0}{4}\hat{t}_i\,\phi_{\noexpand\mkern-4mu t_i}(\bfxi_{s_0}).
\end{align*}
Again, the contribution factors sum up to one, $\sum_{i=0}^4 \phi_{\noexpand\mkern-4mu t_i}(\bfxi_{s_0}) = 1$.

This mapping scheme has the advantage that it requires no communication between the involved processes to determine the target dofs, to which a source dof contributes to. Considering the example in \cref{fig:mapping_between_meshes_2} and assuming that the four target elements are located on four different subdomains, it can be seen that each source point $s_i$ only has to access the target element, where it is contained, to determine the respective element coordinates $\bfxi_{s_i}$.

For the computation of the factors $\alpha_i$ in \cref{eq:mapping_source_target} and for the computation of the target dofs, communication is required. This communication step is the same exchange of ghost dof values, which is also needed for the assembly of finite element stiffness and mass matrices. In the implementation, it is available by the respective functionality of PETSc as described in \cref{sec:oragnization_of_parallel_partitioned_data}.
The reverse mapping from target to source meshes, i.e., the interpolation scheme, works without any communication as all required data are local to the processes.

Instead of reversing the source to target mapping as described, it is often also possible to change the roles of source and target mesh and construct a new mapping in this way. This is only possible, if the two meshes have the same dimensionality, as in the considered example visualizations with two 2D meshes. \Cref{fig:mapping_between_meshes_4} shows the presented mapping scheme with the roles of source and target meshes reversed.
By comparing with \cref{fig:mapping_between_meshes_3}, it can be seen that, in this case, the node $t_0$ contributes to the same nodes $s_0$ to $s_3$ in both approaches. However, the contribution factors are different. In general, the dependent nodes in both meshes are not necessarily the same in the two mapping directions. This means that, in general, the reversed or transposed mapping is not equal to the inverse mapping that is created by interchanging source and target meshes.

For mappings between different dimensionalities, only the approach of reversing the mapping in one direction is possible. For example, mapping from a 1D mesh to a 3D mesh allows no interpolation in the 1D mesh to get the 3D mesh data, as the 1D mesh occupies only a subset of the domain of the 3D mesh. This is a reason for implementing the presented mapping scheme, where the mapping direction can be reversed. Another advantage is that, once the mapping is constructed, both mapping directions are available and the expensive operation of locating the points of one mesh inside the elements of the other mesh has only be performed once.

\subsection{Special Treatment of Coarse Meshes}
% special case with coarse meshes

% reverse mapping scheme
\begin{figure}%
  \centering%
  \begin{subfigure}{0.4\textwidth}
    \centering
    \def\svgwidth{\textwidth}
    \input{images/implementation/mapping_between_meshes_5.pdf_tex}%
    \caption{Mapping scheme from source to target mesh.}%
    \label{fig:mapping_between_meshes_5}%
  \end{subfigure}
  \quad
  \begin{subfigure}{0.4\textwidth}
    \centering
    \def\svgwidth{\textwidth}
    \input{images/implementation/mapping_between_meshes_6.pdf_tex}%
    \caption{Reverse mapping scheme from target mesh to source points.}%
    \label{fig:mapping_between_meshes_6}%
  \end{subfigure}
  \caption{Data mapping scheme with additional data dependencies for a coarse source mesh.}%
  \label{fig:mapping_between_meshes_56}%
\end{figure}%

While the mapping error in the described scheme converges to zero, when the mesh widths approach zero, an issue occurs, if one of the meshes is significantly coarser than the other. \Cref{fig:mapping_between_meshes_5} depicts the case of a coarse source mesh in orange color that is mapped to a finer target mesh in black and gray colors. According to the presented scheme, the source points $s_0$ and $s_3$ contribute to target nodes as visualized by the red arrows. The analog contributions for $s_1$ and $s_2$ are not shown in \cref{fig:mapping_between_meshes_5}. Some target mesh nodes in this example have large distances to the source points and, as a result, do not get contributions from any source point. For example, this is the case for the target points $t_1$ and $t_2$.

To define the value at $t_2$ depending on the source data, we add new contributions from all nodes of the source element in which $t_2$ is located. These contributions are visualized by the yellow arrows in \cref{fig:mapping_between_meshes_5}.
The contributions use the ansatz functions of the source element, and the operation is equivalent to interpolating the value for $t_2$ in the source mesh:
\begin{align*}
  \hat{t}_2 = \s{i=0}{4}\hat{s}_i\,\phi_{\noexpand\mkern-4mu s_i}(\bfxi_{t_2}).
\end{align*}
The location $\bfxi_{t_2}$ of $t_2$ in element coordinates of the source element is required for this computation. Analogously, corresponding contributions are added for the other target nodes that do not yet get any contribution from the source data.

These additional contributions are also present in the reversed mapping scheme from the target to the source mesh. As can be seen in \cref{fig:mapping_between_meshes_6}, the value at $t_2$ contributes to the source nodes $s_0$ to $s_3$. At any source node, the number of contributions increases accordingly. The visualization in \cref{fig:mapping_between_meshes_6} shows five incoming arrows with contributions for $s_0$ and $s_3$. The actual number is higher, since not all target nodes with additional contributions are visualized. At the target nodes, the contribution factors get rescaled, such that they add up to 1 and their relations are preserved.

\subsection{Computation of Element Coordinates For Mapped Points}

During the setup of the mapping between the source mesh and the target mesh, we need to find, for every source point $s_i$, the target element $e_{\text{T},j}$ that contains $s_i$. Furthermore, we need to determine the local element coordinates $\bfx_{s_i} = (\xi_1,\xi_2,\xi_3)^\top$ of the point in this element. To check, if the point is inside a particular element, we compute its coordinates in the element coordinate system. If the coordinates $\bfxi$ are inside the range of $[0,1]^d$, the point is considered inside this element, and the coordinates are determined.

The source point is given by coordinates $\bfx=(x_1,x_2,x_3)^\top \in \R^3$ in the world coordinate frame. The point is related to the $d$-dimensional element coordinate frame $(\xi_1,\dots,\xi_d)$ of its containing target element by the following map:
\begin{align}\label{eq:mapping_parameter_world}
  \bfx(\bfxi) = \s{i=1}{n_\text{dofs}} \phi_i(\bfxi)\, \bfx^i.
\end{align}
Here, $\phi_i$ for $i=1,\dots,n_\text{dofs}$, are the nodal ansatz functions of the target element. The element  has $n_\text{dofs}$ dofs and is given by its node positions $\bfx^i$.

The computation of the element coordinates $\bfxi$ from the world coordinates $\bfx$ consists of inverting the mapping in \cref{eq:mapping_parameter_world}. In the following, several approaches are presented to perform this inversion for different mesh types.

For meshes of type \code{StructuredRegularFixedOfDimension<D>}, the inversion can be performed analytically. The mesh is a Cartesian grid with a fixed mesh width $h$. For quadratic elements, $h$ denotes the side length of an element, not the distance between adjacent nodes.
The computation of the element coordinates $\bfxi$ for the point $\bfx$ uses the position $\bfx^1$ of the first node and is given by:
\begin{align*}
  \bfxi = (\bfx - \bfx^1) / h.
\end{align*}
This formula is also used for 1D meshes of any type.

For non-Cartesian 2D meshes with linear ansatz functions, i.e., meshes of type \code{Struc}\code{tured}\code{DeformableOfDimension<2>}, the inversion of the mapping from element to world coordinate frame in \cref{eq:mapping_parameter_world} can also be done analytically. We consider this problem in a generic way, where both the point $\bfx$ and the nodes $\bfx^1$ to $\bfx^4$ of the 2D element are embedded in 3D space, $\bfx,\bfx^1,\dots,\bfx^4 \in \R^3$. The computation determines the element coordinates $(\xi_1,\xi_2)$ of the projection of $\bfx$ onto the plane of the triangle $(\bfx^1,\bfx^2,\bfx^3)$.

This functionality is used for specifying electrodes on the skin surface. The electrode positions are specified as a 2D grid in 3D space above the muscle. The mapping automatically projects the points of this grid onto the surface of the 3D mesh. \Cref{fig:electrodes} shows such a use case. A simulation of surface EMG is shown, the coloring corresponds to the potential $\phi_b$ in millivolts in the body domain. A grid of electrode points, visualized by spheres, is mapped onto the surface of the muscle mesh and simulates electrode patches that capture high density surface EMG.

% electrodes
\begin{figure}%
  \centering%
  \includegraphics[width=\textwidth]{images/implementation/electrodes.png}%
  \caption{Simulation of surface EMG using the fiber based electrophysiology model with body fat layer. Only the top surface of the fat layer mesh is shown. The spheres correspond to the position of surface electrodes that are used to sample the simulation result in a spatial grid.}%
  \label{fig:electrodes}%
\end{figure}%

After calculating the mentioned projection on the 2D plane, the computation has to invert the map in \cref{eq:mapping_parameter_world}. The ansatz functions $\phi_i$ are bilinear in the coordinates $\xi_1$ and $\xi_2$. This quadratic equation has two solutions for the unknown coordinates $\bfxi$. The formulas for those solutions have been determined using the symbolic mathematics toolbox \emph{SymPy} \cite{meurer2017sympy} and the solution, where the point is inside the element or closer to its center is chosen.

For generic hexahedral 3D meshes, \cref{eq:mapping_parameter_world} is a cubic equation in $\bfxi$, and the analytic inversion is not feasible. However, for simplex elements, i.e., tetrahedra given by points $\bfx^1$ to $\bfx^4$, it is possible. The ansatz in this case is given by:
\begin{align*}
  \bfx &= (1-\xi_1-\xi_2-\xi_3)\,\bfx^1 + \xi_1\,\bfx^2 + \xi_2\,\bfx^3 + \xi_3\,\bfx^4.
\end{align*}
This can be reformulated as:
\begin{align}\label{eq:simplex_ansatz}
   \bfx-\bfx^1 &= (\bfx^2 - \bfx^1)\,\xi_1 + (\bfx^3  - \bfx^1)\,\xi_2 + (\bfx^4 - \bfx^1)\,\xi_3.
\end{align}
This linear system of three equations can be solved for the three unknowns $\xi_1,\xi_2$ and $\xi_3$.

To invert the mapping for hexahedral elements, we proceed as follows.
A hexahedral element can be subdivided into five simplex elements.
Four outer simplex elements share their faces with parts of the hexahedral's surface. One interior simplex element only touches the hexahedron surface by its edges.

In each of the four outer simplex elements, we define a coordinate system $(\xi_1,\xi_2,\xi_3)$ with the origin located at a corner of the hexahedron.
In these elements, the coordinates $\bfxi$ for the point $\bfx$ can be computed  using the ansatz in \cref{eq:simplex_ansatz}. The computed coordinate values can be transformed to the hexahedral coordinate system by applying the appropriate mirror operations $\xi \mapsto (1-\xi)$ on some coordinates. Using the average values of the hexahedral coordinates resulting from all four outer simplex elements gives a good approximation for the correct hexahedral element coordinates $\bfxi$ of the point $\bfx$.

To obtain the correct element coordinates, these approximate values are used as initial guess in a Newton scheme, which subsequently tries to find the root of $\bfr = (\bfxi - \bfx(\bfxi))$ and, thus, invert the mapping in \cref{eq:mapping_parameter_world}.

Runtime measurements have shown that the lower number of Newton iterations resulting from the heuristic with the four simplex elements to compute an initial guess outweighs the additional runtime for the heuristic and, in total, leads to a faster computation.

The Newton scheme uses the inverse Jacobian matrix of the mapping in \cref{eq:mapping_parameter_world}. If the residual norm $\Vert\bfr\Vert_2$ cannot not be brought under the threshold of \num{1e-8} in 16 iterations, this indicates that the problem of inverting the Jacobian is badly conditioned and the Jacobian has a large numerical error. In this case, the optimization is restarted using the derivative-free Nelder-Mead algorithm.

Before applying the Newton and Nelder-Mead algorithms, our implementation performs two basic checks that can directly terminate the computation of the coordinates: First, the coordinates of the point $\bfx$ are compared with the bounding box of all nodes of the element. If the point is outside the bounding box, the element coordinates do not have to be computed, and a different element, which contains the point $\bfx$, is searched. Second, all node positions are checked for equality with the point $\bfx$. If $\bfx$ is the same as one of the node positions, the element coordinates are directly known. This case frequently occurs, if one of source and target mesh is a subset of the other.

\subsection{Conditioning of the Problem and Mapping Tolerances}

As mentioned in the last section, the Newton scheme that solves the inverse problem of mapping a point from elemental coordinates to world coordinates uses the inverse Jacobian matrix of the mapping. The inversion of this matrix has a high numerical error, if the condition number of the Jacobian matrix is large. A large condition number can be found for 3D hexahedral elements, where the two element coordinate directions for $\xi_1$ and $\xi_2$ are almost linearly dependent. This is the case for elements with an interior angle of nearly \SI{180}{\degree}. \Cref{fig:bad_element} shows such an element, which occurs at the outer boundary of the muscle mesh.

% bad_element
\begin{figure}%
  \centering%
  \includegraphics[width=0.3\textwidth]{images/implementation/bad_element2.png}%
  \caption{Hexahedral element of the muscle mesh with an interior angle of nearly \SI{180}{\degree}. Such elements lead to poor conditioning of the Jacobian matrix inversion problem and, as a consequence, require numerous Newton iterations in the setup of the data mapping between meshes.}%
  \label{fig:bad_element}%
\end{figure}%

If the conditioning is too bad and the computed inverse Jacobian has a large numerical error, the Newton scheme fails to find a solution in the given maximum number of iterations and the Nelder-Mead algorithm is used instead. This algorithm usually succeeds. However, it requires significantly more compute time than the Newton scheme. The case where the Nelder-Mead algorithm is needed, however, only occurs for a small number of elements and only in highly-resolved meshes.

\Cref{fig:condition_number2} shows the condition number of the Jacobian matrix of the mapping from element to world coordinates per element. The condition number is numerically approximated using the \emph{von Mises} power iteration algorithm to obtain the largest eigenvalue of the Jacobian and its inverse.
It can be seen in \cref{fig:condition_number7x7} that the elements with the highest condition number are located along longitudinal lines on the outer surface of the muscle mesh. Two such lines exist on both sides of the muscle. The cross-sectional mesh at the top of the muscle shows that the elements along these lines have large interior angles at the respective positions.

% condition number 7x7
\begin{figure}%
  \centering%
  \begin{subfigure}{0.9\textwidth}
    \centering
    \includegraphics[width=\textwidth]{images/implementation/condition_number.png}%
    \caption{Scenario with $7\times 7$ fibers.}%
    \label{fig:condition_number7x7}%
  \end{subfigure}\\[4mm]
  \begin{subfigure}{0.9\textwidth}
    \centering
    \includegraphics[width=\textwidth]{images/implementation/condition_number2.png}%
    \caption{Scenario with $9\times 9$ fibers}%
    \label{fig:condition_number9x9}%
  \end{subfigure}
  \caption{Fiber meshes and corresponding muscle mesh, obtained with a sampling stride of two. The left and right view show both sides of the muscle mesh. The 3D mesh is colored by the condition number of the Jacobian matrix.}%
  \label{fig:condition_number2}%
\end{figure}%

\Cref{fig:condition_number9x9} shows the same information for a different mesh with $9\times 9$ fibers instead of the subset of $7\times 7$ fibers in \cref{fig:condition_number7x7}. In \cref{fig:condition_number9x9}, the outer surface of the muscle mesh is smoother and the interior angle of the elements along the respective longitudinal lines is even closer to \SI{180}{\degree}. Thus, the resulting maximum condition number has a higher value of \num{30.2} compared to \num{4.48} in the example of \cref{fig:condition_number7x7}.

Another effect can be seen in the visualization in \cref{fig:condition_number7x7}. The muscle mesh was generated from the fiber data with sampling strides of two in the cross-sectional directions. As a consequence, the nodes of the 3D mesh are part of every second fiber. This results in some outer fibers being located outside the domain of the 3D mesh. Such a case can be seen for the upper-most fiber in \cref{fig:condition_number7x7}.

To also involve such fibers in the computation, we enable data mapping between the 3D mesh and fibers that are outside but close to the 3D mesh. We add a tolerance parameter $\xi_\text{tolerance}$ to the implementation that specifies, how far outside the mesh fibers can be located to still be included in the mapping. On the element level, a point is considered to be part of an element, if its element coordinates $(\xi_1,\xi_2,\xi_3)$ are no further than $\xi_\text{tolerance}$ off the element domain, i.e., for %
\begin{align*}
  -\xi_\text{tolerance} \leq \xi_i \leq 1 + \xi_\text{tolerance}\quad \forall i \in \{1,2,3\}.
\end{align*}
This treats the outside fibers as if they were located inside the 3D mesh. For the fibers in the interior, the threshold leads to potentially multiple neighboring elements claiming ownership of a point. In this case, the element that contains the point without this tolerance value is chosen.
By default, the tolerance value is set to $\xi_\text{tolerance}=0.1$, but it can be adjusted to different values in the Python settings file if needed.

In summary, OpenDiHu can map data between any two overlapping meshes. The inversion of the mapping from elemental to world coordinates is an important task of this problem, which is non-trivial for 3D hexahedral elements and is solved numerically. The combination of fiber meshes with a 3D muscle mesh leads to specific effects such as degraded condition numbers or fibers outside the 3D mesh that have to be considered in the mapping.

\begin{reproduce_no_break}
  The visualizations in \cref{fig:condition_number2} were obtained using the \code{electrophysiology/fibers/fibers_emg} example. The condition number of the Jacobian is computed by the \code{StaticBidomainSolver} if the parameter \code{`enableJacobianConditionNumber`} is set to \code{True}.
\end{reproduce_no_break}


%---------------------------Mean Aspect Frobenius-----------------------------
\section{Mean Aspect Frobenius}

For quadrilaterals, there is not a unique definition of the aspect Frobenius.
Instead, we use the aspect Frobenius
defined for triangles (see section~\S\ref{s:tri-aspect-Frobenius}).
Consider the four triangles formed by pairs of neighboring quadrilateral edges.
Given three counterclockwise, consecutively ordered quadrilateral vertices $i$, $j$, and $k$
denote the triangular aspect frobenius $F_{ijk}$.
To obtain a single value for the metric, we average the four unique triangular aspects
\[
  q = \frac{1}{4}\left(F_{301} + F_{012} + F_{123} + F_{230}\right).
\]

\quadmetrictable{mean aspect frobenius}%
{$1$}%                                      Dimension
{$[1,1.3]$}%                                Acceptable range
{$[1,DBL\_MAX]$}%                           Normal range
{$[1,DBL\_MAX]$}%                           Full range
{$1$}%                                      Unit square
{\cite{pebay:04}}%                          Citation
{v\_quad\_med\_aspect\_frobenius}%          Verdict function name