@seanhogg/builderforce-memory 2026.10.60 → 2026.10.63
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/assetFile.d.ts +3 -1
- package/dist/knowledge/assetFile.d.ts.map +1 -1
- package/dist/knowledge/assetFile.js +2 -2
- package/dist/knowledge/assetFile.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +2 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +2 -2
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +3 -1
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +1 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/outline.js +1 -1
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +2 -0
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +2 -0
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +4 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +11 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +10 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +11 -5
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/sources.d.ts +2 -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/stats/distributions.d.ts +34 -0
- package/dist/stats/distributions.d.ts.map +1 -0
- package/dist/stats/distributions.js +180 -0
- package/dist/stats/distributions.js.map +1 -0
- package/dist/stats/estimators.d.ts +53 -0
- package/dist/stats/estimators.d.ts.map +1 -0
- package/dist/stats/estimators.js +79 -0
- package/dist/stats/estimators.js.map +1 -0
- package/dist/stats/fitting.d.ts +48 -0
- package/dist/stats/fitting.d.ts.map +1 -0
- package/dist/stats/fitting.js +209 -0
- package/dist/stats/fitting.js.map +1 -0
- package/dist/stats/index.d.ts +26 -0
- package/dist/stats/index.d.ts.map +1 -0
- package/dist/stats/index.js +18 -0
- package/dist/stats/index.js.map +1 -0
- package/dist/stats/information.d.ts +9 -0
- package/dist/stats/information.d.ts.map +1 -0
- package/dist/stats/information.js +21 -0
- package/dist/stats/information.js.map +1 -0
- package/dist/stats/multivariate.d.ts +25 -0
- package/dist/stats/multivariate.d.ts.map +1 -0
- package/dist/stats/multivariate.js +89 -0
- package/dist/stats/multivariate.js.map +1 -0
- package/dist/stats/policies.d.ts +19 -0
- package/dist/stats/policies.d.ts.map +1 -0
- package/dist/stats/policies.js +75 -0
- package/dist/stats/policies.js.map +1 -0
- package/dist/stats/prng.d.ts +11 -0
- package/dist/stats/prng.d.ts.map +1 -0
- package/dist/stats/prng.js +41 -0
- package/dist/stats/prng.js.map +1 -0
- package/dist/stats/scores.d.ts +33 -0
- package/dist/stats/scores.d.ts.map +1 -0
- package/dist/stats/scores.js +134 -0
- package/dist/stats/scores.js.map +1 -0
- package/dist/stats/tests.d.ts +48 -0
- package/dist/stats/tests.d.ts.map +1 -0
- package/dist/stats/tests.js +143 -0
- package/dist/stats/tests.js.map +1 -0
- package/dist/stats/timeSeries.d.ts +34 -0
- package/dist/stats/timeSeries.d.ts.map +1 -0
- package/dist/stats/timeSeries.js +71 -0
- package/dist/stats/timeSeries.js.map +1 -0
- package/dist/working/fold.d.ts +51 -0
- package/dist/working/fold.d.ts.map +1 -0
- package/dist/working/fold.js +218 -0
- package/dist/working/fold.js.map +1 -0
- package/dist/working/index.d.ts +1 -0
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +1 -0
- package/dist/working/index.js.map +1 -1
- package/package.json +7 -3
- package/src/contract/exports.snapshot.json +41 -0
- package/src/contract/regression.assets.test.ts +41 -1
- package/src/contract/regression.review.test.ts +56 -0
- package/src/contract/types.contract.test.ts +15 -2
- package/src/knowledge/assetFile.ts +4 -4
- package/src/knowledge/extractFile.ts +4 -2
- package/src/knowledge/extractJob.ts +3 -3
- package/src/knowledge/outline.ts +1 -1
- package/src/knowledge/owedFiles.ts +3 -0
- package/src/knowledge/plan.ts +14 -5
- package/src/knowledge/reviewModel.ts +10 -1
- package/src/knowledge/reviewPrefetch.ts +11 -5
- package/src/knowledge/sources.ts +3 -1
- package/src/stats/distributions.ts +180 -0
- package/src/stats/estimators.ts +101 -0
- package/src/stats/fitting.ts +252 -0
- package/src/stats/index.ts +59 -0
- package/src/stats/information.ts +20 -0
- package/src/stats/multivariate.ts +93 -0
- package/src/stats/policies.ts +84 -0
- package/src/stats/prng.ts +45 -0
- package/src/stats/scores.ts +135 -0
- package/src/stats/stats.test.ts +294 -0
- package/src/stats/tests.ts +164 -0
- package/src/stats/timeSeries.ts +92 -0
- package/src/working/fold.test.ts +196 -0
- package/src/working/fold.ts +241 -0
- package/src/working/index.ts +1 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the stats module (PRD 41 Part D / D13). The done-checks these cover:
|
|
3
|
+
* - Chapman estimate against textbook values; m < 3 style degenerate inputs give
|
|
4
|
+
* `insufficient-data` (no recaptures).
|
|
5
|
+
* - Rule precision shapes (Beta posterior quantiles) and calibration (ECE, Brier).
|
|
6
|
+
* - The SPRT stops early on a fixture with a 20% regression and runs to the
|
|
7
|
+
* maximum on a no-change fixture.
|
|
8
|
+
* - Determinism: the same seed gives byte-identical draws and schedules.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, expect, it } from "@jest/globals";
|
|
12
|
+
import {
|
|
13
|
+
bayesianOnlineChangePoint,
|
|
14
|
+
betaPosterior,
|
|
15
|
+
brierScore,
|
|
16
|
+
chapmanEstimate,
|
|
17
|
+
createRng,
|
|
18
|
+
cusum,
|
|
19
|
+
effortAwareRecall,
|
|
20
|
+
entropyOfCounts,
|
|
21
|
+
expectedCalibrationError,
|
|
22
|
+
fitBayesianLogistic,
|
|
23
|
+
fitIsotonic,
|
|
24
|
+
fitPlattScaling,
|
|
25
|
+
gammaPoissonPosterior,
|
|
26
|
+
gammaQuantile,
|
|
27
|
+
garwoodPoissonInterval,
|
|
28
|
+
goelOkumotoMLE,
|
|
29
|
+
kaplanMeier,
|
|
30
|
+
ledoitWolfCovariance,
|
|
31
|
+
lincolnPetersenEstimate,
|
|
32
|
+
ndcgAtK,
|
|
33
|
+
pairedBootstrapCi,
|
|
34
|
+
popt,
|
|
35
|
+
prAuc,
|
|
36
|
+
psi,
|
|
37
|
+
shannonEntropy,
|
|
38
|
+
signTestSprt,
|
|
39
|
+
thompsonRank,
|
|
40
|
+
thompsonSample,
|
|
41
|
+
wilcoxonSignedRank,
|
|
42
|
+
} from "./index.js";
|
|
43
|
+
|
|
44
|
+
describe("prng", () => {
|
|
45
|
+
it("is deterministic under its seed", () => {
|
|
46
|
+
const a = createRng(42);
|
|
47
|
+
const b = createRng(42);
|
|
48
|
+
const seqA = Array.from({ length: 8 }, () => a());
|
|
49
|
+
const seqB = Array.from({ length: 8 }, () => b());
|
|
50
|
+
expect(seqA).toEqual(seqB);
|
|
51
|
+
expect(seqA.every((v) => v >= 0 && v < 1)).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("differs across seeds", () => {
|
|
55
|
+
const a = createRng(1);
|
|
56
|
+
const b = createRng(2);
|
|
57
|
+
expect(a()).not.toEqual(b());
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe("distributions", () => {
|
|
62
|
+
it("beta posterior mean and quantiles bracket sensibly", () => {
|
|
63
|
+
const post = betaPosterior(1, 1, 30, 100); // observed 30/100
|
|
64
|
+
expect(post.mean).toBeCloseTo(31 / 102, 5);
|
|
65
|
+
const lo = post.quantile(0.025);
|
|
66
|
+
const hi = post.quantile(0.975);
|
|
67
|
+
expect(lo).toBeGreaterThan(0);
|
|
68
|
+
expect(hi).toBeLessThan(1);
|
|
69
|
+
expect(lo).toBeLessThan(post.mean);
|
|
70
|
+
expect(hi).toBeGreaterThan(post.mean);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("gamma quantile inverts the CDF", () => {
|
|
74
|
+
// median of Gamma(2, 1) ≈ 1.678
|
|
75
|
+
expect(gammaQuantile(0.5, 2, 1)).toBeCloseTo(1.678, 2);
|
|
76
|
+
expect(gammaQuantile(0, 2)).toBe(0);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("garwood interval contains the point estimate and handles zero", () => {
|
|
80
|
+
const interval = garwoodPoissonInterval(10, 1);
|
|
81
|
+
expect(interval.low).toBeLessThan(10);
|
|
82
|
+
expect(interval.high).toBeGreaterThan(10);
|
|
83
|
+
const zero = garwoodPoissonInterval(0, 1);
|
|
84
|
+
expect(zero.low).toBe(0);
|
|
85
|
+
expect(zero.rateLow).toBe(0);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe("fitting", () => {
|
|
90
|
+
it("bayesian logistic recovers a monotone relationship", () => {
|
|
91
|
+
const xs = [-3, -2, -1.5, -1, 0, 1, 1.5, 2, 3, 3.5];
|
|
92
|
+
const ys = [0, 0, 0, 1, 0, 1, 1, 1, 1, 1];
|
|
93
|
+
const fit = fitBayesianLogistic(xs, ys);
|
|
94
|
+
expect(fit.predict(-3)).toBeLessThan(fit.predict(0));
|
|
95
|
+
expect(fit.predict(0)).toBeLessThan(fit.predict(3));
|
|
96
|
+
expect(fit.slope).toBeGreaterThan(0);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("platt scaling maps low scores low and high scores high", () => {
|
|
100
|
+
const scores = [-2, -1, -0.5, 0.5, 1, 2];
|
|
101
|
+
const labels = [0, 0, 0, 1, 1, 1];
|
|
102
|
+
const platt = fitPlattScaling(scores, labels);
|
|
103
|
+
expect(platt.predict(-2)).toBeLessThan(0.2);
|
|
104
|
+
expect(platt.predict(2)).toBeGreaterThan(0.8);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("isotonic regression is monotone non-decreasing", () => {
|
|
108
|
+
const xs = [1, 2, 3, 4, 5];
|
|
109
|
+
const ys = [0.1, 0.4, 0.2, 0.9, 0.8]; // a dip and a peak to pool
|
|
110
|
+
const iso = fitIsotonic(xs, ys);
|
|
111
|
+
let prev = -Infinity;
|
|
112
|
+
for (const x of xs) {
|
|
113
|
+
const v = iso.predict(x);
|
|
114
|
+
expect(v).toBeGreaterThanOrEqual(prev - 1e-12);
|
|
115
|
+
prev = v;
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
describe("statistical tests", () => {
|
|
121
|
+
it("wilcoxon signed-rank detects a consistent shift", () => {
|
|
122
|
+
const before = Array.from({ length: 12 }, (_, i) => 100 + i * 7);
|
|
123
|
+
const after = before.map((v) => v + 5);
|
|
124
|
+
const result = wilcoxonSignedRank(before, after);
|
|
125
|
+
expect(result.n).toBe(12);
|
|
126
|
+
expect(result.pValue).toBeLessThan(0.01);
|
|
127
|
+
expect(result.hodgesLehmann).toBeCloseTo(5, 5);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it("wilcoxon on a zero shift does not reject", () => {
|
|
131
|
+
const values = Array.from({ length: 10 }, (_, i) => 50 + (i % 3));
|
|
132
|
+
const result = wilcoxonSignedRank(values, [...values]);
|
|
133
|
+
expect(result.n).toBe(0);
|
|
134
|
+
expect(result.pValue).toBe(1);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("paired bootstrap CI is deterministic under its seed and contains the estimate", () => {
|
|
138
|
+
const before = [10, 12, 11, 13, 15, 9, 14, 10];
|
|
139
|
+
const after = [11, 13, 12, 14, 16, 10, 15, 11];
|
|
140
|
+
const a = pairedBootstrapCi(before, after, { seed: 7 });
|
|
141
|
+
const b = pairedBootstrapCi(before, after, { seed: 7 });
|
|
142
|
+
expect(a).toEqual(b);
|
|
143
|
+
expect(a.low).toBeLessThanOrEqual(a.estimate);
|
|
144
|
+
expect(a.high).toBeGreaterThanOrEqual(a.estimate);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("SPRT stops early on a clear regression and continues on no change", () => {
|
|
148
|
+
const regression = Array.from({ length: 40 }, () => [1, 1.25] as const); // 20%+ slower
|
|
149
|
+
const stop = signTestSprt(regression, { p0: 0.5, p1: 0.7, alpha: 0.05, beta: 0.1 });
|
|
150
|
+
expect(stop.decision).toBe("reject-null");
|
|
151
|
+
expect(stop.observations).toBeLessThan(40);
|
|
152
|
+
|
|
153
|
+
// No-change fixture: 3 improvements per 2 regressions keeps the cumulative
|
|
154
|
+
// LLR wandering inside the boundaries, so the test runs to its maximum.
|
|
155
|
+
const none: ReadonlyArray<readonly [number, number]> = Array.from(
|
|
156
|
+
{ length: 12 },
|
|
157
|
+
() => [[1, 1.05], [1, 1.02], [1, 0.98], [1, 1.01], [1, 0.97]] as const,
|
|
158
|
+
).flat();
|
|
159
|
+
const run = signTestSprt(none, { p0: 0.5, p1: 0.7, alpha: 0.05, beta: 0.1 });
|
|
160
|
+
expect(run.decision).toBe("continue");
|
|
161
|
+
expect(run.observations).toBe(60);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe("time series", () => {
|
|
166
|
+
it("cusum alarms after a sustained shift", () => {
|
|
167
|
+
const values = [...Array.from({ length: 30 }, () => 0), ...Array.from({ length: 30 }, () => 2.5)];
|
|
168
|
+
const result = cusum(values, 0, { sigma: 1, threshold: 5 });
|
|
169
|
+
expect(result.alarmIndex).toBeGreaterThanOrEqual(30);
|
|
170
|
+
expect(result.alarmIndex).toBeLessThan(45);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("bayesian change point flags the shift index", () => {
|
|
174
|
+
const values = [...Array.from({ length: 40 }, () => 0), ...Array.from({ length: 40 }, () => 3)];
|
|
175
|
+
const result = bayesianOnlineChangePoint(values, { hazard: 0.05 });
|
|
176
|
+
expect(result.currentRunLength).toBeGreaterThanOrEqual(0);
|
|
177
|
+
// The change-point probability near the shift should exceed the background.
|
|
178
|
+
const nearShift = result.changePointProbabilities[41]!;
|
|
179
|
+
const background = result.changePointProbabilities[10]!;
|
|
180
|
+
expect(nearShift).toBeGreaterThan(background);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
describe("multivariate", () => {
|
|
185
|
+
it("ledoit-wolf covariance recovers the diagonal of a near-identity", () => {
|
|
186
|
+
const rng = createRng(11);
|
|
187
|
+
const data = Array.from({ length: 200 }, () => [rng() < 0.5 ? 0 : 1, rng() < 0.5 ? 0 : 1]);
|
|
188
|
+
const { covariance, shrinkage } = ledoitWolfCovariance(data);
|
|
189
|
+
expect(shrinkage).toBeGreaterThanOrEqual(0);
|
|
190
|
+
expect(shrinkage).toBeLessThanOrEqual(1);
|
|
191
|
+
expect(covariance[0]![0]!).toBeGreaterThan(0);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("psi is zero for identical distributions and positive for drift", () => {
|
|
195
|
+
const a = Array.from({ length: 500 }, (_, i) => i / 500);
|
|
196
|
+
expect(psi(a, a, 10)).toBeCloseTo(0, 6);
|
|
197
|
+
const drifted = a.map((v) => v * 0.5 + 0.5);
|
|
198
|
+
expect(psi(a, drifted, 10)).toBeGreaterThan(0.2);
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
describe("information", () => {
|
|
203
|
+
it("entropy is maximal for uniform and zero for a point mass", () => {
|
|
204
|
+
expect(shannonEntropy([1])).toBeCloseTo(0, 10);
|
|
205
|
+
expect(shannonEntropy([0.5, 0.5])).toBeCloseTo(Math.log(2), 10);
|
|
206
|
+
expect(entropyOfCounts([2, 2, 2, 2])).toBeCloseTo(Math.log(4), 10);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
describe("estimators", () => {
|
|
211
|
+
it("chapman estimate matches the textbook value; no recaptures is insufficient", () => {
|
|
212
|
+
// Textbook: m = 20, c = 15, r = 5 → n̂ = (21·16)/6 − 1 = 55
|
|
213
|
+
const estimate = chapmanEstimate(20, 15, 5);
|
|
214
|
+
expect(estimate).toEqual({ estimate: 55 });
|
|
215
|
+
expect(chapmanEstimate(20, 15, 0)).toEqual({ status: "insufficient-data" });
|
|
216
|
+
expect(lincolnPetersenEstimate(20, 15, 5)).toEqual({ estimate: 60 });
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("kaplan-meier drops at event times and honors censoring", () => {
|
|
220
|
+
const km = kaplanMeier([
|
|
221
|
+
{ time: 1, event: 1 },
|
|
222
|
+
{ time: 2, event: 0 },
|
|
223
|
+
{ time: 3, event: 1 },
|
|
224
|
+
{ time: 4, event: 0 },
|
|
225
|
+
]);
|
|
226
|
+
expect(km.curve[0]!.survival).toBeCloseTo(0.75, 6);
|
|
227
|
+
expect(km.survival).toBeCloseTo(0.75 * (1 - 1 / 2), 6);
|
|
228
|
+
expect(km.variance).toBeGreaterThanOrEqual(0);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it("goel-okumoto MLE needs at least two times", () => {
|
|
232
|
+
expect(goelOkumotoMLE([1])).toEqual({ status: "insufficient-data" });
|
|
233
|
+
const fit = goelOkumotoMLE([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
|
234
|
+
if (fit.status === "insufficient-data") throw new Error("expected a fit");
|
|
235
|
+
expect(fit.a).toBeGreaterThan(0);
|
|
236
|
+
expect(fit.b).toBeGreaterThan(0);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("gamma-poisson posterior mean sits between prior and data at small n", () => {
|
|
240
|
+
const prior = gammaPoissonPosterior(2, 4, 0, 0); // Gamma(2, 4), mean 0.5
|
|
241
|
+
const updated = gammaPoissonPosterior(2, 4, 2, 1); // Gamma(4, 5), mean 0.8
|
|
242
|
+
expect(prior.mean).toBeCloseTo(0.5, 6);
|
|
243
|
+
expect(updated.mean).toBeGreaterThan(prior.mean);
|
|
244
|
+
expect(updated.variance).toBeGreaterThan(0);
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
describe("scores", () => {
|
|
249
|
+
it("brier and ECE penalize miscalibration", () => {
|
|
250
|
+
expect(brierScore([1, 1, 1, 1], [1, 1, 1, 1])).toBeCloseTo(0, 10);
|
|
251
|
+
expect(brierScore([1, 0], [0, 1])).toBeCloseTo(1, 10);
|
|
252
|
+
expect(expectedCalibrationError([1, 1, 1, 1], [1, 1, 1, 1])).toBeCloseTo(0, 10);
|
|
253
|
+
expect(expectedCalibrationError([0.9, 0.9, 0.1, 0.1], [0, 0, 1, 1])).toBeGreaterThan(0.7);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("pr-auc is 1 for a perfect ranking and ndcg penalizes bad order", () => {
|
|
257
|
+
expect(prAuc([0.9, 0.8, 0.1, 0.05], [1, 1, 0, 0])).toBeCloseTo(1, 6);
|
|
258
|
+
expect(ndcgAtK([3, 2, 1], 3)).toBeCloseTo(1, 6);
|
|
259
|
+
expect(ndcgAtK([1, 2, 3], 3)).toBeLessThan(1);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("popt and effort-aware recall reward good ordering", () => {
|
|
263
|
+
const efforts = [0.1, 0.2, 0.3, 0.4];
|
|
264
|
+
const goodOrder = [0.9, 0.8, 0.2, 0.1];
|
|
265
|
+
expect(popt(efforts, goodOrder)).toBeGreaterThan(0.5);
|
|
266
|
+
expect(
|
|
267
|
+
effortAwareRecall([true, true, false, false], efforts, 0.5),
|
|
268
|
+
).toBeCloseTo(1, 6);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
describe("policies", () => {
|
|
273
|
+
it("thompson sampling favors the better arm and is deterministic under seed", () => {
|
|
274
|
+
const arms = [
|
|
275
|
+
{ alpha: 30, beta: 10 }, // ~75%
|
|
276
|
+
{ alpha: 10, beta: 30 }, // ~25%
|
|
277
|
+
];
|
|
278
|
+
const picksA = Array.from({ length: 200 }, () => thompsonSample(arms, createRng(99)));
|
|
279
|
+
const picksB = Array.from({ length: 200 }, () => thompsonSample(arms, createRng(99)));
|
|
280
|
+
expect(picksA).toEqual(picksB);
|
|
281
|
+
const betterPicks = picksA.filter((i) => i === 0).length;
|
|
282
|
+
expect(betterPicks).toBeGreaterThan(150);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("thompson rank is a permutation of all arms", () => {
|
|
286
|
+
const arms = [
|
|
287
|
+
{ alpha: 5, beta: 5 },
|
|
288
|
+
{ alpha: 20, beta: 5 },
|
|
289
|
+
{ alpha: 5, beta: 20 },
|
|
290
|
+
];
|
|
291
|
+
const rank = thompsonRank(arms, createRng(3));
|
|
292
|
+
expect([...rank].sort()).toEqual([0, 1, 2]);
|
|
293
|
+
});
|
|
294
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Statistical tests for the stats module (PRD 41 Part D / D13): Wilcoxon signed-rank
|
|
3
|
+
* with the paired Hodges–Lehmann estimator, a seeded paired bootstrap CI, and the
|
|
4
|
+
* sign-test SPRT. All deterministic under their seeds.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createRng, type Rng } from "./prng.js";
|
|
8
|
+
|
|
9
|
+
const WILCOXON_P: number[] = (() => {
|
|
10
|
+
// Exact null distribution of W+ for n <= 60 via DP over subset sums.
|
|
11
|
+
const n = 60;
|
|
12
|
+
const total = (n * (n + 1)) / 2;
|
|
13
|
+
const dp: number[] = new Array(total + 1).fill(0);
|
|
14
|
+
dp[0] = 1;
|
|
15
|
+
for (let rank = 1; rank <= n; rank++) {
|
|
16
|
+
for (let s = total; s >= rank; s--) dp[s] = (dp[s] ?? 0) + (dp[s - rank] ?? 0);
|
|
17
|
+
}
|
|
18
|
+
const cum: number[] = new Array(total + 1).fill(0);
|
|
19
|
+
let running = 0;
|
|
20
|
+
for (let s = 0; s <= total; s++) {
|
|
21
|
+
running += dp[s]!;
|
|
22
|
+
cum[s] = running / 2 ** n;
|
|
23
|
+
}
|
|
24
|
+
return cum;
|
|
25
|
+
})();
|
|
26
|
+
|
|
27
|
+
function wilcoxonPValue(wPlus: number, n: number): number {
|
|
28
|
+
if (n > 60) {
|
|
29
|
+
// Normal approximation with continuity correction.
|
|
30
|
+
const mean = (n * (n + 1)) / 4;
|
|
31
|
+
const sd = Math.sqrt((n * (n + 1) * (2 * n + 1)) / 24);
|
|
32
|
+
const z = (wPlus - mean + 0.5) / sd;
|
|
33
|
+
return Math.min(1, Math.exp(-0.5 * z * z) * 0.5 * 2); // two-sided via |z|
|
|
34
|
+
}
|
|
35
|
+
const total = (n * (n + 1)) / 2;
|
|
36
|
+
const lo = Math.max(0, Math.floor(wPlus));
|
|
37
|
+
const hi = Math.min(total, Math.ceil(wPlus));
|
|
38
|
+
const pLo = WILCOXON_P[lo] ?? 0;
|
|
39
|
+
const pHi = 1 - (WILCOXON_P[hi - 1] ?? 0);
|
|
40
|
+
return Math.min(1, 2 * Math.min(pLo, pHi));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface WilcoxonResult {
|
|
44
|
+
n: number;
|
|
45
|
+
wPlus: number;
|
|
46
|
+
pValue: number;
|
|
47
|
+
/** Paired Hodges–Lehmann estimator: median of pairwise averages (after > 0 filter). */
|
|
48
|
+
hodgesLehmann: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Wilcoxon signed-rank test on the nonzero paired differences of `before` and
|
|
53
|
+
* `after`, plus the paired Hodges–Lehmann location estimator.
|
|
54
|
+
*/
|
|
55
|
+
export function wilcoxonSignedRank(before: readonly number[], after: readonly number[]): WilcoxonResult {
|
|
56
|
+
const diffs: number[] = [];
|
|
57
|
+
const n0 = Math.min(before.length, after.length);
|
|
58
|
+
for (let i = 0; i < n0; i++) {
|
|
59
|
+
const d = after[i]! - before[i]!;
|
|
60
|
+
if (d !== 0) diffs.push(d);
|
|
61
|
+
}
|
|
62
|
+
const n = diffs.length;
|
|
63
|
+
if (n === 0) return { n: 0, wPlus: 0, pValue: 1, hodgesLehmann: 0 };
|
|
64
|
+
const abs = diffs.map((d) => Math.abs(d));
|
|
65
|
+
const order = abs.map((_, i) => i).sort((p, q) => abs[p]! - abs[q]!);
|
|
66
|
+
const ranks = new Array<number>(n).fill(0);
|
|
67
|
+
let i = 0;
|
|
68
|
+
while (i < n) {
|
|
69
|
+
let j = i;
|
|
70
|
+
while (j + 1 < n && abs[order[j + 1]!] === abs[order[i]!]) j++;
|
|
71
|
+
const avg = (i + j) / 2 + 1;
|
|
72
|
+
for (let k = i; k <= j; k++) ranks[order[k]!] = avg;
|
|
73
|
+
i = j + 1;
|
|
74
|
+
}
|
|
75
|
+
let wPlus = 0;
|
|
76
|
+
for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!;
|
|
77
|
+
// Hodges–Lehmann: median of Walsh averages over positive-magnitude pairs.
|
|
78
|
+
const walsh: number[] = [];
|
|
79
|
+
for (let p = 0; p < n; p++) {
|
|
80
|
+
for (let q = p; q < n; q++) walsh.push((diffs[p]! + diffs[q]!) / 2);
|
|
81
|
+
}
|
|
82
|
+
walsh.sort((a, b) => a - b);
|
|
83
|
+
const hl =
|
|
84
|
+
walsh.length % 2 === 1
|
|
85
|
+
? walsh[(walsh.length - 1) / 2]!
|
|
86
|
+
: (walsh[walsh.length / 2 - 1]! + walsh[walsh.length / 2]!) / 2;
|
|
87
|
+
return { n, wPlus, pValue: wilcoxonPValue(wPlus, n), hodgesLehmann: hl };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Paired bootstrap confidence interval for the mean difference `after − before`,
|
|
92
|
+
* resampling PAIRS so the pairing is preserved. Deterministic under `seed`.
|
|
93
|
+
*/
|
|
94
|
+
export function pairedBootstrapCi(
|
|
95
|
+
before: readonly number[],
|
|
96
|
+
after: readonly number[],
|
|
97
|
+
options: { iterations?: number; confidence?: number; seed?: number } = {},
|
|
98
|
+
): { low: number; high: number; estimate: number } {
|
|
99
|
+
const iterations = options.iterations ?? 2000;
|
|
100
|
+
const confidence = options.confidence ?? 0.95;
|
|
101
|
+
const rng: Rng = createRng(options.seed ?? 1);
|
|
102
|
+
const n = Math.min(before.length, after.length);
|
|
103
|
+
const diffs: number[] = [];
|
|
104
|
+
for (let i = 0; i < n; i++) diffs.push(after[i]! - before[i]!);
|
|
105
|
+
const estimate = diffs.reduce((a, b) => a + b, 0) / Math.max(diffs.length, 1);
|
|
106
|
+
if (n === 0) return { low: 0, high: 0, estimate: 0 };
|
|
107
|
+
const means: number[] = [];
|
|
108
|
+
for (let b = 0; b < iterations; b++) {
|
|
109
|
+
let s = 0;
|
|
110
|
+
for (let i = 0; i < n; i++) s += diffs[Math.floor(rng() * n)]!;
|
|
111
|
+
means.push(s / n);
|
|
112
|
+
}
|
|
113
|
+
means.sort((a, b) => a - b);
|
|
114
|
+
const alpha = 1 - confidence;
|
|
115
|
+
return {
|
|
116
|
+
low: means[Math.floor((alpha / 2) * iterations)] ?? estimate,
|
|
117
|
+
high: means[Math.floor((1 - alpha / 2) * iterations) - 1] ?? estimate,
|
|
118
|
+
estimate,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface SprtResult {
|
|
123
|
+
decision: "reject-null" | "accept-null" | "continue";
|
|
124
|
+
likelihoodRatio: number;
|
|
125
|
+
observations: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Sequential probability ratio test on paired signs. H0: P(after > before) = p0,
|
|
130
|
+
* H1: = p1. Decides as soon as the likelihood ratio crosses a boundary, else reports
|
|
131
|
+
* `continue` at `maxObservations`. Deterministic — the observations are supplied.
|
|
132
|
+
*/
|
|
133
|
+
export function signTestSprt(
|
|
134
|
+
pairs: ReadonlyArray<readonly [number, number]>,
|
|
135
|
+
options: {
|
|
136
|
+
p0?: number;
|
|
137
|
+
p1?: number;
|
|
138
|
+
alpha?: number;
|
|
139
|
+
beta?: number;
|
|
140
|
+
alternative?: "greater" | "less";
|
|
141
|
+
} = {},
|
|
142
|
+
): SprtResult {
|
|
143
|
+
const p0 = options.p0 ?? 0.5;
|
|
144
|
+
const p1 = options.p1 ?? 0.7;
|
|
145
|
+
const alpha = options.alpha ?? 0.05;
|
|
146
|
+
const beta = options.beta ?? 0.1;
|
|
147
|
+
const aBound = Math.log((1 - beta) / alpha);
|
|
148
|
+
const bBound = Math.log(beta / (1 - alpha));
|
|
149
|
+
let llr = 0;
|
|
150
|
+
let observations = 0;
|
|
151
|
+
for (const [beforeV, afterV] of pairs) {
|
|
152
|
+
const plus = afterV > beforeV;
|
|
153
|
+
const inc = Math.log((plus ? p1 : 1 - p1) / (plus ? p0 : 1 - p0));
|
|
154
|
+
const incAlt =
|
|
155
|
+
options.alternative === "less"
|
|
156
|
+
? Math.log((plus ? 1 - p1 : p1) / (plus ? 1 - p0 : p0))
|
|
157
|
+
: inc;
|
|
158
|
+
llr += incAlt;
|
|
159
|
+
observations++;
|
|
160
|
+
if (llr >= aBound) return { decision: "reject-null", likelihoodRatio: llr, observations };
|
|
161
|
+
if (llr <= bBound) return { decision: "accept-null", likelihoodRatio: llr, observations };
|
|
162
|
+
}
|
|
163
|
+
return { decision: "continue", likelihoodRatio: llr, observations };
|
|
164
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Time-series change detection for the stats module (PRD 41 Part D / D13): CUSUM
|
|
3
|
+
* and Bayesian online change-point detection. Both are deterministic (fixed hazard,
|
|
4
|
+
* bounded run length); EWMA itself is reused from ml/classical, not copied here.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface CusumResult {
|
|
8
|
+
/** First index where |cumulative sum| exceeds `threshold`, or -1. */
|
|
9
|
+
alarmIndex: number;
|
|
10
|
+
cumulative: number[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Cumulative-sum detector on standardized deviations from `target`. */
|
|
14
|
+
export function cusum(
|
|
15
|
+
values: readonly number[],
|
|
16
|
+
target: number,
|
|
17
|
+
options: { threshold?: number; sigma?: number; drift?: number } = {},
|
|
18
|
+
): CusumResult {
|
|
19
|
+
const sigma = options.sigma ?? 1;
|
|
20
|
+
const h = options.threshold ?? 5;
|
|
21
|
+
const k = options.drift ?? 0.5;
|
|
22
|
+
const cumulative: number[] = [];
|
|
23
|
+
let cPlus = 0;
|
|
24
|
+
let cMinus = 0;
|
|
25
|
+
let alarmIndex = -1;
|
|
26
|
+
for (let i = 0; i < values.length; i++) {
|
|
27
|
+
const z = (values[i]! - target) / sigma;
|
|
28
|
+
cPlus = Math.max(0, cPlus + z - k);
|
|
29
|
+
cMinus = Math.min(0, cMinus + z + k);
|
|
30
|
+
cumulative.push(cPlus + cMinus);
|
|
31
|
+
if (alarmIndex === -1 && (cPlus > h || -cMinus > h)) alarmIndex = i;
|
|
32
|
+
}
|
|
33
|
+
return { alarmIndex, cumulative };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ChangePointResult {
|
|
37
|
+
/** MAP run length at the last observation; -1 when the series is empty. */
|
|
38
|
+
currentRunLength: number;
|
|
39
|
+
/** Posterior probability of a change point at each index (run length 0 mass). */
|
|
40
|
+
changePointProbabilities: number[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Bayesian online change-point detection (Adams & MacKay, 2007), Gaussian with
|
|
45
|
+
* unknown mean and known variance 1, conjugate N(0, 1) prior on the mean per run.
|
|
46
|
+
* Each run length carries its own sufficient statistics (sum of observations), so a
|
|
47
|
+
* level shift accumulates evidence for a young run. Run-length mass is truncated at
|
|
48
|
+
* `maxRunLength` and renormalized; identical inputs give identical outputs.
|
|
49
|
+
*/
|
|
50
|
+
export function bayesianOnlineChangePoint(
|
|
51
|
+
values: readonly number[],
|
|
52
|
+
options: { hazard?: number; maxRunLength?: number } = {},
|
|
53
|
+
): ChangePointResult {
|
|
54
|
+
const hazard = options.hazard ?? 1 / 250;
|
|
55
|
+
const maxRunLength = options.maxRunLength ?? 500;
|
|
56
|
+
let growth: number[] = [1];
|
|
57
|
+
let sums: number[] = [0]; // sums[r] = Σ of observations inside a run of length r
|
|
58
|
+
const changePointProbabilities: number[] = [];
|
|
59
|
+
let currentRunLength = -1;
|
|
60
|
+
for (let t = 0; t < values.length; t++) {
|
|
61
|
+
const x = values[t]!;
|
|
62
|
+
const predProbs = growth.map((g, r) => g * gaussianPredictive(x, sums[r]!, r));
|
|
63
|
+
const evidence = predProbs.reduce((a, b) => a + b, 0) || 1e-300;
|
|
64
|
+
const next = new Array<number>(maxRunLength).fill(0);
|
|
65
|
+
const nextSums = new Array<number>(maxRunLength).fill(0);
|
|
66
|
+
next[0] = hazard;
|
|
67
|
+
nextSums[0] = 0;
|
|
68
|
+
for (let r = 0; r < growth.length && r + 1 < maxRunLength; r++) {
|
|
69
|
+
next[r + 1] = ((1 - hazard) * predProbs[r]!) / evidence;
|
|
70
|
+
nextSums[r + 1] = sums[r]! + x;
|
|
71
|
+
}
|
|
72
|
+
growth = next;
|
|
73
|
+
sums = nextSums;
|
|
74
|
+
const norm = growth.reduce((a, b) => a + b, 0) || 1e-300;
|
|
75
|
+
growth = growth.map((g) => g / norm);
|
|
76
|
+
changePointProbabilities.push(growth[0]!);
|
|
77
|
+
currentRunLength = growth.indexOf(Math.max(...growth));
|
|
78
|
+
}
|
|
79
|
+
return { currentRunLength, changePointProbabilities };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Predictive N(x; sum/(r+1), 1 + 1/(r+1)) for a run of length r: the posterior mean
|
|
84
|
+
* of the run's mean under the N(0, 1) prior is sum/(r+1), and the posterior variance
|
|
85
|
+
* adds 1 to the observation variance 1.
|
|
86
|
+
*/
|
|
87
|
+
function gaussianPredictive(x: number, sum: number, runLength: number): number {
|
|
88
|
+
const mean = sum / (runLength + 1);
|
|
89
|
+
const variance = 1 + 1 / (runLength + 1);
|
|
90
|
+
const z = (x - mean) / Math.sqrt(variance);
|
|
91
|
+
return Math.exp(-0.5 * z * z) / Math.sqrt(2 * Math.PI * variance);
|
|
92
|
+
}
|