\section{\textsc{#1}}}

\def\boldsymbol{\mu}_R{\boldsymbol{\mu}_R}
\def\boldsymbol{\Lambda}_R{\boldsymbol{\Lambda}_R}
\def\boldsymbol{\Lambda}_{R_0}{\boldsymbol{\Lambda}_{R_0}}
\def\boldsymbol{\mu}_0{\boldsymbol{\mu}_0}
\def\kappa_0{\kappa_0}
\def\nu{\nu}
\def\kappa_0{\kappa_0}

\newtheorem{thm}{Theorem}
\newtheorem{lemma}{Lemma}
\newtheorem{prop}{Proposition}
\newtheorem{cor}{Corollary}
\newtheorem{remark}{Remark}
\newtheorem{example}{Example}
\newtheorem{mydef}{Definition}
\newtheorem{assumption}{Assumption}

\def\newshortcut#1#2{%
\let#1=\undefined
\newcommand{#1}{#2}}

\newshortcut{\pyabove}{\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}}


\usepackage{titlesec}
\titleformat{\section}[block]{\sc\filcenter}{}{1em}{}
\titleformat{\subsection}[hang]{\it\filcenter}{}{1em}{}
\titlespacing*{\section}{0pt}{1\baselineskip}{0.1\baselineskip}
\usepackage{fancyhdr}
\pagestyle{fancy}
\thispagestyle{empty}
\fancyhead[C]{\fontsize{10}{12}\sc{Relaxed Random Walks at Scale}}

\begin{document}

\begin{flushright}
Version dated: \today\\
\end{flushright}

\bigskip
\medskip
\begin{center}

\noindent{\Large \bf Relaxed Random Walks at Scale}
\bigskip

\noindent{\normalsize \sc
	Alexander A.~Fisher$^{1}$,
	Xiang Ji$^{1}$,
	Philippe Lemey$^{2}$,
    and Marc A.~Suchard$^{1,3,4}$}\\
\noindent {\small
  \it $^1$Department of Biomathematics, David Geffen School of Medicine at UCLA, University of California,
  Los Angeles, United States \\
  \it $^2$Department of Microbiology and Immunology, Rega Institute, KU Leuven, Leuven, Belgium \\
  \it $^3$Department of Biostatistics, Jonathan and Karin Fielding School of Public Health, University
  of California, Los Angeles, United States \\
  \it $^4$Department of Human Genetics, David Geffen School of Medicine at UCLA, Universtiy of California,
  Los Angeles, United States} \\

\end{center}
\medskip
\noindent{\bf Corresponding author:} Marc A.~Suchard, Departments of Biostatistics, Biomathematics, and Human Genetics,
University of California, Los Angeles, 695 Charles E.~Young Dr., South,
Los Angeles, CA 90095-7088, USA; E-mail: \url{msuchard@ucla.edu}

\vspace{1in}

\clearpage

\section{Abstract}
Relaxed random walk (RRW) models of trait evolution introduce branch-specific rate multipliers to modulate the variance of a standard Brownian diffusion process along a phylogeny and more accurately model overdispersed biological data.
Increased taxonomic sampling challenges inference under RRWs as the number of unknown parameters grows with the number of taxa.
To solve this problem, we present a scalable method to efficiently fit RRWs and infer this branch-specific variation in a Bayesian framework.
We develop a Hamiltonian Monte Carlo (HMC) sampler to approximate the high-dimensional, correlated posterior that exploits a closed-form evaluation of the gradient of the trait data log-likelihood with respect to all branch-rate multipliers simultaneously.
Our gradient calculation achieves computational complexity that scales only linearly with the number of taxa under study.
We compare the efficiency of our HMC sampler to the previously standard univariable Metropolis-Hastings approach while studying the spatial emergence of the West Nile virus in North America in the early 2000s.
Our method achieves an over 300-fold speed-increase over the univariable approach. 
Additionally, we demonstrate the scalability of our method by applying the RRW to study the correlation between five mammalian life history traits in a phylogenetic tree with $3650$ tips.

\section{Introduction}
Phylogenetic comparative methods are an indispensable tool to study the evolution of biological traits across taxa while controlling for their shared evolutionary history that confounds the inference of trait correlation \citep{felsenstein1985}.
Modern comparative methods usually entertain continuous, multivariate traits, although extensions to mixed discrete and continuous outcomes are readily available \citep{ives2009phylogenetic, cybis2015}.
Approaches typically model trait evolution as a Brownian diffusion or ``random walk" process that acts conditionally independently along the branches of a known or random phylogeny.
Specifically, the observed or unobserved (latent) trait value of a node in a phylogeny arises from a multivariate normal distribution centered on the latent trait value of its ancestral node with variance proportional to the units of time between nodes.
A strict Brownian diffusion model, however, is unable to accommodate the overdispersion in trait data that often emerges from real biological processes \citep{schluter1997likelihood}.
One such example arises when examining the dispersal rate of measurably evolving viral pathogens \citep{biek2007high}.
For example, if birds serve as the viral host, migratory patterns may induce inhomogeneous dispersal rates over time \citep{pybus2012unifying}.
In such cases, a strict Brownian diffusion model fails to capture, and therefore can also fail to predict, the spatial dynamics of an emerging epidemic.

\cite{lemey2010} relax the strict Brownian diffusion assumption by introducing branch-rate multipliers that scale the variance of the Brownian diffusion process along each branch of the phylogeny.
This ``relaxed random walk" (RRW) model requires estimating $2N - 2$ correlated branch-rate multipliers, where $N$ is the number of taxa in the phylogeny.
\cite{lemey2010} take a Bayesian approach to parameter estimation where they infer the posterior distribution of the branch-rate multipliers via Markov chain Monte Carlo (MCMC) employing a simple univariable Metropolis-Hastings (UMH) proposal distribution \citep{hastings1970monte}.
Since the rates remain correlated in the posterior, a random-scan \citep{liu2008monte} of UMH proposals inefficiently explores branch-rate space.
Specifically, univariable samplers force accepted proposals to be very close together to avoid a large number of rejection steps in the Markov chain simulation.
This results in high correlation between MCMC samples from the posterior, making point estimates of the branch-rate multipliers unreliable and slow to converge.
For example, in the mammalian life history study we explore here, a UMH sampler requires approximately 33 days of actual run time to achieve reasonable posterior estimates of branch-rate multipliers.
Despite this present drawback, RRWs find many impactful applications, e.g., in phylodynamics and phylogeography \citep{bedford2014integrating, faria2014early}.

To ameliorate the difficulties that high dimensional MCMC sampling presents, we propose adopting a geometry-informed sampling approach using Hamiltonian Monte Carlo (HMC).
HMC equates sampling from a probability distribution with simulating the trajectory of a puck sliding across a frictionless surface warped by the shape of the distribution \citep{neal2011mcmc}.
To map from this statistical problem to the physical one, we view the MCMC samples of our branch-rate multipliers as the ``position" of the puck and, then, for each positional dimension we introduce an associated momentum variable.
In this way, we extend a D-dimensional parameter space to 2D-dimensional phase space \citep{betancourt2017conceptual} and traverse the 2D phase space via differentiating the Hamiltonian and using a numerical integration method to offer proposal states for our MCMC chain.
The major limitation to HMC is calculating the gradient of the log-posterior with respect to all position parameters simultaneously.
Previous approaches for calculating gradients on  phylogenies have employed ``pruning"-type algorithms \citep{felsenstein1981} that scale quadratically with the number of taxa in the tree \citep{bryant2005likelihood}. Likewise, numerical approaches also scale quadratically.

In this paper, we derive a method to calculate the gradient with computational complexity that scales only linearly with the number of taxa.
We implement our method in the BEAST software package \citep{suchard2018}, a popular tool for the study and reconstruction of rooted, time-measured phylogenies.
We demonstrate the speed and accuracy of our linear-order gradient HMC versus previous best practices by examining the spread of the West Nile virus across the Americas in the early 2000s.
Finally, we use our technique to apply the RRW model to study the sensitivity of correlation estimates to model misspecification between mammalian adult body mass, litter size, gestation length, weaning age and litter frequency across $3650$ mammals, thereby demonstrating the scalability of our HMC implementation to tackling a previously intractable problem.

\section{Methods}
\subsection{Model and Inference} \label{sec:modeling
Consider a known or random phylogeny $\mathscr{F}$ with $N$ sampled tip nodes and $N - 1$ internal and root nodes, each with an observed or latent continuous trait value $\mathbf{Y}_{i}\, \in \, \mathbb{R}^{P}$.
To traverse the phylogeny $\mathscr{F}$, let node~$\parent{i}$ index the parent of node~$i$ with branch length $\branchLength{i}$ connecting the two nodes.
Then under the RRW model,
\begin{equation}
\mathbf{Y}_{i} \sim \mvnDensity{\mathbf{Y}_{\parent{i}}}{
\branchLength{i} \nodeVarianceFunction{\rate{i}}
} ,
\end{equation}
where the $P \times P$ matrix-valued function $\nodeVarianceFunction{\rate{i}}$ characterizes the branch-specific multivariate normal (MVN) increment that defines the diffusion process. We parameterize this function in terms of an unknown $P \times P$ positive-definite matrix $\boldsymbol{\Sigma}$ that describes the covariation between trait dimensions after controlling for shared evolutionary history and an unknown branch-rate multiplier $\rate{i}$.
Typical choices include
\begin{equation}
\nodeVarianceFunction{\rate{i}} =
\left\{
\begin{array}{rl}
\rate{i} \boldsymbol{\Sigma} & \text{rate-scalar parameterization}, \rate{i} > 0, \\
\frac{1}{\rate{i}} \boldsymbol{\Sigma} & \text{scale-mixture-of-normals parameterization}, \rate{i} > 0,  \\
e^{\rate{i}} \boldsymbol{\Sigma} & \text{unconstrained parameterization},\rate{i} \in \mathbb{R}, \ \text{and} \\
\boldsymbol{\Sigma} & \text{standard Brownian diffusion}.
\end{array}
\right.
\label{eq:varianceChoices}
\end{equation}
To complete the RRW model specification, we adopt a prior density on the unobserved trait at the parentless root node,
\begin{equation}
\density{\mathbf{Y}_{2 N - 1}} = \mvnDensity{\boldsymbol{\nu}_0}{
	\kappa_0^{-1} \boldsymbol{\Sigma}
	}
\end{equation}
with prior mean $\boldsymbol{\nu}_0$ and sample-size $\kappa_0$.

Letting $\boldsymbol{\phi} = (\rate{1}, \ldots, \rate{2N - 2})$ and the observed data $\mathbf{Y} = (\mathbf{Y}_1, \ldots, \mathbf{Y}_{N})$ at the tips, we are interested in learning about the posterior
\begin{equation}
	\cDensity{\boldsymbol{\phi}, \boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}}{\mathbf{Y}, \mathbf{S}}
	\propto
	\underbrace{
	\cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}}
	\cDensity{\mathbf{S}}{\mathscr{F}, \boldsymbol{\Theta}}}_{\text{likelihood}}
	\underbrace{
	\cDensity{\boldsymbol{\phi}}{s}
	\density{s}
	\density{\boldsymbol{\Sigma}}
	\density{\mathscr{F}, \boldsymbol{\Theta}}}_{\text{priors}},
	\label{eq:fullPosterior}
	\end{equation}
where $s$ is an unknown parameter characterizing our prior on $\boldsymbol{\phi}$ and $\boldsymbol{\Theta}$ represents parameters of a molecular sequence substitution model for the evolution of aligned molecular sequence data $\mathbf{S}$.
Note that we follow usual convention \citep{cybis2015} and assume that $\mathbf{Y}$ and $\mathbf{S}$ are conditionally independent given $\mathscr{F}$.
We follow the example of \cite{lemey2010} and place a log-normal prior distribution on $\boldsymbol{\phi}$ with mean $1$ and standard deviation $s$.
We further assume a relatively uninformative exponential prior on $s$ with mean $10$.
Additionally, we assign a Wishart conjugate prior with scale matrix $\identityMatrix{P}$ and $P$ degrees of freedom to $\boldsymbol{\Sigma}^{-1}$.

We use MCMC integration to approximate this posterior using a random-scan Metropolis-within-Gibbs approach \citep{levine2006, liu2008monte}.
One cycle of this scheme consists of sampling $\boldsymbol{\phi}, \boldsymbol{\Sigma}, s$ and then $(\mathscr{F}, \boldsymbol{\Theta})$ via

\begin{subequations}
\begin{align}
\label{eq:gibbsUpdates1}
\cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}
&\propto
\cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}} \cDensity{\boldsymbol{\phi}}{s},\\
\label{eq:gibbsUpdates2}
\cDensity{\boldsymbol{\Sigma}}{\boldsymbol{\phi}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}
&\propto
\cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}} \density{\boldsymbol{\Sigma}},\\
\label{eq:gibbsUpdates4}
\cDensity{s}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}
&\propto
\cDensity{\boldsymbol{\phi}}{s} \density{s}, \ \text{and} \\
\label{eq:gibbsUpdates3}
\cDensity{\mathscr{F}, \boldsymbol{\Theta}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, s, \mathbf{Y}, \mathbf{S}}
&\propto
\cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}} \cDensity{\mathbf{S}}{\mathscr{F}, \boldsymbol{\Theta}} \density{\mathscr{F}, \boldsymbol{\Theta}},
\end{align}
\end{subequations}
where update (\ref{eq:gibbsUpdates3}) is unecessary when $\mathscr{F}$ is fixed, otherwise
efficient sampling from the density $\cDensity{\mathscr{F}, \boldsymbol{\Theta}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, s, \mathbf{Y}, \mathbf{S}}$ is well described elsewhere, see for example \cite{suchard2018}.
Updates (\ref{eq:gibbsUpdates2}) and (\ref{eq:gibbsUpdates4}) are straightforward due to the conjugate priors chosen in our model.
We turn our focus to the remaining component of our scheme, namely sampling from $\cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}$.





