# Random effects with too few levels
# https://tidyecology.com/posts/random-effects-with-too-few-levels/
#
# 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-04

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- design ----
n_strm  <- 5                        # streams
n_per   <- 4                        # riffle samples per stream
icc_set <- 0.10                     # intraclass correlation of the truth
v_a     <- icc_set                  # among stream variance, total variance one
v_e     <- 1 - v_a                  # within stream variance
mu0     <- 1.2                      # mean log biomass
slope_set <- -0.12                  # per ten percentage points logged
alpha_lev <- 0.05; ci_pct <- 100 * (1 - alpha_lev)

# catchment logged, five to eighty five per cent, in tens of points, centred
gradient_c <- function(J) {
  pct <- seq(5, 85, length.out = J) / 10
  pct - mean(pct)
}

make_streams <- function(J, n_per, slope, va, ve) {
  xg <- gradient_c(J)
  dat <- data.frame(stream = factor(rep(seq_len(J), each = n_per)),
                    logged = rep(xg, each = n_per))
  dat$y <- mu0 + slope * dat$logged +
           rep(rnorm(J, 0, sqrt(va)), each = n_per) + rnorm(J * n_per, 0, sqrt(ve))
  dat
}

## ---- moment ----
vc_moment <- function(dat, n_per) {
  m_within <- lm(y ~ stream, data = dat)
  ms_e <- deviance(m_within) / df.residual(m_within)
  agg  <- aggregate(y ~ stream + logged, data = dat, FUN = mean)
  m_means <- lm(y ~ logged, data = agg)
  ms_m <- deviance(m_means) / df.residual(m_means)
  list(ms_e = ms_e, ms_m = ms_m,
       raw    = ms_m - ms_e / n_per,          # unbiased, can be negative
       sig_a2 = max(0, ms_m - ms_e / n_per),  # what software reports
       m_means = m_means, m_pool = lm(y ~ logged, data = dat))
}
set.seed(3116)
draws <- lapply(seq_len(6), function(i) make_streams(n_strm, n_per, slope_set, v_a, v_e))
vc_draws <- vapply(draws, function(d) vc_moment(d, n_per)$sig_a2, 0)
n_zero_draws <- sum(vc_draws == 0)
round(vc_draws, 3)

## ---- worked ----
i_zero <- which(vc_draws == 0)[1]
ex <- vc_moment(draws[[i_zero]], n_per)
keep_row <- summary(ex$m_means)$coefficients["logged", ]
pool_row <- summary(ex$m_pool)$coefficients["logged", ]
ex_slope <- unname(keep_row[1]); ex_se_keep <- unname(keep_row[2])
ex_se_pool <- unname(pool_row[2]); df_pool <- df.residual(ex$m_pool)
ex_p_keep <- unname(keep_row[4]); ex_p_pool <- unname(pool_row[4])
df_keep <- df.residual(ex$m_means)

## ---- suff ----
analyse_suff <- function(ybar, ss_e, J, n_per, alpha = alpha_lev) {
  xg  <- gradient_c(J); sxx <- sum(xg^2)
  ctr <- ybar - rep(colMeans(ybar), each = J)
  slope_hat <- as.vector(crossprod(xg, ctr)) / sxx
  rss_m <- colSums((ctr - outer(xg, slope_hat))^2)
  dfp   <- J * n_per - 2
  ms_m  <- rss_m / (J - 2)
  ms_e  <- ss_e / (J * (n_per - 1))
  list(slope_hat = slope_hat, ms_m = ms_m, ms_e = ms_e,
       raw = ms_m - ms_e / n_per,
       se_keep = sqrt(ms_m / sxx),
       se_pool = sqrt((ss_e + n_per * rss_m) / dfp / (n_per * sxx)),
       crit_keep = qt(1 - alpha / 2, J - 2), crit_pool = qt(1 - alpha / 2, dfp))
}
i_pos <- which(vc_draws > 0)[1]
ybar_obs <- as.vector(tapply(draws[[i_pos]]$y, draws[[i_pos]]$stream, mean))
ss_e_obs <- sum((draws[[i_pos]]$y - ybar_obs[as.integer(draws[[i_pos]]$stream)])^2)
chk <- analyse_suff(matrix(ybar_obs, nrow = n_strm), ss_e_obs, n_strm, n_per)
ref <- vc_moment(draws[[i_pos]], n_per)
id_gap <- max(abs(c(chk$slope_hat - unname(coef(ref$m_means)["logged"]),
                    chk$se_keep - summary(ref$m_means)$coefficients["logged", 2],
                    chk$se_pool - summary(ref$m_pool)$coefficients["logged", 2],
                    chk$raw - ref$raw)))

