# Checking an Allee analysis
# https://tidyecology.com/posts/checking-an-allee-analysis/
#
# 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_lo <- "#b5651d"; col_hi <- "#3a6b52"; col_ref <- "#555555"

r <- 0.5; K <- 100; A <- 30
pgr <- function(N) r*(1 - N/K)*(N/A - 1)
set.seed(4021)
Nobs <- runif(80, 5, 100); pc <- pgr(Nobs) + rnorm(80, 0, 0.07)
fit_hi <- lm(pc ~ Nobs, subset = Nobs > 40); fit_lo <- lm(pc ~ Nobs, subset = Nobs < A)
sl_hi <- coef(fit_hi)[2]; sl_lo <- coef(fit_lo)[2]
p_hi <- summary(fit_hi)$coefficients[2, 4]; p_lo <- summary(fit_lo)$coefficients[2, 4]

## measurement error fakes density dependence
set.seed(402)
Tn <- 200; Ntrue <- numeric(Tn); Ntrue[1] <- 60
for (t in 2:Tn) Ntrue[t] <- Ntrue[t-1]*exp(rnorm(1, 0, 0.10))   # density-INDEPENDENT truth
obs <- Ntrue*exp(rnorm(Tn, 0, 0.25))
sl_true <- coef(lm(diff(log(Ntrue)) ~ Ntrue[-Tn]))[2]
sl_err  <- coef(lm(diff(log(obs))  ~ obs[-Tn]))[2]

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- detection ----
r <- 0.5; K <- 100; A <- 30
pgr <- function(N) r*(1 - N/K)*(N/A - 1)              # the true dynamics have a strong Allee effect
Ng <- seq(40, 100, by = 0.5); sl_model <- coef(lm(pgr(Ng) ~ Ng))[2]   # straight line through the true curve above 40
rbind(high_density = c(slope = unname(sl_hi), p = unname(p_hi)),
      low_density  = c(slope = unname(sl_lo), p = unname(p_lo)))

## ---- fig-detect ----
dd <- data.frame(N = Nobs, pc = pc, band = ifelse(Nobs < A, "low density", "high density"))
ggplot(dd, aes(N, pc)) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.3) +
  geom_point(aes(colour = band), size = 2, alpha = 0.7) +
  geom_smooth(data = subset(dd, N < A), method = "lm", se = FALSE, colour = col_lo, linewidth = 0.9) +
  geom_smooth(data = subset(dd, N > 40), method = "lm", se = FALSE, colour = col_hi, linewidth = 0.9) +
  scale_colour_manual(values = c("low density" = col_lo, "high density" = col_hi)) +
  labs(x = "Population density", y = "Per-capita growth rate", colour = NULL,
       title = "The Allee effect is clearest where data are scarce")

## ---- regmean ----
set.seed(402)
Ntrue <- 60; for (t in 2:200) Ntrue[t] <- Ntrue[t-1]*exp(rnorm(1, 0, 0.10))  # NO density dependence
obs <- Ntrue*exp(rnorm(200, 0, 0.25))                                        # counts with 25% error
c(slope_true_N = unname(sl_true), slope_observed_N = unname(sl_err))

## ---- fig-regmean ----
dr <- data.frame(N = obs[-200], g = diff(log(obs)))
ggplot(dr, aes(N, g)) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.3) +
  geom_point(colour = col_ref, size = 1.6, alpha = 0.5) +
  geom_smooth(method = "lm", se = FALSE, colour = col_lo, linewidth = 1) +
  labs(x = "Observed density", y = "Per-capita growth rate",
       title = "Measurement error alone makes density dependence appear")
