# Overdispersion, year noise and a wiggly GAM trend
# https://tidyecology.com/posts/overdispersion-and-a-wiggly-trend/
#
# 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-15

## ---- setup ----
library(ggplot2)
library(patchwork)
library(mgcv)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- design ----
n_yr    <- 30           # years in the series
n_site  <- 15           # plots counted every year
mu0     <- exp(2)       # mean count per plot, about 7.4
k_basis <- 20           # basis dimension of s(year)
n_draw  <- 2000         # coefficient draws for the simultaneous band
n_main  <- 40           # series per main cell, set by the knit-time budget
n_side  <- 20           # series per side cell
grid_yr <- seq(1, n_yr, length.out = 100)
eps     <- 1e-4

phi_of   <- function(size) 1 + mu0 / size
sd_equiv <- function(size, n) sqrt((phi_of(size) - 1) / (n * mu0))
flat <- function(t) 0 * t
hump <- function(t) 0.6 * exp(-((t - 15) / 5)^2)

make_counts <- function(n, size, sd_year, f = flat) {
  yr <- rep(seq_len(n_yr), each = n)
  mu <- exp(log(mu0) + f(yr) + rnorm(n_yr, 0, sd_year)[yr])
  y <- if (is.finite(size)) rnbinom(length(mu), mu = mu, size = size) else rpois(length(mu), mu)
  data.frame(y = y, year = yr, yearf = factor(yr, levels = seq_len(n_yr)))
}

## ---- fits ----
fit_all <- function(d) list(
  poisson = gam(y ~ s(year, k = k_basis), family = poisson, data = d, method = "REML"),
  nb      = gam(y ~ s(year, k = k_basis), family = nb(), data = d, method = "REML"),
  nb_re   = gam(y ~ s(year, k = k_basis) + s(yearf, bs = "re"), family = nb(),
                data = d, method = "REML"),
  fixed9  = gam(y ~ s(year, k = 10, fx = TRUE), family = poisson, data = d))
fit_lab <- c(poisson = "Poisson", nb = "nb()", nb_re = "nb() + year effect",
             fixed9 = "Poisson, 9 fixed df")

## ---- bands ----
nd_base <- data.frame(year = grid_yr, yearf = factor(1, levels = seq_len(n_yr)))
nd_int  <- data.frame(year = seq_len(n_yr), yearf = factor(1, levels = seq_len(n_yr)))

deriv_band <- function(fit) {
  nd_up <- nd_base; nd_up$year <- nd_up$year + eps
  D <- (predict(fit, nd_up, type = "lpmatrix") -
        predict(fit, nd_base, type = "lpmatrix")) / eps
  D[, !grepl("s\\(year\\)", colnames(D))] <- 0
  V <- vcov(fit); d_hat <- drop(D %*% coef(fit)); se <- sqrt(rowSums((D %*% V) * D))
  R <- chol(V + diag(1e-10, nrow(V)))
  Z <- matrix(rnorm(n_draw * nrow(V)), n_draw) %*% R
  crit <- unname(quantile(apply(abs(Z %*% t(D)) / rep(se, each = n_draw), 1, max), 0.95))
  list(d = d_hat, se = se, crit = crit,
       pw = any(abs(d_hat / se) > qnorm(0.975)), sim = any(abs(d_hat / se) > crit),
       edf = sum(fit$edf[grepl("s\\(year\\)", names(fit$edf))]))
}
count_turns <- function(s) sum(diff(sign(diff(s))) != 0)
curve_stats <- function(fit, f) {
  s_int <- predict(fit, nd_int, type = "terms", se.fit = TRUE)
  s_hat <- s_int$fit[, "s(year)"]
  truth <- f(seq_len(n_yr)) - mean(f(seq_len(n_yr)))
  s_grid <- predict(fit, nd_base, type = "terms")[, "s(year)"]
  re15 <- if ("s(yearf).15" %in% names(coef(fit))) unname(coef(fit)["s(yearf).15"]) else 0
  c(range = diff(range(s_hat)), rmse = sqrt(mean((s_hat - truth)^2)),
    se_s = mean(s_int$se.fit[, "s(year)"]), turns = count_turns(s_grid),
    peak = unname(s_hat[15]), low = min(s_hat), re15 = re15)
}

## ---- example ----
set.seed(7300)
ex_list <- list(sites = make_counts(n_site, 1.5, 0),
                years = make_counts(n_site, Inf, sd_equiv(1.5, n_site)))
