---
title: "MCMC chain quality and posterior predictive model checks"
author: "Odd Kolbjørnsen"
output:
  html_document:
    toc: true
    toc_float: true
    code_folding: show
    number_sections: true
---

```{r setup, message=FALSE, warning=FALSE}
set.seed(4021)
fig_dir <- "fig_mcmc_quality"
dir.create(fig_dir, showWarnings = FALSE)

have_posterior <- requireNamespace("posterior", quietly = TRUE)
have_bayesplot <- requireNamespace("bayesplot", quietly = TRUE)
have_ggplot2 <- requireNamespace("ggplot2", quietly = TRUE)
have_MASS <- requireNamespace("MASS", quietly = TRUE)

if (have_ggplot2) library(ggplot2)
```

# Two distinct quality questions

This notebook deliberately separates:

1. **algorithmic quality**, whether retained MCMC draws adequately represent the posterior under the chosen model;
2. **model quality**, whether the fitted model reproduces scientifically relevant aspects of the observations.

Posterior predictive checks below are interpreted only after the MCMC diagnostics are acceptable.

# Transparent random-walk Metropolis implementation

```{r sampler}
rw_metropolis <- function(log_target, n_iter, init, proposal_sd) {
  theta <- numeric(n_iter)
  accepted <- logical(n_iter)
  theta[1] <- init

  for (s in 2:n_iter) {
    proposal <- rnorm(1, theta[s - 1], proposal_sd)
    log_alpha <- min(0, log_target(proposal) - log_target(theta[s - 1]))

    if (log(runif(1)) < log_alpha) {
      theta[s] <- proposal
      accepted[s] <- TRUE
    } else {
      theta[s] <- theta[s - 1]
    }
  }

  list(
    theta = theta,
    accepted = accepted,
    acceptance_rate = mean(accepted[-1])
  )
}

log_target_normal <- function(theta) dnorm(theta, 0, 1, log = TRUE)
```

## Visual example: good and poor mixing

The next figure compares two chains with the same standard-normal target. The distinction is not whether both algorithms have the correct invariant distribution. It is how rapidly they move through that distribution.

```{r mixing-good-bad, fig.width=10, fig.height=5}
set.seed(4022)
poor_mix <- rw_metropolis(log_target_normal, 3000, init = -2,
                          proposal_sd = 0.05)$theta
good_mix <- rw_metropolis(log_target_normal, 3000, init = -2,
                          proposal_sd = 2.4)$theta

pdf(file.path(fig_dir, "mixing_good_bad.pdf"), width = 10, height = 4.7)
par(mfrow = c(2, 2), mar = c(3.4, 4, 2, 1), mgp = c(2, 0.7, 0))

plot(poor_mix, type = "l", col = "grey20",
     xlab = "Iteration", ylab = expression(theta),
     main = "Poor mixing: trace")
plot(good_mix, type = "l", col = "grey20",
     xlab = "Iteration", ylab = expression(theta),
     main = "Good mixing: trace")
acf(poor_mix, lag.max = 60, main = "Poor mixing: ACF")
acf(good_mix, lag.max = 60, main = "Good mixing: ACF")
dev.off()

par(mfrow = c(2, 2))
plot(poor_mix, type = "l", main = "Poor mixing: trace")
plot(good_mix, type = "l", main = "Good mixing: trace")
acf(poor_mix, lag.max = 60, main = "Poor mixing: ACF")
acf(good_mix, lag.max = 60, main = "Good mixing: ACF")
```

The poorly mixing chain has long memory: nearby draws are very similar and the autocorrelation decays slowly. The well-mixing chain repeatedly crosses the typical region and forgets its current position more rapidly.

# Parallel chains with dispersed starting points

