@numero-uno-jpn/rstats 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.ja.md +27 -10
  3. package/README.md +26 -9
  4. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-L23RSC2N.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-IAWXF73N.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-BNTBZ5W3.js} +2 -2
  10. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-73LNRWU3.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-VERBXW6E.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-P7ZHH2SF.js} +2 -2
  23. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-T5DRIITM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7INBXTVV.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-BKV3FINA.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +9 -0
  33. package/dist/entries/tests.js +9 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/blandAltman.d.ts +100 -0
  36. package/dist/htest/blandAltman.js +159 -0
  37. package/dist/htest/diagnosticTests.d.ts +91 -0
  38. package/dist/htest/diagnosticTests.js +116 -0
  39. package/dist/htest/iccPsych.d.ts +106 -0
  40. package/dist/htest/iccPsych.js +332 -0
  41. package/dist/htest/ksTest.d.ts +1 -1
  42. package/dist/htest/mcreg.d.ts +209 -0
  43. package/dist/htest/mcreg.js +735 -0
  44. package/dist/htest/roc.d.ts +287 -0
  45. package/dist/htest/roc.js +635 -0
  46. package/dist/htest/rocTest.d.ts +139 -0
  47. package/dist/htest/rocTest.js +444 -0
  48. package/dist/htest/tTOST.d.ts +202 -0
  49. package/dist/htest/tTOST.js +558 -0
  50. package/dist/htest/trendTests.d.ts +1 -1
  51. package/dist/htest/trendTests.js +1 -1
  52. package/dist/internal/summary.js +5 -0
  53. package/dist/linalg/qr.d.ts +3 -0
  54. package/dist/linalg/qr.js +3 -0
  55. package/dist/linalg.js +2 -2
  56. package/dist/mixed.js +2 -2
  57. package/dist/models/coeftest.d.ts +139 -0
  58. package/dist/models/coeftest.js +237 -0
  59. package/dist/models/coxph.d.ts +60 -9
  60. package/dist/models/coxph.js +367 -38
  61. package/dist/models/glm.d.ts +11 -1
  62. package/dist/models/glm.js +19 -2
  63. package/dist/models/inputRows.d.ts +10 -0
  64. package/dist/models/inputRows.js +23 -0
  65. package/dist/models/lm.d.ts +8 -0
  66. package/dist/models/lm.js +14 -2
  67. package/dist/models/sandwich.d.ts +177 -0
  68. package/dist/models/sandwich.js +923 -0
  69. package/dist/numerics.js +2 -2
  70. package/dist/random/rng.d.ts +8 -1
  71. package/dist/random/rng.js +14 -1
  72. package/dist/rstats.js +16 -16
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +13 -13
  75. package/llms.txt +17 -0
  76. package/package.json +1 -1
  77. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  78. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -9,6 +9,12 @@
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
11
  // (R's NA) coefficients.
12
+ //
13
+ // The robust variance (survival's `robust = TRUE` or `cluster`) is the Lin-Wei sandwich, written from section 5 of
14
+ // oracle/robust-behaviour.md and Lin and Wei (1989), "The robust inference for the Cox proportional hazards model",
15
+ // JASA 84, 1074-1078; Therneau and Grambsch (2000), "Modeling Survival Data: Extending the Cox Model", Springer,
16
+ // chapters 4 (score residuals, Efron's weighting of tied deaths) and 7 (dfbeta residuals, clustering, the robust score
17
+ // test).
12
18
  import { pchisq } from "../distributions/chisq.js";
13
19
  import { qnorm } from "../distributions/normal.js";
14
20
  import { numberLevels } from "../internal/levels.js";
@@ -18,14 +24,19 @@ import { reported, Warnings } from "../internal/warnings.js";
18
24
  import { maxOf } from "../internal/extremes.js";
19
25
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
26
  import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
21
- const COXPH_KEYS = ["ties", "weights", "strata", "init", "control", "nocenter", "confLevel"];
27
+ const COXPH_KEYS = /* @__PURE__ */ new Set([
28
+ "ties", "weights", "strata", "init", "control", "nocenter", "confLevel", "robust", "cluster",
29
+ ]);
22
30
  const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf"];
23
31
  const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
24
32
  const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
