# Sequential sampling for pest decisions
# https://tidyecology.com/posts/sequential-sampling-for-pest-decisions/
#
# 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-14

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

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))
}

## ---- boundaries ----
m0 <- 2
m1 <- 4
alpha_err <- 0.10
beta_err  <- 0.10
k_assumed <- 2
n_max     <- 60

a_up <- log((1 - beta_err) / alpha_err)
b_lo <- log(beta_err / (1 - alpha_err))

llr_coef <- function(k_plan) log(m1 * (k_plan + m0) / (m0 * (k_plan + m1)))
slope_of <- function(k_plan) k_plan * log((k_plan + m1) / (k_plan + m0)) / llr_coef(k_plan)

h_upper <- a_up / llr_coef(k_assumed)
h_lower <- b_lo / llr_coef(k_assumed)
s_slope <- slope_of(k_assumed)

set.seed(5207)
x_check   <- rnbinom(25, size = k_assumed, mu = 3)
llr_exact <- cumsum(dnbinom(x_check, size = k_assumed, mu = m1, log = TRUE) -
                    dnbinom(x_check, size = k_assumed, mu = m0, log = TRUE))
llr_line  <- llr_coef(k_assumed) * (cumsum(x_check) - s_slope * seq_along(x_check))
llr_gap   <- max(abs(llr_exact - llr_line))

h_upper_k05 <- a_up / llr_coef(0.5)
s_slope_k05 <- slope_of(0.5)

## ---- fp-guard-1 ----
stopifnot(llr_gap / max(1, abs(llr_exact)) < 1e-10)

## ---- fig-walks ----
walk_one <- function(m, id) {
  x_w  <- rnbinom(n_max, size = k_assumed, mu = m)
  tot  <- cumsum(x_w)
  dev  <- tot - s_slope * seq_len(n_max)
  hit  <- which(dev >= h_upper | dev <= h_lower)[1]
  if (is.na(hit)) hit <- n_max
  data.frame(plant = 0:hit, total = c(0, tot[seq_len(hit)]),
             field = id, true_mean = paste("true mean", m))
}
set.seed(3118)
walk_df <- do.call(rbind, c(lapply(1:6, function(i) walk_one(m0, paste0("a", i))),
                            lapply(1:6, function(i) walk_one(m1, paste0("b", i)))))
walk_end <- do.call(rbind, lapply(split(walk_df, walk_df$field), function(d) d[nrow(d), ]))
n_show   <- max(walk_df$plant) + 2
line_df  <- data.frame(plant = c(0, -h_lower / s_slope, n_show))  # include the point where the lower line crosses zero

ggplot(walk_df, aes(plant, total)) +
  geom_ribbon(data = line_df, aes(x = plant, ymin = pmax(h_lower + s_slope * plant, 0),
                                  ymax = h_upper + s_slope * plant),
              inherit.aes = FALSE, fill = te_line, alpha = 0.6) +
  geom_abline(intercept = h_upper, slope = s_slope, colour = te_rust, linewidth = 0.8) +
  geom_abline(intercept = h_lower, slope = s_slope, colour = te_forest, linewidth = 0.8) +
  geom_step(aes(group = field, colour = true_mean), linewidth = 0.6) +
  geom_point(data = walk_end, aes(colour = true_mean), size = 2) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  coord_cartesian(xlim = c(0, n_show), ylim = c(0, NA)) +
  labs(x = "plants examined", y = "running total of insects",
       title = "Stop at the first crossing",
       subtitle = "red line: treat; green line: do not treat; grey band: keep counting") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- simulate ----
run_plan <- function(m, k_true, n_run, k_plan = k_assumed) {
  h_up <- a_up / llr_coef(k_plan)
  h_lo <- b_lo / llr_coef(k_plan)
  slp  <- slope_of(k_plan)
  counts <- matrix(rnbinom(n_run * n_max, size = k_true, mu = m), n_run)
  dev    <- t(apply(counts, 1, cumsum)) -
            matrix(slp * seq_len(n_max), n_run, n_max, byrow = TRUE)
  up_hit <- dev >= h_up
  lo_hit <- dev <= h_lo
  first_up <- ifelse(rowSums(up_hit) > 0, max.col(up_hit, "first"), n_max + 1)
  first_lo <- ifelse(rowSums(lo_hit) > 0, max.col(lo_hit, "first"), n_max + 1)
  capped   <- first_up > n_max & first_lo > n_max
  stop_n   <- pmin(first_up, first_lo, n_max)
  treat    <- ifelse(capped, dev[, n_max] > 0, first_up < first_lo)
  c(p_treat = mean(treat), asn = mean(stop_n),
    asn_se = sd(stop_n) / sqrt(n_run), capped = mean(capped))
}

