# Checking a beta diversity analysis
# https://tidyecology.com/posts/checking-a-beta-diversity-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-08

## ---- setup ----
library(ggplot2)

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          plot.title    = element_text(colour = "#16241d", face = "bold", size = 12),
          plot.subtitle = element_text(colour = "#5d6b61", size = 9.5),
          axis.title    = element_text(colour = "#46604a", size = 10),
          axis.text     = element_text(colour = "#2c3a31", size = 9),
          legend.text   = element_text(colour = "#2c3a31", size = 9),
          legend.title  = element_text(colour = "#46604a", size = 9.5))
}

hill <- function(p, q) {
  p <- p[p > 0]
  if (abs(q - 1) < 1e-10) return(exp(-sum(p * log(p))))
  sum(p^q)^(1 / (1 - q))
}
alpha_jost <- function(Y, q) {
  P <- Y / rowSums(Y)
  if (abs(q - 1) < 1e-10)
    return(exp(mean(apply(P, 1, function(p) { p <- p[p > 0]; -sum(p * log(p)) }))))
  mean(apply(P, 1, function(p) { p <- p[p > 0]; sum(p^q) }))^(1 / (1 - q))
}
beta_mult <- function(Y, q) hill(colMeans(Y / rowSums(Y)), q) / alpha_jost(Y, q)

good_turing <- function(x) {                       # sample coverage of the sample you have
  n <- sum(x); f1 <- sum(x == 1); f2 <- sum(x == 2)
  if (f1 == 0) return(1)
  1 - (f1 / n) * ((n - 1) * f1 / ((n - 1) * f1 + 2 * f2))
}

## ---- effort ----
set.seed(818)
shared <- rlnorm(120, 0, 1.2)                      # 120 species in both sites
only_1 <- rlnorm(40, 0, 1.2)                       # 40 species only in site 1
only_2 <- rlnorm(40, 0, 1.2)                       # 40 species only in site 2

P1 <- c(shared, only_1, rep(0, 40)); P1 <- P1 / sum(P1)
P2 <- c(shared * runif(120, 0.5, 1.5), rep(0, 40), only_2); P2 <- P2 / sum(P2)
TRUTH <- rbind(P1, P2) * 1e7                       # the whole community, no sampling

true_beta <- c(q0 = beta_mult(TRUTH, 0), q1 = beta_mult(TRUTH, 1), q2 = beta_mult(TRUTH, 2))

one_draw <- function(m) {
  y <- rbind(rmultinom(1, m, P1)[, 1], rmultinom(1, m, P2)[, 1])
  keep <- colSums(y) > 0
  c(coverage = mean(c(good_turing(y[1, ]), good_turing(y[2, ]))),
    q0 = beta_mult(y[, keep, drop = FALSE], 0),
    q1 = beta_mult(y[, keep, drop = FALSE], 1),
    q2 = beta_mult(y[, keep, drop = FALSE], 2))
}

set.seed(3071)
efforts <- c(50, 100, 250, 1000, 4000, 20000)
eff <- do.call(rbind, lapply(efforts, function(m) {
  r <- rowMeans(replicate(60, one_draw(m)))
  data.frame(individuals = m, coverage = r["coverage"],
             q0 = r["q0"], q1 = r["q1"], q2 = r["q2"],
             bias_q0 = 100 * (r["q0"] / true_beta["q0"] - 1),
             bias_q1 = 100 * (r["q1"] / true_beta["q1"] - 1),
             bias_q2 = 100 * (r["q2"] / true_beta["q2"] - 1))
}))
knitr::kable(eff, digits = c(0, 3, 3, 3, 3, 0, 0, 0), row.names = FALSE,
             col.names = c("individuals per site", "coverage", "beta q=0", "beta q=1", "beta q=2",
                           "q=0 bias %", "q=1 bias %", "q=2 bias %"))

## ---- fig-effort ----
long <- rbind(data.frame(m = eff$individuals, beta = eff$q0, q = "q = 0"),
              data.frame(m = eff$individuals, beta = eff$q1, q = "q = 1"),
              data.frame(m = eff$individuals, beta = eff$q2, q = "q = 2"))