\subsection{Hamiltonian Monte Carlo}
We wish to sample $\boldsymbol{\phi}$ jointly to avoid potentially high autocorrelation in the resulting MCMC chain.
To this end, we propose using HMC and begin with a brief description of how HMC maps sampling from a probability distribution to simulating a physical system.
In classical mechanics, the Hamiltonian is the sum of the kinetic and potential energy in a closed system.
To build the connection, we introduce auxiliary momentum variable $\boldsymbol{\rho} = (\momentumAt{1}, \ldots, \momentumAt{2 N - 2})$ and write our Hamiltonian,
\begin{equation}
H(\boldsymbol{\phi}, \boldsymbol{\rho}) =
\underbrace{ - \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}} }_{\text{potential energy}}
+
\underbrace{ \frac{1}{2} \boldsymbol{\rho} ^{'} \mathbf{M} \boldsymbol{\rho} }_{\text{kinetic energy}},
\label{eq:Hamiltonian}
\end{equation}
where the mass matrix $\mathbf{M}$ weights our momentum variables.
The canonical distribution from statistical mechanics relates the joint density of state variables $\boldsymbol{\phi}$ and $\boldsymbol{\rho}$ to the energy in a system via the relationship,
\begin{equation}
	\cDensity{\boldsymbol{\phi}, \boldsymbol{\rho}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}} \propto e^{-H(\boldsymbol{\phi}, \boldsymbol{\rho})}.
\label{eq:canonicalDistribution}
\end{equation}

Substituting our Hamiltonian into (\ref{eq:canonicalDistribution}), we observe that $\boldsymbol{\phi}$ and $\boldsymbol{\rho}$ are independent and recognize the marginal density of ${\boldsymbol{\rho}}$ to be MVN.
To start the HMC algorithm, we first sample $\boldsymbol{\rho}$ from this marginal density.
Then by differentiating $H(\boldsymbol{\phi},\boldsymbol{\rho})$, we generate Hamilton's equations of motion,
\begin{equation}
\begin{aligned}[c]
\frac{d \rate{i}}{dt} &= + \frac{\partial H}{\partial \rho_i}, \hspace{.2em} \text{and} \\
\frac{d \rho_i}{dt} &= - \frac{\partial H}{\partial \rate{i}} = \frac{\partial}{\partial \rate{i}} \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}} \ \
\text{for all} \ i = 1, \dots, 2N - 2 .
\end{aligned}
\end{equation}
We can use the resulting vector field in conjunction with a variety of numerical integration techniques to propose new states of $\boldsymbol{\phi}$ for our MCMC chain.
Consistent with typical construction \citep{neal2011mcmc}, we use the leapfrog method for numerical integration, where we follow the trajectory of $\boldsymbol{\rho}$ for a half-step before updating $\boldsymbol{\phi}$.
For a full discussion of HMC, see \cite{neal2011mcmc}.
Importantly, Hamilton's equations elicit a need to calculate $\nabla_{\boldsymbol{\phi}} \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}} = \left(\gradient{\rate{1}}, \dots, \gradient{\rate{2 N - 2}}\right)^{^{'}} \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}$ to traverse phase space.

