# ABC-MCMC and sequential ABC samplers
# https://tidyecology.com/posts/abc-mcmc-and-sequential-abc/
#
# 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-14

## ---- model ----
library(ggplot2)

ricker <- function(log_r, sigma, phi = 10, n_time = 100, burn = 50) {
  r <- exp(log_r)
  e <- rnorm(burn + n_time, 0, sigma)
  n <- 1
  out <- numeric(n_time)
  for (t in seq_len(burn + n_time)) {
    n <- r * n * exp(-n + e[t])
    if (t > burn) out[t - burn] <- n
  }
  rpois(n_time, phi * out)
}

## ---- summaries ----
summ <- function(y) {
  n_time <- length(y)
  z <- y^0.3
  X <- cbind(1, z[-n_time], z[-n_time]^2)
  fit <- tryCatch({
    b <- qr.solve(X, z[-1])
    c(b[2], b[3], sd(z[-1] - X %*% b))
  }, error = function(e) c(0, 0, 0))
  c(mean(y), sum(y == 0), fit[1], fit[2], fit[3])
}

lo <- c(3, 0)
hi <- c(5, 0.8)

## ---- data ----
set.seed(290)
truth <- c(3.8, 0.3)
y_obs <- ricker(truth[1], truth[2])
s_obs <- summ(y_obs)

pilot <- t(replicate(2000, summ(ricker(runif(1, lo[1], hi[1]), runif(1, lo[2], hi[2])))))
sc <- pmax(apply(pilot, 2, mad), 1e-8)

dist_th <- function(th) sqrt(sum(((summ(ricker(th[1], th[2])) - s_obs) / sc)^2))
in_prior <- function(th) all(th >= lo) && all(th <= hi)

## ---- reference ----
set.seed(2901)
n_ref <- 2e5
th_ref <- cbind(runif(n_ref, lo[1], hi[1]), runif(n_ref, lo[2], hi[2]))
d_ref <- numeric(n_ref)
for (i in seq_len(n_ref)) d_ref[i] <- dist_th(th_ref[i, ])

eps_grid <- c(0.8, 0.5, 0.35, 0.25, 0.2, 0.15)
data.frame(
  eps = eps_grid,
  accept_rate = sapply(eps_grid, function(e) mean(d_ref <= e)),
  sims_per_draw = round(1 / sapply(eps_grid, function(e) mean(d_ref <= e)))
)

## ---- epsstar ----
eps_star <- as.numeric(quantile(d_ref, 0.005))
eps_tight <- as.numeric(quantile(d_ref, 0.001))
rej_rate <- mean(d_ref <= eps_star)
post_ref <- th_ref[d_ref <= eps_star, ]
c(eps_star = eps_star, eps_tight = eps_tight, n_accepted = nrow(post_ref))

## ---- fig-geometry ----
theme_te <- function(base = 11) {
  theme_minimal(base_size = base) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      plot.background = element_rect(fill = "#f5f4ee", colour = NA),
      axis.text = element_text(colour = "#5d6b61"),
      axis.title = element_text(colour = "#2c3a31"),
      plot.title = element_text(colour = "#16241d", face = "bold", size = base + 1),
      plot.subtitle = element_text(colour = "#5d6b61", size = base - 1),
      strip.text = element_text(colour = "#16241d", face = "bold"),
      legend.position = "none"
    )
}
set.seed(1)
show_idx <- sample(n_ref, 4000)
ggplot() +
  geom_point(data = data.frame(x = th_ref[show_idx, 1], y = th_ref[show_idx, 2]),
             aes(x, y), colour = "#c9c8b8", size = 0.35) +
  geom_point(data = data.frame(x = post_ref[, 1], y = post_ref[, 2]),
             aes(x, y), colour = "#275139", size = 0.7) +
  labs(x = "log r", y = "sigma",
       title = "The prior looks everywhere; the data cares about one patch",
       subtitle = paste0("accepted ", nrow(post_ref), " of ", format(n_ref, big.mark = ",", scientific = FALSE),
                         " draws at tolerance ", round(eps_star, 3))) +
  theme_te()

