\section{State modifier components}
All these components work by modifying some global state, so that
the components below them in the tree use this modified value.
On exit from the component, the original state is restored.

See also the \emph{tempo} component (p.~\pageref{comp:tempo}).

\comp{vel}
{Modifies note velocity for components below}
{in:4$\times$input:flow, mod:float}{output:flow}
Modify the velocity of all notes played by components below
this. The new velocity will be
\[
vel \gets vel \times (p_{vel}+p_{mod}\times in)
\]
\startparams
vel & float & the amount to multiply the velocity by\\
mod & float & the amount to multiply the modulation input by, which
is then added to $vel$
\end{tabularx}

\comp{transposer}
{Transposes notes in components below}
{in:4$\times$input:flow, mod:float}{output:flow}
This transposes all notes played by components below it in the tree.
\startparams
trans & int & the number of semitones to transpose by\\
oct & int & the number of octaves to transpose by
\end{tabularx}

\comp{chordstate}
{Set the global default chord}
{in:4$\times$input:flow, chord}{output:flow}
This component sets the chord used by components which have a single
chord input when that input is unconnected, i.e. the default chord.
Such components include \emph{noteplay} and \emph{chordplay}. All
components which are below this component in the tree will use this
chord as the default chord.


\documentclass[main.tex]{subfiles}
\begin{document}

\marginpar{Friday\\ 2020-4-24, \\ compiled \\ \today}

