# Gaussian process regression from scratch
# https://tidyecology.com/posts/gaussian-process-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-11-13

## ---- dgp ----
set.seed(4218)
f_true <- function(x) 1.2*exp(-((x-0.35)^2)/(2*0.09)) - 0.7*exp(-((x-0.78)^2)/(2*0.03)) + 0.25
sig_n_true <- 0.18
gap <- c(0.52, 0.68)                        # an unsampled stretch of the gradient
x  <- sort(runif(58, 0, 1)); x <- x[x < gap[1] | x > gap[2]]
n  <- length(x)
y  <- f_true(x) + rnorm(n, 0, sig_n_true)
ybar <- mean(y); yc <- y - ybar             # centre; the GP prior mean is 0 on the residual

## ---- gp-machinery ----
D  <- as.matrix(dist(x))                     # n x n pairwise |x_i - x_j|
kern <- function(D, sf, ell) sf^2 * exp(-(D^2)/(2*ell^2))

nll <- function(par, D, yc) {                # negative log marginal likelihood
  ell <- exp(par[1]); sf <- exp(par[2]); sn <- exp(par[3])
  K   <- kern(D, sf, ell); Ky <- K + diag(sn^2, nrow(K))
  R   <- tryCatch(chol(Ky), error = function(e) NULL)
  if (is.null(R)) return(1e10)
  a   <- backsolve(R, forwardsolve(t(R), yc))
  0.5*sum(yc*a) + sum(log(diag(R))) + 0.5*length(yc)*log(2*pi)
}

predict_gp <- function(xs, x, yc, ybar, sf, ell, sn) {
  K  <- kern(as.matrix(dist(x)), sf, ell) + diag(sn^2, length(x))
  R  <- chol(K); a <- backsolve(R, forwardsolve(t(R), yc))
  Ds <- outer(xs, x, function(u, v) abs(u - v)); Ks <- kern(Ds, sf, ell)
  mu <- as.numeric(Ks %*% a) + ybar
  v  <- forwardsolve(t(R), t(Ks))
  var_f <- sf^2 - colSums(v^2); var_f[var_f < 0] <- 0
  list(mu = mu, sd_f = sqrt(var_f), sd_y = sqrt(var_f + sn^2))
}

## ---- fit ----
fit <- optim(c(log(0.15), log(sd(yc)), log(0.2)), nll, D = D, yc = yc,
             method = "BFGS", control = list(maxit = 500))
ell_hat <- exp(fit$par[1]); sf_hat <- exp(fit$par[2]); sn_hat <- exp(fit$par[3])
logML   <- -fit$value
xg  <- seq(-0.15, 1.15, length.out = 300)    # a fine grid, with a little extrapolation
pg  <- predict_gp(xg, x, yc, ybar, sf_hat, ell_hat, sn_hat)
inr <- xg >= min(x) & xg <= max(x)
rmse_gp <- sqrt(mean((pg$mu[inr] - f_true(xg[inr]))^2))

## ---- fig-fit ----
suppressPackageStartupMessages(library(ggplot2))
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 13),
          plot.subtitle = element_text(colour = "#46604a", size = 10),
          strip.text = element_text(colour = "#275139", face = "bold"),
          legend.title = element_text(colour = "#2c3a31"),
          legend.text  = element_text(colour = "#46604a"),
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}
forest <- "#275139"; sage <- "#93a87f"; ink <- "#16241d"; terra <- "#b5534e"; gold <- "#c9b458"
dfit <- data.frame(x = xg, mu = pg$mu, lo = pg$mu - 1.96*pg$sd_f, hi = pg$mu + 1.96*pg$sd_f,
                   truth = f_true(xg))
dobs <- data.frame(x = x, y = y)
ggplot() +
  annotate("rect", xmin = gap[1], xmax = gap[2], ymin = -Inf, ymax = Inf,
           fill = "#dad9ca", alpha = 0.35) +
  annotate("text", x = mean(gap), y = 1.85, label = "unsampled gap",
           colour = "#5d6b61", size = 3) +
  geom_ribbon(data = dfit, aes(x, ymin = lo, ymax = hi), fill = sage, alpha = 0.35) +
  geom_line(data = dfit, aes(x, truth), colour = terra, linetype = "dashed", linewidth = 0.7) +
  geom_line(data = dfit, aes(x, mu), colour = forest, linewidth = 1) +
  geom_point(data = dobs, aes(x, y), colour = ink, size = 1.5, alpha = 0.8) +
  labs(x = "environmental gradient (standardised)", y = "response") +
  coord_cartesian(ylim = c(-0.7, 1.95)) + theme_te()

