@numero-uno-jpn/rstats 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.ja.md +7 -7
  3. package/README.md +7 -7
  4. package/dist/chunks/{chunk-HBRSUHSU.js → chunk-27VFB3SA.js} +2 -2
  5. package/dist/chunks/{chunk-Z74ZOTUN.js → chunk-56GFP4UU.js} +2 -2
  6. package/dist/chunks/{chunk-JJRZ2TTF.js → chunk-5SW3L6J3.js} +2 -2
  7. package/dist/chunks/{chunk-TZTVDVP4.js → chunk-6FZAJQ4H.js} +2 -2
  8. package/dist/chunks/{chunk-I5NWGQOQ.js → chunk-BQJFFGYP.js} +2 -2
  9. package/dist/chunks/{chunk-2VZW4XPK.js → chunk-F6Z3GLWA.js} +2 -2
  10. package/dist/chunks/{chunk-LA4H6ZSC.js → chunk-GBSMRVUY.js} +2 -2
  11. package/dist/chunks/{chunk-P7ZHH2SF.js → chunk-GEF2YRBV.js} +2 -2
  12. package/dist/chunks/{chunk-6X2ZMPF5.js → chunk-GIER5WMB.js} +2 -2
  13. package/dist/chunks/{chunk-AJZV2SVY.js → chunk-GLGOV3A5.js} +2 -2
  14. package/dist/chunks/{chunk-6TZVS6WC.js → chunk-H72MW7YP.js} +2 -2
  15. package/dist/chunks/{chunk-UJYRU37Z.js → chunk-HWB7XRX2.js} +2 -2
  16. package/dist/chunks/chunk-J72MLFUG.js +2 -0
  17. package/dist/chunks/{chunk-PDHBRDTF.js → chunk-PZ66PUWC.js} +1 -1
  18. package/dist/chunks/{chunk-FFNHG5SB.js → chunk-RUZATICF.js} +1 -1
  19. package/dist/chunks/{chunk-UMDXXT3M.js → chunk-RY7CCWVU.js} +1 -1
  20. package/dist/chunks/{chunk-UOAFEB64.js → chunk-S2YCFUCA.js} +2 -2
  21. package/dist/chunks/chunk-SVS54D6Z.js +2 -0
  22. package/dist/chunks/{chunk-LNUNKFIH.js → chunk-TEHMTQNB.js} +2 -2
  23. package/dist/chunks/{chunk-IJV43Y7Q.js → chunk-UMMCVF53.js} +2 -2
  24. package/dist/chunks/{chunk-BNTBZ5W3.js → chunk-UNP4HBPP.js} +2 -2
  25. package/dist/chunks/{chunk-LMNU4NHZ.js → chunk-V2KVTAVV.js} +2 -2
  26. package/dist/chunks/{chunk-EBRTF7RM.js → chunk-WWJGCBWH.js} +1 -1
  27. package/dist/chunks/chunk-X7K6EF7S.js +2 -0
  28. package/dist/chunks/{chunk-GUM57VVM.js → chunk-YBOSCQF2.js} +1 -1
  29. package/dist/chunks/{chunk-IOGQEMDE.js → chunk-ZQSOMEIM.js} +2 -2
  30. package/dist/chunks/{chunk-RCGW2DCK.js → chunk-ZRFZ5UIB.js} +2 -2
  31. package/dist/descriptive.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +4 -0
  34. package/dist/entries/tests.js +4 -0
  35. package/dist/linalg.js +2 -2
  36. package/dist/mixed.js +2 -2
  37. package/dist/models/competingRisks.d.ts +188 -0
  38. package/dist/models/competingRisks.js +673 -0
  39. package/dist/models/coxZph.d.ts +67 -0
  40. package/dist/models/coxZph.js +479 -0
  41. package/dist/models/coxph.d.ts +61 -21
  42. package/dist/models/coxph.js +305 -65
  43. package/dist/models/rmst2.d.ts +126 -0
  44. package/dist/models/rmst2.js +365 -0
  45. package/dist/models/survival.d.ts +65 -24
  46. package/dist/models/survival.js +407 -72
  47. package/dist/models/survreg.d.ts +160 -0
  48. package/dist/models/survreg.js +809 -0
  49. package/dist/numerics.js +2 -2
  50. package/dist/rstats.js +16 -16
  51. package/dist/special.js +2 -2
  52. package/dist/tests.js +13 -13
  53. package/llms.txt +8 -0
  54. package/package.json +1 -1
  55. package/dist/chunks/chunk-4OOTEXZU.js +0 -2
  56. package/dist/chunks/chunk-MJXETGT2.js +0 -2
