hypergraph_rs/algorithms/
centrality.rs1use indexmap::IndexMap;
9
10use super::connected::is_connected;
11use crate::linalg::clique_motif_matrix;
12use crate::Hypergraph;
13
14fn l1(v: &[f64]) -> f64 {
16 v.iter().map(|x| x.abs()).sum()
17}
18
19pub fn katz_centrality<N, E, M>(h: &Hypergraph<N, E, M>, cutoff: usize) -> IndexMap<String, f64> {
34 let n = h.num_nodes();
35 let mut result: IndexMap<String, f64> = IndexMap::new();
36 if n == 0 {
37 return result;
38 }
39 let node_ids = h.node_ids();
40 if h.num_edges() == 0 {
41 for nid in node_ids {
42 result.insert(nid, 0.0);
43 }
44 return result;
45 }
46 let (a, _rows) = clique_motif_matrix(h);
47 let alpha = 1.0 / 2f64.powi(n as i32);
48 let mut mat = a.clone();
49 for _ in 1..cutoff {
51 mat = mat.dot(&a) * alpha + &a;
52 }
53 let u = ndarray::Array1::<f64>::from_elem(n, 1.0 / n as f64);
54 let mut c = mat.dot(&u);
55 let norm = l1(c.as_slice().unwrap());
56 if norm != 0.0 {
57 c.mapv_inplace(|x| x / norm);
58 }
59 for (i, nid) in node_ids.into_iter().enumerate() {
60 result.insert(nid, c[i]);
61 }
62 result
63}
64
65pub fn clique_eigenvector_centrality<N, E, M>(
70 h: &Hypergraph<N, E, M>,
71 tol: f64,
72 max_iter: usize,
73) -> IndexMap<String, f64> {
74 let mut result: IndexMap<String, f64> = IndexMap::new();
75 if h.num_nodes() == 0 {
76 return result;
77 }
78 let node_ids = h.node_ids();
79 if !is_connected(h) {
80 for nid in node_ids {
81 result.insert(nid, f64::NAN);
82 }
83 return result;
84 }
85 let (w, _rows) = clique_motif_matrix(h);
86 let n = node_ids.len();
87 let mut v = ndarray::Array1::<f64>::from_elem(n, 1.0 / n as f64);
88 for _ in 0..max_iter {
90 let mut next = w.dot(&v);
91 let norm2 = next.dot(&next).sqrt();
92 if norm2 == 0.0 {
93 break;
94 }
95 next.mapv_inplace(|x| x / norm2);
96 let delta = (&next - &v).mapv(|x| x * x).sum().sqrt();
97 v = next;
98 if delta < tol {
99 break;
100 }
101 }
102 let sign = if v[0] < 0.0 { -1.0 } else { 1.0 };
104 let norm1 = l1(v.as_slice().unwrap());
105 for (i, nid) in node_ids.into_iter().enumerate() {
106 result.insert(nid, sign * v[i] / norm1);
107 }
108 result
109}