# The Levins metapopulation model
# https://tidyecology.com/posts/the-levins-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-06-21

## ---- params ----
c_col <- 0.40    # colonisation parameter
e_ext <- 0.15    # extinction parameter
p_star <- 1 - e_ext / c_col
p_star

## ---- deterministic ----
levins_map <- function(p0, cc, ee, steps) {
  p <- numeric(steps + 1)
  p[1] <- p0
  for (t in 1:steps) {
    pt <- p[t]
    p[t + 1] <- pt + cc * pt * (1 - pt) - ee * pt
  }
  p
}
steps <- 100
det <- levins_map(p0 = 0.10, cc = c_col, ee = e_ext, steps = steps)
det_final <- det[steps + 1]
det_final

## ---- simulate ----
sim_patches <- function(n, cc, ee, steps, p0, seed) {
  set.seed(seed)
  occ <- matrix(0L, n, steps + 1)
  occ[, 1] <- as.integer(runif(n) < p0)
  frac <- numeric(steps + 1)
  frac[1] <- mean(occ[, 1])
  for (t in 1:steps) {
    pt <- frac[t]
    st <- occ[, t]
    new <- st
    empty <- st == 0L
    occupied <- st == 1L
    new[empty] <- as.integer(runif(sum(empty)) < cc * pt)
    new[occupied] <- as.integer(runif(sum(occupied)) >= ee)
    occ[, t + 1] <- new
    frac[t + 1] <- mean(new)
  }
  list(occ = occ, frac = frac)
}
n <- 200
sim <- sim_patches(n, c_col, e_ext, steps, p0 = 0.10, seed = 42)
obs_eq <- mean(sim$frac[(steps - 40 + 1):(steps + 1)])
obs_eq

## ---- fig-trajectory ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
dfp <- data.frame(t = 0:steps, stoch = sim$frac, det = det)
ggplot(dfp, aes(t)) +
  geom_hline(yintercept = p_star, linetype = "dashed", colour = "#b5534e", linewidth = 0.6) +
  geom_point(aes(y = stoch), colour = "#275139", size = 1.3, alpha = 0.7) +
  geom_line(aes(y = det), colour = "#275139", linewidth = 0.9) +
  annotate("text", x = 55, y = 0.775, label = "p* = 1 - e/c = 0.625",
           colour = "#b5534e", size = 3.6, hjust = 0) +
  labs(x = "time step", y = "fraction of patches occupied") +
  coord_cartesian(ylim = c(0, 0.8)) +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- fit ----
occ <- sim$occ
fr <- sim$frac
nll <- function(par) {
  cc <- par[1]; ee <- par[2]
  ll <- 0
  for (t in 1:steps) {
    pt <- fr[t]
    st <- occ[, t]; nx <- occ[, t + 1]
    empty <- st == 0L; occupied <- st == 1L
    cp <- cc * pt
    ll <- ll + sum(dbinom(nx[empty], 1, cp, log = TRUE))
    ll <- ll + sum(dbinom(1L - nx[occupied], 1, ee, log = TRUE))
  }
  -ll
}
fit <- optim(c(0.3, 0.2), nll, method = "L-BFGS-B",
             lower = c(1e-3, 1e-3), upper = c(0.999, 0.999))
c_hat <- fit$par[1]
e_hat <- fit$par[2]
c(c_hat = c_hat, e_hat = e_hat, p_star_hat = 1 - e_hat / c_hat)

## ---- extinction-sim ----
sim_frac <- function(n, cc, ee, steps, p0, seed) {
  set.seed(seed)
  st <- as.integer(runif(n) < p0)
  frac <- numeric(steps + 1); frac[1] <- mean(st)
  for (t in 1:steps) {
    pt <- frac[t]
    empty <- st == 0L; occupied <- st == 1L
    new <- st
    new[empty] <- as.integer(runif(sum(empty)) < cc * pt)
    new[occupied] <- as.integer(runif(sum(occupied)) >= ee)
    st <- new; frac[t + 1] <- mean(st)
  }
  frac
}
c2 <- 0.25; e2 <- 0.30           # e/c = 1.2, above threshold
ratio2 <- e2 / c2
fr_ext <- sim_frac(200, c2, e2, 60, p0 = 0.50, seed = 7)
occ40 <- fr_ext[41]
ratio2
occ40

## ---- fig-threshold ----
rr <- seq(0, 1.4, by = 0.001)
dft <- data.frame(ratio = rr, pstar = pmax(0, 1 - rr))
pts <- data.frame(ratio = c(e_ext / c_col, ratio2),
                  pstar = c(p_star, 0),
                  lab = c("persists", "goes extinct"))
ggplot(dft, aes(ratio, pstar)) +
  geom_vline(xintercept = 1, linetype = "dotted", colour = "#5d6b61") +
  geom_line(colour = "#275139", linewidth = 1) +
  geom_point(data = pts, aes(colour = lab), size = 3) +
  scale_colour_manual(values = c(persists = "#275139", `goes extinct` = "#b5534e"), name = NULL) +
  annotate("text", x = 1.02, y = 0.55, label = "extinction threshold e/c = 1",
           colour = "#5d6b61", size = 3.4, hjust = 0) +
  labs(x = "extinction / colonisation ratio (e/c)",
       y = "equilibrium fraction occupied (p*)") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")
