\documentclass[runningheads]{llncs}
% TODO: get rid of page numbers

\usepackage[utf8]{inputenc}
\usepackage{url}
\usepackage{amsmath}
\usepackage{mathbbol}
\usepackage{mathtools}
\usepackage{hyperref}
\usepackage{todonotes}
\usepackage{appendix}
\usepackage[strict]{changepage}

% Two column itemize
\usepackage{multicol}

% Example code
\usepackage{listings}

% Diagrams
\usepackage{tikz}

% Mathbb doesn't support digits
\usepackage{bbm}

% inference rules
\usepackage{mathpartir}

% Newline inside table
\usepackage{makecell}

% Continue examples later on
% \usepackage{thmtools}
% \renewcommand\thmcontinues[1]{Continued}

% Do not use italics in definitions and theorems
\spnewtheorem{nidefinition}[definition]{Definition}{}{}
\spnewtheorem{nilemma}[lemma]{Lemma}{\bfseries}{}
\spnewtheorem{nitheorem}[theorem]{Theorem}{\bfseries}{}

%% remove for the camera ready
\AtBeginDocument{%
\renewcommand*{\figureautorefname}{Fig.\@\!}
\renewcommand*{\sectionautorefname}{\S\!\!\,}
\renewcommand*{\subsectionautorefname}{\S\!\!\,}
\newcommand*{\nitheoremautorefname}{Thm.}
\newcommand*{\nidefinitionautorefname}{Def.}
\newcommand*{\nilemmaautorefname}{Lem.}
\newcommand*{\exampleautorefname}{Eg.}
}

% Abbreviations
\newcommand{\lambdacalc}{$\lambda$-calculus}
\newcommand{\picalc}{$\pi$-calculus}
\newcommand{\Picalc}{$\pi$-Calculus}

