# When does adaptive sampling pay?
# https://tidyecology.com/posts/when-does-adaptive-sampling-pay/
#
# 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; y <- pop$y; 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))
}
vmr <- function(pop) var(pop$y) / mean(pop$y)

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

## ---- mc-compare ----
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))
}
acs_mc <- function(pop, nets, n1, B, seed) {
  set.seed(seed); ht <- nf <- numeric(B)
  for (b in 1:B) { d <- acs_draw(pop, nets, n1); ht[b] <- d$ht; nf[b] <- d$n_final }
  list(ht = ht, nf = nf)
}
A    <- acs_mc(pop, nets, n1, 20000L, 202L)
srs1 <- srs_mean(pop, n1, 20000L, 303L)        # same INITIAL sample size
c(sd_srs_30 = round(sd(srs1), 4), sd_adaptive = round(sd(A$ht), 4),
  efficiency = round(var(srs1) / var(A$ht), 2))

## ---- final-n ----
c(mean_final_n = round(mean(A$nf), 1), sd_final_n = round(sd(A$nf), 1),
  min_final_n = min(A$nf), max_final_n = max(A$nf))

## ---- fig-final-n ----
ggplot(data.frame(n = A$nf), aes(n)) +
  geom_histogram(binwidth = 4, fill = "#93a87f", colour = "white", linewidth = 0.2) +
  geom_vline(xintercept = n1, linetype = 2, colour = "#b5534e") +
  geom_vline(xintercept = mean(A$nf), linetype = 2, colour = "#16241d") +
  annotate("text", x = n1 + 3, y = Inf, label = "initial n", vjust = 1.6,
           hjust = 0, size = 3.2, colour = "#b5534e") +
  annotate("text", x = mean(A$nf) + 3, y = Inf, label = "mean final n", vjust = 1.6,
           hjust = 0, size = 3.2, colour = "#16241d") +
  labs(x = "quadrats actually visited", y = "draws") +
  theme_minimal(base_size = 11) + te_canvas + theme(panel.grid.minor = element_blank())

## ---- equal-effort ----
ne   <- round(mean(A$nf))
srsE <- srs_mean(pop, ne, 20000L, 404L)        # same TOTAL effort
c(n = ne, sd_srs = round(sd(srsE), 4), sd_adaptive = round(sd(A$ht), 4),
  efficiency = round(var(srsE) / var(A$ht), 2))

## ---- eff-nums ----
eff_init <- var(srs1) / var(A$ht); eff_tot <- var(srsE) / var(A$ht)

## ---- sweep ----
sweep_agg <- function(spreads, B = 8000L, seed = 11L) {
  do.call(rbind, lapply(spreads, function(s) {
    p <- make_population(spread = s, seed = 55L); nn <- build_networks(p, 1L)
    r <- acs_mc(p, nn, n1, B, seed)
    ne <- round(mean(r$nf)); sr <- srs_mean(p, ne, B, seed + 1L)
    data.frame(spread = s, total = sum(p$y), vmr = vmr(p),
               occupancy = mean(p$y >= 1), mean_final_n = mean(r$nf),
               efficiency = var(sr) / var(r$ht))
  }))
}
sw <- sweep_agg(c(0.5, 0.9, 1.5, 2.5))
round(sw, 3)

## ---- sweep-nums ----
best <- sw[which.max(sw$vmr), ]
worst <- sw[which.min(sw$vmr), ]

## ---- fig-efficiency ----
set.seed(88); popC <- list(side = pop$side, N = N, y = rpois(N, mu))
netsC <- build_networks(popC, 1L)
rC <- acs_mc(popC, netsC, n1, 8000L, 99L)
neC <- round(mean(rC$nf)); srC <- srs_mean(popC, neC, 8000L, 111L)
csr <- data.frame(vmr = vmr(popC), efficiency = var(srC) / var(rC$ht),
                  mean_final_n = mean(rC$nf), occupancy = mean(popC$y >= 1))
pd <- rbind(data.frame(vmr = sw$vmr, efficiency = sw$efficiency,
                       kind = "clustered populations"),
            data.frame(vmr = csr$vmr, efficiency = csr$efficiency,
                       kind = "random field (control)"))
ggplot(pd, aes(vmr, efficiency, colour = kind)) +
  geom_hline(yintercept = 1, linetype = 2, colour = "#16241d") +
  geom_point(size = 3) +
  scale_colour_manual(values = c("clustered populations" = "#275139",
                                 "random field (control)" = "#b5534e"), name = NULL) +
  annotate("text", x = max(pd$vmr) * 0.62, y = 1.04,
           label = "break-even", size = 3.2, colour = "#16241d") +
  labs(x = "variance-to-mean ratio (clumping)",
       y = "efficiency vs simple random sampling") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())
