# Checking a circular analysis
# https://tidyecology.com/posts/checking-a-circular-analysis/
#
# 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-14

## ---- 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")
}
circ_mean <- function(t) atan2(mean(sin(t)), mean(cos(t)))
circ_R    <- function(t) sqrt(mean(cos(t))^2 + mean(sin(t))^2)
A_kappa   <- function(k) besselI(k, 1) / besselI(k, 0)
kappa_mle <- function(R) if (R < 1e-8) 0 else if (R > 0.999999) Inf else uniroot(function(k) A_kappa(k) - R, c(1e-6, 700))$root
kappa_bc  <- function(k, n) { if (!is.finite(k)) return(k); if (k < 2) return(max(k - 2 / (n * k), 0)); (n - 1)^3 * k / (n^3 + n) }
dvm <- function(x, mu, k) exp(k * cos(x - mu)) / (2 * pi * besselI(k, 0))
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
}
raxial <- function(n, mu, kappa) { s <- rvm(n, mu, kappa); fl <- runif(n) < 0.5; s[fl] <- (s[fl] + pi) %% (2 * pi); s }
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)) }
rayleigh_Z <- function(th) length(th) * circ_R(th)^2
rao_U <- function(th) { n <- length(th); a <- sort(th %% (2 * pi)); g <- c(diff(a), 2 * pi - (a[n] - a[1])); 0.5 * sum(abs(g - 2 * pi / n)) }
kuiper_V <- function(th) { n <- length(th); u <- sort((th %% (2 * pi)) / (2 * pi)); max((1:n) / n - u) + max(u - (0:(n - 1)) / n) }
watson_U2 <- function(th) { n <- length(th); u <- sort((th %% (2 * pi)) / (2 * pi)); ub <- mean(u); i <- 1:n; sum((u - (2 * i - 1) / (2 * n))^2) + 1 / (12 * n) - n * (ub - 0.5)^2 }
allstats <- function(th) c(Rayleigh = rayleigh_Z(th), Rao = rao_U(th), Kuiper = kuiper_V(th), Watson = watson_U2(th))
ckde <- function(eval, data, kbw) sapply(eval, function(e) mean(dvm(e, data, kbw)))

## ---- mean-dir ----
set.seed(4253)
unimodal <- rvm(60, mu = pi / 2, kappa = 2)   # one preferred direction
bimodal  <- raxial(60, mu = pi / 2, kappa = 4) # a two-way axis

boot_dir <- function(x, B = 2000) { set.seed(7); replicate(B, circ_mean(sample(x, replace = TRUE)) %% (2 * pi)) }
sd_deg <- function(ang) sqrt(-2 * log(circ_R(ang))) * 180 / pi
du <- boot_dir(unimodal); db <- boot_dir(bimodal)
c(unimodal_Rbar = circ_R(unimodal), bimodal_Rbar = circ_R(bimodal),
  unimodal_dir_SD = sd_deg(du), bimodal_dir_SD = sd_deg(db))

## ---- test-choice ----
set.seed(808)
null60 <- t(replicate(5000, allstats(runif(60, 0, 2 * pi))))
pvals <- sapply(1:4, function(j) mean(null60[, j] >= allstats(bimodal)[j]))
names(pvals) <- c("Rayleigh", "Rao", "Kuiper", "Watson")
round(pvals, 4)

## ---- fig-verdict ----
dird <- rbind(data.frame(deg = du * 180 / pi, grp = "unimodal"),
              data.frame(deg = db * 180 / pi, grp = "bimodal"))
pDir <- ggplot(dird, aes(deg, fill = grp, colour = grp)) +
  geom_density(alpha = 0.35, adjust = 0.6, linewidth = 0.6) +
  scale_fill_manual(values = c(unimodal = te_forest, bimodal = te_amber)) +
  scale_colour_manual(values = c(unimodal = te_forest, bimodal = te_amber)) +
  scale_x_continuous(breaks = c(0, 90, 180, 270, 360), limits = c(0, 360)) +
  labs(title = "Bootstrapped mean direction", x = "mean direction (degrees)", y = "density") +
  theme_te(11) + theme(legend.position = "inside", legend.position.inside = c(0.99, 0.9), legend.justification = c(1, 1),
                       legend.title = element_blank(), legend.text = element_text(size = 8),
                       legend.background = element_rect(fill = "white", colour = NA))
