# Peaks over threshold and the GPD
# https://tidyecology.com/posts/peaks-over-threshold-and-the-gpd/
#
# 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

## ---- gpd-helpers ----
library(ggplot2)
dgpd <- function(y, sigma, xi) {
  if (abs(xi) < 1e-8) return((1 / sigma) * exp(-y / sigma))
  t <- 1 + xi * y / sigma
  out <- numeric(length(y)); ok <- t > 0 & y >= 0
  out[ok] <- (1 / sigma) * t[ok]^(-1 / xi - 1)
  out
}
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)

## ---- 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-data ----
set.seed(4247)
n <- 8000
u0 <- 25; sigma0 <- 2.5; xi0 <- 0.15    # true tail above the reference level u0
is_tail <- runif(n) < 0.10
draws <- numeric(0)                       # bulk: Normal(20, 3) truncated below u0
while (length(draws) < sum(!is_tail)) {
  cand <- rnorm(sum(!is_tail), 20, 3)
  draws <- c(draws, cand[cand < u0])
}
x <- numeric(n)
x[!is_tail] <- draws[seq_len(sum(!is_tail))]
x[is_tail]  <- u0 + rgpd(sum(is_tail), sigma0, xi0)

## ---- fit-gpd ----
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)
  se <- sqrt(diag(solve(o$hessian)))
  list(sigma = exp(o$par[1]), xi = o$par[2], se_xi = se[2], nexc = length(y))
}

u  <- 26
exc <- x[x > u] - u
fit <- fit_gpd(exc)
xi_lo <- fit$xi - 1.96 * fit$se_xi
xi_hi <- fit$xi + 1.96 * fit$se_xi

## ---- fig-gpd ----
yy <- seq(0, 14, length.out = 400)
fam <- rbind(
  data.frame(y = yy, d = dgpd(yy, 2.5, 0),     type = "xi = 0 (exponential)"),
  data.frame(y = yy, d = dgpd(yy, 2.5, 0.3),   type = "xi > 0 (heavy)"),
  data.frame(y = yy, d = dgpd(yy, 2.5, -0.3),  type = "xi < 0 (bounded)")
)
bound <- -2.5 / (-0.3)
pA <- ggplot(fam, aes(y, d, colour = type)) +
  geom_line(linewidth = 0.9) +
  geom_vline(xintercept = bound, linetype = "dotted", colour = te_rust) +
  scale_colour_manual(values = c("xi = 0 (exponential)" = "grey35",
                                 "xi > 0 (heavy)" = te_gold,
                                 "xi < 0 (bounded)" = te_forest)) +
  labs(title = "Generalised Pareto: shape sets the tail",
       x = "excess over threshold", y = "density") +
  theme_te() +
  guides(colour = guide_legend(nrow = 2))

grid_y <- seq(0, max(exc) + 1, length.out = 400)
fit_df <- data.frame(y = grid_y, d = dgpd(grid_y, fit$sigma, fit$xi))
pB <- ggplot(data.frame(e = exc), aes(e)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 1, boundary = 0,
                 fill = "grey85", colour = "white") +
  geom_line(data = fit_df, aes(y, d), colour = te_forest, linewidth = 1) +
  labs(title = "Fitted GPD over the exceedances",
       x = "excess over threshold u = 26", 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))

## ---- mrl ----
us <- seq(21, 32, by = 0.5)
mrl <- t(sapply(us, function(uu) {
  e <- x[x > uu] - uu
  c(mean = mean(e), se = sd(e) / sqrt(length(e)))
}))
mrl <- data.frame(u = us, mrl)

## ---- stability ----
uu_grid <- seq(23, 31, by = 1)
stab <- t(sapply(uu_grid, function(uu) {
  g <- fit_gpd(x[x > uu] - uu)
  c(u = uu, xi = g$xi, lo = g$xi - 1.96 * g$se_xi, hi = g$xi + 1.96 * g$se_xi)
}))
stab <- as.data.frame(stab)

## ---- fig-threshold ----
pC <- ggplot(mrl, aes(u, mean)) +
  geom_ribbon(aes(ymin = mean - 1.96 * se, ymax = mean + 1.96 * se),
              fill = "grey85") +
  geom_line(colour = te_forest, linewidth = 0.9) +
  geom_vline(xintercept = 25, linetype = "dashed", colour = te_rust) +
  labs(title = "Mean residual life plot",
       x = "threshold u", y = "mean excess") +
  theme_te()
