# Dispersal limitation: fitting theta and m in R
# https://tidyecology.com/posts/dispersal-limitation-in-a-neutral-model/
#
# 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-04

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

## ---- urn ----
sim_etienne <- function(theta, I, J) {
  loc <- integer(J); anc <- integer(0); nsp <- 0L
  for (k in 0:(J - 1)) {
    if (runif(1) < I / (I + k)) {                       # immigration event
      A <- length(anc)
      if (A == 0 || runif(1) < theta / (theta + A)) {   # the immigrant is a new species
        nsp <- nsp + 1L; s <- nsp
      } else {                                          # the species of an earlier immigrant
        s <- anc[sample.int(A, 1)]
      }
      anc <- c(anc, s); loc[k + 1] <- s
    } else {                                            # local reproduction
      loc[k + 1] <- loc[sample.int(k, 1)]
    }
  }
  as.integer(table(loc))
}
m_to_I <- function(m, J) m * (J - 1) / (1 - m)
I_to_m <- function(I, J) I / (I + J - 1)

## ---- counts ----
ES <- function(theta, J) theta * (digamma(theta + J) - digamma(theta))
theta_true <- 50; m_true <- 0.05; J <- 1000
I_true <- m_to_I(m_true, J)
EA <- ES(I_true, J)                                     # expected number of immigration events
c(I = I_true, E_immigration_events = EA, E_S_from_those_events = ES(theta_true, EA),
  E_S_if_m_were_1 = ES(theta_true, J))

## ---- naive-one ----
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
}
d1 <- sort(sim_etienne(theta_true, I_true, J), decreasing = TRUE)
c(S_observed = length(d1), J = sum(d1), theta_naive = theta_mle(length(d1), J), theta_true = theta_true)

## ---- stirling ----
log_stirling1 <- function(N) {                          # log |s(n,k)|, n = 0..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
}
LS5 <- log_stirling1(5)
round(exp(LS5[6, 2:6]))                                 # s(5,k), k = 1..5

## ---- conv ----
conv_direct <- function(a, b) {
  if (length(a) > length(b)) { tmp <- a; a <- b; b <- tmp }   # loop over the shorter vector
  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])      # log s(n_i,a) + log(a-1)! - log(n_i-1)!
    M  <- max(lv); off <- off + M
    cur <- conv_direct(cur, exp(lv - M))
    m2 <- max(cur); cur <- cur / m2; off <- off + log(m2)     # renormalised at each step
  }
  out <- rep(-Inf, Jn + 1)                                    # index: A + 1
  out[(S:Jn) + 1] <- log(pmax(cur[(S:Jn) - S + 1], 0)) + off
  out
}

## ---- ktest ----
LK1 <- logK(d1, log_stirling1(max(d1)))
c(K_at_S = exp(LK1[length(d1) + 1]), K_at_J = exp(LK1[J + 1]))

## ---- etienne ----
lpoch <- function(x, n) if (n == 0) 0 else sum(log(x + 0:(n - 1)))
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)
}
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)))                # (theta)_A for every A, in one pass
  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)    # log-sum-exp
}
fit_etienne <- function(n) {
  Jn <- sum(n); LK <- logK(n, log_stirling1(max(n)))    # ONCE, before the optimisation
  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 = I_to_m(exp(f$par[2]), Jn), logL = -f$value)
}

## ---- echeck ----
parts <- function(Jn, mx = Jn) {
  if (Jn == 0) return(list(integer(0)))
  out <- list(); for (k in min(Jn, mx):1) for (p in parts(Jn - k, k)) out[[length(out) + 1]] <- c(k, p)
  out
}
P6 <- parts(6)
tot6 <- sapply(list(c(3, 8), c(20, 2)), function(pr)
  sum(sapply(P6, function(n) exp(etienne_loglik(n, pr[1], pr[2], logK(n, log_stirling1(max(n))))))))
esf_loglik <- function(n, theta) {
  const <- lfactorial(sum(n)) - sum(log(n)) - sum(lfactorial(as.numeric(table(n))))
  const + length(n) * log(theta) - lpoch(theta, sum(n))
}
dsm <- c(4, 2, 2, 1, 1)
lim <- sapply(10^(3:9), function(Ibig)
  etienne_loglik(dsm, 6, Ibig, logK(dsm, log_stirling1(max(dsm)))) - esf_loglik(dsm, 6))
data.frame(I = 10^(3:9), gap_vs_Ewens = signif(lim, 3), gap_times_I = signif(lim * 10^(3:9), 3))

## ---- mc ----
B <- 300
mc <- t(replicate(B, {
  d <- sort(sim_etienne(theta_true, I_true, J), decreasing = TRUE)
  f <- fit_etienne(d)
  c(theta_naive = theta_mle(length(d), J), theta_et = f$theta, m_et = f$m, S = length(d))
}))
q <- function(x) c(median = median(x), lo = unname(quantile(x, 0.05)), hi = unname(quantile(x, 0.95)))
round(rbind(theta_naive = q(mc[, "theta_naive"]), theta_etienne = q(mc[, "theta_et"]),
            m_etienne = q(mc[, "m_et"]), S_observed = q(mc[, "S"])), 4)

