spectrafit_levenberg_marquardt/driver.rs
1//! The Levenberg–Marquardt outer control loop (LM / TRF / geodesic).
2//!
3//! One loop drives every LM-family strategy; only the [`StepKind`] and the `λ`
4//! update differ. The loop is classic Levenberg–Marquardt with a Nielsen `λ/ν`
5//! schedule and a gain-ratio accept/reject test, with stopping criteria matched
6//! to `scipy.optimize.least_squares` / `lmfit` defaults (`ftol`, `xtol`,
7//! `gtol`). When the problem exposes a box ([`TrustRegionProblem::bounds`]) the
8//! driver projects every trial point onto it (see "Projection onto the box"
9//! below); any further parameterisation (tied parameters, bounds handling of
10//! problems without `bounds()`) lives in the problem's
11//! [`set_params`](TrustRegionProblem::set_params), and the driver reads back
12//! the applied parameters.
13//!
14//! # Known divergence from scipy: the `ftol` stop
15//!
16//! The `ftol` test here is `actual ≤ ftol · cost` evaluated on an **accepted**
17//! step, and it deliberately omits the `ratio > 0.25` guard that
18//! `scipy.optimize._lsq.common.check_termination` applies alongside the same
19//! inequality. Consequence: an accepted but low-gain step — `ρ ∈ (1e-4, 0.25]`,
20//! i.e. accepted because it did reduce the cost, but by much less than the
21//! model predicted — with a tiny reduction stops this driver where scipy would
22//! take at least one more step. It is a stop-one-step-early difference, not a
23//! wrong answer: the reported point is still an accepted, cost-reducing
24//! iterate. Documented rather than changed so the existing accuracy gates keep
25//! measuring the solver as shipped.
26//!
27//! # Active-set projected step at bounds
28//!
29//! When the problem exposes a box ([`TrustRegionProblem::bounds`]) and a
30//! component sits on a bound with its descent direction `−g_i` pointing out of
31//! the box, that component is *held*: the damped step is solved on the free
32//! subspace only, the trial point is projected (clamped) onto the box, and a
33//! step that the projection reduces to zero is a stationary point, not a
34//! rejected trial. Held set: D. P. Bertsekas, "Projected Newton methods for
35//! optimization problems with simple constraints", SIAM J. Control Optim.
36//! 20(2):221–246, 1982, doi:10.1137/0320018. Projected LM step onto the box:
37//! C. Kanzow, N. Yamashita, M. Fukushima, "Levenberg–Marquardt methods with
38//! strong local convergence properties for solving nonlinear equations with
39//! convex constraints", J. Comput. Appl. Math. 172:375–397, 2004 (erratum
40//! 2005). With nothing held the iteration runs the unchanged unbounded code
41//! path, bit for bit (see `held_components`).
42//!
43//! # Projection onto the box
44//!
45//! A trial point `p + δ` that crosses a bound is projected (componentwise
46//! clamped) onto the box, not reflected back into it: the projected LM step of
47//! C. Kanzow, N. Yamashita, M. Fukushima, J. Comput. Appl. Math. 172:375–397,
48//! 2004 (erratum 2005), whose iterate is `P_X(x + d)`. An iterate can then land
49//! exactly on a bound, where the active-set entry rule (`AT_BOUND_REL`) holds
50//! it; a reflected iterate (`2b − t`) only landed on a bound on a two-sided
51//! double bounce and otherwise parked a small distance off a one-sided bound,
52//! so the active set never engaged from interior starts (#93). The geodesic
53//! probe point is projected the same way. A point inside the box is passed on
54//! unchanged, so a box that is never crossed leaves every iterate bit-identical.
55//! The gain ratio is still judged on the step the problem applied.
56//!
57//! # Global state
58//!
59//! This driver does not touch faer's global parallelism. Callers are expected
60//! to set it (`spectrafit-solver::fit` sets `Par::Seq` for the whole fit); the
61//! driver itself does not touch global state.
62
63use faer::{Mat, MatRef};
64
65use crate::error::StepError;
66use crate::step::{factorize, StepFactor, StepKind};
67use spectrafit_trust_region::{Report, Termination, TrustRegionProblem};
68
69/// Tuning for a single Levenberg–Marquardt solve (covers LM, TRF and geodesic).
70#[derive(Debug, Clone, Copy)]
71pub struct StrategyConfig {
72 /// Linear-algebra path for the step (pick via [`crate::select_regime`]).
73 pub kind: StepKind,
74 /// Relative cost-decrease tolerance.
75 pub ftol: f64,
76 /// Relative step-size tolerance.
77 pub xtol: f64,
78 /// Gradient infinity-norm tolerance.
79 pub gtol: f64,
80 /// Maximum residual evaluations.
81 pub max_nfev: usize,
82 /// Initial Marquardt damping `λ`.
83 pub initial_lambda: f64,
84 /// Enable geodesic acceleration (Transtrum): augment the LM velocity step
85 /// with a second-directional-derivative acceleration term. Faster on
86 /// sloppy/degenerate surfaces (multi-peak) at ~1 extra residual eval/iter.
87 pub geodesic: bool,
88 /// Finite-difference step for the geodesic second directional derivative.
89 pub geodesic_h: f64,
90 /// Acceptance threshold for the acceleration: accept `δ + ½a` only when
91 /// `‖Da‖ / ‖Dδ‖ ≤ α` (mild curvature).
92 pub geodesic_alpha: f64,
93 /// Enable Coleman–Li bound-distance scaling (`solver="trf"`): fold the
94 /// problem's [`trust_scaling`](TrustRegionProblem::trust_scaling) into the
95 /// per-iteration damping so steps shrink as parameters approach a bound for
96 /// which the problem reports `v_i < 1` (in `spectrafit-solver`, parameters
97 /// with two finite bounds). Trial points are projected onto the box either way.
98 pub bound_scaling: bool,
99}
100
101impl Default for StrategyConfig {
102 fn default() -> Self {
103 Self {
104 kind: StepKind::NormalEqLlt,
105 ftol: 1e-8,
106 xtol: 1e-8,
107 gtol: 1e-8,
108 max_nfev: 10_000,
109 initial_lambda: 1e-3,
110 geodesic: false,
111 geodesic_h: 0.1,
112 geodesic_alpha: 0.75,
113 bound_scaling: false,
114 }
115 }
116}
117
118#[inline]
119fn col_dot(a: MatRef<'_, f64>, b: MatRef<'_, f64>) -> f64 {
120 let n = a.nrows();
121 let mut s = 0.0;
122 for i in 0..n {
123 s += a[(i, 0)] * b[(i, 0)];
124 }
125 s
126}
127
128/// `‖Dv‖` where `D = diag(diag)`.
129#[inline]
130fn scaled_norm(v: &Mat<f64>, diag: &[f64]) -> f64 {
131 let mut s = 0.0;
132 for (i, &d) in diag.iter().enumerate() {
133 let x = d * v[(i, 0)];
134 s += x * x;
135 }
136 s.sqrt()
137}
138
139/// Geodesic acceleration (Transtrum/Sethna): given the LM velocity `δ`, compute
140/// the acceleration `a` from the second directional derivative of the residual
141/// along `δ` and return the augmented step `δ + ½a` (or `δ` if the curvature is
142/// too large), plus its predicted reduction `−gᵀs − ½‖Js‖²`.
143///
144/// Probes the residual at `p + h·δ` (one extra eval), then restores the problem
145/// to `p_cur`. Falls back to the plain velocity on any numerical failure.
146// Allowed: this is the per-outer-iteration hot path — the mutable problem,
147// its cached factorization/Jacobian/residual/gradient, the current point and
148// LM velocity, the damping/probe-step/mixing scalars (diag/lambda/h/alpha),
149// and the shared eval counter are each consumed directly below; wrapping
150// them in a struct here would just rename this same parameter list without
151// reducing the coupling.
152#[allow(clippy::too_many_arguments)]
153fn geodesic_augment<P: TrustRegionProblem>(
154 problem: &mut P,
155 factor: &StepFactor,
156 j: MatRef<'_, f64>,
157 r: MatRef<'_, f64>,
158 g: MatRef<'_, f64>,
159 p_cur: &[f64],
160 bounds: Option<&[(f64, f64)]>,
161 velocity: Mat<f64>,
162 diag: &[f64],
163 lambda: f64,
164 h: f64,
165 alpha: f64,
166 n_residual_evals: &mut usize,
167) -> (Mat<f64>, f64) {
168 let p = velocity.nrows();
169 let m = j.nrows();
170
171 let pred_of = |step: &Mat<f64>| {
172 let js = j * step.as_ref();
173 -col_dot(g, step.as_ref()) - 0.5 * js.as_ref().squared_norm_l2()
174 };
175
176 let jv = j * velocity.as_ref(); // m×1
177
178 // Probe r(p + h·δ), projected onto the box like every trial point (module
179 // doc, "Projection onto the box"); restore to p_cur afterwards.
180 let p_probe: Vec<f64> = (0..p).map(|i| p_cur[i] + h * velocity[(i, 0)]).collect();
181 let p_probe_proj = project_point(&p_probe, bounds);
182 problem.set_params(p_probe_proj.as_deref().unwrap_or(&p_probe));
183 let mut r_plus = Mat::<f64>::zeros(m, 1);
184 let probe_ok = problem.residuals_into(r_plus.as_mut()).is_ok();
185 problem.set_params(p_cur);
186 // The probe is a real residual evaluation whether it succeeded or not — count
187 // it before any early return so the work budget is accounted accurately.
188 *n_residual_evals += 1;
189 if !probe_ok {
190 let pr = pred_of(&velocity);
191 return (velocity, pr);
192 }
193
194 // Second directional derivative: r_vv ≈ (2/h)·[ (r(p+hδ) − r)/h − Jδ ].
195 let rvv = Mat::from_fn(m, 1, |i, _| {
196 (2.0 / h) * (((r_plus[(i, 0)] - r[(i, 0)]) / h) - jv[(i, 0)])
197 });
198 let jt_rvv = j.transpose() * rvv.as_ref(); // p×1
199 let rhs2 = Mat::from_fn(p, 1, |i, _| -jt_rvv[(i, 0)]);
200
201 let accel = match factor.solve_rhs(diag, lambda, rhs2.as_ref()) {
202 Ok(a) => a,
203 Err(_) => {
204 let pr = pred_of(&velocity);
205 return (velocity, pr);
206 }
207 };
208
209 // Accept the acceleration only under mild curvature: ‖Da‖/‖Dδ‖ ≤ α.
210 let dv = scaled_norm(&velocity, diag);
211 let da = scaled_norm(&accel, diag);
212 let step = if dv > 0.0 && da / dv <= alpha {
213 Mat::from_fn(p, 1, |i, _| velocity[(i, 0)] + 0.5 * accel[(i, 0)])
214 } else {
215 velocity
216 };
217 let pr = pred_of(&step);
218 (step, pr)
219}
220
221/// Update the monotone Moré column scaling `D` in place from the current
222/// Jacobian's column norms: `D_j ← max(D_j, ‖J_:,j‖)`, floored at 1 for an
223/// all-zero column, seeded (not maxed) on the first call. Per MINPACK, `diag`
224/// never shrinks, so the trust region stays measured in units that equalise
225/// the Jacobian columns regardless of how many outer iterations have run.
226fn update_more_scaling(diag: &mut [f64], diag_initialized: &mut bool, j: MatRef<'_, f64>) {
227 // faer stores columns contiguously, so `col(jc).norm_l2()` is a fast SIMD
228 // reduction.
229 for (jc, d) in diag.iter_mut().enumerate() {
230 let cn = j.col(jc).norm_l2();
231 let cn = if cn > 0.0 { cn } else { 1.0 };
232 *d = if *diag_initialized { (*d).max(cn) } else { cn };
233 }
234 *diag_initialized = true;
235}
236
237/// Gradient `g = Jᵀr`, its raw infinity norm, and the first-order optimality
238/// measure used for the `gtol` stop.
239///
240/// For a bounded problem the raw `‖g‖_∞` is the wrong measure at an active
241/// bound: the gradient component pointing into the wall can stay large at a
242/// legitimate constrained optimum, so the raw test never fires and the loop
243/// stalls to a `NoImprovement` "failure" (repro: TI-003, `fraction` pinned
244/// at 1.0). Use a Coleman–Li-style scaled measure `‖v·g‖_∞` instead — `v_i → 0`
245/// as parameter `i` approaches the bound its descent direction points into —
246/// so an active-bound gradient no longer blocks convergence. Unbounded
247/// problems (`trust_scaling` = `None`) keep the raw norm, unchanged. The raw
248/// `gnorm` (not `opt_norm`) is what callers should record for observability.
249///
250/// NOTE: `trust_scaling` returns `v` normalized by box width (`v_i =
251/// dist_i/range_i`, in `spectrafit-solver::lm_problem`), NOT scipy TRF's
252/// unnormalized distance. So this gate is laxer than scipy's by ~1/range for
253/// a wide-box parameter sitting mid-box facing a wall; the accuracy gate
254/// (max |Δr²| vs the oracle) bounds the practical impact. Making the
255/// optimality gate use the unnormalized distance is a known follow-up, not
256/// yet done.
257///
258/// Returns `(g, gnorm, opt_norm, trust_v)` — `trust_v` is handed back (rather
259/// than recomputed) so the caller can reuse it for the Coleman–Li step-diag
260/// fold in [`compute_step_diag`] without a second `trust_scaling` call.
261fn compute_gradient_and_optimality<P: TrustRegionProblem>(
262 problem: &P,
263 j: MatRef<'_, f64>,
264 r: MatRef<'_, f64>,
265) -> (Mat<f64>, f64, f64, Option<Vec<f64>>) {
266 let g = j.transpose() * r;
267 let gnorm = g.as_ref().norm_max();
268 let p = g.nrows();
269 let g_vec: Vec<f64> = (0..p).map(|i| g[(i, 0)]).collect();
270 let trust_v = problem.trust_scaling(&g_vec);
271 let opt_norm = match &trust_v {
272 Some(v) => g_vec
273 .iter()
274 .zip(v.iter())
275 .map(|(gi, vi)| (gi * vi).abs())
276 .fold(0.0_f64, f64::max),
277 None => gnorm,
278 };
279 (g, gnorm, opt_norm, trust_v)
280}
281
282/// Per-iteration step scaling: the monotone Moré `diag`, optionally folded
283/// with Coleman–Li bound-distance scaling (`solver="trf"`) `D_i ← D_i / √v_i`
284/// so steps shrink near the bound a parameter moves toward when `v_i < 1`.
285/// `diag` itself is never modified — this returns a derived copy for the
286/// current factorization only.
287fn compute_step_diag(diag: &[f64], bound_scaling: bool, trust_v: Option<Vec<f64>>) -> Vec<f64> {
288 if bound_scaling {
289 match trust_v {
290 Some(v) => diag
291 .iter()
292 .zip(v.iter())
293 .map(|(&d, &vi)| d / vi.clamp(1e-12, 1.0).sqrt())
294 .collect(),
295 None => diag.to_vec(),
296 }
297 } else {
298 diag.to_vec()
299 }
300}
301
302/// Relative tolerance that defines "at a bound" for the active-set step:
303/// component `i` is at bound `b` when `|x_i − b| ≤ AT_BOUND_REL · max(|b|, 1)`.
304/// The same 1e-12-relative convention as the F4g stationarity check (#93); the
305/// codebase had no bound tolerance to reuse. Measured in the driver's working
306/// units (after `Parameter.scale`), i.e. on [`TrustRegionProblem::params`] and
307/// [`TrustRegionProblem::bounds`].
308const AT_BOUND_REL: f64 = 1e-12;
309
310/// Whether `x` is at the finite bound `b` within [`AT_BOUND_REL`].
311#[inline]
312fn at_bound(x: f64, b: f64) -> bool {
313 b.is_finite() && (x - b).abs() <= AT_BOUND_REL * b.abs().max(1.0)
314}
315
316/// Projection of `t` onto `[lo, hi]` (one component of `P_X`, Kanzow,
317/// Yamashita, Fukushima 2004). A value inside the box is returned unchanged,
318/// bit for bit; a NaN passes through (it is not mapped onto a bound).
319#[inline]
320fn project_onto_box(t: f64, lo: f64, hi: f64) -> f64 {
321 if t < lo {
322 lo
323 } else if t > hi {
324 hi
325 } else {
326 t
327 }
328}
329
330/// `p` projected componentwise onto `bounds`, or `None` when there is no box.
331fn project_point(p: &[f64], bounds: Option<&[(f64, f64)]>) -> Option<Vec<f64>> {
332 bounds.map(|bx| {
333 p.iter()
334 .zip(bx)
335 .map(|(&t, &(lo, hi))| project_onto_box(t, lo, hi))
336 .collect()
337 })
338}
339
340/// Indices of the free (not held) components for the active-set step, or
341/// `None` when no component is held.
342///
343/// A component is held when it is at a bound and the descent direction `−g_i`
344/// leaves the box: at the lower bound with `g_i > 0`, at the upper bound with
345/// `g_i < 0` (Bertsekas 1982, the set `I⁺`). `None` — nothing held — sends the
346/// iteration down the unchanged unbounded code path, so a problem whose bounds
347/// are never active iterates bit-identically to the driver without this step.
348fn held_components(x: &[f64], g: MatRef<'_, f64>, bounds: &[(f64, f64)]) -> Option<Vec<usize>> {
349 let held = |i: usize| {
350 let (lo, hi) = bounds[i];
351 let gi = g[(i, 0)];
352 (gi > 0.0 && at_bound(x[i], lo)) || (gi < 0.0 && at_bound(x[i], hi))
353 };
354 if (0..x.len()).any(held) {
355 Some((0..x.len()).filter(|&i| !held(i)).collect())
356 } else {
357 None
358 }
359}
360
361/// Minimise `½‖r(p)‖²` over the free parameters of `problem` with Levenberg–Marquardt.
362///
363/// On return the problem holds the best parameters found. Deterministic: no
364/// RNG, no clock — identical inputs give identical iterates — given a fixed
365/// faer parallelism policy; `spectrafit-solver::fit` sets `Par::Seq` for the
366/// whole fit, and a caller that leaves faer on its default (potentially
367/// multi-threaded) policy can see floating-point summation-order differences
368/// across runs.
369pub fn minimize<P: TrustRegionProblem>(problem: &mut P, cfg: &StrategyConfig) -> Report {
370 let m = problem.n_residuals();
371 let p = problem.n_params();
372
373 // Moré column scaling `D`: `D_j = max over iterations of ‖J_:,j‖`, floored at
374 // 1 for all-zero columns. Monotone (never shrinks) per MINPACK, so the trust
375 // region is measured in scaled units that equalise the Jacobian columns —
376 // this is what keeps the normal-equations regime well-behaved despite its κ²
377 // sensitivity. Filled from the first Jacobian below.
378 let mut diag = vec![1.0_f64; p];
379 let mut diag_initialized = false;
380
381 let mut r = Mat::<f64>::zeros(m, 1);
382 let mut r_trial = Mat::<f64>::zeros(m, 1);
383 let mut j = Mat::<f64>::zeros(m, p);
384
385 let mut n_residual_evals = 0usize;
386 let mut n_jacobian_evals = 0usize;
387 let mut n_iter = 0usize;
388
389 // Per-iteration convergence trajectory (observability only). Recorded once at
390 // the top of each outer iteration (the accepted point's cost + gradient norm)
391 // and, via the `report!` macro, the terminal point — de-duplicated so a
392 // gtol/max-eval stop at the same point is not double-counted.
393 let mut cost_history: Vec<f64> = Vec::new();
394 let mut gradient_norm_history: Vec<f64> = Vec::new();
395 // The free-parameter vector θ recorded alongside each cost_history entry
396 // (same length). Raw material for the convergence-to-truth metric.
397 let mut params_history: Vec<Vec<f64>> = Vec::new();
398
399 macro_rules! report {
400 ($term:expr, $cost:expr, $gnorm:expr) => {{
401 let final_cost: f64 = $cost;
402 let final_gnorm: f64 = $gnorm;
403 if cost_history.last() != Some(&final_cost) {
404 cost_history.push(final_cost);
405 gradient_norm_history.push(final_gnorm);
406 params_history.push(problem.params());
407 }
408 return Report {
409 termination: $term,
410 n_iter,
411 n_residual_evals,
412 n_jacobian_evals,
413 cost: final_cost,
414 gradient_norm: final_gnorm,
415 cost_history,
416 gradient_norm_history,
417 params_history,
418 };
419 }};
420 }
421
422 // Initial residual.
423 if problem.residuals_into(r.as_mut()).is_err() {
424 report!(Termination::NumericalError, f64::INFINITY, 0.0);
425 }
426 n_residual_evals += 1;
427 let mut cost = 0.5 * r.as_ref().squared_norm_l2();
428 if !cost.is_finite() {
429 // NaN/inf in the starting residual (e.g. log of a non-positive model
430 // value) — bail immediately rather than spin to NoImprovement.
431 report!(Termination::NumericalError, cost, 0.0);
432 }
433 if cost == 0.0 {
434 report!(Termination::ResidualsZero, cost, 0.0);
435 }
436
437 let mut lambda = cfg.initial_lambda;
438 let mut nu = 2.0_f64;
439
440 // Box for the active-set projected step; ignored unless it has one entry
441 // per free parameter.
442 let bounds: Option<Vec<(f64, f64)>> = problem.bounds().filter(|b| b.len() == p);
443
444 loop {
445 // Jacobian at the current point.
446 if problem.jacobian_into(j.as_mut()).is_err() {
447 report!(Termination::NumericalError, cost, 0.0);
448 }
449 n_jacobian_evals += 1;
450
451 // Update the Moré column scaling from this Jacobian's column norms.
452 update_more_scaling(&mut diag, &mut diag_initialized, j.as_ref());
453
454 // Gradient g = Jᵀr and first-order optimality test — see
455 // `compute_gradient_and_optimality`'s doc comment for the Coleman–Li
456 // rationale behind the scaled measure.
457 let (g, gnorm, opt_norm, trust_v) =
458 compute_gradient_and_optimality(problem, j.as_ref(), r.as_ref());
459 // Record the accepted point's trajectory (index 0 = initial point).
460 // `problem` holds the accepted parameters here (p_cur), so `params()`
461 // is θ at this point — kept in lock-step length with cost_history.
462 cost_history.push(cost);
463 gradient_norm_history.push(gnorm);
464 params_history.push(problem.params());
465 if opt_norm <= cfg.gtol {
466 report!(Termination::Gtol, cost, gnorm);
467 }
468
469 // Per-iteration step scaling — see `compute_step_diag`'s doc comment.
470 let step_diag = compute_step_diag(&diag, cfg.bound_scaling, trust_v);
471
472 // Inner λ search: shrink the trust region (raise λ) until a step is
473 // accepted or the budget runs out. `p_cur` is invariant across trials —
474 // params only change on accept (we break) or reject (we restore to
475 // p_cur) — so capture it once instead of cloning it every trial.
476 let p_cur = problem.params();
477 let mut bumps = 0usize;
478
479 // Bump λ (shrink the trust region) after a rejected/failed trial, advance
480 // the Nielsen ν schedule, and bail out with `NoImprovement` once the
481 // per-outer-iteration λ-search budget is exhausted (200 bumps, or λ
482 // overflowing to non-finite). Identical 4-line sequence at every
483 // "this trial doesn't work" exit from the inner loop below — a failed
484 // factorization, a non-positive predicted reduction (pre- or
485 // post-geodesic), and an outright rejected step — so it is named once
486 // here instead of repeated verbatim at each call site. Local macro (same
487 // technique as `report!` above) rather than a function: it mutates
488 // `lambda`/`nu`/`bumps` and reads `cost`/`gnorm` from the enclosing
489 // scope, so a helper would need all five threaded through its signature
490 // for no benefit. Defined here (not near `report!` above) because macro
491 // hygiene resolves its free identifiers against what's in scope at the
492 // macro's *definition* point, not its call site — `bumps` (declared just
493 // above) must already exist for that to work.
494 macro_rules! bump_lambda {
495 () => {{
496 lambda *= nu;
497 nu *= 2.0;
498 bumps += 1;
499 if !lambda.is_finite() || bumps > 200 {
500 report!(Termination::NoImprovement, cost, gnorm);
501 }
502 }};
503 }
504
505 // Active-set projected step (#93; module doc for the sources). Taken
506 // only when some component is held; otherwise fall through to the
507 // unchanged unbounded step below.
508 if let Some((bx, free)) = bounds
509 .as_deref()
510 .and_then(|bx| held_components(&p_cur, g.as_ref(), bx).map(|free| (bx, free)))
511 {
512 // Every component held: the projected gradient is zero — a
513 // stationary point of the box-constrained problem. Stop as a
514 // first-order success; no trial, so no λ growth.
515 if free.is_empty() {
516 report!(Termination::Gtol, cost, gnorm);
517 }
518 let nf = free.len();
519 // Damped step on the free subspace: the same factorization path,
520 // with the held columns of J, entries of g and of the step scaling
521 // removed (Moré `diag`, Coleman–Li fold and the Nielsen λ are
522 // unchanged for the free components).
523 let j_free = Mat::from_fn(m, nf, |i, c| j[(i, free[c])]);
524 let g_free = Mat::from_fn(nf, 1, |c, _| g[(free[c], 0)]);
525 let diag_free: Vec<f64> = free.iter().map(|&i| step_diag[i]).collect();
526 let factor_free: StepFactor = match factorize(cfg.kind, j_free.as_ref(), &diag_free) {
527 Ok(f) => f,
528 Err(_) => report!(Termination::NumericalError, cost, gnorm),
529 };
530 loop {
531 let step = match factor_free.solve(g_free.as_ref(), r.as_ref(), &diag_free, lambda)
532 {
533 Ok(s) => s,
534 Err(StepError::NotPositiveDefinite) | Err(StepError::Factorization(_)) => {
535 bump_lambda!();
536 continue;
537 }
538 };
539 if !step.predicted_reduction.is_finite() {
540 bump_lambda!();
541 continue;
542 }
543 // Held components keep their value; free ones take the step
544 // and are projected (clamped, not reflected) onto the box.
545 // Geodesic acceleration is not applied while a component is
546 // held: it is defined for the unconstrained step.
547 let mut p_trial = p_cur.clone();
548 // A non-zero step component that lands inside the box and
549 // still leaves p unchanged was rounded away, not clamped.
550 let mut rounded_away = false;
551 for (c, &i) in free.iter().enumerate() {
552 let (lo, hi) = bx[i];
553 let d = step.delta[(c, 0)];
554 let t = p_cur[i] + d;
555 rounded_away |= d != 0.0 && t == p_cur[i] && t > lo && t < hi;
556 p_trial[i] = t.max(lo).min(hi);
557 }
558 // Fully clamped: the projection leaves nothing of the step.
559 // With a positive-definite damped matrix this needs the free
560 // gradient to vanish (each blocked component has g_i·δ_i ≥ 0,
561 // while gᵀδ = −g_Fᵀ(H_F + λD_F²)⁻¹g_F < 0 otherwise), so the
562 // point is stationary. Not a rejection: stop, no λ growth.
563 // A step that only rounded away (λ grown by rejections until
564 // p + δ == p) proves nothing: keep the rejection semantics,
565 // which end in `NoImprovement` as on the unbounded path.
566 if p_trial == p_cur {
567 if rounded_away {
568 bump_lambda!();
569 continue;
570 }
571 report!(Termination::Gtol, cost, gnorm);
572 }
573 // Model reduction of the projected step δₚ = p_trial − p_cur.
574 let delta_p = Mat::from_fn(p, 1, |i, _| p_trial[i] - p_cur[i]);
575 let jdp = j.as_ref() * delta_p.as_ref();
576 let pred =
577 -col_dot(g.as_ref(), delta_p.as_ref()) - 0.5 * jdp.as_ref().squared_norm_l2();
578 if !(pred.is_finite() && pred > 0.0) {
579 bump_lambda!();
580 continue;
581 }
582
583 problem.set_params(&p_trial);
584 if problem.residuals_into(r_trial.as_mut()).is_err() {
585 problem.set_params(&p_cur);
586 report!(Termination::NumericalError, cost, gnorm);
587 }
588 n_residual_evals += 1;
589 let cost_trial = 0.5 * r_trial.as_ref().squared_norm_l2();
590 let actual = cost - cost_trial;
591 // The problem may still move the point (e.g. a scaled bound
592 // rounding by an ulp): judge against the applied step then.
593 let p_applied = problem.params();
594 let pred_eff = if p_applied != p_trial {
595 let delta_a = Mat::from_fn(p, 1, |i, _| p_applied[i] - p_cur[i]);
596 let jda = j.as_ref() * delta_a.as_ref();
597 -col_dot(g.as_ref(), delta_a.as_ref()) - 0.5 * jda.as_ref().squared_norm_l2()
598 } else {
599 pred
600 };
601 let rho = if pred_eff.is_finite() && pred_eff > 0.0 {
602 actual / pred_eff
603 } else {
604 0.0
605 };
606
607 if rho > 1e-4 {
608 // Accept — same bookkeeping and stopping tests as the
609 // unbounded path below.
610 let mut step_norm2 = 0.0;
611 let mut param_norm2 = 0.0;
612 for i in 0..p {
613 let d = p_applied[i] - p_cur[i];
614 step_norm2 += d * d;
615 param_norm2 += p_applied[i] * p_applied[i];
616 }
617 let step_norm = step_norm2.sqrt();
618 let param_norm = param_norm2.sqrt();
619
620 std::mem::swap(&mut r, &mut r_trial);
621 cost = cost_trial;
622 n_iter += 1;
623
624 lambda *= f64::max(1.0 / 3.0, 1.0 - (2.0 * rho - 1.0).powi(3));
625 nu = 2.0;
626
627 if cost == 0.0 {
628 report!(Termination::ResidualsZero, cost, gnorm);
629 }
630 if actual <= cfg.ftol * cost.max(f64::MIN_POSITIVE) {
631 report!(Termination::Ftol, cost, gnorm);
632 }
633 if step_norm <= cfg.xtol * (cfg.xtol + param_norm) {
634 report!(Termination::Xtol, cost, gnorm);
635 }
636 break;
637 } else {
638 problem.set_params(&p_cur);
639 bump_lambda!();
640 }
641
642 if n_residual_evals >= cfg.max_nfev {
643 report!(Termination::MaxEval, cost, gnorm);
644 }
645 }
646 if n_residual_evals >= cfg.max_nfev {
647 report!(Termination::MaxEval, cost, gnorm);
648 }
649 continue;
650 }
651
652 // Factor the step operator ONCE for this outer iteration (the O(m·p²)
653 // work: forming JᵀJ, or the thin SVD of J̃). `J` and `step_diag` are
654 // fixed across the inner λ search — only λ changes — so every λ trial and
655 // the geodesic acceleration solve reuse this factorization.
656 let factor: StepFactor = match factorize(cfg.kind, j.as_ref(), &step_diag) {
657 Ok(f) => f,
658 Err(_) => report!(Termination::NumericalError, cost, gnorm),
659 };
660
661 loop {
662 let step = match factor.solve(g.as_ref(), r.as_ref(), &step_diag, lambda) {
663 Ok(s) => s,
664 Err(StepError::NotPositiveDefinite) | Err(StepError::Factorization(_)) => {
665 bump_lambda!();
666 continue;
667 }
668 };
669 let delta = step.delta;
670 let pred = step.predicted_reduction;
671 if !(pred.is_finite() && pred > 0.0) {
672 bump_lambda!();
673 continue;
674 }
675
676 // Optional geodesic acceleration: augment the velocity δ with the
677 // second-directional-derivative term. Re-validate the predicted
678 // reduction since the augmented step may not be a descent direction.
679 let (delta, pred) = if cfg.geodesic {
680 geodesic_augment(
681 problem,
682 &factor,
683 j.as_ref(),
684 r.as_ref(),
685 g.as_ref(),
686 &p_cur,
687 bounds.as_deref(),
688 delta,
689 &step_diag,
690 lambda,
691 cfg.geodesic_h,
692 cfg.geodesic_alpha,
693 &mut n_residual_evals,
694 )
695 } else {
696 (delta, pred)
697 };
698 if !(pred.is_finite() && pred > 0.0) {
699 bump_lambda!();
700 continue;
701 }
702
703 // Trial point p_cur + δ, projected onto the box when the problem
704 // exposes one (Kanzow, Yamashita, Fukushima 2004, projected LM
705 // step; module doc). Inside the box the projection is the identity.
706 let p_trial: Vec<f64> = (0..p).map(|i| p_cur[i] + delta[(i, 0)]).collect();
707 let p_trial_proj = project_point(&p_trial, bounds.as_deref());
708 problem.set_params(p_trial_proj.as_deref().unwrap_or(&p_trial));
709 if problem.residuals_into(r_trial.as_mut()).is_err() {
710 // Restore the last accepted point before bailing so `problem`
711 // holds the accepted θ (not the NaN-producing trial) when
712 // `report!` fires — keeps params_history lock-step with
713 // cost_history regardless of the dedup, and makes the failed
714 // result report the last good parameters.
715 problem.set_params(&p_cur);
716 report!(Termination::NumericalError, cost, gnorm);
717 }
718 n_residual_evals += 1;
719 let cost_trial = 0.5 * r_trial.as_ref().squared_norm_l2();
720
721 let actual = cost - cost_trial;
722 // Gain ratio. When the projection onto the box (above) or the
723 // problem's own `set_params` clipped the proposed step, judging
724 // `actual` against the RAW step's predicted reduction is wrong:
725 // the phantom reduction from the clipped direction dominates
726 // `pred`, ρ collapses, and legitimate refinements of the still-
727 // free directions get rejected until λ inflates to NoImprovement.
728 // Recompute the model reduction for the
729 // APPLIED step δₐ = p_applied − p_cur in that case. Interior
730 // (unclipped) steps keep the factorization's `pred` unchanged.
731 // `p_trial` is the raw, unprojected p_cur + δ, so a step clipped by
732 // the projection is detected here as before.
733 let p_applied = problem.params();
734 let clipped = p_applied.iter().zip(p_trial.iter()).any(|(a, t)| a != t);
735 let pred_eff = if clipped {
736 let delta_a = Mat::from_fn(p, 1, |i, _| p_applied[i] - p_cur[i]);
737 let jda = j.as_ref() * delta_a.as_ref();
738 -col_dot(g.as_ref(), delta_a.as_ref()) - 0.5 * jda.as_ref().squared_norm_l2()
739 } else {
740 pred
741 };
742 let rho = if pred_eff.is_finite() && pred_eff > 0.0 {
743 actual / pred_eff
744 } else {
745 // Fully-clamped (δₐ = 0) or degenerate applied step: no
746 // model reduction to judge against — treat as a rejection.
747 // (Reached only with nothing held; a fully clamped step of
748 // the active-set path above is a stationary stop instead.)
749 0.0
750 };
751
752 if rho > 1e-4 {
753 // Accept. Step norm uses the parameters the problem actually
754 // applied (post-projection), not the proposed δ.
755 let mut step_norm2 = 0.0;
756 let mut param_norm2 = 0.0;
757 for i in 0..p {
758 let d = p_applied[i] - p_cur[i];
759 step_norm2 += d * d;
760 param_norm2 += p_applied[i] * p_applied[i];
761 }
762 let step_norm = step_norm2.sqrt();
763 let param_norm = param_norm2.sqrt();
764
765 std::mem::swap(&mut r, &mut r_trial);
766 cost = cost_trial;
767 n_iter += 1;
768
769 // Nielsen λ decrease on a successful step.
770 lambda *= f64::max(1.0 / 3.0, 1.0 - (2.0 * rho - 1.0).powi(3));
771 nu = 2.0;
772
773 if cost == 0.0 {
774 report!(Termination::ResidualsZero, cost, gnorm);
775 }
776 if actual <= cfg.ftol * cost.max(f64::MIN_POSITIVE) {
777 report!(Termination::Ftol, cost, gnorm);
778 }
779 if step_norm <= cfg.xtol * (cfg.xtol + param_norm) {
780 report!(Termination::Xtol, cost, gnorm);
781 }
782 break; // re-evaluate the Jacobian at the new point
783 } else {
784 // Reject: restore parameters, shrink the trust region.
785 problem.set_params(&p_cur);
786 bump_lambda!();
787 }
788
789 if n_residual_evals >= cfg.max_nfev {
790 report!(Termination::MaxEval, cost, gnorm);
791 }
792 }
793
794 if n_residual_evals >= cfg.max_nfev {
795 // `gnorm` — ‖Jᵀr‖∞ at the start of this outer iteration, the most
796 // recent point where the Jacobian was evaluated. This used to
797 // recompute `(Jᵀ r).norm_max()` pairing the OLD `j` with the
798 // post-step `r`, a quantity that is the gradient at neither point.
799 // See `Report::gradient_norm`.
800 report!(Termination::MaxEval, cost, gnorm);
801 }
802 }
803}