# Confidence intervals for effective doses
# https://tidyecology.com/posts/confidence-intervals-for-effective-doses/
#
# 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)

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

## ---- truth ----
lc50_true  <- 12
slope_true <- 2.4
x50_true   <- log10(lc50_true)

lx_true <- function(lev) x50_true + qlogis(lev) / slope_true
lc_true <- function(lev) 10^lx_true(lev)

conc_wide <- c(2, 4, 8, 16, 32, 64)
n_wide    <- rep(25, 6)
x_wide    <- log10(conc_wide)
p_wide    <- 1 / (1 + exp(-slope_true * (x_wide - x50_true)))

print(data.frame(concentration = conc_wide, animals = n_wide,
                 log10_conc = round(x_wide, 4),
                 true_response = round(p_wide, 4)))
levs <- c(0.5, 0.1, 0.01)
print(round(rbind(level = levs, true_dose = lc_true(levs),
                  true_log10_dose = lx_true(levs)), 4))
c(true_lc50 = lc50_true, true_slope_per_decade = slope_true,
  total_animals = sum(n_wide),
  doses_below_the_true_lc10 = sum(conc_wide < lc_true(0.1)),
  animals_below_the_true_lc10 = sum(n_wide[conc_wide < lc_true(0.1)]))

## ---- fitters ----
log1pexp <- function(e) ifelse(e > 30, e, log1p(exp(e)))

fit_many <- function(x, n_an, Y) {
  k <- length(x); nrep <- ncol(Y)
  bb <- rbind(rep(0, nrep), rep(1, nrep))
  for (it in 1:60) {
    eta <- x %o% bb[2, ] + rep(bb[1, ], each = k)
    pr <- 1 / (1 + exp(-eta))
    wt <- n_an * pr * (1 - pr); wt[wt < 1e-10] <- 1e-10
    res <- Y - n_an * pr
    s1 <- colSums(res); s2 <- colSums(x * res)
    h11 <- colSums(wt); h12 <- colSums(x * wt); h22 <- colSums(x * x * wt)
    det2 <- h11 * h22 - h12^2
    d1 <- (h22 * s1 - h12 * s2) / det2
    d2 <- (-h12 * s1 + h11 * s2) / det2
    big <- pmax(abs(d1), abs(d2))
    damp <- 1 / (1 + big / 0.5)
    bb[1, ] <- bb[1, ] + damp * d1
    bb[2, ] <- bb[2, ] + damp * d2
    if (max(damp * big) < 1e-11) break
  }
  eta <- x %o% bb[2, ] + rep(bb[1, ], each = k)
  pr <- 1 / (1 + exp(-eta))
  list(b0 = bb[1, ], b1 = bb[2, ], v00 = h22 / det2, v01 = -h12 / det2,
       v11 = h11 / det2, loglik = colSums(Y * eta - n_an * log1pexp(eta)),
       iterations = it, last_step = max(big))
}

simulate_counts <- function(x, n_an, nrep, x50 = x50_true, slope = slope_true) {
  pr <- 1 / (1 + exp(-slope * (x - x50)))
  matrix(rbinom(length(x) * nrep, rep(n_an, nrep), rep(pr, nrep)), length(x), nrep)
}

## ---- example ----
set.seed(20260730)
y_ex <- simulate_counts(x_wide, n_wide, 1)
print(data.frame(concentration = conc_wide, animals = n_wide,
                 dead = as.vector(y_ex),
                 observed = round(as.vector(y_ex) / n_wide, 4)))

fit_ex <- fit_many(x_wide, n_wide, y_ex)
ref <- glm(cbind(as.vector(y_ex), n_wide - as.vector(y_ex)) ~ x_wide,
           family = binomial)
print(round(rbind(newton = c(fit_ex$b0, fit_ex$b1),
                  glm = as.numeric(coef(ref))), 6))
round(c(max_coefficient_difference = max(abs(c(fit_ex$b0, fit_ex$b1) -
                                                as.numeric(coef(ref)))),
        max_variance_difference =
          max(abs(c(fit_ex$v00, fit_ex$v01, fit_ex$v11) -
                    as.numeric(vcov(ref))[c(1, 2, 4)])),
        newton_iterations = fit_ex$iterations), 10)

est_ex <- (qlogis(levs) - fit_ex$b0) / fit_ex$b1
print(round(rbind(level = levs, estimate = 10^est_ex, truth = lc_true(levs)), 4))

