# Allocating survey effort across strata
# https://tidyecology.com/posts/allocating-effort-across-strata/
#
# 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-15

## ---- frame ----
set.seed(371)

Nh   <- c(meadow = 600, wetland = 300, woodland = 300)
mu_h <- c(meadow = 12,  wetland = 26,  woodland = 5)
sd_h <- c(meadow = 4,   wetland = 9,   woodland = 2)

N       <- sum(Nh)
H       <- length(Nh)
stratum <- rep(names(Nh), Nh)
y       <- round(pmax(0, rnorm(N, rep(mu_h, Nh), rep(sd_h, Nh))), 2)

W   <- Nh / N
S2h <- tapply(y, stratum, var)[names(Nh)]
Sh  <- sqrt(S2h)
round(rbind(weight = W, sd = Sh), 3)

## ---- vstr ----
V_str <- function(nh) sum(W^2 * (1 - nh / Nh) * S2h / nh)
n <- 120

## ---- allocations ----
cost <- c(meadow = 1, wetland = 4, woodland = 2)     # relative cost of one plot

alloc <- list(
  equal        = setNames(rep(n / H, H), names(Nh)),
  proportional = n * W,
  Neyman       = n * W * Sh / sum(W * Sh),
  `cost-aware` = n * (W * Sh / sqrt(cost)) / sum(W * Sh / sqrt(cost)))

tab <- t(sapply(alloc, function(a)
  c(round(a, 1), SE = sqrt(V_str(a)), field_cost = sum(a * cost))))
round(tab, 3)

## ---- scalars-1 ----
se_eq  <- sqrt(V_str(alloc$equal))
se_pr  <- sqrt(V_str(alloc$proportional))
se_ne  <- sqrt(V_str(alloc$Neyman))
n_ney  <- alloc$Neyman
cost_pr <- sum(alloc$proportional * cost)
cost_ne <- sum(alloc$Neyman * cost)

## ---- fig-alloc ----
library(ggplot2)

theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
      plot.title    = element_text(colour = "#16241d", face = "bold", size = 12),
      plot.subtitle = element_text(colour = "#5d6b61", size = 9.5),
      axis.title    = element_text(colour = "#46604a", size = 9.5),
      axis.text     = element_text(colour = "#2c3a31", size = 9),
      legend.title  = element_text(colour = "#46604a", size = 9.5),
      legend.text   = element_text(colour = "#2c3a31", size = 9),
      strip.text    = element_text(colour = "#16241d", face = "bold", size = 10)
    )
}
pal_h <- c(meadow = "#cda23f", wetland = "#2f8f63", woodland = "#b5534e")

ad <- do.call(rbind, lapply(names(alloc), function(a)
  data.frame(rule = a, stratum = names(Nh), plots = as.numeric(alloc[[a]]))))
ad$rule    <- factor(ad$rule, levels = names(alloc))
ad$stratum <- factor(ad$stratum, levels = names(Nh))

ggplot(ad, aes(rule, plots, fill = stratum)) +
  geom_col(position = position_dodge(width = 0.78), width = 0.7) +
  scale_fill_manual(values = pal_h) +
  labs(title = "Where the plots go under four rules",
       subtitle = "Total effort fixed at 120 plots",
       x = NULL, y = "plots allocated") +
  theme_te()

## ---- neyman-identity ----
V_prop_nofpc   <- sum(W * S2h) / n
V_neyman_nofpc <- (sum(W * Sh))^2 / n
var_W_Sh       <- (sum(W * S2h) - (sum(W * Sh))^2) / n

c(gap = V_prop_nofpc - V_neyman_nofpc, varW = var_W_Sh,
  difference = (V_prop_nofpc - V_neyman_nofpc) - var_W_Sh)

## ---- scalars-2 ----
id_gap <- abs((V_prop_nofpc - V_neyman_nofpc) - var_W_Sh)

## ---- equal-budget ----
budget <- 300
to_budget <- function(share) {                       # scale shares to exhaust the budget
  p <- share / sum(share)
  p * budget / sum(p * cost)
}

schemes <- list(proportional = W, Neyman = W * Sh, `cost-aware` = W * Sh / sqrt(cost))
bud <- t(sapply(schemes, function(s) {
  a <- to_budget(s)
  c(round(a, 1), n = sum(a), SE = sqrt(V_str(a)), spent = sum(a * cost))
}))
round(bud, 3)

