# Testing your analysis code
# https://tidyecology.com/posts/testing-your-analysis-code/
#
# 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-15

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

## ---- runner ----
run_new <- function() data.frame(check = character(0), passed = logical(0),
                                 stringsAsFactors = FALSE)

expect <- function(run, check, condition) {
  passed <- tryCatch(isTRUE(condition), error = function(e) FALSE,
                     warning = function(w) FALSE)
  rbind(run, data.frame(check = check, passed = passed, stringsAsFactors = FALSE))
}

near <- function(a, b, tol = 1e-8) {
  if (length(a) != length(b)) return(FALSE)
  if (any(is.na(a) != is.na(b))) return(FALSE)
  d <- abs(a[!is.na(a)] - b[!is.na(b)])
  length(d) == 0 || all(!is.na(d) & d <= tol)
}

report <- function(run, label) {
  bad <- run$check[!run$passed]
  cat(label, ":", sum(run$passed), "of", nrow(run), "checks passed")
  if (length(bad) > 0) cat(" | failed:", paste(bad, collapse = "; "))
  cat("\n")
  invisible(length(bad) == 0)
}

runner_lines <- length(deparse(run_new)) + length(deparse(expect)) +
  length(deparse(near)) + length(deparse(report))
c(runner_lines = runner_lines)

demo <- run_new()
demo <- expect(demo, "an even pair of species has diversity log two",
               near(-sum(c(0.5, 0.5) * log(c(0.5, 0.5))), log(2)))
demo <- expect(demo, "a deliberately wrong claim", near(1 + 1, 3))
demo <- expect(demo, "a check that throws an error", near(log("a"), 0))
print(demo)
report(demo, "demonstration")

cat(tryCatch({ stopifnot(near(1 + 1, 3)); "no failure" },
             error = function(e) conditionMessage(e)), "\n")

## ---- field-data ----
set.seed(20260810)
n_site <- 12
n_spec <- 10
wetness <- seq(0, 1, length.out = n_site)
thresh <- seq(-0.25, 0.85, length.out = n_spec)
lambda <- outer(wetness, thresh, function(w, th) 8 * pmax(0, w - th + 0.25))
true_counts <- matrix(rpois(n_site * n_spec, lambda), n_site, n_spec)
effort <- round(runif(n_site, 0.8, 1.6), 2)

p_miss <- 0.05 + 0.35 * wetness
gaps <- matrix(runif(n_site * n_spec), n_site, n_spec) < p_miss
obs_counts <- true_counts
obs_counts[gaps] <- NA

true_rich <- apply(true_counts, 1, function(x) sum(x > 0))
round(c(sites = n_site, species = n_spec,
        missing_probability_dry_end = p_miss[1],
        missing_probability_wet_end = p_miss[n_site],
        cells_missing_percent = 100 * mean(gaps),
        richness_at_the_dry_end = true_rich[1],
        richness_at_the_wet_end = true_rich[n_site]), 2)

## ---- na-drop ----
richness_naive <- function(x) sum(x > 0, na.rm = TRUE)
total_naive    <- function(x) sum(x, na.rm = TRUE)
richness_flag  <- function(x) if (anyNA(x)) NA_real_ else sum(x > 0)

gap_site <- c(4, NA, 6, 0)
c(naive_total = total_naive(gap_site),
  naive_richness = richness_naive(gap_site),
  flagged_richness = richness_flag(gap_site))

naive_rich <- apply(obs_counts, 1, richness_naive)
flag_rich  <- apply(obs_counts, 1, richness_flag)

pair_flip <- function(a, b) {
  ij <- which(upper.tri(matrix(0, length(a), length(a))), arr.ind = TRUE)
  da <- sign(a[ij[, 1]] - a[ij[, 2]])
  db <- sign(b[ij[, 1]] - b[ij[, 2]])
  100 * mean(da * db < 0)
}

slope_true  <- coef(lm(true_rich ~ wetness))
slope_naive <- coef(lm(naive_rich ~ wetness))
round(c(mean_true_richness = mean(true_rich),
        mean_naive_richness = mean(naive_rich),
        mean_shortfall_species = mean(true_rich - naive_rich),
        true_slope_species_per_unit_wetness = slope_true[2],
        naive_slope_species_per_unit_wetness = slope_naive[2],
        slope_attenuation_percent = 100 * (1 - slope_naive[2] / slope_true[2]),
        site_pairs = choose(n_site, 2),
        pairs_reversed_percent = pair_flip(true_rich, naive_rich),
        spearman = cor(true_rich, naive_rich, method = "spearman"),
        sites_the_flagged_version_refuses = sum(is.na(flag_rich))), 4)

