# Choosing a decision threshold from costs
# https://tidyecology.com/posts/decision-thresholds-and-costs/
#
# 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-09-30

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

## ---- simdata ----
set.seed(20260815)
n_train <- 4000
n_pop <- 200000
beta0 <- -1.15
beta1 <- 1.20
beta2 <- -0.75

sim_sites <- function(nn, intercept) {
  x1 <- rnorm(nn)
  x2 <- rnorm(nn)
  pp <- plogis(intercept + beta1 * x1 + beta2 * x2)
  data.frame(y = rbinom(nn, 1, pp), x1 = x1, x2 = x2)
}

train_dat <- sim_sites(n_train, beta0)
pop_dat <- sim_sites(n_pop, beta0)
fit_main <- glm(y ~ x1 + x2, family = binomial, data = train_dat)
pop_dat$phat <- as.numeric(predict(fit_main, newdata = pop_dat, type = "response"))

auc_rank <- function(ph, yy) {
  rk <- rank(ph)
  n1 <- as.numeric(sum(yy == 1))
  n0 <- as.numeric(sum(yy == 0))
  (sum(rk[yy == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}

cat(sprintf("training sites %d, held-out sites %d\n", n_train, n_pop))
cat(sprintf("prevalence: training %.4f, held-out %.4f\n",
            mean(train_dat$y), mean(pop_dat$y)))
cat(sprintf("held-out AUC %.4f\n", auc_rank(pop_dat$phat, pop_dat$y)))
cat(sprintf("mean predicted probability %.4f against observed %.4f\n",
            mean(pop_dat$phat), mean(pop_dat$y)))

## ---- sweepfun ----
sweep_counts <- function(ph, yy, thr_at) {
  o <- order(ph)
  ps <- ph[o]
  ys <- yy[o]
  n1 <- sum(ys)
  n0 <- length(ys) - n1
  k <- findInterval(thr_at, ps, left.open = TRUE)
  false_neg <- c(0, cumsum(ys))[k + 1]
  true_neg <- c(0, cumsum(1 - ys))[k + 1]
  data.frame(thr = thr_at, tp = n1 - false_neg, fp = n0 - true_neg,
             fn = false_neg, tn = true_neg)
}

thr_seq <- seq(0.001, 0.999, by = 0.001)
cnt_main <- sweep_counts(pop_dat$phat, pop_dat$y, thr_seq)

at_grid <- function(thr_at, target) which.min(abs(thr_at - target))
chk_at <- 0.37
chk_j <- at_grid(thr_seq, chk_at)
acted <- pop_dat$phat >= chk_at
cat(sprintf("thresholds on the grid: %d, from %.3f to %.3f\n",
            length(thr_seq), min(thr_seq), max(thr_seq)))
cat(sprintf("cross-check at %.2f: sweep gives tp %d and fp %d, direct count %d and %d\n",
            chk_at, cnt_main$tp[chk_j], cnt_main$fp[chk_j],
            sum(acted & pop_dat$y == 1), sum(acted & pop_dat$y == 0)))

## ---- costverify ----
cost_curve <- function(cnt, cost_fp, cost_fn, nn) {
  (cost_fp * cnt$fp + cost_fn * cnt$fn) / nn
}

ratio_set <- c(1, 4, 19)
verify_tab <- do.call(rbind, lapply(ratio_set, function(rr) {
  cost_fp <- 1
  cost_fn <- rr
  t_star <- cost_fp / (cost_fp + cost_fn)
  cc <- cost_curve(cnt_main, cost_fp, cost_fn, n_pop)
  j <- which.min(cc)
  data.frame(cost_ratio = rr, analytic = t_star, empirical = thr_seq[j],
             cost_analytic = cc[which.min(abs(thr_seq - t_star))],
             cost_empirical = cc[j])
}))
verify_tab$excess <- verify_tab$cost_analytic - verify_tab$cost_empirical
print(round(verify_tab, 5))

## ---- costfig ----
panel_lab <- sprintf("cost ratio %d to 1", ratio_set)
cost_dat <- do.call(rbind, lapply(seq_along(ratio_set), function(i) {
  focus <- verify_tab$analytic[i]
  keep <- thr_seq >= focus / 4 & thr_seq <= min(0.9, focus * 4)
  data.frame(panel = panel_lab[i], thr = thr_seq[keep],
             cost = cost_curve(cnt_main, 1, ratio_set[i], n_pop)[keep])
}))
cost_dat$panel <- factor(cost_dat$panel, levels = panel_lab)
mark_dat <- data.frame(panel = factor(panel_lab, levels = panel_lab),
                       thr = verify_tab$empirical, cost = verify_tab$cost_empirical,
                       vline = verify_tab$analytic)

ggplot(cost_dat, aes(thr, cost)) +
  geom_line(colour = te_pal$forest, linewidth = 0.9) +
  geom_vline(data = mark_dat, aes(xintercept = vline),
             linetype = "dashed", colour = te_pal$clay) +
  geom_point(data = mark_dat, colour = te_pal$clay, size = 2.6) +
  facet_wrap(~ panel, scales = "free") +
  labs(title = "The formula lands where the data does",
       x = "decision threshold", y = "expected cost per site") +
  theme_te()

## ---- impliedrules ----
set.seed(20260816)
beta0_rare <- -3.30
train_rare <- sim_sites(n_train, beta0_rare)
pop_rare <- sim_sites(n_pop, beta0_rare)
fit_rare <- glm(y ~ x1 + x2, family = binomial, data = train_rare)
pop_rare$phat <- as.numeric(predict(fit_rare, newdata = pop_rare, type = "response"))

rules_for <- function(ph, yy) {
  cnt <- sweep_counts(ph, yy, thr_seq)
  sens <- cnt$tp / (cnt$tp + cnt$fn)
  spec <- cnt$tn / (cnt$tn + cnt$fp)
  thr_rule <- c(0.5, thr_seq[which.max(sens + spec - 1)],
                thr_seq[which.min(abs(sens - spec))], round(mean(yy), 3))
  data.frame(threshold = thr_rule, implied_ratio = (1 - thr_rule) / thr_rule)
}

rule_name <- c("fixed 0.5", "max TSS", "sens = spec", "prevalence")
common_rules <- rules_for(pop_dat$phat, pop_dat$y)
rare_rules <- rules_for(pop_rare$phat, pop_rare$y)
implied_tab <- data.frame(rule = rule_name,
                          thr_common = common_rules$threshold,
                          ratio_common = common_rules$implied_ratio,
                          thr_rare = rare_rules$threshold,
                          ratio_rare = rare_rules$implied_ratio)
cat(sprintf("common setting: prevalence %.4f, AUC %.4f\n",
            mean(pop_dat$y), auc_rank(pop_dat$phat, pop_dat$y)))
cat(sprintf("rare setting: prevalence %.4f, AUC %.4f\n",
            mean(pop_rare$y), auc_rank(pop_rare$phat, pop_rare$y)))
print(format(implied_tab, digits = 3))
cat(sprintf("max TSS implied ratio moves by a factor of %.2f\n",
            implied_tab$ratio_rare[2] / implied_tab$ratio_common[2]))

## ---- netbenefit ----
net_benefit <- function(ph, yy, thr_at) {
  cnt <- sweep_counts(ph, yy, thr_at)
  nn <- length(yy)
  cnt$tp / nn - (cnt$fp / nn) * thr_at / (1 - thr_at)
}
nb_treat_all <- function(prev, thr_at) prev - (1 - prev) * thr_at / (1 - thr_at)

nb_seq <- seq(0.02, 0.60, by = 0.005)
nb_model <- net_benefit(pop_dat$phat, pop_dat$y, nb_seq)
nb_all <- nb_treat_all(mean(pop_dat$y), nb_seq)
wins <- nb_model > nb_all & nb_model > 0
cat(sprintf("thresholds examined %d, from %.2f to %.2f\n",
            length(nb_seq), min(nb_seq), max(nb_seq)))
cat(sprintf("calibrated model beats both defaults at %d of them, from %.2f to %.2f\n",
            sum(wins), min(nb_seq[wins]), max(nb_seq[wins])))
j20 <- at_grid(nb_seq, 0.20)
cat(sprintf("at threshold %.2f: model %.4f, treat all %.4f, treat none %.4f\n",
            nb_seq[j20], nb_model[j20], nb_all[j20], 0))

## ---- transferfail ----
set.seed(20260817)
beta0_hi <- 0.30
pop_hi <- sim_sites(n_pop, beta0_hi)
pop_hi$phat <- as.numeric(predict(fit_main, newdata = pop_hi, type = "response"))

nb_hi <- net_benefit(pop_hi$phat, pop_hi$y, nb_seq)
nb_hi_all <- nb_treat_all(mean(pop_hi$y), nb_seq)
mgr_lo <- 0.05
mgr_hi <- 0.25
in_mgr <- nb_seq >= mgr_lo & nb_seq <= mgr_hi
cat(sprintf("transfer region: prevalence %.4f, AUC %.4f, mean predicted %.4f\n",
            mean(pop_hi$y), auc_rank(pop_hi$phat, pop_hi$y), mean(pop_hi$phat)))
cat(sprintf("manager range %.2f to %.2f: model beats treat all at %d of %d thresholds\n",
            mgr_lo, mgr_hi, sum(nb_hi[in_mgr] > nb_hi_all[in_mgr]), sum(in_mgr)))
j10 <- at_grid(nb_seq, 0.10)
cat(sprintf("at threshold %.2f: model %.4f, treat all %.4f, shortfall %.4f\n",
            nb_seq[j10], nb_hi[j10], nb_hi_all[j10], nb_hi_all[j10] - nb_hi[j10]))
cat(sprintf("the transferred model overtakes treat all only from %.3f\n",
            min(nb_seq[nb_hi > nb_hi_all])))

## ---- dcafig ----
nb_panel <- c("calibrated, own region", "transferred, commoner region")
nb_dat <- rbind(
  data.frame(panel = nb_panel[1], thr = nb_seq, nb = nb_model, kind = "model"),
  data.frame(panel = nb_panel[1], thr = nb_seq, nb = nb_all, kind = "treat all"),
  data.frame(panel = nb_panel[1], thr = nb_seq, nb = 0, kind = "treat none"),
  data.frame(panel = nb_panel[2], thr = nb_seq, nb = nb_hi, kind = "model"),
  data.frame(panel = nb_panel[2], thr = nb_seq, nb = nb_hi_all, kind = "treat all"),
  data.frame(panel = nb_panel[2], thr = nb_seq, nb = 0, kind = "treat none"))
nb_dat$panel <- factor(nb_dat$panel, levels = nb_panel)
band_dat <- data.frame(panel = factor(nb_panel, levels = nb_panel),
                       x1 = mgr_lo, x2 = mgr_hi)

ggplot(nb_dat, aes(thr, nb, colour = kind, linetype = kind)) +
  geom_rect(data = band_dat, aes(xmin = x1, xmax = x2, ymin = -Inf, ymax = Inf),
            inherit.aes = FALSE, fill = te_pal$sage, alpha = 0.22) +
  geom_line(linewidth = 0.9) +
  facet_wrap(~ panel) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay, te_pal$ink)) +
  scale_linetype_manual(values = c("solid", "solid", "dashed")) +
  coord_cartesian(ylim = c(-0.1, 0.6)) +
  labs(title = "Beating treat all is not automatic",
       x = "decision threshold", y = "net benefit per site",
       colour = NULL, linetype = NULL) +
  theme_te() +
  theme(legend.position = "top")

## ---- miscal ----
set.seed(20260818)
half_i <- sample.int(n_pop, n_pop / 2)
cal_dat <- pop_dat[half_i, ]
eval_dat <- pop_dat[-half_i, ]

distort <- function(ph) plogis(2 * qlogis(ph))
cal_dat$p_dist <- distort(cal_dat$phat)
eval_dat$p_dist <- distort(eval_dat$phat)

fit_cal <- glm(y ~ qlogis(p_dist), family = binomial, data = cal_dat)
eval_dat$p_recal <- as.numeric(predict(fit_cal, newdata = eval_dat, type = "response"))

cost_fp <- 1
cost_fn <- 4
t_star <- cost_fp / (cost_fp + cost_fn)
realised_cost <- function(ph, yy, thr) {
  act <- ph >= thr
  (cost_fp * sum(act & yy == 0) + cost_fn * sum(!act & yy == 1)) / length(yy)
}

cat(sprintf("calibration sites %d, evaluation sites %d, cost ratio %d to 1, t* %.2f\n",
            nrow(cal_dat), nrow(eval_dat), cost_fn / cost_fp, t_star))
cat(sprintf("AUC calibrated %.4f, distorted %.4f, recalibrated %.4f\n",
            auc_rank(eval_dat$phat, eval_dat$y), auc_rank(eval_dat$p_dist, eval_dat$y),
            auc_rank(eval_dat$p_recal, eval_dat$y)))
cat(sprintf("mean predicted: calibrated %.4f, distorted %.4f, recalibrated %.4f, observed %.4f\n",
            mean(eval_dat$phat), mean(eval_dat$p_dist), mean(eval_dat$p_recal),
            mean(eval_dat$y)))

cost_good <- realised_cost(eval_dat$phat, eval_dat$y, t_star)
cost_bad <- realised_cost(eval_dat$p_dist, eval_dat$y, t_star)
cost_fix <- realised_cost(eval_dat$p_recal, eval_dat$y, t_star)
cat(sprintf("cost per site at t*: calibrated %.4f, distorted %.4f, recalibrated %.4f\n",
            cost_good, cost_bad, cost_fix))
cat(sprintf("excess from miscalibration alone %.4f, that is %.1f per cent\n",
            cost_bad - cost_good, 100 * (cost_bad - cost_good) / cost_good))
cat(sprintf("recovered by recalibration %.4f\n", cost_bad - cost_fix))

cc_dist <- cost_curve(sweep_counts(eval_dat$p_dist, eval_dat$y, thr_seq),
                      cost_fp, cost_fn, nrow(eval_dat))
cat(sprintf("on the distorted scale the best cut is %.3f, giving cost %.4f\n",
            thr_seq[which.min(cc_dist)], min(cc_dist)))
cat(sprintf("the distorted image of t* is %.4f\n", distort(t_star)))
cat(sprintf("cutting the distorted scale at t* really cuts the true scale at %.4f\n",
            plogis(qlogis(t_star) / 2)))

## ---- calfig ----
rel_bins <- function(ph, yy, tag, n_bin = 20) {
  br <- unique(quantile(ph, seq(0, 1, length.out = n_bin + 1)))
  g <- cut(ph, br, include.lowest = TRUE)
  data.frame(kind = tag, pred = as.numeric(tapply(ph, g, mean)),
             obs = as.numeric(tapply(yy, g, mean)))
}
rel_dat <- rbind(rel_bins(eval_dat$phat, eval_dat$y, "calibrated"),
                 rel_bins(eval_dat$p_dist, eval_dat$y, "distorted"),
                 rel_bins(eval_dat$p_recal, eval_dat$y, "recalibrated"))

ggplot(rel_dat, aes(pred, obs, colour = kind, shape = kind)) +
  geom_abline(slope = 1, intercept = 0, colour = te_pal$sage, linewidth = 1.1) +
  geom_vline(xintercept = t_star, linetype = "dashed", colour = te_pal$ink) +
  geom_point(size = 2.4) +
  geom_line(linewidth = 0.6) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay, te_pal$gold)) +
  labs(title = "Same ranking, different probabilities",
       x = "mean predicted probability in bin", y = "observed frequency in bin",
       colour = NULL, shape = NULL) +
  theme_te() +
  theme(legend.position = "top", plot.margin = margin(5.5, 16, 5.5, 5.5))