## ---- fp-guard-1 ----
stopifnot(id_gap < 1e-10)

## ---- fastsim ----
sim_fast <- function(n_rep, J, n_per, slope, va, ve) {
  xg <- gradient_c(J)
  ybar <- matrix(rnorm(n_rep * J, 0, sqrt(va + ve / n_per)), nrow = J) + slope * xg
  analyse_suff(ybar, ve * rchisq(n_rep, J * (n_per - 1)), J, n_per)
}
p_zero_exact <- function(J, n_per, va, ve) pf((ve / n_per) / (va + ve / n_per), J - 2, J * (n_per - 1))
n_rep <- 20000    # fixed before any rate was inspected
n_chk <- 4000     # cross-check, full least squares on every dataset
set.seed(8140)
full_raw <- vapply(seq_len(n_chk), function(i)
  vc_moment(make_streams(n_strm, n_per, 0, v_a, v_e), n_per)$raw, 0)
set.seed(8141)
rate_chk   <- mean(sim_fast(n_chk, n_strm, n_per, 0, v_a, v_e)$raw <= 0)
rate_full <- mean(full_raw <= 0)
rate_exact <- p_zero_exact(n_strm, n_per, v_a, v_e)
chk_gap <- max(abs(c(rate_full, rate_chk) - rate_exact))
mcse_chk <- sqrt(0.25 / n_chk); mcse_rep <- sqrt(0.25 / n_rep)

## ---- mainsim ----
procs <- function(a, slope_true = 0) {
  zero <- a$raw <= 0
  rej_keep <- abs(a$slope_hat / a$se_keep) > a$crit_keep
  rej_pool <- abs(a$slope_hat / a$se_pool) > a$crit_pool
  cov_k <- abs(a$slope_hat - slope_true) <= a$crit_keep * a$se_keep
  cov_p <- abs(a$slope_hat - slope_true) <= a$crit_pool * a$se_pool
  list(zero = zero, keep = rej_keep, pool = rej_pool, cov_keep = cov_k,
       adapt = ifelse(zero, rej_pool, rej_keep), cov_pool = cov_p,
       cov_adapt = ifelse(zero, cov_p, cov_k),
       w_keep = 2 * a$crit_keep * a$se_keep, w_pool = 2 * a$crit_pool * a$se_pool,
       w_adapt = ifelse(zero, 2 * a$crit_pool * a$se_pool, 2 * a$crit_keep * a$se_keep))
}
set.seed(2731)
main <- sim_fast(n_rep, n_strm, n_per, 0, v_a, v_e)
pm <- procs(main)
rate_main <- mean(pm$zero); mean_raw <- mean(main$raw)
mean_trunc <- mean(pmax(0, main$raw)); bias_trunc <- mean_trunc - v_a

## ---- fig-boundary ----
bd <- data.frame(raw = main$raw)
bd$side <- ifelse(bd$raw <= 0, "truncated to zero", "reported as positive")
ggplot(bd, aes(raw, fill = side)) +
  geom_histogram(bins = 70, colour = te_paper, linewidth = 0.15) +
  geom_vline(xintercept = v_a, colour = te_ink, linetype = "dashed", linewidth = 0.8) +
  scale_fill_manual(values = c(te_forest, te_rust), name = NULL) +
  labs(x = "estimated among stream variance, before truncation", y = "datasets",
       title = "Where the moment estimate lands with five streams",
       subtitle = "dashed line: the true among stream variance") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- ratecurve ----
j_seq <- c(4, 5, 6, 8, 10, 14, 20, 30)
n_lab <- c(4, 16)
rate_lev <- sprintf("%d per stream", n_lab)
rate_tab <- do.call(rbind, lapply(n_lab, function(nn)
  data.frame(J = j_seq, n_per = nn,
             rate = vapply(j_seq, function(J) p_zero_exact(J, nn, v_a, v_e), 0),
             label = factor(sprintf("%d per stream", nn), levels = rate_lev))))
