%\documentclass[12pt]{article}
\documentclass[aip,jcp,preprint,superscriptaddress,floatfix]{revtex4-1}
\usepackage{url,graphicx,tabularx,array,geometry,amsmath,listings}
\setlength{\parskip}{2ex} %--skip lines between paragraphs
\setlength{\parindent}{20pt} %--don't indent paragraphs

\usepackage[colorinlistoftodos,prependcaption,textsize=tiny]{todonotes} %--TODO notes

\setlength{\headheight}{-50pt}
\setlength{\textheight}{700pt}
\setlength{\textwidth}{500pt}
\setlength{\oddsidemargin}{-10pt}
\setlength{\footskip}{50pt}
\usepackage{graphicx}% Include figure files
\usepackage{bm}
\usepackage{url}
\usepackage[colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}
\graphicspath{{./Figures/}}

%-- Commands for header
\renewcommand{\title}[1]{\textbf{\large{#1}}\\}
\renewcommand{\line}{\begin{tabularx}{\textwidth}{X>{\raggedleft}X}\hline\\\end{tabularx}\\[-0.5cm]}
\newcommand{\leftright}[2]{\begin{tabularx}{\textwidth}{X>{\raggedleft}X}#1%
& #2\\\end{tabularx}\\[-1cm]}

%\linespread{2} %-- Uncomment for Double Space
\begin{document}

\title{\center{Monte Carlo Simulation of the Lennard Jones Fluid in the Canonical Ensemble}}
\rule{\textwidth}{1pt}
\leftright{The Molecular Sciences Software Institute}{Eliseo Marin-Rimoldi and John D.~Chodera} %-- left and right positions in the header

\bigskip

\section{Introduction}
\subsection{Monte Carlo Integration}

In statistical mechanics, we are interested in computing averages of
thermodynamic properties as a function of atom positions and momenta~\cite{Tuckerman.Book,Hill.Book,McQuarrie.Book}.
A thermodynamic average depending only on configurational properties can be computed using the following
expectation value integral
\begin{equation}
	\left<Q\right> = \int_V Q\left(\textbf{r}^N\right)
	\rho\left(\textbf{r}^N\right) d\textbf{r}^N
	\label{eq.statMechAverage}
\end{equation}
$\textbf{r}^N$ is a $3N$ dimensional vector containing the positions of the $N$ atoms,
where $Q(\textbf{r}^N)$ is the thermodynamic quantity of interest that depends only on the configuration $\textbf{r}^N$,
$\rho\left(\textbf{r}^N\right)$ is the probability
density whose functional form depends on the statistical mechanical ensemble
of interest, and $V$ defines the volume of configuration space over which $\rho$ has support.
Note that the integrals over momenta have been factored out, as
they can be evaluated
analytically. The integral (Eq.~\ref{eq.statMechAverage}) is very hard to compute
even for small atomic systems.
For instance, a monoatomic system of 10 atoms leads to a 30-dimensional
integral. Consequently, we need to resort to a numerical integration scheme if we want to
study atomic systems.

Monte Carlo methods are numerical techniques
frequently used to estimate complex multidimensional
integrals which otherwise
 could not be performed~\cite{Liu.Book,Newman.Book}.
 For instance, the integral of the function $f(\textbf{x})$,
 where $\textbf{x} \in \Re^{M}$, is approximated as
 \begin{equation}
	 I = \int_V f(\textbf{x}) \, d\textbf{x} = \int_V
	 \frac{f(\textbf{x})}{h(\textbf{x})} h(\textbf{x}) \, d\textbf{x}
	 = \left< \frac{f(\textbf{x})}{h(\textbf{x})} \right>_{h(\textbf{x})}
	 \label{eq.averageGeneral}
 \end{equation}
 The idea of Monte Carlo integration is to estimate the expectation value
 $\left<\frac{f(\textbf{x})}{h(\textbf{x})}\right>_{{h(\textbf{x})}}$ by
 generating random samples of \textbf{x} from the probability density $h(\textbf{x})$.

\subsection{Importance Sampling}

In Equation \ref{eq.averageGeneral}, we are free to chose the probability
distribution
$h(\textbf{x})$. The simplest case is to uniformly generate $\textbf{x}$
in the volume $V$. In this way, $h(\textbf{x})$ becomes constant as
\begin{equation}
	h(\textbf{x}) = \frac{1}{V}
	\label{eq.uniformDist}
\end{equation}
Using this sampling density $h(\textbf{x})$, the integral (Eq.~\ref{eq.averageGeneral}) becomes
\begin{equation}
	I = \int_V f(\textbf{x}) \, d\textbf{x} \approx \frac{V}{N} \sum_{i=1}^N
	f(\textbf{x}_i)
	\label{eq.averageUniform}
\end{equation}
where N is the total number of random samples and $f(\textbf{x}_i)$ is the
integrand evaluated using the $i^{th}$ sample. While using a
uniform sampling density often works sufficiently well for simple unidimensional cases, it generally fails to produce useful estimates
for complex problems.

The problem at hand involves the evaluation of $3N$-dimensional integral Eq.~\ref{eq.statMechAverage}, which is dominated by a small region of configuration space~\cite{Tuckerman.Book,Hill.Book,McQuarrie.Book}.
Using a uniform probability distribution $h(\textbf{r}^N)$ over the configuration space hypervolume $V^{3N}$ to generate
representative samples of this subset is not efficient,
as most states generated this way would have a low weight.

A solution to this problem is to sample positions $\textbf{r}^N$ from the desired equilibrium probability density $\rho\left(\textbf{r}^N\right)$:
\begin{eqnarray}
	\textbf{r}^N &\sim& \rho(\textbf{r}^N)
\end{eqnarray}
This is a way to generate
relevant configurations more frequently than configurations that have low
probability.
Mathematically, we set $h(\textbf{r}^N)=\rho\left(\textbf{r}^N\right)$.
This idea is known as \textit{importance sampling}.

Combining Eqs.~\ref{eq.statMechAverage} and \ref{eq.averageGeneral}
and the condition $h(\textbf{r}^N)=\rho\left(\textbf{r}^N\right)$,
we find that
\begin{equation}
	%\left<Q\right> = \frac{\int Q e^{-\beta U\left(\textbf{r}^N\right)}
	%d\textbf{r}^N}{\int e^{-\beta U\left(\textbf{r}^N\right)}
	%d\textbf{r}^N}
	\left<Q\right> \approx \frac{1}{N} \sum_{i=1}^N Q\left(\textbf{r}_i^N\right) .
	\label{eq.importanceSamplingAverage}
\end{equation}
Thus, we can get thermodynamic properties by simply computing an unweighted sample average, given
that we perform importance sampling from $h(\textbf{r}^N)=\rho\left(\textbf{r}^N\right)$.

\subsection{Detailed Balance Condition}

The question now becomes how to generate such atomic positions $\textbf{r}^N$
(or \textit{states}) distributed
according to $\rho\left(\textbf{r}^N\right)$. In 1953, Metropolis, Rosenbluth, Rosenbluth, and Teller introduced a
solution based on Markov chains~\cite{Metropolis.JCP.21.1087.1953}.
They proposed to use the detailed balance
condition in order to ensure proper configurational sampling from
the statistical mechanical distribution of interest. In order to generate
a new configuration $n$ from an old configuration $m$,
the detailed balance condition is

\begin{equation}
	\rho_m\left(\textbf{r}^N\right) \alpha \left(m \rightarrow n \right)
	P_{acc} \left(m \rightarrow n \right) =
	\rho_n\left(\textbf{r}^N\right) \alpha \left(n \rightarrow m \right)
	P_{acc} \left(n \rightarrow m \right)
	   \label{eq.detailedBalance}
\end{equation}

Where $\rho_m\left(\textbf{r}^N\right)$ is the probability of observing
state $m$,
$\alpha \left(m \rightarrow n \right)$ is the probability of
attempting to generate a new state $n$ starting from a state $m$  and
$P_{acc} \left(n \rightarrow m \right)$ is the probability of accepting
such transition. Basically, the condition of detailed balance tells us that the
``flux'' of transitions
from state $m$ to state $n$ equals the flux from state $n$ to state $m$ at
equilibrium.

There are many ways to satisfy Eq.~\ref{eq.detailedBalance} by construction of different acceptance probabilities.
While Metropolis et.~al proposed a choice that both satisfies Eq.~\ref{eq.detailedBalance} and maximizes the average acceptance probability $\left< P_{acc} \right>$~\cite{Metropolis.JCP.21.1087.1953}, Hastings generalized this to the case where proposal probabilities are not symmetric, such that $\alpha \left(m \rightarrow n \right) \ne \alpha \left(n \rightarrow m \right)$, producing the \emph{Metropolis-Hastings}~\cite{Hastings.Biometrika.57.97.1970} acceptance criteria:
\begin{equation}
	P_{acc}(m \rightarrow n) = \text{min} \left[1,\frac{\alpha \left(n
		\rightarrow m \right)}{\alpha \left(m \rightarrow n \right)}
		\frac{\rho_n\left(\textbf{r}^N\right)}{\rho_m\left(\textbf{r}^N\right)}
	\right]
	\label{eq.MetropolisHastings} .
\end{equation}
This algorithm is one of a general class of \emph{Markov chain Monte Carlo (MCMC)} algorithms that generate Markov chains to sample a desired target density, and a great deal of the MCMC literature is valuable for molecular simulations~\cite{Liu.Book}.

\section{Canonical Ensemble Monte Carlo of a Lennard Jones Fluid}

Assume we have $N$ monoatomic particles that interact using the Lennard-Jones (LJ) pairwise potential:
\begin{equation}
U(r) = 4 \epsilon \left[\left(\frac{\sigma}{r}\right)^{12} -\left(\frac{\sigma}{r}\right)^{6} \right]
\end{equation}
where $r$ is the interparticle distance, $\sigma$ is the distance where the interaction energy is zero, and $\epsilon$ is the well depth.
For simulating argon, for example, a common choice is $\sigma = 3.4$~\AA and $\epsilon/k_B = 120$~K.

Our goal is to generate a set of states of $N$ LJ particles distributed according to the canonical (NVT) ensemble
\begin{eqnarray}
	\rho_n \left(\textbf{r}^N ; \beta \right) &=& Z(\beta)^{-1} e^{-\beta U \left( \textbf{r}^N \right)} \label{eq:nvtDist} \\
	Z(\beta) &\equiv& \int_V e^{-\beta U \left(  \textbf{r}^N \right)} \, d\textbf{r}^N
\end{eqnarray}
where $U \left( \textbf{r}^N \right)$ is the potential energy of the system, $\beta = (k_B T)^{-1}$ is the inverse temperature, $k_B$ is the Boltzmann constant, and $T$ is the absolute temperature.

Note that  $U \left( \textbf{r}^N \right)$ is given by
\begin{equation}
	U \left( \textbf{r}^N \right) = \sum_{i < j} U \left( r_{ij} \right)
	\label{eq.LennardJonesTotalPotential}
\end{equation}
where $r_{ij} \equiv || \textbf{r}^N_j - \textbf{r}^N_i ||_2$ is the interparticle separation distance.

Substituting Eq.~\ref{eq:nvtDist} into Eq.~\ref{eq.MetropolisHastings} and assuming $\alpha \left( n \rightarrow m \right) =  \alpha \left( m \rightarrow n \right)$, we obtain
\begin{equation}
	P_{acc}(m \rightarrow n) = \text{min} \left[
		1,e^{-\beta \Delta U}
	\right]
	\label{eq.detailedBalanceNVT}
\end{equation}
where $\Delta U \equiv U(\textbf{r}^N_m) - U(\textbf{r}^N_n)$ is the difference in potential energy of the system
between the new state $n$ and the old state $m$. Note that the argument
of the energy $\textbf{r}^N$ has been dropped for clarity.

\subsection{Flow of Calculations in a Metropolis Monte Carlo simulation}
\label{sec.flow}

The following workflow can be used to implement the Metropolis algorithm to sample the canonical ensemble of configurations of LJ particles \cite{Shell.Notes, Maginn.Notes}:

\begin{enumerate}
\setlength{\itemsep}{0em} %--don't put a huge amount of space between items in a list
\item Generate an inital system state $m$.
\item Choose an atom with uniform probability from $\{1, \ldots, N\}$ from old state $m$.
\item Propose a new state $n$ by translating a LJ particle by a uniform random displacement $\Delta r \sim U(-\Delta x, +\Delta x)$ in each dimension.
	The displacement scale $\Delta x$ should not be too large as this would
	likely result in particle overlaps, but should not be too small
	as this would result in a slow sampling of configurational space.
	More on this below.
\item The difference in energy between the new and old states is computed.
	Note that you do not need to compute the \textit{total} system energy
	difference, as all particles but one remain at the same position.
	It is enough to get difference in energy of the selected molecule
	in the new and old states.
\item The new state is accepted or rejected using the Metropolis criterion.
	Practically, this can be implemented as follows.
	If a move from $m$ to $n$ is ``downhill'', $\beta \Delta U \leq 0$,
	the move is always accepted. For ``uphill'' moves, a random
	number $\zeta$ is generated uniformly on (0,1).
	If $\zeta < \exp[-\beta {\Delta U}]$, the move is
	accepted.  Otherwise, the move is rejected.
	If a non-symmetric proposal is used, this acceptance scheme will have to be modified to implement Eq.~\ref{eq.MetropolisHastings}.
\end{enumerate}

\subsection{Technical considerations}

\textbf{Initial configuration.}
While computed equilibrium expectations should be independent of the starting configuration, from a practical standpoint, we have to select an initial configuration that is not so atypical of equilibrium configurations that relaxation to equilibrium will require an enormous amount of simulation time.
For this particular example, a good way to start is to place atoms in a 3D lattice.
During the Metropolis Monte Carlo simulation at temperatures and box volumes (or pressures) typical of the liquid state, the lattice will ``melt'' and liquid configurations will be obtained.
Once a liquid configuration has been generated from a simulation, you can always save a ``snapshot'' from this simulation as a starting point for a new simulation of the liquid states, and relaxation to equilibrium will generally be much more rapid as long as the conditions are similar.

\textbf{Random number generation.}
Computers cannot generate truly random numbers.
Instead, they rely on \emph{pseudorandom number generators} (PRNGs) that aim to produce random numbers with the desired statistical properties and long recurrence times between repeats of the same random number sequence.
Using a low-quality random number generator can lead to simulation artifacts that can lead to incorrect physical behavior~\cite{Ferrenberg.PRL.69.3382.1992,Cerutti.JCTC.4.1669.2008}.
We recommend you avoid writing your own PRNGs, as this can lead to inadvertent implementation of an ill-conceived algorithm~\cite{RANDU}.
Instead, rely on high-quality, well-understood PRNGs and implementations that have are well-supported, such as the Mersenne Twister~\cite{Mersenne.Twister,Matsumoto.ACMTransModelComputSimul.8.3.1998} implementation provided by \href{https://docs.scipy.org/doc/numpy/reference/routines.random.html}{\tt numpy.random}.

\textbf{Equilibration.}
When the initial configuration is highly atypical compared to true samples from the equilibrium density---such as the initial 3D lattice conditions compared to a true disordered liquid state---it may require very long simulation times for the bias in equilibrium averages computed over the entire trajectory to become small compared to the statistical error~\cite{Chodera.JCTC.12.1799.2016}.
It is therefore common practice to discard some initial part of the simulation to \emph{equilibration} and to average over the subsequent \emph{production} region to minimize this bias at the cost of potentially increasing statistical error by including less data in the average.
While common practice traditionally had selected an arbitrary initial portion of the simulation to equilibrium, modern best practice recommends the use of an automated approach for selecting the optimal equilibration/production split point in a manner that maximizes the number of statistically uncorrelated samples in the production part of the trajectory~\cite{Chodera.JCTC.12.1799.2016}.
To do this, you can use the \href{http://pymbar.readthedocs.io/en/latest/timeseries.html#automatically-identifying-the-equilibrated-production-region}{\tt pymbar.timeseries.detectEquilibration} function from the \href{http://pymbar.org/}{\tt pymbar} module to analyze an array containing timeseries data for your observable (such as energies, box volumes, or densities)~\cite{Chodera.JCTC.12.1799.2016}.

\textbf{System size and periodic boundary conditions.}
A typical simulation of a Lennard-Jones fluid is carried out anywhere from 216 to 10,000 particles.
This amount of particles is far away of being representative of a bulk liquid.
To get around this problem, we employ a trick called periodic boundary conditions.
The primary simulation box is surrounded
by copy images of itself. For a cubic simulation, there would be 26
images around the central box. This trick has two implications
\begin{enumerate}
\setlength{\itemsep}{0em} %--don't put a huge amount of space between items in a list
	\item If the position of a particle (i.e.\ Cartesian coordinates) is
		outside the simulation box after a particle translation,
		an identical particle should enter the box through the
		opposite face of the box, as shown in Figure ~\ref{fig:pbc}
	\item When computing distances $r_{ij}$ used in the evaluation of the LJ potential (Eq.~\ref{eq.LennardJonesTotalPotential}), we use the \textit{minimum image distance}. See Figure ~\ref{fig:minimumImage}.
\end{enumerate}

\begin{figure}[t]
        \includegraphics[scale = 0.5]{pbc.eps}
        \caption{Molecule one is displaced outside the bounds of the central box and placed back
        in through the oposite side of the box. Image from Allen and Tildesley. ~\cite{Allen.Book}}
        \centering
        \label{fig:pbc}
\end{figure}

\begin{figure}[t]
        \includegraphics[scale = 0.5]{minimumImage.eps}
        \caption{Representation of the minimum image distance. Molecule 1 does not interact with
                molecule 4 located in the simulation box because the distance between particles is
                greater than the cutoff. However, molecule 1 does interact with
                the image of molecule 4 located in box E. Image from Allen and
                Tildesley ~\cite{Allen.Book}}
        \centering
        \label{fig:minimumImage}
\end{figure}

\textbf{Maximum displacement $\Delta x$.}
As noted above, the Metropolis Monte Carlo algorithm requires translating a selected LJ particle by a random perturbation.
This displacement should not be too large as this would result in particle overlaps and low acceptance rates; on the other hand, it should not be so small as to result in inefficient sampling of configuration space.
A common practice is to adjust the maximum particle displacement $\Delta x$ during an explicit equilibration phase in order to achieve $\sim$50\% acceptance translation rates over a recent window of $\sim N$ Monte Carlo trial moves.

\textbf{Energy truncation and tail corrections.}
If two particles are separatedby more than a certain distance, we typically truncate their interaction energy if $r > r_c$, where $r_c$ denotes the \emph{cutoff distance}.
Truncating interactions removes contribution to the potential energy that might be non negligible and can lead to significant artifacts, such as significantly perturbed densities when a barostat is used to sample the NPT ensemble due to neglected long-range dispersion interactions.
We can estimate the truncated interactions by incorporating an energy
correction, known as the tail or long range correction.
For the Lennard-Jones fluid, we assume that we have an homogeneous liquid at $r>r_c$ to obtain the correction for neglecting this contribution for all interacting pairs of particles~\cite{Shirts.JPCB.111.13052.2007}:
\begin{equation}
	U_\mathrm{correction} = \frac{8 \pi N^2}{3 V} \epsilon \sigma^3
	\left[\frac{1}{3} \left(\frac{\sigma}{r_c} \right)^9
	- \left(\frac{\sigma}{r_c} \right)^3 \right]
\end{equation}
For a Lennard-Jones fluid, it is common to set $r_c \sim 3 \sigma$, since the pair interaction at this separation is small, $U(3 \sigma) \approx 4 [(3)^{-12} - (3)^{-6} \approx - 0.0055 \epsilon$, or about 0.5\% of the well depth $\epsilon$.
You will want to verify that your computed properties are relatively insensitive to the choice of cutoff $r_c$ so that a too-short cutoff does not induce artifacts in computed physical properties.

\textbf{Units.}
Dealing with unit-bearing quantities---such as energies, distances, masses, and physical constants---in your code can be tricky.
Errors can easily creep in when one part of the code assumes one set of implicit units while another part of the code assumes a different set of implicit units, and error like this have led to billion-dollar accidents (such as the loss of the Mars Polar Lander due to one part of the code using metric units while the other used English units~\cite{MarsPolarLander}).
To avoid costly mistakes that complicate debugging, we recommend one of two approaches:
(1) use a unit library such as \href{http://pint.readthedocs.io/}{\tt pint} or \href{http://docs.openmm.org/7.1.0/userguide/library.html#units-and-dimensional-analysis}{\tt simtk.unit} that automatically handles unit coversions,
or (2) select a single compatible unit system (e.g.~mks or {\AA}ngstroms-amu-picoseconds) and explicitly document the units for all unit-bearing constants and quantities;
The first option is highly preferred, though care must still be paid to ensuring unit-bearing quantities possess the appropriate dimensionality and some considerations must be made for performance impact in parts of the code that must be performant since unit conversion incurs non-negligible overhead.

\textbf{Compatible constants.}
While some constants are exact, many physical constants are known only to a number of significant digits.
All values must be rounded to some number of significant figures when used in computer simulations, and these numbers have finite-precision floating-point representation that further reduces their accuracy.
Perhaps surprisingly, choices of how many significant figures that each constant should be rounded to can have an impact on the resulting simulations if care is not take to ensure that constants frequently used together are not rounded in a self-consistent manner.
For example, a major difference between potential energies computed in CHARMM and AMBER arises from an early arbitrary choice of the number of significant digits to round a set of critical Coulomb energy coefficients~\cite{Shirts.JCAMD.31.147.2017}.
Fortunately, the National Institute of Standards and Technology (NIST) provides up-to-date guidelines on consistent sets of physical parameters in the \href{http://ws680.nist.gov/publication/get_pdf.cfm?pub_id=920686}{2014 CODATA Self-Consistent Physical Constants} (updated every four years).
It is highly recommended that the CODATA parameters be adopted unless there is strong need to reproduce flawed results from a specific molecular simulation package.

\textbf{Pressure, the virial and pressure tail corrections.} To compute the system pressure,
we use the virial theorem

\begin{equation}
        P = \frac{1}{3V} \left< 3 N k_B T + \sum_{i < j} \textbf{f}_i \cdot \textbf{r}_i  \right>
\end{equation}

Where

\begin{equation}
        \sum_{i < j} \textbf{f}_i \cdot \textbf{r}_i = - \sum_{i < j} \frac{dU\left(r_{ij} \right)}{dr} r_{ij} = W
\end{equation}

The term $W$ is known as the virial and it is a pairwise sum and it can be computed
alongside the energies. Note that the negative derivative of the energy is the force.
For the LJ potential, this is

\begin{equation}
        \mathbf{f}\left(r_{ij} \right) = -\frac{dU \left(r_{ij} \right)}{dr} = - \frac{48 \epsilon}{r^2_{ij}} \left[\left(\frac{\sigma}{r_{ij}}\right)^{12} -\frac{1}{2}\left(\frac{\sigma}{r_{ij}}\right)^{6} \right] \mathbf{r}_{ij}
\end{equation}

The effect of the truncation of the interactions must be also taken into account for the pressure
computation using a correction term

\begin{equation}
        P_{tail} = \frac{16 \pi N^2}{3 V^2} \epsilon \sigma^3
        \left[\frac{2}{3} \left(\frac{\sigma}{r_c} \right)^9
        - \left(\frac{\sigma}{r_c} \right)^3 \right]
\end{equation}

\textbf{Reduced units.}
Lennard-Jones fluids have the surprisingly pleasant behavior of possessing universal behavior when expressed in terms of \emph{reduced units} as

\begin{equation}
	U^*\left(r_{ij} \right) = 4 \left[\left(\frac{1}{r^*_{ij}}\right)^{12} -\left(\frac{1}{r^*_{ij}}\right)^{6} \right]
	\label{eq.lennardjonesReduced}
\end{equation}

where

\begin{equation}
	U^* = \frac{U}{\epsilon}
\end{equation}

and

\begin{equation}
	r^* = \frac{r}{\sigma}
\end{equation}

That is, when plotted in reduced units, all Lennard-Jones fluids exhibit the same universal behavior despite the exact choices of $\epsilon$ and $\sigma$ used in the simulation. See Table \ref{table:reducedUnits} for a list
of variables in reduced units.
Using reduced units for input and output will allow you to compare your results with others.

\begin{table}[t]
\centering
 \begin{tabular}{|c c|}
 \hline
 Quantity & Expression \\ [0.5ex]
 \hline\hline
 Length &  $L^*=L / \sigma$   \\
 Density &  $\rho^* = N \sigma^3 / V$   \\
 Energy &  $U^* = U / \epsilon$   \\
 Pressure &  $P^* = P \sigma^3 / \epsilon$   \\
 Temperature & $T^* = k_B T / \epsilon$ \\
 Volume & $V^* = V / \sigma^3$ \\
 Time & $t^* = t \sqrt{\frac{\epsilon}{m \sigma^2}}$ \\
 \hline
 \end{tabular}
 \caption{Conversion factors between real and reduced units.}
 \label{table:reducedUnits}
\end{table}

\subsection{Reference calculations}

See the following resources for NIST Lennard-Jones fluid reference data:
\begin{itemize}
\item \href{https://mmlapps.nist.gov/srs/LJ_PURE/mc.htm}{Reference thermodynamic data ($N=500$, $T^*=0.90$ and $0.90$, $r_c = 3\sigma$)}
\item \href{https://www.nist.gov/mml/csd/chemical-informatics-research-group/lennard-jones-fluid-reference-calculations}{Reference snapshot potential energies and virials}
\end{itemize}

\section{Concrete tasks}

\textbf{Implement one (or more) methods to generate initial configurations. }
You will want implement more than one method to generate an initial
configuration. This will allow you to test if your code produces the same
final answers with different initial conditions. Among the possible options
are random placement of particles in the box, placement of particles in a
lattice or start a simulation using an old configuration.

\textbf{Implement the pairwise and long tail correction equations. }
These are the LJ potential, force (or virial) expression, energy and
pressure long tail corrections. Use reduced units,
as in Equation ~\ref{eq.lennardjonesReduced} to facilitate comparison with
others.

\textbf{Implement a function that computes the total energy of the system. }
Compare to the NIST reference snapshot potential energies and virials.

\textbf{Implement the Metropolis algorithm and compare to the NIST
benchmark. } See Section ~\ref{sec.flow} as
a reference. This is the part of the code where you will implement
features such as periodic boundary conditions, minimum image distance,
particle translation and the acceptance criteria. You can use the state point
$T^* = 0.9$, $\rho^* = 0.9$, and $r_c = 3\sigma$  and compare to the
NIST benchmark for thermodynamic data.

\textbf{Check if your energies are consistent with the NIST benchmark. }

\newpage
%
\bibliographystyle{aip.bst}
\bibliography{references.bib}

\end{document}


\chapter{Non-deterministic Classical Processes}\label{sec:main}
In this section, we will discuss our main contribution: an extension of \cp
which allows for races while still excluding deadlocks.
We have seen in \cref{sec:cp-example} how \cp excludes deadlocks, but how exactly
does \cp exclude races?
Let us return to our first example from \cref{sec:introduction}, to the
interaction between John, Mary and the store.
\[
  \begin{array}{c}
    \tm{(\piPar{%
    \piSend{x}{\sliceofcake}{\piSend{x}{\nope}{\store}}
    }{%
    \piPar{\piRecv{x}{y}{\john}}{\piRecv{x}{z}{\mary}}
    })}
    \\[1ex]
    \rotatebox[origin=c]{270}{$\Longrightarrow^{\star}$}
    \\[1ex]
    \tm{(\piPar{\store}{\piPar{\piSub{\sliceofcake}{y}{\john}}{\piSub{\nope}{z}{\mary}}})}
    \quad
    \text{or}
    \quad
    \tm{(\piPar{\store}{\piPar{\piSub{\nope}{y}{\john}}{\piSub{\sliceofcake}{z}{\mary}}})}
  \end{array}
\]
Races occur when more than two processes attempt to communicate simultaneously
over the \emph{same} channel. However, the \text{Cut} rule of \cp requires that
\emph{exactly two} processes communicate over each channel:
\begin{center}
  \cpInfCut
\end{center}
We could attempt write down a protocol for our example, stating that the store
has a pair of channels $\tm{x}, \tm{y} : \ty{\cake}$ with which it communicates
with John and Mary, taking \cake to be the type of interactions in which cake
\emph{may} be obtained, i.e.\ of both \sliceofcake and \nope, and state that the
store communicates with John \emph{and} Mary over a channel of type \ty{\cake
  \parr \cake}.
However, this \emph{only} models interactions such as the following:
\begin{prooftree}
  \AXC{$\seq[{ \john }]{ \Gamma, \tmty{x}{\cake^\bot} }$}
  \AXC{$\seq[{ \mary }]{ \Delta, \tmty{y}{\cake^\bot} }$}
  \SYM{\tens}
  \BIC{$\seq[{ \cpSend{y}{x}{\john}{\mary} }]{
      \Gamma, \Delta, \tmty{y}{\cake^\bot \tens \cake^\bot} }$}
  \AXC{$\seq[{ \store }]{ \Theta, \tmty{x}{\cake}, \tmty{y}{\cake} }$}
  \SYM{\parr}
  \UIC{$\seq[{ \cpRecv{y}{x}{\store} }]{
      \Theta, \tmty{y}{\cake \parr \cake} }$}
  \NOM{Cut}
  \BIC{$\seq[{ \cpCut{y}{\cpSend{y}{x}{\john}{\mary}}{\cpRecv{y}{x}{\store}} }]{
      \Gamma, \Delta, \Theta }$}
\end{prooftree}
Note that in this interaction, John will get whatever the store decides to send
on \tm{x}, and Mary will get whatever the store decides to send on \tm{y}.
This means that this interactions gives the choice of who receives what \emph{to
the store}. This is not an accurate model of our original example, where
the choice of who receives the cake is non-deterministic and depends on factors
outside of any of the participants' control!
And to make matters worse, the term which models our example is entirely
different from the one we initially wrote down in the \textpi-calculus!

The ability to model racy behaviour, such as that in our example, is essential
to describing the interactions that take place in realistic concurrent systems.
Therefore, we would like to extend \cp to allow such races.
Specifically, we would like to do it in a way which mirrors the way in which the
\textpi-calculus handles non-determinism.
We will base our extension on \rcp, a subset of \cp which we introduced in
\cref{sec:background}.
We have chosen to do this to keep our discussion as simple as possible.
Furthermore, as compatibility with the \textpi-calculus is of interest, we will
use the reduction system without commuting conversions, which we introduced in
\cref{sec:cppi}.

This chapter proceeds as follows.
In \cref{sec:nc-terms-and-types}, we introduce the extensions to the terms,
structural congruence and types of \cp.
In \cref{sec:nc-typing-clients-and-servers}, we introduce the typing rules for
\nodcap.
In \cref{sec:nc-running-clients-and-servers}, we introduce the reduction rules
for \nodcap.
In \cref{sec:nc-properties}, we prove that our extension preserves the
meta-theoretical of \cp.
Finally, in \cref{sec:nc-local-choice}, we discuss the relation between
non-determinism in \nodcap and the non-determinism introduced by the addition of
non-deterministic local choice.

\section{Terms and types}\label{sec:nc-terms-and-types}
Let us return, briefly, to our example.
\[
  \tm{(\piPar{%
      \piSend{x}{\sliceofcake}{\piSend{x}{\nope}{\store}}
    }{%
      \piPar{\piRecv{x}{y}{\john}}{\piRecv{x}{z}{\mary}}
    })}
\]
In this interaction, we see that the channel \tm{x} is used only as a way to
connect the various clients, John and Mary, to the store.
The \emph{real} communication, sending the slice of cake and disappointment,
takes places on the channels \tm{\sliceofcake}, \tm{\nope}, \tm{y} and \tm{z}.

Inspired by this, we add two new constructs to the term language of \cp: sending
and receiving on a \emph{shared} channel.
These actions are marked with a \tm{\star} in order to distinguish them
syntactically from ordinary sending and receiving.
To group clients, we add another form of parallel composition, which we refer to
as \emph{pooling}.
\input{def-nc-terms}
As before, round brackets denote input, square brackets denote output.
Note that \tm{\ncCnt{x}{y}{P}}, much like \tm{\cpSend{x}{y}{P}{Q}}, is a bound
output---this means that both client creation and server interaction bind a new
name.

In \rcp, we terms are identified up to the commutativity and associativity of
parallel composition. In \nodcap, we add another form of parallel composition,
and therefore must extend our structural congruence:
\input{def-nc-equiv}
We add axioms for the commutativity and associativity of pooling.
We do not add an axiom for \ncEquivPoolAss2, as it follows from
\cref{def:nc-equiv}, see \cref{thm:nc-pool-assoc2}.
It should be noted that \tm{\cpCut{x}{P}{Q}} is considered a single,
\emph{atomic} construct.
Therefore you \emph{cannot} use \ncEquivPoolAss1 to rewrite
\tm{\cpCut{x}{P}{\ncPool{Q}{R}}} to \tm{\cpCut{x}{\ncPool{P}{Q}}{R}}.
We do, however, add two axioms which relate cuts and pool.
We call these \emph{extrusion}, because they closely resemble the
\textpi-calculus axiom for scope extrusion.
We add both \ncRedKappaPool1 and \ncRedKappaPool2, as these relate two different
constructs, and therefore we cannot use the one to derive the other.
\input{thm-nc-pool-assoc2}
Furthermore, the extensions to structural congruence preserve symmetry.
\input{thm-nc-symmetry}
We can make another observation from our examples.
In every example in which a server interacts with a pool of clients, and which
does not deadlock, there are \emph{exactly} as many clients as there are
server interactions.
Therefore, we add two new \emph{dual} types for client pools and servers, which
track how many clients or server interactions they represent.
\input{def-nc-types}
\input{def-nc-negation}
With these new types, duality remains an involutive function.
\input{thm-nc-negation-involutive}

\section{Typing clients and servers}\label{sec:nc-typing-clients-and-servers}
We have to add typing rules to associate our new client and server
interactions with their types.
The definition for environments will remain unchanged, but we will extend the
definition for the typing judgement.
To determine the new typing rules, we essentially have to answer the question
``What typing constructs do we need to complete the following proof?''
\begin{prooftree}
  \AXC{$\seq[{ \john }]{ \Gamma, \tmty{y}{\cake^\bot} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \AXC{$\seq[{ \mary }]{ \Delta, \tmty{y'}{\cake^\bot} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \AXC{$\seq[{ \store }]{ \Theta, \tmty{z}{\cake}, \tmty{z'}{\cake} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \noLine\TIC{$\seq[{
      \cpCut{x}{\ncPool{\ncCnt{x}{y}{\john}}{\ncCnt{x}{y'}{\mary}}}{
        \ncSrv{x}{z}{\ncSrv{x}{z'}{\store}}} }]{
      \Gamma, \Delta, \Theta }$}
\end{prooftree}
Ideally, we would still like the composition of the client pool and the server
to be a cut. This seems reasonable, as the left-hand side of the term above has
2 clients, and the right-hand side has two server interactions, so \tm{x} is
used at type \ty{\take[2]{\cake^\bot}} on the left, and as \ty{\give[2]{\cake}}
on the right.
\begin{prooftree}
  \AXC{$\seq[{ \john }]{ \Gamma, \tmty{y}{\cake^\bot} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \AXC{$\seq[{ \mary }]{ \Delta, \tmty{y'}{\cake^\bot} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \noLine\BIC{$\seq[{ \ncPool{\ncCnt{x}{y}{\john}}{\ncCnt{x}{y'}{\mary}} }]{
      \Gamma, \Delta, \tmty{x}{\take[2]{\cake^\bot}} }$}

  \AXC{$\seq[{ \store }]{ \Theta, \tmty{z}{\cake}, \tmty{z'}{\cake} }$}
  \noLine\UIC{$\smash{\vdots}\vphantom{\vdash}$}
  \noLine\UIC{$\seq[{ \ncSrv{x}{z}{\ncSrv{x}{z'}{\store}} }]{
      \Theta, \tmty{x}{\give[2]{\cake}} }$}

  \NOM{Cut}
  \BIC{$\seq[{
      \cpCut{x}{\ncPool{\ncCnt{x}{y}{\john}}{\ncCnt{x}{y'}{\mary}}}{
        \ncSrv{x}{z}{\ncSrv{x}{z'}{\store}}} }]{
      \Gamma, \Delta, \Theta }$}
\end{prooftree}
We will define the typing judgement, and then discuss servers and clients, the
two sides of the above cut, describe the rules we add, and show how they allow
us to complete our proof.
\input{def-nc-typing-judgement}
\input{fig-nc-typing-judgement}

\subsection{Clients and pooling}\label{sec:clients-and-pooling}
A client pool represents a number of independent processes, each wanting to
interact with the server. Examples of such a pool include John and Mary from our
example, customers for online stores in general, and any number of processes
which interact with a single, centralised server.

We introduce two new rules: one to construct clients, and one to pool them
together. The first rule, $(\take[1]{})$, marks interaction over some channel as
a client interaction. It does this by receiving a channel \tm{y} over a
\emph{shared} channel \tm{x}. The channel \tm{y} is the channel across which the
actual interaction will eventually take place.
The second rule, \textsc{Pool}, allows us to pool together clients. This is
implemented, as in the \textpi-calculus, using parallel composition.
\begin{center}
  \ncInfTake1
  \ncInfPool
\end{center}
Using these rules, we can derive the left-hand side of our proof by marking John
and Mary as clients, and pooling them together.
\begin{prooftree}
  \AXC{$\seq[{ \john }]{ \Gamma, \tmty{y}{\cake^\bot} }$}
  \SYM{(\take[1]{})}
  \UIC{$\seq[{ \ncCnt{x}{y}{\john} }]{ \Gamma, \tmty{z}{\take[1]{\cake^\bot}} }$}

  \AXC{$\seq[{ \mary }]{ \Delta, \tmty{y'}{\cake^\bot} }$}
  \SYM{(\take[1]{})}
  \UIC{$\seq[{ \ncCnt{x}{y'}{\mary} }]{ \Delta, \tmty{y'}{\take[1]{\cake^\bot}} }$}

  \NOM{Pool}
  \BIC{$\seq[{ \ncPool{\ncCnt{x}{y}{\john}}{\ncCnt{x}{y'}{\mary}} }]{
      \Gamma, \Delta, \tmty{x}{\take[2]{\cake^\bot}} }$}
\end{prooftree}

\subsection{Servers and contraction}\label{sec:servers-and-contraction}
Dual to a pool of clients is a server. Our interpretation of a server is a
process which offers up some number of interdependent interactions of the same
type. Examples include the store from our example, which gives out slices of
cake and disappointment, online stores in general, and any central server which
interacts with some number of client processes.

We introduce two new rules to construct servers. The first rule, $(\give[1]{})$,
marks a interaction over some channel as a server interaction. It does this by
sending a channel \tm{y} over a \emph{shared} channel \tm{x}. The channel \tm{y}
is the channel across which the actual interaction will eventually take place.
The second rule, \textsc{Cont}, short for contraction, allows us to contract
several server interactions into a single server. This allows us to construct a
server which has multiple interactions of the same type, across the same shared
channel.\footnote{%
  While it ultimately does not matter whether $(\give[1]{})$ and $(\take[1]{})$
  are implemented with a send or a receive action, it feels more natural to have
  the server do the sending.
  Clients indicate their interest in interacting with the server by connecting
  to the shared channel, but it is up to the server to decide \emph{when} to
  interact with each channel.}
\begin{center}
  \ncInfGive1
  \ncInfCont
\end{center}
Using these rules, we can derive the right-hand side of our proof, by marking
each of the store's interactions as server interactions, and then contracting
them.
\begin{prooftree}
  \AXC{$\seq[{ \store }]{ \Theta, \tmty{z}{\cake}, \tmty{z'}{\cake} }$}
  \SYM{(\give[1]{})}
  \UIC{$\seq[{ \ncSrv{x'}{z'}{\store} }]{
      \Theta, \tmty{z}{\cake}, \tmty{x'}{\give[1]{\cake}} }$}
  \SYM{(\give[1]{})}
  \UIC{$\seq[{ \ncSrv{x}{z}{\ncSrv{x'}{z'}{\store}} }]{
      \Theta, \tmty{x}{\give[1]{\cake}}, \tmty{x'}{\give[1]{\cake}} }$}
  \NOM{Cont}
  \UIC{$\seq[{ \ncSrv{x}{z}{\ncSrv{x}{z'}{\store}} }]{
      \Theta, \tmty{x}{\give[2]{\cake}} }$}
\end{prooftree}
Thus, we complete the typing derivation of our example.

\section{Running clients and servers}\label{sec:nc-running-clients-and-servers}
Once we have a client/server interaction, how do we run it? Ideally, we would
simply use the reduction rule closest to the one used in the \textpi-calculus.
\[
  \reducesto
  {\tm{\cpCut{x}{\ncCnt{x}{y}{P}}{\ncSrv{x}{z}{R}}}}
  {\tm{\cpCut{y}{P}{\cpSub{y}{z}{R}}}}
\]
However, our case is complicated by the fact that in \tm{\cpCut{x}{P}{Q}} the
name restriction is an inseparable part of the composition, and therefore has to
be part of our reduction rule.
Because of this, the above reduction can only apply in the singleton case.
If the client pool contains more than one client, such as in the term below,
then there is no way to isolate a single client together with the server,
because \tm{x} occurs in both \tm{\ncCnt{x}{y}{P}} and \tm{\ncCnt{x}{z}{Q}}.
\[
  \tm{\cpCut{x}{\ncPool{\ncCnt{x}{y}{P}}{\ncCnt{x}{z}{Q}}}{\ncSrv{x}{w}{R}}}
  \centernot\Longrightarrow
\]
Therefore, we add a second reduction rule, which handles communication between a
one client in a pool of multiple clients and a server.
\[
  \reducesto
  {\tm{\cpCut{x}{\ncPool{\ncCnt{x}{y}{P}}{Q}}{\ncSrv{x}{z}{R}}}}
  {\tm{\cpCut{x}{Q}{\cpCut{y}{P}{\cpSub{y}{z}{R}}}}}
\]
Lastly, because we have added another form of parallel composition, we add
another congruence rule, to allow for reduction inside client pools.
\input{def-nc-term-reduction}

The rules \ncRedBetaStar1 and \ncRedBetaStar{n+1} seem like the elimination
rules for a list-like construct. This may come as a surprise, as our client
pools are built up like binary trees, and the typing rules for both sides are
tree-like, with $(\take[1]{})$ and $(\give[1]{})$ playing the role of leaves,
and \textsc{Pool} and \textsc{Cont} merging two trees with $m$ and $n$ leaves
into one with $m+n$ leaves.
However, the server process imposes a sequential ordering on its interactions,
and it is because of this that we have to use list-like elimination rules.

So where does the non-determinism in \nodcap come from? Let us say we have a
term of the following form:
\[
  \tm{
    \cpCut{x}
    {\ncPool{\ncCnt{x}{y_1}{P_1}}{\dots \mid \ncCnt{x}{y_n}{P_n}}}
    {\ncSrv{x}{y}{Q}}
  }
\]
Because pooling is commutative and associative, we can rewrite this term to
bring any client in the pool to the front, before applying \ncRedBetaStar{n+1}.
Thus, like in the \textpi-calculus, the non-determinism is introduced by the
structural congruence.

Does this mean that, for an arbitrary client pool \tm{P} in
\tm{\cpCut{x}{P}{\ncSrv{x}{z}{Q}}}, every client in that pool is competing for
the server interaction on \tm{x}?
Not necessarily, as some portion of the clients can be blocked on an external
communication. For instance, in the term below, clients
$\tm{\ncCnt{x}{y_{n+1}}{P_{n+1}}} \dots \tm{\ncCnt{x}{y_m}{P_m}}$ are blocked
on a communication on the external channel \tm{a}.
\[
  \arraycolsep=0pt
  \tm{
  \begin{array}{lrl}
    \nu x.&  ((&\; \ncPool{\ncCnt{x}{y_1}{P_1}}{\dots\mid\ncCnt{x}{y_n}{P_n}}\\
          &\mid&\; \cpWait{a}{\ncPool{\ncCnt{x}{y_{n+1}}{P_{n+1}}}{\dots \mid \ncCnt{x}{y_m}{P_m}}}\;)\\
          &\mid&\; \ncSrv{x}{y_1}{\dots\ncSrv{x}{y_m}{Q}}\;)
  \end{array}}
\]
If we reduce this term, then only the clients
$\tm{\ncCnt{x}{y_1}{P_1}} \dots \tm{\ncCnt{x}{y_n}{P_n}}$
will be assigned server interactions, and we end up with the following canonical
form term.
\[
  \arraycolsep=0pt
  \tm{
  \begin{array}{lrl}
    \nu x.&   (&\; \cpWait{a}{\ncPool{\ncCnt{x}{y_{n+1}}{P_{n+1}}}{\dots\mid\ncCnt{x}{y_m}{P_m}}}\\
          &\mid&\; \ncSrv{x}{y_{n+1}}{\dots\ncSrv{x}{y_m}{Q}}\;)
  \end{array}}
\]
This matches the reduction behaviour of the \textpi-calculus, and it fits with
out notion of computation with processes.

\section{Properties of \nodcap}\label{sec:nc-properties}
In this section, we will revisit the proofs for three important properties of
\rcp, namely preservation, progress, and termination, and show that our
extensions preserve these properties.

\subsection{Preservation}
Preservation is the fact that term reduction preserves typing. There are two
proofs involved in this. First, we show that structural congruence preserves
typing.
\input{thm-nc-preservation-equiv}
\input{fig-nc-preservation-equiv}
Secondly, we prove that term reduction preserves typing.
\input{thm-nc-preservation}
\input{fig-nc-preservation-1}

\subsection{Canonical forms and progress}
In this section, we will extend the definition of canonical forms and the proof
of progress progress given in \cref{sec:cppi}.

\subsubsection{Canonical forms}
First, we extend the definitions of actions with our actions for client and
server creation.
\input{def-nc-action}
Secondly, as we can reduce inside client pools, we will add pooling to our
definition of evaluation prefixes.
\input{def-nc-evaluation-prefixes}
The definition for the maximum evaluation prefix is unchanged.

There are some subtleties to our definition of canonical forms. The type system
for \cp guarantees that all links directly under an evaluation context act on a
bound channel. Not so for \nodcap.
\begin{scprooftree}
  \AXC{}
  \NOM{Ax}
  \UIC{$\seq[{ \cpLink{x}{y} }]{ \tmty{x}{\take[m]{A}}, \tmty{y}{\give[m]{A^\bot}} }$}
  \AXC{$\seq[{ P }]{ \Gamma, \tmty{x}{\take[n]{A}} }$}
  \NOM{Pool}
  \BIC{$\seq[{ \ncPool{\cpLink{x}{y}}{P} }]{ \Gamma, \tmty{x}{\take[m+n]{A}}, \tmty{y}{\give[m]{A^\bot}} }$}
\end{scprooftree}
There is no way to sensibly reduce this link.
Furthermore, in \cp, if two processes act on the same channel, then they must be
on different sides of the cut introducing that channel. The addition of shared
channels and client pools invalidates this property.
Therefore, we will have to be more careful about the way we define canonical
forms.
We restate the definition of canonical forms below. The additions have been
italicised.
\input{def-nc-canonical-forms}

\subsection{Evaluation contexts}
Evaluation contexts are one-holed term contexts under which reduction can take
place. Since we have added another congruence rule, stating that reduction can
take place inside client pools, we extend our definition of evaluation contexts
to match this.
\input{def-nc-evaluation-contexts}
We also restate \cref{thm:cp-display-cut-1}, and prove that our extension
preserves the property.
\input{thm-nc-display-cut-1}
Furthermore, it will be useful to prove a similar lemma, which shows that we can
push any pooling downwards under an evaluation context.
\input{thm-nc-display-pool-1}

\subsection{Progress}
Progress is the fact that every term is either in some canonical form, or can be
reduced further.
First, we will restate \cref{thm:cp-progress-link} and \cref{thm:cp-progress-beta},
which relate evaluation prefixes and evaluation contexts, and show that our
extension preserves these properties.
\input{thm-nc-progress-link}
\input{thm-nc-progress-beta}
In essence, \cref{thm:nc-progress-link} and \cref{thm:nc-progress-beta} cover
the cases in which either \cpRedAxCut1 or a \textbeta-reduction rule will be
applied.
However, after applying \cref{thm:nc-progress-beta}, we cannot immediately apply
\ncRedBetaStar{n+1}. For that, we must uncover at least one layer of pooling.
We prove a lemma which states that if we have an interaction on a shared channel
\tm{x}, we can push all pooling rules which pool clients communicating on \tm{x}
inwards.
\input{thm-nc-progress-shared}
Finally, we are ready to extend our proof of progress. The overall structure of
the proof remains the same, though the addition of pooling makes the wording
slightly more subtle.
\input{thm-nc-progress}

\subsection{Termination}
Termination is the fact that if we iteratively apply progress to obtain a
reduction, and apply that reduction, we will eventually end up with a term in
canonical form.
We restate its proof here for the sake of completeness, but its wording is
unchanged, modulo references to figures.
\input{thm-nc-termination}

\section{\nodcap and non-deterministic local choice}\label{sec:nc-local-choice}
In \cref{sec:local-choice}, we discussed the non-deterministic local choice
operator, which is used in several extensions of \piDILL and
\cp~\parencite{atkey2016,caires2014,caires2017}.
This operator is admissible in \nodcap.
We can derive the non-deterministic choice \tm{P+Q} by constructing the
following term:
\[
  \arraycolsep=0pt
  \tm{
  \begin{array}{lrlrl}
    \nu x.&((  & \; \ncCnt{x}{y}{\cpInr{y}{\cpHalt{y}}} \\
          &\mid& \; \ncCnt{x}{z}{\cpInr{z}{\cpHalt{z}}} \; )\\
          &\mid& \; \ncSrv{x}{y}{\ncSrv{x}{z}{}}\text{case}\;y\;
          &\;\{& \; \cpWait{y}{\cpCase{y}{\cpWait{y}{P}}{\cpWait{y}{P}}}\\
          &&& ;& \; \cpWait{y}{\cpCase{y}{\cpWait{y}{Q}}{\cpWait{y}{Q}}}\;\}\;)
  \end{array}
  }
\]
The term is a cut between two processes.
Both sides are well-typed, see~\cref{fig:nc-local-choice}.
\input{fig-nc-local-choice}
Let us unpack what each side is doing.
On the left-hand side, we have a pool of two processes,
\tm{\ncCnt{x}{y}{\cpInr{y}{\cpHalt{y}}}} and \tm{\ncCnt{x}{z}{\cpInr{z}{\cpHalt{z}}}}.
Each makes a choice---the first sends \tm{\text{inl}}, the second sends \tm{\text{inr}}.
On the right-hand side, we have a server with both \tm{P} and \tm{Q}.
This server has two channels on which a choice is offered, \tm{y} and
\tm{z}. However, the choice on \tm{z} does not affect the outcome of the
process.
When these clients and the server are put together, the choices offered by the
server will be non-deterministically lined up with the clients which make
choices, and either \tm{P} or \tm{Q} will run.

While there is a certain amount of overhead involved in this encoding, it scales
linearly in terms of the number of processes.
The reverse---encoding the non-determinism present in \nodcap using
non-deterministic local choice---scales exponentially, as with the \textpi-calculus.

Nonetheless, it is worrying that we duplicate each program \tm{P} and \tm{Q} in
order to encode non-deterministic local choice.
However, we can replace the each term of the form \tm{\cpCase{y}{\cpWait{y}{P}}{\cpWait{y}{P}}}
with \tm{\cpCut{w}{\cpCase{z}{\cpWait{z}{\cpHalt{w}}}{\cpWait{z}{\cpHalt{w}}}}{\cpWait{w}{P}}}.
This process is also well-typed, see below.
\begin{scprooftree}
  \AXC{}
  \SYM{(\one)}
  \UIC{$\seq[{ \cpHalt{w} }]{ \tmty{w}{\one} }$}
  \SYM{(\bot)}
  \UIC{$\seq[{ \cpWait{z}{\cpHalt{w}} }]{ \tmty{w}{\one}, \tmty{z}{\bot} }$}
  \AXC{}
  \SYM{(\one)}
  \UIC{$\seq[{ \cpHalt{w} }]{ \tmty{w}{\one} }$}
  \SYM{(\bot)}
  \UIC{$\seq[{ \cpWait{z}{\cpHalt{w}} }]{ \tmty{w}{\one}, \tmty{z}{\bot} }$}
  \SYM{(\with)}
  \BIC{$\seq[{
      \cpCase{z}{\cpWait{z}{\cpHalt{w}}}{\cpWait{z}{\cpHalt{w}}}
    }]{ \tmty{w}{\one}, \tmty{z}{\bot\with\bot} }$}
  \AXC{$\seq[{ P }]{ \Gamma }$}
  \SYM{(\bot)}
  \UIC{$\seq[{ \cpWait{w}{P} }]{ \Gamma, \tmty{w}{\bot} }$}
  \NOM{Cut}
  \BIC{$\seq[{
      \cpCut{w}{\cpCase{z}{\cpWait{z}{\cpHalt{w}}}{\cpWait{z}{\cpHalt{w}}}}{\cpWait{w}{P}}
    }]{ \Gamma, \tmty{z}{\bot\with\bot} }$}
\end{scprooftree}
%%% Local Variables:
%%% TeX-master: "main"
%%% End: