# NOEC rewards noisy toxicity tests
# https://tidyecology.com/posts/noec-and-the-reward-for-noise/
#
# 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)
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))
}

## ---- truth ----
top_true   <- 100
ec50_true  <- 16
slope_true <- 2
conc_grid  <- c(2.5, 5, 10, 20, 40)
alpha_lev  <- 0.05

curve_mean <- function(conc) top_true / (1 + (conc / ec50_true)^slope_true)
effect_at  <- function(conc) 1 - curve_mean(conc) / top_true
ec10_true  <- ec50_true * (1 / 9)^(1 / slope_true)
eff_grid   <- 100 * effect_at(conc_grid)
next_above <- min(conc_grid[conc_grid > ec10_true])

## ---- dunnett ----
dunnett_crit <- function(k_conc, df_res, alpha = alpha_lev) {
  z_nodes <- seq(-8, 8, by = 0.05)
  w_z     <- dnorm(z_nodes) * 0.05
  u_nodes <- seq(0.005, 4, by = 0.01)
  w_u     <- dchisq(df_res * u_nodes^2, df_res) * 2 * df_res * u_nodes * 0.01
  coverage <- function(cc) {
    inner <- pnorm(outer(z_nodes, cc * sqrt(2) * u_nodes, "+"))^k_conc
    sum(w_z * (inner %*% w_u))
  }
  uniroot(function(cc) coverage(cc) - (1 - alpha), c(1, 6), tol = 1e-7)$root
}

crit_5_12  <- dunnett_crit(5, 12)
crit_5_inf <- dunnett_crit(5, 5000)
crit_1_12  <- dunnett_crit(1, 12)
t_1_12     <- qt(1 - alpha_lev, 12)

n_null <- 20000
n_null_per <- 3
set.seed(4102)
y_null <- array(rnorm(n_null * 6 * n_null_per, top_true, 10),
                c(n_null, 6, n_null_per))
gm_null <- rowMeans(y_null, dims = 2)
sp_null <- sqrt(rowMeans(apply(y_null, c(1, 2), var)))
t_null  <- (gm_null[, 1] - gm_null[, -1]) / (sp_null * sqrt(2 / n_null_per))
fwer_null <- mean(apply(t_null >= crit_5_12, 1, any))
fwer_se   <- sqrt(fwer_null * (1 - fwer_null) / n_null)

## ---- noecfun ----
noec_readings <- function(y_arr, conc, n_per) {
  k_conc <- length(conc)
  df_res <- (k_conc + 1) * (n_per - 1)
  crit   <- dunnett_crit(k_conc, df_res)
  g_mean <- rowMeans(y_arr, dims = 2)
  s_pool <- sqrt(rowMeans(apply(y_arr, c(1, 2), var)))
  t_dec  <- (g_mean[, 1] - g_mean[, -1]) / (s_pool * sqrt(2 / n_per))
  sig    <- t_dec >= crit
  # LOEC = lowest significant concentration; NOEC = the one below it
  first_sig <- max.col(cbind(sig, TRUE), ties.method = "first")
  noec_low  <- c(0, conc, conc[k_conc])[first_sig]
  # top-down reading: from the top, stop at the first non-significant
  top_run   <- max.col(cbind(!sig[, k_conc:1, drop = FALSE], TRUE),
                       ties.method = "first")
  noec_down <- c(rev(conc), 0)[top_run]
  # Holm on the same one-sided t statistics
  p_one  <- pt(t_dec, df_res, lower.tail = FALSE)
  p_sort <- t(apply(p_one, 1, sort))
  p_ord  <- t(apply(p_one, 1, order))
  holm_m <- t(apply(sweep(p_sort, 2, k_conc:1, "*"), 1, cummax))
  sig_h  <- matrix(FALSE, nrow(p_one), k_conc)
  sig_h[cbind(rep(seq_len(nrow(p_one)), k_conc), as.vector(p_ord))] <-
    as.vector(holm_m <= alpha_lev)
  first_h   <- max.col(cbind(sig_h, TRUE), ties.method = "first")
  noec_holm <- c(0, conc, conc[k_conc])[first_h]
  list(low = noec_low, down = noec_down, holm = noec_holm)
}

sim_assays <- function(n_rep, sd_res, n_per, conc) {
  mu_g <- c(top_true, curve_mean(conc))
  array(rnorm(n_rep * length(mu_g) * n_per, rep(mu_g, each = n_rep), sd_res),
        c(n_rep, length(mu_g), n_per))
}

