params <-
list(EVAL = TRUE)

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

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

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

## ----simulate-----------------------------------------------------------------
set.seed(3)

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

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

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

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

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

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

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

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

## ----summary-known------------------------------------------------------------
summary(fit_known)

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

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

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

## ----summary-free-------------------------------------------------------------
summary(fit_free)

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

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

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

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

## ----active-free--------------------------------------------------------------
af_free <- active_factors(fit_free)
af_free

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

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

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

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

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

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

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

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

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

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

