Skip to main content

lib_jsl_linalg/sparse/
lgmres.rs

1//! LGMRES: restarted GMRES augmented with approximations of the error from previous cycles
2//! (Baker, Jessup and Manteuffel, 2005; SciPy's `lgmres`).
3
4use super::iterative::{IterativeOptions, IterativeResult, LinearOperator};
5use crate::error::{LinalgError, Result};
6
7fn dot(a: &[f64], b: &[f64]) -> f64 {
8    a.iter().zip(b).map(|(x, y)| x * y).sum()
9}
10
11fn norm(a: &[f64]) -> f64 {
12    dot(a, a).sqrt()
13}
14
15/// A stateful LGMRES solver: the augmentation vectors it keeps carry over from one call of
16/// [`LgmresSolver::solve`] to the next, which is how SciPy's `newton_krylov` reuses them across
17/// Newton iterations.
18#[derive(Clone, Debug)]
19pub struct LgmresSolver {
20    /// Arnoldi steps per cycle, besides the augmentation vectors (SciPy's `inner_m`, default 30).
21    pub inner_m: usize,
22    /// The most augmentation vectors kept (SciPy's `outer_k`, default 3).
23    pub outer_k: usize,
24    /// Keep `A z` with each augmentation vector `z`, saving one product each when it is reused
25    /// (SciPy's `store_outer_Av`, default true).
26    pub store_outer_av: bool,
27    /// Put the augmentation vectors before the Krylov vectors in each cycle rather than after
28    /// (SciPy's `prepend_outer_v`, default false).
29    pub prepend_outer_v: bool,
30    outer: Vec<(Vec<f64>, Option<Vec<f64>>)>,
31}
32
33impl Default for LgmresSolver {
34    fn default() -> Self {
35        LgmresSolver { inner_m: 30, outer_k: 3, store_outer_av: true, prepend_outer_v: false, outer: Vec::new() }
36    }
37}
38
39impl LgmresSolver {
40    /// A solver with `inner_m` Krylov steps per cycle and at most `outer_k` augmentation
41    /// vectors, storing `A z` and appending them (SciPy's other defaults).
42    pub fn new(inner_m: usize, outer_k: usize) -> Self {
43        LgmresSolver { inner_m, outer_k, ..Default::default() }
44    }
45
46    /// The augmentation vectors kept from previous cycles, newest last.
47    pub fn augmentation_len(&self) -> usize {
48        self.outer.len()
49    }
50
51    // ANCHOR: lgmres
52    /// Solves `A x = b`, with an optional left preconditioner `M ≈ A⁻¹`. Each cycle runs flexible
53    /// GMRES on `M A` from the preconditioned residual over `inner_m` Krylov vectors plus the
54    /// kept error approximations `z` (with `M A z`), and the correction it finds becomes a new
55    /// augmentation vector. A cycle stops early at a relative residual `ptol`, which adapts: it
56    /// tightens when a cycle reaches it, and relaxes when one does not.
57    /// `options.max_iterations` is the number of cycles (SciPy's `maxiter`, default 1000).
58    pub fn solve(&mut self, a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
59        let (rows, cols) = a.shape();
60        if rows != cols || b.len() != rows {
61            return Err(LinalgError::Shape(format!("operator {rows} × {cols} with right-hand side of length {}", b.len())));
62        }
63        let n = b.len();
64        let psolve = |v: &[f64]| m.map_or_else(|| v.to_vec(), |m| m.matvec(v));
65        let mut x = x0.map_or(vec![0.0; n], |v| v.to_vec());
66        let b_norm = norm(b);
67        let tol = options.atol.max(options.rtol * b_norm);
68        let mut matvecs = 0;
69        let mut history = Vec::new();
70        if b_norm == 0.0 {
71            return Ok(IterativeResult { x: vec![0.0; n], iterations: 0, converged: true, residual_history: vec![0.0] });
72        }
73        let mut ptol_max_factor: f64 = 1.0;
74        let max_cycles = options.max_iterations.unwrap_or(1000);
75        let mut converged = false;
76        for _ in 0..max_cycles {
77            let ax = a.matvec(&x);
78            matvecs += 1;
79            let r: Vec<f64> = ax.iter().zip(b).map(|(p, q)| p - q).collect();
80            let r_norm = norm(&r);
81            history.push(r_norm);
82            if r_norm <= tol {
83                converged = true;
84                break;
85            }
86            let mut v0: Vec<f64> = psolve(&r).iter().map(|v| -v).collect();
87            let inner_res_0 = norm(&v0);
88            if inner_res_0 == 0.0 {
89                return Err(LinalgError::Shape("lgmres: the preconditioner returned a zero vector".into()));
90            }
91            v0.iter_mut().for_each(|v| *v /= inner_res_0);
92            let ptol = ptol_max_factor.min(tol / r_norm);
93            // Flexible GMRES over [Krylov vectors, augmentation vectors].
94            let total = self.inner_m + self.outer.len();
95            let mut vs: Vec<Vec<f64>> = vec![v0.clone()];
96            let mut zs: Vec<Vec<f64>> = Vec::new();
97            let mut h: Vec<Vec<f64>> = Vec::new(); // columns of the Hessenberg matrix
98            let (mut cs, mut sn): (Vec<f64>, Vec<f64>) = (Vec::new(), Vec::new());
99            let mut g = vec![1.0];
100            let mut pres = f64::NAN;
101            let k_outer = self.outer.len();
102            for j in 0..total {
103                let (z, stored) = if self.prepend_outer_v && j < k_outer {
104                    (self.outer[j].0.clone(), self.outer[j].1.clone())
105                } else if self.prepend_outer_v && j == k_outer {
106                    (v0.clone(), None)
107                } else if !self.prepend_outer_v && j >= total - k_outer {
108                    let o = &self.outer[j - (total - k_outer)];
109                    (o.0.clone(), o.1.clone())
110                } else {
111                    (vs[vs.len() - 1].clone(), None)
112                };
113                let mut w = match stored {
114                    Some(w) => w,
115                    None => {
116                        matvecs += 1;
117                        psolve(&a.matvec(&z))
118                    }
119                };
120                let w_norm = norm(&w);
121                // Modified Gram-Schmidt against the basis.
122                let mut col = vec![0.0; j + 2];
123                for (i, v) in vs.iter().enumerate() {
124                    col[i] = dot(v, &w);
125                    w.iter_mut().zip(v).for_each(|(wi, vi)| *wi -= col[i] * vi);
126                }
127                col[j + 1] = norm(&w);
128                // Written to treat a NaN norm as a breakdown, as SciPy does.
129                let breakdown = col[j + 1].partial_cmp(&(f64::EPSILON * w_norm)) != Some(std::cmp::Ordering::Greater);
130                if col[j + 1].is_finite() && col[j + 1] != 0.0 {
131                    let s = col[j + 1];
132                    w.iter_mut().for_each(|wi| *wi /= s);
133                }
134                vs.push(w);
135                zs.push(z);
136                // Givens rotations keep the least-squares problem triangular.
137                for i in 0..j {
138                    let t = cs[i] * col[i] + sn[i] * col[i + 1];
139                    col[i + 1] = -sn[i] * col[i] + cs[i] * col[i + 1];
140                    col[i] = t;
141                }
142                let denom = col[j].hypot(col[j + 1]);
143                let (c, s) = if denom == 0.0 { (1.0, 0.0) } else { (col[j] / denom, col[j + 1] / denom) };
144                cs.push(c);
145                sn.push(s);
146                col[j] = denom;
147                col[j + 1] = 0.0;
148                g.push(-s * g[j]);
149                g[j] *= c;
150                h.push(col);
151                pres = g[j + 1].abs();
152                if pres < ptol || breakdown {
153                    break;
154                }
155            }
156            let k = h.len();
157            let mut y = vec![0.0; k];
158            for i in (0..k).rev() {
159                let s: f64 = (i + 1..k).map(|c| h[c][i] * y[c]).sum();
160                y[i] = (g[i] - s) / h[i][i];
161            }
162            if y.iter().any(|v| !v.is_finite()) {
163                return Ok(IterativeResult { x, iterations: matvecs, converged: false, residual_history: history });
164            }
165            y.iter_mut().for_each(|v| *v *= inner_res_0);
166            ptol_max_factor = if pres > ptol { (1.5 * ptol_max_factor).min(1.0) } else { (0.25 * ptol_max_factor).max(1e-16) };
167            let mut dx = vec![0.0; n];
168            for (z, yc) in zs.iter().zip(&y) {
169                dx.iter_mut().zip(z).for_each(|(d, zi)| *d += yc * zi);
170            }
171            let nx = norm(&dx);
172            if nx > 0.0 {
173                let w = self.store_outer_av.then(|| {
174                    // M A dx = V_{k+1} H y, without a product. The columns hold R = G H after
175                    // the rotations G, so H y = Gᵀ (R y), undoing the rotations in reverse.
176                    let mut q = vec![0.0; k + 1];
177                    for (i, qi) in q.iter_mut().enumerate().take(k) {
178                        *qi = (i..k).map(|c| h[c][i] * y[c]).sum();
179                    }
180                    for i in (0..k).rev() {
181                        let (a0, a1) = (q[i], q[i + 1]);
182                        q[i] = cs[i] * a0 - sn[i] * a1;
183                        q[i + 1] = sn[i] * a0 + cs[i] * a1;
184                    }
185                    let mut ax = vec![0.0; n];
186                    for (v, qc) in vs.iter().zip(&q) {
187                        ax.iter_mut().zip(v).for_each(|(s, vi)| *s += qc * vi);
188                    }
189                    ax.iter().map(|v| v / nx).collect::<Vec<f64>>()
190                });
191                self.outer.push((dx.iter().map(|v| v / nx).collect(), w));
192            }
193            while self.outer.len() > self.outer_k {
194                self.outer.remove(0);
195            }
196            x.iter_mut().zip(&dx).for_each(|(xi, d)| *xi += d);
197        }
198        Ok(IterativeResult { x, iterations: matvecs, converged, residual_history: history })
199    }
200    // ANCHOR_END: lgmres
201}
202
203/// LGMRES with SciPy's defaults (`inner_m = 30`, `outer_k = 3`), from a fresh state.
204/// `options.max_iterations` counts cycles (default 1000).
205pub fn lgmres(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
206    LgmresSolver::default().solve(a, b, x0, m, options)
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use crate::sparse::{CooMatrix, CsrMatrix, spsolve};
213
214    fn convection(m: usize, gamma: f64) -> CsrMatrix {
215        let mut coo = CooMatrix::new(m * m, m * m);
216        for i in 0..m {
217            for j in 0..m {
218                let r = i * m + j;
219                coo.push(r, r, 4.0);
220                for (ok, c, v) in [(i > 0, r.wrapping_sub(m), -1.0 - gamma), (i + 1 < m, r + m, -1.0 + gamma), (j > 0, r.wrapping_sub(1), -1.0 - gamma), (j + 1 < m, r + 1, -1.0 + gamma)] {
221                    if ok {
222                        coo.push(r, c, v);
223                    }
224                }
225            }
226        }
227        coo.to_csr().unwrap()
228    }
229
230    #[test]
231    fn agrees_with_the_direct_solver_and_reuses_its_vectors() {
232        let a = convection(20, 0.7);
233        let b: Vec<f64> = (0..400).map(|k| 1.0 + 0.5 * (0.37 * k as f64).sin()).collect();
234        let exact = spsolve(&a, &b).unwrap();
235        let o = IterativeOptions { rtol: 1e-10, atol: 0.0, max_iterations: None };
236        let r = lgmres(&a, &b, None, None, o).unwrap();
237        assert!(r.converged);
238        assert!(r.x.iter().zip(&exact).all(|(p, q)| (p - q).abs() < 1e-8));
239        // A second solve with the augmentation vectors kept from the first still converges to the
240        // right answer (whether they save work depends on the problem).
241        let b2: Vec<f64> = b.iter().enumerate().map(|(k, v)| v + 1e-3 * (k as f64).cos()).collect();
242        let mut solver = LgmresSolver::default();
243        solver.solve(&a, &b, None, None, o).unwrap();
244        assert_eq!(solver.augmentation_len(), 3);
245        let warm = solver.solve(&a, &b2, None, None, o).unwrap();
246        let exact2 = spsolve(&a, &b2).unwrap();
247        assert!(warm.converged && warm.x.iter().zip(&exact2).all(|(p, q)| (p - q).abs() < 1e-8));
248        assert!(lgmres(&a, &b[..10], None, None, o).is_err());
249    }
250}