@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
@@ -2,7 +2,7 @@
2
2
  // Peto & Peto for rho = 1) and the Kaplan-Meier estimate with Greenwood's standard error, its pointwise confidence
3
3
  // intervals and the median survival times (survival's survfit and summary(fit, censored = TRUE)).
4
4
  //
5
- // Written for rStats.js (no ported code) from oracle/survival-behaviour.md and the published methods: Kaplan and Meier
5
+ // Written for rStats.js (no ported code) from oracle/survival-behaviour.md, oracle/coxph2-behaviour.md part C, and the published methods: Kaplan and Meier
6
6
  // (1958), "Nonparametric estimation from incomplete observations", JASA 53, 457-481; Greenwood (1926) for the variance;
7
7
  // Harrington and Fleming (1982), "A class of rank test procedures for censored survival data", Biometrika 69, 553-566,
8
8
  // for the weights S(t-)^rho; Brookmeyer and Crowley (1982) for the confidence limits of the median.
@@ -13,10 +13,14 @@ import { eigen } from "../linalg/eigen.js";
13
13
  import { solve } from "../linalg/solve.js";
14
14
  import { midpoint } from "../internal/extremes.js";
15
15
  import { mergeTiedTimes } from "./tiedTimes.js";
16
+ import { reported } from "../internal/warnings.js";
17
+ import { wideSum, wideSumAdd, wideSumValue } from "../internal/summary.js";
16
18
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
19
  import { checkOptions } from "../internal/checkOptions.js";
18
20
  const SURVDIFF_KEYS = ["rho"];
19
- const SURVFIT_KEYS = ["group", "confType", "confInt"];
21
+ const SURVFIT_KEYS = /* @__PURE__ */ new Set([
22
+ "group", "start", "id", "weights", "ctype", "stype", "robust", "rmean", "confType", "confInt",
23
+ ]);
20
24
  const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
21
25
  /** Observations with no missing value, the sorted labels and the group index of each */
