\section{Proofs for metatheory}
\label{sec:metatheory:proofs}

\begin{itemize}
\item
  For simplicity, we only consider terms in A-normal forms following the grammar:
  \begin{align*}
    e ::=~& \ldots \mid \aiapp{x}{x'} \mid \aipair{k}{x}{x'} \mid \aimatchin\etransfm{x,y}{z}{e}
  \end{align*}
  Typing and semantics rules are unchanged.
\item Borrow qualifiers  $\BQ ::= \IBORROW_n \mid \MBORROW_n$ where
  $n\ge0$ is a region level. A vector of borrow qualifiers $\Multi\BQ$
  is wellformed if all $\IBORROW$s come before all $\MBORROW$s in the vector.
\item Borrow compatibility
  $\Multi\BQ \Bcompatible \BQ$,
  \begin{mathpar}
  \inferrule{}{
    \BQ_n\Multi\BQ \Bcompatible \BQ_n
  }
  %
  % \inferrule{}{
  %   \MBORROW_n\Multi\MBORROW \Bcompatible \MBORROW_n
  % }
  \end{mathpar}
\item Store typing $ \vdash \Store : \SE$,
  \begin{mathpar}
    \inferrule{
      (\forall \Loc \in \Dom\Store)~~
      \SE \vdash \Store (\Loc) : \SE (\Loc)
    }{ \vdash \Store : \SE }
  \end{mathpar}
\item Relating storables to type schemes $\SE \vdash w : \schm$

  We write $\Disjoint\E$ for $\Active\VEnv$ and $\MutableBorrows\VEnv$
  and $\ImmutableBorrows\VEnv$ and $\Suspended\VEnv$ are all disjoint.
  \begin{mathpar}
  \inferrule{
    (\exists \E)~ \SE \vdash \VEnv : \E
    \\
    \Disjoint\E
    \\
    \inferS{C}{\E; \bvar x{\tau_2}}{e}{\tau_1}
    \\
    \Multi\tvar = \fv{\tau_1,\tau_2} \setminus \fv{\E}
  }{
    \SE \vdash (\VEnv, \ilam {\Multi\kvar}{\Multi\tvar}Ckx{e})
    : \forall\Multi\kvar\forall\Multi{\bvar{\tvar}{k}}.(\qual{C}{\tau_2\tarr{k}\tau_1})
  }
  \end{mathpar}
\item Relating storables to types $ \SE \vdash w : \tau$
  \begin{mathpar}
    \ruleStorableClosure

    \ruleStorablePair

    \ruleStorableResource

    \ruleStorableFreed
  \end{mathpar}
%\item Relating  results to types $ \SE \vdash r : \tau$,
\item Relating results to type schemes $\SE \vdash r : \schm$
  \begin{mathpar}
    \ruleResultConstant

    \ruleResultLocation

    \ruleResultBorrow
  \end{mathpar}
\item
We write $\Affine\SE\Loc$ to express that $\Loc$ points to a resource
that requires at least affine treatment. Borrow types do not appear in
store types as the store only knows about the actual resources.

Define  $\Affine\SE\Loc$ if one of the following cases holds:
\begin{itemize}
\item $\SE (\Loc) =
  \forall\Multi\kvar\forall\Multi{\bvar{\tvar}{k}}.(\qual{C}{\tau_2\tarr{k}\tau_1})$
  and $C \wedge (k \lk \kun_\infty)$ is contradictory;
\item $\SE (\Loc) = \tau_2\tarr{k}{\tau_1}$ and $\Cleq{\kaff}{k}$;
\item $\SE (\Loc) = \tyPair[k]{\tau_1}{\tau_2}$ and $\Cleq \kaff
  k$;
