# Point transect distance sampling
# https://tidyecology.com/posts/point-transect-distance-sampling/
#
# 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-11-04

## ---- 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(r, s) exp(-r^2/(2*s^2))
mu_hn <- function(s, w) sqrt(2*pi)*s*(pnorm(w, 0, s) - 0.5)   # line:  integral of g
nu_hn <- function(s, w) s^2*(1 - g_hn(w, s))                  # point: integral of r g(r)
g_hr  <- function(r, s, b) 1 - exp(-(r/s)^(-b))
mu_hr <- function(s, b, w) integrate(g_hr, 0, w, s = s, b = b)$value
nu_hr <- function(s, b, w) integrate(function(r) r*g_hr(r, s, b), 0, w)$value

## ---- check-closed ----
s <- 0.037; w <- 0.1
c(mu_closed = mu_hn(s, w), mu_numeric = integrate(g_hn, 0, w, s = s)$value,
  nu_closed = nu_hn(s, w), nu_numeric = integrate(function(r) r*g_hn(r, s), 0, w)$value)

## ---- geometry ----
w <- 0.1; K <- 200; D <- 100; s0 <- 0.04
nu0 <- nu_hn(s0, w)
Pa  <- 2*nu0/w^2                 # probability an animal in the circle is detected
EDR <- sqrt(2*nu0)               # effective detection radius
En  <- D*K*2*pi*nu0
fpt <- function(r, s, w) r*g_hn(r, s)/nu_hn(s, w)
sprintf("nu %.7f | P_detect %.4f |  EDR %.5f km | E[N in circles] %.1f | E[n detected] %.1f",
        nu0, Pa, EDR, D*K*pi*w^2, En)
sprintf("f(0) = %.4f | mode of f at r = %.5f (sigma = %.3f)",
        fpt(0, s0, w), optimise(function(r) -fpt(r, s0, w), c(0, w))$minimum, s0)

## ---- naive-plot ----
sprintf("plot count D = n/(K pi w^2): %.2f (%+.1f%%)", D*Pa, 100*(Pa - 1))

## ---- naive-weight ----
## exact: what does the half-normal converge to if the r weighting is dropped?
m2_line  <- function(s, w) s^2*(1 - w*g_hn(w, s)/mu_hn(s, w))
m2_point <- function(s, w) 2*s^4*(1 - (1 + w^2/(2*s^2))*g_hn(w, s))/nu_hn(s, w)
m2_true  <- m2_point(s0, w)
s_naive  <- uniroot(function(s) m2_line(s, w) - m2_true, c(0.005, 0.5), tol = 1e-12)$root
sprintf("E[r^2] = %.7f -> sigma_hat %.5f (true %.3f, %+.1f%%) -> D %.2f (%+.1f%%)",
        m2_true, s_naive, s0, 100*(s_naive/s0 - 1),
        D*nu0/nu_hn(s_naive, w), 100*(nu0/nu_hn(s_naive, w) - 1))
## the untruncated version of the same mistake is exactly a factor of two
sprintf("untruncated: E[r^2]/(2 sigma^2) = %.4f, so sigma_hat = sigma*sqrt(2), nu_hat = 2 nu, D halves",
        m2_point(s0, 10)/(2*s0^2))

## ---- identities ----
h <- 1e-6
fl <- function(x, s, w) g_hn(x, s)/mu_hn(s, w)
sprintf("LINE  f(0) = %.6f vs 1/mu = %.6f (difference %.1e)",
        fl(0, s0, w), 1/mu_hn(s0, w), fl(0, s0, w) - 1/mu_hn(s0, w))
sprintf("POINT f'(0) = %.6f vs 1/nu = %.6f (difference %.1e, numeric derivative)",
        (fpt(h, s0, w) - fpt(0, s0, w))/h, 1/nu0,
        (fpt(h, s0, w) - fpt(0, s0, w))/h - 1/nu0)

