# Density or frequency transmission in enclosures
# https://tidyecology.com/posts/density-or-frequency-dependent-transmission/
#
# 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)
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))
}

## ---- 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)), "}$")
}

## ---- simulator ----
gam_rec <- 0.1     # daily recovery probability
b_ref   <- 0.03    # per-pair daily hazard for ten animals in unit area
n_ref   <- 10
max_day <- 150

sim_experiments <- function(n_exp, sizes, reps, q, sd_log, area = 1) {
  n_arm <- max(length(sizes), length(area))
  arm_n <- rep(sizes, length.out = n_arm); arm_a <- rep(area, length.out = n_arm)
  arm <- rep(seq_len(n_arm), each = reps); n_encl <- length(arm)
  N <- rep(arm_n[arm], n_exp); A <- rep(arm_a[arm], n_exp)
  exper <- rep(seq_len(n_exp), each = n_encl); encl <- rep(seq_len(n_encl), n_exp)
  stratum <- rep(arm, n_exp)
  log_draw <- rnorm(length(N), 0, sd_log)
  beta_encl <- b_ref * n_ref^q * exp(log_draw)
  S <- N - 1; I <- rep(1, length(N)); days <- vector("list", max_day)
  for (day in seq_len(max_day)) {
    live <- which(I > 0 & S > 0)
    if (length(live) == 0) break
    p_inf <- 1 - exp(-beta_encl[live] * I[live] * N[live]^(-q) * A[live]^(q - 1))
    new <- rbinom(length(live), S[live], p_inf)
    rec <- rbinom(length(live), I[live], gam_rec)
    days[[day]] <- cbind(exper[live], encl[live], stratum[live], S[live], I[live],
                         N[live], A[live], new, log_draw[live])
    S[live] <- S[live] - new; I[live] <- I[live] + new - rec
  }
  out <- do.call(rbind, days)
  colnames(out) <- c("exper", "encl", "stratum", "S", "I", "N", "A", "new", "log_draw")
  out <- as.data.frame(out[order(out[, "exper"], out[, "encl"]), ])
  attr(out, "n_encl") <- n_encl
  out
}
r0_approx <- function(N, q) b_ref * n_ref^q * N^(-q) * (N - 1) / gam_rec

