# Null models for interaction networks
# https://tidyecology.com/posts/null-models-for-interaction-networks/
#
# 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-11-13

## ---- setup ----
library(ggplot2)
library(grid)
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"; te_label <- "#46604a"
te_sage <- "#93a87f"; te_paper <- "#f5f4ee"; te_line <- "#dad9ca"; te_gold <- "#c9b458"
te_rust <- "#b5534e"
theme_te <- function(base = 12) theme_minimal(base_size = base) +
  theme(plot.background = element_rect(fill = te_paper, colour = NA),
        panel.background = element_rect(fill = te_paper, colour = NA),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
        axis.text = element_text(colour = te_body), axis.title = element_text(colour = te_label),
        plot.title = element_text(colour = te_ink, face = "bold", size = rel(1.02)),
        plot.subtitle = element_text(colour = te_label, size = rel(0.9)),
        legend.text = element_text(colour = te_body), legend.title = element_text(colour = te_label))
# NODF (Almeida-Neto et al 2008); the full treatment is in the nestedness post
nodf <- function(M) {
  paircontrib <- function(deg, mat, margin) {
    idx <- order(deg, decreasing = TRUE); s <- 0; np <- 0
    for (a in seq_along(idx)) for (b in seq_along(idx)) if (a < b) {
      i <- idx[a]; j <- idx[b]; di <- deg[i]; dj <- deg[j]
      if (di > dj && dj > 0) {
        ov <- if (margin == "row") sum(mat[i, ] & mat[j, ]) / dj else sum(mat[, i] & mat[, j]) / dj
        s <- s + ov * 100
      }
      np <- np + 1
    }
    c(s = s, np = np)
  }
  r <- paircontrib(rowSums(M), M, "row"); cc <- paircontrib(colSums(M), M, "col")
  as.numeric((r["s"] + cc["s"]) / (r["np"] + cc["np"]))
}

## ---- build-web ----
set.seed(4262)
A0 <- 16L; P0 <- 14L
a_row <- exp(rnorm(A0, 0, 0.9)); b_col <- exp(rnorm(P0, 0, 0.8))
Pr <- outer(a_row, b_col); Pr <- Pr / max(Pr)
B <- matrix(rbinom(A0 * P0, 1, 0.85 * Pr), A0, P0)
B[cbind(seq_len(A0), max.col(Pr))] <- 1
B[cbind(max.col(t(Pr)), seq_len(P0))] <- 1
B <- B[rowSums(B) > 0, colSums(B) > 0, drop = FALSE]
A <- nrow(B); P <- ncol(B); L <- sum(B)
NODF_obs <- nodf(B)
c(pollinators = A, plants = P, links = L, connectance = round(L / (A * P), 3), NODF = round(NODF_obs, 2))

## ---- nulls ----
null_equi <- function() { z <- numeric(A * P); z[sample(A * P, L)] <- 1; matrix(z, A, P) }
rd0 <- rowSums(B); cd0 <- colSums(B)
Pp <- outer(rd0, cd0); Pp <- pmin(Pp / sum(Pp) * L, 1)
null_prop <- function() matrix(rbinom(A * P, 1, Pp), A, P)
null_swap <- function(M, nsw = 3000) {
  for (s in seq_len(nsw)) {
    ii <- sample(nrow(M), 2); jj <- sample(ncol(M), 2); sub <- M[ii, jj]
    if (all(sub == matrix(c(1, 0, 0, 1), 2)))      M[ii, jj] <- matrix(c(0, 1, 1, 0), 2)
    else if (all(sub == matrix(c(0, 1, 1, 0), 2))) M[ii, jj] <- matrix(c(1, 0, 0, 1), 2)
  }
  M
}
nrep <- 299L
set.seed(11); N_equi <- replicate(nrep, nodf(null_equi()))
set.seed(12); N_prop <- replicate(nrep, nodf(null_prop()))
set.seed(13); N_swap <- replicate(nrep, nodf(null_swap(B)))
zscore <- function(obs, nd) (obs - mean(nd)) / sd(nd)
pval   <- function(obs, nd) (1 + sum(nd >= obs)) / (length(nd) + 1)

## ---- verdict ----
verdict <- data.frame(
  null = c("equiprobable", "proportional", "fixed-fixed"),
  null_mean = c(mean(N_equi), mean(N_prop), mean(N_swap)),
  z = c(zscore(NODF_obs, N_equi), zscore(NODF_obs, N_prop), zscore(NODF_obs, N_swap)),
  p = c(pval(NODF_obs, N_equi), pval(NODF_obs, N_prop), pval(NODF_obs, N_swap)))
z_equi <- verdict$z[1]; z_prop <- verdict$z[2]; z_swap <- verdict$z[3]
p_swap <- verdict$p[3]
round(verdict[, -1], 3)

## ---- fig-nulls ----
dfn <- rbind(data.frame(NODF = N_equi, null = "equiprobable"),
             data.frame(NODF = N_prop, null = "proportional"),
             data.frame(NODF = N_swap, null = "fixed-fixed"))