## ---- sparse ----
set.seed(4281)
N <- rpois(1, D*K*pi*w^2)
r_all <- sqrt(runif(N))*w                    # uniform on the disc: r = w*sqrt(U)
r <- r_all[runif(N) < g_hn(r_all, s0)]
sprintf("n = %d | inside 0.5 sigma: %d (%.1f%%) | inside sigma: %d (%.1f%%)",
        length(r), sum(r < 0.5*s0), 100*mean(r < 0.5*s0), sum(r < s0), 100*mean(r < s0))

## ---- worked ----
ld_pt <- function(r, s, w) log(r) - r^2/(2*s^2) - log(nu_hn(s, w))
ld_ln <- function(x, s, w) -x^2/(2*s^2) - log(mu_hn(s, w))
fit_pt <- function(r, w) exp(optimise(function(p) -sum(ld_pt(r, exp(p), w)),
                                      c(-8, 1), tol = 1e-10)$minimum)
fit_ln <- function(x, w) exp(optimise(function(p) -sum(ld_ln(x, exp(p), w)),
                                      c(-8, 1), tol = 1e-10)$minimum)
s_hat  <- fit_pt(r, w); nu_hat <- nu_hn(s_hat, w)
s_wrong <- fit_ln(r, w)
sprintf("correct: sigma %.5f (true %.3f) -> EDR %.5f -> D %.2f (truth %g)",
        s_hat, s0, sqrt(2*nu_hat), length(r)/(2*pi*K*nu_hat), D)
sprintf("r weighting dropped: sigma %.5f -> D %.2f (%+.1f%%) | plot count %.2f (%+.1f%%)",
        s_wrong, length(r)/(2*pi*K*nu_hn(s_wrong, w)),
        100*(length(r)/(2*pi*K*nu_hn(s_wrong, w))/D - 1),
        length(r)/(K*pi*w^2), 100*(length(r)/(K*pi*w^2)/D - 1))

## ---- fig-geometry ----
ink <- "#16241d"; forest <- "#275139"; gold <- "#c9b458"; rust <- "#b5534e"
rs <- seq(0, w, length.out = 400)
p1 <- ggplot(data.frame(r = rep(rs, 2),
                        y = c(g_hn(rs, s0), fpt(rs, s0, w)/max(fpt(rs, s0, w))),
                        k = rep(c("g(r): detection probability",
                                  "f(r): distances you record"), each = length(rs))),
             aes(r*1000, y, colour = k)) +
  geom_line(linewidth = 0.9) +
  geom_vline(xintercept = s0*1000, colour = ink, linetype = 3) +
  scale_colour_manual(values = c("g(r): detection probability" = forest,
                                 "f(r): distances you record" = gold)) +
  labs(x = "distance from the point (m)", y = "scaled to a maximum of one", colour = NULL,
       title = "Area rises, detection falls",
       subtitle = "dotted: sigma, where f(r) peaks") +
  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))

fitcurves <- rbind(
  data.frame(r = rs, f = fpt(rs, s_hat, w), k = "correct fit"),
  data.frame(r = rs, f = fpt(rs, s_wrong, w), k = "r weighting dropped"))
p2 <- ggplot(data.frame(r = r), aes(r*1000)) +
  geom_histogram(aes(y = after_stat(density)), bins = 18,
                 fill = forest, alpha = 0.35, colour = NA) +
  geom_line(data = fitcurves, aes(r*1000, f/1000, colour = k), linewidth = 0.9) +
  scale_colour_manual(values = c("correct fit" = forest, "r weighting dropped" = rust)) +
  labs(x = "distance from the point (m)", y = "density", colour = NULL,
       title = "One survey, two analyses",
       subtitle = sprintf("n = %d detections at %d points", length(r), K)) +
  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))

## ---- misspec ----
s_hr <- 0.05; b_hr <- 3
mu_t <- mu_hr(s_hr, b_hr, w); nu_t <- nu_hr(s_hr, b_hr, w)
sprintf("hazard-rate truth: g(0.5 sigma) = %.4f, g(sigma) = %.4f | mu %.5f | nu %.7f",
        g_hr(0.5*s_hr, s_hr, b_hr), g_hr(s_hr, s_hr, b_hr), mu_t, nu_t)

