%
%

\chapter{Examples of {\smart} Applications} \label{SEC:Examples}
\markboth{EXAMPLES OF SMART APPLICATIONS}{}

This chapter contains a variety of examples to illustrate the various
capabilities available in {\smart}, and how to use them.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{A fixpoint iteration with repeated submodels}

Fixpoint iteration schemes can become quite complex.
In the following code, two copies of the same Petri net \Code{b} are used,
with different parameters, together with a second Petri net, \Code{d}.
This situation might arise when a particular Petri net models part of a system
which is replicated multiple times with different characteristics.
%
\lstinputlisting[firstline=3]{examples/conv_pns.sm}
%
Although multiple use of the same Petri net is convenient from the
user's point of view, it might actually cause {\smart} to perform extra work.
This is because {\smart} remembers important, and large, data structures
that it must build to compute a measure for a given high-level model,
so that the data structures can be reused for successive measures.
For example, the statement
\begin{lstlisting}
real x3 := d(i1:=x1, i2:=x2).o1;
\end{lstlisting}
causes the state space and stationary solution of Petri net \Code{d}
to be computed, while statement
\begin{lstlisting}
real x4 := d(i1:=x1, i2:=x2).o2;
\end{lstlisting}
simply reuses the previous computation and just computes a different measure.
However, when a model is parameterized, only the data structures
corresponding to parameters used in the latest call are kept,
to avoid excessive memory consumption.
Thus, if an iteration of the \Code{converge} statement
calls \Code{b(i1:=x3).o1} and \Code{b(i1:=x4).o1} with \Code{x3} and
\Code{x4} set to different values, the next iteration will
not be able to reuse work even if the value of \Code{x3}, \Code{x4},
or both, are the same as in the previous iteration.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Finding the optimal value of a function}

The \Code{converge} statement in {\smart} can be used to obtain the optimal
value of a convex or concave function (or a local optimum for any function
with continuous first derivatives).
The idea is that, given the values $f_1$, $f_2$, $f_3$, and $f_4$
of a convex function at four distinct points $x_1 < x_2 < x_3 < x_4$,
we can discard the leftmost or the rightmost point (or the two leftmost
or righmost points if the values are in monotonic order), based on these values;
we can then iterate the search within the remaining interval,
and stop when the four points and the four values are sufficiently close.
The following code illustrates how to do this in {\smart}:
%
\lstinputlisting[firstline=3]{examples/maxima.sm}
%
Note that option \Code{UseCurrent} must be set to \Code{false} for this
scheme to work properly, otherwise the values of $x_2$, $x_3$, and $x_4$
would be updated using the new values computed for $x_1$, $x_2$, and $x_3$,
which is incorrect.

Of course, instead of using this scheme to discover that the maximum value
of $x-x^2$ over the interval $[0,1]$ is $0.25$ and is achieved at $x=0.5$
(or a close approximation of that, since this a numerical iterative method),
we can use it, for example, to find the time at which a given measure is
maximized in a Petri net model or the value of a rate for which the probability
of absorption is minimized in a continuous-time model.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Dining philosophers}

The dining philosopher model \cite{Pastor1994} is composed of $N$ subnets equal
to the one shown in Fig.~\ref{FIG:dining}.
The net represents a philosopher and the philosopher's right fork.
The philosopher's left fork, represented by
the dotted place $\mathit{Fork}_{(i+1) \bmod N}$, is part of the
subnet for the next philosopher; it
is depicted to illustrate how the subnets interact.
The corresponding {\smart} code is as follows:
%
\lstinputlisting[firstline=3]{examples/phils_ex1.sm}
%

\begin{figure}
  \centering
  \includegraphics[scale=1]{figures/phils.pdf}
  \caption{Model for a single dining philosopher.}
  \label{FIG:dining}
\end{figure}

\begin{comment}

If we wanted to use an advanced symbolic method, we could request this with an
option statement, which must appear before the two \Code{print} statements.
However, this also requires to partition the model.
We could do so by assigning \Code{M} philosophers per level:
\begin{code}
\begin{verbatim}
spn phils(int N, int M) := {
  for (int i in {1..N}) {
    ...
    partition(1+div(i,M):Idle[i]:WaitL[i]:WaitR[i]:HasL[i]:HasR[i]:Fork[i]);
  }
  for (int i in {1..N}) {
    ...
  }
  ...
};
# StateStorage MDD_SATURATION
int N := read_int("number of philosophers");
int M := read_int("number of philosophers per level");
print("Number of reachable states: ", phils(N,M).ns, ".\n");
print("Number of state-to-state transitions: ", phils(N,M).na, ".\n");
\end{verbatim}
\end{code}
Of course, if \Code{N} is not a multiple of \Code{M}, the last
level will have fewer than \Code{M} philosophers.
Also, a partition must define at least two levels, thus
\Code{N} must be strictly greater than \Code{M}.
Having more philosophers per level decreases the number of levels in the
MDD, but increases the size of the local state spaces, hence of the
MDD nodes.

If we had used a method requiring pregeneration of the local state
spaces, we would have to add the statement
\begin{code}
\begin{verbatim}
    inhibit(Fork[1+mod(i,N)]:Rel[i], HasR[1+mod(i,N)]:Rel[i]);
\end{verbatim}
\end{code}
in the second \Code{for} loop, to ensure that these local state spaces
are finite.

\end{comment}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{A flexible manufacturing system}

The Petri net \cite{1991PNPM-Decomposition} in Fig.~\ref{FIG:fms}
models a flexible manufacturing system (FMS).
This model is parameterized by the initial number $N$ of tokens in
$P_1$, $P_2$, and $P_3$.
The {\smart} description for this net is:
%
\lstinputlisting[firstline=3]{examples/fms_ex1.sm}
%

\begin{figure}
  \centering
  \includegraphics[scale=0.5]{figures/FMS-smartman.pdf}
  \caption{A flexible manufacturing system.}
  \label{FIG:fms}
\end{figure}

\begin{comment}

Had we wanted to use a structural solution approach, we could have
partitioned the model with the statement
\begin{code}
\begin{verbatim}
partition(P1:P1wM1:P1M1:M1:P1d:P1s, P12s:P12M3:M3:P12wM3:P12:P1wP2:P2wP1,
  P2:P2wM2:P2M2:M2:P2d:P2s, P3:P3M2:P3s);
\end{verbatim}
\end{code}
(which defines four submodels) and used the options
\begin{code}
\begin{verbatim}
# StateStorage MULTI_LEVEL_AVL
# MarkovStorage MATRIX_DIAGRAM_GENERAL
\end{verbatim}
\end{code}
Note, however, that the usually more efficient methods
\begin{code}
\begin{verbatim}
# StateStorage MDD_SATURATION
# MarkovStorage MATRIX_DIAGRAM_KRONECKER
\end{verbatim}
\end{code}
cannot be used with the given partition, because some immediate transitions,
such as \Code{tP1j}, are synchronizing (i.e., they affect multiple submodels).

%We partition the model into 19 levels obtained by assigning
%each place to a different level, with the exception of
%the complementary places $M_1$, $M_2$, and $M_3$, placed in the same level
%as the places $P_1M_1$, $P_2M_2$, and $P_{12}M_3$, respectively.

\end{comment}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Slotted ring}

Fig.~\ref{FIG:slotted} shows the Petri net for a single node of a slotted
ring network protocol \cite{Pastor1994}.
The overall model is composed of $N$
such subnets connected by merging transitions
(i.e., $\mathit{Free}_{(i+1) \bmod N}$ and $\mathit{Used}_{(i+1) \bmod N}$
really belong to the ``next'' subnet).
The following {\smart} code shows a decomposition where each
node of the ring is in a different level, and the requested
measure is simply the number of states.
%
\lstinputlisting[firstline=3]{examples/slot.sm}
%

\begin{figure}
  \centering
  \includegraphics[scale=0.5]{figures/slot.pdf}
  \caption{Model of a slotted ring.}
  \label{FIG:slotted}
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{A Kanban system}

This model \cite{1996WMPN-SNSkanban}, shown in Fig.~\ref{FIG:kanban},
is parameterized by the number $N$ of tokens initially
in $p_{1}$, $p_{2}$, $p_{3}$, and $p_{4}$.
The following code shows a partition into four levels, one per kanban station.
The output measure is the number of arcs in the state-to-state transition
matrix for $N$ varying from $1$ to a maximum specified at runtime.
\begin{figure}
  \centering
  \includegraphics[scale=1]{figures/kanban.pdf}
  \caption{A kanban system.}
  \label{FIG:kanban}
\end{figure}
%
\lstinputlisting[firstline=3]{examples/kanban.sm}
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Randomized leader election protocol}

The randomized asynchronous leader election protocol in \cite{DolevKR82}
solves the following problem: given a ring of $N$ processors, the
participants are required to designate a unique processor as leader by
sending messages around the ring. The ring is unidirectional, meaning that
the processes send messages to their unique successor (e.g. the one to the
right), and receive messages from their unique predecessor. It is known that
if the processors are indistinguishable (no unique identifiers are
assigned), then there is no deterministic algorithm to solve the problem.

