# Multiplicative beta diversity with Hill numbers
# https://tidyecology.com/posts/multiplicative-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-14

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

sum_pq <- function(p, q) { p <- p[p > 0]; sum(p^q) }   # the zero mask matters: 0^0 is 1 in R

gamma_hill <- function(Y, q) hill(colMeans(Y / rowSums(Y)), q)   # pooled, equal weights

## ---- trap-additive ----
gini <- function(p) 1 - sum(p^2)

mk_distinct <- function(S, N = 2) {          # N communities, S species each, zero overlap
  Y <- matrix(0, N, N * S)
  for (i in 1:N) Y[i, ((i - 1) * S + 1):(i * S)] <- 1
  Y
}

add_gs <- function(Y) {
  P <- Y / rowSums(Y)
  gini(colMeans(P)) - mean(apply(P, 1, gini))
}

S_grid <- c(5, 10, 25, 50, 100)
tab1 <- data.frame(
  S        = S_grid,
  shared   = 0L,
  beta_add = sapply(S_grid, function(S) add_gs(mk_distinct(S))),
  formula  = 1 / (2 * S_grid)
)
tab1$abs_gap <- abs(tab1$beta_add - tab1$formula)

# a gap this small is floating-point rounding, so the tables say it in words
gap_text <- function(g) {
  stopifnot(all(g < 1e-10))
  ifelse(g == 0, "0", "rounding only")
}
knitr::kable(transform(tab1, abs_gap = gap_text(abs_gap)), digits = c(0, 0, 6, 6, 20),
             col.names = c("S per site", "shared species", "additive Gini-Simpson beta",
                           "1/(2S)", "gap"))

## ---- trap-additive-mult ----
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, sum_pq, q = q))^(1 / (1 - q))
}

beta_mult <- function(Y, q) gamma_hill(Y, q) / alpha_jost(Y, q)

tab1$beta_hill_q2 <- sapply(S_grid, function(S) beta_mult(mk_distinct(S), 2))
knitr::kable(tab1[, c("S", "beta_add", "beta_hill_q2")], digits = c(0, 6, 10),
             col.names = c("S per site", "additive Gini-Simpson beta", "multiplicative Hill beta (q = 2)"))

## ---- fig-collapse ----
S_fine <- round(exp(seq(log(3), log(200), length.out = 40)))
fine <- data.frame(S = S_fine,
                   add  = sapply(S_fine, function(S) add_gs(mk_distinct(S))),
                   mult = sapply(S_fine, function(S) beta_mult(mk_distinct(S), 2)))

pA <- ggplot(fine, aes(S, add)) +
  geom_line(colour = "#b5534e", linewidth = 1) +
  scale_x_log10() +
  labs(title = "Additive Gini-Simpson beta", subtitle = "two communities, zero shared species",
       x = NULL, y = "beta") + theme_te()
pB <- ggplot(fine, aes(S, mult)) +
  geom_line(colour = "#275139", linewidth = 1) +
  scale_x_log10() + coord_cartesian(ylim = c(0, 3)) +
  labs(title = "Multiplicative Hill beta (q = 2)", subtitle = "same data, same species, same zero overlap",
       x = "species per site", y = "beta") + theme_te()

grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(2, 1)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- trap-alpha ----
Y2 <- matrix(0, 2, 101)
Y2[1, 1:100] <- 1     # site A: 100 even species
Y2[2, 101]   <- 1     # site B: one species, and it is not in A

per_site  <- apply(Y2 / rowSums(Y2), 1, hill, q = 2)
g2        <- gamma_hill(Y2, 2)
a_naive   <- mean(per_site)          # arithmetic mean of the per-site Hill numbers
a_correct <- alpha_jost(Y2, 2)

c(site_A = per_site[1], site_B = per_site[2],
  gamma = g2, alpha_naive = a_naive, alpha_jost = a_correct,
  beta_naive = g2 / a_naive, beta_jost = g2 / a_correct)

## ---- harmonic ----
c(alpha_jost = a_correct, harmonic_mean = 1 / mean(1 / per_site),
  gap = abs(a_correct - 1 / mean(1 / per_site)))

## ---- power-mean ----
set.seed(304)
Yr <- matrix(rpois(6 * 40, 3), 6, 40)          # six sites, forty species

pm_check <- do.call(rbind, lapply(c(0, 0.5, 2, 3), function(q) {
  ds <- apply(Yr / rowSums(Yr), 1, hill, q = q)
  data.frame(q = q, order = 1 - q,
             alpha_jost  = alpha_jost(Yr, q),
             power_mean  = mean(ds^(1 - q))^(1 / (1 - q)))
}))
pm_check$gap <- abs(pm_check$alpha_jost - pm_check$power_mean)
knitr::kable(transform(pm_check, gap = gap_text(gap)), digits = c(1, 1, 8, 8, 20),
             col.names = c("q", "mean order (1 - q)", "Jost alpha", "power mean of per-site Hill numbers", "gap"))

