# Checking a monitoring design
# https://tidyecology.com/posts/checking-a-monitoring-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-14

## ---- setup ----
sd_site <- 0.55; sd_year <- 0.20; sd_sy <- 0.30; sd_res <- 0.35
beta_true <- -0.03
n_rep <- 2

se_trend <- function(n_year, n_site, v = c(sd_year^2, sd_sy^2, sd_res^2), k = n_rep) {
  Sxx <- n_year * (n_year^2 - 1) / 12
  sqrt((v[1] + (v[2] + v[3] / k) / n_site) / Sxx)
}
trend_power <- function(n_year, n_site, beta, v = c(sd_year^2, sd_sy^2, sd_res^2), alpha = 0.05) {
  df <- n_year - 2; ncp <- abs(beta) / se_trend(n_year, n_site, v)
  crit <- qt(1 - alpha / 2, df)
  pt(-crit, df, ncp) + (1 - pt(crit, df, ncp))
}
true_power <- trend_power(20, 30, beta_true)
round(c(se = se_trend(20, 30), power = true_power), 4)

## ---- sim-fun ----
sim_monitoring <- function(n_site, n_year, n_rep, beta) {
  s  <- rnorm(n_site, 0, sd_site)
  a  <- rnorm(n_year, 0, sd_year)
  tc <- (1:n_year) - mean(1:n_year)
  sa <- matrix(rnorm(n_site * n_year, 0, sd_sy), n_site, n_year)
  d  <- expand.grid(rep = seq_len(n_rep), site = seq_len(n_site), year = seq_len(n_year))
  d$y <- 3 + beta * tc[d$year] + s[d$site] + a[d$year] +
         sa[cbind(d$site, d$year)] + rnorm(nrow(d), 0, sd_res)
  d$site <- factor(d$site); d$yearf <- factor(d$year); d$t <- d$year
  d
}
vc_anova <- function(d, n_site, n_year, n_rep) {
  y <- d$y; gm <- mean(y)
  m_si <- tapply(y, d$site, mean); m_yr <- tapply(y, d$yearf, mean)
  m_cell <- tapply(y, list(d$site, d$yearf), mean)
  SS_year <- n_site * n_rep * sum((m_yr - gm)^2)
  SS_sy   <- n_rep * sum((m_cell - outer(m_si, m_yr, "+") + gm)^2)
  SS_res  <- sum((y - m_cell[cbind(as.integer(d$site), as.integer(d$yearf))])^2)
  MS_year <- SS_year / (n_year - 2)                  # one year df spent on the trend
  MS_sy   <- SS_sy / ((n_site - 1) * (n_year - 1))
  MS_res  <- SS_res / (n_site * n_year * (n_rep - 1))
  c(year = (MS_year - MS_sy) / (n_rep * n_site),
    sy   = (MS_sy - MS_res) / n_rep,
    res  = MS_res)
}

## ---- pilot ----
set.seed(370)
pilot_power <- t(replicate(2000, {
  d <- sim_monitoring(10, 5, n_rep, beta_true)
  d$y <- residuals(lm(y ~ t, data = d))
  v <- vc_anova(d, 10, 5, n_rep)
  c(v_year = unname(v["year"]),
    power  = trend_power(20, 30, beta_true, pmax(unname(v), 0)))
}))
round(c(true_year_component = sd_year^2,
        median_estimate     = median(pilot_power[, "v_year"]),
        negative_estimates  = mean(pilot_power[, "v_year"] < 0),
        true_power          = true_power,
        median_power        = median(pilot_power[, "power"]),
        lower_5pc           = unname(quantile(pilot_power[, "power"], 0.05)),
        pc_claiming_over_95 = mean(pilot_power[, "power"] > 0.95)), 4)