33
+ /** The weights from which the fit runs on weights divided by a power of 2 (see SortedData.logUnit) */
34
+ const WEIGHT_LIMIT = 2 ** 64;
35
+ const MIN_NORMAL = 2 ** -1022;
25
36
  /** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
26
37
  const SHIFT_LIMIT = 700;
27
38
  function evaluate(data, beta, efron) {
28
- const { time, event, weight, x, stratumEnd } = data;
39
+ const { time, event, weight, x, stratumEnd, logUnit } = data;
29
40
  const n = time.length;
30
41
  const p = beta.length;
31
42
  const zeros = () => new Array(p).fill(0);
@@ -115,7 +126,8 @@ function evaluate(data, beta, efron) {
115
126
  const stepWeight = deathWeight / steps;
116
127
  for (let s = 0; s < steps; s++) {
117
128
  riskSum += efron ? deathRisk / share : deathRisk;
118
- loglik -= stepWeight * (Math.log(riskSum) + shift);
129
+ // (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)
130
+ loglik -= stepWeight * (Math.log(riskSum) + shift + logUnit);
119
131
  for (let i = 0; i < p; i++) {
120
132
  riskX[i] += efron ? deathX[i] / share : deathX[i];
121
133
  const mean = riskX[i] / riskSum;
@@ -125,7 +137,15 @@ function evaluate(data, beta, efron) {
125
137
  const irow = info[i];
126
138
  for (let l = 0; l <= i; l++) {
127
139
  row[l] += efron ? drow[l] / share : drow[l];
128
- irow[l] += (stepWeight * (row[l] - mean * riskX[l])) / riskSum;
140
+ const dev = row[l] - mean * riskX[l];
141
+ const term = stepWeight * dev;
142
+ // stepWeight and dev both carry the scale of the weights, so the product leaves the doubles for weights
143
+ // around 2^+-512 although the term does not: there (only) the quotient first, which does not change the
144
+ // bits of the ordinary case
145
+ irow[l] +=
146
+ (term < Infinity && term > -Infinity && (Math.abs(term) >= MIN_NORMAL || dev === 0)) || !Number.isFinite(stepWeight)
147
+ ? term / riskSum
148
+ : stepWeight * (dev / riskSum);
129
149
  }
130
150
  }
131
151
  }
@@ -140,6 +160,149 @@ function evaluate(data, beta, efron) {
140
160
  info[l][i] = info[i][l];
141
161
  return { loglik, score, info };
142
162
  }
163
+ /**
164
+ * The (unweighted) score residuals of every observation at the coefficients `beta`, in the units of `data.x` and the
165
+ * sorted order (oracle/robust-behaviour.md 5.2; Therneau and Grambsch 2000, section 4.6). For each event time t of a
166
+ * 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
167
+ * 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
168
+ * S0 - f E0, the mean xbar_m = (S1 - f E1) / (S0 - f E0) and the hazard increment lambda_m = (dw / M) / (S0 - f E0).
169
+ * An observation j at risk but not dying at t gets -r_j sum_m lambda_m (x_j - xbar_m); a death gets
170
+ * sum_m [(x_j - xbar_m) / M - (1 - f) r_j lambda_m (x_j - xbar_m)]. The increments of the times before an
171
+ * observation's own are accumulated forward in time (C0 = sum lambda, C1 = sum lambda xbar), so that each residual
172
+ * costs O(p) and not O(n p). Sum_j w_j s_j is the score vector.
173
+ *
174
+ * Each risk set is shifted by its own largest linear predictor M (as evaluate shifts the risk sums): S0 and S1 of a
175
+ * 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
176
+ * stratum's largest linear predictor alone made every r of the later risk sets 0 once the linear predictors spanned
177
+ * more than about 745 (an early death with a large one): S0 = 0 and the residuals NaN. M does not increase forward in
178
+ * time, so the rescaling factors of C0 and C1 are at most 1 and only the negligible early terms can underflow. The
179
+ * residuals do not depend on the scale of the weights, which are therefore taken in units of a power of 2 (exact)
180
+ */
181
+ function scoreResiduals(data, beta, efron) {
182
+ const { time, event, x, stratumEnd } = data;
183
+ const weight = scaleToUnit([data.weight]).groups[0];
184
+ const n = time.length;
185
+ const p = beta.length;
186
+ const out = Array.from({ length: n }, () => new Array(p).fill(0));
187
+ const etaOf = (j) => {
188
+ let e = 0;
189
+ for (let i = 0; i < p; i++)
190
+ e += beta[i] * x[j][i];
191
+ return e;
192
+ };
193
+ for (let start = 0; start < n;) {
194
+ let end = start;
195
+ while (!stratumEnd[end])
196
+ end++;
197
+ const eta = [];
198
+ for (let j = start; j <= end; j++)
199
+ eta.push(etaOf(j));
200
+ // the first row of each group of tied times, and the risk sums at it (accumulated from the end of the stratum) in
201
+ // units of e^-shift[g], shift[g] the largest linear predictor of the risk set (0 if it is not finite)
202
+ const groupStart = [];
203
+ for (let j = start; j <= end; j++)
204
+ if (j === start || time[j] !== time[j - 1])
205
+ groupStart.push(j);
206
+ const groupEnd = (g) => (g + 1 < groupStart.length ? groupStart[g + 1] : end + 1);
207
+ const riskSum = new Array(groupStart.length);
208
+ const riskX = new Array(groupStart.length);
209
+ const shift = new Array(groupStart.length);
210
+ let top = -Infinity;
211
+ let s0 = 0;
212
+ const s1 = new Array(p).fill(0);
213
+ for (let g = groupStart.length - 1; g >= 0; g--) {
214
+ const before = Number.isFinite(top) ? top : 0;
215
+ for (let j = groupStart[g]; j < groupEnd(g); j++)
216
+ top = Math.max(top, eta[j - start]);
217
+ const m = Number.isFinite(top) ? top : 0;
218
+ // (nothing to rescale at the last time, where `before` is only a placeholder)
219
+ if (g < groupStart.length - 1 && m !== before) {
220
+ const f = Math.exp(before - m);
221
+ s0 *= f;
222
+ for (let i = 0; i < p; i++)
223
+ s1[i] *= f;
224
+ }
225
+ for (let j = groupStart[g]; j < groupEnd(g); j++) {
226
+ const wr = weight[j] * Math.exp(eta[j - start] - m);
227
+ s0 += wr;
228
+ for (let i = 0; i < p; i++)
229
+ s1[i] += wr * x[j][i];
230
+ }
231
+ riskSum[g] = s0;
232
+ riskX[g] = s1.slice();
233
+ shift[g] = m;
234
+ }
235
+ // C0 = sum lambda and C1 = sum lambda xbar over the earlier event times, in units of e^-shift[g]
236
+ let c0 = 0;
237
+ const c1 = new Array(p).fill(0);
238
+ for (let g = 0; g < groupStart.length; g++) {
239
+ const m = shift[g];
240
+ if (g > 0 && m !== shift[g - 1]) {
241
+ const f = Math.exp(m - shift[g - 1]);
242
+ c0 *= f;
243
+ for (let i = 0; i < p; i++)
244
+ c1[i] *= f;
245
+ }
246
+ const from = groupStart[g];
247
+ const to = groupEnd(g);
248
+ // r_j in units of e^shift[g] (eta_j <= shift[g] for every j at risk)
249
+ const r = [];
250
+ for (let j = from; j < to; j++)
251
+ r.push(Math.exp(eta[j - start] - m));
252
+ let d = 0;
253
+ let dw = 0;
254
+ let e0 = 0;
255
+ const e1 = new Array(p).fill(0);
256
+ for (let j = from; j < to; j++) {
257
+ if (!event[j])
258
+ continue;
259
+ const wr = weight[j] * r[j - from];
260
+ d++;
261
+ dw += weight[j];
262
+ e0 += wr;
263
+ for (let i = 0; i < p; i++)
264
+ e1[i] += wr * x[j][i];
265
+ }
266
+ // the part of the earlier event times: -r_j (x_j C0 - C1)
267
+ for (let j = from; j < to; j++) {
268
+ const rj = r[j - from];
269
+ const xj = x[j];
270
+ const sj = out[j];
271
+ for (let i = 0; i < p; i++)
272
+ sj[i] = -rj * (xj[i] * c0 - c1[i]);
273
+ }
274
+ if (d === 0)
275
+ continue;
276
+ const steps = efron ? d : 1;
277
+ for (let k = 0; k < steps; k++) {
278
+ const f = k / steps;
279
+ const s0m = riskSum[g] - f * e0;
280
+ const xbar = riskX[g].map((v, i) => (v - f * e1[i]) / s0m);
281
+ const lambda = dw / steps / s0m;
282
+ for (let j = from; j < to; j++) {
283
+ const rj = r[j - from];
284
+ const xj = x[j];
285
+ const sj = out[j];
286
+ if (event[j]) {
287
+ for (let i = 0; i < p; i++) {
288
+ const dx = xj[i] - xbar[i];
289
+ sj[i] += dx / steps - (1 - f) * rj * dx * lambda;
290
+ }
291
+ }
292
+ else {
293
+ for (let i = 0; i < p; i++)
294
+ sj[i] -= rj * (xj[i] - xbar[i]) * lambda;
295
+ }
296
+ }
297
+ c0 += lambda;
298
+ for (let i = 0; i < p; i++)
299
+ c1[i] += lambda * xbar[i];
300
+ }
301
+ }
302
+ start = end + 1;
303
+ }
304
+ return out;
305
+ }
143
306
  /**
144
307
  * Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
145
308
  * set to 0. Returns the rank (negative when M is not non-negative definite).
@@ -245,7 +408,7 @@ const chisqTest = (statistic, df) => ({
245
408
  pValue: pchisq(statistic, df, { lowerTail: false }),
246
409
  });
247
410
  /** R's result for data without events (survival's coxph returns it before fitting), with summary(fit)'s values */
