# Activity patterns and temporal overlap
# https://tidyecology.com/posts/activity-patterns-and-temporal-overlap/
#
# 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-30

## ---- setup ----
library(ggplot2)
library(grid)
te_forest <- "#275139"; te_paper <- "#f5f4ee"; te_ink <- "#16241d"
te_body <- "#2c3a31"; te_line <- "#dad9ca"; te_sage <- "#93a87f"; te_label <- "#46604a"
te_amber <- "#cda23f"; te_rust <- "#b5534e"; te_slate <- "#5d6b61"
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(plot.title = element_text(colour = te_ink, face = "bold", size = rel(1.0)),
          plot.subtitle = element_text(colour = te_label, size = rel(0.85)),
          axis.title = element_text(colour = te_body), axis.text = element_text(colour = te_body),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA), legend.position = "none")
}
# von Mises sampler for the synthetic detections
rvm <- function(n, mu, kappa) {
  out <- numeric(n); a <- 1 + sqrt(1 + 4 * kappa^2); b <- (a - sqrt(2 * a)) / (2 * kappa)
  r <- (1 + b^2) / (2 * b); i <- 0
  while (i < n) { u1 <- runif(1); z <- cos(pi * u1); f <- (1 + r * z) / (r + z); c1 <- kappa * (r - f); u2 <- runif(1)
    if (c1 * (2 - c1) - u2 > 0 || log(c1 / u2) + 1 - c1 >= 0) {
      u3 <- runif(1); i <- i + 1; out[i] <- (mu + sign(u3 - 0.5) * acos(f)) %% (2 * pi) } }
  out
}
rmix <- function(n, mus, kappas, w) { k <- sample(seq_along(mus), n, TRUE, w)
  vapply(seq_len(n), function(i) rvm(1, mus[k[i]], kappas[k[i]]), numeric(1)) }
clock24 <- function(h) {                       # a 24-hour clock face with midnight at top
  ang <- seq(0, 2 * pi, length.out = 200); circ <- data.frame(x = cos(ang), y = sin(ang))
  ticks <- seq(0, 2 * pi * 18 / 24, by = 2 * pi * 6 / 24)
  tk <- data.frame(x0 = 0.98 * sin(ticks), y0 = 0.98 * cos(ticks),
                   x1 = 1.06 * sin(ticks), y1 = 1.06 * cos(ticks))
  lab <- data.frame(x = 1.18 * sin(ticks), y = 1.18 * cos(ticks), lab = c("00", "06", "12", "18"))
  list(geom_path(data = circ, aes(x, y), colour = te_line, linewidth = 0.5),
       geom_segment(data = tk, aes(x = x0, y = y0, xend = x1, yend = y1), colour = te_sage, linewidth = 0.5),
       geom_text(data = lab, aes(x, y, label = lab), colour = te_label, size = 2.9),
       coord_fixed(xlim = c(-1.3, 1.3), ylim = c(-1.3, 1.3)), theme_void(),
       theme(plot.title = element_text(colour = te_ink, face = "bold", size = 11, hjust = 0.5),
             plot.background = element_rect(fill = "#f5f4ee", colour = NA)))
}

## ---- times ----
hour2rad <- function(h) 2 * pi * h / 24
rad2hour <- function(r) (r %% (2 * pi)) * 24 / (2 * pi)

# two synthetic species: A nocturnal (one peak at midnight), B crepuscular (dawn and dusk peaks)
set.seed(4252)
A <- rvm(120, mu = hour2rad(0), kappa = 2)                                   # 120 detections
B <- rmix(100, mus = hour2rad(c(6, 18)), kappas = c(4, 4), w = c(0.5, 0.5))  # 100 detections

## ---- kde ----
dvm  <- function(x, mu, kappa) exp(kappa * cos(x - mu)) / (2 * pi * besselI(kappa, 0))

ckde <- function(eval, data, kappa_bw) {           # von Mises kernel density
  sapply(eval, function(e) mean(dvm(e, data, kappa_bw)))
}

kappa_bw <- 20                                     # smoothing concentration (about a one-hour kernel)
grid <- seq(0, 2 * pi, length.out = 512)
fA <- ckde(grid, A, kappa_bw)
fB <- ckde(grid, B, kappa_bw)

## ---- overlap ----
overlap_D1 <- function(A, B, kappa_bw, ngrid = 512) {   # grid estimator, for small samples
  g <- seq(0, 2 * pi, length.out = ngrid + 1)[-(ngrid + 1)]; dg <- 2 * pi / ngrid
  sum(pmin(ckde(g, A, kappa_bw), ckde(g, B, kappa_bw))) * dg
}
overlap_D4 <- function(A, B, kappa_bw) {                # data-point estimator, for larger samples
  0.5 * (mean(pmin(1, ckde(A, B, kappa_bw) / ckde(A, A, kappa_bw))) +
         mean(pmin(1, ckde(B, A, kappa_bw) / ckde(B, B, kappa_bw))))
}