wald_approx <- function(m, k_true, k_plan = k_assumed) {
  cf   <- llr_coef(k_plan)
  cc   <- cf * slope_of(k_plan)
  ez   <- cf * m - cc
  mgf1 <- function(h) (1 + m * (1 - exp(h * cf)) / k_true)^(-k_true) * exp(-h * cc) - 1
  h_cap <- log(1 + k_true / m) / cf
  h_root <- if (ez < 0) uniroot(mgf1, c(1e-6, h_cap * (1 - 1e-9)))$root else
                        uniroot(mgf1, c(-50, -1e-6))$root
  p_no  <- (exp(h_root * a_up) - 1) / (exp(h_root * a_up) - exp(h_root * b_lo))
  p_tr  <- 1 - p_no
  c(p_treat = p_tr, asn = (p_tr * a_up + (1 - p_tr) * b_lo) / ez)
}

n_run  <- 4000
m_grid <- seq(1, 6, by = 0.5)
k_grid <- c(4, 2, 1, 0.5)
taylor_a <- 2
taylor_b <- 1.5
k_taylor <- function(m) m^2 / (taylor_a * m^taylor_b - m)

scen <- rbind(expand.grid(m = m_grid, scenario = paste("k =", k_grid),
                          stringsAsFactors = FALSE),
              data.frame(m = m_grid, scenario = "Taylor law"))
is_taylor   <- scen$scenario == "Taylor law"
scen$k_true <- k_taylor(scen$m)
scen$k_true[!is_taylor] <- as.numeric(sub("k = ", "", scen$scenario[!is_taylor]))

set.seed(8841)
sim_tab  <- t(mapply(run_plan, scen$m, scen$k_true, MoreArgs = list(n_run = n_run)))
wald_tab <- t(mapply(wald_approx, scen$m, scen$k_true))
res <- cbind(scen, as.data.frame(sim_tab),
             wald_treat = wald_tab[, "p_treat"], wald_asn = wald_tab[, "asn"])
res$asn_miss <- (res$asn - res$wald_asn) / res$asn

pick <- function(sc, m) res[res$scenario == sc & res$m == m, ]
r2_0 <- pick("k = 2", m0);  r2_1 <- pick("k = 2", m1);  r2_mid <- pick("k = 2", 3)
r05_0 <- pick("k = 0.5", m0); r05_1 <- pick("k = 0.5", m1); r05_mid <- pick("k = 0.5", 3)
mc_se_err <- sqrt(0.1 * 0.9 / n_run)
miss_right <- range(res$asn_miss[res$scenario == "k = 2" & res$m %in% c(m0, 3, m1)])
miss_wrong <- range(res$asn_miss[res$scenario == "k = 0.5" & res$m %in% c(m0, 3, m1)])
cap_max <- max(res$capped)
miss_all <- range(res$asn_miss)
r1_0 <- pick("k = 1", m0); r1_1 <- pick("k = 1", m1)

## ---- fig-asn ----
asn_df <- res[res$scenario %in% c("k = 4", "k = 2", "k = 1", "k = 0.5"), ]
asn_df$scenario <- factor(asn_df$scenario, levels = paste("k =", k_grid))
asn_long <- rbind(data.frame(asn_df[, c("m", "scenario")], asn = asn_df$asn, source = "simulated"),
                  data.frame(asn_df[, c("m", "scenario")], asn = asn_df$wald_asn, source = "Wald approximation"))

ggplot(asn_long, aes(m, asn, colour = source, linetype = source)) +
  geom_vline(xintercept = c(m0, m1), colour = te_line, linewidth = 0.6) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.6) +
  facet_wrap(~ scenario, nrow = 1, labeller = labeller(scenario = function(s) paste("true", s))) +
  scale_colour_manual(values = c("simulated" = te_forest, "Wald approximation" = te_gold), name = NULL) +
  scale_linetype_manual(values = c("simulated" = "solid", "Wald approximation" = "dashed"), name = NULL) +
  scale_x_continuous(breaks = c(1, 2, 3, 4, 5, 6)) +
  labs(x = "true mean insects per plant", y = "average plants examined",
       title = "The closed form undercounts the plants",
       subtitle = "plan boundaries drawn for k = 2 in every panel; 4000 fields per point") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- taylor ----
tay_0 <- pick("Taylor law", m0)
tay_1 <- pick("Taylor law", m1)
k_tay_0 <- k_taylor(m0)
k_tay_1 <- k_taylor(m1)

## ---- fig-oc ----
oc_df <- res
oc_df$scenario <- factor(oc_df$scenario, levels = c(paste("k =", k_grid), "Taylor law"))
oc_cols <- c("k = 4" = "#8fa89a", "k = 2" = te_forest, "k = 1" = te_gold,
             "k = 0.5" = te_rust, "Taylor law" = te_ink)

