---
title: "Dynamic factor models"
author: "Nicholas J Clark"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: yes
vignette: >
  %\VignetteIndexEntry{Dynamic factor models}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
params:
  EVAL: !r identical(tolower(Sys.getenv("NOT_CRAN")), "true")
---

```{r, echo = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  eval = if (isTRUE(exists("params"))) params$EVAL else FALSE
)
# Inline results come from chunks a build without NOT_CRAN skips. Such a
# build prints each inline expression as code.
if (!isTRUE(knitr::opts_chunk$get("eval"))) {
  knitr::knit_hooks$set(evaluate.inline = function(code, envir) {
    paste0("`", code, "`")
  })
}
```

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  dpi = 100,
  fig.asp = 0.7,
  fig.width = 6,
  out.width = "70%",
  fig.align = "center"
)
library(mvgam)
library(ggplot2)
theme_set(mvgam_theme(base_size = 12))
```

Time series collected together rarely evolve independently. Sites in
the same habitat share their weather, just as species in the same
guild share pulses of resources. Dynamic factor models capture this
common variation by assuming that a small number of latent trends
drive many observed series, with each series a weighted combination
of those trends (Zuur et al.
[2003](https://doi.org/10.1002/env.611); Holmes et al.
[2012](https://doi.org/10.32614/RJ-2012-002)). In mvgam, the
`trend_map` argument of a trend constructor controls which series load
on which trends.

This vignette works through a simulated example of six series driven
by three trends. We fit three models to these data: one that is given
the true loadings, one that estimates the loadings from the data and
one that forces every series onto a single shared trend. Along the
way, we show how to interpret estimated loadings, how to check whether
a model describes its training data and how to compare competing
models by their forecasts of held-out data.

## The model

For series $j$ and latent trend $k$, the mean of each series on the
link scale is a linear combination of the trends:

\begin{align*}
y_{j, t}      & \sim F(\mu_{j, t}, \boldsymbol{\theta}) \\
g(\mu_{j, t}) & = \beta_0 + \beta^\top \mathbf{x}_{j, t}
                       + \sum_{k = 1}^{N_{lv}} Z_{j, k} \, z_{k, t} \\
z_{k, t}      & \sim \text{AR}(1) \text{ or any other trend model}
\end{align*}

$Z$ is the loading matrix, with one row per series and one column per
trend. Row $j$ gives the weight of each trend in series $j$. Every
series with a non-zero weight on trend $k$ uses the same latent path
$z_{k, 1:T}$. All of those series inform its posterior. With fewer
trends than series, the model reduces the dimension of the problem.

## Three ways to write `trend_map`

`trend_map` supplies $Z$ in one of three forms:

- A keyword. `"identity"` gives each series its own trend.
  `"shared"` gives every series the same trend.
- A `data.frame` with columns `series` and `trend`. Series given the
  same trend number share that trend with a loading of one.
- A numeric matrix with one row per series and one column per trend.
  mvgam holds each number fixed and estimates each `NA`.

The matrix form covers partial knowledge. Here series `s5` is free to
load on any of three trends and the other five have known loadings:

```{r partial-map}
Z_partial <- rbind(
  s1 = c(1, 0, 0),
  s2 = c(1, 0, 0),
  s3 = c(1, 0, 0),
  s4 = c(0, 1, 0),
  s5 = c(NA, NA, NA),
  s6 = c(0, 0, 1)
)
```

Passed as `AR(trend_map = Z_partial)`, the fit estimates the three
`NA` entries. `summary()` lists them under `Factor Loadings`. A
matrix of all `NA` estimates every loading, as `n_lv` alone does
later in this vignette.

## Simulated data

To compare the three models with known loadings, we simulate six
series from three AR(1) trends. Trend 1 is strongly autocorrelated
($\phi_1 = 0.85$) and drives series 1 to 3. Trend 2 is weakly
autocorrelated ($\phi_2 = 0.15$) and drives series 4 and 5. Trend 3
($\phi_3 = 0.55$) has the largest innovation SD and drives series 6
alone. We hold out the last 15 of the 80 time points.

```{r simulate}
set.seed(3)

n_time <- 80
n_series <- 6
n_lv <- 3
n_train <- 65
phi_true <- c(0.85, 0.15, 0.55)
sig_true <- c(0.5, 0.35, 0.8)

# Each trend starts at its stationary distribution
lv <- matrix(NA, n_time, n_lv)
lv[1, ] <- rnorm(n_lv, 0, sig_true / sqrt(1 - phi_true^2))
for (t in 2:n_time) {
  lv[t, ] <- phi_true * lv[t - 1L, ] + rnorm(n_lv, 0, sig_true)
}

