# Critical patch size and the dispersal kernel
# https://tidyecology.com/posts/critical-patch-size-and-dispersal/
#
# 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

## ---- setup ----
library(ggplot2)
library(patchwork)

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"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- kernels ----
sd_disp <- 1                          # dispersal standard deviation (length unit)
alpha_lap <- sqrt(2) / sd_disp        # Laplace rate giving the same variance
r0_main <- 1.5                        # offspring per adult at low density

cdf_kern <- list(
  Gaussian = function(d) pnorm(d, 0, sd_disp),
  Laplace  = function(d) ifelse(d < 0, 0.5 * exp(alpha_lap * d),
                                1 - 0.5 * exp(-alpha_lap * d)))

set.seed(3017)
n_draw <- 200000
draw_lap <- rexp(n_draw, alpha_lap) * (2 * (runif(n_draw) < 0.5) - 1)
sd_lap_draw <- sd(draw_lap)
med_gau <- qnorm(0.75, 0, sd_disp)
med_lap <- log(2) / alpha_lap

## ---- operator ----
lambda_max <- function(patch_len, kern, n_cell) {
  h_cell <- patch_len / n_cell
  x_mid  <- (seq_len(n_cell) - 0.5) * h_cell
  gap    <- outer(x_mid, x_mid, "-")
  op_mat <- cdf_kern[[kern]](gap + h_cell / 2) - cdf_kern[[kern]](gap - h_cell / 2)
  eigen(op_mat, symmetric = TRUE, only.values = TRUE)$values[1]
}

critical_len <- function(kern, r0, n_cell) {
  uniroot(function(len) r0 * lambda_max(len, kern, n_cell) - 1,
          c(0.02, 40), tol = 1e-8)$root
}

lap_closed  <- 2 / (alpha_lap * sqrt(r0_main - 1)) * atan(1 / sqrt(r0_main - 1))
kiss_closed <- pi * sqrt((sd_disp^2 / 2) / log(r0_main))

n_check <- c(50, 100, 200)
conv_tab <- data.frame(
  n_cell   = n_check,
  laplace  = vapply(n_check, function(m) critical_len("Laplace", r0_main, m), 0),
  gaussian = vapply(n_check, function(m) critical_len("Gaussian", r0_main, m), 0))
conv_tab$lap_error <- conv_tab$laplace - lap_closed

kiss_linear <- pi * sqrt((sd_disp^2 / 2) / (r0_main - 1))   # diffusion threshold with r = R0 - 1

n_main    <- 200
lstar_gau <- conv_tab$gaussian[conv_tab$n_cell == n_main]
lstar_lap <- conv_tab$laplace[conv_tab$n_cell == n_main]
gau_drift <- abs(diff(conv_tab$gaussian[conv_tab$n_cell >= 100]))
ratio_lap_gau  <- lstar_lap / lstar_gau
ratio_gau_kiss <- lstar_gau / kiss_closed
ratio_gau_kiss_lin <- lstar_gau / kiss_linear

## ---- fig-eigen ----
len_grid <- seq(1, 6, by = 0.25)
eig_df <- rbind(
  data.frame(len = len_grid, kern = "Gaussian",
             growth = r0_main * vapply(len_grid, lambda_max, 0, kern = "Gaussian", n_cell = 120)),
  data.frame(len = len_grid, kern = "Laplace",
             growth = r0_main * vapply(len_grid, lambda_max, 0, kern = "Laplace", n_cell = 120)))
star_df <- data.frame(len = c(lstar_gau, lstar_lap), growth = 1,
                      kern = c("Gaussian", "Laplace"))

ggplot(eig_df, aes(len, growth, colour = kern)) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.5) +
  geom_vline(xintercept = kiss_closed, linetype = "dashed", colour = te_rust, linewidth = 0.7) +
  annotate("text", x = kiss_closed + 0.08, y = 0.55, label = "diffusion threshold",
           hjust = 0, colour = te_rust, size = 3.6) +
  geom_line(linewidth = 1) +
  geom_point(data = star_df, size = 3) +
  scale_colour_manual(values = c(Gaussian = te_forest, Laplace = te_gold), name = NULL) +
  scale_y_continuous(limits = c(0.5, 1.5)) +
  labs(x = "patch length (dispersal standard deviations)",
       y = "growth factor at low density",
       title = "The peaked kernel crosses one sooner",
       subtitle = "points: critical lengths; horizontal line: replacement") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- edgeloss ----
