# Checking a neutral model fit
# https://tidyecology.com/posts/checking-a-neutral-model-fit/
#
# 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(299)

## ---- machinery ----
ES <- function(theta, J) theta * (digamma(theta + J) - digamma(theta))
theta_mle <- function(S, J) {
  if (S <= 1 || S >= J) return(NA_real_)
  uniroot(function(th) ES(th, J) - S, c(1e-8, 1e6), tol = 1e-10)$root
}
lpoch <- function(x, n) if (n == 0) 0 else sum(log(x + 0:(n - 1)))
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
}
conv_direct <- function(a, b) {
  if (length(a) > length(b)) { tmp <- a; a <- b; b <- tmp }
  r <- numeric(length(a) + length(b) - 1)
  for (i in seq_along(a)) r[i + seq_along(b) - 1] <- r[i + seq_along(b) - 1] + a[i] * b
  r
}
logK <- function(n, LS) {
  S <- length(n); Jn <- sum(n); cur <- 1; off <- 0
  for (i in seq_len(S)) {
    a <- 1:n[i]
    lv <- LS[n[i] + 1, a + 1] + lgamma(a) - lgamma(n[i])
    M <- max(lv); off <- off + M
    cur <- conv_direct(cur, exp(lv - M))
    m2 <- max(cur); cur <- cur / m2; off <- off + log(m2)
  }
  out <- rep(-Inf, Jn + 1); out[(S:Jn) + 1] <- log(pmax(cur[(S:Jn) - S + 1], 0)) + off; out
}
etienne_loglik <- function(n, theta, I, LK) {
  Jn <- sum(n); S <- length(n)
  const <- lfactorial(Jn) - sum(log(n)) - sum(lfactorial(as.numeric(table(n))))
  A <- S:Jn; lpt <- cumsum(log(theta + 0:(Jn - 1)))
  tt <- LK[A + 1] + S * log(theta) - lpt[A] + A * log(I)
  mx <- max(tt); const + mx + log(sum(exp(tt - mx))) - lpoch(I, Jn)
}
sim_etienne <- function(theta, I, J) {
  loc <- integer(J); anc <- integer(0); ns <- 0L
  for (k in 0:(J - 1)) {
    if (runif(1) < I / (I + k)) {
      A <- length(anc)
      if (A == 0 || runif(1) < theta / (theta + A)) { ns <- ns + 1L; s <- ns } else s <- anc[sample.int(A, 1)]
      anc <- c(anc, s); loc[k + 1] <- s
    } else loc[k + 1] <- loc[sample.int(k, 1)]
  }
  as.integer(table(loc))
}
m_to_I <- function(m, J) m * (J - 1) / (1 - m)

## ---- cicheck ----
fit2 <- function(n, LK) {
  Jn <- sum(n)
  nll <- function(p) -etienne_loglik(n, exp(p[1]), exp(p[2]), LK)
  starts <- expand.grid(log(c(5, 20, 80, 400)), log(c(5, 20, 80, 400)))   # the ridge can hold two peaks
  fits <- lapply(seq_len(nrow(starts)), function(i)
    optim(unname(unlist(starts[i, ])), nll, method = "Nelder-Mead", control = list(reltol = 1e-12, maxit = 3000)))
  f <- fits[[which.min(sapply(fits, `[[`, "value"))]]                    # keep the best of sixteen starts
  list(theta = exp(f$par[1]), I = exp(f$par[2]), m = exp(f$par[2]) / (exp(f$par[2]) + Jn - 1), logL = -f$value)
}
prof <- function(n, LK, th) -optimize(function(li) -etienne_loglik(n, th, exp(li), LK), c(log(0.05), log(1e6)))$objective

