# Revisit designs for long-term monitoring
# https://tidyecology.com/posts/revisit-designs-for-monitoring/
#
# 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-16

## ---- designs ----
n_visit <- 30      # site visits per year
n_year  <- 12
n_rep   <- 2       # counts per site visit

# a design maps each year to the site identifiers visited that year
visits <- function(design) {
  switch(design,
    always = lapply(1:n_year, function(j) 1:n_visit),
    rotate = lapply(1:n_year, function(j) ((j - 1) %% 4) * n_visit + 1:n_visit),
    split  = lapply(1:n_year, function(j) c(1:15, 15 + ((j - 1) %% 4) * 15 + 1:15)),
    fresh  = lapply(1:n_year, function(j) (j - 1) * n_visit + 1:n_visit))
}
designs <- c("always", "rotate", "split", "fresh")
distinct <- sapply(designs, function(d) length(unique(unlist(visits(d)))))
data.frame(design = designs, distinct_sites = unname(distinct),
           visits_per_site = round(n_visit * n_year / unname(distinct), 1))

## ---- fig-schedule ----
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 = element_blank(),
          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),
          strip.text    = element_text(colour = "#275139", face = "bold"))
}

grid_df <- do.call(rbind, lapply(designs, function(dn) {
  v <- visits(dn)
  do.call(rbind, lapply(1:n_year, function(j) {
    ids <- v[[j]]; ids <- ids[ids <= 60]
    if (length(ids) == 0) NULL else data.frame(design = dn, year = j, site = ids)
  }))
}))
grid_df$design <- factor(grid_df$design, levels = designs,
  labels = c("Always revisit", "Rotate", "Split panel", "Fresh sites"))

ggplot(grid_df, aes(year, site)) +
  geom_tile(fill = "#275139", width = 0.85, height = 0.9) +
  facet_wrap(~design, nrow = 1) +
  scale_x_continuous(breaks = c(1, 4, 8, 12)) +
  scale_y_reverse(breaks = c(1, 20, 40, 60)) +
  labs(x = "Year", y = "Site in the pool",
       title = "The same 30 visits a year, sent to different sites",
       subtitle = "First 60 site slots shown") +
  theme_te()

## ---- covariance ----
sd_site <- 0.55; sd_year <- 0.20; sd_sy <- 0.30; sd_res <- 0.35
beta_true <- -0.03
tc  <- (1:n_year) - mean(1:n_year)
Sxx <- sum(tc^2)

overlap <- function(v) {
  outer(1:n_year, 1:n_year, Vectorize(function(i, j) length(intersect(v[[i]], v[[j]]))))
}
cov_annual <- function(v) {
  within_year <- sd_year^2 + (sd_sy^2 + sd_res^2 / n_rep) / n_visit
  diag(n_year) * within_year + sd_site^2 * overlap(v) / n_visit^2
}
overlap(visits("split"))[1:5, 1:5]

## ---- exact-variances ----
w_trend  <- tc / Sxx
w_status <- rep(1 / n_year, n_year)

exact <- t(sapply(designs, function(d) {
  S <- cov_annual(visits(d))
  c(se_trend  = sqrt(drop(t(w_trend)  %*% S %*% w_trend)),
    se_status = sqrt(drop(t(w_status) %*% S %*% w_status)))
}))
exact <- data.frame(design = designs, distinct = unname(distinct), exact,
                    trend_rel  = exact[, "se_trend"]  / exact[1, "se_trend"],
                    status_rel = exact[, "se_status"] / exact[1, "se_status"])
print(exact, digits = 4, row.names = FALSE)

## ---- mc-check ----
set.seed(368)
run_design <- function(design, B = 3000) {
  v <- visits(design); npool <- length(unique(unlist(v)))
  t(replicate(B, {
    s <- rnorm(npool, 0, sd_site)
    a <- rnorm(n_year, 0, sd_year)
    annual <- vapply(1:n_year, function(j) {
      ids <- v[[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)))
    }, numeric(1))
    c(slope = unname(coef(lm(annual ~ tc))[2]), status = mean(annual))
  }))
}
mc <- t(sapply(designs, function(d) {
  m <- run_design(d)
  c(mc_trend = sd(m[, "slope"]), mc_status = sd(m[, "status"]),
    bias = mean(m[, "slope"]) - beta_true)
}))
round(cbind(mc, exact_trend = exact$se_trend, exact_status = exact$se_status), 5)

## ---- fig-tradeoff ----
pl <- data.frame(x = exact$se_status, y = exact$se_trend,
                 lab = c("Always revisit", "Rotate", "Split panel", "Fresh sites"),
                 sub = paste0(exact$distinct, " sites"))
ggplot(pl, aes(x, y)) +
  geom_point(colour = "#275139", size = 4) +
  geom_text(aes(label = lab), vjust = -1.1, colour = "#16241d", size = 3.6) +
  geom_text(aes(label = sub), vjust = 2.2, colour = "#5d6b61", size = 3) +
  expand_limits(x = range(pl$x) + c(-0.014, 0.014),
                y = range(pl$y) + c(-0.0006, 0.0009)) +
  labs(x = "Standard error of the period mean",
       y = "Standard error of the trend",
       title = "The same budget, two currencies",
       subtitle = "Twelve years, 30 site visits a year, exact standard errors") +
  theme_te() +
  theme(panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3))

## ---- fp-guard-1 ----
stopifnot(abs(drop(t(w_trend) %*% overlap(visits("always")) %*% w_trend)) <
            1e-8 * abs(drop(t(w_trend) %*% overlap(visits("fresh")) %*% w_trend)))

## ---- effective-sites ----
eff_sites <- sapply(designs, function(d) {
  O <- overlap(visits(d))
  n_visit^2 * n_year^2 / sum(O)
})
data.frame(design = designs, distinct_sites = unname(distinct),
           effective_sites = round(unname(eff_sites), 1))

## ---- penalty-curve ----
penalty <- function(n) {
  base <- sd_year^2 + (sd_sy^2 + sd_res^2 / n_rep) / n
  sqrt((base + sd_site^2 / n) / base)
}
data.frame(sites_per_year = c(5, 10, 20, 30, 60, 100),
           trend_se_penalty = round(penalty(c(5, 10, 20, 30, 60, 100)), 3))

## ---- fig-penalty ----
nseq <- seq(4, 100, by = 1)
ggplot(data.frame(n = nseq, p = penalty(nseq)), aes(n, p)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = "#b5534e") +
  geom_line(colour = "#275139", linewidth = 1.1) +
  annotate("text", x = 72, y = 1.02, label = "no penalty", colour = "#b5534e", size = 3.2) +
  labs(x = "Sites visited per year", y = "Trend standard error, fresh / permanent",
       title = "Permanent sites matter most to small programmes",
       subtitle = "Ratio computed from the variance components") +
  theme_te() +
  theme(panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3))
