@numero-uno-jpn/rstats 1.2.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 (89) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.ja.md +28 -11
  3. package/README.md +27 -10
  4. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-27VFB3SA.js} +2 -2
  5. package/dist/chunks/{chunk-BKV3FINA.js → chunk-56GFP4UU.js} +2 -2
  6. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-5SW3L6J3.js} +2 -2
  7. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-6FZAJQ4H.js} +2 -2
  8. package/dist/chunks/{chunk-VERBXW6E.js → chunk-BQJFFGYP.js} +2 -2
  9. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-F6Z3GLWA.js} +2 -2
  10. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-GBSMRVUY.js} +2 -2
  11. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-GEF2YRBV.js} +2 -2
  12. package/dist/chunks/{chunk-L23RSC2N.js → chunk-GIER5WMB.js} +2 -2
  13. package/dist/chunks/{chunk-IAWXF73N.js → chunk-GLGOV3A5.js} +2 -2
  14. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-H72MW7YP.js} +2 -2
  15. package/dist/chunks/{chunk-T5DRIITM.js → chunk-HWB7XRX2.js} +2 -2
  16. package/dist/chunks/chunk-J72MLFUG.js +2 -0
  17. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PZ66PUWC.js} +2 -2
  18. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-RUZATICF.js} +1 -1
  19. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-RY7CCWVU.js} +1 -1
  20. package/dist/chunks/{chunk-7INBXTVV.js → chunk-S2YCFUCA.js} +2 -2
  21. package/dist/chunks/chunk-SVS54D6Z.js +2 -0
  22. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-TEHMTQNB.js} +3 -3
  23. package/dist/chunks/chunk-UMMCVF53.js +2 -0
  24. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-UNP4HBPP.js} +2 -2
  25. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-V2KVTAVV.js} +2 -2
  26. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-WWJGCBWH.js} +1 -1
  27. package/dist/chunks/chunk-X7K6EF7S.js +2 -0
  28. package/dist/chunks/{chunk-73LNRWU3.js → chunk-YBOSCQF2.js} +1 -1
  29. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-ZQSOMEIM.js} +2 -2
  30. package/dist/chunks/{chunk-4AOTAT3O.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 +13 -0
  34. package/dist/entries/tests.js +13 -0
  35. package/dist/htest/agreement.d.ts +2 -2
  36. package/dist/htest/blandAltman.d.ts +100 -0
  37. package/dist/htest/blandAltman.js +159 -0
  38. package/dist/htest/diagnosticTests.d.ts +91 -0
  39. package/dist/htest/diagnosticTests.js +116 -0
  40. package/dist/htest/iccPsych.d.ts +106 -0
  41. package/dist/htest/iccPsych.js +332 -0
  42. package/dist/htest/ksTest.d.ts +1 -1
  43. package/dist/htest/mcreg.d.ts +209 -0
  44. package/dist/htest/mcreg.js +735 -0
  45. package/dist/htest/roc.d.ts +287 -0
  46. package/dist/htest/roc.js +635 -0
  47. package/dist/htest/rocTest.d.ts +139 -0
  48. package/dist/htest/rocTest.js +444 -0
  49. package/dist/htest/tTOST.d.ts +202 -0
  50. package/dist/htest/tTOST.js +558 -0
  51. package/dist/htest/trendTests.d.ts +1 -1
  52. package/dist/htest/trendTests.js +1 -1
  53. package/dist/internal/summary.js +5 -0
  54. package/dist/linalg/qr.d.ts +3 -0
  55. package/dist/linalg/qr.js +3 -0
  56. package/dist/linalg.js +2 -2
  57. package/dist/mixed.js +2 -2
  58. package/dist/models/coeftest.d.ts +139 -0
  59. package/dist/models/coeftest.js +237 -0
  60. package/dist/models/competingRisks.d.ts +188 -0
  61. package/dist/models/competingRisks.js +673 -0
  62. package/dist/models/coxZph.d.ts +67 -0
  63. package/dist/models/coxZph.js +479 -0
  64. package/dist/models/coxph.d.ts +107 -16
  65. package/dist/models/coxph.js +641 -72
  66. package/dist/models/glm.d.ts +11 -1
  67. package/dist/models/glm.js +19 -2
  68. package/dist/models/inputRows.d.ts +10 -0
  69. package/dist/models/inputRows.js +23 -0
  70. package/dist/models/lm.d.ts +8 -0
  71. package/dist/models/lm.js +14 -2
  72. package/dist/models/rmst2.d.ts +126 -0
  73. package/dist/models/rmst2.js +365 -0
  74. package/dist/models/sandwich.d.ts +177 -0
  75. package/dist/models/sandwich.js +923 -0
  76. package/dist/models/survival.d.ts +65 -24
  77. package/dist/models/survival.js +407 -72
  78. package/dist/models/survreg.d.ts +160 -0
  79. package/dist/models/survreg.js +809 -0
  80. package/dist/numerics.js +2 -2
  81. package/dist/random/rng.d.ts +8 -1
  82. package/dist/random/rng.js +14 -1
  83. package/dist/rstats.js +16 -16
  84. package/dist/special.js +2 -2
  85. package/dist/tests.js +13 -13
  86. package/llms.txt +25 -0
  87. package/package.json +1 -1
  88. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  89. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -1,6 +1,6 @@
1
- // Cox proportional hazards regression for right-censored data with a matrix interface: R's coxph from the survival
2
- // package (the fit, with Efron's or Breslow's handling of ties, case weights and strata) and the values of
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,14 @@
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.
13
+ //
14
+ // The robust variance (survival's `robust = TRUE` or `cluster`) is the Lin-Wei sandwich, written from section 5 of
15
+ // oracle/robust-behaviour.md and Lin and Wei (1989), "The robust inference for the Cox proportional hazards model",
16
+ // JASA 84, 1074-1078; Therneau and Grambsch (2000), "Modeling Survival Data: Extending the Cox Model", Springer,
17
+ // chapters 4 (score residuals, Efron's weighting of tied deaths) and 7 (dfbeta residuals, clustering, the robust score
18
+ // test).
12
19
  import { pchisq } from "../distributions/chisq.js";
13
20
  import { qnorm } from "../distributions/normal.js";
14
21
  import { numberLevels } from "../internal/levels.js";
@@ -18,14 +25,19 @@ import { reported, Warnings } from "../internal/warnings.js";
18
25
  import { maxOf } from "../internal/extremes.js";
19
26
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
27
  import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
21
- const COXPH_KEYS = ["ties", "weights", "strata", "init", "control", "nocenter", "confLevel"];
22
- const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf"];
28
+ const COXPH_KEYS = /* @__PURE__ */ new Set([
29
+ "start", "id", "ties", "weights", "strata", "init", "control", "nocenter", "confLevel", "robust", "cluster",
30
+ ]);
31
+ const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf", "timefix"];
23
32
  const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
24
33
  const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
34
+ /** The weights from which the fit runs on weights divided by a power of 2 (see SortedData.logUnit) */
35
+ const WEIGHT_LIMIT = 2 ** 64;
36
+ const MIN_NORMAL = 2 ** -1022;
25
37
  /** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
26
38
  const SHIFT_LIMIT = 700;
27
39
  function evaluate(data, beta, efron) {
28
- const { time, event, weight, x, stratumEnd } = data;
40
+ const { time, event, weight, x, stratumEnd, logUnit, start: startTime } = data;
29
41
  const n = time.length;
30
42
  const p = beta.length;
31
43
  const zeros = () => new Array(p).fill(0);
@@ -68,6 +80,51 @@ function evaluate(data, beta, efron) {
68
80
  riskXX = zeroMatrix();
69
81
  }
70
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
+ }
71
128
  let deaths = 0;
72
129
  let deathWeight = 0;
73
130
  deathRisk = 0;
@@ -86,12 +143,14 @@ function evaluate(data, beta, efron) {
86
143
  }
87
144
  const r = Math.exp(eta - shift) * w;
88
145
  if (!event[j]) {
89
- riskSum += r;
90
- for (let i = 0; i < p; i++) {
91
- riskX[i] += r * xj[i];
92
- const row = riskXX[i];
93
- for (let l = 0; l <= i; l++)
94
- row[l] += r * xj[i] * xj[l];
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
+ }
95
154
  }
96
155
  }
97
156
  else {
@@ -115,7 +174,8 @@ function evaluate(data, beta, efron) {
115
174
  const stepWeight = deathWeight / steps;
116
175
  for (let s = 0; s < steps; s++) {
117
176
  riskSum += efron ? deathRisk / share : deathRisk;
118
- loglik -= stepWeight * (Math.log(riskSum) + shift);
177
+ // (the risk sum of the weights in units of 2^c is 2^-c times that of the fit's: log 2^c = logUnit added back)
178
+ loglik -= stepWeight * (Math.log(riskSum) + shift + logUnit);
119
179
  for (let i = 0; i < p; i++) {
120
180
  riskX[i] += efron ? deathX[i] / share : deathX[i];
121
181
  const mean = riskX[i] / riskSum;
@@ -125,7 +185,15 @@ function evaluate(data, beta, efron) {
125
185
  const irow = info[i];
126
186
  for (let l = 0; l <= i; l++) {
127
187
  row[l] += efron ? drow[l] / share : drow[l];
128
- irow[l] += (stepWeight * (row[l] - mean * riskX[l])) / riskSum;
188
+ const dev = row[l] - mean * riskX[l];
189
+ const term = stepWeight * dev;
190
+ // stepWeight and dev both carry the scale of the weights, so the product leaves the doubles for weights
191
+ // around 2^+-512 although the term does not: there (only) the quotient first, which does not change the
192
+ // bits of the ordinary case
193
+ irow[l] +=
194
+ (term < Infinity && term > -Infinity && (Math.abs(term) >= MIN_NORMAL || dev === 0)) || !Number.isFinite(stepWeight)
195
+ ? term / riskSum
196
+ : stepWeight * (dev / riskSum);
129
197
  }
130
198
  }
131
199
  }
@@ -140,6 +208,235 @@ function evaluate(data, beta, efron) {
140
208
  info[l][i] = info[i][l];
141
209
  return { loglik, score, info };
142
210
  }
211
+ /**
212
+ * The (unweighted) score residuals of every observation at the coefficients `beta`, in the units of `data.x` and the
213
+ * sorted order (oracle/robust-behaviour.md 5.2; Therneau and Grambsch 2000, section 4.6). For each event time t of a
214
+ * stratum with risk set R, deaths D (d of them, weight dw), S0 = sum_R w r, S1 = sum_R w r x and E0, E1 the same sums
215
+ * over D, the time is split into M steps (M = d for Efron's ties, else 1); step m (f = m / M) has the risk sum
216
+ * S0 - f E0, the mean xbar_m = (S1 - f E1) / (S0 - f E0) and the hazard increment lambda_m = (dw / M) / (S0 - f E0).
217
+ * An observation j at risk but not dying at t gets -r_j sum_m lambda_m (x_j - xbar_m); a death gets
218
+ * sum_m [(x_j - xbar_m) / M - (1 - f) r_j lambda_m (x_j - xbar_m)]. The increments of the times before an
219
+ * observation's own are accumulated forward in time (C0 = sum lambda, C1 = sum lambda xbar), so that each residual
220
+ * costs O(p) and not O(n p). Sum_j w_j s_j is the score vector.
221
+ *
222
+ * Each risk set is shifted by its own largest linear predictor M (as evaluate shifts the risk sums): S0 and S1 of a
223
+ * time are held as e^-M times their values, and C0 and C1 in the units e^-M of the current time. A shift by the
224
+ * stratum's largest linear predictor alone made every r of the later risk sets 0 once the linear predictors spanned
225
+ * more than about 745 (an early death with a large one): S0 = 0 and the residuals NaN. M does not increase forward in
226
+ * time, so the rescaling factors of C0 and C1 are at most 1 and only the negligible early terms can underflow. The
227
+ * residuals do not depend on the scale of the weights, which are therefore taken in units of a power of 2 (exact)
228
+ */
229
+ function scoreResiduals(data, beta, efron) {
230
+ const { time, event, x, stratumEnd } = data;
231
+ const weight = scaleToUnit([data.weight]).groups[0];
232
+ const n = time.length;
233
+ const p = beta.length;
234
+ const out = Array.from({ length: n }, () => new Array(p).fill(0));
235
+ const etaOf = (j) => {
236
+ let e = 0;
237
+ for (let i = 0; i < p; i++)
238
+ e += beta[i] * x[j][i];
239
+ return e;
240
+ };
241
+ for (let start = 0; start < n;) {
242
+ let end = start;
243
+ while (!stratumEnd[end])
244
+ end++;
245
+ const eta = [];
246
+ for (let j = start; j <= end; j++)
247
+ eta.push(etaOf(j));
248
+ // the first row of each group of tied times, and the risk sums at it (accumulated from the end of the stratum) in
249
+ // units of e^-shift[g], shift[g] the largest linear predictor of the risk set (0 if it is not finite)
250
+ const groupStart = [];
251
+ for (let j = start; j <= end; j++)
252
+ if (j === start || time[j] !== time[j - 1])
253
+ groupStart.push(j);
254
+ const groupEnd = (g) => (g + 1 < groupStart.length ? groupStart[g + 1] : end + 1);
255
+ const riskSum = new Array(groupStart.length);
256
+ const riskX = new Array(groupStart.length);
257
+ const shift = new Array(groupStart.length);
258
+ let top = -Infinity;
259
+ let s0 = 0;
260
+ const s1 = new Array(p).fill(0);
261
+ for (let g = groupStart.length - 1; g >= 0; g--) {
262
+ const before = Number.isFinite(top) ? top : 0;
263
+ for (let j = groupStart[g]; j < groupEnd(g); j++)
264
+ top = Math.max(top, eta[j - start]);
265
+ const m = Number.isFinite(top) ? top : 0;
266
+ // (nothing to rescale at the last time, where `before` is only a placeholder)
267
+ if (g < groupStart.length - 1 && m !== before) {
268
+ const f = Math.exp(before - m);
269
+ s0 *= f;
270
+ for (let i = 0; i < p; i++)
271
+ s1[i] *= f;
272
+ }
273
+ for (let j = groupStart[g]; j < groupEnd(g); j++) {
274
+ const wr = weight[j] * Math.exp(eta[j - start] - m);
275
+ s0 += wr;
276
+ for (let i = 0; i < p; i++)
277
+ s1[i] += wr * x[j][i];
278
+ }
279
+ riskSum[g] = s0;
280
+ riskX[g] = s1.slice();
281
+ shift[g] = m;
282
+ }
283
+ // C0 = sum lambda and C1 = sum lambda xbar over the earlier event times, in units of e^-shift[g]
284
+ let c0 = 0;
285
+ const c1 = new Array(p).fill(0);
286
+ for (let g = 0; g < groupStart.length; g++) {
287
+ const m = shift[g];
288
+ if (g > 0 && m !== shift[g - 1]) {
289
+ const f = Math.exp(m - shift[g - 1]);
290
+ c0 *= f;
291
+ for (let i = 0; i < p; i++)
292
+ c1[i] *= f;
293
+ }
294
+ const from = groupStart[g];
295
+ const to = groupEnd(g);
296
+ // r_j in units of e^shift[g] (eta_j <= shift[g] for every j at risk)
297
+ const r = [];
298
+ for (let j = from; j < to; j++)
299
+ r.push(Math.exp(eta[j - start] - m));
300
+ let d = 0;
301
+ let dw = 0;
302
+ let e0 = 0;
303
+ const e1 = new Array(p).fill(0);
304
+ for (let j = from; j < to; j++) {
305
+ if (!event[j])
306
+ continue;
307
+ const wr = weight[j] * r[j - from];
308
+ d++;
309
+ dw += weight[j];
310
+ e0 += wr;
311
+ for (let i = 0; i < p; i++)
312
+ e1[i] += wr * x[j][i];
313
+ }
314
+ // the part of the earlier event times: -r_j (x_j C0 - C1)
315
+ for (let j = from; j < to; j++) {
316
+ const rj = r[j - from];
317
+ const xj = x[j];
318
+ const sj = out[j];
319
+ for (let i = 0; i < p; i++)
320
+ sj[i] = -rj * (xj[i] * c0 - c1[i]);
321
+ }
322
+ if (d === 0)
323
+ continue;
324
+ const steps = efron ? d : 1;
325
+ for (let k = 0; k < steps; k++) {
326
+ const f = k / steps;
327
+ const s0m = riskSum[g] - f * e0;
328
+ const xbar = riskX[g].map((v, i) => (v - f * e1[i]) / s0m);
329
+ const lambda = dw / steps / s0m;
330
+ for (let j = from; j < to; j++) {
331
+ const rj = r[j - from];
332
+ const xj = x[j];
333
+ const sj = out[j];
334
+ if (event[j]) {
335
+ for (let i = 0; i < p; i++) {
336
+ const dx = xj[i] - xbar[i];
337
+ sj[i] += dx / steps - (1 - f) * rj * dx * lambda;
338
+ }
339
+ }
340
+ else {
341
+ for (let i = 0; i < p; i++)
342
+ sj[i] -= rj * (xj[i] - xbar[i]) * lambda;
343
+ }
344
+ }
345
+ c0 += lambda;
346
+ for (let i = 0; i < p; i++)
347
+ c1[i] += lambda * xbar[i];
348
+ }
349
+ }
350
+ start = end + 1;
351
+ }
352
+ return out;
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
+ }
143
440
  /**
144
441
  * Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
145
442
  * set to 0. Returns the rank (negative when M is not non-negative definite).
@@ -245,7 +542,7 @@ const chisqTest = (statistic, df) => ({
245
542
  pValue: pchisq(statistic, df, { lowerTail: false }),
246
543
  });
247
544
  /** R's result for data without events (survival's coxph returns it before fitting), with summary(fit)'s values */
248
- function zeroEventResult(rows, p) {
545
+ function zeroEventResult(rows, p, warnings) {
249
546
  const n = rows.length;
250
547
  const nans = () => new Array(p).fill(NaN);
251
548
  const test = chisqTest(0, 0);
@@ -275,23 +572,33 @@ function zeroEventResult(rows, p) {
275
572
  sctest: { ...test },
276
573
  waldtest: { ...test },
277
574
  rsq: { rsq: 0, maxrsq: 0 },
278
- warnings: [],
575
+ usedRobust: false,
576
+ warnings,
279
577
  };
280
578
  }
281
579
  /**
282
580
  * Cox proportional hazards regression. Equivalent to R's `survival::coxph()`. As
283
- * `coxph(Surv(time, status) ~ x [+ strata(strata)], weights, ties, init, control)` for right-censored data, with the
284
- * values of `summary(fit)`.
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:
586
+ * `var` is the robust variance and `naiveVar` the model-based one; `se` (and `stdError`) stay the model-based standard
587
+ * errors (R's `se(coef)`), while `z`, `p`, the intervals `lower`/`upper`, `wald` and `waldtest` use the robust ones
588
+ * (`robustSe`); `robscore` is the robust score test at `init`. The likelihood ratio and score tests and the R^2 ignore
589
+ * the clustering.
285
590
  *
286
- * Rows with a missing time, status, covariate, weight or stratum are dropped. Times within sqrt(eps) of each other are
287
- * treated as tied. Covariates whose values all lie in `nocenter` are not centred; the others are centred by their
288
- * weighted means, which only shifts the linear predictors. R's warnings (non-convergence, possibly infinite
289
- * coefficients) are returned in `warnings`.
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`.
290
595
  *
291
- * @param time Follow-up times.
292
- * @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).
293
598
  * @param x The covariate matrix, one row per observation (at least one column).
294
599
  * @param options See {@link CoxphOptions}.
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.
295
602
  *
296
603
  * @example
297
604
  * ```ts
@@ -305,9 +612,23 @@ function zeroEventResult(rows, p) {
305
612
  export function coxph(time, status, x, options = {}) {
306
613
  checkOptions(options, COXPH_KEYS, "coxph"); // generated: option-keys.mjs
307
614
  checkOptions(nestedOptions(options, "control"), COXPH_CONTROL_KEYS, "coxph", "control"); // generated: option-keys.mjs
308
- const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95 } = options;
615
+ return reported("coxph", fitCoxph(time, status, x, options).result);
616
+ }
617
+ /**
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.
621
+ *
622
+ * @internal
623
+ */
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;
309
626
  const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
310
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;
311
632
  if (ties !== "efron" && ties !== "breslow")
312
633
  throw new RangeError(`invalid 'ties': ${String(ties)}`);
313
634
  if (!(eps > 0 && eps < Infinity))
@@ -327,6 +648,14 @@ export function coxph(time, status, x, options = {}) {
327
648
  throw new RangeError("'weights' must have the same length as 'time'");
328
649
  if (strata !== undefined && strata.length !== nIn)
329
650
  throw new RangeError("'strata' must have the same length as 'time'");
651
+ if (cluster !== undefined && cluster.length !== nIn)
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'");
657
+ if (robust !== undefined && typeof robust !== "boolean")
658
+ throw new TypeError("'robust' must be true or false");
330
659
  const p = nIn === 0 ? 0 : x[0].length;
331
660
  if (p < 1)
332
661
  throw new RangeError("'x' must have at least one column");
@@ -337,17 +666,32 @@ export function coxph(time, status, x, options = {}) {
337
666
  if (init?.some((v) => !Number.isFinite(v)))
338
667
  throw new RangeError("'init' must contain finite values");
339
668
  // 1. the rows used
669
+ const warnings = new Warnings();
340
670
  const keep = [];
341
671
  for (let i = 0; i < nIn; i++) {
342
672
  if (Number.isNaN(time[i]) || Number.isNaN(status[i]) || x[i].some((v) => Number.isNaN(v)))
343
673
  continue;
674
+ if (start !== undefined && Number.isNaN(start[i]))
675
+ continue;
344
676
  if (weights !== undefined && Number.isNaN(weights[i]))
345
677
  continue;
346
678
  if (strata !== undefined && isMissingLabel(strata[i]))
347
679
  continue;
680
+ if (cluster !== undefined && isMissingLabel(cluster[i]))
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
+ }
348
688
  const s = status[i];
349
- if (s !== 0 && s !== 1)
350
- throw new RangeError("'status' must be 0 (censored) or 1 (event)");
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
+ }
351
695
  // a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
352
696
  // infinite time, nor anything at -Infinity (as survdiff and survfit)
353
697
  if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
@@ -356,38 +700,87 @@ export function coxph(time, status, x, options = {}) {
356
700
  }
357
701
  const n = keep.length;
358
702
  if (n === 0)
359
- throw new RangeError("no observations without missing values");
703
+ throw new RangeError(start === undefined ? "no observations without missing values" : "No (non-missing) observations");
360
704
  if (keep.some((i) => x[i].some((v) => !Number.isFinite(v))))
361
705
  throw new RangeError("'x' contains infinite values");
362
706
  const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
363
707
  if (w.some((v) => !(v > 0)))
364
708
  throw new RangeError("Invalid weights, must be >0");
365
- if (w.some((v) => !Number.isInteger(v)))
366
- throw new RangeError("non-integer weights (robust variance) are not supported yet");
709
+ // an infinite weight passes R's check (> 0) and counts as an integer there; the fit cannot use it (the sums become
710
+ // Inf or NaN: NaN coefficients and a misleading "coefficient may be infinite" before this check)
711
+ if (w.some((v) => v === Infinity))
712
+ throw new RangeError("'weights' must be finite");
713
+ // R's default: the robust variance with a cluster or a weight that is not an integer (silently)
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
+ }
729
+ if (cluster !== undefined && !useRobust)
730
+ warnings.add("cluster specified with robust=FALSE, cluster ignored");
367
731
  let nevent = 0;
368
732
  for (const i of keep)
369
733
  nevent += status[i];
370
734
  // no events: R's coxph returns before the fit (issue #472) with NA coefficients, a zero variance, zero log likelihood,
371
735
  // score, Wald statistic and iterations, and the unweighted column means of all covariates (nocenter ignored); `init`
372
736
  // is not an estimate here
373
- if (nevent === 0)
374
- return zeroEventResult(keep.map((i) => x[i]), p);
375
- const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
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
+ }
376
761
  let stratumOf = new Array(n).fill(0);
762
+ let strataValues;
763
+ let stratumLabels = [];
377
764
  if (strata !== undefined) {
378
765
  // numeric labels with the same 15-digit text are one stratum, as in R's factor()
379
766
  const sl = numberLevels(strata);
380
- const labels = Array.from(new Set(keep.map((i) => sl[i]))).sort(compareLabels);
767
+ stratumLabels = Array.from(new Set(keep.map((i) => sl[i]))).sort(compareLabels);
381
768
  const index = new Map();
382
- labels.forEach((l, k) => index.set(l, k));
769
+ stratumLabels.forEach((l, k) => index.set(l, k));
770
+ strataValues = keep.map((i) => sl[i]);
383
771
  stratumOf = keep.map((i) => index.get(sl[i]));
384
772
  }
385
773
  const order = Array.from({ length: n }, (_, k) => k).sort((a, b) => stratumOf[a] - stratumOf[b] || mergedTime[a] - mergedTime[b] || a - b);
386
774
  // 2. centring and scaling (sums over the sorted observations)
775
+ const sortedW = order.map((k) => w[k]);
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).
779
+ const { groups: unitW, k: weightExp } = maxOf(sortedW) >= WEIGHT_LIMIT ? scaleToUnit([sortedW]) : { groups: [sortedW], k: 0 };
780
+ const fitW = unitW[0];
387
781
  let totalWeight = 0;
