# Covariates in the detection function
# https://tidyecology.com/posts/covariates-in-the-detection-function/
#
# 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))

## half-normal detection function and its effective strip half-width
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)   # integral of g from 0 to w

## log density of an observed distance, written out rather than as log(g/mu):
## g underflows to zero in the tail and log(0) would stop every integral below
ld_hn <- function(x, s, w) -x^2/(2*s^2) - log(mu_hn(s, w))

## hazard-rate key, for later
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

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- world ----
w   <- 0.1                    # truncation distance, km
L   <- c(open = 50, dense = 50)  # transect length per stratum, km
D   <- c(open = 30, dense = 60)  # TRUE density, groups per km2
sig <- c(open = 0.060, dense = 0.025)
area  <- 2*w*L                # covered area per stratum, km2
Ntrue <- D*area               # animals in the covered strip
mu    <- mu_hn(sig, w)        # vectorised over sigma. Writing this as
                              # c(open = mu_hn(sig["open"], w)) names the element
                              # "open.open", and mu["open"] then silently misses
Pdet  <- mu/w                 # probability of detecting an animal in the strip
En    <- 2*D*L*mu             # expected detections
data.frame(sigma = sig, mu = round(mu, 5), P_detect = round(Pdet, 4),
           N_in_strip = Ntrue, E_detections = round(En, 1))

## ---- naive-ratio ----
sprintf("naive encounter-rate ratio dense/open: %.4f   (truth: %.1f)",
        En["dense"]/En["open"], D["dense"]/D["open"])

## ---- pooled-exact ----
## true pooled density of observed distances: a mixture weighted by expected detections
wt   <- En/sum(En)
fmix <- function(x) wt["open"]*g_hn(x, sig["open"])/mu["open"] +
                    wt["dense"]*g_hn(x, sig["dense"])/mu["dense"]

## route 1: match the truncated second moment
m2_hn <- function(s, w) s^2*(1 - w*g_hn(w, s)/mu_hn(s, w))
m2_true <- integrate(function(x) x^2*fmix(x), 0, w)$value
sig_star_mom <- uniroot(function(s) m2_hn(s, w) - m2_true, c(0.005, 0.5), tol = 1e-12)$root

## route 2: minimise the KL divergence directly
kl <- function(s) -integrate(function(x) fmix(x)*ld_hn(x, s, w), 0, w)$value
sig_star_kl <- optimise(kl, c(0.005, 0.3), tol = 1e-12)$minimum

sprintf("pooled sigma*: moment identity %.7f | direct KL %.7f | difference %.2e",
        sig_star_mom, sig_star_kl, sig_star_mom - sig_star_kl)

## ---- pooled-consequences ----
mu_star <- mu_hn(sig_star_mom, w)
D_pool_total   <- sum(En)/(2*sum(L)*mu_star)
D_pool_stratum <- En/(2*L*mu_star)

data.frame(stratum = names(D),
           D_true = as.numeric(D),
           D_pooled = round(as.numeric(D_pool_stratum), 2),
           error_pct = round(100*(D_pool_stratum/D - 1), 1))
sprintf("TOTAL: true %.2f | pooled %.2f (%+.2f%%)", sum(Ntrue)/sum(area),
        D_pool_total, 100*(D_pool_total/(sum(Ntrue)/sum(area)) - 1))
sprintf("STRATUM RATIO: true %.2f | pooled %.4f (%+.1f%%)",
        D["dense"]/D["open"], D_pool_stratum["dense"]/D_pool_stratum["open"],
        100*((D_pool_stratum["dense"]/D_pool_stratum["open"])/(D["dense"]/D["open"]) - 1))

## ---- hazard-pooled ----
kl_hr <- function(p) {
  s <- exp(p[1]); b <- exp(p[2])
  v <- try(-integrate(function(x) fmix(x)*log(g_hr(x, s, b)/mu_hr(s, b, w)),
                      1e-6, w)$value, silent = TRUE)
  if (inherits(v, "try-error") || !is.finite(v)) 1e10 else v
}
o <- optim(c(log(0.04), log(2.5)), kl_hr, method = "Nelder-Mead",
           control = list(reltol = 1e-12))
o <- optim(o$par, kl_hr, method = "Nelder-Mead", control = list(reltol = 1e-12))
mu_hr_star <- mu_hr(exp(o$par[1]), exp(o$par[2]), w)
sprintf("hazard-rate pooled: total D %.2f (%+.2f%%) | ratio still %.4f",
        sum(En)/(2*sum(L)*mu_hr_star),
        100*(sum(En)/(2*sum(L)*mu_hr_star)/(sum(Ntrue)/sum(area)) - 1),
        En["dense"]/En["open"])

