# Local regression from scratch
# https://tidyecology.com/posts/local-regression-from-scratch/
#
# 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-15

## ---- dgp ----
set.seed(4219)
f_true <- function(x) 0.50*x +
  0.90*exp(-((x-0.30)^2)/(2*0.008)) +               # sharp bump (sd ~ 0.09)
  0.50*exp(-((x-0.70)^2)/(2*0.040))                 # broad bump (sd ~ 0.20)
sig_true <- 0.12
n  <- 120
x  <- sort(runif(n))
y  <- f_true(x) + rnorm(n, 0, sig_true)
xg <- seq(0, 1, length.out = 400)

gk <- function(u) exp(-0.5*u^2)                        # Gaussian kernel
nw <- function(x0, x, y, h){ w <- gk((x - x0)/h); sum(w*y)/sum(w) }   # local constant

## ---- local-linear ----
ll_wts <- function(x0, x, h){                          # local linear effective weights
  w <- gk((x - x0)/h); X <- cbind(1, x - x0)
  XtW <- t(X * w); A <- XtW %*% X
  as.numeric((solve(A) %*% XtW)[1, ])
}
ll_fit <- function(xt, x, y, h){
  L <- t(vapply(xt, ll_wts, numeric(length(x)), x = x, h = h))
  list(mu = as.numeric(L %*% y), L = L)
}

## ---- bandwidth ----
cv_h <- function(h){
  L <- t(vapply(x, ll_wts, numeric(n), x = x, h = h))
  fit <- as.numeric(L %*% y); dL <- diag(L)
  mean(((y - fit)/(1 - dL))^2)
}
h_grid <- exp(seq(log(0.015), log(0.20), length.out = 40))
cv <- sapply(h_grid, cv_h)
h_cv <- h_grid[which.min(cv)]
cv_thr <- min(cv)*1.05; h_band <- h_grid[cv <= cv_thr]     # within 5% of the best score
h_lo <- min(h_band); h_hi <- max(h_band); h_ratio <- h_hi/h_lo

## ---- fit-band ----
onx <- ll_fit(x, x, y, h_cv); L <- onx$L
nu  <- sum(diag(L))
sig2 <- sum((y - onx$mu)^2)/(n - nu)
fg  <- ll_fit(xg, x, y, h_cv); Lg <- fg$L
sd_g <- sqrt(sig2 * rowSums(Lg^2))                     # variance only, ignores bias
hw_g <- 1.96*sd_g; lo_g <- fg$mu - hw_g; hi_g <- fg$mu + hw_g
tru_g <- f_true(xg); ftx <- f_true(x)
inr <- xg >= min(x) & xg <= max(x)

## ---- 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.subtitle = element_text(colour = "#46604a", size = 10),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))
forest <- "#275139"; terra <- "#b5534e"
dg <- data.frame(x = xg, mu = fg$mu, lo = lo_g, hi = hi_g, tru = tru_g)
pA <- ggplot() +
  geom_point(data = data.frame(x, y), aes(x, y), colour = "#93a87f", alpha = 0.55, size = 1.4) +
  geom_ribbon(data = dg, aes(x, ymin = lo, ymax = hi), fill = "#93a87f", alpha = 0.30) +
  geom_line(data = dg, aes(x, tru), colour = "#16241d", linetype = "dashed", linewidth = 0.8) +
  geom_line(data = dg, aes(x, mu), colour = forest, linewidth = 1.1) +
  labs(x = "environmental gradient", y = "response", subtitle = "(A) local linear fit and 95% band") +
  theme_te()
dcv <- data.frame(h = h_grid, cv = cv)
pB <- ggplot(dcv, aes(h, cv)) +
  annotate("rect", xmin = h_lo, xmax = h_hi, ymin = -Inf, ymax = Inf, fill = "#93a87f", alpha = 0.30) +
  geom_line(colour = forest, linewidth = 1) +
  geom_vline(xintercept = h_cv, colour = "#5d6b61", linetype = "dotted") +
  labs(x = "bandwidth", y = "leave-one-out CV score", subtitle = "(B) the bandwidth is weakly pinned") +
  theme_te()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
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))

