# Zeta diversity in R: beyond pairwise turnover
# https://tidyecology.com/posts/zeta-diversity-multi-site/
#
# 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-11-05

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

## ---- zeta-def ----
zeta <- function(X, i) {
  k <- colSums(X)                       # occupancy: how many sites hold each species
  sum(choose(k, i)) / choose(nrow(X), i)
}

zeta_brute <- function(X, i) {          # the definition, spelled out, for checking only
  mean(apply(combn(nrow(X), i), 2, function(rows) sum(colSums(X[rows, , drop = FALSE]) == i)))
}

## ---- zeta-check ----
set.seed(305)
Xs <- matrix(rbinom(9 * 60, 1, 0.4), 9, 60)      # 9 sites, 60 species

chk <- data.frame(i = 1:9,
                  subsets   = choose(9, 1:9),
                  formula   = sapply(1:9, function(i) zeta(Xs, i)),
                  brute     = sapply(1:9, function(i) zeta_brute(Xs, i)))
chk$gap <- abs(chk$formula - chk$brute)
knitr::kable(chk, digits = c(0, 0, 8, 8, 20),
             col.names = c("order i", "subsets averaged", "combinatorial formula", "brute force", "gap"))

## ---- zeta-anchors ----
c(zeta_1 = zeta(Xs, 1), mean_richness = mean(rowSums(Xs)),
  zeta_2 = zeta(Xs, 2),
  mean_shared_over_pairs = mean(combn(9, 2, function(p) sum(colSums(Xs[p, ]) == 2))))

## ---- ratio-trap ----
sor_pairs <- combn(9, 2, function(p) {
  a <- sum(colSums(Xs[p, ]) == 2)
  2 * a / sum(rowSums(Xs[p, ]))
})

c(ratio_of_means = zeta(Xs, 2) / zeta(Xs, 1),
  mean_of_ratios = mean(sor_pairs),
  difference     = zeta(Xs, 2) / zeta(Xs, 1) - mean(sor_pairs))

## ---- exact-independent ----
zeta_expected <- function(p) function(i) sum(p^i)     # exact for independent occurrence

set.seed(3051)
n_sites <- 30
p_eq <- rep(0.45, 300)                                # 300 species, all with p = 0.45
X_eq <- matrix(rbinom(n_sites * 300, 1, rep(p_eq, each = n_sites)), n_sites, 300)

eq <- data.frame(i = 1:10,
                 observed = sapply(1:10, function(i) zeta(X_eq, i)),
                 expected = sapply(1:10, zeta_expected(p_eq)),
                 closed_form = 300 * 0.45^(1:10))
knitr::kable(eq, digits = 3,
             col.names = c("order i", "observed zeta", "expected under independence", "S * p^i"))

## ---- trap-power ----
set.seed(3052)
S <- 300
p_het <- rbeta(S, 0.6, 0.9)                           # occupancy probabilities now vary
X_het <- matrix(rbinom(n_sites * S, 1, rep(p_het, each = n_sites)), n_sites, S)

z_het <- sapply(1:12, function(i) zeta(X_het, i))
i_ax  <- 1:12

fit_exp <- lm(log(z_het) ~ i_ax)
fit_pow <- lm(log(z_het) ~ log(i_ax))
d_aic   <- AIC(fit_exp) - AIC(fit_pow)

c(cv_of_p = sd(p_het) / mean(p_het),
  r2_exponential = summary(fit_exp)$r.squared,
  r2_power       = summary(fit_pow)$r.squared,
  delta_AIC_favouring_power = d_aic)

## ---- fig-forms ----
z_eq <- sapply(1:12, function(i) zeta(X_eq, i))
mk_fits <- function(z, lab) {
  fe <- lm(log(z) ~ i_ax); fp <- lm(log(z) ~ log(i_ax))
  rbind(data.frame(i = i_ax, zeta = z, kind = "observed", panel = lab),
        data.frame(i = i_ax, zeta = exp(fitted(fe)), kind = "exponential fit", panel = lab),
        data.frame(i = i_ax, zeta = exp(fitted(fp)), kind = "power-law fit", panel = lab))
}
ff <- rbind(mk_fits(z_eq,  "equal occupancy (CV = 0)"),
            mk_fits(z_het, sprintf("unequal occupancy (CV = %.2f)", sd(p_het) / mean(p_het))))

