# Checking early warning signals
# https://tidyecology.com/posts/checking-early-warning-signals/
#
# 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-01

## ---- machinery ----
r <- 1; K <- 10; h <- 1
f <- function(x, c) r*x*(1 - x/K) - c*x^2/(x^2 + h^2)

gauss_detrend <- function(y, bw){ tg <- seq_along(y)
  trend <- sapply(tg, function(i){ w <- dnorm(tg, i, bw); sum(w*y)/sum(w) }); y - trend }
ar1_fast <- function(w){ w <- w - mean(w); L <- length(w)
  sum(w[2:L]*w[1:(L-1)]) / sum(w[1:(L-1)]^2) }              # == ar.ols(order 1, no intercept)
roll_ar1 <- function(res, wf = 0.5){ win <- round(wf*length(res)); s <- 1:(length(res)-win+1)
  sapply(s, function(k) ar1_fast(res[k:(k+win-1)])) }
roll_var <- function(res, wf = 0.5){ win <- round(wf*length(res)); s <- 1:(length(res)-win+1)
  sapply(s, function(k) var(res[k:(k+win-1)])) }
kt <- function(v) cor(seq_along(v), v, method = "kendall")

sim_grazing <- function(seed, T = 600, dt = 0.01, sigma = 0.30, c0 = 1.0, c1 = 2.72, x0 = 8.9){
  set.seed(seed); ns <- T/dt; cvec <- seq(c0, c1, length.out = ns); x <- numeric(ns); x[1] <- x0
  for(i in 2:ns){ x[i] <- x[i-1] + f(x[i-1], cvec[i-1])*dt + sigma*sqrt(dt)*rnorm(1)
    if(x[i] < 0.001) x[i] <- 0.001 }
  keep <- seq(1, ns, by = 1/dt); data.frame(t = (keep-1)*dt, x = x[keep], c = cvec[keep]) }

d <- sim_grazing(seed = 4238)
tr_idx <- which(d$x < 3.5)[1]
seg <- d$x[1:(tr_idx - 10)]; n <- length(seg)
res <- gauss_detrend(seg, 0.10*n)
tau_obs <- kt(roll_ar1(res))

## ---- surrogates ----
arboot_taus <- function(res, B, seed){ set.seed(seed); phi <- ar1_fast(res)
  e <- res[-1] - phi*res[-length(res)]; e <- e - mean(e); nn <- length(res)
  replicate(B, { innov <- sample(e, nn, replace = TRUE); y <- numeric(nn); y[1] <- innov[1]
    for(i in 2:nn) y[i] <- phi*y[i-1] + innov[i]; kt(roll_ar1(y)) }) }
phase_taus <- function(y, B, seed){ set.seed(seed); nn <- length(y); amp <- Mod(fft(y))
  replicate(B, { ph <- runif((nn - 1) %/% 2, 0, 2*pi)
    phases <- c(0, ph, if(nn %% 2 == 0) 0 else NULL, -rev(ph))
    s <- Re(fft(amp*exp(1i*phases), inverse = TRUE)/nn); kt(roll_ar1(s)) }) }

ta <- arboot_taus(res, 500, 71)
tp <- phase_taus(res, 500, 72)
p_ar <- (1 + sum(ta >= tau_obs)) / 501
p_ph <- (1 + sum(tp >= tau_obs)) / 501
q95_ar <- quantile(ta, 0.95)

## ---- setup-theme ----
library(ggplot2)
ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"; label <- "#46604a"
sage <- "#93a87f"; paper <- "#f5f4ee"; line <- "#dad9ca"; faint <- "#5d6b61"
amber <- "#cda23f"; brick <- "#b5534e"
theme_te <- function(){ theme_minimal(base_size = 11) +
  theme(plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = line, linewidth = 0.3),
        axis.title = element_text(colour = body), axis.text = element_text(colour = faint),
        plot.title = element_text(colour = ink, face = "bold", size = 12),
        plot.subtitle = element_text(colour = label, size = 10),
        legend.position = "none") }

## ---- fig-surrogates ----
ds <- data.frame(tau = ta)
p_surr <- ggplot(ds, aes(tau)) +
  geom_histogram(bins = 40, fill = sage, colour = "white", alpha = 0.8) +
  geom_vline(xintercept = tau_obs, colour = forest, linewidth = 0.9) +
  geom_vline(xintercept = q95_ar, colour = brick, linetype = "dashed", linewidth = 0.6) +
  annotate("text", x = tau_obs, y = Inf, label = "observed ", colour = forest,
           hjust = 1, vjust = 2, size = 3.4) +
  annotate("text", x = q95_ar, y = Inf, label = " 95th pct", colour = brick,
           hjust = 0, vjust = 4, size = 3.2) +
  labs(title = "Observed trend against the surrogate null",
       subtitle = paste0("autoregressive-bootstrap p = ", sprintf("%.3f", p_ar)),
       x = "Kendall tau of surrogate", y = "count") + theme_te()
p_surr

## ---- thumb ----
ggsave("thumbnail.png", p_surr, width = 7.5, height = 5.4, dpi = 100)

## ---- falsepos ----
sim_stat <- function(seed, cc = 2.0, n = 200, dt = 0.05, sigma = 0.30, x0 = 7.32){
  set.seed(seed); ns <- n/dt; x <- numeric(ns); x[1] <- x0
  for(i in 2:ns){ x[i] <- x[i-1] + f(x[i-1], cc)*dt + sigma*sqrt(dt)*rnorm(1)
    if(x[i] < 0.001) x[i] <- 0.001 }
  x[seq(1, ns, by = 1/dt)] }

