Skip to main content

hypergraph_rs/algorithms/
clustering.rs

1//! Nodal clustering coefficients (`xgi/algorithms/clustering.py`).
2
3use std::collections::HashSet;
4
5use indexmap::IndexMap;
6use ndarray::Axis;
7
8use crate::linalg::adjacency_matrix;
9use crate::Hypergraph;
10
11/// Clustering coefficient via the unweighted pairwise projection:
12/// `c_i = 0.5 · (A³)_ii / [k_i (k_i − 1) / 2]`, 0 when undefined.
13/// XGI parity: `clustering_coefficient` (`clustering.py:17-74`).
14pub fn clustering_coefficient<N, E, M>(h: &Hypergraph<N, E, M>) -> IndexMap<String, f64> {
15    let (adj, node_ids) = adjacency_matrix(h, None, 1, false);
16    let mut result: IndexMap<String, f64> = IndexMap::new();
17    // Nodes absent from the adjacency (isolated) get 0.
18    for n in h.node_ids() {
19        result.insert(n, 0.0);
20    }
21    if adj.shape() == [0, 0] {
22        return result;
23    }
24    let k = adj.sum_axis(Axis(1));
25    let a3 = adj.dot(&adj).dot(&adj);
26    for (i, n) in node_ids.iter().enumerate() {
27        let denom = k[i] * (k[i] - 1.0) / 2.0;
28        let c = if denom != 0.0 {
29            0.5 * a3[[i, i]] / denom
30        } else {
31            0.0
32        };
33        result.insert(n.clone(), c);
34    }
35    result
36}
37
38/// Local clustering coefficient based on edge overlap.
39/// XGI parity: `local_clustering_coefficient` (`clustering.py:77-164`).
40pub fn local_clustering_coefficient<N, E, M>(h: &Hypergraph<N, E, M>) -> IndexMap<String, f64> {
41    let mut result: IndexMap<String, f64> = IndexMap::new();
42    for n in h.node_ids() {
43        let ev = h.memberships(&n).unwrap_or_default();
44        let dv = ev.len();
45        if dv <= 1 {
46            result.insert(n, 0.0);
47            continue;
48        }
49        let mut total_eo = 0.0;
50        // Bounded: |ev| choose 2.
51        for a in 0..ev.len() {
52            for b in (a + 1)..ev.len() {
53                let edge1: HashSet<String> =
54                    h.members(&ev[a]).unwrap_or_default().into_iter().collect();
55                let edge2: HashSet<String> =
56                    h.members(&ev[b]).unwrap_or_default().into_iter().collect();
57                let d1: HashSet<String> = edge1.difference(&edge2).cloned().collect();
58                let d2: HashSet<String> = edge2.difference(&edge1).cloned().collect();
59                let union: HashSet<String> = d1.union(&d2).cloned().collect();
60                let eo = if union.is_empty() {
61                    0.0
62                } else {
63                    let neigh_d1: HashSet<String> = d1
64                        .iter()
65                        .flat_map(|d| h.node_neighbors(d).unwrap_or_default())
66                        .collect();
67                    let neigh_d2: HashSet<String> = d2
68                        .iter()
69                        .flat_map(|d| h.node_neighbors(d).unwrap_or_default())
70                        .collect();
71                    let a1 = neigh_d1.intersection(&d2).count();
72                    let a2 = neigh_d2.intersection(&d1).count();
73                    (a1 + a2) as f64 / union.len() as f64
74                };
75                total_eo += eo;
76            }
77        }
78        result.insert(n, 2.0 * total_eo / (dv as f64 * (dv as f64 - 1.0)));
79    }
80    result
81}
82
83/// Two-node clustering coefficient averaged over a node's neighbours.
84/// `kind` ∈ {"union", "min", "max"}. XGI parity:
85/// `two_node_clustering_coefficient` (`clustering.py:167-278`).
86pub fn two_node_clustering_coefficient<N, E, M>(
87    h: &Hypergraph<N, E, M>,
88    kind: &str,
89) -> IndexMap<String, f64> {
90    let mut result: IndexMap<String, f64> = IndexMap::new();
91    for n in h.node_ids() {
92        let neighbors = h.node_neighbors(&n).unwrap_or_default();
93        if neighbors.is_empty() {
94            result.insert(n, 0.0);
95            continue;
96        }
97        let m_u: HashSet<String> = h.memberships(&n).unwrap_or_default().into_iter().collect();
98        let mut acc = 0.0;
99        let count = neighbors.len() as f64;
100        for v in &neighbors {
101            let m_v: HashSet<String> = h.memberships(v).unwrap_or_default().into_iter().collect();
102            let num = m_u.intersection(&m_v).count() as f64;
103            let denom = match kind {
104                "union" => m_u.union(&m_v).count() as f64,
105                "min" => m_u.len().min(m_v.len()) as f64,
106                "max" => m_u.len().max(m_v.len()) as f64,
107                _ => panic!("invalid kind of clustering: {kind}"),
108            };
109            // Deviation #10: XGI's `_uv_cc` returns NaN here; we skip the term
110            // instead (unreachable in practice — `v` is a neighbour of `n`, so
111            // they share >=1 edge and every `kind`'s denominator is >=1).
112            if denom != 0.0 {
113                acc += (num / denom) / count;
114            }
115        }
116        result.insert(n, acc);
117    }
118    result
119}