# Prevalence from an imperfect test
# https://tidyecology.com/posts/prevalence-from-an-imperfect-test/
#
# 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-08

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

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

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"),
          axis.text = element_text(colour = "#2c3a31"))
}

## ---- survey-design ----
se_true <- 0.95
sp_true <- 0.98
p_true <- 0.02
n_survey <- 480
n_val_pos <- 100
n_val_neg <- 100

ap_of <- function(p, se, sp) se * p + (1 - sp) * (1 - p)
rg_of <- function(ap, se, sp) (ap + sp - 1) / (se + sp - 1)

ap_exp <- ap_of(p_true, se_true, sp_true)
fp_term <- (1 - sp_true) * (1 - p_true)
fn_term <- (1 - se_true) * p_true
over_pct <- 100 * (ap_exp / p_true - 1)
fp_of_positives <- 100 * fp_term / ap_exp
fp_of_error <- 100 * fp_term / (fp_term + fn_term)
youden <- se_true + sp_true - 1

print(round(c(true_prevalence = p_true, sensitivity = se_true, specificity = sp_true,
              animals = n_survey, youden_index = youden), 4))
print(round(c(expected_apparent = ap_exp, true_positive_term = se_true * p_true,
              false_positive_term = fp_term, missed_positive_term = fn_term,
              overestimate_pct = over_pct), 5))
print(round(c(false_share_of_positives = fp_of_positives, fp_over_fn = fp_term / fn_term,
              false_positive_share_of_error = fp_of_error), 4))

## ---- fig-apparent ----
p_axis <- seq(0, 0.2, length.out = 201)
combo <- data.frame(
  se = c(0.95, 0.95, 0.70, 0.95),
  sp = c(0.98, 0.95, 0.98, 0.999),
  lab = c("Se 0.95, Sp 0.98 (this survey)", "Se 0.95, Sp 0.95",
          "Se 0.70, Sp 0.98", "Se 0.95, Sp 0.999"))
curve_dat <- do.call(rbind, lapply(seq_len(nrow(combo)), function(k)
  data.frame(p = p_axis,
             ap = ap_of(p_axis, combo$se[k], combo$sp[k]),
             lab = factor(combo$lab[k], levels = combo$lab))))

ggplot(curve_dat, aes(100 * p, 100 * ap, colour = lab)) +
  geom_abline(intercept = 0, slope = 1, linetype = "22",
              colour = "#8d9a8d", linewidth = 0.7) +
  geom_vline(xintercept = 100 * p_true, linetype = "11",
             colour = "#8d9a8d", linewidth = 0.7) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay,
                                 te_pal$gold, te_pal$sage), name = NULL) +
  labs(x = "true prevalence (per cent)",
       y = "expected apparent prevalence (per cent)",
       title = "The intercept is one minus the specificity") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 4, 8))

## ---- one-survey ----
set.seed(20260804)
x_pos <- rbinom(1, n_survey, ap_exp)
ap_hat <- x_pos / n_survey
p_hat_one <- rg_of(ap_hat, se_true, sp_true)

print(c(positive_strips = x_pos, animals = n_survey))
print(round(c(apparent_prevalence = ap_hat,
              corrected_prevalence = p_hat_one,
              true_prevalence = p_true), 5))

## ---- correction-average ----
n_rep <- 4000
set.seed(3311)
sv_known <- rbinom(n_rep, n_survey, ap_exp)
ap_known <- sv_known / n_survey
p_known <- rg_of(ap_known, se_true, sp_true)

print(round(c(mean_apparent = mean(ap_known), expected_apparent = ap_exp,
              mean_corrected = mean(p_known), true_prevalence = p_true,
              bias_of_apparent = mean(ap_known) - p_true,
              bias_of_corrected = mean(p_known) - p_true), 6))
print(round(c(mc_se_corrected = sd(p_known) / sqrt(n_rep), sd_corrected = sd(p_known),
              sd_apparent = sd(ap_known), sd_ratio = sd(p_known) / sd(ap_known)), 6))

## ---- validation-draw ----
n_val_rep <- 20000
set.seed(6142)
sp_draws <- rbinom(n_val_rep, n_val_neg, sp_true) / n_val_neg
se_draws <- rbinom(n_val_rep, n_val_pos, se_true) / n_val_pos

