# Checking a dispersal kernel
# https://tidyecology.com/posts/checking-a-dispersal-kernel/
#
# 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-07

## ----
knitr::opts_chunk$set(warning = FALSE, message = FALSE)

## ---- setup ----
kd_2dt <- function(r, a, p) (2 * p * r / a^2) * (1 + r^2 / a^2)^(-(p + 1))
S_2dt  <- function(R, a, p) (1 + R^2 / a^2)^(-p)
m_2dt  <- function(a, p) if (p > 0.5) p * a * (sqrt(pi) / 2) * gamma(p - 0.5) / gamma(p + 1) else Inf
r2dt   <- function(N, a, p) a * sqrt((1 - runif(N))^(-1 / p) - 1)   # sampler
fit_2dt <- function(r) {
  nll <- function(v) { d <- kd_2dt(r, exp(v[1]), exp(v[2])); -sum(log(pmax(d, 1e-300))) }
  o <- tryCatch(optim(c(log(median(r)), 0), nll, method = "BFGS"),
                error = function(e) optim(c(log(median(r)), 0), nll, method = "Nelder-Mead"))
  list(a = exp(o$par[1]), p = exp(o$par[2])) }

## ---- check1 ----
set.seed(505)
r <- r2dt(500, a = 25, p = 1.3)
f_full <- fit_2dt(r)
keep <- r <= quantile(r, 0.95)          # drop the farthest 5%
f_trim <- fit_2dt(r[keep])
n_drop <- sum(!keep)
# the trimmed sample is truncated at the cut, so refit it with the Check 2 truncation term too
D_cut <- max(r[keep])
nll_cut <- function(v) { a <- exp(v[1]); p <- exp(v[2])
  -sum(log(pmax(kd_2dt(r[keep], a, p), 1e-300))) + sum(keep) * log(1 - S_2dt(D_cut, a, p)) }
p_trim_cut <- exp(optim(c(log(median(r[keep])), 0), nll_cut, method = "BFGS")$par[2])

## ---- fig-check1 ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
Rg <- seq(1, 260, length.out = 400)
d1 <- data.frame(R = rep(Rg, 2),
                 S = c(S_2dt(Rg, f_full$a, f_full$p), S_2dt(Rg, f_trim$a, f_trim$p)),
                 fit = rep(c("all seeds", "farthest 5% dropped"), each = length(Rg)))
ggplot(d1, aes(R, S, colour = fit)) +
  geom_vline(xintercept = max(r[keep]), linetype = "dashed", colour = "#5d6b61") +
  geom_line(linewidth = 0.9) +
  scale_y_log10(labels = scales::label_log()) +
  scale_colour_manual(values = c("all seeds" = "#275139", "farthest 5% dropped" = "#b5534e")) +
  labs(x = "distance R (m)", y = "P(distance > R)", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())

## ---- check2 ----
set.seed(606)
r <- r2dt(800, a = 28, p = 1.2); Dmax <- 60
obs <- r[r <= Dmax]                     # only seeds within the trap window
true_mean <- m_2dt(28, 1.2)
frac_beyond <- mean(r > Dmax); n_beyond <- sum(r > Dmax)

nll_naive <- function(v) -sum(log(pmax(kd_2dt(obs, exp(v[1]), exp(v[2])), 1e-300)))
fn <- optim(c(log(median(obs)), 0), nll_naive, method = "BFGS")
mean_naive <- m_2dt(exp(fn$par[1]), exp(fn$par[2]))

# truncated likelihood: divide the density by the probability of landing inside the window
nll_trunc <- function(v) { a <- exp(v[1]); p <- exp(v[2])
  -sum(log(pmax(kd_2dt(obs, a, p), 1e-300))) + length(obs) * log(1 - S_2dt(Dmax, a, p)) }
ft <- optim(c(log(median(obs)), 0), nll_trunc, method = "BFGS")
a_tr <- exp(ft$par[1]); p_tr <- exp(ft$par[2]); mean_trunc <- m_2dt(a_tr, p_tr)

## ---- fig-check2 ----
xr <- seq(0, quantile(r, 0.99), length.out = 500)
n_rain <- length(r)   # histogram density on the scale of all seeds, not just those shown
d2 <- data.frame(r = rep(xr, 2),
                 dens = c(kd_2dt(xr, exp(fn$par[1]), exp(fn$par[2])), kd_2dt(xr, a_tr, p_tr)),
                 fit = rep(c("naive (window ignored)", "truncation corrected"), each = length(xr)))
