# Allee effects and thresholds in R
# https://tidyecology.com/posts/allee-effects-and-thresholds/
#
# 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_strong <- "#b5651d"; col_weak <- "#3a6b52"; col_log <- "#8aa29e"; col_ref <- "#555555"

r <- 0.5; K <- 100; A <- 30
g_strong <- function(N) r*(1 - N/K)*(N/A - 1)
g_weak   <- function(N) r*(1 - N/K)*(N/(N + 12))
g_log    <- function(N) r*(1 - N/K)

## deterministic trajectory (Euler)
traj <- function(N0, g, tmax = 60, dt = 0.05) {
  N <- N0; out <- numeric(tmax/dt + 1); out[1] <- N0
  for (i in 2:length(out)) { N <- max(N + N*g(N)*dt, 0); out[i] <- N }
  data.frame(t = seq(0, tmax, dt), N = out)
}
end_state <- sapply(c(25, 31, 60), function(N0) tail(traj(N0, g_strong)$N, 1))

## ---- curves ----
r <- 0.5; K <- 100; A <- 30
g_log    <- function(N) r*(1 - N/K)                 # logistic: crowding only
g_weak   <- function(N) r*(1 - N/K)*(N/(N + 12))    # weak Allee: reduced but positive
g_strong <- function(N) r*(1 - N/K)*(N/A - 1)       # strong Allee: negative below A
sapply(list(logistic = g_log, weak = g_weak, strong = g_strong), function(f) f(10))

## ---- fig-percap ----
Ng <- seq(0, 100, 0.5)
d <- rbind(data.frame(N = Ng, g = g_log(Ng),    type = "logistic"),
           data.frame(N = Ng, g = g_weak(Ng),   type = "weak Allee"),
           data.frame(N = Ng, g = g_strong(Ng), type = "strong Allee"))
ggplot(d, aes(N, g, colour = type)) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.4) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = A, colour = col_strong, linetype = "dashed") +
  annotate("text", x = A + 1.5, y = -0.28, label = "critical density A", hjust = 0, colour = col_strong, size = 3.4) +
  scale_colour_manual(values = c("logistic" = col_log, "weak Allee" = col_weak, "strong Allee" = col_strong)) +
  labs(x = "Population density", y = "Per-capita growth rate", colour = NULL,
       title = "An Allee effect is positive density dependence at low density")

## ---- trajectories ----
traj <- function(N0, g, tmax = 60, dt = 0.05) {
  N <- N0; out <- numeric(tmax/dt + 1); out[1] <- N0
  for (i in 2:length(out)) { N <- max(N + N*g(N)*dt, 0); out[i] <- N }
  data.frame(t = seq(0, tmax, dt), N = out)
}
sapply(c(25, 31), function(N0) round(tail(traj(N0, g_strong)$N, 1), 1))

## ---- fig-traj ----
runs <- do.call(rbind, lapply(c(15, 25, 29, 31, 45, 80), function(N0) {
  tr <- traj(N0, g_strong); tr$N0 <- factor(N0); tr }))
ggplot(runs, aes(t, N, group = N0, colour = N < 1 | N0 %in% c("15","25","29"))) +
  geom_hline(yintercept = A, colour = col_ref, linetype = "dashed") +
  geom_line(linewidth = 0.9) +
  annotate("text", x = 40, y = A + 4, label = "critical density", hjust = 0, colour = col_ref, size = 3.4) +
  scale_colour_manual(values = c("FALSE" = col_weak, "TRUE" = col_strong), guide = "none") +
  labs(x = "Time", y = "Population size", title = "The critical density decides extinction or recovery")
