# Two-phase sampling when strata are unknown
# https://tidyecology.com/posts/two-phase-sampling-for-stratification/
#
# 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)
stratum <- rep(names(Nh), Nh)
y       <- round(pmax(0, rnorm(N, rep(mu_h, Nh), rep(sd_h, Nh))), 2)

W   <- Nh / N
mu  <- mean(y)
S2  <- var(y)
S2h <- tapply(y, stratum, var)[names(Nh)]

within  <- sum(W * S2h)          # what stays inside the strata
between <- S2 - within           # what the strata remove
c(total = S2, between = between, within = within)

## ---- scalars-0 ----
share_between <- between / S2

## ---- variance-fn ----
V_2ph <- function(n1, n2) (1 - n1 / N) * S2 / n1 + within * (1 / n2 - 1 / n1)
c(`n1=400, n2=100` = V_2ph(400, 100), `n1=300, n2=60` = V_2ph(300, 60))

## ---- monte-carlo ----
one_survey <- function(n1, n2) {
  s1 <- sample.int(N, n1)
  st <- stratum[s1]
  w  <- table(factor(st, levels = names(Nh))) / n1
  nu <- n2 / n1
  est <- 0
  for (h in names(Nh)) {
    ix <- s1[st == h]
    est <- est + w[[h]] * mean(y[sample(ix, max(1, round(nu * length(ix))))])
  }
  est
}

B <- 3000
res <- t(sapply(list(c(400, 100), c(300, 60)), function(p) {
  set.seed(3731)
  mc <- replicate(B, one_survey(p[1], p[2]))
  c(n1 = p[1], n2 = p[2], mc_mean = mean(mc), truth = mu,
    mc_variance = var(mc), formula = V_2ph(p[1], p[2]))
}))
round(res, 4)

## ---- scalars-1 ----
mc_v1 <- res[1, "mc_variance"]; fo_v1 <- res[1, "formula"]
mc_b1 <- res[1, "mc_mean"] - mu
rel1  <- 100 * (fo_v1 / mc_v1 - 1)

## ---- budget-split ----
c1 <- 1; c2 <- 10; budget <- 1000

ratio <- sqrt(between * c2 / (within * c1))
n2_opt <- budget / (ratio * c1 + c2)
n1_opt <- ratio * n2_opt
c(n1 = n1_opt, n2 = n2_opt, V = V_2ph(n1_opt, n2_opt), SE = sqrt(V_2ph(n1_opt, n2_opt)))

## ---- fig-split ----
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)
    )
}

sh <- seq(0.1, 0.85, by = 0.01)
cv <- data.frame(share = sh,
                 V = vapply(sh, function(s) V_2ph(budget * s / c1, budget * (1 - s) / c2), 0))

ggplot(cv, aes(share, V)) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  annotate("point", x = n1_opt * c1 / budget, y = V_2ph(n1_opt, n2_opt),
           colour = "#b5534e", size = 3) +
  annotate("text", x = n1_opt * c1 / budget, y = V_2ph(n1_opt, n2_opt),
           label = " optimum", hjust = 0, vjust = -1, colour = "#b5534e", size = 3.2) +
  labs(title = "The budget split has an interior optimum",
       subtitle = "Phase one costs a tenth of phase two; total spend held fixed",
       x = "share of the budget spent on phase one",
       y = "design variance of the mean") +
  theme_te()

## ---- three-way ----
n_srs <- budget / c2
V_srs <- (1 - n_srs / N) * S2 / n_srs
V_map <- (1 - n_srs / N) / n_srs * within        # stratified, weights known in advance

comparison <- rbind(
  `simple random`  = c(expensive_units = n_srs, V = V_srs,                SE = sqrt(V_srs)),
  `two-phase`      = c(expensive_units = n2_opt, V = V_2ph(n1_opt, n2_opt),
                       SE = sqrt(V_2ph(n1_opt, n2_opt))),
  `map already in hand` = c(expensive_units = n_srs, V = V_map,           SE = sqrt(V_map)))
round(comparison, 4)

