Skip to main content

lib_jsl_linalg/sparse/
ilu.rs

1//! Incomplete LU factorisations as preconditioners for the Krylov solvers: ILU(0), which keeps the
2//! sparsity pattern of `A`, and Saad's ILUT, which drops small entries and keeps the largest few
3//! per row (the role of SciPy's `spilu`, which uses SuperLU's own threshold ILU).
4
5use super::formats::CsrMatrix;
6use super::iterative::LinearOperator;
7use crate::error::{LinalgError, Result};
8use std::collections::BTreeMap;
9
10/// An incomplete factorisation `A ≈ L U`, with `L` unit lower triangular (the unit diagonal not
11/// stored) and `U` upper triangular, both by rows.
12#[derive(Clone, Debug)]
13pub struct Ilu {
14    n: usize,
15    /// Row `i` of `L`: `(column < i, value)`.
16    l: Vec<Vec<(usize, f64)>>,
17    /// Row `i` of `U`: the diagonal first, then `(column > i, value)`.
18    u: Vec<Vec<(usize, f64)>>,
19}
20
21fn check_square(a: &CsrMatrix) -> Result<usize> {
22    if a.nrows != a.ncols {
23        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
24    }
25    Ok(a.nrows)
26}
27
28/// Replaces a zero (or tiny) pivot by a small multiple of the row norm, as is usual for
29/// incomplete factorisations, which have no pivoting to fall back on.
30fn safe_pivot(d: f64, row_norm: f64) -> f64 {
31    let floor = 1e-8 * row_norm.max(f64::MIN_POSITIVE);
32    if d.abs() < floor { if d < 0.0 { -floor } else { floor } } else { d }
33}
34
35impl Ilu {
36    // ANCHOR: ilu0
37    /// ILU(0): Gaussian elimination row by row (the IKJ variant) in which every update that would
38    /// fall outside the sparsity pattern of `A` is discarded, so `L + U` has exactly the pattern
39    /// of `A`.
40    pub fn ilu0(a: &CsrMatrix) -> Result<Ilu> {
41        let n = check_square(a)?;
42        let mut l: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
43        let mut u: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
44        let mut pos = vec![usize::MAX; n];
45        for i in 0..n {
46            let cols = &a.indices[a.indptr[i]..a.indptr[i + 1]];
47            let mut w: Vec<f64> = a.data[a.indptr[i]..a.indptr[i + 1]].to_vec();
48            for (p, &j) in cols.iter().enumerate() {
49                pos[j] = p;
50            }
51            let norm = w.iter().map(|v| v * v).sum::<f64>().sqrt();
52            for p in 0..cols.len() {
53                let k = cols[p];
54                if k >= i {
55                    break;
56                }
57                let lik = w[p] / u[k][0].1;
58                w[p] = lik;
59                for &(j, ukj) in &u[k][1..] {
60                    if pos[j] != usize::MAX {
61                        w[pos[j]] -= lik * ukj;
62                    }
63                }
64            }
65            let mut li = Vec::new();
66            let mut ui = vec![(i, 0.0)];
67            for (p, &j) in cols.iter().enumerate() {
68                match j.cmp(&i) {
69                    std::cmp::Ordering::Less => li.push((j, w[p])),
70                    std::cmp::Ordering::Equal => ui[0].1 = w[p],
71                    std::cmp::Ordering::Greater => ui.push((j, w[p])),
72                }
73                pos[j] = usize::MAX;
74            }
75            ui[0].1 = safe_pivot(ui[0].1, norm);
76            l.push(li);
77            u.push(ui);
78        }
79        Ok(Ilu { n, l, u })
80    }
81    // ANCHOR_END: ilu0
82
83    // ANCHOR: ilut
84    /// Saad's ILUT(τ, p): eliminate row by row with fill allowed, but drop every multiplier and
85    /// every entry of the new row smaller than `τ ‖aᵢ‖₂`, and keep only the `p` largest entries of
86    /// each of the `L` and `U` parts of the row (the diagonal is always kept).
87    pub fn ilut(a: &CsrMatrix, drop_tol: f64, max_fill: usize) -> Result<Ilu> {
88        let n = check_square(a)?;
89        let mut l: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
90        let mut u: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
91        for i in 0..n {
92            let mut w: BTreeMap<usize, f64> = BTreeMap::new();
93            for p in a.indptr[i]..a.indptr[i + 1] {
94                *w.entry(a.indices[p]).or_insert(0.0) += a.data[p];
95            }
96            let norm = w.values().map(|v| v * v).sum::<f64>().sqrt();
97            let tau = drop_tol * norm;
98            // Eliminate the entries left of the diagonal in increasing column order; fill created
99            // by an update is always to the right of the column being eliminated.
100            let mut next = 0;
101            while let Some((&k, &wk)) = w.range(next..i).next() {
102                next = k + 1;
103                let lik = wk / u[k][0].1;
104                if lik.abs() < tau {
105                    w.remove(&k);
106                    continue;
107                }
108                w.insert(k, lik);
109                for &(j, ukj) in &u[k][1..] {
110                    *w.entry(j).or_insert(0.0) -= lik * ukj;
111                }
112            }
113            let diag = w.remove(&i).unwrap_or(0.0);
114            let keep = |entries: Vec<(usize, f64)>| -> Vec<(usize, f64)> {
115                let mut e: Vec<(usize, f64)> = entries.into_iter().filter(|(_, v)| v.abs() >= tau && *v != 0.0).collect();
116                if e.len() > max_fill {
117                    e.sort_by(|x, y| y.1.abs().total_cmp(&x.1.abs()));
118                    e.truncate(max_fill);
119                }
120                e.sort_by_key(|x| x.0);
121                e
122            };
123            let li = keep(w.range(..i).map(|(&j, &v)| (j, v)).collect());
124            let mut ui = vec![(i, safe_pivot(diag, norm))];
125            ui.extend(keep(w.range(i + 1..).map(|(&j, &v)| (j, v)).collect()));
126            l.push(li);
127            u.push(ui);
128        }
129        Ok(Ilu { n, l, u })
130    }
131    // ANCHOR_END: ilut
132
133    /// Solves `L U x = b` by forward and back substitution.
134    pub fn solve(&self, b: &[f64]) -> Vec<f64> {
135        let mut x = b.to_vec();
136        for i in 0..self.n {
137            let s: f64 = self.l[i].iter().map(|&(j, v)| v * x[j]).sum();
138            x[i] -= s;
139        }
140        for i in (0..self.n).rev() {
141            let s: f64 = self.u[i][1..].iter().map(|&(j, v)| v * x[j]).sum();
142            x[i] = (x[i] - s) / self.u[i][0].1;
143        }
144        x
145    }
146
147    /// Solves `(L U)ᵀ x = b`.
148    pub fn solve_transpose(&self, b: &[f64]) -> Vec<f64> {
149        let mut x = b.to_vec();
150        for i in 0..self.n {
151            x[i] /= self.u[i][0].1;
152            let xi = x[i];
153            for &(j, v) in &self.u[i][1..] {
154                x[j] -= v * xi;
155            }
156        }
157        for i in (0..self.n).rev() {
158            let xi = x[i];
159            for &(j, v) in &self.l[i] {
160                x[j] -= v * xi;
161            }
162        }
163        x
164    }
165
166    /// The stored entries of `L` and `U` (the unit diagonal of `L` not counted).
167    pub fn nnz(&self) -> usize {
168        self.l.iter().map(Vec::len).sum::<usize>() + self.u.iter().map(Vec::len).sum::<usize>()
169    }
170}
171
172/// As a preconditioner, `M = (L U)⁻¹`.
173impl LinearOperator for Ilu {
174    fn shape(&self) -> (usize, usize) {
175        (self.n, self.n)
176    }
177    fn matvec(&self, x: &[f64]) -> Vec<f64> {
178        self.solve(x)
179    }
180    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
181        self.solve_transpose(x)
182    }
183}