# Spatial capture-recapture from scratch
# https://tidyecology.com/posts/spatial-capture-recapture-basics/
#
# 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-07

## ---- setup ----
library(ggplot2)
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)
    )
}

## ---- simulate ----
set.seed(0)
spacing  <- 1
tr       <- seq(1, 7, by = spacing)              # 7 x 7 = 49 traps
traps    <- as.matrix(expand.grid(x = tr, y = tr))
J        <- nrow(traps)
K        <- 6                                    # occasions
g0_true  <- 0.30
sig_true <- 0.70
buffer   <- 3
xl <- range(traps[, 1]) + c(-buffer, buffer)     # state-space extent
yl <- range(traps[, 2]) + c(-buffer, buffer)
A  <- diff(xl) * diff(yl)                         # state-space area
N_true <- 72
D_true <- N_true / A                              # animals per unit area

# activity centres and occasion-level encounters
sx <- runif(N_true, xl[1], xl[2])
sy <- runif(N_true, yl[1], yl[2])
d_it <- sqrt(outer(sx, traps[, 1], "-")^2 + outer(sy, traps[, 2], "-")^2)
p_it <- g0_true * exp(-d_it^2 / (2 * sig_true^2))
y_arr <- array(rbinom(N_true * J * K, 1, rep(p_it, times = K)),
               dim = c(N_true, J, K))
y_ij  <- apply(y_arr, c(1, 2), sum)               # per-trap binomial(K,.) counts
caught <- rowSums(y_ij) > 0
n      <- sum(caught)
Y      <- y_ij[caught, , drop = FALSE]            # detected individuals
sxc    <- sx[caught]; syc <- sy[caught]

tot_det    <- sum(Y)
traps_per  <- rowSums(Y > 0)
spat_recap <- sum(traps_per >= 2)                 # caught at 2 or more traps

## ---- fit ----
hx <- diff(xl) / 40; hy <- diff(yl) / 40          # 40 x 40 equal cells
gx <- seq(xl[1] + hx / 2, xl[2] - hx / 2, length.out = 40)   # cell centres
gy <- seq(yl[1] + hy / 2, yl[2] - hy / 2, length.out = 40)
G  <- as.matrix(expand.grid(x = gx, y = gy))
dG <- sqrt(outer(G[, 1], traps[, 1], "-")^2 + outer(G[, 2], traps[, 2], "-")^2)

negll <- function(theta) {
  D  <- exp(theta[1]); g0 <- plogis(theta[2]); sg <- exp(theta[3])
  P  <- g0 * exp(-dG^2 / (2 * sg^2))              # detection prob, grid x trap
  pdot <- 1 - exp(rowSums(K * log1p(-P)))          # P(detected | centre at g)
  pbar <- mean(pdot)
  if (pbar <= 0) return(1e10)
  lb <- matrix(0, n, nrow(G))                      # log capture-history prob per grid cell
  for (j in 1:J)
    lb <- lb + outer(Y[, j], P[, j], function(y, p) dbinom(y, K, p, log = TRUE))
  m    <- apply(lb, 1, max)
  logf <- m + log(rowMeans(exp(lb - m)))           # marginal over the grid
  -(dpois(n, D * A * pbar, log = TRUE) + sum(logf) - n * log(pbar))
}

st  <- c(log(n / (A * 0.4)), qlogis(0.2), log(1))
fit <- optim(st, negll, method = "BFGS", hessian = TRUE,
             control = list(maxit = 500, reltol = 1e-10))
stopifnot(fit$convergence == 0)   # check before inverting the Hessian
D_hat   <- exp(fit$par[1]); g0_hat <- plogis(fit$par[2]); sig_hat <- exp(fit$par[3])
V       <- solve(fit$hessian)
se_logD <- sqrt(V[1, 1])
D_lo <- exp(fit$par[1] - 1.96 * se_logD); D_hi <- exp(fit$par[1] + 1.96 * se_logD)
se_g0  <- sqrt(V[2, 2]) * g0_hat * (1 - g0_hat)
se_sig <- sqrt(V[3, 3]) * sig_hat

Ph       <- g0_hat * exp(-dG^2 / (2 * sig_hat^2))
pdh      <- 1 - exp(rowSums(K * log1p(-Ph)))
pbar_hat <- mean(pdh)
a_eff    <- A * pbar_hat
N_hat    <- D_hat * A

## ---- naive ----
anyk  <- apply(y_arr, c(1, 3), function(z) as.integer(any(z > 0)))
freqK <- rowSums(anyk)[caught]                     # occasions caught, per animal
Ttot  <- sum(freqK)
Ng    <- n:600
m0ll  <- sapply(Ng, function(N) {
  p <- Ttot / (N * K)
  if (p <= 0 || p >= 1) return(-Inf)
  lchoose(N, n) + Ttot * log(p) + (N * K - Ttot) * log(1 - p)
})
N0_hat <- Ng[which.max(m0ll)]
p0_hat <- Ttot / (N0_hat * K)

arr_span   <- apply(traps, 2, function(z) diff(range(z)))        # 6 by 6 array
array_area <- prod(arr_span)                                     # 36
bw         <- c(1, 2, 3, 4)                                      # buffer widths in sigma
buff_area  <- sapply(bw, function(w) prod(arr_span + 2 * w * sig_true))
D_arr      <- N0_hat / array_area
D_buf      <- N0_hat / buff_area

## ---- fig-array ----
seg <- do.call(rbind, lapply(which(caught), function(i) {
  ii <- match(i, which(caught)); js <- which(Y[ii, ] > 0)
  data.frame(x = sxc[ii], y = syc[ii], xend = traps[js, 1], yend = traps[js, 2])
}))
cd <- data.frame(x = sx, y = sy, det = ifelse(caught, "detected", "not detected"))
p1 <- ggplot() +
  annotate("rect", xmin = xl[1], xmax = xl[2], ymin = yl[1], ymax = yl[2],
           fill = NA, colour = sage, linetype = "dashed") +
  geom_segment(data = seg, aes(x, y, xend = xend, yend = yend),
               colour = forest, alpha = 0.35, linewidth = 0.3) +
  geom_point(data = as.data.frame(traps), aes(x, y), shape = 3,
             colour = faint, size = 2, stroke = 0.6) +
  geom_point(data = cd, aes(x, y, shape = det, colour = det, fill = det), size = 2.4) +
  scale_shape_manual(values = c(detected = 21, "not detected" = 21)) +
  scale_colour_manual(values = c(detected = forest, "not detected" = sage)) +
  scale_fill_manual(values = c(detected = forest, "not detected" = paper)) +
  coord_equal() +
  labs(x = "easting", y = "northing", shape = NULL, colour = NULL, fill = NULL,
       title = "A spatial capture-recapture study",
       subtitle = "captures fan out from each animal's activity centre") +
  theme_te() + theme(legend.position = "top")
p1

## ---- fig-pdot ----
gdf <- data.frame(x = G[, 1], y = G[, 2], pdot = pdh)
p2 <- ggplot(gdf, aes(x, y, fill = pdot)) +
  geom_raster(interpolate = TRUE) +
  geom_point(data = as.data.frame(traps), aes(x, y), inherit.aes = FALSE,
             shape = 3, colour = ink, size = 1.6, stroke = 0.5) +
  scale_fill_gradient(low = paper, high = forest, name = "P(detected)") +
  coord_equal() +
  labs(x = "easting", y = "northing",
       title = "Effective sampling area",
       subtitle = paste0("a_eff = ", round(a_eff, 1), " over a state-space of ", A)) +
  theme_te()
p2

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