dfn$null <- factor(dfn$null, levels = c("equiprobable", "proportional", "fixed-fixed"))
pa <- ggplot(dfn, aes(NODF, fill = null)) +
  geom_histogram(bins = 30, colour = te_paper, linewidth = 0.15, alpha = 0.85, position = "identity") +
  geom_vline(xintercept = NODF_obs, colour = te_ink, linewidth = 1) +
  annotate("text", x = NODF_obs, y = Inf, label = sprintf("observed = %.0f", NODF_obs),
           hjust = 1.05, vjust = 1.6, colour = te_ink, size = 3.3) +
  scale_fill_manual(values = c(equiprobable = te_gold, proportional = te_sage, `fixed-fixed` = te_forest), name = "null model") +
  labs(title = "Nestedness against three nulls", x = "NODF of randomised webs", y = "count",
       subtitle = "far right of two nulls, inside the third") +
  theme_te()
pb <- ggplot(verdict, aes(factor(null, levels = null), z, fill = null)) +
  geom_col(width = 0.62) +
  geom_hline(yintercept = 1.96, linetype = "dashed", colour = te_rust, linewidth = 0.5) +
  geom_text(aes(label = sprintf("p = %.3f", p)), vjust = -0.5, colour = te_body, size = 3.2) +
  scale_fill_manual(values = c(equiprobable = te_gold, proportional = te_sage, `fixed-fixed` = te_forest), guide = "none") +
  labs(title = "Significance depends on the null", x = NULL, y = "z-score of observed NODF",
       subtitle = "dashed line: z = 1.96") +
  theme_te() + theme(axis.text.x = element_text(size = rel(0.92)))
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pa, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pb, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- robustness ----
survival_curve <- function(M, order_cols) {
  removed <- logical(ncol(M)); surv <- numeric(ncol(M) + 1); surv[1] <- 1
  for (k in seq_along(order_cols)) {
    removed[order_cols[k]] <- TRUE
    surv[k + 1] <- mean(rowSums(M[, !removed, drop = FALSE]) > 0)
  }
  surv
}
robustness_R <- function(surv) { x <- seq(0, 1, length.out = length(surv)); sum((surv[-1] + surv[-length(surv)]) / 2 * diff(x)) }
deg_c <- colSums(B)
surv_most  <- survival_curve(B, order(deg_c, decreasing = TRUE))
surv_least <- survival_curve(B, order(deg_c, decreasing = FALSE))
set.seed(1); surv_rand <- survival_curve(B, sample(P))
R_most <- robustness_R(surv_most); R_least <- robustness_R(surv_least)
set.seed(7); R_rand <- mean(replicate(200, robustness_R(survival_curve(B, sample(P)))))
c(most_connected = round(R_most, 3), random = round(R_rand, 3), least_connected = round(R_least, 3))

## ---- robustness-null ----
set.seed(21)
R_null <- replicate(199, {
  M <- null_swap(B)
  mean(replicate(30, robustness_R(survival_curve(M, sample(ncol(M))))))
})
z_R <- zscore(R_rand, R_null)
c(null_mean = round(mean(R_null), 3), null_sd = round(sd(R_null), 3),
  observed = round(R_rand, 3), z = round(z_R, 2))

## ---- fig-robustness ----
mkcurve <- function(surv, lab) data.frame(frac_removed = seq(0, 1, length.out = length(surv)), surv = surv, order = lab)
dfc <- rbind(mkcurve(surv_most, "most-connected first"), mkcurve(surv_rand, "random"),
             mkcurve(surv_least, "least-connected first"))
dfc$order <- factor(dfc$order, levels = c("most-connected first", "random", "least-connected first"))
pc <- ggplot(dfc, aes(frac_removed, surv, colour = order)) +
  geom_line(linewidth = 1) + geom_point(size = 1.3) +
  scale_colour_manual(values = c(`most-connected first` = te_rust, random = te_gold, `least-connected first` = te_forest), name = "removal order") +
  labs(title = "Secondary extinctions", x = "fraction of plants removed", y = "fraction of pollinators surviving",
       subtitle = sprintf("R: most %.2f, random %.2f, least %.2f", R_most, R_rand, R_least)) +
  theme_te()
dr <- data.frame(R = R_null)
pd <- ggplot(dr, aes(R)) +
  geom_histogram(bins = 22, fill = te_sage, colour = te_paper, linewidth = 0.2) +
  geom_vline(xintercept = R_rand, colour = te_rust, linewidth = 1) +
  annotate("text", x = R_rand, y = Inf, label = sprintf("observed = %.2f", R_rand), hjust = 1.05, vjust = 1.6, colour = te_rust, size = 3.3) +
  labs(title = "Robustness vs fixed-degree null", x = "robustness R of randomised webs", y = "count",
       subtitle = sprintf("null mean %.2f, z = %.2f", mean(R_null), z_R)) +
  theme_te()
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pc, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pd, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
