# Interference between experimental plots
# https://tidyecology.com/posts/interference-between-experimental-plots/
#
# 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)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text = element_text(colour = "#2c3a31"))
}

## ---- grid-setup ----
shift_torus <- function(M, dr, dc) {
  nr <- nrow(M); nc <- ncol(M)
  M[((seq_len(nr) - 1 - dr) %% nr) + 1, ((seq_len(nc) - 1 - dc) %% nc) + 1]
}

ring_offsets <- function(r) {
  g <- expand.grid(dr = -r:r, dc = -r:r)
  as.matrix(g[pmax(abs(g$dr), abs(g$dc)) == r, ])
}

ring_sum <- function(M, r) {
  off <- ring_offsets(r)
  out <- matrix(0, nrow(M), ncol(M))
  for (k in seq_len(nrow(off))) out <- out + shift_torus(M, off[k, 1], off[k, 2])
  out
}

off1 <- ring_offsets(1)
off2 <- ring_offsets(2)

side <- 12
n_plot <- side^2
mu_base <- 5
tau <- 1
sigma <- 0.6
leak <- 0.35

sim_grid <- function(seed, leak, phi1 = 1) {
  set.seed(seed)
  z <- rep(0L, n_plot)
  z[sample.int(n_plot, n_plot / 2)] <- 1L
  Z <- matrix(z, side, side)
  s1 <- as.vector(ring_sum(Z, 1))
  s2 <- as.vector(ring_sum(Z, 2))
  imported <- tau * leak * (phi1 * s1 / nrow(off1) +
                              (1 - phi1) * s2 / nrow(off2))
  exported <- tau * leak * z
  noise <- rnorm(n_plot, 0, sigma)
  data.frame(z = z, s1 = s1, s2 = s2,
             exported = exported, imported = imported,
             y_leak = mu_base + tau * z - exported + imported + noise,
             y_clean = mu_base + tau * z + noise)
}

print(c(plots = n_plot, treated = n_plot / 2,
        ring1_neighbours = nrow(off1), ring2_neighbours = nrow(off2),
        true_effect = tau, leak_fraction = leak, residual_sd = sigma))

## ---- one-realisation ----
d1 <- sim_grid(20260802, leak)
fit_leak <- lm(y_leak ~ z, data = d1)
fit_clean <- lm(y_clean ~ z, data = d1)

print(round(summary(fit_leak)$coefficients, 4))
print(round(summary(fit_clean)$coefficients, 4))

print(round(c(
  mean_treated = mean(d1$y_leak[d1$z == 1]),
  mean_control = mean(d1$y_leak[d1$z == 0]),
  contrast_leak = unname(coef(fit_leak)[2]),
  contrast_clean = unname(coef(fit_clean)[2]),
  resid_sd_leak = summary(fit_leak)$sigma,
  resid_sd_clean = summary(fit_clean)$sigma,
  shapiro_p = unname(shapiro.test(residuals(fit_leak))$p.value)), 4))

## ---- bias-sweep ----
n_rep <- 2000
est_leak <- se_leak <- est_clean <- se_clean <- numeric(n_rep)
imp_treated <- imp_control <- numeric(n_rep)

for (r in seq_len(n_rep)) {
  d <- sim_grid(20260802 + r, leak)
  m_l <- lm(y_leak ~ z, data = d)
  m_c <- lm(y_clean ~ z, data = d)
  est_leak[r] <- coef(m_l)[2]
  se_leak[r] <- summary(m_l)$coefficients[2, 2]
  est_clean[r] <- coef(m_c)[2]
  se_clean[r] <- summary(m_c)$coefficients[2, 2]
  imp_treated[r] <- mean(d$imported[d$z == 1])
  imp_control[r] <- mean(d$imported[d$z == 0])
}