## ---- bootthr ----
set.seed(20260819)
n_small <- 500
n_boot <- 1000
survey <- eval_dat[sample.int(nrow(eval_dat), n_small), ]

tss_thr <- function(ph, yy) {
  cnt <- sweep_counts(ph, yy, thr_seq)
  tss <- cnt$tp / (cnt$tp + cnt$fn) + cnt$tn / (cnt$tn + cnt$fp) - 1
  thr_seq[which.max(tss)]
}
boot_thr <- replicate(n_boot, {
  ii <- sample.int(n_small, n_small, replace = TRUE)
  tss_thr(survey$phat[ii], survey$y[ii])
})
qq <- unname(quantile(boot_thr, c(0.025, 0.975)))
cat(sprintf("survey sites %d with %d presences, bootstrap resamples %d\n",
            n_small, sum(survey$y), n_boot))
cat(sprintf("max TSS threshold on the survey %.3f, bootstrap mean %.3f, sd %.3f\n",
            tss_thr(survey$phat, survey$y), mean(boot_thr), sd(boot_thr)))
cat(sprintf("bootstrap 2.5 to 97.5 per cent interval %.3f to %.3f, width %.3f\n",
            qq[1], qq[2], qq[2] - qq[1]))
cat(sprintf("implied cost ratio at those ends: %.1f to 1 and %.1f to 1\n",
            (1 - qq[1]) / qq[1], (1 - qq[2]) / qq[2]))

