# Network robustness and secondary extinctions
# https://tidyecology.com/posts/network-robustness-secondary-extinctions/
#
# 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)

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))
}

## ---- build-web ----
make_web <- function(n_poll, n_plant, alpha, theta, seed, total = 1200) {
  set.seed(seed)
  gener <- runif(n_poll)
  attra <- runif(n_plant)
  ab_p  <- exp(rnorm(n_poll, 0, 0.8))
  ab_l  <- exp(rnorm(n_plant, 0, 0.6))
  pr    <- plogis(alpha * (outer(gener, attra, "+") - theta))
  lam   <- outer(ab_p, ab_l) * pr
  lam   <- lam / sum(lam) * total
  wm    <- matrix(rpois(n_poll * n_plant, lam), n_poll, n_plant)
  wm    <- wm[rowSums(wm) > 0, , drop = FALSE]
  wm    <- wm[, colSums(wm) > 0, drop = FALSE]
  dimnames(wm) <- list(paste0("poll", seq_len(nrow(wm))),
                       paste0("plant", seq_len(ncol(wm))))
  wm
}

web_a <- make_web(45, 28, alpha = 10, theta = 1.5, seed = 20260813)
n_a <- nrow(web_a); p_a <- ncol(web_a)
deg_plant <- colSums(web_a > 0)
round(c(pollinators = n_a, plants = p_a,
        connectance = sum(web_a > 0) / (n_a * p_a),
        plant_degree_min = min(deg_plant), plant_degree_max = max(deg_plant)), 3)

## ---- cascade ----
survivors <- function(wm, ord, b = Inf, u = NULL) {
  stopifnot(all(rowSums(wm) > 0))
  strength <- rowSums(wm)
  keep  <- rep(TRUE, ncol(wm))
  alive <- rep(TRUE, nrow(wm))
  out   <- numeric(length(ord) + 1)
  out[1] <- 1
  for (k in seq_along(ord)) {
    keep[ord[k]] <- FALSE
    remain <- rowSums(wm[, keep, drop = FALSE])
    lost   <- 1 - remain / strength
    alive  <- alive & (if (is.infinite(b)) remain > 0 else lost^b <= u)
    out[k + 1] <- mean(alive)
  }
  out
}

# R (Burgos et al 2007) is the area under the curve;
# R50 the removed fraction at half survival
r_index <- function(y) {
  x <- seq(0, 1, length.out = length(y))
  sum(diff(x) * (head(y, -1) + tail(y, -1)) / 2)
}
r50 <- function(y) {
  x <- seq(0, 1, length.out = length(y))
  i <- which(y <= 0.5)[1]
  if (i == 1) return(0)
  x[i - 1] + (y[i - 1] - 0.5) / (y[i - 1] - y[i]) * (x[i] - x[i - 1])
}

curve_most  <- survivors(web_a, order(deg_plant, decreasing = TRUE))
curve_least <- survivors(web_a, order(deg_plant))
round(c(R_most_connected_first = r_index(curve_most),
        R50_most_connected_first = r50(curve_most)), 3)

## ---- orders ----
set.seed(505)
n_rep    <- 2000
ord_mat  <- replicate(n_rep, sample(p_a))
rand_curves <- sapply(seq_len(n_rep), function(i) survivors(web_a, ord_mat[, i]))
rand_r50 <- apply(rand_curves, 2, r50)
xs <- seq(0, 1, length.out = p_a + 1)

order_tab <- data.frame(
  order = c("most connected first", "random (mean)", "least connected first"),
  R     = c(r_index(curve_most), mean(apply(rand_curves, 2, r_index)),
            r_index(curve_least)),
  R50   = c(r50(curve_most), mean(rand_r50), r50(curve_least)))
order_span <- mean(rand_r50) - r50(curve_most)
round(order_tab[, -1], 3)
round(c(most_to_random_span = order_span,
        mc_standard_error = sd(rand_r50) / sqrt(n_rep),
        random_q10 = quantile(rand_r50, 0.1),
        random_q90 = quantile(rand_r50, 0.9),
        ceiling = (p_a - 0.5) / p_a), 3)

## ---- fig-curves ----
band <- data.frame(x = xs,
                   lo = apply(rand_curves, 1, quantile, 0.1),
                   hi = apply(rand_curves, 1, quantile, 0.9),
                   mid = rowMeans(rand_curves))
lines_df <- data.frame(
  x = rep(xs, 3), y = c(curve_most, band$mid, curve_least),
  order = factor(rep(c("most connected first", "random (mean)",
                       "least connected first"), each = p_a + 1),
                 levels = c("most connected first", "random (mean)",
                            "least connected first")))

ggplot(lines_df, aes(x, y)) +
  geom_ribbon(data = band, aes(x = x, ymin = lo, ymax = hi),
              inherit.aes = FALSE, fill = te_gold, alpha = 0.3) +
  geom_hline(yintercept = 0.5, linetype = "dashed", colour = te_body) +
  geom_line(aes(colour = order), linewidth = 1) +
  scale_colour_manual(values = c(te_rust, te_ink, te_forest)) +
  labs(x = "fraction of plants removed", y = "fraction of pollinators surviving",
       colour = NULL, title = "One web, three answers") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- bank ----
