# Camera trap density: the random encounter model
# https://tidyecology.com/posts/random-encounter-model-camera-traps/
#
# 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-14

## ---- fluxconst ----
num <- integrate(function(a) pmax(0, -cos(a)) / (2 * pi), 0, 2 * pi)$value
c(numeric = num, closed_form = 1 / pi, gap = num - 1 / pi)

## ---- geometry ----
## exact boundary crossings of the segments P1 -> P1 + D
## returns, per segment, up to 4 crossing positions u and whether each is inward
crossings <- function(P1, D, r, half) {
  m <- nrow(P1)
  U <- matrix(Inf, m, 4); IN <- matrix(FALSE, m, 4)

  ## the arc: |P1 + u D| = r, and the crossing point inside the angular span
  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]                             # outward normal is Q / r
    IN[good, k] <- ((D[, 1] * Q[, 1] + D[, 2] * Q[, 2]) < 0)[good]
  }
  ## the two radii: the segments from the origin at +half and -half, out to r
  for (k in 1:2) {
    s <- c(1, -1)[k] * half
    e <- c(cos(s), sin(s))
    n <- c(cos(s + c(1, -1)[k] * pi / 2), sin(s + c(1, -1)[k] * pi / 2))
    cP <- P1[, 1] * e[2] - P1[, 2] * e[1]
    cD <- D[, 1] * e[2] - D[, 2] * e[1]
    u <- -cP / 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] * n[1] + D[, 2] * n[2]) < 0)[good]
  }
  list(U = U, IN = IN)
}

## ---- walk ----
walk_one <- function(nstep, dt, v, W, r, half, rho) {
  u <- runif(nstep)
  turn <- if (rho < 1e-9) 2 * pi * u - pi else
    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)   # only steps near the zone
  if (!length(idx)) return(list(t_in = numeric(0), t_out = 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(list(t_in = numeric(0), t_out = numeric(0)))
  tt <- (idx[hit[, 1]] - 1 + cr$U[hit]) * dt
  o <- order(tt); tt <- tt[o]; inw <- cr$IN[hit][o]
  list(t_in = tt[inw], t_out = tt[!inw])
}

## n independent animals on the same torus: that is the gas, at density n / W^2
gas <- function(n, nstep, dt, v, W, r, half, rho) {
  vapply(seq_len(n), function(i)
    length(walk_one(nstep, dt, v, W, r, half, rho)$t_in), numeric(1))
}

## ---- sweeptheta ----
W <- 20; r <- 4; v <- 1; dt <- 0.5; nanim <- 120; nstep <- 25000
A <- W^2; Tt <- nstep * dt; Dtrue <- nanim / A

set.seed(3001)
thd <- c(20, 60, 120, 200)
res <- do.call(rbind, lapply(thd, function(th) {
  half <- (th / 2) * pi / 180
  y <- gas(nanim, nstep, dt, v, W, r, half, rho = 0.9)
  L <- 2 * r + 2 * r * half
  data.frame(zone = paste0(th, " deg"), L = L,
             obs = sum(y) / Tt, se = sd(y / Tt) * sqrt(nanim),
             pred = Dtrue * v * L / pi)
}))
res$ratio <- res$obs / res$pred
res

## ---- discrun ----
## a full circle has no radii, so its perimeter is 2 pi r and its constant is 2 pi
walk_disc <- function(nstep, dt, v, W, r, 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)
  a <- D[, 1]^2 + D[, 2]^2
  b <- 2 * (R1[, 1] * D[, 1] + R1[, 2] * D[, 2])
  cc <- R1[, 1]^2 + R1[, 2]^2 - r^2
  disc <- b^2 - 4 * a * cc
  n <- 0
  for (k in 1:2) {
    uu <- (-b + c(-1, 1)[k] * sqrt(pmax(disc, 0))) / (2 * a)
    Q <- cbind(R1[, 1] + uu * D[, 1], R1[, 2] + uu * D[, 2])
    n <- n + sum(disc > 0 & uu > 0 & uu <= 1 &
                   (D[, 1] * Q[, 1] + D[, 2] * Q[, 2]) < 0, na.rm = TRUE)
  }
  n
}
set.seed(3002)
ydisc <- vapply(seq_len(nanim), function(i) walk_disc(nstep, dt, v, W, r, 0.9), numeric(1))
disc <- data.frame(zone = "360 deg", L = 2 * pi * r, obs = sum(ydisc) / Tt,
                   se = sd(ydisc / Tt) * sqrt(nanim),
                   pred = Dtrue * v * (2 * pi * r) / pi)
disc$ratio <- disc$obs / disc$pred
disc