tcrit <- qt(0.975, n_plot - 2)
bias_meas <- mean(est_leak) - tau
att_pct <- 100 * (1 - mean(est_leak) / tau)
se_ratio <- mean(se_leak) / mean(se_clean)
sd_ratio <- sd(est_leak) / sd(est_clean)
cov_true <- mean(abs(est_leak - tau) < tcrit * se_leak)
cov_att <- mean(abs(est_leak - tau * (1 - leak)) < tcrit * se_leak)
cov_clean <- mean(abs(est_clean - tau) < tcrit * se_clean)

print(round(c(mean_est_clean = mean(est_clean), mean_est_leak = mean(est_leak),
              bias = bias_meas, attenuation_pct = att_pct), 4))
print(round(c(mean_se_clean = mean(se_clean), mean_se_leak = mean(se_leak),
              se_ratio = se_ratio, sd_est_clean = sd(est_clean),
              sd_est_leak = sd(est_leak), sd_ratio = sd_ratio), 4))
print(round(c(coverage_clean = cov_clean, coverage_of_truth = cov_true,
              coverage_of_attenuated = cov_att,
              power_leak = mean(abs(est_leak / se_leak) > tcrit)), 4))

## ---- fig-sampling ----
dens_df <- rbind(
  data.frame(est = est_clean, kind = "No leakage"),
  data.frame(est = est_leak, kind = "35 per cent leaks out"))
bar_df <- data.frame(
  kind = c("No leakage", "35 per cent leaks out"),
  centre = c(mean(est_clean), mean(est_leak)),
  half = tcrit * c(mean(se_clean), mean(se_leak)),
  yy = c(1.05, 0.55))

ggplot(dens_df, aes(est, colour = kind, fill = kind)) +
  geom_density(alpha = 0.25, linewidth = 0.7, adjust = 1.1) +
  geom_vline(xintercept = tau, linetype = "dashed",
             colour = te_pal$ink, linewidth = 0.5) +
  geom_errorbar(data = bar_df, inherit.aes = FALSE,
                aes(y = yy, xmin = centre - half, xmax = centre + half,
                    colour = kind),
                orientation = "y", width = 0.25, linewidth = 0.7,
                show.legend = FALSE) +
  scale_colour_manual(values = c("No leakage" = te_pal$forest,
                                 "35 per cent leaks out" = te_pal$clay)) +
  scale_fill_manual(values = c("No leakage" = te_pal$green,
                               "35 per cent leaks out" = te_pal$clay)) +
  labs(x = "Estimated treatment contrast",
       y = "Density",
       colour = NULL, fill = NULL,
       title = "The estimate moves, the interval does not widen") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 8, 8))

## ---- decomposition ----
export_loss <- tau * leak
import_t <- mean(imp_treated)
import_c <- mean(imp_control)
import_gap <- import_c - import_t
import_gap_se <- sd(imp_control - imp_treated) / sqrt(n_rep)
gap_pred <- tau * leak / (n_plot - 1)
bias_pred <- -(export_loss + gap_pred)

print(round(c(mean_import_treated = import_t,
              mean_import_control = import_c,
              import_gap = import_gap,
              import_gap_mc_se = import_gap_se,
              import_gap_predicted = gap_pred), 6))
print(round(c(export_component = -export_loss,
              control_contamination_component = -import_gap,
              predicted_total_bias = bias_pred,
              measured_total_bias = bias_meas), 5))
print(round(c(export_share_pct = 100 * export_loss / abs(bias_pred),
              contamination_share_pct = 100 * gap_pred / abs(bias_pred)), 3))

## ---- buffer-setup ----
disc_offsets <- function(r) {
  g <- expand.grid(dr = -r:r, dc = -r:r)
  as.matrix(g[g$dr^2 + g$dc^2 <= r^2, ])
}

disc_mean <- function(M, off) {
  out <- matrix(0, nrow(M), ncol(M))
  for (k in seq_len(nrow(off))) out <- out + shift_torus(M, off[k, 1], off[k, 2])
  out / nrow(off)
}

p_side <- 8
k_sub <- 9
rho <- 2
np2 <- p_side^2
g_side <- p_side * k_sub
off_disc <- disc_offsets(rho)