@@ -0,0 +1,673 @@
1
+ // Competing-risks cumulative incidence and Fine-Gray regression.
2
+ //
3
+ // Written for rStats.js (no ported code) from oracle/competing-behaviour.md and the published methods:
4
+ // Gray (1988), "A class of K-sample tests for comparing the cumulative incidence of a competing risk",
5
+ // Annals of Statistics 16, 1141-1154; Fine and Gray (1999), "A proportional hazards model for the
6
+ // subdistribution of a competing risk", JASA 94, 496-509; Kalbfleisch and Prentice (1980).
7
+ // Kaplan-Meier censoring estimates are delegated to the verified survfit implementation.
8
+ import { pchisq } from "../distributions/chisq.js";
9
+ import { pnorm, qnorm } from "../distributions/normal.js";
10
+ import { factorLabels, compareLabels } from "../htest/groups.js";
11
+ import { levelText } from "../internal/levels.js";
12
+ import { reported, Warnings } from "../internal/warnings.js";
13
+ import { sum } from "../internal/summary.js";
14
+ import { solve } from "../linalg/solve.js";
15
+ import { survfit } from "./survival.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const CUMINC_KEYS = ["group", "strata", "rho", "cencode"];
19
+ const CRR_KEYS = /* @__PURE__ */ new Set([
20
+ "cov2", "tf", "failcode", "cencode", "gtol", "maxiter", "init", "variance", "confLevel", "names",
21
+ ]);
22
+ function missingLabel(x) {
23
+ return x === null || x === undefined || (typeof x === "number" && Number.isNaN(x));
24
+ }
25
+ function labelLevels(values) {
26
+ const normalized = factorLabels(values);
27
+ const labels = Array.from(new Set(normalized)).sort(compareLabels);
28
+ return { labels, index: new Map(labels.map((v, i) => [v, i])) };
29
+ }
30
+ function validateVectorLengths(time, status, options) {
31
+ if (time.length !== status.length)
32
+ throw new RangeError("'time' and 'status' must have the same length");
33
+ if (options.group !== undefined && options.group.length !== time.length)
34
+ throw new RangeError("'group' must have the same length as 'time'");
35
+ if (options.strata !== undefined && options.strata.length !== time.length)
36
+ throw new RangeError("'strata' must have the same length as 'time'");
37
+ }
38
+ /**
39
+ * Cumulative incidence functions and Gray's tests for competing risks. Equivalent to `cmprsk::cuminc()` in R.
40
+ * Uses the Aalen-Johansen cumulative-incidence estimator and Gray's weighted test; tied-time
41
+ * variance uses the documented hypergeometric correction.
42
+ *
43
+ * @param time Follow-up times (finite and non-negative).
44
+ * @param status Event codes; every code other than `cencode` is a competing event cause.
45
+ * @param options See {@link CumincOptions}.
46
+ * @returns One step-function curve for each group and cause, optional Gray tests, and warnings.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const fit = cuminc([1, 2, 3, 4], [1, 0, 2, 1]);
51
+ * fit.curves[0]!.est;
52
+ * ```
53
+ *
54
+ * @category Survival analysis
55
+ */
56
+ export function cuminc(time, status, options = {}) {
57
+ checkOptions(options, CUMINC_KEYS, "cuminc"); // generated: option-keys.mjs
58
+ validateVectorLengths(time, status, options);
59
+ const { group, strata, rho = 0, cencode = 0 } = options;
60
+ const keep = [];
61
+ const warnings = new Warnings();
62
+ for (let i = 0; i < time.length; i++) {
63
+ if (Number.isNaN(time[i]) || missingLabel(status[i]) ||
64
+ (group !== undefined && missingLabel(group[i])) ||
65
+ (strata !== undefined && missingLabel(strata[i])))
66
+ continue;
67
+ if (!Number.isFinite(time[i]))
68
+ throw new RangeError("'time' must contain only finite values");
69
+ if (time[i] < 0)
70
+ throw new RangeError("'time' must be non-negative");
71
+ keep.push(i);
72
+ }
73
+ const omitted = time.length - keep.length;
74
+ if (omitted > 0)
75
+ warnings.add(`${omitted} cases omitted due to missing values`);
76
+ if (keep.length === 0)
77
+ throw new RangeError("no complete observations");
78
+ const groupValues = group === undefined ? [1] : factorLabels(keep.map((i) => group[i]));
79
+ const strataValues = strata === undefined ? [1] : factorLabels(keep.map((i) => strata[i]));
80
+ const statusValues = factorLabels([...keep.map((i) => status[i]), cencode]);
81
+ const gs = labelLevels(groupValues);
82
+ if (gs.labels.length >= 2 && !Number.isFinite(rho))
83
+ throw new RangeError("'rho' must be finite when Gray's test is requested");
84
+ const ss = labelLevels(strataValues);
85
+ const cs = labelLevels(statusValues);
86
+ const cencodeValue = statusValues[statusValues.length - 1];
87
+ const causes = cs.labels.filter((x) => x !== cencodeValue);
88
+ if (causes.length === 0)
89
+ throw new Error("there are no events of any cause");
90
+ const rows = keep.map((i) => ({
91
+ time: time[i],
92
+ status: statusValues[keep.indexOf(i)],
93
+ group: group === undefined ? 0 : gs.index.get(groupValues[keep.indexOf(i)]),
94
+ strata: strata === undefined ? 0 : ss.index.get(strataValues[keep.indexOf(i)]),
95
+ source: i,
96
+ })).sort((a, b) => a.time - b.time);
97
+ const curves = [];
98
+ for (const cause of causes) {
99
+ const causeText = levelText(cause);
100
+ for (let g = 0; g < gs.labels.length; g++) {
101
+ const rr = rows.filter((r) => r.group === g);
102
+ const maxTime = rr.reduce((m, r) => Math.max(m, r.time), -Infinity);
103
+ // survfit's timefix uses an absolute sqrt(eps) threshold; scale sub-unit times first so
104
+ // genuinely distinct small times are not collapsed (cuminc itself is scale invariant).
105
+ const timeScale = maxTime > 0 && maxTime < 1
106
+ ? 2 ** Math.min(1023, Math.ceil(-Math.log2(maxTime))) : 1;
107
+ const km = survfit(rr.map((r) => r.time * timeScale), rr.map((r) => (r.status === cencodeValue ? 0 : 1)));
108
+ const times = [0];
109
+ const ests = [0];
110
+ const vars = [0];
111
+ const eventRows = [];
112
+ let S = 1;
113
+ for (let j = 0; j < km.time.length; j++) {
114
+ const d = km.nEvent[j];
115
+ if (d === 0)
116
+ continue;
117
+ const t = km.time[j] / timeScale;
118
+ const Y = km.nRisk[j];
119
+ const dk = rr.filter((r) => r.time === t && r.status === cause).length;
120
+ eventRows.push({ t, Y, d, dk, sb: S, sa: km.surv[j] });
121
+ S = km.surv[j];
122
+ }
123
+ let F = 0;
124
+ let V = 0;
125
+ for (let j = 0; j < eventRows.length; j++) {
126
+ const e = eventRows[j];
127
+ const beforeF = F;
128
+ const beforeV = V;
129
+ F += (e.sb * e.dk) / e.Y;
130
+ let v = 0;
131
+ for (let l = 0; l <= j; l++) {
132
+ const x = eventRows[l];
133
+ const Y = x.Y, d = x.d, dk = x.dk;
134
+ const a = Y === d ? 0 : (d * (Y - d) + 2 * dk * (d - dk)) / ((Y - 1) * (Y - d) ** 2);
135
+ const b = Y === 1 ? dk : (dk * (Y - dk)) / (Y * Y * (Y - 1));
136
+ const c = Y === d || Y === 1 ? 0 : (dk * (Y - dk)) / (Y * (Y - d) * (Y - 1));
137
+ // F_k(t_l) is the estimate immediately after time t_l.
138
+ let Fl = 0;
139
+ for (let q = 0; q <= l; q++) {
140
+ const z = eventRows[q];
141
+ Fl += (z.sb * z.dk) / z.Y;
142
+ }
143
+ const diff = F - Fl;
144
+ v += diff * diff * a + x.sb * x.sb * b - 2 * diff * x.sb * c;
145
+ }
146
+ V = Math.max(0, v);
147
+ if (e.dk > 0) {
148
+ times.push(e.t, e.t);
149
+ ests.push(beforeF, F);
150
+ vars.push(beforeV, V);
151
+ }
152
+ }
153
+ times.push(maxTime);
154
+ ests.push(F);
155
+ vars.push(V);
156
+ curves.push({ name: `${levelText(gs.labels[g])} ${causeText}`, group: levelText(gs.labels[g]), cause: causeText,
157
+ time: times, est: ests, var: vars });
158
+ }
159
+ }
160
+ const tests = gs.labels.length >= 2 ? grayTests(rows, gs.labels, causes, ss.labels.length, rho, cencodeValue) : undefined;
161
+ return reported("cuminc", { curves, ...(tests === undefined ? {} : { tests }), warnings: warnings.list });
162
+ }
163
+ /** Gray's score and covariance, summed over strata; the tied-time own-score term gets the chosen hypergeometric factor. */
164
+ function grayTests(rows, groups, causes, nStrata, rho, cencode) {
165
+ const out = [];
166
+ for (const cause of causes) {
167
+ const K = groups.length;
168
+ const z = new Array(K).fill(0);
169
+ const V = Array.from({ length: K }, () => new Array(K).fill(0));
170
+ for (let st = 0; st < nStrata; st++) {
171
+ const rr = rows.filter((r) => r.strata === st);
172
+ const eventTimes = Array.from(new Set(rr.filter((r) => r.status !== cencode).map((r) => r.time))).sort((a, b) => a - b);
173
+ const S = new Array(K).fill(1);
174
+ const F = new Array(K).fill(0);
175
+ const records = [];
176
+ for (const t of eventTimes) {
177
+ const Y = new Array(K).fill(0), d1 = new Array(K).fill(0), d2 = new Array(K).fill(0);
178
+ for (const r of rr)
179
+ if (r.time >= t)
180
+ Y[r.group]++;
181
+ for (const r of rr)
182
+ if (r.time === t && r.status !== cencode) {
183
+ if (r.status === cause)
184
+ d1[r.group]++;
185
+ else
186
+ d2[r.group]++;
187
+ }
188
+ const sb = S.slice(), fb = F.slice();
189
+ const h = Y.map((y, g) => y === 0 ? 0 : y / sb[g]);
190
+ const R = Y.map((y, g) => y === 0 ? 0 : y * (1 - fb[g]) / sb[g]);
191
+ const d = d1.reduce((a, b) => a + b, 0);
192
+ const htot = h.reduce((a, b) => a + b, 0);
193
+ const dF0 = htot === 0 ? 0 : d / htot;
194
+ const gb = records.length === 0 ? 1 : records[records.length - 1].Gafter;
195
+ const ga = gb - dF0;
196
+ const rtot = R.reduce((a, b) => a + b, 0);
197
+ for (let g = 0; g < K; g++) {
198
+ const L = gb ** rho;
199
+ if (rtot > 0)
200
+ z[g] += L * (d1[g] - (R[g] * d) / rtot);
201
+ if (Y[g] > 0) {
202
+ S[g] = S[g] * (1 - (d1[g] + d2[g]) / Y[g]);
203
+ F[g] += (sb[g] * d1[g]) / Y[g];
204
+ }
205
+ else
206
+ S[g] = 0;
207
+ }
208
+ records.push({ time: t, Y, d1, d2, Sbefore: sb, Safter: S.slice(), Fbefore: fb, h, R, dF0, Gbefore: gb, Gafter: ga });
209
+ }
210
+ for (let k = 0; k < K; k++)
211
+ for (let kp = 0; kp < K; kp++) {
212
+ let covariance = 0;
213
+ for (let g = 0; g < K; g++)
214
+ for (let j = 0; j < records.length; j++) {
215
+ const e = records[j];
216
+ const htot = e.h.reduce((a, b) => a + b, 0);
217
+ if (!(htot > 0) || !(e.h[g] > 0))
218
+ continue;
219
+ const L = e.Gbefore ** rho;
220
+ const dkg = L * e.h[k] * ((k === g ? 1 : 0) - e.h[g] / htot);
221
+ const dpg = L * e.h[kp] * ((kp === g ? 1 : 0) - e.h[g] / htot);
222
+ let restK = 0, restP = 0;
223
+ for (let q = j + 1; q < records.length; q++) {
224
+ const x = records[q];
225
+ const ht = x.h.reduce((a, b) => a + b, 0);
226
+ if (!(ht > 0))
227
+ continue;
228
+ const Lq = x.Gbefore ** rho;
229
+ const d1 = Lq * x.h[k] * ((k === g ? 1 : 0) - x.h[g] / ht);
230
+ const d2 = Lq * x.h[kp] * ((kp === g ? 1 : 0) - x.h[g] / ht);
231
+ const dGamma = x.Gbefore === 0 ? 0 : x.dF0 / x.Gbefore;
232
+ restK += d1 * dGamma;
233
+ restP += d2 * dGamma;
234
+ }
235
+ const qv = e.Safter[g] === 0 ? 0 : e.Gafter / e.Safter[g];
236
+ const ak = dkg + (1 - qv) * restK;
237
+ const ap = dpg + (1 - qv) * restP;
238
+ const bk = -qv * restK;
239
+ const bp = -qv * restP;
240
+ const dF2 = e.Y[g] === 0 ? 0 : e.Sbefore[g] * e.d2[g] / e.Y[g];
241
+ let aa = ak * ap;
242
+ const d1tot = e.d1.reduce((a, b) => a + b, 0);
243
+ const Ytot = e.Y.reduce((a, b) => a + b, 0);
244
+ if (d1tot > 1 && Ytot > 1)
245
+ aa += ((Ytot - d1tot) / (Ytot - 1) - 1) * dkg * dpg;
246
+ covariance += (aa * e.dF0 + bk * bp * dF2) / e.h[g];
247
+ }
248
+ V[k][kp] += covariance;
249
+ }
250
+ }
251
+ const df = K - 1;
252
+ let statistic = NaN, pValue = NaN;
253
+ if (z.every((x) => x === 0)) {
254
+ statistic = 0;
255
+ pValue = 1;
256
+ }
257
+ else {
258
+ const sub = V.slice(0, df).map((row) => row.slice(0, df));
259
+ try {
260
+ const b = solve(sub, z.slice(0, df), { tol: 1e-12 });
261
+ statistic = z.slice(0, df).reduce((s, x, i) => s + x * b[i], 0);
262
+ pValue = pchisq(statistic, df, { lowerTail: false });
263
+ }
264
+ catch {
265
+ statistic = NaN;
266
+ pValue = NaN;
267
+ }
268
+ }
269
+ out.push({ cause: levelText(cause), stat: statistic, df, pValue });
270
+ }
271
+ return out;
272
+ }
273
+ /**
274
+ * Evaluate cumulative-incidence curves at requested times. Equivalent to `cmprsk::timepoints()` in R.
275
+ * At a requested time the last corner at or before it is used; values before zero or after a
276
+ * group's final follow-up are NaN.
277
+ *
278
+ * @param fit Result of {@link cuminc}.
279
+ * @param times Evaluation times.
280
+ * @returns Matrices with one row per curve and one column per sorted unique requested time.
281
+ *
282
+ * @example
283
+ * ```ts
284
+ * const fit = cuminc([1, 2, 3], [1, 0, 1]);
285
+ * timepoints(fit, [1, 2]).est;
286
+ * ```
287
+ *
288
+ * @category Survival analysis
289
+ */
290
+ export function timepoints(fit, times) {
291
+ const ts = Array.from(new Set(times.filter((t) => !Number.isNaN(t)))).sort((a, b) => a - b);
292
+ const est = [], variance = [];
293
+ for (const curve of fit.curves) {
294
+ const erow = [], vrow = [];
295
+ for (const t of ts) {
296
+ let index = -1;
297
+ for (let j = 0; j < curve.time.length; j++)
298
+ if (curve.time[j] <= t)
299
+ index = j;
300
+ if (t < 0 || index < 0 || t > curve.time[curve.time.length - 1]) {
301
+ erow.push(NaN);
302
+ vrow.push(NaN);
303
+ }
304
+ else {
305
+ erow.push(curve.est[index]);
306
+ vrow.push(curve.var[index]);
307
+ }
308
+ }
309
+ est.push(erow);
310
+ variance.push(vrow);
311
+ }
312
+ return { curveNames: fit.curves.map((c) => c.name), times: ts, est, var: variance };
313
+ }
314
+ function zeros(n, m = n) {
315
+ return Array.from({ length: n }, () => new Array(m).fill(0));
316
+ }
317
+ function addOuter(target, x, y, scale) {
318
+ for (let i = 0; i < x.length; i++)
319
+ for (let j = 0; j < y.length; j++)
320
+ target[i][j] += scale * x[i] * y[j];
321
+ }
322
+ function dot(a, b) {
323
+ return sum(a.map((v, i) => v * b[i]));
324
+ }
325
+ function finiteMatrix(x) {
326
+ return x.every((r) => r.every(Number.isFinite));
327
+ }
328
+ /**
329
+ * Fine-Gray proportional subdistribution hazards regression. Equivalent to `cmprsk::crr()` in R.
330
+ * The censoring distribution is estimated by the verified {@link survfit}; Newton-Raphson
331
+ * solves the weighted estimating equations and the variance is the subject-level sandwich.
332
+ *
333
+ * @param time Follow-up times (finite; negative values are allowed).
334
+ * @param status Event codes.
335
+ * @param cov1 Baseline covariate matrix (rows are observations); pass undefined when using only cov2.
336
+ * @param options See {@link CrrOptions}.
337
+ * @returns Coefficients, information, sandwich variance, baseline subdistribution hazard and diagnostics.
338
+ *
339
+ * @example
340
+ * ```ts
341
+ * const fit = crr([1, 2, 3, 4, 5, 6], [1, 0, 1, 2, 0, 1], [[0], [1], [2], [1], [0], [2]]);
342
+ * fit.coefficients;
343
+ * ```
344
+ *
345
+ * @category Survival analysis
346
+ */
347
+ export function crr(time, status, cov1, options = {}) {
348
+ checkOptions(options, CRR_KEYS, "crr"); // generated: option-keys.mjs
349
+ const { cov2, tf, failcode = 1, cencode = 0, gtol = 1e-6, maxiter = 10, init, variance = true, confLevel = 0.95, names } = options;
350
+ if (time.length !== status.length)
351
+ throw new RangeError("'time' and 'status' must have the same length");
352
+ if (cov1 !== undefined && cov1.length !== time.length)
353
+ throw new RangeError("'cov1' must have one row per observation");
354
+ if (cov2 !== undefined && cov2.length !== time.length)
355
+ throw new RangeError("'cov2' must have one row per observation");
356
+ if (cov2 !== undefined && tf === undefined)
357
+ throw new TypeError("'tf' is required when 'cov2' is supplied");
358
+ if (!(gtol > 0) || !Number.isFinite(gtol))
359
+ throw new RangeError("'gtol' must be finite and positive");
360
+ if (!Number.isInteger(maxiter) || maxiter < 0)
361
+ throw new RangeError("'maxiter' must be a non-negative integer");
362
+ if (!(confLevel > 0 && confLevel < 1))
363
+ throw new RangeError("'confLevel' must be between 0 and 1");
364
+ const p1 = cov1?.[0]?.length ?? 0, p2 = cov2?.[0]?.length ?? 0, p = p1 + p2;
365
+ if (p === 0)
366
+ throw new RangeError("at least one covariate is required");
367
+ if (cov1 !== undefined && cov1.some((r) => r.length !== p1))
368
+ throw new RangeError("rows of 'cov1' must have equal length");
369
+ if (cov2 !== undefined && cov2.some((r) => r.length !== p2))
370
+ throw new RangeError("rows of 'cov2' must have equal length");
371
+ if (init !== undefined && init.length !== p)
372
+ throw new RangeError("'init' must have one value per coefficient");
373
+ if (names !== undefined && names.length !== p)
374
+ throw new RangeError("'names' must have one name per coefficient");
375
+ const keep = [];
376
+ for (let i = 0; i < time.length; i++) {
377
+ const missing = Number.isNaN(time[i]) || missingLabel(status[i]) ||
378
+ (cov1 !== undefined && cov1[i].some(Number.isNaN)) || (cov2 !== undefined && cov2[i].some(Number.isNaN));
379
+ if (missing)
380
+ continue;
381
+ if (!Number.isFinite(time[i]))
382
+ throw new RangeError("'time' must contain only finite values");
383
+ if ((cov1 !== undefined && !cov1[i].every(Number.isFinite)) || (cov2 !== undefined && !cov2[i].every(Number.isFinite))) {
384
+ throw new RangeError("covariates must be finite");
385
+ }
386
+ keep.push(i);
387
+ }
388
+ const nMissing = time.length - keep.length;
389
+ if (keep.length === 0)
390
+ throw new RangeError("no complete observations");
391
+ const t = keep.map((i) => time[i]);
392
+ const statusValues = factorLabels([...keep.map((i) => status[i]), cencode, failcode]);
393
+ const s = statusValues.slice(0, keep.length);
394
+ const cencodeValue = statusValues[statusValues.length - 2];
395
+ const failcodeValue = statusValues[statusValues.length - 1];
396
+ const x1 = keep.map((i) => cov1 === undefined ? [] : Array.from(cov1[i]));
397
+ const x2 = keep.map((i) => cov2 === undefined ? [] : Array.from(cov2[i]));
398
+ const uftime = Array.from(new Set(t.filter((_, i) => s[i] === failcodeValue))).sort((a, b) => a - b);
399
+ if (uftime.length === 0)
400
+ throw new RangeError("no observations of 'failcode'");
401
+ const tfs = p2 === 0 ? [[0]] : tf(uftime).map((r) => Array.from(r));
402
+ if (p2 > 0 && (tfs.length !== uftime.length || tfs.some((r) => r.length !== p2) || !finiteMatrix(tfs))) {
403
+ throw new RangeError("'tf' must return a finite matrix with one row per unique failure time and one column per cov2 column");
404
+ }
405
+ const zByTime = uftime.map((_, j) => t.map((__, i) => [...x1[i], ...x2[i].map((v, k) => v * (tfs[j][k] ?? 0))]));
406
+ // Preserve distinct very small time values despite survfit's absolute timefix tolerance.
407
+ const maxAbsTime = t.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
408
+ const timeScale = maxAbsTime > 0 && maxAbsTime < 1
409
+ ? 2 ** Math.min(1023, Math.ceil(-Math.log2(maxAbsTime))) : 1;
410
+ const censorFit = survfit(t.map((v) => v * timeScale), s.map((v) => (v === cencodeValue ? 1 : 0)));
411
+ const censorBefore = (u) => {
412
+ const scaledU = u * timeScale;
413
+ let g = 1;
414
+ for (let j = 0; j < censorFit.time.length; j++) {
415
+ if (censorFit.time[j] >= scaledU)
416
+ break;
417
+ g = censorFit.surv[j];
418
+ }
419
+ return g;
420
+ };
421
+ const weights = uftime.map((u) => t.map((tj, i) => {
422
+ if (tj >= u)
423
+ return 1;
424
+ if (s[i] === cencodeValue || s[i] === failcodeValue)
425
+ return 0;
426
+ const den = censorBefore(tj);
427
+ return den === 0 ? 0 : censorBefore(u) / den;
428
+ }));
429
+ // Every failure at u belongs to its own Fine-Gray risk set, including the terminal
430
+ // failure time when the censoring KM has already reached zero.
431
+ for (let j = 0; j < uftime.length; j++) {
432
+ for (let i = 0; i < t.length; i++) {
433
+ if (t[i] === uftime[j] && s[i] === failcodeValue)
434
+ weights[j][i] = 1;
435
+ }
436
+ }
437
+ const evaluate = (beta) => {
438
+ const scoreTerms = Array.from({ length: p }, () => []);
439
+ const infTerms = Array.from({ length: p }, () => Array.from({ length: p }, () => []));
440
+ const loglikTerms = [];
441
+ const res = zeros(uftime.length, p), bfitj = [], means = [], riskFactors = [];
442
+ for (let j = 0; j < uftime.length; j++) {
443
+ const u = uftime[j];
444
+ const dIndices = t.map((v, i) => v === u && s[i] === failcodeValue ? i : -1).filter((i) => i >= 0);
445
+ const d = dIndices.length;
446
+ const zz = zByTime[j];
447
+ const lp = zz.map((row) => dot(beta, row));
448
+ // Reassert the model definition locally: every failure at u is in its own risk set,
449
+ // independently of the censoring KM (which may be zero after the last censoring time).
450
+ const riskWeights = weights[j].slice();
451
+ for (const i of dIndices)
452
+ riskWeights[i] = 1;
453
+ const maxLp = Math.max(...lp.map((v, i) => riskWeights[i] > 0 ? v : -Infinity));
454
+ if (maxLp === -Infinity)
455
+ throw new Error("empty Fine-Gray risk set");
456
+ // Match the direct exp/sum/log operation order of the estimating equations when safe.
457
+ // Fall back to a common exponential scale only near overflow/underflow.
458
+ const direct = maxLp < 500 && maxLp > -500;
459
+ const rf = direct
460
+ ? lp.map((v, i) => riskWeights[i] * Math.exp(v))
461
+ : lp.map((v, i) => riskWeights[i] * Math.exp(v - maxLp));
462
+ const s0 = sum(rf);
463
+ const s1 = Array.from({ length: p }, (_, a) => sum(rf.map((w, i) => w * zz[i][a])));
464
+ if (!(s0 > 0))
465
+ throw new Error("empty Fine-Gray risk set");
466
+ const meanZ = s1.map((v) => v / s0);
467
+ const needsCentering = Array.from({ length: p }, (_, a) => {
468
+ const anchor = zz[0][a];
469
+ let spread = 0, magnitude = 0;
470
+ for (const row of zz) {
471
+ spread = Math.max(spread, Math.abs(row[a] - anchor));
472
+ magnitude = Math.max(magnitude, Math.abs(row[a]));
473
+ }
474
+ return spread > 0 && magnitude / spread > 1e6;
475
+ });
476
+ const useCentered = needsCentering.some(Boolean);
477
+ // Allocate centered columns only for the exceptional large-offset path; ordinary inputs
478
+ // retain the original second-moment calculation and its operation order.
479
+ const centered = useCentered
480
+ ? Array.from({ length: p }, (_, a) => zz.map(row => row[a] - zz[0][a]))
481
+ : [];
482
+ const centeredMean = useCentered
483
+ ? centered.map(column => sum(column.map((v, i) => rf[i] * v)) / s0)
484
+ : [];
485
+ const s2 = useCentered ? undefined : Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => sum(rf.map((w, i) => w * zz[i][a] * zz[i][b]))));
486
+ means.push(meanZ);
487
+ riskFactors.push(rf.map((v) => v / s0));
488
+ const b = direct ? d / s0 : (d * Math.exp(-maxLp)) / s0;
489
+ bfitj.push(b);
490
+ loglikTerms.push(sum(dIndices.map((i) => dot(beta, zz[i]))) - d * (direct ? Math.log(s0) : maxLp + Math.log(s0)));
491
+ for (let a = 0; a < p; a++) {
492
+ // Sum the failures first, then subtract d times the risk-set mean. This avoids
493
+ // repeatedly rounding the same mean subtraction for tied failures.
494
+ const failureSum = sum(dIndices.map((i) => zz[i][a]));
495
+ const increment = failureSum - d * meanZ[a];
496
+ scoreTerms[a].push(increment);
497
+ res[j][a] = increment;
498
+ }
499
+ for (let a = 0; a < p; a++)
500
+ for (let b0 = 0; b0 < p; b0++) {
501
+ const covariance = useCentered
502
+ ? sum(rf.map((w, i) => w * (centered[a][i] - centeredMean[a]) *
503
+ (centered[b0][i] - centeredMean[b0]))) / s0
504
+ : s2[a][b0] / s0 - meanZ[a] * meanZ[b0];
505
+ infTerms[a][b0].push(d * covariance);
506
+ }
507
+ }
508
+ const eta = zeros(t.length, p);
509
+ for (let j = 0; j < uftime.length; j++) {
510
+ const zz = zByTime[j], rf = riskFactors[j], meanZ = means[j];
511
+ const u = uftime[j];
512
+ for (let i = 0; i < t.length; i++) {
513
+ const isFail = t[i] === u && s[i] === failcodeValue ? 1 : 0;
514
+ const d = t.filter((v, k) => v === u && s[k] === failcodeValue).length;
515
+ const mult = isFail - rf[i] * d;
516
+ for (let a = 0; a < p; a++)
517
+ eta[i][a] += (zz[i][a] - meanZ[a]) * mult;
518
+ }
519
+ }
520
+ const score = scoreTerms.map(sum);
521
+ const inf = infTerms.map((row) => row.map(sum));
522
+ const loglik = sum(loglikTerms);
523
+ return { loglik, score, inf, bfitj, res, eta, means, riskFactors, zByTime };
524
+ };
525
+ const initial = init === undefined ? new Array(p).fill(0) : Array.from(init);
526
+ if (!initial.every(Number.isFinite))
527
+ throw new RangeError("'init' must contain finite values");
528
+ let beta = initial.slice(), state = evaluate(beta), converged = false, iterations = 0;
529
+ const criterion = (st, b) => Math.max(...st.score.map((u, j) => Math.abs(u) * Math.max(Math.abs(b[j]), 1))) <
530
+ gtol * Math.max(Math.abs(st.loglik), 1);
531
+ for (;;) {
532
+ if (criterion(state, beta)) {
533
+ converged = true;
534
+ break;
535
+ }
536
+ if (iterations >= maxiter)
537
+ break;
538
+ const step = solve(state.inf, state.score, { tol: 0 });
539
+ beta = beta.map((v, j) => v + step[j]);
540
+ iterations++;
541
+ state = evaluate(beta);
542
+ }
543
+ // The R algorithm tests once more at the final beta after maxiter steps; the loop above does so naturally.
544
+ const invinf = solve(state.inf);
545
+ let varianceMatrix = zeros(p);
546
+ if (variance) {
547
+ const meat = zeros(p);
548
+ const n = t.length;
549
+ const times = Array.from(new Set(t)).sort((a, b) => a - b);
550
+ const dLambda = times.map((v) => {
551
+ const risk = t.filter((x) => x >= v).length;
552
+ const d = t.filter((x, i) => x === v && s[i] === cencodeValue).length;
553
+ return risk === 0 ? 0 : d / risk;
554
+ });
555
+ const psi = zeros(n, p);
556
+ for (let vi = 0; vi < times.length; vi++) {
557
+ const v = times[vi];
558
+ let q = new Array(p).fill(0);
559
+ for (let i = 0; i < n; i++) {
560
+ if (!(t[i] < v) || s[i] === cencodeValue || s[i] === failcodeValue)
561
+ continue;
562
+ for (let j = 0; j < uftime.length; j++) {
563
+ if (uftime[j] < v)
564
+ continue;
565
+ const rf = state.riskFactors[j][i];
566
+ const d = t.filter((v, k) => v === uftime[j] && s[k] === failcodeValue).length;
567
+ const zz = state.zByTime[j][i];
568
+ const meanZ = state.means[j];
569
+ for (let a = 0; a < p; a++)
570
+ q[a] += (zz[a] - meanZ[a]) * rf * d;
571
+ }
572
+ }
573
+ const risk = t.filter((x) => x >= v).length;
574
+ if (risk === 0)
575
+ continue;
576
+ for (let i = 0; i < n; i++) {
577
+ const indicator = t[i] === v && s[i] === cencodeValue ? 1 : 0;
578
+ const compensator = t[i] >= v ? dLambda[vi] : 0;
579
+ for (let a = 0; a < p; a++)
580
+ psi[i][a] += (q[a] / risk) * (indicator - compensator);
581
+ }
582
+ }
583
+ for (let i = 0; i < n; i++)
584
+ addOuter(meat, state.eta[i].map((v, a) => v + psi[i][a]), state.eta[i].map((v, a) => v + psi[i][a]), 1);
585
+ varianceMatrix = zeros(p);
586
+ const left = multiply(invinf, meat);
587
+ varianceMatrix = multiply(left, invinf);
588
+ }
589
+ else {
590
+ varianceMatrix = zeros(p).map((r) => r.map(() => NaN));
591
+ }
592
+ const se = variance ? varianceMatrix.map((r, i) => Math.sqrt(r[i])) : undefined;
593
+ const z = se === undefined ? undefined : beta.map((v, i) => v / se[i]);
594
+ const pValue = z === undefined ? undefined : z.map((v) => 2 * pnorm(-Math.abs(v)));
595
+ const q = variance ? qnorm((1 + confLevel) / 2) : undefined;
596
+ const lower = q === undefined ? undefined : beta.map((v, i) => Math.exp(v - q * se[i]));
597
+ const upper = q === undefined ? undefined : beta.map((v, i) => Math.exp(v + q * se[i]));
598
+ const expCoef = variance ? beta.map(Math.exp) : undefined;
599
+ const coefNames = names === undefined
600
+ ? [...Array.from({ length: p1 }, (_, i) => `cov1${i + 1}`),
601
+ ...Array.from({ length: p2 }, (_, i) => `cov2${i + 1}*tf${i + 1}`)]
602
+ : Array.from(names);
603
+ return reported("crr", {
604
+ coefficients: beta, names: coefNames, var: varianceMatrix,
605
+ ...(se === undefined ? {} : { se, z: z, pValue: pValue, lower: lower, upper: upper, expCoef: expCoef }),
606
+ loglik: state.loglik, loglikNull: evaluate(new Array(p).fill(0)).loglik,
607
+ logtest: { statistic: 2 * (state.loglik - evaluate(new Array(p).fill(0)).loglik), df: p },
608
+ score: state.score, inf: variance ? state.inf : zeros(p).map((r) => r.map(() => NaN)),
609
+ invinf: variance ? invinf : zeros(p).map((r) => r.map(() => NaN)),
610
+ converged, iterations, n: keep.length, nMissing, uftime, bfitj: state.bfitj, res: variance ? state.res : null,
611
+ tfs, warnings: [], covariateDimensions: [p1, p2],
612
+ });
613
+ }
614
+ /** Matrix product for the small information matrices of Fine-Gray regression. */
615
+ function multiply(a, b) {
616
+ const out = zeros(a.length, b[0]?.length ?? 0);
617
+ for (let i = 0; i < a.length; i++)
618
+ for (let j = 0; j < (b[0]?.length ?? 0); j++) {
619
+ for (let k = 0; k < b.length; k++)
620
+ out[i][j] += a[i][k] * b[k][j];
621
+ }
622
+ return out;
623
+ }
624
+ /**
625
+ * Predict cumulative incidence from a Fine-Gray fit. Equivalent to `cmprsk::predict.crr()` in R.
626
+ *
627
+ * @param fit Result of {@link crr}.
628
+ * @param cov1 New baseline covariate matrix.
629
+ * @param cov2 New time-varying covariate matrix, when the fit used cov2.
630
+ * @returns A matrix whose first column is failure time and remaining columns are predicted incidences.
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * const fit = crr([1, 2, 3, 4, 5, 6], [1, 0, 1, 2, 0, 1], [[0], [1], [2], [1], [0], [2]]);
635
+ * predictCrr(fit, [[0], [1]]);
636
+ * ```
637
+ *
638
+ * @category Survival analysis
639
+ */
640
+ export function predictCrr(fit, cov1, cov2) {
641
+ const [p1, p2] = fit.covariateDimensions;
642
+ if (p1 > 0 && cov1 === undefined)
643
+ throw new TypeError("'cov1' is required by this fit");
644
+ if (p2 > 0 && cov2 === undefined)
645
+ throw new TypeError("'cov2' is required by this fit");
646
+ if (p1 > 0 && cov1.some((r) => r.length !== p1))
647
+ throw new RangeError("'cov1' has the wrong number of columns");
648
+ if (p2 > 0 && cov2.some((r) => r.length !== p2))
649
+ throw new RangeError("'cov2' has the wrong number of columns");
650
+ if (p1 > 0 && p2 > 0 && cov1.length !== cov2.length)
651
+ throw new RangeError("'cov1' and 'cov2' must have the same number of rows");
652
+ const n = p1 > 0 ? cov1.length : cov2.length;
653
+ const tfs = p2 === 0 ? fit.uftime.map(() => [0]) : fit.tfs;
654
+ const out = fit.uftime.map((u, j) => {
655
+ const row = [u];
656
+ for (let i = 0; i < n; i++) {
657
+ let cumulative = 0;
658
+ for (let k = 0; k <= j; k++) {
659
+ const z = [...(p1 === 0 ? [] : cov1[i]), ...(p2 === 0 ? [] : cov2[i].map((v, h) => v * tfs[k][h]))];
660
+ const baseline = fit.bfitj[k];
661
+ const eta = dot(fit.coefficients, z);
662
+ const direct = baseline * Math.exp(eta);
663
+ const increment = Number.isFinite(direct) && (direct !== 0 || baseline === 0)
664
+ ? direct
665
+ : baseline === 0 ? 0 : Math.exp(Math.log(baseline) + eta);
666
+ cumulative += increment;
667
+ }
668
+ row.push(-Math.expm1(-cumulative));
669
+ }
670
+ return row;
671
+ });
672
+ return out;
673
+ }