ex_fits <- lapply(ex_list, function(d) {
  f3 <- fit_all(d)[c("poisson", "nb", "nb_re")]
  f3$quasi <- gam(y ~ s(year, k = k_basis), family = quasipoisson, data = d, method = "REML")
  f3
})
ex_edf <- sapply(ex_fits, function(fl) sapply(fl, function(m)
  sum(m$edf[grepl("s\\(year\\)", names(m$edf))])))
ex_disp <- sapply(ex_fits, function(fl)
  sum(residuals(fl$poisson, type = "pearson")^2) / df.residual(fl$poisson))
ex_theta <- sapply(ex_fits, function(fl) fl$nb$family$getTheta(TRUE))
ex_band <- lapply(ex_fits, function(fl) lapply(fl[c("poisson", "nb", "nb_re")], deriv_band))
ex_flag <- sapply(ex_band, function(bl) sapply(bl, `[[`, "sim"))
ex_flag_pw <- sapply(ex_band, function(bl) sapply(bl, `[[`, "pw"))
ex_disp_p <- sapply(ex_fits, function(fl) pchisq(sum(residuals(fl$poisson, type = "pearson")^2),
                                                 df.residual(fl$poisson), lower.tail = FALSE))
yn <- function(x) if (x) "does" else "does not"
ex_curves <- do.call(rbind, lapply(names(ex_fits), function(src) {
  do.call(rbind, lapply(c("poisson", "nb", "nb_re"), function(fn) {
    p <- predict(ex_fits[[src]][[fn]], nd_base, se.fit = TRUE, exclude = "s(yearf)")
    data.frame(source = src, fit = fn, year = grid_yr, eta = p$fit,
               lo = p$fit - 1.96 * p$se.fit, hi = p$fit + 1.96 * p$se.fit)
  }))
}))
ex_means <- do.call(rbind, lapply(names(ex_list), function(src) {
  a <- aggregate(y ~ year, data = ex_list[[src]], FUN = mean)
  data.frame(source = src, year = a$year, log_mean = log(a$y))
}))

## ---- fig-example ----
ex_curves$fit <- factor(fit_lab[ex_curves$fit], levels = fit_lab[1:3])
src_lab <- c(sites = "Spread between plots (NB size 1.5)",
             years = "Shared year effect (Poisson plots)")
ex_curves$source <- factor(src_lab[ex_curves$source], levels = src_lab)
ex_means$source  <- factor(src_lab[ex_means$source], levels = src_lab)
ggplot(ex_curves, aes(year)) +
  geom_hline(yintercept = log(mu0), colour = te_body, linetype = "dashed", linewidth = 0.4) +
  geom_ribbon(aes(ymin = lo, ymax = hi, fill = fit), alpha = 0.18) +
  geom_line(aes(y = eta, colour = fit), linewidth = 0.9) +
  geom_point(data = ex_means, aes(y = log_mean), colour = te_ink, size = 1.4) +
  facet_wrap(~ source) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_fill_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  labs(x = "year", y = "log mean count",
       title = "A flat truth, read three ways",
       subtitle = "points: log of each year's mean count; dashed: the true level") +
  theme_datasheet() +
  theme(legend.position = "bottom", strip.text = element_text(colour = te_ink, face = "bold"))

## ---- arithmetic ----
set.seed(7311)
n_years_chk <- 20000
ratio_chk <- sapply(c(5, 15, 40), function(n) {
  ybar_nb <- colMeans(matrix(rnbinom(n * n_years_chk, mu = mu0, size = 1.5), n))
  u <- rnorm(n_years_chk, 0, sd_equiv(1.5, n))
  ybar_yr <- colMeans(matrix(rpois(n * n_years_chk, rep(mu0 * exp(u), each = n)), n))
  c(n = n, nb = var(ybar_nb) / (mu0 / n), years = var(ybar_yr) / (mu0 / n),
    sd_eq = sd_equiv(1.5, n))
})

