# Distributional regression with location and scale
# https://tidyecology.com/posts/distributional-regression-location-scale/
#
# 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-14

## ---- setup ----
library(ggplot2); library(dplyr); library(tidyr)
ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"
sage <- "#93a87f"; paper <- "#f5f4ee"; line <- "#dad9ca"
faint <- "#5d6b61"; warm <- "#b5534e"; gold <- "#c9b458"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = paper, colour = NA),
          panel.background = element_rect(fill = paper, colour = NA),
          panel.grid.major = element_line(colour = line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = faint),
          axis.title = element_text(colour = body),
          plot.subtitle = element_text(colour = "#46604a"),
          legend.position = "top", legend.key = element_blank(),
          legend.text = element_text(colour = body),
          legend.title = element_text(colour = body))
}
rho <- function(u, tau) u * (tau - (u < 0))
qrfit <- function(x, y, tau) {
  obj <- function(b) sum(rho(y - (b[1] + b[2] * x), tau))
  optim(unname(coef(lm(y ~ x))), obj, control = list(reltol = 1e-12, maxit = 8000))$par
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- data ----
set.seed(4204)
n  <- 400
x  <- runif(n, 0, 10)
a0 <- 1; a1 <- 0.8              # mean:  a0 + a1 * x
c0 <- log(0.8); c1 <- 0.12     # log standard deviation: c0 + c1 * x
y  <- rnorm(n, a0 + a1 * x, exp(c0 + c1 * x))

coef(lm(y ~ x))[2]             # the mean slope, from ordinary least squares

## ---- locscale ----
nll <- function(p, X, Z, y) {
  k <- ncol(X); b <- p[1:k]; g <- p[(k + 1):(k + ncol(Z))]
  s <- exp(as.vector(Z %*% g))
  -sum(dnorm(y, as.vector(X %*% b), s, log = TRUE))
}
X <- cbind(1, x); Z <- cbind(1, x)
ols <- lm(y ~ x)
fit <- optim(c(unname(coef(ols)), log(sd(resid(ols))), 0),
             nll, X = X, Z = Z, y = y, method = "BFGS", hessian = TRUE)
stopifnot(fit$convergence == 0)   # check before inverting the Hessian
bML <- fit$par[1:2]; gML <- fit$par[3:4]
se  <- sqrt(diag(solve(fit$hessian)))
c(mean_slope = bML[2], logsd_slope = gML[2])

## ---- ls-scalars ----
r_lm_slope <- round(unname(coef(ols)[2]), 3)
r_ls_slope <- round(bML[2], 3)
r_c1 <- round(gML[2], 3); r_c1_se <- round(se[4], 3)
sdm <- sqrt(mean(resid(ols)^2))
ll_homo <- sum(dnorm(y, fitted(ols), sdm, log = TRUE)); ll_LS <- -fit$value
r_LR <- round(2 * (ll_LS - ll_homo), 2)
r_LRp <- signif(pchisq(2 * (ll_LS - ll_homo), 1, lower.tail = FALSE), 3)
r_dAIC <- round((-2 * ll_homo + 2 * 3) - (-2 * ll_LS + 2 * 4), 1)

## ---- coverage ----
set.seed(55)
xt <- runif(20000, 0, 10)
yt <- rnorm(20000, a0 + a1 * xt, exp(c0 + c1 * xt))
z90 <- qnorm(0.95)
covN <- abs(yt - (coef(ols)[1] + coef(ols)[2] * xt)) <= z90 * sdm
covL <- abs(yt - (bML[1] + bML[2] * xt)) <= z90 * exp(gML[1] + gML[2] * xt)
terc <- cut(xt, quantile(xt, c(0, 1/3, 2/3, 1)), include.lowest = TRUE,
            labels = c("low", "mid", "high"))
rbind(naive = tapply(covN, terc, mean), locscale = tapply(covL, terc, mean))

## ---- cov-scalars ----
r_nlo <- round(mean(covN[terc == "low"]), 3); r_nhi <- round(mean(covN[terc == "high"]), 3)
r_llo <- round(mean(covL[terc == "low"]), 3); r_lhi <- round(mean(covL[terc == "high"]), 3)
r_novr <- round(mean(covN), 3); r_lovr <- round(mean(covL), 3)

## ---- fig-bands ----
xg <- seq(0, 10, length.out = 80)
bd <- data.frame(x = xg, muL = bML[1] + bML[2] * xg, sL = exp(gML[1] + gML[2] * xg),
                 muN = coef(ols)[1] + coef(ols)[2] * xg)
ggplot() +
  geom_point(aes(x, y), colour = sage, alpha = 0.55, size = 1.4) +
  geom_ribbon(data = bd, aes(x, ymin = muN - z90 * sdm, ymax = muN + z90 * sdm),
              fill = NA, colour = faint, linetype = "dashed", linewidth = 0.7) +
  geom_ribbon(data = bd, aes(x, ymin = muL - z90 * sL, ymax = muL + z90 * sL),
              fill = forest, alpha = 0.16) +
  geom_line(data = bd, aes(x, muL), colour = forest, linewidth = 0.9) +
  labs(x = "resource gradient", y = "response",
       subtitle = "shaded = location-scale 90% band; dashed = naive constant-width band") +
  theme_te()

## ---- bridge ----
xg <- seq(0, 10, length.out = 60)
agree <- sapply(c(0.1, 0.9), function(tt) {
  para <- (bML[1] + bML[2] * xg) + qnorm(tt) * exp(gML[1] + gML[2] * xg)
  qc   <- qrfit(x, y, tt)
  sdx  <- exp(gML[1] + gML[2] * xg)     # local fitted spread: the yardstick that matters
  max(abs(para - (qc[1] + qc[2] * xg)) / sdx)
})
round(agree, 3)

## ---- bridge-scalars ----
r_g10 <- round(agree[1], 2); r_g90 <- round(agree[2], 2)

## ---- skew ----
set.seed(4214)
e0 <- (rgamma(n, 2, 1) - 2) / sqrt(2)          # standardised right-skewed error
ys <- (a0 + a1 * x) + exp(c0 + c1 * x) * e0
fs <- optim(c(unname(coef(lm(ys ~ x))), log(sd(resid(lm(ys ~ x)))), 0),
            nll, X = X, Z = Z, y = ys, method = "BFGS")
bS <- fs$par[1:2]; gS <- fs$par[3:4]
qc95 <- qrfit(x, ys, 0.95)
set.seed(77)
xts <- runif(40000, 0, 10)
yts <- (a0 + a1 * xts) + exp(c0 + c1 * xts) * (rgamma(40000, 2, 1) - 2) / sqrt(2)
gaussQ <- (bS[1] + bS[2] * xts) + qnorm(0.95) * exp(gS[1] + gS[2] * xts)
qrQ    <- qc95[1] + qc95[2] * xts
c(gaussian = mean(yts < gaussQ), quantile_reg = mean(yts < qrQ))

## ---- skew-scalars ----
r_g95 <- round(mean(yts < gaussQ), 3); r_qr95 <- round(mean(yts < qrQ), 3)

## ---- fig-skew ----
bins <- cut(x, seq(0, 10, 1.25), include.lowest = TRUE)
emp <- tapply(seq_along(ys), bins, function(i) quantile(ys[i], 0.95))
ebd <- data.frame(x = seq(0.625, 10, 1.25)[seq_along(emp)], q = as.numeric(emp))
ll <- data.frame(x = xg, gauss = (bS[1] + bS[2] * xg) + qnorm(0.95) * exp(gS[1] + gS[2] * xg),
                 qr = qc95[1] + qc95[2] * xg)
ggplot() +
  geom_point(aes(x, ys), colour = sage, alpha = 0.4, size = 1.2) +
  geom_point(data = ebd, aes(x, q), colour = ink, size = 2.2, shape = 18) +
  geom_line(data = ll, aes(x, gauss, colour = "Gaussian location-scale"), linewidth = 1) +
  geom_line(data = ll, aes(x, qr, colour = "distribution-free QR"), linewidth = 1) +
  scale_colour_manual(values = c("Gaussian location-scale" = warm,
                                 "distribution-free QR" = forest), name = NULL) +
  labs(x = "resource gradient", y = "response (right-skewed error)",
       subtitle = "diamonds = binned empirical 0.95 quantile") +
  theme_te()
