# Interaction strengths from community time series
# https://tidyecology.com/posts/interaction-strengths-from-time-series/
#
# 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)
Scol  <- Strue; Scol[1, 2] <- Scol[2, 1] <- 0.087
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)
}
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
}

## ---- mc ----
mc <- function(n, S, M, seed0) {
  Bh <- array(0, c(M, p, p)); Sg <- array(0, c(M, p, p))
  for (m in 1:M) {
    Xm <- sim_mar1(n, Atrue, Btrue, S, seed = seed0 + m)
    f <- mar1_cls(Xm)
    Bh[m, , ] <- f$B
    Sg[m, , ] <- abs(f$B / mar1_se(Xm)) > 2   # crude 2-SE screen
  }
  list(B = Bh, sig = Sg)
}

r60  <- mc(60, Strue, 600, 60000)
bias <- apply(r60$B, c(2, 3), mean) - Btrue
round(bias, 3)

## ---- bias-split ----
c(diagonal     = mean(diag(bias)),
  off_diagonal = mean(bias[row(bias) != col(bias)]))

## ---- sweep ----
sweep <- do.call(rbind, lapply(c(25, 40, 60, 120, 400), function(n) {
  r <- mc(n, Strue, 250, n * 1000)
  s <- apply(r$sig, c(2, 3), mean)
  z0 <- which(Btrue == 0)
  data.frame(n = n,
             bias  = mean(diag(apply(r$B, c(2, 3), mean) - Btrue)),
             mc_sd = mean(apply(r$B, c(2, 3), sd)),
             false_pos = mean(s[z0]),
             detection = mean(s[-z0]))
}))
round(sweep, 4)

## ---- fig-bias ----
cells <- data.frame(
  err  = as.vector(bias),
  kind = ifelse(as.vector(diag(4)) == 1, "diagonal", "off-diagonal"),
  cell = paste0("b", as.vector(row(bias)), as.vector(col(bias)))
)

p1 <- ggplot(cells, aes(err, reorder(cell, err), colour = kind)) +
  geom_vline(xintercept = 0, colour = te_ink, linewidth = 0.4) +
  geom_point(size = 2.2) +
  scale_colour_manual(values = c(diagonal = te_rust, `off-diagonal` = te_sage)) +
  labs(title = "Where the bias lands", subtitle = "600 replicates, n = 60",
       x = "Mean estimate minus truth", y = NULL, colour = NULL) +
  theme_te(11)

p2 <- ggplot(sweep, aes(n, bias)) +
  geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.4) +
  geom_line(colour = te_forest, linewidth = 0.7) +
  geom_point(colour = te_forest, size = 2.2) +
  geom_vline(xintercept = 60, colour = te_gold, linetype = 2, linewidth = 0.5) +
  annotate("text", x = 72, y = min(sweep$bias) / 2, label = "a real series",
           hjust = 0, size = 3, colour = te_muted) +
  scale_x_log10(breaks = sweep$n, labels = sweep$n) +
  labs(title = "It goes away like 1/n", subtitle = "Mean bias of the diagonal",
       x = "Series length", y = "Diagonal bias") +
  theme_te(11)

two_panel(p1, p2)

## ---- rates ----
sg <- apply(r60$sig, c(2, 3), mean)
z0 <- which(Btrue == 0)
c(false_positive_on_6_true_zeros = mean(sg[z0]),
  detection_on_10_true_effects   = mean(sg[-z0]))

## ---- weak ----
rbind(
  `b[1,2] = -0.10` = c(sign_error = mean(r60$B[, 1, 2] > 0), detected = sg[1, 2]),
  `b[1,3] = -0.35` = c(sign_error = mean(r60$B[, 1, 3] > 0), detected = sg[1, 3])
)

## ---- fig-detect ----
det <- data.frame(
  abs_b  = as.vector(abs(Btrue)),
  detect = as.vector(sg),
  kind   = ifelse(as.vector(Btrue) == 0, "true zero", "true effect")
)

p1 <- ggplot(det, aes(abs_b, detect, colour = kind)) +
  geom_hline(yintercept = 0.05, colour = te_line, linetype = 2, linewidth = 0.5) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(`true effect` = te_forest, `true zero` = te_rust)) +
  ylim(0, 1) +
  labs(title = "What the screen can see", subtitle = "n = 60, two-SE screen",
       x = "True |b_ij|", y = "Detection rate", colour = NULL) +
  theme_te(11)

sdo <- function(S, seed0) {
  Bh <- array(0, c(300, p, p))
  for (m in 1:300) Bh[m, , ] <- mar1_cls(sim_mar1(60, Atrue, Btrue, S, seed = seed0 + m))$B
  Bh
}
Bb <- sdo(Strue, 11000); Bc <- sdo(Scol, 22000)

dens <- rbind(
  data.frame(v = Bb[, 1, 1], cell = "b11", env = "baseline"),
  data.frame(v = Bc[, 1, 1], cell = "b11", env = "shared"),
  data.frame(v = Bb[, 1, 2], cell = "b12", env = "baseline"),
  data.frame(v = Bc[, 1, 2], cell = "b12", env = "shared")
)
truth <- data.frame(cell = c("b11", "b12"), t = c(Btrue[1, 1], Btrue[1, 2]))

p2 <- ggplot(dens, aes(v, colour = env, fill = env)) +
  geom_density(alpha = 0.18, linewidth = 0.6) +
  geom_vline(data = truth, aes(xintercept = t), colour = te_ink, linetype = 2, linewidth = 0.4) +
  facet_wrap(~ cell, ncol = 1, scales = "free_y") +
  scale_colour_manual(values = c(baseline = te_forest, shared = te_rust)) +
  scale_fill_manual(values = c(baseline = te_forest, shared = te_rust)) +
  labs(title = "Same B, two environments", subtitle = "300 replicates each; dashes are the truth",
       x = "Estimate", y = NULL, colour = NULL, fill = NULL) +
  theme_te(11) +
  theme(axis.text.y = element_blank(), strip.text = element_text(colour = te_ink, face = "bold"))

two_panel(p1, p2)

## ---- vif ----
Xb <- sim_mar1(60, Atrue, Btrue, Strue, seed = 4269)
Xc <- sim_mar1(60, Atrue, Btrue, Scol,  seed = 4269)

vf <- function(M) {
  Ml <- M[-nrow(M), ]
  sapply(1:p, function(j) 1 / (1 - summary(lm(Ml[, j] ~ Ml[, -j]))$r.squared))
}
rbind(baseline = vf(Xb), shared = vf(Xc))

## ---- sd-inflation ----
sb <- apply(Bb, c(2, 3), sd); sc <- apply(Bc, c(2, 3), sd)
tab <- t(sapply(list(c(1, 1), c(1, 2), c(2, 1)), function(ij) {
  c(baseline = sb[ij[1], ij[2]], shared = sc[ij[1], ij[2]],
    ratio = sc[ij[1], ij[2]] / sb[ij[1], ij[2]])
}))
rownames(tab) <- c("b[1,1]", "b[1,2]", "b[2,1]")
round(tab, 3)