D1 <- overlap_D1(A, B, kappa_bw)
D4 <- overlap_D4(A, B, kappa_bw)
round(c(Dhat1 = D1, Dhat4 = D4), 3)

## ---- fig-activity ----
jit <- function(x) 1 + (seq_along(x) %% 7) * 0.006
dA <- data.frame(x = jit(A) * sin(A), y = jit(A) * cos(A))
dB <- data.frame(x = jit(B) * sin(B), y = jit(B) * cos(B))
sp_cols <- c("species A (nocturnal)" = te_forest, "species B (crepuscular)" = te_amber)
sp_key <- list(scale_colour_manual(values = sp_cols, name = NULL),
               theme(legend.position = "top",
                     legend.text = element_text(colour = te_body, size = 8.5)))
pClock <- ggplot() + clock24() +
  geom_point(data = dA, aes(x, y, colour = names(sp_cols)[1]), size = 1.5, alpha = 0.75) +
  geom_point(data = dB, aes(x, y, colour = names(sp_cols)[2]), size = 1.5, alpha = 0.8) +
  guides(colour = guide_legend(override.aes = list(size = 2.2, alpha = 1))) +
  sp_key +
  ggtitle("Detection times (24 h clock)")

hh <- rad2hour(grid); ord <- order(hh)
dens <- data.frame(hour = hh[ord], fa = fA[ord], fb = fB[ord])
dens$lo <- pmin(dens$fa, dens$fb)
pDens <- ggplot(dens, aes(hour)) +
  geom_ribbon(aes(ymin = 0, ymax = lo), fill = te_slate, alpha = 0.35) +
  geom_line(aes(y = fa, colour = names(sp_cols)[1]), linewidth = 0.9) +
  geom_line(aes(y = fb, colour = names(sp_cols)[2]), linewidth = 0.9) +
  annotate("text", x = 12, y = max(dens$fa) * 0.92, label = sprintf("overlap = %.2f", D1),
           colour = te_ink, size = 3.2) +
  scale_x_continuous(breaks = c(0, 6, 12, 18, 24), limits = c(0, 24)) +
  labs(title = "Activity densities and their overlap", x = "hour of day", y = "activity density") +
  theme_te(11) + sp_key

grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pClock, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pDens, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- bootstrap ----
set.seed(11)
Dboot <- replicate(2000, {
  a <- sample(A, replace = TRUE); b <- sample(B, replace = TRUE)
  overlap_D1(a, b, kappa_bw, ngrid = 256)
})
ci <- quantile(Dboot, c(0.025, 0.975))
round(c(estimate = D1, lower = ci[[1]], upper = ci[[2]]), 3)

## ---- camera-bootstrap ----
cam_G <- 128
cam_mid <- (seq_len(cam_G) - 0.5) * 2 * pi / cam_G
cam_K <- outer(cam_mid, cam_mid, dvm, kappa = kappa_bw)         # kernel matrix, same bandwidth
cam_bin <- function(x) tabulate(floor((x %% (2 * pi)) / (2 * pi) * cam_G) + 1, cam_G)
cam_ovl <- function(ca, cb) {                                   # one overlap per column of bin counts
  colSums(pmin(cam_K %*% sweep(ca, 2, colSums(ca), "/"),
               cam_K %*% sweep(cb, 2, colSums(cb), "/"))) * 2 * pi / cam_G
}
stopifnot(abs(cam_ovl(cbind(cam_bin(A)), cbind(cam_bin(B))) - D1) < 0.005)

cam_study <- function(n_cam, sd_cam, shared, n_boot = 199) {
  sA <- rnorm(n_cam, 0, sd_cam); sB <- if (shared) sA else rnorm(n_cam, 0, sd_cam)
  nA <- rnbinom(n_cam, size = 1, mu = 120 / n_cam); nB <- rnbinom(n_cam, size = 1, mu = 100 / n_cam)
  MA <- sapply(seq_len(n_cam), function(k) cam_bin(rvm(nA[k], hour2rad(0) + sA[k], 2)))
  MB <- sapply(seq_len(n_cam), function(k)
    cam_bin(rmix(nB[k], hour2rad(c(6, 18)) + sB[k], c(4, 4), c(0.5, 0.5))))
  ca <- rowSums(MA); cb <- rowSums(MB)
  det_bt <- cam_ovl(rmultinom(n_boot, sum(ca), ca), rmultinom(n_boot, sum(cb), cb))
  W <- rmultinom(n_boot, n_cam, rep(1, n_cam))                  # times each camera is drawn
  lost <- colSums(MA %*% W) == 0 | colSums(MB %*% W) == 0
  while (any(lost)) {                                           # redraw resamples that lose a species
    W[, lost] <- rmultinom(sum(lost), n_cam, rep(1, n_cam))
    lost <- colSums(MA %*% W) == 0 | colSums(MB %*% W) == 0
  }
  cam_bt <- cam_ovl(MA %*% W, MB %*% W)
  c(est = cam_ovl(cbind(ca), cbind(cb))[[1]], det_se = sd(det_bt), cam_se = sd(cam_bt),
    eff = sum(nA)^2 / sum(nA^2),                                # effective number of cameras, species A
    det_lo = quantile(det_bt, 0.025, names = FALSE), det_hi = quantile(det_bt, 0.975, names = FALSE),
    cam_lo = quantile(cam_bt, 0.025, names = FALSE), cam_hi = quantile(cam_bt, 0.975, names = FALSE))
}

