# Choosing summary statistics for ABC
# https://tidyecology.com/posts/summary-statistics-for-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

## ---- setup ----
library(ggplot2)

te_ink <- "#16241d"; te_forest <- "#275139"; te_sage <- "#93a87f"
te_paper <- "#f5f4ee"; te_line <- "#dad9ca"; te_rust <- "#b5534e"
te_gold <- "#c9b458"; te_muted <- "#5d6b61"

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = te_muted, size = rel(0.85)),
          axis.title = element_text(colour = te_muted),
          axis.text = element_text(colour = te_muted),
          strip.text = element_text(colour = te_ink, face = "bold"),
          legend.title = element_text(colour = te_muted, size = rel(0.85)))
}
theme_set(theme_te())

## ---- suff-data ----
set.seed(289)
n_s <- 25L; sig_s <- 1; prior_sd_s <- 10
y_s <- rnorm(n_s, 2.0, sig_s)
mean_obs <- mean(y_s); med_obs <- median(y_s)

post_prec <- 1 / prior_sd_s^2 + n_s / sig_s^2
exact_mean <- (n_s * mean_obs / sig_s^2) / post_prec
exact_sd   <- 1 / sqrt(post_prec)
c(mean_obs = mean_obs, med_obs = med_obs, exact_sd = exact_sd)

## ---- suff-abc ----
M_s <- 400000L
mu_s <- rnorm(M_s, 0, prior_sd_s)
X_s  <- matrix(rnorm(M_s * n_s, rep(mu_s, n_s), sig_s), M_s, n_s)
s_mean <- rowMeans(X_s)
s_med  <- apply(X_s, 1, median)

keep_q <- function(d, q = 0.005) d <= quantile(d, q)
acc_mean <- keep_q(abs(s_mean - mean_obs))
acc_med  <- keep_q(abs(s_med  - med_obs))
c(n_accepted = sum(acc_mean),
  sd_from_mean = sd(mu_s[acc_mean]),
  sd_from_median = sd(mu_s[acc_med]))

## ---- fig-suff ----
gx <- seq(exact_mean - 4 * exact_sd, exact_mean + 4 * exact_sd, length.out = 512)
dens_s <- rbind(
  data.frame(x = density(mu_s[acc_mean], n = 512, from = min(gx), to = max(gx))$x,
             y = density(mu_s[acc_mean], n = 512, from = min(gx), to = max(gx))$y,
             src = "sample mean (sufficient)"),
  data.frame(x = density(mu_s[acc_med], n = 512, from = min(gx), to = max(gx))$x,
             y = density(mu_s[acc_med], n = 512, from = min(gx), to = max(gx))$y,
             src = "sample median (not)"))

ggplot(dens_s, aes(x, y, colour = src)) +
  geom_line(data = data.frame(x = gx, y = dnorm(gx, exact_mean, exact_sd)),
            aes(x, y), colour = te_ink, linewidth = 1.4, inherit.aes = FALSE) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("sample mean (sufficient)" = te_forest,
                                 "sample median (not)" = te_rust), name = NULL) +
  labs(title = "The summary sets the floor, not the tolerance",
       subtitle = "black: exact posterior; coloured: ABC posteriors at the same tolerance quantile",
       x = "mean", y = "density") +
  theme(legend.position = "inside", legend.position.inside = c(0.8, 0.8),
        legend.background = element_rect(fill = te_paper, colour = NA))

## ---- dim-run ----
set.seed(2289)
M_d <- 600000L; K <- 10L; n_keep <- 2000L
mu_d <- rnorm(M_d, 0, prior_sd_s)
s1   <- rnorm(M_d, mu_d, sig_s / sqrt(n_s))
NZ   <- matrix(rnorm(M_d * K), M_d, K)
nz_obs <- rnorm(K)