## ---- intervals ----
rep_fit <- function(fit, times) {
  lapply(fit[c("b0", "b1", "v00", "v01", "v11", "loglik")], rep, times = times)
}

delta_log <- function(lev, fit) {
  xq <- (qlogis(lev) - fit$b0) / fit$b1
  vv <- (fit$v00 + 2 * xq * fit$v01 + xq^2 * fit$v11) / fit$b1^2
  se <- sqrt(pmax(vv, 0))
  cbind(xq - qnorm(0.975) * se, xq + qnorm(0.975) * se)
}

delta_dose <- function(lev, fit) {
  xq <- (qlogis(lev) - fit$b0) / fit$b1
  vv <- (fit$v00 + 2 * xq * fit$v01 + xq^2 * fit$v11) / fit$b1^2
  se <- sqrt(pmax(vv, 0)) * log(10) * 10^xq
  cbind(10^xq - qnorm(0.975) * se, 10^xq + qnorm(0.975) * se)
}

fieller_log <- function(lev, fit) {
  z2 <- qnorm(0.975)^2
  aa <- fit$b1^2 - z2 * fit$v11
  gap <- fit$b0 - qlogis(lev)
  bq <- 2 * (gap * fit$b1 - z2 * fit$v01)
  cq <- gap^2 - z2 * fit$v00
  disc <- bq^2 - 4 * aa * cq
  lo <- rep(-Inf, length(aa)); hi <- rep(Inf, length(aa))
  ok <- aa > 0 & disc > 0
  r1 <- (-bq - sqrt(pmax(disc, 0))) / (2 * aa)
  r2 <- (-bq + sqrt(pmax(disc, 0))) / (2 * aa)
  lo[ok] <- pmin(r1, r2)[ok]; hi[ok] <- pmax(r1, r2)[ok]
  cbind(lo, hi)
}

profile_loglik <- function(xq, lq, x, n_an, Y, b_start) {
  k <- length(x)
  uu <- outer(x, xq, "-")
  bb <- b_start
  for (it in 1:80) {
    eta <- rep(lq, each = k) + uu * rep(bb, each = k)
    pr <- 1 / (1 + exp(-eta))
    sc <- colSums(uu * (Y - n_an * pr))
    hs <- colSums(n_an * pr * (1 - pr) * uu^2); hs[hs < 1e-10] <- 1e-10
    st <- sc / hs
    st <- st / (1 + abs(st) / 0.5)
    bb <- bb + st
    if (max(abs(st)) < 1e-11) break
  }
  eta <- rep(lq, each = k) + uu * rep(bb, each = k)
  colSums(Y * eta - n_an * log1pexp(eta))
}

profile_log <- function(lev, x, n_an, Y, fit, span = 14, steps = 46) {
  lq <- qlogis(lev)
  xhat <- (lq - fit$b0) / fit$b1
  crit <- fit$loglik - qchisq(0.95, 1) / 2
  out <- matrix(NA_real_, length(xhat), 2)
  for (side in c(-1, 1)) {
    far <- xhat + side * span
    unbounded <- profile_loglik(far, lq, x, n_an, Y, fit$b1) > crit
    lo <- xhat; hi <- far
    for (it in 1:steps) {
      mid <- (lo + hi) / 2
      inside <- profile_loglik(mid, lq, x, n_an, Y, fit$b1) > crit
      lo <- ifelse(inside, mid, lo)
      hi <- ifelse(inside, hi, mid)
    }
    bnd <- (lo + hi) / 2
    bnd[unbounded] <- side * Inf
    out[, if (side < 0) 1 else 2] <- bnd
  }
  out
}

cat("z for a two sided 95 per cent interval:", round(qnorm(0.975), 2),
    "| chi-squared quantile:", round(qchisq(0.95, 1), 4),
    "| nominal miss per side:", 0.025, "or in per cent:", 2.5,
    "| one sided level in per cent:", 97.5, "\n")

nlev <- length(levs)
fit_rep <- rep_fit(fit_ex, nlev)
Y_rep <- matrix(rep(as.vector(y_ex), nlev), length(x_wide), nlev)
d_log <- delta_log(levs, fit_rep)
d_dose <- delta_dose(levs, fit_rep)
f_log <- fieller_log(levs, fit_rep)
p_log <- profile_log(levs, x_wide, n_wide, Y_rep, fit_rep)

