################################################################################
# 08_Sobolev.R
#
# Rate of convergence of kernel ridge regression (KRR) with the first-order
# Sobolev kernel k(x, x') = min(x, x') on [0, 1].
#
# We simulate with the design and noise level of the example in 04_kernel.R at
# increasing sample sizes n, fit KRR with lambda chosen by leave-one-out
# cross-validation (LOOCV), and plot a Monte Carlo estimate of the expected
# in-sample squared prediction error
#
#     E [ (1/n) sum_i ( fhat(x_i) - f0(x_i) )^2 ]
#
# against n on log-log axes. Over the unit ball of the first-order Sobolev space
# (the RKHS of this kernel) the minimax rate is n^{-2/3}, i.e. a straight line
# of slope -2/3 on the log-log plot.
#
# Three tricks keep the computation fast even at n = 6400:
#
#  1. LOOCV via a rank-1 update. KRR is a linear smoother, fhat = H(lambda) y
#     with H(lambda) = K (K + lambda I)^{-1}. Leaving out observation i is a
#     rank-1 change to the fitted problem, and the Sherman--Morrison formula
#     gives the leave-one-out residual directly from the full fit:
#
#         y_i - fhat^{(-i)}_i = (y_i - fhat_i) / (1 - H_ii(lambda)).
#
#     So the n leave-one-out fits cost nothing beyond the full fit.
#
#  2. As in ridge_mat() in 04_kernel.R, we work with the eigendecomposition
#     K = U D U^T so that all lambda values share one decomposition:
#     H(lambda) = U diag(d_j / (d_j + lambda)) U^T. Because the design is fixed
#     (equally spaced x), U and D are the same for every repetition. For
#     x_i = i/n they are even available in closed form (sobolev_eigenvalues() below):
#     no O(n^3) call to eigen() is needed.
#
#  3. The eigenvectors are sines, so multiplying by U or U^T is a discrete sine
#     transform, which the FFT performs in O(n log n) without forming the n x n
#     matrix U at all (U_mult(), Ut_mult(), leverages() below).
#
#  Repetitions are also spread over a parallel cluster.
################################################################################

library(parallel)

########################################
# Simulation setup
########################################
sigma <- 0.2

# Signal. The RKHS of the kernel min(x, x') is the first-order Sobolev space
# {f : f(0) = 0, f' in L^2[0, 1]} with squared norm ||f||^2 = int_0^1 f'(x)^2 dx,
# and n^{-2/3} is the minimax rate over the unit ball of this space, i.e. the
# rate for the hardest functions in the ball. We take
#     f0(x) = c x^a  with  a > 1/2  and  c = sqrt(2a - 1) / a,
# for which f0'(x)^2 = a^2 c^2 x^{2a - 2} integrates to a^2 c^2 / (2a - 1) = 1,
# so f0 lies exactly on the boundary of the unit ball. For a = 3/5 this is
# f0(x) = (sqrt(5)/3) x^{3/5}, with f0'(x)^2 = x^{-4/5} / 5.
#
# The closer a is to 1/2 the harder f0 is for KRR: its coefficients in the
# kernel's eigenbasis decay like k^{-(a + 1)}, giving the rate
# n^{-(2a + 1) / (2a + 2)} with optimally tuned lambda. This is n^{-2/3} in the
# limit a -> 1/2 (where ||f0|| blows up) and n^{-0.69} for a = 3/5; no single
# function in the ball attains the worst-case rate exactly.
a  <- 3/5
f0 <- function(x) (sqrt(2*a - 1) / a) * x^a
f0_norm_H <- 1                  # ||f0||_H, by the calculation above
cat("RKHS norm of f0 (numerical integration of f0'^2):",
    sqrt(integrate(function(x) (sqrt(2*a - 1) * x^(a - 1))^2, 0, 1)$value), "\n")

