# Resource competition and the R-star rule
# https://tidyecology.com/posts/r-star-and-resource-competition/
#
# 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-08

## ---- 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))
}

## ---- 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)), "}$")
}

## ---- solver ----
rk4_run <- function(f, x0, h, nstep, keep) {
  x <- x0; out <- matrix(0, floor(nstep / keep) + 1, length(x0))
  tvec <- numeric(nrow(out)); out[1, ] <- x; j <- 1
  for (i in seq_len(nstep)) {
    k1 <- f(x); k2 <- f(x + (h / 2) * k1); k3 <- f(x + (h / 2) * k2); k4 <- f(x + h * k3)
    x <- x + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
    if (i %% keep == 0) { j <- j + 1; out[j, ] <- x; tvec[j] <- i * h }
  }
  list(tvec = tvec[seq_len(j)], x = out[seq_len(j), , drop = FALSE])
}
monod <- function(res, rmax, halfk) rmax * res / (halfk + res)
rstar_of <- function(rmax, halfk, loss) halfk * loss / (rmax - loss)
dil <- 0.25; sup_one <- 50; n_start <- 0.05  # dilution, supply, inoculum
h_fine <- 0.01; h_sweep <- 0.02; h_bi <- 0.05; h_two <- 0.1  # production steps
rmax_s <- 0.55; half_s <- 3                  # slow species: rate, half saturation
rmax_f <- 1.10; half_f <- 30                 # fast species: rate, half saturation
use_s <- 1; use_f <- 1                       # resource drawn per unit of consumer
rs_slow <- rstar_of(rmax_s, half_s, dil)
rs_fast <- rstar_of(rmax_f, half_f, dil); rate_ratio <- rmax_f / rmax_s
r_cross <- (rmax_s * half_f - rmax_f * half_s) / (rmax_f - rmax_s)
mu_at_supply <- c(monod(sup_one, rmax_s, half_s), monod(sup_one, rmax_f, half_f))
one_deriv <- function(rm_fast) function(x) {
  res <- x[1]; n_s <- x[2]; n_f <- x[3]
  g_s <- monod(res, rmax_s, half_s); g_f <- monod(res, rm_fast, half_f)
  c(dil * (sup_one - res) - use_s * g_s * n_s - use_f * g_f * n_f,
    n_s * (g_s - dil), n_f * (g_f - dil))
}

## ---- integrator ----
alone_s <- rk4_run(one_deriv(rmax_f), c(sup_one, n_start, 0), h_fine, 60000, 1000)
alone_f <- rk4_run(one_deriv(rmax_f), c(sup_one, 0, n_start), h_fine, 60000, 1000)
eq_err_s <- abs(alone_s$x[nrow(alone_s$x), 1] - rs_slow)
eq_err_f <- abs(alone_f$x[nrow(alone_f$x), 1] - rs_fast)
h_conv <- c(4, 2, 1) * h_fine
conv <- lapply(h_conv, function(h)
  rk4_run(one_deriv(rmax_f), c(sup_one, n_start, n_start), h, 200 / h, 1 / h))
gap_1 <- max(abs(conv[[1]]$x[, 2] - conv[[2]]$x[, 2]))
gap_2 <- max(abs(conv[[2]]$x[, 2] - conv[[3]]$x[, 2]))
gap_ratio <- gap_1 / gap_2; order_expected <- 2^4

## ---- exclusion ----
traj_one <- rk4_run(one_deriv(rmax_f), c(sup_one, n_start, n_start), h_fine, 40000, 25)
one_dat <- data.frame(day = traj_one$tvec, res = traj_one$x[, 1],
                      slow = traj_one$x[, 2], fast = traj_one$x[, 3])
end_row <- one_dat[nrow(one_dat), ]; peak_i <- which.max(one_dat$fast)
peak_fast <- one_dat$fast[peak_i]; peak_day <- one_dat$day[peak_i]
lead_at_peak <- one_dat$fast[peak_i] / one_dat$slow[peak_i]
ext_frac <- 0.01; ext_level <- n_start * ext_frac
ext_day <- one_dat$day[which(one_dat$fast < ext_level & one_dat$day > peak_day)[1]]
sim_rstar <- end_row$res; eq_dens <- (sup_one - rs_slow) / use_s
decline_rate <- dil - monod(rs_slow, rmax_f, half_f)