## ---- mcds-exact ----
## exact: does the covariate model recover the truth as the sample grows?
z <- c(open = 0, dense = 1)
nll_pop <- function(p) {           # expected negative log-likelihood under the truth
  s <- exp(p[1] + p[2]*z)
  -sum(sapply(names(z), function(k)
    En[k]*integrate(function(x) (g_hn(x, sig[k])/mu[k])*ld_hn(x, s[k], w), 0, w)$value))
}
om <- optim(c(log(0.05), -0.5), nll_pop, method = "Nelder-Mead", control = list(reltol = 1e-14))
om <- optim(om$par, nll_pop, method = "Nelder-Mead", control = list(reltol = 1e-14))
s_hat <- exp(om$par[1] + om$par[2]*z)
D_mcds <- En/(2*L*mu_hn(s_hat, w))
sprintf("recovered sigma: open %.6f (true %.3f) | dense %.6f (true %.3f)",
        s_hat["open"], sig["open"], s_hat["dense"], sig["dense"])
sprintf("recovered D: open %.4f | dense %.4f | ratio %.6f", D_mcds["open"], D_mcds["dense"],
        D_mcds["dense"]/D_mcds["open"])

## ---- worked ----
set.seed(4280)
sim <- function(seed = NULL) {
  if (!is.null(seed)) set.seed(seed)
  do.call(rbind, lapply(names(D), function(k) {
    x <- runif(Ntrue[k], 0, w)
    x <- x[runif(Ntrue[k]) < g_hn(x, sig[k])]
    data.frame(x = x, stratum = k, z = unname(z[k]))
  }))
}
d <- sim()
table(d$stratum)

## pooled fit
nll_pool <- function(p, x) -sum(ld_hn(x, exp(p), w))
fp <- optimise(function(p) nll_pool(p, d$x), c(-6, 0), tol = 1e-10)
sig_p <- exp(fp$minimum)

## covariate fit
nll_cov <- function(p, x, z) {
  s <- exp(p[1] + p[2]*z)
  -sum(-x^2/(2*s^2) - log(mu_hn(s, w)))
}
fc <- optim(c(log(0.04), -0.5), nll_cov, x = d$x, z = d$z, method = "Nelder-Mead")
stopifnot(fc$convergence == 0)   # check before inverting the Hessian
fc <- optim(fc$par, nll_cov, x = d$x, z = d$z, method = "Nelder-Mead", hessian = TRUE)
se_a1 <- sqrt(diag(solve(fc$hessian)))[2]

n_k <- table(d$stratum)[names(D)]
Dp  <- n_k/(2*L*mu_hn(sig_p, w))
sc  <- exp(fc$par[1] + fc$par[2]*z)
Dc  <- n_k/(2*L*mu_hn(sc, w))
dAIC <- (2*fp$objective + 2) - (2*fc$value + 4)
sprintf("n = %d open, %d dense | pooled sigma %.5f -> total D %.2f | ratio %.3f",
        n_k["open"], n_k["dense"], sig_p, sum(n_k)/(2*sum(L)*mu_hn(sig_p, w)),
        Dp["dense"]/Dp["open"])
sprintf("covariate alpha1 %.3f (SE %.3f) -> total D %.2f | ratio %.3f | dAIC %.1f",
        fc$par[2], se_a1, sum(Dc*area)/sum(area), Dc["dense"]/Dc["open"], dAIC)

## ---- fig-curves ----
ink <- "#16241d"; forest <- "#275139"; gold <- "#c9b458"; rust <- "#b5534e"
xs <- seq(0, w, length.out = 400)
p1 <- ggplot(data.frame(
    x = rep(xs, 3),
    g = c(g_hn(xs, sig["open"]), g_hn(xs, sig["dense"]), g_hn(xs, sig_star_mom)),
    k = rep(c("open (true)", "dense (true)", "pooled fit"), each = length(xs))),
  aes(x*1000, g, colour = k, linetype = k)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c("open (true)" = forest, "dense (true)" = rust,
                                 "pooled fit" = gold)) +
  scale_linetype_manual(values = c("open (true)" = 1, "dense (true)" = 1, "pooled fit" = 2)) +
  labs(x = "perpendicular distance (m)", y = "detection probability",
       colour = NULL, linetype = NULL, title = "One curve for two truths") +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"))