# The signal from 04_kernel.R (below) is much smoother than the worst case and
# KRR converges faster on it, empirically about n^{-3/4}. Its rate is held back
# only by f0'(1) != 0, which clashes with the kernel's boundary condition
# f'(1) = 0; a smooth signal with f0'(1) = 0 would give the saturation rate
# n^{-4/5}, which ridge regularisation with this kernel cannot beat however
# smooth f0 is.
# f0 <- function(x) sin(5*x)^2 / (2.5 + cos(2*x))

########################################
# Closed-form eigendecomposition of K
########################################
# For the equally spaced design x_i = i/n we have K = M / n where
# M_ij = min(i, j). The inverse of M is the tridiagonal second-difference
# matrix T with 2 on the diagonal (except T_nn = 1) and -1 on the off-diagonals
# -- the discrete analogue of -d^2/dx^2 with boundary conditions f(0) = 0 and
# f'(1) = 0, whose Green's function is exactly min(x, x'). The eigenpairs of T
# are classical:
#     theta_k = (2k - 1) pi / (2n + 1),   T v_k = (2 - 2 cos theta_k) v_k,
#     v_k(i) = sin(i theta_k),            ||v_k||^2 = (2n + 1) / 4.
# Hence K has eigenvalues d_k = 1 / (n (2 - 2 cos theta_k)) ~ n / ((k - 1/2) pi)^2
# with the same eigenvectors (compare with the Mercer eigenvalues
# 1 / ((k - 1/2) pi)^2 of the kernel min(x, x') on [0, 1]).
sobolev_eigenvalues <- function(n) {
  theta <- (2 * (1:n) - 1) * pi / (2 * n + 1)
  1 / (n * (2 - 2 * cos(theta)))              # decreasing in k
}

# The transforms below need discrete Fourier transforms (DFTs) of lengths 2n + 1
# and 4n + 2. R's fft() is only fast when the length has small prime factors,
# and e.g. 2 * 12800 + 1 = 25601 is prime (an FFT of length 51202 then takes
# over a second instead of a millisecond). Bluestein's chirp-z trick evaluates a
# DFT of ANY length N as a convolution, using FFTs of a power-of-two length
# M >= 2N - 1: writing w = exp(2 pi i / N) and jm = (j^2 + m^2 - (m - j)^2) / 2,
#     X_m = sum_j x_j w^{jm} = w^{m^2/2} sum_j (x_j w^{j^2/2}) w^{-(m - j)^2/2}.
# This costs three power-of-two FFTs rather than one, so it is only used when N
# has a large prime factor. The pieces that depend only on N are computed once
# per length and cached.
largest_prime_factor <- function(N) {
  p <- 1; d <- 2
  while (d * d <= N) {
    while (N %% d == 0) { p <- d; N <- N / d }
    d <- d + 1
  }
  max(p, N)
}
plan_cache <- new.env()
dft_plan <- function(N) {
  key <- as.character(N)
  if (is.null(plan_cache[[key]])) {
    if (largest_prime_factor(N) <= 1000) {
      plan_cache[[key]] <- list(N = N, direct = TRUE)
      return(plan_cache[[key]])
    }
    M <- 2^ceiling(log2(2 * N - 1))
    k <- 0:(N - 1)
    chirp <- exp(1i * pi * ((k^2) %% (2 * N)) / N)   # w^{k^2 / 2}
    b <- complex(M)                                 # conj(chirp), wrapped around
    b[1:N] <- Conj(chirp)
    b[M - k[-1] + 1] <- Conj(chirp[-1])
    plan_cache[[key]] <- list(N = N, direct = FALSE, M = M, chirp = chirp, fb = fft(b))
  }
  plan_cache[[key]]
}
# Column-wise DFT of the N x L matrix X with positive exponent, i.e. the same as
# mvfft(X, inverse = TRUE), but fast for every N
dft <- function(X) {
  p <- dft_plan(nrow(X))
  if (p$direct) return(mvfft(X, inverse = TRUE))
  A <- matrix(0i, p$M, ncol(X))
  A[1:p$N, ] <- X * p$chirp
  conv <- mvfft(mvfft(A) * p$fb, inverse = TRUE) / p$M   # circular convolution
  conv[1:p$N, , drop = FALSE] * p$chirp
}