ex_tab <- cbind(level = levs, estimate = 10^est_ex,
                delta_lo = 10^d_log[, 1], delta_hi = 10^d_log[, 2],
                fieller_lo = 10^f_log[, 1], fieller_hi = 10^f_log[, 2],
                profile_lo = 10^p_log[, 1], profile_hi = 10^p_log[, 2],
                dose_delta_lo = d_dose[, 1], dose_delta_hi = d_dose[, 2])
print(round(ex_tab, 4))
upper_over_lower <- function(bnd) (10^bnd[, 2] - 10^est_ex) / (10^est_ex - 10^bnd[, 1])
print(round(rbind(level = levs, delta = upper_over_lower(d_log),
                  fieller = upper_over_lower(f_log),
                  profile = upper_over_lower(p_log)), 4))

## ---- fig-inverse ----
lev_grid <- plogis(seq(qlogis(0.004), qlogis(0.95), length.out = 70))
fit_g <- rep_fit(fit_ex, length(lev_grid))
Y_g <- matrix(rep(as.vector(y_ex), length(lev_grid)), length(x_wide),
              length(lev_grid))
bnd <- list(Delta = delta_log(lev_grid, fit_g),
            Fieller = fieller_log(lev_grid, fit_g),
            Profile = profile_log(lev_grid, x_wide, n_wide, Y_g, fit_g))
c(non_finite_bounds_in_figure = sum(!is.finite(unlist(bnd))))

band <- do.call(rbind, lapply(names(bnd), function(nm)
  data.frame(lev = rep(lev_grid, 2), xx = as.vector(bnd[[nm]]),
             side = rep(c("lo", "hi"), each = length(lev_grid)), method = nm)))
band$method <- factor(band$method, levels = names(bnd))
curve_df <- data.frame(xx = seq(-2.6, 3, length.out = 240))
curve_df$fitted <- 1 / (1 + exp(-(fit_ex$b0 + fit_ex$b1 * curve_df$xx)))
curve_df$truth <- 1 / (1 + exp(-slope_true * (curve_df$xx - x50_true)))
obs_df <- data.frame(xx = x_wide, lev = as.vector(y_ex) / n_wide)
mark <- data.frame(lev = levs, lab = c("LC50", "LC10", "LC1"))
brk <- log10(c(0.01, 0.1, 1, 10, 100, 1000))

ggplot(band, aes(xx, lev, colour = method, group = interaction(method, side))) +
  geom_hline(data = mark, aes(yintercept = lev),
             colour = te_pal$line, linewidth = 0.8) +
  geom_line(data = curve_df, aes(xx, truth), inherit.aes = FALSE,
            colour = te_pal$ink, linetype = "dashed", linewidth = 0.7) +
  geom_line(data = curve_df, aes(xx, fitted), inherit.aes = FALSE,
            colour = te_pal$ink, linewidth = 0.9) +
  geom_line(linewidth = 0.85) +
  geom_point(data = obs_df, aes(xx, lev), inherit.aes = FALSE,
             colour = te_pal$ink, size = 2.4) +
  geom_text(data = mark, aes(x = -2.5, y = lev, label = lab), inherit.aes = FALSE,
            vjust = -0.5, hjust = 0, size = 3.1, colour = "#2c3a31") +
  scale_colour_manual(values = c(Delta = te_pal$clay, Fieller = te_pal$green,
                                 Profile = te_pal$gold), name = NULL) +
  scale_x_continuous(breaks = brk,
                     labels = c("0.01", "0.1", "1", "10", "100", "1000")) +
  scale_y_continuous(transform = "logit",
                     breaks = c(0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9),
                     labels = c("0.01", "0.05", "0.10", "0.25", "0.50",
                                "0.75", "0.90")) +
  coord_cartesian(xlim = c(-2.6, 3), ylim = c(0.006, 0.93)) +
  labs(x = "Concentration (micrograms per litre, log scale)",
       y = "Proportion responding",
       title = "The interval on the concentration axis opens out as the level falls",
       subtitle = "Solid black: the fitted curve. Dashed black: the curve the counts were generated from.") +
  theme_te() +
  theme(legend.position = "right",
        plot.subtitle = element_text(colour = "#2c3a31", size = 9))