sub_row <- rep(seq_len(g_side), times = g_side)
sub_col <- rep(seq_len(g_side), each = g_side)
plot_id <- ((sub_col - 1) %/% k_sub) * p_side + (sub_row - 1) %/% k_sub + 1
in_r <- (sub_row - 1) %% k_sub
in_c <- (sub_col - 1) %% k_sub
depth <- pmin(in_r, k_sub - 1 - in_r, in_c, k_sub - 1 - in_c)

sigma_u <- 0.15
buffers <- 0:3
keep_list <- lapply(buffers, function(b) depth >= b)
n_kept <- sapply(keep_list, function(k) sum(k) / np2)

print(c(plots = np2, quadrats_per_plot = k_sub^2, disc_cells = nrow(off_disc),
        interference_radius = rho, plot_sd = sigma_u))
print(rbind(buffer = buffers, quadrats_kept = n_kept))

## ---- buffer-sweep ----
sig_e_grid <- c(1.2, 2, 3, 4, 5)
n_rep_b <- 500
nb <- length(buffers)
ns <- length(sig_e_grid)
acc_e <- acc_e2 <- acc_se <- acc_cov <- matrix(0, nb, ns)

for (r in seq_len(n_rep_b)) {
  set.seed(31000 + r)
  zp <- rep(0L, np2)
  zp[sample.int(np2, np2 / 2)] <- 1L
  Zp <- matrix(zp, p_side, p_side)
  Zsub <- Zp[rep(seq_len(p_side), each = k_sub),
             rep(seq_len(p_side), each = k_sub)]
  expo <- as.vector(disc_mean(Zsub, off_disc))
  u_p <- rnorm(np2, 0, sigma_u)[plot_id]
  e_raw <- rnorm(g_side^2)
  base <- mu_base + tau * expo + u_p
  for (js in seq_len(ns)) {
    yv <- base + sig_e_grid[js] * e_raw
    for (jb in seq_len(nb)) {
      kk <- keep_list[[jb]]
      pm <- as.vector(tapply(yv[kk], plot_id[kk], mean))
      mf <- lm(pm ~ zp)
      dd <- unname(coef(mf)[2])
      ss <- summary(mf)$coefficients[2, 2]
      acc_e[jb, js] <- acc_e[jb, js] + dd
      acc_e2[jb, js] <- acc_e2[jb, js] + dd^2
      acc_se[jb, js] <- acc_se[jb, js] + ss
      acc_cov[jb, js] <- acc_cov[jb, js] + (abs(dd - tau) < qt(0.975, np2 - 2) * ss)
    }
  }
}

buf <- expand.grid(buffer = buffers, sigma_e = sig_e_grid)
buf$mean_est <- as.vector(acc_e) / n_rep_b
buf$variance <- as.vector(acc_e2) / n_rep_b - buf$mean_est^2
buf$mean_se <- as.vector(acc_se) / n_rep_b
buf$coverage <- as.vector(acc_cov) / n_rep_b
buf$bias <- buf$mean_est - tau
buf$bias2 <- buf$bias^2
buf$mse <- buf$bias2 + buf$variance
buf$kept <- n_kept[buf$buffer + 1]
qq <- function(b, s, col) buf[[col]][buf$buffer == b & buf$sigma_e == s]

print(round(buf[buf$sigma_e %in% c(1.2, 3, 5),
                c("buffer", "sigma_e", "kept", "mean_est", "bias",
                  "variance", "mse", "coverage")], 5))
best <- tapply(seq_len(nrow(buf)), buf$sigma_e,
               function(i) buf$buffer[i][which.min(buf$mse[i])])
print(rbind(sigma_e = sig_e_grid, best_buffer = as.vector(best)))

## ---- break-even ----
b1 <- buf[buf$buffer == 1, ]
b2 <- buf[buf$buffer == 2, ]
n_arm <- np2 / 2
kept1 <- n_kept[2]
kept2 <- n_kept[3]