# Series 1-3 load on trend 1, series 4-5 on trend 2, series 6 on trend 3
Z_true <- matrix(0, nrow = n_series, ncol = n_lv)
Z_true[cbind(1:6, c(1, 1, 1, 2, 2, 3))] <- 1

# Observations add Gaussian noise with SD 0.2
y_mat <- lv %*% t(Z_true) +
  matrix(rnorm(n_time * n_series, 0, 0.2), n_time, n_series)

sim_data <- data.frame(
  time = rep(seq_len(n_time), n_series),
  series = factor(
    rep(paste0("s", seq_len(n_series)), each = n_time),
    levels = paste0("s", seq_len(n_series))
  ),
  y = as.numeric(y_mat)
)
train <- sim_data[sim_data$time <= n_train, ]
test  <- sim_data[sim_data$time >  n_train, ]
```

`mvgam_data()` checks the training data and plots each series, with
the held-out data in black:

```{r plot-observed, fig.cap = "The six simulated series. Series 1 to 3 follow one trend, series 4 and 5 a second, and series 6 a third. Black lines after the dashed line are the held-out data."}
mvgam_data(train, family = gaussian(), trend_formula = ~ AR(),
           newdata = test)
```

## Fitting known loadings

We give the first model the true grouping as a `data.frame`:

```{r trend-map}
tm_known <- data.frame(
  series = paste0("s", seq_len(n_series)),
  trend = c(1L, 1L, 1L, 2L, 2L, 3L)
)
tm_known
```

The observation formula holds an intercept alone.
`AR(p = 1, trend_map = tm_known)` gives each of the three trends its
own AR(1) process and places the series on them. Passing
`newdata = test` stores the held-out data on the fit for `forecast()`
to use later.

```{r fit-known, results = "hide"}
fit_known <- mvgam(
  formula = y ~ 1,
  trend_formula = ~ AR(p = 1, trend_map = tm_known),
  data = train,
  newdata = test,
  family = gaussian(),
  chains = 4L,
  iter = 2000L,
  warmup = 1000L,
  seed = 1L,
  silent = 2L,
  seed = 1L
)
```

```{r summary-known}
summary(fit_known)
```

`summary()` reports one AR coefficient and one innovation SD per
trend. The 95% intervals of all six contain the simulated values. The
model estimates the observation SD at its true value of 0.2.

`plot(type = "factors")` draws the posterior path of each trend over
the training times. Its panels use the name mvgam gives any latent
process that series load on, a factor. With an AR coefficient of
0.85, trend 1 moves slowly. Trend 2 has the smallest innovations and
little memory. It stays close to zero. Trend 3 swings the most.

```{r plot-factors-known, fig.cap = "Posterior paths of the three latent trends of the model given the true loadings."}
plot(fit_known, type = "factors")
```

`forecast()` extends each trend over the held-out times and maps the
draws back to the series through $Z$. Series on the same trend share
one latent forecast. Each forecast decays toward the series mean at
the rate its AR coefficient sets. The decay is clearest for series 6,
whose forecast starts near its last observation and reaches the mean
within about five steps.

```{r plot-forecast-known, fig.cap = "Forecasts from the model given the true loadings. Points are observations, and those after the dashed line are held out."}
fc_known <- forecast(fit_known)
plot(fc_known)
```

## Estimating the loadings

When the grouping is unknown, `n_lv` asks mvgam to estimate every
loading of that many factors. The loadings take a Student-t prior. To
set the scale of the loadings, the innovation SD of every factor is
fixed at one. Each factor has its own AR coefficient, which lets the
model tell the factors apart by their dynamics and leaves only their
order and signs arbitrary. mvgam orders the factors by the variance
they explain and gives each a positive largest loading.

```{r fit-free, results = "hide"}
fit_free <- mvgam(
  formula = y ~ 1,
  trend_formula = ~ AR(p = 1, n_lv = n_lv),
  data = train,
  newdata = test,
  family = gaussian(),
  chains = 4L,
  iter = 2000L,
  warmup = 1000L,
  seed = 1L,
  silent = 2L,
  seed = 1L
)
```

```{r summary-free}
summary(fit_free)
```

```{r free-numbers, include = FALSE}
z_diag <- posterior::summarise_draws(
  as_draws_df(fit_free, variable = "^Z\\[", regex = TRUE),
  "rhat", "ess_bulk"
)
max_rhat <- formatC(max(z_diag$rhat), format = "f", digits = 2)
min_ess <- floor(min(z_diag$ess_bulk))
```

`summary()` lists the loading `Z[i, k]` of every series `i` on every
factor `k`. Every loading has an `Rhat` of at most `r max_rhat` and a
bulk effective sample size of at least `r min_ess`, enough to support
the 95% intervals interpreted below.

Eighteen rows are hard to scan. `mcmc_plot()` draws the same
posteriors as intervals:

```{r plot-loadings-free, fig.cap = "Posterior medians of the 18 loadings of the model that estimates them, with 50% (thick) and 90% (thin) intervals."}
mcmc_plot(fit_free, variable = "^Z\\[", regex = TRUE,
          type = "intervals")