trim <- function(wm) {
  wm <- wm[rowSums(wm) > 0, , drop = FALSE]
  wm[, colSums(wm) > 0, drop = FALSE]
}
web_er <- function(n_poll, n_plant, fill, seed) {
  set.seed(seed)
  wm <- matrix(0, n_poll, n_plant)
  cells <- sample(n_poll * n_plant, round(fill * n_poll * n_plant))
  wm[cells] <- 1 + rpois(length(cells), 4)
  trim(wm)
}
web_nested <- function(n_poll, n_plant, seed) {
  set.seed(seed)
  k <- 1 + round((n_plant - 1) * sort(rbeta(n_poll, 0.7, 1.3)))
  trim(t(sapply(k, function(d) c(1 + rpois(d, 5), rep(0, n_plant - d)))))
}
web_modular <- function(n_poll, n_plant, n_mod, seed) {
  set.seed(seed)
  gp  <- sample(rep(seq_len(n_mod), length.out = n_poll))
  gl  <- sample(rep(seq_len(n_mod), length.out = n_plant))
  lam <- outer(gp, gl, function(a, b) ifelse(a == b, 3.2, 0.12))
  trim(matrix(rpois(n_poll * n_plant, lam), n_poll, n_plant))
}

bank <- list("generator A" = web_a,
             "generator B" = make_web(45, 28, alpha = 4,  theta = 1.0, seed = 4114),
             "generator C" = make_web(40, 24, alpha = 14, theta = 1.7, seed = 911))
for (s in 1:3) {
  bank[[paste("generator", s)]]   <- make_web(45, 28, alpha = 6 + 3 * s,
                                              theta = 1.1 + 0.2 * s, seed = 700 + s)
  bank[[paste("Erdos-Renyi", s)]] <- web_er(40, 26, fill = 0.14 + 0.06 * s, seed = 300 + s)
  bank[[paste("nested", s)]]      <- web_nested(40, 26, seed = 500 + s)
  bank[[paste("modular", s)]]     <- web_modular(40, 26, n_mod = 1 + s, seed = 900 + s)
}

bank_tab <- do.call(rbind, lapply(names(bank), function(nm) {
  wm <- bank[[nm]]
  dg <- colSums(wm > 0)
  set.seed(505)
  rc <- replicate(200, survivors(wm, sample(ncol(wm))))
  data.frame(web = nm, family = sub(" .*$", "", nm), plants = ncol(wm),
             connectance = sum(wm > 0) / (nrow(wm) * ncol(wm)),
             degree_cv = sd(dg) / mean(dg),
             R50_most = r50(survivors(wm, order(dg, decreasing = TRUE))),
             R50_random = mean(apply(rc, 2, r50)))
}))
bank_tab$order_span <- bank_tab$R50_random - bank_tab$R50_most

fam_tab <- do.call(rbind, lapply(split(bank_tab, bank_tab$family), function(d)
  data.frame(webs = nrow(d), connectance = mean(d$connectance),
             degree_cv = mean(d$degree_cv), R50_most = mean(d$R50_most),
             order_span = mean(d$order_span))))
web_span_most   <- diff(range(bank_tab$R50_most))
web_span_random <- diff(range(bank_tab$R50_random))
print(round(fam_tab, 3))
round(c(between_web_span_most = web_span_most,
        between_web_span_random = web_span_random,
        median_order_span = median(bank_tab$order_span),
        webs_where_order_span_is_larger = sum(bank_tab$order_span > web_span_most)), 3)

## ---- fig-span ----
span_df <- bank_tab
span_df$web <- factor(span_df$web, levels = span_df$web[order(span_df$R50_most)])
pt_df <- data.frame(
  web   = rep(span_df$web, 2),
  value = c(span_df$R50_most, span_df$R50_random),
  ord   = factor(rep(c("most connected first", "random (mean)"),
                     each = nrow(span_df)),
                 levels = c("most connected first", "random (mean)")))

p_span <- ggplot(span_df) +
  geom_segment(aes(x = R50_most, xend = R50_random, y = web, yend = web),
               colour = te_gold, linewidth = 2.2) +
  geom_point(data = pt_df, aes(value, web, colour = ord), size = 2.6) +
  scale_colour_manual(values = c(te_rust, te_ink)) +
  labs(x = "R50", y = NULL, colour = NULL,
       title = "The web moves it further than the order does") +
  theme_datasheet() +
  theme(legend.position = "bottom")
p_span

## ---- thumb ----
ggsave("thumbnail.png",
       p_span + labs(title = NULL) +
         theme(plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = te_paper)

## ---- rule ----
set.seed(77)
u_mat <- replicate(n_rep, runif(n_a))
rule_r50 <- sapply(c(Inf, 3, 1), function(b)
  apply(sapply(seq_len(n_rep), function(i)
    survivors(web_a, ord_mat[, i], b = b, u = u_mat[, i])), 2, r50))
rule_lab <- c("all or nothing", "b = 3", "b = 1")
colnames(rule_r50) <- rule_lab
paired_drop <- rule_r50[, 1] - rule_r50[, 3]
round(colMeans(rule_r50), 3)
round(c(paired_drop = mean(paired_drop),
        mc_standard_error = sd(paired_drop) / sqrt(n_rep),
        share_of_order_span = mean(paired_drop) / order_span), 3)

## ---- fig-rule ----
mean_curves <- sapply(c(Inf, 3, 1), function(b)
  rowMeans(sapply(seq_len(n_rep), function(i)
    survivors(web_a, ord_mat[, i], b = b, u = u_mat[, i]))))
rule_df <- data.frame(x = rep(xs, 3), y = as.vector(mean_curves),
                      rule = factor(rep(rule_lab, each = p_a + 1),
                                    levels = rule_lab))

ggplot(rule_df, aes(x, y, colour = rule)) +
  geom_hline(yintercept = 0.5, linetype = "dashed", colour = te_body) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust)) +
  labs(x = "fraction of plants removed", y = "fraction of pollinators surviving",
       colour = NULL, title = "The same web under three dependence rules") +
  theme_datasheet() +
  theme(legend.position = "bottom")