## ---- fig-exclusion ----
dens_long <- data.frame(day = rep(one_dat$day, 2), dens = c(one_dat$slow, one_dat$fast),
  species = rep(c("slow, low R-star", "fast, high R-star"), each = nrow(one_dat)))
p_dens <- ggplot(dens_long, aes(day, dens, colour = species)) + geom_line(linewidth = 0.9) +
  geom_hline(yintercept = ext_level, linetype = "dashed", colour = te_body, linewidth = 0.4) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  scale_y_log10(labels = scales::label_log()) + coord_cartesian(xlim = c(0, 220), ylim = c(1e-5, 200)) +
  labs(x = "day", y = "density (log scale)", title = "Densities",
       subtitle = "dashed: one per cent of the inoculum") +
  theme_datasheet() + theme(legend.position = "bottom")
p_res <- ggplot(one_dat, aes(day, res)) + geom_line(linewidth = 0.9, colour = te_ink) +
  geom_hline(yintercept = r_cross, linetype = "dotted", colour = te_gold, linewidth = 0.7) +
  geom_hline(yintercept = rs_fast, linetype = "dashed", colour = te_rust, linewidth = 0.6) +
  geom_hline(yintercept = rs_slow, colour = te_forest, linewidth = 0.6) +
  coord_cartesian(xlim = c(0, 220)) +
  labs(x = "day", y = "resource concentration", title = "Resource",
       subtitle = "dotted: the growth curves cross") + theme_datasheet()
p_dens + p_res + plot_annotation(theme = theme_datasheet())

## ---- sweep ----
rmax_flip <- dil + half_f * dil / rs_slow
flip_ratio <- rmax_flip / rmax_s; sweep_tmax <- 600
sweep_rates <- seq(rmax_s * 1.2, rmax_s * 7, length.out = 11)
run_pair <- function(rm_fast, tmax = sweep_tmax, h = h_sweep)
  rk4_run(one_deriv(rm_fast), c(sup_one, n_start, n_start), h,
          round(tmax / h), round(1 / h))
share_slope <- function(z, lo = 400, hi = 600) {   # late trend in log(fast/slow)
  w <- which(z$tvec >= lo & z$tvec <= hi)
  as.numeric(coef(lm(log(z$x[w, 3]) - log(z$x[w, 2]) ~ z$tvec[w]))[2])
}
sweep_tab <- do.call(rbind, lapply(sweep_rates, function(rm_fast) {
  z <- run_pair(rm_fast); fin <- z$x[nrow(z$x), ]
  data.frame(rmax_fast = rm_fast, rstar_fast = rstar_of(rm_fast, half_f, dil),
             end_res = fin[1], end_slow = fin[2], end_fast = fin[3], slope = share_slope(z))
}))
sweep_tab$winner <- ifelse(sweep_tab$end_slow > sweep_tab$end_fast,
                           "slow species", "fast species")
sweep_tab$res_gap <- abs(sweep_tab$end_res - pmin(sweep_tab$rstar_fast, rs_slow))
rmax_flip_sim <- uniroot(function(rm_fast) share_slope(run_pair(rm_fast)),
                         c(rmax_s * 4, rmax_s * 8), tol = 1e-5)$root
flip_gap <- abs(rmax_flip_sim - rmax_flip) / rmax_flip
quad_row <- sweep_tab[which.min(abs(sweep_tab$rmax_fast - 4 * rmax_s)), ]
quad_vs_fast <- quad_row$rmax_fast / rmax_f; quad_vs_slow <- quad_row$rmax_fast / rmax_s
flip_vs_fast <- rmax_flip / rmax_f
worst_i <- which.max(sweep_tab$res_gap); res_worst <- sweep_tab$res_gap[worst_i]
res_rest <- max(sweep_tab$res_gap[-worst_i])
slow_slope <- abs(sweep_tab$slope[worst_i]); worst_holder <- sweep_tab$winner[worst_i]
worst_dir <- ifelse(sweep_tab$slope[worst_i] < 0, "falling", "rising")