cam_R <- 1500                                                   # simulated studies per scenario
cam_scen <- data.frame(cameras = c(25, 25, 25, 25, 12), sd_cam = c(0, 0.3, 0.6, 0.6, 0.6),
                       shift = c("none", "shared", "shared", "independent", "shared"))
set.seed(4253)
cam_out <- t(sapply(seq_len(nrow(cam_scen)), function(i) {
  r <- replicate(cam_R, cam_study(cam_scen$cameras[i], cam_scen$sd_cam[i],
                                  cam_scen$shift[i] != "independent"))
  m <- mean(r["est", ]); s <- sd(r["est", ])
  c(mean_overlap = m, det_ratio = mean(r["det_se", ]) / s, cam_ratio = mean(r["cam_se", ]) / s,
    det_cover = mean(r["det_lo", ] <= m & r["det_hi", ] >= m),
    cam_cover = mean(r["cam_lo", ] <= m & r["cam_hi", ] >= m), eff_cameras = mean(r["eff", ]))
}))
cam_mcz <- function(ratio) (1 - ratio) / (ratio / sqrt(2 * (cam_R - 1)))   # distance below 1 in MC errors
cam_covz <- function(p0, p) (p0 - p) / sqrt((p0 * (1 - p0) + p * (1 - p)) / cam_R)  # coverage gap in MC errors
cbind(cam_scen, shift_hours = round(cam_scen$sd_cam * 24 / (2 * pi), 1), round(cam_out, 2))

## ---- bandwidth ----
sapply(c(5, 10, 20, 40, 80), function(k) round(overlap_D1(A, B, k), 3))

## ---- same-activity ----
# sample size: 200 studies of two species with identical activity (species A's curve),
# 30 detections each, scored with the same two estimators and bandwidth as above
set.seed(530)
same_act <- replicate(200, {
  a30 <- rvm(30, mu = hour2rad(0), kappa = 2); b30 <- rvm(30, mu = hour2rad(0), kappa = 2)
  c(Dhat4 = overlap_D4(a30, b30, kappa_bw), Dhat1 = overlap_D1(a30, b30, kappa_bw, ngrid = 256))
})
round(rowMeans(same_act), 3)
# the same identical pair at this post's own sample sizes, 120 and 100 detections
set.seed(531)
same_own <- replicate(200, {
  a_own <- rvm(120, mu = hour2rad(0), kappa = 2); b_own <- rvm(100, mu = hour2rad(0), kappa = 2)
  c(Dhat4 = overlap_D4(a_own, b_own, kappa_bw), Dhat1 = overlap_D1(a_own, b_own, kappa_bw, ngrid = 256))
})
round(rowMeans(same_own), 3)

## ---- fig-uncertainty ----
dboot <- data.frame(D = Dboot)
pBoot <- ggplot(dboot, aes(D)) +
  geom_histogram(bins = 40, fill = te_sage, colour = "white", linewidth = 0.2) +
  geom_vline(xintercept = D1, colour = te_ink, linewidth = 0.8) +
  geom_vline(xintercept = ci, colour = te_rust, linetype = "dashed", linewidth = 0.7) +
  labs(title = "Bootstrap distribution of the overlap", x = "overlap estimate", y = "count") +
  theme_te(11)

kseq <- c(3, 5, 8, 12, 20, 32, 50, 80, 120)
bw_curve <- data.frame(kappa_bw = kseq, D = sapply(kseq, function(k) overlap_D1(A, B, k)))
pBW <- ggplot(bw_curve, aes(kappa_bw, D)) +
  geom_line(colour = te_forest, linewidth = 0.8) + geom_point(colour = te_forest, size = 1.7) +
  geom_point(data = subset(bw_curve, kappa_bw == 20), colour = te_rust, size = 2.6) +
  annotate("text", x = 20, y = bw_curve$D[bw_curve$kappa_bw == 20] + 0.02, label = "chosen", colour = te_rust, size = 2.8) +
  labs(title = "Overlap depends on the bandwidth", x = "kernel concentration (bandwidth)", y = "overlap estimate") +
  theme_te(11)

grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pBoot, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pBW, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
