# Biotic index scores and sorting effort
# https://tidyecology.com/posts/biotic-index-scores-and-sample-size/
#
# 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)
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),
          strip.text       = element_text(colour = te_ink))
}

## ---- design ----
n_fam     <- 70
score     <- rep(1:10, each = 7)            # tolerance score of each family
psi_clean <- 0.6                            # presence probability, unimpaired
psi_hit   <- 0.3                            # presence of scores 7 to 10, impaired
hit_from  <- 7
sd_log    <- 1.5                            # log-abundance scatter among families
slopes    <- c(0, -0.1, -0.25, -0.4)        # log-abundance change per score unit
n_grid    <- c(50, 100, 200, 300, 500, 1000)
n_ref     <- 500                            # animals sorted at reference sites
n_common  <- 100                            # common count for the blanket repair
q_flag    <- 0.10                           # reference percentile used as threshold
sens_cut  <- 8                              # sensitive family: score 8 or more
n_refsite <- 10000                          # reference sites per slope
n_sites   <- 4000                           # unimpaired and impaired test sites

sort_sites <- function(n_s, b, psi_vec) {
  n_max <- max(n_grid)
  aspt <- bmwp <- pct_sens <- matrix(NA_real_, n_s, length(n_grid))
  true_aspt <- true_bmwp <- true_sens <- numeric(n_s)
  for (i in seq_len(n_s)) {
    present  <- runif(n_fam) < psi_vec
    abund    <- present * exp(b * (score - 5.5) + rnorm(n_fam, 0, sd_log))
    picked   <- sample.int(n_fam, n_max, replace = TRUE, prob = abund)
    first_at <- match(seq_len(n_fam), picked, nomatch = n_max + 1)
    sens_run <- cumsum(score[picked] >= sens_cut)
    for (j in seq_along(n_grid)) {
      seen <- first_at <= n_grid[j]
      aspt[i, j] <- mean(score[seen])
      bmwp[i, j] <- sum(score[seen])
    }
    pct_sens[i, ] <- sens_run[n_grid] / n_grid
    true_aspt[i]  <- mean(score[present])
    true_bmwp[i]  <- sum(score[present])
    true_sens[i]  <- sum(abund[score >= sens_cut]) / sum(abund)
  }
  list(aspt = aspt, bmwp = bmwp, pct_sens = pct_sens,
       true_aspt = true_aspt, true_bmwp = true_bmwp, true_sens = true_sens)
}

psi_ref <- rep(psi_clean, n_fam)
psi_imp <- ifelse(score >= hit_from, psi_hit, psi_clean)
col_of  <- function(n) match(n, n_grid)

## ---- simulate ----
set.seed(20260910)
runs <- lapply(slopes, function(b) list(
  ref  = sort_sites(n_refsite, b, psi_ref),
  test = sort_sites(n_sites, b, psi_ref),
  hit  = sort_sites(n_sites, b, psi_imp)))
names(runs) <- as.character(slopes)

## ---- drift ----
index_names <- c("BMWP-like sum", "ASPT-like average", "sensitive share of animals")
drift_tab <- do.call(rbind, lapply(seq_along(slopes), function(k) {
  tst <- runs[[k]]$test
  data.frame(slope = slopes[k], n = rep(n_grid, 3),
             index = rep(index_names, each = length(n_grid)),
             mean_value = c(colMeans(tst$bmwp), colMeans(tst$aspt),
                            colMeans(tst$pct_sens)),
             ratio = c(colMeans(tst$bmwp) / mean(tst$true_bmwp),
                       colMeans(tst$aspt) / mean(tst$true_aspt),
                       colMeans(tst$pct_sens) / mean(tst$true_sens)))
}))
dr <- function(b, n, idx, what = "mean_value") {
  drift_tab[[what]][drift_tab$slope == b & drift_tab$n == n & drift_tab$index == idx]
}
true_aspt_mean <- sapply(runs, function(r) mean(r$test$true_aspt))
sens_ratio_rng <- range(drift_tab$ratio[drift_tab$index == index_names[3]])
aspt_flat_rng  <- range(drift_tab$ratio[drift_tab$index == index_names[2] &
                                        drift_tab$slope == 0])

