numeris 0.5.13

Pure-Rust numerical algorithms library — high performance with SIMD support while also supporting no-std for embedded and WASM targets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Dynamically-sized variants of the optimization routines.
//!
//! Mirrors the fixed-size API but uses [`DynVector`] / [`DynMatrix`] so the
//! parameter and residual dimensions are chosen at runtime. Requires the
//! `alloc` feature.

use crate::dynmatrix::{DynMatrix, DynVector};
use crate::traits::FloatScalar;

use super::line_search::backtracking_armijo_dyn;
use super::{BfgsSettings, GaussNewtonSettings, LmSettings, OptimError};

// ── Result types ────────────────────────────────────────────────────

/// Result of a dynamically-sized unconstrained minimization algorithm.
#[derive(Debug, Clone)]
pub struct MinimizeResultDyn<T: FloatScalar> {
    /// Approximate minimizer.
    pub x: DynVector<T>,
    /// Function value at the minimizer: `f(x)`.
    pub fx: T,
    /// Gradient norm at the minimizer.
    pub grad_norm: T,
    /// Number of iterations performed.
    pub iterations: usize,
    /// Number of function evaluations.
    pub f_evals: usize,
    /// Number of gradient evaluations.
    pub grad_evals: usize,
}

/// Result of a dynamically-sized nonlinear least-squares algorithm.
#[derive(Debug, Clone)]
pub struct LeastSquaresResultDyn<T: FloatScalar> {
    /// Approximate minimizer of `0.5 * ||r(x)||^2`.
    pub x: DynVector<T>,
    /// Final cost: `0.5 * ||r(x)||^2`.
    pub cost: T,
    /// Gradient norm: `||J^T r||`.
    pub grad_norm: T,
    /// Number of iterations performed.
    pub iterations: usize,
    /// Number of residual evaluations.
    pub r_evals: usize,
    /// Number of Jacobian evaluations.
    pub j_evals: usize,
}

// ── Vector helpers (private) ────────────────────────────────────────

#[inline]
fn vec_add<T: FloatScalar>(a: &DynVector<T>, b: &DynVector<T>) -> DynVector<T> {
    debug_assert_eq!(a.len(), b.len());
    let n = a.len();
    let mut out = DynVector::zeros(n);
    for i in 0..n {
        out[i] = a[i] + b[i];
    }
    out
}

#[inline]
fn vec_sub<T: FloatScalar>(a: &DynVector<T>, b: &DynVector<T>) -> DynVector<T> {
    debug_assert_eq!(a.len(), b.len());
    let n = a.len();
    let mut out = DynVector::zeros(n);
    for i in 0..n {
        out[i] = a[i] - b[i];
    }
    out
}

#[inline]
fn vec_neg<T: FloatScalar>(a: &DynVector<T>) -> DynVector<T> {
    let n = a.len();
    let mut out = DynVector::zeros(n);
    for i in 0..n {
        out[i] = T::zero() - a[i];
    }
    out
}

#[inline]
fn vec_scale<T: FloatScalar>(a: &DynVector<T>, s: T) -> DynVector<T> {
    let n = a.len();
    let mut out = DynVector::zeros(n);
    for i in 0..n {
        out[i] = a[i] * s;
    }
    out
}

/// `m * v` where `m` is M×N and `v` is N → M-vector.
#[inline]
fn mat_vec<T: FloatScalar>(m: &DynMatrix<T>, v: &DynVector<T>) -> DynVector<T> {
    let nr = m.nrows();
    let nc = m.ncols();
    debug_assert_eq!(nc, v.len());
    let mut out = DynVector::zeros(nr);
    for j in 0..nc {
        let vj = v[j];
        for i in 0..nr {
            out[i] = out[i] + m[(i, j)] * vj;
        }
    }
    out
}

/// `m^T * v` where `m` is M×N and `v` is M → N-vector.
#[inline]
fn matt_vec<T: FloatScalar>(m: &DynMatrix<T>, v: &DynVector<T>) -> DynVector<T> {
    let nr = m.nrows();
    let nc = m.ncols();
    debug_assert_eq!(nr, v.len());
    let mut out = DynVector::zeros(nc);
    for j in 0..nc {
        let mut s = T::zero();
        for i in 0..nr {
            s = s + m[(i, j)] * v[i];
        }
        out[j] = s;
    }
    out
}

