# Testing for an ecological threshold
# https://tidyecology.com/posts/detecting-ecological-thresholds/
#
# 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))
}

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

## ---- supf ----
seg_supF <- function(x, y, grid) {
  fit0 <- lm(y ~ x); rss0 <- sum(fit0$residuals^2); n <- length(y)
  best <- Inf; psi <- NA
  for (p in grid) {
    r <- sum(lm(y ~ x + pmax(x - p, 0))$residuals^2)
    if (r < best) { best <- r; psi <- p }
  }
  list(F = ((rss0 - best) / 1) / (best / (n - 3)), psi = psi)
}
grid <- seq(4, 26, by = 0.2)

## ---- typeI ----
set.seed(4199)
Rrep <- 2000; n <- 80
naive_p <- numeric(Rrep)
for (r in seq_len(Rrep)) {
  x <- runif(n, 0, 30)
  y <- 20 - 0.15 * x + rnorm(n, 0, 3)         # a plain line, no break
  naive_p[r] <- pf(seg_supF(x, y, grid)$F, 1, n - 3, lower.tail = FALSE)
}
rej_naive <- mean(naive_p < 0.05)

## ---- fig-pvalues ----
pd <- data.frame(p = naive_p)
ggplot(pd, aes(p)) +
  geom_histogram(breaks = seq(0, 1, 0.05), fill = te_sage, colour = te_paper, linewidth = 0.3) +
  geom_hline(yintercept = Rrep / 20, colour = te_forest, linewidth = 0.8, linetype = "22") +
  annotate("rect", xmin = 0, xmax = 0.05, ymin = 0, ymax = Inf, fill = te_terra, alpha = 0.18) +
  annotate("text", x = 0.5, y = Rrep / 20 + 30, label = "uniform (a valid test)",
           colour = te_forest, size = 3.4, hjust = 0.5) +
  annotate("text", x = 0.08, y = max(table(cut(naive_p, seq(0, 1, 0.05)))) * 0.7, hjust = 0,
           label = sprintf("%.0f%% reject at 0.05", 100 * rej_naive), colour = te_terra, size = 3.4) +
  labs(x = "Naive p-value for a slope change (data have no break)", y = "Count",
       title = "The naive break test rejects far too often",
       subtitle = "Under no break the p-values should be flat; instead they pile up near zero") +
  theme_te()

## ---- break-example ----
set.seed(781)
n <- 100
x <- runif(n, 0, 30); psi0 <- 14
y <- 18 + 0.10 * x - 0.80 * pmax(x - psi0, 0) + rnorm(n, 0, 2.5)
obs <- seg_supF(x, y, grid)
naive_p_obs <- pf(obs$F, 1, n - 3, lower.tail = FALSE)

fit0 <- lm(y ~ x); sig0 <- summary(fit0)$sigma
set.seed(55)
B <- 1200
null_F <- replicate(B, seg_supF(x, fitted(fit0) + rnorm(n, 0, sig0), grid)$F)
p_boot <- (1 + sum(null_F >= obs$F)) / (B + 1)
crit_boot  <- quantile(null_F, 0.95)
crit_naive <- qf(0.95, 1, n - 3)
size_naive <- mean(null_F > crit_naive)     # the naive test's true size

## ---- smooth ----
set.seed(4299)
n <- 90
x <- runif(n, 0, 30)
y <- 30 * x / (6 + x) + rnorm(n, 0, 2.2)        # smooth saturation, no kink
sm <- seg_supF(x, y, grid)
naive_p_smooth <- pf(sm$F, 1, n - 3, lower.tail = FALSE)

fit_seg <- lm(y ~ x + pmax(x - sm$psi, 0))
fit_mm  <- nls(y ~ SSmicmen(x, Vm, K))          # the smooth alternative
aic_seg <- AIC(fit_seg) + 2                      # +2 for the estimated breakpoint
aic_mm  <- AIC(fit_mm)

## ---- fig-smooth ----
cf <- coef(fit_seg); gx <- seq(0, 30, length.out = 400)
pred <- data.frame(gx,
  seg = cf[[1]] + cf[[2]] * gx + cf[[3]] * pmax(gx - sm$psi, 0),
  mm  = predict(fit_mm, newdata = data.frame(x = gx)))
ggplot(data.frame(x, y), aes(x, y)) +
  geom_point(colour = te_forest, alpha = 0.5, size = 1.7) +
  geom_line(data = pred, aes(gx, seg), colour = te_terra, linewidth = 1.1, linetype = "22") +
  geom_line(data = pred, aes(gx, mm), colour = te_forest, linewidth = 1.1) +
  geom_vline(xintercept = sm$psi, colour = te_gold, linewidth = 0.6) +
  annotate("text", x = 16, y = 8, hjust = 0, label = "broken stick (dashed)", colour = te_terra, size = 3.4) +
  annotate("text", x = 16, y = 5, hjust = 0, label = "smooth curve (solid)", colour = te_forest, size = 3.4) +
  labs(x = "Environmental gradient", y = "Response",
       title = "A significant break test is not a threshold",
       subtitle = "Smooth saturating data: the test rejects a line, but there is no kink") +
  theme_te()