# U_ik = c sin(i theta_k) with c = 2 / sqrt(2n + 1) and theta_k = 2 pi (2k-1) / N,
# N = 4n + 2. So (U v)_i = c Im sum_k v_k exp(2 pi i * i (2k-1) / N): place v_k at
# frequency 2k - 1 of a length-N vector and take a DFT. dft() works column by
# column, so V may be an n x L matrix.
U_mult <- function(V, n) {                     # returns U %*% V
  V <- as.matrix(V)
  W <- matrix(0, 4 * n + 2, ncol(V))
  W[2 * (1:n), ] <- V                          # row m + 1 holds frequency m
  (2 / sqrt(2 * n + 1)) * Im(dft(W)[2:(n + 1), , drop = FALSE])
}

# (U^T y)_k = c sum_i y_i sin(i theta_k): same transform with the roles of
# position and frequency exchanged.
Ut_mult <- function(Y, n) {                    # returns t(U) %*% Y
  Y <- as.matrix(Y)
  W <- matrix(0, 4 * n + 2, ncol(Y))
  W[2:(n + 1), ] <- Y                          # row i + 1 holds position i
  (2 / sqrt(2 * n + 1)) * Im(dft(W)[2 * (1:n), , drop = FALSE])
}

# Leverages H_ii(lambda) = sum_j U_ij^2 S_jl, where S_jl = d_j / (d_j + lambda_l).
# Since U_ij^2 = c^2 (1 - cos(2 i theta_j)) / 2 and 2 theta_j = 2 pi (2j-1) / (2n+1),
# this is a cosine transform computed by a DFT of length 2n + 1.
leverages <- function(S, n) {                  # returns the n x L matrix of H_ii
  W <- matrix(0, 2 * n + 1, ncol(S))
  W[2 * (1:n), ] <- S
  cos_part <- Re(dft(W)[2:(n + 1), , drop = FALSE])
  (2 / (2 * n + 1)) * (matrix(colSums(S), n, ncol(S), byrow = TRUE) - cos_part)
}

########################################
# KRR with LOOCV choice of lambda
########################################
# Shrinkage factors d_j / (d_j + lambda) for a grid of lambda values: an n x L
# matrix (cf. scale_mat in ridge_mat() of 04_kernel.R).
#
# The lambda grid is scaled by n: with fhat = K (K + lambda I)^{-1} y and K
# unnormalised, the eigenvalues of K grow linearly in n, so it is lambda / n
# that is comparable across sample sizes.
shrinkage <- function(n, lambda_ratio) {
  d <- sobolev_eigenvalues(n)
  d / outer(d, n * lambda_ratio, "+")
}

# Fits KRR to y (observed at x_i = i/n) for every lambda in the grid and
# computes the LOOCV criterion for each. S and diag_H depend only on n and the
# grid, so they can be precomputed and passed in when fitting many data sets.
krr_loocv <- function(y, n, lambda_ratio, S = shrinkage(n, lambda_ratio),
                      diag_H = leverages(S, n)) {
  z <- as.numeric(Ut_mult(y, n))              # U^T y
  fits <- U_mult(S * z, n)                    # fhat(lambda) for all lambda, n x L
  resid <- y - fits
  loocv <- colMeans((resid / (1 - diag_H))^2) # rank-1 update shortcut
  list(fits = fits, loocv = loocv, best = which.min(loocv))
}

lambda_ratio <- exp(seq(log(1), log(1e-6), length.out = 60))  # grid for lambda / n

########################################
# Illustration at n = 200
########################################
set.seed(101)
n <- 200
x <- (1:n) / n
y <- f0(x) + sigma * rnorm(n)
fit <- krr_loocv(y, n, lambda_ratio)

plot(x, y, col = "grey40", xlab = "x", ylab = "y",
     main = sprintf("n = %d; lambda / n = %.2g chosen by LOOCV", n,
                    lambda_ratio[fit$best]))