248
- function zeroEventResult(rows, p) {
411
+ function zeroEventResult(rows, p, warnings) {
249
412
  const n = rows.length;
250
413
  const nans = () => new Array(p).fill(NaN);
251
414
  const test = chisqTest(0, 0);
@@ -275,13 +438,21 @@ function zeroEventResult(rows, p) {
275
438
  sctest: { ...test },
276
439
  waldtest: { ...test },
277
440
  rsq: { rsq: 0, maxrsq: 0 },
278
- warnings: [],
441
+ usedRobust: false,
442
+ warnings,
279
443
  };
280
444
  }
281
445
  /**
282
446
  * 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)`.
447
+ * `coxph(Surv(time, status) ~ x [+ strata(strata)], weights, ties, init, robust, cluster, control)` for right-censored
448
+ * data, with the values of `summary(fit)`.
449
+ *
450
+ * With `robust` (by default when `cluster` is given or a case weight is not an integer) the variance is the robust
451
+ * (Lin-Wei sandwich) one, summed over the clusters (each observation its own cluster without `cluster`), as R:
452
+ * `var` is the robust variance and `naiveVar` the model-based one; `se` (and `stdError`) stay the model-based standard
453
+ * errors (R's `se(coef)`), while `z`, `p`, the intervals `lower`/`upper`, `wald` and `waldtest` use the robust ones
454
+ * (`robustSe`); `robscore` is the robust score test at `init`. The likelihood ratio and score tests and the R^2 ignore
455
+ * the clustering.
285
456
  *
286
457
  * Rows with a missing time, status, covariate, weight or stratum are dropped. Times within sqrt(eps) of each other are
287
458
  * treated as tied. Covariates whose values all lie in `nocenter` are not centred; the others are centred by their
@@ -292,6 +463,8 @@ function zeroEventResult(rows, p) {
292
463
  * @param status 1 for an event, 0 for a censored time.
293
464
  * @param x The covariate matrix, one row per observation (at least one column).
294
465
  * @param options See {@link CoxphOptions}.
466
+ * @throws TypeError if `robust` is not a boolean. RangeError for invalid arguments, among them an infinite weight
467
+ * and a robust variance with fewer than two clusters.
295
468
  *
296
469
  * @example
297
470
  * ```ts
@@ -305,7 +478,17 @@ function zeroEventResult(rows, p) {
305
478
  export function coxph(time, status, x, options = {}) {
306
479
  checkOptions(options, COXPH_KEYS, "coxph"); // generated: option-keys.mjs
307
480
  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;
481
+ return reported("coxph", fitCoxph(time, status, x, options).result);
482
+ }
483
+ /**
484
+ * The fit of {@link coxph}, and with the robust variance also the residuals it was made from (for the tests; not
485
+ * exported from the package): R's `residuals(fit, type = "score")` (unweighted) and `residuals(fit, type =
486
+ * "dfbeta")` (weighted), one row per observation used, in input order.
487
+ *
488
+ * @internal
489
+ */
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;
309
492
  const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
310
493
  const tolerInf = control.tolerInf ?? Math.sqrt(eps);
311
494
  if (ties !== "efron" && ties !== "breslow")
@@ -327,6 +510,10 @@ export function coxph(time, status, x, options = {}) {
327
510
  throw new RangeError("'weights' must have the same length as 'time'");
328
511
  if (strata !== undefined && strata.length !== nIn)
329
512
  throw new RangeError("'strata' must have the same length as 'time'");
513
+ if (cluster !== undefined && cluster.length !== nIn)
514
+ throw new RangeError("'cluster' must have the same length as 'time'");
515
+ if (robust !== undefined && typeof robust !== "boolean")
516
+ throw new TypeError("'robust' must be true or false");
330
517
  const p = nIn === 0 ? 0 : x[0].length;
331
518
  if (p < 1)
332
519
  throw new RangeError("'x' must have at least one column");
@@ -345,6 +532,8 @@ export function coxph(time, status, x, options = {}) {
345
532
  continue;
346
533
  if (strata !== undefined && isMissingLabel(strata[i]))
347
534
  continue;
535
+ if (cluster !== undefined && isMissingLabel(cluster[i]))
536
+ continue;
348
537
  const s = status[i];
349
538
  if (s !== 0 && s !== 1)
350
539
  throw new RangeError("'status' must be 0 (censored) or 1 (event)");
@@ -362,8 +551,15 @@ export function coxph(time, status, x, options = {}) {
362
551
  const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
363
552
  if (w.some((v) => !(v > 0)))
364
553
  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");
554
+ // an infinite weight passes R's check (> 0) and counts as an integer there; the fit cannot use it (the sums become
555
+ // Inf or NaN: NaN coefficients and a misleading "coefficient may be infinite" before this check)
556
+ if (w.some((v) => v === Infinity))
557
+ throw new RangeError("'weights' must be finite");
558
+ const warnings = new Warnings();
559
+ // R's default: the robust variance with a cluster or a weight that is not an integer (silently)
560
+ const useRobust = robust ?? (cluster !== undefined || w.some((v) => !Number.isInteger(v)));
561
+ if (cluster !== undefined && !useRobust)
562
+ warnings.add("cluster specified with robust=FALSE, cluster ignored");
367
563
  let nevent = 0;
368
564
  for (const i of keep)
369
565
  nevent += status[i];
@@ -371,7 +567,7 @@ export function coxph(time, status, x, options = {}) {
371
567
  // score, Wald statistic and iterations, and the unweighted column means of all covariates (nocenter ignored); `init`
372
568
  // is not an estimate here
373
569
  if (nevent === 0)
374
- return zeroEventResult(keep.map((i) => x[i]), p);
570
+ return { result: zeroEventResult(keep.map((i) => x[i]), p, warnings.list) };
375
571
  const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
376
572
  let stratumOf = new Array(n).fill(0);
377
573
  if (strata !== undefined) {
@@ -384,10 +580,17 @@ export function coxph(time, status, x, options = {}) {
384
580
  }
385
581
  const order = Array.from({ length: n }, (_, k) => k).sort((a, b) => stratumOf[a] - stratumOf[b] || mergedTime[a] - mergedTime[b] || a - b);
386
582
  // 2. centring and scaling (sums over the sorted observations)
583
+ const sortedW = order.map((k) => w[k]);
584
+ // weights of 2^64 or more (to the top of the doubles: the risk sums, w eta and the log likelihood overflowed, giving
585
+ // a coefficient 0 or NaN): the fit runs on the weights divided by 2^c, c the exponent of the largest, which leaves the
586
+ // coefficients, the means and the score residuals as they are and divides the log likelihood (after the term W c log 2,
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)
589
+ const { groups: unitW, k: weightExp } = maxOf(sortedW) >= WEIGHT_LIMIT ? scaleToUnit([sortedW]) : { groups: [sortedW], k: 0 };
590
+ const fitW = unitW[0];
387
591
  let totalWeight = 0;
388
592
  for (const v of w)
389
- totalWeight += v;
390
- const sortedW = order.map((k) => w[k]);
593
+ totalWeight += weightExp === 0 ? v : ldexp(v, -weightExp);
391
594
  const xs = order.map((k) => x[keep[k]].slice());
392
595
  const means = new Array(p).fill(0);
393
596
  // the scale of column j is scales[j] 2^-shift[j]
@@ -401,11 +604,11 @@ export function coxph(time, status, x, options = {}) {
401
604
  const centreScale = (col) => {
402
605
  let sum = 0;
403
606
  for (let k = 0; k < n; k++)
404
- sum += sortedW[k] * col[k];
607
+ sum += fitW[k] * col[k];
405
608
  const m = sum / totalWeight;
406
609
  let absSum = 0;
407
610
  const d = col.map((v, k) => {
408
- absSum += sortedW[k] * Math.abs(v - m);
611
+ absSum += fitW[k] * Math.abs(v - m);
409
612
  return v - m;
410
613
  });
411
614
  const s = absSum === 0 ? 1 : totalWeight / absSum;
@@ -427,9 +630,10 @@ export function coxph(time, status, x, options = {}) {
427
630
  const data = {
428
631
  time: order.map((k) => mergedTime[k]),
429
632
  event: order.map((k) => status[keep[k]] === 1),
430
- weight: sortedW,
633
+ weight: fitW,
431
634
  x: xs,
432
635
  stratumEnd: order.map((k, r) => r === n - 1 || stratumOf[order[r + 1]] !== stratumOf[k]),
636
+ logUnit: weightExp * Math.LN2,
433
637
  };
434
638
  const efron = ties === "efron";
435
639
  // 3.-5. Newton-Raphson on the scaled coefficients
@@ -506,10 +710,12 @@ export function coxph(time, status, x, options = {}) {
506
710
  const mant = scales.map((s, j) => ldexp(s, -scaleExpo[j]));
507
711
  const expo = scaleExpo.map((e, j) => e - shift[j]);
508
712
  const coefUnit = beta.map((b, j) => b * mant[j]);
713
+ // (the score and the variance of the weights divided by 2^c: the fit's variance is 2^-c varFit, which is kept apart,
714
+ // 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
715
  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]));
716
+ const varFit = inverse.map((row, i) => row.map((v, j) => v * mant[i] * mant[j]));
511
717
  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])));
718
+ const variance = varFit.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j] - weightExp)));
513
719
  // 6. output
