# Checking a community classification
# https://tidyecology.com/posts/checking-a-community-classification/
#
# 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-07

## ---- setup ----
library(vegan)
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

n_site <- 30
n_sp   <- 20
noise_matrix <- function(n = n_site, p = n_sp, lambda = 5) {
  matrix(rpois(n * p, lambda), n, p)
}
cut_two <- function(d, linkage = "ward.D2") cutree(hclust(d, method = linkage), k = 2)

## ---- first-look ----
set.seed(20260805)
m1 <- noise_matrix()
d1 <- vegdist(m1)
g1 <- cut_two(d1)
naive1 <- adonis2(d1 ~ factor(g1), permutations = 199)
naive1_p  <- naive1$`Pr(>F)`[1]
naive1_r2 <- naive1$R2[1]
naive1_f  <- naive1$F[1]
table(g1)

## ---- fig-pcoa ----
pc <- cmdscale(d1, k = 2)
pc_df <- data.frame(axis1 = pc[, 1], axis2 = pc[, 2],
                    cluster = factor(g1, labels = c("cluster 1", "cluster 2")))

ggplot(pc_df, aes(x = axis1, y = axis2, colour = cluster, shape = cluster)) +
  geom_point(size = 3, alpha = 0.9) +
  stat_ellipse(level = 0.68, linewidth = 0.5, show.legend = FALSE) +
  scale_colour_manual(values = c("cluster 1" = te_forest, "cluster 2" = te_rust)) +
  labs(x = "principal coordinate 1", y = "principal coordinate 2", colour = NULL,
       shape = NULL, title = "Two convincing clusters, drawn from a single distribution") +
  theme_datasheet() +
  theme(legend.position = "top")

## ---- pseudo-f ----
pseudo_F <- function(d, g) {
  d2 <- as.matrix(d)^2
  n  <- length(g)
  ss_total  <- sum(d2[upper.tri(d2)]) / n
  ss_within <- 0
  for (lev in unique(g)) {
    idx <- which(g == lev)
    if (length(idx) < 2) next
    sub <- d2[idx, idx, drop = FALSE]
    ss_within <- ss_within + sum(sub[upper.tri(sub)]) / length(idx)
  }
  k <- length(unique(g))
  ((ss_total - ss_within) / (k - 1)) / (ss_within / (n - k))
}

f_hand <- pseudo_F(d1, g1)
f_gap  <- abs(f_hand - naive1_f)

## ---- fp-guard-1 ----
stopifnot(f_gap / abs(naive1_f) < 1e-8)

## ---- naive-sweep ----
reps <- 200
linkages <- c("average", "complete", "ward.D2")
sweep <- data.frame(linkage = linkages, adonis = NA_real_, anosim = NA_real_,
                    mean_p = NA_real_, sd_p = NA_real_, smallest = NA_real_,
                    conditional = NA_real_, usable = NA_integer_)

for (i in seq_along(linkages)) {
  p_ad <- numeric(reps); p_an <- numeric(reps); small <- integer(reps)
  set.seed(20260805)
  for (r in seq_len(reps)) {
    d <- vegdist(noise_matrix())
    g <- cut_two(d, linkages[i])
    small[r] <- min(table(g))
    p_ad[r]  <- adonis2(d ~ factor(g), permutations = 199)$`Pr(>F)`[1]
    p_an[r]  <- anosim(d, factor(g), permutations = 199)$signif
  }
  sweep$adonis[i]      <- mean(p_ad <= 0.05) * 100
  sweep$anosim[i]      <- mean(p_an <= 0.05) * 100
  sweep$mean_p[i]      <- mean(p_ad)
  sweep$sd_p[i]        <- sd(p_ad)
  sweep$smallest[i]    <- median(small)
  sweep$conditional[i] <- mean(p_ad[small >= 2] <= 0.05) * 100
  sweep$usable[i]      <- sum(small >= 2)
}
sweep

## ---- fig-linkage ----
link_df <- rbind(
  data.frame(linkage = sweep$linkage, rate = sweep$adonis, subset = "all data sets"),
  data.frame(linkage = sweep$linkage, rate = sweep$conditional,
             subset = "cut gives two groups of 2 or more"))
link_df$linkage <- factor(link_df$linkage, levels = linkages)