## ---- twolabs ----
n_show <- 4000
set.seed(5530)
lab_tight <- sim_assays(n_show, 5, 3, conc_grid)
lab_loose <- sim_assays(n_show, 20, 3, conc_grid)
noec_tight <- noec_readings(lab_tight, conc_grid, 3)$low
noec_loose <- noec_readings(lab_loose, conc_grid, 3)$low
med_tight  <- median(noec_tight)
med_loose  <- median(noec_loose)
pick_tight <- which(noec_tight == med_tight)[1]
pick_loose <- which(noec_loose == med_loose)[1]
eff_tight  <- 100 * effect_at(med_tight)
eff_loose  <- 100 * effect_at(med_loose)

fit_curve <- function(conc_v, y_v) {
  tryCatch(nls(y_v ~ top / (1 + (conc_v / exp(le50))^b),
               start = list(top = mean(y_v[conc_v == 0]),
                            le50 = log(median(conc_v[conc_v > 0])), b = 1.5),
               control = nls.control(maxiter = 1000)),
           error = function(e) NULL)
}
ec10_from_fit <- function(fit) {
  if (is.null(fit)) return(c(est = NA, lo = NA, hi = NA))
  cf <- coef(fit)
  if (cf[["b"]] <= 0) return(c(est = NA, lo = NA, hi = NA))
  l10  <- cf[["le50"]] + log(1 / 9) / cf[["b"]]
  grad <- c(0, 1, -log(1 / 9) / cf[["b"]]^2)
  se10 <- sqrt(drop(grad %*% vcov(fit) %*% grad))
  tq   <- qt(0.975, df.residual(fit))
  c(est = l10, lo = l10 - tq * se10, hi = l10 + tq * se10)
}

one_lab <- function(y_arr, i_row, lab) {
  conc_v <- rep(c(0, conc_grid), times = dim(y_arr)[3])
  y_v    <- as.vector(y_arr[i_row, , ])
  fit    <- fit_curve(conc_v, y_v)
  e10    <- ec10_from_fit(fit)
  list(points = data.frame(conc = conc_v, y = y_v, lab = lab),
       ec10 = exp(e10), coef = coef(fit))
}
show_t <- one_lab(lab_tight, pick_tight, "scatter 5 per cent")
show_l <- one_lab(lab_loose, pick_loose, "scatter 20 per cent")
both_cover <- all(c(show_t$ec10[["lo"]], show_l$ec10[["lo"]]) < ec10_true &
                  c(show_t$ec10[["hi"]], show_l$ec10[["hi"]]) > ec10_true)
ratio_t <- show_t$ec10[["hi"]] / show_t$ec10[["lo"]]
ratio_l <- show_l$ec10[["hi"]] / show_l$ec10[["lo"]]

## ---- fig-twolabs ----
lab_panel <- function(show, noec_val, ttl) {
  conc_line <- exp(seq(log(1), log(60), length.out = 200))
  pts <- show$points
  pts$conc_plot <- ifelse(pts$conc == 0, 1.3, pts$conc)
  ggplot() +
    geom_line(data = data.frame(conc = conc_line, y = curve_mean(conc_line)),
              aes(conc, y), colour = te_body, linetype = "dashed", linewidth = 0.6) +
    geom_vline(xintercept = ec10_true, colour = te_gold, linewidth = 0.9) +
    geom_vline(xintercept = noec_val, colour = te_rust, linewidth = 0.9) +
    geom_line(data = data.frame(conc = conc_line,
                                y = show$coef[["top"]] /
                                  (1 + (conc_line / exp(show$coef[["le50"]]))^show$coef[["b"]])),
              aes(conc, y), colour = te_forest, linewidth = 0.9) +
    geom_point(data = pts, aes(conc_plot, y), colour = te_forest, size = 2,
               alpha = 0.8) +
    scale_x_log10(breaks = c(1.3, conc_grid), labels = c("control", conc_grid)) +
    coord_cartesian(ylim = c(0, 150)) +
    labs(x = "concentration (micrograms per litre)",
         y = "growth rate, per cent of control", title = ttl) +
    theme_datasheet()
}
p_tight <- lab_panel(show_t, med_tight, "Replicate scatter 5 per cent")
p_loose <- lab_panel(show_l, med_loose, "Replicate scatter 20 per cent")
(p_tight | p_loose) +
  plot_annotation(subtitle = paste("dashed: true curve; green: fitted curve; gold: true EC10;",
                                   "red: NOEC from Dunnett's test"),
                  theme = theme_datasheet())

