# Return levels and uncertainty
# https://tidyecology.com/posts/return-levels-and-uncertainty/
#
# 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-14

## ---- gev-fit ----
library(ggplot2)
qgev <- function(p, mu, sigma, xi) {
  if (abs(xi) < 1e-6) return(mu - sigma * log(-log(p)))
  mu + (sigma / xi) * ((-log(p))^(-xi) - 1)
}
rgev <- function(n, mu, sigma, xi) qgev(runif(n), mu, sigma, xi)
nll_gev <- function(par, x) {
  mu <- par[1]; sigma <- exp(par[2]); xi <- par[3]; z <- (x - mu) / sigma
  if (abs(xi) < 1e-6) { ll <- -log(sigma) - z - exp(-z) }
  else {
    t <- 1 + xi * z
    if (any(!is.finite(t)) || any(t <= 0)) return(1e10)
    ll <- -log(sigma) - (1 / xi + 1) * log(t) - t^(-1 / xi)
  }
  v <- -sum(ll); if (!is.finite(v)) return(1e10); v
}

set.seed(4246)
ymax <- rgev(60, 31.0, 1.6, 0.13)
s0 <- sd(ymax) * sqrt(6) / pi
opt <- optim(c(mean(ymax) - 0.5772 * s0, log(s0), 0.1), nll_gev,
             x = ymax, method = "BFGS", hessian = TRUE)
stopifnot(opt$convergence == 0)   # check before inverting the Hessian
mu <- opt$par[1]; sigma <- exp(opt$par[2]); xi <- opt$par[3]
cov_nat <- diag(c(1, sigma, 1)) %*% solve(opt$hessian) %*% diag(c(1, sigma, 1))
return_level <- function(m) qgev(1 - 1 / m, mu, sigma, xi)

## ---- delta-ci ----
grad_zm <- function(m) {
  y <- -log(1 - 1 / m)
  c(1,
    -(1 / xi) * (1 - y^(-xi)),
    (sigma / xi^2) * (1 - y^(-xi)) - (sigma / xi) * y^(-xi) * log(y))
}
delta_ci <- function(m) {
  g <- grad_zm(m)
  v <- as.numeric(t(g) %*% cov_nat %*% g)
  est <- return_level(m)
  c(est = est, lo = est - 1.96 * sqrt(v), hi = est + 1.96 * sqrt(v))
}
d100 <- delta_ci(100)

## ---- profile-ci ----
prof_ll <- function(zm, m) {
  y <- -log(1 - 1 / m)
  obj <- function(theta) {
    sg <- exp(theta[1]); xn <- theta[2]
    mu_z <- zm - (sg / xn) * (y^(-xn) - 1)
    nll_gev(c(mu_z, log(sg), xn), ymax)
  }
  r <- tryCatch(optim(c(log(sigma), xi), obj, method = "Nelder-Mead"),
                error = function(e) NULL)
  if (is.null(r)) return(-1e10)
  -r$value
}
profile_ci <- function(m, span = 25, k = 241) {
  zhat <- return_level(m); Lmax <- -opt$value
  zg <- seq(zhat - span, zhat + span * 1.6, length.out = k)
  dev <- 2 * (Lmax - sapply(zg, prof_ll, m = m))
  crit <- qchisq(0.95, 1)
  ok <- which(dev <= crit)
  lo <- approx(dev[c(min(ok) - 1, min(ok))], zg[c(min(ok) - 1, min(ok))], crit)$y
  hi <- approx(dev[c(max(ok), max(ok) + 1)], zg[c(max(ok), max(ok) + 1)], crit)$y
  list(est = zhat, lo = lo, hi = hi, zg = zg, dev = dev, crit = crit)
}
p100 <- profile_ci(100)

## ---- fig-ci ----
te_forest <- "#275139"; te_rust <- "#9c5b34"; te_gold <- "#b8860b"
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "grey90", linewidth = 0.3),
          plot.title = element_text(face = "bold", size = 11.5),
          axis.title = element_text(size = 10.5),
          legend.position = "top", legend.title = element_blank(),
          plot.margin = margin(6, 10, 6, 6))
}
dev_df <- data.frame(z = p100$zg, dev = p100$dev)
dev_df <- dev_df[dev_df$dev < 8, ]
pA <- ggplot(dev_df, aes(z, dev)) +
  geom_line(colour = te_forest, linewidth = 0.9) +
  geom_hline(yintercept = p100$crit, linetype = "dashed", colour = te_rust) +
  annotate("segment", x = p100$lo, xend = p100$hi, y = -0.35, yend = -0.35,
           colour = te_forest, linewidth = 1.1) +
  annotate("segment", x = d100["lo"], xend = d100["hi"], y = -0.9, yend = -0.9,
           colour = "grey55", linewidth = 1.1) +
  annotate("text", x = p100$est, y = -0.35, label = "profile", vjust = 1.5,
           size = 3, colour = te_forest) +
  annotate("text", x = d100["est"], y = -0.9, label = "delta", vjust = 1.5,
           size = 3, colour = "grey45") +
  coord_cartesian(ylim = c(-1.4, 8)) +
  labs(title = "Profile deviance, hundred-year level",
       x = "return level", y = "profile deviance") +
  theme_te()