% Typing rules
\newcommand{\stacked}[1]{\mprset{flushleft} \inferrule*{}{#1}}
\newcommand{\datatype}[2]{{\mprset{fraction={===}} \inferrule{#1}{#2}}}

\newcommand{\type}[1]{\textcolor{blue}{\operatorname{#1}}}
\newcommand{\constr}[1]{\textcolor{orange}{\operatorname{#1}}}
\newcommand{\func}[1]{\textcolor{teal}{\operatorname{#1}}}

% Constructors
\newcommand{\PO}{\constr{\mathbb{0}}}
\newcommand{\comp}[2]{#1 \, \constr{\parallel} \, #2}
\newcommand{\new}{\constr{\boldsymbol{\nu}} \,}
\newcommand{\send}[2]{#1 \, \constr{\langle} \, #2 \,\constr{\rangle} \,}
\newcommand{\recv}[2]{#1 \, \constr{\mathbb{(}} \, #2 \, \constr{\mathbb{)}} \,}
\newcommand{\suc}{\constr{\scriptstyle 1+}}
\newcommand{\unit}{\constr{\mathbbm{1}}}
\newcommand{\base}[1]{\constr{B[} \, #1 \, \constr{]}}
\newcommand{\channel}[2]{\constr{C[} \, #1 \, \constr{;} \, #2 \, \constr{]}}
\newcommand{\comma}{\, \constr{,} \,}

% Functions
\newcommand{\subst}[3]{#1 \, \func{[} \, #3 \, \func{\mapsto} \,#2 \, \func{]}}
\newcommand{\op}[3]{#1 \, \func{\coloneqq} \, #2 \, \func{\cdot} \, #3}
\newcommand{\opsquared}[3]{#1 \, \func{\coloneqq} \, #2 \, \func{\cdot^2} \, #3}
\newcommand{\opctx}[3]{#1 \, \func{\coloneqq} \, #2 \, \func{\otimes} \, #3}
\newcommand{\zero}{\func{\cdot-0}}
\newcommand{\one}{\func{\cdot-1}}
\newcommand{\li}{\func{\ell_i}}
\newcommand{\lo}{\func{\ell_o}}
\newcommand{\lz}{\func{\ell_{\emptyset}}}
\newcommand{\lio}{\func{\ell_{\#}}}

% Types
\newcommand{\Set}{\type{SET}}
\newcommand{\reduce}[1]{\, \type{\longrightarrow}_{#1} \,}
\newcommand{\types}[4]{#1 \, \type{;} \, #2 \, \type{\vdash} \, #3 \, \type{\triangleright} \, #4}
\newcommand{\contains}[6]{#1 \, \type{;} \, #2 \, \type{\ni}_{#3} \, #4 \, \type{;} \, #5 \, \type{\triangleright} \, #6}
\newcommand{\containsusage}[4]{#1 \, \type{\ni}_{#2} \, #3 \, \type{\triangleright} \, #4}
\newcommand{\Var}{\type{VAR}}
\newcommand{\Process}{\type{PROCESS}}
\newcommand{\Raw}{\type{RAW}}
\newcommand{\Name}{\type{NAME}}
\newcommand{\Names}{\type{NAMES}}
\newcommand{\Fresh}{\type{FRESH}}
\newcommand{\WellScoped}{\type{WELLSCOPED}}
\newcommand{\Unused}{\type{UNUSED}}
\newcommand{\PreCtx}{\type{PRECTX}}
\newcommand{\Ctx}{\type{CTX}}
\newcommand{\Type}{\type{TYPE}\,}
\newcommand{\Idx}{\type{IDX}\,}
\newcommand{\Idxs}{\type{IDXS}}
\newcommand{\Usage}{\type{USAGE}}
\newcommand{\N}{\type{\mathbb{N}}}
\newcommand{\Channel}{\type{CHANNEL}}
\newcommand{\Rec}{\type{REC}}
\newcommand{\Algebra}{\type{ALGEBRA}}
\newcommand{\eq}{\, \type{\simeq} \,}
\newcommand{\eqeq}{\, \type{\cong} \,}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\title{$\pi$ with leftovers: \\ a mechanisation in Agda}
\titlerunning{$\pi$ with leftovers: a mechanisation in Agda}
\author{
  Uma Zalakain\inst{1}\orcidID{0000-0002-3268-9338}
  \and
  Ornela Dardha\inst{2}\orcidID{0000-0001-9927-7875}
}
\authorrunning{U. Zalakain \and O. Dardha}

\institute{
  University of Glasgow, Scotland \ \ \email{u.zalakain.1@research.gla.ac.uk}
  \and
  University of Glasgow, Scotland \ \ \email{ornela.dardha@glasgow.ac.uk}
}
% Support
% This work is supported by the UK EPSRC grant EP/K034413/1 ``From Data Types to Session Types: A Basis for Concurrency and Distribution'' (ABCD), and by the EU HORIZON 2020 MSCA RISE project 778233 ``Behavioural Application Program Interfaces'' (BehAPI).}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\maketitle

\begin{abstract}
  Linear type systems need to keep track of how programs use their resources.
  The standard approach is to use \emph{context splits} specifying how resources are (disjointly) split across subterms.
  In this approach, context splits redundantly echo information which is already present within subterms.  An alternative approach is to use \emph{leftover typing} \cite{Mackie,Allais2018a}, where in addition to the usual (input) usage context, typing judgments have also an output usage context: the leftovers.
  In this approach, the leftovers of one typing derivation are fed as input to the next, threading through linear resources while avoiding context splits.
  We use leftover typing to define a type system for a {resource-aware \picalc{}} \cite{MilnerPW92,Milner99}, a process algebra used to  model concurrent systems.
  Our type system is parametrised over a set of \emph{usage algebras} that are general enough to encompass \emph{shared types} (free to reuse and discard), \emph{graded types} (use exactly $n$ number of times) and \emph{linear types} (use exactly once).
   Linear types are important in the \picalc{}: they ensure privacy and safety of communication and avoid race conditions, while graded and shared types allow for more flexible programming.
  We provide a framing theorem for our type system, generalise the weakening and strengthening theorems to include linear types, and prove subject reduction.
  Our formalisation is fully mechanised in about 1850 lines of Agda \cite{Zalakain2020Agda}.

%  \keywords{Pi-calculus \and Linear types \and Leftover typing \and Concurrency \and Mechanisation \and Agda}
\end{abstract}

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

The \picalc{} \cite{MilnerPW92,Milner99} is a computational model for communication and concurrency that boils concurrent processing down to the sending and receiving of data over communication channels.
Notably, it features channel mobility: channels themselves are first class values and can be sent and received.
Kobayashi et al. \cite{KPT96} introduced a typed version of the \picalc{} with linear channel types, where channels must be used \emph{exactly} once.
Linearity in the \picalc{} guarantees privacy and safety of communication and avoids race conditions.

More broadly, linearity allows for resource-aware programming and more \emph{efficient} implementations \cite{Wadler90}, and it  inspired unique types (as in Clean \cite{BarendsenS96}), and ownership types (as in Rust \cite{MatsakisK14}).
A linear type system must keep track of what resources are used in which parts of the program, and guarantee that they are \emph{neither duplicated nor discarded}.
To do so, the standard approach is to use context splits: typing rules for terms with multiple subterms add an extra side condition specifying what resources to allocate to each of the subterms.
The typing derivations for the subterms must then use the entirety of their allocated resources.
A key observation here is that each subterm already \emph{knows} about the resources it needs.
\emph{Context splits contain usage information that is already present in the subterms.}
Moreover, the subterms cannot be typed until the context splits have been defined.
On top of that, using binary context splits means that typing rules with $n$ subterms require $n - 1$ context splits, which considerably clutters the type system.

An alternative approach is \emph{leftover typing}, a technique used to formulate intuitionistic linear logic \cite{Mackie} and to mechanise the linear \lambdacalc~\cite{Allais2018a}.
Leftover typing changes the shape of the typing judgments and includes a second \emph{leftover} output context that contains the resources that were left unused by the term.
As a result, typing rules \emph{thread} the resources \emph{through} subterms without needing context splits: each subterm uses the resources it needs, and leaves the rest for its siblings.
The first subterm in this chain of resources immediately knows what resources it has available.

In this paper, we use leftover typing to define for the first time a resource-aware type system for the \picalc{}, and we fully mechanise our work in Agda \cite{Zalakain2020Agda}.
All previous work on mechanisation of linear process calculi uses context splits instead \cite{Gay2001,Goto2016a,Gay2010,Thiemann2019,Ciccone}. We will further highlight the benefits of leftover typing as opposed to context splits in contributions and the rest of the paper.

Below we present two alternative typing rules for parallel composition in the linear \picalc{}: the one on the left uses context splits, while the one on the right does not, and uses leftover typing instead:
\begin{mathpar}
  \inferrule
  {\opctx{\Gamma}{\Delta}{\Xi} \\ \Delta \; \type{\vdash} \; P \\ \Xi \; \type{\vdash} \; Q}
  {\Gamma \; \type{\vdash} \; \comp{P}{Q}}

  \inferrule
  {\Gamma \; \type{\vdash} \; P \; \type{\triangleright} \; \Delta \\ \Delta \; \type{\vdash} \; Q \; \type{\triangleright} \; \Xi}
  {\Gamma \; \type{\vdash} \; \comp{P}{Q} \; \type{\triangleright} \; \Xi}
\end{mathpar}

\paragraph*{Contributions and Structure of the Paper}
\begin{enumerate}
  \item \textbf{Leftover typing for resource-aware \picalc{}}. Our type system uses leftover typing to model the resource-aware \picalc{} (\autoref{leftover-typing}) and satisfies subject reduction (\autoref{thm:subject-reduction}).
    In addition to making context splits unnecessary, leftover typing allows for a \emph{framing} theorem (\autoref{thm:framing}) to be stated and is naturally associative, making type safety properties considerably easier to reason about (\autoref{meta-theory}).
    Thanks to leftover typing, we can now state \emph{weakening} (\autoref{thm:weakening}) and \emph{strengthening} (\autoref{thm:strengthening}) for the whole framework, not just the shared fragment. This give a uniform and complete presentation of all the meta-theory for the resource-aware \picalc{}.
  \item \textbf{Shared, graded and linear unified \picalc{}}.
  We {generalise resource counting to a set of usage algebras that can be mixed within the same type system}.
    We do not instantiate our type system to only work with linear resources, instead we present an algebra-agnostic type system, and admit a mix of user-defined \emph{resource aware} algebras (\autoref{multiplicities}).
    Any \emph{partial commutative monoid} that is \emph{decidable}, \emph{deterministic}, \emph{cancellative} and has a \emph{minimal element} is a valid such algebra.
    Multiple algebras can be mixed in the type system --- usage contexts keep information about what algebra to use for each type (\autoref{contexts}).
    In particular, this allows for type systems combining linear (use exactly once), graded (exact number of $n$ times) and shared (free to reuse and discard) types under the same framework.

    \item \textbf{Full mechanisation in Agda}. The formalisation of the \picalc{} with leftover typing, from the syntax to the semantics and the type system, has been fully mechanised in Agda in about 1850 lines of code, and is publicly available at \cite{Zalakain2020Agda}.  We have fully mechanised all meta-theory and the details of a proof of subject reduction can be found in Appendix \ref{app:type-safety}.
\end{enumerate}

We use type level {de Bruijn indices} \cite{deBruijn1972,Dybjer1994} to define a syntax of \picalc{} processes that is \emph{well scoped by construction}: every free variable is accounted for in the type of the process that uses it (\autoref{syntax}).
We then provide an operational semantics for the \picalc{}, prior to any typing (\autoref{semantics}).
This operational semantics is defined as a reduction relation on processes.
The reduction relation tracks at the type level the channel on which communication occurs.
This information is later used to state the subject reduction theorem.
The reduction relation is defined modulo \emph{structural congruence} --- a relation defined on processes that acts as a quotient type to remove unnecessary syntactic minutiae introduced by the syntax of the \picalc{}.
We then define an interface for resource-aware algebras (\autoref{multiplicities}) and use it to parametrise a type system based on leftover typing (\autoref{leftover-typing}).
Finally, we present the meta theoretical properties of our type system in \autoref{meta-theory}.

\paragraph{Notation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%We briefly illustrate the notation used in this paper.
Data type definitions ($\type{\N}$) use double inference lines and index-free synonyms (\textsc{Nat}) as rule names for ease of reference.
Constructors ($\constr{0}$ and $\suc$) are used as inference rule names.
We maintain a close correspondence between the definitions presented in this paper and our mechanised definitions in Agda: inference rules become type constructors, premises become argument types and conclusions return types.
Universe levels and universe polymorphism are omitted for brevity --- all our types are of type $\Set$.
Implicit arguments are mentioned in type definitions but omitted by constructors.
\begin{mathpar}
  \datatype
  { }
  {\type{\N} : \Set}
  \; \textsc{Nat}

  \inferrule
  { }
  {\constr{0} : \type{\N}}

  \inferrule
  {n : \type{\N}}
  {\suc n : \type{\N}}
\end{mathpar}

We use colours to further distinguish the different entities in this paper.
$\type{TYPES}$ are blue and uppercased, with indices as subscripts, $\constr{constructors}$ are orange, $\func{functions}$ are teal, variables are black, and some constructor names are overloaded --- and disambiguated by context.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Syntax}
\label{syntax}

In order to mechanise the \picalc{} syntax in Agda, we need to deal with bound names in continuation processes.
Names are cumbersome to mechanise: they are not inherently well scoped, one has to deal with alpha-conversion, and inserting new variables into a context entails proving that their names differ from all other names in context.
To overcome these challenges, we use de Bruijn indices \cite{deBruijn1972}, where a natural number $n$ (aka \emph{index}) is used to refer to the variable introduced $n$ binders ago.
That is, binders no longer introduce names; terms at different \emph{depths} use different indices to refer to the same binding.

While de Bruijn indices are useful for mechanisation, they are not as readable as names. To overcome this difficulty and demonstrate the correspondence between a \picalc{} that uses names and one that uses de Bruijn indices,
we provide \emph{conversion functions} in both directions and prove that they are inverses of each other up to $\alpha$-conversion. Further details can be found in Appendix~\ref{from_to_deBruijn}.

\begin{nidefinition}[\textsc{Var} and \textsc{Process}]\label{def:syntax}
A variable reference occurring under $n$ binders can refer to $n$ distinct variables.
We introduce the indexed family of types \cite{Dybjer1994} $\Var_n$: for all naturals $n$, the type $\Var_n$ has $n$ distinct elements.
We index processes according to their \emph{depth}: for all naturals $n$, a process of type $\Process_n$ contains free variables that can refer to $n$ distinct elements.
Every time we go under a binder, we increase the index of the continuation process, allowing the variable references within to refer to one more thing.
\begin{mathpar}
  \datatype
  {n : \N}
  {\Var_n : \Set}
  \; \textsc{Var}

  \inferrule
  {n : \N}
  {\constr{0} : \Var_{\suc n}}

  \inferrule
  {x : \Var_n}
  {\suc x : \Var_{\suc n}}

  \datatype
  {n : \N}
  {\Process_n : \Set}
  \; \textsc{Process}
\end{mathpar}

\begin{equation*}
  \begin{aligned}
    \Process_n ::=& \; \PO                &&\text{(inaction)}   \\
    |& \; \new{} \Process_{\suc n}         &&\text{(restriction)}          \\
    |& \; \comp{\Process_n}{\Process_n}    &&\text{(parallel)} \\
    |& \; \recv{\Var_n}{}\Process_{\suc n} &&\text{(input)}                \\
    |& \; \send{\Var_n}{\Var_n}\Process_n  &&\text{(output)}
  \end{aligned}
\end{equation*}

Process $\PO$ denotes the terminated process, where no further communications can occur;
process $\new{} P$ creates a new channel and binds it at index $0$ in the continuation process $P$;
process $\comp{P}{Q}$ composes $P$ and $Q$ in parallel;
process $\recv{x}{}P$ receives data along channel $x$ and makes that data available at index $0$ in the continuation process $P$;
process $\send{x}{y}{P}$ sends variable $y$ over channel $x$ and continues as process $P$.
\end{nidefinition}

\begin{example}[The courier system]
\label{example-process}

We present a courier system that consists of three \emph{roles}:
a sender, who wants to send a package;
a receiver, who receives the package sent by the sender;
and a courier, who carries the package from the sender to the receiver.
\begin{center}
  \small
  \begin{tikzpicture}[draw,circle]
    \node[draw,circle,fill opacity=0.3,text opacity=1,fill=brown] (send-x) at (0,2)   {$\func{send} \, x$};
    \node[draw,circle,fill opacity=0.3,text opacity=1,fill=brown] (send-y) at (0,0)   {$\func{send} \, y$};
    \node[draw,circle,fill opacity=0.3,text opacity=1,fill=purple] (recv-z) at (4,1)   {$\func{recv} \, z$};
    \node[draw,circle,fill opacity=0.3,text opacity=1,fill=cyan,align=center] (sync) at (2,1)   {$\func{carry}$\\$ \, x \, y \, z$};

    \draw[->] (send-x) -- node[above] {$x$} (sync);
    \draw[->] (send-y) -- node[below] {$y$} (sync);
    \draw[->] (sync.10) -- node[above] {$z$} (recv-z.170);
    \draw[->] (sync) -- (recv-z);
  \end{tikzpicture}
\end{center}

Our courier system is defined by four \picalc{} processes composed in parallel instantiating the above three roles:
we have two sender processes, $\func{send} \, x$ and $\func{send} \, y$, sending data over channels $x$ and $y$, respectively;
one receiver process, $\func{recv} \, z$, which receives over channel $z$ the data sent from each of the senders -- hence receives twice;
and a courier process $\func{carry} \, x \, y \, z$, which synchronises communication among the senders and the receiver.
The courier process first receives data from the two senders along its input channels $x$ and $y$, and then sends the two received bits of data to the receiver along its output channel $z$.

The sender and receiver \emph{roles} are defined below, parametrised by the channels on which they operate.
The sender creates a new channel to be sent as data, and sends it over channel $c$, and then terminates.
Processes $\func{send} \, x$ and $\func{send} \, y$ are an instantiation of $\func{send} \, c$.
The receiver receives data \emph{twice} on a channel $c$ and then terminates.
The receiver process $\func{recv} \, z$ is an instantiation of $\func{recv} \, c$.
\begin{align*}
  & \func{send} \; c = \new{} (\send{\suc c}{\constr{0}} \PO) &&
    \func{recv} \; c \; = \recv{c}{} \recv{(\suc c)}{} \PO
\end{align*}

The courier role is defined below as $\func{carry} \; x \; y \; z$.
It sequentially receives on the two input channels $x$ and $y$, instantiated as $in0$ and $in1$, and then outputs the two pieces of received data on the output channel $z$, instantiated as $out$.
Finally, we create three communication channels and compose all four processes together: the first channel is shared between the one sender and the courier, the second between the other sender and the courier, and the third between the receiver  and the courier.
The result is the courier $\func{system}$ defined below.
\begin{align*}
  & \func{carry} \; in0 \; in1 \; out \; =  \recv{in0 }{}
  \recv{(\suc \; in1) }{}
  \send{(\suc \suc \; out) }{\suc \constr{0}}
  \send{(\suc \suc \; out) }{\constr{0}} \PO \\
  & \func{system} =  \new{} ( \func{send} \; \constr{0}
  \comp{}{\new{} ( \func{send} \; \constr{0} }
  \comp{}{\new{} ( \func{recv} \; \constr{0} }
  \comp{}{\func{carry} \; (\suc \suc \constr{0}) \; (\suc \constr{0}) \; \constr{0}))) }
\end{align*}

We continue this running example in  \autoref{leftover-typing}, where we provide typing derivations for the above processes and use a mix of linear, graded and shared typing to type the courier $\func{system}$.
\end{example}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Operational Semantics}
\label{semantics}
Thanks to our well-scoped grammar in \autoref{syntax}, we now define the semantics of our language on the totality of the syntax.

\begin{nidefinition}[\textsc{Unused}] \label{def:unused}
  We consider a variable $i$ to be unused in $P$ ($\Unused_i \; P$) if none of the inputs nor the outputs refer to it.
  $\Unused_i \; P$ is defined as a recursive predicate on $P$, incrementing $i$ every time we go under a binder, and using $i \type{\not\equiv} x$ ( which unfolds to the negation of propositional equality on \textsc{Var}, i.e. $i \type{\equiv} x \to \type{\bot}$) to compare variables.
\end{nidefinition}

\begin{nidefinition}[\textsc{StructCong}] \label{def:structcong}
We define the base cases of a structural congruence relation $\eqeq$ as follows:
\begin{mathpar}
  \datatype
  { }
  {P \eqeq Q : \Set}
  \; \textsc{StructCong}

  \inferrule
  { }
  {\constr{comp-assoc} : \comp{P}{(\comp{Q}{R})} \eqeq \comp{(\comp{P}{Q})}{R}}

  \inferrule
  { }
  {\constr{comp-sym} : \comp{P}{Q} \eqeq \comp{Q}{P}}

  \inferrule
  { }
  {\constr{comp-id} : \comp{P}{\PO_n} \eqeq P}

  \inferrule
  { }
  {\constr{scope-end} : \new \PO_{\suc n} \eqeq \PO_n}

  \inferrule
  {uQ : \Unused_{\constr{0}} \; Q}
  {\constr{scope-ext} : \new (\comp{P}{Q}) \eqeq \comp{(\new P)}{\func{lower}_{\constr{0}} \; \; Q \; uQ}}

  \inferrule
  { }
  {\constr{scope-comm} : \new \new P \eqeq \new \new \func{exchange}_{\constr{0}} \; P}
\end{mathpar}
The first three rules ($\constr{comp}-$*) state associativity, symmetry, and $\PO$ as being the neutral element of parallel composition, respectively.
The last three ($\constr{scope}-$*) state garbage collection, scope extrusion and commutativity of restrictions, respectively.
In $\constr{scope-ext}$ the side condition $\Unused_i \; Q$ makes sure that $i$ is unused in $Q$ (see \autoref{def:unused}).
The function $\func{lower}_i \; Q \; uQ$ traverses $Q$ decrementing every index greater than $i$.
In $\constr{scope-comm}$ the function $\func{exchange}_i \; P$ traverses $P$ (of type $\allowbreak \Process_{\suc \suc n}$) and swaps variable references $i$ and $\suc i$.
In all the above, $i$ is incremented every time we go under a binder.
\end{nidefinition}

\begin{nidefinition}[\textsc{Equals}] \label{def:equals}
We lift the relation \textsc{StructCong} $\eqeq{}$ and close it under equivalence and congruence in $\eq{}$.
This relation is structurally congruent under a context $\mathcal{C}[\cdot]$ \cite{Sangio01} and is reflexive, symmetric and transitive.
\end{nidefinition}

\begin{nidefinition}[\textsc{Reduces}]\label{def:reduces}
The operational semantics of the \picalc{} is defined as a reduction relation $\reduce{c}$ indexed by the channel $c$ on which communication occurs.
We keep track of channel $c$ so we can state subject reduction (\autoref{thm:subject-reduction}).

\begin{mathpar}
  \datatype
  {n : \N}
  {\Channel_n : \Set}
  \; \textsc{Channel}

  \inferrule
  { }
  {\constr{internal} : \Channel_n}

  \inferrule
  {i : \Var_n}
  {\constr{external} \; i : \Channel_n}

  \datatype
  {c : \Channel_n \\ P \; Q : \Process_n}
  {P \reduce{c} Q : \Set}
  \; \textsc{Reduces}

  \inferrule
  {i \; j : \Var_n \\ P : \Process_{\suc n} \\ Q : \Process_n}
  {\constr{comm} : \comp{\recv{i}{}P}{\send{i}{j}{Q}} \reduce{\constr{external} \; i} \comp{\func{lower}_{\constr{0}} \; (\subst{P}{\suc j}{\constr{0}}) \; uP'}{Q}}

  \inferrule
  {red : P \reduce{c} P'}
  {\constr{par} \; red : \comp{P}{Q} \reduce{c} \comp{P'}{Q}}

  \inferrule
  {red : P \reduce{c} Q}
  {\constr{res} \; red : \new P \reduce{\func{dec}\; c} \new Q}

  \inferrule
  {eq_1 : P \eq{} P' \\ red : P' \reduce{c} Q' \\ eq_2 : Q' \eq{} Q}
  {\constr{struct} \; eq \; red : P \reduce{c} Q}
\end{mathpar}

We distinguish between channels that are created inside the process ($\constr{internal}$), and channels that are created outside ($\constr{external}\ i$), where $i$ is the index of the channel variable.
In rule $\constr{comm}$, parallel processes reduce when they communicate over a common channel with index ${i}$.
As a result of that communication, the continuation of the input process $P$ has all the references to its most immediate variable substituted with references to $\suc j$, the variable sent by the output process $\send{i}{j}{Q}$.
After this substitution, $\subst{P}{\suc j}{\constr{0}}$ is \emph{lowered} --- all variable references are decreased by one (and we derive the proof $\Unused_{\constr{0}} \; (\subst{P}{\suc j}{\constr{0}})$).
Reduction is closed under parallel composition (rule $\constr{par}$), restriction (rule $\constr{res}$) and structural congruence (rule $\constr{struct}$)
--- notably, not under input nor output, as doing so would not preserve the sequencing of actions \cite{Sangio01}.
Rule $\constr{res}$ uses $\func{dec}$ to decrement the index of channel $c$ as we wrap processes $P$ and $Q$ inside a binder.
It is defined as expected below:
\begin{equation*}
  \begin{aligned}
    & \func{dec} \; \constr{internal}                 && = \constr{internal} \\
    & \func{dec} \; (\constr{external} \; \constr{0}) && = \constr{internal} \\
    & \func{dec} \; (\constr{external} \; (\suc n))   && = \constr{external} \; n \\
  \end{aligned}
\end{equation*}
\end{nidefinition}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Resource-aware Type System}
\label{type-system}

In \autoref{multiplicities} we characterise a usage algebra for our type system.
It defines how resources are \emph{split} in parallel composition and \emph{consumed} in input and output.
We define typing and usage contexts in \autoref{contexts}.
We provide a type system for a resource-aware \picalc{} in \autoref{leftover-typing}.

\subsection{Multiplicities and Capabilities}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{multiplicities}

In the linear \picalc{} each channel has an input and an output \emph{capability}, and each capability has a given \emph{multiplicity} of 0 (exhausted) or 1 (available).
We generalise over this notion by defining an algebra for multiplicities that is satisfied by linear, graded and shared types alike.
We then use pairs of multiplicities as usage annotations for a channel's input and output capabilities.

\begin{nidefinition}[\textsc{Algebra}]
  A \emph{usage algebra} is a ternary relation $\op{x}{y}{z}$ that is \emph{partial} (as not any two multiplicities can be combined), \emph{deterministic} and \emph{cancellative} (to aid equational reasoning) and \emph{associative} and \emph{commutative} (following directly from subject congruence for parallel composition).
  In addition, we ask that the leftovers can be \emph{computed} so that we can automatically update the usage context every time input and output occurs --- this is purely for usability.
  It has a \emph{neutral element} $\zero$ that is absorbed on either side, and that is also \emph{minimal} (so that new resources cannot arbitrarily spring into life).
  It has an element $\one$ that is used to count inputs and outputs.
  Below we define such an algebra as a record $\Algebra_C$ on a carrier $C$.
  (We use $\forall$ for universal quantification.
  The dependent product $\type{\exists}$ uses the value of its first argument in the type of its second.
  The type $\type{DEC} \; P$ is a witness of either $P$ or $P \to \type{\bot}$, where $\type{\bot}$ is the empty type with no constructors.)
  \begin{equation*}
  \begin{aligned}
    &\op{\_}{\_}{\_}         &:{} &                 &        & C \to C \to C \to \Set \\
    &\func{\cdot-unique}     &:{} &\forall x x' y z  & \to \; & \op{x'}{y}{z} \to \op{x}{y}{z} \to x' \equiv x \\
    &\func{\cdot-unique^l}   &:{} &\forall x y y' z  & \to \; & \op{x}{y'}{z} \to \op{x}{y}{z} \to y' \equiv y \\
    &\func{\cdot-assoc}      &:{} &\forall x y z u v & \to \; & \op{x}{y}{z} \to \op{y}{u}{v} \to \type{\exists} w  \; (\op{x}{u}{w} \times \op{w}{v}{z}) \\
    &\func{\cdot-comm}       &:{} &\forall x y z     & \to \; & \op{x}{y}{z} \to \op{x}{z}{y} \\
    &\func{\cdot-compute^r}  &:{} &\forall x y       & \to \; & \type{DEC} \; (\type{\exists} z  \; (\op{x}{y}{z})) \\
    &\zero                   &:{} &                 &        & C \\
    &\func{\cdot-id^l}       &:{} &\forall x         & \to \; & \op{x}{\zero}{x} \\
    &\func{\cdot-min^l}      &:{} &\forall y z        & \to \; & \op{\zero}{y}{z} \to y \equiv \zero \\
    &\one                    &:{} &                 &        & C \\
  \end{aligned}
  \end{equation*}
\end{nidefinition}

We sketch the implementation of linear, graded and shared types as instances of our usage algebra below.
Their use in typing derivations is illustrated in \autoref{example-derivation}.
\begin{center}
\begin{tabular}{l | l | l}
  & carrier & operation \\
  \hline
  \textbf{linear} & \makecell[cl]{$\constr{0} \, : \, \type{Lin}$ \\ $\constr{1} \, : \, \type{Lin}$} & \makecell[cl]{$\op{\constr{0}}{\constr{0}}{\constr{0}}$ \\ $\op{\constr{1}}{\constr{1}}{\constr{0}}$ \\ $\op{\constr{1}}{\constr{0}}{\constr{1}}$} \\
  \hline
  \textbf{graded} & \makecell[cl]{$\constr{0} \, : \type{Gra}$ \\ $\suc \, : \type{Gra} \to \type{Gra}$} & \makecell[cl]{$\forall \, x \, y \, z$ \\ $\to x \, \type{\equiv} \, y \, \func{+} \, z$ \\ $\to \op{x}{y}{z}$} \\
  \hline
  \textbf{shared} & $\constr{\omega} \, : \, \type{Sha}$ & $\op{\constr{\omega}}{\constr{\omega}}{\constr{\omega}}$ \\
\end{tabular}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Typing Contexts}
\label{contexts}

We use indexed sets of usage algebras to allow several usage algebras to coexist in our type system with leftovers (\autoref{leftover-typing}).
\begin{nidefinition}[\textsc{Algebras}]
  An \emph{indexed set of usage algebras} is a type $\Idx$ of indices that is nonempty ($\type{\exists IDX}$) together with an interpretation $\Usage$ of indices into types, and an interpretation $\type{ALGEBRAS}$ of indices into usage algebras of the corresponding type.

  \begin{equation*}
    \begin{aligned}
      &\Idx               &:{} &\Set \\
      &\type{\exists IDX} &:{} &\Idx \\
      &\Usage             &:{} &\Idx \to \Set \\
      &\type{ALGEBRAS}    &:{} &(idx : \Idx) \to \Algebra_{\Usage_{idx}}
    \end{aligned}
  \end{equation*}
\end{nidefinition}

We keep typing contexts ($\PreCtx$) and usage contexts ($\Ctx$) separate.
The former are preserved throughout typing derivations; the latter are transformed as a result of input, output, and context splits.
\begin{nidefinition}[\textsc{Type} and \textsc{PreCtx}: types and typing contexts]
  A \emph{type} is either a unit type ($\unit$),
  % a base type ($\base{n}$)
  or a channel type ($\channel{t}{x}$).
  \begin{mathpar}
    \datatype
    { }
    {\Type : \Set}
    \; \textsc{Type}

    \inferrule
    { }
    {\unit : \Type}

    \inferrule
    {t : \Type \\ \stacked{idx : \Idx \\\\ x : \Usage_{idx}^{\func{2}}}}
    {\channel{t}{x} : \Type}
  \end{mathpar}

  The unit type $\unit$ serves as a base case for types.
  % The base type $\base{n}$ uses natural numbers as placeholders for types (the host language can then interpret the former into the latter --- e.g., $0$ as the unit type, $1$ as booleans) so that we avoid dealing with universe polymorphism.
  The type $\channel{t}{x}$ of a channel determines what type ${t}$ of data and what usage annotations ${x}$ are sent over that channel --- we use the notation $\type{C}^{\func{2}}$ to stand for a $\type{C} \constr{\times} \type{C}$ pair of input and output multiplicities, respectively.
  This channel notation aligns with $[t]\ \mathbf{chan}_{(i^{y},o^{z})}$, where $y,z$ are the input and output multiplicities, respectively \cite{K07}.
  Henceforth, we use $\lz$ to denote the multiplicity pair $\zero \comma \zero$, $\li$ for the pair $\one \comma \zero$, $\lo$ for $\zero \comma \one$, and $\lio$ for $\one \comma \one$.
  This notation was originally used in the linear \picalc{} \cite{KPT96,Sangio01}.
  A \emph{typing context} $\PreCtx_n$ is a length-indexed list of types that is either empty ($\constr{[]}$) or the result of appending a type $t : \Type$ to an existing context ($\gamma \constr{,} t$).
\end{nidefinition}

\begin{nidefinition}[\textsc{Idxs} and \textsc{Ctx}: contexts of indices and usage contexts]
  A context of indices $\Idxs_n$ is a length-indexed list that is either empty ($\constr{[]}$) or the result of appending an index $i : \Idx$ to an existing context ($idxs \constr{,} i$).
  A \emph{usage context} is a context $\Ctx_{idxs}$ indexed by a context of indices $idxs : \Idxs_n$ that is either empty ($\constr{[]}$) or the result or appending a usage annotation pair $u : \Usage_{idx}^{\func{2}}$ with index $idx : \Idx$ to an existing context ($\Gamma \constr{,} u$).
\end{nidefinition}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Typing with Leftovers}
\label{leftover-typing}

We present a resource-aware type system for the \picalc{} based on \emph{leftover typing} \cite{Allais2018a}, a technique that, in addition to the usual typing context $\PreCtx_n$ and (input) usage context $\Ctx_{idxs}$, adds an extra \emph{(output) usage context} $\Ctx_{idxs}$ to the typing rules.
This output context contains the \emph{leftovers} (the unused multiplicities) of the process being typed.
These leftovers can then be used as input to another typing derivation.

Leftover typing inverts the information flow of usage annotations so that it is the typing derivations of subprocesses which determine how resources are allocated.
As a result, context split proofs are no longer necessary.
Leftover typing also allows \emph{framing} to be stated, and \emph{weakening} and \emph{strengthening} to cover linear types too.

Our type system is composed of two typing judgments: one for variable references (\autoref{def:varref}) and one for processes (\autoref{def:types}).
Both judgments are indexed by a typing context $\gamma$, an input usage context $\Gamma$, and an output usage context $\Delta$ (the leftovers).
The \textbf{typing judgement for variables} $\contains{\gamma}{\Gamma}{i}{t}{y}{\Delta}$ asserts that ``index $i$ in typing context $\gamma$ is of type $t$, and subtracting $y$ at position $i$ from input usage context $\Gamma$ results in leftovers $\Delta$''.
The \textbf{typing judgement for processes} $\types{\gamma}{\Gamma}{P}{\Delta}$ asserts that ``process $P$ is well typed under typing context $\gamma$, usage input context $\Gamma$ and leftovers $\Delta$''.

\begin{nidefinition}[\textsc{VarRef}: typing variable references] \label{def:varref}
  The \textsc{VarRef} typing relation for variable references is presented below.
  \begin{mathpar}
    \mprset{sep=0.5em}

    \datatype{
      \gamma : \PreCtx_n \\
      i : \Var_n \\
      \stacked{
        t : \Type \\\\
        idx : \Idx \\\\
        y : \Usage_{idx}^{\func{2}}} \\
      \stacked{
        idxs : \Idxs_n \\\\
        \Gamma \; \Delta : \Ctx_{idxs}}}
    {\contains{\gamma}{\Gamma}{i}{t}{y}{\Delta} : \Set}
    \; \textsc{VarRef}

    \inferrule
    {\opsquared{x}{y}{z}}
    {\constr{0} : \contains{\gamma \comma t}{\Gamma \comma x}{\constr{0}}{t}{y}{\Gamma \comma z}}

    \inferrule
    {v : \contains{\gamma}{\Gamma}{i}{t}{x}{\Delta}}
    {\suc \; v : \contains{\gamma \comma t'}{\Gamma \comma x'}{\suc i}{t}{x}{\Delta \comma x'}}
  \end{mathpar}

  We lift the operation $\op{x}{y}{z}$ and its algebraic properties to an operation $\opsquared{(x_l \comma x_r)}{(y_l \comma y_r)}{(z_l \comma z_r)}$ on pairs of multiplicities.
  The base case $\constr{0}$ splits the usage annotation $x$ of type $\Usage_{idx}^{\func{2}}$ into $y$ and $z$ (the leftovers).
  Note that the remaining context $\Gamma$ is preserved unused as a leftover.
  This splitting $\opsquared{x}{y}{z}$ is as per the usage algebra provided by the developer for the index $idx$.
  In our Agda implementation, $\opsquared{x}{y}{z}$ is actually a trivially satisfiable implicit argument if $\opsquared{x}{y}{z}$ is inhabited and an unsatisfiable argument otherwise.
  The inductive case $\suc$ appends the type $t'$ to the typing context, and the usage annotation $x'$ to both the input and output usage contexts.

\end{nidefinition}

\begin{example}[Variable reference]
  In $\func{egVar}$ we type a variable reference $\suc \constr{0}$ with type $\channel{\unit}{\li}$ and usage $\li$.
  We must show that the variable with index $\suc \constr{0}$ is of type $\channel{\unit}{\li}$ and has a usage annotation $\li$ in an environment with a typing context $(\constr{[]} \comma \channel{\unit}{\li} \comma \unit)$ and a usage context $(\constr{[]} \comma \lio \comma \lio)$.
  The \textsc{VarRef} constructors are completely determined by the variable index $\suc \; \constr{0}$ in the type.
  The constructor $\suc$ steps under the outermost variable in the context, preserving its usage annotation $\lio$ from input to output.
  The constructor $\constr{0}$ asserts that the next variable is of type $\channel{\unit}{\li}$, and that the usage annotation $\lio$ can be split such that $\op{\lio}{\li}{\lo}$ --- $\func{\cdot-compute^r}$ automatically fulfills this proof obligation.
  \begin{flalign*}
  & \func{egVar} \; : \; \contains{(\constr{[]} \comma \channel{\unit}{\li} \comma \unit)} {\constr{[]} \comma \lio \comma \lio)} {\suc \constr{0}} {\channel{\unit}{\li}} {\li} {(\constr{[]} \comma \lo \comma \lio)}\\
  & \func{egVar} \; = \; \suc \constr{0}
  \end{flalign*}
\end{example}

\begin{nidefinition}[\textsc{Types}: typing processes] \label{def:types}
  The \textsc{Types} typing relation for the resource-aware \picalc{} processes is presented below.
  For convenience, we reuse the constructor names introduced for the syntax in \autoref{syntax}.
  \begin{mathpar}
    \datatype{
      \gamma : \PreCtx_n \\
      P : \Process_n \\
      \stacked{
        idxs : \Idxs_n \\\\
        \Gamma \; \Delta : \Ctx_{idxs}}}
    {\types{\gamma}{\Gamma}{P}{\Delta} : \Set}
    \; \textsc{Types}

    \inferrule
    { }
    {\PO : \types{\gamma}{\Gamma}{\PO}{\Gamma}}

    \inferrule
    {t : \Type \\ x : \Usage_{idx}^{\func{2}} \\ y : \Usage_{idx'} \\\\
     cont : \types{\gamma \comma \channel{t}{x}}{\Gamma \comma (y \comma y) }{P}{\Delta \comma \lz}}
    {\new \; t \; x \; y \; cont : \types{\gamma}{\Gamma}{\new P}{\Delta}}

    \inferrule
        {\stacked{
            chan : \contains{\gamma \hspace{1.0em}}{\Gamma \hspace{1.0em}}{i}{\channel{t}{x}}{\li}{\Xi} \\\\
            cont \hspace{0.3em} : \types{\gamma \comma t}{\Xi \comma x}{P \hspace{3.8em}}{\Theta \comma \lz}}}
        {\recv{chan}{} cont : \types{\gamma}{\Gamma}{\recv{i}{}P}{\Theta}}

    \inferrule
        {\stacked{
            chan : \contains{\gamma}{\Gamma \hspace{0.1em}}{i}{\channel{t}{x}}{\lo}{\Delta} \\\\
            loc \hspace{0.9em} : \contains{\gamma}{\Delta}{j}{t \hspace{2.8em}}{x \hspace{0.2em}}{\Xi} \\\\
            cont \hspace{0.3em} : \types{\gamma}{\Xi}{\hspace{0.4em}P\hspace{3.8em}}{\Theta}}}
        {\send{chan}{loc} cont : \types{\gamma}{\Gamma}{\send{i}{j}P}{\Theta}}

    \inferrule
    {l : \types{\gamma}{\Gamma}{P\hspace{0.3em}}{\Delta} \\\\
     r : \types{\gamma}{\Delta}{Q}{\Xi}}
    {\comp{l}{r} : \types{\gamma}{\Gamma}{\comp{P}{Q}}{\Xi}}
  \end{mathpar}

  The inaction process in rule $\PO$ does not change usage annotations.
  The scope restriction in rule $\new$ expects three arguments: the type $t$ of data being transmitted; the usage annotation $x$ of what is being transmitted; and the multiplicity $y$ given to the channel itself.
  This multiplicity $y$ is used for both input and output, so that they are balanced.
  The continuation process $P$ is provided with the new channel with usage annotation $y \comma y$, which it must completely exhaust.
%
  The input process in rule $\recv{}{}$ requires a channel $chan$ at index $i$ with usage $\li$ available, such that data with type $t$ and usage $x$ can be sent over it.
  Note that the index $i$ is determined by the syntax of the typed process.
  We use the leftovers $\Xi$ to type the continuation process, which is also provided with the received element --- of type $t$ and multiplicity $x$ --- at index $\constr{0}$.
  The received element $x$ must be completely exhausted by the continuation process.
%
  Similarly to input, the output process in rule $\send{}{}$ requires a channel $chan$ at index $i$ with usage $\lo$ available, such that data with type $t$ and usage $x$ can be sent over it.
  We use the leftover context $\Delta$ to type the transmitted data, which needs an element $loc$ at index $j$ with type $t$ and usage $x$, as per the type of the channel $chan$.
  The leftovers $\Xi$ are used to type the continuation process.
  Note that both indices $i$ and $j$ are determined by the syntax of the typed process.
%
  Parallel composition in rule $\comp{}{}$ uses the leftovers of the left-hand process to type the right-hand process.
  Indeed, \autoref{thm:subject-congruence} shows that an alternative rule where the resources are first threaded through $Q$ is admissible too.
\end{nidefinition}

\begin{example}[Typing derivation (Continued)]
\label{example-derivation}
We provide the typing derivation for the courier system defined in \autoref{example-process}.
For the sake of simplicity, we instantiate these processes with concrete variable references before typing them.

The receiver defined by the $\func{recv}$ process receives data along the channel with index $\constr{0}$, which needs to be of type $\channel{t}{u}$ for some $t$ and $u$.
After receiving twice, the process ends: we must not be left with any unused multiplicities, thus $u = \lz$.
We will use graded types to keep track of the exact number of times communication happens.
Whatever the input multiplicity of the channel, we will consume $2$ of it and leave the remaining as leftovers.
The sender defined by the $\func{send}$ process sends data along the channel with index $\constr{0}$, which needs to be of type $\channel{t}{u}$ for some $t$ and $u$.
We instantiate $t$ (the type of data that the sender sends) to the trivial channel $\channel{\unit}{\func{\omega}}$.
As per the type of the process $\func{recv}$, $u = \lz$.
We will transmit once, thus use $\suc{\constr{0}}$ output multiplicity, and leave the rest as leftovers.
Agda can uniquely determine the arguments required by the $\new{}$ constructor.
\begin{align*}
   & \func{recvwt} \;  : \; \types{\gamma \comma \channel{t}{\lz}  }{\Gamma \comma (\suc \suc l \comma r)  }{\func{recv} \; \constr{0}  }{\Gamma \comma (l \comma r)} \\
   & \func{recvwt} \;  = \; \recv{\constr{0}}{} \recv{(\suc \constr{0})}{} \PO \\
   & \func{sendwt} \;  : \; \types{\gamma \comma \channel{\channel{\unit}{\func{\omega}}}{\lz}  }{\Gamma \comma (l \comma \suc r)  }{\func{send} \; \constr{0}  }{\Gamma \comma (l \comma r)}  \\
   & \func{sendwt} \;  = \; \new{} \; \_ \; \_ \; \zero \; (\send{\suc \constr{0}}{\constr{0}} \PO)
\end{align*}

Dually, the courier defined by the $\func{carry}$ process expects input multiplicities for the channels shared with $\func{send}$ and output multiplicities for the channel shared with $\func{recv}$.
We can now compose these processes in parallel and type the courier $\func{system}$.
\begin{align*}
& \func{carrywt} && : \types{\gamma \comma \channel{t}{\lz} \comma \channel{t}{\lz} \comma \channel{t}{\lz}\\ & &&}{\Gamma \comma (\suc lx \comma rx) \comma (\suc ly \comma ry) \comma (lz \comma \suc \suc rz)\\ & &&}{\func{carry} \; (\suc \suc \constr{0}) \; (\suc \constr{0}) \; \constr{0}\\ & &&}{\Gamma \comma (lx \comma rx) \comma (ly \comma ry) \comma (lz \comma rz)} & \\
& \func{carrywt} && = \recv{(\suc \suc \constr{0})}{} \recv{(\suc \suc \constr{0})}{} \send{(\suc \suc \constr{0})}{\suc \constr{0}} \send{(\suc \suc \constr{0})}{\constr{0}} \PO \\
& \func{systemwt} && : \; \types{\constr{[]}}{\constr{[]}}{\func{system}}{\constr{[]}} \\
& \func{systemwt} && = \new{} \; \_ \; \_ \; \_ \; ( \func{sendwt} \comp{}{ \new{} \; \_ \; \_ \; \_ } \; ( \func{sendwt} \comp{}{ \new{} \; \_ \; \_ \; \_ } \; ( \func{recvwt} \comp{}{ \func{carrywt} })))
\end{align*}
\end{example}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Meta-Theory} \label{meta-theory}

We have mechanised subject reduction for our \picalc{} with leftovers in 850 lines of Agda code.
The meta-theory of resource-aware type systems often needs to reason on typing derivations modulo associativity in the allocation of resources.
For type systems using context splitting side conditions, this means applying associativity lemmas to recompute context splits; for type systems using leftover typing it does not.
As an example, the proof that $\constr{comp-asssoc}$ preserves typing proceeds by deconstructing the input derivation into $\comp{P}{(\comp{Q}{R})}$ and reassembling it as $\comp{(\comp{P}{Q})}{R}$ without the need of any extra reasoning.

All the reasoning carried out in our type safety proofs is based on the algebraic properties introduced in \autoref{multiplicities} -- the exception to this is $\func{\cdot -compute^r}$, only there for the user's convenience.
  We lift the operation $\opsquared{x}{y}{z}$ and its algebraic properties to an operation $\opctx{\Gamma}{\Delta}{\Xi}$ on usage contexts that have the same underlying context of indices.
The algebraic properties of the algebras allow us to see a typing derivation $\types{\gamma}{\Gamma}{P}{\Delta}$ as a unique \emph{arrow} from $\Gamma$ to $\Delta$, and to freely compose and reason with arrows with the same typing context and a matching output and input usage contexts.

Leftover typing also allows us to state a \emph{framing} theorem showing that adding or subtracting arbitrary usage annotations to the input and output usage contexts preserves typing -- one can understand a typing derivation independently from its unused resources.
With framing one can show that $\constr{comp-comm}$ preserves typing: in $\comp{P}{Q}$ the typing of $P$ and $Q$ is independent of one another.
\begin{nitheorem}[Framing]
  \label{thm:framing}
  Let $\types{\gamma}{\Gamma_l}{P}{\Xi_l}$.
  Let $\Delta$ be such that $\opctx{\Gamma_l}{\Delta}{\Xi_l}$.
  Then for any $\Gamma_r$ and $\Xi_r$ where $\opctx{\Gamma_r}{\Delta}{\Xi_r}$ it holds that $\types{\gamma}{\Gamma_r}{P}{\Xi_r}$.
\end{nitheorem}

Leftover typing allows \emph{weakening} and \emph{strengthening} to acquire a more general form where linear variables can freely be added or removed from context too -- as long as they are added and removed to and from both the input and output contexts.

\begin{nitheorem}[Weakening]
  \label{thm:weakening}
  Let $\func{ins}_i$ insert an element into a context at position $i$.
  Let $P$ be well typed in $\types{\gamma}{\Gamma}{P}{\Xi}$.
  Then, lifting every variable greater than or equal to $i$ in $P$ is well typed in
  $\types{\func{ins}_i \; t \; \gamma}{\func{ins}_i \; x \; \Gamma}{\func{lift}_i \; P}{\func{ins}_i \; x \; \Xi}$.
\end{nitheorem}

\begin{nitheorem}[Strengthening]
  \label{thm:strengthening}
  Let $\func{del}_i$ delete the element at position $i$ from a context.
  Let $P$ be well typed in $\types{\gamma}{\Gamma}{P}{\Xi}$.
  Let $i$ be a variable not in $P$, such that $uP \; : \; \Unused_i \; P$.
  Then lowering every variable greater than $i$ in $P$ is well typed in $\types{\func{del}_i \; \gamma}{\func{del}_i \; \Gamma}{\func{lower}_i \; P \; uP}{\func{del}_i \; \Xi}$.
\end{nitheorem}

Subject congruence states that structural congruence (\autoref{def:equals}) preserves the well-typedness of a process.
\begin{nitheorem}[Subject Congruence]
  \label{thm:subject-congruence}
  Let $P$ and $Q$ be processes. If $P \eq{} Q$ and $\types{\gamma}{\Gamma}{P}{\Xi}$, then $\types{\gamma}{\Gamma}{Q}{\Xi}$.
\end{nitheorem}

Finally, subject reduction states that reducing on a channel $c$ (\autoref{def:reduces}) preserves the well-typedness of a process --- after consuming $\lio$ from $c$ if $c$ is an $\constr{external}$ channel.  Below we use $\containsusage{\Gamma}{i}{x}{\Delta}$ to stand for $\contains{\gamma}{\Gamma}{i}{t}{x}{\Delta}$ for some $\gamma$ and $t$.
\begin{nitheorem}[Subject Reduction]
  \label{thm:subject-reduction}
  Let $\types{\gamma}{\Gamma}{P}{\Xi}$ and $P \reduce{c} Q$.
  If $c$ is $\constr{internal}$, then $\types{\gamma}{\Gamma}{Q}{\Xi}$.
  If $c$ is $\constr{external} \; i$ and $\containsusage{\Gamma}{i}{\lio}{\Delta}$, then $\types{\gamma}{\Delta}{Q}{\Xi}$.
\end{nitheorem}
We refer to Appendix \ref{app:type-safety} for a more detailed account of the mechanised proofs.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Conclusions, Related and Future Work}

\paragraph*{Extrinsic Encodings}

Extrinsic encodings define a syntax (often well-scoped) and a runtime semantics prior to any type system.
This allows one to talk about ill-typed terms, and defers the proof of subject reduction to a later stage.
%
To the best of our knowledge, leftover typing makes its appearance in 1994, when Ian Mackie first uses it to formulate intuitionistic linear logic \cite{Mackie}.
Allais \cite{Allais2018a} uses leftover typing to mechanise in Agda a bidirectional type system for the linear \lambdacalc{}.
He proves type preservation and provides a decision procedure for type checking and type inference.
In this paper, we follow Allais \cite{Allais2018a} and apply leftover typing to the \picalc{} for the first time.
We generalise the usage algebra, leading to linear, graded and shared type systems.
Drawing from quantitative type theory (by McBride and Atkey \cite{McBride2016,Atkey2018}), in our work we too are able to talk about fully consumed resources --- e.g., we can transmit $\lz$ multiplicities of a fully exhausted channel.
%
Recent years have seen an increase in the efforts to mechanise resource-aware process algebras, but one of the earliest works is the mechanisation of the linear \picalc{} in Isabelle/HOL by Gay \cite{Gay2001}.
Gay encodes the \picalc{} with linear and shared types using de Bruijn indices, a reduction relation and a type system posterior to the syntax.
However, in his work typing rules demand user-provided context splits, and variables with consumed usage annotations are erased from context.
We remove the demand for context splits, preserve the ability to talk about consumed resources, and adopt a more general usage algebra.
%
Orchard et al. introduce Granule \cite{Orchard}, a fully-fledged functional language with graded modal types, linear types, indexed types and polymorphism.
Modalities include exact usages, security levels and intervals; resource algebras are pre-ordered semirings with partial addition.
The authors provide bidirectional typing rules, and show the type safety of their semantics.
%
The work by Goto et al. \cite{Goto2016a} is, to the best of our knowledge, the first formalisation of session types which comes along with a mechanised proof of type safety in Coq.
The authors extend session types with polymorphism and pattern matching.
They use a locally-nameless encoding for variable references, a syntax prior to types, and an LTS semantics that encodes session-typed processes into the \picalc{}.
Their type system uses reordering of contexts and extrinsic context splits, which are not needed in our work.

\paragraph*{Intrinsic Encodings}

Intrinsic encodings merge syntax and type system.
As a result, one can only ever talk about well-typed terms, and the reduction relation by construction carries a proof of subject reduction.
Significantly, by merging the syntax and static semantics of the object language one can fully use the expressive power of the host language.
%
Thiemann formalises in Agda the MicroSession (minimal GV \cite{Gay2010}) calculus with support for recursion and subtyping \cite{Thiemann2019}.
As Gay does in \cite{Gay2001}, context splits are given extrinsically, and exhausted resources are removed from typing contexts altogether.
The runtime semantics are given as an intrinsically typed CEK machine with a global context of session-typed channels.
%
In their recent paper, Ciccone and Padovani mechanise a dependently-typed linear \picalc{} in Agda \cite{Ciccone}.
Their intrinsic encoding allows them to leverage Agda's dependent types to provide a dependently-typed interpretation of messages --- to avoid linearity violations the interpretation of channel types is erased.
Message input is modeled as a dependent function in Agda, and as a result message predicates, branching, and variable-length conversations can be encoded.
In contrast to our work, their algebra is on the multiplicities $0$, $1$, $\omega$, and top-down context splitting proofs must be provided.
%
In another recent work, Rouvoet et al. provide an intrinsic type system for a \lambdacalc{} with session types \cite{Rouvoet2020}.
They use proof relevant separation logic and a notion of a supply and demand \emph{market} to make context splits transparent to the user.
Their separation logic is based on a partial commutative monoid that need not be deterministic nor cancellative.
Their typing rules preserve the balance between supply and demand, and are extremely elegant.
They distill their typing rules even further by modelling the supply and demand market as a state monad.

\paragraph*{Other Work}

Castro et al. \cite{Castro2020} provide tooling for locally-nameless representations of process calculi in Coq, where de Bruijn indices are less popular than in Agda or Idris.
They use their tool to help automate proofs of subject reduction for a type system with session types.
%
Orchard and Yoshida \cite{OrchardY16} embed a small effectul imperative language into the session-typed \picalc{}, showing that session types are expressive enough to encode effect systems.
%
Based on contextual type theory \cite{Pientkaa,Pientka}, LINCX \cite{Georges2017} extends the linear logical framework LLF \cite{Cervesato1996} by internalising the notion of bindings and contexts.
The result is a meta-theory in which HOAS encodings with both linear and dependent types can be described.
The developer obtains for free an equational theory of substitution and decidable typechecking without having to encode context splits within the object language.
%
Further work on mechanisation of the \picalc{} \cite{Henry-Gerard1999,Honsell2001a,Bengtson2013,Despeyroux2000,Affeldt2008}, focuses on non-linear variations, differently from our range of linear, graded and shared types.

\paragraph*{Conclusions and Future Work}

We provide a well-scoped syntax and a semantics for the \picalc{}, extrinsically define a type system on top of the syntax capable of handling linear, graded and shared types under the same unified framework and show subject reduction.
We avoid extrinsic context splits by defining a type system based on leftover typing \cite{Allais2018a}.
As a result, theorems like framing, weakening and strengthening can now be stated also for the linear \picalc{}.
Our work is fully mechanised in around 1850 lines of code in Agda \cite{Zalakain2020Agda}.

As future work we intend to expand our framework to include infinite behaviour by adding process replication, which is challenging, as to prove subject congruence one needs to uniquely determine the resources consumed by a process --- e.g., by adding type annotations to the syntax.
Orthogonally, we aim to investigate making our typing rules bidirectional which would allow us to provide a decision procedure for type checking processes in a given set of algebras.
Finally, we will use our \picalc{} with leftovers as an underlying framework on top of which we can implement session types and other advanced type theories.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\paragraph*{Acknowledgments}

We want to thank Erika Kreuter, Wen Kokke, James Wood, Guillaume Allais, Bob Atkey, and Conor McBride for their valuable suggestions.

%%
\clearpage
\bibliographystyle{splncs04}
\bibliography{paper}

%%
\clearpage
\appendix
\changetext{}{10em}{-5em}{-5em}{}\input{appendix.tex}
\end{document}


% Created: Enze Chen, July 2017
% Last edited: Enze Chen, December 2017
%
% Chapter 8 of the MSE 142 coursereader. This chapter discusses time-dependent perturbation theory. The various approximations for the probability amplitudes are discussed, and particular focus is drawn to sinusoidal perturbations. These model electric fields, which can be applied to stimulated emission in lasers.

% Uncomment the following three lines and last line to individually compile this chapter
%\documentclass[12pt, english]{book}
%\usepackage{142crstyle}
%\begin{document}

\chapter[Perturbation Theory]{Time-dependent Perturbation Theory} \label{ch:pert}
%{ \doublespacing
For the final topic covered in this text, we would like to understand the interaction of light with matter---how materials absorb light, emit light, and the basic ideas behind the operation of the laser. Much of the phenomenon here can be explained using QED, but for the sake of simplicity we will return to the single-particle wave functions used in first quantization. However, one of the key differences between these interactions and our previous examples is that our Hamiltonian is now time-dependent, so instead of solving for a stationary state we must now solve for a superposition state. This framework allows us to model atomic transitions between energy levels due to the emission or absorption of radiation by an atom.

\section{General formalism}
To start off, let's suppose we have a quantum system with known Hamiltonian $H_0(r)$\footnote{We use $r$ here to represent the position vector, which you can view equivalent to $x$.} which we have already solved the \Sch\ equation for, i.e.
\begin{equation*}
	H_0\Psi_n = i\hbar \pdv{\Psi_n}{t}
\end{equation*}
with stationary state solutions
\begin{equation*}
	\Psi_n(r,t) = \psi_n(r)e^{-iE_nt/\hbar}
\end{equation*}

We can now apply a small perturbation $H'(r,t)$ of strength $\lambda$ such that the total Hamiltonian becomes
\begin{tcolorbox}[title = Hamiltonian for small perturbations] \vspace{-2ex}
	\begin{equation}
	\hat{H}(r,t) = H_0(r) + \lambda H'(r,t) \label{eq:ham-pert}
	\end{equation}
\end{tcolorbox}

where all of the time-dependence is accounted for by the second term. Here, $\lambda \ll 1$ characterizes the strength of the perturbation. As we will see, the problem becomes too difficult to solve in general for arbitrary $\lambda$, but in the case when $\lambda$ is small, we can develop a simple approximate theory. The theory will be quite general---only at the end will we apply it to specific examples associated the interactions between light and matter. In any case, the time-dependent \Sch\ equation that we are now trying to solve becomes
\begin{equation}
	\left(H_0 + \lambda H'\right)\Psi = i\hbar \pdv{\Psi}{t} \label{eq:sch-pert}
\end{equation}

Since this general equation is impossible to solve exactly, we will employ the method of \textbf{eigenfunction expansion}, which you've already seen for the particle in a box. We expand the general solution $\Psi(r,t)$ we are trying to find in terms of the known solutions of $H_0$:
\begin{equation}
	\Psi(r,t) = \sum_n c_n(t) \Psi_n(r,t) \label{eq:exp-pert}
\end{equation}
where the individual states $\Psi_n$ are orthonormal basis vectors. This again corresponds to a quantum superposition state with $c_n(t)$ the amplitude of each state in the superposition and $\abs{c_n(t)}^2$ the probability that a measurement finds the system in state $n$ at time $t$ (technically that a measurement of the energy will return $E_n$). Since we are trying to solve for the case where there is only a slight perturbation to the known Hamiltonian, it's a good guess to try to find solutions which can be expressed in terms of the known solutions of $H_0$. Our goal will be to find a general equation for the $c_n$'s, since the probability amplitudes are now changing in time. Once we know these, we know the full time-dependent evolution of the wave function. \par

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Probability amplitude}
If we substitute the expansion in Equation~\ref{eq:exp-pert} into our time-dependent \Sch\ equation, we find
\begin{align*}
	\left(H_0 + \lambda H'\right)\Psi &= i\hbar \pdv{\Psi}{t} \\
	H_0 \sum_n c_n(t) \Psi_n(r,t) + \lambda H'\sum_n c_n(t) \Psi_n(r,t) &= i\hbar \pdv{t}\sum_n c_n(t) \Psi_n(r,t) \\
	i\hbar\sum_n c_n(t) \pdv{\Psi_n}{t} + \lambda H'\sum_n c_n(t) \Psi_n(r,t) &= i\hbar \sum_n c_n(t) \pdv{\Psi_n}{t} + i\hbar \sum_n \dv{c_n(t)}{t} \Psi_n(r,t) \\
	\lambda H'\sum_n c_n(t) \Psi_n(r,t) &= i\hbar \sum_n \dot{c}_n(t) \Psi_n(r,t)
\end{align*}

In the last line we used dot notation to represent the time derivative of a quantity, such that $\dot{c_n}=\dv{c_n}{t}$. We take the last line and multiply both sides on the left with $\bra{\Psi_k}$ to obtain
\begin{equation*}
	\lambda \sum_n c_n \braket{\Psi_k}{H'\Psi_n} = i\hbar \sum_n \dot{c}_n \braket{\Psi_k}{\Psi_n}
\end{equation*}

Why is this useful? Because we claimed that the stationary state solutions were orthogonal, this allows us to pick out just one term in the sum on the right hand side, namely the term with $k=n$. All the other terms are zero. Thus, the final equation we find is
\begin{tcolorbox}[title = Relationship for $c_k$] \vspace{-2ex}
	\begin{equation}
		i\hbar \dot{c}_k = \lambda \sum_n c_n H_{kn}' \label{eq:cdot}
	\end{equation}
\end{tcolorbox}

Here, $H_{kn}' = \braket{\Psi_k}{H'\Psi_n}$. These are typically called \textbf{matrix elements} because the perturbing Hamiltonian is a matrix operator and we are interested in the element in the $k$th row and $n$th column of this matrix. Equation~\ref{eq:cdot} is an infinite series of coupled differential equations and not so easy to deal with. But so far, we have been completely general, i.e. we have not made use of the fact that we are trying to solve for the case of a small perturbation. To do this, we guess the solution
\begin{equation}
	\boxed{c_k(t) = c_k^{(0)} + \lambda c_k^{(1)}(t) + \lambda^2 c_k^{(2)}(t) + \cdots} \label{eq:c-pow}
\end{equation}
which we obtained by expanding $c_k(t)$ in a \textbf{power series in} $\lambda$. The superscript in parentheses indicates the order of the approximation for $c_n$. Again, this is a reasonable assumption in the limit when $\lambda$ is small.\footnote{This is largely a convergence argument, and a brief explanation is given by \href{http://tutorial.math.lamar.edu/Classes/CalcII/PowerSeriesandFunctions.aspx}{Paul Dawkins}.} In the following, what we'll do is find an equation for the first order correction term $c_k^{(1)}$. If we substitute the above equation into both sides of Equation~\ref{eq:cdot} and equate powers of $\lambda$ (since $\lambda$ is arbitrary, those terms with the same power must be equal), we obtain the following equations:
\begin{align}
	i\hbar \dot{c}_k^{(0)} &= 0 \label{eq:cdot0} \\
	i\hbar \dot{c}_k^{(1)} &= \sum_n H_{kn}' c_n^{(0)} \label{eq:cdot1} \\
	&\vdots \nonumber \\
	i\hbar \dot{c}_k^{(n)} &= \sum_n H_{kn}' c_n^{(n-1)} \label{eq:cdotn}
\end{align}

So, if we can find $c_k^{(0)}$, we can use this to find $c_k^{(1)}$, then $c_k^{(2)}$, and so on. \par

As an example, let's assume at time $t=0$, the system is sitting in a stationary state of $H_0$, say $\Psi_l$, such that
\begin{equation*}
	\Psi(r,t)|_{t=0} = \Psi_l(r,t) = \sum_n c_n(t) \Psi_n(r,t)
\end{equation*}

So what is $c_n^{(0)}$? Well, the summation runs over state $l$, so it must be the case that all the $c_n$'s are zero except when $n=l$, in which case $c_l=1$. This can be written simply in terms of the \textbf{Kronecker delta function} as
\begin{equation}
	c_n^{(0)} = \delta_{n,l}
\end{equation}
which is 0 if $n\neq l$ and 1 if $n=l$.\footnote{The Kronecker delta function is analogous to the Dirac delta function, just applied to discrete arguments.} So now we have $c_k^{(0)}$ as set by the initial conditions and we can solve for the first order correction term. Using Equation~\ref{eq:cdot1},
\begin{equation}
	i\hbar \dot{c}_k^{(1)} = \sum_n H_{kn}' \delta_{n,l} = H_{kl}'
\end{equation}

which leads to
\begin{tcolorbox}[title = First order perturbation coefficient] \vspace{-2ex}
	\begin{equation}
		c_k^{(1)}(t) = \frac{1}{i\hbar} \int_{0}^{t_0} H_{kl}'(r,t) \dd{t} \label{eq:c1}
	\end{equation}
\end{tcolorbox}

The square of this quantity gives the probability of making an atomic transition from state $\Psi_l$ to state $\Psi_k$ after some time $t_0$, at least to first order. If higher accuracy is required, we can easily write down the equation for the second order approximation as follows:
\begin{equation*}
	i\hbar \dot{c}_k^{(2)} = \sum_{m\neq l} H_{km}'c_m^{(1)}
\end{equation*}

Inserting Equation~\ref{eq:c1} into the right hand side and taking the integral, we get
\begin{equation}
	c_k^{(2)} = -\frac{1}{\hbar^2} \sum_{m\neq l} \int_{t'}^{t_0} H_{km}'(r,t) \left[ \int_{0}^{t'} H_{ml}'(r,t) \dd{t} \right] \dd{t}
\end{equation}

Of course, we could theoretically continue doing these successive approximations to get higher order corrections and more accurate calculations of $c_k(t)$. The second order approximation allows us to model an intermediate transition from $\Psi_l$ to some state $\Psi_m$ and then finally to $\Psi_k$. In most cases, of course, the first order approximation is sufficient, and certainly in our case as a pedagogical example of the theory.\footnote{Now unless otherwise stated, assume $c_k(t)$ refers to the first order approximation $c_k^{(1)}(t)$ because we set $c^{(0)}_{j \neq l} = 0$.}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Separation of variables}
Before we get to the application of this theory, let's take a closer look at Equation~\ref{eq:c1}. One can often factor the perturbation Hamiltonian as $H'(r,t) = \bar{H}'(r)f(t)$, in which case the matrix element $H'_{kl}$ can be written as
\begin{align*}
	H'_{kl} &= \braket{\Psi_k}{H'\Psi_l} \\
	&= f(t) \braket{\psi_ke^{-iE_kt/\hbar}}{\bar{H}'\psi_le^{-iE_lt/\hbar}} \\
	&= f(t) \braket{\psi_k}{\bar{H}'\psi_l}e^{i(\omega_k-\omega_l)t} \\
	&= f(t) \bar{H}'_{kl} e^{i\omega_{kl}t}
\end{align*}

where we have defined a new matrix element $\bar{H}'_{kl}$ and the quantity $\omega_{kl} = \omega_k - \omega_l = (E_k - E_l)/\hbar$. Note that the matrix element is in principle easy to calculate, at least numerically. We know the solutions of the unperturbed Hamiltonian and therefore can calculate this integral for arbitrary $k$ and $l$. We then have another form of Equation~\ref{eq:c1} for the time-dependent amplitude:
\begin{equation}
	\boxed{c_k(t) = \frac{\bar{H}'_{kl}}{i\hbar} \int_{0}^{t_0} e^{i\omega_{kl}t} f(t) \dd{t}} \label{eq:c1-sep}
\end{equation}

The first order approximation of the probability of the system making a transition from an initial state $l$ to state $k$ is therefore
\begin{tcolorbox}[title = Transition probability] \vspace{-2ex}
	\begin{equation}
		P_{l \rightarrow k} = \abs{c_k}^2 = \abs{\frac{\bar{H}'_{kl}}{\hbar}}^2 \abs{\int_{0}^{t} e^{i\omega_{kl}t'} f(t') \dd{t'}}^2
	\end{equation}
\end{tcolorbox}

This is the fundamental result that we will apply in the next section.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Sinusoidal perturbation}
As a simple application of the previous equation for the transition probability, let's suppose that at time $t<0$ the atom is in a stationary state $l$. Starting at $t=0$, we apply a monochromatic electromagnetic wave that gives a sinusoidal perturbation $H'(r,t) = 2H'(r)\cos(\omega t)$. Substituting this expression into Equation~\ref{eq:c1-sep}, we find
\begin{align*}
	c_k(t) &= \frac{H'_{kl}}{i\hbar} \int_{0}^{t_0} e^{i\omega_{kl}t} \left( 2\cos(\omega t) \right) \dd{t} \\
	&= \frac{H'_{kl}}{i\hbar} \int_{0}^{t_0} e^{i\omega_{kl}t} \left(e^{i\omega t} + e^{-i\omega t} \right) \dd{t} \\
	&= \frac{H'_{kl}}{i\hbar} \int_{0}^{t_0} e^{i(\omega_{kl}+\omega)t} + e^{i(\omega_{kl}-\omega)t} \dd{t} \\
	&= -\frac{H'_{kl}}{\hbar} \left[ \frac{e^{i(\omega_{kl}+\omega)t}}{\omega_{kl}+\omega} + \frac{e^{i(\omega_{kl}-\omega)t}}{\omega_{kl}-\omega} \right]\bigg|_0^{t_0} \\
	\Aboxed{c_k(t) &= -\frac{H'_{kl}}{\hbar} \left[ \frac{e^{i(\omega_{kl} + \omega)t_0} - 1}{\omega_{kl}+\omega} + \frac{e^{i(\omega_{kl} - \omega)t_0} - 1}{\omega_{kl}-\omega} \right]} \numberthis
\end{align*}

To dissect this equation, let's consider the case of absorption, i.e. a transition from state $l$ to a higher energy state $k$ such that $\omega_{kl} > 0$. It is clear then from the denominators that for $\omega \approx \omega_{kl}$, the second term on the right hand side dominates over the first term. In addition, we have
\begin{align*}
	\omega &\approx \omega_{kl} = \frac{E_k - E_l}{\hbar} \\
	E_k &= E_l + \hbar \omega
\end{align*}
which shows that energy is conserved for the absorption of a quantum of energy $\hbar\omega$. We can further simplify the right hand side using the identity
\begin{equation*}
	e^{i\theta} - 1 = 2ie^{i\theta/2} \sin\left(\frac{\theta}{2}\right)
\end{equation*}

to obtain a cleaner expression for the transition probability:
\begin{align*}
	c_k(t) &= -\frac{H'_{kl}}{\hbar} \left[ \frac{e^{i(\omega_{kl} - \omega)t} - 1}{\omega_{kl}-\omega} \right] \\
	c_k(t) &= -\frac{H'_{kl}}{\hbar} \left[ \frac{2ie^{i(\omega_{kl} - \omega)t/2} \sin(\omega_{kl}-\omega)t/2}{\omega_{kl}-\omega} \right] \\
	\Aboxed{P_{l\rightarrow k} &= \abs{c_k}^2 = \frac{\abs{H'_{kl}}^2}{\hbar^2} \left[ \frac{\sin (\omega_{kl}-\omega)t/2}{(\omega_{kl}-\omega)/2} \right]^2} \numberthis \label{eq:prob-abs}
\end{align*}

This equation is plotted in Figure~\ref{fig:prob-abs} first as a function of $t$ and then as a function of $\omega_{kl}-\omega$. Remarkably, when plotted as a function of time, the transition probability oscillates sinusoidally between a maximum value and 0. At times that are integer multiples of $2\pi/\abs{\omega_{kl}-\omega}$, the particle is guaranteed to be in the lower state; thus if one wants to maximize their chances of causing a transition, they should only leave the perturbation on for odd multiples of $\pi/\abs{\omega_{kl}-\omega}$, which hopefully finds the system in the higher energy state. This cyclic behavior is called \textbf{Rabi flopping} and is an integral components of nuclear magnetic resonance (NMR) and quantum computing.

\begin{figure}[!h]
	\centering
	\subfloat[]{\includegraphics[width=0.51\linewidth]{absorption-t} \label{fig:prob-abs-t}}
	\subfloat[]{\includegraphics[width=0.46\linewidth]{absorption-w} \label{fig:prob-abs-w}}
	\caption{The transition probability from state $l$ to state $k$ plotted as \protect\subref{fig:prob-abs-t} a function of time, which displays oscillatory behavior with nodes at integer multiples of $2\pi/\abs{\omega_{kl}-\omega}$, and \protect\subref{fig:prob-abs-w} a function of frequency, which displays a sharp peak at $\omega=\omega_{kl}$ with width $4\pi/t$.}
	\label{fig:prob-abs}
\end{figure}

On the other hand, we see in Figure~\ref{fig:prob-abs-w} that in order to maximize the transition probability, the driving frequency $\omega$ should match the ``natural'' frequency $\omega_{kl}$. The peak has a finite width of $4\pi/t$ and becomes narrower and narrower as time progresses. Thus we see the manifestation of the uncertainty principle in the range of photon energies that are able to drive the transition. On a practical level, the complementarity between time and energy\footnote{Often expressed as $\Delta E \Delta t \ge \frac{\hbar}{2}$, or $\Delta \omega \Delta t \ge \frac{1}{2}$.} is something that we're probably familiar with. If we hear any note (frequency) for a very short amount of time, there is a lot of uncertainty as to what that note is. It's only when the note is extended that the true frequency of the sound wave is determined.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Application: Stimulated emission}
The precise control of the driving frequency to drive atomic transitions was leveraged by Charles Townes to construct the first \textbf{maser} (microwave amplification by stimulated emission of radiation) in 1953.\footnote{See this \href{https://physics.aps.org/story/v15/st4}{focus article} from \emph{Physics} about the history surrounding the maser and Townes' \href{https://journals.aps.org/pr/abstract/10.1103/PhysRev.99.1264}{original work}.} The maser was the precursor to the \textbf{laser}, which was invented seven years later and operates under the same principles to produce coherent radiation at visible wavelengths.\footnote{See T. H. Maiman \href{https://www.nature.com/nature/journal/v187/n4736/pdf/187493a0.pdf}{\emph{Nature}} \textbf{187} (1960).} \par

Both devices operate based on \textbf{stimulated emission}, which was predicted by Einstein back in 1917. Einstein knew that when photons of the right frequency strike an atom, the atom can ``absorb'' the photon and transition into a higher energy state (the electrons jump to higher energy levels). He then posited that it must be possible for the excited atom to return to a lower energy state by emitting a photon in a process known as \textbf{spontaneous emission}. Einstein, of course, did not stop there. He went one step further and postulated that if a photon of the right frequency encountered an excited atom, then there would be a probability that the photon will stimulate the excited atom to release a photon of identical frequency that traveled in the same direction. This process is illustrated in Figure~\ref{fig:laser}. Since we derived the probability of absorption in the text, we will leave it as an exercise to the reader to show that the probability of emission is in fact equivalent to Equation~\ref{eq:prob-abs}.

\begin{figure}[!h]
	\centering
	\subfloat[]{\includegraphics[width=0.20\linewidth]{absorption} \label{fig:absorption}} \qquad
	\subfloat[]{\includegraphics[width=0.23\linewidth]{spont-e} \label{fig:stimu-e}} \qquad
	\subfloat[]{\includegraphics[width=0.22\linewidth]{stimu-e} \label{fig:spont-e}}
	\caption{The three ways in which light interacts with atoms include: \protect\subref{fig:absorption} Absorption, where a photon is absorbed by the atom and an electron transitions into an excited state. \protect\subref{fig:stimu-e} Spontaneous emission, where an excited atom emits a photon and an electron transitions to a lower energy state. \protect\subref{fig:spont-e} Stimulated emission, where an incident photon causes an excited atom to emit a coherent photon.}
	\label{fig:laser}
\end{figure}

Where stimulated emission becomes exciting is when we have a population inversion of many atoms in the excited state that all have the possibility of emitting coherent radiation. Then we get an \emph{amplification} effect where a single incident photon leads to two resulting photons, which then turn into four photons, and so on in a chain reaction. This is the basis for how masers and lasers function, and scientists are getting increasingly creative with these optical resonators. In particular, nanowire lasers, pioneered by Peidong Yang at UC Berkeley,\footnote{See M. H. Huang et al. \href{http://science.sciencemag.org/content/292/5523/1897.full}{\emph{Science}} \textbf{292}, 5523 (2001).} have recently attracted a lot of excitement in the world of nano-optics because they have demonstrated near 100\% efficiency---every single photon they absorb is used to produce a photon of laser light.\footnote{See H. Zhu et al. \href{http://www.nature.com/nmat/journal/v14/n6/full/nmat4271.html}{\emph{Nature Materials}} \textbf{14} (2015).}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Summary}
To recap, in this chapter we analyzed a quantum mechanical system where the Hamiltonian was no longer time-independent, thus exposing us to the framework of time-dependent perturbation theory. It turns out, however, that when the perturbation is small, we can employ our friendly eigenfunction expansion to arrive at a very good first order approximation for the exact solution. We looked at a particular case when the perturbation term is sinusoidal, which is an appropriate model for an electromagnetic field, and the transition probability we derived was sinusoidal in time as well. We finished with an analysis of stimulated emission, which is fundamental to the operation of the laser.

%} % for doublespacing
%\end{document}


\section*{Legend}
In order to facilitate our work during the programming phase, we will use different names for some variables:

$ \vec{ns} $ will be coded as \verb!conflictWeight!.

$ \vec{x} $ will be coded as \verb!etSol!.

$ \vec{y} $ will be coded as \verb!conflict!.