# Infection rates from pooled vector samples
# https://tidyecology.com/posts/pooled-testing-of-vectors/
#
# 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-01

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- design ----
n_trap   <- 20                  # trap-nights in the fortnight
per_trap <- 50                  # females tested per trap-night
n_ins    <- n_trap * per_trap
m_set    <- c(5, 10, 25, 50)    # pool sizes, all divide per_trap
p_set    <- c(0.005, 0.01, 0.03)
rho_set  <- c(0, 0.01, 0.02, 0.05, 0.1)
n_rep    <- 2000                # datasets per cell
z_crit   <- qnorm(0.975)

draw_night_prev <- function(n_rep, p, rho) {
  if (rho == 0) return(matrix(p, n_trap, n_rep))
  s <- 1 / rho - 1
  matrix(rbeta(n_trap * n_rep, p * s, (1 - p) * s), n_trap, n_rep)
}

# pool MLE with a Wald (delta method) and a Wilson score interval, equal pools
pool_fit <- function(x, n_pool, m) {
  th <- x / n_pool
  p_hat <- 1 - (1 - th)^(1 / m)
  inner <- x > 0 & x < n_pool
  se <- ifelse(inner, sqrt(th * (1 - th) / n_pool) / m * (1 - th)^(1 / m - 1), 0)
  half <- z_crit * sqrt(th * (1 - th) / n_pool + z_crit^2 / (4 * n_pool^2))
  centre <- th + z_crit^2 / (2 * n_pool)
  w_lo <- (centre - half) / (1 + z_crit^2 / n_pool)
  w_hi <- (centre + half) / (1 + z_crit^2 / n_pool)
  list(p_hat = p_hat, wald_lo = p_hat - z_crit * se, wald_hi = p_hat + z_crit * se,
       score_lo = 1 - (1 - w_lo)^(1 / m), score_hi = 1 - (1 - w_hi)^(1 / m),
       all_pos = x == n_pool, all_neg = x == 0)
}

## ---- simulate ----
sim_cell <- function(p, rho, m, n_rep) {
  pj <- draw_night_prev(n_rep, p, rho)
  k <- per_trap / m; n_pool <- n_trap * k
  x_night <- matrix(rbinom(n_trap * n_rep, k, 1 - (1 - pj)^m), n_trap)
  x_within <- colSums(x_night)
  y_total <- colSums(matrix(rbinom(n_trap * n_rep, per_trap, pj), n_trap))
  x_random <- vapply(y_total, function(yy) {
    if (yy == 0) return(0L)
    length(unique((sample.int(n_ins, yy) - 1) %/% m))
  }, 1L)
  list(pj = pj, x_night = x_night, n_pool = n_pool, k = k, y_total = y_total,
       within = pool_fit(x_within, n_pool, m), random = pool_fit(x_random, n_pool, m),
       mir = x_within / n_ins)
}

summarise_cell <- function(s, p) {
  covers <- function(lo, hi, target) mean(lo <= target & hi >= target)
  w <- s$within; r <- s$random; nights <- colMeans(s$pj)
  c(bias_mle = mean(w$p_hat) / p - 1,
    bias_mle_def = mean(w$p_hat[!w$all_pos]) / p - 1,
    bias_mir = mean(s$mir) / p - 1,
    bias_rand = mean(r$p_hat[!r$all_pos]) / p - 1,
    wald_w = covers(w$wald_lo, w$wald_hi, p), score_w = covers(w$score_lo, w$score_hi, p),
    wald_r = covers(r$wald_lo, r$wald_hi, p), score_r = covers(r$score_lo, r$score_hi, p),
    wald_r_nights = covers(r$wald_lo, r$wald_hi, nights),
    wald_r_catch = covers(r$wald_lo, r$wald_hi, s$y_total / n_ins),
    all_pos = mean(w$all_pos), all_neg = mean(w$all_neg))
}

grid_cells <- expand.grid(p = p_set, rho = rho_set, m = m_set)
set.seed(1962)
grid_res <- do.call(rbind, lapply(seq_len(nrow(grid_cells)), function(i) {
  g <- grid_cells[i, ]
  summarise_cell(sim_cell(g$p, g$rho, g$m, n_rep), g$p)
}))
grid_tab <- cbind(grid_cells, grid_res)
cell <- function(p, rho, m, col) grid_tab[grid_tab$p == p & grid_tab$rho == rho & grid_tab$m == m, col]
mcse_95 <- sqrt(0.95 * 0.05 / n_rep)

