@numero-uno-jpn/rstats 1.1.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 (59) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.ja.md +11 -10
  3. package/README.md +11 -10
  4. package/dist/chunks/{chunk-X4J6UJHN.js → chunk-2NNBUYHJ.js} +2 -2
  5. package/dist/chunks/{chunk-Y4YWLSWU.js → chunk-47IIPUFN.js} +2 -2
  6. package/dist/chunks/{chunk-7KJ24LYK.js → chunk-4AOTAT3O.js} +2 -2
  7. package/dist/chunks/{chunk-GRUQRNX7.js → chunk-5SGTWSCB.js} +3 -3
  8. package/dist/chunks/{chunk-YN5MLKDL.js → chunk-6FZHTD5G.js} +2 -2
  9. package/dist/chunks/{chunk-N5BDSMXS.js → chunk-73LNRWU3.js} +1 -1
  10. package/dist/chunks/{chunk-7IJCUSA5.js → chunk-7INBXTVV.js} +2 -2
  11. package/dist/chunks/chunk-7WG7X2UI.js +2 -0
  12. package/dist/chunks/{chunk-DTJG2IL2.js → chunk-A66M3ZEA.js} +2 -2
  13. package/dist/chunks/{chunk-EJYCDE4Z.js → chunk-BI7NYJWP.js} +1 -1
  14. package/dist/chunks/{chunk-JNWWLNE3.js → chunk-BKV3FINA.js} +2 -2
  15. package/dist/chunks/{chunk-UMLMY4XS.js → chunk-CQB4BJBR.js} +2 -2
  16. package/dist/chunks/{chunk-DR4GQ7PW.js → chunk-EEU7D4RU.js} +1 -1
  17. package/dist/chunks/{chunk-Z2HGLFZN.js → chunk-F3EQLL4F.js} +2 -2
  18. package/dist/chunks/{chunk-4VRMAYPY.js → chunk-HBHMEPGY.js} +2 -2
  19. package/dist/chunks/{chunk-GJEKNJP7.js → chunk-IAWXF73N.js} +2 -2
  20. package/dist/chunks/{chunk-OG7UORIX.js → chunk-IMPRIQE5.js} +1 -1
  21. package/dist/chunks/{chunk-GYGQUYEP.js → chunk-JWBSEL3V.js} +2 -2
  22. package/dist/chunks/{chunk-U7BRXOUS.js → chunk-L23RSC2N.js} +2 -2
  23. package/dist/chunks/{chunk-QUTJEYDX.js → chunk-NSU6U3ET.js} +2 -2
  24. package/dist/chunks/{chunk-4KCSBTR5.js → chunk-ORE5ZRCY.js} +2 -2
  25. package/dist/chunks/{chunk-GGJA3JRO.js → chunk-RRO4LMCB.js} +2 -2
  26. package/dist/chunks/{chunk-HZLSNJQM.js → chunk-T5DRIITM.js} +2 -2
  27. package/dist/chunks/{chunk-HUWOSLKE.js → chunk-TNETWBF5.js} +1 -1
  28. package/dist/chunks/{chunk-HRA7PCQT.js → chunk-VERBXW6E.js} +2 -2
  29. package/dist/descriptive.js +2 -2
  30. package/dist/distributions.js +2 -2
  31. package/dist/entries/tests.d.ts +5 -0
  32. package/dist/entries/tests.js +5 -0
  33. package/dist/htest/binomCI.d.ts +116 -0
  34. package/dist/htest/binomCI.js +252 -0
  35. package/dist/htest/boschlooTest.d.ts +65 -0
  36. package/dist/htest/boschlooTest.js +394 -0
  37. package/dist/htest/chisqTest.d.ts +19 -0
  38. package/dist/htest/chisqTest.js +30 -2
  39. package/dist/htest/core/twoProportions.d.ts +48 -0
  40. package/dist/htest/core/twoProportions.js +476 -0
  41. package/dist/htest/equivalence.d.ts +172 -0
  42. package/dist/htest/equivalence.js +189 -0
  43. package/dist/htest/fisherTest.d.ts +49 -0
  44. package/dist/htest/fisherTest.js +136 -13
  45. package/dist/htest/tableTests.d.ts +216 -0
  46. package/dist/htest/tableTests.js +650 -0
  47. package/dist/htest/twoByTwo.d.ts +203 -0
  48. package/dist/htest/twoByTwo.js +385 -0
  49. package/dist/linalg.js +2 -2
  50. package/dist/mixed.js +2 -2
  51. package/dist/numerics.js +2 -2
  52. package/dist/rstats.js +16 -16
  53. package/dist/special/igam.js +140 -23
  54. package/dist/special/loader.js +8 -0
  55. package/dist/special.js +2 -2
  56. package/dist/tests.js +13 -13
  57. package/llms.txt +8 -0
  58. package/package.json +1 -1
  59. package/dist/chunks/chunk-NDTJ23A6.js +0 -2
