# Staying time and the REST model in R
# https://tidyecology.com/posts/staying-time-and-the-rest-model/
#
# 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-09-25

## ---- 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))
    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)
}

## ---- walk ----
walk_one <- function(nstep, dt, v, W, r, half, rho, p_ar = 0, p_ra = 1) {
  ## active / resting state sequence, built bout by bout (p_ar = 0 means never rests)
  st <- if (p_ar <= 0) rep(1L, nstep) else {
    z <- integer(0); s <- 1L
    while (length(z) < nstep) {
      z <- c(z, rep(s, rgeom(1, if (s == 1L) p_ar else p_ra) + 1L)); s <- 1L - s
    }
    z[seq_len(nstep)]
  }

  u <- runif(nstep)
  turn <- 2 * atan(((1 - rho) / (1 + rho)) * tan(pi * (u - 0.5)))
  phi <- runif(1, 0, 2 * pi) + cumsum(turn)
  step <- v * dt * st                                     # zero while resting
  D <- cbind(step * cos(phi), step * 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)

  frac_in <- mean(inside(R1, r, half))                    # time-average occupancy
  idx <- which((R1[, 1]^2 + R1[, 2]^2) < (r + v * dt)^2)
  if (!length(idx)) return(list(visits = numeric(0), frac_in = frac_in, active = mean(st)))
  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(visits = numeric(0), frac_in = frac_in, active = mean(st)))
  tt <- (idx[hit[, 1]] - 1 + cr$U[hit]) * dt
  o <- order(tt); tt <- tt[o]; inw <- cr$IN[hit][o]
  t_in <- tt[inw]; t_out <- tt[!inw]
  if (!length(t_in)) return(list(visits = numeric(0), frac_in = frac_in, active = mean(st)))
  j <- findInterval(t_in, t_out) + 1L                     # the exit that closes each entry
  ok <- j <= length(t_out)                                # drop a visit still open at the end
  list(visits = t_out[j[ok]] - t_in[ok], frac_in = frac_in, active = mean(st))
}

gas <- function(n, nstep, dt, v, W, r, half, rho, p_ar = 0, p_ra = 1) {
  out <- lapply(seq_len(n), function(i) walk_one(nstep, dt, v, W, r, half, rho, p_ar, p_ra))
  list(visits = unlist(lapply(out, `[[`, "visits")),
       dur = vapply(out, function(z) sum(z$visits), numeric(1)),    # per animal
       nvis = vapply(out, function(z) length(z$visits), numeric(1)),
       frac_in = vapply(out, `[[`, numeric(1), "frac_in"),
       active = vapply(out, `[[`, numeric(1), "active"))
}

## the mean staying time is a ratio of two per-animal totals, so its standard error
## comes from resampling animals, which also allows for any clustering of visits
boot_stay <- function(g, B = 600) {
  n <- length(g$dur)
  vapply(seq_len(B), function(b) {
    i <- sample.int(n, n, replace = TRUE)
    sum(g$dur[i]) / sum(g$nvis[i])
  }, numeric(1))
}

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

set.seed(2701)
g <- gas(nanim, nstep, dt, v, W, r, half, rho = 0.9)
lambda <- length(g$visits) / Tt                    # arrivals per second, whole population
Wbar <- mean(g$visits)                             # mean staying time
Lnum <- sum(g$frac_in)                             # mean number inside, from positions

data.frame(
  claim = c("gas is uniform: mean number inside = D a",
            "Little's law: arrival rate x staying time = mean number inside",
            "Cauchy chord: mean staying time = pi a / (v L)",
            "REST estimate of density"),
  measured = c(Lnum, lambda * Wbar, Wbar, lambda * Wbar / a_zone),
  predicted = c(Dtrue * a_zone, Lnum, pi * a_zone / (v * L), Dtrue))

