# Fertility control versus culling in R
# https://tidyecology.com/posts/fertility-control-versus-culling/
#
# 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-01

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- design ----
lam_max  <- 1.5     # adult survival + recruits per female, uncrowded
k_cap    <- 1000    # untreated equilibrium, females
h_crit   <- 1 - 1 / lam_max
half_pop <- k_cap / 2
s_show   <- c(0.60, 0.75, 0.85, 0.95)

demog <- function(s_a) {
  r0 <- lam_max - s_a
  list(r0 = r0, cc = (r0 / (1 - s_a) - 1) / k_cap)
}

# lever: "cull", "sterile" (permanent) or "season" (one breeding season)
project <- function(s_a, h, n_year, lever = "cull", sterile_in_dd = TRUE,
                    bonus = 0, demographic = FALSE) {
  n_cell <- max(length(s_a), length(h))
  s_a <- rep_len(s_a, n_cell); h <- rep_len(h, n_cell)
  dm    <- demog(s_a)
  s_st  <- s_a + bonus
  pre_f <- rep(k_cap, n_cell); ster <- rep(0, n_cell); done <- rep(0, n_cell)
  pop <- fert <- hand <- matrix(NA_real_, n_cell, n_year)
  for (yr in seq_len(n_year)) {
    treated  <- if (demographic) rbinom(n_cell, pre_f, h) else h * pre_f
    done     <- done + treated
    fert_now <- pre_f - treated
    ster <- switch(lever, cull = 0, season = treated, sterile = ster + treated)
    pop[, yr] <- fert_now + ster; fert[, yr] <- fert_now; hand[, yr] <- done
    dens   <- fert_now + if (sterile_in_dd) ster else 0
    mu_rec <- dm$r0 * fert_now / (1 + dm$cc * dens)
    if (demographic) {
      live_f   <- rbinom(n_cell, fert_now, s_a)
      live_s   <- rbinom(n_cell, ster, s_st)
      recruits <- rpois(n_cell, mu_rec)
    } else {
      live_f <- s_a * fert_now; live_s <- s_st * ster; recruits <- mu_rec
    }
    if (lever == "season") {
      pre_f <- live_f + live_s + recruits; ster <- 0
    } else {
      pre_f <- live_f + recruits; ster <- live_s
    }
  }
  list(pop = pop, fert = fert, hand = hand)
}

first_below <- function(pop_mat, level = half_pop) {
  apply(pop_mat, 1, function(v) {
    w <- which(v <= level)
    if (length(w)) w[1] else NA_integer_
  })
}

## ---- identity ----
p_star <- function(s_a, h) {
  dm <- demog(s_a)
  pmax((dm$r0 / (1 / (1 - h) - s_a) - 1) / dm$cc, 0)
}
f_star <- function(s_a, h, s_st = s_a) p_star(s_a, h) / (1 + h / ((1 - h) * (1 - s_st)))

grid_id  <- expand.grid(s_a = seq(0.50, 0.95, by = 0.05), h = seq(0.05, 0.30, by = 0.05))
n_long   <- 3000
long_cul <- project(grid_id$s_a, grid_id$h, n_long, "cull")$pop[, n_long]
long_ste <- project(grid_id$s_a, grid_id$h, n_long, "sterile")$pop[, n_long]
closed   <- p_star(grid_id$s_a, grid_id$h)
gap_cul  <- max(abs(long_cul - closed))
gap_ste  <- max(abs(long_ste - closed))
n_id     <- nrow(grid_id)

fert_share <- f_star(s_show, 0.2) / p_star(s_show, 0.2)

## ---- fp-guard-1 ----
stopifnot(gap_cul < 1e-8, gap_ste < 1e-8)

## ---- trajectories ----
n_show <- 40
traj_c <- project(s_show, 0.2, n_show, "cull")
traj_s <- project(s_show, 0.2, n_show, "sterile")
t50_c  <- first_below(traj_c$pop)
t50_s  <- first_below(traj_s$pop)
y10_c3 <- project(s_show, 0.3, 10, "cull")$pop[, 10]
y10_s3 <- project(s_show, 0.3, 10, "sterile")$pop[, 10]
eq_02  <- p_star(s_show, 0.2)
min_s85 <- min(traj_s$pop[3, ])
yr_min_s85 <- which.min(traj_s$pop[3, ])

