@seanhogg/builderforce-memory 2026.10.70 → 2026.10.71
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 +3 -1
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +5 -1
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/coChange.d.ts +104 -0
- package/dist/knowledge/coChange.d.ts.map +1 -0
- package/dist/knowledge/coChange.js +297 -0
- package/dist/knowledge/coChange.js.map +1 -0
- package/dist/knowledge/communities.d.ts +2 -0
- package/dist/knowledge/communities.d.ts.map +1 -1
- package/dist/knowledge/communities.js +5 -1
- package/dist/knowledge/communities.js.map +1 -1
- package/dist/knowledge/index.d.ts +4 -0
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -0
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +2 -0
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +3 -1
- package/dist/knowledge/refs.js.map +1 -1
- package/dist/knowledge/sources.d.ts +1 -1
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +3 -1
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/transitions.d.ts +59 -0
- package/dist/knowledge/transitions.d.ts.map +1 -0
- package/dist/knowledge/transitions.js +90 -0
- package/dist/knowledge/transitions.js.map +1 -0
- package/dist/stats/distributions.d.ts +23 -1
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +102 -19
- package/dist/stats/distributions.js.map +1 -1
- package/dist/stats/index.d.ts +1 -1
- package/dist/stats/index.d.ts.map +1 -1
- package/dist/stats/index.js +1 -1
- package/dist/stats/index.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +20 -0
- package/src/contract/regression.assets.test.ts +4 -0
- package/src/contract/types.contract.test.ts +46 -0
- package/src/knowledge/build.ts +5 -1
- package/src/knowledge/coChange.test.ts +297 -0
- package/src/knowledge/coChange.ts +333 -0
- package/src/knowledge/communities.ts +6 -1
- package/src/knowledge/index.ts +7 -0
- package/src/knowledge/outline.ts +2 -0
- package/src/knowledge/refs.ts +4 -1
- package/src/knowledge/sources.ts +3 -1
- package/src/knowledge/transitions.test.ts +135 -0
- package/src/knowledge/transitions.ts +115 -0
- package/src/stats/distributions.ts +103 -20
- package/src/stats/index.ts +3 -0
- package/src/stats/stats.test.ts +89 -0
package/src/knowledge/outline.ts
CHANGED
|
@@ -19,6 +19,8 @@ export const OUTLINE_BADGE_KEYS: readonly string[] = [
|
|
|
19
19
|
'complexity', 'maxComplexity', 'coverage', 'churn', 'owner', 'patterns', 'cloneGroup', 'unused', 'unusedExports',
|
|
20
20
|
'entry', 'layerRule', 'unusedDependencies', 'externals', 'added', 'removed', 'changed', 'status',
|
|
21
21
|
'communityId', 'communityConfidence',
|
|
22
|
+
// PRD 38 P4 (coChange.ts): the encoded co-change partners (read with decodeCoChange) and how many no reference explains.
|
|
23
|
+
'coChange', 'coChangeHidden',
|
|
22
24
|
// An asset file (assetFile.ts): a binary file the review stores as a node, never read.
|
|
23
25
|
'asset', 'mediaType', 'size', 'oversized',
|
|
24
26
|
];
|
package/src/knowledge/refs.ts
CHANGED
|
@@ -106,9 +106,12 @@ export function basenameOf(path: string): string {
|
|
|
106
106
|
return i < 0 ? path : path.slice(i + 1);
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** Bound once: a bare `Math.round` is a global lookup per call, ~1 µs inside a vm context (jest) on hot paths. */
|
|
110
|
+
const mathRound = Math.round;
|
|
111
|
+
|
|
109
112
|
/** Rounds to 6 decimals so floating noise never reaches the JSON. */
|
|
110
113
|
export function round6(n: number): number {
|
|
111
|
-
return
|
|
114
|
+
return mathRound(n * 1e6) / 1e6;
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
/** JSON with object keys sorted and `undefined` members dropped — the canonical form for digests. */
|
package/src/knowledge/sources.ts
CHANGED
|
@@ -22,7 +22,9 @@ export const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
|
22
22
|
* owedFiles.ts for how an unfinished one is carried to the next review).
|
|
23
23
|
*/
|
|
24
24
|
// 5 (2026-11-10, PRD 43 P0b): the code pack's file nodes carry the file→file rollup of the symbol-level edge kinds.
|
|
25
|
-
|
|
25
|
+
// 6 (2026-11-10, PRD 43 P0c): the agent-tools code pack resolves tsconfig path aliases, names callback-owner symbols,
|
|
26
|
+
// emits `new X().m()` call edges and reads JSX renders as calls, so cached code extracts re-run.
|
|
27
|
+
export const EXTRACTOR_VERSION = 6;
|
|
26
28
|
/**
|
|
27
29
|
* Always ignored: VCS internals, installed dependencies, builderforce config, and lockfiles (`yarn.lock`, `Cargo.lock` …): generated,
|
|
28
30
|
* huge, and plain text — extracted they would cost judgement calls for nothing; they were never stored (once skipped as binary).
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/transitions.test.ts
|
|
3
|
+
* PRD 38 P7: station transition probabilities — row normalisation, dropped self-loops, the per-row choice of traces over
|
|
4
|
+
* reference weights, intervals only on observed (trace) rows, and the greedy most-likely walk.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
mostLikelyWalk, stationTransitions, transitionOf, transitionsFromSequences, transitionsFromWeights,
|
|
9
|
+
} from './transitions.js';
|
|
10
|
+
|
|
11
|
+
const W = (from: string, to: string, weight: number) => ({ from, to, weight });
|
|
12
|
+
const same = (a: unknown, b: unknown) => expect(JSON.stringify(a)).toBe(JSON.stringify(b));
|
|
13
|
+
/** A trace history with `k` hops A → B and `n − k` hops A → C. */
|
|
14
|
+
const traces = (k: number, n: number) => [...Array.from({ length: k }, () => ['A', 'B']), ...Array.from({ length: n - k }, () => ['A', 'C'])];
|
|
15
|
+
|
|
16
|
+
describe('transitionsFromWeights', () => {
|
|
17
|
+
const t = transitionsFromWeights([W('A', 'B', 2), W('A', 'C', 1), W('A', 'B', 1), W('A', 'A', 5), W('B', 'A', 2), W('C', 'B', 0)]);
|
|
18
|
+
|
|
19
|
+
it('sums duplicate edges, drops self-loops and non-positive weights, and row-normalises', () => {
|
|
20
|
+
expect([...t.keys()]).toEqual(['A', 'B']);
|
|
21
|
+
expect(t.get('A')!.transitions.map((h) => [h.to, h.p, h.k, h.n])).toEqual([['B', 0.75, 3, 4], ['C', 0.25, 1, 4]]);
|
|
22
|
+
expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['A', 1]]);
|
|
23
|
+
for (const row of t.values()) expect(row.transitions.reduce((s, h) => s + h.p, 0)).toBeCloseTo(1, 6);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('reference rows are not observations: they say so and carry no interval', () => {
|
|
27
|
+
for (const row of t.values()) {
|
|
28
|
+
expect(row.source).toBe('references');
|
|
29
|
+
for (const h of row.transitions) expect('low' in h || 'high' in h).toBe(false);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('rows sort p desc, then `to` asc, and shuffled input gives the same table', () => {
|
|
34
|
+
const edges = [W('S', 'z', 1), W('S', 'b', 1), W('S', 'm', 2)];
|
|
35
|
+
const a = transitionsFromWeights(edges);
|
|
36
|
+
expect(a.get('S')!.transitions.map((h) => h.to)).toEqual(['m', 'b', 'z']);
|
|
37
|
+
same([...transitionsFromWeights([...edges].reverse())], [...a]);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('transitionsFromSequences', () => {
|
|
42
|
+
it('counts first-order hops of the traces; a repeated station is not a hop', () => {
|
|
43
|
+
const t = transitionsFromSequences([['A', 'B', 'C'], ['A', 'A', 'B'], ['A', 'C']]);
|
|
44
|
+
expect(t.get('A')!.transitions.map((h) => [h.to, h.k, h.n, h.p])).toEqual([['B', 2, 3, 0.666667], ['C', 1, 3, 0.333333]]);
|
|
45
|
+
expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['C', 1]]);
|
|
46
|
+
expect(t.get('A')!.source).toBe('traces');
|
|
47
|
+
expect(t.has('C')).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('a trace hop carries the 90% Jeffreys interval: pinned at 3 of 4', () => {
|
|
51
|
+
const h = transitionOf(transitionsFromSequences(traces(3, 4)), 'A', 'B')!;
|
|
52
|
+
expect([h.p, h.low, h.high]).toEqual([0.75, 0.349293, 0.953993]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('the interval holds p (upper end 1 when every hop goes one way) and narrows with n', () => {
|
|
56
|
+
const all = transitionOf(transitionsFromSequences(traces(2, 2)), 'A', 'B')!;
|
|
57
|
+
expect([all.p, all.high]).toEqual([1, 1]);
|
|
58
|
+
expect(all.low).toBeLessThan(1);
|
|
59
|
+
const width = (k: number, n: number) => {
|
|
60
|
+
const h = transitionOf(transitionsFromSequences(traces(k, n)), 'A', 'B')!;
|
|
61
|
+
expect(h.low!).toBeLessThanOrEqual(h.p);
|
|
62
|
+
expect(h.high!).toBeGreaterThanOrEqual(h.p);
|
|
63
|
+
return h.high! - h.low!;
|
|
64
|
+
};
|
|
65
|
+
expect(width(30, 40)).toBeLessThan(width(3, 4));
|
|
66
|
+
expect(width(300, 400)).toBeLessThan(width(30, 40));
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('stationTransitions', () => {
|
|
71
|
+
it('takes a station\'s trace row over its reference row', () => {
|
|
72
|
+
const t = stationTransitions({ sequences: [['A', 'C']], weights: [W('A', 'B', 10)] });
|
|
73
|
+
expect(t.get('A')!.source).toBe('traces');
|
|
74
|
+
expect(transitionOf(t, 'A', 'C')!.p).toBe(1);
|
|
75
|
+
expect(transitionOf(t, 'A', 'B')).toBeUndefined();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('falls back per row: a station with no trace hop keeps its reference row', () => {
|
|
79
|
+
const t = stationTransitions({ sequences: [['A', 'B']], weights: [W('A', 'C', 5), W('B', 'C', 1), W('B', 'A', 3)] });
|
|
80
|
+
expect([...t].map(([from, row]) => [from, row.source])).toEqual([['A', 'traces'], ['B', 'references']]);
|
|
81
|
+
expect(t.get('B')!.transitions.map((h) => [h.to, h.p])).toEqual([['A', 0.75], ['C', 0.25]]);
|
|
82
|
+
expect(transitionOf(t, 'B', 'A')!.low).toBeUndefined();
|
|
83
|
+
expect(transitionOf(t, 'A', 'B')!.low).toBeDefined();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it.each([
|
|
87
|
+
['no sequences', undefined], ['empty sequences', []], ['one-stop traces', [['A']]], ['traces that never move', [['A', 'A']]],
|
|
88
|
+
])('is all references with %s', (_name, sequences) => {
|
|
89
|
+
const t = stationTransitions({ ...(sequences ? { sequences } : {}), weights: [W('A', 'B', 10)] });
|
|
90
|
+
expect(t.get('A')!.source).toBe('references');
|
|
91
|
+
expect(transitionOf(t, 'A', 'B')!.p).toBe(1);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('mostLikelyWalk', () => {
|
|
96
|
+
// A → B and A → C tie at 0.5 (B wins on `to`); B → A is likelier but visited, so B goes to D; D has no successor.
|
|
97
|
+
const table = transitionsFromWeights([W('A', 'C', 1), W('A', 'B', 1), W('B', 'A', 9), W('B', 'D', 1), W('C', 'E', 1)]);
|
|
98
|
+
|
|
99
|
+
it('follows the per-hop argmax, breaks ties by `to`, never revisits, and stops at a dead end', () => {
|
|
100
|
+
const w = mostLikelyWalk(table, 'A', 10);
|
|
101
|
+
expect(w.stops).toEqual(['A', 'B', 'D']);
|
|
102
|
+
expect(w.hops.map((h) => [h.to, h.p])).toEqual([['B', 0.5], ['D', 0.1]]);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('stops after maxHops', () => {
|
|
106
|
+
expect(mostLikelyWalk(table, 'A', 1).stops).toEqual(['A', 'B']);
|
|
107
|
+
expect(mostLikelyWalk(table, 'A', 0)).toEqual({ stops: ['A'], hops: [] });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('a start with no row is a walk of one stop', () => {
|
|
111
|
+
expect(mostLikelyWalk(table, 'Z', 5)).toEqual({ stops: ['Z'], hops: [] });
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('over a mixed table: trace hops carry their interval, reference hops do not', () => {
|
|
115
|
+
// A and B have trace rows (A → B → C); C has none, so its reference row (C → D) continues the walk.
|
|
116
|
+
const mixed = stationTransitions({ sequences: [['A', 'B', 'C']], weights: [W('A', 'Z', 9), W('C', 'D', 1), W('C', 'A', 0)] });
|
|
117
|
+
const w = mostLikelyWalk(mixed, 'A', 10);
|
|
118
|
+
expect(w.stops).toEqual(['A', 'B', 'C', 'D']);
|
|
119
|
+
expect(w.hops.map((h) => [h.to, h.low !== undefined, h.high !== undefined])).toEqual([['B', true, true], ['C', true, true], ['D', false, false]]);
|
|
120
|
+
expect(w.hops[0]).toMatchObject({ p: 1, high: 1 });
|
|
121
|
+
expect('low' in w.hops[2]! || 'high' in w.hops[2]!).toBe(false);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('a trace row that leads only to visited stations ends the walk; its reference row is not consulted', () => {
|
|
125
|
+
// B's traces only go back to A (visited); B's reference row would offer C, but the trace row wins for B.
|
|
126
|
+
const t = stationTransitions({ sequences: [['A', 'B', 'A']], weights: [W('B', 'C', 5)] });
|
|
127
|
+
expect(t.get('B')!.source).toBe('traces');
|
|
128
|
+
expect(mostLikelyWalk(t, 'A', 10).stops).toEqual(['A', 'B']);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('is deterministic under shuffled input', () => {
|
|
132
|
+
const shuffled = transitionsFromWeights([W('C', 'E', 1), W('B', 'D', 1), W('B', 'A', 9), W('A', 'B', 1), W('A', 'C', 1)]);
|
|
133
|
+
same(mostLikelyWalk(shuffled, 'A', 10), mostLikelyWalk(table, 'A', 10));
|
|
134
|
+
});
|
|
135
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/transitions.ts — station transition probabilities (PRD 38 P7: Simulate, "Run to end", path-strip hops).
|
|
3
|
+
*
|
|
4
|
+
* A first-order Markov chain over stations: P(j|i) = k / n, where k is the count (or weight) of i → j and n the total out
|
|
5
|
+
* of i. A station's row comes from recorded run traces when the traces have a hop out of it, otherwise from the reference
|
|
6
|
+
* weights between stations; each row says which (`source`). Self-loops are dropped (staying put is not a hop), as are
|
|
7
|
+
* non-positive weights.
|
|
8
|
+
*
|
|
9
|
+
* A trace row is an observation, so every hop carries its credible interval (`rateInterval`, ../stats). A reference row is
|
|
10
|
+
* not one, so its hops carry no interval (`low` / `high` are absent).
|
|
11
|
+
*
|
|
12
|
+
* Stations are a view concept: memory holds the formula, the view applies it to its station grouping.
|
|
13
|
+
* Deterministic: rows in station order, each row p desc then `to` asc; weights summed in ascending order.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { rateInterval } from '../stats/index.js';
|
|
17
|
+
import { compareStr, round6 } from './refs.js';
|
|
18
|
+
|
|
19
|
+
export type TransitionSource = 'traces' | 'references';
|
|
20
|
+
|
|
21
|
+
export interface StationTransition {
|
|
22
|
+
to: string;
|
|
23
|
+
/** k / n, round6. */
|
|
24
|
+
p: number;
|
|
25
|
+
/** Count (traces) or weight (references) of this hop. */
|
|
26
|
+
k: number;
|
|
27
|
+
/** Total count or weight out of the row's station. */
|
|
28
|
+
n: number;
|
|
29
|
+
/** Credible interval of p (`rateInterval(k, n)`), round6. Only on a trace row. */
|
|
30
|
+
low?: number;
|
|
31
|
+
high?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface TransitionRow {
|
|
35
|
+
source: TransitionSource;
|
|
36
|
+
transitions: readonly StationTransition[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type TransitionTable = ReadonlyMap<string, TransitionRow>;
|
|
40
|
+
|
|
41
|
+
type Weighted = ReadonlyArray<{ from: string; to: string; weight: number }>;
|
|
42
|
+
|
|
43
|
+
function tableOf(edges: Weighted, source: TransitionSource): Map<string, TransitionRow> {
|
|
44
|
+
const rows = new Map<string, Map<string, number[]>>();
|
|
45
|
+
for (const e of edges) {
|
|
46
|
+
if (e.from === e.to || !(e.weight > 0) || !Number.isFinite(e.weight)) continue;
|
|
47
|
+
const row = rows.get(e.from) ?? new Map<string, number[]>();
|
|
48
|
+
const ws = row.get(e.to) ?? [];
|
|
49
|
+
ws.push(e.weight);
|
|
50
|
+
row.set(e.to, ws);
|
|
51
|
+
rows.set(e.from, row);
|
|
52
|
+
}
|
|
53
|
+
const sum = (ws: number[]) => [...ws].sort((a, b) => a - b).reduce((s, w) => s + w, 0);
|
|
54
|
+
const table = new Map<string, TransitionRow>();
|
|
55
|
+
for (const from of [...rows.keys()].sort(compareStr)) {
|
|
56
|
+
const hops = [...rows.get(from)!].map(([to, ws]) => ({ to, k: sum(ws) }));
|
|
57
|
+
const n = sum(hops.map((h) => h.k));
|
|
58
|
+
const transitions = hops.map(({ to, k }): StationTransition => {
|
|
59
|
+
const hop = { to, p: round6(k / n), k: round6(k), n: round6(n) };
|
|
60
|
+
if (source === 'references') return hop;
|
|
61
|
+
const { low, high } = rateInterval(k, n);
|
|
62
|
+
return { ...hop, low: round6(low), high: round6(high) };
|
|
63
|
+
}).sort((a, b) => b.p - a.p || compareStr(a.to, b.to));
|
|
64
|
+
table.set(from, { source, transitions });
|
|
65
|
+
}
|
|
66
|
+
return table;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Directed reference weights, row-normalised; rows are `references` and carry no interval. */
|
|
70
|
+
export function transitionsFromWeights(edges: Weighted): TransitionTable {
|
|
71
|
+
return tableOf(edges, 'references');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** First-order Markov counts of observed station sequences (run traces); a repeated station is not a hop. */
|
|
75
|
+
export function transitionsFromSequences(sequences: ReadonlyArray<readonly string[]>): TransitionTable {
|
|
76
|
+
const hops: Array<{ from: string; to: string; weight: number }> = [];
|
|
77
|
+
for (const s of sequences) for (let i = 1; i < s.length; i++) hops.push({ from: s[i - 1]!, to: s[i]!, weight: 1 });
|
|
78
|
+
return tableOf(hops, 'traces');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Per station: its trace row when the traces have a hop out of it, else its reference row. */
|
|
82
|
+
export function stationTransitions(input: { sequences?: ReadonlyArray<readonly string[]>; weights: Weighted }): TransitionTable {
|
|
83
|
+
const traced = transitionsFromSequences(input.sequences ?? []);
|
|
84
|
+
const referenced = transitionsFromWeights(input.weights);
|
|
85
|
+
const table = new Map<string, TransitionRow>();
|
|
86
|
+
for (const from of [...new Set([...traced.keys(), ...referenced.keys()])].sort(compareStr)) {
|
|
87
|
+
table.set(from, traced.get(from) ?? referenced.get(from)!);
|
|
88
|
+
}
|
|
89
|
+
return table;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The hop from → to, if the table has it. */
|
|
93
|
+
export function transitionOf(table: TransitionTable, from: string, to: string): StationTransition | undefined {
|
|
94
|
+
return table.get(from)?.transitions.find((t) => t.to === to);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A greedy walk from `start`: at each hop the likeliest unvisited successor (ties by `to` asc), at most `maxHops`, stopping
|
|
99
|
+
* when no unvisited successor is left. Per-hop argmax, NOT the most likely whole path (no Viterbi search).
|
|
100
|
+
* A station whose trace row leads only to stations already visited ends the walk; it does not fall back to its reference row.
|
|
101
|
+
*/
|
|
102
|
+
export function mostLikelyWalk(table: TransitionTable, start: string, maxHops: number): { stops: string[]; hops: StationTransition[] } {
|
|
103
|
+
const stops = [start];
|
|
104
|
+
const hops: StationTransition[] = [];
|
|
105
|
+
const seen = new Set(stops);
|
|
106
|
+
for (let cur = start; hops.length < maxHops;) {
|
|
107
|
+
const next = table.get(cur)?.transitions.find((t) => !seen.has(t.to));
|
|
108
|
+
if (!next) break;
|
|
109
|
+
hops.push(next);
|
|
110
|
+
stops.push(next.to);
|
|
111
|
+
seen.add(next.to);
|
|
112
|
+
cur = next.to;
|
|
113
|
+
}
|
|
114
|
+
return { stops, hops };
|
|
115
|
+
}
|
|
@@ -6,6 +6,11 @@
|
|
|
6
6
|
* shape ranges Part D uses (posterior counts and sample sizes).
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
// Bound once at module scope: a bare `Math.x` is a global lookup on every call, which inside a vm context (the jest
|
|
10
|
+
// runner) costs ~1 µs each and made the inverse beta ~100× slower there; a module binding is free everywhere.
|
|
11
|
+
const { abs, exp, log, max, min, pow, sin, sqrt, PI } = Math;
|
|
12
|
+
const isFiniteNumber = Number.isFinite;
|
|
13
|
+
|
|
9
14
|
const MAX_ITER = 200;
|
|
10
15
|
const EPS = 3e-14;
|
|
11
16
|
const FPMIN = 1e-300;
|
|
@@ -17,13 +22,13 @@ function logGamma(x: number): number {
|
|
|
17
22
|
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
|
|
18
23
|
];
|
|
19
24
|
if (x < 0.5) {
|
|
20
|
-
return
|
|
25
|
+
return log(PI / sin(PI * x)) - logGamma(1 - x);
|
|
21
26
|
}
|
|
22
27
|
const z = x - 1;
|
|
23
28
|
let sum = 0.99999999999980993;
|
|
24
29
|
for (let i = 0; i < p.length; i++) sum += p[i]! / (z + i + 1);
|
|
25
30
|
const t = z + p.length - 0.5;
|
|
26
|
-
return 0.5 *
|
|
31
|
+
return 0.5 * log(2 * PI) + (z + 0.5) * log(t) - t + log(sum);
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
function betaCf(a: number, b: number, x: number): number {
|
|
@@ -32,27 +37,27 @@ function betaCf(a: number, b: number, x: number): number {
|
|
|
32
37
|
const qam = a - 1;
|
|
33
38
|
let c = 1;
|
|
34
39
|
let d = 1 - (qab * x) / qap;
|
|
35
|
-
if (
|
|
40
|
+
if (abs(d) < FPMIN) d = FPMIN;
|
|
36
41
|
d = 1 / d;
|
|
37
42
|
let h = d;
|
|
38
43
|
for (let m = 1; m <= MAX_ITER; m++) {
|
|
39
44
|
const m2 = 2 * m;
|
|
40
45
|
let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
|
|
41
46
|
d = 1 + aa * d;
|
|
42
|
-
if (
|
|
47
|
+
if (abs(d) < FPMIN) d = FPMIN;
|
|
43
48
|
c = 1 + aa / c;
|
|
44
|
-
if (
|
|
49
|
+
if (abs(c) < FPMIN) c = FPMIN;
|
|
45
50
|
d = 1 / d;
|
|
46
51
|
h *= d * c;
|
|
47
52
|
aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
|
|
48
53
|
d = 1 + aa * d;
|
|
49
|
-
if (
|
|
54
|
+
if (abs(d) < FPMIN) d = FPMIN;
|
|
50
55
|
c = 1 + aa / c;
|
|
51
|
-
if (
|
|
56
|
+
if (abs(c) < FPMIN) c = FPMIN;
|
|
52
57
|
d = 1 / d;
|
|
53
58
|
const del = d * c;
|
|
54
59
|
h *= del;
|
|
55
|
-
if (
|
|
60
|
+
if (abs(del - 1) < EPS) break;
|
|
56
61
|
}
|
|
57
62
|
return h;
|
|
58
63
|
}
|
|
@@ -61,25 +66,84 @@ function betaCf(a: number, b: number, x: number): number {
|
|
|
61
66
|
export function regularizedIncompleteBeta(x: number, a: number, b: number): number {
|
|
62
67
|
if (x <= 0) return 0;
|
|
63
68
|
if (x >= 1) return 1;
|
|
64
|
-
const bt =
|
|
65
|
-
logGamma(a + b) - logGamma(a) - logGamma(b) + a *
|
|
69
|
+
const bt = exp(
|
|
70
|
+
logGamma(a + b) - logGamma(a) - logGamma(b) + a * log(x) + b * log(1 - x),
|
|
66
71
|
);
|
|
67
72
|
if (x < (a + 1) / (a + b + 2)) return (bt * betaCf(a, b, x)) / a;
|
|
68
73
|
return 1 - (bt * betaCf(b, a, 1 - x)) / b;
|
|
69
74
|
}
|
|
70
75
|
|
|
71
|
-
/**
|
|
76
|
+
/** The inverse stops when its Newton step is below this RELATIVE to the nearer end's distance, min(x, 1 − x). */
|
|
77
|
+
const INVERSE_BETA_TOL = 1e-10;
|
|
78
|
+
/** Hard cap on the inverse's steps (each costs one I_x evaluation). */
|
|
79
|
+
const INVERSE_BETA_MAX_STEPS = 100;
|
|
80
|
+
|
|
81
|
+
/** Starting point of the inverse (Numerical Recipes 3e §6.14 `invbetai`): a normal approximation, or the tail power law below a, b = 1. */
|
|
82
|
+
function inverseBetaGuess(p: number, a: number, b: number): number {
|
|
83
|
+
if (a >= 1 && b >= 1) {
|
|
84
|
+
const pp = p < 0.5 ? p : 1 - p;
|
|
85
|
+
const t = sqrt(-2 * log(pp));
|
|
86
|
+
let x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
|
|
87
|
+
if (p < 0.5) x = -x;
|
|
88
|
+
const al = (x * x - 3) / 6;
|
|
89
|
+
const h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
|
|
90
|
+
const w = (x * sqrt(al + h)) / h - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h));
|
|
91
|
+
return a / (a + b * exp(2 * w));
|
|
92
|
+
}
|
|
93
|
+
const lna = log(a / (a + b));
|
|
94
|
+
const lnb = log(b / (a + b));
|
|
95
|
+
const t = exp(a * lna) / a;
|
|
96
|
+
const u = exp(b * lnb) / b;
|
|
97
|
+
const w = t + u;
|
|
98
|
+
return p < t / w ? pow(a * w * p, 1 / a) : 1 - pow(b * w * (1 - p), 1 / b);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The scale a tolerance is relative to: the distance to the nearer end of (0, 1), so both tails keep their digits. */
|
|
102
|
+
const nearEnd = (x: number): number => max(min(x, 1 - x), 1e-300);
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Inverse of the regularized incomplete beta: Halley steps on I_x(a, b) − p, kept inside a shrinking bracket [lo, hi].
|
|
106
|
+
* - Converged when the Newton step |f / density| is below INVERSE_BETA_TOL · min(x, 1 − x) (relative, so a quantile near 0
|
|
107
|
+
* or 1 keeps its accuracy); the step is then applied and clamped to the bracket. The test runs on the RAW step, before any
|
|
108
|
+
* bracket fallback, and a step landing exactly on a bracket end is converged too (a step under 1 ulp).
|
|
109
|
+
* - A step that leaves the bracket, or a degenerate density, falls back to the bracket's midpoint.
|
|
110
|
+
* - If INVERSE_BETA_MAX_STEPS pass without converging, plain bisection finishes the bracket to tolerance (or to the last
|
|
111
|
+
* representable midpoint): an unconverged x is never returned.
|
|
112
|
+
* Deterministic: a fixed start and a fixed sequence of steps.
|
|
113
|
+
*/
|
|
72
114
|
export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number): number {
|
|
73
115
|
if (p <= 0) return 0;
|
|
74
116
|
if (p >= 1) return 1;
|
|
117
|
+
const lnBeta = logGamma(a) + logGamma(b) - logGamma(a + b);
|
|
75
118
|
let lo = 0;
|
|
76
119
|
let hi = 1;
|
|
77
|
-
|
|
120
|
+
const guess = inverseBetaGuess(p, a, b);
|
|
121
|
+
let x = guess > 0 && guess < 1 ? guess : 0.5;
|
|
122
|
+
for (let i = 0; i < INVERSE_BETA_MAX_STEPS; i++) {
|
|
123
|
+
const f = regularizedIncompleteBeta(x, a, b) - p;
|
|
124
|
+
if (f === 0) return x;
|
|
125
|
+
if (f < 0) lo = x;
|
|
126
|
+
else hi = x;
|
|
127
|
+
const density = exp((a - 1) * log(x) + (b - 1) * log(1 - x) - lnBeta);
|
|
128
|
+
let next = -1; // outside every bracket: falls back to bisection
|
|
129
|
+
if (density > 0 && isFiniteNumber(density)) {
|
|
130
|
+
const newton = f / density;
|
|
131
|
+
next = x - newton / (1 - 0.5 * min(1, newton * ((a - 1) / x - (b - 1) / (1 - x))));
|
|
132
|
+
// Converged: judged on the undamped Newton distance (a Halley damping can shrink a far step), before any fallback.
|
|
133
|
+
if (abs(newton) < INVERSE_BETA_TOL * nearEnd(x) || next === lo || next === hi) {
|
|
134
|
+
return min(max(next, lo), hi);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (!(next > lo && next < hi)) next = (lo + hi) / 2;
|
|
138
|
+
x = next;
|
|
139
|
+
}
|
|
140
|
+
// Step cap hit: bisect the bracket to tolerance.
|
|
141
|
+
for (;;) {
|
|
78
142
|
const mid = (lo + hi) / 2;
|
|
143
|
+
if (mid <= lo || mid >= hi || hi - lo < INVERSE_BETA_TOL * nearEnd(mid)) return mid;
|
|
79
144
|
if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
|
|
80
145
|
else hi = mid;
|
|
81
146
|
}
|
|
82
|
-
return (lo + hi) / 2;
|
|
83
147
|
}
|
|
84
148
|
|
|
85
149
|
/** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
|
|
@@ -111,15 +175,15 @@ function gammaQ(a: number, x: number): number {
|
|
|
111
175
|
const an = -i * (i - a);
|
|
112
176
|
b += 2;
|
|
113
177
|
d = an * d + b;
|
|
114
|
-
if (
|
|
178
|
+
if (abs(d) < FPMIN) d = FPMIN;
|
|
115
179
|
c = b + an / c;
|
|
116
|
-
if (
|
|
180
|
+
if (abs(c) < FPMIN) c = FPMIN;
|
|
117
181
|
d = 1 / d;
|
|
118
182
|
const del = d * c;
|
|
119
183
|
h *= del;
|
|
120
|
-
if (
|
|
184
|
+
if (abs(del - 1) < EPS) break;
|
|
121
185
|
}
|
|
122
|
-
return
|
|
186
|
+
return exp(-x + a * log(x) - logGamma(a)) * h;
|
|
123
187
|
}
|
|
124
188
|
|
|
125
189
|
/** Regularized lower incomplete gamma P(a, x). */
|
|
@@ -132,9 +196,9 @@ export function regularizedIncompleteGamma(a: number, x: number): number {
|
|
|
132
196
|
for (let n = 1; n <= MAX_ITER; n++) {
|
|
133
197
|
term *= x / (a + n);
|
|
134
198
|
sum += term;
|
|
135
|
-
if (
|
|
199
|
+
if (abs(term) < abs(sum) * EPS) break;
|
|
136
200
|
}
|
|
137
|
-
return
|
|
201
|
+
return exp(-x + a * log(x) - logGamma(a)) * sum;
|
|
138
202
|
}
|
|
139
203
|
return 1 - gammaQ(a, x);
|
|
140
204
|
}
|
|
@@ -144,7 +208,7 @@ export function gammaQuantile(p: number, shape: number, scale = 1): number {
|
|
|
144
208
|
if (p <= 0) return 0;
|
|
145
209
|
if (p >= 1) return Infinity;
|
|
146
210
|
let lo = 0;
|
|
147
|
-
let hi =
|
|
211
|
+
let hi = max(shape * scale * 2, scale, 1e-9);
|
|
148
212
|
while (regularizedIncompleteGamma(shape, hi / scale) < p) {
|
|
149
213
|
hi *= 2;
|
|
150
214
|
if (hi > 1e12) break;
|
|
@@ -178,3 +242,22 @@ export function garwoodPoissonInterval(
|
|
|
178
242
|
rateHigh: high / (2 * exposure),
|
|
179
243
|
};
|
|
180
244
|
}
|
|
245
|
+
|
|
246
|
+
/** The Jeffreys prior Beta(½, ½) of {@link rateInterval}. */
|
|
247
|
+
export const RATE_PRIOR = 0.5;
|
|
248
|
+
/** Mass of {@link rateInterval}: an equal-tailed 90% interval. */
|
|
249
|
+
export const RATE_CREDIBLE_MASS = 0.9;
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The credible interval of an observed rate k of n: the equal-tailed RATE_CREDIBLE_MASS interval of the Jeffreys
|
|
253
|
+
* posterior Beta(½ + k, ½ + n − k), with Brown–Cai–DasGupta's boundary rule (low = 0 at k = 0, high = 1 at k = n) so
|
|
254
|
+
* the interval always holds k/n. THE interval of every rate a graph badge or a hop shows (PRD 38, PRD 41 D3).
|
|
255
|
+
*/
|
|
256
|
+
export function rateInterval(k: number, n: number): { low: number; high: number } {
|
|
257
|
+
const post = betaPosterior(RATE_PRIOR, RATE_PRIOR, k, n);
|
|
258
|
+
const tail = (1 - RATE_CREDIBLE_MASS) / 2;
|
|
259
|
+
return {
|
|
260
|
+
low: k <= 0 ? 0 : post.quantile(tail),
|
|
261
|
+
high: k >= n ? 1 : post.quantile(1 - tail),
|
|
262
|
+
};
|
|
263
|
+
}
|
package/src/stats/index.ts
CHANGED
package/src/stats/stats.test.ts
CHANGED
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
gammaQuantile,
|
|
27
27
|
garwoodPoissonInterval,
|
|
28
28
|
goelOkumotoMLE,
|
|
29
|
+
inverseRegularizedIncompleteBeta,
|
|
29
30
|
kaplanMeier,
|
|
30
31
|
ledoitWolfCovariance,
|
|
31
32
|
lincolnPetersenEstimate,
|
|
@@ -34,6 +35,10 @@ import {
|
|
|
34
35
|
popt,
|
|
35
36
|
prAuc,
|
|
36
37
|
psi,
|
|
38
|
+
RATE_CREDIBLE_MASS,
|
|
39
|
+
RATE_PRIOR,
|
|
40
|
+
rateInterval,
|
|
41
|
+
regularizedIncompleteBeta,
|
|
37
42
|
shannonEntropy,
|
|
38
43
|
signTestSprt,
|
|
39
44
|
thompsonRank,
|
|
@@ -292,3 +297,87 @@ describe("policies", () => {
|
|
|
292
297
|
expect([...rank].sort()).toEqual([0, 1, 2]);
|
|
293
298
|
});
|
|
294
299
|
});
|
|
300
|
+
|
|
301
|
+
describe("rateInterval", () => {
|
|
302
|
+
const r6 = (x: number) => Math.round(x * 1e6) / 1e6;
|
|
303
|
+
|
|
304
|
+
it("is the 90% equal-tailed Jeffreys interval", () => {
|
|
305
|
+
expect([RATE_PRIOR, RATE_CREDIBLE_MASS]).toEqual([0.5, 0.9]);
|
|
306
|
+
const { low, high } = rateInterval(3, 4);
|
|
307
|
+
expect([r6(low), r6(high)]).toEqual([0.349293, 0.953993]);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("pins the boundary: low 0 at k = 0, high 1 at k = n, so it always holds k/n", () => {
|
|
311
|
+
expect(rateInterval(0, 5).low).toBe(0);
|
|
312
|
+
expect(rateInterval(5, 5).high).toBe(1);
|
|
313
|
+
expect(rateInterval(5, 5).low).toBeLessThan(1);
|
|
314
|
+
expect(rateInterval(0, 5).high).toBeGreaterThan(0);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// A loose guard: ~0.2 s here; the fixed-bisection inverse it replaced took ~8 ms per call (~80 s for these).
|
|
318
|
+
it("is cheap: 10,000 distinct (k, n) solve in under 5 s, each inverting I_x to the beta quantile", () => {
|
|
319
|
+
const t0 = Date.now();
|
|
320
|
+
let checked = 0;
|
|
321
|
+
let outside = 0;
|
|
322
|
+
for (let n = 1; checked < 10_000; n++) {
|
|
323
|
+
for (let k = 0; k <= n && checked < 10_000; k++, checked++) {
|
|
324
|
+
const { low, high } = rateInterval(k, n);
|
|
325
|
+
if (!(low <= k / n && k / n <= high)) outside += 1;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const ms = Date.now() - t0;
|
|
329
|
+
expect(outside).toBe(0);
|
|
330
|
+
expect(ms).toBeLessThan(5000);
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
// Jeffreys posterior of k of n: the interval ends must sit on the 5% and 95% points and hold k/n.
|
|
334
|
+
const offQuantile = (k: number, n: number): string | undefined => {
|
|
335
|
+
const { low, high } = rateInterval(k, n);
|
|
336
|
+
const a = k + 0.5, b = n - k + 0.5;
|
|
337
|
+
const ok = low <= k / n && k / n <= high
|
|
338
|
+
&& Math.abs(regularizedIncompleteBeta(low, a, b) - 0.05) < 1e-9 && Math.abs(regularizedIncompleteBeta(high, a, b) - 0.95) < 1e-9;
|
|
339
|
+
return ok ? undefined : `${k}/${n} → [${low}, ${high}]`;
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
it("regression: a Halley step converging onto a bracket end is accepted, not bisected away (tail intervals)", () => {
|
|
343
|
+
// Before the fix: 288/289 gave low 0.986559 > high 0.984397, and 4999/5000 gave high 0.90889 (correct 0.999965).
|
|
344
|
+
expect([offQuantile(288, 289), offQuantile(4999, 5000), offQuantile(2499, 2500)]).toEqual([undefined, undefined, undefined]);
|
|
345
|
+
expect(Math.round(rateInterval(4999, 5000).high * 1e6) / 1e6).toBe(0.999965);
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("regression: every interval on the k ∈ {1, n/2, n − 1} diagonals for n ≤ 5000 is on its quantiles, quickly", () => {
|
|
349
|
+
// Before the fix 7,019 of 34,967 sampled intervals with n ≤ 5000 were wrong.
|
|
350
|
+
const t0 = Date.now();
|
|
351
|
+
const wrong: string[] = [];
|
|
352
|
+
for (let n = 2; n <= 5000; n++) {
|
|
353
|
+
for (const k of new Set([1, n >> 1, n - 1])) {
|
|
354
|
+
const off = offQuantile(k, n);
|
|
355
|
+
if (off) wrong.push(off);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
expect(wrong.slice(0, 5)).toEqual([]);
|
|
359
|
+
expect(Date.now() - t0).toBeLessThan(10_000);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it("regression: the tolerance is relative, so a quantile near 0 or 1 keeps its accuracy", () => {
|
|
363
|
+
// An absolute 1e-10 stop gave I_x = 0.0501 for (0.05, 0.5, 1e7), whose quantile is ~2e-10.
|
|
364
|
+
// (A mirror case near 1, e.g. Beta(1e7, ½), is limited by doubles: 1 − x ≈ 1e-10 has only ~6 digits next to 1.)
|
|
365
|
+
for (const [p, a, b] of [[0.05, 0.5, 1e7], [0.05, 0.5, 1e5], [0.95, 1000.5, 1.5]] as const) {
|
|
366
|
+
const x = inverseRegularizedIncompleteBeta(p, a, b);
|
|
367
|
+
expect(Math.abs(regularizedIncompleteBeta(x, a, b) - p)).toBeLessThan(1e-9);
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
it("the inverse lands on the quantile: I_x(a, b) at the returned x is p", () => {
|
|
372
|
+
for (const [p, a, b] of [[0.05, 3.5, 1.5], [0.95, 3.5, 1.5], [0.05, 12.5, 0.5], [0.95, 400.5, 100.5], [0.5, 0.5, 0.5]] as const) {
|
|
373
|
+
const x = inverseRegularizedIncompleteBeta(p, a, b);
|
|
374
|
+
expect(Math.abs(regularizedIncompleteBeta(x, a, b) - p)).toBeLessThan(1e-9);
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it("narrows as n grows at the same rate", () => {
|
|
379
|
+
const width = (k: number, n: number) => { const i = rateInterval(k, n); return i.high - i.low; };
|
|
380
|
+
expect(width(30, 40)).toBeLessThan(width(3, 4));
|
|
381
|
+
expect(width(300, 400)).toBeLessThan(width(30, 40));
|
|
382
|
+
});
|
|
383
|
+
});
|