# The CRPS and the Brier score
# https://tidyecology.com/posts/the-crps-and-brier-score/
#
# 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 ----
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))

## ---- brier ----
set.seed(202)
n <- 4000
p_true <- plogis(rnorm(n, 0, 1.3))   # true presence probabilities across sites
y <- rbinom(n, 1, p_true)            # realised presence/absence
p_fore <- p_true                     # a well-calibrated forecast

brier <- function(p, y) mean((p - y)^2)
BS <- brier(p_fore, y)
BS

## ---- brier-decomp ----
K <- 10
bin <- cut(p_fore, breaks = seq(0, 1, length.out = K + 1), include.lowest = TRUE)
obar <- mean(y)
rel <- res <- 0
for (b in levels(bin)) {
  idx <- bin == b; nk <- sum(idx); if (nk == 0) next
  pbar_k <- mean(p_fore[idx]); obar_k <- mean(y[idx])
  rel <- rel + nk / n * (pbar_k - obar_k)^2      # reliability (calibration)
  res <- res + nk / n * (obar_k - obar)^2        # resolution (discrimination)
}
unc <- obar * (1 - obar)                          # uncertainty (base rate)
c(reliability = rel, resolution = res, uncertainty = unc, sum = rel - res + unc,
  binned_brier = mean((ave(p_fore, bin) - y)^2))

## ---- brier-over ----
p_over <- pmin(pmax(1.6 * (p_fore - 0.5) + 0.5, 0), 1)   # sharpen toward the extremes
c(calibrated = brier(p_fore, y), overconfident = brier(p_over, y))

## ---- fig-reliability ----
relib <- function(p, y, K = 10) { b <- cut(p, seq(0, 1, length.out = K + 1), include.lowest = TRUE)
  data.frame(pbar = tapply(p, b, mean), obar = tapply(y, b, mean)) }
d2b <- rbind(cbind(relib(p_fore, y), who = "calibrated"),
             cbind(relib(p_over, y), who = "overconfident"))
ggplot(d2b, aes(pbar, obar, colour = who)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = col_mut) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_colour_manual(values = c(col_main, col_acc), name = NULL) +
  coord_equal(xlim = c(0, 1), ylim = c(0, 1)) +
  labs(title = "Reliability diagram: on the line is calibrated",
       x = "forecast probability", y = "observed frequency") +
  base_th + theme(legend.position = "inside", legend.position.inside = c(0.8, 0.15))

## ---- fig-crps-area ----
mu_f <- 3.0; sig_f <- 1.2; y_val <- 4.1
xg <- seq(-1, 7, length.out = 500)
Fx <- pnorm(xg, mu_f, sig_f); step <- as.numeric(xg >= y_val)
ggplot(data.frame(x = xg, Fx = Fx, step = step), aes(x)) +
  geom_ribbon(aes(ymin = pmin(Fx, step), ymax = pmax(Fx, step)), fill = col_main, alpha = 0.25) +
  geom_line(aes(y = Fx), colour = col_main, linewidth = 1) +
  geom_line(aes(y = step), colour = col_acc, linewidth = 1) +
  geom_vline(xintercept = y_val, linetype = "dashed", colour = col_mut) +
  annotate("text", x = 1.1, y = 0.9, label = "forecast CDF", colour = col_main, hjust = 0) +
  annotate("text", x = 5.2, y = 0.5, label = "step at the outcome", colour = col_acc, hjust = 0) +
  labs(title = "CRPS integrates the squared gap between the CDF and the step",
       x = "abundance", y = "cumulative probability") + base_th

## ---- crps-forms ----
crps_norm <- function(mu, sigma, y) {          # closed form for a Normal forecast
  z <- (y - mu) / sigma
  sigma * (z * (2 * pnorm(z) - 1) + 2 * dnorm(z) - 1 / sqrt(pi))
}
mu_f <- 3.0; sig_f <- 1.2; y_val <- 4.1
cf <- crps_norm(mu_f, sig_f, y_val)

# check it against the definition by direct numerical integration
xg2 <- seq(-60, 60, length.out = 2e6)
nd <- sum((pnorm(xg2, mu_f, sig_f) - as.numeric(xg2 >= y_val))^2) * (xg2[2] - xg2[1])
c(closed_form = cf, numerical = nd)

## ---- crps-pointmass ----
c(crps_pointmass = crps_norm(mu_f, 1e-4, y_val), abs_error = abs(y_val - mu_f))

## ---- crps-ensemble ----
crps_fair <- function(x, y) { m <- length(x)
  mean(abs(x - y)) - 0.5 * sum(outer(x, x, function(a, b) abs(a - b))) / (m * (m - 1)) }
set.seed(2025)
ens <- rnorm(10000, mu_f, sig_f)
c(ensemble = crps_fair(ens, y_val), closed_form = cf)

## ---- crps-brier-link ----
tg <- seq(-60, 60, length.out = 2e6)
crps_via_brier <- sum((pnorm(tg, mu_f, sig_f) - as.numeric(y_val <= tg))^2) * (tg[2] - tg[1])
c(via_threshold_brier = crps_via_brier, closed_form = cf)
