# SCR sampling design and precision
# https://tidyecology.com/posts/scr-sampling-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-11-06

## ---- setup ----
library(ggplot2); library(tidyr)
paper <- "#f5f4ee"; ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"
labelc <- "#46604a"; sage <- "#93a87f"; linec <- "#dad9ca"; faint <- "#5d6b61"
gold <- "#c9b458"; rust <- "#b5534e"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.background  = element_rect(fill = paper, colour = NA),
      panel.background = element_rect(fill = paper, colour = NA),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = linec, linewidth = 0.3),
      axis.title = element_text(colour = body), axis.text = element_text(colour = faint),
      plot.title = element_text(colour = ink, face = "bold"),
      plot.subtitle = element_text(colour = labelc),
      legend.title = element_text(colour = body), legend.text = element_text(colour = body),
      strip.text = element_text(colour = ink, face = "bold")
    )
}

## ---- fit-one ----
D_true <- 0.5; g0_true <- 0.30; sig_true <- 0.70; K <- 6

fit_one <- function(spacing) {
  tr    <- seq(0, 4 * spacing, by = spacing)          # 5 x 5 = 25 traps
  traps <- as.matrix(expand.grid(x = tr, y = tr)); J <- nrow(traps)
  buf   <- 4 * sig_true
  xl <- range(traps[, 1]) + c(-buf, buf); yl <- range(traps[, 2]) + c(-buf, buf)
  A  <- diff(xl) * diff(yl)
  N  <- rpois(1, D_true * A)
  sx <- runif(N, xl[1], xl[2]); sy <- runif(N, yl[1], yl[2])
  d2 <- outer(sx, traps[, 1], "-")^2 + outer(sy, traps[, 2], "-")^2
  Yf <- matrix(rbinom(N * J, K, g0_true * exp(-d2 / (2 * sig_true^2))), N, J)
  cc <- rowSums(Yf) > 0; Y <- Yf[cc, , drop = FALSE]; n <- nrow(Y)
  sr <- sum(rowSums(Y > 0) >= 2)
  rr <- sum(Y) - n                                     # recaptures: detections after the first
  if (n < 3) return(list(D = NA, sigma = NA, sr = sr, n = n, r = rr, ok = FALSE))

  hx <- diff(xl) / 26; hy <- diff(yl) / 26           # 26 x 26 equal cells
  gx <- seq(xl[1] + hx / 2, xl[2] - hx / 2, length.out = 26)   # cell centres
  gy <- seq(yl[1] + hy / 2, yl[2] - hy / 2, length.out = 26)
  G  <- as.matrix(expand.grid(x = gx, y = gy))
  d2G <- outer(G[, 1], traps[, 1], "-")^2 + outer(G[, 2], traps[, 2], "-")^2
  Cc  <- rowSums(lchoose(K, Y))
  negll <- function(th) {                             # same likelihood as the basics post
    Dd <- exp(th[1]); g0 <- plogis(th[2]); sg <- exp(th[3])
    P  <- g0 * exp(-d2G / (2 * sg^2))
    pb <- mean(1 - exp(rowSums(K * log1p(-P))))
    if (pb <= 0) return(1e10)
    LM <- Y %*% t(log(P)) + (K - Y) %*% t(log1p(-P)) + Cc
    m  <- apply(LM, 1, max); lf <- m + log(rowMeans(exp(LM - m)))
    -(dpois(n, Dd * A * pb, log = TRUE) + sum(lf) - n * log(pb))
  }
  st <- c(log(max(n, 1) / (A * 0.4)), qlogis(0.25), log(sig_true))
  ft <- tryCatch(optim(st, negll, method = "BFGS",
                       control = list(maxit = 400, reltol = 1e-9)), error = function(e) NULL)
  if (is.null(ft) || ft$convergence != 0) return(list(D = NA, sigma = NA, sr = sr, n = n, r = rr, ok = FALSE))
  Dh <- exp(ft$par[1]); sh <- exp(ft$par[3])
  list(D = Dh, sigma = sh, sr = sr, n = n, r = rr,
       ok = is.finite(Dh) && is.finite(sh) && sh < 4 * sig_true && Dh < 5 * D_true)
}

