Skip to content

Commit 2709681

Browse files
ErichKinuyasafishamsi
authored andcommitted
fix(cluster): canonicalise edge endpoints before sorting in _partition
For an undirected graph, (a,b) and (b,a) are the same edge but networkx may yield the endpoints in either order depending on insertion order / version / hashseed, so the edge sort was keyed on a non-canonical orientation and the ordering fed to Leiden could vary across builds/machines, drifting community assignments. Sort each endpoint pair to (min,max) before the sort so the edge order is canonical; the edge set and weights are unchanged.
1 parent c60ddf7 commit 2709681

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

‎graphify/cluster.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,21 @@ def _partition(G: nx.Graph, resolution: float = 1.0) -> dict[str, int]:
108108
"""
109109
stable = nx.Graph()
110110
stable.add_nodes_from(sorted(G.nodes(), key=str))
111+
# Canonicalise the endpoint pair before sorting. On an undirected graph the
112+
# (u, v) orientation each edge is yielded with comes from adjacency
113+
# iteration, which follows CPython's per-process string-hash order - so the
114+
# SAME edge appears as (A, B) in one run and (B, A) in the next. Sorting on
115+
# the raw pair therefore does not canonicalise anything: the edge lands in a
116+
# different position, `stable` is built in a different insertion order, and
117+
# Louvain - order-sensitive even with a fixed seed - can return a different
118+
# grouping. Measured on a 914-node graph: identical input, identical
119+
# first-pass partition, but the cohesion-split pass produced 70 communities
120+
# under PYTHONHASHSEED=1 and 69 under =2. Sorting the pair itself removes
121+
# the dependency; for nx.Graph the orientation carries no meaning anyway.
111122
edge_rows = sorted(
112123
G.edges(data=True),
113124
key=lambda row: (
114-
str(row[0]),
115-
str(row[1]),
125+
*sorted((str(row[0]), str(row[1]))),
116126
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
117127
),
118128
)

0 commit comments

Comments
 (0)