## ---- coverage ----
efit_g <- as.numeric(Lg %*% ftx)                       # expected fit = smoother on the truth
bias_g <- efit_g - tru_g                               # exact smoothing bias
ipk <- which.max(tru_g); xpk <- xg[ipk]                # the sharp optimum
sd_true_g <- sig_true * sqrt(rowSums(Lg^2))            # sampling sd of the fit (true noise sd)
bias_pk <- bias_g[ipk]; se_pk <- sd_true_g[ipk]; bias_in_se_pk <- abs(bias_pk)/se_pk
## true coverage of the NOMINAL 95% band over repeated samples: the fit is centred at truth + bias
cover_g  <- pnorm(1.96 - bias_g/sd_true_g) - pnorm(-1.96 - bias_g/sd_true_g)
cover_pk <- cover_g[ipk]; min_cov <- min(cover_g[inr])
frac_undercover <- mean(cover_g[inr] < 0.90)

## ---- boundary ----
xb <- xg[xg <= 0.08]                                   # left edge, where the curve has a slope
nw_eb <- sapply(xb, function(x0){ w <- gk((x - x0)/h_cv); sum(w*ftx)/sum(w) })   # NW on the truth
Lb <- t(vapply(xb, ll_wts, numeric(n), x = x, h = h_cv)); ll_eb <- as.numeric(Lb %*% ftx)
bias_nw_0 <- abs(nw_eb[1] - f_true(xb[1])); bias_ll_0 <- abs(ll_eb[1] - f_true(xb[1]))

## ---- fig-coverage ----
dcov <- data.frame(x = xg, cover = cover_g)[inr[order(xg)], ]
qA <- ggplot(data.frame(x = xg[inr], cover = cover_g[inr]), aes(x, cover)) +
  geom_hline(yintercept = 0.95, colour = "#5d6b61", linetype = "dashed") +
  geom_line(colour = forest, linewidth = 1) + ylim(0.5, 1) +
  labs(x = "environmental gradient", y = "true coverage of the 95% band",
       subtitle = "(A) real coverage dips where the curve bends") + theme_te()
xz <- seq(0, 0.15, length.out = 120)
nwz <- sapply(xz, nw, x = x, y = ftx, h = h_cv); llz <- ll_fit(xz, x, ftx, h_cv)$mu   # expected fits: smoothers on the truth
dz <- rbind(data.frame(x = xz, val = f_true(xz), w = "truth"),
            data.frame(x = xz, val = nwz, w = "local constant"),
            data.frame(x = xz, val = llz, w = "local linear"))
