# Checking an empirical dynamic model
# https://tidyecology.com/posts/checking-an-empirical-dynamic-model/
#
# 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-11-04

## ---- engine ----

make_block <- function(x, E, tau = 1) {
  n <- length(x)
  tt <- seq((E - 1) * tau + 1, n)
  M <- matrix(NA_real_, nrow = length(tt), ncol = E)
  for (j in seq_len(E)) M[, j] <- x[tt - (j - 1) * tau]
  list(M = M, t = tt)
}

ccm_once <- function(from, to, E, lib_size, theiler = 0) {
  bl <- make_block(from, E); M <- bl$M; tt <- bl$t
  yv <- to[tt]; n <- length(tt)
  lib <- sample.int(n, min(lib_size, n))
  D <- as.matrix(dist(M))
  pr <- rep(NA_real_, n)
  for (i in seq_len(n)) {
    cand <- lib[lib != i & abs(tt[lib] - tt[i]) > theiler]
    if (length(cand) < E + 1) next
    d <- D[i, cand]
    o <- order(d)[seq_len(E + 1)]
    dn <- d[o]
    w <- if (dn[1] == 0) as.numeric(dn == 0) else exp(-dn / dn[1])
    pr[i] <- sum(pmax(w, 1e-8) * yv[cand[o]]) / sum(pmax(w, 1e-8))
  }
  k <- !is.na(pr)
  suppressWarnings(cor(pr[k], yv[k]))
}

## the reportable statistic: skill at a small library, at a large one, and the rise
ccm_delta <- function(from, to, E, L_lo, L_hi, reps = 20) {
  lo <- mean(replicate(reps, ccm_once(from, to, E, L_lo)), na.rm = TRUE)
  hi <- mean(replicate(reps, ccm_once(from, to, E, L_hi)), na.rm = TRUE)
  c(lo = lo, hi = hi, delta = hi - lo)
}

## Ebisuzaki surrogate: same power spectrum, phases randomised, determinism gone
surrogate_ebi <- function(x) {
  n <- length(x); xm <- mean(x); z <- x - xm
  f <- fft(z); amp <- Mod(f); nyq <- floor(n / 2)
  newf <- complex(modulus = amp, argument = 0)
  newf[2:nyq] <- complex(modulus = amp[2:nyq], argument = runif(nyq - 1, 0, 2 * pi))
  newf[n:(n - nyq + 2)] <- Conj(newf[2:nyq])
  newf[1] <- f[1]
  if (n %% 2 == 0)
    newf[nyq + 1] <- complex(modulus = amp[nyq + 1],
                             argument = ifelse(runif(1) < 0.5, 0, pi))
  Re(fft(newf, inverse = TRUE)) / n + xm
}

## ---- setup ----

library(ggplot2)
library(grid)
te_ink <- "#16241d"; te_forest <- "#275139"; te_gold <- "#c9b458"
te_rust <- "#b5534e"; te_paper <- "#f5f4ee"; te_line <- "#dad9ca"
te_muted <- "#5d6b61"; te_green <- "#2f8f63"

theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.title = element_text(colour = te_ink, face = "bold", size = rel(1.0)),
      plot.subtitle = element_text(colour = te_muted, size = rel(0.85)),
      axis.title = element_text(colour = te_ink, size = rel(0.9)),
      axis.text = element_text(colour = te_muted, size = rel(0.8)),
      panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
      panel.grid.minor = element_blank(),
      panel.background = element_rect(fill = te_paper, colour = NA),
      plot.background = element_rect(fill = te_paper, colour = NA),
      legend.position = "bottom",
      legend.title = element_text(colour = te_ink, size = rel(0.8)),
      legend.text = element_text(colour = te_muted, size = rel(0.75)),
      strip.text = element_text(colour = te_ink, size = rel(0.85))
    )
}
two_panel <- function(pA, pB) {
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1, 2)))
  print(pA, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(pB, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}

gen_coupled <- function(n, burn = 500, rx = 3.8, ry = 3.5,
                        bxy = 0.02, byx = 0.1, x0 = 0.4, y0 = 0.2) {
  N <- n + burn; x <- numeric(N); y <- numeric(N); x[1] <- x0; y[1] <- y0
  for (t in 1:(N - 1)) {
    x[t + 1] <- x[t] * (rx - rx * x[t] - bxy * y[t])
    y[t + 1] <- y[t] * (ry - ry * y[t] - byx * x[t])
  }
  data.frame(x = x[(burn + 1):N], y = y[(burn + 1):N])
}

## ---- length-sweep ----

set.seed(4267)
lengths <- c(30, 50, 100, 200, 400)
len_res <- do.call(rbind, lapply(lengths, function(nn) {
  d <- gen_coupled(nn)
  L_lo <- 20; L_hi <- nn - 5
  obs <- ccm_delta(d$y, d$x, E = 2, L_lo, L_hi, reps = 30)
  null <- replicate(50, ccm_delta(d$y, surrogate_ebi(d$x), E = 2,
                                  L_lo, L_hi, reps = 30)["delta"])
  data.frame(n = nn, rho_hi = obs["hi"], delta = obs["delta"],
             q95 = quantile(null, 0.95),
             verdict = ifelse(obs["delta"] > quantile(null, 0.95),
                              "convergent", "not convergent"))
}))
rownames(len_res) <- NULL

## ---- fig-length ----

pA <- ggplot(len_res, aes(factor(n), delta)) +
  geom_col(aes(fill = verdict), width = 0.6) +
  geom_point(aes(y = q95), colour = te_ink, size = 2.4, shape = 18) +
  geom_line(aes(y = q95, group = 1), colour = te_ink, linetype = 2, linewidth = 0.4) +
  scale_fill_manual(values = c("convergent" = te_forest, "not convergent" = te_rust),
                    name = NULL) +
  labs(title = "The rise, against the null", subtitle = "diamonds: surrogate 95th percentile",
       x = "series length n", y = expression(Delta*rho)) +
  theme_te()
pB <- ggplot(len_res, aes(factor(n), rho_hi)) +
  geom_col(fill = te_gold, width = 0.6) +
  ylim(0, 1) +
  labs(title = "Skill at the largest library", subtitle = "respectable at every length: not the evidence",
       x = "series length n", y = expression(rho)) +
  theme_te()
two_panel(pA, pB)

## ---- shared-driver ----

gen_shared <- function(n, burn = 500, rz = 3.8, ra = 3.7, rb = 3.6,
                       bz1 = 0.5, bz2 = 0.4) {
  N <- n + burn
  z <- numeric(N); a <- numeric(N); b <- numeric(N)
  z[1] <- 0.5; a[1] <- 0.4; b[1] <- 0.35
  for (t in 1:(N - 1)) {
    z[t + 1] <- rz * z[t] * (1 - z[t])                    # driver, autonomous
    a[t + 1] <- a[t] * (ra - ra * a[t] - bz1 * z[t])      # a feels z only
    b[t + 1] <- b[t] * (rb - rb * b[t] - bz2 * z[t])      # b feels z only
  }
  data.frame(z = z[(burn + 1):N], a = a[(burn + 1):N], b = b[(burn + 1):N])
}

set.seed(4267)
ds <- gen_shared(400)
r_ab <- cor(ds$a, ds$b)

ab <- ccm_delta(ds$a, ds$b, E = 2, 20, 399, reps = 30)   # tests b -> a : FALSE
az <- ccm_delta(ds$a, ds$z, E = 2, 20, 399, reps = 30)   # tests z -> a : TRUE
null_ab <- replicate(60, ccm_delta(ds$a, surrogate_ebi(ds$b), E = 2,
                                   20, 399, reps = 30)["delta"])
q95_ab <- quantile(null_ab, 0.95)
p_ab <- mean(null_ab >= ab["delta"])

## ---- fig-shared ----

lab_sp <- "A xmap B\n(spurious)"; lab_tr <- "A xmap Z\n(real driver)"
dS <- data.frame(case = factor(c(lab_sp, lab_tr), levels = c(lab_sp, lab_tr)),
                 rho = c(ab["hi"], az["hi"]), delta = c(ab["delta"], az["delta"]),
                 q95 = c(q95_ab, NA))
pA <- ggplot(dS, aes(case, rho, fill = case)) +
  geom_col(width = 0.55) + ylim(0, 1) +
  scale_fill_manual(values = c(te_rust, te_forest), guide = "none") +
  labs(title = "Skill at the full library", subtitle = "both look like something",
       x = NULL, y = expression(rho)) +
  theme_te()
pB <- ggplot(dS, aes(case, delta, fill = case)) +
  geom_col(width = 0.55) +
  geom_hline(yintercept = q95_ab, colour = te_ink, linetype = 2, linewidth = 0.4) +
  scale_fill_manual(values = c(te_rust, te_forest), guide = "none") +
  labs(title = "The rise", subtitle = "dashed: surrogate 95th percentile for the pair",
       x = NULL, y = expression(Delta*rho)) +
  theme_te()
two_panel(pA, pB)

## ---- synchrony ----

gen_uni <- function(n, burn = 500, rx = 3.8, ry = 3.5, byx) {
  N <- n + burn; x <- numeric(N); y <- numeric(N); x[1] <- 0.4; y[1] <- 0.2
  for (t in 1:(N - 1)) {
    x[t + 1] <- rx * x[t] * (1 - x[t])                 # nothing enters x. ever.
    y[t + 1] <- y[t] * (ry - ry * y[t] - byx * x[t])
  }
  data.frame(x = x[(burn + 1):N], y = y[(burn + 1):N])
}

set.seed(4267)
strengths <- c(0.1, 2.0)
syn <- do.call(rbind, lapply(strengths, function(s) {
  d <- gen_uni(300, byx = s)
  tr <- ccm_delta(d$y, d$x, E = 2, 20, 299, reps = 20)   # TRUE  : x -> y
  fa <- ccm_delta(d$x, d$y, E = 2, 20, 299, reps = 20)   # FALSE : y -> x
  data.frame(byx = s, r = cor(d$x, d$y),
             true_hi = tr["hi"], true_d = tr["delta"],
             false_hi = fa["hi"], false_d = fa["delta"])
}))
rownames(syn) <- NULL

## ---- fig-synchrony ----

mk <- function(row, ttl, sub) {
  dd <- data.frame(
    dir = factor(rep(c("X causes Y\n(TRUE)", "Y causes X\n(IMPOSSIBLE)"), 2),
                 levels = c("X causes Y\n(TRUE)", "Y causes X\n(IMPOSSIBLE)")),
    stat = factor(rep(c("skill at full library", "rise in skill"), each = 2),
                  levels = c("skill at full library", "rise in skill")),
    val = c(row$true_hi, row$false_hi, row$true_d, row$false_d))
  ggplot(dd, aes(dir, val, fill = stat)) +
    geom_col(position = position_dodge(width = 0.7), width = 0.62) +
    geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.3) +
    scale_fill_manual(values = c("skill at full library" = te_gold,
                                 "rise in skill" = te_forest), name = NULL) +
    ylim(-0.1, 1.05) +
    labs(title = ttl, subtitle = sub, x = NULL, y = NULL) +
    theme_te()
}
pA <- mk(syn[1, ], "Weak forcing", paste0("cor(x, y) = ", sprintf("%+.2f", syn$r[1])))
pB <- mk(syn[2, ], "Strong forcing", paste0("cor(x, y) = ", sprintf("%+.2f", syn$r[2])))
two_panel(pA, pB)

## ---- tbl-checklist ----

knitr::kable(data.frame(
  Check = c("Series length", "Convergence", "Surrogate null", "Shared driver",
            "Synchrony", "Embedding", "Interaction coefficients"),
  Question = c("Are there enough points for small and large libraries to differ?",
               "Does skill rise with library length, or is it just high?",
               "Does the rise exceed phase-randomised surrogates of the driver?",
               "Could an unmeasured variable force both series?",
               "Do the species correlate strongly and cross-map well at small L?",
               "Do conclusions survive E plus or minus one?",
               "Is the coefficient large enough to drive the prediction?"),
  Failure = c("In this simulation 30 points only just showed a real link",
              "A single high rho is the classic false positive",
              "Autocorrelation alone lifts short cross-map curves",
              "A moderate flat cross map between unlinked species",
              "Flat curves mean 'cannot tell', not 'no link'",
              "The skill curve is flat, so the argmax is noise",
              "Weak coefficients fluctuate as noise while predicting well")
), col.names = c("Check", "Ask", "What goes wrong"))