The randomized algorithm works in phases. At the beginning of every round,
each process flips a coin to decide whether it will continue running for
election or not. Initially all processes are valid candidates. After
choosing a value ($0 = $ don't run this round, $1 = $ run), this is
communicated to the neighbour to the right. A process is eliminated from the
race only if it chose not to run and it's predecessor chose to run. After
being eliminated from the race, a process never becomes eligible again (it
enters the inactive state), and it is used only to relay messages between
active nodes around the ring. They do no initiate any communication.
Termination is detected by the active processes (at least one active node
exists at all times) by sending a token around the ring to count the
inactive nodes. The process that receives its own token with count $N-1$ is
the elected leader.

In our model, each processes has $5$ state variables:
\begin{lstlisting}
status[i]       : {start, wait, active, inactive, leader};      // init start
preference[i]   : {0, 1};                                       // init 0
counter[i]      : {0..N-1};                                     // init 0
sent[i]         : {none, pref, counter};                        // init none
recv[i]         : {none, pref, counter};                        // init none
\end{lstlisting}

\begin{figure}
  \centering
  \includegraphics[scale=0.5]{figures/leaderchart.pdf}
  \caption{State transition chart for the \Code{status} variable.}
  \label{FIG:leaderchart}
\end{figure}

\noindent The state-transition diagram for the \Code{status} of a process is
shown in Figure \ref{FIG:leaderchart}.

\IGNORE{
The Petri Net model is shown is Figure \ref{FIG:leaderfig}
\begin{figure}
  \CENTERPSSCALE{leaderfig}{0.5}
  \caption{Petri net model: the subnet of process $i$.}
  \label{FIG:leaderfig}
\end{figure}
}

\noindent The SMART code for this model is listed below:
%
\lstinputlisting[firstline=3]{examples/leader.sm}
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{A round--robin mutual exclusion protocol}

\begin{comment}
The protocol regulates the access to a shared resource (e.g. a communication
channel) for a ring of $N$ processors. The resource manager gives permission
to use the channel to each process in order, by moving a token around the
ring. When a process has the token, it reads in a message from the channel and
stores it in its own buffer. It can then release the token to the next processor
before reading the contents of the buffer, or read the buffer first and then
send the token to the neighbour.

Figure \ref{FIG:robinfig} shows the subnet for process $i$.
Each subnet is initially marked with one token in place $\id{wait}_i$,
except for process $0$ which starts with one token in $\id{req}_i$, meaning
that it is the first process to have access when the protocol starts.

\begin{figure}
  \CENTERPSSCALE{robinfig}{0.5}
  \caption{The round--robin mutual exclusion.}
  \label{FIG:robinfig}
\end{figure}

\begin{code}
\begin{verbatim}
spn robin(int N) := {
  place Res;
  partition(1:Res);
  for (int i in {0..N-1}) {
    place
        R[i], bufidle[i], buffull[i],
        pwait[i], pask[i], pok[i], pload[i], psend[i];
    trans
        task[i], tbuf[i], t1load[i], t2load[i], t1send[i], t2send[i];
    partition(
        i+2:bufidle[i]:buffull[i]:pwait[i]:pask[i]:pok[i]:pload[i]:psend[i],
        1:R[i]);
    firing(task[i]:expo(1.0), tbuf[i]:expo(1.0), t1load[i]:expo(1.0),
        t1send[i]:expo(1.0), t2load[i]:expo(1.0), t2send[i]:expo(1.0));
  }
  for (int i in {0..N-1}) {
    arcs(Res:task[i], pask[i]:task[i], task[i]:R[i], task[i]:pok[i],
        R[i]:tbuf[i], bufidle[i]:tbuf[i], tbuf[i]:buffull[i], tbuf[i]:Res,
        buffull[i]:t1load[i], pok[i]:t1load[i], t1load[i]:bufidle[i], t1load[i]:psend[i],
        buffull[i]:t2load[i], pload[i]:t2load[i], t2load[i]:bufidle[i], t2load[i]:pwait[i],
        pok[i]:t1send[i], pwait[mod(i+1,N)]:t1send[i],
        t1send[i]:pload[i], t1send[i]:pask[mod(i+1,N)],
        psend[i]:t2send[i], pwait[mod(i+1,N)]:t2send[i],
        t2send[i]:pwait[i], t2send[i]:pask[mod(i+1,N)]);
  }
  init(Res:1, pask[0]:1);
  for (int i in {1..N-1}) {init (pwait[i]:1);}
  for (int i in {0..N-1}) {init(bufidle[i]:1);}
}
\end{verbatim}
\end{code}

\end{comment}


\chapter{QCD primer}
\label{chap:qcd}

Quantum chromodynamics is the theory of strong interactions\footnote{A brief historical review about the development of {\sffamily QCD} may be found at \cite{historyqcd}.}. It aims to describe the interactions between elementary constituents, namely the quarks\footnote{The quarks were firstly predicted in Gell-Mann's Eightfold Way \cite{gellmann}.}, mediated by the carriers of the color force, the gluons.

The existence of color charge was proposed as an additional quantum number which would solve the violation of Pauli's exclusion principle for some particular baryons\footnote{For example, $\Delta^{++}$, which consists of three up quarks.}. Since the quarks were never experimentally evidenced, it was proposed that the strong interaction constrains the free particles to only exist in color neutral states. This particularity of {\sffamily QCD} is known as color confinement. Nevertheless, in the partonic picture\footnote{Feynman proposed that high energy nuclei are made of elementary constituents, generically called partons \cite{partons}.}, deep inelastic scattering\footnote{{\sffamily DIS} is a process during which the structure of a hadron may be probed via interaction with, in general, a lepton.} experiments between an electron and a proton confirmed the already predicted Bjorken scaling\footnote{Bjorken deduced an expression for the cross-section of the electron by imagining that it interacts electromagnetically with each parton from the proton \cite{bjorkenimf}.} of the electrons' differential cross-section.

In essence, {\sffamily QCD} is an extension of the original $\textsf{SU}(2)$ gauge theory of Yang and Mills \cite{yangmills} to local non-Abelian $\textsf{SU}(3)$ gauge transformations.

\section{Field content}
Following textbook expositions \cite{maggiore, peskin, greiner}, the {\sffamily QCD} Lagrangian $\mathcal{L}$ is constructed from symmetry principles, namely $\textsf{SO}(1,3)$ Lorentz invariance and local gauge invariance under $\textsf{SU}(3)$. The fields should transform according to irreducible representations of these groups. The quark content of the Lagrangian is described by the quark and anti-quark fields $\psi_{\alpha,i,f}(x)$ and $\overline{\psi}_{\alpha,i,f}(x)$. They are Dirac spinors (spinorial index $\alpha$), transform according to the fundamental representation of $\textsf{SU}(3)$ (color index $i=1,2,3$ or red, green, blue) and come in different flavours (flavour index $f=\overline{1,N_f}$ or up, down, strange, charm, bottom, up). The gluon fields $A_a^\mu(x)$ are Lorentz vectors and each correspond to a generator $t^a$ ($a=\overline{1,8}$) which, in the fundamental representation, is given by the Gell-Mann matrices $t^a=\lambda^a/2$.

\section{Gauge transformations}
The quark and anti-quark fields must be invariant under local $\textsf{SU}(3)$ gauge transformations\footnote{For simplicity, all the field indices will be dropped in the following computations.}
\shadedeq{
    \psi(x)\mapsto\textsf{U}(x)\psi(x), \quad \overline{\psi}\mapsto\overline{\psi}(x)\textsf{U}^\dagger(x)
}
with the group transformation expressible, via exponentiation, from the Lie algebra generators, with space-time dependent group parameters $\varepsilon^a(x)$, as
\boxedeqlabel{gaugetransf}{
    \textsf{U}(x)=\exp{i\sum_a\varepsilon^a(x)t^a}
}
The gauge fields\footnote{For each algebra element $t^a$, one may introduce a gauge field $A_a^\mu$. These may be then used to construct a Lie-algebra valued gauge potential $A^\mu$. This potential depends on the chosen representation.} $A_\mu(x)=\sum\limits_a A^a_\mu(x)t^a$ must transform according to
\boxedeqlabel{gaugefields}{
    A_\mu(x)\mapsto\textsf{U}(x)A_\mu(x)\textsf{U}^\dagger(x)+\frac{i}{g}\textsf{U}(x)\big[\partial_\mu\textsf{U}^\dagger(x)\big]
}
where $g$ denotes the coupling constant. It is important to notice that one may generate gluon fields out of a null one, that is $A_\mu=0$ by applying a local gauge transformation. Such field configurations take the form
\begin{equation*}
    A_\mu^{\text{pure}}=\frac{i}{g}\textsf{U}\big(\partial_\mu\textsf{U}^\dagger\big)
\end{equation*}
and are called pure gauge fields \cite{gelisqft,eichmann}. The corresponding field strength tensor is null $F_{\mu\nu}^{\text{pure}}=0$.

One may introduce the covariant derivative\footnote{The covariant derivative has an elegant geometrical interpretation \cite{torre}: it represents the rate of change when fields from different space-time points are parallel transported along a given path. During this procedure, they are being aligned such that they may be properly compared. The corresponding connection is actually the gauge field.}
\begin{equation*}
    \textsf{D}_\mu=\partial_\mu-igA_\mu.
\end{equation*}
Further, one may define the field strength tensor as the commutator between covariant derivatives\footnote{Since it arises as a commutator between covariant derivatives, which describe the parallel transport, the field strength tensor may be interpreted as a measure of the path dependence of parallel transport. For this reason, it is also referred to as the curvature \cite{torre}.}
\begin{equation*}
    F_{\mu\nu}=\frac{i}{g}\big[\textsf{D}_\mu,\textsf{D}_\nu\big],
\end{equation*}
which yields an expression in terms of gauge fields
\shadedeq{
    F_{\mu\nu}=\partial_\mu A_\nu-\partial_\nu A_\mu-ig\big[A_\mu,A_\nu\big]
}
or equivalently, by color components $F_{\mu\nu}=F_{\mu\nu}^at^a$, as
\begin{equation*}
    F_{\mu\nu}^a=\partial_\mu A_\nu^a-\partial_\nu A_\nu^a+gf^{abc}A_\mu^bA_\nu^c,
\end{equation*}
where $f^{abc}$ are the structure constants of the Lie algebra $\mathfrak{su}(3)$. The last term from the above equation, when plugged in the Lagrangian, will give rise to gluonic self-interactions, a particular feature of QCD. The field strength tensor gauge transforms in the usual manner as
\shadedeq{
    F_{\mu\nu}(x)\mapsto \textsf{U}(x)F_{\mu\nu}(x)\textsf{U}^\dagger(x)
}

\section{QCD Lagrangian}
One may now proceed to constructing the Lagrangian. The quark content is that of a free fermionic Lagrangian\footnote{After replacing the partial derivative with the covariant derivative, the Lagrangian will also contain an interaction term
\begin{equation*}
    \mathcal{L}_{\textsf{int}}=g \overline{\psi} \gamma^\mu A_\mu^a t^a \psi.
\end{equation*}}, but built with covariant derivatives, in order to satisfy gauge invariance
\begin{equation*}
    \mathcal{L}_{\textsf{quarks}}=\overline{\psi}(x)\big(i\slashed{\textsf{D}}-\textsf{M}\big)\psi(x),
\end{equation*}
where $\textsf{M}=\textsf{Diag}\left\{m_1,\ldots,m_{N_f}\right\}$ is the diagonal quark mass matrix in flavour space\footnote{In the Standard Model, the quark mass matrix is no longer diagonal. After spontaneous symmetry breaking, the mixing between different flavoured quark masses is given by the {\sffamily CKM} matrix \cite{pdg}.}.

The dynamics of the gluon fields is described by the following construction\footnote{It is important to notice that such a construction contains not only standard kinetic terms but also interaction vertices with three gluons, which are proportional to $g$ and four gluons, proportional to $g^2$.}
\begin{equation*}
    \mathcal{L}_{\textsf{gluons}}=-\frac{1}{2}\textsf{Tr}\left\{F_{\mu\nu}F^{\mu\nu}\right\},
\end{equation*}
where the color tracing over the contraction of field strength tensors assured gauge invariance. Equivalently, one may rewrite the above expression in terms of color components as
\begin{equation*}
    \mathcal{L}_{\textsf{gluons}}=-\frac{1}{4}F_{\mu\nu}^aF^{a,\mu\nu},
\end{equation*}
valid in the fundamental representation, where $\textsf{Tr}\left\{t^at^b\right\}=\delta^{ab}/2$. Therefore, the {\sffamily QCD} Lagrangian takes the form
\boxedeqlabel{qcd6}{
    \mathcal{L}_{\textsf{QCD}}=\overline{\psi}(x)\big(i\slashed{\textsf{D}}-\textsf{M}\big)\psi(x)-\frac{1}{4}F_{\mu\nu}^aF^{a,\mu\nu}
}

The corresponding Yang-Mills action expressed in flat coordinates is given by
\begin{align}\label{yangmills}
    \textsf{S}=\int\mathrm{d}^4x\left(-\frac{1}{2}\textsf{Tr}\left\{F_{\mu\nu}F^{\mu\nu}\right\}\right),
\end{align}

\section{Field equations}
The variational derivatives with respect to the color spinor fields give the colored Dirac equations
\begin{equation*}
    (i\slashed{\textsf{D}}-\textsf{M})\psi=0,
\end{equation*}
and similarly for the anti-quark fields
\begin{equation*}
    \overline{\psi}(i\overleftarrow{\slashed{\textsf{D}}}-\textsf{M})=0.
\end{equation*}
The Euler-Lagrange equations corresponding to the gluon fields yield the Yang-Mills equations, or equivalently, colored Maxwell equations\footnote{There is an additional equation, called the Bianchi identity, which follows from the definition and properties of $F_{\mu\nu}$. It may be expressed as \cite{tong}
\begin{equation*}
    \textsf{D}_\mu^{\phantom{*}*}F^{\mu\nu}=0,
\end{equation*}
where we introduced the dual field strength tensor as
\begin{equation*}
    ^*F^{\mu\nu}=\frac{1}{2}\epsilon^{\mu\nu\rho\sigma}F_{\rho\sigma}.
\end{equation*}}
\shadedeq{
    \textsf{D}_\nu F^{\nu\mu}=gJ^\mu
}
in which $J^\mu=\sum\limits_a J^{a,\mu} t^a$ with $J^{a,\mu}=\overline{\psi}\gamma^\nu t^a\psi$ being the color current. The color current is covariantly conserved $\textsf{D}_\mu J^\mu=0$.


\section{Hints on Using the Prover Effectively}

\begin{frame}
  \frametitle{Control the Size of Formulas}

  \begin{itemize}
  \item \tc{dkblue}{Proof obligations are often large}

    \begin{itemize}
    \o long definitions of actions and invariants
    \o \kw{let} constructions add to complexity when expanded
    \end{itemize}

  \oo \tc{dkblue}{The backend provers are easily overwhelmed by large formulas}

    \begin{itemize}
    \o may work on top-level operators or deeply inside a long formula
    \o even simple proof steps may take an extraordinate amount of time
    \end{itemize}

  \oo \alert{Use local definitions and \HIDE\ them when unnecessary}

    \begin{itemize}
    \o prove facts about a \kw{let}-bound operator, then \HIDE\ it
    \end{itemize}
  \end{itemize}

  \vfill\vfill
\end{frame}

\begin{frame}
  \frametitle{Example: Controlling the Size of Expressions}

  \qquad\begin{tlablock}
    \LEMMA\
    \begin{noj2}
      & \begin{conj}
          x \in SomeVeryBigExpression\\
          y \in AnotherBigExpression
        \end{conj}\\
      \biimplies &
        \begin{conj}
            y \in AnotherBigExpression\\
            x \in SomeVeryBigExpression
        \end{conj}
\pause
        \hspace{1cm}\raisebox{0cm}[0pt][0pt]{\begin{minipage}{3cm}
          \begin{beamercolorbox}[rounded=true,shadow=true]{postit}\footnotesize
            \OBVIOUS\ may take\\forever here
          \end{beamercolorbox}
        \end{minipage}}
    \end{noj2}\\
\pause
    \ps{1}{.}\ \ \ \DEFINE\ S\ \deq\ SomeVeryBigExpression\\
    \ps{1}{.}\ \ \ \DEFINE\ T\ \deq\ AnotherBigExpression\\
    \ps{1}{1.}\ S = SomeVeryBigExpression\\
    \quad\OBVIOUS\\
    \ps{1}{2.}\ T = AnotherBigExpression\\
    \quad\OBVIOUS\\
    \ps{1}{.}\ \ \ \HIDE\ \DEF\ S,\ T\\
    \ps{1}{3.}\
      \begin{noj2}
        & x \in S \land y \in T\\
        \biimplies & y \in T \land x \in S
      \end{noj2}\\
    \quad\OBVIOUS\\
    \ps{1}{4.}\ \QED\qquad\BY\ \ps{1}{1},\ \ps{1}{2},\ \ps{1}{3}
  \end{tlablock}
\end{frame}

\begin{frame}
  \frametitle{Avoid Circular Rewrites}

  \begin{itemize}
  \item \tc{dkblue}{Rewriting is often effective for reasoning about equalities}

    \begin{itemize}
    \o idea: replace left-hand side of equality by right-hand side
    \o Isabelle's automatic tactic are based on rewriting
    \o for example, use\ \ \tc{dkgreen}{$x' = x-y \land y'=y$}\ \ to eliminate $x'$ and $y'$    \end{itemize}

\pause

  \oo \tc{dkblue}{Must make sure that rewriting terminates}

    \begin{itemize}
    \o consider\ \ \tc{dkgreen}{$s = f(t) \land t = g(s)$}
    \o Isabelle attempts to reject circular sets of equations
    \o if rejected, proof may get stuck
    \o if not rejected, proof may never terminate
    \end{itemize}

  \oo \alert{Use local definitions, and \HIDE\ them to break loops}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Circular Rewrites: Example}

  \qquad\begin{tlablock}
    \ps{4}{5.}\ r.name = \str{xyz}\\
    \quad\ps{5}{1.}\ r = [name \mapsto "xyz",\ value \mapsto \alt<1>{r}{\alert{r}}.value]\\
    \quad\quad\BY\ \ps{2}{2}\\
    \quad\ps{5}{2.}\ \QED\\
    \quad\quad\BY\ \ps{5}{1}
  \end{tlablock}

\pause

  \vfill\vfill

  \qquad\alert{The equation in step $\ps{5}{1}$ is circular!}

  \vfill\vfill

\pause

  \qquad\begin{tlablock}
    \ps{4}{5.}\ r.name = \str{xyz}\\
    \quad\ps{5}{}\ \ \ \DEFINE\ rval\ \deq\ r.value\\
    \quad\ps{5}{1.}\ r = [name \mapsto "xyz",\ value \mapsto rval]\\
    \quad\quad\BY\ \ps{2}{2}\\
    \quad\ps{5}{}\ \ \ \HIDE\ \DEF\ rval\\
    \quad\ps{5}{2.}\ \QED\\
    \quad\quad\BY\ \ps{5}{1}
  \end{tlablock}
\end{frame}

\begin{frame}
  \frametitle{Establishing Facts About \CHOOSE}

  \qquad\begin{tlablock}
    \DEFINE\ m\ \deq\ \CHOOSE x \in S : P(x)\\
    \DEFINE\ NoValue\ \deq\ \CHOOSE x : x \notin Value
  \end{tlablock}

  \begin{itemize}
  \oo \tc{dkblue}{How to prove a property $Q(m)$ ?}

    \begin{itemize}
    \o \CHOOSE\ always denotes some value, even if $P(x)$ holds for no $x \in S$
    \end{itemize}

\pause

  \oo \tc{dkblue}{In practice, must establish the two following facts}

    \begin{itemize}
    \o $\E x \in S : P(x)$
    \o $\A x \in S : P(x) \implies Q(x)$
    \o \tlaps\ will then deduce $Q(m)$
    \end{itemize}

\pause

  \oo \tc{dkblue}{Important special case: ``null'' values}

    \begin{itemize}
    \o existence of such a value follows from the library theorem

      \medskip

      \begin{tlablock}
        NoSetContainsEverything\ \deq\ \A S : \E x : x \notin S
      \end{tlablock}
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{It's Easier To Prove Something If It's True}

  \begin{itemize}
  \item \tc{dkblue}{All specifications initially contain mistakes}

    \begin{itemize}
    \o errors range from typos to misunderstandings to genuine bugs
    \o formal mathematical definitions are hard to get right
    \end{itemize}

  \oo \tc{dkblue}{\tlaps\ is not good at catching specification errors}

    \begin{itemize}
    \o if you are stuck on a proof, is it you, the prover or the specification?
    \o even with structured proofs, complexity quickly gets out of hand
    \end{itemize}

  \oo \tc{dkblue}{Extensively debug your specifications using \tlc}

    \begin{itemize}
    \o almost all bugs manifest themselves on small instances
    \o run \tlc\ on many properties and inspect the counter-examples
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Focus On The Theorems You Are Interested In}

  \begin{itemize}
  \item \tc{dkblue}{\tlaps\ currently has limited support for theories}

    \begin{itemize}
    \o set theory and functions are fully supported
    \o decision procedure for elementary integer arithmetic
    \o very rudimentary support for sequences
    \end{itemize}

