# Checking a model-based multivariate model
# https://tidyecology.com/posts/checking-a-model-based-multivariate-model/
#
# 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-06-04

## ---- 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"; te_gold <- "#c9b458"
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 ----
gen_null <- function(seed, n = 50, S = 12, theta = 2, sd_f = 0.7) {
  set.seed(seed)
  b0 <- log(c(rep(8,4), rep(3,4), rep(1,4)))
  f  <- rnorm(n, 0, sd_f)                          # shared site factor => species correlate
  load <- runif(S, 0.5, 1.2)
  mu <- exp(outer(rep(1,n), b0) + outer(f, load))
  L  <- matrix(rnbinom(n*S, mu = as.vector(mu), size = theta), n, S)
  list(L = L, grp = rep(c("A","B"), length.out = n))   # random groups, null is true
}
d0 <- gen_null(1)
cc <- cor(log1p(d0$L))
mean_cor <- mean(cc[lower.tri(cc)])
round(mean_cor, 2)

## ---- residuals ----
ds_pois <- function(y, mu, u) { a <- ppois(y-1, mu); b <- ppois(y, mu); qnorm(a + u*(b-a)) }
ds_nb   <- function(y, mu, th, u) {
  a <- pnbinom(y-1, mu = mu, size = th); b <- pnbinom(y, mu = mu, size = th); qnorm(a + u*(b-a)) }
mom_theta <- function(y) { m <- mean(y); v <- var(y); if (v > m*1.05) m^2/(v - m) else 1e4 }

dd <- gen_null(7); Sd <- ncol(dd$L)
fitmu <- sapply(1:Sd, function(j) ave(dd$L[,j], dd$grp, FUN = mean))   # group-mean fitted
th_j  <- apply(dd$L, 2, mom_theta)
set.seed(21); U <- matrix(runif(length(dd$L)), nrow(dd$L), Sd)
rp <- as.vector(mapply(function(j) ds_pois(dd$L[,j], fitmu[,j], U[,j]), 1:Sd))
rn <- as.vector(mapply(function(j) ds_nb(dd$L[,j], fitmu[,j], th_j[j], U[,j]), 1:Sd))
sd_rp <- sd(rp[is.finite(rp)]); sd_rn <- sd(rn[is.finite(rn)])
c(poisson_resid_sd = round(sd_rp, 2), nb_resid_sd = round(sd_rn, 2))

## ---- fig-resid ----
fv <- as.vector(fitmu)
fd <- rbind(data.frame(fit = fv, r = rp, model = sprintf("Poisson (residual SD %.2f)", sd_rp)),
            data.frame(fit = fv, r = rn, model = sprintf("negative binomial (residual SD %.2f)", sd_rn)))
fd <- fd[is.finite(fd$r),]
ggplot(fd, aes(fit, r, colour = model)) +
  geom_hline(yintercept = c(-2, 2), colour = te_line, linewidth = 0.4) +
  geom_point(size = 1.5, alpha = 0.5) + facet_wrap(~model) + scale_x_log10() +
  scale_colour_manual(values = c(te_green, te_warm)) +
  labs(title = "Do the residuals behave?",
       x = "fitted mean (log scale)", y = "Dunn-Smyth residual") +
  theme_te() + theme(legend.position = "none")

## ---- fit ----
nb_lr <- function(y, grp, theta) {
  mu0 <- mean(y); ll0 <- sum(dnbinom(y, mu = mu0, size = theta, log = TRUE))
  mu1 <- ave(y, grp, FUN = mean); ll1 <- sum(dnbinom(y, mu = mu1, size = theta, log = TRUE))
  2*(ll1 - ll0)
}
pois_lr <- function(y, grp) {
  mu0 <- mean(y); ll0 <- sum(dpois(y, mu0, log = TRUE))
  mu1 <- ave(y, grp, FUN = mean); ll1 <- sum(dpois(y, mu1, log = TRUE))
  2*(ll1 - ll0)
}
community <- function(L, grp, B = 149, seed = 1) {
  S <- ncol(L); th <- apply(L, 2, mom_theta)
  obs_nb <- sum(sapply(1:S, function(j) nb_lr(L[,j], grp, th[j])))
  obs_po <- sum(sapply(1:S, function(j) pois_lr(L[,j], grp)))
  set.seed(seed)
  perm <- replicate(B, { g <- sample(grp); sum(sapply(1:S, function(j) nb_lr(L[,j], g, th[j]))) })
  c(nb_perm  = (1 + sum(perm >= obs_nb)) / (B + 1),
    nb_chisq = pchisq(obs_nb, df = S, lower.tail = FALSE),
    po_chisq = pchisq(obs_po, df = S, lower.tail = FALSE))
}

## ---- typeone ----
M <- 240; B <- 149
res <- t(sapply(1:M, function(m) community(gen_null(2000 + m)$L, gen_null(2000 + m)$grp, B = B, seed = m)))
rate <- colMeans(res < 0.05)
round(rate, 3)

## ---- fig-rates ----
rdf <- data.frame(method = factor(c("nb_perm","nb_chisq","po_chisq"),
                                  levels = c("nb_perm","nb_chisq","po_chisq")),
                  rate = as.numeric(rate[c("nb_perm","nb_chisq","po_chisq")]))
ggplot(rdf, aes(method, rate, fill = method)) +
  geom_col(width = 0.62) + geom_hline(yintercept = 0.05, colour = te_ink, linetype = "dashed") +
  geom_text(aes(label = sprintf("%.2f", rate)), nudge_y = 0.025, vjust = 0,
            colour = te_ink, size = 4) +
  scale_fill_manual(values = c(te_green, te_gold, te_warm)) +
  scale_x_discrete(labels = c("NB +\npermutation", "NB + chi-square\n(independence)", "Poisson +\nchi-square")) +
  labs(title = "What each shortcut does to the false-positive rate",
       x = NULL, y = "rejection rate at 0.05") + theme_te() + theme(legend.position = "none")