dist_grid <- seq(0, 3, by = 0.01)
loss_gau <- 1 - cdf_kern$Gaussian(dist_grid)
loss_lap <- 1 - cdf_kern$Laplace(dist_grid)
cross_d  <- uniroot(function(d) (1 - cdf_kern$Gaussian(d)) - (1 - cdf_kern$Laplace(d)),
                    c(0.5, 3))$root
d_show   <- 0.5
loss_gau_half <- 1 - cdf_kern$Gaussian(d_show)
loss_lap_half <- 1 - cdf_kern$Laplace(d_show)

# loss for the whole population at the Gaussian critical length, uniform adults
mean_loss <- function(kern, len) {
  x_par <- seq(0, len, length.out = 2001)
  mean(1 - (cdf_kern[[kern]](len - x_par) - cdf_kern[[kern]](-x_par)))
}
loss_unif_gau <- mean_loss("Gaussian", lstar_gau)
loss_unif_lap <- mean_loss("Laplace", lstar_gau)

## ---- fig-edgeloss ----
loss_df <- rbind(data.frame(dist = dist_grid, loss = loss_gau, kern = "Gaussian"),
                 data.frame(dist = dist_grid, loss = loss_lap, kern = "Laplace"))
ggplot(loss_df, aes(dist, loss, colour = kern)) +
  geom_vline(xintercept = cross_d, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c(Gaussian = te_forest, Laplace = te_gold), name = NULL) +
  labs(x = "parent's distance from the edge (dispersal standard deviations)",
       y = "share of offspring lost",
       title = "Near the edge the peaked kernel loses less",
       subtitle = "dashed line: where the two loss curves cross") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- ranking ----
mgf_log <- list(Gaussian = function(s) s^2 * sd_disp^2 / 2,
                Laplace  = function(s) log(alpha_lap^2 / (alpha_lap^2 - s^2)))
front_speed <- function(kern, r0) {
  s_top <- if (kern == "Gaussian") 30 else alpha_lap - 1e-9
  optimize(function(s) (log(r0) + mgf_log[[kern]](s)) / s, c(1e-6, s_top))$objective
}

r0_grid <- c(1.1, 1.25, 1.5, 2, 3, 5, 10)
rank_tab <- data.frame(r0 = r0_grid)
rank_tab$lstar_gau <- vapply(r0_grid, function(r) critical_len("Gaussian", r, 150), 0)
rank_tab$lstar_lap <- vapply(r0_grid, function(r) critical_len("Laplace", r, 150), 0)
rank_tab$lap_cf    <- 2 / (alpha_lap * sqrt(r0_grid - 1)) * atan(1 / sqrt(r0_grid - 1))
rank_tab$kiss      <- pi * sqrt((sd_disp^2 / 2) / log(r0_grid))
rank_tab$c_gau     <- vapply(r0_grid, function(r) front_speed("Gaussian", r), 0)
rank_tab$c_lap     <- vapply(r0_grid, function(r) front_speed("Laplace", r), 0)
rank_tab$len_ratio <- rank_tab$lstar_lap / rank_tab$lstar_gau
rank_tab$speed_ratio <- rank_tab$c_lap / rank_tab$c_gau

cf_err_max  <- max(abs(rank_tab$lstar_lap - rank_tab$lap_cf))
c_gau_check <- max(abs(rank_tab$c_gau - sd_disp * sqrt(2 * log(r0_grid))))
n_lap_faster  <- sum(rank_tab$speed_ratio > 1)
n_lap_smaller <- sum(rank_tab$len_ratio < 1)
both_monotone <- all(diff(rank_tab$len_ratio) < 0) && all(diff(rank_tab$speed_ratio) > 0)

# matched variance: log M_Laplace(s) - log M_Gaussian(s) = -log(1 - u) - u with u = s^2 / 2, never negative
s_check  <- seq(0.001, alpha_lap - 0.001, length.out = 5000)
mgf_gap  <- mgf_log$Laplace(s_check) - mgf_log$Gaussian(s_check)
mgf_gap_min <- min(mgf_gap)
len_ratio_lo  <- rank_tab$len_ratio[1]
len_ratio_hi  <- rank_tab$len_ratio[length(r0_grid)]
speed_ratio_lo <- rank_tab$speed_ratio[1]
speed_ratio_hi <- rank_tab$speed_ratio[length(r0_grid)]

