Skip to main content

lib_jsl_graph/
matching.rs

1//! Matchings in bipartite graphs, following `scipy.sparse.csgraph`: maximum-cardinality
2//! matching by Hopcroft and Karp (`maximum_bipartite_matching`), minimum-weight full matching
3//! by successive shortest augmenting paths (`min_weight_full_bipartite_matching`), and the
4//! structural rank of a sparsity pattern (`structural_rank`).
5//!
6//! A bipartite graph is given by its biadjacency pattern: `n_rows` row vertices, `n_cols` column
7//! vertices and edges `(row, col)` (with weights for the weighted problem).
8//!
9//! See the book entry [Matchings, k shortest paths and Laplacians](https://jwkunz.github.io/lib_jsl/book/graph/matching-laplacian.html).
10
11use crate::graph::OrdF64;
12use lib_jsl_core::ErrorsJSL;
13use std::cmp::Reverse;
14use std::collections::{BinaryHeap, VecDeque};
15
16/// A matching: the column of each row and the row of each column, `None` where unmatched.
17#[derive(Clone, Debug, PartialEq)]
18#[non_exhaustive]
19pub struct BipartiteMatching {
20    pub row_to_col: Vec<Option<usize>>,
21    pub col_to_row: Vec<Option<usize>>,
22}
23
24impl BipartiteMatching {
25    /// The number of matched pairs.
26    pub fn size(&self) -> usize {
27        self.row_to_col.iter().filter(|c| c.is_some()).count()
28    }
29}
30
31fn adjacency(n_rows: usize, n_cols: usize, edges: &[(usize, usize)]) -> Result<Vec<Vec<usize>>, ErrorsJSL> {
32    let mut adj = vec![Vec::new(); n_rows];
33    for &(r, c) in edges {
34        if r >= n_rows || c >= n_cols {
35            return Err(ErrorsJSL::InvalidInputRange("bipartite matching: an edge is out of range"));
36        }
37        adj[r].push(c);
38    }
39    for a in adj.iter_mut() {
40        a.sort_unstable();
41        a.dedup();
42    }
43    Ok(adj)
44}
45
46// ANCHOR: hopcroft_karp
47/// A maximum-cardinality matching (SciPy's `maximum_bipartite_matching`) by the Hopcroft-Karp
48/// algorithm, `O(E √V)`: each phase finds, by a breadth-first search from all free rows, the
49/// length of the shortest augmenting paths, then augments along a maximal set of vertex-disjoint
50/// paths of that length by depth-first searches. Maximum matchings are not unique; SciPy may
51/// return a different one of the same size.
52pub fn maximum_bipartite_matching(n_rows: usize, n_cols: usize, edges: &[(usize, usize)]) -> Result<BipartiteMatching, ErrorsJSL> {
53    let adj = adjacency(n_rows, n_cols, edges)?;
54    let mut row_to_col: Vec<Option<usize>> = vec![None; n_rows];
55    let mut col_to_row: Vec<Option<usize>> = vec![None; n_cols];
56    let inf = usize::MAX;
57    let mut dist = vec![inf; n_rows];
58    loop {
59        // Breadth-first layering from the free rows.
60        let mut queue = VecDeque::new();
61        for r in 0..n_rows {
62            if row_to_col[r].is_none() {
63                dist[r] = 0;
64                queue.push_back(r);
65            } else {
66                dist[r] = inf;
67            }
68        }
69        let mut found = false;
70        while let Some(r) = queue.pop_front() {
71            for &c in &adj[r] {
72                match col_to_row[c] {
73                    None => found = true,
74                    Some(r2) if dist[r2] == inf => {
75                        dist[r2] = dist[r] + 1;
76                        queue.push_back(r2);
77                    }
78                    _ => {}
79                }
80            }
81        }
82        if !found {
83            break;
84        }
85        // Depth-first augmentation along the layers (iteratively, with per-row edge pointers).
86        let mut ptr = vec![0usize; n_rows];
87        for start in 0..n_rows {
88            if row_to_col[start].is_some() {
89                continue;
90            }
91            let mut stack = vec![start];
92            while let Some(&r) = stack.last() {
93                if ptr[r] == adj[r].len() {
94                    dist[r] = inf;
95                    stack.pop();
96                    continue;
97                }
98                let c = adj[r][ptr[r]];
99                ptr[r] += 1;
100                match col_to_row[c] {
101                    None => {
102                        // Augment along the stack.
103                        let mut col = c;
104                        for &row in stack.iter().rev() {
105                            let prev = row_to_col[row];
106                            row_to_col[row] = Some(col);
107                            col_to_row[col] = Some(row);
108                            match prev {
109                                Some(p) => col = p,
110                                None => break,
111                            }
112                        }
113                        break;
114                    }
115                    Some(r2) if dist[r2] == dist[r] + 1 => stack.push(r2),
116                    _ => {}
117                }
118            }
119        }
120    }
121    Ok(BipartiteMatching { row_to_col, col_to_row })
122}
123// ANCHOR_END: hopcroft_karp
124
125/// The structural rank of a sparsity pattern (SciPy's `structural_rank`): the largest rank any
126/// matrix with this pattern can have, the size of a maximum matching between rows and columns.
127pub fn structural_rank(n_rows: usize, n_cols: usize, nonzeros: &[(usize, usize)]) -> Result<usize, ErrorsJSL> {
128    Ok(maximum_bipartite_matching(n_rows, n_cols, nonzeros)?.size())
129}
130
131
132// ANCHOR: min_weight
133/// A minimum-weight (or, with `maximize`, maximum-weight) matching that matches every vertex on
134/// the smaller side (SciPy's `min_weight_full_bipartite_matching`). Returns `(rows, cols)` of the
135/// matched pairs, sorted by row. Successive shortest augmenting paths: each row in turn is
136/// matched by Dijkstra's algorithm on the reduced costs `w(r, c) − u(r) − v(c) ≥ 0`, which the
137/// dual potentials `u`, `v` keep non-negative; `O(V E log V)`. Errors if no full matching exists.
138pub fn min_weight_full_bipartite_matching(n_rows: usize, n_cols: usize, edges: &[(usize, usize, f64)], maximize: bool) -> Result<(Vec<usize>, Vec<usize>), ErrorsJSL> {
139    if edges.iter().any(|e| !e.2.is_finite()) {
140        return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: weights must be finite"));
141    }
142    // Work with rows as the smaller side.
143    let transpose = n_rows > n_cols;
144    let (nr, nc) = if transpose { (n_cols, n_rows) } else { (n_rows, n_cols) };
145    let mut adj: Vec<Vec<(usize, f64)>> = vec![Vec::new(); nr];
146    for &(r, c, w) in edges {
147        if r >= n_rows || c >= n_cols {
148            return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: an edge is out of range"));
149        }
150        let (r, c) = if transpose { (c, r) } else { (r, c) };
151        adj[r].push((c, if maximize { -w } else { w }));
152    }
153    // Initial potentials: u(r) = min_c w(r, c), v = 0, so every reduced cost is non-negative.
154    let mut u: Vec<f64> = adj.iter().map(|a| a.iter().map(|e| e.1).fold(f64::INFINITY, f64::min)).collect();
155    if u.iter().any(|x| x.is_infinite()) {
156        return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: no full matching exists"));
157    }
158    let mut v = vec![0.0f64; nc];
159    let mut row_of: Vec<Option<usize>> = vec![None; nc];
160    let mut col_of: Vec<Option<usize>> = vec![None; nr];
161    for start in 0..nr {
162        // Dijkstra over columns: dist[c] is the reduced length of the best alternating path from
163        // `start` to column c; prev[c] the row it was reached from.
164        let mut dist = vec![f64::INFINITY; nc];
165        let mut prev = vec![usize::MAX; nc];
166        let mut done = vec![false; nc];
167        let mut heap = BinaryHeap::new();
168        for &(c, w) in &adj[start] {
169            let d = w - u[start] - v[c];
170            if d < dist[c] {
171                dist[c] = d;
172                prev[c] = start;
173                heap.push(Reverse((OrdF64(d), c)));
174            }
175        }
176        let mut free_col = None;
177        let mut settled = Vec::new();
178        while let Some(Reverse((OrdF64(d), c))) = heap.pop() {
179            if done[c] || d > dist[c] {
180                continue;
181            }
182            done[c] = true;
183            settled.push(c);
184            match row_of[c] {
185                None => {
186                    free_col = Some(c);
187                    break;
188                }
189                Some(r) => {
190                    for &(c2, w) in &adj[r] {
191                        let nd = d + w - u[r] - v[c2];
192                        if !done[c2] && nd < dist[c2] {
193                            dist[c2] = nd;
194                            prev[c2] = r;
195                            heap.push(Reverse((OrdF64(nd), c2)));
196                        }
197                    }
198                }
199            }
200        }
201        let Some(end) = free_col else {
202            return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: no full matching exists"));
203        };
204        let dend = dist[end];
205        // Update the potentials so matched edges stay tight and reduced costs non-negative.
206        u[start] += dend;
207        for &c in &settled {
208            if c != end {
209                let r = row_of[c].expect("settled columns before the end are matched");
210                u[r] += dend - dist[c];
211                v[c] -= dend - dist[c];
212            }
213        }
214        // Augment along the alternating path.
215        let mut c = end;
216        loop {
217            let r = prev[c];
218            let next = col_of[r];
219            col_of[r] = Some(c);
220            row_of[c] = Some(r);
221            if r == start {
222                break;
223            }
224            c = next.expect("an inner row on the path was matched");
225        }
226    }
227    let mut pairs: Vec<(usize, usize)> = (0..nr).map(|r| (r, col_of[r].expect("all rows matched"))).collect();
228    if transpose {
229        pairs = pairs.into_iter().map(|(r, c)| (c, r)).collect();
230    }
231    pairs.sort_unstable();
232    Ok(pairs.into_iter().unzip())
233}
234// ANCHOR_END: min_weight
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn matchings_are_maximum_and_optimal() {
242        // A 4 × 5 pattern with a maximum matching of size 3 (rows 0 and 1 share one column).
243        let e = [(0, 0), (1, 0), (2, 1), (2, 2), (3, 3), (3, 4)];
244        let m = maximum_bipartite_matching(4, 5, &e).unwrap();
245        assert_eq!(m.size(), 3);
246        for (r, c) in m.row_to_col.iter().enumerate() {
247            if let Some(c) = c {
248                assert!(e.contains(&(r, *c)) && m.col_to_row[*c] == Some(r));
249            }
250        }
251        assert_eq!(structural_rank(3, 3, &[(0, 0), (0, 1), (1, 0), (2, 0)]).unwrap(), 2);
252        // Weighted: brute force over all permutations of a dense 4 × 4 matrix.
253        let w = [[4.0, 1.0, 3.0, 2.0], [2.0, 0.5, 5.0, 3.0], [3.0, 2.0, 2.0, 1.0], [1.5, 4.0, 3.0, 0.2]];
254        let edges: Vec<(usize, usize, f64)> = (0..4).flat_map(|r| (0..4).map(move |c| (r, c, w[r][c]))).collect();
255        let (rows, cols) = min_weight_full_bipartite_matching(4, 4, &edges, false).unwrap();
256        let got: f64 = rows.iter().zip(&cols).map(|(&r, &c)| w[r][c]).sum();
257        let mut best = f64::INFINITY;
258        let mut perm = [0, 1, 2, 3];
259        fn permute(k: usize, p: &mut [usize; 4], w: &[[f64; 4]; 4], best: &mut f64) {
260            if k == 4 {
261                *best = best.min((0..4).map(|r| w[r][p[r]]).sum());
262                return;
263            }
264            for i in k..4 {
265                p.swap(k, i);
266                permute(k + 1, p, w, best);
267                p.swap(k, i);
268            }
269        }
270        permute(0, &mut perm, &w, &mut best);
271        assert!((got - best).abs() < 1e-12);
272        assert!(min_weight_full_bipartite_matching(2, 2, &[(0, 0, 1.0), (1, 0, 1.0)], false).is_err());
273    }
274}