# Starting values and identifiability in nls
# https://tidyecology.com/posts/starting-values-and-identifiability/
#
# 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-15

## ---- sim ----
set.seed(4196)
tt <- rep(seq(0, 12, by = 0.5), each = 3)
A1 <- 5; r1 <- 1.2; A2 <- 3; r2 <- 0.18; s <- 0.15
y  <- A1 * exp(-r1 * tt) + A2 * exp(-r2 * tt) + rnorm(length(tt), 0, s)
d  <- data.frame(t = tt, y = y)

## ---- naive ----
naive <- try(nls(y ~ a1 * exp(-b1 * t) + a2 * exp(-b2 * t), data = d,
                 start = list(a1 = 1, b1 = 1, a2 = 1, b2 = 1)), silent = TRUE)
msg <- trimws(conditionMessage(attr(naive, "condition")))

## ---- fit ----
ss  <- nls(y ~ SSbiexp(t, A1, lrc1, A2, lrc2), data = d)
cs  <- coef(ss)
fit <- nls(y ~ a1 * exp(-b1 * t) + a2 * exp(-b2 * t), data = d,
           start = list(a1 = unname(cs["A1"]), b1 = unname(exp(cs["lrc1"])),
                        a2 = unname(cs["A2"]), b2 = unname(exp(cs["lrc2"]))))
co  <- coef(fit)

## ---- fig-decomp ----
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"))
}
gg <- data.frame(t = seq(0, 12, length.out = 300))
gg$fit  <- predict(fit, gg)
gg$fast <- co["a1"] * exp(-co["b1"] * gg$t)
gg$slow <- co["a2"] * exp(-co["b2"] * gg$t)
p_decomp <- ggplot(d, aes(t, y)) +
  geom_point(colour = "#16241d", alpha = 0.55, size = 1.5) +
  geom_line(data = gg, aes(t, fit),  colour = "#275139", linewidth = 1) +
  geom_line(data = gg, aes(t, fast), colour = "#b5534e", linewidth = 0.8, linetype = "21") +
  geom_line(data = gg, aes(t, slow), colour = "#cda23f", linewidth = 0.8, linetype = "41") +
  labs(x = "time", y = "response", subtitle =
       "Green: fit. Red: fast pool. Gold: slow pool") +
  theme_te()
p_decomp

## ---- thumb ----
ggsave("thumbnail.png",
       p_decomp + labs(subtitle = NULL) +
         theme(plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")

## ---- reparam ----
set.seed(4296)
tr <- rep(seq(0, 10, by = 0.5), each = 4)
yr <- 4 * exp(-0.35 * tr) + rnorm(length(tr), 0, 0.12)
dr <- data.frame(t = tr, y = yr)
f_raw <- nls(y ~ a * exp(-b * t),          data = dr, start = list(a = 3, b = 0.3))
f_ctr <- nls(y ~ a * exp(-b * (t - 1.2)),  data = dr, start = list(a = 1, b = 0.3))
c_raw <- cov2cor(vcov(f_raw))["a", "b"]
c_ctr <- cov2cor(vcov(f_ctr))["a", "b"]

## ---- close ----
set.seed(4396)
yc  <- A1 * exp(-0.45 * tt) + A2 * exp(-0.30 * tt) + rnorm(length(tt), 0, s)
dc  <- data.frame(t = tt, y = yc)
ssc <- nls(y ~ SSbiexp(t, A1, lrc1, A2, lrc2), data = dc,
           control = nls.control(maxiter = 500, warnOnly = TRUE))
fitc <- nls(y ~ a1 * exp(-b1 * t) + a2 * exp(-b2 * t), data = dc,
            start = list(a1 = unname(coef(ssc)["A1"]), b1 = unname(exp(coef(ssc)["lrc1"])),
                         a2 = unname(coef(ssc)["A2"]), b2 = unname(exp(coef(ssc)["lrc2"]))),
            control = nls.control(maxiter = 500, warnOnly = TRUE))
corr_aa <- cov2cor(vcov(fitc))["a1", "a2"]
se_b1   <- summary(fitc)$coefficients["b1", "Std. Error"]

## ---- profiles ----
prof_b1 <- function(dat, grid, st) sapply(grid, function(v) {
  fr <- try(nls(y ~ a1 * exp(-v * t) + a2 * exp(-b2 * t), data = dat, start = st,
                control = nls.control(maxiter = 200, warnOnly = TRUE)), silent = TRUE)
  if (inherits(fr, "try-error") || !fr$convInfo$isConv) NA_real_ else sum(resid(fr)^2)
})
gsep <- seq(0.5, 2.2, length.out = 60)
gcls <- seq(0.30, 1.6, length.out = 60)
rss_sep <- prof_b1(d,  gsep, list(a1 = 5, a2 = 3, b2 = 0.18))
rss_cls <- prof_b1(dc, gcls, list(a1 = 5, a2 = 3, b2 = 0.30))
rss_sep <- rss_sep - min(rss_sep, na.rm = TRUE)
rss_cls <- rss_cls - min(rss_cls, na.rm = TRUE)

## ---- fig-profile ----
pf <- rbind(
  data.frame(b1 = gsep, rss = rss_sep, case = "rates well separated"),
  data.frame(b1 = gcls, rss = rss_cls, case = "rates close together"))
# prof_b1() records NA where the constrained refit does not converge, which happens at the
# extreme end of the close-rates grid: there is no profile value there to draw
pf <- pf[!is.na(pf$rss), ]
ggplot(pf, aes(b1, rss, colour = case)) +
  geom_line(linewidth = 1) +
  coord_cartesian(ylim = c(0, 6)) +
  scale_colour_manual(values = c("rates well separated" = "#275139",
                                 "rates close together" = "#b5534e")) +
  labs(x = "fixed fast rate", y = "residual sum of squares above minimum",
       subtitle = "A flat floor means the rate is not identified") +
  theme_te()