\subsection{Gradient of trait data log-likelihood}
A practical HMC sampler demands efficient calculation of $\nabla_{\boldsymbol{\phi}} \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \boldsymbol{\Theta}, \mathbf{Y}, \mathbf{S}}$.
Differentiating the logarithm of (\ref{eq:gibbsUpdates1}), we obtain
\begin{equation}
\gradient{\rate{i}} \log \cDensity{\boldsymbol{\phi}}{\boldsymbol{\Sigma}, s, \mathscr{F}, \mathbf{Y}, \mathbf{S}} = \gradient{\rate{i}} \log \cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}} + \gradient{\rate{i}} \log \cDensity{\boldsymbol{\phi}}{s}.
\label{eq:gradientPosterior}
\end{equation}
Our log-normal prior choice for $\boldsymbol{\phi}$ renders
evaluating the second term in Equation (\ref{eq:gradientPosterior}) trivial.
Here we develop a general recursive algorithm for calculating $\nabla_{\boldsymbol{\phi}} \log \cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}}$.
To facilitate this development, consider splitting $\mathbf{Y}$ into two disjoint sets relative to any node $i$ in $\mathscr{F}$.
We define $\mathbf{Y}_{\below{i}}$ as the observed data descendant of node $i$ and $\mathbf{Y}_{\above{i}}$ as the observed data ``above" (or not descendent of) node $i$.
For clarity, see Figure (\ref{fig:treeTraversal}).
\begin{figure}[H]
	\begin{center}
	\includegraphics[width=.4\textwidth]{Ex_Tree.pdf}
	\end{center}
	\caption{Example tree with $N = 3$ tips.
	Assume trait data $\mathbf{Y}_{i}$ are fully observed for $i = \{1,2,3\}$.
	We write $\mathbf{Y}_{\below{4}}$ and $\mathbf{Y}_{\above{4}}$ to denote the observed data below and above node $4$ respectively.
	Specifically, $\mathbf{Y}_{\below{4}} = \{\mathbf{Y}_{1}, \mathbf{Y}_2\}$ while  $\mathbf{Y}_{\above{4}} = \{\mathbf{Y}_{3}\}$.
	Partial likelihoods $\cDensity{\mathbf{Y}_{\below{4}}}{\mathbf{Y}_{4}}
	=
	\cDensity{\mathbf{Y}_{1}, \mathbf{Y}_{2}}{{\mathbf{Y}_{4}}}$ and
	$\cDensity{\mathbf{Y}_{4}}{\mathbf{Y}_{\above{4}}}
	=
	\cDensity{\mathbf{Y}_{4}}{\mathbf{Y}_3}$. }
	\label{fig:treeTraversal}
	\end{figure}