## ---- scalars-3 ----
se_b_pr <- bud["proportional", "SE"]
se_b_ne <- bud["Neyman", "SE"]
se_b_co <- bud["cost-aware", "SE"]
n_b_pr  <- bud["proportional", "n"]
n_b_co  <- bud["cost-aware", "n"]

## ---- fig-budget ----
bd <- data.frame(rule = factor(rownames(bud), levels = rownames(bud)),
                 SE = bud[, "SE"], n = bud[, "n"])

ggplot(bd, aes(rule, SE)) +
  geom_col(fill = "#275139", width = 0.55) +
  geom_text(aes(label = sprintf("n = %.0f", n)), vjust = -0.6,
            colour = "#5d6b61", size = 3.2) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.14))) +
  labs(title = "Judge allocations on the budget, not on the plot count",
       subtitle = "Wetland plots cost four times a meadow plot; every bar spends the same total",
       x = NULL, y = "standard error of the mean") +
  theme_te()

## ---- pilot ----
idx_h <- split(seq_len(N), stratum)[names(Nh)]
m <- 10                                              # pilot plots per stratum
B <- 2000

set.seed(3721)
V_pilot <- replicate(B, {
  sh <- vapply(idx_h, function(ix) sd(y[sample(ix, m)]), 0)
  a  <- n * W * sh / sum(W * sh)
  a  <- pmax(a, 2); a <- a * n / sum(a)              # never fewer than two plots
  V_str(a)
})

V_oracle <- V_str(alloc$Neyman)
V_propn  <- V_str(alloc$proportional)
c(median_pilot = median(V_pilot), oracle = V_oracle, proportional = V_propn,
  worse_than_proportional = mean(V_pilot > V_propn),
  gain_kept = (V_propn - median(V_pilot)) / (V_propn - V_oracle))

## ---- scalars-4 ----
kept    <- (V_propn - median(V_pilot)) / (V_propn - V_oracle)
worse   <- mean(V_pilot > V_propn)
sd_rel  <- sd(V_pilot) / median(V_pilot)

## ---- fig-pilot ----
ggplot(data.frame(v = V_pilot), aes(v)) +
  geom_histogram(bins = 45, fill = "#93a87f", colour = "white", linewidth = 0.15) +
  geom_vline(xintercept = V_oracle, colour = "#275139", linewidth = 0.7) +
  geom_vline(xintercept = V_propn,  colour = "#b5534e", linewidth = 0.7) +
  annotate("text", x = V_oracle, y = Inf, label = " oracle Neyman", hjust = 0, vjust = 1.6,
           colour = "#275139", size = 3.2) +
  annotate("text", x = V_propn, y = Inf, label = "proportional ", hjust = 1, vjust = 1.6,
           colour = "#b5534e", size = 3.2) +
  labs(title = "Here a rough pilot captures most of the gain",
       subtitle = "2000 pilots of ten plots per stratum, each turned into an allocation",
       x = "design variance of the resulting survey", y = "pilots") +
  theme_te()

## ---- second-response ----
set.seed(3722)
z_mu <- c(meadow = 3,   wetland = 1.5, woodland = 6)
z_sd <- c(meadow = 1.2, wetland = 0.8, woodland = 4.5)
z    <- round(pmax(0, rnorm(N, rep(z_mu, Nh), rep(z_sd, Nh))), 2)

S2hz <- tapply(z, stratum, var)[names(Nh)]
Shz  <- sqrt(S2hz)
V_z  <- function(nh) sum(W^2 * (1 - nh / Nh) * S2hz / nh)
neyman_z <- n * W * Shz / sum(W * Shz)

rbind(sd_biomass = Sh, sd_beetles = Shz,
      `Neyman for biomass` = alloc$Neyman, `Neyman for beetles` = neyman_z)
c(beetle_V_under_biomass_plan = V_z(alloc$Neyman),
  beetle_V_under_own_plan     = V_z(neyman_z),
  beetle_V_under_proportional = V_z(alloc$proportional))

## ---- scalars-5 ----
z_pen_own  <- V_z(alloc$Neyman) / V_z(neyman_z)
z_pen_prop <- V_z(alloc$Neyman) / V_z(alloc$proportional)
