# Distance sampling for density in R
# https://tidyecology.com/posts/distance-sampling-line-transect/
#
# 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-05-12

## ---- setup ----
library(ggplot2)

ink <- "#16241d"; body <- "#2c3a31"; forest <- "#275139"; gold <- "#c9b458"
paper <- "#f5f4ee"; line_c <- "#dad9ca"; faint <- "#5d6b61"; sage <- "#93a87f"; red <- "#b5534e"

theme_te <- function(base = 12) {
  theme_minimal(base_size = base) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = line_c, linewidth = 0.3),
          plot.background = element_rect(fill = paper, colour = NA),
          panel.background = element_rect(fill = paper, colour = NA),
          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 = faint),
          legend.title = element_text(colour = body), legend.text = element_text(colour = faint))
}

## ---- simulate ----
set.seed(6)
Dtrue <- 80; L <- 30; w <- 0.15; sig_true <- 0.06

area <- 2 * w * L                 # surveyed strip area
Ntot <- round(Dtrue * area)       # animals present in the strip
xall <- runif(Ntot, 0, w)         # perpendicular distances, uniform in the strip
det <- rbinom(Ntot, 1, exp(-xall^2 / (2 * sig_true^2)))   # detected with prob g(x)
x <- xall[det == 1]               # distances of detected animals
nobs <- length(x)
c(present = Ntot, detected = nobs)

## ---- naive ----
D_naive <- nobs / (2 * w * L)
c(D_naive = D_naive, D_true = Dtrue)

## ---- fit-halfnormal ----
mu_hn <- function(s) s * sqrt(2 * pi) * (pnorm(w / s) - 0.5)   # integral of g over [0, w]
nll_hn <- function(ls) {
  s <- exp(ls)
  -sum(-x^2 / (2 * s^2) - log(mu_hn(s)))   # f(x) = g(x) / mu
}
ohn <- optim(log(0.05), nll_hn, method = "BFGS", hessian = TRUE)
sig <- exp(ohn$par); mu <- mu_hn(sig)
Phat <- mu / w
c(sigma_hat = sig, ESW = mu, detection_prob = Phat)

## ---- fig-detection-fit ----
g_hr <- function(xx, s, b) 1 - exp(-(xx / s)^(-b))          # hazard-rate detection
mu_hr <- function(s, b) integrate(function(u) g_hr(u, s, b), 0, w)$value
nll_hr <- function(par) {
  s <- exp(par[1]); b <- exp(par[2]); m <- mu_hr(s, b)
  if (!is.finite(m) || m <= 0) return(1e6)
  -sum(log(g_hr(x, s, b)) - log(m))
}
ohr <- optim(c(log(0.06), log(3)), nll_hr, method = "BFGS", hessian = TRUE)
shr <- exp(ohr$par[1]); bhr <- exp(ohr$par[2]); muhr <- mu_hr(shr, bhr)

xs <- seq(0, w, length.out = 200)
fhn <- exp(-xs^2 / (2 * sig^2)) / mu
fhr <- g_hr(xs, shr, bhr) / muhr
dfit <- data.frame(x = rep(xs, 2), f = c(fhn, fhr),
                   model = rep(c("Half-normal", "Hazard-rate"), each = length(xs)))

ggplot(data.frame(x = x), aes(x)) +
  geom_histogram(aes(y = after_stat(density)), breaks = seq(0, w, by = 0.015),
                 fill = sage, colour = paper, linewidth = 0.3) +
  geom_line(data = dfit, aes(x, f, colour = model), linewidth = 0.9) +
  scale_colour_manual(values = c("Half-normal" = forest, "Hazard-rate" = red), name = NULL) +
  labs(title = "Detected objects thin out with distance",
       subtitle = "Perpendicular-distance histogram with fitted detection functions",
       x = "Perpendicular distance (km)", y = "Probability density") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.82, 0.82))

## ---- fig-esw ----
gcurve <- data.frame(x = xs, g = exp(-xs^2 / (2 * sig^2)))
ggplot(gcurve, aes(x, g)) +
  annotate("rect", xmin = 0, xmax = mu, ymin = 0, ymax = 1, fill = gold, alpha = 0.25) +
  geom_line(colour = forest, linewidth = 0.9) +
  geom_vline(xintercept = w, linetype = "dashed", colour = faint) +
  annotate("text", x = mu, y = 0.5, label = sprintf("ESW = %.3f km", mu),
           colour = ink, hjust = -0.05, size = 3.4) +
  annotate("text", x = w, y = 0.95, label = "truncation w", colour = faint, hjust = 1.05, size = 3.2) +
  labs(title = "Effective strip half-width folds detection into an area",
       subtitle = "Fitted half-normal detection function; the shaded rectangle has the same area",
       x = "Perpendicular distance (km)", y = "Detection probability") +
  theme_te()

## ---- density ----
D_hat <- nobs / (2 * L * mu)
se_ls <- sqrt(1 / ohn$hessian[1, 1])                  # SE of log sigma
eps <- 1e-5
dlogmu <- (log(mu_hn(exp(ohn$par + eps))) - log(mu_hn(exp(ohn$par - eps)))) / (2 * eps)
cv2 <- 1 / nobs + (dlogmu * se_ls)^2                  # encounter rate plus detection function
se_D <- D_hat * sqrt(cv2)
D_ci <- D_hat + c(-1.96, 1.96) * se_D
round(c(D_hat = D_hat, se = se_D, lo = D_ci[1], hi = D_ci[2], true = Dtrue), 1)

## ---- fig-density ----
d3 <- data.frame(
  est = factor(c("Naive: assume\nperfect detection", "Distance sampling\nD-hat", "Truth"),
               levels = c("Naive: assume\nperfect detection", "Distance sampling\nD-hat", "Truth")),
  val = c(D_naive, D_hat, Dtrue), lo = c(NA, D_ci[1], NA), hi = c(NA, D_ci[2], NA),
  fill = c("naive", "model", "truth"))
ggplot(d3, aes(est, val, fill = fill)) +
  geom_col(width = 0.6) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.15, colour = ink, na.rm = TRUE) +
  geom_hline(yintercept = Dtrue, linetype = "dashed", colour = faint, linewidth = 0.4) +
  scale_fill_manual(values = c(naive = gold, model = forest, truth = sage), guide = "none") +
  labs(title = "Ignoring imperfect detection halves the density",
       subtitle = "Estimated density: naive strip count versus distance sampling",
       x = NULL, y = "Objects per square km") +
  theme_te()

## ---- aic ----
ll_hn <- -ohn$value; ll_hr <- -ohr$value
aic_hn <- -2 * ll_hn + 2 * 1
aic_hr <- -2 * ll_hr + 2 * 2
c(AIC_half_normal = aic_hn, AIC_hazard_rate = aic_hr, difference = aic_hr - aic_hn)
