# Checking an extreme value model
# https://tidyecology.com/posts/checking-an-extreme-value-model/
#
# 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-06-08

## ---- gof ----
library(ggplot2)
pgev <- function(q, mu, sigma, xi) {
  z <- (q - mu) / sigma
  if (abs(xi) < 1e-6) return(exp(-exp(-z)))
  t <- pmax(1 + xi * z, 0); exp(-t^(-1 / xi))
}
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
}
fit_gev <- function(x) {
  s0 <- sd(x) * sqrt(6) / pi
  o <- optim(c(mean(x) - 0.5772 * s0, log(s0), 0.1), nll_gev,
             x = x, method = "BFGS", hessian = TRUE)
  list(mu = o$par[1], sigma = exp(o$par[2]), xi = o$par[3],
       cov = diag(c(1, exp(o$par[2]), 1)) %*% solve(o$hessian) %*%
             diag(c(1, exp(o$par[2]), 1)))
}

set.seed(4246)
ymax <- rgev(60, 31.0, 1.6, 0.13)
fit <- fit_gev(ymax)

ys <- sort(ymax); n <- length(ys)
emp_p <- (seq_len(n) - 0.5) / n
mod_p <- pgev(ys, fit$mu, fit$sigma, fit$xi)          # PP
mod_q <- qgev(emp_p, fit$mu, fit$sigma, fit$xi)       # QQ
pp_gap <- max(abs(emp_p - mod_p))
qq_cor <- cor(ys, mod_q)

## ---- fig-ppqq ----
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))
}
pp_df <- data.frame(emp = emp_p, mod = mod_p)
pA <- ggplot(pp_df, aes(mod, emp)) +
  geom_abline(slope = 1, intercept = 0, colour = te_rust, linetype = "dashed") +
  geom_point(colour = te_forest, size = 1.6) +
  labs(title = "Probability plot", x = "model probability", y = "empirical probability") +
  theme_te()
qq_df <- data.frame(mod = mod_q, obs = ys)
pB <- ggplot(qq_df, aes(mod, obs)) +
  geom_abline(slope = 1, intercept = 0, colour = te_rust, linetype = "dashed") +
  geom_point(colour = te_forest, size = 1.6) +
  labs(title = "Quantile plot", x = "model quantile", y = "observed maximum") +
  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))

## ---- threshold-sweep ----
qgpd <- function(p, sigma, xi) {
  if (abs(xi) < 1e-8) return(-sigma * log(1 - p))
  (sigma / xi) * ((1 - p)^(-xi) - 1)
}
rgpd <- function(n, sigma, xi) qgpd(runif(n), sigma, xi)
nll_gpd <- function(par, y) {
  sigma <- exp(par[1]); xi <- par[2]
  if (abs(xi) < 1e-8) return(length(y) * log(sigma) + sum(y) / sigma)
  t <- 1 + xi * y / sigma
  if (any(t <= 0)) return(1e10)
  length(y) * log(sigma) + (1 / xi + 1) * sum(log(t))
}
fit_gpd <- function(y) {
  o <- optim(c(log(mean(y)), 0.1), nll_gpd, y = y, method = "BFGS", hessian = TRUE)
  list(sigma = exp(o$par[1]), xi = o$par[2],
       cov = diag(c(exp(o$par[1]), 1)) %*% solve(o$hessian) %*% diag(c(exp(o$par[1]), 1)))
}

set.seed(3249)
Nd <- 9000
is_tail <- runif(Nd) < 0.10
draws <- numeric(0)
while (length(draws) < sum(!is_tail)) {
  cand <- rnorm(sum(!is_tail), 18, 3); draws <- c(draws, cand[cand < 24])
}
xd <- numeric(Nd)
xd[!is_tail] <- draws[seq_len(sum(!is_tail))]
xd[is_tail]  <- 24 + rgpd(sum(is_tail), 2.2, 0.12)

rl_pot <- function(fit, u, zeta, years) {
  m <- years * 365
  u + (fit$sigma / fit$xi) * ((m * zeta)^fit$xi - 1)
}
rl_se <- function(fit, u, zeta, years) {
  m <- years * 365; xi <- fit$xi; s <- fit$sigma; a <- (m * zeta)^xi
  d_s <- (1 / xi) * (a - 1)
  d_x <- s * (-(1 / xi^2) * (a - 1) + (1 / xi) * a * log(m * zeta))
  g <- c(d_s, d_x); sqrt(as.numeric(t(g) %*% fit$cov %*% g))
}

