# Transient dynamics of population matrix models
# https://tidyecology.com/posts/transient-population-dynamics/
#
# 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-11-04

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

## ---- matrix ----
A <- matrix(c(0,    0,    0.40, 1.80,
              0.20, 0.35, 0,    0,
              0,    0.40, 0.55, 0,
              0,    0,    0.35, 0.90), nrow = 4, byrow = TRUE)
stages <- c("Seedling", "Juvenile", "Small adult", "Large adult")

ev <- eigen(A)
ord <- order(Mod(ev$values), decreasing = TRUE)
lambda1 <- Re(ev$values[ord[1]])
lambda2 <- ev$values[ord[2]]
damping <- lambda1 / Mod(lambda2)
c(lambda1 = lambda1, mod_lambda2 = Mod(lambda2), damping_ratio = damping)

## ---- eigenvectors ----
w <- Re(ev$vectors[, ord[1]]); w <- w / sum(w)          # stable stage distribution
evL <- eigen(t(A))
ordL <- order(Mod(evL$values), decreasing = TRUE)
v <- Re(evL$vectors[, ordL[1]]); v <- v / v[1]          # reproductive values

data.frame(stage = stages, stable_dist = round(w, 3), repro_value = round(v, 2))

## ---- reactivity ----
Ahat <- A / lambda1
col_sums <- colSums(Ahat)
names(col_sums) <- stages
round(col_sums, 3)
c(reactivity = max(col_sums), first_step_attenuation = min(col_sums))

## ---- amplification ----
Tt <- 40; P <- diag(4)
max_amp <- 1; min_att <- 1; t_amp <- 0; t_att <- 0
for (t in seq_len(Tt)) {
  P <- Ahat %*% P
  cs <- colSums(P)
  if (max(cs) > max_amp) { max_amp <- max(cs); t_amp <- t }
  if (min(cs) < min_att) { min_att <- min(cs); t_att <- t }
}
c(max_amplification = max_amp, at_year = t_amp,
  max_attenuation = min_att, at_year_att = t_att)

## ---- fig-transient ----
proj_std <- function(n0) {
  x <- n0 / sum(n0); out <- numeric(Tt + 1); out[1] <- 1
  for (t in seq_len(Tt)) { x <- as.numeric(Ahat %*% x); out[t + 1] <- sum(x) }
  out
}
n_large <- c(0, 0, 0, 100); n_seed <- c(100, 0, 0, 0)
ps_large <- proj_std(n_large); ps_seed <- proj_std(n_seed)

df1 <- bind_rows(
  data.frame(year = 0:Tt, std = ps_large, init = "Start: all large adults"),
  data.frame(year = 0:Tt, std = ps_seed,  init = "Start: all seedlings"))

ggplot(df1, aes(year, std, colour = init)) +
  geom_hline(yintercept = 1, colour = te_faint, linetype = "42", linewidth = 0.5) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.0) +
  scale_colour_manual(values = c("Start: all large adults" = te_forest,
                                 "Start: all seedlings" = te_gold)) +
  annotate("text", x = 40, y = ps_large[Tt + 1] + 0.35, label = "amplification (adults)",
           colour = te_forest, hjust = 1, size = 3.1) +
  annotate("text", x = 40, y = ps_seed[Tt + 1] - 0.18, label = "attenuation (seedlings)",
           colour = "#8a7a30", hjust = 1, size = 3.1) +
  annotate("text", x = 6, y = 1.10, label = "stable-structure growth (= lambda1)",
           colour = te_faint, hjust = 0, size = 3.0) +
  labs(title = "Transient amplification and attenuation",
       subtitle = "The initial stage structure sets the short-term path and a permanent offset",
       x = "Year", y = "Population size / lambda1^t") +
  theme_te()

## ---- inertia ----
c(large_first_step = ps_large[2], large_peak = max(ps_large), large_inertia = ps_large[Tt + 1],
  seed_first_step = ps_seed[2], seed_trough = min(ps_seed), seed_inertia = ps_seed[Tt + 1])

## ---- fig-convergence ----
dist_series <- function(n0) {
  x <- n0; dvec <- numeric(Tt + 1)
  for (t in 0:Tt) {
    nn <- x / sum(x); dvec[t + 1] <- 0.5 * sum(abs(nn - w))
    x <- as.numeric(A %*% x)
  }
  dvec
}
dL <- dist_series(n_large); dS <- dist_series(n_seed)
ref <- dL[3] * (1 / damping)^((0:Tt) - 2); ref[1:3] <- NA

df2 <- bind_rows(
  data.frame(year = 0:Tt, dist = dL, init = "Start: all large adults"),
  data.frame(year = 0:Tt, dist = dS, init = "Start: all seedlings"))
df2 <- df2[df2$dist > 1e-6, ]
refdf <- data.frame(year = 0:Tt, ref = ref)
refdf <- refdf[!is.na(refdf$ref) & refdf$ref > 1e-6, ]

ggplot(df2, aes(year, dist, colour = init)) +
  geom_line(data = refdf, aes(year, ref), inherit.aes = FALSE,
            colour = te_brick, linetype = "22", linewidth = 0.7) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.0) +
  scale_colour_manual(values = c("Start: all large adults" = te_forest,
                                 "Start: all seedlings" = te_gold), name = NULL) +
  scale_y_log10(labels = function(x) vapply(x, format, "", scientific = FALSE,
                                            drop0trailing = TRUE)) +
  annotate("text", x = 6.5, y = 0.30,
           label = "slope = (1 / damping ratio)^t", colour = te_brick, hjust = 0, size = 3.1) +
  labs(title = "Convergence to the stable stage structure",
       subtitle = "Distance to the stable distribution decays geometrically at the damping ratio",
       x = "Year", y = "Distance to stable structure (log scale)") +
  theme_te() +
  theme(legend.position = "top")
