# The simulations and data behind the week's deck (slides/11-1-representations.qmd) and reading note
# (effects-features.qmd). Both documents run this file, so they quote the same numbers. set.seed(310) in
# run_sims() is the one seed for both.
#
# The random part takes about six minutes, so its results, and the state of the random number generator
# after it, are saved in _sims.rds and reloaded while this file is unchanged (delete _sims.rds to run it
# again). A document that draws random numbers after sourcing this file gets the same draws either way.
# The documents are frozen (_freeze/) on their own source only: after changing this file, render both again.
library(tidyverse)
library(gapminder)
library(randomForest)
library(nnet)

## Settings and functions (no random numbers) ------------------------------------------------------------

# Double ML on simulated data from a partially linear model with theta = 1.
# Z has five inputs; m (the treatment model) uses z1 and z2, g uses z1, z2 and z3.
theta <- 1; q_z <- 5; n_dml <- 500; R_dml <- 100
plm <- function(n) {
  Z <- matrix(rnorm(n * q_z), n, dimnames = list(NULL, paste0("z", 1:q_z)))
  m <- sin(2 * Z[, 1]) + Z[, 2]^2 / 2 - 1 / 2
  g <- cos(2 * Z[, 1]) + Z[, 2]^2 + Z[, 3] / 2
  T <- m + rnorm(n)
  list(Z = Z, T = T, Y = theta * T + g + rnorm(n))
}
# Residual on residual: a regression through the origin, with the heteroskedasticity-robust standard error,
# and the root mean squares of the two residuals (each learner's prediction error, when the residuals are
# from fits to other rows).
ror <- function(ry, rt) {
  est <- sum(rt * ry) / sum(rt^2); e <- ry - est * rt
  c(est = est, se = sqrt(sum(rt^2 * e^2)) / sum(rt^2), rmse_y = sqrt(mean(ry^2)), rmse_t = sqrt(mean(rt^2)))
}
# The learner for both nuisance functions: bagged trees (a forest that may split on any input); a node of 20 rows or fewer is not split.
learner <- function(Z, v) randomForest(Z, v, ntree = 100, mtry = q_z, nodesize = 20)
crossfit <- function(Z, v, fold) {   # each row predicted by a fit to the other folds
  out <- numeric(length(v))
  for (k in unique(fold)) out[fold == k] <- predict(learner(Z[fold != k, ], v[fold != k]), Z[fold == k, ])
  out
}
mean_cf <- function(v, fold) {   # each row predicted by the mean of the other folds
  out <- numeric(length(v))
  for (k in unique(fold)) out[fold == k] <- mean(v[fold != k])
  out
}
linear_cf <- function(Z, v, fold) {   # the same, with linear regression as the learner (no random numbers)
  out <- numeric(length(v))
  for (k in unique(fold)) out[fold == k] <- cbind(1, Z[fold == k, ]) %*% coef(lm(v[fold != k] ~ Z[fold != k, ]))
  out
}

# Ridge computed both ways, on 50 rows and 200 centered inputs.
lam <- 2

# Fixed and learned features on two simulated truths: p = 10 standard normal inputs, noise sd 0.5.
p_in <- 10; sd_noise <- 0.5; w_dir <- rep(1, p_in) / sqrt(p_in)
truths <- list("one direction" = function(X) { u <- drop(X %*% w_dir); sin(2 * u) + u^2 / 2 },
               "radial" = function(X) 2 * cos(sqrt(rowSums(X^2))))
sqdist <- function(A, B) pmax(outer(rowSums(A^2), rowSums(B^2), "+") - 2 * tcrossprod(A, B), 0)
# Kernel ridge with the Gaussian kernel, bandwidth h and lambda chosen on the tuning rows; y centered.
kernel_ridge <- function(Xtr, ytr, Xtu, ytu, Xnew, hs = c(1, 2, 3, 5), lambdas = c(0.01, 0.1, 1, 10)) {
  mu <- mean(ytr); D <- sqdist(Xtr, Xtr); Dtu <- sqdist(Xtu, Xtr); best <- list(err = Inf)
  for (h in hs) {
    e <- eigen(exp(-D / (2 * h^2)), symmetric = TRUE); Uy <- crossprod(e$vectors, ytr - mu)
    for (l in lambdas) {
      a <- e$vectors %*% (Uy / (e$values + l))
      err <- mean((ytu - mu - exp(-Dtu / (2 * h^2)) %*% a)^2)
      if (err < best$err) best <- list(err = err, h = h, a = a)
    }
  }
  mu + drop(exp(-sqdist(Xnew, Xtr) / (2 * best$h^2)) %*% best$a)
}
# One hidden layer of M logistic units, linear output, fitted by nnet (quasi-Newton). W0: the starting
# weights, in nnet's order (each hidden unit's bias and p input weights, then the output's bias and M weights).
# frozen = TRUE: the mask keeps the input-to-hidden weights at W0 and fits only the output layer.
n_w <- function(M) M * (p_in + 1) + M + 1
net_fit <- function(X, y, M, decay, W0, frozen = FALSE)
  nnet(X, y, size = M, linout = TRUE, decay = decay, Wts = W0, maxit = 1000, MaxNWts = 5000, trace = FALSE,
       mask = c(rep(!frozen, M * (p_in + 1)), rep(TRUE, M + 1)))