// ── Finite differences ──────────────────────────────────────────────

/// Approximate the Jacobian of `f: R^n → R^m` using forward finite differences.
///
/// Uses step size `h_j = sqrt(ε) * max(|x_j|, 1)` for each component,
/// requiring `n + 1` function evaluations. Always sequential; the closure may be
/// `FnMut`. For a parallel version see [`finite_difference_jacobian_dyn_par`]
/// (requires the `rayon` feature).
///
/// # Example
///
/// ```
/// use numeris::optim::finite_difference_jacobian_dyn;
/// use numeris::DynVector;
///
/// let x = DynVector::from_slice(&[3.0_f64, 4.0]);
/// let j = finite_difference_jacobian_dyn(
///     |x: &DynVector<f64>| DynVector::from_slice(&[x[0] * x[0], x[0] * x[1]]),
///     &x,
/// );
/// assert!((j[(0, 0)] - 6.0).abs() < 1e-5);
/// assert!((j[(1, 1)] - 3.0).abs() < 1e-5);
/// ```
pub fn finite_difference_jacobian_dyn<T: FloatScalar>(
    mut f: impl FnMut(&DynVector<T>) -> DynVector<T>,
    x: &DynVector<T>,
) -> DynMatrix<T> {
    let sqrt_eps = T::epsilon().sqrt();
    let f0 = f(x);
    let n = x.len();
    let m = f0.len();
    let mut jac = DynMatrix::zeros(m, n);

    let mut x_pert = x.clone();
    for j in 0..n {
        let h = sqrt_eps * x[j].abs().max(T::one());
        x_pert[j] = x[j] + h;
        let f_pert = f(&x_pert);
        x_pert[j] = x[j];
        for i in 0..m {
            jac[(i, j)] = (f_pert[i] - f0[i]) / h;
        }
    }

    jac
}

/// Approximate the gradient of `f: R^n → R` using forward finite differences.
///
/// Uses step size `h_j = sqrt(ε) * max(|x_j|, 1)` for each component,
/// requiring `n + 1` function evaluations. Always sequential; the closure may be
/// `FnMut`. For a parallel version see [`finite_difference_gradient_dyn_par`]
/// (requires the `rayon` feature).
///
/// # Example
///
/// ```
/// use numeris::optim::finite_difference_gradient_dyn;
/// use numeris::DynVector;
///
/// let x = DynVector::from_slice(&[3.0_f64, 4.0]);
/// let g = finite_difference_gradient_dyn(
///     |x: &DynVector<f64>| x[0] * x[0] + x[1] * x[1] * 2.0,
///     &x,
/// );
/// assert!((g[0] - 6.0).abs() < 1e-5);
/// assert!((g[1] - 16.0).abs() < 1e-5);
/// ```
pub fn finite_difference_gradient_dyn<T: FloatScalar>(
    mut f: impl FnMut(&DynVector<T>) -> T,
    x: &DynVector<T>,
) -> DynVector<T> {
    let sqrt_eps = T::epsilon().sqrt();
    let f0 = f(x);
    let n = x.len();
    let mut grad = DynVector::zeros(n);

    let mut x_pert = x.clone();
    for j in 0..n {
        let h = sqrt_eps * x[j].abs().max(T::one());
        x_pert[j] = x[j] + h;
        grad[j] = (f(&x_pert) - f0) / h;
        x_pert[j] = x[j];
    }

    grad
}

/// Column count at or above which [`finite_difference_jacobian_dyn_par`] /
/// [`finite_difference_gradient_dyn_par`] fan their columns out across threads.
/// Below it the columns are computed sequentially.
///
/// The crossover that actually matters is the *cost of `f`*, which cannot be
/// known here, so column count is only a coarse proxy: with a trivially cheap
/// `f`, even a few dozen columns can run faster sequentially (see
/// `bench/results.md`). The guard is deliberately low to favor the regime
/// parallelism is for — an expensive `f` (an ODE step, a measurement model),
/// where the win is large even at small N.
#[cfg(feature = "rayon")]
const FD_PAR_MIN_COLS: usize = 8;

