Skip to main content

hypergraph_rs/algorithms/
centrality.rs

1//! Hypergraph centralities (`xgi/algorithms/centrality.py`).
2//!
3//! Phase 3 ships the two non-tensor centralities: `katz_centrality` (power
4//! series on the clique-motif matrix) and `clique_eigenvector_centrality`
5//! (hand-rolled power iteration — no LAPACK; deviation #5). Tensor-based
6//! centralities are deferred (Open Questions).
7
8use indexmap::IndexMap;
9
10use super::connected::is_connected;
11use crate::linalg::clique_motif_matrix;
12use crate::Hypergraph;
13
14/// L1 norm of a slice.
15fn l1(v: &[f64]) -> f64 {
16    v.iter().map(|x| x.abs()).sum()
17}
18
19/// Katz centrality via the truncated power series
20/// `mat = Σ αⁱ Aⁱ⁺¹`, then `c = mat · (1/n · 1)`, L1-normalized.
21/// XGI parity: `katz_centrality(H, cutoff)` (`centrality.py:218-296`).
22///
23/// Deliberate deviation: XGI unconditionally does `c *= 1 / norm(c, 1)`
24/// (`centrality.py:294`), which divides by zero (producing inf/nan) when
25/// every node's raw score is zero. This function guards on `norm != 0.0`
26/// and leaves an all-zero vector unnormalized in that case. This is strictly
27/// saner than propagating inf/nan, and the branch is unreachable for any
28/// hypergraph with at least one edge (the `m == 0` case is short-circuited
29/// above and returns zeros directly; with `m >= 1` and `alpha > 0`, the
30/// clique-motif matrix `A` has no negative entries and `mat` accumulates
31/// strictly non-negative contributions from `A`, so `c = mat · (1/n · 1)`
32/// cannot be identically zero).
33pub 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    // Bounded loop: `cutoff` iterations.
50    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
65/// Clique-motif eigenvector centrality via power iteration.
66/// XGI parity: `clique_eigenvector_centrality(H, tol)` (`centrality.py:26-67`);
67/// deviation #5 (power iteration replaces scipy `eigsh`). Empty ⇒ empty map;
68/// disconnected ⇒ all-NaN.
69pub 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    // Power iteration (bounded by max_iter): v ← W v / ||W v||₂.
89    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    // Sign-fix + L1-normalize (XGI: `sign(v[0]) * v / norm(v, 1)`).
103    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}