@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.
- package/CHANGELOG.md +81 -0
- package/README.ja.md +27 -10
- package/README.md +26 -9
- package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-2VZW4XPK.js} +2 -2
- package/dist/chunks/chunk-4OOTEXZU.js +2 -0
- package/dist/chunks/{chunk-F3EQLL4F.js → chunk-6TZVS6WC.js} +2 -2
- package/dist/chunks/{chunk-L23RSC2N.js → chunk-6X2ZMPF5.js} +2 -2
- package/dist/chunks/{chunk-IAWXF73N.js → chunk-AJZV2SVY.js} +2 -2
- package/dist/chunks/{chunk-5SGTWSCB.js → chunk-BNTBZ5W3.js} +2 -2
- package/dist/chunks/{chunk-EEU7D4RU.js → chunk-EBRTF7RM.js} +1 -1
- package/dist/chunks/{chunk-IMPRIQE5.js → chunk-FFNHG5SB.js} +1 -1
- package/dist/chunks/{chunk-73LNRWU3.js → chunk-GUM57VVM.js} +1 -1
- package/dist/chunks/{chunk-RRO4LMCB.js → chunk-HBRSUHSU.js} +2 -2
- package/dist/chunks/{chunk-VERBXW6E.js → chunk-I5NWGQOQ.js} +2 -2
- package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
- package/dist/chunks/{chunk-6FZHTD5G.js → chunk-IOGQEMDE.js} +2 -2
- package/dist/chunks/{chunk-JWBSEL3V.js → chunk-JJRZ2TTF.js} +2 -2
- package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-LA4H6ZSC.js} +2 -2
- package/dist/chunks/{chunk-A66M3ZEA.js → chunk-LMNU4NHZ.js} +2 -2
- package/dist/chunks/{chunk-HBHMEPGY.js → chunk-LNUNKFIH.js} +3 -3
- package/dist/chunks/chunk-MJXETGT2.js +2 -0
- package/dist/chunks/{chunk-7WG7X2UI.js → chunk-P7ZHH2SF.js} +2 -2
- package/dist/chunks/{chunk-TNETWBF5.js → chunk-PDHBRDTF.js} +2 -2
- package/dist/chunks/{chunk-4AOTAT3O.js → chunk-RCGW2DCK.js} +2 -2
- package/dist/chunks/{chunk-NSU6U3ET.js → chunk-TZTVDVP4.js} +2 -2
- package/dist/chunks/{chunk-T5DRIITM.js → chunk-UJYRU37Z.js} +2 -2
- package/dist/chunks/{chunk-BI7NYJWP.js → chunk-UMDXXT3M.js} +1 -1
- package/dist/chunks/{chunk-7INBXTVV.js → chunk-UOAFEB64.js} +2 -2
- package/dist/chunks/{chunk-BKV3FINA.js → chunk-Z74ZOTUN.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +9 -0
- package/dist/entries/tests.js +9 -0
- package/dist/htest/agreement.d.ts +2 -2
- package/dist/htest/blandAltman.d.ts +100 -0
- package/dist/htest/blandAltman.js +159 -0
- package/dist/htest/diagnosticTests.d.ts +91 -0
- package/dist/htest/diagnosticTests.js +116 -0
- package/dist/htest/iccPsych.d.ts +106 -0
- package/dist/htest/iccPsych.js +332 -0
- package/dist/htest/ksTest.d.ts +1 -1
- package/dist/htest/mcreg.d.ts +209 -0
- package/dist/htest/mcreg.js +735 -0
- package/dist/htest/roc.d.ts +287 -0
- package/dist/htest/roc.js +635 -0
- package/dist/htest/rocTest.d.ts +139 -0
- package/dist/htest/rocTest.js +444 -0
- package/dist/htest/tTOST.d.ts +202 -0
- package/dist/htest/tTOST.js +558 -0
- package/dist/htest/trendTests.d.ts +1 -1
- package/dist/htest/trendTests.js +1 -1
- package/dist/internal/summary.js +5 -0
- package/dist/linalg/qr.d.ts +3 -0
- package/dist/linalg/qr.js +3 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/coeftest.d.ts +139 -0
- package/dist/models/coeftest.js +237 -0
- package/dist/models/coxph.d.ts +60 -9
- package/dist/models/coxph.js +367 -38
- package/dist/models/glm.d.ts +11 -1
- package/dist/models/glm.js +19 -2
- package/dist/models/inputRows.d.ts +10 -0
- package/dist/models/inputRows.js +23 -0
- package/dist/models/lm.d.ts +8 -0
- package/dist/models/lm.js +14 -2
- package/dist/models/sandwich.d.ts +177 -0
- package/dist/models/sandwich.js +923 -0
- package/dist/numerics.js +2 -2
- package/dist/random/rng.d.ts +8 -1
- package/dist/random/rng.js +14 -1
- package/dist/rstats.js +16 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +13 -13
- package/llms.txt +17 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-47IIPUFN.js +0 -2
- package/dist/chunks/chunk-CQB4BJBR.js +0 -2
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
// ROC curves of a numeric predictor of a binary outcome (pROC's roc, auc with the partial AUC, and coords).
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js from oracle/roc-behaviour.md (no ported code; the source of pROC was not read):
|
|
4
|
+
// - The curve: the thresholds are the midpoints between consecutive distinct values, with -Inf and +Inf at the ends;
|
|
5
|
+
// for direction "<" an observation is positive when its value is at least the threshold, for ">" when it is at most
|
|
6
|
+
// the threshold. The points are stored by increasing specificity, as pROC stores them.
|
|
7
|
+
// - The AUC is the Mann-Whitney statistic U/(mn) (Hanley and McNeil, Radiology 143, 1982), computed from integer
|
|
8
|
+
// counts and rounded once (pROC sums trapezoids, which agrees to an ulp or two).
|
|
9
|
+
// - The partial AUC is the area between two specificities (or sensitivities), with linear interpolation at the
|
|
10
|
+
// limits, optionally standardised as McClish (Medical Decision Making 9, 1989).
|
|
11
|
+
// - coords computes every column from the integer counts of each threshold (pROC rebuilds the counts from the
|
|
12
|
+
// proportions, which leaves them non-integer and loses digits in 1 - specificity), and compares the criteria of
|
|
13
|
+
// "best" exactly (pROC compares rounded sums with ==, which loses ties). Youden's criterion is pROC's weighted
|
|
14
|
+
// se + r sp (Youden, Cancer 3, 1950; Perkins and Schisterman, Am J Epidemiol 163, 2006; the weights r =
|
|
15
|
+
// (1 - prevalence)/(cost prevalence) as Zweig and Campbell, Clin Chem 39, 1993).
|
|
16
|
+
import { parseFormula, termsOf } from "../models/formula.js";
|
|
17
|
+
import { modelFrame } from "../models/modelFrame.js";
|
|
18
|
+
import { midpoint } from "../internal/extremes.js";
|
|
19
|
+
import { ldexpWide } from "../internal/summary.js";
|
|
20
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
21
|
+
import { formatR } from "./core/simulate.js";
|
|
22
|
+
import { matchChoice } from "./power.js";
|
|
23
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
24
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
25
|
+
import { isOptionsObject } from "../internal/optionalArgs.js";
|
|
26
|
+
const ROC_KEYS_0 = ["controls", "cases"];
|
|
27
|
+
const ROC_KEYS_1 = ["levels", "direction", "naRm"];
|
|
28
|
+
const AUC_KEYS = ["partialAuc", "focus", "correct"];
|
|
29
|
+
const COORDS_KEYS = ["bestMethod", "bestWeights"];
|
|
30
|
+
const ROC_DATA = new WeakMap();
|
|
31
|
+
/** The data a curve was built from (undefined for an object not made by roc, such as a copy) */
|
|
32
|
+
export function rocData(r) {
|
|
33
|
+
return ROC_DATA.get(r);
|
|
34
|
+
}
|
|
35
|
+
const DIRECTIONS = ["auto", "<", ">"];
|
|
36
|
+
/** The label of a response value, as R's as.character (null for a missing value) */
|
|
37
|
+
function labelOf(v) {
|
|
38
|
+
if (v === null || v === undefined)
|
|
39
|
+
return null;
|
|
40
|
+
if (typeof v === "number")
|
|
41
|
+
return Number.isNaN(v) ? null : formatR(v);
|
|
42
|
+
if (typeof v === "boolean")
|
|
43
|
+
return v ? "TRUE" : "FALSE";
|
|
44
|
+
if (typeof v === "string")
|
|
45
|
+
return v;
|
|
46
|
+
throw new TypeError("the response must hold numbers, strings or booleans");
|
|
47
|
+
}
|
|
48
|
+
/** The sorted levels of a response (R's factor levels): numbers numerically, strings by code point, false first */
|
|
49
|
+
function sortedLevels(response) {
|
|
50
|
+
const present = response.filter((v) => labelOf(v) !== null);
|
|
51
|
+
const kinds = new Set(present.map((v) => typeof v));
|
|
52
|
+
if (kinds.size > 1)
|
|
53
|
+
throw new TypeError("the response mixes values of different types");
|
|
54
|
+
const kind = [...kinds][0];
|
|
55
|
+
let sorted;
|
|
56
|
+
if (kind === "number")
|
|
57
|
+
sorted = [...new Set(present)].sort((a, b) => a - b).map(formatR);
|
|
58
|
+
else if (kind === "boolean")
|
|
59
|
+
sorted = [...new Set(present)].sort((a, b) => Number(a) - Number(b)).map((b) => (b ? "TRUE" : "FALSE"));
|
|
60
|
+
else
|
|
61
|
+
sorted = [...new Set(present)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
62
|
+
return [...new Set(sorted)];
|
|
63
|
+
}
|
|
64
|
+
/** Sorted copy */
|
|
65
|
+
function sortedCopy(x) {
|
|
66
|
+
return Float64Array.from(x).sort();
|
|
67
|
+
}
|
|
68
|
+
function tally(controls, cases) {
|
|
69
|
+
const c = sortedCopy(controls);
|
|
70
|
+
const k = sortedCopy(cases);
|
|
71
|
+
const u = [];
|
|
72
|
+
const ctrlLE = [];
|
|
73
|
+
const caseLE = [];
|
|
74
|
+
let i = 0;
|
|
75
|
+
let j = 0;
|
|
76
|
+
while (i < c.length || j < k.length) {
|
|
77
|
+
const v = j >= k.length || (i < c.length && c[i] <= k[j]) ? c[i] : k[j];
|
|
78
|
+
while (i < c.length && c[i] === v)
|
|
79
|
+
i++;
|
|
80
|
+
while (j < k.length && k[j] === v)
|
|
81
|
+
j++;
|
|
82
|
+
u.push(v);
|
|
83
|
+
ctrlLE.push(i);
|
|
84
|
+
caseLE.push(j);
|
|
85
|
+
}
|
|
86
|
+
return { u, ctrlLE, caseLE };
|
|
87
|
+
}
|
|
88
|
+
/** Twice the Mann-Whitney U of the cases against the controls in the curve's direction (an integer) */
|
|
89
|
+
function twiceU(t, n, direction) {
|
|
90
|
+
let u2 = 0;
|
|
91
|
+
for (let i = 0; i < t.u.length; i++) {
|
|
92
|
+
const below = i > 0 ? t.ctrlLE[i - 1] : 0;
|
|
93
|
+
const casesAt = t.caseLE[i] - (i > 0 ? t.caseLE[i - 1] : 0);
|
|
94
|
+
const ctrlAt = t.ctrlLE[i] - below;
|
|
95
|
+
const beaten = direction === "<" ? below : n - t.ctrlLE[i];
|
|
96
|
+
u2 += casesAt * (2 * beaten + ctrlAt);
|
|
97
|
+
}
|
|
98
|
+
return u2;
|
|
99
|
+
}
|
|
100
|
+
/** The AUC of two samples in a direction: U/(mn) from integer counts, rounded once */
|
|
101
|
+
export function aucOf(controls, cases, direction) {
|
|
102
|
+
const n = controls.length;
|
|
103
|
+
const m = cases.length;
|
|
104
|
+
return twiceU(tally(controls, cases), n, direction) / (2 * m * n);
|
|
105
|
+
}
|
|
106
|
+
/** Twice the Mann-Whitney U of two samples in a direction (an integer; the AUC is this over 2mn) */
|
|
107
|
+
export function twiceUOf(controls, cases, direction) {
|
|
108
|
+
return twiceU(tally(controls, cases), controls.length, direction);
|
|
109
|
+
}
|
|
110
|
+
const bitLength = (v) => (v === 0n ? 0 : v.toString(2).length);
|
|
111
|
+
/**
|
|
112
|
+
* The rational num/den rounded once to the nearest double (den nonzero): the quotient to at least 55 bits, with a
|
|
113
|
+
* sticky bit for a remainder, converted by Number (which rounds to nearest, ties to even). A quotient in the
|
|
114
|
+
* subnormal range is rounded twice
|
|
115
|
+
*/
|
|
116
|
+
export function ratioToDouble(num, den) {
|
|
117
|
+
if (den < 0n) {
|
|
118
|
+
num = -num;
|
|
119
|
+
den = -den;
|
|
120
|
+
}
|
|
121
|
+
if (num === 0n)
|
|
122
|
+
return 0;
|
|
123
|
+
const neg = num < 0n;
|
|
124
|
+
const a0 = neg ? -num : num;
|
|
125
|
+
const shift = 55 - (bitLength(a0) - bitLength(den));
|
|
126
|
+
const a = shift >= 0 ? a0 << BigInt(shift) : a0;
|
|
127
|
+
const b = shift >= 0 ? den : den << BigInt(-shift);
|
|
128
|
+
let q = a / b;
|
|
129
|
+
if (q * b !== a)
|
|
130
|
+
q |= 1n;
|
|
131
|
+
const v = ldexpWide(Number(q), -shift);
|
|
132
|
+
return neg ? -v : v;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The threshold between consecutive distinct values a < b (pROC's): the midpoint, from the halves where the sum
|
|
136
|
+
* would pass 1e100; where it rounds onto a or b, b for "<" and a for ">", so that it still separates them
|
|
137
|
+
*/
|
|
138
|
+
function thresholdBetween(a, b, direction) {
|
|
139
|
+
let t = (a + b) / 2;
|
|
140
|
+
if (!(Math.abs(t) <= 1e100))
|
|
141
|
+
t = a / 2 + b / 2;
|
|
142
|
+
if (t === a || t === b)
|
|
143
|
+
t = direction === "<" ? b : a;
|
|
144
|
+
return t;
|
|
145
|
+
}
|
|
146
|
+
/** The curve of two samples in a direction (pROC's stored order: increasing specificity) */
|
|
147
|
+
function curveOf(controls, cases, direction) {
|
|
148
|
+
const t = tally(controls, cases);
|
|
149
|
+
const n = controls.length;
|
|
150
|
+
const m = cases.length;
|
|
151
|
+
const k = t.u.length;
|
|
152
|
+
const thresholds = [];
|
|
153
|
+
const sensitivities = [];
|
|
154
|
+
const specificities = [];
|
|
155
|
+
// point i lies between u[i - 1] and u[i]: counts of the values at most u[i - 1]
|
|
156
|
+
const at = (i) => {
|
|
157
|
+
const thr = i === 0 ? -Infinity : i === k ? Infinity : thresholdBetween(t.u[i - 1], t.u[i], direction);
|
|
158
|
+
const caseLE = i === 0 ? 0 : t.caseLE[i - 1];
|
|
159
|
+
const ctrlLE = i === 0 ? 0 : t.ctrlLE[i - 1];
|
|
160
|
+
thresholds.push(thr);
|
|
161
|
+
sensitivities.push((direction === "<" ? m - caseLE : caseLE) / m);
|
|
162
|
+
specificities.push((direction === "<" ? ctrlLE : n - ctrlLE) / n);
|
|
163
|
+
};
|
|
164
|
+
if (direction === "<")
|
|
165
|
+
for (let i = 0; i <= k; i++)
|
|
166
|
+
at(i);
|
|
167
|
+
else
|
|
168
|
+
for (let i = k; i >= 0; i--)
|
|
169
|
+
at(i);
|
|
170
|
+
return { thresholds, sensitivities, specificities, auc: twiceU(t, n, direction) / (2 * m * n) };
|
|
171
|
+
}
|
|
172
|
+
/** The direction "auto" chooses: "<" when median(controls) <= median(cases) (pROC's rule) */
|
|
173
|
+
function autoDirection(controls, cases) {
|
|
174
|
+
const med = (x) => {
|
|
175
|
+
const s = sortedCopy(x);
|
|
176
|
+
const h = s.length >> 1;
|
|
177
|
+
return s.length % 2 === 1 ? s[h] : midpoint(s[h - 1], s[h]);
|
|
178
|
+
};
|
|
179
|
+
return med(controls) <= med(cases) ? "<" : ">";
|
|
180
|
+
}
|
|
181
|
+
/** Builds the curve from the classes (checked, without missing values), and records its data */
|
|
182
|
+
export function buildRoc(controls, cases, direction, levels, data, warnings) {
|
|
183
|
+
if (controls.length === 0)
|
|
184
|
+
throw new Error("No control observation.");
|
|
185
|
+
if (cases.length === 0)
|
|
186
|
+
throw new Error("No case observation.");
|
|
187
|
+
// (pROC returns NaN with a warning: the order of the values is defined, but pROC refuses them)
|
|
188
|
+
if (controls.some((v) => !Number.isFinite(v)) || cases.some((v) => !Number.isFinite(v))) {
|
|
189
|
+
throw new RangeError("infinite values in the predictor: cannot build a valid ROC curve");
|
|
190
|
+
}
|
|
191
|
+
const dir = direction === "auto" ? autoDirection(controls, cases) : direction;
|
|
192
|
+
const curve = curveOf(controls, cases, dir);
|
|
193
|
+
const result = { ...curve, direction: dir, levels, controls, cases, warnings };
|
|
194
|
+
ROC_DATA.set(result, data);
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
function checkDirection(d) {
|
|
198
|
+
if (d === undefined)
|
|
199
|
+
return "auto";
|
|
200
|
+
if (!DIRECTIONS.includes(d))
|
|
201
|
+
throw new RangeError(`'arg' should be one of “auto”, “<”, “>”`);
|
|
202
|
+
return d;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The curve of a response and a predictor: observations with a missing response or predictor dropped (or an
|
|
206
|
+
* error), the levels, and the classes
|
|
207
|
+
*/
|
|
208
|
+
export function rocFromResponse(response, predictor, options) {
|
|
209
|
+
const direction = checkDirection(options.direction);
|
|
210
|
+
const w = new Warnings();
|
|
211
|
+
const labels = response.map(labelOf);
|
|
212
|
+
let levels;
|
|
213
|
+
if (options.levels === undefined) {
|
|
214
|
+
levels = sortedLevels(response);
|
|
215
|
+
if (levels.length > 2) {
|
|
216
|
+
w.add("'response' has more than two levels. Consider setting 'levels' explicitly or using 'multiclass.roc' instead");
|
|
217
|
+
levels = levels.slice(0, 2);
|
|
218
|
+
}
|
|
219
|
+
if (levels.length < 2)
|
|
220
|
+
throw new RangeError("'response' must have two levels");
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
if (!Array.isArray(options.levels) || options.levels.length !== 2)
|
|
224
|
+
throw new RangeError("'levels' argument must have length 2");
|
|
225
|
+
levels = options.levels.map((v) => {
|
|
226
|
+
const l = labelOf(v);
|
|
227
|
+
if (l === null)
|
|
228
|
+
throw new RangeError("'levels' must not be missing");
|
|
229
|
+
return l;
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
if (predictor.some((v) => typeof v !== "number"))
|
|
233
|
+
throw new TypeError("Predictor must be numeric.");
|
|
234
|
+
if (labels.length !== predictor.length)
|
|
235
|
+
throw new TypeError("Response and predictor must be vectors of the same length.");
|
|
236
|
+
const missing = labels.map((l, i) => l === null || Number.isNaN(predictor[i]));
|
|
237
|
+
if (options.naRm === false && missing.some((b) => b)) {
|
|
238
|
+
throw new RangeError("missing values in the response or the predictor with naRm false");
|
|
239
|
+
}
|
|
240
|
+
const controls = [];
|
|
241
|
+
const cases = [];
|
|
242
|
+
const values = [];
|
|
243
|
+
const isCase = [];
|
|
244
|
+
const kept = [];
|
|
245
|
+
labels.forEach((l, i) => {
|
|
246
|
+
if (missing[i])
|
|
247
|
+
return;
|
|
248
|
+
const v = predictor[i];
|
|
249
|
+
if (l === levels[0])
|
|
250
|
+
controls.push(v);
|
|
251
|
+
else if (l === levels[1])
|
|
252
|
+
cases.push(v);
|
|
253
|
+
else
|
|
254
|
+
return;
|
|
255
|
+
values.push(v);
|
|
256
|
+
isCase.push(l === levels[1]);
|
|
257
|
+
kept.push(i);
|
|
258
|
+
});
|
|
259
|
+
const data = { labels, predictor: [...predictor], values, isCase, kept };
|
|
260
|
+
return buildRoc(controls, cases, direction, [levels[0], levels[1]], data, w.list);
|
|
261
|
+
}
|
|
262
|
+
/** The response and predictor of a formula `response ~ predictor` (rows with a missing value dropped) */
|
|
263
|
+
function formulaData(formula, data) {
|
|
264
|
+
const terms = termsOf(parseFormula(formula), Object.keys(data));
|
|
265
|
+
if (terms.response !== 0 || terms.variables.length !== 2 || terms.terms.length !== 1) {
|
|
266
|
+
throw new TypeError("the formula must be of the form response ~ predictor");
|
|
267
|
+
}
|
|
268
|
+
const frame = modelFrame(data, terms.variables);
|
|
269
|
+
const [rv, pv] = frame.variables;
|
|
270
|
+
if (pv.kind !== "numeric")
|
|
271
|
+
throw new TypeError("Predictor must be numeric.");
|
|
272
|
+
const response = rv.kind === "numeric" ? rv.values : rv.codes.map((c) => rv.levels[c]);
|
|
273
|
+
return { response, predictor: pv.values };
|
|
274
|
+
}
|
|
275
|
+
/** Whether a value is a plain object (not an array or a typed array) */
|
|
276
|
+
function isPlainObject(v) {
|
|
277
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && !ArrayBuffer.isView(v);
|
|
278
|
+
}
|
|
279
|
+
export function roc(x, y, options = {}) {
|
|
280
|
+
if (isOptionsObject(x))
|
|
281
|
+
checkOptions(x, ROC_KEYS_0, "roc"); // generated: option-keys.mjs
|
|
282
|
+
if (typeof x !== "string" && isOptionsObject(y))
|
|
283
|
+
checkOptions(y, ROC_KEYS_1, "roc"); // generated: option-keys.mjs
|
|
284
|
+
checkOptions(options, ROC_KEYS_1, "roc"); // generated: option-keys.mjs
|
|
285
|
+
if (typeof x === "string") {
|
|
286
|
+
const d = formulaData(x, y);
|
|
287
|
+
return reported("roc", rocFromResponse(d.response, d.predictor, options));
|
|
288
|
+
}
|
|
289
|
+
if (isPlainObject(x)) {
|
|
290
|
+
const opts = (y ?? {});
|
|
291
|
+
if (opts.levels !== undefined)
|
|
292
|
+
throw new RangeError("'levels' cannot be given with controls and cases");
|
|
293
|
+
const s = x;
|
|
294
|
+
if (s.controls === undefined || s.cases === undefined)
|
|
295
|
+
throw new TypeError("'controls' and 'cases' must both be given");
|
|
296
|
+
const direction = checkDirection(opts.direction);
|
|
297
|
+
const controls0 = Array.from(s.controls);
|
|
298
|
+
const cases0 = Array.from(s.cases);
|
|
299
|
+
if ([...controls0, ...cases0].some((v) => typeof v !== "number"))
|
|
300
|
+
throw new TypeError("Predictor must be numeric.");
|
|
301
|
+
if (opts.naRm === false && [...controls0, ...cases0].some(Number.isNaN)) {
|
|
302
|
+
throw new RangeError("missing values in the controls or the cases with naRm false");
|
|
303
|
+
}
|
|
304
|
+
const controls = controls0.filter((v) => !Number.isNaN(v));
|
|
305
|
+
const cases = cases0.filter((v) => !Number.isNaN(v));
|
|
306
|
+
const values = [...controls, ...cases];
|
|
307
|
+
const data = {
|
|
308
|
+
labels: null,
|
|
309
|
+
predictor: values,
|
|
310
|
+
values,
|
|
311
|
+
isCase: values.map((_, i) => i >= controls.length),
|
|
312
|
+
kept: values.map((_, i) => i),
|
|
313
|
+
};
|
|
314
|
+
return reported("roc", buildRoc(controls, cases, direction, ["0", "1"], data, []));
|
|
315
|
+
}
|
|
316
|
+
return reported("roc", rocFromResponse(Array.from(x), Array.from(y), options));
|
|
317
|
+
}
|
|
318
|
+
/** y at x = v on the segment from point j to point i (pROC's interpolation, written as in the description) */
|
|
319
|
+
const interpolate = (x, y, v, from, to) => y[from] + ((v - x[from]) / (x[to] - x[from])) * (y[to] - y[from]);
|
|
320
|
+
/** The area under y(x) between lo and hi, x nondecreasing from 0 to 1 */
|
|
321
|
+
function partialArea(x, y, lo, hi) {
|
|
322
|
+
const inside = [];
|
|
323
|
+
x.forEach((v, i) => {
|
|
324
|
+
if (v >= lo && v <= hi)
|
|
325
|
+
inside.push(i);
|
|
326
|
+
});
|
|
327
|
+
if (inside.length === 0) {
|
|
328
|
+
const j = x.findIndex((v) => v >= hi);
|
|
329
|
+
const i = j - 1;
|
|
330
|
+
const yHi = interpolate(x, y, hi, j, i);
|
|
331
|
+
const yLo = interpolate(x, y, lo, j, i);
|
|
332
|
+
return ((yHi + yLo) / 2) * (hi - lo);
|
|
333
|
+
}
|
|
334
|
+
let area = 0;
|
|
335
|
+
for (let k = 1; k < inside.length; k++) {
|
|
336
|
+
const p = inside[k - 1];
|
|
337
|
+
const q = inside[k];
|
|
338
|
+
area += ((x[q] - x[p]) * (y[p] + y[q])) / 2;
|
|
339
|
+
}
|
|
340
|
+
const last = inside[inside.length - 1];
|
|
341
|
+
if (x[last] !== hi) {
|
|
342
|
+
const j = x.findIndex((v) => v >= hi);
|
|
343
|
+
const i = j - 1;
|
|
344
|
+
const yHi = interpolate(x, y, hi, j, i);
|
|
345
|
+
area += ((hi - x[i]) * (y[i] + yHi)) / 2;
|
|
346
|
+
}
|
|
347
|
+
const first = inside[0];
|
|
348
|
+
if (x[first] !== lo) {
|
|
349
|
+
const j = x.findIndex((v) => v > lo) - 1;
|
|
350
|
+
const i = j + 1;
|
|
351
|
+
const yLo = interpolate(x, y, lo, i, j);
|
|
352
|
+
area += ((x[i] - lo) * (y[i] + yLo)) / 2;
|
|
353
|
+
}
|
|
354
|
+
return area;
|
|
355
|
+
}
|
|
356
|
+
const qAdd = (a, b) => [a[0] * b[1] + b[0] * a[1], a[1] * b[1]];
|
|
357
|
+
const qSub = (a, b) => [a[0] * b[1] - b[0] * a[1], a[1] * b[1]];
|
|
358
|
+
const qMul = (a, b) => [a[0] * b[0], a[1] * b[1]];
|
|
359
|
+
const qDiv = (a, b) => (b[0] < 0n ? [-a[0] * b[1], -a[1] * b[0]] : [a[0] * b[1], a[1] * b[0]]);
|
|
360
|
+
const qCmp = (a, b) => {
|
|
361
|
+
const d = a[0] * b[1] - b[0] * a[1];
|
|
362
|
+
return d < 0n ? -1 : d > 0n ? 1 : 0;
|
|
363
|
+
};
|
|
364
|
+
/** The integer numerators of proportions v[k] = count/size, or undefined when a value is not such a quotient */
|
|
365
|
+
function countsOf(v, size) {
|
|
366
|
+
if (!(size >= 1))
|
|
367
|
+
return undefined;
|
|
368
|
+
const out = v.map((p) => Math.round(p * size));
|
|
369
|
+
return out.every((c, k) => c / size === v[k]) ? out : undefined;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* McClish's standardised partial AUC computed exactly and rounded once. For a curve made by roc the points are
|
|
373
|
+
* count/size, and the counts give the exact proportions; for any other curve (a hand-built or edited object) each
|
|
374
|
+
* coordinate is taken as the exact value of its double (a dyadic rational), so the result is correctly rounded and
|
|
375
|
+
* the decision "below the diagonal" is exact in both cases.
|
|
376
|
+
*
|
|
377
|
+
* The excess of the curve over the diagonal at a point, e = y - (1 - x), has the integer numerator
|
|
378
|
+
* Y dx + X dy - dx dy over dx dy, so A - min is the integral of the piecewise linear e between the limits (the
|
|
379
|
+
* trapezoids of the points within them, and the pieces up to the limits interpolated linearly, as partialArea), and
|
|
380
|
+
* max - min = (hi - lo)(hi + lo)/2. Formed in doubles both cancel: a curve on the diagonal came out below it
|
|
381
|
+
* (an error), and limits near 0 lost digits and gave 0/0
|
|
382
|
+
*/
|
|
383
|
+
function mcClishExact(xs, ys, dx, dy, lo, hi) {
|
|
384
|
+
const X = countsOf(xs, dx);
|
|
385
|
+
const Y = countsOf(ys, dy);
|
|
386
|
+
if (X !== undefined && Y !== undefined) {
|
|
387
|
+
return mcClishFromIntegers(X.map(BigInt), Y.map(BigInt), BigInt(dx), BigInt(dy), lo, hi);
|
|
388
|
+
}
|
|
389
|
+
// not counts: the doubles' own rationals over the common denominator 2^K
|
|
390
|
+
const ok = xs.length >= 2 && xs.length === ys.length && xs[0] === 0 && xs[xs.length - 1] === 1 &&
|
|
391
|
+
xs.every((v, k) => v >= 0 && v <= 1 && (k === 0 || v >= xs[k - 1])) && ys.every((v) => v >= 0 && v <= 1);
|
|
392
|
+
if (!ok) {
|
|
393
|
+
throw new RangeError("the curve's sensitivities and specificities must be numbers in [0, 1] forming a ROC curve (use a curve from roc)");
|
|
394
|
+
}
|
|
395
|
+
const rx = xs.map(toRational);
|
|
396
|
+
const ry = ys.map(toRational);
|
|
397
|
+
let K = 0n;
|
|
398
|
+
for (const [, d] of [...rx, ...ry])
|
|
399
|
+
K = d > K ? d : K;
|
|
400
|
+
const scaled = (r) => r[0] * (K / r[1]);
|
|
401
|
+
return mcClishFromIntegers(rx.map(scaled), ry.map(scaled), K, K, lo, hi);
|
|
402
|
+
}
|
|
403
|
+
/** McClish's standardised partial AUC of the points (X/dx, Y/dy), exactly, rounded once */
|
|
404
|
+
function mcClishFromIntegers(X, Y, bdx, bdy, lo, hi) {
|
|
405
|
+
const D = bdx * bdy;
|
|
406
|
+
const e = (k) => [Y[k] * bdx + X[k] * bdy - D, D];
|
|
407
|
+
const x = (k) => [X[k], bdx];
|
|
408
|
+
const L = toRational(lo);
|
|
409
|
+
const H = toRational(hi);
|
|
410
|
+
// e at v on the segment from point i to point j
|
|
411
|
+
const eAt = (v, i, j) => qAdd(e(i), qMul(qDiv(qSub(v, x(i)), qSub(x(j), x(i))), qSub(e(j), e(i))));
|
|
412
|
+
const inside = [];
|
|
413
|
+
X.forEach((_, k) => {
|
|
414
|
+
if (qCmp(x(k), L) >= 0 && qCmp(x(k), H) <= 0)
|
|
415
|
+
inside.push(k);
|
|
416
|
+
});
|
|
417
|
+
let excess;
|
|
418
|
+
if (inside.length === 0) {
|
|
419
|
+
const j = X.findIndex((_, k) => qCmp(x(k), H) >= 0);
|
|
420
|
+
const i = j - 1;
|
|
421
|
+
excess = qMul(qAdd(eAt(H, i, j), eAt(L, i, j)), qMul(qSub(H, L), [1n, 2n]));
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
// the trapezoids within the limits: sum (X_q - X_p)(E_p + E_q) over 2 dx D
|
|
425
|
+
let t = 0n;
|
|
426
|
+
for (let k = 1; k < inside.length; k++) {
|
|
427
|
+
const p = inside[k - 1];
|
|
428
|
+
const q = inside[k];
|
|
429
|
+
t += (X[q] - X[p]) * (e(p)[0] + e(q)[0]);
|
|
430
|
+
}
|
|
431
|
+
excess = [t, 2n * bdx * D];
|
|
432
|
+
const last = inside[inside.length - 1];
|
|
433
|
+
if (qCmp(x(last), H) !== 0) {
|
|
434
|
+
const j = last + 1;
|
|
435
|
+
excess = qAdd(excess, qMul(qSub(H, x(last)), qMul(qAdd(e(last), eAt(H, last, j)), [1n, 2n])));
|
|
436
|
+
}
|
|
437
|
+
const first = inside[0];
|
|
438
|
+
if (qCmp(x(first), L) !== 0) {
|
|
439
|
+
const j = first - 1;
|
|
440
|
+
excess = qAdd(excess, qMul(qSub(x(first), L), qMul(qAdd(e(first), eAt(L, first, j)), [1n, 2n])));
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (excess[0] < 0n)
|
|
444
|
+
throw new Error("Partial AUC correction not defined for ROC curves below the diagonal.");
|
|
445
|
+
// (1 + (A - min)/(max - min))/2 with max - min = (hi - lo)(hi + lo)/2
|
|
446
|
+
const span = qMul(qMul(qSub(H, L), qAdd(H, L)), [1n, 2n]);
|
|
447
|
+
const r = qDiv(qAdd(span, excess), qMul(span, [2n, 1n]));
|
|
448
|
+
return ratioToDouble(r[0], r[1]);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The area under a ROC curve, or the partial area between two specificities or sensitivities. Equivalent to
|
|
452
|
+
* `pROC::auc()` in R.
|
|
453
|
+
*
|
|
454
|
+
* The partial area sums the trapezoids of the points within the limits and interpolates the curve linearly at the
|
|
455
|
+
* limits. With `correct`, it is standardised as McClish (1989): (1 + (A − min)/(max − min))/2, with min the area under
|
|
456
|
+
* the diagonal and max that of the perfect curve between the limits, computed exactly from the counts of the points and
|
|
457
|
+
* rounded once (a curve on the diagonal gives 0.5); below the diagonal that is undefined, an error (pROC: NA with a
|
|
458
|
+
* warning). Limits outside [0, 1] are an error (pROC: NA).
|
|
459
|
+
*
|
|
460
|
+
* @param curve A curve from {@link roc}.
|
|
461
|
+
* @param options See {@link AucOptions}.
|
|
462
|
+
*
|
|
463
|
+
* @example
|
|
464
|
+
* ```ts
|
|
465
|
+
* const r = roc({ controls: [1, 2, 2, 3, 5, 7], cases: [2, 4, 5, 5, 8, 9, 10] });
|
|
466
|
+
* auc(r).auc; // 0.7857142857142857
|
|
467
|
+
* auc(r, { partialAuc: [1, 0.8] }).auc; // 0.08666666666666666
|
|
468
|
+
* auc(r, { partialAuc: [1, 0.8], correct: true }).auc; // 0.6851851851851852
|
|
469
|
+
* ```
|
|
470
|
+
*
|
|
471
|
+
* @category Hypothesis tests
|
|
472
|
+
*/
|
|
473
|
+
export function auc(curve, options = {}) {
|
|
474
|
+
checkOptions(options, AUC_KEYS, "auc"); // generated: option-keys.mjs
|
|
475
|
+
const focus = matchChoice(options.focus, ["specificity", "sensitivity"]);
|
|
476
|
+
const correct = options.correct ?? false;
|
|
477
|
+
if (options.partialAuc === undefined) {
|
|
478
|
+
return reported("auc", { auc: curve.auc, partialAuc: null, focus, correct, warnings: [] });
|
|
479
|
+
}
|
|
480
|
+
const pa = options.partialAuc;
|
|
481
|
+
if (!Array.isArray(pa) || pa.length !== 2 || pa.some((v) => typeof v !== "number")) {
|
|
482
|
+
throw new TypeError("partialAuc must be a numeric vector of length 2");
|
|
483
|
+
}
|
|
484
|
+
const hi = Math.max(pa[0], pa[1]);
|
|
485
|
+
const lo = Math.min(pa[0], pa[1]);
|
|
486
|
+
if (!(lo >= 0 && hi <= 1))
|
|
487
|
+
throw new RangeError("the limits of partialAuc must be within [0, 1]");
|
|
488
|
+
if (!(lo < hi))
|
|
489
|
+
throw new RangeError("the limits of partialAuc must differ");
|
|
490
|
+
const se = curve.sensitivities;
|
|
491
|
+
const sp = curve.specificities;
|
|
492
|
+
const [x, y] = focus === "specificity" ? [sp, se] : [[...se].reverse(), [...sp].reverse()];
|
|
493
|
+
let area;
|
|
494
|
+
const n = curve.controls.length;
|
|
495
|
+
const m = curve.cases.length;
|
|
496
|
+
if (correct)
|
|
497
|
+
area = focus === "specificity" ? mcClishExact(x, y, n, m, lo, hi) : mcClishExact(x, y, m, n, lo, hi);
|
|
498
|
+
else
|
|
499
|
+
area = partialArea(x, y, lo, hi);
|
|
500
|
+
return reported("auc", { auc: area, partialAuc: [hi, lo], focus, correct, warnings: [] });
|
|
501
|
+
}
|
|
502
|
+
/** A finite double as an exact rational num/den (den a power of 2) */
|
|
503
|
+
function toRational(v) {
|
|
504
|
+
if (v === 0)
|
|
505
|
+
return [0n, 1n];
|
|
506
|
+
let e = 0;
|
|
507
|
+
let m = v;
|
|
508
|
+
while (!Number.isInteger(m)) {
|
|
509
|
+
m *= 2;
|
|
510
|
+
e++;
|
|
511
|
+
}
|
|
512
|
+
return [BigInt(m), 1n << BigInt(e)];
|
|
513
|
+
}
|
|
514
|
+
/** The integer counts at given thresholds */
|
|
515
|
+
function countsAt(curve, thresholds) {
|
|
516
|
+
const c = sortedCopy(curve.controls);
|
|
517
|
+
const k = sortedCopy(curve.cases);
|
|
518
|
+
// the number of values below v (strictly, or at most v)
|
|
519
|
+
const below = (s, v, orEqual) => {
|
|
520
|
+
let lo = 0;
|
|
521
|
+
let hi = s.length;
|
|
522
|
+
while (lo < hi) {
|
|
523
|
+
const mid = (lo + hi) >> 1;
|
|
524
|
+
if (orEqual ? s[mid] <= v : s[mid] < v)
|
|
525
|
+
lo = mid + 1;
|
|
526
|
+
else
|
|
527
|
+
hi = mid;
|
|
528
|
+
}
|
|
529
|
+
return lo;
|
|
530
|
+
};
|
|
531
|
+
const lt = curve.direction === "<";
|
|
532
|
+
return {
|
|
533
|
+
tp: thresholds.map((t) => (lt ? k.length - below(k, t, false) : below(k, t, true))),
|
|
534
|
+
tn: thresholds.map((t) => (lt ? below(c, t, false) : c.length - below(c, t, true))),
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Coordinates of a ROC curve: sensitivity, specificity, the counts, predictive values, likelihood ratios and the
|
|
539
|
+
* criteria of the best threshold, at every point of the curve, at the best threshold(s) or at given thresholds.
|
|
540
|
+
* Equivalent to `pROC::coords(roc, x, ret = "all")` in R.
|
|
541
|
+
*
|
|
542
|
+
* Every column is computed from the integer counts of each threshold and rounded once (pROC rebuilds the counts from
|
|
543
|
+
* the proportions, so that they are not always integers, and loses digits in 1 − specificity). The rows of `"best"`
|
|
544
|
+
* are all the points whose criterion equals the best one exactly (pROC compares rounded sums and can lose ties). At a
|
|
545
|
+
* given threshold, an observation equal to it counts as positive.
|
|
546
|
+
*
|
|
547
|
+
* @param curve A curve from {@link roc}.
|
|
548
|
+
* @param x `"all"` (default: every point of the curve), `"best"`, or thresholds (a number or an array).
|
|
549
|
+
* @param options See {@link CoordsOptions}.
|
|
550
|
+
*
|
|
551
|
+
* @example
|
|
552
|
+
* ```ts
|
|
553
|
+
* const r = roc({ controls: [1, 2, 2, 3, 5, 7], cases: [2, 4, 5, 5, 8, 9, 10] });
|
|
554
|
+
* const best = coords(r, "best");
|
|
555
|
+
* best.threshold; // [3.5]
|
|
556
|
+
* best.sensitivity; // [0.8571428571428571]
|
|
557
|
+
* coords(r, [4, 6]).tp; // [6, 3]
|
|
558
|
+
* ```
|
|
559
|
+
*
|
|
560
|
+
* @category Hypothesis tests
|
|
561
|
+
*/
|
|
562
|
+
export function coords(curve, x = "all", options = {}) {
|
|
563
|
+
checkOptions(options, COORDS_KEYS, "coords"); // generated: option-keys.mjs
|
|
564
|
+
const bestMethod = matchChoice(options.bestMethod, ["youden", "closest.topleft", "topleft"]);
|
|
565
|
+
const weights = options.bestWeights ?? [1, 0.5];
|
|
566
|
+
if (!Array.isArray(weights) || weights.length !== 2 || weights.some((v) => typeof v !== "number")) {
|
|
567
|
+
throw new TypeError("'best.weights' must be a numeric vector of length 2");
|
|
568
|
+
}
|
|
569
|
+
const [cost, prevalence] = weights;
|
|
570
|
+
if (!(prevalence > 0 && prevalence < 1))
|
|
571
|
+
throw new RangeError("prevalence ('best.weights[2]') must be in the interval ]0,1[.");
|
|
572
|
+
// (pROC does not check the cost: 0 gives r = Inf, a negative cost a negative r)
|
|
573
|
+
if (!(cost > 0 && cost < Infinity))
|
|
574
|
+
throw new RangeError("the cost ('bestWeights[0]') must be a positive finite number");
|
|
575
|
+
const r = (1 - prevalence) / (cost * prevalence);
|
|
576
|
+
let thresholds;
|
|
577
|
+
let pick = null;
|
|
578
|
+
if (typeof x === "string")
|
|
579
|
+
pick = matchChoice(x, ["all", "best"]);
|
|
580
|
+
if (pick !== null)
|
|
581
|
+
thresholds = [...curve.thresholds];
|
|
582
|
+
else {
|
|
583
|
+
thresholds = typeof x === "number" ? [x] : Array.from(x);
|
|
584
|
+
if (thresholds.length === 0)
|
|
585
|
+
throw new RangeError("Numeric 'x' has length 0");
|
|
586
|
+
if (thresholds.some((v) => typeof v !== "number" || Number.isNaN(v)))
|
|
587
|
+
throw new RangeError("the thresholds must be numbers (not NaN)");
|
|
588
|
+
}
|
|
589
|
+
const P = curve.cases.length;
|
|
590
|
+
const N = curve.controls.length;
|
|
591
|
+
let { tp, tn } = countsAt(curve, thresholds);
|
|
592
|
+
if (pick === "best") {
|
|
593
|
+
// the criteria compared exactly: youden se + r sp times P N rd, closest.topleft minus its distance times P² N² rd,
|
|
594
|
+
// with r = rn/rd the exact rational of the double weights: r = (1 - w2)/(w1 w2) = (d2 - n2) d1/(n1 n2)
|
|
595
|
+
const [n1, d1] = toRational(cost);
|
|
596
|
+
const [n2, d2] = toRational(prevalence);
|
|
597
|
+
const rn = (d2 - n2) * d1;
|
|
598
|
+
const rd = n1 * n2;
|
|
599
|
+
const bP = BigInt(P);
|
|
600
|
+
const bN = BigInt(N);
|
|
601
|
+
const crit = tp.map((t, i) => {
|
|
602
|
+
if (bestMethod === "youden")
|
|
603
|
+
return BigInt(t) * bN * rd + rn * BigInt(tn[i]) * bP;
|
|
604
|
+
const fn = BigInt(P - t);
|
|
605
|
+
const fp = BigInt(N - tn[i]);
|
|
606
|
+
return -(fn * fn * bN * bN * rd + rn * fp * fp * bP * bP);
|
|
607
|
+
});
|
|
608
|
+
const best = crit.reduce((a, b) => (b > a ? b : a));
|
|
609
|
+
const rows = crit.map((c, i) => (c === best ? i : -1)).filter((i) => i >= 0);
|
|
610
|
+
thresholds = rows.map((i) => thresholds[i]);
|
|
611
|
+
tp = rows.map((i) => tp[i]);
|
|
612
|
+
tn = rows.map((i) => tn[i]);
|
|
613
|
+
}
|
|
614
|
+
const fn = tp.map((t) => P - t);
|
|
615
|
+
const fp = tn.map((t) => N - t);
|
|
616
|
+
return reported("coords", {
|
|
617
|
+
threshold: thresholds,
|
|
618
|
+
sensitivity: tp.map((t) => t / P),
|
|
619
|
+
specificity: tn.map((t) => t / N),
|
|
620
|
+
accuracy: tp.map((t, i) => (t + tn[i]) / (P + N)),
|
|
621
|
+
tn,
|
|
622
|
+
tp,
|
|
623
|
+
fn,
|
|
624
|
+
fp,
|
|
625
|
+
npv: tn.map((t, i) => t / (t + fn[i])),
|
|
626
|
+
ppv: tp.map((t, i) => t / (t + fp[i])),
|
|
627
|
+
fpr: fp.map((f) => f / N),
|
|
628
|
+
// (tp N)/(P fp) and (fn N)/(P tn): integer products below 2^53, one rounding
|
|
629
|
+
lrPos: tp.map((t, i) => (t * N) / (P * fp[i])),
|
|
630
|
+
lrNeg: fn.map((f, i) => (f * N) / (P * tn[i])),
|
|
631
|
+
youden: tp.map((t, i) => t / P + r * (tn[i] / N)),
|
|
632
|
+
closestTopleft: fn.map((f, i) => (f / P) ** 2 + r * (fp[i] / N) ** 2),
|
|
633
|
+
warnings: [],
|
|
634
|
+
});
|
|
635
|
+
}
|