# Checking a stratified design
# https://tidyecology.com/posts/checking-a-stratified-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-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
mu    <- mean(y)
S2    <- var(y)
S2h   <- tapply(y, stratum, var)[names(Nh)]
muh   <- tapply(y, stratum, mean)[names(Nh)]
idx_h <- split(seq_len(N), stratum)[names(Nh)]

n  <- 120
nh <- round(n * W)
f  <- n / N
V_str <- sum(W^2 * (1 - nh / Nh) * S2h / nh)
V_srs <- (1 - f) * S2 / n
c(V_stratified = V_str, V_srs = V_srs)

## ---- post-strat ----
post_strat <- function(nn) {
  s  <- sample.int(N, nn)
  st <- stratum[s]
  ys <- y[s]
  k  <- table(factor(st, levels = names(Nh)))
  if (any(k < 2)) return(c(NA, NA))               # a stratum with under two plots is unusable
  m <- tapply(ys, st, mean)[names(Nh)]
  v <- tapply(ys, st, var)[names(Nh)]
  c(sum(W * m), sum(W^2 * (1 - k[names(Nh)] / Nh) * v / k[names(Nh)]))
}

B <- 6000
set.seed(3741)
ps120 <- t(replicate(B, post_strat(120)))
extra <- (1 - f) / n^2 * sum((1 - W) * S2h)         # the leading penalty term

c(mc_variance = var(ps120[, 1], na.rm = TRUE),
  design_stratified = V_str,
  predicted = V_str + extra,
  mean_v_hat = mean(ps120[, 2], na.rm = TRUE),
  coverage = mean(abs(ps120[, 1] - mu) <= 1.96 * sqrt(ps120[, 2]), na.rm = TRUE))

## ---- scalars-1 ----
ps_v   <- var(ps120[, 1], na.rm = TRUE)
ps_pen <- 100 * (ps_v / V_str - 1)
cov120 <- mean(abs(ps120[, 1] - mu) <= 1.96 * sqrt(ps120[, 2]), na.rm = TRUE)

## ---- post-strat-small ----
set.seed(3742)
ps24 <- t(replicate(B, post_strat(24)))
nh24 <- round(24 * W)
c(mc_variance = var(ps24[, 1], na.rm = TRUE),
  design_stratified = sum(W^2 * (1 - nh24 / Nh) * S2h / nh24),
  coverage = mean(abs(ps24[, 1] - mu) <= 1.96 * sqrt(ps24[, 2]), na.rm = TRUE),
  fraction_unusable = mean(is.na(ps24[, 1])))

## ---- scalars-2 ----
cov24  <- mean(abs(ps24[, 1] - mu) <= 1.96 * sqrt(ps24[, 2]), na.rm = TRUE)
fail24 <- mean(is.na(ps24[, 1]))
pen24  <- 100 * (var(ps24[, 1], na.rm = TRUE) / sum(W^2 * (1 - nh24 / Nh) * S2h / nh24) - 1)

## ---- weight-error ----
bias_of <- function(d)                              # published weights overstate wetland by d
  sum(c(-d, d, 0) * muh)                            # taken from meadow, given to wetland

d_grid <- c(0.01, 0.02, 0.05, 0.10)
data.frame(weight_error = d_grid,
           bias = vapply(d_grid, bias_of, 0),
           bias_over_SE = abs(vapply(d_grid, bias_of, 0)) / sqrt(V_str))

## ---- scalars-3 ----
b05  <- bias_of(0.05)
r05  <- abs(b05) / sqrt(V_str)

## ---- weight-mse ----
mse_row <- function(nn) {
  nk <- round(nn * W)
  v  <- sum(W^2 * (1 - nk / Nh) * S2h / nk)
  b2 <- bias_of(0.05)^2
  c(n = nn, variance = v, bias_sq = b2, bias_share_of_MSE = b2 / (v + b2))
}
round(do.call(rbind, lapply(c(120, 480, 1200), mse_row)), 5)

## ---- scalars-4 ----
share120  <- { nk <- round(120 * W); b2 <- bias_of(0.05)^2; b2 / (sum(W^2 * (1 - nk / Nh) * S2h / nk) + b2) }
share480  <- { nk <- round(480 * W); b2 <- bias_of(0.05)^2; b2 / (sum(W^2 * (1 - nk / Nh) * S2h / nk) + b2) }

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