388
782
  for (const v of w)
389
- totalWeight += v;
390
- const sortedW = order.map((k) => w[k]);
783
+ totalWeight += weightExp === 0 ? v : ldexp(v, -weightExp);
391
784
  const xs = order.map((k) => x[keep[k]].slice());
392
785
  const means = new Array(p).fill(0);
393
786
  // the scale of column j is scales[j] 2^-shift[j]
@@ -401,14 +794,15 @@ export function coxph(time, status, x, options = {}) {
401
794
  const centreScale = (col) => {
402
795
  let sum = 0;
403
796
  for (let k = 0; k < n; k++)
404
- sum += sortedW[k] * col[k];
405
- const m = sum / totalWeight;
797
+ sum += (start === undefined ? fitW[k] : 1) * col[k];
798
+ const centreWeight = start === undefined ? totalWeight : n;
799
+ const m = sum / centreWeight;
406
800
  let absSum = 0;
407
801
  const d = col.map((v, k) => {
408
- absSum += sortedW[k] * Math.abs(v - m);
802
+ absSum += (start === undefined ? fitW[k] : 1) * Math.abs(v - m);
409
803
  return v - m;
410
804
  });
411
- const s = absSum === 0 ? 1 : totalWeight / absSum;
805
+ const s = absSum === 0 ? 1 : centreWeight / absSum;
412
806
  return { m, s, d, ok: Number.isFinite(m) && s >= 2 ** -1022 && s < Infinity };
413
807
  };
414
808
  let fit = centreScale(column);
@@ -426,10 +820,12 @@ export function coxph(time, status, x, options = {}) {
426
820
  }
427
821
  const data = {
428
822
  time: order.map((k) => mergedTime[k]),
823
+ ...(mergedStart === undefined ? {} : { start: order.map((k) => mergedStart[k]) }),
429
824
  event: order.map((k) => status[keep[k]] === 1),
430
- weight: sortedW,
825
+ weight: fitW,
431
826
  x: xs,
432
827
  stratumEnd: order.map((k, r) => r === n - 1 || stratumOf[order[r + 1]] !== stratumOf[k]),
828
+ logUnit: weightExp * Math.LN2,
433
829
  };
434
830
  const efron = ties === "efron";
435
831
  // 3.-5. Newton-Raphson on the scaled coefficients
@@ -445,6 +841,7 @@ export function coxph(time, status, x, options = {}) {
445
841
  let iter = 0;
446
842
  let inverse;
447
843
  let ranOut = false;
844
+ let converged = iterMax === 0;
448
845
  if (iterMax === 0 || !Number.isFinite(ev.loglik)) {
449
846
  inverse = cholInverse(factor);
450
847
  }
@@ -452,7 +849,7 @@ export function coxph(time, status, x, options = {}) {
452
849
  let best = ev.loglik;
453
850
  let next = beta.map((b, i) => b + step[i]);
454
851
  let halvings = 0;
455
- let converged = false;
852
+ converged = false;
456
853
  for (iter = 1; iter <= iterMax; iter++) {
457
854
  ev = evaluate(data, next, efron);
458
855
  factor = ev.info.map((row) => row.slice());
@@ -483,9 +880,17 @@ export function coxph(time, status, x, options = {}) {
483
880
  inverse = cholInverse(factor);
484
881
  }
485
882
  else {
486
- iter = iterMax + 1;
883
+ iter = start === undefined ? iterMax + 1 : iterMax;
487
884
  ranOut = true;
488
- if (iterMax > 1) {
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) {
489
894
  // R recomputes at the last accepted point and applies the inverse step without factorising: that step reads
490
895
  // the triangle the accumulation leaves at zero, so only the diagonal survives (off-diagonal entries -0)
491
896
  ev = evaluate(data, beta, efron);
@@ -506,10 +911,12 @@ export function coxph(time, status, x, options = {}) {
506
911
  const mant = scales.map((s, j) => ldexp(s, -scaleExpo[j]));
507
912
  const expo = scaleExpo.map((e, j) => e - shift[j]);
508
913
  const coefUnit = beta.map((b, j) => b * mant[j]);
914
+ // (the score and the variance of the weights divided by 2^c: the fit's variance is 2^-c varFit, which is kept apart,
915
+ // as 2^-c and the units 2^e_j can be far from 1 in opposite directions, e.g. a weight of 1e300 among weights 1)
509
916
  const uUnit = ev.score.map((v, j) => v / mant[j]);
510
- const varUnit = inverse.map((row, i) => row.map((v, j) => v * mant[i] * mant[j]));
917
+ const varFit = inverse.map((row, i) => row.map((v, j) => v * mant[i] * mant[j]));
511
918
  const internal = coefUnit.map((c, j) => ldexp(c, expo[j]));
512
- const variance = varUnit.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j])));
919
+ const variance = varFit.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j] - weightExp)));
513
920
  // 6. output
