# Adaptive dynamics and evolutionary branching
# https://tidyecology.com/posts/adaptive-dynamics-and-branching/
#
# 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 ----
sK <- 1
K0 <- 1000
Kf <- function(x) K0 * exp(-x^2 / (2 * sK^2))
alf <- function(x, y, sa) exp(-(x - y)^2 / (2 * sa^2))

# invasion fitness of mutant y against resident x
sfit <- function(y, x, sa) 1 - alf(y, x, sa) * Kf(x) / Kf(y)

## ---- gradient ----
for (x in c(-1, -0.5, 0.2, 1)) {
  num <- (sfit(x + 1e-6, x, 1.2) - sfit(x - 1e-6, x, 1.2)) / 2e-6
  cat(sprintf("x = %5.2f   numeric = %9.6f   -x/sigma_K^2 = %9.6f\n",
              x, num, -x / sK^2))
}

## ---- curvature ----
for (sa in c(0.6, 0.8, 1.0, 1.2, 1.5)) {
  h <- 1e-4
  d2 <- (sfit(h, 0, sa) - 2 * sfit(0, 0, sa) + sfit(-h, 0, sa)) / h^2
  cat(sprintf("sigma_a = %.1f   curvature = %+9.6f   1/sa^2 - 1/sK^2 = %+9.6f   %s\n",
              sa, d2, 1 / sa^2 - 1 / sK^2,
              if (abs(d2) < 1e-6) "degenerate" else if (d2 > 0) "branching point" else "ESS"))
}

## ---- fig-pip ----
suppressMessages(library(ggplot2))
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

gx <- seq(-1.2, 1.2, length.out = 241)
pip <- do.call(rbind, lapply(c(0.8, 1.2), function(sa) {
  g <- expand.grid(resident = gx, mutant = gx)
  g$sa <- factor(sprintf("sigma_a = %.1f", sa))
  g$sign <- ifelse(sfit(g$mutant, g$resident, sa) > 0,
                   "mutant invades", "mutant fails")
  g
}))
pip$sign <- factor(pip$sign, levels = c("mutant fails", "mutant invades"))

# the non-trivial zero contour is a straight line through the origin
for (sa in c(0.8, 1.2)) {
  slope <- (sK^2 + sa^2) / (sK^2 - sa^2)
  cat(sprintf("sigma_a = %.1f   predicted slope = %+8.4f   fitness on it = %+.3e\n",
              sa, slope, sfit(0.3 * slope, 0.3, sa)))
}

ggplot(pip, aes(resident, mutant, fill = sign)) +
  geom_raster() +
  facet_wrap(~sa) +
  scale_fill_manual(values = c("mutant fails" = "#e6e4dc",
                               "mutant invades" = "#275139")) +
  geom_abline(slope = 1, intercept = 0, colour = "#8d8d80", linewidth = 0.4) +
  coord_equal(expand = FALSE) +
  labs(x = "Resident trait", y = "Mutant trait", fill = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid = element_blank())

## ---- mutual ----
for (sa in c(1.2, 0.8)) {
  for (d in c(0.05, 0.1, 0.2)) {
    cat(sprintf("sigma_a = %.1f  d = %.2f   s(-d -> +d) = %+.6f   s(+d -> -d) = %+.6f   %s\n",
                sa, d, sfit(d, -d, sa), sfit(-d, d, sa),
                if (sfit(d, -d, sa) > 0 && sfit(-d, d, sa) > 0)
                  "mutually invasible" else "not"))
  }
}

## ---- dimorphic ----
neq <- function(x, sa) as.numeric(solve(outer(x, x, alf, sa = sa), Kf(x)))
sfit2 <- function(y, x, sa) 1 - sum(alf(y, x, sa) * neq(x, sa)) / Kf(y)

# gradient acting on the upper branch of a symmetric pair at +/- d
grad2 <- function(d, sa) {
  h <- 1e-6
  (sfit2(d + h, c(-d, d), sa) - sfit2(d - h, c(-d, d), sa)) / (2 * h)
}

for (sa in c(0.8, 0.5)) {
  r <- uniroot(grad2, c(0.05, 3), sa = sa, tol = 1e-10)$root
  n <- neq(c(-r, r), sa)
  cat(sprintf("sigma_a = %.1f   dimorphic singular pair at +/- %.6f   density %.2f each\n",
              sa, r, n[1]))
}

## ---- closed-form ----
dstar <- function(sa, sK. = sK) sa * sqrt(log((2 * sK.^2 - sa^2) / sa^2) / 2)

for (sa in c(0.5, 0.8, 1.0, 1.2)) {
  ok <- 2 * sK^2 - sa^2 > sa^2
  cat(sprintf("sigma_a = %.1f   d* = %s\n", sa,
              if (ok) sprintf("%.6f", dstar(sa)) else "none"))
}

## ---- fig-spacing ----
sas <- seq(0.05, 0.995, length.out = 400)
ds <- data.frame(sa = sas, d = dstar(sas))
cat("maximum spacing", round(max(ds$d), 6),
    "at sigma_a =", round(ds$sa[which.max(ds$d)], 4), "\n")

ggplot(ds, aes(sa, d)) +
  geom_line(colour = "#275139", linewidth = 1.2) +
  labs(x = expression(sigma[a]), y = "Half-spacing of the two branches") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- second-branch ----
for (sa in c(0.8, 0.5)) {
  r <- uniroot(grad2, c(0.05, 3), sa = sa, tol = 1e-10)$root
  h <- 1e-4
  x <- c(-r, r)
  d2 <- (sfit2(r + h, x, sa) - 2 * sfit2(r, x, sa) + sfit2(r - h, x, sa)) / h^2
  cat(sprintf("sigma_a = %.1f   curvature at the pair = %+.6f   %s\n",
              sa, d2, if (d2 > 0) "branches again" else "stable"))
}