514
720
  const coefficients = internal.slice();
515
721
  if (iterMax > 0 && Math.abs(rank) < p) {
@@ -526,13 +732,12 @@ export function coxph(time, status, x, options = {}) {
526
732
  s += x[i][j] * internal[j];
527
733
  return s - centre;
528
734
  });
529
- const warnings = new Warnings();
530
735
  if (iterMax > 1) {
531
736
  // abs(u' var) in units of 2^-e_j
532
- const infinity = varUnit.map((_, j) => {
737
+ const infinity = varFit.map((_, j) => {
533
738
  let s = 0;
534
739
  for (let i = 0; i < p; i++)
535
- s += uUnit[i] * varUnit[i][j];
740
+ s += uUnit[i] * varFit[i][j];
536
741
  return Math.abs(s);
537
742
  });
538
743
  if (ranOut) {
@@ -553,37 +758,158 @@ export function coxph(time, status, x, options = {}) {
553
758
  }
554
759
  }
555
760
  }
556
- // 7. tests and the summary
761
+ // 7. the robust variance (oracle/robust-behaviour.md 5.3, 5.4; Lin and Wei 1989; Therneau and Grambsch 2000,
762
+ // chapter 7), skipped (as R) when every coefficient is NaN. Formed in the units of 2^e_j as the naive variance: a
763
+ // score residual in those units is the scaled one divided by the mantissa of the scale (as the score above)
557
764
  const used = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
558
765
  const k = used.length;
766
+ // (robustUnit 2^-2 dfExp in units of 2^(e_i + e_j))
767
+ let robustUnit;
768
+ let dfExp = 0;
769
+ let rscore = 0;
770
+ let residuals;
771
+ if (useRobust && k > 0) {
772
+ // the cluster of each sorted observation (each its own without a cluster); numeric labels as R's factor()
773
+ let clusterOf = order.map((_, r) => r);
774
+ let nClusters = n;
775
+ if (cluster !== undefined) {
776
+ const cl = numberLevels(cluster);
777
+ const index = new Map();
778
+ clusterOf = order.map((kk) => {
779
+ const label = cl[keep[kk]];
780
+ let c = index.get(label);
781
+ if (c === undefined) {
782
+ c = index.size;
783
+ index.set(label, c);
784
+ }
785
+ return c;
786
+ });
787
+ nClusters = index.size;
788
+ }
789
+ // R fails here with an unrelated message ("(subscript) logical subscript too long")
790
+ if (nClusters < 2)
791
+ throw new RangeError("at least two clusters are needed for the robust variance");
792
+ const toUnit = (rows) => rows.map((row) => row.map((v, j) => v / mant[j]));
793
+ // 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));
795
+ // (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
+ // 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
+ // 1e300 among weights 1, whose units 2^e_j are then about 1e300 too), where the plain product underflowed to 0
798
+ const sv = sUnit.map((s) => varFit.map((_, l) => {
799
+ let v = 0;
800
+ for (let i = 0; i < p; i++)
801
+ v += s[i] * varFit[i][l];
802
+ return v;
803
+ }));
804
+ let dfbeta;
805
+ if (weightExp === 0)
806
+ dfbeta = sv.map((row, r) => row.map((v) => fitW[r] * v));
807
+ else {
808
+ const exponent = (v) => (v === 0 || !Number.isFinite(v) ? 0 : Math.floor(Math.log2(Math.abs(v))));
809
+ let top = -Infinity;
810
+ sv.forEach((row, r) => row.forEach((v) => v !== 0 && Number.isFinite(v) && (top = Math.max(top, exponent(fitW[r]) + exponent(v)))));
811
+ dfExp = top === -Infinity ? 0 : -top;
812
+ dfbeta = sv.map((row, r) => {
813
+ const ew = exponent(fitW[r]);
814
+ return row.map((v) => {
815
+ const ev = exponent(v);
816
+ return ldexp(ldexp(fitW[r], -ew) * ldexp(v, -ev), ew + ev + dfExp);
817
+ });
818
+ });
819
+ }
820
+ const clusterSums = (rows) => {
821
+ const sums = Array.from({ length: nClusters }, () => new Array(p).fill(0));
822
+ rows.forEach((row, r) => {
823
+ const sum = sums[clusterOf[r]];
824
+ for (let i = 0; i < p; i++)
825
+ sum[i] += row[i];
826
+ });
827
+ return sums;
828
+ };
829
+ const crossProduct = (rows) => {
830
+ const m = Array.from({ length: p }, () => new Array(p).fill(0));
831
+ for (const row of rows)
832
+ for (let i = 0; i < p; i++)
833
+ for (let j = 0; j < p; j++)
834
+ m[i][j] += row[i] * row[j];
835
+ return m;
836
+ };
837
+ robustUnit = crossProduct(clusterSums(dfbeta));
838
+ // 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,
839
+ // rscore = u' (sum_c T_c T_c')^- u by the generalised Cholesky factorisation (over all p columns, as R). rscore
840
+ // does not depend on the scale of the weights, and u u' and T_c T_c' scale as its square (overflowing or
841
+ // underflowing for weights around 2^+-512): T_c is formed from the weights in units of a power of 2 (exact)
842
+ const wUnit = scaleToUnit([sortedW]).groups[0];
843
+ const beta0 = init === undefined ? new Array(p).fill(0) : init.map((v, j) => ldexp(v / scales[j], shift[j]));
844
+ const t = clusterSums(toUnit(scoreResiduals(data, beta0, efron)).map((s, r) => s.map((v) => wUnit[r] * v)));
845
+ const u = new Array(p).fill(0);
846
+ for (const row of t)
847
+ for (let i = 0; i < p; i++)
848
+ u[i] += row[i];
849
+ const sMatrix = crossProduct(t);
850
+ if (p === 1) {
851
+ rscore = (u[0] * u[0]) / sMatrix[0][0];
852
+ }
853
+ else {
854
+ cholFactor(sMatrix, tolerChol);
855
+ const y = cholSolve(sMatrix, u);
856
+ for (let i = 0; i < p; i++)
857
+ rscore += u[i] * y[i];
858
+ }
859
+ // the residuals in the original units and the input order
860
+ const scoreOut = new Array(n);
861
+ const dfbetaOut = new Array(n);
862
+ order.forEach((kk, r) => {
863
+ scoreOut[kk] = sUnit[r].map((v, j) => ldexp(v, -expo[j]));
864
+ dfbetaOut[kk] = dfbeta[r].map((v, j) => ldexp(v, expo[j] - dfExp));
865
+ });
866
+ residuals = { scoreResiduals: scoreOut, dfbeta: dfbetaOut };
867
+ }
868
+ const usedRobust = robustUnit !== undefined;
869
+ // the variance of z, p, the intervals and the Wald test: the robust one when used (the se stays the naive one, as R),
870
+ // as testUnit 2^testExp
871
+ const testUnit = robustUnit ?? varFit;
872
+ const testExp = robustUnit === undefined ? -weightExp : -2 * dfExp;
873
+ // 8. tests and the summary
559
874
  // (in units of 2^e_j)
560
875
  const b = used.map((j) => coefUnit[j] - (init === undefined ? 0 : ldexp(init[j], -expo[j])));
561
876
  let wald = 0;
562
877
  if (k === 1) {
563
- wald = (b[0] * b[0]) / varUnit[used[0]][used[0]];
878
+ wald = (b[0] * b[0]) / testUnit[used[0]][used[0]];
564
879
  }
565
880
  else if (k > 1) {
566
- const v = used.map((i) => used.map((j) => varUnit[i][j]));
881
+ const v = used.map((i) => used.map((j) => testUnit[i][j]));
567
882
  cholFactor(v, tolerChol);
568
883
  const y = cholSolve(v, b);
569
884
  for (let i = 0; i < k; i++)
570
885
  wald += b[i] * y[i];
571
886
  }
887
+ wald = ldexp(wald, -testExp);
572
888
  // (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
889
  const a2 = (1 - confLevel) / 2;
574
890
  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]);
