# Checking predictive calibration and coverage
# https://tidyecology.com/posts/checking-predictive-calibration/
#
# 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

## ---- setup ----
set.seed(4221)
f_true <- function(x) 0.40 + 1.2*x - 1.0*x^2 + 0.30*sin(3*x)
sigma0 <- 0.35                                                # homoscedastic observation noise
gen    <- function(n){ x <- runif(n); data.frame(x = x, y = f_true(x) + rnorm(n, 0, sigma0)) }

trf <- gen(150); trc <- gen(1000); te <- gen(6000)           # fit / calibrate / test
mf  <- lm(y ~ poly(x, 6), data = trf)
pse   <- predict(mf, newdata = data.frame(x = te$x), se.fit = TRUE)
mu_te <- as.numeric(pse$fit); se_mean <- as.numeric(pse$se.fit)   # SE of the fitted MEAN
res_c <- abs(trc$y - as.numeric(predict(mf, newdata = data.frame(x = trc$x))))  # conformal scores

levs <- seq(0.50, 0.95, 0.05)
cov_naive <- sapply(levs, function(L){ z <- qnorm(1 - (1-L)/2); mean(abs(te$y - mu_te) <= z*se_mean) })
cov_conf  <- sapply(levs, function(L){ k <- ceiling(L*(nrow(trc)+1)); q <- sort(res_c)[min(k, length(res_c))]
                                       mean(abs(te$y - mu_te) <= q) })
i90 <- which(abs(levs - 0.90) < 1e-6)

## ---- pit ----
pit_naive  <- pnorm((te$y - mu_te)/se_mean)                  # naive predictive N(mu, se_mean)
pit_oracle <- pnorm((te$y - f_true(te$x))/sigma0)            # an oracle predictive: should be uniform
ext <- function(p) mean(p < 0.05 | p > 0.95)                 # mass in the extreme 10% of the scale
ext_naive <- ext(pit_naive); ext_oracle <- ext(pit_oracle)

## ---- fig-intervals ----
suppressPackageStartupMessages(library(ggplot2))
theme_te <- function() theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
        axis.title = element_text(colour = "#2c3a31"), axis.text = element_text(colour = "#5d6b61"),
        plot.subtitle = element_text(colour = "#46604a", size = 10),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))
forest <- "#275139"; terra <- "#b5534e"
dc <- rbind(data.frame(nom = levs, emp = cov_naive, m = "naive confidence band"),
            data.frame(nom = levs, emp = cov_conf, m = "split conformal"))
pA <- ggplot(dc, aes(nom, emp, colour = m)) +
  geom_abline(slope = 1, intercept = 0, colour = "#5d6b61", linetype = "dashed") +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_colour_manual(values = c(`split conformal` = forest, `naive confidence band` = terra)) +
  coord_equal() + labs(x = "nominal coverage", y = "empirical coverage", colour = NULL,
                       subtitle = "(A) interval coverage calibration") +
  theme_te() + theme(legend.position = "bottom", legend.direction = "vertical")
dp <- rbind(data.frame(pit = pit_naive, m = "naive (over-confident)"),
            data.frame(pit = pit_oracle, m = "oracle (calibrated)"))
pB <- ggplot(dp, aes(pit)) +
  geom_histogram(aes(y = after_stat(density)), breaks = seq(0,1,0.1),
                 fill = "#93a87f", colour = "white") +
  geom_hline(yintercept = 1, colour = "#5d6b61", linetype = "dashed") +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  facet_wrap(~ m) + labs(x = "PIT value", y = "density", subtitle = "(B) PIT histograms") +
  theme_te() + theme(strip.text = element_text(colour = "#2c3a31", size = 9),
                     panel.spacing = grid::unit(1, "lines"))
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- probability ----
gx <- runif(4000); ptrue <- plogis(-1.0 + 3.0*gx)            # true presence probability
yb <- rbinom(length(gx), 1, ptrue)
base  <- glm(yb ~ gx, family = binomial)                     # a calibrated base model
pbase <- as.numeric(predict(base, type = "response"))
pover <- pbase^2.4 / (pbase^2.4 + (1-pbase)^2.4)             # sharpened: overconfident
z_over <- qlogis(pmin(pmax(pover, 1e-4), 1-1e-4))            # recalibrate (Platt: intercept and slope)
platt <- glm(yb ~ z_over, family = binomial); pcal <- as.numeric(predict(platt, type = "response"))

reld <- function(p, y, B = 10){
  b <- cut(p, seq(0,1,length.out = B+1), include.lowest = TRUE)
  data.frame(pbar = tapply(p, b, mean), obs = tapply(y, b, mean))
}
brier_decomp <- function(p, y, B = 10){
  b <- cut(p, seq(0,1,length.out = B+1), include.lowest = TRUE)
  nk <- tapply(y, b, length); pk <- tapply(p, b, mean); ok <- tapply(y, b, mean)
  k <- !is.na(nk); N <- sum(nk[k]); obar <- mean(y)
  c(reliability = sum(nk[k]*(pk[k]-ok[k])^2)/N, resolution = sum(nk[k]*(ok[k]-obar)^2)/N,
    brier = mean((p - y)^2))
}
bd_over <- brier_decomp(pover, yb); bd_cal <- brier_decomp(pcal, yb)

## ---- fig-reliability ----
ro <- reld(pover, yb); rc <- reld(pcal, yb)
ro <- ro[!is.na(ro$pbar), ]; rc <- rc[!is.na(rc$pbar), ]
rel <- rbind(cbind(ro, m = "overconfident"), cbind(rc, m = "recalibrated"))
rA <- ggplot(rel, aes(pbar, obs, colour = m)) +
  geom_abline(slope = 1, intercept = 0, colour = "#5d6b61", linetype = "dashed") +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_colour_manual(values = c(overconfident = terra, recalibrated = forest)) +
  coord_equal(xlim = c(0,1), ylim = c(0,1)) +
  labs(x = "mean predicted probability", y = "observed frequency", colour = NULL,
       subtitle = "(A) reliability diagram") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.68, 0.16),
                     legend.background = element_rect(fill = "white", colour = "#dad9ca"))
bd <- rbind(data.frame(comp = c("reliability","resolution"),
                       val = c(bd_over["reliability"], bd_over["resolution"]), m = "overconfident"),
            data.frame(comp = c("reliability","resolution"),
                       val = c(bd_cal["reliability"], bd_cal["resolution"]), m = "recalibrated"))
rB <- ggplot(bd, aes(comp, val, fill = m)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  scale_fill_manual(values = c(overconfident = terra, recalibrated = forest)) +
  labs(x = NULL, y = "component of the Brier score", fill = NULL,
       subtitle = "(B) Brier decomposition") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.72, 0.85),
                     legend.background = element_rect(fill = "white", colour = "#dad9ca"))
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(rA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(rB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
