# Detrending and bandwidth in early warning signals
# https://tidyecology.com/posts/detrending-and-bandwidth-choice-ews/
#
# 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-07

## ---- series ----
r <- 1; K <- 10; h <- 1
f <- function(x, c) r*x*(1 - x/K) - c*x^2/(x^2 + h^2)
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){ 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, 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]
seg <- d$x[1:(tr_idx - 10)]; n <- length(seg)

## ---- detrend ----
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 }
roll_ar1 <- function(res, wf = 0.5){ win <- round(wf*length(res)); s <- 1:(length(res)-win+1)
  sapply(s, function(k){ w <- res[k:(k+win-1)]
    ar.ols(w, order.max = 1, aic = FALSE, demean = TRUE, intercept = FALSE)$ar[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")

res_raw  <- seg - mean(seg)             # no detrending
res_bw05 <- gauss_detrend(seg, 0.05*n)  # small bandwidth
res_bw25 <- gauss_detrend(seg, 0.25*n)  # large bandwidth
res_fd   <- diff(seg)                   # first difference

tau_ar_raw  <- kt(roll_ar1(res_raw));  tau_ar_bw05 <- kt(roll_ar1(res_bw05))
tau_ar_bw25 <- kt(roll_ar1(res_bw25)); tau_ar_fd   <- kt(roll_ar1(res_fd))
tau_var_raw  <- kt(roll_var(res_raw));  tau_var_bw05 <- kt(roll_var(res_bw05))
tau_var_bw25 <- kt(roll_var(res_bw25)); tau_var_fd   <- kt(roll_var(res_fd))

## ---- 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 = "top", legend.title = element_blank(),
        legend.text = element_text(colour = body)) }

## ---- fig-flip ----
choice <- c("raw", "bandwidth 5%", "bandwidth 25%", "first-diff")
df_flip <- data.frame(
  choice = factor(rep(choice, 2), levels = choice),
  indicator = rep(c("autocorrelation", "variance"), each = 4),
  tau = c(tau_ar_raw, tau_ar_bw05, tau_ar_bw25, tau_ar_fd,
          tau_var_raw, tau_var_bw05, tau_var_bw25, tau_var_fd))
ggplot(df_flip, aes(choice, tau, colour = indicator, group = indicator)) +
  geom_hline(yintercept = 0, colour = brick, linetype = "dashed", linewidth = 0.4) +
  geom_line(linewidth = 0.5) +
  geom_point(size = 3.2) +
  scale_colour_manual(values = c("autocorrelation" = forest, "variance" = amber)) +
  labs(title = "The detrending choice moves the trend statistic",
       x = NULL, y = "Kendall tau with time") + theme_te()

## ---- thumb ----
p_thumb <- ggplot(df_flip, aes(choice, tau, colour = indicator, group = indicator)) +
  geom_hline(yintercept = 0, colour = brick, linetype = "dashed", linewidth = 0.4) +
  geom_line(linewidth = 0.7) +
  geom_point(size = 3.8) +
  scale_colour_manual(values = c("autocorrelation" = forest, "variance" = amber)) +
  labs(title = paste(strwrap("Kendall tau under four detrending choices", 46),
                     collapse = "\n"),
       x = NULL, y = "Kendall tau with time") +
  theme_te() +
  theme(plot.title = element_text(size = 13, face = "bold", colour = ink),
        plot.margin = margin(8, 14, 8, 8))
ggsave("thumbnail.png", p_thumb, width = 7.5, height = 5.4, dpi = 100, bg = paper)

## ---- sweeps ----
bws <- seq(0.03, 0.40, by = 0.01)
tau_bw <- sapply(bws, function(b) kt(roll_ar1(gauss_detrend(seg, b*n))))
res10 <- gauss_detrend(seg, 0.10*n)
wins <- seq(0.25, 0.75, by = 0.05)
tau_win <- sapply(wins, function(wf) kt(roll_ar1(res10, wf)))
bw_lo <- min(tau_bw); bw_hi <- max(tau_bw)
win_lo <- min(tau_win); win_hi <- max(tau_win)
win_at_hi <- wins[which.max(tau_win)]

## ---- fig-sweeps ----
d_bw <- data.frame(bw = bws, tau = tau_bw)
d_wn <- data.frame(win = wins, tau = tau_win)
p_bw <- ggplot(d_bw, aes(bw, tau)) + geom_line(colour = forest, linewidth = 0.6) +
  geom_point(colour = forest, size = 1.3) +
  labs(title = "Bandwidth sweep", x = "bandwidth (fraction of length)", y = "AR(1) Kendall tau") +
  theme_te() + theme(legend.position = "none")
p_wn <- ggplot(d_wn, aes(win, tau)) + geom_line(colour = amber, linewidth = 0.6) +
  geom_point(colour = amber, size = 1.3) +
  labs(title = "Window sweep", x = "window (fraction of length)", y = "AR(1) Kendall tau") +
  theme_te() + theme(legend.position = "none")
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p_bw, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_wn, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