\pause

  \oo \tc{dkblue}{State facts about ``data'' as assumptions}

    \begin{itemize}
    \o do you want to verify an algorithm or basic mathematics?
    \o but --- isn't that dangerous?
    \o it is, but you can validate many assumptions using \tlc
    \o override infinite sets with finite ones in the model, e.g.\ \ \tc{dkgreen}{$Nat\ \deq\ 0..50$}
    \end{itemize}

\pause

  \oo \alert{Theory support will improve slowly and your help is welcome}
  \end{itemize}
\end{frame}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "tutorial"
%%% End:


\chapter[Detailed examples of tactics]{Detailed examples of tactics\label{Tactics-examples}}

This chapter presents detailed examples of certain tactics, to
illustrate their behavior.

\section[\tt dependent induction]{\tt dependent induction\label{dependent-induction-example}}
\def\depind{{\tt dependent induction}~}
\def\depdestr{{\tt dependent destruction}~}

The tactics \depind and \depdestr are another solution for inverting
inductive predicate instances and potentially doing induction at the
same time. It is based on the \texttt{BasicElim} tactic of Conor McBride which
works by abstracting each argument of an inductive instance by a variable
and constraining it by equalities afterwards. This way, the usual
{\tt induction} and {\tt destruct} tactics can be applied to the
abstracted instance and after simplification of the equalities we get
the expected goals.

The abstracting tactic is called {\tt generalize\_eqs} and it takes as
argument an hypothesis to generalize. It uses the {\tt JMeq} datatype
defined in {\tt Coq.Logic.JMeq}, hence we need to require it before.
For example, revisiting the first example of the inversion documentation above:

