# Conformal prediction intervals from scratch
# https://tidyecology.com/posts/conformal-prediction-intervals/
#
# 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

## ---- setup ----
set.seed(4220)
f_true <- function(x) 0.40 + 1.2*x - 1.0*x^2 + 0.45*sin(6*x)   # smooth mean
sig    <- function(x) 0.05 + 0.40*x                            # noise grows across the gradient
gen    <- function(n){ x <- runif(n); data.frame(x = x, y = f_true(x) + rnorm(n, 0, sig(x))) }

base_fit  <- function(tr, deg = 6) lm(y ~ poly(x, deg), data = tr)
base_pred <- function(m, xnew) as.numeric(predict(m, newdata = data.frame(x = xnew)))
alpha <- 0.10

split_conf <- function(tr, ca, xnew, alpha = 0.10){
  m <- base_fit(tr); r <- abs(ca$y - base_pred(m, ca$x))
  k <- ceiling((1 - alpha)*(nrow(ca) + 1)); q <- sort(r)[min(k, length(r))]
  mu <- base_pred(m, xnew); list(mu = mu, lo = mu - q, hi = mu + q, q = q)
}

## ---- marginal ----
R <- 3000; hit <- numeric(R)
for (b in 1:R){
  d <- gen(200); tr <- d[1:100, ]; ca <- d[101:200, ]
  xt <- runif(1); yt <- f_true(xt) + rnorm(1, 0, sig(xt))
  sc <- split_conf(tr, ca, xt, alpha); hit[b] <- (yt >= sc$lo) && (yt <= sc$hi)
}
marg_cov <- mean(hit)

## ---- conditional ----
norm_conf <- function(tr, ca, xnew, alpha = 0.10){
  m <- base_fit(tr); rtr <- abs(tr$y - base_pred(m, tr$x))
  smod <- lm(log(rtr + 1e-3) ~ poly(x, 4), data = data.frame(x = tr$x, rtr = rtr))
  s <- function(xx) exp(as.numeric(predict(smod, newdata = data.frame(x = xx)))) + 1e-3
  r <- abs(ca$y - base_pred(m, ca$x)) / s(ca$x)
  k <- ceiling((1 - alpha)*(nrow(ca) + 1)); q <- sort(r)[min(k, length(r))]
  mu <- base_pred(m, xnew); sw <- s(xnew); list(mu = mu, lo = mu - q*sw, hi = mu + q*sw)
}

D <- gen(4500); tr <- D[1:1500, ]; ca <- D[1501:3000, ]; te <- D[3001:4500, ]
sc <- split_conf(tr, ca, te$x, alpha); nc <- norm_conf(tr, ca, te$x, alpha)
cov_s <- (te$y >= sc$lo) & (te$y <= sc$hi); cov_n <- (te$y >= nc$lo) & (te$y <= nc$hi)
bins <- cut(te$x, seq(0, 1, 0.2), include.lowest = TRUE)
covbin_s <- tapply(cov_s, bins, mean); covbin_n <- tapply(cov_n, bins, mean)

## ---- fig-bands ----
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"
o <- order(te$x)
dd <- data.frame(x = te$x[o], y = te$y[o], mu = sc$mu[o],
                 slo = sc$lo[o], shi = sc$hi[o], nlo = nc$lo[o], nhi = nc$hi[o])
pts <- geom_point(data = dd, aes(x, y), colour = "#93a87f", alpha = 0.30, size = 0.9)
pA <- ggplot() + pts +
  geom_ribbon(data = dd, aes(x, ymin = slo, ymax = shi), fill = terra, alpha = 0.22) +
  geom_line(data = dd, aes(x, mu), colour = forest, linewidth = 1) +
  labs(x = "environmental gradient", y = "response", subtitle = "(A) split conformal: constant width") +
  theme_te()
pB <- ggplot() + pts +
  geom_ribbon(data = dd, aes(x, ymin = nlo, ymax = nhi), fill = "#93a87f", alpha = 0.35) +
  geom_line(data = dd, aes(x, mu), colour = forest, linewidth = 1) +
  labs(x = "environmental gradient", y = "response", subtitle = "(B) normalised conformal: adaptive width") +
  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))

## ---- shift ----
Dl <- D[D$x <= 0.7, ]; Dr <- D[D$x > 0.7, ]              # calibrate low-x, predict high-x
h  <- floor(nrow(Dl)/2); trL <- Dl[1:h, ]; caL <- Dl[(h+1):nrow(Dl), ]
scL <- split_conf(trL, caL, Dr$x, alpha)
cov_shift <- mean(Dr$y >= scL$lo & Dr$y <= scL$hi)
idx <- sample(nrow(Dl)); t3 <- floor(nrow(Dl)/3)          # in-distribution comparison
trI <- Dl[idx[1:t3], ]; caI <- Dl[idx[(t3+1):(2*t3)], ]; teI <- Dl[idx[(2*t3+1):nrow(Dl)], ]
scI <- split_conf(trI, caI, teI$x, alpha); cov_indist <- mean(teI$y >= scI$lo & teI$y <= scI$hi)
bias_shift <- mean(abs(scL$mu - f_true(Dr$x)))            # mean miss of the true curve on the high end

## ---- fig-coverage ----
mids <- c(0.1, 0.3, 0.5, 0.7, 0.9)
db <- rbind(data.frame(x = mids, cov = as.numeric(covbin_s), method = "split (constant)"),
            data.frame(x = mids, cov = as.numeric(covbin_n), method = "normalised (adaptive)"))
qA <- ggplot(db, aes(x, cov, colour = method, shape = method)) +
  geom_hline(yintercept = 1 - alpha, colour = "#5d6b61", linetype = "dashed") +
  geom_point(size = 3) + geom_line(linewidth = 0.6) + ylim(0.6, 1.02) +
  scale_colour_manual(values = c(`split (constant)` = terra, `normalised (adaptive)` = forest)) +
  labs(x = "environmental gradient", y = "coverage", colour = NULL, shape = NULL,
       subtitle = "(A) coverage by region") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.62, 0.18),
                     legend.background = element_rect(fill = "white", colour = "#dad9ca"))
ds <- data.frame(what = c("same region", "shifted region"),
                 cov = c(cov_indist, cov_shift))
qB <- ggplot(ds, aes(what, cov, fill = what)) +
  geom_col(width = 0.6) + geom_hline(yintercept = 1 - alpha, colour = "#5d6b61", linetype = "dashed") +
  scale_fill_manual(values = c(`same region` = forest, `shifted region` = terra), guide = "none") +
  ylim(0, 1) + labs(x = NULL, y = "coverage", subtitle = "(B) coverage under covariate shift") +
  theme_te()
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))
