@seanhogg/builderforce-memory 2026.10.62 → 2026.10.66
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/pack/frame.d.ts +12 -3
- package/dist/knowledge/pack/frame.d.ts.map +1 -1
- package/dist/knowledge/pack/frame.js +18 -4
- package/dist/knowledge/pack/frame.js.map +1 -1
- package/dist/knowledge/pack/manifest.d.ts +11 -3
- package/dist/knowledge/pack/manifest.d.ts.map +1 -1
- package/dist/knowledge/pack/manifest.js +26 -12
- package/dist/knowledge/pack/manifest.js.map +1 -1
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extr.js +16 -4
- package/dist/knowledge/pack/sections/extr.js.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/extrLists.js +5 -6
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/facts.js +3 -2
- package/dist/knowledge/pack/sections/facts.js.map +1 -1
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/rows.js +11 -2
- package/dist/knowledge/pack/sections/rows.js.map +1 -1
- package/dist/knowledge/pack/strings.d.ts.map +1 -1
- package/dist/knowledge/pack/strings.js +6 -1
- package/dist/knowledge/pack/strings.js.map +1 -1
- package/dist/knowledge/pack/varint.d.ts +14 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -1
- package/dist/knowledge/pack/varint.js +32 -1
- package/dist/knowledge/pack/varint.js.map +1 -1
- package/dist/knowledge/review.d.ts +6 -6
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +56 -329
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewAnalyse.d.ts +17 -0
- package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
- package/dist/knowledge/reviewAnalyse.js +61 -0
- package/dist/knowledge/reviewAnalyse.js.map +1 -0
- package/dist/knowledge/reviewApply.d.ts +33 -0
- package/dist/knowledge/reviewApply.d.ts.map +1 -0
- package/dist/knowledge/reviewApply.js +121 -0
- package/dist/knowledge/reviewApply.js.map +1 -0
- package/dist/knowledge/reviewContext.d.ts +77 -0
- package/dist/knowledge/reviewContext.d.ts.map +1 -0
- package/dist/knowledge/reviewContext.js +111 -0
- package/dist/knowledge/reviewContext.js.map +1 -0
- package/dist/knowledge/reviewFinish.d.ts +9 -0
- package/dist/knowledge/reviewFinish.d.ts.map +1 -0
- package/dist/knowledge/reviewFinish.js +62 -0
- package/dist/knowledge/reviewFinish.js.map +1 -0
- package/dist/knowledge/reviewRunModel.d.ts +3 -0
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.js +38 -13
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
- package/dist/knowledge/stores/extractRefs.d.ts +68 -0
- package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
- package/dist/knowledge/stores/extractRefs.js +168 -0
- package/dist/knowledge/stores/extractRefs.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +25 -5
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +6 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
- package/dist/knowledge/stores/rowDelta.js.map +1 -1
- package/dist/knowledge/stores/rowMemory.d.ts +30 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
- package/dist/knowledge/stores/rowMemory.js +46 -1
- package/dist/knowledge/stores/rowMemory.js.map +1 -1
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
- package/dist/knowledge/stores/rowSync.js +2 -1
- package/dist/knowledge/stores/rowSync.js.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +22 -9
- package/dist/knowledge/stores/snapshotFormat.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 +65 -0
- package/dist/working/fold.d.ts.map +1 -0
- package/dist/working/fold.js +228 -0
- package/dist/working/fold.js.map +1 -0
- package/dist/working/index.d.ts +3 -0
- package/dist/working/index.d.ts.map +1 -1
- package/dist/working/index.js +2 -0
- package/dist/working/index.js.map +1 -1
- package/dist/working/textSummary.d.ts +46 -0
- package/dist/working/textSummary.d.ts.map +1 -0
- package/dist/working/textSummary.js +142 -0
- package/dist/working/textSummary.js.map +1 -0
- package/package.json +5 -1
- package/src/contract/exports.snapshot.json +48 -1
- package/src/contract/regression.extractEviction.test.ts +162 -0
- package/src/contract/regression.fixCommits.test.ts +112 -0
- package/src/contract/regression.packWire.test.ts +174 -0
- package/src/contract/types.contract.test.ts +2 -1
- package/src/knowledge/pack/frame.ts +21 -5
- package/src/knowledge/pack/manifest.ts +26 -11
- package/src/knowledge/pack/sections/extr.ts +14 -4
- package/src/knowledge/pack/sections/extrLists.ts +4 -6
- package/src/knowledge/pack/sections/facts.ts +3 -2
- package/src/knowledge/pack/sections/rows.ts +11 -2
- package/src/knowledge/pack/strings.ts +5 -1
- package/src/knowledge/pack/varint.ts +33 -1
- package/src/knowledge/review.ts +58 -311
- package/src/knowledge/reviewAnalyse.ts +59 -0
- package/src/knowledge/reviewApply.ts +128 -0
- package/src/knowledge/reviewContext.ts +158 -0
- package/src/knowledge/reviewFinish.ts +63 -0
- package/src/knowledge/reviewRunModel.ts +3 -0
- package/src/knowledge/stores/extractLogWriter.ts +36 -12
- package/src/knowledge/stores/extractRefs.ts +161 -0
- package/src/knowledge/stores/localSnapshotStore.ts +22 -5
- package/src/knowledge/stores/rowDelta.ts +6 -0
- package/src/knowledge/stores/rowMemory.ts +50 -1
- package/src/knowledge/stores/rowSync.ts +2 -1
- package/src/knowledge/stores/snapshotFormat.ts +27 -10
- 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 +252 -0
- package/src/working/index.ts +13 -0
- package/src/working/textSummary.test.ts +113 -0
- package/src/working/textSummary.ts +156 -0
|
@@ -66,6 +66,22 @@ export function stripUndefined<T extends object>(o: T): Partial<T> {
|
|
|
66
66
|
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* What a COMPACTED log line records beside its body: `c` the source refs it is current for, `p` those it is the previous body of
|
|
71
|
+
* (extractRefs.ts). An appended line has neither: its replay derives them from the put sequence. Older readers ignore both.
|
|
72
|
+
*/
|
|
73
|
+
export interface LoggedRefState { current: string[]; previous: string[] }
|
|
74
|
+
|
|
75
|
+
const strings = (v: unknown): string[] | undefined => (Array.isArray(v) && v.every((x) => typeof x === 'string') ? v as string[] : undefined);
|
|
76
|
+
|
|
77
|
+
function refStateOf(row: { c?: unknown; p?: unknown }): LoggedRefState | undefined {
|
|
78
|
+
const current = strings(row.c), previous = strings(row.p);
|
|
79
|
+
return current || previous ? { current: current ?? [], previous: previous ?? [] } : undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One compacted log line (newline-terminated) for a body and its reference state. */
|
|
83
|
+
export const compactedLogLine = (h: string, e: Extracted[], s: LoggedRefState): string => `${JSON.stringify({ h, e, c: s.current, p: s.previous })}\n`;
|
|
84
|
+
|
|
69
85
|
export interface ParsedLog {
|
|
70
86
|
entries: Map<string, Extracted[]>;
|
|
71
87
|
/** The live (last) line of each hash, newline-terminated, in log order. */
|
|
@@ -77,21 +93,22 @@ export interface ParsedLog {
|
|
|
77
93
|
|
|
78
94
|
/**
|
|
79
95
|
* The log's entries, last line per hash winning. A line that does not parse (torn by a crash or a failed
|
|
80
|
-
* append) is skipped on its own: it never costs the other lines.
|
|
96
|
+
* append) is skipped on its own: it never costs the other lines. `onLine` sees EVERY parsed line in log order (superseded
|
|
97
|
+
* ones too), for a reader that replays the puts.
|
|
81
98
|
*/
|
|
82
|
-
export function parseLog(text: string | undefined): ParsedLog {
|
|
99
|
+
export function parseLog(text: string | undefined, onLine?: (hash: string, entries: Extracted[], state?: LoggedRefState) => void): ParsedLog {
|
|
83
100
|
const out: ParsedLog = { entries: new Map(), liveLines: new Map(), liveBytes: 0, deadBytes: 0 };
|
|
84
101
|
if (!text) return out;
|
|
85
102
|
for (const line of text.split('\n')) {
|
|
86
103
|
if (!line.trim()) continue;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
104
|
+
let row: { h?: unknown; e?: unknown; c?: unknown; p?: unknown };
|
|
105
|
+
// Only a line that does not parse is torn; a failure of the replay below is the caller's and surfaces.
|
|
106
|
+
try { row = JSON.parse(line) as typeof row; } catch { continue; /* torn line */ }
|
|
107
|
+
if (!row || typeof row.h !== 'string' || !Array.isArray(row.e)) continue;
|
|
108
|
+
out.entries.set(row.h, row.e as Extracted[]);
|
|
109
|
+
out.liveLines.delete(row.h); // re-set below so the map stays in log order of last occurrence
|
|
110
|
+
out.liveLines.set(row.h, `${line}\n`);
|
|
111
|
+
onLine?.(row.h, row.e as Extracted[], refStateOf(row));
|
|
95
112
|
}
|
|
96
113
|
for (const l of out.liveLines.values()) out.liveBytes += l.length;
|
|
97
114
|
out.deadBytes = Math.max(0, text.length - out.liveBytes);
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Distribution functions for the stats module (PRD 41 Part D / D13): Beta posterior
|
|
3
|
+
* and quantile, Gamma quantile and the exact Poisson (Garwood) interval. Pure and
|
|
4
|
+
* deterministic; the incomplete-beta and incomplete-gamma implementations follow the
|
|
5
|
+
* continued-fraction / series methods (Numerical Recipes), which are stable for the
|
|
6
|
+
* shape ranges Part D uses (posterior counts and sample sizes).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const MAX_ITER = 200;
|
|
10
|
+
const EPS = 3e-14;
|
|
11
|
+
const FPMIN = 1e-300;
|
|
12
|
+
|
|
13
|
+
function logGamma(x: number): number {
|
|
14
|
+
// Lanczos approximation, sufficient for the moderate arguments here.
|
|
15
|
+
const p = [
|
|
16
|
+
676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
|
|
17
|
+
12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
|
|
18
|
+
];
|
|
19
|
+
if (x < 0.5) {
|
|
20
|
+
return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
|
|
21
|
+
}
|
|
22
|
+
const z = x - 1;
|
|
23
|
+
let sum = 0.99999999999980993;
|
|
24
|
+
for (let i = 0; i < p.length; i++) sum += p[i]! / (z + i + 1);
|
|
25
|
+
const t = z + p.length - 0.5;
|
|
26
|
+
return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(sum);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function betaCf(a: number, b: number, x: number): number {
|
|
30
|
+
const qab = a + b;
|
|
31
|
+
const qap = a + 1;
|
|
32
|
+
const qam = a - 1;
|
|
33
|
+
let c = 1;
|
|
34
|
+
let d = 1 - (qab * x) / qap;
|
|
35
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
36
|
+
d = 1 / d;
|
|
37
|
+
let h = d;
|
|
38
|
+
for (let m = 1; m <= MAX_ITER; m++) {
|
|
39
|
+
const m2 = 2 * m;
|
|
40
|
+
let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
|
|
41
|
+
d = 1 + aa * d;
|
|
42
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
43
|
+
c = 1 + aa / c;
|
|
44
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
45
|
+
d = 1 / d;
|
|
46
|
+
h *= d * c;
|
|
47
|
+
aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
|
|
48
|
+
d = 1 + aa * d;
|
|
49
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
50
|
+
c = 1 + aa / c;
|
|
51
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
52
|
+
d = 1 / d;
|
|
53
|
+
const del = d * c;
|
|
54
|
+
h *= del;
|
|
55
|
+
if (Math.abs(del - 1) < EPS) break;
|
|
56
|
+
}
|
|
57
|
+
return h;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Regularized incomplete beta I_x(a, b). */
|
|
61
|
+
export function regularizedIncompleteBeta(x: number, a: number, b: number): number {
|
|
62
|
+
if (x <= 0) return 0;
|
|
63
|
+
if (x >= 1) return 1;
|
|
64
|
+
const bt = Math.exp(
|
|
65
|
+
logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x),
|
|
66
|
+
);
|
|
67
|
+
if (x < (a + 1) / (a + b + 2)) return (bt * betaCf(a, b, x)) / a;
|
|
68
|
+
return 1 - (bt * betaCf(b, a, 1 - x)) / b;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Inverse of the regularized incomplete beta, by bisection. Deterministic. */
|
|
72
|
+
export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number): number {
|
|
73
|
+
if (p <= 0) return 0;
|
|
74
|
+
if (p >= 1) return 1;
|
|
75
|
+
let lo = 0;
|
|
76
|
+
let hi = 1;
|
|
77
|
+
for (let i = 0; i < 100; i++) {
|
|
78
|
+
const mid = (lo + hi) / 2;
|
|
79
|
+
if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
|
|
80
|
+
else hi = mid;
|
|
81
|
+
}
|
|
82
|
+
return (lo + hi) / 2;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
|
|
86
|
+
export interface BetaPosterior {
|
|
87
|
+
alpha: number;
|
|
88
|
+
beta: number;
|
|
89
|
+
mean: number;
|
|
90
|
+
quantile(p: number): number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function betaPosterior(alpha0: number, beta0: number, k: number, n: number): BetaPosterior {
|
|
94
|
+
const alpha = alpha0 + k;
|
|
95
|
+
const beta = beta0 + (n - k);
|
|
96
|
+
return {
|
|
97
|
+
alpha,
|
|
98
|
+
beta,
|
|
99
|
+
mean: alpha / (alpha + beta),
|
|
100
|
+
quantile: (p) => inverseRegularizedIncompleteBeta(p, alpha, beta),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function gammaQ(a: number, x: number): number {
|
|
105
|
+
// Regularized upper incomplete gamma Q(a, x) via continued fraction.
|
|
106
|
+
let b = x + 1 - a;
|
|
107
|
+
let c = 1 / FPMIN;
|
|
108
|
+
let d = 1 / b;
|
|
109
|
+
let h = d;
|
|
110
|
+
for (let i = 1; i <= MAX_ITER; i++) {
|
|
111
|
+
const an = -i * (i - a);
|
|
112
|
+
b += 2;
|
|
113
|
+
d = an * d + b;
|
|
114
|
+
if (Math.abs(d) < FPMIN) d = FPMIN;
|
|
115
|
+
c = b + an / c;
|
|
116
|
+
if (Math.abs(c) < FPMIN) c = FPMIN;
|
|
117
|
+
d = 1 / d;
|
|
118
|
+
const del = d * c;
|
|
119
|
+
h *= del;
|
|
120
|
+
if (Math.abs(del - 1) < EPS) break;
|
|
121
|
+
}
|
|
122
|
+
return Math.exp(-x + a * Math.log(x) - logGamma(a)) * h;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Regularized lower incomplete gamma P(a, x). */
|
|
126
|
+
export function regularizedIncompleteGamma(a: number, x: number): number {
|
|
127
|
+
if (x <= 0) return 0;
|
|
128
|
+
if (x < a + 1) {
|
|
129
|
+
// Series representation for P.
|
|
130
|
+
let sum = 1 / a;
|
|
131
|
+
let term = sum;
|
|
132
|
+
for (let n = 1; n <= MAX_ITER; n++) {
|
|
133
|
+
term *= x / (a + n);
|
|
134
|
+
sum += term;
|
|
135
|
+
if (Math.abs(term) < Math.abs(sum) * EPS) break;
|
|
136
|
+
}
|
|
137
|
+
return Math.exp(-x + a * Math.log(x) - logGamma(a)) * sum;
|
|
138
|
+
}
|
|
139
|
+
return 1 - gammaQ(a, x);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Gamma(shape, scale) quantile by bisection on the CDF. Deterministic. */
|
|
143
|
+
export function gammaQuantile(p: number, shape: number, scale = 1): number {
|
|
144
|
+
if (p <= 0) return 0;
|
|
145
|
+
if (p >= 1) return Infinity;
|
|
146
|
+
let lo = 0;
|
|
147
|
+
let hi = Math.max(shape * scale * 2, scale, 1e-9);
|
|
148
|
+
while (regularizedIncompleteGamma(shape, hi / scale) < p) {
|
|
149
|
+
hi *= 2;
|
|
150
|
+
if (hi > 1e12) break;
|
|
151
|
+
}
|
|
152
|
+
for (let i = 0; i < 100; i++) {
|
|
153
|
+
const mid = (lo + hi) / 2;
|
|
154
|
+
if (regularizedIncompleteGamma(shape, mid / scale) < p) lo = mid;
|
|
155
|
+
else hi = mid;
|
|
156
|
+
}
|
|
157
|
+
return (lo + hi) / 2;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Exact Poisson confidence interval (Garwood, 1936): the equal-tailed interval
|
|
162
|
+
* built from chi-square / gamma quantiles. `count` events over `exposure`.
|
|
163
|
+
*/
|
|
164
|
+
export function garwoodPoissonInterval(
|
|
165
|
+
count: number,
|
|
166
|
+
exposure = 1,
|
|
167
|
+
confidence = 0.95,
|
|
168
|
+
): { low: number; high: number; rateLow: number; rateHigh: number } {
|
|
169
|
+
const alpha = 1 - confidence;
|
|
170
|
+
// Gamma quantiles with chi-square scaling: χ²_{2k, α} = 2·GammaQuantile(α, k).
|
|
171
|
+
const low =
|
|
172
|
+
count === 0 ? 0 : gammaQuantile(alpha / 2, count) * 2;
|
|
173
|
+
const high = gammaQuantile(1 - alpha / 2, count + 1) * 2;
|
|
174
|
+
return {
|
|
175
|
+
low,
|
|
176
|
+
high,
|
|
177
|
+
rateLow: low / (2 * exposure),
|
|
178
|
+
rateHigh: high / (2 * exposure),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Estimators for the stats module (PRD 41 Part D / D13): capture–recapture
|
|
3
|
+
* (Chapman / Lincoln–Petersen), Kaplan–Meier with Greenwood variance, the
|
|
4
|
+
* Goel–Okumoto reliability-growth MLE and Gamma–Poisson empirical Bayes. Pure and
|
|
5
|
+
* deterministic; `insufficient-data` is reported, never guessed around.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type InsufficientData = { status: "insufficient-data" };
|
|
9
|
+
|
|
10
|
+
/** Chapman estimator: n̂ = ((m+1)(c+1)/(r+1)) − 1. Needs r ≥ 1 (and m, c ≥ 3 by the D-done-check). */
|
|
11
|
+
export function chapmanEstimate(
|
|
12
|
+
capturedM: number,
|
|
13
|
+
capturedC: number,
|
|
14
|
+
recapturedR: number,
|
|
15
|
+
): { estimate: number } | InsufficientData {
|
|
16
|
+
if (recapturedR < 1) return { status: "insufficient-data" };
|
|
17
|
+
return { estimate: ((capturedM + 1) * (capturedC + 1)) / (recapturedR + 1) - 1 };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Lincoln–Petersen: n̂ = m·c / r (the biased form; Chapman above is preferred). */
|
|
21
|
+
export function lincolnPetersenEstimate(
|
|
22
|
+
capturedM: number,
|
|
23
|
+
capturedC: number,
|
|
24
|
+
recapturedR: number,
|
|
25
|
+
): { estimate: number } | InsufficientData {
|
|
26
|
+
if (recapturedR < 1) return { status: "insufficient-data" };
|
|
27
|
+
return { estimate: (capturedM * capturedC) / recapturedR };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface KaplanMeierResult {
|
|
31
|
+
/** Survival probability after the last event time (the "current" survival). */
|
|
32
|
+
survival: number;
|
|
33
|
+
/** Greenwood variance of that survival. */
|
|
34
|
+
variance: number;
|
|
35
|
+
/** (time, survival) steps at each distinct event time. */
|
|
36
|
+
curve: Array<{ time: number; survival: number }>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Kaplan–Meier product-limit estimator on (time, event) rows; censored rows have event = 0. */
|
|
40
|
+
export function kaplanMeier(rows: readonly { time: number; event: 0 | 1 }[]): KaplanMeierResult {
|
|
41
|
+
const times = [...new Set(rows.map((r) => r.time))].sort((a, b) => a - b);
|
|
42
|
+
let survival = 1;
|
|
43
|
+
let greenwood = 0;
|
|
44
|
+
const curve: Array<{ time: number; survival: number }> = [];
|
|
45
|
+
for (const t of times) {
|
|
46
|
+
const atRisk = rows.filter((r) => r.time >= t).length;
|
|
47
|
+
const events = rows.filter((r) => r.time === t && r.event === 1).length;
|
|
48
|
+
if (atRisk > 0 && events > 0) {
|
|
49
|
+
survival *= 1 - events / atRisk;
|
|
50
|
+
if (atRisk - events > 0) greenwood += events / (atRisk * (atRisk - events));
|
|
51
|
+
}
|
|
52
|
+
curve.push({ time: t, survival });
|
|
53
|
+
}
|
|
54
|
+
return { survival, variance: survival * survival * greenwood, curve };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Goel–Okumoto NHPP MLE: mean failures μ(t) = a(1 − e^{−bt}). a is solved in
|
|
59
|
+
* closed form given b; b is refined by bisection on the score equation
|
|
60
|
+
* Σ tᵢ = n/b − n·t̄·e^{−b·t̄}/(1 − e^{−b·t̄}). Needs n ≥ 2 distinct times.
|
|
61
|
+
*/
|
|
62
|
+
export function goelOkumotoMLE(
|
|
63
|
+
times: readonly number[],
|
|
64
|
+
): { a: number; b: number } | InsufficientData {
|
|
65
|
+
const sorted = [...times].sort((a, b) => a - b);
|
|
66
|
+
const n = sorted.length;
|
|
67
|
+
if (n < 2) return { status: "insufficient-data" };
|
|
68
|
+
const tMax = sorted[n - 1]!;
|
|
69
|
+
const tMean = sorted.reduce((a, b) => a + b, 0) / n;
|
|
70
|
+
const score = (b: number) => {
|
|
71
|
+
if (b <= 0) return Infinity;
|
|
72
|
+
const denom = 1 - Math.exp(-b * tMax);
|
|
73
|
+
return n / b - (n * tMean * Math.exp(-b * tMean)) / denom;
|
|
74
|
+
};
|
|
75
|
+
let lo = 1e-9;
|
|
76
|
+
let hi = 1;
|
|
77
|
+
while (score(hi) > 0 && hi < 1e6) hi *= 2;
|
|
78
|
+
for (let i = 0; i < 100; i++) {
|
|
79
|
+
const mid = (lo + hi) / 2;
|
|
80
|
+
if (score(mid) > 0) lo = mid;
|
|
81
|
+
else hi = mid;
|
|
82
|
+
}
|
|
83
|
+
const b = (lo + hi) / 2;
|
|
84
|
+
const a = n / (1 - Math.exp(-b * tMax));
|
|
85
|
+
return { a, b };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Gamma–Poisson empirical Bayes rate posterior. Prior Gamma(α₀, β₀) over the rate;
|
|
90
|
+
* observing `count` events over `exposure` gives Gamma(α₀ + count, β₀ + exposure).
|
|
91
|
+
*/
|
|
92
|
+
export function gammaPoissonPosterior(
|
|
93
|
+
alpha0: number,
|
|
94
|
+
beta0: number,
|
|
95
|
+
count: number,
|
|
96
|
+
exposure: number,
|
|
97
|
+
): { alpha: number; beta: number; mean: number; variance: number } {
|
|
98
|
+
const alpha = alpha0 + count;
|
|
99
|
+
const beta = beta0 + exposure;
|
|
100
|
+
return { alpha, beta, mean: alpha / beta, variance: alpha / (beta * beta) };
|
|
101
|
+
}
|
|
@@ -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
|
+
}
|