## ---- sweep ----
sd_set  <- c(5, 10, 20)
rep_set <- c(3, 6, 10)
n_rep   <- 4000
n_fit   <- 400
mc_se_max <- sqrt(0.25 / n_rep)

set.seed(6217)
cells <- expand.grid(sd_res = sd_set, n_per = rep_set)
sweep_list <- lapply(seq_len(nrow(cells)), function(i) {
  y_arr <- sim_assays(n_rep, cells$sd_res[i], cells$n_per[i], conc_grid)
  rd    <- noec_readings(y_arr, conc_grid, cells$n_per[i])
  conc_v <- rep(c(0, conc_grid), times = cells$n_per[i])
  e10 <- vapply(seq_len(n_fit), function(r)
    ec10_from_fit(fit_curve(conc_v, as.vector(y_arr[r, , ]))), numeric(3))
  list(rd = rd, e10 = e10)
})

sweep_tab <- cbind(cells, t(vapply(sweep_list, function(s) {
  ok <- !is.na(s$e10["est", ])
  e_est <- s$e10["est", ok]
  c(p_above   = mean(s$rd$low > ec10_true),
    p_down    = mean(s$rd$down > ec10_true),
    p_holm    = mean(s$rd$holm > ec10_true),
    disagree  = mean(s$rd$low != s$rd$down),
    med_noec  = median(s$rd$low),
    mean_eff  = 100 * mean(effect_at(s$rd$low)),
    fail      = mean(!ok),
    ec10_med  = exp(median(e_est)),
    ec10_q05  = exp(quantile(e_est, 0.05, names = FALSE)),
    ec10_q95  = exp(quantile(e_est, 0.95, names = FALSE)),
    ec10_up   = mean(e_est > log(ec10_true)),
    cover     = mean(s$e10["lo", ok] < log(ec10_true) &
                     s$e10["hi", ok] > log(ec10_true)),
    width     = median(exp(s$e10["hi", ok] - s$e10["lo", ok])))
}, numeric(13))))
sweep_tab$p_se <- sqrt(sweep_tab$p_above * (1 - sweep_tab$p_above) / n_rep)

cell <- function(s, n) which(sweep_tab$sd_res == s & sweep_tab$n_per == n)
c_53  <- cell(5, 3);  c_103 <- cell(10, 3); c_203 <- cell(20, 3)
c_206 <- cell(20, 6); c_2010 <- cell(20, 10); c_1010 <- cell(10, 10)
c_56  <- cell(5, 6)
max_disagree <- max(sweep_tab$disagree)
max_holm_gap <- max(abs(sweep_tab$p_holm - sweep_tab$p_above))
max_down_gap <- max(abs(sweep_tab$p_down - sweep_tab$p_above))
holm_lower   <- all(sweep_tab$p_holm <= sweep_tab$p_above)
n_above_53   <- round(sweep_tab$p_above[c_53] * n_rep)
eff_fold     <- sweep_tab$mean_eff[c_203] / sweep_tab$mean_eff[c_53]
cover_low    <- which.min(sweep_tab$cover)
cover_low_z  <- (0.95 - sweep_tab$cover[cover_low]) / sqrt(0.95 * 0.05 / n_fit)

## ---- fig-sweep ----
sweep_tab$reps <- factor(paste(sweep_tab$n_per, "flasks"),
                         levels = paste(rep_set, "flasks"))
ggplot(sweep_tab, aes(sd_res, p_above, colour = reps)) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = p_above - 2 * p_se, ymax = p_above + 2 * p_se),
                width = 0.6, linewidth = 0.5) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_x_continuous(breaks = sd_set) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "replicate scatter (per cent of control mean)",
       y = "proportion with NOEC above true EC10",
       title = "A noisier test reports a higher NOEC",
       subtitle = "bars: two Monte Carlo standard errors") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- ec10summary ----
fail_max   <- max(sweep_tab$fail)
fail_cell  <- sweep_tab[which.max(sweep_tab$fail), c("sd_res", "n_per")]
n_fail_tot <- round(sum(sweep_tab$fail * n_fit))
ec10_med_rng <- range(sweep_tab$ec10_med)
ec10_up_rng  <- range(sweep_tab$ec10_up)
cover_rng    <- range(sweep_tab$cover)
cover_se     <- sqrt(0.95 * 0.05 / n_fit)
width_53     <- sweep_tab$width[c_53]
width_203    <- sweep_tab$width[c_203]
width_2010   <- sweep_tab$width[c_2010]