## ---- fig-trajectories ----
traj_df <- rbind(
  data.frame(year = rep(seq_len(n_show), each = 4), s_a = rep(s_show, n_show),
             pop = as.vector(traj_c$pop), lever = "culling"),
  data.frame(year = rep(seq_len(n_show), each = 4), s_a = rep(s_show, n_show),
             pop = as.vector(traj_s$pop), lever = "sterilisation"))
traj_df$panel <- factor(sprintf("adult survival %.2f", traj_df$s_a))
eq_df <- data.frame(panel = factor(sprintf("adult survival %.2f", s_show)), eq = eq_02)

ggplot(traj_df, aes(year, pop, colour = lever)) +
  geom_hline(data = eq_df, aes(yintercept = eq), linetype = "dashed",
             colour = te_gold, linewidth = 0.7) +
  geom_hline(yintercept = half_pop, linetype = "dotted", colour = te_body,
             linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  facet_wrap(~ panel, nrow = 2) +
  scale_colour_manual(values = c(culling = te_rust, sterilisation = te_forest),
                      name = NULL) +
  scale_y_continuous(limits = c(0, k_cap)) +
  labs(x = "year of treatment", y = "females at the census",
       title = "Same destination, different arrival",
       subtitle = "treatment rate 0.2; census straight after treatment") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink))

## ---- lagmap ----
map_grid <- expand.grid(s_a = seq(0.50, 0.95, by = 0.01), h = seq(0.02, 0.50, by = 0.01))
n_map    <- 150
map_grid$t_cull <- first_below(project(map_grid$s_a, map_grid$h, n_map, "cull")$pop)
map_grid$t_ster <- first_below(project(map_grid$s_a, map_grid$h, n_map, "sterile")$pop)
map_grid$lag    <- map_grid$t_ster - map_grid$t_cull
map_grid$eq     <- p_star(map_grid$s_a, map_grid$h)

reach    <- !is.na(map_grid$lag)
n_reach  <- sum(reach)
n_cells  <- nrow(map_grid)
n_nonpos <- sum(map_grid$lag[reach] <= 0)
eq_nonpos_min <- min(map_grid$eq[reach & map_grid$lag <= 0])
lag_max  <- max(map_grid$lag[reach])
at_max   <- map_grid[reach & map_grid$lag == lag_max, ][1, ]
lag_hi_crit <- map_grid$lag[reach & abs(map_grid$s_a - 0.95) < 1e-9 & abs(map_grid$h - 0.30) < 1e-9]
lag_lo_crit <- map_grid$lag[reach & abs(map_grid$s_a - 0.60) < 1e-9 & abs(map_grid$h - 0.30) < 1e-9]
row_95   <- map_grid$lag[reach & abs(map_grid$s_a - 0.95) < 1e-9]
row_60   <- map_grid$lag[reach & abs(map_grid$s_a - 0.60) < 1e-9]
miss      <- !reach
n_miss_eq <- sum(miss & map_grid$eq > half_pop + 1e-6 & is.na(map_grid$t_ster))
n_only_s  <- sum(miss & is.na(map_grid$t_cull) & !is.na(map_grid$t_ster))
n_on_line <- sum(miss & abs(map_grid$eq - half_pop) < 1e-6)
n_tie     <- sum(map_grid$lag[reach] == 0)

# the same four life histories with the treatment rate chosen so that the
# shared equilibrium is 200 females in every case
h_match <- sapply(s_show, function(s_val)
  uniroot(function(h) p_star(s_val, h) - 200, c(1e-4, h_crit - 1e-6), tol = 1e-10)$root)
lag_match <- first_below(project(s_show, h_match, 300, "sterile")$pop) -
  first_below(project(s_show, h_match, 300, "cull")$pop)

## ---- fig-lagmap ----
ggplot(map_grid, aes(s_a, h, fill = lag)) +
  geom_raster() +
  geom_hline(yintercept = h_crit, linetype = "dashed", colour = te_ink,
             linewidth = 0.6) +
  scale_fill_gradient(low = te_gold, high = te_forest, na.value = te_line,
                      name = "lag, years") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  labs(x = "adult survival", y = "annual treatment rate",
       title = "The lag grows with survival",
       subtitle = "years to a 50 per cent reduction, sterilisation minus culling") +
  theme_datasheet() +
  theme(legend.position = "right")

