# Checking a Bayesian computation
# https://tidyecology.com/posts/checking-a-bayesian-computation/
#
# 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-07

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

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

int <- function(x) formatC(x, format = "d", big.mark = "")
fmt <- function(x, digits = 4) formatC(x, format = "f", digits = digits)

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"),
          legend.position = "bottom")
}

## ---- diagnostics ----
rhat_split <- function(sims) {
  n <- nrow(sims); h <- floor(n / 2)
  s <- cbind(sims[1:h, , drop = FALSE], sims[(n - h + 1):n, , drop = FALSE])
  nn <- nrow(s); cm <- colMeans(s); cv <- apply(s, 2, var)
  vhat <- ((nn - 1) * mean(cv) + nn * var(cm)) / nn
  sqrt(vhat / mean(cv))
}

ess_geyer <- function(sims) {
  n <- nrow(sims); m <- ncol(sims); lag_max <- min(n - 1, 400)
  ac <- sapply(seq_len(m), function(j)
    acf(sims[, j], lag.max = lag_max, plot = FALSE)$acf[, 1, 1])
  rho <- rowMeans(matrix(ac, ncol = m))
  kmax <- floor(length(rho) / 2)
  gam <- rho[2 * (1:kmax) - 1] + rho[2 * (1:kmax)]
  neg <- which(gam <= 0); kk <- if (length(neg)) neg[1] - 1 else kmax
  if (kk < 1) return(m * n)
  m * n / max(-1 + 2 * sum(cummin(gam[1:kk])), 1)
}

## ---- model ----
n_visit <- 12; y_det <- 3; a_pri <- 1; b_pri <- 1
post_a <- a_pri + y_det; post_b <- b_pri + n_visit - y_det
post_sd <- sqrt(post_a * post_b /
                ((post_a + post_b)^2 * (post_a + post_b + 1)))
print(round(c(visits = n_visit, detections = y_det,
              prior_a = a_pri, prior_b = b_pri,
              post_a = post_a, post_b = post_b,
              post_mean = post_a / (post_a + post_b),
              post_sd = post_sd), 5))

## ---- log-target ----
logpost_z <- function(z, y, n, jac = TRUE) {
  lt <- plogis(z, log.p = TRUE); lu <- plogis(-z, log.p = TRUE)
  out <- (y + a_pri - 1) * lt + (n - y + b_pri - 1) * lu
  if (jac) out + lt + lu else out
}

run_rw <- function(n_iter, step, z0, jac, y = y_det, n = n_visit) {
  keep <- numeric(n_iter); cur <- z0
  lcur <- logpost_z(cur, y, n, jac); n_acc <- 0
  for (i in seq_len(n_iter)) {
    prop <- cur + rnorm(1, 0, step)
    lp <- logpost_z(prop, y, n, jac)
    if (log(runif(1)) < lp - lcur) { cur <- prop; lcur <- lp; n_acc <- n_acc + 1 }
    keep[i] <- cur
  }
  list(z = keep, acc = n_acc / n_iter)
}

## ---- run-samplers ----
set.seed(20260729)
n_chain <- 4; n_iter <- 12000; n_warm <- 2000; rw_step <- 1.2
inits <- c(-3, -1, 0, 1.5)

draw_theta <- function(jac) {
  M <- matrix(NA_real_, n_iter - n_warm, n_chain); a <- numeric(n_chain)
  for (j in seq_len(n_chain)) {
    r <- run_rw(n_iter, rw_step, inits[j], jac)
    M[, j] <- plogis(r$z[(n_warm + 1):n_iter]); a[j] <- r$acc
  }
  list(theta = M, acc = mean(a))
}

fit_ok <- draw_theta(TRUE)
fit_bad <- draw_theta(FALSE)
print(c(chains = n_chain, iter_per_chain = n_iter, warmup = n_warm,
        kept_draws = length(fit_ok$theta)))
print(round(c(proposal_sd = rw_step, accept_correct = fit_ok$acc,
              accept_broken = fit_bad$acc), 4))

## ---- convergence ----
diag_row <- function(M, lab) {
  e <- ess_geyer(M)
  data.frame(sampler = lab, rhat = round(rhat_split(M), 4), ess = round(e),
             post_mean = round(mean(M), 5),
             mcse = round(sd(as.vector(M)) / sqrt(e), 5))
}
conv <- rbind(diag_row(fit_ok$theta, "correct"),
              diag_row(fit_bad$theta, "no Jacobian"))
