# Checking a distance sampling model
# https://tidyecology.com/posts/checking-a-distance-sampling-model/
#
# 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)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

g_hn  <- function(x, s) exp(-x^2/(2*s^2))
mu_hn <- function(s, w) sqrt(2*pi)*s*(pnorm(w, 0, s) - 0.5)
ld_hn <- function(x, s, w) -x^2/(2*s^2) - log(mu_hn(s, w))
g_hr  <- function(x, s, b) 1 - exp(-(x/s)^(-b))
mu_hr <- function(s, b, w) integrate(g_hr, 0, w, s = s, b = b)$value
fit_hn <- function(x, w) exp(optimise(function(p) -sum(ld_hn(x, exp(p), w)),
                                      c(-8, 1), tol = 1e-10)$minimum)
w <- 0.1

## ---- calibrate ----
cut <- seq(0, w, length.out = 6)
pi_hn <- function(s) { P <- sqrt(2*pi)*s*(pnorm(cut[-1], 0, s) - pnorm(cut[-6], 0, s))/w
                       P/sum(P) }
gof_hn <- function(x) {
  s  <- fit_hn(x, w)
  ob <- tabulate(findInterval(x, cut, rightmost.closed = TRUE), 5)
  ex <- length(x)*pi_hn(s)
  c(p = pchisq(sum((ob - ex)^2/ex), df = 5 - 1 - 1, lower.tail = FALSE), sigma = s)
}
## a world where the half-normal is exactly right
s_ok <- 0.045; D0 <- 100; L_ok <- 266/(2*D0*mu_hn(s_ok, w))
cal <- t(sapply(1:400, function(i) {
  set.seed(61000 + i)
  N <- rpois(1, D0*2*w*L_ok); x <- runif(N, 0, w)
  gof_hn(x[runif(N) < g_hn(x, s_ok)])
}))
sprintf("model-true data, n approx 266: test rejects at 0.05 in %.1f%% of surveys | median p %.3f",
        100*mean(cal[, "p"] < 0.05), median(cal[, "p"]))

## ---- blind ----
s_hr <- 0.05; b_hr <- 3
mu_t <- mu_hr(s_hr, b_hr, w); Ln <- 266/(2*D0*mu_t)
res <- t(sapply(1:400, function(i) {
  set.seed(63000 + i)
  N <- rpois(1, D0*2*w*Ln); x <- runif(N, 0, w)
  x <- x[runif(N) < g_hr(x, s_hr, b_hr)]
  g <- gof_hn(x)
  c(p = g["p"], bias = length(x)/(2*Ln*mu_hn(g["sigma"], w))/D0 - 1, n = length(x))
}))
acc <- res[res[, 1] > 0.05, ]
sprintf("half-normal fitted to hazard-rate data (n approx %.0f, 5 bins, df 3):", mean(res[, 3]))
sprintf("  rejects at 0.05: %.1f%% of surveys | median p-value %.3f | mean density bias %+.1f%%",
        100*mean(res[, 1] < 0.05), median(res[, 1]), 100*mean(res[, 2]))
sprintf("  among the surveys the test ACCEPTS: mean bias %+.1f%%, worst %+.1f%%",
        100*mean(acc[, 2]), 100*max(acc[, 2]))
sprintf("  correlation between the p-value and |bias|: %.3f", cor(res[, 1], abs(res[, 2])))

## ---- fig-blind ----
ink <- "#16241d"; forest <- "#275139"; gold <- "#c9b458"; rust <- "#b5534e"
dd <- data.frame(p = res[, 1], bias = 100*res[, 2],
                 k = ifelse(res[, 1] > 0.05, "test accepts", "test rejects"))
p1 <- ggplot(dd, aes(p, bias, colour = k)) +
  geom_hline(yintercept = 0, colour = ink, linetype = 2) +
  geom_vline(xintercept = 0.05, colour = rust, linetype = 3) +
  geom_point(size = 1, alpha = 0.7) +
  scale_colour_manual(values = c("test accepts" = forest, "test rejects" = rust)) +
  labs(x = "goodness-of-fit p-value", y = "density error (%)", colour = NULL,
       title = "No relationship at all",
       subtitle = sprintf("correlation of p with |error|: %.3f", cor(res[, 1], abs(res[, 2])))) +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"),
        plot.subtitle = element_text(size = 8))
