# Phylogenetic community structure: NRI and NTI in R
# https://tidyecology.com/posts/phylogenetic-community-structure-nri-nti/
#
# 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-08

## ---- 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
pool_tree <- rcoal(S, tip.label = sprintf("sp%03d", 1:S))
pool_tree$edge.length <- pool_tree$edge.length / max(node.depth.edgelength(pool_tree))
pool <- pool_tree$tip.label

D <- cophenetic(pool_tree)[pool, pool]
trait <- rTraitCont(pool_tree, model = "BM", sigma = 1)[pool]
trait <- (trait - mean(trait)) / sd(trait)

## ---- metrics ----
mpd <- function(sp) { d <- D[sp, sp]; mean(d[lower.tri(d)]) }

mntd <- function(sp) {
  d <- D[sp, sp]
  diag(d) <- NA
  mean(apply(d, 1, min, na.rm = TRUE))
}

## ---- confounding ----
neutral <- function(k) sample(pool, k)

set.seed(1)
kg <- rep(c(4, 8, 15, 25, 40), each = 200)
raw <- t(sapply(kg, function(k) { s <- neutral(k); c(mpd(s), mntd(s)) }))
tab <- data.frame(
  k      = sort(unique(kg)),
  mpd_m  = tapply(raw[, 1], kg, mean), mpd_s  = tapply(raw[, 1], kg, sd),
  mntd_m = tapply(raw[, 2], kg, mean), mntd_s = tapply(raw[, 2], kg, sd)
)
round(tab, 3)

## ---- fig-confounding ----
dfc <- data.frame(
  k = rep(kg, 2), value = c(raw[, 1], raw[, 2]),
  metric = rep(c("MPD", "MNTD"), each = length(kg))
)
dfc$metric <- factor(dfc$metric, levels = c("MPD", "MNTD"))
ggplot(dfc, aes(k, value)) +
  geom_point(colour = "#93a87f", alpha = 0.35, size = 0.9,
             position = position_jitter(width = 0.8, height = 0)) +
  stat_summary(fun = mean, geom = "line", colour = "#275139", linewidth = 0.9) +
  stat_summary(fun = mean, geom = "point", colour = "#275139", size = 2) +
  facet_wrap(~metric, scales = "free_y") +
  labs(x = "species richness", y = "raw value") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold", colour = "#16241d"))

## ---- ses ----
ses <- function(sp, R = 999) {
  k   <- length(sp)
  obs <- c(mpd(sp), mntd(sp))
  nul <- replicate(R, { s <- sample(pool, k); c(mpd(s), mntd(s)) })
  z   <- (obs - rowMeans(nul)) / apply(nul, 1, sd)
  p   <- (rowSums(nul <= obs) + 1) / (R + 1)
  list(obs = obs, null = nul, z = z, p = p, nri = -z[1], nti = -z[2])
}

## ---- rules ----
filtered <- function(k, opt, w = 0.3) {
  sample(pool, k, prob = exp(-(trait - opt)^2 / (2 * w^2)))
}

spaced <- function(k) {
  sel <- sample(pool, 1)
  while (length(sel) < k) {
    cand <- setdiff(pool, sel)
    sel  <- c(sel, sample(cand, 1, prob = apply(D[cand, sel, drop = FALSE], 1, min)^8))
  }
  sel
}

set.seed(10); cf <- filtered(15, 1.2)
set.seed(11); cn <- neutral(15)
set.seed(12); co <- spaced(15)

set.seed(20); sf <- ses(cf)
set.seed(21); sn <- ses(cn)
set.seed(22); so <- ses(co)

data.frame(
  rule = c("filtered", "neutral", "spaced"),
  MPD  = round(c(sf$obs[1], sn$obs[1], so$obs[1]), 3),
  NRI  = round(c(sf$nri, sn$nri, so$nri), 2),
  MNTD = round(c(sf$obs[2], sn$obs[2], so$obs[2]), 3),
  NTI  = round(c(sf$nti, sn$nti, so$nti), 2)
)

## ---- fig-null ----
dfn <- data.frame(
  value  = c(sf$null[1, ], sf$null[2, ]),
  metric = rep(c("MPD", "MNTD"), each = ncol(sf$null))
)
dfn$metric <- factor(dfn$metric, levels = c("MPD", "MNTD"))
dfo <- data.frame(metric = factor(c("MPD", "MNTD"), levels = c("MPD", "MNTD")), obs = sf$obs)
ggplot(dfn, aes(value)) +
  geom_histogram(bins = 40, fill = "#93a87f", colour = "white", linewidth = 0.15) +
  geom_vline(data = dfo, aes(xintercept = obs), colour = "#b5534e", linewidth = 0.9) +
  facet_wrap(~metric, scales = "free") +
  labs(x = "value under the null", y = "null draws") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold", colour = "#16241d"))

## ---- replicate ----
rep_ses <- function(gen, n = 100, R = 199) {
  t(replicate(n, {
    sp  <- gen(15)
    obs <- c(mpd(sp), mntd(sp))
    nul <- replicate(R, { s <- sample(pool, 15); c(mpd(s), mntd(s)) })
    -(obs - rowMeans(nul)) / apply(nul, 1, sd)
  }))
}

set.seed(30); A <- rep_ses(function(k) filtered(k, rnorm(1)))
set.seed(31); B <- rep_ses(neutral)
set.seed(32); C <- rep_ses(spaced)

data.frame(
  rule    = c("filtered", "neutral", "spaced"),
  NRI     = round(c(mean(A[, 1]), mean(B[, 1]), mean(C[, 1])), 2),
  NRI_sd  = round(c(sd(A[, 1]), sd(B[, 1]), sd(C[, 1])), 2),
  NTI     = round(c(mean(A[, 2]), mean(B[, 2]), mean(C[, 2])), 2),
  NTI_sd  = round(c(sd(A[, 2]), sd(B[, 2]), sd(C[, 2])), 2)
)

## ---- fig-rules ----
dfr <- data.frame(
  value = c(A[, 1], B[, 1], C[, 1], A[, 2], B[, 2], C[, 2]),
  rule  = rep(rep(c("filtered", "neutral", "spaced"), each = nrow(A)), 2),
  index = rep(c("NRI (from MPD)", "NTI (from MNTD)"), each = 3 * nrow(A))
)
dfr$rule <- factor(dfr$rule, levels = c("filtered", "neutral", "spaced"))
ggplot(dfr, aes(rule, value, fill = rule)) +
  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(outlier.size = 0.7, outlier.colour = "#5d6b61", width = 0.6,
               colour = "#16241d", linewidth = 0.35) +
  scale_fill_manual(values = c(filtered = "#275139", neutral = "#93a87f", spaced = "#cda23f"),
                    guide = "none") +
  facet_wrap(~index) +
  labs(x = NULL, y = "index value") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold", colour = "#16241d"))
