# Density surface models for distance sampling
# https://tidyecology.com/posts/density-surface-modelling/
#
# 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

## ---- data ----
set.seed(3130)
suppressPackageStartupMessages(library(mgcv))

W <- 0.25                                        # truncation distance, km
dens_fun <- function(x, y) 8 * exp(-((x - 9)^2 / 60 + (y - 13)^2 / 30)) + 1.2
lines_x <- seq(1.5, 28.5, by = 3)
esw_of <- function(s) s * sqrt(pi / 2) * (2 * pnorm(W / s) - 1)

sim_survey <- function(sigma, seed) {
  set.seed(seed)
  lam_max <- dens_fun(9, 13)
  n0 <- rpois(1, lam_max * 30 * 20)
  px <- runif(n0, 0, 30); py <- runif(n0, 0, 20)
  keep <- runif(n0) < dens_fun(px, py) / lam_max     # thin to the true surface
  px <- px[keep]; py <- py[keep]
  obs <- do.call(rbind, lapply(lines_x, function(lx) {
    d <- abs(px - lx); cand <- which(d <= W)
    if (!length(cand)) return(NULL)
    seen <- cand[runif(length(cand)) < exp(-d[cand]^2 / (2 * sigma^2))]
    if (!length(seen)) return(NULL)
    data.frame(line = lx, dist = d[seen], y = py[seen])
  }))
  list(obs = obs, N_true = length(px))
}
sv <- sim_survey(sigma = 0.10, seed = 11)
p313_Ntrue <- sv$N_true; p313_ndet <- nrow(sv$obs)
c(true_N = p313_Ntrue, detections = p313_ndet)

## ---- detfun ----
nll_hn <- function(lsig, d) {
  s <- exp(lsig)
  sum(d^2) / (2 * s^2) + length(d) * log(esw_of(s))
}
f1 <- optim(log(0.1), nll_hn, d = sv$obs$dist, method = "BFGS", hessian = TRUE)
sig_hat <- exp(f1$par)
esw <- esw_of(sig_hat)
p_hat <- esw / W                                  # average detection probability
se_sig <- sig_hat * sqrt(1 / f1$hessian[1, 1])
grad <- (esw_of(sig_hat * 1.001) - esw_of(sig_hat * 0.999)) / (0.002 * sig_hat)
se_p <- abs(grad) * se_sig / W                    # delta method

p313_sig <- sig_hat; p313_esw <- esw; p313_p <- p_hat
p313_sep <- se_p; p313_cvp <- se_p / p_hat
c(sigma = sig_hat, esw_km = esw, p = p_hat, se_p = se_p, cv_p = p313_cvp)

## ---- segments ----
segs <- expand.grid(line = lines_x, y0 = seq(0, 18, by = 2))
segs$ymid <- segs$y0 + 1
segs$n <- mapply(function(lx, y0)
  sum(sv$obs$line == lx & sv$obs$y >= y0 & sv$obs$y < y0 + 2), segs$line, segs$y0)
segs$area <- 2 * esw * 2                          # effective area, km^2

m <- gam(n ~ s(line, ymid, k = 20), offset = log(area), family = poisson,
         data = segs, method = "REML")
p313_edf <- sum(m$edf); p313_dev <- summary(m)$dev.expl
p313_nseg <- nrow(segs); p313_nonzero <- sum(segs$n > 0)
c(segments = p313_nseg, with_detections = p313_nonzero,
  edf = p313_edf, deviance_explained = p313_dev)

## ---- predict ----
grid <- expand.grid(line = seq(0.5, 29.5, 1), ymid = seq(0.5, 19.5, 1))
grid$area <- 1           # predict() ignores gam()'s offset argument: exp(lp) is per km^2
lp <- predict(m, newdata = grid, type = "link")
N_hat <- sum(exp(lp))
p313_N <- N_hat
c(N_hat = N_hat, true = p313_Ntrue, ratio = N_hat / p313_Ntrue)

## ---- fig-surface ----
library(ggplot2)
theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid = element_blank(),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 11),
          plot.subtitle = element_text(colour = "#5d6b61", size = 9),
          axis.title = element_text(colour = "#46604a", size = 9.5),
          axis.text = element_text(colour = "#5d6b61", size = 8.5),
          legend.title = element_text(colour = "#46604a", size = 8.5),
          legend.text = element_text(colour = "#5d6b61", size = 8))
}
gp <- grid; gp$dens <- exp(lp)
ggplot(gp, aes(line, ymid)) +
  geom_raster(aes(fill = dens)) +
  geom_vline(xintercept = lines_x, colour = "#b5534e", linewidth = 0.25, alpha = 0.6) +
  geom_point(data = sv$obs, aes(line, y), colour = "#b5534e", size = 0.5, alpha = 0.7) +
  scale_fill_gradient(low = "#f5f4ee", high = "#1d5b4e", name = "density\nper km2") +
  coord_fixed() +
  labs(title = "Predicted density surface, with the data that made it",
       subtitle = "the model sees ten lines; everything between them is interpolation",
       x = "east (km)", y = "north (km)") +
  theme_te()

## ---- variance ----
X <- predict(m, newdata = grid, type = "lpmatrix")
mu <- exp(lp)
dN_dbeta <- as.numeric(t(mu) %*% X)
var_spatial <- as.numeric(t(dN_dbeta) %*% vcov(m) %*% dN_dbeta)