## ---- fig-drift ----
slope_cols <- c("0" = te_ink, "-0.1" = te_forest, "-0.25" = te_gold, "-0.4" = te_rust)
drift_tab$slope_f <- factor(as.character(drift_tab$slope), levels = names(slope_cols))
drift_tab$index_f <- factor(drift_tab$index, levels = index_names)
ggplot(drift_tab, aes(n, ratio, colour = slope_f)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.8) +
  facet_wrap(~ index_f, nrow = 1) +
  scale_x_log10(breaks = n_grid) +
  scale_colour_manual(values = slope_cols, name = "slope b") +
  labs(x = "animals sorted", y = "mean index / whole-site value") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        axis.text.x = element_text(angle = 45, hjust = 1))

## ---- flags ----
rule_names <- c("threshold from references at 500",
                "rarefy to the smaller count",
                "rarefy everyone to 100")
flag_tab <- do.call(rbind, lapply(seq_along(slopes), function(k) {
  r <- runs[[k]]
  thr_fixed <- quantile(r$ref$aspt[, col_of(n_ref)], q_flag, names = FALSE)
  thr_comm  <- quantile(r$ref$aspt[, col_of(n_common)], q_flag, names = FALSE)
  do.call(rbind, lapply(n_grid, function(n) {
    m <- min(n, n_ref)
    thr_match <- quantile(r$ref$aspt[, col_of(m)], q_flag, names = FALSE)
    data.frame(slope = slopes[k], n = n, rule = rule_names,
      false_flag = c(mean(r$test$aspt[, col_of(n)] < thr_fixed),
                     mean(r$test$aspt[, col_of(m)] < thr_match),
                     if (n >= n_common) mean(r$test$aspt[, col_of(n_common)] < thr_comm) else NA),
      power = c(mean(r$hit$aspt[, col_of(n)] < thr_fixed),
                mean(r$hit$aspt[, col_of(m)] < thr_match),
                if (n >= n_common) mean(r$hit$aspt[, col_of(n_common)] < thr_comm) else NA))
  }))
}))
# bootstrap Monte Carlo standard error: resample reference and test sites together
n_boot <- 200
set.seed(20260911)
boot_rate <- function(ref_col, test_col) {
  sd(replicate(n_boot, {
    thr <- quantile(ref_col[sample.int(length(ref_col), replace = TRUE)], q_flag,
                    names = FALSE)
    mean(test_col[sample.int(length(test_col), replace = TRUE)] < thr)
  }))
}
flag_tab$mcse <- flag_tab$tie <- NA_real_
for (k in seq_along(slopes)) for (n in n_grid) for (j in 1:3) {
  r <- runs[[k]]
  m <- c(n_ref, min(n, n_ref), n_common)[j]
  tcol <- c(n, min(n, n_ref), n_common)[j]
  if (j == 3 && n < n_common) next
  cell_row <- flag_tab$slope == slopes[k] & flag_tab$n == n & flag_tab$rule == rule_names[j]
  flag_tab$mcse[cell_row] <- boot_rate(r$ref$aspt[, col_of(m)], r$test$aspt[, col_of(tcol)])
  thr <- quantile(r$ref$aspt[, col_of(m)], q_flag, names = FALSE)
  flag_tab$tie[cell_row] <- mean(abs(r$test$aspt[, col_of(tcol)] - thr) < 1e-9)
}
ff <- function(b, n, rule = rule_names[1], what = "false_flag") {
  flag_tab[[what]][flag_tab$slope == b & flag_tab$n == n & flag_tab$rule == rule]
}
mcse_max <- max(flag_tab$mcse, na.rm = TRUE)
thr_of <- function(cell) {
  j <- match(cell$rule, rule_names)
  m <- c(n_ref, min(cell$n, n_ref), n_common)[j]
  quantile(runs[[as.character(cell$slope)]]$ref$aspt[, col_of(m)], q_flag, names = FALSE)
}
mcse_500 <- max(flag_tab$mcse[flag_tab$n == n_ref & flag_tab$rule == rule_names[1]])
matched  <- flag_tab[flag_tab$rule != rule_names[1] & !is.na(flag_tab$false_flag), ]
tie_med  <- median(matched$tie)
tie_cell <- flag_tab[flag_tab$slope == -0.25 & flag_tab$n == n_common &
                     flag_tab$rule == rule_names[3], ]
matched_rng <- range(flag_tab$false_flag[flag_tab$rule != rule_names[1]], na.rm = TRUE)

