# Niche equivalency and similarity tests
# https://tidyecology.com/posts/niche-equivalency-and-similarity-tests/
#
# 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(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 = "#e7e6da", linewidth = 0.3),
      plot.title = element_text(face = "bold", size = 13),
      axis.title = element_text(colour = "#46604a"),
      strip.text = element_text(face = "bold", colour = "#275139")
    )
}

## ---- functions ----
gx <- 40; gy <- 40
temp  <- seq(5, 25, length.out = gx)
moist <- seq(0, 1, length.out = gy)
grid  <- expand.grid(temp = temp, moist = moist)

smoother <- function(ax, bw) {
  K <- exp(-0.5 * (outer(ax, ax, "-") / bw)^2)
  K / rowSums(K)
}
St <- smoother(temp, 2.0); Sm <- smoother(moist, 0.10)

niche_density <- function(pt, pm) {
  it <- findInterval(pt, c(-Inf, (temp[-1] + temp[-gx]) / 2, Inf))
  im <- findInterval(pm, c(-Inf, (moist[-1] + moist[-gy]) / 2, Inf))
  cnt <- matrix(0, gy, gx)
  for (k in seq_along(it)) cnt[im[k], it[k]] <- cnt[im[k], it[k]] + 1
  d <- Sm %*% cnt %*% t(St)
  as.vector(pmax(d, 0)) / sum(d)
}
schoener_D <- function(p, q) sum(pmin(p, q))

avail <- with(grid, dnorm(temp, 15, 4) * dnorm(moist, 0.5, 0.22))
avail <- avail / sum(avail)
draw_occ <- function(n, t0, m0, st = 2.5, sm = 0.14) {
  w <- avail * with(grid, dnorm(grid$temp, t0, st) * dnorm(grid$moist, m0, sm))
  idx <- sample.int(nrow(grid), n, replace = TRUE, prob = w)
  list(t = grid$temp[idx], m = grid$moist[idx])
}
draw_bg <- function(n) {
  idx <- sample.int(nrow(grid), n, replace = TRUE, prob = avail)
  list(t = grid$temp[idx], m = grid$moist[idx])
}

equiv_test <- function(oa, ob, R = 199) {
  nA <- length(oa$t); nB <- length(ob$t)
  allt <- c(oa$t, ob$t); allm <- c(oa$m, ob$m)
  Dobs <- schoener_D(niche_density(oa$t, oa$m), niche_density(ob$t, ob$m))
  Dnull <- numeric(R)
  for (r in 1:R) {
    s <- sample.int(nA + nB); ga <- s[1:nA]; gb <- s[(nA + 1):(nA + nB)]
    Dnull[r] <- schoener_D(niche_density(allt[ga], allm[ga]),
                           niche_density(allt[gb], allm[gb]))
  }
  list(Dobs = Dobs, p = (sum(Dnull <= Dobs) + 1) / (R + 1), Dnull = Dnull)
}
sim_test <- function(oa, ob, R = 199) {
  pa <- niche_density(oa$t, oa$m)
  Dobs <- schoener_D(pa, niche_density(ob$t, ob$m))
  nB <- length(ob$t); Dnull <- numeric(R)
  for (r in 1:R) { bg <- draw_bg(nB); Dnull[r] <- schoener_D(pa, niche_density(bg$t, bg$m)) }
  list(Dobs = Dobs, Dnull = Dnull,
       p_more = (sum(Dnull >= Dobs) + 1) / (R + 1),
       p_less = (sum(Dnull <= Dobs) + 1) / (R + 1))
}

## ---- calib ----
set.seed(101)
reps <- 200; rej_same <- logical(reps)
for (i in 1:reps) {
  oa <- draw_occ(80, 15, 0.5); ob <- draw_occ(80, 15, 0.5)   # one shared niche
  rej_same[i] <- equiv_test(oa, ob, R = 99)$p < 0.05
}
rej_rate <- mean(rej_same)

## ---- mag ----
set.seed(202)
ns <- c(30, 60, 120, 240, 480); reps2 <- 150; off <- 1.5
rej_n <- numeric(length(ns))
for (j in seq_along(ns)) {
  rj <- logical(reps2)
  for (i in 1:reps2) {
    oa <- draw_occ(ns[j], 15 - off/2, 0.5)
    ob <- draw_occ(ns[j], 15 + off/2, 0.5)
    rj[i] <- equiv_test(oa, ob, R = 99)$p < 0.05
  }
  rej_n[j] <- mean(rj)
}
mag <- data.frame(n = ns, rejection = rej_n)

## ---- fig-mag ----
ggplot(mag, aes(n, rejection)) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = "#b5534e") +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 2.6) +
  scale_x_continuous(transform = "log2", breaks = ns) +
  scale_y_continuous(limits = c(0, 1)) +
  annotate("text", x = 30, y = 0.10, label = "nominal 5%",
           hjust = 0, size = 3.3, colour = "#b5534e") +
  labs(title = "A fixed niche difference always rejects, given enough data",
       x = "sample size per species (log scale)", y = "rejection rate") +
  theme_te()

## ---- pair-similar ----
set.seed(303)
oa <- draw_occ(200, 14, 0.48); ob <- draw_occ(200, 16, 0.52)
eq1 <- equiv_test(oa, ob, R = 299)
si1 <- sim_test(oa, ob, R = 299)

## ---- pair-divergent ----
set.seed(404)
oc <- draw_occ(200, 11, 0.35); od <- draw_occ(200, 20, 0.70)
eq2 <- equiv_test(oc, od, R = 299)
si2 <- sim_test(oc, od, R = 299)

## ---- fig-sim-contrast ----
sc <- rbind(
  data.frame(D = si1$Dnull, pair = "Similar pair (14 vs 16)", obs = si1$Dobs),
  data.frame(D = si2$Dnull, pair = "Divergent pair (11 vs 20)", obs = si2$Dobs)
)
sc$pair <- factor(sc$pair, levels = c("Similar pair (14 vs 16)", "Divergent pair (11 vs 20)"))
obs_df <- unique(sc[, c("pair", "obs")])
ggplot(sc, aes(D)) +
  geom_histogram(bins = 30, fill = "#93a87f", colour = "white", linewidth = 0.15) +
  geom_vline(data = obs_df, aes(xintercept = obs), colour = "#b5534e", linewidth = 0.9) +
  facet_wrap(~pair, scales = "free_x") +
  labs(title = "Same equivalency verdict, opposite similarity verdict",
       x = "Schoener's D", y = "count") +
  theme_te()