ms <- c(20, 50, 100, 200, 500)
band <- do.call(rbind, lapply(ms, function(m) {
  d <- delta_ci(m); p <- profile_ci(m)
  rbind(data.frame(m = m, method = "delta",   est = d["est"], lo = d["lo"], hi = d["hi"]),
        data.frame(m = m, method = "profile", est = p$est,    lo = p$lo,    hi = p$hi))
}))
pB <- ggplot(band, aes(m, est, colour = method, fill = method)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.18, colour = NA) +
  geom_line(linewidth = 0.9) +
  scale_x_log10() +
  scale_colour_manual(values = c(delta = "grey45", profile = te_forest)) +
  scale_fill_manual(values = c(delta = "grey45", profile = te_forest)) +
  labs(title = "Both intervals widen with return period",
       x = "return period (blocks, log scale)", y = "return level") +
  theme_te()
library(grid)
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(pA, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- xi-sensitivity ----
se_xi <- sqrt(cov_nat[3, 3])
z_lo <- qgev(1 - 1 / 100, mu, sigma, xi - se_xi)
z_mid <- qgev(1 - 1 / 100, mu, sigma, xi)
z_hi <- qgev(1 - 1 / 100, mu, sigma, xi + se_xi)

## ---- nonstat ----
nll_ns <- function(par, y, t) {
  b0 <- par[1]; b1 <- par[2]; sg <- exp(par[3]); xn <- par[4]
  mu_t <- b0 + b1 * t; z <- (y - mu_t) / sg
  if (abs(xn) < 1e-6) { ll <- -log(sg) - z - exp(-z) }
  else {
    s <- 1 + xn * z
    if (any(!is.finite(s)) || any(s <= 0)) return(1e10)
    ll <- -log(sg) - (1 / xn + 1) * log(s) - s^(-1 / xn)
  }
  v <- -sum(ll); if (!is.finite(v)) return(1e10); v
}

set.seed(555)
Tn <- 80; tt <- 0:(Tn - 1)
yt <- rgev(Tn, 30 + 0.03 * tt, 1.5, 0.1)       # a genuine warming trend
o_ns <- optim(c(30, 0, log(1.5), 0.1), nll_ns, y = yt, t = tt,
              method = "BFGS", hessian = TRUE)
stopifnot(o_ns$convergence == 0)   # check before inverting the Hessian
se_ns <- sqrt(diag(solve(o_ns$hessian)))
b0 <- o_ns$par[1]; b1 <- o_ns$par[2]
sg_ns <- exp(o_ns$par[3]); xi_ns <- o_ns$par[4]

## ---- moving-level ----
rl_year <- function(year) qgev(1 - 1 / 50, b0 + b1 * year, sg_ns, xi_ns)
z_start <- rl_year(0)
z_end <- rl_year(Tn - 1)

# the start-of-record 50-year level, seen at the end of the record
mu_end <- b0 + b1 * (Tn - 1)
s_end <- 1 + xi_ns * (z_start - mu_end) / sg_ns
p_exceed_end <- 1 - exp(-s_end^(-1 / xi_ns))

## ---- fig-nonstat ----
ts_df <- data.frame(t = tt, y = yt,
                    mu = b0 + b1 * tt,
                    rl = sapply(tt, rl_year))
pC <- ggplot(ts_df, aes(t, y)) +
  geom_point(colour = "grey55", size = 1.5) +
  geom_line(aes(y = mu), colour = te_forest, linewidth = 0.9) +
  geom_line(aes(y = rl), colour = te_gold, linewidth = 0.9) +
  labs(title = "Maxima, trend and moving return level",
       x = "year of record", y = "annual maximum") +
  theme_te()
rp_df <- data.frame(t = tt)
rp_df$rp <- sapply(tt, function(year) {
  mu_y <- b0 + b1 * year
  s <- 1 + xi_ns * (z_start - mu_y) / sg_ns
  1 / (1 - exp(-s^(-1 / xi_ns)))
})
pD <- ggplot(rp_df, aes(t, rp)) +
  geom_line(colour = te_rust, linewidth = 0.9) +
  geom_hline(yintercept = 50, linetype = "dotted", colour = "grey55") +
  labs(title = "Return period of a fixed level, over time",
       x = "year of record", y = "return period (years)") +
  theme_te()
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(pC, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pD, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