## ---- fitting ----
irls_cloglog <- function(new, S, x, off, grp, mult = 1, a0 = NULL, b0 = 0,
                         n_it = 100, tol = 1e-8) {
  n_grp <- max(grp); w0 <- S * mult; has_x <- !is.null(x)
  if (!has_x) x <- rep(0, length(new))
  if (is.null(a0)) a0 <- log((rowsum(mult * new, grp)[, 1] + 0.5) /
                             rowsum(w0 * exp(off), grp)[, 1])
  a <- rep_len(a0, n_grp); b <- if (has_x) rep_len(b0, n_grp) else rep(0, n_grp)
  ll_rows <- function(aa, bb, ix) {
    ee <- exp(aa + bb * x[ix] + off[ix])
    mult_i <- if (length(mult) == 1) mult else mult[ix]
    mult_i * (lchoose(S[ix], new[ix]) +
              ifelse(new[ix] > 0, new[ix] * log(-expm1(-ee)), 0) - (S[ix] - new[ix]) * ee)
  }
  ll_grp <- function(aa, bb, ix, g) rowsum(ll_rows(aa[g], bb[g], ix), g)[, 1]
  active <- rep(TRUE, n_grp)
  for (it in seq_len(n_it)) {
    ix <- which(active[grp]); if (length(ix) == 0) break
    g <- grp[ix]; ids <- sort(unique(g))
    lin <- a[g] + b[g] * x[ix]
    eta <- lin + off[ix]; eta[eta < -30] <- -30; eta[eta > 3] <- 3
    ee <- exp(eta); mu <- -expm1(-ee); mu[mu > 1 - 1e-12] <- 1 - 1e-12
    dmu <- ee * exp(-ee); wt <- w0[ix] * dmu^2 / (mu * (1 - mu))
    z <- lin + (new[ix] / S[ix] - mu) / dmu; xx <- x[ix]
    s0 <- rowsum(wt, g)[, 1]; sz <- rowsum(wt * z, g)[, 1]
    a_new <- a; b_new <- b
    if (has_x) {
      s1 <- rowsum(wt * xx, g)[, 1]; s2 <- rowsum(wt * xx^2, g)[, 1]
      s1z <- rowsum(wt * xx * z, g)[, 1]; dt <- s0 * s2 - s1^2
      a_new[ids] <- (s2 * sz - s1 * s1z) / dt; b_new[ids] <- (s0 * s1z - s1 * sz) / dt
    } else a_new[ids] <- sz / s0
    ll_old <- rep(-Inf, n_grp); ll_old[ids] <- ll_grp(a, b, ix, g)
    ll_new <- rep(-Inf, n_grp); ll_new[ids] <- ll_grp(a_new, b_new, ix, g)
    for (h in 1:30) {
      worse <- ids[!(is.finite(ll_new[ids]) & ll_new[ids] >= ll_old[ids] - 1e-10)]
      if (length(worse) == 0) break
      a_new[worse] <- (a[worse] + a_new[worse]) / 2
      b_new[worse] <- (b[worse] + b_new[worse]) / 2
      jx <- which(grp %in% worse)
      ll_new[worse] <- ll_grp(a_new, b_new, jx, grp[jx])
    }
    step <- pmax(abs(a_new - a), abs(b_new - b))
    a <- a_new; b <- b_new
    active[ids] <- step[ids] > tol
  }
  eta <- a[grp] + b[grp] * x + off; ee <- exp(eta); mu <- -expm1(-ee)
  mu[mu > 1 - 1e-12] <- 1 - 1e-12; mu[mu < 1e-300] <- 1e-300
  dmu <- ee * exp(-ee); wt <- w0 * dmu^2 / (mu * (1 - mu))
  info <- if (has_x) cbind(rowsum(wt, grp)[, 1], rowsum(wt * x, grp)[, 1],
                           rowsum(wt * x^2, grp)[, 1]) else rowsum(wt, grp)[, 1]
  list(a = a, b = b, mu = mu, dmu = dmu, info = info,
       loglik = rowsum(ll_rows(a[grp], b[grp], seq_along(new)), grp)[, 1])
}

fit_day_level <- function(dat, covariate = "N") {
  grp <- dat$exper; lx <- log(dat[[covariate]]); off_i <- log(dat$I)
  by_n <- covariate == "N"
  f_dd <- irls_cloglog(dat$new, dat$S, NULL, if (by_n) off_i else off_i - lx, grp)
  f_fd <- irls_cloglog(dat$new, dat$S, NULL, if (by_n) off_i - lx else off_i, grp)
  f_q  <- irls_cloglog(dat$new, dat$S, lx, off_i, grp)
  inf <- f_q$info; dt <- inf[, 1] * inf[, 3] - inf[, 2]^2
  mu <- f_q$mu; n_row <- tabulate(grp)
  pearson <- rowsum((dat$new - dat$S * mu)^2 / (dat$S * mu * (1 - mu)), grp)[, 1]
  score <- (dat$new - dat$S * mu) * f_q$dmu / (mu * (1 - mu))
  n_encl <- attr(dat, "n_encl"); clus <- (grp - 1) * n_encl + dat$encl
  u0 <- rowsum(score, clus)[, 1]; u1 <- rowsum(score * lx, clus)[, 1]
  clus_grp <- (as.numeric(names(u0)) - 1) %/% n_encl + 1
  m00 <- rowsum(u0^2, clus_grp)[, 1]; m01 <- rowsum(u0 * u1, clus_grp)[, 1]
  m11 <- rowsum(u1^2, clus_grp)[, 1]; n_cl <- tabulate(clus_grp)
  c0 <- -inf[, 2] / dt; c1 <- inf[, 1] / dt
  se <- sqrt(inf[, 1] / pmax(dt, 0)); se[!is.finite(se)] <- Inf
  se_cr <- sqrt(pmax(0, c0^2 * m00 + 2 * c0 * c1 * m01 + c1^2 * m11) * n_cl / (n_cl - 1))
  se_cr[!is.finite(se_cr)] <- Inf
  data.frame(pick_dd = f_dd$loglik > f_fd$loglik,
             q_hat = if (by_n) -f_q$b else f_q$b + 1, se = se,
             dispersion = pearson / (n_row - 2), n_row = n_row,
             se_cr = se_cr, n_cl = n_cl, a_hat = f_q$a, b_hat = f_q$b)
}

