@numero-uno-jpn/rstats 1.2.0 → 1.3.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 (78) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.ja.md +27 -10
  3. package/README.md +26 -9
  4. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-L23RSC2N.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-IAWXF73N.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-BNTBZ5W3.js} +2 -2
  10. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-73LNRWU3.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-VERBXW6E.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-P7ZHH2SF.js} +2 -2
  23. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-T5DRIITM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7INBXTVV.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-BKV3FINA.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +9 -0
  33. package/dist/entries/tests.js +9 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/blandAltman.d.ts +100 -0
  36. package/dist/htest/blandAltman.js +159 -0
  37. package/dist/htest/diagnosticTests.d.ts +91 -0
  38. package/dist/htest/diagnosticTests.js +116 -0
  39. package/dist/htest/iccPsych.d.ts +106 -0
  40. package/dist/htest/iccPsych.js +332 -0
  41. package/dist/htest/ksTest.d.ts +1 -1
  42. package/dist/htest/mcreg.d.ts +209 -0
  43. package/dist/htest/mcreg.js +735 -0
  44. package/dist/htest/roc.d.ts +287 -0
  45. package/dist/htest/roc.js +635 -0
  46. package/dist/htest/rocTest.d.ts +139 -0
  47. package/dist/htest/rocTest.js +444 -0
  48. package/dist/htest/tTOST.d.ts +202 -0
  49. package/dist/htest/tTOST.js +558 -0
  50. package/dist/htest/trendTests.d.ts +1 -1
  51. package/dist/htest/trendTests.js +1 -1
  52. package/dist/internal/summary.js +5 -0
  53. package/dist/linalg/qr.d.ts +3 -0
  54. package/dist/linalg/qr.js +3 -0
  55. package/dist/linalg.js +2 -2
  56. package/dist/mixed.js +2 -2
  57. package/dist/models/coeftest.d.ts +139 -0
  58. package/dist/models/coeftest.js +237 -0
  59. package/dist/models/coxph.d.ts +60 -9
  60. package/dist/models/coxph.js +367 -38
  61. package/dist/models/glm.d.ts +11 -1
  62. package/dist/models/glm.js +19 -2
  63. package/dist/models/inputRows.d.ts +10 -0
  64. package/dist/models/inputRows.js +23 -0
  65. package/dist/models/lm.d.ts +8 -0
  66. package/dist/models/lm.js +14 -2
  67. package/dist/models/sandwich.d.ts +177 -0
  68. package/dist/models/sandwich.js +923 -0
  69. package/dist/numerics.js +2 -2
  70. package/dist/random/rng.d.ts +8 -1
  71. package/dist/random/rng.js +14 -1
  72. package/dist/rstats.js +16 -16
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +13 -13
  75. package/llms.txt +17 -0
  76. package/package.json +1 -1
  77. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  78. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -0,0 +1,139 @@
