hypergraph_rs/linalg/
laplacian.rs1use ndarray::{Array1, Array2};
4
5use super::hypergraph_matrix::{adjacency_matrix, degree_matrix, incidence_matrix};
6use super::LinalgError;
7use crate::Hypergraph;
8
9fn 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
19pub 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
40pub 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 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
77pub 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 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 let dv = inc.sum_axis(ndarray::Axis(1)); let de = inc.sum_axis(ndarray::Axis(0)); 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 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}