## ---- handling ----
n_hand <- 40
hand_c <- project(s_show, 0.2, n_hand, "cull")$hand
hand_s <- project(s_show, 0.2, n_hand, "sterile")$hand
to_half_c <- hand_c[cbind(1:4, t50_c)]
to_half_s <- hand_s[cbind(1:4, t50_s)]
yearly_c <- t(apply(hand_c, 1, diff))
yearly_s <- t(apply(hand_s, 1, diff))
n_less   <- sum(yearly_s < yearly_c)
n_pairs  <- length(yearly_c)

annual_c <- 0.2 * eq_02 / (1 - 0.2)
annual_s <- 0.2 * f_star(s_show, 0.2) / (1 - 0.2)

## ---- fig-handling ----
keep <- c(1, 4)
hand_df <- rbind(
  data.frame(year = rep(seq_len(n_hand), each = 2), s_a = rep(s_show[keep], n_hand),
             handled = as.vector(hand_c[keep, ]), lever = "culling"),
  data.frame(year = rep(seq_len(n_hand), each = 2), s_a = rep(s_show[keep], n_hand),
             handled = as.vector(hand_s[keep, ]), lever = "sterilisation"))
hand_df$panel <- factor(sprintf("adult survival %.2f", hand_df$s_a))
mark_df <- data.frame(
  year = c(t50_c[keep], t50_s[keep]),
  handled = c(to_half_c[keep], to_half_s[keep]),
  lever = rep(c("culling", "sterilisation"), each = 2),
  panel = factor(sprintf("adult survival %.2f", rep(s_show[keep], 2))))

ggplot(hand_df, aes(year, handled, colour = lever)) +
  geom_line(linewidth = 0.9) +
  geom_point(data = mark_df, size = 2.6) +
  facet_wrap(~ panel) +
  scale_colour_manual(values = c(culling = te_rust, sterilisation = te_forest),
                      name = NULL) +
  labs(x = "year of treatment", y = "females handled, cumulative",
       title = "Fewer a year, more to the target",
       subtitle = "treatment rate 0.2; points: the year of a 50 per cent reduction") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink))

## ---- census ----
pre_ratio <- 1 / (1 - 0.2)
pre_cull_85 <- eq_02[3] * pre_ratio

# counted before treatment: the culled count is pop / (1 - h), the sterile count
# does not change because treatment moves animals between classes
t50_c_pre <- first_below(traj_c$pop / (1 - 0.2))
lag_pre   <- t50_s - t50_c_pre
lag_post  <- t50_s - t50_c

## ---- demographic ----
n_run  <- 300
n_dem  <- 60
set.seed(20904)
dem_rows <- list()
for (h_val in c(0.2, 0.3)) for (s_val in s_show) for (lv in c("cull", "sterile")) {
  sim <- project(s_val, rep(h_val, n_run), n_dem, lv, demographic = TRUE)
  t50 <- first_below(sim$pop)
  dem_rows[[length(dem_rows) + 1]] <- data.frame(
    h = h_val, s_a = s_val, lever = ifelse(lv == "cull", "culling", "sterilisation"),
    t50_med = median(t50, na.rm = TRUE),
    t50_lo  = unname(quantile(t50, 0.05, na.rm = TRUE)),
    t50_hi  = unname(quantile(t50, 0.95, na.rm = TRUE)),
    n_miss  = sum(is.na(t50)),
    below10 = mean(apply(sim$pop, 1, min) < 10),
    no_fert = mean(sim$fert[, n_dem] == 0),
    pop_end = median(sim$pop[, n_dem]))
}
dem <- do.call(rbind, dem_rows)
dem$no_fert_se <- sqrt(dem$no_fert * (1 - dem$no_fert) / n_run)
pick <- function(h_val, s_val, lv, col) dem[dem$h == h_val & abs(dem$s_a - s_val) < 1e-9 & dem$lever == lv, col]
f_eq_95 <- f_star(0.95, 0.2)
f_eq_85_3 <- f_star(0.85, 0.3)
lost_rows <- dem[dem$lever == "sterilisation" & dem$no_fert > 0.05, ]
eq_lost_max <- max(p_star(lost_rows$s_a, lost_rows$h))
n_lost <- nrow(lost_rows)
n_cull_lost <- sum(dem$lever == "culling" & dem$no_fert > 0.05)
red_lost <- 1 - eq_lost_max / k_cap