print(round(c(mean_sp_hat = mean(sp_draws), sd_sp_hat = sd(sp_draws),
              mean_se_hat = mean(se_draws), sd_se_hat = sd(se_draws)), 5))
print(round(c(sp_hat_equals_one = mean(sp_draws == 1),
              sp_hat_at_or_below_0.96 = mean(sp_draws <= 0.96),
              se_hat_equals_one = mean(se_draws == 1),
              sp_hat_quantiles = quantile(sp_draws, c(0.025, 0.5, 0.975))), 4))

## ---- variance-budget ----
delta_sd <- function(ap, se, sp, n, npos, nneg) {
  dd <- se + sp - 1
  ph <- (ap + sp - 1) / dd
  sqrt((ap * (1 - ap) / n + ph^2 * se * (1 - se) / npos +
          (1 - ph)^2 * sp * (1 - sp) / nneg) / dd^2)
}

v_survey <- ap_exp * (1 - ap_exp) / n_survey
v_sens <- p_true^2 * se_true * (1 - se_true) / n_val_pos
v_spec <- (1 - p_true)^2 * sp_true * (1 - sp_true) / n_val_neg
v_all <- v_survey + v_sens + v_spec
sd_fixed <- sqrt(v_survey) / youden
sd_full <- delta_sd(ap_exp, se_true, sp_true, n_survey, n_val_pos, n_val_neg)

print(round(100 * c(survey_share = v_survey, sensitivity_share = v_sens,
                    specificity_share = v_spec) / v_all, 4))
print(round(c(sd_treating_test_as_fixed = sd_fixed,
              sd_carrying_validation = sd_full,
              width_multiplier = sd_full / sd_fixed), 5))

## ---- interval-machinery ----
zc <- qnorm(0.975)

wilson_ci <- function(x, n) {
  ph <- x / n
  cc <- (ph + zc^2 / (2 * n)) / (1 + zc^2 / n)
  hw <- zc * sqrt(ph * (1 - ph) / n + zc^2 / (4 * n^2)) / (1 + zc^2 / n)
  cbind(cc - hw, cc + hw)
}

boot_ci <- function(ap, se, sp, n, npos, nneg, n_boot) {
  aps <- rbinom(n_boot, n, ap) / n
  ses <- rbinom(n_boot, npos, se) / npos
  sps <- rbinom(n_boot, nneg, sp) / nneg
  ok <- ses + sps - 1 > 0
  qq <- quantile(rg_of(aps[ok], ses[ok], sps[ok]),
                 c(0.025, 0.975), names = FALSE)
  ph <- rg_of(ap, se, sp)
  c(percentile_lo = qq[1], percentile_hi = qq[2],
    basic_lo = 2 * ph - qq[2], basic_hi = 2 * ph - qq[1])
}

## ---- coverage-sweep ----
p_sweep <- c(0.005, 0.01, 0.02, 0.04, 0.08, 0.15)
n_cov <- 2000
n_boot <- 599
cov_tab <- data.frame(p = p_sweep)
head_line <- NULL