pD <- ggplot(stab, aes(u, xi)) +
  geom_hline(yintercept = xi0, linetype = "dotted", colour = "grey55") +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.15, colour = "grey70") +
  geom_line(colour = te_gold, linewidth = 0.9) +
  geom_point(colour = te_gold, size = 2) +
  geom_vline(xintercept = 25, linetype = "dashed", colour = te_rust) +
  labs(title = "Shape stability across thresholds",
       x = "threshold u", 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))

## ---- return-level ----
zeta <- mean(x > u)
return_level <- function(years) {
  m <- years * 365
  u + (fit$sigma / fit$xi) * ((m * zeta)^fit$xi - 1)
}
rl10  <- return_level(10)
rl100 <- return_level(100)

## ---- sim-dependent ----
set.seed(9247)
m2 <- 6000; rho <- 0.9
z <- numeric(m2); z[1] <- rnorm(1)
for (t in 2:m2) z[t] <- rho * z[t - 1] + sqrt(1 - rho^2) * rnorm(1)
ud <- 2.0
pz <- pnorm(z)
pex <- pmin(pmax((pz - 0.9) / 0.1, 0), 1 - 1e-9)   # rank inside the top tenth
xd <- ifelse(pz > 0.9, ud + qgpd(pex, 1.5, 0.12),        # true tail shape 0.12
             qnorm(pmin(pz / 0.9, 1) * pnorm(ud), 0, 1)) # bulk stays below ud
exc_idx <- which(xd > ud)

## ---- extremal-index ----
extremal_index <- function(exc_times) {
  s <- diff(exc_times); N <- length(exc_times)
  if (max(s) <= 2) {
    theta <- 2 * sum(s)^2 / ((N - 1) * sum(s^2))
  } else {
    theta <- 2 * sum(s - 1)^2 / ((N - 1) * sum((s - 1) * (s - 2)))
  }
  min(1, theta)
}
theta_hat <- extremal_index(exc_idx)

## ---- decluster ----
r <- 4
cluster_id <- cumsum(c(1, diff(exc_idx) > r))
n_clusters <- length(unique(cluster_id))
peaks <- as.numeric(tapply(xd[exc_idx], cluster_id, max)) - ud

fit_all  <- fit_gpd(xd[exc_idx] - ud)     # naive: every exceedance
fit_peak <- fit_gpd(peaks)                # declustered: cluster peaks only

## ---- fig-decluster ----
win <- 200:600
seg <- data.frame(t = win, x = xd[win])
seg$exc <- seg$x > ud
peak_times <- as.numeric(tapply(exc_idx, cluster_id, function(ix) ix[which.max(xd[ix])]))
seg$peak <- seg$t %in% peak_times & seg$exc
pE <- ggplot(seg, aes(t, x)) +
  geom_line(colour = "grey70", linewidth = 0.4) +
  geom_hline(yintercept = ud, linetype = "dashed", colour = te_rust) +
  geom_point(data = subset(seg, exc & !peak), colour = te_gold, size = 1.4) +
  geom_point(data = subset(seg, peak), colour = te_forest, size = 2.4) +
  labs(title = "Exceedances arrive in clusters",
       x = "day", y = "value") +
  theme_te()
cmp <- data.frame(
  fit = factor(c("all exceedances", "declustered peaks"),
               levels = c("all exceedances", "declustered peaks")),
  xi = c(fit_all$xi, fit_peak$xi),
  lo = c(fit_all$xi - 1.96 * fit_all$se_xi, fit_peak$xi - 1.96 * fit_peak$se_xi),
  hi = c(fit_all$xi + 1.96 * fit_all$se_xi, fit_peak$xi + 1.96 * fit_peak$se_xi))
pF <- ggplot(cmp, aes(fit, xi)) +
  geom_hline(yintercept = 0.12, linetype = "dotted", colour = "grey45") +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.15, colour = "grey60") +
  geom_point(colour = te_forest, size = 3) +
  labs(title = "Naive against declustered fit",
       x = NULL, y = "estimated shape") +
  theme_te()
grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(pE, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pF, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