514
921
  const coefficients = internal.slice();
515
922
  if (iterMax > 0 && Math.abs(rank) < p) {
@@ -517,31 +924,32 @@ export function coxph(time, status, x, options = {}) {
517
924
  if (inverse[j][j] === 0)
518
925
  coefficients[j] = NaN;
519
926
  }
927
+ const lpBeta = start === undefined ? internal : internal.map((v, j) => (Number.isNaN(coefficients[j]) ? 0 : v));
520
928
  let centre = 0;
521
929
  for (let j = 0; j < p; j++)
522
- centre += internal[j] * means[j];
930
+ centre += lpBeta[j] * means[j];
523
931
  const linearPredictors = keep.map((i) => {
524
932
  let s = 0;
525
933
  for (let j = 0; j < p; j++)
526
- s += x[i][j] * internal[j];
934
+ s += x[i][j] * lpBeta[j];
527
935
  return s - centre;
528
936
  });
529
- const warnings = new Warnings();
530
937
  if (iterMax > 1) {
531
938
  // abs(u' var) in units of 2^-e_j
532
- const infinity = varUnit.map((_, j) => {
939
+ const infinity = varFit.map((_, j) => {
533
940
  let s = 0;
534
941
  for (let i = 0; i < p; i++)
535
- s += uUnit[i] * varUnit[i][j];
942
+ s += uUnit[i] * varFit[i][j];
536
943
  return Math.abs(s);
537
944
  });
538
945
  if (ranOut) {
539
- warnings.add("Ran out of iterations and did not converge");
540
- if (maxOf(linearPredictors) > 500 || infinity.some((f) => !Number.isFinite(f))) {
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)))) {
541
949
  warnings.add("one or more coefficients may be infinite");
542
950
  }
543
951
  }
544
- else {
952
+ else if (start === undefined) {
545
953
  const flagged = [];
546
954
  for (let j = 0; j < p; j++) {
547
955
  const f = infinity[j];
@@ -549,46 +957,170 @@ export function coxph(time, status, x, options = {}) {
549
957
  flagged.push(j + 1);
550
958
  }
551
959
  if (flagged.length > 0) {
552
- warnings.add(`Loglik converged before variable ${flagged.join(",")} ; coefficient may be infinite. `);
960
+ warnings.add("Loglik converged before variable " + flagged.join(",") + " ; coefficient may be infinite. ");
553
961
  }
554
962
  }
555
963
  }
556
- // 7. tests and the summary
964
+ // 7. the robust variance (oracle/robust-behaviour.md 5.3, 5.4; Lin and Wei 1989; Therneau and Grambsch 2000,
965
+ // chapter 7), skipped (as R) when every coefficient is NaN. Formed in the units of 2^e_j as the naive variance: a
966
+ // score residual in those units is the scaled one divided by the mantissa of the scale (as the score above)
557
967
  const used = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
558
968
  const k = used.length;
969
+ // (robustUnit 2^-2 dfExp in units of 2^(e_i + e_j))
970
+ let robustUnit;
971
+ let dfExp = 0;
972
+ let rscore = 0;
973
+ let residuals;
974
+ if (useRobust && k > 0) {
975
+ // the cluster of each sorted observation (each its own without a cluster); numeric labels as R's factor()
976
+ let clusterOf = order.map((_, r) => r);
977
+ let nClusters = n;
978
+ const clusterLabels = cluster ?? (start === undefined ? undefined : id);
979
+ if (clusterLabels !== undefined) {
980
+ const cl = numberLevels(clusterLabels);
981
+ const index = new Map();
982
+ clusterOf = order.map((kk) => {
983
+ const label = cl[keep[kk]];
984
+ let c = index.get(label);
985
+ if (c === undefined) {
986
+ c = index.size;
987
+ index.set(label, c);
988
+ }
989
+ return c;
990
+ });
991
+ nClusters = index.size;
992
+ }
993
+ // R fails here with an unrelated message ("(subscript) logical subscript too long")
994
+ if (nClusters < 2)
995
+ throw new RangeError(start === undefined ? "at least two clusters are needed for the robust variance" : "(subscript) logical subscript too long");
996
+ const toUnit = (rows) => rows.map((row) => row.map((v, j) => v / mant[j]));
997
+ // dfbeta_j = w_j s_j' V_naive (V_naive with zero rows and columns for NaN coefficients), summed by cluster
998
+ const sUnit = toUnit(start === undefined ? scoreResiduals(data, beta, efron) : scoreResidualsCounting(data, beta, efron));
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
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
1001
+ // 1e300 among weights 1, whose units 2^e_j are then about 1e300 too), where the plain product underflowed to 0
1002
+ const sv = sUnit.map((s) => varFit.map((_, l) => {
1003
+ let v = 0;
1004
+ for (let i = 0; i < p; i++)
1005
+ v += s[i] * varFit[i][l];
1006
+ return v;
1007
+ }));
1008
+ let dfbeta;
1009
+ if (weightExp === 0)
1010
+ dfbeta = sv.map((row, r) => row.map((v) => fitW[r] * v));
1011
+ else {
1012
+ const exponent = (v) => (v === 0 || !Number.isFinite(v) ? 0 : Math.floor(Math.log2(Math.abs(v))));
1013
+ let top = -Infinity;
1014
+ sv.forEach((row, r) => row.forEach((v) => v !== 0 && Number.isFinite(v) && (top = Math.max(top, exponent(fitW[r]) + exponent(v)))));
1015
+ dfExp = top === -Infinity ? 0 : -top;
1016
+ dfbeta = sv.map((row, r) => {
1017
+ const ew = exponent(fitW[r]);
1018
+ return row.map((v) => {
1019
+ const ev = exponent(v);
1020
+ return ldexp(ldexp(fitW[r], -ew) * ldexp(v, -ev), ew + ev + dfExp);
1021
+ });
1022
+ });
1023
+ }
1024
+ const clusterSums = (rows) => {
1025
+ const sums = Array.from({ length: nClusters }, () => new Array(p).fill(0));
1026
+ rows.forEach((row, r) => {
1027
+ const sum = sums[clusterOf[r]];
1028
+ for (let i = 0; i < p; i++)
1029
+ sum[i] += row[i];
1030
+ });
1031
+ return sums;
1032
+ };
1033
+ const crossProduct = (rows) => {
1034
+ const m = Array.from({ length: p }, () => new Array(p).fill(0));
1035
+ for (const row of rows)
1036
+ for (let i = 0; i < p; i++)
1037
+ for (let j = 0; j < p; j++)
1038
+ m[i][j] += row[i] * row[j];
1039
+ return m;
1040
+ };
1041
+ robustUnit = crossProduct(clusterSums(dfbeta));
1042
+ // the robust score test at init (0 without it): T_c = the cluster sums of w_j s_j(init), u = sum_c T_c,
1043
+ // rscore = u' (sum_c T_c T_c')^- u by the generalised Cholesky factorisation (over all p columns, as R). rscore
1044
+ // does not depend on the scale of the weights, and u u' and T_c T_c' scale as its square (overflowing or
1045
+ // underflowing for weights around 2^+-512): T_c is formed from the weights in units of a power of 2 (exact)
1046
+ const wUnit = scaleToUnit([sortedW]).groups[0];
1047
+ const beta0 = init === undefined ? new Array(p).fill(0) : init.map((v, j) => ldexp(v / scales[j], shift[j]));
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)));
1050
+ const u = new Array(p).fill(0);
1051
+ for (const row of t)
1052
+ for (let i = 0; i < p; i++)
1053
+ u[i] += row[i];
1054
+ const sMatrix = crossProduct(t);
1055
+ if (p === 1) {
1056
+ rscore = (u[0] * u[0]) / sMatrix[0][0];
1057
+ }
1058
+ else {
1059
+ cholFactor(sMatrix, tolerChol);
1060
+ const y = cholSolve(sMatrix, u);
1061
+ for (let i = 0; i < p; i++)
1062
+ rscore += u[i] * y[i];
1063
+ }
1064
+ // the residuals in the original units and the input order
1065
+ const scoreOut = new Array(n);
1066
+ const dfbetaOut = new Array(n);
1067
+ order.forEach((kk, r) => {
1068
+ scoreOut[kk] = sUnit[r].map((v, j) => ldexp(v, -expo[j]));
1069
+ dfbetaOut[kk] = dfbeta[r].map((v, j) => ldexp(v, expo[j] - dfExp));
1070
+ });
1071
+ residuals = { scoreResiduals: scoreOut, dfbeta: dfbetaOut };
1072
+ }
1073
+ const usedRobust = robustUnit !== undefined;
1074
+ // the variance of z, p, the intervals and the Wald test: the robust one when used (the se stays the naive one, as R),
1075
+ // as testUnit 2^testExp
1076
+ const testUnit = robustUnit ?? varFit;
1077
+ const testExp = robustUnit === undefined ? -weightExp : -2 * dfExp;
1078
+ // 8. tests and the summary
559
1079
  // (in units of 2^e_j)