891
+ // 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)
892
+ const seOf = (vUnit, t) => {
893
+ const h = Math.floor(t / 2);
894
+ const unit = vUnit.map((row, j) => Math.sqrt(ldexp(row[j], t - 2 * h)));
895
+ return { unit, h, se: unit.map((v, j) => ldexp(v, expo[j] + h)) };
896
+ };
897
+ const se = seOf(varFit, -weightExp).se;
898
+ const { unit: testSeUnit, h: testH, se: testSe } = seOf(testUnit, testExp);
899
+ const z = coefficients.map((c, j) => ldexp((Number.isNaN(c) ? c : coefUnit[j]) / testSeUnit[j], -testH));
578
900
  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", {
901
+ const lower = coefficients.map((c, j) => Math.exp(c - q * testSe[j]));
902
+ const upper = coefficients.map((c, j) => Math.exp(c + q * testSe[j]));
903
+ // (the log likelihoods and the score test of the weights divided by 2^c times 2^c; the difference first)
904
+ const lr = ldexp(-2 * (loglik[0] - loglik[1]), weightExp);
905
+ const loglikOut = [ldexp(loglik[0], weightExp), ldexp(loglik[1], weightExp)];
906
+ const scoreTestOut = ldexp(scoreTest, weightExp);
907
+ const robustVariance = robustUnit?.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j] - 2 * dfExp)));
908
+ const result = {
583
909
  coefficients,
584
- var: variance,
585
- loglik,
586
- score: scoreTest,
910
+ var: robustVariance ?? variance,
911
+ loglik: loglikOut,
912
+ score: scoreTestOut,
587
913
  wald,
588
914
  iter,
589
915
  means,
@@ -599,9 +925,12 @@ export function coxph(time, status, x, options = {}) {
599
925
  lower,
600
926
  upper,
601
927
  logtest: chisqTest(lr, k),
602
- sctest: chisqTest(scoreTest, k),
928
+ sctest: chisqTest(scoreTestOut, k),
603
929
  waldtest: chisqTest(wald, k),
604
- rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglik[0]) / n) },
930
+ rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglikOut[0]) / n) },
931
+ usedRobust,
932
+ ...(usedRobust ? { naiveVar: variance, robustSe: testSe, rscore, robscore: chisqTest(rscore, k) } : {}),
605
933
  warnings: warnings.list,
