Skip to main content

hypergraph_rs/communities/
mod.rs

1//! Spectral community detection ported from `xgi/communities/spectral.py`.
2//!
3//! `spectral_clustering` builds the normalized hypergraph Laplacian (formula from the
4//! Phase-3 `linalg/laplacian_matrix.py`, inlined here for self-containment), extracts the
5//! `k` smallest-eigenvalue eigenvectors via hand-rolled power iteration + Hotelling
6//! deflation (the dependency probe found no LAPACK-free ndarray eigensolver), and runs
7//! Forgy k-means. Exact XGI parity is impossible (RNG divergence, spec §9.4); assertions
8//! are structural, and results are deterministic under a fixed `seed`.
9
10use indexmap::IndexMap;
11use ndarray::{Array1, Array2};
12use rand::RngExt;
13use rand_core::SeedableRng;
14use rand_pcg::Pcg64Mcg;
15use thiserror::Error;
16
17use crate::Hypergraph;
18
19/// Errors raised by spectral clustering.
20#[derive(Debug, Clone, Error, PartialEq)]
21pub enum SpectralError {
22    /// More clusters were requested than there are nodes.
23    #[error("cannot request {k} clusters from a hypergraph with {n} nodes")]
24    TooManyClusters { k: usize, n: usize },
25    /// The hypergraph has an isolated node (the normalized Laplacian divides by degree).
26    #[error("every node must belong to an edge (isolated node breaks the normalized Laplacian)")]
27    IsolatedNode,
28}
29
30/// The dense normalized hypergraph Laplacian and its row→node-id map.
31///
32/// XGI parity: `normalized_hypergraph_laplacian` (`linalg/laplacian_matrix.py:187-254`),
33/// unweighted. `L = I − Dv^{-1/2} H De^{-1} Hᵀ Dv^{-1/2}`, with `Dv` = node degrees,
34/// `De` = edge sizes. Errors on any isolated node.
35pub fn normalized_laplacian(h: &Hypergraph) -> Result<(Array2<f64>, Vec<String>), SpectralError> {
36    let node_ids = h.node_ids();
37    let edge_ids = h.edge_ids();
38    let n = node_ids.len();
39    let m = edge_ids.len();
40
41    // Node index map.
42    let mut node_pos = std::collections::HashMap::new();
43    for (i, id) in node_ids.iter().enumerate() {
44        node_pos.insert(id.clone(), i);
45    }
46
47    // Incidence (n x m), edge sizes De (m), node degrees Dv (n).
48    let mut incidence = Array2::<f64>::zeros((n, m));
49    let mut de = vec![0.0_f64; m];
50    let mut dv = vec![0.0_f64; n];
51    for (j, e) in edge_ids.iter().enumerate() {
52        let members = h.members(e).unwrap_or_default();
53        for member in &members {
54            let i = node_pos[member];
55            incidence[[i, j]] = 1.0;
56            de[j] += 1.0;
57            dv[i] += 1.0;
58        }
59    }
60
61    // Isolated-node guard.
62    for &d in &dv {
63        if d == 0.0 {
64            return Err(SpectralError::IsolatedNode);
65        }
66    }
67
68    // M[i][k] = Σ_j (H[i][j] H[k][j] / De[j]) · Dv[i]^{-1/2} Dv[k]^{-1/2}
69    // L = I − M.
70    let dv_invsqrt: Vec<f64> = dv.iter().map(|&d| d.powf(-0.5)).collect();
71    let mut l = Array2::<f64>::zeros((n, n));
72    for i in 0..n {
73        for k in 0..n {
74            let mut acc = 0.0_f64;
75            for j in 0..m {
76                let hij = incidence[[i, j]];
77                let hkj = incidence[[k, j]];
78                if hij != 0.0 && hkj != 0.0 {
79                    acc += hij * hkj / de[j];
80                }
81            }
82            let m_ik = acc * dv_invsqrt[i] * dv_invsqrt[k];
83            l[[i, k]] = if i == k { 1.0 - m_ik } else { -m_ik };
84        }
85    }
86
87    Ok((l, node_ids))
88}
89
90/// Dot product of two column vectors.
91#[inline]
92fn dot(a: &Array1<f64>, b: &Array1<f64>) -> f64 {
93    let mut s = 0.0;
94    for i in 0..a.len() {
95        s += a[i] * b[i];
96    }
97    s
98}
99
100/// Matrix–vector product `m · v` for a dense symmetric matrix.
101fn matvec(m: &Array2<f64>, v: &Array1<f64>) -> Array1<f64> {
102    let n = m.nrows();
103    let mut out = Array1::<f64>::zeros(n);
104    for i in 0..n {
105        let mut s = 0.0;
106        for j in 0..n {
107            s += m[[i, j]] * v[j];
108        }
109        out[i] = s;
110    }
111    out
112}
113
114/// The `k` smallest-eigenvalue eigenvectors of the symmetric matrix `l`, as columns.
115///
116/// Replaces `scipy` `eigsh(which="SA")` (`communities/spectral.py:61`). Uses power
117/// iteration on `B = cI − L` (largest of `B` = smallest of `L`) with Gram–Schmidt
118/// deflation. Convergence tolerance `1e-9`; at most 1000 iterations per eigenvector.
119/// Eigenvector signs are arbitrary. Deterministic under `seed`.
120pub fn smallest_k_eigenvectors(l: &Array2<f64>, k: usize, seed: Option<u64>) -> Array2<f64> {
121    let n = l.nrows();
122    let k = k.min(n);
123
124    // Gershgorin bound on the spectral radius: c = max_i Σ_j |L[i,j]|.
125    let mut c = 0.0_f64;
126    for i in 0..n {
127        let mut row_abs = 0.0;
128        for j in 0..n {
129            row_abs += l[[i, j]].abs();
130        }
131        if row_abs > c {
132            c = row_abs;
133        }
134    }
135    // B = cI − L.
136    let mut b = Array2::<f64>::zeros((n, n));
137    for i in 0..n {
138        for j in 0..n {
139            b[[i, j]] = if i == j { c - l[[i, j]] } else { -l[[i, j]] };
140        }
141    }
142
143    let mut rng = Pcg64Mcg::seed_from_u64(seed.unwrap_or(0));
144    let mut eigvecs: Vec<Array1<f64>> = Vec::with_capacity(k);
145
146    const TOL: f64 = 1e-9;
147    const MAX_ITER: usize = 1000;
148
149    for _ in 0..k {
150        // Random init.
151        let mut v = Array1::<f64>::zeros(n);
152        for i in 0..n {
153            v[i] = rng.random_range(0.0..1.0) - 0.5;
154        }
155        // Deflate + normalize the initial vector.
156        deflate(&mut v, &eigvecs);
157        normalize(&mut v);
158
159        for _ in 0..MAX_ITER {
160            let mut w = matvec(&b, &v);
161            deflate(&mut w, &eigvecs);
162            normalize(&mut w);
163            // Fix sign for a stable convergence check (largest-|component| positive).
164            align_sign(&mut w);
165            let mut prev = v.clone();
166            align_sign(&mut prev);
167            let mut diff = 0.0;
168            for i in 0..n {
169                diff += (w[i] - prev[i]).powi(2);
170            }
171            v = w;
172            if diff.sqrt() < TOL {
173                break;
174            }
175        }
176        eigvecs.push(v);
177    }
178
179    // Pack as columns of an n x k array.
180    let mut x = Array2::<f64>::zeros((n, k));
181    for (col, vec) in eigvecs.iter().enumerate() {
182        for i in 0..n {
183            x[[i, col]] = vec[i];
184        }
185    }
186    x
187}
188
189/// Gram–Schmidt: remove the components of `v` along each already-found eigenvector.
190fn deflate(v: &mut Array1<f64>, basis: &[Array1<f64>]) {
191    for u in basis {
192        let proj = dot(v, u);
193        for i in 0..v.len() {
194            v[i] -= proj * u[i];
195        }
196    }
197}
198
199/// Normalize `v` to unit L2 norm (no-op on a zero vector).
200fn normalize(v: &mut Array1<f64>) {
201    let norm = dot(v, v).sqrt();
202    if norm > 1e-300 {
203        for i in 0..v.len() {
204            v[i] /= norm;
205        }
206    }
207}
208
209/// Flip the sign of `v` so its largest-magnitude component is non-negative
210/// (removes the eigenvector sign ambiguity for deterministic comparison).
211fn align_sign(v: &mut Array1<f64>) {
212    let mut max_abs = 0.0;
213    let mut sign = 1.0;
214    for i in 0..v.len() {
215        if v[i].abs() > max_abs {
216            max_abs = v[i].abs();
217            sign = if v[i] < 0.0 { -1.0 } else { 1.0 };
218        }
219    }
220    if sign < 0.0 {
221        for i in 0..v.len() {
222            v[i] = -v[i];
223        }
224    }
225}
226
227/// Squared Euclidean distance between row `i` of `x` and a centroid vector.
228fn sq_dist(x: &Array2<f64>, i: usize, centroid: &[f64]) -> f64 {
229    let mut s = 0.0;
230    for d in 0..centroid.len() {
231        let diff = x[[i, d]] - centroid[d];
232        s += diff * diff;
233    }
234    s
235}
236
237/// Forgy-initialized k-means over the rows of `x`.
238///
239/// XGI parity: `_kmeans` (`communities/spectral.py:75-136`), with three deliberate
240/// deviations (see the Phase-6 plan header): correct per-dimension centroid mean,
241/// `k == 1 → 0`, and empty-cluster reseeding to the farthest point. Deterministic under
242/// `seed`. At most `max_iter` update rounds (bounded loop).
243///
244/// **Requires `k <= x.nrows()`.** `spectral_clustering` guards this at the call site
245/// (`SpectralError::TooManyClusters`); calling `kmeans` directly with `k` greater than the
246/// row count is a misuse this function does not itself validate (the Forgy-init fallback
247/// loop is bounded by row count and simply returns fewer than `k` distinct centroids).
248pub fn kmeans(x: &Array2<f64>, k: usize, max_iter: usize, seed: Option<u64>) -> Vec<usize> {
249    let n = x.nrows();
250    let dim = x.ncols();
251    if k <= 1 || n == 0 {
252        return vec![0; n];
253    }
254
255    let mut rng = Pcg64Mcg::seed_from_u64(seed.unwrap_or(0));
256
257    // Forgy init: pick k distinct rows as centroids.
258    let mut chosen: Vec<usize> = Vec::with_capacity(k);
259    let mut attempts = 0usize;
260    while chosen.len() < k && attempts < n * 100 {
261        let cand = rng.random_range(0..n);
262        if !chosen.contains(&cand) {
263            chosen.push(cand);
264        }
265        attempts += 1;
266    }
267    // Fallback: if distinct picks failed (degenerate), fill sequentially. Bounded by `n`
268    // (Power-of-10 rule 2): `kmeans` requires `k <= n`, so this loop provably terminates
269    // once `idx` reaches `n` — the `idx < n` guard is the static bound, not a safety net.
270    let mut idx = 0usize;
271    while chosen.len() < k && idx < n {
272        if !chosen.contains(&idx) {
273            chosen.push(idx);
274        }
275        idx += 1;
276    }
277    let mut centroids: Vec<Vec<f64>> = chosen
278        .iter()
279        .map(|&r| (0..dim).map(|d| x[[r, d]]).collect())
280        .collect();
281
282    let mut labels = vec![0usize; n];
283
284    for _ in 0..max_iter {
285        // Assignment step.
286        let mut new_labels = vec![0usize; n];
287        // `i` indexes `new_labels` only, but also drives `sq_dist(x, i, ...)` below;
288        // the index form is clearer than an enumerate-based rewrite here.
289        #[allow(clippy::needless_range_loop)]
290        for i in 0..n {
291            let mut best = 0usize;
292            let mut best_d = f64::INFINITY;
293            for (c, centroid) in centroids.iter().enumerate() {
294                let d = sq_dist(x, i, centroid);
295                if d < best_d {
296                    best_d = d;
297                    best = c;
298                }
299            }
300            new_labels[i] = best;
301        }
302
303        // Update step: per-dimension mean; reseed empty clusters to the farthest point.
304        let mut next = vec![vec![0.0_f64; dim]; k];
305        let mut counts = vec![0usize; k];
306        for i in 0..n {
307            let c = new_labels[i];
308            counts[c] += 1;
309            for d in 0..dim {
310                next[c][d] += x[[i, d]];
311            }
312        }
313        for c in 0..k {
314            if counts[c] > 0 {
315                // `d` indexes `next[c]` only here, but mirrors the paired
316                // accumulation loop above that indexes both `x` and `next`; the
317                // index form is clearer than an iterator adapter in context.
318                #[allow(clippy::needless_range_loop)]
319                for d in 0..dim {
320                    next[c][d] /= counts[c] as f64;
321                }
322            } else {
323                // Reseed to the point farthest from its currently-assigned centroid.
324                let mut far_i = 0usize;
325                let mut far_d = -1.0;
326                for i in 0..n {
327                    let d = sq_dist(x, i, &centroids[new_labels[i]]);
328                    if d > far_d {
329                        far_d = d;
330                        far_i = i;
331                    }
332                }
333                for d in 0..dim {
334                    next[c][d] = x[[far_i, d]];
335                }
336            }
337        }
338        centroids = next;
339
340        let changed = new_labels != labels;
341        labels = new_labels;
342        if !changed {
343            break;
344        }
345    }
346
347    labels
348}
349
350/// Spectral clustering of a hypergraph into `k` partitions.
351///
352/// XGI parity: `xgi.spectral_clustering` (`communities/spectral.py:14-72`). Builds the
353/// normalized Laplacian, embeds nodes via the `k` smallest-eigenvalue eigenvectors, and
354/// k-means-clusters them. Returns an insertion-ordered node-id→cluster map (clusters
355/// begin at 0). Deterministic under `seed`; structural (not exact-XGI) parity (§9.4).
356pub fn spectral_clustering(
357    h: &Hypergraph,
358    k: usize,
359    max_iter: usize,
360    seed: Option<u64>,
361) -> Result<IndexMap<String, usize>, SpectralError> {
362    let n = h.num_nodes();
363    if k > n {
364        return Err(SpectralError::TooManyClusters { k, n });
365    }
366    let (l, rowdict) = normalized_laplacian(h)?;
367    let x = smallest_k_eigenvectors(&l, k, seed);
368    let labels = kmeans(&x, k, max_iter, seed);
369    let mut out = IndexMap::new();
370    for (i, node_id) in rowdict.into_iter().enumerate() {
371        out.insert(node_id, labels[i]);
372    }
373    Ok(out)
374}