# Fitting annual plant competition models
# https://tidyecology.com/posts/annual-plant-competition-models/
#
# 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-11-15

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

theme_te <- theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))

## the generating (true) coefficients we will try to recover
lamA <- 45; aAA <- 0.10; aAB <- 0.03   # focal A: intra 0.10, inter 0.03
lamB <- 30; aBB <- 0.06; aBA <- 0.06   # focal B coefficients, carried into the next post

## ---- simdata ----
set.seed(101)
gridpts <- c(0, 2, 4, 8, 16, 32)
d <- expand.grid(DA = gridpts, DB = gridpts)
d <- d[rep(seq_len(nrow(d)), each = 6), ]           # 6 focal plants per cell
mu <- lamA / (1 + aAA * d$DA + aAB * d$DB)          # expected seeds per focal plant
d$seeds <- rnbinom(nrow(d), mu = mu, size = 10)      # overdispersed counts
n_plants <- nrow(d)

## ---- fitfull ----
fit_A <- nls(seeds ~ lam / (1 + aii * DA + aij * DB), data = d,
             start = list(lam = 40, aii = 0.05, aij = 0.05))
cf <- coef(fit_A)
ci <- suppressMessages(confint(fit_A, "aii"))

## ---- recover-numbers ----
lamA_hat <- unname(cf["lam"]); aAA_hat <- unname(cf["aii"]); aAB_hat <- unname(cf["aij"])

## ---- fig-curves ----
xx <- seq(0, 32, length.out = 100)
pred <- rbind(
  data.frame(D = xx, seeds = lamA_hat / (1 + aAA_hat * xx), neighbour = "conspecific (A)"),
  data.frame(D = xx, seeds = lamA_hat / (1 + aAB_hat * xx), neighbour = "heterospecific (B)"))
obs <- rbind(
  data.frame(D = d$DA[d$DB == 0], seeds = d$seeds[d$DB == 0], neighbour = "conspecific (A)"),
  data.frame(D = d$DB[d$DA == 0], seeds = d$seeds[d$DA == 0], neighbour = "heterospecific (B)"))
ggplot(pred, aes(D, seeds, colour = neighbour)) +
  geom_point(data = obs, alpha = 0.4, size = 1.4) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("conspecific (A)" = "#275139",
                                 "heterospecific (B)" = "#b5534e")) +
  labs(x = "neighbour density (plants per plot)",
       y = "seeds per focal plant", colour = NULL) +
  theme_te + theme(legend.position = "top")

## ---- additive-fail ----
add <- d[d$DA == 0, ]
result <- tryCatch(
  nls(seeds ~ lam / (1 + aii * DA + aij * DB), data = add,
      start = list(lam = 40, aii = 0.05, aij = 0.05)),
  error = function(e) conditionMessage(e))
n_add <- nrow(add)
result

## ---- additive-ok ----
fit_add <- nls(seeds ~ lam / (1 + aij * DB), data = add,
               start = list(lam = 40, aij = 0.05))
round(coef(fit_add), 3)

## ---- fig-identify ----
prof_rss <- function(dat, grid) sapply(grid, function(a) {
  f <- try(nls(seeds ~ lam / (1 + a * DA + aij * DB), data = dat,
               start = list(lam = 40, aij = 0.05)), silent = TRUE)
  if (inherits(f, "try-error")) NA_real_ else sum(residuals(f)^2)
})
agrid <- seq(0, 0.30, by = 0.01)
prof <- rbind(
  data.frame(aii = agrid, rss = prof_rss(d, agrid),   design = "response surface"),
  data.frame(aii = agrid, rss = prof_rss(add, agrid), design = "additive (conspecific absent)"))
prof$rel <- ave(prof$rss, prof$design, FUN = function(z) z / min(z, na.rm = TRUE))
ggplot(prof, aes(aii, rel, colour = design)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("response surface" = "#275139",
                                 "additive (conspecific absent)" = "#b5534e")) +
  labs(x = expression("intraspecific coefficient " * alpha[AA]),
       y = "residual sum of squares (relative to minimum)", colour = NULL) +
  theme_te + theme(legend.position = "top")
