# Simplex projection and delay embedding
# https://tidyecology.com/posts/simplex-projection-and-embedding/
#
# 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-08

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

simplex <- function(x, E, tau = 1, tp = 1, theiler = 0, target = NULL) {
  if (is.null(target)) target <- x
  bl <- make_block(x, E, tau)
  M <- bl$M; tt <- bl$t
  ok <- (tt + tp) >= 1 & (tt + tp) <= length(target)
  M <- M[ok, , drop = FALSE]; tt <- tt[ok]
  y <- target[tt + tp]
  D <- as.matrix(dist(M))
  pred <- rep(NA_real_, length(tt))
  for (i in seq_along(tt)) {
    d <- D[i, ]
    d[abs(tt - tt[i]) <= theiler] <- Inf   # drop self and temporal neighbours
    o <- order(d)[seq_len(E + 1)]
    dn <- d[o]
    if (!all(is.finite(dn))) next
    w <- if (dn[1] == 0) as.numeric(dn == 0) else exp(-dn / dn[1])
    w <- pmax(w, 1e-8)
    pred[i] <- sum(w * y[o]) / sum(w)
  }
  keep <- !is.na(pred)
  list(rho = suppressWarnings(cor(pred[keep], y[keep])),
       pred = pred, obs = y, t = tt)
}

## ---- data ----

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(4264)
n <- 300
z_true <- gen_ricker(n)
z <- z_true * exp(rnorm(n, 0, 0.10))     # 10% observation error

acf1 <- acf(z, plot = FALSE)$acf[2]

## ---- surrogate ----

ar_fit <- ar(z, order.max = 10, method = "mle")
set.seed(9264)
z_lin <- as.numeric(arima.sim(n = n, model = list(ar = ar_fit$ar),
                              sd = sqrt(ar_fit$var.pred)))
acf1_lin <- acf(z_lin, plot = FALSE)$acf[2]

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

## ---- fig-lagplot ----

lagdf <- function(v, lab) data.frame(prev = v[-length(v)], now = v[-1], panel = lab)
dA <- lagdf(z, "chaotic population")
dB <- lagdf(z_lin, "linear series, matching ACF")

pA <- ggplot(dA, aes(prev, now)) +
  geom_point(colour = te_forest, alpha = 0.7, size = 1.1) +
  labs(title = "Chaotic population", subtitle = "deterministic skeleton visible",
       x = expression(x[t-1]), y = expression(x[t])) +
  theme_te()
pB <- ggplot(dB, aes(prev, now)) +
  geom_point(colour = te_rust, alpha = 0.7, size = 1.1) +
  labs(title = "Linear series, matching ACF", subtitle = "no skeleton",
       x = expression(x[t-1]), y = expression(x[t])) +
  theme_te()
two_panel(pA, pB)

## ---- e-sweep ----

Es <- 1:8
rho_E <- sapply(Es, function(E) simplex(z, E = E, tp = 1)$rho)
rho_E_lin <- sapply(Es, function(E) simplex(z_lin, E = E, tp = 1)$rho)
E_best <- Es[which.max(rho_E)]
E_best_lin <- Es[which.max(rho_E_lin)]

## ---- fig-esweep ----

eA <- data.frame(E = Es, rho = rho_E)
eB <- data.frame(E = Es, rho = rho_E_lin)
pA <- ggplot(eA, aes(E, rho)) +
  geom_line(colour = te_forest, linewidth = 0.7) +
  geom_point(colour = te_forest, size = 2) +
  geom_point(data = eA[eA$E == E_best, ], colour = te_gold, size = 3.5) +
  scale_x_continuous(breaks = Es) +
  labs(title = "Chaotic population", subtitle = paste0("best E = ", E_best, " (true dimension 1)"),
       x = "embedding dimension E", y = expression(rho)) +
  theme_te()
pB <- ggplot(eB, aes(E, rho)) +
  geom_line(colour = te_rust, linewidth = 0.7) +
  geom_point(colour = te_rust, size = 2) +
  geom_point(data = eB[eB$E == E_best_lin, ], colour = te_gold, size = 3.5) +
  scale_x_continuous(breaks = Es) +
  labs(title = "Linear series, matching ACF", subtitle = paste0("best E = ", E_best_lin, " (no true dimension)"),
       x = "embedding dimension E", y = expression(rho)) +
  theme_te()
two_panel(pA, pB)

## ---- horizon ----

lin_rho <- function(x, p, tp) {
  n <- length(x)
  X <- embed(x, p + 1)
  cf <- coef(lm(X[, 1] ~ X[, -1, drop = FALSE]))
  pr <- rep(NA_real_, n)
  for (t in p:(n - tp)) {
    st <- x[t:(t - p + 1)]
    for (k in 1:tp) {                       # iterate the linear map forward
      nx <- cf[1] + sum(cf[-1] * st)
      st <- c(nx, st[-p])
    }
    pr[t + tp] <- st[1]
  }
  ok <- !is.na(pr)
  cor(pr[ok], x[ok])
}

