# Basins of attraction and the separatrix
# https://tidyecology.com/posts/basins-of-attraction/
#
# 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 ----
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
winner <- function(N10, N20, a12, a21, Tn = 300, dt = 0.1) {
  N1 <- N10; N2 <- N20
  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 (N1 > N2) 1 else 2
}
grid <- expand.grid(N1 = seq(2, 98, 3), N2 = seq(2, 98, 3))
sym  <- apply(grid, 1, function(x) winner(x[1], x[2], 1.5, 1.5))
asy  <- apply(grid, 1, function(x) winner(x[1], x[2], 1.3, 1.8))   # sp1 the stronger suppressor
frac_sym <- mean(sym == 1); frac_asy <- mean(asy == 1)
Nstar_asy <- c(N1 = K1*(1 - 1.3) / (1 - 1.3*1.8), N2 = K2*(1 - 1.8) / (1 - 1.3*1.8))

## ---- basins ----
r1 <- r2 <- 0.5; K1 <- K2 <- 100
winner <- function(N10, N20, a12, a21, Tn = 300, dt = 0.1) {
  N1 <- N10; N2 <- N20
  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 (N1 > N2) 1 else 2
}
# fraction of a symmetric grid that ends with species 1
mean(apply(expand.grid(N1 = seq(2, 98, 3), N2 = seq(2, 98, 3)), 1,
           function(x) winner(x[1], x[2], 1.5, 1.5)) == 1)

## ---- fig-basin ----
dg <- cbind(grid, winner = factor(sym, labels = c("species 1 wins", "species 2 wins")))
p_basin <- ggplot(dg, aes(N1, N2, colour = winner)) +
  geom_point(size = 1.7) +
  geom_abline(slope = 1, intercept = 0, colour = col_ref, linetype = "dashed") +
  scale_colour_manual(values = c("species 1 wins" = col_1, "species 2 wins" = col_2)) +
  labs(x = "Starting abundance of species 1", y = "Starting abundance of species 2", colour = NULL,
       title = "The separatrix divides the plane in two")
p_basin

## ---- thumb ----
ggsave("thumbnail.png",
  p_basin +
    labs(title = paste(strwrap("Starting abundances split by the separatrix", 46), collapse = "\n")) +
    theme(plot.title = element_text(size = 13, face = "bold"),
          plot.subtitle = element_text(size = 9.5),
          plot.margin = ggplot2::margin(8, 14, 8, 8)),
  width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")

## ---- asymmetric ----
# species 1 suppresses species 2 strongly (a21 = 1.8), species 2 suppresses species 1 weakly (a12 = 1.3)
frac1 <- mean(apply(expand.grid(N1 = seq(2, 98, 3), N2 = seq(2, 98, 3)), 1,
                    function(x) winner(x[1], x[2], 1.3, 1.8)) == 1)
round(frac1, 2)

## ---- fig-asym ----
da <- cbind(grid, winner = factor(asy, labels = c("species 1 wins", "species 2 wins")))
ggplot(da, aes(N1, N2, colour = winner)) +
  geom_point(size = 1.7) +
  scale_colour_manual(values = c("species 1 wins" = col_1, "species 2 wins" = col_2)) +
  labs(x = "Starting abundance of species 1", y = "Starting abundance of species 2", colour = NULL,
       title = "The stronger competitor gets the larger basin")