na_run <- run_new()
na_run <- expect(na_run, "a partly counted site has an unknown richness",
                 is.na(richness_flag(gap_site)))
na_run <- expect(na_run, "the naive version agrees",
                 is.na(richness_naive(gap_site)))
report(na_run, "missing data")

## ---- fig-missing ----
mis_df <- data.frame(wetness = rep(wetness, 2),
                     richness = c(true_rich, naive_rich),
                     source = factor(rep(c("True richness", "Reported with na.rm"),
                                         each = n_site),
                                     levels = c("True richness", "Reported with na.rm")))
seg_df <- data.frame(wetness = wetness, lo = naive_rich, hi = true_rich)
fit_df <- data.frame(intercept = c(slope_true[1], slope_naive[1]),
                     slope = c(slope_true[2], slope_naive[2]),
                     source = factor(c("True richness", "Reported with na.rm"),
                                     levels = levels(mis_df$source)))

ggplot(mis_df, aes(wetness, richness)) +
  geom_segment(data = seg_df, aes(x = wetness, xend = wetness, y = lo, yend = hi),
               inherit.aes = FALSE, colour = te_pal$line, linewidth = 1.4) +
  geom_abline(data = fit_df, aes(intercept = intercept, slope = slope, colour = source),
              linewidth = 0.9, show.legend = FALSE) +
  geom_point(aes(shape = source, colour = source), size = 3.4, stroke = 1.1) +
  scale_shape_manual(values = c(1, 16), name = NULL) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay), name = NULL) +
  scale_y_continuous(breaks = seq(0, 10, 2)) +
  coord_cartesian(ylim = c(0, 11)) +
  labs(x = "Site wetness (dry to wet)", y = "Species recorded",
       title = "Dropping missing counts costs most where the survey was hardest") +
  theme_te() +
  theme(legend.position = "top")

## ---- cover-units ----
set.seed(41)
n_quad <- 40
n_cov  <- 6
wts <- matrix(rgamma(n_quad * n_cov, shape = 0.9), n_quad, n_cov)
tot_cover <- runif(n_quad, 0.35, 0.92)
cover_frac <- wts / rowSums(wts) * tot_cover
cover_pct  <- 100 * cover_frac
sla <- c(9.5, 14.2, 21.8, 12.4, 27.1, 17.6)
mass_per_cover <- c(480, 260, 150, 330, 110, 200)

bare_ground <- function(cov) pmax(0, 1 - rowSums(cov))
cwm_sla     <- function(cov) rowSums(cov * rep(sla, each = nrow(cov))) / rowSums(cov)
standing_biomass <- function(cov) rowSums(cov * rep(mass_per_cover, each = nrow(cov)))

right <- list(bare = bare_ground(cover_frac), cwm = cwm_sla(cover_frac),
              mass = standing_biomass(cover_frac))
wrong <- list(bare = bare_ground(cover_pct), cwm = cwm_sla(cover_pct),
              mass = standing_biomass(cover_pct))

rel_err <- function(a, b) 100 * max(abs(a - b) / pmax(abs(b), 1e-12))
round(c(quadrats = n_quad,
        true_mean_bare_ground = mean(right$bare),
        reported_mean_bare_ground = mean(wrong$bare),
        quadrats_reported_as_fully_covered = sum(wrong$bare == 0),
        cwm_max_error_percent = rel_err(wrong$cwm, right$cwm),
        biomass_max_error_percent = rel_err(wrong$mass, right$mass)), 4)

unit_run <- run_new()
unit_run <- expect(unit_run, "cover values are fractions between zero and one",
                   all(cover_pct >= 0 & cover_pct <= 1))
unit_run <- expect(unit_run, "quadrat cover totals do not exceed one",
                   all(rowSums(cover_pct) <= 1))
unit_run <- expect(unit_run, "the same two checks on the fractions",
                   all(cover_frac >= 0 & cover_frac <= 1) &&
                     all(rowSums(cover_frac) <= 1))