@@ -0,0 +1,203 @@
1
+ import { type CISides, type IntervalLevel, type ProportionCIResult } from "./binomCI.js";
2
+ import type { Counts } from "./types.js";
3
+ /**
4
+ * Methods of {@link binomDiffCI}.
5
+ *
6
+ * @category Hypothesis tests
7
+ */
8
+ export type BinomDiffCIMethod = "ac" | "wald" | "score" | "mn" | "mee";
9
+ /**
10
+ * Options for {@link binomDiffCI}.
11
+ *
12
+ * @category Hypothesis tests
13
+ */
14
+ export interface BinomDiffCIOptions {
15
+ /** `"ac"` (Agresti-Caffo, the default), `"wald"`, `"score"` (Newcombe's hybrid score interval), `"mn"`
16
+ * (Miettinen-Nurminen) or `"mee"` (Farrington-Manning / Mee). Unambiguous abbreviations are accepted. */
17
+ method?: BinomDiffCIMethod | (string & {});
18
+ /** Confidence level, in (0, 1). Default `0.95`. */
19
+ confLevel?: number;
20
+ /** `"two.sided"` (default), `"left"` (lower limit only) or `"right"` (upper limit only); abbreviations accepted. */
21
+ sides?: CISides | (string & {});
22
+ }
23
+ /**
24
+ * Result of {@link binomDiffCI}.
25
+ *
26
+ * @category Hypothesis tests
27
+ */
28
+ export type BinomDiffCIResult = ProportionCIResult<BinomDiffCIMethod>;
29
+ /**
30
+ * The two-sided limits of binomDiffCI for checked counts at the level lv (also used by binomDiffEquivalenceTest, with
31
+ * the level built from its alpha)
32
+ */
33
+ export declare function binomDiffLimits(a1: number, m1: number, a2: number, m2: number, method: BinomDiffCIMethod, lv: IntervalLevel): [number, number];
34
+ /**
35
+ * Confidence interval for the difference p1 - p2 of two independent proportions x1/n1 and x2/n2. Equivalent to
36
+ * `DescTools::BinomDiffCI()` in R.
37
+ *
38
+ * Methods (`method`): `"ac"` (Agresti-Caffo, the default as in DescTools: the Wald interval with one success and one
39
+ * failure added to each group), `"wald"`, `"score"` (Newcombe's hybrid score interval, his method 10), `"mn"`
40
+ * (Miettinen-Nurminen score interval) and `"mee"` (Farrington-Manning / Mee: the same without the factor N/(N - 1);
41
+ * epiR's score interval of the attributable risk). With `sides: "left"` or `"right"` only the lower or the upper limit
42
+ * is kept, at the one-sided level `confLevel`, and the other end is 1 or -1. The `"mn"` and `"mee"` limits are the
43
+ * roots of the score statistic to the precision of the doubles (DescTools stops at about 1e-7 and 1e-4).
44
+ *
45
+ * @param x1 Successes in group 1.
46
+ * @param n1 Trials in group 1.
47
+ * @param x2 Successes in group 2.
48
+ * @param n2 Trials in group 2.
49
+ * @param options See {@link BinomDiffCIOptions}.
50
+ * @returns The estimate p1 - p2 and the interval; see {@link BinomDiffCIResult}.
51
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
52
+ * one-sided), or an unknown method or sides.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * binomDiffCI(56, 70, 48, 80).confInt; // [0.05245292663805373, 0.3357584554757674]
57
+ * binomDiffCI(56, 70, 48, 80, { method: "mn" }).confInt; // [0.05282971324584462, 0.33817294001586834]
58
+ * ```
59
+ *
60
+ * @category Hypothesis tests
61
+ */
62
+ export declare function binomDiffCI(x1: number, n1: number, x2: number, n2: number, options?: BinomDiffCIOptions): BinomDiffCIResult;
63
+ /**
64
+ * Methods of {@link binomRatioCI}.
65
+ *
66
+ * @category Hypothesis tests
67
+ */
68
+ export type BinomRatioCIMethod = "katz.log" | "koopman";
69
+ /**
70
+ * Options for {@link binomRatioCI}.
71
+ *
72
+ * @category Hypothesis tests
73
+ */
74
+ export interface BinomRatioCIOptions {
75
+ /** `"katz.log"` (the default) or `"koopman"` (Koopman's score interval). Unambiguous abbreviations are accepted. */
76
+ method?: BinomRatioCIMethod | (string & {});
77
+ /** Confidence level, in (0, 1). Default `0.95`. */
78
+ confLevel?: number;
79
+ /** `"two.sided"` (default), `"left"` (lower limit only) or `"right"` (upper limit only); abbreviations accepted. */
80
+ sides?: CISides | (string & {});
81
+ }
82
+ /**
83
+ * Result of {@link binomRatioCI}.
84
+ *
85
+ * @category Hypothesis tests
86
+ */
87
+ export type BinomRatioCIResult = ProportionCIResult<BinomRatioCIMethod>;
88
+ /**
89
+ * Confidence interval for the ratio p1/p2 of two independent proportions x1/n1 and x2/n2 (the risk ratio). Equivalent
90
+ * to `DescTools::BinomRatioCI()` in R.
91
+ *
92
+ * Methods (`method`): `"katz.log"` (the default; Katz's log interval, with 0.5 put for a zero count, and n - 0.5 for
93
+ * both counts when both groups are all successes, as DescTools) and `"koopman"` (Koopman's score interval, also epiR's
94
+ * score interval of the risk ratio), whose limits are the roots of Koopman's statistic to the precision of the
95
+ * doubles. With `sides: "left"` or `"right"` only the lower or the upper limit is kept, at the one-sided level
96
+ * `confLevel`, and the other end is Infinity or 0 (DescTools computes the one-sided level but keeps both limits).
97
+ * With x1 = x2 = 0 the estimate is 0 and the interval [0, Infinity], as DescTools.
98
+ *
99
+ * @param x1 Successes in group 1.
100
+ * @param n1 Trials in group 1.
101
+ * @param x2 Successes in group 2.
102
+ * @param n2 Trials in group 2.
103
+ * @param options See {@link BinomRatioCIOptions}.
104
+ * @returns The estimate p1/p2 and the interval; see {@link BinomRatioCIResult}.
105
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
106
+ * one-sided), or an unknown method or sides.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * binomRatioCI(56, 70, 48, 80).confInt; // [1.076626422763193, 1.6512485112663868]
111
+ * binomRatioCI(56, 70, 48, 80, { method: "koopman" }).confInt; // [1.0798215063618983, 1.6708055780191118]
112
+ * ```
113
+ *
114
+ * @category Hypothesis tests
115
+ */
116
+ export declare function binomRatioCI(x1: number, n1: number, x2: number, n2: number, options?: BinomRatioCIOptions): BinomRatioCIResult;
117
+ /**
118
+ * Methods of {@link oddsRatio}.
119
+ *
120
+ * @category Hypothesis tests
121
+ */
122
+ export type OddsRatioMethod = "midp" | "fisher" | "wald" | "score";
123
+ /**
124
+ * Options for {@link oddsRatio}.
125
+ *
126
+ * @category Hypothesis tests
127
+ */
128
+ export interface OddsRatioOptions {
129
+ /** `"midp"` (the default: median-unbiased estimate and mid-p exact interval), `"fisher"` (conditional MLE and
130
+ * Fisher's exact interval), `"wald"` or `"score"` (epiR's score interval). Unambiguous abbreviations accepted. */
131
+ method?: OddsRatioMethod | (string & {});
132
+ /** Confidence level, in (0, 1). Default `0.95`. */
133
+ confLevel?: number;
134
+ }
135
+ /**
136
+ * Result of {@link oddsRatio}.
137
+ *
138
+ * @category Hypothesis tests
139
+ */
140
+ export interface OddsRatioResult {
141
+ /** The odds ratio: the median-unbiased estimate (`"midp"`), the conditional MLE (`"fisher"`) or the sample odds
142
+ * ratio x11 x22 / (x12 x21) (`"wald"`, `"score"`). */
143
+ estimate: number;
144
+ /** `[lower, upper]`. */
145
+ confInt: [number, number];
146
+ /** The confidence level. */
147
+ confLevel: number;
148
+ /** epitools' description of the method (e.g. `"median-unbiased estimate & mid-p exact CI"`). */
149
+ method: string;
150
+ /** epitools' p-values of independence, the same for every method. */
151
+ pValue: {
152
+ /** The two-sided mid-p exact p-value: twice the smaller one-sided mid-p value P(X < a) + P(X = a)/2. */
153
+ midp: number;
154
+ /** Fisher's exact two-sided p-value (as {@link fisherTest}). */
155
+ fisher: number;
156
+ /** Pearson's chi-squared test without continuity correction. */
157
+ chiSquare: number;
158
+ };
159
+ /** R's warnings ("Chi-squared approximation may be incorrect" where an expected count is below 5). */
160
+ warnings: string[];
161
+ }
162
+ /**
163
+ * Odds ratio of a 2 x 2 table with its confidence interval and three p-values of independence. Equivalent to
164
+ * `epitools::oddsratio()` in R.
165
+ *
166
+ * The table is in epitools' orientation: rows are the exposure (row 1 the reference level) and columns the outcome
167
+ * (column 1 without the disease); the odds ratio x11 x22 / (x12 x21) is the same for the transposed table.
168
+ *
169
+ * Methods (`method`): `"midp"` (the default, as epitools: the median-unbiased estimate and the mid-p exact interval
170
+ * from Fisher's noncentral hypergeometric distribution of x11 given the margins), `"fisher"` (the conditional MLE and
171
+ * the exact interval of {@link fisherTest}), `"wald"` (the sample odds ratio and Woolf's interval on the log scale;
172
+ * as epitools, no zero-cell correction: a zero cell gives an estimate of 0 or Infinity and NaN for the limit that is
173
+ * not defined) and `"score"` (the sample odds ratio and the score interval of epiR's `epi.2by2`, Miettinen-Nurminen
174
+ * without the factor N/(N - 1)). The mid-p and score limits are the roots of their equations to the precision of the
175
+ * doubles (epitools solves with uniroot's tolerance on [0, 1000] and fails beyond and for zero cells; epiR steps by
176
+ * 0.1%). With a zero cell the mid-p estimate and limits follow the conventions of exact2x2: 0 or Infinity at the end
177
+ * of the support.
178
+ *
179
+ * `pValue` has epitools' three p-values: the two-sided mid-p (twice the smaller one-sided mid-p value), Fisher's
180
+ * exact test and Pearson's chi-squared without continuity correction (with R's warning "Chi-squared approximation may
181
+ * be incorrect" where an expected count is below 5).
182
+ *
183
+ * @param table A 2 x 2 table of counts as an array of rows.
184
+ * @param options See {@link OddsRatioOptions}.
185
+ * @returns See {@link OddsRatioResult}.
186
+ * Limits: the exact methods (`"midp"`, `"fisher"`) need the support of x11 given the margins (min(x11, x22) +
187
+ * min(x12, x21) + 1 values) to be at most 2^23 (about 6 s), and `"fisher"` counts of at most 2^31 - 1 (as
188
+ * `fisherTest`); the p-values of every method need phyper within its 2^26 terms (counts up to about 1e12).
189
+ *
190
+ * @throws TypeError if the table is not 2 x 2; RangeError for negative or non-integer counts, a table of zeros, a
191
+ * level outside (0, 1), an unknown method, or a table beyond the limits above.
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * const r = oddsRatio([[56, 14], [48, 32]]);
196
+ * r.estimate; // 2.6364237331551914
197
+ * r.confInt; // [1.276159154292712, 5.670866460839431]
198
+ * r.pValue; // { midp: 0.008449442679452648, fisher: 0.012521129749209155, chiSquare: 0.00804508136819659 }
199
+ * ```
200
+ *
201
+ * @category Hypothesis tests
202
+ */
203
+ export declare function oddsRatio(table: readonly Counts[], options?: OddsRatioOptions): OddsRatioResult;
@@ -0,0 +1,385 @@
1
+ // Two independent binomial proportions and the 2 x 2 table: confidence intervals for the difference (DescTools'
2
+ // BinomDiffCI), the ratio (DescTools' BinomRatioCI) and the odds ratio (epitools' oddsratio, with epiR's score
3
+ // interval as an extra method).
4
+ //
5
+ // Written for rStats.js from the published methods and the packages' documented behaviour (no R or package code):
6
+ // - Difference: Wald; Agresti and Caffo (The American Statistician 54, 2000: one success and one failure added to each
7
+ // group); Newcombe's hybrid score interval (Statistics in Medicine 17, 1998, method 10: the Wilson limits of both
8
+ // proportions combined); Miettinen and Nurminen (Statistics in Medicine 4, 1985) and Farrington-Manning / Mee
9
+ // (Statistics in Medicine 9, 1990; Biometrics 40, 1984) score intervals, whose limits are the roots of the score
10
+ // statistic (src/htest/core/twoProportions.ts). DescTools finds the mn limits by a bisection stopped at 1e-7 and the
11
+ // mee limits with uniroot's tolerance 1.22e-4; the roots here are to the precision of the doubles.
12
+ // - Ratio: Katz et al. (Biometrics 34, 1978) log interval, with 0.5 put for a zero count (and n - 0.5 for both counts
13
+ // when both are full), as DescTools; Koopman's score interval (Biometrics 40, 1984) as the roots of his statistic.
14
+ // - Odds ratio: Wald (Woolf); the conditional MLE and Fisher's exact interval (fisherTest); the median-unbiased
15
+ // estimate and the mid-p exact interval (Rothman, Greenland and Lash, Modern Epidemiology, 2008, ch. 14): with X
16
+ // the (1, 1) cell under Fisher's noncentral hypergeometric distribution given the margins, the estimate solves
17
+ // P(X <= a) = P(X >= a), the lower limit P(X > a) + 1/2 P(X = a) = alpha/2 and the upper P(X < a) + 1/2 P(X = a) =
18
+ // alpha/2, solved on the log scale to the precision of the doubles (epitools uses uniroot on [0, 1000] with the
19
+ // tolerance 1.22e-4 and fails beyond); the score interval of the odds ratio (Miettinen and Nurminen without
20
+ // N/(N - 1), as epiR). The p-values are epitools': the doubled one-sided mid-p, Fisher's two-sided p and Pearson's
21
+ // chi-squared without continuity correction.
22
+ import { dhyper1, phyper1 } from "../distributions/hypergeometric.js";
23
+ import { pgamma1 } from "../distributions/gamma.js";
24
+ import { logScaleRoot } from "../internal/uniroot.js";
25
+ import { reported, unreported } from "../internal/warnings.js";
26
+ import { ddAdd } from "../special/dd.js";
27
+ import { checkCount, checkTrials, intervalLevel, wilsonLimits } from "./binomCI.js";
28
+ import { diffScoreLimits, oddsRatioScoreLimits, ratioScoreLimits } from "./core/twoProportions.js";
29
+ import { fisherTest, OddsRatioDistribution, twoSidedPValue, twoSidedPValueUnimodal } from "./fisherTest.js";
30
+ import { matchChoice } from "./power.js";
31
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
32
+ import { checkOptions } from "../internal/checkOptions.js";
33
+ const BINOM_DIFF_CI_KEYS = ["method", "confLevel", "sides"];
34
+ const BINOM_RATIO_CI_KEYS = ["method", "confLevel", "sides"];
35
+ const ODDS_RATIO_KEYS = ["method", "confLevel"];
36
+ const DIFF_METHODS = ["ac", "wald", "score", "mn", "mee"];
37
+ /**
38
+ * The two-sided limits of binomDiffCI for checked counts at the level lv (also used by binomDiffEquivalenceTest, with
39
+ * the level built from its alpha)
40
+ */
41
+ export function binomDiffLimits(a1, m1, a2, m2, method, lv) {
42
+ const { kappa } = lv;
43
+ const p1 = a1 / m1;
44
+ const p2 = a2 / m2;
45
+ const est = p1 - p2;
46
+ let lower;
47
+ let upper;
48
+ switch (method) {
49
+ case "wald": {
50
+ const half = kappa * Math.sqrt((p1 * (1 - p1)) / m1 + (p2 * (1 - p2)) / m2);
51
+ [lower, upper] = [Math.max(-1, est - half), Math.min(1, est + half)];
52
+ break;
53
+ }
54
+ case "ac": {
55
+ const q1 = (a1 + 1) / (m1 + 2);
56
+ const q2 = (a2 + 1) / (m2 + 2);
57
+ const centre = q1 - q2;
58
+ const half = kappa * Math.sqrt((q1 * (1 - q1)) / (m1 + 2) + (q2 * (1 - q2)) / (m2 + 2));
59
+ [lower, upper] = [Math.max(-1, centre - half), Math.min(1, centre + half)];
60
+ break;
61
+ }
62
+ case "score": {
63
+ const [l1, u1] = wilsonLimits(a1, m1, kappa);
64
+ const [l2, u2] = wilsonLimits(a2, m2, kappa);
65
+ lower = est - kappa * Math.sqrt((l1 * (1 - l1)) / m1 + (u2 * (1 - u2)) / m2);
66
+ upper = est + kappa * Math.sqrt((u1 * (1 - u1)) / m1 + (l2 * (1 - l2)) / m2);
67
+ break;
68
+ }
69
+ case "mn":
70
+ case "mee":
71
+ [lower, upper] = diffScoreLimits(a1, m1, a2, m2, lv.chisq, method);
72
+ break;
73
+ }
74
+ return [Math.min(lower, upper), Math.max(lower, upper)];
75
+ }
76
+ /**
77
+ * Confidence interval for the difference p1 - p2 of two independent proportions x1/n1 and x2/n2. Equivalent to
78
+ * `DescTools::BinomDiffCI()` in R.
79
+ *
80
+ * Methods (`method`): `"ac"` (Agresti-Caffo, the default as in DescTools: the Wald interval with one success and one
81
+ * failure added to each group), `"wald"`, `"score"` (Newcombe's hybrid score interval, his method 10), `"mn"`
82
+ * (Miettinen-Nurminen score interval) and `"mee"` (Farrington-Manning / Mee: the same without the factor N/(N - 1);
83
+ * epiR's score interval of the attributable risk). With `sides: "left"` or `"right"` only the lower or the upper limit
84
+ * is kept, at the one-sided level `confLevel`, and the other end is 1 or -1. The `"mn"` and `"mee"` limits are the
85
+ * roots of the score statistic to the precision of the doubles (DescTools stops at about 1e-7 and 1e-4).
86
+ *
87
+ * @param x1 Successes in group 1.
88
+ * @param n1 Trials in group 1.
89
+ * @param x2 Successes in group 2.
90
+ * @param n2 Trials in group 2.
91
+ * @param options See {@link BinomDiffCIOptions}.
92
+ * @returns The estimate p1 - p2 and the interval; see {@link BinomDiffCIResult}.
93
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
94
+ * one-sided), or an unknown method or sides.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * binomDiffCI(56, 70, 48, 80).confInt; // [0.05245292663805373, 0.3357584554757674]
99
+ * binomDiffCI(56, 70, 48, 80, { method: "mn" }).confInt; // [0.05282971324584462, 0.33817294001586834]
100
+ * ```
101
+ *
102
+ * @category Hypothesis tests
103
+ */
104
+ export function binomDiffCI(x1, n1, x2, n2, options = {}) {
105
+ checkOptions(options, BINOM_DIFF_CI_KEYS, "binomDiffCI"); // generated: option-keys.mjs
106
+ const method = matchChoice(options.method, DIFF_METHODS);
107
+ const lv = intervalLevel(options.confLevel, options.sides);
108
+ const [a1, m1] = checkTrials(x1, n1, "x1", "n1");
109
+ const [a2, m2] = checkTrials(x2, n2, "x2", "n2");
110
+ const est = a1 / m1 - a2 / m2;
111
+ let [lower, upper] = binomDiffLimits(a1, m1, a2, m2, method, lv);
112
+ if (lv.sides === "left")
113
+ upper = 1;
114
+ else if (lv.sides === "right")
115
+ lower = -1;
116
+ return reported("binomDiffCI", {
117
+ estimate: est,
118
+ confInt: [lower, upper],
119
+ confLevel: options.confLevel ?? 0.95,
120
+ method,
121
+ sides: lv.sides,
122
+ warnings: [],
123
+ });
124
+ }
125
+ const RATIO_METHODS = ["katz.log", "koopman"];
126
+ /** Katz's log interval of (x1/n1)/(x2/n2) at z, centred at that ratio */
127
+ function katzInterval(x1, n1, x2, n2, z) {
128
+ const ratio = x1 / n1 / (x2 / n2);
129
+ const half = z * Math.sqrt(1 / x1 - 1 / n1 + 1 / x2 - 1 / n2);
130
+ return [ratio * Math.exp(-half), ratio * Math.exp(half)];
131
+ }
132
+ /**
133
+ * Confidence interval for the ratio p1/p2 of two independent proportions x1/n1 and x2/n2 (the risk ratio). Equivalent
134
+ * to `DescTools::BinomRatioCI()` in R.
135
+ *
136
+ * Methods (`method`): `"katz.log"` (the default; Katz's log interval, with 0.5 put for a zero count, and n - 0.5 for
137
+ * both counts when both groups are all successes, as DescTools) and `"koopman"` (Koopman's score interval, also epiR's
138
+ * score interval of the risk ratio), whose limits are the roots of Koopman's statistic to the precision of the
139
+ * doubles. With `sides: "left"` or `"right"` only the lower or the upper limit is kept, at the one-sided level
140
+ * `confLevel`, and the other end is Infinity or 0 (DescTools computes the one-sided level but keeps both limits).
141
+ * With x1 = x2 = 0 the estimate is 0 and the interval [0, Infinity], as DescTools.
142
+ *
143
+ * @param x1 Successes in group 1.
144
+ * @param n1 Trials in group 1.
145
+ * @param x2 Successes in group 2.
146
+ * @param n2 Trials in group 2.
147
+ * @param options See {@link BinomRatioCIOptions}.
148
+ * @returns The estimate p1/p2 and the interval; see {@link BinomRatioCIResult}.
149
+ * @throws RangeError for counts that are not integers with 0 <= x <= n, n > 0, a level outside (0, 1) (at least 0.5
150
+ * one-sided), or an unknown method or sides.
151
+ *
152
+ * @example
153
+ * ```ts
154
+ * binomRatioCI(56, 70, 48, 80).confInt; // [1.076626422763193, 1.6512485112663868]
155
+ * binomRatioCI(56, 70, 48, 80, { method: "koopman" }).confInt; // [1.0798215063618983, 1.6708055780191118]
156
+ * ```
157
+ *
158
+ * @category Hypothesis tests
159
+ */
160
+ export function binomRatioCI(x1, n1, x2, n2, options = {}) {
161
+ checkOptions(options, BINOM_RATIO_CI_KEYS, "binomRatioCI"); // generated: option-keys.mjs
162
+ const method = matchChoice(options.method, RATIO_METHODS);
163
+ const lv = intervalLevel(options.confLevel, options.sides);
164
+ const [a1, m1] = checkTrials(x1, n1, "x1", "n1");
165
+ const [a2, m2] = checkTrials(x2, n2, "x2", "n2");
166
+ const z = lv.kappa;
167
+ // as DescTools, 0 (not NaN) for 0/0
168
+ const est = a1 === 0 ? 0 : a1 / m1 / (a2 / m2);
169
+ let lower;
170
+ let upper;
171
+ if (a1 === 0 && a2 === 0)
172
+ [lower, upper] = [0, Infinity];
173
+ else if (method === "katz.log") {
174
+ if (a1 === 0)
175
+ [lower, upper] = [0, katzInterval(0.5, m1, a2, m2, z)[1]];
176
+ else if (a2 === 0)
177
+ [lower, upper] = [katzInterval(a1, m1, 0.5, m2, z)[0], Infinity];
178
+ else if (a1 === m1 && a2 === m2)
179
+ [lower, upper] = katzInterval(m1 - 0.5, m1, m2 - 0.5, m2, z);
180
+ else
181
+ [lower, upper] = katzInterval(a1, m1, a2, m2, z);
182
+ }
183
+ else {
184
+ [lower, upper] = ratioScoreLimits(a1, m1, a2, m2, lv.chisq);
185
+ }
186
+ if (lv.sides === "left")
187
+ upper = Infinity;
188
+ else if (lv.sides === "right")
189
+ lower = 0;
190
+ return reported("binomRatioCI", {
191
+ estimate: est,
192
+ confInt: [lower, upper],
193
+ confLevel: options.confLevel ?? 0.95,
194
+ method,
195
+ sides: lv.sides,
196
+ warnings: [],
197
+ });
198
+ }
199
+ const OR_METHODS = ["midp", "fisher", "wald", "score"];
200
+ const OR_DESCRIPTIONS = {
201
+ midp: "median-unbiased estimate & mid-p exact CI",
202
+ fisher: "Conditional MLE & exact CI from 'fisher.test'",
203
+ wald: "Unconditional MLE & normal approximation (Wald) CI",
204
+ score: "Unconditional MLE & score CI",
205
+ };
206
+ /**
207
+ * Largest support of the (1, 1) cell for the exact estimate and interval ("midp", "fisher"): the three root searches
208
+ * evaluate the density over the support some 50 to 100 times each (2^23 values take about 6 s, 2^24 about 12 s)
209
+ */
210
+ const MAX_EXACT_SUPPORT = 2 ** 23;
211
+ /** Largest support for Fisher's p-value from the array of the density (fisherTest's way, about 0.1 s at 2^20) */
212
+ const MAX_ARRAY_PVALUE = 2 ** 20;
213
+ /** Double-double sum of v[from..to] */
214
+ function sumRange(v, from, to) {
215
+ let acc = [0, 0];
216
+ for (let i = Math.max(0, from); i <= Math.min(to, v.length - 1); i++)
217
+ if (v[i] !== 0)
218
+ acc = ddAdd(acc, [v[i], 0]);
219
+ return acc[0];
220
+ }
221
+ /**
222
+ * Odds ratio of a 2 x 2 table with its confidence interval and three p-values of independence. Equivalent to
223
+ * `epitools::oddsratio()` in R.
224
+ *
225
+ * The table is in epitools' orientation: rows are the exposure (row 1 the reference level) and columns the outcome
226
+ * (column 1 without the disease); the odds ratio x11 x22 / (x12 x21) is the same for the transposed table.
227
+ *
228
+ * Methods (`method`): `"midp"` (the default, as epitools: the median-unbiased estimate and the mid-p exact interval
229
+ * from Fisher's noncentral hypergeometric distribution of x11 given the margins), `"fisher"` (the conditional MLE and
230
+ * the exact interval of {@link fisherTest}), `"wald"` (the sample odds ratio and Woolf's interval on the log scale;
231
+ * as epitools, no zero-cell correction: a zero cell gives an estimate of 0 or Infinity and NaN for the limit that is
232
+ * not defined) and `"score"` (the sample odds ratio and the score interval of epiR's `epi.2by2`, Miettinen-Nurminen
233
+ * without the factor N/(N - 1)). The mid-p and score limits are the roots of their equations to the precision of the
234
+ * doubles (epitools solves with uniroot's tolerance on [0, 1000] and fails beyond and for zero cells; epiR steps by
235
+ * 0.1%). With a zero cell the mid-p estimate and limits follow the conventions of exact2x2: 0 or Infinity at the end
236
+ * of the support.
237
+ *
238
+ * `pValue` has epitools' three p-values: the two-sided mid-p (twice the smaller one-sided mid-p value), Fisher's
239
+ * exact test and Pearson's chi-squared without continuity correction (with R's warning "Chi-squared approximation may
240
+ * be incorrect" where an expected count is below 5).
241
+ *
242
+ * @param table A 2 x 2 table of counts as an array of rows.
243
+ * @param options See {@link OddsRatioOptions}.
244
+ * @returns See {@link OddsRatioResult}.
245
+ * Limits: the exact methods (`"midp"`, `"fisher"`) need the support of x11 given the margins (min(x11, x22) +
246
+ * min(x12, x21) + 1 values) to be at most 2^23 (about 6 s), and `"fisher"` counts of at most 2^31 - 1 (as
247
+ * `fisherTest`); the p-values of every method need phyper within its 2^26 terms (counts up to about 1e12).
248
+ *
249
+ * @throws TypeError if the table is not 2 x 2; RangeError for negative or non-integer counts, a table of zeros, a
250
+ * level outside (0, 1), an unknown method, or a table beyond the limits above.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * const r = oddsRatio([[56, 14], [48, 32]]);
255
+ * r.estimate; // 2.6364237331551914
256
+ * r.confInt; // [1.276159154292712, 5.670866460839431]
257
+ * r.pValue; // { midp: 0.008449442679452648, fisher: 0.012521129749209155, chiSquare: 0.00804508136819659 }
258
+ * ```
259
+ *
260
+ * @category Hypothesis tests
261
+ */
262
+ export function oddsRatio(table, options = {}) {
263
+ checkOptions(options, ODDS_RATIO_KEYS, "oddsRatio"); // generated: option-keys.mjs
264
+ const method = matchChoice(options.method, OR_METHODS);
265
+ if (table.length !== 2 || table.some((r) => r.length !== 2))
266
+ throw new TypeError("'table' must be a 2 x 2 table");
267
+ const confLevel = options.confLevel ?? 0.95;
268
+ const { alpha, kappa, chisq } = intervalLevel(confLevel, undefined);
269
+ const t = table.map((r, i) => Array.from(r, (v, j) => checkCount(v, `table[${i}][${j}]`)));
270
+ const [[a, b], [c, d]] = t;
271
+ const n = a + b + c + d;
272
+ if (n === 0)
273
+ throw new RangeError("all entries of the table are zero");
274
+ // (the hypergeometric p-values need exact margins)
275
+ if (!(n <= 2 ** 53))
276
+ throw new RangeError("the total of the table must be at most 2^53");
277
+ // the support of the (1, 1) cell given the margins (min(a, d) + min(b, c) + 1 values)
278
+ const lo = Math.max(0, a - d);
279
+ const hi = a + Math.min(b, c);
280
+ const size = hi - lo + 1;
281
+ if (method === "midp" || method === "fisher") {
282
+ if (size > MAX_EXACT_SUPPORT) {
283
+ throw new RangeError(`the exact distribution of the 2 x 2 table has ${size} values, more than 2^23: use method "wald" or "score"`);
284
+ }
285
+ // (fisherTest's limit, as R's fisher.test)
286
+ if (method === "fisher" && Math.max(a, b, c, d) > 2147483647) {
287
+ throw new RangeError("'table' has entries too large for the conditional MLE (above 2^31 - 1): use method \"wald\" or \"score\"");
288
+ }
289
+ }
290
+ // ---- p-values ----
291
+ // (from the central hypergeometric distribution by phyper: no array of the support for the closed-form methods.
292
+ // phyper's limit of 2^26 terms, met with counts of about 1e13, bounds every method: 2 s at counts of 1e12)
293
+ let below;
294
+ let above;
295
+ let fisherP;
296
+ try {
297
+ below = phyper1(a - 1, a + c, b + d, a + b, true, false) + 0.5 * dhyper1(a, a + c, b + d, a + b, false);
298
+ above = phyper1(a, a + c, b + d, a + b, false, false) + 0.5 * dhyper1(a, a + c, b + d, a + b, false);
299
+ // Fisher's two-sided p-value: from the density over the support as fisherTest where it is small enough to hold
300
+ // (R's bits), from two tails by phyper beyond (counts of 1e9: fisherTest stops at entries above 2^31 - 1)
301
+ fisherP =
302
+ size <= MAX_ARRAY_PVALUE
303
+ ? twoSidedPValue(new OddsRatioDistribution(a + c, b + d, a + b), a, 1)
304
+ : twoSidedPValueUnimodal(a, a + c, b + d, a + b);
305
+ }
306
+ catch (e) {
307
+ if (e instanceof RangeError)
308
+ throw new RangeError(`the exact p-values of the table are beyond reach: ${e.message}`);
309
+ throw e;
310
+ }
311
+ const midp = 2 * Math.min(below, above);
312
+ const rows = [a + b, c + d];
313
+ const cols = [a + c, b + d];
314
+ // Pearson's statistic summed in R's (column) order, with expected counts r_i c_j / n
315
+ let x2 = 0;
316
+ let small = false;
317
+ for (let j = 0; j < 2; j++) {
318
+ for (let i = 0; i < 2; i++) {
319
+ const e = (rows[i] * cols[j]) / n;
320
+ if (e < 5)
321
+ small = true;
322
+ const dev = Math.abs(t[i][j] - e);
323
+ x2 += (dev * dev) / e;
324
+ }
325
+ }
326
+ const chiSquare = pgamma1(x2, 0.5, 2, false, false);
327
+ // ---- estimate and interval ----
328
+ let estimate;
329
+ let confInt;
330
+ switch (method) {
331
+ case "wald": {
332
+ estimate = (a * d) / (b * c);
333
+ const half = kappa * Math.sqrt(1 / a + 1 / b + 1 / c + 1 / d);
334
+ confInt = [Math.exp(Math.log(estimate) - half), Math.exp(Math.log(estimate) + half)];
335
+ break;
336
+ }
337
+ case "fisher": {
338
+ const fisher = unreported(() => fisherTest(t, { confLevel }));
339
+ estimate = fisher.estimate;
340
+ confInt = fisher.confInt;
341
+ break;
342
+ }
343
+ case "score": {
344
+ estimate = (a * d) / (b * c);
345
+ // group 1 = row 1 (x1 = a of n1 = a + b), group 2 = row 2. With zero cells that put the estimate at both 0 and
346
+ // Infinity (a zero row or column, or a = b = 0, ...) the statistic does not depend on the odds ratio: [0, Infinity]
347
+ const atZero = a === 0 || d === 0;
348
+ const atInf = b === 0 || c === 0;
349
+ confInt = atZero && atInf ? [0, Infinity] : oddsRatioScoreLimits(a, a + b, c, c + d, chisq);
350
+ break;
351
+ }
352
+ case "midp": {
353
+ const dist = new OddsRatioDistribution(a + c, b + d, a + b);
354
+ // the mid-p tails P(X < a) + P(X = a)/2 and P(X > a) + P(X = a)/2 at psi (direct sums, no 1 - x)
355
+ const tails = (psi) => {
356
+ if (psi === 1)
357
+ return [below, above];
358
+ const dens = dist.density(psi);
359
+ const j = a - lo;
360
+ const half = 0.5 * dens[j];
361
+ return [sumRange(dens, 0, j - 1) + half, sumRange(dens, j + 1, dens.length - 1) + half];
362
+ };
363
+ const root = (f, increasing) => {
364
+ const f1 = f(1);
365
+ if (f1 === 0)
366
+ return 1;
367
+ return logScaleRoot(f, increasing ? f1 > 0 : f1 < 0);
368
+ };
369
+ // P(X <= a) - P(X >= a) = 0, i.e. the lower mid-p tail = 1/2 (decreasing in psi)
370
+ estimate = a === lo ? 0 : a === hi ? Infinity : root((psi) => tails(psi)[0] - 0.5, false);
371
+ const lower = a === lo ? 0 : root((psi) => tails(psi)[1] - alpha / 2, true);
372
+ const upper = a === hi ? Infinity : root((psi) => tails(psi)[0] - alpha / 2, false);
373
+ confInt = [lower, upper];
374
+ break;
375
+ }
376
+ }
377
+ return reported("oddsRatio", {
378
+ estimate,
379
+ confInt,
380
+ confLevel,
381
+ method: OR_DESCRIPTIONS[method],
382
+ pValue: { midp, fisher: fisherP, chiSquare },
383
+ warnings: small ? ["Chi-squared approximation may be incorrect"] : [],
384
+ });
385
+ }