# Choosing the basis dimension k in mgcv
# https://tidyecology.com/posts/choosing-basis-dimension-k/
#
# 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-14

## ---- setup ----
library(mgcv)
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),
      strip.text = element_text(colour = "#16241d", face = "bold"),
      text      = element_text(colour = "#16241d"),
      axis.text = element_text(colour = "#16241d"),
      plot.title = element_text(face = "bold")
    )
}
col_truth <- "#16241d"; col_low <- "#c0622d"
col_ok    <- "#275139"; col_sage <- "#93a87f"

## ---- k-ladder ----
set.seed(4207)
n <- 300
x <- sort(runif(n))
f <- function(x) sin(2 * pi * x) + 0.6 * sin(6 * pi * x)
sigma <- 0.3
y <- f(x) + rnorm(n, 0, sigma)
d <- data.frame(x = x, y = y)
truef <- f(x)
rmse  <- function(fit) sqrt(mean((fit - truef)^2))

ks <- c(4, 6, 8, 12, 16, 24, 32)
res <- lapply(ks, function(k) {
  m  <- gam(y ~ s(x, bs = "tp", k = k), data = d, method = "REML")
  kc <- k.check(m)
  data.frame(k = k, edf = summary(m)$edf, rmse = rmse(fitted(m)),
             ceiling = k - 1, kindex = kc[1, "k-index"], kp = kc[1, "p-value"])
})
res <- do.call(rbind, res)

## ---- pull-numbers ----
g <- function(kk, col) res[[col]][res$k == kk]
p7_edf4  <- g(4,"edf");  p7_rmse4 <- g(4,"rmse");  p7_ki4  <- g(4,"kindex")
p7_edf8  <- g(8,"edf");  p7_rmse8 <- g(8,"rmse");  p7_ki8  <- g(8,"kindex");  p7_p8 <- g(8,"kp")
p7_edf24 <- g(24,"edf"); p7_rmse24<- g(24,"rmse"); p7_ki24 <- g(24,"kindex"); p7_p24<- g(24,"kp")
p7_edf32 <- g(32,"edf"); p7_rmse32<- g(32,"rmse")

## ---- fig-fits ----
m4  <- gam(y ~ s(x, bs = "tp", k = 4),  data = d, method = "REML")
m24 <- gam(y ~ s(x, bs = "tp", k = 24), data = d, method = "REML")
gr <- data.frame(x = seq(min(x), max(x), length = 400))
gr$k4  <- predict(m4,  gr); gr$k24 <- predict(m24, gr); gr$tru <- f(gr$x)
ggplot() +
  geom_point(data = d, aes(x, y), colour = col_sage, alpha = 0.5, size = 1.3) +
  geom_line(data = gr, aes(x, tru), colour = col_truth, linetype = "dotted", linewidth = 0.8) +
  geom_line(data = gr, aes(x, k4),  colour = col_low, linewidth = 1) +
  geom_line(data = gr, aes(x, k24), colour = col_ok,  linewidth = 1) +
  labs(x = "x", y = "y", title = "Too small a basis smooths away real structure") +
  theme_te()

## ---- hand-kindex ----
hand_kindex <- function(m) {
  e  <- residuals(m, type = "deviance")
  eo <- e[order(d$x)]
  mean(diff(eo)^2) / (2 * var(e))
}
p7_hk4  <- hand_kindex(m4)
p7_hk24 <- hand_kindex(m24)

## ---- fig-plateau ----
long <- rbind(
  data.frame(k = res$k, value = res$rmse, panel = "error to truth"),
  data.frame(k = res$k, value = res$edf,  panel = "effective df"))
ceil <- data.frame(k = res$k, value = res$ceiling, panel = "effective df")
ggplot(long, aes(k, value)) +
  geom_line(colour = col_ok, linewidth = 1) +
  geom_point(colour = col_ok, size = 1.8) +
  geom_line(data = ceil, aes(k, value), colour = col_low,
            linetype = "dashed", linewidth = 0.7) +
  facet_wrap(~panel, ncol = 1, scales = "free_y") +
  labs(x = "basis dimension k", y = NULL,
       title = "Fit plateaus; effective df stays under the ceiling") +
  theme_te()