p2 <- ggplot(dd[dd$k == "test accepts", ], aes(bias)) +
  geom_histogram(bins = 30, fill = forest, alpha = 0.6) +
  geom_vline(xintercept = 0, colour = ink, linetype = 2, linewidth = 0.7) +
  labs(x = "density error (%)", y = "surveys",
       title = "The surveys that passed",
       subtitle = sprintf("mean error %+.1f%%, only %.0f%% within 2%% of the truth",
                          100*mean(acc[, 2]), 100*mean(abs(acc[, 2]) < 0.02))) +
  theme_minimal(base_size = 10) + te_canvas +
  theme(plot.title = element_text(colour = ink, face = "bold"),
        plot.subtitle = element_text(size = 8))
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p1, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- g0 ----
set.seed(4283)
s_t <- 0.05; L <- 30; Dtrue <- 60
N <- rpois(1, Dtrue*2*w*L); xa <- runif(N, 0, w)
x <- xa[runif(N) < g_hn(xa, s_t)]
base <- optimise(function(p) -sum(ld_hn(x, exp(p), w)), c(-8, 1), tol = 1e-12)
out <- t(sapply(c(1, 0.8, 0.6, 0.4), function(g0) {
  ## the world where only a fraction g0 of the animals on the line are seen
  nll <- function(p) { s <- exp(p)
    -sum(log(g0*g_hn(x, s)) - log(g0*mu_hn(s, w))) }
  o <- optimise(nll, c(-8, 1), tol = 1e-12)
  c(g0 = g0, sigma = exp(o$minimum), d_sigma = exp(o$minimum) - exp(base$minimum),
    loglik = -o$objective, d_loglik = -o$objective + base$objective,
    D = length(x)/(2*L*mu_hn(exp(o$minimum), w)*g0))
}))
sprintf("one survey, n = %d detections", length(x))
print(round(out, 8))

## ---- fig-g0 ----
xs <- seq(0, w, length.out = 300)
cur <- do.call(rbind, lapply(c(1, 0.8, 0.6, 0.4), function(g0)
  data.frame(x = xs, g = g0*g_hn(xs, s_t), k = sprintf("g(0) = %.1f", g0))))
p1 <- ggplot(cur, aes(x*1000, g, colour = k)) +
  geom_line(linewidth = 0.9) +
  geom_line(data = data.frame(x = xs, g = g_hn(xs, s_t)/mu_hn(s_t, w)/20.2, k = "observed f(x)"),
            colour = ink, linetype = 2, linewidth = 1) +
  scale_colour_manual(values = c("g(0) = 1.0" = forest, "g(0) = 0.8" = gold,
                                 "g(0) = 0.6" = rust, "g(0) = 0.4" = "#93a87f")) +
  labs(x = "perpendicular distance (m)", y = "detection probability", colour = NULL,
       title = "Four worlds, one dataset",
       subtitle = "dashed: the distances you record, scaled; identical in all four") +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"),
        plot.subtitle = element_text(size = 8), legend.text = element_text(size = 7))
sc <- data.frame(g0 = rep(out[, "g0"], 3),
                 v = c(out[, "sigma"]/out[1, "sigma"], out[, "loglik"]/out[1, "loglik"],
                       out[, "D"]/out[1, "D"]),
                 k = rep(c("fitted sigma", "log-likelihood", "estimated density"), each = 4))
