# Fitting dispersal kernels in R
# https://tidyecology.com/posts/fitting-dispersal-kernels/
#
# 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-01

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

## ---- setup-sim ----
# Distance density k_D(r) = 2*pi*r*f(r) for the 2D exponential location kernel.
# Sampling: the distance r ~ Gamma(shape = 2, scale = a).
kd_exp <- function(r, a) (r / a^2) * exp(-r / a)          # per-distance density
f_area <- function(r, a) (1 / (2 * pi * a^2)) * exp(-r / a) # per-area location density

set.seed(101)
a_true <- 20        # location scale, in metres
n_seed <- 400
r <- rgamma(n_seed, shape = 2, scale = a_true)            # observed distances

mean_r <- mean(r)
mode_kd <- a_true   # mode of Gamma(2, a) is (shape - 1) * scale = a

## ---- fig-geometry ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
rr <- seq(0, 100, length.out = 400)
area_d <- f_area(rr, a_true); area_d <- area_d / max(area_d)
dist_d <- kd_exp(rr, a_true);  dist_d <- dist_d / max(dist_d)
dg <- data.frame(
  r = rep(rr, 2),
  dens = c(area_d, dist_d),
  which = rep(c("per-area density f(r)", "per-distance density k_D(r)"), each = length(rr))
)
ggplot(dg, aes(r, dens, colour = which)) +
  geom_vline(xintercept = a_true, linetype = "dashed", colour = "#5d6b61") +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("per-area density f(r)" = "#c9a227",
                                 "per-distance density k_D(r)" = "#275139")) +
  labs(x = "distance from source (m)", y = "relative density", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())

## ---- fit-both ----
# Correct: distances follow k_D(r) = (r/a^2) exp(-r/a), i.e. Gamma(shape 2, scale a).
nll_correct <- function(la) -sum(log(kd_exp(r, exp(la))))
a_hat <- exp(optimize(nll_correct, c(-5, 10))$minimum)

# Naive: treat distances as exponential with density (1/b) exp(-r/b).
nll_naive <- function(lb) -sum(dexp(r, rate = 1 / exp(lb), log = TRUE))
b_hat <- exp(optimize(nll_naive, c(-5, 10))$minimum)

ratio <- b_hat / a_hat

## ---- fig-fits ----
rr2 <- seq(0, max(r), length.out = 400)
fit_correct <- kd_exp(rr2, a_hat)
fit_naive <- dexp(rr2, rate = 1 / b_hat)
df_fit <- data.frame(
  r = rep(rr2, 2),
  dens = c(fit_correct, fit_naive),
  which = rep(c("correct k_D fit", "naive exponential fit"), each = length(rr2))
)
ggplot() +
  geom_histogram(data = data.frame(r = r), aes(r, after_stat(density)),
                 bins = 32, fill = "#dad9ca", colour = "white") +
  geom_line(data = df_fit, aes(r, dens, colour = which), linewidth = 1) +
  scale_colour_manual(values = c("correct k_D fit" = "#275139",
                                 "naive exponential fit" = "#c9a227")) +
  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())
