# Estimating plant cover with point intercepts
# https://tidyecology.com/posts/cover-from-point-intercepts/
#
# 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_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
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"),
          axis.text        = element_text(colour = te_body))
}

set.seed(20260813)

## ---- fields ----
nside    <- 512L        # cells per side; a 5 cm cell makes this a 25.6 m plot
p_target <- 0.35

# white noise smoothed with a Gaussian kernel, on a torus so there are no edges
smooth_noise <- function(nside, sigma) {
  dd <- pmin(0:(nside - 1), nside - 0:(nside - 1))
  gk <- exp(-dd^2 / (2 * sigma^2))
  Re(fft(fft(matrix(rnorm(nside * nside), nside, nside)) * fft(outer(gk, gk)),
         inverse = TRUE))
}

zz        <- smooth_noise(nside, sigma = 2)          # Gaussian kernel sd of 2 cells
clumped   <- (zz >= quantile(zz, 1 - p_target)) * 1L
scattered <- matrix(sample(clumped), nside, nside)   # the same cells, shuffled
p_true    <- mean(clumped)

c(patchy = mean(clumped), scattered = mean(scattered))

## ---- grain ----
# correlation between the field and a copy of itself shifted k cells, both axes
shift_cor <- function(fld, k) {
  jj <- c((k + 1):nrow(fld), seq_len(k))
  0.5 * (cor(as.vector(fld), as.vector(fld[jj, ])) +
         cor(as.vector(fld), as.vector(fld[, jj])))
}

gaps  <- c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 10L, 12L)
rho   <- sapply(gaps, function(k) shift_cor(clumped, k))
reach <- 5 * min(gaps[rho < 0.05])
runs  <- unlist(apply(clumped, 1, function(r) with(rle(r), lengths[values == 1L])))

print(round(setNames(rho, paste0(5 * gaps, "cm")), 3))
round(c(reach_cm        = reach,
        mean_run_cm     = 5 * mean(runs),
        weighted_run_cm = 5 * sum(runs^2) / sum(runs)), 1)

## ---- fig-fields ----
win  <- 60L                                  # a 3 m window at 5 cm cells
cell <- 0.05
idx  <- seq_len(win)

window_df <- function(fld, nm)
  data.frame(x = rep(idx, win) * cell, y = rep(idx, each = win) * cell,
             veg = factor(as.vector(fld[idx, idx]), levels = c(0, 1),
                          labels = c("bare", "plant")),
             field = nm)

maps   <- rbind(window_df(clumped, "patchy"), window_df(scattered, "scattered"))
pin_ij <- as.matrix(expand.grid(i = 21 + 2 * (0:9), j = 21 + 2 * (0:9)))
pins   <- data.frame(x = pin_ij[, 1] * cell, y = pin_ij[, 2] * cell)

ggplot(maps, aes(x = x, y = y)) +
  geom_raster(aes(fill = veg)) +
  geom_point(data = pins, colour = te_rust, size = 0.8) +
  scale_fill_manual(values = c(bare = te_line, plant = te_forest)) +
  coord_equal() +
  facet_wrap(~ field) +
  labs(x = "metres", y = "metres", fill = NULL,
       title = "Same cover, different arrangement, same pins") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- frames ----
pin_grid <- function(side, step)
  expand.grid(dx = step * (0:(side - 1)), dy = step * (0:(side - 1)))

drop_frames <- function(fld, pins, nframes) {
  nside <- nrow(fld)
  ox <- sample.int(nside, nframes, replace = TRUE) - 1L
  oy <- sample.int(nside, nframes, replace = TRUE) - 1L
  ix <- outer(ox, pins$dx, "+") %% nside + 1L
  iy <- outer(oy, pins$dy, "+") %% nside + 1L
  rowMeans(matrix(fld[cbind(as.vector(ix), as.vector(iy))], nrow = nframes))
}

frame100 <- pin_grid(10L, 2L)            # 10 x 10 pins, two cells (10 cm) apart
npin     <- nrow(frame100)
reps     <- 20000L
ph_clump <- drop_frames(clumped,   frame100, reps)
ph_scat  <- drop_frames(scattered, frame100, reps)

binom_var <- p_true * (1 - p_true) / npin
round(c(truth        = p_true,
        mean_patchy  = mean(ph_clump), mean_scattered = mean(ph_scat),
        sd_patchy    = sd(ph_clump),   sd_scattered   = sd(ph_scat),
        sd_binomial  = sqrt(binom_var)), 4)

## ---- deff ----
deff <- c(patchy = var(ph_clump), scattered = var(ph_scat)) / binom_var

