# Checking a metapopulation model
# https://tidyecology.com/posts/checking-a-metapopulation-model/
#
# 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-08

## ---- setup ----
Efun <- function(A, mu, x) pmin(1, mu / A^x)
conn <- function(o, D, A, alpha) {
  M <- exp(-alpha * D) * outer(rep(1, length(A)), A)
  diag(M) <- 0
  as.numeric(M %*% o)
}
Cfun <- function(S, y) S^2 / (S^2 + y^2)

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))
patch <- rbind(clus, iso)
n <- nrow(patch)
A <- rlnorm(n, meanlog = 0, sdlog = 0.9)
D <- as.matrix(dist(patch))
mu_t <- 0.8; x_t <- 1.0; y_t <- 2.5; alpha_t <- 0.6
Etrue <- Efun(A, mu_t, x_t)

fitIFM <- function(o, af = 0.6) {
  S <- conn(o, D, A, af)
  nll <- function(p) {
    mu <- exp(p[1]); x <- exp(p[2]); y <- exp(p[3])
    C <- Cfun(S, y); E <- Efun(A, mu, x)
    J <- pmin(pmax(C / (C + E), 1e-9), 1 - 1e-9)
    -sum(dbinom(o, 1, J, log = TRUE))
  }
  # several starts, one with mu below one: where mu / A^x exceeds one for every
  # patch, E is capped at one and the likelihood is flat in x
  best <- NULL
  for (s in list(log(c(0.5, 1, 2)), log(c(1, 0.5, 1)), log(c(0.3, 1.5, 4)),
                 log(c(2, 1, 0.5)), log(c(0.7, 0.1, 4)))) {
    f <- optim(s, nll, method = "Nelder-Mead",
               control = list(maxit = 4000, reltol = 1e-12))
    f <- optim(f$par, nll, method = "BFGS")
    if (is.null(best) || f$value < best$value) best <- f
  }
  list(par = exp(best$par), ll = -best$value)
}
n

## ---- snapshots ----
o <- as.integer(runif(n) < 0.5)
set.seed(303)
for (t in 1:2000) {
  S <- conn(o, D, A, alpha_t); C <- Cfun(S, y_t)
  new <- o; emp <- o == 0L; occ <- o == 1L
  new[emp] <- as.integer(runif(sum(emp)) < C[emp])
  new[occ] <- as.integer(runif(sum(occ)) >= Etrue[occ])
  o <- new
}
o_eq <- o

tau <- 0.25
stepT <- function(o) {
  S <- conn(o, D, A, alpha_t); C <- Cfun(S, y_t)
  new <- o; emp <- o == 0L; occ <- o == 1L
  new[emp] <- as.integer(runif(sum(emp)) < C[emp] * tau)
  new[occ] <- as.integer(runif(sum(occ)) >= Etrue[occ] * tau)
  new
}
set.seed(505)
o <- as.integer(runif(n) < 0.05)
for (t in 1:6) o <- stepT(o)
o_tr <- o
c(equilibrium_occupied = sum(o_eq), transient_occupied = sum(o_tr))

## ---- transient-fit ----
fe <- fitIFM(o_eq); ft <- fitIFM(o_tr)
rbind(equilibrium = round(fe$par, 3),
      transient   = round(ft$par, 3))

## ---- mechanism ----
S_eq <- conn(o_eq, D, A, alpha_t); S_tr <- conn(o_tr, D, A, alpha_t)
rbind(equilibrium = c(area = cor(o_eq, log(A)), connectivity = cor(o_eq, log(S_eq + 1e-6))),
      transient   = c(area = cor(o_tr, log(A)), connectivity = cor(o_tr, log(S_tr + 1e-6)))) |>
  round(3)

## ---- fig-transient ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
dft <- rbind(
  data.frame(logA = log(A), occ = o_eq, panel = "equilibrium"),
  data.frame(logA = log(A), occ = o_tr, panel = "transient (recovering)"))
ggplot(dft, aes(logA, occ)) +
  geom_point(aes(colour = panel), position = position_jitter(height = 0.04),
             alpha = 0.5, size = 1.4, show.legend = FALSE) +
  geom_smooth(method = "glm", method.args = list(family = "binomial"),
              se = FALSE, colour = "#275139", linewidth = 1) +
  scale_colour_manual(values = c("equilibrium" = "#2f8f63",
                                 "transient (recovering)" = "#b5534e")) +
  facet_wrap(~panel) +
  labs(x = "log patch area", y = "occupied") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- alpha-profile ----