th0 <- 50; m0 <- 0.05; Jloc <- 1000; I0 <- m_to_I(m0, Jloc); Bci <- 200
CI <- t(sapply(1:Bci, function(b) {
  d <- sort(sim_etienne(th0, I0, Jloc), decreasing = TRUE)
  LK <- logK(d, log_stirling1(max(d))); f <- fit2(d, LK)
  cut <- f$logL - qchisq(0.95, 1) / 2
  g <- function(x) prof(d, LK, x) - cut
  c(theta = f$theta, m = f$m,
    lo = tryCatch(uniroot(g, c(1, f$theta))$root, error = function(e) 1),
    hi = tryCatch(uniroot(g, c(f$theta, 1e6))$root, error = function(e) Inf))
}))
cov <- mean(CI[, "lo"] <= th0 & CI[, "hi"] >= th0)
unb <- mean(CI[, "hi"] > 1e5)
wid <- median(log10(pmin(CI[, "hi"], 1e6) / CI[, "lo"]))
rho <- cor(log(CI[, "theta"]), log(CI[, "m"]))
round(c(median_theta = median(CI[, "theta"]), true_theta = th0,
        median_m = median(CI[, "m"]), true_m = m0,
        coverage = cov, unbounded_above = unb, median_width_orders = wid, cor_log_theta_log_m = rho), 4)

## ---- fig-ci ----
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"))
}
ci <- data.frame(lo = CI[, "lo"], hi = pmin(CI[, "hi"], 3000), open = CI[, "hi"] > 1e5)
ci <- ci[order(ci$lo), ]; ci$i <- seq_len(nrow(ci))
ggplot(ci) +
  geom_segment(aes(x = lo, xend = hi, y = i, yend = i, colour = open), linewidth = 0.4) +
  geom_vline(xintercept = th0, linetype = "dashed", colour = "#16241d", linewidth = 0.9) +
  scale_x_log10(breaks = c(1, 3, 10, 30, 100, 300, 1000, 3000)) +
  scale_colour_manual(values = c("FALSE" = "#2f8f63", "TRUE" = "#b5534e"),
                      labels = c("FALSE" = "bounded", "TRUE" = "no upper limit")) +
  labs(x = expression("95% profile interval for " * theta * " (log scale)"), y = "replicate, sorted",
       title = "Honest intervals, and what honesty costs",
       subtitle = sprintf("200 plots simulated at theta = 50, m = 0.05, J = 1000; %.0f%% have no ceiling",
                          100 * unb)) +
  theme_te()

## ---- nested ----
sim_esf_ind <- function(theta, J) {                       # individual labels, in random order
  sp <- integer(J); sp[1] <- 1L; ns <- 1L
  for (k in 1:(J - 1)) {
    if (runif(1) < theta / (theta + k)) { ns <- ns + 1L; sp[k + 1] <- ns } else sp[k + 1] <- sp[sample.int(k, 1)]
  }
  sp
}
sugihara <- function(Sp, f = 0.75) {
  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)
}
Js <- c(250, 500, 1000, 2000, 4000, 8000); Jmax <- 8000; Bd <- 150
nested <- function(gen) {
  R <- t(replicate(Bd, {
    ind <- gen()
    c(sapply(Js, function(j) theta_mle(length(unique(ind[1:j])), j)),
      sapply(Js, function(j) length(unique(ind[1:j]))))
  }))
  TH <- R[, 1:6]; SV <- R[, 7:12]
  pred <- ES(TH[, 1], Jmax)                               # theta fitted at J = 250, carried across for reference
  list(theta = apply(TH, 2, median), S = apply(SV, 2, median),
       ratio = median(TH[, 6] / TH[, 1]),
       pred = median(pred), obs = median(SV[, 6]),
       hit = mean(abs(SV[, 6] / pred - 1) < 0.10),
       err = SV[, 6] / pred - 1)                           # per-community error, to calibrate the check below
}
gens <- list(
  "neutral, theta = 15"     = function() sim_esf_ind(15, Jmax),
  "broken stick, pool 60"   = function() sample.int(60, Jmax, TRUE, prob = diff(sort(c(0, runif(59), 1)))),
  "Sugihara, pool 80"       = function() sample.int(80, Jmax, TRUE, prob = sugihara(80)),
  "Sugihara, pool 200"      = function() sample.int(200, Jmax, TRUE, prob = sugihara(200)))