In the following, we drop the dependence of the log-likelihood on $\boldsymbol{\phi}$, $\boldsymbol{\Sigma}$ and $\mathscr{F}$ for notational convenience. To begin,

\begin{equation}\begin{aligned}
\gradient{\rate{i}} \left[
\log \density{\mathbf{Y}}
\right]
= & \,\, \gradient{\rate{i}} \left[ \density{\mathbf{Y}} \right]
\Big/  \density{\mathbf{Y}} \\
= & \,\, \gradient{\rate{i}} \left[ \int
 \cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
 \density{\mathbf{Y}_{\above{i}}}
 \text{d} \mathbf{Y}_{i} \right]
\Big/  \density{\mathbf{Y}} \\
= & \,\, \int \gradient{\rate{i}} \left[
 \cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
 \density{\mathbf{Y}_{\above{i}}} \right]
 \text{d} \mathbf{Y}_{i}
\Big/  \density{\mathbf{Y}} \\
= & \,\, \int
 \cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}
 \gradient{\rate{i}} \left[
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
 \right]
 \density{\mathbf{Y}_{\above{i}}}
 \text{d} \mathbf{Y}_{i}
\Big/  \density{\mathbf{Y}}.
\label{eq:differential}
\end{aligned}\end{equation}
The last equality above follows from the fact that $\rate{i}$ is associated only with the branch above node $i$.
Therefore when we condition on $\mathbf{Y}_{i}$, $\mathbf{Y}_{\below{i}}$ is independent of $\rate{i}$.
Similarly, $\mathbf{Y}_{\above{i}}$ evolves independent of $\rate{i}$.
To proceed with the differential above, we use the fact that $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}$ follows a MVN distribution with as of yet undetermined mean $\nodePreMean{i}$ and precision $\nodePrePrecision{i}$ (see Appendix (\nameref{sec:preOrderDerivation}) for a detailed derivation).
We extract the middle term from Equation (\ref{eq:differential}) and find
\begin{equation}\begin{aligned}
 \gradient{\rate{i}} \left[
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
 \right] &=
 %
 \frac{1}{2}
 \left\{
 	\left( \mathbf{Y}_{i} - \nodePreMean{i} \right)^{'} \nodePrePrecision{i} \hspace{0.1em}  \branchLength{i}
 	
 		 \gradient{\rate{i}} \left[ \nodeVarianceFunction{\rate{i}} \right]
 	\hspace{-0.1em} \nodePrePrecision{i} \left( \mathbf{Y}_{i} - \nodePreMean{i} \right)
 %
 \right.
 \\
 & \quad \quad \quad \quad \quad \quad
 \left.
 	-
 	\trOperator{
 		\nodePrePrecision{i} \hspace{0.1em}  \branchLength{i} \gradient{\rate{i}} \left[ \nodeVarianceFunction{\rate{i}} \right]
 	}
 \right\}
  \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}} ,
\end{aligned}
\label{eq:differential_mvn}
\end{equation}
using the differential properties
\begin{equation}\begin{aligned}
\text{d} \nodePrePrecision{i} &= - \nodePrePrecision{i} \hspace{-0.1em} \left( \text{d} \nodePrePrecision{i}^{-1} \right) \nodePrePrecision{i} \ \text{ and} \\
\text{d} \hspace{-0.1em} \left| \nodePrePrecision{i}^{-1} \right| &= \left| \nodePrePrecision{i}^{-1} \right| \hspace{-0.1em} \trOperator{ \nodePrePrecision{i} \text{d} \nodePrePrecision{i}^{-1} },
\end{aligned}\end{equation}
found in, e.g., \cite{matrixcookbook}.