set.seed(5504)
rate_sim <- vapply(j_seq, function(J) mean(sim_fast(n_rep, J, n_per, 0, v_a, v_e)$raw <= 0), 0)
sim_tab <- data.frame(J = j_seq, rate = rate_sim,
                      label = factor(rate_lev[1], levels = rate_lev))
sim_exact_gap <- max(abs(rate_sim - rate_tab$rate[rate_tab$n_per == n_per]))
r_at <- function(J) p_zero_exact(J, n_per, v_a, v_e)
se_slope <- function(J, nn) sqrt((v_a + v_e / nn) / sum(gradient_c(J)^2))
n_seq <- 2:40
j_lab <- c(5, 25); se_lev <- sprintf("%d streams", j_lab)
se_tab <- do.call(rbind, lapply(j_lab, function(J)
  data.frame(n_per = n_seq, J = J, se = vapply(n_seq, function(nn) se_slope(J, nn), 0),
             label = factor(sprintf("%d streams", J), levels = se_lev))))
floor_tab <- data.frame(J = j_lab, label = factor(se_lev, levels = se_lev),
      floor_se = vapply(j_lab, function(J) sqrt(v_a / sum(gradient_c(J)^2)), 0))
se_now <- se_slope(5, n_per); se_j25 <- se_slope(25, n_per)
se_gain5 <- se_now / floor_tab$floor_se[1]

## ---- fig-design ----
p_rate <- ggplot(rate_tab, aes(J, rate, colour = label)) +
  geom_line(linewidth = 0.9) +
  geom_point(data = sim_tab, shape = 21, size = 2.2, fill = te_paper,
             stroke = 0.8, show.legend = FALSE) +
  scale_colour_manual(values = c(te_forest, te_gold), name = NULL) +
  scale_y_continuous(limits = c(0, 0.5)) +
  labs(x = "streams", y = "probability of a zero estimate", title = "Boundary rate",
       subtitle = "lines: closed form, circles: simulation") +
  theme_datasheet() + theme(legend.position = "bottom")

p_se <- ggplot(se_tab, aes(n_per, se, colour = label)) +
  geom_line(linewidth = 0.9) +
  geom_hline(data = floor_tab, aes(yintercept = floor_se, colour = label),
             linetype = "dashed", linewidth = 0.6) +
  scale_colour_manual(values = c(te_forest, te_gold), name = NULL) +
  scale_y_continuous(limits = c(0, NA)) +
  labs(x = "riffle samples per stream", y = "standard error of the slope",
       title = "Precision of the slope",
       subtitle = "dashed lines: the variance floor") +
  theme_datasheet() + theme(legend.position = "bottom")

p_rate + p_se + plot_annotation(theme = theme_datasheet())

## ---- typei ----
proc_lev <- c("keep the term", "drop if singular", "always pool")
set.seed(6613)
ti <- do.call(rbind, lapply(j_seq, function(J) {
  pp <- procs(sim_fast(n_rep, J, n_per, 0, v_a, v_e))
  data.frame(J = J, procedure = proc_lev,
             rate = c(mean(pp$keep), mean(pp$adapt), mean(pp$pool)))
}))
ti$procedure <- factor(ti$procedure, levels = proc_lev)
ti$mcse <- sqrt(ti$rate * (1 - ti$rate) / n_rep)
at_j <- function(J, k) ti$rate[ti$J == J & ti$procedure == proc_lev[k]]
mcse_main <- sqrt(alpha_lev * (1 - alpha_lev) / n_rep)
rate_max <- function(k) max(ti$rate[ti$procedure == proc_lev[k]])
pool_max <- rate_max(3); adapt_max <- rate_max(2)
sing <- pm$zero; crit_ratio <- main$crit_keep / main$crit_pool
se_ratio_med <- median(main$se_pool[sing] / main$se_keep[sing])
thr_sing <- (main$crit_pool * main$se_pool[sing]) / (main$crit_keep * main$se_keep[sing])
thr_ratio_med <- median(thr_sing); thr_up <- mean(thr_sing[pm$keep[sing]] > 1)