ggplot(link_df, aes(x = linkage, y = rate, fill = subset)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  geom_text(aes(label = sprintf("%.1f", rate)),
            position = position_dodge(width = 0.7), vjust = -0.5,
            colour = te_body, size = 3.5) +
  scale_fill_manual(values = c("all data sets" = te_gold,
                               "cut gives two groups of 2 or more" = te_forest)) +
  scale_y_continuous(limits = c(0, 112)) +
  labs(x = NULL, y = "data sets declared significant (per cent)", fill = NULL,
       title = "The linkage decides the cut, and the cut decides the rate") +
  theme_datasheet() +
  theme(legend.position = "top")

## ---- corrected-test ----
corrected_p <- function(m, nperm = 199) {
  d <- vegdist(m)
  f_obs <- pseudo_F(d, cut_two(d))
  f_null <- replicate(nperm, {
    d_b <- vegdist(apply(m, 2, sample))
    pseudo_F(d_b, cut_two(d_b))
  })
  list(p = (1 + sum(f_null >= f_obs)) / (nperm + 1), f_obs = f_obs, f_null = f_null)
}

set.seed(4)
demo <- corrected_p(m1)
demo_p    <- demo$p
demo_fobs <- demo$f_obs
demo_fmed <- median(demo$f_null)

## ---- fig-nulls ----
ggplot(data.frame(f = demo$f_null), aes(x = f)) +
  geom_histogram(bins = 24, fill = te_forest, colour = te_paper) +
  geom_vline(xintercept = demo_fobs, linetype = "dashed", colour = te_rust, linewidth = 0.9) +
  annotate("text", x = demo_fobs, y = Inf, vjust = 1.6, hjust = -0.05,
           colour = te_rust, size = 3.6, label = "observed") +
  labs(x = "pseudo-F from reclustered permutations", y = "permutations",
       title = "The comparison the naive test never makes") +
  theme_datasheet()

## ---- calibration ----
set.seed(77)
n_null <- 100
p_corr_noise <- replicate(n_null, corrected_p(noise_matrix())$p)
corr_noise_rate <- mean(p_corr_noise <= 0.05) * 100
corr_se <- 100 * sqrt(0.05 * 0.95 / n_null)

## ---- structure-power ----
structured_matrix <- function(sep) {
  half <- n_site / 2
  base <- exp(rnorm(n_sp, 1.5, 0.7))
  w <- rep(c(sep, 1 / sep), length.out = n_sp)
  rbind(matrix(rpois(half * n_sp, rep(base, each = half)), half, n_sp),
        matrix(rpois(half * n_sp, rep(base * w, each = half)), half, n_sp))
}

truth <- rep(1:2, each = n_site / 2)
n_str <- 30
run_structured <- function(sep, seed) {
  set.seed(seed)
  p_c <- numeric(n_str); rec <- numeric(n_str)
  for (r in seq_len(n_str)) {
    m <- structured_matrix(sep)
    g <- cut_two(vegdist(m))
    rec[r] <- max(mean(g == truth), mean(g != truth))
    p_c[r] <- corrected_p(m)$p
  }
  c(recovery = mean(rec) * 100, power = mean(p_c <= 0.05) * 100)
}
strong <- run_structured(1.8, 500)
weak   <- run_structured(1.25, 501)

## ---- fig-summary ----
summ <- data.frame(
  what = factor(c("naive, noise", "reclustered, noise",
                  "reclustered, strong groups", "reclustered, weak groups"),
                levels = c("naive, noise", "reclustered, noise",
                           "reclustered, strong groups", "reclustered, weak groups")),
  rate = c(sweep$adonis[sweep$linkage == "ward.D2"], corr_noise_rate,
           strong[["power"]], weak[["power"]]),
  kind = c("no structure in the data", "no structure in the data",
           "real groups", "real groups"))

ggplot(summ, aes(x = what, y = rate, fill = kind)) +
  geom_col(width = 0.55) +
  geom_hline(yintercept = 5, linetype = "dotted", colour = te_ink) +
  annotate("text", x = 1.5, y = 7, label = "nominal\n5 per cent",
           hjust = 0.5, vjust = 0, lineheight = 0.9, colour = te_ink, size = 3) +
  geom_text(aes(label = sprintf("%.0f", rate)), vjust = -0.5, colour = te_body, size = 4) +
  scale_fill_manual(values = c("no structure in the data" = te_rust,
                               "real groups" = te_forest)) +
  scale_y_continuous(limits = c(0, 112)) +
  labs(x = NULL, y = "runs declared significant (per cent)", fill = NULL,
       title = "What each test does when there is, and is not, something to find") +
  theme_datasheet() +
  theme(legend.position = "top", axis.text.x = element_text(angle = 15, hjust = 1))