ggplot() +
  annotate("rect", xmin = Dmax, xmax = Inf, ymin = 0, ymax = Inf, fill = "#e7e4d8", alpha = 0.6) +
  geom_histogram(data = data.frame(r = r[r <= 250]), aes(r, after_stat(count / (n_rain * 5))),
                 binwidth = 5, boundary = 0, fill = "#dad9ca", colour = "white") +
  geom_line(data = d2, aes(r, dens, colour = fit), linewidth = 0.9) +
  geom_vline(xintercept = Dmax, linetype = "dashed", colour = "#5d6b61") +
  scale_colour_manual(values = c("naive (window ignored)" = "#b5534e", "truncation corrected" = "#275139")) +
  coord_cartesian(xlim = c(0, 250)) +
  labs(x = "distance from source (m)", y = "density", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())

## ---- check3 ----
kd_gauss <- function(r, a) (2 * r / a^2) * exp(-(r / a)^2)
kd_exp   <- function(r, a) (r / a^2) * exp(-r / a)
kd_ep    <- function(r, a, c) (c * r / (a^2 * gamma(2 / c))) * exp(-(r / a)^c)
S_gauss  <- function(R, a) exp(-(R / a)^2); S_exp <- function(R, a) exp(-R / a) * (1 + R / a)
S_ep     <- function(R, a, c) pgamma((R / a)^c, shape = 2 / c, lower.tail = FALSE)

set.seed(707)
r <- r2dt(550, a = 24, p = 1.6)
fit1 <- function(nll, lo, hi) exp(optimize(nll, c(lo, hi))$minimum)
ag <- fit1(function(la) -sum(log(kd_gauss(r, exp(la)))), -5, 12)
ae <- fit1(function(la) -sum(log(kd_exp(r, exp(la)))), -5, 12)
op <- optim(c(log(median(r)), 0), function(v) -sum(log(pmax(kd_ep(r, exp(v[1]), exp(v[2])), 1e-300))), method = "BFGS")
ap <- exp(op$par[1]); cp <- exp(op$par[2])
ft <- fit_2dt(r); at <- ft$a; pt <- ft$p

# within-data 90th percentile of each fitted kernel, by simulation
set.seed(7071); N <- 2e5
q90 <- c(quantile(ag * sqrt(-log(runif(N))), 0.9), quantile(rgamma(N, 2, scale = ae), 0.9),
         quantile(ap * rgamma(N, 2 / cp, 1)^(1 / cp), 0.9), quantile(r2dt(N, at, pt), 0.9))
# probability of exceeding 150 m under each fitted kernel
p150 <- c(S_gauss(150, ag), S_exp(150, ae), S_ep(150, ap, cp), S_2dt(150, at, pt))
q90_spread <- max(q90) / min(q90)
tail_ratio <- p150[4] / p150[1]

## ---- fig-check3 ----
rs <- sort(r); emp <- 1 - (seq_along(rs) - 0.5) / length(rs)
Rg <- seq(1, 320, length.out = 400)
d3 <- data.frame(R = rep(Rg, 4),
                 S = c(S_gauss(Rg, ag), S_exp(Rg, ae), S_ep(Rg, ap, cp), S_2dt(Rg, at, pt)),
                 fam = rep(c("Gaussian", "exponential", "exponential-power", "2Dt"), each = length(Rg)))
d3$fam <- factor(d3$fam, levels = c("Gaussian", "exponential", "exponential-power", "2Dt"))
ggplot() +
  geom_step(data = data.frame(R = rs, S = emp), aes(R, S, colour = "observed"), linewidth = 0.4) +
  geom_vline(xintercept = max(r), linetype = "dashed", colour = "#5d6b61") +
  geom_line(data = d3, aes(R, S, colour = fam), linewidth = 0.8) +
  scale_y_log10(limits = c(1e-8, 1), labels = scales::label_log()) +
  scale_colour_manual(values = c(observed = "#3a3a3a", Gaussian = "#9aa69d",
                                 exponential = "#c9a227",
                                 `exponential-power` = "#4f8fbf", `2Dt` = "#275139"),
                      breaks = c("observed", "Gaussian", "exponential",
                                 "exponential-power", "2Dt")) +
  labs(x = "distance R (m)", y = "P(distance > R)", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())