proflik <- function(al) {
  Sa <- conn(o_eq, D, A, al)
  nl <- function(p) {
    mu <- exp(p[1]); x <- exp(p[2]); y <- exp(p[3])
    Cc <- Cfun(Sa, y); Ee <- Efun(A, mu, x)
    Jj <- pmin(pmax(Cc / (Cc + Ee), 1e-9), 1 - 1e-9)
    -sum(dbinom(o_eq, 1, Jj, log = TRUE))
  }
  starts <- list(log(c(0.5, 1, 2)), log(c(1, 0.5, 1)),
                 log(c(0.3, 1.5, 4)), log(c(2, 1, 0.5)))
  best <- Inf
  for (s in starts) {
    r <- optim(s, nl, method = "Nelder-Mead", control = list(maxit = 3000, reltol = 1e-11))
    r <- optim(r$par, nl, method = "BFGS")
    if (r$value < best) best <- r$value
  }
  -best
}
alg <- seq(0.05, 1.4, by = 0.05)
pl <- sapply(alg, proflik)
inb <- range(alg[pl >= max(pl) - 1.92])
c(logLik_span = round(max(pl) - min(pl), 2), ci_low = inb[1], ci_high = inb[2])

## ---- fig-alpha ----
dfa <- data.frame(alpha = alg, ll = pl)
ggplot(dfa, aes(alpha, ll)) +
  geom_hline(yintercept = max(pl) - 1.92, linetype = "dashed", colour = "#b5534e") +
  geom_line(colour = "#275139", linewidth = 1) +
  geom_point(colour = "#275139", size = 1.6) +
  annotate("text", x = 1.1, y = max(pl) - 1.92 + 0.25,
           label = "1.92 below peak", colour = "#b5534e", size = 3.3) +
  labs(x = "dispersal parameter alpha", y = "profile log-likelihood") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- alpha-capacity ----
Mmat <- function(al) { M <- exp(-al * D) * outer(A, A); diag(M) <- 0; M }
lamOf <- function(al) eigen(Mmat(al), symmetric = TRUE, only.values = TRUE)$values[1]
c(lambda_at_low = round(lamOf(inb[1]), 1),
  lambda_at_high = round(lamOf(inb[2]), 1),
  fold_range = round(lamOf(inb[1]) / lamOf(inb[2]), 1))

## ---- extinction-curve ----
lamM <- lamOf(alpha_t)
K_t <- exp(-alpha_t * D) * outer(rep(1, n), A)   # the kernel conn() uses, built once
diag(K_t) <- 0
sim_srl <- function(cc, ee, steps, tau, seed) {
  set.seed(seed)
  o <- rep(1L, n)
  for (t in 1:steps) {
    S <- as.numeric(K_t %*% o)
    pc <- 1 - exp(-cc * S * tau); pe <- 1 - exp(-(ee / A) * tau)
    new <- o; emp <- o == 0L; occ <- o == 1L
    new[emp] <- as.integer(runif(sum(emp)) < pc[emp])
    new[occ] <- as.integer(runif(sum(occ)) >= pe[occ])
    o <- new
    if (sum(o) == 0) return(TRUE)
  }
  FALSE
}
# a step that is long against the extinction rates ee / A lets a fully occupied
# network empty in its first step; 0.01 is short enough to prevent that, though
# still coarse against ee / A for most patches, and 4000 steps of it cover the
# same 40 time units
cc <- 1; R <- 250; H <- 4000; tau_s <- 0.01
ratios <- c(0.3, 0.5, 0.7, 0.9, 1.1, 1.3)
pext <- sapply(ratios, function(rr) {
  ee <- rr * lamM * cc
  mean(sapply(1:R, function(k) sim_srl(cc, ee, H, tau_s, seed = 5000 + round(rr * 1000) + k)))
})
data.frame(delta_over_lambda = ratios, extinction_prob = round(pext, 3))

## ---- fig-extinction ----
dfe <- data.frame(ratio = ratios, pext = pext)
step_df <- data.frame(ratio = c(0.3, 1, 1, 1.3), y = c(0, 0, 1, 1))
ggplot() +
  geom_vline(xintercept = 1, linetype = "dashed", colour = "#93a87f") +
  geom_line(data = step_df, aes(ratio, y), colour = "#93a87f", linewidth = 0.9) +
  geom_line(data = dfe, aes(ratio, pext), colour = "#b5534e", linewidth = 1) +
  geom_point(data = dfe, aes(ratio, pext), colour = "#b5534e", size = 2) +
  annotate("text", x = 0.62, y = 0.06, label = "deterministic verdict",
           colour = "#6f836a", size = 3.3) +
  annotate("text", x = 0.52, y = 0.66, label = "stochastic risk", hjust = 0,
           colour = "#b5534e", size = 3.3) +
  labs(x = "threshold / capacity (delta / lambda_M)", y = "extinction probability") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank())
