# Threshold regression with a GLM
# https://tidyecology.com/posts/threshold-regression-glm/
#
# 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)
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_faint <- "#5d6b61"; te_gold <- "#cda23f"
te_green <- "#2f8f63"; te_terra <- "#b5534e"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = te_faint, size = base_size - 2),
          axis.title = element_text(colour = te_body, size = base_size - 1),
          plot.title = element_text(colour = te_ink, face = "bold", size = base_size + 1),
          plot.subtitle = element_text(colour = te_label, size = base_size - 1),
          plot.caption = element_text(colour = te_faint, size = base_size - 3),
          legend.position = "top", plot.margin = margin(10, 12, 8, 10))
}

## ---- data-a ----
set.seed(4200)
n <- 200
temp <- runif(n, 0, 30); psi_true <- 15
count <- rpois(n, exp(2.5 + 0.0 * temp - 0.12 * pmax(temp - psi_true, 0)))

## ---- naive-a ----
fit_naive <- glm(count ~ temp, family = poisson)
naive_slope <- coef(fit_naive)[["temp"]]

## ---- thr-a ----
dev_at <- function(p) deviance(glm(count ~ temp + pmax(temp - p, 0), family = poisson))
grid <- seq(5, 25, by = 0.25)
psi_hat <- grid[which.min(vapply(grid, dev_at, numeric(1)))]
hinge <- pmax(temp - psi_hat, 0)
fit_thr <- glm(count ~ temp + hinge, family = poisson)
cf <- coef(fit_thr)
below_log <- cf[["temp"]]
above_log <- cf[["temp"]] + cf[["hinge"]]

## ---- fig-poisson ----
gx <- seq(0, 30, length.out = 400)
predA <- data.frame(gx,
  naive = exp(coef(fit_naive)[[1]] + coef(fit_naive)[[2]] * gx),
  thr = exp(cf[[1]] + cf[[2]] * gx + cf[[3]] * pmax(gx - psi_hat, 0)))
ggplot(data.frame(temp, count), aes(temp, count)) +
  geom_point(colour = te_forest, alpha = 0.45, size = 1.6) +
  geom_line(data = predA, aes(gx, naive), colour = te_terra, linewidth = 1.0, linetype = "22") +
  geom_line(data = predA, aes(gx, thr), colour = te_forest, linewidth = 1.1) +
  geom_vline(xintercept = psi_hat, colour = te_gold, linewidth = 0.6) +
  annotate("text", x = 1, y = 2, hjust = 0, label = "naive log-linear (dashed)", colour = te_terra, size = 3.4) +
  labs(x = "Temperature", y = "Count",
       title = "A threshold on the log scale of a Poisson GLM",
       subtitle = "Threshold GLM (solid) vs a single log-linear slope (dashed)") +
  theme_te()

## ---- data-b ----
set.seed(4210)
x <- runif(200, 0, 30); psi0 <- 15
yb <- rpois(200, exp(2.4 - 1.1 * (x > psi0)))
g <- seq(5, 25, by = 0.25)
dev_cont <- function(p) deviance(glm(yb ~ x + pmax(x - p, 0), family = poisson))       # slope change
dev_step <- function(p) deviance(glm(yb ~ x + as.numeric(x > p), family = poisson))    # level shift
pc <- g[which.min(vapply(g, dev_cont, numeric(1)))]
ps <- g[which.min(vapply(g, dev_step, numeric(1)))]
fit_cont <- glm(yb ~ x + pmax(x - pc, 0), family = poisson)
fit_step <- glm(yb ~ x + as.numeric(x > ps), family = poisson)
aic_cont <- AIC(fit_cont) + 2
aic_step <- AIC(fit_step) + 2

## ---- fig-step ----
cc <- coef(fit_cont); cs <- coef(fit_step)
predB <- data.frame(gx,
  cont = exp(cc[[1]] + cc[[2]] * gx + cc[[3]] * pmax(gx - pc, 0)),
  step = exp(cs[[1]] + cs[[2]] * gx + cs[[3]] * as.numeric(gx > ps)))
ggplot(data.frame(x, yb), aes(x, yb)) +
  geom_point(colour = te_forest, alpha = 0.45, size = 1.6) +
  geom_line(data = predB, aes(gx, cont), colour = te_terra, linewidth = 1.0, linetype = "22") +
  geom_line(data = predB, aes(gx, step), colour = te_forest, linewidth = 1.1) +
  annotate("text", x = 0.5, y = 2, hjust = 0, label = "slope change (dashed)", colour = te_terra, size = 3.4) +
  annotate("text", x = 0.5, y = 0.3, hjust = 0, label = "level shift (solid)", colour = te_forest, size = 3.4) +
  labs(x = "Environmental gradient", y = "Count",
       title = "A gradual turn or an abrupt shift?",
       subtitle = "Regime-shift data: the step model captures the jump a slope change cannot") +
  theme_te()

## ---- how-many ----
dev0 <- deviance(glm(count ~ temp, family = poisson))
dev1 <- deviance(fit_thr)
g2 <- seq(6, 24, by = 1)
best2 <- Inf
for (a in g2) for (b in g2) if (b > a + 1) {
  d <- deviance(glm(count ~ temp + pmax(temp - a, 0) + pmax(temp - b, 0), family = poisson))
  if (d < best2) best2 <- d
}
dev2 <- best2
aic_k <- c(dev0 + 2 * 2, dev1 + 2 * 4, dev2 + 2 * 6)   # k = 2, 4, 6 parameters
bic_k <- c(dev0 + log(n) * 2, dev1 + log(n) * 4, dev2 + log(n) * 6)
