# Trophic position from stable isotopes
# https://tidyecology.com/posts/trophic-position-from-isotopes/
#
# 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-10-14

## ---- setup ----
library(ggplot2)
options(scipen = 999)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- estimator ----
set.seed(20260718)

lambda_base <- 2
tdf_ref     <- 3.4
n15_base    <- 5.0
tp_true     <- 3.5
sd_cons     <- 0.35
sd_ind_base <- 1.00
n_base      <- 6
se_base     <- sd_ind_base / sqrt(n_base)
n15_cons_true <- n15_base + tdf_ref * (tp_true - lambda_base)

nrep <- 20000
nc <- rnorm(nrep, n15_cons_true, sd_cons)
nb <- rnorm(nrep, n15_base, se_base)
tp_hat <- lambda_base + (nc - nb) / tdf_ref

round(c(replicates = nrep, baseline_individuals = n_base, baseline_se = se_base,
        lambda = lambda_base, tdf_assumed = tdf_ref, baseline_d15N = n15_base,
        consumer_d15N = n15_cons_true, tp_true = tp_true), 4)
round(c(mean_tp_hat = mean(tp_hat), bias = mean(tp_hat) - tp_true,
        mc_se = sd(tp_hat) / sqrt(nrep), sd_tp_hat = sd(tp_hat)), 5)

## ---- fig-biplot ----
c_pel <- -26; c_ben <- -21
n_pel <- 5.0;  n_ben <- 9.0
alpha_true <- 0.6
n_cons <- 10
sd_cons_c <- 0.9
tp_two <- 3.5

mix_c <- alpha_true * c_pel + (1 - alpha_true) * c_ben
mix_n <- alpha_true * n_pel + (1 - alpha_true) * n_ben

set.seed(4407)
base_pts <- rbind(
  data.frame(carbon = rnorm(n_base, c_pel, sd_ind_base),
             nitrogen = rnorm(n_base, n_pel, sd_ind_base), grp = "Pelagic baseline"),
  data.frame(carbon = rnorm(n_base, c_ben, sd_ind_base),
             nitrogen = rnorm(n_base, n_ben, sd_ind_base), grp = "Benthic baseline"))
cons_pts <- data.frame(
  carbon = rnorm(n_cons, mix_c, sd_cons_c),
  nitrogen = rnorm(n_cons, mix_n + tdf_ref * (tp_two - lambda_base), sd_cons),
  grp = "Consumer")
all_pts <- rbind(base_pts, cons_pts)
all_pts$grp <- factor(all_pts$grp,
                      levels = c("Pelagic baseline", "Benthic baseline", "Consumer"))
means <- do.call(rbind, lapply(split(all_pts, all_pts$grp), function(z)
  data.frame(carbon = mean(z$carbon), nitrogen = mean(z$nitrogen),
             se_c = sd(z$carbon) / sqrt(nrow(z)), se_n = sd(z$nitrogen) / sqrt(nrow(z)),
             grp = z$grp[1])))
scale_tp <- data.frame(tp = 2:5,
                       nitrogen = mix_n + tdf_ref * ((2:5) - lambda_base))
scale_tp$lab <- paste("TP =", scale_tp$tp)

ggplot(all_pts, aes(carbon, nitrogen, colour = grp)) +
  geom_hline(data = scale_tp, aes(yintercept = nitrogen),
             colour = te_pal$line, linetype = "22", linewidth = 0.6) +
  geom_text(data = scale_tp, aes(x = -19.4, y = nitrogen + 0.35, label = lab),
            inherit.aes = FALSE, colour = "#8a8977", size = 3.1, hjust = 1) +
  geom_segment(x = c_pel, y = n_pel, xend = c_ben, yend = n_ben,
               inherit.aes = FALSE, colour = te_pal$sage, linewidth = 0.9) +
  annotate("segment", x = -25.8, y = 3.1, xend = -23.85, yend = 6.72,
           colour = "#5c6f4d", linewidth = 0.4) +
  annotate("text", x = -28.3, y = 3.0, hjust = 0, size = 3.1, colour = "#5c6f4d",
           label = "Mixture of the two baselines") +
  geom_point(size = 1.5, alpha = 0.7) +
  geom_errorbar(data = means, aes(ymin = nitrogen - se_n, ymax = nitrogen + se_n),
                width = 0, linewidth = 0.8) +
  geom_errorbar(data = means, aes(xmin = carbon - se_c, xmax = carbon + se_c),
                orientation = "y", width = 0, linewidth = 0.8) +
  geom_point(data = means, size = 4) +
  scale_colour_manual(values = c("Pelagic baseline" = te_pal$forest,
                                 "Benthic baseline" = te_pal$gold,
                                 "Consumer" = te_pal$clay), name = NULL) +
  coord_cartesian(xlim = c(-28.5, -19), ylim = c(2.5, 17.5)) +
  labs(x = "Carbon isotope ratio (per mil)", y = "Nitrogen isotope ratio (per mil)",
       title = "Two baselines and a consumer between them") +
  theme_te() +
  theme(legend.position = "top")