set.seed(7311)
for (k in seq_along(p_sweep)) {
  ap_k <- ap_of(p_sweep[k], se_true, sp_true)
  sv <- rbinom(n_cov, n_survey, ap_k)
  se_h <- rbinom(n_cov, n_val_pos, se_true) / n_val_pos
  sp_h <- rbinom(n_cov, n_val_neg, sp_true) / n_val_neg
  ap_h <- sv / n_survey
  wi <- wilson_ci(sv, n_survey)
  ph <- rg_of(ap_h, se_h, sp_h)
  sdv <- delta_sd(ap_h, se_h, sp_h, n_survey, n_val_pos, n_val_neg)

  lo_ref <- rg_of(wi[, 1], se_true, sp_true)
  hi_ref <- rg_of(wi[, 2], se_true, sp_true)
  lo_nai <- rg_of(wi[, 1], se_h, sp_h)
  hi_nai <- rg_of(wi[, 2], se_h, sp_h)
  lo_del <- ph - zc * sdv
  hi_del <- ph + zc * sdv
  bt <- matrix(NA_real_, n_cov, 4)
  for (i in seq_len(n_cov)) {
    bt[i, ] <- boot_ci(ap_h[i], se_h[i], sp_h[i],
                       n_survey, n_val_pos, n_val_neg, n_boot)
  }
  hit <- function(lo, hi) mean(lo <= p_sweep[k] & hi >= p_sweep[k])
  cov_tab$reference[k] <- hit(lo_ref, hi_ref)
  cov_tab$naive[k] <- hit(lo_nai, hi_nai)
  cov_tab$delta[k] <- hit(lo_del, hi_del)
  cov_tab$boot[k] <- hit(bt[, 3], bt[, 4])
  cov_tab$w_naive[k] <- mean(hi_nai - lo_nai)
  cov_tab$w_delta[k] <- mean(hi_del - lo_del)
  cov_tab$w_boot[k] <- mean(bt[, 4] - bt[, 3])
  if (p_sweep[k] == p_true) {
    head_line <- list(ph = ph, sdv = sdv, sp_h = sp_h, se_h = se_h,
                      lo_nai = lo_nai, hi_nai = hi_nai,
                      lo_del = lo_del, hi_del = hi_del, bt = bt)
  }
}
print(round(cov_tab, 4))

## ---- coverage-headline ----
hl <- head_line
in_ok <- function(lo, hi) lo <= p_true & hi >= p_true
row_at <- which(cov_tab$p == p_true)
cov_ref <- cov_tab$reference[row_at]
cov_nai <- cov_tab$naive[row_at]
cov_del <- cov_tab$delta[row_at]
cov_boo <- cov_tab$boot[row_at]
cov_pct <- mean(in_ok(hl$bt[, 1], hl$bt[, 2]))

print(round(c(reference_known_test = cov_ref, naive_fixed = cov_nai,
              delta_propagated = cov_del, bootstrap_basic = cov_boo,
              bootstrap_percentile = cov_pct), 4))
print(round(c(naive_miss_low = mean(hl$lo_nai > p_true),
              naive_miss_high = mean(hl$hi_nai < p_true),
              delta_miss_low = mean(hl$lo_del > p_true),
              delta_miss_high = mean(hl$hi_del < p_true),
              lower_limit_below_zero = mean(hl$lo_del < 0)), 4))
print(round(c(width_naive = cov_tab$w_naive[row_at], width_delta = cov_tab$w_delta[row_at],
              width_ratio = cov_tab$w_delta[row_at] / cov_tab$w_naive[row_at]), 4))

## ---- fig-coverage ----
meth_lab <- c("test known exactly", "validation ignored",
              "delta method", "bootstrap")
cov_long <- do.call(rbind, Map(function(v, lb)
  data.frame(p = cov_tab$p, coverage = v,
             method = factor(lb, levels = meth_lab)),
  list(cov_tab$reference, cov_tab$naive, cov_tab$delta, cov_tab$boot),
  meth_lab))

ggplot(cov_long, aes(100 * p, coverage, colour = method, shape = method)) +
  geom_hline(yintercept = 0.95, linetype = "22",
             colour = te_pal$ink, linewidth = 0.5) +
  geom_line(linewidth = 0.85) +
  geom_point(size = 2.3) +
  scale_x_log10(breaks = 100 * p_sweep, labels = 100 * p_sweep) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay,
                                 te_pal$gold, te_pal$sage), name = NULL) +
  scale_shape_manual(values = c(16, 17, 15, 18), name = NULL) +
  labs(x = "true prevalence (per cent, log scale)",
       y = "coverage of a nominal 95 per cent interval",
       title = "What ignoring the validation study costs") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 4, 8))

## ---- boot-shape ----
sp_one <- hl$sp_h == 1
skew_ph <- mean((hl$ph - mean(hl$ph))^3) / sd(hl$ph)^3
shift_lo <- mean(hl$bt[, 3] - hl$bt[, 1])

print(round(c(skewness_of_corrected = skew_ph, percentile_coverage = cov_pct,
              basic_coverage = cov_boo, lower_limit_shift = shift_lo,
              mean_abs_endpoint_gap = mean(abs(hl$lo_del - hl$bt[, 3]))), 5))
