# Beta diversity as variance: LCBD and SCBD
# https://tidyecology.com/posts/beta-diversity-as-variance/
#
# 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-15

## ---- 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))
}

## ---- core ----
hellinger <- function(Y) sqrt(Y / rowSums(Y))

beta_div <- function(Y, transform = hellinger) {
  Z  <- transform(Y)
  C  <- sweep(Z, 2, colMeans(Z))        # centre each species column
  SS <- sum(C^2)
  list(SS      = SS,
       BDtotal = SS / (nrow(Y) - 1),
       LCBD    = rowSums(C^2) / SS,     # each site's share of the variance
       SCBD    = colSums(C^2) / SS)     # each species' share
}

## ---- identity ----
set.seed(306)
Y <- matrix(rpois(15 * 40, 4), 15, 40)
Y[cbind(sample(15, 60, TRUE), sample(40, 60, TRUE))] <- 0    # some zeros, as usual

d_hell <- as.matrix(dist(hellinger(Y)))

gower_trace <- function(D) {                       # SS straight from a dissimilarity matrix
  A <- -0.5 * D^2
  G <- sweep(sweep(A, 1, rowMeans(A)), 2, colMeans(A)) + mean(A)
  sum(diag(G))
}

bd <- beta_div(Y)
c(SS_from_centring  = bd$SS,
  SS_from_distances = gower_trace(d_hell),
  SS_from_pairs     = sum(d_hell[upper.tri(d_hell)]^2) / nrow(Y),
  gap = max(abs(c(gower_trace(d_hell), sum(d_hell[upper.tri(d_hell)]^2) / nrow(Y)) - bd$SS)))

## ---- shares ----
c(sum_LCBD = sum(bd$LCBD), sum_SCBD = sum(bd$SCBD),
  n_sites = nrow(Y), expected_LCBD_if_uniform = 1 / nrow(Y))

## ---- bray ----
bray <- function(Y) {
  n <- nrow(Y); D <- matrix(0, n, n)
  for (i in 1:n) for (j in 1:n)
    D[i, j] <- sum(abs(Y[i, ] - Y[j, ])) / sum(Y[i, ] + Y[j, ])
  D
}

Ys <- Y
Ys[1:5, 21:40] <- 0        # five sites hold only the first half of the pool
Ys[6:10, 1:20] <- 0        # five hold only the second half, so the blocks share nothing

d_bray <- bray(Ys)
A <- -0.5 * d_bray^2
G <- sweep(sweep(A, 1, rowMeans(A)), 2, colMeans(A)) + mean(A)
ev <- eigen(G, symmetric = TRUE, only.values = TRUE)$values

c(smallest_eigenvalue = min(ev),
  is_euclidean        = min(ev) > -1e-8,
  SS_from_trace       = sum(diag(G)),
  SS_from_pairs       = sum(d_bray[upper.tri(d_bray)]^2) / nrow(Ys),
  gap = abs(sum(diag(G)) - sum(d_bray[upper.tri(d_bray)]^2) / nrow(Ys)))

## ---- maximum ----
max_tab <- do.call(rbind, lapply(c(2, 5, 20), function(n) {
  do.call(rbind, lapply(c(3, 25), function(S) {
    Yd <- matrix(0, n, n * S)
    for (i in 1:n) Yd[i, ((i - 1) * S + 1):(i * S)] <- rpois(S, 10) + 1
    jac <- as.matrix(dist(Yd > 0, method = "binary"))
    data.frame(n_sites = n, species_per_site = S,
               BD_jaccard   = gower_trace(jac) / (n - 1),
               BD_hellinger = beta_div(Yd)$BDtotal)
  }))
}))
knitr::kable(max_tab, digits = 10,
             col.names = c("sites", "species per site", "BD with Jaccard", "BD with Hellinger"))

## ---- trap-poverty ----
set.seed(3064)
n <- 30; S <- 60
pool <- rlnorm(S, 0, 0.8)                          # one pool, one abundance profile, shared by all
k_of <- round(seq(6, 55, length.out = n))          # the only thing that varies: species count

Yg <- t(sapply(seq_len(n), function(i) {
  y  <- numeric(S)
  sp <- sample(S, k_of[i], prob = pool)
  v  <- rpois(k_of[i], 40 * pool[sp] / mean(pool)); v[v == 0] <- 1
  y[sp] <- v
  y
}))

bg   <- beta_div(Yg)
rich <- rowSums(Yg > 0)

c(spearman_LCBD_richness = cor(bg$LCBD, rich, method = "spearman"),
  richness_of_poorest = min(rich), LCBD_rank_of_poorest = rank(-bg$LCBD)[which.min(rich)],
  richness_of_richest = max(rich), LCBD_rank_of_richest = rank(-bg$LCBD)[which.max(rich)],
  LCBD_of_poorest = bg$LCBD[which.min(rich)], LCBD_if_uniform = 1 / n)

## ---- poverty-control ----
Yr <- Yg
Yr[which.min(rich), ] <- 0
Yr[which.min(rich), order(pool)[1:6]] <- 30       # same site, same count, now the rarest species