/// Parallel forward-difference Jacobian (requires the `rayon` feature).
///
/// Identical result to [`finite_difference_jacobian_dyn`], but the `n` columns
/// — each an independent evaluation of `f` — are computed across threads,
/// writing into disjoint slices of the output (so the value is independent of
/// thread count). Worthwhile when `f` is expensive (e.g. an ODE integration);
/// for a cheap `f` the sequential version is faster.
///
/// Because the columns run concurrently the closure must be `Fn + Sync + Send`
/// rather than `FnMut`. This is a *separate* function precisely so enabling the
/// `rayon` feature never changes the signature of the sequential routine.
///
/// # Example
///
/// ```
/// use numeris::optim::finite_difference_jacobian_dyn_par;
/// use numeris::DynVector;
///
/// let x = DynVector::from_slice(&[3.0_f64, 4.0]);
/// let j = finite_difference_jacobian_dyn_par(
///     |x: &DynVector<f64>| DynVector::from_slice(&[x[0] * x[0], x[0] * x[1]]),
///     &x,
/// );
/// assert!((j[(0, 0)] - 6.0).abs() < 1e-5);
/// assert!((j[(1, 1)] - 3.0).abs() < 1e-5);
/// ```
#[cfg(feature = "rayon")]
pub fn finite_difference_jacobian_dyn_par<T: FloatScalar + Send + Sync>(
    f: impl Fn(&DynVector<T>) -> DynVector<T> + Sync + Send,
    x: &DynVector<T>,
) -> DynMatrix<T> {
    let sqrt_eps = T::epsilon().sqrt();
    let f0 = f(x);
    let m = f0.len();
    let f0 = f0.as_slice();
    let mut jac = DynMatrix::zeros(m, x.len());

    crate::par::for_each_chunk_mut(jac.as_mut_slice(), m, FD_PAR_MIN_COLS, |j, col| {
        let h = sqrt_eps * x[j].abs().max(T::one());
        let mut x_pert = x.clone();
        x_pert[j] = x_pert[j] + h;
        let f_pert = f(&x_pert);
        for i in 0..m {
            col[i] = (f_pert[i] - f0[i]) / h;
        }
    });

    jac
}

/// Parallel forward-difference gradient (requires the `rayon` feature).
///
/// The parallel counterpart of [`finite_difference_gradient_dyn`]: the `n`
/// components are computed across threads into disjoint elements (result
/// independent of thread count). Requires `Fn + Sync + Send`; kept separate so
/// enabling `rayon` never changes the sequential routine's signature.
///
/// # Example
///
/// ```
/// use numeris::optim::finite_difference_gradient_dyn_par;
/// use numeris::DynVector;
///
/// let x = DynVector::from_slice(&[3.0_f64, 4.0]);
/// let g = finite_difference_gradient_dyn_par(
///     |x: &DynVector<f64>| x[0] * x[0] + x[1] * x[1] * 2.0,
///     &x,
/// );
/// assert!((g[0] - 6.0).abs() < 1e-5);
/// assert!((g[1] - 16.0).abs() < 1e-5);
/// ```
#[cfg(feature = "rayon")]
pub fn finite_difference_gradient_dyn_par<T: FloatScalar + Send + Sync>(
    f: impl Fn(&DynVector<T>) -> T + Sync + Send,
    x: &DynVector<T>,
) -> DynVector<T> {
    let sqrt_eps = T::epsilon().sqrt();
    let f0 = f(x);
    let mut grad = DynVector::zeros(x.len());

    crate::par::for_each_chunk_mut(grad.as_mut_slice(), 1, FD_PAR_MIN_COLS, |j, cell| {
        let h = sqrt_eps * x[j].abs().max(T::one());
        let mut x_pert = x.clone();
        x_pert[j] = x_pert[j] + h;
        cell[0] = (f(&x_pert) - f0) / h;
    });

    grad
}

// ── BFGS ────────────────────────────────────────────────────────────