nn_grid <- round(exp(seq(log(40), log(1000), length.out = 40)))
b2 <- bias_of(0.05)^2
wd <- do.call(rbind, lapply(nn_grid, function(nn) {
  nk <- round(nn * W); v <- sum(W^2 * (1 - nk / Nh) * S2h / nk)
  data.frame(n = nn,
             component = c("variance", "squared bias", "mean squared error"),
             value = c(v, b2, v + b2))
}))
wd$component <- factor(wd$component, levels = c("variance", "squared bias", "mean squared error"))

ggplot(wd, aes(n, value, colour = component)) +
  geom_line(linewidth = 0.9) +
  scale_x_log10() + scale_y_log10() +
  scale_colour_manual(values = c("variance" = "#2f8f63", "squared bias" = "#b5534e",
                                 "mean squared error" = "#275139")) +
  labs(title = "A weight error is a floor that data cannot cross",
       subtitle = "Five-point error in the wetland weight; both axes logarithmic",
       x = "sample size", y = "error (variance scale)", colour = NULL) +
  theme_te()

## ---- how-many ----
set.seed(3743)
M  <- 1200
x  <- sort(runif(M))
yc <- round(4 + 12 * x^2 + rnorm(M, 0, 1.6), 2)
muC <- mean(yc)
nC  <- 60
B2  <- 4000

alloc_int <- function(Wk, n) {                      # integer allocation, at least two per stratum
  a <- pmax(2, floor(n * Wk))
  while (sum(a) < n) { r <- n * Wk - a; a[which.max(r)] <- a[which.max(r)] + 1 }
  while (sum(a) > n) { r <- a - n * Wk; k <- which(a > 2); a[k[which.max(r[k])]] <- a[k[which.max(r[k])]] - 1 }
  a
}

grid <- c(1, 2, 3, 4, 6, 8, 10, 15, 20, 30)
res <- do.call(rbind, lapply(grid, function(HH) {
  g   <- cut(x, quantile(x, seq(0, 1, length.out = HH + 1)), include.lowest = TRUE, labels = FALSE)
  Nk  <- as.numeric(table(g)); Wk <- Nk / M; S2k <- as.numeric(tapply(yc, g, var))
  nk  <- alloc_int(Wk, nC)
  Vt  <- sum(Wk^2 * (1 - nk / Nk) * S2k / nk)
  ix  <- split(seq_len(M), g)
  set.seed(3744 + HH)
  rr <- t(replicate(B2, {
    s <- lapply(seq_len(HH), function(k) yc[sample(ix[[k]], nk[k])])
    c(sum(Wk * vapply(s, mean, 0)),
      sum(Wk^2 * (1 - nk / Nk) * vapply(s, var, 0) / nk))
  }))
  data.frame(H = HH, min_nh = min(nk), V_true = Vt,
             cv_v_hat = sd(rr[, 2]) / mean(rr[, 2]),
             coverage = mean(abs(rr[, 1] - muC) <= qt(0.975, sum(nk) - HH) * sqrt(rr[, 2])))
}))
round(res, 4)

## ---- scalars-5 ----
gain4  <- (res$V_true[res$H == 1] - res$V_true[res$H == 4]) /
          (res$V_true[res$H == 1] - min(res$V_true))
cv4    <- res$cv_v_hat[res$H == 4]
cv30   <- res$cv_v_hat[res$H == 30]

## ---- fig-strata ----
library(grid)

p_left <- ggplot(res, aes(H, V_true)) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 1.8) +
  annotate("point", x = 4, y = res$V_true[res$H == 4], colour = "#b5534e", size = 3) +
  labs(title = "Precision saturates fast",
       x = "number of strata", y = "design variance of the mean") +
  theme_te()

p_right <- ggplot(res, aes(H, cv_v_hat)) +
  geom_line(colour = "#b5534e", linewidth = 0.9) +
  geom_point(colour = "#b5534e", size = 1.8) +
  labs(title = "The variance estimator does not",
       x = "number of strata", y = "CV of the variance estimator") +
  theme_te()

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(p_left,  vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_right, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- one-per-stratum ----
HH <- 60
g  <- cut(x, quantile(x, seq(0, 1, length.out = HH + 1)), include.lowest = TRUE, labels = FALSE)
Nk <- as.numeric(table(g)); Wk <- Nk / M
ix <- split(seq_len(M), g)
set.seed(3750)
s  <- lapply(seq_len(HH), function(k) yc[sample(ix[[k]], 1)])
v_hat <- sum(Wk^2 * (1 - 1 / Nk) * vapply(s, var, 0) / 1)
c(true_design_variance = sum(Wk^2 * (1 - 1 / Nk) * as.numeric(tapply(yc, g, var)) / 1),
  estimated_variance = v_hat)