## ---- tort ----
set.seed(2702)
tor <- do.call(rbind, lapply(c(0, 0.5, 0.9, 0.98), function(rh) {
  gg <- gas(150, nstep, dt, v, W, r, half, rho = rh)
  bs <- boot_stay(gg)
  data.frame(rho = rh, n_visits = length(gg$visits), mean_stay = mean(gg$visits),
             boot_se = sd(bs), CV_stay = sd(gg$visits) / mean(gg$visits))
}))
tor$predicted <- pi * a_zone / (v * L)
tor$ratio <- tor$mean_stay / tor$predicted
tor$z <- (tor$mean_stay - tor$predicted) / tor$boot_se
tor

## ---- resting ----
p_ra <- dt / 120                                  # mean rest bout 120 s
A_level <- 0.30
p_ar <- p_ra * (1 - A_level) / A_level            # gives 30 per cent active in the long run

set.seed(2703)
gr <- gas(nanim, nstep, dt, v, W, r, half, rho = 0.9, p_ar = p_ar, p_ra = p_ra)
lam_r <- length(gr$visits) / Tt
W_r <- mean(gr$visits)

rem_D <- function(y, t, vv, r, theta) y * pi / (t * vv * r * (2 + theta))
res <- data.frame(
  method = c("REST: (y/t) E[T] / a",
             "REM with the camera's active speed",
             "REM with the true time-averaged speed"),
  D_hat = c(lam_r * W_r / a_zone,
            rem_D(length(gr$visits), Tt, v, r, 2 * half),
            rem_D(length(gr$visits), Tt, v * mean(gr$active), r, 2 * half)))
res$ratio_to_truth <- res$D_hat / Dtrue
bs_r <- boot_stay(gr)
naive_se <- sd(gr$visits) / sqrt(length(gr$visits))    # pretends visits are independent
c(n_visits = length(gr$visits), realised_activity = mean(gr$active), mean_stay = W_r,
  boot_se = sd(bs_r), naive_se = naive_se, se_ratio = sd(bs_r) / naive_se,
  CV_stay = sd(gr$visits) / W_r, max_stay = max(gr$visits))
res

## ---- censor ----
caps <- c(5, 10, 30, 60, 120, Inf)
cens <- data.frame(setting = ifelse(is.finite(caps), paste0(caps, " s"), "no limit"),
                   cap = caps)
cens$mean_recorded <- vapply(caps, function(cap) mean(pmin(gr$visits, cap)), numeric(1))
cens$D_hat <- lam_r * cens$mean_recorded / a_zone
cens$ratio_to_truth <- cens$D_hat / Dtrue
cens$pct_visits_cut <- vapply(caps, function(cap) 100 * mean(gr$visits > cap), numeric(1))
cens[, c("setting", "mean_recorded", "D_hat", "ratio_to_truth", "pct_visits_cut")]

## ---- fig-censoring ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
fc <- cens[is.finite(cens$cap), ]
ggplot(fc, aes(cap, D_hat)) +
  geom_hline(yintercept = Dtrue, linetype = 2, colour = "#93a87f") +
  geom_line(colour = "#275139", linewidth = 0.8) +
  geom_point(size = 2.6, colour = "#275139") +
  geom_text(aes(label = sprintf("%.1f%% cut", pct_visits_cut),
                hjust = ifelse(fc$cap == max(fc$cap), 0.5, 0.1),
                vjust = ifelse(fc$cap == max(fc$cap), -1.2, 1.9)),
            size = 3.1, colour = "#5d6b61") +
  annotate("text", x = 6, y = Dtrue * 1.03, hjust = 0, size = 3.3, colour = "#46604a",
           label = "true density") +
  scale_x_log10(breaks = fc$cap, expand = expansion(mult = c(0.05, 0.10))) +
  coord_cartesian(ylim = c(0, Dtrue * 1.12)) +
  labs(x = "maximum recording length (s)", y = "estimated density (per m2)") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- censor-fit ----
