\documentclass[12pt]{article}

\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{cite}
\usepackage[margin=1.2in]{geometry}

\providecommand{\eqn}[1]{eqn.~(\ref{eqn:#1})}
\providecommand{\tab}[1]{Table~\ref{tab:#1}}
\providecommand{\fig}[1]{Figure~\ref{fig:#1}}

\providecommand{\vecsymbol}[1]{\ensuremath{\boldsymbol{#1}}}
%\providecommand{\pv}{\vecsymbol{p}}
%\providecommand{\deltav}{\vecsymbol{\delta}}

\title{Observing Hour Angle Assignments\\
for the DESI Survey\\
\vspace{5mm}{\large\bf DESI-doc-3060-v1}}
\author{David Kirkby, Kyle Dawson}

\begin{document}
\maketitle

\section{Introduction}

This note briefly describes the algorithm used to assign a near-optimal observing hour angle (HA) to each tile in the DESI footprint~\cite{desi-717} and documents the result for the current baseline survey strategy~\cite{desi-1767, desi-1770}.

The algorithm is implemented in python code in the {\tt desisurvey} package\footnote{\url{https://github.com/desihub/desisurvey}} and the reader is referred there for implementation details. A jupyter notebook to create the plots in this note is provided under {\tt desisurvey/doc/nb/}. The LaTeX source for this note is maintained under {\tt desimodel/doc/tex/desi3060/}.

\section{Algorithm Description}

The algorithm is run separately for each program (DARK, GRAY, BRIGHT) and has two main inputs:
\begin{itemize}
    \item the date range to optimize the program for, and
    \item a list of tiles remaining to observe in the program.
\end{itemize}
The date range determines the available hours at each apparent local sidereal time (LST) for the specified program, taking into account planned shutdowns (during the annual monsoon and full-moon), expected weather outages each month, and the solar and lunar ephemerides that determine the time available to the program during each night. The list of tiles determines the required exposure time at each LST, given HA assignments and an exposure-time calculator.

The basic idea of the algorithm is to iteratively adjust the HA assignments of each tile to minimize a score function that accounts for two metrics:
\begin{itemize}
    \item the matching of available and planned LST usage, and
    \item the total required exposure time.
\end{itemize}
We run the algorithm in two different modes:
\begin{itemize}
    \item Start of survey: optimize all tiles over the nominal five-year survey dates.
    \item Afternoon planning: optimize all tiles not yet observed for the remainder of the survey.
\end{itemize}
The first mode is only used before the survey starts and then only needs to be rerun after a change in the definition of the tiles, programs, or nominal observing schedule. The second mode is run regularly during the survey and adjusts HA assignments to reflect actual observing progress and any schedule changes.

Most of the assumptions used in the survey planning and program definitions are listed in a text configuration parameter file\footnote{\url{https://github.com/desihub/desisurvey/blob/master/py/desisurvey/data/config.yaml}}. One parameter, in particular, limits the HA solution space by requiring that all tiles are observed above a minimum altitude angle of $30^\circ$.  In order to allow some leeway for exposure duration, we calculate a maximum $|\text{HA}|$ for each tile corresponding to its declination and a minimum altitude of $35^\circ$.

\subsection{Initialization}

The initial HA assignments that are subsequently optimized can be set in three different ways:
\begin{itemize}
    \item Read HAs from a file.
    \item Set all HAs to zero.
    \item Assign HAs to approximately match the cummulative distribution functions of available and planned LST usage.
\end{itemize}
The first method is used during afternoon planning, while the last two methods bootstrap the optimization at the start of the survey.

Assigning zero initial HAs minimizes the total exposure time required, but generally leads to a large mismatch between the available and planned LST usage. While conceptually simple, this approach is inefficient since it requires a large number of iterations to converge to a near-optimal solution. \fig{LST_zero0} compares the available and planned LST usage after initializing
all HAs to zero.

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{LST_zero0}
\caption{Available (red) and planned (blue) LST usage for the HA=0 initialization method.  The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram.  The LST axis starts at $-60^\circ$ and the gaps in the planned usage correspond to the breaks between the southern and northern galactic caps in the DESI footprint.}
\label{fig:LST_zero0}
\end{center}
\end{figure}

An alternative bootstrap initialization, which we refer to as the ``flat'' method, is to approximately match the cummulative distribution of available LST to planned LST usage. We first tabulate the available survey time $a_j$ in $n$ LST bins
$$
\theta_j \le \theta < \theta_{j+1} \quad , \quad \theta_j = (j/n) 360^\circ \; ,
$$
where $j$ ranges from $0$ to $n-1$, then calculate its cummulative distribution function (CDF) in $n+1$ steps as
$$
A_0 = 0 \quad , \quad
A_{j+1} = \frac{\sum_{k=0}^{j} a_k}{\sum_{k=0}^{n-1} a_k} \; .
$$
Next, we approximate the CDF of planned LST usage of $i = 0, 1, \ldots, N-1$ tiles with all HAs equal zero as:
$$
P_i = \frac{\sum_{k=0}^{i} \Delta t_k}{\sum_{k=0}^N \Delta t_k} \; ,
$$
where $\Delta t_k$ is the expected exposure time for tile $k$ at HA=0 and tiles are ordered in increasing right ascension (RA). Finally, we match the available and planned CDFs by adjusting each tile's LST $\tilde{\theta}_i$ using linear interpolation of the inverse mapping $A_j \rightarrow \theta_j$ evaluated at each $P_i$.  We then select
$$
\text{HA}_i = \tilde{\theta}_i - \text{RA}_i
$$
as the initial HA for tile $i$.

Since LST and RA are periodic, the initial HAs obtained with this method depend on an arbitrary choice of starting angle, which corresponds to an LST where all tiles will have HA=0. In practice, we repeat this initialization on a grid of possible starting angles and select the one with the minimum score function (defined below). \fig{LST_flat0} compares the available and planned LST usage after initializing all HAs with this method. \fig{HA_flat0} shows the distribution of initial HAs over the sky for each pass of each program.

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{LST_flat0}
\caption{Available (red) and planned (blue) LST usage for the flat initialization method.  The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram.  The LST axis starts at $-60^\circ$.}
\label{fig:LST_flat0}
\end{center}
\end{figure}

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{HA_flat0}
\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment using the ``flat'' initialization method.  Passes 0-1 (top row), 2-4 (middle row) and 5-7 (bottom row) correspond to the DARK (0-3), GRAY (4) and BRIGHT (5-7) programs.  Histograms show the HA distribution in each pass, color coded by the pass program: black (DARK), gray (GRAY) and orange (BRIGHT).}
\label{fig:HA_flat0}
\end{center}
\end{figure}

This CDF-matching ``flat'' method does a good job of matching the available and planned LST usage, but generally increases the total exposure time required more than necessary. The approximations in this method are that:
\begin{itemize}
    \item Exposure times are calculated for HA=0 and then used to estimate non-zero HAs for each tile.
    \item The contribution from each exposure is assumed to contribute at a single LST rather than being spread of LST in proportion to the length of the exposure.
    \item The CDF matching procedure enforces that the ordering of tile LSTs matches the ordering of tile RAs, but this may not be optimal.
\end{itemize}
The iterative improvement scheme described below does not have any of these limitations.

\subsection{Exposure Times}

Exposure times for observing during the DARK program are estimated as:
$$
\Delta t = \Delta t_{\text{nom}}\, f_{\text{dust}}\, f_{\text{airmass}}\,
f_{\text{seeing}}\, f_{\text{transp}} \; ,
$$
where the nominal exposure time $\Delta t_{\text{nom}}$ is specified by the program (1000 seconds for DARK and GRAY, and 300s for BRIGHT) and the remaining dimensionless factors correct for the actual versus nominal observing conditions: dust extinction, airmass, seeing, and atmospheric transparency.

The dust factor is fixed by the median value of $E_{B-V}(\text{RA}, \text{DEC})$ over the tile and given by:
$$
f_{\text{dust}} = 10^{\alpha E_{B-V}}
\quad, \quad \alpha = 2.6424 \; .
$$
The airmass factor is a function of the airmass $X(\text{DEC}, \text{RA})$ and given by:
$$
f_{\text{airmass}} = X^{1.25} \; .
$$

The remaining DARK program exposure factors are due to atmospheric seeing and transparency, which vary stochastically during actual observing. For the purposes of HA optimization, we only need to account for their mean time-integrated effects, $F_x = \langle f_x\rangle$.  Our assumptions for seeing and transparency are detailed in~\cite{desi-3087} and summarized in \tab{expfac}. The combined effect seeing and transparency, which we assume to be uncorrelated, is a $\simeq 9$\% increase in exposure time which we
round up to 10\%.

\begin{table}[htb]
\begin{center}
\begin{tabular}{lcccccccc}
Condition & Nominal & Median & Mean & $F_x$ \\
\hline
      Seeing & $1.1$" & $1.10$" & $1.17$" & $1.03$ \\
Transparency & $1.0$  & $0.98$  & $0.94$  & $1.06$ \\
\hline
\end{tabular}
\caption{Summary of atmospheric seeing and transparency assumptions, and estimated time-integrated exposure-time factors. See~\cite{desi-3087} for details.}
\label{tab:expfac}
\end{center}
\end{table}

Exposure times during the GRAY and BRIGHT programs have an additional factor due to scattered moonlight, but further study is needed to accurately estimate its impact.  We therefore assign average exposure time factors to account for seeing, transparency and moon of: 1.10 (DARK), ?? (GRAY) and ?? (BRIGHT). These factors multiply the exposure times derived from dust and airmass in our HA optimization algorithm, but are expected to have a negligible impact on the assigned HAs.

\subsection{Iteration}

For details on the iteration scheme, refer to the {\tt optimize.Optimizer.improve} method of the {\tt desisurvey} package. Here we just provide a high-level sketch of the algorithm.

Each iteration is governed by an HA adjustment size parameter, $\delta\text{HA}$, which we gradually decrease in an outer loop as described in the next section. Given an adjustment size, we select a single tile to adjust then recompute the planned LST usage using its new HA and exposure time (due to its change of airmass with HA). The total number of iterations (single-tile adjustments) required to obtain near-optimal HA assignments starting from HA=0 is typically 20--30 times the total number of tiles. The algorithm has several stochastic elements in order to avoid getting stuck in a local minimum, but uses a single source of pseudo-random numbers to ensure reproducibility.

The score function that each iteration attempts to improve combines two figures of merit which we refer to as RSME and LOSS.

RMSE measures the fractional deviation between the available ($A_i$) and planned ($P_i$) LST usage histograms using
$$
\text{RMSE} \equiv \frac{1}{\sum_i^n P_i}
\left( n \sum_i^n (s A_i - P_i)^2 \right)^{1/2}
$$
where the scale factor
$$
s = (\sum_i^n P_i) / (\sum_i^n A_i)
$$
normalizes the total available LST to the total planned usage so that RMSE measures deviations in shape only.  LOSS compares the total exposure time required with the current plan ($T_P$) with the minimum possible total time ($T_0$) when all tiles are observed with HA=0, using
$$
\text{LOSS} \equiv (T_P - T_0) / T_0 \; .
$$
After some experimentation, we combine these dimensionless metrics with equal weight,
$$
\text{SCORE} = \text{RMSE} + \text{LOSS} \; ,
$$
so that RMSE typically dominates during the first phase of optimization, then LOSS dominates towards the end.  Typical final values after optimization are RMS $\simeq 1$\% and LOSS $\simeq 3$\%.

We automatically switch between two algorithms to select the set of candidate tiles to adjust during each iteration: a fast algorithm that is typically selected when RMSE dominates the score, and a slower brute-force algorithm that is typically selected when LOSS dominates.  The fast algorithm first identifies which LST bin would maximally improve RMSE when tiles are shifted away from it, and then only considers tiles whose exposures overlap that bin.  The slow algorithm considers a 20\% random subset of all tiles.  We next rank all tiles in the candidate set according to how much they improve the SCORE when adjusted. We usually pick the tile with the best improvement but will sometimes randomly pick a lower-ranked tile. The size of the HA adjustment is randomly generated from a Rayleigh distribution with mean fixed to the input adjustment-size parameter $\delta\text{HA}$.

\subsection{Annealing and Termination}

The {\tt surveyinit} script uses the {\tt optimize.Optimizer} class to coordinate the overall HA assignment task. Optimization proceeds in ``cycles'' of $n$ adjustments with fixed parameters, where $n$ equals the number of tiles to optimize. After each cycle, the distribution of HAs is smoothed over the sky,
$$
\text{HA}_j = (1 - \alpha)\,\text{HA}_j + \alpha\,\overline{\text{HA}}_j
$$
where $\overline{\text{HA}}_j$ is the weighted average of neighboring HAs,
$$
\overline{\text{HA}}_j = \sum_{k\ne j} \omega_{jk}\,\text{HA}_k \; ,
$$
and $\alpha$ controls the amount of smoothing.  Smoothing weights are Gaussian in the separation angle $\theta_{jk}$ between pairs of tiles,
$$
\omega_{jk} = \exp\left( -0.5(\theta_{jk} / \sigma_S)^2 \right) \; ,
$$
with a smoothing length $\sigma_S \simeq 10^\circ$.

After each complete cycle, the adjustment size $\delta\text{HA}$ and amount of smoothing $\alpha$ are annealed according to:
$$
\delta\text{HA} \rightarrow a \delta\text{HA} \quad, \quad
\alpha\rightarrow a \alpha \; ,
$$
with an annealing factor $a \simeq 0.95$.

Cycles are terminated once both of the following conditions are met:
\begin{itemize}
    \item RMSE below a preset threshold $\simeq 2$\%, and
    \item fractional change in SCORE larger than a preset threshold $\simeq -1\%$.
\end{itemize}
Cycles also terminate after a preset maximum number of cycles.  All of these presets can be modified via {\tt surveyinit} command-line arguments.

\section{Results}

\fig{LST_zero} and \fig{LST_flat} show the LST distributions obtained after optimizing initial HAs set to be zero or ``flat''.  \fig{HA_zero} and \fig{HA_flat} show the corresponding all-sky distributions of HAs for each tile.  Both methods match the available and planned LST usage to high accuracy and predict similar total exposure times and corresponding safety margins. However, they use qualitatively different HA distributions to achieve similar results, indicating that the HA-assignment optimization problem has many comparable local minima.  In the following, we select the ``flat'' initialization method since it has slightly better performance and more closely matches the algorithm used for BOSS and eBOSS.  \tab{summary} summarizes the planned LST usage in each program using ``flat'' initialization.  There is some safety margin for all programs with our assumed exposure-time model and survey schedule.

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{LST_zero}
\caption{Available (red) and planned (blue) LST usage after optimizing initial HA=0 assignments.  The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram.  The LST axis starts at $-60^\circ$.}
\label{fig:LST_zero}
\end{center}
\end{figure}

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{LST_flat}
\caption{Available (red) and planned (blue) LST usage after optimizing initial HAs obtained with the ``flat'' method.  The blue outline histogram shows the planned usage rescaled to the area of the available LST histogram.  The LST axis starts at $-60^\circ$.}
\label{fig:LST_flat}
\end{center}
\end{figure}

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{HA_zero}
\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment after optimizing initial HA=0 assignments.}
\label{fig:HA_zero}
\end{center}
\end{figure}

\begin{figure}[htb]
\begin{center}
\includegraphics[width=6in]{HA_flat}
\caption{All-sky maps of the tiles in each pass (0-7) color coded by their initial HA assignment after optimizing initial HA=0 assignments.}
\label{fig:HA_flat}
\end{center}
\end{figure}

\begin{table}[htb]
\begin{center}
\begin{tabular}{lcccc}
Program & Available & Planned & Stretch & Margin \\
\hline
DARK   & 5319.0h & 4784.9h & 1.4 & 11.2\% \\
GRAY   & 1357.8h & 1284.4h & 1.5 &  5.7\% \\
BRIGHT & 1899.8h & 1553.0h & 2.0 & 22.3\% \\
\hline
\end{tabular}
\caption{Summary of observing plan for each program based on the observing hour angle assignments obtained with the ``flat'' initialization method.}
\label{tab:summary}
\end{center}
\end{table}

\def\apjl{ApJL} %Astrophysical Journal Letters
\def\aj{AJ} %Astronomical Journal
\def\apj{ApJ} %Astrophysical Journal
\def\pasp{PASP} %Publications of the Astronomical Society of the Pacific
\def\spie{SPIE} %
\def\apjs{ApJS} %Astrophysical Journal Supplement
\def\araa{ARAA} %Annual Review of Astronomy and Astrophysics
\def\aap{A\&A} %Astronomy and Astrophysics
\def\aaps{A\&A~Supl.} %Astronomy and Astrophysics Supplement
\def\nat{Nature} %Nature
\def\nar{New Astron. Rev.} %New Astronomy Review
\def\mnras{MNRAS} %Monthly Notices of the Royal Astronomical Society
\def\jcap{JCAP} %Journal of Cosmology and Astroparticle physics
\def\prd{{Phys.~Rev.~D}}        % Physical Review D
\def\physrep{{Phys.~Reports}} % Physics Reports

\bibliographystyle{unsrt}
\bibliography{design_ha}

\end{document}


\documentclass{article}
\usepackage[margin=2.5cm]{geometry}

\usepackage{kpfonts}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{hyperref}
\usepackage{todonotes}
\usepackage{xspace}
\usepackage{listings}

\newcommand{\pOut}{{!}}
\newcommand{\bOut}{{!\!!}}
\newcommand{\pIn}{{?}}
\newcommand{\bIn}{{?\!?}}
\newcommand{\new}[2]{(\nu\!#1) #2}
\newcommand{\freshFor}{\mathrel{\#}}
\newcommand{\rec}{\mathtt{rec}}
\newcommand{\nil}{\mathbf{0}}
\newcommand{\invoke}[1]{\langle #1 \rangle}

\newcommand{\psicalculus}{psi-calculus\xspace}

\newcommand{\refinedBy}{\precsim}

\newtheorem{lemma}{Lemma}
\newtheorem{definition}{Definition}

\lstset{basicstyle=\ttfamily\small}
\lstdefinelanguage{Coq}{
  morekeywords={Require,Import,Open,Scope,Section,Context,Inductive,forall,Fixpoint,match,with,end,End,Arguments,return,Definition,Fact,Qed}
  }

\DeclareMathOperator{\bn}{bn}
\DeclareMathOperator{\n}{n}
\DeclareMathOperator{\len}{len}
\DeclareMathOperator{\chain}{chain}

\begin{document}

\title{Asynchronous Embedded Psi-Calculus}
\author{Edsko de Vries}
\maketitle

\section{Motivation}

The \psicalculus \cite{DBLP:journals/corr/abs-1101-3262} is a parametric process
calculus with support for broadcast communication \cite{Borgström2015} and
equipped with a formally verified metatheory. Its parameterization allows for
modelling of various cryptographic and other primitives, and its definition of
broadcast communication is very general. As such, it is a suitable candidate for
modelling the Proas algorithm and proving some of its properties. Its metatheory
includes a definition of bisimularity, along with a formal proof that
bisimularity is ``sound'', in the sense two bisimilar processes are
interchangeable in any context (sound with respect to a high-level observational
equivalence).

Unfortunately, such soundness comes at a cost. The relation between processes
(bisimilarity) must be detailed and is often complex; the definition of
bisimilarity for the \psicalculus in particular is non-trivial. Consequently,
proving bisimilarity between processes is often difficult and must be supported
by additional formal infrastructure. Although such infrastructure exists for the
\psicalculus in the form of up-to techniques, it currently does not support the
broadcast extension \cite{AmanPohjola:2016:BUT:2854065.2854080}.

Secondly, in order to be able to use \emph{any} kind of sound theory (one that
would allow us to conclude that we can replace a process by another in an
arbitrary context), we would have to fully characterize the behaviour of those
processes. This is a proof obligation which we currently don't have the
resources to take on, and instead we will only give partial specification.

On the positive side giving up on full specifications allows us to be more
flexible in what kind of calculus we use. When we use the \psicalculus directly,
every additional operation (such as encryption) that isn't explicitly supported
in the calculus must be encoded using the \psicalculus parameters. If however we
don't intend to use the existing \psicalculus metatheory, and don't intend to do
any metatheoretical reasoning ourselves (and instead only intend to reason about
concrete processes), we can define a process calculus that reuses infrastructure
from the host language (such as Isabelle) to give us additional power. For
example, in the Verdi project \cite{Wilcox:2015:VFI:2737924.2737958} processes
are simply host-language functions from inputs to outputs.

Embedding host-language functions in a calculus is known as higher order
abstract syntax (HOAS), and is typically associated with three problems in
formal verification. First, for a higher order abstract syntax the use of HOAS
is problematic as it requires a non-positive datatype. Since the psi-calculus is
first order, this is not an issue. Second, HOAS introduces ``exotic'' terms that
extend the power of the calculus; often these terms are undesirable but in our
case this is precisely the reason for introducing HOAS. We do have to be careful
that processes cannot distinguish one ``fresh'' name from another; it suffices
to require that the functions are equivariant. Finally, HOAS makes it difficult
or impossible to do induction over the syntax of the calculus (although there
are workarounds \cite{Röckl2001}). Since we don't intend to do metatheoretical
reasoning, but only plan to reason about concrete processes, I don't think that
this will be an issue.

Having said all that, it \emph{is} useful to stay as close to the \psicalculus
as possible, so that if in the future we do want to take advantage of the
\psicalculus metatheory the transition is not more difficult than it needs to
be. For this reason in this document we introduce an embedded process calculus
(``embedded'' in the sense that it is embedded in a host language with a
function space), which is closely modelled after the \psicalculus as it is
defined in \cite{Borgström2015}. The embedded nature of the calculus however
means that we can simplify the \psicalculus in various ways; this is documented
in detail in Section~\ref{sec:deviations}.

\section{Deviations from the \psicalculus}
\label{sec:deviations}

Since we want to work with a semantics in which we can model network
limitations, we work in an asynchronous process calculus (i.e., the output
process does not have a continuation). In an asynchronous process calculus there
is no guaranteed message delivery and no guaranteed message ordering. It
\emph{does} guarantee that messages don't get duplicated, but this is also
straight-forward to guard against in ``real'' code and moreover likely less
of a problem. The translation from an asynchronous calculus to the corresponding
synchronous calculus is trivial.

The \psicalculus as defined in
\cite{DBLP:journals/corr/abs-1101-3262,Borgström2015} uses the classical
``replication'' operator $!P$, modelling an unbounded number of instances of $P$
in parallel. This operator is convenient for modelling but less convenient for
interpretation. The \psicalculus workbench
\cite{Borgstrom:2015:PWG:2724585.2682570} uses named processes, effectively
introducing general recursion; we do the same. It is important that these named
processes are actually (host language) \emph{functions} from values to
processes, so that we can model things like process state.
Appendix~\ref{app:namedproc} shows one way in which we might model this formally
(the example uses Coq); I experimented also with using PHOAS for this purpose
but it turned out to be non-trivial (\emph{cf}.
\cite{Chlipala:2010:VCI:1706299.1706312}).

The rules for point-to-point communication in the \psicalculus rely on a
name-matching predicate $\xleftrightarrow{.}$; this is used for instance to
express that $\mathtt{fst}(c,d)$ and $c$ denote the same channel. Our use of
HOAS means that $\mathtt{fst}(c,d)$ will simply \emph{evaluate} to $c$ and hence
we don't need the name matching construct. Formally, we instantiate
$\xleftrightarrow{.}$ to be diagonal relation on the set of names (name
equality).

Similarly, the rules for broadcast connectivity use two predicates
$\overset{.}{\prec}$ and $\overset{.}{\succ}$, denoting ``output connectivity''
and ``input connectivity'' respectively. We simplify this to the trivial case:
we only use a single broadcast channel, that all processes can send to and
receive from. Formally, if $b$ is the single broadcast channel, we instantiate
both $\overset{.}{\prec}$ and $\overset{.}{\succ}$ to be trivial diagonal
relation on the set $\{b\}$.

In the \psicalculus the relations $\xleftrightarrow{.}$, $\overset{.}{\prec}$
and $\overset{.}{\succ}$ are all parameterized by the ``frame'' of the process;
a set of formulas that are asserted to be true at any point during the process'
lifecycle. Frames are also used to determine the branch to take in a case
statement. Since our instantiations of $\xleftrightarrow{.}$,
$\overset{.}{\prec}$ and $\overset{.}{\succ}$ are all trivial, and pattern
matching is taken care of by evaluation, we have no use for frames and omit them
from the calculus. Formally, we instantiate $\mathbf{A} = \{\top\}$, containing
only the trivial assertion, let $\mathbf{1} = \top$ and $\top \otimes \top =
\top$.

We follow the presentation of the psi-calculus from \cite{Borgström2015}
closely. In particular, we use nominal logic to deal with name binding
\cite{Pitts2001,DBLP:journals/corr/abs-0809-3960}. As stated, however, we use
HOAS for the input prefix, so that we can take advantage of the expressive power
of the host language to express processes. We do insist that these functions are
equivariant, to ensure that fresh names cannot be distinguished from each other.

The resulting calculus closely follows the \psicalculus, although the
resemblance is somewhat misleading: the introduction of HOAS significantly
extends the expressive power of the calculus. If and when we decide to use the
\psicalculus as stated in the literature, along with its metatheory, we need to
find ways to model all the primitives that we use in our processes.

\section{Formal Definition}

\subsection{Syntax}

\begin{tabular}{llll}
$P, Q$ & $::=$ && Process \\
  && $\nil$               & Nil                \\
  && $c \pOut V$          & Output             \\
  && $c \pIn \mathcal{F}$ & Input              \\
  && $\new{a}{P}$         & Restriction        \\
  && $P \parallel Q$      & Parallel           \\
  && $\bOut V$            & Broadcast output   \\
  && $\bIn \mathcal{F}$   & Broadcast input    \\
  && $\invoke{A} V$       & Process invocation \\
\\
\end{tabular}

We let $a, b, c$ range over channels, $V$ ranges over values, and $\mathcal{F}$
ranges over equivariant functions from values to processes, $\alpha$ over
arbitrary actions, and $A$ over process names. We allow arbitrary values in the
host language.

\subsection{Operational Semantics}

In the semantics below we do not give a rule for process invocation. Ideally,
all rules should be extended with an environment $\Gamma$ and an additional rule
should be added that $\invoke{A}(V)$ can take whatever step that $\Gamma(A)(V)$
can.

\begin{itemize}

\item Point-to-point communication

\begin{equation*}
%
% PIn
%
\frac{
}{
c \pIn \mathcal{F} \xrightarrow{c \pIn V} \mathcal{F}(V)
}
\mathtt{In}
%
\qquad
%
% POut
%
\frac{
}{
c \pOut V \xrightarrow{c \pOut V} \nil
}
\mathtt{Out}
%
\qquad
%
\frac{
P \xrightarrow{\new{\bar{a}}{c \pOut V}} P' \qquad
Q \xrightarrow{c \pIn V} Q' \qquad
\bar{a} \freshFor Q
}{
P \parallel Q \xrightarrow{\tau} \new{\bar{a}}{(P' \parallel Q')}
}
\mathtt{Com}
%
\end{equation*}
%
\begin{equation*}
\frac{
P \xrightarrow{\new{\bar{a}}{c \pOut V}} P' \qquad
b \freshFor \bar{a}, c \qquad
b \in \n(V)
}{
\new{b}{P} \xrightarrow{\new{\bar{a},b}{c \pOut V}} P'
}
\mathtt{Open}
\end{equation*}
%
where
%
\begin{itemize}
\item Symmetric version of $\mathtt{Com}$ elided.
\item Rule $\mathtt{Com}$ doubles as a closing rule.
\end{itemize}

\todo[inline]{The psi calculus paper states some additional assumptions here,
but I \emph{think} they online pertain to frames, which we make no use of. But
we may need an additional freshness requirement somewhere.}

\item Broadcast communication

\begin{equation*}
%
% BOut
%
\frac{
}{
\bOut V \xrightarrow{\bOut V} \nil
}
\mathtt{BrOut}
%
\qquad
%
% BrIn
%
\frac{
}{
\bIn \mathcal{F} \xrightarrow{\bIn V} \mathcal{F}(V)
}
\mathtt{BrIn}
%
\qquad
%
% BCom
%
\frac{
P \xrightarrow{\new{\bar{a}}{\bOut V}} P' \qquad
Q \xrightarrow{\bIn V} Q' \qquad
\bar{a} \freshFor Q
}{
P \parallel Q \xrightarrow{\new{\bar{a}}{\bOut V}} P' \parallel Q'
}
\mathtt{BrCom}
\end{equation*}
%
\begin{equation*}
%
% BrOpen
%
\frac{
P \xrightarrow{\new{\bar{a}}{\bOut V}} P' \qquad
b \freshFor \bar{a} \qquad
b \in \n(V)
}{
\new{b}{P} \xrightarrow{\new{\bar{a},b}{\bOut V}} P'
}
\mathtt{BrOpen}
%
\qquad
%
% Close
%
\frac{
P \xrightarrow{\new{\bar{a}}{\bOut V}} P'
}{
P \xrightarrow{\tau} \new{\bar{a}}{P'}
}
\mathtt{BrClose}
\end{equation*}
%
\begin{equation*}
%
% BrMerge
%
\frac{
P \xrightarrow{\bIn V} P' \qquad
Q \xrightarrow{\bIn V} Q'
}{
P \parallel Q \xrightarrow{\bIn V} P' \parallel Q'
}
\mathtt{BrMerge}
\end{equation*}
%
where
%
\begin{itemize}
\item Symmetric version of rule $\mathtt{BrCom}$ is elided; note that the psi
calculus paper also elides rule $\mathtt{BrOpen}$ (we stated it explicitly).
\item Rule $\mathtt{BrMerge}$ would not be necessary if we had an explicit rule
\begin{math}
\displaystyle
\frac{
P \equiv P' \xrightarrow{\alpha} Q' \equiv Q
}{
P \xrightarrow{\alpha} Q'
}
\end{math}.
If we want such a rule to be \emph{derivable} instead (which makes the semantics
easier to use) rule $\mathtt{BrMerge}$ is needed.
\item Rule $\mathtt{BrClose}$ is slightly more permissive than its equivalent in
the psi calculus presentation, where it only applies at the point where the
channel is bound. I'm not entirely sure why that restriction is in place; it
is unusual (the closing rule for point-to-point communication has no similar
restriction).
\item Since we assume the existance of a single, global, broadcast channel,
restriction does not apply to broadcast channels. However, it \emph{is} possible
to extrude a point-to-point communication channel through a broadcast communication.
\item The rules for broadcast communication together mean that a single
broadcast output can be paired with any number (zero or more) inputs, and once
paired  (i.e., after the action) the output is no longer available. No
assumptions can be made about who will receive the message, and so broadcast
communication is ``unreliable'' in the sense that message may be ``lost''.
Moreover, since broadcast output, like regular output, is asynchronous,
broadcast communication is unordered.
\end{itemize}

\item Congruence rules

\begin{equation*}
%
% Par
%
\frac{
P \xrightarrow{\alpha} P' \qquad
\bn(\alpha) \freshFor Q
}{
P \parallel Q \xrightarrow{\alpha} P' \parallel Q
}
\mathtt{Par}
%
\qquad
%
% Scope
%
\frac{
P \xrightarrow{\alpha} P' \qquad
a \freshFor \alpha
}{
\new{a}{P} \xrightarrow{\alpha} \new{a}{P'}
}
\mathtt{Scope}
%
\qquad
\end{equation*}

Symmetric version of $\mathtt{Par}$ elided.

\end{itemize}

\section{Stating properties}

\todo[inline]{This section serves as a rough sketch only on how we might state
properties.}
\newcommand{\node}{\mathtt{Node}}

One of the main properties we want to state and prove is that a node can always
evolve to a state where its internal chain matches the chain of the environment
(given some compatibility conditions). If $\node$ is the function from a node's
internal state to the corresponding \psicalculus process, for the published
Praos algorithm we can state this simply as:
%
\begin{lemma}[Praos]
In any state $s$ and for any chain $c$ such that $\len(c) > \len(\chain(s))$,
there exists state $s'$ such that
\begin{equation*}
\node_P(s) \xrightarrow{\bIn c} \node_P(s')
\end{equation*}
and $\chain(s') = c$.
\end{lemma}
%
For the ``block Proas'' algorithm, the property is somewhat more complicated
since the node might be missing blocks.
%
\begin{lemma}[Block Praos]
\label{lem:blockpraos}
In any state $s$ and for any block $b$ such that $b$ is a valid successor of
$\chain(s)$ (though perhaps not the \emph{immediate} successor), there exists
$s', s'', \mu^*$ such that
\begin{equation*}
\node_B(s) \xrightarrow{\bIn b} \node(s') \xRightarrow{\mu^*} \node_B(s'')
\end{equation*}
and $b \in \chain(s'')$.
\end{lemma}
%
We can also try to relate the two implementations more directly. For example,
we could state that whenever the Praos node broadcasts a chain, the Block Praos
nodes will broadcast a series of blocks using the following coinductive
definition:
%
\begin{definition}[Simulation]
We say that $\node_B(s_B)$ can simulate $\node_P(s_P)$, written
$\node_P(s_P) \refinedBy \node_B(s_B)$, iff for all $s_P', c$ such that
\begin{equation*}
\node_P(s_P) \xrightarrow{\bOut c} \node_P(s_P')
\end{equation*}
there exists $s_B'$ and blocks $b^*$, a suffix of $c$, such that
\begin{equation*}
\node_B(s_B) \xRightarrow{\bOut b^*} \node_B(s_B')
\end{equation*}
and $\node_P(s_P') \refinedBy \node_B(s_B')$.
\end{definition}
%
We would then prove that
%
\begin{lemma}[Block Praos simulates Praos]
\label{lem:BlockSimPraos}
For all $s_P, s_C$ such that $\chain(s_P) = \chain(s_B)$,
\begin{equation*}
\node_P(s_P) \refinedBy \node_B(s_B)
\end{equation*}
\end{lemma}
%
We may of course also wish to prove something about how the other actions
relate, or prove something in the other direction too (bisimulation rather than
simulation). Note that such a (bi)simulation doesn't necessarily obsolete the
need for additional lemmas such as Lemma~\ref{lem:blockpraos}, since in the
proof of Lemma~\ref{lem:BlockSimPraos} we can pick paths in which no messages
get lost.

\appendix

\section{Appendix: Named Processes}
\label{app:namedproc}

Example Coq development of defining a process calculus with named
process invocation. Relies on some supporting definitions for vectors and
dependent vectors, shown in Appendix~\ref{app:coqaux}.

\begin{lstlisting}[language=Coq]
Section Syntax.

  Context {n   : nat}.
  Context {typ : Vec Set n}.

  Inductive Proc : Type :=
      Done : Proc
    | Out  : nat -> Proc -> Proc
    | Inv  : forall (i : Fin n), nth i typ -> Proc.

  Definition Env := DepVec (fun a => a -> Proc) typ.

End Syntax.

Arguments Proc {n} typ.
Arguments Env  {n} typ.
Arguments Inv  {n} typ.

Section Semantics.

  Context {n   : nat}.
  Context {typ : Vec Set n}.
  Context {env : Env typ}.

  Inductive HasTrace : Proc typ -> list nat -> Prop :=
      TNil  : forall P, HasTrace P nil
    | TOut  : forall n P t, HasTrace P t ->  HasTrace (Out n P) (cons n t)
    | TInv  : forall i x t, HasTrace (dnth i env x) t -> HasTrace (Inv _ i x) t.

End Semantics.

Arguments HasTrace {n} {typ} env.

Section Example.

  Definition typ : Vec Set 2 := (nat, (nat, tt)).

  Definition left  (n : nat) : Proc typ := Out n (Inv typ (FS FZ) (n + 1)).
  Definition right (n : nat) : Proc typ := Out n (Inv typ     FZ  (n + 1)).

  Definition env : Env typ := (left, (right, tt)).

  Fact trace123 : HasTrace env (left 1) (1 :: 2 :: 3 :: nil).
    repeat constructor.
  Qed.

End Example.
\end{lstlisting}

\section{Appendix: Supporting definitions}
\label{app:coqaux}

Some supporting Coq infrastructure for the development in Appendix~\ref{app:namedproc}.

\begin{lstlisting}[language=coq]
Section Vec.

  Context (A : Type).

  Inductive Fin : nat -> Set :=
      FZ : forall {n}, Fin (S n)
    | FS : forall {n}, Fin n -> Fin (S n).

  Fixpoint Vec (n : nat) : Type :=
    match n with
      O    => unit
    | S n' => A * Vec n'
    end.

  Fixpoint nth {n : nat} (i : Fin n) : Vec n -> A :=
    match i with
      FZ    => fun xs => match xs with (x, xs') => x          end
    | FS i' => fun xs => match xs with (x, xs') => nth i' xs' end
    end.

End Vec.
Arguments nth {A} {n} i.

Section DepVec.

  Fixpoint DepVec (f : Set -> Set) {n : nat} : Vec Set n -> Set :=
    match n return Vec Set n -> Set with
      0    => fun _  => unit
    | S n' => fun As => match As with (A, As') => (f A * DepVec f As')%type end
    end.

  Fixpoint dnth {n : nat} {f : Set -> Set} (i : Fin n) :
     forall {xs : Vec Set n}, DepVec f xs -> f (nth i xs) :=
    match i in Fin n return forall (xs : Vec Set n), DepVec f xs -> f (nth i xs) with
      FZ    => fun As =>
                 match As with (A, As') => fun xs =>
                   match xs with (x, xs') => x end
                 end
    | FS i' => fun As =>
                 match As with (A, As') => fun xs =>
                   match xs with (x, xs') => dnth i' xs' end
                 end
    end.

End DepVec.
\end{lstlisting}

\bibliographystyle{acm}
\bibliography{references}

\end{document}


In this section, we assess our framework for characterizing process variation
presented in \sref{bayes-solution}. All the experiments are conducted on a
\up{GNU}/Linux machine equipped with an Intel Core i7 2.66~\up{GH}z and
8~\up{GB} of \up{RAM}. All the configuration files used in the experiments are
available online at \cite{eslab2014a}.

Our goal is to infer the effective channel length \g from temperature \h. Such a
high-level parameter as temperature constitutes a challenging task for the
inference of such a low-level parameter as the effective channel length, which
implies a rigorous assessment of the proposed technique. The performance of our
approach is expected only to increase when the auxiliary parameter \h is closer
to the target parameter \g with respect to the data model $\h = \f(\g)$
described in \sref{bayes-data-model}. For instance, such a closer quantity \h
could be the leakage current, but this might not always be the most preferable
parameter to measure. Lastly, let us note that the chosen effective channel
length is an important target, as it is strongly affected by process variation
and considerably impacts power consumption and heat dissipation
\cite{chandrakasan2000, srivastava2010, juan2011, juan2012}. It also affects
other process-related parameters, such as the threshold voltage.

We first describe the default configuration, which will be adjusted later on
according to the purpose of each particular experiment. We consider a 45-nm
technological process. The diameter of the wafer is 20 dies, and the total
number of dies \nd is 316. The number of measured dies \hnd is 20, and these
dies are chosen by an algorithm that strives for even coverage of the wafer. The
fabricated platform has four processing elements, and they are the points at
which measurements are taken; that is, $\np = 4$. The floorplan of the platform
is constructed in such a way that the processing elements form a regular grid.
The dynamic power profiles involved in the experiments are based on simulations
of applications randomly generated by \up{TGFF} \cite{dick1998}. The model of
static power parameterized by temperature and the effective channel length is
constructed by fitting to \up{SPICE} simulations of reference electrical
circuits that are composed of \up{BSIM4} devices \cite{bsim} configured
according to the 45-nm \up{PTM} \up{HP} model \cite{ptm}. The construction of
thermal \up{RC} circuits is delegated to HotSpot \cite{skadron2003}, and
temperature analysis is performed as described in \sref{transient-solution}. The
sampling interval of power and temperature profiles is 1~ms.

The input data set $H$ is obtained as follows: \one~draw a sample of \g from a
Gaussian distribution with a mean of 17.5~nm (in accordance with the
technological process under consideration \cite{ptm}) and a covariance function
equal to \eref{bayes-covariance} with a standard deviation of 2.25~nm;
\two~perform one fine-grained temperature simulation for each of the \hnd dies
selected for measurement; \three~thin the obtained temperature profiles so that
each has only \ns, which is 20 by default, evenly spaced moments in time; and
\four~perturb the resulting data using white Gaussian noise with a standard
deviation of \celsius{1}.

Let us turn to the statistical model in \sref{bayes-statistical-model} and
summarize the intuition behind the model's parameters and the process by which
they are assigned. In the correlation function given in
\eref{bayes-correlation}, the weight parameter $w$ and the two length-scale
parameters $\ell_\SE$ and $\ell_\OU$ should be set according to the variation
patterns that are typical for the fabrication process at hand
\cite{chandrakasan2000, cheng2011}; we set $w$ to 0.7 and $\ell_\SE$ and
$\ell_\OU$ to half the radius of the wafer. The threshold parameter $\eta$ of
the model-order-reduction procedure shown in \eref{karhunen-loeve} and utilized
in \eref{bayes-reduction} should be set high enough in order to preserve a
sufficiently large portion of the variance of the data, thereby keeping the
model sufficiently accurate; we set it to 0.99. The resulting dimensionality \nz
of \vz in \eref{bayes-reduction} is found to be 27 or 28. The parameters $\mu_0$
and $\tau_\g$ of the prior given in \eref{bayes-prior} are specific to the
technological process under consideration; we set $\mu_0$ to 17.5~nm and
$\tau_\g$ to 2.25~nm. The parameters $\sigma_0$ and $\nu_\g$ used in
\eref{bayes-prior} determine the precision of the information about $\mu_0$ and
$\tau_\g$ and are set according to the beliefs of the designer; we set
$\sigma_0$ to 0.45~nm and $\nu_\g$ to 10. The latter can be thought of as the
number of imaginary observations that the choice of $\tau_\g$ is based on. The
parameter $\tau_\epsilon$ in \eref{bayes-prior} represents the precision of the
equipment utilized for collecting $H$ and can be found in the technical
specification of that equipment; we set $\tau_\epsilon$ to \celsius{1}. The
parameter $\nu_\epsilon$ in \eref{bayes-prior} has the same interpretation as
$\nu_\g$; we set it to 10 as well. In \eref{bayes-proposal}, $\nu$ and $\alpha$
are tuning parameters, which are configured based on experiments; we set $\nu$
to 8 and $\alpha$ to 0.5. The number of sample draws is another tuning
parameter, which we set to \power{10}{4}. The first half of these samples is
ascribed to the burn-in period mentioned in \xref{bayesian-statistics}, and the
second one constitutes $G$; in this case, $\no = 5 \times 10^3$. In the
optimization described in \sref{bayes-optimization}, we use the quasi-Newton
algorithm \cite{press2007}. For parallel computations, we utilize four
computational cores.

In order to ensure that the experimental setup is adequate, we first perform a
detailed inspection of the results obtained for one particular example with the
default configuration. The true and inferred distributions of the quantity of
interest are shown in \fref{bayes-motivation-distribution} where the \ac{NRMSE}
is below 2.8\%, and the absolute error is bounded by 1.4~nm, which suggests that
our framework produces a close match to the true value of the quantity. We also
investigate the behavior of the constructed Markov chains and the quality of the
proposal distribution. All the observations indicate that the optimization and
sampling procedures are properly configured.

In the following subsections, we consider the experimental setup described above
and alter a single parameter at a time in order to investigate its impact.
Specifically, we change \one~the number of measurement sites \hnd, which is 20
by default; \two~the number of measurement points per site \np, which is 4 by
default; \three~the number of data instances per point \ns, which is 20 by
default; and \four~the standard deviation of measurement noise
$\sigma_\epsilon$, which is \celsius{1} by default.

\subsection{Number of Measurement Sites}

\inputtable{bayes-sites}
Let us vary the number of measured sites or dies \hnd. The scenarios being
considered are 1, 10, 20, 40, 80, and 160 dies. The obtained results are shown
in \tref{bayes-sites}. In this and the following tables, we report the
optimization time and sampling time separately, which correspond to Stage~2 and
Stage~3 in \fref{bayes-overview}, respectively. In addition, the sampling time
is given for two cases: sequential and parallel computing, which is followed by
the total time and resulting error. The computation time of the post-processing
stage, Stage~4, is not given, as it is negligibly small. The sequential sampling
time is the most representative indicator of the computational complexity of the
proposed framework, since the number of samples is always fixed, and there is no
parallelization. Therefore, we refer to this value in most of the discussions
given below.

It can be seen in \tref{bayes-sites} that the more data the proposed framework
needs to process, the longer the execution time becomes, which is reasonable.
The trend, however, is modest: when \hnd is doubled, the computation time
increases by less than a factor of two. Regarding accuracy, the error decreases
definitively and drops below 4\% when around 20 sites are measured, which is
only 6\%--7\% of the total number of dies on the wafer under consideration.

\subsection{Number of Measurement Points}

\inputtable{bayes-points}
In this subsection, we consider five platforms with different numbers of
processing elements or, equivalently, measurement points \np. The scenarios
being considered are 2, 4, 8, 16, and 32 processing elements. The results are
summarized in \tref{bayes-points}. The computation time grows along with \np.
This is expected, since the granularity of the temperature model is bound to the
number of processing elements: each processing element contributes four thermal
nodes to the thermal \up{RC} circuit that temperature analysis is based on;
recall \sref{temperature-model}. Hence, temperature analysis becomes more
expensive. Nevertheless, even for large examples, taking into account the
complexity of the inference procedure and the yielded accuracy, the time
requirement is readily acceptable. An interesting observation can be made with
respect to the \ac{NRMSE}: the error tends to decrease as \np grows. The reason
is that, with each measurement point, $H$ delivers more information for the
inference to work with.

\subsection{Number of Data Instances}

\inputtable{bayes-instances}
Now we change the number of data instances \ns, which, in this case, is the
number of moments in time captured by temperature profiles. The scenarios being
considered are 1, 10, 20, 40, 80, and 160 moments. The results are aggregated in
\tref{bayes-instances}. It can be seen that the growth in computation time is
relatively small. One might expect this growth due to \ns to be the same as the
one due to \np, since, technically, the influence of \np and \ns on the
dimensionality of $H$ is identical; recall that $\hvh \in \real^{\hnd \np \ns}$.
However, the meanings of \np and \ns are completely different, and hence the
ways they manifest themselves in the inference algorithm are also different,
which explains the discordant figures shown in \tref{bayes-points} and
\tref{bayes-instances}. The \ac{NRMSE} in \tref{bayes-instances} has a
decreasing trend; however, this trend is less steady than the ones noted before.
The finding can be explained as follows. The temporal distribution of the
moments in time that are present in $H$ changes, since these moments are kept
evenly spaced across the time spans of the corresponding applications. Some
moments can be more informative than others. Consequently, more or less
representative samples can be accumulated in $H$, helping or misleading the
inference. Additionally, we can conclude that a larger number of spatial
measurements is more advantageous than a larger number of temporal measurements.

\subsection{Deviation of Measurement Noise}

\inputtable{bayes-noise}
In this subsection, we vary the standard deviation of measurement noise, which
corrupts $H$. The cases being considered are \celsius{0}, \celsius{0.5},
\celsius{1}, and \celsius{2} \cite{mesa-martinez2007}. Note that the
corresponding prior in \eref{bayes-prior} is kept unchanged. The results are
given in \tref{bayes-noise}. It can be seen that the sampling time is
approximately constant. However, we observe an increase in the optimization time
when the level of noise decreases, which can be ascribed to greater
opportunities for perfection for the optimization procedure. Another observation
revealed by this experiment is that, in spite of the fact that the inference
operates on indirect and incomplete data, a thoroughly calibrated piece of
equipment can considerably improve the quality of prediction. However, even with
a noise of \celsius{2}---meaning that measurements are dispersed over a wide
band of \celsius{8} with a probability of more than 0.95---the \ac{NRMSE} is
still only 4\%.

\subsection{Sequential and Parallel Sampling}

Lastly, we elaborate on the sequential and parallel sampling strategies. In the
sequential Metropolis--Hastings algorithm, the optimization time is typically
smaller than the time needed for drawing posterior samples. The situation
changes when parallel computing is utilized. When four cores are working in
parallel, the sampling time decreases by a factor of 3.81 on average, which
indicates good parallelization properties of the chosen sampling strategy. The
overall speedup ranges from 1.49 to 2.75 with an average value of 1.77, which
can be pushed even further by employing more computational cores.


\section{Language Versions and Cost Models}
\label{sec:protocol-parameters}

We require the following types (see Figure~\ref{fig:defs:protocol-parameters})
in addition to those that are already defined in the Shelley specification~\cite{XX}. \TODO{Add the citation}

\vspace{12pt}
\begin{tabular}{lp{5in}}
  $\Language$ &
  This represents the language name/tag (including the
  version number).
  \\
  $\ExUnits$ &
  A term of this type contains two integer values,
  $(mem, steps)$.
  These represent abstract notions of the relative memory usage and script execution steps,
  respectively.
  \\
  $\CostMod$ &
  A term of this type represents the vector of coefficients that are used to generate
  a term of type $\ExUnits$ given a vector of some resource primitives. The mapping is defined
  concretely by the specific version of the Plutus interpreter that is associated with $\Language$.
  We keep this type as abstract in the specification.
  \\
  $\Prices$ &
  A term of this type comprises two integer values that correspond to the components of $\ExUnits$,
  $\var{pr_{mem}, pr_{steps})}$:
  $pr_{mem}$ is the price (in Ada) per unit of memory, and $pr_{steps}$ is the price (in Ada) per
  reduction step. This is used to calculate the Ada cost for a specific script execution.
\end{tabular}
\vspace{12pt}

We also need a number of additional protocol parameters and accessor functions: ...\todo{List these.}

\begin{tabular}{||l|l||}
  \textbf{Item} & \textbf{Use} \\
  \
  \end{tabular}

\subsection{Language Versions and Backwards Compatibility Requirements}
\label{sec:versions}

In the $\Language$ type, each \emph{version} of a language is considered to be a different language (so there might be several versions of the Plutus language, each of which would be considered to
be different).
Each such language needs to be interpreted by a language-specific interpreter that is called from the ledger implementation.
The interpreter is provided with the (language- and version-specific) arguments that it requires.
It is necessary for the ledger to be capable of executing scripts in languages it ever supported.
This implies that it is necessary to maintain all forms of ledger
data that is needed by any past or current language, which constrains future ledger designs.
Introducing a new language will require a major protocol version update, since the datatypes need to support the new language and the ledger rules must be updated to use the new interpreter.

\subsection{Determinism of Script Evaluation}
\label{sec:determinism}

The data that is passed to the interpreter
includes the validator script, the redeemer, possibly a datum from the UTxO, information about the transaction that
embeds the script, any relevant ledger data, and any relevant protocol parameters.
It is necessary for the validation outcome of any scripts to remain the same during the entire
period between transaction
submission and completion of the script processing.
%
In order to achieve this,
any data that is passed to the interpreter must be determined by the transaction itself.
The transaction therefore includes a hash of any data that is not determined by the transaction or the UTXO.
When the transaction is processed, as part of the UTXOW rule, this hash is compared with a hash of the data that is passed to the interpreter. This
ensures that scripts are only executed if they have been provided with the intended data.

The $\fun{getLanguageView}$ function (Figure~\ref{fig:defs:protocol-parameters}) selects the protocol parameters that are relevant to
a given set of languages.
%
At the time of writing, the only parameter that needs to be passed to the interpreter is the cost model.

\subsection{Script Evaluation Cost Model and Prices}
\label{sec:cost-mod}

To convert resource primitives into the
more abstract $\ExUnits$ during script execution a cost model needs to be supplied to the interpreter.
The cost models required for this purpose are recorded in the $\var{costmdls}$ protocol parameter.
%
The calculation of the actual cost, in Ada, of running
a script that takes $\var{exunits} \in \ExUnits$ resources to run,
is done by a formula in the ledger rules, which uses the
$\var{prices}$ parameter. This is a parameter that applies to all
scripts and that cannot be varied for individual languages. This parameter
reflects the real-world costs in terms of energy usage, hardware resources etc.

\textbf{Limiting Script Execution Costs.}
The $\var{maxTxExUnits}$ and $\var{maxBlockExUnits}$ protocol parameters are
used to limit the total per-transaction and per-block resource use. These only apply to non-native scripts.
The parameters are used to ensure that the time and memory that are required to verify a block are bounded.

\begin{figure*}[htb]
  \emph{Abstract types}
  %
  \begin{equation*}
    \begin{array}{r@{~\in~}l@{\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad}r}
      \var{cm} & \CostMod & \text{Coefficients for the cost model} \\
      \var{ldv} & \LangDepView & \text{Language-dependent view of the protocol parameters}
    \end{array}
  \end{equation*}
  %
  \emph{Derived types}
  \begin{equation*}
    \begin{array}{r@{~\in~}l@{\quad=\quad}l@{\qquad}r}
      \var{lg}
      & \Language
      & \{\Plutus, \dotsb\}
      & \text{Script Language}
      \\
      \var{pr_{mem}, pr_{steps})}
      & \Prices
      & \Coin \times \Coin
      & \text {Coefficients for $\ExUnits$ prices}
      \\
      \var{(mem, steps)}
      & \ExUnits
      & \N \times \N
      & \text{Abstract execution units} \\
    \end{array}
  \end{equation*}
  %
  \emph{Protocol Parameters}
  %
  \begin{equation*}
      \begin{array}{r@{~\in~}l@{\qquad}r}
        \var{costmdls} \mapsto (\Language \mapsto \CostMod) & \PParams & \text{Script exec. cost model}\\
        \var{prices} \mapsto \Prices & \PParams & \text{Coefficients for $\ExUnits$ prices} \\
        \var{maxTxExUnits} \mapsto \ExUnits & \PParams & \text{Max. total tx script exec. resources}\\
        \var{maxBlockExUnits} \mapsto \ExUnits & \PParams & \text{Max. total block script exec. resources}\\
      \end{array}
  \end{equation*}
  %
  \emph{Accessor Functions}
  %
  \begin{center}
  \fun{costmdls},~\fun{maxTxExUnits},~\fun{maxBlockExUnits},~\fun{prices}
  \end{center}
  %
  \emph{Helper Functions}
  %
  \begin{align*}
    & \fun{getLanguageView} \in \PParams \to \Language \to \LangDepView \\
    & \fun{getLanguageView}~\var{pp}~\Plutus = \{\Plutus\} \restrictdom \fun{costmdls}~{pp}
  \end{align*}
  %
  \caption{Definitions Used in Protocol Parameters}
  \label{fig:defs:protocol-parameters}
\end{figure*}


% Abstract

% We show however, that if mass-dependent heating is responsible, the
% differential heating rate is not constant over logarithmic time intervals
% which implies that different heating processes must be acting before and after
% ages of around 1 Gyr.
% Perhaps a more likely scenario is that the relation between rotation period
% and color changes over time, undergoing a particularly sharp transition at
% around 1 Gyr.
% If we assume that mass-dependent heating does not affect the data,

% (similar to the age of the rotation gap and the 1.1 Gyr NGC 6811
% cluster, shown to have a different period-color relation to Praesepe).
% We find that the ages of field stars with measured rotation periods do not
% exceed 4-6 Gyrs, resolving a long-standing degeneracy between age and magnetic
% braking efficiency.
% We also show that stars rotating just below the rotation period gap are
% dynamically young, ruling out the possibility that the rotation period gap is
% caused by incorrect period measurements or binary companions.

% INTRO

% This relation was calibrated by fitting a 5th-order polynomial to the relation
% between (log) rotation period and (log) \gaia\ \gcolor\ color for around 800
% members of the Praesepe cluster, and a straight line in (log) age to Praesepe
% and the Sun.

% In this paper, we shed light on the rotational evolution of old K dwarfs using
% population-based dynamical ages.
% Unfortunately, open clusters with rotation period measurements are mostly
% young -- currently the oldest is 2.5 Gyr (NGC 6819).
% Without rotation periods for precisely dated old stars, it is extremely
% difficult to calibrate the relationship between rotation period and color at
% old ages.
% For this reason, we used a population-based stellar age indicator, velocity
% dispersion, to investigate the period-color relations at old ages in the
% field.

% Stellar velocities have a history of being used as an age proxy, with several
% notable examples within stellar astronomy \citep[\eg][]{faherty2009,
% west2011}.

% Vertical {\it actions} are better age indicators than velocities, because
% actions are calculated by integrating angular momentum over the Milky Way's
% potential, and are therefore position invariant -- \eg\ a star will have the
% same action at periapsis and apoapsis.
% In contrast, orbital velocities are different at periapsis and apoapsis -- so
% in this sense, {\it actions} are the natural quantities to use as age proxies.

% \subsection{The degeneracy between gyrochronology and mass-dependent heating}

% Although only calibrated using Praesepe ($\sim$ 650 Myr) and the Sun (4.56
% Gyr), the \citet{angus2019} gyrochronology relation predicts accurate ages for
% members of NGC 6819, a 2.5 Gyr open cluster.
% However there are no rotation periods for K or M dwarfs in this cluster -- its
% coolest members with rotation periods are G dwarfs.
% The period-color relation of Praesepe is nearly identical to the period-color
% relation of the Hyades, a cluster of around the same age: $\sim$ 650 years
% \citep{douglas2016, douglas2017, rebull2017}.
% However, Praesepe and the Hyades do {\it not} have the same period-color
% relation as NGC 6811, a 1.1 Gyr cluster \citep{curtis2019}.
% The G dwarfs in NGC 6811 rotate at the same rate as the K dwarfs and it
% appears as though the K stars have `stalled' -- their spin-down has been
% halted.

% The \citet{angus2019} gyrochronology relation assumes that the rotation
% period-color relation of Praesepe is applicable to stars of all ages: the same
% polynomial relation fit to Praesepe is used to describe the period-color
% relation for all stars.
% However, the NGC 6811 cluster suggests that this assumption does not hold for
% K dwarfs past around 1 Gyr.
% If the period-color relation of the \citet{angus2019} gyrochronology model
% {\it were} a perfect model for the rotational evolution of stars, then groups
% of stars selected to be similar ages using this relation should fall on an
% isochrone on a CMD.
% % and have the same velocity dispersion across all colors.
% Unfortunately, uncertainties on \gaia\ photometry and parallaxes, plus
% variations in metallicity and extinction, blur out the main sequence enough
% that differences between stars in different age and rotation bins are not
% easily discernable on the CMD, although there is still a general age and
% rotation period gradient on the CMD, as seen in figures \ref{fig:CMD_cuts} and
% \ref{fig:age_gradient}.
% For this reason, we chose to use {\it kinematic} `isochrones', instead of
% magnitude and color-based isochrones: although kinematics as an age indicator
% is not necessarily as well calibrated to an absolute age scale as CMD
% position, it can be very sensitive to {\it differences} in the ages of stellar
% populations.

% Isochrones and stellar evolution tracks are highly dependent on choices made
% about input physics and assumptions.
% % and have often been calibrated using
% % different types of stars.
% As a result, different sets of models can have very different shapes on the
% CMD, particularly at low masses.
% In fact, only empirical models, not physical ones, are currently able to
% reproduce the CMD positions of M dwarfs.
% Instead of relying on CMD position to age-date groups of stars, we opted to
% explore age trends via kinematics.
% Kinematic age-dating has the advantage of being relatively model independent,
% or at least, having a very simple model: that velocity dispersion increases
% over time.
% This means that it is relatively easy to rank groups of stars by age: older
% groups have a larger velocity dispersion.

% METHOD

% \begin{figure}
%   \caption{
% A \gaia\ color magnitude diagram showing the \citet{mcquillan2014} sample with
%     extinction-corrected magnitudes, colored by rotation period.
% We excluded photometric binaries and subgiants from our analysis by removing
% stars above the two dashed lines.
% % The rotation periods of binaries and subgiants do not follow a Skumanich-like
% % braking law.
% % The rotation period gradient across the main sequence is visible by eye in
% %     this figure: young, rapidly rotating stars are located below the old,
% %     slowly rotating stars.
% % since we rely on a simple scaling
% % between rotation period and age to make the argument that the rotation period
% % is not caused by incorrect period measurements.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{CMD_cuts}
% \label{fig:CMD_cuts}
% \end{figure}
% To explore the age of this stellar population from a rotation standpoint, it
% was first necessary to remove visual binaries and subgiants from the sample.
% The rotational evolution of these two types of stars is generally different to
% that of single stars which more usually follow a Skumanich-like spin-down law.
% Tidal and magnetic interactions between the two components of a binary system
% can influence the rotation periods of both stars, and the expanding envelopes
% of subgiants drive rapid spin-down through conservation of angular momentum.

% \begin{figure}
%   \caption{
% the rotation periods of stars in the \citet{mcquillan2014} sample vs.
% effective temperature.
% black points are dwarf stars identified as non-photometric binaries, hotter
% than 4800 k.
% blue circle points are non-photometric binary dwarfs, cooler than 4800 k, with
% a rotation period and \gaia\ color indicating they are older than 1.1 gyr.
% orange squares are stars that with rotation periods that fall just below the
% gap: they have rotation-ages between 0.5 and 1.1 gyrs.
% green triangles are stars with rotation periods faster than the main envelop
% of stars.
% these are probably binaries whose rotation periods are synchronized to their
% orbits and have been spun-up via tidal interactions.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{period_teff}
% \label{fig:period_teff}
% \end{figure}

% This allowed us to remove the degeneracy between mass and age that would
% confound evidence for mass-dependent heating among more massive stars.
% In a sample of massive stars with short MS lifetimes, lower-mass stars
% typically have greater velocity dispersion, but this could be either because
% dynamical heating is more efficient in lower mass stars, or because lower mass
% stars tend to be older because they live longer.
% In a sample of late K and M dwarfs, whose MS lifetime is longer than the age
% of the Universe, we can assume that none have evolved into giants and any
% additional heating seen in the lower-mass stars must be caused by
% mass-dependent heating.

% \begin{figure}
%   \caption{
% A \gaia\ color-magnitude diagram, showing all \kepler\ targets.
% We selected K and M dwarfs by applying color and magnitude cuts at \gcolor\ =
%     1.2 (\teff\ $\sim$ 4800 K) and $G$ = 4.
% We eliminated visual binaries by fitting a 6th order polynomial to the MS and
%     removing stars above it.
% Selected K and M dwarfs are shown as darker points.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{mdwarf_CMD}
% \label{fig:mdwarf_CMD}
% \end{figure}

% A slight excess of non-Gaussian outliers at lower temperatures leads to a
% marginal increase in velocity dispersion at low temperatures when sigma
% clipping is not performed.
% Figure \ref{fig:vb_vs_color} shows velocity and velocity dispersion as a
% function of \gaia\ \gcolor\ color.
% There is no clear trend between velocity dispersion and color.

% \begin{figure}
%   \caption{
%       Top: Stellar velocity (\vb) as a function of \gaia\ \gcolor\ color for
%       \kepler\ K and M dwarfs.
% Vertical lines indicate different color-groupings used to calculate velocity
%     dispersion.
% Pink stars were not included in velocity dispersion calculations as they were
%     removed as outliers during a sigma clipping process.
% Bottom: velocity dispersion as a function of color.
% There is no obvious trend between velocity dispersion and stellar color
%     indicating that mass-dependent heating does not significantly effect
%     low-mass stars in the \kepler\ field.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{vb_vs_color}
% \label{fig:vb_vs_color}
% \end{figure}

% RESULTS

% The shape of the upper envelope of rotation periods in the top panels of
% figures \ref{fig:age_cut} and \ref{fig:dispersion_period_teff} also hints at
% this.

% If we assume that the gap is located at a single (gyrochronal) age, its age is
% remarkably similar to the NGC 6811 cluster (measured from MS turn-off) of 1.1
% Gyr \citep{meibom2011}.

% DISCUSSION

% The \vb\ AVR is not directly comparable to the \vz\ AVR, so, to draw a
% comparison with results from the literature, we calculated a \vz\ AVR for
% the subset of 290 cool stars in the \mct\ sample with \gaia\ RVs.
% We measured an AVR exponent of 0.47 $\pm$ 0.1, which falls within the range of
% values (0.45-0.53) reported from measurements of F and G stars in the Solar
% neighborhood \citep{holmberg2009, aumer2009, aumer2016}.
% It is a little lower than the values of 0.56 $\pm$ 0.14 (for low-z) and 0.51
% $\pm$ 0.15 (for high-z stars), calculated using \LAMOST\ \racomment{(LAMOST
% citation)} K giants \citep{yu2018}.
% K giants are more massive than K dwarfs \racomment{(how much more massive?)},
% so this slightly higher value contradicts the mass-dependent heating
% hypothesis.
% \racomment{Add some words about selection functions...}

% To investigate further, we calculated the exponent of the (\vb) AVR for each
% temperature bin in figure \ref{fig:age_cut}.
% \begin{figure}
%   \caption{
%       The exponent of the (\vb) AVR as a function of effective temperature.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{AVR_exponent}
% \label{fig:AVR_exponent}
% \end{figure}
% Figure \ref{fig:AVR_exponent} shows the significant rise the in AVR exponent
% as a function of effective temperature.
% The hottest stars in our sample (\teff\ = 4833-5000 K) have a (\vb) AVR
% exponent of 0.39 $\pm$ 0.02 and the coolest (\teff\ = 3500-3667 K) have an
% exponent of 0.74 $\pm$ 0.02.
% The masses of stars in our sample differ by less than a factor of two,
% so mass-dependent heating cannot be entirely responsible for this large spread
% in heating rates.
% \racomment{Need to look into this further.}

% If mass-dependent heating is strongly affecting our data, the exponent of the
% AVR should increase with decreasing effective temperature, \ie\ the heating
% rate should be greater for lower-mass stars.
% Figure \ref{fig:AVR_exponent} shows the AVR exponent does indeed increase with
% decreasing effective temperature, however, the AVR exponent calculated using
% more massive stars from the Geneva Copenhagen Survey (GCS)
% \citep{holmberg2009} is also shown on this plot as a dashed horizontal line.
% Most GCS stars are F and G type: 1-3 times more massive than the K dwarfs used
% in our study.
% If mass-dependent orbital heating is the main cause the rise in velocity
% dispersion with decreasing \teff\ seen in figure \ref{fig:age_cut}, then the
% AVR exponent of the more massive GCS stars should fall {\it below} the AVR
% exponent for the most massive stars in our sample.
% In other words, the dynamical heating rate should be lowest for the highest
% mass stars and highest for the lowest mass stars.
% % nordstrom2004, jorgensen2005,
% These AVR exponents were calculated with different populations of stars,
% subject to different selection effects, so directly comparing them comes with
% some risk.
% The most important difference is that the GCS AVR is calculated using \vz,
% however our AVRs are calculated using \vb\ since most stars in our sample do
% not have radial velocities.
% The median galactic latitude of these \kepler\ stars is 12.3\degrees, with
% latitudes ranging from 5.5\degrees\ to 21.4\degrees, so \vb\ is a relatively
% close approximation to \vz.
% Only 290 out of the 6820 stars in our sample, plotted in color in figure
% \ref{fig:age_cut}, have \gaia\ radial velocities, however we used the ones
% that do to compare the \vz\ AVR to the \vb\ AVR, across all temperatures
% between 3500 and 5000 K.
% For stars with gyrochronal ages between 0.5 and 4.5 Gyr, we measured a \vz\
% AVR exponent of 0.519 $\pm$ ... and a \vb\ AVR exponent of 0.514 $\pm$... .
% The similarity of these two AVR exponents suggests that directly comparing
% these two quantities {\it may} be a reasonable approach.
% For now, given the large difference between the (\vz) AVR exponent of the GCS
% sample and the (\vb) AVR exponent of the hottest stars in our sample, we
% assume that the increased velocity dispersion at cooler temperatures is mostly
% caused by incorrect age-grouping due to an incorrect period-color relation at
% old ages, and that any mass-dependent heating, while it may contribute at a
% low level to this result, is not the dominant driver.
% However, differentiating the effects of mass-dependent heating and the shape
% of the gyrochronology relations is certainly warranted in a follow-up study.
% }

% Figure \ref{fig:age_comparison} shows the ages of star groups, predicted with
% the \citet{angus2019} gyrochronology relation, compared with the ages of star
% groups, predicted with the \citet{holmberg2009} AVR.
% \citet{holmberg2009} only provide an exponent (0.53), not an intercept, for the
% relation between logarithmic age (in Gyr) and logarithmic, \vz\ velocity
% dispersion (in \kms), so we fit the intercept to the mean \vb\ velocity
% dispersion across all temperatures, of our sample.
% \begin{figure}
%   \caption{
%       Ages predicted by the \citet{holmberg2009} \vz\ AVR, against ages
%     predicted by the \citet{angus2019} gyrochronology relation, for stars in
%     different temperature ranges.
% Points are colored by the effective temperature in the center of the \teff\
% bin.
% The dashed line shows the y=x relation.
% Predicted kinematic ages fan out over gyrochronal time, either because the AVR
%     is temperature-dependent or because the gyrochronology relations have an
%     age-dependent period-color relation.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{age_comparison}
% \label{fig:age_comparison}
% \end{figure}
% Figure \ref{fig:age_comparison} shows a comparison between ages predicted by
% the \citet{holmberg2009} \vz\ AVR (using \vb\ as a proxy for \vz) and ages
% predicted by the \citet{angus2019} gyrochronology relation, for stars in
% different temperature ranges.
% The predicted kinematic ages fan out over gyrochronal time, either because the
% AVR is temperature-dependent or because the gyrochronology relations have an
% age-dependent period-color relation.
% Figure \ref{fig:age_comparion} also suggests that dynamical heating does not
% begin until after around ... Gyr:

% Alternatively, the ages of these young stars could be under-predicted by
% gyrochronology.
% These young stars have similar rotation periods to the Praesepe cluster, which
% was used to calibrate the gyrochronology relation used in this analysis.
% The ages of these young stars should, therefore, be the most accurate of the
% entire sample.
% However, they are tied to the age of the Praesepe cluster, whose age is not
% accurately known.
% \citet{angus2019} adopted an age for Praesepe of 650 Myrs, however the
% kinematic age-prediction for these stars is around 400 Myrs.
% Other studies have assigned a much older age of 800 Myrs to Praesepe
% \citep{brandt2015}.
% If the age assumed for Praesepe in the \citet{angus2019} gyrochronology
% calibration was inaccurate, the entire age {\it scale} would be incorrect.
% However, this is not what figure \ref{fig:age_comparion} shows -- it shows
% that the {\it relative} age of these youngest stars are under-predicted by
% kinematics or over-predicted by gyrochronology.

% If we assume that the rise in velocity dispersions at cooler effective
% temperatures is caused by an inaccurate period-color relation rather than
% mass-dependent dynamical heating, we can estimate what the shape of the
% period-color relations {\it should} be.
% Figure \ref{fig:age_cut} indicates that the period-color relation flattens
% out, so we applied the same analysis to groups of stars with similar rotation
% periods, equivalent to a completely flat period-color relation.
% The top panel of figure \ref{fig:period_cut} shows the \mct\ sample with stars
% in different period ranges plotted in different colors.
% The bottom panel shows the velocity dispersion of each group as a function of
% effective temperature.
% \begin{figure}
%   \caption{
% This figure is similar to figure \ref{fig:age_cut}, with stars divided into
%     period groups rather than age groups.
% The velocity dispersion is more constant across effective temperatures for the
%     most slowly rotating stars, compared to the stars selected with the
%     \citet{angus2019} gyrochronology model, indicating that the gyrochronology
%     models flatten out, and possibly even invert, at old ages.
% }
%   \centering
%     \includegraphics[width=1\textwidth]{period_cut}
% \label{fig:period_cut}
% \end{figure}
% Once again, the velocity dispersion increases with rotation period overall.
% For the most rapidly rotating groups of stars, velocity dispersion decreases
% with \teff\ as expected given the positively sloped period-color relation of
% Praesepe and other young clusters: late K dwarfs rotate more slowly than early
% K dwarfs of the same age.
% Between rotation periods of 15 and 25 days, the temperature dependence of the
% velocity dispersion starts to disappear, indicating that the period-color
% relation becomes flat: late K dwarfs rotate at the same rate as early K dwarfs
% of the same age.
% At long rotation periods, the velocity dispersion still increases with
% effective temperature, although the increase is much more modest compared to
% the oldest stars in figure \ref{fig:age_cut}.

% If we assume the rise in velocity dispersion at cooler effective temperatures
% is caused by an inaccurate period-color relation rather than mass-dependent
% dynamical heating, we can generate a graphical representation of what the
% relations {\it should} look like.

% Aside from the assumption that mass-dependent dynamical heating is {\it not}
% the main cause of the increased velocity dispersion for cooler stars, a number
% of assumptions went into this analysis which should be addressed before a
% strong conclusion about the nature of stellar spin down is drawn.
% There are some potential confounders that could produce trends between
% velocity dispersion and effective temperature, of which the main ones are
% listed below.
% \begin{itemize}

    % \item{{\bf Extinction.}
% Although we dereddened stars before their ages were estimated, if the
    %     reddening values were underestimated, the gyrochronal ages of stars
    %     would be under-estimated.
% This effect would be largest for the late Ks and early Ms, where the shape of
    %     the period-color relation is more steeply sloped, and stars can more
    %     easily move into the wrong age bin with a small perturbation in color
    %     or temperature.
% Old stars would be incorrectly assigned young ages, and this would happen more
    %     often for cooler stars.
% This effect could lead to an increase in velocity dispersion with \teff, even
% if the gyrochronology relation was perfect.}

    % \item{{\bf Mass-dependent orbital heating.}
% A key assumption going into this analysis is that the orbits of all stars are
% heated at the same rate, regardless of their mass.
% However, if the heating mechanism leads to preferential heating of lower mass
% stars, those stars would have a larger velocity dispersion, not caused by
% ageing.
% No strong evidence has yet been provided to show a mass-dependence in orbital
% heating, however this is an extremely difficult exercise because mass and age
% are so strongly correlated.
% The mass-age degeneracy is reduced in the lowest mass stars which represent
    %     the initial mass function of the Solar neighborhood.
% No mass-dependent heating was found by \citet{faherty2009} who looked
% at the velocity dispersions of low-mass stars.
% Another argument against the increased velocity dispersion as a function of
    %     \teff\ being caused by mass-dependent orbital heating, is that heating
    %     acts most strongly at young ages and most weakly at old ages, \ie\ on
    %     a logarithmic timescale.
% This is related to the fact that stars are more difficult to scatter once they
% are on orbits with a large out-of-plane component and they spend more time out
% of the mid-plane.
% Our data show the opposite trend: stars show little mass-dependent heating
    %     before around 1 Gyr.
% Moreover, the stars in the Geneva-Copenhagen study, used to calibrate the AVR
    %     \citep{holmberg2009} are F and G stars, around 1-3 times as massive as
    %     the K stars in our sample.
% % nordstrom2004, jorgensen2005,
% The ages for our sample of K stars, predicted by gyrochronology agree with the
    %     AVR calibrated using F and G stars, which implies that either
    %     mass-dependent heating is a weak effect, or, mass-dependent heating is
    %     strong and, by coincidence, gyrochronology underpredicts the ages of
    %     the early K dwarfs by just the right amount that they still appear to
    %     agree with the \citet{holmberg2009} AVR.
% We therefore expect that the increased velocity dispersion at cooler
    %     temperatures is mostly caused by incorrect age-grouping, \ie\ the
    %     period-color relation is incorrect for old, low-mass stars, and that
    %     any mass-dependent heating, while it may contribute at a low level to
    %     this result, is not the dominant cause.
% }

    % \item{{\bf Selection bias.}
% The \gaia\
% catalog is incompletebecause they are too faint.
% This is simply due to the fact that \kepler's field of view was aimed at low
    %     galactic latitudes, so nearby \kepler\ stars are close to the galactic
    %     plane.
% The heights of stars above the galactic plane, and correspondingly their
    %     velocities and ages, are therefore correlated with distance.
% Almost no high velocity stars appear in our sample at temperatures cooler than
% 3500, which is why the coolest stars were excluded from our sample, however
% the selection function could still affect stars hotter than 3500 K, and is
% suggested by the decrease in velocity dispersions for cool stars of all ages
% in figure \ref{fig:age_cut}.
% However, this selection effect would act in opposition to the observed trend.
% }

% \item{{\bf Weakened magnetic braking.}
% The rotation periods of old stars are faster than predicted by Skumanich-like
% magnetic braking \citep{angus2015, vansaders2016, metcalfe2019}.
% Magnetic braking is expected to become inefficient once stars approach a
% Rossby number (the ratio of rotation period to convective turnover time) of
% around 2 \citep{vansaders2016, vansaders2018}.
% Since hot stars have shallow convection zones and shorter overturn timescales,
% they reach $Ro = 2$ and stop spinning down at shorter rotation periods than
% cool stars.
% For this reason, some of the hotter stars in the sample may already have
% stopped spinning down, and could be much older than a traditional
% gyrochronology relation (like the simple Praesepe-based relation used in this
% analysis) would suggest.
% However, this effect would work to cancel out the trend observed in figure
% \ref{fig:age_cut} because hotter groups of stars would contain more old stars
% with large velocities.
% }

% \item{Stellar or exoplanet companions.}
% Hotter stars are more likely to be binaries.
% This would make synchronized some stars seem younger, more likely for massive
% stars, although really only likely at short rotation periods.

% \end{itemize}

% CONCLUSION

% This indicates that either the \citep{angus2019} period-color relation is
% incorrect, or that mass-dependent dynamical heating is affecting this data set.
% We presented three pieces of evidence that suggest mass-dependent heating
% cannot be responsible for all of the increasing velocity dispersion.

% \begin{itemize}

% \item{
%         No strong evidence for mass-dependent heating has been found among M, L
% and T-type stars.
% These low-mass stars live longer than the current age of the Universe and
%         therefore do not suffer from a mass-age degeneracy
%         \citep{faherty2009}.
% }

% \item{
%         Literature measurements of the (\vz) AVR exponent are slightly higher
% than the value measured from our data set, but calculated using more massive
% stars.
% Mass-dependent dynamical heating should however produce a {\it smaller} AVR
%         exponent for higher-mass stars.
% We acknowledge that the stars in the \mct\ sample, analyzed in this work, are
%         subject to different selection biases than those used to calculate
%         AVRs in the literature \citep{holmberg2009, aumer2009, yu2018}, so
%         drawing direct comparisons between them does not provide a reliable
%         test.
% }

% \item{
%         The differences in the (\vb) AVR exponent between the hottest and
% coolest K dwarfs in our sample are extremely large, spanning values between
% 0.4 and 0.75, yet the difference in mass is less than a factor of two.
% Such a large spread in AVR exponents cannot be explained by mass-dependent
%         heating alone.
% }

% \end{itemize}

% \racomment{Words about the significance of an inverted period-color relation.}

% \racomment{How does the weakened van Saders braking law fit into all this?}

% \racomment{Talk about the fact that the stars in each bin are not necessarily
% the same age.}

% \racomment{Dispersion could be dependent on the selection function.
% We cut stars at high b, because we find that these do lead to a bias.
% We find no evidence for increased velocity dispersion with decreasing teff in
% either vb or vz.
% We find that sigma clipping is necessary for vb but not vz and do not find
% that the outliers are distributed towards higher galactic latitudes.
% }

% \racomment{Trevor suggest that stars forming in clusters could be the reason
% why young stars are so dynamically cool.}

% \racomment{Are there any asteroseismic stars in this sample that could help
% pin down the age?}


\section{EOS Calls}

\subsection{Initialization}

\subsection{{\tt advance\_timestep}}

\begin{description}
\item[Step 1.] {\em Define the average expansion at time $t^\nph$ and the new $w_0.$}\\ \\
if \runparam{dpdt\_factor} $>$ 0 then
%
\begin{itemize}
\item In {\tt makePfromRhoH}, we compute a thermodynamic $p^n$ for the volume discrepancy
term using $(\rho,h,X)^n$.
\end{itemize}
end if
\item[Step 2.] {\em Construct the provisional edge-based advective velocity, $\uadvone.$}
\item[Step 3.] {\em React the full state and base state through the first time interval
of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^n$.
\item In {\tt react\_state}, we compute $T^{(1)}$ using $(\rho,h,X)^{(1)}$
(if \runparam{use\_tfromp} {\tt = F}) or $(\rho,X)^{(1)}$ and $p_0^n$ (if {\tt use\_tfromp = T})
\end{itemize}
if \runparam{evolve\_base\_state} {\tt = T} then
\begin{itemize}
\item In {\tt make\_gamma}, we compute $\Gamma_1$ using $(\rho,X)^{(1)}$ and $p_0^n$.
\end{itemize}
end if
\item[Step 4.] {\em Advect the base state, then the full state, through a time interval
of $\dt.$}\\ \\
if \runparam{use\_thermal\_diffusion} {\tt = T} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{(1)}$.
\item In {\tt enthalpy\_advance} $\rightarrow$ {\tt update\_scal}, we compute $h$ above
the \runparam{base\_cutoff\_density} using $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$.
\item In {\tt thermal\_conduct}, we compute $T^{(2),*}$ using $(\rho,h,X)^{(2),*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
else
\begin{itemize}
\item In {\tt enthalpy\_advance} $\rightarrow$ {\tt update\_scal}, we compute $h$ above
the \runparam{base\_cutoff\_density} using $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$.
\item In {\tt enthalpy\_advance}, we compute $T^{(2),*}$ using $(\rho,h,X)^{(2),*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
end if
\item[Step 5.] {\em React the full state through a second time interval of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^{(2),*}$.
\item In {\tt react\_state}, we compute $T^{n+1,*}$ using $(\rho,h,X)^{n+1,*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
if {\tt evolve\_base\_state} then
\begin{itemize}
\item In {\tt make\_gamma}, we compute $\Gamma_1$ using $(\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$.
\end{itemize}
end if
\item[Step 6.] {\em Define a new average expansion rate at time $t^\nph.$}\\ \\
if \runparam{use\_thermal\_diffusion} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{n+1,*}$.
\end{itemize}
end if
\begin{itemize}
\item In {\tt make\_S}, we compute thermodynamic variables using $(\rho,T,X)^{n+1,*}$.
\end{itemize}
if \runparam{dpdt\_factor} $>$ 0 then
\begin{itemize}
\item In {\tt makePfromRhoH}, we compute a thermodynamic $p^{n+1,*}$ for the volume
discrepancy term using $(\rho,h,X)^{n+1,*}$.
\end{itemize}
end if
\item[Step 7.] {\em Construct the final edge-based advective velocity, $\uadvtwo.$}
\item[Step 8.] {\em Advect the base state, then the full state, through a time interval
of $\dt.$}\\ \\
if \runparam{use\_thermal\_diffusion} = T then
\begin{itemize}
\item In {\tt enthalpy\_advance} $\rightarrow$ {\tt update\_scal}, we compute $h$ above
the \runparam{base\_cutoff\_density} using $(\rho,X)^{(2)}$ and $p_0^{n+1}$.
\item In {\tt advance} before {\tt thermal\_conduct}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{(2),*}$.
\item In {\tt thermal\_conduct}, we compute $T^{(2)}$ using $(\rho,h,X)^{(2)}$
(if \runparam{use\_tfromp} {\tt = F}) or $(\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\tt use\_tfromp} {\tt = T}).
\end{itemize}
else
\begin{itemize}
\item In {\tt enthalpy\_advance} $\rightarrow$ {\tt update\_scal}, we compute $h$ above
the {\tt base\_cutoff\_density} using $(\rho,X)^{(2)}$ and $p_0^{n+1}$.
\item In {\tt enthalpy\_advance}, we compute $T^{(2)}$ using $(\rho,h,X)^{(2)}$
(if {\tt use\_tfromp} {\tt = F}) or $(\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\tt use\_tfromp = T}).
\end{itemize}
end if
\item[Step 9.] {\em React the full state and base state through a second time interval
of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^{(2)}$.
\item In {\tt react\_state}, we compute $T^{n+1}$ using $(\rho,h,X)^{n+1}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{n+1}$ and $p_0^{n+1}$ (if {\tt use\_tfromp = T}).
\end{itemize}
if \runparam{evolve\_base\_state} {\tt = T} then
\begin{itemize}
\item In {\tt make\_gamma}, we compute $\Gamma_1$ using $(\rho,X)^{n+1}$ and $p_0^{n+1}$.
\end{itemize}
end if
\item[Step 10.] {\em Compute $S^{n+1}$ for the final projection.}\\ \\
if {\tt make\_explicit\_thermal} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{n+1}$.
\end{itemize}
end if
\begin{itemize}
\item In {\tt make\_S}, we compute thermodynamic variables using $(\rho,T,X)^{n+1}$.
\end{itemize}
\item[Step 11.] {\em Update the velocity.}\\ \\
if \runparam{dpdt\_factor} $>$ 0 then
\begin{itemize}
\item In {\tt makePfromRhoH}, we compute a thermodynamic $p^{n+1}$ for the volume
discrepancy term using $(\rho,h,X)^{n+1}$.
\end{itemize}
end if
\item[Step 12.] {\em Compute a new $\dt.$}
\end{description}

\subsection{{\tt make\_plotfile}}

\section{Temperature Usage}

\subsection{{\tt advance\_timestep}}
\begin{description}
\item[Step 1.] {\em Define the average expansion at time $t^\nph$ and the new $w_0.$}
\item[Step 2.] {\em Construct the provisional edge-based advective velocity, $\uadvone.$}
\item[Step 3.] {\em React the full state and base state through the first time interval
of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^n$.
\item In {\tt react\_state}, we compute $T^{(1)}$ using $(\rho,h,X)^{(1)}$
(if \runparam{use\_tfromp} {\tt = F}) or $(\rho,X)^{(1)}$ and $p_0^n$ (if {\tt use\_tfromp = T}).
\end{itemize}
\item[Step 4.] {\em Advect the base state, then the full state, through a time interval
of $\dt.$}\\ \\
if \runparam{use\_thermal\_diffusion} {\tt = T} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{(1)}$.
\item In {\tt thermal\_conduct}, we compute $T^{(2),*}$ using $(\rho,h,X)^{(2),*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
else
\begin{itemize}
\item In {\tt enthalpy\_advance}, we compute $T^{(2),*}$ using $(\rho,h,X)^{(2),*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2),*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
end if
\item[Step 5.] {\em React the full state through a second time interval of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^{(2),*}$.
\item In {\tt react\_state}, we compute $T^{n+1,*}$ using $(\rho,h,X)^{n+1,*}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{n+1,*}$ and $p_0^{n+1,*}$ (if {\tt use\_tfromp = T}).
\end{itemize}
\item[Step 6.] {\em Define a new average expansion rate at time $t^\nph.$}\\ \\
if \runparam{use\_thermal\_diffusion} {\tt = T} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{n+1,*}$.
\end{itemize}
end if
\begin{itemize}
\item In {\tt make\_S}, we compute thermodynamic variables using $(\rho,T,X)^{n+1,*}$.
\end{itemize}
\item[Step 7.] {\em Construct the final edge-based advective velocity, $\uadvtwo.$}
\item[Step 8.] {\em Advect the base state, then the full state, through a time interval
of $\dt.$}\\ \\
if {\tt use\_thermal\_diffusion = T} then
%
\begin{itemize}
\item In {\tt advance} before {\tt thermal\_conduct}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{(2),*}$.
\item In {\tt thermal\_conduct}, we compute $T^{(2)}$ using $(\rho,h,X)^{(2)}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\tt use\_tfromp = T}).
\end{itemize}
else
\begin{itemize}
\item In {\tt enthalpy\_advance}, we compute $T^{(2)}$ using $(\rho,h,X)^{(2)}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{(2)}$ and $p_0^{n+1}$ (if {\tt use\_tfromp = T}).
\end{itemize}
end if
\item[Step 9.] {\em React the full state and base state through a second time interval
of $\dt/2.$}
\begin{itemize}
\item In {\tt react\_state} $\rightarrow$ {\tt burner}, we compute $c_p$ and $\xi_k$
for inputs to {\tt VODE} using $(\rho,T,X)^{(2)}$.
\item In {\tt react\_state}, we compute $T^{n+1}$ using $(\rho,h,X)^{n+1}$
(if {\tt use\_tfromp = F}) or $(\rho,X)^{n+1}$ and $p_0^{n+1}$ (if {\tt use\_tfromp = T}).
\end{itemize}
\item[Step 10.] {\em Compute $S^{n+1}$ for the final projection.}\\ \\
if {\tt make\_explicit\_thermal} then
\begin{itemize}
\item In {\tt advance} before {\tt make\_explicit\_thermal}, we compute the coefficients for
$\nabla\cdot(\kth/c_p)\nabla h + \cdots$ using $(\rho,T,X)^{n+1}$.
\end{itemize}
end if
\begin{itemize}
\item In {\tt make\_S}, we compute thermodynamic variables using $(\rho,T,X)^{n+1}$.
\end{itemize}
\item[Step 11.] {\em Update the velocity.}
\item[Step 12.] {\em Compute a new $\dt.$}
\end{description}