NS <- lapply(gens, nested)
data.frame(model = names(gens),
           theta_at_250 = round(sapply(NS, function(z) z$theta[1]), 1),
           theta_at_8000 = round(sapply(NS, function(z) z$theta[6]), 1),
           ratio = round(sapply(NS, function(z) z$ratio), 2),
           predicted_S = round(sapply(NS, function(z) z$pred)),
           observed_S = round(sapply(NS, function(z) z$obs)),
           error = sprintf("%+.0f%%", 100 * (sapply(NS, function(z) z$pred / z$obs) - 1)),
           within_10pct = sprintf("%.0f%%", 100 * sapply(NS, function(z) z$hit)),
           row.names = NULL)

## ---- nsnum ----
er <- sapply(NS, function(z) 100 * (z$pred / z$obs - 1))
lim <- quantile(NS[[1]]$err, c(0.025, 0.975))              # central 95% of the neutral errors
nest_flag <- sapply(NS, function(z) mean(z$err < lim[1] | z$err > lim[2]))

## ---- fig-drift ----
dr <- do.call(rbind, lapply(names(NS), function(nm)
  data.frame(J = Js, theta = NS[[nm]]$theta, model = nm)))
ggplot(dr, aes(J, theta, colour = model, shape = model)) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.1) +
  scale_x_log10(breaks = Js) +
  scale_colour_manual(values = setNames(c("#275139", "#b5534e", "#cda23f", "#2f8f63"), names(NS))) +
  labs(x = "individuals in the nested subsample (log scale)", y = expression("median fitted " * theta),
       title = "Is theta a property of the community or of the quadrat?",
       subtitle = "same individuals throughout, only the subsample size changes") +
  theme_te() + guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2))

## ---- blind ----
FF <- function(n) sum((n / sum(n))^2)
sim_esf_ab <- function(theta, J) as.integer(table(sim_esf_ind(theta, J)))
J5 <- 500
NP <- do.call(rbind, lapply(c(10, 15, 22), function(th)
  t(replicate(20000, { x <- sim_esf_ab(th, J5); c(length(x), FF(x)) }))))
colnames(NP) <- c("S", "F")
ewens_test <- function(x) {
  nl <- NP[NP[, "S"] == length(x), "F"]
  if (length(nl) < 200) return(NA_real_)
  q <- mean(nl <= FF(x)); min(1, 2 * min(q, 1 - q))
}
draw <- function(p, J) { x <- as.integer(rmultinom(1, J, p)); x[x > 0] }
blind <- sapply(list(neutral = function() sim_esf_ab(11, J5),
                     sugihara80 = function() draw(sugihara(80), J5)),
                function(g) { pv <- replicate(300, ewens_test(g())); mean(pv[!is.na(pv)] < 0.05) })
round(c(exact_test_rejects_neutral = unname(blind["neutral"]),
        exact_test_rejects_sugihara80 = unname(blind["sugihara80"]),
        nested_check_error_pct_sugihara80 = unname(er[3]),
        nested_check_theta_ratio_sugihara80 = unname(NS[[3]]$ratio)), 4)

## ---- ident ----
d <- sort(sim_etienne(th0, I0, Jloc), decreasing = TRUE)
LKd <- logK(d, log_stirling1(max(d)))
f0 <- fit2(d, LKd)
prof_m <- function(th) {                                  # the best m for a given theta
  li <- optimize(function(l) -etienne_loglik(d, th, exp(l), LKd), c(log(0.05), log(1e6)))$minimum
  exp(li) / (exp(li) + Jloc - 1)
}
same <- data.frame(theta = f0$theta * c(1, 3, 10, 1000, 1 / 3, 1 / 10))
same$m_profiled <- round(sapply(same$theta, prof_m), 4)
same$logL_drop <- round(mapply(function(th, mm) etienne_loglik(d, th, m_to_I(mm, Jloc), LKd),
                              same$theta, same$m_profiled) - f0$logL, 3)
same$rejected_at_95 <- ifelse(same$logL_drop < -qchisq(0.95, 1) / 2, "yes", "no")
same$theta <- signif(same$theta, 4)
same