## ---- range ----
range_tab <- do.call(rbind, lapply(c(2, 3, 5, 8), function(N) {
  Y_dist <- mk_distinct(20, N)                # N communities, nothing shared
  Y_same <- matrix(1, N, 20)                  # N identical communities
  data.frame(N = N,
             distinct_q0 = beta_mult(Y_dist, 0), distinct_q1 = beta_mult(Y_dist, 1),
             distinct_q2 = beta_mult(Y_dist, 2),
             identical_q1 = beta_mult(Y_same, 1), identical_q2 = beta_mult(Y_same, 2))
}))
knitr::kable(range_tab, digits = 10,
             col.names = c("N", "distinct, q=0", "distinct, q=1", "distinct, q=2",
                           "identical, q=1", "identical, q=2"))

## ---- bridge ----
P  <- Yr / rowSums(Yr)
Hs <- apply(P, 1, function(p) { p <- p[p > 0]; -sum(p * log(p)) })
Hg <- { p <- colMeans(P); p <- p[p > 0]; -sum(p * log(p)) }

c(log_beta_mult = log(beta_mult(Yr, 1)),
  H_gamma_minus_H_alpha = Hg - mean(Hs),
  gap = abs(log(beta_mult(Yr, 1)) - (Hg - mean(Hs))))

## ---- overlap ----
CqN <- function(beta, q, N) {
  if (abs(q - 1) < 1e-10) return(1 - log(beta) / log(N))
  ((1 / beta)^(q - 1) - (1 / N)^(q - 1)) / (1 - (1 / N)^(q - 1))
}

set.seed(3041)
sor_check <- do.call(rbind, lapply(1:5, function(i) {
  a <- sample(2:20, 1); b <- sample(1:20, 1); cc <- sample(1:20, 1)
  Y <- matrix(0, 2, a + b + cc)
  Y[1, 1:(a + b)] <- 1                                # a shared, b only in A
  Y[2, c(1:a, (a + b + 1):(a + b + cc))] <- 1         # a shared, c only in B
  data.frame(a = a, b = b, c = cc,
             beta_q0  = beta_mult(Y, 0),
             C_02     = CqN(beta_mult(Y, 0), 0, 2),
             sorensen = 2 * a / (2 * a + b + cc))
}))
sor_check$gap <- abs(sor_check$C_02 - sor_check$sorensen)
knitr::kable(transform(sor_check, gap = gap_text(gap)), digits = c(0, 0, 0, 6, 10, 10, 20))

## ---- morisita ----
set.seed(3042)
mh_check <- do.call(rbind, lapply(1:4, function(i) {
  Y <- matrix(rpois(2 * 12, 4), 2, 12)
  Y[1, sample(12, 3)] <- 0; Y[2, sample(12, 3)] <- 0
  Pm <- Y / rowSums(Y)
  data.frame(beta_q2 = beta_mult(Y, 2),
             C_22 = CqN(beta_mult(Y, 2), 2, 2),
             morisita_horn = 2 * sum(Pm[1, ] * Pm[2, ]) / (sum(Pm[1, ]^2) + sum(Pm[2, ]^2)))
}))
mh_check$gap <- abs(mh_check$C_22 - mh_check$morisita_horn)
knitr::kable(transform(mh_check, gap = gap_text(gap)), digits = c(6, 10, 10, 20))

## ---- fig-profile ----
set.seed(3043)
mk_set <- function(kind) {
  Y <- matrix(0, 4, 60)
  if (kind == "rare species differ") {
    for (i in 1:4) { Y[i, 1:28] <- 30; Y[i, 28 + ((i - 1) * 8 + 1):((i - 1) * 8 + 8)] <- 2 }
  } else if (kind == "dominants differ") {
    for (i in 1:4) { Y[i, 1:60] <- 5; Y[i, ((i - 1) * 15 + 1):((i - 1) * 15 + 15)] <- 60 }
  } else {
    for (i in 1:4) Y[i, ((i - 1) * 15 + 1):((i - 1) * 15 + 15)] <- 20
  }
  Y
}
qs <- seq(0, 3, by = 0.1)
prof <- do.call(rbind, lapply(c("rare species differ", "dominants differ", "no overlap at all"), function(k) {
  Y <- mk_set(k); data.frame(q = qs, beta = sapply(qs, function(q) beta_mult(Y, q)), set = k)
}))
ggplot(prof, aes(q, beta, colour = set)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("rare species differ" = "#c9b458",
                                 "dominants differ" = "#2f8f63",
                                 "no overlap at all" = "#b5534e")) +
  coord_cartesian(ylim = c(1, 4.15)) +
  labs(title = "The beta profile", subtitle = "four communities in each set; the ceiling is N = 4",
       x = "order q", y = "multiplicative beta", colour = NULL) +
  theme_te() + theme(legend.position = "bottom")

## ---- profile-numbers ----
pw <- do.call(rbind, lapply(c("rare species differ", "dominants differ"), function(k) {
  Y <- mk_set(k)
  data.frame(set = k, beta_q0 = beta_mult(Y, 0), beta_q1 = beta_mult(Y, 1), beta_q2 = beta_mult(Y, 2))
}))
knitr::kable(pw, digits = 3, col.names = c("site set", "beta (q = 0)", "beta (q = 1)", "beta (q = 2)"))