## ---- oracle ----
oracle_rate <- function(eps, n_try, seed) {
  set.seed(seed)
  acc <- th_ref[d_ref <= eps, , drop = FALSE]
  idx <- sample(nrow(acc), n_try, replace = TRUE)
  mean(vapply(seq_len(n_try), function(i) dist_th(acc[idx[i], ]) <= eps, logical(1)))
}

eps_three <- c(eps_star, quantile(d_ref, 0.002), eps_tight)
ceil_tab <- data.frame(
  eps = round(as.numeric(eps_three), 4),
  rejection = sapply(eps_three, function(e) mean(d_ref <= e)),
  oracle = mapply(oracle_rate, eps_three, 15000, c(11, 12, 13))
)
ceil_tab$ceiling <- ceil_tab$oracle / ceil_tab$rejection
ceil_tab

## ---- ceilnum ----
ceiling_star <- ceil_tab$ceiling[1]
ceiling_star

## ---- formula ----
S_post <- cov(post_ref)
ceiling_pred <- prod(hi - lo) / ((4 * pi)^(length(lo) / 2) * sqrt(det(S_post)))
c(predicted = ceiling_pred, measured = ceiling_star)

## ---- wide ----
set.seed(2902)
n_wide <- 80000
th_wide <- cbind(runif(n_wide, 1, 7), runif(n_wide, 0, 0.8))
d_wide <- numeric(n_wide)
for (i in seq_len(n_wide)) d_wide[i] <- dist_th(th_wide[i, ])

rate_wide <- mean(d_wide <= eps_star)
c(rate_narrow = rej_rate,
  rate_wide = rate_wide,
  ratio = rej_rate / rate_wide,
  outside_narrow_box = mean(th_wide[d_wide <= eps_star, 1] < 3 | th_wide[d_wide <= eps_star, 1] > 5))

## ---- mcmcfn ----
abc_mcmc <- function(n_iter, eps, start, step, seed) {
  set.seed(seed)
  out <- matrix(0, n_iter, 2)
  cur <- start
  acc <- 0L
  for (i in seq_len(n_iter)) {
    prop <- cur + rnorm(2, 0, step)
    if (in_prior(prop) && dist_th(prop) <= eps) {
      cur <- prop
      acc <- acc + 1L
    }
    out[i, ] <- cur
  }
  list(draws = out, acc_rate = acc / n_iter)
}

ess <- function(x) {
  n <- length(x)
  a <- acf(x, lag.max = min(n - 1, 3000), plot = FALSE)$acf[-1]
  k <- which(a < 0.05)[1]
  if (is.na(k)) k <- length(a)
  n / (1 + 2 * sum(a[seq_len(max(k - 1, 1))]))
}

## ---- mcmcsweep ----
psd <- apply(post_ref, 2, sd)
m0 <- colMeans(post_ref)
n_it <- 30000

sweep_tab <- do.call(rbind, lapply(c(0.3, 1.0, 1.7, 2.5, 4.0), function(h) {
  M <- abc_mcmc(n_it, eps_star, m0, h * psd, seed = 30 + h * 10)
  keep <- M$draws[-seq_len(3000), ]
  data.frame(step = h,
             acc_rate = M$acc_rate,
             ess_min = min(ess(keep[, 1]), ess(keep[, 2])),
             eff_per_1000 = min(ess(keep[, 1]), ess(keep[, 2])) / n_it * 1000,
             longest_stick = max(rle(keep[, 1])$lengths),
             sd_log_r = sd(keep[, 1]))
}))
sweep_tab

## ---- mcmcbest ----
best <- sweep_tab[which.max(sweep_tab$eff_per_1000), ]
mcmc_eff <- best$eff_per_1000
worst_eff <- min(sweep_tab$eff_per_1000)
c(best_step = best$step, best_eff = mcmc_eff, worst_eff = worst_eff,
  ratio = mcmc_eff / worst_eff, rejection_eff = rej_rate * 1000)

