# Forecast skill and the baseline
# https://tidyecology.com/posts/forecast-skill-and-the-baseline/
#
# 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-11-04

## ---- 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)) }

## ---- series ----
simulate_series <- function(phi, sp, m0 = 3, n = 6000, seed = 303) {
  set.seed(seed); x <- numeric(n); x[1] <- m0
  for (t in 2:n) x[t] <- m0 + phi * (x[t - 1] - m0) + rnorm(1, 0, sp)
  x
}
x <- simulate_series(phi = 0.85, sp = 0.5)   # strongly autocorrelated series

## ---- fig-series ----
win <- 40:80
ggplot(data.frame(t = win, obs = x[win]), aes(t, obs)) +
  geom_line(colour = col_mut) + geom_point(colour = col_main, size = 1.6) +
  labs(title = "An autocorrelated log-abundance series (phi = 0.85)",
       x = "time step", y = "log-abundance") + base_th

## ---- score-forecasts ----
score_forecasts <- function(phi_true, sp = 0.5, phi_model = 0.4, m0 = 3) {
  x <- simulate_series(phi_true, sp, m0); n <- length(x); idx <- 2:n
  smarg <- sp / sqrt(1 - phi_true^2)                         # stationary marginal sd
  mu_m <- m0 + phi_model * (x[idx - 1] - m0)                 # the model (too little memory)
  s_m  <- smarg * sqrt(1 - phi_model^2)
  sdiff <- sp * sqrt(2 / (1 + phi_true))                     # sd of the year-to-year change
  y <- x[idx]
  c(model = mean(crps_norm(mu_m, s_m, y)),
    clim  = mean(crps_norm(rep(m0, length(idx)), rep(smarg, length(idx)), y)),   # climatology
    pers  = mean(crps_norm(x[idx - 1], rep(sdiff, length(idx)), y)))             # persistence
}
skill <- function(s_fore, s_ref) 1 - s_fore / s_ref

S <- score_forecasts(phi_true = 0.85)
c(S, skill_vs_clim = skill(S["model"], S["clim"]),
     skill_vs_pers = skill(S["model"], S["pers"]))

## ---- skill-sweep ----
phis <- seq(0.05, 0.95, by = 0.05)
sk <- t(sapply(phis, function(ph) {
  s <- score_forecasts(ph)
  c(vs_clim = skill(s["model"], s["clim"]), vs_pers = skill(s["model"], s["pers"]))
}))
head(round(sk, 3))

## ---- fig-skill ----
d3 <- data.frame(phi = rep(phis, 2), skill = c(sk[, 1], sk[, 2]),
  baseline = rep(c("vs climatology", "vs persistence"), each = length(phis)))
ggplot(d3, aes(phi, skill, colour = baseline)) +
  geom_hline(yintercept = 0, colour = col_mut) +
  geom_line(linewidth = 1) + geom_point(size = 1.6) +
  geom_vline(xintercept = 0.85, linetype = "dashed", colour = col_mut) +
  scale_colour_manual(values = c(col_main, col_acc), name = NULL) +
  labs(title = "The same forecast: skilful or useless depends on the baseline",
       x = "true autocorrelation of the series (phi)", y = "skill score") +
  base_th + theme(legend.position = "inside", legend.position.inside = c(0.5, 0.15))