22
26
  function prepare(time, status, group) {
@@ -65,7 +69,7 @@ function prepare(time, status, group) {
65
69
  *
66
70
  * Rows with a missing time, status or group are dropped.
67
71
  *
68
- * @param time Follow-up times.
72
+ * @param time Follow-up times, or stop times when `options.start` is supplied.
69
73
  * @param status 1 for an event, 0 for a censored time.
70
74
  * @param group Group labels, one per observation.
71
75
  * @param options See {@link SurvdiffOptions}.
@@ -195,15 +199,18 @@ function curveMedian(time, curve) {
195
199
  return time[first];
196
200
  }
197
201
  /**
198
- * Kaplan-Meier estimate of the survival function with Greenwood's standard error and pointwise confidence intervals.
199
- * Equivalent to R's `survival::survfit()`. As `summary(survfit(Surv(time, status) ~ group, conf.type, conf.int),
200
- * censored = TRUE)`, with the medians and their confidence limits of `summary(fit)$table`.
202
+ * Kaplan-Meier or exponential cumulative-hazard estimate with pointwise confidence intervals, medians and restricted means.
203
+ * Equivalent to R's `survival::survfit()`. Supports right-censored and counting-process data, Nelson-Aalen and Fleming-Harrington cumulative hazards,
204
+ * integer case weights, infinitesimal-jackknife standard errors and all six confidence transformations.
201
205
  *
202
- * Rows with a missing time, status or group are dropped.
206
+ * Rows with a missing time, status, group, id or weight are dropped. With `start`, the risk set at t is
207
+ * `start < t <= time`; without `id`, each split row ending without an event is a censoring. With `id`, a row
208
+ * followed by another row for the same subject at the same boundary is not a censoring.
203
209
  *
204
- * @param time Follow-up times.
210
+ * @param time Follow-up times, or stop times when `options.start` is supplied.
205
211
  * @param status 1 for an event, 0 for a censored time.
206
212
  * @param options See {@link SurvfitOptions}.
213
+ * @returns Time-row estimates, pointwise limits, per-stratum medians and restricted-mean summaries.
207
214
  *
208
215
  * @example
209
216
  * ```ts
@@ -214,88 +221,416 @@ function curveMedian(time, curve) {
214
221
  */
215
222
  export function survfit(time, status, options = {}) {
216
223
  checkOptions(options, SURVFIT_KEYS, "survfit"); // generated: option-keys.mjs
217
- const { group, confType = "log", confInt = 0.95 } = options;
218
- if (confType !== "log" && confType !== "plain" && confType !== "log-log") {
219
- throw new RangeError(`invalid 'confType': ${String(confType)}`);
224
+ const { group, start: startTimes, id, weights, ctype = 1, stype = 1, robust = false, rmean = "common", confType: confTypeInput = "log", confInt = 0.95 } = options;
225
+ if (typeof confTypeInput !== "string")
226
+ throw new TypeError("confType must be a string");
227
+ const confTypes = ["log", "log-log", "plain", "none", "logit", "arcsin"];
228
+ const confMatches = typeof confTypeInput === "string"
229
+ ? confTypes.filter(value => value.startsWith(confTypeInput))
230
+ : [];
231
+ const confType = confTypes.includes(confTypeInput) ? confTypeInput :
232
+ confMatches.length === 1 ? confMatches[0] : confTypeInput;
233
+ if (typeof ctype !== "number")
234
+ throw new TypeError("ctype must be a number");
235
+ if (typeof stype !== "number")
236
+ throw new TypeError("stype must be a number");
237
+ if (ctype !== 1 && ctype !== 2)
238
+ throw new RangeError("ctype must be 1 or 2");
239
+ if (stype !== 1 && stype !== 2)
240
+ throw new RangeError("stype must be 1 or 2");
241
+ if (!confTypes.some(value => value === confType)) {
242
+ throw new RangeError("'arg' should be one of “log”, “log-log”, “plain”, “none”, “logit”, “arcsin”");
220
243
  }
244
+ if (typeof confInt !== "number")
245
+ throw new TypeError("confInt must be a number");
221
246
  if (!(confInt > 0 && confInt < 1))
222
- throw new RangeError("'confInt' must be between 0 and 1");
223
- const { obs, labels } = prepare(time, status, group);
224
- const names = group === undefined ? ["all"] : labels;
225
- // (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
226
- const a2 = (1 - confInt) / 2;
227
- const z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - (1 - confInt) / 2);
247
+ throw new RangeError("confidence intervals must be between 0 and 1");
248
+ if (time.length !== status.length)
249
+ throw new RangeError("'time' and 'status' must have the same length");
250
+ if (group !== undefined && group.length !== time.length)
251
+ throw new RangeError("'group' must have the same length as 'time'");
252
+ if (startTimes !== undefined && startTimes.length !== time.length)
253
+ throw new RangeError("'start' must have the same length as 'time'");
254
+ if (id !== undefined && id.length !== time.length)
255
+ throw new RangeError("'id' must have the same length as 'time'");
256
+ if (id !== undefined && startTimes === undefined)
257
+ throw new RangeError("'id' requires 'start'");
258
+ if (weights !== undefined && !Array.isArray(weights))
259
+ throw new TypeError("'weights' must be an array");
260
+ if (weights !== undefined && weights.length !== time.length)
261
+ throw new RangeError("'weights' must have the same length as 'time'");
262
+ if (typeof robust !== "boolean")
263
+ throw new TypeError("'robust' must be a boolean");
264
+ if (typeof rmean !== "number" && typeof rmean !== "string")
265
+ throw new TypeError("rmean must be a number or string");
266
+ if (typeof rmean === "number" && !Number.isFinite(rmean))
267
+ throw new RangeError("'rmean' must be finite");
268
+ if (typeof rmean !== "number" && rmean !== "none" && rmean !== "common" && rmean !== "individual") {
269
+ throw new RangeError("'arg' should be one of “none”, “common”, “individual”");
270
+ }
271
+ const keep = [];
272
+ for (let i = 0; i < time.length; i++) {
273
+ const rawWeight = weights?.[i];
274
+ if (weights && rawWeight != null && typeof rawWeight !== "number")
275
+ throw new TypeError("weights must contain numbers");
276
+ if (weights && (rawWeight == null || Number.isNaN(rawWeight)))
277
+ continue;
278
+ const w = rawWeight ?? 1;
279
+ if (!Number.isFinite(w))
280
+ throw new RangeError("weights must be finite");
281
+ if (w < 0)
282
+ throw new RangeError("weights must be non-negative");
283
+ if (!Number.isSafeInteger(w))
284
+ throw new RangeError("weights must be non-negative safe integers");
285
+ if (time[i] != null && typeof time[i] !== "number")
286
+ throw new TypeError("'time' must contain numbers");
287
+ if (status[i] != null && typeof status[i] !== "number")
288
+ throw new TypeError("'status' must contain numbers");
289
+ if (startTimes !== undefined && startTimes[i] != null && typeof startTimes[i] !== "number") {
290
+ throw new TypeError("'start' must contain numbers");
291
+ }
292
+ if (time[i] == null || status[i] == null || Number.isNaN(time[i]) || Number.isNaN(status[i]) ||
293
+ (startTimes !== undefined && (startTimes[i] == null || Number.isNaN(startTimes[i]))) ||
294
+ (group !== undefined && isMissing(group[i])) || (id !== undefined && isMissing(id[i])))
295
+ continue;
296
+ if (startTimes !== undefined && !(startTimes[i] < time[i]))
297
+ throw new RangeError("stop time must be > start time");
298
+ if (status[i] !== 0 && status[i] !== 1)
299
+ throw new RangeError("'status' must be 0 (censored) or 1 (event)");
300
+ if (time[i] === -Infinity || (time[i] === Infinity && status[i] === 1))
301
+ throw new RangeError("event times must be finite");
302
+ keep.push(i);
303
+ }
304
+ if (keep.length === 0)
305
+ throw new RangeError("no observations without missing values");
306
+ const gvals = group === undefined ? [] : numberLevels(group);
307
+ // IDs are identifiers, not factor levels: preserve exact numeric identity instead of numberLevels' display rounding.
308
+ const ivals = id === undefined ? [] : Array.from(id);
309
+ const labels = group === undefined ? ["all"] : Array.from(new Set(keep.map(i => gvals[i]))).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0).map(v => `group=${levelText(v)}`);
310
+ const gindex = new Map();
311
+ if (group !== undefined)
312
+ Array.from(new Set(keep.map(i => gvals[i]))).sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0).forEach((v, i) => gindex.set(v, i));
313
+ const idIndex = new Map();
314
+ if (id !== undefined)
315
+ Array.from(new Set(keep.map(i => ivals[i]))).forEach((v, i) => idIndex.set(v, i));
316
+ const rawTimes = keep.flatMap(i => startTimes === undefined ? [time[i]] : [startTimes[i], time[i]]);
317
+ const mergedTimes = mergeTiedTimes(rawTimes);
318
+ const mergedStart = new Map();
319
+ const mergedStop = new Map();
320
+ keep.forEach((i, k) => {
321
+ if (startTimes === undefined) {
322
+ mergedStop.set(i, mergedTimes[k]);
323
+ }
324
+ else {
325
+ mergedStart.set(i, mergedTimes[2 * k]);
326
+ mergedStop.set(i, mergedTimes[2 * k + 1]);
327
+ if (!(mergedStart.get(i) < mergedStop.get(i))) {
328
+ throw new Error("aeqSurv exception, an interval has effective length 0");
329
+ }
330
+ }
331
+ });
332
+ const obs = keep.map((i) => ({
333
+ time: mergedStop.get(i), start: startTimes === undefined ? -Infinity : mergedStart.get(i),
334
+ event: status[i] === 1, group: group === undefined ? 0 : gindex.get(gvals[i]),
335
+ id: id === undefined ? i : idIndex.get(ivals[i]), weight: weights?.[i] ?? 1,
336
+ })).sort((a, b) => a.time - b.time);
337
+ const allRowsById = id === undefined ? undefined : new Map();
338
+ if (allRowsById)
339
+ for (const row of obs) {
340
+ const list = allRowsById.get(row.id) ?? [];
341
+ list.push(row);
342
+ allRowsById.set(row.id, list);
343
+ }
344
+ const names = labels;
345
+ const allTimes = obs.map(o => o.time);
346
+ const globalMin = Math.min(...allTimes), t0 = Math.min(0, globalMin);
347
+ if (typeof rmean === "number" && rmean <= t0)
348
+ throw new RangeError("'rmean' must be greater than the integration origin");
349
+ const a2 = (1 - confInt) / 2, z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - a2);
228
350
  const stdErr = [];