## ---- check-glm ----
set.seed(4101)
chk_dat <- sim_experiments(10, c(5, 10, 20, 40), 3, 0.5, 0.6)
chk_fit <- fit_day_level(chk_dat)
chk_ref <- t(sapply(1:10, function(e) {
  s_e <- chk_dat[chk_dat$exper == e, ]
  f_q <- glm(cbind(new, S - new) ~ log(N), offset = log(I),
             family = binomial("cloglog"), data = s_e)
  f_d <- glm(cbind(new, S - new) ~ 1, offset = log(I),
             family = binomial("cloglog"), data = s_e)
  f_f <- glm(cbind(new, S - new) ~ 1, offset = log(I) - log(N),
             family = binomial("cloglog"), data = s_e)
  c(-coef(f_q)[[2]], sqrt(vcov(f_q)[2, 2]), logLik(f_d) > logLik(f_f))
}))
gap_q  <- max(abs(chk_ref[, 1] - chk_fit$q_hat))
gap_se <- max(abs(chk_ref[, 2] - chk_fit$se))
same_pick <- sum(chk_ref[, 3] == chk_fit$pick_dd)

## ---- one-experiment ----
one_enclosures <- function(dat) {
  fe <- irls_cloglog(dat$new, dat$S, NULL, log(dat$I), dat$encl)
  n_by <- tapply(dat$N, dat$encl, function(v) v[1])
  tot <- tapply(dat$new, dat$encl, sum)
  data.frame(N = as.numeric(n_by), hazard = exp(fe$a), none = tot == 0)
}
set.seed(4202)
ex_dd <- sim_experiments(1, c(5, 10, 20, 40), 3, 0, 0)
set.seed(4203)
ex_fd <- sim_experiments(1, c(5, 10, 20, 40), 3, 1, 0)
enc_dd <- one_enclosures(ex_dd); enc_fd <- one_enclosures(ex_fd)
fit_dd_ex <- fit_day_level(ex_dd); fit_fd_ex <- fit_day_level(ex_fd)
z95 <- qnorm(0.975)
ci_txt <- function(f) sprintf("%.2f to %.2f", f$q_hat - z95 * f$se, f$q_hat + z95 * f$se)
n_none <- sum(enc_dd$none) + sum(enc_fd$none)

## ---- fig-one-experiment ----
floor_h <- 1e-3
panel_one <- function(enc, fit, ttl) {
  enc$shown <- ifelse(enc$none, floor_h, enc$hazard)
  none_rank <- ave(as.numeric(enc$none), enc$N, enc$none, FUN = seq_along)
  none_count <- ave(as.numeric(enc$none), enc$N, enc$none, FUN = length)
  enc$N_shown <- ifelse(enc$none, enc$N * exp(0.2 * (none_rank - (none_count + 1) / 2)), enc$N)
  lines_df <- data.frame(N = exp(seq(log(4.5), log(45), length.out = 50)))
  lines_df$hazard <- exp(fit$a_hat + fit$b_hat * log(lines_df$N))
  ggplot(enc, aes(N_shown, shown)) +
    geom_line(data = lines_df, aes(N, hazard), colour = te_forest, linewidth = 0.9) +
    geom_point(aes(shape = none, colour = none), size = 2.6, stroke = 0.9) +
    scale_shape_manual(values = c(`FALSE` = 16, `TRUE` = 4),
                       labels = c("rate fitted to the enclosure", "no transmission"), name = NULL) +
    scale_colour_manual(values = c(`FALSE` = te_ink, `TRUE` = te_rust),
                        labels = c("rate fitted to the enclosure", "no transmission"), name = NULL) +
    scale_x_log10(breaks = c(5, 10, 20, 40)) +
    scale_y_log10(limits = c(floor_h * 0.8, 1)) +
    labs(x = "group size", y = "per-pair daily hazard", title = ttl,
         subtitle = sprintf("green line: pooled fit, q = %.2f", fit$q_hat)) +
    theme_datasheet() + theme(legend.position = "bottom")
}
(panel_one(enc_dd, fit_dd_ex, "Truth: density dependent") |
   panel_one(enc_fd, fit_fd_ex, "Truth: frequency dependent")) +
  plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() + theme(legend.position = "bottom"))