/// Minimize `f: R^n → R` using the BFGS quasi-Newton method (dynamic dimension).
///
/// Maintains an `n × n` inverse-Hessian approximation on the heap. Uses Armijo
/// backtracking line search.
///
/// # Arguments
///
/// * `f` — objective function
/// * `grad` — gradient `∇f`
/// * `x0` — initial guess
/// * `settings` — convergence tolerances and algorithm parameters
///
/// # Example
///
/// ```
/// use numeris::optim::{minimize_bfgs_dyn, BfgsSettings};
/// use numeris::DynVector;
///
/// // Minimize f(x) = (x0-1)^2 + (x1-2)^2
/// let r = minimize_bfgs_dyn(
///     |x: &DynVector<f64>| (x[0] - 1.0).powi(2) + (x[1] - 2.0).powi(2),
///     |x: &DynVector<f64>| DynVector::from_slice(&[2.0 * (x[0] - 1.0), 2.0 * (x[1] - 2.0)]),
///     &DynVector::from_slice(&[0.0, 0.0]),
///     &BfgsSettings::default(),
/// ).unwrap();
/// assert!((r.x[0] - 1.0).abs() < 1e-6);
/// assert!((r.x[1] - 2.0).abs() < 1e-6);
/// ```
pub fn minimize_bfgs_dyn<T: FloatScalar>(
    mut f: impl FnMut(&DynVector<T>) -> T,
    mut grad: impl FnMut(&DynVector<T>) -> DynVector<T>,
    x0: &DynVector<T>,
    settings: &BfgsSettings<T>,
) -> Result<MinimizeResultDyn<T>, OptimError> {
    let n = x0.len();
    let mut x = x0.clone();
    let mut fx = f(&x);
    let mut g = grad(&x);
    let mut f_evals = 1usize;
    let mut grad_evals = 1usize;

    assert_eq!(g.len(), n, "gradient length must match x length");

    // Inverse Hessian approximation, initialized to identity
    let mut h = DynMatrix::<T>::zeros(n, n);
    for i in 0..n {
        h[(i, i)] = T::one();
    }

    for iter in 0..settings.max_iter {
        let g_norm = g.norm();

        if g_norm < settings.grad_tol {
            return Ok(MinimizeResultDyn {
                x,
                fx,
                grad_norm: g_norm,
                iterations: iter,
                f_evals,
                grad_evals,
            });
        }

        // Search direction: p = -H * g
        let hg = mat_vec(&h, &g);
        let p_init = vec_neg(&hg);

        let grad_dot_p = g.dot(&p_init);
        let (p, h_reset) = if grad_dot_p >= T::zero() {
            // Not a descent direction, reset H to identity
            (vec_neg(&g), true)
        } else {
            (p_init, false)
        };

        let grad_dot_p = if h_reset { -g.dot(&g) } else { grad_dot_p };

        let (alpha, f_new, ls_evals) = backtracking_armijo_dyn(
            fx,
            grad_dot_p,
            &x,
            &p,
            &mut f,
            settings.armijo_c1,
            settings.armijo_rho,
            settings.max_ls_iter,
        )?;
        f_evals += ls_evals;

        let s = vec_scale(&p, alpha);
        let x_new = vec_add(&x, &s);
        let g_new = grad(&x_new);
        grad_evals += 1;

        let y = vec_sub(&g_new, &g);
        let ys = y.dot(&s);

        if s.norm() < settings.x_tol * (T::one() + x.norm()) {
            return Ok(MinimizeResultDyn {
                x: x_new,
                fx: f_new,
                grad_norm: g_new.norm(),
                iterations: iter + 1,
                f_evals,
                grad_evals,
            });
        }

        if (fx - f_new).abs() < settings.f_tol * (T::one() + fx.abs()) {
            return Ok(MinimizeResultDyn {
                x: x_new,
                fx: f_new,
                grad_norm: g_new.norm(),
                iterations: iter + 1,
                f_evals,
                grad_evals,
            });
        }

        if h_reset {
            for i in 0..n {
                for j in 0..n {
                    h[(i, j)] = if i == j { T::one() } else { T::zero() };
                }
            }
        }

        if ys > T::epsilon() {
            let rho = T::one() / ys;

            // hy = H * y
            let hy = mat_vec(&h, &y);
            let yhy = y.dot(&hy);
            let factor = (T::one() + rho * yhy) * rho;

            // H = H + factor * s s^T - rho * (hy s^T + s hy^T)
            for i in 0..n {
                for j in 0..n {
                    h[(i, j)] =
                        h[(i, j)] + factor * s[i] * s[j] - rho * (hy[i] * s[j] + s[i] * hy[j]);
                }
            }
        }

        x = x_new;
        fx = f_new;
        g = g_new;
    }

    Err(OptimError::MaxIterations)
}

// ── Gauss-Newton ────────────────────────────────────────────────────