\begin{coq_example*}
Require Import Coq.Logic.JMeq.
\end{coq_example*}
\begin{coq_eval}
Require Import Coq.Program.Equality.
\end{coq_eval}

\begin{coq_eval}
Inductive Le : nat -> nat -> Set :=
  | LeO : forall n:nat, Le 0 n
  | LeS : forall n m:nat, Le n m -> Le (S n) (S m).
Variable P : nat -> nat -> Prop.
Variable Q : forall n m:nat, Le n m -> Prop.
\end{coq_eval}

\begin{coq_example*}
Goal forall n m:nat, Le (S n) m -> P n m.
intros n m H.
\end{coq_example*}
\begin{coq_example}
generalize_eqs H.
\end{coq_example}

The index {\tt S n} gets abstracted by a variable here, but a
corresponding equality is added under the abstract instance so that no
information is actually lost. The goal is now almost amenable to do induction
or case analysis. One should indeed first move {\tt n} into the goal to
strengthen it before doing induction, or {\tt n} will be fixed in
the inductive hypotheses (this does not matter for case analysis).
As a rule of thumb, all the variables that appear inside constructors in
the indices of the hypothesis should be generalized. This is exactly
what the \texttt{generalize\_eqs\_vars} variant does:

\begin{coq_eval}
Undo 1.
\end{coq_eval}
\begin{coq_example}
generalize_eqs_vars H.
induction H.
\end{coq_example}

As the hypothesis itself did not appear in the goal, we did not need to
use an heterogeneous equality to relate the new hypothesis to the old
one (which just disappeared here). However, the tactic works just as well
in this case, e.g.:

\begin{coq_eval}
Admitted.
\end{coq_eval}

\begin{coq_example}
Goal forall n m (p : Le (S n) m), Q (S n) m p.
intros n m p ; generalize_eqs_vars p.
\end{coq_example}

One drawback of this approach is that in the branches one will have to
substitute the equalities back into the instance to get the right
assumptions. Sometimes injection of constructors will also be needed to
recover the needed equalities. Also, some subgoals should be directly
solved because of inconsistent contexts arising from the constraints on
indexes. The nice thing is that we can make a tactic based on
discriminate, injection and variants of substitution to automatically
do such simplifications (which may involve the K axiom).
This is what the {\tt simplify\_dep\_elim} tactic from
{\tt Coq.Program.Equality} does. For example, we might simplify the
previous goals considerably:
% \begin{coq_eval}
% Abort.
% Goal forall n m:nat, Le (S n) m -> P n m.
% intros n m H ; generalize_eqs_vars H.
% \end{coq_eval}

\begin{coq_example}
induction p ; simplify_dep_elim.
\end{coq_example}

The higher-order tactic {\tt do\_depind} defined in {\tt
  Coq.Program.Equality} takes a tactic and combines the
building blocks we have seen with it: generalizing by equalities
calling the given tactic with the
generalized induction hypothesis as argument and cleaning the subgoals
with respect to equalities. Its most important instantiations are
\depind and \depdestr that do induction or simply case analysis on the
generalized hypothesis. For example we can redo what we've done manually
with \depdestr:

\begin{coq_eval}
Abort.
\end{coq_eval}
\begin{coq_example*}
Require Import Coq.Program.Equality.
Lemma ex : forall n m:nat, Le (S n) m -> P n m.
intros n m H.
\end{coq_example*}
\begin{coq_example}
dependent destruction H.
\end{coq_example}
\begin{coq_eval}
Abort.
\end{coq_eval}

This gives essentially the same result as inversion. Now if the
destructed hypothesis actually appeared in the goal, the tactic would
still be able to invert it, contrary to {\tt dependent
 inversion}. Consider the following example on vectors:

\begin{coq_example*}
Require Import Coq.Program.Equality.
Set Implicit Arguments.
Variable A : Set.
Inductive vector : nat -> Type :=
| vnil : vector 0
| vcons : A -> forall n, vector n -> vector (S n).
Goal forall n, forall v : vector (S n),
  exists v' : vector n, exists a : A, v = vcons a v'.
  intros n v.
\end{coq_example*}
\begin{coq_example}
  dependent destruction v.
\end{coq_example}
\begin{coq_eval}
Abort.
\end{coq_eval}

In this case, the {\tt v} variable can be replaced in the goal by the
generalized hypothesis only when it has a type of the form {\tt vector
 (S n)}, that is only in the second case of the {\tt destruct}. The
first one is dismissed because {\tt S n <> 0}.

\subsection{A larger example}

Let's see how the technique works with {\tt induction} on inductive
predicates on a real example. We will develop an example application to the
theory of simply-typed lambda-calculus formalized in a dependently-typed style:

\begin{coq_example*}
Inductive type : Type :=
| base : type
| arrow : type -> type -> type.
Notation " t --> t' " := (arrow t t') (at level 20, t' at next level).
Inductive ctx : Type :=
| empty : ctx
| snoc : ctx -> type -> ctx.
Notation " G , tau " := (snoc G tau) (at level 20, tau at next level).
Fixpoint conc (G D : ctx) : ctx :=
  match D with
    | empty => G
    | snoc D' x => snoc (conc G D') x
  end.
Notation " G ; D " := (conc G D) (at level 20).
Inductive term : ctx -> type -> Type :=
| ax : forall G tau, term (G, tau) tau
| weak : forall G tau,
  term G tau -> forall tau', term (G, tau') tau
| abs : forall G tau tau',
  term (G , tau) tau' -> term G (tau --> tau')
| app : forall G tau tau',
  term G (tau --> tau') -> term G tau -> term G tau'.
\end{coq_example*}

We have defined types and contexts which are snoc-lists of types. We
also have a {\tt conc} operation that concatenates two contexts.
The {\tt term} datatype represents in fact the possible typing
derivations of the calculus, which are isomorphic to the well-typed
terms, hence the name. A term is either an application of:
\begin{itemize}
\item the axiom rule to type a reference to the first variable in a context,
\item the weakening rule to type an object in a larger context
\item the abstraction or lambda rule to type a function
\item the application to type an application of a function to an argument
\end{itemize}

Once we have this datatype we want to do proofs on it, like weakening:

\begin{coq_example*}
Lemma weakening : forall G D tau, term (G ; D) tau ->
  forall tau', term (G , tau' ; D) tau.
\end{coq_example*}
\begin{coq_eval}
  Abort.
\end{coq_eval}

The problem here is that we can't just use {\tt induction} on the typing
derivation because it will forget about the {\tt G ; D} constraint
appearing in the instance. A solution would be to rewrite the goal as:
\begin{coq_example*}
Lemma weakening' : forall G' tau, term G' tau ->
  forall G D, (G ; D) = G' ->
  forall tau', term (G, tau' ; D) tau.
\end{coq_example*}
\begin{coq_eval}
  Abort.
\end{coq_eval}

With this proper separation of the index from the instance and the right
induction loading (putting {\tt G} and {\tt D} after the inducted-on
hypothesis), the proof will go through, but it is a very tedious
process. One is also forced to make a wrapper lemma to get back the
more natural statement. The \depind tactic alleviates this trouble by
doing all of this plumbing of generalizing and substituting back automatically.
Indeed we can simply write:

\begin{coq_example*}
Require Import Coq.Program.Tactics.
Lemma weakening : forall G D tau, term (G ; D) tau ->
  forall tau', term (G , tau' ; D) tau.
Proof with simpl in * ; simpl_depind ; auto.
  intros G D tau H. dependent induction H generalizing G D ; intros.
\end{coq_example*}

This call to \depind has an additional arguments which is a list of
variables appearing in the instance that should be generalized in the
goal, so that they can vary in the induction hypotheses. By default, all
variables appearing inside constructors (except in a parameter position)
of the instantiated hypothesis will be generalized automatically but
one can always give the list explicitly.

\begin{coq_example}
  Show.
\end{coq_example}

The {\tt simpl\_depind} tactic includes an automatic tactic that tries
to simplify equalities appearing at the beginning of induction
hypotheses, generally using trivial applications of
reflexivity. In cases where the equality is not between constructor
forms though, one must help the automation by giving
some arguments, using the {\tt specialize} tactic for example.

\begin{coq_example*}
destruct D... apply weak ; apply ax. apply ax.
destruct D...
\end{coq_example*}
\begin{coq_example}
Show.
\end{coq_example}
\begin{coq_example}
  specialize (IHterm G0 empty eq_refl).
\end{coq_example}

Once the induction hypothesis has been narrowed to the right equality,
it can be used directly.

\begin{coq_example}
  apply weak, IHterm.
\end{coq_example}

If there is an easy first-order solution to these equations as in this subgoal, the
{\tt specialize\_eqs} tactic can be used instead of giving explicit proof
terms:

\begin{coq_example}
  specialize_eqs IHterm.
\end{coq_example}
This concludes our example.
\SeeAlso The induction \ref{elim}, case \ref{case} and inversion \ref{inversion} tactics.

\section[\tt autorewrite]{\tt autorewrite\label{autorewrite-example}}

Here are two examples of {\tt autorewrite} use. The first one ({\em Ackermann
function}) shows actually a quite basic use where there is no conditional
rewriting. The second one ({\em Mac Carthy function}) involves conditional
rewritings and shows how to deal with them using the optional tactic of the
{\tt Hint~Rewrite} command.

\firstexample
\example{Ackermann function}
%Here is a basic use of {\tt AutoRewrite} with the Ackermann function:

\begin{coq_example*}
Reset Initial.
Require Import Arith.
Variable Ack :
           nat -> nat -> nat.
Axiom Ack0 :
        forall m:nat, Ack 0 m = S m.
Axiom Ack1 : forall n:nat, Ack (S n) 0 = Ack n 1.
Axiom Ack2 : forall n m:nat, Ack (S n) (S m) = Ack n (Ack (S n) m).
\end{coq_example*}

\begin{coq_example}
Hint Rewrite Ack0 Ack1 Ack2 : base0.
Lemma ResAck0 :
 Ack 3 2 = 29.
autorewrite with base0 using try reflexivity.
\end{coq_example}

\begin{coq_eval}
Reset Initial.
\end{coq_eval}

\example{Mac Carthy function}
%The Mac Carthy function shows a more complex case:

\begin{coq_example*}
Require Import Omega.
Variable g :
           nat -> nat -> nat.
Axiom g0 :
        forall m:nat, g 0 m = m.
Axiom
  g1 :
    forall n m:nat,
      (n > 0) -> (m > 100) -> g n m = g (pred n) (m - 10).
Axiom
  g2 :
    forall n m:nat,
      (n > 0) -> (m <= 100) -> g n m = g (S n) (m + 11).