q1 <- which(plot_id == 1)
own1 <- vapply(q1, function(q) sum(in_r[q] + off_disc[, 1] >= 0 &
                                    in_r[q] + off_disc[, 1] < k_sub &
                                    in_c[q] + off_disc[, 2] >= 0 &
                                    in_c[q] + off_disc[, 2] < k_sub), numeric(1))
exact_bias <- function(b) {
  share_own <- own1[depth[q1] >= b] / nrow(off_disc)
  tau * mean(share_own - (1 - share_own) / (np2 - 1)) - tau
}
bias2_gain <- exact_bias(1)^2 - exact_bias(2)^2
var_slope <- (2 / n_arm) * (1 / kept1 - 1 / kept2)
sigma_star <- sqrt(bias2_gain / (-var_slope))

fit_v1 <- lm(b1$variance ~ I(sig_e_grid^2))
fit_v2 <- lm(b2$variance ~ I(sig_e_grid^2))

print(round(c(mean_bias_buffer1 = mean(b1$bias),
              mean_bias_buffer2 = mean(b2$bias),
              exact_bias_buffer1 = exact_bias(1),
              exact_bias_buffer2 = exact_bias(2),
              squared_bias_gain = bias2_gain,
              variance_slope_per_sigma2 = var_slope,
              break_even_sigma_e = sigma_star), 5))
print(round(c(fitted_slope_buffer1 = unname(coef(fit_v1)[2]),
              predicted_slope_buffer1 = (2 / n_arm) / kept1,
              fitted_slope_buffer2 = unname(coef(fit_v2)[2]),
              predicted_slope_buffer2 = (2 / n_arm) / kept2), 5))
print(round(buf$mse[buf$buffer == 1] - buf$mse[buf$buffer == 2], 5))

## ---- fig-buffer ----
plot_lv <- c(1.2, 3, 5)
bf <- buf[buf$sigma_e %in% plot_lv, ]
bf$panel <- factor(paste("Quadrat noise", bf$sigma_e),
                   levels = paste("Quadrat noise", plot_lv))
parts <- c("Squared bias", "Variance", "Mean squared error")
long <- do.call(rbind, Map(function(v, p)
  data.frame(buffer = bf$buffer, panel = bf$panel, value = v, part = p),
  list(bf$bias2, bf$variance, bf$mse), parts))
long$part <- factor(long$part, levels = parts)
mins <- do.call(rbind, lapply(split(bf, bf$panel), function(s)
  s[which.min(s$mse), c("buffer", "mse", "panel")]))

ggplot(long, aes(buffer, value, colour = part)) +
  geom_line(linewidth = 0.75) +
  geom_point(size = 1.6) +
  geom_point(data = mins, inherit.aes = FALSE,
             aes(buffer, mse), shape = 21, size = 4.2, stroke = 1,
             colour = te_pal$ink, fill = NA) +
  facet_wrap(~panel, scales = "free_y") +
  scale_colour_manual(values = c("Squared bias" = te_pal$clay,
                                 "Variance" = te_pal$gold,
                                 "Mean squared error" = te_pal$forest)) +
  labs(x = "Buffer width (rings of quadrats discarded)",
       y = "Contribution to error",
       colour = NULL,
       title = "Where the buffer stops paying for itself") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 8, 8))

## ---- layout-sim ----
box_smooth <- function(M, r) {
  out <- matrix(0, nrow(M), ncol(M))
  for (dr in -r:r) for (dc in -r:r) out <- out + shift_torus(M, dr, dc)
  out / (2 * r + 1)^2
}

blk <- 3
n_blk <- (side / blk)^2
field_sd <- 0.5