## ---- time-covariate ----
set.seed(2609)
tk_fit <- function(phi, k, in_time) {
  e  <- if (phi == 0) rnorm(n, 0, sigma) else
    as.numeric(arima.sim(list(ar = phi), n, sd = sigma * sqrt(1 - phi^2)))
  xs <- if (in_time) sort(runif(n)) else runif(n)  # rows stay in visit order
  ys <- f(xs) + e; m <- gam(ys ~ s(xs, bs = "tp", k = k), method = "REML")
  kc <- k.check(m); r <- residuals(m); ro <- r[order(xs)]
  c(flag = kc[1, "k-index"] < 1 && kc[1, "p-value"] < 0.05,
    kindex = kc[1, "k-index"], dw_mgcv = mean(diff(ro)^2) / 2 / mean(r^2),
    one_minus_r1 = 1 - cor(ro[-1], ro[-n]), r1_visits = cor(r[-1], r[-n]),
    edf = kc[1, "edf"], rmse = sqrt(mean((fitted(m) - f(xs))^2)))
}
tk_cells <- data.frame(covariate = rep(c("time", "not time"), c(6, 2)),
  phi = c(0, 0.5, 0.5, 0.8, 0.8, 0.8, 0.5, 0.8), k = c(16, 16, 40, 16, 40, 80, 16, 16))
tk_sims <- lapply(seq_len(nrow(tk_cells)), function(i) t(replicate(60,
  tk_fit(tk_cells$phi[i], tk_cells$k[i], tk_cells$covariate[i] == "time"))))
tk_tab <- cbind(tk_cells, t(sapply(tk_sims, function(s) round(c(
  flagged = mean(s[, "flag"]), apply(s[, c("kindex", "one_minus_r1",
  "r1_visits", "edf", "rmse")], 2, median)), 3))))
print(tk_tab, row.names = FALSE)

## ---- time-covariate-numbers ----
tk_all <- do.call(rbind, tk_sims); tk_r4 <- residuals(m4, type = "deviance")
stopifnot(max(abs(tk_all[, "kindex"] - tk_all[, "dw_mgcv"])) < 1e-8,
          isTRUE(all.equal(p7_hk4, sum(diff(tk_r4[order(d$x)])^2) / (2 * sum(tk_r4^2)))))
tk_gap <- max(abs(tk_all[, "kindex"] - tk_all[, "one_minus_r1"]))
tk_n <- function(i) sum(tk_sims[[i]][, "flag"]); tk_v <- function(i, col) tk_tab[[col]][i]
tk_ci80 <- binom.test(60 - tk_n(6), 60)$conf.int
stopifnot(tk_n(1) == 0, sapply(2:6, tk_n) == 60, diff(tk_tab$edf[4:6]) > 0,
          diff(tk_tab$rmse[4:6]) > 0, diff(tk_tab$kindex[4:6]) > 0, diff(tk_tab$one_minus_r1[4:6]) > 0)

## ---- time-covariate-gamm ----
set.seed(2610)
tk_err   <- function(m, xs) sqrt(mean((fitted(m) - f(xs))^2))
tk_cover <- function(m, xs) with(predict(m, se.fit = TRUE), mean(abs(fit - f(xs)) < 1.96 * se.fit))
tk_gamm <- t(replicate(20, {
  xs <- sort(runif(n))
  ys <- f(xs) + as.numeric(arima.sim(list(ar = 0.5), n, sd = sigma * sqrt(1 - 0.5^2)))
  plain <- gam(ys ~ s(xs, k = 16), method = "REML")
  naive <- gam(ys ~ s(xs, k = 40), method = "REML")
  ar1   <- gamm(ys ~ s(xs, k = 40), correlation = nlme::corAR1(form = ~ 1), method = "REML")
  kc <- k.check(ar1$gam)[1, ]; rn <- residuals(ar1$lme, type = "normalized")
  c(edf_naive = sum(naive$edf[-1]), edf_ar1 = sum(ar1$gam$edf[-1]), rmse_naive = tk_err(naive, xs),
    rmse_16 = tk_err(plain, xs), rmse_ar1 = tk_err(ar1$gam, xs), cover_16 = tk_cover(plain, xs),
    cover_ar1 = tk_cover(ar1$gam, xs), r1_norm = cor(rn[-1], rn[-n]),
    flag_ar1 = kc[["k-index"]] < 1 && kc[["p-value"]] < 0.05,
    phi_hat = coef(ar1$lme$modelStruct$corStruct, unconstrained = FALSE)[[1]])
}))
tk_med <- apply(tk_gamm, 2, median); tk_mean <- colMeans(tk_gamm)
tk_better <- with(as.data.frame(tk_gamm), c(sum(rmse_ar1 < rmse_naive), sum(rmse_ar1 < rmse_16)))
stopifnot(tk_mean[["cover_ar1"]] > tk_mean[["cover_16"]], tk_mean[["flag_ar1"]] > 0.5,
          abs(tk_med[["r1_norm"]]) < 0.1, with(as.list(tk_med), abs(rmse_16 - rmse_ar1) < 0.01 &
          rmse_naive - rmse_16 > (rmse_naive - rmse_ar1) / 2))
