# Community stability from a MAR(1) model
# https://tidyecology.com/posts/stability-from-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-07

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

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- stationary ----
stat_mu <- function(A, B) solve(diag(nrow(B)) - B, A)
stat_V  <- function(B, S) {
  matrix(solve(diag(nrow(B)^2) - kronecker(B, B), as.vector(S)), nrow(B), nrow(B))
}

Vt <- stat_V(Btrue, Strue)
round(Vt, 4)

## ---- stationary-check ----
Xlong <- sim_mar1(2e5, Atrue, Btrue, Strue, seed = 999)
max(abs(Vt - cov(Xlong)))

## ---- return-rate ----
set.seed(11)
z <- rnorm(p); z <- z / sqrt(sum(z^2))
for (t in 1:199) z <- as.vector(Btrue %*% z)
n199 <- sqrt(sum(z^2))
z <- as.vector(Btrue %*% z)
decay <- sqrt(sum(z^2)) / n199
c(empirical_decay = decay, max_eigen_mod = max(Mod(eigen(Btrue)$values)))

## ---- complex-trap ----
fit <- mar1_cls(sim_mar1(60, Atrue, Btrue, Strue, seed = 4268))
ev  <- eigen(fit$B)$values
c(is_complex = is.complex(ev),
  max_modulus = max(Mod(ev)),
  max_real    = max(Re(ev)),
  truth       = max(Mod(eigen(Btrue)$values)))

## ---- variance-return ----
max(Mod(eigen(kronecker(Btrue, Btrue))$values)) - max(Mod(eigen(Btrue)$values))^2

## ---- reactivity ----
sigma1 <- sqrt(max(eigen(crossprod(Btrue))$values))

set.seed(13)
amp <- replicate(2e5, {
  u <- rnorm(p); u <- u / sqrt(sum(u^2))
  sqrt(sum((Btrue %*% u)^2))
})
c(sigma1 = sigma1, brute_force_max = max(amp), gap = sigma1 - max(amp))

## ---- ives-reactivity ----
c(sigma_over_Vinf = -sum(diag(Strue)) / sum(diag(Vt)),
  worst_case      = max(eigen(crossprod(Btrue))$values) - 1)

## ---- reactive-example ----
Br <- matrix(c(0.4, 1.4,
               0,   0.4), 2, 2, byrow = TRUE)
c(return_rate = max(Mod(eigen(Br)$values)),
  sigma1      = sqrt(max(eigen(crossprod(Br))$values)))

## ---- fig-decay ----
zz <- {
  set.seed(11); v <- rnorm(p); v <- v / sqrt(sum(v^2))
  out <- numeric(21); out[1] <- 1
  for (t in 2:21) { v <- as.vector(Btrue %*% v); out[t] <- sqrt(sum(v^2)) }
  out
}
lam <- max(Mod(eigen(Btrue)$values))
dec <- data.frame(t = 0:20, size = zz, ref = lam^(0:20))

p1 <- ggplot(dec, aes(t, size)) +
  geom_line(aes(y = ref), colour = te_gold, linewidth = 0.9, linetype = 2) +
  geom_line(colour = te_forest, linewidth = 0.7) +
  geom_point(colour = te_forest, size = 1.6) +
  scale_y_log10(labels = scales::label_log()) +
  annotate("text", x = 12, y = lam^7, label = "max|lambda|^t", colour = te_gold, size = 3, hjust = 0) +
  labs(title = "A perturbation decaying", subtitle = "True B, unit kick at t = 0",
       x = "Time step", y = "Deviation size (log scale)") +
  theme_te(11)

evd <- data.frame(re = Re(ev), im = Im(ev))
circ <- data.frame(a = seq(0, 2 * pi, length.out = 200))
circ$x <- max(Mod(ev)) * cos(circ$a); circ$y <- max(Mod(ev)) * sin(circ$a)