by_panel <- function(sel) c(
  share = mean(sel),
  delta_cover = mean(in_ok(hl$lo_del, hl$hi_del)[sel]),
  boot_cover = mean(in_ok(hl$bt[, 3], hl$bt[, 4])[sel]),
  delta_width = mean((hl$hi_del - hl$lo_del)[sel]))
print(round(rbind(sp_hat_one = by_panel(sp_one),
                  sp_hat_below_one = by_panel(!sp_one)), 4))

## ---- negative-grid ----
p_grid <- c(0, 0.005, 0.01, 0.02, 0.03, 0.05)
n_grid <- c(120, 240, 480, 960, 1920)
n_neg_rep <- 4000
neg_tab <- expand.grid(p = p_grid, n = n_grid)
neg_tab$known <- NA_real_
neg_tab$estimated <- NA_real_

set.seed(5510)
for (k in seq_len(nrow(neg_tab))) {
  ap_k <- ap_of(neg_tab$p[k], se_true, sp_true)
  ap_d <- rbinom(n_neg_rep, neg_tab$n[k], ap_k) / neg_tab$n[k]
  se_d <- rbinom(n_neg_rep, n_val_pos, se_true) / n_val_pos
  sp_d <- rbinom(n_neg_rep, n_val_neg, sp_true) / n_val_neg
  neg_tab$known[k] <- mean(rg_of(ap_d, se_true, sp_true) < 0)
  neg_tab$estimated[k] <- mean(rg_of(ap_d, se_d, sp_d) < 0)
}
print(round(neg_tab[neg_tab$n %in% c(120, 480, 1920), ], 4))

pick <- function(pp, nn, col) neg_tab[[col]][neg_tab$p == pp & neg_tab$n == nn]
print(round(c(at_zero_n120 = pick(0, 120, "known"), at_zero_n1920 = pick(0, 1920, "known"),
              at_two_pct_n120_known = pick(0.02, 120, "known"),
              at_two_pct_n1920_known = pick(0.02, 1920, "known"),
              at_two_pct_n120_est = pick(0.02, 120, "estimated"),
              at_two_pct_n1920_est = pick(0.02, 1920, "estimated"),
              at_one_pct_n1920_est = pick(0.01, 1920, "estimated")), 4))

## ---- fig-negative ----
panel_lab <- c("specificity known exactly",
               "specificity from 100 known negatives")
neg_long <- rbind(
  data.frame(p = neg_tab$p, n = neg_tab$n, y = neg_tab$known,
             panel = panel_lab[1]),
  data.frame(p = neg_tab$p, n = neg_tab$n, y = neg_tab$estimated,
             panel = panel_lab[2]))
neg_long$panel <- factor(neg_long$panel, levels = panel_lab)
neg_long$size_lab <- factor(paste(neg_long$n, "animals"),
                            levels = paste(n_grid, "animals"))

ggplot(neg_long, aes(100 * p, y, colour = size_lab)) +
  geom_vline(xintercept = 100 * (1 - sp_true), linetype = "11",
             colour = "#8d9a8d", linewidth = 0.7) +
  geom_line(linewidth = 0.85) +
  geom_point(size = 1.9) +
  facet_wrap(~panel) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, "#b9c4a4",
                                 te_pal$sage, te_pal$forest), name = NULL) +
  labs(x = "true prevalence (per cent)",
       y = "proportion of estimates below zero",
       title = "More animals cannot buy a better specificity") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 4, 8))

## ---- truncation ----
p_low <- c(0, 0.0025, 0.005, 0.01, 0.02)
n_tr_rep <- 4000
tr_tab <- data.frame(p = p_low)
tr_draws <- NULL

