# Janzen-Connell and tree diversity
# https://tidyecology.com/posts/janzen-connell-and-diversity/
#
# 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 ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_no <- "#b5651d"; col_cndd <- "#3a6b52"; col_ref <- "#555555"

simcomm <- function(cndd, S = 8, T = 400, seed = 415) {
  set.seed(seed); f <- rep(1/S, S); fit <- runif(S, 0.9, 1.1)
  for (t in 1:T) { w <- fit * f * exp(-cndd * f); f <- w / sum(w) }
  f
}
shannon <- function(f) { f <- f[f > 0]; -sum(f * log(f)) }
f_no <- simcomm(0); f_cndd <- simcomm(6)
S_no <- sum(f_no > 0.005); S_cndd <- sum(f_cndd > 0.005)
H_no <- shannon(f_no); H_cndd <- shannon(f_cndd); Hmax <- log(8)

## ---- community ----
simcomm <- function(cndd, S = 8, T = 400, seed = 415) {
  set.seed(seed); f <- rep(1/S, S); fit <- runif(S, 0.9, 1.1)   # small fitness differences
  for (t in 1:T) {
    w <- fit * f * exp(-cndd * f)          # enemies cut recruitment where a species is common
    f <- w / sum(w)
  }
  f
}
round(rbind(no_enemies = simcomm(0), with_enemies = simcomm(6)), 3)

## ---- diversity ----
shannon <- function(f) { f <- f[f > 0]; -sum(f * log(f)) }
c(species_no_enemies = sum(simcomm(0) > 0.005), shannon_no_enemies = shannon(simcomm(0)),
  species_with_enemies = sum(simcomm(6) > 0.005), shannon_with_enemies = shannon(simcomm(6)))

## ---- fig-diversity ----
d <- rbind(data.frame(sp = factor(1:8), f = f_no,   rule = "no enemies"),
           data.frame(sp = factor(1:8), f = f_cndd, rule = "with specialised enemies"))
ggplot(d, aes(sp, f, fill = rule)) +
  geom_col(position = "dodge", width = 0.7) +
  scale_fill_manual(values = c("no enemies" = col_no, "with specialised enemies" = col_cndd)) +
  labs(x = "Species", y = "Relative abundance", fill = NULL,
       title = "Specialised enemies turn exclusion into coexistence")

## ---- fig-gradient ----
cg <- data.frame(cndd = seq(0, 10, 0.25))
cg$H <- sapply(cg$cndd, function(c) shannon(simcomm(c)))
ggplot(cg, aes(cndd, H)) +
  geom_hline(yintercept = Hmax, colour = col_ref, linetype = "dotted") +
  geom_line(colour = col_cndd, linewidth = 1) +
  annotate("text", x = 3, y = Hmax - 0.12, label = "maximum for the species pool", hjust = 0, colour = col_ref, size = 3.4) +
  labs(x = "Strength of enemy density dependence", y = "Shannon diversity",
       title = "Stronger density dependence, more coexisting species")

## ---- escape ----
set.seed(703)
seed_decay  <- 0.1     # seed fall decays at this rate per metre
enemy_decay <- 0.2     # enemy pressure fades at this rate per metre
seedfall <- function(r, sd_) exp(-sd_ * r)
survival <- function(r, ed_, m) 1 - m * exp(-ed_ * r)
recruits <- function(r, sd_, ed_, m) seedfall(r, sd_) * survival(r, ed_, m)

m_star <- seed_decay / (seed_decay + enemy_decay)      # the escape threshold
peak_at <- function(m, sd_ = seed_decay, ed_ = enemy_decay) {
  g <- seq(0, 300, by = 1e-4); g[which.max(recruits(g, sd_, ed_, m))]
}
m_low   <- 0.20                                        # below the threshold
m_high  <- 0.90                                        # well above it
m_grid  <- c(m_low, 0.30, m_star, 0.40, 0.60, m_high)
esc_tab <- data.frame(
  m                = m_grid,
  peak_measured    = sapply(m_grid, peak_at),
  peak_closed_form = pmax(0, log(m_grid * (seed_decay + enemy_decay) / seed_decay) / enemy_decay))
esc_tab$survival_at_peak <- survival(esc_tab$peak_measured, enemy_decay, m_grid)
esc_tab$escape <- ifelse(m_grid > m_star, "yes", "no")
mean_dist <- 1 / seed_decay
peak_090  <- peak_at(m_high)
surv_peak <- enemy_decay / (seed_decay + enemy_decay)
print(round(esc_tab[, 1:4], 4), row.names = FALSE)

## ---- escape-sweep ----
set.seed(704)
m_fix  <- 0.90
b_scan <- exp(seq(log(1e-3), log(100), length.out = 4000))
r_scan <- ifelse(m_fix > seed_decay / (seed_decay + b_scan),
                 log(m_fix * (seed_decay + b_scan) / seed_decay) / b_scan, 0)
b_off  <- seed_decay * (1 - m_fix) / m_fix              # below this gradient there is no escape
b_best <- b_scan[which.max(r_scan)]
r_best <- max(r_scan)

sweep <- data.frame(enemy_decay = c(0.001, 0.01, b_off, 0.02, b_best, 0.2, 1, 50))
sweep$threshold <- seed_decay / (seed_decay + sweep$enemy_decay)
sweep$escape_distance <- ifelse(
  m_fix > sweep$threshold,
  log(m_fix * (seed_decay + sweep$enemy_decay) / seed_decay) / sweep$enemy_decay, 0)
b_soft   <- sweep$enemy_decay[4]        # a gradient flatter than the seed shadow
r_soft   <- sweep$escape_distance[4]
soft_rat <- seed_decay / b_soft
off_rat  <- seed_decay / b_off
b_far <- sweep$enemy_decay[nrow(sweep)]
thr_far <- sweep$threshold[nrow(sweep)]
r_far <- sweep$escape_distance[nrow(sweep)]
print(round(sweep, 4), row.names = FALSE)

## ---- fig-escape ----
m_show <- c(m_low, m_star, m_high)
lab <- sprintf("%.2f, %s the threshold", m_show, c("below", "at", "above"))
rr <- seq(0, 40, 0.05)
d_esc <- do.call(rbind, lapply(seq_along(m_show), function(i) {
  y <- recruits(rr, seed_decay, enemy_decay, m_show[i])
  data.frame(r = rr, y = y / max(y), lab = factor(lab[i], levels = lab))
}))
ggplot(d_esc, aes(r, y, colour = lab)) +
  geom_vline(xintercept = sapply(m_show, peak_at), colour = col_ref,
             linetype = "dotted", linewidth = 0.3) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = setNames(c(col_no, col_ref, col_cndd), lab)) +
  labs(x = "Distance from the parent (metres)", y = "Recruitment, scaled to its own maximum",
       colour = "Mortality under the parent",
       title = "Recruitment leaves the parent only above the threshold")