/// Solve a nonlinear least-squares problem using Gauss-Newton (dynamic dimension).
///
/// Minimizes `0.5 * ||r(x)||^2` where `r: R^n → R^m` and `J: R^n → R^{m×n}`.
/// Each iteration solves the linear least-squares subproblem via QR.
///
/// Requires `m >= n`.
///
/// # Example
///
/// ```
/// use numeris::optim::{least_squares_gn_dyn, GaussNewtonSettings};
/// use numeris::{DynMatrix, DynVector};
///
/// let a = DynMatrix::from_rows(3, 2, &[1.0_f64, 1.0, 1.0, 2.0, 1.0, 3.0]);
/// let b = DynVector::from_slice(&[1.0, 2.0, 3.0]);
/// let r = least_squares_gn_dyn(
///     |x: &DynVector<f64>| {
///         let mut out = DynVector::zeros(3);
///         for i in 0..3 {
///             out[i] = a[(i, 0)] * x[0] + a[(i, 1)] * x[1] - b[i];
///         }
///         out
///     },
///     |_: &DynVector<f64>| a.clone(),
///     &DynVector::from_slice(&[0.0, 0.0]),
///     &GaussNewtonSettings::default(),
/// ).unwrap();
/// assert!(r.iterations <= 2);
/// ```
pub fn least_squares_gn_dyn<T: FloatScalar>(
    mut residual: impl FnMut(&DynVector<T>) -> DynVector<T>,
    mut jacobian: impl FnMut(&DynVector<T>) -> DynMatrix<T>,
    x0: &DynVector<T>,
    settings: &GaussNewtonSettings<T>,
) -> Result<LeastSquaresResultDyn<T>, OptimError> {
    let n = x0.len();
    let mut x = x0.clone();
    let mut r = residual(&x);
    let mut r_evals = 1usize;
    let mut j_evals = 0usize;

    let half = T::one() / (T::one() + T::one());
    let mut cost = r.dot(&r) * half;

    for iter in 0..settings.max_iter {
        let j = jacobian(&x);
        j_evals += 1;
        assert_eq!(
            j.nrows(),
            r.len(),
            "jacobian rows must match residual length"
        );
        assert_eq!(j.ncols(), n, "jacobian cols must match x length");

        let g = matt_vec(&j, &r);
        let g_norm = g.norm();

        if g_norm < settings.grad_tol {
            return Ok(LeastSquaresResultDyn {
                x,
                cost,
                grad_norm: g_norm,
                iterations: iter,
                r_evals,
                j_evals,
            });
        }

        // Solve J * delta = -r via QR
        let neg_r = vec_neg(&r);
        let qr = j.qr().map_err(|_| OptimError::Singular)?;
        let delta = qr.solve(&neg_r);

        let x_new = vec_add(&x, &delta);
        r = residual(&x_new);
        r_evals += 1;
        let cost_new = r.dot(&r) * half;

        if delta.norm() < settings.x_tol * (T::one() + x.norm()) {
            return Ok(LeastSquaresResultDyn {
                x: x_new,
                cost: cost_new,
                grad_norm: g_norm,
                iterations: iter + 1,
                r_evals,
                j_evals,
            });
        }

        if (cost - cost_new).abs() < settings.f_tol * (T::one() + cost.abs()) {
            return Ok(LeastSquaresResultDyn {
                x: x_new,
                cost: cost_new,
                grad_norm: g_norm,
                iterations: iter + 1,
                r_evals,
                j_evals,
            });
        }

        x = x_new;
        cost = cost_new;
    }

    Err(OptimError::MaxIterations)
}

// ── Levenberg-Marquardt ─────────────────────────────────────────────

