# Checking a penalised regression
# https://tidyecology.com/posts/checking-a-penalised-regression/
#
# 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(ggplot2)

te_ink <- "#275139"; te_naive <- "#b5482a"; te_truth <- "#565656"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size, base_family = "sans") +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = "#3f3f3f"),
          axis.title = element_text(colour = te_ink),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e4dfd4", linewidth = 0.35),
          legend.position = "top")
}
theme_set(theme_te())

set.seed(4213)
n <- 100; p <- 30; sigma <- 2.0
nblk <- 6; blk <- 5
gen_X <- function(n) {
  M <- matrix(rnorm(n * p), n, p)
  for (bb in 1:nblk) { idx <- ((bb - 1) * blk + 1):(bb * blk)
    f <- rnorm(n); M[, idx] <- M[, idx] * sqrt(1 - 0.6^2) + f * 0.6 }   # correlated blocks
  colnames(M) <- paste0("x", 1:p); M
}
X <- gen_X(n)
beta_true <- numeric(p)
beta_true[c(1, 6, 16)] <- c(1.2, 1.0, 0.9)   # strong effects, one per block
beta_true[11] <- 0.5                          # the focal effect: moderate, near the selection boundary
focal <- 11
k_true <- sum(beta_true != 0)
mu <- as.numeric(X %*% beta_true)
cc <- cor(X); b3 <- cc[11:15, 11:15]; blk_cor <- mean(b3[upper.tri(b3)])

## ---- penalty ----
soft <- function(z, g) sign(z) * pmax(abs(z) - g, 0)
gram_of <- function(Xs) crossprod(Xs) / nrow(Xs)
xy_of   <- function(Xs, yc) as.numeric(crossprod(Xs, yc)) / nrow(Xs)
lasso_cov <- function(G, xy, lambda, b0 = NULL, maxit = 5000, tol = 1e-7) {
  p <- length(xy); b <- if (is.null(b0)) numeric(p) else b0
  cvec <- xy - as.numeric(G %*% b)
  for (it in 1:maxit) { dmax <- 0
    for (j in 1:p) { zj <- cvec[j] + b[j]; bn <- soft(zj, lambda); d <- bn - b[j]
      if (d != 0) { cvec <- cvec - G[, j] * d; b[j] <- bn }; dmax <- max(dmax, abs(d)) }
    if (dmax < tol) break }
  b
}
standardise <- function(X) { xm <- colMeans(X); Xc <- sweep(X, 2, xm)
  xn <- sqrt(colMeans(Xc^2)); list(Xs = sweep(Xc, 2, xn, "/"), xm = xm, xn = xn) }
lasso_coef_orig <- function(X, yv, lambda) {
  s <- standardise(X); yc <- yv - mean(yv)
  as.numeric(lasso_cov(gram_of(s$Xs), xy_of(s$Xs, yc), lambda)) / s$xn
}
## fast OLS: coefficients and classical standard errors on a chosen design
ols_cse <- function(Z, yv) {
  ch <- chol(crossprod(Z)); bhat <- backsolve(ch, forwardsolve(t(ch), crossprod(Z, yv)))
  r <- yv - Z %*% bhat; s2 <- sum(r^2) / (nrow(Z) - ncol(Z))
  list(b = as.numeric(bhat), se = sqrt(s2 * diag(chol2inv(ch))))
}

## pilot cross-validation to fix the one-standard-error penalty
set.seed(999); ypilot <- mu + rnorm(n, 0, sigma)
sp <- standardise(X); ycp <- ypilot - mean(ypilot)
lam_max <- max(abs(xy_of(sp$Xs, ycp)))
lam_grid <- exp(seq(log(lam_max), log(lam_max * 1e-3), length.out = 50))
K <- 10; set.seed(1001); fold <- sample(rep(1:K, length.out = n))
cvfold <- function(l, agg) {
  e <- numeric(K)
  for (kk in 1:K) { tr <- fold != kk; te <- !tr
    s <- standardise(X[tr, ]); yct <- ypilot[tr] - mean(ypilot[tr])
    bo <- as.numeric(lasso_cov(gram_of(s$Xs), xy_of(s$Xs, yct), l)) / s$xn
    it <- mean(ypilot[tr]) - sum(bo * s$xm)
    e[kk] <- mean((ypilot[te] - (as.numeric(X[te, , drop = FALSE] %*% bo) + it))^2) }
  agg(e)
}
cvm  <- sapply(lam_grid, cvfold, agg = mean)
cvse <- sapply(lam_grid, cvfold, agg = function(e) sd(e) / sqrt(K))
im <- which.min(cvm); i1 <- min(which(cvm <= cvm[im] + cvse[im]))
lam_1se <- lam_grid[i1]; frac_1se <- lam_1se / lam_max

## ---- mc ----
tq <- function(Z) qt(0.975, nrow(Z) - ncol(Z))   # t quantile on the refit's residual degrees of freedom
M <- 2000; half <- n %/% 2
lambda <- lam_1se
set.seed(4223)
ct <- list(t_sel = 0, tpen = 0, tols = 0, n_sel = 0, npen = 0, nols = 0,
           st_sel = 0, stols = 0, sn_sel = 0, snols = 0,
           f_sel = 0, fpen = 0, fols = 0, fs_sel = 0, fsplit = 0)
