From a5d2d2e3889ef3fea2fb261ddd7bd7c26b1e5f4c Mon Sep 17 00:00:00 2001 From: Henry Wallace Date: Wed, 4 Nov 2026 09:42:39 -0500 Subject: [PATCH] louvain+leiden: count self-loops as networkx does modularity counted a self-loop once in its node's degree and as half an internal edge, so 2m was short by one per loop. It now adds 2 to the degree and 1 to L_c; the new test matches networkx 3.7 (0.22 on a triangle with a pendant self-looped node). The four optimizers built their first-level adjacency with a self-loop at its plain weight, while aggregation stores internal edges at twice their weight. They now start a self-loop at twice its weight so both levels use one convention. Graphs without self-loops are unaffected. Checked with cargo fmt, clippy -D warnings and cargo test --all-features. Claude-Session: https://claude.ai/code/session_01UJZpXWnaKuGTdguKe8WFFv --- CHANGELOG.md | 8 ++++++++ src/leiden.rs | 13 +++++++++---- src/louvain.rs | 45 +++++++++++++++++++++++++++++++++++---------- 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e06cd7..1de4c2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +### Changed + +- Self-loops follow the networkx convention: `modularity` counts a + self-loop twice in its node's degree and once as an internal edge, and + Louvain and connectivity-refined Louvain (weighted and unweighted) start + a self-loop at twice its weight, the convention their aggregation step + already used. Graphs without self-loops are unaffected. + ### Added - `WeightedGraph::stored_weights(node)`, a defaulted method that yields every diff --git a/src/leiden.rs b/src/leiden.rs index e58725f..9a00e41 100644 --- a/src/leiden.rs +++ b/src/leiden.rs @@ -71,14 +71,15 @@ pub fn louvain_connected_seeded(graph: &G, resolution: f64, seed: u return vec![]; } - // Build initial weighted adjacency (unweighted = all 1.0). + // Build initial weighted adjacency (unweighted = all 1.0). A self-loop + // gets weight 2, the convention aggregation uses for internal edges. let mut adj: Vec> = (0..n) .map(|u| { graph .neighbors_ref(u) .iter() .filter(|&&v| v < n) - .map(|&v| (v, 1.0)) + .map(|&v| (v, if v == u { 2.0 } else { 1.0 })) .collect() }) .collect(); @@ -179,7 +180,8 @@ pub fn louvain_connected_weighted_seeded( return vec![]; } - // Build initial weighted adjacency using actual edge weights. + // Build initial weighted adjacency using actual edge weights. A + // self-loop counts twice, the convention aggregation uses. let mut adj: Vec> = (0..n) .map(|u| { let mut nb = graph.neighbors(u); @@ -187,7 +189,10 @@ pub fn louvain_connected_weighted_seeded( nb.dedup(); nb.into_iter() .filter(|&v| v < n) - .map(|v| (v, graph.edge_weight(u, v))) + .map(|v| { + let w = graph.edge_weight(u, v); + (v, if v == u { 2.0 * w } else { w }) + }) .collect() }) .collect(); diff --git a/src/louvain.rs b/src/louvain.rs index e540bc1..34b03ad 100644 --- a/src/louvain.rs +++ b/src/louvain.rs @@ -15,6 +15,9 @@ use std::collections::HashMap; /// where L_c is internal edges in community c (each undirected edge counted /// once), sigma_c is the sum of degrees, and m is the total edge count. /// +/// A self-loop `u` in `neighbors_ref(u)` adds 2 to u's degree and 1 to L_c, +/// as in networkx. +/// /// Returns 0.0 for graphs with no edges. pub fn modularity(graph: &G, communities: &[usize]) -> f64 { let n = graph.node_count(); @@ -22,9 +25,14 @@ pub fn modularity(graph: &G, communities: &[usize]) -> f64 { return 0.0; } - let two_m: f64 = (0..n) - .map(|u| graph.neighbors_ref(u).len() as f64) - .sum::(); + let degree = |u: usize| -> f64 { + graph + .neighbors_ref(u) + .iter() + .map(|&v| if v == u { 2.0 } else { 1.0 }) + .sum() + }; + let two_m: f64 = (0..n).map(degree).sum::(); if two_m == 0.0 { return 0.0; @@ -37,14 +45,13 @@ pub fn modularity(graph: &G, communities: &[usize]) -> f64 { for u in 0..n { let cu = communities[u]; - let k_u = graph.neighbors_ref(u).len() as f64; - sigma[cu] += k_u; + sigma[cu] += degree(u); for &v in graph.neighbors_ref(u) { if v >= n { continue; } if communities[v] == cu { - twice_l[cu] += 1.0; + twice_l[cu] += if v == u { 2.0 } else { 1.0 }; } } } @@ -96,14 +103,15 @@ pub fn louvain_seeded(graph: &G, resolution: f64, seed: u64) -> Vec return vec![]; } - // Build initial weighted adjacency (unweighted = all 1.0). + // Build initial weighted adjacency (unweighted = all 1.0). A self-loop + // gets weight 2, the convention aggregation uses for internal edges. let mut adj: Vec> = (0..n) .map(|u| { graph .neighbors_ref(u) .iter() .filter(|&&v| v < n) - .map(|&v| (v, 1.0)) + .map(|&v| (v, if v == u { 2.0 } else { 1.0 })) .collect() }) .collect(); @@ -192,7 +200,8 @@ pub fn louvain_weighted_seeded( return vec![]; } - // Build initial weighted adjacency using actual edge weights. + // Build initial weighted adjacency using actual edge weights. A + // self-loop counts twice, the convention aggregation uses. let mut adj: Vec> = (0..n) .map(|u| { let mut nb = graph.neighbors(u); @@ -200,7 +209,10 @@ pub fn louvain_weighted_seeded( nb.dedup(); nb.into_iter() .filter(|&v| v < n) - .map(|v| (v, graph.edge_weight(u, v))) + .map(|v| { + let w = graph.edge_weight(u, v); + (v, if v == u { 2.0 * w } else { w }) + }) .collect() }) .collect(); @@ -474,6 +486,19 @@ mod tests { ); } + #[test] + fn modularity_counts_self_loops_like_networkx() { + // Triangle 0-1-2, edge 2-3, self-loop on 3. networkx 3.x gives + // modularity(G, [{0, 1, 2}, {3}]) = 0.22 and 0.0 for one community. + let g = VecGraph { + adj: vec![vec![1, 2], vec![0, 2], vec![0, 1, 3], vec![2, 3]], + }; + let q = modularity(&g, &[0, 0, 0, 1]); + assert!((q - 0.22).abs() < 1e-12, "modularity = {q}, expected 0.22"); + let q_one = modularity(&g, &[0; 4]); + assert!(q_one.abs() < 1e-12, "one community = {q_one}, expected 0"); + } + #[test] fn louvain_empty_graph() { let g = VecGraph { adj: vec![] };