## ---- designs ----
n_exp_design <- 300   # experiments per cell, fixed before any rate was seen
designs <- list(
  list(label = "sizes 8, 12 (x4)", sizes = c(8, 12), reps = 4, area = 1, cov = "N"),
  list(label = "sizes 8, 12 (x6)", sizes = c(8, 12), reps = 6, area = 1, cov = "N"),
  list(label = "sizes 5, 20 (x4)", sizes = c(5, 20), reps = 4, area = 1, cov = "N"),
  list(label = "sizes 5 to 40 (x2)", sizes = c(5, 10, 20, 40), reps = 2, area = 1, cov = "N"),
  list(label = "20 animals, area 1 to 8 (x2)", sizes = 20, reps = 2, area = c(1, 2, 4, 8), cov = "A"))
q_set <- c(0, 0.5, 1)
set.seed(4304)
design_tab <- do.call(rbind, lapply(designs, function(ds) do.call(rbind, lapply(q_set, function(q) {
  dat <- sim_experiments(n_exp_design, ds$sizes, ds$reps, q, 0, ds$area)
  ff <- fit_day_level(dat, ds$cov)
  lo <- ff$q_hat - z95 * ff$se; hi <- ff$q_hat + z95 * ff$se
  data.frame(design = ds$label, q = q,
             pick_true = if (q == 0) mean(ff$pick_dd) else mean(!ff$pick_dd),
             pick_dd = mean(ff$pick_dd),
             both_in = mean(lo < 0 & hi > 1), excl_both = mean(lo > 0 & hi < 1),
             rej_true = mean(q < lo | q > hi), no_est = sum(!is.finite(ff$se)))
}))))
design_tab$design <- factor(design_tab$design, levels = rev(sapply(designs, `[[`, "label")))
dv <- function(lab, q, col) design_tab[design_tab$design == lab & design_tab$q == q, col]
lab_n4 <- designs[[1]]$label; lab_n6 <- designs[[2]]$label; lab_two <- designs[[3]]$label
lab_wide <- designs[[4]]$label; lab_area <- designs[[5]]$label
mcse_half <- sqrt(0.25 / n_exp_design)
rej_max <- max(design_tab$rej_true[design_tab$q != 0.5])
n_no_est <- sum(design_tab$no_est)
n_fitted <- n_exp_design * nrow(design_tab)
no_est_txt <- if (n_no_est == 0) sprintf("all %d fitted experiments returned a finite standard error", n_fitted) else
  sprintf("%d of the %d fitted experiments returned no finite standard error", n_no_est, n_fitted)

## ---- fig-designs ----
dplot <- design_tab[design_tab$q != 0.5, ]
dplot$truth <- factor(ifelse(dplot$q == 0, "truth: density dependent", "truth: frequency dependent"))
p_pick <- ggplot(dplot, aes(pick_true, design, colour = truth, shape = truth)) +
  geom_vline(xintercept = 0.5, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(xmin = pick_true - 2 * sqrt(pick_true * (1 - pick_true) / n_exp_design),
                    xmax = pick_true + 2 * sqrt(pick_true * (1 - pick_true) / n_exp_design)),
                orientation = "y", width = 0.25, linewidth = 0.4, show.legend = FALSE) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_shape_manual(values = c(16, 17), name = NULL) +
  coord_cartesian(xlim = c(0, 1.02)) +
  labs(x = "picks the true form", y = NULL, title = "Likelihood choice",
       subtitle = "dashed: a coin") +
  theme_datasheet() + theme(legend.position = "bottom")
p_both <- ggplot(dplot, aes(both_in, design, colour = truth, shape = truth)) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_shape_manual(values = c(16, 17), name = NULL) +
  coord_cartesian(xlim = c(0, 1)) +
  labs(x = "intervals holding 0 and 1", y = NULL, title = "Undecided interval",
       subtitle = "the experiment cannot tell") +
  theme_datasheet() + theme(legend.position = "bottom", axis.text.y = element_blank())
