Package {mvgam}


Title: Multivariate (Dynamic) Generalized Additive Models
Version: 2.0.0
Date: 2026-11-26
Description: Fit Bayesian Dynamic Generalized Additive Models to multivariate observations. Users can build nonlinear State-Space models that can incorporate semiparametric effects in observation and process components, using a wide range of observation families. Estimation is performed using Markov Chain Monte Carlo with Hamiltonian Monte Carlo in the software 'Stan'. References: Clark & Wells (2023) <doi:10.1111/2041-210X.13974>.
URL: https://github.com/nicholasjclark/mvgam, https://nicholasjclark.github.io/mvgam/
BugReports: https://github.com/nicholasjclark/mvgam/issues
License: MIT + file LICENSE
Depends: R (≥ 3.6.0), brms (≥ 2.21.0)
Imports: methods, parallel, mgcv (≥ 1.8-13), cli (≥ 3.6.0), insight (≥ 0.19.1), marginaleffects (≥ 0.16.0), Rcpp (≥ 0.12.0), rstan (≥ 2.29.0), posterior (≥ 1.0.0), loo (≥ 2.10.0), rstantools (≥ 2.1.1), bayesplot (≥ 1.5.0), ggplot2 (≥ 3.5.0), checkmate, data.table, dplyr, rlang (≥ 1.0.0), generics, tibble (≥ 3.0.0), patchwork (≥ 1.2.0)
Encoding: UTF-8
Language: en-GB
LazyData: true
RoxygenNote: 7.3.3
Suggests: ape, bridgesampling, cmdstanr (≥ 0.8.1), future, ggarrow, ggpp, ggrepel, knitr, mice, rmarkdown, scoringRules, testthat (≥ 3.2.0), tsibble, V8, withr
Enhances: gratia (≥ 0.9.0)
SystemRequirements: Stan (>= 2.36.0 for simplex multi-response families `diri()`, `multi()`, `categ()`; >= 2.26.0 otherwise). Install via `cmdstanr::install_cmdstan()` or rstan from `https://mc-stan.org/r-packages/`.
Additional_repositories: https://mc-stan.org/r-packages/
LinkingTo: Rcpp, RcppArmadillo
VignetteBuilder: knitr
NeedsCompilation: yes
Packaged: 2026-11-27 00:48:24 UTC; nicholas-clark
Author: Nicholas J Clark ORCID iD [aut, cre], KANK Karunarathna ORCID iD [ctb] (ARMA parameterisations and factor models), Sarah Heaps ORCID iD [ctb] (VARMA parameterisations), Scott Pease ORCID iD [ctb] (broom enhancements), Matthijs Hollanders ORCID iD [ctb] (ggplot visualizations)
Maintainer: Nicholas J Clark <nicholas.j.clark1214@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-27 01:40:02 UTC

mvgam: Multivariate (Dynamic) Generalized Additive Models

Description

logo

Fit Bayesian Dynamic Generalized Additive Models to multivariate observations. Users can build nonlinear State-Space models that can incorporate semiparametric effects in observation and process components, using a wide range of observation families. Estimation is performed using Markov Chain Monte Carlo with Hamiltonian Monte Carlo in the software 'Stan'. References: Clark & Wells (2023) doi:10.1111/2041-210X.13974.

Author(s)

Maintainer: Nicholas J Clark nicholas.j.clark1214@gmail.com (ORCID)

Other contributors:

See Also

mvgam() fits a state-space model and jsdgam() a joint species distribution model. The mvgam cheatsheet and the JSDM cheatsheet summarise the main functions on one page each.


Local linear trends, with optional damping and seasons

Description

A latent level that moves with a latent growth rate, the local linear trend of Harvey (1989). Each latent process carries a level and a slope:

\mu_t = \mu_{t-1} + \beta_{t-1} + \eta_t

\beta_t = \phi \beta_{t-1} + \zeta_t

The level innovations \eta_t have scale sigma_trend and the slope innovations \zeta_t scale sigma_slope_trend. A small sigma_slope_trend gives a trend that keeps its direction. A zero scale gives a random walk with a fixed drift. damped = TRUE estimates \phi on (0, 1) as ar1_slope_trend, which pulls the growth rate back toward zero over the horizon (Gardner and McKenzie 1985). The undamped trend has \phi = 1. Its forecasts extend the current growth rate.

Usage

LLT(
  time = NA,
  series = NA,
  damped = FALSE,
  cor = NULL,
  gr = NA,
  subgr = NA,
  n_lv = NULL,
  trend_map = NULL,
  df = Inf,
  season = NULL,
  harmonics = NULL,
  centred = FALSE
)

Arguments

time

The unquoted name of the numeric or integer variable in data that holds each row's time. Defaults to time.

series

The unquoted name of the factor variable in data that names each row's series. Its levels fix the order of the series. A trend needs this column even for a single series. Defaults to series.

damped

Logical. Estimate a damping coefficient for the slope? Default FALSE.

cor

Logical. Correlate the innovations of different series? TRUE estimates a full covariance matrix of the innovations when the data hold more than one series. AR() and RW() default to NULL. That means FALSE for an ungrouped trend and TRUE when gr names a grouping variable. VAR(), ZMVN() and grouped AR() and RW() trends always estimate correlations. They refuse cor = FALSE. CAR() defaults to FALSE.

In a factor model with every loading sampled, the factors take independent shocks. The loadings carry the correlation among series, which residual_cor() reports. A correlation among the factors would trade off against the loadings. AR(), RW() and LLT() refuse cor = TRUE there. A trend_map that fixes the loadings keeps the factors apart. cor = TRUE then estimates their correlation.

gr

An optional factor in data that groups the series, such as region. Each level of gr takes its own correlation matrix among the innovations of its series. The matrices are pooled toward one global matrix:

\Omega_{group} = \alpha_{cor}\Omega_{global} + (1 - \alpha_{cor})\Omega_{group, local}

Here \Omega_{global} is shared by every group, \Omega_{group, local} is the deviation of one group and \alpha_{cor} sets the weight on the global matrix. An \alpha_{cor} near 1 pools the groups strongly. Without subgr, the series column names the series within each group.

Within a VAR() it sets up a hierarchical panel vector autoregression. Each group learns its autoregressive, moving-average and correlation matrices from shared hyperparameters. The groups do not interact.

Two constraints apply to hierarchical trend models:

  • Each series belongs to one group. mvgam() refuses a gr that varies within a series.

  • Every group must hold the same number of series. The Stan program sizes each group's correlation block from one shared count. Validation refuses unbalanced groups before fitting.

subgr

A subgrouping factor variable naming the time series within each level of gr. Defaults to series. A model with hierarchical correlations builds its series from gr and subgr, and data then needs no series column.

For example, to model counts of several species (species in data) across three regions (region) with innovations correlated within regions, specify gr = region and subgr = species. mvgam() then builds the series as

⁠series = interaction(gr, subgr, drop = TRUE, sep = "_",⁠ ⁠lex.order = TRUE)⁠

A region r1 and a species sp1 give the series "r1_sp1". The levels sort lexically. summary(), plot() and forecast() all label that series "r1_sp1". A series column that disagrees with the derived series is replaced by it, with a warning.

n_lv

The number of latent factors to estimate for dynamic factor models. When n_lv is smaller than the number of series, the latent processes are modelled as n_lv factors with estimated loadings onto the series. Defaults to NULL, in which case one latent process is used per series.

trend_map

Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:

  • a numeric ⁠n_series x n_lv⁠ matrix of loadings. NA entries are sampled and finite entries stay fixed. An all-NA matrix, such as matrix(NA, n_series, 2), fixes nothing and sets two factors.

  • a data.frame(series, trend) placing each series on one process, with a loading of one.

  • "identity", one process per series, or "shared", one process for every series.

Its columns set the number of factors, which an n_lv given too must match. Without a trend_map every loading is sampled and identified after sampling by a thin QR rotation (Heaps and Jermyn 2024). A map that fixes any loading takes no rotation. The loadings_prior of mvgam() accepts a map with no fixed entries. Defaults to NULL.

df

Degrees of freedom for the latent process innovations. Defaults to Inf, which gives Gaussian innovations: a t with infinite degrees of freedom is a normal. Set df = NA to estimate them, or supply a number above 2 to fix them.

Finite degrees of freedom let the latent process absorb an occasional large shock while sigma_trend stays at the scale of ordinary variation. That suits boom-and-bust population series and outbreak dynamics. The innovations follow a multivariate t. Because it shares one innovation scale across the series at each time point, large innovations tend to occur together. Each series keeps its own direction and magnitude. A shock in one series says nothing about the sign of the others. One series can also stay unmoved by an event that moves its neighbours. cor sets the correlation between series exactly as it does for Gaussian innovations. The degrees of freedom set how heavy the tails of the innovations are.

When df = NA the degrees of freedom are estimated as nu_trend, with a default gamma(4, 0.3) prior. The prior argument replaces it, for example prior(gamma(2, 0.1), class = "nu_trend"). get_prior lists nu_trend with the other trend classes.

Three caveats apply:

  • A fixed value must exceed 2. Below it the innovations have no finite variance. An autoregressive trend then has no stationary covariance to start from.

  • The first states of an autoregressive trend take the stationary mean and covariance. Under t innovations the true stationary distribution has heavier tails than that.

  • Only the tails of the latent process inform the degrees of freedom. Below roughly 200 time points their posterior stays close to the prior.

VAR() samples its states directly and PW() has no innovations. Neither takes df.

season

Optional numeric vector of seasonal periods in time steps, each above 2, such as 12 for monthly data or c(7, 365.25) for daily data. Periods need not be whole. Default NULL fits no season.

harmonics

Optional integer vector with the number of trigonometric harmonics of each period, each below half its period. Fewer harmonics give a smoother seasonal shape. Defaults to the most each period allows, up to 10.

centred

Logical. Sample the latent states directly rather than their innovations? Default FALSE. The model and its posterior are the same. See Centred states below.

Details

The level shocks take the innovation structure of RW(): cor correlates them across series, gr and subgr pool their correlations hierarchically and df gives them a multivariate t. The slope and seasonal shocks are Gaussian and take the level's correlation matrix with scales of their own. residual_cor() reports that one matrix.

The slope starts at a free value, init_slope_trend, damped or not, as in the damped trends of exponential smoothing. Damping serves a series that starts with fast growth and slows. The initial slope of such a series can lie far outside the slope's stationary distribution. The level starts at its first shock. The observation intercept carries its mean.

Default priors scale with the number of time points N and with the factor s that brms uses to widen its own default scales, as get_prior() describes:

A factor model with every loading sampled measures these scales in units of \sqrt{N}, the spread of its level over the series. Its loadings carry s. get_prior() prints the resolved values.

A smooth or linear function of time in either formula competes with the slope for the same variation. mvgam() warns when the time variable appears in one. The slope variance is weakly identified on short series: LLT() warns below 20 time points and refuses fewer than 5. On informative data, such as large counts, a chain started at random can stall far from the posterior. init = "pathfinder" in mvgam() starts every chain from Stan's Pathfinder approximation.

In a factor model with every loading sampled, the loadings set each factor's scale. The level shocks take a fixed scale of one. Every factor keeps its level noise. The factors share one sigma_slope_trend and one ar1_slope_trend. A rotation of the factors then leaves the model unchanged. The QR rotation of RW() factors identifies the loadings. A trend_map that fixes loadings keeps one slope scale per factor. The factors' shocks are independent, as cor describes.

Seasonality: season adds a stochastic season \gamma_t to the level, the trigonometric form of Harvey (1989) with the non-integer and multiple periods of De Livera et al. (2011). The latent state is \mu_t + \gamma_t. Harmonic j of period m holds a state pair that turns by \lambda_j = 2 \pi j / m at each step and takes Gaussian shocks of scale sigma_season_trend:

\gamma_{j,t} = \cos\lambda_j \gamma_{j,t-1} + \sin\lambda_j \gamma^*_{j,t-1} + \omega_{j,t}

\gamma^*_{j,t} = \cos\lambda_j \gamma^*_{j,t-1} - \sin\lambda_j \gamma_{j,t-1} + \omega^*_{j,t}

Common periods are 4 for quarterly data, 12 for monthly data, 52.18 for weekly data over years, 7 and 365.25 for daily data and 24 and 168 for hourly data. LLT(season = 12, harmonics = K) fits the season that AddTrig(period = 12, frequencies = 1:K) specifies in bsts.

The season is the sum of the first states over the harmonics. A small sigma_season_trend keeps the seasonal shape nearly fixed. A zero scale fixes it, as a cyclic smooth does. A larger scale lets the shape drift. Every harmonic of a process shares one scale.

Each harmonic averages to zero over its period, which separates the season from the level and the observation intercept. Two periods sharing a harmonic, such as 6 and 12 with three or more harmonics, are refused. A period longer than the data overlaps the slope and draws a warning. The starting pairs init_season_trend are estimated under one prior for both states of every harmonic. That prior treats every phase at the first time point alike. Under cor or gr each harmonic's shocks are correlated across series, as the level shocks are. Series correlated in their shocks shift their seasons together. In a factor model each factor has its own season, mapped to the series through the loadings.

sigma_season_trend takes a gamma(2, .) prior whose median puts the season's drift over the series at s / 4. A season that drifts by its own size over the series would barely repeat. Each starting state takes normal(0, s / sqrt(K)) over K harmonics, which gives the starting seasonal pattern a root mean square of s. get_prior() prints the resolved values.

Components: hindcast.mvgam(), forecast.mvgam() and plot(type = "trend") report the parts of the trend through component. "level" is the stochastic level and "slope" its growth per time step. "season" is the season. "predictor" holds the effects of the trend formula's covariates. Several names add their components: component = c("level", "predictor") gives the level with the covariate effects it moves with. Level, season and predictor sum to the trend. A factor model reports each component at the series grain, through its loadings. A rotation of the factors leaves them unchanged. seasonality() summarises the swing and peak of the season in each cycle. It also reports how both changed over the series.

Value

An object of class mvgam_trend.

References

Harvey, A. C. (1989). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press.

Gardner, E. S. and McKenzie, E. (1985). Forecasting trends in time series. Management Science, 31:1237-1246.

De Livera, A. M., Hyndman, R. J. and Snyder, R. D. (2011). Forecasting time series with complex seasonal patterns using exponential smoothing. Journal of the American Statistical Association, 106:1513-1527.

See Also

RW(), PW(), trend_constructors, get_prior() for the scale of the default priors, hindcast.mvgam() and forecast.mvgam() for the level, the slope and the season, seasonality() for the swing and peak of each seasonal cycle, series_to_mvgam() for the periods a ts, msts or tsibble carries

Other trend models: PW(), ZMVN(), list_trend_types(), lv_axis(), print.mvgam_trend()

Examples

## Not run: 
# A series that grows fast, then slows: its slope starts at 0.25
# and shrinks by a factor of 0.93 at each step
set.seed(2)
n_t <- 85
slope <- 0.25 * 0.93^(0:(n_t - 1))
dat <- data.frame(
  time = 1:n_t,
  series = factor("s1"),
  y = rpois(n_t, exp(1 + cumsum(slope) + cumsum(rnorm(n_t, 0, 0.03))))
)

# Fit the first 45 points, while the series is still growing
mod <- mvgam(
  y ~ 1,
  trend_formula = ~ LLT(damped = TRUE),
  data = dat[1:45, ],
  family = poisson(),
  chains = 2,
  silent = 2
)

# The posterior for `ar1_slope_trend` covers the simulated 0.93
summary(mod)

# The slope decays toward zero over the fitted times and the horizon
plot(forecast(mod, newdata = dat[46:85, ], type = "trend",
              component = "slope"))

# On the link scale the damped forecast levels off. An undamped slope
# carries the last growth rate forward.
plot(forecast(mod, newdata = dat[46:85, ], type = "link"))
mod_undamped <- update(mod, trend_formula = ~ LLT())
plot(forecast(mod_undamped, newdata = dat[46:85, ], type = "link"))

# Ten years of monthly counts: a slow rise, a seasonal swing that
# widens from 0.3 to 0.9 on the log scale and a rainfall effect
set.seed(3)
n_t <- 120
season <- seq(0.3, 0.9, length.out = n_t) * sin(2 * pi * (1:n_t) / 12)
dat_s <- data.frame(time = 1:n_t, series = factor("s1"),
                    rain = rnorm(n_t))
dat_s$y <- rpois(n_t, exp(2.5 + 0.008 * dat_s$time + season +
                            0.3 * dat_s$rain))

# Two harmonics of a twelve-month season, with rainfall acting on the
# latent state. The last year is held out.
mod_s <- mvgam(
  y ~ 1,
  trend_formula = ~ rain + LLT(season = 12, harmonics = 2),
  data = dat_s[1:108, ],
  family = poisson(),
  chains = 2,
  silent = 2
)

# A small `sigma_season_trend` lets the seasonal shape drift slowly
summary(mod_s)

# Simulated counts match the distribution of the observed ones
pp_check(mod_s, type = "ecdf_overlay")

# The rainfall effect on the expected count
conditional_effects(mod_s, type = "expected")

# The fitted season widens over the years and carries its shape into
# the held-out year
fc_s <- forecast(mod_s, newdata = dat_s[109:120, ], type = "trend",
                 component = "season")
plot(fc_s)

# The swing of each year's season and its peak month. Comparing the
# first and last years gives the widening and its probability
s <- seasonality(mod_s, newdata = dat_s[109:120, ])
s
plot(s)
summary(s)$change

# Draws of the seasonal shock scale
head(as.data.frame(mod_s, variable = "sigma_season_trend"))

# Two regions whose levels move together, with shocks correlated at
# 0.7. Counts near 20 pin the states down, which the centred form
# samples fastest
set.seed(4)
n_t <- 60
z <- rnorm(n_t)
shock <- 0.25 * cbind(z, 0.7 * z + sqrt(1 - 0.7^2) * rnorm(n_t))
dat_r <- data.frame(
  time = rep(1:n_t, 2),
  series = factor(rep(c("north", "south"), each = n_t))
)
dat_r$y <- rpois(2 * n_t, exp(3 + c(apply(shock, 2, cumsum)) +
                                0.5 * sin(2 * pi * dat_r$time / 12)))

# `cor = TRUE` correlates the level, slope and seasonal shocks
mod_r <- mvgam(
  y ~ 1,
  trend_formula = ~ LLT(season = 12, harmonics = 1, cor = TRUE,
                        centred = TRUE),
  data = dat_r,
  family = poisson(),
  chains = 2,
  silent = 2
)

# The one correlation matrix the three kinds of shock share
residual_cor(mod_r)

## End(Not run)


Piecewise linear or logistic trends

Description

A trend that grows at a constant rate between changepoints, as in Prophet (Taylor and Letham 2018). Linear growth is unbounded. Logistic growth saturates at a carrying capacity that data supplies. The constructor records its arguments. The model evaluates them against the data.

Usage

PW(
  time = NA,
  series = NA,
  cap = NA,
  n_changepoints = 10,
  changepoint_range = 0.8,
  changepoint_scale = 0.3,
  growth = "linear",
  n_lv = NULL,
  trend_map = NULL
)

Arguments

time

The unquoted name of the numeric or integer variable in data that holds each row's time. Defaults to time.

series

The unquoted name of the factor variable in data that names each row's series. Its levels fix the order of the series. A trend needs this column even for a single series. Defaults to series.

cap

The unquoted name of the variable in data that holds the carrying capacity of a logistic model, on the response scale. It is numeric and can vary by time and series. Defaults to cap. A logistic model whose data lack the column is refused.

n_changepoints

A positive integer: the number of potential changepoints, spaced evenly over the first changepoint_range of the time points in data. Defaults to 10.

changepoint_range

A number in ⁠(0, 1]⁠: the share of the series that holds the potential changepoints. The default 0.8 leaves the last fifth with the growth rate of the last changepoint. A changepoint among the final points would be estimated from too few observations to trust in a forecast.

changepoint_scale

A positive number: the typical change in growth at one changepoint over the whole series, in link units for linear growth and in logits for logistic growth. For a series of N time points each per-step rate change takes double_exponential(0, s * changepoint_scale / N), where s is the factor get_prior() describes for linear growth and 1 for logistic growth. Larger values give a more flexible trend. The default 0.3 gives the ten default changepoints a prior median movement of the level of about half a unit over the series, the movement the LLT() slope prior allows. Prophet's default of 0.05 holds a link-scale trend close to a straight line.

growth

'linear' (the default) or 'logistic'.

n_lv, trend_map

Factor models are not supported for PW(). Supplying either is refused.

Details

Intercepts: A linear trend takes its level from the observation formula, as every other trend in mvgam does. y ~ 1 is its ordinary observation formula.

A logistic trend contributes cap * inv_logit(...) on the link scale. Its offset m_trend places the inflection in time. The expectation saturates at cap when the observation formula omits its intercept (y ~ -1 or y ~ 0 + ...). An intercept raises the ceiling above cap.

Priors: Time runs in steps ⁠1, ..., N⁠. The base growth rate takes ⁠k_trend ~ normal(0, 2 s / (N - 1))⁠, two units of growth over the series at one standard deviation. The logistic inflection takes m_trend ~ normal((N + 1) / 2, N / 2), centred on the middle of the series. get_prior() shows the values for a given model.

The carrying capacity: A market size, a population size or an ecological carrying capacity can bound a series. growth = 'logistic' takes it from the cap column, which can vary by series and by time. Every observation needs a value. Under a non-identity link the capacity is moved to the link scale, such as its log under poisson() or negbinomial(). Give it on the scale of the response.

Value

An object of class mvgam_trend.

Author(s)

Nicholas J Clark

References

Taylor, S. J. and Letham, B. (2018). Forecasting at scale. The American Statistician, 72, 37-45. doi:10.1080/00031305.2017.1380080

See Also

LLT() for a trend whose growth changes continuously. get_prior() lists the default priors. The forecast evaluation article compares a piecewise trend with other trends out of sample.

Other trend models: LLT(), ZMVN(), list_trend_types(), lv_axis(), print.mvgam_trend()

Examples

## Not run: 
set.seed(2024)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L)
mod <- mvgam(
  y ~ 1,
  trend_formula = ~ PW(growth = "linear"),
  data          = simdat$data_train,
  family        = poisson(),
  chains        = 2,
  silent        = 2
)
summary(mod)

# The base growth rate and the rate change at each changepoint
mcmc_plot(mod, variable = "trend_params")

# The forecast continues the growth rate of the last changepoint
plot(forecast(mod, newdata = simdat$data_test))

# Next, score() rates the forecast against the held-out points

## End(Not run)


Standard deviations and correlations of group-level effects

Description

Posterior draws of the standard deviation of each group-level term of the observation formula, with the correlations and covariances of terms that share a grouping factor.

Usage

## S3 method for class 'mvgam'
VarCorr(
  x,
  sigma = 1,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  ...
)

Arguments

x

A fitted mvgam object.

sigma

A single non-negative number. It has no effect. summary.mvgam() reports the observation family's scale.

summary

Logical. TRUE (the default) summarises the draws. FALSE returns them.

robust

Logical. TRUE summarises with the median and MAD. Defaults to FALSE.

probs

Numeric vector of the two quantiles to report.

...

Unused. Anything passed here is refused.

Details

A trend-side component is named with the ⁠_trend⁠ suffix, as sd_g__Intercept_trend. as_draws.mvgam() returns its draws.

Value

A named list with one entry per grouping factor. Each entry is a list of these components:

Author(s)

Nicholas J Clark

See Also

ranef.mvgam() gives each level's deviation. fixef.mvgam() summarises the population-level effects.

Other posterior summaries: bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(14)
simdat <- sim_mvgam(family = poisson(), n_series = 4L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5) + (1 | series),
             trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# The standard deviation of the series intercepts
VarCorr(mod)$series$sd

# Next: ranef() gives each series' own deviation

## End(Not run)


Correlated latent effects with no time dependence

Description

A latent effect for each unit, such as a site, plot or time point, drawn from a multivariate normal that correlates the series. Unlike the other trends, the effect at one unit does not depend on the previous one. The constructor records its arguments. The model evaluates them against the data.

Usage

ZMVN(
  time = NA,
  series = NA,
  gr = NA,
  subgr = NA,
  n_lv = NULL,
  cor = TRUE,
  trend_map = NULL,
  df = Inf,
  centred = FALSE
)

Arguments

time

The unquoted name of the numeric or integer variable in data that indexes the units, such as sites, plots or times. Defaults to time, as for the other trends.

The values may have any spacing. Each unit's effects follow x_{u, :} \sim MVN(0, \Sigma), with \Sigma indexed by series alone. The gap between two units plays no part. That suits sites, dropped units, k-fold refits and irregular sampling.

series

The unquoted name of the factor variable in data that names each row's series. Its levels fix the order of the series. A trend needs this column even for a single series. Defaults to series.

gr

An optional grouping factor in data. Each of its levels takes its own correlation matrix among the latent effects. Each matrix shrinks toward a global one by the weight alpha_cor_trend, as trend_constructors sets out. Without subgr, the series column names the series within each level.

subgr

A subgrouping factor in data naming the units within each level of gr, from which the series are built as trend_constructors describes. For species (species) counted at sites (site) in regions (region), time = site, gr = region and subgr = species correlate the species' latent effects within each region.

n_lv

The number of latent factors to estimate for dynamic factor models. When n_lv is smaller than the number of series, the latent processes are modelled as n_lv factors with estimated loadings onto the series. Defaults to NULL, in which case one latent process is used per series.

cor

Logical. Correlate the innovations of different series? TRUE estimates a full covariance matrix of the innovations when the data hold more than one series. AR() and RW() default to NULL. That means FALSE for an ungrouped trend and TRUE when gr names a grouping variable. VAR(), ZMVN() and grouped AR() and RW() trends always estimate correlations. They refuse cor = FALSE. CAR() defaults to FALSE.

In a factor model with every loading sampled, the factors take independent shocks. The loadings carry the correlation among series, which residual_cor() reports. A correlation among the factors would trade off against the loadings. AR(), RW() and LLT() refuse cor = TRUE there. A trend_map that fixes the loadings keeps the factors apart. cor = TRUE then estimates their correlation.

trend_map

Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:

  • a numeric ⁠n_series x n_lv⁠ matrix of loadings. NA entries are sampled and finite entries stay fixed. An all-NA matrix, such as matrix(NA, n_series, 2), fixes nothing and sets two factors.

  • a data.frame(series, trend) placing each series on one process, with a loading of one.

  • "identity", one process per series, or "shared", one process for every series.

Its columns set the number of factors, which an n_lv given too must match. Without a trend_map every loading is sampled and identified after sampling by a thin QR rotation (Heaps and Jermyn 2024). A map that fixes any loading takes no rotation. The loadings_prior of mvgam() accepts a map with no fixed entries. Defaults to NULL.

df

Degrees of freedom for the latent process innovations. Defaults to Inf, which gives Gaussian innovations: a t with infinite degrees of freedom is a normal. Set df = NA to estimate them, or supply a number above 2 to fix them.

Finite degrees of freedom let the latent process absorb an occasional large shock while sigma_trend stays at the scale of ordinary variation. That suits boom-and-bust population series and outbreak dynamics. The innovations follow a multivariate t. Because it shares one innovation scale across the series at each time point, large innovations tend to occur together. Each series keeps its own direction and magnitude. A shock in one series says nothing about the sign of the others. One series can also stay unmoved by an event that moves its neighbours. cor sets the correlation between series exactly as it does for Gaussian innovations. The degrees of freedom set how heavy the tails of the innovations are.

When df = NA the degrees of freedom are estimated as nu_trend, with a default gamma(4, 0.3) prior. The prior argument replaces it, for example prior(gamma(2, 0.1), class = "nu_trend"). get_prior lists nu_trend with the other trend classes.

Three caveats apply:

  • A fixed value must exceed 2. Below it the innovations have no finite variance. An autoregressive trend then has no stationary covariance to start from.

  • The first states of an autoregressive trend take the stationary mean and covariance. Under t innovations the true stationary distribution has heavier tails than that.

  • Only the tails of the latent process inform the degrees of freedom. Below roughly 200 time points their posterior stays close to the prior.

VAR() samples its states directly and PW() has no innovations. Neither takes df.

centred

Logical. Sample the latent states directly rather than their innovations? Default FALSE. The model and its posterior are the same. See Centred states below.

Value

An object of class mvgam_trend.

Identification

A factor model with sampled loadings fits equally well under any reordering or sign change of its factors. Some models also fit equally well under any rotation. mvgam reports one version, chosen by the dynamics of the factors:

Post-fit methods use the identified loadings and factor paths. shared_variation() and residual_cor() are the same under every version.

A trend_map keeps its fixed entries on Z exactly. A by = lv_axis() smooth ties each factor to its own covariate effect. Neither takes a rotation. For a model with every loading sampled, the loadings_prior argument of mvgam() replaces the default iid Student-t prior on Z with a structured matrix-normal prior. That prior is built from per-series features, pairwise distance matrices or both. See mvgam for its arguments.

Setting loadings_prior = "mgp" (or loadings_prior = list(column_shrinkage = "mgp")) switches the column scaling to the multiplicative gamma process prior of Bhattacharya & Dunson (2011), which shrinks later columns of Z toward zero with increasing strength. n_lv is then a truncation ceiling on the factor count. active_factors reports the posterior distribution of the number of active factors.

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

See Also

jsdgam() fits ZMVN() factors across species. residual_cor() and ordinate() interpret the fitted correlations. The dynamic factor vignette builds factor models with a partial trend_map. The integrated distribution model article shares one latent process across several observation families.

Other trend models: LLT(), PW(), list_trend_types(), lv_axis(), print.mvgam_trend()

Examples

## Not run: 
# Simulate counts of four series whose latent effects are correlated
# at each time point but independent over time.
set.seed(2)
simdat <- sim_mvgam(
  family       = poisson(),
  n_series     = 4L,
  n_timepoints = 120L,
  trend_model  = ZMVN(),
  prop_trend   = 0.9
)

mod <- mvgam(
  y ~ 1,
  trend_formula = ~ ZMVN(),
  data          = simdat$data_train,
  family        = poisson(),
  chains        = 2,
  silent        = 2
)
summary(mod)

# The correlations among the series that ZMVN() estimates
rc <- residual_cor(mod)
rc
plot(rc)

# Next: jsdgam() fits ZMVN() factors across many species

## End(Not run)


Posterior count of the latent factors a model uses

Description

A factor model fitted with n_lv factors may need fewer. This function counts the factors whose variance the data support. It suits a fit under the multiplicative gamma process (MGP) prior, loadings_prior = "mgp" (Bhattacharya and Dunson 2011). That prior shrinks surplus factors toward zero. n_lv then acts as a ceiling. The function applies to every factor model. Under other loadings priors a surplus factor keeps the variance its prior gives it. The count can then exceed the number of factors the data need.

Usage

active_factors(object, ...)

## S3 method for class 'mvgam'
active_factors(
  object,
  criterion = c("relative", "cumulative"),
  threshold = NULL,
  prob = 0.5,
  ...
)

## S3 method for class 'mvgam_active_factors'
plot(x, ...)

Arguments

object

A fitted mvgam object whose trend includes at least two latent factors (n_lv >= 2).

...

Unused. Anything passed here is refused.

criterion

The activity rule: "relative" (the default) or "cumulative". Details describes each.

threshold

Numeric in ⁠(0, 1]⁠, the cut-off of criterion. NULL (the default) takes 0.1 for "relative" and 0.9 for "cumulative".

prob

Numeric in ⁠(0, 1)⁠. A dimension is reported active when its posterior probability of activity is at least prob. Defaults to 0.5.

x

An mvgam_active_factors object.

Details

The factors give the series the covariance Z \Omega Z^\top, where Z holds the loadings and \Omega the covariance of the latent states. Its eigenvalues \lambda_1 \ge \lambda_2 \ge \dots are the variances along its principal dimensions. Each posterior draw gives one set. The eigenvalues stay the same when the factors are rotated or relabelled, which the individual columns of Z do not.

Two rules decide whether dimension k is active in a draw:

"relative"

The dimension holds at least threshold times the variance of the leading one, \lambda_k \ge threshold \lambda_1. The default threshold is 0.1. The rule counts any number of factors of similar size.

"cumulative"

The dimension is among the fewest leading dimensions whose variance reaches a share threshold of the total. The default threshold is 0.9. The count is the number of factors a scree plot would keep.

prob_active is the posterior probability that a dimension is active. A dimension with prob_active >= prob is reported active. The count is summarised over the per-draw counts.

Both rules compare the factors with one another. The leading dimension is always active, which makes the count at least one. A model whose factors hold almost no variance still reports one. shared_variation() gives the size of that variance on the scale of the linear predictor.

Value

A list with class mvgam_active_factors containing:

print() reports the posterior median count with its 95% interval. plot() draws the posterior probability that each dimension is active, largest first, with a dashed line at prob.

Author(s)

Nicholas J Clark

References

Bhattacharya, A. and Dunson, D. B. (2011). Sparse Bayesian infinite factor models. Biometrika, 98(2), 291-306. doi:10.1093/biomet/asr013.

See Also

shared_variation() reports the covariance the factors give the series. compare_loadings() compares the loadings under two priors. The JSDM article fits an MGP prior and counts its active factors.

Other latent dynamics: compare_loadings(), fevd.mvgam(), irf.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Counts of 20 species at 100 sites, driven by two latent factors.
# Each species has its own intercept and response to `env`.
simdat <- sim_jsdgam(family = brms::negbinomial(), n_species = 20L,
                     n_sites = 100L, n_lv = 2L, seed = 3L)

# Up to five factors under the MGP prior, which shrinks the factors
# the data do not need
mod <- jsdgam(
  y ~ env * series,
  data           = simdat$data_train,
  family         = brms::negbinomial(),
  n_lv           = 5L,
  loadings_prior = "mgp",
  chains         = 2,
  silent         = 2
)

# Dimensions holding at least a tenth of the leading one's variance
af <- active_factors(mod)
af
plot(af)

# The fewest dimensions that explain 90 percent of the variance
active_factors(mod, criterion = "cumulative")

# Next: ordinate() plots the species on the leading factors

## End(Not run)


Augment an mvgam object's training data with fitted values and residuals

Description

The training data with posterior summaries of the fitted value and residual of each row, under broom's column names.

Usage

## S3 method for class 'mvgam'
augment(
  x,
  robust = FALSE,
  conf.int = TRUE,
  conf.level = 0.95,
  resp = NULL,
  ...
)

Arguments

x

A fitted mvgam object.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

conf.int

Logical. TRUE (the default) adds the credible interval columns .lower, .upper, .resid.lower and .resid.upper.

conf.level

Numeric. Probability covered by the credible interval reported in conf.low / conf.high. Defaults to 0.95.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

...

Unused. Anything passed here is refused.

Value

A tibble (or list, when class(x$data) == "list") with the original training data plus:

Closure-unit families (nmix(), occ())

.fitted is the expected count of each visit: psi * p for occ() and lambda * p for nmix(). residuals.mvgam() computes one residual per closure unit, a site in a season, from the PIT of the summed visit counts. Each visit row of a unit repeats that residual. The .unit column names the unit.

See Also

fitted.mvgam(), residuals.mvgam()

Other tidiers: glance.mvgam(), tidy.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# The training data with fitted values and residuals appended
aug <- augment(mod)
head(aug)

# Residuals against fitted values, from one tibble
library(ggplot2)
ggplot(aug, aes(.fitted, .resid)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_point(colour = "#8F2727", alpha = 0.6) +
  labs(x = "Fitted", y = "Residual") +
  mvgam_theme()

# Next, glance() summarises the whole fit in one row

## End(Not run)


Beta negative binomial family for heavy-tailed counts

Description

A three-parameter count family that mixes the negative binomial success probability over a Beta distribution. The tail follows a power law. It suits outbreak counts and boom-bust population series, where a negative binomial fits the bulk of the data but repeatedly underpredicts the largest observations.

Usage

beta_nb()

Details

The family is parameterised with mu as the mean:

Y \mid p \sim \mathrm{NegBinomial}(r, p), \quad p \sim \mathrm{Beta}(1 + \tau, \mu \tau / r)

where r is shape and \tau is mtail. Writing Stan's native first Beta parameter as \alpha = 1 + \tau makes the mean finite by construction. E[Y] = \mu requires \alpha > 1.

The variance is finite only when mtail exceeds 1. Below that value, the family is heavy-tailed. This is the behaviour the family exists to provide. It has two consequences worth knowing. Randomised quantile residuals, the default in residuals.mvgam(), are unaffected. They need only the distribution function. Moment-based scoring is affected. score(..., score = "dss") assumes a finite predictive variance. Avoid it when the posterior for mtail places appreciable mass below 1. Prefer "crps", "drps" or "logs".

As mtail grows the family converges to the negative binomial with the same shape. A posterior for mtail that runs off toward its prior upper range is evidence that the extra tail parameter is not needed.

Value

A customfamily object for use with mvgam().

Distributional parameters

mu

Mean of the response, with a log link.

shape

Negative binomial shape r, log link, positive. Default prior gamma(2, 0.5).

mtail

Tail parameter \tau = \alpha - 1, log link, positive. Smaller values give heavier tails; values below 1 give infinite variance. Default prior gamma(2, 0.25).

Censoring and truncation

The Stan code supplies the distribution function as well as the density. The cens() and trunc() addition terms work as they do for the built-in count families.

Two limits are worth knowing. The distribution function accumulates the mass function term by term. Its cost and the length of the automatic-differentiation tape both grow linearly in the count at which it is evaluated. At the counts these models usually see this is unnoticeable. A censoring bound in the thousands dominates the gradient evaluation. One in the millions is impractical.

Right censoring also needs the upper tail, which is computed as log1m_exp() of the distribution function. That subtraction loses precision once the survival probability approaches the accumulated rounding error, roughly when 1 - F(y) falls below y * 5e-16. A censoring bound placed far into the tail of a light-tailed fit can return a survival probability of zero. A small positive value is the correct result there. Heavy-tailed fits, the purpose of this family, keep 1 - F(y) large. They are unaffected.

References

Irwin, J. O. (1968). The generalized Waring distribution applied to accident theory. Journal of the Royal Statistical Society A, 131(2), 205-225. doi:10.2307/2343842

See Also

brms::negbinomial(), which this family approaches as mtail grows. tweedie() covers non-negative continuous responses with a point mass at zero.

Other observation families: categ(), com_binomial(), diri(), multi(), mvgam_families, mvn(), mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# Counts drawn from the mixture in Details: a negative binomial
# whose success probability follows a Beta distribution. The tail
# is set by `mtail = 2`, the bulk by `shape = 3`.
set.seed(1)
n <- 300
dat <- data.frame(x = rnorm(n), time = seq_len(n))
mu <- exp(1 + 0.5 * dat$x)
p <- rbeta(n, 1 + 2, mu * 2 / 3)
dat$y <- rnbinom(n, size = 3, prob = p)

mod <- mvgam(y ~ x, data = dat, family = beta_nb(), chains = 2,
             silent = 2)

# The posteriors recover `shape` and `mtail`. A negative binomial
# is the limit of a large `mtail`.
summary(mod)
mcmc_plot(mod, variable = c("shape", "mtail"), type = "areas")

## End(Not run)

The BibTeX entries of a how_to_cite object

Description

Joins the BibTeX entries of how_to_cite() into one string. It is printed, or written to file.

Usage

bibtex(x, ...)

## S3 method for class 'how_to_cite'
bibtex(x, file = NULL, other = TRUE, ...)

Arguments

x

A how_to_cite object.

...

Unused. Anything passed here is refused.

file

Optional path of a .bib file to write the entries to in place of printing them.

other

Logical. TRUE (the default) includes the related references. FALSE keeps the references the methods text cites.

Value

The string of entries separated by blank lines, invisibly.

See Also

how_to_cite() builds the object, with an example of both. methods_md() writes the model's equations.

Other posterior summaries: VarCorr.mvgam(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()


Simulated weekly bird song counts with hierarchically correlated AR(1) trends

Description

A multivariate count time series for four bird species observed weekly across 80 weeks. Each species has its own AR(1) latent trend; the four series are coupled through a contemporaneous innovation correlation matrix. Two species (warbler, thrush) rise together; two (wren, finch) move opposite to them. A shared cyclic seasonal smooth is added on week-within-year.

Usage

birdsong

Format

A data.frame with 320 rows and the following fields:

series

factor identifying the species (warbler, thrush, wren, finch); duplicated as species for readability.

time

integer week index from 1 to 80.

y

integer weekly count (Poisson sampled); duplicated as count.

species

factor, alias of series.

week

integer week index, alias of time.

week_in_year

integer week within the annual cycle (1..52), used for the shared seasonal smooth.

count

integer weekly count, alias of y.

Details

An independent-AR fit (trend_formula = ~ AR(p = 1)) treats the four trajectories as unrelated. trend_formula = ~ AR(p = 1, cor = TRUE) recovers the cross-species correlation that couples them.

True generative components:

See Also

AR() for the trend, residual_cor() to extract the fitted correlations between species, mvgam_data() to check the data.

Examples

data(birdsong)
mvgam_data(birdsong, family = poisson())

## Not run: 
# A model with the structure the data were simulated from
mod <- mvgam(
  formula = y ~ s(week_in_year, bs = "cc", k = 8) +
                s(species, bs = "re"),
  trend_formula = ~ AR(p = 1, cor = TRUE),
  data = birdsong,
  family = poisson(),
  chains = 2, silent = 2
)
summary(mod)

## End(Not run)

Bridge sampling and Bayes factors for mvgam fits

Description

Estimates the log marginal likelihood of a fit by bridge sampling (Gronau, Singmann and Wagenmakers 2020) and compares two fits by their Bayes factor. The marginal likelihood weighs how well a model explains the data under its prior. loo.mvgam() and lfo_cv.mvgam() score predictions of held-out data instead. A Bayes factor sets no forecast horizon, which makes it a complement to leave-future-out scores for state-space models. It also depends on the priors, which predictive scores barely do.

Usage

## S3 method for class 'mvgam'
bridge_sampler(samples, recompile = FALSE, ...)

## S3 method for class 'mvgam'
bayes_factor(x1, x2, log = FALSE, ...)

Arguments

samples

An mvgam fit. The name follows the bridgesampling generic.

recompile

Logical. Bridge sampling evaluates the density through a compiled rstan model. A fit without one, sampled by cmdstanr or loaded with readRDS() in a new session, has one compiled, with its draws kept. TRUE compiles one for any fit. Defaults to FALSE.

...

Arguments of bridgesampling::bridge_sampler(), such as method, repetitions or cores.

x1, x2

mvgam fits, or bridge objects returned by bridge_sampler(), to compare.

log

Logical. TRUE returns the log Bayes factor.

Details

The Stan program must keep the normalising constants of its densities. mvgam builds it that way by default. A fit built with normalize = FALSE is refused. Bridge sampling also needs the draws of every parameter, which a fit keeps under save_pars = save_pars(all = TRUE).

Value

bridge_sampler() returns a bridge object holding the log marginal likelihood in logml. bayes_factor() returns a bayes_factor object.

Multivariate fits

The Stan program of an mvbf() fit has one joint log posterior over every response. bridge_sampler() then estimates the joint log marginal likelihood \log p(y_{1}, \ldots, y_{K} \mid \mathrm{model}). The variance of the estimate grows with the number of parameters. For multi-response, factor or VAR fits, pass repetitions above 1 or method = "warp3" when the default method reports a high re2 (relative squared error).

Author(s)

Nicholas J Clark

References

Gronau QF, Singmann H and Wagenmakers E-J (2020). bridgesampling: An R package for estimating normalizing constants. Journal of Statistical Software. 92(10).

See Also

loo.mvgam(), lfo_cv.mvgam(). The forecast evaluation article compares models by their forecasts.

Other model comparison: compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 80L, trend_model = AR())

# Bridge sampling needs many draws and every parameter's draws. It
# evaluates the density through rstan. A fit sampled by rstan needs
# no second compile.
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                save_pars = save_pars(all = TRUE), backend = "rstan",
                chains = 2, iter = 3000, silent = 2)
mod_rw <- update(mod_ar, trend_formula = ~ RW())

# The log marginal likelihood of each model
bs_ar <- bridge_sampler(mod_ar, silent = TRUE)
bs_rw <- bridge_sampler(mod_rw, silent = TRUE)
bs_ar

# A Bayes factor above 1 favours the AR(1) trend. Passing the
# bridge objects reuses their estimates.
bayes_factor(bs_ar, bs_rw)

# Next, compare their forecasts with loo() or lfo_cv()

## End(Not run)


Categorical family for one category observed per unit

Description

For a single category recorded on each unit, such as the dominant species at a site. The data hold one row per category at each unit, with response 1 on the observed category and 0 on the others. The observed category is categorical with probabilities softmax(mu), where mu holds the categories' linear predictors.

Usage

categ()

Details

jsdgam() fits the family, taking the unit and category columns and the number of latent factors n_lv. The constraints that identify the model are those of diri(). A unit holds one trial. It informs the factor loadings less than a multi() unit of many counts does. Recovering the residual correlations needs more units.

Value

A family object to pass to jsdgam() or mvgam().

Identification

The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:

A loadings_prior combines with that constraint.

Post-fit conventions

The density is joint over a unit's components, which makes the unit the grain of log_lik(), loo() and waic() (Vehtari et al. 2017). log_lik() gives each unit's log density on its first row and NA on the others. loo() then counts each unit once. loo_compare() needs every model it compares scored at that grain.

posterior_linpred() gives mu per row before the reference subtraction. posterior_epred() gives the expected shares, which sum to one within each unit.

species_effects(), variance_partition() and forecast_uncertainty(scale = "link") report the predictor centred across each unit's components, the centred log-ratio scale. A shift shared by every component then drops out.

References

Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007

See Also

Other observation families: beta_nb(), com_binomial(), diri(), multi(), mvgam_families, mvn(), mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# The one category observed at each of 150 sites
simdat <- sim_jsdgam(family = categ(), n_species = 3L,
                     n_sites = 150L, seed = 4L)

fit <- jsdgam(
  formula        = y ~ env * series,
  factor_formula = ~ -1,
  data           = simdat$data_train,
  unit           = time, species = series,
  family         = categ(),
  n_lv           = 1L,
  chains         = 2L,
  silent         = 2
)

# The probability of each category along the gradient
conditional_effects(fit, effects = "env:series")

# Next, pp_check(fit) compares observed and replicated categories

## End(Not run)


Validate newdata against the training data of an mvgam model

Description

Runs the structural checks that predict.mvgam() and forecast.mvgam() apply to a newdata frame. A misaligned frame is refused before an expensive prediction. The trend constructor in trend_formula names the time and series columns, time and series by default. Each of them the training data holds must also be in newdata. A hierarchical trend identifies its series by its gr and subgr columns. Those columns are then required. Series levels absent from the training data are refused. The series column of newdata is coerced to the training levels. The prediction functions check the columns the formulas use.

Usage

check_newdata(newdata, data, trend_formula = NULL)

Arguments

newdata

A data.frame of prediction covariates in the same shape as the training data.

data

The training data.frame of the model, whose series levels define the valid set. A fitted model from mvgam() or jsdgam() is also accepted. newdata is then checked against every column the fitted formulas use. trend_formula is then ignored.

trend_formula

The trend formula passed to mvgam(), or NULL for a model without a trend.

Value

newdata with its series column coerced to the training factor levels, returned invisibly, or NULL (invisibly) when newdata is NULL. Checked against a fitted model, newdata is returned with the columns that model predicts from.

See Also

predict.mvgam(), forecast.mvgam()

Other model fitting: jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

train <- data.frame(
  species = factor(rep(c("a", "b"), each = 3L)),
  week = rep(1:3, times = 2L),
  y = rnorm(6L)
)
test_weeks <- data.frame(
  species = factor(rep(c("a", "b"), each = 2L)),
  week = rep(4:5, times = 2L)
)
check_newdata(test_weeks, train, ~ AR(time = week, series = species))

# A species the model never saw is refused.
test_weeks$species <- factor(rep(c("a", "c"), each = 2L))
try(check_newdata(test_weeks, train, ~ AR(time = week, series = species)))

Diagnose whether the Tweedie series-truncation M is adequate

Description

Computes the per-observation Poisson rate lambda = mu^(2 - theta) / ((2 - theta) * phi) at the posterior mean of ⁠(mu, mphi, mtheta)⁠ and compares it against the truncation count M saved in the fit's standata. Warns if max(lambda) exceeds 0.7 * M, the rough point at which the log_sum_exp over ⁠m = 1..M⁠ starts to omit appreciable Poisson tail mass and bias the log-density downward.

Usage

check_tweedie_truncation(object, resp = NULL)

Arguments

object

An mvgam fit with at least one response whose family is tweedie().

resp

Optional name of one response to check. Without it, every tweedie() response is checked.

Details

The rate is taken for every response whose family is tweedie(). A multivariate model can name it for one response among several. All of them share the one M. mphi and mtheta are taken per observation. This covers a parameter given a formula of its own as well as a scalar one.

Value

Invisible NULL. Emits a message on the adequacy of M. It also emits a warning if M looks tight.

See Also

tweedie() for the family and its argument M.

Examples

## Not run: 
set.seed(3)
simdat <- sim_mvgam(family = tweedie(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = tweedie(),
             chains = 2, silent = 2)

# The largest Poisson rate the fit implies, against the default M = 30
check_tweedie_truncation(mod)

# A warning here would call for a refit with a longer series, such
# as family = tweedie(M = 60)

## End(Not run)


Conway-Maxwell-Binomial family for over-, equi-, under-, and super-dispersed bounded counts

Description

A two-parameter generalisation of the binomial that exponentiates the binomial coefficient by a real-valued dispersion parameter nu. nu = 1 is the standard binomial. nu > 1 under-disperses, concentrating mass near the mode. ⁠0 < nu < 1⁠ over-disperses. nu < 0 super-disperses, producing bimodal "all-or-nothing" mass at the boundaries. Useful when a binomial fit shows systematic lack-of-fit in either tail and the response is bounded by a known trial count.

Usage

com_binomial(link = "logit")

Arguments

link

Link function for the success probability p. Currently logit only. The COM-Binomial PMF factorises cleanly only against the canonical logit parameterisation. For that reason, probit and cloglog are not exposed.

Value

A brms::custom_family() object suitable for the family argument of mvgam() / jsdgam(). The object has an attr(., "mvgam_stanvars") attribute, which holds the Stan function-block stanvar. mvgam's setup attaches it automatically.

Distributional parameters

mu

logit-scale success probability (link = logit). Distributional regression on mu is the standard formula side: bf(y | trials(trials) ~ x).

nu

real-valued dispersion exponent (link = identity, lb = -5). nu = 1 is binomial. Distributional regression is supported via bf(y | trials(trials) ~ x, nu ~ z). The support is 0:T, a finite range. The normalising sum runs over T + 1 positive terms at every real nu, which keeps the density proper with no lower bound on it. lb = -5 is a numerical floor. The log factorial term grows with -nu. Gradients past that point are hard for the sampler. A scalar nu carries the floor as ⁠real<lower=-5>⁠ with a prior truncated to match. A modelled nu is a linear predictor and carries no such declaration, leaving nu[n] free. Hold the predictor inside the range the data resolve, roughly ⁠(-1, 4)⁠.

Default priors

Sampler notes

Two corners of ⁠(p, nu)⁠ parameter space stress HMC and should be monitored:

Inspect mcmc_plot(fit, variable = "nu", type = "trace") and the R-hat + ESS on both nu and the intercept; if either degrades, tighten the prior on nu or shift the design to bias p away from 0.5.

Author(s)

Nicholas J Clark, Julijus Bogomolovas

References

Shmueli, G., Minka, T. P., Kadane, J. B., Borle, S. and Boatwright, P. (2005). A useful distribution for fitting discrete data: revival of the Conway-Maxwell-Poisson distribution. Journal of the Royal Statistical Society Series C, 54:127-142.

Conway, R. W. and Maxwell, W. L. (1962). A queuing model with state dependent service rates. Journal of Industrial Engineering, 12:132-136.

See Also

custom_family, tweedie

Other observation families: beta_nb(), categ(), diri(), multi(), mvgam_families, mvn(), mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# Counts out of 10 trials, simulated with `nu = 3`. At `nu = 1`
# the family is the binomial. Values above 1 give counts with
# less spread than a binomial.
set.seed(1)
sim <- sim_mvgam(
  family       = com_binomial(),
  n_series     = 1L,
  n_timepoints = 160L,
  trend_model  = "None",
  family_pars  = list(nu = 3, trials = 10L)
)

# The denominator enters through brms's `trials()` term
fit <- mvgam(
  bf(y | trials(trials) ~ s(x)),
  data   = sim$data_train,
  family = com_binomial(),
  chains = 2,
  silent = 2
)

# The posterior for `nu` lies above the binomial's value of 1
summary(fit)
mcmc_plot(fit, variable = "nu", type = "areas")
pp_check(fit, type = "bars", ndraws = 50)

## End(Not run)

Community quantities from a fitted model

Description

Computes quantities of a whole community, draw by draw, from a model of many series. A community is every series at one site and time. Each gets its expected number of species, its diversity and its community-weighted mean traits. Each species gets its probability of presence. Each pair of species gets how often it occurs together beyond what the covariates predict. Pass newdata as a covariate gradient, such as one from datagrid(), to see how the community changes along it.

Usage

community(object, ...)

## S3 method for class 'mvgam'
community(
  object,
  newdata = NULL,
  ...,
  threshold = NULL,
  traits = NULL,
  latent = c("marginal", "conditional", "forecast", "zero"),
  n_nodes = 100L,
  ndraws = NULL,
  draw_ids = NULL,
  resp = NULL,
  prob_threshold = 0.95
)

## S3 method for class 'mvgam_community'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_community'
as_draws_rvars(x, ...)

## S3 method for class 'mvgam_community'
as_draws_df(x, ...)

## S3 method for class 'mvgam_community'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_community'
plot(
  x,
  type = c("richness", "diversity", "cooccurrence"),
  along = NULL,
  supported_only = FALSE,
  ...
)

Arguments

object

A fitted mvgam object.

...

Unused. Anything passed here is refused.

newdata

Data frame with one row per community, holding its covariates. Each row is crossed with every fitted series, which replaces any series column it holds. NULL takes the communities of the training data, or under latent = "forecast" those of the data held out at fit time. Such a community is the rows sharing a time and any other key of the family's units, such as the site of a multi-season occ() fit.

threshold

A species counts as present when its response exceeds threshold. NULL (the default) takes zero, which a count or binary family needs. A continuous family needs a value, such as a biomass. Under nmix() it applies to the latent abundance.

traits

Species traits for community-weighted means: a data frame with one row per species, matched as jsdgam() matches its traits, or "auto" for the traits the fit was built with, those of traits or else of trait_slopes. NULL (the default) computes none.

latent

How the latent state enters. "marginal" (the default) averages over it. "conditional" takes the state the model fitted, for communities in the training data. "forecast" propagates the fitted state to communities after the training data. "zero" sets it to zero, a typical site. See Latent state.

n_nodes

Number of latent states each draw averages over under latent = "marginal" or "forecast".

ndraws, draw_ids

The posterior draws to use, as hindcast.mvgam() takes them. NULL for both uses every draw.

resp

The response to report, needed on a model with several.

prob_threshold

The posterior probability of its sign a pair's excess co-occurrence needs to count as supported, at least 0.5 and below 1. Defaults to 0.95. It sets the sig column of the co-occurrence table and the pairs plot() outlines.

probs

Interval probabilities of the tables. Defaults to c(0.025, 0.975).

x

An mvgam_community object from community().

digits

Integer number of significant digits. Defaults to 2.

type

"richness" (the default) draws richness along a column of the communities. "diversity" draws each diversity measure. "cooccurrence" draws each pair's median excess co-occurrence, outlining a pair whose prob_nonzero exceeds prob_threshold.

along

The column of the communities to draw along. NULL takes the first numeric column that varies.

supported_only

Logical, for type = "cooccurrence". TRUE leaves blank every pair whose prob_nonzero is at most prob_threshold. Defaults to FALSE.

Details

Richness. Each draw sums the species' probabilities of presence, giving the expected number present. A count family's probability is one less its probability of a zero, which covers zero inflation and hurdles. Under occ() it is the occupancy probability and under nmix() the probability that the latent abundance exceeds threshold. Richness counts the species the model holds.

Latent state. Species share their latent factors or trends, which move them together. Because presence is a non-linear function of the latent state, a typical site differs from an average one. Under latent = "marginal" each draw averages presence over n_nodes latent states drawn from the trend's stationary covariance across series. The draws of the latent state are shared by every community, which makes a difference between communities free of their noise. A RW() or LLT() trend has no stationary covariance. Each draw then averages over the latent states it fitted at the training times.

Under latent = "forecast" each draw propagates its last fitted state n_nodes times with fresh innovations, as forecast_uncertainty() does. Presence is averaged over these paths. The communities need times after the training data. Communities at one time share the paths. A pair's excess co-occurrence then comes from the uncertainty in the forecast state, which grows with the horizon.

Diversity. A family with an abundance, such as a count or a biomass, weights each species by its expected value. Under nmix() the weight is the latent abundance. Hill numbers of order one and two (the exponential of Shannon entropy and inverse Simpson) follow from the relative weights. A binary or occupancy family has no abundance. Its weight is the probability of presence, which gives the expected trait of the species present. Hill numbers are then left out. Each measure is averaged over the latent states, giving the expected value at one site. Under a count family the weights confound abundance with detection.

A factor trait gives one column per level, whose weighted mean is the share of that level.

Co-occurrence. Species sharing a latent state appear together more or less often than their covariates alone predict. A pair's excess co-occurrence is the probability that both are present less the product of their probabilities, averaged over the communities. A pair the latent state moves independently has none. Neither does any pair under latent = "conditional" or "zero", which fix the state.

Value

An object of class mvgam_community. print() gives each community's richness. summary() takes probs and returns a list of tibbles, each with its median and interval. richness and diversity hold one row per community, presence one per community and series and cooccurrence one per pair of species. plot() draws richness or diversity along a column of newdata, or the excess co-occurrence of each pair.

as_draws_rvars() returns the posterior draws as posterior::rvar()s, ready for arithmetic between communities and for posterior::summarise_draws(). Community i is row i of the object's communities element.

richness

one per community

presence

⁠[community, species]⁠, NA where a community lacks the species

diversity

⁠[community, measure]⁠, one measure per Hill number and trait, when there are any

cooccurrence

⁠[species, species]⁠ excess co-occurrence

as_draws_df() returns the same draws as a data frame, one column per element.

Author(s)

Nicholas J Clark

See Also

residual_cor() for the associations between species, species_effects() for each species' response to the covariates, variance_partition() for what moves each species

Examples

## Not run: 
# Detections of 6 species at 80 sites, 4 visits each. Occupancy
# responds to the site covariate `env` and detection to the time of
# day `tod_c`. Two latent factors drive the species associations.
simdat <- sim_closure_unit_data(
  family    = occ(),
  n_species = 6L,
  n_sites   = 80L,
  n_visits  = 4L,
  n_lv      = 2L,
  seed      = 1L
)

# A joint occupancy model. Each species has its own occupancy
# intercept and `env` slope, plus its own detection intercept. Two
# latent factors take up the residual association.
mod <- jsdgam(
  formula        = bf(y ~ series * env, p ~ series + tod_c),
  factor_formula = ~ -1,
  data           = simdat$data_train,
  family         = occ(),
  n_lv           = 2L,
  chains         = 2,
  silent         = 2
)

summary(mod)

# The effect of `env` on the chance of a detection, occupancy times
# detection
conditional_effects(mod)

# Each species' response to env, outlined where its sign is clear
plot(species_effects(mod, variables = "env"))

# The residual correlations among species the factors imply
plot(residual_cor(mod))

# Site scores and species loadings on the two factors
ordinate(mod, rotation = "varimax")

# Expected richness along `env`. The second plot marks the pairs of
# species found together more often than `env` predicts.
gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20))
cm <- community(mod, newdata = gradient)
plot(cm)
plot(cm, type = "cooccurrence")

# The draws, for any contrast: richness at the end of the gradient
# less that at its start
rv <- as_draws_rvars(cm)
rv$richness[20] - rv$richness[1]

# Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo()

## End(Not run)


Tidy comparison of leave-future-out ELPDs across mvgam_lfo runs

Description

Stacks the per-step ELPDs from several mvgam_lfo objects into one long-format tibble, with one row per model and evaluation time.

Usage

compare_elpds(..., model_names = NULL)

## S3 method for class 'mvgam_compare_elpds'
plot(x, relative = NULL, cumulative = FALSE, ...)

Arguments

...

Two or more mvgam_lfo objects from lfo_cv(). Argument names are taken from the call.

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

x

An mvgam_compare_elpds object.

relative

Optional name of a model in x$model. Each ELPD is then drawn less that model's at the same origin, with a dashed zero line. Positive values favour the other model. The baseline itself is left out.

cumulative

Logical. TRUE draws the running sum of the ELPD over the origins, the quantity loo_compare() sums. Defaults to FALSE.

Value

A tibble with columns:

plot() draws each model's ELPD by origin. Hollow points mark the origins where a Pareto k above the threshold forced a refit.

Author(s)

Nicholas J Clark

See Also

lfo_cv(), loo_compare.mvgam_lfo(), loo_model_weights.mvgam_lfo(), compare_scores()

Other model comparison: bridge_sampler.mvgam(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
# Each origin after t = 70 forecasts the next time step. The
# pointwise log densities feed stacking weights
lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE)
lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE)

# One row per model and origin
elpds <- compare_elpds(lfo_gam, lfo_ar, model_names = c("GAM", "AR"))
head(elpds)

# The running sum of the AR model's ELPD minus the GAM's. Hollow
# points mark the origins where the model was refitted
plot(elpds, relative = "GAM", cumulative = TRUE)

# Next, loo_compare() sums the ELPDs with a standard error

## End(Not run)


Compare posterior loadings between two latent-factor fits

Description

Side-by-side comparison of the posterior-median species loadings from two latent-factor mvgam / jsdgam fits on the same set of species. Two fits need not order or orient their factors alike, and a direct overlay of their loadings would mislead. compare_loadings() applies the orthogonal Procrustes solution (Schoenemann 1966) that rotates the posterior-median loadings of fit_b to best match those of fit_a in the least-squares sense, then either overlays both onto a single biplot with displacement segments (default) or splits them into two facets sharing axes.

Useful when teaching the effect of a structured loadings prior: fit one model with loadings_prior = NULL and a second with ⁠traits =⁠ or ⁠phylo =⁠, then plot the comparison to show how the trait or phylogeny similarity reshapes the latent positions.

Procrustes alignment is orthogonal: it rotates and reflects the loadings with their scale unchanged. A factor the model has shrunk towards zero has short loadings, close to the origin. The panel shows which species cluster together and how that arrangement moves between fits. active_factors() reports how many factors the data support.

Usage

compare_loadings(
  fit_a,
  fit_b,
  labels = c("fit_a", "fit_b"),
  which_lvs = c(1L, 2L),
  align = TRUE,
  facet = FALSE,
  label_species = c("all", "shift", "none"),
  ...
)

Arguments

fit_a, fit_b

Two fitted mvgam / jsdgam objects, each with n_lv >= 2 and the same species set in the same factor order.

labels

Optional length-2 character vector of fit labels shown in the legend / facet strips. Defaults to c("fit_a", "fit_b").

which_lvs

Integer vector of length 2 indicating which two latent factors to plot. Defaults to c(1, 2).

align

Logical. When TRUE (default) the posterior-median loadings of fit_b are rotated onto those of fit_a by orthogonal Procrustes before plotting. FALSE plots each fit with the factors it reports.

facet

Logical. When FALSE (default) both fits are overlaid on the same axes in different colours, with segments connecting the same species across fits. When TRUE, fits are drawn as side-by-side facets on shared axes.

label_species

Character. Controls which species are labelled. "all" (default) labels every species; "shift" labels the top 10 species by post-alignment displacement between fits; "none" draws unlabelled points only.

...

Unused. Anything passed here is refused.

Details

The orthogonal Procrustes rotation is the closed-form solution

R = U V^T

where U \Sigma V^T = SVD(Z_a^T Z_b) and Z_a, Z_b are the posterior-median loading matrices restricted to which_lvs. The aligned Z_b is Z_b %*% t(R). Alignment is a sufficient but not unique solution to factor rotation indeterminacy; alternative alignments (varimax on the joint matrix, sign-flip only) are possible but typically less interpretable for the prior-comparison use case here.

Both fits must report the same species in the same factor order; the function errors otherwise. To compare fits with different species sets, subset before fitting.

Value

A ggplot object.

Author(s)

Nicholas J Clark

References

Schoenemann PH (1966). A generalized solution of the orthogonal Procrustes problem. Psychometrika 31, 1-10. doi:10.1007/BF02289451

Heaps SE and Jermyn IH (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing 34, 143. doi:10.1007/s11222-024-10454-0

See Also

ordinate(), residual_cor(), active_factors()

Other latent dynamics: active_factors(), fevd.mvgam(), irf.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Counts of 10 species at 60 sites, driven by two latent factors
simdat <- sim_jsdgam(family = poisson(), n_species = 10L,
                     n_sites = 60L, n_lv = 2L, seed = 3L)
mod <- jsdgam(y ~ env * series, data = simdat$data_train,
              family = poisson(), n_lv = 2L, chains = 2, silent = 2)

# A trait that tracks each species' true loading on the first factor
set.seed(3)
traits <- data.frame(
  size = simdat$truth$loadings[, 1] + rnorm(10, sd = 0.2),
  row.names = levels(simdat$data_train$series)
)
mod_traits <- jsdgam(y ~ env * series, data = simdat$data_train,
                     family = poisson(), n_lv = 2L, traits = traits,
                     chains = 2, silent = 2)

# Grey segments join each species' loadings under the two priors
compare_loadings(mod, mod_traits,
                 labels = c("Default prior", "Trait prior"))

## End(Not run)


Tidy comparison of forecast scores across mvgam models

Description

Scores the forecasts of several models of the same held-out data with one rule, then stacks the results in one table for comparison. Lower scores are better. The table has one row per model, series and forecast horizon. A joint score ("energy", "variogram" or "twenergy") scores all series together. Its per-series rows hold NA. The rows with series == "all_series" hold its value.

Usage

compare_scores(..., score = "crps", model_names = NULL, score_args = list())

## S3 method for class 'mvgam_compare_scores'
plot(x, relative = NULL, facet = TRUE, ...)

## S3 method for class 'mvgam_compare_scores'
summary(object, ...)

## S3 method for class 'mvgam_compare_scores'
print(x, digits = 2L, ...)

Arguments

...

Two or more mvgam_forecast objects from forecast.mvgam(). A named argument, as in compare_scores(GAM = fc1, AR = fc2), names its model. An unnamed one takes the expression passed, such as "fc1".

score

Character name of the scoring rule. The section 'Available scores' of score.mvgam_forecast() lists them.

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

score_args

Optional named list of further arguments of score.mvgam_forecast(), such as score_args = list(interval_width = 0.6).

x

An mvgam_compare_scores object.

relative

Optional name of a model in x$model. Each score is then drawn less that model's at the same series and horizon, with a dashed zero line. Negative values favour the other model. The baseline itself is left out.

facet

Logical. TRUE (the default) gives a univariate score one panel per series. FALSE overlays the series, told apart by line type. A joint score ignores it.

object

An mvgam_compare_scores object.

digits

Integer number of significant digits. Defaults to 2.

Value

A tibble of class mvgam_compare_scores. Its print() method ranks the models by their mean score. Its columns are:

summary() returns the scores wide, one column per model and one row per series and horizon, or per horizon for a joint score. plot() draws each model's score by horizon. A univariate score takes one panel per series and a joint score one panel. An ensemble plots as one more model.

Author(s)

Nicholas J Clark

See Also

score.mvgam_forecast(), compare_elpds(), forecast.mvgam(), ensemble.mvgam_forecast()

Other forecasting: ensemble.mvgam_forecast(), forecast.mvgam(), forecast_uncertainty(), hindcast(), lfo_cv.mvgam(), score()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
fc_gam <- forecast(mod_gam, newdata = simdat$data_test)
fc_ar <- forecast(mod_ar, newdata = simdat$data_test)

# One row per model and horizon, scored by the discrete ranked
# probability score (lower is better)
scores <- compare_scores(fc_gam, fc_ar, score = "drps",
                         model_names = c("GAM", "AR"))
summary(scores)

# The AR model's DRPS minus the GAM's. Negative values favour the
# AR model
plot(scores, relative = "GAM")

# Next, ensemble() combines the two forecasts

## End(Not run)


Display conditional effects of predictors for mvgam models

Description

Plots how the prediction changes with each predictor, holding the other predictors at typical values. Predictors of the observation and trend formulas both count, as do interactions of up to three terms. Each effect gets one panel, drawn by marginaleffects::plot_predictions().

as.data.frame() returns the numbers the panels plot, one row per grid point of each effect. Use it to build a custom plot, overlay several fits or compare with a known truth. The columns are:

Usage

## S3 method for class 'mvgam'
conditional_effects(
  x,
  effects = NULL,
  type = "expected",
  points = FALSE,
  rug = FALSE,
  process_error = FALSE,
  series = NULL,
  resp = NULL,
  ...
)

## S3 method for class 'mvgam_conditional_effects'
plot(x, plot = TRUE, ask = FALSE, ...)

## S3 method for class 'mvgam_conditional_effects'
print(x, ...)

## S3 method for class 'mvgam_conditional_effects'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)

Arguments

x

A fitted mvgam object. The plot(), print() and as.data.frame() methods take the mvgam_conditional_effects object that conditional_effects() returns.

effects

Optional character vector of effects to plot. If NULL (the default), all main effects and interactions in the formula are detected automatically.

type

Scale of predictions. One of "response" (outcome scale with observation-process noise), "link" (link-scale linear predictor), "expected" (E[Y]; default), or one of the family-specific scales handled by predict.mvgam(): "variance", "latent_state", "detection". For occ() and nmix(), "latent_state" plots the state apart from detection: the probability of occupancy psi, or the expected abundance lambda. "detection" plots the detection probability p.

points

Logical or numeric. If TRUE (or a non-zero alpha between 0 and 1), raw observations are overlaid on the plot. The overlay applies where the drawn quantity shares the observations' scale, which covers type = "response" and type = "expected".

rug

Logical. If TRUE, rug tick marks are drawn along the axes, on the same scales the points overlay applies to.

process_error

Logical. Passed to plot_predictions() / get_predict.mvgam. With the default FALSE the trend contributes its covariate part. The panel then shows the covariate effect with the latent process held out. TRUE adds innovations drawn from the trend's long-run spread. The band then widens by that spread.

series

Which series the panels show. NULL (the default) draws one panel per effect at the reference series, as brms does for a grouping factor. A factor model whose trend_formula uses lv_axis() gives each series its own effect. NULL then draws a panel per series. "all" draws a panel per series for any model. A single integer or character value picks one series and filters the prediction grid to its observations.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

...

For conditional_effects(), further arguments of marginaleffects::plot_predictions(). A name that function does not take is refused. The plot() and print() methods ignore them. as.data.frame() refuses them.

plot

Logical. If TRUE (default), draws each plot; otherwise returns the list invisibly so callers can post-process.

ask

Logical. If TRUE, prompts before each new plot.

row.names, optional

Ignored.

Value

An object of class mvgam_conditional_effects: a named list with one ggplot per effect, drawn by the plot and print methods.

The plot() method returns, invisibly, a flat named list of ggplot objects, as brms::conditional_effects() plots return one. A multivariate fit's panels are named ⁠<response>.<effect>⁠, response by response.

Author(s)

Nicholas J Clark

References

Arel-Bundock, V., Greifer, N. and Heiss, A. (2024). How to interpret statistical models using marginaleffects for R and Python. Journal of Statistical Software, 111(9):1-32. doi:10.18637/jss.v111.i09

See Also

marginaleffects::predictions() returns the plotted values as a data frame. marginaleffects::avg_slopes() and marginaleffects::avg_comparisons() summarise effects as numbers. posterior_epred.mvgam() computes the expected values the panels draw. pp_check.mvgam() checks the fit against the data. The overview vignette interprets effects in both formulas.

Other predictions: conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# The effect of x on the expected count, with the observations
conditional_effects(mod, points = TRUE)

# The same effect on the log link scale
conditional_effects(mod, type = "link")

# The average slope of the expected count with respect to x
marginaleffects::avg_slopes(mod, variables = "x", type = "expected")

# Next: marginaleffects::plot_predictions() draws custom effect
# displays, such as one covariate conditional on another

## End(Not run)


Plots of each smooth term

Description

Summarises the posterior of every smooth over a grid of its own variables, in the shape brms::conditional_smooths() returns. Its plot() method draws a smooth of one variable as a line and ribbon, and a smooth of two as a heatmap.

Usage

## S3 method for class 'mvgam'
conditional_smooths(
  x,
  smooths = NULL,
  int_conditions = NULL,
  prob = 0.95,
  spaghetti = FALSE,
  surface = TRUE,
  facets = 3L,
  resolution = 100L,
  too_far = 0,
  ndraws = NULL,
  draw_ids = NULL,
  resp = NULL,
  ...
)

## S3 method for class 'mvgam_conditional_smooths'
plot(x, plot = TRUE, ask = FALSE, ...)

## S3 method for class 'mvgam_conditional_smooths'
print(x, ...)

Arguments

x

An object of class mvgam_conditional_smooths returned by conditional_smooths.mvgam().

smooths

The terms to summarise, as smooths.mvgam() lists them, or NULL for every smooth of every predictor, the trend's included.

int_conditions

A named list setting the grid of a variable: a vector of values, or a function of the variable's training values, such as stats::quantile().

prob

A number in ⁠[0, 1]⁠: the mass of the interval in lower__ and upper__.

spaghetti

Logical. TRUE keeps the draws of a smooth of one variable, which the plot draws as one line each.

surface

Logical. TRUE evaluates a smooth of two variables on a resolution by resolution grid, drawn as a heatmap. FALSE draws lines over the first variable at facets values of the second.

facets

An integer of at least 2: the number of values taken by the second variable and by a numeric by variable. They run evenly from one standard deviation below the mean to one above.

resolution

An integer of at least 2: the number of grid points along each variable.

too_far

A number in ⁠[0, 1]⁠. On a surface, grid points further than this from the training data, in the unit square, are dropped by mgcv::exclude.too.far(). 0 keeps every point.

ndraws, draw_ids

The number of posterior draws, or their indices. Give at most one. NULL for both uses every draw.

resp

The response whose smooths to summarise, or NULL for every response.

...

Unused. Anything passed here is refused.

plot

Logical. TRUE draws each panel. FALSE only returns them.

ask

Logical. TRUE prompts before each panel after the first.

Value

A list of class mvgam_conditional_smooths, one data frame per smooth, named by predictor and term. Each holds its grid with the columns estimate__, se__, lower__, upper__, effect1__ and cond__. A smooth of two variables adds effect2__.

The list of ggplot panels, one per smooth, invisibly.

Author(s)

Nicholas J Clark

See Also

posterior_smooths.mvgam() gives the draws of one smooth. conditional_effects.mvgam() plots covariate effects on the response.

Other predictions: conditional_effects.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# The smooth with 30 of its draws
cs <- conditional_smooths(mod, spaghetti = TRUE, ndraws = 30)
plot(cs)
head(cs[[1]])

# Next, plot(mod, type = "smooths") draws the same panels in one
# figure

## End(Not run)


Sampler control settings of a fitted mvgam model

Description

The NUTS settings the model was sampled with, such as adapt_delta, max_treedepth and stepsize. A fit that reported divergent transitions can be refitted with a higher adapt_delta, such as update(fit, control = list(adapt_delta = 0.95)). The sampler then takes smaller steps.

Usage

## S3 method for class 'mvgam'
control_params(x, ...)

Arguments

x

A fitted mvgam model.

...

Unused. Anything passed here is refused.

Value

A named list, as brms::control_params() returns for a brmsfit. A fit with no NUTS settings, such as a variational fit, gives an empty list.

See Also

mvgam_diagnostics for the divergence counts, summary.mvgam() for convergence checks.

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 60L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, seed = 2, silent = 2)
control_params(mod)$adapt_delta

## End(Not run)

Simulated coral bleaching surveys with an irregular CAR(1) state

Description

A state-space dataset for three coral reefs surveyed at irregular monthly intervals (gap distribution Uniform(1, 6) months, mean approximately 3.5). Each survey inspects between 20 and 40 colonies and counts those that have bleached. The latent state is a continuous-time AR(1) (CAR(1)) trend per reef with phi = 0.9 and sigma = 0.3 on the logit scale. The observation equation adds an observed sea-surface temperature (SST) driver through a smooth nonlinear effect.

Usage

coral_surveys

Format

A data.frame with 150 rows and the following fields:

series

factor identifying the reef (flynn, myrmidon, pixie); duplicated as reef.

time

integer month index (irregularly spaced within each reef).

y

integer count of bleached colonies; duplicated as bleaching.

reef

factor, alias of series.

sst

numeric observed sea-surface temperature in degrees Celsius.

bleaching

integer count of bleached colonies, alias of y.

colonies

integer number of colonies inspected, the binomial trials.

Details

A naive AR(1) treats every consecutive survey as one step. It gives a one-month gap and a six-month gap the same persistence. trend_formula = ~ CAR() with the supplied time column decays the state by the length of each gap. Its ar1_trend measures the persistence over the median gap between surveys, three months here. The simulated value is 0.9^3 = 0.73.

True generative components, on the logit scale:

See Also

CAR() for the trend, AR() for evenly spaced surveys, mvgam_data() to check the data.

Examples

data(coral_surveys)
mvgam_data(coral_surveys, formula = y | trials(colonies) ~ s(sst),
           family = binomial())

## Not run: 
# A model with the structure the data were simulated from
mod <- mvgam(
  formula = y | trials(colonies) ~ series + s(sst, k = 8),
  trend_formula = ~ CAR(),
  data = coral_surveys,
  family = binomial(),
  chains = 2, silent = 2
)
summary(mod)

## End(Not run)

Dirichlet family for compositions

Description

For proportions measured together on each unit that sum to one, such as the cover shares of several species at a site. The data hold one row per component at each unit, whose responses sum to one within the unit. Each unit's vector of K shares is Dirichlet with concentrations softmax(mu) * phi. mu holds the components' linear predictors. phi sets how tightly the shares gather around softmax(mu) (Aitchison 1982).

Usage

diri()

Details

jsdgam() fits the family, taking the unit and component columns and the number of latent factors n_lv. The factors give the components correlated departures from their expected shares (Warton et al. 2015).

Value

A family object to pass to jsdgam() or mvgam().

Identification

The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:

A loadings_prior combines with that constraint.

Regression on phi

bf(y ~ env * series, phi ~ env) models the concentration. A unit's density takes one phi. Its covariates must take one value per unit. mvgam refuses a covariate that varies within a unit. The coefficients of phi take a flat prior by default. prior(student_t(3, 0, 2.5), class = b, dpar = phi) regularises them.

Post-fit conventions

The density is joint over a unit's components, which makes the unit the grain of log_lik(), loo() and waic() (Vehtari et al. 2017). log_lik() gives each unit's log density on its first row and NA on the others. loo() then counts each unit once. loo_compare() needs every model it compares scored at that grain.

posterior_linpred() gives mu per row before the reference subtraction. posterior_epred() gives the expected shares, which sum to one within each unit.

species_effects(), variance_partition() and forecast_uncertainty(scale = "link") report the predictor centred across each unit's components, the centred log-ratio scale. A shift shared by every component then drops out.

References

Aitchison, J. (1982). The statistical analysis of compositional data. Journal of the Royal Statistical Society Series B, 44(2):139-177.

Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4

Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007

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

See Also

Other observation families: beta_nb(), categ(), com_binomial(), multi(), mvgam_families, mvn(), mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# Shares of three categories at 60 sites along an environmental
# gradient
simdat <- sim_jsdgam(family = diri(), n_species = 3L, n_sites = 60L,
                     seed = 2L)
head(simdat$data_train)

# `env * series` gives each category its own slope
fit <- jsdgam(
  formula        = y ~ env * series,
  factor_formula = ~ -1,
  data           = simdat$data_train,
  unit           = time, species = series,
  family         = diri(),
  n_lv           = 2L,
  chains         = 2L,
  silent         = 2
)

# The species terms are contrasts with the first species. `Intercept`
# and `env` act on every species alike. The softmax cancels them. Their
# posteriors repeat the prior.
summary(fit)

# Each species' response to env relative to the average species
species_effects(fit, variables = "env")

# The expected shares move along the gradient
conditional_effects(fit, effects = "env:series")

# Each site's expected shares sum to one
pe <- posterior_epred(fit, ndraws = 50L)
first_site <- which(simdat$data_train$time == 1L)
rowSums(pe[1:5, first_site])

## End(Not run)


Combine forecasts from mvgam models into a weighted ensemble

Description

Build a single mvgam_forecast from the hindcast and forecast draws of two or more mvgam_forecast objects. Each input supplies a share of the draws set by its weight. Weights are even by default.

Usage

ensemble(object, ...)

## S3 method for class 'mvgam_forecast'
ensemble(object, ..., weights = NULL, ndraws = 5000L, seed = NULL)

Arguments

object

An mvgam_forecast object returned by forecast.mvgam() or hindcast.mvgam().

...

More mvgam_forecast objects to combine.

weights

Either NULL (the default, equivalent to even weighting), or a numeric vector with one non-negative entry per supplied forecast. The weights are normalised to sum to 1. Strategies such as stacking need the fitted models. Compute them with loo_model_weights.mvgam() on the fits, or with loo_model_weights.mvgam_lfo() on their lfo_cv() results. weights takes either result as it is.

ndraws

Positive integer giving the total number of ensemble draws to return per series. Defaults to 5000. A model allocated more draws than it holds is sampled with replacement.

seed

Optional integer seed. The session's random state is restored when the call returns.

Details

Per-model weights are split into integer draw counts that sum to ndraws by the largest-remainder rule, after brms::round_largest_remainder(). Each model then gives one set of sampled draws. Every series, in the hindcasts and in the forecasts, takes that same set. The ensemble keeps the dependence between series and the pairing of each hindcast with its forecast.

The returned object takes its series names, family, training data and test data from the first input. All inputs must share the series names, the hindcast lengths, the forecast horizons and, when present, the test observations.

A multivariate fit on a wide frame gives one forecast whose series are its responses. The ensemble is a forecast over those series. On a long frame the ensemble keeps one forecast per response. Every response takes the same draws.

Value

An object of class mvgam_forecast containing the ensembled hindcasts and forecasts. Suitable for plot.mvgam_forecast() and score.mvgam_forecast(). Attribute weights records the per-model weights used. Attribute ndraws_per_model records the integer draw counts drawn from each input.

Author(s)

Nicholas J Clark

See Also

score.mvgam_forecast() scores the ensemble. loo_model_weights.mvgam_lfo() computes weights from forecast performance. pp_average.mvgam() averages predictions in place of forecasts. The forecast evaluation article weights an ensemble by leave-future-out stacking weights.

Other forecasting: compare_scores(), forecast.mvgam(), forecast_uncertainty(), hindcast(), lfo_cv.mvgam(), score()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
fc_gam <- forecast(mod_gam, newdata = simdat$data_test)
fc_ar <- forecast(mod_ar, newdata = simdat$data_test)

# An ensemble that draws 30% of its draws from the GAM
ens <- ensemble(fc_gam, fc_ar, weights = c(0.3, 0.7))
attr(ens, "ndraws_per_model")
plot(ens)

# The ensemble scored against its components
scores <- compare_scores(fc_gam, fc_ar, ens, score = "drps",
                         model_names = c("GAM", "AR", "Ensemble"))
plot(scores, relative = "GAM")

## End(Not run)


Extract family from mvgam object

Description

Extract family from mvgam object

Usage

## S3 method for class 'mvgam'
family(object, resp = NULL, ...)

Arguments

object

mvgam object

resp

Optional name of one response of a multivariate model. Without it, a model with several responses returns one family per response.

...

Unused. Anything passed here is refused.

Value

A family object, or a list of them named by response


Calculate latent VAR forecast error variance decompositions

Description

Compute forecast error variance decompositions from mvgam models with Vector Autoregressive dynamics. A decomposition gives the share of each series' forecast uncertainty at horizons up to h that comes from the innovations of each series.

Usage

fevd(object, ...)

## S3 method for class 'mvgam'
fevd(
  object,
  h = 10,
  ndraws = NULL,
  draw_ids = NULL,
  summary = TRUE,
  probs = c(0.025, 0.975),
  future = FALSE,
  ...
)

Arguments

object

An object of class mvgam fitted with a VAR() latent process model

...

Unused. Anything passed here is refused.

h

Positive integer. The number of forecast horizons to decompose.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

summary

Logical; return the posterior median and interval of each decomposition (the default), or the per-draw decompositions themselves.

probs

The lower and upper percentiles of the interval reported with the median when summary = TRUE.

future

Logical. When TRUE, the per-draw computation runs under the future::plan() the caller has set. The default sequential plan runs as base lapply() does. plan(multisession, workers = N) splits the draws across N R processes. Without the future package the draws run in turn, with a message.

Value

An object of mvgam_fevd-class, which describes the quantities computed, with references.

Author(s)

Nicholas J Clark

References

Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1

See Also

irf() and stability() summarise the same VAR dynamics. forecast_uncertainty() splits a forecast of any model by source. The VAR article runs fevd() on a plankton community.

Other latent dynamics: active_factors(), compare_loadings(), irf.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Ten years of monthly counts of a prey species and its predator.
# Predators suppress the prey a month later. Prey raise the
# predators a month later.
set.seed(2025)
n_months <- 120
A <- rbind(prey     = c(0.6, -0.5),
           predator = c(0.4,  0.5))
z <- matrix(0, n_months, 2)
for (t in 2:n_months) {
  z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35)
}
predator_prey <- data.frame(
  time = rep(seq_len(n_months), 2),
  series = factor(rep(c("prey", "predator"), each = n_months),
                  levels = c("prey", "predator")),
  y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2])))
)
var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(),
                 data = predator_prey, family = poisson(),
                 chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The share of each series' forecast-error variance due to each
# shock, over an eight-step horizon
fevd_obj <- fevd(var_mod, h = 8L)
plot(fevd_obj)

# Next: irf() traces each shock through the system over time

## End(Not run)


Expected values of an mvgam model

Description

Expected values E[Y | X] of an mvgam model, or its linear predictor with scale = "linear", at the training observations by default. The interface follows fitted.brmsfit().

Usage

## S3 method for class 'mvgam'
fitted(
  object,
  newdata = NULL,
  re_formula = NULL,
  scale = c("response", "linear"),
  components = c("response", "latent_state", "detection"),
  unit_level = NULL,
  resp = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  process_error = FALSE,
  incl_autocor = is.null(newdata),
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  ...
)

Arguments

object

An object of class mvgam.

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

scale

Character; one of "response" (default) or "linear". "response" returns expected values on the response scale via posterior_epred.mvgam(). "linear" returns the linear predictor on the link scale via posterior_linpred.mvgam(). Ignored when components is not "response".

components

Character; one of "response" (default), "latent_state", or "detection". The quantity to return:

  • "response": the expected value of each row of the data, on the scale scale sets.

  • "latent_state", for nmix() and occ() only: the latent state of each closure unit given its detections. That is the abundance N for nmix() and the probability of occupancy P(z = 1 | y) for occ(). predict.mvgam() returns the same with type = "latent_state".

  • "detection", for nmix() and occ() only: the detection probability of each visit, as type = "detection" of predict.mvgam() returns it.

The argument matches components of flocker::fitted_flocker().

unit_level

Logical or NULL (default). When TRUE for a closure-unit detection family and components = "response", sums the per-visit response matrix over the visits of each unit. Other components have fixed grains and ignore it. So do families that do not aggregate visits.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

summary

Logical. If TRUE (the default), returns summary statistics. If FALSE, returns the full matrix of posterior draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Numeric vector of probabilities for quantile computation. Default is c(0.025, 0.975) for 95% credible intervals.

process_error

Logical. FALSE, the default, leaves the trend's innovations out of the prediction. TRUE adds a random deviation at each time and series, drawn anew for every posterior draw from the spread the trend shows over the long run. For an AR(1) trend with innovation SD \sigma and coefficient \rho that spread has variance \sigma^2/(1-\rho^2). On a log link the deviations raise the average prediction by the factor \exp(\sigma^2/(2(1-\rho^2))). A random walk has no long-run spread. A ZMVN() trend has no dynamics. These two draw from the innovation covariance itself. CAR() draws from one long-run covariance at every time of an irregular grid. The argument applies under incl_autocor = FALSE. The fitted state already holds every innovation.

Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result.

incl_autocor

Logical; whether the fitted values include the latent trend state the model inferred at each time. Defaults to TRUE for the training data, as in brms::fitted.brmsfit(). Defaults to FALSE with newdata. Under TRUE the observed response minus the fitted value is the ordinary residual of residuals.mvgam().

allow_new_levels

Logical. TRUE predicts for grouping levels the model never saw, with coefficients sample_new_levels draws. A new series stays refused: it has no latent state to propagate.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default) takes those of a fitted level chosen in each draw, "old_levels" those of one fitted level for all draws and "gaussian" draws them from the group's normal distribution. Each distributional parameter draws its own.

...

Unused. Anything passed here is refused.

Details

As in brms, fitted values leave out the observation noise. posterior_predict.mvgam() adds it. Use predict.mvgam() for predictive draws.

For the training data the fitted values include the trend state the model inferred at each time. hindcast.mvgam() returns the same state. With newdata, or under incl_autocor = FALSE, the fitted values describe the covariate part of the model. process_error then sets the trend's part. FALSE keeps the trend's covariate effects. TRUE also samples a state per draw from the trend's dynamics.

The brms arguments dpar, nlpar and sort are refused. posterior_linpred.mvgam() returns a distributional parameter through its own dpar. Rows come back in the order of the frame.

Value

With summary = FALSE, an ⁠[ndraws, nobs]⁠ matrix of draws. With summary = TRUE, a matrix with one row per observation and the columns:

A multivariate model with resp = NULL gives a named list of these, one per response.

See Also

residuals.mvgam() compares the fitted values with the data. hindcast.mvgam() returns the fitted latent states. forecast.mvgam() predicts future times.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Expected counts at the training observations: the posterior mean,
# error and 95% interval of each
head(fitted(mod))

# The covariate effects alone, without the inferred trend state
head(fitted(mod, incl_autocor = FALSE))

# One row per posterior draw and one column per observation
dim(fitted(mod, summary = FALSE))

# Next: residuals() and pp_check() compare the fit with the data

## End(Not run)


Posterior forecasts for an mvgam state-space model

Description

Posterior forecasts at future time points, with posterior hindcasts at the training time points. Each draw propagates the fitted latent state through the trend's dynamics. The observation family then maps the trend to the response scale.

Usage

## S3 method for class 'mvgam'
forecast(
  object,
  newdata = NULL,
  ...,
  type = c("response", "link", "expected", "trend", "latent_state"),
  component = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  coef_uncertainty = TRUE,
  trend_uncertainty = TRUE,
  obs_uncertainty = TRUE,
  resp = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty"
)

Arguments

object

A fitted mvgam object.

newdata

Optional data.frame with the columns of the training data, one row per series and future time to forecast. When NULL, forecast() uses the held-out data given to mvgam(newdata = ). A fit without held-out data needs newdata.

The trend decides which future times are allowed:

  • AR(), RW(), VAR(), LLT() and PW() step once per time point. Their forecast times must continue each series at its own spacing, with no gap. After training ends at t = 30, rows for t = 41:42 alone are refused. The trend would step once and twice, though those times are 11 and 12 steps past the end of training. Supply every time in between, with or without a response.

  • CAR() allows for the gap between times. Each series may have its own forecast times, all after the last fitted time.

  • ZMVN() has no time dynamics and takes any later times.

ZMVN() and PW() need the same forecast times for every series.

...

Unused. Anything passed here is refused.

type

The scale of the draws:

  • "response" (the default) samples from the observation family.

  • "expected" returns the family's mean. A binomial mean is trials * p and a zero-inflated mean is (1 - zi) * mu.

  • "link" returns the linear predictor on the link scale.

  • "trend" returns the latent trend on the link scale.

  • "latent_state" returns the latent state of an occ() or nmix() fit: the occupancy probability, or the abundance N. The hindcast conditions each closure unit on its own visits, as hindcast(type = "latent_state") does. The forecast takes the state from the covariates and the propagated trend. A multi-season fit holds one unit per site in each season and returns the mean over those sites, which for occ() is the expected share of sites occupied.

component

NULL (the default) for the summed trend, or the names of state components of the trend, with type = "trend". Several names give the sum of their components. LLT() has "level", the stochastic level, and "slope", its growth per time step. A seasonal LLT() adds "season". "predictor" holds the effects of the trend formula's covariates. c("level", "predictor") gives the level with those effects. A factor model projects each component through its loadings, as it projects the trend.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

coef_uncertainty

Logical, TRUE by default. FALSE holds the coefficients of the observation and trend formulas at one posterior draw, the first that ndraws or draw_ids selects. That includes smooth, random-effect and gp() coefficients. An exact gp() term's draw at new values is held too. The forecast then leaves out their uncertainty. Turning off one source of uncertainty at a time shows how much each contributes to a forecast.

trend_uncertainty

Logical, TRUE by default. FALSE holds the parameters of the trend dynamics (sigma, AR, MA and VAR coefficients), the last fitted state and the trend formula's predictor at that same draw. Each draw still takes new innovations. The spread then shows innovation noise alone.

obs_uncertainty

Logical, TRUE by default. FALSE returns the family's mean under type = "response", in place of a sampled observation.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

re_formula, allow_new_levels, sample_new_levels

As in posterior_epred.mvgam(). A formula applies to the observation and the trend formulas alike.

Value

An object of class mvgam_forecast-class. Hindcasts and forecasts are returned as named lists of ⁠[ndraws, n_times]⁠ matrices, one per series. A forecast of state components names them in its component slot.

See Also

hindcast.mvgam() returns the fitted latent states. posterior_predict.mvgam() and posterior_epred.mvgam() predict from the covariate part of the model. forecast() extrapolates the fitted latent state. score.mvgam_forecast() scores a forecast against held-out data. forecast_uncertainty() splits its variance by source. The forecast evaluation article scores, compares and combines the forecasts of three models of rodent counts.

Other forecasting: compare_scores(), ensemble.mvgam_forecast(), forecast_uncertainty(), hindcast(), lfo_cv.mvgam(), score()

Examples

## Not run: 
set.seed(11)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR(),
                     proportional_train = 0.75)

mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data    = simdat$data_train,
  newdata = simdat$data_test,
  family  = poisson(),
  chains  = 2, silent = 2
)

# The held-out data given to mvgam() set the forecast horizon
fc <- forecast(mod)
plot(fc)

# The latent AR(1) trend alone, on the log scale
plot(forecast(mod, type = "trend"))

# The expected counts, without the Poisson sampling noise
plot(forecast(mod, type = "expected"))

# Next, score the forecast against the held-out counts
head(score(fc, score = "crps")[[1]])

# The sources of the forecast's variance at each horizon
plot(forecast_uncertainty(mod, ndraws = 200))

# How a future with higher `x` would change the forecast
higher <- simdat$data_test
higher$x <- higher$x + 1
plot(forecast_uncertainty(
  mod, newdata = list(observed = simdat$data_test, higher = higher),
  ndraws = 200
))

## End(Not run)


Forecast uncertainty by source

Description

Shows where a forecast's uncertainty comes from and how each source grows with the horizon. The variance of the forecast at each horizon splits among the model's terms, its random effects, the latent dynamics, process error and, on the response scale, observation noise.

Usage

forecast_uncertainty(object, ...)

## S3 method for class 'mvgam'
forecast_uncertainty(
  object,
  newdata = NULL,
  ...,
  scale = c("link", "expected", "response"),
  n_replicates = 20L,
  n_boot = 200L,
  ndraws = NULL,
  draw_ids = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  resp = NULL
)

## S3 method for class 'mvgam_forecast_uncertainty'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_forecast_uncertainty'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_forecast_uncertainty'
plot(
  x,
  type = c("variance", "share"),
  by = c("kind", "source"),
  series = NULL,
  ...
)

## S3 method for class 'mvgam_forecast_scenarios'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_forecast_scenarios'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_forecast_scenarios'
plot(x, series = NULL, ...)

Arguments

object

A fitted mvgam object.

...

Unused. Anything passed here is refused.

newdata

Data frame of future times, as forecast.mvgam() takes it. NULL uses the data held out at fit time. A named list of such frames compares scenarios, each frame holding one possible future of the covariates. See Scenarios.

scale

"link" (the default) splits the predictor, where its parts add and the split is exact. "expected" splits the expected value. Its variance grows with the mean, which lets a covariate's swings move it between horizons. "response" adds observation noise, giving the variance of new observations.

n_replicates

Number of times each draw is propagated, at least two. More replicates steady the process error.

n_boot

Number of bootstrap resamples of the draws, which give each share its interval.

ndraws, draw_ids

The posterior draws to use, as hindcast.mvgam() takes them. NULL for both uses every draw.

re_formula, allow_new_levels, sample_new_levels

How group-level terms enter, as forecast.mvgam() takes them. A level the fit never saw adds the spread among levels to ⁠random effects⁠.

resp

The response to report, needed on a model with several.

probs

Interval probabilities of the table. Defaults to c(0.025, 0.975).

x

An mvgam_forecast_uncertainty object from forecast_uncertainty().

digits

Integer number of significant digits. Defaults to 2.

type

"variance" (the default) stacks each source's absolute variance. "share" stacks its fraction of the total.

by

"kind" (the default) stacks each kind of source. "source" stacks each term.

series

The series to plot, by name or position. NULL plots every series.

Details

With \theta the parameters and y_h the forecast at horizon h, the law of total variance gives

\mathrm{Var}(y_h) = \mathrm{Var}(\mathrm{E}[y_h \mid \theta]) + \mathrm{E}(\mathrm{Var}[y_h \mid \theta]).

Each draw is propagated n_replicates times with fresh innovations. The variance across a draw's replicates, averaged over the draws, is the ⁠process error⁠. The variance of the replicates' means is the parameter uncertainty, less its known excess of the process error over n_replicates. This holds exactly on every scale. Monte Carlo error can leave a small estimate negative. No estimate is clipped.

Sources. Parameter uncertainty splits by source, each of one kind:

coefficients

each population-level term, smooth or gp(). This uncertainty falls with more data.

⁠random effects⁠

each group-level term

⁠latent dynamics⁠

the latent state's mean path, holding the uncertain last state and trend parameters

⁠process error⁠

what the trend's innovations add. It persists however much data arrives.

driver

what an uncertain future covariate adds. A mi() covariate missing from newdata follows its own trend into the forecast. Its innovations are ⁠imputed covariates⁠, split from ⁠process error⁠ by their covariance with the forecast.

observation

noise around the expected value, under scale = "response" alone

Terms of the trend formula are labelled (trend). A term that is zero at every forecast row is left out.

Contributions. Parts of a model share a posterior: an intercept and a covariate's effect can each be uncertain while their sum is not. A source's own variance can then far exceed the forecast's. Its contribution is its covariance with the whole forecast, which counts what reaches the forecast. The contributions sum to the forecast's variance. A source offsetting another takes a negative one. The contribution is the source's Shapley value in the forecast's variance.

Terms that overlap, such as s(x) with t2(x, z), can take large contributions of opposite sign. The sum over a kind stays stable, which is why the overview and the default plot work by kind.

A diri(), multi() or categ() fit gives each species' share through a softmax, which ignores a shift every species at a site shares. Its link scale is centred across the species at each site, the centred log-ratio scale.

On the link scale the contributions are exact. On the other scales a term's values are the expected value less the expected value without that term, as in variance_partition(), rescaled to sum to the parameter uncertainty. The terms then interact, which makes their split an approximation. The split between parameter uncertainty, process error and observation stays exact. On a skewed scale a few draws can drive a variance, which makes the link scale steadier.

Scenarios. A list of frames sharing their series and times gives each scenario its own split. It also gives the difference between each scenario and the first, draw by draw, with a posterior interval. Every scenario takes the same draws and the same innovations. On the link scale the state then cancels, leaving what the covariates change. Because a list of scenarios is no probability distribution, no variance is taken across it. To separate two covariates, vary one at a time.

The intervals resample the draws. They measure the Monte Carlo error of a share, which falls with ndraws and n_replicates.

Value

An object of class mvgam_forecast_uncertainty. print() gives each series' overview. summary() takes probs and returns a list of three tibbles:

overview

one row per series: the forecast's SD at its first and last horizons, the dominant kind of source at the last horizon, the share of resamples that agree (support) and the horizon at which the dominant kind first changes_at

horizons

the forecast's variance at each horizon

sources

each source's variance, contribution and share at each horizon, the share with its interval

plot() stacks the sources over the horizon. A negative contribution is drawn as zero. The object's draws element holds, per series, the ⁠[draws, horizons]⁠ matrix of the forecast's mean given each draw.

A list of frames in newdata gives an object of class mvgam_forecast_scenarios. print() gives each difference at the last horizon. summary() returns a list of contrasts, one row per horizon, with overview, one row per scenario and series. plot() draws each difference over the horizon. Its scenarios element holds each scenario's own mvgam_forecast_uncertainty object.

Author(s)

Nicholas J Clark

References

Dietze MC (2017). Prediction in ecology: a first-principles framework. Ecological Applications 27(7), 2048-2060.

See Also

forecast.mvgam() for coef_uncertainty and trend_uncertainty, fevd() for the sources of a VAR's forecast errors, variance_partition() for the fitted predictor. The forecast evaluation article runs forecast_uncertainty() on rodent captures.

Other forecasting: compare_scores(), ensemble.mvgam_forecast(), forecast.mvgam(), hindcast(), lfo_cv.mvgam(), score()

Examples

## Not run: 
set.seed(11)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR(),
                     proportional_train = 0.75)

mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data    = simdat$data_train,
  newdata = simdat$data_test,
  family  = poisson(),
  chains  = 2, silent = 2
)

# The held-out data given to mvgam() set the forecast horizon
fc <- forecast(mod)
plot(fc)

# The latent AR(1) trend alone, on the log scale
plot(forecast(mod, type = "trend"))

# The expected counts, without the Poisson sampling noise
plot(forecast(mod, type = "expected"))

# Next, score the forecast against the held-out counts
head(score(fc, score = "crps")[[1]])

# The sources of the forecast's variance at each horizon
plot(forecast_uncertainty(mod, ndraws = 200))

# How a future with higher `x` would change the forecast
higher <- simdat$data_test
higher$x <- higher$x + 1
plot(forecast_uncertainty(
  mod, newdata = list(observed = simdat$data_test, higher = higher),
  ndraws = 200
))

## End(Not run)


Extract formula from mvgam object

Description

Extract formula from mvgam object

Usage

## S3 method for class 'mvgam'
formula(x, ...)

Arguments

x

mvgam object

...

Unused. Anything passed here is refused.

Value

Formula object


The priors of a model

Description

Methods:

default_prior() is the same generic under the newer brms name.

A prior states the plausible values of a parameter before the data are seen. Each row of the table gives the prior of one parameter class. A ⁠_trend⁠ suffix marks the classes of the latent trend. The defaults are weakly informative. Change one when outside knowledge narrows a parameter, or when the sampler struggles in a region the data cannot inform. Pass the new rows, built with brms::prior(), to the prior argument of mvgam().

Usage

get_prior(object, ...)

default_prior(object, ...)

Arguments

object

An mvgam_formula(), an mvgam model, or a model formula.

...

Arguments of the method.

Value

A brmsprior data frame.

See Also

mvgam_formula(), brms::get_prior()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())

# The default priors of a Poisson GAM with an AR(1) trend, before
# any fitting
get_prior(
  mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)),
  data = simdat$data_train,
  family = poisson()
)

# Outside knowledge that the series is strongly persistent narrows
# the AR(1) coefficient
persistent <- prior(normal(0.7, 0.15), class = ar1_trend)
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             prior = persistent, chains = 2, silent = 2)

# The fitted model's prior table records the change
get_prior(mod)

## End(Not run)

The priors of a model formula

Description

Covers a formula, brmsformula or mvbrmsformula, which it wraps in the mvgam_formula it describes with any trend_formula in the call. The table then carries the defaults mvgam gives its own families, with or without a trend.

Usage

## Default S3 method:
get_prior(object, ...)

## Default S3 method:
default_prior(object, ...)

Arguments

object

Model specification object

...

Arguments of get_prior.mvgam_formula(), such as data, family and trend_formula

Value

A brmsprior data frame


The prior table of an mvgam model

Description

get_prior(), default_prior() and prior_summary() return the one prior table a model was built with. Edit it and pass it to update(fit, prior = ...) to refit under other priors without recompiling.

Usage

## S3 method for class 'mvgam'
get_prior(object, ...)

## S3 method for class 'mvgam'
default_prior(object, ...)

Arguments

object

An mvgam model, fitted or built with run_model = FALSE.

...

Unused. Anything passed here is refused.

Value

A brmsprior data frame of the observation and trend priors. A row the user set has source = "user". brms sets the source of the others, mostly "default".

See Also

Other priors: get_prior.mvgam_formula()


The priors an mvgam model takes, before fitting

Description

Lists the priors of the observation and trend parts of the model an mvgam_formula() describes, with their defaults for the data given. Without a trend_formula the table matches that of brms::get_prior(). default_prior() is the same method under the newer brms name.

Usage

## S3 method for class 'mvgam_formula'
get_prior(
  object,
  data,
  family = gaussian(),
  loadings_prior = NULL,
  data2 = NULL,
  ...
)

## S3 method for class 'mvgam_formula'
default_prior(object, ...)

Arguments

object

An mvgam_formula(), or an mvgam model fitted or built with run_model = FALSE.

data

A data frame holding every variable the formulas use.

family

A description of the response distribution and link function, given as a family function, a call to one or its name. Supports most brms families, including the ordinal families (brms::cumulative(), brms::sratio(), brms::cratio(), brms::acat()). The brms families needing a separate linear predictor per response category, brms::categorical(), brms::multinomial() and brms::dirichlet(), are refused: use categ(), multi() and diri(), which take the categories in long format and share one latent structure across them. A family whose mean has to stay positive needs a link that keeps it there once a trend enters the linear predictor: pair stats::Gamma(), brms::weibull(), brms::exponential(), brms::frechet() and stats::inverse.gaussian() with link = "log". Their default links leave the mean positive only where the predictor is. A latent trend is centred near zero and reaches negative values, where the likelihood is undefined. mvgam() warns before fitting. brms::lognormal() is the exception: its mu is a log-scale location that takes any sign.

A family written inside a univariate brms::bf() is the model's family, as in brms. In a multivariate model each response may take its own family, in which case name it inside that response's brms::bf(): bf(count ~ x, family = poisson()) + bf(seen ~ x, family = bernoulli()). Passing a list of families to this argument, as brms::brm() allows, is not supported; the family belongs to the response that names it. A single family given here applies to every response that does not name one of its own. Closure-unit and multi-response families (occ(), nmix(), mvn(), mvt(), diri(), multi(), categ()) lay their data out by unit. Each models its response alone and cannot be one response of a multivariate model.

loadings_prior

Optional named list giving a structured prior on the loadings of a factor model, such as species traits or a phylogeny. Most models leave it NULL. The section 'Structured loadings priors' of mvgam() describes its fields.

data2

A named list of objects the model uses that are not variables in data, as in brms::brm().

...

Further arguments of brms::get_prior(), such as knots or drop_unused_levels.

Details

The observation priors are those brms::get_prior() gives, with mvgam's defaults for the families it adds. The trend rows list every parameter the trend constructor samples and the coefficients of the trend formula.

Default trend priors. brms sets the scale of its default intercept, standard deviation and residual priors to max(2.5, mad(link(y))), from the spread of the response on the link scale under the identity, log, inverse, square-root and inverse-square links. That widens its base scale of 2.5 by the factor s = \max(1, \mathrm{mad}(\mathrm{link}(y)) / 2.5). mvgam widens the trend's scale priors by the same factor, taking the widest over several responses and s = 1 under any other link:

A count model on the log link rarely spreads past 2.5. Its defaults keep their link-scale values. Coefficients without units keep fixed priors: autoregressive and damping coefficients, correlations and degrees of freedom. The table this returns holds the resolved values for the data given.

A shrinkage prior on a trend-side class is written without autoscaling. horseshoe() and R2D2() scale their global parameter by the family's residual standard deviation. The trend's own scale is sigma_trend, one per latent series. A family's residual scale has no meaning on the trend side. Those rows take autoscale = FALSE. Writing autoscale = TRUE on a trend-side class is refused.

Value

A brmsprior data frame of the observation and trend priors, usable with brms::set_prior() and brms::prior(). A trend class carries the _trend suffix.

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

See Also

mvgam_formula(), brms::prior() and brms::set_prior(). The hierarchical VAR article sets priors on the observation error and the trend correlations.

Other priors: get_prior.mvgam()

Examples

## Not run: 
set.seed(1)
dat <- sim_mvgam(family = poisson(), n_series = 2L,
                 n_timepoints = 120L, trend_model = AR())$data_train

# Every prior the model takes, before any fitting. Trend classes
# carry a `_trend` suffix: `b` belongs to the observation formula
# and `b_trend` would belong to the trend formula.
mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1))
get_prior(mf, data = dat, family = poisson())

# Replace three defaults. Each `prior()` call gives one row.
my_priors <- c(
  prior(std_normal(), class = b),
  prior(inv_gamma(5, 1), class = sigma_trend),
  prior(normal(0.5, 0.25), class = ar1_trend)
)

# `run_model = FALSE` builds the model without sampling. Its prior
# table marks the replaced rows as "user".
pre <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = dat, family = poisson(), prior = my_priors,
             run_model = FALSE)
prior_summary(pre)

# Next, drop `run_model = FALSE` to fit the model under these priors

## End(Not run)


Model summary for an mvgam fit

Description

broom-style summary of an mvgam fit, one row per response. Reports the Stan algorithm, post-warmup sample size, training-observation count, response family, link function and (optionally) loo criteria. Mirrors broom.mixed::glance.brmsfit().

Usage

## S3 method for class 'mvgam'
glance(x, looic = FALSE, resp = NULL, ...)

Arguments

x

A fitted mvgam object.

looic

Logical. If TRUE, compute leave-one-out information criteria via loo.mvgam() and add elpd_loo, se_elpd_loo, p_loo and looic columns. Defaults to FALSE because computing loo can be slow on large fits.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

...

Forwarded to loo.mvgam() when looic = TRUE.

Value

A tibble with one row, or on a multivariate fit given no resp one row per response with a resp column. Columns:

See Also

tidy.mvgam(), augment.mvgam(), loo.mvgam()

Other tidiers: augment.mvgam(), tidy.mvgam()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The sampler and data dimensions of the fit, in one row
glance(mod)

# Leave-one-out criteria take longer to compute
glance(mod, looic = TRUE)

## End(Not run)


Posterior hindcasts for an mvgam state-space model

Description

Posterior draws at the training time points. Each draw takes the latent state the model inferred at each time. The observation family maps it to the response scale. A hindcast shows how closely the fitted states track the data. forecast.mvgam() predicts unseen times.

Usage

hindcast(object, ...)

## S3 method for class 'mvgam'
hindcast(
  object,
  ...,
  type = c("response", "link", "expected", "trend", "latent_state"),
  component = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  obs_uncertainty = TRUE,
  process_error = FALSE,
  resp = NULL
)

## S3 method for class 'mvgam_latent_state'
summary(object, probs = c(0.025, 0.25, 0.75, 0.975), ...)

## S3 method for class 'mvgam_latent_state'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_latent_state'
plot(x, series = NULL, ...)

Arguments

object

A fitted mvgam object, or for summary() an mvgam_latent_state object.

...

Unused. Anything passed here is refused.

type

The scale of the draws, as in forecast.mvgam(), or "latent_state" for a closure-unit family. "latent_state" returns the occupancy probability psi of an occ() model or the abundance N of an nmix() model at each closure unit, as an mvgam_latent_state object. Its print() gives the range of the unit medians. summary() and as.data.frame() return one row per unit, with its key columns (series, time and the site of a multi-season fit), the median and the 50% and 95% interval bounds. plot() draws them per series, as a line with ribbons over time or as points with interval bars over units without an order. A multi-season fit holds several sites in each season. Its plot draws the mean over those sites in each draw: the expected share of sites occupied, or the mean abundance per site.

component

NULL (the default) for the summed trend, or the names of state components of the trend, with type = "trend". Several names give the sum of their components. LLT() has "level", the stochastic level, and "slope", its growth per time step. A seasonal LLT() adds "season". "predictor" holds the effects of the trend formula's covariates. c("level", "predictor") gives the level with those effects. A factor model projects each component through its loadings, as it projects the trend.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

obs_uncertainty

Logical, TRUE by default. FALSE returns the family's mean under type = "response", in place of a sampled observation.

process_error

Logical. FALSE (the default) takes the fitted latent state of each draw. type = "response" then adds the observation noise alone. TRUE replaces the fitted states with the covariate part plus newly drawn innovations, as posterior_epred.mvgam() gives with the same argument. The hindcast then shows what the model predicts without the observed history. A component is a fitted state and needs FALSE.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

probs

For summary(), the four interval bounds, lowest first. Defaults to c(0.025, 0.25, 0.75, 0.975), the 50% and 95% intervals.

x

An mvgam_latent_state object.

digits

Integer number of digits in the printed range. Defaults to 2.

series

Names or indices of the series to plot, or NULL for every series.

Value

An mvgam_forecast-class object. Its hindcasts are a named list of ⁠[ndraws, n_times]⁠ matrices, one per series. Its forecast slots are NULL.

See Also

forecast.mvgam() extrapolates the fitted state. posterior_predict.mvgam() and posterior_epred.mvgam() predict from the covariate part of the model. The multivariate article compares type = "trend" hindcasts of one latent state from a joint model and from each data source alone. The N-mixture article summarises type = "latent_state" hindcasts of abundance.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Other forecasting: compare_scores(), ensemble.mvgam_forecast(), forecast.mvgam(), forecast_uncertainty(), lfo_cv.mvgam(), score()

Examples

## Not run: 
set.seed(11)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())

mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data    = simdat$data_train,
  family  = poisson(),
  chains  = 2, silent = 2
)

# The fitted states track the training counts
hc <- hindcast(mod)
plot(hc)

# The AR(1) trend on the log scale
plot(hindcast(mod, type = "trend"))

# Fresh innovations in place of the fitted states give the wider
# spread a model without the observed history would predict
plot(hindcast(mod, process_error = TRUE))

# A local linear trend's slope, the level's growth per step
mod_llt <- update(mod, trend_formula = ~ LLT())
plot(hindcast(mod_llt, type = "trend", component = "slope"))

# Next, forecast the held-out times with forecast()

## End(Not run)


A methods paragraph and references for an mvgam model

Description

Drafts a methods paragraph for a fitted model, with the references it cites and their BibTeX entries. The text and references follow the model's structure: the family and link, the trend, the factor identification and loadings prior, Gaussian process smooths, piecewise trends, the Stan backend and the sampling algorithm.

Usage

how_to_cite(object, ...)

## S3 method for class 'mvgam'
how_to_cite(object, ...)

Arguments

object

A fitted mvgam or jsdgam object.

...

Unused. Anything passed here is refused.

Value

A how_to_cite object holding the methods_text, the citations it makes, an other_citations list of related references and a bibtex list keyed by reference. bibtex() extracts the BibTeX entries. print() shows every section.

Author(s)

Nicholas J Clark

See Also

methods_md() writes the model's equations to accompany the paragraph. utils::citation() cites the package itself.

Other posterior summaries: VarCorr.mvgam(), bibtex(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# A methods paragraph naming the Poisson family, the smooth and
# the AR(1) trend, with the references it cites
cite <- how_to_cite(mod)
cite

# The BibTeX entries, for a reference manager
bibtex(cite)

# Next, methods_md() writes the model's equations

## End(Not run)


Test posterior hypotheses on a fitted mvgam model

Description

The mvgam method of brms::hypothesis(), with the arguments and parameter names of brms::hypothesis.brmsfit(). By default a hypothesis names population-level coefficients without their b_ prefix, as "x > 0" tests b_x. class = NULL names any parameter by the full name variables.mvgam() lists, such as ar1_trend[series_1] or sigma. That help page sets out how the names are formed.

Usage

## S3 method for class 'mvgam'
hypothesis(
  x,
  hypothesis,
  class = "b",
  group = "",
  alpha = 0.05,
  robust = FALSE,
  seed = NULL,
  ...
)

Arguments

x

A fitted mvgam object.

hypothesis

Character vector of hypothesis strings in the brms::hypothesis() grammar, such as "x > 0" or "(x - z) = 0".

class

The class prefix the names in hypothesis omit. Defaults to "b". NULL or "" takes every parameter by its full name.

group

The grouping factor of a group-level class, as ⁠class = "sd", group = "site"⁠ tests sd_site__Intercept as Intercept.

alpha

One minus the credible-interval mass. Defaults to 0.05 (90%-CI for one-sided, 95%-CI for two-sided).

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

seed

Optional integer seed for the random draws of an evidence ratio. The session's random state is restored when the call returns.

...

Forwarded to brms::hypothesis.

Value

A brmshypothesis object. See brms::hypothesis().

Author(s)

Nicholas J Clark

See Also

brms::hypothesis(), variables.mvgam().

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())

mod <- mvgam(y ~ x,
              trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# A population-level coefficient, named as fixef() names it.
hypothesis(mod, "x > 0")

# Any parameter by its full name.
hypothesis(mod, c("ar1_trend[series_1] > 0",
                  "sigma_trend[series_1] < 1"),
           class = NULL)

## End(Not run)


Parameter names of a fitted mvgam model

Description

variables() lists the name of every quantity in a fitted model's draws. hypothesis.mvgam(), as_draws(), as.data.frame.mvgam(), mcmc_plot.mvgam() and posterior_average.mvgam() accept these names. summary.mvgam() and posterior_summary() label their rows with them.

Usage

## S3 method for class 'mvgam'
variables(x, ...)

Arguments

x

A fitted mvgam object.

...

Unused. Anything passed here is refused.

Value

A character vector of parameter names.

How parameters are named

Observation parameters take their brms names, such as b_x, sds_sx_1, sd_site__Intercept and r_site[a,Intercept]. The trend model's parameters take the same names with a ⁠_trend⁠ suffix, such as b_x_trend or sds_sx_1_trend.

An index that runs over the series takes the series' name, as brms labels a grouping factor's levels. A model with series DM and DO has sigma_trend[DM], ar1_trend[DM] and the innovation covariance Sigma_trend[DM,DO]. A VAR's coefficients keep the lag as a number, as in Phi_trend[1,DM,DO], as do the changepoints of PW() in delta_trend[3,DM]. Factor loadings are Z_tilde[DM,1], with the factor as the second index. In a factor model the dynamics belong to the factors, as in ar1_trend[1]. The latent state matrices keep numeric indices, as in trend[12,1] for time 12 of the first series.

A bare name such as variable = "sigma_trend" selects every element of a vector, as in posterior. Because variables() includes the latent states, its output runs to hundreds of names on most fits. grep() narrows it, as in grep("^(sigma|ar1)_trend", variables(fit), value = TRUE).

Author(s)

Nicholas J Clark

See Also

mvgam_draws to extract draws by name, hypothesis.mvgam() to test them, summary.mvgam() and posterior_summary() to summarise them.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 2L,
                    trend_model = AR())
mod <- mvgam(y ~ x,
             trend_formula = ~ AR(),
             data = simdat$data_train,
             family = poisson(),
             chains = 2, silent = 2)

# The trend dynamics, indexed by series
grep("^(sigma|ar1)_trend", variables(mod), value = TRUE)

# Every element of a vector by its bare name
as_draws_df(mod, variable = "sigma_trend")

# Two series' autoregressive coefficients compared
hypothesis(mod, "ar1_trend[series_1] > ar1_trend[series_2]",
           class = NULL)

# Next, plot chosen parameters with mcmc_plot(mod, variable = ...)

## End(Not run)


Initial values of a fitted mvgam model

Description

The init argument each chain started from.

Usage

## S3 method for class 'mvgam'
inits(x, ...)

Arguments

x

A fitted mvgam model.

...

Unused. Anything passed here is refused.

Value

A list with one element per chain.


Calculate latent VAR impulse response functions

Description

Compute Generalized or Orthogonalized Impulse Response Functions (IRFs) from mvgam models with Vector Autoregressive dynamics. An impulse response traces how the latent trend of every series moves over h time steps after a one-standard-deviation innovation to one series. The default generalised responses suit most analyses. Orthogonalised responses need a causal ordering of the series.

Usage

irf(object, ...)

## S3 method for class 'mvgam'
irf(
  object,
  h = 10,
  cumulative = FALSE,
  orthogonal = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  summary = TRUE,
  probs = c(0.025, 0.975),
  future = FALSE,
  ...
)

Arguments

object

An object of class mvgam fitted with a VAR() latent process model

...

Unused. Anything passed here is refused.

h

Positive integer. The number of horizons to compute. Horizon 1 is the time step of the shock.

cumulative

Logical. TRUE accumulates each response over the horizons.

orthogonal

Logical. TRUE computes orthogonalised responses from the lower Cholesky factor of the innovation covariance. These depend on the order of the levels of the series factor. The default generalised responses do not (Pesaran and Shin 1998).

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

summary

Logical; return the posterior median and interval of each response (the default), or the per-draw responses themselves. The draws are one K by K matrix per horizon per draw, which on a wide panel runs to hundreds of megabytes.

probs

The lower and upper percentiles of the interval reported with the median when summary = TRUE.

future

Logical. When TRUE, the per-draw computation runs under the future::plan() the caller has set. The default sequential plan runs as base lapply() does. plan(multisession, workers = N) splits the draws across N R processes. Without the future package the draws run in turn, with a message.

Details

See mvgam_irf-class for the quantities computed and returned, with references.

Value

An object of mvgam_irf-class. plot.mvgam_irf() and summary.mvgam_irf() take it.

Author(s)

Nicholas J Clark

References

Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1

Pesaran HH and Shin Y (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters 58, 17-29. doi:10.1016/S0165-1765(97)00214-0

See Also

fevd() and stability() summarise the same VAR dynamics. The VAR article runs irf() on a plankton community. The hierarchical VAR article runs it on each group of a hierarchical VAR.

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Ten years of monthly counts of a prey species and its predator.
# Predators suppress the prey a month later. Prey raise the
# predators a month later.
set.seed(2025)
n_months <- 120
A <- rbind(prey     = c(0.6, -0.5),
           predator = c(0.4,  0.5))
z <- matrix(0, n_months, 2)
for (t in 2:n_months) {
  z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35)
}
predator_prey <- data.frame(
  time = rep(seq_len(n_months), 2),
  series = factor(rep(c("prey", "predator"), each = n_months),
                  levels = c("prey", "predator")),
  y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2])))
)
var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(),
                 data = predator_prey, family = poisson(),
                 chains = 2, silent = 2)

## End(Not run)
## Not run: 
# Generalised responses of every series to a shock in each
irf_obj <- irf(var_mod, h = 8L)
plot(irf_obj, series = 1)

# Next: fevd() splits each series' forecast variance among the
# shocks. stability() summarises how the system returns to
# equilibrium

## End(Not run)


Whether an object is an mvgam trend

Description

Tests whether an object is a valid mvgam trend specification.

Usage

is.mvgam_trend(x)

Arguments

x

Object to test

Value

Logical indicating if x is a mvgam trend


Fit a joint species distribution model

Description

Fits a joint species distribution model (JSDM) to the presences, detections or counts of many species across many sampling units. Species often co-occur more or less often than their responses to the measured covariates predict. A few latent factors capture that residual association. They need far fewer parameters than a full correlation matrix among species. The observation model takes the smooths, Gaussian processes and random effects of any mvgam model. The factors take their own predictors through factor_formula. Write lv_axis() in one of its terms to give each factor its own effect of a covariate, a constrained ordination.

Usage

jsdgam(
  formula,
  factor_formula = ~-1,
  knots,
  data,
  newdata,
  family = binomial(),
  unit = time,
  species = series,
  priors,
  n_lv = 2L,
  traits = NULL,
  trait_slopes = NULL,
  phylo = NULL,
  loadings_prior = NULL,
  backend = default_backend(),
  threads = NULL,
  run_model = TRUE,
  ...
)

Arguments

formula

The observation model formula, in brms syntax: smooths s() and t2(), gp(), varying intercepts and slopes, mm(), mo(), me(), mi(), distributional and non-linear sub-formulas and offset(). A response leaves rows out by holding NA there. mvgam_formula() lists the terms each formula refuses. gp() takes the approximate Hilbert-space form (gp(x, k = 20)) or the exact form (gp(x), no k), under any brms kernel. An exact term predicts at new covariate values by conditioning on its fitted values, as brms does. Its cost grows with the cube of the number of unique values.

factor_formula

A one-sided formula for the latent factors' linear predictor. Write lv_axis() in a term to give each factor its own effect, as in ~ s(elev, by = lv_axis()) or ~ elev:lv_axis(). Each covariate must take one value per sampling unit. The deprecated by = trend acts as by = lv_axis(). Defaults to ~ -1, factors without predictors.

knots

Optional named list of knot positions for smooth terms, by covariate, as knots of mvgam().

data

A data.frame or list holding the response, the covariates of both formulas, the unit column and the species factor.

Data held as arrays, as unmarked, ubms, flocker, Hmsc and spOccupancy take them, convert to this long format. pivot_detection_array() converts detection histories of occupancy and N-mixture data: ⁠[J, K]⁠, ⁠[N, J, K]⁠, multi-season ⁠[N, J, T, K]⁠ or a list of ⁠[J, K]⁠ matrices per species. pivot_species_matrix() converts a wide ⁠[J, N]⁠ species composition matrix.

newdata

Optional held-out data.frame, stored on the fit as object$test_data. Fitting draws no forecasts. forecast() called without newdata forecasts these times, carrying the fitted latent state forward. plot(fit, type = "series") overlays them. posterior_predict() on these data uses the covariate part alone. The section 'Which prediction function?' of predict.mvgam() compares the two.

family

The observation family every species shares, as a family object. mvgam_families lists them. Defaults to binomial() for presence-absence data. Counts take a count family such as poisson() or negbinomial().

The factors and a family's dispersion parameter, such as shape, phi or sigma, explain the same residual variation. Where the factors explain it, the dispersion posterior runs toward its limit and the sampler can diverge there. An informative dispersion prior or a family without dispersion, such as poisson(), settles it.

For one family per species, write formula with one brms::bf() per species, each naming its family, as in bf(count ~ env, family = poisson()) + bf(seen ~ env, family = bernoulli()). The responses then form the species axis, in place of a species column. family applies to any response that names none.

The simplex families diri(), multi() and categ() need a per-species term, as in y ~ env * species or y ~ 0 + species + env:species. A coefficient shared by every species cancels from their likelihood. In y ~ env, b_Intercept and b_env take their priors alone. mvgam warns of this once per session. diri() sets out the identification.

unit

The unquoted name of the numeric column indexing the sampling units, often time or site. Defaults to time.

species

The unquoted name of the factor column indexing the species. Defaults to series, as in other mvgam models.

priors

Optional brmsprior of priors to set, from brms::prior(). prior, the brms spelling, is accepted in .... get_prior() of a model built with run_model = FALSE lists every class and coefficient with its default, the trait_slopes terms among them. See Trait-mediated responses for their scales. Each loading in Z takes normal(0, s) by default. s is 1, widened as 'brms' widens its default scale priors for responses that spread far on their link scale. A binary response says little about the size of a loading. The light tails keep chains from stalling at extreme values. prior(student_t(3, 0, 1), class = "Z") gives heavier tails.

n_lv

Integer number of latent factors, from 1 to the number of species. Defaults to 2. The residual covariance ⁠Z Z' + diag(Psi^2)⁠ has rank at most the number of species. Further columns of Z add nothing.

Under the default normal prior on Z, or a structured prior built from traits, phylo or loadings_prior$distances, n_lv is the number of factors in the likelihood. Under the multiplicative gamma process prior (loadings_prior = "mgp" or list(column_shrinkage = "mgp", ...)) it is a ceiling. The prior shrinks later columns towards zero. A larger loadings_prior$mgp_a2 shrinks them harder. active_factors() counts the factors the data support.

traits

Optional species traits for a structured loadings prior: a data.frame or matrix with one row per species, or the name of an element of data2. Rows are matched to levels(data[[species]]) by a series column, by row name or by order. Factor columns are one-hot encoded and numeric columns are standardised. They become loadings_prior$features. Supplying an explicit loadings_prior as well is refused.

trait_slopes

Optional one-sided formula of traits, such as ~ trait1 + trait2, for species responses that depend on their traits (the fourth-corner model of Hmsc). The traits must be columns of data, constant within species, as brms takes every variable of a formula. A prediction frame that omits a trait takes each species' value from the fit. The grids of conditional_effects() and marginaleffects omit the traits, which draws each species at its own. Each term of formula takes a shared effect, an effect of each trait and a species deviation. See Trait-mediated responses.

phylo

Optional phylogeny: an ape::phylo tree, whose cophenetic distances are taken, or a numeric distance matrix with row and column names matching levels(data[[species]]). The distances are rescaled to a maximum of 1 and become loadings_prior$distances$phylo. A tree that is not ultrametric draws a warning once. A tree requires the ape package. Supplying an explicit loadings_prior as well is refused.

loadings_prior

Optional structured prior on the loadings, as loadings_prior of mvgam() takes it. Supplying traits or phylo as well is refused.

backend

"cmdstanr" or "rstan". Defaults to getOption("brms.backend") when it is set. Otherwise cmdstanr when it is installed and rstan when it is not.

threads

Positive integer number of threads per chain, or NULL (the default) for none. The model is compiled with cpp_options$stan_threads = TRUE. cmdstanr then samples with threads_per_chain = threads. The closure-unit families (nmix(), occ()) and the multi-response families (diri(), mvn(), mvt(), multi(), categ()) split their likelihood over units with reduce_sum, in about eight chunks. With 50 or more closure units, threads = 4 samples about a third faster. Fewer units can sample slower, the threading overhead outweighing the gain. A brms family without a trend_formula uses the threading brms writes.

A brms family with a trend_formula samples each chain on one thread whatever threads says. The threaded likelihood brms writes leaves no place to add the trend. Each such fit warns.

run_model

Logical. FALSE builds the model without parsing, compiling or sampling it. The result holds ⁠$stancode⁠, ⁠$standata⁠ and the prior table, with ⁠$fit⁠ set to NULL. stancode.mvgam_formula(), standata.mvgam_formula() and get_prior.mvgam_formula() return them. Methods that need draws, such as summary() and forecast(), refuse it. A jsdgam() model has no mvgam_formula(), which makes run_model = FALSE the way to inspect one before fitting. Defaults to TRUE.

...

Further arguments of mvgam(), such as data2 (where traits and phylo find a named element), algorithm, chains and silent.

Value

A fitted model of class c("mvgam", "jsdgam", "brmsfit"). Every mvgam method applies, such as summary(), predict(), forecast() and loo(). ordinate() and residual_cor() describe the factors. update(fit, n_lv = 3) refits it through jsdgam() with the arguments given changed.

Trait-mediated responses

trait_slopes = ~ size adds terms to formula. Each term takes a shared effect, an effect of each trait and a species deviation:

Intercept

size, with the species deviation 1 in (1 + ... | sp | series)

A term with design columns

a numeric or factor covariate, an interaction, I(), poly(), mo(), me() or mi(): the term env:size and the deviation env in (1 + env | sp | series). The ⁠|sp|⁠ tag correlates the deviations under one LKJ prior.

A smooth, s() or t2()

s(x, by = size) scales the smooth by the trait. s(x, by = series, m = 1) gives each species a smooth penalised towards a flat line.

A Gaussian process, gp()

gp(x, by = size) and gp(x, by = series), one approximate process per species

A group-level term

entered as written, as is a smooth with bs = "re" or bs = "fs"

A smooth trait, ~ s(size), gives the intercept s(size). Each design column of a covariate scales the trait's smooth: env takes s(size, by = env) and a factor hab takes s(size, by = habb). A smooth of x takes the surface t2(x, size). A smooth with its own by, such as s(x, by = hab), crosses the trait level by level. Its species deviations keep the by. mo(), me() and mi() terms cross linear traits alone.

A smooth or gp() takes one column of data as its by. A factor level, a poly() column or a by scaled per species enters through a derived column. Its name follows fixef.mvgam(), such as habb, polyx21 or env_size. Each prediction frame recomputes these columns from the variables they come from. A frame that changes env then changes env_size.

A crossing of a centred smooth passes through zero at the mean of its covariates (mgcv's pc). The shared term then carries the effect at the means. mgcv leaves a smooth with a numeric by uncentred. Its crossing keeps the constant, the trait's effect on that column's slope. A t2() surface takes first-order margins. Their penalties separate it from the main smooths. A margin of one covariate is a thin plate spline, or keeps a cyclic basis. An s() of several covariates gives one isotropic Duchon spline margin.

The coefficients take their brms names, such as b_env:size. Each population-level coefficient takes normal(0, r / s) by default. s is the SD of its design column. r is 1, or the SD of the response under an identity link, which keeps the coefficients in its units. Every covariate then has one prior scale on the link, whatever its units or the basis poly() gives it, as rstanarm's autoscaled priors do. ⁠student_t(3, 0, 2.5 r)⁠ is the default on the SDs of the correlated species deviations. The smooth and gp() deviations take the brms defaults. priors overrides any of them. A prior on class b without a coef replaces every coefficient's default. A term of formula naming the species is refused: each species already takes its own response. For some of these terms alone, write them in formula directly, as in y ~ env + size + env:size + (1 + env | series).

References

Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007

Ovaskainen, O., Tikhonov, G., Norberg, A., Blanchet, F. G., Duan, L., Dunson, D., Roslin, T. and Abrego, N. (2017). How to make more out of community data? Ecology Letters, 20(5):561-576. doi:10.1111/ele.12757

Tikhonov, G., Opedal, O. H., Abrego, N., Lehikoinen, A., de Jonge, M. M. J., Oksanen, J. and Ovaskainen, O. (2020). Joint species distribution modelling with the R-package Hmsc. Methods in Ecology and Evolution, 11(3):442-447. doi:10.1111/2041-210X.13345

Hui, F. K. C. (2016). boral - Bayesian Ordination and Regression Analysis of Multivariate Abundance Data in R. Methods in Ecology and Evolution, 7(6):744-750. doi:10.1111/2041-210X.12514

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

See Also

sim_jsdgam() simulates data this function fits. sim_closure_unit_data() simulates the occ() and nmix() case. residual_cor(), ordinate(), shared_variation(), active_factors() and compare_loadings() interpret the fitted factors. species_effects() gives each species' response to the covariates. community() gives richness, diversity and co-occurrence. lv_axis() gives each factor its own covariate effect. how_to_cite() drafts a methods paragraph for the fit and methods_md() writes its equations. The JSDM article fits a negative binomial model with a trait-informed loadings prior, ordination biplots and multiplicative gamma process shrinkage. The JSDM cheatsheet summarises the functions on one page.

Other model fitting: check_newdata(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

## Not run: 
# Detections of 6 species at 80 sites, 4 visits each. Occupancy
# responds to the site covariate `env` and detection to the time of
# day `tod_c`. Two latent factors drive the species associations.
simdat <- sim_closure_unit_data(
  family    = occ(),
  n_species = 6L,
  n_sites   = 80L,
  n_visits  = 4L,
  n_lv      = 2L,
  seed      = 1L
)

# A joint occupancy model. Each species has its own occupancy
# intercept and `env` slope, plus its own detection intercept. Two
# latent factors take up the residual association.
mod <- jsdgam(
  formula        = bf(y ~ series * env, p ~ series + tod_c),
  factor_formula = ~ -1,
  data           = simdat$data_train,
  family         = occ(),
  n_lv           = 2L,
  chains         = 2,
  silent         = 2
)

summary(mod)

# The effect of `env` on the chance of a detection, occupancy times
# detection
conditional_effects(mod)

# Each species' response to env, outlined where its sign is clear
plot(species_effects(mod, variables = "env"))

# The residual correlations among species the factors imply
plot(residual_cor(mod))

# Site scores and species loadings on the two factors
ordinate(mod, rotation = "varimax")

# Expected richness along `env`. The second plot marks the pairs of
# species found together more often than `env` predicts.
gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20))
cm <- community(mod, newdata = gradient)
plot(cm)
plot(cm, type = "cooccurrence")

# The draws, for any contrast: richness at the end of the gradient
# less that at its start
rv <- as_draws_rvars(cm)
rv$richness[20] - rv$richness[1]

# Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo()

## End(Not run)


K-fold cross-validation for mvgam fits

Description

Measures how well a model predicts groups of data it was not fitted to, such as sites or species. Each fold of groups is held out in turn and scored by its expected log predictive density (ELPD). Higher is better. A fold that importance sampling approximates well takes the PSIS estimate of loo::loo() on the fold's summed log likelihood. The rest are refitted without the fold, as lfo_cv.mvgam() refits the time blocks it cannot approximate. Three settings cover the range:

group takes several columns, such as c("site", "season"). Every row of one combination stays in the same fold.

Usage

## S3 method for class 'mvgam'
kfold(
  x,
  K = NULL,
  group = NULL,
  folds = NULL,
  exact = FALSE,
  pareto_k_threshold = NULL,
  fold_split = c("grouped", "stratified", "random"),
  seed = NULL,
  silent = 1L,
  ...
)

## S3 method for class 'mvgam_kfold'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_kfold'
summary(object, ...)

## S3 method for class 'mvgam_kfold'
plot(x, ...)

Arguments

x

A fitted mvgam object, or for the methods an mvgam_kfold object.

K

Integer number of folds. With group and K = NULL (the default), each group is a fold. A K below the number of groups bins the groups into K folds with loo::kfold_split_grouped(). Without group, K defaults to 10.

group

Optional character vector of training-data columns whose combinations define the groups. NULL (the default) takes the closure unit of an occ() or nmix() model and the row otherwise.

folds

Optional integer vector of one fold per training row, replacing K and fold_split. Each fold is then held out and scored as one group. A fold never splits a group, which is a closure unit by default.

exact

Logical. TRUE refits every fold. Defaults to FALSE.

pareto_k_threshold

Numeric. A fold whose Pareto-k exceeds it is refitted. NULL (the default) takes min(1 - 1 / log10(S), 0.7) for S posterior draws. Inf refits nothing.

fold_split

"grouped" (the default), "stratified" or "random": the ⁠loo::kfold_split_*()⁠ function binning groups into K folds when there are more groups than folds.

seed

Optional integer seed for the fold split and the refits. The session's random state is restored when the call returns.

silent

Integer in ⁠\{0, 1, 2\}⁠. 0 prints each refit and its sampler start and finish lines. 1 (default) prints the refit count. 2 prints nothing.

...

Unused. Anything passed here is refused.

digits

Integer number of decimal places. Defaults to 2.

object

An mvgam_kfold object.

Value

A c("mvgam_kfold", "kfold", "loo") object, which loo::loo_compare() takes as it takes loo.mvgam() results. It holds:

print() shows the ELPD with its standard error, the folds and refits and the Pareto k of the PSIS estimates. It then names the groups with the lowest ELPD and the refitted groups whose ELPD moved most from the PSIS estimate. summary() returns a tibble with one row per held-out group: group, its elpd and elpd_share of the total, for a refitted group elpd_psis and the lift of the refit over it, pareto_k and refit. plot() draws the ELPD of each group and its Pareto k, as plot.mvgam_lfo() does for time blocks. Dark red points mark a Pareto k above the dashed threshold, where PSIS is unreliable. In the ELPD panel they mark the groups below the 15% quantile.

Author(s)

Nicholas J Clark

References

Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262

Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4

See Also

loo.mvgam() approximates leave-one-out cross-validation. lfo_cv.mvgam() scores forecasts from rolling origins. summary.mvgam_kfold() and plot.mvgam_kfold() report each group. The forecast evaluation article compares models by cross-validation.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
# Overdispersed counts: a negative binomial size of 2
set.seed(13)
simdat <- sim_mvgam(family = negbinomial(), n_series = 1L,
                     n_timepoints = 120L, type = 6L,
                     family_pars = list(size = 2))

mod <- mvgam(y ~ s(season, bs = "cc", k = 6),
              trend_formula = ~ CAR(),
              data    = simdat$data_train,
              family  = negbinomial(),
              chains  = 2, seed = 1, silent = 2)

# Neighbouring times share information through the trend. Folds of
# contiguous time blocks hold each block out whole. Folds that PSIS
# approximates poorly are refitted.
blocks <- cut(simdat$data_train$time, breaks = 4L, labels = FALSE)
k <- kfold(mod, folds = blocks)
k

# The ELPD and Pareto k of each block
plot(k)

# Next, lfo_cv() scores forecasts made from rolling origins

## End(Not run)


Simulated lake phosphorus with correlated random-walk state

Description

A state-space dataset for five lakes sampled monthly across 60 months. Each sample records total phosphorus in micrograms per litre, drawn from a Gamma distribution with a log link. The latent process is a correlated random walk across lakes. Two regional clusters share positive innovation correlation. A fifth lake is independent. The observation equation adds a binary treatment indicator that switches on at month 31, with heterogeneous slopes across lakes. Phosphorus rises in two lakes and falls in three.

Usage

lake_chemistry

Format

A data.frame with 300 rows and the following fields:

series

factor identifying the lake (alpine, boreal, coastal, delta, estuary); duplicated as lake.

time

integer month index from 1 to 60.

y

positive total phosphorus in micrograms per litre; duplicated as chemistry.

lake

factor, alias of series.

month

integer month index, alias of time.

treated

integer (0/1) treatment indicator; switches on from month 31 onwards in all lakes.

chemistry

positive total phosphorus, alias of y.

Details

A pooled fit with one treatment slope for all lakes reports an effect near zero with a wide credible interval. The positive and negative responses cancel. A state-space fit (trend_formula = ~ RW(cor = TRUE)) with a treatment slope for each lake recovers the response of every lake.

True generative components, on the log scale:

See Also

RW() for the trend, residual_cor() to extract the fitted correlations between lakes, ranef.mvgam() for the lake slopes, mvgam_data() to check the data.

Examples

data(lake_chemistry)
mvgam_data(lake_chemistry, family = Gamma(link = "log"))

## Not run: 
# A model with the structure the data were simulated from
mod <- mvgam(
  formula = y ~ treated + (treated || lake),
  trend_formula = ~ RW(cor = TRUE),
  data = lake_chemistry,
  family = Gamma(link = "log"),
  chains = 2, silent = 2
)
summary(mod)

## End(Not run)

How often each unit's latent state reaches its cap

Description

The sum over a unit's latent abundance stops at its cap K_max. A unit whose posterior abundance often equals the cap is truncated, which biases its abundance down. A higher value in that unit's cap column, then a refit, removes the bias. Under occ() the cap is one, and a unit at its cap is one the species occupies.

Usage

latent_N_saturation(
  object,
  newdata = NULL,
  threshold = 0.05,
  ndraws = NULL,
  draw_ids = NULL
)

Arguments

object

A fitted mvgam with an nmix() or occ() family

newdata

Optional data.frame of visits. NULL takes the training data, whose units take their fitted latent trend.

threshold

Number in ⁠[0, 1]⁠. A unit whose share of draws at its cap exceeds threshold is marked saturated.

ndraws, draw_ids

The number of posterior draws to use, or their indices. Give at most one. NULL for both uses every draw.

Value

A data.frame with one row per closure unit:

unit

The unit's index.

label

The unit's key values, joined by ⁠_⁠.

K_max

The unit's cap.

p_saturated

The posterior probability that the latent state equals K_max.

saturated

p_saturated > threshold.

See Also

nmix(), occ()

Examples

## Not run: 
set.seed(5)
simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L,
                                n_sites = 50L, n_visits = 4L,
                                type = 1L)
# A cap of 3 is low for these counts
dat <- simdat$data_train
dat$cap <- pmax(3L, ave(dat$y, dat$series, dat$time, FUN = max))
mod <- mvgam(bf(y ~ env, p ~ tod_c), data = dat, family = nmix(),
             chains = 2, silent = 2)
saturation <- latent_N_saturation(mod)
saturation[saturation$saturated, ]

# Next, raise 'cap' for the saturated units and refit

## End(Not run)


Approximate leave-future-out cross-validation of fitted mvgam objects

Description

Scores a model on its forecasts. The model is fitted to the times up to min_t and scored on the next fc_horizon observed times. The origin then steps forward one time at a time. Pareto smoothed importance sampling (PSIS) reweights the posterior to each new origin. The model is refitted only where the Pareto k exceeds pareto_k_threshold. The algorithm is that of Burkner, Gabry and Vehtari (2020), as in the loo PSIS-LFO vignette.

The ELPD of each fold is higher for the better model. CRPS and the other scores of score.mvgam_forecast() are lower for the better model. loo.mvgam() explains the ELPD and the Pareto k diagnostic.

Usage

lfo_cv(object, ...)

## S3 method for class 'mvgam'
lfo_cv(
  object,
  newdata = NULL,
  min_t = NULL,
  fc_horizon = 1L,
  pareto_k_threshold = NULL,
  score = "elpd",
  save_log_lik = FALSE,
  silent = 1L,
  ...,
  data = NULL
)

## S3 method for class 'mvgam_lfo'
plot(x, ...)

## S3 method for class 'mvgam_lfo'
summary(object, ...)

## S3 method for class 'mvgam_lfo'
print(x, ...)

Arguments

object

A fitted mvgam object, or for summary() an mvgam_lfo object.

...

Unused. Anything passed here is refused.

newdata

Optional data.frame holding the response, the time and series columns and the covariates. NULL (the default) takes the training data. Every series must share its observed times, except under CAR(), whose series may be observed at their own times.

min_t

The time at which the first training window ends. It must be a time present in the data, which need not be whole for an irregular CAR() grid. NULL (the default) takes the 30th observed time, earlier for a shorter series, leaving at least 10 evaluation origins where the data allow.

fc_horizon

Integer number of observed times after each origin that are scored, whatever the gaps between them. Defaults to 1.

pareto_k_threshold

Numeric. An origin whose Pareto k exceeds it triggers a refit. NULL (the default) takes the adaptive threshold min(1 - 1 / log10(S), 0.7) for S posterior draws (Vehtari et al. 2024). It is stricter for a fit with few draws, where PSIS is less reliable.

score

Character vector of scores to compute at each origin, from "elpd" (the default), "crps", "drps", "sis", "brier", "energy" and "variogram". The ELPD takes the PSIS log-likelihood. The others score forecast draws resampled by the PSIS weights, with score.mvgam_forecast().

save_log_lik

Logical. TRUE keeps the held-out log densities under the reweighted posterior, an ⁠[ndraws, n_eval_obs]⁠ matrix. loo_model_weights.mvgam_lfo() stacks models by it. Defaults to FALSE, the matrix being large.

silent

Integer in ⁠\{0, 1, 2\}⁠. 0 prints each refit and its sampler start and finish lines. 1 (default) and 2 print nothing from the refits.

data

Deprecated alias for newdata.

x

An mvgam_lfo object.

Value

A list of class mvgam_lfo, with one element per origin in each vector.

print() shows the horizon, the Pareto k threshold and the counts of evaluations and refits, with each score's sum and mean over the origins. summary() returns a tibble with one row per origin: eval_time, refit_here, pareto_k (NA at a refit), n_obs and one column per score. plot() draws the Pareto k of each origin and each score. The dashed line marks the threshold above which points are highlighted: the Pareto k threshold, the 15% quantile of the ELPD (lower values highlighted) or the 85% quantile of any other score.

Author(s)

Nicholas J Clark

References

Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262

Vehtari, A., Simpson, D., Gelman, A., Yao, Y. and Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72):1-58. https://jmlr.org/papers/v25/19-556.html

See Also

loo_compare.mvgam_lfo() ranks models by their leave-future-out ELPD. loo_model_weights.mvgam_lfo() weights them. loo.mvgam() approximates leave-one-out cross-validation. kfold.mvgam() runs grouped k-fold cross-validation. The forecast evaluation article runs lfo_cv() on rodent counts, with its Pareto k refits and stacking weights.

Other forecasting: compare_scores(), ensemble.mvgam_forecast(), forecast.mvgam(), forecast_uncertainty(), hindcast(), score()

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
set.seed(11)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())

mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data    = simdat$data_train,
  family  = poisson(),
  chains  = 2, seed = 1, silent = 2
)

# Forecasts one time step after each origin from t = 60, scored by
# ELPD and CRPS. The model is refitted only where the Pareto k is high.
lfo <- lfo_cv(mod, min_t = 60L, score = c("elpd", "crps"))
lfo

# Pareto k, ELPD and CRPS at each origin. Points past the dashed
# line are highlighted
plot(lfo)

# One row per origin, with the refits in 'refit_here'
summary(lfo)

# Next, rank models by their forecasts with loo_compare()

## End(Not run)


List the available trend types

Description

List all registered trend types and their factor model support.

Usage

list_trend_types()

Value

Data frame with trend types and their properties

See Also

Other trend models: LLT(), PW(), ZMVN(), lv_axis(), print.mvgam_trend()


Log-likelihood of a fitted mvgam model

Description

The posterior mean of the summed log likelihood, with the df and nobs attributes that stats::AIC() and stats::BIC() use.

Usage

## S3 method for class 'mvgam'
logLik(object, pointwise = FALSE, ...)

Arguments

object

A fitted mvgam object.

pointwise

Logical. TRUE returns the ⁠[ndraws, nobs]⁠ matrix of log_lik.mvgam(). Defaults to FALSE.

...

Further arguments to log_lik.mvgam(), such as newdata or ndraws.

Details

Each latent state counts as a parameter, which makes AIC and BIC coarse for a state-space model. loo.mvgam() estimates the ELPD with diagnostics for its reliability.

Value

A logLik object. df counts the parameters variables() lists. With pointwise = TRUE, the matrix of log_lik.mvgam().

See Also

log_lik.mvgam() returns the pointwise matrix.


Pointwise log-likelihoods from a fitted mvgam model

Description

The log density of each observation under each posterior draw, as brms::log_lik.brmsfit() returns it. loo.mvgam(), waic.mvgam(), lfo_cv.mvgam() and kfold.mvgam() score models from it.

Usage

## S3 method for class 'mvgam'
log_lik(
  object,
  newdata = NULL,
  re_formula = NULL,
  resp = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  incl_autocor = TRUE,
  process_error = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  ...
)

Arguments

object

A fitted mvgam object.

newdata

Optional data frame holding the response and every covariate of the model. NULL (the default) takes the training data.

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

resp

Optional name of one response of a multivariate model.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

incl_autocor

Logical. TRUE (the default) evaluates each density under the latent trend state the model inferred at that time, the state hindcast.mvgam() returns. The ELPD then describes the series that was observed. FALSE keeps only the trend's deterministic terms and leaves the autocorrelation out.

process_error

Deprecated alias for incl_autocor.

allow_new_levels

Logical. TRUE scores rows whose grouping level the training data lacked, as kfold.mvgam() needs when a fold holds out whole groups. Defaults to FALSE.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default), "gaussian" or "old_levels".

...

Unused. Anything passed here is refused.

Details

Each family uses the brms parameterisation. For example, negbinomial() takes a mean and shape, Beta() a mean and precision. Hurdle and zero-inflated families mix a mass at zero with their base family. The weights(), cens() and trunc() addition terms change each row's contribution as they do in the Stan model.

The posterior_epred.mvgam() family of methods uses the covariate part of the model by default. A covariate effect then has the same meaning at every time. Those predictions describe no particular observed series and do not give an ELPD.

Value

A numeric ⁠[ndraws, nobs]⁠ matrix of log densities. A missing response gives a column of NA. For a multivariate fit with resp = NULL, each column sums the densities of the responses measured in that row, as brms does. An occupancy, N-mixture or composition family has one density per site, carried on the site's first row.

See Also

loo.mvgam() and waic.mvgam() estimate the ELPD from this matrix. hindcast.mvgam() returns the latent states it conditions on. The forecast evaluation article compares models by cross-validation.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())

mod <- mvgam(y ~ s(x, k = 5),
              trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# One row per draw, one column per observation
ll <- log_lik(mod)
dim(ll)

# Without the latent trend, the densities are far lower. The trend
# explains most of the series
ll_fixed <- log_lik(mod, incl_autocor = FALSE)
c(with_trend = mean(rowSums(ll)), without = mean(rowSums(ll_fixed)))

# Next, loo() estimates the ELPD from these densities

## End(Not run)


Approximate leave-one-out cross-validation for mvgam models

Description

Estimates the expected log predictive density (ELPD) of each observation had it been left out of the fit, with loo::loo(). The ELPD measures how well a model predicts data it has not seen. Higher is better. Each observation also takes a Pareto k diagnostic. Above 0.7 the approximation is unreliable for that observation.

Usage

## S3 method for class 'mvgam'
loo(
  x,
  ...,
  compare = TRUE,
  resp = NULL,
  pointwise = FALSE,
  moment_match = FALSE,
  reloo = FALSE,
  k_threshold = 0.7,
  save_psis = FALSE,
  moment_match_args = list(),
  reloo_args = list(),
  model_names = NULL,
  incl_autocor = TRUE,
  incl_dynamics = NULL,
  by_series = FALSE
)

## S3 method for class 'mvgam'
loo_compare(
  x,
  ...,
  criterion = c("loo", "waic"),
  model_names = NULL,
  incl_autocor = TRUE,
  incl_dynamics = NULL
)

Arguments

x

A fitted mvgam or jsdgam object.

...

For loo(), further arguments to loo::loo(). For loo_compare(), further fitted models.

compare, resp, pointwise, moment_match, reloo, k_threshold, save_psis, moment_match_args, reloo_args

The arguments of brms::loo.brmsfit. mvgam uses two of them. resp scopes a multivariate fit to one response. save_psis keeps the smoothing object. Supplying any of the others raises an error. To compare several models, pass the fits to loo_compare.mvgam().

model_names

Character vector of row names for the comparison, one per model. NULL takes them from the call.

incl_autocor

Logical, default TRUE. Passed to log_lik.mvgam(). TRUE scores each observation under the latent trend state the model inferred at that time. The ELPD then describes the series that was observed. FALSE scores the covariate part of the model alone.

incl_dynamics

Deprecated alias for incl_autocor.

by_series

Logical, default FALSE. TRUE returns a data frame with one row per series and columns series, elpd, se_elpd, p and n_obs, as spOccupancy::waicOcc(by.sp = TRUE) ranks species. An occupancy or N-mixture fit is scored per site, each site counted in its species.

criterion

"loo" (the default) or "waic".

Details

Exact leave-one-out cross-validation would refit the model once per observation. Pareto smoothed importance sampling (PSIS) avoids the refits. It re-weights the posterior draws of the one fit to approximate the posterior without each observation (Vehtari et al. 2017). loo::loo() describes the method.

The approximation often fails for a fit with a latent trend. Each observation strongly informs the state at its own time. Removing it changes that part of the posterior a great deal. The importance weights then vary widely. Many observations get a Pareto k above 0.7. The effective number of parameters also climbs towards the number of observations. Check the Pareto k diagnostics before trusting a comparison. lfo_cv.mvgam() refits along the time axis and scores each window against data the model has not seen. forecast.mvgam() with score.mvgam_forecast() scores a held-out horizon.

Value

For loo.mvgam, an object of class psis_loo (see loo::loo()). For loo_compare.mvgam, the compare.loo table of loo::loo_compare(), one row per model, best first. Its p_worse, diag_diff and diag_elpd columns follow Sivula et al. (2025).

Which comparison tool?

Fit to the observed data

loo() or waic.mvgam(), ranked with loo_compare.mvgam(). Trust it for a model without a trend, or once the Pareto k diagnostics are low.

Skill at forecasting

lfo_cv.mvgam() on each model, ranked with loo_compare.mvgam_lfo() and plotted with compare_elpds().

Accuracy over one held-out horizon

forecast.mvgam() with score.mvgam_forecast(), several models at once with compare_scores().

Prediction for held-out sites or species

kfold.mvgam() with group.

The ELPD is higher for the better model. CRPS, DRPS and the other scores of score.mvgam_forecast() are lower for the better model.

Author(s)

Nicholas J Clark

References

Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4

Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262

Sivula, T., Magnusson, M., Matamoros, A. A. and Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. Bayesian Analysis. doi:10.1214/25-BA1569

See Also

lfo_cv.mvgam() scores forecasts by refitting along the time axis. kfold.mvgam() runs grouped k-fold cross-validation. loo_model_weights.mvgam() weights models by their predictions. The forecast evaluation article compares models by approximate and exact cross-validation.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The same smooth of x replaced by a linear effect
mod_lin <- update(mod, formula. = y ~ x)

# The ELPD estimate, with Pareto k diagnostics for each observation
loo(mod)

# The better model comes first, with elpd_diff = 0. The diagnostic
# columns say how far the difference can be trusted
loo_compare(mod, mod_lin)

# Next: lfo_cv() scores each model's forecasts of data it has not
# seen

## End(Not run)


Compare leave-future-out evaluations across models

Description

Ranks two or more lfo_cv() results by their summed ELPD, in the layout of loo::loo_compare(). The standard error of each difference comes from the paired per-fold differences with the best model. The results must share one evaluation grid, with the same min_t, fc_horizon and data.

Usage

## S3 method for class 'mvgam_lfo'
loo_compare(x, ..., model_names = NULL)

Arguments

x

An mvgam_lfo object.

...

Further mvgam_lfo objects.

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

Value

A compare.loo table in the layout of loo::loo_compare(), one row per model, best first.

model

The model's name.

elpd_diff

Summed ELPD difference from the best model, zero for the best.

se_diff

Standard error of elpd_diff, sqrt(N) * sd(fold_diff) over the N folds.

p_worse

The normal probability that the model forecasts worse than the best one (Sivula et al. 2025). NA for the best model and for a difference without spread.

diag_diff

"N < 100" for fewer than 100 folds, else "|elpd_diff| < 4" for a difference too small for its SE.

diag_elpd

The number of folds whose PSIS estimate was kept with a Pareto k above the threshold.

elpd_lfo

Summed per-fold ELPD.

se_elpd_lfo

Standard error of elpd_lfo.

References

Sivula, T., Magnusson, M., Matamoros, A. A. and Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. Bayesian Analysis. doi:10.1214/25-BA1569

See Also

lfo_cv(), loo_model_weights.mvgam_lfo(), compare_elpds(), plot.mvgam_compare_elpds()

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), mvgam_loo_extras, posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
# Each origin after t = 70 forecasts the next time step. The
# pointwise log densities feed stacking weights
lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE)
lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE)

# The model with the higher summed ELPD comes first
loo_compare(lfo_gam, lfo_ar, model_names = c("GAM", "AR"))

# Next, compare_elpds() shows where along the series the models
# part ways

## End(Not run)


Model weights from mvgam_lfo objects

Description

Weights for combining models evaluated by lfo_cv() on one rolling-origin grid, for example in ensemble.mvgam_forecast(). Yao et al. (2018) describe both methods.

Usage

## S3 method for class 'mvgam_lfo'
loo_model_weights(x, ..., method = "pseudo-BMA", model_names = NULL)

Arguments

x

An mvgam_lfo object.

...

Further mvgam_lfo objects, weighted in the order given.

method

"pseudo-BMA" (the default) or "stacking".

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

Value

A named numeric vector of weights summing to 1, of class "pseudobma_weights" or "stacking_weights".

References

Yao, Y., Vehtari, A., Simpson, D., Gelman, A. (2018). Using stacking to average Bayesian predictive distributions. Bayesian Analysis 13(3): 917-1003. doi:10.1214/17-BA1091

See Also

loo_compare.mvgam_lfo(), lfo_cv(), ensemble.mvgam_forecast(), compare_elpds(), plot.mvgam_compare_elpds()

Examples

## Not run: 
set.seed(2)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
# Each origin after t = 70 forecasts the next time step. The
# pointwise log densities feed stacking weights
lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE)
lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE)

# Pseudo-BMA weights come from the summed ELPDs
loo_model_weights(lfo_gam, lfo_ar, model_names = c("GAM", "AR"))

# Stacking weights come from the pointwise log densities
w <- loo_model_weights(lfo_gam, lfo_ar, method = "stacking",
                       model_names = c("GAM", "AR"))
w

# The stacking weights combine the two forecasts
fc <- ensemble(forecast(mod_gam, newdata = simdat$data_test),
               forecast(mod_ar, newdata = simdat$data_test),
               weights = w)
plot(fc)

## End(Not run)


Vary a trend effect along the trend's axis

Description

Use lv_axis() in a trend_formula in any position that takes a factor variable, to give each latent factor its own effect. In a model with no latent factors it gives each series its own effect. Use it when a covariate should act differently on different series, such as temperature raising one species and lowering another.

Usage

lv_axis()

Details

For example:

trend_formula = ~ s(elev, by = lv_axis()) + AR(n_lv = 2)
trend_formula = ~ temp:lv_axis() + AR(n_lv = 2)
trend_formula = ~ (1 + temp | lv_axis()) + AR()
trend_formula = ~ s(temp, lv_axis(), bs = "fs") + AR()

With n_lv set on the trend constructor, each factor ⁠k = 1, ..., n_lv⁠ takes its own effect. The effect of a covariate on series s is the sum over factors of the loading Z[s, k] times the effect on factor k. This is constrained ordination, the model jsdgam() fits. Every term of such a trend_formula is then evaluated once per factor and time. Each covariate must take one value per time.

With no n_lv, each series takes its own effect on the latent state.

The series column itself is not supported in a trend_formula term. Write lv_axis() for an effect that differs along the trend's axis. An effect of the series on the observations belongs in formula. by = trend is deprecated and is treated as by = lv_axis().

Value

NULL (invisibly). The function only marks a term in a formula.

What each form estimates

With no latent factors, lv_axis() is each series:

With n_lv latent factors, each of these is estimated once per factor. The coefficient of one factor has no scale of its own. The loadings and the factor effects trade scale. The data identify their product. conditional_effects.mvgam() and predict.mvgam() report that product, the effect of the covariate on each series. conditional_effects.mvgam() draws a panel per series. When every lv_axis() term is a slope or a level, summary.mvgam() reports the per-factor coefficients in the basis of the identified loadings Z_tilde.

See Also

jsdgam() fits per-factor effects across species. conditional_effects.mvgam() plots the effect on each series. The dynamic factor vignette fits factor models. The JSDM article fits per-factor trait and covariate effects.

Other trend models: LLT(), PW(), ZMVN(), list_trend_types(), print.mvgam_trend()

Examples

# `lv_axis()` marks a term in a formula. Called by itself it
# returns NULL.
lv_axis()

## Not run: 
# Proportions in three series whose seasonal effect on the logit
# scale differs: 1, 0.5 and -1
set.seed(1)
dat <- sim_mvgam(family = Beta(), n_series = 3L,
                 n_timepoints = 60L)$data_train
dat$season <- sin(2 * pi * dat$time / 12)
dat$y <- plogis(qlogis(dat$y) +
                  c(1, 0.5, -1)[as.integer(dat$series)] * dat$season)

# One seasonal slope per series
mod <- mvgam(
  formula       = y ~ 1,
  trend_formula = ~ season:lv_axis() + AR(p = 1),
  data          = dat,
  family        = Beta(),
  chains        = 2,
  silent        = 2
)
summary(mod)
conditional_effects(mod)

# With two latent factors, each factor takes a seasonal slope. The
# loadings carry the two slopes to the three series. The prior
# table lists one coefficient per factor. A smooth takes the same
# marker: `s(season, by = lv_axis())`
get_prior(
  mvgam_formula(y ~ 1,
                trend_formula = ~ season:lv_axis() + AR(p = 1, n_lv = 2)),
  data   = dat,
  family = Beta()
)

## End(Not run)


MCMC plots of mvgam parameters with bayesplot

Description

Draws any bayesplot MCMC plot of the posterior, as brms::mcmc_plot() does. Without variable, the plot shows the parameters pairs.mvgam() shows: the population coefficients, the trend parameters and the family parameters.

Usage

## S3 method for class 'mvgam'
mcmc_plot(object, type = "intervals", variable = NULL, regex = FALSE, ...)

Arguments

object

A fitted mvgam object.

type

The plot type, the name of a bayesplot ⁠mcmc_*()⁠ function without its prefix. bayesplot::available_mcmc() lists them. The default "intervals" shows posterior intervals. "trace" and "rank_overlay" check mixing. "nuts_energy" and the other "nuts_*" types diagnose the sampler.

variable

Either a keyword shortcut, a character vector of parameter names, or (when regex = TRUE) a vector of regular expressions. Recognised keywords:

  • "betas": population-level coefficients, the set brms::fixef() reports (⁠b_*⁠, ⁠bs_*⁠, ⁠bsp_*⁠ and ⁠bcs_*⁠).

  • "obs_params": observation-family distributional parameters (sigma, phi, shape, ...).

  • "smooth_params": smooth-term standard deviations (⁠sds_*⁠).

  • "trend_betas": the trend formula's population-level coefficients (⁠b_*_trend⁠, ⁠bs_*_trend⁠ and ⁠bsp_*_trend⁠).

  • "trend_params": trend-dynamics parameters (autoregressive coefficients, innovation SDs, ...).

  • "trend_smooth_params": trend-side smooth SDs.

NULL (the default) returns every parameter. A bare vector name, such as "sigma_trend", selects every element. Group-level effects, factor loadings and latent states have no keyword. Select them by name. variables.mvgam() lists the names a fit holds.

regex

Logical. When TRUE, each entry of variable is treated as a regular expression and any parameter matching at least one pattern is selected. Keyword shortcuts are still honoured. Defaults to FALSE.

...

Further arguments to the bayesplot function, such as prob for "intervals" or true for the "recover_*" types.

Value

A ggplot object, or a bayesplot_grid for "pairs" and "combo".

See Also

mvgam_draws lists the shortcuts variable accepts, such as "trend_params". pairs.mvgam() plots the joint posterior. See the bayesplot MCMC overview.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Posterior intervals of the trend parameters
mcmc_plot(mod, variable = "trend_params", type = "intervals")

# Rank histograms of the same parameters check that the chains mix
mcmc_plot(mod, variable = "trend_params", type = "rank_overlay")

# Next, pairs() shows how the parameters covary

## End(Not run)


The equations of a model, as Markdown

Description

Writes the model in mathematical notation for a methods section. The Data section names the response, the dimensions and the predictors. The Model section holds the likelihood, the linear predictors and the latent dynamics in one display equation, with a glossary of every symbol. The Priors section states every prior the Stan program applies. The Implementation section gives the call that fits the model and the software versions the fit recorded. The equations are LaTeX inside ⁠$$⁠ fences, which Quarto, R Markdown and MathJax render.

Usage

methods_md(object, file = NULL, implementation = TRUE, ...)

## S3 method for class 'mvgam'
methods_md(object, file = NULL, implementation = TRUE, heading_level = 2L, ...)

Arguments

object

A fitted mvgam or jsdgam object, or a prefit from mvgam(..., run_model = FALSE).

file

Optional path. The Markdown is written there and returned invisibly.

implementation

Logical. TRUE (the default) adds the Implementation section.

...

Unused. Anything passed here is refused.

heading_level

Integer Markdown level of the section headings. The default 2 writes ⁠## Model⁠. A higher level nests the sections under a heading of the host document.

Value

A character string of class mvgam_methods_md, which prints as its Markdown.

Author(s)

Nicholas J Clark

See Also

how_to_cite() writes the matching methods paragraph and its references. prior_summary() lists the priors as a table.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# The equations, glossary and priors as Markdown
md <- methods_md(mod)
md

# Written to a file, nested under a level-two heading
methods_md(mod, file = tempfile(fileext = ".md"), heading_level = 3L)

# Next, forecast(mod) predicts the times after the training data

## End(Not run)


Extract a model frame from a fitted mvgam object

Description

Returns the model's training data restricted to the response plus the variables find_predictors() reports. Used by upstream consumers (insight, marginaleffects::datagrid) when they walk the model frame to build prediction grids.

Usage

## S3 method for class 'mvgam'
model.frame(formula, trend_effects = FALSE, ...)

Arguments

formula

A fitted mvgam object.

trend_effects

Logical; if TRUE and the model has a trend formula, return the trend submodel's covariates only.

...

Unused. Anything passed here is refused.

Value

A data frame.


Multinomial family for counts over several categories

Description

For counts of several categories made together on each unit, such as the sequence counts of several taxa in a sample. The data hold one row per category at each unit. Each unit's vector of K counts is multinomial with probabilities softmax(mu), where mu holds the categories' linear predictors. A unit's total is the sum of its counts and may differ between units.

Usage

multi()

Details

jsdgam() fits the family, taking the unit and category columns and the number of latent factors n_lv. The constraints that identify the model are those of diri().

Value

A family object to pass to jsdgam() or mvgam().

Identification

The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:

A loadings_prior combines with that constraint.

Post-fit conventions

The density is joint over a unit's components, which makes the unit the grain of log_lik(), loo() and waic() (Vehtari et al. 2017). log_lik() gives each unit's log density on its first row and NA on the others. loo() then counts each unit once. loo_compare() needs every model it compares scored at that grain.

posterior_linpred() gives mu per row before the reference subtraction. posterior_epred() gives the expected shares, which sum to one within each unit.

species_effects(), variance_partition() and forecast_uncertainty(scale = "link") report the predictor centred across each unit's components, the centred log-ratio scale. A shift shared by every component then drops out.

References

Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007

See Also

Other observation families: beta_nb(), categ(), com_binomial(), diri(), mvgam_families, mvn(), mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# Counts of four categories at 60 sites, 30 per site
simdat <- sim_jsdgam(family = multi(), n_species = 4L, n_sites = 60L,
                     seed = 3L)

fit <- jsdgam(
  formula        = y ~ env * series,
  factor_formula = ~ -1,
  data           = simdat$data_train,
  unit           = time, species = series,
  family         = multi(),
  n_lv           = 1L,
  chains         = 2L,
  silent         = 2
)

# The probability of each category along the gradient
conditional_effects(fit, effects = "env:series")

# Next, residual_cor(fit) gives the correlations the factor implies

## End(Not run)


Fit a Bayesian multivariate state-space model

Description

Fits a state-space model in Stan. Each observation follows the observation family. On the link scale its mean is the sum of the effects in formula and a latent trend z_{t,s} for series s at time t. The data never record the trend directly. trend_formula names how it moves from one time to the next, through a trend constructor such as AR(). It also takes predictors of the trend. With an AR(p = 1) trend:

g(\mu_{t,s}) = \eta_{t,s} + \eta^{(z)}_{t,s} + z_{t,s}, \qquad z_{t,s} = \phi_s z_{t-1,s} + \epsilon_{t,s}

Here g is the link, \eta the predictor from formula, \eta^{(z)} the predictor from trend_formula and \epsilon the trend's innovation at each time. The overview article walks through a full analysis.

Usage

mvgam(
  formula,
  trend_formula = NULL,
  data = NULL,
  newdata = NULL,
  loadings_prior = NULL,
  backend = default_backend(),
  combine = TRUE,
  family = gaussian(),
  threads = NULL,
  save_pars = brms::save_pars(),
  run_model = TRUE,
  ...
)

Arguments

formula

The observation model formula, in brms syntax: smooths s() and t2(), gp(), varying intercepts and slopes, mm(), mo(), me(), mi(), distributional and non-linear sub-formulas and offset(). A response leaves rows out by holding NA there. mvgam_formula() lists the terms each formula refuses. gp() takes the approximate Hilbert-space form (gp(x, k = 20)) or the exact form (gp(x), no k), under any brms kernel. An exact term predicts at new covariate values by conditioning on its fitted values, as brms does. Its cost grows with the cube of the number of unique values.

trend_formula

A one-sided formula for the latent process: a trend constructor such as AR() with any predictors of the latent state. Write lv_axis() in a term to vary its effect by latent factor, or by series in a model without factors, as in ~ x:lv_axis() + AR().

data

Data frame in long format, one row per series and time. A model with a trend needs a numeric time column and a factor series column, or the columns a trend constructor names through its time and series arguments. mvgam_data() checks a frame against a family before fitting. A list of multiply imputed data frames, or a mids object from mice, is also accepted. mvgam_multiple() describes the imputation path.

newdata

Optional held-out data.frame, stored on the fit as object$test_data. Fitting draws no forecasts. forecast() called without newdata forecasts these times, carrying the fitted latent state forward. plot(fit, type = "series") overlays them. posterior_predict() on these data uses the covariate part alone. The section 'Which prediction function?' of predict.mvgam() compares the two.

loadings_prior

Optional named list giving a structured prior on the loadings of a factor model, such as species traits or a phylogeny. Most models leave it NULL. The section 'Structured loadings priors' of mvgam() describes its fields.

backend

"cmdstanr" or "rstan". Defaults to getOption("brms.backend") when it is set. Otherwise cmdstanr when it is installed and rstan when it is not.

combine

Logical. With imputed data, TRUE (default) pools the imputation fits into one and FALSE returns them as a list.

family

A description of the response distribution and link function, given as a family function, a call to one or its name. Supports most brms families, including the ordinal families (brms::cumulative(), brms::sratio(), brms::cratio(), brms::acat()). The brms families needing a separate linear predictor per response category, brms::categorical(), brms::multinomial() and brms::dirichlet(), are refused: use categ(), multi() and diri(), which take the categories in long format and share one latent structure across them. A family whose mean has to stay positive needs a link that keeps it there once a trend enters the linear predictor: pair stats::Gamma(), brms::weibull(), brms::exponential(), brms::frechet() and stats::inverse.gaussian() with link = "log". Their default links leave the mean positive only where the predictor is. A latent trend is centred near zero and reaches negative values, where the likelihood is undefined. mvgam() warns before fitting. brms::lognormal() is the exception: its mu is a log-scale location that takes any sign.

A family written inside a univariate brms::bf() is the model's family, as in brms. In a multivariate model each response may take its own family, in which case name it inside that response's brms::bf(): bf(count ~ x, family = poisson()) + bf(seen ~ x, family = bernoulli()). Passing a list of families to this argument, as brms::brm() allows, is not supported; the family belongs to the response that names it. A single family given here applies to every response that does not name one of its own. Closure-unit and multi-response families (occ(), nmix(), mvn(), mvt(), diri(), multi(), categ()) lay their data out by unit. Each models its response alone and cannot be one response of a multivariate model.

threads

Positive integer number of threads per chain, or NULL (the default) for none. The model is compiled with cpp_options$stan_threads = TRUE. cmdstanr then samples with threads_per_chain = threads. The closure-unit families (nmix(), occ()) and the multi-response families (diri(), mvn(), mvt(), multi(), categ()) split their likelihood over units with reduce_sum, in about eight chunks. With 50 or more closure units, threads = 4 samples about a third faster. Fewer units can sample slower, the threading overhead outweighing the gain. A brms family without a trend_formula uses the threading brms writes.

A brms family with a trend_formula samples each chain on one thread whatever threads says. The threaded likelihood brms writes leaves no place to add the trend. Each such fit warns.

save_pars

A brms::save_pars() object naming which parameters the posterior keeps. A model is built from working variables it also reports under another name: the standardised deviates a group-level block is scaled from, the unscaled coefficients a shrinkage prior scales, the ordered intercepts a mixture is identified by. Those are left out by default, as brms leaves them out. save_pars(all = TRUE) keeps every one. group and latent keep the per-level deviations and the latent values of a me() covariate or a mi() response with known noise. manual names individual parameters to keep.

run_model

Logical. FALSE builds the model without parsing, compiling or sampling it. The result holds ⁠$stancode⁠, ⁠$standata⁠ and the prior table, with ⁠$fit⁠ set to NULL. stancode.mvgam_formula(), standata.mvgam_formula() and get_prior.mvgam_formula() return them. Methods that need draws, such as summary() and forecast(), refuse it. A jsdgam() model has no mvgam_formula(), which makes run_model = FALSE the way to inspect one before fitting. Defaults to TRUE.

...

Further arguments for the model and its sampler.

prior takes a brmsprior built with brms::prior(). Its rows replace the matching defaults. get_prior.mvgam_formula() lists every class a model takes, with trend classes carrying a ⁠_trend⁠ suffix. The plural priors is accepted as well.

chains, iter, warmup, thin, seed and control reach Stan as in brms::brm(). chains defaults to 4, each running 2000 iterations of which the first half are warmup. Results for publication should use at least four. The examples use two for speed. If the sampler reports divergent transitions, refit with control = list(adapt_delta = 0.95) or simplify the model. mvgam_diagnostics describes the checks. cores sets how many chains sample at once. It defaults to getOption("mc.cores") when that option is set and otherwise to one fewer than the machine's cores, up to chains.

silent sets how much the fit prints. 0 shows everything, Stan's own messages included. 1, the default, shows the sampler's progress and mvgam's notices. 2 prints warnings alone.

algorithm selects how the posterior is explored. It accepts "sampling" (the default), "meanfield", "fullrank" or "fixed_param" on either backend, plus "pathfinder" and "laplace" when backend = "cmdstanr".

init sets the starting values. It accepts "random" (the default), "0", a numeric value, a list or a function. With backend = "cmdstanr" it also accepts "pathfinder". That keyword runs Stan's Pathfinder approximation on the compiled model and draws one starting value per chain from it. Sampling then proceeds as usual from those values. It helps a model whose chains stall at a poor starting point or fill warmup with divergences. On a model that already warms up cleanly it adds about a second and lowers effective samples per second.

Five arguments shape the Stan program and reach brms unchanged:

  • knots gives knot positions by covariate name, for the observation and trend formulas alike.

  • drop_unused_levels decides whether a factor level with no observations still takes a coefficient.

  • sample_prior takes "no", "yes" or "only". Under "only" the observation likelihood drops out and the latent process keeps its prior. The draws then show what the model implies before any response is observed.

  • normalize = FALSE drops the normalising constants from the sampling statements. Sampling is faster and the posterior is unchanged.

  • save_model names a file to write the Stan program to.

Value

An object of class mvgam.

Structured loadings priors

A factor trend loads each series on a few latent factors through the matrix Z. By default each entry of Z takes an independent student_t(3, 0, 0.5) prior. The static factors of ZMVN() take normal(0, 1), as jsdgam() describes. Both scales widen with the responses' spread on their link scale. loadings_prior replaces the default with the structured prior of Heaps and Jermyn (2024). Each column of Z then follows a multivariate normal whose covariance Phi makes similar series load alike. Phi is the product of a kernel over series features and one factor exp(-d / theta) per distance matrix. The argument requires a trend_formula whose trend has latent factors.

The list takes these fields:

features

Per-series features, as a numeric matrix, a data frame or the name of an element of data2. Numeric, integer and logical columns are z-scored. An ordered factor is z-scored on its codes. An unordered factor or character column is one-hot encoded with every level kept (Heaps and Jermyn 2024, Section 6.2). Each encoded column takes its own length-scale.

distances

Pairwise distance matrices, as the names of elements of data2, a matrix or a named list of matrices. Each is rescaled to a largest entry of 1.

column_shrinkage

"iid", the default, shrinks no column. "mgp" shrinks later columns more strongly through the multiplicative gamma process of Bhattacharya and Dunson (2011), applied to the shared innovation scale. AR(), RW() and ZMVN() trends accept it. A VAR() trend builds its own innovation covariance. It takes "iid".

mgp_a1, mgp_a2

The hyperparameters of "mgp", by default 2 and 4. Heaps and Jermyn used an mgp_a2 of 3 and 6 in their two applications. A lower mgp_a2 shrinks less, for data that weakly identify the number of active factors.

Each length-scale takes a lognormal(0, 1) prior. Distances are rescaled to a largest entry of 1. A length-scale of 1 then gives a correlation of exp(-1) between the two most distant series. Heaps and Jermyn used the wider lognormal(0, sqrt(10)). A prior() on theta_features or ⁠theta_dist_<name>⁠ replaces the default. They rescaled a phylogeny to a root-to-tip distance of 1, which gives a largest pairwise distance of 2. Rescale a distance matrix before fitting to match their scale.

The prior applies to the sampled columns of Z. The reported loadings Z_tilde come from a QR rotation of them. Each column of Z_tilde mixes the sampled columns. shared_variation() and residual_cor() use ⁠Z Z'⁠, which the rotation leaves unchanged. The Identification section of trend_constructors describes the rotation.

A trend_map with no fixed entries, NULL or a matrix of NA, is compatible. A trend_map that fixes any loading is refused. Its free entries take the default prior of class Z, which the structured prior would duplicate.

Terms used in this documentation

Latent trend, latent state

The unobserved value z_{t,s} that the trend constructor evolves over time.

Innovation

The random change the trend takes at each time step, \epsilon_{t,s} above. Other texts call it a process error or a shock. cor = TRUE correlates the innovations of different series.

Fitted state, covariate part

The two versions of the trend a prediction can use. The section 'Which prediction function?' of predict.mvgam() defines them.

Prior

A distribution stating which values of a parameter are plausible before the data are seen. get_prior.mvgam_formula() lists the defaults.

Posterior draw

One joint sample of every parameter from the posterior distribution. Summaries and predictions average over the draws.

Hindcast, forecast

Predictions at the training times and after them. See hindcast.mvgam() and forecast.mvgam().

Closure unit

A site, or a site in one season, whose true occupancy or abundance holds across its repeat visits. See occ() and nmix().

ELPD, Pareto k

The expected log predictive density scores predictions of held-out data. Higher is better. A Pareto k above 0.7 marks an observation whose leave-one-out approximation is unreliable. See loo.mvgam().

Workflow

A typical analysis takes these steps:

  1. Check the data with mvgam_data().

  2. Choose a family (mvgam_families) and a trend (trend_constructors). Inspect the default priors with get_prior.mvgam_formula().

  3. Fit with mvgam(), then check convergence with summary.mvgam() and mvgam_diagnostics.

  4. Check the fit against the data with pp_check.mvgam() and plot(fit, type = "residuals").

  5. Interpret effects with conditional_effects.mvgam().

  6. Forecast with forecast.mvgam(). Compare models with lfo_cv.mvgam() or loo.mvgam().

  7. Report the model with how_to_cite() and methods_md().

References

Clark, N. J. and Wells, K. (2023). Dynamic Generalized Additive Models for forecasting discrete ecological time series. Methods in Ecology and Evolution, 14:771-784. doi:10.1111/2041-210X.13974

Burkner, P.-C. (2017). brms: An R package for Bayesian multilevel models using Stan. Journal of Statistical Software, 80(1):1-28. doi:10.18637/jss.v080.i01

Wood, S. N. (2017). Generalized Additive Models: An Introduction with R (2nd edition). Chapman and Hall/CRC.

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

Bhattacharya, A. and Dunson, D. B. (2011). Sparse Bayesian infinite factor models. Biometrika, 98(2):291-306. doi:10.1093/biomet/asr013

Riutort-Mayol, G., Burkner, P.-C., Andersen, M. R., Solin, A. and Vehtari, A. (2023). Practical Hilbert space approximate Bayesian Gaussian processes for probabilistic programming. Statistics and Computing, 33:1. doi:10.1007/s11222-022-10167-2

See Also

trend_constructors lists the latent trends. mvgam_families lists the observation families mvgam adds to those of brms. how_to_cite() writes a methods paragraph for a fitted model. methods_md() writes its equations. jsdgam() fits joint species distribution models. The overview vignette introduces the package. The data vignette sets out the data format. The forecast evaluation article scores and compares forecasts. The multivariate formula article fits several responses at once. The integrated distribution model article ties several observation families to one latent process. The cheatsheet summarises the main functions on one page.

Other model fitting: check_newdata(), jsdgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

## Not run: 
# One count series with a smooth effect of a covariate x and an
# AR(1) latent trend, split into training and test times
set.seed(2)
simdat <- sim_mvgam(family = poisson(), n_timepoints = 100L,
                    trend_model = AR(), prop_trend = 0.5)
head(simdat$data_train)

# The parameters a model takes, with their default priors, before
# any fitting. A `prior` argument to mvgam() replaces any of them
get_prior(
  mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)),
  data   = simdat$data_train,
  family = poisson()
)

# A smooth of x in the observation model and an AR(1) latent trend.
# The test data are stored on the fit for forecasting
mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data          = simdat$data_train,
  newdata       = simdat$data_test,
  family        = poisson(),
  chains        = 2,
  silent        = 2
)
summary(mod)

# Do draws from the model resemble the observed counts?
pp_check(mod)

# The effect of x on the expected count
conditional_effects(mod)

# Forecasts of the test times, with the held-out counts overlaid
plot(forecast(mod))

# A methods paragraph with its references
how_to_cite(mod)

# Next: a slope that drifts over time takes `s(time, by = x)` in the
# formula. loo() and lfo_cv() compare models. The articles under
# 'See Also' fit many series, factor models and VAR trends

## End(Not run)


Fitted mvgam object description

Description

A fitted mvgam object returned by function mvgam. Run methods(class = "mvgam") to see an overview of available methods.

Details

A fit from mvgam() has class c("mvgam", "brmsfit"). The accessors are the supported way in. variables(), as_draws_df() and as.data.frame() return the posterior. stancode() and standata() return the program and its data. prior_summary() returns the prior table. The elements are listed below.

The fit and its inputs:

The Stan program:

The model specification, used by prediction and forecasting:

How it was fitted:

A fit from jsdgam() has class c("mvgam", "jsdgam", "brmsfit") and one further element. Its data carries time and series columns copied from the unit and species columns:

Author(s)

Nicholas J Clark

See Also

mvgam, jsdgam, mvgam_forecast


Inspect long-format data before fitting an mvgam

Description

Runs the checks mvgam() applies to its data before compiling a model. It tests the columns, factor levels, time spacing and response support of a proposed model. A failure raises the error mvgam() would raise. An optional plot shows each observed series.

Usage

mvgam_data(
  data,
  y = NULL,
  family = gaussian(),
  formula = NULL,
  trend_formula = NULL,
  data2 = NULL,
  plot = TRUE,
  newdata = NULL,
  series = NULL,
  lines = TRUE,
  n_bins = NULL,
  log_scale = FALSE
)

Arguments

data

Long-format data.frame (or list) carrying at least the response column and a time column. A latent trend also needs each row's series: a series column, the column the trend constructor's series argument names, or the gr and subgr columns of a hierarchical trend. Closure-unit families (occ(), nmix()) always require series and visit columns. A family without a default cap also requires a cap column.

y

Optional name of the response column. NULL (default) takes the response of formula, or "y" when formula is NULL. A name that differs from the response of formula is refused.

family

A family, brmsfamily or mvgam family object. Defaults to gaussian(). The response must lie in the family's support, such as non-negative integers for poisson() or ⁠(0, 1)⁠ for Beta(). A cap column must hold integers no smaller than the response and stay constant within a closure unit. Multi-response families (diri(), multi(), categ(), mvn(), mvt()) are refused. mvgam() and jsdgam() check their data at fit time.

formula

Optional observation formula, as a formula or a brmsformula. A closure-unit family takes a detection formula in the same bf(). Every column the formula uses must be in data. These include covariates, offsets, random-effect grouping factors and the columns of addition terms such as trials() and weights(). Those columns may not hold NA. A trials() count may not fall below its response. A missing response is allowed. mvgam() keeps its row on the time grid.

trend_formula

Optional trend formula (e.g. ~ AR(time = week, series = species) + s(env)), as passed to mvgam(). Its trend constructor names the time and series columns and decides whether times must be evenly spaced: CAR() and ZMVN() accept gaps, most others refuse them. NULL checks the data for a model without a trend, which needs no series column. Its covariates, offsets and grouping factors get the same checks as those of formula.

data2

Optional named list of further model data, as passed to mvgam(). A formula variable found here, such as a matrix covariate, need not be a column of data.

plot

Logical. TRUE (default) draws the observed series with the panels of plot(fit, type = "series"). Several series draw as one facet each. One series draws four panels: the time series, a histogram, the ACF and the empirical CDF.

newdata

Optional held-out data in the long format of data. The time series panels draw it in black after a dashed line at the first test time. The histogram, ACF and CDF of one series pool the training and test values.

series

Series to plot: NULL, "all", a series name or a positive index into the series levels. NULL draws every series of multi-series data and the one series otherwise. Data without a series column plot as one series named after the response.

lines

Logical. Plot lines (default) or points.

n_bins

Optional histogram bin count.

log_scale

Logical. Plot the response as log(y + 1).

Value

Invisibly, an mvgam_data list with elements data (the validated data), family (the resolved family), series_levels (NULL when the data name no series), n_series, time_range, n_obs, n_missing (the count of missing responses) and plot (the ggplot or patchwork object when plot = TRUE, else NULL). With plot = TRUE the plot is also drawn on the active device.

Author(s)

Nicholas J Clark

See Also

mvgam(), mvgam_formula(), jsdgam(), sim_mvgam(), sim_closure_unit_data(), get_prior.mvgam_formula().

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 3L,
                    n_timepoints = 60L)

# Check the frame for a Poisson trend model and plot every series
mvgam_data(simdat$data_train, family = poisson(),
           trend_formula = ~ AR())

# One series in four panels: time series, histogram, ACF and ECDF.
# The test data follow the dashed line.
mvgam_data(simdat$data_train, family = poisson(), series = 1L,
           newdata = simdat$data_test)

# A response the family cannot take is refused before any Stan
# compile. The error names the column, the values and the support.
counts <- simdat$data_train
counts$y[3L] <- -1
try(mvgam_data(counts, family = poisson(), plot = FALSE))

# AR() assumes evenly spaced times. CAR() models the gaps.
gappy <- simdat$data_train[simdat$data_train$time != 5L, ]
try(mvgam_data(gappy, family = poisson(), trend_formula = ~ AR(),
               plot = FALSE))
mvgam_data(gappy, family = poisson(), trend_formula = ~ CAR(),
           plot = FALSE)


Posterior summaries and sampler diagnostics of mvgam models

Description

The brms and bayesplot accessors for a fitted model. fixef() and vcov() summarise the population-level coefficients of the observation formula, or of the trend formula with trend_effects = TRUE. coef() gives each level of each grouping factor its coefficients: the population effect plus that level's deviation, as brms::coef.brmsfit() does. posterior_summary() summarises any parameters. rhat() and neff_ratio() report convergence. nuts_params() and log_posterior() return the sampler's own quantities. bayes_R2() is the Bayesian R^2 of Gelman et al. (2019). ndraws(), nchains(), niterations() and nvariables() count the posterior.

Usage

## S3 method for class 'mvgam'
coef(object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam'
nuts_params(object, pars = NULL, ...)

## S3 method for class 'mvgam'
log_posterior(object, ...)

## S3 method for class 'mvgam'
rhat(x, pars = NULL, ...)

## S3 method for class 'mvgam'
neff_ratio(object, pars = NULL, ...)

## S3 method for class 'mvgam'
fixef(
  object,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  pars = NULL,
  trend_effects = FALSE,
  ...
)

## S3 method for class 'mvgam'
bayes_R2(
  object,
  resp = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  by_series = FALSE,
  ...
)

## S3 method for class 'mvgam'
prior_summary(object, ...)

## S3 method for class 'mvgam'
ndraws(x, ...)

## S3 method for class 'mvgam'
nchains(x, ...)

## S3 method for class 'mvgam'
niterations(x, ...)

## S3 method for class 'mvgam'
nvariables(x, ...)

## S3 method for class 'mvgam'
posterior_summary(
  x,
  pars = NULL,
  variable = NULL,
  probs = c(0.025, 0.975),
  robust = FALSE,
  ...
)

## S3 method for class 'mvgam'
getCall(x, ...)

## S3 method for class 'mvgam'
vcov(object, correlation = FALSE, pars = NULL, trend_effects = FALSE, ...)

Arguments

object, x

A fitted mvgam object.

summary

Logical. TRUE (the default) returns a summary. FALSE returns the draws.

robust

Logical. TRUE summarises by the median and the median absolute deviation. Defaults to FALSE, the mean and the standard deviation.

probs

Numeric vector of the two interval probabilities, c(0.025, 0.975) by default.

...

Further arguments. nuts_params() and log_posterior() pass them to bayesplot. bayes_R2() passes them to posterior_epred.mvgam(). The other methods refuse them.

pars

Optional character vector of parameter names, or of sampler parameters such as "divergent__" for nuts_params(). NULL takes all of them.

trend_effects

Logical. fixef() and vcov() report the coefficients of the observation formula by default. TRUE reports those of the trend_formula instead. Their names end in ⁠_trend⁠.

resp

Optional name of one response of a multivariate model.

by_series

Logical, for bayes_R2(). TRUE computes the fit of each series from its own rows. A binary response, such as bernoulli() or the detections of occ(), adds Tjur's R^2 and the AUC. Tjur's R^2 is the mean predicted probability of the rows observed as 1 less that of the rows observed as 0. The AUC is the probability that a row observed as 1 is predicted above a row observed as 0. A series observed at one value alone takes NA for both. Defaults to FALSE.

variable

Parameter names for posterior_summary(), the brms name of the argument. There pars is its deprecated alias.

correlation

Logical. TRUE returns the correlation matrix of the coefficients. Defaults to FALSE, the covariance matrix.

Value

fixef(), posterior_summary() and bayes_R2() return a matrix with columns Estimate, Est.Error and one per quantile, or the draws with summary = FALSE. Under by_series = TRUE bayes_R2() returns a data frame with one row per series and measure, or draws in columns named ⁠<measure>[<series>]⁠, such as AUC[sp1]. coef() returns a named list with one array per grouping factor: levels, statistics and coefficients, or draws, levels and coefficients with summary = FALSE. A fit without group-level effects in its observation formula is refused. A level's coefficient omits the terms of other covariates that change it, such as env:size under jsdgam()'s trait_slopes. species_effects() gives each species' full response. vcov() returns the covariance matrix of the coefficients. rhat() and neff_ratio() return a named vector with one value per parameter. nuts_params() and log_posterior() return the long data frames of bayesplot. The counting methods return an integer.

Checking a fit

Three checks come before any interpretation of a fit. Vehtari et al. (2021) give the thresholds for the first two.

  1. Every Rhat should be below 1.01. max(rhat(mod)) gives the largest. A higher value means the chains disagree about the posterior. Longer chains, such as update(mod, iter = 4000), often resolve it.

  2. The bulk and tail effective sample sizes should exceed 400. summary.mvgam() prints them as Bulk_ESS and Tail_ESS. Longer chains raise them.

  3. There should be no divergent transitions. The fit warns when there are any. sum(nuts_params(mod, pars = "divergent__")$Value) counts them. A divergence marks a region of the posterior the sampler could not explore. Its draws may then be biased. Refit with smaller sampler steps, update(mod, control = list(adapt_delta = 0.95)).

Divergences that persist at a higher adapt_delta usually mean the data cannot separate some of the parameters. A common cause is a smooth with more flexibility than the series supports, competing with the trend for the same variation. A smaller basis, such as s(x, k = 5), or a more informative prior then helps.

Author(s)

Nicholas J Clark

References

Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: An improved Rhat for assessing convergence of MCMC. Bayesian Analysis, 16(2):667-718. doi:10.1214/20-BA1221

Gelman, A., Goodrich, B., Gabry, J. and Vehtari, A. (2019). R-squared for Bayesian regression models. The American Statistician, 73(3):307-309. doi:10.1080/00031305.2018.1549100

See Also

summary.mvgam() prints these summaries for every parameter. mcmc_plot.mvgam() plots the draws. mvgam_draws extracts them. loo_R2.mvgam() is the leave-one-out R^2.

Other model checking: plot.mvgam(), pp_check.mvgam(), residuals.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# The population coefficients with 95% intervals
fixef(mod)

# Rhat below 1.01 and effective sample ratios above 0.1 suggest the
# chains mixed
rhat(mod, pars = c("ar1_trend", "sigma_trend"))
neff_ratio(mod, pars = c("ar1_trend", "sigma_trend"))

# The share of variance in the counts the model explains
bayes_R2(mod)

# Next, mcmc_plot() draws the posterior of these parameters

## End(Not run)


Extract posterior draws from fitted mvgam objects

Description

Extract posterior draws as a data frame, matrix or array, or as one of the ⁠posterior::draws_*⁠ classes. Parameters take their brms names, such as b_x and sd_grp__Intercept. A trend parameter indexed by series takes the series name, as in sigma_trend[series_1]. The integrated data model article contrasts intercepts drawn with as_draws_df().

Usage

## S3 method for class 'mvgam'
as.data.frame(
  x,
  row.names = NULL,
  optional = TRUE,
  variable = NULL,
  draw = NULL,
  regex = FALSE,
  ...
)

## S3 method for class 'mvgam'
as.matrix(x, variable = NULL, draw = NULL, regex = FALSE, ...)

## S3 method for class 'mvgam'
as.array(x, variable = NULL, draw = NULL, regex = FALSE, ...)

## S3 method for class 'mvgam'
as_draws(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

## S3 method for class 'mvgam'
as_draws_matrix(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

## S3 method for class 'mvgam'
as_draws_df(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

## S3 method for class 'mvgam'
as_draws_array(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

## S3 method for class 'mvgam'
as_draws_list(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

## S3 method for class 'mvgam'
as_draws_rvars(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)

Arguments

x

A fitted mvgam object.

row.names, optional

Ignored.

variable

Either a keyword shortcut, a character vector of parameter names, or (when regex = TRUE) a vector of regular expressions. Recognised keywords:

  • "betas": population-level coefficients, the set brms::fixef() reports (⁠b_*⁠, ⁠bs_*⁠, ⁠bsp_*⁠ and ⁠bcs_*⁠).

  • "obs_params": observation-family distributional parameters (sigma, phi, shape, ...).

  • "smooth_params": smooth-term standard deviations (⁠sds_*⁠).

  • "trend_betas": the trend formula's population-level coefficients (⁠b_*_trend⁠, ⁠bs_*_trend⁠ and ⁠bsp_*_trend⁠).

  • "trend_params": trend-dynamics parameters (autoregressive coefficients, innovation SDs, ...).

  • "trend_smooth_params": trend-side smooth SDs.

NULL (the default) returns every parameter. A bare vector name, such as "sigma_trend", selects every element. Group-level effects, factor loadings and latent states have no keyword. Select them by name. variables.mvgam() lists the names a fit holds.

draw

Optional positive integer indices of the draws to keep, counted across chains. NULL (the default) keeps every draw.

regex

Logical. When TRUE, each entry of variable is treated as a regular expression and any parameter matching at least one pattern is selected. Keyword shortcuts are still honoured. Defaults to FALSE.

...

Unused. Anything passed here is refused.

inc_warmup

Logical. Include warmup draws? Defaults to FALSE. A fit holds them only when sampled with save_warmup = TRUE.

Value

A data.frame, matrix, array, or one of the ⁠posterior::draws_*⁠ classes (draws_matrix, draws_array, draws_df, draws_list, draws_rvars) depending on the method dispatched.

Author(s)

Nicholas J Clark

See Also

mvgam_diagnostics for higher-level summaries derived from these draws (rhat, neff_ratio, fixef, bayes_R2, posterior_summary, ...), variables.mvgam() to list every parameter name in the fit, mcmc_plot.mvgam() for diagnostic visualisations, summary.mvgam() for a printed model summary, tidy.mvgam() for a tibble of parameter summaries, posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam() for prediction-scale outputs, posterior::draws for the underlying draws classes.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Trend-dynamics parameters as a data frame of draws
head(as.data.frame(mod, variable = "trend_params"))

# Regular expressions select by pattern, here the smooth's basis
# coefficients and its smoothing SD
colnames(as.matrix(mod, variable = c("^s_", "^sds_"), regex = TRUE))

# One random variable per parameter, printed as mean and SD
as_draws_rvars(mod, variable = "trend_params")

# Next, mcmc_plot(mod) plots the same draws

## End(Not run)


Observation families supported by mvgam

Description

mvgam() and jsdgam() accept the observation families that brms and stats define. mvgam adds families for data that ecological and epidemiological series tend to produce. They cover counts observed with imperfect detection, compositions and counts whose dispersion a negative binomial cannot reach.

Pass a family as you would to brms::brm() or stats::glm(), for example mvgam(y ~ x, trend_formula = ~ AR(p = 1), family = nmix()). The N-mixture article fits nmix(). The JSDM article fits a joint species distribution model.

Families mvgam adds

Each fixes its link. com_binomial() takes a link argument that accepts "logit" alone. The table lists every argument.

Family Link Arguments
tweedie() log M, the truncation point of the compound Poisson sum
beta_nb() log none
com_binomial() logit link, "logit" only
nmix() log (state), logit (detection) type, one of "poisson_binomial", "royle_nichols" or "poisson_poisson"; multi_season
occ() logit (state and detection) multi_season
diri() softmax over each unit's categories none
multi() softmax over each unit's categories none
categ() softmax over each unit's categories none
mvn() identity none
mvt() identity none

Choosing by the shape of the response

Real-valued

stats::gaussian(), brms::student(), brms::skew_normal(), brms::exgaussian(), brms::asym_laplace() and brms::von_mises() for angles.

Non-negative real-valued

stats::Gamma(), brms::lognormal(), brms::exponential(), brms::weibull(), brms::frechet() and stats::inverse.gaussian(). tweedie() takes continuous data with a point mass at zero. With a trend, give these families link = "log". Their mean must stay positive. Under the identity, inverse or 1/mu^2 link it stays positive only where the linear predictor is positive on every row. A latent trend is centred near zero and takes negative values, where the likelihood is undefined. stats::Gamma() defaults to the inverse link. mvgam() warns when a trend meets one of these links. lognormal() is the exception. Its mu is a log-scale location that takes any sign. identity is the right link for it.

A single proportion on ⁠(0, 1)⁠

Beta(), with brms::zero_inflated_beta() or brms::zero_one_inflated_beta() when the bounds are attainable.

Compositions and choices among categories

diri() for proportions summing to one, multi() for counts across categories and categ() for one chosen category per unit.

Binary

brms::bernoulli().

Counts out of a known number of trials

stats::binomial(). brms::beta_binomial() takes overdispersed trials. com_binomial() takes trials that are under- or over-dispersed.

Unbounded counts

stats::poisson(), brms::negbinomial(), brms::geometric() and their zero-inflated and hurdle counterparts (see brms::brmsfamily()). beta_nb() takes tails heavier than a negative binomial reaches.

Repeat visits to a site

nmix() estimates latent abundance from repeated counts. occ() estimates latent occupancy from repeated detection histories.

Several responses measured together

mvn() and mvt(), whose residual correlations come from a latent factor structure.

Ordered

brms::cumulative(), brms::sratio(), brms::cratio() and brms::acat().

Link functions

A brms or stats family takes a link argument as usual. poisson(link = "sqrt") and Gamma(link = "log") both work. The families mvgam adds each have the one link the table gives.

Data layout

nmix() and occ() are closure-unit families. A closure unit is a site, or a site in one season, whose true occupancy or abundance holds across its repeat visits. The families expect several rows per closure unit, one per visit. They model the state and the detection process with separate linear predictors. bf() supplies the second, as in bf(y ~ elev, p ~ tod). sim_closure_unit_data() simulates the layout they take. pivot_detection_array() reshapes a site-by-visit array into it. diri(), multi(), categ(), mvn() and mvt() also take several rows per unit, one per category or response.

What the family changes after fitting

A closure-unit family adds predict(type = "latent_state") and predict(type = "detection"). It supports pp_check(type = "fit_stat"). It refuses the pp_check() types that assume one observation per row.

brms::dirichlet(), brms::multinomial() and brms::categorical() are refused with a pointer to diri(), multi() and categ(). These fit the same responses in mvgam's long-format layout. brms::logistic_normal() is refused with a pointer to mvn(), which fits the additive log-ratios of the proportions.

See Also

mvgam(), jsdgam(), brms::brmsfamily(), get_prior(), posterior_predict.mvgam(), sim_closure_unit_data()

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvn(), mvt(), nmix(), occ(), tweedie()

Examples

# Families are constructed, then passed to `family`
nmix(type = "royle_nichols")
com_binomial()
tweedie(M = 40L)

# A brms or stats family still takes its own link
poisson(link = "sqrt")

# The layout occ() takes: one row per visit to each site
head(sim_closure_unit_data(family = occ())$data_train)

# Next, get_prior() lists the priors a family's parameters take


mvgam_fevd object description

Description

The objects returned by fevd(). Run methods(class = "mvgam_fevd") and methods(class = "mvgam_fevd_summary") to see an overview of available methods.

Usage

## S3 method for class 'mvgam_fevd'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_fevd'
plot(x, series = NULL, contributing = NULL, ...)

Arguments

object

An mvgam_fevd object from fevd(summary = FALSE).

probs

The lower and upper percentiles of the interval. Defaults to c(0.025, 0.975).

...

Unused. Anything passed here is refused.

x

An mvgam_fevd object.

series

Optional positions or names of the target processes drawn as panels. Defaults to every process.

contributing

Optional positions or names of the source processes stacked in each panel. Their shares are renormalised to sum to one. Defaults to every process.

Details

A forecast error variance decomposition quantifies how much of the forecast uncertainty in one series of a Vector Autoregression is attributable to each of the others. It is built from the orthogonalised impulse response coefficient matrices \Psi_h, which give the contribution of series j to the h-step forecast error variance of series k:

\sigma_k^2(h) = \sum_{j=1}^K(\psi_{kj, 0}^2 + \ldots + \psi_{kj, h-1}^2) \quad

Dividing the orthogonalised responses (\psi_{kj, 0}^2 + \ldots + \psi_{kj, h-1}^2) by the forecast error variance \sigma_k^2(h) gives the proportion of the forecast error variance for k explained by an exogenous shock to j. These objects hold that proportion.

The orthogonalisation takes the lower Cholesky factor of the innovation covariance. The decomposition then depends on the order of the series. The first series takes all of its own one-step forecast error variance. Each later series shares its one-step variance with the series before it. The order is that of the levels of the series factor.

A decomposition is a K by K matrix per horizon per posterior draw, which on a wide panel runs to hundreds of megabytes. A reader needs only a median and an interval from them. fevd() returns that summary. The two forms have different classes:

Both forms take ndraws and draw_ids. A subset of the posterior computes faster.

Methods

summary() turns the draws into the mvgam_fevd_summary above, at the percentiles probs sets. plot() stacks the median share of each source in one panel per target, by horizon. A summary plots through plot.mvgam_var_surface_summary().

Author(s)

Nicholas J Clark

References

Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1

See Also

mvgam(), VAR(), fevd(), irf()


mvgam_forecast object description

Description

A mvgam_forecast object returned by function hindcast or forecast. Run methods(class = "mvgam_forecast") to see an overview of available methods.

Usage

## S3 method for class 'mvgam_forecast'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_forecast'
print(x, ...)

Arguments

object

An mvgam_forecast object.

probs

The lower and upper quantiles reported with the median. Defaults to c(0.025, 0.975).

...

Unused. Anything passed here is refused.

x

An mvgam_forecast object.

Details

A mvgam_forecast object contains the following elements:

Methods

print() gives the family, the number of series, the sizes of the training and forecast windows and the number of draws. summary() returns a long tibble with one row per series and time: the median and the two quantiles of probs, the observed value for type = "response" and the prediction type. Trend components add a component column, their names joined by " + ". A multivariate fit on a long frame adds a leading resp column. plot.mvgam_forecast() draws the object.

Author(s)

Nicholas J Clark

See Also

mvgam, hindcast.mvgam, forecast.mvgam


insight S3 methods for mvgam objects

Description

Minimum surface that marginaleffects and insight need to build prediction grids and walk formula structure. mvgam keeps its observation submodel formula in x$formula (a brmsformula) and its trend submodel formula in x$trend_formula. These methods combine both into the structures insight expects. The default formula walker fails on the combined observation and trend representation.


mvgam_irf object description

Description

The objects returned by irf(). Run methods(class = "mvgam_irf") and methods(class = "mvgam_irf_summary") to see an overview of available methods.

Usage

## S3 method for class 'mvgam_irf'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_irf'
plot(x, series = 1, responses = NULL, ...)

Arguments

object

An mvgam_irf object from irf(summary = FALSE).

probs

The lower and upper percentiles of the interval. Defaults to c(0.025, 0.975).

...

Unused. Anything passed here is refused.

x

An mvgam_irf object.

series

Position or name of the process given the shock.

responses

Optional positions or names of the processes drawn as response panels. Defaults to every process.

Details

Generalized or Orthogonalized Impulse Response Functions are computed from the posterior estimates of Vector Autoregressive parameters. irf() applies a positive shock of one standard deviation to one process and calculates how each process in the latent VAR responds over h horizons, for every process in turn. Horizon 1 is the time step of the shock. stability() computes community-level metrics of stability from the same parameters.

A shock response is a K by K matrix per horizon per posterior draw. On a wide panel the draws run to hundreds of megabytes, where a median and an interval are what a reader uses. irf() returns the summary by default. The two forms carry different classes:

Both forms take ndraws and draw_ids. A subset of the posterior shortens the computation.

Methods

summary() turns the draws into the mvgam_irf_summary above, at the percentiles probs sets. plot() draws the response of each process to a shock to series, with its median and interval by horizon. A summary plots through plot.mvgam_var_surface_summary().

Author(s)

Nicholas J Clark

References

Pesaran HH and Shin Y (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters 58, 17-29. doi:10.1016/S0165-1765(97)00214-0

See Also

mvgam, VAR, irf, stability


Leave-one-out predictions, R-squared and criteria for mvgam models

Description

The brms methods that take their weights from loo.mvgam(). loo_predict(), loo_epred() and loo_linpred() reweight posterior predictions by the PSIS weights of each observation, approximating the prediction made without it. loo_predictive_interval() gives the leave-one-out predictive interval. loo_R2() is the Bayesian R^2 of Gelman et al. (2019) computed from leave-one-out predictions. add_criterion() stores criteria on the fit. LOO() and WAIC() are the brms aliases of loo.mvgam() and waic.mvgam().

Usage

## S3 method for class 'mvgam'
LOO(
  x,
  ...,
  compare = TRUE,
  resp = NULL,
  pointwise = FALSE,
  moment_match = FALSE,
  reloo = FALSE,
  k_threshold = 0.7,
  save_psis = FALSE,
  moment_match_args = list(),
  reloo_args = list(),
  model_names = NULL
)

## S3 method for class 'mvgam'
WAIC(
  x,
  ...,
  compare = TRUE,
  resp = NULL,
  pointwise = FALSE,
  model_names = NULL
)

## S3 method for class 'mvgam'
loo_R2(
  object,
  resp = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  seed = NULL,
  args_epred = list(),
  args_loglik = list(),
  ...
)

## S3 method for class 'mvgam'
loo_predict(
  object,
  type = c("mean", "var", "quantile"),
  probs = 0.5,
  psis_object = NULL,
  resp = NULL,
  ...
)

## S3 method for class 'mvgam'
loo_epred(
  object,
  type = c("mean", "var", "quantile"),
  probs = 0.5,
  psis_object = NULL,
  resp = NULL,
  ...
)

## S3 method for class 'mvgam'
loo_linpred(
  object,
  type = c("mean", "var", "quantile"),
  probs = 0.5,
  psis_object = NULL,
  resp = NULL,
  ...
)

## S3 method for class 'mvgam'
loo_predictive_interval(object, prob = 0.9, psis_object = NULL, ...)

## S3 method for class 'mvgam'
loo_subsample(x, ..., compare = TRUE, resp = NULL, model_names = NULL)

## S3 method for class 'mvgam'
loo_moment_match(
  x,
  loo = NULL,
  k_threshold = 0.7,
  newdata = NULL,
  resp = NULL,
  check = TRUE,
  recompile = FALSE,
  ...
)

## S3 method for class 'mvgam'
loo_model_weights(x, ..., model_names = NULL)

## S3 method for class 'mvgam'
add_criterion(
  x,
  criterion,
  model_name = NULL,
  overwrite = FALSE,
  file = NULL,
  force_save = FALSE,
  ...
)

Arguments

x, object

A fitted mvgam object.

...

Further arguments to the method each function calls. loo_R2() refuses them.

compare, pointwise, moment_match, reloo, k_threshold, save_psis, moment_match_args, reloo_args

As in loo.mvgam(), which describes the two it uses and refuses the rest.

resp

Optional name of one response of a multivariate model.

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

summary

Logical. TRUE (the default) returns the summary matrix with Estimate, Est.Error and interval columns. FALSE returns the draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Numeric vector of probabilities for quantile computation. Default is c(0.025, 0.975) for 95% credible intervals.

seed

Optional integer seed. The session's random state is restored when the call returns.

args_epred, args_loglik

Lists of further arguments to posterior_epred.mvgam() and log_lik.mvgam() for loo_R2().

type

The expectation: "mean" (the default), "var" or "quantile".

psis_object

Optional psis object from loo(x, save_psis = TRUE), reused across calls.

prob

Interval mass of loo_predictive_interval(), 0.9 by default as in brms.

loo, newdata, check, recompile

Accepted for the brms signature of loo_moment_match(), which mvgam refuses.

criterion

Character vector of criteria for add_criterion(): "loo", "waic", "bayes_R2" or "loo_R2".

model_name

Optional name stored in x$model_name.

overwrite

Logical. TRUE recomputes criteria x$criteria already holds.

file

Optional path without extension. The fit is saved to paste0(file, ".rds") with its criteria.

force_save

Unused. Accepted for the brms signature.

Value

loo_predict(), loo_epred() and loo_linpred() return a matrix with one row per scored observation and a column per expectation. loo_predictive_interval() returns its two quantile columns. loo_R2() returns a one-row summary, or its draws with summary = FALSE. add_criterion() returns x with the criteria in x$criteria. loo_model_weights() returns the weights of loo::loo_model_weights().

The observations scored

The weights and the predictions describe the observation the likelihood scored. For most families that is a row of the data. The detection families (occ(), nmix()) write their likelihood per closure unit, marginalising its visits. loo_predict(), loo_epred(), loo_predictive_interval() and loo_R2() then sum a unit's visits and return one value per unit, in the column order of log_lik.mvgam(). loo_linpred() is refused for them. A sum of linear predictors over visits has no interpretation.

mvn() and mvt() keep one density per row. The composition families (diri(), multi(), categ()) hold one joint density per site. These methods refuse them.

Author(s)

Nicholas J Clark

References

Gelman, A., Goodrich, B., Gabry, J. and Vehtari, A. (2019). R-squared for Bayesian regression models. The American Statistician, 73(3):307-309. doi:10.1080/00031305.2018.1549100

See Also

loo.mvgam() estimates the ELPD these weights come from. bayes_R2.mvgam() is the in-sample R^2. lfo_cv.mvgam() scores forecasts of data the model has not seen.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), posterior_average.mvgam(), waic.mvgam()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The leave-one-out R^2 is lower than the in-sample one
loo_R2(mod)
bayes_R2(mod)

# One PSIS object serves every leave-one-out prediction
psis <- loo(mod, save_psis = TRUE)$psis_object
head(loo_predict(mod, psis_object = psis))
head(loo_predictive_interval(mod, psis_object = psis))

# Next, loo_compare() ranks models by their ELPD

## End(Not run)


marginaleffects methods for mvgam objects

Description

These methods let marginaleffects::predictions(), marginaleffects::slopes() and marginaleffects::comparisons() take an mvgam fit. get_predict() returns the posterior draws in the posterior_draws attribute. marginaleffects computes every summary from those draws. The uncertainty comes from the draws alone. marginaleffects also calls get_coef(), get_vcov() and set_coef(). Their output leaves every result unchanged.

Prediction scale

mvgam registers three type values with marginaleffects:

marginaleffects takes "response" as the default. Pass type = "expected" for the expectation. comparisons() and slopes() replace "response" with "expected". A contrast differences two predictions. Observation noise in each would widen it. A slope also divides that noise by a small step. The result keeps the label "response". predictions() on "response" keeps the observation noise. marginaleffects summarises the draws by their posterior median. For a right-skewed predictive distribution the median falls below the mean.

An occ() or nmix() fit takes two more types. "detection" gives the detection probability of each visit. "latent_N" gives the latent state that mvgam's own methods call "latent_state". marginaleffects checks type against its own list, which records that state as "latent_N". Each row of a grid from marginaleffects::datagrid() becomes its own closure unit.

The latent trend

By default (process_error = FALSE) each prediction takes the covariate part of the trend: the effects in its formula, without its innovations. Each posterior draw keeps its own coefficients. The result shows the effect of the covariates with the latent process at its mean. Its credible band leaves out the uncertainty of the latent state.

Under a nonlinear link this falls short of the model's own E[Y]. Averaging over the innovations of an AR(1) trend raises a log-link expectation by the factor \exp(\sigma^2 / (2(1 - \rho^2))). process_error = TRUE adds the innovations. Slopes and comparisons then describe E[Y], with wider bands.

When the trend explains most of the variation in a series, the covariates have little left to explain under either setting. hindcast.mvgam() and forecast.mvgam() return the state the model inferred.

References

Arel-Bundock, V., Greifer, N. and Heiss, A. (2024). How to interpret statistical models using marginaleffects for R and Python. Journal of Statistical Software, 111(9):1-32. doi:10.18637/jss.v111.i09

See Also

conditional_effects.mvgam() for quick effect plots, posterior_epred.mvgam() for the predictions these methods take.

Examples

## Not run: 
library(marginaleffects)
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 60L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, seed = 2, silent = 2)

# Average change in the expected count per unit of x
avg_slopes(mod, variables = "x", type = "expected")

# The same slope with the trend's innovations averaged in
avg_slopes(mod, variables = "x", type = "expected",
           process_error = TRUE)

# Expected counts across the range of x
plot_predictions(mod, condition = "x", type = "expected")

## End(Not run)


Fit mvgam models to multiply imputed datasets

Description

Fits one model to each of several imputed datasets and pools the draws, as brms::brm_multiple() does. The pooled posterior holds the uncertainty the imputations add. mvgam(data = ) takes the same list and fits the same models.

Usage

mvgam_multiple(formula, trend_formula = NULL, data_list, combine = TRUE, ...)

Arguments

formula

The observation model formula, in brms syntax: smooths s() and t2(), gp(), varying intercepts and slopes, mm(), mo(), me(), mi(), distributional and non-linear sub-formulas and offset(). A response leaves rows out by holding NA there. mvgam_formula() lists the terms each formula refuses. gp() takes the approximate Hilbert-space form (gp(x, k = 20)) or the exact form (gp(x), no k), under any brms kernel. An exact term predicts at new covariate values by conditioning on its fitted values, as brms does. Its cost grows with the cube of the number of unique values.

trend_formula

A one-sided formula for the latent process: a trend constructor such as AR() with any predictors of the latent state. Write lv_axis() in a term to vary its effect by latent factor, or by series in a model without factors, as in ~ x:lv_axis() + AR().

data_list

A list of at least two imputed data frames, or a mids object from mice.

combine

Logical. With imputed data, TRUE (default) pools the imputation fits into one and FALSE returns them as a list.

...

Further arguments to mvgam(), such as family, backend, newdata, chains or iter. Every imputation fit stores newdata.

Details

The imputations must hold the same columns, of the same classes, in the same order, with the same number of rows. The columns that place each row on the time and series axes must match exactly. Impute only the response and the covariates.

rstan::sflist2stanfit() concatenates the chains of every imputation fit. The pooled draws then hold both the within- and the between-imputation variance. Because chains from different imputations sample different posteriors, the R-hat of the pooled chains measures disagreement between imputations. summary() reports each parameter's largest R-hat and summed ESS over the imputation fits. It also tabulates the convergence of each fit.

Value

With combine = TRUE, a pooled fit of class mvgam_pooled, which inherits the class of the imputation fits. Its attribute individual_fits holds those fits. With combine = FALSE, the list of imputation fits. With run_model = FALSE, one unfitted model built from the first dataset. Pooling needs draws, which an unfitted model lacks.

See Also

mvgam(), summary.mvgam_pooled()

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

## Not run: 
# A covariate with ten missing values, filled three ways. An
# imputation model would draw the fills. This example draws them
# from a normal distribution.
set.seed(1)
dat <- sim_mvgam(family = poisson(), n_series = 1L,
                 n_timepoints = 60L, trend_model = AR())$data_train
missing_x <- sample(nrow(dat), 10L)
dat$x[missing_x] <- NA
imputed_list <- lapply(1:3, function(i) {
  filled <- dat
  filled$x[missing_x] <- rnorm(10L, mean(dat$x, na.rm = TRUE),
                               sd(dat$x, na.rm = TRUE))
  filled
})

# One fit per imputation, with the posteriors pooled
fit_pooled <- mvgam_multiple(
  formula = y ~ x,
  trend_formula = ~ AR(p = 1),
  data_list = imputed_list,
  family = poisson(),
  chains = 2,
  silent = 2
)

# The summary adds the convergence of each imputation fit
summary(fit_pooled)

# Next, `combine = FALSE` returns the three fits as a list

## End(Not run)


mvgam_residcor object description

Description

A mvgam_residcor object returned by function residual_cor(). Run methods(class = "mvgam_residcor") to see the available methods.

Usage

## S3 method for class 'mvgam_residcor'
plot(
  x,
  type = c("correlation", "precision"),
  cluster = FALSE,
  rescale = FALSE,
  supported_only = FALSE,
  ...
)

## S3 method for class 'mvgam_residcor_list'
plot(
  x,
  include_global = TRUE,
  ncol = NULL,
  rescale = FALSE,
  supported_only = FALSE,
  ...
)

## S3 method for class 'mvgam_residcor'
summary(object, ...)

## S3 method for class 'mvgam_residcor'
print(x, digits = 2L, ...)

Arguments

x

A summarised mvgam_residcor object, or for plot() an mvgam_residcor_list.

type

Character. Which matrix to plot. "correlation" (the default) draws x$cor. "precision" draws x$prec, the partial correlations, which residual_cor() computes under partial = TRUE.

cluster

Logical. TRUE reorders the matrix by an approximate Robinson ordering (Gruvaeus and Wainer 1972; average linkage on the 1 - cormat distance). Clusters of positive and negative correlations then lie adjacent. Defaults to FALSE.

rescale

Logical. By default colour spans ⁠[-1, 1]⁠, the full range of a correlation, which keeps panels from different fits comparable. TRUE scales colour to the entries present, for a fit whose correlations are all small. Defaults to FALSE.

supported_only

Logical. TRUE leaves blank every pair whose prob_nonzero is at most prob_threshold. Defaults to FALSE.

...

Unused. Anything passed here is refused.

include_global

Logical, for an mvgam_residcor_list. TRUE (the default) adds the ⁠_global⁠ correlation as one panel.

ncol

Optional number of facet columns. Defaults to ceiling(sqrt(n_panels)).

object

A summarised mvgam_residcor object.

digits

Integer number of significant digits. Defaults to 2.

Details

In a latent factor model the residual covariance between series is \Sigma = Z \Omega Z', where Z holds the factor loadings and \Omega is the covariance of the latent states. A strong residual correlation between two species can reflect a species interaction (facilitation or competition), a missing covariate, or any other association the predictors in formula leave unexplained (Hui 2016).

The partial correlation between two series conditions on every other series (Ovaskainen et al. 2016). It is computed from the inverse of the correlation matrix, with the diagonal set to 1. Two species with a partial correlation near zero can still be correlated. They are then conditionally independent given the other species. Their association runs through those species. A larger partial correlation suggests a more direct association.

Value

Objects of this class are structured as a list with the following components:

cor, cor_se, cor_lower, cor_upper

Posterior summaries of the p \times p correlation matrix: the posterior mean (the median under robust = TRUE), the posterior SD (the MAD under robust = TRUE) and the limits of the credible interval at the probs levels.

cor_ess

p \times p matrix of per-entry effective sample sizes of the correlation draws, computed on the Fisher-z scale with posterior::ess_basic(). The diagonal is NA, being fixed at 1. A low value marks a correlation the chains sampled poorly, however narrow its interval.

prob_positive, prob_negative, prob_nonzero

p \times p matrices of Pr(r > 0), Pr(r < 0) and the larger of the two for every off-diagonal entry. Each measures how well the data determine the sign of a correlation.

sig_cor

The correlation matrix with every entry set to zero where prob_nonzero is at most prob_threshold. plot.mvgam_residcor() draws cor. A hard cut would draw a correlation the data leave uncertain the same as one estimated at zero.

cov, cov_se, cov_lower, cov_upper, cov_ess

Posterior summaries of the residual covariance matrix, with per-entry ESS.

mean_abs_offdiag

A list of point, lower and upper summarising the mean absolute off-diagonal correlation. The mean is taken within each draw and then summarised across draws. The interval then describes the overall strength of correlation.

n_series, series_names

Dimensions of the matrix and the series labels.

pattern, hierarchical, group_label

The residual structure that was summarised.

covariance

"stationary" for the covariance of the latent states, or "innovation" for that of one step's shocks, as residual_cor() was asked.

probs, prob_threshold

The credible interval levels and the prob_nonzero threshold of sig_cor.

Passing partial = TRUE to residual_cor() adds the partial correlations, with one field for each correlation field: prec, prec_se, prec_lower, prec_upper, prec_ess, prec_prob_positive, prec_prob_negative, prec_prob_nonzero and the thresholded sig_prec. Partial correlations are bounded like correlations. They are summarised on the same Fisher-z scale. plot.mvgam_residcor() with type = "precision" requires them.

Methods

print() gives the source and kind of covariance, the mean absolute correlation and the number of pairs whose prob_nonzero exceeds prob_threshold. summary() returns a tibble with one row per pair of series, sorted by prob_nonzero: series_1, series_2, Estimate, Est.Error, Q_lower, Q_upper, ESS, the three sign probabilities and sig. A low ESS marks a pair the chains sampled poorly, however tight its interval.

plot() draws the lower triangle of the correlation matrix as a heatmap of the point estimates. A black outline marks each pair whose prob_nonzero exceeds prob_threshold, the pairs sig_cor keeps. The mvgam_residcor_list of residual_cor(by_group = TRUE) plots one facet per group, on shared colour limits.

Author(s)

Nicholas J Clark

References

Gruvaeus G and Wainer H (1972). Two additions to hierarchical cluster analysis. British Journal of Mathematical and Statistical Psychology, 25, 200-206.

Francis KC Hui (2016). BORAL - Bayesian ordination and regression analysis of multivariate abundance data in R. Methods in Ecology and Evolution. 7, 744-750.

Otso Ovaskainen et al. (2016). Using latent variable models to identify large networks of species-to-species associations at different spatial scales. Methods in Ecology and Evolution, 7, 549-555.

See Also

jsdgam(), residual_cor()


The ggplot theme mvgam draws with

Description

Every figure the package draws uses this theme, including the figures it draws through bayesplot. It extends ggplot2::theme_classic(). Apply it to a plot of your own to give it the look of mvgam output.

mvgam's figures take their colours from the "red" scheme of bayesplot, which bayesplot::color_scheme_get("red") returns. The example colours its points with it.

Usage

mvgam_theme(base_size = 11, base_family = "")

Arguments

base_size

Base font size in points. Defaults to 11, matching ggplot2::theme_classic().

base_family

Base font family. Defaults to "", the ggplot2 default.

Value

A ggplot2::theme() object.

Author(s)

Nicholas J Clark

See Also

bayesplot::color_scheme_get()

Examples

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(colour = bayesplot::color_scheme_get("red")$dark) +
  mvgam_theme()


Fields of an mvgam_trend object

Description

Every trend constructor, AR(), RW(), VAR(), CAR(), PW() and ZMVN(), returns an object of class mvgam_trend. The object records the arguments of the call. Model building adds the fields that need the data.

Fields every trend has

trend

The trend type, such as "AR". Stan code generation and the registry look the type up by this name.

time, series

The names of the time and series columns, "time" and "series" unless given.

gr, subgr

The names of the grouping and subgrouping columns of a hierarchical trend, or "NA".

ma

TRUE for a moving-average term.

cor

TRUE for correlated innovations. A grouped trend always has them.

validation_rules

What the trend assumes about the data. "requires_regular_intervals" marks a trend that indexes its lags by position. Fitting it requires evenly spaced times. CAR() and ZMVN() carry no rule.

Fields a constructor adds

n_lv

The number of latent factors, or NULL for none.

trend_map

The loadings as supplied to the constructor.

p

The autoregressive lags of AR() and VAR().

coef_sharing

How AR() shares its coefficients across series.

df

The degrees of freedom of the innovations: Inf for Gaussian, NA to estimate them.

growth, n_changepoints, changepoint_range, changepoint_scale

The arguments of PW().

damped

TRUE for an LLT() whose slope is damped.

season, harmonics

The seasonal periods of an LLT() and the number of harmonics of each, NULL without a season.

cap

The name of the carrying-capacity column that a logistic PW() trend uses, "cap" unless given.

Fields model building adds

fixed_Z

The loadings matrix a trend_map gives, with NA marking a sampled entry. NULL when every loading is sampled.

loadings_prior_spec

The structured loadings prior built from the loadings_prior argument of mvgam().

dimensions

The series and time axes the data defines.

Parameters and priors

Which parameters a trend samples depends on its fields at the time the model is built. A fully fixed trend_map samples no loadings. A loadings prior with column shrinkage derives the innovation scale. get_prior() lists the parameters for a given model.

Author(s)

Nicholas J Clark

See Also

list_trend_types()


Example use cases for mvgam

Description

New to mvgam? Start with mvgam, whose Workflow section lists the steps of an analysis and whose Terms section defines the vocabulary these pages use. mvgam_data checks a data frame before fitting. The overview article walks through a full analysis. The cheatsheet summarises the main functions on one page.

mvgam fits dynamic generalized additive models (GAMs) to one or many time series. Smooth functions of covariates sit beside a latent time-series process that carries the autocorrelation the covariates leave behind. Stan samples the posterior. Every prediction and forecast then carries the uncertainty of every parameter.

The links below lead to questions, blog posts, articles and videos where these models answered a practical problem. They cover counts and other non-Gaussian series, several series modelled together, and predictors such as seasonality that changes over time, monotonic effects and Gaussian processes.

Details

Non-Gaussian time series modelling and forecasting

Counts, proportions and binary outcomes rarely suit a Gaussian model. A latent trend on the link scale handles their autocorrelation.

Multivariate time series modelling and forecasting

Series measured together, such as several species at one site, can share latent trends or have trends that are correlated.

Seasonality and other complex predictors

Cyclic smooths model seasonal patterns. Gaussian processes, monotonic smooths and hierarchical smooths model other nonlinear effects.

Author(s)

Nicholas J Clark

See Also

mvgam, mvgam_data, trend_constructors, the cheatsheet


Multivariate normal family for several continuous responses

Description

For continuous responses measured together on each unit, such as the biomass of several species at a site. The data hold one row per response component at each unit. Latent factors shared by a unit's components give their residuals the covariance ⁠Z Z' + diag(Psi^2)⁠, where Z holds the factor loadings and Psi each component's residual standard deviation (Hui et al. 2015; Niku et al. 2019). Given the factors, each row is normal with mean mu and standard deviation Psi.

Usage

mvn()

Details

jsdgam() fits the family, taking the unit and component columns and the number of factors n_lv. residual_cor() summarises the residual correlations and shared_variation() the part the factors share. Psi takes the prior inv_gamma(3, 1.07), with median 0.40 and no mass at zero, which suits responses near unit scale. prior(..., class = Psi) sets another.

With K components the data separate the factor part from the residual part only when (K - n_lv)^2 >= K + n_lv. Fewer factors or more components meet the bound. jsdgam() warns when it fails.

Value

A family object to pass to jsdgam() or mvgam().

References

Hui, F. K. C., Taskinen, S., Pledger, S., Foster, S. D. and Warton, D. I. (2015). Model-based approaches to unconstrained ordination. Methods in Ecology and Evolution, 6(4):399-411. doi:10.1111/2041-210X.12236

Niku, J., Brooks, W., Herliansyah, R., Hui, F. K. C., Taskinen, S. and Warton, D. I. (2019). Efficient estimation of generalized linear latent variable models. PLOS ONE, 14(5):e0216129. doi:10.1371/journal.pone.0216129

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

See Also

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvgam_families, mvt(), nmix(), occ(), tweedie()

Examples

## Not run: 
# Five species at 80 sites whose residuals share two latent
# factors
simdat <- sim_jsdgam(family = mvn(), n_species = 5L, n_sites = 80L,
                     n_lv = 2L, seed = 1L)

fit <- jsdgam(
  formula        = y ~ env * series,
  factor_formula = ~ -1,
  data           = simdat$data_train,
  unit           = time, species = series,
  family         = mvn(),
  n_lv           = 2L,
  chains         = 2L,
  silent         = 2
)
summary(fit)

# The species-by-species residual correlations, against the values
# the simulation used
round(residual_cor(fit)$cor, 2)
round(simdat$truth$residual_cor, 2)

# Next, shared_variation(fit) gives the part the factors share

## End(Not run)


Multivariate Student-t family for several continuous responses

Description

mvn() with heavy-tailed residuals. Given the latent factors, each row follows a Student-t distribution with location mu, scale Psi and degrees of freedom nu, which every component shares. An outlying row then pulls less on the fit. The residual covariance is ⁠Z Z' + diag(Psi^2 * nu / (nu - 2))⁠. A unit's responses do not follow a multivariate Student-t law. Their factors stay normal.

Usage

mvt()

Details

nu is bounded below by 2, which keeps the residual variance finite. Its prior is gamma(2, 0.1), as brms gives a Student-t nu. Above the bound it places the median of nu at 17 and 95% of its mass between 3.2 and 56. prior(..., class = nu) and prior(..., class = Psi) set other priors. The data layout, the fit and the bound on n_lv follow mvn().

Value

A family object to pass to jsdgam() or mvgam().

References

Hui, F. K. C., Taskinen, S., Pledger, S., Foster, S. D. and Warton, D. I. (2015). Model-based approaches to unconstrained ordination. Methods in Ecology and Evolution, 6(4):399-411. doi:10.1111/2041-210X.12236

See Also

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvgam_families, mvn(), nmix(), occ(), tweedie()

Examples

## Not run: 
simdat <- sim_jsdgam(family = mvt(), n_species = 5L, n_sites = 80L,
                     n_lv = 2L, seed = 1L)
fit <- jsdgam(
  formula        = y ~ env * series,
  factor_formula = ~ -1,
  data           = simdat$data_train,
  unit           = time, species = series,
  family         = mvt(),
  n_lv           = 2L,
  chains         = 2L,
  silent         = 2
)

# The degrees of freedom, against 5 in the simulation
posterior_summary(fit, variable = "nu")

## End(Not run)


Number of levels per grouping factor in a fitted mvgam model

Description

The number of levels of each grouping factor of the observation formula, as brms::ngrps.brmsfit() gives it.

Usage

## S3 method for class 'mvgam'
ngrps(object, ...)

Arguments

object

A fitted mvgam object.

...

Unused. Anything passed here is refused.

Value

A named list of integers, one per grouping factor, or NULL for a model without group-level effects.

Author(s)

Nicholas J Clark

See Also

brms::ngrps.brmsfit(), ranef.mvgam(), VarCorr.mvgam().


N-mixture family for repeated counts of unmarked individuals

Description

For counts made on repeated visits to sites whose abundance stays fixed across the visits, such as bird point counts within a season. The data hold one row per visit. The visits sharing a series and a time belong to one closure unit, whose latent abundance N is Poisson with mean mu. Each visit's count depends on N and the detection parameter p. The likelihood sums over N from the unit's largest count up to the cap K_max (Royle 2004).

Usage

nmix(
  type = c("poisson_binomial", "royle_nichols", "poisson_poisson"),
  multi_season = FALSE
)

Arguments

type

The variant, "poisson_binomial" by default. See Choosing a variant.

multi_season

Logical. TRUE keys a closure unit on ⁠(series, site, time)⁠, for several seasons of visits to each site. The data then need a site column, which pivot_detection_array() creates from a four-dimensional array with multi_season = "hierarchical". Each unit holds the visits of one site in one season.

Details

bf(y ~ elev, p ~ tod) models abundance and detection, each with its own formula. mu takes the log link. predict() with type = "latent_state" gives the expected abundance of each unit given its counts. type = "detection" gives the detection probability of each visit.

Value

A family object to pass to mvgam() or jsdgam().

Choosing a variant

All three variants take N ~ Poisson(mu) and differ in what a visit records.

"poisson_binomial" (Royle 2004)

Counts y ~ Binomial(N, p), which never exceed N. Point counts, removal passes and plot tallies fit this design. p is the detection probability of each individual, on the logit link.

"royle_nichols" (Royle and Nichols 2003)

Detections y ~ Bernoulli(1 - (1 - p)^N) in 0 / 1. Camera-trap or eDNA detections scored as present or absent fit this design. p is the detection probability of each individual, on the logit link. A visit's detection probability rises with N.

"poisson_poisson" (Neyman 1939)

Counts y ~ Poisson(N * p), which can exceed N. Camera-trap events and acoustic detections, where one individual is recorded several times, fit this design. p is the encounter rate of each individual per visit, on the log link.

Priors

A detection probability p on the logit link takes beta(1, 1) as a scalar. With a formula, its intercept takes normal(0, 1.5), which puts most of the probability between 0.05 and 0.95. The encounter rate of "poisson_poisson" takes lognormal(0, 1) as a scalar. With a formula, its intercept takes std_normal(). Either puts most of the rate between 0.14 and 7.4 encounters per visit. get_prior() lists these defaults. prior(..., dpar = "p") replaces one. A rare species might take prior(normal(-2, 0.5), class = Intercept, dpar = "p").

Identification

The counts identify abundance and detection apart through repeated visits and through covariates that act on one of them. With one visit per unit and no covariate, the data identify only the product mu * p. nmix() refuses that model. More than 30% of units visited once raises a warning. A "poisson_poisson" model with intercepts alone separates mu from p only through the extra variance of its counts. It warns. An informative prior on one intercept separates them.

Overdispersed abundance, such as negative binomial counts fitted by a Poisson N, biases abundance up and detection down, leaving their product close to the truth (Knape et al. 2018). pp_check() with type = "fit_stat" tests the per-unit totals for such misfit.

The cap on abundance

A cap column, constant within each unit and at least its largest count, sets the cap K_max. Without one, "poisson_binomial" and "poisson_poisson" take each unit's largest count plus 100, as unmarked::pcount() does. "royle_nichols" takes a fixed 25, as unmarked::occuRN() does. Its 0 / 1 detections carry no count to build a cap from. A lower cap shortens the sum and speeds sampling. A cap that binds biases abundance down. latent_N_saturation() reports, for each unit, the posterior probability that N equals its cap. A prediction frame may carry its own cap.

Joint species models

jsdgam() with nmix() or occ() fits several species at once. Latent factors shared by the species enter the state mu. p keeps its own formula. factor_formula = ~ s(env, by = lv_axis()) lets each factor follow an environmental gradient.

Importing array data

Detection histories from unmarked, spOccupancy or ubms come as a site-by-visit matrix, an array with species or seasons as further dimensions, or a list of matrices. pivot_detection_array() converts any of these to the long format, broadcasting site, season and visit covariates to their rows.

Threading

The density sums over units through Stan's reduce_sum(). Fitting with threads = 2 or more splits the units across threads.

References

Royle, J. A. (2004). N-mixture models for estimating population size from spatially replicated counts. Biometrics, 60, 108-115. doi:10.1111/j.0006-341X.2004.00142.x

Royle, J. A. and Nichols, J. D. (2003). Estimating abundance from repeated presence-absence data or point counts. Ecology, 84, 777-790. doi:10.1890/0012-9658(2003)084[0777:EAFRPA]2.0.CO;2

Neyman, J. (1939). On a new class of "contagious" distributions, applicable in entomology and bacteriology. Annals of Mathematical Statistics, 10, 35-57. doi:10.1214/aoms/1177732245

Knape, J., Arlt, D., Barraquand, F., Berg, A., Chevalier, M., Part, T., Ruete, A. and Zmihorski, M. (2018). Sensitivity of binomial N-mixture models to overdispersion. Methods in Ecology and Evolution, 9, 2102-2114. doi:10.1111/2041-210X.13062

See Also

occ() for the related joint-occupancy family and pp_check.mvgam() for closure-unit goodness-of-fit checks. The N-mixture article fits N-mixture and occupancy models from data preparation to inference. The data article sets out the row layout that nmix() expects.

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvgam_families, mvn(), mvt(), occ(), tweedie()

Examples

## Not run: 
# Counts at 50 sites, each visited four times. The state `mu` is
# the expected abundance and `p` the detection probability.
set.seed(5)
simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L,
                                n_sites = 50L, n_visits = 4L,
                                type = 1L)
mod <- mvgam(
  bf(y ~ env, p ~ tod_c),
  data   = simdat$data_train,
  family = nmix(),
  chains = 2,
  silent = 2
)
summary(mod)

# Abundance and detection, separated by the model
head(predict(mod, type = "latent_state"))
head(predict(mod, type = "detection"))
plot(hindcast(mod, type = "latent_state"))

# A goodness-of-fit test on the per-site totals. A Bayesian p-value
# near 0 or 1 marks a misfit.
pp_check(mod, type = "fit_stat", stat = "freeman_tukey",
         ndraws = 200L)

## End(Not run)


Extract number of observations from mvgam object

Description

Extract number of observations from mvgam object

Usage

## S3 method for class 'mvgam'
nobs(object, ...)

Arguments

object

mvgam object

...

Unused. Anything passed here is refused.

Value

Integer count of the rows the model was given, matching nrow(model.frame(object)). A frame mvgam fits is rectangular, so an unobserved cell is part of the design and is counted.


Occupancy family for repeated detection and non-detection

Description

For detections recorded on repeated visits to sites whose occupancy stays fixed across the visits, such as camera-trap or call surveys within a season. The data hold one row per visit with a 0 / 1 response. The visits sharing a series and a time belong to one closure unit, which is occupied with probability mu. A visit to an occupied unit detects the species with probability p. The likelihood sums over the unit's two states. A unit with a detection is occupied for certain (MacKenzie et al. 2002).

Usage

occ(multi_season = FALSE)

Arguments

multi_season

Logical. TRUE keys a closure unit on ⁠(series, site, time)⁠, for several seasons of visits to each site. The data then need a site column, which pivot_detection_array() creates from a four-dimensional array with multi_season = "hierarchical". Each unit holds the visits of one site in one season.

Details

bf(y ~ elev, p ~ tod) models occupancy and detection, each with its own formula on the logit link. predict() with type = "latent_state" gives the probability that each unit is occupied given its detections. type = "detection" gives the detection probability of each visit. The data need no cap column.

Value

A family object to pass to mvgam() or jsdgam().

Priors

The occupancy intercept takes brms's student_t(3, 0, 2.5) on the logit scale. A scalar p takes beta(1, 1). With a formula, its intercept takes normal(0, 1.5). get_prior() lists the defaults, and prior(..., dpar = "p") replaces one.

Identification

The detections identify occupancy and detection apart through repeated visits and through covariates that act on one of them. With one visit per unit and no covariate, the data identify only the product mu * p. Only the priors then set the two apart (Royle and Dorazio 2008). mvgam() warns on such data. It also warns when more than 30% of units have a single visit.

Joint species models

jsdgam() with nmix() or occ() fits several species at once. Latent factors shared by the species enter the state mu. p keeps its own formula. factor_formula = ~ s(env, by = lv_axis()) lets each factor follow an environmental gradient.

Importing array data

Detection histories from unmarked, spOccupancy or ubms come as a site-by-visit matrix, an array with species or seasons as further dimensions, or a list of matrices. pivot_detection_array() converts any of these to the long format, broadcasting site, season and visit covariates to their rows.

Threading

The density sums over units through Stan's reduce_sum(). Fitting with threads = 2 or more splits the units across threads.

References

MacKenzie, D. I., Nichols, J. D., Lachman, G. B., Droege, S., Royle, J. A. and Langtimm, C. A. (2002). Estimating site occupancy rates when detection probabilities are less than one. Ecology, 83, 2248-2255. doi:10.1890/0012-9658(2002)083[2248:ESORWD]2.0.CO;2

Royle, J. A. and Dorazio, R. M. (2008). Hierarchical Modeling and Inference in Ecology. Academic Press.

See Also

nmix() for the related N-mixture family and pp_check.mvgam() for closure-unit goodness-of-fit checks. The N-mixture article fits occupancy and N-mixture models from data preparation to inference. The data article sets out the row layout that occ() expects.

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvgam_families, mvn(), mvt(), nmix(), tweedie()

Examples

## Not run: 
# Detections at 50 sites, each visited four times, with covariates
# on occupancy and on detection
set.seed(6)
simdat <- sim_closure_unit_data(family = occ(), n_species = 1L,
                                n_sites = 50L, n_visits = 4L,
                                type = 1L)
mod <- mvgam(
  bf(y ~ env, p ~ tod_c),
  data   = simdat$data_train,
  family = occ(),
  chains = 2,
  silent = 2
)
summary(mod)

# Occupancy along the gradient and detection through the day
conditional_effects(mod, effects = "env", type = "latent_state")
conditional_effects(mod, effects = "tod_c", type = "detection")

# Occupancy and detection, separated by the model
head(predict(mod, type = "latent_state"))
head(predict(mod, type = "detection"))

# Next, pp_check(mod, type = "fit_stat") tests the fit of each unit

## End(Not run)


Ordination biplot of a latent factor model

Description

Plots the site scores and series loadings of a factor model on two axes. Sites are the points on the fit's unit or time axis, labelled by their values. Series, such as the species of a jsdgam() fit, are arrows from the origin. Series that point the same way share their residual variation. Arrows are tapered when ggarrow and ggpp are installed.

Usage

ordinate(object, ...)

## S3 method for class 'mvgam'
ordinate(
  object,
  which_lvs = c(1L, 2L),
  biplot = TRUE,
  alpha = 0.5,
  rotation = c("svd", "varimax", "promax", "none"),
  label_sites = TRUE,
  label_species = c("longest", "all", "none"),
  traits = NULL,
  trait_arrow_scale = 1,
  ...
)

Arguments

object

A fitted mvgam or jsdgam model with at least two latent factors, set by n_lv in jsdgam() or in a trend constructor

...

Unused. Anything passed here is refused.

which_lvs

Two distinct integers: the axes to plot

biplot

Logical. TRUE draws the series loadings with the site scores. FALSE draws the site scores alone.

alpha

Number in ⁠[0, 1]⁠: the share of each singular value given to the site scores under rotation = "svd". The loadings take the rest. 0.5 scales sites and series alike. Values near 1 spread the sites, values near 0 spread the series (Hui 2016).

rotation

The basis of the axes:

"svd"

Axes ordered by the variance of LV %*% t(Z) they explain. The first two show the leading gradients.

"varimax"

An orthogonal rotation under which each series loads on as few axes as it can. The axes then lend themselves to names.

"promax"

An oblique rotation, as varimax with correlated axes.

"none"

The identified factors themselves, centred.

Varimax and promax axes carry no variance order. Any two of them make a valid which_lvs.

label_sites

Logical. TRUE labels each site score with its unit or time value.

label_species

The series arrows to label. "longest" (the default) labels the 10 longest arrows in the plotted plane. A fit with up to 10 series then has every arrow labelled. "all" labels every arrow and "none" labels none.

traits

NULL, "auto", or a data frame or matrix of series traits. "auto" takes the traits the fit was built with, those of jsdgam(traits = ) or else of jsdgam(trait_slopes = ). Each numeric trait is regressed on the plotted loadings. Its arrow points the way the trait increases. Rows match the series by a series column, else by rownames(traits) when those name every series, else by position. Drawn only with biplot = TRUE.

trait_arrow_scale

Positive number. The longest trait arrow is trait_arrow_scale times the longest loading arrow.

Details

The plot starts from the posterior medians of the identified factors and loadings. Factors with shared dynamics are identified by a rotation to lower-triangular loadings, Z_tilde and lv_trend_tilde (Heaps and Jermyn 2024). Factors with their own dynamics are identified by an ordering and orientation of Z and lv_trend. The Identification section of trend_constructors describes both. Every rotation keeps the product LV %*% t(Z) the model fitted.

The medians carry no posterior uncertainty into the plot. Axis signs are arbitrary. Two fits may need an axis flipped before they agree. compare_loadings() aligns the loadings of two fits.

A trend_map supplies the loadings as data. A rotation other than "none" replaces them and warns on every call. plot(object, type = "factors") shows the loadings the map declared.

Value

A ggplot object. attr(p, "rotation") holds the rotated scores and loadings, the rotation matrix rotmat (NULL for "svd" and "none"), the method and n_lv.

Author(s)

Nicholas J Clark

References

Hui, F. K. C. (2016). boral: Bayesian ordination and regression analysis of multivariate abundance data in R. Methods in Ecology and Evolution, 7, 744-750. doi:10.1111/2041-210X.12514

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

See Also

plot.mvgam() with type = "factors" plots each factor's path. residual_cor() gives the correlations among series the factors imply. community() gives how often species occur together. The JSDM article interprets a biplot of species loadings.

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), irf.mvgam(), posterior_transition_matrix(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Presence and absence of 10 species at 60 sites, driven by two
# latent factors
simdat <- sim_jsdgam(family = bernoulli(), n_species = 10L,
                     n_sites = 60L, n_lv = 2L, seed = 3L)
mod <- jsdgam(y ~ env * series, data = simdat$data_train,
              family = bernoulli(), n_lv = 2L, chains = 2, silent = 2)

# Sites as points and species loadings as arrows
ordinate(mod)

# Varimax axes, on which each species loads on as few as it can
p <- ordinate(mod, rotation = "varimax", label_sites = FALSE)
p
attr(p, "rotation")$loadings

# Next, residual_cor(mod) gives the species correlations the
# factors imply

## End(Not run)


Pairs plot of mvgam parameters

Description

Scatters the posterior draws of each pair of parameters, with each parameter's marginal posterior on the diagonal, as bayesplot::mcmc_pairs() draws them. Divergent transitions are marked. A ridge or a funnel between two parameters shows that the data separate them poorly.

Usage

## S3 method for class 'mvgam'
pairs(x, variable = NULL, regex = FALSE, ...)

Arguments

x

A fitted mvgam or jsdgam object

variable

Either a keyword shortcut, a character vector of parameter names, or (when regex = TRUE) a vector of regular expressions. Recognised keywords:

  • "betas": population-level coefficients, the set brms::fixef() reports (⁠b_*⁠, ⁠bs_*⁠, ⁠bsp_*⁠ and ⁠bcs_*⁠).

  • "obs_params": observation-family distributional parameters (sigma, phi, shape, ...).

  • "smooth_params": smooth-term standard deviations (⁠sds_*⁠).

  • "trend_betas": the trend formula's population-level coefficients (⁠b_*_trend⁠, ⁠bs_*_trend⁠ and ⁠bsp_*_trend⁠).

  • "trend_params": trend-dynamics parameters (autoregressive coefficients, innovation SDs, ...).

  • "trend_smooth_params": trend-side smooth SDs.

NULL (the default) returns every parameter. A bare vector name, such as "sigma_trend", selects every element. Group-level effects, factor loadings and latent states have no keyword. Select them by name. variables.mvgam() lists the names a fit holds.

regex

Logical. When TRUE, each entry of variable is treated as a regular expression and any parameter matching at least one pattern is selected. Keyword shortcuts are still honoured. Defaults to FALSE.

...

Further arguments to bayesplot::mcmc_pairs(), such as off_diag_args.

Details

Without variable, the plot shows the parameters mcmc_plot.mvgam() shows: the population coefficients, the family parameters, the variance components and the trend's dynamics and loadings. The per-basis smooth coefficients (⁠s_*⁠) and the group-level deviations (⁠r_*⁠) run to hundreds on a spline or hierarchical fit. They are drawn when variable names them.

Value

A bayesplot_grid object

See Also

mcmc_plot.mvgam() draws the other bayesplot MCMC plots. mvgam_draws lists the shortcuts variable accepts.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = gaussian(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR(),
                     prop_trend = 0.5)
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = gaussian(),
              chains  = 2, silent = 2)

# A Gaussian response adds white noise to the latent AR(1) process.
# The data split the total variance between the observation noise
# `sigma` and the process noise `sigma_trend` through the
# autocorrelation alone. A larger `sigma` leaves less variance for
# `sigma_trend`. The pair then forms a negative ridge. Divergences
# gather where `sigma` nears zero.
pairs(mod, variable = c("obs_params", "trend_params"))

# Next, mcmc_plot(mod, type = "rank_overlay") checks that the chains
# mix

## End(Not run)


Convert a detection array to the long format of mvgam

Description

Occupancy and N-mixture packages such as unmarked, ubms, flocker and spOccupancy store detection histories as matrices or arrays, with one dimension for sites and one for visits. mvgam() and jsdgam() with occ() or nmix() take a long data frame instead, with one row per species, site, season and visit. This function converts the one to the other and copies the covariates onto the matching rows.

Data from one season give time = site. Each site is then one closure unit. Data from several seasons take one of two layouts, chosen by multi_season:

Usage

pivot_detection_array(
  y,
  site_covs = NULL,
  season_covs = NULL,
  site_season_covs = NULL,
  obs_covs = NULL,
  species = NULL,
  site_col = "site",
  season_col = "season",
  visit_col = "visit",
  time_col = "time",
  series_col = "series",
  y_col = "y",
  multi_season = c("fused", "hierarchical")
)

Arguments

y

One of four layouts:

  • Single-species, single-season: a ⁠[J_sites, K_max_visits]⁠ matrix of detections (0 / 1 for occ(), non-negative counts for nmix()). The unmarked::unmarkedFrameOccu / unmarkedFramePCount y slot and the flocker::flock obs argument with type = "single".

  • Multi-species, single-season (array): a ⁠[N_species, J_sites, K_max_visits]⁠ array. The spOccupancy::lfMsPGOcc / msPGOcc y slot.

  • Multi-species, single-season (list): a named list of ⁠[J_sites, K_max_visits]⁠ matrices, one per species. The unmarked::unmarkedFrameOccuMulti y slot; list names become species labels.

  • Multi-species, multi-season: a ⁠[N_species, J_sites, T_seasons, K_max_visits]⁠ 4D array. The spOccupancy::tMsPGOcc / svcTMsPGOcc y slot. For single-species multi-season data, wrap in a length-1 list (list(only_species = matrix_or_3d_array)) or pass as a ⁠[1, J, T, K]⁠ array.

NA entries mark missing visits / seasons and are dropped from the output.

site_covs

Optional data.frame of site-level covariates with nrow == J_sites. Broadcast across visits, seasons and species. The unmarked::unmarkedFrameOccu siteCovs slot, the spOccupancy occ.covs and the flocker unit_covs map here.

season_covs

Optional data.frame of season-level covariates with nrow == T_seasons. Broadcast across sites, visits and species. Use for year-of-study effects, season-of-year covariates, or any covariate that varies across primary periods but is constant within a season.

site_season_covs

Optional named list of ⁠[J_sites, T_seasons]⁠ matrices for covariates that vary across the ⁠(site, season)⁠ interaction (e.g., site-level habitat that changes between seasons).

obs_covs

Optional visit-level covariates:

  • Single-season: named list of ⁠[J_sites, K_max_visits]⁠ matrices, OR a long-format data.frame with J_sites * K_max_visits rows in site-major / visit-fastest order (the unmarked obsCovs convention).

  • Multi-season: named list of ⁠[J_sites, T_seasons, K_max_visits]⁠ arrays.

species

Optional character vector of species names with length == N_species. Only meaningful for multi-species y. When y is a named list, list names take precedence. Defaults to ⁠sp1, sp2, ...⁠.

site_col

Name of the site identifier in the output. Defaults to "site".

season_col

Name of the season identifier in the output. Defaults to "season".

visit_col

Name of the visit identifier. Defaults to "visit".

time_col

Name of the time column in the output. Defaults to "time". The Description gives its values for each layout.

series_col

Name of the species column. Defaults to "series".

y_col

Name of the detection / count column. Defaults to "y". This and the other ⁠*_col⁠ arguments must each name a different output column.

multi_season

"fused" (the default) or "hierarchical", the layout for data from several seasons. The Description explains both. Data from one season ignore it: a matrix, a ⁠[N, J, K]⁠ array or a four-dimensional array with T = 1.

Value

A long data.frame with the columns series, site, season, visit, time and y, followed by the covariates. Data from one species have no series column. Data from one season have no season column. Rows where y is NA are dropped. Units may then differ in their number of visits.

Author(s)

Nicholas J Clark

See Also

occ() and nmix() for the families that take this layout. pivot_species_matrix() converts a site-by-species matrix.

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

# Detections of one species at four sites over three visits, laid out
# as the `y` slot of an unmarked frame. NA marks a missed visit
y <- matrix(c(0, 1, 1,
              0, 0, NA,
              1, 1, 0,
              0, 0, 0), nrow = 4, byrow = TRUE)
long <- pivot_detection_array(
  y,
  site_covs = data.frame(forest = c(0.2, 0.8, 0.5, 0.1)),
  obs_covs = list(wind = matrix(seq(0.1, 1.2, by = 0.1), nrow = 4))
)
# One row per observed visit. The missed visit is dropped
long

# Three species in a [species, site, visit] array, as spOccupancy
# stores them. Each row names its species in 'series'
set.seed(1)
y3 <- array(rbinom(36, size = 1, prob = 0.4), dim = c(3, 4, 3))
head(pivot_detection_array(y3, species = c("owl", "hawk", "kite")))

# Next, fit the long frame with mvgam(family = occ())


Pivot a wide species matrix to mvgam long-format

Description

Convert the wide ⁠[J sites, N species]⁠ response matrix used by Hmsc (and any single-visit JSDM workflow) into the long-format ⁠(series, time, y, ...)⁠ layout that mvgam() / jsdgam() with a simplex (diri(), multi(), categ()), continuous-response (mvn(), mvt()), or bernoulli / binomial / poisson family expects.

Usage

pivot_species_matrix(
  Y,
  site_covs = NULL,
  traits = NULL,
  site_id_name = "time",
  series_name = "series",
  values_to = "y"
)

Arguments

Y

A ⁠[J_sites, N_species]⁠ matrix or data.frame. Column names become the series factor levels; missing column names default to ⁠sp1, sp2, ...⁠.

site_covs

Optional data.frame of site-level covariates with nrow == J_sites. The Hmsc XData slot maps here.

traits

Optional data.frame of per-species traits with nrow == N_species. Broadcast across sites. The Hmsc TrData slot maps here.

site_id_name

Name of the site identifier in the output. Defaults to "time".

series_name

Name of the species column. Defaults to "series".

values_to

Name of the response column. Defaults to "y".

Value

A long-format data.frame with J * N rows, each carrying series, time, y, site covariates broadcast across species and species traits broadcast across sites.

Author(s)

Nicholas J Clark

See Also

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

# Counts of three species at five sites, one column per species
Y <- matrix(c(3, 0, 5, 2, 7,
              1, 1, 0, 4, 2,
              0, 6, 2, 3, 1), nrow = 5,
            dimnames = list(NULL, c("ant", "bee", "wasp")))
long <- pivot_species_matrix(
  Y,
  site_covs = data.frame(elev = c(120, 340, 560, 780, 910)),
  traits = data.frame(body_size = c(2.1, 11.5, 16.0))
)
# One row per site and species, each carrying its site's elevation
# and its species' body size
head(long)

# Next, fit the long frame with jsdgam(unit = time, species = series)


Default plots for mvgam models

Description

Draws one of the standard views of a fitted model, chosen by type.

Usage

## S3 method for class 'mvgam'
plot(
  x,
  type = c("residuals", "smooths", "trend", "factors", "series", "latent_state"),
  series = NULL,
  resp = NULL,
  ndraws = NULL,
  component = NULL,
  ...
)

Arguments

x

A fitted mvgam object.

type

The plot to draw:

"residuals" (default)

Randomised quantile (Dunn-Smyth) residuals of one series, defined in residuals.mvgam(). The grid plots them against the fitted values, with their Q-Q plot, ACF and partial ACF, as pp_check.mvgam() draws them. For a model that fits, they look like independent standard normal draws. A series observed at unevenly spaced times shows a semivariogram in place of the ACF and partial ACF. An occ() or nmix() fit has one residual per closure unit and draws the Q-Q plot alone.

"smooths"

The posterior of each smooth, from conditional_smooths.mvgam(), with several smooths combined into one figure.

"trend"

The latent trend over the training times, from hindcast.mvgam(), or the state component component names. A jsdgam() fit has sites in place of times and refuses it.

"factors"

The path of each latent factor. active_factors() reports the variance each factor carries.

"series"

The observed data the fit carries. mvgam_data() plots data before a fit.

"latent_state"

The latent state of an occ() or nmix() fit drawn from the covariates and the fitted trend, unconditioned on the visits: occupancy psi or abundance N, by series and time. A multi-season fit draws the mean over the sites of each season. hindcast(type = "latent_state") conditions each unit on its visits as well.

series

A series index or name. "trend" and "series" also take "all", their default. "residuals" draws one series, the first by default. "smooths", "factors" and "latent_state" ignore it.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

ndraws

The number of posterior draws, or NULL for every draw. "residuals" takes 100 by default. "factors" and "series" ignore it.

component

NULL (the default) for the summed trend, or the names of state components of the trend, with type = "trend". Several names give the sum of their components. LLT() has "level", the stochastic level, and "slope", its growth per time step. A seasonal LLT() adds "season". "predictor" holds the effects of the trend formula's covariates. c("level", "predictor") gives the level with those effects. A factor model projects each component through its loadings, as it projects the trend.

...

Further arguments to the function that draws the plot, such as smooths for conditional_smooths.mvgam().

Value

A ggplot object, or a patchwork of several.

Author(s)

Nicholas J Clark

See Also

forecast.mvgam() and its plot() method draw forecasts. conditional_effects.mvgam() draws covariate effects. mcmc_plot.mvgam() draws posterior diagnostics.

Other model checking: mvgam_diagnostics, pp_check.mvgam(), residuals.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Residual diagnostics, the default
plot(mod)

# The smooth of x and the latent AR(1) trend
plot(mod, type = "smooths")
plot(mod, type = "trend")

# The slope of a local linear trend
mod_llt <- update(mod, trend_formula = ~ LLT())
plot(mod_llt, type = "trend", component = "slope")

# Next, plot(forecast(mod, newdata = simdat$data_test)) carries the
# trend forward

## End(Not run)


Plot posterior hindcasts and forecasts

Description

Plot method for mvgam_forecast objects returned by hindcast.mvgam() and forecast.mvgam(). Draws one panel per series (faceted by default) with nested quantile ribbons for the forecast, a single grey ribbon for the hindcast, posterior median lines and the observations as points. A dashed vertical line marks the boundary between training and forecast times when both are drawn.

Usage

## S3 method for class 'mvgam_forecast'
plot(
  x,
  series = NULL,
  probs = c(0.5, 0.8, 0.95),
  hindcast = TRUE,
  forecast = TRUE,
  newdata_obs = TRUE,
  ...
)

Arguments

x

An mvgam_forecast object.

series

Optional integer vector, character vector of series names, or "all". When NULL (the default), every series is plotted and the panels are faceted via ggplot2::facet_wrap().

probs

Numeric vector of credible interval widths for the forecast ribbon. Defaults to c(0.5, 0.8, 0.95) which draws three nested bands from the outer 95% to the inner 50%. Hindcast ribbons always use the widest entry.

hindcast, forecast

Logical. Whether the hindcast and the forecast are drawn. Both default to TRUE. Setting one to FALSE draws the other alone.

newdata_obs

Logical. When TRUE (the default) and the object carries test_observations, the test observations are overlaid on the forecast region.

...

Unused. Anything passed here is refused.

Details

The forecast takes the shades of the red bayesplot scheme. The hindcast band is light grey, which separates in-sample uncertainty from the nested forecast bands.

forecast.mvgam() and hindcast.mvgam() return the objects this method draws. Predictions that leave out the fitted trend state come from posterior_predict.mvgam() and posterior_epred.mvgam().

Value

A ggplot object.

Author(s)

Nicholas J Clark

See Also

forecast.mvgam(), hindcast.mvgam(), score.mvgam_forecast(), summary.mvgam_forecast()

Examples

## Not run: 
set.seed(1)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
# Two models of one count series: a smooth of x with and without
# an AR(1) trend. The trend model samples with smaller steps
# (adapt_delta = 0.95). That avoids divergent transitions when
# lfo_cv() refits it to shorter stretches of the series
mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train,
                 family = poisson(), chains = 2, silent = 2)
mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
                data = simdat$data_train, family = poisson(),
                chains = 2, silent = 2,
                control = list(adapt_delta = 0.95))

## End(Not run)
## Not run: 
fc <- forecast(mod_ar, newdata = simdat$data_test)

# The grey hindcast band covers the training times. The red bands
# are the 80% and 95% forecast intervals, with the held-out counts
# as points
plot(fc, probs = c(0.8, 0.95))

# The forecast alone
plot(fc, hindcast = FALSE)

## End(Not run)


Plot a summarised impulse response or variance decomposition

Description

An impulse response draws the posterior median and interval of each shock-response pair against the forecast horizon, with a dashed line at zero. A variance decomposition stacks the median shares of its sources in one panel per target, as plot.mvgam_fevd() does.

Usage

## S3 method for class 'mvgam_var_surface_summary'
plot(
  x,
  series = NULL,
  responses = NULL,
  contributing = NULL,
  shocks = NULL,
  ...
)

Arguments

x

A mvgam_irf_summary or mvgam_fevd_summary

series

Positions or names of the processes to keep. On an impulse response these are the processes a shock originates in. On a variance decomposition they are the targets whose forecast error is decomposed. Default keeps every process.

responses

Impulse responses only. Positions or names of the processes whose response to the shock is drawn. Default keeps every process.

contributing

Variance decompositions only. Positions or names of the source processes stacked in each bar. The shares of the sources drawn are renormalised to sum to one.

shocks

Optional character vector naming shock-response pairs directly, for a selection the index arguments cannot express.

...

Unused. Anything passed here is refused.

Value

A ggplot object


Portal Project rodent capture survey data

Description

Monthly time series of rodent captures for selected species of the Portal Project, a long-term study of a Chihuahuan Desert ecosystem near Portal, Arizona. Captures are summed across all control plots.

Usage

portal_data

Format

A data.frame containing the following fields:

time

time of sampling, in lunar monthly cycles

series

factor identifying the species

captures

total captures across all control plots at each time

ndvi_ma12

12-month moving average of the mean Normalised Difference Vegetation Index, a measure of plant greenness

mintemp

monthly mean of the minimum temperature

Source

https://github.com/weecology/PortalData/blob/main/SiteandMethods/Methods.md

See Also

mvgam() for a state-space model of these counts and mvgam_data() to check the data. The overview article fits one.

Examples

data(portal_data)
mvgam_data(portal_data, y = "captures", family = poisson())

Model-averaged posterior draws and predictions across mvgam fits

Description

Bayesian model averaging of two or more mvgam fits, as in brms::posterior_average.brmsfit() and brms::pp_average.brmsfit(). Each fit contributes draws in proportion to its model weight. posterior_average() averages parameter draws. pp_average() averages predictions.

Usage

## S3 method for class 'mvgam'
posterior_average(
  x,
  ...,
  variable = NULL,
  pars = NULL,
  weights = "stacking",
  ndraws = NULL,
  nsamples = NULL,
  missing = NULL,
  model_names = NULL,
  control = list(),
  seed = NULL
)

## S3 method for class 'mvgam'
pp_average(
  x,
  ...,
  weights = "stacking",
  method = "posterior_predict",
  ndraws = NULL,
  nsamples = NULL,
  summary = TRUE,
  probs = c(0.025, 0.975),
  robust = FALSE,
  model_names = NULL,
  control = list(),
  seed = NULL
)

Arguments

x

A fitted mvgam object. Further fits are passed via ....

...

Further fitted mvgam objects to average over. For pp_average(), named arguments are passed to the prediction function method names.

variable

Optional character vector of parameter names to extract, as variables.mvgam() lists them. A bare vector name selects every element. NULL (the default) selects all parameters shared across fits (or all parameters across the union when missing is supplied), excluding "lp__".

pars

Deprecated brms alias for variable.

weights

A numeric vector with one weight per fit, scaled to sum to one, or one of "stacking", "pseudobma", "pseudobma+", "loo" and "waic". mvgam_loo_extras describes each.

ndraws

Total number of model-averaged draws to return. Defaults to the number of draws in the first fit.

nsamples

Deprecated brms alias for ndraws.

missing

Values for parameters some fits lack. NULL (the default) restricts variable to the parameters every fit has and refuses a name outside them. A list keyed by parameter name gives each parameter its own value. A single number fills every parameter a fit lacks.

model_names

Optional character vector of model names, one per forecast. It replaces the names taken from the call.

control

A list of extra arguments passed to loo::loo_model_weights() when computing stacking / pseudo-BMA weights.

seed

Optional integer seed. The session's random state is restored when the call returns.

method

Which prediction function pp_average() calls on each fit before averaging: "posterior_predict" (the default), "posterior_epred" or "posterior_linpred".

summary

Logical. If TRUE (the default), pp_average() summarises the averaged predictions with posterior_summary.mvgam() as a mean, an error and two quantiles. FALSE returns the averaged draws.

probs

Numeric vector of probabilities for quantile computation. Default is c(0.025, 0.975) for 95% credible intervals.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

Value

posterior_average() returns a data.frame of model-averaged posterior draws. pp_average() returns a numeric matrix of averaged predictions. With summary = TRUE its rows are observations and its columns summary statistics. Otherwise its rows are draws and its columns observations. Attribute weights holds the weight of each fit. Attribute ndraws holds the number of draws taken from each fit.

Author(s)

Nicholas J Clark

See Also

loo_model_weights.mvgam() computes the weights. ensemble() averages forecasts. The forecast evaluation article weights and combines competing models.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, waic.mvgam()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The same smooth of x replaced by a linear effect
mod_lin <- update(mod, formula. = y ~ x)

# Stacking weights from approximate leave-one-out cross-validation
loo_model_weights(mod, mod_lin)

# The intercept, averaged over both fits under those weights
pa <- posterior_average(mod, mod_lin, variable = "b_Intercept")
attr(pa, "weights")
summary(pa)

# Averaged expected counts, one row per observation
head(pp_average(mod, mod_lin, method = "posterior_epred"))

## End(Not run)


Expected values of the response for each posterior draw

Description

Draws of E[Y \mid X], the mean of the response given each posterior draw's parameters. The observation and trend predictors are summed on the link scale. The family's mean then maps the sum onto the response scale. posterior_predict.mvgam() adds the observation noise around these means.

Usage

## S3 method for class 'mvgam'
posterior_epred(
  object,
  newdata = NULL,
  process_error = FALSE,
  incl_autocor = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  resp = NULL,
  ...
)

Arguments

object

A fitted mvgam object from mvgam().

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

process_error

Logical. FALSE, the default, leaves the trend's innovations out of the prediction. TRUE adds a random deviation at each time and series, drawn anew for every posterior draw from the spread the trend shows over the long run. For an AR(1) trend with innovation SD \sigma and coefficient \rho that spread has variance \sigma^2/(1-\rho^2). On a log link the deviations raise the average prediction by the factor \exp(\sigma^2/(2(1-\rho^2))). A random walk has no long-run spread. A ZMVN() trend has no dynamics. These two draw from the innovation covariance itself. CAR() draws from one long-run covariance at every time of an irregular grid. The argument applies under incl_autocor = FALSE. The fitted state already holds every innovation.

Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result.

incl_autocor

Logical. Chooses which version of the trend each prediction uses. FALSE, the default, uses the covariate part of the model: the effects in the observation formula and the trend formula, without the trend's innovations. A prediction then depends on the covariates alone. It is the same at the first time point as at the fiftieth. Questions about covariate effects use this version. TRUE uses the fitted state, the value the trend took at each observed time as hindcast() returns it. The section 'Which prediction function?' of predict.mvgam() compares the functions.

An ELPD or an R^2 describes the observed series. log_lik(), loo_R2.mvgam() and bayes_R2.mvgam() use TRUE for that reason. A time outside the training data is refused under TRUE. forecast.mvgam() predicts those times. An in-sample interval under TRUE conditions on states estimated from the same observations. It covers them more often than its nominal level. Calibration is judged out of sample, with forecast.mvgam() or lfo_cv().

The default suits a model whose covariates explain most of the signal. When most of the series-level variation lies in the trend, as in a fit with few covariates and a strong autoregressive process, the covariate part has little to say. hindcast.mvgam() and forecast.mvgam() are more informative there.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

allow_new_levels

Logical. TRUE predicts for grouping levels the model never saw, with coefficients sample_new_levels draws. A new series stays refused: it has no latent state to propagate.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default) takes those of a fitted level chosen in each draw, "old_levels" those of one fitted level for all draws and "gaussian" draws them from the group's normal distribution. Each distributional parameter draws its own.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

...

Unused. Anything passed here is refused.

Details

For most families the mean is the inverse link of the predictor. A binomial mean is trials * p, with the trials taken from the trials() term evaluated against newdata. A zero-inflated or hurdle mean scales the base mean by the probability of a non-zero draw. A lognormal mean carries the correction exp(mu + sigma^2 / 2). A trunc() term gives the mean of the distribution truncated to its bounds.

The mean of an nmix() or occ() visit thins the latent abundance or occupancy by that visit's detection probability. A composition family normalises its means across the components of each unit.

Value

An ⁠[ndraws, nobs]⁠ matrix of expected values on the response scale, one row per draw and one column per row of newdata. An ordinal response gives an ⁠[ndraws, nobs, ncat]⁠ array of category probabilities. A multivariate model with resp = NULL gives a named list, one element per response.

Trend state

By default the trend enters through its covariate part, without the state it took at each observed time. The brms counterparts of this method use that fitted state. incl_autocor = TRUE uses it here too, as fitted.mvgam() and pp_check.mvgam() do on the training data. The section 'Which prediction function?' of predict.mvgam() compares the prediction functions.

See Also

posterior_linpred.mvgam() returns the predictor on the link scale. hindcast.mvgam() and forecast.mvgam() take the trend from its fitted state, in and beyond the training times. The forecast evaluation article scores predictions of held-out times.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# One row per draw, one column per observation
ep <- posterior_epred(mod)
dim(ep)

# Expected counts from the covariate part and from the fitted state,
# against the observed counts
ep_state <- posterior_epred(mod, incl_autocor = TRUE)
library(ggplot2)
ggplot(simdat$data_train, aes(time, y)) +
  geom_point(colour = "grey60") +
  geom_line(aes(y = colMeans(ep), colour = "Covariates")) +
  geom_line(aes(y = colMeans(ep_state), colour = "Fitted trend")) +
  scale_colour_manual(values = c("#DCBCBC", "#8F2727"), name = NULL) +
  labs(y = "Count") +
  mvgam_theme()

# Sampling the trend's innovations raises the average of a log-link
# prediction
c(fixed = mean(ep),
  innovations = mean(posterior_epred(mod, process_error = TRUE)))

# A site the fit never saw takes the spread of the fitted sites
train <- simdat$data_train
train$site <- rep(paste0("site", 1:6), length.out = nrow(train))
mod_site <- mvgam(y ~ (1 | site), trend_formula = ~ AR(p = 1),
                  data = train, family = poisson(),
                  chains = 2, silent = 2)
new_site <- transform(train[1:3, ], site = "unseen")
posterior_epred(mod_site, newdata = new_site, allow_new_levels = TRUE,
                sample_new_levels = "gaussian", ndraws = 3)

# Next: posterior_predict() adds observation noise to these means

## End(Not run)


Posterior credible intervals on a fitted mvgam model

Description

Central quantile intervals of the posterior draws of parameters. The parameters are chosen as in as.matrix.mvgam().

Usage

## S3 method for class 'mvgam'
posterior_interval(object, pars = NULL, variable = NULL, prob = 0.95, ...)

Arguments

object

A fitted mvgam object.

pars

Deprecated alias for variable.

variable

Either a keyword shortcut, a character vector of parameter names, or (when regex = TRUE) a vector of regular expressions. Recognised keywords:

  • "betas": population-level coefficients, the set brms::fixef() reports (⁠b_*⁠, ⁠bs_*⁠, ⁠bsp_*⁠ and ⁠bcs_*⁠).

  • "obs_params": observation-family distributional parameters (sigma, phi, shape, ...).

  • "smooth_params": smooth-term standard deviations (⁠sds_*⁠).

  • "trend_betas": the trend formula's population-level coefficients (⁠b_*_trend⁠, ⁠bs_*_trend⁠ and ⁠bsp_*_trend⁠).

  • "trend_params": trend-dynamics parameters (autoregressive coefficients, innovation SDs, ...).

  • "trend_smooth_params": trend-side smooth SDs.

NULL (the default) returns every parameter. A bare vector name, such as "sigma_trend", selects every element. Group-level effects, factor loadings and latent states have no keyword. Select them by name. variables.mvgam() lists the names a fit holds.

prob

Numeric in ⁠(0, 1)⁠. The probability mass each interval holds. Defaults to 0.95.

...

Further arguments of as.matrix.mvgam(), such as regex.

Value

A numeric matrix with one row per parameter and two columns, the lower and upper bounds.

Author(s)

Nicholas J Clark

See Also

predictive_interval.mvgam() gives intervals of predictive draws. summary.mvgam() reports intervals with convergence diagnostics.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), ranef.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# 90 percent intervals of the autoregression and its innovation SD
posterior_interval(mod, variable = c("ar1_trend", "sigma_trend"),
                   prob = 0.9)

# Next: summary() reports these with convergence diagnostics

## End(Not run)


Linear predictor draws for each posterior draw

Description

Draws of the linear predictor \eta, the sum of the observation and trend predictors on the link scale. A Poisson predictor is on the log scale and a binomial predictor on the logit scale. posterior_epred.mvgam() maps it onto the response scale.

Usage

## S3 method for class 'mvgam'
posterior_linpred(
  object,
  transform = FALSE,
  newdata = NULL,
  process_error = FALSE,
  incl_autocor = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  resp = NULL,
  dpar = NULL,
  ...
)

Arguments

object

A fitted mvgam object from mvgam().

transform

Logical. FALSE (the default) returns the link scale. TRUE applies the inverse link of mu. That gives mu on its own scale. A binomial mu is a probability. A hurdle or zero-inflated mu is the base distribution's parameter. Neither is the mean of the response, which posterior_epred.mvgam() returns.

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

process_error

Logical. FALSE, the default, leaves the trend's innovations out of the prediction. TRUE adds a random deviation at each time and series, drawn anew for every posterior draw from the spread the trend shows over the long run. For an AR(1) trend with innovation SD \sigma and coefficient \rho that spread has variance \sigma^2/(1-\rho^2). On a log link the deviations raise the average prediction by the factor \exp(\sigma^2/(2(1-\rho^2))). A random walk has no long-run spread. A ZMVN() trend has no dynamics. These two draw from the innovation covariance itself. CAR() draws from one long-run covariance at every time of an irregular grid. The argument applies under incl_autocor = FALSE. The fitted state already holds every innovation.

Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result.

incl_autocor

Logical. Chooses which version of the trend each prediction uses. FALSE, the default, uses the covariate part of the model: the effects in the observation formula and the trend formula, without the trend's innovations. A prediction then depends on the covariates alone. It is the same at the first time point as at the fiftieth. Questions about covariate effects use this version. TRUE uses the fitted state, the value the trend took at each observed time as hindcast() returns it. The section 'Which prediction function?' of predict.mvgam() compares the functions.

An ELPD or an R^2 describes the observed series. log_lik(), loo_R2.mvgam() and bayes_R2.mvgam() use TRUE for that reason. A time outside the training data is refused under TRUE. forecast.mvgam() predicts those times. An in-sample interval under TRUE conditions on states estimated from the same observations. It covers them more often than its nominal level. Calibration is judged out of sample, with forecast.mvgam() or lfo_cv().

The default suits a model whose covariates explain most of the signal. When most of the series-level variation lies in the trend, as in a fit with few covariates and a strong autoregressive process, the covariate part has little to say. hindcast.mvgam() and forecast.mvgam() are more informative there.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

allow_new_levels

Logical. TRUE predicts for grouping levels the model never saw, with coefficients sample_new_levels draws. A new series stays refused: it has no latent state to propagate.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default) takes those of a fitted level chosen in each draw, "old_levels" those of one fitted level for all draws and "gaussian" draws them from the group's normal distribution. Each distributional parameter draws its own.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

dpar

Character naming a distributional parameter, such as "sigma" or "nu". The default NULL returns the predictor of the mean. A parameter with a formula of its own returns its linear predictor. That predictor holds no trend term. A parameter sampled as a scalar has no link scale. Its draws fill every row on their own scale, whatever transform is.

...

Unused. Anything passed here is refused.

Details

The observation predictor holds the fixed, group-level, smooth and Gaussian process terms of formula. The trend predictor holds the terms of trend_formula. process_error = TRUE adds a sampled deviation at each time and series, on the link scale. posterior_epred.mvgam() and posterior_predict.mvgam() apply the family's mean and noise to that same predictor.

An ordinal response's category-specific cs() terms give each threshold its own shift. The predictor holds the terms every threshold shares. posterior_epred.mvgam() and posterior_predict.mvgam() subtract the shifts from the thresholds, as brms does.

Value

An ⁠[ndraws, nobs]⁠ matrix, one row per draw and one column per row of newdata. It is on the link scale unless transform = TRUE or dpar names a scalar parameter. A multivariate model with resp = NULL gives a named list, one element per response.

Trend state

By default the trend enters through its covariate part, without the state it took at each observed time. The brms counterparts of this method use that fitted state. incl_autocor = TRUE uses it here too, as fitted.mvgam() and pp_check.mvgam() do on the training data. The section 'Which prediction function?' of predict.mvgam() compares the prediction functions.

See Also

posterior_epred.mvgam() returns expected values. posterior_predict.mvgam() returns predictive draws. hindcast.mvgam() and forecast.mvgam() take the trend from its fitted state. The forecast evaluation article scores predictions of held-out times.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# Log rates, one row per draw and one column per observation
lp <- posterior_linpred(mod, draw_ids = 1:50)
dim(lp)

# A Poisson mean is the inverse link of the predictor
all.equal(exp(lp), posterior_epred(mod, draw_ids = 1:50))

# The predictor under the fitted trend state tracks the series
lp_state <- posterior_linpred(mod, incl_autocor = TRUE)
library(ggplot2)
ggplot(simdat$data_train, aes(time, log1p(y))) +
  geom_point(colour = "grey60") +
  geom_line(aes(y = colMeans(lp_state)), colour = "#8F2727",
            linewidth = 1) +
  labs(y = "log(1 + count)") +
  mvgam_theme()

# Next: posterior_epred() maps the predictor to expected counts

## End(Not run)


Posterior predictive draws of the response

Description

Draws from the posterior predictive distribution: the family's observation noise around the parameters of each posterior draw. They predict new observations, for the training data or new data. pp_check.mvgam() draws them under the fitted state to check a fit against its data.

Usage

## S3 method for class 'mvgam'
posterior_predict(
  object,
  newdata = NULL,
  process_error = FALSE,
  incl_autocor = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  resp = NULL,
  ...
)

Arguments

object

A fitted mvgam object from mvgam().

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

process_error

Logical. FALSE, the default, leaves the trend's innovations out of the prediction. TRUE adds a random deviation at each time and series, drawn anew for every posterior draw from the spread the trend shows over the long run. For an AR(1) trend with innovation SD \sigma and coefficient \rho that spread has variance \sigma^2/(1-\rho^2). On a log link the deviations raise the average prediction by the factor \exp(\sigma^2/(2(1-\rho^2))). A random walk has no long-run spread. A ZMVN() trend has no dynamics. These two draw from the innovation covariance itself. CAR() draws from one long-run covariance at every time of an irregular grid. The argument applies under incl_autocor = FALSE. The fitted state already holds every innovation.

Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result.

incl_autocor

Logical. Chooses which version of the trend each prediction uses. FALSE, the default, uses the covariate part of the model: the effects in the observation formula and the trend formula, without the trend's innovations. A prediction then depends on the covariates alone. It is the same at the first time point as at the fiftieth. Questions about covariate effects use this version. TRUE uses the fitted state, the value the trend took at each observed time as hindcast() returns it. The section 'Which prediction function?' of predict.mvgam() compares the functions.

An ELPD or an R^2 describes the observed series. log_lik(), loo_R2.mvgam() and bayes_R2.mvgam() use TRUE for that reason. A time outside the training data is refused under TRUE. forecast.mvgam() predicts those times. An in-sample interval under TRUE conditions on states estimated from the same observations. It covers them more often than its nominal level. Calibration is judged out of sample, with forecast.mvgam() or lfo_cv().

The default suits a model whose covariates explain most of the signal. When most of the series-level variation lies in the trend, as in a fit with few covariates and a strong autoregressive process, the covariate part has little to say. hindcast.mvgam() and forecast.mvgam() are more informative there.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

allow_new_levels

Logical. TRUE predicts for grouping levels the model never saw, with coefficients sample_new_levels draws. A new series stays refused: it has no latent state to propagate.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default) takes those of a fitted level chosen in each draw, "old_levels" those of one fitted level for all draws and "gaussian" draws them from the group's normal distribution. Each distributional parameter draws its own.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

...

Unused. Anything passed here is refused.

Details

Each family draws from its own distribution at the parameters posterior_linpred.mvgam() and posterior_epred.mvgam() use. A trunc() term restricts the draws to its bounds.

hindcast.mvgam() draws under the fitted latent states at the training times. forecast.mvgam() propagates them to future times.

Value

An ⁠[ndraws, nobs]⁠ matrix on the response scale, one row per draw and one column per row of newdata. A multivariate model with resp = NULL gives a named list, one element per response.

Trend state

By default the trend enters through its covariate part, without the state it took at each observed time. The brms counterparts of this method use that fitted state. incl_autocor = TRUE uses it here too, as fitted.mvgam() and pp_check.mvgam() do on the training data. The section 'Which prediction function?' of predict.mvgam() compares the prediction functions.

See Also

pp_check.mvgam() compares draws taken under the fitted state with the data. forecast.mvgam() predicts future times from the fitted state.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# Simulated counts, one row per draw and one column per observation
pp <- posterior_predict(mod)
dim(pp)

# The share of observed counts inside their 90 percent predictive
# intervals
bounds <- apply(pp, 2, quantile, probs = c(0.05, 0.95))
y <- simdat$data_train$y
mean(y >= bounds[1, ] & y <= bounds[2, ])

# Next: pp_check() plots the draws against the observed counts

## End(Not run)


Posterior draws of one smooth term

Description

Evaluates one smooth at the rows of newdata for each posterior draw, in the shape brms::posterior_smooths() returns. The smooth can be any s() or t2() term of the observation formula, a distributional or non-linear parameter's formula, or the trend formula, by factors included.

Usage

## S3 method for class 'mvgam'
posterior_smooths(
  object,
  smooth,
  newdata = NULL,
  resp = NULL,
  dpar = NULL,
  nlpar = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  ...
)

Arguments

object

A fitted mvgam object.

smooth

The smooth term as the formula writes it, such as "s(x)", "s(z, by = group)" or "t2(x, y)". Spacing is ignored. smooths.mvgam() lists the terms.

newdata

A data.frame holding the smooth's own variables, or NULL for the training data.

resp

The response the smooth belongs to, required on a model with several.

dpar, nlpar

The distributional or non-linear parameter the smooth belongs to. Name at most one. With both NULL the smooth belongs to the mean.

ndraws, draw_ids

The number of posterior draws, or their indices. Give at most one. NULL for both uses every draw.

...

Unused. Anything passed here is refused.

Details

The smooth's contribution is its unpenalised basis times its fixed coefficients plus each penalised basis times its random coefficients, per draw. The bases come from brms::standata() evaluated on newdata. The coefficients come from the draws. brms::posterior_smooths() adds a predictor's offsets to each of its smooths. This method leaves them out.

A term written in both the observation and the trend formula is taken from the observation formula.

Value

A numeric matrix with one row per draw and one column per row of newdata: the smooth's contribution to the linear predictor.

Author(s)

Nicholas J Clark

See Also

conditional_smooths.mvgam() summarises every smooth. smooths.mvgam() lists the terms.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), predict.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Twenty draws of s(x) over a grid of x
grid <- data.frame(x = seq(-2, 2, length.out = 50))
sm <- posterior_smooths(mod, smooth = "s(x, k = 5)", newdata = grid)
draws <- data.frame(x = rep(grid$x, each = 20),
                    value = as.vector(sm[1:20, ]),
                    draw = rep(1:20, times = 50))
library(ggplot2)
ggplot(draws, aes(x, value, group = draw)) +
  geom_line(colour = "#8F2727", alpha = 0.4) +
  labs(y = "s(x)") +
  mvgam_theme()

# Next, conditional_smooths(mod) summarises every smooth in one call

## End(Not run)


Posterior transition matrix of a VAR trend

Description

The coefficient matrix A_l of lag l of a VAR() trend. Row i holds the effects of the processes at time t - l on process i at time t. The diagonal holds each process's persistence. The off-diagonal cells hold the effects of one process on another.

Usage

posterior_transition_matrix(
  object,
  groups = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  prob_threshold = 0.95,
  lag = 1L
)

## S3 method for class 'mvgam_var_matrix'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_var_matrix'
plot(x, cluster = FALSE, supported_only = FALSE, ...)

## S3 method for class 'mvgam_var_matrix_list'
print(x, ...)

## S3 method for class 'mvgam_var_matrix_list'
plot(
  x,
  type = c("heatmap", "diagonal"),
  ncol = NULL,
  supported_only = FALSE,
  ...
)

Arguments

object

A fitted mvgam object whose trend is a VAR.

groups

The panels of a hierarchical VAR, by level or by index, or "all". NULL gives the mean of the panels' matrices. A single-panel fit takes NULL alone. One panel returns its matrix. Several, or "all", return a list whose plot() method is plot.mvgam_var_matrix_list().

summary

Logical. TRUE returns the summary of each cell. FALSE returns the draws as a ⁠[ndraws, K, K]⁠ array, with the processes naming its second and third dimensions.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Numeric vector of probabilities for quantile computation. Default is c(0.025, 0.975) for 95% credible intervals.

prob_threshold

The posterior probability of its sign a cell needs to count as supported, at least 0.5 and below 1. Defaults to 0.95. plot.mvgam_var_matrix() outlines the supported cells.

lag

The lag of the matrix, at most the order p of the fitted VAR(p).

x

An mvgam_var_matrix or mvgam_var_matrix_list.

digits

Integer number of digits in the printed matrix. Defaults to 2.

...

Unused. Anything passed here is refused.

cluster

Logical. TRUE orders the processes by a Robinson clustering of 1 - A, which suits a matrix close to symmetric.

supported_only

Logical. TRUE leaves blank every cell whose prob_nonzero is at most prob_threshold. Defaults to FALSE.

type

For several panels, "heatmap" (the default) or "diagonal".

ncol

The number of facet columns of the heatmaps, or NULL for ceiling(sqrt(length(x))).

Details

A hierarchical VAR (VAR(gr = ...)) has one matrix per panel. groups names a panel to return its matrix. With groups = NULL the function returns the mean of the panels' matrices, computed in each draw. The hyperparameters Amu_trend and Aomega_trend pool unconstrained matrices, which the stationarity map of Heaps (2023) turns into each panel's matrix. Their mean is no transition matrix. The mean over panels summarises the pool on the scale of the matrices.

Each cell is summarised as residual_cor() summarises a correlation. The estimate is the posterior mean, or the median with robust = TRUE. The interval takes the quantiles probs. The effective sample size comes from posterior::ess_basic(). prob_positive, prob_negative and prob_nonzero are the shares of draws above zero, below zero and away from zero.

Value

With summary = TRUE, an mvgam_var_matrix: a list of the matrices A, A_se, A_lower, A_upper, A_ess, prob_positive, prob_negative and prob_nonzero, with n_series, series_names, group_label, probs, prob_threshold and lag. With summary = FALSE, the array of draws. Several panels give a list of either, an mvgam_var_matrix_list when summarised.

print() gives the panel, the dimension, the mean absolute off-diagonal cell and the estimate of the matrix. For several panels it lists each panel's mean absolute off-diagonal cell. The panel with the largest has the strongest effects between processes.

plot() draws the matrix as a heatmap. Row i, column j is the effect of process j at time t - l on process i at time t. A black outline marks each cell whose prob_nonzero exceeds prob_threshold. The colour scale is symmetric about zero. Several panels share one scale. Under type = "diagonal" they draw the persistence of each process as a point with its interval.

Author(s)

Nicholas J Clark

References

Savage J (2016). Hierarchical Vector Autoregression. RPubs, 27 November 2016. https://rpubs.com/jimsavage/hierarchical_var

Heaps SE (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics 32(1), 74-83. doi:10.1080/10618600.2022.2079648

See Also

VAR(), residual_cor(), irf(), fevd(), stability(), print.mvgam_var_matrix(), plot.mvgam_var_matrix().

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), irf.mvgam(), ordinate(), residual_cor(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Ten years of monthly counts of a prey species and its predator.
# Predators suppress the prey a month later. Prey raise the
# predators a month later.
set.seed(2025)
n_months <- 120
A <- rbind(prey     = c(0.6, -0.5),
           predator = c(0.4,  0.5))
z <- matrix(0, n_months, 2)
for (t in 2:n_months) {
  z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35)
}
predator_prey <- data.frame(
  time = rep(seq_len(n_months), 2),
  series = factor(rep(c("prey", "predator"), each = n_months),
                  levels = c("prey", "predator")),
  y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2])))
)
var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(),
                 data = predator_prey, family = poisson(),
                 chains = 2, silent = 2)

## End(Not run)
## Not run: 
# Each series' persistence and its effects on the others
A <- posterior_transition_matrix(var_mod)
A
plot(A)

# Next, irf(var_mod) traces how a shock to one series spreads

## End(Not run)


Posterior predictive checks for mvgam models

Description

Compares the observed response with replicates drawn from the fitted model through the bayesplot ⁠ppc_*⁠ functions. Further types plot randomised quantile residuals and, for nmix() and occ() fits, a discrepancy statistic. Returns a ggplot2 object.

Usage

## S3 method for class 'mvgam'
pp_check(
  object,
  type,
  ndraws = NULL,
  prefix = c("ppc", "ppd"),
  group = NULL,
  x = NULL,
  newdata = NULL,
  resp = NULL,
  draw_ids = NULL,
  per_obs = TRUE,
  series = NULL,
  ...
)

## S3 method for class 'mvgam_ppc_fit_stat'
print(x, ...)

## S3 method for class 'mvgam_ppc_fit_stat'
plot(x, ...)

Arguments

object

An object of class mvgam

type

Type of the check. A bayesplot ⁠ppc_*⁠ or ⁠ppd_*⁠ function named without its prefix, or one of the residual types mvgam adds: "resid_hist", "resid_hist_grouped", "resid_ribbon", "resid_ribbon_grouped", "resid_qq", "resid_vs_fitted", "resid_acf", "resid_pacf" and "resid_variogram". Type "fit_stat" serves nmix() and occ() fits. A bernoulli or ordinal response defaults to "bars". Another discrete response, such as a count, defaults to "rootogram". A continuous response defaults to "dens_overlay". Multi-response families take the defaults under "Multi-response families".

ndraws

Number of posterior draws to plot. NULL (the default) takes the default of the type, listed under Details.

prefix

"ppc" (the default) plots the observed data with the replicates. "ppd" plots the replicates alone.

group

Optional name of a factor variable in the model by which to stratify the ppc plot. This argument is required for ppc *_grouped types and ignored otherwise.

x

An mvgam_ppc_fit_stat object.

newdata

Optional data frame of the variables in the model. NULL (the default) checks the training data. The residual types describe the training data and refuse newdata.

resp

Optional names of response variables. If specified, predictions are performed only for the specified response variables.

draw_ids

Optional integer vector naming the posterior draws to plot. NULL (the default) lets ndraws choose them.

per_obs

Logical. For type = "resid_vs_fitted", TRUE (the default) draws each observation at its posterior median on both axes. FALSE draws every draw of every observation, which shows the posterior spread.

series

For the residual types resid_hist, resid_ribbon, resid_qq, resid_vs_fitted, resid_acf, resid_pacf and resid_variogram, the one series whose residuals are drawn, as a name or an index. The default is the first series. Its residuals are taken in time order. resid_acf keeps missing responses in place. Its lags count time steps. resid_pacf drops them. Its lags count observations. A fit with several series names its series in the title.

...

Further arguments of posterior_predict.mvgam() and of the bayesplot function type names. Any other name is refused. type = "fit_stat" takes stat, either "chi_squared" (the default) or "freeman_tukey".

Details

Replicates of the training data are drawn under the latent trend state the model inferred at each time, as residuals.mvgam() and hindcast.mvgam() use. The check then compares the fitted trajectory with the series that produced it. Replicates of newdata use the covariate part of the model, as posterior_predict.mvgam() does. Passing incl_autocor chooses between the two. The ⁠loo_*⁠ types use the fitted state. Their importance weights come from it.

Overlay types default to 10 draws. Interval, ribbon and statistic types use every draw. The residual histograms and ribbons default to 500 draws, the other residual types to 100 and fit_stat to 500. A posterior with fewer draws gives all of them. resid_hist draws one histogram per draw and shows the first eight.

resid_acf and resid_pacf count lags in rows. They refuse a series observed at unevenly spaced times, such as one a CAR() trend models. resid_variogram measures lags in time units. It plots half the mean squared difference of two residuals against the time between them. Residuals without serial dependence give a flat semivariogram at their variance, the dashed line (Diggle et al. 2002). plot(type = "residuals") draws it in place of the ACF and pACF for such a series.

The PPC documentation of bayesplot describes each ⁠ppc_*⁠ type. A check restricted to one series or covariate slice takes newdata filtered to those rows. A group, such as group = "series", draws one panel per group through the ⁠_grouped⁠ variant of the type, so pp_check(fit, type = "dens_overlay", group = "series") draws "dens_overlay_grouped". "fit_stat" sums the units of each group. The single-series residual types ("resid_qq", "resid_vs_fitted", "resid_acf", "resid_pacf", "resid_variogram") ignore group. Any other type without a grouped variant refuses it.

Value

A ggplot object. A multivariate model given no resp returns one figure with a panel per response. type = "fit_stat" returns an mvgam_ppc_fit_stat object. print() gives its discrepancy and Bayesian p-value. plot() draws the discrepancy of each draw's replicates against that of the observations, with the 1:1 line and the p-value.

Multi-response families

diri(), multi(), categ(), mvn() and mvt() record several outcomes per unit. A pooled density would merge them into one curve. Without a group from the caller, pp_check() draws one panel per species through the type's ⁠_grouped⁠ variant. The default type is "ribbon" for a composition and "dens_overlay" for mvn() and mvt(). Passing a column of newdata as group draws the pooled plot.

Detection families (nmix(), occ())

The visits of a closure unit share one latent state. pp_check() sums the observed and replicated visits of each unit and compares the sums. The count types (bars, rootogram, hist, freqpoly), the density and ECDF overlays, the statistic types, intervals, ribbon, resid_hist and resid_qq apply. Types that plot rows, residuals against fitted values or residuals over time are refused. A group or x column must be constant within each unit. type = "fit_stat" computes the chi-squared or Freeman-Tukey discrepancy of Gelman et al. (1996) from the unit sums.

Author(s)

Nicholas J Clark

References

Diggle, P. J., Heagerty, P., Liang, K.-Y. and Zeger, S. L. (2002). Analysis of Longitudinal Data, 2nd edition. Oxford University Press.

Gabry, J., Simpson, D., Vehtari, A., Betancourt, M. and Gelman, A. (2019). Visualization in Bayesian workflow. Journal of the Royal Statistical Society A, 182:389-402. doi:10.1111/rssa.12378

Gelman, A., Meng, X.-L. and Stern, H. (1996). Posterior predictive assessment of model fitness via realized discrepancies. Statistica Sinica, 6:733-760.

See Also

residuals.mvgam() returns the residuals the residual types plot. CAR() models series observed at unevenly spaced times. loo.mvgam() scores the fit. The overview article explains a rootogram. The N-mixture article runs the discrepancy check.

Other model checking: mvgam_diagnostics, plot.mvgam(), residuals.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# A hanging rootogram, on the square-root scale. Each bar shows how
# often a count was observed. It hangs from the curve of its expected
# frequency under the model. A bar ending below zero marks a count the
# model under-predicts
pp_check(mod, type = "rootogram", style = "hanging")

# Randomised quantile residuals over time. A trend the model missed
# shows as serial structure
pp_check(mod, type = "resid_ribbon")

# Half the mean squared difference of residuals by the time between
# them. A flat band at the dashed variance shows no dependence left
pp_check(mod, type = "resid_variogram")

# Next: plot(mod, type = "residuals") shows the residual grid

## End(Not run)


Posterior predictions from an mvgam model

Description

Predicts new outcomes, their expectation or the linear predictor from every posterior draw, for the training data or for new data. The section 'Which prediction function?' compares predict() with fitted.mvgam(), hindcast.mvgam() and forecast.mvgam().

Usage

## S3 method for class 'mvgam'
predict(
  object,
  newdata = NULL,
  type = c("response", "link", "expected", "variance", "terms", "latent_state",
    "detection"),
  process_error = FALSE,
  incl_autocor = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  re_formula = NULL,
  allow_new_levels = FALSE,
  sample_new_levels = "uncertainty",
  resp = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  ...
)

Arguments

object

An object of class mvgam.

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

type

Character; one of "response" (default), "link", "expected", "variance", "terms", "latent_state", "detection". See Details.

process_error

Logical. FALSE, the default, leaves the trend's innovations out of the prediction. TRUE adds a random deviation at each time and series, drawn anew for every posterior draw from the spread the trend shows over the long run. For an AR(1) trend with innovation SD \sigma and coefficient \rho that spread has variance \sigma^2/(1-\rho^2). On a log link the deviations raise the average prediction by the factor \exp(\sigma^2/(2(1-\rho^2))). A random walk has no long-run spread. A ZMVN() trend has no dynamics. These two draw from the innovation covariance itself. CAR() draws from one long-run covariance at every time of an irregular grid. The argument applies under incl_autocor = FALSE. The fitted state already holds every innovation.

Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result.

incl_autocor

Logical. Chooses which version of the trend each prediction uses. FALSE, the default, uses the covariate part of the model: the effects in the observation formula and the trend formula, without the trend's innovations. A prediction then depends on the covariates alone. It is the same at the first time point as at the fiftieth. Questions about covariate effects use this version. TRUE uses the fitted state, the value the trend took at each observed time as hindcast() returns it. The section 'Which prediction function?' of predict.mvgam() compares the functions.

An ELPD or an R^2 describes the observed series. log_lik(), loo_R2.mvgam() and bayes_R2.mvgam() use TRUE for that reason. A time outside the training data is refused under TRUE. forecast.mvgam() predicts those times. An in-sample interval under TRUE conditions on states estimated from the same observations. It covers them more often than its nominal level. Calibration is judged out of sample, with forecast.mvgam() or lfo_cv().

The default suits a model whose covariates explain most of the signal. When most of the series-level variation lies in the trend, as in a fit with few covariates and a strong autoregressive process, the covariate part has little to say. hindcast.mvgam() and forecast.mvgam() are more informative there.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

allow_new_levels

Logical. TRUE predicts for grouping levels the model never saw, with coefficients sample_new_levels draws. A new series stays refused: it has no latent state to propagate.

sample_new_levels

How a new level's coefficients are drawn: "uncertainty" (the default) takes those of a fitted level chosen in each draw, "old_levels" those of one fitted level for all draws and "gaussian" draws them from the group's normal distribution. Each distributional parameter draws its own.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

summary

Logical. If TRUE (the default), returns summary statistics. If FALSE, returns the full matrix of posterior draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Numeric vector of probabilities for quantile computation. Default is c(0.025, 0.975) for 95% credible intervals.

...

Unused. Anything passed here is refused.

Details

type selects the quantity returned:

Value

With summary = FALSE, an ⁠[ndraws, nobs]⁠ matrix of draws. With summary = TRUE, a matrix with one row per observation and the columns:

A multivariate model with resp = NULL gives a named list of these, one per response.

Which prediction function?

Every prediction adds the latent trend to the observation model. The functions differ in the version of the trend they use and in whether they add observation noise.

Function Times Trend by default Observation noise
fitted() training data fitted state no
predict() any covariate part under type = "response"
posterior_predict() any covariate part yes
posterior_epred(), posterior_linpred() any covariate part no
hindcast() training data fitted state under type = "response"
forecast() after the training data fitted state, carried forward under type = "response"
residuals(), pp_check() training data fitted state yes

The fitted state is the value the trend took at each observed time, as the model inferred it. The covariate part keeps the effects of the observation and trend formulas and leaves out the trend's innovations. Questions about covariates use it, as conditional_effects.mvgam() and the marginaleffects functions do. incl_autocor = TRUE switches predict() and the ⁠posterior_*()⁠ methods to the fitted state, the default of their brms counterparts. fitted() uses the covariate part for newdata.

References

Royle, J. A. (2004). N-mixture models for estimating population size from spatially replicated counts. Biometrics, 60, 108-115. doi:10.1111/j.0006-341X.2004.00142.x

See Also

fitted.mvgam() returns expected values with the inferred trend state. forecast.mvgam() predicts future times from the fitted state. conditional_effects.mvgam() plots predictions against a covariate.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predictive_error.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# Predicted counts with their 95% intervals
head(predict(mod))

# The same fit on the link scale, as an expected count and as the
# variance of a count. A Poisson's variance equals its mean.
head(predict(mod, type = "link"))
head(cbind(
  expected = predict(mod, type = "expected")[, "Estimate"],
  variance = predict(mod, type = "variance")[, "Estimate"]
))

# `summary = FALSE` returns the draws, one row per draw
dim(predict(mod, summary = FALSE))

# Next: forecast() predicts beyond the training times from the
# fitted trend state

## End(Not run)


Posterior predictive errors on a fitted mvgam model

Description

Posterior draws of the prediction error, observed minus predicted, of each observation on the response scale. The arguments are those of brms::predictive_error.brmsfit().

Usage

## S3 method for class 'mvgam'
predictive_error(
  object,
  newdata = NULL,
  re_formula = NULL,
  re.form = NULL,
  method = "posterior_predict",
  resp = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  sort = FALSE,
  ...
)

Arguments

object

A fitted mvgam object from mvgam().

newdata

Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object.

re_formula

Group-level terms to include: NULL (the default) for every one, NA for none, or a formula naming the terms to keep, such as ~ (1 | g). A formula applies to the observation and the trend formulas alike. Any term it does not name is dropped.

re.form

The lme4 name for re_formula.

method

"posterior_predict" (the default) takes the errors from predictive draws, "posterior_epred" from expected values.

resp

Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

sort

Logical. TRUE orders the columns by the observed response. Defaults to FALSE.

...

Further arguments of the method function, such as incl_autocor or allow_new_levels.

Details

The errors are those residuals.mvgam() returns with type = "ordinary". In sample, each prediction carries the latent trend state the model inferred at that time. A prediction for newdata uses the covariate part of the model, without the trend's innovations.

Value

An ⁠[ndraws, nobs]⁠ matrix of observed minus predicted values.

Author(s)

Nicholas J Clark

See Also

brms::predictive_error.brmsfit(), residuals.mvgam(), posterior_predict.mvgam(), posterior_epred.mvgam().

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_interval.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# Observed minus predicted counts, one row per draw
err <- predictive_error(mod, draw_ids = 1:200)
dim(err)

# The three observations with the largest mean absolute error
mae <- colMeans(abs(err))
simdat$data_train[order(mae, decreasing = TRUE)[1:3], c("time", "y")]

# Next: residuals(mod) returns randomised quantile residuals

## End(Not run)


Posterior predictive intervals on a fitted mvgam model

Description

Central quantile intervals of the draws posterior_predict.mvgam() returns, one per observation.

Usage

## S3 method for class 'mvgam'
predictive_interval(object, prob = 0.9, ...)

Arguments

object

A fitted mvgam object.

prob

Numeric in ⁠(0, 1)⁠. The probability mass each interval holds. Defaults to 0.9.

...

Arguments of posterior_predict.mvgam(), such as newdata or incl_autocor.

Value

A numeric matrix with one row per observation and two columns, the lower and upper bounds.

Author(s)

Nicholas J Clark

See Also

posterior_interval.mvgam() gives intervals of parameters. pp_check.mvgam() plots predictive draws against the data.

Other predictions: conditional_effects.mvgam(), conditional_smooths.mvgam(), fitted.mvgam(), hindcast(), posterior_epred.mvgam(), posterior_linpred.mvgam(), posterior_predict.mvgam(), posterior_smooths.mvgam(), predict.mvgam(), predictive_error.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# 90 percent intervals, one row per observation
intervals <- predictive_interval(mod)
head(intervals)

# The share of observed counts the intervals cover
y <- simdat$data_train$y
mean(y >= intervals[, 1] & y <= intervals[, 2])

# Next: pp_check() plots the predictive draws against the data

## End(Not run)


Print an mvgam object

Description

Print an mvgam object

Usage

## S3 method for class 'mvgam'
print(x, ...)

Arguments

x

mvgam object returned from mvgam(), fitted or built with run_model = FALSE

...

Unused. Anything passed here is refused.

Value

The mvgam object is returned invisibly.

See Also

summary.mvgam() summarises the posterior of each parameter. methods_md() writes the model as equations. how_to_cite() drafts its methods paragraph.


Pair an observation formula with a trend formula

Description

Holds the two formulas of a model before it is fitted. get_prior.mvgam_formula(), stancode() and standata() take the pair, with the data and family, to show the priors, the Stan program and the data a fit would use. Nothing is compiled or sampled.

Usage

## S3 method for class 'mvgam_formula'
print(x, ...)

mvgam_formula(formula, trend_formula = NULL)

Arguments

x

An mvgam_formula object.

...

Unused.

formula

A formula, brmsformula or mvbrmsformula for the observation model.

trend_formula

A one-sided formula for the latent trend, such as ~ AR(p = 1). NULL, the default, gives a model without a trend, the model brms itself would fit.

Details

The observation formula takes the brms syntax, with distributional and non-linear sub-formulas through bf(). It refuses:

A trend formula holds one trend constructor (trend_constructors), added as a term of its own, as in ~ x + AR() or ~ x + mvgam::AR(). It also holds covariates of the latent state: smooths such as s() and t2(), random effects such as (1 | group) and Gaussian processes through gp(). lv_axis() in a term varies its effect by latent factor, or by series in a model without factors. It refuses:

Value

An object of class mvgam_formula holding formula and trend_formula. print() shows the two formulas.

Multivariate models

A multivariate model, written with mvbind() or bf() + bf(), takes one trend constructor for all of its responses. Each response can take its own family and its own observation terms, as in bf(count ~ x, family = poisson()) + bf(biomass ~ x, family = Gamma(link = "log")). The gr argument of the trend constructor pools the trends of groups. Responses that need different trend types need separate models.

See Also

get_prior.mvgam_formula() lists the priors of the pair. stancode() and standata() return its Stan program and data. mvgam() fits it.

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), series_to_mvgam(), stancode.mvgam_formula(), update.mvgam()

Examples

f <- mvgam_formula(y ~ s(x), trend_formula = ~ AR(p = 1))
f

# Observation weights belong in the observation formula
mvgam_formula(y ~ x + weights(w), trend_formula = ~ AR(p = 1))
try(mvgam_formula(y ~ x, trend_formula = ~ AR() + weights(w)))

## Not run: 
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    trend_model = AR())
# The priors and the Stan program a fit would use
get_prior(f, data = simdat$data_train, family = poisson())
stancode(f, data = simdat$data_train, family = poisson())

## End(Not run)


Latent trend models for mvgam

Description

Specify the latent trend of a state-space model. Each constructor goes inside trend_formula, as in trend_formula = ~ AR(p = 1). A constructor records its arguments. The model evaluates them against the data. The trends suit different series:

RW()

A level that wanders with no pull back to a mean.

AR()

Movement around a mean, with memory of the previous p times. It is a common first choice.

VAR()

Series whose past values drive one another, such as predators and prey.

CAR()

An AR(1) for series observed at irregular times.

ZMVN()

Correlated effects with no dependence on time, such as among sites or species.

LLT()

A level with a slope that changes over time, with an optional season.

PW()

Linear or logistic growth with changepoints.

Each trend moves by a random innovation at every time step. Other texts call it a process error or a shock. The innovations are independent across series unless cor = TRUE.

Usage

## S3 method for class 'mvgam_trend'
print(x, ...)

RW(
  time = NA,
  series = NA,
  ma = FALSE,
  cor = NULL,
  gr = NA,
  subgr = NA,
  n_lv = NULL,
  trend_map = NULL,
  df = Inf,
  centred = FALSE
)

AR(
  time = NA,
  series = NA,
  p = 1,
  ma = FALSE,
  cor = NULL,
  gr = NA,
  subgr = NA,
  n_lv = NULL,
  trend_map = NULL,
  coef_sharing = c("none", "shared", "hierarchical"),
  df = Inf,
  centred = FALSE
)

CAR(
  time = NA,
  series = NA,
  cor = FALSE,
  n_lv = NULL,
  trend_map = NULL,
  df = Inf,
  centred = FALSE
)

VAR(
  time = NA,
  series = NA,
  p = 1,
  ma = FALSE,
  cor = TRUE,
  gr = NA,
  subgr = NA,
  n_lv = NULL,
  trend_map = NULL
)

Arguments

x

An mvgam_trend object.

...

Unused.

time

The unquoted name of the numeric or integer variable in data that holds each row's time. Defaults to time.

series

The unquoted name of the factor variable in data that names each row's series. Its levels fix the order of the series. A trend needs this column even for a single series. Defaults to series.

ma

Logical. Include moving average terms of order 1? Default is FALSE.

cor

Logical. Correlate the innovations of different series? TRUE estimates a full covariance matrix of the innovations when the data hold more than one series. AR() and RW() default to NULL. That means FALSE for an ungrouped trend and TRUE when gr names a grouping variable. VAR(), ZMVN() and grouped AR() and RW() trends always estimate correlations. They refuse cor = FALSE. CAR() defaults to FALSE.

In a factor model with every loading sampled, the factors take independent shocks. The loadings carry the correlation among series, which residual_cor() reports. A correlation among the factors would trade off against the loadings. AR(), RW() and LLT() refuse cor = TRUE there. A trend_map that fixes the loadings keeps the factors apart. cor = TRUE then estimates their correlation.

gr

An optional factor in data that groups the series, such as region. Each level of gr takes its own correlation matrix among the innovations of its series. The matrices are pooled toward one global matrix:

\Omega_{group} = \alpha_{cor}\Omega_{global} + (1 - \alpha_{cor})\Omega_{group, local}

Here \Omega_{global} is shared by every group, \Omega_{group, local} is the deviation of one group and \alpha_{cor} sets the weight on the global matrix. An \alpha_{cor} near 1 pools the groups strongly. Without subgr, the series column names the series within each group.

Within a VAR() it sets up a hierarchical panel vector autoregression. Each group learns its autoregressive, moving-average and correlation matrices from shared hyperparameters. The groups do not interact.

Two constraints apply to hierarchical trend models:

  • Each series belongs to one group. mvgam() refuses a gr that varies within a series.

  • Every group must hold the same number of series. The Stan program sizes each group's correlation block from one shared count. Validation refuses unbalanced groups before fitting.

subgr

A subgrouping factor variable naming the time series within each level of gr. Defaults to series. A model with hierarchical correlations builds its series from gr and subgr, and data then needs no series column.

For example, to model counts of several species (species in data) across three regions (region) with innovations correlated within regions, specify gr = region and subgr = species. mvgam() then builds the series as

⁠series = interaction(gr, subgr, drop = TRUE, sep = "_",⁠ ⁠lex.order = TRUE)⁠

A region r1 and a species sp1 give the series "r1_sp1". The levels sort lexically. summary(), plot() and forecast() all label that series "r1_sp1". A series column that disagrees with the derived series is replaced by it, with a warning.

n_lv

The number of latent factors to estimate for dynamic factor models. When n_lv is smaller than the number of series, the latent processes are modelled as n_lv factors with estimated loadings onto the series. Defaults to NULL, in which case one latent process is used per series.

trend_map

Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:

  • a numeric ⁠n_series x n_lv⁠ matrix of loadings. NA entries are sampled and finite entries stay fixed. An all-NA matrix, such as matrix(NA, n_series, 2), fixes nothing and sets two factors.

  • a data.frame(series, trend) placing each series on one process, with a loading of one.

  • "identity", one process per series, or "shared", one process for every series.

Its columns set the number of factors, which an n_lv given too must match. Without a trend_map every loading is sampled and identified after sampling by a thin QR rotation (Heaps and Jermyn 2024). A map that fixes any loading takes no rotation. The loadings_prior of mvgam() accepts a map with no fixed entries. Defaults to NULL.

df

Degrees of freedom for the latent process innovations. Defaults to Inf, which gives Gaussian innovations: a t with infinite degrees of freedom is a normal. Set df = NA to estimate them, or supply a number above 2 to fix them.

Finite degrees of freedom let the latent process absorb an occasional large shock while sigma_trend stays at the scale of ordinary variation. That suits boom-and-bust population series and outbreak dynamics. The innovations follow a multivariate t. Because it shares one innovation scale across the series at each time point, large innovations tend to occur together. Each series keeps its own direction and magnitude. A shock in one series says nothing about the sign of the others. One series can also stay unmoved by an event that moves its neighbours. cor sets the correlation between series exactly as it does for Gaussian innovations. The degrees of freedom set how heavy the tails of the innovations are.

When df = NA the degrees of freedom are estimated as nu_trend, with a default gamma(4, 0.3) prior. The prior argument replaces it, for example prior(gamma(2, 0.1), class = "nu_trend"). get_prior lists nu_trend with the other trend classes.

Three caveats apply:

  • A fixed value must exceed 2. Below it the innovations have no finite variance. An autoregressive trend then has no stationary covariance to start from.

  • The first states of an autoregressive trend take the stationary mean and covariance. Under t innovations the true stationary distribution has heavier tails than that.

  • Only the tails of the latent process inform the degrees of freedom. Below roughly 200 time points their posterior stays close to the prior.

VAR() samples its states directly and PW() has no innovations. Neither takes df.

centred

Logical. Sample the latent states directly rather than their innovations? Default FALSE. The model and its posterior are the same. See Centred states below.

p

The autoregressive lags. The accepted form depends on the trend type:

  • For AR() models: a positive integer or a positive integer vector. A scalar p = k is the textbook AR(k) and expands to the consecutive lags 1:k. The fit then estimates ar1_trend through ark_trend. A vector p = c(...) selects a sparse lag set. p = c(1, 12) declares only ar1_trend and ar12_trend, a seasonal AR with no intermediate lags. p = c(2, 4) declares only ar2_trend and ar4_trend.

  • For VAR() models: a positive integer. p = k is the VAR(k), with one coefficient matrix for each of the lags 1:k. The stationarity prior of Heaps (2023) needs consecutive lags. A sparse lag vector is not supported. Use AR(p = c(...)) for sparse lags.

coef_sharing

How the coefficients of AR() vary across the latent series. "none" (the default) estimates each series' coefficients independently. "shared" estimates one coefficient per lag for every series. "hierarchical" pools each series' coefficient toward a mean for its lag, as ⁠ar{lag}_trend[j] ~ normal(mu_ar{lag}_trend, sigma_ar{lag}_trend)⁠. The section on AR coefficient sharing lists the parameters each setting samples.

Details

A trend_formula takes one trend constructor. The arguments of that constructor express richer dynamics:

Centred states: by default the sampler draws standard innovations and builds the states from them. This suits data that say little about each state, such as small counts, presence-absence or short series. When the data pin the states down, as large counts do, every innovation constrains every later state. The sampler then takes long trajectories and can hit the maximum tree depth. centred = TRUE samples each state as its distance from the first and recovers the innovations from them. On large counts it ran two to five times faster per effective draw. On small counts it ran ten to a hundred times slower. ZMVN() factors with sampled loadings draw their states directly either way. VAR() always does.

Stationarity of AR(p): a consecutive lag set with p >= 2 is sampled as partial autocorrelations, ar1_pacf_trend through ark_pacf_trend, each declared on (-1, 1). The Levinson-Durbin recursion derives ar1_trend through ark_trend from them. Every summary, forecast and hypothesis test uses those coefficients. Any vector of partial autocorrelations in (-1, 1) gives a stationary process. Bounding the coefficients directly admits explosive draws. With ar1_trend and ar2_trend both at 0.9 the declared bounds hold, yet that process grows without limit. Priors for these models name the ar{k}_pacf_trend classes.

AR(p = 1) samples ar1_trend directly. At one lag the declared interval is already the stationary region. A sparse lag set such as AR(p = c(1, 12)) also samples ar{k}_trend directly. It fixes its intermediate coefficients at zero, a constraint the recursion cannot express. It carries no stationarity guarantee. Both take priors on the ar{k}_trend classes.

CAR() steps a continuous-time AR(1) over the gaps the data records. A gap dt is measured in units of the median gap between two consecutive observations of one series. ar1_trend and sigma_trend then describe a typical step. The model is the same whatever unit the time column records. Across a gap dt the decay is ar1_trend^dt and the innovation standard deviation is sigma_trend * sqrt((1 - ar1_trend^(2 dt)) / (1 - ar1_trend^2)). The decay and the innovation scale together. The marginal variance is then sigma_trend^2 / (1 - ar1_trend^2) at every occasion of an irregular grid. The first state comes from that marginal.

CAR(cor = TRUE) correlates the innovations of several series. Sigma_trend is their covariance over a gap of one. Series a and b have stationary covariance Sigma_trend[a, b] / (1 - ar1_trend[a] * ar1_trend[b]). The innovations across a gap dt have that covariance times 1 - (ar1_trend[a] * ar1_trend[b])^dt. This is the exact transition of the continuous-time process. A time point added between two others leaves the model for the remaining times unchanged. L_Omega_trend is the Cholesky factor of the correlation between the series' shocks over an instant. Its prior is placed there. The correlation of Sigma_trend is closer to zero than that correlation when the series damp at different rates. On a regular grid the likelihood is that of AR(p = 1, cor = TRUE) with positive coefficients.

The series of a CAR() trend may be observed at their own times. The trend has a state for every series at each time any series was observed. A series contributes to the likelihood at the times it has a row. This is the model a frame gives when every unobserved time of a series has a row with a missing response. forecast() takes each series at its own future times. df needs the series on shared times. With one mixing scale per time, a multivariate t would let the times of one series change the trend of another.

Value

An object of class mvgam_trend holding the constructor's arguments. mvgam() builds the trend from it. print() shows the label a fit would print, such as ⁠AR({1, 12})⁠, with the columns and the settings that differ from their defaults.

AR coefficient sharing

Each coef_sharing setting samples its own Stan parameters:

coef_sharing Stan parameters with priors
"none" ⁠ar{lag}{stem}_trend⁠ per series
"shared" ⁠shared_ar{lag}{stem}_trend⁠ (one per lag)
"hierarchical" ⁠mu_ar{lag}{stem}_trend⁠, ⁠sigma_ar{lag}{stem}_trend⁠

{stem} is ⁠_pacf⁠ for a contiguous lag set of two or more lags, where the sampled quantity is a partial autocorrelation, and empty for p = 1 and for a sparse lag set such as p = c(1, 3). AR(p = 2) samples ar1_pacf_trend and AR(p = 1) samples ar1_trend. Every setting defines the same ⁠ar{lag}_trend[j]⁠ in ⁠transformed parameters⁠. Forecasting, IRF, FEVD and summaries use that quantity whatever the setting. A prior on any sampled parameter is set with brms::set_prior(class = "<name>"). get_prior(mvgam_formula(...)) lists the parameters the chosen coef_sharing samples.

Parameter Naming Convention

Every trend parameter carries a ⁠_trend⁠ suffix, which keeps it distinct from an observation model parameter of the same name. The innovation scale is sigma_trend, the moving-average coefficient theta1_trend, the autoregressive coefficients ar1_trend to ark_trend and the VAR coefficient matrices Phi_trend. Priors take these class names, as in prior(inv_gamma(5, 1), class = sigma_trend). Parameter extraction takes the same names.

Identification

A factor model with sampled loadings fits equally well under any reordering or sign change of its factors. Some models also fit equally well under any rotation. mvgam reports one version, chosen by the dynamics of the factors:

Post-fit methods use the identified loadings and factor paths. shared_variation() and residual_cor() are the same under every version.

A trend_map keeps its fixed entries on Z exactly. A by = lv_axis() smooth ties each factor to its own covariate effect. Neither takes a rotation. For a model with every loading sampled, the loadings_prior argument of mvgam() replaces the default iid Student-t prior on Z with a structured matrix-normal prior. That prior is built from per-series features, pairwise distance matrices or both. See mvgam for its arguments.

Setting loadings_prior = "mgp" (or loadings_prior = list(column_shrinkage = "mgp")) switches the column scaling to the multiplicative gamma process prior of Bhattacharya & Dunson (2011), which shrinks later columns of Z toward zero with increasing strength. n_lv is then a truncation ceiling on the factor count. active_factors reports the posterior distribution of the number of active factors.

Note

VAR fits and init = 0: the stationary map of Heaps (2023) takes matrix square roots by eigendecomposition. The gradient of an eigendecomposition divides by differences between eigenvalues. init = 0 in the call to mvgam() sets every raw coefficient to zero and every innovation scale to one. Each matrix the map decomposes is then the identity, with repeated eigenvalues, and the first gradient is not finite. Leave init at its default random draws for VAR() fits. AR(), RW(), CAR() and ZMVN() are unaffected.

Author(s)

Nicholas J Clark

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

Heaps, S. E. (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics, 32(1):74-83. doi:10.1080/10618600.2022.2079648

Clark NJ, Ernest SKM, Senyondo H, Simonis J, White EP, Yenni GM and Karunarathna KANK (2025). Beyond single-species models: leveraging multispecies forecasts to navigate the dynamics of ecological predictability. PeerJ, 13, e18929. https://doi.org/10.7717/peerj.18929

See Also

get_prior() lists the parameters a trend adds and their default priors. residual_cor(), irf(), fevd() and stability() interpret fitted latent dynamics. forecast() propagates them forward. The overview vignette compares the trend types. The VAR article interprets a fitted VAR() with irf(), fevd() and stability(). The hierarchical VAR article fits gr and subgr. The dynamic factor vignette fits n_lv and trend_map.

Other trend models: LLT(), PW(), ZMVN(), list_trend_types(), lv_axis()

Examples

## Not run: 
# A constructor records a trend before any data are seen. Printing
# one shows the settings the model will use
AR(p = c(1, 12))
VAR(p = 2, ma = TRUE)
RW(gr = region, subgr = species)

# A regularly spaced series usually starts with AR(p = 1). ?mvgam
# fits one. The rest of this example handles irregular sampling.

# Three Poisson series with a seasonal cycle, each surveyed at its
# own irregular times. sim_mvgam(type = 6L) draws the gaps between
# occasions. Every series keeps about 60 percent of the occasions
set.seed(11)
simdat <- sim_mvgam(type = 6L, family = poisson(), n_series = 3L,
                    n_timepoints = 80L)
keep_some <- function(d) d[runif(nrow(d)) < 0.6, ]
own_times <- keep_some(simdat$data_train)

# The parameters a trend adds, with their default priors, before
# any fitting
get_prior(
  mvgam_formula(y ~ s(season, bs = "cc", k = 6),
                trend_formula = ~ CAR(cor = TRUE)),
  data   = own_times,
  family = poisson()
)

# A continuous-time AR(1) steps each series over its own gaps
mod <- mvgam(
  y ~ s(season, bs = "cc", k = 6),
  trend_formula = ~ CAR(cor = TRUE),
  data          = own_times,
  family        = poisson(),
  chains        = 2,
  silent        = 2
)
summary(mod)

# Correlations among the series' latent states
residual_cor(mod)

# Residual checks. Each series has gaps of differing length. A
# semivariogram by time lag replaces the ACF
plot(mod, type = "residuals", series = 2)

# Each series is forecast at its own future times
plot(forecast(mod, newdata = keep_some(simdat$data_test)),
     series = 2)

# Counts near 150 pin each latent state down. Sampled centred, this
# random walk ran about five times faster per effective draw
n_t <- 60
big <- data.frame(time = 1:n_t, series = factor("s1"),
                  y = rpois(n_t, exp(5 + cumsum(rnorm(n_t, 0, 0.1)))))
mod_big <- mvgam(
  y ~ 1,
  trend_formula = ~ RW(centred = TRUE),
  data          = big,
  family        = poisson(),
  chains        = 2,
  silent        = 2
)
summary(mod_big)

# Next: hindcast() returns the fitted latent trends. The articles
# under 'See Also' fit VAR, hierarchical and factor trends

## End(Not run)


Group-level (random) effects of a fitted mvgam model

Description

Posterior draws of each level's deviation for every group-level term of the observation formula, summarised or raw. Each element is named ⁠r_<group>[<level>,<coef>]⁠, as variables.mvgam() lists it.

Usage

## S3 method for class 'mvgam'
ranef(
  object,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  pars = NULL,
  groups = NULL,
  ...
)

Arguments

object

A fitted mvgam object.

summary

Logical. TRUE (the default) summarises each coefficient's draws. FALSE returns the draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Two probabilities for the lower and upper bounds of the credible interval. Default c(0.025, 0.975), a 95% interval.

pars

Optional character vector of coefficient names, such as "Intercept". NULL (the default) keeps every coefficient.

groups

Optional character vector of grouping factors. NULL (the default) keeps every factor.

...

Unused. Anything passed here is refused.

Details

A group-level term in trend_formula is named with the ⁠_trend⁠ suffix, as r_g_trend[a,Intercept]. as_draws.mvgam() returns its draws.

Value

A named list with one 3D array per grouping factor. With summary = TRUE the dimensions are levels, statistics and coefficients. The statistics are Estimate, Est.Error and one quantile per element of probs. With summary = FALSE the dimensions are draws, levels and coefficients, and the array carries an nchains attribute. A grouping factor of a distributional parameter or of one response of several is keyed ⁠<group>__<parameter>⁠.

Author(s)

Nicholas J Clark

See Also

VarCorr.mvgam() summarises the standard deviations and correlations. fixef.mvgam() summarises the population-level effects.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), smooths.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(14)
simdat <- sim_mvgam(family = poisson(), n_series = 4L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5) + (1 | series),
             trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# Each series' intercept deviation, one row per series
ranef(mod)$series[, , "Intercept"]

# Next: VarCorr() gives the standard deviation of these deviations

## End(Not run)


Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

bayesplot

log_posterior, neff_ratio, nuts_params

brms

add_criterion, as.brmsprior, bayes_factor, bayes_R2, bernoulli, Beta, beta_binomial, bf, bridge_sampler, brmsfamily, brmsformula, conditional_effects, conditional_smooths, constant, control_params, custom_family, empty_prior, exponential, fixef, hypothesis, inits, is.brmsformula, is.brmsprior, is.mvbrmsformula, lognormal, LOO, loo_epred, loo_linpred, loo_predict, loo_predictive_interval, loo_R2, make_stancode, make_standata, mcmc_plot, mvbrmsformula, negbinomial, ngrps, posterior_average, posterior_smooths, posterior_summary, pp_average, prior, prior_, prior_draws, prior_samples, prior_string, prior_summary, ranef, set_prior, stancode, standata, stanvar, student, validate_prior, VarCorr, WAIC

generics

augment, forecast, glance, tidy

loo

loo, loo_compare, loo_model_weights, loo_moment_match, loo_subsample, waic

marginaleffects

avg_comparisons, avg_predictions, avg_slopes, comparisons, datagrid, hypotheses, plot_comparisons, plot_predictions, plot_slopes, predictions, slopes

posterior

as_draws, as_draws_array, as_draws_df, as_draws_list, as_draws_matrix, as_draws_rvars, nchains, ndraws, niterations, nvariables, rhat

rstantools

log_lik, posterior_interval, predictive_error, predictive_interval


Residual correlations between the series of a fitted model

Description

Posterior correlations, covariances and optional partial correlations between the series' latent trends. Residual here means the co-variation of the trends left once the covariate effects are accounted for. residuals.mvgam() returns the observation residuals. Three kinds of trend estimate these correlations:

Usage

residual_cor(object, ...)

## S3 method for class 'mvgam'
residual_cor(
  object,
  covariance = c("stationary", "innovation"),
  by_group = FALSE,
  partial = FALSE,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  prob_threshold = 0.95,
  ndraws = NULL,
  draw_ids = NULL,
  ...
)

Arguments

object

A fitted mvgam object.

...

Unused. Anything passed here is refused.

covariance

Which covariance to summarise. "stationary" (the default) gives the covariance of the latent states over the whole series. "innovation" gives the covariance of one time step's innovations. The two coincide for a trend whose states keep no memory between times.

by_group

Logical, for a hierarchical trend. FALSE (the default) returns the population correlation of the innovations, tcrossprod(L_Omega_global), under either covariance. TRUE also returns each group's correlation, alpha * tcrossprod(L_global) + (1 - alpha) * tcrossprod(L_dev[g]).

partial

Logical. TRUE also computes partial correlations, ⁠P_ij = -inv(R)_ij / sqrt(inv(R)_ii * inv(R)_jj)⁠. A partial correlation measures the association of two series once every other series is held fixed. The result stores them in the fields whose names start with prec. A factor fit with fewer factors than series has a singular covariance of rank n_lv and is refused. shared_variation() reports the variation its series share. The residual variances of mvn() and mvt() make their covariance full rank.

summary

Logical. TRUE (the default) summarises each entry: the point estimate, spread, credible interval and posterior sign probabilities. FALSE returns the arrays of draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Two probabilities for the lower and upper bounds of the credible interval. Default c(0.025, 0.975), a 95% interval.

prob_threshold

The posterior probability of its sign a correlation needs to count as supported, at least 0.5 and below 1. Defaults to 0.95. It sets sig_cor, the sig column of summary.mvgam_residcor() and the pairs plot.mvgam_residcor() outlines.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

Details

A correlated-innovation trend gives each draw the covariance ⁠diag(sigma) L_Omega L_Omega' diag(sigma)⁠. A VAR() trend takes the leading block of Omega_trend, the stationary covariance the Stan model derives from Phi_trend, Sigma_trend and, under ma = TRUE, Theta_trend.

The stationary covariance describes the states over the whole series. An AR(cor = TRUE) trend reports the stationary covariance of its states, including any moving-average term. With one lag it is Sigma[a, b] / (1 - ar_a * ar_b). A CAR() trend holds it at every time of an irregular grid. A draw whose autoregression is explosive has no stationary covariance and keeps its innovation covariance. A warning gives the count once per session. ZMVN() keeps no memory between times and RW() and LLT() have no stationary distribution. Each reports its innovation covariance. The level, slope and seasonal shocks of LLT() share its correlation. A hierarchical AR() converts each group's scales to stationary scales in the same way, before its global and group correlations are mixed.

Under covariance = "innovation" a VAR() fit reports the contemporaneous shocks. Its transition matrix spreads each shock across series at every step. The two correlations can differ substantially.

Intervals and spreads of correlations are computed on the Fisher-z scale, atanh(r), then back-transformed. The intervals stay inside ⁠(-1, 1)⁠. The reported matrix summarises each entry separately. It need not be positive semi-definite, most visibly when a few factors drive many series. A computation that factorises the matrix, such as chol(), takes summary = FALSE, whose per-draw matrices are valid correlation matrices. prob_positive and prob_negative are posterior sign probabilities. prob_nonzero is the larger of the two. sig_cor keeps the correlations whose prob_nonzero exceeds prob_threshold. Its other entries are zero.

jsdgam() fits the same factor model. Its species covariance follows the factor rule above.

Value

An mvgam_residcor object. Under by_group = TRUE on a hierarchical trend, an mvgam_residcor_list of them: the population matrix as "_global" and one per group. plot.mvgam_residcor_list() draws them as faceted heatmaps.

References

Hui, F. K. C. (2016). boral - Bayesian Ordination and Regression Analysis of Multivariate Abundance Data in R. Methods in Ecology and Evolution, 7(6), 744-750. doi:10.1111/2041-210X.12514

See Also

plot.mvgam_residcor() draws the matrix as a heatmap. community() gives the same associations as excess co-occurrence. species_effects() gives the responses to the covariates these correlations are net of. summary.mvgam_residcor() lists the pairs. ordinate() draws the loadings as a biplot. The example of trend_constructors takes the correlations of a CAR(cor = TRUE) trend. The joint species distribution article interprets species correlations from a factor model.

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), irf.mvgam(), ordinate(), posterior_transition_matrix(), shared_variation(), stability.mvgam()

Examples

## Not run: 
# Detections of 6 species whose occupancy shares two latent factors
simdat <- sim_closure_unit_data(family = occ(), n_species = 6L,
                                n_sites = 80L, n_visits = 4L,
                                n_lv = 2L, seed = 1L)
mod <- jsdgam(formula = bf(y ~ series * env, p ~ series + tod_c),
              factor_formula = ~ -1,
              data = simdat$data_train, family = occ(),
              n_lv = 2L, chains = 2, silent = 2)

# Species correlations after the fixed effects
rc <- residual_cor(mod)
round(rc$cor, 2)
plot(rc)

# Next: summary(rc) lists the pairs by posterior sign probability

## End(Not run)


Posterior draws of residuals from mvgam models

Description

Posterior draws of the residuals of a fitted mvgam model, of two types:

In sample, both types compare each observation with predictions that condition on the latent trend state the model inferred at that time, the state hindcast.mvgam() returns. For newdata the fit has no such state. The predictions then use the covariate part of the model, without the trend's innovations. Passing process_error = TRUE adds them. pp_check.mvgam() and predictive_error.mvgam() use the same predictions.

Pearson residuals are not supported. A Pearson residual of a count or a bounded response is skewed and discrete even under a correctly specified model.

Usage

## S3 method for class 'mvgam'
residuals(
  object,
  newdata = NULL,
  type = c("quantile", "ordinary"),
  ndraws = NULL,
  draw_ids = NULL,
  summary = TRUE,
  robust = FALSE,
  probs = c(0.025, 0.975),
  ...
)

Arguments

object

A fitted mvgam object.

newdata

Optional data.frame to compute residuals on. Defaults to the training data.

type

Character. Either "quantile" (default) or "ordinary".

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

summary

Logical. TRUE (the default) returns a summary per observation. FALSE returns the residual draws.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

probs

Two probabilities for the lower and upper quantile columns of the summary. Default c(0.025, 0.975), a 95% interval.

...

Further arguments of posterior_predict.mvgam(), such as resp or re_formula.

Details

Each draw places an observation in a PIT interval ⁠[lower, upper]⁠. The residual is qnorm(u) for a u drawn uniformly from that interval. Two routes give the interval.

The analytic route evaluates the family's distribution function at each draw's parameters. A discrete family gives the interval of the observed atom, ⁠[F(y - 1), F(y)]⁠. A continuous family gives the point F(y). A tweedie() zero gives ⁠[0, F(0)]⁠. Censored rows span their censoring interval. A truncated model renormalises over its truncation bounds. log_lik.mvgam() takes its density from the same parameterisation. The route covers gaussian, student, asym_laplace, lognormal, gamma, weibull, exponential, beta, bernoulli, binomial, beta_binomial, poisson, negbinomial, geometric, com_binomial(), beta_nb(), tweedie(), the ordinal families, and the multivariate mvn(), mvt(), diri(), multi() and categ(). A composition family uses the marginal of one component: a Beta for diri(), a Binomial against the site's own total for multi() and a Bernoulli for categ().

Every other family takes the empirical route, among them the zero-inflated, hurdle and mixture families, occ() and nmix(). Under the model the observation and the n pooled posterior_predict.mvgam() draws are exchangeable. The rank of the observation among those n + 1 values, with ties broken at random, is then uniform. The bounds are sum(yrep < y) / (n + 1) and (sum(yrep <= y) + 1) / (n + 1). An observation beyond every draw takes the top interval, ⁠[n / (n + 1), 1]⁠. The pooled predictive carries the posterior uncertainty in the latent state. Its residuals are narrower than N(0, 1). A QQ-plot of them is conservative.

The PIT value is clamped to ⁠[eps, 1 - eps]⁠, with eps = .Machine$double.eps, to keep the residual finite. The clamp bounds a residual at about +/-8.13. On the analytic route one draw can place an observation beyond that bound. Such isolated values describe that draw. A misfit shifts the residual across most draws.

Value

With summary = FALSE, an ⁠[ndraws, nobs]⁠ matrix of residual draws. With summary = TRUE, an ⁠[nobs, 2 + length(probs)]⁠ matrix. Its columns are Estimate (the mean, or the median with robust = TRUE), Est.Error (the standard deviation, or the MAD) and one quantile per probs.

Multivariate families (mvn(), mvt(), diri())

Each row of a unit gets its own residual. Residuals of mvn() and mvt() condition on the latent factor scores and test the observation model. They stay N(0, 1) when the fit has too few factors. active_factors() and residual_cor.mvgam() judge the number of factors.

A diri() residual is the exact marginal of one component, Beta(alpha_j, alpha_0 - alpha_j). Each is N(0, 1) on its own. Because the shares of a unit sum to one, the residuals of a unit of K species are negatively dependent, with K - 1 degrees of freedom. With K = 2 the two residuals are exactly antithetic. Judge a QQ-plot or an ACF at the unit grain.

Closure-unit families (nmix(), occ())

Visits within a closure unit (site by season) share the latent state, N for nmix() and z for occ(). The visits are independent given that state, but dependent marginally. Because residuals per visit would carry that dependence into every diagnostic, residuals() returns one residual per closure unit. The observed counts or detections are summed within each unit. The visit-level posterior_predict.mvgam() draws are summed the same way. Columns (summary = FALSE) or rows (summary = TRUE) are labelled by the unit's grouping values joined with ⁠_⁠.

Each draw simulates the latent state from lambda or psi without conditioning on the unit's detection history. The residuals then test the model across the population of units. predict(type = "latent_state") gives the state given each unit's detection history.

Under occ() a unit sum takes values in ⁠0, ..., n_rep⁠. With few visits the empirical PIT has coarse support. QQ-plot tails then look heavier than N(0, 1) under a correctly specified model. A once-per-session warning is raised when any unit has 4 or fewer visits. Compare QQ-plots with envelopes simulated from N(0, 1) in that case.

Author(s)

Nicholas J Clark

References

Dunn, P. K. and Smyth, G. K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5(3), 236-244.

See Also

augment.mvgam(), posterior_predict.mvgam(), pp_check.mvgam()

Other model checking: mvgam_diagnostics, plot.mvgam(), pp_check.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# Quantile residuals summarised per observation
r <- residuals(mod)
head(r)

# One draw of the residuals should look like N(0, 1) draws
r1 <- residuals(mod, summary = FALSE, draw_ids = 1)
qqnorm(r1[1, ])
qqline(r1[1, ])

# Next: plot(mod, type = "residuals") draws the QQ-plot, ACF and
# residuals against fitted values over many draws. A series observed
# at unevenly spaced times gets a semivariogram in place of the ACF

## End(Not run)


Process error innovation sampling for trend models

Description

Infrastructure for sampling process errors (innovations) from trend model distributions. All mvgam trend models use multivariate normal innovations with different covariance parameterizations.

Details

This module implements a pattern-based sampling system where trend types are mapped to one of four covariance patterns:

Each trend declares its pattern in the trend registry.


Proper scoring rules for mvgam_forecast objects

Description

Scores the held-out forecasts of an mvgam_forecast object from forecast.mvgam() or hindcast.mvgam() against the observations, with one of eleven scoring rules. Lower scores are better.

Usage

score(object, ...)

## S3 method for class 'mvgam_forecast'
score(
  object,
  score = "crps",
  interval_width = 0.9,
  quantile_level = 0.5,
  lower = -Inf,
  upper = Inf,
  log = FALSE,
  weights = NULL,
  ...
)

## S3 method for class 'mvgam_score'
print(x, digits = 2L, ...)

Arguments

object

An mvgam_forecast object whose type is "response" or "expected". The held-out observations are then on the scale of the forecasts.

...

Unused. Anything passed here is refused.

score

Character; one of the names under 'Available scores'. "drps" suits counts, "crps" continuous data and "brier" binary data. "energy" and "variogram" score several series jointly. Lower scores are better.

interval_width

Width of the central interval that sets the per-series in_interval indicator and the "sis" penalty. The indicator is computed for "crps", "drps", "sis" and the joint scores. The other scores report it as NA.

quantile_level

Level of the "qs" score. Defaults to 0.5, the median.

lower, upper

Thresholds of "twcrps" and "twenergy". The defaults -Inf and Inf give the unweighted scores.

log

Logical. TRUE applies log(x + 0.001) to observations and draws before scoring. Taken by "crps", "sis", "energy" and "variogram". Passing TRUE with any other score is an error.

weights

Optional numeric vector of non-negative weights, one per series, for "variogram".

x

An mvgam_score object returned by score().

digits

Integer number of significant digits. Defaults to 2.

Value

An object of class mvgam_score: a named list with one data frame per series plus a trailing all_series summary. Its print() method shows the mean score and interval coverage of each series. A multivariate model gives one such object per response. Each series' data frame has columns score, in_interval, interval_width, eval_horizon and score_type, which names the requested score. A joint score leaves the per-series score column NA.

For a univariate score, all_series sums the scores over the series at each forecast time, with score_type prefixed "sum_". Series forecast at their own times, as CAR() allows, are summed at the times they share. Its eval_horizon then counts the times any series is forecast at. For a joint score, all_series holds the score at each horizon. A joint score needs every series at the same forecast times.

Available scores

"crps"

Continuous ranked probability score (Gneiting and Raftery 2007) of the empirical distribution of the draws.

"drps"

Discrete ranked probability score, the CRPS of a count summed over its integer support.

"sis"

Scaled interval score: the width of the central interval plus a penalty for an observation outside it, scaled by 2 / (1 - interval_width).

"brier"

Brier score of a binary outcome: the squared difference between the observation and the mean of the draws.

"logs"

Log score, ⁠-log f(y)⁠ for a kernel density estimate of the draws.

"dss"

Dawid-Sebastiani score, which depends on the predictive mean and standard deviation alone.

"qs"

Quantile (pinball) score at quantile_level.

"twcrps"

Threshold-weighted CRPS, which scores the forecast inside ⁠[lower, upper]⁠.

"energy"

Energy score of the series jointly.

"variogram"

Variogram score of order 0.5 of the series jointly (Scheuerer and Hamill 2015).

"twenergy"

Threshold-weighted energy score.

References

Gneiting, T. and Raftery, A. E. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association, 102(477), 359-378. doi:10.1198/016214506000001437

Scheuerer, M. and Hamill, T. M. (2015). Variogram-based proper scoring rules for probabilistic forecasts of multivariate quantities. Monthly Weather Review, 143(4), 1321-1334. doi:10.1175/MWR-D-14-00269.1

See Also

forecast.mvgam() produces the forecast. compare_scores() scores several forecasts with one rule. ensemble.mvgam_forecast() combines forecasts. The forecast evaluation article compares models by their scores at each horizon.

Other forecasting: compare_scores(), ensemble.mvgam_forecast(), forecast.mvgam(), forecast_uncertainty(), hindcast(), lfo_cv.mvgam()

Examples

## Not run: 
set.seed(11)
simdat <- sim_mvgam(family = poisson(), n_series = 2L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5),
             trend_formula = ~ AR(p = 1),
             data = simdat$data_train,
             family = poisson(),
             chains = 2, seed = 3, silent = 2)

# Forecast the held-out times, then score each series
fc <- forecast(mod, newdata = simdat$data_test)
sc <- score(fc, score = "drps")
head(sc$series_1)

# The DRPS summed over series at each forecast horizon
library(ggplot2)
ggplot(sc$all_series, aes(eval_horizon, score)) +
  geom_line(colour = "#8F2727") +
  geom_point(colour = "#8F2727") +
  labs(x = "Horizon", y = "DRPS summed over series") +
  mvgam_theme()

# A joint score of both series at each horizon
head(score(fc, score = "energy")$all_series)

# Next: compare_scores() ranks several models by one rule

## End(Not run)


Seasonal patterns of a fitted local linear trend

Description

Lays out the posterior season of an LLT() trend by position within its period. It reports the size of the seasonal swing and where in the period it peaks, cycle by cycle. With newdata the season continues into the forecast horizon. The season is part of the latent trend, on the link scale. scale reports it on the scale of the expected value.

Usage

seasonality(object, ...)

## S3 method for class 'mvgam'
seasonality(
  object,
  newdata = NULL,
  ...,
  ndraws = NULL,
  draw_ids = NULL,
  scale = c("link", "expected", "ratio"),
  resp = NULL
)

## S3 method for class 'mvgam_seasonality'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_seasonality'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_seasonality'
plot(
  x,
  type = c("profile", "positions"),
  period = NULL,
  series = NULL,
  cycles = NULL,
  prob = 0.9,
  ...
)

Arguments

object

A fitted mvgam object whose trend is LLT(season = ...).

...

Unused. Anything passed here is refused.

newdata

Optional data frame of future times, as forecast.mvgam() takes it. The forecast season then extends each series.

ndraws, draw_ids

The posterior draws to use, as hindcast.mvgam() takes them. NULL for both uses every draw.

scale

"link" (the default) reports the latent season. "expected" reports its contribution to the expected value: the expected value with the season less the expected value without it. "ratio" reports the first of those over the second. Under a log link that ratio is the season's multiplicative effect.

resp

The response to report, needed on a model with several.

probs

Interval probabilities of the tables. Defaults to c(0.025, 0.975).

x

An mvgam_seasonality object from seasonality().

digits

Number of decimal places to print. Defaults to 2.

type

"profile" (the default) draws the season against position for a few cycles, one panel per series. "positions" draws one panel per position, the season over the cycles.

period

Which period to draw when the trend has several, by its name such as "season_7". Defaults to the first.

series

For type = "positions", the series to draw, by name or index. Defaults to the first.

cycles

For type = "profile", the cycles to draw. Defaults to the first and last complete fitted cycles and the first complete forecast cycle.

prob

For type = "profile", the width of the posterior interval. Defaults to 0.9. type = "positions" draws the nested intervals of plot.mvgam_forecast().

Details

Positions. A position counts steps within one period. Data from series_to_mvgam() carry a season column, or one ⁠season_<period>⁠ column per period, counted from the calendar. Position 1 of a twelve-month period is then January. A twelve-step period is labelled by month and a four-step one by quarter. Without the column, position 1 is the first fitted time and later times continue from it.

Cycles. A cycle is one pass through the period. A cycle that holds every position is complete. Only complete cycles are summarised.

Amplitude and peak. The amplitude of a cycle is half the range of the season within it. Its peak is the position of the largest value. Both are computed draw by draw. A change between the first and the last complete cycle then comes with its posterior probability.

Strength. The strength of a fitted cycle is the season's share of the variance of the link predictor over that cycle: ⁠Var(season) / (Var(season) + Var(predictor less season))⁠, computed draw by draw. It runs from 0 to 1 on every scale. A cycle spans little of the level's long-run drift, which leaves the season's share visible in a series dominated by that drift. A cycle reaching the forecast has no strength: its predictor mixes the season with fresh innovations.

Scale. The expected value comes from the fit's own family, draw by draw, with every other part of the predictor at its fitted or forecast value. Under a non-linear link the response-scale season then moves with the level. Its amplitude can grow while the latent season stays fixed.

A trend with several periods, such as LLT(season = c(7, 365.25)), reports each period's season separately.

Value

An object of class mvgam_seasonality. print() gives each series' amplitude and peak in its first and last complete cycles. summary() returns five tables: profile, amplitude, peak, strength and change, the last comparing the first and last complete cycles. plot() draws the profile by position, or one panel per position over the cycles.

Author(s)

Nicholas J Clark

See Also

LLT() for the seasonal model, series_to_mvgam() for the calendar positions, forecast.mvgam() with component = "season" for the season along time

Examples

## Not run: 
# Monthly airline passengers, the final year held out. Counts in the
# hundreds determine each month's state closely. Centred states then
# sample better than the default non-centred ones.
air <- series_to_mvgam(AirPassengers, h = 12)
mod <- mvgam(
  y ~ 1,
  trend_formula = ~ LLT(season = 12, harmonics = 3, centred = TRUE),
  data = air$data_train,
  family = poisson(),
  chains = 2,
  seed = 1,
  silent = 2
)

# Amplitude and peak month, first and last complete year
s <- seasonality(mod, newdata = air$data_test)
s

# The season by month in the first, last and forecast years
plot(s)

# Each month's effect over the years and into the forecast
plot(s, type = "positions")

# How the swing and its peak changed between the first and last year
summary(s)$change

# The season as a multiple of the expected passenger count
plot(seasonality(mod, scale = "ratio"))

## End(Not run)


Convert time series objects to mvgam long format

Description

Convert a tsibble, a ts, mts or msts object, or a wide data.frame with a date column into the long data.frame that mvgam() expects: one row per series and time, a series factor and a time column counting steps from the first index value.

Usage

series_to_mvgam(
  series,
  freq = NULL,
  response = NULL,
  index = NULL,
  h = NULL,
  train_prop = NULL
)

Arguments

series

The data to convert. One of:

  • A tsibble (tsibble::tsibble()). Its key variables define the series and its index defines the time grid. Gaps in a regular tsibble become rows with a missing response, as tsibble::fill_gaps(.full = TRUE) builds them. Measured variables other than the response are carried over as covariates, with missing values on those rows. An irregular tsibble keeps its own times, for use with CAR() or ZMVN().

  • A ts, mts or msts object (forecast::msts()). Each column of an mts is a series.

  • A wide data.frame holding one date column and one numeric column per series. Column names become the series levels, in column order.

freq

Optional numeric vector of seasonal periods, in time steps. Each period above 1 adds a column giving the position of each row within that period. Defaults to the periods the object carries: frequency() of a ts, the seasonal.periods of an msts, or tsibble::guess_frequency() of the index.

response

Name of the measured variable to use as the response of a tsibble. Optional when the tsibble has one measured variable. Ignored for other inputs, whose response column is y.

index

Name of the date column of a wide data.frame. Optional when exactly one column has class Date, POSIXt, yearmonth, yearquarter or yearweek.

h

Optional number of final time steps to hold out as test data.

train_prop

Optional proportion of time steps to keep as training data, between 0 and 1. Only one of h and train_prop may be given.

Details

time counts steps from 1 at the first index value. The position within a seasonal period counts steps from the calendar origin of the index. A monthly index with freq = 12 gives the month number whatever month the data start in. A ts gives cycle(). A single period produces a column named season. Several periods produce ⁠season_<period>⁠ columns, such as season_7 and season_365.25.

Rows for future times with a missing response, built for example with tsibble::new_data() and bound to the observed data, receive time values that continue the grid. Converting observed and future rows together keeps the two aligned.

Seasonal periods take the same numbers across packages. Monthly data carry frequency = 12 in a ts. A fable season(period = "year") on a monthly tsibble resolves to 12 steps. Both take freq = 12. Daily data with seasonal.periods = c(7, 365.25) in an msts take freq = c(7, 365.25).

A season column feeds a fixed seasonal shape, such as s(season, bs = "cc"). The same periods give LLT() a season whose shape drifts over the years, as trend_formula = ~ LLT(season = 12).

Value

A long data.frame. Its columns are series (a factor), time (an integer for regular data), the response and the original index (index for a ts). Any tsibble key and covariate columns follow, then one season column per period above 1. Rows are ordered by time, then series. With h or train_prop, a list holding data_train and data_test instead.

Author(s)

Nicholas J Clark

See Also

The data article covers the long format and its conversion in more depth. LLT() takes the same periods for a season that drifts.

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), stancode.mvgam_formula(), update.mvgam()

Examples

# Monthly airline passengers, holding out the final year
air <- series_to_mvgam(AirPassengers, h = 12)
head(air$data_train)

# Two series in one mts
deaths <- series_to_mvgam(cbind(male = mdeaths, female = fdeaths))
levels(deaths$series)

# A wide data.frame with a date column. Converting dates needs the
# tsibble package.
if (requireNamespace("tsibble", quietly = TRUE)) {
  wide <- data.frame(
    date = seq(as.Date("2024-01-01"), by = "day", length.out = 28),
    site_a = rpois(28, 5),
    site_b = rpois(28, 8)
  )
  head(series_to_mvgam(wide))
}

# Next: fit the training data, for example with
# mvgam(y ~ s(season, bs = "cc"), trend_formula = ~ AR(),
#       data = air$data_train)


Posterior summary of the factor-implied shared variation matrix

Description

For a latent-factor mvgam fit, returns the posterior of the shared variation matrix \Delta = Z \Sigma Z^\top. Z is the ⁠n_series x n_lv⁠ loadings matrix and \Sigma is the covariance of the latent states. Delta is the covariance the factors induce between the series' trends. Its diagonal gives the variance of each series that the factors capture. Its off-diagonal entries give the covariance between pairs of series.

Usage

shared_variation(object, ...)

## S3 method for class 'mvgam'
shared_variation(object, probs = c(0.025, 0.975), robust = FALSE, ...)

## S3 method for class 'mvgam_shared_variation'
plot(x, type = c("point", "uncertainty"), ...)

Arguments

object

A fitted mvgam object whose trend model includes latent factors (n_lv < n_series).

...

Unused. Anything passed here is refused.

probs

Two probabilities for the lower and upper bounds of the credible interval. Default c(0.025, 0.975), a 95% interval.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

x

An mvgam_shared_variation object.

type

"point" (the default) draws the point estimate. "uncertainty" draws the per-entry spread, delta_se.

Details

A factor column enters the trend as sigma_trend[k] * Z[, k]. ⁠Z Z'⁠ alone would weight every column equally, while the model scales each column by its latent standard deviation. Under multiplicative gamma process shrinkage those scales hold the whole of the shrinkage. For an autoregressive trend \Sigma is the stationary covariance of the latent states, as in residual_cor().

Delta is invariant to rotation. An orthogonal ⁠Z* = Z Q⁠ with ⁠Sigma* = Q' Sigma Q⁠ leaves ⁠Z* Sigma* Z*'⁠ unchanged. The summary takes the same value for the sampled Z and for the QR-identified Z_tilde of Heaps and Jermyn (2024). It uses the sampled Z, the basis \Sigma is stated in. A trend_map without NA entries fixes Z. The posterior spread of Delta then comes from \Sigma alone.

Value

An object of class mvgam_shared_variation, a list with:

plot() draws the point estimate, or under type = "uncertainty" the per-entry spread, as a heatmap. The diagonal shows the variance the factors capture in each series. The fill scale is symmetric about zero.

Relation to loadings_prior

Under the matrix-normal prior ⁠Z | Phi, Psi ~ MN(0, Phi, Psi)⁠, the prior expectation of ⁠Z Z'⁠ is ⁠tr(Psi) Phi⁠ (Heaps and Jermyn 2024, section 3). Phi sets the prior expectation of the coupling pattern between series, while Z itself is identified only up to rotation. A loadings_prior in mvgam() encodes domain knowledge about that pattern through Phi.

Delta also carries the latent covariance. Its scale includes the variance of the latent states. Compare its pattern with Phi.

Author(s)

Nicholas J Clark

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

See Also

residual_cor() for the implied correlation matrix, cov2cor(Delta). Under mvn() and mvt() it adds each series' residual variance to the diagonal of Delta first. The joint species distribution article interprets both for a community of species.

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), irf.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), stability.mvgam()

Examples

## Not run: 
# Detections of 6 species whose occupancy shares two latent factors
simdat <- sim_closure_unit_data(
  family    = occ(),
  n_species = 6L,
  n_sites   = 80L,
  n_visits  = 4L,
  n_lv      = 2L,
  seed      = 1L
)
mod <- jsdgam(
  formula        = bf(y ~ series * env, p ~ series + tod_c),
  factor_formula = ~ -1,
  data           = simdat$data_train,
  family         = occ(),
  n_lv           = 2L,
  chains         = 2,
  silent         = 2
)

# The species-by-species covariance the two factors induce
sv <- shared_variation(mod)
sv
plot(sv)

# Next: residual_cor() rescales Delta to correlations

## End(Not run)


Simulate closure-unit detection data with known truth

Description

Simulates single-season data for the closure-unit families, occ() and the nmix() variants. Each covariate recipe holds per-site covariates for the latent state and per-visit covariates for detection. data_train is the long frame mvgam() and jsdgam() take. y_array is the four-dimensional layout of pivot_detection_array(). truth holds every generative parameter for recovery checks.

Usage

sim_closure_unit_data(
  type = 1L,
  family = occ(),
  n_species = 1L,
  n_sites = 30L,
  n_visits = 4L,
  n_lv = 0L,
  K_max = 30L,
  seed = NULL
)

## S3 method for class 'mvgam_sim_closure_unit'
summary(object, ...)

## S3 method for class 'mvgam_sim_closure_unit_summary'
print(x, digits = 3L, ...)

Arguments

type

Integer in 1:2 selecting the covariate recipe. See Details.

family

A closure-unit family: occ() (the default), nmix() ("poisson_binomial"), nmix("royle_nichols") or nmix("poisson_poisson").

n_species

Integer number of species. Defaults to 1L.

n_sites

Integer number of closure units per species. Defaults to 30L.

n_visits

Integer number of visits to every closure unit. Defaults to 4L.

n_lv

Integer number of latent factors shared by the species' state intercepts. Defaults to 0L, independent species. Requires n_species > 1L. See Latent factors.

K_max

Integer cap on the latent abundance N of an nmix() family. Defaults to 30L.

seed

Optional integer seed. The session's random state is restored when the call returns.

object

A mvgam_sim_closure_unit object.

...

Unused. Anything passed here is refused.

x

A mvgam_sim_closure_unit_summary object.

digits

Integer number of significant digits. Defaults to 3.

Details

type = 1

State predictor b0 + b1 * env, with env ~ N(0, 1) per site. Detection predictor c0 + c1 * tod_c, with tod_c ~ U(-6, 6) per visit, a centred time of day.

type = 2

State predictor b0 + b1 * env + b2 * elev, with env and elev each N(0, 1) per site. Detection predictor c0 + c1 * tod_c + c2 * effort, with tod_c ~ U(-6, 6) and effort ~ U(0.5, 1.5) per visit.

Each predictor is on the scale of the family's own link. The state predictor takes the logit for occ() and the log for every nmix() variant, where it sets the Poisson abundance mean lambda. The detection predictor takes the logit for occ(), nmix("poisson_binomial") and nmix("royle_nichols"). It takes the log for nmix("poisson_poisson"), whose encounter rate rho is unbounded.

Each species draws an intercept from a normal with mean zero. Each covariate draws one community mean. Each species then draws its slope around that mean. The standard deviations are:

Predictor Intercept Community mean Species slope
occ() state 0.75 1.5 0.5
nmix() state 0.5 0.4 0.3
Detection 0.5 0.2 0.15

The nmix() state scales keep lambda well below K_max. The detection scales keep detection away from 0 and 1 across the range of tod_c.

Value

A list of class c("mvgam_sim_closure_unit", "mvgam_sim"):

data_train

Long data.frame. Its columns are series (the species), site, time (the site, which identifies the closure unit in a single season), visit, y, the site and visit covariates, then cap: 1 for occ(), K_max for nmix().

data_test

NULL. Closure-unit data have no held-out times.

y_array

Integer array ⁠[n_species, n_sites, 1, n_visits]⁠ for pivot_detection_array().

family, type

The family and recipe.

n_species, n_sites, n_visits, n_lv

The simulation dimensions.

truth

The generative parameters. See Truth bundle.

Latent factors

With n_lv > 0L, the state predictor of species k at site i gains ⁠sum_l Z[k, l] * lv[i, l]⁠. The ⁠[n_species x n_lv]⁠ loadings Z are normal with standard deviation 0.7. The ⁠[n_sites x n_lv]⁠ factor scores lv are standard normal. truth$loadings and truth$lv return both for comparison with jsdgam() estimates and ordinate().

Truth bundle

psi (occ) or lambda (nmix)

⁠[n_species x n_sites]⁠ matrix of occupancy probabilities or expected abundances.

z (occ) or N (nmix)

⁠[n_species x n_sites]⁠ matrix of the realised latent states that predict(fit, type = "latent_state") estimates.

p

⁠[n_species x n_sites x n_visits]⁠ array of the detection parameter that predict(fit, type = "detection") estimates: the detection probability, the per-individual probability r of nmix("royle_nichols") or the encounter rate rho of nmix("poisson_poisson").

state_coefs, detection_coefs

The intercept and slopes of each predictor. A named vector for one species, an ⁠[n_species x (1 + p)]⁠ matrix for several.

loadings, lv

Z and the factor scores, when n_lv > 0L.

summary() returns an mvgam_sim_closure_unit_summary list: the dimensions, the recipe, the ranges of the true state and detection parameters and the share of non-zero observations. A share of 0 or 1 marks data with no information on detection. print() shows it.

Author(s)

Nicholas J Clark

See Also

sim_mvgam() simulates state-space time series. sim_jsdgam() simulates site-by-species data without a detection process. The N-mixture article fits occupancy and N-mixture models to data of this layout.

Other simulation: sim_jsdgam(), sim_mvgam()

Examples

# Four species with two site and two visit covariates
simdat <- sim_closure_unit_data(
  family    = occ(),
  n_species = 4L,
  n_sites   = 50L,
  n_visits  = 4L,
  type      = 2L,
  seed      = 1L
)
head(simdat$data_train)
summary(simdat)

# Next: fit these data with jsdgam(), as the shared_variation()
# example does


Simulate multi-species data for a joint species distribution model

Description

Draws a site-by-species response matrix from a latent factor model and returns it in the long format jsdgam() takes. Each species gets its own intercept and its own slope on a site-level covariate. The species share n_lv latent factors, whose loadings set the residual correlation between them.

This is the non-detection counterpart to sim_closure_unit_data(), which simulates the same latent factor structure for the occupancy and N-mixture families.

Usage

sim_jsdgam(
  family = brms::negbinomial(),
  n_species = 5L,
  n_sites = 60L,
  n_lv = 2L,
  family_pars = list(),
  seed = NULL
)

## S3 method for class 'mvgam_sim_jsdgam'
summary(object, ...)

## S3 method for class 'mvgam_sim_jsdgam_summary'
print(x, digits = 3L, ...)

Arguments

family

Observation family. Any family mvgam's response simulator draws from, plus mvn(), mvt(), diri(), multi() and categ(). Defaults to brms::negbinomial().

n_species

Number of species. Defaults to 5.

n_sites

Number of sites. Defaults to 60.

n_lv

Number of latent factors. Defaults to 2.

family_pars

Optional named list of family parameters: Psi (per-species scale for mvn() / mvt()), nu (degrees of freedom for mvt()), phi (concentration for diri()), unit_total (trial total per site for multi()). Other families take their dispersion or scale, such as size for a negative binomial or sigma for a gaussian.

seed

Optional integer seed. The session's random state is restored when the call returns.

object

A mvgam_sim_jsdgam object.

...

Unused. Anything passed here is refused.

x

A mvgam_sim_jsdgam_summary object.

digits

Integer number of significant digits. Defaults to 3.

Details

The linear predictor for species k at site i is intercept[k] + env_slope[k] * env[i] + Z[k, ] %*% lv[i, ], where Z holds the loadings and lv the site scores. The residual covariance the model targets is ⁠Z Z'⁠, plus a diagonal of squared per-species scales for mvn() and mvt().

How that predictor becomes a response depends on the family. Families whose species are drawn independently, such as brms::negbinomial() or stats::poisson(), take one draw per species. mvn() and mvt() add a per-species residual. The composition families draw a site's species together. diri() normalises gamma variates. multi() draws counts against a fixed site total. categ() draws one species per site as a one-hot row.

A composition family identifies its loadings only up to a shift shared by the species, which is the subspace mvgam's sum_to_zero_vector parameterisation covers. The loadings are centred for those families, which puts the simulated truth in the same subspace a fit explores.

How much of the factor structure survives into the response depends on the observation noise. The loadings are drawn with standard deviation 0.7. mvn() and mvt() take their per-species scale from Psi, which defaults to 0.5. Every other family takes the scale its own simulator defaults to. A gaussian's sigma defaults to 1, which can hide the species correlations from the data. Pass family_pars = list(sigma = 0.5) for a gaussian whose correlations a fit can recover.

Value

An object of class mvgam_sim_jsdgam, inheriting mvgam_sim, with elements:

data_train

Long data.frame with columns site, env, series (the species), y and time (the unit index jsdgam() keys on).

data_test

NULL, kept for consistency with the other simulators.

y_array

⁠[n_sites x n_species]⁠ response matrix.

family

The family used.

n_species, n_sites, n_lv

The design.

truth

List of the generative parameters: loadings, lv, intercepts, env_slopes, env, residual_cov, residual_cor and family_pars. For mvn(), mvt(), diri() and multi() these include the defaults Psi = 0.5, nu = 5, phi = 30 and unit_total = 30.

summary() returns an mvgam_sim_jsdgam_summary list: the design, the per-species generative parameters and the range of the residual correlations the loadings imply, which a fit of these data is asked to recover. print() shows it.

See Also

jsdgam() fits the model these data come from. sim_closure_unit_data() simulates occupancy and N-mixture data. sim_mvgam() simulates time series. The joint species distribution article fits and interprets models of this kind.

Other simulation: sim_closure_unit_data(), sim_mvgam()

Examples

simdat <- sim_jsdgam(
  family    = brms::negbinomial(),
  n_species = 4L,
  n_sites   = 30L,
  n_lv      = 2L,
  seed      = 1L
)
head(simdat$data_train)
summary(simdat)

# A composition family draws each site's species together
comp <- sim_jsdgam(family = diri(), n_species = 4L, n_sites = 20L,
                   seed = 2L)
rowSums(comp$y_array)[1:3]

# Next: fit with jsdgam(), then compare residual_cor() of the fit
# with simdat$truth$residual_cor


Simulate mvgam-shaped time-series data with known truth

Description

Simulates training and test data from one of seven observation-side recipes (type) combined with a latent trend (trend_model). The recipes cover smooths, Gaussian processes and random effects. Every generative quantity is returned for recovery checks.

Usage

sim_mvgam(
  type = 1L,
  family = gaussian(),
  n_series = 1L,
  n_timepoints = 80L,
  trend_model = NULL,
  prop_trend = NULL,
  proportional_train = 0.75,
  prop_missing = 0,
  family_pars = list(),
  seed = NULL
)

## S3 method for class 'mvgam_sim'
summary(object, ...)

## S3 method for class 'mvgam_sim_summary'
print(x, digits = 3L, ...)

## S3 method for class 'mvgam_sim'
print(x, ...)

Arguments

type

Integer in 1:7 selecting the observation-side recipe. See Details.

family

The observation family: gaussian() (the default), student(), poisson(), negbinomial(), bernoulli(), binomial(), Beta(), Gamma(), tweedie(), beta_nb() or com_binomial(), or the matching brms::brmsfamily().

n_series

Integer number of series. Defaults to 1L.

n_timepoints

Integer number of time points per series. Defaults to 80L.

trend_model

A trend constructor such as AR(p = 1), AR(p = c(1, 12)), VAR(cor = TRUE), CAR(), ZMVN() or PW(). NULL (the default) takes the type's own trend. "None" simulates no trend. To fit the simulated data, name the same trend inside trend_formula, as in mvgam(y ~ s(x), trend_formula = ~ AR()). mvgam() refuses a trend_model argument.

prop_trend

Share of the link-scale variance given to the trend, in ⁠[0, 1]⁠. NULL takes the type's default: 0.2 for type 5, 0.6 for types 2, 3, 4 and 7, and 0.5 for types 1 and 6.

proportional_train

Share of the time points kept in data_train, between 0.1 and 1. The remaining, later time points form data_test. Defaults to 0.75.

prop_missing

Share of the training responses set to NA, between 0 and 0.5. Defaults to 0.

family_pars

Optional named list of family parameters: sigma and nu (gaussian, student), size (negative binomial), trials (binomial, com_binomial), phi (beta, tweedie), shape (gamma, beta_nb), power (tweedie), mtail (beta_nb) and nu (com_binomial dispersion). Unset entries take defaults.

seed

Optional integer seed. The session's random state is restored when the call returns.

object

An mvgam_sim object.

...

Unused. Anything passed here is refused.

x

An mvgam_sim object or its summary.

digits

Integer number of significant digits. Defaults to 3.

Details

type = 1

y ~ s(x) with an RW() trend.

type = 2

y ~ s(x) + s(z) with an AR(p = 1) trend whose coefficient is 0.7.

type = 3

y ~ s(x) + (1 | grp) with an AR(p = 1) trend whose coefficient is 0.7. The random intercept has five levels.

type = 4

y ~ gp(x) with an AR(p = 1) trend whose coefficient is 0.7.

type = 5

y ~ x with trend_formula = ~ s(z) and an AR(p = 1) trend whose coefficient is 0.6. The smallest prop_trend default keeps the autoregression separable from the smooth.

type = 6

y ~ s(season, bs = "cc") with a CAR() trend on irregular gaps drawn from Uniform(1, 6). The autocorrelation over the median gap is 0.7.

type = 7

y ~ s(x) with a sparse AR(p = c(1, 12)) trend whose coefficients are 0.55 and 0.40. The covariate is not periodic. All of the seasonal recurrence comes from the lag-12 coefficient.

Covariates are drawn independently for each row. Series are independent unless the trend correlates them, as VAR(), ZMVN() and cor = TRUE do. The trend and the observation-side terms are each centred, then rescaled to their shares of a link-scale standard deviation that keeps the response in a plausible range for the family.

Value

A list of class "mvgam_sim":

data_train, data_test

Long data frames with columns y, series, time, the recipe's covariates and, for binomial families, trials. data_test is NULL when proportional_train = 1.

family, trend_model, type

The simulation settings.

true_betas

Named population-level coefficients.

true_smooths

Named list of data frames holding each true smooth on a grid of its covariate, in column f_true.

true_trend

⁠[n_timepoints, n_series]⁠ matrix of the latent trend.

true_trend_sigma

Standard deviation of true_trend.

true_sigma_obs

The family's scale or dispersion, or NA for a family without one.

summary() returns the design and these true parameters as an mvgam_sim_summary list, with the number of series, time points, training and test rows and the names of the true smooths. print() shows that summary.

Author(s)

Nicholas J Clark

See Also

mvgam() fits the simulated data. sim_closure_unit_data() simulates occupancy and N-mixture data. sim_jsdgam() simulates site-by-species data. The overview article fits a model to data from sim_mvgam().

Other simulation: sim_closure_unit_data(), sim_jsdgam()

Examples

# Three Poisson series with an AR(1) latent trend
simdat <- sim_mvgam(
  family       = poisson(),
  n_series     = 3L,
  n_timepoints = 120L,
  trend_model  = AR(),
  seed         = 0L
)
head(simdat$data_train)
simdat

# The true smooth of x
plot(f_true ~ x, data = simdat$true_smooths$`s(x)`, type = "l")

# Next: mvgam(y ~ s(x), trend_formula = ~ AR(),
#   data = simdat$data_train, family = poisson())


The smooth terms of a fitted model

Description

Lists every s() and t2() term of every predictor. The predictors are each response's mean, each distributional or non-linear parameter with a formula and the trend. posterior_smooths.mvgam() and conditional_smooths.mvgam() take these labels.

Usage

## S3 method for class 'mvgam'
smooths(x)

smooths(x)

Arguments

x

A fitted mvgam object.

Value

A character vector of term labels, one per term of each predictor, in the order of the panels of conditional_smooths.mvgam(). Empty for a fit without smooths.

Author(s)

Nicholas J Clark

See Also

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), summary.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5) + s(time, k = 6),
             trend_formula = ~ AR(p = 1),
             data = simdat$data_train, family = poisson(),
             chains = 2, silent = 2)

# The labels posterior_smooths() takes
smooths(mod)

# Next, posterior_smooths(mod, smooth = "s(x, k = 5)") draws one of
# them

## End(Not run)


How each species responds to covariates

Description

Gives each species' response to each named covariate, draw by draw, with the posterior probability of its sign. A jsdgam() fit with trait_slopes also gives each trait's effect on those responses, the fourth-corner coefficients. The heatmaps show which species respond positively, which negatively and which the data leave uncertain.

Usage

species_effects(object, ...)

## S3 method for class 'mvgam'
species_effects(
  object,
  variables,
  ...,
  prob_threshold = 0.95,
  probs = c(0.025, 0.975),
  robust = FALSE,
  ndraws = NULL,
  draw_ids = NULL,
  resp = NULL
)

## S3 method for class 'mvgam_species_effects'
summary(object, type = c("species", "traits"), ...)

## S3 method for class 'mvgam_species_effects'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_species_effects'
plot(x, type = c("species", "traits"), supported_only = FALSE, ...)

Arguments

object

A fitted mvgam object of several series.

...

Unused. Anything passed here is refused.

variables

Character vector of the covariates to report, each a column of the data that a formula of the model uses.

prob_threshold

The posterior probability of its sign an effect needs to count as supported, at least 0.5 and below 1. Defaults to 0.95. It sets the sig column of summary() and the effects plot() outlines.

probs

Two probabilities for the lower and upper bounds of the credible interval. Defaults to c(0.025, 0.975).

robust

Logical. TRUE summarises each effect by its median and median absolute deviation. Defaults to FALSE, the mean and the standard deviation.

ndraws, draw_ids

The posterior draws to use, as hindcast.mvgam() takes them. NULL for both uses every draw.

resp

The response to report, needed on a model with several.

type

"species" (the default) for the species by covariate panel, or "traits" for the trait by covariate panel of a trait_slopes fit.

x

An mvgam_species_effects object.

digits

Integer number of significant digits. Defaults to 2.

supported_only

Logical. TRUE leaves blank every effect whose prob_nonzero is at most prob_threshold. Defaults to FALSE.

Details

Species effects. A species' response to a numeric covariate is the average slope of its linear predictor, over the rows the species was fitted to, as marginaleffects::avg_slopes() gives it with type = "link". A linear term gives the species' own coefficient, such as b_env plus b_env:seriessp_2 in y ~ env * series. A smooth or an interaction gives the slope averaged over the species' rows. A smooth that rises and falls can average to a slope near zero. conditional_effects.mvgam() shows its shape. A covariate in trend_formula, including one written with lv_axis(), reaches each species through its loadings. A factor covariate gives one effect per level, its difference from the reference level.

A diri(), multi() or categ() fit gives each species' share through a softmax, which ignores a slope every species shares. Each draw is then centred across the species. An effect is the slope of the species' log share relative to the geometric mean of the shares, the centred log-ratio scale.

An effect is on the link scale, per unit of the covariate. Effects of covariates measured in different units compare better when the covariates are standardised. A covariate that only a distributional formula uses, such as the detection formula of occ(), moves no species' linear predictor and is refused.

Trait effects. trait_slopes = ~ trait in jsdgam() makes each species' response depend on its traits. A trait effect is how far the response moves per unit of the trait, with each species' own deviation held. A linear term gives its coefficient, such as b_env:size. A smooth of the covariate or of the trait gives the effect averaged over the fitted rows. A factor trait gives one effect per level, its difference from the reference level. A covariate of factor_formula reaches no trait. Its trait effects are zero.

Support. prob_nonzero is the larger of the posterior probabilities that an effect is positive and that it is negative. An effect is supported when prob_nonzero exceeds prob_threshold.

Value

An object of class mvgam_species_effects. print() counts the supported positive and negative responses to each covariate. summary() returns a tibble of each effect's estimate, interval and sign probabilities, with sig marking the supported ones. plot() draws a heatmap of species by covariate, or of trait by covariate with type = "traits". The species element holds the summary matrices, ⁠[species, effect]⁠. The draws element holds the ⁠[draws, species, effect]⁠ array. A trait_slopes fit adds a traits element of the same form.

Author(s)

Nicholas J Clark

References

Ovaskainen, O. and Abrego, N. (2020). Joint Species Distribution Modelling: With Applications in R. Cambridge University Press. doi:10.1017/9781108591720

See Also

residual_cor() for the associations the covariates leave, conditional_effects.mvgam() for the shape of an effect, variance_partition() for how much each source moves a species

Examples

## Not run: 
# Detections of 6 species at 80 sites, 4 visits each. Occupancy
# responds to the site covariate `env` and detection to the time of
# day `tod_c`. Two latent factors drive the species associations.
simdat <- sim_closure_unit_data(
  family    = occ(),
  n_species = 6L,
  n_sites   = 80L,
  n_visits  = 4L,
  n_lv      = 2L,
  seed      = 1L
)

# A joint occupancy model. Each species has its own occupancy
# intercept and `env` slope, plus its own detection intercept. Two
# latent factors take up the residual association.
mod <- jsdgam(
  formula        = bf(y ~ series * env, p ~ series + tod_c),
  factor_formula = ~ -1,
  data           = simdat$data_train,
  family         = occ(),
  n_lv           = 2L,
  chains         = 2,
  silent         = 2
)

summary(mod)

# The effect of `env` on the chance of a detection, occupancy times
# detection
conditional_effects(mod)

# Each species' response to env, outlined where its sign is clear
plot(species_effects(mod, variables = "env"))

# The residual correlations among species the factors imply
plot(residual_cor(mod))

# Site scores and species loadings on the two factors
ordinate(mod, rotation = "varimax")

# Expected richness along `env`. The second plot marks the pairs of
# species found together more often than `env` predicts.
gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20))
cm <- community(mod, newdata = gradient)
plot(cm)
plot(cm, type = "cooccurrence")

# The draws, for any contrast: richness at the end of the gradient
# less that at its start
rv <- as_draws_rvars(cm)
rv$richness[20] - rv$richness[1]

# Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo()

## End(Not run)


Calculate measures of latent VAR community stability

Description

Compute reactivity, return rates and contributions of interactions to stationary forecast variance from mvgam models with Vector Autoregressive dynamics.

Usage

stability(object, ...)

## S3 method for class 'mvgam'
stability(
  object,
  groups = NULL,
  ndraws = NULL,
  draw_ids = NULL,
  summary = TRUE,
  probs = c(0.025, 0.975),
  future = FALSE,
  ...
)

## S3 method for class 'mvgam_stability'
summary(object, probs = c(0.025, 0.975), robust = TRUE, bins = 30L, ...)

## S3 method for class 'mvgam_stability_summary'
plot(
  x,
  variables = c("reactivity", "mean_return_rate", "var_return_rate"),
  intervals = FALSE,
  ...
)

## S3 method for class 'mvgam_stability'
plot(
  x,
  variables = c("reactivity", "mean_return_rate", "var_return_rate"),
  bins = 30L,
  ...
)

Arguments

object

An object of class mvgam fitted with a VAR(p = 1) latent process model. For summary(), an mvgam_stability object from stability(summary = FALSE).

...

Unused. Anything passed here is refused.

groups

Hierarchical VAR fits only. The panels to summarise, by name or by index into the levels of gr. The default NULL summarises every panel. A non-hierarchical fit accepts NULL alone.

ndraws

Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws.

draw_ids

Optional integer vector selecting a subset of posterior draw indices to use. NULL (default) uses all draws (subject to ndraws).

summary

Logical. TRUE (the default) returns the posterior median and interval of each metric. FALSE returns the metrics of each draw. plot() draws histograms of either form.

probs

The lower and upper percentiles of the interval reported with the median when summary = TRUE.

future

Logical. When TRUE, the per-draw computation runs under the future::plan() the caller has set. The default sequential plan runs as base lapply() does. plan(multisession, workers = N) splits the draws across N R processes. Without the future package the draws run in turn, with a message.

robust

Logical, for summary(). TRUE (the default) reports the median and median absolute deviation. FALSE reports the mean and standard deviation.

bins

Number of histogram bins, which summary() records for plot().

x

An mvgam_stability object or its summary.

variables

Character vector of the metrics to draw. Defaults to reactivity and the mean and variance return rates. Any column of x can be named.

intervals

Logical, for a summary. TRUE draws each metric as a median and interval. FALSE (the default) draws its binned posterior.

Details

These measures describe how much the lagged interactions among the series contribute to the variability of the system. They also describe how the system responds to a perturbation (Ives et al. 2003). For a latent VAR(1)

x_t \sim \text{MVNormal}(A x_{t - 1}, \Sigma)

the stationary covariance \Sigma_{\infty} solves \Sigma_{\infty} = A \Sigma_{\infty} A^\top + \Sigma. Each posterior draw of A and \Sigma gives one draw of every metric:

The prior on A keeps every draw stationary (Heaps 2023). \Sigma_{\infty} and every metric then exist in every draw.

irf() and fevd() describe the same dynamics as responses to shocks.

Value

A data.frame with the posterior median and interval of each stability metric, or under summary = FALSE an object of class mvgam_stability holding one row of metrics per posterior draw. summary() turns the draws into the summary, one row per metric, or per panel and metric on a hierarchical VAR. plot() draws a histogram of each metric, with a dashed line at zero on the reactivity panel, above which the system amplifies a shock before it decays. A hierarchical VAR draws a median and interval for each panel. A summary plots the histograms from the bins it recorded, or under intervals = TRUE a median and interval.

Author(s)

Nicholas J Clark

References

AR Ives, B Dennis, KL Cottingham & SR Carpenter (2003). Estimating community stability and ecological interactions from time-series data. Ecological Monographs, 73, 301-330.

MG Neubert, H Caswell & AR Solow (2009). Detecting reactivity. Ecology, 90, 2683-2688.

SE Heaps (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics, 32, 74-83.

See Also

irf() and fevd() summarise the same VAR dynamics. The VAR article runs stability() on a plankton community. The hierarchical VAR article reports the metrics for each group of a hierarchical VAR.

Other latent dynamics: active_factors(), compare_loadings(), fevd.mvgam(), irf.mvgam(), ordinate(), posterior_transition_matrix(), residual_cor(), shared_variation()

Examples

## Not run: 
# Ten years of monthly counts of a prey species and its predator.
# Predators suppress the prey a month later. Prey raise the
# predators a month later.
set.seed(2025)
n_months <- 120
A <- rbind(prey     = c(0.6, -0.5),
           predator = c(0.4,  0.5))
z <- matrix(0, n_months, 2)
for (t in 2:n_months) {
  z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35)
}
predator_prey <- data.frame(
  time = rep(seq_len(n_months), 2),
  series = factor(rep(c("prey", "predator"), each = n_months),
                  levels = c("prey", "predator")),
  y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2])))
)
var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(),
                 data = predator_prey, family = poisson(),
                 chains = 2, silent = 2)

## End(Not run)
## Not run: 
# Posterior medians and intervals of the stability metrics
stab <- stability(var_mod)
stab[stab$metric %in% c("reactivity", "mean_return_rate"), ]

# The full posterior of each metric
plot(stability(var_mod, summary = FALSE))

# Next: irf() traces a shock through the system over time

## End(Not run)


Stan program and data from a formula carrying a trend_formula

Description

stancode() and standata() delegate a plain formula to brms. A trend_formula in the same call, or a family mvgam builds such as tweedie() or nmix(), names an mvgam model. These methods then build the mvgam_formula that call describes and generate its program.

Usage

## S3 method for class 'formula'
stancode(object, ...)

## S3 method for class 'bform'
stancode(object, ...)

## S3 method for class 'formula'
standata(object, ...)

## S3 method for class 'bform'
standata(object, ...)

Arguments

object

A formula, or a brmsformula or mvbrmsformula (both of class bform).

...

Arguments for stancode.mvgam_formula or for brms, data and family among them.

Value

A character string of Stan code, or a list of Stan data.

See Also

mvgam_formula, stancode.mvgam_formula, standata.mvgam_formula


Stan code and data of an mvgam model

Description

The Stan program and data list of an mvgam model. For an mvgam_formula() they are generated without fitting, as mvgam() would build them from the same arguments. For an mvgam model they are the ones the model was built with. Pass the two to rstan or cmdstanr to run the model outside mvgam. The program shows how the trend enters the linear predictor.

Usage

## S3 method for class 'mvgam_formula'
stancode(
  object,
  data,
  family = gaussian(),
  prior = NULL,
  data2 = NULL,
  sample_prior = "no",
  knots = NULL,
  drop_unused_levels = TRUE,
  backend = "rstan",
  threads = 1L,
  normalize = TRUE,
  save_model = NULL,
  silent = 1L,
  stanvars = NULL,
  validate = TRUE,
  ...
)

## S3 method for class 'mvgam_formula'
standata(
  object,
  data,
  family = gaussian(),
  prior = NULL,
  data2 = NULL,
  sample_prior = "no",
  knots = NULL,
  drop_unused_levels = TRUE,
  backend = "rstan",
  threads = 1L,
  normalize = TRUE,
  save_model = NULL,
  silent = 1L,
  stanvars = NULL,
  ...
)

## S3 method for class 'mvgam'
stancode(object, ...)

## S3 method for class 'mvgam'
standata(object, ...)

## S3 method for class 'mvgamstancode'
print(x, ...)

Arguments

object

An mvgam_formula(), or an mvgam model fitted or built with run_model = FALSE.

data

A data frame holding every variable the formulas use.

family

A description of the response distribution and link function, given as a family function, a call to one or its name. Supports most brms families, including the ordinal families (brms::cumulative(), brms::sratio(), brms::cratio(), brms::acat()). The brms families needing a separate linear predictor per response category, brms::categorical(), brms::multinomial() and brms::dirichlet(), are refused: use categ(), multi() and diri(), which take the categories in long format and share one latent structure across them. A family whose mean has to stay positive needs a link that keeps it there once a trend enters the linear predictor: pair stats::Gamma(), brms::weibull(), brms::exponential(), brms::frechet() and stats::inverse.gaussian() with link = "log". Their default links leave the mean positive only where the predictor is. A latent trend is centred near zero and reaches negative values, where the likelihood is undefined. mvgam() warns before fitting. brms::lognormal() is the exception: its mu is a log-scale location that takes any sign.

A family written inside a univariate brms::bf() is the model's family, as in brms. In a multivariate model each response may take its own family, in which case name it inside that response's brms::bf(): bf(count ~ x, family = poisson()) + bf(seen ~ x, family = bernoulli()). Passing a list of families to this argument, as brms::brm() allows, is not supported; the family belongs to the response that names it. A single family given here applies to every response that does not name one of its own. Closure-unit and multi-response families (occ(), nmix(), mvn(), mvt(), diri(), multi(), categ()) lay their data out by unit. Each models its response alone and cannot be one response of a multivariate model.

prior

A brmsprior of priors to set, from brms::prior(). get_prior.mvgam_formula() lists the classes.

data2

A named list of objects the model uses that are not variables in data, as in brms::brm().

sample_prior

"no" (the default), "yes" or "only", as in brms::brm().

knots

Optional named list of knot positions for spline terms, used by the observation and trend formulas alike.

drop_unused_levels

Logical. TRUE (the default) drops factor levels without observations.

backend

"rstan" (the default) or "cmdstanr".

threads

Number of threads within each chain. Defaults to 1.

normalize

Logical. TRUE (the default) keeps the normalising constants of the sampling statements.

save_model

File path to write the Stan program to, or NULL (the default) to write nothing.

silent

Integer verbosity, as in brms::brm(). 0 prints Stan's exceptions and progress, 1 (the default) prints progress and 2 prints nothing.

stanvars

Optional brms::stanvar() object of Stan code to add to the program, merged with the code mvgam writes for the trend.

validate

Logical. TRUE (the default) checks the program with the Stan parser. stancode() alone takes it.

...

For an mvgam_formula(), other arguments of mvgam(). A name mvgam() does not take is refused. For an mvgam model, unused. Anything passed is refused.

x

An mvgamstancode object.

Value

stancode() returns the Stan program as a character string of class mvgamstancode, which prints line by line. standata() returns the named list of Stan data.

See Also

mvgam(), mvgam_formula(), get_prior.mvgam_formula(). methods_md() writes the same model as equations for a methods section.

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), update.mvgam()

Examples

set.seed(1)
dat <- sim_mvgam(family = poisson(), n_series = 2L,
                 n_timepoints = 40L, trend_model = AR())$data_train
mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1))

# The program of the model, before any fitting. The trend's
# parameters carry a `_trend` suffix.
code <- stancode(mf, data = dat, family = poisson())
code

# The data passed to that program: 60 observations of 2 series
# over 30 time points
sdata <- standata(mf, data = dat, family = poisson())
sdata[c("N", "N_series_trend", "N_time_trend")]

# Next, fit the model with mvgam(), which compiles this program


Summary of mvgam model fits

Description

Provides posterior summary statistics for mvgam model parameters, organised by category (fixed effects, smooth terms, family parameters, trend parameters and factor loadings).

Usage

## S3 method for class 'mvgam'
summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...)

## S3 method for class 'mvgam_summary'
print(x, digits = 2, ...)

Arguments

object

An object of class mvgam.

probs

Two probabilities for the lower and upper bounds of the credible interval. Default c(0.025, 0.975), a 95% interval.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

matrices

Logical; if TRUE, also print every cell of the matrices a correlated, VAR or hierarchical trend derives from its sampled parameters (Phi_trend, Sigma_trend, Omega_trend, Phi_group_trend, Sigma_group_trend). The default FALSE prints the sampled parameters alone, among them sigma_trend, Amu_trend, Aomega_trend and alpha_cor_trend. posterior_transition_matrix() and residual_cor() summarise the matrices a cell at a time.

...

Unused. Anything passed here is refused.

x

An mvgam_summary object.

digits

Integer number of decimal places. Defaults to 2.

Details

Each block has the columns:

Estimate

Posterior mean, or median with robust = TRUE.

Est.Error

Posterior standard deviation, or MAD with robust = TRUE.

l-95% CI, u-95% CI

Credible interval bounds at probs, labelled by its coverage.

Rhat

Potential scale reduction factor on split chains, 1 at convergence.

Bulk_ESS, Tail_ESS

Bulk and tail effective sample sizes.

Vehtari et al. (2021) recommend an Rhat below 1.01 and bulk and tail effective sample sizes above 400 before a summary is used. A fit should also have no divergent transitions. The section 'Checking a fit' of mvgam_diagnostics says what to do when one of these checks fails.

Value

An object of class mvgam_summary. Each block is a data frame of the columns below, one row per parameter, named as print() shows it. A block is absent when the model has no such parameter. The observation model's blocks are:

smooth

Smoothing standard deviations, one row per penalty of each smooth. The basis coefficients are available by name from as_draws(object, variable = "^s_", regex = TRUE).

gp

Gaussian-process marginal standard deviations and length-scales.

random

Group-level standard deviations and correlations, as a list of tables named by grouping factor. ngrps gives each factor's number of levels. ranef() gives the per-level effects.

fixed

Regression coefficients, those of every distributional parameter given a formula among them.

mo

The simplex of each monotonic effect.

spec

Family parameters without a formula of their own, such as sigma or shape.

The trend model's blocks take the same names with the prefix trend_, joined by trend_spec for the trend's dynamics, loadings for the factor loadings and loadings_prior for the hyperparameters of their prior. The formula, family, draw counts and data dimensions are stored with them. print() sets the blocks out under their headings, followed by the sampler diagnostics and suggested next steps.

References

Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: an improved Rhat for assessing convergence of MCMC. Bayesian Analysis, 16(2):667-718. doi:10.1214/20-BA1221

See Also

mvgam_diagnostics checks convergence. pp_check.mvgam() checks the fit against the data. how_to_cite() drafts a methods paragraph for the model. methods_md() writes its equations, glossary and priors. mcmc_plot.mvgam() plots the draws of these parameters.

Other posterior summaries: VarCorr.mvgam(), bibtex(), how_to_cite.mvgam(), hypothesis.mvgam(), index-mvgam, mcmc_plot.mvgam(), methods_md(), mvgam_draws, pairs.mvgam(), posterior_interval.mvgam(), ranef.mvgam(), smooths.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data = simdat$data_train,
              family = poisson(),
              chains = 2, silent = 2)

summary(mod)

# Each block is a data frame, such as the trend's dynamics
round(summary(mod)$trend_spec, 2)

# Next: pp_check(mod) compares draws from the model with the data

## End(Not run)


Summary of a fit pooled over imputations

Description

The summary of a fit from mvgam_multiple(). The estimates come from the pooled draws. Chains from different imputations sample different posteriors, which raises the R-hat of the pooled chains. Each parameter's Rhat is its largest over the imputation fits instead. Bulk_ESS and Tail_ESS are the sums over those fits. A table gives each fit's largest R-hat and smallest ESS over its parameters.

Usage

## S3 method for class 'mvgam_pooled'
summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...)

## S3 method for class 'mvgam_pooled_summary'
print(x, digits = 2, ...)

Arguments

object

A fit of class mvgam_pooled.

probs

Two probabilities for the lower and upper bounds of the credible interval. Default c(0.025, 0.975), a 95% interval.

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

matrices

Logical; if TRUE, also print every cell of the matrices a correlated, VAR or hierarchical trend derives from its sampled parameters (Phi_trend, Sigma_trend, Omega_trend, Phi_group_trend, Sigma_group_trend). The default FALSE prints the sampled parameters alone, among them sigma_trend, Amu_trend, Aomega_trend and alpha_cor_trend. posterior_transition_matrix() and residual_cor() summarise the matrices a cell at a time.

...

Unused. Anything passed here is refused.

x

An object of class mvgam_pooled_summary.

digits

Integer number of decimal places to print.

Value

summary() returns an object of class c("mvgam_pooled_summary", "mvgam_summary"). It holds the blocks of summary.mvgam() and mi_diagnostics, a list of the number of imputations, the draws per imputation and the per-imputation convergence table. print() returns x invisibly.

See Also

mvgam_multiple(), summary.mvgam()


Model terms for a fitted mvgam object

Description

terms() reports a model's structure to a caller that does not know its class. model.frame() is the accessor usually paired with it. The object holds the model's responses on the left and the covariates of both submodels on the right. stats::terms() has no meaning for the bar syntax of group-level terms. insight::find_random() returns those.

Usage

## S3 method for class 'mvgam'
terms(x, ...)

Arguments

x

A fitted mvgam object.

...

Unused. Anything passed here is refused.

Value

An object of class terms.


Tidy an mvgam object's parameter posteriors

Description

Posterior summaries of the parameters of a fitted mvgam model, as a tibble with the columns of broom.mixed: term, estimate, std.error, conf.low and conf.high. A type column assigns each parameter to the observation model or the trend.

Usage

## S3 method for class 'mvgam'
tidy(
  x,
  effects = "all",
  robust = FALSE,
  conf.int = TRUE,
  conf.level = 0.95,
  rhat = FALSE,
  ess = FALSE,
  ...
)

Arguments

x

A fitted mvgam object.

effects

"all" (the default) for every parameter, or one of "fixed", "ran_pars" and "ran_vals" for the categories above, as in broom.mixed::tidy.brmsfit().

robust

Logical. If FALSE (the default), uses mean and standard deviation for summaries. If TRUE, uses median and median absolute deviation (MAD).

conf.int

Logical. If TRUE (the default), include conf.low and conf.high posterior quantile columns.

conf.level

Numeric. Probability covered by the credible interval reported in conf.low / conf.high. Defaults to 0.95.

rhat

Logical. If TRUE, add a rhat column with posterior::rhat() values.

ess

Logical. If TRUE, add an ess_bulk column with posterior::ess_bulk() values.

...

Unused. Anything passed here is refused.

Details

The type column places every parameter into one of the following categories, each with the effects class it belongs to:

Fixed-effect terms take the names fixef.mvgam() gives them, as broom.mixed::tidy.brmsfit() names them: b_x is x and b_sigma_x is sigma_x. Every other term keeps the name variables.mvgam() lists. brms samples a centred intercept and transforms it to the intercept on the data's scale. The table reports the coefficient once, as Intercept.

Value

A tibble with one row per parameter and the columns term, type, estimate and std.error. conf.int = TRUE adds conf.low and conf.high. rhat and ess add rhat and ess_bulk.

See Also

Other tidiers: augment.mvgam(), glance.mvgam()

Examples

## Not run: 
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                     n_timepoints = 120L, trend_model = AR())
mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1),
              data    = simdat$data_train,
              family  = poisson(),
              chains  = 2, silent = 2)

# One row per parameter, with broom's column names
td <- tidy(mod)
td

# The `type` column separates the trend's parameters from the
# observation model's
td[td$type == "trend_model_param", ]

# The fixed effects alone, with convergence diagnostics
tidy(mod, effects = "fixed", rhat = TRUE, ess = TRUE)

# Next, augment() adds fitted values and residuals to the data

## End(Not run)


Trait-mediated responses for jsdgam()

Description

Internal helpers that expand formula and trait_slopes into the fourth-corner model

Details

\beta_{s,k} = \gamma_{0,k} + \sum_l T_{s,l}\, \gamma_{l,k} + \epsilon_{s,k}

where each term k of formula takes a shared effect, an effect of each trait l and a species deviation. The expansion adds terms to formula and leaves its own terms as written:

formula = y ~ env + s(x) trait_slopes = ~ size

becomes

y ~ env + s(x) + size + env:size + s(x, by = size) + (1 + env | sp | series) + s(x, by = series, m = 1)

The ⁠|sp|⁠ tag correlates the species deviations of the intercept and the linear terms under one LKJ prior. A smooth's species deviation is a smooth per species penalised towards a flat line (the "GI" model of Pedersen et al. 2019). species_effects() reports the species' responses and the trait effects.

References

Pedersen, E. J., Miller, D. L., Simpson, G. L. and Ross, N. (2019). Hierarchical generalized additive models in ecology: an introduction with mgcv. PeerJ 7:e6876. doi:10.7717/peerj.6876


Tweedie compound Poisson-gamma family for mvgam

Description

The Tweedie distribution with power mtheta between 1 and 2, the compound Poisson-gamma. It models non-negative continuous data with a point mass at zero, such as catch per unit effort, rainfall or biomass. A Poisson number of events each contributes a Gamma amount. The variance is mphi * mu^mtheta.

Usage

tweedie(M = 30L)

Arguments

M

Positive integer number of series terms in the Stan log density. Defaults to 30L. The cost grows linearly in M. Too small a value biases the likelihood down and the posteriors of mphi and mtheta with it.

Details

The family has three distributional parameters:

mu

The mean, on a fixed log link. The compound construction needs mu > 0, which an identity link driven by a latent trend cannot guarantee.

mphi

The dispersion, on a log link.

mtheta

The power, bounded to ⁠[1.001, 1.999]⁠. Near 1 the Poisson rate ⁠mu^(2 - mtheta) / ((2 - mtheta) mphi)⁠ and near 2 the Gamma shape (2 - mtheta) / (mtheta - 1) leave floating-point range.

The latent trend enters through mu. mphi and mtheta are scalars by default. A formula such as bf(y ~ x, mphi ~ site) gives the dispersion its own linear predictor on the log scale, whose intercept takes a student_t(3, 0, 2.5) prior. mtheta takes no formula.

mu, mphi and mtheta trade off along Var[Y] = mphi * mu^mtheta. Data that weakly separate Poisson-like from Gamma-like tails leave a ridge in their joint posterior. An informative prior such as prior(normal(1.5, 0.3), class = mtheta) resolves it.

The Stan log density sums M terms of the compound series for each non-zero observation (Dunn and Smyth 2005). The terms past M are negligible when M is well above the Poisson rate lambda, which grows as mtheta approaches 2 or mphi approaches 0. Raise M when check_tweedie_truncation() reports a rate near it. log_lik() and posterior_predict() use mgcv::ldTweedie() and mgcv::rTweedie().

The Stan code adapts the custom_family of the Australian Institute of Marine Science (2023), which uses the decomposition of Spinkney (2020).

Value

A brms::customfamily object for mvgam(family = ).

References

Australian Institute of Marine Science (2023). open-AIMS/tweedie: a brms custom_family implementation of the Tweedie compound Poisson-gamma distribution. GitHub, https://github.com/open-AIMS/tweedie. MIT licence.

Spinkney (2020). Tweedie likelihood (compound Poisson-gamma) in Stan. Stan Discourse, https://discourse.mc-stan.org/t/tweedie-likelihood-compound-poisson-gamma-in-stan/14636

Dunn, P. K., & Smyth, G. K. (2005). Series evaluation of Tweedie exponential dispersion model densities. Statistics and Computing, 15(4), 267-280. doi:10.1007/s11222-005-4070-y

Jorgensen, B. (1987). Exponential dispersion models. Journal of the Royal Statistical Society: Series B, 49(2), 127-162. doi:10.1111/j.2517-6161.1987.tb01685.x

See Also

Other observation families: beta_nb(), categ(), com_binomial(), diri(), multi(), mvgam_families, mvn(), mvt(), nmix(), occ()

Examples

## Not run: 
set.seed(3)
simdat <- sim_mvgam(family = tweedie(), n_series = 1L,
                    n_timepoints = 120L, trend_model = AR())
mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1),
  data          = simdat$data_train,
  family        = tweedie(),
  chains        = 2,
  silent        = 2
)

# The dispersion and power
mcmc_plot(mod, variable = c("mphi", "mtheta"), type = "areas")

# The share of zeros the model predicts against the share observed
prop_zero <- function(y) mean(y == 0)
pp_check(mod, type = "stat", stat = "prop_zero", binwidth = 0.02)

# Next: check_tweedie_truncation(mod) checks the series length M

## End(Not run)


Update a fitted mvgam model

Description

Refit a fitted mvgam object with new data, an updated formula, new priors, different sampler settings or any other argument mvgam() accepts. The signature follows brms::update.brmsfit().

Usage

## S3 method for class 'mvgam'
update(object, formula. = NULL, newdata = NULL, recompile = NULL, ...)

Arguments

object

A fitted mvgam object.

formula.

A new observation formula, or an update to the fitted one such as ~ . + new_term. NULL (the default) keeps object$formula. stats::update.formula() applies the update. ~ . + z, ~ . - z, y2 ~ x and . ~ . all work.

newdata

An optional new training data frame. NULL (the default) keeps object$data. A data argument in ... is an error.

recompile

Optional logical. NULL (the default) and TRUE refit through mvgam(). Both backends cache compiled models by their Stan code. A refit with unchanged code skips compilation. FALSE builds the new Stan code first and compares it with object$stancode. A difference is an error. A refit that passes the check compiles nothing.

...

Any other argument mvgam() accepts, or jsdgam() for a jsdgam fit (e.g. trend_formula, family, prior, chains, iter, warmup, cores, threads, algorithm, backend, silent, seed, init, control). Each value overrides the one inherited from object. A prior joins the priors the original fit set, as Details describes.

Details

Every mvgam() argument comes from object unless ... overrides it. update(fit, iter = 4000) keeps the original formula, data, family, trend, prior and backend. Only the iteration count changes.

Sampler settings follow brms::update.brmsfit(). chains, iter, warmup, thin and control carry over when the refit keeps the original algorithm. control also needs the original backend. A new iter without a warmup takes the default warmup of iter / 2. control merges entry by entry: update(fit, adapt_delta = 0.99) keeps the original max_treedepth.

New training data passed as newdata keeps the fit's held-out data when that lies after the new training times. Held-out data overlapping them is dropped with a message.

A refit reuses the fitted prior table. The adaptive priors of brms, such as the Intercept prior centred on the response, keep the constants of the original fit. Because the constants stay fixed, a refit on a different newdata window has the same Stan code and reuses the compiled model. lfo_cv() and other workflows that refit many times then repeat only the sampling. An inherited row for a parameter the refit lacks, such as the smooth of a dropped term, is left out of the refit. A prior passed to update() joins the priors the user set on the original fit, as in brms::update.brmsfit(). A new row replaces an old one for the same parameter:

new_priors <- c(
  prior(std_normal(), class = "b"),
  prior(exponential(1), class = "sigma")
)
refit <- update(mod, prior = new_priors)

A prior change that alters the Stan code recompiles the model. With recompile = FALSE it is an error. stancode(refit) shows the model the refit compiled.

Multivariate fits take a complete new formula as formula.. A formula update written with . is refused, as brms refuses it.

A jsdgam() fit refits through jsdgam() with the arguments the original call evaluated, including factor_formula, n_lv, traits, trait_slopes and phylo. ... overrides any of them.

update() refuses multiple-imputation fits from mvgam_multiple(combine = TRUE). Refit each imputation with mvgam() and pool them again.

Value

A refit mvgam object.

Author(s)

Nicholas J Clark

See Also

loo.mvgam() and loo_compare.mvgam() compare a refit with the original. stancode.mvgam() shows the compiled model. The forecast evaluation article compares competing models by their forecasts.

Other model fitting: check_newdata(), jsdgam(), mvgam(), mvgam_data(), mvgam_multiple(), pivot_detection_array(), pivot_species_matrix(), print.mvgam_formula(), series_to_mvgam(), stancode.mvgam_formula()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# Swap the family for a negative binomial. The formula, priors, data
# and sampler settings carry over
upd <- update(mod, family = negbinomial())

# Compare the two fits by approximate leave-one-out cross-validation.
# The better model comes first, with elpd_diff = 0. An elpd_diff
# smaller than 4 in size means the two predict about equally well.
# p_worse is the probability that a model predicts worse than the best
loo_compare(mod, upd)

# A change of sampler settings alone reuses the compiled model
longer <- update(mod, iter = 3000, recompile = FALSE)

## End(Not run)


Partition each series' predictor variance among its sources

Description

Shows what moves each series: its covariates, the latent factors it shares with other series, its own trend, its season and, in a detection model, its detection process. Each source's share of the variance is computed draw by draw, which gives every share a posterior distribution.

Usage

variance_partition(object, ...)

## S3 method for class 'mvgam'
variance_partition(
  object,
  ...,
  ndraws = NULL,
  draw_ids = NULL,
  scale = c("link", "expected"),
  resp = NULL
)

## S3 method for class 'mvgam_variance_partition'
summary(object, probs = c(0.025, 0.975), ...)

## S3 method for class 'mvgam_variance_partition'
print(x, digits = 2L, ...)

## S3 method for class 'mvgam_variance_partition'
plot(x, ...)

Arguments

object

A fitted mvgam object.

...

Unused. Anything passed here is refused.

ndraws, draw_ids

The posterior draws to use, as hindcast.mvgam() takes them. NULL for both uses every draw.

scale

"link" (the default) partitions the predictor, where its parts add. "expected" partitions the expected value: a source's values are the expected value less the expected value without that source.

resp

The response to report, needed on a model with several.

probs

Interval probabilities of the table. Defaults to c(0.025, 0.975).

x

An mvgam_variance_partition object from variance_partition().

digits

Number of decimal places to print. Defaults to 2.

Details

Sources. Each source is a sum of parts of the fitted predictor:

environment

every term of the observation and trend formulas, group-level terms included

associations

the latent factors, shared across series

trend

a latent state belonging to its series alone

season

the season of an LLT() trend

detection

the terms of an occ() or nmix() detection formula, p ~ ..., on that formula's own link scale. It joins scale = "link" alone.

A source a model lacks or that never varies is left out.

A diri(), multi() or categ() fit gives each species' share through a softmax, which ignores a shift every species at a site shares. Each source is centred across the species at each site, the centred log-ratio scale. A covariate with one slope for every species then moves no share and is left out.

Under a non-linear link, scale = "expected" holds the other sources at their fitted values. Its sources then interact, as a covariate's effect on a count grows with the level.

Shares. A source's share is the variance of its values over the fitted rows of a series, divided by the sum of those variances across sources. Covariances between sources are left out. They would give a negative share to a source that offsets another. Observation noise is left out too: the shares describe the predictor, on a scale every family has. A series whose predictor never moves has no share.

A series row reports what moves that series over its own rows. An effect that differs only between series, such as a covariate measured once per site, has no variance there. The community row pools every row and counts those effects.

Value

An object of class mvgam_variance_partition. print() gives the mean share of each source by series. summary() returns a tibble of each share's median and interval. plot() draws one stacked bar per series and one for the community.

Author(s)

Nicholas J Clark

See Also

residual_cor() for the associations between series, seasonality() for the season, bayes_R2() for the share of the response's variance the predictor explains, forecast_uncertainty() for the variance of a forecast

Examples

## Not run: 
set.seed(4)
simdat <- sim_mvgam(family = poisson(), n_series = 4L,
                    n_timepoints = 80L, trend_model = AR())
mod <- mvgam(
  y ~ s(x, k = 5),
  trend_formula = ~ AR(p = 1, n_lv = 2),
  data = simdat$data_train,
  family = poisson(),
  chains = 2,
  silent = 2
)

# The covariate's share against the shared factors', by series
vp <- variance_partition(mod)
vp
plot(vp)

# Each share with its posterior interval
summary(vp)

## End(Not run)


Widely applicable information criterion for mvgam models

Description

Passes the pointwise log likelihood of log_lik.mvgam() to loo::waic(). loo.mvgam() estimates the same ELPD by PSIS and reports Pareto k diagnostics that say when to distrust it. Vehtari et al. (2017) recommend it over WAIC.

Usage

## S3 method for class 'mvgam'
waic(
  x,
  ...,
  compare = TRUE,
  resp = NULL,
  pointwise = FALSE,
  model_names = NULL,
  incl_autocor = TRUE,
  incl_dynamics = NULL,
  by_series = FALSE
)

Arguments

x

A fitted mvgam or jsdgam object.

...

Further arguments to log_lik.mvgam(), such as ndraws.

compare, resp, pointwise, model_names

The arguments of brms::waic.brmsfit. resp scopes a multivariate fit to one response. Supplying one of the others raises an error. loo_compare() ranks several waic() results.

incl_autocor

Logical, default TRUE. Passed to log_lik.mvgam(). TRUE scores each observation under the latent trend state the model inferred at that time. The ELPD then describes the series that was observed. FALSE scores the covariate part of the model alone.

incl_dynamics

Deprecated alias for incl_autocor.

by_series

Logical, default FALSE. TRUE returns a data frame with one row per series and columns series, elpd, se_elpd, p and n_obs, as spOccupancy::waicOcc(by.sp = TRUE) ranks species. An occupancy or N-mixture fit is scored per site, each site counted in its species.

Value

A waic object (see loo::waic()), or with by_series = TRUE a data frame of per-series estimates.

References

Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4

See Also

loo.mvgam() estimates the same ELPD by PSIS. lfo_cv.mvgam() scores forecasts from rolling origins. The forecast evaluation article compares models by approximate and exact cross-validation.

Other model comparison: bridge_sampler.mvgam(), compare_elpds(), kfold.mvgam(), lfo_cv.mvgam(), log_lik.mvgam(), loo.mvgam(), loo_compare.mvgam_lfo(), mvgam_loo_extras, posterior_average.mvgam()

Examples

## Not run: 
# A Poisson GAM without a latent trend. PSIS approximates each
# held-out count of such a model well (see Details of ?loo.mvgam)
set.seed(13)
simdat <- sim_mvgam(family = poisson(), n_series = 1L,
                    n_timepoints = 120L, trend_model = "None")
mod <- mvgam(y ~ s(x), data = simdat$data_train,
             family = poisson(), chains = 2, silent = 2)

## End(Not run)
## Not run: 
# The WAIC estimate of the ELPD, with its effective number of
# parameters p_waic. A p_waic above 0.4 for any observation raises
# a warning that recommends loo()
waic(mod)

# The PSIS estimate of the same ELPD. Its Pareto k diagnostics mark
# the observations it estimates poorly
loo(mod)

# Next, loo_compare() ranks several models by either estimate

## End(Not run)