# Source-sink population dynamics
# https://tidyecology.com/posts/source-sink-dynamics/
#
# 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-07

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

lam <- function(PA, PJ, b) PA + PJ * b
l1 <- lam(0.6, 0.3, 3.0)   # source
l2 <- lam(0.6, 0.3, 0.8)   # sink
n1 <- 100
n2_eq <- n1 * (l1 - 1) / (1 - l2)
years <- 40; surplus <- n1 * (l1 - 1)
Na <- numeric(years+1); Ns <- numeric(years+1); Na[1] <- Ns[1] <- 80
for (t in 2:(years+1)) { Na[t] <- Na[t-1]*l2; Ns[t] <- Ns[t-1]*l2 + surplus }

## ---- lambda ----
lam <- function(PA, PJ, b) PA + PJ * b   # adult survival + juvenile survival * fecundity
c(source = lam(0.6, 0.3, 3.0), sink = lam(0.6, 0.3, 0.8))

## ---- dynamics ----
l2 <- lam(0.6, 0.3, 0.8); surplus <- 100 * (lam(0.6, 0.3, 3.0) - 1)
sink_alone <- Reduce(function(N, .) N * l2,             1:40, accumulate = TRUE, 80)
sink_subs  <- Reduce(function(N, .) N * l2 + surplus,   1:40, accumulate = TRUE, 80)
c(alone_final = tail(sink_alone, 1), subsidised_final = tail(sink_subs, 1))

## ---- fig-dynamics ----
d <- rbind(data.frame(t = 0:years, N = Na, kind = "isolated sink"),
           data.frame(t = 0:years, N = Ns, kind = "sink with source subsidy"))
ggplot(d, aes(t, N, colour = kind)) +
  geom_hline(yintercept = n2_eq, colour = col_ref, linetype = "dotted") +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("isolated sink" = col_alone, "sink with source subsidy" = col_sub)) +
  labs(x = "Year", y = "Sink population size", colour = NULL,
       title = "The sink persists only on the source's surplus")

## ---- fig-equilibrium ----
l2g <- seq(0.3, 0.97, 0.01)
de <- data.frame(l2 = l2g, n2 = surplus / (1 - l2g))
ggplot(de, aes(l2, n2)) +
  geom_line(colour = col_sub, linewidth = 1) +
  geom_hline(yintercept = n1, colour = col_ref, linetype = "dotted") +
  annotate("text", x = 0.32, y = n1, label = "source size", hjust = 0, vjust = -0.6, colour = col_ref, size = 3.4) +
  labs(x = "Sink's own local growth rate", y = "Equilibrium sink size",
       title = "A shallow sink holds a large subsidised population")
