# Checking an adaptive sampling design
# https://tidyecology.com/posts/checking-an-adaptive-sampling-design/
#
# 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-11-06

## ---- setup ----
options(digits = 6)

make_population <- function(side = 20L, n_clusters = 5L, per_cluster = 22,
                            spread = 0.9, seed = 101L) {
  set.seed(seed); N <- side * side; y <- integer(N)
  cx0 <- runif(n_clusters, 2, side - 1); cy0 <- runif(n_clusters, 2, side - 1)
  for (k in seq_len(n_clusters)) {
    np <- rpois(1, per_cluster); if (np == 0) next
    cx <- pmin(pmax(round(rnorm(np, cx0[k], spread)), 1), side)
    cy <- pmin(pmax(round(rnorm(np, cy0[k], spread)), 1), side)
    cell <- (cy - 1) * side + cx
    tb <- table(cell); idx <- as.integer(names(tb)); y[idx] <- y[idx] + as.integer(tb)
  }
  list(side = side, N = N, y = y)
}
rook <- function(i, side) {
  x <- ((i - 1) %% side) + 1L; yy <- ((i - 1) %/% side) + 1L
  nb <- integer(0)
  if (x > 1) nb <- c(nb, i - 1L); if (x < side) nb <- c(nb, i + 1L)
  if (yy > 1) nb <- c(nb, i - side); if (yy < side) nb <- c(nb, i + side)
  nb
}
build_networks <- function(pop, cval = 1L) {
  side <- pop$side; N <- pop$N; y <- pop$y; sat <- y >= cval
  net_id <- integer(N); cur <- 0L; seen <- logical(N)
  for (i in seq_len(N)) {
    if (seen[i]) next
    if (!sat[i]) { cur <- cur + 1L; net_id[i] <- cur; seen[i] <- TRUE; next }
    cur <- cur + 1L; stack <- i; seen[i] <- TRUE; net_id[i] <- cur
    while (length(stack)) {
      u <- stack[length(stack)]; stack <- stack[-length(stack)]
      for (v in rook(u, side)) if (!seen[v] && sat[v]) {
        seen[v] <- TRUE; net_id[v] <- cur; stack <- c(stack, v) }
    }
  }
  m <- as.integer(table(net_id)); tot <- as.numeric(tapply(y, net_id, sum))
  list(net_id = net_id, m = m, tot = tot, sat = sat,
       net_mean_of_unit = (tot / m)[net_id],
       net_is_sat = as.logical(tapply(sat, net_id, function(z) z[1])))
}
choose2 <- function(a, b) { out <- exp(lchoose(a, b)); out[b < 0 | b > a] <- 0; out }

acs_draw <- function(pop, nets, n1) {
  N <- pop$N; side <- pop$side
  init <- sample.int(N, n1); hit <- unique(nets$net_id[init])
  in_s <- logical(N); in_s[init] <- TRUE
  ubn <- split(seq_len(N), nets$net_id)
  for (k in hit) { uk <- ubn[[k]]; in_s[uk] <- TRUE
    if (nets$net_is_sat[k]) for (u in uk) for (v in rook(u, side)) in_s[v] <- TRUE }
  a <- 1 - choose2(N - nets$m[hit], n1) / choose2(N, n1)
  list(ht = sum(nets$tot[hit] / a) / N, n_final = sum(in_s))
}
srs_mean <- function(pop, n, B, seed) {
  set.seed(seed); N <- pop$N; y <- pop$y
  vapply(1:B, function(b) mean(y[sample.int(N, n)]), numeric(1))
}

pop <- make_population(); nets <- build_networks(pop, 1L)
N <- pop$N; mu <- mean(pop$y); n1 <- 30L
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

