# Stream metabolism from one oxygen logger
# https://tidyecology.com/posts/stream-metabolism-from-oxygen/
#
# 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 ----
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

step   <- 1 / 96                        # fifteen minutes, expressed in days
tod    <- (seq_len(96) - 0.5) / 96      # time of day
c_sat  <- 9.0                           # saturation, mg/L, near 20 degrees C

# normalised light: a sine over a fourteen hour photoperiod, integrating to one
light <- pmax(sin(pi * (tod - 0.22) / 0.58), 0)
light <- light / (sum(light) * step)

# five days are integrated and the last one kept, so the series is on its
# repeating daily cycle and carries no start up transient
simulate_do <- function(gpp, er, k_gas, depth, c0 = 8.6, noise = 0, days = 5) {
  n <- 96 * days; lt <- rep(light, days)
  conc <- numeric(n); conc[1] <- c0
  for (i in 2:n)
    conc[i] <- conc[i - 1] + step * ((gpp * lt[i - 1] - er) / depth +
                                     k_gas * (c_sat - conc[i - 1]))
  conc[(n - 95):n] + rnorm(96, 0, noise)
}

## ---- reaches ----
reaches <- data.frame(
  name  = c("shallow, slow", "intermediate", "deep, fast"),
  depth = c(0.4, 1.2, 3.0),
  k_gas = c(8, 25, 80))
gpp_true <- 3.0; er_true <- 2.5

swings <- sapply(seq_len(nrow(reaches)), function(i)
  diff(range(simulate_do(gpp_true, er_true, reaches$k_gas[i], reaches$depth[i]))))
reaches$diel_range <- round(swings, 3)
reaches

## ---- fig-curves ----
set.seed(5210)
curves <- do.call(rbind, lapply(seq_len(nrow(reaches)), function(i) {
  clean <- simulate_do(gpp_true, er_true, reaches$k_gas[i], reaches$depth[i])
  noisy <- clean + rnorm(96, 0, 0.15)
  data.frame(tod = tod, clean = clean, noisy = noisy,
             reach = sprintf("%s (range %.2f mg/L)", reaches$name[i],
                             reaches$diel_range[i]))
}))
curves$reach <- factor(curves$reach, levels = unique(curves$reach))

ggplot(curves, aes(24 * tod)) +
  geom_point(aes(y = noisy), colour = te_rust, size = 1.1, alpha = 0.75) +
  geom_line(aes(y = clean), colour = te_forest, linewidth = 0.9, linetype = "dashed") +
  facet_wrap(~ reach, scales = "free_y", nrow = 1) +
  scale_x_continuous(breaks = c(0, 6, 12, 18, 24)) +
  labs(x = "hour of day", y = "dissolved oxygen, mg/L",
       title = "Same metabolism, three reaches") +
  theme_datasheet() +
  theme(strip.text = element_text(colour = te_ink, face = "bold", size = 9))

## ---- fitting ----
fit_metab <- function(obs, k_gas, depth, start = c(5, 5)) {
  rss <- function(par) {
    conc <- numeric(96); conc[1] <- obs[1]
    for (i in 2:96)
      conc[i] <- conc[i - 1] + step * ((par[1] * light[i - 1] - par[2]) / depth +
                                       k_gas * (c_sat - conc[i - 1]))
    sum((obs - conc)^2)
  }
  o <- optim(start, rss, method = "Nelder-Mead",
             control = list(reltol = 1e-10, maxit = 2000))
  c(gpp = o$par[1], er = o$par[2])
}

set.seed(5220)
one_day <- simulate_do(gpp_true, er_true, reaches$k_gas[1], reaches$depth[1],
                       noise = 0.15)
round(fit_metab(one_day, reaches$k_gas[1], reaches$depth[1]), 3)

## ---- replicates ----
run_reach <- function(i, nrep = 300, seed) {
  set.seed(seed)
  out <- t(replicate(nrep, {
    obs <- simulate_do(gpp_true, er_true, reaches$k_gas[i], reaches$depth[i],
                       noise = 0.15)
    fit_metab(obs, reaches$k_gas[i], reaches$depth[i])
  }))
  data.frame(reach = reaches$name[i], gpp = out[, 1], er = out[, 2])
}
sims <- do.call(rbind, lapply(seq_len(nrow(reaches)),
                              function(i) run_reach(i, seed = 5300 + i)))