1
+ import { type RocDirection, type RocResponseValue, type RocResult } from "./roc.js";
2
+ import { type Alternative, type HTest, type Sample } from "./types.js";
3
+ /**
4
+ * Options for {@link ciAuc}.
5
+ *
6
+ * @category Hypothesis tests
7
+ */
8
+ export interface CiAucOptions {
9
+ /** Confidence level, in [0, 1]. Default `0.95`. */
10
+ confLevel?: number;
11
+ /** `"delong"` (default) or `"bootstrap"`; abbreviations are accepted. */
12
+ method?: "delong" | "bootstrap" | (string & {});
13
+ /** Number of bootstrap replicates. Default `2000`. */
14
+ bootN?: number;
15
+ /** Resample the controls and the cases separately (default `true`), or all observations together. */
16
+ bootStratified?: boolean;
17
+ }
18
+ /**
19
+ * Result of {@link ciAuc}.
20
+ *
21
+ * @category Hypothesis tests
22
+ */
23
+ export interface CiAucResult {
24
+ /** The AUC: DeLong's θ (the mean of the placements), or the curve's AUC for the bootstrap. */
25
+ estimate: number;
26
+ /** The interval `[lower, upper]`. */
27
+ confInt: [number, number];
28
+ /** The confidence level. */
29
+ confLevel: number;
30
+ /** The method, in full. */
31
+ method: "delong" | "bootstrap";
32
+ /** DeLong's variance of the AUC (pROC's `var(roc)`), or the variance of the bootstrap AUCs. */
33
+ variance: number;
34
+ /** R's warnings, each once, in R's order (an empty array when there are none). */
35
+ warnings: string[];
36
+ }
37
+ /**
38
+ * Confidence interval of the area under a ROC curve, by DeLong's method or the bootstrap. Equivalent to
39
+ * `pROC::ci.auc()` in R.
40
+ *
41
+ * DeLong's interval is θ ∓ z√S (DeLong, DeLong and Clarke-Pearson 1988), clipped to [0, 1]; it needs at least two
42
+ * controls and two cases (pROC: NA). The bootstrap draws R's random stream as pROC does (`setSeed` gives R's values):
43
+ * `bootN` resamples of the controls then the cases (stratified, at least two of each) or of all observations, and
44
+ * the type-7 quantiles α/2 and 1 − α/2 of their AUCs. A non-stratified resample without cases or without controls is
45
+ * dropped with pROC's warning (pROC stops at one without controls).
46
+ *
47
+ * @param curve A curve from {@link roc}.
48
+ * @param options See {@link CiAucOptions}.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const r = roc({ controls: [1, 2, 2, 3, 5, 7], cases: [2, 4, 5, 5, 8, 9, 10] });
53
+ * ciAuc(r).confInt; // [0.5272205221855736, 1]
54
+ * ```
55
+ *
56
+ * @category Hypothesis tests
57
+ */
58
+ export declare function ciAuc(curve: RocResult, options?: CiAucOptions): CiAucResult;
59
+ /**
60
+ * Options for {@link rocTest}.
61
+ *
62
+ * @category Hypothesis tests
63
+ */
64
+ export interface RocTestOptions {
65
+ /** `"delong"` (default) or `"bootstrap"`; abbreviations are accepted. */
66
+ method?: "delong" | "bootstrap" | (string & {});
67
+ /** The alternative for the difference AUC₁ − AUC₂. Default `"two.sided"`. */
68
+ alternative?: Alternative | (string & {});
69
+ /**
70
+ * Whether the curves are paired (on the same observations). Default: paired when both come from the same response
71
+ * (as pROC). `true` for curves that are not is an error; `false` for curves that are gives pROC's warning.
72
+ */
73
+ paired?: boolean;
74
+ /** Confidence level of the interval of the paired DeLong test, in [0, 1]. Default `0.95`. */
75
+ confLevel?: number;
76
+ /** Number of bootstrap replicates. Default `2000`. */
77
+ bootN?: number;
78
+ /** Resample the controls and the cases separately (default `true`), or all observations together. */
79
+ bootStratified?: boolean;
80
+ /** With a response and two predictors: the control and case levels (see {@link RocOptions}). */
81
+ levels?: readonly RocResponseValue[];
82
+ /** With a response and two predictors: the direction of both curves (see {@link RocOptions}). */
83
+ direction?: "auto" | RocDirection;
84
+ }
85
+ /**
86
+ * Result of {@link rocTest}.
87
+ *
88
+ * @category Hypothesis tests
89
+ */
90
+ export interface RocTestResult extends HTest {
91
+ /** The AUCs of the two curves. */
92
+ estimate: [number, number];
93
+ /** `"AUC of roc1"` and `"AUC of roc2"`. */
94
+ estimateNames: [string, string];
95
+ /** The first curve compared (when paired, rebuilt on the observations where neither predictor is missing). */
96
+ roc1: RocResult;
97
+ /** The second curve compared (when paired, rebuilt as `roc1`). */
98
+ roc2: RocResult;
99
+ /** For the bootstrap: whether it was stratified. */
100
+ bootStratified?: boolean;
101
+ }
102
+ /**
103
+ * Tests the difference of the areas under two ROC curves, by DeLong's method or the bootstrap. Equivalent to
104
+ * `pROC::roc.test()` in R.
105
+ *
106
+ * Curves from the same response are paired, as pROC pairs them (identical responses; where a predictor is missing,
107
+ * both curves are rebuilt on the observations where neither is). Paired DeLong: Z = (θ₁ − θ₂)/σ with σ² from the
108
+ * placements' covariances (DeLong, DeLong and Clarke-Pearson 1988), Z = 0 when both are 0, and the interval θ₁ − θ₂ ∓
109
+ * zσ. Unpaired DeLong: D = (θ₁ − θ₂)/√(S₁ + S₂) on pROC's Welch-Satterthwaite degrees of freedom (when both variances
110
+ * are 0, D = 0 with p-value 1 if the AUCs are equal, and the degrees of freedom are NaN). Bootstrap: D = (AUC₁ −
111
+ * AUC₂)/sd of the resampled differences, with R's random stream. DeLong's method needs at least two controls and two
112
+ * cases in each curve, as does the stratified bootstrap. The method is DeLong's unless given (pROC switches to the
113
+ * bootstrap silently for curves of different directions; here DeLong's test gives pROC's warning).
114
+ *
115
+ * @param roc1 The first curve, from {@link roc}.
116
+ * @param roc2 The second curve.
117
+ * @param options See {@link RocTestOptions}.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * const y = [0, 0, 0, 0, 1, 1, 1, 1];
122
+ * const t = rocTest(roc(y, [1, 2, 3, 5, 4, 6, 7, 8]), roc(y, [2, 1, 5, 4, 3, 7, 6, 8]));
123
+ * t.estimate; // [0.9375, 0.875]
124
+ * t.statistic; // 0.7071067811865475
125
+ * ```
126
+ *
127
+ * @category Hypothesis tests
128
+ */
129
+ export declare function rocTest(roc1: RocResult, roc2: RocResult, options?: RocTestOptions): RocTestResult;
130
+ /**
131
+ * Tests the difference of the areas under the ROC curves of two predictors of the same response (paired);
132
+ * observations with a missing response or predictor are dropped from both.
133
+ *
134
+ * @param response The outcome (see {@link roc}).
135
+ * @param predictor1 The first predictor.
136
+ * @param predictor2 The second predictor.
137
+ * @param options See {@link RocTestOptions}.
138
+ */
139
+ export declare function rocTest(response: readonly RocResponseValue[] | Float64Array, predictor1: Sample, predictor2: Sample, options?: RocTestOptions): RocTestResult;
@@ -0,0 +1,444 @@
1
+ // Confidence intervals of the AUC and tests comparing two ROC curves (pROC's ci.auc and roc.test, DeLong's and
2
+ // bootstrap methods).
3
+ //
4
+ // Written for rStats.js from oracle/roc-behaviour.md (no ported code; the source of pROC was not read):
5
+ // - DeLong, DeLong and Clarke-Pearson (Biometrics 44, 1988): the placements V10 of the cases and V01 of the controls,
6
+ // the variance S = var(V10)/m + var(V01)/n of the AUC, and the paired test of two curves on the same observations,
7
+ // whose variance is computed here as that of the differences of the placements (the same as L'SL, without the
8
+ // cancellation of S11 + S22 - 2 S12). The placements are mid-rank counts (Sun and Xu, IEEE Signal Processing Letters
9
+ // 21, 2014), multiples of 1/(2n) and 1/(2m) kept as their integer numerators; the differences of two AUCs are formed
10
+ // from the integer counts and rounded once.
11
+ // - The unpaired test: (theta1 - theta2)/sqrt(S1 + S2) on pROC's Welch-Satterthwaite degrees of freedom.
12
+ // - The bootstrap (Robin et al., BMC Bioinformatics 12, 2011, the paper's description): the observations resampled
13
+ // with R's sample() (src/random), stratified by class or not, the AUC of each resample, and the type-7 quantiles
14
+ // (ciAuc) or the standard deviation of the differences (rocTest).
15
+ import { quantile } from "../descriptive/quantile.js";
16
+ import { pnorm, qnorm } from "../distributions/normal.js";
17
+ import { pt1 } from "../distributions/t.js";
18
+ import { variance } from "../internal/summary.js";
19
+ import { reported, Warnings } from "../internal/warnings.js";
20
+ import { unifIndex } from "../random/rng.js";
21
+ import { matchChoice } from "./power.js";
22
+ import { aucOf, ratioToDouble, rocData, rocFromResponse, twiceUOf } from "./roc.js";
23
+ import { checkConfLevel, matchAlternative } from "./types.js";
24
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
25
+ import { checkOptions } from "../internal/checkOptions.js";
26
+ import { isOptionsObject } from "../internal/optionalArgs.js";
27
+ const CI_AUC_KEYS = ["confLevel", "method", "bootN", "bootStratified"];
28
+ const ROC_TEST_KEYS = [
29
+ "method", "alternative", "paired", "confLevel", "bootN", "bootStratified", "levels", "direction",
30
+ ];
31
+ // Generated by `node scripts/option-keys.mjs --write` (end)
32
+ /**
33
+ * The placements of the cases (V10, in the order of the cases) and of the controls (V01) as their integer numerators:
34
+ * V10 = k10/(2n) and V01 = k01/(2m), for n controls and m cases
35
+ */
36
+ function placements(curve) {
37
+ const c = Float64Array.from(curve.controls).sort();
38
+ const k = Float64Array.from(curve.cases).sort();
39
+ const n = c.length;
40
+ const m = k.length;
41
+ // the number of values of s below v, and of those equal to v
42
+ const split = (s, v) => {
43
+ let lo = 0;
44
+ let hi = s.length;
45
+ while (lo < hi) {
46
+ const mid = (lo + hi) >> 1;
47
+ if (s[mid] < v)
48
+ lo = mid + 1;
49
+ else
50
+ hi = mid;
51
+ }
52
+ let end = lo;
53
+ while (end < s.length && s[end] === v)
54
+ end++;
55
+ return [lo, end - lo];
56
+ };
57
+ const lt = curve.direction === "<";
58
+ const k10 = curve.cases.map((x) => {
59
+ const [below, eq] = split(c, x);
60
+ return 2 * (lt ? below : n - below - eq) + eq;
61
+ });
62
+ const k01 = curve.controls.map((y) => {
63
+ const [below, eq] = split(k, y);
64
+ return 2 * (lt ? m - below - eq : below) + eq;
65
+ });
66
+ return { k10, k01 };
67
+ }
68
+ /**
69
+ * S = var(V10)/m + var(V01)/n from the variances of the integer numerators, divided by (2n)^2 and (2m)^2: the
70
+ * placements as rounded doubles near 1 carried an absolute error that was large against their deviations for a
71
+ * near-perfect curve (S of 5e-21 came out with 1.3e-11 relative error)
72
+ */
73
+ function delongS(k10, k01, n, m) {
74
+ return variance(k10) / (4 * n * n) / m + variance(k01) / (4 * m * m) / n;
75
+ }
76
+ /** DeLong's variance of the AUC, S = var(V10)/m + var(V01)/n */
77
+ function delongVariance(curve) {
78
+ const { k10, k01 } = placements(curve);
79
+ return delongS(k10, k01, curve.controls.length, curve.cases.length);
80
+ }
81
+ /**
82
+ * The difference of two AUCs, U1/(m1 n1) - U2/(m2 n2), from the integer counts of the two samples and rounded once
83
+ * (the difference of the rounded AUCs cancels: 6e-10 relative error in Z for two curves of 30000 + 30000
84
+ * observations that differ in two cases)
85
+ */
86
+ function aucDifference(controls1, cases1, direction1, controls2, cases2, direction2) {
87
+ const u1 = BigInt(twiceUOf(controls1, cases1, direction1));
88
+ const u2 = BigInt(twiceUOf(controls2, cases2, direction2));
89
+ const d1 = BigInt(controls1.length) * BigInt(cases1.length);
90
+ const d2 = BigInt(controls2.length) * BigInt(cases2.length);
91
+ return ratioToDouble(u1 * d2 - u2 * d1, 2n * d1 * d2);
92
+ }
93
+ /** Whether the curve is perfect (AUC 1: a point with sensitivity and specificity 1) */
94
+ const isPerfect = (curve) => curve.sensitivities.some((s, i) => s === 1 && curve.specificities[i] === 1);
95
+ /** At least two observations in each class, for DeLong's variance and the stratified bootstrap */
96
+ function requireTwoPerClass(curve, what) {
97
+ if (curve.controls.length < 2 || curve.cases.length < 2) {
98
+ throw new Error(`${what} needs at least 2 controls and 2 cases`);
99
+ }
100
+ }
101
+ /** z = qnorm(1 - alpha/2), from the upper tail for alpha/2 below 1e-8 (rule 10) */
102
+ function zOf(confLevel) {
103
+ const a2 = (1 - confLevel) / 2;
104
+ return a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - a2);
105
+ }
106
+ function checkBootN(bootN) {
107
+ if (!(Number.isInteger(bootN) && bootN >= 1 && bootN <= 2 ** 24))
108
+ throw new RangeError("bootN must be an integer from 1 to 2^24");
109
+ }
110
+ /** R's sample(x, replace = TRUE) of a vector of length > 1: x[i] for size draws of R_unif_index(length) */
111
+ function resample(x) {
112
+ const out = new Array(x.length);
113
+ for (let i = 0; i < x.length; i++)
114
+ out[i] = x[unifIndex(x.length)];
115
+ return out;
116
+ }
117
+ /** The observations of a curve in their order: values and classes (c(controls, cases) without its data) */
118
+ function observations(curve) {
119
+ const d = rocData(curve);
120
+ if (d !== undefined)
121
+ return { values: d.values, isCase: d.isCase };
122
+ const values = [...curve.controls, ...curve.cases];
123
+ return { values, isCase: values.map((_, i) => i >= curve.controls.length) };
124
+ }
125
+ /** The controls and cases of a non-stratified resample of the observations (undefined when a class is empty) */
126
+ function resampledClasses(values, isCase, idx) {
127
+ const controls = [];
128
+ const cases = [];
129
+ for (const i of idx)
130
+ (isCase[i] ? cases : controls).push(values[i]);
131
+ if (controls.length === 0 || cases.length === 0)
132
+ return undefined;
133
+ return { controls, cases };
134
+ }
135
+ /** The AUC of a non-stratified resample of the observations (NaN when a class is empty) */
136
+ function resampledAuc(values, isCase, idx, direction) {
137
+ const s = resampledClasses(values, isCase, idx);
138
+ return s === undefined ? NaN : aucOf(s.controls, s.cases, direction);
139
+ }
140
+ /** N draws of R_unif_index(N) (R's sample(1:N, replace = TRUE), 0-based) */
141
+ function drawIndices(n) {
142
+ const out = new Array(n);
143
+ for (let i = 0; i < n; i++)
144
+ out[i] = unifIndex(n);
145
+ return out;
146
+ }
147
+ /**
148
+ * Confidence interval of the area under a ROC curve, by DeLong's method or the bootstrap. Equivalent to
149
+ * `pROC::ci.auc()` in R.
150
+ *
151
+ * DeLong's interval is θ ∓ z√S (DeLong, DeLong and Clarke-Pearson 1988), clipped to [0, 1]; it needs at least two
152
+ * controls and two cases (pROC: NA). The bootstrap draws R's random stream as pROC does (`setSeed` gives R's values):
153
+ * `bootN` resamples of the controls then the cases (stratified, at least two of each) or of all observations, and
154
+ * the type-7 quantiles α/2 and 1 − α/2 of their AUCs. A non-stratified resample without cases or without controls is
155
+ * dropped with pROC's warning (pROC stops at one without controls).
156
+ *
157
+ * @param curve A curve from {@link roc}.
158
+ * @param options See {@link CiAucOptions}.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * const r = roc({ controls: [1, 2, 2, 3, 5, 7], cases: [2, 4, 5, 5, 8, 9, 10] });
163
+ * ciAuc(r).confInt; // [0.5272205221855736, 1]
164
+ * ```
165
+ *
166
+ * @category Hypothesis tests
167
+ */
168
+ export function ciAuc(curve, options = {}) {
169
+ checkOptions(options, CI_AUC_KEYS, "ciAuc"); // generated: option-keys.mjs
170
+ const confLevel = options.confLevel ?? 0.95;
171
+ checkConfLevel(confLevel);
172
+ const method = matchChoice(options.method, ["delong", "bootstrap"]);
173
+ const w = new Warnings();
174
+ if (isPerfect(curve))
175
+ w.add("ci.auc() of a ROC curve with AUC == 1 is always 1-1 and can be misleading.");
176
+ const alpha = 1 - confLevel;
177
+ if (method === "delong") {
178
+ requireTwoPerClass(curve, "DeLong's interval");
179
+ const { k10, k01 } = placements(curve);
180
+ const theta = curve.auc;
181
+ const S = delongS(k10, k01, curve.controls.length, curve.cases.length);
182
+ const sd = Math.sqrt(S);
183
+ // qnorm(c(alpha/2, 1 - alpha/2), theta, sd), clipped to [0, 1]
184
+ const clip = (v) => Math.min(1, Math.max(0, v));
185
+ // (the lower quantile from qnorm(alpha/2) as R; at level 1 the quantiles are -Inf and Inf whatever the sd, as R's
186
+ // qnorm, which checks p = 0 and 1 before sd = 0)
187
+ const a2 = alpha / 2;
188
+ const confInt = confLevel === 1 ? [0, 1] : sd === 0 ? [theta, theta] : [clip(theta + qnorm(a2) * sd), clip(theta + zOf(confLevel) * sd)];
189
+ return reported("ciAuc", { estimate: theta, confInt, confLevel, method, variance: S, warnings: w.list });
190
+ }
191
+ const bootN = options.bootN ?? 2000;
192
+ checkBootN(bootN);
193
+ const stratified = options.bootStratified ?? true;
194
+ const aucs = [];
195
+ let failed = 0;
196
+ if (stratified) {
197
+ requireTwoPerClass(curve, "a stratified bootstrap");
198
+ for (let b = 0; b < bootN; b++) {
199
+ const controls = resample(curve.controls);
200
+ const cases = resample(curve.cases);
201
+ aucs.push(aucOf(controls, cases, curve.direction));
202
+ }
203
+ }
204
+ else {
205
+ const { values, isCase } = observations(curve);
206
+ for (let b = 0; b < bootN; b++) {
207
+ const a = resampledAuc(values, isCase, drawIndices(values.length), curve.direction);
208
+ if (Number.isNaN(a))
209
+ failed++;
210
+ else
211
+ aucs.push(a);
212
+ }
213
+ }
214
+ if (failed > 0)
215
+ w.add("NA value(s) produced during bootstrap were ignored.");
216
+ if (aucs.length === 0)
217
+ throw new Error("no bootstrap replicate had both controls and cases");
218
+ const q = quantile(aucs, [alpha / 2, 1 - alpha / 2]);
219
+ return reported("ciAuc", {
220
+ estimate: curve.auc,
221
+ confInt: [q[0], q[1]],
222
+ confLevel,
223
+ method,
224
+ variance: aucs.length > 1 ? variance(aucs) : NaN,
225
+ warnings: w.list,
226
+ });
227
+ }
228
+ /** Whether a value is a curve made by roc() */
229
+ const isCurve = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && "thresholds" in v && "sensitivities" in v;
230
+ const sameArray = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
231
+ /**
232
+ * The paired versions of two curves (pROC's pairing): as they are when their responses after the removals are
233
+ * identical, rebuilt on the observations where neither predictor nor the response is missing when their original
234
+ * responses are; undefined when they are not paired
235
+ */
236
+ function pairedCurves(r1, r2) {
237
+ const d1 = rocData(r1);
238
+ const d2 = rocData(r2);
239
+ if (d1?.labels == null || d2?.labels == null || !sameArray(r1.levels, r2.levels))
240
+ return undefined;
241
+ const kept = (d) => d.kept.map((i) => d.labels[i]);
242
+ if (sameArray(kept(d1), kept(d2)) && sameArray(d1.isCase, d2.isCase))
243
+ return [r1, r2];
244
+ if (!sameArray(d1.labels, d2.labels))
245
+ return undefined;
246
+ const rows = d1.labels.map((_, i) => i).filter((i) => d1.labels[i] !== null && !Number.isNaN(d1.predictor[i]) && !Number.isNaN(d2.predictor[i]));
247
+ const rebuild = (r, d) => rocFromResponse(rows.map((i) => d.labels[i]), rows.map((i) => d.predictor[i]), { levels: r.levels, direction: r.direction });
248
+ return [rebuild(r1, d1), rebuild(r2, d2)];
249
+ }
250
+ /** Normal p-value of a statistic */
251
+ function normalP(z, alternative) {
252
+ if (alternative === "two.sided")
253
+ return 2 * pnorm(-Math.abs(z));
254
+ return alternative === "greater" ? pnorm(z, { lowerTail: false }) : pnorm(z);
255
+ }
256
+ export function rocTest(a, b, c, d) {
257
+ if (isOptionsObject(c))
258
+ checkOptions(c, ROC_TEST_KEYS, "rocTest"); // generated: option-keys.mjs
259
+ checkOptions(d, ROC_TEST_KEYS, "rocTest"); // generated: option-keys.mjs
260
+ let options;
261
+ const w = new Warnings();
262
+ let r1;
263
+ let r2;
264
+ if (isCurve(a)) {
265
+ if (!isCurve(b))
266
+ throw new TypeError("roc2 must be a curve from roc()");
267
+ options = (c ?? {});
268
+ if (options.levels !== undefined || options.direction !== undefined) {
269
+ throw new RangeError("'levels' and 'direction' apply only to a response and two predictors");
270
+ }
271
+ r1 = a;
272
+ r2 = b;
273
+ }
274
+ else {
275
+ options = d ?? {};
276
+ const response = Array.from(a);
277
+ const p1 = Array.from(b);
278
+ const p2 = Array.from(c);
279
+ if (response.length !== p1.length || response.length !== p2.length) {
280
+ throw new TypeError("the response and the predictors must have the same length");
281
+ }
282
+ const rows = response.map((_, i) => i).filter((i) => {
283
+ const v = response[i];
284
+ return v !== null && v !== undefined && !(typeof v === "number" && Number.isNaN(v)) && !Number.isNaN(p1[i]) && !Number.isNaN(p2[i]);
285
+ });
286
+ const resp = rows.map((i) => response[i]);
287
+ const curveOpts = { levels: options.levels, direction: options.direction };
288
+ r1 = rocFromResponse(resp, rows.map((i) => p1[i]), curveOpts);
289
+ r2 = rocFromResponse(resp, rows.map((i) => p2[i]), curveOpts);
290
+ for (const m of r1.warnings)
291
+ w.add(m);
292
+ }
293
+ const alternative = matchAlternative(options.alternative);
294
+ const method = matchChoice(options.method, ["delong", "bootstrap"]);
295
+ const confLevel = options.confLevel ?? 0.95;
296
+ checkConfLevel(confLevel);
297
+ if (isPerfect(r1) && isPerfect(r2))
298
+ w.add("roc.test() of two ROC curves with AUC == 1 has always p.value = 1 and can be misleading.");
299
+ const pairs = pairedCurves(r1, r2);
300
+ let paired;
301
+ if (options.paired === true) {
302
+ if (pairs === undefined)
303
+ throw new RangeError("The paired ROC test cannot be applied to unpaired curves.");
304
+ paired = true;
305
+ }
306
+ else if (options.paired === false) {
307
+ if (pairs !== undefined)
308
+ w.add("The ROC curves seem to be paired. Consider performing a paired roc.test.");
309
+ paired = false;
310
+ }
311
+ else
312
+ paired = pairs !== undefined;
313
+ if (paired)
314
+ [r1, r2] = pairs;
315
+ const common = {
316
+ alternative,
317
+ estimate: [r1.auc, r2.auc],
318
+ estimateNames: ["AUC of roc1", "AUC of roc2"],
319
+ nullValue: 0,
320
+ nullValueName: "difference in AUC",
321
+ roc1: r1,
322
+ roc2: r2,
323
+ };
324
+ const diff = aucDifference(r1.controls, r1.cases, r1.direction, r2.controls, r2.cases, r2.direction);
325
+ if (method === "delong") {
326
+ if (r1.direction !== r2.direction)
327
+ w.add("DeLong's test should not be applied to ROC curves with a different direction.");
328
+ requireTwoPerClass(r1, "DeLong's test");
329
+ requireTwoPerClass(r2, "DeLong's test");
330
+ if (paired) {
331
+ const p1 = placements(r1);
332
+ const p2 = placements(r2);
333
+ // (the differences of the integer numerators: both curves have the same n controls and m cases)
334
+ const d10 = p1.k10.map((v, i) => v - p2.k10[i]);
335
+ const d01 = p1.k01.map((v, i) => v - p2.k01[i]);
336
+ const sigma = Math.sqrt(delongS(d10, d01, r1.controls.length, r1.cases.length));
337
+ const z = diff === 0 && sigma === 0 ? 0 : diff / sigma;
338
+ const half = sigma === 0 ? 0 : zOf(confLevel) * sigma;
339
+ return reported("rocTest", {
340
+ method: "DeLong's test for two correlated ROC curves",
341
+ statistic: z,
342
+ statisticName: "Z",
343
+ pValue: normalP(z, alternative),
344
+ confInt: [diff - half, diff + half],
345
+ confLevel,
346
+ ...common,
347
+ warnings: w.list,
348
+ });
349
+ }
350
+ const s1 = delongVariance(r1);
351
+ const s2 = delongVariance(r2);
352
+ const n1 = r1.controls.length + r1.cases.length;
353
+ const n2 = r2.controls.length + r2.cases.length;
354
+ const s = s1 + s2;
355
+ let D;
356
+ let df;
357
+ let pValue;
358
+ if (s === 0) {
359
+ // both variances 0 (pROC: 0/0, NaN throughout): D = 0 for equal AUCs, else its limit ±Inf
360
+ D = diff === 0 ? 0 : diff > 0 ? Infinity : -Infinity;
361
+ df = NaN;
362
+ pValue = normalP(D, alternative);
363
+ }
364
+ else {
365
+ D = diff / Math.sqrt(s);
366
+ df = (s * s) / ((s1 * s1) / (n1 - 1) + (s2 * s2) / (n2 - 1));
367
+ pValue =
368
+ alternative === "two.sided" ? 2 * pt1(-Math.abs(D), df, true, false) : alternative === "greater" ? pt1(D, df, false, false) : pt1(D, df, true, false);
369
+ }
370
+ return reported("rocTest", {
371
+ method: "DeLong's test for two ROC curves",
372
+ statistic: D,
373
+ statisticName: "D",
374
+ parameter: df,
375
+ parameterName: "df",
376
+ pValue,
377
+ ...common,
378
+ warnings: w.list,
379
+ });
380
+ }
381
+ // bootstrap
382
+ const bootN = options.bootN ?? 2000;
383
+ checkBootN(bootN);
384
+ const stratified = options.bootStratified ?? true;
385
+ const diffs = [];
386
+ let failed = 0;
387
+ if (stratified) {
388
+ requireTwoPerClass(r1, "a stratified bootstrap");
389
+ requireTwoPerClass(r2, "a stratified bootstrap");
390
+ for (let k = 0; k < bootN; k++) {
391
+ if (paired) {
392
+ const ci = drawIndices(r1.controls.length);
393
+ const ki = drawIndices(r1.cases.length);
394
+ diffs.push(aucDifference(ci.map((i) => r1.controls[i]), ki.map((i) => r1.cases[i]), r1.direction, ci.map((i) => r2.controls[i]), ki.map((i) => r2.cases[i]), r2.direction));
395
+ }
396
+ else {
397
+ // (the draws in R's order: the controls and cases of curve 1, then those of curve 2)
398
+ const c1 = resample(r1.controls);
399
+ const k1 = resample(r1.cases);
400
+ const c2 = resample(r2.controls);
401
+ const k2 = resample(r2.cases);
402
+ diffs.push(aucDifference(c1, k1, r1.direction, c2, k2, r2.direction));
403
+ }
404
+ }
405
+ }
406
+ else {
407
+ const o1 = observations(r1);
408
+ const o2 = observations(r2);
409
+ for (let k = 0; k < bootN; k++) {
410
+ let s1;
411
+ let s2;
412
+ if (paired) {
413
+ const idx = drawIndices(o1.values.length);
414
+ s1 = resampledClasses(o1.values, o1.isCase, idx);
415
+ s2 = resampledClasses(o2.values, o2.isCase, idx);
416
+ }
417
+ else {
418
+ s1 = resampledClasses(o1.values, o1.isCase, drawIndices(o1.values.length));
419
+ s2 = resampledClasses(o2.values, o2.isCase, drawIndices(o2.values.length));
420
+ }
421
+ if (s1 === undefined || s2 === undefined)
422
+ failed++;
423
+ else
424
+ diffs.push(aucDifference(s1.controls, s1.cases, r1.direction, s2.controls, s2.cases, r2.direction));
425
+ }
426
+ }
427
+ if (failed > 0)
428
+ w.add(`${failed} NA value(s) produced during bootstrap were ignored.`);
429
+ if (diffs.length < 2)
430
+ throw new Error("fewer than 2 bootstrap replicates had both controls and cases");
431
+ const sd = Math.sqrt(variance(diffs));
432
+ const D = diff === 0 && sd === 0 ? 0 : diff / sd;
433
+ return reported("rocTest", {
434
+ method: paired ? "Bootstrap test for two correlated ROC curves" : "Bootstrap test for two ROC curves",
435
+ statistic: D,
436
+ statisticName: "D",
437
+ parameter: bootN,
438
+ parameterName: "boot.n",
439
+ pValue: normalP(D, alternative),
440
+ bootStratified: stratified,
441
+ ...common,
442
+ warnings: w.list,
443
+ });
444
+ }