net_tuned <- function(Xtr, ytr, Xtu, ytu, Xnew, M, W0, frozen = FALSE, decays = 10^(-3:2)) {
  fits <- lapply(decays, function(dc) net_fit(Xtr, ytr, M, dc, W0, frozen))
  f <- fits[[which.min(sapply(fits, function(f) mean((ytu - predict(f, Xtu))^2)))]]
  list(pred = drop(predict(f, Xnew)), fit = f)
}
unit_cos <- function(W, M = 10) {   # |cos| between each hidden unit's input weights and the direction v (w_dir)
  W <- matrix(W[1:(M * (p_in + 1))], p_in + 1, M)[-1, ]
  abs(drop(crossprod(W, w_dir))) / sqrt(colSums(W^2))
}
ns <- c(250, 500, 1000, 2000); reps <- 3

## The random part, in the order the deck drew it ---------------------------------------------------------

run_sims <- function() {
  set.seed(310)   # the one seed of the deck and the note: every random step below follows from it, in order

  # Double ML with each part removed.
  dml_runs <- replicate(R_dml, {
    d <- plm(n_dml)
    fit_l <- learner(d$Z, d$Y); fit_m <- learner(d$Z, d$T)
    fold <- sample(rep(1:5, length.out = n_dml))   # one assignment to five folds, for both fits
    l_cf <- crossfit(d$Z, d$Y, fold); m_cf <- crossfit(d$Z, d$T, fold)
    rbind(none     = ror(d$Y - mean(d$Y), d$T - mean(d$T)),
          linear   = ror(d$Y - linear_cf(d$Z, d$Y, fold), d$T - linear_cf(d$Z, d$T, fold)),   # same folds
          y_only   = ror(d$Y - l_cf, d$T),
          insample = ror(d$Y - predict(fit_l, d$Z), d$T - predict(fit_m, d$Z)),   # newdata given: every tree
          oob      = ror(d$Y - predict(fit_l), d$T - predict(fit_m)),             # no newdata: out of bag
          dml      = ror(d$Y - l_cf, d$T - m_cf),
          mean_cf  = ror(d$Y - mean_cf(d$Y, fold), d$T - mean_cf(d$T, fold)))   # for the table of learners
  }, simplify = "array")

  # Ridge computed both ways: the data.
  Xr <- scale(matrix(rnorm(50 * 200), 50), scale = FALSE); yr <- drop(Xr[, 1:5] %*% rep(1, 5)) + rnorm(50)
  yr <- yr - mean(yr); x_new <- rnorm(200)

  # Fixed and learned features: excess risk of each method, three data sets per truth and sample size.
  feat <- list(); align <- NULL
  for (tn in names(truths)) for (n in ns) for (r in 1:reps) {
    f <- truths[[tn]]
    Xtr <- matrix(rnorm(n * p_in), n); Xtu <- matrix(rnorm(500 * p_in), 500); Xte <- matrix(rnorm(5000 * p_in), 5000)
    ytr <- f(Xtr) + sd_noise * rnorm(n); ytu <- f(Xtu) + sd_noise * rnorm(500); fte <- f(Xte)
    W10 <- runif(n_w(10), -0.7, 0.7); W200 <- runif(n_w(200), -0.7, 0.7)   # nnet's default starting range
    excess <- function(pr) mean((pr - fte)^2)
    tr <- net_tuned(Xtr, ytr, Xtu, ytu, Xte, 10, W10)
    feat[[length(feat) + 1]] <- tibble(truth = tn, n = n, rep = r,
      linear = excess(cbind(1, Xte) %*% coef(lm(ytr ~ Xtr))),
      kernel = excess(kernel_ridge(Xtr, ytr, Xtu, ytu, Xte)),
      frozen10 = excess(net_tuned(Xtr, ytr, Xtu, ytu, Xte, 10, W10, frozen = TRUE)$pred),
      frozen200 = excess(net_tuned(Xtr, ytr, Xtu, ytu, Xte, 200, W200, frozen = TRUE)$pred),
      trained10 = excess(tr$pred))
    if (tn == "one direction" && n == 1000 && r == 1)
      align <- tibble(unit = 1:10, before = unit_cos(W10), after = unit_cos(tr$fit$wts))
  }
  feat <- bind_rows(feat)

  # Twenty starting points. One data set from the one-direction truth, n = 1,000; each version's penalty
  # chosen once on 500 tuning rows (from one start) and then held fixed; twenty random starting weights per
  # version; excess risk on 5,000 new inputs.
  f <- truths[["one direction"]]; n_seed <- 1000
  Xs <- matrix(rnorm(n_seed * p_in), n_seed); Xs_tu <- matrix(rnorm(500 * p_in), 500); Xs_te <- matrix(rnorm(5000 * p_in), 5000)
  ys <- f(Xs) + sd_noise * rnorm(n_seed); ys_tu <- f(Xs_tu) + sd_noise * rnorm(500); fs_te <- f(Xs_te)
  decay_of <- function(M, frozen) net_tuned(Xs, ys, Xs_tu, ys_tu, Xs_tu, M, runif(n_w(M), -0.7, 0.7), frozen)$fit$decay
  dec <- c(trained10 = decay_of(10, FALSE), trained20 = decay_of(20, FALSE), frozen200 = decay_of(200, TRUE))
  seed_runs <- map_dfr(1:20, function(s) {
    W10 <- runif(n_w(10), -0.7, 0.7); W20 <- runif(n_w(20), -0.7, 0.7); W200 <- runif(n_w(200), -0.7, 0.7)
    tibble(start = s,
           trained10 = mean((predict(net_fit(Xs, ys, 10, dec[["trained10"]], W10), Xs_te) - fs_te)^2),
           trained20 = mean((predict(net_fit(Xs, ys, 20, dec[["trained20"]], W20), Xs_te) - fs_te)^2),
           frozen200 = mean((predict(net_fit(Xs, ys, 200, dec[["frozen200"]], W200, frozen = TRUE), Xs_te) - fs_te)^2))
  })

  # The curse: from each of 100 new points to 1,000 standard normal points in p dimensions, the nearest
  # distance over the farthest; its median and 10th and 90th percentiles over the new points, for each p.
  near_far_p <- c(1, 2, 3, 5, 7, 10, 15, 20, 30, 50, 70, 100)
  curse <- map_dfr(near_far_p, function(p) {
    X <- matrix(rnorm(1000 * p), 1000); Xnew <- matrix(rnorm(100 * p), 100)
    D <- sqrt(sqdist(Xnew, X)); r <- apply(D, 1, min) / apply(D, 1, max)
    tibble(p = p, median = median(r), lo = quantile(r, 0.1), hi = quantile(r, 0.9))
  })

  list(objects = list(dml_runs = dml_runs, Xr = Xr, yr = yr, x_new = x_new, feat = feat, align = align,
                      dec = dec, seed_runs = seed_runs, curse = curse),
       seed = get(".Random.seed", envir = globalenv()))
}