## ---- mir ----
mir_closed <- function(p, m) (1 - (1 - p)^m) / m / p - 1
mir_gap <- max(abs(vapply(seq_len(nrow(grid_tab)), function(i)
  if (grid_tab$rho[i] == 0) grid_tab$bias_mir[i] - mir_closed(grid_tab$p[i], grid_tab$m[i]) else 0, 0)))
homog <- grid_tab[grid_tab$rho == 0, ]
mle_homog_max <- max(abs(homog$bias_mle_def))

## ---- fig-mir ----
mir_lines <- expand.grid(m = seq(1, 50, by = 0.5), p = p_set)
mir_lines$bias <- mir_closed(mir_lines$p, mir_lines$m)
p_lab <- function(p) factor(sprintf("p = %s", p), levels = sprintf("p = %s", p_set))
mir_lines$prev <- p_lab(mir_lines$p); homog$prev <- p_lab(homog$p)
ggplot() +
  geom_hline(yintercept = 0, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_line(data = mir_lines, aes(m, bias, colour = prev), linewidth = 0.9) +
  geom_point(data = homog, aes(m, bias_mir, colour = prev), size = 2.6) +
  geom_point(data = homog, aes(m, bias_mle_def, colour = prev), shape = 21,
             fill = te_paper, size = 2.6, stroke = 0.9) +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust), name = NULL) +
  scale_x_continuous(breaks = m_set) +
  labs(x = "insects per pool", y = "relative bias",
       title = "The MIR falls behind as pools grow",
       subtitle = "filled: MIR, open: pool MLE (all-positive datasets left out)") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- bias ----
pool_limit_bias <- function(p, rho, m) {
  if (rho == 0) return(0)
  s <- 1 / rho - 1; a <- p * s; b <- (1 - p) * s
  theta <- 1 - exp(lbeta(a, b + m) - lbeta(a, b))
  (1 - (1 - theta)^(1 / m)) / p - 1
}
grid_tab$bias_closed <- mapply(pool_limit_bias, grid_tab$p, grid_tab$rho, grid_tab$m)
chk <- grid_tab[grid_tab$rho > 0 & grid_tab$p >= 0.01, ]
bias_gap <- max(abs(chk$bias_mle_def - chk$bias_closed))
gap_at <- chk[which.max(abs(chk$bias_mle_def - chk$bias_closed)), ]
chk5 <- grid_tab[grid_tab$rho > 0 & grid_tab$p == 0.005, ]
bias_gap5 <- max(abs(chk5$bias_mle_def - chk5$bias_closed))
rand_bias_max <- max(abs(grid_tab$bias_rand[grid_tab$p >= 0.01]))
rand_bias_max_m25 <- max(abs(grid_tab$bias_rand[grid_tab$p >= 0.01 & grid_tab$m <= 25]))
s_02 <- 1 / 0.02 - 1
share_quiet <- pbeta(0.001, 0.01 * s_02, 0.99 * s_02)
share_hot <- 1 - pbeta(0.03, 0.01 * s_02, 0.99 * s_02)

## ---- fig-bias ----
het <- grid_tab[grid_tab$rho > 0 & grid_tab$p >= 0.01, ]
het$prev <- p_lab(het$p)
het$rho_lab <- factor(sprintf("rho = %s", het$rho), levels = sprintf("rho = %s", rho_set[-1]))
bias_lines <- expand.grid(m = 1:50, p = c(0.01, 0.03), rho = rho_set[-1])
bias_lines$bias <- mapply(pool_limit_bias, bias_lines$p, bias_lines$rho, bias_lines$m)
bias_lines$prev <- p_lab(bias_lines$p)
bias_lines$rho_lab <- factor(sprintf("rho = %s", bias_lines$rho), levels = levels(het$rho_lab))
ggplot() +
  geom_hline(yintercept = 0, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_line(data = bias_lines, aes(m, bias, colour = rho_lab), linewidth = 0.8) +
  geom_point(data = het, aes(m, bias_mle_def, colour = rho_lab), size = 2.4) +
  facet_wrap(~ prev) +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust, te_ink), name = NULL) +
  scale_x_continuous(breaks = m_set) +
  labs(x = "insects per pool", y = "relative bias of the pool MLE",
       title = "Within-night pools pull the estimate down",
       subtitle = "lines: 1 - B(a, b + m) / B(a, b) limit, points: 2000 fortnights") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- coverage ----