best_fit <- function(dens, ld, w) {
  optimise(function(p) -integrate(function(x) dens(x)*ld(x, exp(p), w), 1e-9, w)$value,
           c(-6, 0), tol = 1e-12)$minimum
}
sL <- exp(best_fit(function(x) g_hr(x, s_hr, b_hr)/mu_t, ld_ln, w))
sP <- exp(best_fit(function(r) r*g_hr(r, s_hr, b_hr)/nu_t, ld_pt, w))
sprintf("LINE : best half-normal sigma %.5f -> mu %.5f vs true %.5f -> D bias %+.2f%%",
        sL, mu_hn(sL, w), mu_t, 100*(mu_t/mu_hn(sL, w) - 1))
sprintf("POINT: best half-normal sigma %.5f -> nu %.7f vs true %.7f -> D bias %+.2f%%",
        sP, nu_hn(sP, w), nu_t, 100*(nu_t/nu_hn(sP, w) - 1))

## ---- truncation-sweep ----
sw <- t(sapply(c(0.06, 0.07, 0.08, 0.09, 0.10), function(ww) {
  nt <- nu_hr(s_hr, b_hr, ww); mt <- mu_hr(s_hr, b_hr, ww)
  sp <- exp(best_fit(function(r) r*g_hr(r, s_hr, b_hr)/nt, ld_pt, ww))
  sl <- exp(best_fit(function(x) g_hr(x, s_hr, b_hr)/mt, ld_ln, ww))
  c(w = ww, dropped_pct = 100*(1 - nt/nu_t),
    point_bias = 100*(nt/nu_hn(sp, ww) - 1), line_bias = 100*(mt/mu_hn(sl, ww) - 1))
}))
round(sw, 2)

## ---- mc ----
Ln <- 266.1/(2*D*mu_t)
M <- 400
res <- t(sapply(1:M, function(i) {
  set.seed(52820 + i)
  Np <- rpois(1, D*K*pi*w^2); rp <- sqrt(runif(Np))*w
  rp <- rp[runif(Np) < g_hr(rp, s_hr, b_hr)]
  Nl <- rpois(1, D*2*w*Ln);   xl <- runif(Nl, 0, w)
  xl <- xl[runif(Nl) < g_hr(xl, s_hr, b_hr)]
  c(n_pt = length(rp), n_ln = length(xl),
    D_pt = length(rp)/(2*pi*K*nu_hn(fit_pt(rp, w), w)),
    D_ln = length(xl)/(2*Ln*mu_hn(fit_ln(xl, w), w)))
}))
sprintf("effort matched: %d points and %.1f km of line, both expecting %.0f detections",
        K, Ln, 2*D*Ln*mu_t)
sprintf("POINT: D %.2f (SD %.2f) = %+.1f%% | within 5%% of the truth in %.1f%% of surveys",
        mean(res[, "D_pt"]), sd(res[, "D_pt"]), 100*(mean(res[, "D_pt"])/D - 1),
        100*mean(abs(res[, "D_pt"]/D - 1) < 0.05))
sprintf("LINE : D %.2f (SD %.2f) = %+.1f%% | within 5%% of the truth in %.1f%% of surveys",
        mean(res[, "D_ln"]), sd(res[, "D_ln"]), 100*(mean(res[, "D_ln"])/D - 1),
        100*mean(abs(res[, "D_ln"]/D - 1) < 0.05))

