@seanhogg/builderforce-memory 2026.10.73 → 2026.10.75

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.
@@ -40,7 +40,7 @@ export {
40
40
  signTestSprt,
41
41
  wilcoxonSignedRank,
42
42
  } from "./tests.js";
43
- export type { SprtResult, WilcoxonResult } from "./tests.js";
43
+ export type { PairedStatistic, SprtResult, WilcoxonResult } from "./tests.js";
44
44
 
45
45
  export { bayesianOnlineChangePoint, cusum } from "./timeSeries.js";
46
46
  export type { ChangePointResult, CusumResult } from "./timeSeries.js";
@@ -50,6 +50,9 @@ export type { CovarianceResult } from "./multivariate.js";
50
50
 
51
51
  export { entropyOfCounts, shannonEntropy } from "./information.js";
52
52
 
53
+ export { meanAndSd } from "./moments.js";
54
+ export type { MeanAndSd } from "./moments.js";
55
+
53
56
  export {
54
57
  chapmanEstimate,
55
58
  gammaPoissonPosterior,
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The PRD 41 D13 mean / sample sd primitive (`meanAndSd`): the one mean and standard
3
+ * deviation for predicted measures (Builderforce run-delta's naturalness model).
4
+ */
5
+
6
+ import { describe, expect, it } from "@jest/globals";
7
+ import { meanAndSd } from "./index.js";
8
+
9
+ describe("meanAndSd", () => {
10
+ it("gives the textbook mean and sample sd", () => {
11
+ // 2,4,4,4,5,5,7,9: mean 5, Σ(x−5)² = 32, sample variance 32/7.
12
+ const r = meanAndSd([2, 4, 4, 4, 5, 5, 7, 9]);
13
+ expect(r.n).toBe(8);
14
+ expect(r.nonFinite).toBe(0);
15
+ expect(r.mean).toBe(5);
16
+ expect(r.sd).toBeCloseTo(Math.sqrt(32 / 7), 14);
17
+ const s = meanAndSd([1, 2, 3, 4]);
18
+ expect(s.mean).toBe(2.5);
19
+ expect(s.sd).toBeCloseTo(Math.sqrt(5 / 3), 14);
20
+ });
21
+
22
+ it("survives catastrophic cancellation (large common offset)", () => {
23
+ const r = meanAndSd([1e9 + 4, 1e9 + 7, 1e9 + 13, 1e9 + 16]);
24
+ expect(r.n).toBe(4);
25
+ expect(r.mean).toBe(1e9 + 10);
26
+ expect(r.sd * r.sd).toBeCloseTo(30, 9);
27
+ });
28
+
29
+ it("n = 0: mean NaN, sd 0", () => {
30
+ expect(meanAndSd([])).toEqual({ n: 0, mean: Number.NaN, sd: 0, nonFinite: 0 });
31
+ });
32
+
33
+ it("n = 1: mean is the value, sd 0", () => {
34
+ expect(meanAndSd([3.25])).toEqual({ n: 1, mean: 3.25, sd: 0, nonFinite: 0 });
35
+ });
36
+
37
+ it("all-equal input has sd exactly 0", () => {
38
+ const r = meanAndSd([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]);
39
+ expect(r.n).toBe(7);
40
+ expect(r.mean).toBeCloseTo(0.1, 15);
41
+ expect(r.sd).toBe(0);
42
+ });
43
+
44
+ it("skips NaN and ±Infinity, counting them in nonFinite", () => {
45
+ const r = meanAndSd([1, Number.NaN, 2, Number.POSITIVE_INFINITY, 3, Number.NEGATIVE_INFINITY, 4]);
46
+ expect(r.n).toBe(4);
47
+ expect(r.nonFinite).toBe(3);
48
+ expect(r.mean).toBe(2.5);
49
+ expect(r.sd).toBeCloseTo(Math.sqrt(5 / 3), 14);
50
+ expect(meanAndSd([Number.NaN, Number.NaN])).toEqual({ n: 0, mean: Number.NaN, sd: 0, nonFinite: 2 });
51
+ });
52
+
53
+ it("is deterministic and does not mutate its input", () => {
54
+ const input = Object.freeze([5, 1, 9, 3, 7]);
55
+ expect(meanAndSd(input)).toEqual(meanAndSd(input));
56
+ expect(input).toEqual([5, 1, 9, 3, 7]);
57
+ });
58
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Sample moments for the stats module (PRD 41 Part D / D13): the ONE mean and
3
+ * standard deviation for predicted measures, so callers stop hand-rolling them.
4
+ */
5
+
6
+ /** Result of {@link meanAndSd}. */
7
+ export interface MeanAndSd {
8
+ /** Number of finite values actually used. */
9
+ n: number;
10
+ /** Arithmetic mean of the finite values; NaN when `n` is 0. */
11
+ mean: number;
12
+ /** Sample standard deviation (n − 1 denominator); 0 when `n` < 2. */
13
+ sd: number;
14
+ /**
15
+ * Values that were not finite (NaN or ±Infinity) and were skipped, the same
16
+ * convention as `WilcoxonResult.nonFinite`.
17
+ */
18
+ nonFinite: number;
19
+ }
20
+
21
+ /**
22
+ * Mean and SAMPLE standard deviation by Welford's online algorithm, which stays
23
+ * accurate where the naive Σx² − (Σx)²/n form cancels catastrophically (values
24
+ * with a large common offset).
25
+ *
26
+ * - Non-finite values (NaN, ±Infinity) are skipped and counted in `nonFinite`;
27
+ * `n` is the count of values used.
28
+ * - `n` = 0: `mean` is NaN and `sd` is 0. One result shape is kept rather than the
29
+ * estimators' `InsufficientData` union, so callers branch on `n`.
30
+ * - `n` = 1: `mean` is the value and `sd` is 0 (a sample sd needs two values).
31
+ * - A z-score consumer must guard `n >= 2 && sd > 0`: sd is 0 (not NaN) for one
32
+ * value or all-equal data, so an unguarded division yields ±Infinity.
33
+ *
34
+ * Pure and deterministic: one pass in input order, no allocation beyond the result.
35
+ */
36
+ export function meanAndSd(values: readonly number[]): MeanAndSd {
37
+ let n = 0;
38
+ let nonFinite = 0;
39
+ let mean = 0;
40
+ let m2 = 0;
41
+ for (const x of values) {
42
+ if (!Number.isFinite(x)) {
43
+ nonFinite++;
44
+ continue;
45
+ }
46
+ n++;
47
+ const delta = x - mean;
48
+ mean += delta / n;
49
+ m2 += delta * (x - mean);
50
+ }
51
+ if (n === 0) return { n: 0, mean: Number.NaN, sd: 0, nonFinite };
52
+ const sd = n < 2 ? 0 : Math.sqrt(Math.max(0, m2) / (n - 1));
53
+ return { n, mean, sd, nonFinite };
54
+ }
@@ -1,120 +1,294 @@
1
1
  /**
2
2
  * Statistical tests for the stats module (PRD 41 Part D / D13): Wilcoxon signed-rank
3
- * with the paired Hodges–Lehmann estimator, a seeded paired bootstrap CI, and the
4
- * sign-test SPRT. All deterministic under their seeds.
3
+ * (exact per n, normal approximation for large n) with the paired Hodges–Lehmann
4
+ * estimator, a seeded paired bootstrap CI (mean or Hodges–Lehmann), and the sign-test
5
+ * SPRT. All deterministic under their seeds.
5
6
  */
6
7
 
8
+ import { regularizedUpperIncompleteGamma } from "./distributions.js";
7
9
  import { createRng, type Rng } from "./prng.js";
8
10
 
9
- const WILCOXON_P: number[] = (() => {
10
- // Exact null distribution of W+ for n <= 60 via DP over subset sums.
11
- const n = 60;
12
- const total = (n * (n + 1)) / 2;
13
- const dp: number[] = new Array(total + 1).fill(0);
11
+ // Bound once at module scope for the hot loops: a bare `Math.x` is a global lookup on every call, which inside a vm
12
+ // context (the jest runner) costs ~1 µs each (the same reason as distributions.ts).
13
+ const { floor, max, min } = Math;
14
+
15
+ /** Up to this many nonzero differences the p-value is EXACT; above it, the normal approximation. */
16
+ export const WILCOXON_EXACT_MAX_N = 50;
17
+
18
+ /**
19
+ * Upper standard-normal tail P(Z ≥ z) for z ≥ 0: ½·erfc(z/√2) = ½·Q(½, z²/2), with Q taken
20
+ * directly (not 1 − P) so a far tail stays a tiny positive number instead of underflowing to 0.
21
+ */
22
+ function normalUpperTail(z: number): number {
23
+ if (z <= 0) return 0.5;
24
+ return 0.5 * regularizedUpperIncompleteGamma(0.5, (z * z) / 2);
25
+ }
26
+
27
+ /** The paired differences `after − before` that are finite, and how many were not. */
28
+ function finiteDifferences(before: readonly number[], after: readonly number[]): { diffs: number[]; nonFinite: number } {
29
+ const diffs: number[] = [];
30
+ let nonFinite = 0;
31
+ const n = Math.min(before.length, after.length);
32
+ for (let i = 0; i < n; i++) {
33
+ const d = after[i]! - before[i]!;
34
+ if (Number.isFinite(d)) diffs.push(d);
35
+ else nonFinite++;
36
+ }
37
+ return { diffs, nonFinite };
38
+ }
39
+
40
+ /**
41
+ * Exact two-sided p-value: the permutation distribution of W+ given THESE ranks (mid-ranks
42
+ * for ties), each sign ± with probability ½. Ranks are doubled so mid-ranks are integers,
43
+ * and the distribution is built by DP over subset sums for this n — never a table built for
44
+ * another n. Probabilities (halved at each step) rather than counts, so no overflow.
45
+ */
46
+ export function exactSignedRankPValue(doubledRanks: readonly number[], doubledWPlus: number): number {
47
+ const total = doubledRanks.reduce((a, b) => a + b, 0);
48
+ let dp = new Float64Array(total + 1);
14
49
  dp[0] = 1;
15
- for (let rank = 1; rank <= n; rank++) {
16
- for (let s = total; s >= rank; s--) dp[s] = (dp[s] ?? 0) + (dp[s - rank] ?? 0);
50
+ for (const r of doubledRanks) {
51
+ const next = new Float64Array(total + 1);
52
+ for (let s = 0; s <= total; s++) {
53
+ const p = dp[s]!;
54
+ if (p === 0) continue;
55
+ next[s] = next[s]! + p / 2;
56
+ next[s + r] = next[s + r]! + p / 2;
57
+ }
58
+ dp = next;
17
59
  }
18
- const cum: number[] = new Array(total + 1).fill(0);
19
- let running = 0;
60
+ let lower = 0; // P(W+ ≤ observed)
61
+ let upper = 0; // P(W+ ≥ observed)
20
62
  for (let s = 0; s <= total; s++) {
21
- running += dp[s]!;
22
- cum[s] = running / 2 ** n;
63
+ if (s <= doubledWPlus) lower += dp[s]!;
64
+ if (s >= doubledWPlus) upper += dp[s]!;
65
+ }
66
+ return Math.min(1, 2 * Math.min(lower, upper));
67
+ }
68
+
69
+ /**
70
+ * Normal approximation for large n: mean n(n+1)/4, variance n(n+1)(2n+1)/24 reduced by
71
+ * Σ(t³ − t)/48 over tie groups, continuity correction ½, two-sided normal tail.
72
+ */
73
+ export function normalSignedRankPValue(n: number, wPlus: number, tieGroups: readonly number[]): number {
74
+ const mean = (n * (n + 1)) / 4;
75
+ const tieCorrection = tieGroups.reduce((acc, t) => acc + (t * t * t - t), 0) / 48;
76
+ const variance = (n * (n + 1) * (2 * n + 1)) / 24 - tieCorrection;
77
+ if (!(variance > 0)) return 1;
78
+ const z = Math.max(0, Math.abs(wPlus - mean) - 0.5) / Math.sqrt(variance);
79
+ return Math.min(1, 2 * normalUpperTail(z));
80
+ }
81
+
82
+ /** Walsh averages (sᵢ + sⱼ)/2, i ≤ j, of an ASCENDING array, that are ≤ x: one O(n) two-pointer sweep. */
83
+ function walshCountAtMost(s: readonly number[], x: number): number {
84
+ const n = s.length;
85
+ let count = 0;
86
+ let j = n - 1;
87
+ for (let i = 0; i < n; i++) {
88
+ while (j >= i && (s[i]! + s[j]!) / 2 > x) j--;
89
+ if (j < i) break;
90
+ count += j - i + 1;
91
+ }
92
+ return count;
93
+ }
94
+
95
+ /** Bisection steps per round before a stuck range (a cluster of equal averages) is stepped past. */
96
+ const WALSH_BISECTION_MAX_STEPS = 128;
97
+
98
+ /** The smallest Walsh average of an ASCENDING array strictly above `x` (Infinity if none): O(n). */
99
+ function walshNextAbove(s: readonly number[], x: number): number {
100
+ const n = s.length;
101
+ let best = Infinity;
102
+ let j = n - 1; // last j with avg ≤ x for the current i
103
+ for (let i = 0; i < n; i++) {
104
+ while (j >= i && (s[i]! + s[j]!) / 2 > x) j--;
105
+ const first = max(i, j + 1);
106
+ if (first < n) best = min(best, (s[i]! + s[first]!) / 2);
107
+ }
108
+ return best;
109
+ }
110
+
111
+ /** The largest Walsh average of an ASCENDING array at most `x` (−Infinity if none): O(n). */
112
+ function walshLargestAtMost(s: readonly number[], x: number): number {
113
+ const n = s.length;
114
+ let best = -Infinity;
115
+ let j = n - 1;
116
+ for (let i = 0; i < n; i++) {
117
+ while (j >= i && (s[i]! + s[j]!) / 2 > x) j--;
118
+ if (j < i) break;
119
+ const v = (s[i]! + s[j]!) / 2;
120
+ if (v > best) best = v;
121
+ }
122
+ return best;
123
+ }
124
+
125
+ /**
126
+ * The kLow-th and kHigh-th smallest (0-based; kHigh ∈ {kLow, kLow + 1}) Walsh averages of
127
+ * an ASCENDING array, EXACTLY, without materialising the n(n+1)/2 averages — an exact
128
+ * value-space selection (same result as Monahan's algorithm), O(n log n) for the sort plus
129
+ * O(n) per bisection step:
130
+ * - bisect on the VALUE with an O(n) two-pointer count until at most n averages lie in
131
+ * (lo, hi] around both ranks, then enumerate just those and select;
132
+ * - when a bisection point falls between the two ranks, the kLow-th is the largest
133
+ * average ≤ it and the kHigh-th the smallest above it;
134
+ * - a range that will not shrink (a cluster of EQUAL averages) is stepped past one
135
+ * distinct value at a time.
136
+ * Each candidate is the same expression (sᵢ + sⱼ)/2 as a full sort, so the doubles match it.
137
+ */
138
+ function kthWalshAverages(s: readonly number[], kLow: number, kHigh: number): [number, number] {
139
+ const n = s.length;
140
+ let lo = s[0]!; // the smallest average
141
+ let loCount = walshCountAtMost(s, lo);
142
+ if (loCount > kHigh) return [lo, lo];
143
+ if (loCount > kLow) return [lo, walshNextAbove(s, lo)]; // kHigh = kLow + 1 = loCount
144
+ let hi = s[n - 1]!; // the largest average (its count, m, exceeds every rank)
145
+ let hiCount = walshCountAtMost(s, hi);
146
+ // Invariant: loCount ≤ kLow and hiCount > kHigh.
147
+ for (;;) {
148
+ for (let step = 0; step < WALSH_BISECTION_MAX_STEPS && hiCount - loCount > n; step++) {
149
+ const mid = lo + (hi - lo) / 2;
150
+ if (mid <= lo || mid >= hi) break;
151
+ const c = walshCountAtMost(s, mid);
152
+ if (c > kHigh) { hi = mid; hiCount = c; }
153
+ else if (c <= kLow) { lo = mid; loCount = c; }
154
+ else return [walshLargestAtMost(s, mid), walshNextAbove(s, mid)]; // c = kHigh = kLow + 1
155
+ }
156
+ if (hiCount - loCount <= n) break;
157
+ // Stuck on a cluster of equal averages: everything in (lo, next] equals `next`.
158
+ const next = walshNextAbove(s, lo);
159
+ const c = walshCountAtMost(s, next);
160
+ if (c > kHigh) return [next, next];
161
+ if (c > kLow) return [next, walshNextAbove(s, next)];
162
+ lo = next;
163
+ loCount = c;
23
164
  }
24
- return cum;
25
- })();
26
-
27
- function wilcoxonPValue(wPlus: number, n: number): number {
28
- if (n > 60) {
29
- // Normal approximation with continuity correction.
30
- const mean = (n * (n + 1)) / 4;
31
- const sd = Math.sqrt((n * (n + 1) * (2 * n + 1)) / 24);
32
- const z = (wPlus - mean + 0.5) / sd;
33
- return Math.min(1, Math.exp(-0.5 * z * z) * 0.5 * 2); // two-sided via |z|
165
+ // Both ranks lie in (lo, hi]: enumerate those averages (at most n) and select.
166
+ const candidates: number[] = [];
167
+ let jLo = n - 1; // last j with avg ≤ lo (for the current i)
168
+ let jHi = n - 1; // last j with avg ≤ hi
169
+ for (let i = 0; i < n; i++) {
170
+ while (jHi >= i && (s[i]! + s[jHi]!) / 2 > hi) jHi--;
171
+ while (jLo >= i && (s[i]! + s[jLo]!) / 2 > lo) jLo--;
172
+ if (jHi < i) break;
173
+ for (let j = max(i, jLo + 1); j <= jHi; j++) candidates.push((s[i]! + s[j]!) / 2);
34
174
  }
35
- const total = (n * (n + 1)) / 2;
36
- const lo = Math.max(0, Math.floor(wPlus));
37
- const hi = Math.min(total, Math.ceil(wPlus));
38
- const pLo = WILCOXON_P[lo] ?? 0;
39
- const pHi = 1 - (WILCOXON_P[hi - 1] ?? 0);
40
- return Math.min(1, 2 * Math.min(pLo, pHi));
175
+ candidates.sort((a, b) => a - b);
176
+ return [candidates[kLow - loCount] ?? hi, candidates[kHigh - loCount] ?? hi];
177
+ }
178
+
179
+ /**
180
+ * Median of the Walsh averages (dᵢ + dⱼ)/2, i ≤ j, over ALL the given differences (zeros
181
+ * included), in O(n log n): one sort, then exact selection of the middle one or two
182
+ * ({@link kthWalshAverages}).
183
+ */
184
+ function hodgesLehmannOf(diffs: readonly number[]): number {
185
+ const n = diffs.length;
186
+ if (n === 0) return 0;
187
+ const s = [...diffs].sort((a, b) => a - b);
188
+ const m = (n * (n + 1)) / 2;
189
+ if (m % 2 === 1) return kthWalshAverages(s, (m - 1) / 2, (m - 1) / 2)[0];
190
+ const [a, b] = kthWalshAverages(s, m / 2 - 1, m / 2);
191
+ return (a + b) / 2;
41
192
  }
42
193
 
43
194
  export interface WilcoxonResult {
195
+ /** Nonzero differences — the ones the test ranks (zeros are dropped: Wilcoxon's rule). */
44
196
  n: number;
197
+ /** Sum of the (mid-)ranks of the positive differences. */
45
198
  wPlus: number;
199
+ /** Two-sided. Exact for n ≤ {@link WILCOXON_EXACT_MAX_N}, normal approximation (continuity + tie corrected) above. */
46
200
  pValue: number;
47
- /** Paired Hodges–Lehmann estimator: median of pairwise averages (after > 0 filter). */
201
+ /**
202
+ * Paired Hodges–Lehmann estimator: median of the Walsh averages of ALL finite paired
203
+ * differences, zeros included (Hollander & Wolfe). R's `wilcox.test(conf.int = TRUE)` drops
204
+ * zeros for its estimate too; this does not, because dropping them biases the estimate away
205
+ * from 0.
206
+ */
48
207
  hodgesLehmann: number;
208
+ /**
209
+ * Pairs whose difference was not a finite number (NaN or ±Infinity, e.g. a missing or
210
+ * failed measurement). They are DROPPED from the test and the estimate, never ranked;
211
+ * a caller that cannot tolerate missing pairs should check this is 0.
212
+ */
213
+ nonFinite: number;
49
214
  }
50
215
 
51
216
  /**
52
- * Wilcoxon signed-rank test on the nonzero paired differences of `before` and
53
- * `after`, plus the paired Hodges–Lehmann location estimator.
217
+ * Wilcoxon signed-rank test of `after − before`, plus the paired Hodges–Lehmann location
218
+ * estimator.
219
+ *
220
+ * - Zeros: Wilcoxon's rule — zero differences are dropped before ranking (`n` counts the
221
+ * rest). They still count toward the Hodges–Lehmann estimate, which would otherwise be
222
+ * biased away from 0.
223
+ * - Ties: tied |differences| share their mid-rank. The exact p-value conditions on those
224
+ * ranks; the normal approximation applies the tie variance correction.
225
+ * - Non-finite differences (NaN, ±Infinity) are dropped and counted in `nonFinite`.
54
226
  */
55
227
  export function wilcoxonSignedRank(before: readonly number[], after: readonly number[]): WilcoxonResult {
56
- const diffs: number[] = [];
57
- const n0 = Math.min(before.length, after.length);
58
- for (let i = 0; i < n0; i++) {
59
- const d = after[i]! - before[i]!;
60
- if (d !== 0) diffs.push(d);
61
- }
228
+ const { diffs: all, nonFinite } = finiteDifferences(before, after);
229
+ const hodgesLehmann = hodgesLehmannOf(all);
230
+ const diffs = all.filter((d) => d !== 0);
62
231
  const n = diffs.length;
63
- if (n === 0) return { n: 0, wPlus: 0, pValue: 1, hodgesLehmann: 0 };
232
+ if (n === 0) return { n: 0, wPlus: 0, pValue: 1, hodgesLehmann, nonFinite };
64
233
  const abs = diffs.map((d) => Math.abs(d));
65
234
  const order = abs.map((_, i) => i).sort((p, q) => abs[p]! - abs[q]!);
66
235
  const ranks = new Array<number>(n).fill(0);
236
+ const tieGroups: number[] = [];
67
237
  let i = 0;
68
238
  while (i < n) {
69
239
  let j = i;
70
240
  while (j + 1 < n && abs[order[j + 1]!] === abs[order[i]!]) j++;
71
241
  const avg = (i + j) / 2 + 1;
72
242
  for (let k = i; k <= j; k++) ranks[order[k]!] = avg;
243
+ if (j > i) tieGroups.push(j - i + 1);
73
244
  i = j + 1;
74
245
  }
75
246
  let wPlus = 0;
76
247
  for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!;
77
- // Hodges–Lehmann: median of Walsh averages over positive-magnitude pairs.
78
- const walsh: number[] = [];
79
- for (let p = 0; p < n; p++) {
80
- for (let q = p; q < n; q++) walsh.push((diffs[p]! + diffs[q]!) / 2);
81
- }
82
- walsh.sort((a, b) => a - b);
83
- const hl =
84
- walsh.length % 2 === 1
85
- ? walsh[(walsh.length - 1) / 2]!
86
- : (walsh[walsh.length / 2 - 1]! + walsh[walsh.length / 2]!) / 2;
87
- return { n, wPlus, pValue: wilcoxonPValue(wPlus, n), hodgesLehmann: hl };
248
+ const pValue =
249
+ n <= WILCOXON_EXACT_MAX_N
250
+ ? exactSignedRankPValue(ranks.map((r) => Math.round(2 * r)), Math.round(2 * wPlus))
251
+ : normalSignedRankPValue(n, wPlus, tieGroups);
252
+ return { n, wPlus, pValue, hodgesLehmann, nonFinite };
88
253
  }
89
254
 
255
+ /** The statistic a paired bootstrap resamples. */
256
+ export type PairedStatistic = "mean" | "hodges-lehmann";
257
+
90
258
  /**
91
- * Paired bootstrap confidence interval for the mean difference `after − before`,
92
- * resampling PAIRS so the pairing is preserved. Deterministic under `seed`.
259
+ * Paired bootstrap percentile confidence interval for a location statistic of
260
+ * `after − before` — the mean difference (default) or the paired Hodges–Lehmann estimate
261
+ * (PRD 41 C6.2) — resampling PAIRS so the pairing is preserved. Deterministic: seeded
262
+ * (`seed`, default 1) with a fixed resample count (`iterations`, default 2000). The
263
+ * Hodges–Lehmann statistic costs O(n log n) per resample (exact selection, no n² list).
264
+ * Pairs with a non-finite difference are dropped, as in {@link wilcoxonSignedRank}.
93
265
  */
94
266
  export function pairedBootstrapCi(
95
267
  before: readonly number[],
96
268
  after: readonly number[],
97
- options: { iterations?: number; confidence?: number; seed?: number } = {},
269
+ options: { iterations?: number; confidence?: number; seed?: number; statistic?: PairedStatistic } = {},
98
270
  ): { low: number; high: number; estimate: number } {
99
271
  const iterations = options.iterations ?? 2000;
100
272
  const confidence = options.confidence ?? 0.95;
273
+ const stat = options.statistic === "hodges-lehmann"
274
+ ? hodgesLehmannOf
275
+ : (d: readonly number[]) => d.reduce((a, b) => a + b, 0) / Math.max(d.length, 1);
101
276
  const rng: Rng = createRng(options.seed ?? 1);
102
- const n = Math.min(before.length, after.length);
103
- const diffs: number[] = [];
104
- for (let i = 0; i < n; i++) diffs.push(after[i]! - before[i]!);
105
- const estimate = diffs.reduce((a, b) => a + b, 0) / Math.max(diffs.length, 1);
277
+ const { diffs } = finiteDifferences(before, after);
278
+ const n = diffs.length;
106
279
  if (n === 0) return { low: 0, high: 0, estimate: 0 };
107
- const means: number[] = [];
280
+ const estimate = stat(diffs);
281
+ const values: number[] = [];
282
+ const sample = new Array<number>(n);
108
283
  for (let b = 0; b < iterations; b++) {
109
- let s = 0;
110
- for (let i = 0; i < n; i++) s += diffs[Math.floor(rng() * n)]!;
111
- means.push(s / n);
284
+ for (let i = 0; i < n; i++) sample[i] = diffs[floor(rng() * n)]!;
285
+ values.push(stat(sample));
112
286
  }
113
- means.sort((a, b) => a - b);
287
+ values.sort((a, b) => a - b);
114
288
  const alpha = 1 - confidence;
115
289
  return {
116
- low: means[Math.floor((alpha / 2) * iterations)] ?? estimate,
117
- high: means[Math.floor((1 - alpha / 2) * iterations) - 1] ?? estimate,
290
+ low: values[Math.floor((alpha / 2) * iterations)] ?? estimate,
291
+ high: values[Math.floor((1 - alpha / 2) * iterations) - 1] ?? estimate,
118
292
  estimate,
119
293
  };
120
294
  }