# Concurvity in additive models
# https://tidyecology.com/posts/concurvity-in-additive-models/
#
# 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-07

## ---- 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_naive <- "#c0622d"
col_corr  <- "#275139"; col_sage <- "#93a87f"

## ---- simulate ----
set.seed(4208)
n <- 400
x1 <- runif(n)
x2 <- cos(2 * pi * x1) + rnorm(n, 0, 0.25)   # a curved function of x1
g  <- function(z) 1.6 * cos(2 * pi * z)      # true effect of x1 only
y  <- g(x1) + rnorm(n, 0, 0.6)               # x2 has no direct effect
d  <- data.frame(x1 = x1, x2 = x2, y = y)

p8_cor <- cor(x1, x2)
p8_vif <- 1 / (1 - summary(lm(x2 ~ x1))$r.squared)   # linear VIF of x2 given x1

## ---- fig-scatter ----
p8_cw <- concurvity(gam(y ~ s(x1) + s(x2), data = d, method = "REML"),
                    full = TRUE)["worst", "s(x2)"]
ggplot(d, aes(x1, x2)) +
  geom_point(colour = col_sage, alpha = 0.6, size = 1.4) +
  annotate("text", x = 0.5, y = 1.75,
           label = sprintf("cor = %.2f    VIF = %.2f    concurvity = %.2f", p8_cor, p8_vif, p8_cw),
           colour = col_truth, size = 3.8) +
  labs(x = "x1", y = "x2", title = "A curved dependence the linear checks miss") +
  theme_te()

## ---- fit-both ----
naive <- gam(y ~ s(x1) + s(x2), data = d, method = "REML")
corr  <- gam(y ~ s(x1),          data = d, method = "REML")
sm <- summary(naive)
p8_edf_x1 <- sm$edf[1]; p8_p_x1 <- sm$s.pv[1]
p8_edf_x2 <- sm$edf[2]; p8_p_x2 <- sm$s.pv[2]

## compare each fit to the true effect on a grid
xg <- seq(0.02, 0.98, length = 100)
gt <- g(xg) - mean(g(x1))                      # centred truth
pn <- predict(naive, data.frame(x1 = xg, x2 = 0), type = "terms")[, "s(x1)"]
pc <- predict(corr,  data.frame(x1 = xg),         type = "terms")[, "s(x1)"]
p8_rmse_naive <- sqrt(mean((pn - gt)^2))
p8_rmse_corr  <- sqrt(mean((pc - gt)^2))

## ---- fig-terms ----
gr <- data.frame(x1 = xg, naive = pn, corr = pc, tru = gt)
ggplot(gr, aes(x1)) +
  geom_line(aes(y = tru),   colour = col_truth, linetype = "dotted", linewidth = 0.9) +
  geom_line(aes(y = naive), colour = col_naive, linewidth = 1) +
  geom_line(aes(y = corr),  colour = col_corr,  linewidth = 1) +
  annotate("text", x = 0.5, y = min(gt) * 1.05,
           label = sprintf("error to truth: naive %.2f, x1-only %.2f",
                           p8_rmse_naive, p8_rmse_corr),
           colour = col_truth, size = 3.6) +
  labs(x = "x1", y = "s(x1)",
       title = "The x1 smooth under both models") +
  theme_te()

## ---- concurvity ----
cfull <- concurvity(naive, full = TRUE)
p8_cw <- cfull["worst", "s(x2)"]; p8_ce <- cfull["estimate", "s(x2)"]

X <- predict(naive, type = "lpmatrix")
idx <- lapply(naive$smooth, function(s) s$first.para:s$last.para)
X2 <- X[, idx[[2]], drop = FALSE]
Xother <- cbind(1, X[, idx[[1]], drop = FALSE])
proj <- Xother %*% solve(crossprod(Xother), t(Xother))
p8_hand <- sum(diag(t(X2) %*% proj %*% X2)) / sum(diag(crossprod(X2)))

## ---- simulations ----
set.seed(7)
Bb <- 300; s2mag <- numeric(Bb)
for (b in 1:Bb) {
  ii <- sample(n, replace = TRUE); db <- d[ii, ]
  mb <- gam(y ~ s(x1) + s(x2), data = db, method = "REML")
  s2mag[b] <- sd(predict(mb, type = "terms")[, "s(x2)"])
}
p8_boot_med <- median(s2mag)
p8_boot_lo  <- quantile(s2mag, 0.05); p8_boot_hi <- quantile(s2mag, 0.95)

set.seed(2020)
Bm <- 500; sig <- 0
for (b in 1:Bm) {
  a1 <- runif(n); a2 <- cos(2 * pi * a1) + rnorm(n, 0, 0.25)
  yy <- g(a1) + rnorm(n, 0, 0.6)
  if (summary(gam(yy ~ s(a1) + s(a2), method = "REML"))$s.pv[2] < 0.05) sig <- sig + 1
}
p8_type1 <- sig / Bm
