# The mid-domain effect as a null for richness
# https://tidyecology.com/posts/the-mid-domain-effect-null/
#
# 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(ggplot2)
library(patchwork)

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"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- design ----
n_sp     <- 250     # species in the regional pool
n_band   <- 40      # bands along the domain
n_null   <- 199     # null placements per world
n_world  <- 300     # simulated worlds per cell
alpha    <- 0.05
opt_sd   <- 0.15    # spread of midpoints around a central optimum
ext_sets <- list("Beta(1, 3)" = c(1, 3), "Beta(2, 2)" = c(2, 2))
band_mid <- (seq_len(n_band) - 0.5) / n_band

# richness per band for many sets of ranges at once (species in rows, sets in columns)
band_rich <- function(lo, hi) {
  n_set <- ncol(lo)
  first <- pmax(ceiling(lo * n_band + 0.5), 1)
  last  <- pmin(floor(hi * n_band + 0.5), n_band)
  ok    <- first <= last
  off   <- (col(lo) - 1) * (n_band + 1)
  step  <- tabulate((off + first)[ok], n_set * (n_band + 1)) -
    tabulate((off + last + 1)[ok], n_set * (n_band + 1))
  apply(matrix(step, n_band + 1), 2, cumsum)[seq_len(n_band), , drop = FALSE]
}

# Colwell-Lees null: keep each extent, draw its midpoint uniformly where it fits
null_envelope <- function(lo, hi) {
  ext   <- hi - lo
  mid0  <- ext / 2 + matrix(runif(n_sp * n_null), n_sp) * (1 - ext)
  nullr <- band_rich(mid0 - ext / 2, mid0 + ext / 2)
  offb  <- rep((seq_len(n_band) - 1) * 1000, n_null)
  srt   <- matrix(sort(nullr + offb) - sort(offb), ncol = n_band)
  list(lo = srt[5, ], hi = srt[195, ], mean = rowMeans(nullr), nullr = nullr)
}

# species-level test: where each midpoint sits inside its own feasible interval
pit_test <- function(lo, hi, keep = TRUE) {
  ext  <- hi - lo
  use  <- ext < 1 - 1e-9 & keep
  pit  <- ((lo + hi) / 2 - ext / 2)[use] / (1 - ext[use])
  n_u  <- length(pit)
  pit  <- pmin(pmax(pit, runif(n_u, 0, 1e-9)), 1 - runif(n_u, 0, 1e-9))
  ks.test(pit, "punif", exact = FALSE)$p.value
}

central_mid <- function(n) pmin(pmax(rnorm(n, 0.5, opt_sd), 0), 1)

one_world <- function(truth, shape, w_mde = 1, extras = TRUE) {
  ext_true <- rbeta(n_sp, shape[1], shape[2])
  feasible <- runif(n_sp, ext_true / 2, 1 - ext_true / 2)
  mid <- switch(truth,
                mde     = feasible,
                mono    = rbeta(n_sp, 1, 3),
                central = central_mid(n_sp),
                mix     = ifelse(runif(n_sp) < w_mde, feasible, central_mid(n_sp)))
  lo  <- pmax(mid - ext_true / 2, 0)
  hi  <- pmin(mid + ext_true / 2, 1)
  obs <- band_rich(cbind(lo), cbind(hi))[, 1]
  env <- null_envelope(lo, hi)
  r2_o <- cor(obs, env$mean)^2
  in_o <- mean(obs >= env$lo & obs <= env$hi)
  # the same two scores for every null placement, against the same mean and envelope
  r2_n <- cor(env$nullr, env$mean)[, 1]^2
  in_n <- colMeans(env$nullr >= env$lo & env$nullr <= env$hi)
  core <- c(r2       = r2_o,
            inside   = in_o,
            rej      = pit_test(lo, hi) < alpha,
            rej_env  = (1 + sum(in_n <= in_o)) / (n_null + 1) < alpha,
            rej_r2   = (1 + sum(r2_n <= r2_o)) / (n_null + 1) < alpha)
  if (!extras) return(core)
  env_true <- null_envelope(0.5 - ext_true / 2, 0.5 + ext_true / 2)
  clip  <- lo <= 0 | hi >= 1
  covar <- sin(2 * pi * (runif(1, 0.5, 1.5) * band_mid + runif(1)))
  c(core,
    inside_true = mean(obs >= env_true$lo & obs <= env_true$hi),
    below       = mean(obs < env$lo),
    below_true  = mean(obs < env_true$lo),
    above       = mean(obs > env$hi),
    above_true  = mean(obs > env_true$hi),
    tot_null    = sum(env$mean) / sum(obs),
    tot_true    = sum(env_true$mean) / sum(obs),
    rej_unclip  = pit_test(lo, hi, !clip) < alpha,
    clip        = mean(clip),
    cor_smooth  = cor.test(obs, covar)$p.value < alpha,
    cor_resid   = cor.test(obs - env$mean, covar)$p.value < alpha,
    cor_white   = cor.test(obs, rnorm(n_band))$p.value < alpha)
}