set.seed(8810)
for (k in seq_along(p_low)) {
  ap_k <- ap_of(p_low[k], se_true, sp_true)
  ap_d <- rbinom(n_tr_rep, n_survey, ap_k) / n_survey
  se_d <- rbinom(n_tr_rep, n_val_pos, se_true) / n_val_pos
  sp_d <- rbinom(n_tr_rep, n_val_neg, sp_true) / n_val_neg
  ph <- rg_of(ap_d, se_d, sp_d)
  sdv <- delta_sd(ap_d, se_d, sp_d, n_survey, n_val_pos, n_val_neg)
  pt <- pmax(ph, 0)
  lo <- ph - zc * sdv
  hi <- ph + zc * sdv
  tr_tab$raw_mean[k] <- mean(ph); tr_tab$trunc_mean[k] <- mean(pt)
  tr_tab$rmse_raw[k] <- sqrt(mean((ph - p_low[k])^2))
  tr_tab$rmse_trunc[k] <- sqrt(mean((pt - p_low[k])^2))
  tr_tab$cover_raw[k] <- mean(lo <= p_low[k] & hi >= p_low[k])
  tr_tab$cover_clip[k] <- mean(pmax(lo, 0) <= p_low[k] & pmax(hi, 0) >= p_low[k])
  tr_tab$width_raw[k] <- mean(hi - lo)
  tr_tab$width_clip[k] <- mean(pmax(hi, 0) - pmax(lo, 0))
  tr_tab$q90_trunc[k] <- unname(quantile(pt, 0.9))
  tr_tab$mc_se[k] <- sd(ph) / sqrt(n_tr_rep)
  tr_tab$at_design[k] <- mean(pt >= p_true)
  if (p_low[k] == 0) tr_draws <- ph
}
print(round(tr_tab[, 1:6], 5))
print(round(tr_tab[, c(1, 7:12)], 5))

## ---- fig-truncation ----
tr_df <- data.frame(est = 100 * tr_draws)
tr_df$side <- ifelse(tr_df$est < 0, "below zero", "at or above zero")
lab_x <- min(tr_df$est)

ggplot(tr_df, aes(est, fill = side)) +
  geom_histogram(binwidth = 0.4, colour = NA) +
  geom_vline(xintercept = 0, colour = te_pal$ink, linewidth = 0.6) +
  geom_vline(xintercept = 100 * tr_tab$trunc_mean[1],
             colour = te_pal$gold, linewidth = 1) +
  geom_vline(xintercept = 100 * tr_tab$q90_trunc[1], linetype = "22",
             colour = te_pal$ink, linewidth = 0.7) +
  annotate("text", x = lab_x, y = Inf, vjust = 1.7, hjust = 0, size = 3.2,
           colour = te_pal$ink, label = "solid dark line: the truth, zero") +
  annotate("text", x = lab_x, y = Inf, vjust = 3.3, hjust = 0, size = 3.2,
           colour = "#9c7a1f", label = "gold line: mean after truncation") +
  annotate("text", x = lab_x, y = Inf, vjust = 4.9, hjust = 0, size = 3.2,
           colour = te_pal$ink,
           label = "dashed line: ninetieth percentile after truncation") +
  scale_fill_manual(values = c("below zero" = te_pal$clay,
                               "at or above zero" = te_pal$green),
                    name = NULL) +
  labs(x = "corrected prevalence (per cent)",
       y = "surveys out of four thousand",
       title = "What a disease-free population reports") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 16, 4, 8))

## ---- design-formula ----
req_n <- function(p, se, sp, nneg, pow = 0.8) {
  ap1 <- ap_of(p, se, sp)
  sig_target <- p * (se + sp - 1) / (zc + qnorm(pow))
  budget <- sig_target^2 - sp * (1 - sp) / nneg
  ifelse(budget <= 0, NA_real_, ap1 * (1 - ap1) / budget)
}

min_neg <- function(p, se, sp, pow = 0.8) {
  sp * (1 - sp) / (p * (se + sp - 1) / (zc + qnorm(pow)))^2
}
pow_ceiling <- function(p, se, sp, nneg) {
  pnorm(p * (se + sp - 1) / sqrt(sp * (1 - sp) / nneg) - zc)
}

sp_show <- c(0.95, 0.96, 0.97, 0.98, 0.99, 0.995, 0.999)
des_tab <- data.frame(
  specificity = sp_show,
  n_if_known = req_n(p_true, se_true, sp_show, Inf),
  n_val_2000 = req_n(p_true, se_true, sp_show, 2000),
  n_val_500 = req_n(p_true, se_true, sp_show, 500),
  n_val_100 = req_n(p_true, se_true, sp_show, 100),
  min_negatives = min_neg(p_true, se_true, sp_show),
  ceiling_100 = pow_ceiling(p_true, se_true, sp_show, 100))