conv$exact <- round(post_a / (post_a + post_b), 5)
conv$z <- round((conv$post_mean - conv$exact) / conv$mcse, 2)
print(conv)
print(round(c(broken_target_mean = (post_a - 1) / (post_a + post_b - 2)), 5))

## ---- benchmark ----
q_lev <- c(0.025, 0.25, 0.5, 0.75, 0.975)
q_exact <- qbeta(q_lev, post_a, post_b)

bench <- function(M, lab) {
  x <- as.vector(M)
  qh <- quantile(x, q_lev, names = FALSE)
  dd <- density(x, n = 2048, from = 0, to = 1)
  fq <- approx(dd$x, dd$y, xout = qh)$y
  se <- numeric(length(q_lev))
  for (k in seq_along(q_lev)) {
    e <- ess_geyer((M <= qh[k]) * 1)
    se[k] <- sqrt(q_lev[k] * (1 - q_lev[k]) / e) / fq[k]
  }
  data.frame(sampler = lab, level = q_lev, exact = round(q_exact, 5),
             sampled = round(qh, 5), mcse = round(se, 5),
             z = round((qh - q_exact) / se, 2))
}

bench_tab <- rbind(bench(fit_ok$theta, "correct"),
                   bench(fit_bad$theta, "no Jacobian"))
print(bench_tab)
print(round(c(max_abs_z_correct = max(abs(bench_tab$z[1:5])),
              max_abs_z_broken = max(abs(bench_tab$z[6:10]))), 2))
print(round(c(gap_at_lowest_level =
                bench_tab$sampled[1] - bench_tab$exact[1]), 5))

## ---- fig-benchmark ----
bt <- bench_tab
bt$sampler <- factor(bt$sampler, levels = c("correct", "no Jacobian"))
ggplot(bt, aes(level, z, colour = sampler, shape = sampler)) +
  annotate("rect", xmin = 0, xmax = 1, ymin = -2, ymax = 2,
           fill = te_pal$sage, alpha = 0.35) +
  geom_hline(yintercept = 0, colour = te_pal$ink, linewidth = 0.4) +
  geom_line(linewidth = 0.7) +
  geom_point(size = 2.8) +
  annotate("text", x = 0.5, y = 5.5, label = "plus or minus 2 standard errors",
           colour = "#2c3a31", size = 3.2) +
  scale_colour_manual(values = c(correct = te_pal$green,
                                 `no Jacobian` = te_pal$clay)) +
  scale_shape_manual(values = c(correct = 16, `no Jacobian` = 17)) +
  scale_x_continuous(breaks = q_lev) +
  labs(x = "posterior quantile level",
       y = "(sampled - exact) / Monte Carlo SE",
       colour = NULL, shape = NULL,
       title = "Sampled quantiles against the exact beta posterior") +
  theme_te()

## ---- sbc-engine ----
sbc_narrow <- 0.6; sbc_wide <- 1.6; sbc_shift <- 0.4

rw_thin <- function(y, n_keep, warm, thin, jac) {
  cur <- 0; lcur <- logpost_z(cur, y, n_visit, jac)
  total <- warm + n_keep * thin; out <- numeric(n_keep); k <- 0
  for (i in seq_len(total)) {
    prop <- cur + rnorm(1, 0, rw_step)
    lp <- logpost_z(prop, y, n_visit, jac)
    if (log(runif(1)) < lp - lcur) { cur <- prop; lcur <- lp }
    if (i > warm && ((i - warm) %% thin == 0)) { k <- k + 1; out[k] <- cur }
  }
  plogis(out)
}

## ---- sbc-run ----
set.seed(20260730)
n_rep <- 400; n_draw <- 15; n_bin <- n_draw + 1
sbc_warm <- 250; sbc_thin <- 25
theta_true <- rbeta(n_rep, a_pri, b_pri)
y_sim <- rbinom(n_rep, n_visit, theta_true)
sbc_lab <- c("exact conjugate", "Metropolis, correct", "Metropolis, no Jacobian",
             "posterior too narrow", "posterior too wide", "posterior shifted")
ranks <- matrix(NA_integer_, n_rep, 6)

