# Block maxima and the GEV distribution
# https://tidyecology.com/posts/block-maxima-and-the-gev/
#
# 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-01

## ---- gev-helpers ----
library(ggplot2)

dgev <- function(x, mu, sigma, xi) {
  z <- (x - mu) / sigma
  if (abs(xi) < 1e-8) {
    exp(-z) * exp(-exp(-z)) / sigma
  } else {
    t <- 1 + xi * z
    d <- numeric(length(x))
    ok <- t > 0
    d[ok] <- (1 / sigma) * t[ok]^(-1 / xi - 1) * exp(-t[ok]^(-1 / xi))
    d
  }
}
qgev <- function(p, mu, sigma, xi) {
  if (abs(xi) < 1e-8) mu - sigma * log(-log(p))
  else mu - (sigma / xi) * (1 - (-log(p))^(-xi))
}
rgev <- function(n, mu, sigma, xi) qgev(runif(n), mu, sigma, xi)

# a Weibull-type GEV has a hard ceiling; a Frechet-type one does not
weibull_endpoint <- 31 - 1.6 / (-0.25)

## ---- setup-theme ----
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))
}

## ---- sim-fit ----
nll_gev <- function(par, x) {
  mu <- par[1]; sigma <- exp(par[2]); xi <- par[3]   # log-scale keeps sigma > 0
  z <- (x - mu) / sigma
  if (abs(xi) < 1e-6) {
    ll <- -log(sigma) - z - exp(-z)
  } else {
    t <- 1 + xi * z
    if (any(t <= 0)) return(1e10)
    ll <- -log(sigma) - (1 / xi + 1) * log(t) - t^(-1 / xi)
  }
  -sum(ll)
}
fit_gev <- function(x) {
  s0 <- sd(x) * sqrt(6) / pi                 # moment starts (Gumbel)
  mu0 <- mean(x) - 0.5772 * s0
  o <- optim(c(mu0, log(s0), 0.1), nll_gev, x = x,
             method = "BFGS", hessian = TRUE)
  # a second start: BFGS can stall against the support boundary
  o2 <- optim(c(mu0, log(s0), -0.1), nll_gev, x = x,
              method = "BFGS", hessian = TRUE)
  if (o2$value < o$value) o <- o2
  se <- sqrt(diag(solve(o$hessian)))
  list(mu = o$par[1], sigma = exp(o$par[2]), xi = o$par[3],
       se_mu = se[1], se_xi = se[3])
}

set.seed(4246)
mu_true <- 31.0; sigma_true <- 1.6; xi_true <- 0.13
ymax <- rgev(60, mu_true, sigma_true, xi_true)   # sixty annual maxima
fit <- fit_gev(ymax)
xi_lo <- fit$xi - 1.96 * fit$se_xi
xi_hi <- fit$xi + 1.96 * fit$se_xi

## ---- fig-gev ----
xx <- seq(26, 42, length.out = 400)
fam <- rbind(
  data.frame(x = xx, d = dgev(xx, 31, 1.6, 0),     type = "Gumbel (xi = 0)"),
  data.frame(x = xx, d = dgev(xx, 31, 1.6, 0.35),  type = "Frechet (xi > 0)"),
  data.frame(x = xx, d = dgev(xx, 31, 1.6, -0.25), type = "Weibull (xi < 0)")
)
pA <- ggplot(fam, aes(x, d, colour = type)) +
  geom_line(linewidth = 0.9) +
  geom_vline(xintercept = weibull_endpoint, linetype = "dotted", colour = te_rust) +
  scale_colour_manual(values = c("Gumbel (xi = 0)" = "grey35",
                                 "Frechet (xi > 0)" = te_gold,
                                 "Weibull (xi < 0)" = te_forest)) +
  labs(title = "Three tail types, one shape parameter",
       x = "block maximum", y = "density") +
  theme_te()

grid_x <- seq(min(ymax) - 1, max(ymax) + 3, length.out = 400)
fit_df <- data.frame(x = grid_x,
                     d = dgev(grid_x, fit$mu, fit$sigma, fit$xi))
pB <- ggplot(data.frame(y = ymax), aes(y)) +
  geom_histogram(aes(y = after_stat(density)), bins = 16,
                 fill = "grey85", colour = "white") +
  geom_line(data = fit_df, aes(x, d), colour = te_forest, linewidth = 1) +
  labs(title = "Fitted GEV over sixty annual maxima",
       x = "annual maximum temperature", y = "density") +
  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))

## ---- return-levels ----
return_level <- function(fit, m) qgev(1 - 1 / m, fit$mu, fit$sigma, fit$xi)
rl50  <- return_level(fit, 50)
rl100 <- return_level(fit, 100)
rl50_true  <- qgev(1 - 1 / 50,  mu_true, sigma_true, xi_true)
rl100_true <- qgev(1 - 1 / 100, mu_true, sigma_true, xi_true)

## ---- block-bias ----
set.seed(202)
block_sizes <- c(10, 30, 90, 365, 2000)
bias_tab <- data.frame(block = block_sizes, xi = NA_real_, sd = NA_real_)
for (i in seq_along(block_sizes)) {
  xis <- replicate(30, {
    M <- replicate(400, max(rnorm(block_sizes[i])))
    fit_gev(M)$xi
  })
  bias_tab$xi[i] <- mean(xis)
  bias_tab$sd[i] <- sd(xis)
}
xi_small <- bias_tab$xi[bias_tab$block == 10]
xi_big   <- bias_tab$xi[bias_tab$block == 2000]

## ---- fig-returnbias ----
mgrid <- exp(seq(log(2), log(200), length.out = 120))
rl_df <- data.frame(m = mgrid, z = sapply(mgrid, function(m) return_level(fit, m)))
n <- length(ymax)
emp <- data.frame(z = sort(ymax), p = (seq_len(n) - 0.44) / (n + 0.12))
emp$m <- 1 / (1 - emp$p)
pC <- ggplot(rl_df, aes(m, z)) +
  geom_line(colour = te_forest, linewidth = 1) +
  geom_point(data = emp, aes(m, z), colour = te_rust, size = 1.4, alpha = 0.8) +
  scale_x_log10() +
  labs(title = "Return level plot", x = "return period (years, log scale)",
       y = "return level") +
  theme_te()
pD <- ggplot(bias_tab, aes(block, xi)) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = "grey55") +
  geom_errorbar(aes(ymin = xi - sd, ymax = xi + sd), width = 0.06, colour = "grey70") +
  geom_line(colour = te_gold, linewidth = 0.9) +
  geom_point(colour = te_gold, size = 2) +
  scale_x_log10() +
  labs(title = "Estimated shape against block size",
       x = "block size (log scale)", y = "estimated shape") +
  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))
