Skip to main content

lib_jsl_linalg/sparse/
direct.rs

1//! Direct sparse solvers: a left-looking sparse LU factorisation with partial pivoting
2//! (Gilbert and Peierls), a fill-reducing reverse Cuthill-McKee ordering, and `spsolve`.
3
4use super::amd::minimum_degree;
5use super::formats::{CscMatrix, CsrMatrix};
6use crate::error::{LinalgError, Result};
7use std::cmp::Reverse;
8use std::collections::{BinaryHeap, HashSet, VecDeque};
9
10// ANCHOR: rcm
11/// The reverse Cuthill-McKee ordering of the symmetric pattern of `A + Aᵀ` (SciPy's
12/// `reverse_cuthill_mckee`): a breadth-first search from a vertex of low degree in each
13/// connected component, visiting neighbours by increasing degree, then reversed. It concentrates
14/// the entries near the diagonal (reduces the bandwidth), which limits fill-in during elimination.
15pub fn reverse_cuthill_mckee(a: &CsrMatrix) -> Vec<usize> {
16    let n = a.nrows.max(a.ncols);
17    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
18    for i in 0..a.nrows {
19        for p in a.indptr[i]..a.indptr[i + 1] {
20            let j = a.indices[p];
21            if i != j {
22                adj[i].push(j);
23                adj[j].push(i);
24            }
25        }
26    }
27    for list in adj.iter_mut() {
28        list.sort_unstable();
29        list.dedup();
30    }
31    let degree: Vec<usize> = adj.iter().map(|l| l.len()).collect();
32    let mut visited = vec![false; n];
33    let mut order = Vec::with_capacity(n);
34    let mut by_degree: Vec<usize> = (0..n).collect();
35    by_degree.sort_by_key(|&v| degree[v]);
36    for &start in &by_degree {
37        if visited[start] {
38            continue;
39        }
40        visited[start] = true;
41        let mut queue = VecDeque::from([start]);
42        while let Some(v) = queue.pop_front() {
43            order.push(v);
44            let mut next: Vec<usize> = adj[v].iter().copied().filter(|&w| !visited[w]).collect();
45            next.sort_by_key(|&w| degree[w]);
46            for w in next {
47                visited[w] = true;
48                queue.push_back(w);
49            }
50        }
51    }
52    order.reverse();
53    order
54}
55// ANCHOR_END: rcm
56
57// ANCHOR: minimum_degree_exact
58/// The textbook minimum-degree ordering of the symmetric pattern of `A + Aᵀ`: repeatedly eliminate a vertex of least degree in the elimination graph, where
59/// eliminating a vertex joins all its neighbours into a clique (the fill it would create). Ties go
60/// to the lowest index. This is the textbook algorithm on an explicit graph with a lazily updated
61/// priority queue; AMD and MMD reach similar orderings faster with quotient graphs,
62/// supervariables and approximate degrees.
63pub fn minimum_degree_exact(a: &CsrMatrix) -> Vec<usize> {
64    let n = a.nrows.max(a.ncols);
65    let mut adj: Vec<HashSet<usize>> = vec![HashSet::new(); n];
66    for i in 0..a.nrows {
67        for p in a.indptr[i]..a.indptr[i + 1] {
68            let j = a.indices[p];
69            if i != j {
70                adj[i].insert(j);
71                adj[j].insert(i);
72            }
73        }
74    }
75    minimum_degree_graph(adj)
76}
77
78/// Minimum degree on an explicit undirected graph given by adjacency sets.
79pub(super) fn minimum_degree_graph(mut adj: Vec<HashSet<usize>>) -> Vec<usize> {
80    let n = adj.len();
81    let mut heap: BinaryHeap<Reverse<(usize, usize)>> = (0..n).map(|v| Reverse((adj[v].len(), v))).collect();
82    let mut eliminated = vec![false; n];
83    let mut order = Vec::with_capacity(n);
84    while let Some(Reverse((d, v))) = heap.pop() {
85        if eliminated[v] || adj[v].len() != d {
86            continue; // a stale entry
87        }
88        eliminated[v] = true;
89        order.push(v);
90        let mut nbrs: Vec<usize> = adj[v].drain().collect();
91        nbrs.sort_unstable();
92        for &u in &nbrs {
93            adj[u].remove(&v);
94        }
95        for (x, &u) in nbrs.iter().enumerate() {
96            for &w in &nbrs[x + 1..] {
97                adj[u].insert(w);
98                adj[w].insert(u);
99            }
100        }
101        for &u in &nbrs {
102            heap.push(Reverse((adj[u].len(), u)));
103        }
104    }
105    order
106}
107// ANCHOR_END: minimum_degree_exact
108
109/// The bandwidth `max |i − j|` over the stored entries of `A` with rows and columns permuted by
110/// `perm` (`perm[k]` is the original index placed at position `k`).
111pub fn bandwidth(a: &CsrMatrix, perm: Option<&[usize]>) -> usize {
112    let n = a.nrows;
113    let mut pos: Vec<usize> = (0..n).collect();
114    if let Some(p) = perm {
115        for (k, &v) in p.iter().enumerate() {
116            pos[v] = k;
117        }
118    }
119    let mut b = 0;
120    for i in 0..n {
121        for p in a.indptr[i]..a.indptr[i + 1] {
122            b = b.max(pos[i].abs_diff(pos[a.indices[p]]));
123        }
124    }
125    b
126}
127
128/// Column orderings for [`SparseLu`].
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum Ordering {
131    /// The columns in their natural order.
132    Natural,
133    /// Reverse Cuthill-McKee on the pattern of `A + Aᵀ`.
134    ReverseCuthillMcKee,
135    /// Minimum degree on the pattern of `A + Aᵀ` (the default of [`spsolve`]).
136    MinimumDegree,
137}
138
139/// A sparse LU factorisation `P A Q = L U` (SciPy's `splu`, with its own algorithm).
140#[derive(Clone, Debug)]
141pub struct SparseLu {
142    n: usize,
143    /// Column `k` of L: (original row, value), the unit diagonal stored first.
144    l: Vec<Vec<(usize, f64)>>,
145    /// Column `k` of U: (step, value), the diagonal last.
146    u: Vec<Vec<(usize, f64)>>,
147    /// The original row pivoted at each step.
148    pivot_row: Vec<usize>,
149    /// The column order.
150    q: Vec<usize>,
151}
152
153// ANCHOR: splu
154impl SparseLu {
155    /// Factorises a square sparse matrix column by column (left-looking): each column of `A Q` is
156    /// solved against the columns of `L` found so far, visiting only the rows its pattern can
157    /// reach in the graph of `L` (found by a depth-first search, which also gives a valid order),
158    /// and the largest remaining entry becomes the pivot.
159    pub fn factor(a: &CsrMatrix, ordering: Ordering) -> Result<SparseLu> {
160        let n = a.nrows;
161        if a.ncols != n {
162            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
163        }
164        let q = match ordering {
165            Ordering::Natural => (0..n).collect(),
166            Ordering::ReverseCuthillMcKee => reverse_cuthill_mckee(a),
167            Ordering::MinimumDegree => minimum_degree(a),
168        };
169        SparseLu::factor_with_order(a, &q)
170    }
171
172    /// As [`SparseLu::factor`], with the column order given explicitly: `q[k]` is the original
173    /// column eliminated at step `k`. This takes the orderings that are separate functions,
174    /// [`colamd`](super::colamd) and [`nested_dissection`](super::nested_dissection), or any other
175    /// permutation.
176    pub fn factor_with_order(a: &CsrMatrix, q: &[usize]) -> Result<SparseLu> {
177        let n = a.nrows;
178        if a.ncols != n {
179            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
180        }
181        let mut seen = vec![false; n];
182        if q.len() != n || q.iter().any(|&c| c >= n || std::mem::replace(&mut seen[c], true)) {
183            return Err(LinalgError::Shape(format!("the column order must be a permutation of 0..{n}")));
184        }
185        let q = q.to_vec();
186        let csc: CscMatrix = a.to_csc();
187        let scale = a.data.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE);
188        let mut l: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
189        let mut u: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
190        let mut pinv: Vec<Option<usize>> = vec![None; n];
191        let mut pivot_row = Vec::with_capacity(n);
192        let mut x = vec![0.0; n];
193        let mut mark = vec![usize::MAX; n];
194        for (k, &col) in q.iter().enumerate() {
195            // Depth-first search for the reach of the column's pattern in the graph of L.
196            let mut topo: Vec<usize> = Vec::new();
197            let mut stack: Vec<(usize, usize)> = Vec::new();
198            for p in csc.indptr[col]..csc.indptr[col + 1] {
199                let r = csc.indices[p];
200                if mark[r] == k {
201                    continue;
202                }
203                mark[r] = k;
204                stack.push((r, 0));
205                while let Some((v, child)) = stack.pop() {
206                    let children = pinv[v].map(|j| &l[j][1..]);
207                    match children.and_then(|c| c.get(child)) {
208                        Some(&(w, _)) => {
209                            stack.push((v, child + 1));
210                            if mark[w] != k {
211                                mark[w] = k;
212                                stack.push((w, 0));
213                            }
214                        }
215                        None => topo.push(v),
216                    }
217                }
218            }
219            for p in csc.indptr[col]..csc.indptr[col + 1] {
220                x[csc.indices[p]] = csc.data[p];
221            }
222            // Sparse triangular solve in reverse postorder.
223            for &r in topo.iter().rev() {
224                if let Some(j) = pinv[r] {
225                    let ujk = x[r];
226                    for &(i, lij) in &l[j][1..] {
227                        x[i] -= lij * ujk;
228                    }
229                }
230            }
231            // Split into U (pivoted rows) and the candidates for L.
232            let mut ucol = Vec::new();
233            let mut best: Option<(usize, f64)> = None;
234            for &r in &topo {
235                match pinv[r] {
236                    Some(j) => {
237                        if x[r] != 0.0 {
238                            ucol.push((j, x[r]));
239                        }
240                    }
241                    None => {
242                        if best.is_none_or(|(_, v)| x[r].abs() > v.abs()) {
243                            best = Some((r, x[r]));
244                        }
245                    }
246                }
247            }
248            let Some((piv, d)) = best.filter(|(_, v)| v.abs() > f64::EPSILON * scale * 1e-3) else {
249                return Err(LinalgError::Singular(k));
250            };
251            if d == 0.0 {
252                return Err(LinalgError::Singular(k));
253            }
254            ucol.sort_by_key(|e| e.0);
255            ucol.push((k, d));
256            let mut lcol = vec![(piv, 1.0)];
257            for &r in &topo {
258                if pinv[r].is_none() && r != piv && x[r] != 0.0 {
259                    lcol.push((r, x[r] / d));
260                }
261            }
262            for &r in &topo {
263                x[r] = 0.0;
264            }
265            pinv[piv] = Some(k);
266            pivot_row.push(piv);
267            l.push(lcol);
268            u.push(ucol);
269        }
270        Ok(SparseLu { n, l, u, pivot_row, q })
271    }
272
273    // ANCHOR: refactor
274    /// The factorisation of a matrix `a` with the same sparsity pattern as the one factored to make
275    /// `self` but new values (the Newton matrices of an ODE solver, the Jacobians of a nonlinear
276    /// solve), keeping the column order, the pivot rows and the structure of `L` and `U`: no
277    /// search for the reach of each column, only the numerical updates. Where a pivot is smaller
278    /// than a tenth of the largest candidate in its column (the pivot sequence is no longer a good
279    /// one), or an update would land outside the stored structure, the result is
280    /// [`LinalgError::Singular`] and the caller factors from scratch with
281    /// [`SparseLu::factor_with_order`].
282    pub fn refactor(&self, a: &CsrMatrix) -> Result<SparseLu> {
283        let n = self.n;
284        if a.nrows != n || a.ncols != n {
285            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
286        }
287        let csc: CscMatrix = a.to_csc();
288        let mut out = self.clone();
289        let mut x = vec![0.0; n];
290        let mut mark = vec![usize::MAX; n];
291        for k in 0..n {
292            let col = self.q[k];
293            // The rows this column may touch: those of U (as pivot rows), the pivot, and L.
294            let (u_col, l_col) = (&self.u[k], &self.l[k]);
295            for &(j, _) in &u_col[..u_col.len() - 1] {
296                mark[self.pivot_row[j]] = k;
297            }
298            for &(i, _) in l_col {
299                mark[i] = k;
300            }
301            for p in csc.indptr[col]..csc.indptr[col + 1] {
302                let r = csc.indices[p];
303                if mark[r] != k {
304                    return Err(LinalgError::Singular(k));
305                }
306                x[r] = csc.data[p];
307            }
308            // U's entries in increasing step order: the triangular solve against the earlier columns.
309            for e in 0..u_col.len() - 1 {
310                let j = u_col[e].0;
311                let ujk = x[self.pivot_row[j]];
312                out.u[k][e].1 = ujk;
313                for &(i, lij) in &out.l[j][1..] {
314                    if mark[i] != k {
315                        return Err(LinalgError::Singular(k));
316                    }
317                    x[i] -= lij * ujk;
318                }
319            }
320            let piv = l_col[0].0;
321            let d = x[piv];
322            let biggest = l_col.iter().map(|&(i, _)| x[i].abs()).fold(0.0, f64::max);
323            if d == 0.0 || d.is_nan() || d.abs() < 0.1 * biggest {
324                return Err(LinalgError::Singular(k));
325            }
326            *out.u[k].last_mut().expect("diagonal") = (k, d);
327            for (e, &(i, _)) in l_col.iter().enumerate().skip(1) {
328                out.l[k][e].1 = x[i] / d;
329            }
330            for &(j, _) in &u_col[..u_col.len() - 1] {
331                x[self.pivot_row[j]] = 0.0;
332            }
333            for &(i, _) in l_col {
334                x[i] = 0.0;
335            }
336        }
337        Ok(out)
338    }
339    // ANCHOR_END: refactor
340
341    /// Solves `A x = b`.
342    pub fn solve(&self, b: &[f64]) -> Result<Vec<f64>> {
343        if b.len() != self.n {
344            return Err(LinalgError::Shape(format!("right-hand side of length {}, expected {}", b.len(), self.n)));
345        }
346        // Forward: L y = P b, in step order.
347        let mut w = b.to_vec();
348        let mut y = vec![0.0; self.n];
349        for j in 0..self.n {
350            let yj = w[self.pivot_row[j]];
351            y[j] = yj;
352            for &(i, lij) in &self.l[j][1..] {
353                w[i] -= lij * yj;
354            }
355        }
356        // Backward: U z = y.
357        for j in (0..self.n).rev() {
358            let (_, ujj) = *self.u[j].last().expect("diagonal");
359            let zj = y[j] / ujj;
360            y[j] = zj;
361            for &(i, uij) in &self.u[j][..self.u[j].len() - 1] {
362                y[i] -= uij * zj;
363            }
364        }
365        let mut x = vec![0.0; self.n];
366        for (k, &col) in self.q.iter().enumerate() {
367            x[col] = y[k];
368        }
369        Ok(x)
370    }
371
372    /// The floating-point operations of the factorisation: for each pivot, one division per entry
373    /// below it and a multiply and an add per entry of its rank-one update, so
374    /// `ℓₖ + 2 ℓₖ uₖ` with `ℓₖ` the entries of `L` below the pivot and `uₖ` those of `U` to its
375    /// right. A measure of the cost an ordering leads to, independent of the machine.
376    pub fn flops(&self) -> f64 {
377        let n = self.n;
378        // The number of entries of row k of U (right of the diagonal), from the columns of U.
379        let mut right = vec![0usize; n];
380        for col in &self.u {
381            for &(i, _) in &col[..col.len() - 1] {
382                right[i] += 1;
383            }
384        }
385        (0..n).map(|k| 2.0 * (self.l[k].len() - 1) as f64 * right[k] as f64 + (self.l[k].len() - 1) as f64).sum()
386    }
387
388    /// The number of stored entries of `L` and `U` together (the fill).
389    pub fn nnz(&self) -> usize {
390        self.l.iter().map(|c| c.len()).sum::<usize>() + self.u.iter().map(|c| c.len()).sum::<usize>()
391    }
392}
393// ANCHOR_END: splu
394
395/// Solves the sparse system `A x = b` (SciPy's `spsolve`) by a sparse LU factorisation with the
396/// minimum-degree column ordering.
397pub fn spsolve(a: &CsrMatrix, b: &[f64]) -> Result<Vec<f64>> {
398    SparseLu::factor(a, Ordering::MinimumDegree)?.solve(b)
399}