tru  <- data.frame(q = c("q = 0", "q = 1", "q = 2"), beta = as.numeric(true_beta))
p_effort <- ggplot(long, aes(m, beta, colour = q)) +
  geom_hline(data = tru, aes(yintercept = beta, colour = q), linetype = "dashed", linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_x_log10(breaks = efforts, labels = efforts) +
  scale_colour_manual(values = c("q = 0" = "#b5534e", "q = 1" = "#c9b458", "q = 2" = "#2f8f63")) +
  labs(title = "Reported beta against sampling effort",
       subtitle = "dashed lines are the true values; the same two communities throughout",
       x = "individuals sampled per site", y = "reported beta", colour = NULL) +
  theme_te() + theme(legend.position = "bottom")
p_effort

## ---- thumb ----
ggsave("thumbnail.png", p_effort, width = 7.5, height = 5.4, dpi = 100)

## ---- equal-effort ----
mk_region <- function(shape) {
  co <- rlnorm(60, 0, shape); u1 <- rlnorm(40, 0, shape); u2 <- rlnorm(40, 0, shape)
  p1 <- c(co, u1, rep(0, 40)); p2 <- c(co, rep(0, 40), u2)
  rbind(p1 / sum(p1), p2 / sum(p2))
}
set.seed(1414)
PX <- mk_region(0.3)     # region X: even
PY <- mk_region(2.6)     # region Y: heavy-tailed

draw_beta0 <- function(P, m) {
  y <- rbind(rmultinom(1, m, P[1, ])[, 1], rmultinom(1, m, P[2, ])[, 1])
  keep <- colSums(y) > 0
  c(beta0 = beta_mult(y[, keep, drop = FALSE], 0),
    coverage = mean(c(good_turing(y[1, ]), good_turing(y[2, ]))),
    seen = mean(rowSums(y > 0)),
    shared_seen = sum(colSums(y[, 1:60, drop = FALSE] > 0) == 2) / 60)   # of the 60 truly shared
}

set.seed(1515)
cmp <- rbind(
  data.frame(region = "X (even)",         t(rowMeans(replicate(300, draw_beta0(PX, 200))))),
  data.frame(region = "Y (heavy-tailed)", t(rowMeans(replicate(300, draw_beta0(PY, 200))))))
cmp$true_beta0 <- c(beta_mult(PX * 1e7, 0), beta_mult(PY * 1e7, 0))
knitr::kable(cmp, digits = c(0, 3, 3, 1, 2, 4), row.names = FALSE,
             col.names = c("region", "reported beta (q = 0)", "coverage", "species seen (per site, of 100)",
                           "shared species detected", "true beta (q = 0)"))

## ---- coverage-predicts ----
set.seed(99)
probe <- t(replicate(30, {
  P <- mk_region(runif(1, 0.2, 2.8))                 # 30 regions, tails from even to very heavy
  o <- rowMeans(replicate(60, draw_beta0(P, 200)))
  c(coverage = unname(o["coverage"]), shared_detected = unname(o["shared_seen"]),
    bias = unname(100 * (o["beta0"] / 1.4 - 1)))
}))

c(cor_coverage_with_bias        = cor(probe[, "coverage"], probe[, "bias"]),
  cor_shared_detected_with_bias = cor(probe[, "shared_detected"], probe[, "bias"]))

## ---- coverage-std ----
cov_at <- function(x, k) {                         # expected coverage of a subsample of size k
  n <- sum(x); if (k >= n) return(good_turing(x))
  x <- x[x > 0]
  1 - sum((x / n) * exp(lchoose(n - x, k) - lchoose(n - 1, k)))
}
k_for <- function(x, target) {
  n <- sum(x); if (good_turing(x) < target) return(NA_integer_)
  ks <- seq(5, n, by = 5); ks[which.min(abs(sapply(ks, cov_at, x = x) - target))]
}
subsample <- function(x, k) tabulate(sample(rep(seq_along(x), x), k), nbins = length(x))

std_draw <- function(P, target) {
  y  <- rbind(rmultinom(1, 8000, P[1, ])[, 1], rmultinom(1, 8000, P[2, ])[, 1])
  ys <- rbind(subsample(y[1, ], k_for(y[1, ], target)), subsample(y[2, ], k_for(y[2, ], target)))
  keep <- colSums(ys) > 0
  c(beta0 = beta_mult(ys[, keep, drop = FALSE], 0), n_used = mean(rowSums(ys)),
    seen = mean(rowSums(ys > 0)))
}

set.seed(17)
std <- do.call(rbind, lapply(c(0.80, 0.90, 0.95, 0.99), function(tg) {
  X <- rowMeans(replicate(80, std_draw(PX, tg))); Y <- rowMeans(replicate(80, std_draw(PY, tg)))
  data.frame(target_coverage = tg, X_beta0 = X["beta0"], X_individuals = X["n_used"], X_seen = X["seen"],
             Y_beta0 = Y["beta0"], Y_individuals = Y["n_used"], Y_seen = Y["seen"],
             gap_pct = 100 * (Y["beta0"] / X["beta0"] - 1))
}))
knitr::kable(std, digits = c(2, 3, 0, 1, 3, 0, 1, 0), row.names = FALSE,
             col.names = c("target coverage", "X beta", "X individuals", "X species seen",
                           "Y beta", "Y individuals", "Y species seen", "gap"))

## ---- metric-flip ----
set.seed(3072)
region_A <- t(sapply(1:8, function(i) { y <- rep(6, 24); y[i * 3] <- 300; y }))   # same list, different king
region_B <- t(sapply(1:8, function(i) {                                            # different lists, flat
  y <- numeric(20 + 8 * 4); y[1:20] <- 40; y[20 + ((i - 1) * 4 + 1):((i - 1) * 4 + 4)] <- 40; y
}))

bd_total <- function(Y) { Z <- sqrt(Y / rowSums(Y)); C <- sweep(Z, 2, colMeans(Z)); sum(C^2) / (nrow(Y) - 1) }
sorensen_mean <- function(Y) {
  X <- Y > 0
  mean(combn(nrow(Y), 2, function(p) {
    a <- sum(X[p[1], ] & X[p[2], ]); 2 * a / (sum(X[p[1], ]) + sum(X[p[2], ]))
  }))
}

verdict <- data.frame(
  metric = c("beta (q = 0)", "beta (q = 1)", "beta (q = 2)", "mean Sorensen similarity", "BD total (Hellinger)"),
  region_A = c(beta_mult(region_A, 0), beta_mult(region_A, 1), beta_mult(region_A, 2),
               sorensen_mean(region_A), bd_total(region_A)),
  region_B = c(beta_mult(region_B, 0), beta_mult(region_B, 1), beta_mult(region_B, 2),
               sorensen_mean(region_B), bd_total(region_B)))
verdict$more_beta_diverse <- ifelse(
  verdict$metric == "mean Sorensen similarity",
  ifelse(verdict$region_A < verdict$region_B, "A", "B"),
  ifelse(verdict$region_A > verdict$region_B, "A", "B"))
knitr::kable(verdict, digits = 4, row.names = FALSE,
             col.names = c("metric", "region A", "region B", "which is more beta diverse?"))

## ---- fig-flip ----
sc <- data.frame(
  metric = rep(c("beta q=0", "beta q=1", "beta q=2", "Sorensen\n(inverted)", "BD total"), 2),
  region = rep(c("region A", "region B"), each = 5),
  value  = c(verdict$region_A[1:3] - 1, 1 - verdict$region_A[4], verdict$region_A[5],
             verdict$region_B[1:3] - 1, 1 - verdict$region_B[4], verdict$region_B[5]))
sc$rel <- ave(sc$value, sc$metric, FUN = function(v) v / max(v))
sc$metric <- factor(sc$metric, levels = c("beta q=0", "Sorensen\n(inverted)", "beta q=1", "beta q=2", "BD total"))
ggplot(sc, aes(metric, rel, fill = region)) +
  geom_col(position = position_dodge(width = 0.75), width = 0.65) +
  geom_text(aes(label = sprintf("%.2f", rel)), position = position_dodge(width = 0.75),
            vjust = -0.4, size = 3, colour = "#233a2c") +
  scale_fill_manual(values = c("region A" = "#275139", "region B" = "#c9b458")) +
  labs(title = "The same two regions, five metrics, two opposite verdicts",
       subtitle = "betas as excess over one; each metric rescaled to its own maximum; taller means more beta diverse",
       x = NULL, y = "score relative to the higher region", fill = NULL) +
  theme_te() + theme(legend.position = "bottom")

## ---- site-set ----
lcbd <- function(Y) { Z <- sqrt(Y / rowSums(Y)); C <- sweep(Z, 2, colMeans(Z)); rowSums(C^2) / sum(C^2) }

set.seed(2020)
S2 <- 50
opt <- seq(-0.15, 1.15, length.out = S2)
mk_site <- function(g) rpois(S2, 60 * exp(-((g - opt)^2) / (2 * 0.18^2)))
Y1 <- t(sapply(seq(0, 1, length.out = 12), mk_site))
rownames(Y1) <- paste0("G", 1:12)
L1 <- lcbd(Y1)

drop_one <- do.call(rbind, lapply(c(1, 6, 12), function(d) {
  Y2 <- Y1[-d, ]; L2 <- lcbd(Y2)
  data.frame(dropped = rownames(Y1)[d],
             BD_before = bd_total(Y1), BD_after = bd_total(Y2),
             top_before = names(which.max(L1[-d])), top_after = names(which.max(L2)),
             rank_spearman = cor(rank(-L1[-d]), rank(-L2), method = "spearman"))
}))
knitr::kable(drop_one, digits = c(0, 4, 4, 0, 0, 3), row.names = FALSE,
             col.names = c("site removed", "BD before", "BD after", "most unique before",
                           "most unique after", "rank correlation"))

## ---- site-set-add ----
set.seed(2121)
opt2 <- seq(1.6, 2.8, length.out = S2)
Y3 <- rbind(Y1, t(sapply(seq(1.8, 2.6, length.out = 6),
                         function(g) rpois(S2, 60 * exp(-((g - opt2)^2) / (2 * 0.18^2))))))
rownames(Y3) <- c(rownames(Y1), paste0("H", 1:6))
L3 <- lcbd(Y3)

c(BD_12_sites = bd_total(Y1), BD_18_sites = bd_total(Y3),
  LCBD_sum_of_original_12 = sum(L3[1:12]),
  G1_LCBD_before = L1["G1"], G1_LCBD_after = L3["G1"],
  rank_correlation_among_the_original_12 = cor(rank(-L1), rank(-L3[1:12]), method = "spearman"))

## ---- site-set-beta ----
c(beta0_12_sites = beta_mult(Y1, 0), ceiling_12 = 12,
  beta0_18_sites = beta_mult(Y3, 0), ceiling_18 = 18,
  overlap_12 = (12 - beta_mult(Y1, 0)) / 11,       # the N-normalised version
  overlap_18 = (18 - beta_mult(Y3, 0)) / 17)