sens_flag <- sapply(runs, function(r) {
  thr <- quantile(r$ref$pct_sens[, col_of(n_ref)], q_flag, names = FALSE)
  mean(r$test$pct_sens[, col_of(50)] < thr)
})
sens_thr  <- sapply(runs, function(r)
  quantile(r$ref$pct_sens[, col_of(n_ref)], q_flag, names = FALSE))
sens_zero <- sapply(runs, function(r) mean(r$test$pct_sens[, col_of(50)] == 0))
sens_mcse <- sapply(runs, function(r)
  boot_rate(r$ref$pct_sens[, col_of(n_ref)], r$test$pct_sens[, col_of(50)]))

## ---- fig-falseflag ----
fixed_tab <- flag_tab[flag_tab$rule == rule_names[1], ]
fixed_tab$slope_f <- factor(as.character(fixed_tab$slope), levels = names(slope_cols))
ggplot(fixed_tab, aes(n, false_flag, colour = slope_f)) +
  geom_hline(yintercept = q_flag, linetype = "dashed", colour = te_body) +
  geom_vline(xintercept = n_ref, linetype = "dotted", colour = te_body) +
  geom_errorbar(aes(ymin = false_flag - 2 * mcse, ymax = false_flag + 2 * mcse),
                width = 0.03, linewidth = 0.5) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2) +
  scale_x_log10(breaks = n_grid) +
  scale_colour_manual(values = slope_cols, name = "slope b") +
  labs(x = "animals sorted at the test site",
       y = "unimpaired sites flagged") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- spread ----
spread_tab <- do.call(rbind, lapply(c(0, -0.25), function(b) {
  r <- runs[[as.character(b)]]
  do.call(rbind, lapply(c(100, 500), function(n) {
    data.frame(slope = factor(paste("slope b =", b),
                              levels = paste("slope b =", c(0, -0.25))),
               n = paste(n, "animals"),
               aspt = r$test$aspt[, col_of(n)])
  }))
}))
thr_lines <- data.frame(
  slope = factor(paste("slope b =", c(0, -0.25)), levels = paste("slope b =", c(0, -0.25))),
  thr = sapply(c("0", "-0.25"), function(s)
    quantile(runs[[s]]$ref$aspt[, col_of(n_ref)], q_flag, names = FALSE)))
sd_of <- function(b, n) sd(runs[[as.character(b)]]$test$aspt[, col_of(n)])
sd_true0 <- sd(runs[["0"]]$test$true_aspt)

## ---- fig-spread ----
ggplot(spread_tab, aes(aspt, fill = n, colour = n)) +
  geom_density(alpha = 0.35, linewidth = 0.6, adjust = 1.3) +
  geom_vline(data = thr_lines, aes(xintercept = thr), colour = te_rust,
             linewidth = 0.8) +
  facet_wrap(~ slope, nrow = 1) +
  scale_fill_manual(values = c("100 animals" = te_gold, "500 animals" = te_forest),
                    name = NULL) +
  scale_colour_manual(values = c("100 animals" = te_gold, "500 animals" = te_forest),
                      name = NULL) +
  labs(x = "ASPT-like average score", y = "density") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- fig-repair ----
rule_cols <- setNames(c(te_rust, te_forest, te_gold), rule_names)
rep_tab <- flag_tab[flag_tab$slope == -0.25, ]
rep_tab$rule <- factor(rep_tab$rule, levels = rule_names)
rep_tab <- rep_tab[!is.na(rep_tab$false_flag), ]
p_ff <- ggplot(rep_tab, aes(n, false_flag, colour = rule)) +
  geom_hline(yintercept = q_flag, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
  scale_x_log10(breaks = n_grid) +
  scale_colour_manual(values = rule_cols, name = NULL) +
  labs(x = "animals sorted at the test site", y = "unimpaired sites flagged") +
  theme_datasheet()
p_pw <- ggplot(rep_tab, aes(n, power, colour = rule)) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
  scale_x_log10(breaks = n_grid) +
  scale_y_continuous(limits = c(0, 1)) +
  scale_colour_manual(values = rule_cols, name = NULL) +
  labs(x = "animals sorted at the test site", y = "impaired sites flagged") +
  theme_datasheet()
(p_ff | p_pw) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet()) &
  theme(legend.position = "bottom",
        axis.text.x = element_text(angle = 45, hjust = 1))
