# Model-based multivariate abundance
# https://tidyecology.com/posts/model-based-multivariate-abundance/
#
# 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(MASS)
library(ggplot2)

te_ink   <- "#16241d"; te_body <- "#2c3a31"; te_green <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line  <- "#dad9ca"; te_faint <- "#5d6b61"; te_warm <- "#b5534e"
theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#5d6b61"),
          plot.title = element_text(colour = "#16241d", face = "bold", size = 13),
          plot.subtitle = element_text(colour = "#46604a", size = 10),
          strip.text = element_text(colour = "#275139", face = "bold"),
          legend.title = element_text(colour = "#2c3a31"),
          legend.text  = element_text(colour = "#46604a"),
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}

## ---- data ----
set.seed(4222)
S     <- 20
n_per <- 25
grp   <- factor(rep(c("Control", "Impact"), each = n_per),
                levels = c("Control", "Impact"))
n     <- length(grp)

base_mu   <- c(rep(14, 3), rep(7, 5), rep(3, 7), rep(1.1, 5))  # control means
mult      <- rep(0.30, S)                                      # impact: abundance reduction
mult[1:4] <- 0.12                                              # four sensitive species
theta_true <- 2                                               # NB size, identical in both groups

mu_mat <- outer(rep(1, n), base_mu)
mu_mat[grp == "Impact", ] <- sweep(mu_mat[grp == "Impact", ], 2, mult, "*")
Y <- matrix(rnbinom(n * S, mu = as.vector(mu_mat), size = theta_true), n, S)
colnames(Y) <- paste0("sp", 1:S)

mean_ctrl  <- mean(Y[grp == "Control", ])
mean_imp   <- mean(Y[grp == "Impact", ])
ratio_mean <- mean_imp / mean_ctrl
zeros_ctrl <- 100 * mean(Y[grp == "Control", ] == 0)
zeros_imp  <- 100 * mean(Y[grp == "Impact", ] == 0)
c(mean_ctrl = mean_ctrl, mean_imp = mean_imp, ratio = ratio_mean)

## ---- meanvar ----
sp_mean  <- colMeans(Y[grp == "Control", ])
sp_var   <- apply(Y[grp == "Control", ], 2, var)
mv_slope <- coef(lm(log(sp_var) ~ log(sp_mean)))[2]
round(mv_slope, 3)

## ---- fig-meanvar ----
gg  <- seq(min(sp_mean), max(sp_mean), length = 100)
ref <- rbind(data.frame(mean = gg, var = gg, ref = "Poisson (var = mean)"),
             data.frame(mean = gg, var = gg + gg^2 / theta_true,
                        ref = "negative binomial"))
ggplot(data.frame(mean = sp_mean, var = sp_var), aes(mean, var)) +
  geom_line(data = ref, aes(mean, var, linetype = ref), colour = te_ink, linewidth = 0.5) +
  geom_point(colour = te_green, size = 2.4) +
  scale_x_log10() + scale_y_log10() +
  labs(title = "Count data have a strong mean-variance relationship",
       x = "species mean abundance (log)", y = "species variance (log)") +
  theme_te() + theme(legend.title = element_blank())

## ---- fit ----
theta_hat <- numeric(S)
for (s in 1:S) {
  fit <- tryCatch(glm.nb(Y[, s] ~ 1), error = function(e) NULL)
  theta_hat[s] <- if (is.null(fit)) 1e6 else fit$theta
}

lr_species <- function(y, g, th) {
  f1 <- glm(y ~ g, family = negative.binomial(th))
  f0 <- glm(y ~ 1, family = negative.binomial(th))
  as.numeric(deviance(f0) - deviance(f1))
}
LR_obs    <- sapply(1:S, function(s) lr_species(Y[, s], grp, theta_hat[s]))
Tcomm_obs <- sum(LR_obs)
round(Tcomm_obs, 1)

## ---- perm ----
B <- 999
Tperm <- numeric(B)
for (b in 1:B) {
  gp <- sample(grp)
  Tperm[b] <- sum(sapply(1:S, function(s) lr_species(Y[, s], gp, theta_hat[s])))
}
p_comm <- (1 + sum(Tperm >= Tcomm_obs)) / (B + 1)
c(observed = round(Tcomm_obs, 1), max_null = round(max(Tperm), 1), p = p_comm)

## ---- permdisp ----
bray <- function(M) {
  n <- nrow(M); D <- matrix(0, n, n)
  for (i in 1:(n - 1)) for (j in (i + 1):n) {
    d <- sum(abs(M[i, ] - M[j, ])) / sum(M[i, ] + M[j, ]); D[i, j] <- D[j, i] <- d
  }
  D
}
D  <- bray(Y)
G  <- { A <- -0.5 * D^2; Cn <- diag(n) - matrix(1/n, n, n); Cn %*% A %*% Cn }
ev <- eigen(G, symmetric = TRUE)
X  <- ev$vectors[, ev$values > 1e-8] %*% diag(sqrt(ev$values[ev$values > 1e-8]))

dcen <- numeric(n)
for (lev in levels(grp)) {
  idx <- grp == lev; ctr <- colMeans(X[idx, , drop = FALSE])
  dcen[idx] <- sqrt(rowSums(sweep(X[idx, , drop = FALSE], 2, ctr)^2))
}
permdisp_F <- function(d, g) {
  gm <- tapply(d, g, mean); grand <- mean(d)
  ssb <- sum(table(g) * (gm - grand)^2); ssw <- sum((d - gm[as.character(g)])^2)
  (ssb / (nlevels(g) - 1)) / (ssw / (length(d) - nlevels(g)))
}
F_obs  <- permdisp_F(dcen, grp)
Fp     <- replicate(999, permdisp_F(dcen, sample(grp)))
p_disp <- (1 + sum(Fp >= F_obs)) / 1000
disp_ctrl <- mean(dcen[grp == "Control"]); disp_imp <- mean(dcen[grp == "Impact"])
c(disp_ctrl = round(disp_ctrl, 3), disp_imp = round(disp_imp, 3),
  F = round(F_obs, 1), p = p_disp)

## ---- fig-confound ----
ggplot(data.frame(group = grp, d = dcen), aes(group, d, fill = group)) +
  geom_boxplot(width = 0.55, outlier.shape = NA, alpha = 0.85) +
  geom_jitter(width = 0.12, height = 0, colour = te_ink, alpha = 0.5, size = 1.4) +
  scale_fill_manual(values = c(Control = te_sage, Impact = te_green)) +
  labs(title = "A pure mean shift fakes a dispersion difference",
       subtitle = sprintf("PERMDISP F = %.1f, p = %s, though dispersion is identical by construction",
                          F_obs, ifelse(p_disp < 0.0015, "0.001", format(round(p_disp, 3)))),
       x = NULL, y = "distance to group centroid (PCoA)") +
  guides(fill = "none") + theme_te()
