# Metapopulation capacity
# https://tidyecology.com/posts/metapopulation-capacity/
#
# 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

## ---- landscape ----
set.seed(2024)
K <- 6; per <- 26
centres <- cbind(runif(K, 3, 25), runif(K, 3, 25))
clus <- do.call(rbind, lapply(1:K, function(k)
  cbind(rnorm(per, centres[k, 1], 1.3), rnorm(per, centres[k, 2], 1.3))))
iso <- cbind(runif(44, 1, 27), runif(44, 1, 27))
xy <- rbind(clus, iso)
n <- nrow(xy)
A <- rlnorm(n, meanlog = 0, sdlog = 0.9)
D <- as.matrix(dist(xy))
alpha <- 0.6
n

## ---- capacity ----
Mmat <- function(D, A, alpha) {
  M <- exp(-alpha * D) * outer(A, A)
  diag(M) <- 0
  M
}
M <- Mmat(D, A, alpha)
ev <- eigen(M, symmetric = TRUE)
lamM <- ev$values[1]
v <- abs(ev$vectors[, 1])
v <- v / sqrt(sum(v^2))
c(lambda_M = round(lamM, 2), eigenvector_single_signed = all(ev$vectors[, 1] > 0) || all(ev$vectors[, 1] < 0))

## ---- fig-landscape ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
dfl <- data.frame(x = xy[, 1], y = xy[, 2], area = A, contrib = v^2)
ggplot(dfl, aes(x, y, size = area, colour = contrib)) +
  geom_point(alpha = 0.9) +
  scale_size_area(max_size = 8, guide = "none") +
  scale_colour_gradient(low = "#c9b458", high = "#1d5b4e", name = "capacity share",
                        breaks = c(0.05, 0.15),
                        guide = guide_colourbar(barwidth = grid::unit(6, "cm"),
                                                barheight = grid::unit(0.35, "cm"))) +
  coord_equal() +
  labs(x = "east", y = "north") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")

## ---- patch-value ----
drop <- sapply(1:n, function(i)
  lamM - eigen(M[-i, -i], symmetric = TRUE, only.values = TRUE)$values[1])
ord <- order(drop, decreasing = TRUE)
top5 <- round(drop[ord[1:5]], 2)
share5 <- 100 * sum(drop[ord[1:5]]) / sum(drop)
trivial <- sum(drop < 0.01 * lamM)
list(top5_values = top5, top5_share_pct = round(share5, 1), patches_under_1pct = trivial)

## ---- approx ----
approx <- lamM * v^2
c(correlation = round(cor(drop, approx), 4),
  rank_correlation = round(cor(drop, approx, method = "spearman"), 4))

## ---- removal ----
delta <- 58
lam_seq <- numeric(n + 1); lam_seq[1] <- lamM; keep <- rep(TRUE, n)
for (k in 1:n) {
  keep[ord[k]] <- FALSE
  lam_seq[k + 1] <- if (sum(keep) >= 2)
    eigen(M[keep, keep], symmetric = TRUE, only.values = TRUE)$values[1] else 0
}
set.seed(11)
lam_rnd <- numeric(n + 1); lam_rnd[1] <- lamM; keepr <- rep(TRUE, n); rnd <- sample(n)
for (k in 1:n) {
  keepr[rnd[k]] <- FALSE
  lam_rnd[k + 1] <- if (sum(keepr) >= 2)
    eigen(M[keepr, keepr], symmetric = TRUE, only.values = TRUE)$values[1] else 0
}
cross_val <- which(lam_seq < delta)[1] - 1
cross_rnd <- which(lam_rnd < delta)[1] - 1
c(by_value = cross_val, at_random = cross_rnd)

## ---- fig-removal ----
dfr <- data.frame(
  removed = rep(0:n, 2),
  lambda = c(lam_seq, lam_rnd),
  order = rep(c("by value", "random"), each = n + 1))
ggplot(dfr, aes(removed, lambda, colour = order)) +
  geom_hline(yintercept = delta, linetype = "dashed", colour = "#b5534e") +
  geom_line(linewidth = 1) +
  annotate("text", x = n * 0.7, y = delta + 4, label = "persistence threshold",
           colour = "#b5534e", size = 3.5) +
  scale_colour_manual(values = c("by value" = "#b5534e", "random" = "#2f8f63"), name = NULL) +
  labs(x = "patches removed", y = "metapopulation capacity") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")

## ---- alpha-sens ----
lamOf <- function(a) eigen(Mmat(D, A, a), symmetric = TRUE, only.values = TRUE)$values[1]
als <- c(0.3, 0.6, 1.0, 1.5)
lams <- sapply(als, lamOf)
persists <- lams > delta
data.frame(alpha = als, lambda_M = round(lams, 1), persists = persists)