## ---- fig-typei ----
ggplot(ti, aes(J, rate, colour = procedure)) +
  geom_hline(yintercept = alpha_lev, colour = te_body, linetype = "dashed",
             linewidth = 0.5) +
  geom_errorbar(aes(ymin = rate - 2 * mcse, ymax = rate + 2 * mcse),
                width = 0.6, linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust), name = NULL) +
  scale_y_continuous(limits = c(0, NA)) +
  labs(x = "streams", y = "rejection rate under the null",
       title = "Deleting the term barely moves the test",
       subtitle = "dashed line: the nominal five per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- conditional ----
n_sing <- sum(pm$zero); n_ok <- sum(!pm$zero)
keep_sing <- mean(pm$keep[pm$zero]);  keep_ok <- mean(pm$keep[!pm$zero])
pool_sing <- mean(pm$pool[pm$zero]);  pool_ok <- mean(pm$pool[!pm$zero])
n_rej_ok <- sum(pm$keep[!pm$zero]); share_sing <- sum(pm$keep[pm$zero]) / sum(pm$keep)

n_grid <- c(2, 4, 8, 16, 32, 64)
set.seed(9127)
nsweep <- do.call(rbind, lapply(n_grid, function(nn) {
  pp <- procs(sim_fast(n_rep, n_strm, nn, 0, v_a, v_e))
  data.frame(n_per = nn, procedure = proc_lev, zero = mean(pp$zero),
             rate = c(mean(pp$keep), mean(pp$adapt), mean(pp$pool)))
}))
nsweep$procedure <- factor(nsweep$procedure, levels = proc_lev)
sw <- function(nn, k) nsweep$rate[nsweep$n_per == nn & nsweep$procedure == proc_lev[k]]
a_sub <- nsweep[nsweep$procedure == proc_lev[2], ]
a_max <- max(a_sub$rate); a_max_n <- a_sub$n_per[which.max(a_sub$rate)]
z_n64 <- nsweep$zero[nsweep$n_per == 64][1]; alt_b <- c(slope_set, -0.3, -0.5)
a_cross <- min(a_sub$n_per[a_sub$rate > alpha_lev])
a_dev <- max(abs(a_sub$rate[a_sub$n_per >= a_cross] - alpha_lev))
set.seed(7742)
share_alt <- vapply(alt_b, function(b) {
  pa <- procs(sim_fast(n_rep, n_strm, n_per, b, v_a, v_e), slope_true = b)
  c(sum(pa$keep[pa$zero]) / sum(pa$keep), mean(pa$keep))
}, numeric(2))

## ---- fig-conditional ----
cond <- data.frame(
  state = factor(rep(c("singular fit", "positive estimate"), each = 2),
                 levels = c("singular fit", "positive estimate")),
  procedure = factor(rep(proc_lev[c(1, 3)], 2), levels = proc_lev[c(1, 3)]),
  rate = c(keep_sing, pool_sing, keep_ok, pool_ok))

p_cond <- ggplot(cond, aes(state, rate, fill = procedure)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6,
           colour = te_paper, linewidth = 0.3) +
  geom_hline(yintercept = alpha_lev, colour = te_body, linetype = "dashed",
             linewidth = 0.5) +
  scale_fill_manual(values = c(te_forest, te_rust), name = NULL) +
  labs(x = NULL, y = "rejection rate under the null",
       title = "Five streams, split by state",
       subtitle = "green: keep the term, rust: pooling") +
  theme_datasheet() + theme(legend.position = "none")

p_sweep <- ggplot(nsweep, aes(n_per, rate, colour = procedure)) +
  geom_hline(yintercept = alpha_lev, colour = te_body, linetype = "dashed",
             linewidth = 0.5) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_x_log10(breaks = n_grid) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust), name = NULL) +
  scale_y_continuous(limits = c(0, NA)) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "riffle samples per stream", y = "rejection rate under the null",
       title = "Five streams, more riffles",
       subtitle = "pooling explodes, the reflex does not") +
  theme_datasheet() + theme(legend.position = "bottom")

p_cond + p_sweep + plot_annotation(theme = theme_datasheet())

## ---- intervals ----
set.seed(4459)
pc <- procs(sim_fast(n_rep, n_strm, n_per, slope_set, v_a, v_e), slope_true = slope_set)
cov_keep <- mean(pc$cov_keep); cov_adapt <- mean(pc$cov_adapt); cov_pool <- mean(pc$cov_pool)
w_keep <- mean(pc$w_keep); w_adapt <- mean(pc$w_adapt); w_pool <- mean(pc$w_pool)
w_ratio_pool <- w_pool / w_keep; w_ratio_adapt <- w_adapt / w_keep; w_over_slope <- w_keep / abs(slope_set)
