# Life expectancy and passage time in an IPM
# https://tidyecology.com/posts/ipm-life-expectancy-passage-time/
#
# 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

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

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)

## ---- fundamental-matrix ----
L <- 0; U <- 14; m <- 100
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, "/")          # eviction-corrected growth
P <- sweep(G, 2, S, "*") * h                    # survival-growth (columns sum to survival)

Nmat <- solve(diag(m) - P)                       # fundamental matrix
eta       <- colSums(Nmat)                       # life expectancy from each size
eta_naive <- 1 / (1 - S)                         # naive: size treated as fixed

## ---- life-expectancy-table ----
zq  <- c(recruit = 2.2, small = 4, medium = 6, large = 9)
idx <- sapply(zq, function(z) which.min(abs(mesh - z)))
data.frame(size = zq, survival = round(S[idx], 3),
           fundamental = round(eta[idx], 2), naive = round(eta_naive[idx], 2))

## ---- fig-life-expectancy ----
d1 <- data.frame(z = mesh, N = eta, naive = eta_naive) |>
  filter(z >= 1, z <= 11) |>
  pivot_longer(c(N, naive), names_to = "method", values_to = "years")
d1$method <- factor(d1$method, levels = c("N", "naive"),
                    labels = c("Fundamental matrix N", "Naive 1/(1 - s(z))"))
ggplot(d1, aes(z, years, colour = method)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c(te$forest, te$rust), name = NULL) +
  coord_cartesian(ylim = c(0, 24)) +
  labs(x = "Current size z", y = "Expected remaining lifespan (years)") +
  theme_te(11) + theme(legend.position = "inside", legend.position.inside = c(0.28, 0.82),
                       legend.background = element_rect(fill = te$paper, colour = NA))

## ---- first-passage ----
TG    <- G * h                                   # column-stochastic growth transition
zstar <- 5.5
absb  <- mesh >= zstar
Q     <- TG[!absb, !absb]
Ng    <- solve(diag(sum(!absb)) - Q)
pass  <- rep(0, m); pass[!absb] <- colSums(Ng)   # years to grow up to zstar

sapply(c(2.2, 3, 4, 5), function(z) round(pass[which.min(abs(mesh - z))], 2))

## ---- fig-passage ----
d2 <- data.frame(z = mesh[!absb], years = pass[!absb])
ggplot(d2, aes(z, years)) +
  geom_line(colour = te$forest, linewidth = 1) +
  labs(x = "Starting size z", y = "Expected years to reach size 5.5") +
  theme_te(11)
