# Analysis Clinic Case 001: a controlled lavaan nonconvergence example
#
# Purpose: reproduce lavaan's maximum-iteration failure, show the diagnostic
# fields a researcher should inspect, and verify that estimates from the failed
# run are not interpreted. The one-iteration cap is deliberately artificial so
# the symptom is stable and the cause is known. It illustrates one cause of
# nonconvergence; it is not a claim that raising the limit fixes other causes.

suppressPackageStartupMessages(library(lavaan))

set.seed(20261003)

population_model <- '
  visual  =~ 0.80*x1 + 0.70*x2 + 0.75*x3
  textual =~ 0.85*x4 + 0.80*x5 + 0.70*x6
  speed   =~ 0.75*x7 + 0.70*x8 + 0.80*x9

  visual ~~ 0.35*textual
  visual ~~ 0.25*speed
  textual ~~ 0.30*speed

  visual ~~ 1*visual
  textual ~~ 1*textual
  speed ~~ 1*speed

  x1 ~~ 0.36*x1
  x2 ~~ 0.51*x2
  x3 ~~ 0.4375*x3
  x4 ~~ 0.2775*x4
  x5 ~~ 0.36*x5
  x6 ~~ 0.51*x6
  x7 ~~ 0.4375*x7
  x8 ~~ 0.51*x8
  x9 ~~ 0.36*x9
'

analysis_model <- '
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
'

dat <- simulateData(population_model, sample.nobs = 250)

# Deliberately stop the optimizer after one iteration. Capture the exact warning
# so changes in future lavaan versions are visible during verification.
failed_warnings <- character()
fit_failed <- withCallingHandlers(
  cfa(
    analysis_model,
    data = dat,
    control = list(iter.max = 1)
  ),
  warning = function(w) {
    failed_warnings <<- c(failed_warnings, conditionMessage(w))
    invokeRestart("muffleWarning")
  }
)

# Refit the same identified model and same data with lavaan's ordinary optimizer
# controls. This is defensible here because the failed run's cause was the
# artificial one-iteration cap. It is not a general prescription.
fit_default <- cfa(analysis_model, data = dat)

failed_optim <- lavInspect(fit_failed, "optim")
default_optim <- lavInspect(fit_default, "optim")

cat("R version:", R.version.string, "\n")
cat("lavaan version:", as.character(packageVersion("lavaan")), "\n")
cat("seed: 20261003\n")
cat("n:", nrow(dat), "\n\n")

cat("FAILED RUN (deliberate iter.max = 1)\n")
cat("warning:", paste(failed_warnings, collapse = " | "), "\n")
cat("lavInspect converged:", lavInspect(fit_failed, "converged"), "\n")
cat("optimizer iterations:", failed_optim$iterations, "\n")
cat("optimizer message:", failed_optim$warn.txt, "\n")
cat("fit measures available:", length(tryCatch(fitMeasures(fit_failed), error = function(e) numeric())), "\n\n")

cat("DEFAULT-CONTROL REFIT (same model and data)\n")
cat("lavInspect converged:", lavInspect(fit_default, "converged"), "\n")
cat("optimizer iterations:", default_optim$iterations, "\n")
cat("largest absolute gradient:", format(max(abs(lavInspect(fit_default, "gradient"))), scientific = TRUE), "\n")
cat("post-fit admissibility check:", lavInspect(fit_default, "post.check"), "\n")
cat("CFI:", round(fitMeasures(fit_default, "cfi"), 3), "\n")
cat("RMSEA:", round(fitMeasures(fit_default, "rmsea"), 3), "\n\n")

cat("INTERPRETATION\n")
cat("The first fit did not converge because it was prevented from taking more than one iteration.\n")
cat("Its parameter values and fit measures must not be interpreted.\n")
cat("The refit converged under ordinary controls, had a near-zero gradient, and passed lavaan's post-fit check.\n")
cat("This comparison supports the known diagnosis in this controlled example only; increasing iterations is not a general remedy for misspecification, nonidentification, scaling problems, or inadmissible solutions.\n")

stopifnot(
  identical(lavInspect(fit_failed, "converged"), FALSE),
  identical(lavInspect(fit_default, "converged"), TRUE),
  failed_optim$iterations == 1,
  max(abs(lavInspect(fit_default, "gradient"))) < 0.001,
  identical(lavInspect(fit_default, "post.check"), TRUE)
)