## ---- coverage ----
set.seed(20260730)
n_rep <- 4000
Y_cov <- simulate_counts(x_wide, n_wide, n_rep)
fit_cov <- fit_many(x_wide, n_wide, Y_cov)
c(replicates = n_rep, animals_per_set = sum(n_wide))
round(c(newton_iterations = fit_cov$iterations, last_step = fit_cov$last_step,
        smallest_slope = min(fit_cov$b1)), 8)

cov_rows <- NULL
resid_prof <- 0
for (lev in levs) {
  tv <- lx_true(lev); tvd <- lc_true(lev)
  dl <- delta_log(lev, fit_cov)
  dd <- delta_dose(lev, fit_cov)
  fl <- fieller_log(lev, fit_cov)
  pl <- profile_log(lev, x_wide, n_wide, Y_cov, fit_cov)
  ok <- is.finite(pl[, 1])
  resid_prof <- max(resid_prof, max(abs(
    2 * (fit_cov$loglik[ok] -
           profile_loglik(pl[ok, 1], qlogis(lev), x_wide, n_wide,
                          Y_cov[, ok, drop = FALSE], fit_cov$b1[ok])) -
      qchisq(0.95, 1))))
  cov_rows <- rbind(cov_rows, c(
    level = lev,
    delta_dose = mean(dd[, 1] <= tvd & dd[, 2] >= tvd),
    delta_log = mean(dl[, 1] <= tv & dl[, 2] >= tv),
    fieller = mean(fl[, 1] <= tv & fl[, 2] >= tv),
    profile = mean(pl[, 1] <= tv & pl[, 2] >= tv),
    above_delta = mean(dl[, 1] > tv), below_delta = mean(dl[, 2] < tv),
    above_fieller = mean(fl[, 1] > tv), below_fieller = mean(fl[, 2] < tv),
    above_profile = mean(pl[, 1] > tv), below_profile = mean(pl[, 2] < tv),
    dose_lower_at_or_below_zero = mean(dd[, 1] <= 0),
    dose_above = mean(dd[, 1] > tvd), dose_below = mean(dd[, 2] < tvd),
    w_delta = median(dl[, 2] - dl[, 1]), w_fieller = median(fl[, 2] - fl[, 1]),
    w_profile = median(pl[, 2] - pl[, 1]),
    w_delta_dose = median(dd[, 2] - dd[, 1]),
    w_fieller_dose = median(10^fl[, 2] - 10^fl[, 1])))
}
rownames(cov_rows) <- c("LC50", "LC10", "LC1")
print(round(cov_rows[, 1:5], 4))
print(round(cov_rows[, 6:14], 4))
one_sided <- 1 - cov_rows[, c("above_delta", "above_fieller", "above_profile")]
colnames(one_sided) <- c("delta_log", "fieller", "profile")
print(round(one_sided, 4))
round(c(monte_carlo_se = sqrt(0.95 * 0.05 / n_rep),
        max_profile_check_residual = resid_prof), 5)

## ---- fig-coverage ----
miss <- data.frame(
  level = factor(rep(rownames(cov_rows), 6), levels = rownames(cov_rows)),
  method = factor(rep(rep(c("Delta on the log scale", "Fieller", "Profile"),
                          each = 3), 2),
                  levels = c("Delta on the log scale", "Fieller", "Profile")),
  side = rep(c("Interval lies above the true dose",
               "Interval lies below the true dose"), each = 9),
  pct = 100 * as.vector(cov_rows[, c("above_delta", "above_fieller",
                                     "above_profile", "below_delta",
                                     "below_fieller", "below_profile")]))

ggplot(miss, aes(level, pct, fill = method)) +
  geom_col(position = position_dodge(width = 0.75), width = 0.68) +
  geom_hline(yintercept = 2.5, colour = te_pal$ink, linetype = "dashed",
             linewidth = 0.7) +
  facet_wrap(~side) +
  scale_fill_manual(values = c("Delta on the log scale" = te_pal$clay,
                               Fieller = te_pal$green, Profile = te_pal$gold),
                    name = NULL) +
  labs(x = NULL, y = "Per cent of data sets",
       title = "The delta interval misses the low effective doses from one side",
       subtitle = "Dashed line: the 2.5 per cent on each side that a 95 per cent interval promises.") +
  theme_te() +
  theme(legend.position = "right",
        plot.subtitle = element_text(colour = "#2c3a31", size = 9),
        strip.text = element_text(colour = te_pal$ink, face = "bold"))

