# The exact Ewens test: is your SAD neutral?
# https://tidyecology.com/posts/testing-neutrality-with-the-ewens-test/
#
# 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-10-14

## ---- setup ----
library(ggplot2)
set.seed(298)

## ---- stirlingid ----
log_stirling1 <- function(N) {
  L <- matrix(-Inf, N + 1, N + 1); L[1, 1] <- 0
  for (n in 0:(N - 1)) for (k in 0:(n + 1)) {
    a <- if (k >= 1) L[n + 1, k] else -Inf
    b <- if (n >= 1) log(n) + L[n + 1, k + 1] else -Inf
    mx <- max(a, b)
    L[n + 2, k + 1] <- if (is.infinite(mx)) -Inf else mx + log(exp(a - mx) + exp(b - mx))
  }
  L
}
parts <- function(J, mx = J) {
  if (J == 0) return(list(integer(0)))
  out <- list(); for (k in min(J, mx):1) for (p in parts(J - k, k)) out[[length(out) + 1]] <- c(k, p)
  out
}
comb <- function(n) exp(lfactorial(sum(n)) - sum(log(n)) - sum(lfactorial(as.numeric(table(n)))))

chk <- do.call(rbind, lapply(6:8, function(J) {
  LS <- log_stirling1(J); P <- parts(J)
  do.call(rbind, lapply(2:4, function(S) {
    lhs <- sum(sapply(Filter(function(n) length(n) == S, P), comb))
    data.frame(J = J, S = S, partition_sum = lhs, stirling = exp(LS[J + 1, S + 1]))
  }))
}))
chk$gap <- chk$partition_sum - chk$stirling
chk

## ---- stat ----
FF <- function(n) sum((n / sum(n))^2)                    # Watterson's F
sim_esf <- function(theta, J) {                          # vectorised Hoppe urn
  k <- 1:(J - 1)
  new <- runif(J - 1) < theta / (theta + k)              # is individual k+1 a new species?
  par <- ceiling(runif(J - 1) * k)                       # whom to copy, if not new
  sp <- integer(J); sp[1] <- 1L; ns <- 1L
  for (i in seq_len(J - 1)) {
    if (new[i]) { ns <- ns + 1L; sp[i + 1] <- ns } else sp[i + 1] <- sp[par[i]]
  }
  tabulate(sp, ns)
}
J <- 500

## ---- nullpool ----
t0 <- proc.time()[3]
NP <- do.call(rbind, lapply(c(8, 12, 16, 20, 26), function(th)
  t(replicate(30000, { x <- sim_esf(th, J); c(length(x), FF(x)) }))))
colnames(NP) <- c("S", "F")
np_time <- proc.time()[3] - t0
bins <- table(NP[, "S"])
c(draws = nrow(NP), seconds = round(np_time), S_min = min(NP[, "S"]), S_max = max(NP[, "S"]),
  smallest_bin_in_40_to_70 = min(bins[names(bins) %in% 40:70]))

## ---- invariance ----
src_theta <- rep(c(8, 12, 16, 20, 26), each = 30000)
kstest <- function(x, y) { k <- suppressWarnings(ks.test(x, y)); c(n1 = length(x), n2 = length(y),
                                                                   D = unname(k$statistic), p = k$p.value) }
exact <- NP[, "S"] == 54                                  # EXACTLY one S
range9 <- NP[, "S"] %in% 50:58                            # an S-range: a trap, see below
inv <- rbind(
  "S = 54 exactly"   = kstest(NP[exact & src_theta == 12, "F"],  NP[exact & src_theta == 20, "F"]),
  "S in 50:58"       = kstest(NP[range9 & src_theta == 12, "F"], NP[range9 & src_theta == 20, "F"]),
  "not conditioned"  = kstest(NP[src_theta == 12, "F"],          NP[src_theta == 20, "F"]))
data.frame(round(inv[, 1:3], 4), p = signif(inv[, 4], 3))

## ---- invnum ----
cond_p <- inv["S = 54 exactly", "p"]; unc_D <- inv["not conditioned", "D"]
rng_p  <- inv["S in 50:58", "p"];     rng_D <- inv["S in 50:58", "D"]