report(unit_run, "units")

## ---- fig-units ----
unit_lab <- c("Community weighted\nmean of leaf area",
              "Standing biomass\n(grams per quadrat)",
              "Bare ground\n(fraction)")
unit_df <- data.frame(
  correct = c(right$cwm, right$mass, right$bare),
  reported = c(wrong$cwm, wrong$mass, wrong$bare),
  panel = factor(rep(unit_lab, each = n_quad), levels = unit_lab))
span <- do.call(rbind, lapply(unit_lab, function(k) {
  z <- unit_df[unit_df$panel == k, c("correct", "reported")]
  data.frame(v = range(c(0, unlist(z))), panel = factor(k, levels = unit_lab))
}))

ggplot(unit_df, aes(correct, reported)) +
  geom_blank(data = span, aes(v, v)) +
  geom_abline(slope = 1, intercept = 0, linetype = 2, colour = te_pal$sage,
              linewidth = 0.8) +
  geom_point(colour = te_pal$clay, size = 2.2, alpha = 0.85) +
  facet_wrap(~panel, scales = "free") +
  labs(x = "Value computed from cover fractions",
       y = "Value reported from percentages",
       title = "One unit error, three completely different consequences") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold", size = 9))

## ---- target ----
ref_src <- c(
  "site_stats <- function(counts, effort) {",
  "  ns <- nrow(counts)",
  "  out <- matrix(NA_real_, ns, 4)",
  "  for (i in seq_len(ns)) {",
  "    x <- counts[i, ]",
  "    n <- sum(x, na.rm = FALSE)",
  "    s <- sum(x > 0)",
  "    f1 <- sum(x == 1)",
  "    f2 <- sum(x == 2)",
  "    chao <- s + f1 * (f1 - 1) / (2 * (f2 + 1))",
  "    p <- x[x > 0] / n",
  "    h <- -sum(p * log(p))",
  "    out[i, ] <- c(n / effort[i], s, chao, h)",
  "  }",
  "  colnames(out) <- c('density', 'richness', 'chao1', 'shannon')",
  "  out",
  "}")
ref_txt <- paste(ref_src, collapse = "\n")

compile_fun <- function(txt) {
  env <- new.env(parent = globalenv())
  eval(parse(text = txt), envir = env)
  get("site_stats", envir = env)
}
site_stats <- compile_fun(ref_txt)
stat_names <- c("density", "richness", "chao1", "shannon")

c(target_lines = length(ref_src))
print(round(site_stats(true_counts, effort), 4))

## ---- mutants ----
ops <- data.frame(rbind(
  c("relational", "x > 0", "x >= 0"),
  c("constant", "x > 0", "x > 1"),
  c("constant", "== 1", "== 2"),
  c("constant", "== 2", "== 1"),
  c("relational", "sum(x == 2)", "sum(x >= 2)"),
  c("relational", "sum(x == 1)", "sum(x <= 1)"),
  c("sign", "s + f1", "s - f1"),
  c("sign", "f1 - 1", "f1 + 1"),
  c("sign", "f2 + 1", "f2 - 1"),
  c("sign", "-sum(p * log(p))", "sum(p * log(p))"),
  c("constant", "2 * (f2 + 1)", "(f2 + 1)"),
  c("arithmetic", "chao <- s + ", "chao <- s * "),
  c("arithmetic", "] / n", "] * n"),
  c("arithmetic", "n / effort[i]", "n * effort[i]"),
  c("arithmetic", "p * log(p)", "p + log(p)"),
  c("arithmetic", "sum(p * log(p))", "sum(p) * log(p)"),
  c("arithmetic", "log(p)", "log2(p)"),
  c("index shift", "seq_len(ns)", "seq_len(ns - 1)"),
  c("index shift", "seq_len(ns)", "seq_len(ns + 1)"),
  c("index shift", "counts[i, ]", "counts[i - 1, ]"),
  c("index shift", "counts[i, ]", "counts[i + 1, ]"),
  c("index shift", "x[x > 0] / n", "x[x > 0][-1] / n"),
  c("aggregate", "sum(x > 0)", "mean(x > 0)"),
  c("aggregate", "sum(x, na.rm = FALSE)", "mean(x, na.rm = FALSE)"),
  c("missing data", "na.rm = FALSE", "na.rm = TRUE"),
  c("variable swap", "f1 * (f1 - 1)", "f1 * (f2 - 1)"),
  c("structure", "nrow(counts)", "ncol(counts)"),
  c("structure", "matrix(NA_real_, ns, 4)", "matrix(NA_real_, 4, ns)"),
  c("structure", "c(n / effort[i], s, chao, h)", "c(n / effort[i], chao, s, h)"),
  c("structure", "colnames(out) <-", "rownames(out) <-")),
  stringsAsFactors = FALSE)