tps <- 1:8
sx_chaos <- sapply(tps, function(tp) simplex(z, E = E_best, tp = tp)$rho)
ln_chaos <- sapply(tps, function(tp) lin_rho(z, ar_fit$order, tp))

ar_lin <- ar(z_lin, order.max = 10, method = "mle")
sx_lin <- sapply(tps, function(tp) simplex(z_lin, E = E_best_lin, tp = tp)$rho)
ln_lin <- sapply(tps, function(tp) lin_rho(z_lin, ar_lin$order, tp))

## ---- fig-horizon ----

hA <- rbind(data.frame(tp = tps, rho = sx_chaos, method = "simplex"),
            data.frame(tp = tps, rho = ln_chaos, method = "linear AR"))
hB <- rbind(data.frame(tp = tps, rho = sx_lin, method = "simplex"),
            data.frame(tp = tps, rho = ln_lin, method = "linear AR"))
pal <- c("simplex" = te_forest, "linear AR" = te_rust)
pA <- ggplot(hA, aes(tp, rho, colour = method)) +
  geom_line(linewidth = 0.7) + geom_point(size = 1.8) +
  scale_colour_manual(values = pal, name = NULL) +
  scale_x_continuous(breaks = tps) +
  labs(title = "Chaotic population", subtitle = "determinism pays, then decays",
       x = "forecast horizon (steps)", y = expression(rho)) +
  theme_te()
pB <- ggplot(hB, aes(tp, rho, colour = method)) +
  geom_line(linewidth = 0.7) + geom_point(size = 1.8) +
  scale_colour_manual(values = pal, name = NULL) +
  scale_x_continuous(breaks = tps) +
  labs(title = "Linear series, matching ACF", subtitle = "nothing to gain",
       x = "forecast horizon (steps)", y = expression(rho)) +
  theme_te()
two_panel(pA, pB)

## ---- mc-null ----

gain <- function(x, Emax = 6) {
  rr <- sapply(1:Emax, function(E) simplex(x, E = E, tp = 1)$rho)
  p <- max(1, ar(x, order.max = 6, method = "mle")$order)
  X <- embed(x, p + 1)
  max(rr) - cor(fitted(lm(X[, 1] ~ X[, -1, drop = FALSE])), X[, 1])
}

set.seed(3264)
g_null <- replicate(60, gain(as.numeric(arima.sim(n = 200, model = list(ar = ar_fit$ar),
                                                  sd = sqrt(ar_fit$var.pred)))))
g_chaos <- replicate(30, gain(gen_ricker(200, x0 = runif(1, 0.3, 0.9)) *
                              exp(rnorm(200, 0, 0.10))))
fp <- mean(g_null > 0)
tp_rate <- mean(g_chaos > 0)

## ---- noise-e ----

set.seed(5264)
noise_levels <- c(0, 0.05, 0.10, 0.20)
E_by_noise <- sapply(noise_levels, function(s) {
  zz <- z_true * exp(rnorm(n, 0, s))
  which.max(sapply(1:8, function(E) simplex(zz, E = E, tp = 1)$rho))
})
rho_flat <- diff(range(rho_E[1:4]))

## ---- fig-noise ----

nA <- data.frame(noise = noise_levels, E = E_by_noise)
pA <- ggplot(nA, aes(noise, E)) +
  geom_step(colour = te_forest, linewidth = 0.8) +
  geom_point(colour = te_gold, size = 3) +
  scale_y_continuous(breaks = 1:8, limits = c(0.5, 8.5)) +
  labs(title = "Selected E drifts with noise", subtitle = "true dimension is 1 throughout",
       x = "observation error (lognormal sd)", y = "selected E") +
  theme_te()

set.seed(5264)
curves <- do.call(rbind, lapply(noise_levels, function(s) {
  zz <- z_true * exp(rnorm(n, 0, s))
  data.frame(E = Es, rho = sapply(Es, function(E) simplex(zz, E = E, tp = 1)$rho),
             noise = factor(s))
}))
pB <- ggplot(curves, aes(E, rho, colour = noise)) +
  geom_line(linewidth = 0.6) + geom_point(size = 1.4) +
  scale_colour_manual(values = c("0" = te_ink, "0.05" = te_forest,
                                 "0.1" = te_green, "0.2" = te_gold),
                      name = "obs sd") +
  scale_x_continuous(breaks = Es) +
  labs(title = "The curves are flat", subtitle = "the maximum is a weak signal",
       x = "embedding dimension E", y = expression(rho)) +
  theme_te()
two_panel(pA, pB)