\section{The Zel'dovich approximation}

So far we have discussed perturbation in two ways: initially, we had a contribution on the RHS of the EFE given by the perturbations.

During radiation dominance there is not much need to go beyond linear theory.

Now we want to go full nonlinear.

We need to use a mixture of techniques: both the study of the 2-body problem and a continuous distribution of matter.
This is what we do if we use numerical techniques.

On the other hand, we can make some smart approximations.

Last semester we mentioned the ``spherical top-hat solution'': we assume spherical symmetry, and work from there.

The Zel'dovich approximation gives an exact solution in the case of planar symmetry.
We can also get exact solutions with cylindrical symmetry.

We come back to the fluid equations: continuity, Euler, Poisson on a FRLW background.

When you do linear perturbation theory, you perturb around the background value.

However, in doing this we are assuming that all the perturbations have the same weight: this is not necessarily true. We should define an internal hierarchy.

What we are doing is formal in the context of Lagrangian perturbation theory.

We define
%
\begin{subequations}
\begin{align}
\eta &= \frac{\rho }{ \rho_{b}}  = 1 + \delta  \\
\vec{u} &= \dv{\vec{x}}{a} = \frac{\vec{v}}{a \dot{a} }  \\
\varphi &= \frac{3 t_{*}^2}{2 a_{*}^3} \phi
\,.
\end{align}
\end{subequations}

This is because he wanted dependence on the growth factor. In EDS this is the scale factor, in general this could be a different thing.

We are referring to a more general background: there can be a growth suppression factor, such that the density perturbation \(\delta \) does not scale with \(a\) but instead based on some function of \(a\).
We should use this function and not the scale factor in general.
In the matter-filled universe we are considering right now this is the same.

The new equations are
%
\begin{subequations}
\begin{align}
\frac{ \DD \vec{u}}{\DD a} + \frac{3}{2a} \vec{u} &= - \frac{3}{2a} \nabla \varphi  \\
\frac{ \DD \eta }{\DD a} + \eta \nabla \cdot \vec{u} &= 0  \\
\nabla^2 \varphi &= \frac{\delta}{a}
\,,
\end{align}
\end{subequations}
%
where
%
\begin{align}
\frac{\DD }{\DD a} = \pdv{}{a} + \vec{u} \cdot \nabla
\,
\end{align}
%
is the convective derivative.

We have chosen this variable \(\vec{u}\) precisely because we want something which is almost constant in linear theory: we have \(\delta \sim t^{2/3}\) and \(v \sim t^{1/3}\) and \(\phi \sim \const\).

So, we get
%
\begin{align}
\pdv{\vec{u}}{a} = 0
\,,
\end{align}
%
so then we can approximate:
%
\begin{align}
\bigd{\vec{u}}{a} = 0
\,.
\end{align}

At the linear level, \(\vec{u} = - \nabla \varphi \).
The argument is that we can \emph{extend} the linear result beyond the linear level. This is because the velocity goes like \(k\), while the potential goes like \(\delta / k^2\).

The system becomes more and more linear as we increase the scale.

Why don't we try to solve the equation by neglecting the nonlinearity in the velocity?

Then the equation system reads:
%
\begin{subequations}
\begin{align}
\bigd{\vec{u}}{a} &= 0  \\
\bigd{\eta }{a} + \eta \nabla \cdot \vec{u} &= 0
\,.
\end{align}
\end{subequations}

This can be solved exactly, as we will now see.

This is describing the inertial motion of particles with no external force acting on them.

It is important to say that this is a total derivative: the variation is zero along the trajectories of the particles.

The velocity of a particle which has a velocity \(\vec{u}_{0}\) at a position \(\vec{q}\) is preserevd. We can integrate the position straightforwardly, since the relation we get is linear.

This, however, is in our weird variables: the real motion is more complicated, but we can map the new variables to the new ones.

We can solve the continuity equation in different ways: we can divide by \(\eta \) to get logarithmic derivatives, so that
%
\begin{align}
\bigd{\log \eta }{a} =  -\nabla \cdot \vec{u}
\,.
\end{align}

when we integrate, though, we should follow the trajectory:
%
\begin{align}
\eta (\vec{x}, a) = \eta_0 (\vec{q}) \exp{ - \int_{a_0 }^{a} \dd{a'} \nabla \cdot \vec{u} \qty[\vec{x}(\vec{q}, a',), a']}
\,.
\end{align}

This calculation is done in `The large scale structure of the universe' by Peebles \cite[]{peeblesLargescaleStructureUniverse1980}.

Also, we can use an approach in which we use the Jacobian of the change of coordinates between Lagrangian and Eulerian.

The tensor
%
\begin{align}
D_{ij} = \pdv[2]{\varphi_0}{q_{i}}{q^{j}}
\,
\end{align}
%
is called the deformation tensor.
The matrix
%
\begin{align}
\pdv{x^{i}}{q_{j}} = \delta^{i}_{j} - a \pdv[2]{\varphi_0}{q_{i}}{q^{j}}
\,
\end{align}
%
defines the transformation between the old and new coordinates.
The eigenvalues of the transformation tensor are local.

It can be shown (Doroshevick 1970) that there is a \SI{92}{\percent} probability that at least one eigenvalue is positive.

This is computed using the assumption that \(\varphi_0 \) has a gaussian distribution.

This is important since we can write
%
\begin{align}
\eta (\vec{x}, a) = \frac{1}{\prod_{i=1}^{3} (1 - \lambda_{i}(\vec{q}) a)}
\,.
\end{align}

Pancakes in terms of shapes, of course, not in terms of ingredients.

The jacobian of the change of coordinates is ill defined if two particles collide.

At that point, we get nonlinearities, which \emph{are} structure formation.
This is a sort of non-gaussianity we get from this approximation.

\end{document}


\pdfoutput=1
\documentclass[twocolumn]{aastex62}
%%\documentclass[]{emulateapj}

%Accepted/received/... %%

\received{xxx}
\revised{yyy}
\accepted{zzz}

%% Command to document which AAS Journal the manuscript was submitted to.
\submitjournal{AAS Journals}

%% Short title/authors

\shorttitle{LXUV History of TRAPPIST-1}
\shortauthors{Fleming et al.}

%% Begin document, title, packages %%
\usepackage{hyperref}
\usepackage{xspace}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage[caption=false]{subfig}

%% Custom commands
\def\mearth{{\rm\,M_\oplus}}
\def\rearth{{\rm\,R_\oplus}}
\def\msun{{\rm\,M_\odot}}
\def\rsun{{\rm\,R_\odot}}
\def\lsun{{\rm\,L_\odot}}
\def\gsim{~\rlap{$>$}{\lower 1.0ex\hbox{$\sim$}}}
\def\lsim{~\rlap{$<$}{\lower 1.0ex\hbox{$\sim$}}}

\newcommand{\xxx}[1]{{\textbf{#1}}}
\newcommand{\vplanet}[0]{\texttt{VPLanet}\xspace}
\newcommand{\emcee}[0]{\texttt{emcee}\xspace}
\newcommand{\approxposterior}[0]{\texttt{approxposterior}\xspace}
\newcommand{\eqtide}[0]{\texttt{EQTIDE}\xspace}
\newcommand{\stellar}[0]{\texttt{STELLAR}\xspace}
\newcommand{\kepler}[0]{\textit{Kepler}\xspace}
\newcommand{\jwst}[0]{\textit{JWST}\xspace}

%% Begin doc %%
\begin{document}

\title{On The XUV Luminosity Evolution of TRAPPIST-1}

%% AUTHORS %%

%%\correspondingauthor{David P. Fleming}
%%\email{dflemin3@uw.edu}

%%\author[0000-0001-9293-4043]{David P. Fleming}
\author[0000-0001-9293-4043]{David P. Fleming}
\affil{Astronomy Department, University of Washington \\
Box 951580, Seattle, WA 98195}
\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}
% ORCID 0000-0001-9293-4043

\author{Rory Barnes}
\affiliation{Astronomy Department, University of Washington \\
Box 951580, Seattle, WA 98195}
\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}
% no orcid

\author[0000-0002-0296-3826]{Rodrigo Luger}
\affil{NASA NExSS - Virtual Planetary Laboratory Lead Team, USA}
\affiliation{Center for Computational Astrophysics, Flatiron Institute \\
New York, NY 10010}
% ORCIF 0000-0002-0296-3826

\author[0000-0002-9623-3401]{Jacob T. VanderPlas}
\affiliation{Google \\
601 N 34th St, Seattle, WA 98103}
% ORCID 0000-0002-9623-3401

%% ABSTRACT %%

\begin{abstract}

We model the long-term XUV luminosity of TRAPPIST-1 to constrain the evolving high-energy radiation environment experienced by its planetary system. Using Markov Chain Monte Carlo (MCMC), we derive probabilistic constraints for TRAPPIST-1's stellar and XUV evolution that account for observational uncertainties, degeneracies between model parameters, and empirical data of low-mass stars. We constrain TRAPPIST-1's mass to $m_{\star} = 0.089 \pm{0.001}$ M$_{\odot}$ and find that its early XUV luminosity likely saturated at $\log_{10}(L_{XUV}/L_{bol}) = -3.05^{+0.24}_{-0.10}$. From our posterior distributions, we infer that there is a ${\sim}43\%$ chance that TRAPPIST-1 is still in the saturated phase today, suggesting that TRAPPIST-1 has maintained high activity and $L_{XUV}/L_{bol} \approx 10^{-3}$ for several Gyrs. TRAPPIST-1's planetary system therefore likely experienced a persistent and extreme XUV flux environment, potentially driving significant atmospheric erosion and volatile loss. The inner planets likely received XUV fluxes ${\sim}10^3 - 10^4\times$ that of the modern Earth during TRAPPIST-1's 1 Gyr-long pre-main sequence phase. Deriving these constraints via MCMC is computationally non-trivial, so scaling our methods to constrain the XUV evolution of a larger number of M dwarfs that harbor terrestrial exoplanets would incur significant computational expenses. We demonstrate that \approxposterior, a Python machine learning package for approximate Bayesian inference using Gaussian processes, can efficiently replicate our analysis. We find that it derives constraints that are in good agreement with our MCMC, although it underestimates the uncertainties for two parameters by $30\%$. \approxposterior requires $330\times$ less computational time than traditional MCMC methods in this case, demonstrating its utility in efficient Bayesian inference.

\end{abstract}

%% Keywords %%

\keywords{}

%% Intro %%

\section{Introduction} \label{sec:intro}

The James Webb Space Telescope (JWST) is poised to detect and characterize the first terrestrial exoplanet atmospheres via transmission spectroscopy. This search will likely focus on planets orbiting nearby M dwarfs given their favorable relative transit depths, the potential buildup of biosignature gases due to UV-driven photochemisty \citep{Segura2005}, and the large occurrence rates of M dwarf planets \citep{Dressing2015}. The correct interpretation of those observations, however, is predicated on understanding the system's long-term evolution, most importantly processes that could impact the planet's atmospheric state and habitability, such as atmospheric escape, water loss, and the potential buildup of an abiotic O$_2$ atmosphere \citep{Watson1981,Lammer2003,MurrayClay2009,Luger2015}. These volatile escape mechanisms are partially driven by the host star's XUV luminosity (X-ray and EUV emission ranging over approximately 1-1000\AA), and therefore characterizing the long-term stellar XUV evolution of late M-dwarfs is critical to assessing the present state of their planets, including habitability.

High-energy stellar radiation originates from the corona via the heating of magnetically-confined plasma \citep{Vaiana1981}. The stellar magnetic field is likely generated via differential rotation within the stellar convective envelope \citep{Parker1955}, linking rotation to stellar activity and XUV emission. Stellar rotation rates slow over time due to magnetic braking \citep{Skumanich1972}, causing XUV emission to decline with time. The X-ray luminosity ($L_{X}$) of FGK stars, for example, has been empirically shown to monotonically decrease with age \citep{Jackson2012}. This trend has also been observed for commonly-used proxies for stellar age, rotation period and Rossby number \citep[Ro = $P_{rot}/\tau$ for convective turnover timescale $\tau$,][]{Pizzolato2003,Wright2011}. Stellar activity evolution is characterized by two distinct phases. First, in the saturated phase, young, rapidly-rotating stars ($\mathrm{Ro}\lsim 0.1$) maintain a constant $L_{X}/L_{bol} \approx 10^{-3}$ \citep{Wright2011,Jackson2012}. Then, at longer rotation periods and larger Ro, stars transition to the unsaturated phase in which $L_{X}/L_{bol}$ exponentially decays over time \citep{Pizzolato2003,Ribas2005}. Recent work has shown that the stellar dynamo processes that generate magnetic fields and drive XUV emission in fully-convective M dwarfs follow the same evolution with Ro as described above for solar-type stars \citep{Wright2016,Wright2018}. We can therefore apply this model to examine the XUV evolution of individual fully-convective stars.

TRAPPIST-1 \citep{Gillon2016,Gillon2017}, an ultracool dwarf located 12 pc from Earth, harbors 7 approximately Earth-sized transiting planets that are prime targets for JWST transmission spectroscopy observations \citep{Morley2017,Lincowski2018,Lustig2019}. TRAPPIST-1's high observed L$_{X}$ \citep{Wheatley2017}, short photometric rotation period \citep[3.3 d, ][]{Luger2017}, and low Rossby number \citep[Ro $\approx 0.01$, ][]{Roettenbacher2017} suggest that TRAPPIST-1 is still saturated today \citep{Pizzolato2003,Wright2011,Wright2018}. Both \citet{Roettenbacher2017} and \citet{Morris2018} suggest that the photometrically-determined rotation period is inaccurate, with the latter study proposing that the 3.3 d period corresponds to a characteristic timescale for active regions on the stellar surface. TRAPPIST-1's $v \sin i = 6$ km s$^{-1}$ \citep{Barnes2014}, however, implies a rotation period of $\approx 1$ d for $i = 90^{\circ}$, providing evidence that TRAPPIST-1's rapid rotation is physical and consistent with saturation \citep[$P_{rot} \lsim 20$ d,][]{Wright2018}. The TRAPPIST-1 planetary system currently receives significant high-energy fluxes \citep{Bourrier2017b,Wheatley2017,Peacock2019}, possibly a consequence of TRAPPIST-1 remaining in the saturated regime. These fluxes were likely more extreme during the pre-main sequence, driving significant water loss and potentially rendering the planets uninhabitable \citep{Bolmont2017,Bourrier2017a}.

Here, we model the long-term stellar and XUV evolution of TRAPPIST-1 to characterize the evolving XUV environment of its planetary system. We use MCMC to derive probability distributions for our model parameters that describe the XUV evolution and are consistent with TRAPPIST-1's observed properties and their uncertainties. TRAPPIST-1 is not the only system that merits this modelling, however, as the Transiting Exoplanet Survey Satellite will likely discover additional transiting planets orbiting in the habitable zone of nearby M dwarfs \citep{Barclay2018}, some of which will likely be suitable targets for atmospheric characterization with JWST.

In this work, we show that stellar XUV histories can be accurately inferred using machine learning \citep[\approxposterior, ][]{FlemingVanderPlas2018}, but using $330\times$ less computational resources than traditional MCMC methods. This massive speed-up enables our methods to scale to additional stars that host potential targets for atmospheric characterization.

We describe our model and statistical methods in $\S$~\ref{sec:methods} and $\S$~\ref{sec:mcmc}, respectively. We present our results in $\S$~\ref{sec:results}, demonstrate the ability of machine learning to reproduce our analysis in $\S$~\ref{sec:approx}, and discuss the implications of our results in $\S$~\ref{sec:discussion}.

% extra
% , so their dynamos likely differ, e.g. magnetic field generation via convective turbulence \citep{Dobler2006} rather than the tachocline-driven generation theorized for late-type stars with radiative cores \citep{Durney1993}.

\section{Methods} \label{sec:methods}

\subsection{XUV Evolution} \label{sec:model}

We simulate TRAPPIST-1's stellar evolution using the \stellar module in \vplanet\footnote{\vplanet is publicly available at \href{https://github.com/VirtualPlanetaryLaboratory/vplanet}{https://github.com/VirtualPlanetaryLaboratory/vplanet}.} \citep{Barnes2019}, which performs a bicubic interpolation over mass and age of the \citet{Baraffe2015} stellar evolution tracks. The \citet{Baraffe2015} models (also employed by both \citet{Burgasser2017} and \citet{vanGrootel2018} to constrain TRAPPIST-1's stellar properties) were computed for solar metallicity stars and hence are suitable for TRAPPIST-1 whose [Fe/H] is consistent with solar \citep{Gillon2016}, although \citet{Burgasser2017} argue TRAPPIST-1 has a slightly super-solar metallicity based on isochrone modeling.

The X-ray luminosity, L$_{X}$, evolution of fully-convective stars follows the same broken power law model examined for partially-convective FGK stars \citep{Wright2016,Wright2018}. We assume TRAPPIST-1's L$_{XUV}$ evolution traces that of L$_{X}$ and use the model of \citet{Ribas2005},
\begin{align}
\label{eqn:lxuv}
\frac{L_\mathrm{XUV}}{L_\mathrm{bol}} = \left\{
				\begin{array}{lcr}
					f_\mathrm{sat} &\ & t \leq t_\mathrm{sat} \\
					f_\mathrm{sat}\left(\frac{t}{t_\mathrm{sat}}\right)^{-\beta_\mathrm{XUV}} &\ & t > t_\mathrm{sat}
				\end{array}
				\right.,
\end{align}
where $f_{sat}$ is the constant ratio of stellar XUV to bolometric luminosity during the saturated phase, $t_{sat}$ is the duration of the saturated phase, and $\beta_{XUV}$ is the exponent that controls how steeply L$_{XUV}$ decays after saturation.

\subsection{Markov Chain Monte Carlo} \label{sec:mcmc}

We use \texttt{emcee}, a Python implementation of the affine-invariant Metropolis-Hastings MCMC sampling algorithm \citep{ForemanMackey2013}, to infer posterior probability distributions for our model parameters. These distributions are conditioned on observations of TRAPPIST-1 and the activity evolution of late-type stars and account for both observational uncertainties and correlations between parameters. Our model parameters that we fit for via MCMC comprise the state vector
\begin{equation} \label{eqn:state}
    \textbf{x} = \{m_{\star}, f_{sat}, t_{sat}, \mathrm{age}, \beta_{XUV}\},
\end{equation}
where $m_{\star}$ and age are the stellar mass and age, respectively, and the other parameters are defined by Eqn.~\ref{eqn:lxuv}. All of the code used to perform the simulations and analysis in this work is publicly available online.\footnote{ \href{https://github.com/dflemin3/trappist}{https://github.com/dflemin3/trappist}}

\subsection{Priors} \label{sec:mcmc:priors}

Since we have few available observable properties of TRAPPIST-1 to use to condition our analysis ($L_{bol}$ and $L_{XUV}$, see $\S$~\ref{sec:mcmc:like}), our prior probability distributions will strongly impact our results. We use previous studies and empirical data of late M dwarfs to assemble the best available constraints to serve as priors for our MCMC analysis. Following \citet{vanGrootel2018}, we rely on TRAPPIST-1's luminosity and age to constrain its mass. We therefore adopt a simple uniform prior of $m_{\star} \sim \mathcal{U}(0.07, 0.11)$. For the age, we use the empirical estimate for TRAPPIST-1 derived by \citet{Burgasser2017}, age $\sim \mathcal{N}(7.6, 2.2^2)$ Gyr, as their thorough analysis considered both observations of TRAPPIST-1 and a host of empirical age indicators for ultracool dwarfs. We cap the maximum age we consider at 12 Gyr. Younger ages have been suggested based on TRAPPIST-1's activity \citep[e.g.~$\gsim 500$ Myr,][]{Bourrier2017b}, but here we argue that behavior is consistent with an extended saturation timescale.

We construct an empirical $f_{sat} = \log_{10}(L_{XUV}/L_{bol})$ distribution from the sample of fully-convective, saturated M dwarfs with observed $L_{X}$ from \citet{Wright2011}. For each star in the \citet{Wright2011} sample, we follow \citet{Wheatley2017} and estimate $L_{XUV}$ as a function of L$_{X}$ using Eqn.~(2) from \citet{Chadney2015}. We find that the distribution is well-approximated by a normal distribution, $f_{sat} \sim \mathcal{N}(-2.92, 0.26^2)$, and we adopt it as our prior.

The duration of the saturated phase is estimated to be $t_{sat} \approx 100$ Myr for FGK stars \citep{Jackson2012}. Studies of stellar activity of late type stars as a function of stellar age, or its proxy, rotation period, indicate that the activity lifetime, and hence duration of the saturated phase, is likely longer for later-type stars \citep{Shkolnik2014,Wright2011,West2015}, with fully-convective M dwarfs potentially remaining active throughout their lifetimes \citep[$t_{sat} \gsim 7$ Gyr,][]{West2008,Schneider2018}. Furthermore, the spin-down timescales of late M dwarfs increases with decreasing stellar mass \citep{Delfosse1998}, with late M dwarfs retaining rapid rotation longer than earlier-type stars and hence remaining active for up to $P_{rot} \approx 86$ d \citep{West2015}, well-beyond TRAPPIST-1's estimated rotation period. Given these constraints, we adopt a broad uniform $t_{sat}$ prior distribution capped by the maximum age we consider, $t_{sat} \sim \mathcal{U}(0.1, 12)$ Gyr.

In the unsaturated phase, $L_{X}$, and hence $L_{XUV}$, decay exponentially with powerlaw slope $\beta_{XUV}$ \citep{Ribas2005}. \citet{Jackson2012} find that $\beta_{XUV}$ does not significantly vary with stellar mass in their sample of FGK stars. Since \citet{Wright2016} found that the X-ray evolution of fully-convective stars is qualitatively similar to that of partially-convective FGK stars, we adopt the $\beta_{XUV}$ distribution of late K dwarfs from the \citet{Jackson2012} sample as our prior, $\beta_{XUV} \sim \mathcal{N}(-1.18, 0.31^2)$.

%\begin{deluxetable}{lcc}
%\tabletypesize{\small}
%\tablecaption{Prior Distributions \label{tab:priors}}
%\tablewidth{0pt}
%\tablehead{
%\colhead{Parameter [units]} & \colhead{Prior} & \colhead{Notes}
%}
%\startdata
%$m_\star$ [$M_{\odot}$] & $\mathcal{U}(0.07, 0.11)$ & -- \\
%$f_{sat}$ & $\mathcal{N}(-2.92, 0.26^2)$ & \citet{Wright2011}  \\
%$t_{sat}$ [Gyr] & $\mathcal{U}(0.1, 12)$ & -- \\
%age [Gyr] & $\mathcal{N}(7.6, 2.2^2)$ & \citet{Burgasser2017} \\
%$\beta_{XUV}$ & $\mathcal{N}(-1.18, 0.31^2)$ & \citet{Jackson2012}
%\enddata \vspace*{0.1in}
%\end{deluxetable}

\subsection{Likelihood Function and Convergence} \label{sec:mcmc:like}

We further condition our analysis on TRAPPIST-1's observed bolometric luminosity, $L_{bol} = 5.22 \pm{0.19} \times 10^{-4} \ L_{\odot}$ \citep{vanGrootel2018}, and $L_{XUV}/L_{bol}$ \citep{Wheatley2017}. We convolve the \citet{vanGrootel2018} $L_{bol}$ measurement with the $L_{XUV}/L_{bol}$ constraints from \citet{Wheatley2017}, finding $L_{XUV} = 3.9 \pm{0.5} \times 10^{-7} \ L_{\odot}$ today.

For a given state vector \textbf{x}, we define our likelihood function, $\mathcal{L}$, as
\small
\begin{equation} \label{eqn:lnlike}
    \ln \mathcal{L} \propto -\frac{1}{2} \left[ \frac{(L_{bol} - L_{bol}(\textbf{x}))^2}{\sigma_{L_{bol}}^2} + \frac{(L_{XUV} - L_{XUV}(\textbf{x}))^2}{\sigma_{L_{XUV}}^2} \right] \\
\end{equation}
\normalsize
where $L_{bol}$, $L_{XUV}$ and $L_{bol}(\textbf{x})$, $L_{XUV}(\textbf{x})$ are the observed values and \vplanet outputs given \textbf{x}, respectively and $\sigma_{L_{bol}}$ and $\sigma_{L_{XUV}}$ are the observational uncertainties. We compute the total logprobability for each \textbf{x} by summing $\mathcal{L}$ and $\ln \mathrm{Prior}(\textbf{x})$, the log prior probability of \textbf{x}. We compute the log prior using the distributions described in $\S$~\ref{sec:mcmc:priors}.

We run our MCMC with 100 parallel chains for 10,000 iterations, initializing each chain by randomly sampling each element of \textbf{x} from their respective prior distributions. During each step of the MCMC chain, \vplanet takes \textbf{x} as input and simulates TRAPPIST-1's evolution up to the age in \textbf{x}, predicting $L_{bol}$ and $L_{XUV}$ to evaluate the likelihood function. We discard the first 500 iterations as burn-in and assess the convergence of our MCMC chains by computing the integrated autocorrelation length and acceptance fraction for each chain. We find a mean acceptance fraction of 0.45 and a minimum and mean number of iterations per integrated autocorrelation length of 75 and 110, respectively, indicating that our chains have converged \citep{ForemanMackey2013}. Given our integrated autocorrelation lengths, our MCMC chain yielded about 10,000 effective samples from the posterior distribution.

\subsection{Inference with \approxposterior} \label{sec:methods:approx}

The methods presented above can be applied to any late-type star to constrain its $L_{XUV}$ history, given suitable priors and observational constraints. Our MCMC analysis, however, required 3,700 core hours on the University of Washington Hyak supercomputer to converge. The main computational cost is incurred by running a $10$~s \vplanet simulation each MCMC step to evaluate the likelihood, requiring ${\sim}1,000,000$ simulations in total for the full MCMC. Assuming similar convergence properties, repeating this analysis for even a modest sample of 30 stars would require~${\sim} 110,000$ core-hours, a significant computational expense. Moreover, performing a similar analysis with a more computationally-expensive model, perhaps one that interpolates stellar models over metallicity to additionally fit for [Fe/H], would only exacerbate this issue.

We apply \approxposterior\footnote{\approxposterior is publicly available at \href{https://github.com/dflemin3/approxposterior}{https://github.com/dflemin3/approxposterior}.}, an open source Python machine learning package \citep{FlemingVanderPlas2018}, to compute an accurate approximation to the true MCMC-derived posterior distribution for TRAPPIST-1's XUV evolution, while minimizing the computational cost. \approxposterior, an implementation of the ``Bayesian Active Learning for Posterior Estimation" (BAPE) algorithm of \citet{Kandasamy2015}, trains a Gaussian process (GP) surrogate for the likelihood evaluation, learning on the results of \vplanet simulations. The GP is then used within an MCMC sampling algorithm, e.g. \emcee, to quickly obtain the posterior distribution. In our case, predicting the likelihood using the GP (${\sim} 130 \mu$s) is $80,000 \times$ faster than running \vplanet (10s) each likelihood evaluation, yielding a massive reduction in computational cost.

Following \citet{Kandasamy2015}, \approxposterior iteratively improves the GP's predictive ability by identifying high-likelihood regions in parameter space where the GP predictions are uncertain. \approxposterior then evaluates \vplanet in those regions to supplement the training set, improving the GP's predictive ability in the relevant regions of parameter space, while minimizing the number of forward model evaluations required for suitable predictive accuracy. Similar techniques using a GP surrogate model have been shown to rapidly and accurately infer Bayesian posterior distributions for computationally-expensive cosmology studies \citep[e.g.][]{Bird2019}.

To model the covariance between points in the GP training set, we use a squared exponential kernel,
\begin{equation} \label{eqn:kernel}
k(x_i, x_j) = \exp \left( - \frac{(x_i - x_j)^2}{2l^2} \right),
\end{equation}
where $x_i$ and $x_j$ are two arbitrary points in parameter space and $l$ is a hyperparameter that controls the scale length of the correlations. We assume correlations in each dimension have different scale lengths and fit for each $l$ by optimizing the GP's marginal likelihood of the training set data using the Nelder-Mead algorithm, randomly restarting this optimization 25 times to mitigate the influence of local extrema. We run \approxposterior for 10 iterations, initially training the GP on a set of 250 \vplanet simulations with initial conditions sampled from our prior distributions. For each iteration, \approxposterior selects 100 new training points, alternating between the \citet{Kandasamy2015} and \citet{Wang2017} selection criteria, both based on GP predictive uncertainty. \approxposterior runs \vplanet at each point for a total of 1,250 training samples. The trained GP is then used within \emcee to quickly obtain the approximate posterior distribution following the same procedure described in $\S$~\ref{sec:mcmc}.

%% Results %%

\section{Results} \label{sec:results}

\subsection{The Evolution of TRAPPIST-1}

In Fig.~\ref{fig:corner}, we display the posterior probability distributions for our model parameters derived via MCMC. We adopt the median values of the marginalized distributions as our best-fit solutions and derive the lower and upper uncertainties using the 16th and 84th percentiles, respectively.

TRAPPIST-1 likely maintained a large $L_{XUV}$ throughout its lifetime as we find $f_{sat} = -3.05^{+0.24}_{-0.10}$ and $t_{sat} = 6.85^{+3.43}_{-3.15}$ Gyr, consistent with observed $L_{XUV}/L_{bol}$ and long activity lifetimes of late M dwarfs \citep{West2008,Wright2018}. The long upper-tail in the marginalized $f_{sat}$ distribution arises from the combination of the degeneracy between $f_{sat}$ and $t_{sat}$ and from our strong empirical $f_{sat}$ prior that disfavors $f_{sat} \gsim -2.5$. The degeneracy stems from our model attempting to match TRAPPIST-1's observed $L_{XUV}$. For example, larger values of $f_{sat}$ produce high initial $L_{XUV}$, requiring shorter $t_{sat}$, and hence an earlier transition to unsaturated $L_{XUV}$ decay, to decrease $L_{XUV}$ to its observed value, and vice versa. From the posterior distribution, we infer that there is a $43\%$ chance that TRAPPIST-1 is still in the high-$L_{XUV}$ saturated phase today, suggesting that the TRAPPIST-1 planets could have undergone prolonged water loss. Our analysis strongly disfavors short saturation timescales, with only a $0.4\%$ chance that $t_{sat} \leq 1$ Gyr, the saturation timescale adopted by \citet{Luger2015} in their analysis of water loss from exoplanets orbiting in the habitable zone of late M dwarfs.

\begin{figure*}[t]
\centering
	\includegraphics[width=0.75\textwidth]{trappist1Corner.pdf}
   \caption{Joint and marginal posterior probability distributions for the TRAPPIST-1 stellar parameters given in Eqn.~(\ref{eqn:state}) made using \texttt{corner} \citep{ForemanMackey2016}. The black vertical dashed lines on the marginalized distributions indicate the median values and lower and upper uncertainties from the 16th and 84th percentiles, respectively. From the posterior, we infer that there is a $43\%$ chance that TRAPPIST-1 is still in the saturated phase today, potentially driving significant volatile loss from its planets.}%
    \label{fig:corner}%
\end{figure*}

We constrain TRAPPIST-1's mass to $m_{\star} = 0.089 \pm{0.001}$ M$_{\odot}$, in a good agreement with and $6\times$ more precise than the value derived by \citet{vanGrootel2018}. Our marginalized age and $\beta_{XUV}$ posterior distributions reflect their prior distributions as for the former, $L_{bol}$ is not sufficient to further constrain TRAPPIST-1's age beyond our adopted prior since the luminosities of ultracool dwarfs do not significantly change during the main sequence \citep{Baraffe2015}. The posterior for $\beta_{XUV}$ does not vary from the prior because our XUV model is over-parameterized with 3 parameters to fit 2 observations, although all are motivated by empirical data and hence merit inclusion. Our model prefers to exploit the degeneracy between $f_{sat}$ and $t_{sat}$ to match TRAPPIST-1's observed $L_{XUV}$ in our MCMC instead of varying the slope of the unsaturated $L_{XUV}$ decay. Age and $\beta_{XUV}$ weakly correlate with $f_{sat}$, requiring a narrow spread of $f_{sat} \approx -3.05$ for young ages and steeper $\beta_{XUV}$, respectively. $\beta_{XUV}$ and $t_{sat}$ are uncorrelated, except at short $t_{sat}$ where steep $\beta_{XUV}$ are disfavored as this evolution would underpredict the observed $L_{XUV}$.

\subsection{TRAPPIST-1's Evolutionary History}

Here we consider plausible stellar evolutionary histories for TRAPPIST-1 by simulating 100 samples from the posterior distribution using \vplanet. We plot the evolution of TRAPPIST-1's $L_{bol}$, $L_{XUV}$, and radius in Fig.~\ref{fig:evol} and compare our models to the measured values.

\begin{figure*}[t]
	\includegraphics[width=\textwidth]{trappist1Evol.pdf}
   \caption{Plausible evolutionary histories of TRAPPIST-1's $L_{bol}$ (left), $L_{XUV}$ (center), and radius (right) using 100 samples drawn from the posterior distribution and simulated with \vplanet. In each panel, the blue shaded regions display the 1, 2, and 3 $\sigma$ uncertainties. The insets display the marginalized distributions (black) evaluated at the age of the system, with the blue dashed lines indicating the observed value and +/- 1 $\sigma$ uncertainties. The radius, $L_{bol}$, and $L_{XUV}$ constraints are adopted from \citet{vanGrootel2018} and \citet{Wheatley2017}, respectively.}%
    \label{fig:evol}%
\end{figure*}

TRAPPIST-1 remains saturated throughout its $1$ Gyr pre-main sequence, with both $L_{XUV}$ and $L_{bol}$ decreasing by a factor of ${\sim}40$ before stabilizing on the main sequence. TRAPPIST-1's radius likely shrank by roughly a factor of 4 along the pre-main sequence. We derive a present-day radius $R_{\star} = 0.112 \pm{0.001} \ R_{\odot}$ from the posterior distribution, a value that is ${\sim} 7\%$ smaller than the \citet{vanGrootel2018} constraint, $R_{\star} = 0.121 \pm {0.003} \ R_{\odot}$, that was computed from their inferred mass and TRAPPIST-1's density \citep{Delrez2018}. This difference arises from the likely underprediction of TRAPPIST-1's radius by the \citet{Baraffe2015} models, consistent with stellar evolution models often underestimating the radii of late M dwarfs \citep{Reid2005,Spada2013}. An alternate explanation to account for its inflated radius is that TRAPPIST-1 has super-solar metallicity \citep{Burgasser2017,vanGrootel2018}, but \citet{vanGrootel2018} found in their modeling that [Fe/H] = 0.4, a $4.5\sigma$ outlier, was required to reproduce TRAPPIST-1's density and radius. If we instead compute the radius from our marginalized stellar mass posterior distribution and the observed density \citep{Delrez2018}, we obtain $R_{\star} = 0.120 \pm{0.002} \ R_{\odot}$, in agreement with \citet{vanGrootel2018} who used the same procedure.

Since TRAPPIST-1 could still be saturated today, its planetary system has likely experienced a persistent extreme XUV environment. In Fig.~\ref{fig:fluxes}, we probe the distribution of XUV fluxes, $F_{XUV}$, derived from our posterior distributions for each TRAPPIST-1 planet when the system was 0.01, 0.1, and 1 Gyr old. We normalize these values by the $F_{XUV}$ received by Earth during the mean solar cycle \citep[$F_{XUV,\oplus} = 3.88$ erg s$^{-1}$cm$^{-2}$,][]{Ribas2005} and assume the planets remained near their current semi-major axes after migration in the natal protoplanetary disk halted \citep{Luger2017}. We infer that TRAPPIST-1b likely received extreme $F_{XUV}/F_{XUV, \oplus} \gsim 10^4$ during the early pre-main sequence before decaying to the present-day $F_{XUV}/F_{XUV, \oplus} \approx 10^3$, consistent with estimates from \citet{Wheatley2017}. The extended upper-tail of the $F_{XUV}$ distributions corresponds to the large $f_{sat}$ values permitted by the posterior distributions. The likely habitable zone planets, e, f, and g, similarly experienced severe XUV fluxes ranging from $F_{XUV}/F_{XUV, \oplus} \approx 10^2 - 10^{3.5}$ throughout the pre-main sequence. Even today, e, f, and g receive $F_{XUV}/F_{XUV, \oplus} \approx 10^2$, far in excess of the modern Earth, due to TRAPPIST-1's large present $L_{XUV}$, its extended saturated phase, and the close proximity of M dwarf HZ planets to their host star. These significant high energy fluxes likely drove an extended epoch of substantial atmospheric escape and water loss from the TRAPPIST-1 planets, potentially producing substantial abiotic O$_2$ atmospheres \citep{Luger2015,Bolmont2017,Bourrier2017a}.

\begin{figure}
	\includegraphics[width=\columnwidth]{fluxes.pdf}
   \caption{$F_{XUV}/F_{XUV,\oplus}$ for each TRAPPIST-1 planet derived from samples drawn from the posterior distribution and simulated using \vplanet when the system was 0.01, 0.1, and 1 Gyr old. The latter age corresponds to the approximate age at which TRAPPIST-1 entered the main sequence.}%
    \label{fig:fluxes}%
\end{figure}

%% approxposterior %%

\subsection{Comparison with \approxposterior} \label{sec:approx}

% Extra
%If using a slower model than ours, perhaps one that models stellar evolution by interpolating tracks over mass, age, and metallicity to additionally constrain [Fe/H], or if testing alternate models of $L_{XUV}$ evolution for model comparisons, the computational expense will grow, exacerbating this issue.

\begin{figure*}[t]
\centering
	\includegraphics[width=0.75\textwidth]{apCorner.pdf}
   \caption{Same format as Fig.~\ref{fig:corner}, but derived by \approxposterior.}%
    \label{fig:approx}%
\end{figure*}

Here we compare the approximate posterior distribution derived using \approxposterior with our previous results (referred to as the fiducial MCMC). We display the approximate joint and marginalized posterior distributions in Fig.~\ref{fig:approx}. We find that \approxposterior requires only 11 core hours to derive the approximate posterior distribution, a factor of $330\times$ faster than our fiducial MCMC. \approxposterior also used $800\times$ fewer \vplanet simulations to build its training set than the ${\sim}10^6$ simulations ran by the fiducial MCMC for likelihood evaluations. This reduction in computational expense arises from \approxposterior's GP-based likelihood predictions only taking ${\sim}130\mu$s, compared to the much longer $10$~s per \vplanet simulation. Moreover, \approxposterior's efficient selection of the GP's training set focuses on high-likelihood regions to improve the GP's predictive ability in relevant regions of parameter space while minimizing the training set size.

In Table~\ref{tab:constraints}, we list the marginalized constraints derived by both methods and find that both the median values and magnitude of the uncertainties are in good agreement. Furthermore as seen in Fig.~\ref{fig:approx}, \approxposterior recovers the same non-trivial correlations between model parameters seen in the fiducial MCMC posterior distribution.

The posterior distribution derived by \approxposterior, however, is not an exact match. \approxposterior underestimates the magnitude of both the age and $\beta_{XUV}$ uncertainties by ${\sim}30\%$ and predicts that there is a $39\%$ chance that TRAPPIST-1 is still saturated today, $9\%$ smaller than the fiducial MCMC-derived value. Our experiment demonstrates that \approxposterior can be used to derive accurate approximations to the posterior probability distributions of the parameters that control stellar XUV evolution in late M dwarfs, but significantly faster than traditional MCMC methods.

\begin{deluxetable}{lcc}
\caption{Parameter Constraints} \label{tab:constraints}
\tabletypesize{\small}
\tablewidth{0pt}
\tablehead{
\colhead{Parameter [units]} & \colhead{\vplanet MCMC} & \colhead{\approxposterior MCMC}
}
\startdata
$m_\star$ [$M_{\odot}$] & $0.089 \pm{0.001}$ & $0.089 \pm{0.001}$ \\
$f_{sat}$ & $-3.05^{+0.24}_{-0.10}$ & $-3.03^{+0.20}_{-0.10}$,  \\
$t_{sat}$ [Gyr] & $6.85^{+3.43}_{-3.15}$ & $6.62^{+3.56}_{-2.56}$ \\
age [Gyr] & $7.44^{+2.04}_{-2.13}$ & $7.54^{+1.43}_{-1.51}$ \\
$\beta_{XUV}$ & $-1.16^{+0.31}_{-0.30}$ & $-1.16^{+0.21}_{-0.21}$ \\
P$(\mathrm{saturated})$ & $0.43$ & $0.39$ \\
\enddata \vspace*{0.1in}
\tablecomments{Best fit values and uncertainties are derived using the medians, $16^{th}$, and $84^{th}$ percentiles from the marginalized posterior distributions, respectively.}
\end{deluxetable}

%% Discussion %%

\section{Discussion and Conclusions} \label{sec:discussion}

Here, we used MCMC to derive probabilistic constraints for TRAPPIST-1's stellar and $L_{XUV}$ evolution to characterize the evolving XUV environment of its planetary system. We inferred that TRAPPIST-1 likely maintained high $L_{XUV}/L_{bol} \approx 10^{-3}$ throughout its lifetime, with a $43\%$ chance that TRAPPIST-1 is still in the saturated regime today. Our results indicate that ultracool dwarfs can sustain large $L_{XUV}$ in the saturated regime for Gyrs, consistent with activity lifetimes of late M dwarfs \citep{West2008}. Our choice of prior distributions strongly impact our results as our inference hinges on only two measured properties of TRAPPIST-1, $L_{XUV}$ and $L_{bol}$. To mitigate this effect, we consulted previous studies and empirical observations of the activity evolution of late M dwarfs to construct realistic prior distributions.

The TRAPPIST-1 planets likely experienced significant XUV fluxes during the pre-main sequence, potentially driving extreme atmospheric erosion and water loss \citep{Bolmont2017,Bourrier2017a}. The high-energy fluxes incident on the inner-most planets throughout this phase were probably large enough for atmospheric mass loss to be recombination-limited ($F_{UV} \gsim 10^4$ g s$^{-1}$ cm$^{-2}$) and scale as $\dot{m} \sim F_{XUV}^{0.6}$ \citep{MurrayClay2009}, as opposed to the oft-assumed energy-limited escape \citep[$\dot{m} \sim F_{XUV}$,][]{Watson1981,Lammer2003}, potentially inhibiting volatile loss. If the TRAPPIST-1 planets did lose significant amounts of water as our estimates suggest, they must have formed with a large initial volatile inventory to account for their observed low densities \citep{Grimm2018}.

We demonstrated that the machine learning Python package, \approxposterior \citep{FlemingVanderPlas2018}, can efficiently compute an approximation to the posterior distribution using an adaptive GP-based method, requiring $800\times$ fewer \vplanet simulations and a factor of $330\times$ less core hours than traditional MCMC approaches for this application. The posterior distributions derived by \approxposterior accurately reproduced the non-trivial parameter correlations and best-fit values uncovered by our fiducial MCMC analysis. The agreement is not perfect, however as \approxposterior underestimated the magnitude of the uncertainties of two parameters by ${\sim}30\%$.

Finally, we note that our methodology constrains parameters that describe the long-term XUV evolution of the star, conditioned on measurements. In principle, this approach can be extended to obtain evolutionary histories of planetary systems in general.  For example, in Figures~\ref{fig:evol} and \ref{fig:fluxes}, we examined the long-term evolution of TRAPPIST-1 and the evolving XUV fluxes received by its planetary system, respectively, with samples drawn from the posterior distribution. Future research can combine those results with additional physical effects, e.g. water loss or tidal dissipation, to build a probabilistic model for the long-term evolution of the planetary system, given our model for the underlying physics, to characterize its present state. While simulating additional physical effects will inevitably increase the computational expense, we have demonstrated that \approxposterior can enable such efforts and provide insight into the histories of stars and their planets.

% extra
% Applying these methods to other M dwarfs, however, requires measuring their current $L_{X}$ or $L_{XUV}$, a difficult task given that most M and ultracool dwarfs are faint and that much of the stellar EUV radiation is absorbed by neutral interstellar hydrogen \citep{Airapetian2019}. These quantities, however, can be reconstructed via empirical scaling relations \citep[e.g.][]{Linsky2014}.
% The accuracy and massive reduction in compute time afforded by \approxposterior enables our analysis to scale to a larger sample of late M dwarfs to constrain their XUV histories.

%% ACKNOWLEDGEMENTS %%
\acknowledgments
This work was facilitated though the use of advanced computational, storage, and networking infrastructure provided by the Hyak supercomputer system and funded by the Student Technology Fund at the University of Washington. DPF was supported by NASA Headquarters under the NASA Earth and Space Science Fellowship Program - Grant 80NSSC17K0482.  This work was supported by the NASA Astrobiology Program Grant Number 80NSSC18K0829 and benefited from participation in the NASA Nexus for Exoplanet Systems Science research coordination network.

%% SOFTWARE %%
\software{\approxposterior: \citet{FlemingVanderPlas2018}, \texttt{corner}: \citet{ForemanMackey2016}, \texttt{emcee}: \citet{ForemanMackey2013}, \vplanet: \citet{Barnes2019}}

%% BIBLIOGRAPHY %%

\begin{thebibliography}{}
\expandafter\ifx\csname natexlab\endcsname\relax\def\natexlab#1{#1}\fi
\providecommand{\url}[1]{\href{#1}{#1}}

\bibitem[{{Baraffe} {et~al.}(2015){Baraffe}, {Homeier}, {Allard}, \&
  {Chabrier}}]{Baraffe2015}
{Baraffe}, I., {Homeier}, D., {Allard}, F., \& {Chabrier}, G. 2015, \aap, 577,
  A42

\bibitem[{{Barclay} {et~al.}(2018){Barclay}, {Pepper}, \&
  {Quintana}}]{Barclay2018}
{Barclay}, T., {Pepper}, J., \& {Quintana}, E.~V. 2018, \apjs, 239, 2

\bibitem[{{Barnes} {et~al.}(2014){Barnes}, {Jenkins}, {Jones}, {Jeffers},
  {Rojo}, {Arriagada}, {Jord{\'a}n}, {Minniti}, {Tuomi}, {Pinfield}, \&
  {Anglada-Escud{\'e}}}]{Barnes2014}
{Barnes}, J.~R., {Jenkins}, J.~S., {Jones}, H.~R.~A., {et~al.} 2014, \mnras,
  439, 3094

\bibitem[{{Barnes} {et~al.}(2019){Barnes}, {Luger}, {Deitrick}, {Driscoll},
  {Quinn}, {Fleming}, {Smotherman}, {McDonald}, {Wilhelm}, {Garcia}, {Barth},
  {Guyer}, {Meadows}, {Bitz}, {Gupta}, {Domagal-Goldman}, \&
  {Armstrong}}]{Barnes2019}
{Barnes}, R., {Luger}, R., {Deitrick}, R., {et~al.} 2019, arXiv e-prints,
  arXiv:1905.06367

\bibitem[{{Bird} {et~al.}(2019){Bird}, {Rogers}, {Peiris}, {Verde},
  {Font-Ribera}, \& {Pontzen}}]{Bird2019}
{Bird}, S., {Rogers}, K.~K., {Peiris}, H.~V., {et~al.} 2019, \jcap, 2, 050

\bibitem[{{Bolmont} {et~al.}(2017){Bolmont}, {Gallet}, {Mathis}, {Charbonnel},
  {Amard}, \& {Alibert}}]{Bolmont2017}
{Bolmont}, E., {Gallet}, F., {Mathis}, S., {et~al.} 2017, \aap, 604, A113

\bibitem[{{Bourrier} {et~al.}(2017{\natexlab{a}}){Bourrier}, {Ehrenreich},
  {Wheatley}, {Bolmont}, {Gillon}, {de Wit}, {Burgasser}, {Jehin}, {Queloz}, \&
  {Triaud}}]{Bourrier2017b}
{Bourrier}, V., {Ehrenreich}, D., {Wheatley}, P.~J., {et~al.}
  2017{\natexlab{a}}, \aap, 599, L3

\bibitem[{{Bourrier} {et~al.}(2017{\natexlab{b}}){Bourrier}, {de Wit},
  {Bolmont}, {Stamenkovi{\'c}}, {Wheatley}, {Burgasser}, {Delrez}, {Demory},
  {Ehrenreich}, {Gillon}, {Jehin}, {Leconte}, {Lederer}, {Lewis}, {Triaud}, \&
  {Van Grootel}}]{Bourrier2017a}
{Bourrier}, V., {de Wit}, J., {Bolmont}, E., {et~al.} 2017{\natexlab{b}}, \aj,
  154, 121

\bibitem[{{Burgasser} \& {Mamajek}(2017)}]{Burgasser2017}
{Burgasser}, A.~J., \& {Mamajek}, E.~E. 2017, \apj, 845, 110

\bibitem[{{Chadney} {et~al.}(2015){Chadney}, {Galand}, {Unruh}, {Koskinen}, \&
  {Sanz-Forcada}}]{Chadney2015}
{Chadney}, J.~M., {Galand}, M., {Unruh}, Y.~C., {Koskinen}, T.~T., \&
  {Sanz-Forcada}, J. 2015, \icarus, 250, 357

\bibitem[{Delfosse {et~al.}(1998)Delfosse, Forveille, Perrier, \&
  Mayor}]{Delfosse1998}
Delfosse, X., Forveille, T., Perrier, C., \& Mayor, M. 1998, Astronomy and
  Astrophysics, 331, 581

\bibitem[{{Delrez} {et~al.}(2018){Delrez}, {Gillon}, {Triaud}, {Demory}, {de
  Wit}, {Ingalls}, {Agol}, {Bolmont}, {Burdanov}, {Burgasser}, {Carey},
  {Jehin}, {Leconte}, {Lederer}, {Queloz}, {Selsis}, \& {Van
  Grootel}}]{Delrez2018}
{Delrez}, L., {Gillon}, M., {Triaud}, A.~H.~M.~J., {et~al.} 2018, \mnras, 475,
  3577

\bibitem[{{Dressing} \& {Charbonneau}(2015)}]{Dressing2015}
{Dressing}, C.~D., \& {Charbonneau}, D. 2015, \apj, 807, 45

\bibitem[{{Fleming} \& {VanderPlas}(2018)}]{FlemingVanderPlas2018}
{Fleming}, D.~P., \& {VanderPlas}, J. 2018, The Journal of Open Source
  Software, 3, 781

\bibitem[{{Foreman-Mackey}(2016)}]{ForemanMackey2016}
{Foreman-Mackey}, D. 2016, The Journal of Open Source Software, 1,
  doi:10.21105/joss.00024

\bibitem[{{Foreman-Mackey} {et~al.}(2013){Foreman-Mackey}, {Hogg}, {Lang}, \&
  {Goodman}}]{ForemanMackey2013}
{Foreman-Mackey}, D., {Hogg}, D.~W., {Lang}, D., \& {Goodman}, J. 2013, \pasp,
  125, 306

\bibitem[{{Gillon} {et~al.}(2016){Gillon}, {Jehin}, {Lederer}, {Delrez}, {de
  Wit}, {Burdanov}, {Van Grootel}, {Burgasser}, {Triaud}, {Opitom}, {Demory},
  {Sahu}, {Bardalez Gagliuffi}, {Magain}, \& {Queloz}}]{Gillon2016}
{Gillon}, M., {Jehin}, E., {Lederer}, S.~M., {et~al.} 2016, \nat, 533, 221

\bibitem[{{Gillon} {et~al.}(2017){Gillon}, {Triaud}, {Demory}, {Jehin}, {Agol},
  {Deck}, {Lederer}, {de Wit}, {Burdanov}, {Ingalls}, {Bolmont}, {Leconte},
  {Raymond}, {Selsis}, {Turbet}, {Barkaoui}, {Burgasser}, {Burleigh}, {Carey},
  {Chaushev}, {Copperwheat}, {Delrez}, {Fernandes}, {Holdsworth}, {Kotze}, {Van
  Grootel}, {Almleaky}, {Benkhaldoun}, {Magain}, \& {Queloz}}]{Gillon2017}
{Gillon}, M., {Triaud}, A.~H.~M.~J., {Demory}, B.-O., {et~al.} 2017, \nat, 542,
  456

\bibitem[{{Grimm} {et~al.}(2018){Grimm}, {Demory}, {Gillon}, {Dorn}, {Agol},
  {Burdanov}, {Delrez}, {Sestovic}, {Triaud}, {Turbet}, {Bolmont}, {Caldas},
  {de Wit}, {Jehin}, {Leconte}, {Raymond}, {Van Grootel}, {Burgasser}, {Carey},
  {Fabrycky}, {Heng}, {Hernandez}, {Ingalls}, {Lederer}, {Selsis}, \&
  {Queloz}}]{Grimm2018}
{Grimm}, S.~L., {Demory}, B.-O., {Gillon}, M., {et~al.} 2018, \aap, 613, A68

\bibitem[{{Jackson} {et~al.}(2012){Jackson}, {Davis}, \&
  {Wheatley}}]{Jackson2012}
{Jackson}, A.~P., {Davis}, T.~A., \& {Wheatley}, P.~J. 2012, \mnras, 422, 2024

\bibitem[{Kandasamy {et~al.}(2015)Kandasamy, Schneider, \&
  Poczos}]{Kandasamy2015}
Kandasamy, K., Schneider, J., \& Poczos, B. 2015, in {International Joint
  Conference on Artificial Intelligence}

\bibitem[{{Lammer} {et~al.}(2003){Lammer}, {Selsis}, {Ribas}, {Guinan},
  {Bauer}, \& {Weiss}}]{Lammer2003}
{Lammer}, H., {Selsis}, F., {Ribas}, I., {et~al.} 2003, \apjl, 598, L121

\bibitem[{{Lincowski} {et~al.}(2018){Lincowski}, {Meadows}, {Crisp},
  {Robinson}, {Luger}, {Lustig-Yaeger}, \& {Arney}}]{Lincowski2018}
{Lincowski}, A.~P., {Meadows}, V.~S., {Crisp}, D., {et~al.} 2018, \apj, 867, 76

\bibitem[{{Luger} \& {Barnes}(2015)}]{Luger2015}
{Luger}, R., \& {Barnes}, R. 2015, Astrobiology, 15, 119

\bibitem[{{Luger} {et~al.}(2017){Luger}, {Sestovic}, {Kruse}, {Grimm},
  {Demory}, {Agol}, {Bolmont}, {Fabrycky}, {Fernandes}, {Van Grootel},
  {Burgasser}, {Gillon}, {Ingalls}, {Jehin}, {Raymond}, {Selsis}, {Triaud},
  {Barclay}, {Barentsen}, {Howell}, {Delrez}, {de Wit}, {Foreman-Mackey},
  {Holdsworth}, {Leconte}, {Lederer}, {Turbet}, {Almleaky}, {Benkhaldoun},
  {Magain}, {Morris}, {Heng}, \& {Queloz}}]{Luger2017}
{Luger}, R., {Sestovic}, M., {Kruse}, E., {et~al.} 2017, Nature Astronomy, 1,
  0129

\bibitem[{{Lustig-Yaeger} {et~al.}(2019){Lustig-Yaeger}, {Meadows}, \&
  {Lincowski}}]{Lustig2019}
{Lustig-Yaeger}, J., {Meadows}, V.~S., \& {Lincowski}, A.~P. 2019, arXiv
  e-prints, arXiv:1905.07070

\bibitem[{{Morley} {et~al.}(2017){Morley}, {Kreidberg}, {Rustamkulov},
  {Robinson}, \& {Fortney}}]{Morley2017}
{Morley}, C.~V., {Kreidberg}, L., {Rustamkulov}, Z., {Robinson}, T., \&
  {Fortney}, J.~J. 2017, \apj, 850, 121

\bibitem[{{Morris} {et~al.}(2018){Morris}, {Agol}, {Davenport}, \&
  {Hawley}}]{Morris2018}
{Morris}, B.~M., {Agol}, E., {Davenport}, J.~R.~A., \& {Hawley}, S.~L. 2018,
  \apj, 857, 39

\bibitem[{{Murray-Clay} {et~al.}(2009){Murray-Clay}, {Chiang}, \&
  {Murray}}]{MurrayClay2009}
{Murray-Clay}, R.~A., {Chiang}, E.~I., \& {Murray}, N. 2009, \apj, 693, 23

\bibitem[{{Parker}(1955)}]{Parker1955}
{Parker}, E.~N. 1955, \apj, 122, 293

\bibitem[{{Peacock} {et~al.}(2019){Peacock}, {Barman}, {Shkolnik},
  {Hauschildt}, \& {Baron}}]{Peacock2019}
{Peacock}, S., {Barman}, T., {Shkolnik}, E.~L., {Hauschildt}, P.~H., \&
  {Baron}, E. 2019, \apj, 871, 235

\bibitem[{{Pizzolato} {et~al.}(2003){Pizzolato}, {Maggio}, {Micela},
  {Sciortino}, \& {Ventura}}]{Pizzolato2003}
{Pizzolato}, N., {Maggio}, A., {Micela}, G., {Sciortino}, S., \& {Ventura}, P.
  2003, \aap, 397, 147

\bibitem[{{Reid} \& {Hawley}(2005)}]{Reid2005}
{Reid}, I.~N., \& {Hawley}, S.~L. 2005, {New light on dark stars : red dwarfs,
  low-mass stars, brown dwarfs}, doi:10.1007/3-540-27610-6

\bibitem[{{Ribas} {et~al.}(2005){Ribas}, {Guinan}, {G{\"u}del}, \&
  {Audard}}]{Ribas2005}
{Ribas}, I., {Guinan}, E.~F., {G{\"u}del}, M., \& {Audard}, M. 2005, \apj, 622,
  680

\bibitem[{{Roettenbacher} \& {Kane}(2017)}]{Roettenbacher2017}
{Roettenbacher}, R.~M., \& {Kane}, S.~R. 2017, \apj, 851, 77

\bibitem[{{Schneider} \& {Shkolnik}(2018)}]{Schneider2018}
{Schneider}, A.~C., \& {Shkolnik}, E.~L. 2018, \aj, 155, 122

\bibitem[{{Segura} {et~al.}(2005){Segura}, {Kasting}, {Meadows}, {Cohen},
  {Scalo}, {Crisp}, {Butler}, \& {Tinetti}}]{Segura2005}
{Segura}, A., {Kasting}, J.~F., {Meadows}, V., {et~al.} 2005, Astrobiology, 5,
  706

\bibitem[{{Shkolnik} \& {Barman}(2014)}]{Shkolnik2014}
{Shkolnik}, E.~L., \& {Barman}, T.~S. 2014, \aj, 148, 64

\bibitem[{{Skumanich}(1972)}]{Skumanich1972}
{Skumanich}, A. 1972, \apj, 171, 565

\bibitem[{{Spada} {et~al.}(2013){Spada}, {Demarque}, {Kim}, \&
  {Sills}}]{Spada2013}
{Spada}, F., {Demarque}, P., {Kim}, Y.-C., \& {Sills}, A. 2013, \apj, 776, 87

\bibitem[{{Vaiana} {et~al.}(1981){Vaiana}, {Cassinelli}, {Fabbiano},
  {Giacconi}, {Golub}, {Gorenstein}, {Haisch}, {Harnden}, {Johnson}, {Linsky},
  {Maxson}, {Mewe}, {Rosner}, {Seward}, {Topka}, \& {Zwaan}}]{Vaiana1981}
{Vaiana}, G.~S., {Cassinelli}, J.~P., {Fabbiano}, G., {et~al.} 1981, \apj, 245,
  163

\bibitem[{{Van Grootel} {et~al.}(2018){Van Grootel}, {Fernandes}, {Gillon},
  {Jehin}, {Manfroid}, {Scuflaire}, {Burgasser}, {Barkaoui}, {Benkhaldoun},
  {Burdanov}, {Delrez}, {Demory}, {de Wit}, {Queloz}, \&
  {Triaud}}]{vanGrootel2018}
{Van Grootel}, V., {Fernandes}, C.~S., {Gillon}, M., {et~al.} 2018, \apj, 853,
  30

\bibitem[{{Wang} \& {Li}(2017)}]{Wang2017}
{Wang}, H., \& {Li}, J. 2017, ArXiv e-prints, arXiv:1703.09930

\bibitem[{{Watson} {et~al.}(1981){Watson}, {Donahue}, \& {Walker}}]{Watson1981}
{Watson}, A.~J., {Donahue}, T.~M., \& {Walker}, J.~C.~G. 1981, \icarus, 48, 150

\bibitem[{{West} {et~al.}(2008){West}, {Hawley}, {Bochanski}, {Covey}, {Reid},
  {Dhital}, {Hilton}, \& {Masuda}}]{West2008}
{West}, A.~A., {Hawley}, S.~L., {Bochanski}, J.~J., {et~al.} 2008, \aj, 135,
  785

\bibitem[{{West} {et~al.}(2015){West}, {Weisenburger}, {Irwin},
  {Berta-Thompson}, {Charbonneau}, {Dittmann}, \& {Pineda}}]{West2015}
{West}, A.~A., {Weisenburger}, K.~L., {Irwin}, J., {et~al.} 2015, \apj, 812, 3

\bibitem[{{Wheatley} {et~al.}(2017){Wheatley}, {Louden}, {Bourrier},
  {Ehrenreich}, \& {Gillon}}]{Wheatley2017}
{Wheatley}, P.~J., {Louden}, T., {Bourrier}, V., {Ehrenreich}, D., \& {Gillon},
  M. 2017, \mnras, 465, L74

\bibitem[{{Wright} \& {Drake}(2016)}]{Wright2016}
{Wright}, N.~J., \& {Drake}, J.~J. 2016, \nat, 535, 526

\bibitem[{{Wright} {et~al.}(2011){Wright}, {Drake}, {Mamajek}, \&
  {Henry}}]{Wright2011}
{Wright}, N.~J., {Drake}, J.~J., {Mamajek}, E.~E., \& {Henry}, G.~W. 2011,
  \apj, 743, 48

\bibitem[{{Wright} {et~al.}(2018){Wright}, {Newton}, {Williams}, {Drake}, \&
  {Yadav}}]{Wright2018}
{Wright}, N.~J., {Newton}, E.~R., {Williams}, P.~K.~G., {Drake}, J.~J., \&
  {Yadav}, R.~K. 2018, \mnras, 479, 2351

\end{thebibliography}

% End of file
\end{document}


\subsection{Choosing K for K-Nearest Neighbours}


\vssub
\subsubsection{~Rotated grids} \label{sub:num_space_rotagrid}
\opthead{RTD}{\ws\ (MetOffice)}{J.-G. Li}

\noindent
The rotated grid is a latitude-longitude (lat-lon) grid and is obtained by
rotating the North Pole to a new position at latitude $\phi_{p}$ and
longitude $\lambda_{p}$ in the standard latitude-longitude system.  The new
pole position is chosen so that the model domain of interest may be placed
around the rotated equatorial area for a evenly-spaced lat-lon mesh. For this
reason the rotated grid is also known as \emph{Equatorial grid}. For instance,
the North Atlantic and European wave (NAEW) model used in the UK Met Office
uses a rotated pole at 37.5N, 177.5E so that London, UK
(\textasciitilde{}51.5N 0.0E) is almost on the rotated equator. This rotated
grid allows a much more evenly spaced lat-lon mesh in the NAEW domain than the
standard lat-lon grid in the same area.

In \ws\, the rotated grid is implemented with minimum changes to the original
lat-lon grid. In fact, the rotated grid is treated just like the standard
lat-lon grid inside the model. To set up and run a rotated grid model configuration,
users should choose the regular lat-lon grid along with the {\code RTD} switch.
The rotated pole position is set using the {\code PLAT} and {\code PLON} variables in the
{\bf ww3\_grid.inp} namelist {\code ROTD}. Model input files, like wind, current and ice files
should be mapped on to the rotated grid. For convenience of nesting in standard
lat-lon grid frameworks, boundary conditions provided to and output from the
rotated grid use spectra referenced to a standard grid north and standard lat-lon
grid points values, which are converted into rotated grid lat-lon inside \ws\.
The list of 2D spectral output locations in {\bf ww3\_shel.inp} are also specified in
standard lat-lon.

Model directional and x-y vector outputs can be converted to a standard grid
north reference by setting the UNROT variable in the {\bf ww3\_grid.inp} namelist
ROTD to True. With this set, for point outputs lat-lon locations all directional
values such as wind direction, current direction and 2D spectra are converted
into standard lat-lon orientation. Functions to de-rotate gridded
fields are applied in {\bf ww3\_ounf}, {\bf ww3\_outf} and {\bf ww3\_grib}.
When running {\bf ww3\_ounf} and {\bf ww3\_ounp}, the resulting netCDF
files will include a variable attribute direction\_reference, which describes
whether a standard (True North) or rotated grid directional reference frame
has been used. Gridded netCDF files generated by {\bf ww3\_ounf} also include
\emph{standard\_latitude} and \emph{standard\_longitude} two-dimensional arrays
that describe location of the rotated model cell centres in the standard lat-lon
reference frame.

Six subroutines are provided in module {\bf w3servmd.ftn} for rotated grid
conversion:
\begin{vlist}
\vit{w3spectn}{}{Turns wave spectrum anti-clockwise by AnglD}
\vit{w3acturn}{}{Turns wave action(k,nth) anti-clockwise by AnglD}
\vit{w3thrtn}{}{Turns direction parameters anti-clockwise by AnglD}
\vit{w3xyrtn}{}{Turns x-y vector parameters anti-clockwise by AnglD}
\vit{w3lltoeq}{}{Convert standard into rotated lat/lon plus AnglD}
\vit{w3eqtoll}{}{Reverse of w3lltoeq, but AnglD unchanged}
\end{vlist}
These subroutines are self-contained and can be extracted outside the model
for pre- or post-processing of rotated grid files.  Some conversion tools have
been developed based on these subroutines but have not been included in \ws\
yet. Refer to the regression test \emph{regtests/ww3\_tp2.11} for an example
of a rotated grid model (NAEW).  Users may find more information in
\emph{smc\_docs/Rotated\_Grid.pdf} or contact Jian-Guo Li for help
(\url{Jian-Guo.Li@metoffice.gov.uk}).


\chapter{The unwind Library}

This document describes the facilities provided by the \ml{unwind} library
for the HOL system~\cite{description}. The library provides conversions and
rules for unfolding, unwinding and pruning device implementations (logical
representations of hardware). For a detailed description of these techniques,
see~\cite{HVusingHOL}.

Most of the functions fall into one of five groups. The first group consists
of conversions and inference rules for moving universal quantifiers up and
down through conjunctions; they have names beginning with either
\ml{CONJ\_FORALL} or \ml{FORALL\_CONJ}. The second group of functions are for
unfolding, that is expanding sub-components using their definitions. The names
of these begin with \ml{UNFOLD}. The functions in the third group perform
unwinding and have names beginning with \ml{UNWIND}. The fourth group of
functions prune internal lines that have been unwound. Their names begin with
\ml{PRUNE}. The final group of functions combine unfolding, unwinding and
pruning. They have names beginning with \ml{EXPAND}.

I have tried to make the behaviour of the functions uniform. The conversions
apply to the smallest term possible, to provide maximum flexibility. The
inference rules, on the other hand, are designed to apply to the definition
of a hardware component. They expect to be given a theorem of the form:

\begin{small}\begin{verbatim}
   |- !x1 ... xn. DEVICE (x1,...,xn) = ?l1 ... lm. t1 /\ ... /\ tp
\end{verbatim}\end{small}

\section{Using the library}

The \ml{unwind} library can be loaded into a \HOL\ session using the function
\ml{load\_library}\index{load\_library@{\ptt load\_library}} (see the \HOL\
manual for a general description of library loading). The first action in the
load sequence initiated by \ml{load\_library} is to update the \HOL\
help\index{help!updating search path} search path. The help search path is
updated with a pathname to online help files for the \ML\ functions in the
library. After updating the help search path, the \ML\ functions in the
library are loaded into \HOL.

The following session shows how the \ml{unwind} library may be loaded using
\ml{load\_library}:

\setcounter{sessioncount}{1}
\begin{session}\begin{verbatim}
#load_library `unwind`;;
Loading library `unwind` ...
Updating help search path
..................................
Library `unwind` loaded.
() : void
\end{verbatim}\end{session}

We now illustrate the use of the library on the parity-checker example.
Firstly, we begin a new theory:

\begin{session}\begin{verbatim}
#new_theory `PARITY`;;
() : void
\end{verbatim}\end{session}

\vfill

\noindent
We define the sub-components used:

\vfill

\begin{session}\begin{verbatim}
#let ONE_DEF =
# new_definition
#  (`ONE_DEF`, "ONE(out:num->bool) = !t. out t = T");;
ONE_DEF = |- !out. ONE out = (!t. out t = T)
\end{verbatim}\end{session}

\vfill

\begin{session}\begin{verbatim}
#let NOT_DEF =
# new_definition
#  (`NOT_DEF`, "NOT(in,out:num->bool) = !t. out t = ~(in t)");;
NOT_DEF = |- !in out. NOT(in,out) = (!t. out t = ~in t)
\end{verbatim}\end{session}

\vfill

\begin{session}\begin{verbatim}
#let MUX_DEF =
# new_definition
#  (`MUX_DEF`,
#   "MUX(sw,in1,in2,out:num->bool) =
#     !t. out t = (sw t => in1 t | in2 t)");;
MUX_DEF =
|- !sw in1 in2 out.
    MUX(sw,in1,in2,out) = (!t. out t = (sw t => in1 t | in2 t))
\end{verbatim}\end{session}

\vfill

\begin{session}\begin{verbatim}
#let REG_DEF =
# new_definition
# (`REG_DEF`, "REG(in,out:num->bool) =
#              !t. out t = ((t=0) => F | in(t-1))");;
REG_DEF =
|- !in out. REG(in,out) = (!t. out t = ((t = 0) => F | in(t - 1)))
\end{verbatim}\end{session}

\vfill

\noindent
Now we define the parity-checker implementation:

\begin{session}\begin{verbatim}
#let PARITY_IMP_DEF =
# new_definition
#  (`PARITY_IMP_DEF`,
#   "PARITY_IMP(in,out) =
#    ?l1 l2 l3 l4 l5.
#     NOT(l2,l1) /\ MUX(in,l1,l2,l3) /\ REG(out,l2) /\
#     ONE l4     /\ REG(l4,l5)       /\ MUX(l5,l3,l4,out)");;
PARITY_IMP_DEF =
|- !in out.
    PARITY_IMP(in,out) =
    (?l1 l2 l3 l4 l5.
      NOT(l2,l1) /\
      MUX(in,l1,l2,l3) /\
      REG(out,l2) /\
      ONE l4 /\
      REG(l4,l5) /\
      MUX(l5,l3,l4,out))
\end{verbatim}\end{session}

\noindent
The function \ml{EXPAND\_AUTO\_RIGHT\_RULE} can be used to unfold, unwind and
prune the body of this definition:

\begin{session}\begin{verbatim}
#EXPAND_AUTO_RIGHT_RULE [ONE_DEF;NOT_DEF;MUX_DEF;REG_DEF] PARITY_IMP_DEF;;
|- !in out.
    PARITY_IMP(in,out) =
    (!t.
      out t =
      (((t = 0) => F | T) =>
       (in t =>
        ~((t = 0) => F | out(t - 1)) |
        ((t = 0) => F | out(t - 1))) |
       T))
\end{verbatim}\end{session}

\section{Automatic unwinding}

\def\putbox(#1,#2){\put(#1,#2){\framebox(2,2){}}}

Hardware implementations often contain feedbacks. This presents a problem
when trying to unwind and prune the internal lines in the logical
representation. The mutual dependencies between lines can cause a brute-force
unwind to loop indefinitely. To avoid this one has to be selective about
which lines to unwind. The tools in the \ml{unwind} library allow the user
to be selective in this way. However, it is possible for the machine itself to
be selective. The function \ml{UNWIND\_AUTO\_CONV} attempts to analyze the
dependencies between lines and unwind as far as possible without looping.

Consider the following term which arises in the parity-checker example:

\begin{small}\begin{verbatim}
   "?l1 l2 l3 l4 l5.
     (!t. l1 (t:num) = ~l2 t) /\
     (!t. l3 t = (in t => l1 t | l2 t)) /\
     (!t. l2 t = ((t = 0) => F | out (t - 1))) /\
     (!t. l4 t = T) /\
     (!t. l5 t = ((t = 0) => F | l4 (t - 1))) /\
     (!t. out t = (l5 t => l3 t | l4 t))"
\end{verbatim}\end{small}

\noindent
We can represent the dependencies of the lines using a directed graph:

{\setlength{\unitlength}{4mm}
\begin{center}
\begin{picture}(14,10)(0,0)
\put(0,2){\makebox(2,2){\small{\tt l2}}}
\put(4,2){\makebox(2,2){\small{\tt l1}}}
\put(8,4){\makebox(2,2){\small{\tt l3}}}
\put(12,6){\makebox(2,2){\small{\tt out}}}
\put(2,8){\makebox(2,2){\small{\tt l4}}}
\put(6,8){\makebox(2,2){\small{\tt l5}}}

\put(2,3){\vector(1,0){2}}
\put(2,3){\vector(3,1){6}}
\put(6,3){\vector(1,1){2}}
\put(10,5){\vector(1,1){2}}
\put(4,9){\vector(1,0){2}}
\put(4,9){\vector(4,-1){8}}
\put(8,9){\vector(2,-1){4}}

\put(13,6){\line(0,-1){6}}
\put(13,0){\line(-1,0){12}}
\put(1,0){\vector(0,1){2}}
\end{picture}
\end{center}}

\noindent
which can in turn be represented by the following list:

\begin{small}\begin{verbatim}
   l1, [l2]
   l3, [l1;l2]
   l2, [out]
   l4, []
   l5, [l4]
   out,[l5;l3;l4]
\end{verbatim}\end{small}

Since we wish to eliminate the internal lines, we want to be left with a
recursive equation for {\small\verb%out%} in terms of itself. We can do this
be `breaking the loop' at {\small\verb%out%}, giving the following structure:

\begin{small}\begin{verbatim}
   l1, [l2]
   l3, [l1;l2]
   l2, []
   l4, []
   l5, [l4]
\end{verbatim}\end{small}

\noindent
Note that {\small\verb%out%} has been removed from the structure. From the
graph we can see that {\small\verb%l2%} and {\small\verb%l4%} do not depend
on any internal lines. They can therefore be used to unwind without any risk
of looping. They can be recognized in the datastructure by the fact that their
corresponding dependency lists are empty.

Once we have unwound with {\small\verb%l2%} and {\small\verb%l4%} they can be
removed from the datastructure:

\begin{small}\begin{verbatim}
   l1, []
   l3, [l1]
   l5, []
\end{verbatim}\end{small}

\noindent
We now see that {\small\verb%l1%} and {\small\verb%l5%} can be unwound to give:

\begin{small}\begin{verbatim}
   l3, []
\end{verbatim}\end{small}

\noindent
Unwinding {\small\verb%l3%} then leaves us with the required recursive
equation for {\small\verb%out%}.

The problem with the approach just described is that it only unwinds fully if
there is at most one loop in the circuit, and the output is in that loop. We
can be a bit more general. Consider the circuit:

\vfill

{\setlength{\unitlength}{4mm}
\begin{center}
\begin{picture}(4,18)(0,0)
\put(1,0){\makebox(2,2){\small{\tt out}}}
\putbox(1,4)
\put(0,6){\makebox(2,2){\small{\tt l2}}}
\putbox(1,8)
\put(0,10){\makebox(2,2){\small{\tt l1}}}
\putbox(1,12)
\put(1,16){\makebox(2,2){\small{\tt in}}}

\put(2,16){\vector(0,-1){2}}
\put(2,12){\vector(0,-1){2}}
\put(2,8){\vector(0,-1){2}}
\put(2,4){\vector(0,-1){2}}

\put(2,7){\circle*{0.2}}
\put(2,7){\line(1,0){2}}
\put(4,7){\line(0,1){8}}
\put(4,15){\line(-1,0){1}}
\put(3,15){\vector(0,-1){1}}
\end{picture}
\end{center}}

\vfill

\noindent
represented by the graph:

\vfill

\begin{small}\begin{verbatim}
   l1, [l2]
   l2, [l1]
   out,[l2]
\end{verbatim}\end{small}

\vfill

\noindent
There are no lines with an empty dependency list, and eliminating
{\small\verb%out%} will not help because it is not in the loop. However, if we
break the loop at {\small\verb%l2%} we can unwind {\small\verb%l1%}. This will
leave us with a recursive equation for {\small\verb%l2%} and an equation for
{\small\verb%out%} in terms of {\small\verb%l2%}. This is the best that we can
do, and it is now up to the user to deal with the recursive equation.

Now let's consider an example with more than one loop:

{\setlength{\unitlength}{4mm}
\begin{center}
\begin{picture}(12,30)(0,0)
\put(1,0){\makebox(2,2){\small{\tt out}}}
\putbox(1,4)
\put(0,6){\makebox(2,2){\small{\tt l5}}}
\putbox(1,8)
\put(0,10){\makebox(2,2){\small{\tt l4}}}
\putbox(1,12)
\put(0,14){\makebox(2,2){\small{\tt l3}}}
\putbox(1,16)
\putbox(5,16)
\put(0,18){\makebox(2,2){\small{\tt l2}}}
\put(6,18){\makebox(2,2){\small{\tt l6}}}
\putbox(1,20)
\putbox(9,20)
\put(0,22){\makebox(2,2){\small{\tt l1}}}
\put(10,22){\makebox(2,2){\small{\tt l7}}}
\putbox(1,24)
\put(1,28){\makebox(2,2){\small{\tt in}}}

\put(2,28){\vector(0,-1){2}}
\put(2,24){\vector(0,-1){2}}
\put(2,20){\vector(0,-1){2}}
\put(2,16){\vector(0,-1){2}}
\put(2,12){\vector(0,-1){2}}
\put(2,8){\vector(0,-1){2}}
\put(2,4){\vector(0,-1){2}}

\put(2,11){\circle*{0.2}}
\put(2,11){\line(1,0){4}}
\put(6,11){\vector(0,1){5}}
\put(6,18){\line(0,1){1}}
\put(6,19){\line(-1,0){3}}
\put(3,19){\vector(0,-1){1}}
\put(2,7){\circle*{0.2}}
\put(2,7){\line(1,0){8}}
\put(10,7){\vector(0,1){13}}
\put(10,22){\line(0,1){1}}
\put(10,23){\line(-1,0){7}}
\put(3,23){\vector(0,-1){1}}
\end{picture}
\end{center}}

\noindent
We could unwind {\small\verb%l1%} but then we would get stuck. If we break at
{\small\verb%l2%} or {\small\verb%l7%} we will still get stuck because of the
inner loop. If we break at {\small\verb%l5%} we can unwind {\small\verb%l7%},
but then get stuck. If we break at {\small\verb%l6%} we get stuck because of
the outer loop. However, if we break at {\small\verb%l3%} or {\small\verb%l4%}
both loops are broken and we can unwind fully to leave a recursive equation
for either {\small\verb%l3%} or {\small\verb%l4%} and an equation for
{\small\verb%out%} in terms of that line. So, the choice of where to break a
loop may determine how far the unwinding can go.

\ml{UNWIND\_AUTO\_CONV} attempts to break every loop in the circuit using the
minimum number of breaks, so that there are as few equations left as possible.
The function also gives priority to non-internal lines when determining where
to break, so that if possible the recursive equations are in terms of these
lines.

The algorithm used determines from the term a list of line variables. Each
line variable has a right-hand side of an equation associated with it. The
free variables in each right-hand side are computed and those that are also
line variables are placed in the dependency list for the corresponding line.
From the dependency structure, the loops are determined. Lines are then
eliminated so that all loops are broken.

A study of the following circuit reveals why {\em all\/} loops have to be
broken. If not all loops are broken, then a remaining loop can make the
breaking of other loops fruitless.

{\setlength{\unitlength}{4mm}
\begin{center}
\begin{picture}(12,30)(0,0)
\put(1,0){\makebox(2,2){\small{\tt out}}}
\putbox(1,4)
\put(0,6){\makebox(2,2){\small{\tt l5}}}
\putbox(1,8)
\put(0,10){\makebox(2,2){\small{\tt l4}}}
\putbox(1,12)
\putbox(9,12)
\put(0,14){\makebox(2,2){\small{\tt l3}}}
\put(10,14){\makebox(2,2){\small{\tt l7}}}
\putbox(1,16)
\putbox(5,16)
\put(0,18){\makebox(2,2){\small{\tt l2}}}
\put(6,18){\makebox(2,2){\small{\tt l6}}}
\putbox(1,20)
\put(0,22){\makebox(2,2){\small{\tt l1}}}
\putbox(1,24)
\put(1,28){\makebox(2,2){\small{\tt in}}}

\put(2,28){\vector(0,-1){2}}
\put(2,24){\vector(0,-1){2}}
\put(2,20){\vector(0,-1){2}}
\put(2,16){\vector(0,-1){2}}
\put(2,12){\vector(0,-1){2}}
\put(2,8){\vector(0,-1){2}}
\put(2,4){\vector(0,-1){2}}

\put(2,11){\circle*{0.2}}
\put(2,11){\line(1,0){4}}
\put(6,11){\vector(0,1){5}}
\put(6,18){\line(0,1){1}}
\put(6,19){\line(-1,0){3}}
\put(3,19){\vector(0,-1){1}}
\put(2,7){\circle*{0.2}}
\put(2,7){\line(1,0){8}}
\put(10,7){\vector(0,1){5}}
\put(10,14){\line(0,1){1}}
\put(10,15){\line(-1,0){7}}
\put(3,15){\vector(0,-1){1}}
\end{picture}
\end{center}}

\noindent
The dependency structure for the circuit is:

\begin{small}\begin{verbatim}
   l1, []
   l2, [l1]
   l3, [l2;l6]
   l4, [l3;l7]
   l5, [l4]
   l6, [l4]
   l7, [l5]
   out,[l5]
\end{verbatim}\end{small}

\noindent
The loops for the circuit are:

\begin{small}\begin{verbatim}
   [l3;l4;l6]
   [l4;l5;l7]
\end{verbatim}\end{small}

\noindent
Both loops can be broken by eliminating {\small\verb%l4%}:

\begin{small}\begin{verbatim}
   l1, []
   l2, [l1]
   l3, [l2;l6]
   l5, []
   l6, []
   l7, [l5]
   out,[l5]
\end{verbatim}\end{small}

\noindent
We can now unwind {\small\verb%l1%}, {\small\verb%l5%} and {\small\verb%l6%}:

\begin{small}\begin{verbatim}
   l2, []
   l3, [l2]
   l7, []
   out,[]
\end{verbatim}\end{small}

\noindent
and then unwind {\small\verb%l2%}, {\small\verb%l7%} and {\small\verb%out%},
followed by unwinding with {\small\verb%l3%} to yield a recursive equation for
{\small\verb%l4%} and all other equations in terms of {\small\verb%l4%}. All
the internal lines except for {\small\verb%l4%} can be pruned. This leaves
equations for {\small\verb%l4%} and {\small\verb%out%} only.

The technique does not always yield a single recursive equation. Mutual
recursion is also possible. This is illustrated by the following example:

{\setlength{\unitlength}{4mm}
\begin{center}
\begin{picture}(10,30)(0,0)
\put(1,0){\makebox(2,2){\small{\tt out}}}
\putbox(1,4)
\put(0,6){\makebox(2,2){\small{\tt l5}}}
\putbox(1,8)
\put(0,10){\makebox(2,2){\small{\tt l4}}}
\putbox(1,12)
\putbox(5,10)
\put(0,14){\makebox(2,2){\small{\tt l3}}}
\put(6,12){\makebox(2,2){\small{\tt l7}}}
\putbox(1,16)
\put(0,18){\makebox(2,2){\small{\tt l2}}}
\putbox(1,20)
\putbox(5,18)
\put(0,22){\makebox(2,2){\small{\tt l1}}}
\put(6,20){\makebox(2,2){\small{\tt l6}}}
\putbox(1,24)
\put(1,28){\makebox(2,2){\small{\tt in}}}

\put(2,28){\vector(0,-1){2}}
\put(2,24){\vector(0,-1){2}}
\put(2,20){\vector(0,-1){2}}
\put(2,16){\vector(0,-1){2}}
\put(2,12){\vector(0,-1){2}}
\put(2,8){\vector(0,-1){2}}
\put(2,4){\vector(0,-1){2}}

\put(2,15){\circle*{0.2}}
\put(2,15){\line(1,0){4}}
\put(6,15){\vector(0,1){3}}
\put(6,20){\line(0,1){2}}
\put(6,22){\vector(-1,0){3}}
\put(2,7){\circle*{0.2}}
\put(2,7){\line(1,0){4}}
\put(6,7){\vector(0,1){3}}
\put(6,12){\line(0,1){2}}
\put(6,14){\vector(-1,0){3}}
\put(6,7){\circle*{0.2}}
\put(6,7){\line(1,0){4}}
\put(10,7){\line(0,1){16}}
\put(10,23){\line(-1,0){7}}
\put(3,23){\vector(0,-1){1}}
\end{picture}
\end{center}}

There are three loops, but breaking at {\small\verb%l2%} and {\small\verb%l4%}
is sufficient to break all the loops. The result is three equations: an
equation for {\small\verb%l2%} in terms of itself and {\small\verb%l4%}, an
equation for {\small\verb%l4%} in terms of itself and {\small\verb%l2%}, and
an equation for {\small\verb%out%} in terms of {\small\verb%l4%}. So, it can
be seen that the loop analysis technique used by \ml{UNWIND\_AUTO\_CONV} does
not eliminate loops; it simply `shrinks' them.


%% LaTeX2e Template by Stephen Iota (https://stepheniota.com/)
%% last updated: Feb. 2019
%% for papers
%\documentclass[aps,preprint,notitlepage]{revtex4-1}
%% https://www-d0.fnal.gov/Run2Physics/WWW/templates/revtex4.pdf
%% https://cdn.journals.aps.org/files/revtex/auguide4-1.pdf
%% ^^ revTeX4-1 class options

%% for other
\documentclass[11pt]{article}
\usepackage[margin=2cm]{geometry}
%%%%%%%%%%%%%%%%
%%% Packages %%%
%%%%%%%%%%%%%%%%

\usepackage[utf8]{inputenc}
\usepackage[noadjust]{cite}
\usepackage{lipsum}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{mathtools}
\usepackage{physics} %http://ftp.math.purdue.edu/mirrors/ctan.org/macros/latex/contrib/physics/physics.pdf
\usepackage[thinc]{esdiff} % easy derivatives
\usepackage{graphicx} % \includegraphics{ }
\usepackage[shortlabels]{enumitem} % change labels in enum/item environments
\usepackage[dvipsnames]{xcolor} % colored links=
%\usepackage{footmisc} % http://mirror.utexas.edu/ctan/macros/latex/contrib/footmisc/footmisc.pdf
%\usepackage[small]{titlesec} % [small,medium,big] << controls size of *section text
%\usepackage{fancyhdr} %http://tug.ctan.org/tex-archive/macros/latex/contrib/fancyhdr/fancyhdr.pdf
% always put this at the end
\usepackage[
	colorlinks=true,
	citecolor=NavyBlue!90!black,
	linkcolor=NavyBlue!75!black,
	urlcolor=green!50!black,
	hypertexnames=false]{hyperref}

 %%%%%%%%%%%%%%%%%%
 %% New Commands %%
 %%%%%%%%%%%%%%%%%%
\newcommand{\email}[1]{\texttt{\href{mailto:#1}{#1}}}
%\newcommand{\ave}[1]{$\langle #1 \rangle$}
\renewcommand{\d}[1]{\ensuremath{\operatorname{d}\!{#1}}}
%%%%%%%%%%%%%%%%%%
%% Front Matter %%
%%%%%%%%%%%%%%%%%%

%\pagenumbering{gobble} % no page numbers
\graphicspath{{figures/}} % set directory for figures
%\setcounter{section}{-1} % start with section 0

%%%%%%%%%%%%%
%%% Title %%%
%%%%%%%%%%%%%
\begin{document}

\begin{center}

\Large{\textsc{Statistical Mechanics}: \textbf{Problem Set 2}}
\end{center}
\vspace{.5mm}

%%%%%%%%%%
%% INFO %%
%%%%%%%%%%

\begin{tabular}{rl}
\textsc{Name}:
&
Stephen Iota (\email{siota001@ucr.edu})
\\
\textsc{Course}:
&
Physics 133 (Spring 2019), Prof.~Kuhlman
\\
\textsc{Date}:
&
\today
\end{tabular}
\vspace{2mm}
%%%%%%%%%%%%%%
%% PROBLEMS %%
%%%%%%%%%%%%%%

\noindent
Sethna problems 2.6, 3.5 and 3.9. Painstakingly typeset using \LaTeX. All final answers are \boxed{\text{boxed.}}

%%%%%%%%%%%%%%%%
%% Sethna 2.6 %%
%%%%%%%%%%%%%%%%
\section{Fourier and Green}

An initial denisty profile $\rho(x,t=0)$ is perturbed slightly from $\rho_0$. The density obeys the diffusion equation
$\pdv{\rho}{t} = D \pdv[2]{\rho}{x}$,
where $D = 0.001$ m/s$^2$.

\begin{figure}[h!]
\centering
\includegraphics[width=.5\linewidth]{Pset2_Fig1}
\caption{Initial profile density deviation from average.\label{density}}
\end{figure}

\vspace{2mm}
\noindent
\textbf{(a) Fourier}
\textit{Consider just a cosine wave. If the intial wave were
$\rho_\text{cos}(x,0) = \cos{10x}$, what would it be at $t = 10s$?}

\vspace{2mm}
\noindent
\textbf{Solution:}
We can decompose $\rho$ into a superpostition of complex plane wave solutions using the Fourier method. We expect the solution to look like $\rho_\text{cos} = \rho_k e^{ikx}$.
We can superimpose all different wave vectors to get a general solution.
$$
\rho(x,t) = \frac{1}{2\pi} \int_{-\infty}^{\infty} \rho_k(0) e^{ikx} e^{-Dk^2t} \text{d}k
$$
where the coefficients $\rho_k(0)$ are the Fourier transform of the initial density profile
$$
\rho_k(0) = \int_{-\infty}^{\infty} \rho(x,0) e^{-ikx} \text{d}x
$$

Plugging in $\rho_\text{cos}(x,0) = \cos{10x}$, we get
\begin{align*}
\rho_k &= \int_{-\infty}^{\infty} \cos{10x} \ e^{-ikx} \text{d}x
\\
       &= \int_{-\infty}^{\infty} \frac{e^{i10x} + e^{-i10x}}{2} \ e^{-ikx} \text{d}x
\\
			 &= \frac{1}{2} \Big[ \delta(k-10) + \delta(k+10) \Big]
\end{align*}
So the initial distribution is composed of two frequencies.
Now we solve for the time evolution in position space.
\begin{align*}
\rho(x,t) &= \frac{1}{2\pi} \int_{-\infty}^{\infty} \frac{1}{2} \Big[ \delta(k-10) + \delta(k+10) \Big] e^{ikx} e^{-Dk^2t} \text{d}k
\\
          &= \frac{1}{4\pi} \int_{-\infty}^{\infty} \Big[ \delta(k-10)e^{ikx} e^{-Dk^2t} + \delta(k+10)e^{ikx} e^{-Dk^2t} \Big] \text{d}k
					\\
					&= \frac{1}{4\pi} \Big[ (e^{i10x} + e^{-i10x}) e^{-D100t}  \Big]
					\\
					&= \frac{1}{8\pi} \cos{10x} \ e^{-D100t}
\end{align*}
This is the general time evolution for $\rho_\text{cos}$. Solving for $t =0$ yields
\begin{align*}
\rho(x, t = 10s) &=  \frac{1}{8\pi} \cos{10x}\  e^{-(.001\cdot100\cdot10)}
\\
&=  \boxed{ \frac{1}{8\pi} \cos{10x}\  e^{-1}}
\end{align*}

\vspace{2mm}
\noindent
\textbf{(b) Green}
\textit{If a wave at some earlier time $-t_0$ were a $\delta$-function at $x = 0$, such that $\rho(x,-t_0) = \delta(x)$, what choice of time elapsed $t_0$ would yield a Gaussian $\rho(x,0) = \exp(-x^2/2)/\sqrt{2\pi}$ for the given diffusion constant $D$?}

\vspace{2mm}
\noindent
\textbf{Solution:}
We define Green's function $G(x,t)$ to be the time evolution of $G(x,t=-t_0) = \delta(x)$. We follow the same steps as in part a to solve for $G(x,t).$
\begin{align*}
G_k(-t_0) &= \int G(x,-t_0) e^{-ikx}\d{x}
\\
          &= \int \delta(x) e^{-ikx} = 1
\end{align*}
$G_k$ is independent of $k$. The time evolved Fourier transform is $G_k(t) = e^{-Dk^2(t+t_0)}.$
The time evolution in position space is
\begin{align*}
G(x,t) &= \frac{1}{2\pi} \int e^{ikx} G_k(-t_0) e^{-Dk^2(t+t_0)} \d{k}
\\
       &= \frac{1}{2\pi} \int e^{ikx} e^{-Dk^2(t+t_0)} \d{k}
\end{align*}
The answer to this integral is the well known Green's function for the diffusion equation
$$
G(x,t) = \frac{1}{\sqrt{4\pi D(t+t_0)}} e^{-x^2/4D(t+t_0)}
$$
We need to find a time $-t_0$ such that $G(x,0)$ looks like a Gaussian function centered about the origin for the given diffusion constant $D.$ By analysis, we see that a time of \boxed{t_0 = 500 \ \text{seconds}} will give a Gaussian at $t=0$.

\vspace{2mm}
\noindent
\textbf{(c) Pictures}
\textit{Now consider time evolution for the next ten seconds. The initial density profile $\rho(x,t = 0)$ is as shown in fig.~\ref{density}.
What figure represents the density at $t = 10s$?}

\vspace{2mm}
\noindent
\textbf{Solution:}
The density profile in fig.~\ref{density} is a Gaussian centered at $x=5$ on the left,
and a smooth envelope function multiplied by $\cos{10x}$ centered at $x=15$ on the right. From the previous two parts, we know that the Gaussian function takes a much longer time to diffuse that the cosine function. Thus, in 10 seconds, we expect the function on the left to remain fairly similar. The short wavelength parts of the cosine function will be suppressed.
We expect the distribution at $t = 10$ sec to look like \boxed{\text{fig.~\ref{10sec} (figure \textbf{E} from the text).}}

\begin{figure}[h!]
\centering
\includegraphics[width=.4\linewidth]{PSet2_Fig3}
\caption{Profile density at $t = 10$ seconds.}
\label{10sec}
\end{figure}

%%%%%%%%%%%%%%%%
%% Sentha 3.5 %%
%%%%%%%%%%%%%%%%
\section{Hard sphere gas}
A 2D $L \cross L$ box with hard walls contains a gas of $N$ hard disks of radius $r \ll L$, as shown in fig.~\ref{sphere}.
The disks are dilute; the summed area $N\pi r^2 \ll L^2$.
Let A be the effective area allowed for the disks in the box: $A = (L-2r)^2$.
\begin{figure}[h!]
	\centering
	\includegraphics[width=.3\linewidth]{PSet2_Fig2}
	\caption{Hard sphere gas.}
	\label{sphere}
\end{figure}

\vspace{2mm}
\noindent
\textbf{(a)}
\textit{The area allowed for the second disk is approximately $A - \pi(2r)^2$.
What is the allowed 2N-dimensional volume in configuration space, of allowed zero-energy configurations of hard disks, in this dilute limit?}

\vspace{2mm}
\noindent
\textbf{Solution:}
For $N = 2$, $A_2 = A(A-4\pi r^2)$; for $N = 3$, $A_3 = A(A_2)(A_2 - 4\pi r^2)$, and so on. As $N$ increases, each disk will have a smaller area by $4\pi r^2$ than the previous disk.

$$
\boxed{A_N = \frac{1}{N!}\prod_{n = 0}^{N}A - n4\pi r^2}
$$

\vspace{2mm}
\noindent
\textbf{(b)}
\textit{
What is the configuration entropy for the hard disks?}

\vspace{2mm}
\noindent
\textbf{Solution:}
Let $S$ denote configuration entropy. Using answer from part a:

\begin{align*}
S &= k_B \log{A_N}
\\
  &= k_B \log{\Big( \frac{1}{N!}\prod_{n = 0}^{N}A - n4\pi r^2 \Big)}
	\\
	&= k_B \Big( -\log{N!} + \sum_{n = 1}^{N} \log{(A - (n-1)4\pi r^2)} \Big)
\end{align*}
where in the last step we changed the starting index.
In the dilute limit, $N 4\pi r^2 \ll A$. We taylor expand $\log{(A - n4\pi r^2)}$:
\begin{align*}
\log{(A - (n-1)4\pi r^2)} &= \log{A} + \log{(1 - (n-1)4\pi r^2/A)}
\\
&\approx \log{A} - (n-1)\frac{4\pi r^2}{A}
\end{align*}
Plugging in this approximation to the sum, we find a sum of the form $\sum_{n = 1}^{N} = N(N-1)/2$.
We use Stirling's approximation $\log{N!} \approx N \log{N} - N$.
\begin{align*}
S &= k_B \Bigg( - N \log{N} - N + \bigg( N\log{A} - \frac{N(N-1) 4\pi r^2}{2A} \bigg) \Bigg)
\end{align*}
Simplifying, we reach our result
$$
\boxed{S = N k_B \bigg( 1 + \log{\Big( \frac{A}{N} - \frac{4\pi r^2}{N}\frac{N - 1}{2} \Big)} \bigg)}
$$
where we might possibly be able to say $ \frac{4\pi r^2}{N}\frac{N - 1}{2}$ is about $2\pi r^2$.
%%%%%%%%%%%%%%%%
%% Sentha 3.9 %%
%%%%%%%%%%%%%%%%
\section{Gauss and Poisson}
Calculate the probability of having $n$ particles in a subvolume $V$, for a box with total volume $KV$ and a total number of particles $T = KN_0$.

\vspace{2mm}
\noindent
\textbf{(a)}
\textit{Find the exact formula for this probability; $n$ particles fall in the subvolume $V$, with a total of $T$ particles in $KV$.}

\vspace{2mm}
\noindent
\textbf{Solution:}
Suppose $n$ particles are in subvolume $V$ and $T - n$ particles are outside of $V$, in subvolume $(K-1)V$, where the total volume is $KV$.
In configuration space, the available volume is $V^n ((K - 1)V)^{T - n} = V^T (K-1)^{T - n}$, and the total volume is $(KV)^T$. The probability is given by the ratio of these two volumes, where we need to be mindful about the different ways to pick the $n$ particles. The total probability is given by:
\begin{align*}
P(n) &= \binom{T}{n} \frac{(K - 1)^{T - n}}{K^T}
\\
     &= \boxed{\frac{T!}{n!(T - n)!} \frac{(K - 1)^{T - n}}{K^T}}
\end{align*}

\vspace{2mm}
\noindent
\textbf{(b)}
\textit{
Show that the Poisson distribution in normalized: $\sum_n \rho_n = 1$.
Calculate the mean of the distribution $\langle n \rangle$ in terms of $a$. Calculate the variance $\langle(n - \langle n\rangle)^2\rangle$.}

\vspace{2mm}
\noindent
\textbf{Solution:}
For normalization:
\begin{align*}
\sum_{n=0}^{\infty} \rho_n &= \exp{-a} \sum_{n=0}^{\infty} \frac{a^n}{n!}
\\
&= \exp{-a} \exp{a}
\\
&= \boxed{1}
\end{align*}
For mean of Poisson distribution:
\begin{align*}
\langle n \rangle &= \sum_{n=0}^{\infty} n \frac{a^n}{n!} e^{-a}
\\
&= \sum_{n=1}^{\infty} n \frac{a^n}{n!} e^{-a}
\\
&= \sum_{n=1}^{\infty} \frac{aa^{n-1}}{(n-1)!} e^{-a}
\\
&= a \sum_{n=0}^{\infty} \frac{a^n}{n!} e^{-a}
\\
&= a \sum_{n=0}^{\infty} \frac{a^n}{n!} e^{-a}
\\
&= a \sum_{n=0}^{\infty} \rho_n
\end{align*}
which is equal to $\boxed{a}$ because the distribution is normalized.
For the variace, we have
$
\langle(n - \langle n\rangle)^2\rangle = \langle n^2 \rangle - \langle n \rangle^2
$.
\begin{align*}
\langle n\rangle)^2 &= \sum_{n=0}^{\infty} n^2 \frac{a^n}{n!} e^{-a}
\\
&= a \sum_{n=0}^{\infty} (n+1)\rho_n
\\
&= a \langle n+1 \rangle
\\
&= a^2 + a
\end{align*}
This gives us a variance of $(a^2 + a) - (a^2) = \boxed{a}$.

\vspace{2mm}
\noindent
\textbf{(c)}
\textit{As $K \rightarrow \infty$, show that the probability that $n$ particles fall in the subvolume $V$ has the Poisson distribution $\rho_n = a^n e^{-a}/n!$. What is $a$?}

\vspace{2mm}
\noindent
\textbf{Solution:}
Recall the answer to part a:
$$
P(n) = \frac{T!}{n!(T - n)!} \frac{(K - 1)^{T - n}}{K^T}
$$
As we let $K \text{and} T \rightarrow \infty, \ (1 - 1/K)^(T-n) \approx e^{\frac{T}{K}}.$ Also $T! \approx (T/e)^T$. We simplify:

\begin{align*}
\frac{T!}{n!(T - n)!}
&\approx \frac{(T/e)^T}{((T-n)/e)^{T-n}}
\\
&= \Big(\frac{T-n}{T}\Big)^{n-T}  \ \Big(\frac{T}{e}\Big) ^n
\\
&\approx e^{\frac{n}{T}(T-n)} \Big(\frac{T}{e}\Big)^N
\\
&\approx T^n
\end{align*}
The final result is a Poisson distribution where $a = T/K.$
$$
\boxed{
P(n) = \frac{(T/K)^n}{n!} e^{-T/K}
}
$$

\end{document}


\section{Conclusions and future work}

We have described a technique for type inference of intermediate code
resulting from the translation of \commonlisp{} code to an
intermediate representation that manipulates only objects of the
source language.  Our technique uses a straightforward dataflow
algorithm, which is also the most natural way of thinking about the
evolution of type information in a \commonlisp{} program.

Type inference can be much more effective if the intermediate code is
first converted to SSA form \cite{Cytron:1989:EMC:75277.75280,
  Cytron:1991:ECS:115372.115320} or some other notation that preserves
values of lexical variables across assignments.  Assigning to a
lexical variable may lose existing type information associated with
that variable, so that the type of the new value must be tested again
at some later point in the program.  Our technique works whether the
intermediate code is transformed this way or not, but we have not yet
tested the effect of such transformations on the effectiveness of our
technique.

At present, the type inference only operates within function, and does
not use any information about other functions that isn't explicitly
declared. The algorithm can be extended to incorporate type information
from local functions without much change, but using inferred types of
global functions will require more work due to the semantics of
redefinition.

Determining precise dataflow in a \commonlisp{} program is complicated
when a lexical variable is shared between nested closures, and
arbitrary dataflow may invalidate essential type information, thereby
limiting the effectiveness of type inference.  Currently, Cleavir only
contains a very rudimentary \emph{escape analysis} phase, forcing our
type-inference technique to be very conservative by treating all shared
variables as being of unknown type.  We intend to improve the quality
of the escape analysis so as to improve the effectiveness of our
type-inference technique.

Currently, the dataflow computation is implemented with an ad hoc
approach.  However, Kildall \cite{Kildall:1973:UAG:512927.512945}
designed a general approach for solving a large spectrum of problems,
and our type-inference technique is a good candidate for using that
general approach.  We already have a general implementation of this
approach, and it can be customized by providing a \emph{domain} in the
form of a standard instance%
\footnote{Recall that a \emph{standard instance} is an instance of
  (a subclass of) the class named \texttt{standard-class}.  Some
  authors use the term ``CLOS class'', but that term does not exist in
  the \commonlisp{} standard.}
that provides the details of the required lattice operations.  In
order to improve maintainability, we intend to adapt our
type-inference technique so that it uses this implementation of
Kildall's approach.

Finally, the type lattice used by our technique is currently very
coarse.  A more populated lattice can greatly improve the
effectiveness of our technique, though care must be taken to avoid
excessive processor time in the type inferencer itself.

After the submission of this paper, considerable progress has been made in implementing the algorithm in terms of Kildall's algorithm, and using an expanded lattice with more joins, but it has not yet been tested extensively.


%&context

\section[sct_trim]{Trimming trees}

Trimming a tree means cutting the nodes whose depth is larger than a specified threshold. Here is what will happen if I cut the catarrhini tree at depth 30:

\midaligned{\externalfigure[trim_1]}

The tree will be "cut" on the red line, and everything right of it will be discarded:

\svgCmdOutput{trim_2}

By default, depth is expressed in branch length units -- usually substitutions
per site. By passing the \code{-a} switch, it is measured in number of
ancestors, instead. Here are the first four levels of a huge tree (it has more than 1000 leaves):

\svgCmdOutput{trim_3}

The leaves with labels of the form \id{ID *} are also leaves in
the original tree, the other leaves are former inner nodes whose children got
trimmed.  Their labels are the (absolute) bootstrap support values of those
nodes. Note that the branch lengths are conserved. It is apparent that the
ingroup's lower half has very poor support. This would be harder to see without
trimming the tree, due to its huge size.

\subsubsection{Trimming cladograms}

By definition, cladograms do not have branch lengths, so you need to express depth in numbers of ancestors, and thus you want to pass \code{-a}.