# Priority effects and alternative stable states
# https://tidyecology.com/posts/priority-effects-and-alternative-states/
#
# 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-11-15

## ---- 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_1 <- "#3a6b52"; col_2 <- "#b5651d"; col_ref <- "#555555"

r1 <- r2 <- 0.5; K1 <- K2 <- 100; a12 <- a21 <- 1.5   # interspecific > intraspecific: founder control
lv <- function(N10, N20, Tn = 200, dt = 0.1) {
  N1 <- N10; N2 <- N20; out <- data.frame(t = 0, N1 = N1, N2 = N2)
  for (t in 1:(Tn/dt)) {
    dN1 <- r1*N1*(1 - (N1 + a12*N2)/K1); dN2 <- r2*N2*(1 - (N2 + a21*N1)/K2)
    N1 <- max(N1 + dN1*dt, 0); N2 <- max(N2 + dN2*dt, 0)
    if (t %% 5 == 0) out <- rbind(out, data.frame(t = t*dt, N1 = N1, N2 = N2))
  }
  out
}
end_state <- function(a, b) { z <- lv(a, b); c(N1 = tail(z$N1, 1), N2 = tail(z$N2, 1)) }
Nstar <- K1/(1 + a12)
e_ab <- end_state(60, 40); e_ba <- end_state(40, 60)

## ---- founder ----
r1 <- r2 <- 0.5; K1 <- K2 <- 100; a12 <- a21 <- 1.5   # each hurts the other more than itself
step <- function(N, dt = 0.1) {
  dN1 <- r1*N[1]*(1 - (N[1] + a12*N[2])/K1); dN2 <- r2*N[2]*(1 - (N[2] + a21*N[1])/K2)
  pmax(N + c(dN1, dN2)*dt, 0)
}
run <- function(N) { for (t in 1:2000) N <- step(N); round(N) }
rbind(species1_ahead = run(c(60, 40)), species2_ahead = run(c(40, 60)))

## ---- fig-traj ----
d <- rbind(cbind(lv(60, 40), case = "species 1 starts ahead"),
           cbind(lv(40, 60), case = "species 2 starts ahead"))
dl <- reshape(d, varying = c("N1", "N2"), v.names = "N", timevar = "sp", direction = "long")
ggplot(dl, aes(t, N, colour = factor(sp))) +
  geom_line(linewidth = 0.9) + facet_wrap(~case) +
  scale_colour_manual(values = c("1" = col_1, "2" = col_2), labels = c("species 1", "species 2")) +
  labs(x = "Time", y = "Abundance", colour = NULL,
       title = "Who arrives first wins") +
  theme(strip.text = element_text(size = 9))

## ---- fig-isocline ----
N1 <- seq(0, 100, 1)
iso <- rbind(data.frame(N1 = N1, N2 = (K1 - N1)/a12, sp = "species 1 isocline"),
             data.frame(N1 = N1, N2 = K2 - a21*N1,   sp = "species 2 isocline"))
iso <- iso[iso$N2 >= 0 & iso$N2 <= 100, ]
eq <- data.frame(N1 = c(100, 0, Nstar), N2 = c(0, 100, Nstar),
                 kind = c("stable", "stable", "unstable"))
ggplot(iso, aes(N1, N2, colour = sp)) +
  geom_abline(slope = 1, intercept = 0, colour = col_ref, linetype = "dashed") +
  geom_line(linewidth = 1) +
  geom_point(data = eq, aes(N1, N2, shape = kind), colour = col_ref, size = 3, inherit.aes = FALSE) +
  scale_shape_manual(values = c(stable = 16, unstable = 1)) +
  scale_colour_manual(values = c("species 1 isocline" = col_1, "species 2 isocline" = col_2)) +
  guides(colour = guide_legend(order = 1), shape = guide_legend(order = 2)) +
  labs(x = "Species 1 abundance", y = "Species 2 abundance", colour = NULL, shape = NULL,
       title = "Two stable corners, one unstable crossing")