## ---- arithmetic ----
occ_exact <- function(x, a, b) {
  integrate(function(r) dbeta(r, a, b) * pmin(r, x, 1 - x, 1 - r) / (1 - r),
            0, 1, rel.tol = 1e-8)$value
}
calib_sets <- list("Beta(1, 1)" = c(1, 1), "Beta(1, 2)" = c(1, 2),
                   "Beta(1, 3)" = c(1, 3), "Beta(2, 2)" = c(2, 2))
n_calib <- 20000
set.seed(7301)
calib <- do.call(rbind, lapply(names(calib_sets), function(nm) {
  ab  <- calib_sets[[nm]]
  ext <- rbeta(n_calib, ab[1], ab[2])
  mid <- runif(n_calib, ext / 2, 1 - ext / 2)
  data.frame(extents = nm, x = band_mid,
             exact = vapply(band_mid, occ_exact, 0, a = ab[1], b = ab[2]),
             sim = band_rich(cbind(mid - ext / 2), cbind(mid + ext / 2))[, 1] / n_calib)
}))
entropy <- function(x) -x * log(x) - (1 - x) * log(1 - x)
cpick <- function(nm, band) calib$exact[calib$extents == nm][band]
gap_entropy  <- max(abs(calib$exact[calib$extents == "Beta(1, 1)"] - entropy(band_mid)))
gap_parabola <- max(abs(calib$exact[calib$extents == "Beta(1, 2)"] - 2 * band_mid * (1 - band_mid)))
gap_sim  <- max(abs(calib$sim - calib$exact))
se_worst <- sqrt(0.25 / n_calib)
ratio_dev <- max(abs(calib$exact[calib$extents == "Beta(2, 2)"] /
                     calib$exact[calib$extents == "Beta(1, 3)"] - 2))

## ---- fig-calibration ----
ggplot(calib, aes(x, exact, colour = extents)) +
  geom_line(aes(linetype = extents), linewidth = 0.9) +
  geom_point(aes(y = sim), size = 1.4, alpha = 0.8) +
  scale_linetype_manual(values = c("Beta(1, 1)" = "22", "Beta(1, 2)" = "solid",
                                   "Beta(1, 3)" = "solid", "Beta(2, 2)" = "solid"),
                        name = "range extents") +
  scale_colour_manual(values = c("Beta(1, 1)" = te_ink, "Beta(1, 2)" = te_gold,
                                 "Beta(1, 3)" = te_rust, "Beta(2, 2)" = te_forest),
                      name = "range extents") +
  labs(x = "position in the domain", y = "share of species covering the band",
       title = "The mid-domain hump before any biology",
       subtitle = "lines: exact integral; points: 20000 simulated species") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- example-worlds ----
set.seed(4417)
truth_lab <- c(mde = "geometry only", mono = "monotone gradient", central = "central optimum")
ex <- do.call(rbind, lapply(names(truth_lab), function(tr) {
  ext_true <- rbeta(n_sp, 1, 3)
  mid <- switch(tr, mde = runif(n_sp, ext_true / 2, 1 - ext_true / 2),
                mono = rbeta(n_sp, 1, 3), central = central_mid(n_sp))
  lo  <- pmax(mid - ext_true / 2, 0)
  hi  <- pmin(mid + ext_true / 2, 1)
  obs <- band_rich(cbind(lo), cbind(hi))[, 1]
  env <- null_envelope(lo, hi)
  data.frame(truth = tr, x = band_mid, obs = obs, lo = env$lo, hi = env$hi, nm = env$mean,
             r2 = cor(obs, env$mean)^2, inside = mean(obs >= env$lo & obs <= env$hi),
             p_sp = pit_test(lo, hi))
}))
ex_stat <- unique(ex[, c("truth", "r2", "inside", "p_sp")])
epick <- function(tr, col) ex_stat[ex_stat$truth == tr, col]

## ---- fig-worlds ----
ex$panel <- factor(sprintf("%s\nr2 %.2f, %d of %d bands inside", truth_lab[ex$truth],
                           ex$r2, round(ex$inside * n_band), n_band),
                   levels = unique(sprintf("%s\nr2 %.2f, %d of %d bands inside",
                                           truth_lab[ex$truth], ex$r2,
                                           round(ex$inside * n_band), n_band)))
ex$out <- ex$obs < ex$lo | ex$obs > ex$hi
ggplot(ex, aes(x)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = te_line) +
  geom_line(aes(y = nm), colour = te_forest, linewidth = 0.8) +
  geom_point(aes(y = obs, colour = out), size = 1.6) +
  scale_colour_manual(values = c("FALSE" = te_ink, "TRUE" = te_rust),
                      labels = c("inside the envelope", "outside"), name = NULL) +
  facet_wrap(~panel) +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  labs(x = "position in the domain", y = "species per band",
       title = "Same null, three truths",
       subtitle = "250 species, Beta(1, 3) extents; grey: 95 per cent envelope of 199 null placements") +
  theme_datasheet() +
  theme(legend.position = "bottom", panel.spacing = unit(1.4, "lines"))