## ---- fig-mc ----
p1 <- ggplot(data.frame(r = rep(rs, 3),
                        g = c(g_hr(rs, s_hr, b_hr), g_hn(rs, sL), g_hn(rs, sP)),
                        k = rep(c("hazard-rate (true)", "best half-normal, line",
                                  "best half-normal, point"), each = length(rs))),
             aes(r*1000, g, colour = k, linetype = k)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c("hazard-rate (true)" = ink, "best half-normal, line" = forest,
                                 "best half-normal, point" = rust)) +
  scale_linetype_manual(values = c("hazard-rate (true)" = 1, "best half-normal, line" = 2,
                                   "best half-normal, point" = 2)) +
  labs(x = "distance (m)", y = "detection probability", colour = NULL, linetype = NULL,
       title = "A shoulder the half-normal cannot make") +
  guides(colour = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  theme_minimal(base_size = 10) + te_canvas +
  theme(legend.position = "bottom", plot.title = element_text(colour = ink, face = "bold"),
        legend.text = element_text(size = 7))
mc <- rbind(data.frame(v = res[, "D_pt"], k = "point (200 points)"),
            data.frame(v = res[, "D_ln"], k = sprintf("line (%.1f km)", Ln)))
p2 <- ggplot(mc, aes(v, fill = k)) +
  geom_histogram(bins = 34, position = "identity", alpha = 0.55) +
  geom_vline(xintercept = D, colour = ink, linetype = 2, linewidth = 0.7) +
  scale_fill_manual(values = setNames(c(rust, forest), c("point (200 points)",
                                                         sprintf("line (%.1f km)", Ln)))) +
  labs(x = "estimated density (animals per km2)", y = "surveys", fill = NULL,
       title = "Equal detections, equal mistake",
       subtitle = "dashed: the truth (100)") +
  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))

## ---- estimated-distances-limit ----
de_rg <- seq(5e-5, 0.4, by = 1e-4)                 # true distances, far beyond w
de_wr <- de_rg*g_hn(de_rg, s0); de_wr <- de_wr/sum(de_wr)
de_z  <- qnorm(ppoints(100))
de_asym <- function(se, ww, parts = FALSE) {       # limit of D-hat/D, naive fit
  ro <- outer(de_rg, exp(se*de_z - se^2/2))
  pw <- outer(de_wr, rep(1/length(de_z), length(de_z)))
  keep <- ro <= ww; p_in <- sum(pw[keep])
  s_star <- exp(optimise(function(q) -sum(pw[keep]*ld_pt(ro[keep], exp(q), ww)),
                         c(-6, 0), tol = 1e-12)$minimum)
  if (parts) return(c(p_in/(1 - g_hn(ww, s0)), nu_hn(s_star, ww)/nu_hn(s0, ww),
                      sum(pw[keep]*ro[keep]^2)/p_in/m2_point(s0, ww)))
  p_in*s0^2/nu_hn(s_star, ww)
}
de_s <- c(0.1, 0.2, 0.3, 0.4); de_w <- c(2, 2.5, 3, 3.5, 4, 8)
de_tab <- sapply(de_s, function(se) sapply(de_w*s0, function(ww) de_asym(se, ww)))
dimnames(de_tab) <- list(paste(de_w, "sigma"), paste("s =", de_s))
stopifnot(abs(de_asym(0, w) - 1) < 1e-3, abs(de_tab["8 sigma", 1:3] - exp(-de_s[1:3]^2)) < 0.01)
round(rbind(de_tab, "no truncation, exp(-s^2)" = exp(-de_s^2)), 3)
de_parts <- de_asym(0.3, w, parts = TRUE)
sprintf("w = 2.5 sigma, s = 0.3: share inside w %.3f of error-free | mean r^2 inside w %.3f of error-free | fitted nu %.3f of true",
        de_parts[1], de_parts[3], de_parts[2])

