# Checking a camera trap density estimate
# https://tidyecology.com/posts/checking-a-camera-trap-density-estimate/
#
# 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

## ---- rig ----
inside <- function(P, r, half) {
  (P[, 1]^2 + P[, 2]^2 <= r^2) & (abs(atan2(P[, 2], P[, 1])) <= half)
}

crossings <- function(P1, D, r, half) {
  m <- nrow(P1)
  U <- matrix(Inf, m, 4); IN <- matrix(FALSE, m, 4)
  a <- D[, 1]^2 + D[, 2]^2
  b <- 2 * (P1[, 1] * D[, 1] + P1[, 2] * D[, 2])
  cc <- P1[, 1]^2 + P1[, 2]^2 - r^2
  disc <- b^2 - 4 * a * cc
  ok <- disc > 0 & a > 0
  sq <- ifelse(ok, sqrt(pmax(disc, 0)), NA_real_)
  for (k in 1:2) {
    u <- (-b + c(-1, 1)[k] * sq) / (2 * a)
    Q <- cbind(P1[, 1] + u * D[, 1], P1[, 2] + u * D[, 2])
    good <- ok & !is.na(u) & u > 0 & u <= 1 & abs(atan2(Q[, 2], Q[, 1])) <= half
    good[is.na(good)] <- FALSE
    U[good, k] <- u[good]
    IN[good, k] <- ((D[, 1] * Q[, 1] + D[, 2] * Q[, 2]) < 0)[good]
  }
  for (k in 1:2) {
    s <- c(1, -1)[k] * half
    e <- c(cos(s), sin(s))
    nrm <- c(cos(s + c(1, -1)[k] * pi / 2), sin(s + c(1, -1)[k] * pi / 2))
    cD <- D[, 1] * e[2] - D[, 2] * e[1]
    u <- -(P1[, 1] * e[2] - P1[, 2] * e[1]) / cD
    tt <- (P1[, 1] + u * D[, 1]) * e[1] + (P1[, 2] + u * D[, 2]) * e[2]
    good <- abs(cD) > 1e-12 & !is.na(u) & u > 0 & u <= 1 & tt >= 0 & tt <= r
    good[is.na(good)] <- FALSE
    U[good, 2 + k] <- u[good]
    IN[good, 2 + k] <- ((D[, 1] * nrm[1] + D[, 2] * nrm[2]) < 0)[good]
  }
  list(U = U, IN = IN)
}

## returns the times of every entry into the zone, per animal
entry_times <- function(nstep, dt, v, W, r, half, rho) {
  u <- runif(nstep)
  turn <- 2 * atan(((1 - rho) / (1 + rho)) * tan(pi * (u - 0.5)))
  phi <- runif(1, 0, 2 * pi) + cumsum(turn)
  D <- cbind(v * dt * cos(phi), v * dt * sin(phi))
  p0 <- c(runif(1, -W / 2, W / 2), runif(1, -W / 2, W / 2))
  X <- p0[1] + cumsum(D[, 1]); Y <- p0[2] + cumsum(D[, 2])
  P1 <- cbind(c(p0[1], X[-nstep]), c(p0[2], Y[-nstep]))
  R1 <- cbind(((P1[, 1] + W / 2) %% W) - W / 2, ((P1[, 2] + W / 2) %% W) - W / 2)
  idx <- which((R1[, 1]^2 + R1[, 2]^2) < (r + v * dt)^2)
  if (!length(idx)) return(numeric(0))
  cr <- crossings(R1[idx, , drop = FALSE], D[idx, , drop = FALSE], r, half)
  hit <- which(is.finite(cr$U), arr.ind = TRUE)
  if (!nrow(hit)) return(numeric(0))
  tt <- (idx[hit[, 1]] - 1 + cr$U[hit]) * dt
  sort(tt[cr$IN[hit]])
}

rem_D <- function(y, t, v, r, theta) y * pi / (t * v * r * (2 + theta))

## ---- filter ----
W <- 20; r <- 4; half <- 20 * pi / 180; v <- 1; dt <- 0.5
A <- W^2; nanim <- 120; nstep <- 20000; Tt <- nstep * dt; Dtrue <- nanim / A

set.seed(3301)
ev <- lapply(seq_len(nanim), function(i) entry_times(nstep, dt, v, W, r, half, rho = 0.9))

## a filter with window w keeps an entry only if the previous kept entry, for the
## same animal, was more than w seconds ago
apply_filter <- function(ev, w) {
  sum(vapply(ev, function(x) {
    if (!length(x)) return(0L)
    keep <- 1L; last <- x[1]
    for (s in x[-1]) if (s - last > w) { keep <- keep + 1L; last <- s }
    keep
  }, integer(1)))
}

wins <- c(0, 1, 5, 30, 300, 1800)
flt <- data.frame(window_s = wins)
flt$y <- vapply(wins, function(w) apply_filter(ev, w), numeric(1))
flt$D_hat <- rem_D(flt$y, Tt, v, r, 2 * half)
flt$ratio_to_truth <- flt$D_hat / Dtrue
flt