lines(x, f0(x), lwd = 2)
lines(x, fit$fits[, fit$best], col = "blue", lwd = 2)
legend("topleft", bty = "n", lwd = c(NA, 2, 2), pch = c(1, NA, NA),
       col = c("grey40", "black", "blue"),
       legend = c("Data", "Signal f0", "KRR fit, LOOCV-tuned lambda"))

########################################
# A batch of repetitions
########################################
# Runs the repetitions with ids `rep_ids` at sample size n. Each repetition
# draws fresh noise, chooses lambda from the grid n * lambda_ratio by LOOCV and
# records the in-sample squared prediction error at the chosen lambda.
run_reps <- function(rep_ids, n, lambda_ratio, sigma, f0) {
  x  <- (1:n) / n
  mu <- f0(x)
  L <- length(lambda_ratio)

  # Shrinkage factors and leverages do not depend on y, so compute them once
  S <- shrinkage(n, lambda_ratio)
  diag_H <- leverages(S, n)

  out <- matrix(NA_real_, length(rep_ids), 3,
                dimnames = list(NULL, c("mse", "lambda_ratio", "boundary")))
  for (k in seq_along(rep_ids)) {
    set.seed(1000 * n + rep_ids[k])
    y <- mu + sigma * rnorm(n)

    fit <- krr_loocv(y, n, lambda_ratio, S, diag_H)
    best <- fit$best

    out[k, ] <- c(mean((fit$fits[, best] - mu)^2),
                  lambda_ratio[best],
                  best == 1 || best == L)     # flag if the optimum hits the grid edge
  }
  out
}

########################################
# Run the simulation in parallel
########################################
n_vec <- c(200, 400, 800, 1600, 3200, 6400)
n_rep <- 200                    # repetitions per sample size

n_workers <- max(1, detectCores() - 2)
cl <- makeCluster(n_workers)
clusterExport(cl, c("sobolev_eigenvalues", "U_mult", "Ut_mult", "leverages",
                    "dft", "dft_plan", "plan_cache", "largest_prime_factor",
                    "shrinkage", "krr_loocv", "a"))

t_start <- Sys.time()
results <- vector("list", length(n_vec))
for (i in seq_along(n_vec)) {
  n <- n_vec[i]
  # Give each worker a batch of repetitions so that the leverages are computed
  # once per worker rather than once per repetition
  chunks <- split(1:n_rep, rep_len(1:n_workers, n_rep))
  t0 <- Sys.time()
  res <- parLapply(cl, chunks, run_reps, n = n, lambda_ratio = lambda_ratio,
                   sigma = sigma, f0 = f0)
  results[[i]] <- do.call(rbind, res)
  cat(sprintf("n = %5d: %5.1f s\n", n, as.numeric(difftime(Sys.time(), t0, units = "secs"))))
}
stopCluster(cl)
cat(sprintf("Simulation time: %.1f s on %d workers (%d repetitions per n)\n",
            as.numeric(difftime(Sys.time(), t_start, units = "secs")),
            n_workers, n_rep))

########################################
# Summarise
########################################
summary_df <- data.frame(
  n = n_vec,
  mse = sapply(results, function(r) mean(r[, "mse"])),
  se = sapply(results, function(r) sd(r[, "mse"]) / sqrt(nrow(r))),
  lambda_over_n = sapply(results, function(r) exp(mean(log(r[, "lambda_ratio"])))),
  at_boundary = sapply(results, function(r) sum(r[, "boundary"]))
)

