# Checking an ABC analysis
# https://tidyecology.com/posts/checking-an-abc-analysis/
#
# 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

## ---- model ----
sim_ricker <- function(log_r, sigma, T = 50, phi = 10, N0 = 1) {
  M <- length(log_r)
  N <- rep(N0, M)
  Y <- matrix(0L, M, T)
  r <- exp(log_r)
  for (t in seq_len(T)) {
    N <- r * N * exp(-N + rnorm(M, 0, sigma))
    Y[, t] <- rpois(M, phi * N)
  }
  Y
}

summ <- function(Y) {
  n  <- ncol(Y)
  L  <- log1p(Y)
  Lc <- L - rowMeans(L)
  acf1 <- rowSums(Lc[, -1, drop = FALSE] * Lc[, -n, drop = FALSE]) / rowSums(Lc^2)
  S <- cbind(mean  = rowMeans(Y),                # average count
             sdlog = sqrt(rowMeans(Lc^2)),       # spread on the log scale
             acf1  = acf1,                       # year to year autocorrelation
             zeros = rowMeans(Y == 0))           # how often the count is zero
  S[!is.finite(S)] <- 0        # a series pinned at zero has no autocorrelation
  S
}

prior <- function(M) cbind(log_r = runif(M, 3, 5), sigma = runif(M, 0, 0.8))

set.seed(4291)
th_pilot <- prior(20000)
sc       <- apply(summ(sim_ricker(th_pilot[, 1], th_pilot[, 2])), 2, mad)
fit_cols <- names(sc)
round(sc, 3)

## ---- calibration ----
n_rep <- 400
M     <- 8000
arms  <- c(0.0025, 0.01, 0.05, 0.20, 1)
L     <- 19
rk <- array(NA_integer_, c(n_rep, length(arms), 2, 2))   # rep x arm x parameter x set
wd <- array(NA_real_,    c(n_rep, length(arms), 2, 2))

set.seed(291)
for (i in seq_len(n_rep)) {
  th0 <- prior(1)
  s0  <- drop(summ(sim_ricker(th0[1], th0[2])))
  Th  <- prior(M)
  S   <- summ(sim_ricker(Th[, 1], Th[, 2]))
  for (q in 1:2) {
    cols <- if (q == 1) fit_cols else "mean"       # four summaries, or the mean alone
    d <- sqrt(rowSums(sweep(sweep(S[, cols, drop = FALSE], 2, s0[cols], "-"),
                            2, sc[cols], "/")^2))
    o <- order(d)
    for (j in seq_along(arms)) {
      acc <- o[seq_len(round(arms[j] * M))]
      sub <- acc[sample.int(length(acc), L)]
      for (p in 1:2) {
        rk[i, j, p, q] <- sum(Th[sub, p] < th0[p])
        wd[i, j, p, q] <- sd(Th[acc, p])
      }
    }
  }
}

flat_test <- function(r) {                # chi-square against a flat rank histogram
  o <- tabulate(r + 1, L + 1)
  e <- length(r) / (L + 1)
  pchisq(sum((o - e)^2) / e, L, lower.tail = FALSE)
}
cal <- expand.grid(arm = seq_along(arms), par = 1:2, set = 1:2)
cal$rate <- arms[cal$arm]
grab <- function(f) mapply(function(a, p, q) f(rk[, a, p, q], wd[, a, p, q]),
                           cal$arm, cal$par, cal$set)
cal$p_flat  <- grab(function(r, w) flat_test(r))
cal$cover   <- grab(function(r, w) mean(r > 0 & r < L))
cal$top_bin <- grab(function(r, w) sum(r == L))
cal$bot_bin <- grab(function(r, w) sum(r == 0))
cal$post_sd <- grab(function(r, w) mean(w))
band <- qbinom(c(0.025, 0.975), n_rep, 1 / (L + 1))     # where a flat histogram puts its bars
cal$out_band <- grab(function(r, w) {
  tb <- tabulate(r + 1, L + 1); sum(tb < band[1] | tb > band[2])
})
cal$parameter <- c("log_r", "sigma")[cal$par]
cal$summaries <- c("four summaries", "the mean alone")[cal$set]
pick <- function(a, p, q, col) cal[cal$arm == a & cal$par == p & cal$set == q, col]
subset(cal, set == 1 & par == 1, c(rate, cover, top_bin, bot_bin, p_flat, post_sd))

## ---- fig-ranks ----
library(ggplot2)
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    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.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          strip.text = element_text(colour = "#16241d", face = "bold"))
}
arm_lab <- c(sprintf("accept %.2f%%", 100 * arms[1:4]), "accept everything")
rd <- do.call(rbind, lapply(seq_along(arms), function(j)
  data.frame(rank = rk[, j, 1, 1], arm = factor(arm_lab[j], levels = arm_lab))))
ggplot(rd, aes(rank)) +
  annotate("rect", xmin = -0.6, xmax = L + 0.6, ymin = band[1], ymax = band[2],
           fill = "#93a87f", alpha = 0.35) +
  geom_histogram(breaks = seq(-0.5, L + 0.5, 1), fill = "#275139", colour = "white",
                 linewidth = 0.2) +
  geom_hline(yintercept = n_rep / (L + 1), colour = "#b5534e", linewidth = 0.5) +
  facet_wrap(~arm, nrow = 1) +
  labs(x = "rank of the true log growth rate among 19 posterior draws", y = "replicates",
       subtitle = "flat is correct; the band is where 95 per cent of the bars of a flat histogram fall") +
  theme_te()

