# Hysteresis and tipping points
# https://tidyecology.com/posts/hysteresis-and-tipping-points/
#
# 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-07-04

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_up <- "#3a6b52"; col_dn <- "#b5651d"; col_ref <- "#555555"; col_un <- "#8aa29e"

r <- 1; K <- 10; h <- 1
growth <- function(x) r*x*(1 - x/K); graze <- function(x, c) c*x^2/(x^2 + h^2)
# equilibrium curve via inversion: c(x) = growth(x) / (x^2/(x^2+h^2))
xg <- seq(0.02, K, 0.002); cg <- growth(xg) / (xg^2/(xg^2 + h^2))
# fold points: turning points of c(x)
dcg <- diff(cg); turn <- which(diff(sign(dcg)) != 0)
folds_c <- sort(cg[turn + 1]); c_recover <- folds_c[1]; c_collapse <- folds_c[2]
# hysteresis sweep
sim_eq <- function(c, x0, Tn = 400, dt = 0.05) { x <- x0; for (t in 1:(Tn/dt)) x <- max(x + (growth(x) - graze(x, c))*dt, 0); x }
cs <- seq(1.4, 3.0, 0.02)
up <- numeric(length(cs)); x <- 9; for (i in seq_along(cs)) { x <- sim_eq(cs[i], x); up[i] <- x }
dn <- numeric(length(cs)); x <- 0.3; for (i in rev(seq_along(cs))) { x <- sim_eq(cs[i], x); dn[i] <- x }
veg_at2 <- up[which.min(abs(cs - 2))]; col_at2 <- dn[which.min(abs(cs - 2))]
window_w <- c_collapse - c_recover

## ---- equilibrium ----
r <- 1; K <- 10; h <- 1
growth <- function(x) r*x*(1 - x/K)          # logistic growth
graze  <- function(x, c) c*x^2/(x^2 + h^2)   # saturating, threshold-shaped loss
xg <- seq(0.02, K, 0.002)
cg <- growth(xg) / (xg^2/(xg^2 + h^2))          # grazing pressure that holds each x steady
c(lower_fold = round(sort(cg[which(diff(sign(diff(cg))) != 0) + 1])[1], 2),
  upper_fold = round(sort(cg[which(diff(sign(diff(cg))) != 0) + 1])[2], 2))

## ---- fig-fold ----
# classify each branch by its position relative to the two fold x-values
xfold <- xg[which(diff(sign(diff(cg))) != 0) + 1]
branch <- ifelse(xg < min(xfold), "collapsed (stable)",
          ifelse(xg > max(xfold), "vegetated (stable)", "unstable"))
dfold <- data.frame(c = cg, x = xg, branch = branch)
ggplot(dfold, aes(c, x, colour = branch, linetype = branch, group = branch)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("vegetated (stable)" = col_up, "collapsed (stable)" = col_dn, "unstable" = col_un)) +
  scale_linetype_manual(values = c("vegetated (stable)" = 1, "collapsed (stable)" = 1, "unstable" = 2)) +
  coord_cartesian(xlim = c(0, 4), ylim = c(0, 10)) +
  labs(x = "Grazing pressure", y = "Equilibrium population", colour = NULL, linetype = NULL,
       title = "The equilibrium curve folds back on itself")

## ---- sweep ----
# run the population to near-equilibrium at a given pressure, starting from x0
sim_eq <- function(c, x0, Tn = 400, dt = 0.05) {
  x <- x0
  for (t in 1:(Tn/dt)) x <- max(x + (growth(x) - graze(x, c))*dt, 0)
  x
}
cs <- seq(1.4, 3.0, 0.02)
up <- numeric(length(cs)); x <- 9                                         # raise pressure
for (i in seq_along(cs)) { x <- sim_eq(cs[i], x); up[i] <- x }
dn <- numeric(length(cs)); x <- 0.3                                       # lower pressure
for (i in rev(seq_along(cs))) { x <- sim_eq(cs[i], x); dn[i] <- x }
veg_at2 <- up[which.min(abs(cs - 2))]; col_at2 <- dn[which.min(abs(cs - 2))]

## ---- fig-loop ----
dl <- rbind(data.frame(c = cs, x = up, dir = "raising pressure"),
            data.frame(c = cs, x = dn, dir = "lowering pressure"))
ggplot(dl, aes(c, x, colour = dir)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("raising pressure" = col_up, "lowering pressure" = col_dn)) +
  labs(x = "Grazing pressure", y = "Population", colour = NULL,
       title = "Collapse and recovery happen at different thresholds")
