# Niche and fitness differences
# https://tidyecology.com/posts/niche-and-fitness-differences/
#
# 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-15

## ---- setup ----
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))

lamA <- 45; lamB <- 30                 # seeds per plant without competition
aAA <- 0.10; aBB <- 0.06               # intraspecific competition
aAB <- 0.03; aBA <- 0.06               # interspecific: B on A, and A on B
gA <- 0.60; gB <- 0.70                 # germination fractions
sA <- 0.10; sB <- 0.20                 # ungerminated-seed survival

## ---- niche ----
rho    <- sqrt((aAB * aBA) / (aAA * aBB))   # niche overlap
ndiff  <- 1 - rho                            # stabilising niche difference

## ---- niche-num ----
rho_v <- rho; nd_v <- ndiff

## ---- fitness ----
eta <- function(lam, g, s) g * lam / (1 - (1 - g) * s) - 1
etaA <- eta(lamA, gA, sA); etaB <- eta(lamB, gB, sB)
demo_ratio <- etaA / etaB                              # demographic component
comp_ratio <- sqrt((aBB * aBA) / (aAA * aAB))          # competitive-response component
fitness_ratio <- demo_ratio * comp_ratio               # kappa_A / kappa_B

## ---- fitness-num ----
fr_v <- fitness_ratio; dr_v <- demo_ratio; cr_v <- comp_ratio; upper_v <- 1 / rho

## ---- condition ----
upper <- 1 / rho
coexist <- (fitness_ratio > rho) && (fitness_ratio < upper)

## ---- fig-plane ----
nd_seq <- seq(0.001, 0.85, length.out = 200)
band <- data.frame(nd = nd_seq, lo = 1 - nd_seq, hi = 1 / (1 - nd_seq))
ggplot(band, aes(nd)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = "#275139", alpha = 0.12) +
  geom_line(aes(y = hi), colour = "#275139", linewidth = 0.8) +
  geom_line(aes(y = lo), colour = "#275139", linewidth = 0.8) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = "grey55") +
  annotate("point", x = nd_v, y = fr_v, colour = "#b5534e", size = 3) +
  annotate("text", x = nd_v, y = fr_v, label = "  A and B", hjust = 0,
           colour = "#b5534e", size = 3.6) +
  scale_y_log10() +
  labs(x = "niche difference (1 minus overlap)",
       y = "fitness ratio (log scale)") +
  theme_te

## ---- model ----
seed_step <- function(N) {
  FA <- lamA / (1 + aAA * gA * N[1] + aAB * gB * N[2])
  FB <- lamB / (1 + aBA * gA * N[1] + aBB * gB * N[2])
  c((1 - gA) * sA * N[1] + gA * N[1] * FA,
    (1 - gB) * sB * N[2] + gB * N[2] * FB)
}
run <- function(N0, tmax = 400) {
  M <- matrix(0, tmax + 1, 2); M[1, ] <- N0
  for (t in 1:tmax) M[t + 1, ] <- seed_step(M[t, ])
  M
}
Nstar <- function(lam, g, s, a) (g * lam / (1 - (1 - g) * s) - 1) / (a * g)
NAstar <- Nstar(lamA, gA, sA, aAA); NBstar <- Nstar(lamB, gB, sB, aBB)

## ---- invasion ----
ldgr_A <- log((1 - gA) * sA + gA * lamA / (1 + aAB * gB * NBstar))
ldgr_B <- log((1 - gB) * sB + gB * lamB / (1 + aBA * gA * NAstar))

## ---- invasion-num ----
la_v <- ldgr_A; lb_v <- ldgr_B

## ---- fig-invasion ----
tr <- rbind(
  data.frame(gen = 0:120, A = run(c(1, NBstar), 120)[, 1], B = run(c(1, NBstar), 120)[, 2], start = "A rare"),
  data.frame(gen = 0:120, A = run(c(NAstar, 1), 120)[, 1], B = run(c(NAstar, 1), 120)[, 2], start = "B rare"),
  data.frame(gen = 0:120, A = run(c(20, 20), 120)[, 1], B = run(c(20, 20), 120)[, 2], start = "balanced"))
long <- reshape(tr, varying = c("A", "B"), v.names = "N", timevar = "species",
                times = c("A", "B"), direction = "long")
ggplot(long, aes(gen, N, colour = species)) +
  geom_line(linewidth = 0.8) +
  facet_wrap(~ start) +
  scale_y_log10() +
  scale_colour_manual(values = c("A" = "#275139", "B" = "#b5534e")) +
  labs(x = "generation", y = "seed density (log scale)", colour = "species") +
  theme_te + theme(legend.position = "top")

## ---- eq-num ----
eqm <- run(c(20, 20), 400)[401, ]
eqA_v <- eqm[1]; eqB_v <- eqm[2]