## ---- sweep ----
set.seed(129)
spacings <- c(0.5, 0.75, 1.0, 1.5, 2.0, 2.5)
R <- 80
res <- data.frame()
for (sp in spacings) {
  Ds <- Ss <- SRs <- Ns <- RRs <- oks <- numeric(R)
  for (r in 1:R) { o <- fit_one(sp); Ds[r] <- o$D; Ss[r] <- o$sigma
    SRs[r] <- o$sr; Ns[r] <- o$n; RRs[r] <- o$r; oks[r] <- o$ok }
  use <- oks == 1
  res <- rbind(res, data.frame(
    spacing = sp, sigma_ratio = sp / sig_true,
    n_mean = mean(Ns), r_mean = mean(RRs), sr_frac = mean(SRs / pmax(Ns, 1)), usable = mean(use),
    D_cv = sd(Ds[use]) / mean(Ds[use]), sig_cv = sd(Ss[use]) / mean(Ss[use]),
    D_sig_cor = cor(Ds[use], Ss[use])))
}
best <- res$spacing[which.min(res$D_cv)]

## ---- fig-cv ----
cvl <- pivot_longer(res, c(D_cv, sig_cv), names_to = "which", values_to = "cv")
cvl$which <- factor(cvl$which, c("D_cv", "sig_cv"), c("density CV", "sigma CV"))
bmin <- res[which.min(res$D_cv), ]
p1 <- ggplot(cvl, aes(sigma_ratio, cv, colour = which)) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.8) +
  geom_point(data = bmin, aes(sigma_ratio, D_cv), colour = ink, size = 3.2, inherit.aes = FALSE) +
  annotate("text", x = bmin$sigma_ratio, y = bmin$D_cv, label = "optimum near 2 sigma",
           vjust = 2.2, hjust = 0.2, colour = ink, size = 3.3) +
  scale_colour_manual(values = c("density CV" = forest, "sigma CV" = rust), name = NULL) +
  labs(x = "trap spacing (units of sigma)", y = "coefficient of variation",
       title = "Density precision is U-shaped in trap spacing",
       subtitle = "too tight catches few animals; too wide loses spatial recaptures") +
  theme_te() + theme(legend.position = "top")
p1

## ---- fig-drivers ----
dl <- pivot_longer(res, c(n_mean, sr_frac), names_to = "metric", values_to = "value")
dl$metric <- factor(dl$metric, c("n_mean", "sr_frac"),
                    c("animals detected", "spatial-recapture fraction"))
p2 <- ggplot(dl, aes(sigma_ratio, value)) +
  geom_line(colour = forest, linewidth = 0.9) + geom_point(colour = forest, size = 1.8) +
  facet_wrap(~ metric, scales = "free_y") +
  labs(x = "trap spacing (units of sigma)", y = NULL,
       title = "Coverage rises, recaptures fall",
       subtitle = "the density optimum needs a workable amount of both") +
  theme_te()
p2

## ---- rule ----
res$rule <- 1 / sqrt(pmin(res$n_mean, res$r_mean))
res$cv_over_rule <- res$D_cv / res$rule
hr95_diam <- 2 * sqrt(qchisq(0.95, 2)) * sig_true   # 95 per cent home range, bivariate normal
array_w <- 4 * spacings
stopifnot(res$n_mean[4] < res$r_mean[4], res$n_mean[5] > res$r_mean[5],
          res$cv_over_rule[1] > 1.3, array_w[1] < hr95_diam)
print(round(res[, c("sigma_ratio", "n_mean", "r_mean", "rule", "D_cv", "cv_over_rule")], 3))
print(round(c(home_range_95_diameter = hr95_diam, tightest_array_width = array_w[1]), 3))

## ---- thumb ----
ggsave("thumbnail.png", p1 + labs(title = NULL, subtitle = NULL) +
         theme(legend.position = "none"),
       width = 7.5, height = 5.4, dpi = 100, bg = paper)
