# Convergent cross mapping in ecology
# https://tidyecology.com/posts/convergent-cross-mapping/
#
# 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-01

## ---- ccm-core ----

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)
}

## "from xmap to": use M_from to estimate `to`. Evidence that `to` causes `from`.
ccm_once <- function(from, to, E, tau = 1, lib_size, theiler = 0) {
  bl <- make_block(from, E, tau)
  M <- bl$M; tt <- bl$t
  yv <- to[tt]
  n <- length(tt)
  lib <- sample.int(n, lib_size)
  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])
    w <- pmax(w, 1e-8)
    pr[i] <- sum(w * yv[cand[o]]) / sum(w)
  }
  k <- !is.na(pr)
  suppressWarnings(cor(pr[k], yv[k]))
}

ccm_curve <- function(from, to, E, lib_sizes, reps = 30, theiler = 0) {
  sapply(lib_sizes, function(L)
    mean(replicate(reps, ccm_once(from, to, E, lib_size = L, theiler = theiler)),
         na.rm = TRUE))
}

## ---- 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))
}

## ---- data ----

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])
}

set.seed(4266)
n <- 400
d <- gen_coupled(n)
r_pearson <- cor(d$x, d$y)

Ls <- c(20, 40, 80, 160, 320, 399)
ccm_YX <- ccm_curve(d$y, d$x, E = 2, lib_sizes = Ls)   # Y xmap X : tests X -> Y
ccm_XY <- ccm_curve(d$x, d$y, E = 2, lib_sizes = Ls)   # X xmap Y : tests Y -> X

## ---- fig-ccm ----

gen_ricker <- function(n, burn = 500, r = 3.0, x0 = 0.6) {
  N <- n + burn; x <- numeric(N); x[1] <- x0
  for (t in 1:(N - 1)) x[t + 1] <- x[t] * exp(r * (1 - x[t]))
  x[(burn + 1):N]
}
set.seed(7266)
a_ind <- gen_ricker(n, x0 = 0.6); b_ind <- gen_ricker(n, x0 = 0.31)
ccm_AB <- ccm_curve(a_ind, b_ind, E = 2, lib_sizes = Ls)
ccm_BA <- ccm_curve(b_ind, a_ind, E = 2, lib_sizes = Ls)

labA <- c("Y xmap X  (tests X causes Y)", "X xmap Y  (tests Y causes X)")
dA <- rbind(data.frame(L = Ls, rho = ccm_YX, dir = labA[1]),
            data.frame(L = Ls, rho = ccm_XY, dir = labA[2]))
labB <- c("A xmap B  (tests B causes A)", "B xmap A  (tests A causes B)")
dB <- rbind(data.frame(L = Ls, rho = ccm_AB, dir = labB[1]),
            data.frame(L = Ls, rho = ccm_BA, dir = labB[2]))

pA <- ggplot(dA, aes(L, rho, colour = dir)) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  scale_colour_manual(values = setNames(c(te_forest, te_gold), labA), name = NULL) +
  ylim(-0.1, 1) +
  labs(title = "Coupled species", subtitle = "both converge, strong link higher",
       x = "library length L", y = expression(rho)) +
  theme_te() + theme(legend.direction = "vertical")
pB <- ggplot(dB, aes(L, rho, colour = dir)) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  scale_colour_manual(values = setNames(c(te_rust, te_muted), labB), name = NULL) +
  ylim(-0.1, 1) +
  labs(title = "Unconnected systems", subtitle = "no convergence, no signal",
       x = "library length L", y = expression(rho)) +
  theme_te() + theme(legend.direction = "vertical")
two_panel(pA, pB)

## ---- shared ----

set.seed(6266)
z_drv <- gen_ricker(n)                                # shared driver
r1 <- as.numeric(2.0 * scale(z_drv)) + rnorm(n, 0, 0.3)
r2 <- as.numeric(1.5 * scale(z_drv)) + rnorm(n, 0, 0.3)

r_shared <- cor(r1, r2)
ccm_12 <- ccm_curve(r1, r2, E = 2, lib_sizes = Ls)
ccm_21 <- ccm_curve(r2, r1, E = 2, lib_sizes = Ls)
delta_12 <- ccm_12[length(Ls)] - ccm_12[1]
delta_YX <- ccm_YX[length(Ls)] - ccm_YX[1]

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

dS <- rbind(data.frame(L = Ls, rho = ccm_12, dir = "R1 xmap R2"),
            data.frame(L = Ls, rho = ccm_21, dir = "R2 xmap R1"))
pA <- ggplot(dS, aes(L, rho, colour = dir)) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  scale_colour_manual(values = c("R1 xmap R2" = te_rust, "R2 xmap R1" = te_gold), name = NULL) +
  ylim(0, 1) +
  labs(title = "Shared driver, no interaction", subtitle = "high skill, flat curve",
       x = "library length L", y = expression(rho)) +
  theme_te()

dD <- data.frame(
  case = factor(c("true coupling\n(Y xmap X)", "shared driver\n(R1 xmap R2)"),
                levels = c("true coupling\n(Y xmap X)", "shared driver\n(R1 xmap R2)")),
  delta = c(delta_YX, delta_12))
pB <- ggplot(dD, aes(case, delta, fill = case)) +
  geom_col(width = 0.55) +
  geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.3) +
  scale_fill_manual(values = c(te_forest, te_rust), guide = "none") +
  labs(title = "What convergence looks like",
       subtitle = "change in skill from smallest to largest library",
       x = NULL, y = expression(Delta*rho)) +
  theme_te()
two_panel(pA, pB)

## ---- surrogate ----

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)
  ph <- runif(nyq - 1, 0, 2 * pi)
  newf[2:nyq] <- complex(modulus = amp[2:nyq], argument = ph)
  newf[n:(n - nyq + 2)] <- Conj(newf[2:nyq])          # keep the series real
  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
}

set.seed(8266)
obs_delta <- delta_YX
null_delta <- replicate(100, {
  xs <- surrogate_ebi(d$x)
  lo <- mean(replicate(6, ccm_once(d$y, xs, E = 2, lib_size = Ls[1])), na.rm = TRUE)
  hi <- mean(replicate(6, ccm_once(d$y, xs, E = 2, lib_size = Ls[length(Ls)])), na.rm = TRUE)
  hi - lo
})
p_conv <- mean(null_delta >= obs_delta)
null_q95 <- quantile(null_delta, 0.95)