library(survival)
fams <- c("exponential", "weibull", "lognormal", "loglogistic")
fam_mean <- function(fit, dist) {                  # mean of the fitted distribution
  m <- unname(coef(fit)); s <- fit$scale
  switch(dist, exponential = exp(m), weibull = exp(m) * gamma(1 + s),
         lognormal = exp(m + s^2 / 2),
         loglogistic = if (s < 1) exp(m) * pi * s / sin(pi * s) else Inf)
}
mix_nll <- function(p, yo, yc) {                   # lognormal + exponential; yo seen to the end, yc cut
  w <- plogis(p[1]); s <- exp(p[3]); rt <- exp(p[4])
  dens <- (1 - w) * dlnorm(yo, p[2], s) + w * dexp(yo, rt)
  surv <- (1 - w) * plnorm(yc, p[2], s, lower.tail = FALSE) + w * pexp(yc, rt, lower.tail = FALSE)
  v <- -sum(log(pmax(dens, 1e-300))) - sum(log(pmax(surv, 1e-300)))
  if (is.finite(v)) v else 1e10
}
mix_fit <- function(y, d, which_starts = 1:6) {   # either part in either role, then a polish
  yo <- y[d == 1]; yc <- y[d == 0]; my <- log(median(y))
  starts <- list(c(-3, my, 0, log(1 / 30)), c(-2, my, -0.5, log(1 / 100)),    # 1-3: exponential long
                 c(-4, my, 0.3, log(1 / 300)), c(3, log(max(y)), 0, -my),      # 4-5: exponential short
                 c(3.5, log(max(y)) - 1, -0.5, -my), c(0.5, my, -1, -my))     # 6: both short
  fits <- lapply(starts[which_starts], function(st)
    optim(st, mix_nll, yo = yo, yc = yc, control = list(maxit = 2000)))
  p <- fits[[which.min(vapply(fits, `[[`, numeric(1), "value"))]]$par
  p <- optim(p, mix_nll, yo = yo, yc = yc, method = "BFGS")$par
  w <- plogis(p[1]); m_ln <- exp(p[2] + exp(p[3])^2 / 2); m_ex <- exp(-p[4])
  c(mean = (1 - w) * m_ln + w * m_ex, long_share = if (m_ex > m_ln) w else 1 - w,
    long_mean = max(m_ln, m_ex), nll = mix_nll(p, yo, yc))
}
to_truth <- function(m) lam_r * m / a_zone / Dtrue  # a mean stay as a ratio of density to truth

fit_caps <- c(10, 30, 60, 120)
fit_tab <- do.call(rbind, lapply(fit_caps, function(cap) {
  y <- pmin(gr$visits, cap); d <- as.integer(gr$visits < cap)
  fits <- lapply(fams, function(f) survreg(Surv(y, d) ~ 1, dist = f))
  best <- which.min(vapply(fits, AIC, numeric(1)))
  mx <- mix_fit(y, d)
  data.frame(setting = paste0(cap, " s"), truncated = to_truth(mean(y)), aic_family = fams[best],
             aic_best = to_truth(fam_mean(fits[[best]], fams[best])), mixture = to_truth(mx[["mean"]]),
             long_share = mx[["long_share"]], long_mean = mx[["long_mean"]], nll = mx[["nll"]])
}))
aic_same <- all(fit_tab$aic_family == fit_tab$aic_family[1])
fit_tab

## the 30 s fit again, started only with the exponential on the long stays
low30 <- mix_fit(pmin(gr$visits, 30), as.integer(gr$visits < 30), which_starts = 1:3)
c(low_peak_ratio = to_truth(low30[["mean"]]), nll_above_best = low30[["nll"]] - fit_tab$nll[2])

## the spread: resample animals, refit the mixture, compare with the uncapped mean
by_animal <- split(gr$visits, factor(rep(seq_len(nanim), gr$nvis), levels = seq_len(nanim)))
n_refit <- 50
set.seed(2704)
refit <- t(vapply(seq_len(n_refit), function(b) {
  xb <- unlist(by_animal[sample.int(nanim, nanim, replace = TRUE)], use.names = FALSE)
  c(no_limit = mean(xb),
    vapply(fit_caps[-1], function(cap) mix_fit(pmin(xb, cap), as.integer(xb < cap))[["mean"]], numeric(1)))
}, numeric(length(fit_caps))))
colnames(refit) <- c("no limit", paste0(fit_caps[-1], " s"))
refit_q <- apply(refit / W_r, 2, quantile, c(0.1, 0.5, 0.9, 1))
refit_q