qB <- ggplot(dz, aes(x, val, colour = w, linetype = w)) + geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(truth = "#16241d", `local constant` = terra, `local linear` = forest)) +
  scale_linetype_manual(values = c(truth = "dashed", `local constant` = "dotted", `local linear` = "solid")) +
  labs(x = "environmental gradient", y = "response", colour = NULL, linetype = NULL,
       subtitle = "(B) local constant is biased at the edge") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.68, 0.22),
                     legend.background = element_rect(fill = "white", colour = "#dad9ca"))
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(qA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(qB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- smooth-default ----
sm_msg <- character()
keep_msg <- function(expr) withCallingHandlers(expr, message = function(m) {
  sm_msg <<- c(sm_msg, conditionMessage(m)); invokeRestart("muffleMessage") })
ld_def <- keep_msg(layer_data(ggplot(data.frame(x, y), aes(x, y)) + geom_smooth(), 1))
cat(sm_msg, sep = "\n")                                # the message ggplot2 prints
lo_def <- loess(y ~ x, span = 0.75)                    # loess default degree: 2 (local quadratic)
stopifnot(formals(loess)$degree == 2, isTRUE(all.equal(ld_def$y,   # the plotted curve is this loess
  as.numeric(predict(lo_def, data.frame(x = ld_def$x))), tolerance = 1e-6)))
fit_def_pk <- predict(lo_def, data.frame(x = xpk))     # the default on these data, at the peak
ef_def_pk <- predict(loess(ftx ~ x, span = 0.75), data.frame(x = xpk))  # smoother on the truth
bias_def_pk <- ef_def_pk - tru_g[ipk]
xe_n <- seq(0, 1, length.out = n); ef_def_even <- predict(loess(f_true(xe_n) ~ xe_n, span = 0.75), data.frame(xe_n = xpk))
set.seed(2191)   # own seed, so no later draw moves; 300 fresh noise draws at the same x
mc_def <- replicate(300, predict(loess(I(ftx + rnorm(n, 0, sig_true)) ~ x, span = 0.75), data.frame(x = xpk)))

## ---- smooth-switch ----
f_narrow <- function(x) 0.50*x + 0.90*exp(-((x-0.30)^2)/(2*0.0016)) +  # sharp bump sd 0.04
  0.50*exp(-((x-0.70)^2)/(2*0.040))
xpn <- xg[which.max(f_narrow(xg))]
draw_fit <- function(f, m, x0, guard = FALSE) {        # the default's value at x0 on m rows
  dd <- data.frame(x = sort(runif(m))); dd$y <- f(dd$x) + rnorm(m, 0, sig_true)
  sm <- if (m < 1000) loess(y ~ x, data = dd, span = 0.75) else
    mgcv::gam(y ~ s(x, bs = "cs"), method = "REML", data = dd)
  if (guard) { ld <- keep_msg(layer_data(ggplot(dd, aes(x, y)) + geom_smooth(), 1))
    stopifnot(isTRUE(all.equal(ld$y, as.numeric(predict(sm, data.frame(x = ld$x))),
                               tolerance = 1e-6))) }
  as.numeric(predict(sm, data.frame(x = x0)))
}
set.seed(2192)
invisible(draw_fit(f_true, 999, xpk, TRUE)); invisible(draw_fit(f_true, 1000, xpk, TRUE))
cat(tail(sm_msg, 1), sep = "\n")
sw <- sapply(c(999, 1000), function(m) cbind(host = replicate(50, draw_fit(f_true, m, xpk)),
                                            narrow = replicate(50, draw_fit(f_narrow, m, xpn))),
             simplify = "array")                       # 50 draws x bump x rows
sw_mean <- apply(sw, 2:3, mean); sw_se <- apply(sw, 2:3, sd)/sqrt(dim(sw)[1])
xe <- seq(0, 1, length.out = 999)                     # smoother on the truth, even 999-row design
ef_999 <- c(predict(loess(f_true(xe) ~ xe, span = 0.75), data.frame(xe = xpk)),
            predict(loess(f_narrow(xe) ~ xe, span = 0.75), data.frame(xe = xpn)))

## ---- smooth-span ----
spans <- seq(0.15, 0.75, by = 0.05); inner <- 2:(n - 1)   # loess will not extrapolate to the ends
cv_span <- sapply(spans, function(s) mean(sapply(inner, function(i)
  (y[i] - predict(loess(y ~ x, span = s, subset = -i), data.frame(x = x[i])))^2)))
span_cv <- spans[which.min(cv_span)]
ld_cv <- layer_data(ggplot(data.frame(x, y), aes(x, y)) +
                      geom_smooth(method = "loess", span = span_cv, formula = y ~ x), 1)
stopifnot(isTRUE(all.equal(ld_cv$y, as.numeric(predict(loess(y ~ x, span = span_cv),
                                                        data.frame(x = ld_cv$x))), tolerance = 1e-6)))
ef_cv_pk <- predict(loess(ftx ~ x, span = span_cv), data.frame(x = xpk))
