Skip to main content

lib_jsl_linalg/sparse/
ichol.rs

1//! Incomplete Cholesky factorisations `A ≈ L Lᵀ` of symmetric positive definite matrices as
2//! preconditioners for conjugate gradients: IC(0), which keeps the sparsity pattern of the lower
3//! triangle of `A`, and a threshold version (ICT) that drops small entries and caps the fill per
4//! row. SciPy has no incomplete Cholesky; the algorithms are those of PETSc and scikit-sparse.
5
6use super::formats::CsrMatrix;
7use super::iterative::LinearOperator;
8use crate::error::{LinalgError, Result};
9use std::collections::BTreeMap;
10
11/// An incomplete Cholesky factorisation `A + α diag(A) ≈ L Lᵀ`, with `L` lower triangular.
12#[derive(Clone, Debug)]
13pub struct IncompleteCholesky {
14    n: usize,
15    /// Row `i` of `L` left of the diagonal: `(column, value)`, by increasing column.
16    rows: Vec<Vec<(usize, f64)>>,
17    /// The diagonal of `L`.
18    diag: Vec<f64>,
19    shift: f64,
20    /// The ordering the matrix was permuted by before factoring: `order[k]` is the original index
21    /// at position `k`.
22    order: Option<Vec<usize>>,
23}
24
25/// The ordering applied before an incomplete factorisation: the factor of `P A Pᵀ` is a different
26/// (and often better) preconditioner than that of `A`.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum IcOrdering {
30    /// The matrix as given.
31    Natural,
32    /// Reverse Cuthill-McKee: a small bandwidth.
33    ReverseCuthillMcKee,
34    /// Minimum degree (approximate): little fill, which makes IC(k) and ICT keep more of what
35    /// matters.
36    MinimumDegree,
37}
38
39#[derive(Clone, Copy)]
40enum Mode {
41    /// Updates outside the pattern of `A` are discarded.
42    Pattern,
43    /// Entries below `tau ‖aᵢ‖₂` are dropped, and each row keeps its `max_fill` largest.
44    Threshold { drop_tol: f64, max_fill: usize },
45}
46
47impl IncompleteCholesky {
48    // ANCHOR: ic0
49    /// IC(0): the factor has exactly the sparsity pattern of the lower triangle of `A`. If a pivot
50    /// turns out non-positive, which can happen even for an SPD matrix, the factorisation is
51    /// restarted with the diagonal increased to `(1 + α) diag(A)` for a growing `α` (Manteuffel's
52    /// shift); the shift used is reported by [`IncompleteCholesky::shift`].
53    pub fn ic0(a: &CsrMatrix) -> Result<IncompleteCholesky> {
54        Self::with_shifts(a, Mode::Pattern)
55    }
56    // ANCHOR_END: ic0
57
58    /// IC(0) with a given shift `α ≥ 0` and no retry: fails with
59    /// [`LinalgError::NotPositiveDefinite`] if a pivot is not positive.
60    pub fn ic0_shifted(a: &CsrMatrix, shift: f64) -> Result<IncompleteCholesky> {
61        factor(a, Mode::Pattern, shift)
62    }
63
64    // ANCHOR: icholk
65    /// IC(k): the factor keeps the entries whose *level of fill* is at most `level`. Entries of `A`
66    /// have level 0, and an entry created by eliminating column `j` from entries of levels `a` and
67    /// `b` has level `a + b + 1`; IC(0) is [`IncompleteCholesky::ic0`], and a large `level` gives the
68    /// exact factor. With `modified`, every update that is dropped is subtracted from the two
69    /// diagonal entries it would have changed (MIC, Gustafsson 1978), so that `L Lᵀ` has the row
70    /// sums of `A` (up to the shift): this improves the condition number of the preconditioned
71    /// system of a Laplacian-like matrix from `O(h⁻²)` to `O(h⁻¹)`. The elimination is
72    /// right-looking, because the compensation changes diagonals that are not yet used.
73    /// A failing pivot restarts with a shift, as for [`IncompleteCholesky::ic0`].
74    pub fn ic_k(a: &CsrMatrix, level: usize, modified: bool) -> Result<IncompleteCholesky> {
75        let pattern = level_pattern(a, level)?;
76        let mut shift = 0.0;
77        loop {
78            match factor_right_looking(a, &pattern, modified, shift) {
79                Err(LinalgError::NotPositiveDefinite(_)) if shift < 1e3 => shift = if shift == 0.0 { 1e-3 } else { shift * 2.0 },
80                other => return other,
81            }
82        }
83    }
84    // ANCHOR_END: icholk
85
86    /// The threshold version, ICT(τ, p): fill is allowed, but every entry of row `i` smaller than
87    /// `τ ‖aᵢ‖₂` is dropped, and only the `p` largest entries of each row are kept (the diagonal
88    /// always). With `τ = 0` and a large `p` it is the exact Cholesky factor.
89    pub fn ict(a: &CsrMatrix, drop_tol: f64, max_fill: usize) -> Result<IncompleteCholesky> {
90        Self::with_shifts(a, Mode::Threshold { drop_tol, max_fill })
91    }
92
93    fn with_shifts(a: &CsrMatrix, mode: Mode) -> Result<IncompleteCholesky> {
94        let mut shift = 0.0;
95        loop {
96            match factor(a, mode, shift) {
97                Err(LinalgError::NotPositiveDefinite(_)) if shift < 1e3 => shift = if shift == 0.0 { 1e-3 } else { shift * 2.0 },
98                other => return other,
99            }
100        }
101    }
102
103    // ANCHOR: ic_ordered
104    /// The factorisation of `P A Pᵀ` for the ordering `P` chosen by `ordering`, with `factor` (for
105    /// example `|m| IncompleteCholesky::ic_k(m, 1, false)`); [`IncompleteCholesky::solve`] applies
106    /// the permutation, so the result is used exactly like an unordered factor. Ordering helps
107    /// ICT and IC(k) most; IC(0) keeps the pattern of `A`, which an ordering changes.
108    pub fn ordered(a: &CsrMatrix, ordering: IcOrdering, factor: impl FnOnce(&CsrMatrix) -> Result<IncompleteCholesky>) -> Result<IncompleteCholesky> {
109        let order = match ordering {
110            IcOrdering::Natural => return factor(a),
111            IcOrdering::ReverseCuthillMcKee => super::direct::reverse_cuthill_mckee(a),
112            IcOrdering::MinimumDegree => super::amd::minimum_degree(a),
113        };
114        let n = a.nrows;
115        if a.ncols != n || order.len() != n {
116            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
117        }
118        let mut position = vec![0usize; n];
119        for (k, &o) in order.iter().enumerate() {
120            position[o] = k;
121        }
122        let (mut rows, mut cols, mut vals) = (Vec::with_capacity(a.nnz()), Vec::with_capacity(a.nnz()), Vec::with_capacity(a.nnz()));
123        for i in 0..n {
124            for p in a.indptr[i]..a.indptr[i + 1] {
125                rows.push(position[i]);
126                cols.push(position[a.indices[p]]);
127                vals.push(a.data[p]);
128            }
129        }
130        let permuted = CsrMatrix::from_triplets(n, n, &rows, &cols, &vals)?;
131        let mut ic = factor(&permuted)?;
132        ic.order = Some(order);
133        Ok(ic)
134    }
135    // ANCHOR_END: ic_ordered
136
137    /// Solves `L Lᵀ x = b` by forward and back substitution (with the permutation, if the factor was
138    /// made by [`IncompleteCholesky::ordered`]).
139    pub fn solve(&self, b: &[f64]) -> Vec<f64> {
140        match &self.order {
141            None => self.solve_natural(b),
142            Some(order) => {
143                let permuted: Vec<f64> = order.iter().map(|&o| b[o]).collect();
144                let z = self.solve_natural(&permuted);
145                let mut x = vec![0.0; b.len()];
146                for (k, &o) in order.iter().enumerate() {
147                    x[o] = z[k];
148                }
149                x
150            }
151        }
152    }
153
154    fn solve_natural(&self, b: &[f64]) -> Vec<f64> {
155        let mut x = b.to_vec();
156        for i in 0..self.n {
157            let s: f64 = self.rows[i].iter().map(|&(j, v)| v * x[j]).sum();
158            x[i] = (x[i] - s) / self.diag[i];
159        }
160        for i in (0..self.n).rev() {
161            x[i] /= self.diag[i];
162            let xi = x[i];
163            for &(j, v) in &self.rows[i] {
164                x[j] -= v * xi;
165            }
166        }
167        x
168    }
169
170    /// The stored entries of `L`, diagonal included.
171    pub fn nnz(&self) -> usize {
172        self.n + self.rows.iter().map(Vec::len).sum::<usize>()
173    }
174
175    /// The diagonal shift `α` of the factorised matrix `A + α diag(A)`.
176    pub fn shift(&self) -> f64 {
177        self.shift
178    }
179}
180
181/// The strictly lower pattern of IC(k): `pattern[j]` lists the rows `i > j` of column `j`.
182fn level_pattern(a: &CsrMatrix, level: usize) -> Result<Vec<Vec<usize>>> {
183    let n = a.nrows;
184    if a.ncols != n {
185        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
186    }
187    // Column j of the finished rows: row -> level. Row i meets column j through its entry (i, j):
188    // eliminating j combines it with every (m, j), j < m < i, into a possible entry (i, m).
189    let mut cols_lev: Vec<BTreeMap<usize, usize>> = vec![BTreeMap::new(); n];
190    for i in 0..n {
191        let mut r: BTreeMap<usize, usize> = (a.indptr[i]..a.indptr[i + 1]).map(|p| a.indices[p]).filter(|&j| j < i).map(|j| (j, 0)).collect();
192        let mut next = 0;
193        while let Some((&j, &lij)) = r.range(next..i).next() {
194            next = j + 1;
195            for (&m, &lmj) in &cols_lev[j] {
196                let lev = lij + lmj + 1;
197                if lev <= level {
198                    let e = r.entry(m).or_insert(lev);
199                    *e = (*e).min(lev);
200                }
201            }
202        }
203        for (&j, &lev) in &r {
204            cols_lev[j].insert(i, lev);
205        }
206    }
207    let cols: Vec<Vec<usize>> = cols_lev.into_iter().map(|c| c.into_keys().collect()).collect();
208    Ok(cols)
209}
210
211/// Right-looking IC on a given pattern, with optional diagonal compensation of the dropped updates.
212fn factor_right_looking(a: &CsrMatrix, pattern: &[Vec<usize>], modified: bool, shift: f64) -> Result<IncompleteCholesky> {
213    let n = a.nrows;
214    let mut diag = vec![0.0; n];
215    let mut cols: Vec<BTreeMap<usize, f64>> = pattern.iter().map(|rows| rows.iter().map(|&i| (i, 0.0)).collect()).collect();
216    for i in 0..n {
217        for p in a.indptr[i]..a.indptr[i + 1] {
218            let (j, v) = (a.indices[p], a.data[p]);
219            if j == i {
220                diag[i] += v;
221            } else if j < i {
222                *cols[j].get_mut(&i).expect("the pattern contains the pattern of A") += v;
223            }
224        }
225        diag[i] *= 1.0 + shift;
226    }
227    let mut factored: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
228    let mut l_diag = vec![0.0; n];
229    for k in 0..n {
230        let d = diag[k];
231        if d <= 0.0 || !d.is_finite() {
232            return Err(LinalgError::NotPositiveDefinite(k));
233        }
234        let dk = d.sqrt();
235        l_diag[k] = dk;
236        let col: Vec<(usize, f64)> = std::mem::take(&mut cols[k]).into_iter().map(|(i, v)| (i, v / dk)).collect();
237        for (x, &(i, lik)) in col.iter().enumerate() {
238            diag[i] -= lik * lik;
239            for &(j, ljk) in &col[..x] {
240                // The update of entry (i, j), i > j, of the trailing matrix.
241                let upd = lik * ljk;
242                match cols[j].get_mut(&i) {
243                    Some(v) => *v -= upd,
244                    None if modified => {
245                        diag[i] -= upd;
246                        diag[j] -= upd;
247                    }
248                    None => {}
249                }
250            }
251        }
252        factored.push(col);
253    }
254    let mut rows: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
255    for (j, col) in factored.iter().enumerate() {
256        for &(i, v) in col {
257            rows[i].push((j, v));
258        }
259    }
260    Ok(IncompleteCholesky { n, rows, diag: l_diag, shift, order: None })
261}
262
263// ANCHOR: ic_factor
264/// The up-looking factorisation: row `i` of `L` solves `L₀ ℓᵢ = aᵢ` against the rows computed so
265/// far. Working left to right, each entry `ℓᵢⱼ = wⱼ / ℓⱼⱼ` is final once the contributions of the
266/// earlier entries have been subtracted, and then updates the entries to its right through column
267/// `j` of `L`.
268fn factor(a: &CsrMatrix, mode: Mode, shift: f64) -> Result<IncompleteCholesky> {
269    let n = a.nrows;
270    if a.ncols != n {
271        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
272    }
273    let mut rows: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
274    let mut diag: Vec<f64> = Vec::with_capacity(n);
275    // Column j of L below the diagonal, for the rows finished so far: (row, value).
276    let mut cols: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
277    for i in 0..n {
278        let mut w: BTreeMap<usize, f64> = BTreeMap::new();
279        let mut aii = 0.0;
280        let mut norm = 0.0;
281        for p in a.indptr[i]..a.indptr[i + 1] {
282            let (j, v) = (a.indices[p], a.data[p]);
283            norm += v * v;
284            if j < i {
285                *w.entry(j).or_insert(0.0) += v;
286            } else if j == i {
287                aii += v;
288            }
289        }
290        let (tau, max_fill) = match mode {
291            Mode::Pattern => (0.0, usize::MAX),
292            Mode::Threshold { drop_tol, max_fill } => (drop_tol * norm.sqrt(), max_fill),
293        };
294        let mut sum_sq = 0.0;
295        let mut kept: Vec<(usize, f64)> = Vec::new();
296        let mut next = 0;
297        while let Some((&j, &wj)) = w.range(next..i).next() {
298            next = j + 1;
299            let lij = wj / diag[j];
300            if matches!(mode, Mode::Threshold { .. }) && lij.abs() < tau {
301                w.remove(&j);
302                continue;
303            }
304            w.insert(j, lij);
305            for &(m, lmj) in &cols[j] {
306                match mode {
307                    Mode::Pattern => {
308                        if let Some(x) = w.get_mut(&m) {
309                            *x -= lij * lmj;
310                        }
311                    }
312                    Mode::Threshold { .. } => *w.entry(m).or_insert(0.0) -= lij * lmj,
313                }
314            }
315        }
316        let mut entries: Vec<(usize, f64)> = w.into_iter().filter(|&(_, v)| v != 0.0).collect();
317        if entries.len() > max_fill {
318            entries.sort_by(|x, y| y.1.abs().total_cmp(&x.1.abs()));
319            entries.truncate(max_fill);
320            entries.sort_by_key(|e| e.0);
321        }
322        for &(j, v) in &entries {
323            sum_sq += v * v;
324            kept.push((j, v));
325        }
326        let d = aii * (1.0 + shift) - sum_sq;
327        if d <= 1e-14 * aii.abs() || d <= 0.0 || !d.is_finite() {
328            return Err(LinalgError::NotPositiveDefinite(i));
329        }
330        let dii = d.sqrt();
331        for &(j, v) in &kept {
332            cols[j].push((i, v));
333        }
334        rows.push(kept);
335        diag.push(dii);
336    }
337    Ok(IncompleteCholesky { n, rows, diag, shift, order: None })
338}
339// ANCHOR_END: ic_factor
340
341/// As a preconditioner, `M = (L Lᵀ)⁻¹`.
342impl LinearOperator for IncompleteCholesky {
343    fn shape(&self) -> (usize, usize) {
344        (self.n, self.n)
345    }
346    fn matvec(&self, x: &[f64]) -> Vec<f64> {
347        self.solve(x)
348    }
349    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
350        self.solve(x)
351    }
352}