## ---- simulate ----
cells <- data.frame(
  cell = c("NB size 1.5", "NB size 5", "Poisson", "Poisson + year sd 0.211",
           "NB size 5 + year sd 0.3", "Poisson + year sd 0.115", "NB size 5 + year sd 0.15",
           "NB size 1.5, 5 plots", "NB size 1.5, 40 plots", "hump"),
  n = c(15, 15, 15, 15, 15, 15, 15, 5, 40, 15),
  size = c(1.5, 5, Inf, Inf, 5, Inf, 5, 1.5, 1.5, 5),
  sd_year = c(0, 0, 0, sd_equiv(1.5, 15), 0.3, sd_equiv(5, 15), 0.15, 0, 0, 0.15),
  reps = c(rep(n_main, 5), rep(n_side, 5)),
  seed = 7301:7310)

one_series <- function(n, size, sd_year, f = flat) {
  d <- make_counts(n, size, sd_year, f)
  fits <- fit_all(d)
  b <- lapply(fits, deriv_band)
  x2 <- sum(residuals(fits$poisson, type = "pearson")^2)
  disp <- x2 / df.residual(fits$poisson)
  disp_rej <- pchisq(x2, df.residual(fits$poisson), lower.tail = FALSE) < 0.05
  stats <- data.frame(fit = names(fits), edf = sapply(b, `[[`, "edf"),
                      pw = sapply(b, `[[`, "pw"), sim = sapply(b, `[[`, "sim"),
                      disp = disp, disp_rej = disp_rej, row.names = NULL)
  stats <- cbind(stats, t(sapply(fits, curve_stats, f = f)))
  curves <- sapply(fits, function(m) predict(m, nd_base, type = "terms")[, "s(year)"])
  list(stats = stats, curves = curves)
}

sim_out <- lapply(seq_len(nrow(cells)), function(i) {
  set.seed(cells$seed[i])
  f_i <- if (cells$cell[i] == "hump") hump else flat
  lapply(seq_len(cells$reps[i]), function(j) one_series(cells$n[i], cells$size[i],
                                                        cells$sd_year[i], f_i))
})
res <- do.call(rbind, lapply(seq_len(nrow(cells)), function(i)
  do.call(rbind, lapply(seq_along(sim_out[[i]]), function(j)
    cbind(cell = cells$cell[i], rep = j, sim_out[[i]][[j]]$stats)))))

res$turn2 <- res$turns >= 2
tab <- aggregate(cbind(pw, sim, disp, disp_rej, range, rmse, se_s, turns, turn2, peak, low, re15) ~
                   cell + fit, data = res, FUN = mean)
tab$edf <- aggregate(edf ~ cell + fit, data = res, FUN = median)$edf
tab$edf_lo <- aggregate(edf ~ cell + fit, data = res, FUN = quantile, probs = 0.1)$edf
tab$edf_hi <- aggregate(edf ~ cell + fit, data = res, FUN = quantile, probs = 0.9)$edf
g <- function(cell, fit, what) tab[tab$cell == cell & tab$fit == fit, what]
mcse_half <- sqrt(0.25 / n_main)

## ---- fig-rates ----
main_cells <- cells$cell[1:5]
rt <- tab[tab$cell %in% main_cells & tab$fit %in% c("poisson", "nb", "nb_re"), ]
rt$cell <- factor(rt$cell, levels = rev(main_cells))
rt$fit  <- factor(fit_lab[rt$fit], levels = fit_lab[1:3])
rt_long <- rbind(data.frame(rt[, c("cell", "fit")], band = "pointwise", rate = rt$pw),
                 data.frame(rt[, c("cell", "fit")], band = "simultaneous", rate = rt$sim))
rt_long$ypos <- as.numeric(rt_long$cell) + c(0.22, 0, -0.22)[as.numeric(rt_long$fit)]
ggplot(rt_long, aes(rate, ypos, colour = fit)) +
  geom_vline(xintercept = 0.05, colour = te_body, linetype = "dashed", linewidth = 0.4) +
  geom_line(aes(group = interaction(cell, fit)), linewidth = 0.5) +
  geom_point(aes(shape = band), size = 2.6, stroke = 0.9, fill = te_paper) +
  scale_y_continuous(breaks = seq_along(levels(rt$cell)), labels = levels(rt$cell)) +
  scale_shape_manual(values = c(pointwise = 21, simultaneous = 16), name = NULL) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_x_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 1), shape = guide_legend(nrow = 1)) +
  labs(x = "share of flat series flagged as changing", y = NULL,
       title = "False change by source of extra spread",
       subtitle = "dashed: 0.05") +
  theme_datasheet() + theme(legend.position = "bottom", legend.box = "vertical")