560
1080
  const b = used.map((j) => coefUnit[j] - (init === undefined ? 0 : ldexp(init[j], -expo[j])));
561
1081
  let wald = 0;
562
1082
  if (k === 1) {
563
- wald = (b[0] * b[0]) / varUnit[used[0]][used[0]];
1083
+ wald = (b[0] * b[0]) / testUnit[used[0]][used[0]];
564
1084
  }
565
1085
  else if (k > 1) {
566
- const v = used.map((i) => used.map((j) => varUnit[i][j]));
1086
+ const v = used.map((i) => used.map((j) => testUnit[i][j]));
567
1087
  cholFactor(v, tolerChol);
568
1088
  const y = cholSolve(v, b);
569
1089
  for (let i = 0; i < k; i++)
570
1090
  wald += b[i] * y[i];
571
1091
  }
1092
+ wald = ldexp(wald, -testExp);
572
1093
  // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
573
1094
  const a2 = (1 - confLevel) / 2;
574
1095
  const q = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2);
575
- const seUnit = varUnit.map((row, j) => Math.sqrt(row[j]));
576
- const se = seUnit.map((v, j) => ldexp(v, expo[j]));
577
- const z = coefficients.map((c, j) => (Number.isNaN(c) ? c : coefUnit[j]) / seUnit[j]);
1096
+ // the standard errors of a variance vUnit 2^t in units of 2^e_j: sqrt(vUnit 2^(t - 2h)) 2^h, h = floor(t / 2)
1097
+ const seOf = (vUnit, t) => {
1098
+ const h = Math.floor(t / 2);
1099
+ const unit = vUnit.map((row, j) => Math.sqrt(ldexp(row[j], t - 2 * h)));
1100
+ return { unit, h, se: unit.map((v, j) => ldexp(v, expo[j] + h)) };
1101
+ };
1102
+ const se = seOf(varFit, -weightExp).se;
1103
+ const { unit: testSeUnit, h: testH, se: testSe } = seOf(testUnit, testExp);
1104
+ const z = coefficients.map((c, j) => ldexp((Number.isNaN(c) ? c : coefUnit[j]) / testSeUnit[j], -testH));
578
1105
  const pz = z.map((v) => pchisq(v * v, 1, { lowerTail: false }));
