# Scoring ecological forecasts
# https://tidyecology.com/posts/scoring-ecological-forecasts/
#
# 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-09-30

## ---- 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"; col_blu <- "#31688E"
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))

## ---- point-forecast ----
set.seed(101)
mu0 <- 3.0; sigma0 <- 1.0          # the process: next year ~ Normal(mu0, sigma0)
y_obs <- rnorm(2000, mu0, sigma0)  # realised outcomes over many forecast occasions
fc_A <- list(mu = mu0, sd = 0.5)   # confident forecaster
fc_B <- list(mu = mu0, sd = 2.0)   # cautious forecaster

rmse_A <- sqrt(mean((y_obs - fc_A$mu)^2))   # the sd is never read
rmse_B <- sqrt(mean((y_obs - fc_B$mu)^2))
c(rmse_A = rmse_A, rmse_B = rmse_B)

## ---- fig-densities ----
xs <- seq(-2, 8, length.out = 400)
d1 <- data.frame(x = rep(xs, 3),
  dens = c(dnorm(xs, 3, 0.5), dnorm(xs, 3, 1), dnorm(xs, 3, 2)),
  who = rep(c("overconfident (sd 0.5)", "honest (sd 1.0)", "underconfident (sd 2.0)"), each = 400))
d1$who <- factor(d1$who, levels = c("overconfident (sd 0.5)", "honest (sd 1.0)", "underconfident (sd 2.0)"))
ggplot(d1, aes(x, dens, colour = who)) + geom_line(linewidth = 1) +
  geom_vline(xintercept = 3, linetype = "dashed", colour = col_mut) +
  scale_colour_manual(values = c(col_acc, col_main, col_blu), name = NULL) +
  labs(title = "Same mean, different spread", x = "next year's log-abundance", y = "predictive density") +
  base_th + theme(legend.position = "inside", legend.position.inside = c(0.78, 0.8))

## ---- log-score ----
logscore <- function(y, m, s) -dnorm(y, m, s, log = TRUE)
ls_A      <- mean(logscore(y_obs, mu0, 0.5))  # overconfident
ls_B      <- mean(logscore(y_obs, mu0, 2.0))  # underconfident
ls_honest <- mean(logscore(y_obs, mu0, 1.0))  # the honest forecast
c(overconfident = ls_A, honest = ls_honest, underconfident = ls_B)

## ---- propriety ----
elog <- function(s) 0.5 * log(2 * pi) + log(s) + sigma0^2 / (2 * s^2)
sgrid  <- seq(0.3, 3, by = 0.001)
s_star <- sgrid[which.min(elog(sgrid))]   # where the expected log score bottoms out
s_star

## ---- linear-score ----
elin <- function(s) 1 / sqrt(2 * pi * (sigma0^2 + s^2))   # expected linear score
s_lin_best <- sgrid[which.max(elin(sgrid))]
c(best_reported_sd = s_lin_best,
  score_at_0.3 = elin(0.3), score_at_1 = elin(1), score_at_2 = elin(2))

## ---- fig-scores ----
d1b <- data.frame(s = rep(sgrid, 2),
  score = c(elog(sgrid), elin(sgrid)),
  rule = rep(c("log score (proper, lower better)", "linear score (improper, higher better)"), each = length(sgrid)))
d1b$rule <- factor(d1b$rule, levels = c("log score (proper, lower better)",
                                        "linear score (improper, higher better)"))
ggplot(d1b, aes(s, score, colour = rule)) + geom_line(linewidth = 1) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = col_mut) +
  facet_wrap(~rule, scales = "free_y") +
  scale_colour_manual(values = c("log score (proper, lower better)" = col_main,
                                 "linear score (improper, higher better)" = col_acc),
                      guide = "none") +
  labs(title = "A proper rule is optimised at the truth; an improper one is not",
       x = "reported sd (truth = 1, dashed)", y = "expected score") + base_th