## ---- fig-sweep ----
line_dat <- data.frame(rmax_fast = seq(min(sweep_rates), max(sweep_rates), length.out = 300))
line_dat$rstar_fast <- rstar_of(line_dat$rmax_fast, half_f, dil)
ggplot(line_dat, aes(rmax_fast, rstar_fast)) +
  geom_line(colour = te_rust, linewidth = 0.9) +
  geom_hline(yintercept = rs_slow, colour = te_forest, linewidth = 0.8) +
  geom_vline(xintercept = rmax_flip, linetype = "dotted",
             colour = te_body, linewidth = 0.6) +
  geom_point(data = sweep_tab, aes(rmax_fast, end_res, colour = winner), size = 2.6) +
  scale_colour_manual(values = c(te_rust, te_forest), name = "survivor") +
  coord_cartesian(ylim = c(0, 9)) +
  labs(x = "maximum growth rate of the fast species (per day)",
       y = "resource concentration", title = "R-star, not speed, decides the contest",
       subtitle = "red curve: the fast species R-star; green line: the slow species R-star") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- alpha ----
rspan <- seq(rs_slow, sup_one, length.out = 400)
alpha_sf <- (use_f * monod(rspan, rmax_f, half_f)) / (use_s * monod(rspan, rmax_s, half_s))
alpha_fs <- 1 / alpha_sf
prod_dev  <- max(abs(alpha_sf * alpha_fs - 1))
niche_dev <- max(abs(1 - sqrt(alpha_sf * alpha_fs)))
alpha_at_win <- alpha_sf[1]

## ---- fp-guard-1 ----
stopifnot(prod_dev < 1e-10, niche_dev < 1e-10)

## ---- twores ----
rmx <- 1.0
half_sp1 <- c(3, 12)     # species 1: good on resource 1, poor on resource 2
half_sp2 <- c(12, 3)     # species 2: the mirror image
cons_sp1 <- c(0.3, 0.7)  # species 1 takes mostly resource 2
cons_sp2 <- c(0.7, 0.3)  # species 2 takes mostly resource 1
rst_sp1 <- half_sp1 * dil / (rmx - dil)   # zero net growth corner, species 1
rst_sp2 <- half_sp2 * dil / (rmx - dil)   # and species 2
res_int <- c(rst_sp2[1], rst_sp1[2])      # where the two isoclines cross
grow_two <- function(rr, halfk)
  rmx * min(rr[1] / (halfk[1] + rr[1]), rr[2] / (halfk[2] + rr[2]))
two_deriv <- function(c1, c2, spl) function(x) {
  rr <- pmax(x[1:2], 0); n1 <- x[3]; n2 <- x[4]
  g1 <- grow_two(rr, half_sp1); g2 <- grow_two(rr, half_sp2)
  c(dil * (spl[1] - rr[1]) - c1[1] * g1 * n1 - c2[1] * g2 * n2,
    dil * (spl[2] - rr[2]) - c1[2] * g1 * n1 - c2[2] * g2 * n2,
    n1 * (g1 - dil), n2 * (g2 - dil))
}
mono_eq <- function(rst, cvec, spl) {
  n_a <- (spl[1] - rst[1]) / cvec[1]; n_b <- (spl[2] - rst[2]) / cvec[2]
  if (n_a > 0 && spl[2] - cvec[2] * n_a >= rst[2])
    return(c(rst[1], spl[2] - cvec[2] * n_a, n_a))
  if (n_b > 0 && spl[1] - cvec[1] * n_b >= rst[1])
    return(c(spl[1] - cvec[1] * n_b, rst[2], n_b))
  c(spl[1], spl[2], 0)
}
label_cell <- function(c1, c2, spl) {
  e1 <- mono_eq(rst_sp1, c1, spl); e2 <- mono_eq(rst_sp2, c2, spl)
  ok1 <- e1[3] > 0; ok2 <- e2[3] > 0
  if (!ok1 || !ok2) return(if (ok1) "species 1 wins" else
                           if (ok2) "species 2 wins" else "neither persists")
  inv1 <- grow_two(e2[1:2], half_sp1) - dil   # invasion of a species 2 stand
  inv2 <- grow_two(e1[1:2], half_sp2) - dil   # invasion of a species 1 stand
  if (inv1 > 0 && inv2 > 0) return("coexistence")
  if (inv1 < 0 && inv2 < 0) return("bistable")
  if (inv1 > 0) "species 1 wins" else "species 2 wins"
}
sup_seq <- seq(3.3, 31.3, length.out = 15)
cell_tab <- expand.grid(s1 = sup_seq, s2 = sup_seq); n_cell <- nrow(cell_tab)
spl_i <- function(i) c(cell_tab$s1[i], cell_tab$s2[i])   # the supply pair of one cell
lab_col <- function(c1, c2)
  vapply(seq_len(n_cell), function(i) label_cell(c1, c2, spl_i(i)), "")