for (r in seq_len(n_rep)) {
  y <- y_sim[r]; tt <- theta_true[r]
  aa <- a_pri + y; bb <- b_pri + n_visit - y
  ex <- rbeta(n_draw, aa, bb); zz <- qlogis(ex)
  mz <- digamma(aa) - digamma(bb); sz <- sqrt(trigamma(aa) + trigamma(bb))
  ranks[r, 1] <- sum(ex < tt)
  ranks[r, 2] <- sum(rw_thin(y, n_draw, sbc_warm, sbc_thin, TRUE) < tt)
  ranks[r, 3] <- sum(rw_thin(y, n_draw, sbc_warm, sbc_thin, FALSE) < tt)
  ranks[r, 4] <- sum(plogis(mz + sbc_narrow * (zz - mz)) < tt)
  ranks[r, 5] <- sum(plogis(mz + sbc_wide * (zz - mz)) < tt)
  ranks[r, 6] <- sum(plogis(zz + sbc_shift * sz) < tt)
}
print(c(replicates = n_rep, draws_per_fit = n_draw, bins = n_bin,
        df = n_bin - 1, expected_per_bin = n_rep / n_bin,
        sbc_warmup = sbc_warm, sbc_thin = sbc_thin))
print(round(c(narrow_factor = sbc_narrow, wide_factor = sbc_wide,
              shift_in_sd = sbc_shift, chisq_crit_level = 0.95,
              chisq_crit_value = qchisq(0.95, n_bin - 1)), 3))

## ---- sbc-chisq ----
exp_bin <- n_rep / n_bin
sbc_tab <- data.frame(sampler = sbc_lab,
  chisq = round(apply(ranks, 2, function(x)
    sum((tabulate(x + 1, n_bin) - exp_bin)^2 / exp_bin)), 2))
sbc_tab$lowest_bin <- apply(ranks, 2, function(x) sum(x == 0))
sbc_tab$highest_bin <- apply(ranks, 2, function(x) sum(x == n_draw))
sbc_tab$middle_four <- apply(ranks, 2, function(x) sum(x >= 6 & x <= 9))
print(sbc_tab)
print(c(expected_per_bin = exp_bin, expected_middle_four = 4 * exp_bin))

## ---- fig-sbc ----
rk_df <- do.call(rbind, lapply(seq_len(6), function(j)
  data.frame(rank = 0:n_draw, count = tabulate(ranks[, j] + 1, n_bin),
             sampler = sbc_lab[j],
             verdict = if (j <= 2) "calibrated" else "not calibrated")))
rk_df$sampler <- factor(rk_df$sampler, levels = sbc_lab)

ggplot(rk_df, aes(rank, count, fill = verdict)) +
  geom_col(width = 0.85) +
  geom_hline(yintercept = exp_bin, colour = te_pal$ink,
             linetype = 2, linewidth = 0.4) +
  facet_wrap(~ sampler, ncol = 3) +
  scale_fill_manual(values = c(calibrated = te_pal$green,
                               `not calibrated` = te_pal$clay)) +
  labs(x = "rank of the true value among 15 posterior draws",
       y = "number of simulations", fill = NULL,
       title = "Rank histograms from 400 calibration runs") +
  theme_te()

## ---- sbc-split ----
edge <- y_sim %in% c(0, n_visit)
chisq_of <- function(r) {
  e <- length(r) / n_bin
  sum((tabulate(r + 1, n_bin) - e)^2 / e)
}
print(c(edge_surveys = sum(edge), other_surveys = sum(!edge),
        edge_runs_in_end_bins = sum(ranks[edge, 3] %in% c(0, n_draw))))
print(round(c(chisq_no_jacobian_other = chisq_of(ranks[!edge, 3]),
              chisq_correct_other = chisq_of(ranks[!edge, 2])), 2))

## ---- hmc-engine ----
hmc <- function(logp, glogp, q0, n_it, eps, n_leap, delta_max = 1000) {
  d <- length(q0)
  out <- matrix(NA_real_, n_it, d); dv <- logical(n_it); en <- numeric(n_it)
  q <- q0; lp <- logp(q); n_acc <- 0
  for (i in seq_len(n_it)) {
    mom <- rnorm(d); h0 <- -lp + 0.5 * sum(mom^2); en[i] <- h0
    qq <- q; pp <- mom; lpp <- lp; gg <- glogp(qq); bad <- FALSE; hh <- h0
    for (l in seq_len(n_leap)) {
      pp <- pp + 0.5 * eps * gg
      qq <- qq + eps * pp
      gg <- glogp(qq)
      pp <- pp + 0.5 * eps * gg
      lpp <- logp(qq); hh <- -lpp + 0.5 * sum(pp^2)
      if (!is.finite(hh) || (hh - h0) > delta_max) { bad <- TRUE; break }
    }
    if (!bad && log(runif(1)) < h0 - hh) { q <- qq; lp <- lpp; n_acc <- n_acc + 1 }
    out[i, ] <- q; dv[i] <- bad
  }
  list(draws = out, div = dv, energy = en, acc = n_acc / n_it)
}