## ---- variance ----
sd_tdf <- 1.0
var_parts <- function(tp) c(consumer = sd_cons^2, baseline = se_base^2,
                            tdf = (tp - lambda_base)^2 * sd_tdf^2) / tdf_ref^2
tp_lo <- 2.5; tp_hi <- 4.5
pa <- var_parts(tp_lo); pb <- var_parts(tp_hi)

mc_sd <- function(tp, m) {
  td  <- rnorm(m, tdf_ref, sd_tdf)
  ncc <- n15_base + td * (tp - lambda_base) + rnorm(m, 0, sd_cons)
  nbb <- rnorm(m, n15_base, se_base)
  sd(lambda_base + (ncc - nbb) / tdf_ref)
}
set.seed(11)
round(c(sd_tdf = sd_tdf, tp_low = tp_lo, tp_high = tp_hi,
        delta_sd_low = sqrt(sum(pa)), mc_sd_low = mc_sd(tp_lo, nrep),
        delta_sd_high = sqrt(sum(pb)), mc_sd_high = mc_sd(tp_hi, nrep)), 4)
pct <- rbind(low = 100 * pa / sum(pa), high = 100 * pb / sum(pb))
print(round(pct, 2))

## ---- fig-variance ----
lab_src <- c(consumer = "Consumer measurement", baseline = "Baseline measurement",
             tdf = "Discrimination factor")
vd <- data.frame(
  tp = rep(c(tp_lo, tp_hi), each = 3),
  source = factor(rep(lab_src, 2), levels = rev(lab_src)),
  pct = c(pct["low", ], pct["high", ]))
vd$panel <- factor(paste("Trophic position", vd$tp))
tops <- data.frame(panel = levels(vd$panel),
                   lab = paste("SD =", round(c(sqrt(sum(pa)), sqrt(sum(pb))), 3)))

ggplot(vd, aes(panel, pct, fill = source)) +
  geom_col(width = 0.55) +
  geom_text(data = tops, aes(panel, 104, label = lab), inherit.aes = FALSE,
            colour = te_pal$ink, size = 3.6) +
  scale_fill_manual(values = c("Discrimination factor" = te_pal$clay,
                               "Baseline measurement" = te_pal$gold,
                               "Consumer measurement" = te_pal$forest), name = NULL) +
  coord_cartesian(ylim = c(0, 110)) +
  labs(x = NULL, y = "Share of the variance (per cent)",
       title = "What the error bar is made of, low and high in the web") +
  theme_te() +
  theme(legend.position = "top")

## ---- tdf-sweep ----
tdf_grid <- seq(2.5, 4.5, by = 0.05)
cons_tp   <- c(2.5, 3.5, 4.5)
cons_n15  <- n15_base + tdf_ref * (cons_tp - lambda_base)
implied <- sapply(cons_n15, function(x) lambda_base + (x - n15_base) / tdf_grid)
colnames(implied) <- paste0("consumer_", cons_tp)

round(c(tdf_low = min(tdf_grid), tdf_high = max(tdf_grid), grid_points = length(tdf_grid)), 3)
round(rbind(consumer_d15N = cons_n15,
            tp_at_low_tdf = implied[1, ],
            tp_at_high_tdf = implied[nrow(implied), ],
            span = implied[1, ] - implied[nrow(implied), ]), 4)

## ---- fig-tdf ----
fan <- do.call(rbind, lapply(seq_along(cons_tp), function(i)
  data.frame(tdf = tdf_grid, tp = implied[, i],
             consumer = sprintf("Consumer at %.1f per mil", cons_n15[i]))))