\item $\SE (\Loc) = \tapp{\tcon}{\Multi\tau}$.
% \item if $\SE (\Loc) = \borrow[\MBORROW]\tau$, then $\Loc$ is affine
%   \dots (THAT SHOULDN'T REALLY  BE A STORE TYPE)
% \item if $\SE (\Loc) = \borrow[\IBORROW]\tau$, then $\Loc$ is not affine
%   \dots (THAT SHOULDN'T REALLY  BE A STORE TYPE)
\end{itemize}
\item
We write $\Linear\SE\Loc$ to express that $\Loc$ points to a linear
resource.

Define  $\Linear\SE\Loc$ if one of the following cases holds:
\begin{itemize}
\item $\SE (\Loc) =
  \forall\Multi\kvar\forall\Multi{\bvar{\tvar}{k}}.(\qual{C}{\tau_2\tarr{k}\tau_1})$
  and $C \wedge (k \lk \kaff_\infty)$ is contradictory;
\item $\SE (\Loc) = \tau_2\tarr{k}{\tau_1}$ and $\Cleq{\klin}{k}$;
\item $\SE (\Loc) = \tyPair[k]{\tau_1}{\tau_2}$ and $\Cleq \klin
  k$;
\item $\SE (\Loc) = \tapp{\tcon}{\Multi\tau}$.
\end{itemize}
\item
It remains to characterize unrestricted resources.
Define $\Unrestricted\SE\Loc$ if neither $\Affine\SE\Loc$ nor
$\Linear\SE\Loc$ holds.
\item
  Relating environments to contexts\\
  $\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
\ImmutableBorrows\VEnv, \Suspended[\kaff]\VEnv, \Suspended[\kun]\VEnv : \E$.

Here we consider an
environment $\VEnv = (\Active\VEnv, \MutableBorrows\VEnv,
\ImmutableBorrows\VEnv, \Suspended\VEnv)$ as a tuple
consisting of the active entries in $\Active\VEnv$ and the
entries for exclusive borrows in $\MutableBorrows\VEnv$ and for
shared borrows in $\ImmutableBorrows\VEnv$, and suspended entries
in $\Suspended\VEnv = \Suspended[\kaff]\VEnv, \Suspended[\kun]\VEnv$
for affine and unrestricted entries. The
suspended entries cannot be used directly, but they can be activated
by appropriate borrowing on entry to a region.
\end{itemize}

\begin{mathpar}
  \inferrule{}{\SE \vdash \Sempty, \Sempty, \Sempty, \Sempty : \Eempty}
  \\
  \inferrule{
    \SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E
    \\ \SE \vdash r : \schm
    \\ \Linear\SE r}
  {\SE \vdash \Active\VEnv[ x\mapsto r], \MutableBorrows\VEnv ,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E;\bvar x\schm }

  \inferrule{
    \SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E
    \\ \SE \vdash r : \schm
    \\ \Affine\SE r}
  {\SE \vdash \Active\VEnv, \MutableBorrows\VEnv[ x\mapsto r] ,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E;\bvar x\schm }

  \inferrule{
    \SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E
    \\ \SE \vdash r : \schm
    \\ \Unrestricted\SE r}
  {\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv[ x\mapsto r], \Suspended\VEnv : \E;\bvar
    x\schm }

  \inferrule{\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended[\kaff]\VEnv, \Suspended[\kun]\VEnv : \E \\
    \SE \vdash r : \schm}
  { \SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended[\kaff]\VEnv, \Suspended[\kun]\VEnv[ x\mapsto r] :
    \E;\svar[\IBORROW] x\schm^n }

  \inferrule{\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended[\kaff]\VEnv, \Suspended[\kun]\VEnv : \E \\
    \SE \vdash r : \schm}
  { \SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended[\kaff]\VEnv[ x\mapsto r], \Suspended[\kun]\VEnv :
    \E;\svar[\MBORROW] x\schm^n }

  \inferrule{\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E \\ \SE \vdash
    \IBORROW\Addr : \schm}
  {\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv[ x\mapsto \IBORROW\Addr], \Suspended\VEnv :
    \E;\bbvar[\IBORROW] x k{ \schm} }

  \inferrule{\SE \vdash \Active\VEnv, \MutableBorrows\VEnv,
    \ImmutableBorrows\VEnv, \Suspended\VEnv : \E \\ \SE \vdash
    \MBORROW\Addr : \schm}
  {\SE \vdash \Active\VEnv, \MutableBorrows\VEnv[ x\mapsto \MBORROW\Addr],
    \ImmutableBorrows\VEnv, \Suspended\VEnv
    : \E;\bbvar[\MBORROW] x k{ \schm} }
\end{mathpar}
\paragraph{Extending environments and stores}
\begin{mathpar}
  \inferrule{}{\SE \le \SE}

  \inferrule{\SE \le \SE' \\ \Loc \notin \Dom\Store}{\SE \le \SE' (\Loc : \schm)}
\\
  \inferrule{}{\Store\le\Store}

  \inferrule{\Store \le \Store' \\ \Loc \notin \Dom\Store
  }{\Store \le \Store'[ \Loc \mapsto w] }
\end{mathpar}

\begin{lemma}[Store Weakening]\label{lemma:store-weakening}
  $\SE \vdash \VEnv : \E$ and $\SE \le \SE'$ implies $\SE' \vdash
  \VEnv : \E$.
\end{lemma}

\begin{lemma}[Store Extension]\label{lemma:store-extension-transitive}
  \begin{itemize}
  \item If $\SE_1 \le \SE_2$ and $\SE_2 \le \SE_3$, then $\SE_1 \le
    \SE_3$.
  \item If $\Store_1 \le \Store_2$ and $\Store_2 \le \Store_3$, then
    $\Store_1 \le \Store_3$.
  \end{itemize}
\end{lemma}

We write $\Rawloc\cdot$ for the function that extracts a multiset of
\emph{raw locations} from a result or from the range of the variable
environment.

\begin{align*}
  \Rawloc{\Multi\BQ\Loc} &= \{\Loc\} \\
  \Rawloc{c} &= \{ \} \\
  \Rawloc\Eempty &= \{\} \\
  \Rawloc{\VEnv( x \mapsto r)} &= \Rawloc\VEnv \cup \Rawloc r
\end{align*}

We write $\Reach\Store\VEnv$ for the multiset of all \emph{addresses}
reachable from $\Rawloc\VEnv$
assuming that $\Rawloc\VEnv \subseteq \Dom\Store$\footnote{In
  mixed comparisons between a multiset and a set, we tacitly convert
  a multiset $M$ to its supporting set $\{ x \mid \MultiNumber x M \ne 0\}$.}.
The function $\Reach\Store\cdot$ is defined in
two steps. First a helper function
for results, storables, and environments.

\begin{align*}
  \RS\Store\Eempty &= \Eempty \\
  \RS\Store{\VEnv (x \mapsto r)} &= \RS\Store\VEnv \cup
                                      \RS\Store r \\
  \RS\Store\Addr &= \{ \Addr \}  \\
  \RS\Store c &= \{ \} \\
  \RS\Store{\StPClosure \VEnv {\Multi\kvar} C k x e} &=
                                       \RS\Store\VEnv
  \\
  \RS\Store{\StClosure \VEnv k x e} &=
                                                   \RS\Store\VEnv
  \\
  \RS\Store{\StPair k {r_1} {r_2}} &=
                                                   \RS\Store{r_1}
                                                   \cup \RS\Store{r_2}
  \\
  \RS\Store{\StRes r} &=
                                   \RS\Store r
  \\
  \RS\Store{\StFreed} &= \{ \}
\end{align*}

This multiset is closed transitively by store lookup. We define
$\Reach\Store\VEnv$ as the smallest multiset $\REACH$ that fulfills
the following inequations. We assume a nonstandard
model of multisets such that an element $\Loc$ may occur infinitely often as in
$\MultiNumber\Loc\REACH = \infty$.
\begin{align*}
  \REACH &\supseteq \RS\Store\VEnv \\
  \REACH &\supseteq \RS\Store w & \text{if }
                                     \Multi\BQ\Loc
                                     \in \REACH \wedge w = \Store (\Loc)
\end{align*}

\begin{definition}[Wellformed permission]
  A permission $\Perm$ is \emph{wellformed} if it contains at most one
  address for each raw location.
\end{definition}
\begin{definition}[Permission closure]
  The closure of a permission $\Sclos\Perm$ is the set of addresses
  reachable from $\Perm$ by stripping an arbitrary number of borrows
  from it. It is the homomorphic extension of the closure
  $\Sclos\Addr$ for a single address.
  \begin{align*}
    \Sclos\Loc & = \{ \Loc \} & \Sclos{(\BQ\Addr)} & = \{ \BQ\Addr \}  \cup \Sclos\Addr
  \end{align*}
\end{definition}

\begin{lemma}[Containment]\label{lemma:containment}
  Suppose that $\vdash \Store : \SE$,
  $\SE \vdash r : \tau$, $\entail C
  {\Cleq{\tau}{k} \Cand \Cleq{k}{\klin_{m-1}}}$.
  Then $\Reach\Store r$ cannot contain addresses $\Addr$ such that
  $\Addr = \BORROW_n\Addr'$ with $n\ge m$.
\end{lemma}
\begin{proof}
  By inversion of result typing there are three cases.

  \textbf{Case }$\ruleResultConstant$. Immediate: reachable set
  is empty.

  \textbf{Case }$\ruleResultBorrow$. The typing constraint enforces
  that $n < m$.

  \textbf{Case }$\ruleResultLocation$. We need to continue by
  dereferencing $\Loc$ and inverting store typing.

  \textbf{Case }$\ruleStorableFreed$. Trivial.

  \textbf{Case }$\ruleStorableResource$. We assume the implementation
  type of a result to be unrestricted.

  \textbf{Case }$\ruleStorablePair$.

  The typing constraint yields that $k \le \klin_{m-1}$.
  By induction and transitivity of $\le$, we find that
  $\Reach\Store{r_1}$ and $\Reach\Store{r_2}$ cannot contain offending addresses.

  \textbf{Case }$\ruleStorableClosure$.

  The typing constraint yields that $k\le\klin_{m-1}$.
  By transitivity of $\le$ and $\SE \vdash \VEnv:\E$, we find that the
  types of all addresses in
  $\VEnv$ have types bounded by $\klin_{m-1}$ and, by induction, they
  cannot contain offending addresses.
\end{proof}
\clearpage{}
\lstMakeShortInline[keepspaces,style=rule]@

\SoundnessThm

Some explanations are in order for the resource-related assumptions
and statements.

Incoming resources are always active (i.e., not freed).
Linear and affine resources as well as suspended affine borrows have
exactly one pointer in the environment.

The Frame condition states that only store locations reachable from
the current environment can change and that all permissions outside
the reachable locations remain the same.

Unrestricted values, resources, and borrows do not change their
underlying resource and do not spend their permission.

Affine borrows and resources may or may not spend their
permission. Borrows are not freed, but resources may be freed. The
permissions for suspended entries remain intact.

% Incoming suspended borrows have no permission attached to them and
% their permission has been retracted on exit of their region.

A linear resource is always freed.

Outgoing permissions are either inherited from the caller or they
refer to newly created values.

\newpage
\begin{proof}
  By induction on the evaluation of
  @eval \Store \Perm \VEnv i e@.

  The base case is trivial as
  @eval \Store \Perm \VEnv 0 e = \TimeOut@.

  For $i>0$ consider the different cases for expressions. For lack of
  spacetime, we only give details on some important cases.

  \textbf{Case $e$ of}
  \lstsemrule{slet}
  We need to invert rule \TirName{Let} for monomorphic let:
  \begin{gather*}
    \ruleSDILet
    % \ruleSDLet
  \end{gather*}
  %% PJT: separate lemma about splitting needed
  As $\Sp$ is the evidence for the splitting judgment and @vsplit@
  distributes values according to $\Sp$, we obtain
  \begin{gather}
    \label{eq:16}
    \SE \vdash \VEnv_1 : \E_1
    \\\label{eq:17}
    \SE \vdash \VEnv_2 : \E_2
  \end{gather}
  Moreover (using $\uplus$ for disjoint union),
  \begin{itemize}
  \item $\Active\VEnv = \Active{\VEnv_1} \uplus\Active{\VEnv_2}$,
  \item $\MutableBorrows\VEnv = \MutableBorrows{\VEnv_1} \uplus
    \MutableBorrows{\VEnv_2}$,
  \item $\ImmutableBorrows\VEnv =
    \ImmutableBorrows{\VEnv_1} = \ImmutableBorrows{\VEnv_2}$,
  \item $\Suspended\VEnv = \Suspended{\VEnv_1} \uplus
    \Suspended{\VEnv_2}$ (this splitting does not distinguish potentially
    unrestricted or affine bindings)
  \end{itemize}
  We establish the assumptions for the call
  @eval \Store \Perm \VEnv_1  i' e_1@.
  \begin{enumerate}[({A1-}1)]
  \item From inversion: $\inferS{C \Cand D}{\E_1}{e_1}{\tau_1} $
  \item From~\eqref{eq:16}: $\SE \vdash \VEnv_1 : \E_1$
  \item From assumption
  \item From assumption
  \item From assumption because $\VEnv_1$ is projected from $\VEnv$.
  \item From assumption because $\VEnv_1$ is projected from $\VEnv$.
  \item From assumption because $\VEnv_1$ is projected from $\VEnv$.
  \end{enumerate}
  Hence, we can apply the induction hypothesis and obtain
  \begin{enumerate}[({R1-}1)]
  \item \resultOk{}{_1}
  \item\label{item:8} \resultEnv{}{_1}
  \item\label{item:9} $\SE_1 \vdash r_1 : \tau_1$
  \item\label{item:14} \resultPermDom{}{_1}
  \item\label{item:13} \resultReachPerm{}{_1}
  \item\label{item:16} \resultFrame{}{_1}{_1}
  \item\label{item:24} \resultImmutables{}{}{_1}
  \item\label{item:26} \resultMutables{}{}{_1}
  % \item\label{item:28} \resultSuspended{}{}{_1}
  \item\label{item:30} \resultResources{}{}{_1}
  \item\label{item:10} \resultThinAir{}{_1}
  \end{enumerate}
  To establish the assumptions for the call \\
  @eval delta_1 pi_1 gamma_2(x-:>r_1) i' e_2@,
  we write $\VEnv_2' = \VEnv (x \mapsto r_1)$.
  \begin{enumerate}[({A2-}1)]
  \item From inversion: $\inferS{C}{\E;\bvar{x}{\tau_1}}{e_2}{\tau_2}$
  \item From~\eqref{eq:17} we have $\SE \vdash \VEnv_2 : \E_2$.
    By store weakening (Lemma~\ref{lemma:store-weakening}) and
    using~\ref{item:8}, we have
    $\SE_1 \vdash \VEnv_2 : \E_2$.
    With~\ref{item:9}, we obtain
    $\SE_1 \vdash \VEnv_2 (x \mapsto r_1 ) : \E_2;\bvar x {\tau_1}$.
  \item Immediate from~\ref{item:8}.
  \item Immediate from~\ref{item:14}.
  \item Show \assumeReachable{_1}{'_2}\\
    % $\Reach{\Store_1}{\Active{\VEnv_2'}, \MutableBorrows{\VEnv_2'},
    %   \ImmutableBorrows{\VEnv_2'}} \subseteq \Perm_1$ \\
    From~\ref{item:12}, we have
    \assumeReachable{_1}{_2}
    % $\Reach{\Store_1}{\Active{\VEnv_2}, \MutableBorrows{\VEnv_2},
    %   \ImmutableBorrows{\VEnv_2}} \subseteq \Perm_1$.
    The extra
    binding $(x \mapsto r_1)$ goes into one of the compartments
    according to its type. We conclude by~\ref{item:13}.
  \item Disjointness holds by assumption for $\VEnv_2$ and it remains
    to discuss $r_1$. But $r_1$ is either a fresh resource, a
    linear/affine resource from $\VEnv_1$ (which is disjoint), or
    unrestricted. In each case, there is no overlap with another
    compartment of the environment.
  \item We need to show
    \assumeIncoming{_1}{_2'}
    The first item holds by assumption, splitting, and (for $r_1$)
    by~\ref{item:14} and~\ref{item:13}.

    The second and third items hold by assumption~\ref{item:15},
    splitting, and framing~\ref{item:16}.
  \end{enumerate}
  Hence, we can apply the induction hypothesis and obtain
  \begin{enumerate}[({R2}-1)]
  \item\label{item:17} \resultOk{_1}{_2}
  \item\label{item:18} \resultEnv{_1}{_2}
  \item\label{item:19} $\SE_2 \vdash r_2 : \tau_2$
  \item\label{item:20} \resultPermDom{_1}{_2}
  \item\label{item:21} \resultReachPerm{_1}{_2}
  \item\label{item:22} \resultFrame{_1}{_2'}{_2}
  \item\label{item:23} \resultImmutables{_1}{_2'}{_2}
  \item\label{item:25} \resultMutables{_1}{_2'}{_2}
  % \item\label{item:27} \resultSuspended{_1}{_2'}{_2}
  \item\label{item:29} \resultResources{_1}{_2'}{_2}
  \item\label{item:31} \resultThinAir{_1}{_2}
  \end{enumerate}

  It remains to establish the assertions for the let expression.
  \begin{enumerate}[({R}-1)]
  \item \resultOk{_1}{_2}
    \\ Immediate from~\ref{item:17}.
  \item \resultEnv{}{_2}
    \\ Transitivity of store extension
    (Lemma~\ref{lemma:store-extension-transitive}), \ref{item:18},
    and~\ref{item:8}.
  \item  $\SE_2 \vdash r_2 : \tau_2$
    \\ Immediate from~\ref{item:19}.
  \item \resultPermDom{}{_2}
    \\ Immediate from~\ref{item:20}.
  \item \resultReachPerm{}{_2}
    \\ Immediate from~\ref{item:21}
    %% \textcolor{red}
    {because $\Reach{\Store_2}{\VEnv_1}
    \subseteq \Reach{\Store_2}{\VEnv} $ and
    $\Reach{\Store_2}{\Suspended{\VEnv_1}} \subseteq
    \Reach{\Store_2}{\Suspended\VEnv}$.
    Moreover, $\Dom\Store \subseteq \Dom{\Store_1}$.
  }
\item \resultFrame{}{}{_2}
    ~\\ Suppose that $\Loc \in \Dom\Store \setminus
    \Rawloc{\Reach{\Store_2}{\VEnv}}$.
    \\ Then $\Loc \in \Dom\Store \setminus
    \Rawloc{\Reach{\Store_1}{\VEnv_1}}$.
    \\ By~\ref{item:16}, $\Store_1 (\Loc) = \Store (\Loc)$ and for any
    $\Addr$ with $\Rawloc\Addr = \{\Loc\}$: $\Addr \in \Perm
    \Leftrightarrow \Addr \in \Perm_1$.
    \\ But also $\Loc \in \Dom{\Store_1} \setminus
    \Rawloc{\Reach{\Store_2}{\VEnv_2'}}$.
    \\ By~\ref{item:22}, $\Store_2 (\Loc) = \Store_1 (\Loc)$ for
    applicable $\Addr$, $\Addr \in \Perm_1
    \Leftrightarrow \Addr \in \Perm_2$.
    \\ Taken together, we obtain the claim.
  \item \resultImmutables{}{}{_2}
    \\ Follows from~\ref{item:23} or~\ref{item:24} because
    $\ImmutableBorrows\VEnv = \ImmutableBorrows{\VEnv_1} =
    \ImmutableBorrows{\VEnv_2}$.
  \item \resultMutables{}{}{_2}
    \\ Follows from~\ref{item:25},~\ref{item:26}, and framing.
  % \item \resultSuspended{}{}{_2}
  %   ~\\ Follows from~\ref{item:27},~\ref{item:28}, and framing.
  \item \resultResources{}{}{_2}
    \\ Follows from disjoint splitting of
    $\Active\VEnv$,~\ref{item:29},~\ref{item:30}, and framing.
  \item \resultThinAir{}{_2}
    \\ Immediate from~\ref{item:31}.
  \end{enumerate}

  \newpage{}
  \textbf{Case $e$ of}
  \lstsemrule{sappanf}

  We need to invert rule \TirName{App}:
  \begin{mathpar}
    \ruleSDAIApp
    %\ruleSDVApp
  \end{mathpar}

  We need to establish the assumptions for the recursive call
  @eval \Store' \Perm' \VEnv'(x'-:>r_2) i' e'@.
  We write $\VEnv_2' = \VEnv' (x'\mapsto r_2)$.
  \begin{enumerate}[({A1-}1)]
  \item $\inferS{C'}{\E'; \bvar{x'}{\tau_2}}{e'}{\tau_1}$, for some
    $C'$ and $\E'$\\
    Applying the first premise of \TirName{App} to $r_1 = \VEnv
    (x_1)$, $\SE \vdash \VEnv : \E$, and inversion of result typing
    yields that $r_1 = \Loc_1$ with $\SE (\Loc_1) = \tau_2 \tarr{k}
    \tau_1$.
    By inversion of store typing and storable typing, we find that
    there exist $\E'$ and $C'$ such that
    \begin{enumerate}
    \item $\Store (\Loc_1) = (\VEnv', \lam[k]{x'}{e'})$
    \item $\Disjoint{\E'}$
    \item\label{item:32} $\SE \vdash \VEnv', \E'$
    \item $\inferS{C'}{\E';\bvar {x'}{\tau_2}}{e'}{\tau_1}$
    \item $\addlin{\entail{C'}{\Cleq{\E'}{k}}}$
    \end{enumerate}
  \item $\SE \vdash \VEnv' (x' \mapsto r_2) : \E';
    \bvar{x'}{\tau_2}$\\
    By~\ref{item:32}, assumption on $\VEnv$, and the subtyping premise.
  \item $\vdash \Store' : \SE'$ \\
    by assumption and the released rule of store typing (where we
    write $\SE'=\SE$ henceforth)
  \item \assumeWellformed{'} \\
    the possible removal of a permission does not violate
    wellformedness; the permission is taken away exactly when the
    closure is destroyed
  \item
    \assumeReachable{}{'_2} \\
    as the reach set is a subset of the incoming environment's reach
  \item $\Rawloc{\Active{\VEnv_2'}}$,
    $\Rawloc{\MutableBorrows{\VEnv_2'}}$,
    $\Rawloc{\ImmutableBorrows{\VEnv_2'}}$, and
    $\Rawloc{\Suspended{\VEnv_2'}}$ are all disjoint follows from
    $\Disjoint{\E'}$ and since $r_2= \E (x_2)$ which is an entry
    disjoint from the closure $\E(x_1)$.
  \item \assumeIncoming{'}{_2'}
    The first item holds because of assumption~\ref{item:15}.

    The second item holds because $\REACH' \subseteq \REACH$ from
    assumption~\ref{item:15}.
  \end{enumerate}
  The inductive hypothesis yields that
    $\exists$ $\Store_3$, $\Perm_3$, $r_3$, $\SE_3$ such that
  \begin{enumerate}[({R1-}1)]
  \item \resultOk{}{_3}
  \item \resultEnv{'}{_3}
  \item $\SE_3 \vdash r_3 : \tau_1$
  \item \resultPermDom{}{_3}
  \item \resultReachPerm{}{_3}
  \item \resultFrame{'}{_2'}{_3}
  \item \resultImmutables{'}{_2'}{_3}
  \item \resultMutables{'}{_2'}{_3}
    % \item \resultSuspended{}{}{'}
  \item \resultResources{'}{_2'}{_3}
  \item \resultThinAir{'}{_3}
  \end{enumerate}
  The desired results are immediate because $\Dom\Store = \Dom{\Store'}$.

  \newpage{}
  \textbf{Case $e$ of}
  \lstsemrule{sregion}

  We need to invert rule \TirName{Region}
  \begin{mathpar}
    \ruleSDRegion
  \end{mathpar}

  We need to establish the assumptions for the recursive call
  @eval \Store \Perm' \VEnv' i' e'@ where  $\VEnv' =
  \VEnv (x\mapsto \Addr')$.

  \begin{enumerate}[({A1-}1)]
  \item $\inferS{C}{\E'}{e}{\tau}$ \\
    immediate from the inverted premise
  \item $\SE \vdash \VEnv' : \E'$ \\
    the only change of the environments is at $x$; adding the borrow
    modifier $\BORROW$ succeeds due to the second premise; the address $\Addr'$
    stored into $x$ is compatible with its type by store typing
  \item $\vdash \Store : \SE$ \\
    Immediate by outer assumption
  \item\label{item:11} \assumeWellformed{} \\
    Immediate by outer assumption; adding the modifier does not change
    the underlying raw location
  \item\label{item:12}
    \assumeReachable{}{'} \\
    locations were swapped simultaneously
    %% this may not work because the pair's components do not change
    %% their permissions
  \item $\Rawloc{\Active{\VEnv'}}$,
    $\Rawloc{\MutableBorrows{\VEnv'}}$,
    $\Rawloc{\ImmutableBorrows{\VEnv'}}$, and
    $\Rawloc{\Suspended{\VEnv'}}$ are all disjoint \\
    Immediate by assumption
  % \item  $\VEnv'$ with $\Rawloc{\VEnv'}
  %   \subseteq \Dom\Store$ and $\Dom\VEnv \cap \Dom{\VEnv'}=\emptyset$
  \item\label{item:15} \assumeIncoming{}{'}
    Immediate by assumption.
  \end{enumerate}

  The induction hypothesis yields the following statements.
  $\exists$ $\Store_1$, $\Perm_1$, $r_1$, $\SE_1$ such that
  \begin{enumerate}[({R1-}1)]
  \item \resultOk{}{_1}
  \item \resultEnv{}{_1}
  \item $\SE_1 \vdash r_1 : \tau$
  \item \resultPermDom{}{_1}
  \item \resultReachPerm{}{_1}
  \item \resultFrame{}{'}{_1}
  \item \resultImmutables{}{'}{_1}
  \item \resultMutables{}{'}{_1}
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{'}{_1}
  \item \resultThinAir{}{_1}
  \end{enumerate}

  It remains to derive the induction hypothesis in the last line. The
  only additional action is the exchange of permissions which
  withdraws the borrow.
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{_1}\\
    Immediate
  \item \resultEnv{}{_1}\\
    Immediate
  \item $\SE_1 \vdash r_1 : \tau$\\
    Immediate
  \item \resultPermDom{}{_1} \\
    The addresses $\Addr$ and $\Addr'$ (as well as the elements of
    $\Perm'$ and $\Perm''$) have the same raw location, so
    exchanging them does not affect wellformedness. The underlying set
    of locations does not change.
  \item \resultReachPerm{}{_1} \\
    This case is critical for region encapsulation. Here we need to
    argue that $\Addr'$ (and hence $\Perm''$) is not reachable from $r_1$ because its type
    $\tau$ is bounded by $\klin_{n-1}$ according to the fourth
    premise. We conclude with Lemma~\ref{lemma:containment}.
    %%% need lemma
  \item \resultFrame{}{'}{_1}
    Immediate
  \item \resultImmutables{}{'}{_1} \\
    Immediate
  \item \resultMutables{}{'}{_1} \\
    Immediate
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{'}{_1} \\
    Immediate
  \item \resultThinAir{}{_1} \\
    Immediate
  \end{enumerate}

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \newpage{}
  \textbf{Case $e$ of}
  \lstsemrule{screateanf}

  We need to invert the corresponding rule
  \begin{mathpar}
    \ruleSDCreate
  \end{mathpar}

  It is sufficient to show that there is some $\SE_1 = \SE(\Loc_1 :
  \tapp\tres\tau)$ such that
  $\Store_1$, $\Perm_1$, and $r_1 = \Loc_1$ fulfill the following requirements.
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{_1}
  \item \resultEnv{}{_1} \\
    For the last item, we need to show that $\SE (\Loc_1) :
    \tapp\tres\tau$, but this follows from the setting of $w$ to a
    resource storable in the semantics.
  \item $\SE_1 \vdash r_1 : \tapp\tres\tau$ \\
    Immediate from the discussion of the preceding case
  \item \resultPermDom{}{_1} \\
    Follows from the assumption on $\Perm$ and for $\Loc_1$ from the
    allocation of the resource.
  \item \resultReachPerm{}{_1} \\
    Immediate from the assignment to $\Perm_1$.
  \item \resultFrame{}{}{_1}
    Obvious as no existing location is changed.
  \item \resultImmutables{}{}{_1} \\
    Obvious as no existing location has changed and no permission is withdrawn.
  \item \resultMutables{}{}{_1} \\
    Obvious as no existing location has changed and no permission is
    withdrawn.
    % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{_1} \\
    By the constraint on $\E$ in the \TirName{Create} rule, $\Active\VEnv = \emptyset$.
  \item \resultThinAir{}{_1} \\
    Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{sdestroyanf}

  We need to invert rule \TirName{Destroy}.
  \begin{mathpar}
    \ruleSDDestroy
  \end{mathpar}
  It is sufficient to show that $\SE_1 = \SE$,
  $\Store_1$, $\Perm_1$, and $r_1 = ()$ fulfill the following
  requirements.
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{_1}
  \item \resultEnv{}{_1} \\
    Immediate: $\Loc$ was updated to void, which has any type.
  \item $\SE_1 \vdash () : \tunit$
  \item \resultPermDom{}{_1}\\
    By assumption on $\Perm$ and because $\Loc$ was removed.
  \item \resultReachPerm{}{_1} \\
    Immediate because the reach set is empty
  \item \resultFrame{}{}{_1}
    Only $\Store (\Loc)$ was changed, which is not reachable from the frame.
  \item \resultImmutables{}{}{_1} \\
    Immediate because we updated (destroyed) a resource (in $\Active\VEnv$).
  \item \resultMutables{}{}{_1} \\
    Immediate because we updated (destroyed) a resource (in $\Active\VEnv$).
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{_1} \\
    By the constraint on $\E$, $\Loc$ was the only resource passed to
    this invocation of eval. The claimed condition holds as $\Loc$ was
    removed from $\Perm_1$ and the location's contents cleared.
  \item \resultThinAir{}{_1}
    \\ Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{var}

  We need to invert rule \TirName{Var}.
  \begin{mathpar}
    \ruleSDIVar
  \end{mathpar}

  We establish that the claims hold for
  $\Store' = \Store$, $\Perm' = \Perm$, $r = \VEnv (x)$, and $\SE' = \SE$.
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{}
  \item \resultEnv{}{}
    \\ Immediate by reflexivity and assumption.
  \item $\SE \vdash r : \tau$
    \\ Immediate by assumption~\ref{item:32}.
  \item \resultPermDom{}{}
    \\ Immediate by assumption~\ref{item:11}
  \item \resultReachPerm{}{}
    \\ Immediate
  \item \resultFrame{}{}{}
    Immediate as permissions and store stay the same.
  \item \resultImmutables{}{}{}
    \\ Immediate
  \item \resultMutables{}{}{}
    \\Immediate
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{}
    \\ As $\Perm$ remains the same, a linear resource in $x$ is
    returned untouched.
  \item \resultThinAir{}{}
    \\ Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{const}

  We need to invert rule \TirName{Const}.
  \begin{mathpar}
    \ruleSDConst
  \end{mathpar}

  We need to establish the claims for $\Store' = \Store$,
  $\Perm'=\Perm$, $r' = c$, and $\SE' = \SE$:
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{}
  \item \resultEnv{}{} \\
    By assumption~\ref{item:33}.
  \item $\SE \vdash c : \CType c$
    \\by result typing.
  \item \resultPermDom{}{}
    \\ By assumption~\ref{item:11}.
  \item \resultReachPerm{}{}
    \\ As $\Reach\Store c = \emptyset$.
  \item \resultFrame{}{}{}
    Immediate
  \item \resultImmutables{}{}{}
    \\ Immediate
  \item \resultMutables{}{}{}
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{}
    \\ Immediate as $\Active\VEnv = \emptyset$.
  \item \resultThinAir{}{}
    \\ Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{spairanf}

  We need to invert rule \TirName{Pair}.
  \begin{mathpar}
    \ruleSDAIPair
  \end{mathpar}
  Show that $\Store'$, $\Perm'$, $r' = \Loc'$, $\SE' = \SE (\Loc' : \tyPair[k]{\tau_1}{\tau_2})$ such that
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{'}
  \item \resultEnv{}{'}
  \item $\SE' \vdash \Loc' : \tyPair{\tau_1}{\tau_2}$
  \item \resultPermDom{}{'}
    \\ By assumption~\ref{item:11} and because $\Loc'$ is properly initialized.
  \item \resultReachPerm{}{'}
    \\ By assumption~\ref{item:12}, $\Reach{\Store'}{\Loc'} =
    \Reach\Store{r_1, r_2} \cup \{\Loc'\} \subseteq
    \Reach{\Store}\VEnv \cup \{\Loc'\}$ and $\{\Loc'\} = \Dom{\Store'}
    \setminus \Dom\Store$.
  \item \resultFrame{}{}{'}
    Immediate
  \item \resultImmutables{}{}{'}
    \\ Immediate
  \item \resultMutables{}{}{'}
    \\ Immediate
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'}
    \\ Every such $\Loc$ must be reachable either from $r_1$ or
    $r_2$. So they become reachable from $\Loc'$, as required.
  \item \resultThinAir{}{'}
    \\ Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{lam}

  We need to invert rule \TirName{Abs}
  \begin{mathpar}
    \ruleSDLam
  \end{mathpar}

  Show that $\Store'$, $\Perm'$, $r' = \Loc'$, and $\SE' = \SE (\Loc'
  : \tau_2\tarr{k}\tau_1)$ fulfill
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{'}
  \item \resultEnv{}{'} \\
    Immediate by definition and store typing
  \item $\SE' \vdash r' : \tau_2\tarr{k}\tau_1$ \\
    Immediate by store typing
  \item \resultPermDom{}{'} \\
    Wellformedness holds by assumption on $\Perm$ and because $\Loc'$ is a new location.
    The domain constraint is assumed for $\Perm$ and $\Loc'$ is
    initialized to a  closure.
  \item \resultReachPerm{}{'}
    \begin{align*}
      \Reach{\Store'}{r'} & = \{ \Loc' \} \cup \Reach{\Store'}{\VEnv} \\
      &= \Dom{\Store'}\setminus\Dom\Store \cup \Reach{\Store'}{\VEnv}
    \end{align*}
    Moreover, the constraint ${\Cleq{\E}{k}}$ implies that
    $\Suspended\VEnv = \emptyset$.
  \item \resultFrame{}{}{'}
    Immediate
  \item \resultImmutables{}{}{'}   \\
    Immediate
  \item \resultMutables{}{}{'} \\
    Immediate
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'} \\
    The second case is immediately applicable.
  \item \resultThinAir{}{'} \\
    Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{sborrow}

  We have to invert rule \TirName{Borrow}
  \begin{mathpar}
    \ruleSDBorrow
  \end{mathpar}

  Show that $\Store' = \Store$, $\Perm' = \Perm$, $r' = \Addr$, $\SE'
  = \SE$ such that
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{'}
  \item \resultEnv{}{'} \\
    Immediate, no changes.
  \item $\SE' \vdash r' : \borrowty{k}{\tau}$\\
    Immediate by result typing and because the interpreter checks that
    the permissions of the borrow are very restricted.
  \item \resultPermDom{}{'}\\
    Immediate (no change).
  \item \resultReachPerm{}{'} \\
    By typing, $\Addr$ is not in $\Suspended\VEnv$.
    Hence,  the condition is immediate.
  \item \resultFrame{}{}{'}
    Immediate as no change.
  \item \resultImmutables{}{}{'}\\
    Immediate as no change
  \item \resultMutables{}{}{'} \\
    Immediate
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'} \\
    Immediate because $\REACH$, $\REACH'$ must be empty
  \item \resultThinAir{}{'}\\
    Immediate.
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{sobserveanf}

  We have to invert the rule \TirName{Observe}
  \begin{mathpar}
    \ruleSDObserve
  \end{mathpar}
  Show that $\Store' = \Store$, $\Perm' = \Perm$, $r'$, and $\SE' =
  \SE$ fulfill
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{'}
  \item \resultEnv{}{'} \\
    By reflexivity and assumption.
  \item $\SE' \vdash r' : \tau$ \\
    Immediate by store typing
  \item \resultPermDom{}{'} \\
    Immediate: no changes.
  \item \resultReachPerm{}{'} \\
    Immediate
  \item \resultFrame{}{}{'}
    Immediate: no changes.
  \item \resultImmutables{}{}{'} \\
    Immediate: no changes to immutables.
  \item \resultMutables{}{}{'}  \\
    Immediate: one particular $\Addr$ is overwritten, but not freed.
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'} \\
    Immediate because $\REACH = \emptyset$
  \item \resultThinAir{}{'} \\
    Immediate
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{supdateanf}

  We need to invert rule \TirName{Update}
  \begin{mathpar}
    \ruleSDUpdate
  \end{mathpar}

  We need to show that $\Store'$, $\Perm'$, $r' = ()$, $\SE' = \SE$ fulfill
  \begin{enumerate}[({R}1)]
  \item \resultOk{}{'}
  \item \resultEnv{}{'} \\
    Immediate by store typing for $\Loc$
  \item $\SE' \vdash r' : \tunit$ \\
    Immediate
  \item \resultPermDom{}{'} \\
    Immediate, as we remove a permission from $\Perm$
  \item \resultReachPerm{}{'}\\
    Immediate, as we only update a reachable $\Loc$
  \item \resultFrame{}{}{'}
    Immediate
  \item \resultImmutables{}{}{'} \\
    Immediate
  \item \resultMutables{}{}{'} \\
    Immediate; for $\Loc$, we observe that it is overwritten, but not  freed.
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'} \\
    Immediate because $\Active\VEnv = \emptyset$ and hence $\REACH = \emptyset$.
  \item \resultThinAir{}{'}
  \end{enumerate}

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{smatchanf}

  We need to invert rule \TirName{MatchPair}
  \begin{mathpar}
    \ruleSDAIMatchPair
  \end{mathpar}
  The case VMatch corresponds to the match specification
  $\etransfm = \operatorname{id}$.

  Establish the assumptions for the recursive call
  with $\VEnv'_2 = \VEnv_2 (x\mapsto r_1) (x' \mapsto r_1')$ and $\SE' = \SE$:
  \begin{enumerate}[({A1-}1)]
  \item $\inferS{C}{\E_2 (x:\tau_1) (x':\tau'_1)}{e_2}{\tau_2}$ by inversion
  \item $\SE \vdash \VEnv_2 : \E_2$  by assumption; moreover, $\SE
    \vdash r_1 : \tau_1$ and $\SE \vdash r_1' : \tau'_1$ by inversion
    of the store typing for $\Loc$. As $\SE'=\SE$, we have $\SE' \vdash \VEnv_2' : \E_2 (x:\tau_1) (x':\tau_1')$.
  \item $\vdash \Store' : \SE'$ : the only change from assumption is in
    $\Loc$ which potentially maps to $\StFreed$.
  \item \assumeWellformed{'} : permission to $\Loc$ is removed iff
    $\Loc$ is mapped to $\StFreed$.
  \item \assumeReachable{'}{'_2} \\
    by assumption
  \item $\Rawloc{\Active{\VEnv'_2}}$,
    $\Rawloc{\MutableBorrows{\VEnv'_2}}$,
    $\Rawloc{\ImmutableBorrows{\VEnv'_2}}$, and
    $\Rawloc{\Suspended{\VEnv'_2}}$ are all disjoint: by assumption
    and splitting
  % \item  $\VEnv'$ with $\Rawloc{\VEnv'}
  %   \subseteq \Dom\Store$ and $\Dom\VEnv \cap \Dom{\VEnv'}=\emptyset$
  \item \assumeIncoming{'}{'_2}
  \end{enumerate}

  Hence the call to @eval@ yields
  $\exists$ $\Store_2$, $\Perm_2$, $r_2$, $\SE_2$ such that
  \begin{enumerate}[({R1-}1)]
  \item \resultOk{}{_2}
  \item \resultEnv{'}{_2}
  \item $\SE_2 \vdash r_2 : \tau_2$
  \item \resultPermDom{}{_2}
  \item \resultReachPerm{}{_2}
  \item \resultFrame{}{}{_2}
  \item \resultImmutables{}{}{'}
  \item \resultMutables{}{}{'}
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{'}
  \item \resultThinAir{}{'}
  \end{enumerate}
  As $R_2$ is also returned from the match, these results carry over.

  \newpage
  \textbf{Case $e$ of}
  \lstsemrule{matchborrowanf}

  We need to invert rule \TirName{MatchPair}
  \begin{mathpar}
    \ruleSDAIMatchPair
  \end{mathpar}
  The case VMatchborrow corresponds to the match specification
  $\etransfm = \&^{\BORROW}$.
  In contrast to the non-borrowing match, the borrowed pair is never deallocated.

  Establish the assumptions for the recursive call
  with  $\SE'' = \SE$:
  \begin{enumerate}[({A1-}1)]
  \item $\inferS{C}{\E_2 (x:\borrow{\tau_1}) (x':\borrow{\tau'_1})}{e_2}{\tau_2}$ by inversion
  \item $\SE \vdash \VEnv_2 : \E_2$  by assumption; moreover, $\SE
    \vdash r_1'' : \borrow{\tau_1}$ and $\SE \vdash r_2'' : \borrow{\tau'_1}$ by inversion
    of the store typing for $\Addr$. As $\SE''=\SE$, we have $\SE'' \vdash \VEnv_2'' : \E_2 (x:\borrow{\tau_1}) (x':\borrow{\tau_1'})$.
  \item $\vdash \Store' : \SE''$ : the only change from assumption is in
    $\Loc$ which potentially maps to $\StFreed$.
  \item \assumeWellformed{''} : permission to $\Loc$ is removed iff
    $\Loc$ is mapped to $\StFreed$.
  \item \assumeReachable{''}{''_2} \\
    by assumption
  \item $\Rawloc{\Active{\VEnv''_2}}$,
    $\Rawloc{\MutableBorrows{\VEnv''_2}}$,
    $\Rawloc{\ImmutableBorrows{\VEnv''_2}}$, and
    $\Rawloc{\Suspended{\VEnv''_2}}$ are all disjoint: by assumption
    and splitting
  % \item  $\VEnv'$ with $\Rawloc{\VEnv'}
  %   \subseteq \Dom\Store$ and $\Dom\VEnv \cap \Dom{\VEnv'}=\emptyset$
  \item \assumeIncoming{''}{'_2}
  \end{enumerate}

  Hence the call to @eval@ yields
  $\Store_2$, $\Perm_2$, $r_2$, $\SE_2$ such that
  \begin{enumerate}[({R1-}1)]
  \item \resultOk{}{_2}
  \item\label{item:1} \resultEnv{''}{_2}
  \item\label{item:3} $\SE_2 \vdash r_2 : \tau_2$
  \item\label{item:4} \resultPermDom{}{_2}
  \item\label{item:5} \resultReachPerm{_2''}{_2}
  \item\label{item:6} \resultFrame{''}{_2''}{_2}
  \item\label{item:7} \resultImmutables{''}{_2''}{_2}
  \item\label{item:34} \resultMutables{''}{_2''}{_2}
  % \item \resultSuspended{}{}{'}
  \item\label{item:35} \resultResources{''}{_2''}{_2}
  \item\label{item:36} \resultThinAir{''}{_2}
  \end{enumerate}

  It remains to relate to result with the original call to @eval@.
  \begin{enumerate}[(R1)]
  \item \resultOk{}{_2}
  \item \resultEnv{}{_2} because $\SE'' = \SE$ and \ref{item:1}.
  \item $\SE_2 \vdash r_2 : \tau_2$ by \ref{item:3}
  \item \resultPermDom{}{_2}
    Immediate from~\ref{item:4}.
  \item \resultReachPerm{}{_2} By~\ref{item:5} and because $\Store =\Store''$.
  \item \resultFrame{}{}{_2} Immediate from~\ref{item:6} because
    $\Store = \Store''$
  \item \resultImmutables{}{}{_2}
  \item \resultMutables{}{}{_2}
  % \item \resultSuspended{}{}{'}
  \item \resultResources{}{}{_2}
    Immediate by~\ref{item:35} because the borrowing match does not deallocate.
  \item \resultThinAir{}{_2}
  \end{enumerate}

\end{proof}

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


\section{GPUE: GPU Gross--Pitaevskii equation solver}\label{sec:GPUE}

Given the effectiveness of GPU computing in the simulation of the linear Sch\"odinger equation system for SAP, we next applied the newly-developed techniques to simulating Bose--Einstein condensates, which formed the bulk of work during my thesis. The body of software developed for this project has been released as the tool ``GPUE'', available at \url{https://github.com/mlxd/gpue}~\cite{MLXD_GPUE}. Performance testing of this code was carried out by Peter Wittek, ICFO, Barcelona~\cite{Wittek:2016}. A comparison was performed between GPUE, the Trotter--Suzuki (TS) package developed by Wittek \textit{et} al. \cite{NUM:Wittek_cpc_2013}, and the mature GPELab software suite for MATLAB \cite{NUM:GPElab_1,NUM:GPElab_2}. The sample results taken for time evolution are given in Fig.~\ref{fig:gpuevsts}. GPUE and GPU-enabled TS clearly beat MATLAB, and CPU performance by a significant margin. Although TS is a more generalised suite for computing, as far as we are currently aware the GPU computation does not yet allow for Gross--Pitaevskii solutions with angular momentum. GPUE is currently the optimal choice for rotating condensate systems out of the examined software suites.

\begin{figure}[htb]
    \centering
    \includegraphics[width=0.5\textwidth,]{ch3_numerics/GPUEvsTS.png}
    \caption{Performance benchmark of GPUE and other simulation packages for the evolution of a harmonically trapped atom in a superposition state between ground and first excited states. Lower numbers are better and give results in faster times. Data adapted from \cite{Wittek:2016}. }
    \label{fig:gpuevsts}
\end{figure}

Figures ~\ref{fig:profile_ev} and \ref{fig:profile_im} demonstrate some of the resulting calls to different segments of the code, with timings given in Tables \ref{tbl:gpue_ev} and \ref{tbl:gpue_im}. The important data of the figures is both the kernel percentage utilisation, and that the operations are mostly saturating the available number of GPU cores. The data shows the average time spent in each individual kernel during both real and imaginary time evolution for 1010 steps at $2^{10}\times 2^{10}$ resolution with (real) and without (imaginary) angular momentum operators. As can be seen, the inclusion of angular momentum operators lead to a performance hit, compared with an imaginary time evolution for a static condensate. While further optimisations can almost always be provided for such simulations, the performance of the software as a whole is defined by its slowest component. In this case the routines are equally met in performance by the Fourier transforms, which are already fully optimised as an external library. As such, improving performance much beyond this with the other kernels will be wasteful in time and resources.

%\iffalse
\begin{figure}
    \centering
    \includegraphics[width=0.98\textwidth,]{ch3_numerics/CUDA/Profiler_ev_1k_1024.png}
    \caption{Nvidia Nsight performance analysis of GPUE for real time evolution simulation for 1010 steps at $2^{10}\times 2^{10}$ resolution. The respective kernel calls and total utilisation are listed on the left.}
    \label{fig:profile_ev}
\end{figure}

\begin{table}
    \scriptsize
    \centering
\begin{tabular}{c|c|c|c|c}
\textbf{Kernel}  & \textbf{Info} & \textbf{Avg. runtime} & \textbf{\# Runs} & \textbf{Total time} \\
\hline
Mem. copy [H2D] & Memory copy from host to GPU & $2.312$ ms & 11 & $25.432$ ms\\
Mem. copy [D2H] & Memory copy from GPU to host & $2.18$ ms & 9 & $19.62$ ms\\
cMult & Complex mult. in time ev. & $0.342$ ms & 3030 & $1.0363$ s\\
cMultDensity & Complex mult. in time ev. for nonlinear op. & $0.456$ ms & 2020 & $0.921$ s \\
scalarDiv & Renorm. of $\Psi$ following FFT & $0.2216$ ms & 8080 & $1.791$ s\\
dpRadix0032B & Internal CUFFT operation & $0.237$ ms & 8080 & $1.915$ s\\
dpVector1024D & Internal CUFFT operation & $0.252$ ms & 8080 & $2.0362$ s\\
\end{tabular}
\caption{Kernel usage and timings for 1010 steps of real time evolution with angular momentum.}\label{tbl:gpue_ev}
\end{table}

\begin{figure}
    \centering
    \includegraphics[width=0.98\textwidth,]{ch3_numerics/CUDA/Profiler_im_1k_1024.png}
    \caption{Nvidia Nsight performance analysis of GPUE for imaginary time simulation for 1010 steps at $2^{10}\times 2^{10}$ resolution with angular momentum. The respective kernel calls and total utilisation are listed on the left.}
    \label{fig:profile_im}
\end{figure}

\begin{table}
    \scriptsize
    \centering
\begin{tabular}{c|c|c|c|c}
\textbf{Kernel}  & \textbf{Info} & \textbf{Avg. runtime} & \textbf{\# Runs} & \textbf{Total time} \\
\hline
Mem. copy [H2D] & Memory copy from host to GPU & $2.311$ ms & 3 & $6.933$ ms\\
Mem. copy [D2H] & Memory copy from GPU to host & $1.85$ ms & 5 & $9.25$ ms\\
cMult & Complex mult. in time ev. & $0.342$ ms & 1010 & $0.345$ s\\
cMultDensity & Complex mult. in time ev. for nonlinear op. & $0.346$ ms & 2020 & $0.698$ s \\
multipass & Optimised parallel summation & $0.125$ ms & 3030 & $0.378$ s \\
scalarDiv & Renorm. of $\Psi$ following FFT & $0.221$ ms & 2020 & $0.446$ s \\
scalarDiv_wfcNorm & Normalisation of wavefunction during ev. & $0.226$ ms & 1010 & $0.228$ s\\
dpRadix0032B & Internal CUFFT operation & $0.237$ ms & 4040 & $0.957$ s \\
dpVector1024D & Internal CUFFT operation & $0.251$ ms & 2020 & $0.507$ s \\
\end{tabular}
\caption{Kernel usage and timings for 1010 steps of imaginary time evolution for a non-rotating condensate.}\label{tbl:gpue_im}
\end{table}

A simplified sequence and state diagram combination is given in Figs.~\ref{fig:gpue_seq1} and~\ref{fig:gpue_seq2} which describes the operating process for GPUE. A document listing all aspects of component dependencies and intercommunication is available at~\cite{MLXD_GPUE}. For brevity, we will refer the reader to this location for more information.\footnote{The documentation is built using ~\href{http://www.stack.nl/~dimitri/doxygen/}{Doxygen} with the command ``doxygen ./docs/gpue_doxy.conf'', and requires the \textit{dot} package for figure generation. This may change during future releases.}.

\begin{figure}[]
    \centering
        \includegraphics[height=\textwidth,angle=270]{ch3_numerics/GPUE_Seq1}
    \caption{Simplified combined sequence and state diagram for GPUE operation (1 of 2). The operation procedure of GPUE is outlined in sequence from top-to-bottom. While much of the setup and analysis takes place on the host (CPU), the device (GPU) is used to offload all the time-evolution calculations. After setup, the wavefunction and all required operators are sent to the GPU.}
    \label{fig:gpue_seq1}
\end{figure}
\begin{figure}[]
    \centering
        \includegraphics[height=\textwidth,angle=270]{ch3_numerics/GPUE_Seq2}
    \caption{Simplified combined sequence and state diagram for GPUE operation (2 of 2). Following the completion of the time evolution after a predetermined number of steps, the wavefunction is unloaded from the GPU and returned to the CPU for output. Minimising this transfer allows for optimal performance from the device. Further details of dependencies and data flow are given by \cite[docs/gpue.pdf]{MLXD_GPUE}.}
    \label{fig:gpue_seq2}
\end{figure}

\subsection{Angular momentum operators using Fourier split-operator  method}\label{ss:ang_mom_fso}
As discussed earlier, in the presence of large values of angular momentum, the condensate wavefunction will accommodate many vortices. To ensure a well ordered lattice, more consideration is required than to just directly numerically solve the GPE at the required rotation rate. Assuming an initial Gaussian guess, and using the imaginary time evolution algorithm to find the ground state, a large number of vortices will enter the condensate from the edge and compete for lattice sites to form the expected Abrikosov pattern. Due to the highly dense spectrum of the condensate close to the ground state in this regime, only minimal energy shifts will be given for deviations from the perfect Abriksov geometry. As a result, it can take a significantly long time to reach an ordered state for rotation frequencies close to the transverse trapping frequency \cite{Vtx:Mueller_prl_2002}. To overcome this issue, one can choose to follow the ground state of the condensate with a ramp of the rotation rate. This essentially mimics adiabatic evolution, and allows for the determination of the vortex lattice ground state for all rotation frequencies.

The Fourier split-operator algorithm described earlier works well in handling cases where the individual operators live in position or momentum space respectively. However, the angular momentum operators are a combination of both spaces. Taking the angular momentum operator along the $z$-axis, $L_z = xp_y - yp_x$, and applying it to the wavefunction requires each basis element to be in a different space in the different directions. For applying this operator we must therefore Fourier transform along a single dimension, multiply by the respective $\mathbf{k}$-space component, take the inverse, multiply by the respective $\mathbf{r}$-space component in the other direction, and then perform this operation along the other dimensions, summing the results.

This accrues an error which is not encountered using methods that are solely in position or momentum space. Following the process given in Sec.~\ref{sec:fso} the error can be determined by checking the commutativity of the respective components of the angular momentum operator as

 \begin{align}
 	\alpha_1 = [x p_y,-y p_x] &= [x p_y,-y] p_x  -  y[x p_y,p_x] = -[-y,x p_y] p_x + y [p_x, x p_y] \nonumber \\
 		&= -\left( {\cancelto{0}{[-y,x]}} p_y + x [-y,p_y] \right) p_x + y \left( [p_x,x] p_y + x {\cancelto{0}{[p_x,p_y]}} \right) \nonumber \\
 		&= -x {\cancelto{-\textrm{i}\hbar}{[-y, p_y]}} p_x + y {\cancelto{-\textrm{i}\hbar}{[p_x,x]}} p_y \nonumber \\
        &= \textrm{i}\hbar \left(x p_x - y p_y \right).
 \end{align}

 The complex error term can be seen as, in the case of the above implemented evolution, allowing the angular momentum operator to change from imaginary time to real-time, and vice-versa in each respective case. To overcome this, we simply swap the application order of the operator components, between odd and even steps during the evolution. Starting with the alternate order we obtain a value of $\alpha_2 = [-y p_x, x p_y] = \textrm{i}\hbar \left(-x p_x + y p_y \right)$. Since we are applying these operators to the condensate we can overcome the error of one term by the application of the other, as
 \begin{equation}
 \exp{\textrm{i} \alpha_1}\exp{\textrm{i} \alpha_2} = 1.
 \end{equation}

 Although alternating will provide a cancellation of this error, it can be assumed that for large timesteps the error will have a significant contribution to the overall dynamics, as the wavefunction evolves during each timestep. For greater accuracy of this method one can perform a decomposition following Eq.~\eqref{eqn:3} for a third-order error, or using the above splitting for second-order.

An example of the density of the ground state and the associated wavefunction phase at a rotation frequency of $\Omega = 0.995\omega_x$ is given in Fig.~\ref{fig:showingoff} at a resolution of $2^{11}\times 2^{11}$ ($2048\times 2048$). Although aliasing may be apparent in the phase, this is due to the limited resolution of the computer monitor (printer). The presence of a well ordered Abrikosov lattice is clearly visible.

 \begin{figure}
     \centering
     \includegraphics[width=0.45\textwidth,]{ch3_numerics/Rho_995}
     \includegraphics[width=0.45\textwidth,]{ch3_numerics/phi_995}
     \caption{Condensate density (left) and phase (right) at a rotation rate of $\Omega=0.995\omega_x$ for a $2^{11}\times 2^{11}$ grid showing approximately 600 vortices in the visible density regions. For both images the box size is $700~\mu\textrm{m} ~\times ~700~\mu\textrm{m}$.}
     \label{fig:showingoff}
 \end{figure}

 \subsection{Vortex tracking}\label{sec:vortrack}
 To efficiently follow the dynamics of individual vortices, a robust algorithm is needed to track their positions. One could track regions where the density drops to zero. However, this gives very little information on the topological excitation, and may miss many vortices, as the numerical wavefunction may never truly approach this value. A more effective way is to locate the $\pm 2\pi$ charge in the wavefunction phase, which is a signature of quantum vortices. For this we examine each $2\times 2$ subgrid of the underlying lattice and check if the phase rotates from $-\pi$ to $+\pi$ (or vice versa). After an initial pass to identify vortex locations closest the nearest grid element, a least-squares fit is performed to more accurately determine the vortex core position \cite{c42f}. Linear least squares is used generally for an overdetermined linear system $\mathbf{A}\mathbf{r} = \mathbf{b}$, where unique solutions are unlikely to exist. Thus, for a solution, we seek the best fit plane that minimises the error, of the form

 \begin{equation}
 S(\mathbf{r}) = \displaystyle\sum |b_i - \displaystyle\sum A_{ij} r_j |^2
 \end{equation}
 where $S$ is the objective function to be minimised, following $\mathbf{b} = \argmin S(\mathbf{r})$. The solution of this minimisation problem is given by
 \begin{subequations}
\begin{align}
    \mathbf{A} ^{T}\mathbf{A} \mathbf{r} &= \mathbf{A} ^{T}\mathbf{b}, \\
    \mathbf{r} &= (\mathbf{A}^{T}\mathbf{A})^{-1}\mathbf{A}^{T}\mathbf{b}.
\end{align}
\end{subequations}
The best-fit plane is sought of the form
$a_0 c + \displaystyle\sum\limits_{i}^{m} a_i r_i = f(\mathbf{r})$
which for a two-dimensional system, $\mathbf{r} = (x,y)$, is given by the matrix,
\begin{equation}
    \mathbf{A} = \left(
    \begin{array}{ccc}
        0 & 0 & 1 \\
        0 & 1 & 1 \\
        1 & 0 & 1 \\
        1 & 1 & 1
    \end{array}\right).
\end{equation}
The above matrix is composed of all possible planes that can fit over a square $2\times 2$ grid plaquette,
and
\begin{equation}
    \mathbf{b} = \left(
    \begin{array}{cccc}
        \Psi(x_0,y_0) & \Psi(x_0,y_1) & \Psi(x_1,y_0) & \Psi(x_1,y_1)
    \end{array} \right)^{T},
\end{equation}
are the wavefunction values around the sampled $2\times 2$ grid.
Upon evaluating the vector $\mathbf{r}$ above, one can obtain the best fit plane  solution as
\begin{equation}\left(
    \begin{array}{c}
        x \\
        y \\
        c
    \end{array}\right)
    = \left(
    \begin{array}{c}
        {\left( -\Psi(x_0,y_0) + \Psi(x_0,y_1) - \Psi(x_1,y_0) + \Psi(x_1,y_1) \right)}{/2} \\
        {\left( -\Psi(x_0,y_0) - \Psi(x_0,y_1) + \Psi(x_1,y_0) + \Psi(x_1,y_1) \right)}{/2} \\
        3\Psi(x_0,y_0) + \Psi(x_0,y_1) - \Psi(x_1,y_0) - \Psi(x_1,y_1)
    \end{array}\right).
\end{equation}

The goal is to find where both the real and imaginary components cross through zero, and thus we seek a solution of the form $x + y = -c$. Rearranging the above equations as
\begin{equation}\left(
    \begin{array}{cc}
        \Re(x) & \Re(y) \\
        \Im(x) & \Im(y) \\
    \end{array}\right)
    \left(
    \begin{array}{c}
        \delta x \\
        \delta y
    \end{array}\right)
    = -
    \left(
    \begin{array}{c}
        \Re(c) \\
        \Im(c)
    \end{array}\right),
\end{equation}
and again solving the linear system by inverting the left-hand matrix and multiplying across allows one to seek the corrections to the vortex position, $\delta \mathbf{r} = (\delta x, \delta y )$.

 With this, we can accurately determine the position of the vortices with high precision. To track their motion during the evolution, we create an initial list of positions and give each vortex a unique identifier (UID). Assuming the vortex cores can travel a limited distance (some multiple of the grid resolution) between time steps, we can say at subsequent times which vortex has moved to the newly found positions.

 This process is performed by representing the vortices as a graph, each with an assigned unique identifier, associated location, phase winding and on/off flag. Edges are created between vortices that are separated by at most root-two the average of the inter-vortex spacings. A finite boundary is chosen to examine only vortices in areas of significant condensate density, since vortices can easily appear and disappear close to the condensate boundary. Any vortex which appears without association to an initial vortex, or any tracked vortex that crosses the boundary, is switched off and remains so for all analysis. A graph for an initial ($t=0$) vortex lattice shown in Fig.~\ref{fig:graphit}, with the identifiers indicated on each node, and the neighbouring distances indicated by the edge weights. %The almost perfect triangular structure is clearly confirmed. %%This is a graph, not a location plot. Positions are chosen at mathematicas discretion

 \begin{figure}
     \centering
     \includegraphics[width=0.98\textwidth,]{ch3_numerics/Graph_full}
     \caption{Graph of vortex lattice positions indicating the vortex identifier and the intervortex distances in units of grid-spacing $\Delta= \Delta x = \Delta y$. A hard-walled boundary is chosen such that the vortex distances remain almost uniform, and are shown here with a mean value of $\bar{r} = 30.2451$ and variance of $\sigma^2 = 0.16118$.}
     \label{fig:graphit}
 \end{figure}


% !TEX root = ../00_thesis.tex

\section{Concrete Realization of \DRP}
\label{sec:concrete_realization}

\squarepar{%}
  This section discusses how to concretely implement \DRP's concepts. In particular, one needs to define
  (i)~the fixed flushing interval $T_f^s$ of the \CPs~(\cref{subsec:CP_schedule}), and
  (ii)~how to dynamically compute the network deadline \ndeadlinei of a flow \flowi and the flushing interval $T_f^d$ of each \ap (\cref{subsec:D_Tfd_computation}).%
}

Then, a worst-case buffer analysis (\cref{subsec:WC_buffer}) will allow to formulate admission tests (\cref{subsec:admission}), one for {\ap}s and one for {\cp}s.
The success of all admission tests guarantees that both contracts \textbf{Source}~$\boldsymbol{\leftrightarrow}$~\textbf{Blink} and \textbf{Blink}~$\boldsymbol{\leftrightarrow}$~\textbf{Destination} can be satisfied by \DRP.

\subsection{Setting \CPs' Flushing Interval}\label{subsec:CP_schedule}

\squarepar{%}
  To guarantee that all \CPs fulfill their share of the contracts (\ie prevent buffer overflows), we conceive a time-triggered approach to schedule all tasks of \CPs. It consists of (\emph{i}) setting the flushing interval $T_f^s$ of all \CPs to the same constant value, and (\emph{ii}) letting the round interval $T_{net}$ be a multiple of $T_f^s$.
  As discussed in \cref{sec:designDetailed}, $T_f^s$ should not to constrain the achievable deadline: thus, we aim to set it as short as possible.
  \CPs have three tasks to perform%
}

\begin{itemize}
 \item flushing \bolt before each communication round,
 \item participating in the communication during the rounds,
 \item writing all received messages into \bolt after the rounds.
\end{itemize}

Performing those tasks altogether takes $C_{CP} + C_{net}$ time units, where $C_{CP} = C_f + \nslotsmax * C_w$, and \nslotsmax denotes the number of time slots in one round.
Hence, $C_{CP} + C_{net}$ is the smallest admissible round interval (otherwise \CPs' task set is not schedulable). Thus we set for all \CPs in the system,
\begin{align}
\label{eq:design_flush_period_source}
	& T_f^s = C_{CP} + C_{net} \\
\intertext{and we let the round interval be a multiple of $T_f^s$. That is, for $k \in \mathbb{N}$, $k > 0$,}
\label{eq:design_round_period}
	& T_{net} = k * T_f^s
\end{align}
For a given $C_{net}$, a larger $k$ entails less available bandwidth but also lower energy consumption.
\blink is designed to dynamically adjust $k$ to match the bandwidth requirements and save energy~\cite{zimmerling2017Blink}.

\subsection{\mbox{Computing Network Deadlines \& \APs ' Flushing Interval}}
\label{subsec:D_Tfd_computation}

Having fixed \CPs' flushing interval, we now turn to the problem of dynamically computing the network deadline \ndeadlinei of flow \flowi and the flushing interval $T_f^d$ of \flowi's destination \apdst, such that the end-to-end deadline \deadlinei is met.
To this end, we need to define expressions for the functions $f$ and $g$ (introduced in \cref{sec:designDetailed}), and derive values for \ndeadlinei and $T_f^d$ such that equations \eqref{eq:function_f} and \eqref{eq:function_g} are satisfied.

\begin{theorem}
  \label{thm:delta}
  For any flow \flowi = (\flowsrci,\flowdsti,\periodi,\jitteri,\deadlinei), and given the duration of communication rounds $C_{net}$, functions $f$ and $g$ are upper-bounded as follows
  \begin{align}
  f(T_f^s ,  \ndeadlinei)
  	& \; \leq \;
  	T_i + D_i + \overline{\jitteri}  + \delta_f^{const} \label{eq:expression_f}\\
  g(T_f^d)
  	& \; \leq  \;
  	T_f^d(\flowdsti) + \delta_g^{const} \label{eq:expression_g}
  \end{align}
  where $ \delta_f^{const}$ and $\delta_f^{const}$ are constant delays that depend on the WCETs of the \bolt API functions, on the maximum number of messages \nslotsmax that can be %inside a \bolt queue at the end of a round
  served by \blink in one round, and on the fixed flushing interval $T_f^s$ of \CPs,
  \begin{align}
  \delta_f^{const} &\;= \;\; C_w + C_f + T_f^s \\
  \delta_g^{const} &\;= \;\;\nslotsmax*C_w - (\nslotsmax-1)* C_r + C_f\\
  \label{eq:jitter_bar}
  \overline{\jitteri}  &\;= \;\; \floor*{(\jitteri + C_f - C_r)/{T_f^s}}\cdot T_f^s
  \end{align}
\end{theorem}

\begin{proof}%
Function $f$ is the time between when a message is written into \bolt by the source \apsrc and when the communication round in which the message is sent by \blink ends (\ie when the message is available at the destination \cpdst).
This is the sum of two delays: $\delta_{source}$, the time until the message is available for communication at the source \cpsrc; and $\delta_{network}$, the time until the message is shipped over the network to \cpdst.

Similarly, function $g$ is the time between when a packet is available at the destination \cpdst and the end of the \opflush operation that reads the message out of \bolt at the destination \apdst (\ie when the message can be processed by the destination application).
We refer to this delay as $\delta_{dest}$.

Hence, the expressions for functions $f$ and $g$ in \eqref{eq:expression_f} and \eqref{eq:expression_g} directly follow from the delays expression derived in Lemmas~\ref{lem:delta_source}, \ref{lem:delta_network}, and \ref{lem:delta_destination}~(\cref{append:drp_WCanalysis}).
\
\end{proof}

We use Theorem~\ref{thm:delta} to express conditions on \ndeadlinei and $T_f^d$ such that \eqref{eq:function_f} and \eqref{eq:function_g} are satisfied.
In particular, it is sufficient that for any flow $\flowi = (\flowsrci,\flowdsti,\periodi,\jitteri,\deadlinei) \in \flowset$
\begin{align}
\nonumber
 T_i + D_i + \overline{\jitteri} \;
	& \leq  \;\; r * \deadlinei - \delta_f^{const} \\
\label{eq:ndeadline_constraint_latency}
\Rightarrow \qquad T_i \;
	& \leq  \;\; r * \deadlinei - \delta_f^{const} - D_i - \overline{\jitteri} \\
\intertext{and}
\label{eq:APflush_constraint_base}
T_f^d(\flowdsti) \;
	& \leq \, (1-r)*\deadlinei -  \delta_g^{const}
\end{align}

As low-power wireless networks typically feature limited bandwidth,%
\footnote{Low-power radio bit rates are often limited to 256\kbps; the latest version of Bluetooth (Bluetooth~5) supports up to 2\Mbps.}
%
it makes sense to choose the network deadline \ndeadlinei as large as possible in order to increase the schedulability of flows in the network.
However, \blink only supports constrained deadlines ($\ndeadlineany \leq \periodany$) and deadlines must be multiples of the round length ($\ndeadlineany = 0 \mod \rperiod $).
Furthermore, a network deadline cannot be smaller than \rperiodmin (see \cref{subsec:details_blink}).
%
Hence, for any flow \flowi, it must hold that
\begin{align}
  \label{eq:ndeadline_constraint_period}
  \rperiodmin \; &\leq \; \ndeadlinei \; \leq \; \periodi \\
  \ndeadlinei \; &= \; 0 \mod \rperiod
\end{align}

Finally, to satisfy all contracts in the system, \eqref{eq:ndeadline_constraint_latency}, \eqref{eq:APflush_constraint_base} and \eqref{eq:ndeadline_constraint_period} must hold for all flows $\flowi \in \flowset$.
Hence, the values for \ndeadlinei and $T_f^d$ computed dynamically at runtime must satisfy for any flow $\flowi = (\flowsrci,\flowdsti,\periodi,\jitteri,\deadlinei) \in \flowset$ and any $n \in \mathcal{N}$
\begin{align}
\label{eq:design_ndeadline}
\ndeadlinei \;
	& = \; \min \left(\; \periodi \;\, , \,  r*\deadlinei - \delta_f^{const} - \periodi - \overline{\jitteri} \right) - (\ndeadlinei \mod \rperiod) \\
\label{eq:design_delay_destination}
T_f^d(n) \;
	& \leq \; \min_{F_j\in \mathcal{F}, n = \flowdstj}
	\left( (1-r)*\deadlinej - \delta_g^{const} \right)
\end{align}
If using \eqref{eq:design_ndeadline} leads to a violation of the constraint in \eqref{eq:ndeadline_constraint_period} or if $T_f^d$ results in a load that \ap at node $n$ cannot handle, \DRP rejects the flow since the two contracts cannot be guaranteed.

\subsection{Worst-case Buffer Analysis}
\label{subsec:WC_buffer}

Satisfying all contracts entails preventing overflows of message buffers in the system.
Specifically, as shown in \cref{fig:design_overview},
\begin{itemize}
	\item \APs are responsible for ensuring that the incoming \bolt queues do not overflow, and
	\item \CPs are responsible for ensuring that their local message buffers and the outgoing \bolt queues do not overflow.
\end{itemize}

\squarepar{%}
  To formulate the admission tests for {\ap}s and {\cp}s, we first need the worst-case buffer sizes (\ie maximum number of messages in a buffer) induced by a given flow set \flowset.
  For ease of exposition, we make the following hypothesis.%
}
\begin{hypothesis}\label{hyp:f_max}
For a given flow set \flowset, an \ap (resp. \cp) never writes more messages into \bolt than can be flushed by \cp (resp. \ap) in one \emph{\opflush} operation in the time span between two \emph{\opflush}.
\end{hypothesis}
This hypothesis implies that the \bolt queues are always empty at the end of a \opflush operation.
We prove at the end of this section that our admission tests effectively guarantee that Hypothesis~\ref{hyp:f_max} is always verified.

\begin{lemma} \label{lem:buffer_bolt_out}
Given a flow set \flowset, the buffer size of the outgoing \bolt queue of node $n \in \nodeset$, $B_{\bolt,out}(n)$, is upper-bounded,
\begin{equation}
\label{eq:bolt_out_buffer_stress}
	B_{\bolt, out}(n) \; \leq \;
	\sum_{\substack{F_i\in \mathcal{F},\, n = \flowsrci}} \ceil*{\frac{T_f^s + C_w + C_r + \jitteri}{T_i}}
\end{equation}
\end{lemma}

\begin{proof}%
According to the \textbf{Source} $\boldsymbol{\leftrightarrow}$ \textbf{Blink} contract, \apsrc at node $n$ does not write more than one message every \periodi with jitter \jitteri into the outgoing \bolt queue.
Based on Hypothesis~\ref{hyp:f_max}, the buffer size is bounded by the number of messages that can be written by \apsrc during the maximum time a message can stay inside the queue, which is $\Delta = T_f^s + C_w + C_r$ (see \cref{fig:delta_source_time_graph}).
The maximum number of messages that can be written by \apsrc within any time interval $\Delta$ is $\ceil*{(\Delta + J_i)/{T_i}}$ for each flow \flowi sourced by~$n$. \
\end{proof}

The worst-case buffer size of a \cp depends on (i) the maximum time a message can stay in \cp's local memory awaiting to be served by \blink, and (ii) the number of messages that can be sent within one round to a node.

\begin{lemma} \label{lem:buffer_CP}
Given a flow set \flowset, the buffer size of {\cp}'s internal memory of node $n \in \nodeset$, $B_{CP}(n)$, is upper-bounded,
\begin{equation}
\label{eq:CP_memory_stress}
	B_{CP}(n) \leq
	\sum_{\substack{F_i\in \mathcal{F},\\ n = \flowsrci}}
	1 + \ceil*{\frac{\ndeadlinei + \overline{\jitteri} + C_f}{T_i}} +
	\sum_{\substack{F_i\in \mathcal{F},\\ n = \flowdsti}} 1
\end{equation}
\end{lemma}

\begin{proof}%
On the source side, we make the conservative assumption that all messages read out during a \emph{\opflush} occupy memory in \cpsrc from the beginning of the \emph{\opflush}. Hence, the maximum waiting time in \cpsrc for a message until it is served by \blink is $\delta_{network} + C_f$ (see Lemma~\ref{lem:delta_network} -- \cref{append:drp_WCanalysis}). The number of messages in \cpsrc due to the source is upper-bounded by the maximum number of messages \apsrc can write during this time interval, given by
$\ceil*{\delta_{network} + C_f)/T_i}$.
Using Lemma~\ref{lem:delta_network}, this is at most
$1 + \ceil*{( \ndeadlinei + \overline{\jitteri} + C_f)/\periodi }$  per outgoing flow.

One the destination side, during a round, \cpdst may receive several messages, which it immediately writes into \bolt after the round.
However, \blink expects one packet every \periodi from each flow, which it serves within \ndeadlinei. As $\ndeadlinei \leq \periodi$, \blink never schedules more than one packet per round for each flow.
Thus, the maximum number of messages in \cpdst due to the destination is 1 packet per incoming flow.
\
\end{proof}

\begin{lemma} \label{lem:buffer_bolt_in}
Given a flow set \flowset, the buffer size of the incoming \bolt queue of node $n \in \nodeset$, $B_{\bolt,in}(n)$, is upper-bounded,
\begin{equation}
\label{eq:bolt_in_buffer_stress}
	B_{\bolt, in}(n)\;  \leq \;
	\sum_{\substack{F_i\in \mathcal{F},\\ n = \flowdsti}} \ceil*{\frac{T_f^d(n) + C_w + C_r + D_i}{T_i}}
\end{equation}
\end{lemma}

\begin{proof}%
As specified in the \textbf{Source} $\boldsymbol{\leftrightarrow}$ \textbf{Blink} contract, \blink delivers packets from any flow \flowi before the network deadline \ndeadlinei~(\cref{sec:designDetailed}). Therefore, \blink delivers at most one packet every \periodi time units, with a jitter equal to \ndeadlinei, which are written into \bolt immediately after the round.

Based on Hypothesis~\ref{hyp:f_max},
the buffer constraint of the incoming \bolt queue is bounded by the number of packets that can be written by \cpdst during the maximum elapsed time before a packet is read out by \apdst. As in the proof of Lemma~\ref{lem:buffer_bolt_out}, there are at most $\ceil*{(T_f^d(n) + C_w + C_r + D_i)/{T_i}}$ such messages from each flow \flowi that has node $n$ as destination.
\end{proof}

\subsection{Admission Tests}
\label{subsec:admission}

We now combine the above results and formulate the admission tests for \CPs and \APs, which form the cornerstone of \DRP's registration mechanism described in \cref{sec:designDetailed}.
We further show that the computation complexity of the admission tests is not only small but \emph{constant}, and hence supports the requirements of \feature{Adaptability} and \feature{Efficiency}.

\squarepar{%}
  Let $F_j$ be the flow for which a request has been issued, and $\mathcal{F}_{new} = \mathcal{F} \cup \{F_j\}$.
  The \cp of node $n$ is responsible for preventing overflows of its local memory (of size $S_{CP}$) and of the outgoing \bolt queue of node $n$ (of size $S_{\bolt}$).%
}

\begin{theorem}[{Admission Test of \cp}]\label{thm:CP}
If
\begin{align*}
S_{\bolt} \;
	 & \geq \sum_{\substack{\flowi \in \mathcal{F}_{new}, \\ n = \flowsrci}}
	 	\ceil*{\frac{T_f^s + C_w + C_r + \jitteri}{T_i}} \\
\textup{and}\qquad
S_{CP} \;
 	& \geq
	\sum_{\substack{\flowi \in \mathcal{F}_{new}, \\ n = \flowsrci}}
		1 + \ceil*{\frac{\ndeadlinei + \overline{\jitteri} + C_f}{T_i}}
	+ \sum_{\substack{\flowi \in \mathcal{F}_{new}, \\ n = \flowdsti}}
		1
\end{align*}
then the requested flow \flowj can be safely admitted by $\cp$.
\end{theorem}

\begin{proof}Immediate from Lemmas~\ref{lem:buffer_bolt_out} and \ref{lem:buffer_CP}. \
\end{proof}

The \ap of node $n$ is responsible for preventing overflows of the incoming \bolt queue (of size $S_{\bolt}$) and for guaranteeing its share of the end-to-end deadline.

\begin{theorem}[{Admission Test of \ap}]
\label{thm:AP}
  If there exists $T_f^d(n)$ such that
  \begin{align*}
    T_f^d(n) \;
    & \leq \, \min_{\substack{F_i\in \mathcal{F}_{new}, \\  n = \flowdsti}}
    \left( (1-r)*\deadlinei - \delta_g^{const} \right)\\
\textup{and}\qquad
    S_{\bolt} \;
    & \geq \sum_{\substack{\flowi \in \mathcal{F}_{new}, \\ n = \flowdsti}} \ceil*{\frac{T_f^d(n) + C_w + C_r + D_i}{T_i}}
  \end{align*}
  then the requested flow \flowj can be safely admitted by $\ap$.
\end{theorem}
\begin{proof}
Immediate from Lemma~\ref{lem:buffer_bolt_in} and equation \eqref{eq:design_delay_destination}.
\end{proof}

Finally, we verify that Hypothesis~\ref{hyp:f_max} holds, showing the validity of our buffer analysis. From \eqref{eq:f_max=M} we have $f_{max} = S_{\bolt}$. Thus, by performing the admission tests at runtime, it follows from Theorems~\ref{thm:CP} and \ref{thm:AP} and Lemmas~\ref{lem:buffer_bolt_out} and \ref{lem:buffer_bolt_in} that $f_{max}$ is always bigger than the filling level of any \bolt queue, which entails Hypothesis~\ref{hyp:f_max} is true.


\title{\bf Spectra}

\section{Basics \& Nomenclature}

Spectra of objects can be determined in a number of ways, through
refraction, diffraction, or through energy-sensitive devices (most
commonly in the X-rays). Here we concentrate on the issues most
relevant to diffraction grating spectra, though many of these issues
are also relevant in other contexts.

Typically, spectra are obtained by putting a dispersive element in the
collimated beam. Although prisms can and have been used at the
objective pupil, more typically the dispersing element is at a pupil
beyond the focus. In addition to providing a smaller area for the
dispersing element to cover, this allows the focal plane to be used to
remove light not associated with the object or object of
interest. Slit spectrographs put a slit (or many slits) in this focal
plane, recollimate the diverging beam, disperse it, and then refocus
it on a new focal plane. Fiber spectrographs use optical fibers in the
focal plane and then align the fiber outputs in a convenient manner
with respect to the detectors.

Diffraction gratings consist of optical elements ruled in some manner
with a set of closely spaced apertures. At any given wavelength, light
coming through the grating will be diffracted. The majority of energy
passes straight through in the 0th order mode, but diffraction causes
additional modes at angles perpendicular to the ruling. The location
of the 1st and greater order modes depends on wavelength, meaning the
higher-order modes yield spectra, with larger dispersion but a smaller
fraction of the incoming energy at higher order modes. Traditional
diffraction gratings were usually ruled metal or mirrors, often mated
to a prism (a configuration known as a {\it grism}) to reorient the
desired mode along a convenient path. Modern gratings are usually
volume-phase holographic gratings, created within a substrate through
holographic techniques. With greater control over the grating
geometry, these gratings typically result in optics with higher
throughput by avoiding occlusion along the geometric optics light
path.

Spectra can be described as having a characteristic resolution. The
raw spectrum is usually detected on in a two-dimensional image, and
the spectrum appears along a somewhat curved line, known as the {\it
trace}, traversing the image along the dispersion direction. The
resolution parallel to the dispersion direction is known as the {\it
line spread function}, whereas the resolution perpendicular to the
dispersion direction is known as the {\it point spread function}, in
analogy to an image.

For slit spectra, the point spread function is determined largely by
the seeing and telescope PSF; the actual profile of the spectrum
perpendicular to the trace is the image of the object convolved with
the PSF. For fiber spectra, the light is usually sufficiently
scrambled that the width of the PSF is determined by the size of the
fiber, as reimaged by the camera.

The line spread function is charactered by the resolution $R= \lambda
/ \Delta \lambda$, where $\Delta\lambda$ is usually the FWHM of the
LSF (but not always). It is determined by the size of the fiber and
the dispersion power of the grating. For exposures more than a few
minutes, any flexure of the spectrograph over the course of the
exposure may also cause blurring in the LSF (or PSF).

The raw spectra need to be extracted and calibrated. The {\it
extraction} involves inferring a signal as a function of position on
the trace, to create a one-dimensional spectrum. The position in
pixels needs to be converted to wavelength; the relationship between
the two is usually inferred by injecting a signal into the
spectrograph, often sourced by an {\it arc lamp} which emits light at
discrete lines associated with ionized inert gases (He, Ne, Ar,
etc).

The signal needs to be converted to flux units. If we assume the
detector is bias-subtracted as if it were an image, the signal in the
trace can be modeled as:
\begin{equation}
{\rm DN}(x) = \left[f(\lambda(x)) + f_{\rm
sky}(\lambda(x))\right] \times F(x) \times T(\lambda)
\end{equation}
The quantity $F(x)$, the {\it flat}, characterizes the effects of the
detector response and is typically determined by injecting light from
a flat-field lamp, which has a broad spectrum; in fact, only
small-scale features are usually retained from the flat-field for
reasons that will soon be clear.

The quantity $T(\lambda)$ characterizes the throughput as a function
of wavelength, and is affected by the atmospheric transmission, how
much of the light enters the spectroscopic aperture at any given
wavelength, and the throughput of the optics, as well as any remaining
dependence of efficiency on wavelength on scales larger than those
probed by the flat. It must be determined in part by observing
standard stars whose true spectra are assumed, either through
additional slits or fibers at the same time as the objects of
interest, or through the same slits or fibers at slightly different
times. Either approach requires accounting for the resulting slight
differences in the observations.

The sky signal $f_{\rm sky}(\lambda)$ also needs to be removed. In the
case of slit observations, the sky can be estimated from the outer
parts of the slit, which contain little object flux. In the case of
fiber observations, the sky needs to be estimated from other nearby
fibers. Because the fiber varies with position and time on the sky,
this can be uncertain.

\section{Commentary}

In ground-based spectroscopy it is extremely important to pay
attention to the chromatic atmospheric refraction. This effect can
lead to different amounts of light getting through fiber or slit as a
function of wavelength, because the image in the telescope focal plane
is a function of wavelength. These differences lead to both a
variation in throughput and potential loss of signal-to-noise, and
also may make the spectrum hard to calibrate (if the standards used
are not under the same conditions). Slit spectra are often arranged so
that the slit is parallel to the parallactic direction to minimize
this effect, but there is no such mitigation for fibers. Atmospheric
dispersion correctors consisting of crossed prisms can be used to
reduce this effect, but they need to act in a pupil so are large and
expensive.

In practice, the difficulty in sky subtraction is almost entirely due
to the LSF modeling. Typically the issue arises because there are
strong lines that need to be subtracted, and so the LSF model needs to
be very good to be accurate enough. In addition, the sky can have a
different LSF than the object, since there are slit-filling
issues or due to imperfections in the extraction method.

\section{Key References}

\begin{itemize}
  \item
    {\it Design and Construction of Large Telescopes},
      \citet{bely03a}
  \item
    {\it Astrophysical Techniques}, \citet{kitchin09a}
\end{itemize}

\section{Order-of-magnitude Exercises}

\begin{enumerate}
\item Assuming the centroid accuracy is related to $R$ and $S/N$ ratio
    in a similar way for optical spectra of single emission lines as
    for point sources in an image, for an unresolved line with
    $S/N \sim 10$ in its total flux, how high $R$ do you have to be to
    determine a Doppler velocity to 10 km s$^{-1}$ precision?  How
    would a redshift determination using a full optical spectrum
    (i.e. using many lines) change the precision of the determination
    qualitatively? How does dependence of the velocity precision on
    $R$ differ qualitatively for absorption lines?

\begin{answer}[Author: Matthew Daunt]
    Due to the Doppler shift, we can predict the radial velocity of an
    object using the observed wavelength and observed wavelength,
    via
\begin{equation}
    v_r = \frac{\lambda_{obs} -\lambda_0}{\lambda_0} c
\end{equation}
    Resolution is defined as
    \begin{equation}
        R = \frac{\lambda}{\Delta \lambda}
    \end{equation}
    where $\Delta \lambda$ is the full width half max (FWHM). We
    can express the resolution in velocity units therefore as
    \begin{equation}
    \Delta v = \frac{\lambda}{R } \frac{c}{\lambda} = \frac{c}{R}
\end{equation}
    The precision in the radial velocity should be better when the FWHM is
    smaller and the $S/N$ is higher. The scaling is the same as for
    positions in an image, such that
    \begin{equation}
    \sigma \sim {\rm FWHM~}/ (S/N) = \frac{c}{R} \frac{1}{S/N}
    \end{equation}
    For $S/N = 10$, this equation is therefore:
    \begin{equation}
    \sigma \sim \frac{30,000 {\rm ~km} {\rm ~s}^{-1}}{R}
    \end{equation}
    which therefore requires $R\sim 3,000$.  If you have more than one
    emission line, you can use the $S/N$ in each of the, and the
    combined precision will be better than just using one. The case of
    absorption lines will differ because the noise in the continuum
    will contribute, and a larger width of the line will degrade the
    precision further than for an emission line.
\end{answer}
\end{enumerate}

% \section{Analytic Exercises}

% \begin{enumerate}
% \item Assuming that the
% \end{enumerate}

\section{Numerics and Data Exercises}

\begin{enumerate}
\item Find an SDSS spectrum of a galaxy and sky fiber from the same
    plate of the BOSS survey. Plot the sky and the object spectrum.
\item Find an arc spectrum from the BOSS survey, and a corresponding sky
spectrum taken during the same calibration-exposure sequence. You will
need to use
the \href{https://data.sdss.org/datamodel/files/SPECTRO_REDUX/RUN2D/PLATE4/spPlan2d.html}{\tt
spPlan2d} files to figure out which
\href{https://data.sdss.org/datamodel/files/BOSS_SPECTRO_REDUX/RUN2D/PLATE4/spCFrame.html}{\tt
spCframe} files to use. Find at least one pair of sky and arc lines,
each of which is bright and isolated from other lines. Estimate the
FWHM of the LSF from each and compare them.
\end{enumerate}

\bibliographystyle{apj}
\bibliography{exex}


% Chapter 2

\chapter{Experimental Setup} % Chapter title

\label{ch:experim} % For referencing the chapter elsewhere, use \autoref{ch:examples}

%----------------------------------------------------------------------------------------

A collection of 1322 misspellings and their corrections were obtained from Fawthrop's contribution in Birkbeck spelling error corpus \cite{mitton1985birkbeck}.
The dataset is divided into two parts: training set (comprises of 930 words) and test set (comprises of 392 words).
The hyperparameters would be tuned on the training set and then it would be tested on the test set.
Aspell dictionary \cite{atkinson2006gnu} is used as the spell-check dictionary.
The spellings from the aspell dictionary serve as the document match for the information retrieval system.
Every query (misspelling) would have only one relevant document (correct spelling) to match.
Hence we would use MRR (Mean Reciprocal Rank) as our evaluation metric.

MeTA toolkit \cite{massung2016meta} is employed to build the search engine for the spell variants.

Following k-gram variants are employed in this experiment:
\begin{enumerate}
	\item Basic k-gram split
	\item Double-ended positional k-gram split
	\item Double-ended positional k-gram split with offsets
\end{enumerate}
The units $k = 2$, $k = 3$, and $k = 2$ with $3$ (union of $k = 2$ and $k = 3$ sets) are chosen.
Following ranking functions are employed in this experiment:
\begin{enumerate}
	\item TF-IDF, no hyperparameters \cite{tfidf}
	\item Okapi BM25 with hyperparameters $b$ and $k$ \cite{bm25}
	\item Bayesian smoothing with a Dirichlet prior with hyperparameter $\mu$ \cite{dirich}
\end{enumerate}
The experimental results are summarized in Table \ref{split}.

We used MRR (Mean Reciprocal Rank) here as our evaluation metric, since each misspelling had only one solution in our dataset.

\begin{equation*}
	MRR = \frac{1}{s} \sum_{i = 1}^s \frac{1}{rank_i}
\end{equation*}

Here $s$ is the size of the dataset and $rank_i$ is the position of the rank for the first relevant document of the $i^{th}$ query.


\part{part}
part text
part text
\chapter{chapter long title}
 chapter text
 chapter text
 \[
	 f(x)=x^2
 \]
 \section[for the toc]{section}
  section text
  section text
 \section[for the toc]{section}
  section text
  section text
  \subsection[for the toc]{subsection}
  subsection text
  subsection text
  \subsection[for the toc]{subsection}
  subsection text
  subsection text
 \section[for the toc]{section}
  section text
  section text
\chapter{chapter}
 chapter text
 chapter text
 \part{part}
 part text
 part text
\chapter[toc]{chapter title}
 chapter text
 chapter text
 \section[for the toc]{section}
  section text
  section text
  \subsubsection[for the toc]{subsubsection}
  subsubsection text
  subsubsection text
  \paragraph{paragraph}
  paragraph text
  paragraph text
  \subparagraph{subparagraph}
  subparagraph text
  subparagraph text
 \section[for the toc]{section}
  section text
  section text
  \subsubsection[for the toc]{subsubsection}
  subsubsection text
  subsubsection text
  \paragraph{paragraph}
  paragraph text
  paragraph text
  \subparagraph{subparagraph}
  subparagraph text
  subparagraph text
\chapter[somethingelse]{goes here}


\section{Glossary}
\paragraph{Mode} = local maximum of a given distribution
\paragraph{k-means vs knn}   KNN represents a supervised classification algorithm that will give new data points accordingly to the k number or the closest data points,
while k-means clustering is an unsupervised clustering algorithm that gathers and groups data into k number of clusters.