# Early warning signals and critical slowing
# https://tidyecology.com/posts/early-warning-signals-critical-slowing/
#
# 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-06-06

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

## positive equilibria (f/x = 0) and the fold, by scanning c
g <- function(x, c) r*(1 - x/K) - c*x/(x^2 + h^2)
cgrid <- seq(1.0, 3.2, by = 0.002)
nroot <- sapply(cgrid, function(c){
  xs <- seq(0.001, K, length.out = 6000)
  length(which(diff(sign(g(xs, c))) != 0))
})
c_fold <- cgrid[min(which(nroot <= 1 & cgrid > 2.0))]

## ---- recovery ----
fp <- function(x, c) r*(1 - 2*x/K) - c*(2*x*h^2)/(x^2 + h^2)^2   # d f / d x
upper_eq <- function(c){ xs <- seq(0.001, K, length.out = 6000)
  idx <- which(diff(sign(g(xs, c))) != 0); max((xs[idx] + xs[idx+1])/2) }
lam <- function(c) fp(upper_eq(c), c)          # dominant eigenvalue (negative)
lam_lo <- lam(1.0); lam_hi <- lam(2.58)
ar1_theory_lo <- exp(lam_lo); ar1_theory_hi <- exp(lam_hi)   # discrete-time AR(1) at unit step

## ---- simulate ----
sim_grazing <- function(seed, T = 600, dt = 0.01, sigma = 0.30,
                        c0 = 1.0, c1 = 2.72, x0 = 8.9){
  set.seed(seed)
  nstep <- T/dt
  cvec  <- seq(c0, c1, length.out = nstep)
  x <- numeric(nstep); x[1] <- x0
  for(i in 2:nstep){
    xi <- x[i-1]
    x[i] <- xi + f(xi, cvec[i-1])*dt + sigma*sqrt(dt)*rnorm(1)
    if(x[i] < 0.001) x[i] <- 0.001
  }
  keep <- seq(1, nstep, 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]                 # first crossing into the lower state
t_tr   <- d$t[tr_idx]; c_tr <- d$c[tr_idx]

## ---- ews ----
seg <- d$x[1:(tr_idx - 10)]; tt <- d$t[1:(tr_idx - 10)]
n <- length(seg)

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
}
res <- gauss_detrend(seg, 0.10 * n)

win    <- round(0.50 * n)                      # window = half the record
starts <- 1:(n - win + 1)
ar1 <- numeric(length(starts)); vv <- numeric(length(starts))
for(k in seq_along(starts)){
  w <- res[starts[k]:(starts[k] + win - 1)]
  vv[k]  <- var(w)
  ar1[k] <- ar.ols(w, order.max = 1, aic = FALSE,
                   demean = TRUE, intercept = FALSE)$ar[1]
}
tmid <- tt[starts + win %/% 2]

kt_ar  <- cor(seq_along(ar1), ar1, method = "kendall")
kt_var <- cor(seq_along(vv),  vv,  method = "kendall")

## ---- 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-series ----
p_top <- ggplot(d, aes(t, x)) +
  annotate("rect", xmin = 0, xmax = tt[n], ymin = -Inf, ymax = Inf,
           fill = sage, alpha = 0.12) +
  geom_line(colour = forest, linewidth = 0.4) +
  geom_vline(xintercept = t_tr, colour = brick, linetype = "dashed", linewidth = 0.4) +
  labs(title = "Biomass approaching a fold", subtitle = "shaded: pre-transition record analysed",
       x = NULL, y = "biomass x") + theme_te()
p_bot <- ggplot(d, aes(t, c)) +
  geom_line(colour = amber, linewidth = 0.6) +
  geom_hline(yintercept = c_fold, colour = brick, linetype = "dashed", linewidth = 0.4) +
  annotate("text", x = 60, y = c_fold + 0.06, label = "fold", colour = brick, size = 3,
           hjust = 0, vjust = 0) +
  labs(x = "time", y = "grazing pressure c") + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1, heights = c(1.15, 1))))
print(p_top, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_bot, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- fig-indicators ----
di <- data.frame(t = tmid, ar1 = ar1, vv = vv)
p_ar <- ggplot(di, aes(t, ar1)) + geom_line(colour = forest, linewidth = 0.6) +
  labs(title = "Lag-1 autocorrelation",
       subtitle = paste0("Kendall tau = ", sprintf("%.2f", kt_ar)),
       x = "window mid-time", y = "AR(1)") + theme_te()
p_vv <- ggplot(di, aes(t, vv)) + geom_line(colour = amber, linewidth = 0.6) +
  labs(title = "Variance",
       subtitle = paste0("Kendall tau = ", sprintf("%.2f", kt_var)),
       x = "window mid-time", y = "variance") + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p_ar, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_vv, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