cov_w <- grid_tab[grid_tab$p >= 0.01, ]
wald_homog <- range(cov_w$wald_w[cov_w$rho == 0])
score_homog <- range(cov_w$score_w[cov_w$rho == 0])
neg_max <- max(grid_tab$all_neg[grid_tab$p == 0.005 & grid_tab$rho == 0.1])
neg_homog <- max(grid_tab$all_neg[grid_tab$p == 0.005 & grid_tab$rho == 0])

## ---- fig-coverage ----
cov_long <- rbind(
  data.frame(cov_w[, c("p", "rho", "m")], interval = "Wald", coverage = cov_w$wald_w),
  data.frame(cov_w[, c("p", "rho", "m")], interval = "score", coverage = cov_w$score_w))
cov_long$prev <- p_lab(cov_long$p)
cov_long$interval <- factor(cov_long$interval, levels = c("Wald", "score"))
cov_long$rho_lab <- factor(sprintf("rho = %s", cov_long$rho), levels = sprintf("rho = %s", rho_set))
ggplot(cov_long, aes(m, coverage, colour = rho_lab, linetype = rho_lab)) +
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = 0.95 - 2 * mcse_95,
           ymax = 0.95 + 2 * mcse_95, fill = te_line, alpha = 0.8) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  facet_grid(interval ~ prev) +
  scale_colour_manual(values = c(te_body, te_gold, te_forest, te_rust, te_ink), name = NULL) +
  scale_linetype_manual(values = c("dashed", "solid", "solid", "solid", "solid"), name = NULL) +
  scale_x_continuous(breaks = m_set) +
  scale_y_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 1), linetype = guide_legend(nrow = 1)) +
  labs(x = "insects per pool", y = "coverage of the true rate",
       title = "Coverage falls as nights differ and pools grow",
       subtitle = "within-night pools; rho = 0 dashed") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- randomised ----
wald_predicted <- function(p, rho, m) {
  k <- per_trap / m; n_pool <- n_trap * k
  theta <- 1 - (1 - p)^m
  v_pool <- theta * (1 - theta) / n_pool / m^2 * (1 - theta)^(2 / m - 2)
  v_night <- p * (1 - p) * rho / n_trap
  2 * pnorm(z_crit * sqrt(v_pool / (v_pool + v_night))) - 1
}
grid_tab$wald_pred <- mapply(wald_predicted, grid_tab$p, grid_tab$rho, grid_tab$m)
rnd <- grid_tab[grid_tab$p >= 0.01 & grid_tab$all_pos < 0.001, ]
nights_range <- range(rnd$wald_r_nights[rnd$p == 0.03])
nights_range01 <- range(rnd$wald_r_nights[rnd$p == 0.01])
pred_gap <- max(abs(rnd$wald_r - rnd$wald_pred)[rnd$p == 0.03])
catch_range <- range(rnd$wald_r_catch)
wr01 <- sapply(m_set, function(mm) cell(0.01, 0.02, mm, "wald_r"))
wr03 <- sapply(m_set, function(mm) cell(0.03, 0.02, mm, "wald_r"))
wp03 <- sapply(m_set, function(mm) cell(0.03, 0.02, mm, "wald_pred"))

## ---- bootstrap ----
n_rep_boot <- 1000
n_boot <- 500
boot_cell <- function(p, rho, m) {
  s <- sim_cell(p, rho, m, n_rep_boot)
  hits <- vapply(seq_len(n_rep_boot), function(r) {
    idx <- matrix(sample.int(n_trap, n_trap * n_boot, replace = TRUE), n_trap)
    x_b <- colSums(matrix(s$x_night[idx, r], n_trap))
    q <- quantile(1 - (1 - x_b / s$n_pool)^(1 / m), c(0.025, 0.975), names = FALSE)
    q[1] <= p && q[2] >= p
  }, TRUE)
  c(boot = mean(hits), wald = mean(s$within$wald_lo <= p & s$within$wald_hi >= p))
}
boot_cells <- expand.grid(p = c(0.01, 0.03), rho = c(0, 0.02, 0.05), m = m_set)
set.seed(2003)
boot_tab <- cbind(boot_cells, t(mapply(boot_cell, boot_cells$p, boot_cells$rho, boot_cells$m)))
bcell <- function(p, rho, m, col = "boot") boot_tab[boot_tab$p == p & boot_tab$rho == rho & boot_tab$m == m, col]
boot_homog <- range(boot_tab$boot[boot_tab$rho == 0])
mcse_boot <- sqrt(0.95 * 0.05 / n_rep_boot)
pop_cov <- grid_tab[grid_tab$rho > 0 & grid_tab$p >= 0.01, ]
pop_best <- max(unlist(pop_cov[, c("wald_w", "score_w", "wald_r", "score_r")]), boot_tab$boot[boot_tab$rho > 0])
boot_vs_rand_se <- sqrt(bcell(0.03, 0.02, 5) * (1 - bcell(0.03, 0.02, 5)) / n_rep_boot +
  cell(0.03, 0.02, 25, "wald_r") * (1 - cell(0.03, 0.02, 25, "wald_r")) / n_rep)