## ---- scalars-2 ----
gap_closed <- (V_srs - V_2ph(n1_opt, n2_opt)) / (V_srs - V_map)
se_srs <- sqrt(V_srs); se_2ph <- sqrt(V_2ph(n1_opt, n2_opt)); se_map <- sqrt(V_map)

## ---- fig-three ----
cd <- data.frame(design = factor(rownames(comparison), levels = rownames(comparison)),
                 SE = comparison[, "SE"])
ggplot(cd, aes(design, SE)) +
  geom_col(fill = c("#b5534e", "#93a87f", "#275139"), width = 0.55) +
  geom_text(aes(label = sprintf("%.3f", SE)), vjust = -0.6, colour = "#5d6b61", size = 3.2) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.14))) +
  labs(title = "What the cheap phase buys you",
       subtitle = "Same field budget in all three; only the right-hand bar needs a map in advance",
       x = NULL, y = "standard error of the mean") +
  theme_te()

## ---- cost-sweep ----
V_at <- function(cc) {
  r <- sqrt(between * c2 / (within * cc))
  n2 <- budget / (r * cc + c2)
  V_2ph(r * n2, n2)
}
break_even <- uniroot(function(cc) V_at(cc) - V_srs, c(0.2, 20))$root

sweep <- data.frame(c1 = c(0.2, 0.5, 1, 2, 4))
sweep$V     <- vapply(sweep$c1, V_at, 0)
sweep$ratio <- sweep$V / V_srs
round(sweep, 4)
c(break_even_c1 = break_even, as_fraction_of_c2 = break_even / c2)

## ---- scalars-3 ----
be_frac <- break_even / c2

## ---- fig-cost ----
cs <- seq(0.15, 6, by = 0.05)
cd2 <- data.frame(c1 = cs, ratio = vapply(cs, function(cc) V_at(cc) / V_srs, 0))
ggplot(cd2, aes(c1, ratio)) +
  geom_hline(yintercept = 1, colour = "#b5534e", linetype = "dashed", linewidth = 0.4) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  annotate("point", x = break_even, y = 1, colour = "#b5534e", size = 3) +
  labs(title = "There is a price above which the first phase is a waste",
       subtitle = "Phase-two unit costs 10; dashed line is parity with a simple random sample",
       x = "cost of one phase-one unit", y = "variance relative to simple random sampling") +
  theme_te()

## ---- optimal-nu ----
Sh <- sqrt(S2h)
V_2ph_opt <- function(n1, n2) (1 - n1 / N) * S2 / n1 + (sum(W * Sh))^2 / n2 - within / n1
r2  <- sqrt(between * c2 / ((sum(W * Sh))^2 * c1))
n2b <- budget / (r2 * c1 + c2); n1b <- r2 * n2b
c(n1 = n1b, n2 = n2b, V_uniform = V_2ph(n1_opt, n2_opt), V_optimal_nu = V_2ph_opt(n1b, n2b))

## ---- scalars-4 ----
nu_gain <- 1 - V_2ph_opt(n1b, n2b) / V_2ph(n1_opt, n2_opt)

## ---- proxy-error ----
set.seed(3733)
proxy <- do.call(rbind, lapply(c(0, 0.10, 0.20, 0.35), function(e) {
  cls <- stratum
  flip <- runif(N) < e
  cls[flip] <- sample(names(Nh), sum(flip), replace = TRUE)
  Wc  <- as.numeric(table(factor(cls, levels = names(Nh)))) / N
  wi  <- sum(Wc * tapply(y, cls, var)[names(Nh)])
  r   <- sqrt((S2 - wi) * c2 / (wi * c1)); n2e <- budget / (r * c1 + c2); n1e <- r * n2e
  Ve  <- (1 - n1e / N) * S2 / n1e + wi * (1 / n2e - 1 / n1e)
  data.frame(error = e, within_share = wi / S2, V = Ve, ratio_to_srs = Ve / V_srs)
}))
round(proxy, 3)

## ---- scalars-5 ----
r10 <- proxy$ratio_to_srs[proxy$error == 0.10]
r35 <- proxy$ratio_to_srs[proxy$error == 0.35]