606
- });
934
+ };
935
+ return { result, ...residuals };
607
936
  }
@@ -64,6 +64,8 @@ export interface GlmModel {
64
64
  start: number[] | undefined;
65
65
  /** k when the fit was computed on the response scaled by 2^-k (gaussian on the identity link; see scaledView). */
66
66
  yScale?: number;
67
+ /** 0-based indices of the input rows used (the rows without a missing value; rows of weight 0 included). */
68
+ rows: number[];
67
69
  }
68
70
  /**
69
71
  * Result of {@link glm}: R's `glm` object.
@@ -226,7 +228,10 @@ export interface GlmSummary {
226
228
  statistic: number[];
227
229
  /** Two-sided p-values (R's `Pr(>|z|)` or `Pr(>|t|)`). */
228
230
  pValue: number[];
229
- /** `"z value"` when the dispersion is fixed (binomial, poisson), else `"t value"`. */
231
+ /**
232
+ * `"z value"` when the dispersion is not estimated (fixed by the family: binomial, poisson; or given as
233
+ * `options.dispersion`), else `"t value"`.
234
+ */
230
235
  statisticName: "z value" | "t value";
231
236
  /** (R'R)^-1 of the columns that are not aliased. */
232
237
  covUnscaled: number[][];
@@ -321,6 +326,11 @@ export declare function glmResiduals(fit: GlmResult, options: GlmResidualsOption
321
326
  * @category Generalized linear models
322
327
  */
323
328
  export declare function glmHatvalues(fit: GlmResult): number[];
329
+ /**
330
+ * For each row of non-zero prior weight (in order, as glmHatvalues), its row in the fit's QR decomposition, or -1 for
331
+ * a row the last least squares step left out
332
+ */
333
+ export declare function glmQrRows(fit: GlmResult): number[];
324
334
  /**
325
335
  * Options for {@link glmRstandard}.
326
336
  *