# Design-based variance and spatial balance
# https://tidyecology.com/posts/design-based-variance-and-spatial-balance/
#
# 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-14

## ---- setup ----
library(ggplot2); library(MASS)
theme_te <- function() {
  theme_minimal(base_size = 12) +
    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 = "#e7e6da", linewidth = 0.3),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 13),
          plot.subtitle = element_text(colour = "#5d6b61", size = 10),
          axis.title = element_text(colour = "#46604a"),
          axis.text = element_text(colour = "#5d6b61"),
          legend.title = element_text(colour = "#46604a"),
          legend.text = element_text(colour = "#5d6b61"))
}
pal_forest <- "#275139"; pal_gold <- "#cda23f"; pal_rust <- "#b5534e"

# GRTS engine (see the opener for the derivation); returns sites in spatial order
grts_address <- function(x, y, L = 8L) {
  n <- length(x); addr <- numeric(n)
  recurse <- function(idx, xlo, xhi, ylo, yhi, level, prefix) {
    if (level >= L || length(idx) <= 1L) { addr[idx] <<- prefix * 4^(L - level); return(invisible(NULL)) }
    xm <- (xlo + xhi) / 2; ym <- (ylo + yhi) / 2
    q <- (x[idx] >= xm) + 2L * (y[idx] >= ym); perm <- sample(0:3)
    for (qq in 0:3) {
      sub <- idx[q == qq]; if (length(sub) == 0L) next
      cxlo <- if (qq %% 2L == 1L) xm else xlo; cxhi <- if (qq %% 2L == 1L) xhi else xm
      cylo <- if (qq >= 2L) ym else ylo;       cyhi <- if (qq >= 2L) yhi else ym
      recurse(sub, cxlo, cxhi, cylo, cyhi, level + 1L, prefix * 4 + perm[qq + 1L])
    }
  }
  recurse(seq_len(n), 0, 1, 0, 1, 0L, 0); addr
}
grts_draw <- function(x, y, m, L = 8L) {          # returns sites in ascending address order
  n <- length(x); pip <- rep(m / n, n)
  a <- grts_address(x, y, L); ord <- order(a, runif(n))
  cs <- cumsum(pip[ord]); picks <- runif(1) + 0:(m - 1)
  sort_sel <- ord[findInterval(picks, c(0, cs), rightmost.closed = TRUE)]
  sort_sel[order(a[sort_sel])]
}

set.seed(101)
side <- 22
frame <- expand.grid(x = seq(0.02, 0.98, length.out = side),
                     y = seq(0.02, 0.98, length.out = side))
N <- nrow(frame)
Dm <- as.matrix(dist(frame)); rho <- 0.18
z <- as.numeric(mvrnorm(1, rep(10, N), 4 * exp(-Dm / rho)))
mu_true <- mean(z)
m <- 40
f <- m / N

## ---- truevar ----
set.seed(202)
R <- 3000
est_srs  <- numeric(R); est_grts <- numeric(R)
for (r in seq_len(R)) {
  est_srs[r]  <- mean(z[sample(N, m)])
  est_grts[r] <- mean(z[grts_draw(frame$x, frame$y, m)])
}
var_srs  <- var(est_srs); var_grts <- var(est_grts)
gain <- var_srs / var_grts
bias_srs  <- mean(est_srs)  - mu_true
bias_grts <- mean(est_grts) - mu_true

## ---- fig-dist ----
dd <- rbind(data.frame(est = est_srs, design = "Simple random"),
            data.frame(est = est_grts, design = "GRTS"))
ggplot(dd, aes(est, fill = design, colour = design)) +
  geom_density(alpha = 0.35, linewidth = 0.7) +
  geom_vline(xintercept = mu_true, linetype = "dashed", colour = "#5d6b61") +
  scale_fill_manual(values = c("GRTS" = pal_forest, "Simple random" = pal_gold)) +
  scale_colour_manual(values = c("GRTS" = pal_forest, "Simple random" = pal_gold)) +
  labs(title = "GRTS estimates cluster tighter around the truth",
       subtitle = "Dashed line: the true frame mean.",
       x = "Estimated mean", y = "Density", fill = NULL, colour = NULL) +
  theme_te()

## ---- srsvar ----
srs_var_mean <- function(zs) (1 - f) * var(zs) / m
set.seed(303)
v_srs_on_grts <- numeric(2000)
for (r in seq_len(2000)) v_srs_on_grts[r] <- srs_var_mean(z[grts_draw(frame$x, frame$y, m)])
srs_est <- mean(v_srs_on_grts)
srs_ratio <- srs_est / var_grts

## ---- sdvar ----
sd_var_mean <- function(zo) (1 - f) / m * sum(diff(zo)^2) / (2 * (m - 1))
set.seed(404)
v_sd <- numeric(2000)
for (r in seq_len(2000)) v_sd[r] <- sd_var_mean(z[grts_draw(frame$x, frame$y, m)])
sd_est <- mean(v_sd)
sd_ratio <- sd_est / var_grts

## ---- fig-estimators ----
db <- data.frame(
  what = factor(c("True variance", "Successive difference", "Simple-random formula"),
                levels = c("True variance", "Successive difference", "Simple-random formula")),
  value = c(var_grts, sd_est, srs_est))
ggplot(db, aes(what, value, fill = what)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = var_grts, linetype = "dashed", colour = "#5d6b61") +
  scale_fill_manual(values = c("True variance" = pal_forest,
                               "Successive difference" = pal_gold,
                               "Simple-random formula" = pal_rust), guide = "none") +
  labs(title = "Both estimators are conservative, the spatial one less so",
       subtitle = "Dashed line: the true variance of the GRTS mean.",
       x = NULL, y = "Estimated variance of the mean") +
  theme_te() + theme(axis.text.x = element_text(size = 9))