## ---- fig-trace ----
trace_dat <- do.call(rbind, lapply(c(0.3, 1.7, 4.0), function(h) {
  M <- abc_mcmc(12000, eps_star, m0, h * psd, seed = 30 + h * 10)
  data.frame(iter = seq_len(12000), log_r = M$draws[, 1],
             panel = paste0("step = ", h, " x posterior sd"))
}))
ggplot(trace_dat, aes(iter, log_r)) +
  annotate("rect", xmin = -Inf, xmax = Inf,
           ymin = m0[1] - 2 * psd[1], ymax = m0[1] + 2 * psd[1],
           fill = "#93a87f", alpha = 0.25) +
  geom_line(colour = "#275139", linewidth = 0.3) +
  facet_wrap(~panel, ncol = 1) +
  scale_x_continuous(breaks = seq(0, 10000, 2500)) +
  labs(x = "iteration", y = "log r",
       title = "Every iteration is billed, accepted or not",
       subtitle = "flat stretches are paid for at full price") +
  theme_te()

## ---- mcmctight ----
M_tight <- abc_mcmc(40000, eps_tight, m0, best$step * psd, seed = 77)
k_tight <- M_tight$draws[-seq_len(4000), ]
eff_tight <- min(ess(k_tight[, 1]), ess(k_tight[, 2])) / 40000 * 1000
rej_eff_tight <- mean(d_ref <= eps_tight) * 1000
c(acc_rate = M_tight$acc_rate,
  accepted_moves = round(M_tight$acc_rate * 40000),
  eff_per_1000 = eff_tight,
  longest_stick = max(rle(k_tight[, 1])$lengths),
  rejection_eff = rej_eff_tight)

## ---- smcfn ----
smc_abc <- function(n_part, alpha, target, eps1 = 0.9, seed) {
  set.seed(seed)
  th <- matrix(0, n_part, 2)
  d <- numeric(n_part)
  w <- rep(1 / n_part, n_part)
  total <- 0L
  eps <- eps1
  round_id <- 0L
  hist <- list()
  clouds <- list()
  repeat {
    round_id <- round_id + 1L
    if (round_id > 1) eps <- max(as.numeric(quantile(d, alpha)), target)
    th_old <- th
    w_old <- w
    tries <- 0L
    if (round_id > 1) L <- chol(2 * cov.wt(th_old, wt = w_old)$cov)
    th_new <- matrix(0, n_part, 2)
    d_new <- numeric(n_part)
    for (i in seq_len(n_part)) {
      repeat {
        tries <- tries + 1L
        p <- if (round_id == 1) {
          c(runif(1, lo[1], hi[1]), runif(1, lo[2], hi[2]))
        } else {
          th_old[sample.int(n_part, 1, prob = w_old), ] + as.numeric(crossprod(L, rnorm(2)))
        }
        if (round_id > 1 && !in_prior(p)) next
        dd <- dist_th(p)
        if (dd <= eps) {
          th_new[i, ] <- p
          d_new[i] <- dd
          break
        }
      }
    }
    if (round_id > 1) {
      dens <- numeric(n_part)
      for (j in seq_len(n_part)) {
        z <- backsolve(L, t(sweep(th_new, 2, th_old[j, ], "-")), transpose = TRUE)
        dens <- dens + w_old[j] * exp(-0.5 * colSums(z^2))
      }
      w <- 1 / dens
      w <- w / sum(w)
    }
    th <- th_new
    d <- d_new
    total <- total + tries
    hist[[round_id]] <- data.frame(round = round_id, eps = eps, sims = tries,
                                   ess = 1 / sum(w^2), cum_sims = total)
    clouds[[round_id]] <- data.frame(round = round_id, eps = eps,
                                     log_r = th[, 1], sigma = th[, 2])
    if (eps <= target + 1e-12 || round_id > 12) break
  }
  list(particles = th, weights = w, total = total, ess = 1 / sum(w^2),
       hist = do.call(rbind, hist), clouds = do.call(rbind, clouds))
}

