Skip to main content

lib_jsl_linalg/sparse/
amd.rs

1//! Approximate minimum degree ordering (Amestoy, Davis and Duff, 1996) on a quotient graph.
2
3use super::formats::CsrMatrix;
4use std::cmp::Reverse;
5use std::collections::{BTreeMap, BinaryHeap};
6
7// ANCHOR: amd
8/// A minimum-degree ordering of the symmetric pattern of `A + Aᵀ` (SciPy's `MMD_AT_PLUS_A` is the
9/// same idea): repeatedly eliminate a vertex of least degree in the elimination graph.
10///
11/// The graph is never formed. Eliminating a vertex turns it into an *element*, standing for the
12/// clique of its neighbours, and a vertex's degree is bounded using the sizes of the elements it
13/// belongs to (Amestoy, Davis and Duff's *approximate* degree), so one elimination costs work
14/// proportional to the size of the new element and not to the square of it. Elements contained in
15/// a new one are absorbed, vertices left with the same neighbours are merged into one weighted
16/// *supervariable* and eliminated together, and a vertex whose only neighbour is the new element
17/// is eliminated with it. Ties go to the lowest index.
18///
19/// Returns `q` with `q[k]` the vertex eliminated `k`-th.
20pub fn minimum_degree(a: &CsrMatrix) -> Vec<usize> {
21    let n = a.nrows.max(a.ncols);
22    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
23    for i in 0..a.nrows {
24        for p in a.indptr[i]..a.indptr[i + 1] {
25            let j = a.indices[p];
26            if i != j {
27                adj[i].push(j);
28                adj[j].push(i);
29            }
30        }
31    }
32    for l in adj.iter_mut() {
33        l.sort_unstable();
34        l.dedup();
35    }
36    amd_graph(&adj, &vec![false; n])
37}
38// ANCHOR_END: amd
39
40/// Approximate minimum degree on an undirected graph given by sorted, duplicate-free adjacency
41/// lists. Vertices with `frozen[v]` are never eliminated and do not appear in the result, but they
42/// take part in the degrees: ordering a piece of a graph together with the vertices around it,
43/// which come later, is how nested dissection orders its leaves ("halo" minimum degree).
44pub(super) fn amd_graph(adj: &[Vec<usize>], frozen: &[bool]) -> Vec<usize> {
45    let n = adj.len();
46    let mut vadj: Vec<Vec<usize>> = adj.to_vec();
47    let mut velem: Vec<Vec<usize>> = vec![Vec::new(); n];
48    let mut elem_vars: Vec<Vec<usize>> = vec![Vec::new(); n];
49    let mut elem_alive = vec![false; n];
50    let mut alive = vec![true; n];
51    let mut weight = vec![1usize; n];
52    let mut members: Vec<Vec<usize>> = vec![Vec::new(); n];
53    let mut degree: Vec<usize> = adj.iter().map(|l| l.len()).collect();
54    let mut remaining = n; // the total weight of the variables not yet eliminated
55    let mut heap: BinaryHeap<Reverse<(usize, usize)>> = (0..n).filter(|&v| !frozen[v]).map(|v| Reverse((degree[v], v))).collect();
56    let mut order: Vec<usize> = Vec::with_capacity(n);
57    let mut tag = vec![usize::MAX; n];
58    let mut wstamp = vec![usize::MAX; n];
59    let mut w = vec![0usize; n];
60    let mut step = 0usize;
61    while let Some(Reverse((d, p))) = heap.pop() {
62        if !alive[p] || degree[p] != d {
63            continue; // a stale entry
64        }
65        step += 1;
66        // The new element: the neighbours of p, directly and through its elements.
67        tag[p] = step;
68        let mut lp: Vec<usize> = Vec::new();
69        for &j in &vadj[p] {
70            if alive[j] && tag[j] != step {
71                tag[j] = step;
72                lp.push(j);
73            }
74        }
75        for &e in &velem[p] {
76            if !elem_alive[e] {
77                continue;
78            }
79            for &j in &elem_vars[e] {
80                if alive[j] && tag[j] != step {
81                    tag[j] = step;
82                    lp.push(j);
83                }
84            }
85            elem_alive[e] = false; // absorbed
86            elem_vars[e] = Vec::new();
87        }
88        alive[p] = false;
89        remaining -= weight[p];
90        order.push(p);
91        order.extend(members[p].iter().copied());
92        vadj[p] = Vec::new();
93        velem[p] = Vec::new();
94        lp.sort_unstable();
95        elem_alive[p] = true;
96        let lp_weight: usize = lp.iter().map(|&j| weight[j]).sum();
97        // Within Lp, drop the neighbours the new element now covers, and the absorbed elements.
98        for &j in &lp {
99            vadj[j].retain(|&k| alive[k] && tag[k] != step);
100            velem[j].retain(|&e| elem_alive[e]);
101            velem[j].push(p);
102        }
103        // |Le \ Lp| (weighted) for every other element that meets Lp.
104        for &j in &lp {
105            for &e in &velem[j] {
106                if e == p {
107                    continue;
108                }
109                if wstamp[e] != step {
110                    wstamp[e] = step;
111                    elem_vars[e].retain(|&k| alive[k]);
112                    w[e] = elem_vars[e].iter().map(|&k| weight[k]).sum();
113                }
114                w[e] -= weight[j];
115            }
116        }
117        // Aggressive absorption, then the approximate degrees.
118        let mut survivors: Vec<usize> = Vec::with_capacity(lp.len());
119        for &j in &lp {
120            let mut sum = 0usize;
121            let mut kept = Vec::with_capacity(velem[j].len());
122            for &e in &velem[j] {
123                if e == p {
124                    kept.push(e);
125                } else if w[e] == 0 {
126                    elem_alive[e] = false; // Le is contained in Lp
127                } else {
128                    sum += w[e];
129                    kept.push(e);
130                }
131            }
132            velem[j] = kept;
133            let others = lp_weight - weight[j];
134            let avars: usize = vadj[j].iter().map(|&k| weight[k]).sum();
135            // A vertex whose only neighbour is the new element can be eliminated with it.
136            if !frozen[j] && vadj[j].is_empty() && velem[j].len() == 1 {
137                alive[j] = false;
138                remaining -= weight[j];
139                order.push(j);
140                order.extend(members[j].iter().copied());
141                continue;
142            }
143            degree[j] = (remaining - weight[j]).min(degree[j] + others).min(avars + others + sum);
144            survivors.push(j);
145        }
146        elem_vars[p] = survivors.clone();
147        // Vertices with identical neighbours become one supervariable.
148        let mut buckets: BTreeMap<(usize, usize, usize), Vec<usize>> = BTreeMap::new();
149        for &j in &survivors {
150            vadj[j].sort_unstable();
151            velem[j].sort_unstable();
152            let hash = vadj[j].iter().chain(velem[j].iter()).fold(0usize, |h, &x| h.wrapping_add(x.wrapping_mul(2654435761)));
153            buckets.entry((vadj[j].len(), velem[j].len(), hash)).or_default().push(j);
154        }
155        for group in buckets.values().filter(|g| g.len() > 1) {
156            for (x, &i) in group.iter().enumerate() {
157                if !alive[i] {
158                    continue;
159                }
160                for &k in &group[x + 1..] {
161                    if alive[k] && frozen[i] == frozen[k] && vadj[i] == vadj[k] && velem[i] == velem[k] {
162                        weight[i] += weight[k];
163                        let moved = std::mem::take(&mut members[k]);
164                        members[i].push(k);
165                        members[i].extend(moved);
166                        alive[k] = false;
167                        degree[i] = degree[i].saturating_sub(weight[k]);
168                    }
169                }
170            }
171        }
172        for &j in &survivors {
173            if alive[j] && !frozen[j] {
174                heap.push(Reverse((degree[j], j)));
175            }
176        }
177    }
178    order
179}