\newcommand{\functional}[1]{\mathbf{F}\hspace{-0.1em}\left( #1 \right)}
\newcommand{\nastyPrecision}[1]{\boldsymbol{\Upsilon}_{#1}}
\newcommand{\nastyDeterminant}[1]{\boldsymbol{\chi}_{#1}}

To simplify notation, we let function
\begin{equation}\begin{aligned}
\functional{\mathbf{Y}_{i}} =
 \frac{1}{2}
 \left\{
 	\left( \mathbf{Y}_{i} - \nodePreMean{i} \right)^{'}
 	\nastyPrecision{i}
 	\left( \mathbf{Y}_{i} - \nodePreMean{i} \right)
 %
 	-
 	\trOperator{
		\nastyDeterminant{i}
 	}
 \right\} ,
 \label{eq:functional}
\end{aligned}\end{equation}
where
$\nastyPrecision{i} =
\nodePrePrecision{i} \hspace{0.1em}  \branchLength{i} \gradient{\rate{i}} \left[ \nodeVarianceFunction{\rate{i}} \right] \hspace{-0.1em} \nodePrePrecision{i}$ and
$\nastyDeterminant{i} =
\nodePrePrecision{i} \hspace{0.1em}  \branchLength{i} \gradient{\rate{i}} \left[ \nodeVarianceFunction{\rate{i}} \right]$.
Substituting Equation (\ref{eq:functional}) back into Equation (\ref{eq:differential}), we observe that
\begin{equation}\begin{aligned}
\gradient{\rate{i}} \left[
\log \density{\mathbf{Y}}
\right]
= & \,\, \int
 \functional{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
 \density{\mathbf{Y}_{\above{i}}}
 \text{d} \mathbf{Y}_{i}
\Big/  \density{\mathbf{Y}} \\
= & \,\, \int
 \functional{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}}
 \text{d} \mathbf{Y}_{i} \\
= & \,\, \expectation{ \functional{\mathbf{Y}_{i}} \mid \mathbf{Y}}.
\end{aligned}
\label{eq:expectationOfF}
\end{equation}
When $\mathbf{Y}_{i}$ is fully observed (typically $i \leq N$), this expectation collapses to the direct evaluation of $\functional{\mathbf{Y}_{i}}$.
When $i = N + 1, \ldots, 2 N - 2$
 or if $\mathbf{Y}_{i}$ is partially observed for $i = 1,\ldots, N$,
we require $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}}$.
From Bayes' theorem, $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}} \propto \cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}
 \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}$.
Partial likelihood $\cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}$ is proportional to a MVN density characterized by computable mean $\nodeMean{i}$ and precision $\nodePrecision{i}$ \citep{pybus2012unifying}.
Using this fact, $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}}$ becomes MVN with
mean
$
\fullConditionalMean{i} =
\fullConditionalVariance{i} \left(
	\nodePrecision{i} \nodeMean{i} + \nodePrePrecision{i} \nodePreMean{i}
\right)
$
and
variance
$
\fullConditionalVariance{i} =
\left[
	\nodePrecision{i} + \nodePrePrecision{i}
\right] ^{-1}.
$
 When tip $i$ is partially observed, we partition $\mathbf{Y}_{i} = \left( \mathbf{Y}_{i} ^{\text{u}}, \ \mathbf{Y}_{i} ^{ \text{o} } \right) ^{'}$ into its unobserved and observed entries.
Using properties of the conditional MVN,
$\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}}$ becomes degenerate with mean
\begin{equation}
\fullConditionalMean{i} =
\begin{bmatrix}
\nodePreMean{i} ^{\text{u}} - \left( \nodePrePrecision{i} ^{\text{u}} \right) ^{-1}
\nodePrePrecision{i} ^{\text{uo}}
\left(
	\mathbf{Y}_{i} ^{ \text{o} } - \nodePreMean{i} ^{ \text{o} }
\right)
\\
\mathbf{Y}_{i} ^{ \text{o} }
\end{bmatrix}
\end{equation}
and variance
\begin{equation}
	\fullConditionalVariance{i} =
	\begin{bmatrix}
	\left(
	\nodePrePrecision{i} ^{\text{u}}
	\right) ^{-1}
	& 0\\
	0 & 0
\end{bmatrix}.
\end{equation}
Finally, for both partially and completely unobserved cases above,
\begin{equation}\begin{aligned}
\expectation{ \functional{\mathbf{Y}_{i}} \mid \mathbf{Y}} &=
 \frac{1}{2}
 \left\{
 \trOperator{
 	\fullConditionalVariance{i} \nastyPrecision{i}
 }
 +
 \left( \fullConditionalMean{i} - \nodePreMean{i} \right)^{'}
 	\nastyPrecision{i}
 \left( \fullConditionalMean{i} - \nodePreMean{i} \right)
 	-
 	\trOperator{
		\nastyDeterminant{i}
 	}
 \right\}.
 \label{eq:linearGradient}
\end{aligned}\end{equation}
Equation (\ref{eq:linearGradient}) provides a recipe to compute $\nabla_{\boldsymbol{\phi}} \log \cDensity{\mathbf{Y}}{\boldsymbol{\phi}, \boldsymbol{\Sigma}, \mathscr{F}}$ using the means and precisions that characterize partial data likelihoods $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}$ and $\cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}}$.

\subsection{Tree Traversals} \label{sec:algorithms}
We introduce post- and pre-order tree traversals to recursively calculate all partial data likelihood means and precisions in computational complexity $\order{N}$ that scales linearly with $N$.
To begin, let nodes $i$ and $j$ be daughters of node $k$.
Following \cite{hassler2019inferring}, let $\observedMatrix{k} = \text{diag}(\delta_{k 1}, \ldots \delta_{k P})$ for $k = 1, \ldots, N$ be a diagonal matrix with indicator elements $\delta_{k p}$ that take value $1$ if $\text{Y}_{k p}$ is observed and $0$ if not. For the post-order traversal,
\begin{equation}
\cDensity{\mathbf{Y}_{\below{i}}}{\mathbf{Y}_{i}} \propto \mvnDensity{\mathbf{Y}_{i}; \ \nodeMean{i}}{\nodePrecision{i}},
\end{equation}
with post-order mean $\nodeMean{i}$ and precision $\nodePrecision{i}$.
For $k = 1, \ldots, 2 N - 1$ in post-order, we build the precision via

\begin{equation}
\nodePrecision{k} =  \begin{cases} \infty \times \observedMatrix{k} \ \ \ \text{if k is a tip}\\
(\nodePrecision{i}^* + \nodePrecision{j}^*)  \ \ \text{otherwise,}
\end{cases}
\end{equation}
with the definition that $\infty \times 0 = 0 $ and
\begin{equation}
\nodePrecision{i}^* = \Big( \nodePrecision{i} ^- + \branchLength{i} \observedMatrix{i} \nodeVarianceFunction{\rate{i}} \observedMatrix{i} \Big) ^-
\ \ \ \text{and} \ \ \
\nodePrecision{j}^* = \Big( \nodePrecision{j} ^- + \branchLength{j} \observedMatrix{j} \nodeVarianceFunction{\rate{j}} \observedMatrix{j} \Big) ^-,
\end{equation}
where the pseudo-inverse, defined and developed by \cite{bastide2018inference, hassler2019inferring}, is described in Appendix (\nameref{sec:pseudoInverseExplanation}).
At the tips, we build the mean
$
\nodeMean{k}
= \observedMatrix{k} \odot \mathbf{Y}_{k}
$
where $\odot$ is the elementwise dot product,
and for the internal nodes, $\nodeMean{k}$ is a solution to
\begin{equation}
	\nodePrecision{k}
	\nodeMean{k}
	=
	 (\nodePrecision{i}^* \nodeMean{i} + \nodePrecision{j}^* \nodeMean{j}).
