# Checking a network analysis
# https://tidyecology.com/posts/checking-a-network-analysis/
#
# 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-15

## ---- 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))
# H2' and NODF as coded in the earlier posts of this series
H2prime <- function(W) {
  m <- sum(W); if (m == 0) return(NA_real_)
  pm <- W[W > 0] / m; H2 <- -sum(pm * log(pm))
  r <- rowSums(W) / m; cc <- colSums(W) / m
  H2max <- -sum(r[r > 0] * log(r[r > 0])) - sum(cc[cc > 0] * log(cc[cc > 0]))
  rr <- rowSums(W); ccx <- colSums(W); ent <- 0
  repeat {
    if (sum(rr) <= 0) break
    best <- -1; bi <- bj <- NA
    for (i in which(rr > 0)) for (j in which(ccx > 0)) { v <- min(rr[i], ccx[j]); if (v > best) { best <- v; bi <- i; bj <- j } }
    p <- best / m; ent <- ent - p * log(p); rr[bi] <- rr[bi] - best; ccx[bj] <- ccx[bj] - best
  }
  if (H2max <= ent) return(0)
  (H2max - H2) / (H2max - ent)
}
nodf <- function(M) {
  pc <- function(deg, mat, mar) {
    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 (mar == "r") 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 <- pc(rowSums(M), M, "r"); cc <- pc(colSums(M), M, "c")
  as.numeric((r["s"] + cc["s"]) / (r["np"] + cc["np"]))
}
null_swap <- function(M, nsw = 2000) {
  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
}

## ---- true-web ----
set.seed(4263)
A <- 20L; P <- 16L
a_row <- exp(rnorm(A, 0, 0.8)); b_col <- exp(rnorm(P, 0, 0.7))
mu <- runif(A); pos <- seq(0.05, 0.95, length.out = P); niche_w <- 0.22
Ptrue <- outer(a_row, b_col) * exp(-(outer(mu, pos, "-")^2) / (2 * niche_w^2))
Ptrue <- Ptrue / sum(Ptrue)
p_min <- 1e-6
n_possible <- sum(Ptrue > p_min)
c(cells = A * P, ecologically_possible = n_possible)

## ---- accumulation ----
set.seed(6)
grid_n <- c(seq(20, 400, 20), seq(500, 3000, 250))
pool <- sample(A * P, max(grid_n), replace = TRUE, prob = as.vector(Ptrue))
accum <- vapply(grid_n, function(k) length(unique(pool[seq_len(k)])), numeric(1))
acc_df <- data.frame(sampled = grid_n, unique_links = accum)
acc_end <- accum[length(accum)]
c(links_found_at_3000 = acc_end, links_that_exist = n_possible,
  fraction = round(acc_end / n_possible, 2))

## ---- effort-drift ----
samp_metrics <- function(n) {
  W <- matrix(rmultinom(1, n, as.vector(Ptrue)), A, P)
  Wt <- W[rowSums(W) > 0, colSums(W) > 0, drop = FALSE]
  c(effort = n, connectance = sum(W > 0) / (A * P),
    H2prime = H2prime(Wt), NODF = nodf((Wt > 0) * 1))
}
set.seed(5)
efforts <- c(50, 100, 200, 400, 800, 1600, 3200)
drift <- as.data.frame(t(vapply(efforts, samp_metrics, numeric(4))))
conn_lo <- drift$connectance[1]; conn_hi <- drift$connectance[nrow(drift)]
h2_lo <- drift$H2prime[1]; h2_hi <- drift$H2prime[nrow(drift)]
nodf_lo <- drift$NODF[1]; nodf_hi <- drift$NODF[nrow(drift)]
round(drift, 3)

## ---- fig-effort ----
pa <- ggplot(acc_df, aes(sampled, unique_links)) +
  geom_hline(yintercept = n_possible, linetype = "dashed", colour = te_rust, linewidth = 0.5) +
  annotate("text", x = 0, y = n_possible, label = "links that exist", hjust = -0.05, vjust = -0.6,
           colour = te_rust, size = 3.2) +
  geom_line(colour = te_forest, linewidth = 0.9) + geom_point(colour = te_forest, size = 1.4) +
  labs(title = "Interaction accumulation", x = "interactions recorded", y = "distinct links found",
       subtitle = sprintf("%.0f%% of existing links found at 3000 interactions", 100 * acc_end / n_possible)) +
  theme_te()
dl <- rbind(data.frame(effort = drift$effort, value = drift$connectance, metric = "connectance"),
            data.frame(effort = drift$effort, value = drift$H2prime,     metric = "H2' (specialisation)"),
            data.frame(effort = drift$effort, value = drift$NODF / 100,  metric = "NODF / 100"))
pb <- ggplot(dl, aes(effort, value, colour = metric)) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.9) +
  scale_x_log10() +
  scale_colour_manual(values = c(connectance = te_forest, `H2' (specialisation)` = te_rust,
                                 `NODF / 100` = te_gold), name = NULL) +
  labs(title = "Metrics against sampling effort", x = "interactions recorded (log scale)",
       y = "metric value (NODF rescaled to 0-1)",
       subtitle = "same true web throughout") +
  theme_te() + theme(legend.position = "inside", legend.position.inside = c(0.72, 0.35),
                     legend.background = element_rect(fill = te_paper, colour = NA))
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))