```{r parallel-chains}
initial_values <- c(-8, -3, 3, 8)
n_iter <- 4000
burn_in <- 1000
proposal_sd <- 0.20

fits <- lapply(initial_values, function(x0) {
  rw_metropolis(log_target_normal, n_iter, x0, proposal_sd)
})

draws_all <- sapply(fits, `[[`, "theta")
colnames(draws_all) <- paste0("chain_", seq_along(initial_values))
draws_post <- draws_all[(burn_in + 1):n_iter, , drop = FALSE]
```

##  Trace plots including warm-up

```{r plot-all, fig.width=10, fig.height=5}
pdf(file.path(fig_dir, "chains_all.pdf"), width = 10, height = 4.6)
matplot(draws_all, type = "l", lty = 1, col = 1:4,
        xlab = "Iteration", ylab = expression(theta),
        main = "Four dispersed chains; warm-up included")
abline(v = burn_in, lty = 2, lwd = 2)
legend("topright", legend = colnames(draws_all), col = 1:4, lty = 1, bty = "n")
dev.off()

pdf(file.path(fig_dir, "chains_one.pdf"), width = 10, height = 4.6)
matplot(draws_all[,1], type = "l", lty = 1, col = 2,
        xlab = "Iteration", ylab = expression(theta),
        main = "One chains; warm-up included")
#abline(v = burn_in, lty = 2, lwd = 2)
legend("topright", legend = colnames(draws_all)[1], col = 2, lty = 1, bty = "n")
dev.off()



matplot(draws_all, type = "l", lty = 1, col = 1:4,
        xlab = "Iteration", ylab = expression(theta))
abline(v = burn_in, lty = 2)
```

##  Trace plots after warm-up

```{r plot-post, fig.width=10, fig.height=5}
pdf(file.path(fig_dir, "chains_postwarmup.pdf"), width = 10, height = 4.6)
matplot(draws_post, type = "l", lty = 1, col = 1:4,
        xlab = "Retained iteration", ylab = expression(theta),
        main = "Post-warm-up draws")
legend("topright", legend = colnames(draws_post), col = 1:4, lty = 1, bty = "n")
dev.off()

matplot(draws_post, type = "l", lty = 1, col = 1:4,
        xlab = "Retained iteration", ylab = expression(theta))
```

#  Manual calculation of classical R-hat

The elementary derivation uses

\[
W=\frac1M\sum_{m=1}^M s_m^2,
\qquad
B=\frac{N}{M-1}\sum_{m=1}^M
(\bar\theta_{\cdot m}-\bar\theta_{\cdot\cdot})^2,
\]

\[
\widehat{\mathrm{var}}^+=\frac{N-1}{N}W+\frac1N B,
\qquad
\widehat R=\sqrt{\widehat{\mathrm{var}}^+/W}.
\]

```{r rhat-function}
rhat_classical <- function(draw_matrix) {
  draw_matrix <- as.matrix(draw_matrix)
  N <- nrow(draw_matrix)
  M <- ncol(draw_matrix)

  chain_means <- colMeans(draw_matrix)
  chain_vars <- apply(draw_matrix, 2, var)
  W <- mean(chain_vars)
  B <- N * var(chain_means)
  var_plus <- ((N - 1) / N) * W + B / N
  Rhat <- sqrt(var_plus / W)

  list(
    N = N,
    M = M,
    chain_means = chain_means,
    chain_vars = chain_vars,
    W = W,
    B = B,
    var_plus = var_plus,
    Rhat = Rhat
  )
}
```

##  Before and after warm-up

```{r rhat-before-after}
rhat_all <- rhat_classical(draws_all)
rhat_post <- rhat_classical(draws_post)

rbind(
  all_iterations = c(W = rhat_all$W, B = rhat_all$B,
                     var_plus = rhat_all$var_plus, Rhat = rhat_all$Rhat),
  post_warmup = c(W = rhat_post$W, B = rhat_post$B,
                  var_plus = rhat_post$var_plus, Rhat = rhat_post$Rhat)
)
```

```{r chain-summary}
data.frame(
  chain = colnames(draws_all),
  start = initial_values,
  mean_all = colMeans(draws_all),
  mean_post = colMeans(draws_post),
  sd_all = apply(draws_all, 2, sd),
  sd_post = apply(draws_post, 2, sd),
  acceptance = vapply(fits, `[[`, numeric(1), "acceptance_rate")
)
```

# Split R-hat

```{r split-chains}
split_chains <- function(draw_matrix) {
  draw_matrix <- as.matrix(draw_matrix)
  N <- nrow(draw_matrix)
  half <- floor(N / 2)
  first <- draw_matrix[seq_len(half), , drop = FALSE]
  second <- draw_matrix[(N - half + 1):N, , drop = FALSE]
  out <- cbind(first, second)
  colnames(out) <- paste0(rep(colnames(draw_matrix), 2),
                          rep(c("_first", "_second"), each = ncol(draw_matrix)))
  out
}

split_post <- split_chains(draws_post)
rhat_classical(split_post)$Rhat
```

If the `posterior` package is installed, compare with modern rank-normalized split R-hat.

```{r modern-rhat}
if (have_posterior) {
  posterior::rhat(draws_post)
}
```

#  ESS and MCSE

The covariance-sum derivation was covered previously. Here we use the results diagnostically.

```{r ess-functions}
ess_geyer_one <- function(x) {
  n <- length(x)
  ac <- as.numeric(acf(x, plot = FALSE, lag.max = n - 1, demean = TRUE)$acf)
  if (length(ac) < 3) return(n)

  pair_sum <- numeric(0)
  k <- 2
  while ((k + 1) <= length(ac)) {
    gamma_hat <- ac[k] + ac[k + 1]
    if (!is.finite(gamma_hat) || gamma_hat <= 0) break
    pair_sum <- c(pair_sum, gamma_hat)
    k <- k + 2
  }

  tau_hat <- 1 + 2 * sum(pair_sum)
  min(n, n / tau_hat)
}

ess_total <- function(draw_matrix) {
  sum(apply(draw_matrix, 2, ess_geyer_one))
}

mcse_mean_manual <- function(draw_matrix) {
  pooled <- as.numeric(draw_matrix)
  sqrt(var(pooled) / ess_total(draw_matrix))
}

c(
  ESS = ess_total(draws_post),
  MCSE_mean = mcse_mean_manual(draws_post),
  posterior_SD = sd(as.numeric(draws_post))
)
```

#  Proposal-scale experiment

We compare three scales using the same dispersed starting points and the same retained length.

```{r scale-experiment}
proposal_scales <- c(0.05, 2.4, 12)
scale_results <- vector("list", length(proposal_scales))

for (i in seq_along(proposal_scales)) {
  s <- proposal_scales[i]
  fs <- lapply(initial_values, function(x0) {
    rw_metropolis(log_target_normal, n_iter, x0, s)
  })
  mat <- sapply(fs, function(f) f$theta[(burn_in + 1):n_iter])
  colnames(mat) <- paste0("chain_", 1:4)

  scale_results[[i]] <- list(
    scale = s,
    fits = fs,
    draws = mat,
    acceptance = mean(vapply(fs, `[[`, numeric(1), "acceptance_rate")),
    lag1 = mean(apply(mat, 2, function(x) acf(x, lag.max = 1,
                                                plot = FALSE)$acf[2])),
    ESS = ess_total(mat),
    MCSE = mcse_mean_manual(mat),
    Rhat = rhat_classical(split_chains(mat))$Rhat
  )
}

diagnostics_table <- do.call(rbind, lapply(scale_results, function(z) {
  data.frame(
    proposal_sd = z$scale,
    acceptance = z$acceptance,
    lag1_acf = z$lag1,
    ESS = z$ESS,
    MCSE = z$MCSE,
    Rhat = z$Rhat
  )
}))
diagnostics_table
```

## Synchronized trace and ACF plots

```{r diagnostic-plot-function}
plot_scale_diagnostics <- function(result, filename) {
  mat <- result$draws
  pdf(file.path(fig_dir, filename), width = 10, height = 4.6)
  par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
  matplot(mat, type = "l", lty = 1, col = 1:4,
          xlab = "Retained iteration", ylab = expression(theta),
          main = sprintf("s = %.2f; acceptance = %.2f",
                         result$scale, result$acceptance))
  acfs <- sapply(1:ncol(mat), function(j) {
    as.numeric(acf(mat[, j], lag.max = 50, plot = FALSE)$acf)
  })
  mean_acf <- rowMeans(acfs)
  plot(0:50, mean_acf, type = "h", lwd = 1.2,
       xlab = "Lag", ylab = "Mean ACF",
       main = sprintf("ESS = %.0f; R-hat = %.3f",
                      result$ESS, result$Rhat), ylim = c(-0.05, 1))
  abline(h = 0, lty = 3)
  dev.off()
}

plot_scale_diagnostics(scale_results[[1]], "proposal_small.pdf")
plot_scale_diagnostics(scale_results[[2]], "proposal_good.pdf")
plot_scale_diagnostics(scale_results[[3]], "proposal_large.pdf")
```

```{r show-scale-plots, fig.width=10, fig.height=13, echo=FALSE}
par(mfrow = c(3, 2))
for (res in scale_results) {
  matplot(res$draws, type = "l", lty = 1, col = 1:4,
          xlab = "Iteration", ylab = "theta",
          main = paste("proposal SD", res$scale))
  acf(res$draws[, 1], main = "ACF, chain 1")
}
```

# Posterior summaries from retained MCMC draws

Use the best-performing setting according to the synchronized table, not a hard-coded acceptance rule.

```{r posterior-summaries}
best_index <- which.max(vapply(scale_results, `[[`, numeric(1), "ESS"))
best_draws <- as.numeric(scale_results[[best_index]]$draws)

posterior_mean <- mean(best_draws)
posterior_probability <- mean(best_draws > 0.5)
posterior_quantiles <- quantile(best_draws, c(0.025, 0.5, 0.975))

list(
  mean = posterior_mean,
  probability_theta_gt_0.5 = posterior_probability,
  quantiles = posterior_quantiles
)
```

Inference for a nonlinear transformation is obtained directly from transformed draws.

```{r transformed-summaries}
g_draws <- exp(best_draws)
c(
  mean = mean(g_draws),
  probability_gt_2 = mean(g_draws > 2),
  quantile(g_draws, c(0.025, 0.5, 0.975))
)
```

#  A warning example: all chains trapped in one mode

A value of R-hat near one is not a proof that the full target has been explored.

```{r mixture-target}
log_sum_exp <- function(a, b) {
  m <- max(a, b)
  m + log(exp(a - m) + exp(b - m))
}

log_target_mixture <- function(theta) {
  log_sum_exp(log(0.5) + dnorm(theta, -4, 1, log = TRUE),
              log(0.5) + dnorm(theta,  4, 1, log = TRUE))
}

same_mode_starts <- c(-5, -4.5, -4, -3.5)
mixture_fits <- lapply(same_mode_starts, function(x0) {
  rw_metropolis(log_target_mixture, 5000, x0, proposal_sd = 0.4)
})
mixture_draws <- sapply(mixture_fits, function(f) f$theta[1001:5000])

c(
  split_Rhat = rhat_classical(split_chains(mixture_draws))$Rhat,
  minimum = min(mixture_draws),
  maximum = max(mixture_draws)
)
```

```{r mixture-plot, fig.width=10, fig.height=4}
matplot(mixture_draws, type = "l", lty = 1, col = 1:4,
        xlab = "Retained iteration", ylab = expression(theta),
        main = "All chains agree, but may occupy only one mode")
abline(h = 4, lty = 2)
```

#  Posterior predictive simulation: 

A generic two-stage implementation takes posterior draws and a conditional simulator.

```{r posterior-predict-function}
simulate_posterior_predictive <- function(draws, simulate_y) {
  lapply(seq_len(nrow(draws)), function(s) {
    simulate_y(draws[s, , drop = FALSE])
  })
}
```

For each retained draw, the function first takes a posterior parameter value, then simulates a replicated dataset conditionally on that value.


# Newcomb speed-of-light data

The fallback values below are the data listed in the MASS documentation
(Stigler's ordering). They have the same unordered values as MASS::newcomb.
Do not interpret the fallback ordering as experimental time.
Source: https://rdrr.io/cran/MASS/man/newcomb.html

```{r newcomb-data}
if (requireNamespace("MASS", quietly = TRUE)) {
  y_newcomb <- MASS::newcomb
} else {
  y_newcomb <- c(28, 26, 33, 24, 34, -44, 27, 16, 40, -2, 29, 22, 24, 21, 25, 30, 23, 29, 31, 19, 24, 20, 36, 32, 36, 28, 25, 21, 28, 29, 37, 25, 28, 26, 30, 32, 36, 26, 30, 22, 36, 23, 27, 27, 28, 27, 31, 27, 26, 33, 26, 32, 32, 24, 39, 28, 24, 25, 32, 25, 29, 27, 28, 29, 16, 23)
}
n_newcomb <- length(y_newcomb)
summary(y_newcomb)

# Use the same directory as your existing lecture figures.
fig_dir <- "fig"
dir.create(fig_dir, recursive = TRUE, showWarnings = FALSE)
```

##  Gaussian model and posterior simulation

Let $\theta=(\mu,\sigma)$ and assume
\[
Y_i\mid\theta\overset{\mathrm{iid}}{\sim}N(\mu,\sigma^2),
\qquad p(\mu,\sigma^2)\propto1/\sigma^2.
\]
Then
\[
\sigma^2\mid y\sim\operatorname{InvGamma}
\left(\frac{n-1}{2},\frac{(n-1)s_y^2}{2}\right),
\qquad
\mu\mid\sigma^2,y\sim N(\bar y,\sigma^2/n).
\]
These are independent posterior draws, not an MCMC chain.

```{r newcomb-posterior}
set.seed(4021)
S <- 5000
ybar <- mean(y_newcomb)
s2 <- var(y_newcomb)
sigma2_draw <- 1 / rgamma(S, shape = (n_newcomb - 1) / 2,
                          rate = (n_newcomb - 1) * s2 / 2)
sigma_draw <- sqrt(sigma2_draw)
mu_draw <- rnorm(S, ybar, sigma_draw / sqrt(n_newcomb))
```

##  Replicated datasets

Each row is a replicated dataset of the same size as the observations.

```{r newcomb-replicates}
yrep_newcomb <- matrix(NA_real_, S, n_newcomb)
for (s in seq_len(S)) {
  yrep_newcomb[s, ] <- rnorm(n_newcomb, mu_draw[s], sigma_draw[s])
}
```

##  Test statistic and discrepancy measure

The minimum is a **test statistic**, depending only on observations:
\[
T_1(y)=\min_i y_i.
\]
The largest standardized residual is a **discrepancy measure**:
\[
T_2(y,\theta)=\max_i|(y_i-\mu)/\sigma|.
\]
Use the same posterior draw for each observed/replicated discrepancy pair.

```{r newcomb-test-quantities}
T_min_obs <- min(y_newcomb)
T_min_rep <- apply(yrep_newcomb, 1, min)
T_extreme_obs <- numeric(S)
T_extreme_rep <- numeric(S)
for (s in seq_len(S)) {
  T_extreme_obs[s] <- max(abs((y_newcomb - mu_draw[s]) / sigma_draw[s]))
  T_extreme_rep[s] <- max(abs((yrep_newcomb[s, ] - mu_draw[s]) / sigma_draw[s]))
}
pB_min_lower <- mean(T_min_rep <= T_min_obs)
pB_extreme_upper <- mean(T_extreme_rep >= T_extreme_obs)
c(minimum_lower_tail = pB_min_lower,
  standardized_extreme_upper_tail = pB_extreme_upper)
```

A reported zero means no event occurred in these finite simulations, not
that the exact posterior predictive probability is zero.

##  Graphical check 1: observed and replicated histograms

Use common bins and axes. Histogram outlines avoid obscuring the observed
histogram. This shows the whole distribution, not only one extreme.

```{r newcomb-histograms, fig.width=10, fig.height=4.8}
set.seed(4022)
show_index <- sample(seq_len(S), 20)
breaks_y <- pretty(range(y_newcomb, yrep_newcomb[show_index, ]), n = 25)
h_obs <- hist(y_newcomb, breaks = breaks_y, plot = FALSE)
h_rep <- lapply(show_index, function(s) {
  hist(yrep_newcomb[s, ], breaks = breaks_y, plot = FALSE)
})
ymax <- max(h_obs$density, unlist(lapply(h_rep, function(h) h$density)))

plot_histograms <- function() {
  par(mfrow = c(1, 1), mar = c(4, 4, 2, 1))
  plot(h_obs, freq = FALSE, col = "grey85", border = "white",
       ylim = c(0, 1.05 * ymax), xlab = "Measurement", ylab = "Density",
       main = "Observed and replicated histograms")
  for (h in h_rep) {
    lines(rep(h$breaks, each = 2), c(0, rep(h$density, each = 2), 0),
          col = adjustcolor("blue", alpha.f = 0.25))
  }
  lines(rep(h_obs$breaks, each = 2), c(0, rep(h_obs$density, each = 2), 0),
        col = "black", lwd = 2)
  legend("topleft", c("Observed", "Replicated"), col = c("black", "blue"),
         lty = 1, lwd = c(2, 1), bty = "n")
}
pdf(file.path(fig_dir, "newcomb_histograms.pdf"), width = 10, height = 4.8)
plot_histograms()
dev.off()
plot_histograms()
```

##  Graphical check 2: empirical CDF and predictive envelope

At each measurement value, compare the observed fraction at or below that
value with the fractions in replicated datasets. The shaded region is a
**pointwise 90% predictive envelope**, not a simultaneous confidence band.
A second panel zooms into the lower tail.

```{r newcomb-ecdf, fig.width=10, fig.height=4.8}
grid_y <- seq(min(c(y_newcomb, yrep_newcomb)) - 1,
              max(c(y_newcomb, yrep_newcomb)) + 1, length.out = 400)
F_obs <- ecdf(y_newcomb)(grid_y)
F_rep <- vapply(grid_y, function(t) rowMeans(yrep_newcomb <= t), numeric(S))
F_lower <- apply(F_rep, 2, quantile, probs = 0.05)
F_median <- apply(F_rep, 2, median)
F_upper <- apply(F_rep, 2, quantile, probs = 0.95)

plot_ecdf <- function() {
  par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
  for (tail in c(FALSE, TRUE)) {
    plot(grid_y, F_obs, type = "n", xlab = "Measurement",
         ylab = "Fraction at or below measurement",
         xlim = if (tail) c(-50, 15) else range(grid_y),
         ylim = if (tail) c(0, 0.15) else c(0, 1),
         main = if (tail) "Lower-tail detail" else "Empirical CDF check")
    polygon(c(grid_y, rev(grid_y)), c(F_lower, rev(F_upper)),
            col = "grey85", border = NA)
    lines(grid_y, F_median, col = "blue", lty = 2)
    lines(grid_y, F_obs, type = "s", lwd = 2)
    if (!tail) legend("topleft", c("Observed", "Predictive median", "90% pointwise envelope"),
                     col = c("black", "blue", "grey70"), lty = c(1, 2, 1), bty = "n", cex = 0.8)
  }
}
pdf(file.path(fig_dir, "newcomb_ecdf.pdf"), width = 10, height = 4.8)
plot_ecdf()
dev.off()
plot_ecdf()
```

##  Graphical check 3: observed minimum versus replicated minima

Here the observed statistic is a single fixed number. The horizontal axis
must include it; otherwise the observed line can be invisible.

```{r newcomb-minimum, fig.width=9, fig.height=4.8}
plot_minimum <- function() {
  par(mfrow = c(1, 1), mar = c(4, 4, 2, 1))
  hist(T_min_rep, breaks = 40, col = "grey80", border = "white",
       xlim = extendrange(c(T_min_obs, T_min_rep), f = 0.04), xlab = "Minimum measurement",
       main = "Observed minimum versus replicated minima")
  abline(v = T_min_obs, col = "red", lwd = 3)
  legend("topright", c("Replicated minima", "Observed minimum"),
         fill = c("grey80", NA), border = NA, lty = c(NA, 1),
         col = c(NA, "red"), lwd = c(NA, 3), bty = "n")
}
pdf(file.path(fig_dir, "newcomb_minimum.pdf"), width = 9, height = 4.8)
plot_minimum()
dev.off()
plot_minimum()
```

##  Graphical check 4: paired discrepancy values

Unlike the minimum, $T_2(y,\theta^{(s)})$ changes with the posterior draw.
The left panel compares the two marginal histograms. The right panel
preserves the pairing: one point per posterior draw, with observed
 discrepancy horizontally and replicated discrepancy vertically.
Points above the diagonal contribute to the upper-tail probability.

```{r newcomb-discrepancy, fig.width=10, fig.height=4.8}
breaks_T <- pretty(range(T_extreme_obs, T_extreme_rep), n = 35)
h_Tobs <- hist(T_extreme_obs, breaks = breaks_T, plot = FALSE)
h_Trep <- hist(T_extreme_rep, breaks = breaks_T, plot = FALSE)

plot_discrepancy <- function() {
  par(mfrow = c(1, 2), mar = c(4, 4, 2, 1))
  plot(h_Trep, freq = FALSE, col = adjustcolor("blue", 0.35), border = NA,
       ylim = c(0, max(h_Tobs$density, h_Trep$density) * 1.05),
       xlab = "Largest standardized residual", main = "Discrepancy distributions")
  plot(h_Tobs, freq = FALSE, add = TRUE,
       col = adjustcolor("red", 0.35), border = NA)
  legend("topright", c("Replicated", "Observed"),
         fill = adjustcolor(c("blue", "red"), 0.35), border = NA, bty = "n")
  limits <- range(T_extreme_obs, T_extreme_rep)
  plot(T_extreme_obs, T_extreme_rep, pch = 16, cex = 0.3,
       col = adjustcolor("navy", 0.15), xlim = limits, ylim = limits, asp = 1,
       xlab = "Observed discrepancy", ylab = "Replicated discrepancy",
       main = "Paired comparison: same posterior draw")
  abline(a = 0, b = 1, col = "red", lwd = 2)
}
pdf(file.path(fig_dir, "newcomb_discrepancy.pdf"), width = 10, height = 4.8)
plot_discrepancy()
dev.off()
plot_discrepancy()
```

##  Interpretation

The four displays examine distributional shape, cumulative probabilities,
a targeted extreme statistic, and a parameter-dependent discrepancy.
A fitted Gaussian model can have a stable posterior yet fail these checks.
Predictive failure does not prove that a measurement is erroneous.

Newcomb has no covariates or groups in this model. Residuals against $x$
and subgroup checks are therefore reserved for the regression or deer case.


#  Sequential binary data: dependence missed by an iid Bernoulli model

The observed sequence is adapted from the model-checking material. The likelihood can fit the total number of ones while missing serial clustering.

```{r binary-data}
y_binary <- c(1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0)
n_binary <- length(y_binary)
sum(y_binary)
```

Under a uniform prior, the posterior is

\[
\theta\mid y\sim \operatorname{Beta}(1+\sum y_i,1+n-\sum y_i).
\]

Use the number of switches

\[
T(y)=\sum_{i=2}^n I(y_i\neq y_{i-1})
\]

as the discrepancy.

```{r binary-ppc}
S_binary <- 10000
theta_binary <- rbeta(S_binary,
                      1 + sum(y_binary),
                      1 + n_binary - sum(y_binary))

yrep_binary <- sapply(theta_binary, function(th) {
  rbinom(n_binary, size = 1, prob = th)
})
yrep_binary <- t(yrep_binary)

switches <- function(y) sum(y[-1] != y[-length(y)])
T_switch_obs <- switches(y_binary)
T_switch_rep <- apply(yrep_binary, 1, switches)

pB_switch_lower <- mean(T_switch_rep <= T_switch_obs)
c(observed_switches = T_switch_obs,
  lower_tail_pB = pB_switch_lower)
```

```{r binary-ppc-plot, fig.width=8, fig.height=4}
hist(T_switch_rep, breaks = seq(-0.5, n_binary - 0.5, by = 1),
     col = "grey80", border = "white",
     xlab = "Number of switches", main = "iid Bernoulli replications")
abline(v = T_switch_obs, col = 2, lwd = 3)
```
# Deer example

Place `deerecervi.csv` beside this file. Expected columns are:

- `deerecervi.txt`: binary parasite presence indicator;
- `Length`: host length;
- `Sex`: host sex;
- `Farm`: farm identifier.

No synthetic deer data are substituted. If the file is absent, the fitting and predictive-check chunks are skipped.

```{r deer-load}
deer_file <- "deerecervi.txt"
have_deer <- file.exists(deer_file)

if (have_deer) {
  deer <- read.table(deer_file ,header = TRUE, row.names = 1)
  names(deer)
  head(deer)
  required <- c("Ecervi.01", "Length", "Sex", "Farm")
  stopifnot(all(required %in% names(deer)))

  keep <- complete.cases(deer[, required])
  message(sum(!keep), " incomplete observations removed.")
  deer <- deer[keep, , drop = FALSE]
  stopifnot(nrow(deer) > 1, is.numeric(deer$Length), sd(deer$Length) > 0)

  deer$Farm <- droplevels(factor(deer$Farm))
  deer$Sex <- droplevels(factor(deer$Sex))
  deer$Length_std <- as.numeric(scale(deer$Length))

  y <- deer$Ecervi.01
  stopifnot(is.numeric(y), all(y %in% c(0, 1)), nlevels(deer$Sex) >= 2)
  X <- model.matrix(~ Length_std + Sex, data = deer)
  farm <- as.integer(deer$Farm)
  n_obs <- length(y)
  K <- ncol(X)
  J <- nlevels(deer$Farm)
  stopifnot(J >= 2)
} else {
  message("DeerEcervi.csv not found; deer fitting and predictive checks are skipped.")
}
```

## Model and priors

Let $y_i$ indicate parasite presence and let $x_i$ contain standardized length and sex. We use
\[
Y_i\mid\theta,x_i\sim\operatorname{Bernoulli}(p_i),
\qquad
\operatorname{logit}(p_i)=x_i^T\beta+a_{\operatorname{Farm}(i)}.
\]
The priors are
\[
\beta_j\sim N(0,2.5^2),\qquad a_j\mid\tau\sim N(0,\tau^2),
\qquad \tau\sim\operatorname{Exponential}(1).
\]
Here the intercept is included in $\beta$. These are explicit normal priors, rather than relying on package defaults.

For computation, write $a_j=\tau u_j$, where $u_j\sim N(0,1)$, and sample $\eta=\log\tau$. This is a non-centred representation of the same hierarchical model. The sampled parameter vector is $\theta=(\beta,u,\eta)$.

```{r deer-target, eval=have_deer}
parameter_names <- c(colnames(X), paste0("u_", levels(deer$Farm)), "log_tau")

softplus <- function(z) {
  pmax(z, 0) + log1p(exp(-abs(z)))
}

log_posterior_deer <- function(theta) {
  beta <- theta[seq_len(K)]
  u <- theta[K + seq_len(J)]
  eta <- theta[K + J + 1]
  tau <- exp(eta)
  if (!is.finite(tau)) return(-Inf)

  linear_predictor <- as.numeric(X %*% beta) + tau * u[farm]
  if (any(!is.finite(linear_predictor))) return(-Inf)

  log_likelihood <- sum(y * linear_predictor - softplus(linear_predictor))
  log_prior <- sum(dnorm(beta, 0, 2.5, log = TRUE)) +
    sum(dnorm(u, 0, 1, log = TRUE)) +
    dexp(tau, rate = 1, log = TRUE) + eta

  # + eta is the Jacobian for tau = exp(eta).
  # The standard-normal prior is specified directly for u.
  log_likelihood + log_prior
}
```

## Model fitting with component-wise Metropolis

One sweep proposes each parameter in turn, with a separate acceptance decision for each parameter. Four independent chains use dispersed starting points. They run sequentially here; simultaneous execution is not needed for the diagnostic comparison.

Proposal scales are adjusted every 100 sweeps during warm-up. The target acceptance of 0.44 is a tuning heuristic for scalar random-walk updates, not a convergence criterion. After warm-up, proposal scales are fixed.

```{r deer-sampler, eval=have_deer}
metropolis_deer <- function(B, warmup, init, proposal_sd) {
  d <- length(init)
  draws <- matrix(NA_real_, B, d)
  current <- init
  current_lp <- log_posterior_deer(current)
  stopifnot(is.finite(current_lp), warmup < B)

  accepted_window <- numeric(d)
  accepted_retained <- numeric(d)
  adaptation_step <- 0

  for (b in seq_len(B)) {
    for (j in seq_len(d)) {
      proposal <- current
      proposal[j] <- current[j] + rnorm(1, sd = proposal_sd[j])
      proposal_lp <- log_posterior_deer(proposal)

      if (is.finite(proposal_lp) &&
          log(runif(1)) < proposal_lp - current_lp) {
        current <- proposal
        current_lp <- proposal_lp
        accepted_window[j] <- accepted_window[j] + 1
        if (b > warmup) accepted_retained[j] <- accepted_retained[j] + 1
      }
    }
    draws[b, ] <- current
    if (b %% 500 == 0) {
       message("Completed sweep ", b, " of ", B)
    }

    if (b <= warmup && b %% 100 == 0) {
      adaptation_step <- adaptation_step + 1
      rate <- accepted_window / 100
      gain <- 1 / sqrt(adaptation_step)
      proposal_sd <- proposal_sd * exp(gain * (rate - 0.44))
      proposal_sd <- pmin(pmax(proposal_sd, 0.001), 3)
      accepted_window[] <- 0
    }
  }
  colnames(draws) <- parameter_names
  list(draws = draws, acceptance = accepted_retained / (B - warmup),
       proposal_sd = proposal_sd)
}
```

```{r deer-fit, eval=have_deer}
set.seed(4021)
B <- 20000
warmup <- 5000
intercept_start <- qlogis((sum(y) + 0.5) / (n_obs + 1))

starts <- lapply(seq_len(4), function(m) {
  beta <- rnorm(K, 0, 0.5)
  beta[1] <- intercept_start + c(-2, -1, 1, 2)[m]
  c(beta, rnorm(J, 0, 0.5), log(c(0.2, 0.5, 1, 2)[m]))
})
proposal_sd <- c(rep(0.15, K), rep(0.30, J), 0.15)
fit_deer <- lapply(starts, function(init) {
  metropolis_deer(B, warmup, init, proposal_sd)
})
acceptance <- sapply(fit_deer, function(z) z$acceptance)
rownames(acceptance) <- parameter_names
acceptance

post_chains <- lapply(fit_deer, function(z) {
  z$draws[(warmup + 1):B, , drop = FALSE]
})
```

## Algorithm checks first

Inspect the complete traces before interpreting the retained output. The diagnostics below use classical split-$\widehat R$ and a simple ACF-based ESS approximation. They are not the modern rank-normalized diagnostic or bulk/tail ESS.

ESS is computed within each chain and summed, not calculated from a concatenated series. This interpretation is useful only when chains plausibly explore the same stationary distribution. A fixed lag limit can miss slowly decaying autocorrelation; compare estimates with larger lag limits when needed.

```{r deer-diagnostic-functions, eval=have_deer}
rhat_split <- function(draw_matrix) {
  half <- floor(nrow(draw_matrix) / 2)
  split <- cbind(draw_matrix[seq_len(half), , drop = FALSE],
                 draw_matrix[(nrow(draw_matrix) - half + 1):nrow(draw_matrix),
                             , drop = FALSE])
  N <- nrow(split)
  W <- mean(apply(split, 2, var))
  B_between <- N * var(colMeans(split))
  sqrt((((N - 1) / N) * W + B_between / N) / W)
}

ess_from_acf <- function(z, lag_max = 500) {
  rho <- as.numeric(acf(z, lag.max = min(lag_max, length(z) - 1),
                        plot = FALSE)$acf)[-1]
  first_negative <- which(rho < 0)[1]
  if (!is.na(first_negative)) rho <- rho[seq_len(first_negative - 1)]
  length(z) / (1 + 2 * sum(rho))
}

to_reported_parameters <- function(draws) {
  beta <- draws[, seq_len(K), drop = FALSE]
  tau <- exp(draws[, K + J + 1])
  a <- sweep(draws[, K + seq_len(J), drop = FALSE], 1, tau, "*")
  out <- cbind(beta, a, tau)
  colnames(out) <- c(colnames(X), paste0("a_", levels(deer$Farm)), "tau")
  out
}
```

```{r deer-diagnostics, eval=have_deer}
reported_chains <- lapply(post_chains, to_reported_parameters)
reported_draws <- do.call(rbind, reported_chains)

diagnostics <- do.call(rbind, lapply(seq_len(ncol(reported_draws)), function(j) {
  chain_matrix <- sapply(reported_chains, function(z) z[, j])
  ess <- sum(apply(chain_matrix, 2, ess_from_acf))
  c(mean = mean(chain_matrix), sd = sd(as.numeric(chain_matrix)),
    Rhat = rhat_split(chain_matrix), ESS = ess,
    MCSE_mean = sd(as.numeric(chain_matrix)) / sqrt(ess))
}))
rownames(diagnostics) <- colnames(reported_draws)
diagnostics
```

```{r deer-traces, eval=have_deer, fig.width=10, fig.height=7}
# Separate plots avoid squeezing many parameters into one figure.
for (j in c(seq_len(K), K + J + 1)) {
  par(mfrow = c(1, 1), mar = c(4, 4, 2, 1))
  values <- sapply(fit_deer, function(z) z$draws[, j])
  if (j == K + J + 1) values <- exp(values)
  matplot(values, type = "l", lty = 1, col = 1:4, xlab = "Sweep",
          ylab = if (j == K + J + 1) "tau" else parameter_names[j])
  abline(v = warmup, lty = 2)
}
```

```{r deer-acf, eval=have_deer, fig.width=9, fig.height=4}
par(mfrow = c(1, 2))
acf(reported_chains[[1]][, 1], lag.max = 100, main = "Intercept: chain 1")
acf(reported_chains[[1]][, "tau"], lag.max = 100, main = "Farm SD: chain 1")
```

**Interpret predictive checks only after inspecting these diagnostics.** The run length and warm-up length are starting choices, not guarantees. If chains disagree, drift, or have low ESS, improve the computation first. This sampler has not been tuned on your dataset in this environment.

## Posterior predictive replications

For each retained posterior draw, calculate fitted probabilities and generate binary responses:
\[
p_i^{(s)}=\operatorname{logit}^{-1}
\{x_i^T\beta^{(s)}+\tau^{(s)}u_{\operatorname{Farm}(i)}^{(s)}\},
\qquad
Y_i^{\mathrm{rep},(s)}\sim\operatorname{Bernoulli}(p_i^{(s)}).
\]
These are replications for the **existing farms**, using their posterior farm effects and the observed covariates. A genuinely new farm requires a new draw from the farm-effect distribution.

```{r deer-yrep, eval=have_deer}
set.seed(4022)
posterior_draws <- do.call(rbind, post_chains)
S <- min(2000, nrow(posterior_draws))
selected <- sample(seq_len(nrow(posterior_draws)), S)
p_draws <- matrix(NA_real_, S, n_obs)
yrep_deer <- matrix(NA_integer_, S, n_obs)

for (s in seq_len(S)) {
  theta <- posterior_draws[selected[s], ]
  beta <- theta[seq_len(K)]
  u <- theta[K + seq_len(J)]
  tau <- exp(theta[K + J + 1])
  p_draws[s, ] <- plogis(as.numeric(X %*% beta) + tau * u[farm])
  yrep_deer[s, ] <- rbinom(n_obs, 1, p_draws[s, ])
}
```

## Overall fraction with parasites

The statistic
\[
T(y)=\frac1n\sum_i y_i
\]
checks the overall fraction with parasites. It may be reproduced even when the model misses between-farm structure.

```{r deer-fraction, eval=have_deer}
T_fraction_obs <- mean(y)
T_fraction_rep <- rowMeans(yrep_deer)
mean(T_fraction_rep >= T_fraction_obs)
```

## Between-farm variation and extreme farm

Calculate the fraction with parasites in each farm. Compare its standard deviation and maximum between observed and replicated datasets. Keep the observed farm sizes fixed in every replication.

```{r deer-farm-statistics, eval=have_deer}
farm_index <- split(seq_len(n_obs), deer$Farm)
farm_fraction <- function(response) {
  vapply(farm_index, function(ind) mean(response[ind]), numeric(1))
}
observed_farm_fraction <- farm_fraction(y)
T_farm_sd_obs <- sd(observed_farm_fraction)
T_farm_max_obs <- max(observed_farm_fraction)
T_farm_sd_rep <- apply(yrep_deer, 1, function(response) sd(farm_fraction(response)))
T_farm_max_rep <- apply(yrep_deer, 1, function(response) max(farm_fraction(response)))

c(pB_fraction = mean(T_fraction_rep >= T_fraction_obs),
  pB_farm_sd = mean(T_farm_sd_rep >= T_farm_sd_obs),
  pB_farm_max = mean(T_farm_max_rep >= T_farm_max_obs))
```

These use upper-tail probabilities. A small value means the observed statistic is unusually large relative to replications; a large value indicates the opposite direction. Discrete statistics can have many ties, so the two inclusive tails need not sum to one.

```{r deer-check-plots, eval=have_deer, fig.width=11, fig.height=4}
par(mfrow = c(1, 3), mar = c(4, 4, 2, 1))
hist(T_fraction_rep, breaks = 30,
     xlim = extendrange(c(T_fraction_rep, T_fraction_obs)),
     col = "grey80", border = "white", main = "Overall fraction",
     xlab = "Replicated fraction")
abline(v = T_fraction_obs, col = "red", lwd = 3)
hist(T_farm_sd_rep, breaks = 30,
     xlim = extendrange(c(T_farm_sd_rep, T_farm_sd_obs)),
     col = "grey80", border = "white", main = "Between-farm variation",
     xlab = "SD of farm fractions")
abline(v = T_farm_sd_obs, col = "red", lwd = 3)
hist(T_farm_max_rep, breaks = 30,
     xlim = extendrange(c(T_farm_max_rep, T_farm_max_obs)),
     col = "grey80", border = "white", main = "Extreme farm",
     xlab = "Largest farm fraction")
abline(v = T_farm_max_obs, col = "red", lwd = 3)
```

## Calibration by fitted-risk bins

Group observations by posterior mean fitted probability. Compare the observed fraction in each bin with replicated fractions. The intervals are pointwise 90% predictive intervals for bin fractions, conditional on this fitted grouping.

This is an **in-sample predictive check**, not evidence of out-of-sample predictive performance.

```{r deer-calibration, eval=have_deer, fig.width=7, fig.height=6}
p_hat <- colMeans(p_draws)
bin_breaks <- unique(as.numeric(quantile(p_hat, seq(0, 1, length.out = 6))))
if (length(bin_breaks) >= 2) {
  bin <- cut(p_hat, breaks = bin_breaks, include.lowest = TRUE)
} else {
  bin <- factor(rep("All observations", n_obs))
}
bin_index <- split(seq_len(n_obs), bin, drop = TRUE)
predicted_by_bin <- vapply(bin_index, function(ind) mean(p_hat[ind]), numeric(1))
observed_by_bin <- vapply(bin_index, function(ind) mean(y[ind]), numeric(1))
replicated_by_bin <- vapply(bin_index, function(ind) {
  rowMeans(yrep_deer[, ind, drop = FALSE])
}, numeric(S))
lower <- apply(replicated_by_bin, 2, quantile, probs = 0.05)
upper <- apply(replicated_by_bin, 2, quantile, probs = 0.95)

par(mfrow = c(1, 1))
plot(predicted_by_bin, observed_by_bin, xlim = c(0, 1), ylim = c(0, 1), pch = 16,
     xlab = "Posterior mean fitted probability",
     ylab = "Observed fraction with parasites",
     main = "Calibration: 90% predictive intervals")
abline(0, 1, lty = 2)
arrows(predicted_by_bin, lower, predicted_by_bin, upper,
       angle = 90, code = 3, length = 0.05, col = "blue")
points(predicted_by_bin, observed_by_bin, pch = 16)
```

# Bayesian R-squared

For each posterior draw,
\[
R_s^2=\frac{V_{\mathrm{fit}}^{(s)}}
{V_{\mathrm{fit}}^{(s)}+V_{\mathrm{res}}^{(s)}}.
\]
The fitted variation is the sample variance across conditional fitted means. Residual variation is the average conditional outcome variance. This summarizes explained variation; it does not replace predictive checks.

## Gaussian regression helper

```{r bayes-r2-gaussian}
bayes_R2_gaussian <- function(mu_draws, sigma_draws) {
  stopifnot(nrow(mu_draws) == length(sigma_draws))
  v_fit <- apply(mu_draws, 1, var)
  v_res <- sigma_draws^2
  v_fit / (v_fit + v_res)
}
```

## Logistic regression helper

```{r bayes-r2-logistic}
bayes_R2_logistic <- function(p_draws) {
  v_fit <- apply(p_draws, 1, var)
  v_res <- rowMeans(p_draws * (1 - p_draws))
  v_fit / (v_fit + v_res)
}
```

For this hierarchical model, fitted probabilities include the existing farms' posterior effects. Consequently, this R-squared describes fitted variation for the observed design and farms, not performance for new farms.

```{r deer-r2, eval=have_deer, fig.width=7, fig.height=4}
R2_deer <- bayes_R2_logistic(p_draws)
quantile(R2_deer, c(0.025, 0.25, 0.5, 0.75, 0.975))
hist(R2_deer, breaks = 40, col = "grey80", border = "white",
     xlab = expression(R^2), main = "Posterior Bayesian R-squared")
```

# Optional deer count extension

If the original count response is available, useful **test statistics** are
\[
T_0(y)=\sum_i I(y_i=0),\qquad T_{\max}(y)=\max_i y_i,
\qquad T_D(y)=\frac{\operatorname{Var}_i(y_i)}{\operatorname{Mean}_i(y_i)}.
\]

```{r count-statistics}
count_statistics <- function(y) {
  c(zeros = sum(y == 0), maximum = max(y),
    dispersion = if (mean(y) > 0) var(y) / mean(y) else NA_real_)
}
```

The binary model above cannot generate parasite counts. A separate count model must be fitted before using these statistics in predictive checks.

Compare the statistics with replicated counts under that model. Excess variation may motivate a negative-binomial model; excess zeroes may motivate a zero-inflated or hurdle model. Covariate and farm heterogeneity can also generate excess marginal variation or zeroes, so these checks do not uniquely identify the cause.

# Practical notes

- All computation and plots use base R; no brms, Stan, posterior, bayesplot, or KernSmooth installation is required.
- Warm-up adaptation ends before retained sampling.
- Check the actual farm effects and the quantities of interest, not only the computational parameters.
- Predictive checks are meaningful only after the computation is sufficiently reliable.
- No deer data were available when preparing this notebook, so the sampler has not been executed or tuned on the actual dataset.

# Consolidated diagnostic output

```{r diagnostic-summary-table}
diagnostic_summary <- diagnostics_table
diagnostic_summary$proposal_sd <- sprintf("%.2f", diagnostic_summary$proposal_sd)
diagnostic_summary$acceptance <- sprintf("%.2f", diagnostic_summary$acceptance)
diagnostic_summary$lag1_acf <- sprintf("%.2f", diagnostic_summary$lag1_acf)
diagnostic_summary$ESS <- round(diagnostic_summary$ESS)
diagnostic_summary$MCSE <- sprintf("%.3f", diagnostic_summary$MCSE)
diagnostic_summary$Rhat <- sprintf("%.3f", diagnostic_summary$Rhat)
diagnostic_summary
```

Suggested discussion questions:

1. Which proposal scale is preferable, and why?
2. Why can the chain with the highest acceptance rate have the lowest ESS?
3. What does R-hat assess that ESS does not?
4. Suppose chain diagnostics are satisfactory but a posterior predictive p-value is 0.97. Is this an algorithmic or model-level warning?
5. What aspect of the model is assessed by the chosen discrepancy?
6. Why would running the same chain longer not remove a posterior predictive mismatch?

# 17. Final checklist

## Algorithmic quality

- multiple dispersed chains;
- warm-up separated from retained sampling;
- trace plots;
- split/rank-normalized R-hat;
- bulk and tail ESS;
- MCSE for reported estimands;
- algorithm-specific warnings.

## Statistical model quality

- posterior predictive replications;
- graphical comparisons;
- targeted discrepancies;
- posterior predictive p-values with a stated tail convention;
- Bayesian R-squared as a summary, not a universal certificate;
- model expansion and refitting when relevant features are missed.