cell_tab$matched <- lab_col(cons_sp1, cons_sp2)
cell_tab$swapped <- lab_col(cons_sp2, cons_sp1)
sup_lo <- min(sup_seq); sup_hi <- max(sup_seq)
n_coex <- sum(cell_tab$matched == "coexistence")
n_bist <- sum(cell_tab$swapped == "bistable")
pct_coex <- 100 * n_coex / n_cell; pct_bist <- 100 * n_bist / n_cell
same_set <- identical(which(cell_tab$matched == "coexistence"),
                      which(cell_tab$swapped == "bistable"))

## ---- twocheck ----
persist_at <- 1e-3
sim_label <- function(c1, c2, spl, h = h_two, tmax = 600, trace_d = 1e-4) {
  e1 <- mono_eq(rst_sp1, c1, spl); e2 <- mono_eq(rst_sp2, c2, spl)
  f <- two_deriv(c1, c2, spl)
  x1 <- if (e1[3] > 0) c(e1[1:2], e1[3], trace_d) else c(spl, trace_d, trace_d)
  x2 <- if (e2[3] > 0) c(e2[1:2], trace_d, e2[3]) else c(spl, trace_d, trace_d)
  z1 <- rk4_run(f, x1, h, tmax / h, tmax / h)$x[2, ]
  z2 <- rk4_run(f, x2, h, tmax / h, tmax / h)$x[2, ]
  code_of <- function(e) paste0(as.integer(e[3] > persist_at), as.integer(e[4] > persist_at))
  if (code_of(z1) != code_of(z2)) return("bistable")
  switch(code_of(z1), "11" = "coexistence", "10" = "species 1 wins",
         "01" = "species 2 wins", "00" = "neither persists")
}
set.seed(41)
n_per_class <- 6
check_i <- unlist(lapply(split(seq_len(n_cell), cell_tab$matched),
  function(v) v[sample(length(v), min(n_per_class, length(v)))]))
h_two_fine <- h_two / 4
check_m <- vapply(check_i, function(i) sim_label(cons_sp1, cons_sp2, spl_i(i)), "")
check_s <- vapply(check_i, function(i) sim_label(cons_sp2, cons_sp1, spl_i(i)), "")
long_m <- vapply(check_i, function(i)
  sim_label(cons_sp1, cons_sp2, spl_i(i), tmax = 1200), "")
fine_m <- vapply(check_i, function(i)
  sim_label(cons_sp1, cons_sp2, spl_i(i), h = h_two_fine), "")
n_check <- length(check_i); moved_long <- sum(long_m != check_m)
moved_fine <- sum(fine_m != check_m)
agree_m <- sum(check_m == cell_tab$matched[check_i])
agree_s <- sum(check_s == cell_tab$swapped[check_i])

## ---- fig-zngi ----
zngi_arm <- function(rst, tagname, hi)
  data.frame(x = c(rst[1], rst[1], hi), y = c(hi, rst[2], rst[2]), who = tagname)
hi_lim <- max(sup_seq) + 2
zngi_all <- rbind(zngi_arm(rst_sp1, "species 1", hi_lim),
                  zngi_arm(rst_sp2, "species 2", hi_lim))
arrow_of <- function(ca, cb) data.frame(
  x = res_int[1], y = res_int[2], who = c("species 1", "species 2"),
  xend = res_int[1] + 9 * c(ca[1], cb[1]), yend = res_int[2] + 9 * c(ca[2], cb[2]))
out_cols <- c("coexistence" = te_gold, "bistable" = te_gold, "neither persists" = te_ink,
              "species 1 wins" = te_forest, "species 2 wins" = te_rust)