run_layout <- function(mode, n_rep_l = 2000, seed0 = 47000) {
  est <- se <- imp_t <- imp_c <- fld <- numeric(n_rep_l)
  for (r in seq_len(n_rep_l)) {
    set.seed(seed0 + r)
    if (mode == "interspersed") {
      z <- rep(0L, n_plot)
      z[sample.int(n_plot, n_plot / 2)] <- 1L
      Z <- matrix(z, side, side)
    } else {
      bm <- matrix(0L, side / blk, side / blk)
      bm[sample.int(n_blk, n_blk / 2)] <- 1L
      Z <- bm[rep(seq_len(side / blk), each = blk),
              rep(seq_len(side / blk), each = blk)]
      z <- as.vector(Z)
    }
    imported <- tau * leak * as.vector(ring_sum(Z, 1)) / nrow(off1)
    fv <- as.vector(scale(as.vector(
      box_smooth(matrix(rnorm(n_plot), side, side), 2)))) * field_sd
    y <- mu_base + tau * z - tau * leak * z + imported + fv +
      rnorm(n_plot, 0, sigma)
    mf <- lm(y ~ z)
    est[r] <- coef(mf)[2]
    se[r] <- summary(mf)$coefficients[2, 2]
    imp_t[r] <- mean(imported[z == 1])
    imp_c[r] <- mean(imported[z == 0])
    fld[r] <- mean(fv[z == 1]) - mean(fv[z == 0])
  }
  data.frame(est = est, se = se, imp_t = imp_t, imp_c = imp_c, fld = fld)
}

lay_int <- run_layout("interspersed")
lay_clu <- run_layout("clustered")

lay_row <- function(x, nm) data.frame(
  layout = nm, mean_est = mean(x$est), bias = mean(x$est) - tau,
  sd_est = sd(x$est), mean_se = mean(x$se),
  import_gap = mean(x$imp_t - x$imp_c), field_gap_sd = sd(x$fld),
  coverage = mean(abs(x$est - tau) < tcrit * x$se),
  rmse = sqrt(mean((x$est - tau)^2)))
lay_tab <- rbind(lay_row(lay_int, "interspersed"),
                 lay_row(lay_clu, "clustered"))
lay_tab$se_honesty <- lay_tab$sd_est / lay_tab$mean_se
print(round(lay_tab[, -1], 5))
print(lay_tab$layout)

## ---- fig-layout ----
lay_df <- rbind(
  data.frame(est = lay_int$est, layout = "Interspersed"),
  data.frame(est = lay_clu$est, layout = "Clustered blocks"))
lay_mean <- data.frame(
  layout = c("Interspersed", "Clustered blocks"),
  m = c(mean(lay_int$est), mean(lay_clu$est)))

ggplot(lay_df, aes(est, colour = layout, fill = layout)) +
  geom_density(alpha = 0.22, linewidth = 0.7, adjust = 1.1) +
  geom_vline(xintercept = tau, linetype = "dashed",
             colour = te_pal$ink, linewidth = 0.5) +
  geom_rug(data = lay_mean, inherit.aes = FALSE,
           aes(x = m, colour = layout), linewidth = 1.1,
           length = unit(0.05, "npc"), show.legend = FALSE) +
  scale_colour_manual(values = c("Interspersed" = te_pal$clay,
                                 "Clustered blocks" = te_pal$forest)) +
  scale_fill_manual(values = c("Interspersed" = te_pal$clay,
                               "Clustered blocks" = te_pal$green)) +
  labs(x = "Estimated treatment contrast",
       y = "Density", colour = NULL, fill = NULL,
       title = "Clustering trades bias for randomisation variance") +
  theme_te() +
  theme(legend.position = "bottom",
        plot.margin = margin(8, 14, 8, 8))

## ---- neighbour-covariate ----
combo <- function(fit, wts) {
  b <- coef(fit)
  kv <- setNames(rep(0, length(b)), names(b))
  kv[names(wts)] <- unlist(wts)
  c(est = sum(kv * b), se = sqrt(drop(t(kv) %*% vcov(fit) %*% kv)))
}

