Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 9 additions & 4 deletions src/leiden.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,15 @@ pub fn louvain_connected_seeded<G: GraphRef>(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<Vec<(usize, f64)>> = (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();
Expand Down Expand Up @@ -179,15 +180,19 @@ pub fn louvain_connected_weighted_seeded<G: WeightedGraph>(
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<Vec<(usize, f64)>> = (0..n)
.map(|u| {
let mut nb = graph.neighbors(u);
nb.sort_unstable();
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();
Expand Down
45 changes: 35 additions & 10 deletions src/louvain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,24 @@ 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<G: GraphRef>(graph: &G, communities: &[usize]) -> f64 {
let n = graph.node_count();
if n == 0 {
return 0.0;
}

let two_m: f64 = (0..n)
.map(|u| graph.neighbors_ref(u).len() as f64)
.sum::<f64>();
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::<f64>();

if two_m == 0.0 {
return 0.0;
Expand All @@ -37,14 +45,13 @@ pub fn modularity<G: GraphRef>(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 };
}
}
}
Expand Down Expand Up @@ -96,14 +103,15 @@ pub fn louvain_seeded<G: GraphRef>(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<Vec<(usize, f64)>> = (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();
Expand Down Expand Up @@ -192,15 +200,19 @@ pub fn louvain_weighted_seeded<G: WeightedGraph>(
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<Vec<(usize, f64)>> = (0..n)
.map(|u| {
let mut nb = graph.neighbors(u);
nb.sort_unstable();
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();
Expand Down Expand Up @@ -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![] };
Expand Down
Loading