\end{equation}
For a proof of these post-order updates, see \cite{hassler2019inferring} (Supplemental Material).

To compute $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}$, we traverse the tree in pre-order fashion according to our generalized version of the recursive algorithm proposed by \cite{cybis2015}.
See Appendix (\nameref{sec:preOrderDerivation}) for a derivation of our generalized pre-order update.
For the pre-order traversal,

\begin{equation}
\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}} = \mvnDensity{\mathbf{Y}_{i}; \ \nodePreMean{i}}{\nodePrePrecision{i}}.
\label{eq:preOrderDistribution}
\end{equation}
For $i = 2N - 1, \ldots, 1$ looking down the tree, we update our pre-order precision,

\begin{equation}
\nodePrePrecision{i} =
\begin{cases}
	\kappa_0 \boldsymbol{\Sigma} ^{-1} \ \ \ \
	\text{if i is root}\\
\Big( (\nodePrePrecision{i}^{*}) ^{-1} + t_i \nodeVarianceFunction{\rate{i}} \Big)^{-1} \ \ \ \ \text{otherwise}
\end{cases}
\end{equation}
at each node where
\begin{equation}
\nodePrePrecision{i}^{*} = \nodePrecision{j}^* + \nodePrePrecision{k}.
\end{equation}
We also keep track of the pre-order mean at each node via
\begin{equation}
\nodePreMean{i} =
\begin{cases}
\boldsymbol{\nu}_0 \ \ \ \
\text{if i is root}\\
(\nodePrePrecision{i}^{*}) ^{-1} \big( \nodePrecision{j}^* \nodeMean{j}
+
\nodePrePrecision{k} \nodePreMean{k} \big) \ \ \ \
\text{otherwise}.
\end{cases}
\end{equation}

Both traversals visit each node exactly once and perform a matrix inversion as their most costly operation, providing an $\order{N P^3}$ algorithm.
However, as we observe in Equation (\ref{eq:varianceChoices}), generally $\nodeVarianceFunction{\rate{i}} = \general{\rate{i}} \boldsymbol{\Sigma}$.
In this case, we can further reduce the computational complexity to $\order{N P ^2}$ by factoring out $\boldsymbol{\Sigma}$.
Instead of inverting $\nodeVarianceFunction{\rate{i}}$ at each step, we only need to invert $\boldsymbol{\Sigma}$ at most once per likelihood or gradient evaluation.



\section{Results}
\subsection{West Nile Virus}
West Nile virus (WNV) is responsible for more than 1,500 deaths and caused over 700,000 illnesses since first reported in North America in 1999.
The virus typically spreads via mosquito bites; however, the primary host is birds.
First identified in New York City, WNV spread to the Pacific coast by 2003 and reached south into Argentina by 2005 \citep{petersen2013west}.
We examine whole aligned viral genomes (11,029 nt) and geographic data on $104$ cases of WNV collected between 1999 and 2007 \citep{pybus2012unifying}.
In cases where only the year of sampling is known, we set the sampling date to the midpoint of that year.
Previous authors have recorded latitude and longitude geographic sampling information by converting zip code locations using ZIPList5.
For 27 of the specimens, only the U.S. or Mexican state of discovery is known and so we have augmented sampling data with the coordinates of the centroid of the state \citep{pybus2012unifying}.

Here we study the simultaneous evolution and dispersal of WNV as it spreads across North America, following the modeling choices of \cite{pybus2012unifying}.
We define geographic location as our trait of interest $\mathbf{Y}$ within a RRW and infer rates $\boldsymbol{\phi}$ using our new HMC method.
In two separate inference scenarios, we compare the computational efficiency of our method to the random-scan UMH approach employed by \cite{pybus2012unifying}.
\begin{figure}
	\begin{center}
	\includegraphics[width=.7\textwidth]{logESS_Fixed_histo.pdf}
	\end{center}
	\caption{Comparing computational efficiency of Hamiltonian Monte Carlo (HMC) and univariable Metropolis-Hastings (UMH) transition kernels through effective sample size (ESS) per unit time in West Nile virus (WNV) phylogeography.


	}
	\label{fig:ess}
	\end{figure}

To begin, we set up a RRW model with log-normal prior on rates $\boldsymbol{\phi}$ with mean $= 1$ and standard deviation $s$ and use a general time-reversible (GTR) + $\Gamma$ substitution model with a log-normal relaxed molecular clock.
We use the UMH transition kernel to run a 250 million state MCMC chain simulation to obtain  posterior mean estimates of $\boldsymbol{\Sigma}$ and $s$ as well as a maximum clade crediblility (MCC) tree.
In scenario (\textbf{a}) we use these fixed model parameters and topology to strictly sample $\boldsymbol{\phi}$ using both the HMC and UMH transition kernels.
Under this fixed analysis we run our HMC-based chain for 1 million states and a UMH-based chain for 150 million states.
We use effective sample size (ESS) of the  posterior $\rate{i}$ samples for all $i$ divided by computational runtime to evaluate the performance of each MCMC approach and report densities of ESS/second across all branches in Figure (\ref{fig:ess}).
ESS/second is averaged across five runs each with uniform (0-10) random initial branch-rate multipliers.

The median ESS/second across $\boldsymbol{\phi}$ is $118$ and $0.377$ for the HMC and UMH transition kernels respectively.
This demonstrates a $312$-fold speed increase.
Additionally, the minimum ESS/second is $12.4$ with HMC and $0.183$ with UMH, exhibiting a $67.7$-fold speed-up for the ``least well'' explored $\rate{i}$.



