# Fitting a MAR(1) model to community time series
# https://tidyecology.com/posts/fitting-a-mar1-model/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-08

## ---- setup ----
library(ggplot2)
library(grid)

te_ink    <- "#16241d"
te_forest <- "#275139"
te_gold   <- "#c9b458"
te_rust   <- "#b5534e"
te_sage   <- "#93a87f"
te_line   <- "#dad9ca"
te_muted  <- "#5d6b61"

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      text             = element_text(colour = te_ink),
      plot.title       = element_text(face = "bold", size = rel(1.02), colour = te_ink),
      plot.subtitle    = element_text(colour = te_muted, size = rel(0.88)),
      axis.title       = element_text(colour = te_ink, size = rel(0.92)),
      axis.text        = element_text(colour = te_muted, size = rel(0.82)),
      panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
      panel.grid.minor = element_blank(),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
      legend.position  = "bottom",
      legend.title     = element_text(size = rel(0.82)),
      legend.text      = element_text(size = rel(0.78)),
      legend.key.size  = unit(0.8, "lines")
    )
}

two_panel <- function(p1, p2) {
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1, 2)))
  print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(p2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}

## ---- dgp ----
Btrue <- matrix(c( 0.50, -0.10, -0.35,  0.00,
                  -0.15,  0.60,  0.00,  0.00,
                   0.30,  0.00,  0.45, -0.30,
                   0.00,  0.00,  0.25,  0.55), 4, 4, byrow = TRUE)
Atrue <- c(1.20, 0.90, 0.40, 0.30)
Strue <- matrix(c(0.09, 0.03, 0,    0,
                  0.03, 0.09, 0,    0,
                  0,    0,    0.04, 0.01,
                  0,    0,    0.01, 0.04), 4, 4, byrow = TRUE)
p <- 4

sim_mar1 <- function(n, A, B, S, seed, burn = 200) {
  set.seed(seed)
  p <- length(A)
  L <- chol(S)
  x <- solve(diag(p) - B, A)          # start at the stationary mean
  X <- matrix(0, n, p)
  for (t in seq_len(burn + n)) {
    x <- A + B %*% x + as.vector(rnorm(p) %*% L)
    if (t > burn) X[t - burn, ] <- x
  }
  X
}

X <- sim_mar1(60, Atrue, Btrue, Strue, seed = 4268)

## ---- fig-series ----
series <- data.frame(
  time    = rep(seq_len(nrow(X)), 4),
  logabun = as.vector(X),
  species = factor(rep(paste("Species", 1:4), each = nrow(X)))
)

ggplot(series, aes(time, logabun, colour = species)) +
  geom_line(linewidth = 0.55) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold, te_sage)) +
  labs(title = "A four-species community on the log scale",
       subtitle = "Simulated MAR(1) process, 60 time steps",
       x = "Time step", y = "Log abundance", colour = NULL) +
  theme_te()

## ---- fit ----
mar1_cls <- function(X) {
  n  <- nrow(X)
  Y  <- X[-1, , drop = FALSE]           # response: steps 2..n
  D  <- cbind(1, X[-n, , drop = FALSE]) # design: intercept + steps 1..n-1
  cf <- solve(crossprod(D), crossprod(D, Y))
  E  <- Y - D %*% cf
  list(A = cf[1, ], B = t(cf[-1, , drop = FALSE]),
       Sigma = crossprod(E) / nrow(Y), E = E)
}

fit <- mar1_cls(X)
round(fit$B, 3)

## ---- se ----
mar1_se <- function(X) {
  n <- nrow(X); pp <- ncol(X)
  Y <- X[-1, , drop = FALSE]
  D <- cbind(1, X[-n, , drop = FALSE])
  XtXi <- solve(crossprod(D))
  q <- nrow(Y); k <- ncol(D)
  SE <- matrix(0, pp, pp)
  for (i in 1:pp) {
    r <- Y[, i] - D %*% (XtXi %*% crossprod(D, Y[, i]))
    SE[i, ] <- sqrt(sum(r^2) / (q - k) * diag(XtXi))[-1]
  }
  SE
}

