\documentclass[aps,pre,preprint,floatfix,twoside,tightenlines,showpacs,
showkeys]{revtex4}
\usepackage{amsmath,graphicx}
%\usepackage{showkeys}
\vfuzz2pt % Don't report over-full v-boxes if over-edge is small
\hfuzz2pt % Don't report over-full h-boxes if over-edge is small
\bibliographystyle{apsrev}
%===============================================================
\begin{document}
%
%--------------------------------------
\title{Field theoretical representation of classical statistical mechanics. I. Wave-vector space}
\author{A.Yu.~Zakharov}\email[E-mail: ]{Anatoly.Zakharov@novsu.ru}
\author{E.V.~Sokolova} \email[E-mail: ]{lenux999@yandex.ru}
\affiliation{Novgorod State University, Novgorod the Great, 173003, Russia}
%
%
%----------------------------------------------------------------------
\begin{abstract}
Thermodynamic equivalence between classical many-body system and some auxiliary nonlinear auxiliary field is proved. Connection between Hamiltonians of the many-body system and the auxiliary field is derived.
\end{abstract}
%------------------------------------------------------------------------------
%
\pacs{05.20.-y, 05.70.Ce, 03.50.Kk}
\keywords{continual model, partition function, canonical ensemble, functional integral, interatomic potentials, non-linear field theory}
\maketitle
%------------------------------------------------------------------------------

%------------------------------------------------------------------------------
\section{Introduction}

There are a few different starting points for setting of the statistical mechanics problems. These starting points are canonical, microcanonical, grand canonical and other ensembles. In general, these ensembles are not equivalent. Moreover, nonequivalence of the ensembles occurs for most interesting problems, such as new phases nucleations, statistics of small systems, metastable states etc. Therefore, statistical mechanics in its present state is not a well-posed theory.

From this standpoint, it is interesting to develop the general methods that can be used to different ensembles so as to different models of statistical mechanics. The problem of the canonical configuration integral calculation exists in every ensemble of statistical mechanics with some variations: for canonical and grand canonical ensembles the configuration integral depends on the {\em real} temperature, whereas for microcanonical ensemble this  integral depends on the {\em imaginary} temperature~\cite{Zak0}. The main difficulty in the partition function calculation caused the atomic coordinates entanglements in the integrand. Factorization of the integrand on the atomic coordinates by means of the functional integral representation solves the entanglements problem. But instead of that, the new problem of the non-Gaussian functional integral calculation occurs.

Probably, for the first time the notion of the functional integration was introduced by Wiener~\cite{Wie}. In connection with statistical mechanics the functional integration method was initialized by Zubarev~\cite{Zub} and Edwards~\cite{Edw}. Some mathematical aspects  of the functional integration method, including approximate calculation of functional integrals,  are systematized by Egorov, Zhidkov and Lobanov~\cite{Ego}.

Functional integrals include integration over some set of the auxiliary functions. In accordance with domain of definition of the auxiliary functions, there are two basic variants of the functional integral representations for classical partition functions in classical statistical mechanics.
\begin{enumerate}
    \item Functional integration over the functions defined in the real space~\cite{Edw,Iva1,Iva2};
    \item Functional integration over the functions defined in the wave-vectors space~\cite{Zub,Ami,Par,Zak1}.
\end{enumerate}
%
In both of these variants the partition functions or the configuration integrals calculations reduced to the non-Gaussian functional integral evaluations.

Functional integration approach has essential advantages over the direct analysis of the configuration integrals. In particular, this method makes possible
\begin{enumerate}
    \item  avoidance of the combinatorial problems related to the Mayer expansion~\cite{Iva2,Par} and some other similar problems;
    \item analysis of some simple models statistical mechanics such as the systems with non-negative Fourier-transforms of the interatomic potentials \cite{Zak2,Efi,Bae1,Bae2};
\end{enumerate}
%
However, the auxiliary field in the functional integrals is an interesting object by itself. It gives a new way of the statistical mechanical problems formulation.

%%%%%%%%%%%%%%% INSERTED TEXT

%%%%%%%%%%%%%%%%%%%END INSERT

The object of this paper is the formulation of the new variant of the statistical mechanical problems setting. This variant based on the functional integration method over the auxiliary functions defined in the wave-vectors space.

\section{Functional integral representation in wave-vector space}