summary_tab <- do.call(rbind, lapply(reaches$name, function(nm) {
  d <- sims[sims$reach == nm, ]
  data.frame(reach = nm,
             gpp_mean = mean(d$gpp), gpp_sd = sd(d$gpp),
             gpp_neg = 100 * mean(d$gpp < 0),
             er_mean = mean(d$er), er_sd = sd(d$er),
             er_neg = 100 * mean(d$er < 0),
             pr_median = median(d$gpp / d$er),
             gpp_below_er = 100 * mean(d$gpp < d$er))
}))
round(summary_tab[, -1], 3)

## ---- fig-spread ----
long <- rbind(data.frame(reach = sims$reach, flux = sims$gpp, what = "gross primary production"),
              data.frame(reach = sims$reach, flux = sims$er,  what = "ecosystem respiration"))
long$reach <- factor(long$reach, levels = reaches$name)
long$what <- factor(long$what, levels = c("gross primary production",
                                          "ecosystem respiration"))
truth <- data.frame(what = factor(c("gross primary production", "ecosystem respiration"),
                                  levels = levels(long$what)),
                    value = c(gpp_true, er_true))

ggplot(long, aes(reach, flux)) +
  geom_hline(yintercept = 0, linetype = "dotted", colour = te_ink, linewidth = 0.6) +
  geom_violin(fill = te_gold, colour = NA, alpha = 0.55, scale = "width") +
  geom_hline(data = truth, aes(yintercept = value), linetype = "dashed",
             colour = te_forest, linewidth = 0.7) +
  facet_wrap(~ what) +
  coord_cartesian(ylim = c(-12, 16)) +
  labs(x = NULL, y = "estimate, g O2 per m2 per day",
       title = "Unbiased on average, impossible on the day") +
  theme_datasheet() +
  theme(strip.text = element_text(colour = te_ink, face = "bold"),
        axis.text.x = element_text(angle = 12, hjust = 1))

## ---- k-sweep ----
k_factors <- c(0.70, 0.85, 1.00, 1.15, 1.30)
set.seed(5400)
sweep <- do.call(rbind, lapply(k_factors, function(f) {
  out <- t(replicate(80, {
    obs <- simulate_do(gpp_true, er_true, reaches$k_gas[1], reaches$depth[1],
                       noise = 0.15)
    fit_metab(obs, reaches$k_gas[1] * f, reaches$depth[1])
  }))
  data.frame(k_factor = f, gpp = mean(out[, 1]), er = mean(out[, 2]),
             pr = mean(out[, 1] / out[, 2]))
}))
sweep$gpp_error <- 100 * (sweep$gpp / gpp_true - 1)
sweep$er_error  <- 100 * (sweep$er / er_true - 1)
sweep$pr_error  <- 100 * (sweep$pr / (gpp_true / er_true) - 1)
round(sweep, 2)

## ---- fig-ksweep ----
err <- rbind(data.frame(k = 100 * sweep$k_factor, err = sweep$gpp_error,
                        what = "gross primary production"),
             data.frame(k = 100 * sweep$k_factor, err = sweep$er_error,
                        what = "ecosystem respiration"),
             data.frame(k = 100 * sweep$k_factor, err = sweep$pr_error,
                        what = "production to respiration ratio"))
err$what <- factor(err$what, levels = c("gross primary production",
                                        "ecosystem respiration",
                                        "production to respiration ratio"))

ggplot(err, aes(k, err, colour = what, shape = what)) +
  geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.4, linetype = "dotted") +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.8) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold)) +
  labs(x = "reaeration coefficient used in the fit, per cent of truth",
       y = "error in the estimate, per cent", colour = NULL, shape = NULL,
       title = "The ratio survives what the fluxes do not") +
  theme_datasheet() +
  theme(legend.position = "top", legend.text = element_text(size = 8))