In scenario (\textbf{b}), we use a random starting tree and jointly estimate all parameters ($\boldsymbol{\phi}, \boldsymbol{\Sigma}$, $s$, $\mathscr{F}$ and $\boldsymbol{\Theta}$) of the full posterior (\ref{eq:fullPosterior}).
Since branch-specific $\rate{i}$ are no longer identifiable when $\mathscr{F}$ is random, we compare square jump distance across all $\boldsymbol{\phi}$ between samples from the posterior under both MCMC regimes to compare efficiency.
We run HMC chains for 22.5 million states so that we are sampling from the posterior distribution of all parameters and we save the state of BEAST.
Subsequently, we run both HMC and UMH chains from the same saved states and compute lag-7 square jump distance to adjust for the relative weight of the transition kernel in the full analysis.
Since the UMH sampler updates only one branch-rate multiplier at a time, we compare square jump distance between samples of our HMC chain with samples from the UMH chain that are lagged $(2N - 2)\times$ (i.e.~$206\times$) farther apart.
We run each MCMC simulation until we obtain 5000 samples from the posterior and report the average median across five separate runs.
In this comparison, we find that the average square jump distances from five separate runs
is $1457$ and $128.2$ for the HMC and UMH chains respectively.

\begin{figure}[H]
	\begin{center}
	\includegraphics[width=0.8\textwidth]{wnv_hmc_tree_thinLines.pdf}
	\end{center}
	\caption{Maximum clade crediblility (MCC) tree resulting from Hamiltonian Monte Carlo (HMC) inference under phylogeographic relaxed random walk (RRW) of West Nile virus.
	We color branches by posterior mean branch-rate parameters $\boldsymbol{\phi}$.}
	\label{fig:wnvTree}
	\end{figure}


In Figure (\ref{fig:wnvTree}) we report the MCC tree,
obtained from applying HMC to the RRW model as described in scenario (\textbf{b}), where substitution rate variation is accounted for by the molecular clock model.
The branch with the highest posterior dispersal rate starts the WN02 lineage identified by \cite{gray2010evolutionary}.
The clade of New York isolates sampled in 1999, however, maintains a much slower dispersal rate. Sufficiently precise posterior estimates under the previous UMH approach remain unavailable in reasonable time to expose these differences.




\subsection{Mammalian Life History}
Life history theory aims to explain how traits such as adult body mass, litter size and lifespan evolve to optimize reproductive success \citep{stearns2000life}.
Life history theory finds important applications in determining a species' fecundity and predicting extinction risk in response to changing environmental stimuli \citep{pacifici2017species, fritz2009geographical, de2019demographic},
but due to the sparseness of much life history data, it is essential to understand how traits covary to make meaningful predictions \citep{santini2016trait}.
To determine which traits covary, comparative mammalian life-history studies posit a `fast–slow' continuum, claiming small mammals are typically `fast', characterized by early maturation, large litters and shorter lifespans, while larger mammals are typically `slow' and present contrasting characteristics \citep{oli2004fast, millar1983life}. Under this framework, certain traits such as gestation length, weaning age and body mass are predicted to be positively correlated, but reported estimates of positive correlation from data may be artifacts of the restrictive assumptions of strict Brownian diffusion modeling.
Here we re-evaluate this claim within the RRW of trait evolution made tractable through $\order{N}$ HMC sampling.

Under the RRW, we infer correlation between five life history traits from the PanTHERIA data set \citep{jones2009pantheria}, namely body mass, litter size, gestation length, weaning age and litter frequency across $3650$ mammalian species related by the fixed supertree of \cite{fritz2009geographical}.
To obtain this subset of the supertree, we only consider taxa for which at least one of these five traits is observed.
We take the intersection of this set of taxa with those in the fixed supertree of \cite{fritz2009geographical} and prune all other observations from the tree.
We log-transform and standardize the trait measurements and subsequently estimate posterior mean correlations between each pair of traits under the RRW using an HMC-based chain for 300 thousand states.
To gauge the effect of a heterogeneous diffusion process on the correlation between traits, we also make inference using the strict Brownian diffusion model where the $\boldsymbol{\phi}$ are all identically $1$. Here we perform MCMC inference on the diffusion matrix $\boldsymbol{\Sigma}$ for 100 thousand states.
We report posterior mean estimates of correlation between each pair of traits under both the RRW and strict Brownian diffusion in Figure (\ref{fig:mammalCorrelation}).
\begin{figure}[H]
\begin{center}
\includegraphics[width=.8\textwidth]{mammalCorrelation2-2.pdf}
\end{center}
\caption{Posterior mean correlation between mammalian life history traits under the RRW and strict Brownian diffusion model. Shape of ellipse indicates strength and sign of correlation, while colors indicate the posterior probability that the correlation is positive (red) or negative (blue).}
\label{fig:mammalCorrelation}
\end{figure}
In most cases, the RRW reassuringly confirms analysis under the more limited model. However, in some cases our confidence in the sign of the correlation differs between models and
in one instance the sign of the posterior mean correlation disagrees.
Under the RRW, we observe positive posterior mean correlation  of $0.021$ between litter frequency and litter size with posterior odds ratio $2.63$ that the correlation is positive.
Under the strict Brownian diffusion model we observe a negative posterior mean correlation of $-0.018$ with posterior odds ratio $2.25$ of being negative, indicating slightly weaker belief in the correlation's sign under the strict model.







\section{Discussion}

Previous MCMC techniques to investigate trait evolution under the RRW model scale poorly with large data sets.
Specifically the UMH transition kernel is ineffective for sampling correlated, high dimensional parameter space.
We provide a remedy by using an HMC transition kernel to sample all branch-rate multipliers simultaneously.
To improve the speed of HMC we derive an algorithm for calculating the gradient of the trait data log-likelihood.
This gradient calculation achieves $\order{N}$ computational speed, a vast improvement compared to both numerical and pruning methods for calculating the gradient that typically require $\order{N^2}$.

We observe over 300-fold speed-up when comparing our HMC transition kernel to UMH in the spread of the WNV across North America in the early 2000s.
The resulting MCC tree reveals that the largest dispersal rate precedes the most recent common ancestor of the WN02 lineage.
Subsequently, the dispersal rates slow down through the WN02 clade.
This suggests that this clade developed after some rapid geographic displacement.
Interestingly, the appearance of smaller branch-rate multipliers within the WN02 lineage is consistent with the slowing speed of sequence evolution as described in \cite{snapinn2007declining}.

