Skip to main content

lib_jsl_linalg/sparse/
iterative.rs

1//! Krylov-subspace solvers for large sparse systems, following `scipy.sparse.linalg`: conjugate
2//! gradients (`cg`) for symmetric positive definite matrices, MINRES for symmetric indefinite
3//! ones, restarted GMRES and BiCGSTAB for general matrices, and LSQR for least squares. Each
4//! works with any [`LinearOperator`], and the square solvers accept a preconditioner `M ≈ A⁻¹`.
5
6use super::formats::{CscMatrix, CsrMatrix};
7use crate::error::{LinalgError, Result};
8use ndarray::Array2;
9
10/// A matrix seen only through its products with vectors (SciPy's `LinearOperator`).
11pub trait LinearOperator {
12    /// `(rows, columns)`.
13    fn shape(&self) -> (usize, usize);
14    /// `A x`.
15    fn matvec(&self, x: &[f64]) -> Vec<f64>;
16    /// `Aᵀ x` (needed by LSQR).
17    fn rmatvec(&self, x: &[f64]) -> Vec<f64>;
18}
19
20impl LinearOperator for CsrMatrix {
21    fn shape(&self) -> (usize, usize) {
22        (self.nrows, self.ncols)
23    }
24    fn matvec(&self, x: &[f64]) -> Vec<f64> {
25        CsrMatrix::matvec(self, x)
26    }
27    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
28        CsrMatrix::rmatvec(self, x)
29    }
30}
31
32impl LinearOperator for CscMatrix {
33    fn shape(&self) -> (usize, usize) {
34        (self.nrows, self.ncols)
35    }
36    fn matvec(&self, x: &[f64]) -> Vec<f64> {
37        CscMatrix::matvec(self, x)
38    }
39    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
40        let mut y = vec![0.0; self.ncols];
41        for (j, yj) in y.iter_mut().enumerate() {
42            *yj = (self.indptr[j]..self.indptr[j + 1]).map(|p| self.data[p] * x[self.indices[p]]).sum();
43        }
44        y
45    }
46}
47
48impl LinearOperator for Array2<f64> {
49    fn shape(&self) -> (usize, usize) {
50        self.dim()
51    }
52    fn matvec(&self, x: &[f64]) -> Vec<f64> {
53        self.dot(&ndarray::ArrayView1::from(x)).to_vec()
54    }
55    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
56        self.t().dot(&ndarray::ArrayView1::from(x)).to_vec()
57    }
58}
59
60/// A linear operator defined by closures.
61pub struct FnOperator<F: Fn(&[f64]) -> Vec<f64>, G: Fn(&[f64]) -> Vec<f64>> {
62    pub shape: (usize, usize),
63    pub matvec: F,
64    pub rmatvec: G,
65}
66
67impl<F: Fn(&[f64]) -> Vec<f64>, G: Fn(&[f64]) -> Vec<f64>> LinearOperator for FnOperator<F, G> {
68    fn shape(&self) -> (usize, usize) {
69        self.shape
70    }
71    fn matvec(&self, x: &[f64]) -> Vec<f64> {
72        (self.matvec)(x)
73    }
74    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
75        (self.rmatvec)(x)
76    }
77}
78
79/// The Jacobi (diagonal) preconditioner `M = diag(A)⁻¹`.
80pub struct Jacobi {
81    inverse_diagonal: Vec<f64>,
82}
83
84impl Jacobi {
85    pub fn new(a: &CsrMatrix) -> Result<Self> {
86        let d = a.diagonal();
87        if d.contains(&0.0) {
88            return Err(LinalgError::Singular(0));
89        }
90        Ok(Jacobi { inverse_diagonal: d.iter().map(|v| 1.0 / v).collect() })
91    }
92}
93
94impl LinearOperator for Jacobi {
95    fn shape(&self) -> (usize, usize) {
96        (self.inverse_diagonal.len(), self.inverse_diagonal.len())
97    }
98    fn matvec(&self, x: &[f64]) -> Vec<f64> {
99        x.iter().zip(&self.inverse_diagonal).map(|(a, b)| a * b).collect()
100    }
101    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
102        self.matvec(x)
103    }
104}
105
106/// Options for the iterative solvers. Convergence when `‖b − A x‖ ≤ max(rtol ‖b‖, atol)`
107/// (SciPy's defaults: `rtol = 10⁻⁵`, `atol = 0`).
108#[derive(Clone, Copy, Debug)]
109pub struct IterativeOptions {
110    pub rtol: f64,
111    pub atol: f64,
112    /// Default: 10 n (GMRES: 10 n inner iterations).
113    pub max_iterations: Option<usize>,
114}
115
116impl Default for IterativeOptions {
117    fn default() -> Self {
118        IterativeOptions { rtol: 1e-5, atol: 0.0, max_iterations: None }
119    }
120}
121
122/// The result of an iterative solve.
123#[derive(Clone, Debug)]
124#[non_exhaustive]
125pub struct IterativeResult {
126    pub x: Vec<f64>,
127    /// Matrix-vector products with `A`.
128    pub iterations: usize,
129    pub converged: bool,
130    /// The residual norm after each iteration, starting with the initial one.
131    pub residual_history: Vec<f64>,
132}
133
134fn dot(a: &[f64], b: &[f64]) -> f64 {
135    a.iter().zip(b).map(|(x, y)| x * y).sum()
136}
137
138fn norm(a: &[f64]) -> f64 {
139    dot(a, a).sqrt()
140}
141
142fn axpy(y: &mut [f64], a: f64, x: &[f64]) {
143    y.iter_mut().zip(x).for_each(|(yi, xi)| *yi += a * xi);
144}
145
146fn residual(a: &dyn LinearOperator, b: &[f64], x: &[f64]) -> Vec<f64> {
147    let ax = a.matvec(x);
148    b.iter().zip(&ax).map(|(p, q)| p - q).collect()
149}
150
151fn setup(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>) -> Result<Vec<f64>> {
152    let (m, n) = a.shape();
153    if m != n || b.len() != n {
154        return Err(LinalgError::Shape(format!("operator {m} × {n} with right-hand side of length {}", b.len())));
155    }
156    Ok(x0.map_or(vec![0.0; n], |v| v.to_vec()))
157}
158
159fn precondition(m: Option<&dyn LinearOperator>, r: &[f64]) -> Vec<f64> {
160    m.map_or_else(|| r.to_vec(), |m| m.matvec(r))
161}
162
163// ANCHOR: cg
164/// Conjugate gradients for symmetric positive definite `A` (SciPy's `cg`): each step minimises
165/// the `A`-norm of the error over a growing Krylov subspace, with search directions that are
166/// `A`-conjugate. With `M`, the preconditioned residual `z = M r` replaces `r` in the recurrences.
167pub fn cg(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
168    let mut x = setup(a, b, x0)?;
169    let tol = (options.rtol * norm(b)).max(options.atol);
170    let max_it = options.max_iterations.unwrap_or(10 * b.len());
171    let mut r = residual(a, b, &x);
172    let mut history = vec![norm(&r)];
173    let mut z = precondition(m, &r);
174    let mut p = z.clone();
175    let mut rz = dot(&r, &z);
176    let mut it = 0;
177    while history[history.len() - 1] > tol && it < max_it {
178        let ap = a.matvec(&p);
179        let alpha = rz / dot(&p, &ap);
180        axpy(&mut x, alpha, &p);
181        axpy(&mut r, -alpha, &ap);
182        it += 1;
183        history.push(norm(&r));
184        z = precondition(m, &r);
185        let rz_new = dot(&r, &z);
186        let beta = rz_new / rz;
187        rz = rz_new;
188        p = z.iter().zip(&p).map(|(zi, pi)| zi + beta * pi).collect();
189    }
190    let converged = history[history.len() - 1] <= tol;
191    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
192}
193// ANCHOR_END: cg
194
195/// BiCGSTAB for general square `A` (SciPy's `bicgstab`): biconjugate gradients stabilised by a
196/// one-step minimal-residual smoothing, two products with `A` per iteration.
197pub fn bicgstab(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
198    let mut x = setup(a, b, x0)?;
199    let tol = (options.rtol * norm(b)).max(options.atol);
200    let max_it = options.max_iterations.unwrap_or(10 * b.len());
201    let mut r = residual(a, b, &x);
202    let rhat = r.clone();
203    let mut history = vec![norm(&r)];
204    let (mut rho, mut alpha, mut omega) = (1.0, 1.0, 1.0);
205    let n = b.len();
206    let (mut v, mut p) = (vec![0.0; n], vec![0.0; n]);
207    let mut it = 0;
208    while history[history.len() - 1] > tol && it < max_it {
209        let rho_new = dot(&rhat, &r);
210        if rho_new == 0.0 {
211            break;
212        }
213        let beta = rho_new / rho * alpha / omega;
214        rho = rho_new;
215        for i in 0..n {
216            p[i] = r[i] + beta * (p[i] - omega * v[i]);
217        }
218        let phat = precondition(m, &p);
219        v = a.matvec(&phat);
220        alpha = rho / dot(&rhat, &v);
221        let s: Vec<f64> = r.iter().zip(&v).map(|(ri, vi)| ri - alpha * vi).collect();
222        it += 1;
223        if norm(&s) <= tol {
224            axpy(&mut x, alpha, &phat);
225            history.push(norm(&s));
226            r = s;
227            break;
228        }
229        let shat = precondition(m, &s);
230        let t = a.matvec(&shat);
231        omega = dot(&t, &s) / dot(&t, &t);
232        axpy(&mut x, alpha, &phat);
233        axpy(&mut x, omega, &shat);
234        r = s.iter().zip(&t).map(|(si, ti)| si - omega * ti).collect();
235        history.push(norm(&r));
236        if omega == 0.0 {
237            break;
238        }
239    }
240    let converged = norm(&r) <= tol;
241    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
242}
243
244// ANCHOR: gmres
245/// Restarted GMRES(`restart`) for general square `A` (SciPy's `gmres`, default restart 20): the
246/// Arnoldi process builds an orthonormal Krylov basis, and Givens rotations keep the small least-
247/// squares problem for the residual-minimising combination triangular, which gives the residual
248/// norm at every step without forming `x`. Right preconditioning, `A M y = b`, `x = M y`.
249pub fn gmres(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, restart: usize, options: IterativeOptions) -> Result<IterativeResult> {
250    let mut x = setup(a, b, x0)?;
251    let n = b.len();
252    let restart = restart.clamp(1, n.max(1));
253    let tol = (options.rtol * norm(b)).max(options.atol);
254    let max_it = options.max_iterations.unwrap_or(10 * n);
255    let mut r = residual(a, b, &x);
256    let mut history = vec![norm(&r)];
257    let mut it = 0;
258    while history[history.len() - 1] > tol && it < max_it {
259        let beta = norm(&r);
260        let mut basis: Vec<Vec<f64>> = vec![r.iter().map(|v| v / beta).collect()];
261        let mut h = vec![vec![0.0; restart]; restart + 1];
262        let (mut cs, mut sn) = (vec![0.0; restart], vec![0.0; restart]);
263        let mut g = vec![0.0; restart + 1];
264        g[0] = beta;
265        let mut k_done = 0;
266        for k in 0..restart {
267            let mut w = a.matvec(&precondition(m, &basis[k]));
268            // Modified Gram-Schmidt.
269            for (j, vj) in basis.iter().enumerate() {
270                h[j][k] = dot(&w, vj);
271                axpy(&mut w, -h[j][k], vj);
272            }
273            h[k + 1][k] = norm(&w);
274            // Apply the previous rotations to the new column, then a new rotation.
275            for j in 0..k {
276                let t = cs[j] * h[j][k] + sn[j] * h[j + 1][k];
277                h[j + 1][k] = -sn[j] * h[j][k] + cs[j] * h[j + 1][k];
278                h[j][k] = t;
279            }
280            let denom = h[k][k].hypot(h[k + 1][k]);
281            cs[k] = h[k][k] / denom;
282            sn[k] = h[k + 1][k] / denom;
283            h[k][k] = denom;
284            h[k + 1][k] = 0.0;
285            g[k + 1] = -sn[k] * g[k];
286            g[k] *= cs[k];
287            it += 1;
288            k_done = k + 1;
289            history.push(g[k + 1].abs());
290            if g[k + 1].abs() <= tol || it >= max_it {
291                break;
292            }
293            let hk1 = h_norm(&w);
294            if hk1 == 0.0 {
295                break;
296            }
297            basis.push(w.iter().map(|v| v / hk1).collect());
298        }
299        // Back-substitution for y, then x += M V y.
300        let mut y = vec![0.0; k_done];
301        for i in (0..k_done).rev() {
302            let s: f64 = (i + 1..k_done).map(|j| h[i][j] * y[j]).sum();
303            y[i] = (g[i] - s) / h[i][i];
304        }
305        let mut update = vec![0.0; n];
306        for (j, yj) in y.iter().enumerate() {
307            axpy(&mut update, *yj, &basis[j]);
308        }
309        let dx = precondition(m, &update);
310        axpy(&mut x, 1.0, &dx);
311        r = residual(a, b, &x);
312        let true_norm = norm(&r);
313        let last = history.len() - 1;
314        history[last] = true_norm;
315    }
316    let converged = history[history.len() - 1] <= tol;
317    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
318}
319// ANCHOR_END: gmres
320
321fn h_norm(w: &[f64]) -> f64 {
322    norm(w)
323}
324
325/// MINRES for symmetric (possibly indefinite) `A` (Paige and Saunders; SciPy's `minres`):
326/// the Lanczos process with Givens rotations, minimising `‖b − A x‖` over the Krylov subspace with
327/// short recurrences.
328pub fn minres(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, options: IterativeOptions) -> Result<IterativeResult> {
329    let mut x = setup(a, b, x0)?;
330    let n = b.len();
331    let tol = (options.rtol * norm(b)).max(options.atol);
332    let max_it = options.max_iterations.unwrap_or(5 * n);
333    let r0 = residual(a, b, &x);
334    let beta1 = norm(&r0);
335    let mut history = vec![beta1];
336    if beta1 <= tol {
337        return Ok(IterativeResult { x, iterations: 0, converged: true, residual_history: history });
338    }
339    // Paige and Saunders' recurrences, as in SciPy's `minres` without a preconditioner.
340    let (mut r1, mut r2) = (r0.clone(), r0);
341    let (mut oldb, mut beta) = (0.0, beta1);
342    let (mut dbar, mut epsln, mut phibar) = (0.0, 0.0, beta1);
343    let (mut cs, mut sn) = (-1.0, 0.0);
344    let (mut w, mut w2) = (vec![0.0; n], vec![0.0; n]);
345    let mut it = 0;
346    while phibar > tol && it < max_it {
347        it += 1;
348        let v: Vec<f64> = r2.iter().map(|t| t / beta).collect();
349        let mut y = a.matvec(&v);
350        if it >= 2 {
351            axpy(&mut y, -beta / oldb, &r1);
352        }
353        let alfa = dot(&v, &y);
354        axpy(&mut y, -alfa / beta, &r2);
355        r1 = r2;
356        r2 = y;
357        oldb = beta;
358        beta = norm(&r2);
359        let oldeps = epsln;
360        let delta = cs * dbar + sn * alfa;
361        let gbar = sn * dbar - cs * alfa;
362        epsln = sn * beta;
363        dbar = -cs * beta;
364        let gamma = gbar.hypot(beta).max(f64::MIN_POSITIVE);
365        cs = gbar / gamma;
366        sn = beta / gamma;
367        let phi = cs * phibar;
368        phibar *= sn;
369        let w1 = std::mem::replace(&mut w2, w.clone());
370        w = (0..n).map(|i| (v[i] - oldeps * w1[i] - delta * w2[i]) / gamma).collect();
371        axpy(&mut x, phi, &w);
372        history.push(phibar);
373        if beta == 0.0 {
374            break;
375        }
376    }
377    let true_res = norm(&residual(a, b, &x));
378    let last = history.len() - 1;
379    history[last] = true_res;
380    Ok(IterativeResult { x, iterations: it, converged: true_res <= tol * (1.0 + 1e-6), residual_history: history })
381}
382
383// ANCHOR: lsqr
384/// LSQR for `min ‖A x − b‖` with any rectangular `A` (Paige and Saunders; SciPy's `lsqr`):
385/// Golub-Kahan bidiagonalisation of `A`, mathematically CG on the normal equations but stable. It
386/// stops when `‖r‖ ≤ btol ‖b‖ + atol ‖A‖ ‖x‖` (a consistent system) or
387/// `‖Aᵀr‖ ≤ atol ‖A‖ ‖r‖` (a least-squares solution), with SciPy's `atol = btol = 10⁻⁶` by
388/// default (`options.rtol` is used for both).
389pub fn lsqr(a: &dyn LinearOperator, b: &[f64], options: IterativeOptions) -> Result<IterativeResult> {
390    let (m, n) = a.shape();
391    if b.len() != m {
392        return Err(LinalgError::Shape(format!("operator {m} × {n} with right-hand side of length {}", b.len())));
393    }
394    let tol = options.rtol;
395    let max_it = options.max_iterations.unwrap_or(2 * n);
396    let mut x = vec![0.0; n];
397    let mut u = b.to_vec();
398    let mut beta = norm(&u);
399    let bnorm = beta;
400    let mut history = vec![beta];
401    if beta == 0.0 {
402        return Ok(IterativeResult { x, iterations: 0, converged: true, residual_history: history });
403    }
404    u.iter_mut().for_each(|v| *v /= beta);
405    let mut v = a.rmatvec(&u);
406    let mut alpha = norm(&v);
407    v.iter_mut().for_each(|t| *t /= alpha);
408    let mut w = v.clone();
409    let (mut phibar, mut rhobar) = (beta, alpha);
410    let mut anorm2 = 0.0;
411    let mut it = 0;
412    let mut converged = false;
413    while it < max_it {
414        it += 1;
415        let av = a.matvec(&v);
416        u = av.iter().zip(&u).map(|(p, q)| p - alpha * q).collect();
417        beta = norm(&u);
418        if beta > 0.0 {
419            u.iter_mut().for_each(|t| *t /= beta);
420            let atu = a.rmatvec(&u);
421            v = atu.iter().zip(&v).map(|(p, q)| p - beta * q).collect();
422            alpha = norm(&v);
423            if alpha > 0.0 {
424                v.iter_mut().for_each(|t| *t /= alpha);
425            }
426        }
427        anorm2 += alpha * alpha + beta * beta;
428        let rho = rhobar.hypot(beta);
429        let (c, s) = (rhobar / rho, beta / rho);
430        let theta = s * alpha;
431        rhobar = -c * alpha;
432        let phi = c * phibar;
433        phibar *= s;
434        axpy(&mut x, phi / rho, &w);
435        w = v.iter().zip(&w).map(|(vi, wi)| vi - theta / rho * wi).collect();
436        let rnorm = phibar;
437        history.push(rnorm);
438        let arnorm = phibar * alpha * c.abs();
439        let anorm = anorm2.sqrt();
440        let xnorm = norm(&x);
441        if rnorm <= tol * bnorm + tol * anorm * xnorm || arnorm <= tol * anorm * rnorm || rnorm == 0.0 {
442            converged = true;
443            break;
444        }
445    }
446    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
447}
448// ANCHOR_END: lsqr
449
450/// Options for [`lsmr`], with SciPy's defaults.
451#[derive(Clone, Copy, Debug)]
452#[non_exhaustive]
453pub struct LsmrOptions {
454    /// The damping `λ` in `min ‖A x − b‖² + λ² ‖x‖²`.
455    pub damp: f64,
456    /// Relative error in `A`: stop when `‖Aᵀr‖ ≤ atol ‖A‖ ‖r‖`.
457    pub atol: f64,
458    /// Relative error in `b`: stop when `‖r‖ ≤ btol ‖b‖ + atol ‖A‖ ‖x‖`.
459    pub btol: f64,
460    /// Stop when the condition estimate exceeds this.
461    pub conlim: f64,
462    /// Default `min(m, n)`.
463    pub max_iterations: Option<usize>,
464}
465
466impl Default for LsmrOptions {
467    fn default() -> Self {
468        LsmrOptions { damp: 0.0, atol: 1e-6, btol: 1e-6, conlim: 1e8, max_iterations: None }
469    }
470}
471
472impl LsmrOptions {
473    /// The defaults with damping `λ`.
474    pub fn with_damp(damp: f64) -> Self {
475        LsmrOptions { damp, ..Default::default() }
476    }
477}
478
479/// The result of [`lsmr`] (SciPy's `x, istop, itn, normr, normar, norma, conda, normx`).
480#[derive(Clone, Debug)]
481#[non_exhaustive]
482pub struct LsmrResult {
483    pub x: Vec<f64>,
484    /// SciPy's `istop`: 0 `x = 0` is the solution, 1 `Ax = b` to `btol`, 2 least squares to
485    /// `atol`, 3 the condition limit, 4–6 the same at machine precision, 7 the iteration limit.
486    pub istop: i32,
487    pub iterations: usize,
488    /// `‖b − A x‖` (with the damping term included when `λ > 0`).
489    pub normr: f64,
490    /// `‖Aᵀ(b − A x) − λ² x‖`.
491    pub normar: f64,
492    /// Estimates of `‖A‖` (of `[A; λI]`) and its condition number.
493    pub norma: f64,
494    pub conda: f64,
495    pub normx: f64,
496}
497
498/// SciPy's `_sym_ortho`: a stable Givens rotation `(c, s, r)` with `[c s; −s c] [a; b] = [r; 0]`.
499fn sym_ortho(a: f64, b: f64) -> (f64, f64, f64) {
500    if b == 0.0 {
501        (if a == 0.0 { 0.0 } else { a.signum() }, 0.0, a.abs())
502    } else if a == 0.0 {
503        (0.0, b.signum(), b.abs())
504    } else if b.abs() > a.abs() {
505        let tau = a / b;
506        let s = b.signum() / (1.0 + tau * tau).sqrt();
507        (s * tau, s, b / s)
508    } else {
509        let tau = b / a;
510        let c = a.signum() / (1.0 + tau * tau).sqrt();
511        (c, c * tau, a / c)
512    }
513}
514
515// ANCHOR: lsmr
516/// LSMR for `min ‖A x − b‖² + λ² ‖x‖²` (Fong and Saunders; SciPy's `lsmr`). Like LSQR it
517/// builds the Golub-Kahan bidiagonalisation of `A`, but it minimises `‖Aᵀr‖` over the Krylov
518/// subspace rather than `‖r‖`, so `‖Aᵀr‖` decreases monotonically and the iteration can be
519/// stopped safely early: the property that makes it the inner solver of large least-squares
520/// trust-region methods.
521pub fn lsmr(a: &dyn LinearOperator, b: &[f64], options: LsmrOptions) -> Result<LsmrResult> {
522    let (m, n) = a.shape();
523    if b.len() != m {
524        return Err(LinalgError::Shape(format!("operator {m} × {n} with right-hand side of length {}", b.len())));
525    }
526    let LsmrOptions { damp, atol, btol, conlim, max_iterations } = options;
527    let maxiter = max_iterations.unwrap_or(m.min(n));
528    let mut u = b.to_vec();
529    let normb = norm(&u);
530    let mut x = vec![0.0; n];
531    let mut beta = normb;
532    let (mut v, mut alpha) = if beta > 0.0 {
533        u.iter_mut().for_each(|t| *t /= beta);
534        let v = a.rmatvec(&u);
535        let alpha = norm(&v);
536        (v, alpha)
537    } else {
538        (vec![0.0; n], 0.0)
539    };
540    if alpha > 0.0 {
541        v.iter_mut().for_each(|t| *t /= alpha);
542    }
543    let mut zetabar = alpha * beta;
544    let mut alphabar = alpha;
545    let (mut rho, mut rhobar, mut cbar, mut sbar) = (1.0, 1.0, 1.0, 0.0);
546    let mut h = v.clone();
547    let mut hbar = vec![0.0; n];
548    let (mut betadd, mut betad, mut rhodold, mut tautildeold, mut thetatilde, mut zeta, mut d) = (beta, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0);
549    let mut norma2 = alpha * alpha;
550    let (mut maxrbar, mut minrbar) = (0.0f64, 1e100f64);
551    let mut norma = norma2.sqrt();
552    let mut conda = 1.0;
553    let mut normx = 0.0;
554    let ctol = if conlim > 0.0 { 1.0 / conlim } else { 0.0 };
555    let mut normr = beta;
556    let mut normar = alpha * beta;
557    let mut istop = 0;
558    let mut itn = 0;
559    if normar == 0.0 {
560        return Ok(LsmrResult { x, istop, iterations: 0, normr, normar, norma, conda, normx });
561    }
562    while itn < maxiter {
563        itn += 1;
564        let av = a.matvec(&v);
565        u = av.iter().zip(&u).map(|(p, q)| p - alpha * q).collect();
566        beta = norm(&u);
567        if beta > 0.0 {
568            u.iter_mut().for_each(|t| *t /= beta);
569            let atu = a.rmatvec(&u);
570            v = atu.iter().zip(&v).map(|(p, q)| p - beta * q).collect();
571            alpha = norm(&v);
572            if alpha > 0.0 {
573                v.iter_mut().for_each(|t| *t /= alpha);
574            }
575        }
576        let (chat, shat, alphahat) = sym_ortho(alphabar, damp);
577        let rhoold = rho;
578        let (c, s, r) = sym_ortho(alphahat, beta);
579        rho = r;
580        let thetanew = s * alpha;
581        alphabar = c * alpha;
582        let rhobarold = rhobar;
583        let zetaold = zeta;
584        let thetabar = sbar * rho;
585        let rhotemp = cbar * rho;
586        let (cb, sb, rb) = sym_ortho(cbar * rho, thetanew);
587        (cbar, sbar, rhobar) = (cb, sb, rb);
588        zeta = cbar * zetabar;
589        zetabar *= -sbar;
590        let fh = thetabar * rho / (rhoold * rhobarold);
591        hbar = h.iter().zip(&hbar).map(|(p, q)| p - fh * q).collect();
592        axpy(&mut x, zeta / (rho * rhobar), &hbar);
593        let fv = thetanew / rho;
594        h = v.iter().zip(&h).map(|(p, q)| p - fv * q).collect();
595        // The residual norm estimate.
596        let betaacute = chat * betadd;
597        let betacheck = -shat * betadd;
598        let betahat = c * betaacute;
599        betadd = -s * betaacute;
600        let thetatildeold = thetatilde;
601        let (ctildeold, stildeold, rhotildeold) = sym_ortho(rhodold, thetabar);
602        thetatilde = stildeold * rhobar;
603        rhodold = ctildeold * rhobar;
604        betad = -stildeold * betad + ctildeold * betahat;
605        tautildeold = (zetaold - thetatildeold * tautildeold) / rhotildeold;
606        let taud = (zeta - thetatilde * tautildeold) / rhodold;
607        d += betacheck * betacheck;
608        normr = (d + (betad - taud).powi(2) + betadd * betadd).sqrt();
609        // ‖A‖ and cond(A).
610        norma2 += beta * beta;
611        norma = norma2.sqrt();
612        norma2 += alpha * alpha;
613        maxrbar = maxrbar.max(rhobarold);
614        if itn > 1 {
615            minrbar = minrbar.min(rhobarold);
616        }
617        conda = maxrbar.max(rhotemp) / minrbar.min(rhotemp);
618        normar = zetabar.abs();
619        normx = norm(&x);
620        let test1 = normr / normb;
621        let test2 = if norma * normr != 0.0 { normar / (norma * normr) } else { f64::INFINITY };
622        let test3 = 1.0 / conda;
623        let t1 = test1 / (1.0 + norma * normx / normb);
624        let rtol = btol + atol * norma * normx / normb;
625        if itn >= maxiter {
626            istop = 7;
627        }
628        if 1.0 + test3 <= 1.0 {
629            istop = 6;
630        }
631        if 1.0 + test2 <= 1.0 {
632            istop = 5;
633        }
634        if 1.0 + t1 <= 1.0 {
635            istop = 4;
636        }
637        if test3 <= ctol {
638            istop = 3;
639        }
640        if test2 <= atol {
641            istop = 2;
642        }
643        if test1 <= rtol {
644            istop = 1;
645        }
646        if istop > 0 {
647            break;
648        }
649    }
650    Ok(LsmrResult { x, istop, iterations: itn, normr, normar, norma, conda, normx })
651}
652// ANCHOR_END: lsmr