@numero-uno-jpn/rstats 1.4.0 → 1.5.0

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 (48) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.ja.md +7 -5
  3. package/README.md +7 -5
  4. package/dist/chunks/{chunk-SVS54D6Z.js → chunk-2IYY74LX.js} +2 -2
  5. package/dist/chunks/{chunk-GBSMRVUY.js → chunk-2MYUAEYE.js} +2 -2
  6. package/dist/chunks/{chunk-YBOSCQF2.js → chunk-3BEE6BHN.js} +1 -1
  7. package/dist/chunks/{chunk-F6Z3GLWA.js → chunk-73QCE2CI.js} +2 -2
  8. package/dist/chunks/{chunk-GLGOV3A5.js → chunk-AIXJAVDS.js} +2 -2
  9. package/dist/chunks/{chunk-GIER5WMB.js → chunk-BJOZZ5J6.js} +2 -2
  10. package/dist/chunks/{chunk-GEF2YRBV.js → chunk-CX4XK7WC.js} +2 -2
  11. package/dist/chunks/{chunk-PZ66PUWC.js → chunk-DYCWYHYV.js} +1 -1
  12. package/dist/chunks/{chunk-H72MW7YP.js → chunk-E5M5RAVB.js} +2 -2
  13. package/dist/chunks/{chunk-UMMCVF53.js → chunk-F2MURX2Y.js} +2 -2
  14. package/dist/chunks/{chunk-27VFB3SA.js → chunk-F7SQG6BV.js} +2 -2
  15. package/dist/chunks/{chunk-S2YCFUCA.js → chunk-FCF6FBJP.js} +2 -2
  16. package/dist/chunks/{chunk-6FZAJQ4H.js → chunk-FMLFYM7N.js} +2 -2
  17. package/dist/chunks/{chunk-WWJGCBWH.js → chunk-GDMNF4P3.js} +1 -1
  18. package/dist/chunks/{chunk-ZRFZ5UIB.js → chunk-JBJTXMRJ.js} +2 -2
  19. package/dist/chunks/{chunk-56GFP4UU.js → chunk-L7PDJNJ3.js} +2 -2
  20. package/dist/chunks/{chunk-BQJFFGYP.js → chunk-LVB22NKV.js} +2 -2
  21. package/dist/chunks/{chunk-HWB7XRX2.js → chunk-MJV5G7FG.js} +2 -2
  22. package/dist/chunks/{chunk-5SW3L6J3.js → chunk-MXOGMN4P.js} +2 -2
  23. package/dist/chunks/{chunk-RY7CCWVU.js → chunk-MYRCEQ2R.js} +1 -1
  24. package/dist/chunks/{chunk-ZQSOMEIM.js → chunk-Q32WODL4.js} +2 -2
  25. package/dist/chunks/{chunk-UNP4HBPP.js → chunk-RZBX6VYO.js} +2 -2
  26. package/dist/chunks/{chunk-J72MLFUG.js → chunk-TP4PRPVQ.js} +2 -2
  27. package/dist/chunks/{chunk-RUZATICF.js → chunk-UJM7AJII.js} +1 -1
  28. package/dist/chunks/{chunk-X7K6EF7S.js → chunk-VAWD57ZB.js} +2 -2
  29. package/dist/chunks/{chunk-TEHMTQNB.js → chunk-WBEYJ5W5.js} +2 -2
  30. package/dist/chunks/{chunk-V2KVTAVV.js → chunk-YK2EJU6T.js} +2 -2
  31. package/dist/descriptive.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +2 -0
  34. package/dist/entries/tests.js +2 -0
  35. package/dist/htest/sampleSize.d.ts +290 -0
  36. package/dist/htest/sampleSize.js +625 -0
  37. package/dist/linalg.js +2 -2
  38. package/dist/mixed.js +2 -2
  39. package/dist/models/competingRisks.d.ts +1 -1
  40. package/dist/models/competingRisks.js +42 -30
  41. package/dist/models/metaAnalysis.d.ts +207 -0
  42. package/dist/models/metaAnalysis.js +696 -0
  43. package/dist/numerics.js +2 -2
  44. package/dist/rstats.js +19 -16
  45. package/dist/special.js +2 -2
  46. package/dist/tests.js +16 -13
  47. package/llms.txt +5 -2
  48. package/package.json +1 -1