names(ops) <- c("family", "from", "to")

mutate_at <- function(txt, from, to, k) {
  g <- gregexpr(from, txt, fixed = TRUE)[[1]]
  st <- g[k]
  en <- st + attr(g, "match.length")[k] - 1
  paste0(substr(txt, 1, st - 1), to, substr(txt, en + 1, nchar(txt)))
}

mut <- do.call(rbind, lapply(seq_len(nrow(ops)), function(r) {
  g <- gregexpr(ops$from[r], ref_txt, fixed = TRUE)[[1]]
  if (g[1] == -1) return(NULL)
  data.frame(family = ops$family[r], op = paste(ops$from[r], "to", ops$to[r]),
             site = seq_along(g),
             src = sapply(seq_along(g), function(k)
               mutate_at(ref_txt, ops$from[r], ops$to[r], k)),
             stringsAsFactors = FALSE)
}))
mut <- mut[!duplicated(mut$src), ]
rownames(mut) <- NULL
n_mut <- nrow(mut)
c(operators = nrow(ops), mutants = n_mut)
print(table(mut$family))

## ---- battery ----
set.seed(907)
n_batt <- 300
battery <- lapply(seq_len(n_batt), function(b) {
  ns <- sample(3:8, 1)
  sp <- sample(3:9, 1)
  cm <- matrix(rpois(ns * sp, sample(c(0.6, 1.4, 3.5), 1)), ns, sp)
  if (runif(1) < 0.3) cm[sample(length(cm), max(1, round(0.12 * length(cm))))] <- NA
  list(counts = cm, effort = round(runif(ns, 0.5, 2), 2))
})

safe_out <- function(fun, case) {
  tryCatch(fun(case$counts, case$effort),
           error = function(e) "stopped", warning = function(w) "stopped")
}
same_out <- function(a, b) {
  if (is.character(a) || is.character(b)) return(identical(a, b))
  if (!identical(dim(a), dim(b)) || !identical(dimnames(a), dimnames(b))) return(FALSE)
  na_a <- is.na(a); na_b <- is.na(b)
  if (!identical(na_a, na_b)) return(FALSE)
  all(abs(a[!na_a] - b[!na_b]) <= 1e-9)
}

ref_battery <- lapply(battery, function(cs) safe_out(site_stats, cs))
mut_funs <- lapply(mut$src, function(s)
  tryCatch(compile_fun(s), error = function(e) NULL))

mut$distinguished <- sapply(seq_len(n_mut), function(m) {
  if (is.null(mut_funs[[m]])) return(TRUE)
  any(!mapply(same_out, lapply(battery, function(cs) safe_out(mut_funs[[m]], cs)),
              ref_battery))
})
mut$stops_everywhere <- sapply(seq_len(n_mut), function(m) {
  if (is.null(mut_funs[[m]])) return(TRUE)
  all(sapply(battery, function(cs)
    identical(safe_out(mut_funs[[m]], cs), "stopped")))
})

round(c(battery_cases = n_batt,
        cases_with_missing_cells = sum(sapply(battery, function(cs)
          anyNA(cs$counts))),
        mutants = n_mut,
        distinguished = sum(mut$distinguished),
        not_distinguished = sum(!mut$distinguished),
        stop_on_every_input = sum(mut$stops_everywhere)), 4)

## ---- suites ----
cnt_main <- true_counts
eff_main <- effort
perm_id  <- c(4, 9, 1, 7, 2, 10, 5, 3, 8, 6)

cnt_known <- rbind(c(5, 5, 0, 0), c(8, 1, 1, 0), c(2, 2, 2, 2))
eff_known <- c(1, 2, 4)
known <- rbind(c(10, 2, 2, log(2)),
               c(5, 3, 4, -(0.8 * log(0.8) + 0.2 * log(0.1))),
               c(2, 4, 4, log(4)))
