# Stochastic population growth in variable environments
# https://tidyecology.com/posts/stochastic-population-growth/
#
# 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(dplyr)
library(tidyr)

## ---- theme ----
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_gold <- "#c9b458"; te_deep <- "#1d5b4e"
te_brick <- "#b5534e"; te_faint <- "#5d6b61"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = te_body),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = te_faint),
          axis.title = element_text(colour = te_label),
          axis.text = element_text(colour = te_body),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          legend.background = element_rect(fill = te_paper, colour = NA),
          legend.position = "none")
}

## ---- matrices ----
A_good <- matrix(c(0, 0, 5.6,
                   0.55, 0.25, 0,
                   0, 0.42, 0.90), nrow = 3, byrow = TRUE)
A_bad <- matrix(c(0, 0, 1.4,
                  0.28, 0.18, 0,
                  0, 0.22, 0.78), nrow = 3, byrow = TRUE)

lambda <- function(A) {
  ev <- eigen(A)
  Re(ev$values[which.max(Re(ev$values))])
}

p <- 0.5                      # probability of a good year
Abar <- p * A_good + (1 - p) * A_bad    # the arithmetic mean matrix

c(good = lambda(A_good), bad = lambda(A_bad), mean_matrix = lambda(Abar))

## ---- simulate ----
sim_loglambda <- function(A_good, A_bad, p, steps, burnin, seed) {
  set.seed(seed)
  n <- rep(1/3, 3)
  lg <- numeric(steps)
  for (t in seq_len(steps)) {
    A <- if (runif(1) < p) A_good else A_bad
    n1 <- as.numeric(A %*% n)
    total <- sum(n1)
    lg[t] <- log(total)
    n <- n1 / total
  }
  mean(lg[(burnin + 1):steps])
}

loglam_s <- sim_loglambda(A_good, A_bad, p, steps = 50000, burnin = 1000, seed = 4242)
c(log_lambda_s = loglam_s, lambda_s = exp(loglam_s),
  log_lambda_meanmatrix = log(lambda(Abar)))

## ---- means ----
lam_g <- lambda(A_good); lam_b <- lambda(A_bad)
c(arithmetic_mean_lambda = p * lam_g + (1 - p) * lam_b,
  geometric_mean_lambda  = exp(p * log(lam_g) + (1 - p) * log(lam_b)),
  stochastic_lambda_s    = exp(loglam_s))

## ---- fig-trajectories ----
loglam_bar <- log(lambda(Abar))
ev <- eigen(Abar)
w <- Re(ev$vectors[, which.max(Re(ev$values))]); w <- w / sum(w)

set.seed(919)
years <- 30; nrep <- 6
traj <- lapply(seq_len(nrep), function(r) {
  n <- w * 100; tot <- numeric(years + 1); tot[1] <- sum(n)
  for (t in seq_len(years)) {
    A <- if (runif(1) < p) A_good else A_bad
    n <- as.numeric(A %*% n); tot[t + 1] <- sum(n)
  }
  data.frame(year = 0:years, N = tot, rep = factor(r))
}) |> bind_rows()

det <- data.frame(year = 0:years, N = 100 * exp(loglam_bar * (0:years)))
sto <- data.frame(year = 0:years, N = 100 * exp(loglam_s * (0:years)))

p_traj <- ggplot(traj, aes(year, N, group = rep)) +
  geom_line(colour = te_sage, linewidth = 0.5, alpha = 0.9) +
  geom_line(data = det, aes(year, N), inherit.aes = FALSE,
            colour = te_brick, linewidth = 1.0, linetype = "22") +
  geom_line(data = sto, aes(year, N), inherit.aes = FALSE,
            colour = te_forest, linewidth = 1.0) +
  scale_y_log10(labels = scales::label_log()) +
  annotate("text", x = years * 0.62, y = det$N[years + 1] * 1.6,
           label = "mean-matrix slope (log lambda-bar)", colour = te_brick, hjust = 0, size = 3.1) +
  annotate("text", x = years, y = sto$N[years + 1] * 0.12,
           label = "stochastic slope (log lambda_s)", colour = te_forest, hjust = 1, size = 3.1) +
  labs(title = "Environmental variance lowers long-run growth",
       subtitle = "Six stochastic runs scatter around the stochastic rate, below the mean-matrix rate",
       x = "Year", y = "Total population (log scale)") +
  theme_te()
p_traj

## ---- thumb ----
ggsave("thumbnail.png",
       p_traj + labs(title = NULL, subtitle = NULL) +
         theme(plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = te_paper)

## ---- tuljapurkar ----
# sensitivities of the mean matrix: S_ij = v_i w_j / (v . w)
ev    <- eigen(Abar)
w_bar <- Re(ev$vectors[, which.max(Re(ev$values))]); w_bar <- w_bar / sum(w_bar)
evL <- eigen(t(Abar))
v_bar <- Re(evL$vectors[, which.max(Re(evL$values))]); v_bar <- v_bar / v_bar[1]
S <- outer(v_bar, w_bar) / sum(v_bar * w_bar)

dA <- A_good - A_bad
tau2 <- p * (1 - p) * (sum(S * dA))^2
lam_bar <- lambda(Abar)
approx <- log(lam_bar) - 0.5 * tau2 / lam_bar^2

c(sum_S_times_dA = sum(S * dA), tau_squared = tau2,
  approx_log_lambda_s = approx, simulated_log_lambda_s = loglam_s,
  error = approx - loglam_s)

## ---- fig-running ----
set.seed(4242)
Tr <- 3000; n <- rep(1/3, 3); lg <- numeric(Tr)
for (t in seq_len(Tr)) {
  A <- if (runif(1) < p) A_good else A_bad
  n1 <- as.numeric(A %*% n); g <- sum(n1); lg[t] <- log(g); n <- n1 / g
}
runmean <- cumsum(lg) / seq_along(lg)

data.frame(year = seq_len(Tr), rm = runmean) |>
  ggplot(aes(year, rm)) +
  geom_hline(yintercept = loglam_bar, colour = te_brick, linetype = "22", linewidth = 0.7) +
  geom_hline(yintercept = approx, colour = te_gold, linetype = "42", linewidth = 0.7) +
  geom_line(colour = te_forest, linewidth = 0.5) +
  scale_x_log10() +
  annotate("text", x = 3, y = loglam_bar + 0.014,
           label = "log lambda-bar (mean matrix)", colour = te_brick, hjust = 0, size = 3.1) +
  annotate("text", x = 3, y = approx - 0.015,
           label = "Tuljapurkar approximation", colour = te_gold, hjust = 0, size = 3.1) +
  labs(title = "Running estimate of the stochastic growth rate",
       subtitle = "The cumulative mean of log annual growth settles below the mean-matrix value",
       x = "Years simulated (log scale)", y = "Running estimate of log lambda_s") +
  theme_te()