## ---- fig-repair ----
rep_rows <- lapply(c(0, 0.02, 0.05), function(rr) {
  g <- grid_tab[grid_tab$p == 0.03 & grid_tab$rho == rr, ]
  b <- boot_tab[boot_tab$p == 0.03 & boot_tab$rho == rr, ]
  rbind(data.frame(rho = rr, m = g$m, analysis = "within-night Wald", coverage = g$wald_w),
        data.frame(rho = rr, m = b$m, analysis = "trap-night bootstrap", coverage = b$boot),
        data.frame(rho = rr, m = g$m, analysis = "randomised Wald", coverage = g$wald_r),
        data.frame(rho = rr, m = g$m, analysis = "randomised, predicted", coverage = g$wald_pred))
})
rep_df <- do.call(rbind, rep_rows)
rep_df$analysis <- factor(rep_df$analysis, levels = c("within-night Wald", "trap-night bootstrap",
                                                      "randomised Wald", "randomised, predicted"))
rep_df$rho_lab <- factor(sprintf("rho = %s", rep_df$rho), levels = sprintf("rho = %s", c(0, 0.02, 0.05)))
ggplot(rep_df, aes(m, coverage, colour = analysis, linetype = analysis)) +
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = 0.95 - 2 * mcse_95,
           ymax = 0.95 + 2 * mcse_95, fill = te_line, alpha = 0.8) +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  facet_wrap(~ rho_lab) +
  scale_colour_manual(values = c(te_rust, te_forest, te_gold, te_ink), name = NULL) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "dashed"), name = NULL) +
  scale_x_continuous(breaks = m_set) +
  scale_y_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "insects per pool", y = "coverage of the population rate",
       title = "No analysis of pooled data restores 0.95 once nights differ",
       subtitle = "p = 0.03; grey band: 0.95 plus or minus two Monte Carlo standard errors") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- logitnormal ----
ln_moments <- function(par) {
  e1 <- integrate(function(z) plogis(par[1] + exp(par[2]) * z) * dnorm(z),
                  -Inf, Inf, rel.tol = 1e-10)$value
  e2 <- integrate(function(z) plogis(par[1] + exp(par[2]) * z)^2 * dnorm(z),
                  -Inf, Inf, rel.tol = 1e-10)$value
  c(e1, e2 - e1^2)
}
p_ln <- 0.01; rho_ln <- 0.02
target <- c(p_ln, p_ln * (1 - p_ln) * rho_ln)
ln_fit <- optim(c(qlogis(p_ln), 0), function(par) sum(((ln_moments(par) - target) / target)^2),
                control = list(reltol = 1e-12, maxit = 5000))
ln_mu <- ln_fit$par[1]; ln_sd <- exp(ln_fit$par[2])
ln_match <- max(abs(ln_moments(ln_fit$par) / target - 1))
ln_limit <- function(m) {
  theta <- 1 - integrate(function(z) (1 - plogis(ln_mu + ln_sd * z))^m * dnorm(z),
                         -Inf, Inf, rel.tol = 1e-10)$value
  (1 - (1 - theta)^(1 / m)) / p_ln - 1
}
set.seed(1996)
ln_res <- t(vapply(c(10, 25, 50), function(m) {
  pj <- matrix(plogis(ln_mu + ln_sd * rnorm(n_trap * n_rep)), n_trap)
  k <- per_trap / m; n_pool <- n_trap * k
  fit <- pool_fit(colSums(matrix(rbinom(n_trap * n_rep, k, 1 - (1 - pj)^m), n_trap)), n_pool, m)
  c(m = m, limit = ln_limit(m), bias = mean(fit$p_hat[!fit$all_pos]) / p_ln - 1,
    wald = mean(fit$wald_lo <= p_ln & fit$wald_hi >= p_ln))
}, numeric(4)))