## ---- fig-filter ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
ggplot(flt, aes(sqrt(window_s), ratio_to_truth)) +
  geom_hline(yintercept = 1, linetype = 2, colour = "#93a87f") +
  geom_line(colour = "#275139", linewidth = 0.8) +
  geom_point(size = 2.6, colour = "#275139") +
  annotate("text", x = 0.15, y = 1.09, hjust = 0, size = 3.2, colour = "#46604a",
           label = "every crossing counted: correct") +
  annotate("text", x = sqrt(1800) - 0.4, y = 0.25, hjust = 1, size = 3.2,
           colour = "#b5534e", label = "the 30 minute folk standard") +
  coord_cartesian(ylim = c(0, 1.18)) +
  scale_x_continuous(breaks = sqrt(wins), labels = c("0\n(none)", wins[-1])) +
  labs(x = "independence filter window (s, square root scale)",
       y = "estimated density / truth") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- overdisp ----
set.seed(3302)
ncam <- 400; nsm <- 4000; nan_c <- 20
Tc <- nsm * dt; Dbar <- nan_c / A

one_count <- function(n) sum(vapply(seq_len(n), function(i)
  length(entry_times(nsm, dt, v, W, r, half, rho = 0.9)), integer(1)))

y_hom <- vapply(seq_len(ncam), function(k) one_count(nan_c), numeric(1))
c(mean_count = mean(y_hom), var_count = var(y_hom),
  variance_to_mean = var(y_hom) / mean(y_hom))

## ---- hetero ----
set.seed(3303)
cv_local <- 0.5
D_local <- rlnorm(ncam, log(Dbar) - log(1 + cv_local^2) / 2, sqrt(log(1 + cv_local^2)))
y_het <- vapply(D_local, function(d) one_count(max(1, round(d * A))), numeric(1))

c(mean_count = mean(y_het), var_count = var(y_het),
  variance_to_mean = var(y_het) / mean(y_het))

## ---- coverage ----
per_survey <- 10
grp <- function(y) split(y, rep(seq_len(length(y) / per_survey), each = per_survey))

pois_ci <- function(y) {                       # pooled count treated as Poisson
  s <- sum(y); t_tot <- per_survey * Tc
  rem_D(s + c(-1, 1) * 1.96 * sqrt(s), t_tot, v, r, 2 * half)
}
camera_ci <- function(y) {                     # cameras as the replicate unit
  d <- rem_D(y, Tc, v, r, 2 * half)
  mean(d) + c(-1, 1) * qt(0.975, length(d) - 1) * sd(d) / sqrt(length(d))
}
cover <- function(y, ci) mean(vapply(grp(y), function(g) {
  b <- ci(g); Dbar >= b[1] && Dbar <= b[2]
}, logical(1)))

data.frame(
  landscape = c("uniform", "uniform", "patchy (CV 0.5)", "patchy (CV 0.5)"),
  interval = rep(c("Poisson on the pooled count", "t interval across cameras"), 2),
  coverage = c(cover(y_hom, pois_ci), cover(y_hom, camera_ci),
               cover(y_het, pois_ci), cover(y_het, camera_ci)),
  nominal = 0.95)

## ---- delta ----
cv_count <- sd(rem_D(y_het, Tc, v, r, 2 * half)) /
  (mean(rem_D(y_het, Tc, v, r, 2 * half)) * sqrt(per_survey))   # 10 cameras, patchy
cvs <- c(count = cv_count, speed = 0.20, zone = 0.10)
tot <- sqrt(sum(cvs^2))
rbind(component_CV = round(c(cvs, total = tot), 4),
      share_of_variance = round(c(cvs^2 / tot^2, total = 1), 4))

## ---- fig-variance ----
vs <- data.frame(component = names(cvs), share = as.numeric(cvs^2 / tot^2))
vs$component <- factor(vs$component, levels = vs$component[order(vs$share)])
ggplot(vs, aes(share, component)) +
  geom_col(fill = "#275139", width = 0.62) +
  geom_text(aes(label = sprintf("%.0f%%", 100 * share)), hjust = -0.25,
            size = 3.4, colour = "#46604a") +
  coord_cartesian(xlim = c(0, 1.05)) +
  labs(x = "share of the variance in the density estimate", y = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), panel.grid.major.y = element_blank())

## ---- placement ----
set.seed(3304)
one_camera <- function(D_hab) {                       # a camera in its own habitat
  rem_D(one_count(round(D_hab * A)), Tc, v, r, 2 * half)
}
D_good <- 0.50; D_poor <- 0.10
truth_landscape <- (D_good + D_poor) / 2               # habitats are equal in area

good <- vapply(seq_len(8), function(i) one_camera(D_good), numeric(1))
poor <- vapply(seq_len(2), function(i) one_camera(D_poor), numeric(1))

data.frame(
  quantity = c("cameras in good habitat", "cameras in poor habitat",
               "unweighted mean of the 10 cameras", "area-weighted mean",
               "true landscape density"),
  value = c(mean(good), mean(poor), mean(c(good, poor)),
            (mean(good) + mean(poor)) / 2, truth_landscape))