c(rank_with_ordinary_species = rank(-bg$LCBD)[which.min(rich)],
  rank_with_rarest_species   = rank(-beta_div(Yr)$LCBD)[which.min(rich)],
  n_sites = n)

## ---- fig-poverty ----
dfp <- data.frame(richness = rich, LCBD = bg$LCBD, site = 1:n)
ip <- which.min(rich)
p_poverty <- ggplot(dfp, aes(richness, LCBD)) +
  geom_hline(yintercept = 1 / n, colour = "#93a87f", linewidth = 0.4, linetype = "dashed") +
  geom_point(size = 2.6, colour = "#16241d", alpha = 0.75) +
  annotate("text", x = max(rich) * 0.55, y = 1 / n, vjust = -0.7,
           label = "LCBD if every site contributed equally", colour = "#46604a", size = 3) +
  annotate("segment", x = rich[ip] + 5.5, xend = rich[ip] + 1.2, y = bg$LCBD[ip], yend = bg$LCBD[ip],
           colour = "#b5534e", linewidth = 0.4) +
  annotate("text", x = rich[ip] + 6.5, y = bg$LCBD[ip], hjust = 0, size = 3.1, colour = "#b5534e",
           label = sprintf("%d species, rank %d of %d", rich[ip], rank(-bg$LCBD)[ip], n)) +
  labs(title = "LCBD rewards being different, and poverty is a way to be different",
       subtitle = "thirty sites, one shared species pool, no gradient, Hellinger transformation",
       x = "species richness", y = "LCBD") +
  theme_te()
p_poverty

## ---- thumb ----
ggsave("thumbnail.png",
       p_poverty +
         labs(title = paste(strwrap("LCBD against richness in one species pool", 46),
                            collapse = "\n"),
              subtitle = NULL) +
         theme(plot.title = element_text(colour = "#16241d", face = "bold", size = 13),
               plot.subtitle = element_text(colour = "#5d6b61", size = 9.5),
               plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")

## ---- trap-coefficient ----
set.seed(3062)
Yc <- matrix(rpois(20 * 30, 6), 20, 30)                 # zeros happen, so species lists differ
Yc[cbind(sample(20, 90, TRUE), sample(30, 90, TRUE))] <- 0
Yc[rowSums(Yc) == 0, 1] <- 1
present13 <- which(Yc[13, ] > 0)                        # site 13 keeps its species list exactly
Yc[13, present13] <- 1
Yc[13, present13[1]] <- 400                             # and lets one of them take over completely

lcbd_hell <- beta_div(Yc)$LCBD
jac_d     <- as.matrix(dist(Yc > 0, method = "binary"))
Aj <- -0.5 * jac_d^2
Gj <- sweep(sweep(Aj, 1, rowMeans(Aj)), 2, colMeans(Aj)) + mean(Aj)
lcbd_jac <- diag(Gj) / sum(diag(Gj))

c(site13_species_count = sum(Yc[13, ] > 0),
  site13_share_of_top_species = max(Yc[13, ]) / sum(Yc[13, ]),
  site13_rank_hellinger = rank(-lcbd_hell)[13],
  site13_rank_jaccard   = rank(-lcbd_jac)[13],
  spearman_between_the_two = cor(lcbd_hell, lcbd_jac, method = "spearman"),
  BD_hellinger = beta_div(Yc)$BDtotal,
  BD_jaccard   = sum(diag(Gj)) / (nrow(Yc) - 1))

## ---- fig-flip ----
dff <- data.frame(hell = rank(-lcbd_hell), jac = rank(-lcbd_jac), site = 1:20)
dff$flag <- ifelse(dff$site == 13, "site 13: one dominant species", "other sites")
ggplot(dff, aes(hell, jac, colour = flag)) +
  geom_abline(slope = 1, intercept = 0, colour = "#dad9ca", linewidth = 0.5) +
  geom_point(size = 3) +
  scale_colour_manual(values = c("site 13: one dominant species" = "#b5534e", "other sites" = "#16241d")) +
  scale_x_continuous(breaks = c(1, 5, 10, 15, 20)) +
  scale_y_continuous(breaks = c(1, 5, 10, 15, 20)) +
  labs(title = "Same sites, same species lists, two different answers",
       subtitle = "LCBD rank, 1 is the most unique site",
       x = "rank under Hellinger", y = "rank under Jaccard", colour = NULL) +
  theme_te() + theme(legend.position = "bottom")

## ---- permtest ----
lcbd_test <- function(Y, nperm = 999) {
  obs <- beta_div(Y)$LCBD
  cnt <- rep(1, length(obs))                        # the observed value counts as one
  for (k in 1:nperm) {
    Yp <- apply(Y, 2, sample)                       # permute each species column independently
    cnt <- cnt + (beta_div(Yp)$LCBD >= obs)
  }
  cnt / (nperm + 1)
}

set.seed(3063)
pvals <- lcbd_test(Yg, nperm = 499)
signif_sites <- which(pvals <= 0.05)

data.frame(site = signif_sites, richness = rich[signif_sites],
           LCBD = round(bg$LCBD[signif_sites], 4), p = pvals[signif_sites])