ggplot(ff, aes(i, zeta, colour = kind, linetype = kind)) +
  geom_line(linewidth = 0.8) +
  facet_wrap(~ panel) +
  scale_y_log10(breaks = 10^(-1:3), labels = c("0.1", "1", "10", "100", "1000")) +
  scale_x_continuous(breaks = seq(2, 12, 2)) +
  scale_colour_manual(values = c("observed" = "#16241d", "exponential fit" = "#2f8f63",
                                 "power-law fit" = "#b5534e")) +
  scale_linetype_manual(values = c("observed" = "solid", "exponential fit" = "dashed",
                                   "power-law fit" = "dotted")) +
  labs(title = "The zeta decline diagnoses occupancy, not assembly",
       subtitle = "both communities: 300 species, 30 sites, every species placed independently",
       x = "order i (number of sites)", y = "zeta (log scale)", colour = NULL, linetype = NULL) +
  theme_te() + theme(legend.position = "bottom",
                     strip.text = element_text(colour = "#46604a", size = 9.5))

## ---- sweep ----
set.seed(3053)
dAIC_of <- function(z) {
  keep <- z > 0.5; ii <- which(keep); zz <- z[keep]
  if (length(zz) < 4) return(NA_real_)
  AIC(lm(log(zz) ~ ii)) - AIC(lm(log(zz) ~ log(ii)))
}

pars <- list(c(400, 600), c(40, 60), c(10, 15), c(4, 6), c(1.5, 2.25), c(0.8, 1.2), c(0.35, 0.55))
sweep_res <- do.call(rbind, lapply(pars, function(ab) {
  r <- replicate(12, {
    p <- rbeta(S, ab[1], ab[2])
    Xi <- matrix(rbinom(n_sites * S, 1, rep(p, each = n_sites)), n_sites, S)
    c(sd(p) / mean(p), dAIC_of(sapply(1:12, function(i) zeta(Xi, i))))
  })
  data.frame(cv = mean(r[1, ]), dAIC = mean(r[2, ], na.rm = TRUE), se = sd(r[2, ], na.rm = TRUE) / sqrt(12))
}))
sweep_res$verdict <- ifelse(sweep_res$dAIC > 2, "power law",
                     ifelse(sweep_res$dAIC < -2, "exponential", "tie"))
knitr::kable(sweep_res, digits = c(3, 1, 1, 0),
             col.names = c("CV of occupancy probability", "mean delta AIC (positive favours power law)",
                           "standard error", "verdict"))

## ---- fig-sweep ----
ggplot(sweep_res, aes(cv, dAIC)) +
  geom_hline(yintercept = 0, colour = "#93a87f", linewidth = 0.4) +
  geom_errorbar(aes(ymin = dAIC - se, ymax = dAIC + se), width = 0.02, colour = "#93a87f") +
  geom_line(colour = "#275139", linewidth = 0.8) +
  geom_point(size = 2.4, colour = "#16241d") +
  annotate("text", x = max(sweep_res$cv), y = 0.25 * max(sweep_res$dAIC), label = "power law wins",
           colour = "#b5534e", size = 3.2, hjust = 1) +
  annotate("text", x = min(sweep_res$cv), y = 0.25 * min(sweep_res$dAIC), label = "exponential wins",
           colour = "#2f8f63", size = 3.2, hjust = 0) +
  labs(title = "Where the verdict flips", subtitle = "zero species interactions anywhere on this chart",
       x = "coefficient of variation of occupancy probability", y = "delta AIC") +
  theme_te()

## ---- retention ----
ret <- function(z) z[-1] / z[-length(z)]
r_eq  <- ret(sapply(1:8, function(i) zeta(X_eq, i)))
r_het <- ret(sapply(1:8, function(i) zeta(X_het, i)))

knitr::kable(data.frame(step = paste0("zeta_", 2:8, " / zeta_", 1:7),
                        equal_occupancy = r_eq, unequal_occupancy = r_het),
             digits = 3, col.names = c("step", "equal occupancy", "unequal occupancy"))