(p_pick | p_both) + plot_layout(guides = "collect", widths = c(1.25, 1)) +
  plot_annotation(theme = theme_datasheet() + theme(legend.position = "bottom"))

## ---- heterogeneity ----
n_exp_het <- 300
sd_grid <- c(0, 0.2, 0.4, 0.6)
het_cells <- expand.grid(sd_log = sd_grid, q = c(0, 1), reps = c(3, 6))
set.seed(4405)
kept <- list()
het_tab <- do.call(rbind, lapply(seq_len(nrow(het_cells)), function(i) {
  cc <- het_cells[i, ]
  dat <- sim_experiments(n_exp_het, c(5, 10, 20, 40), cc$reps, cc$q, cc$sd_log)
  ff <- fit_day_level(dat)
  if (cc$reps == 3 && cc$sd_log %in% c(0, 0.6))
    kept[[sprintf("q%g_sd%g", cc$q, cc$sd_log)]] <<- list(dat = dat, fit = ff, q = cc$q, sd_log = cc$sd_log)
  data.frame(cc, n_encl = 4 * cc$reps,
             rej_true = mean(abs(ff$q_hat - cc$q) > z95 * ff$se),
             pick_true = if (cc$q == 0) mean(ff$pick_dd) else mean(!ff$pick_dd),
             med_bias = median(ff$q_hat) - cc$q, sd_q = sd(ff$q_hat), med_se = median(ff$se),
             med_disp = median(ff$dispersion))
}))
hv <- function(q, s, r, col) het_tab[het_tab$q == q & het_tab$sd_log == s & het_tab$reps == r, col]
mcse_rej <- function(p) sqrt(p * (1 - p) / n_exp_het)

## ---- shift ----
n_exp_big <- 1000   # experiments per cell, fixed before any rate was seen
set.seed(4407)
big <- list()
for (q in c(0, 1)) for (s_log in c(0, 0.6)) {
  dat <- sim_experiments(n_exp_big, c(5, 10, 20, 40), 3, q, s_log)
  big[[sprintf("q%g_sd%g", q, s_log)]] <- list(dat = dat, fit = fit_day_level(dat), q = q, sd_log = s_log)
}
mcse_median <- function(v) 1.2533 * sd(v) / sqrt(length(v))
shift_tab <- do.call(rbind, lapply(big[c("q0_sd0.6", "q1_sd0.6")], function(bc) {
  d <- bc$dat
  oracle <- irls_cloglog(d$new, d$S, log(d$N), log(d$I) + d$log_draw, d$exper)
  enc_key <- (d$exper - 1) * attr(d, "n_encl") + d$encl
  n_days <- tapply(d$new, enc_key, length)
  enc_N <- tapply(d$N, enc_key, function(v) v[1])
  enc_draw <- tapply(d$log_draw, enc_key, function(v) v[1])
  cors <- sapply(c(5, 10, 20, 40), function(n) cor(enc_draw[enc_N == n], n_days[enc_N == n]))
  data.frame(q = bc$q, naive = median(bc$fit$q_hat) - bc$q, naive_se = mcse_median(bc$fit$q_hat),
             oracle = median(-oracle$b) - bc$q, oracle_se = mcse_median(-oracle$b),
             cor5 = cors[1], cor10 = cors[2], cor20 = cors[3], cor40 = cors[4])
}))
sv <- function(q, col) shift_tab[shift_tab$q == q, col]

