Skip to main content

hypergraph_rs/linalg/
hypergraph_matrix.rs

1//! Incidence, adjacency, intersection-profile, degree, and clique-motif matrices.
2
3use indexmap::IndexMap;
4use ndarray::{Array1, Array2, Axis};
5use sprs::{CsMat, TriMat};
6
7use super::filtered_edge_ids;
8use crate::Hypergraph;
9
10/// Dense incidence matrix `I` (rows = nodes, cols = edges); `I[i,j] = 1`
11/// iff node `i` is a member of edge `j`.
12///
13/// XGI parity: `xgi.incidence_matrix(H, order, sparse=False, index=True)`
14/// (`hypergraph_matrix.py:64-135`). Returns a `(0, 0)` matrix with empty id
15/// vectors when there are no nodes or no (filtered) edges.
16pub fn incidence_matrix<N, E, M>(
17    h: &Hypergraph<N, E, M>,
18    order: Option<usize>,
19) -> (Array2<f64>, Vec<String>, Vec<String>) {
20    let node_ids = h.node_ids();
21    let edge_ids = filtered_edge_ids(h, order);
22    if node_ids.is_empty() || edge_ids.is_empty() {
23        return (Array2::zeros((0, 0)), Vec::new(), Vec::new());
24    }
25    let node_index: IndexMap<&str, usize> = node_ids
26        .iter()
27        .enumerate()
28        .map(|(i, n)| (n.as_str(), i))
29        .collect();
30    let mut m = Array2::<f64>::zeros((node_ids.len(), edge_ids.len()));
31    for (j, e) in edge_ids.iter().enumerate() {
32        for member in h.members(e).unwrap_or_default() {
33            if let Some(&i) = node_index.get(member.as_str()) {
34                m[[i, j]] = 1.0;
35            }
36        }
37    }
38    (m, node_ids, edge_ids)
39}
40
41/// Sparse (CSR) incidence matrix — same values and ordering as
42/// [`incidence_matrix`], as a `sprs::CsMat<f64>`.
43pub fn incidence_matrix_sparse<N, E, M>(
44    h: &Hypergraph<N, E, M>,
45    order: Option<usize>,
46) -> (CsMat<f64>, Vec<String>, Vec<String>) {
47    let node_ids = h.node_ids();
48    let edge_ids = filtered_edge_ids(h, order);
49    if node_ids.is_empty() || edge_ids.is_empty() {
50        return (CsMat::zero((0, 0)), Vec::new(), Vec::new());
51    }
52    let node_index: IndexMap<&str, usize> = node_ids
53        .iter()
54        .enumerate()
55        .map(|(i, n)| (n.as_str(), i))
56        .collect();
57    let mut tri = TriMat::<f64>::new((node_ids.len(), edge_ids.len()));
58    for (j, e) in edge_ids.iter().enumerate() {
59        for member in h.members(e).unwrap_or_default() {
60            if let Some(&i) = node_index.get(member.as_str()) {
61                tri.add_triplet(i, j, 1.0);
62            }
63        }
64    }
65    (tri.to_csr(), node_ids, edge_ids)
66}
67
68/// Adjacency matrix `A` (nodes × nodes). `A = I·Iᵀ` with the diagonal zeroed;
69/// then thresholded by `s` overlapping edges. If `weighted`, the surviving
70/// entries carry the shared-edge count; otherwise they are `1.0`.
71///
72/// XGI parity: `xgi.adjacency_matrix(H, order, s, weighted)`
73/// (`hypergraph_matrix.py:138-204`).
74pub fn adjacency_matrix<N, E, M>(
75    h: &Hypergraph<N, E, M>,
76    order: Option<usize>,
77    s: usize,
78    weighted: bool,
79) -> (Array2<f64>, Vec<String>) {
80    let (inc, node_ids, _edge_ids) = incidence_matrix(h, order);
81    if inc.shape() == [0, 0] {
82        // No (filtered) edges: XGI returns an N×N zero matrix over all nodes.
83        let n = h.num_nodes();
84        return (Array2::zeros((n, n)), h.node_ids());
85    }
86    let mut a = inc.dot(&inc.t());
87    let n = a.nrows();
88    for d in 0..n {
89        a[[d, d]] = 0.0;
90    }
91    let s = s as f64;
92    let out = a.mapv(|v| {
93        if v >= s {
94            if weighted {
95                v
96            } else {
97                1.0
98            }
99        } else {
100            0.0
101        }
102    });
103    (out, node_ids)
104}
105
106/// Weighted clique-motif matrix — `adjacency_matrix(H, None, 1, true)`.
107///
108/// XGI parity: `xgi.clique_motif_matrix(H)` (`hypergraph_matrix.py:268-299`).
109pub fn clique_motif_matrix<N, E, M>(h: &Hypergraph<N, E, M>) -> (Array2<f64>, Vec<String>) {
110    adjacency_matrix(h, None, 1, true)
111}
112
113/// Intersection profile `P = Iᵀ·I` (edges × edges). `P[a,b]` is the number of
114/// nodes shared by edges `a` and `b`; the diagonal is each edge's size.
115///
116/// XGI parity: `xgi.intersection_profile(H, order)`
117/// (`hypergraph_matrix.py:207-233`). Row ids are edge ids.
118pub fn intersection_profile<N, E, M>(
119    h: &Hypergraph<N, E, M>,
120    order: Option<usize>,
121) -> (Array2<f64>, Vec<String>) {
122    let (inc, _node_ids, edge_ids) = incidence_matrix(h, order);
123    if inc.shape() == [0, 0] {
124        return (Array2::zeros((0, 0)), Vec::new());
125    }
126    let p = inc.t().dot(&inc);
127    (p, edge_ids)
128}
129
130/// Degree vector `K` (one entry per node) = incidence row sums.
131///
132/// XGI parity: `xgi.degree_matrix(H, order)` (`hypergraph_matrix.py:236-265`).
133/// When there are no (filtered) edges, returns `zeros(num_nodes)`.
134pub fn degree_matrix<N, E, M>(
135    h: &Hypergraph<N, E, M>,
136    order: Option<usize>,
137) -> (Array1<f64>, Vec<String>) {
138    let (inc, node_ids, _edge_ids) = incidence_matrix(h, order);
139    if inc.shape() == [0, 0] {
140        return (Array1::zeros(h.num_nodes()), h.node_ids());
141    }
142    let k = inc.sum_axis(Axis(1));
143    (k, node_ids)
144}