Skip to main content

lib_jsl_graph/
laplacian.rs

1//! Graph Laplacians (SciPy's `scipy.sparse.csgraph.laplacian`).
2//!
3//! See the book entry [Matchings, k shortest paths and Laplacians](https://jwkunz.github.io/lib_jsl/book/graph/matching-laplacian.html#the-laplacian).
4
5// Dense matrices read best as index loops.
6#![allow(clippy::needless_range_loop)]
7
8use crate::graph::Graph;
9
10// ANCHOR: laplacian
11/// The Laplacian `L = D − A` of a weighted graph, as a dense matrix, and the degrees (SciPy's
12/// `laplacian`). `A` is the weighted adjacency matrix (parallel edges summed, loops ignored) and
13/// `D` the diagonal of degrees: the in-degrees (column sums) by default, the out-degrees (row
14/// sums) with `use_out_degree`; the two agree for undirected graphs. With `normed`, the symmetric
15/// normalisation `I − D^{−1/2} A D^{−1/2}`, with isolated vertices left at 0 on the diagonal; the
16/// returned degrees are then their square roots (1 for isolated vertices), as SciPy returns them.
17pub fn laplacian(g: &Graph, normed: bool, use_out_degree: bool) -> (Vec<Vec<f64>>, Vec<f64>) {
18    let n = g.vertex_count();
19    let mut a = vec![vec![0.0; n]; n];
20    for u in 0..n {
21        for &(v, w) in g.neighbors(u) {
22            if u != v {
23                a[u][v] += w;
24            }
25        }
26    }
27    let deg: Vec<f64> = if use_out_degree { a.iter().map(|r| r.iter().sum()).collect() } else { (0..n).map(|j| a.iter().map(|r| r[j]).sum()).collect() };
28    if !normed {
29        let mut l = a;
30        for i in 0..n {
31            for j in 0..n {
32                l[i][j] = if i == j { deg[i] } else { -l[i][j] };
33            }
34        }
35        return (l, deg);
36    }
37    let isolated: Vec<bool> = deg.iter().map(|&d| d == 0.0).collect();
38    let s: Vec<f64> = deg.iter().zip(&isolated).map(|(&d, &iso)| if iso { 1.0 } else { d.sqrt() }).collect();
39    let mut l = a;
40    for i in 0..n {
41        for j in 0..n {
42            l[i][j] = if i == j { if isolated[i] { 0.0 } else { 1.0 } } else { -l[i][j] / s[j] / s[i] };
43        }
44    }
45    (l, s)
46}
47// ANCHOR_END: laplacian
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn rows_sum_to_zero_and_normalised_spectrum_is_bounded() {
55        let g = Graph::from_edges(4, &[(0, 1, 1.0), (1, 2, 2.0), (2, 0, 0.5), (2, 3, 1.5)], false).unwrap();
56        let (l, d) = laplacian(&g, false, false);
57        assert_eq!(d, vec![1.5, 3.0, 4.0, 1.5]);
58        for row in &l {
59            assert!(row.iter().sum::<f64>().abs() < 1e-15);
60        }
61        let (n, _) = laplacian(&g, true, false);
62        assert!((n[0][1] + 1.0 / (1.5f64 * 3.0).sqrt()).abs() < 1e-15 && n[2][2] == 1.0);
63        // An isolated vertex.
64        let g = Graph::from_edges(3, &[(0, 1, 2.0)], true).unwrap();
65        let (n, d) = laplacian(&g, true, false);
66        assert_eq!(n[0][0], 0.0);
67        assert_eq!(d[0], 1.0);
68    }
69}