# Testing for circular uniformity
# https://tidyecology.com/posts/testing-for-circular-uniformity/
#
# 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-27

## ---- tests ----
circ_R <- function(th) sqrt(mean(cos(th))^2 + mean(sin(th))^2)

# Rayleigh: based on the resultant length; large R is evidence of a single direction
rayleigh_Z <- function(th) length(th) * circ_R(th)^2

# Rao's spacing: based on how evenly the gaps between sorted angles are spread
rao_U <- function(th) {
  n <- length(th); a <- sort(th %% (2 * pi))
  gaps <- c(diff(a), 2 * pi - (a[n] - a[1]))          # arcs between neighbours, wrap included
  0.5 * sum(abs(gaps - 2 * pi / n))
}

# Kuiper: a rotation-invariant Kolmogorov-Smirnov statistic on the circle
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 U-squared: a rotation-invariant Cramer-von Mises statistic
watson_U2 <- function(th) {
  n <- length(th); u <- sort((th %% (2 * pi)) / (2 * pi)); ubar <- mean(u); i <- 1:n
  sum((u - (2 * i - 1) / (2 * n))^2) + 1 / (12 * n) - n * (ubar - 0.5)^2
}

allstats <- function(th) c(Rayleigh = rayleigh_Z(th), Rao = rao_U(th),
                           Kuiper = kuiper_V(th), Watson = watson_U2(th))

## ---- 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")
}
comp_x <- function(b) sin(b); comp_y <- function(b) cos(b)
compass_base <- function() {
  ang <- seq(0, 2 * pi, length.out = 200); circ <- data.frame(x = cos(ang), y = sin(ang))
  ticks <- seq(0, 3 * pi / 2, by = pi / 2)
  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.20 * sin(ticks), y = 1.20 * cos(ticks), lab = c("N", "E", "S", "W"))
  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 = 3.0),
       coord_fixed(xlim = c(-1.32, 1.32), ylim = c(-1.32, 1.32)), 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)))
}
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
}
# a two-way axis: half the angles pointing one way, half the opposite way
raxial <- function(n, mu, kappa) { s <- rvm(n, mu, kappa); fl <- runif(n) < 0.5; s[fl] <- (s[fl] + pi) %% (2 * pi); s }

## ---- build-null ----
mc_null <- function(n, B, seed) { set.seed(seed); t(replicate(B, allstats(runif(n, 0, 2 * pi)))) }

n <- 60
null_dist <- mc_null(n, B = 5000, seed = 808)          # 5000 uniform samples of size 60
pvalue <- function(obs) sapply(seq_len(4), function(j) mean(null_dist[, j] >= obs[j]))

## ---- two-datasets ----
set.seed(4251)
unimodal <- rvm(n, mu = pi / 2, kappa = 1.2)
set.seed(4300)
axial    <- raxial(n, mu = pi / 2, kappa = 4)

p_uni <- pvalue(allstats(unimodal))
p_axi <- pvalue(allstats(axial))
round(rbind(unimodal = p_uni, axial = p_axi), 4)

## ---- fig-examples ----
mkpanel <- function(th, title, note, notecol) {
  jr <- 1 + (seq_along(th) %% 7) * 0.006
  d <- data.frame(x = jr * comp_x(th), y = jr * comp_y(th))
  ggplot() + compass_base() +
    geom_point(data = d, aes(x, y), colour = te_forest, size = 1.7, alpha = 0.75) +
    labs(title = title, caption = note) +
    theme(plot.caption = element_text(hjust = 0.5, colour = notecol, size = 8.2,
                                      lineheight = 1.15, margin = margin(t = 0, b = 2)))
}
pA <- mkpanel(unimodal, "Unimodal", "all four tests: reject", te_forest)
axial_word <- function(p) if (p < 0.05) "reject" else "miss"
axial_note <- sprintf("Rayleigh p = %.2f (%s)\nWatson p = %.4f (%s)",
                      p_axi[1], axial_word(p_axi[1]),
                      p_axi[4], axial_word(p_axi[4]))
pB <- mkpanel(axial, "Two-way axis", axial_note, te_rust)
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pA, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- power-table ----
crit <- apply(null_dist, 2, quantile, 0.95)               # 5% critical values from the shared null

power_for <- function(gen, B, seed) {
  set.seed(seed); S <- t(replicate(B, allstats(gen())))
  colMeans(sweep(S, 2, crit, ">="))
}
B <- 4000
size    <- power_for(function() runif(n, 0, 2 * pi), B, 5001)   # should sit near 0.05
pow_uni <- power_for(function() rvm(n, pi / 2, 1.0), B, 5002)   # single direction
pow_ax2 <- power_for(function() raxial(n, pi / 2, 2), B, 5003)  # weak two-way axis
pow_ax4 <- power_for(function() raxial(n, pi / 2, 4), B, 5004)  # strong two-way axis
round(rbind(size = size, unimodal = pow_uni, axis_k2 = pow_ax2, axis_k4 = pow_ax4), 3)

## ---- fig-power ----
GB <- 1500
kap_uni <- c(0.3, 0.5, 0.8, 1.2, 1.8, 2.5)
kap_axi <- c(1, 1.5, 2, 3, 4, 5)
curve_pow <- function(gen_of_k, kgrid, seed0) {
  do.call(rbind, lapply(seq_along(kgrid), function(ii) {
    set.seed(seed0 + ii); S <- t(replicate(GB, allstats(gen_of_k(kgrid[ii]))))
    data.frame(kappa = kgrid[ii], t(colMeans(sweep(S, 2, crit, ">="))))
  }))
}
uc <- curve_pow(function(k) rvm(n, pi / 2, k),    kap_uni, 6000)
ac <- curve_pow(function(k) raxial(n, pi / 2, k), kap_axi, 6100)
long <- function(df) {
  do.call(rbind, lapply(c("Rayleigh", "Rao", "Kuiper", "Watson"),
                        function(t) data.frame(kappa = df$kappa, test = t, power = df[[t]])))
}
cols <- c(Rayleigh = te_rust, Rao = te_amber, Kuiper = te_slate, Watson = te_forest)
mkpow <- function(df, ttl) {
  ggplot(long(df), aes(kappa, power, colour = test)) +
    geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_line) +
    geom_line(linewidth = 0.8) + geom_point(size = 1.6) +
    scale_colour_manual(values = cols) + ylim(0, 1) +
    labs(title = ttl, x = "concentration kappa", y = "power at 5%") +
    theme_te(11) + theme(legend.position = "inside", legend.position.inside = c(0.98, 0.35), legend.justification = c(1, 0.5),
                         legend.title = element_blank(), legend.text = element_text(size = 7),
                         legend.key.size = unit(0.35, "cm"),
                         legend.background = element_rect(fill = "white", colour = NA))
}
pP <- mkpow(uc, "Single preferred direction")
pQ <- mkpow(ac, "Two-way axis")
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pP, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pQ, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
