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

Panel data is common in various fields such as social sciences. These data consist of multiple individuals, followed over several time points, and there are often many observations per individual at each time, for example, family status and income of each individual at each time point of interest. Such data can be analyzed in various ways, depending on the research questions and the characteristics of the data such as the number of individuals and time points, and the assumed distribution of the response variables. In social sciences, popular, somewhat overlapping modeling approaches include dynamic panel models, fixed effect models, dynamic structural equation models \citep{Asparouhov2018}, cross-lagged panel models (CLPM), and their various extensions such as CLPM with fixed or random effects \citep{arellano1991, Allison2009, Bollen2010, Allison2017, Hamaker2015, Mulder2021} and general cross-lagged panel model \citep{Zyphur2020}.

There are several \proglang{R} \citep{R} packages available from the Comprehensive \proglang{R} Archive Network (CRAN) focusing on analysis of panel data. The \pkg{plm} \citep{plm} package provides various estimation methods and tests for linear panel data models, while \pkg{fixest} \citep{fixest} supports multiple fixed effects and different distributions of response variables (based on \code{stats::family}. The \pkg{panelr} \citep{panelr} package contains tools for panel data manipulation and estimation methods for so-called ``within-between'' models which combine fixed effect and random effect models. This is done by using \pkg{lme4} \citep{lme4}, \pkg{geepack} \citep{geepack}, and \pkg{brms} \citep{brms} packages as a backend. The \pkg{lavaan} \citep{lavaan} package provides methods for general structural equation modeling and thus can be used to estimate various panel data models such as CLPMs with fixed or random intercepts. Similarly, it is also possible to use the general multilevel modeling packages \pkg{lme4} and \pkg{brms} directly for panel data modeling. Of these, only \pkg{lavaan} and \pkg{brms} support joint modeling of multiple interdependent response variables, which is typically necessary for multi-step predictions and long-term causal effect estimation \citep{dmpm}.

In traditional panel data models such as the ones supported by the aforementioned packages, the number of time points considered is often assumed to be relatively small, say less than 10, while the number of individuals can be for example hundreds or thousands. This is especially true for commonly used wide-format SEM approaches which cannot handle a large number of time points \citep{Asparouhov2018}. Perhaps due to the small number of time points, the effects of predictors are typically assumed to be time-invariant (although some extensions to time-varying effects have emerged \citep[e.g.,][]{Sun2009, Asparouhov2018, hayakawa2019}. On the other hand, when the number of time points is moderate or large, say hundreds or thousands (sometimes referred as intensive longitudinal data), it can be reasonable to assume that the dynamics of the system change over time, for example so that effects of predictors vary in time.

Modeling time-varying effects in (generalized) linear models can be based on state space models (SSMs) \citep{harvey1982, durbin2012, helske2022}, for which there are various \proglang{R} implementations such as \pkg{walker} \citep{helske2022}, \pkg{shrinkTVP} \citep{knaus2021}, and \pkg{CausalImpact} \citep{brodersen2014}. However, these implementations are restricted to a non-panel setting of single individual and single response variable. Other approaches include methods based on the varying coefficients models \citep{hastie1993, eubank2004}, implemented in \pkg{tvReg} \citep{casas2019} and \pkg{tvem} \citep{dziak2021} packages. While \pkg{tvem} supports multiple individuals, it does not support multiple response variables per individual. The \pkg{tvReg} supports only univariate single-individual responses. Also based on SSMs and differential equations, the \pkg{dynr} \citep{dynr} package provides methods for modeling multivariate dynamic regime-switching models with linear or non-linear latent dynamics and linear-Gaussian observations. Because both multilevel models and SEMs can be defined as SSMs \citep[see e.g.,][]{Sallas1981,KFAS,Chow2010}, other packages supporting general SSMs could be in principle suitable for panel data analysis as well (e.g., \pkg{KFAS} \citep{KFAS}, \pkg{bssm} \citep{bssm}, and \pkg{pomp} \citep{pomp}). However, SSMs are often computationally demanding especially for non-Gaussian observations where the marginal likelihood is analytically intractable, and the large number of individuals can be problematic particularly in the presence of additional group-level random effects which complicates the construction of the corresponding state space model \citep{KFAS}.

The \pkg{dynamite} \citep{dynamitepackage} package provides an alternative approach to panel data inference which avoids some of the limitations and drawbacks of the aforementioned methods. First, the dynamic multivariate panel data models (DMPMs), introduced by \citet{dmpm} and implemented in the \pkg{dynamite} package support estimation of effects that vary smoothly over time according to Bayesian P-splines \citep{lang2004}, with penalization based on random walk priors. This allows modeling for example effects of interventions which increase or decrease over time. Second, \pkg{dynamite} supports a wide variety of distributions for the response variables such as Gaussian, Poisson, binomial, and categorical distributions. Third, with \pkg{dynamite} we can model an arbitrary number of simultaneous measurements per individual. Finally, the estimation is fully Bayesian using \proglang{Stan} \citep{Stan, rstan}, which leads to transparent and interpretable quantification of parameter and predictive uncertainty.

One of the most defining features of \pkg{dynamite} is its high-performance prediction function, which is fully automated, supports multi-step predictions over the entire observed time-interval, and can operate at the individual-level or group-level. This is in stark contrast to packages such as \pkg{brms} where, in presence of lagged response variables as covariates, obtaining such predictions necessitates the computation of manual stepwise predictions and can pose a challenge even for an experienced user. Furthermore, by jointly modeling all endogenous variables simultaneously, \pkg{dynamite} allows us to consider the long-term effects of interventions which take into account the interdependence of several variables of the model.

The paper is organized as follows. In Section~\ref{sec:model} we introduce the dynamic multivariate panel model which is the class of models considered in the \pkg{dynamite} package and describe the assumptions made in the package with respect to these models. Section~\ref{sec:dynamitepackage} introduces the software package and its core features along with two illustrative examples using a real dataset and a synthetic dataset. Sections~\ref{sec:construction} and \ref{sec:fitting} provide a more comprehensive and technical overview on how to define and estimate models using the package, respectively. The use of the model fit objects for prediction is discussed in Section~\ref{sec:prediction}. Finally, Section~\ref{sec:summary} provides some concluding remarks.

\section{The dynamic multivariate panel model} \label{sec:model}

Consider an individual \(i\) with observations \(y_{i,t} = (y^1_{i,t}, \ldots, y^c_{i,t},\ldots, y^C_{i,t})\), \(t=1,\ldots,T\), \(i = 1,\ldots,N\) i.e., at each time point \(t\) we have \(C\) observations from \(N\) individuals, where \(C\) is the number of  channels, i.e., different response variables that have been measured. Assume that each element of \(y_{i,t}\) can depend on the past observations \(y_{i,t-\ell}\), \(\ell=1,\ldots\) (where the set of past values can be different for each channel) and also on additional exogenous covariates \(x_{i,t}\). In addition, \(y^c_{i,t}\) can depend on the elements of current \(y_{i,t}\), assuming that this does not lead to cyclic dependencies; this translates to a condition that the channels can be ordered so that \(y^c_{i,t}\) depends only on \(y^1_{i,t}, \ldots, y^{c-1}_{i,t}\), exogenous covariates, and past observations. For simplicity of the presentation, we now assume that the observations of each channel only depend on the previous time points, i.e., \(\ell = 1\) for all channels. We denote the set of all model parameters by \(\theta\). Now, assuming that the elements of \(y_{i,t}\) are independent given \(y_{i, t-1}\), \(x_{i,t}\), and \(\theta\) we have
\[
\begin{aligned}
  y_{i,t} &\sim p_t(y_{i,t} | y_{i,t-1},x_{i,t},\theta) =
    \prod_{c=1}^C p^c_t(y^c_{i,t} | y^1_{i,t-1}, \ldots, y^C_{i,t-1}, x_{i,t}, \theta).
\end{aligned}
\]
Importantly, the parameters of the conditional distributions \(p^c\) are time-dependent, enabling us to consider the evolution of the dynamics of our system over time.

Given a suitable link function depending on our distributional assumptions, we define a linear predictor \(\eta^c_{i,t}\) for the conditional distribution \(p^c_t\) of each channel \(c\) with the following general form:
\[
\begin{aligned}
  \eta^c_{i,t} &=
    \alpha^c_{t} + X^{\beta, c}_{i,t} \beta^c + X^{\delta, c}_{i,t} \delta^c_{t} + X^{\nu, c}_{i,t} \nu_i^c +  \lambda^c_i \psi^c_t,
\end{aligned}
\]
where \(\alpha_t\) is the (possibly time-varying) common intercept term, \(X^{\beta, c}_{i,t}\) defines the predictors corresponding to the vector of time-invariant coefficients \(\beta^c\), and similarly for the time-varying term \(X^{\delta, c}_{i,t} \delta^c_{t}\). The term \(X^{\nu, c}_{i,t} \nu^c_{t}\) corresponds to individual-level random effects, where \(\nu^1_{i},\ldots, \nu^C_{i}\) are assumed to follow zero-mean Gaussian distribution, either with a diagonal or a full covariance matrix. Note that the predictors in \(X^{\beta, c}_{i,t}\), \(X^{\delta, c}_{i,t}\), and \(X^{\nu, c}_{i,t}\) may contain exogenous covariates or past observations of the response channels (or transformations of either).The final term \(\lambda^c_i \psi^c_t\) is a product of latent individual loadings \(\lambda^c_i\) and a univariate latent dynamic factor \(\psi^c_t\).

For time-varying coefficients \(\delta\) (and similarly for time-varying \(\alpha\) and latent factor \(\psi\)), we use Bayesian P-splines (penalized B-splines) \citep{lang2004} where
\[
  \delta^c_{k,t} = B_t \omega_k^c, \quad k=1,\ldots,K,
\]
where \(K\) is the number of covariates, \(B_t\) is a vector of B-spline basis function values at time \(t\) and \(\omega_k^c\) is a vector of corresponding spline coefficients. In general, the number of B-splines \(D\) used for constructing the splines for the study period \(1,\ldots,T\) can be chosen freely, but the actual value is not too important (as long as \(D \leq T\) and larger than the degree of the spline, e.g., three in case of cubic splines) \citep{Wood2020}. Therefore, we use the same \(D\) basis functions for all time-varying effects. To mitigate overfitting due to too large a value of \(D\), we define a random walk prior for \(\omega^c_k\) as
\[
  \omega^c_{k,1} \sim p(\omega^c_{k,1}), \quad
  \omega^c_{k,d} \sim N(\omega^c_{k,d-1}, (\tau^c_k)^2), \quad d=2, \ldots, D.
\]
with a user defined prior \(p(\omega^c_{k,1})\) on the first coefficient, which due to the structure of \(B_1\) corresponds to the prior on the \(\delta^c_{k,1}\). Here, the parameter \(\tau^c_k\) controls the smoothness of the spline curves. While the different time-varying coefficients are modeled as independent a~priori, the latent factors \(\psi\) can be modeled as correlated via correlated spline coefficients \(\omega\).

\section[The dynamite package]{The \pkg{dynamite} package}\label{sec:dynamitepackage}

The \code{dynamite} package provides an easy-to-use interface for fitting DMPMs in \proglang{R}. As the package is part of rOpenSci (\url{htps://ropensci.org}), it complies with its rigorous software standards and the development version of \pkg{dynamite} can be installed from the \proglang{R}-universe system \url{https://ropensci.org/r-universe/}. The stable version of the package is available from CRAN at \url{https://cran.r-project.org/package=dynamite}. The software is published under the GNU general public license (GPL \(\geq\) 3) and can be obtained in \proglang{R} by running the following commands:
\begin{CodeChunk}
\begin{CodeInput}
R> install.packages("dynamite")
R> library("dynamite")
\end{CodeInput}
\end{CodeChunk}
The package takes advantage of several other well established \proglang{R} packages. Estimation of the models is carried out by \proglang{Stan} for which both \pkg{rstan} and \pkg{cmdstanr} \citep{cmdstanr} interfaces are available. The \pkg{data.table} \citep{datatable} package is used for efficient computation and memory management of predictions and internal data manipulations. For posterior inference and visualization, \pkg{ggplot2} \citep{ggplot2}, and \pkg{posterior} \citep{posterior} packages are leveraged. Leave-one-out (LOO) and leave-future-out (LFO) cross-validation methods are implemented with the help of the \pkg{loo} \citep{loo} package. All of the aforementioned dependencies are available on CRAN with the exception of \pkg{cmdstanr} whose installation is optional and needed only if the user wishes to use the \pkg{CmdStan} backend for \proglang{Stan}.

Several example datasets and corresponding model fit objects are included in \pkg{dynamite} which are also used throughout this paper for illustrative purposes. The script files to generate these datasets and the model fit objects can be found in the package GitHub repository (\url{https://https://github.com/ropensci/dynamite/}) under the \code{data-raw} directory. Table~\ref{tab:dynamite_funs} provides an overview of the available functions and methods of the package. Before presenting the more technical details, we demonstrate the key features of the package and the general workflow by performing an illustrative analysis on a real dataset and on a synthetic dataset.

\begin{table}
  \footnotesize
  \centering
  \begin{tabular}{lll}
    \toprule
    Function & Output & Description \\
    \midrule
    \multicolumn{3}{l}{\emph{Model fitting}} \\[0.15cm]
    \fct{dynamite} & \class{dynamitefit} & Estimates dynamic multivariate panel data models \\
    \midrule
    \multicolumn{3}{l}{\emph{Model formula construction}} \\[0.15cm]
    \fct{dynamiteformula} & \class{dynamiteformula} & Defines a response channel \\
    \fct{obs}             & \class{dynamiteformula} & Defines a response channel (alias) \\
    \fct{aux}             & \class{dynamiteformula} & Defines a deterministic channel \\
    \fct{splines}         & \class{splines}         & Defines P-splines for time-varying coefficients \\
    \fct{random_spec}     & \class{random_spec}     & Defines additional properties of random effects \\
    \fct{lags}            & \class{lags}            & Defines lagged predictors across channels \\
    \fct{lfactor}         & \class{lfactor}         & Defines latent factors \\
    \midrule
    \multicolumn{3}{l}{\proglang{S3} \emph{Methods for} \class{dynamitefit} \emph{objects}} \\[0.15cm]
    \fct{as.data.frame}       & \class{data.frame}  & Extracts posterior samples or summaries \\
    \fct{as.data.table}       & \class{data.table}  & Extracts posterior samples or summaries \\
    \fct{as_draws_df}         & \class{draws_df}    & Extracts posterior samples or summaries \\
    \fct{coef}                & \class{data.frame}  & Extracts posterior samples or summaries \\
    \fct{confint}             & \class{matrix}      & Extracts credible intervals \\
    \fct{fitted}              & \class{data.table}  & Computes fitted values \\
    \fct{formula}             & \class{language}    & Extracts the model formula \\
    \fct{get_code}            & \class{data.frame}  & Extracts the \proglang{Stan} model code \\
    \fct{get_data}            & \class{list}        & Extracts the data used to fit the model \\
    \fct{get_parameter_types} & \class{character}   & Extracts parameter types \\
    \fct{get_parameter_names} & \class{character}   & Extracts parameter names \\
    \fct{get_priors}          & \class{data.frame}  & Extracts the prior distribution definitions\\
    \fct{mcmc_diagnostics}    & \class{dynamitefit} & Computes MCMC diagnostics \\
    \fct{ndraws}              & \class{integer}     & Extracts the number of posterior draws \\
    \fct{nobs}                & \class{integer}     & Extracts the number of observations \\
    \fct{plot}                & \class{ggplot}      & Plots posterior densities and traceplots \\
    \fct{predict}             & \class{data.frame}  & Computes predictions \\
    \fct{print}               & \class{dynamitefit} & Prints information on the model fit \\
    \fct{summary}             & \class{data.frame}  & Prints a summary of the model fit \\
    \fct{update}              & \class{dynamitefit} & Updates the model fit \\
    \midrule
    \multicolumn{3}{l}{\emph{Other model outputs}} \\[0.15cm]
    \fct{lfo}              & \class{lfo}         & Computes LFO cross-validation for the model \\
    \fct{loo}              & \class{loo}         & Computes LOO cross-validation for the model \\
    \fct{plot_betas}       & \class{ggplot}      & Plots posteriors of time-invariant parameters \\
    \fct{plot_deltas}      & \class{ggplot}      & Plots posteriors of time-varying parameters \\
    \fct{plot_lambdas}     & \class{ggplot}      & Plots posteriors of latent factor loadings\\
    \fct{plot_nus}         & \class{ggplot}      & Plots posteriors of random effects\\
    \fct{plot_psis}        & \class{ggplot}      & Plots posteriors of latent factors\\
    \bottomrule
  \end{tabular}
  \caption{Functionality of \pkg{dynamite}.}
  \label{tab:dynamite_funs}
\end{table}

\subsection{Bayesian inference of seat belt usage and traffic fatalities}\label{sec:seatbelt}

As the first illustration, we consider the effect of seat belt laws on traffic fatalities using data from the \pkg{pder} \citep{pder} package, originally analyzed in \citep{Cohen2003}. The data consists of the number of traffic fatalities and other related variables in the United States from all 51 states for every year from 1983 to 1997. During this time, many states passed laws regarding mandatory seat belt use. We distinguish two types of laws: secondary enforcement law and primary enforcement law. Secondary enforcement means that the police can fine violators only when they are stopped for other offences, whereas in primary enforcement the police can also stop and fine based on the seat belt use violation itself. This dataset is named \code{SeatBelt} and it can be loaded into the current \proglang{R} session by running:
\begin{CodeChunk}
\begin{CodeInput}
R> data("SeatBelt", package = "pder")
\end{CodeInput}
\end{CodeChunk}
To begin, we rename some variables and compute additional transformations to make the subsequent analyses straight-forward.
\begin{CodeChunk}
\begin{CodeInput}
R> library("dplyr")
R> seatbelt <- SeatBelt |>
+    mutate(
+      miles = (vmturban + vmtrural) / 10000,
+      log_miles = log(miles),
+      fatalities = farsocc,
+      income10000 = percapin / 10000,
+      law = factor(
+        case_when(
+          dp == 1 ~ "primary",
+          dsp == 1 ~ "primary",
+          ds == 1 & dsp == 0 ~ "secondary",
+          TRUE ~ "no_law"
+        ),
+        levels = c("no_law", "secondary", "primary")
+      )
+    )
\end{CodeInput}
\end{CodeChunk}
We are interested in the effect of the seat belt law on traffic fatalities in terms of car occupants via the changes in seat belt usage. For this purpose, we build a joint model for the seat belt usage and the fatalities. We model the rate of seat belt usage with a Beta distribution (with logit-link) and assume that the usage depends on the level of the seat belt law, state-level effects (modeled as random intercepts) and overall time-varying trend (modeled as a spline), which captures potential changes in the general tendency to use a seat belt in the US. We model the number of fatalities with a negative binomial distribution (with log-link) using the total miles traveled as an offset. In addition to the seat belt usage and state level random intercepts, we also use several other variables related to traffic density, speed limit, alcohol usage, and income (see the \code{pder::SeatBelt} for details) as controls. We construct the model formula and fit the model as follows:
\begin{CodeChunk}
\begin{CodeInput}
R> seatbelt_formula <-
+    obs(usage ~ -1 + law + random(~1) + varying(~1), family = "beta") +
+    obs(fatalities ~ usage + densurb + densrur +
+        bac08 + mlda21 + lim65 + lim70p + income10000 + unemp + fueltax +
+        random(~1) + offset(log_miles), family = "negbin") +
+    splines(df = 10)
R> fit <- dynamite(
+    dformula = seatbelt_formula,
+    data = seatbelt, time = "year", group = "state",
+    chains = 4, cores = 4, refresh = 0)
\end{CodeInput}
\end{CodeChunk}
We can extract the estimated coefficients with \fct{summary} method which shows clear positive effects for both secondary enforcement and primary enforcement laws:
\begin{CodeChunk}
\begin{CodeOutput}
# A tibble: 2 x 5
  parameter                mean     sd    q5   q95
  <chr>                   <dbl>  <dbl> <dbl> <dbl>
1 beta_usage_lawsecondary 0.495 0.0475 0.417 0.573
2 beta_usage_lawprimary   1.06  0.0844 0.922 1.19
\end{CodeOutput}
\end{CodeChunk}
While these coefficients can be interpreted as changes in log-odds as usual, we can also estimate the marginal means using the \fct{fitted} method which returns the posterior samples of the expected values of the responses at each time point given the predictors. For this purpose, we create a new data frame where we switch the values of the \code{law} variable to different levels, call \fct{fitted} using these data, compute the averages of over the states and finally over the posterior samples:
\begin{CodeChunk}
\begin{CodeInput}
R> seatbelt_new <- seatbelt
R> seatbelt_new$law[] <- "no_law"
R> pnl <- fitted(fit, newdata = seatbelt_new)
R> seatbelt_new$law[] <- "secondary"
R> psl <- fitted(fit, newdata = seatbelt_new)
R> seatbelt_new$law[] <- "primary"
R> ppl <- fitted(fit, newdata = seatbelt_new)
R> bind_rows(no_law = pnl, secondary = psl, primary = ppl, .id = "law") |>
+    mutate(
+      law = factor(law, levels = c("no_law", "secondary", "primary"))
+    ) |>
+    group_by(law, .draw) |>
+    summarise(mm = mean(usage_fitted)) |>
+    group_by(law) |>
+    summarise(
+      mean = mean(mm),
+      q5 = quantile(mm, 0.05),
+      q95 = quantile(mm, 0.95)
+    )
\end{CodeInput}
\begin{CodeOutput}
# A tibble: 3 x 4
  law        mean    q5   q95
  <fct>     <dbl> <dbl> <dbl>
1 no_law    0.359 0.346 0.373
2 secondary 0.467 0.459 0.477
3 primary   0.592 0.568 0.615
\end{CodeOutput}
\end{CodeChunk}
These estimates are in line with the results of \citet{Cohen2003} who report the law effects on usage as increases of 11 and 22 percentage points for secondary enforcement and primary enforcement laws, respectively.

For the effect of seat belt laws on the number of traffic fatalities, we compare the number of fatalities with 68\% seat belt usage against 90\% usage. These values, coinciding with the national average in 1996 and the target of 2005, were also used by \citet{Cohen2003} who reported an increase in annual lives saved as 1500--3000. We do this by comparing the differences in total fatalities across states for each year, and average over years, again with the help of the \fct{fitted} method;
\begin{CodeChunk}
\begin{CodeInput}
R> seatbelt_new <- seatbelt
R> seatbelt_new$usage[] <- 0.68
R> p68 <- fitted(fit, newdata = seatbelt_new)
R> seatbelt_new$usage[] <- 0.90
R> p90 <- fitted(fit, newdata = seatbelt_new)
R>
R> bind_rows(low = p68, high = p90, .id = "usage") |>
+    group_by(year, .draw) |>
+    summarise(s = sum(
+      fatalities_fitted[usage == "low"] -
+        fatalities_fitted[usage == "high"])
+    ) |>
+    group_by(.draw) |>
+    summarise(m = mean(s)) |>
+    summarise(
+      mean = mean(m),
+      q5 = quantile(m, 0.05),
+      q95 = quantile(m, 0.95)
+    )
\end{CodeInput}
\begin{CodeOutput}
# A tibble: 1 x 3
   mean    q5   q95
  <dbl> <dbl> <dbl>
1 1555.  736. 2317.
\end{CodeOutput}
\end{CodeChunk}
In this example, the model did not contain any lagged responses as predictors, so it was enough to compute predictions for each time point essentially independently using the \fct{fitted} method. However, when the responses depend on the past values of themselves or of other channels, as is the case for example in cross-lagged panel models, estimating long-term effects such as \(\E(y_{t+k} | do(y_t)), k = 1,\ldots\), where \(do(y_t)\) denotes an intervention on \(y_t\) \citep{Pearl2009}, is more complicated. We illustrate this in our next example.

\subsection{Causal effects in a multichannel model}\label{sec:multichannel}

We now consider the following simulated multichannel data available in the \pkg{dynamite} package:
\begin{CodeChunk}
\begin{CodeInput}
R> head(multichannel_example)
\end{CodeInput}
\begin{CodeOutput}
  id time          g  p b
1  1    1 -0.6264538  5 1
2  1    2 -0.2660091 12 0
3  1    3  0.4634939  9 1
4  1    4  1.0451444 15 1
5  1    5  1.7131026 10 1
6  1    6  2.1382398  8 1
\end{CodeOutput}
\end{CodeChunk}
The data contains 50 unique groups (variable \code{id}), over 20 time points (\code{time}), a continuous variable \(g_t\) (\code{g}), a variable with non-negative integer
values \(p_t\) (\code{p}), and a binary variable \(b_t\) (\code{b}). We define the following model (which actually matches the data generating process used in generating the data):
\begin{CodeChunk}
\begin{CodeInput}
R> multi_formula <- obs(g ~ lag(g) + lag(logp), family = "gaussian") +
+    obs(p ~ lag(g) + lag(logp) + lag(b), family = "poisson") +
+    obs(b ~ lag(b) * lag(logp) + lag(b) * lag(g), family = "bernoulli") +
+    aux(numeric(logp) ~ log(p + 1))
\end{CodeInput}
\end{CodeChunk}
Here, the \fct{aux} creates a deterministic transformation of \(p_t\) as \(\log(p_t + 1)\) which can subsequently be used in other channels as a predictor and correctly computes the transformation for predictions. A directed acyclic graph (DAG) that depicts the model is shown in Figure~\ref{fig:multichannel_dag}. We fit the model using the \code{dynamite()} function.
\begin{figure}
  \begin{center}
     \begin{tikzpicture}[thick, scale=0.6]

     \node (gpast) at (-10, 3) {\(\cdots\)};
     \node (ppast) at (-10, 0) {\(\cdots\)};
     \node (bpast) at (-10,-3) {\(\cdots\)};

     \node [obs = {g_t}{g_t}] at (-6, 3) {\(\vphantom{0}\)};
     \node [obs = {p_t}{p_t}] at (-6, 0) {\(\vphantom{0}\)};
     \node [obs = {b_t}{b_t}] at (-6,-3) {\(\vphantom{0}\)};

     \node [obs = {g_{t+1}}{g_{t+1}}] at (-2, 3) {\(\vphantom{0}\)};
     \node [obs = {p_{t+1}}{p_{t+1}}] at (-2, 0) {\(\vphantom{0}\)};
     \node [obs = {b_{t+1}}{b_{t+1}}] at (-2,-3) {\(\vphantom{0}\)};

     \node [obs = {g_{t+2}}{g_{t+2}}] at (2, 3) {\(\vphantom{0}\)};
     \node [obs = {p_{t+2}}{p_{t+2}}] at (2, 0) {\(\vphantom{0}\)};
     \node [obs = {b_{t+2}}{b_{t+2}}] at (2,-3) {\(\vphantom{0}\)};

     \node (gfuture) at (6, 3) {$\cdots$};
     \node (pfuture) at (6, 0) {$\cdots$};
     \node (bfuture) at (6,-3) {$\cdots$};

     \path [->] (gpast) edge (g_t);
     \path [->] (gpast) edge (p_t);
     \path [->] (gpast) edge (b_t);
     \path [->] (ppast) edge (g_t);
     \path [->] (ppast) edge (p_t);
     \path [->] (ppast) edge (b_t);

     \path [->] (bpast) edge (p_t);
     \path [->] (bpast) edge (b_t);

     \path [->] (g_t) edge (g_{t+1});
     \path [->] (g_t) edge (p_{t+1});
     \path [->] (g_t) edge (b_{t+1});
     \path [->] (p_t) edge (g_{t+1});
     \path [->] (p_t) edge (p_{t+1});
     \path [->] (p_t) edge (b_{t+1});

     \path [->] (b_t) edge (p_{t+1});
     \path [->] (b_t) edge (b_{t+1});

     \path [->] (g_{t+1}) edge (g_{t+2});
     \path [->] (g_{t+1}) edge (p_{t+2});
     \path [->] (g_{t+1}) edge (b_{t+2});
     \path [->] (p_{t+1}) edge (g_{t+2});
     \path [->] (p_{t+1}) edge (p_{t+2});
     \path [->] (p_{t+1}) edge (b_{t+2});

     \path [->] (b_{t+1}) edge (p_{t+2});
     \path [->] (b_{t+1}) edge (b_{t+2});

     \path [->] (g_{t+2}) edge (gfuture);
     \path [->] (g_{t+2}) edge (pfuture);
     \path [->] (g_{t+2}) edge (bfuture);
     \path [->] (p_{t+2}) edge (gfuture);
     \path [->] (p_{t+2}) edge (pfuture);
     \path [->] (p_{t+2}) edge (bfuture);

     \path [->] (b_{t+2}) edge (pfuture);
     \path [->] (b_{t+2}) edge (bfuture);
     \end{tikzpicture}
  \end{center}
  \caption{A directed acyclic graph for the multichannel model with arrows corresponding to the assumed direct causal effects. A cross-section at times \(t\), \(t+1\), and \(t+2\) is shown. The nodes corresponding to the deterministic tranformation \(\log(p_t)\) are omitted for clarity.}
  \label{fig:multichannel_dag}
\end{figure}
\begin{CodeChunk}
\begin{CodeInput}
R> multichannel_fit <- dynamite(
+    dformula = multi_formula,
+    data = multichannel_example, time = "time", group = "id",
+    chains = 4, cores = 4, refresh = 0
+  )
\end{CodeInput}
\begin{CodeOutput}
Warning: Deterministic channel `logp` has a maximum lag of 1 but you've
supplied no initial values:
i This may result in NA values for `logp`.
\end{CodeOutput}
\end{CodeChunk}
Note that the \fct{dynamite} call above produces a warning message related to the deterministic channel \code{logp}. This happens because the formulas of the other channels have \code{lag(logp)} as a predictor, whose value is undefined at the first time point without the initial value. However, in this case we can safely ignore the warning because the model contains lags of \code{b} and \code{g} as well meaning that the first time point in the model is treated as fixed and does not enter the model fitting process.

We can obtain posterior samples or summary statistics of the model using the \fct{as.data.frame}, \fct{coef}, and \fct{summary} methods, but here we opt for visualizing the results as depicted in Figure~\ref{fig:multichannel_betas} by using the \code{plot_betas} function:
\begin{CodeChunk}
\begin{CodeInput}
R> library("ggplot2")
R> theme_set(theme_bw())
R> plot_betas(multichannel_fit) + labs(title = "")
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{multichannel_betas-1} \caption[Posterior means and 90\% intervals of the time-invariant coefficients for the multichannel model]{Posterior means and 90\% intervals of the time-invariant coefficients for the multichannel model.}\label{fig:multichannel_betas}
\end{figure}
\end{CodeChunk}
Note the naming of the model parameters; for example, \code{beta_b_g_lag1} corresponds to a time-invariant coefficient \code{beta} of the lagged predictor \code{g} of the channel \code{b}.

Assume now that we are interested in the causal effect of \(b_5\) on \(g_t\) at times \(t = 6, \ldots, 20\). There is no direct effect from \(b_5\) to \(g_6\), but because \(g_t\) affects \(b_{t+1}\) (and \(p_{t+1}\)), which in turn has an effect on all the variables at \(t+2\), we should see an indirect effect of \(b_5\) to \(g_t\) from time \(t = 7\) onward. For this task, we first create a new dataset where the values of our response variables after time \(t = 5\) are assigned to be missing:
\begin{CodeChunk}
\begin{CodeInput}
R> multichannel_newdata <- multichannel_example |>
+    mutate(across(g:b, ~ ifelse(time > 5, NA, .x)))
\end{CodeInput}
\end{CodeChunk}
We then obtain predictions for time points \(t = 6,\ldots,20\) when \(b_t\) is assigned to be 0 or 1 for every individual at time \(t = 5\):
\begin{CodeChunk}
\begin{CodeInput}
R> new0 <- multichannel_newdata |> mutate(b = ifelse(time == 5, 0, b))
R> pred0 <- predict(multichannel_fit, newdata = new0, type = "mean")
R> new1 <- multichannel_newdata |> mutate(b = ifelse(time == 5, 1, b))
R> pred1 <- predict(multichannel_fit, newdata = new1, type = "mean")
\end{CodeInput}
\end{CodeChunk}
By default, the output from \fct{predict} is a single data frame containing the original new data and the samples from the posterior predictive distribution of new observations. By defining \code{type = "mean"} we specify that we are interested in the posterior distribution of the expected values instead. In this case the the predicted values in a data frame are in the columns \code{g_mean}, \code{p_mean}, and \code{b_mean} where the \code{NA} values of the \code{newdata} argument are replaced with the posterior samples from the model (the output also contains an additional column corresponding to the auxiliary channel \code{logp} and posterior draw index variable \code{.draw}).
\begin{CodeChunk}
\begin{CodeInput}
R> head(pred0, n = 10) |> round(3)
\end{CodeInput}
\begin{CodeOutput}
   g_mean p_mean b_mean  logp id time .draw      g  p  b
1      NA     NA     NA 1.792  1    1     1 -0.626  5  1
2      NA     NA     NA 2.565  1    2     1 -0.266 12  0
3      NA     NA     NA 2.303  1    3     1  0.463  9  1
4      NA     NA     NA 2.773  1    4     1  1.045 15  1
5      NA     NA     NA 2.398  1    5     1  1.713 10  0
6   1.844  3.474  0.718 1.386  1    6     1     NA NA NA
7   1.972  4.175  0.813 1.792  1    7     1     NA NA NA
8   2.126  5.427  0.814 1.792  1    8     1     NA NA NA
9   2.042  5.607  0.799 2.079  1    9     1     NA NA NA
10  2.066  6.982  0.785 2.079  1   10     1     NA NA NA
\end{CodeOutput}
\end{CodeChunk}
We can now compute summary statistics over the individuals and then over the posterior samples to obtain posterior distribution of the causal effects \(\E(g_t | do(b_5))\) as
\begin{CodeChunk}
\begin{CodeInput}
R> sumr <- bind_rows(list(b0 = pred0, b1 = pred1), .id = "case") |>
+    group_by(case, .draw, time) |>
+    summarise(mean_t = mean(g_mean)) |>
+    group_by(case, time) |>
+    summarise(
+      mean = mean(mean_t),
+      q5 = quantile(mean_t, 0.05, na.rm = TRUE),
+      q95 = quantile(mean_t, 0.95, na.rm = TRUE)
+    )
\end{CodeInput}
\end{CodeChunk}
It is also possible to perform the marginalization over groups within \fct{predict} by using the argument \code{funs}, which can be used to provide a named list of lists which contains functions to be applied for the corresponding channel. This approach can save considerably amount of memory in case of large number of groups. The names of the outermost list should be channel names. The output is now returned as a \class{list} with two components, \code{simulated} and \code{observed}, with the new samples and the original \code{newdata} respectively. In our case we can write
\begin{CodeChunk}
\begin{CodeInput}
R> pred0b <- predict(
+    multichannel_fit, newdata = new0, type = "mean",
+    funs = list(g = list(mean_t = mean))
+  )$simulated
R> pred1b <- predict(
+    multichannel_fit, newdata = new1, type = "mean",
+    funs = list(g = list(mean_t = mean))
+  )$simulated
R> sumrb <- bind_rows(
+    list(b0 = pred0b, b1 = pred1b), .id = "case") |>
+    group_by(case, time) |>
+    summarise(
+      mean = mean(mean_t_g),
+      q5 = quantile(mean_t_g, 0.05, na.rm = TRUE),
+      q95 = quantile(mean_t_g, 0.95, na.rm = TRUE)
+    )
\end{CodeInput}
\end{CodeChunk}
The resulting data frame \code{sumrb} is equal to the previous \code{sumr} (apart from stochasticity due to simulation of new trajectories). We can the visualize our predictions as shown in Figure~\ref{fig:multichannelvisual} by writing:
\begin{CodeChunk}
\begin{CodeInput}
R> ggplot(sumr, aes(time, mean)) +
+    geom_ribbon(aes(ymin = q5, ymax = q95), alpha = 0.5) +
+    geom_line() +
+    scale_x_continuous(n.breaks = 10) +
+    facet_wrap(~ case)
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{multichannelvisual-1} \caption[Expected causal effects of interventions \(do(b_5 = 0)\) and \(do(b_5 = 1)\) on \(g_t\)]{Expected causal effects of interventions \(do(b_5 = 0)\) and \(do(b_5 = 1)\) on \(g_t\).}\label{fig:multichannelvisual}
\end{figure}
\end{CodeChunk}
Note that these estimates do indeed coincide with the causal effects (assuming of course that our model is correct), as we can find the backdoor adjustment formula \citep{Pearl1995}
\[
  \E(g_t | do(b_5 = x)) = \sum_{g_5, p_5}\E(g_t | b_5 = x, g_5, p_5)\Prob(g_5, p_5),
\]
which is equal to \code{mean_t} in above codes. We can also compute the difference \(\E(g_t | do(b_5 = 1)) - \E(g_t | do(b_5 = 0))\) to directly compare the effects of the interventions by writing:
\begin{CodeChunk}
\begin{CodeInput}
R> sumr_diff <- bind_rows(list(b0 = pred0, b1 = pred1), .id = "case") |>
+    group_by(.draw, time) |>
+    summarise(
+      mean_t = mean(g_mean[case == "b1"] - g_mean[case == "b0"])
+    ) |>
+    group_by(time) |>
+    summarise(
+      mean = mean(mean_t),
+      q5 = quantile(mean_t, 0.05, na.rm = TRUE),
+      q95 = quantile(mean_t, 0.95, na.rm = TRUE)
+    )
\end{CodeInput}
\end{CodeChunk}
We can also plot the difference in the expected causal effects as shown in Figure~\ref{fig:multichannelcausaldiffplot} by running:
\begin{CodeChunk}
\begin{CodeInput}
R> ggplot(sumr_diff, aes(time, mean)) +
+    geom_ribbon(aes(ymin = q5, ymax = q95), alpha = 0.5) +
+    geom_line() +
+    scale_x_continuous(n.breaks = 10)
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{multichannelcausaldiffplot-1} \caption[Difference of the expected causal effects \(\E(g_t | do(b_5 = 1)) - \E(g_t | do(b_5 = 0)) \)]{Difference of the expected causal effects \(\E(g_t | do(b_5 = 1)) - \E(g_t | do(b_5 = 0)) \).}\label{fig:multichannelcausaldiffplot}
\end{figure}
\end{CodeChunk}
Which shows that there is a short term effect of \(b\) on \(g\), although the posterior uncertainty is quite large.

\section{Model construction}\label{sec:construction}

Here we describe the various model components that be included in the model formulas of the package. These components are modular and easily combined in any order via a specialized \code{+} operator, which also ensures that the model formula is well-defined and syntactically valid before estimating the model. The model formula components define the response channels, auxiliary channels, the splines used for time-varying coefficients, correlated random effects, and latent factors.

\subsection{Defining response channels}\label{sec:defining}

The response channels are defined by combining the channel-specific formulas defined via the function \fct{dynamiteformula} for which a shorthand alias \fct{obs} is also provided. The function \fct{obs} takes two arguments: \code{formula} and \code{family}, which define how the response variable of the channel depends on the predictor variables in the standard \proglang{R} formula syntax and the family of the response variable as a \code{`character'} string, respectively. These channel-specific definitions are then combined into a single model with the \code{+} operator. For example, the following formula
\begin{CodeChunk}
\begin{CodeInput}
R> dform <- obs(y ~ lag(x), family = "gaussian") +
+    obs(x ~ z, family = "poisson")
\end{CodeInput}
\end{CodeChunk}
defines a model with two channels. First, we declare that \code{y} is a gaussian variable depending on the previous value of \code{x} (\code{lag(x)}) and then we add a second channel declaring \code{x} as Poisson distributed depending on some exogenous variable \code{z} (for which we do not define any distribution). Note that the model formula can be defined without any reference to some external data, just as an \proglang{R} formula can. The model formula is an object of class \class{dynamiteformula} for which the \fct{print} method is available which provides a summary of the defined channels and other model components:
\begin{CodeChunk}
\begin{CodeInput}
R> print(dform)
\end{CodeInput}
\begin{CodeOutput}
  Family   Formula
y gaussian y ~ lag(x)
x poisson  x ~ z
\end{CodeOutput}
\end{CodeChunk}
Currently, the package supports the following distributions for the observations:

\begin{description}
\item[Categorical] (\code{"categorical"}) with a softmax link using the first category as the reference. It is recommended to use \proglang{Stan} version~2.23 or higher which enables the use of the  \code{categorical_logit_glm} function in the generated \proglang{Stan} code for improved computational performance. See the documentation of \code{categorical_logit_glm} in the \proglang{Stan} function reference manual \url{https://mc-stan.org/users/documentation/} for further information.
\item[Gaussian] (\code{"gaussian"}) identity link, parameterized using mean and standard deviation.
\item[Poisson] (\code{"poisson"}) log-link, with an optional known offset variable.
\item[Negative-binomial] (\code{"negbin"}) log-link, using mean and dispersion parameterization, with an optional known offset variable. See the documentation on the \code{NegBinomial2} function in the \proglang{Stan} function reference manual.
\item[Bernoulli] (\code{"bernoulli"}) logit-link.
\item[Binomial] (\code{"binomial"}) logit-link.
\item[Exponential] (\code{"exponential"}) log-link.
\item[Gamma] (\code{"gamma"}) log-link, using mean and shape parameterization.
\item[Beta] (\code{"beta"}) logit-link, using mean and precision parameterization.
\end{description}

There is also a special response variable type \code{"deterministic"} which can be used to define deterministic transformations of other variables in the model. This special type is explained in greater detail in Section~\ref{sec:auxiliary}.

\subsection{Lagged responses and predictors}\label{sec:lags}

Models in the \pkg{dynamite} package have limited support for contemporaneous dependencies in order to avoid complex cyclic dependencies which would make handling missing data, subsequent predictions, and causal inference challenging or impossible. In other words, the model structure must be acyclic, meaning that there is an order of the response variables such that each response at time \(t\) can be unambiguously defined in this order in terms of responses that have already been defined at time \(t\) or in terms of other variables in the model at time \(t-1\). The acyclicity of model formulas defined by the user is checked automatically upon construction. To demonstrate, the following formula is valid:
\begin{Code}
obs(y ~ x, family = "gaussian") +
  obs(x ~ z, family = "poisson")
\end{Code}
but the following is not and produces an error due to a cyclic dependency between the responses:
\begin{CodeChunk}
\begin{CodeInput}
R> obs(y ~ x, family = "gaussian") +
+    obs(x ~ z, family = "poisson") +
+    obs(z ~ y, family = "categorical")
\end{CodeInput}
\begin{CodeOutput}
Error in `join_dynamiteformulas()` at dynamite/R/dynamiteformula.R:476:4:
! Cyclic dependency found in model formula.
\end{CodeOutput}
\end{CodeChunk}
On the other hand, there are no limitations concerning dependence of response variables and their previous values or previous values of exogenous predictors, i.e., lags. In the first example of Section~\ref{sec:defining} we used the syntax \code{lag(x)}, a shorthand for \code{lag(x, k = 1)}, which defines a one-step lag of the variable \code{x}. Higher order lags can also be defined by adjusting the argument \code{k}. The argument \code{x} of \fct{lag} can either be a response variable or an exogenous predictor.

The model component \fct{lags} can also be used to quickly add lagged responses as predictors across multiple channels. This component adds a lagged value of each response in the model as a predictor to every channel. For example, calling
\begin{Code}
obs(y ~ z, family = "gaussian") +
  obs(x ~ z, family = "poisson") +
  lags(k = 1)
\end{Code}
would add \code{lag(y, k = 1)} and \code{lag(x, k = 1)} as predictors of \code{x} and \code{y}. Therefore, the previous code would produce the same model as writing
\begin{Code}
obs(y ~ z + lag(y, k = 1) + lag(x, k = 1), family = "gaussian") +
  obs(x ~ z + lag(y, k = 1) + lag(x, k = 1), family = "poisson")
\end{Code}
The function \fct{lags} can help to simplify the individual model formulas, especially in the case where the model consists of many channels each containing a large number of lags. Just as with the function \fct{lag}, the argument \code{k} in \fct{lags} can be adjusted to add higher order lags of each response to each channel, but for \fct{lags} it can also be a vector so that multiple lags can be added at once. The inclusion of lagged response variables in the model implies that some time points have to be considered fixed in the estimation. The number of fixed time points in the model is equal to the largest shift value \(k\) of any observed response variable in the model (defined either via \fct{lag} terms or the model component \fct{lags}).

\subsection{Time-varying and time-invariant predictors}

The \code{formula} argument of \fct{obs} can also contain an additional special term \fct{varying}, which defines the time-varying part of the model equation. For example, we could write
\begin{Code}
obs(x ~ z + varying(~ -1 + w), family = "poisson")
\end{Code}
to define a model equation with a constant intercept, a time-invariant effect of \code{z}, and a time-varying effect of \code{w}. We also remove the duplicate intercept with \code{-1} within \fct{varying} in order to avoid identifiability issues in the model estimation. We could also define a time-varying intercept, in which case we would write:
\begin{Code}
obs(x ~ -1 + z + varying(~ w), family = "poisson")
\end{Code}
The part of the formula not wrapped with \fct{varying} is assumed to correspond to the time-invariant part of the model, which can alternatively be defined with the special syntax \fct{fixed}. This means that the following lines would all produce the same model:
\begin{Code}
obs(x ~ z + varying(~ -1 + w), family = "poisson")
obs(x ~ -1 + fixed(~ z) + varying(~ -1 + w), family = "poisson")
obs(x ~ fixed(~ z) + varying(~ -1 + w), family = "poisson")
\end{Code}
The use of \fct{fixed} is therefore optional in the formula. If both time-varying and time-invariant intercepts are defined, the model will default to using a time-varying intercept and provides an appropriate warning for the user:
\begin{CodeChunk}
\begin{CodeInput}
R> dform_warn <- obs(y ~ 1 + varying(~1), family = "gaussian")
\end{CodeInput}
\begin{CodeOutput}
Warning: Both time-independent and time-varying intercept specified:
i Defaulting to time-varying intercept.
\end{CodeOutput}
\end{CodeChunk}
When defining time-varying effects, we also need to define how their respective regression coefficient behave. For this purpose, a \fct{splines} component should be added to the model formula, e.g.,
\begin{Code}
obs(x ~ varying(~ -1 + w), family = "poisson") +
  splines(df = 10)
\end{Code}
defines a cubic B-spline with 10 degrees of freedom for the time-varying coefficients, which corresponds to the variable \code{w} in this instance. If the model contains multiple time-varying coefficients, the same spline basis is used for all coefficients, with unique spline coefficients and their corresponding random-walk standard deviations. The \fct{splines} component constructs the matrix of cardinal B-splines \(B_t\) using the \fct{bs} function of the \pkg{splines} package based on the degrees of freedom \code{df} and spline degree \code{degree} (default being 3 corresponding to cubic B-splines). It is also possible to switch between centered (the default) and non-centered parameterization \citep{Papaspiliopoulos2007} for the spline coefficients using the \code{noncentered} argument of the \fct{splines} component. This can affect the sampling efficiency of \proglang{Stan}, depending on the model and the informativeness of data \citep{Betancourt2013}.

\subsection{Group-level random effects}

Random effect terms for each group can be defined using the special term \fct{random} within the \code{formula} argument of \fct{obs}, analogously to \fct{varying}. By default, all random effects within a group and across all channels are modeled as zero-mean multivariate normal. The optional model component \fct{random_spec} can be used to define non-correlated random effects as \code{random_spec(correlated = FALSE)}. In addition, as with the spline coefficients, it is possible to switch between centered and non-centered (the default) parameterization of the random effects using the \code{noncentered} argument of \fct{random_spec}. The random effects are not yet supported for categorical distribution due to technical reasons.

For example, the following code defines a Gaussian response variable \code{x} with a time-invariant common effect of \code{z} as well as a group-specific intercept and group-specific effect of \code{z}.
\begin{Code}
obs(x ~ z + random(~1 + z), family = "gaussian")
\end{Code}
The variable that defines the groups in the data is provided in the call to the model fitting function \fct{dynamite} as shown in Section~\ref{sec:fitting}.

\subsection{Latent factors}

Instead of common time-varying intercept terms, it is possible to define channel-specific univariate latent factors using the \fct{lfactor} model component. Each latent factor is modeled as a spline, with degrees of freedom and spline degree defined via the \fct{splines} component (in the case that the model also contains time-varying effects, the same spline basis definition is currently used for both latent factors and time-varying effects). The argument \code{responses} of \fct{lfactor} defines which channels should contain a latent factor, while argument \code{correlated} determines whether the latent factors should modeled as correlated. Again, users can switch between centered and non-centered parameterizations using the arguments \code{noncentered_lambda} and \code{noncentered_psi}.

In general, dynamic latent factors are not identifiable without imposing some constraints on the factor loadings \(\lambda\) or the latent factor \(\psi\) \citep[see, e.g.,][]{Bai2015}, especially in the context of DMPMs and \pkg{dynamite}. In \pkg{dynamite} these identifiability problems are addressed via internal reparameterization and an additional argument \code{nonzero_lambda} which determines whether we assume that the expected value of the factor loadings is zero or not. The theory and thorough experiments regarding the robustness of these identifiability constraints is a work in progress, so some caution should be used regarding the use of the \fct{lfactor} component.

\subsection{Auxiliary channels}\label{sec:auxiliary}

In addition to declaring response variables via \fct{obs}, we can also use the function \fct{aux} to define auxiliary channels which are deterministic functions of other variables in the model. Defining these auxiliary variables explicitly instead of defining them implicitly on the right-hand side of the formulas (i.e., by using the ``as is'' function \fct{I}) makes the subsequent prediction steps more clear and allows easier checks on the model validity. In fact, we do not allow the use of \fct{I} in the \code{formula} argument of \fct{dynamiteformula}. The values of auxiliary variables are computed automatically when fitting the model, and dynamically during prediction, making the use of lagged values and other transformations possible in prediction as well. An example of a model formula using an auxiliary channel could be
\begin{Code}
obs(y ~ lag(log1x), family = "gaussian") +
  obs(x ~ z, family = "poisson") +
  aux(numeric(log1x) ~ log(1 + x) | init(0))
\end{Code}
For auxiliary channels, the formula declaration via \code{~} should be understood as a mathematical equality, where the right-hand side provides the defining expression of the variable on the left-hand side. Thus, the example above defines a new auxiliary channel whose response is \code{log1x} defined as the logarithm of \code{1 + x} and assigns it to be of type \class{numeric}. The type declaration is required, because it might not be possible to unambiguously determine the type of the response variable based on its expression alone from the data, especially if the expression contains \class{factor} type variables.

Auxiliary variables can be used directly in the formulas of other channels, just like any other variable. The function \fct{aux} does not use the \code{family} argument, which is automatically set to \code{"deterministic"} and is a special channel type of the \fct{obs} function. Note that lagged values of deterministic auxiliary channels do not imply fixed time points. Instead, they must be given starting values using one of the two special syntax variants, \fct{init} or \fct{past} after the main formula separated by the \code{|} symbol.

In the example above, because the channel for \code{y} contains a lagged value of \code{log1x} as a predictor, we also need to supply \code{log1x} with a single initial value that determines the value of the lag at the first time point. Here, \code{init(0)} defines the initial value of \code{lag(log1x)} to be zero for all individuals. In general, if the model contains higher order lags of an auxiliary channel, then \fct{init} can be supplied with a vector initializing each lag.

While \fct{init} defines the same starting value to be used for all individuals, an alternative, special syntax \fct{past} can be used, which takes an \proglang{R} expression as its argument, and computes the starting value for each individual based on that expression. The expression is evaluated in the context of the \code{data} supplied to the model fitting function \fct{dynamite}. For example, instead of \code{init(0)} in the example above, we could write:
\begin{Code}
obs(y ~ lag(log1x), family = "gaussian") +
  obs(x ~ z, family = "poisson") +
  aux(numeric(log1x) ~ log(1 + x) | past(log(z)))
\end{Code}
which defines that the value of \code{lag(log1x)} at the first time point is \code{log(z)} for each individual, using the value of \code{z} in the data to be supplied to compute the actual value of the expression. The special syntax \fct{past} can also be used if the model contains higher order lags of auxiliary responses. In this case, more observations from the variables bound by the expression given as the argument will simply be used.

\section{Model fitting and posterior inference}\label{sec:fitting}

To estimate the model, the declared model formula is supplied to the \fct{dynamite} function, which has the following arguments:
\begin{Code}
dynamite(
  dformula, data, time, group = NULL,
  priors = NULL, backend = "rstan",
  verbose = TRUE, verbose_stan = FALSE, debug = NULL, ...
)
\end{Code}

This function parses the model formula and the data to generate a custom \proglang{Stan} model code, which is then compiled and used to simulate the posterior distribution of the model parameters. The first three arguments of the function are mandatory. The first argument \code{dformula} is a \class{dynamiteformula} object that defines the model using the model components described in Section~\ref{sec:construction}. The second argument \code{data} is a \class{data.frame} or a \class{data.table} object that contains the variables used in the model formula. The third argument \code{time} is a column name of \code{data} that specifies the unique time points.

The remaining arguments of the function are optional. The \code{group} argument is a column name of \code{data} that specifies the unique groups (individuals), and when \code{group = NULL} we assume that there is only a single group (or individual). The argument \code{priors} supplies user-defined priors for the model parameters. The \proglang{Stan} backend can be selected using the \code{backend} argument, which accepts either \code{"rstan"} (the default) or \code{"cmdstanr"}. These options correspond to using the \pkg{rstan} and \pkg{cmdstanr} packages for the estimation, respectively. The \code{verbose} and \code{verbose_stan} arguments control the verbosity of the output from \fct{dynamite} and \proglang{Stan}, respectively. The \code{debug} argument can be used for various debugging options (see \code{?dynamite} for further information on these parameters). Finally, \code{...} supplies additional arguments to the backend sampling function (either \code{rstan::sampling()} or the \fct{sample} method of the \code{CmdStanModel} model object).

The \code{data} argument should be supplied in long format, i.e., with \(N \times T\) rows in case of balanced panel data. Acceptable column types of \code{data} are \class{integer}, \class{logical}, \class{double}, \class{character}, and objects of class \class{factor}. Columns of the \class{character} type will be converted to \class{factor} columns. Beyond these standard types, any special classes such as \class{Date} whose internal storage type is one of aforementioned types can be used, but these classes will be dropped, and the columns will be converted to their respective storage types. List columns are not supported. The \code{time} argument should be a \class{numeric} or a \class{factor} column of \code{data}. If \code{time} is a \class{factor} column, it will be converted to an \class{integer} column. For categorical response channels, \class{ordered factor} columns are also accepted, and they will be converted to unordered \class{factor} columns. Missing values in both response and predictor columns are supported but non-finite values are not. Observations with missing predictor or response values are omitted from the data when the model is fitted.

As an example, the following function call would estimate the model using data in the data frame \code{d}, which contains the variables \code{year} and \code{id} (defining the time-index and group-index variables of the data, respectively). Arguments \code{chains} and \code{cores} are passed to \code{rstan::sampling()} which then uses two parallel Markov chains in the Markov chain Monte Carlo (MCMC) sampling of the model parameters.
\begin{Code}
dynamite(
  dformula = obs(x ~ varying(~ -1 + w), family = "poisson") +
    splines(df = 10),
  data = d, time = "year", group = "id",
  chains = 2, cores = 2
)
\end{Code}
The output of \code{dynamite} is a \class{dynamitefit} object for which the standard \proglang{S3} methods such as \fct{summary}, \fct{plot}, \fct{print}, \fct{fitted}, and \fct{predict} are provided along with various other methods and utility functions which we will describe in the following sections in more detail.

\subsection{User-defined priors}

The function \fct{get_priors} can be used to determine the parameters of the model whose prior distribution can be customized. The function can be applied to an existing model fit object (\class{dynamitefit}) or a model formula object (\class{dynamiteformula}). The function returns a \class{data.frame} object, which the user can then manipulate to include their desired priors and consequently supply to the model fitting function \fct{dynamite}.

For instance, using the model fit object \code{gaussian_example_fit} available in the \pkg{dynamite} package, we have the following priors:
\begin{CodeChunk}
\begin{CodeInput}
R> get_priors(gaussian_example_fit)
\end{CodeInput}
\begin{CodeOutput}
         parameter response             prior      type category
1 sigma_nu_y_alpha        y    normal(0, 3.1)  sigma_nu
2          alpha_y        y  normal(1.5, 3.1)     alpha
3      tau_alpha_y        y    normal(0, 3.1) tau_alpha
4         beta_y_z        y    normal(0, 6.1)      beta
5        delta_y_x        y      normal(0, 3)     delta
6   delta_y_y_lag1        y    normal(0, 2.8)     delta
7          tau_y_x        y      normal(0, 3)       tau
8     tau_y_y_lag1        y    normal(0, 2.8)       tau
9          sigma_y        y exponential(0.65)     sigma
\end{CodeOutput}
\end{CodeChunk}
To change a prior distribution, the user only needs to manipulate the \code{prior} column of the desired parameters using the appropriate \proglang{Stan} syntax and parameterization. For a categorical response variable, the column \code{category} describes which category the parameter is related to. For model parameters of the same type and response, a vectorized form the corresponding distribution is automatically used in the generated Stan code if applicable.

\subsection[Methods for dynamitefit objects]{Methods for \class{dynamitefit} objects}

We can obtain a simple model summary with the \fct{print} method of objects of class \class{dynamitefit}. For instance, the model fit object \code{gaussian_example_fit} gives the following summary:
\begin{CodeChunk}
\begin{CodeInput}
R> print(gaussian_example_fit)
\end{CodeInput}
\begin{CodeOutput}
Model:
  Family   Formula
y gaussian y ~ -1 + z + varying(~x + lag(y)) + random(~1)

Correlated random effects added for response(s): y

Data: gaussian_example (Number of observations: 1450)
Grouping variable: id (Number of groups: 50)
Time index variable: time (Number of time points: 30)

Smallest bulk-ESS: 112 (delta_y_y_lag1[12])
Smallest tail-ESS: 93 (delta_y_y_lag1[18])
Largest Rhat: 1.042 (nu_y_alpha_id38)

Elapsed time (seconds):
        warmup sample
chain:1  5.997  3.161
chain:2  5.781  3.283

Summary statistics of the time-invariant parameters
(excluding random effects):
# A tibble: 6 x 10
  variable      mean median      sd     mad     q5   q95  rhat ess_b~1
  <chr>        <dbl>  <dbl>   <dbl>   <dbl>  <dbl> <dbl> <dbl>   <dbl>
1 beta_y_z    1.97   1.97   0.0107  0.0101  1.95   1.99  1.01     259.
2 sigma_nu_y~ 0.0943 0.0937 0.0117  0.0114  0.0757 0.114 0.999    221.
3 sigma_y     0.198  0.198  0.00409 0.00411 0.192  0.205 1.00     166.
4 tau_alpha_y 0.210  0.204  0.0441  0.0397  0.147  0.285 0.999    162.
5 tau_y_x     0.363  0.355  0.0761  0.0739  0.259  0.494 1.00     224.
6 tau_y_y_la~ 0.103  0.100  0.0200  0.0164  0.0754 0.139 0.998    156.
# ... with 1 more variable: ess_tail <dbl>, and abbreviated variable
#   name 1: ess_bulk
\end{CodeOutput}
\end{CodeChunk}
Convergence of the MCMC chains and the smallest effective sample sizes of the model parameters can be assessed using the \fct{mcmc_diagnostics} method of \class{dynamitefit} object whose arguments are the model fit object and \code{n}, the number of potentially problematic variables report (default is 3). We refer the reader to the documentation of the \code{rstan::check_hmc_diagnostics()} and \code{posterior::default_convergence_measures()} for detailed information on the diagnostics reported by function.
\begin{CodeChunk}
\begin{CodeInput}
R> mcmc_diagnostics(gaussian_example_fit)
\end{CodeInput}
\begin{CodeOutput}
NUTS sampler diagnostics:

No divergences, saturated max treedepths or low E-BFMIs.

Smallest bulk-ESS values:

delta_y_y_lag1[12] 112
delta_y_y_lag1[29] 125
nu_y_alpha_id11    128

Smallest tail-ESS values:

delta_y_y_lag1[18]  93
nu_y_alpha_id49    101
nu_y_alpha_id14    109

Largest Rhat values:

nu_y_alpha_id38 1.04
alpha_y[17]     1.03
delta_y_x[3]    1.03
\end{CodeOutput}
\end{CodeChunk}
Note that due to CRAN restrictions the number of stored posterior samples in this example \code{dynamitefit} object is very small, leading to the small effective sample sizes.

A table of posteriors draws or summaries of each parameter of the model can be obtained with the method \fct{as.data.frame} and \fct{as.data.table} which differ only in their output type which are \class{data.frame} and \class{data.table}, respectively. More specifically, the output of \fct{as.data.frame} is a tibble; a tidyverse variant of data frames (of class \class{tbl_df} as defined in the \pkg{tibble} \citep{tibble} package). These functions have the following arguments:
\begin{Code}
as.data.frame.dynamitefit(
  x, row.names = NULL, optional = FALSE, parameters = NULL, responses = NULL,
  types = NULL, summary = FALSE, probs = c(0.05, 0.95), include_fixed = TRUE, ...
)
\end{Code}
Here, \code{x} is the \class{dynamitefit} object and \code{parameters} is a \class{character} vector that determines which parameters should be included in the output. If \code{parameters} is not used, a \class{character} vector argument \code{responses} can be used to determine the channels whose parameters should be included, whereas \code{types} is a \class{character} vector that selects a subset of parameters to extract. For determining suitable options for arguments \code{parameters} and \code{types}, methods \fct{get_parameter_names} and \fct{get_parameter_types} can be used. The argument \code{summary} determines whether to provide summary statistics (mean, standard deviation and quantiles selected by argument \code{probs}) of each parameter, or the full posterior draws. The argument \code{include_fixed} determines whether to include parameters related to fixed time points in the output (see Section~\ref{sec:lags} for details on fixed time points). The arguments \code{row.names}, \code{optional} and \code{...} are ignored for \class{dynamitefit} objects.

For instance, we can extract the posterior summary of the time-invariant regression coefficients (\code{type = "beta"}) for the response variable \code{y} in the \code{gaussian_example_fit} object by writing:
\begin{CodeChunk}
\begin{CodeInput}
R> as.data.frame(
+    gaussian_example_fit,
+    responses = "y", types = "beta", summary = TRUE
+  )
\end{CodeInput}
\begin{CodeOutput}
# A tibble: 1 x 10
  parameter  mean     sd    q5   q95  time group categ~1 respo~2 type
  <chr>     <dbl>  <dbl> <dbl> <dbl> <int> <int> <chr>   <chr>   <chr>
1 beta_y_z   1.97 0.0107  1.95  1.99    NA    NA <NA>    y       beta
# ... with abbreviated variable names 1: category, 2: response
\end{CodeOutput}
\end{CodeChunk}
For \class{dynamitefit} objects, the \code{summary()} method is a shortcut for \code{as.data.frame(summary = TRUE)}.

The default \fct{plot} method for \class{dynamitefit} objects produces the marginal posterior densities and traceplots of the MCMC chains for the desired parameters by using the \pkg{ggplot2} package to produce the plot. This method has the same \code{parameters} and \code{responses} arguments as the \fct{as.data.frame} method, and the argument \code{type}, which is analogous to the \code{types} argument of \fct{as.data.frame}, but accepts only a single character string for plotting parameters of a specific type. Figure~\ref{fig:parameter_posterior_plot} shows the posterior density and traceplot of the \code{beta_y_z} parameter, which is the time-invariant regression coefficient of \code{y} in the \code{gaussian_example_fit} model.
\begin{CodeChunk}
\begin{CodeInput}
R> plot(gaussian_example_fit, responses = "y", type = "beta")
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{parameter_posterior_plot-1} \caption[Posterior density and traceplots for the time-invariant regression coefficient of \code{z} in the model for the response variable \code{y} (parameter \code{beta\_y\_z}) in the \code{gaussian\_example\_fit} model]{Posterior density and traceplots for the time-invariant regression coefficient of \code{z} in the model for the response variable \code{y} (parameter \code{beta\_y\_z}) in the \code{gaussian\_example\_fit} model.}\label{fig:parameter_posterior_plot}
\end{figure}
\end{CodeChunk}
There are also customized plotting functions available for specific parameters types: \fct{plot_betas}, \fct{plot_deltas}, \fct{plot_nus}, \fct{plot_lambdas} and \fct{plot_psis}, which correspond to time-invariant regression coefficients, time-varying regression coefficients, group-specific random effects, latent factor loadings, and latent factors. For instance, we can obtain the posteriors of the time-varying coefficients for the \code{gaussian_example_fit} object to see how the parameter values change over time, as shown in Figure~\ref{fig:gaussian_deltas}.
\begin{CodeChunk}
\begin{CodeInput}
R> plot_deltas(gaussian_example_fit) + labs(title = "")
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{gaussian_deltas-1} \caption{Posterior mean and 90\% intervals of the time-varying coefficients for the \code{gaussian\_example\_fit} model. The panels from left to right show the time-varying intercept for \code{y}, the time-varying effect of \code{x} on \code{y}, and the time-varying effect of \code{lag(y)} (the previous time-point) on \code{y}.}\label{fig:gaussian_deltas}
\end{figure}
\end{CodeChunk}
The generated \proglang{Stan} code of the model can be extracted with the method \fct{get_code} as a \class{character} string. This feature of geared towards advanced users who may for example need to make slight modifications to the generated code in order to adapt the model to a specific scenario that cannot be accomplished with the \pkg{dynamite} model syntax. The generated code also contains helpful annotations describing the model blocks, parameters, and complicated code sections. Using the argument \code{blocks}, we can extract only specific blocks of the full model code. To illustrate, we extract the parameters block of the \code{gaussian_example_fit} model code as the full model code is too large to display.
\begin{CodeChunk}
\begin{CodeInput}
R> cat(get_code(gaussian_example_fit, blocks = "parameters"))
\end{CodeInput}
\begin{CodeOutput}
parameters {
  // Random group-level effects
  vector<lower=0>[M] sigma_nu; // standard deviations of random effects
  matrix[N, M] nu_raw;
  vector[K_fixed_y] beta_y; // Fixed coefficients
  matrix[K_varying_y, D] omega_y; // Spline coefficients
  vector<lower=0>[K_varying_y] tau_y; // SDs for the random walks
  real a_y; // Mean of the first time point
  row_vector[D - 1] omega_raw_alpha_y; // Coefficients for alpha
  real<lower=0> tau_alpha_y; // SD for the random walk
  real<lower=0> sigma_y; // SD of the normal distribution
}
\end{CodeOutput}
\end{CodeChunk}

\section{Prediction}\label{sec:prediction}

The \pkg{dynamite} package provides a comprehensive set of features for obtaining predictions based on the posterior distribution of the model parameters. The package supports imputation of missing exogenous predictor values (last observation carried forward), summarized and individual-level predictions, and various methods to account for new levels of the \code{group} variable for random effects. Counterfactual predictions can also be obtained which enables the study of causal effects and other intricate causal quantities. It should be noted that the predictions do not directly support forecasting as there is no unambiguous way to define how the splines for the time-varying regression coefficients should behave outside of the observed time points. However, such predictions can be obtained by augmenting the original data with missing values for future time points.

The \fct{predict} method for \class{dynamitefit} objects can be used to obtain predictions from the posterior predictive distribution. This function has the following arguments:
\begin{Code}
predict.dynamitefit(
  object, newdata = NULL, type = c("response", "mean", "link"),
  funs = list(), impute = c("none", "locf"),
  new_levels = c("none", "bootstrap", "gaussian", "original"),
  global_fixed = FALSE, n_draws = NULL, expand = TRUE,
  df = TRUE, ...
)
\end{Code}
We will only explain the most important arguments of this method and refer the reader to the package documentation for more information. The first argument \code{object} is the \class{dynamitefit} object. The argument \code{newdata} can be used to define the groups, time points and predictor values that the predictions should be computed for. If \code{newdata} is \code{NULL}, predictions will be computed for the original \code{data} supplied to the \fct{dynamite} function when the model was fitted from the first non-fixed time point onward. The \code{type} argument selects the type of the computed predictions. By default, \code{type = "response"} returns the individual-level simulated predictions for the response variables of the model. Options \code{"link"} and \code{"mean"} return the linear predictor values and the expected values of the posterior predictive distribution, respectively. The argument \code{n_draws} control the number of posterior draws to be used for prediction. By default, all draws are used.

For example, we can obtain posterior predictive samples for the first 4 groups in the \code{gaussian_example} dataset using the corresponding example model fit \code{gaussian_example_fit}. The predictions are shown in Figure~\ref{fig:gaussianpred} and can be obtained as follows:
\begin{CodeChunk}
\begin{CodeInput}
R> pred <- predict(gaussian_example_fit, n_draws = 50)
R> pred |>
+    dplyr::filter(id < 5) |>
+    ggplot(aes(time, y_new, group = .draw)) +
+    geom_line(alpha = 0.5) +
+    geom_line(aes(y = y), colour = "tomato") +
+    facet_wrap(~ id)
\end{CodeInput}
\begin{figure}
\includegraphics[width=\maxwidth]{gaussianpred-1} \caption[Posterior predictive samples for the first 4 groups of the \code{gaussian\_example} data]{Posterior predictive samples for the first 4 groups of the \code{gaussian\_example} data. Lines in red represent the observed values.}\label{fig:gaussianpred}
\end{figure}
\end{CodeChunk}
The \fct{fitted} method is also provided for \class{dynamitefit} objects. In contrast to multi-step predictions of \fct{predict}, this function computes expected values of the posterior predictive distributions at each time point conditional on the original observations.

We note that the multi-step predictions contain not only the parameter uncertainty but also the inherent aleatoric (stochastic) uncertainty of the trajectories. The Monte Carlo variation due to finite number of posterior samples can be reduced by increasing the number of iterations or chains of the MCMC run (as with any posterior summaries) or by combining samples from multiple \fct{predict} calls in case the Monte Carlo error is mostly due to trajectory simulation.

\subsection{Summarized predictions and memory conservation}\label{sec:summary_prediction}

For large data sets and complicated models, obtaining individual-level predictions can be memory intensive. For example, data with 100 groups, 100 time points, a categorical response with 4 categories, and 1000 posterior draws would result in 40 million elements. A simple way to reduce memory usage is to set the argument \code{expand} of \fct{predict} to \code{FALSE} (the default is \code{TRUE}). Disabling this argument separates the simulated values from the fixed predictors in the model into two \class{data.table} objects in the output, called \code{simulated} and \code{observed}, which are then returned as a \class{list} object. This optimization is always carried out internally, meaning that the value of the \code{expand} argument only affects the returned output.

To further reduce memory usage, the argument \code{funs} can be used to obtain summarized predictions instead of individual-level predictions for each time point. This argument accepts a named list of lists of named functions for each response channel of the model, where the supplied functions are then applied over the individuals. The resulting columns in the output are named based on the function names and the response variables. The \code{expand} argument is automatically set to \code{FALSE} when using the \code{funs} argument. For example, we could compute the mean and standard deviation of the predictions for the response variable \code{y} in the \code{gaussian_example} dataset at each time point as follows:
\begin{CodeChunk}
\begin{CodeInput}
R> pred_funs <- predict(
+    gaussian_example_fit,
+    funs = list(y = list(mean = mean, sd = sd))
+  )
R> head(pred_funs$simulated)
\end{CodeInput}
\begin{CodeOutput}
    mean_y      sd_y time .draw
1       NA        NA    1     1
2 1.498783 0.8521039    2     1
3 1.670262 1.3924744    3     1
4 1.662776 1.2291129    4     1
5 2.143064 1.2747560    5     1
6 2.223972 1.4186190    6     1
\end{CodeOutput}
\end{CodeChunk}
The reduction in memory usage compared to the full individual-level predictions is rather substantial even in this simple scenario:
\begin{CodeChunk}
\begin{CodeInput}
R> pred_full <- predict(gaussian_example_fit)
R> format(object.size(pred_full), "Mb")
\end{CodeInput}
\begin{CodeOutput}
[1] "11.4 Mb"
\end{CodeOutput}
\begin{CodeInput}
R> format(object.size(pred_funs), "Mb")
\end{CodeInput}
\begin{CodeOutput}
[1] "0.2 Mb"
\end{CodeOutput}
\end{CodeChunk}

\section{Summary} \label{sec:summary}

In this paper, we presented the \pkg{dynamite} package for Bayesian inference of DMPMs. The package provides a user-friendly interface for model construction, estimation, prediction, posterior inference, and visualization with an extensive and detailed documentation of its features. The package has been designed with the aim of being as general as possible by supporting multivariate models, many response variable distributions, custom prior distributions, and common model features such as time-varying and random effects. The package design also aims for high performance in model estimation by employing \proglang{Stan} and in general-purpose data manipulation by using \pkg{data.table} which is especially reflected in prediction. For advanced users, the \proglang{Stan} code generated by \pkg{dynamite} can be extracted and adapted to user-specific scenarios.

In the future, we plan to extend the capabilities of \pkg{dynamite} by adding support for more distributions. Some distributions in \proglang{Stan} also lack efficient likelihood function variants, such as the Bernoulli distribution, which will likely become available in the future, and will be subsequently implemented in \pkg{dynamite} as well.

\section*{Acknowledgments}
This work was supported by Academy of Finland grant number 331817.