# Phylogenetic beta diversity: UniFrac and PhyloSor
# https://tidyecology.com/posts/phylogenetic-beta-diversity/
#
# 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

sorensen <- function(a, b) 2 * length(intersect(a, b)) / (length(a) + length(b))

## ---- accounting ----
desc_tips <- function(tr) {
  out <- vector("list", max(tr$edge))
  for (i in seq_len(Ntip(tr))) out[[i]] <- i
  for (e in rev(seq_len(nrow(tr$edge)))) {
    p <- tr$edge[e, 1]; ch <- tr$edge[e, 2]
    out[[p]] <- c(out[[p]], out[[ch]])
  }
  out
}
DT <- desc_tips(tr)

branch_flags <- function(sp) {
  idx <- match(sp, tr$tip.label)
  vapply(tr$edge[, 2], function(ch) any(DT[[ch]] %in% idx), logical(1))
}

## ---- metrics ----
pbd <- function(a, b) {
  A <- branch_flags(a); B <- branch_flags(b); L <- tr$edge.length
  s  <- sum(L[A & B])
  pa <- sum(L[A]); pb <- sum(L[B])
  c(unifrac  = (pa + pb - 2 * s) / (pa + pb - s),
    phylosor = 2 * s / (pa + pb))
}

## ---- pairs ----
nt    <- node.depth(tr)[-(1:S)]
cands <- which(nt >= 20 & nt <= 30) + S
cl1   <- extract.clade(tr, cands[1])$tip.label
cl2   <- extract.clade(tr, cands[length(cands)])$tip.label

set.seed(7)
near_a <- sample(cl1, 10); near_b <- sample(setdiff(cl1, near_a), 10)
far_a  <- sample(cl1, 10); far_b  <- sample(cl2, 10)

rbind(relatives = c(sorensen = sorensen(near_a, near_b), pbd(near_a, near_b)),
      distant   = c(sorensen = sorensen(far_a,  far_b),  pbd(far_a,  far_b)))

## ---- fig-trees ----
par(mfrow = c(1, 2), mar = c(0, 0, 2, 0))
show_pair <- function(a, b, main) {
  plot(tr, type = "fan", show.tip.label = FALSE, edge.color = "#c9cec2",
       edge.width = 0.6, no.margin = FALSE, main = main, col.main = "#16241d")
  col <- rep(NA, S); col[match(a, pool)] <- "#cda23f"; col[match(b, pool)] <- "#275139"
  tiplabels(pch = 19, cex = 0.7, col = col, frame = "none")
}
show_pair(near_a, near_b, sprintf("relatives: UniFrac %.2f", pbd(near_a, near_b)[["unifrac"]]))
show_pair(far_a,  far_b,  sprintf("distant: UniFrac %.2f",   pbd(far_a,  far_b)[["unifrac"]]))

## ---- identity ----
set.seed(8)
z <- t(replicate(200, {
  a <- sample(pool, sample(5:30, 1))
  b <- sample(pool, sample(5:30, 1))
  pbd(a, b)
}))
all.equal(z[, "unifrac"], 1 - z[, "phylosor"] / (2 - z[, "phylosor"]))
cor(z[, "unifrac"], z[, "phylosor"], method = "spearman")

## ---- fig-identity ----
curve_df <- data.frame(ps = seq(0, 1, 0.001))
curve_df$uf <- 1 - curve_df$ps / (2 - curve_df$ps)
ggplot(as.data.frame(z), aes(phylosor, unifrac)) +
  geom_line(data = curve_df, aes(ps, uf), colour = "#b5534e", linewidth = 1.1) +
  geom_point(colour = "#275139", size = 1.7, alpha = 0.7) +
  labs(x = "PhyloSor", y = "UniFrac",
       subtitle = "red line: 1 - PhyloSor / (2 - PhyloSor)") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(),
        plot.subtitle = element_text(colour = "#5d6b61", size = 9))

## ---- fig-richness ----
set.seed(9)
ks <- c(5, 10, 20, 40, 80)
rd <- do.call(rbind, lapply(ks, function(k) {
  data.frame(k = k, uf = replicate(60, pbd(sample(pool, k), sample(pool, k))[["unifrac"]]))
}))
ggplot(rd, aes(factor(k), uf)) +
  geom_jitter(width = 0.15, colour = "#93a87f", size = 1.1, alpha = 0.6) +
  stat_summary(aes(group = 1), fun = mean, geom = "line", colour = "#275139", linewidth = 0.9) +
  stat_summary(fun = mean, geom = "point", colour = "#275139", size = 2.2) +
  labs(x = "species per community", y = "UniFrac") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- richness-table ----
aggregate(uf ~ k, rd, function(x) round(c(mean = mean(x), sd = sd(x)), 3))