## ---- mcnum ----
med_naive <- median(mc[, "theta_naive"]); med_et <- median(mc[, "theta_et"])
med_m <- median(mc[, "m_et"]); below <- mean(mc[, "theta_naive"] < theta_true)
rho <- cor(log(mc[, "theta_et"]), log(mc[, "m_et"]))
hi_th <- unname(quantile(mc[, "theta_et"], 0.95))

## ---- fig-mc ----
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"))
}
dd <- rbind(data.frame(v = mc[, "theta_naive"], k = "Ewens fit (assumes m = 1)"),
            data.frame(v = pmin(mc[, "theta_et"], 1e4), k = "Etienne fit (theta and m)"))
ggplot(dd, aes(v, fill = k, colour = k)) +
  geom_density(alpha = 0.35, linewidth = 0.8, adjust = 1.1) +
  geom_vline(xintercept = theta_true, linetype = "dashed", colour = "#16241d", linewidth = 0.9) +
  annotate("text", x = theta_true * 1.12, y = 0, label = "true theta", hjust = 0, vjust = -0.6,
           colour = "#16241d", size = 3.4) +
  scale_x_log10(breaks = c(10, 20, 50, 100, 300, 1000)) +
  scale_fill_manual(values = c("Ewens fit (assumes m = 1)" = "#b5534e", "Etienne fit (theta and m)" = "#2f8f63")) +
  scale_colour_manual(values = c("Ewens fit (assumes m = 1)" = "#b5534e", "Etienne fit (theta and m)" = "#2f8f63")) +
  labs(x = expression("estimated " * theta * " (log scale)"), y = "density",
       title = "What ignoring dispersal limitation costs",
       subtitle = sprintf("300 plots; naive median %.1f, Etienne median %.1f, truth %.0f",
                          med_naive, med_et, theta_true)) +
  theme_te()

## ---- suffbreak ----
even   <- rep(10L, 20)
uneven <- c(100L, 48L, 24L, 12L, rep(1L, 16))
fe <- fit_etienne(sort(even, decreasing = TRUE))
fu <- fit_etienne(sort(uneven, decreasing = TRUE))
rbind(even   = c(theta = fe$theta, I = fe$I, m = fe$m, logL = fe$logL),
      uneven = c(theta = fu$theta, I = fu$I, m = fu$m, logL = fu$logL))

## ---- limitcheck ----
theta_grid <- 10^(2:12)
gap <- sapply(theta_grid, function(th) etienne_loglik(uneven, th, 5, LK = logK(uneven, log_stirling1(max(uneven)))) -
                esf_loglik(uneven, 5))
th_ew <- theta_mle(length(uneven), sum(uneven))
c(gap_at_theta_1e12 = gap[11], I_hat_uneven = fu$I, theta_Ewens_uneven = th_ew,
  difference = abs(fu$I - th_ew), logL_gap = abs(fu$logL - esf_loglik(uneven, th_ew)))

## ---- profile ----
LKu <- logK(uneven, log_stirling1(max(uneven)))
prof <- sapply(10^(1:8), function(th)
  -optimize(function(li) -etienne_loglik(uneven, th, exp(li), LK = LKu), c(log(0.2), log(4000)))$objective)
data.frame(theta = 10^(1:8), profile_logL = round(prof, 3))

## ---- fig-ridge ----
LKd <- logK(d1, log_stirling1(max(d1)))
gt <- exp(seq(log(8), log(1200), length.out = 60)); gm <- exp(seq(log(0.006), log(0.6), length.out = 60))
gr <- expand.grid(theta = gt, m = gm)
gr$ll <- mapply(function(a, b) etienne_loglik(d1, a, m_to_I(b, J), LKd), gr$theta, gr$m)
gr$rel <- gr$ll - max(gr$ll)
f1 <- fit_etienne(d1)
ggplot(gr, aes(theta, m, z = rel)) +
  geom_contour_filled(breaks = c(-40, -20, -10, -6, -3, -1.92, 0), alpha = 0.9) +
  annotate("point", x = f1$theta, y = f1$m, shape = 4, size = 4, stroke = 1.4,
           colour = "#16241d") +
  annotate("point", x = theta_true, y = m_true, shape = 21, size = 4, stroke = 1.4,
           colour = "#16241d", fill = NA) +
  scale_x_log10() + scale_y_log10() +
  scale_fill_manual(values = c("#f0eee0", "#dfe3c8", "#c9d4ab", "#a8c092", "#6ba77a", "#2f8f63"),
                    name = "relative log-likelihood") +
  labs(x = expression(theta * " (log scale)"), y = "m (log scale)",
       title = "The ridge", subtitle = "cross: maximum likelihood estimate. circle: the truth") +
  theme_te() + theme(legend.position = "right", legend.title = element_text(size = rel(0.8)))
