@numero-uno-jpn/rstats 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.ja.md +9 -7
  3. package/README.md +9 -7
  4. package/dist/chunks/chunk-2IYY74LX.js +2 -0
  5. package/dist/chunks/{chunk-LA4H6ZSC.js → chunk-2MYUAEYE.js} +2 -2
  6. package/dist/chunks/{chunk-GUM57VVM.js → chunk-3BEE6BHN.js} +1 -1
  7. package/dist/chunks/{chunk-2VZW4XPK.js → chunk-73QCE2CI.js} +2 -2
  8. package/dist/chunks/{chunk-AJZV2SVY.js → chunk-AIXJAVDS.js} +2 -2
  9. package/dist/chunks/{chunk-6X2ZMPF5.js → chunk-BJOZZ5J6.js} +2 -2
  10. package/dist/chunks/{chunk-P7ZHH2SF.js → chunk-CX4XK7WC.js} +2 -2
  11. package/dist/chunks/{chunk-PDHBRDTF.js → chunk-DYCWYHYV.js} +1 -1
  12. package/dist/chunks/{chunk-6TZVS6WC.js → chunk-E5M5RAVB.js} +2 -2
  13. package/dist/chunks/{chunk-IJV43Y7Q.js → chunk-F2MURX2Y.js} +2 -2
  14. package/dist/chunks/{chunk-HBRSUHSU.js → chunk-F7SQG6BV.js} +2 -2
  15. package/dist/chunks/{chunk-UOAFEB64.js → chunk-FCF6FBJP.js} +2 -2
  16. package/dist/chunks/{chunk-TZTVDVP4.js → chunk-FMLFYM7N.js} +2 -2
  17. package/dist/chunks/{chunk-EBRTF7RM.js → chunk-GDMNF4P3.js} +1 -1
  18. package/dist/chunks/{chunk-RCGW2DCK.js → chunk-JBJTXMRJ.js} +2 -2
  19. package/dist/chunks/{chunk-Z74ZOTUN.js → chunk-L7PDJNJ3.js} +2 -2
  20. package/dist/chunks/{chunk-I5NWGQOQ.js → chunk-LVB22NKV.js} +2 -2
  21. package/dist/chunks/{chunk-UJYRU37Z.js → chunk-MJV5G7FG.js} +2 -2
  22. package/dist/chunks/{chunk-JJRZ2TTF.js → chunk-MXOGMN4P.js} +2 -2
  23. package/dist/chunks/{chunk-UMDXXT3M.js → chunk-MYRCEQ2R.js} +1 -1
  24. package/dist/chunks/{chunk-IOGQEMDE.js → chunk-Q32WODL4.js} +2 -2
  25. package/dist/chunks/{chunk-BNTBZ5W3.js → chunk-RZBX6VYO.js} +2 -2
  26. package/dist/chunks/chunk-TP4PRPVQ.js +2 -0
  27. package/dist/chunks/{chunk-FFNHG5SB.js → chunk-UJM7AJII.js} +1 -1
  28. package/dist/chunks/chunk-VAWD57ZB.js +2 -0
  29. package/dist/chunks/{chunk-LNUNKFIH.js → chunk-WBEYJ5W5.js} +2 -2
  30. package/dist/chunks/{chunk-LMNU4NHZ.js → chunk-YK2EJU6T.js} +2 -2
  31. package/dist/descriptive.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +6 -0
  34. package/dist/entries/tests.js +6 -0
  35. package/dist/htest/sampleSize.d.ts +290 -0
  36. package/dist/htest/sampleSize.js +625 -0
  37. package/dist/linalg.js +2 -2
  38. package/dist/mixed.js +2 -2
  39. package/dist/models/competingRisks.d.ts +188 -0
  40. package/dist/models/competingRisks.js +685 -0
  41. package/dist/models/coxZph.d.ts +67 -0
  42. package/dist/models/coxZph.js +479 -0
  43. package/dist/models/coxph.d.ts +61 -21
  44. package/dist/models/coxph.js +305 -65
  45. package/dist/models/metaAnalysis.d.ts +207 -0
  46. package/dist/models/metaAnalysis.js +696 -0
  47. package/dist/models/rmst2.d.ts +126 -0
  48. package/dist/models/rmst2.js +365 -0
  49. package/dist/models/survival.d.ts +65 -24
  50. package/dist/models/survival.js +407 -72
  51. package/dist/models/survreg.d.ts +160 -0
  52. package/dist/models/survreg.js +809 -0
  53. package/dist/numerics.js +2 -2
  54. package/dist/rstats.js +19 -16
  55. package/dist/special.js +2 -2
  56. package/dist/tests.js +16 -13
  57. package/llms.txt +13 -2
  58. package/package.json +1 -1
  59. package/dist/chunks/chunk-4OOTEXZU.js +0 -2
  60. package/dist/chunks/chunk-MJXETGT2.js +0 -2
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Options for {@link rmst2}.
3
+ *
4
+ * @category Survival analysis
5
+ */
6
+ export interface Rmst2Options {
7
+ /** Restriction time. Defaults to the largest follow-up time allowed by both arms. */
8
+ tau?: number;
9
+ /** Numeric covariates, one row per observation. A vector is treated as one column; rows with missing values are omitted. */
10
+ covariates?: readonly number[] | readonly (readonly number[])[];
11
+ /** Optional names of matrix columns; a vector is named "covariates", an unnamed matrix has empty names. */
12
+ covariateNames?: readonly string[];
13
+ /** Confidence level. Default 0.95. */
14
+ confLevel?: number;
15
+ }
16
+ /** An estimate, its standard error and a two-sided confidence interval. */
17
+ /**
18
+ * An RMST or RMTL estimate with its standard error and confidence interval.
19
+ *
20
+ * @category Survival analysis
21
+ */
22
+ export interface RmstEstimate {
23
+ /** Restricted mean or restricted mean time lost. */
24
+ estimate: number;
25
+ /** Greenwood or sandwich standard error. */
26
+ se: number;
27
+ /** Two-sided confidence interval. */
28
+ confInt: [number, number];
29
+ }
30
+ /** A between-arm difference or ratio with its confidence interval and two-sided p-value. */
31
+ /**
32
+ * A between-arm contrast with its confidence interval and p-value.
33
+ *
34
+ * @category Survival analysis
35
+ */
36
+ export interface RmstContrast {
37
+ /** Difference (arm 1 minus arm 0) or ratio (arm 1 divided by arm 0). */
38
+ estimate: number;
39
+ /** Two-sided confidence interval. */
40
+ confInt: [number, number];
41
+ /** Two-sided normal-tail p-value. */
42
+ pValue: number;
43
+ }
44
+ /** Coefficient estimates and robust Wald inference for an adjusted model. */
45
+ /**
46
+ * Coefficient estimates and robust Wald inference for an adjusted RMST model.
47
+ *
48
+ * @category Survival analysis
49
+ */
50
+ export interface RmstCoefficientTable {
51
+ /** Intercept, treatment indicator and covariate names. */
52
+ names: string[];
53
+ /** Model coefficients (log-scale coefficients for ratio models). */
54
+ estimate: number[];
55
+ se: number[];
56
+ z: number[];
57
+ pValue: number[];
58
+ /** Confidence limits: coefficient scale for the difference model, exponentiated scale for ratio models. */
59
+ confInt: [number[], number[]];
60
+ }
61
+ /**
62
+ * Result of {@link rmst2}.
63
+ *
64
+ * @category Survival analysis
65
+ */
66
+ export interface Rmst2Result {
67
+ /** Restriction time used in the analysis. */
68
+ tau: number;
69
+ /** Whether tau was selected from the follow-up times. */
70
+ tauDefault: boolean;
71
+ /** Confidence level. */
72
+ confLevel: number;
73
+ /** Warnings, each distinct message once. */
74
+ warnings: string[];
75
+ /** Unadjusted per-arm estimates; omitted when covariate adjustment is requested. */
76
+ arm1?: {
77
+ rmst: RmstEstimate;
78
+ rmtl: RmstEstimate;
79
+ };
80
+ arm0?: {
81
+ rmst: RmstEstimate;
82
+ rmtl: RmstEstimate;
83
+ };
84
+ /** Unadjusted between-arm contrasts. */
85
+ difference: RmstContrast;
86
+ ratio: RmstContrast;
87
+ rmtlRatio: RmstContrast;
88
+ /** Covariate-adjusted between-arm contrasts, present when covariates are supplied. */
89
+ adjusted?: {
90
+ difference: RmstContrast;
91
+ ratio: RmstContrast;
92
+ rmtlRatio: RmstContrast;
93
+ };
94
+ /** Coefficient estimates, robust standard errors and Wald tests for the three adjusted models. */
95
+ coefficients?: {
96
+ difference: RmstCoefficientTable;
97
+ ratio: RmstCoefficientTable;
98
+ rmtlRatio: RmstCoefficientTable;
99
+ };
100
+ }
101
+ /**
102
+ * Restricted mean survival time (RMST), restricted mean time lost (RMTL), and their between-arm contrasts.
103
+ * Implements the unadjusted Kaplan-Meier estimators and Tian, Zhao & Wei's adjusted estimating equations.
104
+ * Equivalent to `survRM2::rmst2()` in R.
105
+ *
106
+ * @param time Follow-up times.
107
+ * @param status Event indicator (1 event, 0 censored; 1/2 coding is also accepted). Invalid values are omitted with a warning.
108
+ * @param arm Treatment indicator (0 or 1; booleans are also accepted).
109
+ * @param options Restriction time, covariates, optional matrix column names and confidence level.
110
+ * @returns Per-arm RMST/RMTL estimates and between-arm contrasts; adjusted contrasts and coefficient tables are added
111
+ * when covariates are supplied.
112
+ *
113
+ * Rows with missing time, status, arm, or covariates are omitted. Negative follow-up times, non-positive tau, tau below
114
+ * the first retained observation, and tau above its default upper bound are errors.
115
+ * @example
116
+ * ```ts
117
+ * const r = rmst2([1,2,3,4,5,6,1.5,2.5,3.5,4.5,7,8],
118
+ * [1,0,1,1,0,1,1,1,0,1,1,0], [1,1,1,1,1,1,0,0,0,0,0,0]);
119
+ * r.tau; // 8
120
+ * r.arm1?.rmst.estimate; // 4.125
121
+ * r.arm0?.rmst.estimate; // 5
122
+ * r.difference.estimate; // -0.875
123
+ * ```
124
+ * @category Survival analysis
125
+ */
126
+ export declare function rmst2(time: readonly number[], status: readonly number[], arm: readonly (number | boolean)[], options?: Rmst2Options): Rmst2Result;
@@ -0,0 +1,365 @@
1
+ // Restricted mean survival time and adjusted contrasts.
2
+ // Written for rStats.js (no ported code), from oracle/survfit2-behaviour.md,
3
+ // Klein & Moeschberger (2003) §4.5, Uno et al. (2014), and Tian, Zhao & Wei (2014).
4
+ import { pnorm, qnorm } from "../distributions/normal.js";
5
+ import { crossprod } from "../linalg/basic.js";
6
+ import { matMul } from "../linalg/ops.js";
7
+ import { solve } from "../linalg/solve.js";
8
+ import { reported } from "../internal/warnings.js";
9
+ import { wideSum, wideSumAdd, wideSumValue } from "../internal/summary.js";
10
+ import { glm } from "./glm.js";
11
+ import { lm } from "./lm.js";
12
+ import { survfit } from "./survival.js";
13
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
14
+ import { checkOptions } from "../internal/checkOptions.js";
15
+ const RMST2_KEYS = ["tau", "covariates", "covariateNames", "confLevel"];
16
+ function pTwoSided(z) { return 2 * pnorm(-Math.abs(z)); }
17
+ function interval(estimate, se, z) { return [estimate - z * se, estimate + z * se]; }
18
+ function estimate(estimate, standardError, z) {
19
+ return { estimate, se: standardError, confInt: interval(estimate, standardError, z) };
20
+ }
21
+ function contrast(estimate, se, z, test) {
22
+ return { estimate, confInt: interval(estimate, se, z), pValue: pTwoSided(test) };
23
+ }
24
+ /**
25
+ * Obtain the KM restricted mean and Greenwood standard error from the verified survfit implementation.
26
+ * The complementary area is accumulated from survfit's returned step curve to avoid tau - RMST cancellation.
27
+ */
28
+ function armCurve(rows, tau) {
29
+ const fit = survfit(rows.map(r => r.time), rows.map(r => r.status), { rmean: tau });
30
+ const rmst = fit.rmean[0];
31
+ const se = fit.seRmean[0];
32
+ let previous = 0, survival = 1;
33
+ const lostArea = wideSum();
34
+ for (let i = 0; i < fit.time.length && fit.time[i] < tau; i++) {
35
+ const t = fit.time[i];
36
+ wideSumAdd(lostArea, (1 - survival) * (t - previous), fit.time.length + 1);
37
+ survival = fit.surv[i];
38
+ previous = t;
39
+ }
40
+ wideSumAdd(lostArea, (1 - survival) * (tau - previous), fit.time.length + 1);
41
+ const rmtl = wideSumValue(lostArea);
42
+ return { rmst: { estimate: rmst, se }, rmtl: { estimate: rmtl, se } };
43
+ }
44
+ function tableContrast(a, b, which, z) {
45
+ if (which === "difference") {
46
+ const d = a.estimate - b.estimate, se = Math.hypot(a.se, b.se);
47
+ return contrast(d, se, z, d / se);
48
+ }
49
+ const x = a.estimate, y = b.estimate;
50
+ if (x === 0 || y === 0) {
51
+ const value = x === 0 ? (y === 0 ? NaN : 0) : Infinity;
52
+ return { estimate: value, confInt: [NaN, NaN], pValue: NaN };
53
+ }
54
+ if (!(x > 0 && y > 0))
55
+ return { estimate: NaN, confInt: [NaN, NaN], pValue: NaN };
56
+ const ratio = x / y, logRatio = Math.log(ratio), se = Math.hypot(a.se / x, b.se / y);
57
+ return { estimate: ratio, confInt: [Math.exp(logRatio - z * se), Math.exp(logRatio + z * se)], pValue: pTwoSided(logRatio / se) };
58
+ }
59
+ /**
60
+ * Right-continuous inverse censoring survival weights from the verified KM implementation.
61
+ */
62
+ function censorWeights(rows) {
63
+ const weights = new Array(rows.length).fill(0);
64
+ for (const arm of [0, 1]) {
65
+ const indices = rows.flatMap((r, i) => r.arm === arm ? [i] : []);
66
+ const fit = survfit(indices.map(i => rows[i].time), indices.map(i => rows[i].status === 0 ? 1 : 0), { rmean: "none" });
67
+ for (const i of indices) {
68
+ const row = rows[i];
69
+ if (row.status === 0)
70
+ continue;
71
+ let g = 1;
72
+ for (let j = 0; j < fit.time.length && fit.time[j] <= row.time; j++)
73
+ g = fit.surv[j];
74
+ if (!(g > 0))
75
+ throw new Error("the censoring survival probability is zero");
76
+ weights[i] = 1 / g;
77
+ }
78
+ }
79
+ return weights;
80
+ }
81
+ /**
82
+ * Fit one specified estimating-equation model with validated lm/glm.
83
+ * Only the censoring-process correction in the subject-level B matrix is rmst2-specific.
84
+ */
85
+ function adjustedFit(rows, tau, y, logLink, names, zCrit) {
86
+ const rawPredictors = rows.map(r => [r.arm, ...r.x]);
87
+ // Keep ordinary columns unchanged; only extreme magnitudes are divided by an exact power of two.
88
+ // The fit and sandwich are computed in these equivalent coordinates, then mapped back below.
89
+ const columnScales = rawPredictors[0].map((_, j) => {
90
+ const magnitude = rawPredictors.reduce((m, row) => Math.max(m, Math.abs(row[j])), 0);
91
+ if (magnitude === 0)
92
+ return 1;
93
+ const exponent = Math.floor(Math.log2(magnitude));
94
+ return exponent > 500 || exponent < -500 ? 2 ** exponent : 1;
95
+ });
96
+ const predictors = rawPredictors.map(row => row.map((v, j) => v / columnScales[j]));
97
+ const Z = rows.map((_, i) => [1, ...predictors[i]]);
98
+ const parameterScales = [1, ...columnScales];
99
+ const w = censorWeights(rows);
100
+ const fit = logLink
101
+ ? glm(predictors, y, { family: "poisson", weights: w })
102
+ : lm(predictors, y, { weights: w });
103
+ if (logLink && !fit.converged) {
104
+ throw new Error("the adjusted RMST Poisson model did not converge");
105
+ }
106
+ const scaledCoef = fit.coefficients;
107
+ const coef = scaledCoef.map((v, j) => v / parameterScales[j]);
108
+ const mu = fit.fittedValues;
109
+ if (coef.some(v => !Number.isFinite(v)) || mu.some(v => !Number.isFinite(v))) {
110
+ throw new Error("the adjusted RMST model is singular or has non-finite fitted values");
111
+ }
112
+ const eps = Z.map((row, i) => row.map(v => w[i] * v * (y[i] - mu[i])));
113
+ const eta = eps.map(row => row.slice());
114
+ // B's extra influence term for the separately estimated censoring distribution, arm by arm.
115
+ for (const arm of [0, 1]) {
116
+ const indices = rows.flatMap((r, i) => r.arm === arm ? [i] : []);
117
+ const censorFit = survfit(indices.map(i => rows[i].time), indices.map(i => rows[i].status === 0 ? 1 : 0), { rmean: "none" });
118
+ for (let k = 0; k < censorFit.time.length; k++) {
119
+ const u = censorFit.time[k];
120
+ const dC = censorFit.nEvent[k];
121
+ if (!(u < tau) || dC === 0)
122
+ continue;
123
+ const pi = censorFit.nRisk[k];
124
+ if (!(pi > 0))
125
+ continue;
126
+ const q = new Array(Z[0].length).fill(0);
127
+ for (let j = 0; j < q.length; j++) {
128
+ const sum = wideSum();
129
+ for (const i of indices)
130
+ if (rows[i].time >= u)
131
+ wideSumAdd(sum, eps[i][j], indices.length);
132
+ q[j] = wideSumValue(sum);
133
+ }
134
+ const dLambda = dC / pi;
135
+ for (const i of indices) {
136
+ const row = rows[i];
137
+ const isCensor = row.time === u && row.status === 0;
138
+ const isAtRisk = row.time >= u;
139
+ for (let j = 0; j < q.length; j++) {
140
+ eta[i][j] += (q[j] / pi) * (Number(isCensor) - (isAtRisk ? dLambda : 0));
141
+ }
142
+ }
143
+ }
144
+ }
145
+ // A = sum Z_i Z_i' g_i (unweighted), B = sum eta_i eta_i'.
146
+ const derivativeRows = Z.map((row, i) => row.map(v => v * Math.sqrt(logLink ? mu[i] : 1)));
147
+ const A = crossprod(derivativeRows);
148
+ const B = crossprod(eta);
149
+ const Ainv = solve(A);
150
+ const scaledCov = matMul(matMul(Ainv, B), Ainv);
151
+ const cov = scaledCov.map((row, i) => row.map((v, j) => v / parameterScales[i] / parameterScales[j]));
152
+ const se = cov.map((row, i) => Math.sqrt(Math.max(0, row[i])));
153
+ const z = coef.map((v, i) => v / se[i]);
154
+ const pValue = z.map(pTwoSided);
155
+ const lower = coef.map((v, i) => v - zCrit * se[i]);
156
+ const upper = coef.map((v, i) => v + zCrit * se[i]);
157
+ const confInt = logLink
158
+ ? [lower.map(Math.exp), upper.map(Math.exp)]
159
+ : [lower, upper];
160
+ return {
161
+ coef,
162
+ cov,
163
+ table: { names: ["intercept", "arm", ...names], estimate: coef, se, z, pValue, confInt },
164
+ };
165
+ }
166
+ /**
167
+ * Restricted mean survival time (RMST), restricted mean time lost (RMTL), and their between-arm contrasts.
168
+ * Implements the unadjusted Kaplan-Meier estimators and Tian, Zhao & Wei's adjusted estimating equations.
169
+ * Equivalent to `survRM2::rmst2()` in R.
170
+ *
171
+ * @param time Follow-up times.
172
+ * @param status Event indicator (1 event, 0 censored; 1/2 coding is also accepted). Invalid values are omitted with a warning.
173
+ * @param arm Treatment indicator (0 or 1; booleans are also accepted).
174
+ * @param options Restriction time, covariates, optional matrix column names and confidence level.
175
+ * @returns Per-arm RMST/RMTL estimates and between-arm contrasts; adjusted contrasts and coefficient tables are added
176
+ * when covariates are supplied.
177
+ *
178
+ * Rows with missing time, status, arm, or covariates are omitted. Negative follow-up times, non-positive tau, tau below
179
+ * the first retained observation, and tau above its default upper bound are errors.
180
+ * @example
181
+ * ```ts
182
+ * const r = rmst2([1,2,3,4,5,6,1.5,2.5,3.5,4.5,7,8],
183
+ * [1,0,1,1,0,1,1,1,0,1,1,0], [1,1,1,1,1,1,0,0,0,0,0,0]);
184
+ * r.tau; // 8
185
+ * r.arm1?.rmst.estimate; // 4.125
186
+ * r.arm0?.rmst.estimate; // 5
187
+ * r.difference.estimate; // -0.875
188
+ * ```
189
+ * @category Survival analysis
190
+ */
191
+ export function rmst2(time, status, arm, options = {}) {
192
+ checkOptions(options, RMST2_KEYS, "rmst2"); // generated: option-keys.mjs
193
+ if (time.length !== status.length || time.length !== arm.length)
194
+ throw new RangeError("'time', 'status' and 'arm' must have the same length");
195
+ if (options.tau !== undefined && typeof options.tau !== "number")
196
+ throw new TypeError("'tau' must be a number");
197
+ if (options.confLevel !== undefined && typeof options.confLevel !== "number")
198
+ throw new TypeError("'confLevel' must be a number");
199
+ if (options.covariateNames !== undefined && !Array.isArray(options.covariateNames))
200
+ throw new TypeError("'covariateNames' must be an array of strings");
201
+ const confLevel = options.confLevel ?? 0.95;
202
+ if (!(confLevel > 0 && confLevel < 1))
203
+ throw new RangeError("'confLevel' must be between 0 and 1");
204
+ // Normalize very large follow-up times by an exact power of two before integration.
205
+ // This keeps the RMST/RMTL ratios and their Wald statistics scale-invariant while
206
+ // avoiding loss of low-order bits in long interval sums.
207
+ const maxTimeMagnitude = time.reduce((m, t) => Number.isFinite(t) ? Math.max(m, Math.abs(t)) : m, 0);
208
+ const proposedTimeScale = maxTimeMagnitude > 2 ** 500 ? 2 ** Math.floor(Math.log2(maxTimeMagnitude)) : 1;
209
+ const scalePreservesInputs = time.every(t => !Number.isFinite(t) || t === 0 || t / proposedTimeScale !== 0) &&
210
+ (options.tau === undefined || options.tau === 0 || options.tau / proposedTimeScale !== 0);
211
+ const timeScale = scalePreservesInputs ? proposedTimeScale : 1;
212
+ const toWorkingTime = (t) => t / timeScale;
213
+ const raw = Array.from(status);
214
+ // Surv objects are constructed within each arm. A 1/2-coded arm can therefore coexist with a 0/1-coded arm;
215
+ // in a 1/2-coded arm, zero is an invalid status and is omitted (while it remains part of the raw tau rule).
216
+ const status12Arms = new Set();
217
+ for (let i = 0; i < raw.length; i++) {
218
+ const a = arm[i] === true ? 1 : arm[i] === false ? 0 : arm[i];
219
+ if ((a === 0 || a === 1) && raw[i] === 2)
220
+ status12Arms.add(a);
221
+ }
222
+ const firstCovariate = options.covariates?.[0];
223
+ const vectorCovariate = options.covariates !== undefined && typeof firstCovariate === "number";
224
+ if (options.covariates !== undefined && options.covariates.length > 0 && !vectorCovariate && !Array.isArray(firstCovariate)) {
225
+ throw new TypeError("'covariates' must be a numeric vector or a matrix of numeric rows");
226
+ }
227
+ const X = options.covariates === undefined ? undefined : (vectorCovariate
228
+ ? options.covariates.map(v => [v])
229
+ : options.covariates.map(r => Array.from(r)));
230
+ if (X && X.length !== time.length)
231
+ throw new RangeError("'covariates' must have one row per observation");
232
+ if (X && X.some(row => row.length !== X[0].length))
233
+ throw new RangeError("'covariates' must have the same number of columns in every row");
234
+ if (X && X.some(row => row.some(v => typeof v !== "number")))
235
+ throw new TypeError("'covariates' must contain numeric values");
236
+ if (X && X.some(row => row.some(v => !Number.isFinite(v) && !Number.isNaN(v))))
237
+ throw new RangeError("'covariates' must be finite");
238
+ const rows = [];
239
+ const tauCandidates = [];
240
+ const extraArmTimes = [];
241
+ const warnings = [];
242
+ for (let i = 0; i < time.length; i++) {
243
+ if (time[i] == null || Number.isNaN(time[i]) || raw[i] == null || Number.isNaN(raw[i]) ||
244
+ arm[i] == null || Number.isNaN(arm[i])) {
245
+ throw new Error("missing value where TRUE/FALSE needed");
246
+ }
247
+ if (typeof time[i] !== "number")
248
+ throw new TypeError("'time' must contain numbers");
249
+ if (!Number.isFinite(time[i]))
250
+ throw new RangeError("'time' must be finite");
251
+ if (typeof arm[i] !== "number" && typeof arm[i] !== "boolean")
252
+ throw new TypeError("'arm' must contain numbers or booleans");
253
+ const a = arm[i] === true ? 1 : arm[i] === false ? 0 : arm[i];
254
+ // Additional arm levels are ignored only when their observations lie beyond tau,
255
+ // where they cannot contribute to either restricted curve.
256
+ if (a !== 0 && a !== 1) {
257
+ extraArmTimes.push(toWorkingTime(time[i]));
258
+ continue;
259
+ }
260
+ if (typeof raw[i] !== "number")
261
+ throw new TypeError("'status' must contain numbers");
262
+ const rawD = raw[i];
263
+ // The default-tau rule uses the original 0/1 status convention, independently of
264
+ // the per-arm Surv coding used for the Kaplan-Meier curves below.
265
+ const tauStatus = rawD === 1 ? 1 : 0;
266
+ const x = X ? X[i] : [];
267
+ if (x.some(v => !Number.isFinite(v)))
268
+ continue;
269
+ tauCandidates.push({ time: toWorkingTime(time[i]), status: tauStatus, arm: a, x, index: i });
270
+ let d = rawD;
271
+ if (status12Arms.has(a)) {
272
+ if (rawD === 2)
273
+ d = 1;
274
+ else if (rawD === 1)
275
+ d = 0;
276
+ else {
277
+ if (!warnings.includes("Invalid status value, converted to NA"))
278
+ warnings.push("Invalid status value, converted to NA");
279
+ continue;
280
+ }
281
+ }
282
+ else if (d !== 0 && d !== 1) {
283
+ if (!warnings.includes("Invalid status value, converted to NA"))
284
+ warnings.push("Invalid status value, converted to NA");
285
+ continue;
286
+ }
287
+ rows.push({ time: toWorkingTime(time[i]), status: d, arm: a, x, index: i });
288
+ }
289
+ if (tauCandidates.some(r => r.time < 0))
290
+ throw new Error("negative follow-up times are not supported");
291
+ if (!rows.some(r => r.arm === 0) || !rows.some(r => r.arm === 1))
292
+ throw new Error("both arms 0 and 1 are required");
293
+ const maxima = [0, 1].map(a => Math.max(...tauCandidates.filter(r => r.arm === a).map(r => r.time)));
294
+ const censored = [0, 1].map(a => { const m = maxima[a]; return tauCandidates.some(r => r.arm === a && r.time === m && r.status === 0); });
295
+ const tauMax = censored.some(Boolean) ? Math.min(...maxima.filter((_, i) => censored[i])) : Math.max(...maxima);
296
+ const tauDefault = options.tau === undefined;
297
+ const tau = options.tau === undefined ? tauMax : toWorkingTime(options.tau);
298
+ const tauOutput = options.tau === undefined ? tau * timeScale : options.tau;
299
+ if (extraArmTimes.some(t => t <= tau))
300
+ throw new RangeError("'arm' must contain only 0 and 1 through tau");
301
+ if (!(tau > 0))
302
+ throw new RangeError("'tau' must be greater than zero");
303
+ if (tau > tauMax)
304
+ throw new RangeError(`'tau' must be at most ${tauMax * timeScale}: the minimum of the largest times allowed by both arms`);
305
+ if (tau < Math.min(...tauCandidates.map(r => r.time)))
306
+ throw new RangeError("'tau' must not be below the first observed time");
307
+ const a2 = (1 - confLevel) / 2, z = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm(1 - a2);
308
+ const arm1Rows = rows.filter(r => r.arm === 1), arm0Rows = rows.filter(r => r.arm === 0);
309
+ const c1Working = armCurve(arm1Rows, tau), c0Working = armCurve(arm0Rows, tau);
310
+ const scaleCurve = (curve) => ({ estimate: curve.estimate * timeScale, se: curve.se * timeScale });
311
+ const c1 = { rmst: scaleCurve(c1Working.rmst), rmtl: scaleCurve(c1Working.rmtl) };
312
+ const c0 = { rmst: scaleCurve(c0Working.rmst), rmtl: scaleCurve(c0Working.rmtl) };
313
+ const arm1Rmst = estimate(c1.rmst.estimate, c1.rmst.se, z), arm0Rmst = estimate(c0.rmst.estimate, c0.rmst.se, z);
314
+ const arm1Rmtl = { estimate: c1.rmtl.estimate, se: c1.rmtl.se,
315
+ confInt: [tauOutput - arm1Rmst.confInt[1], tauOutput - arm1Rmst.confInt[0]] };
316
+ const arm0Rmtl = { estimate: c0.rmtl.estimate, se: c0.rmtl.se,
317
+ confInt: [tauOutput - arm0Rmst.confInt[1], tauOutput - arm0Rmst.confInt[0]] };
318
+ const difference = tableContrast(c1.rmst, c0.rmst, "difference", z);
319
+ const ratio = tableContrast(c1.rmst, c0.rmst, "ratio", z);
320
+ const rmtlRatio = tableContrast(c1.rmtl, c0.rmtl, "rmtlRatio", z);
321
+ const result = { tau: tauOutput, tauDefault, confLevel, arm1: { rmst: arm1Rmst, rmtl: arm1Rmtl },
322
+ arm0: { rmst: arm0Rmst, rmtl: arm0Rmtl }, difference, ratio, rmtlRatio, warnings };
323
+ if (X) {
324
+ const names = options.covariateNames === undefined
325
+ ? (vectorCovariate ? ["covariates"] : Array.from({ length: X[0].length }, () => ""))
326
+ : Array.from(options.covariateNames);
327
+ if (names.some(name => typeof name !== "string"))
328
+ throw new TypeError("'covariateNames' must contain strings");
329
+ if (names.length !== X[0].length)
330
+ throw new RangeError("'covariateNames' must have one name per covariate column");
331
+ const adjustedRows = rows.map(r => ({ ...r, time: Math.min(r.time, tau), status: r.time >= tau ? 1 : r.status }));
332
+ const yRmst = adjustedRows.map(r => r.time), yRmtl = adjustedRows.map(r => tau - r.time);
333
+ const fD = adjustedFit(adjustedRows, tau, yRmst, false, names, z);
334
+ const noRmst = !(c1.rmst.estimate > 0 && c0.rmst.estimate > 0), noRmtl = !(c1.rmtl.estimate > 0 && c0.rmtl.estimate > 0);
335
+ const fR = noRmst ? undefined : adjustedFit(adjustedRows, tau, yRmst, true, names, z);
336
+ const fL = noRmtl ? undefined : adjustedFit(adjustedRows, tau, yRmtl, true, names, z);
337
+ const get = (f, log) => {
338
+ const b = f.coef[1], se = Math.sqrt(Math.max(0, f.cov[1][1]));
339
+ return log ? { estimate: Math.exp(b), confInt: [Math.exp(b - z * se), Math.exp(b + z * se)], pValue: pTwoSided(b / se) } :
340
+ { estimate: b * timeScale, confInt: [(b - z * se) * timeScale, (b + z * se) * timeScale], pValue: pTwoSided(b / se) };
341
+ };
342
+ const scaleLinearTable = (table) => ({
343
+ ...table, estimate: table.estimate.map(v => v * timeScale), se: table.se.map(v => v * timeScale),
344
+ confInt: [table.confInt[0].map(v => v * timeScale), table.confInt[1].map(v => v * timeScale)],
345
+ });
346
+ const restoreLogIntercept = (table) => ({
347
+ ...table, estimate: table.estimate.map((v, i) => i === 0 ? v + Math.log(timeScale) : v),
348
+ confInt: [table.confInt[0].map((v, i) => i === 0 ? v + Math.log(timeScale) : v),
349
+ table.confInt[1].map((v, i) => i === 0 ? v + Math.log(timeScale) : v)],
350
+ });
351
+ const unavailable = { names: ["intercept", "arm", ...names],
352
+ estimate: Array(fD.coef.length).fill(NaN), se: Array(fD.coef.length).fill(NaN),
353
+ z: Array(fD.coef.length).fill(NaN), pValue: Array(fD.coef.length).fill(NaN),
354
+ confInt: [Array(fD.coef.length).fill(NaN), Array(fD.coef.length).fill(NaN)] };
355
+ const undefinedRatio = { estimate: NaN, confInt: [NaN, NaN], pValue: NaN };
356
+ result.adjusted = { difference: get(fD, false), ratio: noRmst ? undefinedRatio : get(fR, true),
357
+ rmtlRatio: noRmtl ? undefinedRatio : get(fL, true) };
358
+ result.coefficients = { difference: scaleLinearTable(fD.table),
359
+ ratio: fR ? restoreLogIntercept(fR.table) : unavailable,
360
+ rmtlRatio: fL ? restoreLogIntercept(fL.table) : unavailable };
361
+ delete result.arm1;
362
+ delete result.arm0;
363
+ }
364
+ return reported("rmst2", result);
365
+ }
@@ -39,11 +39,11 @@ export interface SurvdiffResult {
39
39
  warnings: string[];
40
40
  }