cnt_even  <- rbind(c(3, 3, 3, 3), c(5, 5, 5, 5))
cnt_mono  <- rbind(c(7, 0, 0, 0), c(0, 0, 4, 0))
eff_small <- c(1, 1)

make_type <- function(cnt, eff) function(fun) {
  run <- run_new()
  out <- fun(cnt, eff)
  run <- expect(run, "a numeric matrix", is.matrix(out) && is.numeric(out))
  run <- expect(run, "one row per site", nrow(out) == nrow(cnt))
  run <- expect(run, "four named columns", identical(colnames(out), stat_names))
  run <- expect(run, "nothing missing", !any(is.na(out)))
  run <- expect(run, "everything finite", all(is.finite(out)))
  run <- expect(run, "richness and density not negative",
                all(out[, "richness"] >= 0) && all(out[, "density"] >= 0))
  run
}

suite_known <- function(fun) {
  run <- run_new()
  out <- fun(cnt_known, eff_known)
  run <- expect(run, "site A by hand", near(as.numeric(out[1, ]), known[1, ]))
  run <- expect(run, "site B by hand", near(as.numeric(out[2, ]), known[2, ]))
  run <- expect(run, "site C by hand", near(as.numeric(out[3, ]), known[3, ]))
  run
}

make_invariant <- function(cnt, eff) function(fun) {
  run <- run_new()
  bs <- fun(cnt, eff)
  run <- expect(run, "species order is irrelevant",
                near(as.numeric(fun(cnt[, perm_id], eff)), as.numeric(bs)))
  run <- expect(run, "doubling counts leaves richness and diversity alone",
                near(as.numeric(fun(2 * cnt, eff)[, c("richness", "shannon")]),
                     as.numeric(bs[, c("richness", "shannon")])))
  run <- expect(run, "halving effort doubles density",
                near(as.numeric(fun(cnt, eff / 2)[, "density"]),
                     2 * as.numeric(bs[, "density"])))
  run <- expect(run, "an unseen species changes nothing",
                near(as.numeric(fun(cbind(cnt, 0), eff)), as.numeric(bs)))
  run <- expect(run, "diversity below the log of richness",
                all(bs[, "shannon"] <= log(bs[, "richness"]) + 1e-8))
  run <- expect(run, "an even community sits on the bound",
                near(as.numeric(fun(cnt_even, eff_small)[, "shannon"]),
                     log(as.numeric(fun(cnt_even, eff_small)[, "richness"]))))
  run <- expect(run, "one species means zero diversity",
                near(as.numeric(fun(cnt_mono, eff_small)[, "shannon"]), c(0, 0)))
  run <- expect(run, "chao1 at least richness",
                all(bs[, "chao1"] >= bs[, "richness"]))
  run
}

suites <- list(Types = make_type(cnt_main, eff_main),
               `Known answer` = suite_known,
               Invariants = make_invariant(cnt_main, eff_main))
for (nm in names(suites)) report(suites[[nm]](site_stats), nm)

suite_catches <- function(suite, fun) {
  if (is.null(fun)) return(TRUE)
  r <- tryCatch(suite(fun), error = function(e) NULL, warning = function(w) NULL)
  if (is.null(r)) return(TRUE)
  any(!r$passed)
}
suite_lines <- sapply(suites, function(s) length(deparse(s)))
suite_checks <- sapply(suites, function(s) nrow(s(site_stats)))
print(rbind(lines = suite_lines, checks = suite_checks))

## ---- kills ----
caught <- sapply(suites, function(s)
  sapply(seq_len(n_mut), function(m) suite_catches(s, mut_funs[[m]])))
colnames(caught) <- names(suites)
keep <- mut$distinguished
caught_any <- apply(caught[keep, ], 1, any)

kill_rate <- 100 * colMeans(caught[keep, ])
per_line <- colSums(caught[keep, ]) / suite_lines
print(round(rbind(mutants_caught = colSums(caught[keep, ]),
                  kill_rate_percent = kill_rate,
                  lines_of_test_code = suite_lines,
                  caught_per_line = per_line), 4))
