@numero-uno-jpn/rstats 1.3.0 → 1.5.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 +85 -0
- package/README.ja.md +9 -7
- package/README.md +9 -7
- package/dist/chunks/chunk-2IYY74LX.js +2 -0
- package/dist/chunks/{chunk-LA4H6ZSC.js → chunk-2MYUAEYE.js} +2 -2
- package/dist/chunks/{chunk-GUM57VVM.js → chunk-3BEE6BHN.js} +1 -1
- package/dist/chunks/{chunk-2VZW4XPK.js → chunk-73QCE2CI.js} +2 -2
- package/dist/chunks/{chunk-AJZV2SVY.js → chunk-AIXJAVDS.js} +2 -2
- package/dist/chunks/{chunk-6X2ZMPF5.js → chunk-BJOZZ5J6.js} +2 -2
- package/dist/chunks/{chunk-P7ZHH2SF.js → chunk-CX4XK7WC.js} +2 -2
- package/dist/chunks/{chunk-PDHBRDTF.js → chunk-DYCWYHYV.js} +1 -1
- package/dist/chunks/{chunk-6TZVS6WC.js → chunk-E5M5RAVB.js} +2 -2
- package/dist/chunks/{chunk-IJV43Y7Q.js → chunk-F2MURX2Y.js} +2 -2
- package/dist/chunks/{chunk-HBRSUHSU.js → chunk-F7SQG6BV.js} +2 -2
- package/dist/chunks/{chunk-UOAFEB64.js → chunk-FCF6FBJP.js} +2 -2
- package/dist/chunks/{chunk-TZTVDVP4.js → chunk-FMLFYM7N.js} +2 -2
- package/dist/chunks/{chunk-EBRTF7RM.js → chunk-GDMNF4P3.js} +1 -1
- package/dist/chunks/{chunk-RCGW2DCK.js → chunk-JBJTXMRJ.js} +2 -2
- package/dist/chunks/{chunk-Z74ZOTUN.js → chunk-L7PDJNJ3.js} +2 -2
- package/dist/chunks/{chunk-I5NWGQOQ.js → chunk-LVB22NKV.js} +2 -2
- package/dist/chunks/{chunk-UJYRU37Z.js → chunk-MJV5G7FG.js} +2 -2
- package/dist/chunks/{chunk-JJRZ2TTF.js → chunk-MXOGMN4P.js} +2 -2
- package/dist/chunks/{chunk-UMDXXT3M.js → chunk-MYRCEQ2R.js} +1 -1
- package/dist/chunks/{chunk-IOGQEMDE.js → chunk-Q32WODL4.js} +2 -2
- package/dist/chunks/{chunk-BNTBZ5W3.js → chunk-RZBX6VYO.js} +2 -2
- package/dist/chunks/chunk-TP4PRPVQ.js +2 -0
- package/dist/chunks/{chunk-FFNHG5SB.js → chunk-UJM7AJII.js} +1 -1
- package/dist/chunks/chunk-VAWD57ZB.js +2 -0
- package/dist/chunks/{chunk-LNUNKFIH.js → chunk-WBEYJ5W5.js} +2 -2
- package/dist/chunks/{chunk-LMNU4NHZ.js → chunk-YK2EJU6T.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +6 -0
- package/dist/entries/tests.js +6 -0
- package/dist/htest/sampleSize.d.ts +290 -0
- package/dist/htest/sampleSize.js +625 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/competingRisks.d.ts +188 -0
- package/dist/models/competingRisks.js +685 -0
- package/dist/models/coxZph.d.ts +67 -0
- package/dist/models/coxZph.js +479 -0
- package/dist/models/coxph.d.ts +61 -21
- package/dist/models/coxph.js +305 -65
- package/dist/models/metaAnalysis.d.ts +207 -0
- package/dist/models/metaAnalysis.js +696 -0
- package/dist/models/rmst2.d.ts +126 -0
- package/dist/models/rmst2.js +365 -0
- package/dist/models/survival.d.ts +65 -24
- package/dist/models/survival.js +407 -72
- package/dist/models/survreg.d.ts +160 -0
- package/dist/models/survreg.js +809 -0
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +19 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +16 -13
- package/llms.txt +13 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-4OOTEXZU.js +0 -2
- package/dist/chunks/chunk-MJXETGT2.js +0 -2
package/dist/models/coxph.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// Cox proportional hazards regression for right-censored data with a matrix interface: R's
|
|
2
|
-
// package (the fit, with Efron's or Breslow's handling of ties, case weights and strata) and the
|
|
3
|
-
// summary(fit): the coefficient table, the confidence intervals of exp(coef), the likelihood ratio, score and Wald
|
|
1
|
+
// Cox proportional hazards regression for right-censored and counting-process data with a matrix interface: R's
|
|
2
|
+
// coxph from the survival package (the fit, with Efron's or Breslow's handling of ties, case weights and strata) and the
|
|
3
|
+
// values of summary(fit): the coefficient table, the confidence intervals of exp(coef), the likelihood ratio, score and Wald
|
|
4
4
|
// tests and the R^2 of Nagelkerke's kind.
|
|
5
5
|
//
|
|
6
6
|
// Written for rStats.js (no ported code) from oracle/coxph-behaviour.md (a description of the behaviour of survival
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
// "The efficiency of Cox's likelihood function for censored data", JASA 72, 557-565; Breslow (1974), "Covariance
|
|
9
9
|
// analysis of censored survival data", Biometrics 30, 89-99. Newton-Raphson runs on centred and scaled covariates and
|
|
10
10
|
// uses a generalised Cholesky factorisation (LDL' with a tolerance on the pivots) so that aliased columns get NaN
|
|
11
|
-
// (R's NA) coefficients.
|
|
11
|
+
// (R's NA) coefficients. Counting-process risk sets follow Andersen and Gill (1982), "Cox's regression model for
|
|
12
|
+
// counting processes: a large sample study", Annals of Statistics 10, 1100-1120.
|
|
12
13
|
//
|
|
13
14
|
// The robust variance (survival's `robust = TRUE` or `cluster`) is the Lin-Wei sandwich, written from section 5 of
|
|
14
15
|
// oracle/robust-behaviour.md and Lin and Wei (1989), "The robust inference for the Cox proportional hazards model",
|
|
@@ -25,9 +26,9 @@ import { maxOf } from "../internal/extremes.js";
|
|
|
25
26
|
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
26
27
|
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
27
28
|
const COXPH_KEYS = /* @__PURE__ */ new Set([
|
|
28
|
-
"ties", "weights", "strata", "init", "control", "nocenter", "confLevel", "robust", "cluster",
|
|
29
|
+
"start", "id", "ties", "weights", "strata", "init", "control", "nocenter", "confLevel", "robust", "cluster",
|
|
29
30
|
]);
|
|
30
|
-
const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf"];
|
|
31
|
+
const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf", "timefix"];
|
|
31
32
|
const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
32
33
|
const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
|
|
33
34
|
/** The weights from which the fit runs on weights divided by a power of 2 (see SortedData.logUnit) */
|
|
@@ -36,7 +37,7 @@ const MIN_NORMAL = 2 ** -1022;
|
|
|
36
37
|
/** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
|
|
37
38
|
const SHIFT_LIMIT = 700;
|
|
38
39
|
function evaluate(data, beta, efron) {
|
|
39
|
-
const { time, event, weight, x, stratumEnd, logUnit } = data;
|
|
40
|
+
const { time, event, weight, x, stratumEnd, logUnit, start: startTime } = data;
|
|
40
41
|
const n = time.length;
|
|
41
42
|
const p = beta.length;
|
|
42
43
|
const zeros = () => new Array(p).fill(0);
|
|
@@ -79,6 +80,51 @@ function evaluate(data, beta, efron) {
|
|
|
79
80
|
riskXX = zeroMatrix();
|
|
80
81
|
}
|
|
81
82
|
const t = time[k];
|
|
83
|
+
let hasDeathAtTime = false;
|
|
84
|
+
if (startTime !== undefined) {
|
|
85
|
+
let first = k;
|
|
86
|
+
while (first > 0 && time[first - 1] === t && !stratumEnd[first - 1])
|
|
87
|
+
first--;
|
|
88
|
+
for (let r = first; r <= k; r++)
|
|
89
|
+
if (event[r])
|
|
90
|
+
hasDeathAtTime = true;
|
|
91
|
+
}
|
|
92
|
+
if (startTime !== undefined && hasDeathAtTime) {
|
|
93
|
+
// Rebuild the risk-set moments for start < t <= stop. The shift covers the
|
|
94
|
+
// complete risk set (deaths included), so Efron's death moments share its scale.
|
|
95
|
+
let lo = k;
|
|
96
|
+
while (lo > 0 && !stratumEnd[lo - 1])
|
|
97
|
+
lo--;
|
|
98
|
+
let hi = k;
|
|
99
|
+
while (!stratumEnd[hi])
|
|
100
|
+
hi++;
|
|
101
|
+
const etaAt = (r) => {
|
|
102
|
+
let value = 0;
|
|
103
|
+
for (let i = 0; i < p; i++)
|
|
104
|
+
value += beta[i] * x[r][i];
|
|
105
|
+
return value;
|
|
106
|
+
};
|
|
107
|
+
let top = -Infinity;
|
|
108
|
+
for (let r = lo; r <= hi; r++) {
|
|
109
|
+
if (startTime[r] < t && time[r] >= t)
|
|
110
|
+
top = Math.max(top, etaAt(r));
|
|
111
|
+
}
|
|
112
|
+
shift = Number.isFinite(top) ? top : 0;
|
|
113
|
+
riskSum = 0;
|
|
114
|
+
riskX = zeros();
|
|
115
|
+
riskXX = zeroMatrix();
|
|
116
|
+
for (let r = lo; r <= hi; r++) {
|
|
117
|
+
if (!(startTime[r] < t && time[r] >= t) || (time[r] === t && event[r]))
|
|
118
|
+
continue;
|
|
119
|
+
const rr = Math.exp(etaAt(r) - shift) * weight[r];
|
|
120
|
+
riskSum += rr;
|
|
121
|
+
for (let i = 0; i < p; i++) {
|
|
122
|
+
riskX[i] += rr * x[r][i];
|
|
123
|
+
for (let l = 0; l <= i; l++)
|
|
124
|
+
riskXX[i][l] += rr * x[r][i] * x[r][l];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
82
128
|
let deaths = 0;
|
|
83
129
|
let deathWeight = 0;
|
|
84
130
|
deathRisk = 0;
|
|
@@ -97,12 +143,14 @@ function evaluate(data, beta, efron) {
|
|
|
97
143
|
}
|
|
98
144
|
const r = Math.exp(eta - shift) * w;
|
|
99
145
|
if (!event[j]) {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
146
|
+
if (startTime === undefined) {
|
|
147
|
+
riskSum += r;
|
|
148
|
+
for (let i = 0; i < p; i++) {
|
|
149
|
+
riskX[i] += r * xj[i];
|
|
150
|
+
const row = riskXX[i];
|
|
151
|
+
for (let l = 0; l <= i; l++)
|
|
152
|
+
row[l] += r * xj[i] * xj[l];
|
|
153
|
+
}
|
|
106
154
|
}
|
|
107
155
|
}
|
|
108
156
|
else {
|
|
@@ -303,6 +351,92 @@ function scoreResiduals(data, beta, efron) {
|
|
|
303
351
|
}
|
|
304
352
|
return out;
|
|
305
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* Counting-process score residuals evaluated directly on the (start, stop] risk sets.
|
|
356
|
+
* This delayed-entry calculation is kept separate from the verified right-censored sweep.
|
|
357
|
+
*/
|
|
358
|
+
function scoreResidualsCounting(data, beta, efron) {
|
|
359
|
+
const startTime = data.start;
|
|
360
|
+
const { time, event, x, stratumEnd } = data;
|
|
361
|
+
const weight = scaleToUnit([data.weight]).groups[0];
|
|
362
|
+
const n = time.length;
|
|
363
|
+
const p = beta.length;
|
|
364
|
+
const out = Array.from({ length: n }, () => new Array(p).fill(0));
|
|
365
|
+
const eta = time.map((_, j) => {
|
|
366
|
+
let v = 0;
|
|
367
|
+
for (let i = 0; i < p; i++)
|
|
368
|
+
v += beta[i] * x[j][i];
|
|
369
|
+
return v;
|
|
370
|
+
});
|
|
371
|
+
for (let lo = 0; lo < n;) {
|
|
372
|
+
let hi = lo;
|
|
373
|
+
while (!stratumEnd[hi])
|
|
374
|
+
hi++;
|
|
375
|
+
for (let k = lo; k <= hi;) {
|
|
376
|
+
const t = time[k];
|
|
377
|
+
let end = k;
|
|
378
|
+
while (end < hi && time[end + 1] === t)
|
|
379
|
+
end++;
|
|
380
|
+
const risk = [];
|
|
381
|
+
const deaths = [];
|
|
382
|
+
let shift = -Infinity;
|
|
383
|
+
for (let j = k; j <= end; j++)
|
|
384
|
+
if (event[j])
|
|
385
|
+
deaths.push(j);
|
|
386
|
+
if (deaths.length > 0) {
|
|
387
|
+
for (let j = lo; j <= hi; j++) {
|
|
388
|
+
if (startTime[j] < t && time[j] >= t) {
|
|
389
|
+
risk.push(j);
|
|
390
|
+
shift = Math.max(shift, eta[j]);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (deaths.length > 0 && risk.length > 0) {
|
|
395
|
+
if (!Number.isFinite(shift))
|
|
396
|
+
shift = 0;
|
|
397
|
+
let s0 = 0;
|
|
398
|
+
const s1 = new Array(p).fill(0);
|
|
399
|
+
let e0 = 0;
|
|
400
|
+
const e1 = new Array(p).fill(0);
|
|
401
|
+
let dw = 0;
|
|
402
|
+
for (const j of risk) {
|
|
403
|
+
const r = Math.exp(eta[j] - shift);
|
|
404
|
+
const wr = weight[j] * r;
|
|
405
|
+
s0 += wr;
|
|
406
|
+
for (let i = 0; i < p; i++)
|
|
407
|
+
s1[i] += wr * x[j][i];
|
|
408
|
+
if (event[j] && time[j] === t) {
|
|
409
|
+
dw += weight[j];
|
|
410
|
+
e0 += wr;
|
|
411
|
+
for (let i = 0; i < p; i++)
|
|
412
|
+
e1[i] += wr * x[j][i];
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const steps = efron ? deaths.length : 1;
|
|
416
|
+
for (let m = 0; m < steps; m++) {
|
|
417
|
+
const f = m / steps;
|
|
418
|
+
const denom = s0 - f * e0;
|
|
419
|
+
const lambda = dw / steps / denom;
|
|
420
|
+
const xbar = s1.map((v, i) => (v - f * e1[i]) / denom);
|
|
421
|
+
for (const j of risk) {
|
|
422
|
+
const r = Math.exp(eta[j] - shift);
|
|
423
|
+
const death = event[j] && time[j] === t;
|
|
424
|
+
for (let i = 0; i < p; i++) {
|
|
425
|
+
const dx = x[j][i] - xbar[i];
|
|
426
|
+
if (death)
|
|
427
|
+
out[j][i] += dx / steps - (1 - f) * r * dx * lambda;
|
|
428
|
+
else
|
|
429
|
+
out[j][i] -= r * dx * lambda;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
k = end + 1;
|
|
435
|
+
}
|
|
436
|
+
lo = hi + 1;
|
|
437
|
+
}
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
306
440
|
/**
|
|
307
441
|
* Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
|
|
308
442
|
* set to 0. Returns the rank (negative when M is not non-negative definite).
|
|
@@ -444,27 +578,27 @@ function zeroEventResult(rows, p, warnings) {
|
|
|
444
578
|
}
|
|
445
579
|
/**
|
|
446
580
|
* Cox proportional hazards regression. Equivalent to R's `survival::coxph()`. As
|
|
447
|
-
* `coxph(Surv(time, status) ~ x
|
|
448
|
-
* data, with the values of `summary(fit)`.
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
581
|
+
* `coxph(Surv(time, status) ~ x ...)` for right-censored data and `coxph(Surv(start, stop, status) ~ x ...)` for
|
|
582
|
+
* counting-process data (with the option `start`), with the values of `summary(fit)`.
|
|
583
|
+
* With `robust` (by default when `cluster` is given, a counting-process `id` has repeated event rows, or a case
|
|
584
|
+
* weight is not an integer) the variance is the robust (Lin-Wei sandwich) one, summed over the clusters (each
|
|
585
|
+
* observation its own cluster without `cluster` or `id`), as R:
|
|
452
586
|
* `var` is the robust variance and `naiveVar` the model-based one; `se` (and `stdError`) stay the model-based standard
|
|
453
587
|
* errors (R's `se(coef)`), while `z`, `p`, the intervals `lower`/`upper`, `wald` and `waldtest` use the robust ones
|
|
454
588
|
* (`robustSe`); `robscore` is the robust score test at `init`. The likelihood ratio and score tests and the R^2 ignore
|
|
455
589
|
* the clustering.
|
|
456
590
|
*
|
|
457
|
-
* Rows with a missing time, status, covariate, weight or
|
|
458
|
-
*
|
|
459
|
-
*
|
|
460
|
-
*
|
|
591
|
+
* Rows with a missing time, status, covariate, weight, stratum, cluster or id are dropped. With `start`, the time is
|
|
592
|
+
* the stop time and the risk set is `start < t <= stop`; start and stop times are merged together unless
|
|
593
|
+
* `control.timefix` is false. Counting-process means are unweighted; right-censored means are weighted. With `id`,
|
|
594
|
+
* `nId` reports distinct subjects; `rsq` still uses the number of rows. R's warnings are returned in `warnings`.
|
|
461
595
|
*
|
|
462
|
-
* @param time Follow-up times.
|
|
463
|
-
* @param status 1 for an event, 0 for a censored time.
|
|
596
|
+
* @param time Follow-up/stop times; with `start`, these are the stop times.
|
|
597
|
+
* @param status 1 for an event, 0 for a censored time (other counting-process values are dropped with a warning).
|
|
464
598
|
* @param x The covariate matrix, one row per observation (at least one column).
|
|
465
599
|
* @param options See {@link CoxphOptions}.
|
|
466
|
-
* @throws TypeError if `robust` is not a boolean. RangeError for invalid arguments, among them
|
|
467
|
-
* and a robust variance with fewer than two clusters.
|
|
600
|
+
* @throws TypeError if `robust` or `control.timefix` is not a boolean. RangeError for invalid arguments, among them
|
|
601
|
+
* an infinite weight, an interval with `start >= stop`, and a robust variance with fewer than two clusters.
|
|
468
602
|
*
|
|
469
603
|
* @example
|
|
470
604
|
* ```ts
|
|
@@ -481,16 +615,20 @@ export function coxph(time, status, x, options = {}) {
|
|
|
481
615
|
return reported("coxph", fitCoxph(time, status, x, options).result);
|
|
482
616
|
}
|
|
483
617
|
/**
|
|
484
|
-
* The fit of {@link coxph},
|
|
485
|
-
*
|
|
486
|
-
*
|
|
618
|
+
* The fit of {@link coxph}, plus the score and dfbeta residuals used by the tests (not exported from the package):
|
|
619
|
+
* R's `residuals(fit, type = "score")` (unweighted) and `residuals(fit, type = "dfbeta")` (weighted), one row per
|
|
620
|
+
* observation used, in input order. Counting-process fixtures also compare the final score vector and convergence flag.
|
|
487
621
|
*
|
|
488
622
|
* @internal
|
|
489
623
|
*/
|
|
490
|
-
export function fitCoxph(time, status, x, options = {}) {
|
|
491
|
-
const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95, robust, cluster } = options;
|
|
624
|
+
export function fitCoxph(time, status, x, options = {}, collectCountingResiduals = false) {
|
|
625
|
+
const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95, robust, cluster, start, id } = options;
|
|
492
626
|
const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
|
|
493
627
|
const tolerInf = control.tolerInf ?? Math.sqrt(eps);
|
|
628
|
+
if (control.timefix !== undefined && typeof control.timefix !== "boolean") {
|
|
629
|
+
throw new TypeError("'timefix' must be a boolean");
|
|
630
|
+
}
|
|
631
|
+
const timefix = control.timefix ?? true;
|
|
494
632
|
if (ties !== "efron" && ties !== "breslow")
|
|
495
633
|
throw new RangeError(`invalid 'ties': ${String(ties)}`);
|
|
496
634
|
if (!(eps > 0 && eps < Infinity))
|
|
@@ -512,6 +650,10 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
512
650
|
throw new RangeError("'strata' must have the same length as 'time'");
|
|
513
651
|
if (cluster !== undefined && cluster.length !== nIn)
|
|
514
652
|
throw new RangeError("'cluster' must have the same length as 'time'");
|
|
653
|
+
if (start !== undefined && start.length !== nIn)
|
|
654
|
+
throw new RangeError("'start' must have the same length as 'time'");
|
|
655
|
+
if (id !== undefined && id.length !== nIn)
|
|
656
|
+
throw new RangeError("'id' must have the same length as 'time'");
|
|
515
657
|
if (robust !== undefined && typeof robust !== "boolean")
|
|
516
658
|
throw new TypeError("'robust' must be true or false");
|
|
517
659
|
const p = nIn === 0 ? 0 : x[0].length;
|
|
@@ -524,19 +666,32 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
524
666
|
if (init?.some((v) => !Number.isFinite(v)))
|
|
525
667
|
throw new RangeError("'init' must contain finite values");
|
|
526
668
|
// 1. the rows used
|
|
669
|
+
const warnings = new Warnings();
|
|
527
670
|
const keep = [];
|
|
528
671
|
for (let i = 0; i < nIn; i++) {
|
|
529
672
|
if (Number.isNaN(time[i]) || Number.isNaN(status[i]) || x[i].some((v) => Number.isNaN(v)))
|
|
530
673
|
continue;
|
|
674
|
+
if (start !== undefined && Number.isNaN(start[i]))
|
|
675
|
+
continue;
|
|
531
676
|
if (weights !== undefined && Number.isNaN(weights[i]))
|
|
532
677
|
continue;
|
|
533
678
|
if (strata !== undefined && isMissingLabel(strata[i]))
|
|
534
679
|
continue;
|
|
535
680
|
if (cluster !== undefined && isMissingLabel(cluster[i]))
|
|
536
681
|
continue;
|
|
682
|
+
if (id !== undefined && isMissingLabel(id[i]))
|
|
683
|
+
continue;
|
|
684
|
+
// The selected API decision is stricter than Surv(): invalid intervals are rejected rather than dropped.
|
|
685
|
+
if (start !== undefined && !(start[i] < time[i])) {
|
|
686
|
+
throw new RangeError("stop time must be > start time");
|
|
687
|
+
}
|
|
537
688
|
const s = status[i];
|
|
538
|
-
if (s !== 0 && s !== 1)
|
|
539
|
-
|
|
689
|
+
if (s !== 0 && s !== 1) {
|
|
690
|
+
if (start === undefined)
|
|
691
|
+
throw new RangeError("'status' must be 0 (censored) or 1 (event)");
|
|
692
|
+
warnings.add("Invalid status value, converted to NA");
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
540
695
|
// a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
|
|
541
696
|
// infinite time, nor anything at -Infinity (as survdiff and survfit)
|
|
542
697
|
if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
|
|
@@ -545,7 +700,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
545
700
|
}
|
|
546
701
|
const n = keep.length;
|
|
547
702
|
if (n === 0)
|
|
548
|
-
throw new RangeError("no observations without missing values");
|
|
703
|
+
throw new RangeError(start === undefined ? "no observations without missing values" : "No (non-missing) observations");
|
|
549
704
|
if (keep.some((i) => x[i].some((v) => !Number.isFinite(v))))
|
|
550
705
|
throw new RangeError("'x' contains infinite values");
|
|
551
706
|
const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
|
|
@@ -555,9 +710,22 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
555
710
|
// Inf or NaN: NaN coefficients and a misleading "coefficient may be infinite" before this check)
|
|
556
711
|
if (w.some((v) => v === Infinity))
|
|
557
712
|
throw new RangeError("'weights' must be finite");
|
|
558
|
-
const warnings = new Warnings();
|
|
559
713
|
// R's default: the robust variance with a cluster or a weight that is not an integer (silently)
|
|
560
|
-
const
|
|
714
|
+
const idLevels = id === undefined ? undefined : numberLevels(id);
|
|
715
|
+
const idEvents = new Map();
|
|
716
|
+
if (idLevels !== undefined) {
|
|
717
|
+
for (const i of keep) {
|
|
718
|
+
if (status[i] !== 1)
|
|
719
|
+
continue;
|
|
720
|
+
const label = idLevels[i];
|
|
721
|
+
idEvents.set(label, (idEvents.get(label) ?? 0) + 1);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
const repeatedIdEvents = start !== undefined && [...idEvents.values()].some((v) => v > 1);
|
|
725
|
+
const useRobust = robust ?? (cluster !== undefined || w.some((v) => !Number.isInteger(v)) || repeatedIdEvents);
|
|
726
|
+
if (start !== undefined && robust === true && cluster === undefined && id === undefined) {
|
|
727
|
+
throw new RangeError("one of cluster or id is needed");
|
|
728
|
+
}
|
|
561
729
|
if (cluster !== undefined && !useRobust)
|
|
562
730
|
warnings.add("cluster specified with robust=FALSE, cluster ignored");
|
|
563
731
|
let nevent = 0;
|
|
@@ -566,26 +734,48 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
566
734
|
// no events: R's coxph returns before the fit (issue #472) with NA coefficients, a zero variance, zero log likelihood,
|
|
567
735
|
// score, Wald statistic and iterations, and the unweighted column means of all covariates (nocenter ignored); `init`
|
|
568
736
|
// is not an estimate here
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
737
|
+
const rawTime = keep.map((i) => time[i]);
|
|
738
|
+
const rawStart = start === undefined ? undefined : keep.map((i) => start[i]);
|
|
739
|
+
let mergedTime;
|
|
740
|
+
let mergedStart;
|
|
741
|
+
if (rawStart === undefined)
|
|
742
|
+
mergedTime = timefix ? mergeTiedTimes(rawTime) : rawTime;
|
|
743
|
+
else if (!timefix) {
|
|
744
|
+
mergedTime = rawTime;
|
|
745
|
+
mergedStart = rawStart;
|
|
746
|
+
}
|
|
747
|
+
else {
|
|
748
|
+
const merged = mergeTiedTimes([...rawStart, ...rawTime]);
|
|
749
|
+
mergedStart = merged.slice(0, n);
|
|
750
|
+
mergedTime = merged.slice(n);
|
|
751
|
+
if (mergedStart.some((v, i) => v >= mergedTime[i])) {
|
|
752
|
+
throw new Error("aeqSurv exception, an interval has effective length 0");
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
if (nevent === 0) {
|
|
756
|
+
const result = zeroEventResult(keep.map((i) => x[i]), p, warnings.list);
|
|
757
|
+
if (idLevels !== undefined)
|
|
758
|
+
result.nId = new Set(keep.map((i) => idLevels[i])).size;
|
|
759
|
+
return { result };
|
|
760
|
+
}
|
|
572
761
|
let stratumOf = new Array(n).fill(0);
|
|
762
|
+
let strataValues;
|
|
763
|
+
let stratumLabels = [];
|
|
573
764
|
if (strata !== undefined) {
|
|
574
765
|
// numeric labels with the same 15-digit text are one stratum, as in R's factor()
|
|
575
766
|
const sl = numberLevels(strata);
|
|
576
|
-
|
|
767
|
+
stratumLabels = Array.from(new Set(keep.map((i) => sl[i]))).sort(compareLabels);
|
|
577
768
|
const index = new Map();
|
|
578
|
-
|
|
769
|
+
stratumLabels.forEach((l, k) => index.set(l, k));
|
|
770
|
+
strataValues = keep.map((i) => sl[i]);
|
|
579
771
|
stratumOf = keep.map((i) => index.get(sl[i]));
|
|
580
772
|
}
|
|
581
773
|
const order = Array.from({ length: n }, (_, k) => k).sort((a, b) => stratumOf[a] - stratumOf[b] || mergedTime[a] - mergedTime[b] || a - b);
|
|
582
774
|
// 2. centring and scaling (sums over the sorted observations)
|
|
583
775
|
const sortedW = order.map((k) => w[k]);
|
|
584
|
-
//
|
|
585
|
-
//
|
|
586
|
-
//
|
|
587
|
-
// W the weight of the deaths), the score and the information by 2^c. Its stopping rule compares log likelihoods by
|
|
588
|
-
// their ratio, which the factor does not change. Below 2^64 nothing is scaled (the same bits as before)
|
|
776
|
+
// Weights of 2^64 or more are divided by 2^c, c the exponent of the largest, to prevent overflow in risk sums,
|
|
777
|
+
// w eta and the log likelihood. Coefficients and means are unchanged; log likelihood, score and information are
|
|
778
|
+
// divided by 2^c and restored in the outputs. Below 2^64 nothing is scaled (the same bits as before).
|
|
589
779
|
const { groups: unitW, k: weightExp } = maxOf(sortedW) >= WEIGHT_LIMIT ? scaleToUnit([sortedW]) : { groups: [sortedW], k: 0 };
|
|
590
780
|
const fitW = unitW[0];
|
|
591
781
|
let totalWeight = 0;
|
|
@@ -604,14 +794,15 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
604
794
|
const centreScale = (col) => {
|
|
605
795
|
let sum = 0;
|
|
606
796
|
for (let k = 0; k < n; k++)
|
|
607
|
-
sum += fitW[k] * col[k];
|
|
608
|
-
const
|
|
797
|
+
sum += (start === undefined ? fitW[k] : 1) * col[k];
|
|
798
|
+
const centreWeight = start === undefined ? totalWeight : n;
|
|
799
|
+
const m = sum / centreWeight;
|
|
609
800
|
let absSum = 0;
|
|
610
801
|
const d = col.map((v, k) => {
|
|
611
|
-
absSum += fitW[k] * Math.abs(v - m);
|
|
802
|
+
absSum += (start === undefined ? fitW[k] : 1) * Math.abs(v - m);
|
|
612
803
|
return v - m;
|
|
613
804
|
});
|
|
614
|
-
const s = absSum === 0 ? 1 :
|
|
805
|
+
const s = absSum === 0 ? 1 : centreWeight / absSum;
|
|
615
806
|
return { m, s, d, ok: Number.isFinite(m) && s >= 2 ** -1022 && s < Infinity };
|
|
616
807
|
};
|
|
617
808
|
let fit = centreScale(column);
|
|
@@ -629,6 +820,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
629
820
|
}
|
|
630
821
|
const data = {
|
|
631
822
|
time: order.map((k) => mergedTime[k]),
|
|
823
|
+
...(mergedStart === undefined ? {} : { start: order.map((k) => mergedStart[k]) }),
|
|
632
824
|
event: order.map((k) => status[keep[k]] === 1),
|
|
633
825
|
weight: fitW,
|
|
634
826
|
x: xs,
|
|
@@ -649,6 +841,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
649
841
|
let iter = 0;
|
|
650
842
|
let inverse;
|
|
651
843
|
let ranOut = false;
|
|
844
|
+
let converged = iterMax === 0;
|
|
652
845
|
if (iterMax === 0 || !Number.isFinite(ev.loglik)) {
|
|
653
846
|
inverse = cholInverse(factor);
|
|
654
847
|
}
|
|
@@ -656,7 +849,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
656
849
|
let best = ev.loglik;
|
|
657
850
|
let next = beta.map((b, i) => b + step[i]);
|
|
658
851
|
let halvings = 0;
|
|
659
|
-
|
|
852
|
+
converged = false;
|
|
660
853
|
for (iter = 1; iter <= iterMax; iter++) {
|
|
661
854
|
ev = evaluate(data, next, efron);
|
|
662
855
|
factor = ev.info.map((row) => row.slice());
|
|
@@ -687,9 +880,17 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
687
880
|
inverse = cholInverse(factor);
|
|
688
881
|
}
|
|
689
882
|
else {
|
|
690
|
-
iter = iterMax + 1;
|
|
883
|
+
iter = start === undefined ? iterMax + 1 : iterMax;
|
|
691
884
|
ranOut = true;
|
|
692
|
-
if (
|
|
885
|
+
if (start !== undefined) {
|
|
886
|
+
// Counting-process fits use the information at the last accepted coefficient, including iter.max = 1.
|
|
887
|
+
ev = evaluate(data, beta, efron);
|
|
888
|
+
loglik[1] = ev.loglik;
|
|
889
|
+
factor = ev.info.map((row) => row.slice());
|
|
890
|
+
rank = cholFactor(factor, tolerChol);
|
|
891
|
+
inverse = cholInverse(factor);
|
|
892
|
+
}
|
|
893
|
+
else if (iterMax > 1) {
|
|
693
894
|
// R recomputes at the last accepted point and applies the inverse step without factorising: that step reads
|
|
694
895
|
// the triangle the accumulation leaves at zero, so only the diagonal survives (off-diagonal entries -0)
|
|
695
896
|
ev = evaluate(data, beta, efron);
|
|
@@ -723,13 +924,14 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
723
924
|
if (inverse[j][j] === 0)
|
|
724
925
|
coefficients[j] = NaN;
|
|
725
926
|
}
|
|
927
|
+
const lpBeta = start === undefined ? internal : internal.map((v, j) => (Number.isNaN(coefficients[j]) ? 0 : v));
|
|
726
928
|
let centre = 0;
|
|
727
929
|
for (let j = 0; j < p; j++)
|
|
728
|
-
centre +=
|
|
930
|
+
centre += lpBeta[j] * means[j];
|
|
729
931
|
const linearPredictors = keep.map((i) => {
|
|
730
932
|
let s = 0;
|
|
731
933
|
for (let j = 0; j < p; j++)
|
|
732
|
-
s += x[i][j] *
|
|
934
|
+
s += x[i][j] * lpBeta[j];
|
|
733
935
|
return s - centre;
|
|
734
936
|
});
|
|
735
937
|
if (iterMax > 1) {
|
|
@@ -741,12 +943,13 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
741
943
|
return Math.abs(s);
|
|
742
944
|
});
|
|
743
945
|
if (ranOut) {
|
|
744
|
-
|
|
745
|
-
|
|
946
|
+
if (start === undefined || iterMax > 1)
|
|
947
|
+
warnings.add("Ran out of iterations and did not converge");
|
|
948
|
+
if (start === undefined && (maxOf(linearPredictors) > 500 || infinity.some((f) => !Number.isFinite(f)))) {
|
|
746
949
|
warnings.add("one or more coefficients may be infinite");
|
|
747
950
|
}
|
|
748
951
|
}
|
|
749
|
-
else {
|
|
952
|
+
else if (start === undefined) {
|
|
750
953
|
const flagged = [];
|
|
751
954
|
for (let j = 0; j < p; j++) {
|
|
752
955
|
const f = infinity[j];
|
|
@@ -754,7 +957,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
754
957
|
flagged.push(j + 1);
|
|
755
958
|
}
|
|
756
959
|
if (flagged.length > 0) {
|
|
757
|
-
warnings.add(
|
|
960
|
+
warnings.add("Loglik converged before variable " + flagged.join(",") + " ; coefficient may be infinite. ");
|
|
758
961
|
}
|
|
759
962
|
}
|
|
760
963
|
}
|
|
@@ -772,8 +975,9 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
772
975
|
// the cluster of each sorted observation (each its own without a cluster); numeric labels as R's factor()
|
|
773
976
|
let clusterOf = order.map((_, r) => r);
|
|
774
977
|
let nClusters = n;
|
|
775
|
-
|
|
776
|
-
|
|
978
|
+
const clusterLabels = cluster ?? (start === undefined ? undefined : id);
|
|
979
|
+
if (clusterLabels !== undefined) {
|
|
980
|
+
const cl = numberLevels(clusterLabels);
|
|
777
981
|
const index = new Map();
|
|
778
982
|
clusterOf = order.map((kk) => {
|
|
779
983
|
const label = cl[keep[kk]];
|
|
@@ -788,10 +992,10 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
788
992
|
}
|
|
789
993
|
// R fails here with an unrelated message ("(subscript) logical subscript too long")
|
|
790
994
|
if (nClusters < 2)
|
|
791
|
-
throw new RangeError("at least two clusters are needed for the robust variance");
|
|
995
|
+
throw new RangeError(start === undefined ? "at least two clusters are needed for the robust variance" : "(subscript) logical subscript too long");
|
|
792
996
|
const toUnit = (rows) => rows.map((row) => row.map((v, j) => v / mant[j]));
|
|
793
997
|
// dfbeta_j = w_j s_j' V_naive (V_naive with zero rows and columns for NaN coefficients), summed by cluster
|
|
794
|
-
const sUnit = toUnit(scoreResiduals(data, beta, efron));
|
|
998
|
+
const sUnit = toUnit(start === undefined ? scoreResiduals(data, beta, efron) : scoreResidualsCounting(data, beta, efron));
|
|
795
999
|
// (w 2^-c varFit = (w 2^-c) (s' varFit)). With the weights divided by 2^c, the product is taken times 2^dfExp, dfExp
|
|
796
1000
|
// such that its largest value is near 1: w 2^-c and s' varFit can both be near the bottom of the doubles (a weight of
|
|
797
1001
|
// 1e300 among weights 1, whose units 2^e_j are then about 1e300 too), where the plain product underflowed to 0
|
|
@@ -841,7 +1045,8 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
841
1045
|
// underflowing for weights around 2^+-512): T_c is formed from the weights in units of a power of 2 (exact)
|
|
842
1046
|
const wUnit = scaleToUnit([sortedW]).groups[0];
|
|
843
1047
|
const beta0 = init === undefined ? new Array(p).fill(0) : init.map((v, j) => ldexp(v / scales[j], shift[j]));
|
|
844
|
-
const
|
|
1048
|
+
const initialResiduals = start === undefined ? scoreResiduals(data, beta0, efron) : scoreResidualsCounting(data, beta0, efron);
|
|
1049
|
+
const t = clusterSums(toUnit(initialResiduals).map((s, r) => s.map((v) => wUnit[r] * v)));
|
|
845
1050
|
const u = new Array(p).fill(0);
|
|
846
1051
|
for (const row of t)
|
|
847
1052
|
for (let i = 0; i < p; i++)
|
|
@@ -915,6 +1120,7 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
915
1120
|
means,
|
|
916
1121
|
n,
|
|
917
1122
|
nevent,
|
|
1123
|
+
...(idLevels === undefined ? {} : { nId: new Set(keep.map((i) => idLevels[i])).size }),
|
|
918
1124
|
linearPredictors,
|
|
919
1125
|
se,
|
|
920
1126
|
z,
|
|
@@ -932,5 +1138,39 @@ export function fitCoxph(time, status, x, options = {}) {
|
|
|
932
1138
|
...(usedRobust ? { naiveVar: variance, robustSe: testSe, rscore, robscore: chisqTest(rscore, k) } : {}),
|
|
933
1139
|
warnings: warnings.list,
|
|
934
1140
|
};
|
|
935
|
-
|
|
1141
|
+
// Convert the score from the centred/scaled covariates to the original covariate units:
|
|
1142
|
+
// x_scaled = (x / 2^shift - mean) * scale, so dℓ/dβ_original = (dℓ/dβ_scaled) * 2^shift / scale.
|
|
1143
|
+
const first = ev.score.map((v, j) => ldexp(v / scales[j], shift[j] + weightExp));
|
|
1144
|
+
Object.defineProperty(result, "coxZphData", {
|
|
1145
|
+
enumerable: false,
|
|
1146
|
+
value: {
|
|
1147
|
+
time: mergedTime.slice(),
|
|
1148
|
+
...(mergedStart === undefined ? {} : { start: mergedStart.slice() }),
|
|
1149
|
+
status: keep.map((i) => status[i] === 1),
|
|
1150
|
+
weights: w.slice(),
|
|
1151
|
+
...(strataValues === undefined ? {} : { strata: strataValues.slice() }),
|
|
1152
|
+
x: keep.map((i) => x[i].slice()),
|
|
1153
|
+
sortedToInput: order.slice(),
|
|
1154
|
+
sortedTime: data.time.slice(),
|
|
1155
|
+
...(data.start === undefined ? {} : { sortedStart: data.start.slice() }),
|
|
1156
|
+
sortedEvent: data.event.slice(),
|
|
1157
|
+
sortedWeight: data.weight.slice(),
|
|
1158
|
+
sortedX: data.x.map((row) => row.slice()),
|
|
1159
|
+
stratumIndex: order.map((k) => stratumOf[k]),
|
|
1160
|
+
stratumEnd: data.stratumEnd.slice(),
|
|
1161
|
+
betaScaled: beta.slice(),
|
|
1162
|
+
inverseCovariateScale: mant.map((v, j) => ldexp(1 / v, -expo[j])),
|
|
1163
|
+
weightExp,
|
|
1164
|
+
ties,
|
|
1165
|
+
},
|
|
1166
|
+
});
|
|
1167
|
+
let scoreOut = residuals?.scoreResiduals;
|
|
1168
|
+
if (start !== undefined && collectCountingResiduals && scoreOut === undefined) {
|
|
1169
|
+
const raw = scoreResidualsCounting(data, beta, efron);
|
|
1170
|
+
scoreOut = new Array(n);
|
|
1171
|
+
order.forEach((kk, r) => {
|
|
1172
|
+
scoreOut[kk] = raw[r].map((v, j) => ldexp(v / mant[j], -expo[j]));
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
return { result, ...residuals, ...(scoreOut === undefined ? {} : { scoreResiduals: scoreOut }), first, converged };
|
|
936
1176
|
}
|