## ---- blindness ----
subset(cal, par == 2, c(summaries, rate, cover, p_flat, post_sd))

## ---- fig-blind ----
wdd <- cal
wdd$parameter <- factor(wdd$parameter, levels = c("log_r", "sigma"))
pri <- data.frame(parameter = factor(c("log_r", "sigma"), levels = c("log_r", "sigma")),
                  s = c(2, 0.8) / sqrt(12))
ggplot(wdd, aes(rate, post_sd, colour = summaries, shape = summaries)) +
  geom_hline(data = pri, aes(yintercept = s), linetype = 2, colour = "#5d6b61") +
  geom_line(linewidth = 0.7) + geom_point(size = 2) +
  facet_wrap(~parameter, scales = "free_y",
             labeller = as_labeller(c(log_r = "log growth rate", sigma = "process sd"))) +
  scale_x_log10(breaks = arms, labels = c("0.25%", "1%", "5%", "20%", "all")) +
  scale_colour_manual(values = c("four summaries" = "#275139", "the mean alone" = "#b5534e")) +
  labs(x = "acceptance rate", y = "posterior standard deviation", colour = NULL, shape = NULL,
       subtitle = "dashed: the prior standard deviation, which is what learning nothing looks like") +
  theme_te() + theme(legend.position = "bottom")

## ---- misspec ----
sim_nb <- function(log_r, sigma, size, T = 50, phi = 10, N0 = 1) {
  M <- length(log_r); N <- rep(N0, M); Y <- matrix(0L, M, T)
  for (t in seq_len(T)) {
    N <- exp(log_r) * N * exp(-N + rnorm(M, 0, sigma))
    Y[, t] <- rnbinom(M, mu = phi * N, size = size)
  }
  Y
}

set.seed(2911)
M_pool  <- 20000
Th_p    <- prior(M_pool)
Sj      <- sweep(summ(sim_ricker(Th_p[, 1], Th_p[, 2]))[, fit_cols], 2, sc[fit_cols], "/")
k_acc   <- 50                                   # the closest 0.25 per cent
dist_to <- function(s0) sqrt(rowSums(sweep(Sj, 2, s0[fit_cols] / sc[fit_cols], "-")^2))

abc_gof <- function(y0, B = 30) {
  s0   <- drop(summ(y0))
  d    <- dist_to(s0)
  acc  <- order(d)[seq_len(k_acc)]
  dobs <- d[acc[k_acc]]                         # distance the last accepted draw came in at
  th   <- Th_p[acc[sample.int(k_acc, B, replace = TRUE)], , drop = FALSE]
  Yr   <- sim_ricker(th[, 1], th[, 2])          # data the fitted model itself produces
  drep <- vapply(seq_len(B),
                 function(b) sort(dist_to(drop(summ(Yr[b, , drop = FALSE]))))[k_acc],
                 numeric(1))
  ci <- quantile(Th_p[acc, 1], c(0.05, 0.95))
  structure(c(p = mean(drep >= dobs), dobs = dobs, logr = mean(Th_p[acc, 1]),
              sd = sd(Th_p[acc, 1]), cover = as.numeric(ci[1] <= 3.8 && 3.8 <= ci[2])),
            drep = drep)
}

set.seed(29111)
sizes <- c(Inf, 10, 3, 1)
ms <- do.call(rbind, lapply(sizes, function(sz) {
  r <- replicate(40, {
    y0 <- if (is.infinite(sz)) sim_ricker(3.8, 0.3) else sim_nb(3.8, 0.3, size = sz)
    abc_gof(y0)
  })
  # var_ratio is 1 + mean count / size; the mean count under the truth is 39.0
  data.frame(size = sz, var_ratio = ifelse(is.infinite(sz), 1, 1 + 39 / sz),
             logr = mean(r["logr", ]), scatter = sd(r["logr", ]),
             post_sd = mean(r["sd", ]), cover90 = mean(r["cover", ]),
             alarm = mean(r["p", ] < 0.05), dobs = mean(r["dobs", ]))
}))
print(ms, digits = 3, row.names = FALSE)

## ---- fig-gof ----
set.seed(29112)
g_ok  <- abc_gof(sim_ricker(3.8, 0.3), B = 200)
set.seed(29113)
g_bad <- abc_gof(sim_nb(3.8, 0.3, size = 1), B = 200)
gd <- rbind(data.frame(d = attr(g_ok, "drep"),  panel = "Poisson counts: the model is right"),
            data.frame(d = attr(g_bad, "drep"), panel = "patchy counts: the model is wrong"))
ggplot(gd, aes(d)) +
  geom_density(fill = "#dad9ca", colour = "#93a87f", adjust = 1.1) +
  geom_vline(data = data.frame(panel = unique(gd$panel),
                               dobs = c(g_ok["dobs"], g_bad["dobs"])),
             aes(xintercept = dobs), colour = "#275139", linewidth = 1) +
  facet_wrap(~panel) +
  labs(x = "distance at which the last draw was accepted", y = "density",
       subtitle = "the acceptance rule always returns a posterior; the distance is what gives the model away") +
  theme_te()
