# Checking a MAR(1) model
# https://tidyecology.com/posts/checking-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-14

## ---- 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))
}

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); 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
}
mar1_cls <- function(X) {
  n <- nrow(X); Y <- X[-1, , drop = FALSE]; D <- cbind(1, X[-n, , drop = FALSE])
  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)
}

## ---- attenuation ----
tau_grid <- c(0, 0.02, 0.05, 0.10, 0.20)

att <- do.call(rbind, lapply(tau_grid, function(tau2) {
  Bh <- array(0, c(300, p, p)); rr <- dt <- numeric(300)
  for (m in 1:300) {
    Xm <- sim_mar1(60, Atrue, Btrue, Strue, seed = 7000 + m)
    set.seed(107000 + m)
    B <- mar1_cls(Xm + matrix(rnorm(60 * p, 0, sqrt(tau2)), 60, p))$B
    Bh[m, , ] <- B
    rr[m] <- max(Mod(eigen(B)$values))
    dt[m] <- abs(det(B))^(2 / p)
  }
  Bm <- apply(Bh, c(2, 3), mean)
  data.frame(tau2 = tau2,
             mean_diag = mean(diag(Bm)),
             pct_of_truth = 100 * mean(diag(Bm)) / mean(diag(Btrue)),
             return_rate = mean(rr),
             det_index = mean(dt))
}))
round(att, 4)

## ---- fig-attenuation ----
p1 <- ggplot(att, aes(tau2, mean_diag)) +
  geom_hline(yintercept = mean(diag(Btrue)), colour = te_ink, linetype = 2, linewidth = 0.5) +
  annotate("text", x = 0.11, y = mean(diag(Btrue)) + 0.018, label = "true mean b_ii",
           colour = te_ink, size = 3) +
  geom_line(colour = te_rust, linewidth = 0.8) +
  geom_point(colour = te_rust, size = 2.2) +
  ylim(0, 0.58) +
  labs(title = "The interaction matrix shrinks",
       subtitle = "300 refits per level, n = 60",
       x = "Observation error variance", y = "Mean estimated diagonal") +
  theme_te(11)

met <- rbind(data.frame(tau2 = att$tau2, v = att$return_rate, w = "return rate",
                        truth = max(Mod(eigen(Btrue)$values))),
             data.frame(tau2 = att$tau2, v = att$det_index, w = "|det B|^(2/p)",
                        truth = abs(det(Btrue))^(2 / p)))

p2 <- ggplot(met, aes(tau2, v, colour = w)) +
  geom_hline(aes(yintercept = truth, colour = w), linetype = 2, linewidth = 0.5) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.2) +
  scale_colour_manual(values = c(`return rate` = te_forest, `|det B|^(2/p)` = te_gold)) +
  labs(title = "So does every metric built on it",
       subtitle = "Dashes are the true values",
       x = "Observation error variance", y = "Metric", colour = NULL) +
  theme_te(11)

two_panel(p1, p2)

## ---- ljung-box ----
lb <- do.call(rbind, lapply(c(0, 0.05, 0.20), function(tau2) {
  rej <- matrix(FALSE, 400, p)
  for (m in 1:400) {
    Xt <- sim_mar1(60, Atrue, Btrue, Strue, seed = 300000 + m)
    set.seed(600000 + m)
    E <- mar1_cls(Xt + matrix(rnorm(60 * p, 0, sqrt(tau2)), 60, p))$E
    rej[m, ] <- sapply(1:p, function(i) Box.test(E[, i], lag = 5, type = "Ljung-Box")$p.value < 0.05)
  }
  data.frame(tau2 = tau2, sp1 = mean(rej[, 1]), sp2 = mean(rej[, 2]),
             sp3 = mean(rej[, 3]), sp4 = mean(rej[, 4]), any = mean(apply(rej, 1, any)))
}))
round(lb, 3)

## ---- fig-silence ----
lbl <- do.call(rbind, lapply(1:nrow(lb), function(i) {
  data.frame(tau2 = factor(sprintf("%.2f", lb$tau2[i])),
             species = paste("Species", 1:4),
             rate = as.numeric(lb[i, c("sp1", "sp2", "sp3", "sp4")]))
}))

p1 <- ggplot(lbl, aes(tau2, rate, fill = species)) +
  geom_col(position = position_dodge(0.8), width = 0.7) +
  geom_hline(yintercept = 0.05, colour = te_rust, linetype = 2, linewidth = 0.7) +
  annotate("text", x = 0.7, y = 0.062, label = "nominal", colour = te_rust, size = 3) +
  scale_fill_manual(values = c(te_forest, te_sage, te_gold, te_muted)) +
  ylim(0, 0.1) +
  labs(title = "Ljung-Box, lag 5", subtitle = "400 replicates per level",
       x = "Observation error variance", y = "Rejection rate", fill = NULL) +
  theme_te(11)

cmp <- rbind(
  data.frame(tau2 = lb$tau2, v = lb$any, w = "diagnostic fires (any species)"),
  data.frame(tau2 = att$tau2[c(1, 3, 5)], v = att$pct_of_truth[c(1, 3, 5)] / 100,
             w = "interaction strength retained")
)

p2 <- ggplot(cmp, aes(tau2, v, colour = w)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(`diagnostic fires (any species)` = te_muted,
                                 `interaction strength retained` = te_rust)) +
  ylim(0, 1) +
  labs(title = "Flat where it hurts", subtitle = "Both on the same noise axis",
       x = "Observation error variance", y = "Proportion", colour = NULL) +
  theme_te(11) +
  guides(colour = guide_legend(ncol = 1))

two_panel(p1, p2)

## ---- reliability ----
b <- 0.7; s2 <- 0.25
V1 <- s2 / (1 - b^2)

rel <- do.call(rbind, lapply(c(0, 0.05, 0.25, 1.00), function(tau2) {
  bh <- numeric(400)
  for (m in 1:400) {
    set.seed(50000 + m)
    x <- numeric(3000)
    for (t in 2:3000) x[t] <- b * x[t - 1] + rnorm(1, 0, sqrt(s2))
    set.seed(150000 + m)
    xo <- x + rnorm(3000, 0, sqrt(tau2))
    bh[m] <- coef(lm(xo[-1] ~ xo[-3000]))[2]
  }
  data.frame(tau2 = tau2, empirical = mean(bh),
             predicted = b * V1 / (V1 + tau2),
             gap = mean(bh) - b * V1 / (V1 + tau2),
             reliability = V1 / (V1 + tau2))
}))
round(rel, 4)

## ---- fig-reliability ----
ggplot(rel, aes(predicted, empirical)) +
  geom_abline(slope = 1, intercept = 0, colour = te_line, linewidth = 0.8) +
  geom_point(aes(colour = factor(tau2)), size = 3.4) +
  scale_colour_manual(values = c(te_ink, te_forest, te_gold, te_rust)) +
  labs(title = "b times V/(V + tau squared)",
       subtitle = "Predicted against empirical, 400 replicates per level",
       x = "Predicted by the dilution formula", y = "Empirical mean estimate",
       colour = "Observation error variance") +
  theme_te()
