Skip to main content

spectrafit_solver/
dispatch.rs

1//! `fit()` — the public solver entry point and dispatcher.
2//!
3//! Parses [`FitOptionsSpec::solver`] into a [`Solver`] and routes it: `irls`,
4//! `global` and `varpro` dispatch early to their own module/crate, while the
5//! Levenberg–Marquardt family (`lm`/`trf`/`geodesic`/`lm-legacy`, and `auto`'s
6//! non-VarPro case) runs the shared pre-solve, solve and post-fit path here.
7//!
8//! Steps (LM-family path):
9//!   1. Compile the graph → get `free_keys`
10//!   2. Extract initial parameter vector + bounds
11//!   3. Evaluate the model *before* optimisation (`init_fit`)
12//!   4. Run `LevenbergMarquardt::minimize`
13//!   5. Compute post-fit statistics: χ², reduced-χ², R², DOF, AIC, BIC
14//!   6. Compute covariance matrix: (J_wᵀ J_w)⁻¹ when σ is user-supplied, else (JᵀJ)⁻¹ · (χ²/DOF)
15//!   7. Assemble and return `FitResultSpec`
16
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::ops::ControlFlow;
20use std::str::FromStr;
21
22use levenberg_marquardt::LevenbergMarquardt;
23use nalgebra::DVector;
24use spectrafit_graph::{evaluate_compiled, CompiledGraph};
25use spectrafit_types::{
26    CoreError, FitGraphSpec, FitOptionsSpec, FitResultSpec, JacobianMode, MeasurementSpec,
27    TerminationReason,
28};
29
30use crate::error::SolverError;
31use crate::global::{solve_global, DeConfig};
32use crate::irls::{solve_irls, WeightFn, DEFAULT_MAX_OUTER_ITER, DEFAULT_TOL_WEIGHTS};
33use crate::lm_problem::LmProblem;
34use crate::postfit::{self, LmSolveOutcome};
35
36/// Flatten one dataset's `dims × points` coordinates into the **point-major**
37/// (stride = n_dims) layout the executor's `coord_layout` expects: point `i`
38/// occupies `x[i*n_dims .. (i+1)*n_dims]`. For the 1-D case this is exactly
39/// `ds.x[0]`, so existing behaviour is unchanged; for n-D it interleaves the
40/// per-dimension coordinate rows so a Gaussian2D node receives `[xᵢ, yᵢ]`.
41pub(crate) fn point_major_x(ds: &MeasurementSpec) -> Vec<f64> {
42    let n_dims = ds.x.len();
43    if n_dims == 0 {
44        return Vec::new();
45    }
46    let n_points = ds.x[0].len();
47    let mut out = Vec::with_capacity(n_points * n_dims);
48    for i in 0..n_points {
49        for dim in &ds.x {
50            out.push(dim[i]);
51        }
52    }
53    out
54}
55
56// ---------------------------------------------------------------------------
57// Solver dispatch
58// ---------------------------------------------------------------------------
59
60/// Every solver [`fit`] can dispatch to, parsed once from
61/// [`FitOptionsSpec::solver`]. This enum + [`Solver::parse`] + the single match
62/// in [`fit`] is the *one place* that answers "which solvers exist and where
63/// does each one run":
64///
65/// * [`Lm`](Solver::Lm) / [`Trf`](Solver::Trf) / [`Geodesic`](Solver::Geodesic) /
66///   [`LmLegacy`](Solver::LmLegacy) — the Levenberg–Marquardt family. All run the
67///   shared pre-solve + solve below: the first three on the faer
68///   `spectrafit-levenberg-marquardt` core (TRF = Coleman–Li bound-distance
69///   scaling of parameters with two finite bounds, geodesic = Transtrum
70///   acceleration), `LmLegacy` on the nalgebra oracle.
71/// * [`Irls`](Solver::Irls) / [`Global`](Solver::Global) / [`Varpro`](Solver::Varpro)
72///   — distinct algorithms that dispatch early to their own module/crate.
73/// * [`Auto`](Solver::Auto) — VarPro when the graph is separable, unconstrained
74///   and untied (see [`graph_prefers_varpro`]), otherwise the faer LM family.
75#[derive(Debug, Clone, Copy, PartialEq)]
76enum Solver {
77    /// Default faer Levenberg–Marquardt.
78    Lm,
79    /// nalgebra `levenberg-marquardt` parity oracle.
80    LmLegacy,
81    /// The faer LM core with Coleman–Li bound-distance scaling of parameters with
82    /// two finite bounds; trial points are projected onto the box as in [`Lm`](Solver::Lm).
83    Trf,
84    /// Geodesic acceleration on the faer LM core.
85    Geodesic,
86    /// Powell's dogleg trust-region method.
87    Dogleg,
88    /// Matrix-free Newton-CG (Steihaug–Toint) trust-region method.
89    NewtonCg,
90    /// Iteratively-reweighted least squares (robust loss).
91    Irls(WeightFn),
92    /// Differential Evolution (global search).
93    Global,
94    /// Variable Projection (separable nonlinear least squares).
95    Varpro,
96    /// Choose from the graph shape at run time.
97    Auto,
98}
99
100impl Solver {
101    /// Parse the `FitOptionsSpec.solver` string.
102    ///
103    /// Unrecognised strings are rejected rather than silently defaulting to
104    /// LM — previously a typo (e.g. `"lmm"`, wrong-case `"Trf"`) silently ran
105    /// the LM solver instead of erroring, which could mask a misconfigured
106    /// fit with a plausible-looking but unintended result.
107    fn parse(s: &str) -> Result<Self, SolverError> {
108        match s {
109            "lm" => Ok(Solver::Lm),
110            "lm-legacy" => Ok(Solver::LmLegacy),
111            "trf" => Ok(Solver::Trf),
112            "geodesic" | "lm-geodesic" => Ok(Solver::Geodesic),
113            "dogleg" => Ok(Solver::Dogleg),
114            "newton-cg" | "newton_cg" | "newtoncg" | "steihaug" => Ok(Solver::NewtonCg),
115            "global" => Ok(Solver::Global),
116            "varpro" => Ok(Solver::Varpro),
117            "auto" => Ok(Solver::Auto),
118            _ if s.starts_with("irls") => {
119                let name = s.split_once(':').map(|(_, name)| name).unwrap_or("huber");
120                Ok(Solver::Irls(WeightFn::from_str(name)?))
121            }
122            other => Err(SolverError::UnrecognisedSolver(other.to_string())),
123        }
124    }
125}
126
127/// Whether a graph carries any tied parameters — a constraint expression from a
128/// graph `expr_edge` OR a per-parameter `Parameter.expr`. VarPro reconstructs
129/// parameters from the linear/nonlinear split and never applies the `TiedPlan`,
130/// so a tied graph must never be routed to / accepted by VarPro on EITHER surface
131/// (CX-VPE-01: checking `expr_edges` alone silently dropped `Parameter.expr` ties).
132fn graph_has_tied_params(graph: &FitGraphSpec) -> bool {
133    !graph.expr_edges.is_empty()
134        || graph
135            .nodes
136            .iter()
137            .any(|n| n.parameters.values().any(|p| p.expr.is_some()))
138}
139
140/// Whether `solver="auto"` should choose VarPro: the graph is separable, every
141/// nonlinear parameter is unconstrained (VarPro ignores bounds), and there are no
142/// tied parameters (via `expr_edges` or `Parameter.expr`; VarPro cannot honour them).
143fn graph_prefers_varpro(graph: &FitGraphSpec) -> bool {
144    !graph_has_tied_params(graph)
145        // VarPro stacks all datasets and is not dataset_index-aware, so it must
146        // not be auto-selected for simultaneous multi-dataset ("global analysis")
147        // graphs — those need the LM-family scoped executor path.
148        && graph.nodes.iter().all(|n| n.dataset_index.is_none())
149        && spectrafit_varpro::is_separable(graph)
150        && graph.nodes.iter().all(|n| {
151            n.parameters
152                .iter()
153                // amplitude is the linear coeff VarPro projects out; skip it BY NAME
154                // (HashMap order is non-deterministic, so positional `.skip(1)` could
155                // drop an arbitrary nonlinear param and miss its bounds — silent bound
156                // violation when that param is bounded but amplitude is not).
157                .filter(|(name, _)| name.as_str() != "amplitude")
158                .filter(|(_, p)| p.vary)
159                .all(|(_, p)| p.min.is_infinite() && p.max.is_infinite())
160        })
161}
162
163/// Build the `ParameterSpec` map and run VarPro. Shared by the explicit
164/// `solver="varpro"` arm and the `solver="auto"`→VarPro arm.
165fn solve_varpro_path(
166    graph: &FitGraphSpec,
167    datasets: &[MeasurementSpec],
168    options: &FitOptionsSpec,
169) -> Result<FitResultSpec, CoreError> {
170    let mut param_specs: HashMap<String, spectrafit_types::ParameterSpec> = HashMap::new();
171    for node in &graph.nodes {
172        for (pname, pspec) in &node.parameters {
173            param_specs.insert(format!("{}.{}", node.id, pname), pspec.clone());
174        }
175    }
176    spectrafit_varpro::solve_varpro(graph, datasets, &param_specs, options)
177}
178
179// ---------------------------------------------------------------------------
180// Public API
181// ---------------------------------------------------------------------------
182
183/// Run a fit of `graph` against `datasets` using the solver named by
184/// `options.solver` (see `Solver::parse` for the accepted strings: `lm`,
185/// `lm-legacy`, `trf`, `geodesic`, `dogleg`, `newton-cg`, `irls[:weight]`,
186/// `global`, `varpro`, `auto`).
187///
188/// The LM family (`lm`, `lm-legacy`, `trf`, `geodesic`) plus the
189/// trust-region methods (`dogleg`, `newton-cg`) and `auto`'s non-VarPro
190/// fallback share one pre-solve/solve/post-fit path through this function.
191/// `irls`, `global`, and `varpro` are routed to their own modules/crates in
192/// `dispatch_solver` and return before that shared path runs.
193///
194/// Returns a fully populated [`FitResultSpec`] including parameter values,
195/// standard errors, covariance matrix, and goodness-of-fit statistics.
196///
197/// # Errors
198/// Returns [`CoreError`] when:
199/// - `options.solver` does not parse (unrecognised solver name, or an
200///   unrecognised `irls:<weight>` weight-function name) — `Solver::parse`.
201/// - The routed non-LM-family solver fails: `irls` (`crate::irls::solve_irls`),
202///   `global` (differential evolution), or `varpro` (not separable, tied
203///   parameters present, or per-dataset scoping unsupported).
204/// - Graph compilation or the initial model evaluation fails (malformed
205///   graph, a free-key/parameter lookup miss, or a model evaluation error) —
206///   `prepare_lm_pre_solve`.
207/// - The LM-family solve itself fails or produces a numerically unusable
208///   result (e.g. ill-conditioned Jacobian) that maps to `CoreError::Solver`.
209/// - `options.eta` is set alongside `solver="dogleg"` / `"newton-cg"` but is
210///   not finite and in `[0.0, 0.25)` — `SolverError::InvalidEta`.
211/// - Post-fit assembly fails while re-evaluating the model or its Jacobian
212///   at the solution — `postfit::assemble_result`.
213pub fn fit(
214    graph: &FitGraphSpec,
215    datasets: Vec<MeasurementSpec>,
216    options: &FitOptionsSpec,
217) -> Result<FitResultSpec, CoreError> {
218    // Run faer's dense kernels serially for the whole fit (solve loop AND the
219    // post-fit covariance/condition-number). Our matrices are skinny (p ≲ 150),
220    // so faer's default Rayon dispatch costs more in thread-pool wake-up
221    // (~30–50 µs per matmul) than the arithmetic itself — measured ~4–6×
222    // slowdown overall, ~4.7× on a 50k×3 fit, including the n×p post-fit
223    // Gram/SVD. The data-parallelism that pays off lives one level down in the
224    // graph executor's own Rayon path (over points), not in these
225    // per-iteration p×p factorizations.
226    //
227    // THIS IS THE ONLY SITE that sets faer's global parallelism. The LM and
228    // trust-region drivers each used to set it again on entry to their own
229    // `minimize`/`minimize_tr`; setting one process-global three times from
230    // three crates made the effective policy depend on call order and left the
231    // drivers quietly mutating global state their doc comments never mentioned.
232    // Ownership now sits here, at the one place that already owns the whole
233    // fit — faer is solver-internal in this workspace, so a single global
234    // policy set at the fit boundary is safe.
235    faer::set_global_parallelism(faer::Par::Seq);
236
237    // ── 0. Solver dispatch ───────────────────────────────────────────────────
238    // Route the non-LM-family solvers to their own module/crate; the LM family
239    // (Lm/LmLegacy/Trf/Geodesic, and Auto's non-VarPro case) falls through to the
240    // shared pre-solve + solve below.
241
242    let solver = Solver::parse(&options.solver)?;
243    let datasets = match dispatch_solver(solver, graph, datasets, options) {
244        ControlFlow::Break(result) => return result,
245        ControlFlow::Continue(datasets) => datasets,
246    };
247
248    // ── 1/2/3/6/7. Compile the graph, collect free-param specs, evaluate the
249    // initial model, and build the index-based node-param buffers ───────────
250    let LmPreSolve {
251        cg,
252        free_keys,
253        all_params,
254        bounds,
255        scales,
256        sigma,
257        x_all,
258        y_all,
259        init_fit,
260        init_params,
261        node_param_bufs,
262        free_to_node_param,
263        tied_to_node_param,
264    } = prepare_lm_pre_solve(graph, &datasets)?;
265
266    // ── 8. Construct problem ─────────────────────────────────────────────────
267    let problem = LmProblem {
268        compiled: &cg,
269        free_keys: free_keys.clone(),
270        bounds: bounds.clone(),
271        all_params: all_params.clone(),
272        node_param_bufs,
273        free_to_node_param,
274        tied_to_node_param,
275        x_concat: x_all.clone(),
276        y_concat: y_all.clone(),
277        params: init_params,
278        scales: scales.clone(),
279        sigma,
280        jacobian_mode: options.jacobian,
281        residual_buf: RefCell::new(vec![0.0; y_all.len()]),
282        // One Jacobian row per data point (residual), not per coordinate: size by
283        // the point count (y_all.len()), which equals x_all.len() only in 1-D.
284        jacobian_buf: RefCell::new(vec![0.0; y_all.len() * free_keys.len()]),
285        residual_count: RefCell::new(0),
286        jacobian_count: RefCell::new(0),
287        residual_time_ns: RefCell::new(0),
288        jacobian_time_ns: RefCell::new(0),
289    };
290
291    // ── 4/8. Initialise tied parameters and run the LM-family solve ──────────
292    let outcome = run_lm_solve(problem, solver, options, free_keys.len(), y_all.len())?;
293
294    // ── 5/6/7. Post-fit statistics, covariance, and result assembly ──────────
295    postfit::assemble_result(
296        outcome,
297        postfit::PostfitInputs {
298            cg: &cg,
299            graph,
300            datasets: &datasets,
301            x_all: &x_all,
302            y_all: &y_all,
303        },
304        init_fit,
305    )
306}
307
308// ---------------------------------------------------------------------------
309// Private helpers
310// ---------------------------------------------------------------------------
311
312/// Route `solver` to its own module/crate when it is not part of the LM
313/// family, otherwise hand `datasets` back unchanged. Step 0 of [`fit`]'s
314/// sequence, extracted verbatim from the original inline `match`.
315///
316/// Returns [`ControlFlow::Break`] carrying the already-final
317/// `Result<FitResultSpec, CoreError>` for `Irls` / `Global` / `Varpro` / an
318/// `Auto` that prefers VarPro — `fit` returns this immediately. Returns
319/// [`ControlFlow::Continue`] carrying `datasets` handed back unchanged for the
320/// LM family (`Lm` / `LmLegacy` / `Trf` / `Geodesic` / `Dogleg` / `NewtonCg`,
321/// and an `Auto` that does not prefer VarPro) — `fit` falls through to the
322/// shared pre-solve + solve path for these.
323fn dispatch_solver(
324    solver: Solver,
325    graph: &FitGraphSpec,
326    datasets: Vec<MeasurementSpec>,
327    options: &FitOptionsSpec,
328) -> ControlFlow<Result<FitResultSpec, CoreError>, Vec<MeasurementSpec>> {
329    match solver {
330        Solver::Irls(weight) => ControlFlow::Break(solve_irls(
331            graph,
332            datasets,
333            options,
334            weight,
335            DEFAULT_MAX_OUTER_ITER,
336            // The IRLS weight-convergence tolerance is its own constant, not
337            // `options.tolerance` (the LM cost/step/gradient tolerance) — see
338            // `DEFAULT_TOL_WEIGHTS`.
339            DEFAULT_TOL_WEIGHTS,
340        )),
341
342        Solver::Global => {
343            // Honour the caller's iteration budget: map `max_iterations` onto the
344            // number of DE generations. Without this the 500-generation budget the
345            // benchmark passes for pathological cases was silently dropped and DE
346            // ran with the 100-generation default.
347            let config = DeConfig {
348                max_gen: if options.max_iterations > 0 {
349                    options.max_iterations as usize
350                } else {
351                    DeConfig::default().max_gen
352                },
353                ..DeConfig::default()
354            };
355            ControlFlow::Break(solve_global(graph, datasets, options, config))
356        }
357        Solver::Varpro => {
358            // Explicit VarPro: require separability, and reject tied params from
359            // EITHER surface (expr_edges or Parameter.expr) — VarPro reconstructs
360            // parameters from the linear/nonlinear split and never applies the
361            // tied-plan, so a tie would be silently dropped (CX-VPE-01).
362            if !spectrafit_varpro::is_separable(graph) {
363                return ControlFlow::Break(Err(SolverError::VarproNotSeparable.into()));
364            }
365            if graph_has_tied_params(graph) {
366                return ControlFlow::Break(Err(SolverError::VarproExprEdgesUnsupported.into()));
367            }
368            // VarPro stacks all datasets into one synthetic spec and is not
369            // dataset_index-aware, so a per-dataset (local) node would silently
370            // contribute to every dataset. Reject rather than mis-scope; the
371            // LM-family solvers honour dataset_index (simultaneous global analysis).
372            if graph.nodes.iter().any(|n| n.dataset_index.is_some()) {
373                return ControlFlow::Break(
374                    Err(SolverError::VarproDatasetScopingUnsupported.into()),
375                );
376            }
377            // VarPro differentiates its basis functions through the kernels; it has
378            // no graph-level residual Jacobian the forced finite-difference mode
379            // could replace (#93). Reject rather than run analytic derivatives.
380            if options.jacobian == JacobianMode::FiniteDifference {
381                return ControlFlow::Break(Err(
382                    SolverError::VarproFiniteDifferenceUnsupported.into()
383                ));
384            }
385            // Falls through to the shared VarPro tail below, which applies the
386            // post-fit success guards. Do not call `solve_varpro_path` directly
387            // here — see the note on that tail.
388            ControlFlow::Break(run_varpro_guarded(graph, &datasets, options))
389        }
390        // With a forced finite-difference Jacobian `auto` never routes to VarPro
391        // (it cannot honour that mode, see the explicit arm above); it falls
392        // through to TRF like any non-VarPro graph.
393        Solver::Auto
394            if options.jacobian == JacobianMode::Analytic && graph_prefers_varpro(graph) =>
395        {
396            // MUST use the same guarded tail as the explicit `Solver::Varpro`
397            // arm above. This arm previously called `solve_varpro_path` raw,
398            // skipping `finalize_varpro_result` — so on a graph where automatic
399            // routing chooses VarPro, `solver="auto"` reported success on
400            // exactly the degenerate fits `solver="varpro"` reported as failed,
401            // on identical data. `auto` is the documented default, which made
402            // it a silent wrong answer on the recommended path.
403            ControlFlow::Break(run_varpro_guarded(graph, &datasets, options))
404        }
405        // LM family + the Δ-radius methods (and Auto without VarPro) flow through
406        // to the shared pre-solve + solve below.
407        Solver::Lm
408        | Solver::LmLegacy
409        | Solver::Trf
410        | Solver::Geodesic
411        | Solver::Dogleg
412        | Solver::NewtonCg
413        | Solver::Auto => ControlFlow::Continue(datasets),
414    }
415}
416
417/// Bundle of everything the shared LM-family pre-solve step produces (steps
418/// 1/2/3/6/7 of [`fit`]'s sequence: compile the graph, collect free-parameter
419/// specs, evaluate the initial model, and build the index-based node-param
420/// buffers). [`fit`] destructures this into the same flat local bindings the
421/// original inline code used, so field names mirror the original variable
422/// names exactly.
423struct LmPreSolve {
424    /// Compiled DAG (step 1), including `dataset_offsets` for simultaneous
425    /// multi-dataset ("global analysis") fits.
426    cg: CompiledGraph,
427    /// `"node_id.param_name"` for every free parameter, canonical order.
428    free_keys: Vec<String>,
429    /// All parameters (free + fixed), keyed by `"node_id.param_name"`.
430    all_params: HashMap<String, f64>,
431    /// `(min, max)` bounds per free parameter.
432    bounds: Vec<(f64, f64)>,
433    /// Per-free-parameter `Parameter.scale` factors (identity when unset).
434    scales: Vec<f64>,
435    /// Per-point σ (default 1.0 where `MeasurementSpec.sigma` is `None`).
436    sigma: Vec<f64>,
437    /// Point-major concatenated x across all datasets.
438    x_all: Vec<f64>,
439    /// Concatenated y across all datasets.
440    y_all: Vec<f64>,
441    /// The model evaluated at the initial parameters, before optimisation.
442    init_fit: Vec<f64>,
443    /// Initial free-parameter vector in the optimiser's scaled working units.
444    init_params: DVector<f64>,
445    /// Per-node parameter buffers (fixed pre-filled, free updated in-place).
446    node_param_bufs: Vec<Vec<f64>>,
447    /// free-param index → `(node_idx, param_pos)`.
448    free_to_node_param: Vec<(usize, usize)>,
449    /// tied-target index → `(node_idx, param_pos)`.
450    tied_to_node_param: Vec<(usize, usize)>,
451}
452
453/// Compile `graph`, collect free-parameter specs, evaluate the initial model,
454/// and build the index-based node-param buffers — steps 1/2/3/6/7 of [`fit`]'s
455/// sequence, extracted verbatim from the original inline code (including the
456/// `Parameter.scale` wiring doc comment and its `debug_assert_eq!`).
457fn prepare_lm_pre_solve(
458    graph: &FitGraphSpec,
459    datasets: &[MeasurementSpec],
460) -> Result<LmPreSolve, CoreError> {
461    // ── 1. Compile graph ────────────────────────────────────────────────────
462    let mut cg = CompiledGraph::compile(graph)?;
463    // Per-dataset point boundaries (cumulative, len = n_datasets + 1) so the
464    // executor can scope a node with `dataset_index = Some(i)` to dataset i's
465    // contiguous point-range — the primitive for simultaneous multi-dataset
466    // ("global analysis") fits. Left as the single-range no-op for one dataset.
467    cg.dataset_offsets = {
468        let mut offs = Vec::with_capacity(datasets.len() + 1);
469        let mut acc = 0usize;
470        offs.push(0);
471        for ds in datasets {
472            acc += ds.y.len();
473            offs.push(acc);
474        }
475        offs
476    };
477    let free_keys = cg.free_keys.clone();
478
479    // ── 2/3. All-param flat map + initial values/bounds/scales for free params ─
480    let (all_params, init_vals, bounds, scales) = collect_free_param_specs(graph, &free_keys)?;
481
482    let init_vals_clone = init_vals.clone();
483    // The solver optimises the scaled working variable θ'_i = θ_i / s_i, so its
484    // starting point is the physical initial value divided by the scale factor
485    // (a no-op when s_i = 1.0). `node_param_bufs` is still seeded from the
486    // physical `init_vals_clone` below.
487    let init_params = DVector::from_vec(
488        init_vals
489            .iter()
490            .zip(scales.iter())
491            .map(|(&v, &s)| v / s)
492            .collect::<Vec<f64>>(),
493    );
494
495    // ── 4. Build per-point sigma vector (default = 1.0) ─────────────────────
496    let sigma: Vec<f64> = datasets
497        .iter()
498        .flat_map(|ds| {
499            let n = ds.y.len();
500            match &ds.sigma {
501                Some(s) => s.clone(),
502                None => vec![1.0_f64; n],
503            }
504        })
505        .collect();
506
507    // ── 5. Concatenated x and y for all datasets (cached in the problem) ────
508    // Point-major (stride = n_dims) so the executor reads each point's full
509    // coordinate; 1-D reduces to the old per-dataset `ds.x[0]` concatenation.
510    let x_all: Vec<f64> = datasets.iter().flat_map(point_major_x).collect();
511
512    let y_all: Vec<f64> = datasets
513        .iter()
514        .flat_map(|ds| ds.y.iter().copied())
515        .collect();
516
517    // ── 6. Evaluate initial model (before optimisation) ─────────────────────
518    let init_fit = evaluate_compiled(&cg, &all_params, &x_all)?;
519
520    // ── 7. Build index-based node param buffers ──────────────────────────────
521    let (node_param_bufs, free_to_node_param, tied_to_node_param) =
522        build_node_param_buffers(&cg, &all_params, &bounds, &init_vals_clone)?;
523
524    // ── 7b. Per-parameter scale normalization (Parameter.scale → LM step) ─────
525    //
526    // `Parameter.scale` lets a caller request that a parameter be optimised in
527    // rescaled units (e.g. an amplitude ~1e6 alongside a width ~1e-3). The solver
528    // operates on the rescaled variable `θ'_i = θ_i / s_i`, which equalises the
529    // columns of the Jacobian and thereby reshapes — and typically improves — the
530    // conditioning of `JᵀJ` (see the condition-number computation in §11). The
531    // wiring is now end-to-end:
532    //   1. `init_params` (above) is the physical start divided by `scales[i]`,
533    //   2. `LmProblem` carries `scales`; `set_params`/`params` translate between
534    //      scaled (optimiser) and physical (`node_param_bufs`) coordinates and the
535    //      analytic/FD Jacobian columns are multiplied by `scales[i]` (chain rule),
536    //   3. `node_param_bufs` — and hence `to_flat` / the reported result — is
537    //      always physical, so the converged values come back in real units.
538    // The post-fit condition number (§11 of postfit) applies the same column
539    // scaling so it reflects the optimiser's effective conditioning.
540    //
541    // With all-default (None ⇒ 1.0) scales every step above is an exact
542    // arithmetic no-op, so a fit without any `scale` set is byte-for-byte
543    // unchanged — the parity oracle (`tests/parity.rs`) pins this.
544    debug_assert_eq!(
545        scales.len(),
546        free_keys.len(),
547        "one scale factor per free parameter"
548    );
549
550    Ok(LmPreSolve {
551        cg,
552        free_keys,
553        all_params,
554        bounds,
555        scales,
556        sigma,
557        x_all,
558        y_all,
559        init_fit,
560        init_params,
561        node_param_bufs,
562        free_to_node_param,
563        tied_to_node_param,
564    })
565}
566
567/// Initialise tied parameters from the starting free values, then dispatch
568/// `solver` to the matching LM-family engine — extracted verbatim from the
569/// original inline code: `lm-legacy` on the retained nalgebra
570/// `levenberg-marquardt` crate (the parity oracle); `dogleg` / `newton-cg` on
571/// the Δ-radius trust-region drivers; everything else (`lm` / `trf` /
572/// `geodesic` / `auto`) on the faer-native LM core.
573fn run_lm_solve<'a>(
574    mut problem: LmProblem<'a>,
575    solver: Solver,
576    options: &FitOptionsSpec,
577    free_keys_len: usize,
578    y_all_len: usize,
579) -> Result<LmSolveOutcome<'a>, CoreError> {
580    // Initialise tied parameters from the starting free values. `node_param_bufs`
581    // was seeded with the tied-target *placeholders* (their spec `value`, e.g.
582    // 0.0); without this the first residual/Jacobian would evaluate the model
583    // with stale tied values. No-op for graphs without ties (`expr_edges` or `Parameter.expr`).
584    if problem.has_tied() {
585        let p0: Vec<f64> = problem.params.iter().copied().collect();
586        problem.set_free_and_tied(&p0);
587    }
588
589    // `patience` controls max function evaluations = patience * (n_params + 1)
590    let patience = (options.max_iterations as usize).max(1);
591
592    // Solver engine selection. The faer-native trust-region core is the default
593    // for every LM-family solver string (`"lm"`, `"auto"`, `"trf"`, `"geodesic"`);
594    // the proven `levenberg-marquardt` (nalgebra) crate is retained as the
595    // `"lm-legacy"` oracle for parity testing until it is removed.
596    let tol = if options.tolerance > 0.0 {
597        options.tolerance
598    } else {
599        1e-8
600    };
601    let max_nfev = patience.saturating_mul(free_keys_len + 1);
602    let _solve_t0 = std::time::Instant::now();
603    let (
604        result_problem,
605        n_iter_val,
606        success_val,
607        message_val,
608        cost_history,
609        gradient_norm_history,
610        params_history,
611    ) = match solver {
612        Solver::LmLegacy => {
613            // Retained nalgebra `levenberg-marquardt` crate — the parity oracle.
614            // It does not expose a per-iteration trajectory, so the history stays
615            // empty (the benchmark layer reconstructs a labelled proxy).
616            let lm = LevenbergMarquardt::new().with_patience(patience);
617            let lm = if options.tolerance > 0.0 {
618                lm.with_tol(options.tolerance)
619            } else {
620                lm
621            };
622            let (rp, report) = lm.minimize(problem);
623            (
624                rp,
625                report.number_of_evaluations as u64,
626                report.termination.was_successful(),
627                map_termination(&report.termination).as_str().to_string(),
628                Vec::new(),
629                Vec::new(),
630                Vec::new(),
631            )
632        }
633        Solver::Dogleg | Solver::NewtonCg => {
634            // Explicit Δ-radius trust-region methods on the shared framework loop.
635            // `Report`/`Termination` are the same types the faer LM core returns.
636            // Power-user knobs for the TR core: each `Option<f64>` on
637            // `FitOptionsSpec` keeps the library default when `None`, so the wire
638            // surface remains backward-compatible. The TR driver clamps `delta0`
639            // and `max_delta` internally; we just pass through what the caller set.
640            let mut cfg = spectrafit_dogleg::TrustRegionConfig {
641                ftol: tol,
642                xtol: tol,
643                gtol: tol,
644                max_nfev,
645                ..Default::default()
646            };
647            if let Some(d0) = options.delta0 {
648                cfg.delta0 = d0;
649            }
650            if let Some(md) = options.max_delta {
651                cfg.max_delta = md;
652            }
653            if let Some(e) = options.eta {
654                // `TrustRegionConfig::eta` is only `debug_assert!`-checked by
655                // the driver, which compiles out in release builds — this is
656                // the check that actually enforces the bound for callers that
657                // reach the Rust core directly (the JSON `fit` entrypoint),
658                // not just the Pydantic `FitOptions` validator.
659                if !(e.is_finite() && (0.0..0.25).contains(&e)) {
660                    return Err(SolverError::InvalidEta(e).into());
661                }
662                cfg.eta = e;
663            }
664            let report = if solver == Solver::Dogleg {
665                spectrafit_dogleg::minimize(&mut problem, &cfg)
666            } else {
667                spectrafit_newton_cg::minimize(&mut problem, &cfg)
668            };
669            let msg = faer_termination_str(report.termination).to_string();
670            (
671                problem,
672                report.n_iter as u64,
673                report.termination.was_successful(),
674                msg,
675                report.cost_history,
676                report.gradient_norm_history,
677                report.params_history,
678            )
679        }
680        // LM family: lm / trf / geodesic / auto on the faer LM core. Regime-adaptive
681        // (normal equations for tall-skinny, SVD/secular for many-parameter), with
682        // Moré column scaling applied inside the driver.
683        _ => {
684            let cfg = spectrafit_levenberg_marquardt::StrategyConfig {
685                kind: spectrafit_levenberg_marquardt::select_regime(y_all_len, free_keys_len),
686                ftol: tol,
687                xtol: tol,
688                gtol: tol,
689                max_nfev,
690                // `solver="geodesic"` (Transtrum acceleration) — faster on sloppy /
691                // degenerate multi-peak surfaces; otherwise plain faer LM.
692                geodesic: solver == Solver::Geodesic,
693                // `solver="trf"` — Coleman–Li bound-distance scaling, so steps of a
694                // parameter with two finite bounds shrink near the bound it moves
695                // toward. `solver="auto"` that did not
696                // route to VarPro also lands here as TRF: across a representative
697                // case per scenario family, TRF is the fastest LM-family strategy at
698                // top accuracy in most problem classes. The TRF-over-VarPro speed
699                // result may invert for very large separable problems, which is why
700                // VarPro routing is retained for the fully-unconstrained separable
701                // case.
702                bound_scaling: solver == Solver::Trf || solver == Solver::Auto,
703                ..Default::default()
704            };
705            let report = spectrafit_levenberg_marquardt::minimize(&mut problem, &cfg);
706            let msg = faer_termination_str(report.termination).to_string();
707            (
708                problem,
709                report.n_iter as u64,
710                report.termination.was_successful(),
711                msg,
712                report.cost_history,
713                report.gradient_norm_history,
714                report.params_history,
715            )
716        }
717    };
718    let solve_ns = _solve_t0.elapsed().as_nanos();
719
720    Ok(LmSolveOutcome {
721        result_problem,
722        n_iter_val,
723        success_val,
724        message_val,
725        solve_ns,
726        cost_history,
727        gradient_norm_history,
728        params_history,
729    })
730}
731
732/// `(all_params, init_vals, bounds, scales)` — see [`collect_free_param_specs`].
733type FreeParamSpecs = (HashMap<String, f64>, Vec<f64>, Vec<(f64, f64)>, Vec<f64>);
734
735/// `(node_param_bufs, free_to_node_param, tied_to_node_param)` — see
736/// [`build_node_param_buffers`].
737type NodeParamBuffers = (Vec<Vec<f64>>, Vec<(usize, usize)>, Vec<(usize, usize)>);
738
739/// Build the flat all-parameters map (free + fixed) plus per-free-parameter
740/// initial values, bounds, and scale factors.
741///
742/// Returns `(all_params, init_vals, bounds, scales)`, all indexed in `free_keys`
743/// order for the latter three. `scales[i]` defaults to 1.0 (identity — a
744/// non-finite or non-positive `Parameter.scale` is meaningless for
745/// normalization and falls back to the identity too).
746fn collect_free_param_specs(
747    graph: &FitGraphSpec,
748    free_keys: &[String],
749) -> Result<FreeParamSpecs, CoreError> {
750    let mut all_params: HashMap<String, f64> = HashMap::new();
751    for node in &graph.nodes {
752        for (pname, pspec) in &node.parameters {
753            let key = format!("{}.{}", node.id, pname);
754            all_params.insert(key, pspec.value);
755        }
756    }
757
758    let mut init_vals: Vec<f64> = Vec::with_capacity(free_keys.len());
759    let mut bounds: Vec<(f64, f64)> = Vec::with_capacity(free_keys.len());
760    let mut scales: Vec<f64> = Vec::with_capacity(free_keys.len());
761
762    for key in free_keys {
763        // key = "node_id.param_name"
764        let (node_id, param_name) = key
765            .split_once('.')
766            .ok_or_else(|| SolverError::Dispatch(format!("malformed free key: '{}'", key)))?;
767
768        let node = graph
769            .nodes
770            .iter()
771            .find(|n| n.id == node_id)
772            .ok_or_else(|| SolverError::Dispatch(format!("node '{}' not found", node_id)))?;
773
774        let pspec = node.parameters.get(param_name).ok_or_else(|| {
775            SolverError::Dispatch(format!(
776                "param '{}' not found in node '{}'",
777                param_name, node_id
778            ))
779        })?;
780
781        init_vals.push(pspec.value);
782        bounds.push((pspec.min, pspec.max));
783        // A non-finite or non-positive scale is meaningless for normalization;
784        // fall back to the identity (1.0) so it is a no-op.
785        let s = pspec.scale.unwrap_or(1.0);
786        scales.push(if s.is_finite() && s > 0.0 { s } else { 1.0 });
787    }
788
789    Ok((all_params, init_vals, bounds, scales))
790}
791
792/// Build index-based node param buffers, the free→node/param index mapping,
793/// and the tied-target→node/param index mapping.
794///
795/// `node_param_bufs[i]` holds `cg.nodes[i]`'s current param values in model
796/// `param_names()` order — fixed params are pre-filled and never changed;
797/// free params are updated in-place by `LmProblem::set_params()`.
798/// `free_to_node_param` inverts `cg.node_free_cols` (built during `compile()`)
799/// so free-key index → `(node_idx, param_pos_in_node)`, and is used here to
800/// apply the initial bounds-clamp to `node_param_bufs`. `tied_to_node_param`
801/// maps each tied target (`tied_plan.order`) to its `(node_idx, param_pos)`
802/// slot so the solver can write each recomputed tied value back — empty when
803/// the graph declares no ties (`expr_edges` or `Parameter.expr`).
804fn build_node_param_buffers(
805    cg: &CompiledGraph,
806    all_params: &HashMap<String, f64>,
807    bounds: &[(f64, f64)],
808    init_vals_clone: &[f64],
809) -> Result<NodeParamBuffers, CoreError> {
810    let mut node_param_bufs: Vec<Vec<f64>> = (0..cg.nodes.len())
811        .map(|i| {
812            cg.node_params(i, all_params)
813                .unwrap_or_else(|_| vec![0.0; cg.nodes[i].param_names.len()])
814        })
815        .collect();
816
817    let free_to_node_param: Vec<(usize, usize)> = {
818        // Invert node_free_cols: for each free_key index (col), find the
819        // (node_idx, local_param_idx) pair.
820        let mut mapping = vec![(0usize, 0usize); cg.free_keys.len()];
821        for (node_idx, pairs) in cg.node_free_cols.iter().enumerate() {
822            for &(local_idx, col) in pairs {
823                mapping[col] = (node_idx, local_idx);
824            }
825        }
826        mapping
827    };
828
829    // Apply initial bounds clamping to node_param_bufs for free params.
830    for (i, &(node_idx, param_pos)) in free_to_node_param.iter().enumerate() {
831        let (lo, hi) = bounds[i];
832        node_param_bufs[node_idx][param_pos] = init_vals_clone[i].clamp(lo, hi);
833    }
834
835    let tied_to_node_param: Vec<(usize, usize)> = cg
836        .tied_plan
837        .order
838        .iter()
839        .map(|tp| {
840            let (nid, pname) = tp
841                .target
842                .split_once('.')
843                .ok_or_else(|| SolverError::MalformedTiedTarget(tp.target.clone()))?;
844            let ni = cg
845                .nodes
846                .iter()
847                .position(|n| n.id == nid)
848                .ok_or_else(|| SolverError::TiedTargetNodeMissing(nid.to_string()))?;
849            let pos = cg.nodes[ni]
850                .param_names
851                .iter()
852                .position(|p| p == pname)
853                .ok_or_else(|| SolverError::TiedTargetParamMissing(pname.to_string()))?;
854            Ok::<(usize, usize), CoreError>((ni, pos))
855        })
856        .collect::<Result<_, _>>()?;
857
858    Ok((node_param_bufs, free_to_node_param, tied_to_node_param))
859}
860
861/// Run the VarPro path and apply the shared post-fit success guards.
862///
863/// Both VarPro entry points — the explicit `Solver::Varpro` arm and the
864/// `Solver::Auto` arm when `graph_prefers_varpro` — must route through here.
865/// They are separate match arms because they have different *preconditions*
866/// (explicit VarPro rejects non-separable/tied/dataset-scoped graphs with a
867/// specific error; automatic routing only reaches VarPro when the graph already
868/// qualifies), but they must share the same *postcondition*. Keeping the guard
869/// in one function is what makes "the two solver strings agree on `success`"
870/// structural rather than a thing to remember.
871fn run_varpro_guarded(
872    graph: &FitGraphSpec,
873    datasets: &[MeasurementSpec],
874    options: &FitOptionsSpec,
875) -> Result<FitResultSpec, CoreError> {
876    let result = solve_varpro_path(graph, datasets, options)?;
877    Ok(finalize_varpro_result(graph, datasets, result))
878}
879
880/// Apply the shared post-fit success guards (off-domain runaway + degenerate
881/// peak-collapse) to a VarPro result.
882///
883/// VarPro builds its own [`FitResultSpec`] outside `postfit::assemble_result`
884/// (it has no `LmProblem`/covariance path to hang off), so this re-derives the
885/// inputs `apply_postfit_guards` needs — free-key list, flat parameter map,
886/// concatenated x/y — from the already-assembled `result` and applies the same
887/// guard the LM-family path gets for free. Without this a degenerate VarPro
888/// fit would report false success.
889fn finalize_varpro_result(
890    graph: &FitGraphSpec,
891    datasets: &[MeasurementSpec],
892    mut result: FitResultSpec,
893) -> FitResultSpec {
894    let x_all: Vec<f64> = datasets.iter().flat_map(point_major_x).collect();
895    let y_all: Vec<f64> = datasets
896        .iter()
897        .flat_map(|ds| ds.y.iter().copied())
898        .collect();
899    let final_flat: HashMap<String, f64> = result
900        .parameters
901        .iter()
902        .map(|(k, p)| (k.clone(), p.value))
903        .collect();
904    let vp_free_keys: Vec<String> = result
905        .parameters
906        .iter()
907        .filter(|(_, p)| p.vary)
908        .map(|(k, _)| k.clone())
909        .collect();
910    let (success, message) = postfit::apply_postfit_guards(
911        graph,
912        &vp_free_keys,
913        &final_flat,
914        &x_all,
915        &y_all,
916        result.r_squared,
917        vp_free_keys.len(),
918        result.success,
919        result.message.clone(),
920    );
921    result.success = success;
922    result.message = message;
923    result
924}
925
926/// Stable snake_case message for a faer-native [`spectrafit_levenberg_marquardt::Termination`].
927fn faer_termination_str(t: spectrafit_levenberg_marquardt::Termination) -> &'static str {
928    use spectrafit_levenberg_marquardt::Termination as T;
929    match t {
930        T::Gtol => "converged_gtol",
931        T::Ftol => "converged_ftol",
932        T::Xtol => "converged_xtol",
933        T::ResidualsZero => "residuals_zero",
934        T::MaxEval => "max_iterations",
935        T::NoImprovement => "no_improvement_possible",
936        T::NumericalError => "numerical_error",
937    }
938}
939
940/// Map the `levenberg_marquardt` crate's `TerminationReason` onto our own
941/// stable enum so callers get a deterministic snake_case string, not a
942/// debug-format blob that changes with crate versions.
943fn map_termination(lm: &levenberg_marquardt::TerminationReason) -> TerminationReason {
944    use levenberg_marquardt::TerminationReason as L;
945    match lm {
946        L::ResidualsZero => TerminationReason::ResidualsZero,
947        L::Orthogonal => TerminationReason::Orthogonal,
948        L::Converged { .. } => TerminationReason::Converged,
949        L::LostPatience => TerminationReason::MaxIterations,
950        L::NoImprovementPossible(_) => TerminationReason::NoImprovementPossible,
951        L::NoParameters => TerminationReason::NoParameters,
952        L::NoResiduals => TerminationReason::NoResiduals,
953        L::WrongDimensions(_) => TerminationReason::WrongDimensions,
954        L::Numerical(_) => TerminationReason::NumericalError,
955        L::User(_) => TerminationReason::UserCancelled,
956    }
957}
958
959// ---------------------------------------------------------------------------
960// Tests
961// ---------------------------------------------------------------------------
962#[cfg(test)]
963mod tests {
964    use super::*;
965    use approx::assert_relative_eq;
966    use spectrafit_types::{
967        FitGraphSpec, FitOptionsSpec, MeasurementSpec, ModelNodeSpec, ModelTypeStr, ParameterSpec,
968    };
969    use std::collections::HashMap;
970
971    // ── helpers ──────────────────────────────────────────────────────────────
972
973    fn make_param(value: f64, vary: bool) -> ParameterSpec {
974        ParameterSpec {
975            value,
976            min: f64::NEG_INFINITY,
977            max: f64::INFINITY,
978            vary,
979            expr: None,
980            scale: None,
981        }
982    }
983
984    fn default_options() -> FitOptionsSpec {
985        FitOptionsSpec {
986            schema_version: None,
987            solver: "lm".to_string(),
988            max_iterations: 200,
989            tolerance: 1e-8,
990            delta0: None,
991            max_delta: None,
992            eta: None,
993            jacobian: JacobianMode::Analytic,
994        }
995    }
996
997    /// Analytical Gaussian: A · exp(−(x−c)² / (2σ²))
998    fn gaussian(x: f64, amplitude: f64, center: f64, sigma: f64) -> f64 {
999        amplitude * (-(x - center).powi(2) / (2.0 * sigma * sigma)).exp()
1000    }
1001
1002    // ── Test 1: Gaussian parameter recovery ──────────────────────────────────
1003
1004    #[test]
1005    fn test_gaussian_recovery() {
1006        // True parameters
1007        let (true_a, true_c, true_s) = (5.0_f64, 2.0_f64, 0.5_f64);
1008
1009        // x grid: 50 points in [−1, 5]
1010        let n = 50usize;
1011        let x: Vec<f64> = (0..n)
1012            .map(|i| -1.0 + 6.0 * i as f64 / (n - 1) as f64)
1013            .collect();
1014        let y: Vec<f64> = x
1015            .iter()
1016            .map(|&xi| gaussian(xi, true_a, true_c, true_s))
1017            .collect();
1018
1019        // Graph with perturbed initial params
1020        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1021        params.insert("amplitude".into(), make_param(4.0, true));
1022        params.insert("center".into(), make_param(1.8, true));
1023        params.insert("sigma".into(), make_param(0.6, true));
1024
1025        let graph = FitGraphSpec {
1026            schema_version: "0.1".into(),
1027            nodes: vec![ModelNodeSpec {
1028                id: "g1".into(),
1029                model_type: ModelTypeStr::Gaussian,
1030                dataset_index: None,
1031                parameters: params,
1032            }],
1033            expr_edges: vec![],
1034        };
1035
1036        let dataset = MeasurementSpec {
1037            schema_version: None,
1038            x: vec![x],
1039            y,
1040            sigma: None,
1041            label: None,
1042        };
1043
1044        let result = fit(&graph, vec![dataset], &default_options()).expect("fit should not error");
1045
1046        assert!(
1047            result.success,
1048            "LM should converge; message: {}",
1049            result.message
1050        );
1051        assert!(
1052            result.n_iter > 0,
1053            "should have done at least one evaluation"
1054        );
1055        assert!(
1056            result.chi2 < 1e-10,
1057            "chi2 = {} should be near zero",
1058            result.chi2
1059        );
1060
1061        let a = result.parameters["g1.amplitude"].value;
1062        let c = result.parameters["g1.center"].value;
1063        let s = result.parameters["g1.sigma"].value;
1064
1065        assert_relative_eq!(a, true_a, max_relative = 0.01);
1066        assert_relative_eq!(c, true_c, max_relative = 0.01);
1067        assert_relative_eq!(s, true_s, max_relative = 0.01);
1068    }
1069
1070    // ── Test: unrecognised `solver`/weight-fn strings are rejected, not
1071    //    silently defaulted ────────────────────────────────────────────────
1072    //
1073    // Before this fix, `Solver::parse` silently mapped ANY unrecognised
1074    // string to `Solver::Lm` (and `WeightFn::from_str` silently mapped any
1075    // unrecognised name to Huber) — a typo like `solver="lmm"` ran a fit
1076    // with the LM solver instead of erroring, which could hide a
1077    // misconfigured request behind a plausible-looking successful result.
1078
1079    #[test]
1080    fn fit_rejects_unrecognised_solver_string_instead_of_defaulting_to_lm() {
1081        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1082        params.insert("amplitude".into(), make_param(4.0, true));
1083        params.insert("center".into(), make_param(1.8, true));
1084        params.insert("sigma".into(), make_param(0.6, true));
1085        let graph = FitGraphSpec {
1086            schema_version: "0.1".into(),
1087            nodes: vec![ModelNodeSpec {
1088                id: "g1".into(),
1089                model_type: ModelTypeStr::Gaussian,
1090                dataset_index: None,
1091                parameters: params,
1092            }],
1093            expr_edges: vec![],
1094        };
1095        let dataset = MeasurementSpec {
1096            schema_version: None,
1097            x: vec![vec![0.0, 1.0, 2.0]],
1098            y: vec![1.0, 2.0, 1.0],
1099            sigma: None,
1100            label: None,
1101        };
1102        let opts = FitOptionsSpec {
1103            solver: "lmm".to_string(), // typo for "lm"
1104            ..default_options()
1105        };
1106
1107        let err = fit(&graph, vec![dataset], &opts)
1108            .expect_err("a typo'd solver name must error, not silently run LM");
1109        let msg = err.to_string();
1110        assert!(
1111            msg.contains("lmm"),
1112            "error should name the offending string, got: {msg}"
1113        );
1114        assert!(
1115            msg.contains("expected one of"),
1116            "error should list valid solver names, got: {msg}"
1117        );
1118    }
1119
1120    // ── Test: `eta >= 0.25` is rejected on the JSON/Rust path, not just by
1121    //    the Pydantic `Field(ge=0.0, lt=0.25)` validator ─────────────────────
1122    //
1123    // Before this fix, `FitOptionsSpec.eta` was only bounds-checked in
1124    // `python/spectrafit_core/options.py`; a caller reaching the Rust core
1125    // directly (the JSON `fit` entrypoint, or any non-Python consumer) could
1126    // set `eta >= 0.25`, which the trust-region driver only caught with a
1127    // `debug_assert!` that compiles out of release builds — so a release
1128    // build silently ran with the invalid ratio.
1129
1130    #[test]
1131    fn fit_rejects_eta_at_or_above_a_quarter_on_dogleg() {
1132        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1133        params.insert("amplitude".into(), make_param(4.0, true));
1134        params.insert("center".into(), make_param(1.8, true));
1135        params.insert("sigma".into(), make_param(0.6, true));
1136        let graph = FitGraphSpec {
1137            schema_version: "0.1".into(),
1138            nodes: vec![ModelNodeSpec {
1139                id: "g1".into(),
1140                model_type: ModelTypeStr::Gaussian,
1141                dataset_index: None,
1142                parameters: params,
1143            }],
1144            expr_edges: vec![],
1145        };
1146        let dataset = MeasurementSpec {
1147            schema_version: None,
1148            x: vec![vec![0.0, 1.0, 2.0]],
1149            y: vec![1.0, 2.0, 1.0],
1150            sigma: None,
1151            label: None,
1152        };
1153        let opts = FitOptionsSpec {
1154            solver: "dogleg".to_string(),
1155            eta: Some(0.5),
1156            ..default_options()
1157        };
1158
1159        let err = fit(&graph, vec![dataset], &opts)
1160            .expect_err("eta >= 0.25 must error, not silently run with an invalid ratio");
1161        let msg = err.to_string();
1162        assert!(
1163            msg.contains("eta"),
1164            "error should name the offending option, got: {msg}"
1165        );
1166    }
1167
1168    #[test]
1169    fn fit_rejects_unrecognised_irls_weight_fn_instead_of_defaulting_to_huber() {
1170        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1171        params.insert("amplitude".into(), make_param(4.0, true));
1172        params.insert("center".into(), make_param(1.8, true));
1173        params.insert("sigma".into(), make_param(0.6, true));
1174        let graph = FitGraphSpec {
1175            schema_version: "0.1".into(),
1176            nodes: vec![ModelNodeSpec {
1177                id: "g1".into(),
1178                model_type: ModelTypeStr::Gaussian,
1179                dataset_index: None,
1180                parameters: params,
1181            }],
1182            expr_edges: vec![],
1183        };
1184        let dataset = MeasurementSpec {
1185            schema_version: None,
1186            x: vec![vec![0.0, 1.0, 2.0]],
1187            y: vec![1.0, 2.0, 1.0],
1188            sigma: None,
1189            label: None,
1190        };
1191        let opts = FitOptionsSpec {
1192            solver: "irls:buisquare".to_string(), // typo for "bisquare"
1193            ..default_options()
1194        };
1195
1196        let err = fit(&graph, vec![dataset], &opts)
1197            .expect_err("a typo'd irls weight-fn name must error, not silently run Huber");
1198        let msg = err.to_string();
1199        assert!(
1200            msg.contains("buisquare"),
1201            "error should name the offending string, got: {msg}"
1202        );
1203    }
1204
1205    // ── Test 2: Constant model trivial fit ────────────────────────────────────
1206
1207    #[test]
1208    fn test_constant_recovery() {
1209        let n = 20usize;
1210        let x: Vec<f64> = (0..n).map(|i| i as f64 / (n - 1) as f64).collect();
1211        // Tiny deterministic "noise" to avoid a perfectly flat problem
1212        let y: Vec<f64> = x
1213            .iter()
1214            .enumerate()
1215            .map(|(i, _)| 3.0 + 1e-6 * (i as f64 * 0.1).sin())
1216            .collect();
1217
1218        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1219        params.insert("c".into(), make_param(0.0, true)); // start far from 3
1220
1221        let graph = FitGraphSpec {
1222            schema_version: "0.1".into(),
1223            nodes: vec![ModelNodeSpec {
1224                id: "const1".into(),
1225                model_type: ModelTypeStr::Constant,
1226                dataset_index: None,
1227                parameters: params,
1228            }],
1229            expr_edges: vec![],
1230        };
1231
1232        let dataset = MeasurementSpec {
1233            schema_version: None,
1234            x: vec![x],
1235            y,
1236            sigma: None,
1237            label: None,
1238        };
1239
1240        let result = fit(&graph, vec![dataset], &default_options()).expect("fit should not error");
1241
1242        assert!(
1243            result.success,
1244            "LM should converge; message: {}",
1245            result.message
1246        );
1247
1248        let c_val = result.parameters["const1.c"].value;
1249        assert!(
1250            (c_val - 3.0).abs() < 1e-4,
1251            "recovered constant = {}, expected ≈ 3.0",
1252            c_val
1253        );
1254    }
1255
1256    // ── SP-2: N-D (gaussian_nd) end-to-end fits ───────────────────────────────
1257    //
1258    // The compiler infers D from the node's `center_<i>` parameters and builds a
1259    // `GaussianND` of that dimensionality; the N-D-general executor strides the
1260    // coordinate buffer at stride D and the LM solver recovers every parameter.
1261    // Both 3-D and 5-D run, so "arbitrary N" is exercised, not extrapolated.
1262    fn run_gaussian_nd_recovery(d: usize) {
1263        let amp = 3.0_f64;
1264        let centers: Vec<f64> = (0..d).map(|i| -1.0 + 0.5 * i as f64).collect();
1265        let sigmas: Vec<f64> = (0..d).map(|i| 0.8 + 0.1 * i as f64).collect();
1266
1267        // Keep the grid tiny so d=5 stays cheap (5^5 = 3125 points).
1268        let axis_n = if d <= 3 { 7 } else { 5 };
1269        let axis: Vec<f64> = (0..axis_n)
1270            .map(|i| -3.0 + 6.0 * i as f64 / (axis_n - 1) as f64)
1271            .collect();
1272        // Cartesian product of the axis over d dimensions → point coordinates.
1273        let mut coords: Vec<Vec<f64>> = vec![vec![]];
1274        for _dim in 0..d {
1275            let mut next = Vec::with_capacity(coords.len() * axis.len());
1276            for prefix in &coords {
1277                for &a in &axis {
1278                    let mut p = prefix.clone();
1279                    p.push(a);
1280                    next.push(p);
1281                }
1282            }
1283            coords = next;
1284        }
1285        let g = |pt: &[f64]| -> f64 {
1286            let mut z = 0.0;
1287            for i in 0..d {
1288                let dx = pt[i] - centers[i];
1289                z -= dx * dx / (2.0 * sigmas[i] * sigmas[i]);
1290            }
1291            amp * z.exp()
1292        };
1293        let y: Vec<f64> = coords.iter().map(|pt| g(pt)).collect();
1294        let n_points = coords.len();
1295        // Dimension-major x: x[dim] is the coordinate array for axis `dim`.
1296        let x: Vec<Vec<f64>> = (0..d)
1297            .map(|dim| (0..n_points).map(|p| coords[p][dim]).collect())
1298            .collect();
1299
1300        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1301        params.insert("amplitude".into(), make_param(2.0, true));
1302        for (i, &center) in centers.iter().enumerate() {
1303            params.insert(format!("center_{i}"), make_param(center + 0.3, true));
1304            params.insert(format!("sigma_{i}"), make_param(1.0, true));
1305        }
1306        let graph = FitGraphSpec {
1307            schema_version: "0.1".into(),
1308            nodes: vec![ModelNodeSpec {
1309                id: "gnd".into(),
1310                model_type: ModelTypeStr::GaussianNd,
1311                dataset_index: None,
1312                parameters: params,
1313            }],
1314            expr_edges: vec![],
1315        };
1316        let dataset = MeasurementSpec {
1317            schema_version: None,
1318            x,
1319            y,
1320            sigma: None,
1321            label: None,
1322        };
1323        let result =
1324            fit(&graph, vec![dataset], &default_options()).expect("N-D fit should not error");
1325        assert!(
1326            result.success,
1327            "LM should converge on {d}-D; msg: {}",
1328            result.message
1329        );
1330        let p = &result.parameters;
1331        assert_relative_eq!(p["gnd.amplitude"].value, amp, max_relative = 0.02);
1332        for i in 0..d {
1333            assert_relative_eq!(
1334                p[&format!("gnd.center_{i}")].value,
1335                centers[i],
1336                epsilon = 0.05
1337            );
1338            assert_relative_eq!(
1339                p[&format!("gnd.sigma_{i}")].value,
1340                sigmas[i],
1341                epsilon = 0.05
1342            );
1343        }
1344    }
1345
1346    #[test]
1347    fn gaussian_nd_fit_recovers_3d() {
1348        run_gaussian_nd_recovery(3);
1349    }
1350
1351    #[test]
1352    fn gaussian_nd_fit_recovers_5d_arbitrary_n() {
1353        run_gaussian_nd_recovery(5);
1354    }
1355
1356    // ── TDD: tied-parameter (expr_edge) end-to-end fit ────────────────────────
1357    //
1358    // The compiler builds a dependency-ordered `tied_plan` (parse +
1359    // topo-order + cycle-detection). The LM solver loop calls `TiedPlan::apply`
1360    // on every iteration, so tied parameters are recomputed from `expr_edges` and
1361    // `Parameter.expr` at each step. These tests run unconditionally and pass.
1362
1363    /// Build a two-Gaussian graph where `g2.amplitude = k * g1.amplitude`.
1364    ///
1365    /// The tie is expressed through the top-level `expr_edge` list only.
1366    /// `ParameterSpec.expr` is intentionally `None` on the tied amplitude so
1367    /// this helper exercises the legacy `expr_edge` path without triggering the
1368    /// `DuplicateExprTarget` error that T1 introduced when both routes target
1369    /// the same parameter.
1370    fn tied_two_gaussian_graph(k: f64) -> FitGraphSpec {
1371        let mut g1: HashMap<String, ParameterSpec> = HashMap::new();
1372        g1.insert("amplitude".into(), make_param(4.0, true));
1373        g1.insert("center".into(), make_param(-1.0, true));
1374        g1.insert("sigma".into(), make_param(0.5, true));
1375
1376        let mut g2: HashMap<String, ParameterSpec> = HashMap::new();
1377        // `vary = false`, `expr = None` — the tie lives in expr_edges below.
1378        g2.insert("amplitude".into(), make_param(0.0, false));
1379        g2.insert("center".into(), make_param(1.0, true));
1380        g2.insert("sigma".into(), make_param(0.5, true));
1381
1382        FitGraphSpec {
1383            schema_version: "0.1".into(),
1384            nodes: vec![
1385                ModelNodeSpec {
1386                    id: "g1".into(),
1387                    model_type: ModelTypeStr::Gaussian,
1388                    dataset_index: None,
1389                    parameters: g1,
1390                },
1391                ModelNodeSpec {
1392                    id: "g2".into(),
1393                    model_type: ModelTypeStr::Gaussian,
1394                    dataset_index: None,
1395                    parameters: g2,
1396                },
1397            ],
1398            expr_edges: vec![spectrafit_types::ExprEdge {
1399                target_node: "g2".into(),
1400                target_param: "amplitude".into(),
1401                expression: format!("{} * g1.amplitude", k),
1402            }],
1403        }
1404    }
1405
1406    /// A tied fit recovers `g2.amplitude == k * g1.amplitude` (wired in M6).
1407    #[test]
1408    fn test_tied_amplitude_fit_recovers_ratio() {
1409        let k = 0.5_f64;
1410        let (true_a, true_s) = (5.0_f64, 0.5_f64);
1411        let n = 80usize;
1412        let x: Vec<f64> = (0..n)
1413            .map(|i| -3.0 + 6.0 * i as f64 / (n - 1) as f64)
1414            .collect();
1415        let y: Vec<f64> = x
1416            .iter()
1417            .map(|&xi| gaussian(xi, true_a, -1.0, true_s) + gaussian(xi, k * true_a, 1.0, true_s))
1418            .collect();
1419
1420        let graph = tied_two_gaussian_graph(k);
1421        let dataset = MeasurementSpec {
1422            schema_version: None,
1423            x: vec![x],
1424            y,
1425            sigma: None,
1426            label: None,
1427        };
1428        let result = fit(&graph, vec![dataset], &default_options()).unwrap();
1429
1430        assert!(
1431            result.success,
1432            "tied fit should converge: {}",
1433            result.message
1434        );
1435        let a1 = result.parameters["g1.amplitude"].value;
1436        let a2 = result.parameters["g2.amplitude"].value;
1437        // The tied plan enforces the ratio exactly each iteration…
1438        assert_relative_eq!(a2, k * a1, epsilon = 1e-9);
1439        // …and the free amplitude is recovered.
1440        assert_relative_eq!(a1, true_a, max_relative = 1e-3);
1441    }
1442
1443    /// End-to-end proof that a `Parameter.expr`-only tie (no `expr_edge`) is
1444    /// honoured by the solver — the tied parameter tracks its derived value at
1445    /// the converged solution, not its initial placeholder.
1446    ///
1447    /// The graph expresses `g2.amplitude = 0.5 * g1.amplitude` purely through
1448    /// `ParameterSpec.expr`; the `expr_edges` list is intentionally **empty**.
1449    /// T1 folds `Parameter.expr` into the compiled `TiedPlan`, and the solver
1450    /// calls `set_free_and_tied` each iteration, so `g2.amplitude` is recomputed
1451    /// from the current `g1.amplitude` on every step.
1452    #[test]
1453    fn test_param_expr_fit_recovers_derived_value() {
1454        let k = 0.5_f64;
1455        let (true_a, true_s) = (5.0_f64, 0.5_f64);
1456        let n = 80usize;
1457        let x: Vec<f64> = (0..n)
1458            .map(|i| -3.0 + 6.0 * i as f64 / (n - 1) as f64)
1459            .collect();
1460        // Synthesise data from the known-true parameters consistent with the tie.
1461        let y: Vec<f64> = x
1462            .iter()
1463            .map(|&xi| gaussian(xi, true_a, -1.0, true_s) + gaussian(xi, k * true_a, 1.0, true_s))
1464            .collect();
1465
1466        // Build a graph identical to `tied_two_gaussian_graph(k)` **except** the
1467        // `expr_edges` list is empty — the tie lives solely in `Parameter.expr`.
1468        let mut g1: HashMap<String, ParameterSpec> = HashMap::new();
1469        g1.insert("amplitude".into(), make_param(4.0, true));
1470        g1.insert("center".into(), make_param(-1.0, true));
1471        g1.insert("sigma".into(), make_param(0.5, true));
1472
1473        let mut g2: HashMap<String, ParameterSpec> = HashMap::new();
1474        let mut tied_amp = make_param(0.0, false);
1475        tied_amp.expr = Some(format!("{} * g1.amplitude", k));
1476        g2.insert("amplitude".into(), tied_amp);
1477        g2.insert("center".into(), make_param(1.0, true));
1478        g2.insert("sigma".into(), make_param(0.5, true));
1479
1480        let graph = FitGraphSpec {
1481            schema_version: "0.1".into(),
1482            nodes: vec![
1483                ModelNodeSpec {
1484                    id: "g1".into(),
1485                    model_type: ModelTypeStr::Gaussian,
1486                    dataset_index: None,
1487                    parameters: g1,
1488                },
1489                ModelNodeSpec {
1490                    id: "g2".into(),
1491                    model_type: ModelTypeStr::Gaussian,
1492                    dataset_index: None,
1493                    parameters: g2,
1494                },
1495            ],
1496            // Intentionally empty — the tie is expressed only via Parameter.expr.
1497            expr_edges: vec![],
1498        };
1499
1500        let dataset = MeasurementSpec {
1501            schema_version: None,
1502            x: vec![x],
1503            y,
1504            sigma: None,
1505            label: None,
1506        };
1507        let result = fit(&graph, vec![dataset], &default_options()).unwrap();
1508
1509        assert!(
1510            result.success,
1511            "param-expr tied fit should converge: {}",
1512            result.message
1513        );
1514        let a1 = result.parameters["g1.amplitude"].value;
1515        let a2 = result.parameters["g2.amplitude"].value;
1516        // `g2.amplitude` must equal `k * g1.amplitude` at the solution — not
1517        // the initial placeholder (0.0).
1518        assert!(
1519            a2.abs() > 1e-6,
1520            "tied param must not be frozen at placeholder 0.0"
1521        );
1522        assert_relative_eq!(a2, k * a1, epsilon = 1e-9);
1523        // The free amplitude must recover the ground truth.
1524        assert_relative_eq!(a1, true_a, max_relative = 1e-3);
1525    }
1526
1527    /// The tied parameter is excluded from the free set, so the solver reports
1528    /// DOF = n_points − n_free with n_free reduced by the tied count.
1529    #[test]
1530    fn test_tied_fit_reduces_free_param_count() {
1531        let graph = tied_two_gaussian_graph(0.5);
1532        let cg = CompiledGraph::compile(&graph).unwrap();
1533        // 6 params total, 1 tied (g2.amplitude) → 5 free.
1534        assert_eq!(cg.free_keys.len(), 5);
1535        assert_eq!(cg.tied_plan.len(), 1);
1536    }
1537
1538    // ── Helper: build a well-conditioned single-Gaussian fit problem ──────────
1539
1540    /// Returns a graph + dataset that recovers a clean Gaussian. `scale` is a
1541    /// base `Parameter.scale` factor (`None` ⇒ all parameters unset, i.e. 1.0).
1542    ///
1543    /// When `Some(base)`, a deliberately **non-uniform** scale is applied across
1544    /// the three parameters — `amplitude·base`, `center` unscaled, `sigma/base`.
1545    /// This is intentional: a *uniform* column scaling `J → J·(s·I)` multiplies
1546    /// `JᵀJ` by `s²` and leaves `κ(JᵀJ) = σ_max/σ_min` exactly invariant, so it
1547    /// could never change the reported conditioning. Spreading the scale across
1548    /// the columns changes their relative norms, which is what actually reshapes
1549    /// `κ(JᵀJ)` (see `parameter_scale_changes_effective_conditioning`).
1550    fn gaussian_fit_inputs(scale: Option<f64>) -> (FitGraphSpec, MeasurementSpec) {
1551        let (true_a, true_c, true_s) = (5.0_f64, 2.0_f64, 0.5_f64);
1552        let n = 50usize;
1553        let x: Vec<f64> = (0..n)
1554            .map(|i| -1.0 + 6.0 * i as f64 / (n - 1) as f64)
1555            .collect();
1556        let y: Vec<f64> = x
1557            .iter()
1558            .map(|&xi| gaussian(xi, true_a, true_c, true_s))
1559            .collect();
1560
1561        let mk = |value: f64, scale: Option<f64>| ParameterSpec {
1562            value,
1563            min: f64::NEG_INFINITY,
1564            max: f64::INFINITY,
1565            vary: true,
1566            expr: None,
1567            scale,
1568        };
1569        // Non-uniform scale spread (see doc comment) so κ(JᵀJ) genuinely changes.
1570        let (sa, sc, ss) = match scale {
1571            None => (None, None, None),
1572            Some(base) => (Some(base), Some(1.0), Some(1.0 / base)),
1573        };
1574        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1575        params.insert("amplitude".into(), mk(4.0, sa));
1576        params.insert("center".into(), mk(1.8, sc));
1577        params.insert("sigma".into(), mk(0.6, ss));
1578
1579        let graph = FitGraphSpec {
1580            schema_version: "0.1".into(),
1581            nodes: vec![ModelNodeSpec {
1582                id: "g1".into(),
1583                model_type: ModelTypeStr::Gaussian,
1584                dataset_index: None,
1585                parameters: params,
1586            }],
1587            expr_edges: vec![],
1588        };
1589        let dataset = MeasurementSpec {
1590            schema_version: None,
1591            x: vec![x],
1592            y,
1593            sigma: None,
1594            label: None,
1595        };
1596        (graph, dataset)
1597    }
1598
1599    // ── GREEN: condition number is computed end-to-end through the LM path ────
1600
1601    #[test]
1602    fn condition_number_is_some_and_finite_after_gaussian_fit() {
1603        let (graph, dataset) = gaussian_fit_inputs(None);
1604        let result = fit(&graph, vec![dataset], &default_options()).expect("fit should not error");
1605        let cond = result
1606            .condition_number
1607            .expect("well-conditioned Gaussian fit should report a condition number");
1608        assert!(cond.is_finite(), "condition number must be finite: {cond}");
1609        assert!(cond >= 1.0, "condition number must be ≥ 1.0: {cond}");
1610    }
1611
1612    // ── U3: Parameter.scale is wired into the LM step / Jacobian ──────────────
1613
1614    #[test]
1615    fn parameter_scale_changes_effective_conditioning() {
1616        // Same problem, once unscaled and once with a deliberately non-uniform
1617        // `Parameter.scale` spread across the free parameters (see
1618        // `gaussian_fit_inputs`). With scale wired into the LM step and Jacobian,
1619        // the reported condition number must differ — the per-column scaling
1620        // reshapes the columns of J and hence κ(JᵀJ). (A *uniform* scale would be
1621        // κ-invariant, which is why the helper spreads it across columns.)
1622        let (g_unscaled, d_unscaled) = gaussian_fit_inputs(None);
1623        let (g_scaled, d_scaled) = gaussian_fit_inputs(Some(1000.0));
1624
1625        let r_unscaled =
1626            fit(&g_unscaled, vec![d_unscaled], &default_options()).expect("unscaled fit");
1627        let r_scaled = fit(&g_scaled, vec![d_scaled], &default_options()).expect("scaled fit");
1628
1629        let c0 = r_unscaled
1630            .condition_number
1631            .expect("unscaled fit should report κ");
1632        let c1 = r_scaled
1633            .condition_number
1634            .expect("scaled fit should report κ");
1635        assert!(
1636            (c0 - c1).abs() > 1e-6,
1637            "Parameter.scale should change effective conditioning: κ_unscaled={c0}, κ_scaled={c1}"
1638        );
1639    }
1640
1641    #[test]
1642    fn parameter_scale_of_one_is_a_bitwise_no_op() {
1643        // The parity contract: `scale = Some(1.0)` on every free parameter must be
1644        // byte-for-byte identical to `scale = None` (the un-scaled path). Every
1645        // scaling operation reduces to multiply/divide by 1.0, which is exact in
1646        // IEEE-754, so the reported κ — and the recovered parameters — must match
1647        // to the last bit, not merely within a tolerance.
1648        let (g_none, d_none) = gaussian_fit_inputs(None);
1649        let g_one = {
1650            let mut g = g_none.clone();
1651            for p in g.nodes[0].parameters.values_mut() {
1652                p.scale = Some(1.0);
1653            }
1654            g
1655        };
1656
1657        let r_none = fit(&g_none, vec![d_none.clone()], &default_options()).expect("none fit");
1658        let r_one = fit(&g_one, vec![d_none], &default_options()).expect("scale=1 fit");
1659
1660        assert_eq!(
1661            r_none.condition_number, r_one.condition_number,
1662            "scale=Some(1.0) must reproduce the un-scaled κ bit-for-bit"
1663        );
1664        for (key, p_none) in &r_none.parameters {
1665            let p_one = &r_one.parameters[key];
1666            assert_eq!(
1667                p_none.value, p_one.value,
1668                "scale=1 changed converged value of {key}: {} vs {}",
1669                p_none.value, p_one.value
1670            );
1671        }
1672    }
1673
1674    // ── auto-routing: non-VarPro graph → TRF ─────────────────────────────────
1675
1676    #[test]
1677    fn auto_routes_to_trf_for_bounded_graph() {
1678        // A bounded sigma disqualifies the graph from VarPro (graph_prefers_varpro
1679        // requires unconstrained nonlinear params), so `solver="auto"` must fall
1680        // through to TRF. Assert auto's result is identical to an explicit trf fit
1681        // (and that graph_prefers_varpro is indeed false for this graph).
1682        let (true_a, true_c, true_s) = (5.0_f64, 2.0_f64, 0.5_f64);
1683        let n = 60usize;
1684        let x: Vec<f64> = (0..n)
1685            .map(|i| -1.0 + 6.0 * i as f64 / (n - 1) as f64)
1686            .collect();
1687        let y: Vec<f64> = x
1688            .iter()
1689            .map(|&xi| gaussian(xi, true_a, true_c, true_s))
1690            .collect();
1691
1692        let bounded = |value: f64, min: f64, max: f64| ParameterSpec {
1693            value,
1694            min,
1695            max,
1696            vary: true,
1697            expr: None,
1698            scale: None,
1699        };
1700        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1701        params.insert("amplitude".into(), bounded(4.0, 0.0, f64::INFINITY));
1702        params.insert("center".into(), make_param(1.8, true));
1703        params.insert("sigma".into(), bounded(0.6, 1e-6, 10.0)); // finite → not varpro-eligible
1704        let graph = FitGraphSpec {
1705            schema_version: "0.1".into(),
1706            nodes: vec![ModelNodeSpec {
1707                id: "g1".into(),
1708                model_type: ModelTypeStr::Gaussian,
1709                dataset_index: None,
1710                parameters: params,
1711            }],
1712            expr_edges: vec![],
1713        };
1714        assert!(
1715            !graph_prefers_varpro(&graph),
1716            "bounded sigma must disqualify the graph from VarPro"
1717        );
1718        let data = MeasurementSpec {
1719            schema_version: None,
1720            x: vec![x],
1721            y,
1722            sigma: None,
1723            label: None,
1724        };
1725        let opts = |s: &str| FitOptionsSpec {
1726            solver: s.to_string(),
1727            ..default_options()
1728        };
1729        let r_auto = fit(&graph, vec![data.clone()], &opts("auto")).expect("auto fit");
1730        let r_trf = fit(&graph, vec![data], &opts("trf")).expect("trf fit");
1731        // auto routed to TRF → bit-for-bit the same outcome.
1732        assert_eq!(
1733            r_auto.n_iter, r_trf.n_iter,
1734            "auto should match trf iterations"
1735        );
1736        assert_relative_eq!(r_auto.chi2, r_trf.chi2, max_relative = 1e-12);
1737        for key in ["g1.amplitude", "g1.center", "g1.sigma"] {
1738            assert_relative_eq!(
1739                r_auto.parameters[key].value,
1740                r_trf.parameters[key].value,
1741                max_relative = 1e-12
1742            );
1743        }
1744    }
1745
1746    // ── degenerate peak-collapse guard ───────────────────────────────────────
1747
1748    #[test]
1749    fn degenerate_peak_collapse_is_flagged_unsuccessful() {
1750        // Narrow Gaussian (true centre 7) fit from centre=0 on the flat tail:
1751        // local LM stalls and collapses the amplitude to ~0 (R² < 0). The
1752        // degenerate-fit guard must downgrade success to false.
1753        let n = 200usize;
1754        let x: Vec<f64> = (0..n).map(|i| 10.0 * i as f64 / (n - 1) as f64).collect();
1755        let y: Vec<f64> = x.iter().map(|&xi| gaussian(xi, 3.0, 7.0, 0.3)).collect();
1756
1757        let bounded = |value: f64, min: f64, max: f64| ParameterSpec {
1758            value,
1759            min,
1760            max,
1761            vary: true,
1762            expr: None,
1763            scale: None,
1764        };
1765        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1766        params.insert("amplitude".into(), bounded(1.0, 0.0, f64::INFINITY));
1767        params.insert("center".into(), make_param(0.0, true)); // far from 7, flat region
1768        params.insert("sigma".into(), bounded(0.3, 1e-6, f64::INFINITY));
1769        let graph = FitGraphSpec {
1770            schema_version: "0.1".into(),
1771            nodes: vec![ModelNodeSpec {
1772                id: "g1".into(),
1773                model_type: ModelTypeStr::Gaussian,
1774                dataset_index: None,
1775                parameters: params,
1776            }],
1777            expr_edges: vec![],
1778        };
1779        let data = MeasurementSpec {
1780            schema_version: None,
1781            x: vec![x],
1782            y,
1783            sigma: None,
1784            label: None,
1785        };
1786        let r = fit(&graph, vec![data], &default_options()).expect("fit runs");
1787        assert!(
1788            !r.success,
1789            "a collapsed-peak fit (R²<0, amplitude≈0) must be flagged unsuccessful, got success=true r2={}",
1790            r.r_squared
1791        );
1792        assert!(
1793            r.message.contains("degenerate_fit"),
1794            "expected degenerate_fit message, got {:?}",
1795            r.message
1796        );
1797    }
1798
1799    /// A collapsed-peak end point that the solver's convergence test accepts and
1800    /// the stationarity gate refuses reports `success=false` with the
1801    /// degenerate-fit reason as its message, not the bare convergence test.
1802    #[test]
1803    fn gate_refused_peak_collapse_keeps_degenerate_fit_message() {
1804        let n = 120usize;
1805        let x: Vec<f64> = (0..n)
1806            .map(|i| -4.0 + 8.0 * i as f64 / (n - 1) as f64)
1807            .collect();
1808        let y: Vec<f64> = x
1809            .iter()
1810            .map(|&xi| gaussian(xi, 3.0, 0.3, 0.8) + 0.05 * (13.7 * xi).sin())
1811            .collect();
1812        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1813        params.insert("amplitude".into(), make_param(50.0, true));
1814        params.insert("center".into(), make_param(-3.9, true));
1815        params.insert(
1816            "sigma".into(),
1817            ParameterSpec {
1818                value: 0.05,
1819                min: 1e-3,
1820                max: f64::INFINITY,
1821                vary: true,
1822                expr: None,
1823                scale: None,
1824            },
1825        );
1826        let graph = FitGraphSpec {
1827            schema_version: "0.1".into(),
1828            nodes: vec![ModelNodeSpec {
1829                id: "peak".into(),
1830                model_type: ModelTypeStr::Gaussian,
1831                dataset_index: None,
1832                parameters: params,
1833            }],
1834            expr_edges: vec![],
1835        };
1836        let data = MeasurementSpec {
1837            schema_version: None,
1838            x: vec![x],
1839            y,
1840            sigma: None,
1841            label: None,
1842        };
1843        let r = fit(&graph, vec![data], &default_options()).expect("fit runs");
1844        assert!(
1845            !r.success,
1846            "collapsed peak reported success, r2={}",
1847            r.r_squared
1848        );
1849        assert!(r.r_squared < 0.0, "r2={}", r.r_squared);
1850        assert!(
1851            r.message.starts_with("degenerate_fit"),
1852            "expected the degenerate_fit reason, got {:?}",
1853            r.message
1854        );
1855    }
1856
1857    // ── VarPro rejects dataset_index scoping (it is not scope-aware) ──────────
1858
1859    #[test]
1860    fn varpro_rejects_dataset_index_scoped_graph() {
1861        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
1862        params.insert("amplitude".into(), make_param(1.0, true));
1863        params.insert("center".into(), make_param(0.0, true));
1864        params.insert("sigma".into(), make_param(1.0, true));
1865        let graph = FitGraphSpec {
1866            schema_version: "0.1".into(),
1867            nodes: vec![ModelNodeSpec {
1868                id: "g1".into(),
1869                model_type: ModelTypeStr::Gaussian,
1870                dataset_index: Some(0), // per-dataset local node
1871                parameters: params,
1872            }],
1873            expr_edges: vec![],
1874        };
1875        let x: Vec<f64> = (0..10).map(|i| i as f64).collect();
1876        let data = MeasurementSpec {
1877            schema_version: None,
1878            x: vec![x],
1879            y: vec![0.0; 10],
1880            sigma: None,
1881            label: None,
1882        };
1883        let opts = FitOptionsSpec {
1884            solver: "varpro".into(),
1885            ..default_options()
1886        };
1887        let err = fit(&graph, vec![data], &opts);
1888        assert!(
1889            err.is_err(),
1890            "varpro must reject dataset_index-scoped graphs rather than mis-scope them"
1891        );
1892        let msg = format!("{:?}", err.unwrap_err());
1893        assert!(
1894            msg.contains("dataset_index"),
1895            "error should mention dataset_index, got {msg}"
1896        );
1897    }
1898
1899    // ── CX-VPE-01: VarPro routing must honour `Parameter.expr` ties ───────────
1900
1901    /// Two unbounded, separable Gaussians. When `tie` is set, `g2.sigma` is tied
1902    /// to `g1.sigma` via `Parameter.expr` (no `expr_edge`), so the graph is
1903    /// VarPro-eligible on every axis EXCEPT the tie — isolating the tie check.
1904    fn two_gaussian_param_expr_graph(tie: bool) -> FitGraphSpec {
1905        let mut g1: HashMap<String, ParameterSpec> = HashMap::new();
1906        g1.insert("amplitude".into(), make_param(5.0, true));
1907        g1.insert("center".into(), make_param(-1.0, true));
1908        g1.insert("sigma".into(), make_param(0.5, true));
1909
1910        let mut g2: HashMap<String, ParameterSpec> = HashMap::new();
1911        g2.insert("amplitude".into(), make_param(3.0, true));
1912        g2.insert("center".into(), make_param(1.5, true));
1913        // tied => vary=false and value derived from g1.sigma via Parameter.expr.
1914        let mut sig2 = make_param(0.5, !tie);
1915        if tie {
1916            sig2.expr = Some("g1.sigma".into());
1917        }
1918        g2.insert("sigma".into(), sig2);
1919
1920        FitGraphSpec {
1921            schema_version: "0.1".into(),
1922            nodes: vec![
1923                ModelNodeSpec {
1924                    id: "g1".into(),
1925                    model_type: ModelTypeStr::Gaussian,
1926                    dataset_index: None,
1927                    parameters: g1,
1928                },
1929                ModelNodeSpec {
1930                    id: "g2".into(),
1931                    model_type: ModelTypeStr::Gaussian,
1932                    dataset_index: None,
1933                    parameters: g2,
1934                },
1935            ],
1936            expr_edges: vec![],
1937        }
1938    }
1939
1940    #[test]
1941    fn graph_prefers_varpro_false_for_param_expr_tie() {
1942        // CX-VPE-01 regression: an otherwise VarPro-eligible (separable, single
1943        // dataset, all nonlinear params unbounded) graph whose ONLY tie lives in
1944        // `Parameter.expr` must NOT auto-route to VarPro (which would silently drop
1945        // the tie). Before the fix this returned true (only `expr_edges` checked).
1946        let graph = two_gaussian_param_expr_graph(true);
1947        assert!(
1948            !graph_prefers_varpro(&graph),
1949            "a Parameter.expr tie must disqualify the graph from VarPro auto-routing"
1950        );
1951    }
1952
1953    #[test]
1954    fn graph_prefers_varpro_true_for_untied_unbounded_separable() {
1955        // Positive control: the SAME unbounded separable graph WITHOUT a tie stays
1956        // VarPro-eligible — the fix must not over-reject untied graphs.
1957        let graph = two_gaussian_param_expr_graph(false);
1958        assert!(
1959            graph_prefers_varpro(&graph),
1960            "an untied, unbounded, separable graph must remain VarPro-eligible"
1961        );
1962    }
1963
1964    #[test]
1965    fn auto_and_explicit_varpro_agree_on_success() {
1966        // REGRESSION. The `Solver::Auto if graph_prefers_varpro` arm used to call
1967        // `solve_varpro_path` raw while `Solver::Varpro` wrapped it in
1968        // `finalize_varpro_result`. The guards live in that wrapper, so on a
1969        // VarPro-eligible graph the two solver strings could disagree about
1970        // `success` for identical data — with `auto`, the documented default,
1971        // being the one that reported the false success.
1972        //
1973        // The assertion is deliberately on AGREEMENT rather than on a specific
1974        // verdict: whether this particular fit converges is not the point, and
1975        // pinning it would make the test brittle to solver tuning. What must
1976        // hold is that routing does not change the answer.
1977        let graph = two_gaussian_param_expr_graph(false);
1978        assert!(
1979            graph_prefers_varpro(&graph),
1980            "fixture must actually route auto -> varpro, or this proves nothing"
1981        );
1982
1983        let n = 64usize;
1984        let x: Vec<f64> = (0..n)
1985            .map(|i| -3.0 + 6.0 * i as f64 / (n - 1) as f64)
1986            .collect();
1987        // Data two Gaussians cannot represent: a high-frequency oscillation.
1988        // The fit converges but to a poor optimum, which is what puts r² under
1989        // OFF_DOMAIN_R2_FLOOR (0.5) so `apply_postfit_guards` actually engages.
1990        // A clean, well-fit dataset makes this test VACUOUS — the guard's own
1991        // r²-quality escape short-circuits it and both paths trivially agree.
1992        let y: Vec<f64> = x.iter().map(|xi| (20.0 * xi).sin()).collect();
1993        let data = MeasurementSpec {
1994            schema_version: None,
1995            x: vec![x],
1996            y,
1997            sigma: None,
1998            label: None,
1999        };
2000        let opts = |s: &str| FitOptionsSpec {
2001            solver: s.to_string(),
2002            ..default_options()
2003        };
2004
2005        let r_auto = fit(&graph, vec![data.clone()], &opts("auto")).expect("auto fit");
2006        let r_varpro = fit(&graph, vec![data], &opts("varpro")).expect("varpro fit");
2007
2008        assert_eq!(
2009            r_auto.success, r_varpro.success,
2010            "auto and explicit varpro must reach the same success verdict on the \
2011             same graph and data; a difference means one path skipped the \
2012             post-fit guards in `finalize_varpro_result`"
2013        );
2014        assert_relative_eq!(r_auto.chi2, r_varpro.chi2, max_relative = 1e-12);
2015    }
2016
2017    #[test]
2018    fn varpro_explicit_rejects_param_expr_tie() {
2019        // Explicit solver="varpro" on a `Parameter.expr`-tied graph must return the
2020        // tied-params-unsupported error, NOT a silently-wrong success.
2021        let graph = two_gaussian_param_expr_graph(true);
2022        let n = 64usize;
2023        let x: Vec<f64> = (0..n)
2024            .map(|i| -3.0 + 6.0 * i as f64 / (n - 1) as f64)
2025            .collect();
2026        let y: Vec<f64> = x
2027            .iter()
2028            .map(|&xi| gaussian(xi, 5.0, -1.0, 0.5) + gaussian(xi, 3.0, 1.5, 0.5))
2029            .collect();
2030        let data = MeasurementSpec {
2031            schema_version: None,
2032            x: vec![x],
2033            y,
2034            sigma: None,
2035            label: None,
2036        };
2037        let opts = FitOptionsSpec {
2038            solver: "varpro".into(),
2039            ..default_options()
2040        };
2041        let msg = format!(
2042            "{}",
2043            fit(&graph, vec![data], &opts).expect_err(
2044                "solver='varpro' with a Parameter.expr tie must error, not drop the tie"
2045            )
2046        );
2047        assert!(
2048            msg.contains("tied parameters") || msg.contains("Parameter.expr"),
2049            "error should name the tied-params limitation, got: {msg}"
2050        );
2051    }
2052
2053    /// S1 regression: a node with an UNBOUNDED amplitude but a BOUNDED nonlinear
2054    /// param (sigma) must NOT auto-route to VarPro (which ignores bounds). The old
2055    /// positional `.skip(1)` over a HashMap could skip sigma instead of amplitude
2056    /// and wrongly green-light VarPro — a silent bound violation.
2057    #[test]
2058    fn graph_with_unbounded_amplitude_but_bounded_sigma_is_not_varpro() {
2059        let bounded_sigma = ParameterSpec {
2060            value: 0.6,
2061            min: 0.1,
2062            max: 2.0,
2063            vary: true,
2064            expr: None,
2065            scale: None,
2066        };
2067        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2068        params.insert("amplitude".into(), make_param(4.0, true)); // unbounded linear coeff
2069        params.insert("center".into(), make_param(0.0, true)); // unbounded
2070        params.insert("sigma".into(), bounded_sigma); // BOUNDED nonlinear param
2071        let graph = FitGraphSpec {
2072            schema_version: "0.1".into(),
2073            nodes: vec![ModelNodeSpec {
2074                id: "g1".into(),
2075                model_type: ModelTypeStr::Gaussian,
2076                dataset_index: None,
2077                parameters: params,
2078            }],
2079            expr_edges: vec![],
2080        };
2081        assert!(
2082            !graph_prefers_varpro(&graph),
2083            "a bounded nonlinear param must block VarPro auto-routing (bounds would be ignored)"
2084        );
2085    }
2086
2087    // ------------------------------------------------------------------
2088    // A2 follow-up: typed SolverError variants reach the boundary
2089    // ------------------------------------------------------------------
2090
2091    /// Build a minimal 1-D Gaussian graph + dataset for VarPro-rejection tests.
2092    fn make_varpro_inputs() -> (FitGraphSpec, MeasurementSpec) {
2093        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2094        params.insert("amplitude".into(), make_param(1.0, true));
2095        params.insert("center".into(), make_param(0.0, true));
2096        params.insert("sigma".into(), make_param(1.0, true));
2097        let graph = FitGraphSpec {
2098            schema_version: "0.1".into(),
2099            nodes: vec![ModelNodeSpec {
2100                id: "g1".into(),
2101                model_type: ModelTypeStr::Gaussian,
2102                dataset_index: None,
2103                parameters: params,
2104            }],
2105            expr_edges: vec![],
2106        };
2107        let x: Vec<f64> = (0..10).map(|i| i as f64 * 0.1).collect();
2108        let y: Vec<f64> = x.iter().map(|&xi| gaussian(xi, 1.0, 0.0, 1.0)).collect();
2109        let dataset = MeasurementSpec {
2110            schema_version: None,
2111            x: vec![x],
2112            y,
2113            sigma: None,
2114            label: None,
2115        };
2116        (graph, dataset)
2117    }
2118
2119    /// VarPro with expr_edges must surface the typed
2120    /// `SolverError::VarproExprEdgesUnsupported` variant via the CoreError
2121    /// boundary conversion.
2122    #[test]
2123    fn varpro_with_expr_edges_emits_solver_error_variant() {
2124        use spectrafit_types::ExprEdge;
2125
2126        let (mut graph, dataset) = make_varpro_inputs();
2127        // Tie one parameter to force the expr_edge check to fail.
2128        graph.nodes[0]
2129            .parameters
2130            .insert("amplitude".to_string(), make_param(1.0, false));
2131        graph.expr_edges.push(ExprEdge {
2132            target_node: "g1".to_string(),
2133            target_param: "amplitude".to_string(),
2134            expression: "2.0".to_string(),
2135        });
2136
2137        let mut options = default_options();
2138        options.solver = "varpro".to_string();
2139        let err = fit(&graph, vec![dataset], &options).unwrap_err();
2140        let expected: CoreError = SolverError::VarproExprEdgesUnsupported.into();
2141        assert_eq!(format!("{err}"), format!("{expected}"));
2142    }
2143
2144    /// VarPro with a `dataset_index`-scoped node must surface the typed
2145    /// `SolverError::VarproDatasetScopingUnsupported` variant.
2146    #[test]
2147    fn varpro_with_dataset_index_emits_solver_error_variant() {
2148        let (mut graph, dataset) = make_varpro_inputs();
2149        graph.nodes[0].dataset_index = Some(0);
2150
2151        let mut options = default_options();
2152        options.solver = "varpro".to_string();
2153        let err = fit(&graph, vec![dataset], &options).unwrap_err();
2154        let expected: CoreError = SolverError::VarproDatasetScopingUnsupported.into();
2155        assert_eq!(format!("{err}"), format!("{expected}"));
2156    }
2157
2158    // ------------------------------------------------------------------
2159    // Coverage-gap follow-up: `Solver::Varpro` on a non-separable graph
2160    // ------------------------------------------------------------------
2161
2162    /// Explicit `solver="varpro"` on a graph that `spectrafit_varpro::is_separable`
2163    /// rejects (e.g. `true_voigt`, which is not in `SEPARABLE_MODEL_TYPES`) must
2164    /// surface `SolverError::VarproNotSeparable`, not silently fall back to
2165    /// another solver or panic.
2166    #[test]
2167    fn fit_rejects_varpro_on_non_separable_graph() {
2168        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2169        params.insert("amplitude".into(), make_param(1.0, true));
2170        params.insert("center".into(), make_param(0.0, true));
2171        params.insert("sigma".into(), make_param(1.0, true));
2172        params.insert("gamma".into(), make_param(1.0, true));
2173        let graph = FitGraphSpec {
2174            schema_version: "0.1".into(),
2175            nodes: vec![ModelNodeSpec {
2176                id: "v1".into(),
2177                model_type: ModelTypeStr::TrueVoigt,
2178                dataset_index: None,
2179                parameters: params,
2180            }],
2181            expr_edges: vec![],
2182        };
2183        let x: Vec<f64> = (0..10).map(|i| i as f64 * 0.1).collect();
2184        let dataset = MeasurementSpec {
2185            schema_version: None,
2186            x: vec![x],
2187            y: vec![0.0; 10],
2188            sigma: None,
2189            label: None,
2190        };
2191        let opts = FitOptionsSpec {
2192            solver: "varpro".to_string(),
2193            ..default_options()
2194        };
2195        let err = fit(&graph, vec![dataset], &opts).expect_err(
2196            "solver='varpro' on a non-separable graph (true_voigt) must error, not fall back",
2197        );
2198        let expected: CoreError = SolverError::VarproNotSeparable.into();
2199        assert_eq!(format!("{err}"), format!("{expected}"));
2200    }
2201
2202    // ------------------------------------------------------------------
2203    // Coverage-gap follow-up: `Solver::Global`'s max_iterations → DE-generation
2204    // budget mapping in `dispatch_solver`
2205    // ------------------------------------------------------------------
2206
2207    /// A cheap single-parameter constant fit through `solver="global"`, used to
2208    /// exercise `dispatch_solver`'s DE-generation-budget mapping without the
2209    /// cost of a multi-peak DE search.
2210    fn constant_global_fit_inputs() -> (FitGraphSpec, MeasurementSpec) {
2211        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2212        params.insert(
2213            "c".into(),
2214            ParameterSpec {
2215                value: 0.0,
2216                min: -10.0,
2217                max: 10.0,
2218                vary: true,
2219                expr: None,
2220                scale: None,
2221            },
2222        );
2223        let graph = FitGraphSpec {
2224            schema_version: "0.1".into(),
2225            nodes: vec![ModelNodeSpec {
2226                id: "const1".into(),
2227                model_type: ModelTypeStr::Constant,
2228                dataset_index: None,
2229                parameters: params,
2230            }],
2231            expr_edges: vec![],
2232        };
2233        let n = 10usize;
2234        let x: Vec<f64> = (0..n).map(|i| i as f64).collect();
2235        let y = vec![3.0; n];
2236        let dataset = MeasurementSpec {
2237            schema_version: None,
2238            x: vec![x],
2239            y,
2240            sigma: None,
2241            label: None,
2242        };
2243        (graph, dataset)
2244    }
2245
2246    /// `options.max_iterations > 0` must map onto `DeConfig::max_gen`, capping
2247    /// the DE search at that many generations — see the comment on
2248    /// `Solver::Global` in `dispatch_solver`.
2249    #[test]
2250    fn dispatch_global_solver_uses_max_iterations_as_de_generation_budget() {
2251        let (graph, dataset) = constant_global_fit_inputs();
2252        let opts = FitOptionsSpec {
2253            solver: "global".to_string(),
2254            max_iterations: 7,
2255            ..default_options()
2256        };
2257        let result = fit(&graph, vec![dataset], &opts).expect("global fit should not error");
2258        let gens = result
2259            .n_de_generations
2260            .expect("global solver must report n_de_generations");
2261        assert!(
2262            gens <= 7,
2263            "max_iterations=7 must cap the DE generation budget at 7, got {gens}"
2264        );
2265    }
2266
2267    /// `options.max_iterations == 0` must fall back to `DeConfig::default().max_gen`
2268    /// (100) rather than passing a zero-generation budget through to DE.
2269    #[test]
2270    fn dispatch_global_solver_falls_back_to_default_generation_budget_when_max_iterations_is_zero()
2271    {
2272        let (graph, dataset) = constant_global_fit_inputs();
2273        let opts = FitOptionsSpec {
2274            solver: "global".to_string(),
2275            max_iterations: 0,
2276            ..default_options()
2277        };
2278        let result = fit(&graph, vec![dataset], &opts)
2279            .expect("global fit with max_iterations=0 must still run, using the DE default");
2280        let gens = result
2281            .n_de_generations
2282            .expect("global solver must report n_de_generations");
2283        assert!(
2284            gens <= DeConfig::default().max_gen as u64,
2285            "max_iterations=0 must fall back to DeConfig::default().max_gen (100), got {gens}"
2286        );
2287    }
2288
2289    // ------------------------------------------------------------------
2290    // Coverage-gap follow-up: `run_lm_solve`'s tolerance/delta0/max_delta
2291    // fallback and override branches
2292    // ------------------------------------------------------------------
2293
2294    /// `options.tolerance <= 0.0` must fall back to the built-in `1e-8` default
2295    /// for the shared `tol` used by the faer/trust-region drivers (the `else`
2296    /// arm of the top-level `tol` binding), AND must skip `LevenbergMarquardt::with_tol`
2297    /// for the `lm-legacy` oracle (its own, separate `options.tolerance > 0.0`
2298    /// check) rather than calling it with a non-positive tolerance.
2299    #[test]
2300    fn run_lm_solve_falls_back_to_default_tolerance_when_non_positive() {
2301        let (graph, dataset) = gaussian_fit_inputs(None);
2302        let opts = FitOptionsSpec {
2303            solver: "lm-legacy".to_string(),
2304            tolerance: 0.0,
2305            ..default_options()
2306        };
2307        let result = fit(&graph, vec![dataset], &opts)
2308            .expect("lm-legacy fit with tolerance<=0.0 should still run on the 1e-8 default");
2309        assert!(
2310            result.success,
2311            "lm-legacy should converge on a clean Gaussian even via the default tolerance; \
2312             message: {}",
2313            result.message
2314        );
2315    }
2316
2317    /// An explicit `delta0`/`max_delta` must override the trust-region driver's
2318    /// own defaults (the `if let Some(..)` bodies in `run_lm_solve`), not be
2319    /// silently ignored.
2320    #[test]
2321    fn run_lm_solve_applies_explicit_delta0_and_max_delta_overrides() {
2322        let (graph, dataset) = gaussian_fit_inputs(None);
2323        let opts = FitOptionsSpec {
2324            solver: "dogleg".to_string(),
2325            delta0: Some(0.5),
2326            max_delta: Some(50.0),
2327            ..default_options()
2328        };
2329        let result = fit(&graph, vec![dataset], &opts)
2330            .expect("dogleg fit with explicit delta0/max_delta should not error");
2331        assert!(
2332            result.success,
2333            "dogleg should converge on a clean Gaussian with an explicit \
2334             delta0/max_delta override; message: {}",
2335            result.message
2336        );
2337    }
2338
2339    // ------------------------------------------------------------------
2340    // Coverage-gap follow-up: `collect_free_param_specs`'s malformed-lookup
2341    // error path
2342    // ------------------------------------------------------------------
2343
2344    /// A `free_keys` entry naming a parameter the node itself does not carry
2345    /// (e.g. a stale/malformed key) must surface a `SolverError::Dispatch`
2346    /// naming the missing parameter and node, not panic on an unwrap.
2347    #[test]
2348    fn collect_free_param_specs_errors_when_free_key_param_missing_from_node() {
2349        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2350        params.insert("amplitude".into(), make_param(1.0, true));
2351        let graph = FitGraphSpec {
2352            schema_version: "0.1".into(),
2353            nodes: vec![ModelNodeSpec {
2354                id: "g1".into(),
2355                model_type: ModelTypeStr::Gaussian,
2356                dataset_index: None,
2357                parameters: params,
2358            }],
2359            expr_edges: vec![],
2360        };
2361        // "sigma" is a plausible free key for a Gaussian node, but this node's
2362        // own parameter map only has "amplitude" — collect_free_param_specs must
2363        // report the mismatch rather than panicking on a missing-key unwrap.
2364        let free_keys = vec!["g1.sigma".to_string()];
2365        let err = collect_free_param_specs(&graph, &free_keys)
2366            .expect_err("a free key naming a param absent from its node must error");
2367        let msg = format!("{err}");
2368        assert!(
2369            msg.contains("sigma") && msg.contains("g1"),
2370            "error should name the missing param and its node, got: {msg}"
2371        );
2372    }
2373
2374    // ------------------------------------------------------------------
2375    // Coverage-gap follow-up: termination-reason mapping helpers
2376    // ------------------------------------------------------------------
2377
2378    /// `faer_termination_str` must map every `spectrafit_levenberg_marquardt::Termination`
2379    /// variant to its stable snake_case string — including `NumericalError`,
2380    /// which no end-to-end fit in this suite naturally triggers.
2381    #[test]
2382    fn faer_termination_str_maps_numerical_error() {
2383        assert_eq!(
2384            faer_termination_str(spectrafit_levenberg_marquardt::Termination::NumericalError),
2385            "numerical_error"
2386        );
2387    }
2388
2389    /// `map_termination` must translate every `levenberg_marquardt::TerminationReason`
2390    /// variant (the `lm-legacy` oracle's own type) onto our stable
2391    /// `spectrafit_types::TerminationReason`, independent of any particular fit
2392    /// reaching that termination naturally.
2393    #[test]
2394    fn map_termination_covers_every_lm_legacy_variant() {
2395        use levenberg_marquardt::TerminationReason as L;
2396
2397        let cases: Vec<(L, TerminationReason)> = vec![
2398            (L::ResidualsZero, TerminationReason::ResidualsZero),
2399            (L::Orthogonal, TerminationReason::Orthogonal),
2400            (L::LostPatience, TerminationReason::MaxIterations),
2401            (
2402                L::NoImprovementPossible("test"),
2403                TerminationReason::NoImprovementPossible,
2404            ),
2405            (L::NoParameters, TerminationReason::NoParameters),
2406            (L::NoResiduals, TerminationReason::NoResiduals),
2407            (
2408                L::WrongDimensions("test"),
2409                TerminationReason::WrongDimensions,
2410            ),
2411            (L::Numerical("test"), TerminationReason::NumericalError),
2412            (L::User("test"), TerminationReason::UserCancelled),
2413        ];
2414        for (input, expected) in cases {
2415            let mapped = map_termination(&input);
2416            assert_eq!(
2417                mapped, expected,
2418                "map_termination({input:?}) should map to {expected:?}, got {mapped:?}"
2419            );
2420        }
2421    }
2422
2423    // ── #93: FitOptionsSpec.jacobian = "finite_difference" ──────────────────
2424
2425    /// A single Gaussian with deterministic, non-zero residuals so the
2426    /// covariance (and hence `stderr`) is not degenerate.
2427    fn fd_mode_gaussian_inputs() -> (FitGraphSpec, MeasurementSpec) {
2428        let n = 60usize;
2429        let x: Vec<f64> = (0..n)
2430            .map(|i| -1.0 + 6.0 * i as f64 / (n - 1) as f64)
2431            .collect();
2432        let y: Vec<f64> = x
2433            .iter()
2434            .map(|&xi| gaussian(xi, 5.0, 2.0, 0.5) + 0.02 * (7.0 * xi).sin())
2435            .collect();
2436        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2437        params.insert("amplitude".into(), make_param(4.0, true));
2438        params.insert("center".into(), make_param(1.8, true));
2439        params.insert("sigma".into(), make_param(0.6, true));
2440        let graph = FitGraphSpec {
2441            schema_version: "0.1".into(),
2442            nodes: vec![ModelNodeSpec {
2443                id: "g1".into(),
2444                model_type: ModelTypeStr::Gaussian,
2445                dataset_index: None,
2446                parameters: params,
2447            }],
2448            expr_edges: vec![],
2449        };
2450        let dataset = MeasurementSpec {
2451            schema_version: None,
2452            x: vec![x],
2453            y,
2454            sigma: None,
2455            label: None,
2456        };
2457        (graph, dataset)
2458    }
2459
2460    /// Every solver path that consumes a Jacobian runs with the forced FD
2461    /// Jacobian: the fit converges to the analytic-mode optimum (to FD
2462    /// accuracy) and its post-fit `stderr` comes from the FD Jacobian (so it
2463    /// is not bit-identical to the analytic one). `irls` and `global` reach the
2464    /// LM core through `..options.clone()`, so the option must survive that.
2465    #[test]
2466    fn forced_fd_jacobian_runs_on_every_jacobian_consuming_solver() {
2467        let (graph, dataset) = fd_mode_gaussian_inputs();
2468        for solver in [
2469            "lm",
2470            "lm-legacy",
2471            "trf",
2472            "geodesic",
2473            "dogleg",
2474            "newton-cg",
2475            "irls",
2476            "global",
2477        ] {
2478            let opts = |jacobian| FitOptionsSpec {
2479                solver: solver.into(),
2480                jacobian,
2481                ..default_options()
2482            };
2483            let an = fit(&graph, vec![dataset.clone()], &opts(JacobianMode::Analytic))
2484                .expect("analytic fit");
2485            let fd = fit(
2486                &graph,
2487                vec![dataset.clone()],
2488                &opts(JacobianMode::FiniteDifference),
2489            )
2490            .expect("fd fit");
2491            assert!(an.success, "{solver}: analytic fit must converge");
2492            assert!(fd.success, "{solver}: fd fit must converge: {}", fd.message);
2493            let mut stderr_differs = false;
2494            for (k, pa) in &an.parameters {
2495                let pf = &fd.parameters[k];
2496                assert!(
2497                    (pa.value - pf.value).abs() <= 1e-5 * pa.value.abs().max(1.0),
2498                    "{solver} {k}: analytic {} vs fd {}",
2499                    pa.value,
2500                    pf.value
2501                );
2502                stderr_differs |= pa.stderr != pf.stderr;
2503            }
2504            assert!(
2505                stderr_differs,
2506                "{solver}: the fd-mode stderr must come from the FD Jacobian"
2507            );
2508        }
2509    }
2510
2511    /// The default stays analytic: omitting the option and passing
2512    /// `JacobianMode::Analytic` explicitly give bit-identical results.
2513    #[test]
2514    fn default_jacobian_mode_is_bit_identical_to_explicit_analytic() {
2515        let (graph, dataset) = fd_mode_gaussian_inputs();
2516        let implicit = fit(&graph, vec![dataset.clone()], &FitOptionsSpec::default()).unwrap();
2517        let explicit = fit(
2518            &graph,
2519            vec![dataset],
2520            &FitOptionsSpec {
2521                jacobian: JacobianMode::Analytic,
2522                ..FitOptionsSpec::default()
2523            },
2524        )
2525        .unwrap();
2526        for (k, p) in &implicit.parameters {
2527            let q = &explicit.parameters[k];
2528            assert_eq!(p.value.to_bits(), q.value.to_bits(), "{k} value");
2529            assert_eq!(
2530                p.stderr.map(f64::to_bits),
2531                q.stderr.map(f64::to_bits),
2532                "{k} stderr"
2533            );
2534        }
2535        assert_eq!(implicit.chi2.to_bits(), explicit.chi2.to_bits());
2536    }
2537
2538    /// `auto` on a VarPro-eligible graph runs TRF under the forced FD mode:
2539    /// bit-identical to an explicit `trf` + FD fit.
2540    #[test]
2541    fn auto_with_forced_fd_jacobian_runs_trf_instead_of_varpro() {
2542        let (graph, dataset) = make_varpro_inputs();
2543        assert!(
2544            graph_prefers_varpro(&graph),
2545            "fixture must be VarPro-eligible"
2546        );
2547        let opts = |solver: &str| FitOptionsSpec {
2548            solver: solver.into(),
2549            jacobian: JacobianMode::FiniteDifference,
2550            ..default_options()
2551        };
2552        let auto = fit(&graph, vec![dataset.clone()], &opts("auto")).expect("auto fd");
2553        let trf = fit(&graph, vec![dataset], &opts("trf")).expect("trf fd");
2554        for (k, p) in &auto.parameters {
2555            assert_eq!(p.value.to_bits(), trf.parameters[k].value.to_bits(), "{k}");
2556        }
2557        assert_eq!(auto.chi2.to_bits(), trf.chi2.to_bits());
2558        assert_eq!(auto.n_iter, trf.n_iter);
2559    }
2560
2561    /// Explicit VarPro cannot honour the forced FD mode and says so.
2562    #[test]
2563    fn varpro_rejects_forced_fd_jacobian() {
2564        let (graph, dataset) = make_varpro_inputs();
2565        let opts = FitOptionsSpec {
2566            solver: "varpro".into(),
2567            jacobian: JacobianMode::FiniteDifference,
2568            ..default_options()
2569        };
2570        let err = fit(&graph, vec![dataset], &opts).expect_err("varpro + fd must error");
2571        let msg = err.to_string();
2572        assert!(
2573            msg.contains("finite_difference") && msg.contains("varpro"),
2574            "unexpected message: {msg}"
2575        );
2576    }
2577
2578    // ── #93 F4g: the stationarity gate on whole fits ─────────────────────────
2579    //
2580    // NIST StRD Misra1a/Misra1b (https://www.itl.nist.gov/div898/strd/nls/),
2581    // the same data and options as `tests/scenario/nist_strd/test_misra1{a,b}.py`
2582    // (lm, tolerance 1e-12, max_iterations 10000, both parameters min = 0). The
2583    // fit reaches the certified optimum and may stop on
2584    // `no_improvement_possible`; at a stationary end point that is a success.
2585
2586    const MISRA_X: [f64; 14] = [
2587        77.6, 114.9, 141.1, 190.8, 239.9, 289.0, 332.8, 378.4, 434.8, 477.3, 536.8, 593.1, 689.1,
2588        760.0,
2589    ];
2590    const MISRA_Y: [f64; 14] = [
2591        10.07, 14.73, 17.94, 23.93, 29.61, 35.18, 40.02, 44.82, 50.76, 55.05, 61.01, 66.40, 75.47,
2592        81.78,
2593    ];
2594
2595    fn misra_fit(model: ModelTypeStr, b1: f64, b2: f64) -> FitResultSpec {
2596        let lower0 = |value: f64| ParameterSpec {
2597            value,
2598            min: 0.0,
2599            max: f64::INFINITY,
2600            vary: true,
2601            expr: None,
2602            scale: None,
2603        };
2604        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2605        params.insert("amplitude".into(), lower0(b1));
2606        params.insert("rate".into(), lower0(b2));
2607        let graph = FitGraphSpec {
2608            schema_version: "0.1".into(),
2609            nodes: vec![ModelNodeSpec {
2610                id: "m".into(),
2611                model_type: model,
2612                dataset_index: None,
2613                parameters: params,
2614            }],
2615            expr_edges: vec![],
2616        };
2617        let dataset = MeasurementSpec {
2618            schema_version: None,
2619            x: vec![MISRA_X.to_vec()],
2620            y: MISRA_Y.to_vec(),
2621            sigma: None,
2622            label: None,
2623        };
2624        let options = FitOptionsSpec {
2625            max_iterations: 10_000,
2626            tolerance: 1e-12,
2627            ..default_options()
2628        };
2629        fit(&graph, vec![dataset], &options).expect("Misra fit should not error")
2630    }
2631
2632    #[test]
2633    fn misra_fits_at_the_certified_optimum_report_success() {
2634        // (model, start b1, start b2, certified b1, certified b2, certified RSS)
2635        let cases = [
2636            (
2637                ModelTypeStr::SaturatingExponential,
2638                500.0,
2639                1.0e-4,
2640                2.389_421_291_8e2,
2641                5.501_564_318_1e-4,
2642                1.245_513_889_4e-1,
2643            ),
2644            (
2645                ModelTypeStr::SaturatingExponential,
2646                250.0,
2647                5.0e-4,
2648                2.389_421_291_8e2,
2649                5.501_564_318_1e-4,
2650                1.245_513_889_4e-1,
2651            ),
2652            (
2653                ModelTypeStr::PowerSaturation,
2654                500.0,
2655                1.0e-4,
2656                3.379_974_616_3e2,
2657                3.903_909_128_7e-4,
2658                7.546_468_153_3e-2,
2659            ),
2660            (
2661                ModelTypeStr::PowerSaturation,
2662                300.0,
2663                2.0e-4,
2664                3.379_974_616_3e2,
2665                3.903_909_128_7e-4,
2666                7.546_468_153_3e-2,
2667            ),
2668        ];
2669        for (model, s1, s2, b1, b2, rss) in cases {
2670            let r = misra_fit(model.clone(), s1, s2);
2671            let got_b1 = r.parameters["m.amplitude"].value;
2672            let got_b2 = r.parameters["m.rate"].value;
2673            assert!(
2674                ((got_b1 - b1) / b1).abs() < 1e-6 && ((got_b2 - b2) / b2).abs() < 1e-6,
2675                "{model:?} from ({s1}, {s2}): ({got_b1}, {got_b2}) is not the certified optimum"
2676            );
2677            assert!(((r.chi2 - rss) / rss).abs() < 1e-8, "RSS {}", r.chi2);
2678            assert!(
2679                r.success,
2680                "{model:?} from ({s1}, {s2}) at the certified optimum must be a success \
2681                 (message: {})",
2682                r.message
2683            );
2684        }
2685    }
2686
2687    /// The fit of `test_fit_json_boundary_success_path_serialises_result`
2688    /// (`tests/unit/spectrafit_core/test_binding_edge_paths.py`): a Gaussian
2689    /// (`sigma` min = 0, the rest unbounded) on three points of y = 2^(−x), lm,
2690    /// max_iterations 50, tolerance 1e-8. ln y is linear in x and a Gaussian's
2691    /// log is a concave parabola, so the RSS has no finite minimiser: it only
2692    /// tends to 0 as σ grows. With three points and three parameters J is square,
2693    /// so at any full-rank point with RSS > 0 the Gauss-Newton step removes the
2694    /// whole residual (predicted decrease = RSS). The budget stop is therefore
2695    /// not stationary and stays `success=false` under the gate.
2696    #[test]
2697    fn three_point_gaussian_without_finite_minimiser_is_not_success() {
2698        let mut params: HashMap<String, ParameterSpec> = HashMap::new();
2699        params.insert("amplitude".into(), make_param(1.0, true));
2700        params.insert("center".into(), make_param(0.0, true));
2701        params.insert(
2702            "sigma".into(),
2703            ParameterSpec {
2704                min: 0.0,
2705                ..make_param(1.0, true)
2706            },
2707        );
2708        let graph = FitGraphSpec {
2709            schema_version: "0.1".into(),
2710            nodes: vec![ModelNodeSpec {
2711                id: "g".into(),
2712                model_type: ModelTypeStr::Gaussian,
2713                dataset_index: None,
2714                parameters: params,
2715            }],
2716            expr_edges: vec![],
2717        };
2718        let dataset = MeasurementSpec {
2719            schema_version: None,
2720            x: vec![vec![0.0, 1.0, 2.0]],
2721            y: vec![1.0, 0.5, 0.25],
2722            sigma: None,
2723            label: None,
2724        };
2725        let options = FitOptionsSpec {
2726            max_iterations: 50,
2727            ..default_options()
2728        };
2729        let r = fit(&graph, vec![dataset], &options).expect("fit should not error");
2730        assert_eq!(r.message, "max_iterations");
2731        assert!(r.chi2 > 0.0);
2732        assert!(
2733            !r.success,
2734            "a non-stationary budget stop must not be a success"
2735        );
2736    }
2737}