## ---- simulate ----
set.seed(2003)
cells <- expand.grid(truth = c("mde", "mono", "central"), extents = names(ext_sets),
                     stringsAsFactors = FALSE)
sim_raw <- do.call(rbind, lapply(seq_len(nrow(cells)), function(i) {
  runs <- t(replicate(n_world, one_world(cells$truth[i], ext_sets[[cells$extents[i]]])))
  data.frame(truth = cells$truth[i], extents = cells$extents[i], runs)
}))
spick <- function(tr, ex_nm, col, f = mean) f(sim_raw[sim_raw$truth == tr & sim_raw$extents == ex_nm, col])
mc_se <- function(p) sqrt(p * (1 - p) / n_world)
shift <- function(tr, ex_nm) spick(tr, ex_nm, "inside") - spick(tr, ex_nm, "inside_true")
shift_se <- function(tr, ex_nm) {
  k <- sim_raw$truth == tr & sim_raw$extents == ex_nm
  sd(sim_raw$inside[k] - sim_raw$inside_true[k]) / sqrt(n_world)
}

## ---- fig-rates ----
sim_raw$truth_lab <- factor(truth_lab[sim_raw$truth], levels = truth_lab)
p_r2 <- ggplot(sim_raw, aes(r2, truth_lab)) +
  geom_boxplot(fill = te_line, colour = te_body, outlier.size = 0.6, width = 0.6) +
  facet_wrap(~extents, ncol = 1) +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  labs(x = "r-squared against null mean", y = NULL, title = "Fit to the null") +
  theme_datasheet()
p_in <- ggplot(sim_raw, aes(inside, truth_lab)) +
  geom_boxplot(fill = te_line, colour = te_body, outlier.size = 0.6, width = 0.6) +
  facet_wrap(~extents, ncol = 1) +
  scale_x_continuous(breaks = c(0, 0.5, 1)) +
  labs(x = "share of bands inside", y = NULL, title = "Envelope") +
  theme_datasheet() +
  theme(axis.text.y = element_blank())
p_r2 + p_in + plot_annotation(theme = theme_datasheet())

## ---- mixture ----
set.seed(2005)
w_grid <- c(0.25, 0.5, 0.75, 0.9)
mix_raw <- do.call(rbind, lapply(w_grid, function(w) {
  runs <- t(replicate(n_world, one_world("mix", ext_sets[["Beta(1, 3)"]], w, extras = FALSE)))
  data.frame(w_mde = w, runs)
}))
ends <- rbind(data.frame(w_mde = 0, sim_raw[sim_raw$truth == "central" & sim_raw$extents == "Beta(1, 3)", colnames(mix_raw)[-1]]),
              data.frame(w_mde = 1, sim_raw[sim_raw$truth == "mde" & sim_raw$extents == "Beta(1, 3)", colnames(mix_raw)[-1]]))
mix_all <- rbind(mix_raw, ends)
mix_s <- data.frame(w_mde = sort(unique(mix_all$w_mde)))
mix_s$rej    <- tapply(mix_all$rej, mix_all$w_mde, mean)
mix_s$env    <- tapply(mix_all$rej_env, mix_all$w_mde, mean)
mix_s$r2cut  <- tapply(mix_all$rej_r2, mix_all$w_mde, mean)
# paired difference between the envelope rank test and the species test
mix_d <- function(w) {
  d <- mix_all$rej_env[mix_all$w_mde == w] - mix_all$rej[mix_all$w_mde == w]
  c(diff = mean(d), se = sd(d) / sqrt(length(d)))
}
mix_s$r2med  <- tapply(mix_all$r2, mix_all$w_mde, median)
mpick <- function(w, col) mix_s[mix_s$w_mde == w, col]

## ---- fig-mixture ----
mix_long <- rbind(data.frame(w_mde = mix_s$w_mde, rate = mix_s$rej, rule = "species midpoint test"),
                  data.frame(w_mde = mix_s$w_mde, rate = mix_s$env, rule = "envelope share, rank test"),
                  data.frame(w_mde = mix_s$w_mde, rate = mix_s$r2cut, rule = "r-squared, rank test"))
mix_long$se <- sqrt(mix_long$rate * (1 - mix_long$rate) / n_world)
ggplot(mix_long, aes(w_mde, rate, colour = rule)) +
  geom_hline(yintercept = alpha, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 0.9) +
  geom_errorbar(aes(ymin = rate - 2 * se, ymax = rate + 2 * se), width = 0.02) +
  geom_point(size = 2) +
  scale_colour_manual(values = c("species midpoint test" = te_forest,
                                 "envelope share, rank test" = te_gold,
                                 "r-squared, rank test" = te_rust), name = NULL) +
  labs(x = "share of species placed by geometry alone", y = "rejection rate of the null",
       title = "How much environment the tests can see",
       subtitle = "Beta(1, 3) extents, 300 worlds per point, bars two Monte Carlo standard errors") +
  theme_datasheet() +
  theme(legend.position = "bottom")