p2 <- ggplot(evd, aes(re, im)) +
  geom_path(data = circ, aes(x, y), colour = te_gold, linetype = 2, linewidth = 0.6) +
  geom_hline(yintercept = 0, colour = te_line, linewidth = 0.3) +
  geom_vline(xintercept = 0, colour = te_line, linewidth = 0.3) +
  geom_vline(xintercept = max(Re(ev)), colour = te_rust, linewidth = 0.6) +
  geom_point(colour = te_forest, size = 2.6) +
  annotate("text", x = max(Re(ev)) - 0.02, y = 0.3, label = "max Re: wrong",
           colour = te_rust, size = 3, hjust = 1) +
  coord_equal() +
  labs(title = "Eigenvalues of the fitted B",
       subtitle = "Gold circle: the modulus, which is the return rate",
       x = "Real part", y = "Imaginary part") +
  theme_te(11)

two_panel(p1, p2)

## ---- thumb ----
thumb_title <- paste(strwrap("Eigenvalues of the fitted B", 46), collapse = "\n")
ggsave("thumbnail.png",
       p2 + labs(title = thumb_title) +
         theme(plot.title = element_text(size = 13, face = "bold"),
               plot.subtitle = element_text(size = 9.5),
               plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")

## ---- p1-identity ----
t(sapply(c(0.3, 0.7, 0.9), function(b) {
  V <- 0.25 / (1 - b^2)
  c(b = b, sigma_over_V = 0.25 / V, one_minus_b2 = 1 - b^2, gap = 0.25 / V - (1 - b^2))
}))

## ---- det-sweep ----
Sl <- list(
  "original"          = Strue,
  "5x scaled"         = 5 * Strue,
  "identity"          = diag(p) * 0.06,
  "different shape"   = diag(c(0.20, 0.02, 0.10, 0.01)),
  "strongly correlated" = 0.06 * (0.8 * matrix(1, p, p) + 0.2 * diag(p))
)
ratios <- sapply(Sl, function(S) (det(S) / det(stat_V(Btrue, S)))^(1 / p))
round(ratios, 6)

## ---- det-b ----
c(det_B_2_over_p = abs(det(Btrue))^(2 / p),
  one_minus_it   = 1 - abs(det(Btrue))^(2 / p))

## ---- fig-sigma ----
sw <- data.frame(env = factor(names(ratios), levels = names(ratios)),
                 ratio = as.vector(ratios))

p1 <- ggplot(sw, aes(env, ratio)) +
  geom_col(fill = te_sage, width = 0.65) +
  geom_hline(yintercept = 1 - abs(det(Btrue))^(2 / p), colour = te_rust,
             linetype = 2, linewidth = 0.8) +
  annotate("text", x = 3, y = 1 - abs(det(Btrue))^(2 / p) + 0.02,
           label = "1 - |det B|^(2/p)", colour = te_rust, size = 3) +
  labs(title = "Same B, five environments", subtitle = "(det Sigma / det V)^(1/p)",
       x = NULL, y = "Variance ratio") +
  theme_te(11) +
  theme(axis.text.x = element_text(angle = 35, hjust = 1))

amp_path <- function(B, steps = 14) {
  sv <- svd(B); v <- sv$v[, 1]
  out <- numeric(steps + 1); out[1] <- 1
  for (t in 1:steps) { v <- as.vector(B %*% v); out[t + 1] <- sqrt(sum(v^2)) }
  out
}
Br <- matrix(c(0.4, 1.4, 0, 0.4), 2, 2, byrow = TRUE)
react <- rbind(
  data.frame(t = 0:14, size = amp_path(Br), which = "reactive B"),
  data.frame(t = 0:14, size = amp_path(Btrue), which = "our community")
)

p2 <- ggplot(react, aes(t, size, colour = which)) +
  geom_hline(yintercept = 1, colour = te_ink, linewidth = 0.4) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.5) +
  scale_colour_manual(values = c(`reactive B` = te_rust, `our community` = te_forest)) +
  labs(title = "Stable does not mean unamplifying",
       subtitle = "Worst-case perturbation, both with return rate below 1",
       x = "Time step", y = "Deviation size", colour = NULL) +
  theme_te(11)

two_panel(p1, p2)