########################################
# Theoretical upper bounds
########################################
# For every lambda, the expected in-sample error of KRR satisfies
#
#   E MSE <= sigma^2/n * sum_i d_i^2 / (d_i + lambda)^2 + lambda ||f0||_H^2 / (4n),   (B1)
#
# where the d_i are the eigenvalues of K: the first term is exactly the variance
# and the second bounds the squared bias. Writing gamma_n = lambda / n and using
# d_i ~ n / (pi^2 (i - 1/2)^2) for this kernel and design, the eigenvalue sum is
# at most 1 / (pi sqrt(gamma_n)) + 1/2, which gives the closed-form bound
#
#   E MSE <= sigma^2 / (n gamma_n) * (sqrt(gamma_n) / pi + gamma_n / 2)
#              + ||f0||_H^2 gamma_n / 4.                                              (B2)
#
# Minimising (B2) over gamma_n gives gamma_n ~ n^{-2/3} and hence the n^{-2/3}
# rate. Below each bound is minimised over gamma_n for every n and added to
# the plot.
gamma_grid <- exp(seq(log(1e-8), log(1), length.out = 400))
bound1 <- function(n, gamma) {
  d <- sobolev_eigenvalues(n)
  sapply(gamma, function(g) sigma^2 / n * sum(d^2 / (d + n * g)^2)) + gamma * f0_norm_H^2 / 4
}
bound2 <- function(n, gamma) {
  sigma^2 / (n * gamma) * (sqrt(gamma) / pi + gamma / 2) + f0_norm_H^2 * gamma / 4
}
summary_df$bound1 <- sapply(n_vec, function(n) min(bound1(n, gamma_grid)))
summary_df$bound2 <- sapply(n_vec, function(n) min(bound2(n, gamma_grid)))

print(summary_df, digits = 3)
if (any(summary_df$at_boundary > 0)) {
  cat("Note: in", sum(summary_df$at_boundary), "repetition(s) LOOCV chose a lambda",
      "at the edge of the grid (essentially interpolation).\n")
}

# Least squares fit of log(MSE) on log(n): the slope estimates the rate
rate_fit <- lm(log(mse) ~ log(n), data = summary_df)
slope <- unname(coef(rate_fit)[2])
cat(sprintf("Fitted slope of log(MSE) vs log(n): %.3f  (minimax rate: -2/3 = %.3f)\n",
            slope, -2/3))
cat(sprintf("Slopes of the minimised bounds: %.3f for (B1), %.3f for (B2)\n",
            coef(lm(log(bound1) ~ log(n), data = summary_df))[2],
            coef(lm(log(bound2) ~ log(n), data = summary_df))[2]))

########################################
# Log-log plot
########################################
plot(summary_df$n, summary_df$mse, log = "xy", pch = 19,
     xlab = "Sample size n",
     ylab = "Expected in-sample squared prediction error",
     main = "Kernel ridge regression, first-order Sobolev kernel",
     ylim = range(summary_df$mse + 2 * summary_df$se,
                  summary_df$mse - 2 * summary_df$se,
                  summary_df$bound1, summary_df$bound2))
# Monte Carlo error bars (+/- 2 standard errors)
arrows(summary_df$n, summary_df$mse - 2 * summary_df$se,
       summary_df$n, summary_df$mse + 2 * summary_df$se,
       angle = 90, code = 3, length = 0.03)
# Least squares line
n_grid <- exp(seq(log(min(n_vec)), log(max(n_vec)), length.out = 100))
lines(n_grid, exp(predict(rate_fit, newdata = data.frame(n = n_grid))),
      col = "blue", lwd = 2)
# Reference line with the minimax slope -2/3, anchored at the fitted line's
# value at the geometric mean sample size
n_mid <- exp(mean(log(n_vec)))
mse_mid <- exp(predict(rate_fit, newdata = data.frame(n = n_mid)))
lines(n_grid, mse_mid * (n_grid / n_mid)^(-2/3), col = "red", lwd = 2, lty = 2)
# Upper bounds (B1) and (B2), each minimised over lambda
lines(summary_df$n, summary_df$bound1, col = "darkgreen", lwd = 2, lty = 1)
lines(summary_df$n, summary_df$bound2, col = "darkorange", lwd = 2, lty = 4)
legend("topright", bty = "n", lwd = c(NA, 2, 2, 2, 2), lty = c(NA, 1, 2, 1, 4),
       pch = c(19, NA, NA, NA, NA),
       col = c("black", "blue", "red", "darkgreen", "darkorange"),
       legend = c("LOOCV-tuned lambda (+/- 2 s.e.)",
                  sprintf("Least squares fit, slope = %.2f", slope),
                  "Reference slope -2/3",
                  "Bound (B1): exact eigenvalues, best lambda",
                  "Bound (B2): closed form, best lambda"))
