# Food web structure: connectance and trophic level
# https://tidyecology.com/posts/food-web-structure-connectance/
#
# 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-04

## ---- build-web ----
sp <- c("Grass","Sedge","Detritus","Vole","Hare","Grasshopper","Beetle",
        "Weasel","Shrew","Fox","Kestrel","Buzzard","Raven","Eagle")
S <- length(sp)

# prey list: what each species eats (by index)
prey <- list(
  integer(0),  # Grass      (basal)
  integer(0),  # Sedge      (basal)
  integer(0),  # Detritus   (basal)
  c(1, 2),     # Vole
  c(2, 3),     # Hare
  c(1, 3),     # Grasshopper
  c(1, 2),     # Beetle
  c(4, 6, 7),  # Weasel
  c(6, 7),     # Shrew
  c(4, 5, 8),  # Fox
  c(6, 7, 9),  # Kestrel
  c(8, 9, 10), # Buzzard
  c(3, 12),    # Raven   (detritus and buzzard: a broad scavenger)
  c(10)        # Eagle   (a fox specialist)
)

A <- matrix(0L, S, S, dimnames = list(sp, sp))
for (i in seq_len(S)) if (length(prey[[i]])) A[i, prey[[i]]] <- 1L

L <- sum(A)          # number of feeding links
C <- L / S^2         # directed connectance
c(species = S, links = L, connectance = round(C, 3))

## ---- roles ----
gen <- rowSums(A)              # generality: number of prey
vul <- colSums(A)              # vulnerability: number of predators
basal <- which(gen == 0)
top   <- which(vul == 0)
inter <- which(gen > 0 & vul > 0)

data.frame(
  role  = c("basal", "intermediate", "top"),
  count = c(length(basal), length(inter), length(top))
)

c(mean_generality   = round(mean(gen[gen > 0]), 2),
  mean_vulnerability = round(mean(vul[vul > 0]), 2),
  linkage_density    = round(L / S, 2))

## ---- fig-web ----
library(ggplot2)

# prey-averaged trophic level for vertical placement
Wmat <- A / pmax(rowSums(A), 1)
tl_pa <- solve(diag(S) - Wmat, rep(1, S))

role <- ifelse(gen == 0, "basal", ifelse(vul == 0, "top", "intermediate"))
set.seed(1)
# horizontal spread within trophic bands to reduce overlap
xpos <- ave(tl_pa, round(tl_pa), FUN = function(z) seq_along(z) - mean(seq_along(z)))
nodes <- data.frame(sp = sp, x = xpos, y = tl_pa, role = role)

edges <- do.call(rbind, lapply(seq_len(S), function(i) {
  if (!length(prey[[i]])) return(NULL)
  data.frame(x = nodes$x[prey[[i]]], y = nodes$y[prey[[i]]],
             xend = nodes$x[i], yend = nodes$y[i])
}))

ggplot() +
  geom_segment(data = edges, aes(x, y, xend = xend, yend = yend),
               colour = "grey72", linewidth = 0.4) +
  geom_point(data = nodes, aes(x, y, fill = role), shape = 21,
             size = 6, colour = "grey25") +
  geom_text(data = nodes, aes(x, y, label = sp), size = 2.6, colour = "grey15",
            nudge_y = 0.11, vjust = 0) +
  scale_fill_manual(values = c(basal = "#4c9f70", intermediate = "#e0c341",
                               top = "#c1523f")) +
  scale_y_continuous(expand = expansion(mult = c(0.06, 0.10))) +
  labs(x = NULL, y = "Prey-averaged trophic level", fill = NULL) +
  theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        axis.text.x = element_blank(),
        plot.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA))

## ---- trophic-levels ----
# (1) prey-averaged: t = 1 + W t, basal = 1  ->  (I - W) t = 1
tl_pa <- solve(diag(S) - Wmat, rep(1, S))

# (2) shortest path to a basal species
tl_sp <- rep(NA_real_, S); tl_sp[basal] <- 1
repeat {
  changed <- FALSE
  for (i in setdiff(seq_len(S), basal)) {
    p <- prey[[i]]
    if (all(!is.na(tl_sp[p]))) {
      v <- 1 + min(tl_sp[p])
      if (is.na(tl_sp[i]) || v < tl_sp[i]) { tl_sp[i] <- v; changed <- TRUE }
    }
  }
  if (!changed) break
}

# (3) longest chain (this web is acyclic, so it is finite)
tl_lc <- rep(NA_real_, S); tl_lc[basal] <- 1
repeat {
  changed <- FALSE
  for (i in setdiff(seq_len(S), basal)) {
    p <- prey[[i]]
    if (all(!is.na(tl_lc[p]))) {
      v <- 1 + max(tl_lc[p])
      if (is.na(tl_lc[i]) || v != tl_lc[i]) { tl_lc[i] <- v; changed <- TRUE }
    }
  }
  if (!changed) break
}

data.frame(species = sp, prey_avg = round(tl_pa, 2),
           shortest = tl_sp, longest = tl_lc)

## ---- fig-tl-spread ----
tl_long <- rbind(
  data.frame(sp = sp, tl = tl_pa, def = "prey-averaged"),
  data.frame(sp = sp, tl = tl_sp, def = "shortest path"),
  data.frame(sp = sp, tl = tl_lc, def = "longest chain")
)
ord <- sp[order(tl_pa)]
tl_long$sp <- factor(tl_long$sp, levels = ord)
tl_long$def <- factor(tl_long$def,
                       levels = c("shortest path", "prey-averaged", "longest chain"))

ggplot(tl_long, aes(tl, sp)) +
  geom_line(aes(group = sp), colour = "grey75", linewidth = 0.5) +
  geom_point(aes(colour = def, shape = def), size = 2.6) +
  scale_colour_manual(values = c("shortest path" = "#4c9f70",
                                 "prey-averaged" = "#3d6cb0",
                                 "longest chain" = "#c1523f")) +
  labs(x = "Trophic level", y = NULL, colour = NULL, shape = 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))

## ---- rank-flip ----
c(prey_avg_highest = sp[which.max(tl_pa)],
  longest_highest  = sp[which.max(tl_lc)])

# rank agreement between definitions
round(c(pa_vs_shortest = cor(tl_pa, tl_sp, method = "spearman"),
        pa_vs_longest  = cor(tl_pa, tl_lc, method = "spearman"),
        shortest_vs_longest = cor(tl_sp, tl_lc, method = "spearman")), 3)