print(transform(round(des_tab, 2), specificity = sp_show))

sp_break <- uniroot(function(s) min_neg(p_true, se_true, s) - n_val_neg,
                    c(0.98, 0.9999))$root
sp_for_480 <- uniroot(function(s) req_n(p_true, se_true, s, Inf) - n_survey,
                      c(0.98, 0.9999))$root
print(round(c(specificity_making_100_negatives_enough = sp_break,
              specificity_making_480_animals_enough = sp_for_480,
              min_negatives_at_design_spec = min_neg(p_true, se_true, sp_true),
              power_ceiling_at_design_spec =
                pow_ceiling(p_true, se_true, sp_true, n_val_neg)), 5))

## ---- fig-design ----
sp_fine <- seq(0.95, 0.999, length.out = 400)
val_lab <- c("100 validation negatives", "500 validation negatives",
             "2000 validation negatives", "specificity known exactly")
des_long <- do.call(rbind, Map(function(nn, lb)
  data.frame(sp = sp_fine, n_need = req_n(p_true, se_true, sp_fine, nn),
             panel = factor(lb, levels = val_lab)),
  list(100, 500, 2000, Inf), val_lab))
des_long <- des_long[is.finite(des_long$n_need) &
                       des_long$n_need <= 12000, ]

ggplot(des_long, aes(sp, n_need, colour = panel)) +
  geom_hline(yintercept = n_survey, linetype = "22",
             colour = te_pal$ink, linewidth = 0.5) +
  geom_line(linewidth = 0.95) +
  scale_y_log10(breaks = c(500, 1000, 2000, 5000, 10000),
                labels = c("500", "1000", "2000", "5000", "10000")) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold,
                                 te_pal$sage, te_pal$forest), name = NULL) +
  guides(colour = guide_legend(nrow = 2, byrow = TRUE)) +
  labs(x = "specificity of the test",
       y = "animals needed (log scale)",
       title = "Below a specificity floor, no sample size works") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 16, 4, 8))

## ---- design-check ----
sim_reject <- function(nn, nneg, p_at, reps = 40000, seed = 4400) {
  set.seed(seed)
  ap_d <- rbinom(reps, nn, ap_of(p_at, se_true, sp_true)) / nn
  se_d <- rbinom(reps, n_val_pos, se_true) / n_val_pos
  sp_d <- if (is.finite(nneg)) rbinom(reps, nneg, sp_true) / nneg else
    rep(sp_true, reps)
  nv <- if (is.finite(nneg)) nneg else 1e12
  ph <- rg_of(ap_d, se_d, sp_d)
  mean(ph - zc * delta_sd(ap_d, se_d, sp_d, nn, n_val_pos, nv) > 0)
}

n_formula <- ceiling(req_n(p_true, se_true, sp_true, Inf))
pow_grid <- c(650, 700, 750, 800, n_formula)
print(rbind(animals = pow_grid,
            power = round(vapply(pow_grid,
                                 function(nn) sim_reject(nn, Inf, p_true),
                                 numeric(1)), 4)))

size_grid <- c(100, 250, 500, 1000, 2000)
print(rbind(validation_negatives = size_grid,
            size_at_p_zero = round(vapply(size_grid,
                                          function(nv) sim_reject(n_survey, nv, 0),
                                          numeric(1)), 4)))
print(round(c(size_with_known_specificity = sim_reject(n_survey, Inf, 0)), 4))

n_formula_500 <- ceiling(req_n(p_true, se_true, sp_true, 500))
pow_500 <- sim_reject(n_formula_500, 500, p_true)
pow_limit <- sim_reject(1e6, n_val_neg, p_true)
print(round(c(animals_formula_500_negatives = n_formula_500,
              power_there = pow_500,
              ceiling_normal_approx = pow_ceiling(p_true, se_true, sp_true, n_val_neg),
              power_at_a_million_animals = pow_limit), 4))