## Run it, or reload what was saved -----------------------------------------------------------------------

sims_key <- unname(tools::md5sum("sims.R"))
sims_saved <- if (file.exists("_sims.rds")) readRDS("_sims.rds")
if (is.null(sims_saved) || !identical(sims_saved$key, sims_key)) {
  sims_saved <- c(run_sims(), key = sims_key)
  saveRDS(sims_saved, "_sims.rds")
}
list2env(sims_saved$objects, envir = environment())
assign(".Random.seed", sims_saved$seed, envir = globalenv())

## What follows from it (no random numbers) ---------------------------------------------------------------

dml_tab <- tibble(version = dimnames(dml_runs)[[1]],
                  mean = apply(dml_runs[, "est", ], 1, mean), sd = apply(dml_runs[, "est", ], 1, sd),
                  se = apply(dml_runs[, "se", ], 1, mean),
                  cover = apply(abs(dml_runs[, "est", ] - theta) < 1.96 * dml_runs[, "se", ], 1, sum))
dt <- function(v, col) dml_tab[[col]][dml_tab$version == v]
# Limits with the true nuisance functions: Var(m(Z)) = (1 - exp(-8))/2 + 1/2; linear partialling out
# leaves Cov(Z2^2/2, Z2^2) = 1 over the variance of T's residual on Z, 1 + Var(m) - (2 exp(-2))^2.
var_m <- (1 - exp(-8)) / 2 + 1 / 2
lim_linear <- theta + 1 / (1 + var_m - (2 * exp(-2))^2)
lim_yonly <- theta / (1 + var_m)
lim_none <- theta + 1 / (1 + var_m)   # Y on T: Cov(T, g) / Var(T), with Cov(m, g) = 1
# Cross-fitting removed, paired over the same data sets: in-sample estimate minus cross-fitted estimate
cf_diff <- dml_runs["insample", "est", ] - dml_runs["dml", "est", ]
cf_diff_mean <- mean(cf_diff); cf_diff_se <- sd(cf_diff) / sqrt(R_dml)
# Choosing the learners: each learner's cross-fitted prediction error for Y and for T, and the mean estimate
learner_tab <- tibble(version = c("mean_cf", "linear", "dml"),
                      rmse_y = apply(dml_runs[version, "rmse_y", ], 1, mean),
                      rmse_t = apply(dml_runs[version, "rmse_t", ], 1, mean),
                      mean = apply(dml_runs[version, "est", ], 1, mean))

