# Neutral theory in R: theta and the Ewens formula
# https://tidyecology.com/posts/neutral-theory-and-the-ewens-formula/
#
# 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-07

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

## ---- hoppe ----
sim_esf <- function(theta, J) {
  sp <- integer(J); sp[1] <- 1L; nsp <- 1L
  for (k in 1:(J - 1)) {
    if (runif(1) < theta / (theta + k)) {            # new species
      nsp <- nsp + 1L; sp[k + 1] <- nsp
    } else {                                          # a copy of an existing individual
      sp[k + 1] <- sp[sample.int(k, 1)]
    }
  }
  as.integer(table(sp))
}
sim_esf(theta = 5, J = 20)

## ---- esf ----
lpoch <- function(x, n) if (n == 0) 0 else sum(log(x + 0:(n - 1)))   # rising factorial

esf_loglik <- function(n, theta) {
  J <- sum(n); S <- length(n)
  phi <- as.numeric(table(n))
  const <- lfactorial(J) - sum(log(n)) - sum(lfactorial(phi))
  const + S * log(theta) - lpoch(theta, J)
}

## ---- norm ----
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
}
P6 <- parts(6)
tot <- sapply(c(0.5, 2, 10), function(th) sum(sapply(P6, function(n) exp(esf_loglik(n, th)))))
n_p6 <- length(P6)
signif(tot, 12)

## ---- suff ----
J <- 200
even   <- rep(10L, 20)                                  # every species 10 individuals
uneven <- c(100L, 48L, 24L, 12L, rep(1L, 16))           # one species is half the sample
c(J_even = sum(even), S_even = length(even), J_uneven = sum(uneven), S_uneven = length(uneven))
simpson <- function(n) 1 - sum((n / sum(n))^2)
ev_simp <- simpson(even); un_simp <- simpson(uneven)
round(c(Simpson_even = ev_simp, Simpson_uneven = un_simp,
        dominance_even = max(even) / J, dominance_uneven = max(uneven) / J), 3)

## ---- mle ----
ES <- function(theta, J) theta * (digamma(theta + J) - digamma(theta))
theta_mle <- function(S, J) uniroot(function(th) ES(th, J) - S, c(1e-8, 1e6), tol = 1e-10)$root

th_even   <- theta_mle(length(even),   sum(even))
th_uneven <- theta_mle(length(uneven), sum(uneven))
c(theta_even = th_even, theta_uneven = th_uneven, difference = abs(th_even - th_uneven))

## ---- suffgrid ----
grid <- seq(1, 60, length.out = 400)
gap  <- sapply(grid, function(x) esf_loglik(even, x) - esf_loglik(uneven, x))
gap_sd <- sd(gap)
sci_tex <- function(x, d = 1) {                       # readable exponent form for the prose
  e <- floor(log10(abs(x))); sprintf("$%.*f \\times 10^{%d}$", d, x / 10^e, e)
}
c(min_gap = min(gap), max_gap = max(gap), sd_gap = gap_sd)

## ---- fig-suff ----
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"))
}
rad <- rbind(
  data.frame(rank = seq_along(even),   abund = sort(even, decreasing = TRUE),   set = "even"),
  data.frame(rank = seq_along(uneven), abund = sort(uneven, decreasing = TRUE), set = "uneven"))
p1 <- ggplot(rad, aes(rank, abund, colour = set)) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.8) +
  scale_y_log10() +
  scale_colour_manual(values = c(even = "#2f8f63", uneven = "#b5534e")) +
  labs(x = "species rank", y = "abundance (log scale)",
       title = "Same richness, same sample size, different shape") + theme_te()
lk <- data.frame(theta = grid,
                 ll = sapply(grid, function(x) length(even) * log(x) - lpoch(x, J)))
lk$ll <- lk$ll - max(lk$ll)
p2 <- ggplot(lk, aes(theta, ll)) +
  geom_line(linewidth = 1, colour = "#275139") +
  geom_vline(xintercept = th_even, linetype = "dashed", colour = "#cda23f", linewidth = 0.8) +
  coord_cartesian(ylim = c(-6, 0.3)) +
  labs(x = expression(theta), y = "relative log-likelihood",
       title = "One curve, both samples",
       subtitle = sprintf("maximum at theta = %.2f for each", th_even)) + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1)))
print(p1, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- calib ----
theta_ci <- function(S, J) {
  part <- function(x) S * log(x) - lpoch(x, J)
  th <- theta_mle(S, J); mx <- part(th)
  f <- function(x) part(x) - mx + qchisq(0.95, 1) / 2
  c(uniroot(f, c(1e-6, th))$root, uniroot(f, c(th, 1e5))$root)
}
th_true <- 5.5; B <- 2000
mc <- t(replicate(B, {
  x <- sim_esf(th_true, J); S <- length(x)
  c(theta_mle(S, J), theta_ci(S, J))
}))
cal_mean <- mean(mc[, 1]); cal_med <- median(mc[, 1])
cal_cov  <- mean(mc[, 2] <= th_true & mc[, 3] >= th_true)
round(c(true = th_true, mean_est = cal_mean, median_est = cal_med, coverage = cal_cov), 3)

## ---- ci ----
ci20 <- theta_ci(20, 200)
round(c(lower = ci20[1], mle = th_even, upper = ci20[2]), 2)

## ---- logseries ----
Ephi <- function(theta, J, j) exp(log(theta) - log(j) + lfactorial(J) - lfactorial(J - j) +
                                    lgamma(theta + J - j) - lgamma(theta + J))
lser <- function(theta, J, j) theta * (J / (theta + J))^j / j
jj <- 1:12
cmp <- data.frame(j = jj, exact = Ephi(5.5, 200, jj), log_series = lser(5.5, 200, jj))
cmp$pct_gap <- 100 * (cmp$log_series / cmp$exact - 1)
sum_phi <- sum(Ephi(5.5, 200, 1:200)); es55 <- ES(5.5, 200)
round(cmp, 4)

## ---- fig-ls ----
ld <- rbind(data.frame(j = jj, v = cmp$exact, k = "Ewens, exact"),
            data.frame(j = jj, v = cmp$log_series, k = "Fisher log-series"))
ggplot(ld, aes(j, v, colour = k, shape = k)) +
  geom_line(linewidth = 0.8) + geom_point(size = 2.2) +
  scale_colour_manual(values = c("Ewens, exact" = "#275139", "Fisher log-series" = "#cda23f")) +
  scale_x_continuous(breaks = jj) +
  labs(x = "individuals per species (j)", y = expression(E * "[" * Phi[j] * "]"),
       title = "Why moth catches look log-series",
       subtitle = "the neutral metacommunity produces the shape Fisher only described") +
  theme_te()

## ---- nonid ----
JM <- c(1e6, 1e9, 1e12)
data.frame(J_M = format(JM, scientific = TRUE),
           nu_implied = signif(th_even / (2 * JM), 3),
           theta = th_even / (2 * JM) * 2 * JM)