229
- const out = {
230
- strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr, stdError: stdErr, lower: [], upper: [],
231
- median: [], medianRows: names,
232
- };
233
- names.forEach((name, g) => {
234
- const rows = obs.filter((o) => o.group === g);
235
- const start = out.time.length;
236
- let atRisk = rows.length;
237
- let S = 1;
238
- let greenwood = 0;
351
+ const out = { strata: [], time: [], nRisk: [], nEvent: [], nCensor: [], surv: [], stdErr, stdError: stdErr,
352
+ lower: [], upper: [], cumhaz: [], stdChaz: [], logse: !robust || ctype === 2, n: [], records: [], nMax: [], nStart: [], events: [],
353
+ rmean: [], seRmean: [], median: [], medianRows: names, table: { colNames: [], rowNames: names, table: [] }, warnings: [] };
354
+ if (weights !== undefined)
355
+ out.counts = { nRisk: [], nEvent: [], nCensor: [] };
356
+ const tableRows = [];
357
+ for (let g = 0; g < names.length; g++) {
358
+ const rows = obs.filter(o => o.group === g);
359
+ if (!rows.some(o => o.weight > 0))
360
+ throw new Error("a group has no positive weight");
361
+ const start = out.time.length, records = rows.length, maxTime = Math.max(...rows.map(o => o.time));
362
+ let nRisk = 0, nUnweighted = 0, S = 1, H = 0, green = 0, varH = 0;
363
+ // Preserve the original right-censored path's up-front weight validation and decrementing risk set.
364
+ // Counting-process risk sets are recomputed from start < t <= stop below.
365
+ if (startTimes === undefined) {
366
+ let totalWeight = 0;
367
+ for (const o of rows) {
368
+ totalWeight += o.weight;
369
+ if (!Number.isSafeInteger(totalWeight)) {
370
+ throw new RangeError("total case weight per group must be a safe integer");
371
+ }
372
+ }
373
+ nRisk = totalWeight;
374
+ nUnweighted = rows.length;
375
+ }
376
+ const events = [];
377
+ const curveEvents = [];
378
+ const eventRows = [];
379
+ const subjectRows = id === undefined ? undefined : new Map();
380
+ if (subjectRows)
381
+ for (const row of rows) {
382
+ const list = subjectRows.get(row.id) ?? [];
383
+ list.push(row);
384
+ subjectRows.set(row.id, list);
385
+ }
239
386
  for (let i = 0; i < rows.length;) {
240
387
  const t = rows[i].time;
241
- let j = i;
242
- let d = 0;
243
- while (j < rows.length && rows[j].time === t) {
244
- if (rows[j].event)
245
- d++;
388
+ let j = i, d = 0, e = 0, c = 0, uwRisk = nUnweighted;
389
+ while (j < rows.length && rows[j].time === t)
246
390
  j++;
391
+ const atTime = rows.slice(i, j);
392
+ if (startTimes !== undefined) {
393
+ // Risk is counted by interval rows, not unique IDs. IDs only identify split-point censorings;
394
+ // overlapping rows remain distinct risk contributions just as in the supplied counting-process data.
395
+ const active = rows.filter(o => o.start < t && o.time >= t);
396
+ nRisk = active.reduce((sum, o) => sum + o.weight, 0);
397
+ nUnweighted = active.length;
398
+ uwRisk = nUnweighted;
399
+ if (!Number.isSafeInteger(nRisk))
400
+ throw new RangeError("total case weight at risk must be a safe integer");
247
401
  }
248
- const c = j - i - d;
249
- if (d > 0) {
250
- S *= 1 - d / atRisk;
251
- greenwood += d < atRisk ? d / (atRisk * (atRisk - d)) : Infinity;
252
- }
253
- const sigma = Math.sqrt(greenwood);
254
- let lo;
255
- let up;
256
- if (confType === "log") {
257
- lo = S === 0 ? NaN : S * Math.exp(-z * sigma);
258
- up = S === 0 ? NaN : Math.min(1, S * Math.exp(z * sigma));
402
+ const eventRowsAtTime = atTime.filter(o => o.event);
403
+ const censorRows = atTime.filter(o => !o.event && (allRowsById === undefined ||
404
+ !(allRowsById.get(o.id) ?? []).some(next => next.start === t && next.time > t)));
405
+ for (const o of eventRowsAtTime) {
406
+ d += o.weight;
407
+ e++;
259
408
  }
260
- else if (confType === "plain") {
261
- const h = z * sigma * S;
262
- lo = Number.isNaN(h) ? NaN : Math.max(0, S - h);
263
- up = Number.isNaN(h) ? NaN : Math.min(1, S + h);
409
+ for (const o of censorRows)
410
+ c += o.weight;
411
+ const unEvent = eventRowsAtTime.length, unCensor = censorRows.length;
412
+ // A stop that only splits an id's follow-up is not a censoring and does not create a summary row.
413
+ // Keep genuine zero-weight events/censorings, as the right-censored path does.
414
+ if (id !== undefined && eventRowsAtTime.length === 0 && censorRows.length === 0) {
415
+ i = j;
416
+ continue;
264
417
  }
265
- else if (S === 0) {
266
- lo = NaN;
267
- up = NaN;
418
+ let inc = 0, incVar = 0;
419
+ if (d > 0) {
420
+ if (ctype === 1) {
421
+ inc = d / nRisk;
422
+ incVar = d / (nRisk * nRisk);
423
+ }
424
+ else {
425
+ for (let k = 0; k < e; k++) {
426
+ const a = d / e, den = nRisk - k * a;
427
+ inc += a / den;
428
+ incVar += a / (den * den);
429
+ }
430
+ }
431
+ H += inc;
432
+ varH += incVar;
433
+ if (stype === 1) {
434
+ S *= 1 - d / nRisk;
435
+ green += d < nRisk ? d / (nRisk * (nRisk - d)) : Infinity;
436
+ }
437
+ else
438
+ S = Math.exp(-H);
439
+ eventRows.push({ t, d, n: nRisk, e, S });
268
440
  }
269
- else if (S === 1) {
270
- // log(-log(1)) is -Inf with a standard error of 0: survival 3.8-12 gives the limits 1 and 1 there (before
271
- // 3.8-12, NA)
272
- lo = 1;
273
- up = 1;
441
+ const sigma = stype === 1 ? Math.sqrt(green) : Math.sqrt(varH);
442
+ let robustS = 0, robustH = 0;
443
+ if (robust) {
444
+ let vS = 0, vH = 0;
445
+ const subjects = subjectRows === undefined ? rows : Array.from(subjectRows.values(), groupRows => groupRows[0]);
446
+ for (const subject of subjects) {
447
+ const ownRows = subjectRows?.get(subject.id) ?? [subject];
448
+ let dS = 0, dH = 0;
449
+ for (const ev of eventRows) {
450
+ if (ev.t > t)
451
+ break;
452
+ const atRisk = ownRows.some(row => row.start < ev.t && row.time >= ev.t);
453
+ const event = ownRows.some(row => row.time === ev.t && row.event);
454
+ const h = ev.d / ev.n;
455
+ if (ctype === 1)
456
+ dH += (Number(event) - Number(atRisk) * h) / ev.n;
457
+ else {
458
+ let fd = 0, fn = 0;
459
+ for (let k = 0; k < ev.e; k++) {
460
+ const a = ev.d / ev.e, den = ev.n - k * a;
461
+ fd += (den + k * a) / (ev.e * den * den);
462
+ fn -= a / (den * den);
463
+ }
464
+ dH += fd * Number(event) + fn * Number(atRisk);
465
+ }
466
+ if (stype === 1 && h < 1)
467
+ dS -= S * (Number(event) - Number(atRisk) * h) / ((1 - h) * ev.n);
468
+ }
469
+ vS += (subject.weight * dS) ** 2;
470
+ vH += (subject.weight * dH) ** 2;
471
+ }
472
+ robustS = Math.sqrt(vS);
473
+ robustH = Math.sqrt(vH);
274
474
  }
275
- else {
276
- const ls = Math.log(S);
277
- const m = Math.log(-ls);
278
- lo = Math.exp(-Math.exp(m - (z * sigma) / ls));
279
- up = Math.exp(-Math.exp(m + (z * sigma) / ls));
475
+ // Robust stype 1 uses the KM influence variance; stype 2 uses the cumulative-hazard influence variance.
476
+ // With ctype 2, log-scale limits use the IJ scale selected by logse:
477
+ // KM influence for stype 1, FH influence for stype 2. The public stdErr is
478
+ // always on the survival scale, so multiply by S when logse is true.
479
+ const seLog = robust
480
+ ? (ctype === 2 ? (stype === 1 ? robustS : robustH) : stype === 1 ? (S === 0 ? NaN : robustS / S) : robustH)
481
+ : sigma;
482
+ const seS = robust
483
+ ? (ctype === 2 ? S * (stype === 1 ? robustS : robustH) : stype === 1 ? robustS : S * robustH)
484
+ : S * sigma;
485
+ let lo = NaN, up = NaN;
486
+ if (confType !== "none") {
487
+ if (confType === "log") {
488
+ lo = S === 0 ? (seS === 0 ? 0 : NaN) : S * Math.exp(-z * seLog);
489
+ up = S === 0 ? (seS === 0 ? 0 : NaN) : Math.min(1, S * Math.exp(z * seLog));
490
+ }
491
+ else if (confType === "log-log") {
492
+ if (S === 0 || S === 1) {
493
+ lo = seS === 0 ? S : NaN;
494
+ up = lo;
495
+ }
496
+ else {
497
+ const m = Math.log(-Math.log(S));
498
+ lo = Math.exp(-Math.exp(m - z * seLog / Math.log(S)));
499
+ up = Math.exp(-Math.exp(m + z * seLog / Math.log(S)));
500
+ }
501
+ }
502
+ else if (confType === "plain") {
503
+ if (S === 0 && seS === Infinity) {
504
+ lo = NaN;
505
+ up = NaN;
506
+ }
507
+ else {
508
+ lo = Math.max(0, S - z * seS);
509
+ up = Math.min(1, S + z * seS);
510
+ }
511
+ }
512
+ else if (confType === "logit") {
513
+ if (S === 0 || S === 1) {
514
+ lo = seS === 0 ? S : NaN;
515
+ up = lo;
516
+ }
517
+ else {
518
+ const l = Math.log(S / (1 - S)), h = z * seS / (S * (1 - S));
519
+ lo = 1 - 1 / (1 + Math.exp(l - h));
520
+ up = 1 - 1 / (1 + Math.exp(l + h));
521
+ }
522
+ }
523
+ else {
524
+ if (S > 0 && S < 1) {
525
+ const a = Math.asin(Math.sqrt(S)), h = z * seS / (2 * Math.sqrt(S * (1 - S)));
526
+ lo = Math.sin(Math.max(0, a - h)) ** 2;
527
+ up = Math.sin(Math.min(Math.PI / 2, a + h)) ** 2;
528
+ }
529
+ else {
530
+ lo = NaN;
531
+ up = NaN;
532
+ }
533
+ }
280
534
  }
281
- out.strata.push(name);
535
+ const rowRisk = nRisk;
536
+ out.strata.push(names[g]);
282
537
  out.time.push(t);
283
- out.nRisk.push(atRisk);
538
+ out.nRisk.push(rowRisk);
284
539
  out.nEvent.push(d);
285
540
  out.nCensor.push(c);
286
541
  out.surv.push(S);
287
- out.stdErr.push(S * sigma);
542
+ out.cumhaz.push(H);
543
+ out.stdChaz.push(robust ? robustH : Math.sqrt(varH));
544
+ out.stdErr.push(robust
545
+ ? (ctype === 2 ? S * (stype === 1 ? robustS : robustH) : stype === 1 ? robustS : S * robustH)
546
+ : S * sigma);
288
547
  out.lower.push(lo);
289
548
  out.upper.push(up);
290
- atRisk -= j - i;
549
+ if (out.counts) {
550
+ out.counts.nRisk.push(uwRisk);
551
+ out.counts.nEvent.push(unEvent);
552
+ out.counts.nCensor.push(unCensor);
553
+ }
554
+ if (startTimes === undefined) {
555
+ nRisk -= d + c;
556
+ nUnweighted -= j - i;
557
+ }
291
558
  i = j;
292
559
  }
293
- const tt = out.time.slice(start);
294
- out.median.push([
295
- curveMedian(tt, out.surv.slice(start)),
296
- curveMedian(tt, out.lower.slice(start)),
297
- curveMedian(tt, out.upper.slice(start)),
298
- ]);
299
- });
300
- return out;
560
+ const tt = out.time.slice(start), ss = out.surv.slice(start), ll = out.lower.slice(start), uu = out.upper.slice(start);
561
+ out.median.push([curveMedian(tt, ss), confType === "none" ? NaN : curveMedian(tt, ll), confType === "none" ? NaN : curveMedian(tt, uu)]);
562
+ out.n.push(records);
563
+ out.records.push(records);
564
+ const risks = out.nRisk.slice(start);
565
+ out.nMax.push(Math.max(...risks));
566
+ out.nStart.push(risks[0] ?? 0);
567
+ out.events.push(rows.reduce((v, o) => v + (o.event ? o.weight : 0), 0));
568
+ const tau = rmean === "none" ? NaN : rmean === "common" ? Math.max(...allTimes) : rmean === "individual" ? maxTime : rmean;
569
+ if (rmean !== "none" && !Number.isFinite(tau))
570
+ throw new RangeError("'rmean' must be finite");
571
+ const finiteTimes = rows.filter(o => Number.isFinite(o.time)).map(o => Math.abs(o.time));
572
+ const largestTime = Number.isFinite(tau) ? Math.max(Math.abs(tau), Math.abs(t0), ...finiteTimes) : Math.max(Math.abs(t0), ...finiteTimes);
573
+ const exponent = largestTime === 0 ? 0 : Math.max(-1074, Math.min(1023, Math.floor(Math.log2(largestTime))));
574
+ const timeScale = largestTime === 0 ? 1 : 2 ** exponent;
575
+ const scaleEndpoints = Number.isFinite(tau) && !Number.isFinite(tau - t0);
576
+ const survAt = (t) => { let x = 1; for (const ev of eventRows) {
577
+ if (ev.t <= t)
578
+ x = ev.S;
579
+ else
580
+ break;
581
+ } return x; };
582
+ const survAtScaled = (t) => { let x = 1; for (const ev of eventRows) {
583
+ if (ev.t / timeScale <= t)
584
+ x = ev.S;
585
+ else
586
+ break;
587
+ } return x; };
588
+ const areaSum = wideSum();
589
+ if (scaleEndpoints) {
590
+ const cuts = Array.from(new Set([t0 / timeScale, ...eventRows.map(e => e.t / timeScale).filter(t => t > t0 / timeScale && t < tau / timeScale), tau / timeScale])).sort((a, b) => a - b);
591
+ for (let k = 0; k < cuts.length - 1; k++) {
592
+ const l = cuts[k], u = cuts[k + 1];
593
+ wideSumAdd(areaSum, survAtScaled(l) * (u - l), cuts.length + 1);
594
+ }
595
+ }
596
+ else {
597
+ const cuts = Array.from(new Set([t0, ...eventRows.map(e => e.t).filter(t => t > t0 && t < tau), tau])).sort((a, b) => a - b);
598
+ for (let k = 0; k < cuts.length - 1; k++) {
599
+ const l = cuts[k], u = cuts[k + 1];
600
+ wideSumAdd(areaSum, survAt(l) * (u - l), cuts.length + 1);
601
+ }
602
+ }
603
+ const area = wideSumValue(areaSum) * (scaleEndpoints ? timeScale : 1);
604
+ const varianceSum = wideSum();
605
+ if (Number.isFinite(tau)) {
606
+ for (const ev of eventRows) {
607
+ if (ev.t > tau || ev.n <= ev.d)
608
+ continue;
609
+ const aSum = wideSum();
610
+ if (scaleEndpoints) {
611
+ const c2 = Array.from(new Set([ev.t / timeScale, ...eventRows.map(e => e.t / timeScale).filter(t => t > ev.t / timeScale && t < tau / timeScale), tau / timeScale])).sort((a, b) => a - b);
612
+ for (let k = 0; k < c2.length - 1; k++)
613
+ wideSumAdd(aSum, survAtScaled(c2[k]) * (c2[k + 1] - c2[k]), c2.length + 1);
614
+ }
615
+ else {
616
+ const c2 = Array.from(new Set([ev.t, ...eventRows.map(e => e.t).filter(t => t > ev.t && t < tau), tau])).sort((a, b) => a - b);
617
+ for (let k = 0; k < c2.length - 1; k++)
618
+ wideSumAdd(aSum, survAt(c2[k]) * ((c2[k + 1] - c2[k]) / timeScale), c2.length + 1);
619
+ }
620
+ const A = wideSumValue(aSum);
621
+ wideSumAdd(varianceSum, A * A * ev.d / (ev.n * (ev.n - ev.d)), eventRows.length + 1);
622
+ }
623
+ }
624
+ const varianceScaled = wideSumValue(varianceSum);
625
+ out.rmean.push(rmean === "none" ? NaN : area);
626
+ out.seRmean.push(rmean === "none" ? NaN : Math.sqrt(varianceScaled) * timeScale);
627
+ tableRows.push(rmean === "none"
628
+ ? (confType === "none" ? [records, out.nMax[g], out.nStart[g], out.events[g], out.median[g][0]]
629
+ : [records, out.nMax[g], out.nStart[g], out.events[g], out.median[g][0], out.median[g][1], out.median[g][2]])
630
+ : (confType === "none" ? [records, out.nMax[g], out.nStart[g], out.events[g], area, Math.sqrt(varianceScaled) * timeScale, out.median[g][0]]
631
+ : [records, out.nMax[g], out.nStart[g], out.events[g], area, Math.sqrt(varianceScaled) * timeScale, out.median[g][0], out.median[g][1], out.median[g][2]]));
632
+ }
633
+ out.table = { colNames: [...(rmean === "none" ? ["records", "n.max", "n.start", "events", "median"] : ["records", "n.max", "n.start", "events", "rmean", "se(rmean)", "median"]),
634
+ ...(confType === "none" ? [] : [`${confInt}LCL`, `${confInt}UCL`])], rowNames: names, table: tableRows };
635
+ return reported("survfit", out);
301
636
  }