pred_p <- sum(x_new * solve(crossprod(Xr) + lam * diag(200), crossprod(Xr, yr)))
pred_n <- sum((Xr %*% x_new) * solve(tcrossprod(Xr) + lam * diag(50), yr))
ridge_gap <- abs(pred_p - pred_n)
n_poly <- choose(104, 4)

feat_mean <- feat |> group_by(truth, n) |> summarise(across(linear:trained10, mean), .groups = "drop")
fm <- function(tn, nn, col) feat_mean[[col]][feat_mean$truth == tn & feat_mean$n == nn]
# Radial truth: the largest gap, over sample sizes, between a network's mean excess risk and linear regression's
rad_gap <- with(filter(feat_mean, truth == "radial"), max(abs(cbind(frozen10, frozen200, trained10) - linear)))
method_names <- c(linear = "linear regression", kernel = "kernel ridge", frozen200 = "frozen, M = 200",
                  frozen10 = "frozen, M = 10", trained10 = "trained, M = 10")

n_bad <- sum(seed_runs$trained10 > max(seed_runs$trained20))   # starts at width 10 worse than every run at width 20
# How often one run of each would put M = 20 ahead of M = 10 (over all 400 pairings of the runs)
p_wrong <- mean(outer(seed_runs$trained20, seed_runs$trained10, "<"))
p_frozen <- mean(outer(seed_runs$frozen200, seed_runs$trained10, "<"))

# Life expectancy against log GDP per capita, 2007, all 142 countries: three weighted sums of the outcomes.
gm <- gapminder |> filter(year == 2007) |> mutate(lgdp = log10(gdpPercap))
grid_g <- tibble(lgdp = seq(min(gm$lgdp) - 0.1, max(gm$lgdp) + 0.1, length.out = 400))
h_g <- 0.15; k_g <- 20; lam_g <- 1
knn_g <- sapply(grid_g$lgdp, function(x0) mean(gm$lifeExp[order(abs(gm$lgdp - x0))[1:k_g]]))
nw_g <- sapply(grid_g$lgdp, function(x0) { w <- exp(-0.5 * ((gm$lgdp - x0) / h_g)^2); sum(w * gm$lifeExp) / sum(w) })
K_g <- exp(-outer(gm$lgdp, gm$lgdp, "-")^2 / (2 * h_g^2))
alpha_g <- solve(K_g + lam_g * diag(nrow(gm)), gm$lifeExp - mean(gm$lifeExp))
kr_g <- mean(gm$lifeExp) + drop(exp(-outer(grid_g$lgdp, gm$lgdp, "-")^2 / (2 * h_g^2)) %*% alpha_g)
# Kernel ridge's weights on the outcomes at one point. With y centered and the mean added back, the weight
# on y_i is w_i + (1 - sum(w)) / n, so the weights sum to one; some are negative.
w_at <- drop(exp(-(3.5 - gm$lgdp)^2 / (2 * h_g^2)) %*% solve(K_g + lam_g * diag(nrow(gm))))
w_raw <- w_at + (1 - sum(w_at)) / nrow(gm)
n_negative <- sum(w_raw < 0)
near_far <- curse$median[match(c(1, 10, 100), curse$p)]   # the medians quoted for p = 1, 10, 100
