# Stability and complexity in food webs
# https://tidyecology.com/posts/stability-and-complexity-in-food-webs/
#
# 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-15

## ---- stability-fn ----
stable <- function(M) max(Re(eigen(M, only.values = TRUE)$values)) < 0

## ---- mat-random ----
mat_random <- function(S, C, sigma, d = 1) {
  E <- matrix(rnorm(S * S), S, S) * (matrix(runif(S * S), S, S) < C)
  diag(E) <- 0
  -d * diag(S) + sigma * E
}

## ---- may-threshold ----
S <- 50; C <- 0.20; d <- 1
sigma_crit <- d / sqrt(S * C)
round(sigma_crit, 3)

## ---- sweep ----
set.seed(2024)
sigmas <- seq(0.15, 0.55, by = 0.05)
frac_stable <- sapply(sigmas, function(s)
  mean(replicate(300, stable(mat_random(S, C, s, d)))))
data.frame(sigma = sigmas, stable = frac_stable)

## ---- fig-threshold ----
library(ggplot2)
df <- data.frame(sigma = sigmas, stable = frac_stable)

ggplot(df, aes(sigma, stable)) +
  geom_vline(xintercept = sigma_crit, linetype = "dashed", colour = "grey55") +
  geom_line(colour = "#3d6cb0", linewidth = 0.8) +
  geom_point(colour = "#3d6cb0", size = 2) +
  annotate("text", x = sigma_crit + 0.005, y = 0.9, label = "May threshold",
           hjust = 0, size = 3.4, colour = "grey35") +
  labs(x = "Interaction strength (sigma)", y = "Fraction stable") +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))

## ---- eigenvalue-check ----
set.seed(11)
big <- sapply(c(0.2, 0.3, 0.4), function(s) {
  M <- mat_random(200, C, s, d)
  c(sigma = s,
    observed  = max(Re(eigen(M, only.values = TRUE)$values)),
    predicted = s * sqrt(200 * C) - d)
})
round(t(big), 3)

## ---- mat-predprey ----
mat_predprey <- function(S, C, sigma, d = 1) {
  E <- matrix(0, S, S)
  for (i in 1:(S - 1)) for (j in (i + 1):S) if (runif(1) < C) {
    E[i, j] <-  abs(rnorm(1))       # prey j raises predator i
    E[j, i] <- -abs(rnorm(1))       # predator i lowers prey j
  }
  -d * diag(S) + sigma * E
}

## ---- predprey-sweep ----
# reciprocal correlation of the two directions of each link
set.seed(5)
rho <- mean(replicate(200, {
  E <- matrix(0, S, S)
  for (i in 1:(S - 1)) for (j in (i + 1):S) if (runif(1) < C) {
    E[i, j] <- abs(rnorm(1)); E[j, i] <- -abs(rnorm(1)) }
  k <- which(E != 0 & t(E) != 0)
  mean(E[k] * t(E)[k]) / mean(E[E != 0]^2)
}))

set.seed(2024)
sig_wide <- seq(0.3, 1.1, by = 0.1)
frac_pp <- sapply(sig_wide, function(s)
  mean(replicate(300, stable(mat_predprey(S, C, s, d)))))

c(reciprocal_corr = round(rho, 3),
  predator_prey_threshold = round(d / (sqrt(S * C) * (1 + rho)), 3))

## ---- fig-compare ----
comp <- rbind(
  data.frame(sigma = sigmas,   stable = frac_stable, type = "random"),
  data.frame(sigma = sig_wide, stable = frac_pp,     type = "predator-prey")
)

ggplot(comp, aes(sigma, stable, colour = type)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.8) +
  scale_colour_manual(values = c("random" = "#c1523f",
                                 "predator-prey" = "#4c9f70")) +
  labs(x = "Interaction strength (sigma)", y = "Fraction stable", colour = NULL) +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        legend.position = "top",
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))
