# Population viability analysis and extinction risk
# https://tidyecology.com/posts/extinction-risk-pva/
#
# 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-07

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

## ---- data ----
mu_true <- -0.035; sig_true <- 0.18; N0 <- 250; years_obs <- 25
set.seed(18)
logN <- numeric(years_obs + 1); logN[1] <- log(N0)
for (t in seq_len(years_obs)) logN[t + 1] <- logN[t] + mu_true + sig_true * rnorm(1)
counts <- exp(logN)
round(counts)

## ---- estimate ----
r <- diff(log(counts))          # log(N_{t+1} / N_t) for each year
mu_hat <- mean(r)
s2_hat <- var(r)
s_hat <- sqrt(s2_hat)
Nc <- counts[years_obs + 1]     # current abundance = the last count
Nx <- 25                        # quasi-extinction threshold
d <- log(Nc) - log(Nx)          # log-distance from now to the threshold

c(mu_hat = mu_hat, sigma_hat = s_hat, current_N = Nc, log_distance_d = d)

## ---- cdf ----
ext_cdf <- function(t, d, mu, s2) {
  s <- sqrt(s2); md <- -mu       # absolute drift for a declining population
  pmin(1, pmax(0, pnorm((-d + md * t) / (s * sqrt(t))) +
    exp(2 * d * md / s2) * pnorm((-d - md * t) / (s * sqrt(t)))))
}

years <- 1:50
risk <- ext_cdf(years, d, mu_hat, s2_hat)
c(mean_time_d_over_mu = d / (-mu_hat),
  median_year = years[which.min(abs(risk - 0.5))],
  P_within_20yr = ext_cdf(20, d, mu_hat, s2_hat),
  P_within_50yr = ext_cdf(50, d, mu_hat, s2_hat))

## ---- fig-projection ----
set.seed(321); npr <- 45
proj <- lapply(seq_len(npr), function(i) {
  lp <- log(Nc); v <- numeric(51); v[1] <- Nc
  for (t in seq_len(50)) { lp <- lp + mu_hat + s_hat * rnorm(1); v[t + 1] <- exp(lp) }
  data.frame(year = years_obs + (0:50), N = v, rep = i)
}) |> bind_rows()
obs <- data.frame(year = 0:years_obs, N = counts)

ggplot() +
  geom_line(data = proj, aes(year, N, group = rep), colour = te_sage, linewidth = 0.3, alpha = 0.5) +
  geom_hline(yintercept = Nx, colour = te_brick, linetype = "22", linewidth = 0.7) +
  geom_line(data = obs, aes(year, N), colour = te_forest, linewidth = 0.9) +
  geom_point(data = obs, aes(year, N), colour = te_forest, size = 1.2) +
  geom_vline(xintercept = years_obs, colour = te_faint, linetype = "42", linewidth = 0.4) +
  scale_y_log10() +
  annotate("text", x = 1, y = Nx * 0.72, label = "quasi-extinction threshold",
           colour = te_brick, hjust = 0, size = 3.1) +
  annotate("text", x = years_obs - 0.5, y = max(counts) * 1.05, label = "observed",
           colour = te_forest, hjust = 1, size = 3.1) +
  annotate("text", x = years_obs + 1.5, y = max(counts) * 1.05, label = "projected",
           colour = te_sage, hjust = 0, size = 3.1) +
  labs(title = "Count-based population viability projection",
       subtitle = "Fitted stochastic model projected 50 years from the last count",
       x = "Year", y = "Population count (log scale)") +
  theme_te()

## ---- validate ----
M <- 20000; set.seed(909)
ext_time <- rep(NA_integer_, M)
for (m in seq_len(M)) {
  lp <- log(Nc)
  for (t in seq_len(50)) {
    lp <- lp + mu_hat + s_hat * rnorm(1)
    if (lp <= log(Nx)) { ext_time[m] <- t; break }
  }
}
risk_sim <- sapply(years, function(y) mean(!is.na(ext_time) & ext_time <= y))
c(P50_simulated = risk_sim[50], P50_formula = risk[50],
  max_gap = max(abs(risk_sim - risk)))

## ---- fig-uncertainty ----
set.seed(4040); B <- 2000
band <- matrix(NA, B, length(years))
for (b in seq_len(B)) {
  lb <- numeric(years_obs + 1); lb[1] <- log(N0)
  for (t in seq_len(years_obs)) lb[t + 1] <- lb[t] + mu_hat + s_hat * rnorm(1)
  rb <- diff(lb); mub <- mean(rb); s2b <- var(rb)
  band[b, ] <- ext_cdf(years, d, mub, s2b)   # condition on the observed current count
}
lo <- apply(band, 2, quantile, 0.05); hi <- apply(band, 2, quantile, 0.95)

curve_df <- data.frame(year = years, pred = risk, lo = lo, hi = hi, sim = risk_sim)
ggplot(curve_df, aes(year)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = te_gold, alpha = 0.30) +
  geom_line(aes(y = pred), colour = te_forest, linewidth = 1.0) +
  geom_point(data = curve_df[seq(2, 50, by = 3), ], aes(y = sim), colour = te_brick, size = 1.4) +
  annotate("text", x = 2, y = 0.93, label = "90 per cent interval (parameter uncertainty)",
           colour = "#8a7a30", hjust = 0, size = 3.1) +
  annotate("text", x = 30, y = 0.30, label = "diffusion formula (line), simulation (points)",
           colour = te_forest, hjust = 0, size = 3.1) +
  labs(title = "Cumulative risk of quasi-extinction",
       subtitle = "The point estimate looks precise; the parameter uncertainty around it is wide",
       x = "Years from present", y = "Probability of quasi-extinction by year") +
  coord_cartesian(ylim = c(0, 1)) +
  theme_te()

## ---- ci ----
c(P50_point = risk[50],
  P50_lower = lo[50], P50_upper = hi[50])