## ---- gens ----
brokenstick <- function(Sp) diff(sort(c(0, runif(Sp - 1), 1)))        # MacArthur 1957
preemption  <- function(Sp, k) { p <- k * (1 - k)^(0:(Sp - 1)); p / sum(p) }   # geometric series, after Motomura
sugihara <- function(Sp, f = 0.75) {                                  # Sugihara 1980
  seg <- 1
  while (length(seg) < Sp) {
    i <- sample.int(length(seg), 1); s <- seg[i]
    g <- if (runif(1) < 0.5) f else 1 - f
    seg <- c(seg[-i], s * g, s * (1 - g))
  }
  seg / sum(seg)
}
draw <- function(p, J) { x <- as.integer(rmultinom(1, J, p)); x[x > 0] }

## ---- power ----
B <- 500                                                  # replicates per generator
gens <- list(
  "neutral (theta = 15)"   = function() sim_esf(15, J),
  "broken stick (pool 60)" = function() draw(brokenstick(60), J),
  "preemption (k = 0.08)"  = function() draw(preemption(300, 0.08), J),
  "Sugihara (pool 110)"    = function() draw(sugihara(110), J))
res <- do.call(rbind, lapply(names(gens), function(nm) {
  R <- t(replicate(B, { x <- gens[[nm]](); nl <- NP[NP[, "S"] == length(x), "F"]
    c(S = length(x), Fo = FF(x), q = if (length(nl) < 200) NA else mean(nl <= FF(x))) }))
  ok <- !is.na(R[, "q"]); q <- R[ok, "q"]; p <- pmin(1, 2 * pmin(q, 1 - q))
  data.frame(model = nm, median_S = median(R[, "S"]), median_F = round(median(R[, "Fo"]), 4),
             rejected = sprintf("%.1f%%", 100 * mean(p < 0.05)),
             too_even = sprintf("%.1f%%", 100 * mean(p < 0.05 & q < 0.5)),
             too_uneven = sprintf("%.1f%%", 100 * mean(p < 0.05 & q >= 0.5)))
}))
res

## ---- pownum ----
mf <- setNames(res$median_F, c("neu", "bs", "pre", "sug"))
mcse <- sqrt(0.05 * 0.95 / B)

## ---- geom ----
p8 <- preemption(300, 0.08)
c(first_species_share = p8[1], F_analytic = sum(p8^2), F_broken_stick_expected = 2 / 61)

## ---- fig-null ----
theme_te <- function(base_size = 11) {
  theme_minimal(base_size = base_size) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#46604a", size = rel(0.9)),
          axis.text = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold", size = rel(1.05)),
          plot.subtitle = element_text(colour = "#5d6b61", size = rel(0.9)),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          legend.position = "bottom", legend.title = element_blank(),
          strip.text = element_text(colour = "#275139", face = "bold"))
}
nl52 <- NP[NP[, "S"] == 52, "F"]
mk <- data.frame(F = as.numeric(res$median_F), model = res$model)
ggplot(data.frame(F = nl52), aes(F)) +
  geom_histogram(bins = 60, fill = "#c9d4ab", colour = "#93a87f", linewidth = 0.2) +
  geom_vline(data = mk, aes(xintercept = F, colour = model), linewidth = 1.1) +
  scale_colour_manual(values = setNames(c("#275139", "#2f8f63", "#cda23f", "#b5534e"), res$model)) +
  labs(x = "Watterson's F (sum of squared relative abundances)", y = "null draws",
       title = "Where the niche models land",
       subtitle = sprintf("neutral null at S = 52, J = 500 (%d draws); markers are median observed F", length(nl52))) +
  theme_te() + guides(colour = guide_legend(nrow = 2))

## ---- sweep ----
J2 <- 2000; Sp2 <- 110                                    # same pool as at J = 500: only J changes
NP2 <- do.call(rbind, lapply(c(10, 15, 22), function(th)
  t(replicate(12000, { x <- sim_esf(th, J2); c(length(x), FF(x)) }))))
colnames(NP2) <- c("S", "F")
q2 <- replicate(300, { x <- draw(sugihara(Sp2), J2); nl <- NP2[NP2[, "S"] == length(x), "F"]
  if (length(nl) < 150) NA else mean(nl <= FF(x)) })
q2 <- q2[!is.na(q2)]
rej2 <- mean(pmin(1, 2 * pmin(q2, 1 - q2)) < 0.05)
data.frame(J = c(J, J2), pool = c(110, Sp2), tested = c(B, length(q2)),
           rejected = c(res$rejected[4], sprintf("%.1f%%", 100 * rej2)))
