# Checking a food web analysis
# https://tidyecology.com/posts/checking-a-food-web-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-09-27

## ---- base-web ----
niche_web <- function(S, C) {
  n <- runif(S); beta <- 1 / (2 * C) - 1; r <- n * rbeta(S, 1, beta)
  r[which.min(n)] <- 0; centre <- runif(S, r / 2, n)
  A <- matrix(0L, S, S)
  for (i in seq_len(S)) A[i, n >= centre[i] - r[i] / 2 & n <= centre[i] + r[i] / 2] <- 1L
  A
}
role <- function(A) {
  g <- rowSums(A); v <- colSums(A)
  ifelse(g == 0, "basal", ifelse(v == 0, "top", "intermediate"))
}

set.seed(43)
S <- 30
A <- niche_web(S, 0.15)
true_role <- role(A)
c(species = S, links = sum(A), connectance = round(sum(A) / S^2, 3),
  basal = sum(true_role == "basal"), top = sum(true_role == "top"))

## ---- sampling ----
set.seed(101)
ps <- c(0.3, 0.5, 0.7, 0.9, 1.0)
sampled <- t(sapply(ps, function(p) {
  z <- t(replicate(400, {
    D <- A * (matrix(runif(S * S), S, S) < p)   # keep each true link w.p. p
    rr <- role(D)
    c(connectance = sum(D) / S^2,
      basal = sum(rr == "basal"),
      top   = sum(rr == "top"),
      misclassified = mean(rr != true_role))
  }))
  colMeans(z)
}))
data.frame(detection = ps, round(sampled, 3))

## ---- fig-sampling ----
library(ggplot2)
sdf <- data.frame(detection = ps, connectance = sampled[, "connectance"])
Ctrue <- sum(A) / S^2

ggplot(sdf, aes(detection, connectance)) +
  geom_hline(yintercept = Ctrue, linetype = "dashed", colour = "grey55") +
  geom_line(colour = "#3d6cb0", linewidth = 0.8) +
  geom_point(colour = "#3d6cb0", size = 2.4) +
  annotate("text", x = 0.35, y = Ctrue + 0.006, label = "true connectance",
           hjust = 0, size = 3.4, colour = "grey35") +
  labs(x = "Detection probability", y = "Estimated connectance") +
  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))

## ---- nulls ----
random_L  <- function(S, L) { M <- matrix(0L, S, S); M[sample(S * S, L)] <- 1L; M }
cascade_L <- function(S, L) {
  p <- L / (S * (S - 1) / 2); M <- matrix(0L, S, S)
  for (i in 2:S) for (j in 1:(i - 1)) if (runif(1) < p) M[i, j] <- 1L
  M
}
obs_basal <- sum(true_role == "basal"); L <- sum(A)

set.seed(202)
rand_basal <- replicate(2000, sum(rowSums(random_L(S, L)) == 0))
casc_basal <- replicate(2000, sum(rowSums(cascade_L(S, L)) == 0))

data.frame(
  null = c("random", "cascade"),
  mean_basal = round(c(mean(rand_basal), mean(casc_basal)), 2),
  sd_basal   = round(c(sd(rand_basal),   sd(casc_basal)),   2),
  z_observed = round(c((obs_basal - mean(rand_basal)) / sd(rand_basal),
                       (obs_basal - mean(casc_basal)) / sd(casc_basal)), 1),
  p_one_sided = round(c(mean(rand_basal >= obs_basal),
                        mean(casc_basal >= obs_basal)), 3)
)

## ---- fig-nulls ----
nd <- rbind(data.frame(basal = rand_basal, null = "random"),
            data.frame(basal = casc_basal, null = "cascade"))

ggplot(nd, aes(basal, fill = null)) +
  geom_histogram(binwidth = 1, alpha = 0.75, position = "identity") +
  geom_vline(xintercept = obs_basal, colour = "#c1523f", linewidth = 0.8) +
  annotate("text", x = obs_basal - 0.3, y = Inf, vjust = 1.6, hjust = 1,
           label = "observed", size = 3.4, colour = "#c1523f") +
  scale_fill_manual(values = c("random" = "#8aa0c8", "cascade" = "#e0c341")) +
  labs(x = "Basal species in null web", y = "Count", fill = 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))

## ---- self-regulation ----
stable <- function(M) max(Re(eigen(M, only.values = TRUE)$values)) < 0

set.seed(7)
Sp <- 50; Cp <- 0.20; sigma <- 0.35
E <- matrix(0, Sp, Sp)                       # one fixed predator-prey interaction structure
for (i in 1:(Sp - 1)) for (j in (i + 1):Sp) if (runif(1) < Cp) {
  E[i, j] <- abs(rnorm(1)); E[j, i] <- -abs(rnorm(1))
}

ds <- c(0.2, 0.3, 0.4, 0.6, 1.0)
verdict <- sapply(ds, function(dd) {
  M <- -dd * diag(Sp) + sigma * E
  c(self_regulation = dd,
    rightmost_eig = round(max(Re(eigen(M, only.values = TRUE)$values)), 3),
    stable = stable(M))
})
t(verdict)