pbar <- data.frame(test = factor(names(pvals), levels = names(pvals)), p = as.numeric(pvals))
pP <- ggplot(pbar, aes(test, p, fill = p > 0.05)) +
  geom_col(width = 0.65) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_rust) +
  annotate("text", x = 3.5, y = 0.075, label = "5% level", colour = te_rust, size = 3) +
  scale_fill_manual(values = c(`TRUE` = te_amber, `FALSE` = te_forest)) +
  labs(title = "Uniformity p-value by test (bimodal sample)", x = NULL, y = "p-value") +
  theme_te(11)
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pDir, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pP, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- kappa-bias ----
kappa_true <- 2
kbias <- do.call(rbind, lapply(c(10, 15, 25, 50, 100), function(n) {
  set.seed(500 + n)
  est <- t(replicate(2500, { x <- rvm(n, 0, kappa_true); kh <- kappa_mle(circ_R(x)); c(kh, kappa_bc(kh, n)) }))
  data.frame(n = n, mle = mean(est[is.finite(est[, 1]), 1]), corrected = mean(est[is.finite(est[, 2]), 2]))
}))
round(kbias, 2)

## ---- overlap-bias ----
hour2rad <- function(h) 2 * pi * h / 24
fa <- function(t) dvm(t, hour2rad(0), 2)
fb <- function(t) 0.5 * dvm(t, hour2rad(6), 4) + 0.5 * dvm(t, hour2rad(18), 4)
gT <- seq(0, 2 * pi, length.out = 20001)[-20001]
D_true <- sum(pmin(fa(gT), fb(gT))) * (2 * pi / 20000)

oD4 <- function(A, B, kbw, ng = 256) { g <- seq(0, 2 * pi, length.out = ng + 1)[-(ng + 1)]
  sum(pmin(ckde(g, A, kbw), ckde(g, B, kbw))) * (2 * pi / ng) }
oD1 <- function(A, B, kbw) 0.5 * (mean(pmin(1, ckde(A, B, kbw) / ckde(A, A, kbw))) +
                                  mean(pmin(1, ckde(B, A, kbw) / ckde(B, B, kbw))))
kbw_adaptive <- function(n) 3.17 * n^0.4                 # tightens as n grows

obias <- do.call(rbind, lapply(c(20, 50, 100, 300), function(n) {
  set.seed(900 + n)
  res <- t(replicate(800, { A <- rvm(n, hour2rad(0), 2); B <- rmix(n, hour2rad(c(6, 18)), c(4, 4), c(0.5, 0.5))
    kb <- kbw_adaptive(n); c(oD4(A, B, kb), oD1(A, B, kb)) }))
  data.frame(n = n, Dhat4 = mean(res[, 1]), Dhat1 = mean(res[, 2]), SD4 = sd(res[, 1]))
}))
round(cbind(obias, true = D_true), 3)

## ---- fig-bias ----
kl <- rbind(data.frame(n = kbias$n, val = kbias$mle, est = "MLE"),
            data.frame(n = kbias$n, val = kbias$corrected, est = "bias-corrected"))
pK <- ggplot(kl, aes(n, val, colour = est)) +
  geom_hline(yintercept = kappa_true, linetype = "dashed", colour = te_line) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
  scale_colour_manual(values = c(MLE = te_rust, `bias-corrected` = te_forest)) +
  labs(title = "Concentration estimate vs sample size", x = "sample size n", y = "estimated kappa") +
  theme_te(11) + theme(legend.position = "inside", legend.position.inside = c(0.99, 0.99), legend.justification = c(1, 1),
                       legend.title = element_blank(), legend.text = element_text(size = 8),
                       legend.background = element_rect(fill = "white", colour = NA))
ol <- rbind(data.frame(n = obias$n, val = obias$Dhat4, est = "grid (Dhat4)"),
            data.frame(n = obias$n, val = obias$Dhat1, est = "data-point (Dhat1)"))
pO <- ggplot(ol, aes(n, val, colour = est)) +
  geom_hline(yintercept = D_true, linetype = "dashed", colour = te_line) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
  scale_colour_manual(values = c(`grid (Dhat4)` = te_rust, `data-point (Dhat1)` = te_forest)) +
  labs(title = "Overlap estimate vs sample size", x = "sample size n", y = "estimated overlap") +
  theme_te(11) + theme(legend.position = "inside", legend.position.inside = c(0.99, 0.99), legend.justification = c(1, 1),
                       legend.title = element_blank(), legend.text = element_text(size = 8),
                       legend.background = element_rect(fill = "white", colour = NA))
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pK, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pO, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