```

Series 1 to 3 load on factor 1 and series 6 on factor 2. Series 4
and 5 load on factor 3. Every other loading has a median near zero
and an interval that contains zero. The model recovers the simulated
grouping without being given it. The interval of each AR coefficient
contains the simulated value of the trend its factor matches.

Fixing each factor's innovation SD at one moves the scale of its
trend into the loadings. A recovered loading should then match the
innovation SD that the first model estimates for the same trend. The
chunk below takes, for each trend, the loading of one of its series
on the factor that matches it:

```{r loading-scale}
loading_free <- colMeans(as_draws_matrix(
  fit_free, variable = c("Z[s1,1]", "Z[s4,3]", "Z[s6,2]")
))
sd_known <- colMeans(as_draws_matrix(
  fit_known, variable = "^sigma_trend", regex = TRUE
))
round(data.frame(trend = 1:3, sd_known, loading_free,
                 row.names = NULL), 2)
```

The two estimates differ by at most
`r formatC(max(abs(loading_free - sd_known)), format = "f", digits = 2)`
for any trend.

```{r plot-factors-free, fig.cap = "The three latent factors of the model that estimates its loadings. Factors 1, 2 and 3 match trends 1, 3 and 2 of the simulation."}
plot(fit_free, type = "factors")
```

`active_factors()` decomposes the covariance that the factors give
the series into its principal dimensions and reports the share of
the variance each carries. Each series here loads on a single
factor, which lines the dimensions up with the factors:

```{r active-free}
af_free <- active_factors(fit_free)
af_free
```

```{r active-text, include = FALSE}
share <- round(100 * af_free$per_factor$median_share)
prob3 <- formatC(af_free$per_factor$prob_active[3], format = "f",
                 digits = 2)
```

The first dimension carries `r share[1]`% of the variance and the
third `r share[3]`%. The third holds the trend of series 4 and 5, the
trend with the smallest innovations. Its posterior probability of
being active is `r prob3`. Under the Student-t prior, a factor the
data do not need keeps the variance its prior gives it. The count can
then exceed the number of factors the data need. The prior
`loadings_prior = "mgp"` shrinks surplus factors toward zero. With it,
fit more factors than you expect and count those that stay active.

The dependence among series is often the target of a factor model.
`residual_cor()` computes the correlations that the loadings imply
between each pair of series. They describe the latent predictor
alone. Observation noise does not enter them:

```{r plot-residcor-free, fig.cap = "Posterior median correlations among the six series, implied by the estimated loadings."}
plot(residual_cor(fit_free))
```

The correlations show the same grouping. Series 1 to 3 are strongly
correlated with one another, as are series 4 and 5. Series 6 is
weakly correlated with the rest.

## Pooling every series

To measure what a wrong grouping costs, we fit a third model that
puts all six series on one trend with `AR(trend_map = "shared")`:

```{r fit-pooled, results = "hide"}
fit_pooled <- mvgam(
  formula = y ~ 1,
  trend_formula = ~ AR(p = 1, trend_map = "shared"),
  data = train,
  newdata = test,
  family = gaussian(),
  chains = 4L,
  iter = 2000L,
  warmup = 1000L,
  seed = 1L,
  silent = 2L,
  seed = 1L
)
```

### Checking the fit

Before comparing forecasts, check that each fit describes its training
data. For a fit that does, the randomised quantile residuals of a
series look like independent standard normal draws.
`plot(type = "residuals")` draws them for one series:

```{r plot-resid-pooled, fig.cap = "Randomised quantile residuals of series 1 under the pooled model: against the fitted values, on a normal Q-Q plot and as autocorrelation and partial autocorrelation functions."}
plot(fit_pooled, type = "residuals", series = "s1")
```

The residuals of series 1 rise with the fitted values and are
correlated at lag 1. Because one trend cannot follow three sets of
dynamics, the residuals keep the part of series 1 that the shared
trend misses. The same plot for `fit_free` shows neither pattern.

`pp_check()` compares the observed values of each series with values
simulated from the fit:

```{r plot-ppc-pooled, fig.cap = "Density of the observed values of each series (dark line) and of 50 sets of values simulated from the pooled model (light lines)."}
pp_check(fit_pooled, type = "dens_overlay_grouped", group = "series",
         ndraws = 50)
