Skip to main content

lib_jsl_linalg/sparse/
colamd.rs

1//! Column approximate minimum degree ordering (Davis, Gilbert, Larimore and Ng, 2004), the default
2//! column ordering of SciPy's `splu`. Unlike minimum degree on `A + Aᵀ` it works on the pattern of
3//! `AᵀA` without forming it, so it suits unsymmetric and rectangular matrices.
4
5use super::formats::CsrMatrix;
6use std::cmp::Reverse;
7use std::collections::{BTreeMap, BinaryHeap};
8
9// ANCHOR: colamd
10/// A column ordering of `A` that approximately minimises the fill of the Cholesky factor of
11/// `AᵀA`, and so bounds the fill of the LU factors of `A Q` under any row pivoting (SciPy's
12/// `COLAMD`).
13///
14/// The rows of `A` start as *elements*, the cliques they create in the graph of `AᵀA`. Eliminating
15/// a column merges the elements that contain it into one new element; the degree of a column is
16/// then bounded by the sizes of the elements it belongs to, without forming any clique. Elements
17/// contained in a new element are absorbed, and columns with identical patterns are merged into one
18/// weighted *supercolumn* and eliminated together. Rows and columns with more than
19/// `max(16, 10 √n)` entries are ignored (dense columns are placed last), as in the reference
20/// implementation.
21///
22/// Returns `q` with `q[k]` the original column placed at position `k`; `q` has length `ncols`.
23pub fn colamd(a: &CsrMatrix) -> Vec<usize> {
24    let (m, n) = (a.nrows, a.ncols);
25    let dense_row = ((10.0 * (n as f64).sqrt()) as usize).max(16);
26    let dense_col = ((10.0 * (m.min(n) as f64).sqrt()) as usize).max(16);
27
28    // Patterns: rows are the initial elements.
29    let mut row_cols: Vec<Vec<usize>> = Vec::with_capacity(m + n);
30    let mut alive_row: Vec<bool> = Vec::with_capacity(m + n);
31    for i in 0..m {
32        let mut c: Vec<usize> = a.indices[a.indptr[i]..a.indptr[i + 1]].to_vec();
33        c.sort_unstable();
34        c.dedup();
35        alive_row.push(!c.is_empty() && c.len() <= dense_row);
36        if c.len() > dense_row {
37            c.clear();
38        }
39        row_cols.push(c);
40    }
41    let mut count = vec![0usize; n];
42    for c in row_cols.iter().flatten() {
43        count[*c] += 1;
44    }
45    let mut col_alive = vec![true; n];
46    // Dense columns (the sparser first) and then empty ones go last.
47    let mut tail: Vec<usize> = (0..n).filter(|&j| count[j] == 0 || count[j] > dense_col).collect();
48    tail.sort_by_key(|&j| (count[j] == 0, count[j], j));
49    for &j in &tail {
50        col_alive[j] = false;
51    }
52
53    let mut col_rows: Vec<Vec<usize>> = vec![Vec::new(); n];
54    for (i, cols) in row_cols.iter().enumerate() {
55        if !alive_row[i] {
56            continue;
57        }
58        for &j in cols {
59            if col_alive[j] {
60                col_rows[j].push(i);
61            }
62        }
63    }
64    for r in 0..m {
65        row_cols[r].retain(|&j| col_alive[j]);
66    }
67    let mut weight = vec![1usize; n];
68    let mut members: Vec<Vec<usize>> = vec![Vec::new(); n];
69    let mut remaining = col_alive.iter().filter(|&&x| x).count();
70    let mut score = vec![0usize; n];
71    let mut heap: BinaryHeap<Reverse<(usize, usize)>> = BinaryHeap::new();
72    for j in 0..n {
73        if col_alive[j] {
74            score[j] = col_rows[j].iter().map(|&r| row_cols[r].len() - 1).sum::<usize>().min(remaining.saturating_sub(1));
75            heap.push(Reverse((score[j], j)));
76        }
77    }
78
79    let mut elem_cols: Vec<Vec<usize>> = Vec::new(); // the columns eliminated with each element
80    let mut parent: Vec<usize> = Vec::new(); // the element that absorbed it, or MAX
81    let mut tag = vec![usize::MAX; n];
82    let mut wstamp: Vec<usize> = vec![usize::MAX; m + n];
83    let mut w: Vec<usize> = vec![0; m + n];
84    let mut step = 0usize;
85    while let Some(Reverse((s, p))) = heap.pop() {
86        if !col_alive[p] || score[p] != s {
87            continue; // a stale entry
88        }
89        step += 1;
90        let t = elem_cols.len();
91        let mut cols_of_t = vec![p];
92        cols_of_t.extend(members[p].iter().copied());
93        elem_cols.push(cols_of_t);
94        parent.push(usize::MAX);
95        // The new element Lp: the union of the elements containing the pivot column.
96        let rows_p: Vec<usize> = col_rows[p].iter().copied().filter(|&r| alive_row[r]).collect();
97        let mut lp: Vec<usize> = Vec::new();
98        tag[p] = step;
99        for &r in &rows_p {
100            for &c in &row_cols[r] {
101                if col_alive[c] && tag[c] != step {
102                    tag[c] = step;
103                    lp.push(c);
104                }
105            }
106            alive_row[r] = false;
107            row_cols[r] = Vec::new();
108            if r >= m {
109                parent[r - m] = t;
110            }
111        }
112        col_alive[p] = false;
113        remaining -= weight[p];
114        lp.sort_unstable();
115        let e = row_cols.len();
116        let lp_weight: usize = lp.iter().map(|&j| weight[j]).sum();
117        row_cols.push(lp.clone());
118        alive_row.push(true);
119        for &j in &lp {
120            col_rows[j].retain(|&r| alive_row[r]);
121            col_rows[j].push(e);
122        }
123        // |Le \ Lp|, weighted, for every other element that meets Lp.
124        for &j in &lp {
125            for &r in &col_rows[j] {
126                if r == e {
127                    continue;
128                }
129                if wstamp[r] != step {
130                    wstamp[r] = step;
131                    row_cols[r].retain(|&c| col_alive[c]);
132                    w[r] = row_cols[r].iter().map(|&c| weight[c]).sum();
133                }
134                w[r] -= weight[j];
135            }
136        }
137        // Aggressive absorption, and the approximate degrees.
138        for &j in &lp {
139            let mut sum = 0usize;
140            let mut kept = Vec::with_capacity(col_rows[j].len());
141            for &r in &col_rows[j] {
142                if r == e {
143                    kept.push(r);
144                } else if w[r] == 0 {
145                    alive_row[r] = false; // Le is contained in Lp
146                    if r >= m {
147                        parent[r - m] = t;
148                    }
149                } else {
150                    sum += w[r];
151                    kept.push(r);
152                }
153            }
154            col_rows[j] = kept;
155            let others = lp_weight - weight[j];
156            score[j] = (remaining - weight[j]).min(score[j] + others).min(sum + others);
157        }
158        // Columns with identical patterns become one supercolumn.
159        let mut buckets: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
160        for &j in &lp {
161            col_rows[j].sort_unstable();
162            let hash = col_rows[j].iter().fold(0usize, |h, &r| h.wrapping_add(r.wrapping_mul(2654435761)));
163            buckets.entry((col_rows[j].len(), hash)).or_default().push(j);
164        }
165        for group in buckets.values().filter(|g| g.len() > 1) {
166            for (x, &i) in group.iter().enumerate() {
167                if !col_alive[i] {
168                    continue;
169                }
170                for &k in &group[x + 1..] {
171                    if col_alive[k] && col_rows[i] == col_rows[k] {
172                        weight[i] += weight[k];
173                        let moved = std::mem::take(&mut members[k]);
174                        members[i].push(k);
175                        members[i].extend(moved);
176                        col_alive[k] = false;
177                        score[i] = score[i].saturating_sub(weight[k]);
178                    }
179                }
180            }
181        }
182        for &j in &lp {
183            if col_alive[j] {
184                heap.push(Reverse((score[j], j)));
185            }
186        }
187    }
188    // Postorder the assembly tree: every element after the elements it absorbed, each subtree
189    // contiguous. The fill is the same; the order is the one a supernodal factorisation wants.
190    let count = elem_cols.len();
191    let mut children: Vec<Vec<usize>> = vec![Vec::new(); count];
192    let mut roots = Vec::new();
193    for t in 0..count {
194        if parent[t] == usize::MAX {
195            roots.push(t);
196        } else {
197            children[parent[t]].push(t);
198        }
199    }
200    let mut order: Vec<usize> = Vec::with_capacity(n);
201    for &root in &roots {
202        let mut stack = vec![(root, 0usize)];
203        while let Some((t, next)) = stack.pop() {
204            if next < children[t].len() {
205                stack.push((t, next + 1));
206                stack.push((children[t][next], 0));
207            } else {
208                order.extend(elem_cols[t].iter().copied());
209            }
210        }
211    }
212    order.extend(tail);
213    debug_assert_eq!(order.len(), n);
214    order
215}
216
217// ANCHOR: symamd
218/// A column ordering for a symmetric matrix (SYMAMD): `colamd` applied to a matrix with one row,
219/// holding the two columns `i` and `j`, for each off-diagonal pair `a_ij ≠ 0`, whose `AᵀA` has the
220/// pattern of `A + Aᵀ`. It is a minimum-degree ordering of the symmetric graph, found by the
221/// COLAMD machinery, with its handling of dense vertices.
222pub fn symamd(a: &CsrMatrix) -> Vec<usize> {
223    let n = a.nrows.max(a.ncols);
224    let mut pairs: Vec<(usize, usize)> = Vec::new();
225    for i in 0..a.nrows {
226        for p in a.indptr[i]..a.indptr[i + 1] {
227            let j = a.indices[p];
228            if i != j {
229                pairs.push((i.min(j), i.max(j)));
230            }
231        }
232    }
233    pairs.sort_unstable();
234    pairs.dedup();
235    let (mut rows, mut cols) = (Vec::with_capacity(2 * pairs.len()), Vec::with_capacity(2 * pairs.len()));
236    for (k, &(i, j)) in pairs.iter().enumerate() {
237        rows.extend([k, k]);
238        cols.extend([i, j]);
239    }
240    let edges = CsrMatrix::from_triplets(pairs.len(), n, &rows, &cols, &vec![1.0; rows.len()]).expect("a valid pattern");
241    colamd(&edges)
242}
243// ANCHOR_END: symamd
244// ANCHOR_END: colamd