# Checking a threshold model
# https://tidyecology.com/posts/checking-a-threshold-model/
#
# 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-08

## ---- 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))
}

## ---- 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)), "}$")
}

## ---- residuals ----
set.seed(4231)
n <- 90
x <- runif(n, 0, 30); psi0 <- 14
y <- 18 + 0.10 * x - 0.55 * pmax(x - psi0, 0) + rnorm(n, 0, 2.5)
grid <- seq(4, 26, by = 0.2)
psi_hat <- grid[which.min(vapply(grid, function(p) sum(lm(y ~ x + pmax(x - p, 0))$residuals^2), numeric(1)))]
fit_line <- lm(y ~ x)
fit_thr  <- lm(y ~ x + pmax(x - psi_hat, 0))

line_curv <- summary(lm(residuals(fit_line) ~ poly(fitted(fit_line), 2)))$coefficients[3, 4]
thr_curv  <- summary(lm(residuals(fit_thr)  ~ poly(fitted(fit_thr),  2)))$coefficients[3, 4]

## ---- fig-residuals ----
rd <- rbind(
  data.frame(fit = fitted(fit_line), res = residuals(fit_line), model = "single line"),
  data.frame(fit = fitted(fit_thr),  res = residuals(fit_thr),  model = "broken stick"))
rd$model <- factor(rd$model, levels = c("single line", "broken stick"))
ggplot(rd, aes(fit, res)) +
  geom_hline(yintercept = 0, colour = te_faint, linewidth = 0.4) +
  geom_point(colour = te_forest, alpha = 0.5, size = 1.5) +
  geom_smooth(method = "loess", formula = y ~ x,
              se = FALSE, colour = te_terra, linewidth = 0.9, span = 0.9) +
  facet_wrap(~ model) +
  labs(x = "Fitted value", y = "Residual",
       title = "Do the residuals still carry a pattern?",
       subtitle = "The single line leaves a curve in its residuals; the broken stick leaves no clear one") +
  theme_te() + theme(strip.text = element_text(colour = te_label, face = "bold"))

## ---- fit-bs ----
fit_bs <- function(x, y, grid) {
  n <- length(y)
  rss <- vapply(grid, function(p) sum(lm(y ~ x + pmax(x - p, 0))$residuals^2), numeric(1))
  psi <- grid[which.min(rss)]; rss_min <- min(rss); sig2 <- rss_min / (n - 3)
  aug <- lm(y ~ x + pmax(x - psi, 0) + as.numeric(x > psi))    # Muggeo's augmented fit
  se_psi <- summary(aug)$coefficients[4, 2] / abs(coef(aug)[[3]])
  wald <- psi + c(-1, 1) * 1.96 * se_psi
  prof <- range(grid[rss <= rss_min + sig2 * qchisq(0.95, 1)])
  list(wald = wald, prof = prof)
}

## ---- coverage ----
set.seed(4201)
Rrep <- 1500; n <- 80; psi0 <- 14
cov_wald <- 0; cov_prof <- 0
for (r in seq_len(Rrep)) {
  x <- runif(n, 0, 30)
  y <- 18 + 0.10 * x - 0.60 * pmax(x - psi0, 0) + rnorm(n, 0, 3)
  f <- fit_bs(x, y, grid)
  cov_wald <- cov_wald + (psi0 >= f$wald[1] && psi0 <= f$wald[2])
  cov_prof <- cov_prof + (psi0 >= f$prof[1] && psi0 <= f$prof[2])
}
cov_wald <- cov_wald / Rrep; cov_prof <- cov_prof / Rrep

## ---- fig-coverage ----
rows <- list()
for (r in seq_len(40)) {
  x <- runif(n, 0, 30); y <- 18 + 0.10 * x - 0.60 * pmax(x - psi0, 0) + rnorm(n, 0, 3)
  fr <- fit_bs(x, y, grid); pj <- grid[which.min(vapply(grid, function(p) sum(lm(y ~ x + pmax(x - p, 0))$residuals^2), numeric(1)))]
  rows[[length(rows) + 1]] <- data.frame(id = r, psi = pj, method = "Wald",
    lo = fr$wald[1], hi = fr$wald[2], cover = psi0 >= fr$wald[1] && psi0 <= fr$wald[2])
  rows[[length(rows) + 1]] <- data.frame(id = r, psi = pj, method = "profile",
    lo = fr$prof[1], hi = fr$prof[2], cover = psi0 >= fr$prof[1] && psi0 <= fr$prof[2])
}
cat_df <- do.call(rbind, rows)
ord <- cat_df$id[cat_df$method == "Wald"][order(cat_df$psi[cat_df$method == "Wald"])]
cat_df$rank <- match(cat_df$id, ord)
cat_df$method <- factor(cat_df$method, levels = c("Wald", "profile"))
ggplot(cat_df, aes(y = rank)) +
  geom_vline(xintercept = psi0, colour = te_gold, linewidth = 0.7) +
  geom_segment(aes(x = lo, xend = hi, yend = rank, colour = cover), linewidth = 0.7) +
  facet_wrap(~ method) +
  scale_colour_manual(values = c(`TRUE` = te_green, `FALSE` = te_terra),
                      labels = c(`TRUE` = "covers", `FALSE` = "misses"), name = NULL) +
  labs(x = "Breakpoint interval", y = "Data set (sorted)",
       title = "Wald intervals miss the breakpoint too often",
       subtitle = "40 data sets; gold line is the true breakpoint at 14") +
  theme_te() + theme(strip.text = element_text(colour = te_label, face = "bold"),
                     axis.text.y = element_blank())

## ---- sensitivity ----
set.seed(9014)
n <- 120
x <- runif(n, 0, 30); psi0 <- 14
y <- 18 + 0.10 * x - 0.70 * pmax(x - psi0, 0) + rnorm(n, 0, 2.5)
psi_cont <- grid[which.min(vapply(grid, function(p) sum(lm(y ~ x + pmax(x - p, 0))$residuals^2), numeric(1)))]
psi_step <- grid[which.min(vapply(grid, function(p) sum(lm(y ~ x + as.numeric(x > p))$residuals^2), numeric(1)))]

est_psi <- function(xx, yy) {
  g <- seq(4, 26, by = 0.25)
  g[which.min(vapply(g, function(p) sum(lm(yy ~ xx + pmax(xx - p, 0))$residuals^2), numeric(1)))]
}
set.seed(31)
boot_psi <- replicate(1500, { i <- sample.int(n, n, replace = TRUE); est_psi(x[i], y[i]) })
bci <- quantile(boot_psi, c(0.025, 0.975))