run_cov <- function(phi1, n_rep_c = 1500, seed0 = 61000) {
  out <- matrix(NA_real_, n_rep_c, 9)
  for (r in seq_len(n_rep_c)) {
    d <- sim_grid(seed0 + r, leak, phi1)
    m0 <- lm(y_leak ~ z, data = d)
    m1 <- lm(y_leak ~ z + s1, data = d)
    m2 <- lm(y_leak ~ z + s1 + s2, data = d)
    out[r, ] <- c(combo(m0, list(z = 1)),
                  combo(m1, list(z = 1, s1 = nrow(off1))),
                  combo(m2, list(z = 1, s1 = nrow(off1), s2 = nrow(off2))),
                  unname(coef(m1)["z"]), unname(coef(m1)["s1"]),
                  cor(d$s1, d$s2))
  }
  colnames(out) <- c("e0", "s0", "e1", "s1", "e2", "s2",
                     "direct1", "gamma1", "cor12")
  as.data.frame(out)
}

cov_near <- run_cov(1)
cov_far <- run_cov(0.7)

summ_cov <- function(x, label) data.frame(
  truth = label,
  model = c("treatment only", "plus ring 1", "plus rings 1 and 2"),
  est = c(mean(x$e0), mean(x$e1), mean(x$e2)),
  se = c(mean(x$s0), mean(x$s1), mean(x$s2)),
  cover = c(mean(abs(x$e0 - tau) < tcrit * x$s0),
            mean(abs(x$e1 - tau) < tcrit * x$s1),
            mean(abs(x$e2 - tau) < tcrit * x$s2)))
rec <- rbind(summ_cov(cov_near, "all leakage in ring 1"),
             summ_cov(cov_far, "70 per cent ring 1, 30 per cent ring 2"))
rec$recovered_pct <- 100 * rec$est / tau
print(round(rec[, c("est", "se", "cover", "recovered_pct")], 4))
print(rec[, c("truth", "model")])
print(round(c(direct_coef_ring1_model = mean(cov_near$direct1),
              attenuated_truth = tau * (1 - leak),
              se_inflation_ring1 = rec$se[2] / rec$se[1],
              se_inflation_ring12 = rec$se[3] / rec$se[1]), 4))

## ---- range-mismatch ----
short_recovery <- rec$recovered_pct[5]
full_recovery <- rec$recovered_pct[6]
shortfall <- rec$est[2] - rec$est[5]
beyond <- tau * leak * 0.3
print(round(c(ring1_model_wrong_range = rec$est[5],
              ring1_model_right_range = rec$est[2],
              full_model_either_truth = rec$est[6],
              recovery_pct_wrong_range = short_recovery,
              shortfall = shortfall,
              leakage_beyond_assumed_range = beyond,
              overshoot = shortfall - beyond), 4))
print(round(c(coverage_wrong_range = rec$cover[5],
              coverage_right_range = rec$cover[2],
              bias_in_se_units = (tau - rec$est[5]) / rec$se[5]), 4))
print(round(c(gamma1_right_range = mean(cov_near$gamma1),
              gamma1_wrong_range = mean(cov_far$gamma1),
              gamma1_if_no_absorption = mean(cov_near$gamma1) - tau * leak * 0.3 / nrow(off1),
              mean_cor_s1_s2 = mean(cov_far$cor12)), 5))

## ---- fig-recovery ----
rec$model <- factor(rec$model, levels = rev(unique(rec$model)))
rec$truth <- factor(rec$truth, levels = unique(rec$truth))
rec$lo <- rec$est - tcrit * rec$se
rec$hi <- rec$est + tcrit * rec$se

ggplot(rec, aes(est, model)) +
  geom_vline(xintercept = tau, linetype = "dashed",
             colour = te_pal$ink, linewidth = 0.5) +
  geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0.18,
                colour = te_pal$sage, linewidth = 0.8) +
  geom_point(size = 3, colour = te_pal$forest) +
  scale_x_continuous(expand = expansion(mult = 0.07)) +
  facet_wrap(~truth, ncol = 1) +
  labs(x = "Recovered total effect of treating one plot",
       y = NULL,
       title = "The covariate fix works only out to the assumed range") +
  theme_te() +
  theme(plot.margin = margin(8, 18, 8, 8))