ggplot(oc_df, aes(m, p_treat, colour = scenario)) +
  annotate("rect", xmin = m0, xmax = m1, ymin = -Inf, ymax = Inf, fill = te_line, alpha = 0.35) +
  geom_line(aes(y = wald_treat), linetype = "dashed", linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.7) +
  geom_hline(yintercept = c(alpha_err, 1 - beta_err), linetype = "dotted", colour = te_body) +
  scale_colour_manual(values = oc_cols, name = "true aggregation") +
  scale_x_continuous(breaks = 1:6) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "true mean insects per plant", y = "probability of treating the field",
       title = "Clumping flattens the decision curve",
       subtitle = "solid: simulated; dashed: Wald; dotted: nominal 0.1 and 0.9 at means 2 and 4") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- fixedn ----
fixed_design <- function(k_plan, e0, e1) {
  for (n in 1:400) {
    cuts <- 0:(20 * n)
    ok <- which(pnbinom(cuts, size = n * k_plan, mu = n * m0, lower.tail = FALSE) <= e0 &
                pnbinom(cuts, size = n * k_plan, mu = n * m1) <= e1)
    if (length(ok) > 0) return(c(n = n, cut = cuts[ok[1]]))
  }
}
fixed_err <- function(plan, k_true) {
  c(err0 = pnbinom(plan[["cut"]], size = plan[["n"]] * k_true, mu = plan[["n"]] * m0,
                   lower.tail = FALSE),
    err1 = pnbinom(plan[["cut"]], size = plan[["n"]] * k_true, mu = plan[["n"]] * m1))
}

plan_nom  <- fixed_design(k_assumed, alpha_err, beta_err)
fix_k2    <- fixed_err(plan_nom, k_assumed)
fix_k05   <- fixed_err(plan_nom, 0.5)
plan_real <- fixed_design(k_assumed, r2_0$p_treat, 1 - r2_1$p_treat)

save_nom  <- 1 - c(r2_0$asn, r2_1$asn) / plan_nom[["n"]]
save_real <- 1 - c(r2_0$asn, r2_1$asn) / plan_real[["n"]]
save_mid_nom  <- 1 - r2_mid$asn / plan_nom[["n"]]
save_mid_real <- 1 - r2_mid$asn / plan_real[["n"]]
se_diff <- function(p) sqrt(p * (1 - p) / n_run)
z_safe <- (r05_0$p_treat - fix_k05[["err0"]]) / se_diff(r05_0$p_treat)
z_inf  <- ((1 - r05_1$p_treat) - fix_k05[["err1"]]) / se_diff(1 - r05_1$p_treat)

## ---- fig-fixed ----
cmp_df <- data.frame(
  plan   = rep(c("sequential", "fixed n"), each = 4),
  truth  = rep(rep(c("true k = 2", "true k = 0.5"), each = 2), 2),
  field  = rep(c("safe field, mean 2", "infested field, mean 4"), 4),
  wrong  = c(r2_0$p_treat, 1 - r2_1$p_treat, r05_0$p_treat, 1 - r05_1$p_treat,
             fix_k2[["err0"]], fix_k2[["err1"]], fix_k05[["err0"]], fix_k05[["err1"]]),
  plants = c(r2_0$asn, r2_1$asn, r05_0$asn, r05_1$asn, rep(plan_nom[["n"]], 4)))
cmp_df$truth <- factor(cmp_df$truth, levels = c("true k = 2", "true k = 0.5"))
cmp_df$field <- factor(cmp_df$field, levels = c("safe field, mean 2", "infested field, mean 4"))

ggplot(cmp_df, aes(plants, wrong, colour = plan, shape = truth)) +
  geom_hline(yintercept = alpha_err, linetype = "dotted", colour = te_body) +
  geom_line(aes(group = plan), colour = te_line, linewidth = 0.6) +
  geom_point(size = 3.2) +
  facet_wrap(~ field) +
  scale_colour_manual(values = c("sequential" = te_rust, "fixed n" = te_forest), name = NULL) +
  scale_shape_manual(values = c("true k = 2" = 16, "true k = 0.5" = 17), name = NULL) +
  scale_y_continuous(limits = c(0, NA)) +
  labs(x = "plants examined (average for the sequential plan)",
       y = "probability of the wrong decision",
       title = "Same wrong k, both plans pay",
       subtitle = "dotted: the nominal error of one tenth both plans were designed for") +
  theme_datasheet() +
  theme(legend.position = "bottom", legend.box = "vertical")