579
- const lower = coefficients.map((c, j) => Math.exp(c - q * se[j]));
580
- const upper = coefficients.map((c, j) => Math.exp(c + q * se[j]));
581
- const lr = -2 * (loglik[0] - loglik[1]);
582
- return reported("coxph", {
1106
+ const lower = coefficients.map((c, j) => Math.exp(c - q * testSe[j]));
1107
+ const upper = coefficients.map((c, j) => Math.exp(c + q * testSe[j]));
1108
+ // (the log likelihoods and the score test of the weights divided by 2^c times 2^c; the difference first)
1109
+ const lr = ldexp(-2 * (loglik[0] - loglik[1]), weightExp);
1110
+ const loglikOut = [ldexp(loglik[0], weightExp), ldexp(loglik[1], weightExp)];
1111
+ const scoreTestOut = ldexp(scoreTest, weightExp);
1112
+ const robustVariance = robustUnit?.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j] - 2 * dfExp)));
1113
+ const result = {
583
1114
  coefficients,
584
- var: variance,
585
- loglik,
586
- score: scoreTest,
1115
+ var: robustVariance ?? variance,
1116
+ loglik: loglikOut,
1117
+ score: scoreTestOut,
587
1118
  wald,
588
1119
  iter,
589
1120
  means,
590
1121
  n,
591
1122
  nevent,
1123
+ ...(idLevels === undefined ? {} : { nId: new Set(keep.map((i) => idLevels[i])).size }),
592
1124
  linearPredictors,
593
1125
  se,
594
1126
  z,
@@ -599,9 +1131,46 @@ export function coxph(time, status, x, options = {}) {
599
1131
  lower,
600
1132
  upper,
601
1133
  logtest: chisqTest(lr, k),
602
- sctest: chisqTest(scoreTest, k),
1134
+ sctest: chisqTest(scoreTestOut, k),
603
1135
  waldtest: chisqTest(wald, k),
604
- rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglik[0]) / n) },
1136
+ rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglikOut[0]) / n) },
1137
+ usedRobust,
1138
+ ...(usedRobust ? { naiveVar: variance, robustSe: testSe, rscore, robscore: chisqTest(rscore, k) } : {}),
605
1139
  warnings: warnings.list,
1140
+ };
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
+ },
606
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 };
607
1176
  }