wald_covers <- function(ph, n, truth) {
  se <- sqrt(ph * (1 - ph) / n)
  mean(ph - 1.96 * se <= truth & truth <= ph + 1.96 * se)
}

round(c(deff,
        n_eff_patchy    = npin / deff[["patchy"]],
        wald_patchy     = wald_covers(ph_clump, npin, p_true),
        wald_scattered  = wald_covers(ph_scat,  npin, p_true)), 3)

## ---- fig-sampling ----
samp <- data.frame(phat  = c(ph_clump, ph_scat),
                   field = rep(c("patchy", "scattered"), each = reps))

ggplot(samp, aes(x = phat, fill = field)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 0.01,
                 boundary = 0.005, position = "identity", alpha = 0.6,
                 colour = NA) +
  geom_vline(xintercept = p_true, colour = te_ink, linewidth = 0.6) +
  geom_vline(xintercept = p_true + c(-1, 1) * 1.96 * sqrt(binom_var),
             linetype = "dashed", colour = te_body) +
  scale_fill_manual(values = c(patchy = te_rust, scattered = te_forest)) +
  labs(x = "cover estimated from one 100-pin frame", y = "density", fill = NULL,
       title = "The same estimator, two sampling distributions") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- layout-table ----
survey_phat <- function(fld, side, nframes) {
  fr <- drop_frames(fld, pin_grid(side, 2L), nframes * reps)
  rowMeans(matrix(fr, nrow = reps, byrow = TRUE))
}

lay_ph <- list(ph_clump,                      # the single frame from above, reused
               survey_phat(clumped,  5L,   4L),
               survey_phat(clumped,  2L,  25L),
               survey_phat(clumped,  1L, 100L))

lay <- data.frame(pins_per_frame = c(100L, 25L, 4L, 1L),
                  frames         = c(1L, 4L, 25L, 100L),
                  se       = sapply(lay_ph, sd),
                  deff     = sapply(lay_ph, var) / binom_var,
                  coverage = sapply(lay_ph, wald_covers, n = npin, truth = p_true))
print(round(lay, 3))

## ---- fig-layouts ----
ggplot(lay, aes(x = pins_per_frame, y = coverage)) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = te_body) +
  geom_line(colour = te_forest, linewidth = 0.9) +
  geom_point(colour = te_rust, size = 3) +
  scale_x_log10(breaks = lay$pins_per_frame) +
  labs(x = "pins per frame (one hundred pins in total)",
       y = "coverage of the nominal 95 per cent interval",
       title = "The same pins, spread out") +
  theme_datasheet()

## ---- ultimate ----
nfr      <- 10L
nsurv    <- 4000L
frame_ph <- matrix(drop_frames(clumped, frame100, nfr * nsurv),
                   nrow = nsurv, byrow = TRUE)
ph_big   <- rowMeans(frame_ph)                       # ten frames, 1000 pins
se_pin   <- sqrt(ph_big * (1 - ph_big) / (nfr * npin))
se_uc    <- apply(frame_ph, 1, sd) / sqrt(nfr)       # ultimate-cluster
tcrit    <- qt(0.975, nfr - 1)
cov_pin  <- mean(abs(ph_big - p_true) <= 1.96 * se_pin)
cov_uc   <- mean(abs(ph_big - p_true) <= tcrit * se_uc)

round(c(true_sd        = sd(ph_big),
        mean_se_pins   = mean(se_pin),
        mean_se_frames = mean(se_uc),
        cover_pins     = cov_pin,
        cover_frames   = cov_uc), 4)

## ---- transfer ----
new_field <- function(sigma) {
  z <- smooth_noise(nside, sigma)
  (z >= quantile(z, 1 - p_target)) * 1L
}

field_deff <- function(fld) {
  ph <- drop_frames(fld, frame100, reps)
  pp <- mean(fld)
  c(deff = var(ph) / (pp * (1 - pp) / npin), coverage = wald_covers(ph, npin, pp))
}

sweep_one <- function(sigma) {
  fl <- new_field(sigma)
  rr <- sapply(1:100, function(k) shift_cor(fl, k))
  c(kernel_cm   = 5 * sigma,
    rho_at_pins = shift_cor(fl, 2L),
    reach_cm    = 5 * which(rr < 0.05)[1],
    field_deff(fl))
}

swp <- as.data.frame(t(sapply(c(0.5, 1, 2, 4, 20), sweep_one)))
print(round(swp, 3))

## ---- redraw ----
dfs <- replicate(12L, field_deff(new_field(2))[["deff"]])

round(c(published = deff[["patchy"]], mean = mean(dfs), sd = sd(dfs),
        lowest = min(dfs), highest = max(dfs),
        below_published = sum(dfs < deff[["patchy"]])), 2)
