@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,67 @@
1
+ import type { CoxphResult } from "./coxph.js";
2
+ /** Transform names and custom functions accepted by coxZph.
3
+ * @category Survival analysis
4
+ */
5
+ export type CoxZphTransform = "km" | "rank" | "identity" | "log" | ((times: readonly number[]) => readonly number[]);
6
+ /** Term grouping accepted by coxZph; use `collapseTerms: false` to retain individual columns within groups.
7
+ * @category Survival analysis
8
+ */
9
+ export type CoxZphTerms = readonly (readonly number[])[] | false;
10
+ /**
11
+ * Options for Schoenfeld-residual tests of proportional hazards.
12
+ *
13
+ * @category Survival analysis
14
+ */
15
+ export interface CoxZphOptions {
16
+ /** Transform of the merged stop times. Default `"km"`; a function receives all used rows in input order. */
17
+ transform?: CoxZphTransform;
18
+ /** Zero-based column groups defining formula terms; false makes each column its own term. A multi-column group is collapsed by default. */
19
+ terms?: CoxZphTerms;
20
+ /** Keep grouped columns separate in y, var and the test table. Default true. */
21
+ collapseTerms?: boolean;
22
+ /** Include the global test row. Default true. */
23
+ global?: boolean;
24
+ }
25
+ /**
26
+ * Result of the proportional-hazards test.
27
+ *
28
+ * @category Survival analysis
29
+ */
30
+ export interface CoxZphResult {
31
+ /** Names of the tested terms, with GLOBAL last when requested. */
32
+ rowNames: string[];
33
+ /** Chi-squared statistics, with GLOBAL last when requested. */
34
+ chisq: number[];
35
+ /** Degrees of freedom. */
36
+ df: number[];
37
+ /** Upper chi-squared probabilities. */
38
+ p: number[];
39
+ /** Alias of p. */
40
+ pValue: number[];
41
+ /** Transformed times at the event rows. */
42
+ x: number[];
43
+ /** Event times in the fit's merged time scale. */
44
+ time: number[];
45
+ /** Stratum labels at event rows, only when the fit had strata. */
46
+ strata?: string[];
47
+ /** Scaled Schoenfeld residuals, one row per event. */
48
+ y: number[][];
49
+ /** Variance matrix for y. */
50
+ var: number[][];
51
+ /** Transform used. */
52
+ transform: CoxZphTransform;
53
+ /** Warnings of the fit and this call. */
54
+ warnings: string[];
55
+ }
56
+ /**
57
+ * Tests the proportional-hazards assumption using the score test of Grambsch and Therneau (1994).
58
+ * Equivalent to R's `survival::cox.zph()`. The fit retains its processed rows privately, so no refit is performed; robust and clustered
59
+ * variances of the fit are not used.
60
+ *
61
+ * @param fit A result returned by `coxph`.
62
+ * @param options See {@link CoxZphOptions}.
63
+ * @throws Error for no events, fewer than two distinct event times, a constant transform, or singular information.
64
+ *
65
+ * @category Survival analysis
66
+ */
67
+ export declare function coxZph(fit: CoxphResult, options?: CoxZphOptions): CoxZphResult;
@@ -0,0 +1,479 @@
1
+ import { pchisq } from "../distributions/chisq.js";
2
+ import { levelText } from "../internal/levels.js";
3
+ import { ldexp, ldexpWide } from "../internal/summary.js";
4
+ import { reported } from "../internal/warnings.js";
5
+ import { solve } from "../linalg/solve.js";
6
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
7
+ import { checkOptions } from "../internal/checkOptions.js";
8
+ const COX_ZPH_KEYS = ["transform", "terms", "collapseTerms", "global"];
9
+ const zeros = (n) => new Array(n).fill(0);
10
+ const square = (n) => Array.from({ length: n }, () => zeros(n));
11
+ function rankAverage(values) {
12
+ const order = Array.from({ length: values.length }, (_, i) => i).sort((a, b) => values[a] - values[b] || a - b);
13
+ const out = new Array(values.length);
14
+ for (let i = 0; i < order.length;) {
15
+ let j = i + 1;
16
+ while (j < order.length && values[order[j]] === values[order[i]])
17
+ j++;
18
+ const rank = (i + 1 + j) / 2;
19
+ for (let k = i; k < j; k++)
20
+ out[order[k]] = rank;
21
+ i = j;
22
+ }
23
+ return out;
24
+ }
25
+ function lowerBound(sorted, value) {
26
+ let lo = 0;
27
+ let hi = sorted.length;
28
+ while (lo < hi) {
29
+ const mid = Math.floor((lo + hi) / 2);
30
+ if (sorted[mid] < value)
31
+ lo = mid + 1;
32
+ else
33
+ hi = mid;
34
+ }
35
+ return lo;
36
+ }
37
+ function kmTransform(data) {
38
+ const n = data.time.length;
39
+ const out = new Array(n);
40
+ const byTime = new Map();
41
+ for (let i = 0; i < n; i++) {
42
+ const t = data.time[i];
43
+ const group = byTime.get(t) ?? { rows: [], deaths: 0 };
44
+ group.rows.push(i);
45
+ if (data.status[i])
46
+ group.deaths++;
47
+ byTime.set(t, group);
48
+ }
49
+ const times = [...byTime.keys()].sort((a, b) => a - b);
50
+ const sortedStop = data.time.slice().sort((a, b) => a - b);
51
+ const sortedStart = (data.start ?? new Array(n).fill(-Infinity)).slice().sort((a, b) => a - b);
52
+ let survival = 1;
53
+ for (const t of times) {
54
+ const group = byTime.get(t);
55
+ for (const i of group.rows)
56
+ out[i] = 1 - survival;
57
+ const risk = lowerBound(sortedStart, t) - lowerBound(sortedStop, t);
58
+ if (group.deaths > 0)
59
+ survival *= 1 - group.deaths / risk;
60
+ }
61
+ return out;
62
+ }
63
+ function transformTimes(data, transform, eventInput, warnings) {
64
+ let values;
65
+ if (typeof transform === "function") {
66
+ const returned = transform(data.time.slice());
67
+ if (!Array.isArray(returned) || returned.length !== data.time.length) {
68
+ throw new RangeError("transform function must return one value per observation");
69
+ }
70
+ values = Array.from(returned);
71
+ }
72
+ else if (transform === "km") {
73
+ values = kmTransform(data);
74
+ }
75
+ else if (transform === "rank") {
76
+ values = rankAverage(data.time);
77
+ }
78
+ else if (transform === "identity") {
79
+ values = data.time.slice();
80
+ }
81
+ else if (transform === "log") {
82
+ if (data.time.some((t) => t < 0))
83
+ warnings.push("NaNs produced");
84
+ values = data.time.map(Math.log);
85
+ }
86
+ else {
87
+ throw new RangeError("Unrecognized transform");
88
+ }
89
+ for (const i of eventInput) {
90
+ if (!Number.isFinite(values[i]))
91
+ throw new RangeError("transform must be finite at every event time");
92
+ }
93
+ return values;
94
+ }
95
+ /**
96
+ * Tests the proportional-hazards assumption using the score test of Grambsch and Therneau (1994).
97
+ * Equivalent to R's `survival::cox.zph()`. The fit retains its processed rows privately, so no refit is performed; robust and clustered
98
+ * variances of the fit are not used.
99
+ *
100
+ * @param fit A result returned by `coxph`.
101
+ * @param options See {@link CoxZphOptions}.
102
+ * @throws Error for no events, fewer than two distinct event times, a constant transform, or singular information.
103
+ *
104
+ * @category Survival analysis
105
+ */
106
+ export function coxZph(fit, options = {}) {
107
+ checkOptions(options, COX_ZPH_KEYS, "coxZph"); // generated: option-keys.mjs
108
+ checkOptions(options, COX_ZPH_KEYS, "coxZph");
109
+ const transform = options.transform ?? "km";
110
+ const global = options.global ?? true;
111
+ const collapse = options.collapseTerms ?? true;
112
+ if (typeof global !== "boolean")
113
+ throw new TypeError("'global' must be a boolean");
114
+ if (typeof collapse !== "boolean")
115
+ throw new TypeError("'collapseTerms' must be a boolean");
116
+ if (options.terms !== undefined && options.terms !== false && !Array.isArray(options.terms)) {
117
+ throw new TypeError("'terms' must be an array of column groups or false");
118
+ }
119
+ if (fit.nevent === 0)
120
+ throw new Error("the proportional-hazards test requires events");
121
+ const data = fit.coxZphData;
122
+ if (data === undefined)
123
+ throw new TypeError("coxZph requires a CoxphResult returned by coxph");
124
+ const columns = fit.coefficients.map((v, i) => (Number.isNaN(v) ? -1 : i)).filter((i) => i >= 0);
125
+ const p = columns.length;
126
+ if (p === 0)
127
+ throw new Error("the proportional-hazards test has no estimable coefficients");
128
+ const eventInput = [];
129
+ for (let lo = 0; lo < data.sortedTime.length;) {
130
+ let hi = lo;
131
+ while (!data.stratumEnd[hi])
132
+ hi++;
133
+ for (let i = lo; i <= hi;) {
134
+ const t = data.sortedTime[i];
135
+ let end = i;
136
+ while (end < hi && data.sortedTime[end + 1] === t)
137
+ end++;
138
+ const deaths = [];
139
+ for (let j = i; j <= end; j++)
140
+ if (data.sortedEvent[j])
141
+ deaths.push(j);
142
+ if (data.start !== undefined)
143
+ deaths.reverse();
144
+ for (const j of deaths)
145
+ eventInput.push(data.sortedToInput[j]);
146
+ i = end + 1;
147
+ }
148
+ lo = hi + 1;
149
+ }
150
+ if (eventInput.length === 0)
151
+ throw new Error("the proportional-hazards test requires events");
152
+ const eventTimes = eventInput.map((i) => data.time[i]);
153
+ if (new Set(eventTimes).size < 2)
154
+ throw new Error("the test needs events at two or more distinct times");
155
+ const warnings = [...fit.warnings];
156
+ const gInput = transformTimes(data, transform, eventInput, warnings);
157
+ const firstEventG = gInput[eventInput[0]];
158
+ if (eventInput.every((i) => gInput[i] === firstEventG)) {
159
+ throw new Error("the transform is constant at the event times");
160
+ }
161
+ const maxG = eventInput.reduce((max, i) => Math.max(max, Math.abs(gInput[i])), 0);
162
+ const gExp = maxG === 0 ? 0 : Math.floor(Math.log2(maxG));
163
+ const gScaled = gInput.map((v) => (Number.isFinite(v) ? ldexp(v, -gExp) : v));
164
+ const gMean = eventInput.reduce((sum, i) => sum + gScaled[i], 0) / eventInput.length;
165
+ const gCentered = gScaled.map((v) => v - gMean);
166
+ if (eventInput.every((i) => gCentered[i] === 0))
167
+ throw new Error("the transform is constant at the event times");
168
+ const beta = columns.map((j) => data.betaScaled[j]);
169
+ const info = square(p);
170
+ const cross = square(p);
171
+ const thetaInfo = square(p);
172
+ const U = zeros(p);
173
+ const events = [];
174
+ for (let lo = 0; lo < data.sortedTime.length;) {
175
+ let hi = lo;
176
+ while (!data.stratumEnd[hi])
177
+ hi++;
178
+ for (let i = lo; i <= hi;) {
179
+ const t = data.sortedTime[i];
180
+ let end = i;
181
+ while (end < hi && data.sortedTime[end + 1] === t)
182
+ end++;
183
+ const deaths = [];
184
+ for (let j = i; j <= end; j++)
185
+ if (data.sortedEvent[j])
186
+ deaths.push(j);
187
+ if (deaths.length > 0) {
188
+ const risk = [];
189
+ let shift = -Infinity;
190
+ for (let j = lo; j <= hi; j++) {
191
+ const atRisk = data.sortedStart === undefined
192
+ ? data.sortedTime[j] >= t
193
+ : data.sortedStart[j] < t && data.sortedTime[j] >= t;
194
+ if (!atRisk)
195
+ continue;
196
+ risk.push(j);
197
+ let eta = 0;
198
+ for (let k = 0; k < p; k++)
199
+ eta += beta[k] * data.sortedX[j][columns[k]];
200
+ shift = Math.max(shift, eta);
201
+ }
202
+ if (risk.length === 0 || !Number.isFinite(shift))
203
+ throw new Error("empty Cox proportional-hazards risk set");
204
+ const S1 = zeros(p);
205
+ const S2 = square(p);
206
+ const E1 = zeros(p);
207
+ const E2 = square(p);
208
+ let S0 = 0;
209
+ let E0 = 0;
210
+ for (const j of risk) {
211
+ let eta = 0;
212
+ for (let k = 0; k < p; k++)
213
+ eta += beta[k] * data.sortedX[j][columns[k]];
214
+ const wr = data.sortedWeight[j] * Math.exp(eta - shift);
215
+ S0 += wr;
216
+ for (let a = 0; a < p; a++) {
217
+ const xa = data.sortedX[j][columns[a]];
218
+ S1[a] += wr * xa;
219
+ for (let b = 0; b < p; b++)
220
+ S2[a][b] += wr * xa * data.sortedX[j][columns[b]];
221
+ }
222
+ if (data.sortedEvent[j] && data.sortedTime[j] === t) {
223
+ E0 += wr;
224
+ for (let a = 0; a < p; a++) {
225
+ const xa = data.sortedX[j][columns[a]];
226
+ E1[a] += wr * xa;
227
+ for (let b = 0; b < p; b++)
228
+ E2[a][b] += wr * xa * data.sortedX[j][columns[b]];
229
+ }
230
+ }
231
+ }
232
+ let dw = 0;
233
+ const eventSum = zeros(p);
234
+ for (const j of deaths) {
235
+ const w = data.sortedWeight[j];
236
+ dw += w;
237
+ for (let a = 0; a < p; a++)
238
+ eventSum[a] += w * data.sortedX[j][columns[a]];
239
+ }
240
+ const d = deaths.length;
241
+ const steps = data.ties === "efron" && d > 1 ? d : 1;
242
+ const xbar = zeros(p);
243
+ const V = square(p);
244
+ for (let m = 0; m < steps; m++) {
245
+ const f = m / steps;
246
+ const denom = S0 - f * E0;
247
+ const xb = S1.map((v, k) => (v - f * E1[k]) / denom);
248
+ for (let a = 0; a < p; a++)
249
+ xbar[a] += xb[a] / steps;
250
+ const factor = dw / steps;
251
+ for (let a = 0; a < p; a++)
252
+ for (let b = 0; b < p; b++) {
253
+ V[a][b] += factor * ((S2[a][b] - f * E2[a][b]) / denom - xb[a] * xb[b]);
254
+ }
255
+ }
256
+ const score = eventSum.map((v, k) => v - dw * xbar[k]);
257
+ const input = data.sortedToInput[deaths[0]];
258
+ const g = gCentered[input];
259
+ for (let a = 0; a < p; a++) {
260
+ U[a] += g * score[a];
261
+ for (let b = 0; b < p; b++) {
262
+ info[a][b] += V[a][b];
263
+ cross[a][b] += g * V[a][b];
264
+ thetaInfo[a][b] += g * g * V[a][b];
265
+ }
266
+ }
267
+ if (data.start !== undefined)
268
+ deaths.reverse();
269
+ for (const j of deaths) {
270
+ const rowInput = data.sortedToInput[j];
271
+ const residual = columns.map((col) => data.sortedX[j][col]);
272
+ for (let a = 0; a < p; a++)
273
+ residual[a] -= xbar[a];
274
+ events.push({
275
+ input: rowInput,
276
+ time: t,
277
+ stratum: data.stratumIndex[j],
278
+ g: gInput[rowInput],
279
+ residual,
280
+ });
281
+ }
282
+ }
283
+ i = end + 1;
284
+ }
285
+ lo = hi + 1;
286
+ }
287
+ let solved;
288
+ try {
289
+ solved = solve(info, cross);
290
+ }
291
+ catch {
292
+ throw new Error("the proportional-hazards information is singular");
293
+ }
294
+ const M = square(p);
295
+ for (let a = 0; a < p; a++)
296
+ for (let b = 0; b < p; b++) {
297
+ let correction = 0;
298
+ for (let k = 0; k < p; k++)
299
+ correction += cross[k][a] * solved[k][b];
300
+ M[a][b] = thetaInfo[a][b] - correction;
301
+ }
302
+ for (let a = 0; a < p; a++)
303
+ for (let b = 0; b < a; b++) {
304
+ const v = (M[a][b] + M[b][a]) / 2;
305
+ M[a][b] = v;
306
+ M[b][a] = v;
307
+ }
308
+ const sourceGroups = options.terms === false || options.terms === undefined ? columns.map((j) => [j]) : options.terms;
309
+ const seen = new Set();
310
+ const groups = [];
311
+ const groupSourceIndex = [];
312
+ sourceGroups.forEach((group, gi) => {
313
+ if (!Array.isArray(group) || group.length === 0)
314
+ throw new RangeError("each terms group must be a non-empty array");
315
+ const kept = [];
316
+ for (const col of group) {
317
+ if (!Number.isInteger(col) || col < 0 || col >= fit.coefficients.length) {
318
+ throw new RangeError("terms column indices must be zero-based and within x");
319
+ }
320
+ if (seen.has(col))
321
+ throw new RangeError("terms groups must not overlap");
322
+ seen.add(col);
323
+ if (columns.includes(col))
324
+ kept.push(col);
325
+ }
326
+ if (kept.length > 0) {
327
+ groups.push(kept);
328
+ groupSourceIndex.push(gi);
329
+ }
330
+ });
331
+ columns.forEach((col) => {
332
+ if (!seen.has(col)) {
333
+ groups.push([col]);
334
+ groupSourceIndex.push(sourceGroups.length);
335
+ }
336
+ });
337
+ if (groups.length === 0)
338
+ throw new Error("the proportional-hazards test has no estimable terms");
339
+ const expanded = [];
340
+ groups.forEach((group, gi) => {
341
+ if (collapse && group.length > 1) {
342
+ expanded.push({ col: -1, group: gi, collapsed: true });
343
+ }
344
+ else {
345
+ for (const col of group)
346
+ expanded.push({ col, group: gi, collapsed: false });
347
+ }
348
+ });
349
+ const q = expanded.length;
350
+ const L = Array.from({ length: p }, () => zeros(q));
351
+ const intercept = [];
352
+ const rowNames = [];
353
+ expanded.forEach((term, j) => {
354
+ const group = groups[term.group];
355
+ const sourceIndex = groupSourceIndex[term.group];
356
+ if (term.collapsed) {
357
+ for (const col of group) {
358
+ const k = columns.indexOf(col);
359
+ L[k][j] = beta[k];
360
+ }
361
+ intercept.push(1);
362
+ rowNames.push(`g${sourceIndex + 1}`);
363
+ }
364
+ else {
365
+ const k = columns.indexOf(term.col);
366
+ L[k][j] = data.inverseCovariateScale[term.col];
367
+ intercept.push(fit.coefficients[term.col]);
368
+ rowNames.push(group.length > 1 ? `g${sourceIndex + 1}x${term.col + 1}` : `x${term.col + 1}`);
369
+ }
370
+ });
371
+ // Scale each column of L by an exact power of two before forming L' I L. The terms can be in very different
372
+ // covariate units (e.g. a covariate multiplied by 2^40); solving the unscaled J makes the condition check depend
373
+ // on those units even though the test and the residuals are well-defined.
374
+ const columnExp = Array.from({ length: q }, (_, j) => {
375
+ let max = 0;
376
+ for (let k = 0; k < p; k++)
377
+ max = Math.max(max, Math.abs(L[k][j]));
378
+ if (!(max > 0 && Number.isFinite(max)))
379
+ throw new Error("the proportional-hazards residual variance is singular");
380
+ return Math.floor(Math.log2(max));
381
+ });
382
+ const scaledL = L.map((row) => row.map((v, j) => ldexp(v, -columnExp[j])));
383
+ const IL = Array.from({ length: p }, () => zeros(q));
384
+ for (let a = 0; a < p; a++)
385
+ for (let j = 0; j < q; j++) {
386
+ for (let b = 0; b < p; b++)
387
+ IL[a][j] += info[a][b] * scaledL[b][j];
388
+ }
389
+ const J = square(q);
390
+ for (let a = 0; a < q; a++)
391
+ for (let b = 0; b < q; b++) {
392
+ for (let k = 0; k < p; k++)
393
+ J[a][b] += scaledL[k][a] * IL[k][b];
394
+ }
395
+ for (let a = 0; a < q; a++)
396
+ for (let b = 0; b < a; b++) {
397
+ const v = (J[a][b] + J[b][a]) / 2;
398
+ J[a][b] = v;
399
+ J[b][a] = v;
400
+ }
401
+ let Jinv;
402
+ try {
403
+ Jinv = solve(J);
404
+ }
405
+ catch {
406
+ throw new Error("the proportional-hazards residual variance is singular");
407
+ }
408
+ for (let a = 0; a < q; a++)
409
+ for (let b = 0; b < a; b++) {
410
+ const v = (Jinv[a][b] + Jinv[b][a]) / 2;
411
+ Jinv[a][b] = v;
412
+ Jinv[b][a] = v;
413
+ }
414
+ // J_original^-1 = D J_scaled^-1 D, D_j = 2^-columnExp[j]. The fit's weights are
415
+ // divided by 2^weightExp, so that exponent is restored here too.
416
+ const variance = Jinv.map((row, i) => row.map((v, j) => eventInput.length * ldexpWide(v, -columnExp[i] - columnExp[j] - data.weightExp)));
417
+ const y = events.map((event) => {
418
+ const ls = zeros(q);
419
+ for (let a = 0; a < q; a++)
420
+ for (let k = 0; k < p; k++)
421
+ ls[a] += scaledL[k][a] * event.residual[k];
422
+ return intercept.map((b, j) => {
423
+ let delta = 0;
424
+ for (let k = 0; k < q; k++)
425
+ delta += ls[k] * Jinv[k][j];
426
+ return b + eventInput.length * ldexpWide(delta, -columnExp[j] - data.weightExp);
427
+ });
428
+ });
429
+ // U and M above use weights divided by 2^weightExp. Since U' M^-1 U is linear in a common weight multiplier,
430
+ // restore that factor for the reported score-test statistic (the y and var outputs restore its inverse below).
431
+ const chisq = [];
432
+ const df = [];
433
+ const pValues = [];
434
+ const testGroups = expanded.map((term) => term.collapsed ? groups[term.group].map((col) => columns.indexOf(col)) : [columns.indexOf(term.col)]);
435
+ for (const group of testGroups) {
436
+ const sub = group.map((a) => group.map((b) => M[a][b]));
437
+ const u = group.map((a) => U[a]);
438
+ let estimate;
439
+ try {
440
+ estimate = solve(sub, u);
441
+ }
442
+ catch {
443
+ throw new Error("the proportional-hazards term information is singular");
444
+ }
445
+ const stat = ldexp(Math.max(0, u.reduce((sum, v, i) => sum + v * estimate[i], 0)), data.weightExp);
446
+ chisq.push(stat);
447
+ df.push(group.length);
448
+ pValues.push(pchisq(stat, group.length, { lowerTail: false }));
449
+ }
450
+ if (global) {
451
+ let estimate;
452
+ try {
453
+ estimate = solve(M, U);
454
+ }
455
+ catch {
456
+ throw new Error("the global proportional-hazards information is singular");
457
+ }
458
+ const stat = ldexp(Math.max(0, U.reduce((sum, v, i) => sum + v * estimate[i], 0)), data.weightExp);
459
+ chisq.push(stat);
460
+ df.push(p);
461
+ pValues.push(pchisq(stat, p, { lowerTail: false }));
462
+ rowNames.push("GLOBAL");
463
+ }
464
+ const result = {
465
+ rowNames,
466
+ chisq,
467
+ df,
468
+ p: pValues,
469
+ pValue: pValues,
470
+ x: events.map((event) => event.g),
471
+ time: events.map((event) => event.time),
472
+ ...(data.strata === undefined ? {} : { strata: events.map((event) => levelText(data.strata[event.input])) }),
473
+ y,
474
+ var: variance,
475
+ transform,
476
+ warnings,
477
+ };
478
+ return reported("coxZph", result, fit);
479
+ }