## ---- threshold-sweep ----
sweep_threshold <- function(cvals, B = 12000L) {
  do.call(rbind, lapply(cvals, function(cv) {
    nn <- build_networks(pop, cval = cv)
    set.seed(21); ht <- nf <- numeric(B)
    for (b in 1:B) { d <- acs_draw(pop, nn, n1); ht[b] <- d$ht; nf[b] <- d$n_final }
    ne <- round(mean(nf)); sr <- srs_mean(pop, ne, B, 22L)
    data.frame(condition = cv, networks = sum(nn$net_is_sat),
               mean_final_n = mean(nf), se = sd(ht),
               efficiency = var(sr) / var(ht))
  }))
}
th <- sweep_threshold(1:3)
round(th, 3)

## ---- fig-threshold ----
ggplot(th, aes(mean_final_n, se)) +
  geom_line(colour = "#93a87f", linewidth = 0.8) +
  geom_point(colour = "#275139", size = 3) +
  geom_text(aes(label = paste0("condition = ", condition), hjust = c(1, 0, 0)),
            nudge_x = c(-1.2, 1.2, 1.2), nudge_y = 0.006, size = 3.2, colour = "#16241d") +
  scale_x_continuous(expand = expansion(mult = 0.14)) +
  scale_y_continuous(expand = expansion(mult = 0.14)) +
  labs(x = "mean quadrats visited", y = "standard error of the estimate") +
  theme_minimal(base_size = 11) + te_canvas + theme(panel.grid.minor = element_blank())

## ---- budget ----
set.seed(202); B <- 20000L; nf <- numeric(B)
for (b in 1:B) nf[b] <- acs_draw(pop, nets, n1)$n_final
c(planned_initial = n1, mean = round(mean(nf), 1), sd = round(sd(nf), 1),
  q90 = unname(quantile(nf, 0.9)), max = max(nf))

## ---- budget-probs ----
budgets <- c(60, 80, 100, 120)
setNames(round(sapply(budgets, function(b) mean(nf > b)), 3), budgets)

## ---- budget-nums ----
p80 <- mean(nf > 80); p120 <- mean(nf > 120); q90 <- unname(quantile(nf, 0.9))

## ---- fig-budget ----
bs <- seq(min(nf), max(nf), by = 1)
ex <- data.frame(budget = bs, p = sapply(bs, function(b) mean(nf > b)))
ggplot(ex, aes(budget, p)) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_vline(xintercept = q90, linetype = 2, colour = "#b5534e") +
  annotate("text", x = q90 - 2, y = 0.75, label = "90th percentile",
           hjust = 1, size = 3.2, colour = "#b5534e") +
  labs(x = "budget (quadrats)", y = "probability of exceeding it") +
  theme_minimal(base_size = 11) + te_canvas + theme(panel.grid.minor = element_blank())

## ---- double-count ----
ht_double <- function(pop, nets, n1, B, seed) {          # WRONG on purpose
  set.seed(seed); N <- pop$N; est <- numeric(B)
  for (b in 1:B) {
    init <- sample.int(N, n1)
    hit  <- nets$net_id[init]                            # no unique(): repeats
    a <- 1 - choose2(N - nets$m[hit], n1) / choose2(N, n1)
    est[b] <- sum(nets$tot[hit] / a) / N
  }
  est
}
wrong <- ht_double(pop, nets, n1, 20000L, 202L)
set.seed(202); right <- numeric(20000L)
for (b in 1:20000L) right[b] <- acs_draw(pop, nets, n1)$ht
c(truth = round(mu, 4), correct = round(mean(right), 4),
  double_counted = round(mean(wrong), 4))

## ---- dc-nums ----
dc_bias <- mean(wrong) - mu; dc_pct <- 100 * dc_bias / mu

## ---- fig-double-count ----
dd <- rbind(data.frame(est = right, which = "distinct networks (correct)"),
            data.frame(est = wrong, which = "one entry per hit (wrong)"))
ggplot(dd, aes(est, colour = which)) +
  geom_density(linewidth = 0.9) +
  geom_vline(xintercept = mu, linetype = 2, colour = "#16241d") +
  scale_colour_manual(values = c("distinct networks (correct)" = "#275139",
                                 "one entry per hit (wrong)" = "#b5534e"), name = NULL) +
  coord_cartesian(xlim = c(0, 1.2)) +
  labs(x = "estimated mean count per quadrat", y = "density") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())
