Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

dream(performance): #3976 fallbackLouvain() communityTotal O(n^2)->O(n*deg) incremental fix

Claude0aa99cd5aad1
diff --git a/docs/dream-cycle/dream-gist-2026-10-10.md b/docs/dream-cycle/dream-gist-2026-10-10.md
new file mode 100644
index 0000000000..512e8947da
--- /dev/null
+++ b/docs/dream-cycle/dream-gist-2026-10-10.md
@@ -0,0 +1,86 @@
+# Performance SOTA Report β€” 2026-10-10
+
+TL;DR: Louvain community detection has one settled 2026 practical lesson, violated tonight: its efficiency case rests on maintaining each community's total degree *incrementally*, not recomputing it from scratch. Ruflo's `graph-analyzer.ts` did the latter β€” made worse by a correction to 2026-10-09's own recommendation to "wire the real `ruvector` graph exports into `loadRuVector()`": that premise is false. Direct inspection of the installed `[email protected]`'s 100+ real exports (and `@ruvector/gnn`'s real API) confirms no published `ruvector`/`@ruvector/wasm` version has ever exported the `hooks_graph_mincut`/`hooks_graph_cluster`/`GraphAnalyzer` surface `loadRuVector()` checks for. Nothing real to wire in β€” "native acceleration" is permanently dead in every correctly-installed environment, so the plain-JS `fallbackLouvain()`/`fallbackMinCut()` are the *only* code that ever runs. That raised the stakes on their own efficiency: `fallbackLouvain()` rebuilt a `communityTotal` map via a full O(n) node scan, once per node, once per pass β€” O(nΒ²) per pass vs. the O(nΒ·avg_degree) a correctly incrementalized pass costs. Fixed tonight.
+
+## What's New in 2026
+
+| Finding | Source | Confidence |
+|---|---|---|
+| networkx's `louvain_communities`/`_one_level` maintains per-community total degree (`Stot`) incrementally β€” `Stot[u_com] -= degree` on removal, `+= degree` on insertion β€” never rescanning all nodes | Direct read, `networkx/algorithms/community/louvain.py` (networkx.org, accessed 2026-10-10) | A |
+| python-louvain (`taynaud/python-louvain`)'s `Status.degrees`/`gdegrees` use the identical subtract/add pattern inside `__one_level`'s inner loop; full modularity only recomputed once per *pass*, not per node move | Direct read, `community/community_louvain.py` (GitHub, accessed 2026-10-10) | A |
+| Blondel et al. 2008 (arXiv:0803.0476) makes no formal Big-O claim β€” reports empirically "complexity is linear on typical and sparse data," with memory (not CPU) as the practical bottleneck at scale (12 min/39M nodes, 152 min/118M nodes) | Direct full-text read (ar5iv mirror, accessed 2026-10-10) | A |
+| igraph's own docs state no complexity bound for `community_multilevel`; the commonly-repeated "O(n log n)" figure traces only to community commentary (Wikipedia), which itself notes no rigorous published analysis exists | python.igraph.org API docs + en.wikipedia.org/wiki/Louvain_method (accessed 2026-10-10) | C |
+| graphology-communities-louvain's README claims runtime "bounded by the number of edges" (~O(m) per pass), qualitative only, no independent source-level confirmation of its incremental-vs-recompute mechanism | unpkg.com README (accessed 2026-10-10) | B |
+
+No mainstream tool surveyed β€” including the two JS/TS dependency-graph tools checked (madge, dependency-cruiser) β€” applies Louvain-style community detection to a *code*-dependency graph specifically; every implementation above targets generic/social-network graphs. Closest precedent: academic Girvan-Newman clustering of Java dependency graphs, a different algorithm, single unverified source. Noted as a genuine framing gap, not padded.
+
+## Ruflo Current Capability
+
+`v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts` builds a code-dependency graph (import/require/dynamic-import/re-export edges) and offers MinCut-based boundary detection and Louvain-based module/community detection, reachable today via the shipped `claude-flow analyze modules <dir>` CLI command (`analyze.ts`, lazy-loaded from `commands/index.ts`) β†’ `analyzeGraph()` β†’ `analyzeModuleCommunities()`.
+
+`loadRuVector()` tries to resolve "native acceleration" from `ruvector` (checking `hooks_graph_mincut`/`hooks_graph_cluster`) or `@ruvector/wasm` (checking a `GraphAnalyzer` class). Verified by direct inspection, not the code's own comments: the installed `[email protected]` (`@claude-flow/cli`'s own normal, non-optional pin) resolves and exports 100+ real functions/classes (`VectorDB`, `FlashAttention`, `buildGraph`, `calculateModularity`, `CodeGraph`, etc.) β€” but not `hooks_graph_mincut`/`hooks_graph_cluster` (`typeof` β†’ `undefined`). `@ruvector/wasm` isn't resolvable at all. `@ruvector/gnn` exists but its real API (`differentiableSearch`, `hierarchicalForward`, `RuvectorLayer`, `TensorCompress`) is GNN-embedding machinery, zero overlap with graph partitioning. **Correction to 2026-10-09's recommendation #1** ("wire the real exports in"): there's nothing real to wire in. `fallbackMinCut()`/`fallbackLouvain()` aren't a degraded-environment fallback β€” they're the only path that has ever run, in any correctly-installed environment.
+
+That raised `fallbackLouvain()`'s own efficiency to this file's top priority. Its local-moving loop rebuilt `communityTotal` from a full scan of all n nodes, inside the per-node loop β€” O(n)Γ—n = O(nΒ²) per pass, Γ—10 passes β€” when the reference implementations above (and the algorithm's design intent) maintain it incrementally, O(1) per accepted move. Fixed: `communityTotal` now initializes once before the loop and is patched by Β±`nodeDegree` on the two affected communities immediately after each accepted move β€” the existing modularity-gain arithmetic (which assumes the moving node's own degree is still counted in its current community at evaluation time) is untouched.
+
+## Competitor Comparison
+
+| Tool | Degree-sum tracking | Complexity evidence | Grade |
+|---|---|---|---|
+| networkx `louvain_communities` | Incremental (`Stot -=`/`+=` per move) | Matches near-linear-per-pass design intent | A |
+| python-louvain (Aynaud) | Incremental (`status.degrees` subtract/add) | Same pattern, independently confirmed | A |
+| igraph `community_multilevel` | Not disclosed in official docs | No official Big-O; community figure (~O(n log n)) disputed/unproven | C |
+| graphology-communities-louvain (JS) | Unconfirmed from README alone | Qualitative "bounded by edge count" claim | B |
+| madge / dependency-cruiser (JS, code-dependency-graph tools) | N/A β€” neither implements community detection at all | N/A | C |
+
+**ruflo (pre-fix)**: communityTotal recomputed from scratch per node per pass β€” O(nΒ²) per pass, the one practice every implementation above avoids. **ruflo (post-fix)**: incremental, matching the networkx/python-louvain pattern (Grade A precedent).
+
+## Hypothesis (frozen before evaluation)
+
+Given `fallbackLouvain()`'s local-moving phase, when `communityTotal` is initialized once and maintained incrementally (Β±`nodeDegree` per accepted move) instead of rebuilt via a full node scan per node, then (a) output partitions/modularity should be byte-identical to the pre-fix algorithm, and (b) wall-clock should scale near-linearly with node count at fixed average degree instead of quadratically β€” subject to: zero change to `fallbackMinCut()`, zero regression across the full suite (byte-identical failing-file set), deterministic $0 evaluation.
+
+## Benchmarks / Evaluation
+
+Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls, against a freshly `pnpm install`-ed `v3/` workspace.
+
+New test file `graph-analyzer.louvain-complexity.test.ts` (4 tests), with a frozen verbatim copy of the pre-fix algorithm (`legacyFallbackLouvain`) inline for self-contained, CI-safe comparison:
+- Byte-identical community partitions + modularity vs. the frozen pre-fix copy on two differently-shaped synthetic graphs, plus empty-graph/single-node degenerate cases.
+- Growth-ratio test (fixed avg. degree, 8x node-count): legacy must show >20x growth (true O(nΒ²) β‰ˆ64x, confirming the fixture exercises the quadratic path) and the fix's growth must stay under half that.
+- Stash-isolated independently by an adversarial critic: reverting only the source file fails the growth-ratio assertion exactly as predicted; the 3 correctness assertions still pass (reverted, both algorithms are identical).
+- Standalone `tsx` measurement (N=200→1600, 8x nodes, fixed avg. degree): baseline 10.37ms→837.29ms (~81x growth); candidate 5.00ms→22.33ms (~4.5x growth) — speedup itself grows, 2.1x→37.5x, the signature of a complexity-class fix.
+- Full `@claude-flow/cli` suite, both ways (JSON reporter, 1295 suites): candidate 3266/3632 tests passed (199 failed files), baseline 3265/3632 (200 failed files) β€” the only difference in the failed-file set between the two runs is the new test file itself (fails on baseline exactly as predicted, passes on candidate); all 199 other failures are byte-identical, pre-existing, unrelated to this change. `tsc --noEmit`: 498 pre-existing errors both ways (unbuilt sibling packages), zero new.
+
+## Darwin Results
+
+Skipped β€” binary, correctness-preserving complexity fix with no continuous/categorical parameter to search over (same skip class as nearly every accepted fix since 2026-08-18). `npx ruvector harness darwin --help` was reachable during STEP 0.5 but went transiently unreachable on retry; noted, not a blocker β€” this candidate skips regardless.
+
+## SOTA Proof & Witness
+
+See issue/PR for the full reward-hack checklist, adversarial critique (independent verdict: CONFIRMED, no blocking caveats), and security review. Witness stamp at the end of this file.
+
+## Recommended Next Steps
+
+1. **Correct `loadRuVector()`'s "fallback" framing** (not a fallback β€” the only path) via a doc/comment fix, or remove the permanently-dead native-detection branch outright in a future `ruvector-integration` night, so "wire in the real exports" isn't reproposed again.
+2. **`fallbackMinCut()`'s docstring claims "Stoer-Wagner MinCut"; it is not** β€” it's a randomized-restart maximum-adjacency heuristic with no global-minimum guarantee (real Stoer-Wagner contracts the graph per phase). Low-priority naming fix, correctness not performance, not bundled tonight.
+3. **hive-mind scan (carried, not bundled):** `v3/@claude-flow/swarm/src/consensus/raft.ts:513-578`'s `handleVoteRequest()`/`handleAppendEntries()` are a second, fully unreachable Raft receiver, only exercised by unit tests, already diverged from the real transport path (`handleInboundRaftMessage()`, lines 99-147) β€” e.g. its commit-index clamp uses `this.node.log.length` instead of `lastLogInfo().index`. False confidence in safety-critical logic. Testable-tonight-sized for a future `swarm`/`hive-mind` night.
+
+## Scan Findings: security
+
+MCP tool-result injection screening (`applyContentBoundaryGuardrail`, `mcp-client.ts` ~304-351) only scans top-level string values of a tool's return object β€” anything nested in an array/sub-object is skipped by design. `memory_search`'s real shape (`{ results: [...] }`, each entry carrying `.content`) is exactly that skipped shape, so poisoned memory content passes unfiltered even with the opt-in flag on (off by default). A separate, independently-gated AgentDB-level retrieval guard exists but isn't wired to this path. Testable-tonight-sized (bounded recursion, capped for latency) but not bundled tonight β€” flagged for a future `security` night.
+
+## Scan Findings: hive-mind
+
+See Recommended Next Steps #3 for the primary finding. Also confirmed: `AgentPool.updateAgentHeartbeat()` (`agent-pool.ts:439`), flagged as dead code by 2026-10-09's own gist, still has zero production callers as of tonight β€” the open question from last night is settled (no, it has not gained a caller).
+
+## Competitors Reviewed
+
+networkx, python-louvain (taynaud), igraph, graphology-communities-louvain, madge, dependency-cruiser (Louvain/community-detection comparison); OWASP agentic/LLM guidance (security scan).
+
+## Witness
+
+```
+Session commit (STEP 0): 6c046548e29506be9bfd6640186d6e85a444e849
+Gist SHA-256 (pre-witness, this block's filled values stripped to PENDING): c179941b356c8a09bf9b9f2d1ea4598bd1fe65d45d809823f1cf847087a41b70
+Witness stamp: 81e2148140bfe55da2e1d1ff613171d3c1d8252322c065480c7273357cf6b32e
+```
+
+Verifier: fetch this file from the branch, strip this block's filled values back to `PENDING`, SHA-256 the file, concatenate with the session commit above, SHA-256 again β€” must equal the witness stamp.
diff --git a/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts
new file mode 100644
index 0000000000..c7744632a0
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruvector/graph-analyzer.louvain-complexity.test.ts
@@ -0,0 +1,233 @@
+/**
+ * fallbackLouvain() complexity-class regression test.
+ *
+ * `loadRuVector()` never successfully resolves native acceleration against
+ * any real published `ruvector`/`@ruvector/wasm` version (confirmed: the
+ * installed `ruvector` package exports no `hooks_graph_mincut`/
+ * `hooks_graph_cluster`, and `@ruvector/wasm` isn't a resolvable package at
+ * all) β€” so `fallbackLouvain()` is the only community-detection path that
+ * ever actually runs, reached from the shipped `claude-flow analyze modules`
+ * CLI command via `analyzeGraph()` β†’ `analyzeModuleCommunities()`.
+ *
+ * `fallbackLouvain()`'s local-moving loop used to rebuild a `communityTotal`
+ * map from a full scan of every node, once per node, once per pass β€” O(n)
+ * work repeated n times per pass, i.e. O(n^2) per pass regardless of how
+ * sparse the graph is. `legacyFallbackLouvain` below is a frozen, verbatim
+ * copy of that pre-fix logic (community/degree bookkeeping identical to the
+ * current `fallbackLouvain`, only the inner-loop total computation differs)
+ * so both the correctness-parity and performance-regression assertions below
+ * are self-contained and don't depend on `git stash` during CI.
+ */
+import { describe, it, expect } from 'vitest';
+import { fallbackLouvain } from '../../src/ruvector/graph-analyzer.js';
+
+type Edge = [string, string, number];
+
+function legacyFallbackLouvain(
+ nodes: string[],
+ edges: Edge[]
+): { communities: Array<{ id: number; members: string[] }>; modularity: number } {
+ if (nodes.length === 0) return { communities: [], modularity: 0 };
+
+ const adj = new Map<string, Map<string, number>>();
+ for (const node of nodes) adj.set(node, new Map());
+ let totalWeight = 0;
+ for (const [u, v, w] of edges) {
+ if (adj.has(u) && adj.has(v)) {
+ adj.get(u)!.set(v, (adj.get(u)!.get(v) || 0) + w);
+ adj.get(v)!.set(u, (adj.get(v)!.get(u) || 0) + w);
+ totalWeight += w * 2;
+ }
+ }
+ if (totalWeight === 0) {
+ return { communities: nodes.map((n, i) => ({ id: i, members: [n] })), modularity: 0 };
+ }
+
+ const community = new Map<string, number>();
+ let nextCommunityId = 0;
+ for (const node of nodes) community.set(node, nextCommunityId++);
+
+ const degree = new Map<string, number>();
+ for (const node of nodes) {
+ let d = 0;
+ for (const [, w] of Array.from(adj.get(node)!.entries())) d += w;
+ degree.set(node, d);
+ }
+
+ let improved = true;
+ const maxIterations = 10;
+ let iteration = 0;
+
+ while (improved && iteration < maxIterations) {
+ improved = false;
+ iteration++;
+
+ for (const node of nodes) {
+ const currentCommunity = community.get(node)!;
+ const nodeAdj = adj.get(node)!;
+ const nodeDegree = degree.get(node)!;
+
+ const communityWeights = new Map<number, number>();
+ for (const [neighbor, weight] of Array.from(nodeAdj.entries())) {
+ const neighborCommunity = community.get(neighbor)!;
+ communityWeights.set(neighborCommunity, (communityWeights.get(neighborCommunity) || 0) + weight);
+ }
+
+ // The pre-fix defect: a full O(n) rebuild, inside the per-node loop.
+ const communityTotal = new Map<number, number>();
+ for (const [n, c] of Array.from(community.entries())) {
+ communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0));
+ }
+
+ let bestCommunity = currentCommunity;
+ let bestGain = 0;
+
+ for (const [targetCommunity, edgeWeight] of Array.from(communityWeights.entries())) {
+ if (targetCommunity === currentCommunity) continue;
+ const currentTotal = communityTotal.get(currentCommunity) || 0;
+ const targetTotal = communityTotal.get(targetCommunity) || 0;
+ const currentEdges = communityWeights.get(currentCommunity) || 0;
+ const gain =
+ (edgeWeight - currentEdges) / totalWeight -
+ (nodeDegree * (targetTotal - currentTotal + nodeDegree)) / (totalWeight * totalWeight);
+ if (gain > bestGain) {
+ bestGain = gain;
+ bestCommunity = targetCommunity;
+ }
+ }
+
+ if (bestCommunity !== currentCommunity) {
+ community.set(node, bestCommunity);
+ improved = true;
+ }
+ }
+ }
+
+ const communityMembers = new Map<number, string[]>();
+ for (const [node, comm] of Array.from(community.entries())) {
+ if (!communityMembers.has(comm)) communityMembers.set(comm, []);
+ communityMembers.get(comm)!.push(node);
+ }
+ const communities: Array<{ id: number; members: string[] }> = [];
+ let id = 0;
+ for (const members of Array.from(communityMembers.values())) communities.push({ id: id++, members });
+
+ let modularity = 0;
+ for (const [u, v, w] of edges) {
+ const cu = community.get(u)!;
+ const cv = community.get(v)!;
+ if (cu === cv) {
+ const du = degree.get(u)!;
+ const dv = degree.get(v)!;
+ modularity += w - (du * dv) / totalWeight;
+ }
+ }
+ modularity /= totalWeight;
+
+ return { communities, modularity };
+}
+
+/** Deterministic LCG PRNG β€” no Math.random, so fixtures are byte-identical across runs. */
+function makeRng(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 4294967296;
+ };
+}
+
+function buildClusteredGraph(
+ numClusters: number,
+ clusterSize: number,
+ seed: number
+): { nodes: string[]; edges: Edge[] } {
+ const rng = makeRng(seed);
+ const nodes: string[] = [];
+ for (let c = 0; c < numClusters; c++) {
+ for (let i = 0; i < clusterSize; i++) nodes.push(`c${c}n${i}`);
+ }
+ const edges: Edge[] = [];
+ for (let c = 0; c < numClusters; c++) {
+ const members = nodes.slice(c * clusterSize, (c + 1) * clusterSize);
+ for (let i = 0; i < members.length; i++) {
+ for (let j = i + 1; j < members.length; j++) {
+ if (rng() < 0.6) edges.push([members[i], members[j], 1]);
+ }
+ }
+ }
+ for (let c = 0; c < numClusters - 1; c++) {
+ const a = nodes[c * clusterSize + Math.floor(rng() * clusterSize)];
+ const b = nodes[(c + 1) * clusterSize + Math.floor(rng() * clusterSize)];
+ edges.push([a, b, 1]);
+ }
+ return { nodes, edges };
+}
+
+function normalize(result: { communities: Array<{ members: string[] }>; modularity: number }) {
+ const members = result.communities
+ .map(c => [...c.members].sort())
+ .sort((a, b) => (a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0));
+ return { members, modularity: Number(result.modularity.toFixed(9)) };
+}
+
+describe('fallbackLouvain complexity fix', () => {
+ it('produces byte-identical community partitions to the pre-fix algorithm', () => {
+ const { nodes, edges } = buildClusteredGraph(6, 10, 42);
+ const current = normalize(fallbackLouvain(nodes, edges));
+ const legacy = normalize(legacyFallbackLouvain(nodes, edges));
+ expect(current).toEqual(legacy);
+ // Not a degenerate all-one-community or all-singleton result.
+ expect(current.members.length).toBeGreaterThan(1);
+ expect(current.members.length).toBeLessThan(nodes.length);
+ });
+
+ it('produces byte-identical output on a second, differently-shaped graph', () => {
+ const { nodes, edges } = buildClusteredGraph(4, 25, 1337);
+ const current = normalize(fallbackLouvain(nodes, edges));
+ const legacy = normalize(legacyFallbackLouvain(nodes, edges));
+ expect(current).toEqual(legacy);
+ });
+
+ it('handles the zero-edge and single-node degenerate cases identically', () => {
+ expect(normalize(fallbackLouvain([], []))).toEqual(normalize(legacyFallbackLouvain([], [])));
+ expect(normalize(fallbackLouvain(['solo'], []))).toEqual(normalize(legacyFallbackLouvain(['solo'], [])));
+ });
+
+ it('scales near-linearly with node count at fixed average degree, unlike the pre-fix O(n^2) rebuild', () => {
+ // Fixed cluster size (20) keeps average degree roughly constant as
+ // numClusters grows, isolating the complexity-class difference from
+ // any confound where a denser graph also has a larger `communityWeights`
+ // inner loop (which is correctly O(degree) in both versions).
+ const small = buildClusteredGraph(10, 20, 7); // n=200
+ const large = buildClusteredGraph(80, 20, 7); // n=1600 (8x nodes)
+
+ function bestOf(fn: (n: string[], e: Edge[]) => unknown, nodes: string[], edges: Edge[]): number {
+ fn(nodes, edges); // warmup (JIT)
+ let best = Infinity;
+ for (let t = 0; t < 3; t++) {
+ const start = performance.now();
+ fn(nodes, edges);
+ const dur = performance.now() - start;
+ if (dur < best) best = dur;
+ }
+ return best;
+ }
+
+ const currentSmall = bestOf(fallbackLouvain, small.nodes, small.edges);
+ const currentLarge = bestOf(fallbackLouvain, large.nodes, large.edges);
+ const legacySmall = bestOf(legacyFallbackLouvain, small.nodes, small.edges);
+ const legacyLarge = bestOf(legacyFallbackLouvain, large.nodes, large.edges);
+
+ const currentGrowth = currentLarge / Math.max(currentSmall, 0.001);
+ const legacyGrowth = legacyLarge / Math.max(legacySmall, 0.001);
+
+ // 8x nodes: true O(n) would grow ~8x, true O(n^2) would grow ~64x.
+ // Generous thresholds (CI-timing headroom): fixed algorithm stays well
+ // under half the quadratic growth the legacy algorithm exhibits, and
+ // the legacy algorithm itself must show clearly super-linear growth β€”
+ // otherwise this fixture isn't actually exercising the O(n^2) path.
+ expect(legacyGrowth).toBeGreaterThan(20); // legacy is genuinely ~quadratic
+ expect(currentGrowth).toBeLessThan(legacyGrowth / 2); // fixed algorithm is materially better
+ expect(currentLarge).toBeLessThan(legacyLarge); // and strictly faster in absolute terms at n=1600
+ });
+});
diff --git a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
index b6dde4ebb2..505a73f875 100644
--- a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
+++ b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
@@ -696,6 +696,18 @@ function fallbackLouvain(
const maxIterations = 10;
let iteration = 0;
+ // Community total weighted degree. Maintained incrementally (Β±nodeDegree on
+ // each accepted move) rather than rebuilt from a full scan of `community`
+ // inside the per-node loop below β€” the rebuild was O(n) per node (O(n^2) per
+ // pass), matching neither the reference Louvain implementations (networkx's
+ // `Stot`, python-louvain's `status.degrees`, both updated in O(1) per move)
+ // nor the algorithm's own linear-on-sparse-data design intent.
+ const communityTotal = new Map<number, number>();
+ for (const node of nodes) {
+ const c = community.get(node)!;
+ communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(node) || 0));
+ }
+
while (improved && iteration < maxIterations) {
improved = false;
iteration++;
@@ -716,19 +728,17 @@ function fallbackLouvain(
);
}
- // Calculate community totals
- const communityTotal = new Map<number, number>();
- for (const [n, c] of Array.from(community.entries())) {
- communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0));
- }
-
let bestCommunity = currentCommunity;
let bestGain = 0;
for (const [targetCommunity, edgeWeight] of Array.from(communityWeights.entries())) {
if (targetCommunity === currentCommunity) continue;
- // Calculate modularity gain
+ // Calculate modularity gain. `currentTotal` still includes this
+ // node's own degree (not yet removed) β€” the `+ nodeDegree` term
+ // below backs it out, so `communityTotal` must stay un-patched for
+ // `node` until after the move decision, matching the pre-existing
+ // formula this complexity fix leaves unchanged.
const currentTotal = communityTotal.get(currentCommunity) || 0;
const targetTotal = communityTotal.get(targetCommunity) || 0;
const currentEdges = communityWeights.get(currentCommunity) || 0;
@@ -745,6 +755,8 @@ function fallbackLouvain(
if (bestCommunity !== currentCommunity) {
community.set(node, bestCommunity);
+ communityTotal.set(currentCommunity, (communityTotal.get(currentCommunity) || 0) - nodeDegree);
+ communityTotal.set(bestCommunity, (communityTotal.get(bestCommunity) || 0) + nodeDegree);
improved = true;
}
}