/// Solve a nonlinear least-squares problem using Levenberg-Marquardt (dynamic dimension).
///
/// Minimizes `0.5 * ||r(x)||^2` using damped normal equations:
/// `(J^T J + μ I) δ = -J^T r`.
///
/// # Example
///
/// ```
/// use numeris::optim::{least_squares_lm_dyn, LmSettings};
/// use numeris::{DynMatrix, DynVector};
///
/// let t = [0.0_f64, 1.0, 2.0, 3.0, 4.0];
/// let y = [2.0, 2.7, 3.65, 4.95, 6.7];
///
/// let r = least_squares_lm_dyn(
///     |x: &DynVector<f64>| {
///         let mut res = DynVector::zeros(5);
///         for i in 0..5 {
///             res[i] = x[0] * (x[1] * t[i]).exp() - y[i];
///         }
///         res
///     },
///     |x: &DynVector<f64>| {
///         let mut j = DynMatrix::zeros(5, 2);
///         for i in 0..5 {
///             let e = (x[1] * t[i]).exp();
///             j[(i, 0)] = e;
///             j[(i, 1)] = x[0] * t[i] * e;
///         }
///         j
///     },
///     &DynVector::from_slice(&[1.0, 0.1]),
///     &LmSettings::default(),
/// ).unwrap();
/// assert!(r.cost < 0.1);
/// ```
pub fn least_squares_lm_dyn<T: FloatScalar>(
    mut residual: impl FnMut(&DynVector<T>) -> DynVector<T>,
    mut jacobian: impl FnMut(&DynVector<T>) -> DynMatrix<T>,
    x0: &DynVector<T>,
    settings: &LmSettings<T>,
) -> Result<LeastSquaresResultDyn<T>, OptimError> {
    let n = x0.len();
    let mut x = x0.clone();
    let mut r = residual(&x);
    let mut r_evals = 1usize;
    let mut j_evals = 0usize;

    let half = T::one() / (T::one() + T::one());
    let mut cost = r.dot(&r) * half;
    let mut mu = settings.mu_init;

    for iter in 0..settings.max_iter {
        let j = jacobian(&x);
        j_evals += 1;
        assert_eq!(
            j.nrows(),
            r.len(),
            "jacobian rows must match residual length"
        );
        assert_eq!(j.ncols(), n, "jacobian cols must match x length");

        // J^T J (n×n)
        let jt = j.transpose();
        let jtj = &jt * &j;
        // g = J^T r
        let g = matt_vec(&j, &r);
        let g_norm = g.norm();

        if g_norm < settings.grad_tol {
            return Ok(LeastSquaresResultDyn {
                x,
                cost,
                grad_norm: g_norm,
                iterations: iter,
                r_evals,
                j_evals,
            });
        }

        let neg_g = vec_neg(&g);
        let delta = solve_damped_dyn(&jtj, mu, &neg_g)?;

        let x_new = vec_add(&x, &delta);
        let r_new = residual(&x_new);
        r_evals += 1;
        let cost_new = r_new.dot(&r_new) * half;

        // Predicted reduction: delta^T (mu * delta - g)
        let mu_delta_minus_g = vec_sub(&vec_scale(&delta, mu), &g);
        let predicted = delta.dot(&mu_delta_minus_g);
        let eps = T::epsilon();

        if predicted > T::zero() && predicted.abs() >= eps * cost.abs() {
            let actual = cost - cost_new;
            let gain_ratio = actual / predicted;

            if gain_ratio > T::zero() {
                x = x_new;
                r = r_new;
                cost = cost_new;
                mu = (mu * settings.mu_decrease).max(settings.mu_min);

                if delta.norm() < settings.x_tol * (T::one() + x.norm()) {
                    return Ok(LeastSquaresResultDyn {
                        x,
                        cost,
                        grad_norm: g_norm,
                        iterations: iter + 1,
                        r_evals,
                        j_evals,
                    });
                }

                if actual.abs() < settings.f_tol * (T::one() + cost.abs()) {
                    return Ok(LeastSquaresResultDyn {
                        x,
                        cost,
                        grad_norm: g_norm,
                        iterations: iter + 1,
                        r_evals,
                        j_evals,
                    });
                }
            } else {
                mu = (mu * settings.mu_increase).min(settings.mu_max);
            }
        } else {
            mu = (mu * settings.mu_increase).min(settings.mu_max);
        }
    }

    Err(OptimError::MaxIterations)
}

/// Solve `(A + mu * I) * x = b` via Cholesky, falling back to LU.
fn solve_damped_dyn<T: FloatScalar>(
    a: &DynMatrix<T>,
    mu: T,
    b: &DynVector<T>,
) -> Result<DynVector<T>, OptimError> {
    let n = a.nrows();
    let mut damped = a.clone();
    for i in 0..n {
        damped[(i, i)] = damped[(i, i)] + mu;
    }

    if let Ok(chol) = damped.cholesky() {
        return Ok(chol.solve(b));
    }

    let lu = damped.lu().map_err(|_| OptimError::Singular)?;
    Ok(lu.solve(b))
}