########################################################################
### The Lasso: prediction works, variable selection need not
###
### We simulate from a sparse linear model with a Gaussian design and let
### n, p and the sparsity s grow together.  The design has
###
###  * signal variables Z_1, ..., Z_s, i.i.d. N(0, 1)  (Sigma_SS = I);
###  * ONE "proxy" noise variable
###        X_{s+1} = (r / sqrt(s)) (Z_1 + ... + Z_s) + sqrt(1 - r^2) W,
###    W ~ N(0, 1), so that X_{s+1} has unit variance and correlation
###    r / sqrt(s) with each signal variable;
###  * p - s - 1 further noise variables, i.i.d. N(0, 1).
###
### Consequences:
###  * the minimum eigenvalue of Sigma is exactly 1 - r for every (n, p, s)
###    (the only non-trivial block is the 2 x 2 matrix [1, r; r, 1] on the
###    span of (Z_1 + ... + Z_s)/sqrt(s) and X_{s+1}), so compatibility /
###    restricted eigenvalue conditions hold uniformly and the prediction
###    error should scale like  const * s log(p) / n;
###  * the (population) irrepresentable condition
###        || Sigma_NS Sigma_SS^{-1} sign(beta_S) ||_inf  <  1
###    FAILS as soon as  r * sqrt(s) > 1: for the proxy variable
###        Sigma_NS Sigma_SS^{-1} sign(beta_S) = s * r / sqrt(s) = r sqrt(s).
###    Note the pairwise correlations r / sqrt(s) between the proxy and the
###    signals are small; what matters is the correlation of the proxy with
###    the whole regression function X beta, which is r.  The proxy explains
###    a fraction r^2 of the signal with a single coefficient, which is much
###    cheaper in l_1 than s coefficients, so the Lasso picks it up and
###    variable selection fails -- even with oracle tuning.
########################################################################

library(glmnet)
library(parallel)

## ---- Sequence of problem sizes -------------------------------------
n_vec <- c(100, 200, 400, 800)
p_vec <- c(400, 800, 1600, 3200)
s_vec <- c(4, 8, 16, 32)

## ---- Parameters (change these!) --------------------------------------
r        <- 0.5 # correlation of the proxy with X beta; lambda_min(Sigma) = 1 - r
                # (larger r: selection fails harder, but the MSPE / (s log(p)/n)
                #  ratio at a fixed lambda drifts upwards with s, towards ~ A^2/(1-r^2))
sigma    <- 1   # noise standard deviation
beta_val <- 1   # all signal coefficients equal to beta_val (> 0)
A        <- 1   # lambda = A * sigma * sqrt(log(p) / n)
nrep     <- 100 # repetitions per (n, p, s)

stopifnot(0 <= r, r < 1)
cat("Minimum eigenvalue of Sigma: 1 - r =", 1 - r, "\n")
cat("Irrepresentable constant r * sqrt(s) =", round(r * sqrt(s_vec), 2),
    "(> 1 means the irrepresentable condition fails)\n")

## ---- Simulating the design ------------------------------------------
## Column order: signals 1:s, the proxy (column s + 1), independent noise.
gen_x <- function(n, p, s, r) {
  Z <- matrix(rnorm(n * s), n, s)
  proxy <- (r / sqrt(s)) * rowSums(Z) + sqrt(1 - r^2) * rnorm(n)
  cbind(Z, proxy, matrix(rnorm(n * (p - s - 1)), n, p - s - 1))
}

## ---- One simulation run ---------------------------------------------
## glmnet (with intercept = FALSE, standardize = FALSE) minimises exactly
##     (1/(2n)) ||y - X beta||_2^2 + lambda ||beta||_1
## so lambda is on the same scale as in the lectures.
one_rep <- function(n, p, s, r, sigma, beta_val, A) {
  x <- gen_x(n, p, s, r)
  beta <- c(rep(beta_val, s), rep(0, p - s))
  y <- as.numeric(x[, 1:s] %*% beta[1:s]) + sigma * rnorm(n)

  ## lambda grid: glmnet's usual geometric grid, with the theoretical
  ## lambda = A sigma sqrt(log(p)/n) inserted so we can read it off exactly
  lam_theory <- A * sigma * sqrt(log(p) / n)
  lam_max <- max(abs(crossprod(x, y))) / n
  lam_grid <- exp(seq(log(lam_max), log(min(lam_max, lam_theory) * 1e-2),
                      length.out = 100))
  lam_grid <- sort(unique(c(lam_grid, lam_theory)), decreasing = TRUE)

  fit <- glmnet(x, y, lambda = lam_grid, intercept = FALSE, standardize = FALSE)
  B <- unname(as.matrix(fit$beta))         # p x length(lam_grid)
  i_th <- which.min(abs(fit$lambda - lam_theory))

  ## in-sample prediction error ||X(beta_hat - beta)||^2 / n at each lambda
  mspe <- colMeans((x %*% (B - beta))^2)

  ## variable selection
  supp <- B != 0
  S_hat_eq_S <- colSums(supp[1:s, , drop = FALSE]) == s &
                colSums(supp[-(1:s), , drop = FALSE]) == 0

  c(mspe_theory  = mspe[i_th],                  # at lambda = A sigma sqrt(log p / n)
    mspe_oracle  = min(mspe),                   # best lambda on the path (unattainable)
    exact_theory = S_hat_eq_S[i_th],            # supp(beta_hat) == S at theoretical lambda?
    exact_path   = any(S_hat_eq_S),             # ... at *some* lambda on the path?
    proxy_theory = supp[s + 1, i_th],           # proxy selected at theoretical lambda?
    fp_theory    = sum(supp[-(1:s), i_th]),     # false positives at theoretical lambda
    fn_theory    = s - sum(supp[1:s, i_th]))    # false negatives at theoretical lambda
}