## ---- estimated-distances-mc ----
de_xg <- seq(1e-4, 0.25, by = 5e-4)                # grid of true distances for the fix
de_fit_err <- function(o, se) {
  kern <- outer(o, de_xg, function(a, x) dlnorm(a, log(x) - se^2/2, se))
  p_w  <- plnorm(w, log(de_xg) - se^2/2, se)       # P(recorded <= w | true x)
  nll  <- function(q) { gx <- de_xg*g_hn(de_xg, exp(q))
    -sum(log(kern %*% gx)) + length(o)*log(sum(p_w*gx)) }
  sg <- exp(optimise(nll, c(-6, -1), tol = 1e-8)$minimum)
  length(o)/(2*pi*K*sum(p_w*de_xg*g_hn(de_xg, sg))*5e-4)
}
set.seed(34510); de_M <- 1000
de_mc <- t(replicate(de_M, {
  n_all <- rpois(1, D*K*pi*0.25^2); r_true <- sqrt(runif(n_all))*0.25
  r_true <- r_true[runif(n_all) < g_hn(r_true, s0)]
  z_err <- rnorm(length(r_true)); z_rep <- rnorm(30) - rnorm(30)
  out <- c(exact = sum(r_true <= w)/(2*pi*K*nu_hn(fit_pt(r_true[r_true <= w], w), w)))
  for (se in c(0.2, 0.3)) {
    o <- r_true*exp(se*z_err - se^2/2); o <- o[o <= w]
    out <- c(out, setNames(c(length(o)/(2*pi*K*nu_hn(fit_pt(o, w), w)), de_fit_err(o, se),
                             de_fit_err(o, se*sd(z_rep)/sqrt(2))), paste0(c("naive", "known", "est"), se)))
  }
  out
}))/D
de_mean <- colMeans(de_mc); de_sd <- apply(de_mc, 2, sd)
de_pair <- de_mc[, c("naive0.2", "naive0.3")] - de_mc[, "exact"]
sprintf("%s: mean D/D %.3f (MC SE %.3f), survey SD %.3f", names(de_mean), de_mean, de_sd/sqrt(de_M), de_sd)
sprintf("naive minus exact, same birds: s = %.1f %+.3f (MC SE %.3f) | limit %+.3f",
        c(0.2, 0.3), colMeans(de_pair), apply(de_pair, 2, sd)/sqrt(de_M), de_tab["2.5 sigma", 2:3] - 1)

## ---- plain-counts-closed ----
pc_Kd <- K; pc_Kp <- 4*K; pc_rho <- 0.8          # 200 distance points, 800 plain counts
pc_mu <- D*2*pi*nu0                               # expected detections per point
pc_dl <- function(s, wr) { a <- wr^2/(2*s^2); if (is.finite(a)) 2 - 2*a*exp(-a)/(1 - exp(-a)) else 2 }
pc_dlnu <- pc_dl(s0, w)                           # d log nu / d log sigma
stopifnot(abs(pc_dlnu - log(nu_hn(s0*1.001, w)/nu_hn(s0/1.001, w))/(2*log(1.001))) < 1e-5)
pc_mom <- function(k) integrate(function(x) (x^2/s0^2)^k*fpt(x, s0, w), 0, w)$value
pc_I  <- pc_mom(2) - pc_mom(1)^2                  # information per detection on log sigma
pc_c  <- pc_dlnu^2/pc_I
pc_se <- function(Kd, Kp) sqrt(1/((Kd + Kp)*pc_mu) + pc_c/(Kd*pc_mu))
pc_r  <- nu_hn(pc_rho*s0, w)/nu0                  # plain counts with sigma_p = 0.8 sigma
pc_lim <- (pc_Kd + pc_Kp*pc_r)/(pc_Kd + pc_Kp)
sprintf("mu %.4f per point | c %.4f | detection term %.1f%% of the distance-only variance",
        pc_mu, pc_c, 100*pc_c/(1 + pc_c))
sprintf("SE of log D: distances only %.4f | with %d plain counts %.4f (%+.1f%%) | floor %.4f (%+.1f%%)",
        pc_se(pc_Kd, 0), pc_Kp, pc_se(pc_Kd, pc_Kp), 100*(pc_se(pc_Kd, pc_Kp)/pc_se(pc_Kd, 0) - 1),
        sqrt(pc_c/(pc_Kd*pc_mu)), 100*(sqrt(pc_c/(1 + pc_c)) - 1))
sprintf("sigma_p = %.1f sigma: r = %.4f (rho^2 = %.2f) | shared fit converges to %.4f D",
        pc_rho, pc_r, pc_rho^2, pc_lim)