## ---- estpenalty ----
set.seed(20260820)
n_rep <- 400
est_thr <- replicate(n_rep, {
  ii <- sample.int(nrow(eval_dat), n_small)
  cc <- cost_curve(sweep_counts(eval_dat$phat[ii], eval_dat$y[ii], thr_seq),
                   cost_fp, cost_fn, n_small)
  thr_seq[which.min(cc)]
})
cost_of <- function(thr) realised_cost(eval_dat$phat, eval_dat$y, thr)
cost_est <- vapply(est_thr, cost_of, numeric(1))
cat(sprintf("replicate surveys %d of %d sites each\n", n_rep, n_small))
cat(sprintf("estimated cut: mean %.3f, sd %.3f, against the formula value %.2f\n",
            mean(est_thr), sd(est_thr), t_star))
cat(sprintf("cost with the estimated cut %.4f, with the formula %.4f\n",
            mean(cost_est), cost_of(t_star)))
cat(sprintf("penalty for estimating rather than computing %.4f, that is %.2f per cent\n",
            mean(cost_est) - cost_of(t_star),
            100 * (mean(cost_est) - cost_of(t_star)) / cost_of(t_star)))

## ---- flatness ----
excess_for <- function(true_ratio) {
  assumed <- exp(seq(log(1), log(60), length.out = 121))
  cnt_a <- sweep_counts(eval_dat$phat, eval_dat$y, 1 / (1 + assumed))
  cc <- cost_curve(cnt_a, 1, true_ratio, nrow(eval_dat))
  best <- min(cost_curve(sweep_counts(eval_dat$phat, eval_dat$y, thr_seq),
                         1, true_ratio, nrow(eval_dat)))
  data.frame(true_ratio = sprintf("true ratio %d to 1", true_ratio),
             assumed = assumed, excess = cc / best - 1)
}
flat_dat <- rbind(excess_for(4), excess_for(19))
report_at <- c(1, 2, 4, 8, 19, 40)
for (rr in report_at) {
  a4 <- flat_dat[flat_dat$true_ratio == "true ratio 4 to 1", ]
  a19 <- flat_dat[flat_dat$true_ratio == "true ratio 19 to 1", ]
  cat(sprintf("assumed ratio %5.1f: excess %.3f when the truth is 4, %.3f when it is 19\n",
              rr, a4$excess[which.min(abs(a4$assumed - rr))],
              a19$excess[which.min(abs(a19$assumed - rr))]))
}
tol <- 0.05
for (tag in unique(flat_dat$true_ratio)) {
  sub_dat <- flat_dat[flat_dat$true_ratio == tag & flat_dat$excess < tol, ]
  cat(sprintf("%s: within %.2f of optimal for assumed ratios %.1f to %.1f\n",
              tag, tol, min(sub_dat$assumed), max(sub_dat$assumed)))
}

## ---- flatfig ----
ratio_lab <- c("true ratio 4 to 1", "true ratio 19 to 1")
truth_dat <- data.frame(true_ratio = factor(ratio_lab, levels = ratio_lab),
                        vline = c(4, 19))
flat_dat$true_ratio <- factor(flat_dat$true_ratio, levels = ratio_lab)

ggplot(flat_dat, aes(assumed, excess, colour = true_ratio)) +
  geom_hline(yintercept = tol, colour = te_pal$ink, linetype = "dotted",
             linewidth = 0.7) +
  geom_vline(data = truth_dat, aes(xintercept = vline, colour = true_ratio),
             linetype = "dashed", show.legend = FALSE) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay)) +
  scale_x_log10(breaks = c(1, 2, 5, 10, 20, 50)) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(title = "A shallow valley, not a spike",
       x = "assumed cost ratio", y = "relative excess cost", colour = NULL) +
  theme_te() +
  theme(legend.position = "top")