## ---- fig-heterogeneity ----
het_tab$truth <- factor(ifelse(het_tab$q == 0, "truth: density dependent", "truth: frequency dependent"))
het_tab$encl_lab <- factor(sprintf("%d enclosures", het_tab$n_encl))
ggplot(het_tab, aes(sd_log, rej_true, colour = encl_lab, linetype = encl_lab)) +
  geom_hline(yintercept = 0.05, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(ymin = rej_true - 2 * mcse_rej(rej_true), ymax = rej_true + 2 * mcse_rej(rej_true)),
                width = 0.02, linewidth = 0.4, linetype = "solid", show.legend = FALSE) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  facet_wrap(~ truth) +
  scale_colour_manual(values = c(te_forest, te_gold), name = NULL) +
  scale_linetype_manual(values = c("solid", "longdash"), name = NULL) +
  scale_y_continuous(limits = c(0, NA)) +
  labs(x = "standard deviation of log transmission rate between enclosures",
       y = "share rejecting the true exponent",
       title = "The day records are not the replicates",
       subtitle = "dashed line: the nominal five per cent") +
  theme_datasheet() + theme(legend.position = "bottom",
                            strip.text = element_text(colour = te_ink, face = "bold"))

## ---- repairs ----
n_boot <- 99; n_exp_fix <- 200   # fixed before any rate was seen
resample_q <- function(dat, fit, n_boot, chunk = 25) {
  n_encl <- attr(dat, "n_encl"); n_ex <- max(dat$exper)
  key <- (dat$exper - 1) * n_encl + dat$encl
  rows_by_key <- split(seq_len(nrow(dat)), factor(key, levels = seq_len(n_ex * n_encl)))
  strat <- tapply(dat$stratum, dat$encl, function(v) v[1])
  n_rep <- 1 + n_encl + n_boot
  out_jk <- matrix(NA, n_ex, n_encl); out_bs <- matrix(NA, n_ex, n_boot)
  for (start in seq(1, n_ex, by = chunk)) {
    ex_ids <- start:min(n_ex, start + chunk - 1)
    mult <- array(0, c(length(ex_ids), n_rep, n_encl))
    for (i in seq_along(ex_ids)) {
      m <- matrix(0, n_rep, n_encl); m[1, ] <- 1
      m[2:(n_encl + 1), ] <- 1 - diag(n_encl)
      if (n_boot > 0) for (k in unique(strat)) {
        ids <- which(strat == k)
        draws <- matrix(ids[sample.int(length(ids), n_boot * length(ids), TRUE)], n_boot)
        for (j in ids) m[(n_encl + 2):n_rep, j] <- rowSums(draws == j)
      }
      mult[i, , ] <- m
    }
    cmb <- expand.grid(i = seq_along(ex_ids), r = seq_len(n_rep), j = seq_len(n_encl))
    cmb$m <- mult[cbind(cmb$i, cmb$r, cmb$j)]
    cmb <- cmb[cmb$m > 0, ]
    idx <- rows_by_key[(ex_ids[cmb$i] - 1) * n_encl + cmb$j]; len <- lengths(idx)
    rows <- unlist(idx, use.names = FALSE)
    grp_raw <- rep((cmb$i - 1) * n_rep + cmb$r, len)
    ug <- sort(unique(grp_raw)); grp <- match(grp_raw, ug)
    gi <- (ug - 1) %/% n_rep + 1; gr <- (ug - 1) %% n_rep + 1
    fr <- irls_cloglog(dat$new[rows], dat$S[rows], log(dat$N[rows]), log(dat$I[rows]), grp,
                       mult = rep(cmb$m, len), a0 = fit$a_hat[ex_ids][gi],
                       b0 = fit$b_hat[ex_ids][gi])
    for (i in seq_along(ex_ids)) {
      sel <- gi == i
      out_jk[ex_ids[i], gr[sel][gr[sel] %in% 2:(n_encl + 1)] - 1] <- -fr$b[sel][gr[sel] %in% 2:(n_encl + 1)]
      if (n_boot > 0) out_bs[ex_ids[i], ] <- -fr$b[sel][gr[sel] > n_encl + 1]
    }
  }
  list(jk = out_jk, bs = out_bs)
}
method_lev <- c("day-level Wald", "day-level quasi", "cluster sandwich, t",
                "enclosure jackknife, t", "cluster bootstrap")