## ---- ratio ----
flat_cells <- cells[cells$cell != "hump", ]
phi_c <- ifelse(is.finite(flat_cells$size), phi_of(flat_cells$size), 1)
nms2 <- flat_cells$n * mu0 * flat_cells$sd_year^2
source_c <- ifelse(phi_c > 1 & nms2 > 0, "plots and years",
            ifelse(phi_c > 1, "plots only", ifelse(nms2 > 0, "years only", "none")))
rat <- rbind(
  data.frame(cell = flat_cells$cell, fit = "poisson", ratio = phi_c + nms2, source = source_c),
  data.frame(cell = flat_cells$cell, fit = "nb", ratio = 1 + nms2 / phi_c, source = source_c))
rat$edf <- mapply(function(cc, ff) g(cc, ff, "edf"), rat$cell, rat$fit)
rat_cor <- cor(log(rat$ratio), rat$edf, method = "spearman")
pois_n <- sapply(c("NB size 1.5, 5 plots", "NB size 1.5", "NB size 1.5, 40 plots"), function(cc)
  c(pw = g(cc, "poisson", "pw"), sim = g(cc, "poisson", "sim"), edf = g(cc, "poisson", "edf"),
    reps = cells$reps[cells$cell == cc]))
diff_5_40 <- pois_n["sim", 1] - pois_n["sim", 3]
se_diff_5_40 <- sqrt(sum(pois_n["sim", c(1, 3)] * (1 - pois_n["sim", c(1, 3)]) / pois_n["reps", c(1, 3)]))

## ---- fig-ratio ----
rat$fit <- factor(fit_lab[rat$fit], levels = fit_lab[1:2])
rat$source <- factor(rat$source, levels = c("none", "plots only", "years only", "plots and years"))
ggplot(rat, aes(ratio, edf, colour = fit, shape = source)) +
  geom_point(data = rat[rat$source != "none", ], size = 3, stroke = 1) +
  geom_point(data = rat[rat$source == "none", ], size = 3, stroke = 1,
             position = position_dodge(width = 0.08)) +
  scale_x_log10(breaks = c(1, 1.5, 2.5, 4, 6, 12)) +
  scale_colour_manual(values = c(te_rust, te_gold), name = NULL) +
  scale_shape_manual(values = c("none" = 1, "plots only" = 16, "years only" = 17,
                                "plots and years" = 15), breaks = levels(rat$source), name = NULL) +
  guides(colour = guide_legend(nrow = 1), shape = guide_legend(nrow = 2)) +
  labs(x = "true / claimed variance of a log year mean (log scale)",
       y = "median effective degrees of freedom",
       title = "The smooth sees mainly one ratio, not its source",
       subtitle = "nine flat cells, Poisson and nb() fits") +
  theme_datasheet() + theme(legend.position = "bottom", legend.box = "vertical")

## ---- hump ----
hump_true <- hump(seq_len(n_yr)) - mean(hump(seq_len(n_yr)))
hump_range <- diff(range(hump_true))
hump_turns_true <- count_turns(hump(grid_yr))
hc <- "hump"
se_ratio <- g(hc, "nb_re", "se_s") / g(hc, "nb", "se_s")
hump_curves <- do.call(rbind, lapply(seq_along(sim_out[[10]]), function(j) {
  cv <- sim_out[[10]][[j]]$curves
  do.call(rbind, lapply(c("nb", "nb_re"), function(fn)
    data.frame(rep = j, fit = fn, year = grid_yr, s = cv[, fn])))
}))
truth_grid <- data.frame(year = grid_yr, s = hump(grid_yr) - mean(hump(seq_len(n_yr))))

## ---- fig-hump ----
hump_curves$fit <- factor(fit_lab[hump_curves$fit], levels = fit_lab[2:3])
ggplot(hump_curves, aes(year, s)) +
  geom_line(aes(group = rep, colour = fit), linewidth = 0.45, alpha = 0.7) +
  geom_line(data = truth_grid, colour = te_ink, linewidth = 1.3) +
  facet_wrap(~ fit) +
  scale_colour_manual(values = c(te_gold, te_forest), guide = "none") +
  labs(x = "year", y = "s(year), log scale",
       title = "The year term keeps the hump but lowers its peak",
       subtitle = "thin lines: twenty fitted smooths; thick line: the truth") +
  theme_datasheet() + theme(strip.text = element_text(colour = te_ink, face = "bold"))