SE <- mar1_se(X)
round(SE, 3)

## ---- cls-is-ols ----
lmB <- t(sapply(1:p, function(i) coef(lm(X[-1, i] ~ X[-nrow(X), ]))[-1]))
max(abs(fit$B - lmB))

## ---- consistency ----
Xlong <- sim_mar1(4000, Atrue, Btrue, Strue, seed = 4001)
rbind(true = diag(Btrue), n60 = diag(fit$B), n4000 = diag(mar1_cls(Xlong)$B))

## ---- fig-recovery ----
stat_V <- function(B, S) {
  matrix(solve(diag(nrow(B)^2) - kronecker(B, B), as.vector(S)), nrow(B), nrow(B))
}
naive_target <- function(B, S) { V <- stat_V(B, S); diag(B %*% V) / diag(V) }

Scol <- Strue; Scol[1, 2] <- Scol[2, 1] <- 0.087

rec <- data.frame(
  true = as.vector(Btrue), est = as.vector(fit$B), se = as.vector(SE),
  kind = ifelse(as.vector(diag(4)) == 1, "diagonal", "off-diagonal")
)

p1 <- ggplot(rec, aes(true, est, colour = kind)) +
  geom_abline(slope = 1, intercept = 0, colour = te_line, linewidth = 0.7) +
  geom_hline(yintercept = 0, colour = te_line, linewidth = 0.3, linetype = 3) +
  geom_errorbar(aes(ymin = est - 2 * se, ymax = est + 2 * se), width = 0, linewidth = 0.4) +
  geom_point(size = 2) +
  scale_colour_manual(values = c(diagonal = te_forest, `off-diagonal` = te_rust)) +
  labs(title = "Estimated against true", subtitle = "n = 60, two standard errors",
       x = "True coefficient", y = "Estimate", colour = NULL) +
  theme_te(11)

nv <- data.frame(
  species = rep(paste0("b", 1:4, 1:4), 3),
  value   = c(diag(Btrue), naive_target(Btrue, Strue), naive_target(Btrue, Scol)),
  what    = rep(c("true b_ii", "naive target, baseline", "naive target, shared"), each = 4)
)
nv$what <- factor(nv$what, levels = c("true b_ii", "naive target, baseline", "naive target, shared"))

p2 <- ggplot(nv, aes(value, species, colour = what, shape = what)) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c(te_ink, te_forest, te_rust)) +
  scale_shape_manual(values = c(16, 17, 15)) +
  labs(title = "What a per-species AR(1) is aiming at",
       subtitle = "Same B, two environments",
       x = "Coefficient", y = NULL, colour = NULL, shape = NULL) +
  theme_te(11) +
  guides(colour = guide_legend(ncol = 1), shape = guide_legend(ncol = 1))

two_panel(p1, p2)

## ---- naive-target ----
rbind(`true b_ii`  = diag(Btrue),
      `naive aims at` = naive_target(Btrue, Strue))

## ---- naive-shared ----
Va <- stat_V(Btrue, Strue); Vc <- stat_V(Btrue, Scol)
rbind(`true b_ii`  = diag(Btrue),
      baseline     = naive_target(Btrue, Strue),
      shared       = naive_target(Btrue, Scol))
c(cor_baseline = Va[1, 2] / sqrt(Va[1, 1] * Va[2, 2]),
  cor_shared   = Vc[1, 2] / sqrt(Vc[1, 1] * Vc[2, 2]))

## ---- naive-stability ----
c(naive_baseline = max(Mod(eigen(diag(naive_target(Btrue, Strue)))$values)),
  naive_shared   = max(Mod(eigen(diag(naive_target(Btrue, Scol)))$values)),
  truth          = max(Mod(eigen(Btrue)$values)))