set.seed(4506)
boot_tab <- do.call(rbind, lapply(kept, function(kc) {
  keep_ex <- kc$dat$exper <= n_exp_fix
  dat <- kc$dat[keep_ex, ]; attr(dat, "n_encl") <- attr(kc$dat, "n_encl")
  f <- kc$fit[seq_len(n_exp_fix), ]
  rs <- resample_q(dat, f, n_boot)
  G <- attr(dat, "n_encl"); q <- kc$q
  se_jk <- sqrt((G - 1) / G * rowSums((rs$jk - rowMeans(rs$jk))^2))
  bs_lo <- apply(rs$bs, 1, quantile, 0.025); bs_hi <- apply(rs$bs, 1, quantile, 0.975)
  data.frame(q = q, sd_log = kc$sd_log, method = method_lev[5], rej = mean(q < bs_lo | q > bs_hi),
             rej_other = NA, rej_half = NA, n = n_exp_fix, jk_ratio = NA, jk_spread = NA,
             bs_ratio = median(apply(rs$bs, 1, sd) / se_jk))
}))
enc_tab <- do.call(rbind, lapply(big, function(bc) {
  dat <- bc$dat; f <- bc$fit
  rs <- resample_q(dat, f, 0)
  G <- attr(dat, "n_encl"); q <- bc$q
  crit_t <- qt(0.975, G - 2)
  se_jk <- sqrt((G - 1) / G * rowSums((rs$jk - rowMeans(rs$jk))^2))
  half <- list(z95 * f$se,
               qt(0.975, f$n_row - 2) * f$se * sqrt(pmax(1, f$dispersion)),
               crit_t * f$se_cr, crit_t * se_jk)
  miss <- function(target) sapply(half, function(h) mean(abs(f$q_hat - target) > h))
  data.frame(q = q, sd_log = bc$sd_log, method = method_lev[1:4], rej = miss(q),
             rej_other = miss(1 - q), rej_half = miss(0.5), n = n_exp_big,
             jk_ratio = median(se_jk / f$se_cr), jk_spread = median(se_jk) / sd(f$q_hat),
             bs_ratio = NA)
}))
repair_tab <- rbind(enc_tab, boot_tab)
repair_tab$method <- factor(repair_tab$method, levels = method_lev)
rv <- function(q, s, k, col = "rej") repair_tab[repair_tab$q == q & repair_tab$sd_log == s &
                                                repair_tab$method == method_lev[k], col]
mcse_big <- sqrt(0.05 * 0.95 / n_exp_big); mcse_fix <- sqrt(0.05 * 0.95 / n_exp_fix)
bs_ratio_med <- median(boot_tab$bs_ratio)
jk_ratio_med <- median(enc_tab$jk_ratio)
jk_spread_rng <- range(enc_tab$jk_spread)
bs_range <- range(boot_tab$rej)
sand_range <- range(enc_tab$rej[enc_tab$method == method_lev[3] & enc_tab$sd_log == 0])
sand_z <- (sand_range[2] - 0.05) / mcse_big
jk_dev <- max(abs(enc_tab$rej[enc_tab$method == method_lev[4]] - 0.05)) / mcse_big

## ---- fig-repairs ----
repair_tab$truth <- factor(ifelse(repair_tab$q == 0, "density dependent", "frequency dependent"))
repair_tab$spread <- factor(sprintf("between-enclosure sd %.1f", repair_tab$sd_log))
repair_tab$method <- factor(repair_tab$method, levels = rev(method_lev))
ggplot(repair_tab, aes(rej, method, colour = truth, shape = truth)) +
  geom_vline(xintercept = 0.05, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(xmin = rej - 2 * sqrt(rej * (1 - rej) / n),
                    xmax = rej + 2 * sqrt(rej * (1 - rej) / n)),
                orientation = "y", width = 0.25, linewidth = 0.4,
                position = position_dodge(width = 0.5), show.legend = FALSE) +
  geom_point(size = 2.6, position = position_dodge(width = 0.5)) +
  facet_wrap(~ spread) +
  scale_colour_manual(values = c(te_forest, te_rust), name = "truth") +
  scale_shape_manual(values = c(16, 17), name = "truth") +
  coord_cartesian(xlim = c(0, NA)) +
  labs(x = "share rejecting the true exponent", y = NULL,
       title = "Twelve enclosures, five intervals",
       subtitle = "dashed line: the nominal five per cent") +
  theme_datasheet() + theme(legend.position = "bottom",
                            strip.text = element_text(colour = te_ink, face = "bold"))