# abundance scales as 1/p, so dN/dp = -N/p
var_detect <- (N_hat / p_hat)^2 * se_p^2

p313_vsp <- var_spatial; p313_vdet <- var_detect
p313_cv_naive <- sqrt(var_spatial) / N_hat
p313_cv_prop <- sqrt(var_spatial + var_detect) / N_hat
p313_share <- var_detect / (var_spatial + var_detect)
c(cv_spatial_only = p313_cv_naive, cv_propagated = p313_cv_prop,
  detection_share = p313_share)

## ---- mc ----
one_dsm <- function(sv) {
  d <- sv$obs$dist
  f1 <- optim(log(0.1), function(ls) {
    s <- exp(ls); sum(d^2) / (2 * s^2) + length(d) * log(esw_of(s))
  }, method = "BFGS", hessian = TRUE)
  sg <- exp(f1$par); esw <- esw_of(sg); p <- esw / W
  se_sg <- sg * sqrt(1 / f1$hessian[1, 1])
  gr <- (esw_of(sg * 1.001) - esw_of(sg * 0.999)) / (0.002 * sg)
  se_p <- abs(gr) * se_sg / W
  sg2 <- expand.grid(line = lines_x, y0 = seq(0, 18, by = 2))
  sg2$ymid <- sg2$y0 + 1
  sg2$n <- mapply(function(lx, y0)
    sum(sv$obs$line == lx & sv$obs$y >= y0 & sv$obs$y < y0 + 2), sg2$line, sg2$y0)
  sg2$area <- 2 * esw * 2
  mm <- try(gam(n ~ s(line, ymid, k = 20), offset = log(area), family = poisson,
                data = sg2, method = "REML"), silent = TRUE)
  if (inherits(mm, "try-error")) return(NULL)
  gr2 <- expand.grid(line = seq(0.5, 29.5, 1), ymid = seq(0.5, 19.5, 1)); gr2$area <- 1
  l2 <- predict(mm, newdata = gr2, type = "link")
  Nh <- sum(exp(l2))
  Xm <- predict(mm, newdata = gr2, type = "lpmatrix")
  dN <- as.numeric(t(exp(l2)) %*% Xm)
  vsp <- as.numeric(t(dN) %*% vcov(mm) %*% dN)
  c(N = Nh, se_sp = sqrt(vsp), se_tot = sqrt(vsp + (Nh / p)^2 * se_p^2), Nt = sv$N_true)
}
M <- 300
res <- t(sapply(1:M, function(i) {
  r <- one_dsm(sim_survey(0.10, 5000 + i))
  if (is.null(r)) rep(NA_real_, 4) else r
}))
res <- res[complete.cases(res), ]
p313_M <- nrow(res)
p313_bias <- 100 * (mean(res[, "N"] / res[, "Nt"]) - 1)
p313_truecv <- sd(res[, "N"]) / mean(res[, "N"])
p313_mcv_sp <- mean(res[, "se_sp"] / res[, "N"])
p313_mcv_tot <- mean(res[, "se_tot"] / res[, "N"])
p313_cov_naive <- mean(abs(res[, "N"] - res[, "Nt"]) <= 1.96 * res[, "se_sp"])
p313_cov_prop <- mean(abs(res[, "N"] - res[, "Nt"]) <= 1.96 * res[, "se_tot"])
data.frame(replicates = p313_M,
           rel_bias_pct = p313_bias,
           cv_actual = p313_truecv,
           cv_spatial_only = p313_mcv_sp,
           cv_propagated = p313_mcv_tot,
           cover_spatial_only = p313_cov_naive,
           cover_propagated = p313_cov_prop)

## ---- fig-coverage ----
vc <- data.frame(part = c("spatial model", "detection function"),
                 v = c(p313_vsp, p313_vdet))
vc$part <- factor(vc$part, levels = c("detection function", "spatial model"))
pA <- ggplot(vc, aes(x = "total", y = v, fill = part)) +
  geom_col(width = 0.5) +
  scale_fill_manual(values = c("spatial model" = "#275139",
                               "detection function" = "#c9b458")) +
  labs(title = "Where the variance comes from", x = NULL, y = "variance of N") +
  theme_te() + theme(legend.position = "top", legend.title = element_blank(),
                     panel.grid.major.y = element_line(colour = "#dad9ca", linewidth = 0.3))
cv <- data.frame(what = c("spatial only", "propagated"),
                 cover = c(p313_cov_naive, p313_cov_prop))
cv$what <- factor(cv$what, levels = c("spatial only", "propagated"))
pB <- ggplot(cv, aes(what, cover, fill = what)) +
  geom_col(width = 0.55) +
  geom_hline(yintercept = 0.95, linetype = "dashed", colour = "#b5534e", linewidth = 0.5) +
  scale_fill_manual(values = c("spatial only" = "#c9b458", "propagated" = "#275139"),
                    guide = "none") +
  scale_y_continuous(limits = c(0, 1)) +
  labs(title = "Coverage of a nominal 95% interval", x = NULL, y = "measured coverage") +
  theme_te() + theme(panel.grid.major.y = element_line(colour = "#dad9ca", linewidth = 0.3))
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