## ---- widths ----
wr <- cov_rows[, c("w_fieller", "w_fieller_dose")]
fold <- 10^cov_rows[, "w_fieller"]
print(round(cbind(log10_width = wr[, 1], fold_factor = fold,
                  dose_width = wr[, 2],
                  true_dose = lc_true(levs)), 4))
round(c(log_width_lc10_over_lc50 = wr[2, 1] / wr[1, 1],
        log_width_lc1_over_lc50 = wr[3, 1] / wr[1, 1],
        dose_width_lc10_over_lc50 = wr[2, 2] / wr[1, 2],
        dose_width_lc1_over_lc50 = wr[3, 2] / wr[1, 2],
        fold_lc10_over_lc50 = as.numeric(fold[2] / fold[1]),
        fold_lc1_over_lc50 = as.numeric(fold[3] / fold[1])), 4)

## ---- designs ----
set.seed(20260730)
designs <- list(
  Centred = list(conc = c(4, 6, 9, 14, 21, 32), n_an = rep(25, 6)),
  Wide = list(conc = c(2, 4, 8, 16, 32, 64), n_an = rep(25, 6)),
  "Low weighted" = list(conc = c(0.5, 1, 2, 4, 16, 64),
                        n_an = c(30, 30, 30, 25, 20, 15)),
  "Very narrow" = list(conc = c(6, 8, 10, 14, 18, 24), n_an = rep(25, 6)))
n_des <- 3000

for (nm in names(designs)) {
  xx <- log10(designs[[nm]]$conc)
  designs[[nm]]$x <- xx
  designs[[nm]]$p <- 1 / (1 + exp(-slope_true * (xx - x50_true)))
}
print(t(sapply(designs, function(dz) dz$conc)))
print(t(sapply(designs, function(dz) dz$n_an)))
print(round(t(sapply(designs, function(dz)
  c(total_animals = sum(dz$n_an), lowest_conc = min(dz$conc),
    highest_conc = max(dz$conc), lowest_response = min(dz$p),
    highest_response = max(dz$p)))), 4))

lev_sweep <- plogis(seq(qlogis(0.01), qlogis(0.6), length.out = 30))
sweep_rows <- NULL
sweep_curve <- NULL
for (nm in names(designs)) {
  dz <- designs[[nm]]
  Yd <- simulate_counts(dz$x, dz$n_an, n_des)
  fd <- fit_many(dz$x, dz$n_an, Yd)
  wid <- sapply(lev_sweep, function(lev) {
    bb <- fieller_log(lev, fd); median(bb[, 2] - bb[, 1]) })
  sweep_curve <- rbind(sweep_curve,
                       data.frame(design = nm, lev = lev_sweep, width = wid))
  row_out <- c(replicates = n_des)
  for (lev in levs) {
    bb <- fieller_log(lev, fd)
    wd <- bb[, 2] - bb[, 1]
    row_out <- c(row_out, median(wd), mean(!is.finite(wd)),
                 mean(bb[, 1] <= lx_true(lev) & bb[, 2] >= lx_true(lev)))
  }
  sweep_rows <- rbind(sweep_rows, row_out)
}
colnames(sweep_rows) <- c("replicates", paste0(rep(c("width", "unbounded",
                                                     "coverage"), 3),
                                               rep(c("_LC50", "_LC10", "_LC1"),
                                                   each = 3)))
rownames(sweep_rows) <- names(designs)
print(round(sweep_rows[, c(1, 2, 3, 4, 5, 6, 7)], 4))
print(round(sweep_rows[, c(8, 9, 10)], 4))
round(c(low_over_centred_lc10 = sweep_rows["Low weighted", "width_LC10"] /
          sweep_rows["Centred", "width_LC10"],
        low_over_centred_lc50 = sweep_rows["Low weighted", "width_LC50"] /
          sweep_rows["Centred", "width_LC50"],
        low_over_wide_lc10 = sweep_rows["Low weighted", "width_LC10"] /
          sweep_rows["Wide", "width_LC10"],
        centred_over_wide_lc50 = sweep_rows["Centred", "width_LC50"] /
          sweep_rows["Wide", "width_LC50"]), 4)

## ---- fig-designs ----
sweep_curve$design <- factor(sweep_curve$design, levels = names(designs))
des_cols <- c(Centred = te_pal$clay, Wide = te_pal$forest,
              "Low weighted" = te_pal$green, "Very narrow" = te_pal$gold)