sweep_k <- data.frame(k = c(0L, 1L, 2L, 3L, 5L, 10L))
sweep_k$abc_sd <- NA_real_; sweep_k$tol_s1 <- NA_real_; sweep_k$keep <- vector("list", nrow(sweep_k))
for (i in seq_len(nrow(sweep_k))) {
  k  <- sweep_k$k[i]
  d2 <- (s1 - mean_obs)^2
  if (k > 0) {
    j  <- seq_len(k)
    d2 <- d2 + rowSums(sweep(NZ[, j, drop = FALSE], 2, nz_obs[j], "-")^2)
  }
  d   <- sqrt(d2)
  sel <- d <= sort(d, partial = n_keep)[n_keep]
  sweep_k$abc_sd[i] <- sd(mu_d[sel])
  sweep_k$tol_s1[i] <- max(abs(s1[sel] - mean_obs))
  sweep_k$keep[[i]] <- mu_d[sel]
}
sweep_k$widening <- sweep_k$abc_sd / exact_sd
print(sweep_k[, c("k", "abc_sd", "tol_s1", "widening")], digits = 3)

## ---- fig-dim ----
show_k <- c(0L, 2L, 5L, 10L)
gxd <- seq(exact_mean - 12 * exact_sd, exact_mean + 12 * exact_sd, length.out = 512)
dens_d <- do.call(rbind, lapply(show_k, function(kk) {
  v <- sweep_k$keep[[match(kk, sweep_k$k)]]
  dd <- density(v, n = 512, from = min(gxd), to = max(gxd))
  data.frame(x = dd$x, y = dd$y, k = factor(kk, levels = show_k))
}))

p1 <- ggplot(dens_d, aes(x, y, colour = k)) +
  geom_line(data = data.frame(x = gxd, y = dnorm(gxd, exact_mean, exact_sd)),
            aes(x, y), colour = te_ink, linewidth = 1.2, linetype = "dashed",
            inherit.aes = FALSE) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = setNames(c(te_forest, te_sage, te_gold, te_rust), show_k),
                      name = "noise summaries") +
  labs(title = "Each empty summary widens it", x = "mean", y = "density") +
  theme(legend.position = "inside", legend.position.inside = c(0.83, 0.68),
        legend.background = element_rect(fill = te_paper, colour = NA),
        legend.key.size = unit(0.8, "lines"))

p2 <- ggplot(sweep_k, aes(k, abc_sd)) +
  geom_hline(yintercept = exact_sd, colour = te_ink, linetype = "dashed") +
  geom_line(colour = te_rust, linewidth = 0.9) +
  geom_point(colour = te_forest, size = 2.4) +
  annotate("text", x = 6.2, y = exact_sd * 1.5, label = "exact posterior sd",
           colour = te_ink, size = 3.2, hjust = 0) +
  labs(title = "The cost is not gentle", x = "summaries carrying nothing",
       y = "ABC posterior sd")