M <- 300; nb <- 200; naive_rej <- 0; surro_rej <- 0; tau_null <- numeric(M)
for(m in 1:M){
  y <- sim_stat(5000 + m); rr <- gauss_detrend(y, 0.10*nb)
  a <- roll_ar1(rr); to <- kt(a); tau_null[m] <- to
  pn <- cor.test(seq_along(a), a, method = "kendall")$p.value
  if(!is.na(pn) && pn < 0.05 && to > 0) naive_rej <- naive_rej + 1
  ps <- (1 + sum(arboot_taus(rr, 150, 9000 + m) >= to)) / 151
  if(ps < 0.05) surro_rej <- surro_rej + 1
}
naive_fp <- naive_rej/M; surro_fp <- surro_rej/M
sd_null <- sd(tau_null); frac_half <- mean(tau_null > 0.5)

## ---- fig-falsepos ----
p_hist <- ggplot(data.frame(tau = tau_null), aes(tau)) +
  geom_histogram(bins = 40, fill = sage, colour = "white", alpha = 0.8) +
  geom_vline(xintercept = 0.5, colour = faint, linetype = "dotted", linewidth = 0.4) +
  geom_vline(xintercept = tau_obs, colour = forest, linewidth = 0.9) +
  annotate("text", x = tau_obs, y = Inf, label = " observed", colour = forest,
           hjust = 0, vjust = 2, size = 3.2) +
  scale_x_continuous(expand = expansion(mult = c(0.05, 0.20))) +
  labs(title = "Trend statistic under a stationary null", x = "Kendall tau", y = "count") + theme_te()
d_fp <- data.frame(test = factor(c("naive", "surrogate"), levels = c("naive", "surrogate")),
                   fp = c(naive_fp, surro_fp))
p_bar <- ggplot(d_fp, aes(test, fp, fill = test)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 0.05, colour = brick, linetype = "dashed", linewidth = 0.5) +
  scale_fill_manual(values = c("naive" = amber, "surrogate" = forest)) +
  labs(title = "False-positive rate", x = NULL, y = "P(declare warning | no transition)") + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p_hist, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_bar,  vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- falsealarm ----
sim_risingnoise <- function(seed, cc = 2.0, n = 300, dt = 0.05, s0 = 0.12, s1 = 0.55, x0 = 7.32){
  set.seed(seed); ns <- n/dt; sv <- seq(s0, s1, length.out = ns); x <- numeric(ns); x[1] <- x0
  for(i in 2:ns){ x[i] <- x[i-1] + f(x[i-1], cc)*dt + sv[i-1]*sqrt(dt)*rnorm(1)
    if(x[i] < 0.001) x[i] <- 0.001 }
  x[seq(1, ns, by = 1/dt)] }
y_fa <- sim_risingnoise(seed = 4241); r_fa <- gauss_detrend(y_fa, 0.10*length(y_fa))
tau_var_fa <- kt(roll_var(r_fa)); tau_ar_fa <- kt(roll_ar1(r_fa))

## ---- fastapproach ----
sim_fast <- function(seed, T = 90, dt = 0.01, sigma = 0.30, c0 = 1.0, c1 = 2.95, x0 = 8.9){
  set.seed(seed); ns <- T/dt; cvec <- seq(c0, c1, length.out = ns); x <- numeric(ns); x[1] <- x0
  for(i in 2:ns){ x[i] <- x[i-1] + f(x[i-1], cvec[i-1])*dt + sigma*sqrt(dt)*rnorm(1)
    if(x[i] < 0.001) x[i] <- 0.001 }
  keep <- seq(1, ns, by = 1/dt); data.frame(t = (keep-1)*dt, x = x[keep], c = cvec[keep]) }

tau_fast <- c()
for(sd in 1:30){ df <- sim_fast(sd); tp <- which(df$x < 3.5)[1]
  if(is.na(tp) || tp < 40) next; sg <- df$x[1:(tp-4)]; if(length(sg) < 50) next
  tau_fast <- c(tau_fast, kt(roll_ar1(gauss_detrend(sg, 0.10*length(sg))))) }
med_fast <- median(tau_fast); lo_fast <- min(tau_fast); hi_fast <- max(tau_fast)

## ---- fig-necessary ----
d_fa <- data.frame(t = seq_along(y_fa), x = y_fa)
p_fa <- ggplot(d_fa, aes(t, x)) + geom_line(colour = amber, linewidth = 0.4) +
  labs(title = "Constant driver, growing noise", subtitle = paste0("variance tau = ", sprintf("%+.2f", tau_var_fa)),
       x = "time", y = "biomass x") + theme_te()
d_ft <- data.frame(tau = tau_fast)
p_ft <- ggplot(d_ft, aes(x = 1, y = tau)) +
  geom_hline(yintercept = tau_obs, colour = forest, linewidth = 0.6) +
  geom_hline(yintercept = 0, colour = faint, linetype = "dotted", linewidth = 0.4) +
  geom_jitter(width = 0.12, height = 0, colour = brick, size = 2, alpha = 0.8) +
  annotate("text", x = Inf, y = tau_obs, label = "slow approach", colour = forest, size = 3,
           hjust = 1.05, vjust = -0.5) +
  labs(title = "Fast approach across noise seeds", subtitle = paste0("median tau = ", sprintf("%.2f", med_fast)),
       x = NULL, y = "AR(1) Kendall tau") +
  theme_te() + theme(axis.text.x = element_blank())
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p_fa, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_ft, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