41
41
  /**
42
- * Confidence interval type of {@link survfit}.
42
+ * Confidence interval type of {@link survfit}. The unambiguous prefixes "p", "a", "n", "log-", and "logi" are accepted.
43
43
  *
44
44
  * @category Survival analysis
45
45
  */
46
- export type SurvfitConfType = "log" | "plain" | "log-log";
46
+ export type SurvfitConfType = "log" | "plain" | "log-log" | "logit" | "arcsin" | "none" | "p" | "a" | "n" | "log-" | "logi";
47
47
  /**
48
48
  * Options for {@link survfit}.
49
49
  *
@@ -52,7 +52,21 @@ export type SurvfitConfType = "log" | "plain" | "log-log";
52
52
  export interface SurvfitOptions {
53
53
  /** Group labels, one per observation: one curve per group. Omitted: a single curve. */
54
54
  group?: readonly GroupLabel[];
55
- /** Transformation of the pointwise confidence intervals. Default `"log"`. */
55
+ /** Start times for counting-process data; `time` contains the stop times. */
56
+ start?: readonly number[];
57
+ /** Subject identifiers for counting-process data; requires `start`; adjacent split rows are not censorings. */
58
+ id?: readonly (GroupLabel | null)[];
59
+ /** Case weights. Non-negative safe-integer counts are required. */
60
+ weights?: readonly number[];
61
+ /** Cumulative hazard estimator: 1 Nelson-Aalen, 2 Fleming-Harrington. Default 1. */
62
+ ctype?: 1 | 2;
63
+ /** Survival estimator: 1 Kaplan-Meier, 2 exponential of cumulative hazard. Default 1. */
64
+ stype?: 1 | 2;
65
+ /** Use the infinitesimal-jackknife variance. Default false; non-integer weights are rejected. */
66
+ robust?: boolean;
67
+ /** Restricted-mean upper limit: "common" (default), "individual", "none", or a finite number. */
68
+ rmean?: "none" | "common" | "individual" | number;
69
+ /** Transformation of the pointwise confidence intervals. Default "log". */
56
70
  confType?: SurvfitConfType;