fan$consumer <- factor(fan$consumer,
                       levels = sprintf("Consumer at %.1f per mil", cons_n15))
ends <- fan[fan$tdf == min(tdf_grid), ]

ggplot(fan, aes(tdf, tp, colour = consumer)) +
  geom_vline(xintercept = tdf_ref, colour = te_pal$line, linetype = "22",
             linewidth = 0.7) +
  geom_line(linewidth = 0.9) +
  geom_point(data = ends, size = 2) +
  scale_colour_manual(values = c(te_pal$sage, te_pal$green, te_pal$clay), name = NULL) +
  labs(x = "Assumed discrimination factor (per mil)",
       y = "Implied trophic position",
       title = "One measurement, a whole fan of answers") +
  theme_te() +
  theme(legend.position = "top")

## ---- diet-tdf ----
tdf_slope <- 0.30
tdf_diet <- function(nd) tdf_ref - tdf_slope * (nd - n15_base)

n15_chain <- numeric(4)
n15_chain[1] <- n15_base
for (i in 1:3) n15_chain[i + 1] <- n15_chain[i] + tdf_diet(n15_chain[i])
tp_chain <- lambda_base + 0:3
tp_naive <- lambda_base + (n15_chain - n15_base) / tdf_ref

round(c(slope_per_per_mil = tdf_slope, levels = length(tp_chain)), 3)
print(round(rbind(true_tp = tp_chain, step_enrichment = tdf_diet(n15_chain),
                  d15N = n15_chain, estimated_tp = tp_naive,
                  bias = tp_naive - tp_chain), 4))

## ---- two-baselines ----
n_ben_sep <- c(small = 5.5, large = 9.0)

two_rep <- function(nb2, m) {
  se_b <- sd_ind_base / sqrt(n_base)
  c1 <- rnorm(m, c_pel, se_b); c2 <- rnorm(m, c_ben, se_b)
  b1 <- rnorm(m, n_pel, se_b); b2 <- rnorm(m, nb2, se_b)
  mc <- alpha_true * c_pel + (1 - alpha_true) * c_ben
  mn <- alpha_true * n_pel + (1 - alpha_true) * nb2
  cc  <- rnorm(m, mc, sd_cons_c / sqrt(n_cons))
  ncn <- rnorm(m, mn + tdf_ref * (tp_two - lambda_base), sd_cons / sqrt(n_cons))
  ah <- (cc - c2) / (c1 - c2)
  th <- lambda_base + (ncn - (ah * b1 + (1 - ah) * b2)) / tdf_ref
  c(correlation = cor(ah, th), sd_alpha = sd(ah), sd_tp = sd(th),
    mean_alpha = mean(ah), mean_tp = mean(th))
}

set.seed(505)
m_two <- 6000
res_two <- rbind(small = two_rep(n_ben_sep["small"], m_two),
                 large = two_rep(n_ben_sep["large"], m_two))

round(c(replicates = m_two, consumers = n_cons, alpha_true = alpha_true,
        separation_small = as.numeric(n_ben_sep["small"] - n_pel),
        separation_large = as.numeric(n_ben_sep["large"] - n_pel)), 3)
print(round(res_two, 4))
round(c(sd_ratio = res_two["large", "sd_tp"] / res_two["small", "sd_tp"]), 4)

## ---- fig-ridge ----
one_dataset <- function(nb2, seed) {
  set.seed(seed)
  se_b <- sd_ind_base / sqrt(n_base)
  mc <- alpha_true * c_pel + (1 - alpha_true) * c_ben
  mn <- alpha_true * n_pel + (1 - alpha_true) * nb2
  list(c1 = rnorm(1, c_pel, se_b), c2 = rnorm(1, c_ben, se_b),
       b1 = rnorm(1, n_pel, se_b), b2 = rnorm(1, nb2, se_b),
       cc = rnorm(n_cons, mc, sd_cons_c),
       nn = rnorm(n_cons, mn + tdf_ref * (tp_two - lambda_base), sd_cons))
}
a_grid <- seq(0.25, 0.95, length.out = 141)
t_grid <- seq(3.00, 4.00, length.out = 141)