round(c(distinguishable = sum(keep),
        caught_by_all_three_together = sum(caught_any),
        combined_kill_rate_percent = 100 * mean(caught_any),
        total_lines_all_three = sum(suite_lines),
        missed_by_everything = sum(!caught_any)), 4)
print(mut$op[keep][!caught_any])

## ---- fig-kills ----
kill_df <- data.frame(
  suite = factor(rep(names(suites), 2), levels = names(suites)),
  value = c(kill_rate, per_line),
  panel = factor(rep(c("Mutants caught (per cent)",
                       "Mutants caught per line of test code"),
                     each = length(suites)),
                 levels = c("Mutants caught (per cent)",
                            "Mutants caught per line of test code")))

ggplot(kill_df, aes(suite, value, fill = suite)) +
  geom_col(width = 0.62, show.legend = FALSE) +
  geom_text(aes(label = sprintf("%.2f", value)), vjust = -0.45, size = 3.4,
            colour = te_pal$ink) +
  facet_wrap(~panel, scales = "free_y") +
  scale_fill_manual(values = c(te_pal$sage, te_pal$gold, te_pal$forest)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.16))) +
  labs(x = NULL, y = NULL,
       title = "The hand-worked answer is the cheapest test and the sharpest one") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold", size = 9))

## ---- damage ----
ref_shannon <- site_stats(cnt_main, eff_main)[, "shannon"]
damage_of <- function(fun) {
  if (is.null(fun)) return(100)
  out <- tryCatch(fun(cnt_main, eff_main),
                  error = function(e) NULL, warning = function(w) NULL)
  if (is.null(out) || !is.matrix(out)) return(100)
  if (!"shannon" %in% colnames(out) || nrow(out) != n_site) return(100)
  sh <- out[, "shannon"]
  if (anyNA(sh)) return(100)
  pair_flip(ref_shannon, sh)
}
mut$damage <- sapply(mut_funs, damage_of)
mut$caught_any <- apply(caught, 1, any)
mut$n_suites <- rowSums(caught)

surv <- keep & !mut$caught_any
round(c(survivors = sum(surv),
        mutants_that_run_and_leave_the_ranking_alone = sum(mut$damage[keep] == 0),
        mutants_that_reverse_at_least_one_pair = sum(mut$damage[keep] > 0 &
                                                       mut$damage[keep] < 100),
        mutants_that_stop_or_return_missing = sum(mut$damage[keep] == 100),
        worst_damage_percent = max(mut$damage[keep & mut$damage < 100]),
        caught_by_all_three = sum(mut$n_suites[keep] == 3),
        caught_by_exactly_two = sum(mut$n_suites[keep] == 2),
        caught_by_exactly_one = sum(mut$n_suites[keep] == 1)), 4)
part <- keep & mut$damage > 0 & mut$damage < 100
print(data.frame(op = mut$op[part], family = mut$family[part],
                 damage_percent = round(mut$damage[part], 4),
                 suites_catching = mut$n_suites[part])[order(-mut$damage[part]), ])
print(data.frame(op = mut$op[surv], family = mut$family[surv],
                 damage_on_complete_data = round(mut$damage[surv], 2)))

## ---- corpus ----
na_case <- list(counts = obs_counts, effort = eff_main)
extra_check <- function(fun) {
  if (is.null(fun)) return(TRUE)
  out <- tryCatch(fun(na_case$counts, na_case$effort),
                  error = function(e) NULL, warning = function(w) NULL)
  if (is.null(out) || !is.matrix(out)) return(TRUE)
  !same_out(out, site_stats(na_case$counts, na_case$effort))
}
with_na <- caught_any | sapply(mut_funs[keep], extra_check)
round(c(combined_kill_rate_percent = 100 * mean(caught_any),
        kill_rate_with_one_extra_case_percent = 100 * mean(with_na),
        survivors_after_the_extra_case = sum(!with_na)), 4)

surv_out <- mut_funs[[which(surv)]](obs_counts, eff_main)
truth_out <- site_stats(true_counts, eff_main)
round(c(survivor_mean_density_error_percent =
          100 * mean(abs(surv_out[, "density"] - truth_out[, "density"]) /
                       truth_out[, "density"]),
        survivor_worst_density_error_percent =
          100 * max(abs(surv_out[, "density"] - truth_out[, "density"]) /
                      truth_out[, "density"]),
        survivor_density_pairs_reversed_percent =
          pair_flip(truth_out[, "density"], surv_out[, "density"]),
        survivor_sites_left_missing = sum(is.na(surv_out[, "richness"]))), 4)

