@seanhogg/builderforce-memory 2026.10.56 → 2026.10.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/knowledge/build.d.ts +2 -1
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +5 -2
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/communities.d.ts +74 -0
- package/dist/knowledge/communities.d.ts.map +1 -0
- package/dist/knowledge/communities.js +143 -0
- package/dist/knowledge/communities.js.map +1 -0
- package/dist/knowledge/index.d.ts +3 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +1 -0
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/louvain.d.ts +38 -0
- package/dist/knowledge/louvain.d.ts.map +1 -0
- package/dist/knowledge/louvain.js +164 -0
- package/dist/knowledge/louvain.js.map +1 -0
- package/dist/knowledge/model.d.ts +17 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +4 -0
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/trace.d.ts.map +1 -1
- package/dist/knowledge/trace.js +24 -3
- package/dist/knowledge/trace.js.map +1 -1
- package/package.json +3 -3
- package/src/contract/exports.snapshot.json +9 -0
- package/src/contract/types.contract.test.ts +9 -1
- package/src/knowledge/build.test.ts +1 -1
- package/src/knowledge/build.ts +5 -2
- package/src/knowledge/communities.test.ts +322 -0
- package/src/knowledge/communities.ts +167 -0
- package/src/knowledge/index.ts +6 -1
- package/src/knowledge/louvain.ts +147 -0
- package/src/knowledge/model.ts +21 -1
- package/src/knowledge/outline.test.ts +17 -5
- package/src/knowledge/outline.ts +4 -0
- package/src/knowledge/trace.ts +24 -4
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/communities.test.ts
|
|
3
|
+
* PRD 38 P1: Louvain communities over the file reference graph (code `references` and docs `links`), the
|
|
4
|
+
* label-propagation fallback above the cap, the membership confidence, determinism, the placement helper
|
|
5
|
+
* and that an unreferenced file gets no badge. Hand computations are in the comments.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
applyCommunities, communityTable, COMMUNITY_EDGE_KINDS, detectCommunities, placementOf,
|
|
10
|
+
} from './communities.js';
|
|
11
|
+
import { buildGraph } from './build.js';
|
|
12
|
+
import { buildAdjacency, localMoving } from './louvain.js';
|
|
13
|
+
import { buildOutline } from './outline.js';
|
|
14
|
+
import type { BuildGraphInput, KNode, KnowledgeGraph } from './model.js';
|
|
15
|
+
import { traceGraph } from './trace.js';
|
|
16
|
+
import { edge, extractedOf, fileNode, ref } from './testkit.test-util.js';
|
|
17
|
+
|
|
18
|
+
const E = (a: string, b: string, weight = 1) => ({ from: ref(a), to: ref(b), weight });
|
|
19
|
+
const same = (a: unknown, b: unknown) => expect(JSON.stringify(a)).toBe(JSON.stringify(b));
|
|
20
|
+
|
|
21
|
+
/** Two triangles, a1-a2-a3 and b1-b2-b3, joined by the single edge a3-b1. m = 7. */
|
|
22
|
+
const CLIQUES = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'].map((p) => `${p}.md`);
|
|
23
|
+
const CLIQUE_EDGES = [
|
|
24
|
+
E('a1.md', 'a2.md'), E('a2.md', 'a3.md'), E('a1.md', 'a3.md'),
|
|
25
|
+
E('b1.md', 'b2.md'), E('b2.md', 'b3.md'), E('b1.md', 'b3.md'),
|
|
26
|
+
E('a3.md', 'b1.md'),
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
describe('detectCommunities — Louvain', () => {
|
|
30
|
+
const r = detectCommunities(CLIQUES.map(ref), CLIQUE_EDGES);
|
|
31
|
+
const id = (p: string) => r.members.get(ref(p))!.communityId;
|
|
32
|
+
|
|
33
|
+
it('splits two cliques joined by one edge into two communities with Q > 0.3', () => {
|
|
34
|
+
expect(r.method).toBe('louvain');
|
|
35
|
+
expect(new Set([...r.members.values()].map((m) => m.communityId)).size).toBe(2);
|
|
36
|
+
expect(id('a1.md')).toBe(id('a3.md'));
|
|
37
|
+
expect(id('b1.md')).toBe(id('b3.md'));
|
|
38
|
+
expect(id('a1.md')).not.toBe(id('b1.md'));
|
|
39
|
+
expect(r.modularity).toBeGreaterThan(0.3);
|
|
40
|
+
// Hand computed: 2 × (3/7 − (7/14)²) = 0.357143.
|
|
41
|
+
expect(r.modularity).toBe(0.357143);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('community ids are indexes by smallest member path', () => {
|
|
45
|
+
expect(id('a2.md')).toBe(0);
|
|
46
|
+
expect(id('b3.md')).toBe(1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('confidence is the share of a file\'s edge weight inside its community', () => {
|
|
50
|
+
expect(r.members.get(ref('a1.md'))!.confidence).toBe(1);
|
|
51
|
+
// a3: two edges inside (a1, a2), one out (b1) → 2/3.
|
|
52
|
+
expect(r.members.get(ref('a3.md'))!.confidence).toBe(0.666667);
|
|
53
|
+
expect(r.members.get(ref('b1.md'))!.confidence).toBe(0.666667);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('sums both directions and weights by reference count', () => {
|
|
57
|
+
const weighted = detectCommunities(CLIQUES.map(ref), [...CLIQUE_EDGES, E('b1.md', 'a3.md', 5)]);
|
|
58
|
+
// Hand computed: the a3-b1 bridge weighs 1 + 5 = 6 (m = 12), so a3 and b1 form one community
|
|
59
|
+
// ({a1,a2}, {a3,b1}, {b2,b3}; Q = 0.166667 beats the two triangles' Q = 0). Each has 6 of its 8 edge weight inside.
|
|
60
|
+
const w = (p: string) => weighted.members.get(ref(p))!;
|
|
61
|
+
expect(w('a3.md').communityId).toBe(w('b1.md').communityId);
|
|
62
|
+
expect([w('a1.md').communityId, w('a3.md').communityId, w('b2.md').communityId]).toEqual([0, 1, 2]);
|
|
63
|
+
expect(w('a3.md').confidence).toBe(0.75);
|
|
64
|
+
expect(w('b1.md').confidence).toBe(0.75);
|
|
65
|
+
expect(weighted.modularity).toBe(0.166667);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('a file with no references gets no membership', () => {
|
|
69
|
+
const withIsolated = detectCommunities([...CLIQUES, 'lonely.md'].map(ref), CLIQUE_EDGES);
|
|
70
|
+
expect(withIsolated.members.has(ref('lonely.md'))).toBe(false);
|
|
71
|
+
expect(withIsolated.members.size).toBe(6);
|
|
72
|
+
expect(withIsolated.modularity).toBe(r.modularity);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('no edges: nothing is assigned and Q is 0', () => {
|
|
76
|
+
const none = detectCommunities(CLIQUES.map(ref), []);
|
|
77
|
+
expect(none.members.size).toBe(0);
|
|
78
|
+
expect(none.modularity).toBe(0);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('ignores self references and non-positive weights', () => {
|
|
82
|
+
const noisy = detectCommunities(CLIQUES.map(ref), [...CLIQUE_EDGES, E('a1.md', 'a1.md', 9), E('a1.md', 'b3.md', 0)]);
|
|
83
|
+
same([...noisy.members], [...r.members]);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('shuffled input gives byte-identical output', () => {
|
|
87
|
+
const shuffled = detectCommunities([...CLIQUES].reverse().map(ref), [...CLIQUE_EDGES].reverse().map((e) => ({ ...e })));
|
|
88
|
+
same([...shuffled.members], [...r.members]);
|
|
89
|
+
expect(shuffled.modularity).toBe(r.modularity);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('a ring of ten triangles: the second level merges neighbouring cliques', () => {
|
|
93
|
+
// Clique i is ci{a,b,c}; ci-c links to c(i+1)-a. m = 10 × 3 + 10 = 40, 2m = 80, every clique has degree sum 8.
|
|
94
|
+
// Level 1 forms the ten cliques. Level 2 (nodes of degree 8, self-loop 3, ring edges of weight 1): node 0 joins 1 on a
|
|
95
|
+
// 0.2 gain (1 − 8·8/80), 2 joins 3, … so five pairs. Level 3 (degree 16): 1 − 16·16/80 < 0, no further merge.
|
|
96
|
+
// Q = 5 × (14/80 − (16/80)²) = 0.675.
|
|
97
|
+
const nm = (i: number, x: string) => `c${String(i).padStart(2, '0')}${x}.md`;
|
|
98
|
+
const files: string[] = [];
|
|
99
|
+
const links: ReturnType<typeof E>[] = [];
|
|
100
|
+
for (let i = 0; i < 10; i++) {
|
|
101
|
+
files.push(nm(i, 'a'), nm(i, 'b'), nm(i, 'c'));
|
|
102
|
+
links.push(E(nm(i, 'a'), nm(i, 'b')), E(nm(i, 'b'), nm(i, 'c')), E(nm(i, 'a'), nm(i, 'c')), E(nm(i, 'c'), nm((i + 1) % 10, 'a')));
|
|
103
|
+
}
|
|
104
|
+
const ring = detectCommunities(files.map(ref), links);
|
|
105
|
+
const c = (p: string) => ring.members.get(ref(p))!;
|
|
106
|
+
expect(new Set([...ring.members.values()].map((m) => m.communityId)).size).toBe(5);
|
|
107
|
+
expect(c(nm(0, 'a')).communityId).toBe(c(nm(1, 'c')).communityId);
|
|
108
|
+
expect(c(nm(0, 'a')).communityId).not.toBe(c(nm(2, 'a')).communityId);
|
|
109
|
+
expect([0, 2, 4, 6, 8].map((i) => c(nm(i, 'a')).communityId)).toEqual([0, 1, 2, 3, 4]);
|
|
110
|
+
// c00a has 2 of its 3 links inside the pair (the third comes from c09c); c00c has all 3 (its bridge goes to c01a).
|
|
111
|
+
expect(c(nm(0, 'a')).confidence).toBe(0.666667);
|
|
112
|
+
expect(c(nm(0, 'c')).confidence).toBe(1);
|
|
113
|
+
expect(ring.modularity).toBe(0.675);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('a tie keeps the lowest community id', () => {
|
|
117
|
+
// a0-a1 and b0-b1 weigh 5; x links a1 and b0 with 1 each. Degrees: a0 5, a1 6, b0 6, b1 5, x 2; 2m = 24.
|
|
118
|
+
// x has the same gain on both sides (1 − 11·2/24 = 0.083), so the lowest id (the a side) wins; confidence 1/2.
|
|
119
|
+
const tie = detectCommunities(
|
|
120
|
+
['a0', 'a1', 'b0', 'b1', 'x'].map((p) => ref(`${p}.md`)),
|
|
121
|
+
[E('a0.md', 'a1.md', 5), E('b0.md', 'b1.md', 5), E('a1.md', 'x.md'), E('x.md', 'b0.md')],
|
|
122
|
+
);
|
|
123
|
+
const t = (p: string) => tie.members.get(ref(p))!;
|
|
124
|
+
expect([t('a0.md').communityId, t('a1.md').communityId, t('x.md').communityId]).toEqual([0, 0, 0]);
|
|
125
|
+
expect([t('b0.md').communityId, t('b1.md').communityId]).toEqual([1, 1]);
|
|
126
|
+
expect(t('x.md').confidence).toBe(0.5);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe('detectCommunities — label propagation above the cap', () => {
|
|
131
|
+
const TRIANGLES = ['x1', 'x2', 'x3', 'y1', 'y2', 'y3'].map((p) => `${p}.md`);
|
|
132
|
+
const TRI_EDGES = [
|
|
133
|
+
E('x1.md', 'x2.md'), E('x2.md', 'x3.md'), E('x1.md', 'x3.md'),
|
|
134
|
+
E('y1.md', 'y2.md'), E('y2.md', 'y3.md'), E('y1.md', 'y3.md'),
|
|
135
|
+
];
|
|
136
|
+
|
|
137
|
+
it('finds the exact partition of two disjoint triangles', () => {
|
|
138
|
+
// Sorted labels x1..y3 = 0..5. x1 hears labels 1 and 2 (tie → smallest, 1); x2 keeps 1 on a tie; x3 hears 1 twice. Same for y with 4.
|
|
139
|
+
const r = detectCommunities(TRIANGLES.map(ref), TRI_EDGES, 4);
|
|
140
|
+
expect(r.method).toBe('label-propagation');
|
|
141
|
+
expect([...r.members].map(([k, m]) => [k, m.communityId, m.confidence])).toEqual(
|
|
142
|
+
TRIANGLES.map((p, i) => [ref(p), i < 3 ? 0 : 1, 1]),
|
|
143
|
+
);
|
|
144
|
+
// 2 × (6/12 − (6/12)²) = 0.5
|
|
145
|
+
expect(r.modularity).toBe(0.5);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('is deterministic under shuffled input', () => {
|
|
149
|
+
const a = detectCommunities(CLIQUES.map(ref), CLIQUE_EDGES, 4);
|
|
150
|
+
const b = detectCommunities([...CLIQUES].reverse().map(ref), [...CLIQUE_EDGES].reverse(), 4);
|
|
151
|
+
expect(a.method).toBe('label-propagation');
|
|
152
|
+
same([...b.members], [...a.members]);
|
|
153
|
+
expect(a.modularity).toBe(b.modularity);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('a node keeps its own label when it is the larger of two tied labels', () => {
|
|
157
|
+
// Path p0 - p1 - p3 - p2 (edges p0-p1, p1-p3, p2-p3), labels start as the sorted index 0..3. One sweep:
|
|
158
|
+
// p0 hears {1} and takes 1; p1 hears {1 (p0), 3 (p3)}, holds 1 and keeps it; p2 hears {3} and takes 3;
|
|
159
|
+
// p3 hears {1 (p1), 3 (p2)} equally while holding 3, so it KEEPS 3. (A "smallest label wins" rule would give it 1
|
|
160
|
+
// and merge everything into one community.) The second sweep changes nothing.
|
|
161
|
+
const r = detectCommunities(
|
|
162
|
+
['p0', 'p1', 'p2', 'p3'].map((p) => ref(`${p}.md`)),
|
|
163
|
+
[E('p0.md', 'p1.md'), E('p1.md', 'p3.md'), E('p2.md', 'p3.md')],
|
|
164
|
+
2,
|
|
165
|
+
);
|
|
166
|
+
expect(r.method).toBe('label-propagation');
|
|
167
|
+
expect([...r.members.values()].map((m) => [m.communityId, m.confidence])).toEqual([[0, 1], [0, 0.5], [1, 1], [1, 0.5]]);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
describe('Louvain tie rule', () => {
|
|
172
|
+
it('a node stays put when its own community ties a lower-id one', () => {
|
|
173
|
+
// a-b 12, b-d 7, c-d 1 (a..d = indexes 0..3). Degrees a 12, b 19, c 1, d 8; 2m = 40. Sweep 1: a joins b; b stays (6.3 against 3.2);
|
|
174
|
+
// c joins d. d, in {c,d} (id 3), then weighs staying (1 − 1·8/40 = 0.8) against {a,b} (id 1: 7 − 31·8/40 = 0.8): an exact
|
|
175
|
+
// tie, so it stays. A rule that sent ties to the lowest id would pull d into {a,b}.
|
|
176
|
+
const order = ['a', 'b', 'c', 'd'].map((p) => ref(`${p}.md`));
|
|
177
|
+
const adj = buildAdjacency(order, [E('a.md', 'b.md', 12), E('b.md', 'd.md', 7), E('c.md', 'd.md', 1)]);
|
|
178
|
+
const { comm, moved } = localMoving(adj, [0, 0, 0, 0], 40);
|
|
179
|
+
expect(moved).toBe(true);
|
|
180
|
+
expect(comm).toEqual([0, 0, 1, 1]);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
describe('applyCommunities / buildGraph', () => {
|
|
185
|
+
/** Two triangles in d1/ and d2/ joined by one edge; `lonely.md` has no edges. `kind` is the edge kind of every reference. */
|
|
186
|
+
function input(kind: string): BuildGraphInput {
|
|
187
|
+
const files = ['d1/a.md', 'd1/b.md', 'd1/c.md', 'd2/a.md', 'd2/b.md', 'd2/c.md', 'lonely.md'];
|
|
188
|
+
const pairs: Array<[string, string]> = [
|
|
189
|
+
['d1/a.md', 'd1/b.md'], ['d1/b.md', 'd1/c.md'], ['d1/a.md', 'd1/c.md'],
|
|
190
|
+
['d2/a.md', 'd2/b.md'], ['d2/b.md', 'd2/c.md'], ['d2/a.md', 'd2/c.md'], ['d1/c.md', 'd2/a.md'],
|
|
191
|
+
];
|
|
192
|
+
return {
|
|
193
|
+
rootId: 'r', packs: [],
|
|
194
|
+
extracted: files.map((p) => extractedOf(fileNode(p), pairs.filter(([f]) => f === p).map(([f, t]) => edge(f, t, kind)))),
|
|
195
|
+
facts: [], relations: [],
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
it('counts both `references` and `links`', () => {
|
|
200
|
+
expect(COMMUNITY_EDGE_KINDS).toEqual(['references', 'links']);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it.each(['references', 'links'])('a %s-only graph is clustered, reports Q and the method, and leaves an unreferenced file bare', (kind) => {
|
|
204
|
+
const g = buildGraph(input(kind));
|
|
205
|
+
const node = (p: string) => g.nodes.find((n) => n.ref === ref(p))!;
|
|
206
|
+
expect(node('d1/b.md').badges).toMatchObject({ communityId: 0, communityConfidence: 1 });
|
|
207
|
+
expect(node('d2/b.md').badges).toMatchObject({ communityId: 1 });
|
|
208
|
+
expect(node('d1/c.md').badges?.['communityConfidence']).toBe(0.666667);
|
|
209
|
+
expect(node('lonely.md').badges).toBeUndefined();
|
|
210
|
+
expect(g.stats.modularity).toBe(0.357143);
|
|
211
|
+
expect(g.stats.communityMethod).toBe('louvain');
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it('other edge kinds and stale relations are not references', () => {
|
|
215
|
+
const nodes = CLIQUES.map((p) => fileNode(p));
|
|
216
|
+
const q = applyCommunities(nodes, [
|
|
217
|
+
edge('a1.md', 'a2.md', 'mentions'), edge('a2.md', 'a3.md', 'near-duplicate'), edge('a1.md', 'a3.md', 'links', { stale: true }),
|
|
218
|
+
]);
|
|
219
|
+
expect(q.modularity).toBe(0);
|
|
220
|
+
expect(nodes.every((n) => n.badges === undefined)).toBe(true);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it('equal input in a different order builds byte-identical graphs', () => {
|
|
224
|
+
const base = input('links');
|
|
225
|
+
const rev = { ...base, extracted: [...base.extracted].reverse().map((e) => ({ ...e, edges: [...e.edges].reverse() })) };
|
|
226
|
+
same(buildGraph(rev), buildGraph(base));
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('the outline carries the badges and a labelled communities table', () => {
|
|
230
|
+
const o = buildOutline(buildGraph(input('links')));
|
|
231
|
+
expect(o.files.find((x) => x.path.endsWith('d1/c.md'))!.badges).toEqual({ communityId: 0, communityConfidence: 0.666667 });
|
|
232
|
+
expect(o.files.find((x) => x.path.endsWith('lonely.md'))!.badges).toBeUndefined();
|
|
233
|
+
expect(o.communities).toEqual([{ id: 0, label: 'd1', size: 3 }, { id: 1, label: 'd2', size: 3 }]);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it('the cut graph keeps modularity in its stats', () => {
|
|
237
|
+
const g = buildGraph(input('links'), { maxNodes: 3 });
|
|
238
|
+
expect(g.stats.truncated).toBe(true);
|
|
239
|
+
expect(g.stats.modularity).toBe(0.357143);
|
|
240
|
+
expect(g.outline!.communities!.length).toBe(2);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe('communityTable', () => {
|
|
245
|
+
it('labels a community with its common directory, else with its most important member', () => {
|
|
246
|
+
const mk = (p: string, importance: number) => fileNode(p, { importance, badges: { communityId: 0 } });
|
|
247
|
+
expect(communityTable([mk('src/a/x.ts', 0.1), mk('src/a/y.ts', 0.2)])).toEqual([{ id: 0, label: 'src/a', size: 2 }]);
|
|
248
|
+
expect(communityTable([mk('src/x.ts', 0.1), mk('lib/y.ts', 0.9)])).toEqual([{ id: 0, label: 'lib/y.ts', size: 2 }]);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('builds the label from the outline-relative path (prefix stripped)', () => {
|
|
252
|
+
const n = fileNode('src/a/x.ts', { badges: { communityId: 0 } });
|
|
253
|
+
expect(communityTable([n], 'src:r::')).toEqual([{ id: 0, label: 'src/a', size: 1 }]);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it('makes labels unique: top member basename first, then a numeric suffix', () => {
|
|
257
|
+
const mk = (p: string, id: number, importance: number) => fileNode(p, { importance, badges: { communityId: id } });
|
|
258
|
+
// Communities 0 and 1 share the directory 'src', so each gets its top member's basename; 2 and 3 are already distinct.
|
|
259
|
+
const table = communityTable([
|
|
260
|
+
mk('src/a.ts', 0, 0.9), mk('src/b.ts', 0, 0.1),
|
|
261
|
+
mk('src/c.ts', 1, 0.9), mk('src/d.ts', 1, 0.1),
|
|
262
|
+
mk('src/lib/x.ts', 2, 0.9), mk('src/lib/y.ts', 2, 0.1),
|
|
263
|
+
mk('doc/z.md', 3, 0.5),
|
|
264
|
+
]);
|
|
265
|
+
expect(table.map((c) => c.label)).toEqual(['src · a.ts', 'src · c.ts', 'src/lib', 'doc']);
|
|
266
|
+
expect(new Set(table.map((c) => c.label)).size).toBe(table.length);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it('falls back to a numeric suffix when the top member name also collides', () => {
|
|
270
|
+
const mk = (p: string, id: number) => fileNode(p, { badges: { communityId: id } });
|
|
271
|
+
// Both communities are {src/index.ts + a sibling in src}: same directory, same top basename (ties → smaller ref first).
|
|
272
|
+
const table = communityTable([mk('src/index.ts', 0), mk('src/x.ts', 0), mk('src/index.ts', 1), mk('src/y.ts', 1)]);
|
|
273
|
+
expect(table.map((c) => c.label)).toEqual(['src · index.ts', 'src · index.ts 2']);
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
describe('placementOf', () => {
|
|
278
|
+
it('is the partition when there is one, else the community, else nothing', () => {
|
|
279
|
+
expect(placementOf({ partition: 'domain', badges: { communityId: 3 } })).toEqual({ kind: 'partition', id: 'domain' });
|
|
280
|
+
expect(placementOf({ badges: { communityId: 3, communityConfidence: 0.5 } })).toEqual({ kind: 'community', id: 3 });
|
|
281
|
+
expect(placementOf({ badges: { complexity: 4 } })).toBeUndefined();
|
|
282
|
+
expect(placementOf({})).toBeUndefined();
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it('a trace puts an unpartitioned file in its community lane', () => {
|
|
286
|
+
const g = buildGraph(input2());
|
|
287
|
+
const t = traceGraph(g, ref('d1/a.md'), { edgeKinds: ['links'] });
|
|
288
|
+
expect(t.laneOf[ref('d1/a.md')]).toBe('community 0');
|
|
289
|
+
expect(t.laneOf[ref('d2/a.md')]).toBe('community 1');
|
|
290
|
+
expect(t.lanes).not.toContain('(none)');
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('with a registry the lanes are partitions first, then communities by numeric id', () => {
|
|
294
|
+
const mk = (p: string, extra: Partial<KNode>) => fileNode(p, extra);
|
|
295
|
+
const g: KnowledgeGraph = {
|
|
296
|
+
scope: { rootId: 'r', packs: [], digest: 'd' },
|
|
297
|
+
nodes: [
|
|
298
|
+
mk('a.ts', { badges: { communityId: 10 } }), mk('b.ts', { badges: { communityId: 2 } }),
|
|
299
|
+
mk('c.ts', { partition: 'domain' }), mk('d.ts', {}),
|
|
300
|
+
],
|
|
301
|
+
edges: [edge('a.ts', 'b.ts', 'links'), edge('b.ts', 'c.ts', 'links'), edge('c.ts', 'd.ts', 'links')],
|
|
302
|
+
findings: [], stats: { sources: 4, nodes: 4, edges: 3, stale: 0, truncated: false },
|
|
303
|
+
};
|
|
304
|
+
const t = traceGraph(g, ref('a.ts'), { edgeKinds: ['links'], registry: { partitions: [{ id: 'domain', order: 0, match: [] }], allow: {} } });
|
|
305
|
+
// 'community 10' sorts before 'community 2' as text; by number it comes after.
|
|
306
|
+
expect(t.lanes).toEqual(['domain', 'community 2', 'community 10', '(none)']);
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
/** d1/a → d1/b → d1/c → d2/a → d2/b, plus the closing links, so both folders cluster. */
|
|
311
|
+
function input2(): BuildGraphInput {
|
|
312
|
+
const pairs: Array<[string, string]> = [
|
|
313
|
+
['d1/a.md', 'd1/b.md'], ['d1/b.md', 'd1/c.md'], ['d1/a.md', 'd1/c.md'], ['d1/c.md', 'd2/a.md'],
|
|
314
|
+
['d2/a.md', 'd2/b.md'], ['d2/b.md', 'd2/c.md'], ['d2/a.md', 'd2/c.md'],
|
|
315
|
+
];
|
|
316
|
+
const files = ['d1/a.md', 'd1/b.md', 'd1/c.md', 'd2/a.md', 'd2/b.md', 'd2/c.md'];
|
|
317
|
+
return {
|
|
318
|
+
rootId: 'r', packs: [],
|
|
319
|
+
extracted: files.map((p) => extractedOf(fileNode(p), pairs.filter(([f]) => f === p).map(([f, t]) => edge(f, t, 'links')))),
|
|
320
|
+
facts: [], relations: [],
|
|
321
|
+
};
|
|
322
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/communities.ts — deterministic community detection over the FILE reference graph
|
|
3
|
+
* (PRD 38 P1: a placement for every file the packs could not place, plus a membership confidence).
|
|
4
|
+
*
|
|
5
|
+
* Louvain modularity maximisation: Q = (1/2m) Σᵢⱼ [Aᵢⱼ − kᵢkⱼ/2m] δ(cᵢ,cⱼ), over the undirected graph
|
|
6
|
+
* whose edge weight is the reference count (both directions summed). Above COMMUNITY_LOUVAIN_MAX_NODES
|
|
7
|
+
* connected files, deterministic label propagation is the fallback. The algorithms live in louvain.ts.
|
|
8
|
+
*
|
|
9
|
+
* Determinism: see louvain.ts; edge weights are merged and summed in a fixed order. Same input (in any
|
|
10
|
+
* order) gives byte-identical output.
|
|
11
|
+
*
|
|
12
|
+
* A file with no references is in no community (absent, never a guess; no folder fallback).
|
|
13
|
+
*
|
|
14
|
+
* Community ids are indexes (0.. in order of each community's smallest member path). They are NOT stable
|
|
15
|
+
* across builds: a changed graph can renumber them. A consumer keeps the id only together with the graph
|
|
16
|
+
* (the outline's `communities` table) that it indexes, never as a long-lived key.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { KEdge, KNode, NodeRef, OutlineCommunity } from './model.js';
|
|
20
|
+
import {
|
|
21
|
+
buildAdjacency, COMMUNITY_LP_ITERATIONS, COMMUNITY_MAX_ITERATIONS, COMMUNITY_MAX_PASSES, degreeOf, labelPropagation,
|
|
22
|
+
louvain, modularityOf,
|
|
23
|
+
} from './louvain.js';
|
|
24
|
+
import { basenameOf, compareStr, fileRefOf, pathOfRef, round6 } from './refs.js';
|
|
25
|
+
|
|
26
|
+
export { COMMUNITY_LP_ITERATIONS, COMMUNITY_MAX_ITERATIONS, COMMUNITY_MAX_PASSES };
|
|
27
|
+
|
|
28
|
+
/** Above this many connected files label propagation replaces Louvain. Separate from the outline cap. */
|
|
29
|
+
export const COMMUNITY_LOUVAIN_MAX_NODES = 20000;
|
|
30
|
+
/** The file-to-file edge kinds that count as a reference between two files (code `references`, docs `links`). */
|
|
31
|
+
export const COMMUNITY_EDGE_KINDS: readonly string[] = ['references', 'links'];
|
|
32
|
+
|
|
33
|
+
export type CommunityMethod = 'louvain' | 'label-propagation';
|
|
34
|
+
|
|
35
|
+
export interface CommunityMembership {
|
|
36
|
+
/** Index of the community: 0.. by smallest member path. Not stable across builds. */
|
|
37
|
+
communityId: number;
|
|
38
|
+
/** Share of this file's edge weight that falls inside its community, 0..1. */
|
|
39
|
+
confidence: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CommunityResult {
|
|
43
|
+
/** Only files with at least one reference appear. */
|
|
44
|
+
members: Map<NodeRef, CommunityMembership>;
|
|
45
|
+
/** Q of the returned partition, rounded to 6 decimals (0 with no edges). */
|
|
46
|
+
modularity: number;
|
|
47
|
+
method: CommunityMethod;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Where a node sits on the map: the pack's partition when it has one, else its community. */
|
|
51
|
+
export type NodePlacement = { kind: 'partition'; id: string } | { kind: 'community'; id: number };
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Communities over `edges` (any direction; both summed). `maxNodes` is the number of connected files above
|
|
55
|
+
* which label propagation replaces Louvain.
|
|
56
|
+
*/
|
|
57
|
+
export function detectCommunities(
|
|
58
|
+
refs: readonly NodeRef[],
|
|
59
|
+
edges: ReadonlyArray<{ from: NodeRef; to: NodeRef; weight: number }>,
|
|
60
|
+
maxNodes: number = COMMUNITY_LOUVAIN_MAX_NODES,
|
|
61
|
+
): CommunityResult {
|
|
62
|
+
const order = [...new Set(refs)].sort(compareStr);
|
|
63
|
+
const adj = buildAdjacency(order, edges);
|
|
64
|
+
const connected = order.map((_, i) => i).filter((i) => adj[i]!.size > 0);
|
|
65
|
+
const method: CommunityMethod = connected.length > maxNodes ? 'label-propagation' : 'louvain';
|
|
66
|
+
const comm = connected.length === 0 ? order.map((_, i) => i) : method === 'louvain' ? louvain(adj) : labelPropagation(adj);
|
|
67
|
+
|
|
68
|
+
// Ids by first appearance over the sorted connected files: community 0 holds the smallest path.
|
|
69
|
+
const idOf = new Map<number, number>();
|
|
70
|
+
const members = new Map<NodeRef, CommunityMembership>();
|
|
71
|
+
for (const i of connected) {
|
|
72
|
+
if (!idOf.has(comm[i]!)) idOf.set(comm[i]!, idOf.size);
|
|
73
|
+
let inside = 0;
|
|
74
|
+
for (const [j, w] of adj[i]!) if (comm[j] === comm[i]) inside += w;
|
|
75
|
+
members.set(order[i]!, { communityId: idOf.get(comm[i]!)!, confidence: round6(inside / degreeOf(adj[i]!)) });
|
|
76
|
+
}
|
|
77
|
+
return { members, modularity: modularityOf(adj, comm), method };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* File-to-file links of the chosen kinds, merged per ordered pair. The weights of a pair are summed in ascending
|
|
82
|
+
* order, so the total never depends on the order the edges arrive in (the sort across pairs is `buildAdjacency`'s).
|
|
83
|
+
*/
|
|
84
|
+
function fileLinks(files: ReadonlySet<NodeRef>, edges: Iterable<KEdge>): Array<{ from: NodeRef; to: NodeRef; weight: number }> {
|
|
85
|
+
const pairs = new Map<string, { from: NodeRef; to: NodeRef; weights: number[] }>();
|
|
86
|
+
for (const e of edges) {
|
|
87
|
+
if (!COMMUNITY_EDGE_KINDS.includes(e.kind) || e.stale) continue;
|
|
88
|
+
const from = fileRefOf(e.from), to = fileRefOf(e.to);
|
|
89
|
+
if (!files.has(from) || !files.has(to)) continue;
|
|
90
|
+
const key = `${from}\u0000${to}`;
|
|
91
|
+
const hit = pairs.get(key);
|
|
92
|
+
if (hit) hit.weights.push(e.weight);
|
|
93
|
+
else pairs.set(key, { from, to, weights: [e.weight] });
|
|
94
|
+
}
|
|
95
|
+
return [...pairs.values()].map((p) => ({
|
|
96
|
+
from: p.from, to: p.to, weight: p.weights.sort((a, b) => a - b).reduce((s, w) => s + w, 0),
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The one call `buildGraph` makes: stamps `communityId` / `communityConfidence` badges on file nodes that
|
|
102
|
+
* have references (file-to-file edges of COMMUNITY_EDGE_KINDS, stale relations skipped) and returns Q and
|
|
103
|
+
* the method for the graph stats.
|
|
104
|
+
*/
|
|
105
|
+
export function applyCommunities(nodes: Iterable<KNode>, edges: Iterable<KEdge>): { modularity: number; method: CommunityMethod } {
|
|
106
|
+
const files = new Map<NodeRef, KNode>();
|
|
107
|
+
for (const n of nodes) if (n.kind === 'file') files.set(n.ref, n);
|
|
108
|
+
const { members, modularity, method } = detectCommunities([...files.keys()], fileLinks(new Set(files.keys()), edges));
|
|
109
|
+
for (const [ref, m] of members) {
|
|
110
|
+
const n = files.get(ref)!;
|
|
111
|
+
n.badges = { ...n.badges, communityId: m.communityId, communityConfidence: m.confidence };
|
|
112
|
+
}
|
|
113
|
+
return { modularity, method };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The ONE placement of a node: its partition, else its community, else none (never a guess). */
|
|
117
|
+
export function placementOf(node: Pick<KNode, 'partition' | 'badges'>): NodePlacement | undefined {
|
|
118
|
+
if (node.partition !== undefined) return { kind: 'partition', id: node.partition };
|
|
119
|
+
const id = node.badges?.['communityId'];
|
|
120
|
+
return typeof id === 'number' ? { kind: 'community', id } : undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Longest directory shared by every path ('' when none). */
|
|
124
|
+
function commonDirectory(paths: readonly string[]): string {
|
|
125
|
+
const dirs = paths.map((p) => p.split('/').slice(0, -1));
|
|
126
|
+
const first = dirs[0] ?? [];
|
|
127
|
+
let n = first.length;
|
|
128
|
+
for (const d of dirs) {
|
|
129
|
+
let i = 0;
|
|
130
|
+
while (i < n && d[i] === first[i]) i++;
|
|
131
|
+
n = i;
|
|
132
|
+
}
|
|
133
|
+
return first.slice(0, n).join('/');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The outline's `communities` table for the given file nodes: id, a label and the member count, sorted by id.
|
|
138
|
+
* The label is the members' longest common directory (else the path of the most important member), built from
|
|
139
|
+
* the outline-relative path (`prefix` stripped, like `OutlineFile.path`). Labels are unique: two communities with
|
|
140
|
+
* the same label get ` · <top member basename>` appended, then a numeric suffix if they still collide.
|
|
141
|
+
*/
|
|
142
|
+
export function communityTable(files: readonly KNode[], prefix = ''): OutlineCommunity[] {
|
|
143
|
+
const groups = new Map<number, KNode[]>();
|
|
144
|
+
for (const n of files) {
|
|
145
|
+
const id = n.badges?.['communityId'];
|
|
146
|
+
if (typeof id !== 'number') continue;
|
|
147
|
+
const list = groups.get(id) ?? [];
|
|
148
|
+
list.push(n);
|
|
149
|
+
groups.set(id, list);
|
|
150
|
+
}
|
|
151
|
+
const relative = (n: KNode): string => (prefix !== '' && n.ref.startsWith(prefix) ? n.ref.slice(prefix.length) : (pathOfRef(n.ref) ?? n.ref));
|
|
152
|
+
const rows = [...groups.keys()].sort((a, b) => a - b).map((id) => {
|
|
153
|
+
const members = groups.get(id)!;
|
|
154
|
+
const top = [...members].sort((a, b) => b.importance - a.importance || compareStr(a.ref, b.ref))[0]!;
|
|
155
|
+
const topPath = relative(top);
|
|
156
|
+
return { id, size: members.length, base: commonDirectory(members.map(relative)) || topPath, topName: basenameOf(topPath) };
|
|
157
|
+
});
|
|
158
|
+
const count = new Map<string, number>();
|
|
159
|
+
for (const r of rows) count.set(r.base, (count.get(r.base) ?? 0) + 1);
|
|
160
|
+
const withTop = rows.map((r) => ({ ...r, label: count.get(r.base)! > 1 ? `${r.base} · ${r.topName}` : r.base }));
|
|
161
|
+
const seen = new Map<string, number>();
|
|
162
|
+
return withTop.map((r) => {
|
|
163
|
+
const n = (seen.get(r.label) ?? 0) + 1;
|
|
164
|
+
seen.set(r.label, n);
|
|
165
|
+
return { id: r.id, label: n === 1 ? r.label : `${r.label} ${n}`, size: r.size };
|
|
166
|
+
});
|
|
167
|
+
}
|
package/src/knowledge/index.ts
CHANGED
|
@@ -11,7 +11,7 @@ export type {
|
|
|
11
11
|
PartitionRule, PartitionRegistry, JudgementSpec, JudgementRequest, JudgedClaim, JudgedEntity, JudgementResult,
|
|
12
12
|
JudgementPort, AnalyzerPort, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord,
|
|
13
13
|
KnowledgeStore, DirectorySource, LiveOverlay, KnowledgeGraph, ReviewPlan, ReviewProgress, ReviewReport,
|
|
14
|
-
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile,
|
|
14
|
+
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile, OutlineCommunity,
|
|
15
15
|
GraphSystem, GraphApp, GraphReadSkip,
|
|
16
16
|
} from './model.js';
|
|
17
17
|
export {
|
|
@@ -23,6 +23,11 @@ export { buildGraph, graphDigest, oneLineLabel, DEFAULT_MAX_NODES, MAX_NODES_CAP
|
|
|
23
23
|
export { placeInSystem, crossesSystems, type SystemPlacement } from './systems.js';
|
|
24
24
|
export { truncateGraph, TRUNCATION_HARD_CAP, UNANCHORED_AREA } from './truncate.js';
|
|
25
25
|
export type { TruncateOptions } from './truncate.js';
|
|
26
|
+
export {
|
|
27
|
+
detectCommunities, applyCommunities, communityTable, placementOf, COMMUNITY_EDGE_KINDS, COMMUNITY_LOUVAIN_MAX_NODES,
|
|
28
|
+
COMMUNITY_MAX_PASSES, COMMUNITY_MAX_ITERATIONS, COMMUNITY_LP_ITERATIONS,
|
|
29
|
+
} from './communities.js';
|
|
30
|
+
export type { CommunityMembership, CommunityMethod, CommunityResult, NodePlacement } from './communities.js';
|
|
26
31
|
export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
|
|
27
32
|
export {
|
|
28
33
|
loadPartitions, partitionOf, partitionOrder, verdictOf, globToRegExp, matchGlob, TOP_LEVEL_FOLDER,
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/louvain.ts — the community-detection algorithms behind communities.ts: Louvain modularity
|
|
3
|
+
* maximisation and deterministic label propagation, over an undirected weighted adjacency. Pure; internal
|
|
4
|
+
* to the knowledge module (the public surface is communities.ts).
|
|
5
|
+
*
|
|
6
|
+
* Determinism: nodes are visited in index order; at most COMMUNITY_MAX_PASSES aggregation passes of at most
|
|
7
|
+
* COMMUNITY_MAX_ITERATIONS sweeps; a node stays put on a tie, otherwise the lowest community id wins;
|
|
8
|
+
* no randomness.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { NodeRef } from './model.js';
|
|
12
|
+
import { compareStr, round6 } from './refs.js';
|
|
13
|
+
|
|
14
|
+
export const COMMUNITY_MAX_PASSES = 10;
|
|
15
|
+
export const COMMUNITY_MAX_ITERATIONS = 20;
|
|
16
|
+
export const COMMUNITY_LP_ITERATIONS = 20;
|
|
17
|
+
const EPS = 1e-12;
|
|
18
|
+
|
|
19
|
+
export type Adj = Array<Map<number, number>>;
|
|
20
|
+
|
|
21
|
+
/** Undirected weighted graph over the sorted refs; self-references and non-positive weights are dropped. */
|
|
22
|
+
export function buildAdjacency(order: readonly NodeRef[], edges: ReadonlyArray<{ from: NodeRef; to: NodeRef; weight: number }>): Adj {
|
|
23
|
+
const index = new Map(order.map((r, i) => [r, i] as const));
|
|
24
|
+
const adj: Adj = order.map(() => new Map());
|
|
25
|
+
// Sorted, so the floating-point sums are the same whatever order the edges arrive in.
|
|
26
|
+
const sorted = [...edges].sort((x, y) => compareStr(x.from, y.from) || compareStr(x.to, y.to) || x.weight - y.weight);
|
|
27
|
+
for (const e of sorted) {
|
|
28
|
+
const a = index.get(e.from), b = index.get(e.to);
|
|
29
|
+
if (a === undefined || b === undefined || a === b || !(e.weight > 0)) continue;
|
|
30
|
+
adj[a]!.set(b, (adj[a]!.get(b) ?? 0) + e.weight);
|
|
31
|
+
adj[b]!.set(a, (adj[b]!.get(a) ?? 0) + e.weight);
|
|
32
|
+
}
|
|
33
|
+
return adj;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const degreeOf = (m: Map<number, number>): number => {
|
|
37
|
+
let s = 0;
|
|
38
|
+
for (const w of m.values()) s += w;
|
|
39
|
+
return s;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Community ids renumbered 0.. in order of first appearance, so the next level is order-independent. */
|
|
43
|
+
function relabel(comm: readonly number[]): { labels: number[]; count: number } {
|
|
44
|
+
const next = new Map<number, number>();
|
|
45
|
+
const labels = comm.map((c) => {
|
|
46
|
+
if (!next.has(c)) next.set(c, next.size);
|
|
47
|
+
return next.get(c)!;
|
|
48
|
+
});
|
|
49
|
+
return { labels, count: next.size };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* One Louvain level: each node moves to the neighbouring community with the best modularity gain. It moves only
|
|
54
|
+
* for a strictly better gain (a tie keeps it where it is; among tied better communities the lowest id wins).
|
|
55
|
+
* `self` is each node's internal weight (aggregated levels), `twoM` the total degree.
|
|
56
|
+
*/
|
|
57
|
+
export function localMoving(adj: Adj, self: readonly number[], twoM: number): { comm: number[]; count: number; moved: boolean } {
|
|
58
|
+
const n = adj.length;
|
|
59
|
+
const comm = Array.from({ length: n }, (_, i) => i);
|
|
60
|
+
const k = adj.map((m, i) => degreeOf(m) + 2 * self[i]!);
|
|
61
|
+
const tot = [...k];
|
|
62
|
+
let moved = false;
|
|
63
|
+
for (let it = 0; it < COMMUNITY_MAX_ITERATIONS; it++) {
|
|
64
|
+
let changed = false;
|
|
65
|
+
for (let i = 0; i < n; i++) {
|
|
66
|
+
const own = comm[i]!;
|
|
67
|
+
const links = new Map<number, number>();
|
|
68
|
+
for (const [j, w] of adj[i]!) links.set(comm[j]!, (links.get(comm[j]!) ?? 0) + w);
|
|
69
|
+
tot[own]! -= k[i]!;
|
|
70
|
+
const gain = (c: number) => (links.get(c) ?? 0) - (tot[c]! * k[i]!) / twoM;
|
|
71
|
+
let best = own, bestGain = gain(own);
|
|
72
|
+
for (const c of [...links.keys()].sort((a, b) => a - b)) {
|
|
73
|
+
if (c === own) continue;
|
|
74
|
+
const g = gain(c);
|
|
75
|
+
if (g > bestGain + EPS) { best = c; bestGain = g; }
|
|
76
|
+
}
|
|
77
|
+
tot[best]! += k[i]!;
|
|
78
|
+
if (best !== own) { comm[i] = best; changed = true; moved = true; }
|
|
79
|
+
}
|
|
80
|
+
if (!changed) break;
|
|
81
|
+
}
|
|
82
|
+
const { labels, count } = relabel(comm);
|
|
83
|
+
return { comm: labels, count, moved };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Louvain: local moving, then aggregation, up to COMMUNITY_MAX_PASSES; returns a community label per node. */
|
|
87
|
+
export function louvain(adj0: Adj): number[] {
|
|
88
|
+
let adj = adj0;
|
|
89
|
+
let self: number[] = adj0.map(() => 0);
|
|
90
|
+
const twoM = adj0.reduce((s, m) => s + degreeOf(m), 0);
|
|
91
|
+
let membership = adj0.map((_, i) => i);
|
|
92
|
+
for (let pass = 0; pass < COMMUNITY_MAX_PASSES; pass++) {
|
|
93
|
+
const { comm, count, moved } = localMoving(adj, self, twoM);
|
|
94
|
+
if (!moved) break;
|
|
95
|
+
membership = membership.map((c) => comm[c]!);
|
|
96
|
+
const nextAdj: Adj = Array.from({ length: count }, () => new Map());
|
|
97
|
+
const nextSelf: number[] = new Array<number>(count).fill(0);
|
|
98
|
+
for (let i = 0; i < adj.length; i++) {
|
|
99
|
+
nextSelf[comm[i]!]! += self[i]!;
|
|
100
|
+
for (const [j, w] of adj[i]!) {
|
|
101
|
+
const a = comm[i]!, b = comm[j]!;
|
|
102
|
+
if (a === b) nextSelf[a]! += w / 2; // each internal pair is seen from both ends
|
|
103
|
+
else nextAdj[a]!.set(b, (nextAdj[a]!.get(b) ?? 0) + w);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
adj = nextAdj;
|
|
107
|
+
self = nextSelf;
|
|
108
|
+
if (count === 1) break;
|
|
109
|
+
}
|
|
110
|
+
return membership;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Deterministic label propagation: sorted order, each node takes the heaviest neighbour label; it keeps its own on a tie, else the smallest label wins. */
|
|
114
|
+
export function labelPropagation(adj: Adj): number[] {
|
|
115
|
+
const label = adj.map((_, i) => i);
|
|
116
|
+
for (let it = 0; it < COMMUNITY_LP_ITERATIONS; it++) {
|
|
117
|
+
let changed = false;
|
|
118
|
+
for (let i = 0; i < adj.length; i++) {
|
|
119
|
+
const votes = new Map<number, number>();
|
|
120
|
+
for (const [j, w] of adj[i]!) votes.set(label[j]!, (votes.get(label[j]!) ?? 0) + w);
|
|
121
|
+
let best = label[i]!, bestW = votes.get(best) ?? 0;
|
|
122
|
+
for (const l of [...votes.keys()].sort((a, b) => a - b)) {
|
|
123
|
+
if (votes.get(l)! > bestW + EPS) { best = l; bestW = votes.get(l)!; }
|
|
124
|
+
}
|
|
125
|
+
if (best !== label[i]) { label[i] = best; changed = true; }
|
|
126
|
+
}
|
|
127
|
+
if (!changed) break;
|
|
128
|
+
}
|
|
129
|
+
return label;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Q = Σc [Lc/m − (Dc/2m)²] for a partition of the undirected graph, 6 decimals. */
|
|
133
|
+
export function modularityOf(adj: Adj, comm: readonly number[]): number {
|
|
134
|
+
let twoM = 0;
|
|
135
|
+
const inside = new Map<number, number>(), degree = new Map<number, number>();
|
|
136
|
+
for (let i = 0; i < adj.length; i++) {
|
|
137
|
+
for (const [j, w] of adj[i]!) {
|
|
138
|
+
twoM += w;
|
|
139
|
+
degree.set(comm[i]!, (degree.get(comm[i]!) ?? 0) + w);
|
|
140
|
+
if (comm[i] === comm[j]) inside.set(comm[i]!, (inside.get(comm[i]!) ?? 0) + w);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (twoM === 0) return 0;
|
|
144
|
+
let q = 0;
|
|
145
|
+
for (const [c, d] of degree) q += (inside.get(c) ?? 0) / twoM - (d / twoM) ** 2;
|
|
146
|
+
return round6(q);
|
|
147
|
+
}
|