# The niche model of food webs
# https://tidyecology.com/posts/the-niche-model-of-food-webs/
#
# 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

## ---- niche-model ----
niche_web <- function(S, C) {
  n <- runif(S)                     # niche value: a position on the feeding axis
  beta <- 1 / (2 * C) - 1           # sets mean range width to hit connectance C
  r <- n * rbeta(S, 1, beta)        # feeding range, always at most the niche value
  r[which.min(n)] <- 0              # smallest niche eats nothing: a basal resource
  centre <- runif(S, r / 2, n)      # range centre, placed below the niche value
  A <- matrix(0L, S, S)
  for (i in seq_len(S)) {
    lo <- centre[i] - r[i] / 2
    hi <- centre[i] + r[i] / 2
    A[i, n >= lo & n <= hi] <- 1L   # eat everything whose niche is inside the range
  }
  A
}

## ---- one-web ----
set.seed(43)
S <- 30
A <- niche_web(S, 0.15)

gen <- rowSums(A); vul <- colSums(A)
c(species      = S,
  links        = sum(A),
  connectance  = round(sum(A) / S^2, 3),
  basal        = sum(gen == 0),
  intermediate = sum(gen > 0 & vul > 0),
  top          = sum(gen > 0 & vul == 0),
  cannibals    = sum(diag(A)))

## ---- fig-niche-axis ----
library(ggplot2)

# recover the ranges for the drawn web by rerunning with the same seed
set.seed(43)
n <- runif(S); beta <- 1 / (2 * 0.15) - 1; r <- n * rbeta(S, 1, beta)
r[which.min(n)] <- 0; centre <- runif(S, r / 2, n)

ord <- order(n)
df <- data.frame(niche = n[ord], lo = (centre - r / 2)[ord],
                 hi = (centre + r / 2)[ord], rank = seq_len(S))
df$role <- ifelse(rowSums(A)[ord] == 0, "basal",
           ifelse(colSums(A)[ord] == 0, "top", "intermediate"))

ggplot(df, aes(y = rank)) +
  geom_segment(aes(x = lo, xend = hi, yend = rank, colour = role), linewidth = 1.6,
               alpha = 0.5) +
  geom_point(aes(x = niche, colour = role), size = 2) +
  scale_colour_manual(values = c(basal = "#4c9f70", intermediate = "#e0c341",
                                 top = "#c1523f")) +
  labs(x = "Niche value", y = "Species (ordered by niche value)", colour = NULL) +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        legend.position = "top",
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))

## ---- three-models ----
cascade_web <- function(S, C) {
  p <- 2 * C * S / (S - 1)          # link probability that matches connectance C
  A <- matrix(0L, S, S)
  for (i in 2:S) for (j in 1:(i - 1)) if (runif(1) < p) A[i, j] <- 1L
  A
}
random_web <- function(S, C) matrix(rbinom(S * S, 1, C), S, S)

troph <- function(A) {              # prey-averaged trophic level, or NA if undefined
  S <- nrow(A); W <- A / pmax(rowSums(A), 1)
  tryCatch(solve(diag(S) - W, rep(1, S)), error = function(e) rep(NA_real_, S))
}

props <- function(f, S = 30, C = 0.15, reps = 1000) {
  z <- t(replicate(reps, {
    A <- f(S, C); g <- rowSums(A); v <- colSums(A); tl <- troph(A)
    c(connectance = sum(A) / S^2,
      no_basal    = sum(g == 0) == 0,
      basal_frac  = mean(g == 0),
      tl_undef    = any(!is.finite(tl)) | any(tl > 100))
  }))
  colMeans(z)
}

set.seed(2024)
summ <- rbind(niche   = props(niche_web),
              cascade = props(cascade_web),
              random  = props(random_web))
round(summ, 3)

## ---- fig-no-basal ----
nb <- data.frame(model = rownames(summ), no_basal = summ[, "no_basal"])
nb$model <- factor(nb$model, levels = c("niche", "cascade", "random"))

ggplot(nb, aes(model, no_basal, fill = model)) +
  geom_col(width = 0.6) +
  scale_fill_manual(values = c(niche = "#4c9f70", cascade = "#3d6cb0",
                               random = "#c1523f"), guide = "none") +
  labs(x = NULL, y = "Fraction of webs with no basal species") +
  ylim(0, 1) +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))
