# IPM sensitivity and elasticity
# https://tidyecology.com/posts/ipm-sensitivity-and-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-15

## ---- setup ----
library(ggplot2)
library(dplyr)

te <- list(ink="#16241d", body="#2c3a31", forest="#275139", label="#46604a",
           sage="#93a87f", paper="#f5f4ee", line="#dad9ca", faint="#5d6b61", rust="#b5534e")
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = te$body),
          plot.title = element_text(colour = te$ink, face = "bold", size = rel(1.02)),
          plot.subtitle = element_text(colour = te$faint, size = rel(0.9)),
          axis.title = element_text(colour = te$label),
          axis.text = element_text(colour = te$faint),
          panel.grid.major = element_line(colour = te$line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          panel.background = element_rect(fill = te$paper, colour = NA),
          plot.background = element_rect(fill = te$paper, colour = NA),
          legend.key = element_rect(fill = te$paper, colour = NA),
          strip.text = element_text(colour = te$forest, face = "bold"))
}

pars <- list(a_s=-1.4, b_s=0.50, a_g=1.9, b_g=0.65, sig_g=0.90,
             a_f=-6.0, b_f=0.80, a_r=0.42, b_r=0.24, mu_r=2.2, sig_r=0.70)

## ---- kernel-eigenvectors ----
build_K <- function(L, U, m) {
  h    <- (U - L) / m
  mesh <- L + (1:m - 0.5) * h
  S  <- plogis(pars$a_s + pars$b_s * mesh)
  G  <- outer(mesh, mesh, function(zp, z) dnorm(zp, pars$a_g + pars$b_g * z, pars$sig_g))
  G  <- sweep(G, 2, colSums(G) * h, "/")
  Cr <- dnorm(mesh, pars$mu_r, pars$sig_r); Cr <- Cr / (sum(Cr) * h)
  P  <- sweep(G, 2, S, "*") * h
  Pf <- plogis(pars$a_f + pars$b_f * mesh); Rn <- exp(pars$a_r + pars$b_r * mesh)
  Fk <- outer(Cr, Pf * Rn) * h
  list(K = P + Fk, P = P, Fk = Fk, mesh = mesh, h = h)
}

L <- 0; U <- 14; m <- 100
k <- build_K(L, U, m); K <- k$K; mesh <- k$mesh; h <- k$h

ev  <- eigen(K); lambda <- Re(ev$values[1])
w   <- Re(ev$vectors[, 1]); if (w[which.max(abs(w))] < 0) w <- -w; w <- w / sum(w)
v   <- Re(eigen(t(K))$vectors[, 1]); if (v[which.max(abs(v))] < 0) v <- -v
v   <- v / v[which.max(w)]                 # reproductive value scaled to 1 at the modal size
lambda

## ---- sensitivity ----
Smat <- outer(v, w) / sum(v * w)           # sensitivity of matrix entries: dlambda/dK_ij
Sfun <- Smat / h                           # kernel sensitivity function s(z', z)

i0 <- which.min(abs(mesh - 3)); j0 <- which.min(abs(mesh - 8))
delta <- 1e-6; Kp <- K; Kp[i0, j0] <- Kp[i0, j0] + delta
c(numerical = (Re(eigen(Kp)$values[1]) - lambda) / delta, analytic = Smat[i0, j0])

## ---- fig-sensitivity ----
idx <- which(Sfun == max(Sfun), arr.ind = TRUE)
zmax_from <- mesh[idx[2]]; zmax_to <- mesh[idx[1]]; Kval_there <- K[idx[1], idx[2]]
long <- function(M) data.frame(z = rep(mesh, each = m), zp = rep(mesh, times = m), val = as.vector(M))
ggplot(long(Sfun), aes(z, zp, fill = val)) +
  geom_raster(interpolate = TRUE) +
  scale_fill_gradient(low = te$paper, high = te$forest, name = "sensitivity") +
  annotate("point", x = zmax_from, y = zmax_to, colour = te$rust, size = 2.2) +
  coord_equal(expand = FALSE) +
  labs(x = "Size z at time t (parent)", y = "Size z' at time t+1 (offspring or survivor)") +
  theme_te(11) + theme(panel.grid = element_blank())

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- elasticity ----
E   <- (K / lambda) * Smat                 # elasticity of matrix entries; sums to 1
e_P <- sum((k$P  / lambda) * Smat)         # survival-growth elasticity
e_F <- sum((k$Fk / lambda) * Smat)         # fecundity elasticity
c(total = sum(E), survival_growth = e_P, fecundity = e_F)

## ---- fig-elasticity ----
ggplot(long(E), aes(z, zp, fill = val)) +
  geom_raster(interpolate = TRUE) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "#ffffffaa", linewidth = 0.4) +
  scale_fill_gradient(low = te$paper, high = te$forest, trans = "sqrt", name = "elasticity") +
  coord_equal(expand = FALSE) +
  labs(x = "Size z at time t", y = "Size z' at time t+1") +
  theme_te(11) + theme(panel.grid = element_blank())
