# Why sinks hold high density
# https://tidyecology.com/posts/sinks-can-hold-high-density/
#
# 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_source <- "#3a6b52"; col_sink <- "#b5651d"; col_ref <- "#555555"

l1 <- 1.5; l2 <- 0.84; n1 <- 100
n2 <- n1 * (l1 - 1) / (1 - l2)
ratio <- n2 / n1

set.seed(408)
imm <- 40
habitat <- data.frame(lambda = seq(0.5, 1.5, length = 25))
habitat$density <- ifelse(habitat$lambda >= 1, 80 + rnorm(25, 0, 4),
                          pmin(imm/(1 - habitat$lambda), 400))
cor_dq <- cor(habitat$lambda, habitat$density)
dens_top <- habitat$lambda[order(-habitat$density)[1:3]]

## ---- paradox ----
l1 <- 1.5; l2 <- 0.84; n1 <- 100          # source growth rate, sink growth rate, source size
surplus <- n1 * (l1 - 1)                    # emigrants the source sends each year
n2 <- surplus / (1 - l2)                    # equilibrium sink size
c(source_size = n1, sink_size = n2, ratio = n2 / n1)

## ---- fig-paradox ----
dp <- data.frame(habitat = c("source\n(grows locally)", "sink\n(shrinks locally)"),
                 N = c(n1, n2), kind = c("source", "sink"))
ggplot(dp, aes(habitat, N, fill = kind)) +
  geom_col(width = 0.6) +
  scale_fill_manual(values = c("source" = col_source, "sink" = col_sink), guide = "none") +
  labs(x = NULL, y = "Standing population", title = "The worst habitat holds the most animals")

## ---- density-quality ----
set.seed(408)
imm <- 40
habitat <- data.frame(lambda = seq(0.5, 1.5, length = 25))
habitat$density <- ifelse(habitat$lambda >= 1, 80 + rnorm(25, 0, 4),   # sources capped
                          pmin(imm/(1 - habitat$lambda), 400))          # sinks pile up near lambda = 1
c(correlation_density_quality = cor(habitat$lambda, habitat$density))

## ---- fig-density ----
habitat$kind <- ifelse(habitat$lambda >= 1, "source", "sink")
ggplot(habitat, aes(lambda, density, colour = kind)) +
  geom_vline(xintercept = 1, colour = col_ref, linetype = "dashed") +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c("source" = col_source, "sink" = col_sink)) +
  labs(x = "Local growth rate (habitat quality)", y = "Standing density", colour = NULL,
       title = "Density does not measure quality")