dd <- rbind(data.frame(x = xs, f = g_hn(xs, sc["open"])/mu_hn(sc["open"], w), k = "open"),
            data.frame(x = xs, f = g_hn(xs, sc["dense"])/mu_hn(sc["dense"], w), k = "dense"))
dp <- data.frame(x = xs, f = g_hn(xs, sig_p)/mu_hn(sig_p, w))
p2 <- ggplot(d, aes(x*1000)) +
  geom_histogram(aes(y = after_stat(density), fill = stratum), bins = 20,
                 position = "identity", alpha = 0.45) +
  geom_line(data = dd, aes(x*1000, f/1000, colour = k), linewidth = 0.8) +
  geom_line(data = dp, aes(x*1000, f/1000), colour = gold, linetype = 2, linewidth = 0.9) +
  scale_fill_manual(values = c(open = forest, dense = rust)) +
  scale_colour_manual(values = c(open = forest, dense = rust), guide = "none") +
  labs(x = "perpendicular distance (m)", y = "density", fill = NULL,
       title = "One survey, two histograms",
       subtitle = "dashed gold: the pooled fit") +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"),
        plot.subtitle = element_text(colour = gold, 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))

## ---- mc ----
M <- 400
res <- t(sapply(1:M, function(i) {
  d <- sim(52800 + i)
  n_k <- table(factor(d$stratum, levels = names(D)))
  fp <- optimise(function(p) nll_pool(p, d$x), c(-6, 0), tol = 1e-10)
  fc <- optim(c(log(0.04), -0.5), nll_cov, x = d$x, z = d$z, method = "Nelder-Mead")
  fc <- optim(fc$par, nll_cov, x = d$x, z = d$z, method = "Nelder-Mead")
  mp <- mu_hn(exp(fp$minimum), w)
  sc <- exp(fc$par[1] + fc$par[2]*z)
  Dp <- n_k/(2*L*mp); Dc <- n_k/(2*L*mu_hn(sc, w))
  c(Dp_tot = sum(n_k)/(2*sum(L)*mp), Dc_tot = sum(Dc*area)/sum(area),
    Rp = Dp[2]/Dp[1], Rc = Dc[2]/Dc[1],
    dAIC = (2*fp$objective + 2) - (2*fc$value + 4))
}))
Dtot <- sum(Ntrue)/sum(area)
sprintf("total density (truth %.1f): pooled %.2f (SD %.2f, %+.1f%%) | covariate %.2f (SD %.2f, %+.1f%%)",
        Dtot, mean(res[, "Dp_tot"]), sd(res[, "Dp_tot"]), 100*(mean(res[, "Dp_tot"])/Dtot - 1),
        mean(res[, "Dc_tot"]), sd(res[, "Dc_tot"]), 100*(mean(res[, "Dc_tot"])/Dtot - 1))
sprintf("stratum ratio (truth 2.00): pooled %.3f (SD %.3f) | covariate %.3f (SD %.3f)",
        mean(res[, "Rp.dense"]), sd(res[, "Rp.dense"]),
        mean(res[, "Rc.dense"]), sd(res[, "Rc.dense"]))
sprintf("pooled analysis calls the dense stratum denser in %.1f%% of surveys; dAIC > 2 in %.1f%%",
        100*mean(res[, "Rp.dense"] > 1), 100*mean(res[, "dAIC"] > 2))

## ---- fig-mc ----
mc <- rbind(data.frame(v = res[, "Dp_tot"], m = "pooled", panel = "total density"),
            data.frame(v = res[, "Dc_tot"], m = "covariate", panel = "total density"),
            data.frame(v = res[, "Rp.dense"], m = "pooled", panel = "stratum ratio"),
            data.frame(v = res[, "Rc.dense"], m = "covariate", panel = "stratum ratio"))
mk <- function(pn, tv, xl) ggplot(mc[mc$panel == pn, ], aes(v, fill = m)) +
  geom_histogram(bins = 34, position = "identity", alpha = 0.55) +
  geom_vline(xintercept = tv, colour = ink, linetype = 2, linewidth = 0.7) +
  scale_fill_manual(values = c(pooled = gold, covariate = forest)) +
  labs(x = xl, y = "surveys", fill = NULL, title = pn,
       subtitle = sprintf("dashed: the truth (%.1f)", tv)) +
  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(mk("total density", Dtot, "animals per km2"),
      vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(mk("stratum ratio", 2, "dense / open"),
      vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