@@ -0,0 +1,625 @@
1
+ // Sample-size and power calculations: epiR parallel designs, exact McNemar power, Freedman/Schoenfeld and Simon designs.
2
+ // Written for rStats.js from the published formulae and public package documentation (no R or GPL package source ported).
3
+ import { pnorm, qnorm } from "../distributions/normal.js";
4
+ import { reported } from "../internal/warnings.js";
5
+ import { checkExactlyOne, isUnknown, matchChoice } from "./power.js";
6
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
7
+ import { checkOptions } from "../internal/checkOptions.js";
8
+ const EPI_SSEQUB_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
9
+ const EPI_SSEQUC_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
10
+ const EPI_SSNINFB_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
11
+ const EPI_SSNINFC_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
12
+ const EPI_SSSUPB_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
13
+ const EPI_SSSUPC_KEYS = ["n", "power", "r", "type", "nfractional", "alpha", "sidedTest"];
14
+ const POWER_PAIRED2X2_KEYS = ["sigLevel", "alternative", "strict", "nullOddsRatio", "errbound", "tsmethod"];
15
+ const SSIZE_CT_KEYS = ["alpha"];
16
+ const POWER_CT_KEYS = ["alpha"];
17
+ const SSIZE_EPI_KEYS = ["alpha"];
18
+ const POWER_EPI_KEYS = ["alpha"];
19
+ const NUM_DEPI_KEYS = ["alpha"];
20
+ const PH2SIMON_KEYS = ["nmax"];
21
+ // Generated by `node scripts/option-keys.mjs --write` (end)
22
+ const DEFAULT_ALPHA = 0.05;
23
+ const z = (p) => qnorm(p);
24
+ const phi = (x) => pnorm(x);
25
+ const finite = (x) => Number.isFinite(x);
26
+ const prob = (x) => finite(x) && x >= 0 && x <= 1;
27
+ const positive = (x) => finite(x) && x > 0;
28
+ function checkNumber(x, name, test, message) {
29
+ if (typeof x !== "number")
30
+ throw new TypeError(`'${name}' must be numeric`);
31
+ if (!test(x))
32
+ throw new RangeError(message);
33
+ }
34
+ function checkAlpha(alpha) {
35
+ checkNumber(alpha, "alpha", prob, "'alpha' must be a probability in [0, 1]");
36
+ }
37
+ function splitN(n, r) {
38
+ return [n * r / (1 + r), n / (1 + r)];
39
+ }
40
+ function epi(kind, measure, treat, control, sigma, delta, options = {}) {
41
+ const { n, power } = options;
42
+ const r = options.r ?? 1;
43
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
44
+ const nfractional = options.nfractional ?? false;
45
+ const type = kind === "equivalence" ? matchChoice(options.type, ["equivalence", "equality"]) : "equivalence";
46
+ const sides = options.sidedTest ?? 1;
47
+ if (kind === "equivalence" && type !== "equivalence" && type !== "equality") {
48
+ throw new RangeError("'type' should be one of “equivalence”, “equality”");
49
+ }
50
+ checkNumber(treat, "treat", finite, "'treat' must be finite");
51
+ checkNumber(control, "control", finite, "'control' must be finite");
52
+ if (measure === "binary") {
53
+ checkNumber(treat, "treat", prob, "'treat' must be a probability in [0, 1]");
54
+ checkNumber(control, "control", prob, "'control' must be a probability in [0, 1]");
55
+ }
56
+ else {
57
+ checkNumber(sigma, "sigma", positive, "'sigma' must be positive and finite");
58
+ }
59
+ checkNumber(r, "r", positive, "'r' must be positive and finite");
60
+ checkAlpha(alpha);
61
+ if (kind !== "equivalence" || type !== "equality")
62
+ checkNumber(delta, "delta", (v) => finite(v) && v >= 0, "'delta' must be nonnegative and finite");
63
+ if (kind === "superiority" && sides !== 1 && sides !== 2)
64
+ throw new RangeError("'sidedTest' must be 1 or 2");
65
+ if (typeof nfractional !== "boolean")
66
+ throw new TypeError("'nfractional' must be logical");
67
+ checkExactlyOne([n, power], "exactly one of 'n' and 'power' must be NULL");
68
+ if (!isUnknown(power)) {
69
+ checkNumber(power, "power", (v) => prob(v) && v > 0 && v < 1, "'power' must be strictly between 0 and 1");
70
+ }
71
+ if (n !== null && n !== undefined)
72
+ checkNumber(n, "n", (v) => finite(v) && v > 0, "'n' must be positive and finite");
73
+ const D = treat - control;
74
+ const vt = measure === "binary" ? treat * (1 - treat) : sigma * sigma;
75
+ const vc = measure === "binary" ? control * (1 - control) : sigma * sigma;
76
+ const equality = kind === "equivalence" && type === "equality";
77
+ const margin = equality ? undefined : delta;
78
+ const E = kind === "noninferiority" ? D + margin : kind === "superiority" ? D - margin : equality ? D : margin - Math.abs(D);
79
+ if (kind === "noninferiority" && E <= 0)
80
+ throw new RangeError("Target power is not reachable under the specified hypotheses");
81
+ // Pass the upper-tail probability directly. Forming 1 - tail loses relative precision
82
+ // when alpha is much smaller than machine epsilon near 1.
83
+ const critical = kind === "superiority" ? qnorm(alpha / sides, { lowerTail: false }) :
84
+ equality ? qnorm(alpha / 2, { lowerTail: false }) : qnorm(alpha, { lowerTail: false });
85
+ const targetPower = power ?? 0.8;
86
+ const zPower = equality || kind !== "equivalence"
87
+ ? qnorm(1 - targetPower, { lowerTail: false })
88
+ : qnorm((1 - targetPower) / 2, { lowerTail: false });
89
+ let nTreat;
90
+ let nControl;
91
+ let nTreatUnrounded;
92
+ let nControlUnrounded;
93
+ let actualPower;
94
+ if (isUnknown(n)) {
95
+ if (E === 0) {
96
+ nTreatUnrounded = Infinity;
97
+ nControlUnrounded = Infinity;
98
+ }
99
+ else {
100
+ nControlUnrounded = ((critical + zPower) ** 2 * (vt / r + vc)) / (E * E);
101
+ nTreatUnrounded = r * nControlUnrounded;
102
+ }
103
+ if (nfractional) {
104
+ nTreat = nTreatUnrounded;
105
+ nControl = nControlUnrounded;
106
+ }
107
+ else {
108
+ nControl = Math.ceil(nControlUnrounded);
109
+ // Public epiR outputs show method-specific integer allocation. For
110
+ // continuous equivalence and superiority, round the control arm first
111
+ // and then round r * nControl; the other four methods round each
112
+ // unrounded arm independently. epiR is inconsistent for some ratios
113
+ // (including fractional outputs with nfractional=FALSE); rStats keeps
114
+ // the requested integer-size contract instead of returning fractions.
115
+ const ratioFromRoundedControl = (kind === "equivalence" && measure === "continuous") || kind === "superiority";
116
+ nTreat = ratioFromRoundedControl ? Math.ceil(r * nControl) : Math.ceil(nTreatUnrounded);
117
+ }
118
+ actualPower = power;
119
+ }
120
+ else {
121
+ [nTreatUnrounded, nControlUnrounded] = splitN(n, r);
122
+ nTreat = nfractional ? nTreatUnrounded : Math.ceil(nTreatUnrounded);
123
+ nControl = nfractional ? nControlUnrounded : Math.ceil(nControlUnrounded);
124
+ const se = Math.sqrt(vt / nTreat + vc / nControl);
125
+ if (kind === "equivalence" && !equality) {
126
+ // User-selected TOST probability: the intersection of the two one-sided rejection events.
127
+ actualPower = Math.max(0, phi((delta - D) / se - z(1 - alpha)) + phi((delta + D) / se - z(1 - alpha)) - 1);
128
+ }
129
+ else if (equality) {
130
+ actualPower = phi(Math.abs(D) / se - z(1 - alpha / 2)) + phi(-Math.abs(D) / se - z(1 - alpha / 2));
131
+ }
132
+ else if (kind === "noninferiority") {
133
+ actualPower = phi((D + delta) / se - z(1 - alpha));
134
+ }
135
+ else {
136
+ const e = Math.abs(D - delta) / se;
137
+ actualPower = phi(e - critical) + phi(-e - critical);
138
+ }
139
+ }
140
+ const result = {
141
+ nTotal: nTreat + nControl,
142
+ nTreat,
143
+ nControl,
144
+ nTotalUnrounded: nTreatUnrounded + nControlUnrounded,
145
+ nTreatUnrounded,
146
+ nControlUnrounded,
147
+ power: actualPower,
148
+ ...(margin === undefined ? {} : { delta: margin }),
149
+ warnings: [],
150
+ };
151
+ return result;
152
+ }
153
+ /** Equivalence/equality sample size or power for two proportions. Equivalent to `epiR::epi.ssequb()` in R.
154
+ * @param treat Expected treatment-group proportion.
155
+ * @param control Expected control-group proportion.
156
+ * @param delta Equivalence margin; pass null for equality.
157
+ * @param options Sample-size, power and allocation options.
158
+ * @returns The fractional and requested group sizes, and power. The sample-size formula follows epiR's expression and is not an exact inverse of the TOST power calculation.
159
+ * @example
160
+ * ```ts
161
+ * epiSsequb(0.5, 0.45, 0.1, { n: 120 }).power;
162
+ * ```
163
+ * @category Effect sizes and power
164
+ */
165
+ export function epiSsequb(treat, control, delta, options = {}) {
166
+ checkOptions(options, EPI_SSEQUB_KEYS, "epiSsequb"); // generated: option-keys.mjs
167
+ return reported("epiSsequb", epi("equivalence", "binary", treat, control, undefined, delta ?? undefined, options));
168
+ }
169
+ /** Equivalence/equality sample size or power for two means. Equivalent to `epiR::epi.ssequc()` in R.
170
+ * @param treat Expected treatment-group mean.
171
+ * @param control Expected control-group mean.
172
+ * @param sigma Common standard deviation.
173
+ * @param delta Equivalence margin; pass null for equality.
174
+ * @param options Sample-size, power and allocation options.
175
+ * @returns The fractional and requested group sizes, and power. The sample-size formula follows epiR's expression and is not an exact inverse of the TOST power calculation.
176
+ * @example
177
+ * ```ts
178
+ * epiSsequc(20, 21, 10, 5, { n: 120 }).power;
179
+ * ```
180
+ * @category Effect sizes and power
181
+ */
182
+ export function epiSsequc(treat, control, sigma, delta, options = {}) {
183
+ checkOptions(options, EPI_SSEQUC_KEYS, "epiSsequc"); // generated: option-keys.mjs
184
+ const out = epi("equivalence", "continuous", treat, control, sigma, delta ?? undefined, options);
185
+ return reported("epiSsequc", out);
186
+ }
187
+ /** Non-inferiority sample size or power for two proportions. Equivalent to `epiR::epi.ssninfb()` in R.
188
+ * @param treat Expected treatment-group proportion.
189
+ * @param control Expected control-group proportion.
190
+ * @param delta Non-inferiority margin.
191
+ * @param options Sample-size, power and allocation options.
192
+ * @returns The fractional and requested group sizes, and power.
193
+ * @example
194
+ * ```ts
195
+ * epiSsninfb(0.85, 0.65, 0.1, { n: 120 }).power;
196
+ * ```
197
+ * @category Effect sizes and power
198
+ */
199
+ export function epiSsninfb(treat, control, delta, options = {}) {
200
+ checkOptions(options, EPI_SSNINFB_KEYS, "epiSsninfb"); // generated: option-keys.mjs
201
+ return reported("epiSsninfb", epi("noninferiority", "binary", treat, control, undefined, delta, options));
202
+ }
203
+ /** Non-inferiority sample size or power for two means. Equivalent to `epiR::epi.ssninfc()` in R.
204
+ * @param treat Expected treatment-group mean.
205
+ * @param control Expected control-group mean.
206
+ * @param sigma Common standard deviation.
207
+ * @param delta Non-inferiority margin.
208
+ * @param options Sample-size, power and allocation options.
209
+ * @returns The fractional and requested group sizes, and power.
210
+ * @example
211
+ * ```ts
212
+ * epiSsninfc(0.22, 0.2, 0.1, 0.05, { n: 120 }).power;
213
+ * ```
214
+ * @category Effect sizes and power
215
+ */
216
+ export function epiSsninfc(treat, control, sigma, delta, options = {}) {
217
+ checkOptions(options, EPI_SSNINFC_KEYS, "epiSsninfc"); // generated: option-keys.mjs
218
+ return reported("epiSsninfc", epi("noninferiority", "continuous", treat, control, sigma, delta, options));
219
+ }
220
+ /** Superiority sample size or power for two proportions. Equivalent to `epiR::epi.sssupb()` in R.
221
+ * @param treat Expected treatment-group proportion.
222
+ * @param control Expected control-group proportion.
223
+ * @param delta Superiority margin.
224
+ * @param options Sample-size, power and allocation options.
225
+ * @returns The fractional and requested group sizes, and power.
226
+ * @example
227
+ * ```ts
228
+ * epiSssupb(0.5, 0.3, 0.05, { n: 101, r: 0.5, sidedTest: 1 }).power;
229
+ * ```
230
+ * @category Effect sizes and power
231
+ */
232
+ export function epiSssupb(treat, control, delta, options = {}) {
233
+ checkOptions(options, EPI_SSSUPB_KEYS, "epiSssupb"); // generated: option-keys.mjs
234
+ return reported("epiSssupb", epi("superiority", "binary", treat, control, undefined, delta, options));
235
+ }
236
+ /** Superiority sample size or power for two means. Equivalent to `epiR::epi.sssupc()` in R.
237
+ * @param treat Expected treatment-group mean.
238
+ * @param control Expected control-group mean.
239
+ * @param sigma Common standard deviation.
240
+ * @param delta Superiority margin.
241
+ * @param options Sample-size, power and allocation options.
242
+ * @returns The fractional and requested group sizes, and power.
243
+ * @example
244
+ * ```ts
245
+ * epiSssupc(20, 20, 10, 5, { n: 120, r: 1.5, sidedTest: 1 }).power;
246
+ * ```
247
+ * @category Effect sizes and power
248
+ */
249
+ export function epiSssupc(treat, control, sigma, delta, options = {}) {
250
+ checkOptions(options, EPI_SSSUPC_KEYS, "epiSssupc"); // generated: option-keys.mjs
251
+ return reported("epiSssupc", epi("superiority", "continuous", treat, control, sigma, delta, options));
252
+ }
253
+ function binomialMasses(n, p) {
254
+ const out = new Array(n + 1).fill(0);
255
+ if (p === 0) {
256
+ out[0] = 1;
257
+ return out;
258
+ }
259
+ if (p === 1) {
260
+ out[n] = 1;
261
+ return out;
262
+ }
263
+ // Reflect probabilities above one half. The mode mass is then formed from
264
+ // log(p) and log1p(-p) without subtracting two O(n log n) terms.
265
+ if (p > 0.5)
266
+ return binomialMasses(n, 1 - p).reverse();
267
+ const mode = Math.floor((n + 1) * p);
268
+ out[mode] = Math.exp((n * Math.log1p(-p)) + mode * Math.log(p / (1 - p)) +
269
+ Array.from({ length: mode }, (_, i) => Math.log(n - i) - Math.log(i + 1)).reduce((a, b) => a + b, 0));
270
+ for (let k = mode; k > 0; k--)
271
+ out[k - 1] = out[k] * (k / (n - k + 1)) * ((1 - p) / p);
272
+ for (let k = mode; k < n; k++)
273
+ out[k + 1] = out[k] * ((n - k) / (k + 1)) * (p / (1 - p));
274
+ return out;
275
+ }
276
+ /** Exact power of McNemar's test for paired binary outcomes. Equivalent to `exact2x2::powerPaired2x2()` in R.
277
+ * @param pb Probability of a discordant pair with control 0 and treatment 1.
278
+ * @param pc Probability of a discordant pair with control 1 and treatment 0.
279
+ * @param npairs Number of pairs.
280
+ * @param options Test options. `errbound=0` evaluates the full sum; a positive value may omit extreme discordant-pair-count tails with total omitted probability no greater than `errbound`.
281
+ * @returns The power and test settings.
282
+ * @example
283
+ * ```ts
284
+ * powerPaired2x2(0.5, 0.3, 40).power;
285
+ * ```
286
+ * @category Effect sizes and power
287
+ */
288
+ export function powerPaired2x2(pb, pc, npairs, options = {}) {
289
+ checkOptions(options, POWER_PAIRED2X2_KEYS, "powerPaired2x2"); // generated: option-keys.mjs
290
+ const sigLevel = options.sigLevel ?? DEFAULT_ALPHA;
291
+ const alternative = matchChoice(options.alternative, ["two.sided", "one.sided"]);
292
+ const strict = options.strict ?? false;
293
+ const nullOddsRatio = options.nullOddsRatio ?? 1;
294
+ const errbound = options.errbound ?? 1e-6;
295
+ const tsmethod = matchChoice(options.tsmethod, ["central", "minlike", "blaker"]);
296
+ checkNumber(pb, "pb", prob, "'pb' must be in [0, 1]");
297
+ checkNumber(pc, "pc", prob, "'pc' must be in [0, 1]");
298
+ checkNumber(npairs, "npairs", (v) => Number.isSafeInteger(v) && v >= 0 && v <= 100000, "'npairs' must be a nonnegative safe integer");
299
+ checkAlpha(sigLevel);
300
+ checkNumber(nullOddsRatio, "nullOddsRatio", positive, "'nullOddsRatio' must be positive and finite");
301
+ checkNumber(errbound, "errbound", (v) => finite(v) && v >= 0, "'errbound' must be nonnegative and finite");
302
+ if (pb + pc > 1)
303
+ throw new RangeError("probabilities must be finite, non-negative and not all 0");
304
+ if (alternative !== "two.sided" && alternative !== "one.sided")
305
+ throw new RangeError("'alternative' should be one of “two.sided”, “one.sided”");
306
+ if (!["central", "minlike", "blaker"].includes(tsmethod))
307
+ throw new RangeError("'tsmethod' should be one of “central”, “minlike”, “blaker”");
308
+ const q = pb + pc;
309
+ const pAlt = q === 0 ? 0.5 : pb / q;
310
+ const pNull = nullOddsRatio / (1 + nullOddsRatio);
311
+ const direction = pb >= pc ? 1 : -1;
312
+ const useBoth = alternative === "two.sided" && strict && tsmethod !== "blaker";
313
+ const useOne = alternative === "one.sided";
314
+ const massM = binomialMasses(npairs, q);
315
+ let firstM = 0, lastM = npairs;
316
+ // Treat errbound as a total omitted-probability budget for the two tails of M.
317
+ if (errbound > 0) {
318
+ let tail = 0;
319
+ while (firstM <= npairs && (tail += massM[firstM]) <= errbound / 2)
320
+ firstM++;
321
+ tail = 0;
322
+ while (lastM >= 0 && (tail += massM[lastM]) <= errbound / 2)
323
+ lastM--;
324
+ }
325
+ let power = 0;
326
+ for (let m = firstM; m <= lastM; m++) {
327
+ const wm = massM[m];
328
+ if (wm === 0)
329
+ continue;
330
+ const alt = binomialMasses(m, pAlt);
331
+ const nul = binomialMasses(m, pNull);
332
+ let lower = 0, upper = 0;
333
+ const lowerTail = new Array(m + 1);
334
+ const upperTail = new Array(m + 1);
335
+ for (let x = 0; x <= m; x++) {
336
+ lower += nul[x];
337
+ lowerTail[x] = lower;
338
+ }
339
+ for (let x = m; x >= 0; x--) {
340
+ upper += nul[x];
341
+ upperTail[x] = upper;
342
+ }
343
+ for (let x = 0; x <= m; x++) {
344
+ const lo = lowerTail[x];
345
+ const hi = upperTail[x];
346
+ let reject;
347
+ // At the exact half-tail boundary, compare the rational binomial tail combinatorially
348
+ // rather than letting floating-point summation decide whether it is just above or below 1/2.
349
+ const exactHalfBoundary = pNull === 0.5 && sigLevel === 1;
350
+ if (useOne) {
351
+ reject = exactHalfBoundary || (direction > 0 ? hi <= sigLevel : lo <= sigLevel);
352
+ }
353
+ else if (useBoth) {
354
+ // The central two-sided p-value is capped at 1, so at alpha=1 every outcome is rejected.
355
+ reject = exactHalfBoundary || lo <= sigLevel / 2 || hi <= sigLevel / 2;
356
+ }
357
+ else {
358
+ reject = direction > 0
359
+ ? (exactHalfBoundary ? x > Math.floor(m / 2) : hi <= sigLevel / 2)
360
+ : (exactHalfBoundary ? x < Math.ceil(m / 2) : lo <= sigLevel / 2);
361
+ }
362
+ if (reject)
363
+ power += wm * alt[x];
364
+ }
365
+ }
366
+ const note = `errbound= ${errbound === 0 ? "0" : errbound >= 0.001 ? String(errbound) : `${errbound.toExponential(0).replace(/e([+-]?)(\\d+)$/, (_m, sign, exp) => `e${sign || "+"}${exp.padStart(2, "0")}`)}`}${pb + pc === 1 ? " no non-informative pairs: pa+pd=0" : ""}`;
367
+ const method = "Power for McNemar's Exact Test" +
368
+ (useBoth ? ", including power to reject in the wrong direction" : "") +
369
+ (tsmethod === "central" && options.tsmethod !== undefined ? `, using (tsmethod=${tsmethod})` :
370
+ tsmethod === "minlike" ? `, using (tsmethod=${tsmethod})` :
371
+ tsmethod === "blaker" ? `, using (tsmethod=${tsmethod})` : "");
372
+ return reported("powerPaired2x2", { power, npairs, pb, pc, sigLevel, alternative, nullOddsRatio, note, method, warnings: [] });
373
+ }
374
+ /** Freedman clinical-trial power. Equivalent to `powerSurvEpi::powerCT.default()` in R.
375
+ * @param nE Experimental-group sample size.
376
+ * @param nC Control-group sample size.
377
+ * @param pE Experimental-group event probability.
378
+ * @param pC Control-group event probability.
379
+ * @param RR Experimental/control hazard ratio.
380
+ * @param options Significance level.
381
+ * @returns The normal-approximation power.
382
+ * @example
383
+ * ```ts
384
+ * powerCT(200, 200, 0.3707, 0.489, 0.7);
385
+ * ```
386
+ * @category Effect sizes and power
387
+ */
388
+ export function powerCT(nE, nC, pE, pC, RR, options = {}) {
389
+ checkOptions(options, POWER_CT_KEYS, "powerCT"); // generated: option-keys.mjs
390
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
391
+ checkAlpha(alpha);
392
+ for (const [v, name] of [[nE, "nE"], [nC, "nC"]])
393
+ checkNumber(v, name, positive, `'${name}' must be positive and finite`);
394
+ for (const [v, name] of [[pE, "pE"], [pC, "pC"]])
395
+ checkNumber(v, name, prob, `'${name}' must be in [0, 1]`);
396
+ checkNumber(RR, "RR", positive, "'RR' must be positive and finite");
397
+ const k = nE / nC;
398
+ const m = nE * pE + nC * pC;
399
+ return phi(Math.sqrt(k * m) * Math.abs(RR - 1) / (k * RR + 1) - z(1 - alpha / 2));
400
+ }
401
+ /** Freedman clinical-trial sample size. Equivalent to `powerSurvEpi::ssizeCT.default()` in R.
402
+ * @param power Target power.
403
+ * @param k Experimental/control allocation ratio.
404
+ * @param pE Experimental-group event probability.
405
+ * @param pC Control-group event probability.
406
+ * @param RR Experimental/control hazard ratio.
407
+ * @param options Significance level.
408
+ * @returns The integer sample sizes in the two groups.
409
+ * @example
410
+ * ```ts
411
+ * ssizeCT(0.8, 1, 0.3707, 0.489, 0.7);
412
+ * ```
413
+ * @category Effect sizes and power
414
+ */
415
+ export function ssizeCT(power, k, pE, pC, RR, options = {}) {
416
+ checkOptions(options, SSIZE_CT_KEYS, "ssizeCT"); // generated: option-keys.mjs
417
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
418
+ checkAlpha(alpha);
419
+ checkNumber(power, "power", (v) => prob(v) && v > 0 && v < 1, "'power' must be strictly between 0 and 1");
420
+ checkNumber(k, "k", positive, "'k' must be positive and finite");
421
+ checkNumber(pE, "pE", prob, "'pE' must be in [0, 1]");
422
+ checkNumber(pC, "pC", prob, "'pC' must be in [0, 1]");
423
+ checkNumber(RR, "RR", positive, "'RR' must be positive and finite");
424
+ const zz = z(1 - alpha / 2) + z(power);
425
+ const m = (1 / k) * (((k * RR + 1) / (RR - 1)) ** 2) * (zz * zz);
426
+ const den = k * pE + pC;
427
+ return { nE: Math.ceil(m * k / den), nC: Math.ceil(m / den) };
428
+ }
429
+ /** Schoenfeld/Latouche Cox-model power. Equivalent to `powerSurvEpi::powerEpi.default()` in R.
430
+ * @param n Total sample size.
431
+ * @param theta Hazard ratio.
432
+ * @param p Prevalence of the binary covariate.
433
+ * @param psi Event proportion.
434
+ * @param rho2 Squared correlation with another covariate.
435
+ * @param options Significance level.
436
+ * @returns The normal-approximation power.
437
+ * @example
438
+ * ```ts
439
+ * powerEpi(139, 2, 0.39, 0.505, 0.132 ** 2);
440
+ * ```
441
+ * @category Effect sizes and power
442
+ */
443
+ export function powerEpi(n, theta, p, psi, rho2, options = {}) {
444
+ checkOptions(options, POWER_EPI_KEYS, "powerEpi"); // generated: option-keys.mjs
445
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
446
+ checkAlpha(alpha);
447
+ checkNumber(n, "n", positive, "'n' must be positive and finite");
448
+ checkNumber(theta, "theta", positive, "'theta' must be positive and finite");
449
+ checkNumber(p, "p", prob, "'p' must be in [0, 1]");
450
+ checkNumber(psi, "psi", prob, "'psi' must be in [0, 1]");
451
+ checkNumber(rho2, "rho2", prob, "'rho2' must be in [0, 1]");
452
+ const info = n * Math.log(theta) ** 2 * p * (1 - p) * psi * (1 - rho2);
453
+ return phi(Math.sqrt(info) - z(1 - alpha / 2));
454
+ }
455
+ /** Schoenfeld/Latouche total sample size. Equivalent to `powerSurvEpi::ssizeEpi.default()` in R.
456
+ * @param power Target power.
457
+ * @param theta Hazard ratio.
458
+ * @param p Prevalence of the binary covariate.
459
+ * @param psi Event proportion.
460
+ * @param rho2 Squared correlation with another covariate.
461
+ * @param options Significance level.
462
+ * @returns The integer total sample size.
463
+ * @example
464
+ * ```ts
465
+ * ssizeEpi(0.8, 2, 0.39, 0.505, 0.132 ** 2);
466
+ * ```
467
+ * @category Effect sizes and power
468
+ */
469
+ export function ssizeEpi(power, theta, p, psi, rho2, options = {}) {
470
+ checkOptions(options, SSIZE_EPI_KEYS, "ssizeEpi"); // generated: option-keys.mjs
471
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
472
+ checkAlpha(alpha);
473
+ checkNumber(power, "power", prob, "'power' must be in [0, 1]");
474
+ checkNumber(theta, "theta", positive, "'theta' must be positive and finite");
475
+ checkNumber(p, "p", prob, "'p' must be in [0, 1]");
476
+ checkNumber(psi, "psi", prob, "'psi' must be in [0, 1]");
477
+ checkNumber(rho2, "rho2", prob, "'rho2' must be in [0, 1]");
478
+ const den = Math.log(theta) ** 2 * p * (1 - p) * psi * (1 - rho2);
479
+ return Math.ceil((z(1 - alpha / 2) + z(power)) ** 2 / den);
480
+ }
481
+ /** Schoenfeld/Latouche required event count. Equivalent to `powerSurvEpi::numDEpi.default()` in R.
482
+ * @param power Target power.
483
+ * @param theta Hazard ratio.
484
+ * @param p Prevalence of the binary covariate.
485
+ * @param rho2 Squared correlation with another covariate.
486
+ * @param options Significance level.
487
+ * @returns The integer number of events required.
488
+ * @example
489
+ * ```ts
490
+ * numDEpi(0.8, 2, 0.39, 0.132 ** 2);
491
+ * ```
492
+ * @category Effect sizes and power
493
+ */
494
+ export function numDEpi(power, theta, p, rho2, options = {}) {
495
+ checkOptions(options, NUM_DEPI_KEYS, "numDEpi"); // generated: option-keys.mjs
496
+ const alpha = options.alpha ?? DEFAULT_ALPHA;
497
+ checkAlpha(alpha);
498
+ checkNumber(power, "power", (v) => prob(v) && v > 0 && v < 1, "'power' must be strictly between 0 and 1");
499
+ checkNumber(theta, "theta", positive, "'theta' must be positive and finite");
500
+ checkNumber(p, "p", prob, "'p' must be in [0, 1]");
501
+ checkNumber(rho2, "rho2", prob, "'rho2' must be in [0, 1]");
502
+ const den = Math.log(theta) ** 2 * p * (1 - p) * (1 - rho2);
503
+ return Math.ceil((z(1 - alpha / 2) + z(power)) ** 2 / den);
504
+ }
505
+ function cumulative(mass) {
506
+ const out = new Array(mass.length);
507
+ let sum = 0, correction = 0;
508
+ for (let i = 0; i < mass.length; i++) {
509
+ const y = mass[i] - correction, t = sum + y;
510
+ correction = (t - sum) - y;
511
+ sum = t;
512
+ out[i] = sum;
513
+ }
514
+ return out;
515
+ }
516
+ function survival(mass) {
517
+ const out = new Array(mass.length);
518
+ let sum = 0, correction = 0;
519
+ for (let i = mass.length - 1; i >= 0; i--) {
520
+ const y = mass[i] - correction, t = sum + y;
521
+ correction = (t - sum) - y;
522
+ sum = t;
523
+ out[i] = sum;
524
+ }
525
+ return out;
526
+ }
527
+ function designProb(r1, r, p0Stage1, p1Stage1, p0Stage2Survival, p1Stage2Cdf) {
528
+ let alpha = 0, beta = 0;
529
+ // A trial that stops for futility after stage 1 is a type-II error under pa.
530
+ beta = p1Stage1.slice(0, r1 + 1).reduce((sum, value) => sum + value, 0);
531
+ for (let x = r1 + 1; x < p0Stage1.length; x++) {
532
+ const j = r - x;
533
+ const c0 = j < 0 ? 1 : j + 1 >= p0Stage2Survival.length ? 0 : p0Stage2Survival[j + 1];
534
+ const c1 = j < 0 ? 0 : p1Stage2Cdf[Math.min(j, p1Stage2Cdf.length - 1)];
535
+ // Sum the upper tail directly: 1 - CDF(j) erases probabilities near machine epsilon.
536
+ alpha += p0Stage1[x] * c0;
537
+ beta += p1Stage1[x] * c1;
538
+ }
539
+ return [alpha, beta];
540
+ }
541
+ /** Enumerates Simon's two-stage Phase II designs. Equivalent to `clinfun::ph2simon()` in R.
542
+ * @param pu Unacceptable response rate.
543
+ * @param pa Desirable response rate.
544
+ * @param ep1 Maximum type-I error at pu.
545
+ * @param ep2 Maximum type-II error at pa.
546
+ * @param options Maximum total sample size, at most 1000.
547
+ * @returns Candidate rows and structured minimax, optimal and admissible designs.
548
+ * @example
549
+ * ```ts
550
+ * ph2simon(0.2, 0.4, 0.05, 0.1).minimax.n;
551
+ * ```
552
+ * @category Effect sizes and power
553
+ */
554
+ export function ph2simon(pu, pa, ep1, ep2, options = {}) {
555
+ checkOptions(options, PH2SIMON_KEYS, "ph2simon"); // generated: option-keys.mjs
556
+ const nmax = options.nmax ?? 100;
557
+ for (const [v, name] of [[pu, "pu"], [pa, "pa"], [ep1, "ep1"], [ep2, "ep2"]])
558
+ checkNumber(v, name, prob, `'${name}' must be in [0, 1]`);
559
+ checkNumber(nmax, "nmax", (v) => Number.isInteger(v) && v >= 1 && v <= 1000, "nmax cannot exceed 1000");
560
+ const masses0 = Array.from({ length: nmax + 1 }, (_, size) => binomialMasses(size, pu));
561
+ const masses1 = Array.from({ length: nmax + 1 }, (_, size) => binomialMasses(size, pa));
562
+ const cdfs0 = masses0.map(cumulative), cdfs1 = masses1.map(cumulative), survivals0 = masses0.map(survival);
563
+ const out = [];
564
+ for (let n = 2; n <= nmax; n++) {
565
+ let best;
566
+ for (let n1 = 1; n1 < n && (best === undefined || n1 < best.enP0); n1++) {
567
+ const n2 = n - n1;
568
+ const p0Stage1 = masses0[n1], p1Stage1 = masses1[n1];
569
+ const p1Stage2Cdf = cdfs1[n2];
570
+ const p0Stage1Cdf = cdfs0[n1];
571
+ for (let r1 = 0; r1 < n1; r1++) {
572
+ const pet = p0Stage1Cdf[r1];
573
+ const en = n1 + n2 * (1 - pet);
574
+ // Match clinfun: choose the largest final cutoff r satisfying both error constraints.
575
+ let low = r1, high = n - 1, rFound = -1;
576
+ while (low <= high) {
577
+ const mid = Math.floor((low + high) / 2);
578
+ const [, bAlt] = designProb(r1, mid, p0Stage1, p1Stage1, survivals0[n2], p1Stage2Cdf);
579
+ if (bAlt <= ep2) {
580
+ rFound = mid;
581
+ low = mid + 1;
582
+ }
583
+ else
584
+ high = mid - 1;
585
+ }
586
+ if (rFound >= 0) {
587
+ const [a] = designProb(r1, rFound, p0Stage1, p1Stage1, survivals0[n2], p1Stage2Cdf);
588
+ if (a > ep1)
589
+ rFound = -1;
590
+ }
591
+ if (rFound >= 0 && (best === undefined || en < best.enP0)) {
592
+ best = { r1, n1, r: rFound, n, enP0: en, petP0: pet };
593
+ }
594
+ }
595
+ }
596
+ if (best)
597
+ out.push(best);
598
+ }
599
+ if (out.length === 0)
600
+ throw new Error(` No feasible solution found. \n\tIncrease maximum sample size. Current nmax value = ${nmax}.`);
601
+ const frontier = out.filter((row, i) => !out.some((other, j) => j !== i && other.n <= row.n && other.enP0 <= row.enP0 && (other.n < row.n || other.enP0 < row.enP0)));
602
+ const hull = [];
603
+ const crossing = (a, b) => (a.enP0 - b.enP0) / ((b.n - a.n) + (a.enP0 - b.enP0));
604
+ for (const row of frontier) {
605
+ hull.push(row);
606
+ while (hull.length >= 3) {
607
+ const a = hull[hull.length - 3], b = hull[hull.length - 2], c = hull[hull.length - 1];
608
+ if (crossing(a, b) > crossing(b, c))
609
+ break;
610
+ hull.splice(hull.length - 2, 1);
611
+ }
612
+ }
613
+ const selected = hull.map((row, i) => {
614
+ const qLo = i === hull.length - 1 ? 0 : crossing(row, hull[i + 1]);
615
+ const qHi = i === 0 ? 1 : crossing(hull[i - 1], row);
616
+ return { ...row, qLo, qHi };
617
+ });
618
+ const minimax = selected[0];
619
+ const optimal = selected.reduce((a, b) => b.enP0 < a.enP0 ? b : a);
620
+ const admissible = selected;
621
+ const warnings = [];
622
+ if (optimal.n >= nmax - 1)
623
+ warnings.push(` Optimal sample size too close to nmax. \n Try increasing nmax (current value = ${nmax})\n`);
624
+ return reported("ph2simon", { out, minimax, optimal, admissible, pu, pa, alpha: ep1, beta: ep2, nmax, warnings });
625
+ }