## ---- fig-ranking ----
p_len <- ggplot(rank_tab, aes(r0, len_ratio)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_line(colour = te_gold, linewidth = 1) +
  geom_point(colour = te_gold, size = 2.4) +
  scale_x_log10(breaks = c(1.1, 1.5, 2, 3, 5, 10), labels = c("1.1", "1.5", "2", "3", "5", "10")) +
  scale_y_continuous(limits = c(0.5, 1.5)) +
  labs(x = "R0 (log scale)", y = "Laplace / Gaussian",
       title = "Critical patch length") +
  theme_datasheet()
p_spd <- ggplot(rank_tab, aes(r0, speed_ratio)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_line(colour = te_rust, linewidth = 1) +
  geom_point(colour = te_rust, size = 2.4) +
  scale_x_log10(breaks = c(1.1, 1.5, 2, 3, 5, 10), labels = c("1.1", "1.5", "2", "3", "5", "10")) +
  scale_y_continuous(limits = c(0.5, 1.5)) +
  labs(x = "R0 (log scale)", y = NULL, title = "Front speed") +
  theme_datasheet()
p_len + p_spd + plot_annotation(theme = theme_datasheet())

## ---- ibm ----
n_gen   <- 100
n_rep   <- 200
k_dens  <- c(5, 20)
ibm_len <- seq(1.5, 6, by = 0.25)

draw_kern <- function(n_off, kern) {
  if (kern == "Gaussian") rnorm(n_off, 0, sd_disp)
  else rexp(n_off, alpha_lap) * (2 * (runif(n_off) < 0.5) - 1)
}

run_ibm <- function(kern, k_per_len, dd_form) {
  cell_len <- rep(ibm_len, each = n_rep)
  n_run    <- length(cell_len)
  cap      <- round(k_per_len * cell_len)
  run_id   <- rep(seq_len(n_run), cap)
  pos      <- runif(length(run_id)) * cell_len[run_id]
  for (gen in seq_len(n_gen)) {
    size_now <- tabulate(run_id, n_run)
    mu_off <- if (dd_form == "ceiling") r0_main else
      (r0_main / (1 + (r0_main - 1) * size_now / cap))[run_id]
    n_off  <- rpois(length(run_id), mu_off)
    run_id <- rep(run_id, n_off)
    pos    <- rep(pos, n_off) + draw_kern(length(run_id), kern)
    inside <- pos > 0 & pos < cell_len[run_id]
    run_id <- run_id[inside]; pos <- pos[inside]
    if (dd_form == "ceiling") {
      size_now <- tabulate(run_id, n_run)
      if (any(size_now > cap)) {
        ord    <- order(run_id, runif(length(run_id)))
        run_id <- run_id[ord]; pos <- pos[ord]
        rank_in <- seq_along(run_id) - cumsum(c(0, size_now))[run_id]
        keep   <- rank_in <= cap[run_id]
        run_id <- run_id[keep]; pos <- pos[keep]
      }
    }
    if (length(run_id) == 0) break
  }
  data.frame(kern = kern, k_dens = k_per_len, dd_form = dd_form,
             len = cell_len, alive = tabulate(run_id, n_run) > 0)
}

set.seed(6211)
ibm_runs <- do.call(rbind, lapply(c("Beverton-Holt", "ceiling"), function(dd)
  do.call(rbind, lapply(k_dens, function(kk)
    do.call(rbind, lapply(c("Gaussian", "Laplace"), function(ke) run_ibm(ke, kk, dd)))))))

persist_df <- aggregate(alive ~ kern + k_dens + dd_form + len, data = ibm_runs, FUN = mean)
persist_df$se <- sqrt(persist_df$alive * (1 - persist_df$alive) / n_rep)
mc_se_max <- sqrt(0.25 / n_rep)

## ---- thresholds ----
half_len <- function(p_alive) {
  i_up <- which(p_alive >= 0.5)[1]
  if (is.na(i_up) || i_up == 1) return(NA_real_)
  approx(p_alive[(i_up - 1):i_up], ibm_len[(i_up - 1):i_up], xout = 0.5)$y
}
n_boot <- 500
fit_l50 <- function(sub_runs) {
  p_hat  <- tapply(sub_runs$alive, sub_runs$len, mean)
  boot_l <- replicate(n_boot, half_len(rbinom(length(p_hat), n_rep, p_hat) / n_rep))
  c(l50 = half_len(p_hat), se = sd(boot_l, na.rm = TRUE))
}
set.seed(8093)
cell_keys <- unique(ibm_runs[, c("kern", "k_dens", "dd_form")])
l50_tab <- cbind(cell_keys, t(vapply(seq_len(nrow(cell_keys)), function(i) {
  sub_runs <- ibm_runs[ibm_runs$kern == cell_keys$kern[i] &
                       ibm_runs$k_dens == cell_keys$k_dens[i] &
                       ibm_runs$dd_form == cell_keys$dd_form[i], ]
  fit_l50(sub_runs)
}, numeric(2))))
l50_tab$lstar <- ifelse(l50_tab$kern == "Gaussian", lstar_gau, lstar_lap)
l50_tab$lift  <- l50_tab$l50 / l50_tab$lstar

pick <- function(ke, kk, dd, col) l50_tab[l50_tab$kern == ke & l50_tab$k_dens == kk &
                                          l50_tab$dd_form == dd, col]
bh20_gau <- pick("Gaussian", 20, "Beverton-Holt", "l50"); bh20_gau_se <- pick("Gaussian", 20, "Beverton-Holt", "se")
bh20_lap <- pick("Laplace", 20, "Beverton-Holt", "l50");  bh20_lap_se <- pick("Laplace", 20, "Beverton-Holt", "se")
bh5_gau  <- pick("Gaussian", 5, "Beverton-Holt", "l50");  bh5_gau_se <- pick("Gaussian", 5, "Beverton-Holt", "se")
bh5_lap  <- pick("Laplace", 5, "Beverton-Holt", "l50");   bh5_lap_se <- pick("Laplace", 5, "Beverton-Holt", "se")
cl20_gau <- pick("Gaussian", 20, "ceiling", "l50")
cl20_lap <- pick("Laplace", 20, "ceiling", "l50")
cl5_gau  <- pick("Gaussian", 5, "ceiling", "l50")
cl5_lap  <- pick("Laplace", 5, "ceiling", "l50")
gap_det  <- lstar_gau - lstar_lap
gap_bh20 <- bh20_gau - bh20_lap
gap_bh5  <- bh5_gau - bh5_lap
gap_bh5_se <- sqrt(bh5_gau_se^2 + bh5_lap_se^2)
lift_bh20_gau <- bh20_gau / lstar_gau
lift_bh5_gau  <- bh5_gau / lstar_gau
lift_cl20_gau <- cl20_gau / lstar_gau
lift_cl5_gau  <- cl5_gau / lstar_gau

# deterministic Beverton-Holt equilibrium at a patch length: K L (R0 lambda - 1) / (R0 - 1)
eq_size <- function(kern, len, kk) kk * len * (r0_main * lambda_max(len, kern, n_main) - 1) / (r0_main - 1)
eq_bh20_gau <- eq_size("Gaussian", bh20_gau, 20)
eq_bh5_gau  <- eq_size("Gaussian", bh5_gau, 5)
below_len  <- max(ibm_len[ibm_len < lstar_gau])
below_p    <- persist_df$alive[persist_df$kern == "Gaussian" & persist_df$k_dens == 20 &
                               persist_df$dd_form == "ceiling" & persist_df$len == below_len]
below_grow <- r0_main * lambda_max(below_len, "Gaussian", n_main)

## ---- fig-persist ----
persist_df$panel <- factor(paste0(persist_df$dd_form, ", K = ", persist_df$k_dens),
                           levels = c("Beverton-Holt, K = 20", "Beverton-Holt, K = 5",
                                      "ceiling, K = 20", "ceiling, K = 5"))
vline_df <- data.frame(kern = c("Gaussian", "Laplace"), len = c(lstar_gau, lstar_lap))
ggplot(persist_df, aes(len, alive, colour = kern)) +
  geom_vline(data = vline_df, aes(xintercept = len, colour = kern),
             linetype = "dashed", linewidth = 0.6, show.legend = FALSE) +
  geom_errorbar(aes(ymin = alive - 1.96 * se, ymax = alive + 1.96 * se),
                width = 0.08, linewidth = 0.4, show.legend = FALSE) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.6) +
  facet_wrap(~panel, ncol = 2) +
  scale_colour_manual(values = c(Gaussian = te_forest, Laplace = te_gold), name = NULL) +
  labs(x = "patch length (dispersal standard deviations)",
       y = "share of runs alive after 100 generations",
       title = "The practical threshold depends on density dependence",
       subtitle = "200 runs per point; bars: 95 per cent Monte Carlo intervals") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink, face = "bold"))