## ---- fig-ec10 ----
ggplot(sweep_tab, aes(factor(sd_res), ec10_med, colour = reps)) +
  geom_hline(yintercept = ec10_true, colour = te_gold, linewidth = 0.9) +
  geom_errorbar(aes(ymin = ec10_q05, ymax = ec10_q95),
                position = position_dodge(width = 0.6), width = 0.25,
                linewidth = 0.7) +
  geom_point(position = position_dodge(width = 0.6), size = 2.6) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_y_log10(breaks = c(2, 3, 5, 8, 12)) +
  labs(x = "replicate scatter (per cent of control mean)",
       y = "EC10 estimate (micrograms per litre)",
       title = "The EC10 widens but stays centred",
       subtitle = "gold line: true EC10; bars: 5th to 95th percentile of estimates") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- budget ----
budget <- list(
  "3 concentrations" = list(conc = 2.5 * 4^(0:2), n_per = 15),
  "5 concentrations" = list(conc = 2.5 * 2^(0:4), n_per = 10),
  "9 concentrations" = list(conc = 2.5 * sqrt(2)^(0:8), n_per = 6))
n_flask <- vapply(budget, function(b) (length(b$conc) + 1) * b$n_per, 0)
sd_budget <- c(10, 20)

set.seed(7384)
budget_tab <- do.call(rbind, lapply(sd_budget, function(sd_res) {
  do.call(rbind, lapply(names(budget), function(nm) {
    conc  <- budget[[nm]]$conc
    n_per <- budget[[nm]]$n_per
    y_arr <- sim_assays(n_rep, sd_res, n_per, conc)
    noec  <- noec_readings(y_arr, conc, n_per)$low
    conc_v <- rep(c(0, conc), times = n_per)
    e10 <- vapply(seq_len(n_fit), function(r)
      ec10_from_fit(fit_curve(conc_v, as.vector(y_arr[r, , ])))[["est"]], 0)
    ok <- !is.na(e10)
    p_big <- mean(effect_at(noec) > 0.10)
    data.frame(design = nm, sd_res = sd_res,
               p_big = p_big, p_big_se = sqrt(p_big * (1 - p_big) / n_rep),
               mean_eff = 100 * mean(effect_at(noec)),
               fail = mean(!ok),
               ratio90 = exp(quantile(e10[ok], 0.95, names = FALSE) -
                             quantile(e10[ok], 0.05, names = FALSE)))
  }))
}))
bt <- function(s, d) which(budget_tab$sd_res == s & budget_tab$design == d)
b_3_20 <- bt(20, "3 concentrations"); b_5_20 <- bt(20, "5 concentrations")
b_9_20 <- bt(20, "9 concentrations"); b_3_10 <- bt(10, "3 concentrations")
b_9_10 <- bt(10, "9 concentrations"); b_5_10 <- bt(10, "5 concentrations")
fail_budget <- max(budget_tab$fail)
eff_coarse  <- 100 * effect_at(2.5 * 4^(0:2))

## ---- fig-budget ----
budget_tab$scatter <- factor(paste(budget_tab$sd_res, "per cent scatter"),
                             levels = paste(sd_budget, "per cent scatter"))
p_left <- ggplot(budget_tab, aes(design, p_big, colour = scatter,
                                 group = scatter)) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = p_big - 2 * p_big_se, ymax = p_big + 2 * p_big_se),
                width = 0.12, linewidth = 0.5) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = NULL, y = "share with effect at NOEC over 10%",
       title = "NOEC") +
  theme_datasheet() +
  theme(legend.position = "none")
p_right <- ggplot(budget_tab, aes(design, ratio90, colour = scatter,
                                  group = scatter)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_y_continuous(limits = c(1, NA)) +
  labs(x = NULL, y = "95th over 5th percentile of EC10",
       title = "Fitted EC10") +
  theme_datasheet() +
  theme(legend.position = "none")
(p_left | p_right) +
  plot_annotation(subtitle = paste("60 flasks over 2.5 to 40 micrograms per litre;",
                                   "green: 10 per cent scatter, red: 20 per cent"),
                  theme = theme_datasheet()) &
  theme(axis.text.x = element_text(angle = 20, hjust = 1))