The generating functional of a system of $N$ particles, interacting via two-body potential~$v\left(\textbf{r}\right)$ in presence of an external field $\varphi\left(\textbf{r}\right)$, after integration with respect to momentum has the known form
%
\begin{equation}\label{Stat}
\begin{array}{r}
{\displaystyle
Z{\left\{  \varphi(\mathbf{r})\right\} } =\frac{V^{N}}{N!\lambda^{DN}} \idotsint\limits_{(V)}\ \left(\prod^{N}_{s=1}\frac{d^{D}R_{s}}{V}\right)\exp\left( -\beta\sum\limits_{s=1}^N \varphi(\textbf{R}_s)\right)}\\ \\
{\displaystyle
\times
\exp\left(-\frac{\beta}{2}\sum\limits_{\stackrel{\scriptstyle s,s'=1,}{s\neq s'}  }^{N} v\left(\textbf{R}_{s} - \textbf{R}_{s'}\right)\right)}{,}
\end{array}
\end{equation}
where $\lambda=\left(2\pi\hbar/m k_{B}T\right)^{1/2}$ is de Broglie thermal wavelength, $\beta=1/k_{B}T$ is reciprocal temperature, $V$ is the system volume, $D$ is the space dimensionality, $\hbar$ and $k_{B}$ are the Planck and Boltzmann constants, respectively.

The first exponent in the integrand separates into one-atom multipliers in contrast of the second exponent. Suppose that the central interatomic potential $v\left(\textbf{r}\right)$ assumes expansion into the Fourier series. Then the pairwise interactions energy of the particles in the system can be written as
%
\begin{equation}
\label{pot1}
\begin{array}{r}
{\displaystyle
\frac{1}{2} \sum\limits_{\stackrel{\scriptstyle s,s'=1,}{s\neq s'} }^N v(\textbf{R}_s - \textbf{R}_{s'}) = \frac{N}{2}\left(n\tilde{v} \left(0\right) - v\left(0\right)\right) }\\ \\
{\displaystyle  + \frac{1}{2V}\sum\limits_{\textbf{k}\in \Omega^+}v^{+}\left(\textbf{k}\right)\left[C^{2}\left(\textbf{k}\right) + S^{2}\left(\textbf{k}\right)\right]
 - \frac{1}{2V}\sum\limits_{\textbf{k}{'}\in\Omega^{-}} v^{-}\left(\textbf{k}{'}\right)\left[C^{2}\left(\textbf{k}{'}\right) + S^{2}\left(\textbf{k}{'}\right)\right]},
\end{array}
\end{equation}
where $C\left(\mathbf{k}\right)$ and $S\left(\mathbf{k}\right)$ are the collective variables
%
\begin{equation}
\label{cos}
C\left(\mathbf{k}\right)= \sum\limits^{N}_{s=1}\cos\left(\mathbf{k}\textbf{R}_s\right){;} \quad S\left(\mathbf{k}\right)= \sum\limits^{N}_{s=1}\sin\left(\mathbf{k}\textbf{R}_s\right){,}
\end{equation}
%
summation over $\mathbf{k}$ and $\mathbf{k}'$ in (\ref{pot1}) does not contain the point $\mathbf{k}=0$, the term ${-}\frac{N}{2}v\left(0\right)$ compensates the summands with $s = s{'}$ in the right hand side of (\ref{pot1}), $\Omega^{\pm}$ denote the subsets of the wave vector space in which the Fourier transform $\tilde{v}\left(\textbf{k}\right)$ of the interatomic potential is positive and negative, respectively,
\begin{equation}\label{v-pm}
\left\{
\begin{array}{l}
    {\displaystyle v^+\left(\mathbf{k}\right)=+\tilde{v},\quad \mathbf{k}\in\Omega^+ ;}\\
{\displaystyle v^-\left(\mathbf{k}\right)=-\tilde{v},\quad  \mathbf{k}\in\Omega^-, }
\end{array}
\right.
\end{equation}
$v^{\pm}(\mathbf{k})>0$, $n=N/V$.

The second exponent in the integrand of~(\ref{Stat}) as function of the collective variables has the following form:
\begin{equation}\label{Z-C-S}
\begin{array}{r}
    {\displaystyle \exp\left(-\frac{\beta}{2}\sum\limits_{\stackrel{\scriptstyle s,s'=1,}{s\neq s'}  }^{N} v\left(\textbf{R}_{s} - \textbf{R}_{s'}\right)\right) = \exp {\left( \frac{\beta N}{2} \left[v(0) - n\tilde{v}(0) \right] \right)}}\\ \\
\times {\displaystyle  \left[ \prod_{\mathbf{k}\in \Omega^+} e^{ \left( -\frac{\beta v^+(\mathbf{k})}{2V} \left\{ C^2(\mathbf{k}) + S^2(\mathbf{k}) \right\} \right)} \right]\, \left[ \prod_{\mathbf{k}'\in \Omega^-} e^{ \left( \frac{\beta v^-(\mathbf{k}')}{2V} \left\{ C^2(\mathbf{k}') + S^2(\mathbf{k}') \right\} \right)} \right] }.
\end{array}
\end{equation}

Applying the Stratonovich-Hubbard transformation
\begin{equation}\label{SH}
\left\{
\begin{array}{c}
    {\displaystyle e^{-\frac{B^2}{2A}}=\sqrt\frac{A}{2\pi} \int\limits_{-\infty}^{+\infty}e^{-\frac{A}{2}x^{2}+iBx}\,dx,}\\
{\displaystyle e^{+\frac{B^2}{2A}}=\sqrt\frac{A}{2\pi} \int\limits_{-\infty}^{+\infty}e^{-\frac{A}{2}x^{2}+Bx}\,dx}
\end{array}
\right.
\end{equation}
for each of the exponents in~(\ref{Z-C-S})
%
\begin{equation}\label{e1}
\begin{array}{r}
{\displaystyle e^{ \left( -\frac{\beta v^+(\mathbf{k})}{2V} \left\{ C^2(\mathbf{k}) + S^2(\mathbf{k}) \right\} \right)} = \iint\limits_{-\infty}^{+\infty} \frac{\beta m \omega^{2} (\mathbf{k})\, dx^{+}(\mathbf{k})\, dy^{+} (\mathbf{k})}{2\pi}\ e^{ -\frac{\beta m \omega^{2}(\mathbf{k})\left(\left[x^{+} \left(\mathbf{k}\right)\right]^{2} + \left[y^{+}\left(\mathbf{k}\right)\right]^{2}\right)}{2}} }\\
\times\ {\displaystyle e^{i\beta \sqrt{\frac{m v^+(\mathbf{k})}{V}} \omega(\mathbf{k})  \left[ x^+(\mathbf{k}) C(\mathbf{k}) + y^+(\mathbf{k}) S(\mathbf{k}) \right] }\, ,  }
\end{array}
\end{equation}
%
\begin{equation}\label{e2}
\begin{array}{r}
{\displaystyle e^{ \left( \frac{\beta v^-(\mathbf{k}')}{2V} \left\{ C^2(\mathbf{k}') + S^2(\mathbf{k}') \right\} \right)} = \iint\limits_{-\infty}^{+\infty} \frac{\beta m \omega^{2} (\mathbf{k}')\, dx^{-}(\mathbf{k}')\, dy^{-} (\mathbf{k}')}{2\pi}\ e^{ -\frac{\beta m \omega^{2}(\mathbf{k}')\left(\left[x^{-}(\mathbf{k}')\right]^{2} + \left[y^{-}(\mathbf{k}')\right]^{2}\right)}{2}} }\\
\times\ {\displaystyle e^{\beta \sqrt{\frac{m v^-(\mathbf{k}')}{V}} \omega(\mathbf{k}')  \left[ x^-(\mathbf{k}') C(\mathbf{k}') + y^-(\mathbf{k}') S(\mathbf{k}') \right] }\, ,  }
\end{array}
\end{equation}
we obtain the following functional integral representation for $Z{\left\{  \varphi(\mathbf{r})\right\}}$:
%
\begin{equation}
\label{Z}
\begin{array}{r}
{\displaystyle
Z{\left\{  \varphi(\mathbf{r})\right\} } = \frac{V^{N}}{N!\lambda^{DN}}e^{\left( \frac{\beta N}{2} \left[v(0) - n\tilde{v}(0) \right] \right)}
}\\
\times\ {\displaystyle
\idotsint\limits_{-\infty}^{+\infty} \left(\prod_{\mathbf{k}\in\Omega^{+}} \frac{\beta\, m\, \omega^{2}\left(\mathbf{k}\right)\,dx^{+}\left(\mathbf{k}\right)dy^{+} \left(\mathbf{k}\right)}{2\pi}\right) \left(\prod_{\mathbf{k}'\in\Omega^{-}} \frac{\beta\, m\, \omega^{2}\left(\mathbf{k}'\right)dx^{-}\left(\mathbf{k}'\right)dy^{-} \left(\mathbf{k}'\right)}{2\pi}\right)
}\\
{\displaystyle
\times {\exp\left(- \beta \left\{ \sum_{\mathbf{k}\in\Omega^+}\frac{ m\, \omega^{2}\left(\mathbf{k}\right)\left(\left[x^{+} \left(\mathbf{k}\right)\right]^{2} + \left[y^{+}\left(\mathbf{k}\right)\right]^{2}\right)}{2} \right\}\right)}
}\\
{\displaystyle
\times {\exp\left(- \beta \left\{ \sum_{\mathbf{k}'\in\Omega^-}\frac{ m\, \omega^{2}\left(\mathbf{k}'\right)\left(\left[x^{-} \left(\mathbf{k}'\right)\right]^{2} + \left[y^{-}\left(\mathbf{k}'\right)\right]^{2}\right)}{2} \right\}\right)}
}\\ {\displaystyle \times
\left[\mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right)\right]^{N}}\, ,
\end{array}
\end{equation}
where
%
\begin{equation}
\label{Fu}
\begin{array}{r}
{\displaystyle
\mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right) = \int\limits_{(V)}\frac{d\mathbf{r}}{V}\, e^{{-}\beta\varphi\left(\mathbf{r}\right)}} \\
{\displaystyle
\times\exp\left\{i\beta\sum_{\mathbf{k}\in\Omega^{+}} \sqrt{\frac{m v^{+}\left( \mathbf{k}\right)}{V}}\ \omega \left(\mathbf{k}\right) \left[x^{+}\left(\mathbf{k}\right) \cos\left(\mathbf{k}\mathbf{r}\right) + y^{+}\left(\mathbf{k}\right) \sin\left(\mathbf{k}\mathbf{r}\right)\right]\right\}} \\
{\displaystyle \times
\exp\left\{\beta\sum_{\mathbf{k}'\in\Omega^{-}}\sqrt{\frac{m v^{-}\left(\mathbf{k}'\right)}{V}}\ \omega\left(\mathbf{k}'\right) \left[x^{-}\left(\mathbf{k}'\right)\cos \left(\mathbf{k}'\mathbf{r}\right) + y^{-}\left(\mathbf{k}'\right) \sin\left(\mathbf{k}'\mathbf{r}\right)\right]\right\}},
\end{array}
\end{equation}
$\omega\left(\mathbf{k}\right)$ is an arbitrary positive function of the wave-vector with the dimensionality of the circular frequency, $m$ is an arbitrary positive parameter with the dimensionality of mass, and  $x^{\pm}\left(\mathbf{k}\right)$, $y^{\pm}\left(\mathbf{k}\right)$ are auxiliary  variables as a result of Stratonovich-Hubbard transformation.

Functional $ \mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right) $ has a very simple physical interpretation: it is the configuration integral for one particle in {\em complex-valued} external field $\Psi\left(\textbf{r}\right)$:
\begin{equation}
\label{psi}
\begin{array}{r}
{\displaystyle
\Psi\left(\mathbf{r}\right)=\varphi\left(\mathbf{r}\right) - i\sum_{\mathbf{k}\in\Omega^{+}}\sqrt{\frac{mv^{+} \left(\mathbf{k}\right)}{V}}\omega\left(\mathbf{k}\right) \left[x^{+}\left(\mathbf{k}\right) \cos\left(\mathbf{k}\mathbf{r}\right) + y^{+}\left(\mathbf{k}\right) \sin\left(\mathbf{k}\mathbf{r}\right)\right]}\\
{\displaystyle -
\sum_{\mathbf{k}{'}\in\Omega^{-}} \sqrt{\frac{mv^{-}\left(\mathbf{k}{'}\right)}{V}} \omega\left(\mathbf{k}{'}\right) \left[x^{-}\left(\mathbf{k}{'}\right)\cos \left(\mathbf{k}{'}\mathbf{r}\right) + y^{-}\left(\mathbf{k}'\right)\sin\left(\mathbf{k}'\mathbf{r}\right)\right]}.
\end{array}
\end{equation}
This complex-valued external field consists of two parts: the ``true'' external field $\varphi\left(\mathbf{r}\right)$ and some
artificial complex field caused by exclusion of the interatomic interactions   and represented in the form of the Fourier series with
its coefficients $\sqrt{\frac{mv^{\pm}\left(\mathbf{k}\right)}{V}}\, \omega\left(\mathbf{k}\right)x^{\pm}\left(\mathbf{k}\right)$, $\sqrt{\frac{mv^{\pm}\left(\mathbf{k}\right)}{V}}\, \omega\left(\mathbf{k}\right)y^{\pm}\left(\mathbf{k}\right)$.
The expression $\mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right), y^{\pm}\left(\mathbf{k}\right), \left\{\varphi\left(\textbf{r}\right)\right\}\right)^{N}$ is a configuration integral of a classical ideal gas in the external
field $\Psi\left(\textbf{r}\right)$.

In accordance with (\ref{Z}), {\bf any classical system of interacting particles is statistically equivalent to an ideal gas in the complex-valued external field with Gaussian distribution of its the Fourier coefficients}.

There are a few variants for functional integral representations like~(\ref{Z}) of the canonical and grand canonical partition functions in statistical mechanics. These representations can be used for analysis of some concrete models~\cite{Zak2,Efi,Bae1,Bae2}. But, there are not any general methods of the functional integrals calculation excepting Gaussian integrals. Therefore, most of the results, related to the functional integral representations of the partitions functions in statistical mechanics, are obtained by the following ways:
\begin{enumerate}
    \item The saddle point method. This method is consistent if $\Omega^- = \emptyset$ and leads to Gaussian functional integral. The saddle point method relates to the mean field approximation. Otherwise (i.e. if $\Omega^- \not= \emptyset$), the location of the saddle point in space of the auxiliary field components depends on temperature and Gaussian approximation is inadequate. This problem has not solution yet.
    \item The expansions of the functional integral in powers of the auxiliary fields $x^{\pm}(\mathbf{k})$, $y^{\pm}(\mathbf{k})$ with summation  of some finite number of the terms in this series. In this connection, there is no results on this series convergences.
\end{enumerate}

\section{Hamiltonian of Auxiliary Field}

The expression (\ref{Z}) can be interpreted as a statistical integral of the system of interacting oscillators. Substitute the identity
%
\begin{equation}
\label{1}
\frac{\beta}{2\pi m}\int\int dp_{x}dp_{y}\exp\left[{-}\beta\left(\frac{p^{2}_{x}}{2m} + \frac{p^{2}_{y}}{2m}\right)\right] = 1,
\end{equation}
into~(\ref{Z}) and obtain
%
\begin{equation}
\label{ZZ}
\begin{array}{r}
{\displaystyle
Z{\left\{  \varphi(\mathbf{r})\right\} } = \frac{V^{N}}{N!\lambda^{DN}} e^{\left( \frac{\beta N}{2} \left[v(0) - n\tilde{v}(0) \right] \right)}}\\ \\
{\displaystyle\times
\idotsint\limits_{-\infty}^{+\infty}\left(\prod\limits_{\mathbf{k}\in\Omega^{+}}\left[\frac{\beta\omega \left(\mathbf{k}\right)}{2\pi}\right]^{2}dx^{+}\left(\mathbf{k} \right)dp^{+}_{x}\left(\mathbf{k}\right)dy^{+}\left(\mathbf{k} \right)dp^{+}_{y}\left(\mathbf{k}\right)\right)}\\ \\
{\displaystyle\times
\left(\prod\limits_{\mathbf{k}'\in\Omega^{-}}\left[\frac{\beta\omega \left(\mathbf{k}'\right)}{2\pi}\right]^{2}dx^{-}\left(\mathbf{k}{'} \right)dp^{-}_{x}\left(\mathbf{k}'\right)dy^{-}\left(\mathbf{k}' \right)dp^{-}_{y}\left(\mathbf{k}'\right)\right)}\\ \\
{\displaystyle \times
\exp\left\{{-}\beta\sum\limits_{\mathbf{k}\in\Omega^{+}}\left(\frac{\left( \left[p^{+}_{x}\left(\mathbf{k}\right)\right]^{2} + \left[p^{+}_{y}\left(\mathbf{k}\right)\right]^{2}\right)}{2m} + \frac{m\omega^{2}\left(\mathbf{k}\right)\left(\left[x^{+}\left(\mathbf{k} \right) \right]^{2} + \left[y^{+}\left(\mathbf{k}\right)\right]^{2}\right)}{2}\right)\right\} }\\ \\
{\displaystyle\times
\exp\left\{{-}\beta\sum\limits_{\mathbf{k}'\in\Omega^{-}}\left(\frac{\left( \left[p^{-}_{x}\left(\mathbf{k}'\right)\right]^{2} + \left[p^{-}_{y}\left(\mathbf{k}'\right)\right]^{2}\right)}{2m} + \frac{m\omega^{2}\left(\mathbf{k}'\right)\left(\left[x^{-}\left( \mathbf{k}'\right)\right]^{2} + \left[y^{-}\left(\mathbf{k}'\right)\right]^{2}\right)}{2}\right)\right\}}\\ \\
{\displaystyle\times
\left[\mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right)\right]^{N}}.
\end{array}
\end{equation}
%
%
This integral represents the classical partition function of a system described by the Hamiltonian $\tilde{\mathcal{H}}$:
%
\begin{equation}
\label{Ham}
\begin{array}{r}
{\displaystyle
\tilde{\mathcal{H}} = \sum\limits_{\mathbf{k}\in\Omega^{+}} \left[\frac{\left[p^{+}_{x}\left(\mathbf{k}\right)\right]^{2}}{2m} + \frac{m\omega^{2} \left(\mathbf{k}\right) \left(x^{+}\left(\mathbf{k}\right)\right)^{2}}{2} +
\frac{\left[p^{+}_{y}\left(\mathbf{k}\right)\right]^{2}}{2m} + \frac{m\omega^2\left(\mathbf{k}\right)\left(y^{+} \left(\mathbf{k}\right)\right)^{2}}{2}\right] }\\ \\
{\displaystyle+
\sum\limits_{\mathbf{k}'\in\Omega^{-}} \left[\frac{\left[p^{-}_{x}\left(\mathbf{k}'\right)\right]^{2}}{2m} + \frac{m\omega^{2}\left(\mathbf{k}'\right) \left(x^{-}\left(\mathbf{k}'\right)\right)^{2}}{2} +
\frac{\left[p^{-}_{y}\left(\mathbf{k}'\right)\right]^{2}}{2m} + \frac{m\omega^2\left(\mathbf{k}'\right) \left(y^{-}\left(\mathbf{k}'\right)\right)^{2}}{2}\right]}\\ \\
{\displaystyle -
\frac{N}{\beta}\ln{\mathcal{F}_{1}\left(x^{\pm}\left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right)}}.
\end{array}
\end{equation}
%
The multipliers $\frac{2\pi}{\beta\omega(\mathbf{k})}$ in the integrand of~(\ref{ZZ}) have the dimensionality of the Planck constant and play the role of an elementary cell volume in related phase space.

Hamiltonian (\ref{Ham}) depends on the generalized coordinates $x^{\pm}\left(\mathbf{k}\right)$,  $y^{\pm}\left(\mathbf{k}\right)$ and the generalized momenta $p^{\pm}_{x}\left(\mathbf{k}\right)$, $p^{\pm}_{y}\left(\mathbf{k}\right)$. In addition, $\tilde{\mathcal{H}}$ contains the temperature as parameter in the term $\mathcal{F}_{1}\left(x^{\pm} \left(\mathbf{k}\right),\ y^{\pm}\left(\mathbf{k}\right),\ \left\{\varphi\left(\mathbf{r}\right)\right\}\right)$.
%

Thus, {\bf the partition functions for a classical many-body system and for the auxiliary field with Hamiltonian~(\ref{Ham}) are identical}.

\section{conclusion}
In accordance with relation~(\ref{ZZ}), the problem of obtaining the thermodynamic properties of many-body system is equivalent to the analogical problem of a system described by Hamiltonian~(\ref{Ham}). This Hamiltonian contains the summands corresponding to a system non-interacting classical harmonic oscillators (the first and the second lines in formula~(\ref{Ham}));  the third lines of~(\ref{Ham})  contains interactions between these fictitious oscillators including their anharmonicities.

This Hamiltonian leads to some non-linear equation of the auxiliary field motion. The analysis of the auxiliary field evolution on base of these equations can be used for the statistical properties of the auxiliary fields by analogy with molecular dynamics method.

\begin{thebibliography}{99}

\bibitem{Zak0} {\it A.Yu.~Zakharov.} Techn. Phys. Lett., 2003. {\bf 29}. 791.

\bibitem {Wie} {\it N.~Wiener.} J. Math. and Phys. Sci., 1923. V. {\bf 2}. 131.

\bibitem{Zub} {\it D.N.~Zubarev.} Dokl. Akad. Nauk SSSR, 1954. {\bf 95}. No.4. 757.
%
\bibitem{Edw} {\it S.F.~Edwards.}  Phil. Mag., 1959. {\bf 46}. 1171.
%
\bibitem{Ego} {\it A.D.~Egorov, E.P.~Zhidkov, Yu.Yu.~Lobanov.} Introduction into Theory and Applications of Functional Integration. Moscow: Fizmatlit, 2006. (In Russian).
%
\bibitem{Iva1} {\it Yu.M.~Ivanchenko, A.A.~Lisyansky.} Phys. Lett. A, 1983. {\bf 98}. 115.

\bibitem{Iva2} {\it Yu.M.~Ivanchenko, A.A.~Lisyansky.} Physics of Critical Fluctuations. N.Y.: Springer, 1995.

\bibitem{Ami} {\it D.J.~Amit.} Field Theory, the Renormalization Group, and Critical Phenomena. N.Y.: McGraw-Hill, 1978.% 336 p.
%
\bibitem{Par} {\it G.~Parisi.} Statistical Field Theory. Reading, Massachusetts: Addison-Wesley, 1988. % 352 p.
%
\bibitem{Zak1} {\it A.Yu.~Zakharov.}  Phys. Lett. A. 1990. {\bf 147}. 442.
%
\bibitem{Zak2} {\it A.Yu.~Zakharov, I.K.~Loktionov.} Theor. Math. Phys. 1999. {\bf 119}. 532.
%
\bibitem{Efi} {\it G.V.~Efimov, E.A.~Nogovitsin.} Physica A. 1996. {\bf 234}. 506.
%
\bibitem{Bae1} {\it S.A.~Baeurle, R.~Marto\v{n}\'ak, M.~Parrinello.} J. Chem. Phys. 2002. {\bf 117}. 3027.
%
\bibitem{Bae2} {\it S.A.~Baeurle, G.V.~Efimov, E.A.~Nogovitsin.} J. Chem. Phys. 2006. {\bf 124} 224110.
%
%

\end{thebibliography}
%------------------------------------------------------------------------------
\end{document}
%==============================================================================


\section{Collision detection\label{collisionDetection}}

I now turn to the fourth main component of the system (as listed in section~\ref{introOverview}).
An important requirement of the simulation is that bodies must not penetrate each other. In order
to enforce this constraint, the program must first be able to detect penetration.

\subsection{Intersection of triangle meshes\label{meshIntersection}}

Collision detection determines which meshes are geometrically in contact, and what type of contact
is present. The simplest algorithm for this purpose would be to take each triangle
of one mesh and test it for intersection~\cite{Moeller:97} against each triangle of the other
mesh. This $O(N^2)$ algorithm is clearly very inefficient; most research in collision detection
endeavours to create algorithms which are as close as possible to $O(1)$ complexity while
remaining semantically equivalent.

Fast computation is only a minor concern in this project, therefore I shall describe my solution
only briefly. This algorithm was suggested by Dr.~Breton Saunders~\cite{Saunders} and is
simpler than most published algorithms, but nevertheless effective.

For each mesh, the closest-fitting Axis-Aligned Bounding Box (AABB) is computed. The set of
triangles is split approximately in half along the axis of the longest bounding box side, and
an AABB is computed for each subset of triangles (the two new AABBs may overlap). The subdivision
continues recursively until each box contains only a single triangle. Thus we obtain a binary
tree of bounding boxes (see figure~\ref{collisionVolumes}).

\begin{figure}
\centerline{\includegraphics{figures/coll-volumes}}
\caption{Example tree of axis-aligned bounding boxes (AABBs).\label{collisionVolumes}}
\end{figure}

AABBs can efficiently be tested for intersection. To determine whether two meshes are in
contact, the boxes at the roots of their AABB trees are tested against each other. If the boxes
intersect, all four pairings of their immediate children are tested. This procedure continues
recursively as long as the boxes intersect. At the leaves of the tree, the actual triangles are
tested for intersection.

\subsection{Finding the time of contact\label{findingContactTime}}

This collision detection algorithm returns nothing if meshes are separated me\-re\-ly by a very
small distance. Thus it is likely that bodies which were separate in one time step are suddenly
found to have interpenetrated in the next. There are elaborate solutions which predict the time of
impact using proximity detection and the bodies' velocities. I take a simpler approach: if, at
some time, meshes have penetrated beyond some tolerance threshold, the current simulation step
is discarded and retried using a smaller step length.

Retrying a step is quite expensive, so it is desirable to find the time of first contact with a
minimum number of retries. The depth of penetration can usually be estimated from the collision
geometry, and the velocities of the bodies are known from the simulation. Hence I can use the
Newton-Raphson algorithm~\cite{NRinC} for root finding (see figure~\ref{collisionTime}) to make
a good guess at the next step size. This method converges rapidly in most cases, but
occasionally it is unstable, so my program automatically resorts to binary
search~\cite{Sedgewick:83} if Newton-Raphson diverges or converges too slowly.

\begin{figure}
\psfrag{frag:0}{$0$}
\psfrag{frag:delta}{$-d$}
\psfrag{frag:t}{$t$}
\psfrag{frag:h}{$t+h$}
\psfrag{frag:hprime}{$t+h'$}
\centerline{\includegraphics{figures/coll-time}}
\caption{Estimating a new step length $h'$ after penetration occurred when using step length $h$.
    The iteration stops when the penetration depth lies within the tolerance $d$.
    \label{collisionTime}}
\end{figure}

\subsection{Types of contact}

We are now in a state where the polygon meshes are in non-penetrative contact, i.e.\ there is some
intersection between their surfaces, but the intersection of their volumes is very small or zero.
Between polyhedral bodies we can identify several basic types of contact, and the most common~--
\emph{vertex/face} and \emph{edge/edge} contact~-- are exemplified in figure~\ref{contacts1Figure}.
I have derived expressions for handling these two types of contact in
appendices~\ref{vertexFaceConstraint} and~\ref{edgeEdgeConstraint}.

There are many other types of contact which occur, particularly when complicated meshes
collide. It is unclear how these might best be handled; regrettably I could not find any results
of research in this area. It seems intuitively plausible that it might be possible to decompose any
contact between polyhedral bodies into a set of vertex/face and edge/edge contacts, as
figure~\ref{contacts2Figure} demonstrates. However, no such algorithm is known to me, and my own
attempts at creating one turned out to be unfruitful~-- the problem is extraordinarily difficult
to tackle in general.

Instead, I chose to use a heuristic if a collision cannot be classified as either vertex/face or
edge/edge: the colliding surfaces are approximated by spheres, planes and points, for which
handling expressions can be derived. This approximation can cause unrealistic behaviour in some
cases, but I have not found it to be a problem in practice.

\section{Collision and contact handling\label{collisionHandling}}

\subsection{Overview}

In the last section I explained how to detect contact between meshes. To prevent the bodies from
penetrating each other during the simulation, the collision that has been detected must be
handled in a physical way.

Let us distinguish two cases of contact between bodies: resting contact and colliding contact.
Resting contact is given when the relative velocity at the contact point is zero (or very small)
when projected onto the contact plane. Bodies in colliding contact are moving towards each other.

Creating a simulation involving contacts is generally seen as a difficult task.
Baraff~\cite{BaraffWitkin:97} derives equations to handle collisions, and outlines (with a number
of errors) a way of handling resting contact. Unfortunately his collision handling does not work
in combination with constraints, and his resting contact computation relies on a complicated and
uncommon numerical routine. In this project, I developed a new method of handling contacts which
is simpler to implement, more powerful, and works perfectly together with constraints like those
required for articulated bodies.

\begin{figure}
\centerline{\includegraphics{figures/contacts1}}
\caption{Basic types of polyhedral contact: \emph{(a)}~vertex/face, \emph{(b)}~edge/edge.
    \label{contacts1Figure}}
\end{figure}

\begin{figure}
\centerline{\includegraphics{figures/contacts2}}
\caption{Two examples of composite contacts between polyhedral bodies:
    \emph{(a)}~four vertex/face contacts (one for each corner on the upper cube's bottom face),
    \emph{(b)}~two vertex/face and two edge/edge contacts.
    \label{contacts2Figure}}
\end{figure}

\subsection{Resting contact\label{restingContact}}

Bodies in resting contact exert equal and opposite forces on each other so that they do not
interpenetrate. This force must exactly balance the outside force, otherwise they will accelerate
apart. The direction of this force is perpendicular to the plane of contact.

We need an algorithm which computes the contact forces in an arbitrary system, where there may be
objects stacked on top of each other, different forces and torques acting, etc. Let us employ a
constraint function $c$ whose value is positive when the bodies are separated, zero when they are
in contact, and negative when they have penetrated. In resting contact we have $\dot{c} = 0$. The
function becomes interesting when we consider its second derivative, $\ddot{c}$. The
non-penetration constraint for a resting contact can be written as
\begin{equation} \label{constrInequality}
\ddot{c} \ge 0.
\end{equation}

More exactly, if it is the case that $\ddot{c} < 0$, we need to apply forces and torques
to the bodies such that afterwards we have $\ddot{c} = 0$. When
$\ddot{c} \ge 0$, no force is applied (otherwise we would be glueing the bodies together).
But how do we solve this inequality in practice? At this point we diverge from Baraff's
method~\cite{BaraffWitkin:97}, which expresses equation~\ref{constrInequality} and additional
side conditions as a \emph{quadratic program} and uses a specialized numerical solver.

Let us take a much simpler approach and pretend for now that (\ref{constrInequality})
contained an equals sign. Then this is a constraint like any other, which we can satisfy by using
the Lagrange multiplier method of section~\ref{lagrange}. Moreover, if there are multiple
points of resting contact in the system, and also `real' equality constraints like joints between
bodies, we can solve all of these simultaneously without having to think twice.

However, having solved equation~\ref{lagrangeEquation} for \ve{\lambda}, we need to take care.
Observe equation~\ref{lagrangeSolution}, in which the constraint forces are computed:
\begin{equation}
\ve{\Phi}_c = \m{J}^T\ve{\lambda} = \sum_{i=1}^{m} (\ve{J}_i)^T \lambda_i
\end{equation}
Since each row of \m{J} is generated by a particular constraint, and the $i$th row of \m{J} is
scaled with component $\lambda_i$ of \ve{\lambda} in the linear combination of constraint forces,
we can say that each each component $\lambda_i$ specifies the `amount' of constraint $i$
to apply to the system. Moreover, a positive value of the $\lambda_i$ component generates
forces and torques which push the bodies apart, while a negative value pulls them together (the
opposite sign convention is equivalent, but one convention must be used consistently). It is such
a negative $\lambda_i$ that we must avoid.

This gives us a basis for an algorithm which turns (\ref{constrInequality}) back into what
it actually is~-- an inequality: set up constraint functions for all contact points, and solve the
system of linear equations for the Lagrange multiplier \ve{\lambda}. In this vector, find all
components relating to inequality constraints whose value is negative. (Equality constraints
are left untouched whatever their \ve{\lambda} component value is.)
If there are none, calculate $\m{J}^T\ve{\lambda}$ and add the forces and torques to the system~--
then we are done. If there are negative components, completely discard the constraints to which
they belong (since the bodies are accelerating away from each other in this point, the contact
will break in the next time step), then repeat the solving for \ve{\lambda} with the reduced set
of constraints. The process may take several iterations before terminating, but always terminates
because in each iteration we either reduce the number of active constraints or exit.

I have not yet been successful in proving this novel algorithm correct, but despite extensive
pondering and testing I have not found any examples in which it fails either.

\subsection{Colliding contact\label{collidingContact}}

While points of resting contact had the property that $\dot{c} = 0$, colliding contact is
characterized by $\dot{c} < 0$. (If $\dot{c} > 0$ then the bodies are separating.
Such a contact can be ignored for now, but we cannot fully discard it, as explained
below.) The bodies' linear and angular momenta must be modified instantaneously to satisfy
$\dot{c}' \ge 0$, otherwise the bodies will interpenetrate in the next time step.

Physically, this operation is expressed in terms of an \emph{impulse}. An impulse \ve{u} has the
same dimensions as linear momentum \ve{p} (kg\,m/s) and is directly added to the momentum of the
body to which it is applied: $\ve{p}' = \ve{p} + \ve{u}$. If the impulse is applied at the point
$\ve{s}$, and \ve{r} is the body's centre of mass, it also changes the angular momentum to
$\ve{L}' = \ve{L} + (\ve{s} - \ve{r})\times\ve{u}$. This behaviour is analogous to that of a
force.

A collision between two bodies must conserve the total momentum of the system~\cite{Feynman:63}.
This implies that the impulses acting on the bodies at a point of collision must be equal and
opposite. However, the collision need not necessarily conserve energy. A collision which does
conserve energy is called \emph{fully elastic}, and may be given for example
by an ideal rubber ball which, when dropped, bounces up to exactly the same height as it was
dropped from. At the other extreme, an \emph{inelastic} collision is one which reduces the energy
of the system as much as possible~-- the bodies do not `bounce apart' again.

Most real collisions are somewhere in between, depending on the materials of the colliding
objects. The elasticity (also called \emph{coefficient of restitution}) is a scalar
$0 \le \varepsilon \le 1$, where $\varepsilon = 0$ indicates an inelastic collision, and
$\varepsilon = 1$ full elasticity.

How do we now find the impulses we need to apply to the colliding bodies, and how do we
simultaneously handle constraints? Once again we can use a Lagrange multiplier method, but a new
equation must be derived which operates on impulses rather than on forces.

Set up a vector \ve{c} of concatenated constraint functions including all equality constraints
and all points of colliding contact. Points of resting contact and separating contacts must
not be included. Now for all points $i$ of colliding contact we have $\dot{c}_i < 0$.
Remember that this value is the relative velocity of the bodies in the point of contact,
projected onto the normal of the contact plane. Then the relative velocity $\dot{c}_i'$ after
the collision is given by $\dot{c}_i' = -\varepsilon_i \dot{c}_i$. The components of the relative
velocity parallel to the contact plane remain unchanged.

Assume for convenience that the first $m$ components of \ve{c} come from equality constraints, and
that the remaining $k$ components are due to inequalities.
Then $\dot{\ve{c}}'$ is the required value of $\dot{\ve{c}}$ after the collision:
\begin{equation}
\dot{\ve{c}}' = \left[\begin{array}[m]{c}
    \left. \begin{array}{c} 0 \\\vdots\\ 0 \end{array} \right\} m \\
    -\varepsilon_1 \dot{\ve{c}}_{m+1} \\\vdots\\
    -\varepsilon_k \dot{\ve{c}}_{m+k}
    \end{array}\right]
\end{equation}
i.e.\ we require all equalities to be satisfied, and all inequalities to have `bounced' by the
right amount. We can rewrite this as $\dot{\ve{c}}' = \dot{\ve{c}} - \m{E}\dot{\ve{c}}$, where
\m{E} is the diagonal $m+k \times m+k$ matrix
\begin{equation}
\m{E} = \left[ \begin{array}{cc}
    \begin{array}{ccc} 1 \\ & \ddots \\ && 1 \end{array} \\
    \underbrace{\quad\quad\quad\quad}_m &
    \begin{array}[t]{ccc} 1+\varepsilon_1 \\ & \ddots \\ && 1+\varepsilon_k \end{array}
    \end{array} \right]
\end{equation}

Let us now concatenate the linear and angular momenta of all $n$ bodies into a single vector
\ve{\Psi}, like we previously did for forces and torques (equation~\ref{PhiVector}):
\begin{equation} \label{PsiVector}
\ve{\Psi} = \left[\begin{array}{c}
    \ve{p}_1 \\ \ve{L}_1 \\ \vdots \\ \ve{p}_n \\ \ve{L}_n \end{array}\right]
\end{equation}

From the definition of $\m{M}^{-1}$ (equation~\ref{massInertiaTensor}) we can deduce that
$\dot{\ve{x}} = \m{M}^{-1}\ve{\Psi}$. We are seeking a vector $\ve{\Psi}_c$ which, when
added to $\ve{\Psi}$, causes the constraints to return the value $\dot{\ve{c}}'$:
\begin{equation} \label{cDotPrime}
\dot{\ve{c}} = \m{J}\dot{\ve{x}} = \m{J}\m{M}^{-1}\ve{\Psi} \quad\Longrightarrow\quad
    \dot{\ve{c}}' = \m{J}\m{M}^{-1}(\ve{\Psi} + \ve{\Psi}_c)
\end{equation}
(cf.\ equation~\ref{cDotAndCDDot}).
It turns out\footnote{The argument is analogous to the derivation of the force vector in terms of
Lagrange multipliers; see~\cite{BaraffWitkin:97} for details.} that this vector can be written as
$\ve{\Psi}_c = \m{J}^T\ve{\lambda}$ for some $m+k$-row vector \ve{\lambda}. Substituting the
previously defined expressions into equation~\ref{cDotPrime}:
\begin{eqnarray}
\dot{\ve{c}}' &=& \m{J}\m{M}^{-1}(\ve{\Psi} + \m{J}^T\ve{\lambda}) \nonumber\\
\dot{\ve{c}} - \m{E}\dot{\ve{c}} &=&
    \m{J}\m{M}^{-1}\ve{\Psi} + \m{J}\m{M}^{-1}\m{J}^T\ve{\lambda} \nonumber\\
\m{J}\m{M}^{-1}\ve{\Psi} - \m{E}\m{J}\m{M}^{-1}\ve{\Psi} & = &
    \m{J}\m{M}^{-1}\ve{\Psi} + \m{J}\m{M}^{-1}\m{J}^T\ve{\lambda} \nonumber\\
-\m{J}\m{M}^{-1}\m{J}^T\ve{\lambda} &=& \m{E}\m{J}\m{M}^{-1}\ve{\Psi} \label{collisionLagrange}
\end{eqnarray}

All variables in equation~\ref{collisionLagrange} are known except for \ve{\lambda}, so this is
just a system of linear equations which we can solve for \ve{\lambda}. The resulting vector
$\ve{\Psi}_c = \m{J}^T\ve{\lambda}$ of impulses can be directly added to the rigid bodies' momenta.

We are not quite finished yet. Having modified the bodies' momenta, the state of other contact
points in the system may have changed. While the previously colliding contacts will have
turned into resting or separating contacts, other (previously unconsidered) contacts may now
be colliding! Thus we must repeat the whole process described in this section, ignoring the
previously colliding points, and considering the new ones instead. If there are no new colliding
contacts, we have finished.

The bad news is that this algorithm is not guaranteed to terminate~-- indeed
figure~\ref{contacts3Figure} shows an example in which it will run indefinitely. An easy way of
solving this problem is by not allowing $\varepsilon$ to be too close to 1; then if a loop
occurs, the system will eventually run out of energy and return to a resting contact.

\begin{figure}
\centerline{\includegraphics{figures/contacts3}}
\caption{Fully elastic spheres are packed tightly in a rigid box, with no space between them or at
    either end. When one is tapped horizontally with a hammer, the impulse travels up and down the
    chain forever, always being reflected at the walls of the box.\label{contacts3Figure}}
\end{figure}

\subsection{Generalized collisions\label{generalizedCollisions}}

In section~\ref{angleLimitation} I mentioned that the simulation still needed a way of limiting
the range of valid angles for a joint of an articulated body. I could not find any literature
explaining how one might realize such a constraint, but I was excited to notice one day that
I already had all the tools in hand, and merely needed to combine them.

An angle limitation is simply another type of inequality constraint. Usually two constraints are
required for each axis about which rotation is possible:
\begin{eqnarray}
c_1 & = & \mbox{\textit{current angle}} - \mbox{\textit{minimum angle}} \nonumber\\
c_2 & = & \mbox{\textit{maximum angle}} - \mbox{\textit{current angle}} \label{genCollIneq}
\end{eqnarray}

The two inequalities $c_1 \ge 0$ and $c_2 \ge 0$ then require the current angle to always stay
within the range bracketed by the minimum and the maximum. Once $c_1$ and $c_2$ have been
formulated in an appropriate way, these inequalities can be given directly to the algorithms
for resting and colliding contact, alongside any other constraints generated by meshes in contact
or by joints. These algorithms will ensure that all constraints are satisfied simultaneously
(irrespective of their origin), and the result actually behaves just as expected!

The continuation of the good news is that I have already given a suitable formula to determine
the current angle of rotation about a particular axis in equation~\ref{rotationConstraintEqn}
(section~\ref{rotationConstraints}). This formula can simply be reused for inequalities.

There is just one problem: it is fiendishly hard to visualize what a particular restriction on
a 3D rotation actually means. The best I could come up with is to imagine a 3D phase space in
which each coordinate is the angle of rotation about one of the segment's local (Cartesian) axes.
The set of valid rotations for one joint is then a subspace of some shape; despite the linear
look of inequalities~\ref{genCollIneq}, this space is generally not polyhedral; in fact it is
often not even compact. Maple cannot visualize such a solution space of inequalities, so I wrote
myself a little program for this task (figure~\ref{jointLimit}) and used it to set up the joint
limits for Alfred's skeleton.

\begin{figure}
\centerline{\includegraphics[width=120mm,height=70.54mm]{figures/jointlimit}}
\caption{Screenshot of a tool to visualize the solution space of simultaneous inequalities in
    three variables (here, the rotation about three different axes). If a point in the solution
    space is selected, the three angles of rotation corresponding to this point are applied to the
    cube on the right-hand side; this allows the inequalities to be adjusted to fit the desired
    set of rotations.\label{jointLimit}}
\end{figure}


\index{numbering}

The UFC specification dictates a certain numbering of the vertices,
edges etc. of the cells of a finite element mesh. First, an \emph{ad
hoc} numbering is picked for the vertices of each cell. Then, the
remaining entities are ordered based on a simple rule, as described in
detail below.

\section{Basic concepts}
\index{mesh entity}
\index{topological dimension}

The topological entities of a cell (or mesh) are referred to as
\emph{mesh entities}. A mesh entity can be identified by a pair
$(d, i)$, where $d$ is the topological dimension of the mesh entity and $i$
is a unique index of the mesh entity. Mesh entities are numbered
within each topological dimension from $0$ to $n_d-1$, where $n_d$ is
the number of mesh entities of topological dimension $d$.

For convenience, mesh entities of topological dimension $0$ are
referred to as \emph{vertices}, entities of dimension $1$
as \emph{edges}, entities of dimension $2$ as \emph{faces}, entities of
\emph{codimension} $1$ as \emph{facets} and entities of codimension
$0$ as \emph{cells}. These concepts are summarized in
Table~\ref{tab:entities}.

Thus, the vertices of a tetrahedron are identified as
$v_0 = (0, 0)$, $v_1 = (0, 1)$ and $v_2 = (0, 2)$,
the edges are
$e_0 = (1, 0)$, $e_1 = (1, 1)$, $e_2 = (1, 2)$,
$e_3 = (1, 3)$, $e_4 = (1, 4)$ and $e_5 = (1, 5)$,
the faces (facets) are
$f_0 = (2, 0)$, $f_1 = (2, 1)$, $f_2 = (2, 2)$ and $f_3 = (2, 3)$,
and the cell itself is
$c_0 = (3, 0)$.

\begin{table}
\linespread{1.2}\selectfont
  \begin{center}
    \begin{tabular}{|l|c|c|}
      \hline
      Entity & Dimension & Codimension \\
      \hline
      Vertex & $0$       & -- \\
      Edge   & $1$       & -- \\
      Face   & $2$       & -- \\
      & & \\
      Facet  & --      &  $1$ \\
      Cell   & --      &  $0$ \\
      \hline
    \end{tabular}
    \caption{Named mesh entities.}
    \label{tab:entities}
  \end{center}
\end{table}

\section{Numbering of vertices}
\index{vertex numbering}

For simplicial cells (intervals, triangles and tetrahedra) of a finite
element mesh, the vertices are numbered locally based on the
corresponding global vertex numbers. In particular, a tuple of
increasing local vertex numbers corresponds to a tuple of increasing
global vertex numbers.  This is illustrated in
Figure~\ref{fig:numbering_example_triangles} for a mesh consisting of
two triangles.

\begin{figure}[htbp]
  \begin{center}
    \psfrag{v0}{$v_0$}
    \psfrag{v1}{$v_1$}
    \psfrag{v2}{$v_2$}
    \psfrag{0}{$0$}
    \psfrag{1}{$1$}
    \psfrag{2}{$2$}
    \psfrag{3}{$3$}
    \includegraphics[width=8cm]{eps/numbering_example_triangles.eps}
    \caption{The vertices of a simplicial mesh are numbered locally
      based on the corresponding global vertex numbers.}
    \label{fig:numbering_example_triangles}
  \end{center}
\end{figure}

For non-simplicial cells (quadrilaterals and hexahedra), the numbering
is arbitrary, as long as each cell is isomorphic to the corresponding
reference cell by matching each vertex with the corresponding vertex
in the reference cell. This is illustrated in
Figure~\ref{fig:numbering_example_quadrilaterals} for a mesh
consisting of two quadrilaterals.

\begin{figure}[htbp]
  \begin{center}
    \psfrag{v0}{$v_0$}
    \psfrag{v1}{$v_1$}
    \psfrag{v2}{$v_2$}
    \psfrag{v3}{$v_3$}
    \psfrag{0}{$0$}
    \psfrag{1}{$1$}
    \psfrag{2}{$2$}
    \psfrag{3}{$3$}
    \psfrag{4}{$4$}
    \psfrag{5}{$5$}
    \includegraphics[width=8cm]{eps/numbering_example_quadrilaterals.eps}
    \caption{The local numbering of vertices of a non-simplicial mesh
      is arbitrary, as long as each cell is isomorphic to the
      reference cell by matching each vertex to the corresponding
      vertex of the reference cell.}
    \label{fig:numbering_example_quadrilaterals}
  \end{center}
\end{figure}

\section{Numbering of other mesh entities}

When the vertices have been numbered, the remaining mesh entities are
numbered within each topological dimension based on a
\emph{lexicographical ordering} of the corresponding ordered tuples of
\emph{non-incident vertices}.

As an illustration, consider the numbering of edges (the mesh entities
of topological dimension one) on the reference triangle in
Figure~\ref{fig:orderingexample,triangle}. To number the edges of the
reference triangle, we identify for each edge the corresponding
non-incident vertices. For each edge, there is only one such vertex
(the vertex opposite to the edge). We thus identify the three edges in
the reference triangle with the tuples $(v_0)$, $(v_1)$ and $(v_2)$. The
first of these is edge $e_0$ between vertices $v_1$ and $v_2$ opposite
to vertex $v_0$, the second is edge $e_1$ between vertices $v_0$ and
$v_2$ opposite to vertex $v_1$, and the third is edge $e_2$ between
vertices $v_0$ and $v_1$ opposite to vertex $v_2$.

Similarly, we identify the six edges of the reference tetrahedron with
the corresponding non-incident tuples $(v_0, v_1)$, $(v_0, v_2)$,
$(v_0, v_3)$, $(v_1, v_2)$, $(v_1, v_3)$ and $(v_2, v_3)$. The first of these is
edge $e_0$ between vertices $v_2$ and $v_3$ opposite to vertices $v_0$
and $v_1$ as shown in Figure~\ref{fig:orderingexample,tetrahedron}.

\begin{figure}[htbp]
  \begin{center}
    \psfrag{v0}{$v_0$}
    \psfrag{v1}{$v_1$}
    \psfrag{v2}{$v_2$}
    \psfrag{e0}{$e_0$}
    \includegraphics[width=5cm]{eps/ordering_example_triangle.eps}
    \caption{Mesh entities are ordered based on a lexicographical ordering
      of the corresponding ordered tuples of non-incident vertices.
      The first edge $e_0$ is non-incident to vertex $v_0$.}
    \label{fig:orderingexample,triangle}
  \end{center}
\end{figure}

\begin{figure}[htbp]
  \begin{center}
    \psfrag{v0}{$v_0$}
    \psfrag{v1}{$v_1$}
    \psfrag{v2}{$v_2$}
    \psfrag{v3}{$v_3$}
    \psfrag{e0}{$e_0$}
    \includegraphics[width=5cm]{eps/ordering_example_tetrahedron.eps}
    \caption{Mesh entities are ordered based on a lexicographical ordering
      of the corresponding ordered tuples of non-incident vertices.
      The first edge $e_0$ is non-incident to vertices $v_0$ and $v_1$.}
    \label{fig:orderingexample,tetrahedron}
  \end{center}
\end{figure}

\subsection{Relative ordering}

The relative ordering of mesh entities with respect to other incident
mesh entities follows by sorting the entities by their (global)
indices. Thus, the pair of vertices incident to the first edge $e_0$
of a triangular cell is $(v_1, v_2)$, not $(v_2, v_1)$. Similarly, the
first face $f_0$ of a tetrahedral cell is incident to vertices $(v_1,
v_2, v_3)$.

For simplicial cells, the relative ordering in combination with the
convention of numbering the vertices locally based on global vertex
indices means that two incident cells will always agree on the
orientation of incident subsimplices. Thus, two incident triangles
will agree on the orientation of the common edge and two incident
tetrahedra will agree on the orientation of the common edge(s) and the
orientation of the common face (if any). This is illustrated in
Figure~\ref{fig:orientation_example_triangles} for two incident
triangles sharing a common edge.

\begin{figure}[htbp]
  \begin{center}
    \psfrag{v0}{$v_0$}
    \psfrag{v1}{$v_1$}
    \psfrag{v2}{$v_2$}
    \psfrag{v3}{$v_3$}
    \includegraphics[width=9cm]{eps/orientation_example_triangles.eps}
    \caption{Two incident triangles will always agree on the
      orientation of the common edge.}
    \label{fig:orientation_example_triangles}
  \end{center}
\end{figure}

\subsection{Limitations}

The UFC specification is only concerned with the ordering of mesh
entities with respect to entities of larger topological dimension. In
other words, the UFC specification is only concerned with the ordering
of incidence relations of the class $d - d'$ where $d > d'$. For
example, the UFC specification is not concerned with the ordering of
incidence relations of the class $0 - 1$, that is, the ordering of
edges incident to vertices.

\newpage

\section{Numbering schemes for reference cells}

The numbering scheme is demonstrated below for cells
isomorphic to each of the five reference cells.

\subsection{Numbering of mesh entities on intervals}

\begin{minipage}{\textwidth}
\linespread{1.2}\selectfont
  \begin{center}
    \begin{tabular}{|c|c|c|}
      \hline
      Entity & Incident vertices & Non-incident vertices \\
      \hline
      \hline
      $v_0 = (0, 0)$ & $(v_0)$ & $(v_1)$ \\
      \hline
      $v_1 = (0, 1)$ & $(v_1)$ & $(v_0)$ \\
      \hline
      $c_0 = (1, 0)$ & $(v_0, v_1)$ & $\emptyset$ \\
      \hline
    \end{tabular}
  \end{center}
\end{minipage}

\subsection{Numbering of mesh entities on triangular cells}
%
\begin{minipage}{\textwidth}
\linespread{1.2}\selectfont
  \begin{center}
    \begin{tabular}{|c|c|c|}
      \hline
      Entity & Incident vertices & Non-incident vertices \\
      \hline
      \hline
      $v_0 = (0, 0)$ & $(v_0)$ & $(v_1, v_2)$ \\
      \hline
      $v_1 = (0, 1)$ & $(v_1)$ & $(v_0, v_2)$ \\
      \hline
      $v_2 = (0, 2)$ & $(v_2)$ & $(v_0, v_1)$ \\
      \hline
      $e_0 = (1, 0)$ & $(v_1, v_2)$ & $(v_0)$ \\
      \hline
      $e_1 = (1, 1)$ & $(v_0, v_2)$ & $(v_1)$ \\
      \hline
      $e_2 = (1, 2)$ & $(v_0, v_1)$ & $(v_2)$ \\
      \hline
      $c_0 = (2, 0)$ & $(v_0, v_1, v_2)$ & $\emptyset$ \\
      \hline
    \end{tabular}
  \end{center}
\end{minipage}

\subsection{Numbering of mesh entities on quadrilateral cells}
%
\begin{minipage}{\textwidth}
\linespread{1.1}\selectfont
  \begin{center}
    \begin{tabular}{|c|c|c|}
      \hline
      Entity & Incident vertices & Non-incident vertices \\
      \hline
      \hline
      $v_0 = (0, 0)$ & $(v_0)$ & $(v_1, v_2, v_3)$ \\
      \hline
      $v_1 = (0, 1)$ & $(v_1)$ & $(v_0, v_2, v_3)$ \\
      \hline
      $v_2 = (0, 2)$ & $(v_2)$ & $(v_0, v_1, v_3)$ \\
      \hline
      $v_3 = (0, 3)$ & $(v_3)$ & $(v_0, v_1, v_2)$ \\
      \hline
      $e_0 = (1, 0)$ & $(v_2, v_3)$ & $(v_0, v_1)$ \\
      \hline
      $e_1 = (1, 1)$ & $(v_1, v_2)$ & $(v_0, v_3)$ \\
      \hline
      $e_2 = (1, 2)$ & $(v_0, v_3)$ & $(v_1, v_2)$ \\
      \hline
      $e_3 = (1, 3)$ & $(v_0, v_1)$ & $(v_2, v_3)$ \\
      \hline
      $c_0 = (2, 0)$ & $(v_0, v_1, v_2, v_3)$ & $\emptyset$ \\
      \hline
    \end{tabular}
  \end{center}
\end{minipage}

\subsection{Numbering of mesh entities on tetrahedral cells}
%
\begin{minipage}{\textwidth}
\linespread{1.1}\selectfont
  \begin{center}
    \begin{tabular}{|c|c|c|}
      \hline
      Entity & Incident vertices & Non-incident vertices \\
      \hline
      \hline
      $v_0 = (0, 0)$ & $(v_0)$ & $(v_1, v_2, v_3)$ \\
      \hline
      $v_1 = (0, 1)$ & $(v_1)$ & $(v_0, v_2, v_3)$ \\
      \hline
      $v_2 = (0, 2)$ & $(v_2)$ & $(v_0, v_1, v_3)$ \\
      \hline
      $v_3 = (0, 3)$ & $(v_3)$ & $(v_0, v_1, v_2)$ \\
      \hline
      $e_0 = (1, 0)$ & $(v_2, v_3)$ & $(v_0, v_1)$ \\
      \hline
      $e_1 = (1, 1)$ & $(v_1, v_3)$ & $(v_0, v_2)$ \\
      \hline
      $e_2 = (1, 2)$ & $(v_1, v_2)$ & $(v_0, v_3)$ \\
      \hline
      $e_3 = (1, 3)$ & $(v_0, v_3)$ & $(v_1, v_2)$ \\
      \hline
      $e_4 = (1, 4)$ & $(v_0, v_2)$ & $(v_1, v_3)$ \\
      \hline
      $e_5 = (1, 5)$ & $(v_0, v_1)$ & $(v_2, v_3)$ \\
      \hline
      $f_0 = (2, 0)$ & $(v_1, v_2, v_3)$ & $(v_0)$ \\
      \hline
      $f_1 = (2, 1)$ & $(v_0, v_2, v_3)$ & $(v_1)$ \\
      \hline
      $f_2 = (2, 2)$ & $(v_0, v_1, v_3)$ & $(v_2)$ \\
      \hline
      $f_3 = (2, 3)$ & $(v_0, v_1, v_2)$ & $(v_3)$ \\
      \hline
      $c_0 = (3, 0)$ & $(v_0, v_1, v_2, v_3)$ & $\emptyset$ \\
      \hline
    \end{tabular}
  \end{center}
\end{minipage}

\vfill

\newpage

\subsection{Numbering of mesh entities on hexahedral cells}

\begin{minipage}{\textwidth}
\small
\linespread{1.2}\selectfont
  \begin{center}
    \begin{tabular}{|c|c|c|}
      \hline
      Entity & Incident vertices & Non-incident vertices \\
      \hline
      \hline
      $v_0 = (0, 0)$ & $(v_0)$ & $(v_1, v_2, v_3, v_4, v_5, v_6, v_7)$ \\
      \hline
      $v_1 = (0, 1)$ & $(v_1)$ & $(v_0, v_2, v_3, v_4, v_5, v_6, v_7)$ \\
      \hline
      $v_2 = (0, 2)$ & $(v_2)$ & $(v_0, v_1, v_3, v_4, v_5, v_6, v_7)$ \\
      \hline
      $v_3 = (0, 3)$ & $(v_3)$ & $(v_0, v_1, v_2, v_4, v_5, v_6, v_7)$ \\
      \hline
      $v_4 = (0, 4)$ & $(v_4)$ & $(v_0, v_1, v_2, v_3, v_5, v_6, v_7)$ \\
      \hline
      $v_5 = (0, 5)$ & $(v_5)$ & $(v_0, v_1, v_2, v_3, v_4, v_6, v_7)$ \\
      \hline
      $v_6 = (0, 6)$ & $(v_6)$ & $(v_0, v_1, v_2, v_3, v_4, v_5, v_7)$ \\
      \hline
      $v_7 = (0, 7)$ & $(v_7)$ & $(v_0, v_1, v_2, v_3, v_4, v_5, v_6)$ \\
      \hline
      $e_0 = (1, 0)$ & $(v_6, v_7)$ & $(v_0, v_1, v_2, v_3, v_4, v_5)$ \\
      \hline
      $e_1 = (1, 1)$ & $(v_5, v_6)$ & $(v_0, v_1, v_2, v_3, v_4, v_7)$ \\
      \hline
      $e_2 = (1, 2)$ & $(v_4, v_7)$ & $(v_0, v_1, v_2, v_3, v_5, v_6)$ \\
      \hline
      $e_3 = (1, 3)$ & $(v_4, v_5)$ & $(v_0, v_1, v_2, v_3, v_6, v_7)$ \\
      \hline
      $e_4 = (1, 4)$ & $(v_3, v_7)$ & $(v_0, v_1, v_2, v_4, v_5, v_6)$ \\
      \hline
      $e_5 = (1, 5)$ & $(v_2, v_6)$ & $(v_0, v_1, v_3, v_4, v_5, v_7)$ \\
      \hline
      $e_6 = (1, 6)$ & $(v_2, v_3)$ & $(v_0, v_1, v_4, v_5, v_6, v_7)$ \\
      \hline
      $e_7 = (1, 7)$ & $(v_1, v_5)$ & $(v_0, v_2, v_3, v_4, v_6, v_7)$ \\
      \hline
      $e_8 = (1, 8)$ & $(v_1, v_2)$ & $(v_0, v_3, v_4, v_5, v_6, v_7)$ \\
      \hline
      $e_9 = (1, 9)$ & $(v_0, v_4)$ & $(v_1, v_2, v_3, v_5, v_6, v_7)$ \\
      \hline
      $e_{10} = (1, 10)$ & $(v_0, v_3)$ & $(v_1, v_2, v_4, v_5, v_6, v_7)$ \\
      \hline
      $e_{11} = (1, 11)$ & $(v_0, v_1)$ & $(v_2, v_3, v_4, v_5, v_6, v_7)$ \\
      \hline
      $f_0 = (2, 0)$ & $(v_4, v_5, v_6, v_7)$ & $(v_0, v_1, v_2, v_3)$ \\
      \hline
      $f_1 = (2, 1)$ & $(v_2, v_3, v_6, v_7)$ & $(v_0, v_1, v_4, v_5)$ \\
      \hline
      $f_2 = (2, 2)$ & $(v_1, v_2, v_5, v_6)$ & $(v_0, v_3, v_4, v_7)$ \\
      \hline
      $f_3 = (2, 3)$ & $(v_0, v_3, v_4, v_7)$ & $(v_1, v_2, v_5, v_6)$ \\
      \hline
      $f_4 = (2, 4)$ & $(v_0, v_1, v_4, v_5)$ & $(v_2, v_3, v_6, v_7)$ \\
      \hline
      $f_5 = (2, 5)$ & $(v_0, v_1, v_2, v_3)$ & $(v_4, v_5, v_6, v_7)$ \\
      \hline
      $c_0 = (3, 0)$ & $(v_0, v_1, v_2, v_3, v_4, v_5, v_6, v_7)$ & $\emptyset$ \\
      \hline
    \end{tabular}
  \end{center}
\end{minipage}


\chapter{Definitions}
\label{chap:definitions}

In this chapter, we formally define multi-tape Turing machines.  We take the definition of multi-tape Turing machines and their tapes from Asperti and
Ricciotti \cite{asperti2015}.  We introduce notions for specifying correctness and time complexity of machines, where the former is also based
on~\cite{asperti2015}.

\section{Preliminary Definitions}
\label{sec:prelim}

\subsection{Notational Conventions}
\label{sec:notational-conventions}

The symbols $\Unit$, $\Bool$, $\Nat$, $X \times Y$, $X + Y$, $\Option(X)$, and $\List(X)$ stand for the well-known standard types.  $\Type$ stands for
the type of types and $\Prop$ for the type of propositions.  The unit element $\unit$ is the only element of $\Unit$.  $\sum_{a:A} B(a)$ denotes sigma
types, i.e.\ dependent pairs, with the projections $\pi_1$ and $\pi_2$.  We write $(a,b)$ for elements of sigma types.  For (named) tuples
$A = (a:X,~b:Y,~c:Z)$, we use subscripts, i.e.\ $a_A$, for the projections.  We use the symbols $\None$ and $\Some x$ as elements of the type
$\Option(X)$.  $\Fin_n := \setOf{0, \dots, n-1}$ is the type with $n$ elements.  We use indices $i:\Fin_n$ for vector-access $x[i]$ with $x:X^n$,
where $X^n$ denotes the type of vectors over $X$ of size $n$.  We usually leave subscripts out if they are clear from the context.

\subsection{Relations}
\label{sec:relations}
\setCoqFilename{ProgrammingTuringMachines.TM.Relations}

We define the semantics of concrete Turing machines in terms of relations.  We write $R \subseteq A \times B$ as a notation for
$R : A \to B \to \Prop$.  We call relations of the form $R \subseteq A \times (B \times A)$ \emph{labelled relations} (labelled over $B$) and write
$R \subseteq A \times B \times A$.  We identify unit-labelled relations $R \subseteq A \times \Unit \times A$ with binary relations
$R \subseteq A \times A$.  We use $\lambda$-notation to define relations.

We use the following standard relational operators:

\begin{definition}[Relational operators]
  Let $R, S \subseteq A \times B$ and $T \subseteq B \times C$.
  \begin{align*}
    \coqlink[rintersection]{R \cap S}  &:= \lambda x~y.~R~x~y \land S~x~y \\
    \coqlink[runion]       {R \cup S}  &:= \lambda x~y.~R~x~y \lor S~x~y \\
    \coqlink[rcomp]        {R \circ T} &:= \lambda x~z.~\exists y.~R~x~y \land T~y~z
  \end{align*}
\end{definition}

Note that if we compose a binary relation $R \subseteq A \times A$ with a labelled relation $S \subseteq A \times B \times A$, we get a labelled
relation $R \circ S \subseteq A \times B \times A$.

We use $\coqlink[rUnion]{\bigcup_{c:C} R(c)}$ as a notation for $\lambda a~b.~\exists c.~R(c)~a~b$.  We also define the reflexive transitive closure
of binary relations, also known as relational Kleene star:

\begin{definition}[Kleene star][star]
  \label{def:Kleene}
  Let $R \subseteq A \times A$.  The relation $R^*$ is defined inductively:
  \[
    \inferrule{ }{R^*~x~x}
    \qquad
    \inferrule{R~x~y \and R^*~y~z}{R^*~x~z}
  \]
\end{definition}

The relational power operator composes a relation $k$ times.
\begin{definition}[Relational power][pow]
  \label{def:pow}
  Let $R \subseteq A \times A$.  The relation $R^k$ is defined inductively:
  \[
    \inferrule{ }{R^0~x~x}
    \qquad
    \inferrule{R~x~y \and R^k~y~z}{R^{(S~k)}~x~z}
  \]
\end{definition}

We have an operator that restricts the label $B$ of a labelled relation and yields a binary relation:
\begin{definition}[Relational restriction][restrict]
  \label{def:rel-restrict}
  Let $R \subseteq A \times B \times A$ and $y:B$.
  \[
    R \at y := \lambda x~z.~R~x~(y,z)
  \]
\end{definition}

Similarly, we can define an operator that takes a binary relation and yields a labelled relation where we fix the label.
\begin{definition}[Relational fix][rfix]
  \label{def:rel-fix}
  Let $R \subseteq A \times A$ and $y : B$.
  \[
    R \att y := \lambda x~(y', z).~R~x~z \land y'=y
  \]
\end{definition}

\begin{definition}[Relational inclusion and equivalence]
  Let $R,S \subseteq A \times A$.
  \begin{align*}
    \coqlink[subrel]{R \subseteq S} &:= \forall x~y.~R~x~y \rightarrow S~x~y \\
    \coqlink[eqrel] {R \equiv S}    &:= R \subseteq S ~\land~ S \subseteq R
  \end{align*}
\end{definition}

\subsection{Retractions}
\label{sec:retracts}

Retractions are a natural way to formalise injections $f$ together with their partial inversion function $f^{-1}$.

\begin{definition}[Retraction]
  \label{def:retract}
  Let $A, B : \Type$.  A pair of functions $f : A \to B$, $f^{-1} : B \to \Option(A)$ is called a retraction from $A$ to $B$, if
  $\forall x~y.~f^{-1}(y) = \Some x \iff y = f(x).$
\end{definition}

The direction from right to left of Definition~\ref{def:retract} means that $f^{-1}$ inverses $f$.  It is equivalent to the following commutative
diagram:
\[
  \begin{tikzcd}
    A \arrow[r, "f"] \arrow[d, "\Some \cdot", swap] & B \arrow[ld, "f^{-1}"] \\
    \Option(A) &
  \end{tikzcd}
\]
The direction from left to right of Definition~\ref{def:retract} means that $f^{-1}$ only maps values back that are in the image of $f$.  This
property is called \textit{tightness}.

We write $f : A \hookrightarrow B$ when we assume that the pair $(f, f^{-1})$ is a retraction.  Note that this notation introduces two names for
functions ($f : A \to B$ and $f^{-1} : B \to \Option(A)$), but mostly we use the name $f$ for the \textit{pair} of both functions.

\begin{lemma}[Basic properties of retractions]
  \label{lem:retracts-basic}
  Let $f : A \hookrightarrow B$.
  \begin{enumerate}
  \item \label{lem:retract_g_adjoint}
    $\forall (x:A).~f^{-1}(f(x)) = \Some{x}$
  \item \label{lem:retract_g_None}
    $\forall (y:B).~f^{-1}(y) = \None \rightarrow \forall (x:A).~f(x) \neq y$
  \item \label{lem:retract_f_injective}
    $f : A \to B$ is injective, i.e.\ $\forall x~y.~f(x)=f(y) \rightarrow x=y$
  \item \label{lem:retract_g_Some}
    $\forall (x~y:A).~f^{-1}(f(x)) = \Some y \rightarrow x=y$
  \end{enumerate}
\end{lemma}

\begin{proof}
  Claim~\ref{lem:retract_g_adjoint} and~\ref{lem:retract_g_None} are direct consequences of Definition~\ref{def:retract}.
  Claim~\ref{lem:retract_g_Some} follows by Claim~\ref{lem:retract_f_injective}.

  Proof of Claim~\ref{lem:retract_f_injective}.  Let $x, y: A$ and $f(x)=f(y)$.  We have to show $x=y$.  It is enough to show $\Some x = \Some y$.  By
  Claim~\ref{lem:retract_g_adjoint}, we know $\Some x = f^{-1}(f(x))$ and $\Some y = f^{-1}(f(y))$.  Therefore, it is enough to show that
  $f^{-1}(f(x)) = f^{-1}(f(y))$.  This is trivial because we assumed $f(x)=f(y)$.
\end{proof}

\begin{definition}[Basic retractions]
  \label{def:retracts-basic}
  Let $A$ and $B$ be types.  We define the retractions\\
  $RetrId : A \hookrightarrow A$, $RetrLft : A \hookrightarrow A+B$, and $RetrRgt : B \hookrightarrow A+B$:
  \begin{alignat*}{2}
    RetrId(x)  &:= x      &\qquad\qquad RetrId ^{-1} (x) &:= \Some x \\
    RetrLft(x) &:= \inl x &             RetrLft^{-1} (z) &:=
    \begin{cases}
      \Some x & z = \inl x \\
      \None   & z = \inr y
    \end{cases} \\
    RetrRgt(y) &:= \inr y & RetrRgt^{-1} (z) &:=
    \begin{cases}
      \None   & z = \inl x \\
      \Some y & z = \inr y
    \end{cases}
  \end{alignat*}
\end{definition}

\begin{definition}[Composition of retractions]
  \label{def:retract-compose}
  Let $f : A \hookrightarrow B$ and $g : B \hookrightarrow C$.  Then $g \circ f : A \hookrightarrow C$ is defined as the following retraction:
  \begin{alignat*}{2}
    & (g \circ f)      & (a) &:= g(f(a)) \\
    & (g \circ f)^{-1} & (c) &:=
    \begin{cases}
      f^{-1}(b) & g^{-1}(c) = \Some{b} \\
      \None & g^{-1}(c) = \None
    \end{cases}
  \end{alignat*}
\end{definition}

\section{Machines and Tapes}
\label{sec:machine-tapes}

\setCoqFilename{ProgrammingTuringMachines.TM.TM}

% There are many variations of Turing machines.  We have chosen multi-Tape

We use the definition of multi-tape Turing machines, their tapes, and semantics from Asperti and Ricciotti~\cite{asperti2015}.\footnote{Asperti and
  Ricciotti~\cite{asperti2015} restrict machines to have $n>0$ tapes.  We do not have this restriction.  We actually define a $0$-tape machine
  $\MS{Null}$, see Section~\ref{sec:Null}.}

\begin{definition}[Multi-tape Turing machine][mTM]
  \label{def:mTM}
  An $n$-tape Turing machine over a finite alphabet $\Sigma$ is a tuple $M = (Q, \delta, start, halt)$ where
  \begin{itemize}
  \item $Q$ is a finite type
  \item $\delta \from Q \times \left(\Option(\Sigma)\right)^n \to Q \times \left(\Option(\Sigma) \times \MS{Move}\right)^n$
  \item $start:Q$
  \item $halt \from Q \to \Bool$
  \end{itemize}
  There are three possible movements: $\coqlink[move]{\MS{Move}} ::= \MS{L} ~|~ \MS{R} ~|~ \MS{N}.$
\end{definition}

We write $\MS{TM}_\Sigma^n$ for the type of $n$-tape Turing machines over the alphabet $\Sigma$.

While we parametrise Definition~\ref{def:mTM} over the alphabet $\Sigma$ and the number of tapes $n$, we abstract the finite type $Q$ of states inside
the type of Turing machines.  The transition function $\delta$ yields for every state and vector of $n$ read symbols the new state and for every tape
an optional symbols to write and a direction to move.  The read symbols are also optional, since it can be the case that there is no symbol under the
head of a tape.  $start$ is the start state of the machine and $halt$ represents the subset of halting states.  Tuples of the type
$\Option(\Sigma) \times \Move$ are called \textit{actions}.  They are referred to with the symbol $\MS{Act}_\Sigma$ or $\MS{Act}$ if $\Sigma$ is
clear.  Our machines behave deterministically, because $\delta$ is a function.

When we want to verify complex machines, we do not want to reason about \textit{concrete machine states}, because the number of states of a machine
could be huge.  Reasoning about \textit{all} states of a machine is thus unfeasible.  We still need to reason about states, but we do not need to
distinct most of the states.  We introduce the notion of \textbf{labelled machines}, where we assign a \textit{label} to every state.  A label type
could be, for example, the type $\Bool$.  Then we only distinct between two kinds of states.  If $L$ is a finite type, then $M = (M', lab)$ is a
labelled machine, where $M'$ is an unlabelled machine and $lab : Q_{M'} \to L$ is called the \textit{labelling function} of $M$.  The value of $lab$
is irrelevant for non-terminating states.  The function $lab$ partitions the terminating states.  This means that all terminating states with the same
label can be seen semantically equivalent.  We write $\MS{TM}_\Sigma^n(L)$ for the type of labelled machines over $L$.\footnote{Formally, the type is
  defined as a sigma type: $\MS{TM}_\Sigma^n(L) := \sum_{M':\MS{TM}_\Sigma^n}\bigl(Q_{M'} \to L\bigr)$.  We use the projection $\pi_1$ implicitly and
  write $lab_M$ for $\pi_2(M)$.}  We identify unit-labelled machines $\TM_\Sigma^n(\Unit)$ with unlabelled machines $\TM_\Sigma^n$.  We use the symbol
$M$ for both labelled and unlabelled machines $\TM_\Sigma^n$.  It should however be always clear from the context, whether $M$ is a labelled or
unlabelled machine.

On a \emph{tape}, arbitrarily much memory can be allocated.  However, every tape has only finitely many symbols, i.e.\ there is a left-most and a
right-most symbol.  A tape essentially is a triple $(ls,m,rs)$, where the symbol $m$ is the symbol under which the (read/write) head of tape is.  It
is essential that the symbol lists ($ls$ and $rs$) are ordered such that the head of the list is the symbol next to the symbol $m$.  When we think of
tapes as a finite sequence of symbols from left to right, this means that $ls$ is stored in reversed order.

There are three cases where there is no current symbol: the tape can be completely empty, or the head can be to the left (or right) outermost of a
non-empty tape.  Formally, tapes are defined inductively:

\begin{definition}[Tape][tape]
  \label{def:tape}
  Let $\Sigma : \Type$.  Then $\Tape_\Sigma$ is defined as the inductive type:
  \begin{alignat*}{2}
    & \Tape_\Sigma &~::=~& \MS{niltape} \\
    &&& |~ \MS{leftof}  ~ (r:\Sigma) ~ (rs:\List(\Sigma)) \\
    &&& |~ \MS{midtape} ~ (ls:\List(\Sigma)) ~ (m:\Sigma) ~ (rs:\List(\Sigma)) \\
    &&& |~ \MS{rightof} ~ (l:\Sigma) ~ (ls:\List(\Sigma))
  \end{alignat*}
\end{definition}

Recall that we leave the subscript $\Sigma$ out, if it is clear from the context.

% We introduce a informal notation of tapes, where the symbols are represented from left to right, hence we have to reverse the lists $ls$.  The
% position of the head is marked by the arrow:
% \begin{align*}
%   \niltape &:= \MS{niltape}\\
%   \leftof{r}{rs} &:= \MS{leftof}~r~rs\\
%   \midtape{ls}{m}{rs} &:= \MS{midtape}~(\rev~rs)~m~rs\\
%   \rightof{ls}{l} &:= \MS{rightof}~(\rev~ls)~l
% \end{align*}

Now we can define the \emph{configuration} of a multi-tape Turing machine.  It is captured by the current state and the vector of the $n$ tapes:
\begin{definition}[Configuration][mconfig]
  \label{def:config}
  A configuration of $M: \TM_\Sigma^n$ is a tuple $c = (q, t)$, where $q: Q_M$ and $t: \Tape_\Sigma^n$.  We write
  $\Conf_M := Q_M \times \Tape_\Sigma^n$ for the type of configurations of $M$.
\end{definition}

% \begin{alignat*}{2}
%   \MS{mv}_R&~(\leftof{r}{R}               &&:= \midtape{\nil}{r}{R} \\
%   \MS{mv}_R&~(\midtape{L}{m}{\nil})       &&:= \rightof{L}{m} \\
%   \MS{mv}_R&~(\midtape{L}{m}{r \cons R)}) &&:= \midtape{L \app [m]}{r}{R} \\
%   \MS{mv}_N&~(t)                          &&:= t
% \end{alignat*}
% The function $\MS{mv}_L$ is defined analogously.
The function $\MS{mv} \from \Move \to \Tape_\Sigma \to \Tape_\Sigma$ moves a tape in a direction.
\begin{definition}[Tape movement][tape_move]
  \footnotesize
  \begin{alignat*}{4}
    & \MS{mv}~\MS{L}~(\MS{leftof}~r~rs)                &&:= \MS{leftof}~r~rs
    && \MS{mv}~\MS{R}~(\MS{leftof}~r~rs)               &&:= \MS{midtape}~\nil~r~rs \\
    & \MS{mv}~\MS{L}~(\MS{midtape}~\nil~m~rs)          &&:= \MS{leftof}~m~rs
    && \MS{mv}~\MS{R}~(\MS{midtape}~ls~m~\nil)         &&:= \MS{rightof}~m~ls \\
    & \MS{mv}~\MS{L}~(\MS{midtape}~(l \cons ls)~m~rs)  &&:= \MS{midtape}~ls~l~(m \cons rs)
    && \MS{mv}~\MS{R}~(\MS{midtape}~ls~m~(r \cons rs)) &&:= \MS{midtape}~(m \cons ls)~r~rs \\
    & \MS{mv}~\MS{L}~(\MS{rightof}~l~ls)               &&:= \MS{midtape}~ls~l~\nil
    && \MS{mv}~\MS{R}~(\MS{rightof}~l~ls)              &&:= \MS{rightof}~l~ls \\
    & \MS{mv}~\_~(\MS{niltape})                        &&:= \MS{niltape}
    && \MS{mv}~\MS{N}~t                                &&:= t
  \end{alignat*}
\end{definition}
Note that moving further right (or left) when that tape already is to the right (or left) of the symbols, does not change the tape.

The functions $\MS{left},~\MS{right} \from \Tape \to \List(\Sigma)$ return the symbols to the left (or right) side of the head:
\begin{definition}[$\MS{left}$ and $\MS{right}$][left]
  \begin{alignat*}{4}
    \MS{left} &~(\MS{niltape})                 &&:= \nil
    \quad\quad\quad\quad
    & \MS{right}&~(\MS{niltape})               &&:= \nil \\
    \MS{left} &~(\MS{leftof}~{r}~{rs})         &&:= \nil
    & \MS{right}&~(\MS{leftof}~{r}~{rs})       &&:= r \cons rs \\
    \MS{left} &~(\MS{midtape}~{ls}~{m}~{rs})   &&:= ls
    & \MS{right}&~(\MS{midtape}~{ls}~{m}~{rs}) &&:= rs \\
    \MS{left} &~(\MS{rightof}~{l}~{ls})        &&:= l \cons ls
    & \MS{right}&~(\MS{rightof}~{l}~{ls})      &&:= \nil
  \end{alignat*}
\end{definition}

% Note that as a consequence of the informal notation, we have
% $$\MS{left}(\midtape{ls}{m}{rs}) = \MS{left}(\MS{midtape}~(\rev{ls})~{m}~{rs}) = \rev{ls}.$$

Now we can define the function $\MS{wr} \from \Tape_\Sigma \to \Option(\Sigma) \to \Tape_\Sigma$, that writes an optional symbol to a tape.  When we
write $\Some a$, we get a $\MS{midtape}$, where the left and right symbols remain unchanged and $a$ is now in the middle.  For $\None$, the tape
remains unchanged.  Note that there is no way to decrease the number of symbols on a tape or to write ``blank'' symbols.

\begin{definition}[$\MS{wr}$][tape_write]
  \begin{alignat*}{3}
    \MS{wr}~t &~ \None   &&:= t \\
    \MS{wr}~t &~ \Some a &&:= \MS{midtape}~(\MS{left}~t)~{a}~(\MS{right}~t)
  \end{alignat*}
\end{definition}

To define the function $\MS{step} \from \Conf \to \Conf$, we need to know the symbols on the tapes.  Therefore, we define a function
$\MS{current} \from \Tape_\Sigma \to \Option(\Sigma)$.  It returns $\None$ if the head is not under a symbol, and $\Some m$ if the head is under the
symbol~$m$.

\begin{definition}[$\MS{current}$][current]
  The function $\MS{current} \from \Tape_\Sigma \to \Option(\Sigma)$ is defined by
  \begin{alignat*}{2}
    \MS{current}&~(\MS{midtape}~{ls}~{m}~{rs})&&:= \Some m \\
    \MS{current}&~\_                          &&:= \None
  \end{alignat*}
\end{definition}

We can state a correctness lemma of the function $\MS{wr}$:

\begin{fact}[Correctness of $\MS{wr}$]
  \label{lem:write}
  For all tapes $t$ and symbols $a:\Sigma$:
  % TODO: Align it, for example like in https://tex.stackexchange.com/questions/12771/mix-align-and-enumerate
  \begin{enumerate}
  \item $\MS{right}   (\MS{wr}~t~\Some a) = \MS{right}(t)$
  \item $\MS{left}    (\MS{wr}~t~\Some a) = \MS{left} (t)$
  \item $\MS{current} (\MS{wr}~t~\Some a) = \Some a$
  \end{enumerate}
\end{fact}
% \begin{proof}
%   All claims follow by case analysis over $t$.
% \end{proof}

We can now define the function $\MS{step} \from \Conf \to \Conf$.  First, the machine reads all the current symbols from the tapes.  We apply this
vector and the machine state to the transition function $\delta$.  Then, each tape writes the symbol and moves its head into the direction that
$\delta$ yielded for it.  The machine ends up in a new state $q'$.

\begin{definition}[$\MS{step}$][step]
  \label{def:step}
  \begin{alignat*}{2}
    \MS{doAct} &~t~(s, d) &~:=~& \MS{mv}~d~(\MS{wr}~t~s) \\
    \MS{step}  &~(q, t)   &~:=~& \Let{(q', act) := \delta(q, \map{\MS{current}}{t})}{ \\
               &          &~  ~& (q', \maptwo{\MS{doAct}}{t}{act})}
  \end{alignat*}
\end{definition}

To define the execution of a machine, we first define an abstract recursive function
$\Loop \from (A \to A) \to (A \to \Bool) \to A \to \Nat \to \Option(A)$ (for every $A:\Type$):

\setCoqFilename{ProgrammingTuringMachines.TM.Prelim}
\begin{definition}[$\Loop$][loop]
  \begin{align*}
    \Loop~f~h~a~k :=
    \begin{cases}
      \Some{a}               & h(a) \\
      \None                  & \lnot h(a) \land k = 0 \\
      \Loop~f~h~(f~a)~(k-1)  & \lnot h(a) \land k > 0
    \end{cases}
  \end{align*}
\end{definition}

We can show basic facts about $\Loop$.
\begin{lemma}[Basic facts about $\Loop$]
  \label{lem:loop}
  Let $k,l : \Nat$ and $a,b,c:A$.
  \begin{enumerate}
  \item \label{lem:loop_monotone}
    \coqlink[loop_monotone]{If $k \le l$ and $\Loop~f~h~a~k = \Some{b}$, then $\Loop~f~h~a~l = \Some{b}$.}
  \item \label{lem:loop_injective}
    \coqlink[loop_injective]{If $\Loop~f~h~a~k = \Some{b}$ and $\Loop~f~h~a~l = \Some{c}$, then $b = c$.}
  \item \label{lem:loop_fulfills}
    \coqlink[loop_fulfills]{If $\Loop~f~h~a~k = \Some{b}$, then $h(b) = \true$.}
  \item \label{lem:loop_0}
    \coqlink[loop_0]{If $h~a = \true$, then $\Loop~f~h~a~k = \Some{a}$.}
  \item \label{lem:loop_eq_0}
    \coqlink[loop_eq_0]{If $h~a = \true$ and $\Loop~f~h~a~k = \Some{b}$, then $a=b$.}
  \end{enumerate}
\end{lemma}
\begin{proof}
  Claims~\ref{lem:loop_monotone},~\ref{lem:loop_injective}, and~\ref{lem:loop_fulfills} follow by induction on $k : \Nat$.  Claim~\ref{lem:loop_0}
  follows by Definition.  Claim~\ref{lem:loop_eq_0} is a direct consequence of claim~\ref{lem:loop_0}.
\end{proof}
\setCoqFilename{ProgrammingTuringMachines.TM.TM}

We instantiate the abstract $\Loop$ function and get a function $\MS{loopM} \from \Conf \to \Nat \to \Option(\Conf)$ that executes $k$ steps of the
machine:
\begin{definition}[Machine execution][loopM]
  \begin{alignat*}{3}
    \MS{initConf}   &~t         &&:= (t, start) \\
    \MS{haltConf}   &~(t, q)    &&:= halt(q) \\
    \MS{loopM}      &~c~k       &&:= \Loop~\MS{step}~\MS{haltConf}~c~k
  \end{alignat*}
\end{definition}

We write $M(c) \terminates^k c'$ for $\MS{loopM}~c~k = \Some {c'}$ and $M(t) \terminates^k c$ for $M(\MS{initConf}~t) \terminates^k c$.

All definitions, except labelled machines, are from Asperti and Ricciotti \cite{asperti2015}, with similar names.  However, the $\Loop$ function was
slightly changed for convenience, so that it needs zero steps when the (abstract) starting state is a halting state.

\section{Specification of Semantics}
\label{sec:spec_semantics}

We have defined semantics for multi-tape Turing machines.  Now we want to define predicates to specify the semantics of a concrete machine
$M: \TM_\Sigma^n(L)$.  There are two parts of the semantics: \emph{correctness} and \emph{time complexity}.

The correctness part is captured by realisation of a (labelled) relation $R$:

\begin{definition}[Realisation][Realise]
  \label{def:realisation}
  Let $M:\TM_\Sigma^n(L)$ and $R \subseteq \Tape_\Sigma^n \times L \times \Tape_\Sigma^n$.
  \[
    M \Realise R :=
    \forall t~k~q~t'.~M(t) \terminates^k (q, t') \rightarrow
    R~t~(lab_M~q, t')
  \]
  Where $lab_M \from Q_M \to L$ is the labelling function of $M$.
\end{definition}

If $M \Realise R$, we say that $M$ realises the relation $R$.  Informally, this means that the output of the machine is correct w.r.t.\ the relation,
if the machine terminates.

To show realisation, e.g.\ $M \Realise R$, it suffices to find a (smaller) relation $R'$ and show that it implies the (target) relation $R$:
\begin{lemma}[Monotonicity of $M \Realise R$][Realise_monotone]
  \label{lem:Realise_monotone}
  If $M \Realise R'$ and $R' \subseteq R$, then $M \Realise R$.
\end{lemma}

The running time part of the semantics implies termination of the machine on certain inputs.  It relates the input $t:\Tape_\Sigma^n$ to the number of
steps that the machine needs for the computation.

\begin{definition}[Termination in a running time relation][TerminatesIn]
  \label{def:TerminatesIn}
  Let $T \subseteq \Tape_\Sigma^n \times \Nat$.
  \[
    M \TerminatesIn T :=
    \forall t~k.~T~t~k \rightarrow
    \exists c.~M (t) \terminates^k c.
  \]
\end{definition}

Termination is anti-monotone.  This means that it suffices for showing $M \downarrow T$ to find a (bigger) relation $T'$ and show $T \subseteq T'$.
\begin{lemma}[Anti-monotonicity of $M \TerminatesIn T$][TerminatesIn_monotone]
  \label{lem:TerminatesIn_monotone}
  If $M \TerminatesIn T'$ and $T \subseteq T'$, then $M \TerminatesIn T$.
\end{lemma}

For machines that always terminate in a constant number of steps, it is useful to combine both predicates:
\begin{definition}[Realisation in constant time][RealiseIn]
  \label{def:RealiseIn}
  ~
  \[
    M \RealiseIn{k} R := \forall t'.~ \exists q~t'.~ M(t) \terminates^k(q, t') \land R~t~(lab_M~q,~t')
  \]
\end{definition}

\begin{lemma}[][Realise_total]
  \label{lem:Realise_total}
  $M \RealiseIn{k} R ~\iff~ M \Realise R ~\land~ M \TerminatesIn (\lambda \_~k'.~k \le k')$
\end{lemma}

\begin{lemma}[Monotonicity of $M \RealiseIn{k} R$][RealiseIn_monotone]
  \label{lem:RealiseIn_monotone}
  If $M \RealiseIn{k'} R'$, $k' \leq k$, and $R' \subseteq R$, then \\
  $M \RealiseIn{k} R$.
\end{lemma}

Asperti and Ricciotti~\cite{asperti2015} make a distinction between weak and strong realisation, where the strong version implies termination for
every input, however, in an uncertain number of steps.  We use a variant of their weak realisation.  They have no notion of time complexity.  Because
we do not want to reason about concrete machine states, we introduced the notion of labelled machines.  The idea to label the states of machines with
elements of a finite type is due to Y.~Forster and F.~Kunze.  They also invented the realisation of labelled relations and the notion for time
complexity.

% \section{Canonical Relations}
% \label{sec:canonical}

% \enlargethispage{0.5cm}

% Similar as in Asperti and Ricciotti~\cite{asperti2015}, we can define correctness relations that every machine realises.  Trivially, every machine
% realises the universal relation $Univ := \lambda t~(l,t').~\True$.  Every non-terminating (diverging) machine can only realise the empty relation
% $Empty := \lambda t~(l,t').~\False$.  The \textit{canonical relation} is the smallest relation that every machine realises:

% \begin{fact}[Canonical correctness][Canonical_Realise]
%   Let $M : \TM_\Sigma^n(L)$, then
%   \[
%     M \Realise \left( \lambda t~(l,t').~\exists q~k.~M(t) \terminates^k (q,t') \land lab_M(q) = l \right)
%   \]
% \end{fact}

% Dually, every machine terminates in the empty relation.  The canonical termination relation is the biggest relation in that every machine terminates:
% \begin{fact}[Canonical termination][Canonical_TerminatesIn]
%   Let $M : \TM_\Sigma^n$, then $M \TerminatesIn \left( \lambda t~k.~\exists c.~M(t) \terminates^k c \right)$.
% \end{fact}

%%% Local Variables:
%%% TeX-master: "thesis"
%%% End:


\documentclass[11pt]{article}
\usepackage{listings}
\usepackage{tikz}
\usepackage{enumerate}
\usepackage{url}
%\usepackage{algorithm2e}
\usetikzlibrary{arrows,automata,shapes}
\tikzstyle{block} = [rectangle, draw, fill=blue!20,
    text width=5em, text centered, rounded corners, minimum height=2em]
\tikzstyle{bt} = [rectangle, draw, fill=blue!20,
    text width=1em, text centered, rounded corners, minimum height=2em]

\lstset{ %
language=Java,
basicstyle=\ttfamily,commentstyle=\scriptsize\itshape,showstringspaces=false,breaklines=true,numbers=left}

\newtheorem{defn}{Definition}
\newtheorem{crit}{Criterion}

\newcommand{\handout}[5]{
  \noindent
  \begin{center}
  \framebox{
    \vbox{
      \hbox to 5.78in { {\bf Software Testing, Quality Assurance and Maintenance } \hfill #2 }
      \vspace{4mm}
      \hbox to 5.78in { {\Large \hfill #5  \hfill} }
      \vspace{2mm}
      \hbox to 5.78in { {\em #3 \hfill #4} }
    }
  }
  \end{center}
  \vspace*{4mm}
}

\newcommand{\lecture}[4]{\handout{#1}{#2}{#3}{#4}{Lecture #1}}
\topmargin 0pt
\advance \topmargin by -\headheight
\advance \topmargin by -\headsep
\textheight 8.9in
\oddsidemargin 0pt
\evensidemargin \oddsidemargin
\marginparwidth 0.5in
\textwidth 6.5in

\parindent 0in
\parskip 1.5ex
%\renewcommand{\baselinestretch}{1.25}

\begin{document}

\lecture{3 --- January 9, 2017}{Winter 2017}{Patrick Lam}{version 2}

\paragraph{Exercise: findLast.} Here's a faulty program.
\begin{lstlisting}
    static public int findLast(int[] x, int y) {
        /* bug: loop test should be i >= 0 */
        for (int i = x.length - 1; i > 0; i--) {
            if (x[i] == y) {
                return i;
            }
        }
        return -1;
    }
\end{lstlisting}
You might expect to be asked a question like this:
\begin{enumerate}[(a)]
    \item Identify the fault, and fix it.
    \item If possible, identify a test case that does not execute the fault.
    \item If possible, identify a test case that executes the fault, but does not result in an error state.
    \item If possible, identify a test case that results in an error, but not a failure. (Hint: program counter)
    \item For the given test case, identify the first error state. Be sure to describe the complete state.
\end{enumerate}

I asked you to work on that question in class. Here are some answers:

\begin{enumerate}[(a)]
\item The loop condition must include index 0: {\tt i >= 0}.
\item This is a bit of a trick question. To avoid the loop condition, you must not enter the loop body. The only way to do that is to pass in {\tt x = null}. You should also state, for instance, {\tt y = 3}. The expected output is a {\tt NullPointerException}, which is also the actual output.
\item Inputs where {\tt y} appears in the second or later position execute the fault but do not result in the error state; nor do inputs where {\tt x} is an empty array. (There may be other inputs as well.) So, a concrete input: {\tt x = \{2, 3, 5\}; y = 3}. Expected output = actual output = 1.
\item One error input that does not lead to a failure is where {\tt y}
  does not occur in {\tt x}. That results in an incorrect PC after the final executed iteration of the loop.
 \item After running line 6 with {\tt i = 1}, the decrement occurs, followed by the evaluation of {\tt i > 0}, causing the PC to exit the loop (statement 8) instead of returning to statement 4. The faulty state is {\tt x = \{2, 3, 5\}; y = 3; i = 0; PC = 8}, while correct state would be {\tt PC = 4}.
\end{enumerate}

Someone asked about distinguishing errors from failures. These
questions were about failures at the method level, and so a wrong
return value would be a failure when we're asking about methods. In
the context of a bigger program, that return value might not be
visible to the user, and so it might not constitute a failure, just an
error.

\section*{Line Intersections}
We then talked about different ways of validating a test suite.
Consider the following Python code, found by Michael Thiessen
on stackoverflow (\url{http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other}).

\begin{lstlisting}[language=python]
class LineSegment:
    def __init__(self, x1, x2):
        self.x1 = x1; self.x2 = x2;

def intersect(a, b):
    return (a.x1 < b.x2) & (a.x2 > b.x1);
\end{lstlisting}

We could construct test suites that:
\begin{itemize}
\item execute every statement in {\tt intersect} (statement coverage). Well, that's not very useful; any old test case
  will do that. There are no branches, so what we'll call edge coverage
  doesn't help either.
\item feed random inputs to {\tt intersect}; unfortunately,
  interesting behaviours are not random, so it won't help much
  in general.
\item check all outputs of {\tt intersect} (i.e. a test case with
  lines that intersect and one with lines that don't intersect): we're
  getting somewhere---that will certify that the method works in some
  cases, but it's easy to think of situations that we missed.
\item check different values of clauses {\tt a.x1 < b.x2} and {\tt a.x2 > b.x1} (logic coverage)---better than the above coverage criteria, but still misses interesting behaviours;
  \item analyze possible inputs and cover all interesting combinations of inputs (input space coverage)---can create an exhaustive test suite, if your analysis is sound.
\end{itemize}

Let's try to prove correctness of {\tt intersect}. There's an old
saying about testing---supposedly, it can only find the presence of
bugs, not their absence. This is not completely true, especially if
you have reliable software that automatically constructs an exhaustive
test suite.  But that is beyond the state of the practice in 2015, for
the most part.

\paragraph{Inputs to {\tt intersect}.} There are essentially
four inputs to this function. Rename them $aAbB$, for {\tt a.x1},
{\tt a.x2}, etc.
\begin{itemize}
\item Let's first assume that all points are distinct. We should
  make a note to ourselves to check violations of this, as well:
  we may have $a = A, a = b, a = B$, and symmetrically for $B$:
  $b = a, b = A, b = B$.
  \item For the purpose of the analysis, let's assume that $a < b$;
    when constructing test cases, we can swap $a$ and $b$ around.
    That's why there are duplicate assert statements below.
  \item Without loss of generality, we can assume that
$a < A$ and $b < B$. (We ought to update the constructor if we
    want to make that assumption.)
\end{itemize}
With these assumptions, we have to test the three possible permutations
$aAbB$, $abAB$, and $abBa$. It is simple to construct test cases
for these permutations, using Python's unittest framework:
\begin{lstlisting}
      def test_aAbB(self):
        a = LineSegment(0,2)
        b = LineSegment(3,7)
        self.assertFalse(intersect(a,b))
        self.assertFalse(intersect(b,a))

    def test_abAB(self):
        a = LineSegment(0,4)
        b = LineSegment(3,7)
        self.assertTrue(intersect(a,b))
        self.assertTrue(intersect(b,a))

    def test_abBA(self):
        a = LineSegment(0,4)
        b = LineSegment(1,2)
        self.assertTrue(intersect(a,b))
        self.assertTrue(intersect(b,a))
\end{lstlisting}
Those test cases pass. However, if you construct test cases for
equality (as I've committed to the repository), you see that the given {\tt
  intersect} function fails on line segments that intersect only at a
point. Replacing \verb+<+ with \verb+<=+ and \verb+>+ with \verb+>=+
fixes the code.

\end{document}


\documentclass[11pt]{article}
%\usepackage{fancyheadings}
\usepackage{wrapfig}
\usepackage{epsfig}
\usepackage{hyperref}
\setlength{\headheight}{0pt}
%\setlength{\footheight}{0pt}
\setlength{\topmargin}{-.5in}
\setlength{\oddsidemargin}{-0.25in}
\setlength{\evensidemargin}{-0.25in}
\setlength{\textwidth}{7truein}
\setlength{\textheight}{9truein}
\setlength{\parskip}{6pt}

\begin{document}

\section*{Social Distancing}

%\subsection*{Description}

\begin{wrapfigure}{r}{3in}
\vspace{-10pt}
\epsfig{figure=park,width=3in}
\vspace{-30pt}
\end{wrapfigure}

During these difficult Covid times, it is important to balance getting fresh air and maintaining social distancing standards to keep everyone safe. You work for the local government and help run a local park. You want your park visitors to be as happy and safe as possible. You have picnic tables at the park and many visitors arriving. Your job is to assign picnic tables to your visitors to try and spread the visitors out as much as possible (each visitor must hang out at one of the tables).

Your park is very peculiar. It is a very long, narrow park. The picnic tables are spread out in a straight line through this long narrow park, and the distance between picnic tables varies (they are not uniformly positioned across the park). In addition, the tables are WAY too heavy to move. Given a list of the positions of the picnic tables in the park, and the number of visitors that wish to use the park, return the maximum social distancing value that can be achieved by assigning visitors to tables. By maximum, we mean the arrangement of visitors that maximizes the distance between the closest two patrons in the park.

\subsection*{Input}
The input file will begin with one line containing $ 2 \leq n \leq 10^6$ and $p \leq n \leq 10^6$, the number of picnic tables in your park and the number of visitors respectively. The following $n$ lines will each contain a single integer $l_i \leq 10^8$ describing the integer position of table $i$. These positions will be sorted in increasing order. All positions will be unique.

\subsection*{Output}
Output the largest possible value of the minimum distance between visitors after being seated in the optimal arrangement at the picnic tables.

\vspace{0.25in}\hspace{-0.3in}\begin{tabular}{ll}

%\subsection*{Sample Input}
\parbox{3in}{{\large\bf Sample Input}

\vspace{0.15in}

{\tt
5 3\linebreak
1\linebreak
2\linebreak
4\linebreak
8\linebreak
9
}
}

&

\parbox{3in}{{\large\bf Sample Output}

\vspace{0.15in}

{\tt
3
}
}

\\
\end{tabular}

\end{document}


\documentclass{article}
\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{amsmath}
\allowdisplaybreaks

\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}

\begin{document}
\title{Notes}
\date{February 14, 2014}
\maketitle
\section*{homework}
\subsection*{hw 16}
lesson 10 exercise 3. Find the cosine transform $U(\omega ,t)$ of the solution $u(x,t)$.
\subsection*{hw 17}
find the inverse transform $u(x,t)$. Hint use mathematica
\subsection*{hw 18}
plot the solutioon $u(x,t)$ for $t=0.01,0.1,1.0$ (take $\alpha ^2=1$)
\section*{homework help}
lesson 9. non-homogeneous pde. $u_t=\alpha u_{xx}+f(x,t)$ find fundamental solutions of the form $T(t)X(x)$ where $X(x)$ and $\lambda $ are eigendata for the homogeneous BC.

He wrote $-\lambda ^2$ originally instead of $\lambda $.

The separation constant occurs
\begin{align*}
  \frac{T'(t)}{\alpha ^2T(t)}=\frac{X''(x)}{X(x)}=\mu \text{ the separation constant}
\end{align*}
To find the separation constant study the hom. BC. It's okay to restrict to $\leq 0$

\section*{question?}
\begin{align*}
  I&=\int_0^\infty{\frac{\sin(\omega x}{\omega }e^{-\alpha ^2\omega ^2t}\,\mathrm{d}\omega }=\int_0^\infty{\frac{\sin(\frac{x}{\alpha \sqrt{t}}s)}{s}e^{-s^2}\,\mathrm{d}s}\\
  I(\beta)&=\int_0^\infty{\frac{\sin(\beta s}{s}e^{-s^2}\,\mathrm{d}s}\qquad\beta =\frac{x}{\alpha \sqrt{t}}
\end{align*}
Do we know any special values for $I(\beta)$?
\begin{align*}
  \beta &=0&I&=0\\
  &&&=\int_0^\infty{\frac{\sin(\beta s)}{s}\,\mathrm{d}s}=\int_0^\infty{\frac{\sin(s)}{s}\,\mathrm{d}s}=\frac{\pi }{2}\\
  &&&s\gets\frac{s}{\beta  }
\end{align*}
\end{document}


\chapter*{Symbols and Acronyms}
\addcontentsline{toc}{chapter}{Symbols and Acronyms}

In general, we denote a scalar by an italic lower case letter,
a vector by a roman lower case bold letter,
and a matrix by a roman upper case bold letter respectively, e.g.,
$a \in \bbR$, $\mathbf{v} \in \bbR^n$ and $\mathbf{M} \in \bbR^{p \times q}$, with any exceptions to be mentioned in the context case by case.

Specifically, the components of any vector ${\bf v} \in \bbR^2$ or ${\bf v}\in \bbR^3$ are written as $[v_x\,v_y]^T$ or $[v_x\,v_y\,v_z]^T$.

An identity matrix is written as $\bI$. Specifically, an $n\times n$ identity matrix is written as $\bI_n$.
A zero matrix or vector is written as ${\bf 0}$. Specifically, an $m\times n$ zero matrix is written as ${\bf 0}_{m\times n}$.

$\check{(\cdot)}$ denotes the prior of any quantity, while $\hat{(\cdot)}$ denotes the posterior.

Specialized symbols and major acronyms are defined as follows:

\newpage

\noindent
$\bR \in$ SO(3) \hfill a $3\times 3$ rotation matrix \\
$\bT \in$ SE(3) \hfill a $4 \times 4$ homogeneous transformation matrix\\
$\bp \in \bbR^3$ \hfill a 3D translational vector \\
$\bq=[q_x \, q_y \, q_z \, q_w ]^T$ \hfill a Hamilton quaternion, with $q_w$ being the real part \\
$[\bq]_\Im=[q_x\,q_y\,q_z]^T$ \hfill the imaginary vector part of $\bq$\\
$\otimes$ \hfill multiplication of quatertions \\
$\bm\theta \in \bbR^3$ \hfill a rotation vector \\
$\bl \in \bbR^3$ \hfill the 3D position of a landmark point \\
$\bv \in \bbR^3$ \hfill  translational velocity \\
$\ba \in \bbR^3$ \hfill  translational acceleration \\
$\bm\omega \in \bbR^3$ \hfill  angular velocity \\
${\bf u} \in \bbR^2$ \hfill 2D position in image coordinates \\
$p(\cdot)$ \hfill the probability density function (PDF) \\
$E(\cdot)$ \hfill  the expectation \\
$\bm\Sigma$ \hfill a covariance matrix \\
$\bm\Omega$ \hfill an information matrix \\
$\caN(\bar\bx,\bSigma)$ \hfill a normal distribution with mean $\bar\bx$ and covariance $\bSigma$ \\
${\bm\eta}$ \hfill a noise vector \\
${\bf e}(\cdot)$ \hfill an error/residual function \\
$\bJ$ \hfill a Jacobian matrix \\
$\bH$ \hfill a Hessian matrix \\
$\bJ_\ell$ \hfill left Jacobian of SO(3) \\
$\caJ_\ell$ \hfill left Jacobian of SE(3) \\
$\caT$ \hfill adjoint of SE(3)\\
$\tr(\cdot)$ \hfill trace of a matrix \\
$\det(\cdot)$ \hfill determinant of a matrix \\

\newpage
\noindent
BA        \hfill bundle adjustment                       \\
BoW       \hfill Bags of Words                           \\
DoF       \hfill degree of freedom                       \\
EKF       \hfill extended Kalman filter                  \\
GPS       \hfill Global Positioning System               \\
GN        \hfill Gauss-Newton                            \\
IMU       \hfill inertial measurement unit               \\
KF        \hfill Kalman filter                           \\
LM        \hfill Levenberg-Marquardt                     \\
MAP       \hfill maximum a posteriori                    \\
PF        \hfill partical filtering                      \\
RANSAC    \hfill random sample consensus                 \\
SfM       \hfill structure from motion                   \\
SLAM      \hfill simultaneously localization and mapping \\
MSCKF     \hfill multi-state constraint Kalman filter    \\
ToF       \hfill Time-of-Flight                          \\
UKF       \hfill unscended Kalman filter                 \\
V-SLAM    \hfill visual SLAM                             \\
VINS      \hfill visual inertial navigation system       \\
VIF       \hfill visual inertial fusion                  \\
VIO       \hfill visual inertial odometry                \\
VO        \hfill visual odometry                         \\