@seanhogg/builderforce-memory 2026.10.62 → 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.
Files changed (69) hide show
  1. package/dist/stats/distributions.d.ts +34 -0
  2. package/dist/stats/distributions.d.ts.map +1 -0
  3. package/dist/stats/distributions.js +180 -0
  4. package/dist/stats/distributions.js.map +1 -0
  5. package/dist/stats/estimators.d.ts +53 -0
  6. package/dist/stats/estimators.d.ts.map +1 -0
  7. package/dist/stats/estimators.js +79 -0
  8. package/dist/stats/estimators.js.map +1 -0
  9. package/dist/stats/fitting.d.ts +48 -0
  10. package/dist/stats/fitting.d.ts.map +1 -0
  11. package/dist/stats/fitting.js +209 -0
  12. package/dist/stats/fitting.js.map +1 -0
  13. package/dist/stats/index.d.ts +26 -0
  14. package/dist/stats/index.d.ts.map +1 -0
  15. package/dist/stats/index.js +18 -0
  16. package/dist/stats/index.js.map +1 -0
  17. package/dist/stats/information.d.ts +9 -0
  18. package/dist/stats/information.d.ts.map +1 -0
  19. package/dist/stats/information.js +21 -0
  20. package/dist/stats/information.js.map +1 -0
  21. package/dist/stats/multivariate.d.ts +25 -0
  22. package/dist/stats/multivariate.d.ts.map +1 -0
  23. package/dist/stats/multivariate.js +89 -0
  24. package/dist/stats/multivariate.js.map +1 -0
  25. package/dist/stats/policies.d.ts +19 -0
  26. package/dist/stats/policies.d.ts.map +1 -0
  27. package/dist/stats/policies.js +75 -0
  28. package/dist/stats/policies.js.map +1 -0
  29. package/dist/stats/prng.d.ts +11 -0
  30. package/dist/stats/prng.d.ts.map +1 -0
  31. package/dist/stats/prng.js +41 -0
  32. package/dist/stats/prng.js.map +1 -0
  33. package/dist/stats/scores.d.ts +33 -0
  34. package/dist/stats/scores.d.ts.map +1 -0
  35. package/dist/stats/scores.js +134 -0
  36. package/dist/stats/scores.js.map +1 -0
  37. package/dist/stats/tests.d.ts +48 -0
  38. package/dist/stats/tests.d.ts.map +1 -0
  39. package/dist/stats/tests.js +143 -0
  40. package/dist/stats/tests.js.map +1 -0
  41. package/dist/stats/timeSeries.d.ts +34 -0
  42. package/dist/stats/timeSeries.d.ts.map +1 -0
  43. package/dist/stats/timeSeries.js +71 -0
  44. package/dist/stats/timeSeries.js.map +1 -0
  45. package/dist/working/fold.d.ts +51 -0
  46. package/dist/working/fold.d.ts.map +1 -0
  47. package/dist/working/fold.js +218 -0
  48. package/dist/working/fold.js.map +1 -0
  49. package/dist/working/index.d.ts +1 -0
  50. package/dist/working/index.d.ts.map +1 -1
  51. package/dist/working/index.js +1 -0
  52. package/dist/working/index.js.map +1 -1
  53. package/package.json +5 -1
  54. package/src/contract/exports.snapshot.json +41 -0
  55. package/src/stats/distributions.ts +180 -0
  56. package/src/stats/estimators.ts +101 -0
  57. package/src/stats/fitting.ts +252 -0
  58. package/src/stats/index.ts +59 -0
  59. package/src/stats/information.ts +20 -0
  60. package/src/stats/multivariate.ts +93 -0
  61. package/src/stats/policies.ts +84 -0
  62. package/src/stats/prng.ts +45 -0
  63. package/src/stats/scores.ts +135 -0
  64. package/src/stats/stats.test.ts +294 -0
  65. package/src/stats/tests.ts +164 -0
  66. package/src/stats/timeSeries.ts +92 -0
  67. package/src/working/fold.test.ts +196 -0
  68. package/src/working/fold.ts +241 -0
  69. package/src/working/index.ts +1 -0
@@ -527,6 +527,41 @@
527
527
  "toDecayLambda",
528
528
  "tokenize"
529
529
  ],
530
+ "./stats": [
531
+ "bayesianOnlineChangePoint",
532
+ "betaPosterior",
533
+ "brierScore",
534
+ "chapmanEstimate",
535
+ "createRng",
536
+ "cusum",
537
+ "effortAwareRecall",
538
+ "entropyOfCounts",
539
+ "expectedCalibrationError",
540
+ "fitBayesianLogistic",
541
+ "fitIsotonic",
542
+ "fitPlattScaling",
543
+ "gammaPoissonPosterior",
544
+ "gammaQuantile",
545
+ "garwoodPoissonInterval",
546
+ "goelOkumotoMLE",
547
+ "inverseRegularizedIncompleteBeta",
548
+ "kaplanMeier",
549
+ "ledoitWolfCovariance",
550
+ "lincolnPetersenEstimate",
551
+ "ndcgAtK",
552
+ "normalDraw",
553
+ "pairedBootstrapCi",
554
+ "popt",
555
+ "prAuc",
556
+ "psi",
557
+ "regularizedIncompleteBeta",
558
+ "regularizedIncompleteGamma",
559
+ "shannonEntropy",
560
+ "signTestSprt",
561
+ "thompsonRank",
562
+ "thompsonSample",
563
+ "wilcoxonSignedRank"
564
+ ],
530
565
  "./telemetry": [
531
566
  "ANTHROPIC_PRICE_BOOK",
532
567
  "ConsoleSpanExporter",
@@ -592,6 +627,8 @@
592
627
  "HISTORY_WINDOW",
593
628
  "MAX_RECALLED_MAPS",
594
629
  "MIN_CONSOLIDATED_FILES",
630
+ "NARRATION_OVERLAP",
631
+ "PROGRESS_NOTE",
595
632
  "TRANSCRIPT_SUMMARY_INPUT_TOKENS",
596
633
  "TRANSCRIPT_SUMMARY_MAX_TOKENS",
597
634
  "TRANSCRIPT_SUMMARY_PROMPT",
@@ -609,6 +646,9 @@
609
646
  "consolidationMarkerOf",
610
647
  "consolidationMetadata",
611
648
  "foldKeepFromId",
649
+ "foldRepeatedNarration",
650
+ "foldSupersededReads",
651
+ "foldWorkingTranscript",
612
652
  "isConsolidationMarker",
613
653
  "lastConsolidationIndex",
614
654
  "mergeConsolidated",
@@ -618,6 +658,7 @@
618
658
  "stillInWorkingContext",
619
659
  "summarizeTranscript",
620
660
  "summaryChunks",
661
+ "supersededReadMarker",
621
662
  "transcriptTokens",
622
663
  "windowed",
623
664
  "withoutConsolidatedFiles"
@@ -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
+ }