# Checking a foraging analysis
# https://tidyecology.com/posts/checking-a-foraging-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-11-04

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_true <- "#555555"; col_disc <- "#b5651d"; col_rog <- "#3a6b52"

## (b) type II vs III proportion eaten
propII  <- function(N) 0.9/(1 + 0.9*0.045*N)
propIII <- function(N) 0.05*N/(1 + 0.05*0.045*N^2)
Ng <- seq(1, 120, 1); peakIII <- Ng[which.max(propIII(Ng))]

## (c) currency
Gmax <- 30; k <- 0.18; g <- function(t) Gmax*(1 - exp(-k*t)); gp <- function(t) Gmax*k*exp(-k*t)
travel <- 6; mf <- 0.6
t_rate <- uniroot(function(t) gp(t) - g(t)/(t + travel), c(1e-6, 200))$root
tt_grid <- seq(0.01, 60, 0.01)
t_eff  <- tt_grid[which.max((g(tt_grid) - mf*tt_grid)/(tt_grid + travel))]
cur_diff <- 100 * abs(t_rate - t_eff)/t_rate

## ---- depletion ----
a0 <- 1.0; h0 <- 0.03; Tt <- 1                          # the truth, over a trial of length 1
rogers_Ne <- function(N0) uniroot(function(Ne)          # prey eaten with depletion
  Ne - N0*(1 - exp(-a0*(Tt - h0*Ne))), c(0, N0 - 1e-9))$root

set.seed(398)                                           # six trials at each of eight densities
N0 <- rep(c(5, 10, 20, 40, 60, 80, 100, 150), each = 6)
truth <- sapply(N0, rogers_Ne)
Ne <- pmin(rbinom(length(N0), N0, truth/N0), N0)

fdisc <- nls(Ne ~ aa*N0/(1 + aa*hh*N0),                 # disc equation: density held constant
             start = list(aa = 0.5, hh = 0.02), control = nls.control(warnOnly = TRUE))
rog_pred <- function(N0, aa, hh) sapply(N0, function(n)
  uniroot(function(Ne) Ne - n*(1 - exp(-aa*(Tt - hh*Ne))), c(0, n - 1e-9))$root)
frog <- nls(Ne ~ rog_pred(N0, aa, hh),                  # random predator equation
            start = list(aa = 0.6, hh = 0.02), control = nls.control(warnOnly = TRUE))
a_disc <- coef(fdisc)["aa"]; a_rog <- coef(frog)["aa"]

c(disc_attack_rate = unname(a_disc), rogers_attack_rate = unname(a_rog), true = a0)

## ---- fig-depletion ----
db <- data.frame(method = factor(c("true","disc equation","random predator"),
                                 levels = c("true","disc equation","random predator")),
                 a = c(a0, a_disc, a_rog))
ggplot(db, aes(method, a, fill = method)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = a0, colour = col_true, linetype = "dashed") +
  scale_fill_manual(values = c("true" = col_true, "disc equation" = col_disc, "random predator" = col_rog), guide = "none") +
  labs(x = NULL, y = "Estimated attack rate", title = "Depletion biases the disc-equation attack rate down")

## ---- proportion ----
propII  <- function(N) 0.9/(1 + 0.9*0.045*N)             # Ne/N, type II
propIII <- function(N) 0.05*N/(1 + 0.05*0.045*N^2)       # Ne/N, type III
rbind(type_II  = round(propII(c(2, 20, 60)), 3),
      type_III = round(propIII(c(2, 20, 60)), 3))

## ---- fig-proportion ----
dp <- rbind(data.frame(N = Ng, p = propII(Ng),  type = "type II"),
            data.frame(N = Ng, p = propIII(Ng), type = "type III"))
ggplot(dp, aes(N, p, colour = type)) +
  annotate("rect", xmin = 0, xmax = 15, ymin = -Inf, ymax = Inf, fill = "#8aa29e", alpha = 0.15) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("type II" = col_disc, "type III" = col_rog)) +
  labs(x = "Prey density", y = "Proportion of prey eaten", colour = NULL,
       title = "The two responses differ most where prey are scarce")

## ---- false-type-three ----
fr_a <- 0.9; fr_h <- 0.045                                 # propII above: the instantaneous type II
fr_N <- c(2, 5, 10, 20, 40, 60, 100, 150)                  # Check 1 densities, 80 swapped for 2
stopifnot(isTRUE(all.equal(fr_a/(1 + fr_a*fr_h*fr_N), propII(fr_N))))
fr_sdlog <- 0.6; fr_rho <- 0.12; fr_reps <- 250            # design constants, fixed before running
fr_prop <- function(N, par, q) exp(par[1])*N^q/(1 + exp(par[1] + par[2])*N^(1 + q))
rp_eat <- function(N, a, h) { Ne <- pmin(N, a*N*Tt/(1 + a*h*N))   # rog_pred as Newton steps
  for (i in 1:6) { e <- exp(-a*(Tt - h*Ne)); Ne <- Ne - (Ne - N*(1 - e))/(1 + N*a*h*e) }; Ne }
for (m in c(0.2, 1, 5))                                    # the same numbers as Check 1's solver
  stopifnot(isTRUE(all.equal(rp_eat(fr_N, m*fr_a, fr_h), rog_pred(fr_N, m*fr_a, fr_h), tolerance = 1e-5)))
rp_prop <- function(N, par, q) rp_eat(N, exp(par[1])*N^q, exp(par[2]))/N
fr_nll <- function(par, eaten, left, q_of, pf) {          # binomial likelihood, from the totals
  p <- pmin(pmax(pf(fr_N, par, q_of(par)), 1e-9), 1 - 1e-9); -sum(eaten*log(p) + left*log(1 - p)) }