# deterministic fertile trough under sterilisation, over the same 60 years
det_f95  <- project(0.95, 0.2, n_dem, "sterile")$fert[1, ]
det_f853 <- project(0.85, 0.3, n_dem, "sterile")$fert[1, ]
min_f95 <- min(det_f95); yr_f95 <- which.min(det_f95)
min_f853 <- min(det_f853); yr_f853 <- which.min(det_f853)

## ---- fig-demographic ----
dem02 <- dem[dem$h == 0.2, ]
p_time <- ggplot(dem02, aes(s_a, t50_med, colour = lever)) +
  geom_errorbar(aes(ymin = t50_lo, ymax = t50_hi), width = 0.015, linewidth = 0.6) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = c(culling = te_rust, sterilisation = te_forest),
                      name = NULL) +
  scale_x_continuous(breaks = s_show) +
  labs(x = "adult survival", y = "year of 50 per cent reduction",
       title = "Timing") +
  theme_datasheet() +
  theme(legend.position = "none")
dem$rate <- factor(sprintf("rate %.1f", dem$h))
p_fert <- ggplot(dem, aes(s_a, no_fert, colour = lever, linetype = rate)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2) +
  scale_colour_manual(values = c(culling = te_rust, sterilisation = te_forest),
                      name = NULL) +
  scale_linetype_manual(values = c("dashed", "solid"), name = NULL) +
  scale_x_continuous(breaks = s_show) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "adult survival", y = "share of runs, no fertile female",
       title = "Breeding core lost by year 60") +
  guides(colour = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")
(p_time | p_fert) +
  plot_annotation(theme = theme_datasheet())

## ---- variants ----
s_v <- 0.85; h_v <- 0.2; n_v <- 2000
dm_v <- demog(s_v); bonus_v <- 0.05
runs_v <- list(
  culling        = project(s_v, h_v, n_v, "cull"),
  sterilisation  = project(s_v, h_v, n_v, "sterile"),
  outside        = project(s_v, h_v, n_v, "sterile", sterile_in_dd = FALSE),
  bonus          = project(s_v, h_v, n_v, "sterile", bonus = bonus_v),
  season         = project(s_v, h_v, n_v, "season"))
end_v   <- sapply(runs_v, function(x) x$pop[n_v])
t50_v   <- sapply(runs_v, function(x) first_below(x$pop))
yr_v    <- sapply(runs_v, function(x) x$hand[n_v] - x$hand[n_v - 1])

closed_v <- c(
  culling       = p_star(s_v, h_v),
  sterilisation = p_star(s_v, h_v),
  outside       = p_star(s_v, h_v) * (1 + h_v / ((1 - h_v) * (1 - s_v))),
  bonus         = p_star(s_v, h_v),
  season        = (dm_v$r0 * (1 - h_v) / (1 - s_v) - 1) / dm_v$cc)
gap_v    <- max(abs(end_v - closed_v))
h_season <- 1 - (1 - s_v) / dm_v$r0
fert_bonus <- runs_v$bonus$fert[n_v]
fert_base  <- runs_v$sterilisation$fert[n_v]

## ---- fp-guard-2 ----
stopifnot(gap_v < 1e-8)

## ---- fig-variants ----
n_vs <- 60
lab_v <- c(culling = "culling", sterilisation = "sterilisation",
           outside = "sterile animals outside density feedback",
           bonus = "sterile females survive 0.05 better",
           season = "contraceptive lasts one season")
var_df <- do.call(rbind, lapply(names(runs_v), function(nm)
  data.frame(year = seq_len(n_vs), pop = runs_v[[nm]]$pop[1, seq_len(n_vs)],
             version = lab_v[[nm]])))
var_df$version <- factor(var_df$version, levels = unname(lab_v))

ggplot(var_df, aes(year, pop, colour = version, linetype = version)) +
  geom_hline(yintercept = half_pop, linetype = "dotted", colour = te_body,
             linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(te_rust, te_forest, te_gold, te_forest, te_ink),
                      name = NULL) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "dashed", "solid"),
                        name = NULL) +
  scale_y_continuous(limits = c(0, k_cap)) +
  labs(x = "year of treatment", y = "females at the census",
       title = "Slower or different",
       subtitle = "adult survival 0.85, treatment rate 0.2") +
  guides(colour = guide_legend(ncol = 2), linetype = guide_legend(ncol = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")