## ---- smcrun ----
smc_tab <- do.call(rbind, lapply(c(0.3, 0.5, 0.7), function(a) {
  S <- smc_abc(n_part = 400, alpha = a, target = eps_star, seed = 900 + a * 10)
  data.frame(alpha = a, rounds = nrow(S$hist), total_sims = S$total,
             ess = S$ess, eff_per_1000 = S$ess / S$total * 1000)
}))
smc_tab

## ---- smcdetail ----
best_alpha <- smc_tab$alpha[which.max(smc_tab$eff_per_1000)]
S_main <- smc_abc(n_part = 400, alpha = best_alpha, target = eps_star, seed = 900 + best_alpha * 10)
S_main$hist
smc_eff <- max(smc_tab$eff_per_1000)
final_round_rate <- 400 / S_main$hist$sims[nrow(S_main$hist)]
c(smc_eff = smc_eff, final_round_accept = final_round_rate,
  rejection_accept = rej_rate, final_vs_rejection = final_round_rate / rej_rate)

## ---- fig-smc ----
clouds <- S_main$clouds
clouds$panel <- sprintf("round %d, eps = %.2f", clouds$round, clouds$eps)
clouds$panel <- factor(clouds$panel, levels = unique(clouds$panel))
ggplot(clouds, aes(log_r, sigma)) +
  geom_point(colour = "#275139", size = 0.5, alpha = 0.7) +
  facet_wrap(~panel) +
  coord_cartesian(xlim = c(3, 5), ylim = c(0, 0.8)) +
  labs(x = "log r", y = "sigma",
       title = "The population walks the tolerance down",
       subtitle = "each round proposes from the last round's survivors") +
  theme_te()

## ---- scoreboard ----
board <- data.frame(
  method = c("rejection", "ABC-MCMC (tuned)", "sequential ABC", "oracle (unreachable)"),
  eff_per_1000 = c(rej_rate * 1000, mcmc_eff, smc_eff, ceil_tab$oracle[1] * 1000)
)
board$vs_rejection <- board$eff_per_1000 / (rej_rate * 1000)
board

## ---- agreement ----
rbind(
  rejection = c(colMeans(post_ref), apply(post_ref, 2, sd)),
  abc_mcmc = {
    M <- abc_mcmc(30000, eps_star, m0, best$step * psd, seed = 33)
    k <- M$draws[-seq_len(3000), ]
    c(colMeans(k), apply(k, 2, sd))
  },
  sequential = {
    w <- S_main$weights
    m <- colSums(S_main$particles * w)
    c(m, sqrt(colSums(w * sweep(S_main$particles, 2, m)^2)))
  }
)

## ---- fig-scoreboard ----
bar_dat <- board[board$method != "oracle (unreachable)", ]
bar_dat$method <- factor(bar_dat$method, levels = rev(bar_dat$method))
ggplot(bar_dat, aes(eff_per_1000, method)) +
  geom_col(fill = "#275139", width = 0.55) +
  geom_vline(xintercept = ceil_tab$oracle[1] * 1000, linetype = "dashed",
             colour = "#b5534e", linewidth = 0.6) +
  annotate("text", x = ceil_tab$oracle[1] * 1000, y = 0.62,
           label = paste0(" oracle: ", round(ceil_tab$oracle[1] * 1000, 0)),
           hjust = 0, colour = "#b5534e", size = 3.2) +
  coord_cartesian(xlim = c(0, ceil_tab$oracle[1] * 1000 * 1.25)) +
  labs(x = "effective samples per 1000 simulations", y = NULL,
       title = "The samplers are fighting over a factor of ten",
       subtitle = paste0("working tolerance ", round(eps_star, 3),
                         "; the dashed line is unreachable by construction")) +
  theme_te()