\end{coq_example*}

\begin{coq_example}
Hint Rewrite g0 g1 g2 using omega : base1.
Lemma Resg0 :
 g 1 110 = 100.
autorewrite with base1 using reflexivity || simpl.
\end{coq_example}

\begin{coq_eval}
Abort.
\end{coq_eval}

\begin{coq_example}
Lemma Resg1 : g 1 95 = 91.
autorewrite with base1 using reflexivity || simpl.
\end{coq_example}

\begin{coq_eval}
Reset Initial.
\end{coq_eval}

\section[\tt quote]{\tt quote\tacindex{quote}
\label{quote-examples}}

The tactic \texttt{quote} allows using Barendregt's so-called
2-level approach without writing any ML code. Suppose you have a
language \texttt{L} of
'abstract terms' and a type \texttt{A} of 'concrete terms'
and a function \texttt{f : L -> A}. If \texttt{L} is a simple
inductive datatype and \texttt{f} a simple fixpoint, \texttt{quote f}
will replace the head of current goal by a convertible term of the form
\texttt{(f t)}. \texttt{L} must have a constructor of type: \texttt{A
  -> L}.

Here is an example:

\begin{coq_example}
Require Import Quote.
Parameters A B C : Prop.
Inductive formula : Type :=
  | f_and : formula -> formula -> formula (* binary constructor *)
  | f_or : formula -> formula -> formula
  | f_not : formula -> formula (* unary constructor *)
  | f_true : formula (* 0-ary constructor *)
  | f_const : Prop -> formula (* constructor for constants *).
Fixpoint interp_f (f:
                   formula) : Prop :=
  match f with
  | f_and f1 f2 => interp_f f1 /\ interp_f f2
  | f_or f1 f2 => interp_f f1 \/ interp_f f2
  | f_not f1 => ~ interp_f f1
  | f_true => True
  | f_const c => c
  end.
Goal A /\ (A \/ True) /\ ~ B /\ (A <-> A).
quote interp_f.
\end{coq_example}

The algorithm to perform this inversion is: try to match the
term with right-hand sides expression of \texttt{f}. If there is a
match, apply the corresponding left-hand side and call yourself
recursively on sub-terms. If there is no match, we are at a leaf:
return the corresponding constructor (here \texttt{f\_const}) applied
to the term.

\begin{ErrMsgs}
\item \errindex{quote: not a simple fixpoint} \\
  Happens when \texttt{quote} is not able to perform inversion properly.
\end{ErrMsgs}

\subsection{Introducing variables map}

The normal use of \texttt{quote} is to make proofs by reflection: one
defines a function \texttt{simplify : formula -> formula} and proves a
theorem \texttt{simplify\_ok: (f:formula)(interp\_f (simplify f)) ->
  (interp\_f f)}. Then, one can simplify formulas by doing:
\begin{verbatim}
   quote interp_f.
   apply simplify_ok.
   compute.
\end{verbatim}
But there is a problem with leafs: in the example above one cannot
write a function that implements, for example, the logical simplifications
$A \land A \ra A$ or $A \land \lnot A \ra \texttt{False}$. This is
because the \Prop{} is impredicative.

It is better to use that type of formulas:

\begin{coq_eval}
Reset formula.
\end{coq_eval}
\begin{coq_example}
Inductive formula : Set :=
  | f_and : formula -> formula -> formula
  | f_or : formula -> formula -> formula
  | f_not : formula -> formula
  | f_true : formula
  | f_atom : index -> formula.
\end{coq_example*}

\texttt{index} is defined in module \texttt{quote}. Equality on that
type is decidable so we are able to simplify $A \land A$ into $A$ at
the abstract level.

When there are variables, there are bindings, and \texttt{quote}
provides also a type \texttt{(varmap A)} of bindings from
\texttt{index} to any set \texttt{A}, and a function
\texttt{varmap\_find} to search in such maps. The interpretation
function has now another argument, a variables map:

\begin{coq_example}
Fixpoint interp_f (vm:
                    varmap Prop) (f:formula) {struct f} : Prop :=
  match f with
  | f_and f1 f2 => interp_f vm f1 /\ interp_f vm f2
  | f_or f1 f2 => interp_f vm f1 \/ interp_f vm f2
  | f_not f1 => ~ interp_f vm f1
  | f_true => True
  | f_atom i => varmap_find True i vm
  end.
\end{coq_example}

\noindent\texttt{quote} handles this second case properly:

\begin{coq_example}
Goal A /\ (B \/ A) /\ (A \/ ~ B).
quote interp_f.
\end{coq_example}

It builds \texttt{vm} and \texttt{t} such that \texttt{(f vm t)} is
convertible with the conclusion of current goal.

\subsection{Combining variables and constants}

One can have both variables and constants in abstracts terms; that is
the case, for example, for the \texttt{ring} tactic (chapter
\ref{ring}). Then one must provide to \texttt{quote} a list of
\emph{constructors of constants}. For example, if the list is
\texttt{[O S]} then closed natural numbers will be considered as
constants and other terms as variables.

Example:

\begin{coq_eval}
Reset formula.
\end{coq_eval}
\begin{coq_example*}
Inductive formula : Type :=
  | f_and : formula -> formula -> formula
  | f_or : formula -> formula -> formula
  | f_not : formula -> formula
  | f_true : formula
  | f_const : Prop -> formula (* constructor for constants *)
  | f_atom : index -> formula.
Fixpoint interp_f
 (vm:            (* constructor for variables *)
  varmap Prop) (f:formula) {struct f} : Prop :=
  match f with
  | f_and f1 f2 => interp_f vm f1 /\ interp_f vm f2
  | f_or f1 f2 => interp_f vm f1 \/ interp_f vm f2
  | f_not f1 => ~ interp_f vm f1
  | f_true => True
  | f_const c => c
  | f_atom i => varmap_find True i vm
  end.
Goal
A /\ (A \/ True) /\ ~ B /\ (C <-> C).
\end{coq_example*}

\begin{coq_example}
quote interp_f [ A B ].
Undo.
  quote interp_f [ B C iff ].
\end{coq_example}

\Warning Since function inversion
is undecidable in general case, don't expect miracles from it!

\begin{Variants}

\item {\tt quote {\ident} in {\term} using {\tac}}

  \tac\ must be a functional tactic (starting with {\tt fun x =>})
  and will be called with the quoted version of \term\ according to
  \ident.

\item {\tt quote {\ident} [ \ident$_1$ \dots\ \ident$_n$ ] in {\term} using {\tac}}

  Same as above, but will use \ident$_1$, \dots, \ident$_n$ to
  chose which subterms are constants (see above).

\end{Variants}

% \SeeAlso file \texttt{theories/DEMOS/DemoQuote.v}

\SeeAlso comments of source file \texttt{plugins/quote/quote.ml}

\SeeAlso the \texttt{ring} tactic (Chapter~\ref{ring})

\section{Using the tactical language}

\subsection{About the cardinality of the set of natural numbers}

A first example which shows how to use the pattern matching over the proof
contexts is the proof that natural numbers have more than two elements. The
proof of such a lemma can be done as %shown on Figure~\ref{cnatltac}.
follows:
%\begin{figure}
%\begin{centerframe}
\begin{coq_eval}
Reset Initial.
Require Import Arith.
Require Import List.
\end{coq_eval}
\begin{coq_example*}
Lemma card_nat :
 ~ (exists x : nat, exists y : nat, forall z:nat, x = z \/ y = z).
Proof.
red; intros (x, (y, Hy)).
elim (Hy 0); elim (Hy 1); elim (Hy 2); intros;
 match goal with
 | [_:(?a = ?b),_:(?a = ?c) |- _ ] =>
     cut (b = c); [ discriminate | transitivity a; auto ]
 end.
Qed.
\end{coq_example*}
%\end{centerframe}
%\caption{A proof on cardinality of natural numbers}
%\label{cnatltac}
%\end{figure}

We can notice that all the (very similar) cases coming from the three
eliminations (with three distinct natural numbers) are successfully solved by
a {\tt match goal} structure and, in particular, with only one pattern (use
of non-linear matching).

\subsection{Permutation on closed lists}

Another more complex example is the problem of permutation on closed lists. The
aim is to show that a closed list is a permutation of another one.

First, we define the permutation predicate as shown in table~\ref{permutpred}.

\begin{figure}
\begin{centerframe}
\begin{coq_example*}
Section Sort.
Variable A : Set.
Inductive permut : list A -> list A -> Prop :=
  | permut_refl   : forall l, permut l l
  | permut_cons   :
      forall a l0 l1, permut l0 l1 -> permut (a :: l0) (a :: l1)
  | permut_append : forall a l, permut (a :: l) (l ++ a :: nil)
  | permut_trans  :
      forall l0 l1 l2, permut l0 l1 -> permut l1 l2 -> permut l0 l2.
End Sort.
\end{coq_example*}
\end{centerframe}
\caption{Definition of the permutation predicate}
\label{permutpred}
\end{figure}

A more complex example is the problem of permutation on closed lists.
The aim is to show that a closed list is a permutation of another one.
First, we define the permutation predicate as shown on
Figure~\ref{permutpred}.