## ---- Run everything in parallel -------------------------------------
cl <- makeCluster(max(1, detectCores() - 1))
invisible(clusterEvalQ(cl, library(glmnet)))
clusterExport(cl, c("gen_x", "one_rep", "r", "sigma", "beta_val", "A"))
clusterSetRNGStream(cl, iseed = 1)

configs <- data.frame(n = n_vec, p = p_vec, s = s_vec)
configs$rate <- with(configs, s * log(p) / n)   # the predicted scale of the MSPE
configs$label <- with(configs, paste0("n=", n, "\np=", p, "\ns=", s))

system.time(
  res <- lapply(seq_len(nrow(configs)), function(i) {
    out <- parSapply(cl, seq_len(nrep), function(j, n, p, s)
      one_rep(n, p, s, r, sigma, beta_val, A),
      n = configs$n[i], p = configs$p[i], s = configs$s[i])
    t(out)   # nrep x (number of metrics)
  })
)
stopCluster(cl)

## ---- Summaries --------------------------------------------------------
summ <- do.call(rbind, lapply(res, colMeans))
summ <- cbind(configs[, c("n", "p", "s", "rate")], summ)
summ$ratio_theory <- summ$mspe_theory / summ$rate
summ$ratio_oracle <- summ$mspe_oracle / summ$rate
print(round(summ, 3), row.names = FALSE)
## mspe_* / rate roughly constant  <=>  MSPE ~ const * s log(p) / n
## exact_*  = estimated probability that the Lasso selects exactly S
## proxy_theory = estimated probability that the proxy is selected

## ---- Plots ------------------------------------------------------------
op <- par(mfrow = c(1, 2), mar = c(5, 4.5, 3, 1))

## 1. Prediction error (in-sample) across the sequence of problems
mspe_th <- lapply(res, function(x) x[, "mspe_theory"])
const_th <- median(unlist(mspe_th) / rep(configs$rate, each = nrep))
boxplot(mspe_th, names = configs$label, col = "lightblue", ylim = c(0, max(unlist(mspe_th))),
        ylab = expression("||X(" * hat(beta) - beta^0 * ")||"[2]^2 / n), xlab = "",
        main = expression("Prediction error at " * lambda == A * sigma * sqrt(log(p) / n)))
lines(seq_along(configs$rate), const_th * configs$rate, col = "red", lwd = 2, type = "b", pch = 19)
legend("topleft", bty = "n", col = "red", lwd = 2, pch = 19,
       legend = sprintf("%.2f * s log(p) / n", const_th))

## 2. Probability of recovering exactly the set of signal variables S
barplot(rbind(summ$exact_theory, summ$exact_path), beside = TRUE,
        names.arg = configs$label, col = c("lightblue", "lightgreen"),
        ylim = c(0, 1), ylab = "Probability", main = expression("P(" * supp(hat(beta)) == S * ")"))
legend("topleft", bty = "n", fill = c("lightblue", "lightgreen"),
       legend = c("at theoretical lambda", "at some lambda on the path"))
par(op)

## ---- A single solution path -------------------------------------------
## Signal variables coloured, the proxy black (dashed), independent noise
## variables grey.  The proxy enters the path first and the signal
## coefficients are heavily shrunk: that is the irrepresentable condition
## failing.
set.seed(2)
n <- n_vec[2]; p <- p_vec[2]; s <- s_vec[2]
x <- gen_x(n, p, s, r)
y <- as.numeric(x[, 1:s] %*% rep(beta_val, s)) + sigma * rnorm(n)
fit <- glmnet(x, y, intercept = FALSE, standardize = FALSE)
col_vec <- c(rainbow(s, end = 0.8), "black", rep(adjustcolor("grey", 0.5), p - s - 1))
lty_vec <- c(rep(1, s), 2, rep(1, p - s - 1))
lwd_vec <- c(rep(2, s), 2, rep(1, p - s - 1))
matplot(x = log(fit$lambda), y = as.matrix(t(fit$beta)), type = "l",
        col = col_vec, lty = lty_vec, lwd = lwd_vec,
        xlab = expression(log(lambda)), ylab = expression(hat(beta)),
        main = sprintf("Lasso path (n=%d, p=%d, s=%d): signals coloured, proxy dashed black", n, p, s))
abline(v = log(A * sigma * sqrt(log(p) / n)), lty = 3)
abline(h = beta_val, lty = 3)