As exhibited in Figure (\ref{fig:ess}), ESS from posterior sampling accumulates at variable speed across the branches of the tree.
To further improve the sampling of our HMC algorithm, one might use an approximation of the posterior covariance of $\boldsymbol{\phi}$ for the mass matrix $\mathbf{M}$ to appropriately weight momentum updates in the HMC algorithm \citep{neal2011mcmc}.
Possible approximations include the Hessian of the log-posterior (a local approximation of the curvature of branch-rate multiplier space) or the sample variance across each dimension.
An important consideration in choosing an appropriate $\mathbf{M}$ is whether one is studying under a fixed or random phylogeny $\mathscr{F}$.
Since varying $\mathscr{F}$ in the posterior often creates multimodal distributions of $\boldsymbol{\phi}$, local approximations such as the Hessian may be of limited assistance in such cases.

We show in our application to mammalian life history that our computationally efficient HMC algorithm imbues the RRW model with the ability to handle large trees with thousands of taxa.
By applying the RRW model to this massive example we confirm that large mammals have `slower' life history characteristics, exhibited by the positive correlation between body mass, gestation length and weaning age, while smaller mammals scale in the opposite manner and tend to have high litter frequency and size, see Figure (\ref{fig:mammalCorrelation}).
The posterior mean correlation between litter frequency and litter size changes sign under each model, but with low posterior probability reflecting a lack of correlation between these traits.
Importantly, our method allows us to obtain results in 48 hours where the previous UMH method would take approximately 33 days.

In a time where biological data are more prolific than ever, scalable approaches to complex models of evolution such as the RRW prove increasingly useful in a variety of applications.
From spatial epidemiology where determining the dispersal rate of an infectious disease is crucial, to evolutionary ecology where understanding life-history can provide insight into declining animal populations, the analysis of data is becoming a bottleneck to the scientific process and the need for computationally faster approaches stands evident.
We hope that this work will serve to improve the speed of such analyses.


\section{Acknowledgments}

This work was supported by the European Research Council under the European Union's Horizon 2020 research and innovation programme (grant agreement number 725422 - ReservoirDOCS); The Artic Network from the Wellcome Trust (grant number 206298/Z/17/Z); National Science Foundation (grant number DMS 1264153); National Institutes of Health (grants R01 AI107034, U19 AI135995, and T32 GM008185 to AAF); and Research Foundation -- Flanders (`Fonds voor Wetenschappelijk Onderzoek -- Vlaanderen',  G066215N, G0D5117N and G0B9317N) to PL.


\input{rrw_arxiv.bbl}


\section{Appendices}
\label{sec:computationalProcedures}
We provide public access to all BEAST XML files used in this work at \url{http://github.com/suchard-group/RRW_at_scale}.


\subsection{Pre-Order Partial Likelihood}
\label{sec:preOrderDerivation}
Here we derive a generalized version of the pre-order recursive algorithm proposed by \cite{cybis2015} to compute $\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}$ for all $i$ in $\order{N}$.
We begin with the law of total probability,

\begin{equation}
	\cDensity{\mathbf{Y}_{i} }{\mathbf{Y}_{\above{i}}} \propto \int \cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{k}} \cDensity{\mathbf{Y}_{\below{j}}}{\mathbf{Y}_{k}}
	\cDensity{\mathbf{Y}_{k}}{\mathbf{Y}_{\above{k}}} \ \text{d} \mathbf{Y}_{k}
	\label{eq:preorder1}
\end{equation}
for node $i$ with parent $k$ and sibling $j$. Recalling that

\begin{equation}
	\begin{aligned}
	\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{k}} &= \mvnDensity{\mathbf{Y}_{i}; \ \mathbf{Y}_{k}}{
		\branchLength{i} \nodeVarianceFunction{\rate{i}}}, \  \text{and}\\
\cDensity{\mathbf{Y}_{\below{j}}}{\mathbf{Y}_{k}}
&\propto
\mvnDensity{\mathbf{Y}_{k}; \ \nodeMean{j}}{(\nodePrecision{j}^* )^{-1}},
	\end{aligned}
\end{equation}
we identify Equation (\ref{eq:preorder1}) as a recursive expression whose solution has the form
\begin{equation}
	\cDensity{\mathbf{Y}_{i}}{\mathbf{Y}_{\above{i}}}
	=
	\mvnDensity{\mathbf{Y}_{i}; \ \nodePreMean{i}}{\nodePrePrecision{i}},
\end{equation}
with presently undetermined pre-order mean $\nodePreMean{i}$ and pre-order precision $\nodePrePrecision{i}$.

We unravel these quantities by first identifying that $\cDensity{\mathbf{Y}_{2 N - 1}}{\mathbf{Y}_{\above{2 N - 1}}} = \density{\mathbf{Y}_{2 N - 1}}$ and set $\nodePreMean{2 N - 1} = \boldsymbol{\nu}_0$ and $\nodePrePrecision{2 N - 1} = \kappa_0 \boldsymbol{\Sigma} ^{-1}$. Then proceeding in pre-order fashion for $i = 2 N - 2, \ldots, 1$
\begin{equation}
	\begin{aligned}
	\nodePrePrecision{i}
	&=
	\Big( (\nodePrePrecision{i}^{*}) ^{-1}
	+ t_i \nodeVarianceFunction{\rate{i}} \Big)^{-1}
	\ \text{where}\\
	\nodePrePrecision{i}^{*}
	&=
	 \nodePrecision{j}^* + \nodePrePrecision{k},
	\ \text{and}\\
	\nodePreMean{i}
	&=
	(\nodePrePrecision{i}^{*}) ^{-1} \big( \nodePrecision{j}^* \nodeMean{j}
	+
	\nodePrePrecision{k} \nodePreMean{k} \big).
	\end{aligned}
	\end{equation}

\subsection{Pseudo-inverse}
\label{sec:pseudoInverseExplanation}

The pseudo-inverse used in the post-order tree traversal and defined by \cite{bastide2018inference} and \cite{hassler2019inferring} is an operation for inverting precision and variance matrices with diagonal entries that take the value $\infty$.
To invert a diagonal precision matrix, $\nodePrecision{i}$ with entries $\infty$ and $0$, we define $\infty ^- = 0$ and $0 ^- = \infty$.
To invert the variance matrix, $ \left( \nodePrecision{i} ^- + \branchLength{i} \observedMatrix{i} \nodeVarianceFunction{\rate{i}} \observedMatrix{i} \right)$ we invert the block matrix of observed trait covariation and invert the remaining diagonal elements using the convention that $\infty ^- = 0$.

\end{document}
