@numero-uno-jpn/rstats 1.17.0 → 1.19.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 +39 -0
- package/README.ja.md +7 -7
- package/README.md +7 -7
- package/dist/causal/mediationProcedures.js +18 -1
- package/dist/causal/moderation.js +11 -2
- package/dist/causal.js +2 -2
- package/dist/chunks/chunk-2S45NNTL.js +2 -0
- package/dist/chunks/chunk-4JFGT4PN.js +2 -0
- package/dist/chunks/chunk-4JRJU5F5.js +2 -0
- package/dist/chunks/{chunk-KY53MB3J.js → chunk-5NW4WT4F.js} +2 -2
- package/dist/chunks/chunk-6ZGEYAFC.js +2 -0
- package/dist/chunks/{chunk-XR7Y4ZV6.js → chunk-7D7FBLWD.js} +2 -2
- package/dist/chunks/chunk-ANFN3X2M.js +2 -0
- package/dist/chunks/{chunk-NCRL33PQ.js → chunk-AS2XTRHH.js} +2 -2
- package/dist/chunks/chunk-BJ5WAL2C.js +2 -0
- package/dist/chunks/{chunk-EIUK6TKF.js → chunk-CEOSH3H2.js} +2 -2
- package/dist/chunks/{chunk-VZSQAGL2.js → chunk-CMNKXRZF.js} +2 -2
- package/dist/chunks/{chunk-XEJX5HBJ.js → chunk-CNJLPH6W.js} +2 -2
- package/dist/chunks/{chunk-TTOJDLIQ.js → chunk-DXSVV47D.js} +2 -2
- package/dist/chunks/{chunk-GIIURG5X.js → chunk-FAKOND5W.js} +2 -2
- package/dist/chunks/chunk-FCGTZ6BD.js +2 -0
- package/dist/chunks/{chunk-O4D43LWM.js → chunk-FELX2TZZ.js} +2 -2
- package/dist/chunks/{chunk-EB45CDFA.js → chunk-G4B2SQR6.js} +2 -2
- package/dist/chunks/chunk-HPIZAWMT.js +2 -0
- package/dist/chunks/chunk-I5XUWUEV.js +2 -0
- package/dist/chunks/{chunk-JG4TWDQ4.js → chunk-ILQ4VWSD.js} +2 -2
- package/dist/chunks/chunk-JLFRYDYO.js +2 -0
- package/dist/chunks/{chunk-GTSK4IN4.js → chunk-JXKHFSGK.js} +1 -1
- package/dist/chunks/{chunk-YMI33F7W.js → chunk-LBU73UMS.js} +2 -2
- package/dist/chunks/{chunk-ZRKXHVTJ.js → chunk-LSZTDKIB.js} +2 -2
- package/dist/chunks/chunk-LWFKGF43.js +2 -0
- package/dist/chunks/{chunk-NCDPZSI2.js → chunk-M5J3DHXB.js} +2 -2
- package/dist/chunks/{chunk-DD2GG4EC.js → chunk-MOYWWJP4.js} +1 -1
- package/dist/chunks/{chunk-I2KJMF4G.js → chunk-MPBFXHXT.js} +1 -1
- package/dist/chunks/chunk-NWNJEAKI.js +2 -0
- package/dist/chunks/{chunk-GOYTZ5RB.js → chunk-OTETSONJ.js} +2 -2
- package/dist/chunks/{chunk-V54MBEJM.js → chunk-QH4GK3JN.js} +2 -2
- package/dist/chunks/chunk-QVE7V5UG.js +2 -0
- package/dist/chunks/{chunk-RNGDVSTS.js → chunk-RMGEIU4Z.js} +2 -2
- package/dist/chunks/{chunk-LKKUUREA.js → chunk-SAFH76DR.js} +2 -2
- package/dist/chunks/{chunk-QCPGV7XH.js → chunk-SJJJ7Y4X.js} +2 -2
- package/dist/chunks/{chunk-L77QFL3C.js → chunk-TVU4N6BA.js} +2 -2
- package/dist/chunks/{chunk-6MLDKHTY.js → chunk-U6RXYALO.js} +2 -2
- package/dist/chunks/chunk-VNLSP22M.js +2 -0
- package/dist/chunks/chunk-W4EITKLJ.js +2 -0
- package/dist/chunks/{chunk-JHABMYNH.js → chunk-WWRKCRTZ.js} +1 -1
- package/dist/chunks/{chunk-NPWWGIFG.js → chunk-XHHDBEHB.js} +2 -2
- package/dist/chunks/{chunk-72I7GDWL.js → chunk-XJMBX6A2.js} +2 -2
- package/dist/chunks/chunk-YZ6SBFFG.js +2 -0
- package/dist/descriptive/qcc.d.ts +320 -0
- package/dist/descriptive/qcc.js +524 -0
- package/dist/descriptive/qccTools.d.ts +301 -0
- package/dist/descriptive/qccTools.js +390 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/normal.d.ts +4 -0
- package/dist/distributions/normal.js +4 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +2 -0
- package/dist/entries/descriptive.js +2 -0
- package/dist/entries/regression.d.ts +1 -0
- package/dist/entries/regression.js +2 -0
- package/dist/entries/tests.d.ts +1 -0
- package/dist/entries/tests.js +1 -0
- package/dist/htest/timeROC.d.ts +564 -0
- package/dist/htest/timeROC.js +1106 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/betareg.js +14 -2
- package/dist/models/bradleyterry.d.ts +188 -0
- package/dist/models/bradleyterry.js +533 -0
- package/dist/models/survreg.d.ts +5 -0
- package/dist/models/survreg.js +23 -3
- package/dist/models/tobit.js +16 -5
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +18 -18
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries.js +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-23QCIPET.js +0 -2
- package/dist/chunks/chunk-3UEYA6VG.js +0 -2
- package/dist/chunks/chunk-3Y4DNK4O.js +0 -2
- package/dist/chunks/chunk-4BGGWQWS.js +0 -2
- package/dist/chunks/chunk-5UFVACSV.js +0 -2
- package/dist/chunks/chunk-5W2OZAHQ.js +0 -2
- package/dist/chunks/chunk-BWDXJL7T.js +0 -2
- package/dist/chunks/chunk-GLABB425.js +0 -2
- package/dist/chunks/chunk-JV3POOET.js +0 -2
- package/dist/chunks/chunk-K3YSXDTU.js +0 -2
- package/dist/chunks/chunk-LY2UZGUL.js +0 -2
- package/dist/chunks/chunk-PSQ6MLJM.js +0 -2
- package/dist/chunks/chunk-RM5D7Q7W.js +0 -2
- package/dist/chunks/chunk-SA2E5GVO.js +0 -2
- package/dist/chunks/chunk-T5ZALLTJ.js +0 -2
- package/dist/chunks/chunk-XPYZOG5H.js +0 -2
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
// Time-dependent ROC curves for censored event times (1.19.0): timeROC's estimators (Blanche, Dartigues and
|
|
2
|
+
// Jacqmin-Gadda 2013) with marginal (Kaplan-Meier), Cox or Aalen inverse probability of censoring weights, a single
|
|
3
|
+
// event or competing risks, the iid representation and the standard errors, confint, compare and SeSpPPVNPV; and
|
|
4
|
+
// survivalROC's Kaplan-Meier estimator (Heagerty, Lumley and Pepe 2000). The behaviour is in
|
|
5
|
+
// oracle/tdroc-behaviour.md, the R experiments behind it in experiments/tdroc119-*.R (log experiments/tdroc119-log.md).
|
|
6
|
+
//
|
|
7
|
+
// Every estimate is a ratio of weighted totals W(f) = sum_i w_i f_i / n, w_i the subject's weight at the evaluation
|
|
8
|
+
// time t: 1 / G(T_i-) for a subject with an event at T_i <= t, 1 / G(t) for a subject with T_i > t, 0 otherwise. With
|
|
9
|
+
// the marginal weights, the influence of a total is w_k f_k - W + Q_k, Q_k the censoring martingale's term
|
|
10
|
+
// sum_u (dN_k(u) - Y_k(u) dLambda(u)) V(u) / R(u), V(u) the weighted mass whose weight runs through u (computed per
|
|
11
|
+
// distinct time, so that each total costs O(n)). This is the tie-correct form chosen by the user (2026-11-26): without
|
|
12
|
+
// tied times it equals R's iid; with ties R mixes a by-time jump with a positional compensator and depends on the
|
|
13
|
+
// data order within ties, which is not followed here.
|
|
14
|
+
import { pnorm, qnorm, pnorm1, qnorm1 } from "../distributions/normal.js";
|
|
15
|
+
import { pbvnorm } from "../distributions/bvnorm.js";
|
|
16
|
+
import { quantile } from "../descriptive/quantile.js";
|
|
17
|
+
import { normRand } from "../random/rng.js";
|
|
18
|
+
import { survfitCoxph } from "../models/survfitCoxph.js";
|
|
19
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
20
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
21
|
+
const TIME_ROC_KEYS = ["times", "cause", "weighting", "otherMarkers", "iid", "roc"];
|
|
22
|
+
const TIME_ROCCONFINT_KEYS = ["level", "nSim"];
|
|
23
|
+
const TIME_ROCCOMPARE_KEYS = ["adjusted"];
|
|
24
|
+
const TIME_ROCAUC_CURVE_KEYS = ["fp", "level", "nSim"];
|
|
25
|
+
const TIME_ROCAUC_DIFF_KEYS = ["level", "fp"];
|
|
26
|
+
const SE_SP_PPVNPV_KEYS = ["times", "cause", "weighting", "otherMarkers", "iid"];
|
|
27
|
+
const SURVIVAL_ROC_KEYS = ["predictTime", "cutValues", "method"];
|
|
28
|
+
/** What compare needs to check that two fits come from the same subjects. */
|
|
29
|
+
const fitData = new WeakMap();
|
|
30
|
+
function checkVector(x, what, allowNaN = false) {
|
|
31
|
+
if (!Array.isArray(x) && !ArrayBuffer.isView(x))
|
|
32
|
+
throw new TypeError(`'${what}' must be an array of numbers`);
|
|
33
|
+
const v = Array.from(x);
|
|
34
|
+
for (const e of v) {
|
|
35
|
+
if (typeof e !== "number")
|
|
36
|
+
throw new TypeError(`'${what}' must be an array of numbers`);
|
|
37
|
+
if (Number.isNaN(e) ? !allowNaN : !Number.isFinite(e))
|
|
38
|
+
throw new RangeError(`'${what}' must contain finite numbers${allowNaN ? " (or NaN for NA)" : ""}`);
|
|
39
|
+
}
|
|
40
|
+
return v;
|
|
41
|
+
}
|
|
42
|
+
/** The subjects without NaN (R's NA) in time, delta, marker and the other markers, as R drops them. */
|
|
43
|
+
function completeCases(time, delta, marker, other) {
|
|
44
|
+
const t = checkVector(time, "time", true);
|
|
45
|
+
const d = checkVector(delta, "delta", true);
|
|
46
|
+
const m = checkVector(marker, "marker", true);
|
|
47
|
+
if (d.length !== t.length || m.length !== t.length)
|
|
48
|
+
throw new RangeError("'time', 'delta' and 'marker' must have the same length");
|
|
49
|
+
return t.map((_, i) => i).filter((i) => !Number.isNaN(t[i]) && !Number.isNaN(d[i]) && !Number.isNaN(m[i]) && !(other?.[i]?.some((v) => Number.isNaN(v)) ?? false));
|
|
50
|
+
}
|
|
51
|
+
function prepare(time, delta, marker) {
|
|
52
|
+
const t = checkVector(time, "time");
|
|
53
|
+
const d = checkVector(delta, "delta");
|
|
54
|
+
const m = checkVector(marker, "marker");
|
|
55
|
+
const n = t.length;
|
|
56
|
+
if (n === 0)
|
|
57
|
+
throw new RangeError("no subjects");
|
|
58
|
+
if (d.length !== n || m.length !== n)
|
|
59
|
+
throw new RangeError("'time', 'delta' and 'marker' must have the same length");
|
|
60
|
+
for (const e of d)
|
|
61
|
+
if (!Number.isInteger(e) || e < 0)
|
|
62
|
+
throw new RangeError("'delta' must hold non-negative integers (0 censored)");
|
|
63
|
+
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => t[a] - t[b] || a - b);
|
|
64
|
+
const u = [];
|
|
65
|
+
const ti = new Array(n);
|
|
66
|
+
for (const i of order) {
|
|
67
|
+
if (u.length === 0 || t[i] !== u[u.length - 1])
|
|
68
|
+
u.push(t[i]);
|
|
69
|
+
ti[i] = u.length - 1;
|
|
70
|
+
}
|
|
71
|
+
const m_ = u.length;
|
|
72
|
+
const atRiskFrom = new Array(m_ + 1).fill(0); // #(T >= u_m)
|
|
73
|
+
const C = new Array(m_).fill(0);
|
|
74
|
+
const ev = new Array(m_).fill(0);
|
|
75
|
+
for (let i = 0; i < n; i++) {
|
|
76
|
+
atRiskFrom[ti[i]]++;
|
|
77
|
+
if (d[i] === 0)
|
|
78
|
+
C[ti[i]]++;
|
|
79
|
+
else
|
|
80
|
+
ev[ti[i]]++;
|
|
81
|
+
}
|
|
82
|
+
for (let k = m_ - 1; k >= 0; k--)
|
|
83
|
+
atRiskFrom[k] += atRiskFrom[k + 1];
|
|
84
|
+
const R = u.map((_, k) => atRiskFrom[k] - ev[k]);
|
|
85
|
+
const G = new Array(m_);
|
|
86
|
+
let g = 1;
|
|
87
|
+
for (let k = 0; k < m_; k++) {
|
|
88
|
+
if (R[k] > 0)
|
|
89
|
+
g *= 1 - C[k] / R[k];
|
|
90
|
+
G[k] = g;
|
|
91
|
+
}
|
|
92
|
+
return { n, time: t, delta: d, marker: m, order, u, ti, R, C, G };
|
|
93
|
+
}
|
|
94
|
+
/** Index of the last distinct time <= s (or < s with strict), -1 if none. */
|
|
95
|
+
function lastIndex(u, s, strict) {
|
|
96
|
+
let lo = 0;
|
|
97
|
+
let hi = u.length;
|
|
98
|
+
while (lo < hi) {
|
|
99
|
+
const mid = (lo + hi) >> 1;
|
|
100
|
+
if (strict ? u[mid] < s : u[mid] <= s)
|
|
101
|
+
lo = mid + 1;
|
|
102
|
+
else
|
|
103
|
+
hi = mid;
|
|
104
|
+
}
|
|
105
|
+
return lo - 1;
|
|
106
|
+
}
|
|
107
|
+
function weightsAt(data, t, cause, gLeft, gAt) {
|
|
108
|
+
const { n, time, delta } = data;
|
|
109
|
+
const w = new Array(n).fill(0);
|
|
110
|
+
const left = new Array(n).fill(false);
|
|
111
|
+
const role = new Array(n).fill(0);
|
|
112
|
+
for (let i = 0; i < n; i++) {
|
|
113
|
+
const T = time[i];
|
|
114
|
+
if (T > t) {
|
|
115
|
+
role[i] = 2;
|
|
116
|
+
w[i] = 1 / gAt(i);
|
|
117
|
+
}
|
|
118
|
+
else if (delta[i] !== 0) {
|
|
119
|
+
role[i] = T < t ? (delta[i] === cause ? 1 : 3) : 4;
|
|
120
|
+
w[i] = 1 / gLeft(i);
|
|
121
|
+
left[i] = true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { t, w, left, role };
|
|
125
|
+
}
|
|
126
|
+
/** The marginal weights' left and at-t censoring probabilities. */
|
|
127
|
+
function marginalG(data, t) {
|
|
128
|
+
const k = lastIndex(data.u, t, false);
|
|
129
|
+
const Gt = k >= 0 ? data.G[k] : 1;
|
|
130
|
+
return { gLeft: (i) => (data.ti[i] > 0 ? data.G[data.ti[i] - 1] : 1), gAt: () => Gt, Gt };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The influence of W(f) = sum_i w_i f_i / n. `exact` takes the derivative of the weighted Kaplan-Meier itself
|
|
134
|
+
* (1 / (R - C) in place of 1 / R; used by the tests' infinitesimal jackknife), the default the usual asymptotic form.
|
|
135
|
+
*/
|
|
136
|
+
function total(data, at, f, exact = false) {
|
|
137
|
+
const { n, u, ti, R, C, delta } = data;
|
|
138
|
+
const m = u.length;
|
|
139
|
+
const acc = new Array(m).fill(0);
|
|
140
|
+
let atT = 0;
|
|
141
|
+
let value = 0;
|
|
142
|
+
for (let i = 0; i < n; i++) {
|
|
143
|
+
const wf = at.w[i] * f[i];
|
|
144
|
+
if (wf === 0)
|
|
145
|
+
continue;
|
|
146
|
+
value += wf;
|
|
147
|
+
if (at.left[i])
|
|
148
|
+
acc[ti[i]] += wf;
|
|
149
|
+
else
|
|
150
|
+
atT += wf;
|
|
151
|
+
}
|
|
152
|
+
value /= n;
|
|
153
|
+
// V(u_k) = sum over the left weights with T_i > u_k + [u_k <= t] the at-t mass; g = V / D
|
|
154
|
+
const g = new Array(m).fill(0);
|
|
155
|
+
let suffix = 0;
|
|
156
|
+
for (let k = m - 1; k >= 0; k--) {
|
|
157
|
+
const V = suffix + (u[k] <= at.t ? atT : 0);
|
|
158
|
+
const D = exact ? R[k] - C[k] : R[k];
|
|
159
|
+
g[k] = D > 0 ? V / D : 0;
|
|
160
|
+
suffix += acc[k];
|
|
161
|
+
}
|
|
162
|
+
const comp = new Array(m + 1).fill(0); // sum_{u' < u_k} dLambda g
|
|
163
|
+
for (let k = 0; k < m; k++)
|
|
164
|
+
comp[k + 1] = comp[k] + (R[k] > 0 ? (C[k] / R[k]) * g[k] : 0);
|
|
165
|
+
const inf = new Array(n);
|
|
166
|
+
for (let i = 0; i < n; i++) {
|
|
167
|
+
const k = ti[i];
|
|
168
|
+
let q = -comp[k];
|
|
169
|
+
if (delta[i] === 0)
|
|
170
|
+
q += g[k] - (R[k] > 0 ? (C[k] / R[k]) * g[k] : 0);
|
|
171
|
+
inf[i] = at.w[i] * f[i] - value + q;
|
|
172
|
+
}
|
|
173
|
+
return { value, inf };
|
|
174
|
+
}
|
|
175
|
+
/** Influence of a ratio a / b of totals. */
|
|
176
|
+
function ratioInf(a, b) {
|
|
177
|
+
const r = a.value / b.value;
|
|
178
|
+
return a.inf.map((x, k) => (x - r * b.inf[k]) / b.value);
|
|
179
|
+
}
|
|
180
|
+
/** sum_ij h_ij a_i c_j / n^2 for the cases (role 1) against the controls in `isControl`, with each subject's partial sum. */
|
|
181
|
+
function concordance(data, at, isControl) {
|
|
182
|
+
const { n, marker } = data;
|
|
183
|
+
const cases = [];
|
|
184
|
+
const ctrls = [];
|
|
185
|
+
for (let i = 0; i < n; i++) {
|
|
186
|
+
if (at.role[i] === 1)
|
|
187
|
+
cases.push(i);
|
|
188
|
+
else if (isControl(at.role[i]))
|
|
189
|
+
ctrls.push(i);
|
|
190
|
+
}
|
|
191
|
+
// A_i = sum_ctrl c_j h_ij, B_j = sum_case a_i h_ij, by sorting both groups by the marker
|
|
192
|
+
const cumBelow = (group) => {
|
|
193
|
+
const s = [...group].sort((a, b) => marker[a] - marker[b]);
|
|
194
|
+
const vals = [];
|
|
195
|
+
const cum = [0];
|
|
196
|
+
const eq = [];
|
|
197
|
+
for (const j of s) {
|
|
198
|
+
if (vals.length && vals[vals.length - 1] === marker[j]) {
|
|
199
|
+
eq[eq.length - 1] += at.w[j];
|
|
200
|
+
cum[cum.length - 1] += at.w[j];
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
vals.push(marker[j]);
|
|
204
|
+
eq.push(at.w[j]);
|
|
205
|
+
cum.push(cum[cum.length - 1] + at.w[j]);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// weight strictly below x plus half the weight equal to x
|
|
209
|
+
return (x) => {
|
|
210
|
+
let lo = 0;
|
|
211
|
+
let hi = vals.length;
|
|
212
|
+
while (lo < hi) {
|
|
213
|
+
const mid = (lo + hi) >> 1;
|
|
214
|
+
if (vals[mid] < x)
|
|
215
|
+
lo = mid + 1;
|
|
216
|
+
else
|
|
217
|
+
hi = mid;
|
|
218
|
+
}
|
|
219
|
+
return cum[lo] + (lo < vals.length && vals[lo] === x ? eq[lo] / 2 : 0);
|
|
220
|
+
};
|
|
221
|
+
};
|
|
222
|
+
const totalOf = (group) => group.reduce((s, j) => s + at.w[j], 0);
|
|
223
|
+
const belowCtrl = cumBelow(ctrls);
|
|
224
|
+
const belowCase = cumBelow(cases);
|
|
225
|
+
const caseTotal = totalOf(cases);
|
|
226
|
+
const v = new Array(n).fill(0);
|
|
227
|
+
let N = 0;
|
|
228
|
+
for (const i of cases) {
|
|
229
|
+
const A = belowCtrl(marker[i]);
|
|
230
|
+
v[i] = A / n;
|
|
231
|
+
N += at.w[i] * A;
|
|
232
|
+
}
|
|
233
|
+
// B_j = sum_case a_i ([M_i > M_j] + [M_i = M_j] / 2) = caseTotal - (weight below M_j + half equal)
|
|
234
|
+
for (const j of ctrls)
|
|
235
|
+
v[j] = (caseTotal - belowCase(marker[j])) / n;
|
|
236
|
+
return { N: N / (n * n), v };
|
|
237
|
+
}
|
|
238
|
+
/** TP or FP curve: the weighted proportion of the group above each distinct marker value, decreasing, then 1. */
|
|
239
|
+
function curve(data, at, inGroup, cuts) {
|
|
240
|
+
const { n, marker } = data;
|
|
241
|
+
let tot = 0;
|
|
242
|
+
const idx = [];
|
|
243
|
+
for (let i = 0; i < n; i++)
|
|
244
|
+
if (inGroup(at.role[i])) {
|
|
245
|
+
tot += at.w[i];
|
|
246
|
+
idx.push(i);
|
|
247
|
+
}
|
|
248
|
+
idx.sort((a, b) => marker[b] - marker[a]);
|
|
249
|
+
const out = [];
|
|
250
|
+
let p = 0;
|
|
251
|
+
let acc = 0;
|
|
252
|
+
for (const c of cuts) {
|
|
253
|
+
while (p < idx.length && marker[idx[p]] > c)
|
|
254
|
+
acc += at.w[idx[p++]];
|
|
255
|
+
out.push(acc / tot);
|
|
256
|
+
}
|
|
257
|
+
out.push(1);
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
function covariates(data, other) {
|
|
261
|
+
const { n, marker } = data;
|
|
262
|
+
if (other !== undefined) {
|
|
263
|
+
if (!Array.isArray(other) || other.length !== n)
|
|
264
|
+
throw new RangeError("'otherMarkers' must have one row per subject");
|
|
265
|
+
const p = other[0]?.length ?? 0;
|
|
266
|
+
for (const row of other) {
|
|
267
|
+
if (!Array.isArray(row))
|
|
268
|
+
throw new TypeError("'otherMarkers' must be an array of rows");
|
|
269
|
+
if (row.length !== p)
|
|
270
|
+
throw new RangeError("the rows of 'otherMarkers' must have the same length");
|
|
271
|
+
for (const e of row)
|
|
272
|
+
if (typeof e !== "number" || !Number.isFinite(e))
|
|
273
|
+
throw new RangeError("'otherMarkers' must contain finite numbers (or NaN for NA)");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return marker.map((m, i) => [m, ...(other?.[i] ?? [])]);
|
|
277
|
+
}
|
|
278
|
+
function coxWeights(data, Z, times) {
|
|
279
|
+
const { n, time, delta } = data;
|
|
280
|
+
if (!delta.some((d) => d === 0))
|
|
281
|
+
return { left: new Array(n).fill(1), at: times.map(() => new Array(n).fill(1)) };
|
|
282
|
+
// One curve at the fit's means and S_i = S_0^exp(beta'(z_i - means)), the relation of survfit's curves for a Cox fit
|
|
283
|
+
// (exp(-H_0 exp(lp))), so that n curves cost one. timefix off: the weights depend on the order of the times only
|
|
284
|
+
// (aeqSurv's tolerance would merge tiny or nearly equal times).
|
|
285
|
+
const sf = survfitCoxph(time, delta.map((d) => (d === 0 ? 1 : 0)), Z, { ties: "efron", confType: "none", control: { timefix: false } });
|
|
286
|
+
const beta = sf.fit.coefficients.map((b) => (Number.isNaN(b) ? 0 : b)); // aliased columns: R's NA, no effect
|
|
287
|
+
const means = sf.fit.means;
|
|
288
|
+
// log H_0 + lp, not H_0 exp(lp): a large linear predictor would overflow exp(lp) and give 0 x Infinity = NaN where
|
|
289
|
+
// H_0 is still 0 (before the first censoring)
|
|
290
|
+
const logH0 = sf.surv[0].map((v) => Math.log(-Math.log(v)));
|
|
291
|
+
const lp = Z.map((z) => z.reduce((acc, v, j) => acc + beta[j] * (v - means[j]), 0));
|
|
292
|
+
const read = (i, s, strict) => {
|
|
293
|
+
const k = lastIndex(sf.time, s, strict);
|
|
294
|
+
return k >= 0 ? Math.exp(-Math.exp(logH0[k] + lp[i])) : 1;
|
|
295
|
+
};
|
|
296
|
+
return {
|
|
297
|
+
left: Array.from({ length: n }, (_, i) => read(i, time[i], true)),
|
|
298
|
+
at: times.map((t) => Array.from({ length: n }, (_, i) => read(i, t, false))),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/** Solves the small symmetric system A x = b by Gaussian elimination with partial pivoting; null if singular. */
|
|
302
|
+
function solveSmall(A, b) {
|
|
303
|
+
const p = b.length;
|
|
304
|
+
const M = A.map((row, i) => [...row, b[i]]);
|
|
305
|
+
const scale = Math.max(...A.map((row, i) => Math.abs(row[i])));
|
|
306
|
+
for (let c = 0; c < p; c++) {
|
|
307
|
+
let piv = c;
|
|
308
|
+
for (let r = c + 1; r < p; r++)
|
|
309
|
+
if (Math.abs(M[r][c]) > Math.abs(M[piv][c]))
|
|
310
|
+
piv = r;
|
|
311
|
+
if (!(Math.abs(M[piv][c]) > 1e-10 * scale))
|
|
312
|
+
return null;
|
|
313
|
+
[M[c], M[piv]] = [M[piv], M[c]];
|
|
314
|
+
for (let r = c + 1; r < p; r++) {
|
|
315
|
+
const f = M[r][c] / M[c][c];
|
|
316
|
+
for (let k = c; k <= p; k++)
|
|
317
|
+
M[r][k] -= f * M[c][k];
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const x = new Array(p).fill(0);
|
|
321
|
+
for (let r = p - 1; r >= 0; r--) {
|
|
322
|
+
let s = M[r][p];
|
|
323
|
+
for (let k = r + 1; k < p; k++)
|
|
324
|
+
s -= M[r][k] * x[k];
|
|
325
|
+
x[r] = s / M[r][r];
|
|
326
|
+
}
|
|
327
|
+
return x;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Aalen's additive hazards model of the censoring, least-squares increments at each censoring time over the risk set
|
|
331
|
+
* of the marginal weights (T > u, or censored at u), the tied censorings of a time together (R's timereg breaks ties
|
|
332
|
+
* with random noise; Choice 2). The covariates enter centred and scaled by powers of 2, which leaves the fitted G
|
|
333
|
+
* unchanged (the same linear span) and keeps X'X in range; columns dependent on the earlier ones are left out. From the
|
|
334
|
+
* first singular X'X on (too few subjects at risk), G is kept.
|
|
335
|
+
*/
|
|
336
|
+
function aalenWeights(data, Z, times) {
|
|
337
|
+
const { n, delta, u, ti, C } = data;
|
|
338
|
+
const q = Z[0].length;
|
|
339
|
+
const X = Z.map(() => [1]);
|
|
340
|
+
for (let j = 0; j < q; j++) {
|
|
341
|
+
const col = Z.map((r) => r[j]);
|
|
342
|
+
const mid = (Math.max(...col) + Math.min(...col)) / 2;
|
|
343
|
+
const half = (Math.max(...col) - Math.min(...col)) / 2;
|
|
344
|
+
const s = half > 0 ? 2 ** Math.round(Math.log2(half)) : 1;
|
|
345
|
+
for (let i = 0; i < n; i++)
|
|
346
|
+
X[i].push((col[i] - mid) / s);
|
|
347
|
+
}
|
|
348
|
+
// columns dependent on the intercept and the earlier ones (a constant or collinear covariate: R's NA) are left out,
|
|
349
|
+
// by Gram-Schmidt on the centred and scaled columns
|
|
350
|
+
const basis = [];
|
|
351
|
+
const keep = [];
|
|
352
|
+
for (let j = 1; j <= q; j++) {
|
|
353
|
+
const v = X.map((r) => r[j]);
|
|
354
|
+
const m = v.reduce((a, b) => a + b, 0) / n;
|
|
355
|
+
const w = v.map((x) => x - m);
|
|
356
|
+
const norm0 = Math.hypot(...w);
|
|
357
|
+
for (const b of basis) {
|
|
358
|
+
const dot = w.reduce((a, x, i) => a + x * b[i], 0);
|
|
359
|
+
for (let i = 0; i < n; i++)
|
|
360
|
+
w[i] -= dot * b[i];
|
|
361
|
+
}
|
|
362
|
+
const norm = Math.hypot(...w);
|
|
363
|
+
if (norm0 > 0 && norm > 1e-7 * norm0) {
|
|
364
|
+
basis.push(w.map((x) => x / norm));
|
|
365
|
+
keep.push(j);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
for (let i = 0; i < n; i++)
|
|
369
|
+
X[i] = [1, ...keep.map((j) => X[i][j])];
|
|
370
|
+
const p = keep.length + 1;
|
|
371
|
+
// cumulative B after each distinct time (rows of u), increments only at censoring times
|
|
372
|
+
const B = [];
|
|
373
|
+
let cur = new Array(p).fill(0);
|
|
374
|
+
let stopped = false;
|
|
375
|
+
const byTime = u.map(() => []);
|
|
376
|
+
for (let i = 0; i < n; i++)
|
|
377
|
+
byTime[ti[i]].push(i);
|
|
378
|
+
// risk set at u_k: T > u_k or censored at u_k; built from the latest times backwards
|
|
379
|
+
const XtX = [];
|
|
380
|
+
const acc = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
381
|
+
for (let k = u.length - 1; k >= 0; k--) {
|
|
382
|
+
for (const i of byTime[k])
|
|
383
|
+
if (delta[i] === 0)
|
|
384
|
+
for (let a = 0; a < p; a++)
|
|
385
|
+
for (let b = 0; b < p; b++)
|
|
386
|
+
acc[a][b] += X[i][a] * X[i][b];
|
|
387
|
+
XtX[k] = acc.map((r) => [...r]);
|
|
388
|
+
for (const i of byTime[k])
|
|
389
|
+
if (delta[i] !== 0)
|
|
390
|
+
for (let a = 0; a < p; a++)
|
|
391
|
+
for (let b = 0; b < p; b++)
|
|
392
|
+
acc[a][b] += X[i][a] * X[i][b];
|
|
393
|
+
}
|
|
394
|
+
for (let k = 0; k < u.length; k++) {
|
|
395
|
+
if (!stopped && C[k] > 0) {
|
|
396
|
+
const rhs = new Array(p).fill(0);
|
|
397
|
+
for (const i of byTime[k])
|
|
398
|
+
if (delta[i] === 0)
|
|
399
|
+
for (let a = 0; a < p; a++)
|
|
400
|
+
rhs[a] += X[i][a];
|
|
401
|
+
const dB = solveSmall(XtX[k], rhs);
|
|
402
|
+
if (dB === null)
|
|
403
|
+
stopped = true;
|
|
404
|
+
else
|
|
405
|
+
cur = cur.map((x, a) => x + dB[a]);
|
|
406
|
+
}
|
|
407
|
+
B.push(cur);
|
|
408
|
+
}
|
|
409
|
+
const G = (i, k) => {
|
|
410
|
+
if (k < 0)
|
|
411
|
+
return 1;
|
|
412
|
+
let eta = 0;
|
|
413
|
+
for (let a = 0; a < p; a++)
|
|
414
|
+
eta += X[i][a] * B[k][a];
|
|
415
|
+
return Math.min(1, Math.max(0, Math.exp(-eta)));
|
|
416
|
+
};
|
|
417
|
+
return {
|
|
418
|
+
left: Array.from({ length: n }, (_, i) => G(i, ti[i] - 1)),
|
|
419
|
+
at: times.map((t) => {
|
|
420
|
+
const k = lastIndex(u, t, false);
|
|
421
|
+
return Array.from({ length: n }, (_, i) => G(i, k));
|
|
422
|
+
}),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
function prepareFit(time, delta, marker, options, fn) {
|
|
426
|
+
if (options === null || typeof options !== "object")
|
|
427
|
+
throw new TypeError(`${fn}: 'options' with 'times' is required`);
|
|
428
|
+
if (options.otherMarkers !== undefined && (!Array.isArray(options.otherMarkers) || options.otherMarkers.length !== time.length))
|
|
429
|
+
throw new RangeError("'otherMarkers' must have one row per subject");
|
|
430
|
+
const keep = completeCases(time, delta, marker, options.otherMarkers);
|
|
431
|
+
const data = prepare(keep.map((i) => time[i]), keep.map((i) => delta[i]), keep.map((i) => marker[i]));
|
|
432
|
+
const otherMarkers = options.otherMarkers === undefined ? undefined : keep.map((i) => options.otherMarkers[i]);
|
|
433
|
+
const times = checkVector(options.times ?? [], "times");
|
|
434
|
+
if (times.length === 0)
|
|
435
|
+
throw new RangeError("'times' must have at least one time");
|
|
436
|
+
const cause = options.cause ?? 1;
|
|
437
|
+
if (!Number.isInteger(cause) || cause <= 0)
|
|
438
|
+
throw new RangeError("'cause' must be a positive integer");
|
|
439
|
+
const weighting = options.weighting ?? "marginal";
|
|
440
|
+
if (!["marginal", "cox", "aalen"].includes(weighting))
|
|
441
|
+
throw new RangeError(`'weighting' must be "marginal", "cox" or "aalen"`);
|
|
442
|
+
if (options.otherMarkers !== undefined && weighting === "marginal")
|
|
443
|
+
throw new RangeError("'otherMarkers' is used by the cox and aalen weights only");
|
|
444
|
+
const competing = data.delta.some((d) => d !== 0 && d !== cause);
|
|
445
|
+
let cond = null;
|
|
446
|
+
if (weighting !== "marginal") {
|
|
447
|
+
const Z = covariates(data, otherMarkers);
|
|
448
|
+
cond = weighting === "cox" ? coxWeights(data, Z, times) : aalenWeights(data, Z, times);
|
|
449
|
+
}
|
|
450
|
+
return { data, cause, competing, times, weighting, cond };
|
|
451
|
+
}
|
|
452
|
+
function atTimes(p) {
|
|
453
|
+
return p.times.map((t, j) => p.cond === null
|
|
454
|
+
? (() => {
|
|
455
|
+
const g = marginalG(p.data, t);
|
|
456
|
+
return weightsAt(p.data, t, p.cause, g.gLeft, g.gAt);
|
|
457
|
+
})()
|
|
458
|
+
: weightsAt(p.data, t, p.cause, (i) => p.cond.left[i], (i) => p.cond.at[j][i]));
|
|
459
|
+
}
|
|
460
|
+
function statsOf(at, competing) {
|
|
461
|
+
let cases = 0;
|
|
462
|
+
let survivors = 0;
|
|
463
|
+
let other = 0;
|
|
464
|
+
for (const r of at.role) {
|
|
465
|
+
if (r === 1)
|
|
466
|
+
cases++;
|
|
467
|
+
else if (r === 2)
|
|
468
|
+
survivors++;
|
|
469
|
+
else if (r === 3)
|
|
470
|
+
other++;
|
|
471
|
+
}
|
|
472
|
+
const n = at.role.length;
|
|
473
|
+
return competing ? { cases, survivors, otherEvents: other, censored: n - cases - survivors - other } : { cases, survivors, censored: n - cases - survivors };
|
|
474
|
+
}
|
|
475
|
+
const sorted = (data, v) => data.order.map((i) => v[i]);
|
|
476
|
+
const sdOver = (x) => {
|
|
477
|
+
const n = x.length;
|
|
478
|
+
const m = x.reduce((s, v) => s + v, 0) / n;
|
|
479
|
+
return Math.sqrt(x.reduce((s, v) => s + (v - m) * (v - m), 0) / (n - 1) / n);
|
|
480
|
+
};
|
|
481
|
+
/** The AUC's influence: definition "i" (controls T > t) or "ii" (with the other events before t). @internal */
|
|
482
|
+
export function aucInfluence(data, at, definition, exact = false) {
|
|
483
|
+
const isCtrl = definition === "i" ? (r) => r === 2 : (r) => r === 2 || r === 3;
|
|
484
|
+
const { N, v } = concordance(data, at, isCtrl);
|
|
485
|
+
const Nt = total(data, at, v, exact);
|
|
486
|
+
const IFN = Nt.inf; // W(v) = 2N, so the total's influence w v - 2N + Q is IF(N)
|
|
487
|
+
const F = total(data, at, at.role.map((r) => (r === 1 ? 1 : 0)), exact);
|
|
488
|
+
let S;
|
|
489
|
+
if (definition === "i")
|
|
490
|
+
S = total(data, at, at.role.map((r) => (r === 2 ? 1 : 0)), exact);
|
|
491
|
+
else {
|
|
492
|
+
// S = 1 - F - M, M the mass of the events at exactly t: IF(S) = -IF(F) - IF(M) (R's form when M = 0)
|
|
493
|
+
const M = total(data, at, at.role.map((r) => (r === 4 ? 1 : 0)), exact);
|
|
494
|
+
const Sv = total(data, at, at.role.map((r) => (r === 2 || r === 3 ? 1 : 0)), exact).value;
|
|
495
|
+
S = { value: Sv, inf: F.inf.map((x, k) => -x - M.inf[k]) };
|
|
496
|
+
}
|
|
497
|
+
const auc = N / (F.value * S.value);
|
|
498
|
+
const inf = IFN.map((x, k) => (x - auc * (S.value * F.inf[k] + F.value * S.inf[k])) / (F.value * S.value));
|
|
499
|
+
return { auc, inf };
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Time-dependent ROC curves and AUC for censored event times, with a single event or competing risks: the
|
|
503
|
+
* cumulative/dynamic definition (cases T < t with the cause, controls T > t, and for competing risks definition (ii)
|
|
504
|
+
* also the subjects with another event before t), inverse probability of censoring weights from the Kaplan-Meier of
|
|
505
|
+
* the censoring (`"marginal"`), a Cox model (`"cox"`, Efron ties) or Aalen's additive model (`"aalen"`) with the marker
|
|
506
|
+
* and `otherMarkers`; ties in the marker count 1/2. With `iid` (marginal weights), the iid representation of the AUC and
|
|
507
|
+
* its standard error.
|
|
508
|
+
*
|
|
509
|
+
* Differences from R: the times are used as given (R adds 0 to a single time); the iid handles tied times correctly
|
|
510
|
+
* (independent of the data order; equal to R's without ties) and definition (ii)'s is centred on the reported AUC_2;
|
|
511
|
+
* the Cox weights use the maximum of the partial likelihood (R's cph stops about 5e-7 short); Aalen's increments take
|
|
512
|
+
* tied censorings together (R breaks ties at random); a time with a single survivor works (R's competing-risks iid
|
|
513
|
+
* fails there).
|
|
514
|
+
*
|
|
515
|
+
* Equivalent to `timeROC::timeROC()` in R.
|
|
516
|
+
*
|
|
517
|
+
* @param time observed times
|
|
518
|
+
* @param delta 0 censored, otherwise the kind of event
|
|
519
|
+
* @param marker the marker (larger values: the event sooner)
|
|
520
|
+
* @param options `times` (required) and the options of timeROC
|
|
521
|
+
* @category Survival analysis
|
|
522
|
+
*/
|
|
523
|
+
export function timeROC(time, delta, marker, options) {
|
|
524
|
+
checkOptions(options, TIME_ROC_KEYS, "timeROC"); // generated: option-keys.mjs
|
|
525
|
+
const p = prepareFit(time, delta, marker, options, "timeROC");
|
|
526
|
+
const iid = options.iid ?? false;
|
|
527
|
+
if (iid && p.weighting !== "marginal")
|
|
528
|
+
throw new RangeError("weighting must be marginal for computing the iid representation (as R)");
|
|
529
|
+
const roc = options.roc ?? true;
|
|
530
|
+
const { data, competing } = p;
|
|
531
|
+
const ats = atTimes(p);
|
|
532
|
+
const cuts = [...new Set(data.marker)].sort((a, b) => b - a);
|
|
533
|
+
const cumulativeIncidence = ats.map((at) => at.w.reduce((s, w, i) => s + (at.role[i] === 1 ? w : 0), 0) / data.n);
|
|
534
|
+
const common = {
|
|
535
|
+
times: p.times,
|
|
536
|
+
n: data.n,
|
|
537
|
+
cumulativeIncidence,
|
|
538
|
+
// R's survProb: the survivors' weighted mass (the Kaplan-Meier with the marginal weights, exactly)
|
|
539
|
+
survProb: ats.map((at) => at.w.reduce((s, w, i) => s + (at.role[i] === 2 ? w : 0), 0) / data.n),
|
|
540
|
+
stats: ats.map((at) => statsOf(at, competing)),
|
|
541
|
+
weights: (p.cond === null
|
|
542
|
+
? { method: "marginal", ipcwTimes: p.times.map((t) => marginalG(data, t).Gt), ipcwSubjectTimes: sorted(data, data.ti.map((k) => (k > 0 ? data.G[k - 1] : 1))) }
|
|
543
|
+
: { method: p.weighting, ipcwTimes: p.cond.at.map((g) => sorted(data, g)), ipcwSubjectTimes: sorted(data, p.cond.left) }),
|
|
544
|
+
...(roc ? { tp: ats.map((at) => curve(data, at, (r) => r === 1, cuts)) } : {}),
|
|
545
|
+
};
|
|
546
|
+
const aucs = (def) => ats.map((at) => aucInfluence(data, at, def));
|
|
547
|
+
const r1 = aucs("i");
|
|
548
|
+
let result;
|
|
549
|
+
if (!competing) {
|
|
550
|
+
result = {
|
|
551
|
+
...common,
|
|
552
|
+
competingRisks: false,
|
|
553
|
+
auc: r1.map((r) => r.auc),
|
|
554
|
+
...(roc ? { fp: ats.map((at) => curve(data, at, (r) => r === 2, cuts)) } : {}),
|
|
555
|
+
...(iid ? { inference: { iid: r1.map((r) => sorted(data, r.inf)), sd: r1.map((r) => sdOver(r.inf)) } } : {}),
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
const r2 = aucs("ii");
|
|
560
|
+
result = {
|
|
561
|
+
...common,
|
|
562
|
+
competingRisks: true,
|
|
563
|
+
auc1: r1.map((r) => r.auc),
|
|
564
|
+
auc2: r2.map((r) => r.auc),
|
|
565
|
+
...(roc ? { fp1: ats.map((at) => curve(data, at, (r) => r === 2, cuts)), fp2: ats.map((at) => curve(data, at, (r) => r === 2 || r === 3, cuts)) } : {}),
|
|
566
|
+
...(iid ? { inference: { iid1: r1.map((r) => sorted(data, r.inf)), sd1: r1.map((r) => sdOver(r.inf)), iid2: r2.map((r) => sorted(data, r.inf)), sd2: r2.map((r) => sdOver(r.inf)) } } : {}),
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
fitData.set(result, { time: data.time, delta: data.delta });
|
|
570
|
+
return result;
|
|
571
|
+
}
|
|
572
|
+
function iidOf(fit, which) {
|
|
573
|
+
if (fit === null || typeof fit !== "object" || !("competingRisks" in fit))
|
|
574
|
+
throw new TypeError("'fit' must be a result of timeROC");
|
|
575
|
+
if (fit.inference === undefined)
|
|
576
|
+
throw new RangeError("the fit has no iid representation: call timeROC with iid: true (marginal weights)");
|
|
577
|
+
if (!fit.competingRisks)
|
|
578
|
+
return { auc: fit.auc, iid: fit.inference.iid, sd: fit.inference.sd };
|
|
579
|
+
return which === 1
|
|
580
|
+
? { auc: fit.auc1, iid: fit.inference.iid1, sd: fit.inference.sd1 }
|
|
581
|
+
: { auc: fit.auc2, iid: fit.inference.iid2, sd: fit.inference.sd2 };
|
|
582
|
+
}
|
|
583
|
+
/** The intervals of one or more AUC definitions; with competing risks R uses the same draws for both (log 49). */
|
|
584
|
+
function intervals(list, level, nSim) {
|
|
585
|
+
const z = qnorm((1 + level) / 2);
|
|
586
|
+
const n = list[0].iid[0].length;
|
|
587
|
+
const max = list.map(() => new Array(nSim));
|
|
588
|
+
const xi = new Array(n);
|
|
589
|
+
for (let s = 0; s < nSim; s++) {
|
|
590
|
+
for (let i = 0; i < n; i++)
|
|
591
|
+
xi[i] = normRand();
|
|
592
|
+
list.forEach((a, l) => {
|
|
593
|
+
let m = -Infinity;
|
|
594
|
+
for (let j = 0; j < a.auc.length; j++) {
|
|
595
|
+
const col = a.iid[j];
|
|
596
|
+
let acc = 0;
|
|
597
|
+
for (let i = 0; i < n; i++)
|
|
598
|
+
acc += xi[i] * col[i];
|
|
599
|
+
const v = Math.abs(acc / (n * a.sd[j]));
|
|
600
|
+
if (v > m)
|
|
601
|
+
m = v;
|
|
602
|
+
}
|
|
603
|
+
max[l][s] = m;
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
return list.map((a, l) => {
|
|
607
|
+
const cAlpha = quantile(max[l], level);
|
|
608
|
+
return {
|
|
609
|
+
ci: a.auc.map((x, j) => [100 * (x - z * a.sd[j]), 100 * (x + z * a.sd[j])]),
|
|
610
|
+
band: a.auc.map((x, j) => [100 * (x - cAlpha * a.sd[j]), 100 * (x + cAlpha * a.sd[j])]),
|
|
611
|
+
cAlpha,
|
|
612
|
+
};
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Pointwise confidence intervals of the time-dependent AUC and a simultaneous confidence band over the times, from the
|
|
617
|
+
* iid representation: the band's multiplier is the `level` quantile of the maximum over the times of the
|
|
618
|
+
* standardized multiplier-bootstrap process (`nSim` draws of n standard normals, from rStats.js's generator: set it
|
|
619
|
+
* with `setSeed`; the same seed as R's `set.seed` gives R's band). Percent, not rounded (R rounds to 2 decimals).
|
|
620
|
+
*
|
|
621
|
+
* Equivalent to `timeROC::confint.ipcwsurvivalROC()` in R.
|
|
622
|
+
*
|
|
623
|
+
* @param fit a result of {@link timeROC} with `iid: true`
|
|
624
|
+
* @param options `level` and `nSim`
|
|
625
|
+
* @category Survival analysis
|
|
626
|
+
*/
|
|
627
|
+
export function timeROCConfint(fit, options = {}) {
|
|
628
|
+
checkOptions(options, TIME_ROCCONFINT_KEYS, "timeROCConfint"); // generated: option-keys.mjs
|
|
629
|
+
const level = options.level ?? 0.95;
|
|
630
|
+
if (!(level > 0 && level < 1))
|
|
631
|
+
throw new RangeError("'level' must be in (0, 1)");
|
|
632
|
+
const nSim = options.nSim ?? 2000;
|
|
633
|
+
if (!Number.isInteger(nSim) || nSim < 1)
|
|
634
|
+
throw new RangeError("'nSim' must be a positive integer");
|
|
635
|
+
const a1 = iidOf(fit, 1);
|
|
636
|
+
if (!fit.competingRisks)
|
|
637
|
+
return { times: fit.times, level, auc: intervals([a1], level, nSim)[0] };
|
|
638
|
+
const [auc1, auc2] = intervals([a1, iidOf(fit, 2)], level, nSim);
|
|
639
|
+
return { times: fit.times, level, auc1, auc2 };
|
|
640
|
+
}
|
|
641
|
+
function comparison(x, y, adjusted) {
|
|
642
|
+
const T = x.auc.length;
|
|
643
|
+
const d = x.iid.map((col, j) => col.map((v, i) => v - y.iid[j][i]));
|
|
644
|
+
const se = d.map(sdOver);
|
|
645
|
+
const z = x.auc.map((a, j) => (a - y.auc[j]) / se[j]);
|
|
646
|
+
const pValues = z.map((v) => 2 * pnorm(-Math.abs(v)));
|
|
647
|
+
if (!adjusted)
|
|
648
|
+
return { pValues };
|
|
649
|
+
const n = d[0].length;
|
|
650
|
+
const sdv = se.map((s) => s * Math.sqrt(n));
|
|
651
|
+
const means = d.map((col) => col.reduce((s, v) => s + v, 0) / n);
|
|
652
|
+
const cor = Array.from({ length: T }, (_, a) => Array.from({ length: T }, (_, b) => {
|
|
653
|
+
let s = 0;
|
|
654
|
+
for (let i = 0; i < n; i++)
|
|
655
|
+
s += (d[a][i] - means[a]) * (d[b][i] - means[b]);
|
|
656
|
+
return s / (n - 1) / (sdv[a] * sdv[b]);
|
|
657
|
+
}));
|
|
658
|
+
const adj = z.map((v) => {
|
|
659
|
+
const b = Math.abs(v);
|
|
660
|
+
if (Number.isNaN(b))
|
|
661
|
+
return NaN;
|
|
662
|
+
return pmaxAbsExceed(b, cor);
|
|
663
|
+
});
|
|
664
|
+
return { pValues, adjusted: adj, cor };
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Compares the time-dependent AUCs of two markers measured on the same subjects at each time, by the z statistic of
|
|
668
|
+
* the difference with the standard error from the difference of the iid representations; with `adjusted`, also the
|
|
669
|
+
* p-values adjusted for the several times, P(max_t |Z_t| >= |z_t|) for Z normal with the correlation of the
|
|
670
|
+
* statistics (computed deterministically as a sum of positive terms, so that small p-values keep their relative
|
|
671
|
+
* accuracy: to rounding up to three times, to about 1e-6 relative from four on; R integrates 1 − P at random with
|
|
672
|
+
* mvtnorm's default absolute tolerance of 1e-3, so the two differ by up to about 1e-4).
|
|
673
|
+
*
|
|
674
|
+
* Equivalent to `timeROC::compare()` in R.
|
|
675
|
+
*
|
|
676
|
+
* @param x a result of {@link timeROC} with `iid: true`
|
|
677
|
+
* @param y another, on the same subjects and times
|
|
678
|
+
* @param options `adjusted`
|
|
679
|
+
* @category Survival analysis
|
|
680
|
+
*/
|
|
681
|
+
export function timeROCCompare(x, y, options = {}) {
|
|
682
|
+
checkOptions(options, TIME_ROCCOMPARE_KEYS, "timeROCCompare"); // generated: option-keys.mjs
|
|
683
|
+
const adjusted = options.adjusted ?? false;
|
|
684
|
+
const dx = fitData.get(x);
|
|
685
|
+
const dy = fitData.get(y);
|
|
686
|
+
iidOf(x, 1);
|
|
687
|
+
iidOf(y, 1);
|
|
688
|
+
if (x.n !== y.n || x.times.length !== y.times.length || x.times.some((t, j) => t !== y.times[j]) || x.competingRisks !== y.competingRisks
|
|
689
|
+
|| (dx && dy && (dx.time.some((t, i) => t !== dy.time[i]) || dx.delta.some((t, i) => t !== dy.delta[i]))))
|
|
690
|
+
throw new RangeError("the two fits must come from the same subjects and times");
|
|
691
|
+
if (!x.competingRisks)
|
|
692
|
+
return { times: x.times, auc: comparison(iidOf(x, 1), iidOf(y, 1), adjusted) };
|
|
693
|
+
return { times: x.times, auc1: comparison(iidOf(x, 1), iidOf(y, 1), adjusted), auc2: comparison(iidOf(x, 2), iidOf(y, 2), adjusted) };
|
|
694
|
+
}
|
|
695
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
696
|
+
// The adjusted p-value P(max_j |Z_j| >= b), Z ~ N(0, cor)
|
|
697
|
+
/**
|
|
698
|
+
* P(max_j |Z_j| >= b) for Z ~ N(0, cor), computed directly (not as 1 − P(all |Z_j| < b), which loses the small values
|
|
699
|
+
* to cancellation) by the first exceedance: Q = 2 Σ_i P(|Z_j| < b for j < i, Z_i >= b), a sum of positive terms (the
|
|
700
|
+
* factor 2 by the symmetry Z → −Z). The i-th term is a probability of the leading i variables: pnorm for i = 1,
|
|
701
|
+
* pbvnorm for i = 2, adaptive Gauss-Legendre over Z_3 >= b of the conditional bivariate probability (pbvnorm) for
|
|
702
|
+
* i = 3, and Genz's separation of variables (Genz 1992) with a Richtmyer lattice for i >= 4 or a correlation within
|
|
703
|
+
* 1e-9 of ±1 (a Richtmyer lattice periodized by the baker's transform, fixed shifts from a private generator: no use of
|
|
704
|
+
* the user's random numbers; points doubled until two standard errors fall below 1e-6 of the term). Each term
|
|
705
|
+
* keeps its relative accuracy, so small adjusted p-values do too.
|
|
706
|
+
*
|
|
707
|
+
* @internal
|
|
708
|
+
*/
|
|
709
|
+
export function pmaxAbsExceed(b, cor) {
|
|
710
|
+
const d = cor.length;
|
|
711
|
+
if (Number.isNaN(b))
|
|
712
|
+
return NaN;
|
|
713
|
+
if (b === Infinity)
|
|
714
|
+
return 0;
|
|
715
|
+
if (!(b > 0))
|
|
716
|
+
return 1;
|
|
717
|
+
let q = 0;
|
|
718
|
+
for (let i = 1; i <= d; i++)
|
|
719
|
+
q += firstExceedance(b, cor, i);
|
|
720
|
+
return Math.min(1, 2 * q);
|
|
721
|
+
}
|
|
722
|
+
/** P(all |Z_j| <= b) = 1 − {@link pmaxAbsExceed} (for moderate b; the tests). @internal */
|
|
723
|
+
export function pmvnormSymmetric(b, cor) {
|
|
724
|
+
return 1 - pmaxAbsExceed(b, cor);
|
|
725
|
+
}
|
|
726
|
+
/** P(|Z_j| < b for j < i, Z_i >= b) over the leading i variables. */
|
|
727
|
+
function firstExceedance(b, cor, i) {
|
|
728
|
+
if (i === 1)
|
|
729
|
+
return pnorm1(-b, 0, 1, true, false);
|
|
730
|
+
const r = (a, c) => Math.max(-1, Math.min(1, cor[a][c]));
|
|
731
|
+
if (i === 2)
|
|
732
|
+
return pbvnorm([-b, b], [b, Infinity], r(0, 1));
|
|
733
|
+
if (i === 3) {
|
|
734
|
+
const r13 = r(0, 2);
|
|
735
|
+
const r23 = r(1, 2);
|
|
736
|
+
if (Math.abs(r13) < 1 - 1e-9 && Math.abs(r23) < 1 - 1e-9) {
|
|
737
|
+
const s1 = Math.sqrt(1 - r13 * r13);
|
|
738
|
+
const s2 = Math.sqrt(1 - r23 * r23);
|
|
739
|
+
const rho = Math.max(-1, Math.min(1, (r(0, 1) - r13 * r23) / (s1 * s2)));
|
|
740
|
+
const f = (x) => (Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI))
|
|
741
|
+
* pbvnorm([(-b - r13 * x) / s1, (-b - r23 * x) / s2], [(b - r13 * x) / s1, (b - r23 * x) / s2], rho);
|
|
742
|
+
return adaptiveGL(f, b, b + 40);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
// the exceedance Z_i >= b first (the most constrained variable first, as Genz advises): the integrand is then Phi(-b)
|
|
746
|
+
// times conditional probabilities of order 1, so the lattice keeps the relative accuracy of a tiny term
|
|
747
|
+
const order = [i - 1, ...Array.from({ length: i - 1 }, (_, j) => j)];
|
|
748
|
+
const lower = order.map((j) => (j === i - 1 ? b : -b));
|
|
749
|
+
const upper = order.map((j) => (j === i - 1 ? Infinity : b));
|
|
750
|
+
return genzLattice(lower, upper, order.map((a) => order.map((c) => cor[a][c])));
|
|
751
|
+
}
|
|
752
|
+
/** Ten-point Gauss-Legendre nodes and weights on [-1, 1]. */
|
|
753
|
+
const GL_X = [-0.9739065285171717, -0.8650633666889845, -0.6794095682990244, -0.4333953941292472, -0.1488743389816312,
|
|
754
|
+
0.1488743389816312, 0.4333953941292472, 0.6794095682990244, 0.8650633666889845, 0.9739065285171717];
|
|
755
|
+
const GL_W = [0.0666713443086881, 0.1494513491505806, 0.219086362515982, 0.2692667193099963, 0.2955242247147529,
|
|
756
|
+
0.2955242247147529, 0.2692667193099963, 0.219086362515982, 0.1494513491505806, 0.0666713443086881];
|
|
757
|
+
/** ∫_a^c f by ten-point Gauss-Legendre, halving the panels until the halves agree to 1e-13 of the total. */
|
|
758
|
+
function adaptiveGL(f, a, c) {
|
|
759
|
+
const gl = (lo, hi) => {
|
|
760
|
+
const m = (lo + hi) / 2;
|
|
761
|
+
const h = (hi - lo) / 2;
|
|
762
|
+
let s = 0;
|
|
763
|
+
for (let k = 0; k < 10; k++)
|
|
764
|
+
s += GL_W[k] * f(m + h * GL_X[k]);
|
|
765
|
+
return s * h;
|
|
766
|
+
};
|
|
767
|
+
// start from panels that grow away from a (the integrand is largest near a)
|
|
768
|
+
const edges = [a];
|
|
769
|
+
for (let w = 1 / 64; edges[edges.length - 1] < c; w *= 2)
|
|
770
|
+
edges.push(Math.min(c, edges[edges.length - 1] + w));
|
|
771
|
+
const panels = edges.slice(1).map((hi, k) => ({ lo: edges[k], hi, v: gl(edges[k], hi) }));
|
|
772
|
+
const scale = Math.abs(panels.reduce((s, p) => s + p.v, 0));
|
|
773
|
+
let total = 0;
|
|
774
|
+
const stack = panels.map((p) => ({ ...p, depth: 0 }));
|
|
775
|
+
while (stack.length) {
|
|
776
|
+
const p = stack.pop();
|
|
777
|
+
const m = (p.lo + p.hi) / 2;
|
|
778
|
+
const left = gl(p.lo, m);
|
|
779
|
+
const right = gl(m, p.hi);
|
|
780
|
+
if (Math.abs(left + right - p.v) <= 1e-13 * scale || p.depth >= 40)
|
|
781
|
+
total += left + right;
|
|
782
|
+
else
|
|
783
|
+
stack.push({ lo: p.lo, hi: m, v: left, depth: p.depth + 1 }, { lo: m, hi: p.hi, v: right, depth: p.depth + 1 });
|
|
784
|
+
}
|
|
785
|
+
return total;
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* P(lower < Z < upper), Z ~ N(0, cor), by Genz's separation of variables with a Richtmyer lattice (see
|
|
789
|
+
* {@link pmaxAbsExceed}); relative accuracy about 1e-6.
|
|
790
|
+
*/
|
|
791
|
+
function genzLattice(lower, upper, cor) {
|
|
792
|
+
const d = cor.length;
|
|
793
|
+
// Cholesky (positive semidefinite: a zero pivot makes that variable a combination of the earlier ones)
|
|
794
|
+
const L = Array.from({ length: d }, () => new Array(d).fill(0));
|
|
795
|
+
for (let i = 0; i < d; i++) {
|
|
796
|
+
for (let j = 0; j <= i; j++) {
|
|
797
|
+
let s = cor[i][j];
|
|
798
|
+
for (let k = 0; k < j; k++)
|
|
799
|
+
s -= L[i][k] * L[j][k];
|
|
800
|
+
if (i === j)
|
|
801
|
+
L[i][i] = s > 1e-12 ? Math.sqrt(s) : 0;
|
|
802
|
+
else
|
|
803
|
+
L[i][j] = L[j][j] > 0 ? s / L[j][j] : 0;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
|
|
807
|
+
const gen = Array.from({ length: Math.max(1, d - 1) }, (_, j) => {
|
|
808
|
+
const s = Math.sqrt(primes[j % primes.length] + 100 * Math.floor(j / primes.length));
|
|
809
|
+
return s - Math.floor(s);
|
|
810
|
+
});
|
|
811
|
+
let seed = 0x2545f491;
|
|
812
|
+
const rand = () => {
|
|
813
|
+
seed ^= seed << 13;
|
|
814
|
+
seed ^= seed >>> 17;
|
|
815
|
+
seed ^= seed << 5;
|
|
816
|
+
return (seed >>> 0) / 4294967296;
|
|
817
|
+
};
|
|
818
|
+
// Each interval's width from the tail it lies in (the upper tail where both bounds are above the conditional mean), so
|
|
819
|
+
// that a tiny probability such as Z >= b keeps its relative accuracy; the draw inverts within the same tail.
|
|
820
|
+
const lowerTail = (x) => (x === -Infinity ? 0 : x === Infinity ? 1 : pnorm1(x, 0, 1, true, false));
|
|
821
|
+
const upperTail = (x) => (x === -Infinity ? 1 : x === Infinity ? 0 : pnorm1(x, 0, 1, false, false));
|
|
822
|
+
const y = new Array(d);
|
|
823
|
+
const point = (w) => {
|
|
824
|
+
let f = 1;
|
|
825
|
+
for (let i = 0; i < d; i++) {
|
|
826
|
+
let s = 0;
|
|
827
|
+
for (let k = 0; k < i; k++)
|
|
828
|
+
s += L[i][k] * y[k];
|
|
829
|
+
const l = L[i][i];
|
|
830
|
+
if (l === 0) {
|
|
831
|
+
if (!(s >= lower[i] && s <= upper[i]))
|
|
832
|
+
return 0;
|
|
833
|
+
if (i < d - 1)
|
|
834
|
+
y[i] = 0;
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const a = (lower[i] - s) / l;
|
|
838
|
+
const c = (upper[i] - s) / l;
|
|
839
|
+
const upperSide = a > 0;
|
|
840
|
+
const ta = upperSide ? upperTail(a) : lowerTail(a);
|
|
841
|
+
const tc = upperSide ? upperTail(c) : lowerTail(c);
|
|
842
|
+
const width = upperSide ? ta - tc : tc - ta;
|
|
843
|
+
f *= width;
|
|
844
|
+
if (!(f > 0))
|
|
845
|
+
return 0;
|
|
846
|
+
if (i < d - 1) {
|
|
847
|
+
const u = Math.max(upperSide ? ta - w[i] * width : ta + w[i] * width, 1e-300);
|
|
848
|
+
y[i] = upperSide ? -qnorm1(u, 0, 1, true, false) : qnorm1(Math.min(u, 1 - 1e-16), 0, 1, true, false);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return f;
|
|
852
|
+
};
|
|
853
|
+
const shifts = 10;
|
|
854
|
+
let N = 1009;
|
|
855
|
+
let est = NaN;
|
|
856
|
+
const w = new Array(d - 1);
|
|
857
|
+
for (let round = 0; round < 10; round++) {
|
|
858
|
+
const vals = [];
|
|
859
|
+
for (let s = 0; s < shifts; s++) {
|
|
860
|
+
const shift = gen.map(() => rand());
|
|
861
|
+
let acc = 0;
|
|
862
|
+
for (let k = 1; k <= N; k++) {
|
|
863
|
+
for (let j = 0; j < d - 1; j++) {
|
|
864
|
+
const x = (k * gen[j] + shift[j]) % 1;
|
|
865
|
+
w[j] = Math.abs(2 * x - 1);
|
|
866
|
+
}
|
|
867
|
+
acc += point(w);
|
|
868
|
+
}
|
|
869
|
+
vals.push(acc / N);
|
|
870
|
+
}
|
|
871
|
+
const m = vals.reduce((s, v) => s + v, 0) / shifts;
|
|
872
|
+
const se = Math.sqrt(vals.reduce((s, v) => s + (v - m) ** 2, 0) / (shifts - 1) / shifts);
|
|
873
|
+
est = m;
|
|
874
|
+
if (2 * se <= 1e-6 * m || m === 0)
|
|
875
|
+
break;
|
|
876
|
+
N *= 2;
|
|
877
|
+
}
|
|
878
|
+
return est;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Time-dependent sensitivity, specificity and predictive values of the rule "marker > cutpoint", with the weights of
|
|
882
|
+
* {@link timeROC}: PPV = TP F / (TP F + FP S) and NPV = (1 − FP) S / ((1 − FP) S + (1 − TP) F) (F the cumulative
|
|
883
|
+
* incidence, S its complement); with competing risks PPV and NPV_2 with definition (ii) and NPV_1 = (1 − FP_1) S_1 /
|
|
884
|
+
* ((1 − FP_2) S_2 + (1 − TP) F). With `iid` (marginal weights), the iid representations and standard errors of Se,
|
|
885
|
+
* Sp (both definitions), PPV and the NPVs.
|
|
886
|
+
*
|
|
887
|
+
* Differences from R: as {@link timeROC}; Sp2's denominator is the weighted mass of the definition (ii) controls (R's
|
|
888
|
+
* 1 − F, the same unless events fall at t).
|
|
889
|
+
*
|
|
890
|
+
* Equivalent to `timeROC::SeSpPPVNPV()` in R.
|
|
891
|
+
*
|
|
892
|
+
* @param cutpoint the marker's threshold
|
|
893
|
+
* @param time observed times
|
|
894
|
+
* @param delta 0 censored, otherwise the kind of event
|
|
895
|
+
* @param marker the marker
|
|
896
|
+
* @param options `times` (required) and the options of timeROC
|
|
897
|
+
* @category Survival analysis
|
|
898
|
+
*/
|
|
899
|
+
export function seSpPPVNPV(cutpoint, time, delta, marker, options) {
|
|
900
|
+
checkOptions(options, SE_SP_PPVNPV_KEYS, "seSpPPVNPV"); // generated: option-keys.mjs
|
|
901
|
+
if (typeof cutpoint !== "number" || Number.isNaN(cutpoint))
|
|
902
|
+
throw new RangeError("'cutpoint' must be a number");
|
|
903
|
+
const p = prepareFit(time, delta, marker, options, "seSpPPVNPV");
|
|
904
|
+
const iid = options.iid ?? false;
|
|
905
|
+
if (iid && p.weighting !== "marginal")
|
|
906
|
+
throw new RangeError("weighting must be marginal for computing the iid representation (as R)");
|
|
907
|
+
const { data, competing } = p;
|
|
908
|
+
const pos = data.marker.map((m) => (m > cutpoint ? 1 : 0));
|
|
909
|
+
const ats = atTimes(p);
|
|
910
|
+
const res = ats.map((at) => {
|
|
911
|
+
const sel = (pred) => at.role.map((r, i) => (pred(r, i) ? 1 : 0));
|
|
912
|
+
const isC1 = (r) => r === 2;
|
|
913
|
+
const isC2 = (r) => r === 2 || r === 3;
|
|
914
|
+
const T = (f) => total(data, at, f);
|
|
915
|
+
const aP = T(sel((r, i) => r === 1 && pos[i] === 1));
|
|
916
|
+
const a = T(sel((r) => r === 1));
|
|
917
|
+
const aN = T(sel((r, i) => r === 1 && pos[i] === 0));
|
|
918
|
+
const c1P = T(sel((r, i) => isC1(r) && pos[i] === 1));
|
|
919
|
+
const c1 = T(sel(isC1));
|
|
920
|
+
const c1N = T(sel((r, i) => isC1(r) && pos[i] === 0));
|
|
921
|
+
const c2P = T(sel((r, i) => isC2(r) && pos[i] === 1));
|
|
922
|
+
const c2 = T(sel(isC2));
|
|
923
|
+
const c2N = T(sel((r, i) => isC2(r) && pos[i] === 0));
|
|
924
|
+
const sum = (x, y) => ({ value: x.value + y.value, inf: x.inf.map((v, k) => v + y.inf[k]) });
|
|
925
|
+
const se = { value: aP.value / a.value, inf: ratioInf(aP, a) };
|
|
926
|
+
const fp1 = c1P.value / c1.value;
|
|
927
|
+
const fp2 = c2P.value / c2.value;
|
|
928
|
+
const sp1 = ratioInf(c1P, c1).map((v) => -v);
|
|
929
|
+
const sp2 = ratioInf(c2P, c2).map((v) => -v);
|
|
930
|
+
const ppvD = sum(aP, c2P);
|
|
931
|
+
const negD = sum(c2N, aN);
|
|
932
|
+
return {
|
|
933
|
+
tp: se.value, fp1, fp2,
|
|
934
|
+
ppv: aP.value / ppvD.value, npv1: c1N.value / negD.value, npv2: c2N.value / negD.value,
|
|
935
|
+
inf: { se: se.inf, sp1, sp2, ppv: ratioInf(aP, ppvD), npv1: ratioInf(c1N, negD), npv2: ratioInf(c2N, negD) },
|
|
936
|
+
stats: { ...statsOf(at, competing), positive: pos.reduce((s, v) => s + v, 0), negative: pos.length - pos.reduce((s, v) => s + v, 0) },
|
|
937
|
+
};
|
|
938
|
+
});
|
|
939
|
+
const keys = ["se", "sp1", "sp2", "ppv", "npv1", "npv2"];
|
|
940
|
+
const inference = iid
|
|
941
|
+
? {
|
|
942
|
+
se: Object.fromEntries(keys.map((k) => [k, res.map((r) => sdOver(r.inf[k]))])),
|
|
943
|
+
iid: Object.fromEntries(keys.map((k) => [k, res.map((r) => sorted(data, r.inf[k]))])),
|
|
944
|
+
}
|
|
945
|
+
: undefined;
|
|
946
|
+
const weights = (p.cond === null
|
|
947
|
+
? { method: "marginal", ipcwTimes: p.times.map((t) => marginalG(data, t).Gt), ipcwSubjectTimes: sorted(data, data.ti.map((k) => (k > 0 ? data.G[k - 1] : 1))) }
|
|
948
|
+
: { method: p.weighting, ipcwTimes: p.cond.at.map((g) => sorted(data, g)), ipcwSubjectTimes: sorted(data, p.cond.left) });
|
|
949
|
+
return {
|
|
950
|
+
cutpoint, times: p.times, n: data.n, competingRisks: competing,
|
|
951
|
+
tp: res.map((r) => r.tp),
|
|
952
|
+
...(competing ? { fp1: res.map((r) => r.fp1), fp2: res.map((r) => r.fp2) } : { fp: res.map((r) => r.fp1) }),
|
|
953
|
+
ppv: res.map((r) => r.ppv),
|
|
954
|
+
...(competing ? { npv1: res.map((r) => r.npv1), npv2: res.map((r) => r.npv2) } : { npv: res.map((r) => r.npv1) }),
|
|
955
|
+
stats: res.map((r) => r.stats),
|
|
956
|
+
weights,
|
|
957
|
+
...(inference ? { inference } : {}),
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* The values that R's `plotAUCcurve` draws: the AUC over the times with the pointwise confidence interval and the
|
|
962
|
+
* simultaneous band of {@link timeROCConfint} (as proportions). No plot.
|
|
963
|
+
*
|
|
964
|
+
* Equivalent to `timeROC::plotAUCcurve()` in R.
|
|
965
|
+
*
|
|
966
|
+
* @param fit a result of {@link timeROC} with `iid: true`
|
|
967
|
+
* @param options `level`, `nSim` and `fp`
|
|
968
|
+
* @category Survival analysis
|
|
969
|
+
*/
|
|
970
|
+
export function timeROCAucCurve(fit, options = {}) {
|
|
971
|
+
checkOptions(options, TIME_ROCAUC_CURVE_KEYS, "timeROCAucCurve"); // generated: option-keys.mjs
|
|
972
|
+
const which = options.fp ?? 1;
|
|
973
|
+
if (which !== 1 && which !== 2)
|
|
974
|
+
throw new RangeError("'fp' must be 1 or 2");
|
|
975
|
+
const level = options.level ?? 0.95;
|
|
976
|
+
if (!(level > 0 && level < 1))
|
|
977
|
+
throw new RangeError("'level' must be in (0, 1)");
|
|
978
|
+
const nSim = options.nSim ?? 2000;
|
|
979
|
+
if (!Number.isInteger(nSim) || nSim < 1)
|
|
980
|
+
throw new RangeError("'nSim' must be a positive integer");
|
|
981
|
+
const a = iidOf(fit, which);
|
|
982
|
+
const iv = intervals([a], level, nSim)[0];
|
|
983
|
+
return {
|
|
984
|
+
times: fit.times, auc: a.auc,
|
|
985
|
+
lower: iv.ci.map((c) => c[0] / 100), upper: iv.ci.map((c) => c[1] / 100),
|
|
986
|
+
bandLower: iv.band.map((c) => c[0] / 100), bandUpper: iv.band.map((c) => c[1] / 100),
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* The values behind R's `plotAUCcurveDiff`: the difference of two time-dependent AUCs over the times with the
|
|
991
|
+
* pointwise confidence interval from the difference of the iid representations (as {@link timeROCCompare}). R also
|
|
992
|
+
* draws a simultaneous band, whose simulation cannot be checked (R returns nothing); it is not offered. No plot.
|
|
993
|
+
*
|
|
994
|
+
* Not an R function.
|
|
995
|
+
*
|
|
996
|
+
* @param x a result of {@link timeROC} with `iid: true`
|
|
997
|
+
* @param y another, on the same subjects and times
|
|
998
|
+
* @param options `level` and `fp`
|
|
999
|
+
* @category Survival analysis
|
|
1000
|
+
*/
|
|
1001
|
+
export function timeROCAucDiff(x, y, options = {}) {
|
|
1002
|
+
checkOptions(options, TIME_ROCAUC_DIFF_KEYS, "timeROCAucDiff"); // generated: option-keys.mjs
|
|
1003
|
+
const which = options.fp ?? 1;
|
|
1004
|
+
if (which !== 1 && which !== 2)
|
|
1005
|
+
throw new RangeError("'fp' must be 1 or 2");
|
|
1006
|
+
const level = options.level ?? 0.95;
|
|
1007
|
+
if (!(level > 0 && level < 1))
|
|
1008
|
+
throw new RangeError("'level' must be in (0, 1)");
|
|
1009
|
+
timeROCCompare(x, y);
|
|
1010
|
+
const a = iidOf(x, which);
|
|
1011
|
+
const b = iidOf(y, which);
|
|
1012
|
+
const z = qnorm((1 + level) / 2);
|
|
1013
|
+
const diff = a.auc.map((v, j) => v - b.auc[j]);
|
|
1014
|
+
const se = a.iid.map((col, j) => sdOver(col.map((v, i) => v - b.iid[j][i])));
|
|
1015
|
+
return { times: x.times, diff, lower: diff.map((v, j) => v - z * se[j]), upper: diff.map((v, j) => v + z * se[j]) };
|
|
1016
|
+
}
|
|
1017
|
+
/** Kaplan-Meier survival at t of the subjects selected by `sel`, over the subjects sorted by time (events before
|
|
1018
|
+
* censorings at a tie). */
|
|
1019
|
+
function kmOf(time, status, byTime, sel, t) {
|
|
1020
|
+
let atRisk = 0;
|
|
1021
|
+
for (const i of byTime)
|
|
1022
|
+
if (sel(i))
|
|
1023
|
+
atRisk++;
|
|
1024
|
+
let surv = 1;
|
|
1025
|
+
let k = 0;
|
|
1026
|
+
while (k < byTime.length && time[byTime[k]] <= t) {
|
|
1027
|
+
const u = time[byTime[k]];
|
|
1028
|
+
let ev = 0;
|
|
1029
|
+
let all = 0;
|
|
1030
|
+
for (; k < byTime.length && time[byTime[k]] === u; k++) {
|
|
1031
|
+
const i = byTime[k];
|
|
1032
|
+
if (!sel(i))
|
|
1033
|
+
continue;
|
|
1034
|
+
if (status[i] === 1)
|
|
1035
|
+
ev++;
|
|
1036
|
+
all++;
|
|
1037
|
+
}
|
|
1038
|
+
if (atRisk > 0 && ev > 0)
|
|
1039
|
+
surv *= 1 - ev / atRisk;
|
|
1040
|
+
atRisk -= all;
|
|
1041
|
+
}
|
|
1042
|
+
return surv;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Time-dependent ROC curve at a prediction time by Heagerty, Lumley and Pepe's Kaplan-Meier estimator: S(c, t) =
|
|
1046
|
+
* KM_{marker > c}(t) P(marker > c), TP(c) = (P(marker > c) − S(c, t)) / (1 − S(t)), FP(c) = S(c, t) / S(t) (neither
|
|
1047
|
+
* is forced to be monotone or below 1, as R), and the AUC by the trapezoid over the thresholds in order.
|
|
1048
|
+
*
|
|
1049
|
+
* Differences from R: only the Kaplan-Meier estimator (`method = "KM"`); R's default, the nearest-neighbour estimator,
|
|
1050
|
+
* is not offered.
|
|
1051
|
+
*
|
|
1052
|
+
* Equivalent to `survivalROC::survivalROC()` in R.
|
|
1053
|
+
*
|
|
1054
|
+
* @param time observed times
|
|
1055
|
+
* @param status 1 event, 0 censored
|
|
1056
|
+
* @param marker the marker
|
|
1057
|
+
* @param options `predictTime` (required), `cutValues` and `method`
|
|
1058
|
+
* @category Survival analysis
|
|
1059
|
+
*/
|
|
1060
|
+
export function survivalROC(time, status, marker, options) {
|
|
1061
|
+
checkOptions(options, SURVIVAL_ROC_KEYS, "survivalROC"); // generated: option-keys.mjs
|
|
1062
|
+
if (options === null || typeof options !== "object")
|
|
1063
|
+
throw new TypeError("survivalROC: 'options' with 'predictTime' is required");
|
|
1064
|
+
if ((options.method ?? "KM") !== "KM")
|
|
1065
|
+
throw new RangeError(`only method "KM" is offered (the nearest-neighbour estimator "NNE" is not)`);
|
|
1066
|
+
const keep = completeCases(time, status, marker);
|
|
1067
|
+
const t = keep.map((i) => time[i]);
|
|
1068
|
+
const st = keep.map((i) => status[i]);
|
|
1069
|
+
const m = keep.map((i) => marker[i]);
|
|
1070
|
+
const n = t.length;
|
|
1071
|
+
if (n === 0)
|
|
1072
|
+
throw new RangeError("no subjects (without NA)");
|
|
1073
|
+
for (const e of st)
|
|
1074
|
+
if (e !== 0 && e !== 1)
|
|
1075
|
+
throw new RangeError("'status' must be 0 or 1");
|
|
1076
|
+
const pt = options.predictTime;
|
|
1077
|
+
if (typeof pt !== "number" || !Number.isFinite(pt))
|
|
1078
|
+
throw new RangeError("'predictTime' must be a finite number");
|
|
1079
|
+
// R sorts given thresholds and, from two given thresholds on, sets the last point to (0, 0) even when markers lie
|
|
1080
|
+
// above it; a single given threshold is computed (log 48, 52)
|
|
1081
|
+
const cuts = options.cutValues === undefined ? [...new Set(m)].sort((a, b) => a - b) : checkVector(options.cutValues, "cutValues").sort((a, b) => a - b);
|
|
1082
|
+
const byTime = Array.from({ length: n }, (_, i) => i).sort((a, b) => t[a] - t[b]);
|
|
1083
|
+
const St = kmOf(t, st, byTime, () => true, pt);
|
|
1084
|
+
const cutValues = [-Infinity, ...cuts];
|
|
1085
|
+
const tp = [];
|
|
1086
|
+
const fp = [];
|
|
1087
|
+
for (const [k, c] of cutValues.entries()) {
|
|
1088
|
+
if (k === cutValues.length - 1 && cutValues.length > 2) {
|
|
1089
|
+
tp.push(0);
|
|
1090
|
+
fp.push(0);
|
|
1091
|
+
break;
|
|
1092
|
+
}
|
|
1093
|
+
const above = (i) => m[i] > c;
|
|
1094
|
+
const count = m.reduce((acc, v) => acc + (v > c ? 1 : 0), 0);
|
|
1095
|
+
const pc = count / n;
|
|
1096
|
+
const Sc = count > 0 ? kmOf(t, st, byTime, above, pt) * pc : 0;
|
|
1097
|
+
tp.push((pc - Sc) / (1 - St));
|
|
1098
|
+
fp.push(Sc / St);
|
|
1099
|
+
}
|
|
1100
|
+
let auc = 0;
|
|
1101
|
+
for (let k = 0; k + 1 < fp.length; k++)
|
|
1102
|
+
auc += (fp[k] - fp[k + 1]) * (tp[k] + tp[k + 1]) / 2;
|
|
1103
|
+
return { cutValues, tp, fp, predictTime: pt, survival: St, auc };
|
|
1104
|
+
}
|
|
1105
|
+
/** The pieces used by the tests' infinitesimal jackknife. @internal */
|
|
1106
|
+
export const timeROCInternals = { prepare, weightsAt, marginalG, total, aucInfluence };
|