## ---- size-dependence ----
gen_web <- function(S, eff_per_sp = 32) {
  a <- exp(rnorm(S, 0, 0.7)); b <- exp(rnorm(S, 0, 0.6))
  mu_s <- runif(S); pos_s <- seq(0.05, 0.95, length.out = S)
  Pt <- outer(a, b) * exp(-(outer(mu_s, pos_s, "-")^2) / (2 * 0.22^2)); Pt <- Pt / sum(Pt)
  W <- matrix(rmultinom(1, eff_per_sp * S, as.vector(Pt)), S, S)
  W[rowSums(W) > 0, colSums(W) > 0, drop = FALSE]
}
set.seed(77)
sizes <- c(6, 9, 12, 15, 18, 21, 24)
size_res <- as.data.frame(t(vapply(sizes, function(S) {
  reps <- replicate(8, { W <- gen_web(S); c(conn = sum(W > 0) / (nrow(W) * ncol(W)), nd = nodf((W > 0) * 1)) })
  c(size = S, connectance = mean(reps["conn", ]), NODF = mean(reps["nd", ]))
}, numeric(3))))
size_conn_lo <- size_res$connectance[nrow(size_res)]; size_conn_hi <- size_res$connectance[1]
round(size_res, 3)

## ---- null-rescue ----
set.seed(41)
zt <- as.data.frame(t(vapply(c(100, 200, 400, 800, 1600, 3200), function(n) {
  W <- matrix(rmultinom(1, n, as.vector(Ptrue)), A, P)
  B <- (W > 0) * 1; B <- B[rowSums(B) > 0, colSums(B) > 0, drop = FALSE]
  obs <- nodf(B); nd <- replicate(99, nodf(null_swap(B)))
  c(effort = n, raw_NODF = obs, z = (obs - mean(nd)) / sd(nd))
}, numeric(3))))
z_raw_lo <- zt$raw_NODF[1]; z_raw_hi <- zt$raw_NODF[nrow(zt)]
z_range <- range(zt$z)
round(zt, 2)

## ---- fig-rescue ----
pc <- ggplot(size_res, aes(size, connectance)) +
  geom_line(colour = te_forest, linewidth = 0.9) + geom_point(colour = te_forest, size = 2.2) +
  labs(title = "Connectance falls with network size", x = "species per side", y = "connectance",
       subtitle = "identical ecology and per-species effort") +
  theme_te()
zl <- rbind(data.frame(effort = zt$effort, value = zt$raw_NODF / 100, what = "raw NODF / 100"),
            data.frame(effort = zt$effort, value = zt$z, what = "z vs fixed-degree null"))
pd <- ggplot(zl, aes(effort, value, colour = what)) +
  geom_hline(yintercept = 0, colour = te_line, linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_x_log10() +
  scale_colour_manual(values = c(`raw NODF / 100` = te_gold, `z vs fixed-degree null` = te_forest), name = NULL) +
  labs(title = "Raw nestedness against its null z-score", x = "interactions recorded (log scale)",
       y = "index value (NODF/100 or z)",
       subtitle = "raw index drifts, z-score does not track it") +
  theme_te() + theme(legend.position = "bottom",
                     legend.background = element_rect(fill = te_paper, colour = NA))
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))

## ---- forbidden-vs-missing ----
set.seed(42)
W_obs <- matrix(rmultinom(1, 600, as.vector(Ptrue)), A, P)
zero_cells <- which(W_obs == 0)
thr <- p_min   # the same cutoff that defined the links that exist
n_forbidden <- sum(Ptrue[zero_cells] < thr)
n_missing   <- sum(Ptrue[zero_cells] >= thr)
exp_visits  <- 600 * Ptrue[zero_cells][Ptrue[zero_cells] >= thr]
c(zeros = length(zero_cells), forbidden = n_forbidden, missing = n_missing,
  pct_missing = round(100 * n_missing / length(zero_cells)),
  median_expected_visits = round(median(exp_visits), 2))
