# Null models for phylogenetic community structure
# https://tidyecology.com/posts/null-models-for-phylogenetic-structure/
#
# 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(ape)
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

set.seed(292)
S  <- 200
tr <- rcoal(S, tip.label = sprintf("sp%03d", 1:S))
tr$edge.length <- tr$edge.length / max(node.depth.edgelength(tr))
pool  <- tr$tip.label
D     <- cophenetic(tr)[pool, pool]
trait <- rTraitCont(tr, model = "BM", sigma = 1)[pool]
trait <- (trait - mean(trait)) / sd(trait)

mpd     <- function(sp) { d <- D[sp, sp]; mean(d[lower.tri(d)]) }
mpd_row <- function(r) mpd(pool[r == 1])

## ---- equivalence ----
set.seed(60)
comm <- sample(pool, 15)

pool_null <- replicate(4000, mpd(sample(pool, 15)))

tip_null <- replicate(4000, {
  lab <- sample(pool)
  Ds  <- D
  dimnames(Ds) <- list(lab, lab)
  d <- Ds[comm, comm]
  mean(d[lower.tri(d)])
})

c(pool_mean = mean(pool_null), tip_mean = mean(tip_null),
  pool_sd = sd(pool_null), tip_sd = sd(tip_null))
ks.test(pool_null, tip_null)$p.value

## ---- swap ----
swap_n <- function(M, n, B = 300) {
  R <- nrow(M); Cc <- ncol(M); done <- 0
  while (done < n) {
    i1 <- sample(R, B, TRUE); i2 <- sample(R, B, TRUE)
    j1 <- sample(Cc, B, TRUE); j2 <- sample(Cc, B, TRUE)
    a  <- M[cbind(i1, j1)]; b  <- M[cbind(i1, j2)]
    c2 <- M[cbind(i2, j1)]; d  <- M[cbind(i2, j2)]
    hit <- which(i1 != i2 & j1 != j2 &
                 ((a == 1 & b == 0 & c2 == 0 & d == 1) |
                  (a == 0 & b == 1 & c2 == 1 & d == 0)))
    for (h in hit) {
      if (done >= n) break
      if (M[i1[h], j1[h]] == a[h] && M[i1[h], j2[h]] == b[h] &&
          M[i2[h], j1[h]] == c2[h] && M[i2[h], j2[h]] == d[h]) {
        M[i1[h], j1[h]] <- 1 - a[h];  M[i1[h], j2[h]] <- 1 - b[h]
        M[i2[h], j1[h]] <- 1 - c2[h]; M[i2[h], j2[h]] <- 1 - d[h]
        done <- done + 1
      }
    }
  }
  M
}

## ---- nulls ----
ses_pool <- function(M, R = 199) {
  sapply(seq_len(nrow(M)), function(i) {
    k <- sum(M[i, ]); o <- mpd_row(M[i, ])
    nul <- replicate(R, mpd(sample(pool, k)))
    -(o - mean(nul)) / sd(nul)
  })
}

ses_swap <- function(M, R = 199, iter = 200) {
  obs <- apply(M, 1, mpd_row)
  nul <- matrix(NA_real_, R, nrow(M))
  X   <- swap_n(M, 5000)                       # burn-in away from the observed matrix
  for (r in 1:R) { X <- swap_n(X, iter); nul[r, ] <- apply(X, 1, mpd_row) }
  -(obs - colMeans(nul)) / apply(nul, 2, sd)
}

## ---- data ----
nt   <- node.depth(tr)[-(1:S)]                # species descending from each internal node
node <- (which(nt >= 40 & nt <= 45) + S)[1]   # first clade holding 40 to 45 species
wide <- extract.clade(tr, node)$tip.label

draw <- function(seed, prob_i) {
  set.seed(seed)
  M <- matrix(0L, 40, S, dimnames = list(NULL, pool))
  for (i in 1:40) M[i, sample(S, 15, prob = prob_i(i))] <- 1L
  M
}

# A: no local process at all. Every site is the same weighted draw, and one
#    clade is six times as likely to turn up as anything else.
pw <- ifelse(pool %in% wide, 6, 1)
M1 <- draw(41, function(i) pw)

# B: real habitat filtering, sites differ in what they select for.
set.seed(42); optB <- rnorm(40)
M2 <- draw(421, function(i) exp(-(trait - optB[i])^2 / (2 * 0.5^2)))

# C: real habitat filtering, but every site is nearly the same habitat.
set.seed(43); optC <- rnorm(40, 1.2, 0.25)
M3 <- draw(431, function(i) exp(-(trait - optC[i])^2 / (2 * 0.5^2)))

## ---- check-a ----
exp_mpd <- function(w) { W <- outer(w, w); diag(W) <- 0; sum(W * D) / sum(W) }
c(uniform = exp_mpd(rep(1, S)), weighted_A = exp_mpd(pw))

## ---- run ----
set.seed(51); p1 <- ses_pool(M1); set.seed(52); s1 <- ses_swap(M1)
set.seed(53); p2 <- ses_pool(M2); set.seed(54); s2 <- ses_swap(M2)
set.seed(55); p3 <- ses_pool(M3); set.seed(56); s3 <- ses_swap(M3)

pct <- function(x) round(100 * mean(abs(x) > 1.96))
data.frame(
  matrix     = c("A no local process", "B filtering, mixed sites", "C filtering, one habitat"),
  pool_NRI   = round(c(mean(p1), mean(p2), mean(p3)), 2),
  pool_pct   = c(pct(p1), pct(p2), pct(p3)),
  swap_NRI   = round(c(mean(s1), mean(s2), mean(s3)), 2),
  swap_pct   = c(pct(s1), pct(s2), pct(s3))
)

## ---- fig-three ----
dfp <- data.frame(
  nri  = c(p1, p2, p3, s1, s2, s3),
  data = rep(rep(c("A: no local process", "B: filtering, mixed sites",
                   "C: filtering, one habitat"), each = 40), 2),
  null = rep(c("uniform pool null", "occupancy-preserving swap null"), each = 120)
)
dfp$null <- factor(dfp$null, levels = c("uniform pool null", "occupancy-preserving swap null"))
ggplot(dfp, aes(data, nri, fill = data)) +
  geom_hline(yintercept = 0, colour = "#16241d", linewidth = 0.3) +
  geom_hline(yintercept = c(-1.96, 1.96), linetype = 2, colour = "#5d6b61", linewidth = 0.3) +
  geom_boxplot(width = 0.6, colour = "#16241d", linewidth = 0.35,
               outlier.size = 0.7, outlier.colour = "#5d6b61") +
  scale_fill_manual(values = c("#cda23f", "#93a87f", "#275139"), guide = "none") +
  scale_x_discrete(labels = c("A", "B", "C")) +
  facet_wrap(~null) +
  labs(x = "data set", y = "NRI") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold", colour = "#16241d"))
