# Checking a community phylogenetics analysis
# https://tidyecology.com/posts/checking-a-community-phylogenetics-analysis/
#
# 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-01

## ---- 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, Dm = D) { d <- Dm[sp, sp]; mean(d[lower.tri(d)]) }

nri <- function(sp, pl, Dm = D, R = 199) {
  o   <- mpd(sp, Dm)
  nul <- replicate(R, mpd(sample(pl, length(sp)), Dm))
  -(o - mean(nul)) / sd(nul)
}

set.seed(43);  optC <- rnorm(40, 1.2, 0.25)
M <- matrix(0L, 40, S, dimnames = list(NULL, pool))
set.seed(431)
for (i in 1:40) M[i, sample(S, 15, prob = exp(-(trait - optC[i])^2 / (2 * 0.5^2)))] <- 1L
comms <- lapply(1:40, function(i) pool[M[i, ] == 1])

## ---- pools ----
obs_sp    <- pool[colSums(M) > 0]                                    # seen somewhere in the matrix
hab       <- pool[trait >= min(trait[colSums(M) > 0]) &
                  trait <= max(trait[colSums(M) > 0])]               # inside the observed trait range
plausible <- pool[abs(trait - 1.2) <= 1.2]                           # could tolerate this habitat

pools <- list(`whole tree`              = pool,
              `observed anywhere`       = obs_sp,
              `trait range of the data` = hab,
              `habitat-plausible`       = plausible)

sweep <- do.call(rbind, lapply(names(pools), function(nm) {
  set.seed(11)
  v <- sapply(comms, nri, pl = pools[[nm]])
  data.frame(pool = nm, size = length(pools[[nm]]),
             mean_NRI = round(mean(v), 2), pct_sig = round(100 * mean(abs(v) > 1.96)))
}))
sweep

## ---- fig-pool ----
dfp <- do.call(rbind, lapply(names(pools), function(nm) {
  set.seed(11)
  data.frame(pool = nm, nri = sapply(comms, nri, pl = pools[[nm]]))
}))
dfp$pool <- factor(dfp$pool, levels = names(pools))
ggplot(dfp, aes(pool, nri, fill = pool)) +
  geom_hline(yintercept = 0, colour = "#16241d", linewidth = 0.3) +
  geom_hline(yintercept = 1.96, linetype = 2, colour = "#b5534e", linewidth = 0.4) +
  geom_boxplot(width = 0.6, colour = "#16241d", linewidth = 0.35,
               outlier.size = 0.7, outlier.colour = "#5d6b61") +
  scale_fill_manual(values = c("#275139", "#93a87f", "#93a87f", "#93a87f"), guide = "none") +
  labs(x = NULL, y = "NRI", subtitle = "dashed line: the usual significance threshold") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        axis.text.x = element_text(size = 9),
        plot.subtitle = element_text(colour = "#5d6b61", size = 9))

## ---- calib ----
set.seed(12); fp15 <- replicate(400, abs(nri(sample(pool, 15), pool)) > 1.96)
set.seed(13); fp5  <- replicate(400, abs(nri(sample(pool,  5), pool)) > 1.96)
set.seed(14); z15  <- replicate(400, nri(sample(pool, 15), pool))

c(false_positive_k15 = mean(fp15), false_positive_k5 = mean(fp5),
  null_mean = mean(z15), null_sd = sd(z15))

## ---- fig-calib ----
ggplot(data.frame(z = z15), aes(z)) +
  geom_histogram(aes(y = after_stat(density)), bins = 30,
                 fill = "#93a87f", colour = "#f5f4ee", linewidth = 0.2) +
  stat_function(fun = dnorm, colour = "#b5534e", linewidth = 1) +
  geom_vline(xintercept = c(-1.96, 1.96), linetype = 2, colour = "#5d6b61", linewidth = 0.4) +
  labs(x = "NRI under no signal", y = "density",
       subtitle = "red: standard normal") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        plot.subtitle = element_text(colour = "#5d6b61", size = 9))

## ---- tree-break ----
tr2 <- tr
tr2$edge.length <- rep(1, nrow(tr2$edge))
D2  <- cophenetic(tr2)[pool, pool]

set.seed(15); v_true <- sapply(comms, nri, pl = pool)
set.seed(15); v_eq   <- sapply(comms, nri, pl = pool, Dm = D2)

c(true_mean = mean(v_true), equal_mean = mean(v_eq),
  true_pct = mean(abs(v_true) > 1.96), equal_pct = mean(abs(v_eq) > 1.96),
  correlation = cor(v_true, v_eq))

## ---- fig-tree ----
ggplot(data.frame(t = v_true, e = v_eq), aes(t, e)) +
  geom_abline(linetype = 2, colour = "#5d6b61", linewidth = 0.4) +
  geom_hline(yintercept = 1.96, linetype = 3, colour = "#b5534e", linewidth = 0.4) +
  geom_point(colour = "#275139", size = 2, alpha = 0.75) +
  labs(x = "NRI, real branch lengths", y = "NRI, all branches equal") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank())