q_II <- function(par) 0; q_gen <- function(par) exp(par[3]); q_III <- function(par) 1; fr_fail <- fr_calls <- 0
fr_fit <- function(starts, N, y, q_of, pf = fr_prop) { best <- NULL   # best of several starts
  eaten <- tapply(y, N, sum); left <- tapply(N - y, N, sum)          # per density, in fr_N order
  for (s in starts) { fr_calls <<- fr_calls + 1
    o <- try(optim(s, fr_nll, eaten = eaten, left = left, q_of = q_of, pf = pf,
                   control = list(maxit = 2000)), silent = TRUE)
    if (inherits(o, "try-error") || o$convergence != 0) { fr_fail <<- fr_fail + 1; next }
    if (is.null(best) || o$value < best$value) best <- o }; best }
fr_one <- function(trials, arm) {
  N <- rep(fr_N, each = trials); p2 <- fr_a/(1 + fr_a*fr_h*N)
  a_i <- fr_a*exp(if (arm == "predators differ") fr_sdlog*rnorm(length(N)) else 0)
  p <- switch(arm, "binomial" = p2,
    "beta-binomial" = rbeta(length(N), p2*(1 - fr_rho)/fr_rho, (1 - p2)*(1 - fr_rho)/fr_rho),
    rp_eat(N, a_i, fr_h)/N)                                # no replacement: Check 1's equation
  y <- rbinom(length(N), N, p)
  m2 <- fr_fit(list(log(c(fr_a, fr_h)), log(c(0.3, 0.1))), N, y, q_II)
  mq <- fr_fit(list(c(m2$par, log(1e-3)), c(m2$par, log(0.3)), log(c(0.3, 0.05, 0.5))), N, y, q_gen)
  m3 <- fr_fit(list(log(c(0.05, fr_h)), log(c(0.01, 0.02))), N, y, q_III)
  mu <- N*fr_prop(N, m2$par, 0)
  disp <- sum((y - mu)^2/(mu*(1 - mu/N)))/(length(y) - 2) # Pearson dispersion of the type II fit
  lr <- max(2*(m2$value - mq$value), 0); lr_rp <- disp_rp <- NA
  if (arm %in% c("same predator", "predators differ")) {  # the exponent inside Check 1's equation
    r2 <- fr_fit(list(m2$par, log(c(fr_a, fr_h))), N, y, q_II, rp_prop)
    rq <- fr_fit(list(c(r2$par, log(1e-3)), c(r2$par, log(0.3))), N, y, q_gen, rp_prop)
    lr_rp <- max(2*(r2$value - rq$value), 0); mu <- N*rp_prop(N, r2$par, 0)
    disp_rp <- sum((y - mu)^2/(mu*(1 - mu/N)))/(length(y) - 2) }
  c(aic = lr > 4, quasi_F = pf(lr/disp, 1, length(y) - 3, lower.tail = FALSE) < 0.05,
    strict_III = m3$value < m2$value - 1, exponent = 1 + exp(mq$par[3]), disp = disp,
    aic_rpe = lr_rp > 4, disp_rpe = disp_rp) }
fr_tab <- data.frame(arm = rep(c("binomial", "beta-binomial", "same predator", "predators differ"), each = 2), trials = c(6, 20))
set.seed(3451)
fr_runs <- Map(function(tr, arm) replicate(fr_reps, fr_one(tr, arm)), fr_tab$trials, fr_tab$arm)
fr_tab <- cbind(fr_tab, t(sapply(fr_runs, function(r) c(rowMeans(r[c("aic", "quasi_F", "strict_III", "aic_rpe"), ]),
  exponent = median(r["exponent", r["aic", ] == 1]), disp = median(r["disp", ]),
  disp_rpe = median(r["disp_rpe", ])))))
fr_cf <- function(phi) 0.5*pchisq(4/phi, 1, lower.tail = FALSE)   # the half chi-square rate
fr_tab$formula <- fr_cf(fr_tab$disp); fr_tab$formula_rpe <- fr_cf(fr_tab$disp_rpe)
fr_mcse <- sqrt(fr_tab$formula*(1 - fr_tab$formula)/fr_reps)
fr_ref <- fr_tab$arm %in% c("binomial", "beta-binomial")  # guards: the fitter, and the closed form
stopifnot(fr_tab$aic[fr_tab$arm == "binomial"] < 0.08, abs(fr_tab$aic - fr_tab$formula)[fr_ref] < 4*fr_mcse[fr_ref])
fr_r <- function(arm, trials, col) fr_tab[fr_tab$arm == arm & fr_tab$trials == trials, col]
print(cbind(fr_tab[, 1:2], round(fr_tab[, c("aic", "quasi_F", "disp", "formula", "aic_rpe", "formula_rpe")], 3)), row.names = FALSE)
fr_bend <- rbind(density = fr_N[1:4], disc = propII(fr_N[1:4]), random_predator = rog_pred(fr_N[1:4], fr_a, fr_h)/fr_N[1:4])
round(fr_bend, 3)

## ---- currency ----
g <- function(t) 30*(1 - exp(-0.18*t)); gp <- function(t) 30*0.18*exp(-0.18*t)
t_rate <- uniroot(function(t) gp(t) - g(t)/(t + 6), c(1e-6, 200))$root      # maximise rate
tt <- seq(0.01, 60, 0.01)
t_eff  <- tt[which.max((g(tt) - 0.6*tt)/(tt + 6))]                          # net of metabolism
round(c(gross_rate_currency = t_rate, net_rate_currency = t_eff), 2)