thr <- seq(23, 28, by = 1)
sweep <- do.call(rbind, lapply(thr, function(u) {
  e <- xd[xd > u] - u; fg <- fit_gpd(e); zeta <- mean(xd > u)
  est <- rl_pot(fg, u, zeta, 100); se <- rl_se(fg, u, zeta, 100)
  data.frame(u = u, nexc = length(e), xi = fg$xi,
             est = est, lo = est - 1.96 * se, hi = est + 1.96 * se)
}))

## ---- fig-threshold ----
pT <- ggplot(sweep, aes(u, est)) +
  geom_hline(yintercept = 54.7, linetype = "dotted", colour = te_rust) +
  annotate("text", x = 23, y = 55.4, label = "true level", hjust = 0,
           size = 3.3, colour = te_rust) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.18, colour = "grey65") +
  geom_line(colour = te_forest, linewidth = 0.7) +
  geom_point(colour = te_forest, size = 2.6) +
  labs(title = "Estimated hundred-year level against threshold",
       x = "threshold u", y = "estimated 100-year level") +
  theme_te()
print(pT)

## ---- coverage ----
grad_zm <- function(m, sigma, xi) {
  y <- -log(1 - 1 / m)
  c(1, -(1 / xi) * (1 - y^(-xi)),
    (sigma / xi^2) * (1 - y^(-xi)) - (sigma / xi) * y^(-xi) * log(y))
}
mu_t <- 31; sig_t <- 1.6; xi_t <- 0.13
periods <- c(10, 50, 100, 500)
true_z <- sapply(periods, function(m) qgev(1 - 1 / m, mu_t, sig_t, xi_t))

set.seed(8249)
B <- 600; nblock <- 60
covered <- numeric(length(periods)); width <- numeric(length(periods)); nok <- 0
for (b in seq_len(B)) {
  yb <- rgev(nblock, mu_t, sig_t, xi_t)
  fb <- tryCatch(fit_gev(yb), error = function(e) NULL)
  if (is.null(fb) || any(!is.finite(diag(fb$cov))) || any(diag(fb$cov) < 0)) next
  nok <- nok + 1
  for (j in seq_along(periods)) {
    m <- periods[j]
    est <- qgev(1 - 1 / m, fb$mu, fb$sigma, fb$xi)
    v <- as.numeric(t(grad_zm(m, fb$sigma, fb$xi)) %*% fb$cov %*% grad_zm(m, fb$sigma, fb$xi))
    if (!is.finite(v) || v < 0) next
    se <- sqrt(v)
    if (true_z[j] >= est - 1.96 * se && true_z[j] <= est + 1.96 * se)
      covered[j] <- covered[j] + 1
    width[j] <- width[j] + 2 * 1.96 * se
  }
}
cover_pct <- 100 * covered / nok
mean_width <- width / nok

## ---- fig-coverage ----
cov_df <- data.frame(m = periods, cover = cover_pct, width = mean_width)
pC <- ggplot(cov_df, aes(m, cover)) +
  geom_hline(yintercept = 95, linetype = "dashed", colour = te_rust) +
  annotate("text", x = 10, y = 95.6, label = "nominal 95%", hjust = 0,
           size = 3.2, colour = te_rust) +
  geom_line(colour = te_forest, linewidth = 0.8) +
  geom_point(colour = te_forest, size = 2.6) +
  scale_x_log10() +
  labs(title = "Coverage against return period",
       x = "return period (blocks, log scale)", y = "coverage (%)") +
  coord_cartesian(ylim = c(84, 97)) +
  theme_te()
pD <- ggplot(cov_df, aes(m, width)) +
  geom_line(colour = te_gold, linewidth = 0.8) +
  geom_point(colour = te_gold, size = 2.6) +
  scale_x_log10() +
  labs(title = "Mean interval width against return period",
       x = "return period (blocks, log scale)", y = "mean interval width") +
  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))

## ---- thumb ----
ggsave("thumbnail.png", pC, width = 7.5, height = 5.4, dpi = 100)
