Matchings, k shortest paths and Laplacians
| Problem | All-pairs shortest paths on sparse graphs with negative edges; the shortest loopless paths between two vertices; the largest matching and the cheapest complete matching in a bipartite graph; the structural rank of a sparse matrix; and the Laplacian matrix of a graph |
| Devised by | Donald Johnson (1977); Jin Yen (1971); John Hopcroft and Richard Karp (1973); Harold Kuhn (1955), James Munkres (1957), Jack Edmonds and Richard Karp (1972), and Roy Jonker and Anton Volgenant (1987), shortest augmenting paths; Gustav Kirchhoff (1847), Miroslav Fiedler (1973), the Laplacian |
| Accuracy | Exact up to rounding; the same distances, path lengths, matching sizes, assignments and matrices as scipy.sparse.csgraph |
| Cost | Johnson: ; Yen: ; Hopcroft-Karp: ; minimum-weight matching: ; Laplacian: dense |
| Read first | Shortest paths, Maximum flow and minimum cut |
| API | johnson, yen, maximum_bipartite_matching, min_weight_full_bipartite_matching, structural_rank, laplacian |
Overview
This entry completes the library’s coverage of scipy.sparse.csgraph:
- Johnson’s algorithm gives all-pairs shortest paths with negative edges. On sparse graphs it is faster than Floyd-Warshall.
- Yen’s algorithm gives the shortest loopless paths, for alternative routes in transport and networks.
- Maximum bipartite matching (Hopcroft-Karp) pairs as many rows with columns as possible. Applications include assigning workers to jobs they can do. In sparse linear algebra it finds a zero-free diagonal by permuting rows, and the structural rank of a sparsity pattern is the size of such a matching: the largest rank any matrix with that pattern can have.
- Minimum-weight full bipartite matching is the sparse assignment problem: match every row to a column at least total cost, using only allowed pairs.
- The graph Laplacian underlies spectral clustering and graph partitioning, diffusion on graphs, and Kirchhoff’s matrix-tree theorem.
Where it is used
These tools handle problems that arise once a graph gets realistic.
- Routes with alternatives. The K shortest loopless paths give a navigation system its second and third best routes, and give a network operator backup paths.
- All-pairs distances. Johnson’s algorithm handles sparse networks with negative weights, as in currency arbitrage detection and some scheduling problems.
- Graph Laplacians. Spectral clustering, image segmentation, mesh processing and the study of how fast a network mixes all use Laplacian eigenvectors.
- Assignment problems. Matching workers to jobs, or tracked objects to detections in successive video frames.
History
Donald Johnson (1977) combined Bellman-Ford and Dijkstra by reweighting the edges. Jin Yen (1971) found the shortest loopless paths with a deviation scheme that later variants still follow. John Hopcroft and Richard Karp (1973) showed that augmenting along many shortest paths at once gives an bipartite matching algorithm.
The assignment problem goes back to Harold Kuhn’s Hungarian method (1955), named for the work of Dénes Kőnig and Jenő Egerváry. Jack Edmonds and Richard Karp (1972) introduced potentials that make Dijkstra’s algorithm usable for its augmenting paths. Roy Jonker and Anton Volgenant (1987) gave the fast variant that SciPy’s sparse LAPJVsp builds on.
Gustav Kirchhoff (1847) used the Laplacian to count spanning trees in electrical networks. Miroslav Fiedler (1973) showed that its second eigenvalue measures how well connected a graph is.
The idea
Johnson’s algorithm
Add a vertex joined to every vertex by an edge of weight 0, and run Bellman-Ford from it to get potentials . The triangle inequality makes the reweighted edges non-negative. The weight of every path from to changes by the same amount, , so shortest paths stay shortest. Dijkstra’s algorithm from each vertex then finishes the job, and the distances are recovered as .
Yen’s k shortest paths
The first path is the shortest. Each later path deviates from an earlier one at some vertex, the spur. The prefix up to the spur, the root, is shared. For every vertex of the last path found:
- Remove the root’s vertices, and the next edge of every found path that shares this root.
- Find the shortest spur path to the target.
- Root plus spur is a candidate.
The cheapest candidate is the next path. Removing those edges forces the new path to differ from all earlier ones, and removing the root’s vertices keeps it loopless.
Hopcroft-Karp
An augmenting path alternates between unmatched and matched edges from a free row to a free column. Flipping it enlarges the matching by one, and a matching is maximum exactly when no augmenting path exists (Berge). Each Hopcroft-Karp phase does two things:
- A breadth-first search from all free rows finds the length of the shortest augmenting paths.
- Depth-first searches along the breadth-first layers augment along a maximal set of vertex-disjoint paths of that length.
Only phases are needed.
Minimum-weight matching by shortest augmenting paths
Keep dual potentials and with reduced costs , zero on matched edges. The cheapest augmenting path from a new row is then a shortest path on non-negative reduced costs, which Dijkstra’s algorithm finds. Updating the potentials by the shortest-path distances keeps every reduced cost non-negative and the matched ones zero. After every row has been matched, the matching is optimal by linear-programming duality.
The Laplacian
, with the weighted adjacency matrix and the diagonal of degrees: in-degrees by default in SciPy, out-degrees on request. For an undirected graph, , so is positive semi-definite, with one zero eigenvalue per connected component. The normalised form has eigenvalues in .
Implementation
/// Johnson's algorithm (SciPy's `johnson`), `O(V E log V)`, better than Floyd-Warshall on sparse
/// graphs and allowing negative edges. Bellman-Ford from an added vertex joined to every vertex
/// by a zero edge gives potentials `h` with `w(u, v) + h(u) − h(v) ≥ 0`; Dijkstra from every
/// vertex on these reweighted edges, which keeps shortest paths shortest, then gives the
/// distances `d'(u, v) − h(u) + h(v)`. Errors on a negative cycle (any negative edge of an
/// undirected graph is one).
pub fn johnson(g: &Graph) -> Result<AllPairsShortestPaths, ErrorsJSL> {
let n = g.vertex_count();
let edges = g.edges();
let arcs: Vec<(usize, usize, f64)> = edges
.iter()
.flat_map(|e| if g.is_directed() { vec![(e.from, e.to, e.weight)] } else { vec![(e.from, e.to, e.weight), (e.to, e.from, e.weight)] })
.collect();
if arcs.iter().any(|a| a.2.is_nan()) {
return Err(ErrorsJSL::InvalidInputRange("johnson: edge weights must not be NaN"));
}
// Potentials: Bellman-Ford from a virtual source at distance 0 from everything.
let mut h = vec![0.0f64; n];
let mut changed = true;
for _ in 0..=n {
changed = false;
for &(u, v, w) in &arcs {
if h[u] + w < h[v] {
h[v] = h[u] + w;
changed = true;
}
}
if !changed {
break;
}
}
if changed {
return Err(ErrorsJSL::RuntimeError("The graph contains a negative cycle."));
}
let mut adj: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
for &(u, v, w) in &arcs {
adj[u].push((v, (w + h[u] - h[v]).max(0.0)));
}
let mut distance = vec![vec![f64::INFINITY; n]; n];
let mut next = vec![vec![None; n]; n];
for s in 0..n {
let mut dist = vec![f64::INFINITY; n];
let mut pred: Vec<Option<usize>> = vec![None; n];
dist[s] = 0.0;
let mut heap = std::collections::BinaryHeap::new();
heap.push(std::cmp::Reverse((OrdF64(0.0), s)));
while let Some(std::cmp::Reverse((OrdF64(d), u))) = heap.pop() {
if d > dist[u] {
continue;
}
for &(v, w) in &adj[u] {
if d + w < dist[v] {
dist[v] = d + w;
pred[v] = Some(u);
heap.push(std::cmp::Reverse((OrdF64(d + w), v)));
}
}
}
for t in 0..n {
if dist[t].is_finite() {
distance[s][t] = dist[t] - h[s] + h[t];
// The first step from s towards t: walk back along the predecessors.
let mut v = t;
while let Some(p) = pred[v] {
if p == s {
break;
}
v = p;
}
next[s][t] = Some(v);
}
}
next[s][s] = Some(s);
}
Ok(AllPairsShortestPaths { distance, next })
}
/// The `k` shortest loopless paths from `source` to `sink`, shortest first, as
/// `(length, vertices)` (SciPy's `yen`). Yen's algorithm takes each path found so far and, for
/// every vertex on it (the spur), finds the shortest path from the spur that leaves the common
/// prefix differently from every path already found, avoiding the prefix's vertices; the best of
/// these candidates is the next path. Weights must be non-negative. Fewer than `k` paths are
/// returned if fewer exist.
pub fn yen(g: &Graph, source: usize, sink: usize, k: usize) -> Result<Vec<(f64, Vec<usize>)>, ErrorsJSL> {
let n = g.vertex_count();
if source >= n || sink >= n {
return Err(ErrorsJSL::InvalidInputRange("yen: vertex out of range"));
}
if g.edges().iter().any(|e| e.weight.is_nan() || e.weight < 0.0) {
return Err(ErrorsJSL::InvalidInputRange("yen: weights must be non-negative"));
}
let mut found: Vec<(f64, Vec<usize>)> = Vec::new();
if k == 0 {
return Ok(found);
}
let none = vec![false; n];
match restricted_path(g, source, sink, &none, &HashSet::new()) {
Some(p) => found.push(p),
None => return Ok(found),
}
let mut candidates: Vec<(f64, Vec<usize>)> = Vec::new();
while found.len() < k {
let last = found.last().expect("non-empty").1.clone();
for i in 0..last.len() - 1 {
let spur = last[i];
let root = &last[..=i];
let mut blocked_e = HashSet::new();
for (_, p) in &found {
if p.len() > i && &p[..=i] == root {
blocked_e.insert((p[i], p[i + 1]));
if !g.is_directed() {
blocked_e.insert((p[i + 1], p[i]));
}
}
}
let mut blocked_v = vec![false; n];
for &v in &root[..i] {
blocked_v[v] = true;
}
if let Some((_, spur_path)) = restricted_path(g, spur, sink, &blocked_v, &blocked_e) {
let mut path = root[..i].to_vec();
path.extend(spur_path);
let cost: f64 = path.windows(2).map(|w| arc_weight(g, w[0], w[1])).sum();
if !candidates.iter().any(|c| c.1 == path) && !found.iter().any(|c| c.1 == path) {
candidates.push((cost, path));
}
}
}
if candidates.is_empty() {
break;
}
// The cheapest candidate; ties to the one with fewer vertices, then the first found.
let best = (0..candidates.len())
.min_by(|&a, &b| candidates[a].0.total_cmp(&candidates[b].0).then(candidates[a].1.len().cmp(&candidates[b].1.len())))
.expect("non-empty");
found.push(candidates.remove(best));
}
Ok(found)
}
/// A minimum-weight (or, with `maximize`, maximum-weight) matching that matches every vertex on
/// the smaller side (SciPy's `min_weight_full_bipartite_matching`). Returns `(rows, cols)` of the
/// matched pairs, sorted by row. Successive shortest augmenting paths: each row in turn is
/// matched by Dijkstra's algorithm on the reduced costs `w(r, c) − u(r) − v(c) ≥ 0`, which the
/// dual potentials `u`, `v` keep non-negative; `O(V E log V)`. Errors if no full matching exists.
pub fn min_weight_full_bipartite_matching(n_rows: usize, n_cols: usize, edges: &[(usize, usize, f64)], maximize: bool) -> Result<(Vec<usize>, Vec<usize>), ErrorsJSL> {
if edges.iter().any(|e| !e.2.is_finite()) {
return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: weights must be finite"));
}
// Work with rows as the smaller side.
let transpose = n_rows > n_cols;
let (nr, nc) = if transpose { (n_cols, n_rows) } else { (n_rows, n_cols) };
let mut adj: Vec<Vec<(usize, f64)>> = vec![Vec::new(); nr];
for &(r, c, w) in edges {
if r >= n_rows || c >= n_cols {
return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: an edge is out of range"));
}
let (r, c) = if transpose { (c, r) } else { (r, c) };
adj[r].push((c, if maximize { -w } else { w }));
}
// Initial potentials: u(r) = min_c w(r, c), v = 0, so every reduced cost is non-negative.
let mut u: Vec<f64> = adj.iter().map(|a| a.iter().map(|e| e.1).fold(f64::INFINITY, f64::min)).collect();
if u.iter().any(|x| x.is_infinite()) {
return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: no full matching exists"));
}
let mut v = vec![0.0f64; nc];
let mut row_of: Vec<Option<usize>> = vec![None; nc];
let mut col_of: Vec<Option<usize>> = vec![None; nr];
for start in 0..nr {
// Dijkstra over columns: dist[c] is the reduced length of the best alternating path from
// `start` to column c; prev[c] the row it was reached from.
let mut dist = vec![f64::INFINITY; nc];
let mut prev = vec![usize::MAX; nc];
let mut done = vec![false; nc];
let mut heap = BinaryHeap::new();
for &(c, w) in &adj[start] {
let d = w - u[start] - v[c];
if d < dist[c] {
dist[c] = d;
prev[c] = start;
heap.push(Reverse((OrdF64(d), c)));
}
}
let mut free_col = None;
let mut settled = Vec::new();
while let Some(Reverse((OrdF64(d), c))) = heap.pop() {
if done[c] || d > dist[c] {
continue;
}
done[c] = true;
settled.push(c);
match row_of[c] {
None => {
free_col = Some(c);
break;
}
Some(r) => {
for &(c2, w) in &adj[r] {
let nd = d + w - u[r] - v[c2];
if !done[c2] && nd < dist[c2] {
dist[c2] = nd;
prev[c2] = r;
heap.push(Reverse((OrdF64(nd), c2)));
}
}
}
}
}
let Some(end) = free_col else {
return Err(ErrorsJSL::InvalidInputRange("min_weight_full_bipartite_matching: no full matching exists"));
};
let dend = dist[end];
// Update the potentials so matched edges stay tight and reduced costs non-negative.
u[start] += dend;
for &c in &settled {
if c != end {
let r = row_of[c].expect("settled columns before the end are matched");
u[r] += dend - dist[c];
v[c] -= dend - dist[c];
}
}
// Augment along the alternating path.
let mut c = end;
loop {
let r = prev[c];
let next = col_of[r];
col_of[r] = Some(c);
row_of[c] = Some(r);
if r == start {
break;
}
c = next.expect("an inner row on the path was matched");
}
}
let mut pairs: Vec<(usize, usize)> = (0..nr).map(|r| (r, col_of[r].expect("all rows matched"))).collect();
if transpose {
pairs = pairs.into_iter().map(|(r, c)| (c, r)).collect();
}
pairs.sort_unstable();
Ok(pairs.into_iter().unzip())
}
- Bipartite graphs are given as their biadjacency pattern,
(row, column)pairs, as SciPy takes a sparse matrix. - Maximum matchings are not unique, and the library’s may differ from SciPy’s. The sizes agree, and so do the minimum-weight assignments when, as generically, the optimum is unique.
laplacianreturns a dense matrix. Parallel edges are summed and loops ignored, as SciPy does with a sparse adjacency matrix.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_geograph_refs.py:
Table 23.3. Johnson, Yen, bipartite matchings, structural rank and Laplacians against `scipy.sparse.csgraph`.
| Function | Difference from SciPy | Notes |
|---|---|---|
johnson, 40 vertices, 155 edges (42 negative) | 9e-16 | all 1600 distances |
yen, 8 shortest paths 0 → 17, directed | 9e-16 | lengths 4.690 … 7.323 |
yen, 8 shortest paths 0 → 17, undirected | 4e-16 | lengths 2.111 … 3.102 |
laplacian (in-degrees) | 0 | |
laplacian, normalised | 0 | |
laplacian, out-degrees | 4e-15 | |
maximum_bipartite_matching, structural_rank, 30 × 40 | same size | 29 pairs; structural rank 29 |
min_weight_full_bipartite_matching, 25 × 35 | 7e-15 | total 59.0774; same assignment |
min_weight_full_bipartite_matching, 25 × 35, maximize | 0 | total 225.7493; same assignment |
All results agree with SciPy to rounding, including Johnson’s distances with 42 negative edges and the full assignments, both minimum and maximum.
Figure 23.4. The four shortest paths across a weighted grid, by Yen's algorithm (offset slightly to keep them apart). Each later path deviates from an earlier one at a spur vertex. Paths 3 and 4 have equal length.
Strengths
- Johnson’s algorithm handles negative edges at nearly the cost of repeated Dijkstra.
- Hopcroft-Karp and the shortest-augmenting-path assignment work directly on sparse patterns, at a cost close to linear in the number of edges per phase or row.
- Yen’s paths are loopless, which simple -best variants of Dijkstra do not guarantee.
Weaknesses
- Yen’s algorithm runs a Dijkstra search for every vertex of every path found, so it is slow for large on large graphs.
- No minimum-weight matching in general (non-bipartite) graphs (Edmonds’ blossom algorithm), and no sparse Laplacian.
Exercises
- Why can’t Dijkstra’s algorithm be used directly with negative edges, even without negative cycles?
- Show that reweighting by potentials changes every – path weight by the same amount.
- A 3 × 3 matrix has non-zeros only in its first column and first row. What is its structural rank?
- Show that the Laplacian of a connected undirected graph has a one-dimensional null space spanned by .
Hints and answers
- Dijkstra’s algorithm settles a vertex for good when it is popped. A negative edge found later could still lower its distance.
- Along a path , the potentials telescope: .
- 2: rows 1 and 2 have non-zeros only in column 0, so at most one of them can be matched.
- forces along every edge, hence everywhere in a connected graph.
Further reading
- D. B. Johnson, “Efficient algorithms for shortest paths in sparse networks”, Journal of the ACM 24 (1977) 1–13.
- J. Y. Yen, “Finding the K shortest loopless paths in a network”, Management Science 17 (1971) 712–716.
- J. E. Hopcroft and R. M. Karp, “An n^{5/2} algorithm for maximum matchings in bipartite graphs”, SIAM Journal on Computing 2 (1973) 225–231.
- R. Jonker and A. Volgenant, “A shortest augmenting path algorithm for dense and sparse linear assignment problems”, Computing 38 (1987) 325–340.
- M. Fiedler, “Algebraic connectivity of graphs”, Czechoslovak Mathematical Journal 23 (1973) 298–305.
- F. R. K. Chung, Spectral Graph Theory, American Mathematical Society (1997).