## ---- funnel-targets ----
n_x <- 9
lp_cen <- function(q) {
  v <- q[1]; x <- q[-1]
  -v^2 / 18 - n_x * v / 2 - 0.5 * exp(-v) * sum(x^2)
}
gl_cen <- function(q) {
  v <- q[1]; x <- q[-1]
  c(-v / 9 - n_x / 2 + 0.5 * exp(-v) * sum(x^2), -exp(-v) * x)
}
lp_nc <- function(q) -0.5 * sum(q^2)
gl_nc <- function(q) -q

## ---- hmc-run ----
hmc_iter <- 2500; hmc_warm <- 500; n_leap <- 20

run_hmc <- function(lp, gl, centred, eps) {
  kp <- (hmc_warm + 1):hmc_iter; nk <- length(kp)
  V <- matrix(NA_real_, nk, n_chain); X <- V; E <- V
  D <- matrix(NA, nk, n_chain); a <- numeric(n_chain)
  for (j in seq_len(n_chain)) {
    r <- hmc(lp, gl, rnorm(n_x + 1) * 0.5, hmc_iter, eps, n_leap)
    d <- r$draws[kp, ]
    if (centred) { V[, j] <- d[, 1]; X[, j] <- d[, 2] }
    else { V[, j] <- 3 * d[, 1]; X[, j] <- exp(3 * d[, 1] / 2) * d[, 2] }
    D[, j] <- r$div[kp]; E[, j] <- r$energy[kp]; a[j] <- r$acc
  }
  list(V = V, X = X, D = D, acc = mean(a), div_rate = mean(D), n_div = sum(D),
       ebfmi = mean(apply(E, 2, function(e)
         sum(diff(e)^2) / (length(e) * var(e)))),
       rhat = rhat_split(V), ess = ess_geyer(V),
       mean_v = mean(V), sd_v = sd(as.vector(V)),
       q05 = quantile(as.vector(V), 0.05, names = FALSE))
}

set.seed(20260731)
hmc_runs <- list(run_hmc(lp_cen, gl_cen, TRUE, 0.2),
                 run_hmc(lp_cen, gl_cen, TRUE, 0.4),
                 run_hmc(lp_cen, gl_cen, TRUE, 0.6),
                 run_hmc(lp_nc, gl_nc, FALSE, 0.4))
hmc_tab <- data.frame(
  run = c("centred, step 0.2", "centred, step 0.4", "centred, step 0.6",
          "non-centred, step 0.4"),
  accept = round(sapply(hmc_runs, function(o) o$acc), 4),
  div_rate = round(sapply(hmc_runs, function(o) o$div_rate), 4),
  n_div = sapply(hmc_runs, function(o) o$n_div),
  ebfmi = round(sapply(hmc_runs, function(o) o$ebfmi), 4),
  rhat = round(sapply(hmc_runs, function(o) o$rhat), 4),
  ess = round(sapply(hmc_runs, function(o) o$ess)),
  sd_v = round(sapply(hmc_runs, function(o) o$sd_v), 4),
  q05_v = round(sapply(hmc_runs, function(o) o$q05), 4))
print(hmc_tab)
print(c(hmc_chains = n_chain, hmc_iter = hmc_iter, hmc_warmup = hmc_warm,
        leapfrog = n_leap, latent_x = n_x, kept = length(hmc_runs[[1]]$V)))
print(round(c(true_sd_v = 3, true_q05_v = qnorm(0.05, 0, 3),
              rhat_rule_old = 1.1, rhat_rule_modern = 1.01,
              ebfmi_warning_line = 0.3), 4))

## ---- divergence-location ----
cc <- hmc_runs[[2]]; nc <- hmc_runs[[4]]
print(round(c(mean_v_all = mean(cc$V), mean_v_divergent = mean(cc$V[cc$D]),
              frac_div_below_zero = mean(cc$V[cc$D] < 0),
              frac_all_below_zero = mean(cc$V < 0),
              lowest_v_centred = min(cc$V),
              lowest_v_noncentred = min(nc$V)), 4))