## ---- fig-perimeter ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
all5 <- rbind(res, disc)
ggplot(all5, aes(L, obs)) +
  geom_abline(intercept = 0, slope = Dtrue * v / pi, colour = "#93a87f", linewidth = 0.9) +
  geom_errorbar(aes(ymin = obs - se, ymax = obs + se), width = 0.35, colour = "#275139") +
  geom_point(size = 2.6, colour = "#275139") +
  geom_text(aes(label = zone), nudge_x = 0.45, hjust = 0, vjust = 1.5,
            size = 3.2, colour = "#5d6b61") +
  scale_x_continuous(limits = c(8.4, 27.5)) +
  labs(x = "detection zone perimeter L (m)",
       y = expression(paste("encounter rate y/t (", s^-1, ")"))) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- perimfacts ----
all5$z <- (all5$obs - all5$pred) / all5$se
rr <- range(all5$ratio); X2 <- sum(all5$z^2)
cat(sprintf("observed / predicted, five zones: %.4f to %.4f\n", rr[1], rr[2]))
cat(sprintf("deviations in standard errors: %s\n",
            paste(sprintf("%+.2f", all5$z), collapse = ", ")))
cat(sprintf("pooled against the theory: sum of squared z = %.2f on 5 df, p = %.3f\n",
            X2, pchisq(X2, 5, lower.tail = FALSE)))

## ---- sweeprho ----
half40 <- 20 * pi / 180
L40 <- 2 * r + 2 * r * half40
pred40 <- Dtrue * v * L40 / pi
set.seed(3003)
rhos <- c(0, 0.5, 0.9, 0.98)
tor <- do.call(rbind, lapply(rhos, function(rh) {
  y <- gas(nanim, nstep, dt, v, W, r, half40, rho = rh)
  data.frame(rho = rh, obs = sum(y) / Tt, se = sd(y / Tt) * sqrt(nanim))
}))
tor$ratio <- tor$obs / pred40
tor$rel_se <- tor$se / pred40
tor

## ---- fig-tortuosity ----
ggplot(tor, aes(factor(rho), ratio)) +
  geom_hline(yintercept = 1, linetype = 2, colour = "#93a87f") +
  geom_errorbar(aes(ymin = ratio - rel_se, ymax = ratio + rel_se), width = 0.14,
                colour = "#275139", linewidth = 0.7) +
  geom_point(size = 2.8, colour = "#275139") +
  labs(x = "path persistence (mean resultant length of the turning angle)",
       y = "observed / predicted encounter rate") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- rhofacts ----
tor$z <- (tor$obs - pred40) / tor$se
X2r <- sum(tor$z^2)
cat(sprintf("deviations in standard errors: %s\n",
            paste(sprintf("%+.2f", tor$z), collapse = ", ")))
cat(sprintf("pooled: sum of squared z = %.2f on 4 df, p = %.3f\n",
            X2r, pchisq(X2r, 4, lower.tail = FALSE)))
cat(sprintf("standard error, rho = 0 relative to rho = 0.98: %.2f times\n",
            tor$rel_se[1] / tor$rel_se[4]))

## ---- remestimate ----
th40 <- 2 * half40
yy <- sum(gas(nanim, nstep, dt, v, W, r, half40, rho = 0.9))
rem_D <- function(y, t, v, r, theta) y * pi / (t * v * r * (2 + theta))
Dhat <- rem_D(yy, Tt, v, r, th40)
c(y = yy, D_hat = Dhat, D_true = Dtrue, ratio = Dhat / Dtrue)

## ---- nonident ----
wrong <- c(0.5, 0.8, 1, 1.25, 2)
data.frame(v_assumed = v * wrong,
           D_hat = vapply(v * wrong, function(vv) rem_D(yy, Tt, vv, r, th40), numeric(1)),
           ratio_to_truth = vapply(v * wrong, function(vv)
             rem_D(yy, Tt, vv, r, th40), numeric(1)) / Dtrue)

## ---- fieldunits ----
y_field <- 200
t_field <- 60 * 30                      # camera-days
v_field <- 3.5                          # km per day
r_field <- 0.010                        # km
th_field <- 40 * pi / 180               # radians
D_field <- rem_D(y_field, t_field, v_field, r_field, th_field)
c(D_per_km2 = D_field, animals_in_100km2 = D_field * 100)

## ---- fieldsens ----
grid <- expand.grid(v = v_field * c(1 / 1.3, 1, 1.3), r = c(0.008, 0.010, 0.012))
grid$D <- mapply(function(v, r) rem_D(y_field, t_field, v, r, th_field), grid$v, grid$r)
grid$ratio <- grid$D / D_field
grid[order(grid$D), ]