## ---- fig-pilot ----
library(ggplot2)
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    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),
          text = element_text(colour = "#2c3a31"),
          plot.title    = element_text(colour = "#16241d", face = "bold", size = base_size + 1),
          plot.subtitle = element_text(colour = "#46604a", size = base_size - 1))
}
ggplot(data.frame(p = pilot_power[, "power"]), aes(p)) +
  geom_histogram(binwidth = 0.02, fill = "#2f8f63", colour = "white", linewidth = 0.2) +
  geom_vline(xintercept = true_power, linetype = "dashed", colour = "#b5534e", linewidth = 0.8) +
  annotate("text", x = true_power - 0.02, y = Inf, vjust = 1.6, hjust = 1,
           label = "true power", colour = "#b5534e", size = 3.3) +
  labs(x = "Power claimed by the pilot", y = "Pilots",
       title = "A short pilot flatters the design it is used to plan",
       subtitle = "Five years at ten sites, planning twenty years at thirty sites") +
  theme_te()

## ---- attrition ----
run_attrition <- function(mode, B = 1500, n_year = 15, n_site = 30, rate = 0.08) {
  tc <- (1:n_year) - mean(1:n_year)
  t(replicate(B, {
    s <- rnorm(n_site, 0, sd_site); a <- rnorm(n_year, 0, sd_year)
    alive <- rep(TRUE, n_site); annual <- numeric(n_year)
    for (j in 1:n_year) {
      if (j > 1 && mode != "none") {
        p_drop <- if (mode == "random") rep(rate, n_site)
                  else 2 * rate / (1 + exp(3 * (s - mean(s))))   # poor sites go first
        alive <- alive & !(runif(n_site) < p_drop)
      }
      ids <- which(alive)
      annual[j] <- mean(3 + beta_true * tc[j] + s[ids] + a[j] +
                        rnorm(length(ids), 0, sd_sy) +
                        rnorm(length(ids), 0, sd_res / sqrt(n_rep)))
    }
    c(slope = unname(coef(lm(annual ~ tc))[2]), left = sum(alive))
  }))
}
set.seed(3701)
att <- t(sapply(c("none", "random", "selective"), function(m) {
  r <- run_attrition(m)
  c(mean_slope = mean(r[, "slope"]), bias = mean(r[, "slope"]) - beta_true,
    sites_left = mean(r[, "left"]))
}))
round(att, 4)

## ---- fig-attrition ----
ab <- data.frame(mode = factor(c("No attrition", "Random", "Selective"),
                               levels = c("Selective", "Random", "No attrition")),
                 slope = att[, "mean_slope"])
ggplot(ab, aes(slope, mode)) +
  geom_vline(xintercept = beta_true, linetype = "dashed", colour = "#b5534e") +
  geom_col(fill = "#275139", width = 0.55) +
  annotate("text", x = beta_true, y = 3.45, label = "true trend",
           colour = "#b5534e", size = 3.2, hjust = -0.1) +
  labs(x = "Estimated trend (log scale, per year)", y = NULL,
       title = "Only one kind of dropout moves the answer",
       subtitle = "Fifteen years, eight per cent of sites lost per year") +
  theme_te()

## ---- drift ----
drift_run <- function(pop_trend, detection_trend, B = 1500, n_year = 20, n_site = 30) {
  tc <- (1:n_year) - mean(1:n_year)
  t(replicate(B, {
    d <- sim_monitoring(n_site, n_year, n_rep, pop_trend)
    d$y <- d$y + detection_trend * tc[d$year]      # observers slowly change
    annual <- tapply(d$y, d$yearf, mean)
    co <- summary(lm(annual ~ tc))$coefficients[2, ]
    c(est = unname(co[1]), sig = as.numeric(abs(co[1] / co[2]) > qt(0.975, n_year - 2)))
  }))
}
set.seed(3702)
flat <- drift_run(0, -0.015)
decl <- drift_run(-0.03, -0.015)
round(c(stable_pop_mean_estimate = mean(flat[, "est"]),
        stable_pop_pc_significant = 100 * mean(flat[, "sig"]),
        declining_pop_mean_estimate = mean(decl[, "est"]),
        sum_of_the_two_trends = -0.03 - 0.015), 4)
