# Spatial early warning signals
# https://tidyecology.com/posts/spatial-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-14

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

sim_spatial <- function(seed, L = 25, D = 0.30, sigma = 0.20, dt = 0.01,
                        c_snaps = c(1.0, 1.6, 2.0, 2.3, 2.5, 2.58), burn = 40, hold = 25){
  set.seed(seed)
  X <- matrix(8.9, L, L)
  neigh_mean <- function(M)                       # rook mean, periodic
    (M[c(L, 1:(L-1)), ] + M[c(2:L, 1), ] + M[, c(L, 1:(L-1))] + M[, c(2:L, 1)]) / 4
  step <- function(M, c){
    lap <- neigh_mean(M) - M
    M2 <- M + (f(M, c) + D*lap)*dt + sigma*sqrt(dt)*matrix(rnorm(L*L), L, L)
    M2[M2 < 0.001] <- 0.001; M2
  }
  snaps <- vector("list", length(c_snaps))
  for(s in seq_along(c_snaps)){
    cc <- c_snaps[s]
    for(i in 1:round(burn/dt)) X <- step(X, cc)   # relax towards a stationary field
    for(i in 1:round(hold/dt)) X <- step(X, cc)
    snaps[[s]] <- X
  }
  list(c = c_snaps, snaps = snaps, L = L)
}
sp <- sim_spatial(seed = 4240)

## ---- indicators ----
moran_grid <- function(M){
  L <- nrow(M); z <- as.vector(M) - mean(M); n <- L*L
  idx <- function(i, j) ((i-1) %% L)*L + ((j-1) %% L) + 1
  num <- 0
  for(i in 1:L) for(j in 1:L){
    nb <- c(z[idx(i-1, j)], z[idx(i+1, j)], z[idx(i, j-1)], z[idx(i, j+1)])
    num <- num + z[idx(i, j)] * sum(nb)/4          # row-standardised weights (1/4 each)
  }
  num / sum(z^2)                                    # (n / sum of weights) = 1 here
}
skew <- function(v){ v <- v - mean(v); mean(v^3) / (mean(v^2))^1.5 }

tab <- data.frame(
  c     = sp$c,
  mean  = sapply(sp$snaps, mean),
  s_var = sapply(sp$snaps, function(M) var(as.vector(M))),
  s_skew = sapply(sp$snaps, function(M) skew(as.vector(M))),
  moran = sapply(sp$snaps, moran_grid))

tau_var  <- cor(tab$c, tab$s_var,  method = "kendall")
tau_skew <- cor(tab$c, tab$s_skew, method = "kendall")
tau_moran <- cor(tab$c, tab$moran, method = "kendall")
var_fold <- tab$s_var[nrow(tab)] / tab$s_var[1]

## ---- setup-theme ----
library(ggplot2)
ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"; label <- "#46604a"
paper <- "#f5f4ee"; line <- "#dad9ca"; faint <- "#5d6b61"; amber <- "#cda23f"; brick <- "#b5534e"
grad_lo <- "#c9b458"; grad_hi <- "#1d5b4e"
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") }
mat_long <- function(M, cc){ L <- nrow(M)
  data.frame(row = rep(1:L, times = L), col = rep(1:L, each = L),
             value = as.vector(M), c = paste0("c = ", cc)) }

## ---- fig-fields ----
picks <- c(1, 3, 6)
long <- do.call(rbind, Map(function(i) mat_long(sp$snaps[[i]], sp$c[i]), picks))
long$c <- factor(long$c, levels = paste0("c = ", sp$c[picks]))
long$dev <- ave(long$value, long$c, FUN = function(v) v - mean(v))
p_fields <- ggplot(long, aes(col, row, fill = dev)) +
  geom_raster() + facet_wrap(~ c, nrow = 1) +
  scale_fill_gradient2(low = grad_lo, mid = paper, high = grad_hi, midpoint = 0) +
  coord_equal() +
  labs(title = "The field grows patchier as the fold nears", x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), strip.text = element_text(colour = body))
p_fields

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

## ---- fig-indicators ----
p_v <- ggplot(tab, aes(c, s_var)) + geom_line(colour = forest, linewidth = 0.6) +
  geom_point(colour = forest, size = 1.8) +
  labs(title = "Spatial variance", subtitle = paste0("tau = ", sprintf("%.2f", tau_var)),
       x = "grazing pressure c", y = "variance") + theme_te()
p_m <- ggplot(tab, aes(c, moran)) + geom_line(colour = amber, linewidth = 0.6) +
  geom_point(colour = amber, size = 1.8) +
  labs(title = "Moran's I", subtitle = paste0("tau = ", sprintf("%.2f", tau_moran)),
       x = "grazing pressure c", y = "Moran's I") + theme_te()
p_s <- ggplot(tab, aes(c, s_skew)) + geom_line(colour = brick, linewidth = 0.6) +
  geom_point(colour = brick, size = 1.8) +
  labs(title = "Spatial skewness", subtitle = paste0("tau = ", sprintf("%.2f", tau_skew)),
       x = "grazing pressure c", y = "skewness") + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 3)))
print(p_v, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_m, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
print(p_s, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 3))