x_win <- 10
print(c(window = x_win,
        outside_centred = sum(abs(cc$X) > x_win),
        outside_noncentred = sum(abs(nc$X) > x_win)))

## ---- fig-divergence ----
mk_df <- function(o, lab) data.frame(
  x1 = as.vector(o$X), v = as.vector(o$V),
  state = ifelse(as.vector(o$D), "divergent", "kept"), run = lab)
d3 <- rbind(mk_df(cc, "centred, step 0.4"), mk_df(nc, "non-centred, step 0.4"))
d3$state <- factor(d3$state, levels = c("kept", "divergent"))

ggplot(mapping = aes(x1, v, colour = state, shape = state)) +
  geom_point(data = d3[d3$state == "kept", ], size = 0.7, alpha = 0.25) +
  geom_point(data = d3[d3$state == "divergent", ], size = 1.7, alpha = 0.9) +
  facet_wrap(~ run) +
  coord_cartesian(xlim = c(-x_win, x_win), ylim = c(-12, 10)) +
  scale_colour_manual(values = c(kept = te_pal$sage, divergent = te_pal$clay)) +
  scale_shape_manual(values = c(kept = 16, divergent = 17)) +
  labs(x = "first latent value x1", y = "log scale parameter v",
       colour = NULL, shape = NULL,
       title = "Where the divergent transitions sit") +
  guides(colour = guide_legend(override.aes = list(size = 2.5, alpha = 1))) +
  theme_te()

## ---- precision ----
target_mcse <- 0.0005; report_ess <- 200
ess_mean_need <- (post_sd / target_mcse)^2
need_q <- function(p) {
  q <- qbeta(p, post_a, post_b)
  p * (1 - p) / (target_mcse * dbeta(q, post_a, post_b))^2
}
mcse_q_at <- function(p, ess) {
  sqrt(p * (1 - p) / ess) / dbeta(qbeta(p, post_a, post_b), post_a, post_b)
}
prec_tab <- data.frame(
  quantity = c("posterior mean", "quantile 0.025", "quantile 0.5",
               "quantile 0.975"),
  ess_needed = round(c(ess_mean_need, need_q(0.025), need_q(0.5),
                       need_q(0.975))),
  mcse_at_report_ess = round(c(post_sd / sqrt(report_ess),
                               mcse_q_at(0.025, report_ess),
                               mcse_q_at(0.5, report_ess),
                               mcse_q_at(0.975, report_ess)), 5))
prec_tab$factor_vs_mean <- round(prec_tab$ess_needed / ess_mean_need, 2)
print(prec_tab)
need_norm <- function(p) p * (1 - p) * post_sd^2 / (target_mcse * dnorm(qnorm(p)))^2
print(round(c(target_mcse = target_mcse, report_ess = report_ess,
              post_sd = post_sd, ess_achieved = conv$ess[1],
              shortfall_mean = ess_mean_need / conv$ess[1],
              normal_tail_factor = need_norm(0.025) / ess_mean_need), 4))

## ---- fig-mcse ----
p_grid <- seq(0.01, 0.99, by = 0.005)
d4 <- rbind(
  data.frame(p = p_grid, need = need_q(p_grid), shape = "beta posterior (actual)"),
  data.frame(p = p_grid, need = need_norm(p_grid),
             shape = "normal with the same SD"))

ggplot(d4, aes(p, need, colour = shape, linetype = shape)) +
  geom_line(linewidth = 0.8) +
  geom_hline(yintercept = ess_mean_need, colour = te_pal$ink,
             linetype = 3, linewidth = 0.5) +
  annotate("text", x = 0.5, y = ess_mean_need * 0.72,
           label = "what the posterior mean needs",
           colour = "#2c3a31", size = 3.2) +
  annotate("point", x = c(0.025, 0.975),
           y = c(need_q(0.025), need_q(0.975)),
           size = 3, colour = te_pal$gold) +
  scale_y_log10(breaks = c(1e4, 3e4, 1e5, 3e5, 1e6),
                labels = c("10k", "30k", "100k", "300k", "1M")) +
  scale_colour_manual(values = c(`beta posterior (actual)` = te_pal$forest,
                                 `normal with the same SD` = te_pal$clay)) +
  labs(x = "quantile level", y = "effective sample size needed",
       colour = NULL, linetype = NULL,
       title = "Cost of a third decimal place, by quantile") +
  theme_te()
