Skip to main content

hypergraph_rs/linalg/
laplacian.rs

1//! Laplacian matrices (order-`d`, multiorder, normalized) of a hypergraph.
2
3use ndarray::{Array1, Array2};
4
5use super::hypergraph_matrix::{adjacency_matrix, degree_matrix, incidence_matrix};
6use super::LinalgError;
7use crate::Hypergraph;
8
9/// Build a diagonal matrix from a vector.
10fn diag(v: &Array1<f64>) -> Array2<f64> {
11    let n = v.len();
12    let mut m = Array2::<f64>::zeros((n, n));
13    for i in 0..n {
14        m[[i, i]] = v[i];
15    }
16    m
17}
18
19/// Order-`d` Laplacian `L = d·diag(K) − A` (A = weighted adjacency at order `d`).
20///
21/// XGI parity: `xgi.laplacian(H, order, rescale_per_node)`
22/// (`laplacian_matrix.py:62-115`). `order = 1` gives the usual graph Laplacian.
23pub fn laplacian<N, E, M>(
24    h: &Hypergraph<N, E, M>,
25    order: usize,
26    rescale_per_node: bool,
27) -> (Array2<f64>, Vec<String>) {
28    let (a, node_ids) = adjacency_matrix(h, Some(order), 1, true);
29    if a.shape() == [0, 0] {
30        return (Array2::zeros((0, 0)), Vec::new());
31    }
32    let (k, _) = degree_matrix(h, Some(order));
33    let mut l = diag(&k) * (order as f64) - &a;
34    if rescale_per_node {
35        l /= order as f64;
36    }
37    (l, node_ids)
38}
39
40/// Multiorder Laplacian `Σ_d L_d · w_d / mean(K_d)`, skipping orders with no edges.
41///
42/// XGI parity: `xgi.multiorder_laplacian(H, orders, weights, rescale_per_node)`
43/// (`laplacian_matrix.py:118-184`). Panics if `orders.len() != weights.len()`
44/// (XGI raises `ValueError`).
45pub fn multiorder_laplacian<N, E, M>(
46    h: &Hypergraph<N, E, M>,
47    orders: &[usize],
48    weights: &[f64],
49    rescale_per_node: bool,
50) -> (Array2<f64>, Vec<String>) {
51    assert_eq!(
52        orders.len(),
53        weights.len(),
54        "orders and weights must have the same length"
55    );
56    let n = h.num_nodes();
57    let mut l_multi = Array2::<f64>::zeros((n, n));
58    for (&d, &w) in orders.iter().zip(weights.iter()) {
59        let (k, _) = degree_matrix(h, Some(d));
60        let mean_k = if k.is_empty() {
61            0.0
62        } else {
63            k.mean().unwrap_or(0.0)
64        };
65        // Skip orders with no edges (all-zero K) to avoid divide-by-zero.
66        if mean_k == 0.0 {
67            continue;
68        }
69        let (l_d, _) = laplacian(h, d, rescale_per_node);
70        if l_d.shape() == [n, n] {
71            l_multi = l_multi + l_d * (w / mean_k);
72        }
73    }
74    (l_multi, h.node_ids())
75}
76
77/// Normalized hypergraph Laplacian
78/// `L = I − Dv^{-1/2}·Inc·W·De^{-1}·Incᵀ·Dv^{-1/2}`.
79///
80/// XGI parity: `xgi.normalized_hypergraph_laplacian(H, weighted)`
81/// (`laplacian_matrix.py:187-254`). Concrete over `N = E = serde_json::Value`
82/// because `weighted = true` reads each edge's `"weight"` attribute (default 1.0).
83///
84/// # Errors
85/// [`LinalgError::IsolatedNodes`] if any node has degree 0 (division by zero).
86pub fn normalized_hypergraph_laplacian<M>(
87    h: &Hypergraph<serde_json::Value, serde_json::Value, M>,
88    weighted: bool,
89) -> Result<(Array2<f64>, Vec<String>), LinalgError> {
90    // Isolate check: every node must belong to at least one edge.
91    for nid in h.node_ids() {
92        if h.memberships(&nid).map(|m| m.is_empty()).unwrap_or(true) {
93            return Err(LinalgError::IsolatedNodes);
94        }
95    }
96
97    let (inc, node_ids, edge_ids) = incidence_matrix(h, None);
98    let n = node_ids.len();
99
100    // Dv = node degrees (incidence row sums); De = edge sizes (col sums).
101    let dv = inc.sum_axis(ndarray::Axis(1)); // len n
102    let de = inc.sum_axis(ndarray::Axis(0)); // len m
103
104    let weights: Vec<f64> = if weighted {
105        edge_ids
106            .iter()
107            .map(|e| {
108                h.edge_attrs(e)
109                    .and_then(|a| a.get("weight"))
110                    .and_then(|w| w.as_f64())
111                    .unwrap_or(1.0)
112            })
113            .collect()
114    } else {
115        vec![1.0; edge_ids.len()]
116    };
117
118    let dv_invsqrt = diag(&dv.mapv(|x| x.powf(-0.5)));
119    // D1-ripple: a size-0 edge (constructible after D1) has De == 0; its
120    // incidence column is all zero, so its contribution must vanish rather
121    // than propagate as Inf/NaN through 1/0.
122    let de_inv = diag(&de.mapv(|x| if x == 0.0 { 0.0 } else { 1.0 / x }));
123    let w = diag(&Array1::from(weights));
124    let eye = Array2::<f64>::eye(n);
125
126    let mid = inc.dot(&w).dot(&de_inv).dot(&inc.t());
127    let l = eye - dv_invsqrt.dot(&mid).dot(&dv_invsqrt);
128    Ok((l, node_ids))
129}