# Nonlinear regression in R with nls
# https://tidyecology.com/posts/nonlinear-regression-with-nls/
#
# 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-15

## ---- sim ----
set.seed(4221)
a_true <- 1.2
h_true <- 0.045
dens   <- rep(c(2, 4, 8, 16, 32, 50, 75, 100), each = 4)
mu     <- a_true * dens / (1 + a_true * h_true * dens)   # expected number eaten
Ne     <- rpois(length(dens), mu)
d      <- data.frame(N = dens, Ne = Ne)

## ---- fit-lin ----
dpos <- d[d$Ne > 0, ]                       # 1/Ne is undefined at Ne = 0
lb   <- lm(I(1 / Ne) ~ I(1 / N), data = dpos)
a_lin <- unname(1 / coef(lb)[2])
h_lin <- unname(coef(lb)[1])

## ---- fit-nls ----
ss  <- nls(Ne ~ SSmicmen(N, Vm, K), data = d)     # self-starting, no guesses
Vm  <- unname(coef(ss)["Vm"]); K <- unname(coef(ss)["K"])
fit <- nls(Ne ~ a * N / (1 + a * h * N), data = d,
           start = list(a = Vm / K, h = 1 / Vm))
a_hat <- unname(coef(fit)["a"]); h_hat <- unname(coef(fit)["h"])

## ---- fig-fits ----
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"),
          plot.subtitle = element_text(colour = "#5d6b61"),
          legend.position = "top",
          legend.title = element_blank(),
          legend.text  = element_text(colour = "#46604a"))
}
grid <- data.frame(N = seq(1, 105, length.out = 300))
grid$nls <- a_hat * grid$N / (1 + a_hat * h_hat * grid$N)
grid$lin <- a_lin * grid$N / (1 + a_lin * h_lin * grid$N)
ggplot(d, aes(N, Ne)) +
  geom_point(colour = "#16241d", alpha = 0.7, size = 1.9) +
  geom_line(data = grid, aes(N, nls, colour = "direct nls"), linewidth = 1) +
  geom_line(data = grid, aes(N, lin, colour = "double reciprocal"),
            linewidth = 1, linetype = "21") +
  scale_colour_manual(values = c("direct nls" = "#275139",
                                 "double reciprocal" = "#b5534e")) +
  labs(x = "prey density N", y = "prey eaten", subtitle =
       "Same data, two fitting methods") +
  theme_te()

## ---- mc ----
set.seed(20260810)
B  <- 2000
mc <- matrix(NA_real_, B, 2, dimnames = list(NULL, c("a_nls", "a_lin")))
for (b in seq_len(B)) {
  Neb <- rpois(length(dens), mu)
  db  <- data.frame(N = dens, Ne = Neb)
  fb  <- try(nls(Ne ~ a * N / (1 + a * h * N), data = db,
                 start = list(a = 1, h = 0.04)), silent = TRUE)
  if (!inherits(fb, "try-error")) mc[b, 1] <- coef(fb)["a"]
  dp  <- db[db$Ne > 0, ]
  mc[b, 2] <- 1 / coef(lm(I(1 / Ne) ~ I(1 / N), data = dp))[2]
}
mc     <- mc[complete.cases(mc), ]
bias_nls <- mean(mc[, 1]) / a_true - 1
bias_lin <- mean(mc[, 2]) / a_true - 1
sd_nls   <- sd(mc[, 1]); sd_lin <- sd(mc[, 2])

## ---- fig-mc ----
mcl <- data.frame(
  a = c(mc[, 1], mc[, 2]),
  method = rep(c("direct nls", "double reciprocal"), each = nrow(mc)))
ggplot(mcl, aes(a, fill = method, colour = method)) +
  geom_density(alpha = 0.35, linewidth = 0.6) +
  geom_vline(xintercept = a_true, colour = "#16241d", linetype = "31") +
  scale_fill_manual(values = c("direct nls" = "#275139",
                               "double reciprocal" = "#b5534e")) +
  scale_colour_manual(values = c("direct nls" = "#275139",
                                 "double reciprocal" = "#b5534e")) +
  coord_cartesian(xlim = c(0.4, 2.4)) +
  labs(x = "estimated attack rate", y = "density", subtitle =
       "Dashed line is the true attack rate") +
  theme_te()

## ---- ci ----
se_a  <- summary(fit)$coefficients["a", "Std. Error"]
wald  <- a_hat + c(-1, 1) * 1.96 * se_a
prof  <- suppressMessages(confint(fit, "a"))