fpen_est <- c(); nols_est <- c(); npen_est <- c()
for (m in 1:M) {
  yv <- mu + rnorm(n, 0, sigma)
  ## full-data selection, then refit OLS on the survivors
  bpen <- lasso_coef_orig(X, yv, lambda); S <- which(bpen != 0)
  if (length(S) >= 1) {
    Z <- cbind(1, X[, S, drop = FALSE]); fit <- ols_cse(Z, yv)
    for (t in seq_along(S)) {
      j <- S[t]; bo <- fit$b[t + 1]; se <- fit$se[t + 1]; hw <- tq(Z) * se; tr <- beta_true[j]
      okp <- abs(tr - bpen[j]) <= hw; oko <- abs(tr - bo) <= hw
      if (tr != 0) { ct$t_sel <- ct$t_sel + 1; ct$tpen <- ct$tpen + okp; ct$tols <- ct$tols + oko }
      else { ct$n_sel <- ct$n_sel + 1; ct$npen <- ct$npen + okp; ct$nols <- ct$nols + oko
             if (length(nols_est) < 4000) { nols_est <- c(nols_est, bo); npen_est <- c(npen_est, bpen[j]) } }
      if (j == focal) { ct$f_sel <- ct$f_sel + 1; ct$fpen <- ct$fpen + okp; ct$fols <- ct$fols + oko
                        fpen_est <- c(fpen_est, bpen[j]) }
    }
  }
  ## sample splitting: select on half A, form the interval on half B
  idA <- sample.int(n, half); A <- rep(FALSE, n); A[idA] <- TRUE; Bs <- !A
  SA <- which(lasso_coef_orig(X[A, ], yv[A], lambda) != 0)
  if (length(SA) >= 1) {
    ZB <- cbind(1, X[Bs, SA, drop = FALSE]); fB <- ols_cse(ZB, yv[Bs])
    for (t in seq_along(SA)) {
      j <- SA[t]; ok <- abs(beta_true[j] - fB$b[t + 1]) <= tq(ZB) * fB$se[t + 1]; tr <- beta_true[j]
      if (tr != 0) { ct$st_sel <- ct$st_sel + 1; ct$stols <- ct$stols + ok }
      else { ct$sn_sel <- ct$sn_sel + 1; ct$snols <- ct$snols + ok }
      if (j == focal) { ct$fs_sel <- ct$fs_sel + 1; ct$fsplit <- ct$fsplit + ok }
    }
  }
}
pc <- function(a, b) unname(100 * a / b)
sel_f_pct <- pc(ct$f_sel, M)
cov_f_pen <- pc(ct$fpen, ct$f_sel); cov_f_ols <- pc(ct$fols, ct$f_sel); cov_f_split <- pc(ct$fsplit, ct$fs_sel)
cov_t_pen <- pc(ct$tpen, ct$t_sel); cov_t_ols <- pc(ct$tols, ct$t_sel); cov_t_split <- pc(ct$stols, ct$st_sel)
cov_n_pen <- pc(ct$npen, ct$n_sel); cov_n_ols <- pc(ct$nols, ct$n_sel); cov_n_split <- pc(ct$snols, ct$sn_sel)
mean_f_pen <- mean(fpen_est); mean_n_ols <- mean(nols_est)

## ---- fig-coverage ----
lev_m <- c("naive penalised", "post-selection OLS", "sample-split")
cd <- data.frame(
  type = factor(rep(c("real effect (x11)", "null, once selected"), each = 3),
                levels = c("real effect (x11)", "null, once selected")),
  method = factor(rep(lev_m, 2), levels = lev_m),
  coverage = c(cov_f_pen, cov_f_ols, cov_f_split, cov_n_pen, cov_n_ols, cov_n_split))
ggplot(cd, aes(type, coverage, fill = method)) +
  geom_col(position = position_dodge(width = 0.75), width = 0.68) +
  geom_hline(yintercept = 95, linetype = "dashed", colour = te_truth, linewidth = 0.5) +
  annotate("text", x = 0.62, y = 97.2, label = "95% nominal", hjust = 0, size = 3, colour = te_truth) +
  scale_fill_manual(values = c("naive penalised" = te_naive, "post-selection OLS" = "#c98b3a",
                               "sample-split" = te_ink), name = NULL) +
  scale_y_continuous(limits = c(0, 100)) +
  labs(title = "Naive intervals miss, each in a different place",
       subtitle = "coverage of nominal 95% intervals, conditional on the coefficient being selected",
       x = NULL, y = "coverage (%)")

## ---- fig-winners ----
nd <- rbind(data.frame(est = npen_est, method = "naive penalised"),
            data.frame(est = nols_est, method = "post-selection OLS"))
nd$method <- factor(nd$method, levels = c("naive penalised", "post-selection OLS"))
ggplot(nd, aes(est, fill = method, colour = method)) +
  geom_histogram(aes(y = after_stat(density)), bins = 45, position = "identity",
                 alpha = 0.45, linewidth = 0.2) +
  geom_vline(xintercept = 0, linetype = "dashed", colour = te_truth, linewidth = 0.6) +
  annotate("text", x = 0.02, y = Inf, label = "truth = 0", hjust = 0, vjust = 1.6, size = 3, colour = te_truth) +
  scale_fill_manual(values = c("naive penalised" = te_naive, "post-selection OLS" = "#c98b3a"), name = NULL) +
  scale_colour_manual(values = c("naive penalised" = te_naive, "post-selection OLS" = "#c98b3a"), name = NULL) +
  labs(title = "The winner's curse pushes selected nulls away from zero",
       subtitle = "estimates of truly-zero coefficients on the resamples where the lasso selected them",
       x = "estimated coefficient (truth 0)", y = "density")