set.seed(3105)
n_corp <- 20
alt_rate <- sapply(seq_len(n_corp), function(k) {
  cm <- matrix(rpois(n_site * n_spec, sample(c(0.7, 2, 5), 1)), n_site, n_spec)
  ef <- round(runif(n_site, 0.6, 1.8), 2)
  sapply(list(make_type(cm, ef), make_invariant(cm, ef)), function(s)
    mean(sapply(mut_funs[keep], function(f) suite_catches(s, f))))
})
rownames(alt_rate) <- c("Types", "Invariants")
round(rbind(corpora = c(n_corp, n_corp),
            lowest_percent = 100 * apply(alt_rate, 1, min),
            median_percent = 100 * apply(alt_rate, 1, median),
            highest_percent = 100 * apply(alt_rate, 1, max),
            on_the_field_data_percent = kill_rate[c("Types", "Invariants")]), 4)

## ---- fig-damage ----
dam_df <- mut[keep, ]
fam_order <- names(sort(tapply(dam_df$damage, dam_df$family, mean)))
dam_df$family <- factor(dam_df$family, levels = fam_order)
dam_df$cover <- factor(dam_df$n_suites, levels = 0:3,
                       labels = c("none", "one", "two", "all three"))

ggplot(dam_df, aes(damage, family, fill = cover)) +
  geom_point(size = 3.6, shape = 21, colour = te_pal$ink, stroke = 0.7,
             position = position_nudge(y = ave(dam_df$damage, dam_df$family,
                                               dam_df$damage,
                                               FUN = function(z)
                                                 0.17 * (seq_along(z) - 1)))) +
  scale_fill_manual(values = c(te_pal$paper, te_pal$gold, te_pal$sage,
                               te_pal$forest),
                    name = "Suites that catch it", drop = FALSE) +
  scale_x_continuous(limits = c(-4, 104)) +
  labs(x = "Site pairs whose diversity ranking is reversed (per cent)", y = NULL,
       title = "Most small edits either stop the run or leave the ranking alone") +
  theme_te() +
  theme(legend.position = "top")

## ---- blessed ----
naive_txt <- paste(c(
  "site_stats <- function(counts, effort) {",
  "  ns <- nrow(counts)",
  "  out <- matrix(NA_real_, ns, 4)",
  "  for (i in seq_len(ns)) {",
  "    x <- counts[i, ]",
  "    x <- x[!is.na(x)]",
  "    n <- sum(x, na.rm = TRUE)",
  "    s <- sum(x > 0)",
  "    f1 <- sum(x == 1)",
  "    f2 <- sum(x == 2)",
  "    chao <- s + f1 * (f1 - 1) / (2 * (f2 + 1))",
  "    p <- x[x > 0] / n",
  "    h <- -sum(p * log(p))",
  "    out[i, ] <- c(n / effort[i], s, chao, h)",
  "  }",
  "  colnames(out) <- c('density', 'richness', 'chao1', 'shannon')",
  "  out",
  "}"), collapse = "\n")
naive_fun <- compile_fun(naive_txt)
blessed <- naive_fun(obs_counts, eff_main)

suite_blessed <- function(fun) {
  run <- run_new()
  out <- fun(obs_counts, eff_main)
  run <- expect(run, "matches the recorded output",
                near(as.numeric(out), as.numeric(blessed)))
  run
}
blessed_kill <- mean(sapply(mut_funs[keep], function(f)
  suite_catches(suite_blessed, f)))

round(c(blessed_suite_lines = length(deparse(suite_blessed)),
        blessed_kill_rate_percent = 100 * blessed_kill,
        blessed_also_rejects_the_corrected_function =
          suite_catches(suite_blessed, site_stats),
        blessed_mean_richness = mean(blessed[, "richness"]),
        true_mean_richness = mean(true_rich),
        blessed_slope = coef(lm(blessed[, "richness"] ~ wetness))[2],
        true_slope = slope_true[2],
        blessed_pairs_reversed_percent =
          pair_flip(true_rich, blessed[, "richness"])), 4)