## ---- equivalence ----
lambda_kr <- sn_hat^2 / sf_hat^2                 # noise-to-signal ratio = ridge penalty
Ktil   <- exp(-(D^2)/(2*ell_hat^2))              # correlation kernel (signal SD set to 1)
a_kr   <- solve(Ktil + diag(lambda_kr, n), yc)
Ds_g   <- outer(xg, x, function(u, v) abs(u - v)); Ktil_s <- exp(-(Ds_g^2)/(2*ell_hat^2))
mu_kr  <- as.numeric(Ktil_s %*% a_kr) + ybar
max_gp_vs_kr <- max(abs(pg$mu - mu_kr))          # agreement to machine precision

## ---- fp-guard-1 ----
stopifnot(max_gp_vs_kr < 1e-10)

## ---- profile ----
ell_grid <- exp(seq(log(0.03), log(0.60), length.out = 60))
prof <- sapply(ell_grid, function(le) {
  o <- optim(c(log(sd(yc)), log(0.2)),
             function(p) nll(c(log(le), p[1], p[2]), D, yc),
             method = "BFGS", control = list(maxit = 300))
  -o$value
})
ell_mle <- ell_grid[which.max(prof)]
within2 <- ell_grid[prof >= max(prof) - 2]       # length-scales within 2 log-ML of the best
ell_lo  <- min(within2); ell_hi <- max(within2); ratio_flat <- ell_hi / ell_lo

refit_at <- function(le) {
  o <- optim(c(log(sd(yc)), log(0.2)),
             function(p) nll(c(log(le), p[1], p[2]), D, yc),
             method = "BFGS", control = list(maxit = 300))
  list(ell = le, sf = exp(o$par[1]), sn = exp(o$par[2]))
}
plo <- refit_at(ell_lo); phi <- refit_at(ell_hi)
glo <- predict_gp(xg, x, yc, ybar, plo$sf, plo$ell, plo$sn)
ghi <- predict_gp(xg, x, yc, ybar, phi$sf, phi$ell, phi$sn)
dense <- inr & (xg < gap[1] | xg > gap[2])
maxdiff_dense <- max(abs(glo$mu[dense] - ghi$mu[dense]))
ig <- which.min(abs(xg - mean(gap)))
diff_gap    <- abs(glo$mu[ig] - ghi$mu[ig])
band_lo_gap <- 2*1.96*glo$sd_f[ig]; band_hi_gap <- 2*1.96*ghi$sd_f[ig]

## ---- fig-identifiability ----
dprof <- data.frame(ell = ell_grid, lml = prof)
pA <- ggplot(dprof, aes(ell, lml)) +
  annotate("rect", xmin = ell_lo, xmax = ell_hi, ymin = -Inf, ymax = Inf,
           fill = sage, alpha = 0.30) +
  geom_line(colour = forest, linewidth = 1) +
  geom_vline(xintercept = ell_mle, colour = ink, linetype = "dotted") +
  labs(x = "length-scale", y = "profile log marginal likelihood",
       subtitle = "(A) the length-scale is weakly identified") + theme_te()
mk <- function(g, lab) data.frame(x = xg, mu = g$mu, lo = g$mu - 1.96*g$sd_f,
                                  hi = g$mu + 1.96*g$sd_f, which = lab)
d2 <- rbind(mk(glo, sprintf("short (%.2f)", plo$ell)), mk(ghi, sprintf("long (%.2f)", phi$ell)))
pB <- ggplot() +
  annotate("rect", xmin = gap[1], xmax = gap[2], ymin = -Inf, ymax = Inf,
           fill = "#dad9ca", alpha = 0.35) +
  geom_ribbon(data = d2, aes(x, ymin = lo, ymax = hi, fill = which), alpha = 0.20) +
  geom_line(data = data.frame(x = xg, truth = f_true(xg)), aes(x, truth),
            colour = terra, linetype = "dashed", linewidth = 0.6) +
  geom_line(data = d2, aes(x, mu, colour = which), linewidth = 0.9) +
  geom_point(data = dobs, aes(x, y), colour = ink, size = 1, alpha = 0.7) +
  scale_colour_manual(values = c(forest, gold), name = "length-scale") +
  scale_fill_manual(values = c(forest, gold), name = "length-scale") +
  coord_cartesian(ylim = c(-0.7, 1.95)) +
  labs(x = "environmental gradient", y = "response",
       subtitle = "(B) the two ends of the plateau") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.80, 0.86),
                     legend.background = element_rect(fill = "white", colour = "#dad9ca"),
                     legend.key.size = unit(0.8, "lines"))
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2, widths = grid::unit(c(1, 1.15), "null"))))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