```

```{r sigma-text, include = FALSE}
obs_sd <- function(fit) {
  formatC(median(as_draws_matrix(fit, variable = "sigma")),
          format = "f", digits = 2)
}
```

The simulated values of series 4 and 5 spread far wider than the
observed ones. The pooled model estimates an observation SD of
`r obs_sd(fit_pooled)`, against `r obs_sd(fit_free)` for the model
that estimates its loadings. It assigns the variation its single
trend misses to observation noise. That noise widens the forecast
intervals of every series:

```{r plot-forecast-pooled, fig.cap = "Forecasts from the model that pools all six series onto one trend. The intervals over the training period are several times wider than those of the model given the true loadings."}
fc_pooled <- forecast(fit_pooled)
plot(fc_pooled)
```

## Comparing forecasts

`compare_scores()` scores the three forecasts against the held-out
data with one rule. Each argument name becomes the name of its model.
We use the continuous ranked probability score (CRPS) and the log
score, for which lower values are better. Printing the result ranks
the models by their score at each horizon, summed over the six
series and averaged over the 15 horizons:

```{r scores}
fc_free <- forecast(fit_free)
crps <- compare_scores(known = fc_known, free = fc_free,
                       pooled = fc_pooled, score = "crps")
crps
logs <- compare_scores(known = fc_known, free = fc_free,
                       pooled = fc_pooled, score = "logs")
logs
```

```{r score-text, include = FALSE}
avg <- function(scores, model) {
  rows <- scores$series == "all_series" & scores$model == model
  formatC(mean(scores$score[rows]), format = "f", digits = 2)
}
```

The pooled model ranks last on both scores. Its mean log score of
`r avg(logs, "pooled")` compares with `r avg(logs, "known")` for the
model given the true loadings. The model that estimates its loadings
scores `r avg(crps, "free")` on CRPS and `r avg(logs, "free")` on the
log score, close to the `r avg(crps, "known")` and
`r avg(logs, "known")` of the model given the true loadings. In this
simulation, estimating the loadings costs little forecast accuracy. A
wrong grouping costs much more.

`plot()` draws the CRPS of each series at each horizon:

```{r plot-scores, fig.cap = "CRPS of each series at each forecast horizon for the three models. Lower values are better."}
plot(crps)
```

The pooled model scores worst on series 4 and 5 at most horizons.
Its forecasts of those series carry the observation noise it
estimates from all six series.

A held-out forecast score is a practical check on a proposed
grouping. Where two candidate `trend_map` structures are plausible,
fit both and compare their scores.

## Where to next

- `?trend_constructors` describes `trend_map`. `?mvgam` describes
  `loadings_prior`, which sets a structured prior on estimated
  loadings (Heaps and Jermyn 2024).
- `?compare_scores` and `?score` list the available scoring rules.
- `?residual_cor` and `?shared_variation` give the correlations and
  covariances among series, with their intervals.
- `?ordinate` draws the series loadings and the factor scores as a
  biplot.
- `how_to_cite()` writes a methods paragraph for a fitted model with
  the references for its factor structure. `methods_md()` writes out
  its equations.
- The
  [forecast evaluation article](https://nicholasjclark.github.io/mvgam/articles/forecast_evaluation.html)
  covers `lfo_cv()` and `ensemble()` for comparing and combining
  models.
- The
  [JSDM article](https://nicholasjclark.github.io/mvgam/articles/jsdgam.html)
  applies the same factor structure to community data with
  `jsdgam()`.
- The
  [VAR article](https://nicholasjclark.github.io/mvgam/articles/var.html)
  covers models where each series keeps its own trend and the trends
  affect one another.
- The
  [overview vignette](https://nicholasjclark.github.io/mvgam/articles/mvgam_overview.html)
  introduces the other trend models and their arguments.

## References

Heaps, S. E. and Jermyn, I. H. (2024). Structured prior
distributions for the covariance matrix in latent factor models.
*Statistics and Computing* 34, 143.
[doi:10.1007/s11222-024-10454-0](https://doi.org/10.1007/s11222-024-10454-0)

Holmes, E. E., Ward, E. J. and Wills, K. (2012). MARSS: Multivariate
Autoregressive State-space Models for Analyzing Time-series Data.
*The R Journal* 4(1), 11-19.
[doi:10.32614/RJ-2012-002](https://doi.org/10.32614/RJ-2012-002)

Zuur, A. F., Fryer, R. J., Jolliffe, I. T., Dekker, R. and Beukema,
J. J. (2003). Estimating common trends in multivariate time series
using dynamic factor analysis. *Environmetrics* 14(7), 665-685.
[doi:10.1002/env.611](https://doi.org/10.1002/env.611)