\begin{figure}
\begin{centerframe}
\begin{coq_example}
Ltac Permut n :=
  match goal with
  | |- (permut _ ?l ?l) => apply permut_refl
  | |- (permut _ (?a :: ?l1) (?a :: ?l2)) =>
      let newn := eval compute in (length l1) in
      (apply permut_cons; Permut newn)
  | |- (permut ?A (?a :: ?l1) ?l2) =>
      match eval compute in n with
      | 1 => fail
      | _ =>
          let l1' := constr:(l1 ++ a :: nil) in
          (apply (permut_trans A (a :: l1) l1' l2);
            [ apply permut_append | compute; Permut (pred n) ])
      end
  end.
Ltac PermutProve :=
  match goal with
  | |- (permut _ ?l1 ?l2) =>
      match eval compute in (length l1 = length l2) with
      | (?n = ?n) => Permut n
      end
  end.
\end{coq_example}
\end{centerframe}
\caption{Permutation tactic}
\label{permutltac}
\end{figure}

Next, we can write naturally the tactic and the result can be seen on
Figure~\ref{permutltac}. We can notice that we use two toplevel
definitions {\tt PermutProve} and {\tt Permut}. The function to be
called is {\tt PermutProve} which computes the lengths of the two
lists and calls {\tt Permut} with the length if the two lists have the
same length. {\tt Permut} works as expected.  If the two lists are
equal, it concludes. Otherwise, if the lists have identical first
elements, it applies {\tt Permut} on the tail of the lists.  Finally,
if the lists have different first elements, it puts the first element
of one of the lists (here the second one which appears in the {\tt
  permut} predicate) at the end if that is possible, i.e., if the new
first element has been at this place previously. To verify that all
rotations have been done for a list, we use the length of the list as
an argument for {\tt Permut} and this length is decremented for each
rotation down to, but not including, 1 because for a list of length
$n$, we can make exactly $n-1$ rotations to generate at most $n$
distinct lists. Here, it must be noticed that we use the natural
numbers of {\Coq} for the rotation counter. On Figure~\ref{ltac}, we
can see that it is possible to use usual natural numbers but they are
only used as arguments for primitive tactics and they cannot be
handled, in particular, we cannot make computations with them. So, a
natural choice is to use {\Coq} data structures so that {\Coq} makes
the computations (reductions) by {\tt eval compute in} and we can get
the terms back by {\tt match}.

With {\tt PermutProve}, we can now prove lemmas as
% shown on Figure~\ref{permutlem}.
follows:
%\begin{figure}
%\begin{centerframe}

\begin{coq_example*}
Lemma permut_ex1 :
  permut nat (1 :: 2 :: 3 :: nil) (3 :: 2 :: 1 :: nil).
Proof. PermutProve. Qed.
Lemma permut_ex2 :
  permut nat
    (0 :: 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: 8 :: 9 :: nil)
    (0 :: 2 :: 4 :: 6 :: 8 :: 9 :: 7 :: 5 :: 3 :: 1 :: nil).
Proof. PermutProve. Qed.
\end{coq_example*}
%\end{centerframe}
%\caption{Examples of {\tt PermutProve} use}
%\label{permutlem}
%\end{figure}

\subsection{Deciding intuitionistic propositional logic}

\begin{figure}[b]
\begin{centerframe}
\begin{coq_example}
Ltac Axioms :=
  match goal with
  | |- True => trivial
  | _:False |- _  => elimtype False; assumption
  | _:?A |- ?A  => auto
  end.
\end{coq_example}
\end{centerframe}
\caption{Deciding intuitionistic propositions (1)}
\label{tautoltaca}
\end{figure}

\begin{figure}
\begin{centerframe}
\begin{coq_example}
Ltac DSimplif :=
  repeat
   (intros;
    match goal with
     | id:(~ _) |- _ => red in id
     | id:(_ /\ _) |- _ =>
         elim id; do 2 intro; clear id
     | id:(_ \/ _) |- _ =>
         elim id; intro; clear id
     | id:(?A /\ ?B -> ?C) |- _ =>
         cut (A -> B -> C);
          [ intro | intros; apply id; split; assumption ]
     | id:(?A \/ ?B -> ?C) |- _ =>
         cut (B -> C);
          [ cut (A -> C);
             [ intros; clear id
             | intro; apply id; left; assumption ]
          | intro; apply id; right; assumption ]
     | id0:(?A -> ?B),id1:?A |- _ =>
         cut B; [ intro; clear id0 | apply id0; assumption ]
     | |- (_ /\ _) => split
     | |- (~ _) => red
     end).
Ltac TautoProp :=
  DSimplif;
   Axioms ||
     match goal with
     | id:((?A -> ?B) -> ?C) |- _ =>
          cut (B -> C);
          [ intro; cut (A -> B);
             [ intro; cut C;
                [ intro; clear id | apply id; assumption ]
             | clear id ]
          | intro; apply id; intro; assumption ]; TautoProp
     | id:(~ ?A -> ?B) |- _ =>
         cut (False -> B);
          [ intro; cut (A -> False);
             [ intro; cut B;
                [ intro; clear id | apply id; assumption ]
             | clear id ]
          | intro; apply id; red; intro; assumption ]; TautoProp
     | |- (_ \/ _) => (left; TautoProp) || (right; TautoProp)
     end.
\end{coq_example}
\end{centerframe}
\caption{Deciding intuitionistic propositions (2)}
\label{tautoltacb}
\end{figure}

The pattern matching on goals allows a complete and so a powerful
backtracking when returning tactic values. An interesting application
is the problem of deciding intuitionistic propositional logic.
Considering the contraction-free sequent calculi {\tt LJT*} of
Roy~Dyckhoff (\cite{Dyc92}), it is quite natural to code such a tactic
using the tactic language as shown on Figures~\ref{tautoltaca}
and~\ref{tautoltacb}. The tactic {\tt Axioms} tries to conclude using
usual axioms. The tactic {\tt DSimplif} applies all the reversible
rules of Dyckhoff's system. Finally, the tactic {\tt TautoProp} (the
main tactic to be called) simplifies with {\tt DSimplif}, tries to
conclude with {\tt Axioms} and tries several paths using the
backtracking rules (one of the four Dyckhoff's rules for the left
implication to get rid of the contraction and the right or).

For example, with {\tt TautoProp}, we can prove tautologies like
 those:
% on Figure~\ref{tautolem}.
%\begin{figure}[tbp]
%\begin{centerframe}
\begin{coq_example*}
Lemma tauto_ex1 : forall A B:Prop, A /\ B -> A \/ B.
Proof. TautoProp. Qed.
Lemma tauto_ex2 :
   forall A B:Prop, (~ ~ B -> B) -> (A -> B) -> ~ ~ A -> B.
Proof. TautoProp. Qed.
\end{coq_example*}
%\end{centerframe}
%\caption{Proofs of tautologies with {\tt TautoProp}}
%\label{tautolem}
%\end{figure}

\subsection{Deciding type isomorphisms}

A more tricky problem is to decide equalities between types and modulo
isomorphisms. Here, we choose to use the isomorphisms of the simply typed
$\lb{}$-calculus with Cartesian product and $unit$ type (see, for example,
\cite{RC95}). The axioms of this $\lb{}$-calculus are given by
table~\ref{isosax}.

\begin{figure}
\begin{centerframe}
\begin{coq_eval}
Reset Initial.
\end{coq_eval}
\begin{coq_example*}
Open Scope type_scope.
Section Iso_axioms.
Variables A B C : Set.
Axiom Com : A * B = B * A.
Axiom Ass : A * (B * C) = A * B * C.
Axiom Cur : (A * B -> C) = (A -> B -> C).
Axiom Dis : (A -> B * C) = (A -> B) * (A -> C).
Axiom P_unit : A * unit = A.
Axiom AR_unit : (A -> unit) = unit.
Axiom AL_unit : (unit -> A) = A.
Lemma Cons : B = C -> A * B = A * C.
Proof.
intro Heq; rewrite Heq; reflexivity.
Qed.
End Iso_axioms.
\end{coq_example*}
\end{centerframe}
\caption{Type isomorphism axioms}
\label{isosax}
\end{figure}

A more tricky problem is to decide equalities between types and modulo
isomorphisms. Here, we choose to use the isomorphisms of the simply typed
$\lb{}$-calculus with Cartesian product and $unit$ type (see, for example,
\cite{RC95}). The axioms of this $\lb{}$-calculus are given on
Figure~\ref{isosax}.

\begin{figure}[ht]
\begin{centerframe}
\begin{coq_example}
Ltac DSimplif trm :=
  match trm with
  | (?A * ?B * ?C) =>
      rewrite <- (Ass A B C); try MainSimplif
  | (?A * ?B -> ?C) =>
      rewrite (Cur A B C); try MainSimplif
  | (?A -> ?B * ?C) =>
      rewrite (Dis A B C); try MainSimplif
  | (?A * unit) =>
      rewrite (P_unit A); try MainSimplif
  | (unit * ?B) =>
      rewrite (Com unit B); try MainSimplif
  | (?A -> unit) =>
      rewrite (AR_unit A); try MainSimplif
  | (unit -> ?B) =>
      rewrite (AL_unit B); try MainSimplif
  | (?A * ?B) =>
      (DSimplif A; try MainSimplif) || (DSimplif B; try MainSimplif)
  | (?A -> ?B) =>
      (DSimplif A; try MainSimplif) || (DSimplif B; try MainSimplif)
  end
 with MainSimplif :=
  match goal with
  | |- (?A = ?B) => try DSimplif A; try DSimplif B
  end.
Ltac Length trm :=
  match trm with
  | (_ * ?B) => let succ := Length B in constr:(S succ)
  | _ => constr:1
  end.
Ltac assoc := repeat rewrite <- Ass.
\end{coq_example}
\end{centerframe}
\caption{Type isomorphism tactic (1)}
\label{isosltac1}
\end{figure}

\begin{figure}[ht]
\begin{centerframe}
\begin{coq_example}
Ltac DoCompare n :=
  match goal with
  | [ |- (?A = ?A) ] => reflexivity
  | [ |- (?A * ?B = ?A * ?C) ] =>
      apply Cons; let newn := Length B in
                  DoCompare newn
  | [ |- (?A * ?B = ?C) ] =>
      match eval compute in n with
      | 1 => fail
      | _ =>
          pattern (A * B) at 1; rewrite Com; assoc; DoCompare (pred n)
      end
  end.
Ltac CompareStruct :=
  match goal with
  | [ |- (?A = ?B) ] =>
      let l1 := Length A
      with l2 := Length B in
      match eval compute in (l1 = l2) with
      | (?n = ?n) => DoCompare n
      end
  end.
Ltac IsoProve := MainSimplif; CompareStruct.
\end{coq_example}
\end{centerframe}
\caption{Type isomorphism tactic (2)}
\label{isosltac2}
\end{figure}

The tactic to judge equalities modulo this axiomatization can be written as
shown on Figures~\ref{isosltac1} and~\ref{isosltac2}. The algorithm is quite
simple. Types are reduced using axioms that can be oriented (this done by {\tt
MainSimplif}). The normal forms are sequences of Cartesian
products without Cartesian product in the left component. These normal forms
are then compared modulo permutation of the components (this is done by {\tt
CompareStruct}). The main tactic to be called and realizing this algorithm is
{\tt IsoProve}.

% Figure~\ref{isoslem} gives
Here are examples of what can be solved by {\tt IsoProve}.
%\begin{figure}[ht]
%\begin{centerframe}
\begin{coq_example*}
Lemma isos_ex1 :
  forall A B:Set, A * unit * B = B * (unit * A).
Proof.
intros; IsoProve.
Qed.

Lemma isos_ex2 :
  forall A B C:Set,
    (A * unit -> B * (C * unit)) =
    (A * unit -> (C -> unit) * C) * (unit -> A -> B).
Proof.
intros; IsoProve.
Qed.
\end{coq_example*}
%\end{centerframe}
%\caption{Type equalities solved by {\tt IsoProve}}
%\label{isoslem}
%\end{figure}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "Reference-Manual"
%%% End:


\documentclass{scrartcl}

%\usepackage{natbib}
\usepackage{latexrc/macros}

\addbibresource{biblio.bib}

