# Sensitivity and elasticity of matrix models
# https://tidyecology.com/posts/matrix-sensitivity-elasticity/
#
# 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)

te_ink <- "#16241d"; te_forest <- "#275139"; te_mown <- "#2f8f63"
te_gold <- "#c9b458"; te_faint <- "#5d6b61"; te_line <- "#dad9ca"; te_paper <- "#f5f4ee"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = "#2c3a31"),
          plot.title = element_text(colour = te_ink, face = "bold", size = base_size * 1.15),
          plot.subtitle = element_text(colour = te_faint, size = base_size * 0.95),
          axis.title = element_text(colour = "#46604a"), axis.text = element_text(colour = te_faint),
          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.key = element_rect(fill = te_paper, colour = NA))
}

stages <- c("Seedling", "Juvenile", "Small adult", "Large adult")
A <- matrix(0, 4, 4, dimnames = list(stages, stages))
A["Juvenile",    "Seedling"]    <- 0.30
A["Juvenile",    "Juvenile"]    <- 0.35
A["Small adult", "Juvenile"]    <- 0.30
A["Small adult", "Small adult"] <- 0.45
A["Large adult", "Small adult"] <- 0.25
A["Seedling",    "Small adult"] <- 1.60
A["Large adult", "Large adult"] <- 0.82
A["Seedling",    "Large adult"] <- 3.00

ev  <- eigen(A)
lam <- Re(ev$values[1])
w   <- Re(ev$vectors[, 1]);        w <- w / sum(w)     # stable stage distribution
v   <- Re(eigen(t(A))$vectors[, 1]); v <- v / v[1]     # reproductive value
S   <- outer(v, w) / sum(v * w)                        # sensitivity matrix
dimnames(S) <- dimnames(A)
round(S, 3)

## ---- numerical-check ----
delta <- 1e-6
S_num <- matrix(NA, 4, 4)
for (i in 1:4) for (j in 1:4) {
  Ap <- A; Ap[i, j] <- Ap[i, j] + delta
  S_num[i, j] <- (Re(eigen(Ap)$values[1]) - lam) / delta
}
max(abs(S - S_num))

## ---- elasticity ----
E <- (A / lam) * S
round(E, 3)
sum(E)

## ---- fig-elasticity ----
df <- as.data.frame(as.table(E)); colnames(df) <- c("to", "from", "elas")
df$to <- factor(df$to, levels = rev(stages)); df$from <- factor(df$from, levels = stages)
df$lab <- ifelse(df$elas > 0.0005, sprintf("%.2f", df$elas), "")
ggplot(df, aes(from, to, fill = elas)) +
  geom_tile(colour = "white", linewidth = 1.2) +
  geom_text(aes(label = lab), colour = te_ink, size = 4) +
  scale_fill_gradient(low = te_paper, high = te_forest, name = "elasticity") +
  labs(title = "Elasticity: where a proportional change moves lambda most",
       subtitle = "Large-adult stasis dominates; the entries sum to one",
       x = "from stage", y = "to stage") +
  theme_te() +
  theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 20, hjust = 1))

## ---- by-process ----
proc <- matrix("", 4, 4)
for (i in 1:4) for (j in 1:4) {
  if (A[i, j] == 0) next
  if (i == 1 && j >= 3) proc[i, j] <- "Fecundity"
  else if (i == j)      proc[i, j] <- "Stasis"
  else                  proc[i, j] <- "Growth"
}
round(tapply(E[proc != ""], proc[proc != ""], sum), 3)

## ---- fig-process ----
byproc <- tapply(E[proc != ""], proc[proc != ""], sum)
data.frame(process = factor(names(byproc), levels = c("Stasis", "Growth", "Fecundity")),
           elas = as.numeric(byproc)) |>
  ggplot(aes(process, elas)) +
  geom_col(aes(fill = process), width = 0.62, show.legend = FALSE) +
  geom_text(aes(label = sprintf("%.0f%%", 100 * elas)), vjust = -0.4, colour = te_ink, size = 4.2) +
  scale_fill_manual(values = c(Stasis = te_faint, Growth = te_mown, Fecundity = te_gold)) +
  ylim(0, max(byproc) * 1.15) +
  labs(title = "Elasticity summed by demographic process",
       subtitle = "For the same proportional gain, adult survival buys more than seed output",
       x = NULL, y = "Summed elasticity") +
  theme_te()