gridExtra_free <- function(a, b) {
  grid::grid.newpage()
  grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
  print(a, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(b, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
}
gridExtra_free(p1, p2)

## ---- ricker-fns ----
sim_ricker <- function(log_r, sigma, phi, n_years, N0 = 1) {
  M <- length(log_r); N <- rep(N0, M); Y <- matrix(0L, M, n_years)
  for (t in seq_len(n_years)) {
    N <- N * exp(log_r - N + rnorm(M, 0, sigma))
    Y[, t] <- rpois(M, phi * N)
  }
  Y
}

summ8 <- function(Y) {
  nn <- ncol(Y); m <- rowMeans(Y)
  sdv <- sqrt(pmax(rowMeans(Y^2) - m^2, 0)) * sqrt(nn / (nn - 1))
  Yc <- Y - m; den <- pmax(rowSums(Yc^2), 1e-9)
  cbind(mean  = m,
        sd    = sdv,
        cv    = sdv / pmax(m, 1e-8),
        acf1  = rowSums(Yc[, -1, drop = FALSE] * Yc[, -nn, drop = FALSE]) / den,
        acf2  = rowSums(Yc[, -(1:2), drop = FALSE] * Yc[, -((nn - 1):nn), drop = FALSE]) / den,
        max   = apply(Y, 1, max),
        zeros = rowSums(Y == 0),
        jump  = rowMeans(abs(Y[, -1, drop = FALSE] - Y[, -nn, drop = FALSE])))
}

## ---- ricker-data ----
set.seed(3289)
true_lr <- 1.5; true_sg <- 0.3; phi_known <- 20; n_years <- 50L
y_ric <- as.vector(sim_ricker(true_lr, true_sg, phi_known, n_years))
S_obs <- summ8(matrix(y_ric, nrow = 1))
round(S_obs[, c("mean", "cv", "acf1")], 3)

## ---- ricker-sim ----
set.seed(4289)
M_r <- 200000L
lr <- runif(M_r, 0, 3); sg <- runif(M_r, 0, 1)
S_all <- summ8(sim_ricker(lr, sg, phi_known, n_years))
i3 <- c("mean", "cv", "acf1")
scale3 <- apply(S_all[, i3], 2, mad)
round(scale3, 3)

## ---- scale-run ----
Dev  <- sweep(S_all[, i3], 2, S_obs[, i3], "-")
d_raw <- sqrt(rowSums(Dev^2))
d_std <- sqrt(rowSums(sweep(Dev, 2, scale3, "/")^2))
n_acc <- 500L

pick_n <- function(d, k = n_acc) d <= sort(d, partial = k)[k]
a_raw <- pick_n(d_raw); a_std <- pick_n(d_std)

report <- function(sel, label) {
  data.frame(distance = label,
             mean_matched_to = max(abs(Dev[sel, "mean"])),
             cv_lo = min(S_all[sel, "cv"]),  cv_hi = max(S_all[sel, "cv"]),
             sigma_post_sd = sd(sg[sel]),
             sigma_mean = mean(sg[sel]))
}
scale_tab <- rbind(report(a_raw, "raw"), report(a_std, "standardised"))
print(scale_tab, digits = 3, row.names = FALSE)

## ---- fig-scale ----
gxs <- seq(0, 1, length.out = 512)
dens_sc <- rbind(
  data.frame(x = density(sg[a_raw], n = 512, from = 0, to = 1)$x,
             y = density(sg[a_raw], n = 512, from = 0, to = 1)$y, d = "raw"),
  data.frame(x = density(sg[a_std], n = 512, from = 0, to = 1)$x,
             y = density(sg[a_std], n = 512, from = 0, to = 1)$y, d = "standardised"))

ggplot(dens_sc, aes(x, y, colour = d)) +
  geom_hline(yintercept = 1, colour = te_muted, linetype = "dotted") +
  geom_vline(xintercept = true_sg, colour = te_ink, linetype = "dashed") +
  geom_line(linewidth = 1) +
  annotate("text", x = 0.88, y = 1.35, label = "prior", colour = te_muted, size = 3.2) +
  annotate("text", x = true_sg, y = 7.4, label = " truth", colour = te_ink,
           size = 3.2, hjust = 0) +
  scale_colour_manual(values = c(raw = te_rust, standardised = te_forest),
                      name = "distance") +
  coord_cartesian(xlim = c(0, 1), ylim = c(0, 7.8), expand = FALSE) +
  labs(title = "Units are not a modelling decision, but they act like one",
       x = "process noise sigma", y = "density") +
  theme(legend.position = "inside", legend.position.inside = c(0.82, 0.62),
        legend.background = element_rect(fill = te_paper, colour = NA))

## ---- fp-pilot ----
d_pilot <- d_std
box_sel <- pick_n(d_pilot, 2000L)
box <- rbind(log_r = range(lr[box_sel]), sigma = range(sg[box_sel]))
round(box, 3)

## ---- fp-basis ----
scale8 <- apply(S_all, 2, mad); scale8[scale8 == 0] <- 1
Z_full <- sweep(S_all, 2, scale8, "/")
B_full <- cbind(1, Z_full, Z_full^2)
h_full <- 1:100000
resid_sd <- function(fit) sqrt(sum(fit$residuals^2) / (length(fit$residuals) - length(fit$coefficients)))
c(full_prior_lr = resid_sd(lm.fit(B_full[h_full, ], lr[h_full])),
  full_prior_sg = resid_sd(lm.fit(B_full[h_full, ], sg[h_full])))

## ---- fp-sim ----
set.seed(6289)
M_t <- 100000L
lr_t <- runif(M_t, box["log_r", 1], box["log_r", 2])
sg_t <- runif(M_t, box["sigma", 1], box["sigma", 2])
S_t  <- summ8(sim_ricker(lr_t, sg_t, phi_known, n_years))

scale_t <- apply(S_t, 2, mad); scale_t[scale_t == 0] <- 1
Z_t  <- sweep(S_t, 2, scale_t, "/")
Zo_t <- S_obs / scale_t
B_t  <- cbind(1, Z_t, Z_t^2)
Bo_t <- cbind(1, Zo_t, Zo_t^2)

fit_half <- 1:50000; abc_half <- 50001:M_t
f_lr <- lm.fit(B_t[fit_half, ], lr_t[fit_half])
f_sg <- lm.fit(B_t[fit_half, ], sg_t[fit_half])
c(truncated_lr = resid_sd(f_lr), truncated_sg = resid_sd(f_sg))

## ---- fp-compare ----
proj <- function(fit, B) as.vector(B %*% fit$coefficients)
P  <- cbind(proj(f_lr, B_t),  proj(f_sg, B_t))
Po <- c(proj(f_lr, Bo_t), proj(f_sg, Bo_t))
scale_P <- apply(P[abc_half, ], 2, mad)

dist_of <- function(Z, Zo, sc) {
  d <- sqrt(rowSums(sweep(sweep(Z, 2, Zo, "-"), 2, sc, "/")^2))
  d[fit_half] <- Inf   # the fitting half is spent; it cannot also be the posterior
  d
}
cands <- list(
  "all 8"        = dist_of(Z_t, as.vector(Zo_t), rep(1, 8)),
  "hand-picked 3"= dist_of(Z_t[, i3], as.vector(Zo_t[, i3]), rep(1, 3)),
  "semi-auto 2"  = dist_of(P, Po, scale_P))

fp_tab <- do.call(rbind, lapply(names(cands), function(nm) {
  sel <- pick_n(cands[[nm]], n_acc)
  data.frame(summaries = nm, log_r_mean = mean(lr_t[sel]), log_r_sd = sd(lr_t[sel]),
             sigma_mean = mean(sg_t[sel]), sigma_sd = sd(sg_t[sel]))
}))
print(fp_tab, digits = 3, row.names = FALSE)

## ---- fig-fp ----
sel_list <- lapply(cands, pick_n, k = n_acc)
mk <- function(par_vals, lab, from, to) {
  do.call(rbind, lapply(names(sel_list), function(nm) {
    dd <- density(par_vals[sel_list[[nm]]], n = 512, from = from, to = to)
    data.frame(x = dd$x, y = dd$y, summaries = factor(nm, levels = names(cands)), par = lab)
  }))
}
dens_fp <- rbind(mk(lr_t, "growth rate (log r)", 1.15, 1.95),
                 mk(sg_t, "process noise sigma", 0, 0.51))
truths  <- data.frame(par = c("growth rate (log r)", "process noise sigma"),
                      v = c(true_lr, true_sg))
pal_fp <- c("all 8" = te_rust, "hand-picked 3" = te_gold, "semi-auto 2" = te_forest)

ggplot(dens_fp, aes(x, y, colour = summaries)) +
  geom_vline(data = truths, aes(xintercept = v), colour = te_ink, linetype = "dashed") +
  geom_line(linewidth = 1) +
  facet_wrap(~par, scales = "free") +
  scale_colour_manual(values = pal_fp, name = NULL) +
  labs(title = "Two summaries beat eight, and beat three chosen by hand",
       subtitle = "dashed: truth; same simulations, 500 accepted draws each",
       x = NULL, y = "density") +
  theme(legend.position = "bottom")