\title{Metastability for the Contact Process on $\integer$}
\author{Owen Lynch \and Kacper Urbański}
\DeclareMathOperator{\expDist}{Exp}

\usepackage{interval}
\newcommand{\ep}{\varepsilon}
\intervalconfig{soft open fences}
\newcommand{\loi}[2]{\interval[open left]{#1}{#2}}
\newcommand{\roi}[2]{\interval[open right]{#1}{#2}}
\newcommand{\Ninf}{\roi{-N}{\infty}}
\newcommand{\infN}{\loi{-\infty}{N}}
\begin{document}

\maketitle
\begin{abstract}
    Metastability is the coexistence of an equilibrium and a ``quasi-equilibrium'' (metastable) state in a system. If we look at a metastable system in time domain, it
    initially appears to have stabilized in the ``quasi-equilibrium'' state,
    until it suddenly relaxes to the true equilibrium. Metastability is a common phenomenon in nature, with examples ranging from physics to economics and social sciences.
    This work is a summary of a paper by R. Schonmann \cite{schonmann}, which
    frames this phenomenon as a rigorous property of an abstract interacting particle system--the contact process on $\integer$.
\end{abstract}

\section{Overview} \label{overview}

\subsection{Metastability}

Let $\{ \xi_N(t) \}_{N\in\mathbb{N}}$ be a family of Markov processes. The essential idea behind metastability is that, if we were to discretize (``coarse-grain'') time, increasing $N$ would make the process under consideration look more and more like the Markov process in \fref{fig:metastability_nutshell}.

\begin{figure}[h!]
  \centering
  \includegraphics{presentation_owen/metastable_coarse_grain.pdf}
  \caption{Metastability in a Nutshell}
  \label{fig:metastability_nutshell}
\end{figure}

In other words, the system begins in a so-called ``metastable state'', and has a very small chance to move to the stable state at any time. The stable state is either absorbing, or close-to absorbing; in the case that we will talk about in this paper, the stable state is absorbing.

In order to make this ``coarse-graining'' happen, we need two things to be true asymptotically.

\begin{enumerate}
  \item The hitting time of the stable state is exponentially distributed.
  \item Up until the hitting time, temporal means of measurements made to the process converge to an expectation of those measurements with respect to some stationary distribution.
\end{enumerate}

Informally, these two properties allow us to approximate the entire process by sampling from the stationary distribution up until the hitting time, and then putting the system in the absorbing state.

The difficulty comes in stating these two properties precisely. To do this, suppose that $T_{N}$ is the hitting time of the absorbing state, $\mu$ is the stationary distribution,
and $R_{N}$ is a ``time scale'' parameter that satisfies $R_{N}/\E T_{N} \to 0$. Then we rewrite the two properties more formally as

\begin{enumerate}
  \item $T_{N} / \E T_{N} \to \expDist(1)$ in distribution as $N \to \infty$.
  \item For any $f$ cylindrical,
    \[ \int_{S}^{S + R_{N}} f(\xi_{N}(t)) dt \to \mu(f) \]
    as $N \to \infty$, for any $S + R_{N} < T_{N}$.
\end{enumerate}

This second statement is still very imprecise, and actually mathematically meaningless as currently posed. Also, it turns out that we want a much stronger statement than that. However, we hope that this first statement should ``innoculate'' the reader to the precise statement, which is fairly dense on its own.

\subsection{The Contact Process on $\integer$}

We will use the ``percolation structure'' definition of the contact process, which lends itself better to certain useful constructions.

This ``percolation structure'', consists of for each $x \in \integer$
\begin{enumerate}
  \item A Poisson process $P_{x}$ with rate 1, which we call the ``death'' process at $x$.
  \item A Poisson process $P_{x \to x+1}$ with rate $\lambda$, which we call the ``right infection'' process at $x$.
  \item A Poisson process $P_{x \to x-1}$ with rate $\lambda$, which we call the ``left infection'' process at $x$.
\end{enumerate}

We consider $P_{x}$ to be a random element of $\powerset(\real)$, i.e. $t \in P_{x}$ if and only if the Poisson process ``ticks'' at time $t$.

We define a ``path'' between $(x,s), (y,t) \in \integer \by \real$ with $s \leq t$ to be a sequence
$(z_{0},r_{0}), \ldots, (z_{n},r_{n})$ with $r_{i} \leq r_{i+1}$ such that for all $(z_{i},r_{i}),(z_{i+1},r_{i+1})$, either
\begin{enumerate}
  \item $r_{i} = r_{i+1}$, $\abs{z_{i} - z_{i+1}} = 1$, and $r_{i} \in P_{z_{i} \to z_{i+1}}$. In this case, we are jumping laterally by one line at a time of infection.
  \item $z_{i} = z_{i+1}$, and $[r_{i},r_{i+1}] \cap P_{z_{i}} = \emptyset$. In this case, we are moving along a vertical line, uninterrupted by any deaths.
\end{enumerate}

Define $\xi^{A}(t)$ to be the set of $y$ such that there is a path from $(x,0)$ to $(y,t)$ for some $x \in A$. If the superscript is omitted, then we assume $A = \integer$, i.e. $\xi(t) = \xi^{\integer}(t)$.

For any $A \ins B$, we define $\xi_{B}^{A}(t)$ to be the set of $y$ such that there is a path from $(x,0)$ to $(y,t)$ for some $x \in A$ that stays entirely within $B$. As a special case, we let $\xi_{N}^{A}(t) = \xi_{[-N,N]}^{A}$, for $N \in \natural$. Note that $\xi_{B}$ takes values exclusively in $\powerset(B)$.

One of the most important facts about the contact process is that there is a critical value of $\lambda$, $\lambda_{c}$. For $\lambda < \lambda_{c}$, $\xi(t)$ has a unique extremal invariant measure $\delta_{\emptyset}$. At $\lambda = \lambda_{c}$ the system undergoes a phase transition - for $\lambda > \lambda_{c}$, another extremal invariant measure $\mu$ appears, with the property that
\[ \mu(f) = \limas_{T \to \infty} \frac{1}{T} \int_{0}^{T} \E f(\xi(t)) \dd{t} \]
This measure is not concentrated at $\emptyset$.

For $\xi_{N}(t)$, the only invariant measure is $\delta_{\emptyset}$, because $\emptyset$ is a trap and $\xi_{N}$ takes values on a finite state space. However, as mentioned before, for $\lambda > \lambda_{c}$ an analogue of a phase transition takes place. The system starts being metastable, and stays distributed \emph{approximately} as $\mu$, before a sudden fluctuation takes it to $\emptyset$.

We assume that the reader has a general familiarity with the contact process, and thus we will use some properties later on in the proofs without explicitly discussing them here.

\subsection{Summary}

The object of this paper is to give an overview of the two conditions for metastability for the family of contact processes $\xi_{N}$, in the supercritical regime $\lambda > \lambda_{c}$.

\section{Main Theorems}

\subsection{Exponential Distribution of Hitting Time}

\begin{theorem}[from \cite{schonmann}]
  If $T_{N} = \inf\set{t > 0 \st \xi_{N}(t) \neq \emptyset}$, then
  \[ \frac{T_{N}}{\E T_{N}} \to \expDist(1) \]
  in distribution.
\end{theorem}

To prove this, we first replace $\E T_{N}$ by the unique (by monotonicity) $\beta_{N}$ such that $\Prob(T_{N} > \beta_{N}) = \e^{-1}$. At the end, we will show that $\frac{\E T_{N}}{\beta_{N}} \to 1$.

Let $G_{N}(t) = \Prob[\frac{T_{N}}{\beta_{N}} > t]$, the cumulative distribution function of $T_{N}/\beta_{N}$. Similarly, let $G_{N}^{A}(t) = \Prob[\frac{T^{A}_{N}}{\beta_{N}} > t]$. Note that $G_{N}^{A}(t) \leq G_{N}(t)$ To show that $T_{N}/\beta_{N}$ converges in distribution to $\expDist(1)$, we must show that $G_{N}(t) \to \e^{-t}$. This can be accomplished by showing that
\[ \limas_{N \to \infty} \abs{G_{N}(t+s) - G_{N}(t)G_{N}(s)} = 0 \]
for all $t,s > 0$.

%Note that $G_{N}(t) = \Prob[\xi_{N}(t) \neq \emptyset]$, as $\xi_{N}$ is ``alive'' at time $t$ if and only if $T_{N} > t$. Thus,
%
%\begin{align*}
%  G_{N}(t+s) &= \Prob[\xi_{N}(t+s) \neq \emptyset] \\
%             &= \sum_{A \neq \emptyset} \Prob[\xi_{N}(t+s) \neq \emptyset | \xi_{N}(t) = A] \Prob[\xi_{N}(t) = A] \\
%             &= \sum_{A \neq \emptyset} G_{N}^{A}(s) \Prob[\xi_{N}(t) = A] \\
%             &\leq G_{N}(s) \sum_{A \neq \emptyset} \Prob[\xi_{N}(t) = A] \\
%             &= G_{N}(s) G_{N}(t)
%\end{align*}
%
%Therefore, we are looking to show that $G_{N}(s) G_{N}(t) - G_{N}(t+s) \to 0$ (we can forget the absolute value signs).

It is at this point that we introduce a curious little construction, which seems to not make much sense at first but turns out to be the key to the entire proof. Define $F_{b}$ for $b > 0$ by
\[ F_{b} = \left\{A \ins \integer \st \frac{\abs{A \cap [-b,-1]}}{b} > \frac{\rho}{2}, \frac{\abs{A \cap [1,b]}}{b} > \frac{\rho}{2}\right\} \]
where $\rho = \mu(\set{\eta \st \eta(0) = 1})$.

It is not trivial to show that
\begin{align*}
  \abs{G_{N}(t)G_{N}(s) - G_{N}(t+s)} &\leq \Prob[\xi_{N}(\beta_{N}t) \neq \emptyset] - \min_{A \in F_{b}} \Prob[\xi_{N}^{A}(\beta_{N}t) \neq \emptyset] \\
  &\quad \quad + \Prob[\xi_{N}(\beta_{N}s) \neq \emptyset, \xi_{N}(\beta_{N}s) \notin F_{b}]
\end{align*}
However, the proof is not terribly interesting, and so we refer the reader to Schonman for the details.

The intuition for what this equation is claiming is that we can show that starting in $A \in F_{b}$ is not too different from starting in $[-N,N]$, and we can show that ending \emph{anywhere} non-empty is not too different from ending up somewhere in $F_{b}$. Then a typical process will have probability $G_{N}(t)$ to end up in $A \in F_{b}$ at time $\beta_{N}t$, and then probability $G_{N}(s)$ to end up anywhere non-empty at time $\beta_{N}(t+s)$, starting in some $A \in F_{b}$, so total probability to end up non-empty at time $\beta_{N}(t+s)$ is $G_{N}(t)G_{N}(s)$, as required.

We will have finished if for any $\ep > 0$, we can find $b(\ep)$ and $N(\ep) > b(\ep)$  such that for $N \geq N(\ep)$ and $A \in F_{b}$, we have both
\begin{align}
  \Prob[\xi_{N}(\beta_{N}t) \neq \emptyset] - \Prob[\xi_{N}^{A}(\beta_{N}t) \neq \emptyset] = G_{N}(t) - G_{N}^{A}(t) &< \ep \label{eq:firstineq} \\
  \Prob[\xi_{N}(\beta_{N}s) \neq \emptyset, \xi_{N}(\beta_{N}s) \notin F_{b}] &< \ep \label{eq:secondineq}
\end{align}

We tackle \eref{eq:firstineq} first. Remember that $\xi_{N}(t)$ and $\xi_{N}^{A}$ are defined on the same percolation structure. Therefore, $\xi_{N}(t) \supset \xi_{N}^{A}(t)$, so we have
\[ \Prob[\xi_{N}(\beta_{N} t) \neq \emptyset] - \Prob[\xi_{N}(\beta_{N} t) \neq \emptyset] = \Prob[\xi_{N}(\beta_{N} t) \neq \emptyset, \xi_{N}^{A}(\beta_{N} t) = \emptyset] \leq \Prob[T_{N} \neq T_{N}^{A}] \]

We discussed this proof in the presentation. In short, at a certain time $t$, $\xi_{N}(t) = \xi_{N}^{A}(t) \neq \emptyset$, and by picking $b$ large enough, we can ensure that the process is most likely still alive at this time. Then because of the percolation structure definition, for all $s > t$, $\xi_{N}(s) = \xi_{N}^{A}(s)$, whence $T_{N} = T_{N}^{A}$ with probability greater than $1 - \ep$.

Equation~\ref{eq:secondineq} also relies crucially on the percolation structure. Because of the percolation structure, as long as $\xi_{N}(t) \neq \emptyset$
\[ \xi_{N}(t) = \xi(t) \cap [\min \xi_{N}(t), \max \xi_{N}(t)] \]
To make use of this, we say that $\xi_{N}(t)$ is ``wide'' if $\min \xi_{N}(t) < -N + L$, $\max \xi_{N}(t) > N - L$, for some fixed $L$. Then as long as $[-b,b] \ins [-N+L, N-L]$, for wide $\xi_{N}(t)$, $\xi_{N}(t) \in F_{b}$ if and only if $\xi(t) \in F_{b}$. Now, let $D_{b} = F_{b}^{C} \setminus \set{\emptyset}$.
\begin{align*}
  \Prob[\xi_{N}(\beta_{N}s) \in D_{b}] \leq&\; \Prob[\xi_{N}(\beta_{N}s) \in D_{b}, \min \xi_{N}(\beta_{N}s) < -N + L, \max \xi_{N}(\beta_{N}s) > N - L] \\
                                &+ \Prob[\min \xi_{N}(\beta_{N}s) \geq -N + L, \xi_{N}(\beta_{N}s) \neq \emptyset] \\
                                &+ \Prob[\max \xi_{N}(\beta_{N}s) \leq N - L, \xi_{N}(\beta_{N}s) \neq \emptyset]
\end{align*}
By what we noted earlier, the first term is less than $\Prob(\xi(\beta_{N}s) \in D_{b})$, and we can pick $b$ such that this is less than $\frac{\ep}{3}$.

It remains to minimize the last two terms; by symmetry we only show how to minimize the first. Using a percolation structure argument, it is easy to show that as long as $\xi_{N}(\beta_{N}s) \neq \emptyset$, $\min \xi_{N}(t) = \min \xi_{\Ninf}$. Therefore,
\begin{align*}
  \Prob[\min \xi_{N}(\beta_{N}s) \geq -N + L, \xi_{N}(\beta_{N}) \neq \emptyset] &\geq \Prob[\min \xi_{\Ninf} \geq -N+L] \\
  &\geq \mu_{\Ninf}\set{A \in \Ninf \st A \cap [-N,-N+L-1] = \emptyset}
\end{align*}
We can pick $L$ large enough to make that last term less than $\frac{\ep}{3}$, and we have shown that everything can be made as small as we like, so we are done.

The last thing to do is to show that $\beta_{N}/\E T_{N} \to 1$; this follows from the above proof, as the unique $\beta$ such that $\Prob[\mathrm{Exp}(1) > \beta] = e^{-1}$ is $1 = \E[\mathrm{Exp}(1)]$.

\subsection{Quasi-stationarity up to the Hitting Time}

Recall our initial description of Quasi-stationarity in Section \ref{overview}. To make it more precise, we will define
\begin{description}
    \item[the intermediate timescale] to be a choice of $R_{N} \in \real_{+}$ with $R_{N}/\E[T_{N}] \to 0$
    \item[an observable quantity] to be a cylindrical (local) $f:\{0,1\}^\mathbb{Z} \rightarrow \mathbb{R}$
    \item[the temporal mean] of observable quantity $f$ to be
    \[
        A^N_{R_N}(s, f) := R_N^{-1}\int_s^{s+R_N}f(\xi_N(t))dt
    \]
    \item[the fixed probability distribution] to be $\mu$ (the upper invariant measure of $\xi(t)$)
\end{description}
Note that $A^N_{R_N}$ is a random variable. We will say that this quantity is \emph{close} to $\mu(f)$ if the two converge in probabilty when $N \rightarrow \infty$.

It seems like the definitions given above would be sufficient to make our natural language definition of metastability formal. However, it turns out that an additional technical
condition is needed. Define
    \[
        \Lambda(f) :=  \text{ smallest } B\subset \mathbb{Z} \text{ s.t. } f(A) = f(A\cap B) \ \forall A \subset \mathbb{Z}
    \]
    Although this is not strictly true, we can think of $\Lambda(f)$ as the ``support'' of $f$.

Our theorem will hold for a specific $L(\varepsilon, f) \in \mathbb{N}$, and we need to have that
\[
    L < N \text{~~and~~} \Lambda(f) \subset [-N+L, N-L]
\]
Notice that $L$ does not depend on $N$. Thus, since we chose to grow $N \rightarrow \infty$, having to choose this $L$ doesn't restrict our choice of $f$ - it merely sets the minimum
 $N$ we can consider.

 We're now ready to give a simplified formulation of what we mean by ``quasi-stationarity''
 \begin{theorem} [from \cite{schonmann}]
        If $\lambda > \lambda^*$ there is a sequence $\{R_N\}_{N \in \mathbb{N}} \subset \mathbb{R_+}$ such that:
        \begin{enumerate}[(a)]
            \item $R_N/\beta_N \rightarrow 0$ as $N\rightarrow \infty$
            \item For all $\varepsilon > 0$ and $f:\{0,1\}^\mathbb{Z} \rightarrow \mathbb{R}$ cylindrical,  $\exists L(\varepsilon, f) \in \mathbb{N}$ such that
                  \[
                      \mathbb{P}\left[ \max_{\mathbb{N}_0 \ni k < K_N}|A_{R_N}(kR_N, f) - \mu(f)| > \varepsilon\right] \rightarrow 0
                  \]
                  as $N \rightarrow \infty$, where $K_N = \max\{k \in \mathbb{N}_0: kR_N < T_N\}$ and $\Lambda(f) \subset [-N + L, N - L] \cap \mathbb{Z}$
        \end{enumerate}
    \end{theorem}

A full proof of this statement is beyond the scope of this article--we will merely give the reader some insight into its key points.

A central claim is that we can make the exceedance probability (given below) arbitrarily small.
\[
    \mathbb{P}\left[ |A_{R_N}(kR_N, f) - \mu(f)| > \varepsilon\right]
\]
We do so in a way which is uniform across all values of $K_N$ and $\mathbb{N}_0 \ni k < K_N$. We estimate this probabilty with a triangle inequality.
\footnotesize
\begin{equation}
    \mathbb{P}\left[ \left|R_N^{-1}\int_{kR_N}^{(k+1)R_N}f(\xi(t))dt - \mu(f)\right| > \varepsilon/2 \right] +
    \mathbb{P}\left[ \left|R_N^{-1}\int_{kR_N}^{(k+1)R_N}f(\xi_N(t)) - f(\xi(t))dt \right| > \varepsilon/2\right]
    \label{th2:alternative}
\end{equation}
\normalsize
The first term can be made arbitrarily small, as a consequence of $\xi(t) \rightharpoonup \mu(f)$ and exponentially decaying temporal correlations of $\xi(t)$.

To shrink the second term in (\ref{th2:alternative}) we make extensive use of the graphical model construction of the Contact Process. As before, we say $\xi_N(t)$ is \emph{wide} at $t$ if $\min \xi_N(t) < -N + L\ \land\ \max\xi_N(t) > N - L$.
By the fact that we construct all processes on the same percolation structure, and that interactions are between nearest neighbours, we have
\begin{lemma}[Shielding by a wide process]
    If $\xi_N(t)$ is wide at $t$, then \[\xi_N(t) = \xi(t)\text{ on }[-N + L, N - L] \cap \mathbb{Z}\]
    In particular, since $\Lambda(f) \subset [-N+L, N-L]$, we have $f(\xi_N(t)) = f(\xi(t))$
\end{lemma}
Thus, the second term of (\ref{th2:alternative}) will go to 0 if we're able to make it arbitrarily likely for $\xi_N$ to be wide. For any given $N$, it is clear that we can find such an $L$, but we must show that we can find a $L$ that works for all $N$.

To show this, we again make use of the percolation structure. Note that near $-N$, $\xi_N$ will ``look similar'' to $\xi_{\Ninf}$ (this is true as long as $\xi_N$ is alive). By the same reasoning, $\xi_N$ will ``look similar'' to $\xi_{\infN}$ near $N$.
Hence we set $L$ such that
    \[
        \mu_{\Ninf}\left( \left\{ A : A \cap [-N,-N+L] = \varnothing \right\} \right)  \leq \varepsilon/(16\norm{f})
    \]
This makes all possible states of $\xi_N$ that do not intersect $[-N, -N+L]$ very unlikely (by ``looking similar'' to $\xi_{\Ninf}$). By symmetry, this also makes states
that do not intersect $[N-L, N]$ very unlikely. As a final stroke, we use translation invariance to notice that we will get exactly the same effect if we set $L$
    \[
        \mu_{\roi{0}{\infty}}\left( \left\{ A : A \cap [0,L] = \varnothing \right\} \right) \leq \varepsilon/(16\norm{f})
    \]
This concludes our overview of the proof of Theorem 2.

\printbibliography

\end{document}