# The S-map and state-dependent dynamics
# https://tidyecology.com/posts/s-map-and-state-dependence/
#
# 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

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

## S-map over an arbitrary state matrix M predicting target y
smap_block <- function(M, y, theta = 0, loo = TRUE) {
  n <- nrow(M)
  D <- as.matrix(dist(scale(M)))          # standardise: coordinates share a scale
  A0 <- cbind(1, M)
  cf <- matrix(NA_real_, n, ncol(M) + 1)
  pred <- rep(NA_real_, n)
  for (i in seq_len(n)) {
    use <- if (loo) seq_len(n) != i else rep(TRUE, n)
    d <- D[i, use]
    w <- exp(-theta * d / mean(d))
    A <- A0[use, , drop = FALSE] * w
    b <- y[use] * w
    sv <- svd(A)                          # SVD solve: weights make A ill-conditioned
    tol <- max(dim(A)) * .Machine$double.eps * max(sv$d)
    co <- as.numeric(sv$v %*% (ifelse(sv$d > tol, 1 / sv$d, 0) * crossprod(sv$u, b)))
    cf[i, ] <- co
    pred[i] <- sum(c(1, M[i, ]) * co)
  }
  list(coef = cf, pred = pred, rho = cor(pred, y))
}

smap <- function(x, E, tau = 1, tp = 1, theta = 0, loo = TRUE) {
  bl <- make_block(x, E, tau)
  ok <- (bl$t + tp) <= length(x)
  smap_block(bl$M[ok, , drop = FALSE], x[bl$t[ok] + tp], theta = theta, loo = loo)
}

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

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- identity ----

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(4265)
n <- 300
z <- gen_ricker(n) * exp(rnorm(n, 0, 0.05))    # 5% observation error

s0 <- smap(z, E = 2, tp = 1, theta = 0, loo = FALSE)
X <- embed(z, 3)
m_lm <- lm(X[, 1] ~ X[, 2] + X[, 3])
coef_gap <- max(abs(sweep(s0$coef, 2, coef(m_lm))))
fit_gap <- max(abs(s0$pred - fitted(m_lm)))

## ---- fp-guard-1 ----
stopifnot(coef_gap / max(abs(coef(m_lm))) < 1e-10,
          fit_gap / max(abs(fitted(m_lm))) < 1e-10)

## ---- theta-sweep ----

ar_fit <- ar(z, order.max = 10, method = "mle")
set.seed(9265)
z_lin <- as.numeric(arima.sim(n = n, model = list(ar = ar_fit$ar),
                              sd = sqrt(ar_fit$var.pred)))

thetas <- c(0, 0.1, 0.3, 0.5, 1, 2, 3, 4, 6, 8)
rho_chaos <- sapply(thetas, function(th) smap(z, E = 2, tp = 1, theta = th)$rho)
rho_lin <- sapply(thetas, function(th) smap(z_lin, E = 2, tp = 1, theta = th)$rho)

gain_chaos <- max(rho_chaos) - rho_chaos[1]
gain_lin <- max(rho_lin) - rho_lin[1]

## ---- fig-theta ----

tA <- data.frame(theta = thetas, rho = rho_chaos)
tB <- data.frame(theta = thetas, rho = rho_lin)
pA <- ggplot(tA, aes(theta, rho)) +
  geom_line(colour = te_forest, linewidth = 0.8) +
  geom_point(colour = te_forest, size = 2) +
  geom_hline(yintercept = rho_chaos[1], colour = te_muted, linetype = 2, linewidth = 0.4) +
  labs(title = "Chaotic population", subtitle = "skill climbs as the fit localises",
       x = expression(theta), y = expression(rho)) +
  theme_te()
pB <- ggplot(tB, aes(theta, rho)) +
  geom_line(colour = te_rust, linewidth = 0.8) +
  geom_point(colour = te_rust, size = 2) +
  geom_hline(yintercept = rho_lin[1], colour = te_muted, linetype = 2, linewidth = 0.4) +
  labs(title = "Linear series, same ACF", subtitle = "nothing to localise",
       x = expression(theta), y = expression(rho)) +
  theme_te()
two_panel(pA, pB)

## ---- coupled ----

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(4265)
nc <- 400
d <- gen_coupled(nc)
M <- cbind(x = d$x[-nc], y = d$y[-nc])

## true Jacobian entries, from differentiating the model by hand
true_YX <- -0.10 * M[, "y"]                          # d y[t+1] / d x[t] : strong link
true_XY <- -0.02 * M[, "x"]                          # d x[t+1] / d y[t] : weak link
true_XX <- 3.8 - 2 * 3.8 * M[, "x"] - 0.02 * M[, "y"]

th_grid <- c(0, 0.5, 1, 2, 3, 4, 6, 8)
rho_X <- sapply(th_grid, function(th) smap_block(M, d$x[-1], theta = th)$rho)
rho_Y <- sapply(th_grid, function(th) smap_block(M, d$y[-1], theta = th)$rho)
th_best <- th_grid[which.max(rho_Y)]

fitX <- smap_block(M, d$x[-1], theta = th_best)      # x[t+1] ~ (x[t], y[t])
fitY <- smap_block(M, d$y[-1], theta = th_best)      # y[t+1] ~ (x[t], y[t])

est_YX <- fitY$coef[, 2]     # coefficient on x in the y equation : strong link
est_XY <- fitX$coef[, 3]     # coefficient on y in the x equation : weak link
est_XX <- fitX$coef[, 2]     # self effect : strong

cor_strong <- cor(est_YX, true_YX)
cor_weak <- cor(est_XY, true_XY)
cor_self <- cor(est_XX, true_XX)

## the same model with Y driving X as strongly as X drives Y, theta chosen the same way
d_eq <- gen_coupled(nc, bxy = 0.1)
M_eq <- cbind(x = d_eq$x[-nc], y = d_eq$y[-nc])
th_eq <- th_grid[which.max(sapply(th_grid, function(th) smap_block(M_eq, d_eq$y[-1], theta = th)$rho))]
cor_eq   <- cor(smap_block(M_eq, d_eq$x[-1], theta = th_eq)$coef[, 3], -0.1 * M_eq[, "x"])  # Y on X, now strong
cor_eq_y <- cor(smap_block(M_eq, d_eq$y[-1], theta = th_eq)$coef[, 2], -0.1 * M_eq[, "y"])  # X on Y, as before

## ---- fig-coefs ----

cA <- data.frame(truth = true_YX, est = est_YX)
cB <- data.frame(truth = true_XY, est = est_XY)
pA <- ggplot(cA, aes(truth, est)) +
  geom_abline(slope = 1, intercept = 0, colour = te_gold, linewidth = 0.8) +
  geom_point(colour = te_forest, alpha = 0.5, size = 1.1) +
  labs(title = "Strong link: X on Y", subtitle = paste0("r = ", sprintf("%.3f", cor_strong)),
       x = "true coefficient", y = "S-map estimate") +
  theme_te()
pB <- ggplot(cB, aes(truth, est)) +
  geom_abline(slope = 1, intercept = 0, colour = te_gold, linewidth = 0.8) +
  geom_point(colour = te_rust, alpha = 0.5, size = 1.1) +
  labs(title = "Weak link: Y on X", subtitle = paste0("r = ", sprintf("%.3f", cor_weak)),
       x = "true coefficient", y = "S-map estimate") +
  theme_te()
two_panel(pA, pB)
