# Measuring animal speed from camera traps
# https://tidyecology.com/posts/animal-speed-from-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-11-04

## ---- geometry ----
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) {                                       # the arc
    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) {                                       # the two radii
    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))
    u <- -(P1[, 1] * e[2] - P1[, 2] * e[1]) / (D[, 1] * e[2] - D[, 2] * e[1])
    tt <- (P1[, 1] + u * D[, 1]) * e[1] + (P1[, 2] + u * D[, 2]) * e[2]
    good <- abs(D[, 1] * e[2] - D[, 2] * e[1]) > 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_one <- 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(0L)
  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(0L)
  sum(cr$IN[hit])                                        # entries only
}

## ---- simspeed ----
W <- 20; r <- 4; half <- 20 * pi / 180; dt <- 0.5
A <- W^2; L <- 2 * r + 2 * r * half; nstep <- 20000; Tt <- nstep * dt

set.seed(2601)
n <- 150
sdlog <- 0.8                          # gives CV close to 1, as reported for real species
vi <- rlnorm(n, log(1) - sdlog^2 / 2, sdlog)      # E[V] = 1 m/s by construction
ent <- vapply(vi, function(v) walk_one(nstep, dt, v, W, r, half, rho = 0.9), integer(1))
obs <- rep(vi, ent)                   # one recorded speed per encounter

c(n_animals = n, n_encounters = length(obs),
  true_mean = mean(vi), true_CV = sd(vi) / mean(vi))

## ---- biasnumbers ----
wmedian <- function(x, w) {
  o <- order(x); x[o][which(cumsum(w[o]) / sum(w) >= 0.5)[1]]
}
sb <- data.frame(
  estimator = c("camera arithmetic mean", "camera median", "camera harmonic mean"),
  from_camera = c(mean(obs), median(obs), 1 / mean(1 / obs)),
  exact_expectation = c(sum(vi^2) / sum(vi), wmedian(vi, vi), sum(vi) / n))
sb$ratio_to_truth <- sb$from_camera / mean(vi)
c(truth_mean_speed = mean(vi), truth_CV = sd(vi) / mean(vi))
sb

## ---- fig-sizebias ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
gx <- seq(0.01, 6, length.out = 400)
dens <- rbind(
  data.frame(v = gx, d = dlnorm(gx, log(1) - sdlog^2 / 2, sdlog),
             which = "true, across individuals"),
  data.frame(v = gx, d = gx * dlnorm(gx, log(1) - sdlog^2 / 2, sdlog) / 1,
             which = "as sampled by the camera"))
vl <- data.frame(x = c(mean(vi), mean(obs), 1 / mean(1 / obs)),
                 lab = c("true mean", "camera arithmetic", "camera harmonic"))
ggplot(dens, aes(v, d, linetype = which)) +
  geom_line(colour = "#275139", linewidth = 0.8) +
  geom_vline(data = vl, aes(xintercept = x), colour = "#b5534e", linewidth = 0.4) +
  geom_text(data = vl, aes(x = x, y = c(0.93, 0.86, 0.93), label = lab),
            inherit.aes = FALSE, angle = 90, vjust = c(-0.4, -0.4, 1.4), hjust = 1,
            size = 3.1, colour = "#b5534e") +
  scale_linetype_manual(values = c("as sampled by the camera" = 2,
                                   "true, across individuals" = 1), name = NULL) +
  coord_cartesian(xlim = c(0, 5), ylim = c(0, 0.95)) +
  labs(x = "speed (m/s)", y = "density") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")

## ---- remcost ----
rem_D <- function(y, t, v, r, theta) y * pi / (t * v * r * (2 + theta))
Dtrue <- n / A
rate <- length(obs) / Tt
out <- data.frame(
  speed_used = c("camera arithmetic mean", "camera harmonic mean"),
  v = c(mean(obs), 1 / mean(1 / obs)))
out$D_hat <- rem_D(length(obs), Tt, out$v, r, 2 * half)
out$ratio_to_truth <- out$D_hat / Dtrue
out

## ---- activity ----
vm <- function(x, mu, k) exp(k * cos(x - mu)) / (2 * pi * besselI(k, 0))
grid <- seq(0, 2 * pi, length.out = 2001)[-2001]
shape_raw <- function(x) 0.55 * vm(x, 1.4, 6) + 0.45 * vm(x, 4.3, 4)
gmax <- max(shape_raw(grid))
shape <- function(x) shape_raw(x) / gmax          # scaled so that max(shape) = 1
A_shape <- mean(shape(grid))                      # the activity level if the peak is 1

kern_f <- function(x, dat, k)
  vapply(x, function(z) mean(exp(k * cos(z - dat)) / (2 * pi * besselI(k, 0))), numeric(1))

lcv_k <- function(dat) {                          # leave-one-out likelihood CV
  m <- length(dat)
  nll <- function(lk) {
    k <- exp(lk)
    Cm <- outer(dat, dat, function(a, b) exp(k * cos(a - b)))
    diag(Cm) <- 0
    -sum(log(rowSums(Cm) / ((m - 1) * 2 * pi * besselI(k, 0))))
  }
  exp(optimise(nll, c(log(0.3), log(200)))$minimum)
}

set.seed(2602)
nrec <- 1200
tt <- (sample(grid, nrec, replace = TRUE, prob = shape(grid)) +
         runif(nrec, 0, 2 * pi / 2000)) %% (2 * pi)
k_hat <- lcv_k(tt)
A_hat <- 1 / (2 * pi * max(kern_f(grid, tt, k_hat)))
c(kappa_cv = k_hat, A_hat = A_hat, A_shape = A_shape, ratio = A_hat / A_shape)

## ---- bwsweep ----
bw <- data.frame(kappa = c(3, 10, 40, k_hat))
bw$A_hat <- vapply(bw$kappa, function(k) 1 / (2 * pi * max(kern_f(grid, tt, k))), numeric(1))
bw$ratio_to_truth <- bw$A_hat / A_shape
bw$note <- c("far too smooth", "too smooth", "close", "chosen by cross-validation")
bw[order(bw$kappa), ]

## ---- fig-activity ----
fit <- kern_f(grid, tt, k_hat)
tru <- shape(grid) / (2 * pi * A_shape)
dfa <- rbind(data.frame(h = grid * 24 / (2 * pi), d = tru, which = "true record density"),
             data.frame(h = grid * 24 / (2 * pi), d = fit, which = "fitted kernel density"))
ggplot(dfa, aes(h, d, linetype = which)) +
  geom_hline(yintercept = max(fit), linetype = 3, colour = "#93a87f") +
  geom_line(colour = "#275139", linewidth = 0.8) +
  scale_linetype_manual(values = c("true record density" = 1,
                                   "fitted kernel density" = 2), name = NULL) +
  scale_x_continuous(breaks = seq(0, 24, 6)) +
  labs(x = "time of day (h)", y = "density of records") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")

## ---- nonident ----
worlds <- data.frame(peak_activity = c(1, 0.7, 0.4))
worlds$true_A <- worlds$peak_activity * A_shape
worlds$A_hat <- A_hat                        # identical data in all three worlds
worlds$ratio <- worlds$A_hat / worlds$true_A
worlds
