@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,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model fitting for the stats module (PRD 41 Part D / D13): Bayesian logistic with a
|
|
3
|
+
* Laplace posterior, Platt scaling and isotonic regression (PAV). Pure, deterministic
|
|
4
|
+
* (Newton iterations with fixed caps), and independent of ml/classical — these are the
|
|
5
|
+
* calibration shapes the classical catalog does not carry.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createRng, normalDraw, type Rng } from "./prng.js";
|
|
9
|
+
|
|
10
|
+
export interface LaplaceApproximation {
|
|
11
|
+
mean: number[];
|
|
12
|
+
covariance: number[][];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function sigmoid(x: number): number {
|
|
16
|
+
if (x >= 0) return 1 / (1 + Math.exp(-x));
|
|
17
|
+
const e = Math.exp(x);
|
|
18
|
+
return e / (1 + e);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function invert2x2(m: number[][]): number[][] {
|
|
22
|
+
const det = m[0]![0]! * m[1]![1]! - m[0]![1]! * m[1]![0]!;
|
|
23
|
+
if (Math.abs(det) < 1e-12) {
|
|
24
|
+
return [
|
|
25
|
+
[1e6, 0],
|
|
26
|
+
[0, 1e6],
|
|
27
|
+
];
|
|
28
|
+
}
|
|
29
|
+
return [
|
|
30
|
+
[m[1]![1]! / det, -m[0]![1]! / det],
|
|
31
|
+
[-m[1]![0]! / det, m[0]![0]! / det],
|
|
32
|
+
];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface BayesianLogisticOptions {
|
|
36
|
+
/** L2 prior precision (1/σ²). Default 1. */
|
|
37
|
+
priorPrecision?: number;
|
|
38
|
+
maxIterations?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function penalizedLogLikelihood(
|
|
42
|
+
x: readonly number[],
|
|
43
|
+
y: readonly number[],
|
|
44
|
+
b0: number,
|
|
45
|
+
b1: number,
|
|
46
|
+
priorPrecision: number,
|
|
47
|
+
): number {
|
|
48
|
+
let ll = -(priorPrecision / 2) * (b0 * b0 + b1 * b1);
|
|
49
|
+
for (let i = 0; i < x.length; i++) {
|
|
50
|
+
const eta = b0 + b1 * x[i]!;
|
|
51
|
+
// log(1 + e^η) in a numerically stable form.
|
|
52
|
+
const softplus = eta >= 0 ? eta + Math.log1p(Math.exp(-eta)) : Math.log1p(Math.exp(eta));
|
|
53
|
+
ll += y[i]! * eta - softplus;
|
|
54
|
+
}
|
|
55
|
+
return ll;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Bayesian logistic regression on one feature, fitted by Newton–Raphson with
|
|
60
|
+
* step-halving on the penalized log-likelihood (IRLS is unstable on near-separable
|
|
61
|
+
* data with a weak prior: the raw step can leap into the saturated boundary, where
|
|
62
|
+
* the quadratic approximation no longer describes the surface). The posterior at
|
|
63
|
+
* the mode is approximated by a Laplace (Gaussian) whose covariance is the inverse
|
|
64
|
+
* observed information. Returns the mode, the covariance, a posterior-sample
|
|
65
|
+
* log-odds sampler (deterministic under `rng`), and the posterior-mean predictive
|
|
66
|
+
* probability at a point.
|
|
67
|
+
*/
|
|
68
|
+
export function fitBayesianLogistic(
|
|
69
|
+
x: readonly number[],
|
|
70
|
+
y: readonly number[],
|
|
71
|
+
options: BayesianLogisticOptions = {},
|
|
72
|
+
): {
|
|
73
|
+
intercept: number;
|
|
74
|
+
slope: number;
|
|
75
|
+
covariance: number[][];
|
|
76
|
+
sampleLogOdds(x0: number, rng?: Rng): number;
|
|
77
|
+
predict(x0: number): number;
|
|
78
|
+
} {
|
|
79
|
+
const priorPrecision = options.priorPrecision ?? 1;
|
|
80
|
+
const maxIterations = options.maxIterations ?? 50;
|
|
81
|
+
let b0 = 0;
|
|
82
|
+
let b1 = 0;
|
|
83
|
+
let current = penalizedLogLikelihood(x, y, b0, b1, priorPrecision);
|
|
84
|
+
let covariance: number[][] = [
|
|
85
|
+
[1 / priorPrecision, 0],
|
|
86
|
+
[0, 1 / priorPrecision],
|
|
87
|
+
];
|
|
88
|
+
for (let iter = 0; iter < maxIterations; iter++) {
|
|
89
|
+
let g0 = priorPrecision * b0;
|
|
90
|
+
let g1 = priorPrecision * b1;
|
|
91
|
+
let h00 = priorPrecision;
|
|
92
|
+
let h01 = 0;
|
|
93
|
+
let h11 = priorPrecision;
|
|
94
|
+
for (let i = 0; i < x.length; i++) {
|
|
95
|
+
const p = sigmoid(b0 + b1 * x[i]!);
|
|
96
|
+
const w = Math.max(p * (1 - p), 1e-9);
|
|
97
|
+
const r = y[i]! - p;
|
|
98
|
+
g0 += r;
|
|
99
|
+
g1 += r * x[i]!;
|
|
100
|
+
h00 += w;
|
|
101
|
+
h01 += w * x[i]!;
|
|
102
|
+
h11 += w * x[i]! * x[i]!;
|
|
103
|
+
}
|
|
104
|
+
// Newton for the MODE of the penalized likelihood: δ = (−H)⁻¹g, where
|
|
105
|
+
// −H = priorPrecision·I + Σ w·xxᵀ (the `h` accumulators, all positive).
|
|
106
|
+
const step = invert2x2([
|
|
107
|
+
[h00, h01],
|
|
108
|
+
[h01, h11],
|
|
109
|
+
]);
|
|
110
|
+
const d0 = step[0]![0]! * g0 + step[0]![1]! * g1;
|
|
111
|
+
const d1 = step[1]![0]! * g0 + step[1]![1]! * g1;
|
|
112
|
+
// Step-halving: accept the step only while the penalized likelihood rises.
|
|
113
|
+
let scale = 1;
|
|
114
|
+
for (let halving = 0; halving < 40; halving++) {
|
|
115
|
+
const candidate = penalizedLogLikelihood(x, y, b0 + d0 * scale, b1 + d1 * scale, priorPrecision);
|
|
116
|
+
if (candidate >= current - 1e-12) {
|
|
117
|
+
b0 += d0 * scale;
|
|
118
|
+
b1 += d1 * scale;
|
|
119
|
+
current = candidate;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
scale /= 2;
|
|
123
|
+
if (halving === 39) {
|
|
124
|
+
covariance = invert2x2([
|
|
125
|
+
[h00, h01],
|
|
126
|
+
[h01, h11],
|
|
127
|
+
]);
|
|
128
|
+
return {
|
|
129
|
+
intercept: b0,
|
|
130
|
+
slope: b1,
|
|
131
|
+
covariance,
|
|
132
|
+
sampleLogOdds: (x0, rng = createRng(1)) => sampleLogOdds(b0, b1, covariance, x0, rng),
|
|
133
|
+
predict: (x0) => sigmoid(b0 + b1 * x0),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (Math.abs(d0 * scale) < 1e-10 && Math.abs(d1 * scale) < 1e-10) {
|
|
138
|
+
covariance = invert2x2([
|
|
139
|
+
[h00, h01],
|
|
140
|
+
[h01, h11],
|
|
141
|
+
]);
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
intercept: b0,
|
|
147
|
+
slope: b1,
|
|
148
|
+
covariance,
|
|
149
|
+
sampleLogOdds: (x0, rng = createRng(1)) => sampleLogOdds(b0, b1, covariance, x0, rng),
|
|
150
|
+
predict: (x0) => sigmoid(b0 + b1 * x0),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** One posterior draw of the log-odds at `x0` from the Laplace approximation. */
|
|
155
|
+
function sampleLogOdds(b0: number, b1: number, covariance: number[][], x0: number, rng: Rng): number {
|
|
156
|
+
const s00 = Math.sqrt(Math.max(covariance[0]![0]!, 0));
|
|
157
|
+
const s10 = s00 > 1e-12 ? covariance[1]![0]! / s00 : 0;
|
|
158
|
+
const s11 = Math.sqrt(Math.max(covariance[1]![1]! - s10 * s10, 0));
|
|
159
|
+
const l0 = b0 + s00 * normalDraw(rng);
|
|
160
|
+
const l1 = b1 + s10 * normalDraw(rng) + s11 * normalDraw(rng);
|
|
161
|
+
return l0 + l1 * x0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Platt scaling: fit p = σ(a·s + b) on scores `s` and labels `y` by Newton descent. */
|
|
165
|
+
export function fitPlattScaling(
|
|
166
|
+
scores: readonly number[],
|
|
167
|
+
y: readonly number[],
|
|
168
|
+
): { a: number; b: number; predict(score: number): number } {
|
|
169
|
+
let a = 0;
|
|
170
|
+
let b = Math.log((0.01 + sum(y)) / (0.01 + (y.length - sum(y))));
|
|
171
|
+
const target = y.map((v) => (v === 1 ? 0.999 : 0.001));
|
|
172
|
+
for (let iter = 0; iter < 100; iter++) {
|
|
173
|
+
let ga = 0;
|
|
174
|
+
let gb = 0;
|
|
175
|
+
let haa = 1e-4;
|
|
176
|
+
let hab = 0;
|
|
177
|
+
let hbb = 1e-4;
|
|
178
|
+
for (let i = 0; i < scores.length; i++) {
|
|
179
|
+
const p = sigmoid(a * scores[i]! + b);
|
|
180
|
+
const r = p - target[i]!;
|
|
181
|
+
ga += r * scores[i]!;
|
|
182
|
+
gb += r;
|
|
183
|
+
const w = Math.max(p * (1 - p), 1e-9);
|
|
184
|
+
haa += w * scores[i]! * scores[i]!;
|
|
185
|
+
hab += w * scores[i]!;
|
|
186
|
+
hbb += w;
|
|
187
|
+
}
|
|
188
|
+
const det = haa * hbb - hab * hab;
|
|
189
|
+
const da = (hbb * -ga - hab * -gb) / det;
|
|
190
|
+
const db = (-hab * -ga + haa * -gb) / det;
|
|
191
|
+
a += da;
|
|
192
|
+
b += db;
|
|
193
|
+
if (Math.abs(da) < 1e-10 && Math.abs(db) < 1e-10) break;
|
|
194
|
+
}
|
|
195
|
+
return { a, b, predict: (score) => sigmoid(a * score + b) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function sum(values: readonly number[]): number {
|
|
199
|
+
let s = 0;
|
|
200
|
+
for (const v of values) s += v;
|
|
201
|
+
return s;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface IsotonicFit {
|
|
205
|
+
/** Thresholds between fitted steps; `predict` returns fittedY[0] below x[0]. */
|
|
206
|
+
thresholds: number[];
|
|
207
|
+
values: number[];
|
|
208
|
+
predict(x: number): number;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Isotonic regression by the pool-adjacent-violators algorithm. Deterministic. */
|
|
212
|
+
export function fitIsotonic(x: readonly number[], y: readonly number[]): IsotonicFit {
|
|
213
|
+
const order = x.map((_, i) => i).sort((p, q) => x[p]! - x[q]!);
|
|
214
|
+
const blocks: { weight: number; sum: number; value: number }[] = [];
|
|
215
|
+
for (const i of order) {
|
|
216
|
+
blocks.push({ weight: 1, sum: y[i]!, value: y[i]! });
|
|
217
|
+
while (blocks.length >= 2 && blocks[blocks.length - 2]!.value > blocks[blocks.length - 1]!.value) {
|
|
218
|
+
const top = blocks.pop()!;
|
|
219
|
+
const below = blocks.pop()!;
|
|
220
|
+
const merged = {
|
|
221
|
+
weight: below.weight + top.weight,
|
|
222
|
+
sum: below.sum + top.sum,
|
|
223
|
+
value: (below.sum + top.sum) / (below.weight + top.weight),
|
|
224
|
+
};
|
|
225
|
+
blocks.push(merged);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const thresholds: number[] = [];
|
|
229
|
+
const values: number[] = [];
|
|
230
|
+
for (let bi = 0; bi < blocks.length; bi++) {
|
|
231
|
+
values.push(blocks[bi]!.value);
|
|
232
|
+
if (bi < blocks.length - 1) {
|
|
233
|
+
// Threshold at the midpoint of the x-range of this block.
|
|
234
|
+
const startIdx = order.slice(
|
|
235
|
+
blocks.slice(0, bi).reduce((acc, bl) => acc + bl.weight, 0),
|
|
236
|
+
);
|
|
237
|
+
const blockIdx = startIdx.slice(0, blocks[bi]!.weight);
|
|
238
|
+
thresholds.push(x[blockIdx[blockIdx.length - 1]!]!);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
thresholds,
|
|
243
|
+
values,
|
|
244
|
+
predict: (x0) => {
|
|
245
|
+
let v = values[0]!;
|
|
246
|
+
for (let t = 0; t < thresholds.length; t++) {
|
|
247
|
+
if (x0 >= thresholds[t]!) v = values[t + 1]!;
|
|
248
|
+
}
|
|
249
|
+
return v;
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stats module (PRD 41 Part D / D13): the ONE home for the predicted-measure
|
|
3
|
+
* maths. Pure and deterministic — seeded PRNG, fixed iteration caps, quantized
|
|
4
|
+
* outputs. It holds only what the memory-engine `ml/classical` catalog lacks and
|
|
5
|
+
* imports (never re-implements) those primitives; EWMA and the classical models
|
|
6
|
+
* stay in `ml/classical`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { createRng, normalDraw } from "./prng.js";
|
|
10
|
+
export type { Rng } from "./prng.js";
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
betaPosterior,
|
|
14
|
+
gammaQuantile,
|
|
15
|
+
garwoodPoissonInterval,
|
|
16
|
+
inverseRegularizedIncompleteBeta,
|
|
17
|
+
regularizedIncompleteBeta,
|
|
18
|
+
regularizedIncompleteGamma,
|
|
19
|
+
} from "./distributions.js";
|
|
20
|
+
export type { BetaPosterior } from "./distributions.js";
|
|
21
|
+
|
|
22
|
+
export { fitBayesianLogistic, fitIsotonic, fitPlattScaling } from "./fitting.js";
|
|
23
|
+
export type { BayesianLogisticOptions, IsotonicFit } from "./fitting.js";
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
pairedBootstrapCi,
|
|
27
|
+
signTestSprt,
|
|
28
|
+
wilcoxonSignedRank,
|
|
29
|
+
} from "./tests.js";
|
|
30
|
+
export type { SprtResult, WilcoxonResult } from "./tests.js";
|
|
31
|
+
|
|
32
|
+
export { bayesianOnlineChangePoint, cusum } from "./timeSeries.js";
|
|
33
|
+
export type { ChangePointResult, CusumResult } from "./timeSeries.js";
|
|
34
|
+
|
|
35
|
+
export { ledoitWolfCovariance, psi } from "./multivariate.js";
|
|
36
|
+
export type { CovarianceResult } from "./multivariate.js";
|
|
37
|
+
|
|
38
|
+
export { entropyOfCounts, shannonEntropy } from "./information.js";
|
|
39
|
+
|
|
40
|
+
export {
|
|
41
|
+
chapmanEstimate,
|
|
42
|
+
gammaPoissonPosterior,
|
|
43
|
+
goelOkumotoMLE,
|
|
44
|
+
kaplanMeier,
|
|
45
|
+
lincolnPetersenEstimate,
|
|
46
|
+
} from "./estimators.js";
|
|
47
|
+
export type { InsufficientData, KaplanMeierResult } from "./estimators.js";
|
|
48
|
+
|
|
49
|
+
export {
|
|
50
|
+
brierScore,
|
|
51
|
+
effortAwareRecall,
|
|
52
|
+
expectedCalibrationError,
|
|
53
|
+
ndcgAtK,
|
|
54
|
+
popt,
|
|
55
|
+
prAuc,
|
|
56
|
+
} from "./scores.js";
|
|
57
|
+
|
|
58
|
+
export { thompsonRank, thompsonSample } from "./policies.js";
|
|
59
|
+
export type { BetaArm } from "./policies.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Information-theoretic primitives for the stats module (PRD 41 Part D / D13):
|
|
3
|
+
* Shannon entropy over empirical probabilities.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Shannon entropy in nats (natural log) of an empirical distribution. */
|
|
7
|
+
export function shannonEntropy(probabilities: readonly number[]): number {
|
|
8
|
+
let h = 0;
|
|
9
|
+
for (const p of probabilities) {
|
|
10
|
+
if (p > 0) h -= p * Math.log(p);
|
|
11
|
+
}
|
|
12
|
+
return h;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Entropy of a count vector; zero counts contribute nothing. */
|
|
16
|
+
export function entropyOfCounts(counts: readonly number[]): number {
|
|
17
|
+
const total = counts.reduce((a, b) => a + b, 0);
|
|
18
|
+
if (total === 0) return 0;
|
|
19
|
+
return shannonEntropy(counts.map((c) => c / total));
|
|
20
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multivariate summaries for the stats module (PRD 41 Part D / D13): Ledoit–Wolf
|
|
3
|
+
* shrinkage covariance and the population stability index (PSI). Pure and
|
|
4
|
+
* deterministic.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface CovarianceResult {
|
|
8
|
+
/** Column means of the input matrix (rows = observations). */
|
|
9
|
+
means: number[];
|
|
10
|
+
covariance: number[][];
|
|
11
|
+
/** Shrinkage intensity in [0, 1]. */
|
|
12
|
+
shrinkage: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Ledoit–Wolf shrunk covariance estimator. `data` is an n×d matrix (rows are
|
|
17
|
+
* observations). The optimal shrinkage intensity follows the Ledoit–Wolf formula
|
|
18
|
+
* toward the scaled-identity target (tr(S)/d)·I.
|
|
19
|
+
*/
|
|
20
|
+
export function ledoitWolfCovariance(data: readonly (readonly number[])[]): CovarianceResult {
|
|
21
|
+
const n = data.length;
|
|
22
|
+
const d = data[0]?.length ?? 0;
|
|
23
|
+
if (n === 0 || d === 0) return { means: new Array(d).fill(0), covariance: [], shrinkage: 0 };
|
|
24
|
+
const means = new Array<number>(d).fill(0);
|
|
25
|
+
for (const row of data) for (let j = 0; j < d; j++) means[j]! += row[j]! / n;
|
|
26
|
+
const center = data.map((row) => row.map((v, j) => v - means[j]!));
|
|
27
|
+
const scale = 1 / n; // MLE denominator, matching the LW derivation
|
|
28
|
+
const s: number[][] = [];
|
|
29
|
+
for (let i = 0; i < d; i++) {
|
|
30
|
+
s.push(new Array<number>(d).fill(0));
|
|
31
|
+
for (let j = 0; j < d; j++) {
|
|
32
|
+
let acc = 0;
|
|
33
|
+
for (let r = 0; r < n; r++) acc += center[r]![i]! * center[r]![j]!;
|
|
34
|
+
s[i]![j] = acc * scale;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const trace = s.reduce((acc, row, i) => acc + row[i]!, 0);
|
|
38
|
+
const mu = trace / d;
|
|
39
|
+
// Sum of asymptotic variances of the off-diagonal (and diagonal) entries.
|
|
40
|
+
let deltaSum = 0;
|
|
41
|
+
for (let i = 0; i < d; i++) {
|
|
42
|
+
for (let j = 0; j < d; j++) {
|
|
43
|
+
let acc = 0;
|
|
44
|
+
for (let r = 0; r < n; r++) {
|
|
45
|
+
acc += (center[r]![i]! * center[r]![j]! - (i === j ? s[i]![i]! : s[i]![j]!)) ** 2;
|
|
46
|
+
}
|
|
47
|
+
deltaSum += acc / n;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
deltaSum *= scale * scale;
|
|
51
|
+
// Squared distance from S to the target.
|
|
52
|
+
let targetDist = 0;
|
|
53
|
+
for (let i = 0; i < d; i++) {
|
|
54
|
+
for (let j = 0; j < d; j++) {
|
|
55
|
+
const target = i === j ? mu : 0;
|
|
56
|
+
targetDist += (s[i]![j]! - target) ** 2;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const beta = Math.min(deltaSum, targetDist);
|
|
60
|
+
const shrinkage = targetDist > 0 ? beta / targetDist : 0;
|
|
61
|
+
const covariance = s.map((row, i) =>
|
|
62
|
+
row.map((v, j) => (1 - shrinkage) * v + (i === j ? shrinkage * mu : 0)),
|
|
63
|
+
);
|
|
64
|
+
return { means, covariance, shrinkage };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Population stability index, Σ (aᵢ − eᵢ) ln(aᵢ / eᵢ), over `bins` equal-width bins
|
|
69
|
+
* spanning [min, max] of the pooled data. Zero-count bins contribute 0 (the
|
|
70
|
+
* convention PS ≈ 0 uses). PSI above 0.2 signals drift (PRD 41 D12).
|
|
71
|
+
*/
|
|
72
|
+
export function psi(actual: readonly number[], expected: readonly number[], bins = 10): number {
|
|
73
|
+
if (!actual.length || !expected.length) return 0;
|
|
74
|
+
const lo = Math.min(...actual, ...expected);
|
|
75
|
+
const hi = Math.max(...actual, ...expected);
|
|
76
|
+
if (hi === lo) return 0;
|
|
77
|
+
const width = (hi - lo) / bins;
|
|
78
|
+
const count = (values: readonly number[]) => {
|
|
79
|
+
const counts = new Array<number>(bins).fill(0);
|
|
80
|
+
for (const v of values) {
|
|
81
|
+
const idx = Math.min(bins - 1, Math.floor((v - lo) / width));
|
|
82
|
+
counts[idx]!++;
|
|
83
|
+
}
|
|
84
|
+
return counts.map((c) => c / values.length);
|
|
85
|
+
};
|
|
86
|
+
const a = count(actual);
|
|
87
|
+
const e = count(expected);
|
|
88
|
+
let sum = 0;
|
|
89
|
+
for (let i = 0; i < bins; i++) {
|
|
90
|
+
if (a[i]! > 0 && e[i]! > 0) sum += (a[i]! - e[i]!) * Math.log(a[i]! / e[i]!);
|
|
91
|
+
}
|
|
92
|
+
return sum;
|
|
93
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Policies for the stats module (PRD 41 Part D / D13): Thompson sampling over
|
|
3
|
+
* Beta-bandit arms. Draws are made from the caller-supplied seeded RNG (prng.ts),
|
|
4
|
+
* so a schedule is reproducible under its seed. State-free: the RNG is the only
|
|
5
|
+
* source of randomness.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { type Rng } from "./prng.js";
|
|
9
|
+
|
|
10
|
+
export interface BetaArm {
|
|
11
|
+
alpha: number;
|
|
12
|
+
beta: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Beta draw by the Gamma-ratio method. */
|
|
16
|
+
function betaDraw(alpha: number, beta: number, rng: Rng): number {
|
|
17
|
+
const x = gammaDraw(alpha, rng);
|
|
18
|
+
const y = gammaDraw(beta, rng);
|
|
19
|
+
return x / (x + y);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Gamma(shape, 1) draw by Marsaglia's method; shape < 1 boosted by a fractional power. */
|
|
23
|
+
function gammaDraw(shape: number, rng: Rng): number {
|
|
24
|
+
if (shape < 1) {
|
|
25
|
+
const u = Math.max(rng(), 1e-12);
|
|
26
|
+
return gammaDraw(shape + 1, rng) * Math.pow(u, 1 / shape);
|
|
27
|
+
}
|
|
28
|
+
const d = shape - 1 / 3;
|
|
29
|
+
const c = 1 / Math.sqrt(9 * d);
|
|
30
|
+
for (;;) {
|
|
31
|
+
const z = normalZ(rng);
|
|
32
|
+
const v = Math.pow(1 + c * z, 3);
|
|
33
|
+
if (v <= 0) continue;
|
|
34
|
+
const u = rng();
|
|
35
|
+
if (Math.log(u) < 0.5 * z * z + d - d * v + d * Math.log(v)) return d * v;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Standard-normal draw via the polar form of Box–Muller (caches its spare). */
|
|
40
|
+
function makeNormalZ() {
|
|
41
|
+
let spare: number | null = null;
|
|
42
|
+
return (rng: Rng): number => {
|
|
43
|
+
if (spare !== null) {
|
|
44
|
+
const z = spare;
|
|
45
|
+
spare = null;
|
|
46
|
+
return z;
|
|
47
|
+
}
|
|
48
|
+
let u: number, v: number, s: number;
|
|
49
|
+
do {
|
|
50
|
+
u = rng() * 2 - 1;
|
|
51
|
+
v = rng() * 2 - 1;
|
|
52
|
+
s = u * u + v * v;
|
|
53
|
+
} while (s >= 1 || s === 0);
|
|
54
|
+
const mul = Math.sqrt((-2 * Math.log(s)) / s);
|
|
55
|
+
spare = v * mul;
|
|
56
|
+
return u * mul;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const normalZ = makeNormalZ();
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Sample one arm index by Thompson sampling: draw θᵢ ~ Beta(αᵢ, βᵢ) per arm and
|
|
63
|
+
* return the argmax. Deterministic under the supplied `rng`.
|
|
64
|
+
*/
|
|
65
|
+
export function thompsonSample(arms: readonly BetaArm[], rng: Rng): number {
|
|
66
|
+
let best = 0;
|
|
67
|
+
let bestDraw = -1;
|
|
68
|
+
for (let i = 0; i < arms.length; i++) {
|
|
69
|
+
const draw = betaDraw(arms[i]!.alpha, arms[i]!.beta, rng);
|
|
70
|
+
if (draw > bestDraw) {
|
|
71
|
+
bestDraw = draw;
|
|
72
|
+
best = i;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return best;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Rank all arms by one Thompson draw each, descending. Deterministic under `rng`. */
|
|
79
|
+
export function thompsonRank(arms: readonly BetaArm[], rng: Rng): number[] {
|
|
80
|
+
const draws = arms.map((arm) => betaDraw(arm.alpha, arm.beta, rng));
|
|
81
|
+
return arms
|
|
82
|
+
.map((_, i) => i)
|
|
83
|
+
.sort((a, b) => draws[b]! - draws[a]! || a - b);
|
|
84
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic seeded PRNG for the stats module (PRD 41 Part D, D13/B8): every
|
|
3
|
+
* stochastic routine here draws from THIS generator, seeded by the caller, so the
|
|
4
|
+
* same inputs give byte-identical outputs on any machine. Algorithm: xoshiro128**.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type Rng = () => number;
|
|
8
|
+
|
|
9
|
+
/** SplitMix32-style seed expansion to four uint32 words. */
|
|
10
|
+
function seedWords(seed: number): [number, number, number, number] {
|
|
11
|
+
let s = seed >>> 0;
|
|
12
|
+
const next = () => {
|
|
13
|
+
s = (s + 0x9e3779b9) >>> 0;
|
|
14
|
+
let z = s;
|
|
15
|
+
z = Math.imul(z ^ (z >>> 16), 0x21f0aaad) >>> 0;
|
|
16
|
+
z = Math.imul(z ^ (z >>> 15), 0x735a2d97) >>> 0;
|
|
17
|
+
z = (z ^ (z >>> 15)) >>> 0;
|
|
18
|
+
return z;
|
|
19
|
+
};
|
|
20
|
+
return [next(), next(), next(), next()];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A deterministic RNG in [0, 1), seeded once. `seed = 0` is a valid seed. */
|
|
24
|
+
export function createRng(seed: number): Rng {
|
|
25
|
+
let [a, b, c, d] = seedWords(seed);
|
|
26
|
+
return () => {
|
|
27
|
+
const result = (Math.imul(b, 5) << 7 | Math.imul(b, 5) >>> 25) >>> 0;
|
|
28
|
+
const out = ((result * 9) >>> 0) / 4294967296;
|
|
29
|
+
const t = (b << 9 | b >>> 23) >>> 0;
|
|
30
|
+
c = (c ^ a) >>> 0;
|
|
31
|
+
d = (d ^ b) >>> 0;
|
|
32
|
+
b = (b ^ c) >>> 0;
|
|
33
|
+
a = (a ^ d) >>> 0;
|
|
34
|
+
c = (c ^ t) >>> 0;
|
|
35
|
+
d = ((d << 11) | (d >>> 21)) >>> 0;
|
|
36
|
+
return out;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Box–Muller standard-normal draw from a uniform RNG (deterministic under seed). */
|
|
41
|
+
export function normalDraw(rng: Rng): number {
|
|
42
|
+
const u1 = Math.max(rng(), Number.EPSILON);
|
|
43
|
+
const u2 = rng();
|
|
44
|
+
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
|
|
45
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scoring functions for the stats module (PRD 41 Part D / D13): Brier, expected
|
|
3
|
+
* calibration error, PR-AUC, NDCG, Popt and effort-aware recall. All are pure,
|
|
4
|
+
* deterministic orderings on their inputs.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Brier score: mean squared error of probabilistic predictions. Lower is better. */
|
|
8
|
+
export function brierScore(probabilities: readonly number[], outcomes: readonly number[]): number {
|
|
9
|
+
const n = Math.min(probabilities.length, outcomes.length);
|
|
10
|
+
if (n === 0) return 0;
|
|
11
|
+
let sum = 0;
|
|
12
|
+
for (let i = 0; i < n; i++) sum += (probabilities[i]! - outcomes[i]!) ** 2;
|
|
13
|
+
return sum / n;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Expected calibration error over `bins` equal-width probability bins: the weighted
|
|
18
|
+
* mean of |accuracy − confidence| per bin.
|
|
19
|
+
*/
|
|
20
|
+
export function expectedCalibrationError(
|
|
21
|
+
probabilities: readonly number[],
|
|
22
|
+
outcomes: readonly number[],
|
|
23
|
+
bins = 10,
|
|
24
|
+
): number {
|
|
25
|
+
const n = Math.min(probabilities.length, outcomes.length);
|
|
26
|
+
if (n === 0) return 0;
|
|
27
|
+
let ece = 0;
|
|
28
|
+
for (let b = 0; b < bins; b++) {
|
|
29
|
+
const lo = b / bins;
|
|
30
|
+
const hi = (b + 1) / bins;
|
|
31
|
+
let count = 0;
|
|
32
|
+
let confSum = 0;
|
|
33
|
+
let accSum = 0;
|
|
34
|
+
for (let i = 0; i < n; i++) {
|
|
35
|
+
const p = probabilities[i]!;
|
|
36
|
+
if (p >= lo && (p < hi || (b === bins - 1 && p === 1))) {
|
|
37
|
+
count++;
|
|
38
|
+
confSum += p;
|
|
39
|
+
accSum += outcomes[i]!;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (count > 0) {
|
|
43
|
+
ece += (count / n) * Math.abs(accSum / count - confSum / count);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return ece;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Area under the precision–recall curve (trapezoid over the full recall range). */
|
|
50
|
+
export function prAuc(scores: readonly number[], labels: readonly number[]): number {
|
|
51
|
+
const n = Math.min(scores.length, labels.length);
|
|
52
|
+
if (n === 0) return 0;
|
|
53
|
+
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => scores[b]! - scores[a]!);
|
|
54
|
+
const totalPos = labels.reduce((a, _, i) => a + (i < n && labels[i] === 1 ? 1 : 0), 0);
|
|
55
|
+
if (totalPos === 0) return 0;
|
|
56
|
+
let tp = 0;
|
|
57
|
+
let fp = 0;
|
|
58
|
+
let prevRecall = 0;
|
|
59
|
+
let prevPrecision = 1;
|
|
60
|
+
let auc = 0;
|
|
61
|
+
for (const i of order) {
|
|
62
|
+
if (labels[i] === 1) tp++;
|
|
63
|
+
else fp++;
|
|
64
|
+
const recall = tp / totalPos;
|
|
65
|
+
const precision = tp / (tp + fp);
|
|
66
|
+
auc += (recall - prevRecall) * ((precision + prevPrecision) / 2);
|
|
67
|
+
prevRecall = recall;
|
|
68
|
+
prevPrecision = precision;
|
|
69
|
+
}
|
|
70
|
+
return auc;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* NDCG@k from graded relevance, with the log2 discount (position 1 = 1). The ideal
|
|
75
|
+
* DCG orders by relevance descending.
|
|
76
|
+
*/
|
|
77
|
+
export function ndcgAtK(relevances: readonly number[], k: number): number {
|
|
78
|
+
const take = relevances.slice(0, k);
|
|
79
|
+
const dcg = take.reduce((acc, rel, i) => acc + rel / Math.log2(i + 2), 0);
|
|
80
|
+
const ideal = [...relevances].sort((a, b) => b - a).slice(0, k)
|
|
81
|
+
.reduce((acc, rel, i) => acc + rel / Math.log2(i + 2), 0);
|
|
82
|
+
return ideal > 0 ? dcg / ideal : 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Popt (performance optimum): the area under the effort–accuracy curve achieved in
|
|
87
|
+
* the given order, normalized by the area of the optimal ordering (items sorted by
|
|
88
|
+
* score descending). `efforts` are per-item costs, `scores` are per-item values.
|
|
89
|
+
* Returns a value in (0, 1], 1 for the optimal order.
|
|
90
|
+
*/
|
|
91
|
+
export function popt(efforts: readonly number[], scores: readonly number[]): number {
|
|
92
|
+
const n = Math.min(efforts.length, scores.length);
|
|
93
|
+
if (n === 0) return 0;
|
|
94
|
+
const area = (order: readonly number[]) => {
|
|
95
|
+
let acc = 0;
|
|
96
|
+
let cumEffort = 0;
|
|
97
|
+
let cumScore = 0;
|
|
98
|
+
let prevScore = 0;
|
|
99
|
+
for (const i of order) {
|
|
100
|
+
cumEffort += efforts[i]!;
|
|
101
|
+
cumScore += scores[i]!;
|
|
102
|
+
acc += efforts[i]! * (cumScore + prevScore) / 2;
|
|
103
|
+
prevScore = cumScore;
|
|
104
|
+
}
|
|
105
|
+
void cumEffort;
|
|
106
|
+
return acc;
|
|
107
|
+
};
|
|
108
|
+
const optimal = area(scores.map((_, i) => i).sort((a, b) => scores[b]! - scores[a]!));
|
|
109
|
+
if (optimal <= 0) return 0;
|
|
110
|
+
return area(scores.map((_, i) => i)) / optimal;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Effort-aware recall: the share of the target found after spending `effortBudget`
|
|
115
|
+
* fraction of the total effort, where items are examined in the given order.
|
|
116
|
+
* `efforts` are per-item costs.
|
|
117
|
+
*/
|
|
118
|
+
export function effortAwareRecall(
|
|
119
|
+
relevant: readonly boolean[],
|
|
120
|
+
efforts: readonly number[],
|
|
121
|
+
effortBudget: number,
|
|
122
|
+
): number {
|
|
123
|
+
const totalRelevant = relevant.filter(Boolean).length;
|
|
124
|
+
if (totalRelevant === 0) return 0;
|
|
125
|
+
const totalEffort = efforts.reduce((a, b) => a + b, 0);
|
|
126
|
+
const budget = totalEffort * effortBudget;
|
|
127
|
+
let spent = 0;
|
|
128
|
+
let found = 0;
|
|
129
|
+
for (let i = 0; i < relevant.length; i++) {
|
|
130
|
+
if (spent + efforts[i]! > budget) break;
|
|
131
|
+
spent += efforts[i]!;
|
|
132
|
+
if (relevant[i]) found++;
|
|
133
|
+
}
|
|
134
|
+
return found / totalRelevant;
|
|
135
|
+
}
|