Skip to main content

lib_jsl_optimization/
bounded.rs

1//! Optimisation with simple bounds `l ≤ x ≤ u`, following `scipy.optimize`:
2//!
3//! * [`minimize_lbfgsb`]: the limited-memory quasi-Newton method L-BFGS-B of Byrd, Lu, Nocedal
4//!   and Zhu (1995): a generalised Cauchy point along the projected gradient path fixes the active
5//!   bounds, a subspace minimisation of the limited-memory model moves the free variables, and a
6//!   line search capped at the bounds finishes the step.
7//! * [`least_squares_bounded`]: nonlinear least squares with bounds and robust loss functions by
8//!   the trust-region reflective method of Branch, Coleman and Li (a port of SciPy's
9//!   `least_squares(method='trf')` with the exact trust-region solver).
10//! * [`lsq_linear`]: linear least squares with bounds by the bounded-variable least-squares
11//!   algorithm of Stark and Parker (SciPy's `lsq_linear(method='bvls')`).
12//! * [`nnls`]: non-negative least squares by the active-set method of Lawson and Hanson.
13//!
14//! See the book entry [Bound-constrained optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/bounded.html).
15
16// Guards such as `!(x > 0.0)` are deliberate: unlike `x <= 0.0` they also reject NaN.
17#![allow(clippy::neg_cmp_op_on_partial_ord)]
18// The linear-algebra loops read most clearly with explicit indices.
19#![allow(clippy::needless_range_loop)]
20
21use lib_jsl_core::ErrorsJSL;
22use lib_jsl_linalg::sparse::{LinearOperator, LsmrOptions, lsmr};
23use lib_jsl_linalg::{EigVals, Inverse, LeastSquaresSvd, SVD};
24use ndarray::{Array1, Array2, Axis, s};
25
26fn dot(a: &[f64], b: &[f64]) -> f64 {
27    a.iter().zip(b).map(|(p, q)| p * q).sum()
28}
29
30fn norm(a: &[f64]) -> f64 {
31    dot(a, a).sqrt()
32}
33
34fn check_bounds(x0: &[f64], lb: &[f64], ub: &[f64]) -> Result<(), ErrorsJSL> {
35    if lb.len() != x0.len() || ub.len() != x0.len() {
36        return Err(ErrorsJSL::IncompatibleArraySizes((lb.len(), x0.len())));
37    }
38    if lb.iter().zip(ub).any(|(l, u)| !(l < u)) {
39        return Err(ErrorsJSL::InvalidInputRange("each lower bound must be less than its upper bound"));
40    }
41    Ok(())
42}
43
44// ------------------------------------------------------------------------------------ L-BFGS-B
45
46/// Options for [`minimize_lbfgsb`], with SciPy's defaults.
47#[derive(Clone, Copy, Debug)]
48pub struct LbfgsbOptions {
49    /// The number of correction pairs kept (`maxcor`).
50    pub memory: usize,
51    /// Stop when `(f_k − f_{k+1}) / max(|f_k|, |f_{k+1}|, 1) ≤ ftol`.
52    pub ftol: f64,
53    /// Stop when the largest component of the projected gradient is at most `gtol`.
54    pub gtol: f64,
55    pub max_iterations: usize,
56}
57
58impl Default for LbfgsbOptions {
59    fn default() -> Self {
60        LbfgsbOptions { memory: 10, ftol: 2.220_446_049_250_313e-9, gtol: 1e-5, max_iterations: 15000 }
61    }
62}
63
64/// The result of a bound-constrained minimisation.
65#[derive(Clone, Debug)]
66#[non_exhaustive]
67pub struct BoundedResult {
68    pub x: Vec<f64>,
69    pub fun: f64,
70    pub gradient: Vec<f64>,
71    pub iterations: usize,
72    pub nfev: usize,
73    /// `true` when a convergence test was met.
74    pub converged: bool,
75    /// −1, 0, +1 per variable: at its lower bound, free, at its upper bound.
76    pub active: Vec<i8>,
77}
78
79fn project(x: &mut [f64], lb: &[f64], ub: &[f64]) {
80    for i in 0..x.len() {
81        x[i] = x[i].clamp(lb[i], ub[i]);
82    }
83}
84
85/// `‖P(x − g) − x‖∞`, the size of the projected gradient.
86fn projected_gradient_norm(x: &[f64], g: &[f64], lb: &[f64], ub: &[f64]) -> f64 {
87    (0..x.len()).map(|i| ((x[i] - g[i]).clamp(lb[i], ub[i]) - x[i]).abs()).fold(0.0, f64::max)
88}
89
90/// The limited-memory matrix `B = θI − W M Wᵀ` in compact form.
91struct Compact {
92    /// W = [Y, θS], n × 2k, stored by rows.
93    w: Vec<Vec<f64>>,
94    /// M, 2k × 2k.
95    m: Array2<f64>,
96    theta: f64,
97}
98
99impl Compact {
100    fn new(s: &[Vec<f64>], y: &[Vec<f64>], theta: f64, n: usize) -> Result<Self, ErrorsJSL> {
101        let k = s.len();
102        let w: Vec<Vec<f64>> = (0..n).map(|i| (0..2 * k).map(|j| if j < k { y[j][i] } else { theta * s[j - k][i] }).collect()).collect();
103        if k == 0 {
104            return Ok(Compact { w, m: Array2::zeros((0, 0)), theta });
105        }
106        // M⁻¹ = [[−D, Lᵀ], [L, θ SᵀS]].
107        let mut minv = Array2::<f64>::zeros((2 * k, 2 * k));
108        for i in 0..k {
109            for j in 0..k {
110                let sy = dot(&s[i], &y[j]);
111                if i == j {
112                    minv[(i, i)] = -sy;
113                }
114                if i > j {
115                    minv[(k + i, j)] = sy;
116                    minv[(j, k + i)] = sy;
117                }
118                minv[(k + i, k + j)] = theta * dot(&s[i], &s[j]);
119            }
120        }
121        let m = minv.inv().map_err(|_| ErrorsJSL::RuntimeError("L-BFGS-B: singular limited-memory matrix"))?;
122        Ok(Compact { w, m, theta })
123    }
124
125    fn two_k(&self) -> usize {
126        self.m.nrows()
127    }
128
129    fn m_times(&self, v: &[f64]) -> Vec<f64> {
130        (0..self.two_k()).map(|i| (0..self.two_k()).map(|j| self.m[(i, j)] * v[j]).sum()).collect()
131    }
132}
133
134// ANCHOR: cauchy
135/// The generalised Cauchy point: the first local minimiser of the quadratic model along the
136/// projected steepest-descent path `P(x − t g)`, found by visiting the breakpoints where variables
137/// reach their bounds in order (Byrd, Lu, Nocedal and Zhu, algorithm CP). Returns the point and
138/// `c = Wᵀ(x_cp − x)`.
139fn cauchy_point(x: &[f64], g: &[f64], lb: &[f64], ub: &[f64], b: &Compact) -> (Vec<f64>, Vec<f64>) {
140    let n = x.len();
141    let two_k = b.two_k();
142    let mut t = vec![f64::INFINITY; n];
143    let mut d = vec![0.0; n];
144    for i in 0..n {
145        if g[i] < 0.0 {
146            t[i] = (x[i] - ub[i]) / g[i];
147        } else if g[i] > 0.0 {
148            t[i] = (x[i] - lb[i]) / g[i];
149        }
150        if t[i] > 0.0 {
151            d[i] = -g[i];
152        }
153    }
154    let mut order: Vec<usize> = (0..n).filter(|&i| t[i] > 0.0 && t[i].is_finite()).collect();
155    order.sort_by(|&a, &c| t[a].total_cmp(&t[c]));
156    let mut xcp = x.to_vec();
157    for i in 0..n {
158        if t[i] == 0.0 {
159            xcp[i] = x[i];
160        }
161    }
162    // p = Wᵀ d, c = 0.
163    let mut p: Vec<f64> = (0..two_k).map(|j| (0..n).map(|i| b.w[i][j] * d[i]).sum()).collect();
164    let mut c = vec![0.0; two_k];
165    let mut fp = -dot(&d, &d);
166    let mut fpp = -b.theta * fp - dot(&p, &b.m_times(&p));
167    let mut dt_min = if fpp > 0.0 { -fp / fpp } else { f64::INFINITY };
168    let mut t_old = 0.0;
169    for &bi in &order {
170        let dt = t[bi] - t_old;
171        if dt_min < dt {
172            break;
173        }
174        // Variable bi reaches its bound.
175        xcp[bi] = if d[bi] > 0.0 { ub[bi] } else { lb[bi] };
176        let zb = xcp[bi] - x[bi];
177        for j in 0..two_k {
178            c[j] += dt * p[j];
179        }
180        let gb = g[bi];
181        let wb = &b.w[bi];
182        let mc = b.m_times(&c);
183        let mp = b.m_times(&p);
184        let mw = b.m_times(wb);
185        fp += dt * fpp + gb * gb + b.theta * gb * zb - gb * dot(wb, &mc);
186        fpp += -b.theta * gb * gb - 2.0 * gb * dot(wb, &mp) - gb * gb * dot(wb, &mw);
187        for j in 0..two_k {
188            p[j] += gb * wb[j];
189        }
190        d[bi] = 0.0;
191        dt_min = if fpp > 0.0 { -fp / fpp } else { f64::INFINITY };
192        t_old = t[bi];
193    }
194    let dt_min = if dt_min.is_finite() { dt_min.max(0.0) } else { 0.0 };
195    let t_final = t_old + dt_min;
196    for i in 0..n {
197        if d[i] != 0.0 {
198            xcp[i] = (x[i] + t_final * d[i]).clamp(lb[i], ub[i]);
199        }
200    }
201    for j in 0..two_k {
202        c[j] += dt_min * p[j];
203    }
204    (xcp, c)
205}
206// ANCHOR_END: cauchy
207
208/// Subspace minimisation (the direct primal method): minimises the model over the variables that
209/// are free at the Cauchy point, by the Sherman-Morrison-Woodbury formula for the reduced
210/// matrix, and truncates the step at the bounds.
211fn subspace_min(x: &[f64], g: &[f64], lb: &[f64], ub: &[f64], xcp: &[f64], c: &[f64], b: &Compact) -> Result<Vec<f64>, ErrorsJSL> {
212    let n = x.len();
213    let two_k = b.two_k();
214    let free: Vec<usize> = (0..n).filter(|&i| xcp[i] > lb[i] && xcp[i] < ub[i]).collect();
215    if free.is_empty() || two_k == 0 {
216        // With no curvature pairs the model is θ/2 ‖·‖²: minimise it over the free variables directly.
217        let mut out = xcp.to_vec();
218        if two_k == 0 {
219            for &i in &free {
220                out[i] = (xcp[i] - (g[i] + b.theta * (xcp[i] - x[i])) / b.theta).clamp(lb[i], ub[i]);
221            }
222        }
223        return Ok(out);
224    }
225    let mc = b.m_times(c);
226    // Reduced gradient r = Zᵀ (g + θ (x_cp − x) − W M c).
227    let r: Vec<f64> = free.iter().map(|&i| g[i] + b.theta * (xcp[i] - x[i]) - dot(&b.w[i], &mc)).collect();
228    // v = M W_Fᵀ r;  N = I − (1/θ) M W_Fᵀ W_F;  v ← N⁻¹ v;  d = −r/θ − W_F v / θ².
229    let wtr: Vec<f64> = (0..two_k).map(|j| free.iter().zip(&r).map(|(&i, ri)| b.w[i][j] * ri).sum()).collect();
230    let v = b.m_times(&wtr);
231    let mut wtw = Array2::<f64>::zeros((two_k, two_k));
232    for &i in &free {
233        for a in 0..two_k {
234            for c2 in 0..two_k {
235                wtw[(a, c2)] += b.w[i][a] * b.w[i][c2];
236            }
237        }
238    }
239    let nmat = Array2::<f64>::eye(two_k) - b.m.dot(&wtw) / b.theta;
240    let v = nmat.inv().map_err(|_| ErrorsJSL::RuntimeError("L-BFGS-B: singular subspace matrix"))?.dot(&Array1::from(v));
241    let du: Vec<f64> = free.iter().zip(&r).map(|(&i, ri)| -ri / b.theta - dot(&b.w[i], v.as_slice().expect("contiguous")) / (b.theta * b.theta)).collect();
242    // Truncate the step to stay feasible.
243    let mut alpha: f64 = 1.0;
244    for (k, &i) in free.iter().enumerate() {
245        if du[k] > 0.0 {
246            alpha = alpha.min((ub[i] - xcp[i]) / du[k]);
247        } else if du[k] < 0.0 {
248            alpha = alpha.min((lb[i] - xcp[i]) / du[k]);
249        }
250    }
251    let mut out = xcp.to_vec();
252    for (k, &i) in free.iter().enumerate() {
253        out[i] = xcp[i] + alpha * du[k];
254    }
255    project(&mut out, lb, ub);
256    Ok(out)
257}
258
259/// A line search along `d` for the strong Wolfe conditions (`c₁ = 10⁻³`, `c₂ = 0.9`, as L-BFGS-B),
260/// with the step limited to `max_step` so that the iterate stays feasible.
261/// An accepted line-search point: step, x, f(x), ∇f(x).
262type LinePoint = (f64, Vec<f64>, f64, Vec<f64>);
263/// A function returning a value and its gradient.
264type ValueAndGradient<'a> = dyn FnMut(&[f64]) -> (f64, Vec<f64>) + 'a;
265
266fn line_search(fg: &mut ValueAndGradient, x: &[f64], f0: f64, g0: &[f64], d: &[f64], first: f64, max_step: f64) -> Option<LinePoint> {
267    let (c1, c2) = (1e-3, 0.9);
268    let slope0 = dot(g0, d);
269    if !(slope0 < 0.0) {
270        return None;
271    }
272    let point = |a: f64| -> Vec<f64> { x.iter().zip(d).map(|(xi, di)| xi + a * di).collect() };
273    let (mut lo, mut f_lo, mut slope_lo) = (0.0, f0, slope0);
274    let (mut hi, mut f_hi) = (f64::INFINITY, f64::INFINITY);
275    let mut a = first.min(max_step);
276    for _ in 0..40 {
277        let xa = point(a);
278        let (fa, ga) = fg(&xa);
279        let slope = dot(&ga, d);
280        if !fa.is_finite() || fa > f0 + c1 * a * slope0 || fa >= f_lo {
281            (hi, f_hi) = (a, fa);
282        } else {
283            if slope.abs() <= -c2 * slope0 || (a >= max_step && slope < 0.0) {
284                return Some((a, xa, fa, ga));
285            }
286            if slope * (hi - lo) >= 0.0 && hi.is_finite() {
287                (hi, f_hi) = (lo, f_lo);
288            }
289            (lo, f_lo, slope_lo) = (a, fa, slope);
290        }
291        a = if hi.is_finite() {
292            // Minimiser of the quadratic through (lo, f_lo, slope_lo) and (hi, f_hi), kept away from
293            // the ends of the bracket.
294            let h = hi - lo;
295            let curv = f_hi - f_lo - slope_lo * h;
296            let trial = if curv > 0.0 && f_hi.is_finite() { lo - 0.5 * slope_lo * h * h / curv } else { lo + 0.5 * h };
297            let (l, u) = (lo.min(hi), lo.max(hi));
298            trial.clamp(l + 0.1 * (u - l), u - 0.1 * (u - l))
299        } else if a >= max_step {
300            break;
301        } else {
302            (4.0 * a).min(max_step)
303        };
304        if hi.is_finite() && (hi - lo).abs() < 1e-14 * a.abs().max(1.0) {
305            break;
306        }
307    }
308    if lo > 0.0 {
309        let xa = point(lo);
310        let (fa, ga) = fg(&xa);
311        return Some((lo, xa, fa, ga));
312    }
313    None
314}
315
316// ANCHOR: lbfgsb
317/// Minimises `f` subject to `lb ≤ x ≤ ub` by L-BFGS-B (SciPy's `minimize(method='L-BFGS-B')`).
318/// `fg` returns the value and gradient. Infinite bounds are allowed.
319pub fn minimize_lbfgsb(mut fg: impl FnMut(&[f64]) -> (f64, Vec<f64>), x0: &[f64], lb: &[f64], ub: &[f64], options: LbfgsbOptions) -> Result<BoundedResult, ErrorsJSL> {
320    check_bounds(x0, lb, ub)?;
321    let n = x0.len();
322    let mut nfev = 0;
323    let mut eval = |x: &[f64]| {
324        nfev += 1;
325        fg(x)
326    };
327    let mut x = x0.to_vec();
328    project(&mut x, lb, ub);
329    let (mut f, mut g) = eval(&x);
330    let mut s_hist: Vec<Vec<f64>> = Vec::new();
331    let mut y_hist: Vec<Vec<f64>> = Vec::new();
332    let mut theta = 1.0;
333    let mut iterations = 0;
334    let mut converged = projected_gradient_norm(&x, &g, lb, ub) <= options.gtol;
335    while !converged && iterations < options.max_iterations {
336        let b = Compact::new(&s_hist, &y_hist, theta, n)?;
337        let (xcp, c) = cauchy_point(&x, &g, lb, ub, &b);
338        let xbar = subspace_min(&x, &g, lb, ub, &xcp, &c, &b)?;
339        let mut d: Vec<f64> = xbar.iter().zip(&x).map(|(a, b)| a - b).collect();
340        if dot(&d, &g) >= 0.0 {
341            // Not a descent direction (rounding in the model): restart from steepest descent.
342            s_hist.clear();
343            y_hist.clear();
344            theta = 1.0;
345            let b = Compact::new(&s_hist, &y_hist, theta, n)?;
346            let (xcp, _) = cauchy_point(&x, &g, lb, ub, &b);
347            d = xcp.iter().zip(&x).map(|(a, b)| a - b).collect();
348            if dot(&d, &g) >= 0.0 {
349                converged = true;
350                break;
351            }
352        }
353        // The largest feasible step along d.
354        let mut max_step = f64::INFINITY;
355        for i in 0..n {
356            if d[i] > 0.0 {
357                max_step = max_step.min((ub[i] - x[i]) / d[i]);
358            } else if d[i] < 0.0 {
359                max_step = max_step.min((lb[i] - x[i]) / d[i]);
360            }
361        }
362        let first = if iterations == 0 && s_hist.is_empty() { (1.0 / norm(&d)).min(max_step) } else { 1.0f64.min(max_step) };
363        let Some((_, mut x_new, f_new, g_new)) = line_search(&mut eval, &x, f, &g, &d, first, max_step) else { break };
364        project(&mut x_new, lb, ub);
365        iterations += 1;
366        let s: Vec<f64> = x_new.iter().zip(&x).map(|(a, b)| a - b).collect();
367        let y: Vec<f64> = g_new.iter().zip(&g).map(|(a, b)| a - b).collect();
368        let (f_old, sy, yy) = (f, dot(&s, &y), dot(&y, &y));
369        (x, f, g) = (x_new, f_new, g_new);
370        if sy > f64::EPSILON * yy {
371            if s_hist.len() == options.memory {
372                s_hist.remove(0);
373                y_hist.remove(0);
374            }
375            s_hist.push(s);
376            y_hist.push(y);
377            theta = yy / sy;
378        }
379        if (f_old - f) / f_old.abs().max(f.abs()).max(1.0) <= options.ftol || projected_gradient_norm(&x, &g, lb, ub) <= options.gtol {
380            converged = true;
381        }
382    }
383    let active = (0..n).map(|i| if x[i] <= lb[i] { -1 } else if x[i] >= ub[i] { 1 } else { 0 }).collect();
384    Ok(BoundedResult { x, fun: f, gradient: g, iterations, nfev, converged, active })
385}
386// ANCHOR_END: lbfgsb
387
388// ------------------------------------------------------------------------- least_squares (TRF)
389
390/// Robust loss functions `ρ(z)` of the squared residual `z = (f / f_scale)²` (SciPy's `loss`).
391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
392pub enum Loss {
393    /// `ρ(z) = z`: ordinary least squares.
394    Linear,
395    /// `ρ(z) = 2(√(1 + z) − 1)`.
396    SoftL1,
397    /// `ρ(z) = z` for `z ≤ 1`, `2√z − 1` beyond.
398    Huber,
399    /// `ρ(z) = ln(1 + z)`.
400    Cauchy,
401    /// `ρ(z) = arctan(z)`.
402    Arctan,
403}
404
405impl Loss {
406    /// `(ρ, ρ', ρ'')` at `z`.
407    fn rho(self, z: f64) -> [f64; 3] {
408        match self {
409            Loss::Linear => [z, 1.0, 0.0],
410            Loss::SoftL1 => {
411                let t = 1.0 + z;
412                [2.0 * (t.sqrt() - 1.0), t.powf(-0.5), -0.5 * t.powf(-1.5)]
413            }
414            Loss::Huber => {
415                if z <= 1.0 {
416                    [z, 1.0, 0.0]
417                } else {
418                    [2.0 * z.sqrt() - 1.0, z.powf(-0.5), -0.5 * z.powf(-1.5)]
419                }
420            }
421            Loss::Cauchy => {
422                let t = 1.0 + z;
423                [z.ln_1p(), 1.0 / t, -1.0 / (t * t)]
424            }
425            Loss::Arctan => {
426                let t = 1.0 + z * z;
427                [z.atan(), 1.0 / t, -2.0 * z / (t * t)]
428            }
429        }
430    }
431}
432
433/// Options for [`least_squares_bounded`], with SciPy's defaults.
434#[derive(Clone, Copy, Debug)]
435pub struct LeastSquaresOptions {
436    pub ftol: f64,
437    pub xtol: f64,
438    pub gtol: f64,
439    /// The largest number of residual evaluations; `100 n` when `None`.
440    pub max_nfev: Option<usize>,
441    pub loss: Loss,
442    /// The residual size at which the robust loss starts to differ from ordinary least squares.
443    pub f_scale: f64,
444}
445
446impl Default for LeastSquaresOptions {
447    fn default() -> Self {
448        LeastSquaresOptions { ftol: 1e-8, xtol: 1e-8, gtol: 1e-8, max_nfev: None, loss: Loss::Linear, f_scale: 1.0 }
449    }
450}
451
452/// The result of [`least_squares_bounded`].
453#[derive(Clone, Debug)]
454#[non_exhaustive]
455pub struct BoundedLeastSquaresResult {
456    pub x: Vec<f64>,
457    /// `½ Σ ρ(fᵢ²)` (with the loss and scale applied).
458    pub cost: f64,
459    /// The residuals at the solution.
460    pub fun: Vec<f64>,
461    /// The gradient of the cost.
462    pub grad: Vec<f64>,
463    /// The first-order optimality `‖v ∘ g‖∞` with the Coleman-Li scaling `v`.
464    pub optimality: f64,
465    pub active: Vec<i8>,
466    pub nfev: usize,
467    pub njev: usize,
468    /// SciPy's status: 1 gtol, 2 ftol, 3 xtol, 4 ftol and xtol, 0 the evaluation limit.
469    pub status: i32,
470}
471
472/// The Coleman-Li scaling vector `v` and its derivative `dv` (SciPy's `CL_scaling_vector`).
473fn cl_scaling(x: &[f64], g: &[f64], lb: &[f64], ub: &[f64]) -> (Vec<f64>, Vec<f64>) {
474    let n = x.len();
475    let (mut v, mut dv) = (vec![1.0; n], vec![0.0; n]);
476    for i in 0..n {
477        if g[i] < 0.0 && ub[i].is_finite() {
478            v[i] = ub[i] - x[i];
479            dv[i] = -1.0;
480        } else if g[i] > 0.0 && lb[i].is_finite() {
481            v[i] = x[i] - lb[i];
482            dv[i] = 1.0;
483        }
484    }
485    (v, dv)
486}
487
488/// The step length to the nearest bound along `s`, and for each variable whether (and in which
489/// direction) it is the one that hits (SciPy's `step_size_to_bound`).
490fn step_size_to_bound(x: &[f64], s: &[f64], lb: &[f64], ub: &[f64]) -> (f64, Vec<i8>) {
491    let steps: Vec<f64> = (0..x.len()).map(|i| if s[i] != 0.0 { ((lb[i] - x[i]) / s[i]).max((ub[i] - x[i]) / s[i]) } else { f64::INFINITY }).collect();
492    let min = steps.iter().copied().fold(f64::INFINITY, f64::min);
493    let hits = (0..x.len()).map(|i| if steps[i] == min { s[i].signum() as i8 } else { 0 }).collect();
494    (min, hits)
495}
496
497fn in_bounds(x: &[f64], lb: &[f64], ub: &[f64]) -> bool {
498    (0..x.len()).all(|i| x[i] >= lb[i] && x[i] <= ub[i])
499}
500
501/// Moves points on or outside the bounds strictly inside (SciPy's `make_strictly_feasible`).
502fn make_strictly_feasible(x: &[f64], lb: &[f64], ub: &[f64], rstep: f64) -> Vec<f64> {
503    let mut out = x.to_vec();
504    for i in 0..x.len() {
505        let lower = x[i] <= lb[i] + if rstep == 0.0 { 0.0 } else { rstep * lb[i].abs().max(1.0) };
506        let upper = x[i] >= ub[i] - if rstep == 0.0 { 0.0 } else { rstep * ub[i].abs().max(1.0) };
507        if lower && lb[i].is_finite() {
508            out[i] = if rstep == 0.0 { next_toward(lb[i], ub[i]) } else { lb[i] + rstep * lb[i].abs().max(1.0) };
509        } else if upper && ub[i].is_finite() {
510            out[i] = if rstep == 0.0 { next_toward(ub[i], lb[i]) } else { ub[i] - rstep * ub[i].abs().max(1.0) };
511        }
512        if out[i] < lb[i] || out[i] > ub[i] {
513            out[i] = 0.5 * (lb[i] + ub[i]);
514        }
515    }
516    out
517}
518
519fn next_toward(a: f64, b: f64) -> f64 {
520    if b > a { a.next_up() } else { a.next_down() }
521}
522
523/// `½ ‖J s‖² + ½ sᵀ diag s + gᵀ s`.
524fn evaluate_quadratic(j: &dyn LinearOperator, g: &[f64], s: &[f64], diag: &[f64]) -> f64 {
525    let js = j.matvec(s);
526    0.5 * (dot(&js, &js) + s.iter().zip(diag).map(|(a, d)| a * a * d).sum::<f64>()) + dot(s, g)
527}
528
529/// The coefficients of the quadratic `a t² + b t + c` along `s0 + t s` (SciPy's
530/// `build_quadratic_1d`).
531fn build_quadratic_1d(j: &dyn LinearOperator, g: &[f64], s: &[f64], diag: &[f64], s0: Option<&[f64]>) -> (f64, f64, f64) {
532    let v = j.matvec(s);
533    let a = 0.5 * (dot(&v, &v) + s.iter().zip(diag).map(|(a, d)| a * a * d).sum::<f64>());
534    let mut b = dot(g, s);
535    let mut c = 0.0;
536    if let Some(s0) = s0 {
537        let u = j.matvec(s0);
538        b += dot(&u, &v) + s0.iter().zip(diag).zip(s).map(|((a, d), b)| a * d * b).sum::<f64>();
539        c = 0.5 * dot(&u, &u) + dot(g, s0) + 0.5 * s0.iter().zip(diag).map(|(a, d)| a * a * d).sum::<f64>();
540    }
541    (a, b, c)
542}
543
544/// The minimiser of `a t² + b t + c` on `[lo, hi]` and its value.
545fn minimize_quadratic_1d(a: f64, b: f64, lo: f64, hi: f64, c: f64) -> (f64, f64) {
546    let mut ts = vec![lo, hi];
547    if a != 0.0 {
548        let ext = -0.5 * b / a;
549        if lo < ext && ext < hi {
550            ts.push(ext);
551        }
552    }
553    let mut best = (ts[0], ts[0] * (a * ts[0] + b) + c);
554    for &t in &ts[1..] {
555        let y = t * (a * t + b) + c;
556        if y < best.1 {
557            best = (t, y);
558        }
559    }
560    best
561}
562
563/// The parameter values where `x + t s` crosses the sphere of radius `Δ` (SciPy's
564/// `intersect_trust_region`).
565fn intersect_trust_region(x: &[f64], s: &[f64], delta: f64) -> (f64, f64) {
566    let a = dot(s, s);
567    let b = dot(x, s);
568    let c = dot(x, x) - delta * delta;
569    let d = (b * b - a * c).max(0.0).sqrt();
570    let q = -(b + d.copysign(b));
571    let (t1, t2) = (q / a, c / q);
572    if t1 < t2 { (t1, t2) } else { (t2, t1) }
573}
574
575/// The exact trust-region subproblem `min ‖J p + f‖` with `‖p‖ ≤ Δ` from the SVD of `J`, by
576/// Moré's iteration on the Levenberg-Marquardt parameter (SciPy's `solve_lsq_trust_region`).
577fn solve_lsq_trust_region(n: usize, m: usize, uf: &[f64], s: &[f64], v: &Array2<f64>, delta: f64, initial_alpha: f64) -> (Vec<f64>, f64) {
578    let suf: Vec<f64> = s.iter().zip(uf).map(|(a, b)| a * b).collect();
579    let full_rank = m >= n && s[n - 1] > f64::EPSILON * m as f64 * s[0];
580    let phi = |alpha: f64| -> (f64, f64) {
581        let denom: Vec<f64> = s.iter().map(|si| si * si + alpha).collect();
582        let p: Vec<f64> = suf.iter().zip(&denom).map(|(a, d)| a / d).collect();
583        let pn = norm(&p);
584        (pn - delta, -suf.iter().zip(&denom).map(|(a, d)| a * a / (d * d * d)).sum::<f64>() / pn)
585    };
586    let vdot = |w: &[f64]| -> Vec<f64> { (0..n).map(|i| (0..n).map(|k| v[(i, k)] * w[k]).sum()).collect() };
587    if full_rank {
588        let p: Vec<f64> = vdot(&uf.iter().zip(s).map(|(a, b)| -a / b).collect::<Vec<_>>());
589        if norm(&p) <= delta {
590            return (p, 0.0);
591        }
592    }
593    let mut alpha_upper = norm(&suf) / delta;
594    let mut alpha_lower = if full_rank {
595        let (ph, dp) = phi(0.0);
596        -ph / dp
597    } else {
598        0.0
599    };
600    let mut alpha = if !full_rank && initial_alpha == 0.0 { (0.001 * alpha_upper).max((alpha_lower * alpha_upper).sqrt()) } else { initial_alpha };
601    for _ in 0..10 {
602        if alpha < alpha_lower || alpha > alpha_upper {
603            alpha = (0.001 * alpha_upper).max((alpha_lower * alpha_upper).sqrt());
604        }
605        let (ph, dp) = phi(alpha);
606        if ph < 0.0 {
607            alpha_upper = alpha;
608        }
609        let ratio = ph / dp;
610        alpha_lower = alpha_lower.max(alpha - ratio);
611        alpha -= (ph + delta) * ratio / delta;
612        if ph.abs() < 0.01 * delta {
613            break;
614        }
615    }
616    let mut p = vdot(&suf.iter().zip(s).map(|(a, si)| -a / (si * si + alpha)).collect::<Vec<_>>());
617    let pn = norm(&p);
618    p.iter_mut().for_each(|v| *v *= delta / pn);
619    (p, alpha)
620}
621
622/// Chooses among the trust-region step (reflected or truncated at a bound) and the scaled
623/// gradient step, the one with the lowest model value (SciPy's `select_step`).
624#[allow(clippy::too_many_arguments)]
625fn select_step(x: &[f64], j_h: &dyn LinearOperator, diag_h: &[f64], g_h: &[f64], p: &[f64], p_h: &[f64], d: &[f64], delta: f64, lb: &[f64], ub: &[f64], theta: f64) -> (Vec<f64>, Vec<f64>, f64) {
626    let n = x.len();
627    let xp: Vec<f64> = x.iter().zip(p).map(|(a, b)| a + b).collect();
628    if in_bounds(&xp, lb, ub) {
629        return (p.to_vec(), p_h.to_vec(), -evaluate_quadratic(j_h, g_h, p_h, diag_h));
630    }
631    let (p_stride, hits) = step_size_to_bound(x, p, lb, ub);
632    // The reflected direction.
633    let mut r_h = p_h.to_vec();
634    for i in 0..n {
635        if hits[i] != 0 {
636            r_h[i] = -r_h[i];
637        }
638    }
639    let mut r: Vec<f64> = r_h.iter().zip(d).map(|(a, b)| a * b).collect();
640    let mut p = p.iter().map(|v| v * p_stride).collect::<Vec<_>>();
641    let mut p_h = p_h.iter().map(|v| v * p_stride).collect::<Vec<_>>();
642    let x_on_bound: Vec<f64> = x.iter().zip(&p).map(|(a, b)| a + b).collect();
643    let (_, to_tr) = intersect_trust_region(&p_h, &r_h, delta);
644    let (to_bound, _) = step_size_to_bound(&x_on_bound, &r, lb, ub);
645    let r_stride = to_bound.min(to_tr);
646    let (r_stride_l, r_stride_u) = if r_stride > 0.0 { ((1.0 - theta) * p_stride / r_stride, if r_stride == to_bound { theta * to_bound } else { to_tr }) } else { (0.0, -1.0) };
647    let r_value;
648    if r_stride_l <= r_stride_u {
649        let (a, b, c) = build_quadratic_1d(j_h, g_h, &r_h, diag_h, Some(&p_h));
650        let (rs, rv) = minimize_quadratic_1d(a, b, r_stride_l, r_stride_u, c);
651        r_value = rv;
652        r_h = r_h.iter().zip(&p_h).map(|(a, b)| a * rs + b).collect();
653        r = r_h.iter().zip(d).map(|(a, b)| a * b).collect();
654    } else {
655        r_value = f64::INFINITY;
656    }
657    p.iter_mut().for_each(|v| *v *= theta);
658    p_h.iter_mut().for_each(|v| *v *= theta);
659    let p_value = evaluate_quadratic(j_h, g_h, &p_h, diag_h);
660    let mut ag_h: Vec<f64> = g_h.iter().map(|v| -v).collect();
661    let mut ag: Vec<f64> = ag_h.iter().zip(d).map(|(a, b)| a * b).collect();
662    let to_tr = delta / norm(&ag_h);
663    let (to_bound, _) = step_size_to_bound(x, &ag, lb, ub);
664    let ag_stride = if to_bound < to_tr { theta * to_bound } else { to_tr };
665    let (a, b, _) = build_quadratic_1d(j_h, g_h, &ag_h, diag_h, None);
666    let (ag_stride, ag_value) = minimize_quadratic_1d(a, b, 0.0, ag_stride, 0.0);
667    ag_h.iter_mut().for_each(|v| *v *= ag_stride);
668    ag.iter_mut().for_each(|v| *v *= ag_stride);
669    if p_value < r_value && p_value < ag_value {
670        (p, p_h, -p_value)
671    } else if r_value < p_value && r_value < ag_value {
672        (r, r_h, -r_value)
673    } else {
674        (ag, ag_h, -ag_value)
675    }
676}
677
678// ANCHOR: trf
679/// Minimises `½ Σ ρ(fᵢ(x)²)` subject to `lb ≤ x ≤ ub` by the trust-region reflective method
680/// (SciPy's `least_squares(method='trf', tr_solver='exact', x_scale=1)`). `fun` returns the
681/// residuals and `jac` their Jacobian (rows = residuals).
682///
683/// Each iteration scales the variables by the Coleman-Li vector `v` (the distance to the bound
684/// that the gradient points at), so that the trust region shrinks near the bounds; solves the
685/// scaled trust-region problem exactly through an SVD; and then takes the best of that step
686/// truncated at the bound, its reflection off the bound, and a scaled gradient step.
687pub fn least_squares_bounded(
688    fun: impl Fn(&[f64]) -> Vec<f64>,
689    jac: impl Fn(&[f64]) -> Array2<f64>,
690    x0: &[f64],
691    lb: &[f64],
692    ub: &[f64],
693    options: LeastSquaresOptions,
694) -> Result<BoundedLeastSquaresResult, ErrorsJSL> {
695    check_bounds(x0, lb, ub)?;
696    if !in_bounds(x0, lb, ub) {
697        return Err(ErrorsJSL::InvalidInputRange("the initial guess is outside the bounds"));
698    }
699    let n = x0.len();
700    let mut x = make_strictly_feasible(x0, lb, ub, 1e-10);
701    let mut f = fun(&x);
702    let m = f.len();
703    let mut j = jac(&x);
704    if j.dim() != (m, n) {
705        return Err(ErrorsJSL::IncompatibleArraySizes((j.nrows(), m)));
706    }
707    let (mut nfev, mut njev) = (1, 1);
708    let max_nfev = options.max_nfev.unwrap_or(100 * n);
709    let fs = options.f_scale;
710    // Robust loss: cost and the rescaled residuals and Jacobian.
711    let loss_cost = |f: &[f64]| 0.5 * fs * fs * f.iter().map(|v| options.loss.rho((v / fs).powi(2))[0]).sum::<f64>();
712    let scale_for_loss = |j: &mut Array2<f64>, f: &mut Vec<f64>| {
713        if options.loss == Loss::Linear {
714            return;
715        }
716        for i in 0..f.len() {
717            let r = options.loss.rho((f[i] / fs).powi(2));
718            let (r1, r2) = (r[1], r[2] / (fs * fs));
719            let js = (r1 + 2.0 * r2 * f[i] * f[i]).max(f64::EPSILON).sqrt();
720            f[i] *= r1 / js;
721            j.row_mut(i).mapv_inplace(|v| v * js);
722        }
723    };
724    let mut f_true = f.clone();
725    let mut cost = loss_cost(&f);
726    scale_for_loss(&mut j, &mut f);
727    let grad = |j: &Array2<f64>, f: &[f64]| -> Vec<f64> { j.t().dot(&Array1::from(f.to_vec())).to_vec() };
728    let mut g = grad(&j, &f);
729    let (v0, _) = cl_scaling(&x, &g, lb, ub);
730    let mut delta = norm(&x.iter().zip(&v0).map(|(a, b)| a / b.sqrt()).collect::<Vec<_>>());
731    if delta == 0.0 {
732        delta = 1.0;
733    }
734    let mut alpha = 0.0;
735    let mut status = None;
736    loop {
737        let (v, dv) = cl_scaling(&x, &g, lb, ub);
738        let g_norm = g.iter().zip(&v).map(|(a, b)| (a * b).abs()).fold(0.0, f64::max);
739        if g_norm < options.gtol {
740            status = Some(1);
741        }
742        if status.is_some() || nfev == max_nfev {
743            break;
744        }
745        let d: Vec<f64> = v.iter().map(|vi| vi.sqrt()).collect();
746        let diag_h: Vec<f64> = g.iter().zip(&dv).map(|(a, b)| a * b).collect();
747        let g_h: Vec<f64> = d.iter().zip(&g).map(|(a, b)| a * b).collect();
748        let mut j_h = j.clone();
749        for c in 0..n {
750            j_h.column_mut(c).mapv_inplace(|x| x * d[c]);
751        }
752        // Augmented system [J_h; diag(√diag_h)] and its SVD.
753        let mut j_aug = Array2::<f64>::zeros((m + n, n));
754        j_aug.slice_mut(s![..m, ..]).assign(&j_h);
755        for i in 0..n {
756            j_aug[(m + i, i)] = diag_h[i].max(0.0).sqrt();
757        }
758        let mut f_aug = vec![0.0; m + n];
759        f_aug[..m].copy_from_slice(&f);
760        let (u, sv, vt) = j_aug.svd(true, true).map_err(|_| ErrorsJSL::RuntimeError("least_squares: SVD failed"))?;
761        let (u, vt) = (u.expect("requested"), vt.expect("requested"));
762        let k = sv.len();
763        let uf: Vec<f64> = (0..k).map(|c| (0..m + n).map(|r| u[(r, c)] * f_aug[r]).sum()).collect();
764        let vmat = vt.t().slice(s![.., ..k]).to_owned();
765        let theta = 0.995f64.max(1.0 - g_norm);
766        let mut actual_reduction = -1.0;
767        let (mut x_new, mut f_new, mut cost_new) = (x.clone(), f.clone(), cost);
768        while actual_reduction <= 0.0 && nfev < max_nfev {
769            let (p_h, a) = solve_lsq_trust_region(n, m, &uf, sv.as_slice().expect("contiguous"), &vmat, delta, alpha);
770            alpha = a;
771            let p: Vec<f64> = d.iter().zip(&p_h).map(|(a, b)| a * b).collect();
772            let (step, step_h, predicted) = select_step(&x, &j_h, &diag_h, &g_h, &p, &p_h, &d, delta, lb, ub, theta);
773            x_new = make_strictly_feasible(&x.iter().zip(&step).map(|(a, b)| a + b).collect::<Vec<_>>(), lb, ub, 0.0);
774            f_new = fun(&x_new);
775            nfev += 1;
776            let step_h_norm = norm(&step_h);
777            if f_new.iter().any(|v| !v.is_finite()) {
778                delta = 0.25 * step_h_norm;
779                continue;
780            }
781            cost_new = loss_cost(&f_new);
782            actual_reduction = cost - cost_new;
783            let ratio = if predicted > 0.0 {
784                actual_reduction / predicted
785            } else if predicted == 0.0 && actual_reduction == 0.0 {
786                1.0
787            } else {
788                0.0
789            };
790            let delta_new = if ratio < 0.25 {
791                0.25 * step_h_norm
792            } else if ratio > 0.75 && step_h_norm > 0.95 * delta {
793                2.0 * delta
794            } else {
795                delta
796            };
797            let step_norm = norm(&step);
798            let ftol_ok = actual_reduction < options.ftol * cost && ratio > 0.25;
799            let xtol_ok = step_norm < options.xtol * (options.xtol + norm(&x));
800            status = match (ftol_ok, xtol_ok) {
801                (true, true) => Some(4),
802                (true, false) => Some(2),
803                (false, true) => Some(3),
804                _ => None,
805            };
806            if status.is_some() {
807                break;
808            }
809            alpha *= delta / delta_new;
810            delta = delta_new;
811        }
812        if actual_reduction > 0.0 {
813            x = x_new;
814            f = f_new;
815            f_true = f.clone();
816            cost = cost_new;
817            j = jac(&x);
818            njev += 1;
819            scale_for_loss(&mut j, &mut f);
820            g = grad(&j, &f);
821        }
822    }
823    let (v, _) = cl_scaling(&x, &g, lb, ub);
824    let optimality = g.iter().zip(&v).map(|(a, b)| (a * b).abs()).fold(0.0, f64::max);
825    let active = (0..n)
826        .map(|i| {
827            let tol = 1e-10 * lb[i].abs().max(ub[i].abs()).max(1.0);
828            if x[i] - lb[i] <= tol { -1 } else if ub[i] - x[i] <= tol { 1 } else { 0 }
829        })
830        .collect();
831    Ok(BoundedLeastSquaresResult { x, cost, fun: f_true, grad: g, optimality, active, nfev, njev, status: status.unwrap_or(0) })
832}
833// ANCHOR_END: trf
834
835/// `diag(rows) · A · diag(cols)` without forming it.
836struct Scaled<'a> {
837    inner: &'a dyn LinearOperator,
838    rows: &'a [f64],
839    cols: &'a [f64],
840}
841
842impl LinearOperator for Scaled<'_> {
843    fn shape(&self) -> (usize, usize) {
844        self.inner.shape()
845    }
846    fn matvec(&self, x: &[f64]) -> Vec<f64> {
847        let xs: Vec<f64> = x.iter().zip(self.cols).map(|(a, b)| a * b).collect();
848        self.inner.matvec(&xs).iter().zip(self.rows).map(|(a, b)| a * b).collect()
849    }
850    fn rmatvec(&self, y: &[f64]) -> Vec<f64> {
851        let ys: Vec<f64> = y.iter().zip(self.rows).map(|(a, b)| a * b).collect();
852        self.inner.rmatvec(&ys).iter().zip(self.cols).map(|(a, b)| a * b).collect()
853    }
854}
855
856/// `[A; diag(d)]` (SciPy's `regularized_lsq_operator`).
857struct Regularized<'a> {
858    inner: &'a dyn LinearOperator,
859    diag: &'a [f64],
860}
861
862impl LinearOperator for Regularized<'_> {
863    fn shape(&self) -> (usize, usize) {
864        let (m, n) = self.inner.shape();
865        (m + n, n)
866    }
867    fn matvec(&self, x: &[f64]) -> Vec<f64> {
868        let mut y = self.inner.matvec(x);
869        y.extend(x.iter().zip(self.diag).map(|(a, b)| a * b));
870        y
871    }
872    fn rmatvec(&self, y: &[f64]) -> Vec<f64> {
873        let m = self.inner.shape().0;
874        let mut x = self.inner.rmatvec(&y[..m]);
875        x.iter_mut().zip(&y[m..]).zip(self.diag).for_each(|((a, b), d)| *a += b * d);
876        x
877    }
878}
879
880/// The trust-region problem `min ½ pᵀBp + gᵀp`, `‖p‖ ≤ Δ`, in two dimensions (SciPy's
881/// `solve_trust_region_2d`): the Newton step if it is inside, otherwise the best boundary point,
882/// from the real roots of a quartic in `t = tan(φ/2)`.
883fn solve_trust_region_2d(b: [[f64; 2]; 2], g: [f64; 2], delta: f64) -> [f64; 2] {
884    let det = b[0][0] * b[1][1] - b[0][1] * b[1][0];
885    if b[0][0] > 0.0 && det > 0.0 {
886        let p = [-(b[1][1] * g[0] - b[0][1] * g[1]) / det, -(b[0][0] * g[1] - b[1][0] * g[0]) / det];
887        if p[0] * p[0] + p[1] * p[1] <= delta * delta {
888            return p;
889        }
890    }
891    let (a, bb, c) = (b[0][0] * delta * delta, b[0][1] * delta * delta, b[1][1] * delta * delta);
892    let (d, f) = (g[0] * delta, g[1] * delta);
893    let coeffs = [-bb + d, 2.0 * (a - c + f), 6.0 * bb, 2.0 * (-a + c + f), -bb - d];
894    // Real roots of the quartic from its companion matrix (lower degree if leading terms vanish).
895    let lead = coeffs.iter().position(|v| *v != 0.0).unwrap_or(4);
896    let poly = &coeffs[lead..];
897    let deg = poly.len() - 1;
898    let mut ts = Vec::new();
899    if deg >= 1 {
900        let mut comp = Array2::<f64>::zeros((deg, deg));
901        for j in 0..deg {
902            comp[(0, j)] = -poly[j + 1] / poly[0];
903        }
904        for i in 1..deg {
905            comp[(i, i - 1)] = 1.0;
906        }
907        if let Ok(ev) = comp.eigvals() {
908            ts.extend(ev.iter().filter(|z| z.im.abs() <= 1e-12 * z.re.abs().max(1.0)).map(|z| z.re));
909        }
910    }
911    let value = |p: [f64; 2]| 0.5 * (p[0] * (b[0][0] * p[0] + b[0][1] * p[1]) + p[1] * (b[1][0] * p[0] + b[1][1] * p[1])) + g[0] * p[0] + g[1] * p[1];
912    // t = ±∞ is φ = π, the point (0, −Δ), which the substitution cannot reach.
913    let mut best = [0.0, -delta];
914    let mut best_v = if lead > 0 { value(best) } else { f64::INFINITY };
915    for t in ts {
916        let p = [delta * 2.0 * t / (1.0 + t * t), delta * (1.0 - t * t) / (1.0 + t * t)];
917        let v = value(p);
918        if v < best_v {
919            (best, best_v) = (p, v);
920        }
921    }
922    best
923}
924
925// ANCHOR: trf_lsmr
926/// The trust-region reflective method with an iterative trust-region solver, for large or
927/// sparse problems (SciPy's `least_squares(method='trf', tr_solver='lsmr')`). The Jacobian is
928/// any [`LinearOperator`] (a sparse [`CsrMatrix`](lib_jsl_linalg::sparse::CsrMatrix), a dense
929/// matrix, or products supplied by closures), used only through products with vectors.
930///
931/// Each iteration solves the regularised Gauss-Newton problem `min ‖[J_h; D] p + [f; 0]‖`
932/// approximately with [`lsmr`], and then solves the trust-region problem exactly in the
933/// two-dimensional subspace spanned by that step and the scaled gradient. As in SciPy, `D` adds
934/// to the Coleman-Li term a regularisation `−(m(Δ ĝ)) / Δ²` from the best gradient step, which
935/// keeps LSMR's step inside the trust region's scale. The bounds, step selection and stopping
936/// rules are those of [`least_squares_bounded`].
937pub fn least_squares_lsmr<J: LinearOperator>(
938    fun: impl Fn(&[f64]) -> Vec<f64>,
939    jac: impl Fn(&[f64]) -> J,
940    x0: &[f64],
941    lb: &[f64],
942    ub: &[f64],
943    options: LeastSquaresOptions,
944) -> Result<BoundedLeastSquaresResult, ErrorsJSL> {
945    check_bounds(x0, lb, ub)?;
946    if !in_bounds(x0, lb, ub) {
947        return Err(ErrorsJSL::InvalidInputRange("the initial guess is outside the bounds"));
948    }
949    let n = x0.len();
950    let mut x = make_strictly_feasible(x0, lb, ub, 1e-10);
951    let mut f = fun(&x);
952    let m = f.len();
953    let mut j = jac(&x);
954    if j.shape() != (m, n) {
955        return Err(ErrorsJSL::IncompatibleArraySizes((j.shape().0, m)));
956    }
957    let (mut nfev, mut njev) = (1, 1);
958    let max_nfev = options.max_nfev.unwrap_or(100 * n);
959    let fs = options.f_scale;
960    let loss_cost = |f: &[f64]| 0.5 * fs * fs * f.iter().map(|v| options.loss.rho((v / fs).powi(2))[0]).sum::<f64>();
961    // The robust loss scales the residuals and the rows of the Jacobian.
962    let row_scale = |f: &mut Vec<f64>| -> Vec<f64> {
963        if options.loss == Loss::Linear {
964            return vec![1.0; f.len()];
965        }
966        (0..f.len())
967            .map(|i| {
968                let r = options.loss.rho((f[i] / fs).powi(2));
969                let (r1, r2) = (r[1], r[2] / (fs * fs));
970                let js = (r1 + 2.0 * r2 * f[i] * f[i]).max(f64::EPSILON).sqrt();
971                f[i] *= r1 / js;
972                js
973            })
974            .collect()
975    };
976    let ones = vec![1.0; n];
977    let mut f_true = f.clone();
978    let mut cost = loss_cost(&f);
979    let mut rows = row_scale(&mut f);
980    let grad = |j: &J, rows: &[f64], f: &[f64]| -> Vec<f64> { Scaled { inner: j, rows, cols: &ones }.rmatvec(f) };
981    let mut g = grad(&j, &rows, &f);
982    let (v0, _) = cl_scaling(&x, &g, lb, ub);
983    let mut delta = norm(&x.iter().zip(&v0).map(|(a, b)| a / b.sqrt()).collect::<Vec<_>>());
984    if delta == 0.0 {
985        delta = 1.0;
986    }
987    let mut status = None;
988    loop {
989        let (v, dv) = cl_scaling(&x, &g, lb, ub);
990        let g_norm = g.iter().zip(&v).map(|(a, b)| (a * b).abs()).fold(0.0, f64::max);
991        if g_norm < options.gtol {
992            status = Some(1);
993        }
994        if status.is_some() || nfev == max_nfev {
995            break;
996        }
997        let d: Vec<f64> = v.iter().map(|vi| vi.sqrt()).collect();
998        let diag_h: Vec<f64> = g.iter().zip(&dv).map(|(a, b)| a * b).collect();
999        let g_h: Vec<f64> = d.iter().zip(&g).map(|(a, b)| a * b).collect();
1000        let j_h = Scaled { inner: &j, rows: &rows, cols: &d };
1001        // Regularisation from the best step along −ĝ inside the trust region.
1002        let neg_g: Vec<f64> = g_h.iter().map(|v| -v).collect();
1003        let (qa, qb, _) = build_quadratic_1d(&j_h, &g_h, &neg_g, &diag_h, None);
1004        let (_, ag_value) = minimize_quadratic_1d(qa, qb, 0.0, delta / norm(&g_h), 0.0);
1005        let reg_term = -ag_value / (delta * delta);
1006        let reg_diag: Vec<f64> = diag_h.iter().map(|v| (v + reg_term).max(0.0).sqrt()).collect();
1007        let mut f_aug = f.clone();
1008        f_aug.extend(std::iter::repeat_n(0.0, n));
1009        let gn_h = lsmr(&Regularized { inner: &j_h, diag: &reg_diag }, &f_aug, LsmrOptions::default()).map_err(|_| ErrorsJSL::RuntimeError("least_squares: LSMR failed"))?.x;
1010        // Orthonormal basis of span{ĝ, gn} (Gram-Schmidt; one vector if they are parallel).
1011        let mut basis: Vec<Vec<f64>> = Vec::new();
1012        for w in [&g_h, &gn_h] {
1013            let mut u = w.clone();
1014            for q in &basis {
1015                let c = dot(q, &u);
1016                u.iter_mut().zip(q).for_each(|(a, b)| *a -= c * b);
1017            }
1018            let un = norm(&u);
1019            if un > 1e-12 * norm(w).max(f64::MIN_POSITIVE) {
1020                basis.push(u.iter().map(|a| a / un).collect());
1021            }
1022        }
1023        if basis.is_empty() {
1024            status = Some(1);
1025            break;
1026        }
1027        let js: Vec<Vec<f64>> = basis.iter().map(|q| j_h.matvec(q)).collect();
1028        let k = basis.len();
1029        let mut b_s = [[0.0; 2]; 2];
1030        let mut g_s = [0.0; 2];
1031        for a in 0..k {
1032            g_s[a] = dot(&basis[a], &g_h);
1033            for c in 0..k {
1034                b_s[a][c] = dot(&js[a], &js[c]) + basis[a].iter().zip(&basis[c]).zip(&diag_h).map(|((p, q), w)| p * q * w).sum::<f64>();
1035            }
1036        }
1037        if k == 1 {
1038            // A one-dimensional subspace: pad with an inert second direction.
1039            b_s[1][1] = 1.0;
1040        }
1041        let theta = 0.995f64.max(1.0 - g_norm);
1042        let mut actual_reduction = -1.0;
1043        let (mut x_new, mut f_new, mut cost_new) = (x.clone(), f.clone(), cost);
1044        while actual_reduction <= 0.0 && nfev < max_nfev {
1045            let p_s = solve_trust_region_2d(b_s, g_s, delta);
1046            let mut p_h = vec![0.0; n];
1047            for a in 0..k {
1048                p_h.iter_mut().zip(&basis[a]).for_each(|(p, q)| *p += p_s[a] * q);
1049            }
1050            let p: Vec<f64> = d.iter().zip(&p_h).map(|(a, b)| a * b).collect();
1051            let (step, step_h, predicted) = select_step(&x, &j_h, &diag_h, &g_h, &p, &p_h, &d, delta, lb, ub, theta);
1052            x_new = make_strictly_feasible(&x.iter().zip(&step).map(|(a, b)| a + b).collect::<Vec<_>>(), lb, ub, 0.0);
1053            f_new = fun(&x_new);
1054            nfev += 1;
1055            let step_h_norm = norm(&step_h);
1056            if f_new.iter().any(|v| !v.is_finite()) {
1057                delta = 0.25 * step_h_norm;
1058                continue;
1059            }
1060            cost_new = loss_cost(&f_new);
1061            actual_reduction = cost - cost_new;
1062            let ratio = if predicted > 0.0 {
1063                actual_reduction / predicted
1064            } else if predicted == 0.0 && actual_reduction == 0.0 {
1065                1.0
1066            } else {
1067                0.0
1068            };
1069            let delta_new = if ratio < 0.25 {
1070                0.25 * step_h_norm
1071            } else if ratio > 0.75 && step_h_norm > 0.95 * delta {
1072                2.0 * delta
1073            } else {
1074                delta
1075            };
1076            let step_norm = norm(&step);
1077            let ftol_ok = actual_reduction < options.ftol * cost && ratio > 0.25;
1078            let xtol_ok = step_norm < options.xtol * (options.xtol + norm(&x));
1079            status = match (ftol_ok, xtol_ok) {
1080                (true, true) => Some(4),
1081                (true, false) => Some(2),
1082                (false, true) => Some(3),
1083                _ => None,
1084            };
1085            if status.is_some() {
1086                break;
1087            }
1088            delta = delta_new;
1089        }
1090        if actual_reduction > 0.0 {
1091            x = x_new;
1092            f = f_new;
1093            f_true = f.clone();
1094            cost = cost_new;
1095            j = jac(&x);
1096            njev += 1;
1097            rows = row_scale(&mut f);
1098            g = grad(&j, &rows, &f);
1099        }
1100    }
1101    let (v, _) = cl_scaling(&x, &g, lb, ub);
1102    let optimality = g.iter().zip(&v).map(|(a, b)| (a * b).abs()).fold(0.0, f64::max);
1103    let active = (0..n)
1104        .map(|i| {
1105            let tol = 1e-10 * lb[i].abs().max(ub[i].abs()).max(1.0);
1106            if x[i] - lb[i] <= tol { -1 } else if ub[i] - x[i] <= tol { 1 } else { 0 }
1107        })
1108        .collect();
1109    Ok(BoundedLeastSquaresResult { x, cost, fun: f_true, grad: g, optimality, active, nfev, njev, status: status.unwrap_or(0) })
1110}
1111// ANCHOR_END: trf_lsmr
1112
1113// ANCHOR: dogbox
1114/// Bounded nonlinear least squares by the dogbox method (SciPy's `least_squares(method="dogbox")`),
1115/// Voglis and Lagaris's rectangular trust region. Variables on a bound whose gradient pushes
1116/// further out are fixed; for the others the Gauss-Newton step and the Cauchy point define a
1117/// dogleg, followed inside the intersection of the box-shaped trust region with the bounds.
1118/// It suits small problems with bounds, and is SciPy's port step for step; same options and
1119/// result as [`least_squares_bounded`].
1120pub fn least_squares_dogbox(
1121    fun: impl Fn(&[f64]) -> Vec<f64>,
1122    jac: impl Fn(&[f64]) -> Array2<f64>,
1123    x0: &[f64],
1124    lb: &[f64],
1125    ub: &[f64],
1126    options: LeastSquaresOptions,
1127) -> Result<BoundedLeastSquaresResult, ErrorsJSL> {
1128    check_bounds(x0, lb, ub)?;
1129    if !in_bounds(x0, lb, ub) {
1130        return Err(ErrorsJSL::InvalidInputRange("the initial guess is outside the bounds"));
1131    }
1132    let n = x0.len();
1133    let mut x = x0.to_vec();
1134    let mut f = fun(&x);
1135    let m = f.len();
1136    let mut j = jac(&x);
1137    if j.dim() != (m, n) {
1138        return Err(ErrorsJSL::IncompatibleArraySizes((j.nrows(), m)));
1139    }
1140    let (mut nfev, mut njev) = (1, 1);
1141    let max_nfev = options.max_nfev.unwrap_or(100 * n);
1142    let fs = options.f_scale;
1143    let loss_cost = |f: &[f64]| 0.5 * fs * fs * f.iter().map(|v| options.loss.rho((v / fs).powi(2))[0]).sum::<f64>();
1144    let scale_for_loss = |j: &mut Array2<f64>, f: &mut Vec<f64>| {
1145        if options.loss == Loss::Linear {
1146            return;
1147        }
1148        for i in 0..f.len() {
1149            let r = options.loss.rho((f[i] / fs).powi(2));
1150            let (r1, r2) = (r[1], r[2] / (fs * fs));
1151            let js = (r1 + 2.0 * r2 * f[i] * f[i]).max(f64::EPSILON).sqrt();
1152            f[i] *= r1 / js;
1153            j.row_mut(i).mapv_inplace(|v| v * js);
1154        }
1155    };
1156    let mut f_true = f.clone();
1157    let mut cost = loss_cost(&f);
1158    scale_for_loss(&mut j, &mut f);
1159    let grad = |j: &Array2<f64>, f: &[f64]| -> Vec<f64> { j.t().dot(&Array1::from(f.to_vec())).to_vec() };
1160    let mut g = grad(&j, &f);
1161    let mut delta = x.iter().fold(0.0f64, |a, v| a.max(v.abs()));
1162    if delta == 0.0 {
1163        delta = 1.0;
1164    }
1165    let mut on_bound: Vec<i8> = (0..n).map(|i| if x[i] == lb[i] { -1 } else if x[i] == ub[i] { 1 } else { 0 }).collect();
1166    let mut status = None;
1167    let mut g_full;
1168    let mut g_norm;
1169    loop {
1170        let active: Vec<bool> = (0..n).map(|i| (on_bound[i] as f64) * g[i] < 0.0).collect();
1171        let free: Vec<usize> = (0..n).filter(|&i| !active[i]).collect();
1172        let g_free: Vec<f64> = free.iter().map(|&i| g[i]).collect();
1173        g_full = g.clone();
1174        for i in 0..n {
1175            if active[i] {
1176                g[i] = 0.0;
1177            }
1178        }
1179        g_norm = g.iter().fold(0.0f64, |a, v| a.max(v.abs()));
1180        if g_norm < options.gtol {
1181            status = Some(1);
1182        }
1183        if status.is_some() || nfev == max_nfev {
1184            break;
1185        }
1186        let x_free: Vec<f64> = free.iter().map(|&i| x[i]).collect();
1187        let lb_free: Vec<f64> = free.iter().map(|&i| lb[i]).collect();
1188        let ub_free: Vec<f64> = free.iter().map(|&i| ub[i]).collect();
1189        let j_free = columns(&j, &free);
1190        let neg_f = Array1::from(f.iter().map(|v| -v).collect::<Vec<_>>());
1191        let newton = lstsq(&j_free, &neg_f)?.to_vec();
1192        let zeros = vec![0.0; free.len()];
1193        let neg_g: Vec<f64> = g_free.iter().map(|v| -v).collect();
1194        let (qa, qb, _) = build_quadratic_1d(&j_free, &g_free, &neg_g, &zeros, None);
1195        let mut actual_reduction = -1.0;
1196        let (mut x_new, mut f_new, mut cost_new) = (x.clone(), f.clone(), cost);
1197        let mut on_bound_free = vec![0i8; free.len()];
1198        while actual_reduction <= 0.0 && nfev < max_nfev {
1199            let tr = vec![delta; free.len()];
1200            let (step_free, hits, tr_hit) = dogleg_step(&x_free, &newton, &g_free, qa, qb, &tr, &lb_free, &ub_free);
1201            on_bound_free = hits;
1202            let mut step = vec![0.0; n];
1203            for (k, &i) in free.iter().enumerate() {
1204                step[i] = step_free[k];
1205            }
1206            let predicted = -evaluate_quadratic(&j_free, &g_free, &step_free, &zeros);
1207            x_new = (0..n).map(|i| (x[i] + step[i]).clamp(lb[i], ub[i])).collect();
1208            f_new = fun(&x_new);
1209            nfev += 1;
1210            let step_h_norm = step.iter().fold(0.0f64, |a, v| a.max(v.abs()));
1211            if f_new.iter().any(|v| !v.is_finite()) {
1212                delta = 0.25 * step_h_norm;
1213                continue;
1214            }
1215            cost_new = loss_cost(&f_new);
1216            actual_reduction = cost - cost_new;
1217            let ratio = if predicted > 0.0 {
1218                actual_reduction / predicted
1219            } else if predicted == 0.0 && actual_reduction == 0.0 {
1220                1.0
1221            } else {
1222                0.0
1223            };
1224            if ratio < 0.25 {
1225                delta = 0.25 * step_h_norm;
1226            } else if ratio > 0.75 && tr_hit {
1227                delta *= 2.0;
1228            }
1229            let step_norm = norm(&step);
1230            let ftol_ok = actual_reduction < options.ftol * cost && ratio > 0.25;
1231            let xtol_ok = step_norm < options.xtol * (options.xtol + norm(&x));
1232            status = match (ftol_ok, xtol_ok) {
1233                (true, true) => Some(4),
1234                (true, false) => Some(2),
1235                (false, true) => Some(3),
1236                _ => None,
1237            };
1238            if status.is_some() {
1239                break;
1240            }
1241        }
1242        if actual_reduction > 0.0 {
1243            for (k, &i) in free.iter().enumerate() {
1244                on_bound[i] = on_bound_free[k];
1245            }
1246            x = x_new;
1247            for i in 0..n {
1248                if on_bound[i] == -1 {
1249                    x[i] = lb[i];
1250                } else if on_bound[i] == 1 {
1251                    x[i] = ub[i];
1252                }
1253            }
1254            f = f_new;
1255            f_true = f.clone();
1256            cost = cost_new;
1257            j = jac(&x);
1258            njev += 1;
1259            scale_for_loss(&mut j, &mut f);
1260            g = grad(&j, &f);
1261        }
1262    }
1263    Ok(BoundedLeastSquaresResult { x, cost, fun: f_true, grad: g_full, optimality: g_norm, active: on_bound, nfev, njev, status: status.unwrap_or(0) })
1264}
1265
1266/// The dogleg step in the intersection of the box trust region `|sᵢ| ≤ Δ` with the bounds
1267/// (SciPy's `dogleg_step`): the Newton step if it fits, otherwise the Cauchy point along `−g`
1268/// followed by the segment towards the Newton step, cut at the box. Returns the step, which
1269/// original bounds it hits, and whether it hit the trust region.
1270#[allow(clippy::too_many_arguments)]
1271fn dogleg_step(x: &[f64], newton: &[f64], g: &[f64], a: f64, b: f64, tr: &[f64], lb: &[f64], ub: &[f64]) -> (Vec<f64>, Vec<i8>, bool) {
1272    let n = x.len();
1273    let lbc: Vec<f64> = (0..n).map(|i| lb[i] - x[i]).collect();
1274    let ubc: Vec<f64> = (0..n).map(|i| ub[i] - x[i]).collect();
1275    let lt: Vec<f64> = (0..n).map(|i| lbc[i].max(-tr[i])).collect();
1276    let ut: Vec<f64> = (0..n).map(|i| ubc[i].min(tr[i])).collect();
1277    let mut hits_out = vec![0i8; n];
1278    if in_bounds(newton, &lt, &ut) {
1279        return (newton.to_vec(), hits_out, false);
1280    }
1281    let neg_g: Vec<f64> = g.iter().map(|v| -v).collect();
1282    let (to_bounds, _) = step_size_to_bound(&vec![0.0; n], &neg_g, &lt, &ut);
1283    let t = minimize_quadratic_1d(a, b, 0.0, to_bounds, 0.0).0;
1284    let cauchy: Vec<f64> = g.iter().map(|v| -t * v).collect();
1285    let diff: Vec<f64> = (0..n).map(|i| newton[i] - cauchy[i]).collect();
1286    let (size, hits) = step_size_to_bound(&cauchy, &diff, &lt, &ut);
1287    let mut tr_hit = false;
1288    for i in 0..n {
1289        if hits[i] < 0 && lt[i] == lbc[i] {
1290            hits_out[i] = -1;
1291        }
1292        if hits[i] > 0 && ut[i] == ubc[i] {
1293            hits_out[i] = 1;
1294        }
1295        if (hits[i] < 0 && lt[i] == -tr[i]) || (hits[i] > 0 && ut[i] == tr[i]) {
1296            tr_hit = true;
1297        }
1298    }
1299    ((0..n).map(|i| cauchy[i] + size * diff[i]).collect(), hits_out, tr_hit)
1300}
1301// ANCHOR_END: dogbox
1302
1303// ------------------------------------------------------------------------------ linear problems
1304
1305fn lstsq(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, ErrorsJSL> {
1306    if a.ncols() == 0 {
1307        return Ok(Array1::zeros(0));
1308    }
1309    Ok(a.least_squares(b).map_err(|_| ErrorsJSL::RuntimeError("least-squares solve failed"))?.solution)
1310}
1311
1312fn columns(a: &Array2<f64>, idx: &[usize]) -> Array2<f64> {
1313    a.select(Axis(1), idx)
1314}
1315
1316/// The result of [`lsq_linear`] and [`nnls`].
1317#[derive(Clone, Debug)]
1318#[non_exhaustive]
1319pub struct LinearLsqResult {
1320    pub x: Vec<f64>,
1321    /// `½ ‖A x − b‖²`.
1322    pub cost: f64,
1323    /// The residual norm `‖A x − b‖`.
1324    pub residual_norm: f64,
1325    pub active: Vec<i8>,
1326    pub iterations: usize,
1327}
1328
1329// ANCHOR: nnls
1330/// Non-negative least squares `min ‖A x − b‖` with `x ≥ 0` (SciPy's `nnls`), by Lawson and Hanson's
1331/// active-set method: repeatedly free the variable whose gradient most wants to grow, solve the
1332/// unconstrained problem on the free set, and step back to the boundary when a free variable
1333/// would turn negative.
1334pub fn nnls(a: &Array2<f64>, b: &[f64]) -> Result<LinearLsqResult, ErrorsJSL> {
1335    let (m, n) = a.dim();
1336    if b.len() != m {
1337        return Err(ErrorsJSL::IncompatibleArraySizes((b.len(), m)));
1338    }
1339    let b = Array1::from(b.to_vec());
1340    let mut x = Array1::<f64>::zeros(n);
1341    let mut passive = vec![false; n];
1342    let tol = 10.0 * f64::EPSILON * a.iter().fold(0.0f64, |s, v| s.max(v.abs())) * m.max(n) as f64;
1343    let mut iterations = 0;
1344    loop {
1345        let w = a.t().dot(&(&b - &a.dot(&x)));
1346        let candidate = (0..n).filter(|&j| !passive[j]).max_by(|&i, &j| w[i].total_cmp(&w[j]));
1347        let Some(jmax) = candidate else { break };
1348        if w[jmax] <= tol || iterations >= 3 * n {
1349            break;
1350        }
1351        passive[jmax] = true;
1352        loop {
1353            iterations += 1;
1354            let p: Vec<usize> = (0..n).filter(|&j| passive[j]).collect();
1355            let sp = lstsq(&columns(a, &p), &b)?;
1356            if sp.iter().all(|&v| v > 0.0) {
1357                x.fill(0.0);
1358                for (k, &j) in p.iter().enumerate() {
1359                    x[j] = sp[k];
1360                }
1361                break;
1362            }
1363            // Step from x towards s until the first passive variable reaches zero.
1364            let mut alpha = f64::INFINITY;
1365            for (k, &j) in p.iter().enumerate() {
1366                if sp[k] <= 0.0 {
1367                    alpha = alpha.min(x[j] / (x[j] - sp[k]));
1368                }
1369            }
1370            for (k, &j) in p.iter().enumerate() {
1371                x[j] += alpha * (sp[k] - x[j]);
1372            }
1373            for &j in &p {
1374                if x[j] <= tol {
1375                    x[j] = 0.0;
1376                    passive[j] = false;
1377                }
1378            }
1379            if iterations > 30 * n.max(1) {
1380                break;
1381            }
1382        }
1383    }
1384    let r = &a.dot(&x) - &b;
1385    let rn = r.dot(&r).sqrt();
1386    let active = (0..n).map(|j| if x[j] == 0.0 { -1 } else { 0 }).collect();
1387    Ok(LinearLsqResult { x: x.to_vec(), cost: 0.5 * rn * rn, residual_norm: rn, active, iterations })
1388}
1389// ANCHOR_END: nnls
1390
1391/// Linear least squares with bounds, `min ½‖A x − b‖²` subject to `lb ≤ x ≤ ub` (SciPy's
1392/// `lsq_linear(method='bvls')`), by Stark and Parker's bounded-variable least squares: start from
1393/// the unconstrained solution clipped to the bounds, then, while the KKT conditions are violated,
1394/// free the variable with the most violated condition and solve on the free set, stepping back to
1395/// the first bound crossed.
1396pub fn lsq_linear(a: &Array2<f64>, b: &[f64], lb: &[f64], ub: &[f64], tol: f64) -> Result<LinearLsqResult, ErrorsJSL> {
1397    let (m, n) = a.dim();
1398    if b.len() != m {
1399        return Err(ErrorsJSL::IncompatibleArraySizes((b.len(), m)));
1400    }
1401    check_bounds(&vec![0.0; n], lb, ub)?;
1402    let bv = Array1::from(b.to_vec());
1403    let mut x = lstsq(a, &bv)?.to_vec();
1404    let mut on_bound = vec![0i8; n];
1405    for i in 0..n {
1406        if x[i] <= lb[i] {
1407            x[i] = lb[i];
1408            on_bound[i] = -1;
1409        } else if x[i] >= ub[i] {
1410            x[i] = ub[i];
1411            on_bound[i] = 1;
1412        }
1413    }
1414    let residual = |x: &[f64]| -> Array1<f64> { a.dot(&Array1::from(x.to_vec())) - &bv };
1415    let grad = |x: &[f64]| -> Vec<f64> { a.t().dot(&residual(x)).to_vec() };
1416    let kkt = |g: &[f64], ob: &[i8]| -> f64 { (0..n).map(|i| if ob[i] == 0 { g[i].abs() } else { g[i] * ob[i] as f64 }).fold(f64::NEG_INFINITY, f64::max) };
1417    // Initial loop: solve on the free set until no free variable violates its bounds.
1418    let mut free: Vec<usize> = (0..n).filter(|&i| on_bound[i] == 0).collect();
1419    let mut iterations = 0;
1420    while !free.is_empty() {
1421        iterations += 1;
1422        let fixed_part: Vec<f64> = (0..n).map(|i| if on_bound[i] != 0 { x[i] } else { 0.0 }).collect();
1423        let b_free = &bv - &a.dot(&Array1::from(fixed_part));
1424        let z = lstsq(&columns(a, &free), &b_free)?;
1425        let mut violated = false;
1426        let mut still_free = Vec::new();
1427        for (k, &i) in free.iter().enumerate() {
1428            if z[k] < lb[i] {
1429                x[i] = lb[i];
1430                on_bound[i] = -1;
1431                violated = true;
1432            } else if z[k] > ub[i] {
1433                x[i] = ub[i];
1434                on_bound[i] = 1;
1435                violated = true;
1436            } else {
1437                x[i] = z[k];
1438                still_free.push(i);
1439            }
1440        }
1441        if !violated {
1442            break;
1443        }
1444        free = still_free;
1445    }
1446    let r = residual(&x);
1447    let mut cost = 0.5 * r.dot(&r);
1448    let mut g = grad(&x);
1449    let (start, max_iter) = (iterations, n + iterations);
1450    for _ in start..max_iter {
1451        if kkt(&g, &on_bound) < tol {
1452            break;
1453        }
1454        // Free the variable whose bound is most strongly opposed by the gradient.
1455        let mv = (0..n).max_by(|&i, &j| (g[i] * on_bound[i] as f64).total_cmp(&(g[j] * on_bound[j] as f64))).expect("non-empty");
1456        on_bound[mv] = 0;
1457        loop {
1458            iterations += 1;
1459            let free: Vec<usize> = (0..n).filter(|&i| on_bound[i] == 0).collect();
1460            let fixed_part: Vec<f64> = (0..n).map(|i| if on_bound[i] != 0 { x[i] } else { 0.0 }).collect();
1461            let b_free = &bv - &a.dot(&Array1::from(fixed_part));
1462            let z = lstsq(&columns(a, &free), &b_free)?;
1463            let mut best: Option<(f64, usize, i8)> = None;
1464            for (k, &i) in free.iter().enumerate() {
1465                let (alpha, side) = if z[k] < lb[i] {
1466                    ((lb[i] - x[i]) / (z[k] - x[i]), -1)
1467                } else if z[k] > ub[i] {
1468                    ((ub[i] - x[i]) / (z[k] - x[i]), 1)
1469                } else {
1470                    continue;
1471                };
1472                if best.is_none_or(|(a, _, _)| alpha < a) {
1473                    best = Some((alpha, i, side));
1474                }
1475            }
1476            match best {
1477                Some((alpha, i, side)) => {
1478                    for (k, &fi) in free.iter().enumerate() {
1479                        x[fi] += alpha * (z[k] - x[fi]);
1480                    }
1481                    x[i] = if side < 0 { lb[i] } else { ub[i] };
1482                    on_bound[i] = side;
1483                }
1484                None => {
1485                    for (k, &fi) in free.iter().enumerate() {
1486                        x[fi] = z[k];
1487                    }
1488                    break;
1489                }
1490            }
1491            if iterations > 50 * n.max(1) {
1492                break;
1493            }
1494        }
1495        let r = residual(&x);
1496        let cost_new = 0.5 * r.dot(&r);
1497        let change = cost - cost_new;
1498        cost = cost_new;
1499        g = grad(&x);
1500        if change < tol * cost {
1501            break;
1502        }
1503    }
1504    let r = residual(&x);
1505    let rn = r.dot(&r).sqrt();
1506    Ok(LinearLsqResult { x, cost: 0.5 * rn * rn, residual_norm: rn, active: on_bound, iterations })
1507}
1508
1509#[cfg(test)]
1510mod tests {
1511    use super::*;
1512    use ndarray::array;
1513
1514    fn rosen(x: &[f64]) -> (f64, Vec<f64>) {
1515        let n = x.len();
1516        let mut f = 0.0;
1517        let mut g = vec![0.0; n];
1518        for i in 0..n - 1 {
1519            let (a, b) = (x[i + 1] - x[i] * x[i], 1.0 - x[i]);
1520            f += 100.0 * a * a + b * b;
1521            g[i] += -400.0 * x[i] * a - 2.0 * b;
1522            g[i + 1] += 200.0 * a;
1523        }
1524        (f, g)
1525    }
1526
1527    #[test]
1528    fn lbfgsb_unconstrained_and_bounded_rosenbrock() {
1529        let x0 = vec![-1.2, 1.0, -1.2, 1.0];
1530        let inf = vec![f64::INFINITY; 4];
1531        let ninf = vec![f64::NEG_INFINITY; 4];
1532        let r = minimize_lbfgsb(rosen, &x0, &ninf, &inf, LbfgsbOptions::default()).unwrap();
1533        assert!(r.x.iter().all(|v| (v - 1.0).abs() < 1e-4), "{:?}", r.x);
1534        // With x ≤ 0.5 the optimum has x₀ on its bound and the KKT conditions hold.
1535        let ub = vec![0.5; 4];
1536        let r = minimize_lbfgsb(rosen, &x0, &ninf, &ub, LbfgsbOptions::default()).unwrap();
1537        assert!(r.converged);
1538        assert!(projected_gradient_norm(&r.x, &r.gradient, &ninf, &ub) < 1e-4, "{:?} {:?}", r.x, r.gradient);
1539        assert!(r.active.contains(&1));
1540    }
1541
1542    #[test]
1543    fn nnls_and_lsq_linear_satisfy_kkt() {
1544        let a = array![[1.0, 2.0, 0.5], [0.3, -1.0, 2.0], [2.0, 0.1, -0.7], [1.5, 1.5, 1.5]];
1545        let b = [1.0, -2.0, 3.0, 0.5];
1546        let r = nnls(&a, &b).unwrap();
1547        let g = a.t().dot(&(a.dot(&Array1::from(r.x.clone())) - Array1::from(b.to_vec())));
1548        for j in 0..3 {
1549            assert!(r.x[j] >= 0.0);
1550            if r.x[j] > 0.0 {
1551                assert!(g[j].abs() < 1e-10);
1552            } else {
1553                assert!(g[j] >= -1e-10);
1554            }
1555        }
1556        let r = lsq_linear(&a, &b, &[-0.2, -0.2, -0.2], &[0.3, 0.3, 0.3], 1e-12).unwrap();
1557        let g = a.t().dot(&(a.dot(&Array1::from(r.x.clone())) - Array1::from(b.to_vec())));
1558        for j in 0..3 {
1559            match r.active[j] {
1560                0 => assert!(g[j].abs() < 1e-10),
1561                -1 => assert!(g[j] >= -1e-10),
1562                _ => assert!(g[j] <= 1e-10),
1563            }
1564        }
1565    }
1566
1567    #[test]
1568    fn trf_fits_an_exponential_with_bounds() {
1569        // y = 2 e^{−0.7 t}, fitted with the rate bounded above by 0.5: the rate sits on its bound.
1570        let t: Vec<f64> = (0..20).map(|i| i as f64 * 0.25).collect();
1571        let y: Vec<f64> = t.iter().map(|&ti| 2.0 * (-0.7 * ti).exp()).collect();
1572        let fun = |p: &[f64]| t.iter().zip(&y).map(|(&ti, &yi)| p[0] * (-p[1] * ti).exp() - yi).collect::<Vec<_>>();
1573        let jac = |p: &[f64]| Array2::from_shape_fn((t.len(), 2), |(i, k)| if k == 0 { (-p[1] * t[i]).exp() } else { -p[0] * t[i] * (-p[1] * t[i]).exp() });
1574        let free = least_squares_bounded(fun, jac, &[1.0, 0.1], &[0.0, 0.0], &[10.0, 5.0], LeastSquaresOptions::default()).unwrap();
1575        assert!((free.x[0] - 2.0).abs() < 1e-6 && (free.x[1] - 0.7).abs() < 1e-6, "{:?}", free.x);
1576        let bounded = least_squares_bounded(fun, jac, &[1.0, 0.1], &[0.0, 0.0], &[10.0, 0.5], LeastSquaresOptions::default()).unwrap();
1577        assert_eq!(bounded.active[1], 1);
1578        assert!(bounded.optimality < 1e-6, "{}", bounded.optimality);
1579    }
1580
1581    #[test]
1582    fn trf_lsmr_matches_the_exact_solver() {
1583        let t: Vec<f64> = (0..20).map(|i| i as f64 * 0.25).collect();
1584        let y: Vec<f64> = t.iter().map(|&ti| 2.0 * (-0.7 * ti).exp() + 0.01 * (3.0 * ti).sin()).collect();
1585        let fun = |p: &[f64]| t.iter().zip(&y).map(|(&ti, &yi)| p[0] * (-p[1] * ti).exp() - yi).collect::<Vec<_>>();
1586        let jac = |p: &[f64]| Array2::from_shape_fn((t.len(), 2), |(i, k)| if k == 0 { (-p[1] * t[i]).exp() } else { -p[0] * t[i] * (-p[1] * t[i]).exp() });
1587        for (ub, loss) in [(5.0, Loss::Linear), (0.5, Loss::Linear), (5.0, Loss::SoftL1)] {
1588            let o = LeastSquaresOptions { loss, ..Default::default() };
1589            let exact = least_squares_bounded(fun, jac, &[1.0, 0.1], &[0.0, 0.0], &[10.0, ub], o).unwrap();
1590            let it = least_squares_lsmr(fun, jac, &[1.0, 0.1], &[0.0, 0.0], &[10.0, ub], o).unwrap();
1591            assert!(it.status > 0 && (it.x[0] - exact.x[0]).abs() < 1e-6 && (it.x[1] - exact.x[1]).abs() < 1e-6, "{:?} {:?}", it.x, exact.x);
1592        }
1593        // Unbounded, with a sparse Jacobian: the Broyden tridiagonal system.
1594        let n = 50;
1595        let f = |x: &[f64]| (0..n).map(|i| (3.0 - 2.0 * x[i]) * x[i] - if i > 0 { x[i - 1] } else { 0.0 } - 2.0 * if i + 1 < n { x[i + 1] } else { 0.0 } + 1.0).collect::<Vec<_>>();
1596        let j = |x: &[f64]| {
1597            let mut coo = lib_jsl_linalg::sparse::CooMatrix::new(n, n);
1598            for i in 0..n {
1599                coo.push(i, i, 3.0 - 4.0 * x[i]);
1600                if i > 0 {
1601                    coo.push(i, i - 1, -1.0);
1602                }
1603                if i + 1 < n {
1604                    coo.push(i, i + 1, -2.0);
1605                }
1606            }
1607            coo.to_csr().unwrap()
1608        };
1609        let r = least_squares_lsmr(f, j, &vec![-1.0; n], &vec![f64::NEG_INFINITY; n], &vec![f64::INFINITY; n], LeastSquaresOptions::default()).unwrap();
1610        assert!(r.cost < 1e-12, "{}", r.cost);
1611    }
1612}