57
71
  /** Confidence level. Default 0.95. */
58
72
  confInt?: number;
@@ -63,33 +77,57 @@ export interface SurvfitOptions {
63
77
  * @category Survival analysis
64
78
  */
65
79
  export interface SurvfitResult {
66
- /** Stratum of each row (`"group=<label>"`, or `"all"` for a single curve) */
80
+ /** Stratum label for every time row. */
67
81
  strata: string[];
68
- /** Time of each row (the distinct times of the stratum, censored ones included) */
82
+ /** Distinct observed times, including censoring times. */
69
83
  time: number[];
70
- /** Number at risk just before the time (R's `n.risk`) */
84
+ /** Weighted number at risk just before each time. */
71
85
  nRisk: number[];
72
- /** Number of events at the time (R's `n.event`) */
86
+ /** Weighted number of events at each time. */
73
87
  nEvent: number[];
74
- /** Number censored at the time (R's `n.censor`) */
88
+ /** Weighted number censored at each time. */
75
89
  nCensor: number[];
76
- /** Kaplan-Meier estimate S(t) */
90
+ /** Survival estimate: Kaplan-Meier (`stype: 1`) or exp(-cumhaz) (`stype: 2`). */
77
91
  surv: number[];
78
- /** Standard error of S(t) (S times the standard error of log S) */
92
+ /** Standard error of the survival estimate (the summary standard error). */
79
93
  stdErr: number[];
80
- /** Alias of `stdErr`: the same array. */
94
+ /** Alias of `stdErr`. */
81
95
  stdError: number[];
82
- /**
83
- * Lower limit of the pointwise confidence interval of S(t) (where S(t) = 1, 1 for each `confType`; with `"log-log"`
84
- * as survival 3.8-12, NA before it)
85
- */
96
+ /** Lower and upper pointwise confidence limits. */
86
97
  lower: number[];
87
- /** Upper limit of the pointwise confidence interval of S(t) */
88
98
  upper: number[];
89
- /** Per stratum, [median, lower limit, upper limit] (NaN for R's NA) */
99
+ /** Cumulative hazard and its standard error. */
100
+ cumhaz: number[];
101
+ stdChaz: number[];
102
+ /** Whether the standard error is on the log-survival scale. */
103
+ logse: boolean;
104
+ /** Number of retained records per stratum. */
105
+ n: number[];
106
+ /** Unweighted risk/event/censor counts, present when case weights were supplied. */
107
+ counts?: {
108
+ nRisk: number[];
109
+ nEvent: number[];
110
+ nCensor: number[];
111
+ };
112
+ /** Summary-table record count, maximum risk set, starting risk set and weighted event total. */
113
+ records: number[];
114
+ nMax: number[];
115
+ nStart: number[];
116
+ events: number[];
117
+ /** Restricted mean survival time and its standard error per stratum (NaN when rmean is "none"). */
118
+ rmean: number[];
119
+ seRmean: number[];
120
+ /** Per stratum: median, lower median limit, upper median limit. */
90
121
  median: number[][];
91
- /** The strata of `median` */
92
122
  medianRows: string[];
123
+ /** R-style summary table, with column and row names. */
124
+ table: {
125
+ colNames: string[];
126
+ rowNames: string[];
127
+ table: number[][];
128
+ };
129
+ /** Warnings produced by the fit. */
130
+ warnings: string[];
93
131
  }
94
132
  /**
95
133
  * Test of the difference between survival curves: the G-rho family of Harrington and Fleming, the log-rank test for
@@ -97,7 +135,7 @@ export interface SurvfitResult {
97
135
  *
98
136
  * Rows with a missing time, status or group are dropped.
99
137
  *
100
- * @param time Follow-up times.
138
+ * @param time Follow-up times, or stop times when `options.start` is supplied.
101
139
  * @param status 1 for an event, 0 for a censored time.
102
140
  * @param group Group labels, one per observation.
103
141
  * @param options See {@link SurvdiffOptions}.
@@ -113,15 +151,18 @@ export interface SurvfitResult {
113
151
  */
114
152
  export declare function survdiff(time: readonly number[], status: readonly number[], group: readonly (GroupLabel | null)[], options?: SurvdiffOptions): SurvdiffResult;
115
153
  /**
116
- * Kaplan-Meier estimate of the survival function with Greenwood's standard error and pointwise confidence intervals.
117
- * Equivalent to R's `survival::survfit()`. As `summary(survfit(Surv(time, status) ~ group, conf.type, conf.int),
118
- * censored = TRUE)`, with the medians and their confidence limits of `summary(fit)$table`.
154
+ * Kaplan-Meier or exponential cumulative-hazard estimate with pointwise confidence intervals, medians and restricted means.
155
+ * Equivalent to R's `survival::survfit()`. Supports right-censored and counting-process data, Nelson-Aalen and Fleming-Harrington cumulative hazards,
156
+ * integer case weights, infinitesimal-jackknife standard errors and all six confidence transformations.
119
157
  *
120
- * Rows with a missing time, status or group are dropped.
158
+ * Rows with a missing time, status, group, id or weight are dropped. With `start`, the risk set at t is
159
+ * `start < t <= time`; without `id`, each split row ending without an event is a censoring. With `id`, a row
160
+ * followed by another row for the same subject at the same boundary is not a censoring.
121
161
  *
122
- * @param time Follow-up times.
162
+ * @param time Follow-up times, or stop times when `options.start` is supplied.
123
163
  * @param status 1 for an event, 0 for a censored time.
124
164
  * @param options See {@link SurvfitOptions}.
165
+ * @returns Time-row estimates, pointwise limits, per-stratum medians and restricted-mean summaries.
125
166
  *
126
167
  * @example
127
168
  * ```ts