## ---- plain-counts-sim ----
pc_draw <- function(npt, sig, dens) {             # counts and distances within w
  n_in <- rpois(npt, dens*pi*w^2)
  rr <- sqrt(runif(sum(n_in)))*w
  seen <- runif(length(rr)) < g_hn(rr, sig)
  list(n = tabulate(rep.int(seq_len(npt), n_in)[seen], npt), r = rr[seen])
}
## shared against separate sigma for the plain counts: the distances enter both fits alike
pc_ll  <- function(y) sum(dpois(y, mean(y), log = TRUE))
pc_lrt <- function(a, b) 2*(pc_ll(a) + pc_ll(b) - pc_ll(c(a, b)))
pc_one <- function() {
  dd <- pc_draw(pc_Kd, s0, D); nuh <- nu_hn(fit_pt(dd$r, w), w)
  p_same <- pc_draw(pc_Kp, s0, D)$n
  p_det  <- pc_draw(pc_Kp, pc_rho*s0, D)$n        # plain counts see less far
  p_hab  <- pc_draw(pc_Kp, s0, D*pc_r)$n          # plain-count points hold fewer birds
  shared <- function(p) sum(dd$n, p)/(2*pi*(pc_Kd + pc_Kp)*nuh)
  se_sh  <- sqrt(1/sum(dd$n, p_det) + pc_c/length(dd$r))
  c(D_ds = sum(dd$n)/(2*pi*pc_Kd*nuh), D_same = shared(p_same), D_det = shared(p_det),
    cov_det = abs(log(shared(p_det)/D)) < 1.96*se_sh,
    lrt_same = pc_lrt(dd$n, p_same), lrt_det = pc_lrt(dd$n, p_det), lrt_hab = pc_lrt(dd$n, p_hab),
    Dp_hab = mean(p_hab)/(2*pi*nuh))
}
set.seed(34120)
pc_R <- 2000
pc_sim <- t(replicate(pc_R, pc_one()))
pc_rej <- colMeans(pc_sim[, c("lrt_same", "lrt_det", "lrt_hab")] > qchisq(0.95, 1))
sprintf("SD of log D: distances only %.4f | with plain counts %.4f (MC SE %.4f)",
        sd(log(pc_sim[, "D_ds"])), sd(log(pc_sim[, "D_same"])),
        sd(log(pc_sim[, "D_same"]))/sqrt(2*(pc_R - 1)))
pc_mcse <- apply(pc_sim[, c("D_ds", "D_same", "D_det")]/D, 2, sd)/sqrt(pc_R)
sprintf("mean D/D (MC SE): distances only %.4f (%.4f) | shared, same detection %.4f (%.4f) | shared, sigma_p 0.8 %.4f (%.4f)",
        mean(pc_sim[, "D_ds"])/D, pc_mcse[1], mean(pc_sim[, "D_same"])/D, pc_mcse[2],
        mean(pc_sim[, "D_det"])/D, pc_mcse[3])
## E[nu/nu-hat] - 1 to second order in log sigma-hat, its small-sample bias included
pc_L  <- function(h) log(nu_hn(s0*exp(h), w))
pc_L2 <- (pc_L(1e-3) - 2*pc_L(0) + pc_L(-1e-3))/1e-6
pc_L3 <- (pc_L(2e-3) - 2*pc_L(1e-3) + 2*pc_L(-1e-3) - pc_L(-2e-3))/2e-9
pc_b  <- (4*pc_mom(1) - pc_L3 - 4*pc_I)/(2*pc_Kd*pc_mu*pc_I^2)
pc_exc <- -pc_dlnu*pc_b - (pc_L2 - pc_dlnu^2)/(2*pc_Kd*pc_mu*pc_I)
pc_dev <- (colMeans(pc_sim[, c("D_ds", "D_same", "D_det")])/D - c(1, 1, pc_lim)*(1 + pc_exc))/pc_mcse
stopifnot(all(abs(pc_dev) < 2))
sprintf("small-sample excess %.2f%% | mean minus raised limit, in MC SE: %s", 100*pc_exc, toString(sprintf("%+.2f", pc_dev)))
sprintf("sigma_p 0.8: 95%% interval covers D in %.3f | LRT rejects: same %.3f, sigma_p %.3f, habitat %.3f",
        mean(pc_sim[, "cov_det"]), pc_rej[1], pc_rej[2], pc_rej[3])