p2 <- ggplot(sc, aes(g0, v, colour = k)) +
  geom_hline(yintercept = 1, colour = ink, linetype = 3) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_colour_manual(values = c("fitted sigma" = forest, "log-likelihood" = gold,
                                 "estimated density" = rust)) +
  scale_x_reverse() +
  labs(x = "true g(0)", y = "relative to the g(0) = 1 analysis", colour = NULL,
       title = "Everything you can check is flat",
       subtitle = "the one thing you report is not") +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"),
        plot.subtitle = element_text(size = 8))
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(p1, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- tail-fitter ----
## g = key x (1 + cosines); centred cosines give, for fixed sigma, a concave log-likelihood
tr_fitk <- function(x, tw, k) {                    # k cosine terms, orders 2 to k + 1
  cosm <- function(z) outer(z, seq_len(k) + 1, function(z, j) cos(j*pi*z/tw))
  xq <- (1:1000 - 0.5)*tw/1000; xm <- seq(0, tw, length.out = 20)  # quadrature, monotonicity
  Cq <- cosm(xq); Cx <- cosm(x); Cm <- cosm(xm)
  prof <- function(s) {                            # sigma fixed: best coefficients
    kq <- g_hn(xq, s); m0 <- mean(kq)*tw; ll0 <- -sum(x^2)/(2*s^2) - length(x)*log(m0)
    if (k == 0) return(list(ll = ll0, f0 = 1/m0, ok = TRUE))
    cbar <- colMeans(kq*Cq)*tw/m0; E <- sweep(Cx, 2, cbar); M <- sweep(Cm, 2, cbar)
    r <- exp(-diff(xm^2)/(2*s^2))                  # constraints: g falls, g(tw) >= 0
    A <- rbind(M[-20, , drop = FALSE] - r*M[-1, , drop = FALSE], M[20, ]); b <- c(r - 1, -1)
    cf <- rep(0, k); u <- rep(1, length(x)); ok <- FALSE
    for (it in 1:80) {                             # Newton steps under the constraints
      Eu <- E/u
      grad <- colSums(Eu)
      H <- crossprod(Eu) + diag(1e-10*max(1, Eu^2), k)
      move <- tryCatch(quadprog::solve.QP(H, grad, t(A), pmin(b - drop(A %*% cf), 0))$solution,
                       error = function(e) NULL)
      ok <- !is.null(move) && sum(grad*move) < 1e-9   # converged
      if (is.null(move) || ok) break
      a <- 1
      repeat {                                     # halve the step until the fit improves
        un <- 1 + drop(E %*% (cf + a*move))
        if (all(un > 0) && sum(log(un)) >= sum(log(u)) + 1e-4*a*sum(grad*move)) break
        a <- a/2
        if (a < 1e-12) break }
      ok <- a < 1e-12 && sum(grad*move) < 1e-6
      if (a < 1e-12) break                         # no step improves the fit: stop
      cf <- cf + a*move
      u <- un }
    list(ll = ll0 + sum(log(u)), f0 = (1 + sum((1 - cbar)*cf))/m0, ok = ok) }
  lg <- log(tw) + seq(log(1/200), log(20), length.out = 30)  # sigma: grid, then optimise
  pl <- sapply(lg, function(l) prof(exp(l))$ll); i <- which.max(pl)
  o <- optimise(function(l) -prof(exp(l))$ll, lg[c(max(1, i - 1), min(30, i + 1))])
  f <- prof(exp(if (-o$objective > pl[i]) o$minimum else lg[i]))
  c(f, aic = -2*f$ll + 2*(k + 1)) }
tr_ds <- function(x, tw, all_k = FALSE) {          # forward AIC: stop at the first worse model
  x <- x[x <= tw]; fits <- list(tr_fitk(x, tw, 0)); k <- NA   # k: the selected model
  for (j in 1:5) {                   # all_k = TRUE: fit every k anyway (b = 2.2 only)
    if (!is.na(k) && !all_k) break
    fits[[j + 1]] <- tr_fitk(x, tw, j)
    if (is.na(k) && (!fits[[j + 1]]$ok || fits[[j + 1]]$aic > fits[[j]]$aic)) k <- j - 1 }
  if (is.na(k)) k <- 5
  nf0 <- length(x)*sapply(fits, `[[`, "f0"); list(k = k, nf0 = nf0[k + 1], nf0_k = nf0) }

## ---- tail-sim ----
tr_g <- list(`half-normal` = function(x) g_hn(x, s_hr),
             `hazard-rate, b = 3` = function(x) g_hr(x, s_hr, b_hr),
             `hazard-rate, b = 2.2` = function(x) g_hr(x, s_hr, 2.2))
tr_W <- 1; tr_L <- sapply(tr_g, function(g) 266/(2*D0*integrate(g, 0, tr_W)$value))
tr_res <- do.call(rbind, lapply(1:3, function(j) t(sapply(1:120, function(i) {
  set.seed(96000 + 1000*j + i)
  N <- rpois(1, D0*2*tr_W*tr_L[j]); xa <- runif(N, 0, tr_W); x <- xa[runif(N) < tr_g[[j]](xa)]
  fm <- tr_ds(x, max(x), all_k = j == 3)           # ds() default: the largest distance
  fq <- tr_ds(x, unname(quantile(x, 0.9)))         # the farthest 10 per cent cut
  rbk <- fm$nf0_k; length(rbk) <- 6; rb <- c(fm$nf0, fq$nf0, rbk)/(2*tr_L[[j]]*D0) - 1
  c(j = j, w = max(x), k_max = fm$k, k_cut = fq$k,
    rb_max = rb[1], rb_cut = rb[2], rbk = rb[-(1:2)]) }))))
tr_cell <- function(j, h) { v <- tr_res[tr_res[, "j"] == j, ]; rb <- v[, paste0("rb_", h)]
  c(bias = mean(rb), mcse = sd(rb)/sqrt(120), median = median(rb),
    cv = sd(1 + rb)/mean(1 + rb), five_terms = mean(v[, paste0("k_", h)] == 5)) }
tr_sum <- expand.grid(w = c("max", "cut"), truth = names(tr_g), stringsAsFactors = FALSE)
tr_sum <- cbind(tr_sum, t(mapply(tr_cell, match(tr_sum$truth, names(tr_g)), tr_sum$w)))
print(tr_sum, digits = 2)
tr_shift <- tr_res[tr_res[, "j"] == 2, "rb_cut"] - tr_res[tr_res[, "j"] == 2, "rb_max"]
tr_km <- tr_res[tr_res[, "j"] == 3, paste0("rbk", 1:6)]; tr_k <- colMeans(tr_km)
cat("b = 2.2 at the largest distance, FIXED k = 0 to 5:", sprintf("%+.3f", tr_k),
    sprintf("(MC SE at most %.3f)\n", max(apply(tr_km, 2, sd))/sqrt(120)))

## ---- tail-range ----
tr_rw <- data.frame(t(mapply(function(W, i) {      # hazard-rate b = 2.2, animals out to W km
  set.seed(91000 + 1000*W + i)
  L <- 266/(2*D0*integrate(tr_g[[3]], 0, W)$value)
  xa <- runif(rpois(1, D0*2*W*L), 0, W)
  x <- xa[runif(length(xa)) < tr_g[[3]](xa)]
  f <- lapply(c(max(x), unname(quantile(x, 0.9))), tr_ds, x = x)  # largest distance, 10% cut
  c(W = W, cap = f[[1]]$k == 5, rb = sapply(f, `[[`, "nf0")/(2*L*D0) - 1) },  # rb1, rb2
  rep(c(0.5, 2), each = 60), 1:60)))
print(aggregate(. ~ W, tr_rw, function(v) c(mean = mean(v), se = sd(v)/sqrt(60))), digits = 2)
tr_step <- diff(t(tr_km))                          # fixed k: paired steps, k to k + 1
cat(sprintf("steps in k: largest paired SE %.3f\n", max(apply(tr_step, 1, sd))/sqrt(120)))

## ---- checklist ----
knitr::kable(data.frame(
  Assumption = c("Key function has the right shape", "No long tail left in the fitted range",
                 "Distances measured accurately",
                 "No heaping on round numbers", "Detection depends on the recorded covariates",
                 "Animals uniform with respect to the line", "g(0) = 1",
                 "Animals do not move before detection"),
  `Can the distances check it` = c("Weakly", "Partly", "Partly", "Yes", "Partly", "No", "No", "No"),
  `What settles it` = c("Goodness of fit, AIC, shouldered key by default",
                        "The histogram, then cutting the farthest 5 to 10 per cent and reporting the cut, which can add bias of its own",
                        "Repeat measurement of a subset, the input of an [error-aware fit](../point-transect-distance-sampling/#distances-estimated-with-error)",
                        "The histogram, and a rangefinder",
                        "AIC, once the covariate is recorded",
                        "Random placement of the design",
                        "Double observer or mark-recapture distance sampling",
                        "Snapshot protocol, or a faster observer"),
  check.names = FALSE))

## ---- double-observer ----
set.seed(90210)
do_g0 <- 0.8; do_s <- 0.05; do_N <- 1200; do_reps <- 150
do_grid <- seq(0, w, length.out = 400)

## match the two worlds on the spread of each animal's own detection probability
do_cv <- function(cc, ss) { p <- cc*mu_hn(ss, w)/w; sd(p)/mean(p) }
do_u   <- rnorm(2e5)
do_a0  <- uniroot(function(a) mean(plogis(a + 2*do_u)) - do_g0, c(-20, 20))$root
do_cvl <- do_cv(plogis(do_a0 + 2*do_u), do_s)
do_ts  <- uniroot(function(t) do_cv(do_g0, do_s*exp(t*do_u - t^2/2)) - do_cvl, c(0.01, 3))$root

do_sim <- function(at_line) {
  xx <- runif(do_N, 0, w)
  cc <- if (at_line) plogis(do_a0 + 2*rnorm(do_N)) else rep(do_g0, do_N)
  ss <- if (at_line) do_s else do_s*exp(do_ts*rnorm(do_N) - do_ts^2/2)
  p  <- cc*g_hn(xx, ss)              # one animal, one detectability, offered to both
  a  <- runif(do_N) < p; b <- runif(do_N) < p; k <- a | b
  list(x = xx[k], a = a[k], b = b[k])
}
do_key  <- function(xx, q) g_hn(xx, exp(q[1]))*(1 + q[2]*cos(pi*xx/w))/(1 + q[2])
do_fitk <- function(xx) {
  nk <- function(q) { gg <- do_key(do_grid, q); if (any(gg <= 0)) return(1e9)
    -(sum(log(pmax(do_key(xx, q), 1e-12))) - length(xx)*log(mean(gg)*w)) }
  o <- optim(c(log(do_s), 0.1), nk); optim(o$par, nk)$par
}
do_cds <- function(xx) length(xx)*w/mu_hn(fit_hn(xx, w), w)     # one observer, g(0) = 1
do_full <- function(d) {                                        # MRDS, full independence
  nll <- function(q) { th <- plogis(q[1]); s <- exp(q[2]); p <- th*g_hn(d$x, s)
    Pd <- (2*th*mu_hn(s, w) - th^2*mu_hn(s/sqrt(2), w))/w
    -(sum(ifelse(d$a & d$b, 2*log(p), log(p) + log1p(-p))) - length(d$x)*log(Pd)) }
  o <- optim(c(1, log(do_s)), nll); o <- optim(o$par, nll)
  sum(1/(1 - (1 - plogis(o$par[1])*g_hn(d$x, exp(o$par[2])))^2))
}
do_p0 <- function(d) {                    # height, from the mark-recapture model at zero
  xr <- c(d$x[d$a], d$x[d$b]); yr <- c(d$b[d$a], d$a[d$b])
  m <- optim(c(1, -1, 0), function(bb) { e <- bb[1] + bb[2]*xr/w + bb[3]*(xr/w)^2
                                         -sum(yr*e - log1p(exp(e))) })
  1 - (1 - plogis(m$par[1]))^2
}
do_point <- function(d, adjust) {                 # MRDS, point independence
  pd0 <- do_p0(d)
  if (adjust) { q <- do_fitk(d$x); gg <- do_key(d$x, q)/do_key(0, q) }
  else gg <- g_hn(d$x, fit_hn(d$x, w))
  sum(1/(pd0*gg))
}
do_run <- function(at_line) t(replicate(do_reps, { d <- do_sim(at_line)
  c(conv = do_cds(d$x[d$a])/do_N, full = do_full(d)/do_N,
    point = do_point(d, TRUE)/do_N, bare = do_point(d, FALSE)/do_N) }))
do_L <- colMeans(do_run(TRUE)); do_S <- colMeans(do_run(FALSE))
do_rec <- function(v, k) unname((v[k] - v["conv"])/(1 - v["conv"]))
do_rec_line_full   <- do_rec(do_L, "full");  do_rec_line_point  <- do_rec(do_L, "point")
do_rec_shape_full  <- do_rec(do_S, "full");  do_rec_shape_point <- do_rec(do_S, "point")
do_rec_line_bare   <- do_rec(do_L, "bare");  do_rec_shape_bare  <- do_rec(do_S, "bare")

## pooling robustness on its own terms: g(0) = 1 genuinely true, same spread of scale
do_pool <- function(adjust) mean(replicate(do_reps, {
  xx <- runif(do_N, 0, w); ss <- do_s*exp(do_ts*rnorm(do_N) - do_ts^2/2)
  dd <- xx[runif(do_N) < g_hn(xx, ss)]
  if (adjust) { q <- do_fitk(dd); gg <- do_key(do_grid, q)/do_key(0, q)
                length(dd)/(mean(gg)*w)*w/do_N } else do_cds(dd)/do_N }))
do_pool_bare <- do_pool(FALSE); do_pool_adj <- do_pool(TRUE)

cat(sprintf("both worlds carry the same CV of individual detection probability: %.2f\n", do_cvl))
for (i in 1:2) { v <- list(do_L, do_S)[[i]]
  cat(sprintf("\n%s\n", c("heterogeneity SURVIVING at zero distance",
                          "heterogeneity that VANISHES at zero distance")[i]))
  cat(sprintf("  one observer, g(0) = 1 assumed    : N_hat/N %.3f\n", v["conv"]))
  cat(sprintf("  two observers, full independence  : N_hat/N %.3f, gap recovered %.2f\n",
              v["full"], do_rec(v, "full")))
  cat(sprintf("  two observers, point independence : N_hat/N %.3f, gap recovered %.2f\n",
              v["point"], do_rec(v, "point")))
  cat(sprintf("     the same, pooled key left bare : N_hat/N %.3f, gap recovered %.2f\n",
              v["bare"], do_rec(v, "bare"))) }
cat(sprintf("\npooling robustness alone, g(0) = 1 true: bare key %.3f, adjusted key %.3f\n",
            do_pool_bare, do_pool_adj))
