@numero-uno-jpn/rstats 1.0.0 → 1.2.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 (79) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.ja.md +12 -11
  3. package/README.md +12 -11
  4. package/THIRD_PARTY_NOTICES.md +3 -2
  5. package/dist/chunks/{chunk-UJ66VQIG.js → chunk-2NNBUYHJ.js} +2 -2
  6. package/dist/chunks/{chunk-YHNMBYSW.js → chunk-47IIPUFN.js} +2 -2
  7. package/dist/chunks/{chunk-WIBKS73G.js → chunk-4AOTAT3O.js} +2 -2
  8. package/dist/chunks/{chunk-4F2IALD4.js → chunk-5SGTWSCB.js} +3 -3
  9. package/dist/chunks/{chunk-F7YGX7PN.js → chunk-6FZHTD5G.js} +2 -2
  10. package/dist/chunks/{chunk-NSWENS3S.js → chunk-73LNRWU3.js} +1 -1
  11. package/dist/chunks/{chunk-BQSIBJVX.js → chunk-7INBXTVV.js} +2 -2
  12. package/dist/chunks/chunk-7WG7X2UI.js +2 -0
  13. package/dist/chunks/{chunk-H7I32ZZE.js → chunk-A66M3ZEA.js} +2 -2
  14. package/dist/chunks/{chunk-BWKHYRM6.js → chunk-BI7NYJWP.js} +1 -1
  15. package/dist/chunks/{chunk-QZK3CCBA.js → chunk-BKV3FINA.js} +2 -2
  16. package/dist/chunks/{chunk-QQX46TCI.js → chunk-CQB4BJBR.js} +2 -2
  17. package/dist/chunks/{chunk-3W5NFFAA.js → chunk-EEU7D4RU.js} +1 -1
  18. package/dist/chunks/{chunk-DCAWMF4K.js → chunk-F3EQLL4F.js} +2 -2
  19. package/dist/chunks/{chunk-IEOD5GWC.js → chunk-HBHMEPGY.js} +2 -2
  20. package/dist/chunks/{chunk-4OLDGML4.js → chunk-IAWXF73N.js} +2 -2
  21. package/dist/chunks/{chunk-CKV4JWW2.js → chunk-IMPRIQE5.js} +1 -1
  22. package/dist/chunks/chunk-JWBSEL3V.js +2 -0
  23. package/dist/chunks/{chunk-LROMWFAK.js → chunk-L23RSC2N.js} +2 -2
  24. package/dist/chunks/{chunk-UKNDX4BA.js → chunk-NSU6U3ET.js} +2 -2
  25. package/dist/chunks/{chunk-WQWZ7FND.js → chunk-ORE5ZRCY.js} +2 -2
  26. package/dist/chunks/{chunk-YG5S5AVP.js → chunk-RRO4LMCB.js} +2 -2
  27. package/dist/chunks/{chunk-6XJBCRBV.js → chunk-T5DRIITM.js} +2 -2
  28. package/dist/chunks/{chunk-63OPBEYO.js → chunk-TNETWBF5.js} +1 -1
  29. package/dist/chunks/{chunk-O2SQMGE3.js → chunk-VERBXW6E.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions/signrank.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +6 -1
  34. package/dist/entries/tests.js +5 -0
  35. package/dist/htest/ansariTest.js +32 -34
  36. package/dist/htest/binomCI.d.ts +116 -0
  37. package/dist/htest/binomCI.js +252 -0
  38. package/dist/htest/boschlooTest.d.ts +65 -0
  39. package/dist/htest/boschlooTest.js +394 -0
  40. package/dist/htest/chisqTest.d.ts +19 -0
  41. package/dist/htest/chisqTest.js +30 -2
  42. package/dist/htest/cor.d.ts +2 -2
  43. package/dist/htest/cor.js +2 -1
  44. package/dist/htest/core/scoreDistribution.d.ts +39 -0
  45. package/dist/htest/core/scoreDistribution.js +151 -0
  46. package/dist/htest/core/twoProportions.d.ts +48 -0
  47. package/dist/htest/core/twoProportions.js +476 -0
  48. package/dist/htest/equivalence.d.ts +172 -0
  49. package/dist/htest/equivalence.js +189 -0
  50. package/dist/htest/fisherTest.d.ts +49 -0
  51. package/dist/htest/fisherTest.js +136 -13
  52. package/dist/htest/tableTests.d.ts +216 -0
  53. package/dist/htest/tableTests.js +650 -0
  54. package/dist/htest/twoByTwo.d.ts +203 -0
  55. package/dist/htest/twoByTwo.js +385 -0
  56. package/dist/htest/wilcoxTest.d.ts +23 -8
  57. package/dist/htest/wilcoxTest.js +521 -199
  58. package/dist/linalg/chol.d.ts +3 -3
  59. package/dist/linalg/chol.js +10 -2
  60. package/dist/linalg/qr.js +39 -15
  61. package/dist/linalg.js +2 -2
  62. package/dist/mixed.js +2 -2
  63. package/dist/models/anovaSequential.d.ts +16 -1
  64. package/dist/models/anovaSequential.js +40 -5
  65. package/dist/models/aovStrata.js +21 -4
  66. package/dist/models/glm.d.ts +15 -4
  67. package/dist/models/glm.js +13 -6
  68. package/dist/models/survival.d.ts +4 -1
  69. package/dist/models/survival.js +7 -1
  70. package/dist/numerics.js +2 -2
  71. package/dist/rstats.js +16 -16
  72. package/dist/special/igam.js +140 -23
  73. package/dist/special/loader.js +8 -0
  74. package/dist/special.js +2 -2
  75. package/dist/tests.js +13 -13
  76. package/llms.txt +9 -1
  77. package/package.json +1 -1
  78. package/dist/chunks/chunk-KICBQGFN.js +0 -2
  79. package/dist/chunks/chunk-WWVMVZUL.js +0 -2
@@ -0,0 +1,172 @@
1
+ import { type Sample } from "./types.js";
2
+ /**
3
+ * Options for {@link tost}.
4
+ *
5
+ * @category Hypothesis tests
6
+ */
7
+ export interface TostOptions {
8
+ /** The equivalence margin: equivalence means |mean difference| < epsilon. Positive. Default `1` (as R). */
9
+ epsilon?: number;
10
+ /** Paired TOST on `x - y` (pairs with `NaN` are dropped). Default `false`. */
11
+ paired?: boolean;
12
+ /** Pooled variance (Student's t) instead of Welch's. Default `false`. */
13
+ varEqual?: boolean;
14
+ /** One minus the level of each one-sided test, in (0.5, 1); the interval is a 1 - 2(1 - confLevel) interval.
15
+ * Default `0.95`. */
16
+ confLevel?: number;
17
+ /** The level of each one-sided test, in (0, 0.5); overrides `confLevel` (which becomes `1 - alpha`). */
18
+ alpha?: number;
19
+ }
20
+ /**
21
+ * Result of {@link tost}.
22
+ *
23
+ * @category Hypothesis tests
24
+ */
25
+ export interface TostResult {
26
+ /** `"Welch Two Sample TOST"`, `" Two Sample TOST"` (pooled; the leading space is R's) or `"Paired TOST"`. */
27
+ method: string;
28
+ /** Degrees of freedom of the t tests (`parameterName` `"df"`). */
29
+ parameter: number;
30
+ /** `"df"`. */
31
+ parameterName: string;
32
+ /** The larger of the two one-sided p-values, `P(T > (epsilon - |d|)/se)` (R's `tost.p.value`). */
33
+ pValue: number;
34
+ /** `"rejected"` (equivalence shown: `confInt` lies inside (-epsilon, epsilon)) or `"not rejected"`, as R. */
35
+ result: "rejected" | "not rejected";
36
+ /** `d -+ qt(confLevel, df) se`: the 1 - 2(1 - confLevel) interval of the difference (R's `tost.interval`). */
37
+ confInt: [number, number];
38
+ /** `confLevel` (or `1 - alpha`), R's `conf.level` attribute of the interval. */
39
+ confLevel: number;
40
+ /** `[mean of x, mean of y]`, or the mean of the differences for a paired test. */
41
+ estimate: number | number[];
42
+ /** Names of `estimate`, as tTest's. */
43
+ estimateNames: string | string[];
44
+ /** The margin. */
45
+ epsilon: number;
46
+ /** Standard error of the difference (R's `se.diff`). */
47
+ seDiff: number;
48
+ /** Warnings (none: input without a defined result is an error). */
49
+ warnings: string[];
50
+ }
51
+ /**
52
+ * Two one-sided t tests (TOST) of equivalence of two means. Equivalent to `equivalence::tost()` in R.
53
+ *
54
+ * Equivalence, |mean(x) - mean(y)| < epsilon, is shown at level alpha = 1 - confLevel when both one-sided t tests of
55
+ * H01: d <= -epsilon and H02: d >= epsilon reject; the p-value is the larger of their p-values and `confInt` the dual
56
+ * 1 - 2 alpha interval (90% for the default `confLevel` 0.95). The difference, standard error and degrees of freedom are
57
+ * those of {@link tTest} (Welch's by default, pooled with `varEqual`, paired with `paired`), with tTest's checks and
58
+ * errors. Used on 0/1 data it compares two proportions with a t approximation; for counts
59
+ * {@link binomDiffEquivalenceTest} is the better test.
60
+ *
61
+ * Unlike R, a level of 0.5 or less (`confLevel`) or of 0.5 or more (`alpha`) is an error (the interval would be empty),
62
+ * and so is a margin that is not positive.
63
+ *
64
+ * @param x Sample.
65
+ * @param y Second sample.
66
+ * @param options See {@link TostOptions}.
67
+ * @returns See {@link TostResult}.
68
+ * @throws RangeError for a margin that is not positive and finite or a level out of range; Error where tTest has
69
+ * too few observations or the data are essentially constant.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const r = tost([5.1, 4.9, 5.6, 5.8, 6.0, 5.4], [5.3, 5.0, 5.5, 5.7, 5.9, 5.2], { epsilon: 0.5 });
74
+ * r.pValue; // 0.029694342816029128
75
+ * r.confInt; // [-0.36394177233776226, 0.4306084390044287] (a 90% interval)
76
+ * r.result; // "rejected"
77
+ * ```
78
+ *
79
+ * @category Hypothesis tests
80
+ */
81
+ export declare function tost(x: Sample, y: Sample, options?: TostOptions): TostResult;
82
+ /**
83
+ * Statistics of {@link binomDiffEquivalenceTest}.
84
+ *
85
+ * @category Hypothesis tests
86
+ */
87
+ export type BinomDiffEquivalenceMethod = "mn" | "mee" | "wald";
88
+ /**
89
+ * Options for {@link binomDiffEquivalenceTest}.
90
+ *
91
+ * @category Hypothesis tests
92
+ */
93
+ export interface BinomDiffEquivalenceTestOptions {
94
+ /** The equivalence margin epsilon, in (0, 1): equivalence means -epsilon < p1 - p2 < epsilon. Required. */
95
+ margin?: number;
96
+ /** The statistic: `"mn"` (Miettinen-Nurminen score, the default), `"mee"` (Farrington-Manning score) or `"wald"`.
97
+ * Unambiguous abbreviations are accepted. */
98
+ method?: BinomDiffEquivalenceMethod | (string & {});
99
+ /** The level of each one-sided test, in (0, 0.5). Default `0.05`. */
100
+ alpha?: number;
101
+ }
102
+ /**
103
+ * Result of {@link binomDiffEquivalenceTest}.
104
+ *
105
+ * @category Hypothesis tests
106
+ */
107
+ export interface BinomDiffEquivalenceTestResult {
108
+ /** The statistic, in full (`"mn"`, `"mee"` or `"wald"`). */
109
+ method: BinomDiffEquivalenceMethod;
110
+ /** The estimate p1 - p2. */
111
+ estimate: number;
112
+ /** The margin epsilon. */
113
+ margin: number;
114
+ /** The level of each one-sided test. */
115
+ alpha: number;
116
+ /**
117
+ * `[z(-margin), z(margin)]`, z(delta0) = (p1 - p2 - delta0) / sqrt(var(delta0)): the statistics of H01: p1 - p2 <=
118
+ * -margin (large values reject) and of H02: p1 - p2 >= margin (small values reject).
119
+ */
120
+ statistic: [number, number];
121
+ /** `"z"`. */
122
+ statisticName: string;
123
+ /** `[P(Z > z(-margin)), P(Z < z(margin))]`: the one-sided p-values of H01 and H02. */
124
+ pValues: [number, number];
125
+ /** The larger of `pValues`: the p-value of the test of equivalence. */
126
+ pValue: number;
127
+ /** `"rejected"` (equivalence shown: both p-values below alpha) or `"not rejected"`, as {@link tost}'s `result`. */
128
+ result: "rejected" | "not rejected";
129
+ /** The 1 - 2 alpha interval of p1 - p2 of {@link binomDiffCI} with the same method; equivalence is shown exactly when
130
+ * it lies inside (-margin, margin). */
131
+ confInt: [number, number];
132
+ /** `1 - 2 alpha`. */
133
+ confLevel: number;
134
+ /** Warnings (none: input without a defined result is an error). */
135
+ warnings: string[];
136
+ }
137
+ /**
138
+ * Test of equivalence of two independent proportions x1/n1 and x2/n2 within a margin. Two one-sided tests of
139
+ * H01: p1 - p2 <= -margin and H02: p1 - p2 >= margin, each at level `alpha`; equivalence is shown when both reject.
140
+ * Not an R function. (The R packages in scope give the dual intervals, `DescTools::BinomDiffCI`, or test one bound at
141
+ * a time.)
142
+ *
143
+ * The statistic at a bound delta0 is z = (p1 - p2 - delta0) / sqrt(var), with var the variance of p1 - p2 at the
144
+ * maximum likelihood estimate of (p1, p2) under p1 - p2 = delta0 (Farrington and Manning 1990, `"mee"`), the same times
145
+ * N/(N - 1) (Miettinen and Nurminen 1985, `"mn"`, the default), or at the observed proportions (`"wald"`). The
146
+ * p-values are normal tails. The test is dual to {@link binomDiffCI} with the same method at the level 1 - 2 alpha:
147
+ * equivalence is shown exactly when that interval, returned as `confInt`, lies inside (-margin, margin).
148
+ *
149
+ * The Wald variance is 0 when both proportions are 0 or 1: the statistics are then infinite and the p-values 0 or 1,
150
+ * as binomDiffCI's Wald interval is a point there.
151
+ *
152
+ * @param x1 Successes in group 1.
153
+ * @param n1 Trials in group 1.
154
+ * @param x2 Successes in group 2.
155
+ * @param n2 Trials in group 2.
156
+ * @param options See {@link BinomDiffEquivalenceTestOptions}; `margin` is required.
157
+ * @returns See {@link BinomDiffEquivalenceTestResult}.
158
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a margin outside (0, 1), alpha
159
+ * outside (0, 0.5), or an unknown method.
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * const r = binomDiffEquivalenceTest(80, 100, 78, 100, { margin: 0.15 });
164
+ * r.pValues; // [0.0018937433499954864, 0.012899725361675841]
165
+ * r.pValue; // 0.012899725361675841
166
+ * r.confInt; // [-0.07557697533608577, 0.11553638647686569] (binomDiffCI, method "mn", 90%)
167
+ * r.result; // "rejected"
168
+ * ```
169
+ *
170
+ * @category Hypothesis tests
171
+ */
172
+ export declare function binomDiffEquivalenceTest(x1: number, n1: number, x2: number, n2: number, options?: BinomDiffEquivalenceTestOptions): BinomDiffEquivalenceTestResult;
@@ -0,0 +1,189 @@
1
+ // Tests of equivalence: the two one-sided t tests (TOST) of the package equivalence's tost, and a test of equivalence
2
+ // of two proportions on counts with the score statistics of the difference.
3
+ //
4
+ // Written for rStats.js from the published methods and the package's documented behaviour (no R or package code):
5
+ // - TOST (Schuirmann, Journal of Pharmacokinetics and Biopharmaceutics 15, 1987): equivalence of the means within
6
+ // (-epsilon, epsilon) is shown at level alpha when both H01: d <= -epsilon and H02: d >= epsilon are rejected by
7
+ // one-sided t tests at alpha; the larger one-sided p-value is P(T > (epsilon - |d|)/se) on the df of the t test, and
8
+ // the dual interval is d -+ qt(1 - alpha, df) se, a 1 - 2 alpha interval. The mean difference, its standard error
9
+ // and the df are tTest's (Welch's, pooled or paired).
10
+ // - Two proportions: the same pair of one-sided hypotheses about p1 - p2, tested with the score statistic
11
+ // z(delta0) = (p1 - p2 - delta0) / sqrt(var(delta0)) at delta0 = -epsilon and +epsilon, var at the maximum likelihood
12
+ // estimate under p1 - p2 = delta0 (Farrington and Manning, Statistics in Medicine 9, 1990, 1447-1454), times
13
+ // N/(N - 1) for Miettinen and Nurminen (Statistics in Medicine 4, 1985, 213-226), or at the observed proportions
14
+ // (Wald). The statistics and the restricted MLE are those of src/htest/core/twoProportions.ts; the dual 1 - 2 alpha
15
+ // interval is binomDiffCI's with the same method.
16
+ import { pnorm } from "../distributions/normal.js";
17
+ import { pt1, qt1 } from "../distributions/t.js";
18
+ import { reported, unreported } from "../internal/warnings.js";
19
+ import { checkTrials, levelOfAlpha } from "./binomCI.js";
20
+ import { diffDeviation, diffVariance } from "./core/twoProportions.js";
21
+ import { matchChoice } from "./power.js";
22
+ import { tTest } from "./tTest.js";
23
+ import { checkConfLevelOpen } from "./types.js";
24
+ import { binomDiffLimits } from "./twoByTwo.js";
25
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
26
+ import { checkOptions } from "../internal/checkOptions.js";
27
+ const TOST_KEYS = ["epsilon", "paired", "varEqual", "confLevel", "alpha"];
28
+ const BINOM_DIFF_EQUIVALENCE_TEST_KEYS = ["margin", "method", "alpha"];
29
+ // Generated by `node scripts/option-keys.mjs --write` (end)
30
+ /** The level of a TOST: alpha in (0, 0.5), so that the 1 - 2 alpha interval is an interval */
31
+ function checkAlpha(alpha, name) {
32
+ if (!(typeof alpha === "number" && alpha > 0 && alpha < 0.5))
33
+ throw new RangeError(`'${name}' must be a single number in (0, 0.5)`);
34
+ }
35
+ /**
36
+ * Two one-sided t tests (TOST) of equivalence of two means. Equivalent to `equivalence::tost()` in R.
37
+ *
38
+ * Equivalence, |mean(x) - mean(y)| < epsilon, is shown at level alpha = 1 - confLevel when both one-sided t tests of
39
+ * H01: d <= -epsilon and H02: d >= epsilon reject; the p-value is the larger of their p-values and `confInt` the dual
40
+ * 1 - 2 alpha interval (90% for the default `confLevel` 0.95). The difference, standard error and degrees of freedom are
41
+ * those of {@link tTest} (Welch's by default, pooled with `varEqual`, paired with `paired`), with tTest's checks and
42
+ * errors. Used on 0/1 data it compares two proportions with a t approximation; for counts
43
+ * {@link binomDiffEquivalenceTest} is the better test.
44
+ *
45
+ * Unlike R, a level of 0.5 or less (`confLevel`) or of 0.5 or more (`alpha`) is an error (the interval would be empty),
46
+ * and so is a margin that is not positive.
47
+ *
48
+ * @param x Sample.
49
+ * @param y Second sample.
50
+ * @param options See {@link TostOptions}.
51
+ * @returns See {@link TostResult}.
52
+ * @throws RangeError for a margin that is not positive and finite or a level out of range; Error where tTest has
53
+ * too few observations or the data are essentially constant.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const r = tost([5.1, 4.9, 5.6, 5.8, 6.0, 5.4], [5.3, 5.0, 5.5, 5.7, 5.9, 5.2], { epsilon: 0.5 });
58
+ * r.pValue; // 0.029694342816029128
59
+ * r.confInt; // [-0.36394177233776226, 0.4306084390044287] (a 90% interval)
60
+ * r.result; // "rejected"
61
+ * ```
62
+ *
63
+ * @category Hypothesis tests
64
+ */
65
+ export function tost(x, y, options = {}) {
66
+ checkOptions(options, TOST_KEYS, "tost"); // generated: option-keys.mjs
67
+ const epsilon = options.epsilon ?? 1;
68
+ if (!(typeof epsilon === "number" && epsilon > 0 && epsilon < Infinity))
69
+ throw new RangeError("'epsilon' must be a positive number");
70
+ let confLevel;
71
+ // the upper tail probability of the t quantile: alpha itself where given (1 - confLevel would lose its digits)
72
+ let tail;
73
+ if (options.alpha !== undefined) {
74
+ // as R, alpha overrides conf.level
75
+ checkAlpha(options.alpha, "alpha");
76
+ confLevel = 1 - options.alpha;
77
+ tail = options.alpha;
78
+ }
79
+ else {
80
+ confLevel = options.confLevel ?? 0.95;
81
+ checkConfLevelOpen(confLevel);
82
+ if (!(confLevel > 0.5))
83
+ throw new RangeError("'confLevel' must be greater than 0.5");
84
+ tail = 1 - confLevel;
85
+ }
86
+ if (y === undefined)
87
+ throw new TypeError("'y' is required");
88
+ const paired = options.paired ?? false;
89
+ const varEqual = options.varEqual ?? false;
90
+ const t = unreported(() => tTest(x, y, { paired, varEqual }));
91
+ const se = t.stdErr;
92
+ const df = t.parameter;
93
+ const d = typeof t.estimate === "number" ? t.estimate : t.estimate[0] - t.estimate[1];
94
+ const pValue = pt1((epsilon - Math.abs(d)) / se, df, false, false);
95
+ // (rule 10: for a tail below 1e-8 the upper tail itself; at alpha = 1e-12 and 8 df the quantile from 1 - alpha was
96
+ // 69.69523624766852 for 69.69504323785972, as 1 - alpha has lost its digits)
97
+ const q = tail < 1e-8 ? qt1(tail, df, false, false) : qt1(confLevel, df, true, false);
98
+ const confInt = [d - q * se, d + q * se];
99
+ return reported("tost", {
100
+ method: t.method.replace("t-test", "TOST"),
101
+ parameter: df,
102
+ parameterName: "df",
103
+ pValue,
104
+ result: confInt[0] > -epsilon && confInt[1] < epsilon ? "rejected" : "not rejected",
105
+ confInt,
106
+ confLevel,
107
+ estimate: t.estimate,
108
+ // equivalence::tost names a paired estimate "mean of the differences" (tTest, as R's t.test, "mean difference")
109
+ estimateNames: paired ? "mean of the differences" : t.estimateNames,
110
+ epsilon,
111
+ seDiff: se,
112
+ warnings: [],
113
+ });
114
+ }
115
+ const EQUIVALENCE_METHODS = ["mn", "mee", "wald"];
116
+ /**
117
+ * Test of equivalence of two independent proportions x1/n1 and x2/n2 within a margin. Two one-sided tests of
118
+ * H01: p1 - p2 <= -margin and H02: p1 - p2 >= margin, each at level `alpha`; equivalence is shown when both reject.
119
+ * Not an R function. (The R packages in scope give the dual intervals, `DescTools::BinomDiffCI`, or test one bound at
120
+ * a time.)
121
+ *
122
+ * The statistic at a bound delta0 is z = (p1 - p2 - delta0) / sqrt(var), with var the variance of p1 - p2 at the
123
+ * maximum likelihood estimate of (p1, p2) under p1 - p2 = delta0 (Farrington and Manning 1990, `"mee"`), the same times
124
+ * N/(N - 1) (Miettinen and Nurminen 1985, `"mn"`, the default), or at the observed proportions (`"wald"`). The
125
+ * p-values are normal tails. The test is dual to {@link binomDiffCI} with the same method at the level 1 - 2 alpha:
126
+ * equivalence is shown exactly when that interval, returned as `confInt`, lies inside (-margin, margin).
127
+ *
128
+ * The Wald variance is 0 when both proportions are 0 or 1: the statistics are then infinite and the p-values 0 or 1,
129
+ * as binomDiffCI's Wald interval is a point there.
130
+ *
131
+ * @param x1 Successes in group 1.
132
+ * @param n1 Trials in group 1.
133
+ * @param x2 Successes in group 2.
134
+ * @param n2 Trials in group 2.
135
+ * @param options See {@link BinomDiffEquivalenceTestOptions}; `margin` is required.
136
+ * @returns See {@link BinomDiffEquivalenceTestResult}.
137
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a margin outside (0, 1), alpha
138
+ * outside (0, 0.5), or an unknown method.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const r = binomDiffEquivalenceTest(80, 100, 78, 100, { margin: 0.15 });
143
+ * r.pValues; // [0.0018937433499954864, 0.012899725361675841]
144
+ * r.pValue; // 0.012899725361675841
145
+ * r.confInt; // [-0.07557697533608577, 0.11553638647686569] (binomDiffCI, method "mn", 90%)
146
+ * r.result; // "rejected"
147
+ * ```
148
+ *
149
+ * @category Hypothesis tests
150
+ */
151
+ export function binomDiffEquivalenceTest(x1, n1, x2, n2, options = {}) {
152
+ checkOptions(options, BINOM_DIFF_EQUIVALENCE_TEST_KEYS, "binomDiffEquivalenceTest"); // generated: option-keys.mjs
153
+ const method = matchChoice(options.method, EQUIVALENCE_METHODS);
154
+ const margin = options.margin;
155
+ if (margin === undefined)
156
+ throw new TypeError("'margin' is required");
157
+ if (!(typeof margin === "number" && margin > 0 && margin < 1))
158
+ throw new RangeError("'margin' must be a single number in (0, 1)");
159
+ const alpha = options.alpha ?? 0.05;
160
+ checkAlpha(alpha, "alpha");
161
+ const [a1, m1] = checkTrials(x1, n1, "x1", "n1");
162
+ const [a2, m2] = checkTrials(x2, n2, "x2", "n2");
163
+ const est = a1 / m1 - a2 / m2;
164
+ // z at delta0 = -+margin, written as diffStatistic's deviation (p1 - p2 - delta0); the variance is positive for the
165
+ // score methods (the restricted MLE cannot put both proportions at 0 or 1 when 0 < |delta0| < 1)
166
+ const z = (delta0) => diffDeviation(a1, m1, a2, m2, delta0) / Math.sqrt(diffVariance(a1, m1, a2, m2, delta0, method));
167
+ const zLower = z(-margin);
168
+ const zUpper = z(margin);
169
+ const pValues = [pnorm(zLower, { lowerTail: false }), pnorm(zUpper)];
170
+ const pValue = Math.max(pValues[0], pValues[1]);
171
+ const confLevel = 1 - 2 * alpha;
172
+ // binomDiffCI's interval at 1 - 2 alpha, from 2 alpha itself (alpha taken back as 1 - confLevel is about
173
+ // eps / (2 alpha) relative off, and loses the level's digits for tiny alpha)
174
+ const confInt = binomDiffLimits(a1, m1, a2, m2, method, levelOfAlpha(2 * alpha, confLevel));
175
+ return reported("binomDiffEquivalenceTest", {
176
+ method,
177
+ estimate: est,
178
+ margin,
179
+ alpha,
180
+ statistic: [zLower, zUpper],
181
+ statisticName: "z",
182
+ pValues,
183
+ pValue,
184
+ result: pValues[0] < alpha && pValues[1] < alpha ? "rejected" : "not rejected",
185
+ confInt,
186
+ confLevel,
187
+ warnings: [],
188
+ });
189
+ }
@@ -24,6 +24,13 @@ export interface FisherTestOptions {
24
24
  simulatePValue?: boolean;
25
25
  /** Number of replicates for `simulatePValue`. Default `2000`. */
26
26
  B?: number;
27
+ /**
28
+ * The mid-p version of the test of a 2 x 2 table (as `exact2x2::fisher.exact(x, midp = TRUE)`): the p-value and the
29
+ * confidence limits from the mid-p tails P(X < x) + P(X = x)/2 and P(X > x) + P(X = x)/2 of the (1, 1) cell; the
30
+ * two-sided p-value is twice the smaller tail (the central test) and the estimate stays the conditional MLE. An error
31
+ * for larger tables. Default `false`.
32
+ */
33
+ midp?: boolean;
27
34
  }
28
35
  /**
29
36
  * Result of {@link fisherTest}. Has no `statistic` or `statisticName`, because R's
@@ -49,6 +56,11 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
49
56
  * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
50
57
  * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
51
58
  *
59
+ * With `midp: true` (2 x 2 only), the mid-p version of exact2x2's `fisher.exact()`: the p-value and the interval come
60
+ * from the mid-p tails (two-sided: the central test, twice the smaller tail, at most 1), the limits are the roots of
61
+ * the mid-p tails to the precision of the doubles (exact2x2's search stops up to 1% from them), and `method` is
62
+ * `"Central Fisher's Exact Test (mid-p version)"` or `"One-sided Fisher's Exact Test (mid-p version)"`.
63
+ *
52
64
  * Not implemented: R's `hybrid` option.
53
65
  *
54
66
  * @param x Contingency table as an array of rows (at least 2 x 2).
@@ -61,8 +73,45 @@ export interface FisherTestResult extends Omit<HTest, "statistic" | "statisticNa
61
73
  * r.pValue; // 0.4857142857142857
62
74
  * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
63
75
  * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
76
+ * const m = fisherTest([[3, 1], [1, 3]], { midp: true });
77
+ * m.pValue; // 0.2571428571428571
78
+ * m.confInt; // [0.31005488171907974, 308.5567715811547] (exact2x2: 0.3100451, 311.4363)
64
79
  * ```
65
80
  *
66
81
  * @category Hypothesis tests
67
82
  */
68
83
  export declare function fisherTest(x: readonly Counts[], options?: FisherTestOptions): FisherTestResult;
84
+ /**
85
+ * Fisher's noncentral hypergeometric distribution of the (1, 1) cell of a 2 x 2 table with margins fixed:
86
+ * P(X = i; psi) proportional to dhyper(i; m, n, k) psi^i on lo..hi
87
+ */
88
+ export declare class OddsRatioDistribution {
89
+ private readonly m;
90
+ private readonly n;
91
+ private readonly k;
92
+ readonly lo: number;
93
+ readonly hi: number;
94
+ /** log dhyper(i; m, n, k) for i = lo..hi */
95
+ private readonly logCentral;
96
+ constructor(m: number, n: number, k: number);
97
+ /** Normalised density on lo..hi for 0 < psi < Infinity */
98
+ density(psi: number): Float64Array;
99
+ /** E[X; psi] */
100
+ mean(psi: number): number;
101
+ /** P(X <= q; psi), or P(X >= q; psi) when upper */
102
+ tail(q: number, psi: number, upper: boolean): number;
103
+ /** The mid-p tail P(X < q; psi) + P(X = q; psi)/2, or P(X > q; psi) + P(X = q; psi)/2 when upper (lo <= q <= hi) */
104
+ midTail(q: number, psi: number, upper: boolean): number;
105
+ }
106
+ /**
107
+ * The two-sided p-value of the count x at the odds ratio psi (0 < psi < Infinity): the sum of the probabilities at
108
+ * most P(X = x) (1 + 1e-7), as R
109
+ */
110
+ export declare function twoSidedPValue(dist: OddsRatioDistribution, x: number, psi: number): number;
111
+ /**
112
+ * Fisher's two-sided p-value of the 2 x 2 table with the (1, 1) cell x and the margins m (column 1), n (column 2) and
113
+ * k (row 1), at the odds ratio 1, without the array of the support: the hypergeometric density is unimodal, so the
114
+ * values at most P(X = x) (1 + 1e-7) are the two tails below and above two cut points, found by bisection and summed
115
+ * by phyper. For supports beyond what twoSidedPValue allocates (oddsRatio's p-value of tables with counts of 1e9)
116
+ */
117
+ export declare function twoSidedPValueUnimodal(x: number, m: number, n: number, k: number): number;
@@ -16,6 +16,12 @@
16
16
  // - Counts are made integer by rounding half to even, with R's warning "'x' has been rounded to integer: " and the text
17
17
  // of all.equal(original, rounded) (allEqualMessage)
18
18
  // The same distribution and root conventions are used for the exact Mantel-Haenszel test (src/htest/core/mantelhaen.ts).
19
+ // - midp (exact2x2's fisher.exact(midp = TRUE), from oracle/contingency-behaviour.md section 3; the mid-p idea is
20
+ // Lancaster 1961, JASA 56, 223-234): the tails P(X < x) + P(X = x)/2 and P(X > x) + P(X = x)/2 replace the ordinary
21
+ // ones in the p-value and the limits; two-sided is the central test, min(1, 2 min(tails)). At psi = 0 and Infinity
22
+ // the distribution is a point mass at the end of the support (a tail of 1/2 there), so a limit at an end of the
23
+ // support is 0 or Infinity, and where x is at an end and alpha >= 1/2 the other limit is that end too. The roots are
24
+ // those of the tails (exact2x2's uniroot stops up to 1% from them; 1/eps where the limit is large)
19
25
  //
20
26
  // rxc tables: the probabilities of tables with fixed margins (multivariate hypergeometric) are
21
27
  // traversed via a network that fixes one column at a time (Mehta & Patel 1983, JASA 78, 427-434),
@@ -45,7 +51,7 @@ import { matchAlternative } from "./types.js";
45
51
  import { maxOf, minOf } from "../internal/extremes.js";
46
52
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
47
53
  import { checkOptions } from "../internal/checkOptions.js";
48
- const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B"];
54
+ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulatePValue", "B", "midp"];
49
55
  /**
50
56
  * Fisher's exact test for count data. Equivalent to R's `fisher.test()`.
51
57
  *
@@ -60,6 +66,11 @@ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulate
60
66
  * With `simulatePValue: true`, the p-value of a table larger than 2 x 2 is computed from `B` random tables with the
61
67
  * observed margins, drawn from the random stream of {@link setSeed} exactly as in R.
62
68
  *
69
+ * With `midp: true` (2 x 2 only), the mid-p version of exact2x2's `fisher.exact()`: the p-value and the interval come
70
+ * from the mid-p tails (two-sided: the central test, twice the smaller tail, at most 1), the limits are the roots of
71
+ * the mid-p tails to the precision of the doubles (exact2x2's search stops up to 1% from them), and `method` is
72
+ * `"Central Fisher's Exact Test (mid-p version)"` or `"One-sided Fisher's Exact Test (mid-p version)"`.
73
+ *
63
74
  * Not implemented: R's `hybrid` option.
64
75
  *
65
76
  * @param x Contingency table as an array of rows (at least 2 x 2).
@@ -72,6 +83,9 @@ const FISHER_TEST_KEYS = ["alternative", "confInt", "confLevel", "or", "simulate
72
83
  * r.pValue; // 0.4857142857142857
73
84
  * r.estimate; // 6.408319658199675 (conditional MLE of the odds ratio; R: 6.408309)
74
85
  * r.confInt; // [0.2117355954465785, 626.2435305888127] (R: 0.2117329, 621.93)
86
+ * const m = fisherTest([[3, 1], [1, 3]], { midp: true });
87
+ * m.pValue; // 0.2571428571428571
88
+ * m.confInt; // [0.31005488171907974, 308.5567715811547] (exact2x2: 0.3100451, 311.4363)
75
89
  * ```
76
90
  *
77
91
  * @category Hypothesis tests
@@ -99,6 +113,10 @@ export function fisherTest(x, options = {}) {
99
113
  if (rounding !== null)
100
114
  warnings.push(`'x' has been rounded to integer: ${rounding}`);
101
115
  const method = "Fisher's Exact Test for Count Data";
116
+ if (options.midp !== undefined && typeof options.midp !== "boolean")
117
+ throw new TypeError("'midp' must be true or false");
118
+ if ((options.midp ?? false) && !(nr === 2 && nc === 2))
119
+ throw new RangeError("the mid-p version ('midp') needs a 2 x 2 table");
102
120
  if (nr === 2 && nc === 2)
103
121
  return reported("fisherTest", { ...fisher2x2(t, options, method), warnings });
104
122
  // For rxc, alternative etc. are not validated and are returned as given (as in R)
@@ -205,7 +223,7 @@ function accurateSum(v, from, to) {
205
223
  * Fisher's noncentral hypergeometric distribution of the (1, 1) cell of a 2 x 2 table with margins fixed:
206
224
  * P(X = i; psi) proportional to dhyper(i; m, n, k) psi^i on lo..hi
207
225
  */
208
- class OddsRatioDistribution {
226
+ export class OddsRatioDistribution {
209
227
  m;
210
228
  n;
211
229
  k;
@@ -285,6 +303,94 @@ class OddsRatioDistribution {
285
303
  const j = q - this.lo;
286
304
  return upper ? accurateSum(d, j, d.length - 1) : accurateSum(d, 0, j);
287
305
  }
306
+ /** The mid-p tail P(X < q; psi) + P(X = q; psi)/2, or P(X > q; psi) + P(X = q; psi)/2 when upper (lo <= q <= hi) */
307
+ midTail(q, psi, upper) {
308
+ if (psi === 1) {
309
+ const half = 0.5 * dhyper1(q, this.m, this.n, this.k, false);
310
+ return (upper ? phyper1(q, this.m, this.n, this.k, false, false) : phyper1(q - 1, this.m, this.n, this.k, true, false)) + half;
311
+ }
312
+ if (psi === 0 || psi === Infinity) {
313
+ const at = psi === 0 ? this.lo : this.hi;
314
+ if (q === at)
315
+ return 0.5;
316
+ return (upper ? q < at : q > at) ? 1 : 0;
317
+ }
318
+ const d = this.density(psi);
319
+ const j = q - this.lo;
320
+ return (upper ? accurateSum(d, j + 1, d.length - 1) : accurateSum(d, 0, j - 1)) + 0.5 * d[j];
321
+ }
322
+ }
323
+ /**
324
+ * The two-sided p-value of the count x at the odds ratio psi (0 < psi < Infinity): the sum of the probabilities at
325
+ * most P(X = x) (1 + 1e-7), as R
326
+ */
327
+ export function twoSidedPValue(dist, x, psi) {
328
+ const dens = dist.density(psi);
329
+ const cut = dens[x - dist.lo] * SLACK;
330
+ let acc = [0, 0];
331
+ for (const v of dens)
332
+ if (v <= cut)
333
+ acc = ddAdd(acc, [v, 0]);
334
+ return acc[0];
335
+ }
336
+ /**
337
+ * Fisher's two-sided p-value of the 2 x 2 table with the (1, 1) cell x and the margins m (column 1), n (column 2) and
338
+ * k (row 1), at the odds ratio 1, without the array of the support: the hypergeometric density is unimodal, so the
339
+ * values at most P(X = x) (1 + 1e-7) are the two tails below and above two cut points, found by bisection and summed
340
+ * by phyper. For supports beyond what twoSidedPValue allocates (oddsRatio's p-value of tables with counts of 1e9)
341
+ */
342
+ export function twoSidedPValueUnimodal(x, m, n, k) {
343
+ const lo = Math.max(0, k - n);
344
+ const hi = Math.min(k, m);
345
+ // (on the log scale: P(X = x) underflows far in the tails, and a cut of 0 would take in every value that underflows)
346
+ const d = (i) => dhyper1(i, m, n, k, true);
347
+ const cut = d(x) + Math.log(SLACK);
348
+ // a mode (the density increases up to it and decreases after; the formula may be one off where it rounds)
349
+ let mode = Math.min(hi, Math.max(lo, Math.floor(((k + 1) * (m + 1)) / (m + n + 2))));
350
+ while (mode < hi && d(mode + 1) > d(mode))
351
+ mode++;
352
+ while (mode > lo && d(mode - 1) > d(mode))
353
+ mode--;
354
+ // the last i in [from, to] with d(i) <= cut, d rising over [from, to] and d(from) <= cut
355
+ const risingLast = (from, to) => {
356
+ let a = from;
357
+ let b = to + 1;
358
+ while (b - a > 1) {
359
+ const mid = a + Math.floor((b - a) / 2);
360
+ if (d(mid) <= cut)
361
+ a = mid;
362
+ else
363
+ b = mid;
364
+ }
365
+ return a;
366
+ };
367
+ // the first i in [from, to] with d(i) <= cut, d falling over [from, to]; to + 1 if there is none
368
+ const fallingFirst = (from, to) => {
369
+ let a = from - 1;
370
+ let b = to + 1;
371
+ while (b - a > 1) {
372
+ const mid = a + Math.floor((b - a) / 2);
373
+ if (d(mid) <= cut)
374
+ b = mid;
375
+ else
376
+ a = mid;
377
+ }
378
+ return b;
379
+ };
380
+ // the p-value is P(X <= below) + P(X >= above)
381
+ let below;
382
+ let above;
383
+ if (x <= mode) {
384
+ below = risingLast(x, mode);
385
+ above = fallingFirst(mode + 1, hi);
386
+ }
387
+ else {
388
+ above = fallingFirst(mode, x);
389
+ below = mode - 1 < lo || d(lo) > cut ? lo - 1 : risingLast(lo, mode - 1);
390
+ }
391
+ const lower = below < lo ? 0 : phyper1(below, m, n, k, true, false);
392
+ const upper = above > hi ? 0 : phyper1(above - 1, m, n, k, false, false);
393
+ return lower + upper;
288
394
  }
289
395
  /** Root of f, monotone in the odds ratio psi, to the precision of the doubles (on the log scale, see logScaleRoot) */
290
396
  function oddsRatioRoot(f, belowOne) {
@@ -307,8 +413,19 @@ function fisher2x2(t, options, method) {
307
413
  }
308
414
  const dist = new OddsRatioDistribution(a + c, b + d, a + b);
309
415
  const { lo, hi } = dist;
416
+ const midp = options.midp ?? false;
310
417
  let pValue;
311
- if (alternative === "less")
418
+ if (midp) {
419
+ // the central test: twice the smaller mid-p tail (exact2x2 supports no other two-sided mid-p test)
420
+ if (alternative === "less")
421
+ pValue = dist.midTail(x, or, false);
422
+ else if (alternative === "greater")
423
+ pValue = dist.midTail(x, or, true);
424
+ else
425
+ pValue = Math.min(1, 2 * Math.min(dist.midTail(x, or, false), dist.midTail(x, or, true)));
426
+ method = alternative === "two.sided" ? "Central Fisher's Exact Test (mid-p version)" : "One-sided Fisher's Exact Test (mid-p version)";
427
+ }
428
+ else if (alternative === "less")
312
429
  pValue = dist.tail(x, or, false);
313
430
  else if (alternative === "greater")
314
431
  pValue = dist.tail(x, or, true);
@@ -316,15 +433,8 @@ function fisher2x2(t, options, method) {
316
433
  pValue = x === lo ? 1 : 0;
317
434
  else if (or === Infinity)
318
435
  pValue = x === hi ? 1 : 0;
319
- else {
320
- const dens = dist.density(or);
321
- const cut = dens[x - lo] * SLACK;
322
- let acc = [0, 0];
323
- for (const v of dens)
324
- if (v <= cut)
325
- acc = ddAdd(acc, [v, 0]);
326
- pValue = acc[0];
327
- }
436
+ else
437
+ pValue = twoSidedPValue(dist, x, or);
328
438
  let estimate;
329
439
  if (x === lo)
330
440
  estimate = 0;
@@ -346,16 +456,29 @@ function fisher2x2(t, options, method) {
346
456
  };
347
457
  if (!(options.confInt ?? true))
348
458
  return result;
349
- // P(X <= x; psi) decreases and P(X >= x; psi) increases in psi
459
+ // P(X <= x; psi) decreases and P(X >= x; psi) increases in psi, and so do the mid-p tails. At the ends of the support
460
+ // the mid-p tail is P(X = x; psi)/2 <= 1/2 (exact2x2's conventions: a limit of 0 or Infinity where alpha >= 1/2)
350
461
  const upperLimit = (level) => {
351
462
  if (x === hi)
352
463
  return Infinity;
464
+ if (midp) {
465
+ if (x === lo && level >= 0.5)
466
+ return 0;
467
+ const p1 = dist.midTail(x, 1, false);
468
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.midTail(x, psi, false) - level, p1 < level);
469
+ }
353
470
  const p1 = dist.tail(x, 1, false);
354
471
  return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, false) - level, p1 < level);
355
472
  };
356
473
  const lowerLimit = (level) => {
357
474
  if (x === lo)
358
475
  return 0;
476
+ if (midp) {
477
+ if (x === hi && level >= 0.5)
478
+ return Infinity;
479
+ const p1 = dist.midTail(x, 1, true);
480
+ return p1 === level ? 1 : oddsRatioRoot((psi) => dist.midTail(x, psi, true) - level, p1 > level);
481
+ }
359
482
  const p1 = dist.tail(x, 1, true);
360
483
  return p1 === level ? 1 : oddsRatioRoot((psi) => dist.tail(x, psi, true) - level, p1 > level);
361
484
  };