# Checking a generalised additive model
# https://tidyecology.com/posts/checking-a-gam/
#
# 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 ----
library(mgcv)
library(nlme)
library(ggplot2)
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#e5e4dc", linewidth = 0.3),
      plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      text      = element_text(colour = "#16241d"),
      axis.text = element_text(colour = "#16241d"),
      plot.title = element_text(face = "bold")
    )
}
col_truth <- "#16241d"; col_naive <- "#c0622d"
col_ok    <- "#275139"; col_sage <- "#93a87f"

## ---- autocorr ----
set.seed(4209)
n <- 200; t <- 1:n
mu <- function(t) 3 * sin(pi * t / n)          # gentle single-hump trend
e  <- as.numeric(arima.sim(n = n, list(ar = 0.7), sd = 0.8))
y  <- mu(t) + e
d  <- data.frame(t = t, y = y)

naive <- gam(y ~ s(t, k = 25), data = d, method = "REML")
gmm   <- gamm(y ~ s(t, k = 25), data = d,
              correlation = corAR1(form = ~ t), method = "REML")

p9_edf_naive <- summary(naive)$edf
p9_edf_gamm  <- summary(gmm$gam)$edf
p9_phi       <- as.numeric(coef(gmm$lme$modelStruct$corStruct, unconstrained = FALSE))
p9_acf_naive <- as.numeric(acf(residuals(naive, type = "deviance"),
                               plot = FALSE, lag.max = 1)$acf[2])
p9_acf_gamm  <- as.numeric(acf(residuals(gmm$lme, type = "normalized"),
                               plot = FALSE, lag.max = 1)$acf[2])
p9_ciw_naive <- 2 * 1.96 * predict(naive,     data.frame(t = n/2), se.fit = TRUE)$se.fit
p9_ciw_gamm  <- 2 * 1.96 * predict(gmm$gam,    data.frame(t = n/2), se.fit = TRUE)$se.fit

## ---- fig-acf ----
al <- 18
an <- acf(residuals(naive, type = "deviance"), plot = FALSE, lag.max = al)
ag <- acf(residuals(gmm$lme, type = "normalized"), plot = FALSE, lag.max = al)
adf <- rbind(
  data.frame(lag = 1:al, acf = an$acf[-1], model = "naive (iid)"),
  data.frame(lag = 1:al, acf = ag$acf[-1], model = "gamm AR(1)"))
ggplot(adf, aes(lag, acf, fill = model)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  geom_hline(yintercept = 0, colour = col_truth) +
  scale_fill_manual(values = c("naive (iid)" = col_naive, "gamm AR(1)" = col_ok)) +
  labs(x = "lag", y = "residual ACF", fill = NULL,
       title = "Residual autocorrelation is the fingerprint") +
  theme_te() +
  theme(legend.position = "top")

## ---- basis-check ----
set.seed(21)
xk <- sort(runif(300))
yk <- sin(2 * pi * xk) + 0.6 * sin(6 * pi * xk) + rnorm(300, 0, 0.3)
m_small <- gam(yk ~ s(xk, k = 5),  method = "REML")
m_big   <- gam(yk ~ s(xk, k = 25), method = "REML")
kc_s <- k.check(m_small); kc_b <- k.check(m_big)
p9_ki5  <- kc_s[1, "k-index"]
p9_ki25 <- kc_b[1, "k-index"]; p9_p25 <- kc_b[1, "p-value"]

## ---- extrapolation ----
set.seed(4219)
xc <- sort(runif(180)); yc <- sin(1.6 * pi * xc) + rnorm(180, 0, 0.4)
dc <- data.frame(x = xc, y = yc)
truef <- function(z) sin(1.6 * pi * z)
m_tp <- gam(y ~ s(x, bs = "tp", k = 15), data = dc, method = "REML")
m_cr <- gam(y ~ s(x, bs = "cr", k = 15), data = dc, method = "REML")

xin <- data.frame(x = seq(0.05, 0.95, length = 60))
p9_in_bases <- max(abs(predict(m_tp, xin) - predict(m_cr, xin)))
p9_in_truth <- sqrt(mean((predict(m_tp, xin) - truef(xin$x))^2))

pe <- predict(m_tp, data.frame(x = 1.30), se.fit = TRUE)
p9_tp13    <- pe$fit
p9_cr13    <- predict(m_cr, data.frame(x = 1.30))
p9_truth13 <- truef(1.30)
p9_lo13    <- pe$fit - 1.96 * pe$se.fit
p9_hi13    <- pe$fit + 1.96 * pe$se.fit

## ---- fig-extrap ----
xg <- data.frame(x = seq(0.02, 1.40, length = 200))
pg <- predict(m_tp, xg, se.fit = TRUE)
pdf <- data.frame(x = xg$x, fit = pg$fit, se = pg$se.fit, tru = truef(xg$x))
ggplot(pdf, aes(x)) +
  geom_ribbon(aes(ymin = fit - 1.96 * se, ymax = fit + 1.96 * se),
              fill = col_sage, alpha = 0.4) +
  geom_point(data = dc, aes(x, y), colour = col_sage, alpha = 0.4, size = 1.1) +
  geom_line(aes(y = tru), colour = col_truth, linetype = "dotted", linewidth = 0.9) +
  geom_line(aes(y = fit), colour = col_ok, linewidth = 1) +
  geom_vline(xintercept = max(xc), colour = col_naive, linetype = "dashed", linewidth = 0.7) +
  coord_cartesian(ylim = c(-4, 3)) +
  labs(x = "covariate x", y = "response y",
       title = "Beyond the data, the fit follows the basis") +
  theme_te()

## ---- edf-spread ----
set.seed(303); B <- 400; edfs <- numeric(B)
for (b in 1:B) {
  xb <- sort(runif(180)); yb <- sin(1.6 * pi * xb) + rnorm(180, 0, 0.4)
  edfs[b] <- summary(gam(yb ~ s(xb, k = 15), method = "REML"))$edf
}
p9_edf_med <- median(edfs)
p9_edf_lo  <- quantile(edfs, 0.05); p9_edf_hi <- quantile(edfs, 0.95)
