# Checking a nonlinear model
# https://tidyecology.com/posts/checking-a-nonlinear-model/
#
# 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-07

## ---- sim-het ----
set.seed(4197)
xx <- rep(seq(0.5, 40, length.out = 20), each = 3)
Vm <- 20; K <- 8; cv <- 0.22
mu <- Vm * xx / (K + xx)
y  <- mu + rnorm(length(xx), 0, cv * mu)     # SD grows with the mean
d  <- data.frame(x = xx, y = y)
f_ols <- nls(y ~ Vm * x / (K + x), data = d, start = list(Vm = 15, K = 5))

## ---- fit-wls ----
w <- 1 / fitted(f_ols)^2
f_w <- nls(y ~ Vm * x / (K + x), data = d, start = coef(f_ols), weights = w)
for (i in 1:3) {
  w   <- 1 / fitted(f_w)^2
  f_w <- nls(y ~ Vm * x / (K + x), data = d, start = coef(f_w), weights = w)
}

## ---- fig-resid ----
library(ggplot2)
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
          axis.title = element_text(colour = "#2c3a31"),
          axis.text  = element_text(colour = "#46604a"),
          strip.text = element_text(colour = "#16241d"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          legend.position = "none")
}
rd <- rbind(
  data.frame(fitted = fitted(f_ols), resid = resid(f_ols),
             panel = "ordinary: raw residuals"),
  data.frame(fitted = fitted(f_w), resid = resid(f_w) * sqrt(w),
             panel = "weighted: standardised residuals"))
ggplot(rd, aes(fitted, resid)) +
  geom_hline(yintercept = 0, colour = "#dad9ca") +
  geom_point(colour = "#275139", alpha = 0.7, size = 1.6) +
  facet_wrap(~ panel, scales = "free_y") +
  labs(x = "fitted value", y = "residual", subtitle =
       "The funnel on the left is non-constant variance") +
  theme_te()

## ---- coverage ----
Vm2 <- 20; K2 <- 12; sig <- 1.6
xc  <- rep(c(1, 2, 3, 4, 6, 8, 11, 15), each = 2)
mu2 <- Vm2 * xc / (K2 + xc)
set.seed(20260812)
B <- 1200; wald_hit <- 0; prof_hit <- 0; n <- 0; n_drop <- 0; wald_all <- 0; n_all <- 0
for (b in seq_len(B)) {
  yb <- mu2 + rnorm(length(xc), 0, sig)
  fb <- try(nls(y ~ Vm * x / (K + x), data = data.frame(x = xc, y = yb),
                start = list(Vm = 18, K = 10)), silent = TRUE)
  if (inherits(fb, "try-error")) next
  se <- summary(fb)$coefficients["K", "Std. Error"]
  if (!is.finite(se)) next
  tq <- qt(0.975, df.residual(fb))              # the quantile confint() also uses
  wK <- coef(fb)["K"] + c(-1, 1) * tq * se
  n_all <- n_all + 1; wald_all <- wald_all + (K2 >= wK[1] && K2 <= wK[2])
  pk <- try(suppressMessages(suppressWarnings(confint(fb, "K"))), silent = TRUE)
  if (inherits(pk, "try-error") || !all(is.finite(pk))) { n_drop <- n_drop + 1; next }
  n <- n + 1
  wald_hit <- wald_hit + (K2 >= wK[1] && K2 <= wK[2])
  prof_hit <- prof_hit + (K2 >= pk[1] && K2 <= pk[2])
}
wald_cov <- 100 * wald_hit / n
prof_cov <- 100 * prof_hit / n
wald_all_cov <- 100 * wald_all / n_all
print(round(c(fits_scored = n, profiles_dropped = n_drop,
              wald_coverage = wald_cov, profile_coverage = prof_cov,
              wald_coverage_all = wald_all_cov), 2))

## ---- extrap ----
set.seed(4297)
xr  <- rep(seq(1, 12, length.out = 16), each = 3)   # all below the half-saturation
yr  <- 25 * xr / (15 + xr) + rnorm(length(xr), 0, 0.6)
dr  <- data.frame(x = xr, y = yr)
mm  <- nls(y ~ Vm * x / (K + x), data = dr, start = list(Vm = 20, K = 10))
pw  <- nls(y ~ c * x^p,          data = dr, start = list(c = 2, p = 0.8))
pred <- function(m, xnew) predict(m, data.frame(x = xnew))

## ---- fig-extrap ----
gx <- data.frame(x = seq(1, 100, length.out = 400))
gx$saturating <- pred(mm, gx$x)
gx$power      <- pred(pw, gx$x)
ggplot() +
  annotate("rect", xmin = 1, xmax = 12, ymin = -Inf, ymax = Inf,
           fill = "#93a87f", alpha = 0.14) +
  geom_point(data = dr, aes(x, y), colour = "#16241d", alpha = 0.5, size = 1.4) +
  geom_line(data = gx, aes(x, saturating), colour = "#275139", linewidth = 1) +
  geom_line(data = gx, aes(x, power), colour = "#b5534e", linewidth = 1, linetype = "21") +
  annotate("text", x = 70, y = pred(mm, 70), label = "saturating", colour = "#275139", vjust = 1.8) +
  annotate("text", x = 70, y = pred(pw, 70), label = "power", colour = "#b5534e", vjust = -1.6) +
  labs(x = "predictor x", y = "response y", subtitle =
       "Shaded band is the observed range; the curves agree there") +
  theme_te() + theme(legend.position = "none")