## ---- rightk ----
set.seed(6630)
k05_0   <- run_plan(m0, 0.5, n_run, k_plan = 0.5)
k05_mid <- run_plan(3, 0.5, n_run, k_plan = 0.5)
k05_1   <- run_plan(m1, 0.5, n_run, k_plan = 0.5)
plan_k05 <- fixed_design(0.5, alpha_err, beta_err)
fix_k05_right <- fixed_err(plan_k05, 0.5)
ratio_seq <- c(k05_0[["asn"]] / r2_0$asn, k05_mid[["asn"]] / r2_mid$asn, k05_1[["asn"]] / r2_1$asn)
ratio_fix <- plan_k05[["n"]] / plan_nom[["n"]]

## ---- walk-gradient ----
edge_ratio <- c(1, 1.6, 2.7)
n_plants   <- 400
depth      <- (seq_len(n_plants) - 1) / (n_plants - 1)
field_mu   <- function(ratio) { w <- ratio^(-depth); m0 * w / mean(w) }
s_top <- ceiling(h_upper + s_slope * n_max) + 1  # any total above this has crossed the upper line

# exact P(treat) and ASN of the k = 2 plan for plant means mu[1..60], by recursion on the total
plan_exact <- function(mu) {
  dist <- c(1, numeric(s_top)); p_tr <- 0; asn <- 0; tot <- 0:s_top
  for (n in seq_len(n_max)) {
    asn <- asn + sum(dist)
    px <- dnbinom(0:s_top, size = k_assumed, mu = mu[n])
    nd <- numeric(s_top + 1)
    for (i in which(dist > 0)) {
      nd[i:(s_top + 1)] <- nd[i:(s_top + 1)] + dist[i] * px[1:(s_top + 2 - i)]
      p_tr <- p_tr + dist[i] * pnbinom(s_top + 1 - i, k_assumed, mu = mu[n], lower.tail = FALSE)
    }
    dev <- tot - s_slope * n
    up  <- if (n < n_max) dev >= h_upper else dev > 0
    p_tr <- p_tr + sum(nd[up])
    nd[up | dev <= h_lower] <- 0
    dist <- nd
  }
  c(p_treat = p_tr, asn = asn)
}
# exact P(treat) of the fixed plan: P(total > cut) for plant means mu
fixed_exact <- function(mu) {
  d <- c(1, numeric(plan_nom[["cut"]]))
  for (m in mu) {
    px <- dnbinom(0:plan_nom[["cut"]], size = k_assumed, mu = m)
    d  <- sapply(seq_along(d), function(j) sum(d[1:j] * px[j:1]))
  }
  1 - sum(d)
}

leg <- function(n_leg) 1 - abs(((seq_len(n_max) - 1) / n_leg) %% 2 - 1)
paths <- list("straight, 1 plant apart" = 1:n_max,
              "straight, 5 plants apart" = seq(1, by = 5, length.out = n_max),
              "V, legs of 30 stops" = 1 + round(leg(30) * (n_plants - 1)),
              "W, legs of 15 stops" = 1 + round(leg(15) * (n_plants - 1)))
fixed_idx <- round(seq(1, n_plants, length.out = plan_nom[["n"]]))

walk_tab <- do.call(rbind, lapply(edge_ratio, function(r) {
  mu <- field_mu(r)
  seq_res <- t(sapply(paths, function(p) {
    ex <- plan_exact(mu[p])
    loc <- mean(mu[p][seq_len(round(ex[["asn"]]))])
    c(ex, local_mean = loc, oc_local = plan_exact(rep(loc, n_max))[["p_treat"]])
  }))
  data.frame(ratio = r, path = c(names(paths), "fixed plan, spread"),
             rbind(seq_res, c(fixed_exact(mu[fixed_idx]), plan_nom[["n"]], NA, NA)),
             row.names = NULL)
}))
walk_tab$path <- factor(walk_tab$path, levels = unique(walk_tab$path))
flat_check <- plan_exact(rep(m0, n_max))
fixed_edge <- fixed_exact(field_mu(2.7)[seq_len(plan_nom[["n"]])])  # the fixed plan with its plants taken at the edge
wget <- function(r, p, col) walk_tab[walk_tab$ratio == r & walk_tab$path == p, col]
seq_rows <- walk_tab$ratio > 1 & !is.na(walk_tab$oc_local)
gap_row  <- walk_tab$p_treat - walk_tab$oc_local
near_rows <- seq_rows & walk_tab$path %in% c("straight, 1 plant apart", "W, legs of 15 stops")
# a field at the infested mean with the same 2.7 gradient, straight walk 1 plant apart
mu_inf <- field_mu(2.7) * m1 / m0
entry_inf <- c(sparse = plan_exact(rev(mu_inf)[seq_len(n_max)])[["p_treat"]],
               edge = plan_exact(mu_inf[seq_len(n_max)])[["p_treat"]], flat = plan_exact(rep(m1, n_max))[["p_treat"]])
print(round(xtabs(p_treat ~ path + ratio, walk_tab), 3))