map_plot <- function(col_name, arrows, ttl) {
  ggplot(cell_tab, aes(s1, s2)) +
    geom_point(aes(colour = .data[[col_name]]), size = 2.2) +
    geom_path(data = zngi_all, aes(x, y, group = who, linetype = who),
              colour = te_body, linewidth = 0.7) +
    geom_segment(data = arrows, aes(x = x, y = y, xend = xend, yend = yend,
                 linetype = who), colour = te_ink, linewidth = 0.6,
                 arrow = arrow(length = unit(0.16, "cm"), type = "closed")) +
    scale_colour_manual(values = out_cols, name = NULL) +
    scale_linetype_manual(values = c("solid", "dashed"), guide = "none") +
    guides(colour = guide_legend(nrow = 2)) +
    labs(x = "supply of resource 1", y = "supply of resource 2", title = ttl) +
    theme_datasheet() + theme(legend.position = "bottom",
      legend.box = "vertical", legend.key.size = unit(0.3, "cm"),
      legend.text = element_text(size = 7.5), legend.margin = margin(1, 1, 1, 1))
}
map_plot("matched", arrow_of(cons_sp1, cons_sp2), "Matched consumption vectors") +
  labs(subtitle = "arrows: each species consumption vector at the crossing point")

## ---- bistable ----
sup_bi <- c(15.3, 19.3)
dens_m <- solve(cbind(cons_sp1, cons_sp2), sup_bi - res_int)
dens_int <- solve(cbind(cons_sp2, cons_sp1), sup_bi - res_int)
jac_num <- function(f, x, eps = 1e-6) vapply(seq_along(x), function(j) {
  bump <- numeric(length(x)); bump[j] <- eps
  (f(x + bump) - f(x - bump)) / (2 * eps)
}, numeric(length(x)))
lead_of <- function(c1, c2, nn)
  max(Re(eigen(jac_num(two_deriv(c1, c2, sup_bi), c(res_int, nn)))$values))
lead_m <- lead_of(cons_sp1, cons_sp2, dens_m); lead_s <- lead_of(cons_sp2, cons_sp1, dens_int)
head_hi <- 0.50; head_lo <- 0.05
bi_run <- function(n1, n2) rk4_run(two_deriv(cons_sp2, cons_sp1, sup_bi),
                                   c(sup_bi, n1, n2), h_bi, 12000, 100)
bi_one <- bi_run(head_hi, head_lo); bi_two <- bi_run(head_lo, head_hi)
end_1 <- bi_one$x[nrow(bi_one$x), ]; end_2 <- bi_two$x[nrow(bi_two$x), ]
head_start <- head_hi / head_lo
bi_half <- rk4_run(two_deriv(cons_sp2, cons_sp1, sup_bi), c(sup_bi, head_hi, head_lo),
                   h_bi / 2, 24000, 200)
bi_dev <- abs(bi_half$x[nrow(bi_half$x), 3] / end_1[3] - 1)

## ---- fig-bistable ----
traj_of <- function(z, tag) rbind(
  data.frame(day = z$tvec, dens = z$x[, 3], species = "species 1", start = tag),
  data.frame(day = z$tvec, dens = z$x[, 4], species = "species 2", start = tag))
traj_bi <- rbind(traj_of(bi_one, "species 1 first"), traj_of(bi_two, "species 2 first"))
p_traj <- ggplot(traj_bi, aes(day, dens, colour = species, linetype = start)) +
  geom_line(linewidth = 0.8) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  scale_linetype_manual(values = c("solid", "dashed"), name = NULL) +
  scale_y_log10(labels = scales::label_log()) + coord_cartesian(ylim = c(1e-6, 100)) +
  labs(x = "day", y = "density (log scale)", title = "Same supply, two outcomes") +
  theme_datasheet() + theme(legend.position = "bottom",
    legend.box = "vertical", legend.key.width = unit(0.9, "cm"),
    legend.text = element_text(size = 7.5), legend.margin = margin(1, 1, 1, 1))
map_plot("swapped", arrow_of(cons_sp2, cons_sp1), "Swapped vectors") + p_traj +
  plot_annotation(theme = theme_datasheet())
