# Checking a forecast evaluation
# https://tidyecology.com/posts/checking-a-forecast-evaluation/
#
# 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-15

## ---- setup ----
suppressMessages(library(ggplot2))
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
col_main <- "#275139"; col_acc <- "#B5651D"; col_mut <- "#8C8C8C"
base_th <- theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 13),
        axis.title = element_text(size = 11))
crps_norm <- function(mu, sigma, y) { z <- (y - mu) / sigma
  sigma * (z * (2 * pnorm(z) - 1) + 2 * dnorm(z) - 1 / sqrt(pi)) }

## ---- coverage ----
set.seed(909)
mu_t <- 3; sig0 <- 1
y <- rnorm(5000, mu_t, sig0)
cover90 <- function(mu, s, y) { lo <- qnorm(0.05, mu, s); hi <- qnorm(0.95, mu, s)
  mean(y >= lo & y <= hi) }

honest <- c(coverage = cover90(mu_t, sig0, y),     crps = mean(crps_norm(mu_t, sig0, y)))
wide   <- c(coverage = cover90(mu_t, 4 * sig0, y), crps = mean(crps_norm(mu_t, 4 * sig0, y)))
rbind(honest, wide)

## ---- fig-coverage ----
d4l <- data.frame(
  forecast = rep(c("honest", "wide (4x sd)"), 2),
  metric = rep(c("coverage", "crps"), each = 2),
  val = c(honest["coverage"], wide["coverage"], honest["crps"], wide["crps"]))
ggplot(d4l, aes(forecast, val, fill = forecast)) + geom_col(width = 0.6) +
  facet_wrap(~metric, scales = "free_y") +
  scale_fill_manual(values = c(col_main, col_acc), guide = "none") +
  labs(title = "Ranking by coverage picks the worse (wider) forecast", x = NULL, y = NULL) + base_th

## ---- sharpness ----
set.seed(919)
y2 <- rnorm(5000, mu_t, sig0)
width90 <- function(s) qnorm(0.95, 0, s) - qnorm(0.05, 0, s)
pit <- function(mu, s, y) pnorm(y, mu, s)

honest_s <- c(width = width90(sig0),       crps = mean(crps_norm(mu_t, sig0, y2)),
              tail = mean(pit(mu_t, sig0, y2) < 0.05 | pit(mu_t, sig0, y2) > 0.95))
sharp_s  <- c(width = width90(0.5 * sig0), crps = mean(crps_norm(mu_t, 0.5 * sig0, y2)),
              tail = mean(pit(mu_t, 0.5 * sig0, y2) < 0.05 | pit(mu_t, 0.5 * sig0, y2) > 0.95))
rbind(honest_s, sharp_s)

## ---- fig-pit ----
n2 <- length(y2)
d4b <- data.frame(pit = c(pit(mu_t, sig0, y2), pit(mu_t, 0.5 * sig0, y2)),
  who = rep(c("calibrated", "overconfident (sharp)"), each = n2))
ggplot(d4b, aes(pit)) +
  geom_histogram(aes(fill = who), bins = 20, boundary = 0, colour = "white") +
  geom_hline(yintercept = n2 / 20, linetype = "dashed", colour = col_mut) +
  facet_wrap(~who) +
  scale_fill_manual(values = c(col_main, col_acc), guide = "none") +
  labs(title = "PIT histogram: flat is calibrated, U-shape is overconfident",
       x = "probability integral transform", y = "count") + base_th

## ---- diffci ----
crps_diff_ci <- function(ntest, seed, B = 4000) {
  set.seed(seed)
  yy <- rnorm(ntest, mu_t, sig0)
  d <- crps_norm(mu_t, 1.4 * sig0, yy) - crps_norm(mu_t, sig0, yy)   # B minus A, positive = A better
  bs <- replicate(B, mean(sample(d, replace = TRUE)))
  c(mean = mean(d), lo = quantile(bs, 0.025), hi = quantile(bs, 0.975))
}
t(sapply(c(10, 30, 100, 300), function(nt) crps_diff_ci(nt, seed = 1000 + nt)))

## ---- fig-diffci ----
ns <- c(10, 30, 100, 300)
M <- t(sapply(ns, function(nt) crps_diff_ci(nt, 1000 + nt)))
d4c <- data.frame(n = factor(ns), mean = M[, 1], lo = M[, 2], hi = M[, 3])
ggplot(d4c, aes(n, mean)) +
  geom_hline(yintercept = 0, colour = col_mut) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.2, colour = col_main) +
  geom_point(size = 2.4, colour = col_main) +
  labs(title = "Small test sets may not tell two forecasts apart",
       x = "number of forecast-observation pairs", y = "mean CRPS difference (B - A)") + base_th