p_designs <- ggplot(sweep_curve, aes(lev, width, colour = design)) +
  geom_line(linewidth = 1) +
  scale_x_continuous(transform = "logit", breaks = c(0.01, 0.05, 0.1, 0.2, 0.5),
                     labels = c("LC1", "LC5", "LC10", "LC20", "LC50")) +
  scale_y_continuous(transform = "log10", breaks = c(0.3, 0.5, 1, 2, 4),
                     labels = c("0.3", "0.5", "1.0", "2.0", "4.0")) +
  scale_colour_manual(values = des_cols, name = "Concentrations") +
  labs(x = "Effective dose being estimated",
       y = "Interval width (log10 concentration units)",
       title = "The concentration layout decides which effective dose is precise") +
  theme_te() +
  theme(legend.position = "right")
p_designs

## ---- thumb ----
ggsave("thumbnail.png",
       p_designs + labs(title = NULL) +
         theme(plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = te_pal$paper)

## ---- animals ----
set.seed(20260730)
mult <- c(1, 2, 3, 4, 6, 8, 12)
target <- sweep_rows["Low weighted", "width_LC10"]
dz <- designs$Centred
grow <- t(sapply(mult, function(m) {
  Ym <- simulate_counts(dz$x, dz$n_an * m, 2000)
  fm <- fit_many(dz$x, dz$n_an * m, Ym)
  b10 <- fieller_log(0.1, fm); b50 <- fieller_log(0.5, fm)
  c(multiple = m, animals = sum(dz$n_an * m),
    width_LC10 = median(b10[, 2] - b10[, 1]),
    width_LC50 = median(b50[, 2] - b50[, 1]))
}))
print(round(grow, 4))
n_need <- exp(approx(log(grow[, "width_LC10"]), log(grow[, "animals"]),
                     xout = log(target))$y)
sl_fit <- coef(lm(log(grow[, "width_LC10"]) ~ log(grow[, "animals"])))[2]
round(c(target_width = target, animals_needed = n_need,
        animals_needed_rounded = round(n_need),
        animal_factor = n_need / sum(dz$n_an),
        width_slope_against_animals = as.numeric(sl_fit)), 4)

## ---- fig-animals ----
gd <- data.frame(animals = grow[, "animals"], width = grow[, "width_LC10"])

ggplot(gd, aes(animals, width)) +
  geom_hline(yintercept = target, colour = te_pal$green, linewidth = 1) +
  geom_segment(x = log10(n_need), xend = log10(n_need), y = 0.2, yend = target,
               colour = te_pal$ink, linetype = "dashed", linewidth = 0.6) +
  geom_line(colour = te_pal$clay, linewidth = 1) +
  geom_point(colour = te_pal$clay, size = 2.6) +
  annotate("point", x = n_need, y = target, colour = te_pal$ink, shape = 4,
           size = 4, stroke = 1.3) +
  annotate("text", x = 470, y = 0.95,
           label = "440 animals in the centred layout", hjust = 0, size = 3.2,
           colour = "#2c3a31") +
  annotate("text", x = 700, y = target + 0.06,
           label = "low weighted layout, 150 animals", hjust = 0, size = 3.2,
           colour = "#2c3a31") +
  scale_x_continuous(transform = "log10", breaks = c(150, 300, 600, 1200, 1800),
                     labels = c("150", "300", "600", "1200", "1800")) +
  labs(x = "Animals in the test (log scale)",
       y = "LC10 interval width (log10 concentration units)",
       title = "Nearly three times the animals buys what the layout gives away") +
  theme_te()

## ---- misplaced ----
set.seed(20260730)
truths <- c(4, 12, 36)
mis <- NULL
for (tl in truths) {
  for (nm in c("Centred", "Wide", "Low weighted")) {
    dz <- designs[[nm]]
    Ym <- simulate_counts(dz$x, dz$n_an, 2000, x50 = log10(tl))
    fm <- fit_many(dz$x, dz$n_an, Ym)
    b10 <- fieller_log(0.1, fm); b50 <- fieller_log(0.5, fm)
    mis <- rbind(mis, c(true_lc50 = tl, design = which(names(designs) == nm),
                        width_LC50 = median(b50[, 2] - b50[, 1]),
                        width_LC10 = median(b10[, 2] - b10[, 1]),
                        unbounded = mean(!is.finite(b10[, 2] - b10[, 1]))))
  }
}
mis <- data.frame(design = names(designs)[mis[, "design"]],
                  true_lc50 = mis[, "true_lc50"],
                  width_LC50 = round(mis[, "width_LC50"], 4),
                  width_LC10 = round(mis[, "width_LC10"], 4),
                  unbounded = round(mis[, "unbounded"], 4))
print(mis)
round(c(low_over_centred_lc10_at_true_4 =
          mis$width_LC10[mis$true_lc50 == 4 & mis$design == "Low weighted"] /
          mis$width_LC10[mis$true_lc50 == 4 & mis$design == "Centred"],
        low_lc10_spread_across_truths = max(mis$width_LC10[mis$design == "Low weighted"]) /
          min(mis$width_LC10[mis$design == "Low weighted"]),
        centred_lc50_spread_across_truths = max(mis$width_LC50[mis$design == "Centred"]) /
          min(mis$width_LC50[mis$design == "Centred"])), 4)

## ---- optimum ----
q_lev     <- 0.1
n_total   <- sum(designs[["Low weighted"]]$n_an)
x_q       <- lx_true(q_lev)
width_low <- sweep_rows["Low weighted", "width_LC10"]

# Standard error of the fitted LC10 for an arbitrary layout: the information is
# M = N sum_j w_j v_j f_j f_j' with f_j = (1, x_j) and v_j = p_j (1 - p_j), and the
# delta method gives var(x_q) = (1 / b^2) (1, x_q) M^-1 (1, x_q)'.
se_design <- function(x_pts, w) {
  pp <- 1 / (1 + exp(-slope_true * (x_pts - x50_true)))
  Fm <- cbind(1, x_pts)
  Mm <- n_total * crossprod(Fm, w * pp * (1 - pp) * Fm)
  cv <- c(1, x_q)
  c(se = sqrt(drop(cv %*% solve(Mm) %*% cv)) / slope_true, rcond = rcond(Mm))
}

# The layout the sweep measured, put through that same formula: its animal counts are
# the weights, so the bound and the layout are compared at one animal count and on one
# asymptotic scale.
w_low_layout   <- designs[["Low weighted"]]$n_an / n_total
se_low         <- se_design(designs[["Low weighted"]]$x, w_low_layout)[["se"]]
width_low_asym <- 2 * qnorm(0.975) * se_low

# For the logistic, 1 / sqrt(v(x)) is 2 cosh(b (x - x50) / 2), and the standard error
# of a two point layout is the chord of that function through the two concentrations,
# read off at the target, with the animals split between them in the best proportion.
g_inv <- function(x) 2 * cosh(slope_true * (x - x50_true) / 2)

shrink <- t(sapply(c(1, 0.5, 0.1, 0.01), function(gap) {
  x_pts <- x_q + c(-gap / 2, gap / 2)
  lagr  <- c(x_pts[2] - x_q, x_q - x_pts[1]) / (x_pts[2] - x_pts[1])
  aa    <- (lagr * g_inv(x_pts))^2
  w_low <- sqrt(aa[1]) / sum(sqrt(aa))
  c(gap = gap, weight_low = w_low,
    chord = sum(lagr * g_inv(x_pts)) / (slope_true * sqrt(n_total)),
    se_design(x_pts, c(w_low, 1 - w_low)))
}))
print(round(shrink, 6))

# A chord of a convex function never dips below it, so the floor is the function
# itself at the LC10: 1 / (b sqrt(N q (1 - q))). The layout that reaches it puts
# every animal on the LC10, and its information matrix has rank one.
se_opt      <- 1 / (slope_true * sqrt(n_total * q_lev * (1 - q_lev)))
width_opt   <- 2 * qnorm(0.975) * se_opt
rcond_point <- rcond(n_total * q_lev * (1 - q_lev) * tcrossprod(c(1, x_q)))
round(c(se_optimum = se_opt,
        se_from_the_convex_function = g_inv(x_q) / (slope_true * sqrt(n_total)),
        se_low_weighted = se_low,
        width_optimum = width_opt,
        width_low_weighted_asymptotic = width_low_asym,
        width_low_weighted_fieller_median = width_low,
        factor_above_the_optimum = width_low_asym / width_opt,
        per_cent_of_se_still_on_the_table = 100 * (1 - se_opt / se_low),
        rcond_at_the_optimum = rcond_point), 6)