surface <- function(ob) {
  gr <- expand.grid(alpha = a_grid, tp = t_grid)
  mixc <- gr$alpha * ob$c1 + (1 - gr$alpha) * ob$c2
  mixn <- gr$alpha * ob$b1 + (1 - gr$alpha) * ob$b2
  pred <- mixn + tdf_ref * (gr$tp - lambda_base)
  ssc <- (n_cons * (mixc - mean(ob$cc))^2 + sum((ob$cc - mean(ob$cc))^2)) / sd_cons_c^2
  ssn <- (n_cons * (pred - mean(ob$nn))^2 + sum((ob$nn - mean(ob$nn))^2)) / sd_cons^2
  gr$dev <- (ssc + ssn) - min(ssc + ssn)
  gr
}
ridge_line <- function(ob) data.frame(
  alpha = a_grid,
  tp = lambda_base + (mean(ob$nn) - (a_grid * ob$b1 + (1 - a_grid) * ob$b2)) / tdf_ref)

sep_levels <- c("Baselines 0.5 per mil apart", "Baselines 4 per mil apart")
ob_s <- one_dataset(n_ben_sep["small"], 24)
ob_l <- one_dataset(n_ben_sep["large"], 24)
surf <- rbind(data.frame(surface(ob_s), sep = sep_levels[1]),
              data.frame(surface(ob_l), sep = sep_levels[2]))
rl <- rbind(data.frame(ridge_line(ob_s), sep = sep_levels[1]),
            data.frame(ridge_line(ob_l), sep = sep_levels[2]))
rl <- rl[rl$tp >= min(t_grid) & rl$tp <= max(t_grid), ]
truth_pt <- data.frame(alpha = alpha_true, tp = tp_two, sep = sep_levels)
surf$sep <- factor(surf$sep, levels = sep_levels)
rl$sep <- factor(rl$sep, levels = sep_levels)
truth_pt$sep <- factor(truth_pt$sep, levels = sep_levels)

ggplot(surf, aes(alpha, tp, z = dev)) +
  geom_contour_filled(breaks = c(0, 2.3, 6.18, 11.83, Inf)) +
  geom_line(data = rl, aes(alpha, tp), inherit.aes = FALSE,
            colour = te_pal$gold, linewidth = 0.7, linetype = "22") +
  geom_point(data = truth_pt, aes(alpha, tp), inherit.aes = FALSE,
             colour = te_pal$clay, shape = 4, size = 3.4, stroke = 1.3) +
  scale_fill_manual(values = c("#275139", "#3f9970", "#93a87f", "#e6e4d6"),
                    name = "Deviance") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  facet_wrap(~sep) +
  labs(x = "Mixing proportion from the pelagic chain",
       y = "Trophic position",
       title = "A ridge that only tilts when the baselines differ") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold"),
        panel.border = element_rect(colour = "#c4c2b1", fill = NA, linewidth = 0.5),
        panel.spacing = unit(10, "pt"))

## ---- seasonal ----
amp <- 1.5
period_months <- 12
w_freq <- 2 * pi / period_months
half_life <- 2
k_turn <- log(2) / half_life
atten <- k_turn / sqrt(k_turn^2 + w_freq^2)
lag_months <- atan(w_freq / k_turn) / w_freq

phase <- 1
t_cons <- 8
base_at <- function(tt) n15_base + amp * sin(w_freq * (tt - phase))
base_eff <- n15_base + amp * atten * sin(w_freq * (t_cons - phase) - atan(w_freq / k_turn))

gaps <- seq(0, 11.99, by = 0.001)
err_gap <- (base_eff - base_at(t_cons - gaps)) / tdf_ref
best_gap <- gaps[which.min(abs(err_gap))]
off_err <- function(o) c(earlier = (base_eff - base_at(t_cons - best_gap - o)) / tdf_ref,
                         later   = (base_eff - base_at(t_cons - best_gap + o)) / tdf_ref)

round(c(amplitude = amp, period_months = period_months, half_life_months = half_life,
        turnover_rate = k_turn, attenuation = atten, phase_lag_months = lag_months), 4)
round(c(effective_baseline = base_eff, same_day_baseline = base_at(t_cons),
        same_day_tp_error = (base_eff - base_at(t_cons)) / tdf_ref,
        best_gap_months = best_gap), 4)
round(c(off_one_month = off_err(1), off_three_months = off_err(3),
        worst_over_the_year = max(abs(err_gap)),
        full_seasonal_swing = 2 * amp / tdf_ref), 4)