sprintf("habitat world, shared sigma with its own D at the plain-count points: %.2f", mean(pc_sim[, "Dp_hab"]))

## what the plain counts still inform: a habitat slope, log D = log(100) + 0.3 x
set.seed(34121)
pc_b1 <- 0.3
pc_slope <- function() {
  xd <- rnorm(pc_Kd); xp <- rnorm(pc_Kp)
  nd <- pc_draw(pc_Kd, s0, D*exp(pc_b1*xd))$n; np <- pc_draw(pc_Kp, s0, D*exp(pc_b1*xp))$n
  one <- glm.fit(cbind(1, xd), nd, family = poisson())   # nu only shifts the intercept
  two <- glm.fit(cbind(rep(1:0, c(pc_Kd, pc_Kp)), rep(0:1, c(pc_Kd, pc_Kp)), c(xd, xp)),
                 c(nd, np), family = poisson())          # own intercept for the plain counts
  c(ds = one$coefficients[[2]], joint = two$coefficients[[3]])
}
pc_sl <- t(replicate(500, pc_slope()))
sprintf("slope (true %.1f): distances only %.3f (SD %.4f) | with plain counts %.3f (SD %.4f)",
        pc_b1, mean(pc_sl[, "ds"]), sd(pc_sl[, "ds"]), mean(pc_sl[, "joint"]), sd(pc_sl[, "joint"]))
pc_slse <- 1/sqrt(c(pc_Kd, pc_Kd + pc_Kp)*pc_mu*exp(pc_b1^2/2))   # large-sample SD of the slope
sprintf("large-sample SD of the slope: distances only %.4f | with plain counts %.4f", pc_slse[1], pc_slse[2])

## ---- plain-counts-radius ----
## plain counts without a radius: the count now depends on the tail beyond w
pc_nu <- function(s, wr) if (is.finite(wr)) nu_hn(s, wr) else s^2
pc_info <- function(wp) {                          # expected information, (log D, log sigma)
  gd <- c(1, pc_dl(s0, w)); gp <- c(1, pc_dl(s0, wp))
  pc_Kd*pc_mu*gd %o% gd + pc_Kp*D*2*pi*pc_nu(s0, wp)*gp %o% gp +
    diag(c(0, pc_Kd*pc_mu*pc_I))
}
pc_sdw <- sapply(c(w, Inf), function(wp) sqrt(solve(pc_info(wp))[1, 1]))
stopifnot(all.equal(pc_sdw[1], pc_se(pc_Kd, pc_Kp)))
pc_pseudo <- function(wp) {                        # where the shared fit converges, sigma_p = 0.8 sigma
  mp <- D*2*pi*pc_nu(pc_rho*s0, wp)
  nll <- function(p) {
    ld <- exp(p[1])*2*pi*nu_hn(exp(p[2]), w); lp <- exp(p[1])*2*pi*pc_nu(exp(p[2]), wp)
    -(pc_Kd*(pc_mu*log(ld) - ld) + pc_Kp*(mp*log(lp) - lp) +
      pc_Kd*pc_mu*(-pc_mom(1)*s0^2/(2*exp(2*p[2])) - log(nu_hn(exp(p[2]), w))))
  }
  exp(optim(c(log(D), log(s0)), nll, method = "BFGS", control = list(reltol = 1e-14))$par)/c(D, s0)
}
pc_ps <- sapply(c(w, Inf), pc_pseudo)
sprintf("plain counts within w: SE %.4f, shared fit D/D %.4f, sigma/sigma %.4f", pc_sdw[1], pc_ps[1, 1], pc_ps[2, 1])
sprintf("plain counts, no radius: SE %.4f, shared fit D/D %.4f, sigma/sigma %.4f", pc_sdw[2], pc_ps[1, 2], pc_ps[2, 2])
