@numero-uno-jpn/rstats 0.8.0 → 0.10.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 (122) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.ja.md +89 -13
  3. package/README.md +90 -13
  4. package/THIRD_PARTY_NOTICES.md +12 -2
  5. package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
  6. package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
  7. package/dist/chunks/chunk-7HPVUVZB.js +2 -0
  8. package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
  9. package/dist/chunks/chunk-ENL43FNO.js +2 -0
  10. package/dist/chunks/chunk-EWC6I75B.js +2 -0
  11. package/dist/chunks/chunk-IT354SHV.js +3 -0
  12. package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
  13. package/dist/chunks/chunk-O6PT7IVU.js +2 -0
  14. package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
  15. package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
  16. package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
  17. package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
  18. package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
  19. package/dist/descriptive/factanal.d.ts +56 -0
  20. package/dist/descriptive/factanal.js +186 -0
  21. package/dist/descriptive/omega.d.ts +56 -0
  22. package/dist/descriptive/omega.js +323 -0
  23. package/dist/descriptive.js +2 -2
  24. package/dist/distributions/bvnorm.d.ts +15 -0
  25. package/dist/distributions/bvnorm.js +131 -0
  26. package/dist/distributions/nbeta.js +34 -1
  27. package/dist/distributions/nchisq.d.ts +10 -0
  28. package/dist/distributions/nchisq.js +46 -0
  29. package/dist/distributions.js +2 -2
  30. package/dist/entries/distributions.d.ts +1 -0
  31. package/dist/entries/distributions.js +1 -0
  32. package/dist/entries/linalg.d.ts +2 -0
  33. package/dist/entries/linalg.js +2 -0
  34. package/dist/entries/numerics.d.ts +2 -0
  35. package/dist/entries/numerics.js +1 -0
  36. package/dist/entries/tests.d.ts +25 -1
  37. package/dist/entries/tests.js +22 -1
  38. package/dist/htest/agreement.d.ts +141 -0
  39. package/dist/htest/agreement.js +274 -0
  40. package/dist/htest/aov.d.ts +19 -0
  41. package/dist/htest/aov.js +22 -15
  42. package/dist/htest/core/simulate.d.ts +2 -0
  43. package/dist/htest/core/simulate.js +1 -1
  44. package/dist/htest/dunnett.d.ts +5 -0
  45. package/dist/htest/dunnett.js +89 -0
  46. package/dist/htest/effectSize.d.ts +112 -0
  47. package/dist/htest/effectSize.js +385 -0
  48. package/dist/htest/leveneTest.d.ts +30 -0
  49. package/dist/htest/leveneTest.js +41 -0
  50. package/dist/htest/multipleComparisons.d.ts +147 -0
  51. package/dist/htest/multipleComparisons.js +369 -0
  52. package/dist/htest/normalityTests.d.ts +44 -0
  53. package/dist/htest/normalityTests.js +164 -0
  54. package/dist/htest/polycor.d.ts +117 -0
  55. package/dist/htest/polycor.js +468 -0
  56. package/dist/htest/power.d.ts +132 -0
  57. package/dist/htest/power.js +227 -0
  58. package/dist/htest/pwr.d.ts +263 -0
  59. package/dist/htest/pwr.js +440 -0
  60. package/dist/htest/rankTests.d.ts +7 -0
  61. package/dist/htest/rankTests.js +11 -1
  62. package/dist/htest/trendTests.d.ts +57 -0
  63. package/dist/htest/trendTests.js +167 -0
  64. package/dist/linalg/eigen.d.ts +8 -0
  65. package/dist/linalg/eigen.js +5 -4
  66. package/dist/linalg/expm.d.ts +48 -0
  67. package/dist/linalg/expm.js +472 -0
  68. package/dist/linalg/schur.d.ts +48 -0
  69. package/dist/linalg/schur.js +225 -0
  70. package/dist/linalg.js +2 -2
  71. package/dist/models/anovaSequential.d.ts +58 -0
  72. package/dist/models/anovaSequential.js +138 -0
  73. package/dist/models/aovEz.d.ts +64 -0
  74. package/dist/models/aovEz.js +332 -0
  75. package/dist/models/aovStrata.d.ts +32 -0
  76. package/dist/models/aovStrata.js +104 -0
  77. package/dist/models/carAnova.d.ts +30 -0
  78. package/dist/models/carAnova.js +121 -0
  79. package/dist/models/coxph.d.ts +101 -0
  80. package/dist/models/coxph.js +502 -0
  81. package/dist/models/ddLeastSquares.d.ts +30 -0
  82. package/dist/models/ddLeastSquares.js +90 -0
  83. package/dist/models/ddMatrix.d.ts +10 -0
  84. package/dist/models/ddMatrix.js +91 -0
  85. package/dist/models/formula.d.ts +83 -0
  86. package/dist/models/formula.js +333 -0
  87. package/dist/models/glm.d.ts +226 -0
  88. package/dist/models/glm.js +546 -0
  89. package/dist/models/glmAnova.d.ts +31 -0
  90. package/dist/models/glmAnova.js +146 -0
  91. package/dist/models/glmConfint.d.ts +25 -0
  92. package/dist/models/glmConfint.js +139 -0
  93. package/dist/models/glmFamily.d.ts +66 -0
  94. package/dist/models/glmFamily.js +359 -0
  95. package/dist/models/lm.d.ts +84 -3
  96. package/dist/models/lm.js +141 -44
  97. package/dist/models/mauchly.d.ts +48 -0
  98. package/dist/models/mauchly.js +123 -0
  99. package/dist/models/modelFrame.d.ts +40 -0
  100. package/dist/models/modelFrame.js +131 -0
  101. package/dist/models/modelMatrix.d.ts +88 -0
  102. package/dist/models/modelMatrix.js +170 -0
  103. package/dist/models/survival.d.ts +87 -0
  104. package/dist/models/survival.js +238 -0
  105. package/dist/numerics.js +2 -2
  106. package/dist/optim/lbfgsb.d.ts +20 -0
  107. package/dist/optim/lbfgsb.js +1240 -0
  108. package/dist/optim/optim.d.ts +85 -0
  109. package/dist/optim/optim.js +610 -0
  110. package/dist/rstats.js +19 -3
  111. package/dist/special.js +2 -2
  112. package/dist/tests.js +18 -3
  113. package/llms.txt +102 -0
  114. package/package.json +3 -2
  115. package/dist/chunks/chunk-EJRCDJ76.js +0 -2
  116. package/dist/chunks/chunk-JERGQKZM.js +0 -2
  117. package/dist/chunks/chunk-JVYV4633.js +0 -2
  118. package/dist/chunks/chunk-LXMMKO26.js +0 -2
  119. package/dist/chunks/chunk-MJQLKEO5.js +0 -2
  120. package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
  121. package/dist/chunks/chunk-SPQC445Q.js +0 -2
  122. package/dist/chunks/chunk-U633VFH3.js +0 -2
@@ -0,0 +1,101 @@
1
+ import type { GroupLabel } from "../htest/groups.js";
2
+ /** Control of the Newton-Raphson iterations of {@link coxph} (R's `coxph.control`). */
3
+ export interface CoxphControl {
4
+ /** Convergence tolerance on the relative change of the log partial likelihood. Default 1e-9. */
5
+ eps?: number;
6
+ /** Maximum number of iterations. Default 20. */
7
+ iterMax?: number;
8
+ /** Tolerance of the pivots of the Cholesky factorisation. Default 2^-39 (eps^0.75 for the machine eps 2^-52). */
9
+ tolerChol?: number;
10
+ /** Tolerance of the check for infinite coefficients. Default sqrt(`eps`). */
11
+ tolerInf?: number;
12
+ }
13
+ /** Options for {@link coxph}. */
14
+ export interface CoxphOptions {
15
+ /** Handling of tied event times. Default `"efron"`. */
16
+ ties?: "efron" | "breslow";
17
+ /** Case weights (positive integers; other weights make R use a robust variance, which is not supported yet). */
18
+ weights?: readonly number[];
19
+ /** Stratum labels, one per observation: a separate baseline hazard per stratum. */
20
+ strata?: readonly (GroupLabel | null)[];
21
+ /** Starting coefficients. Default 0. */
22
+ init?: readonly number[];
23
+ /** See {@link CoxphControl}. */
24
+ control?: CoxphControl;
25
+ /** Covariates whose values all lie in this set are neither centred nor scaled. Default `[-1, 0, 1]`. */
26
+ nocenter?: readonly number[];
27
+ /** Confidence level of the intervals of exp(coef). Default 0.95. */
28
+ confLevel?: number;
29
+ }
30
+ /** A test statistic with its degrees of freedom and upper chi-squared tail. */
31
+ export interface CoxphTest {
32
+ statistic: number;
33
+ df: number;
34
+ pValue: number;
35
+ }
36
+ /** Result of {@link coxph}. */
37
+ export interface CoxphResult {
38
+ /** Coefficients (NaN for R's NA: an aliased column or one whose information fell below the tolerance) */
39
+ coefficients: number[];
40
+ /** Variance matrix of the coefficients (array of rows) */
41
+ var: number[][];
42
+ /** Log partial likelihood at the starting values and at the end */
43
+ loglik: [number, number];
44
+ /** The score test statistic at the starting values */
45
+ score: number;
46
+ /** The Wald statistic of the non-NA coefficients (against `init` when given) */
47
+ wald: number;
48
+ /** Number of iterations (`iterMax + 1` when they ran out) */
49
+ iter: number;
50
+ /** The means used to centre the covariates (0 for the columns not centred) */
51
+ means: number[];
52
+ /** Number of observations used */
53
+ n: number;
54
+ /** Number of events */
55
+ nevent: number;
56
+ /** Linear predictors (centred by the means), one per observation used, in input order */
57
+ linearPredictors: number[];
58
+ /** Standard errors of the coefficients */
59
+ se: number[];
60
+ /** Wald z statistics */
61
+ z: number[];
62
+ /** Two-sided p-values `Pr(>|z|)` */
63
+ p: number[];
64
+ /** Lower confidence limits of exp(coef) */
65
+ lower: number[];
66
+ /** Upper confidence limits of exp(coef) */
67
+ upper: number[];
68
+ /** Likelihood ratio test */
69
+ logtest: CoxphTest;
70
+ /** Score (log-rank) test */
71
+ sctest: CoxphTest;
72
+ /** Wald test */
73
+ waldtest: CoxphTest;
74
+ /** R^2 (1 - exp(-logtest / n)) and its maximum (1 - exp(2 loglik[0] / n)) */
75
+ rsq: {
76
+ rsq: number;
77
+ maxrsq: number;
78
+ };
79
+ /** R's warnings, each once, in order of first appearance. */
80
+ warnings: string[];
81
+ }
82
+ /**
83
+ * Cox proportional hazards regression. Equivalent to R's `coxph(Surv(time, status) ~ x [+ strata(strata)], weights,
84
+ * ties, init, control)` (package survival) for right-censored data, with the values of `summary(fit)`.
85
+ *
86
+ * Rows with a missing time, status, covariate, weight or stratum are dropped. Times within sqrt(eps) of each other are
87
+ * treated as tied. Covariates whose values all lie in `nocenter` are not centred; the others are centred by their
88
+ * weighted means, which only shifts the linear predictors. R's warnings (non-convergence, possibly infinite
89
+ * coefficients) are returned in `warnings`.
90
+ *
91
+ * @param time Follow-up times.
92
+ * @param status 1 for an event, 0 for a censored time.
93
+ * @param x The covariate matrix, one row per observation (at least one column).
94
+ * @param options See {@link CoxphOptions}.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * coxph([5, 3, 8, 1, 9, 4], [1, 1, 0, 1, 0, 1], [[1.2], [0.3], [-0.5], [2], [0.7], [0.1]]).coefficients;
99
+ * ```
100
+ */
101
+ export declare function coxph(time: readonly number[], status: readonly number[], x: readonly (readonly number[])[], options?: CoxphOptions): CoxphResult;
@@ -0,0 +1,502 @@
1
+ // Cox proportional hazards regression for right-censored data with a matrix interface: R's coxph from the survival
2
+ // package (the fit, with Efron's or Breslow's handling of ties, case weights and strata) and the values of
3
+ // summary(fit): the coefficient table, the confidence intervals of exp(coef), the likelihood ratio, score and Wald
4
+ // tests and the R^2 of Nagelkerke's kind.
5
+ //
6
+ // Written for rStats.js (no ported code) from oracle/coxph-behaviour.md (a description of the behaviour of survival
7
+ // 3.8-3) and the published methods: Cox (1972), "Regression models and life-tables", JRSS B 34, 187-220; Efron (1977),
8
+ // "The efficiency of Cox's likelihood function for censored data", JASA 72, 557-565; Breslow (1974), "Covariance
9
+ // analysis of censored survival data", Biometrics 30, 89-99. Newton-Raphson runs on centred and scaled covariates and
10
+ // uses a generalised Cholesky factorisation (LDL' with a tolerance on the pivots) so that aliased columns get NaN
11
+ // (R's NA) coefficients.
12
+ import { pchisq } from "../distributions/chisq.js";
13
+ import { qnorm } from "../distributions/normal.js";
14
+ import { Warnings } from "./glmFamily.js";
15
+ const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
16
+ const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
17
+ /** Times within sqrt(eps) (absolutely or relative to the mean absolute distinct time) merged to the smaller one */
18
+ function mergeTiedTimes(time) {
19
+ const tol = Math.sqrt(2 ** -52);
20
+ const distinct = Array.from(new Set(time.filter((t) => Number.isFinite(t)))).sort((a, b) => a - b);
21
+ if (distinct.length < 2)
22
+ return time.slice();
23
+ let meanAbs = 0;
24
+ for (const y of distinct)
25
+ meanAbs += Math.abs(y);
26
+ meanAbs /= distinct.length;
27
+ const cuts = [distinct[0]];
28
+ for (let k = 0; k + 1 < distinct.length; k++) {
29
+ const gap = distinct[k + 1] - distinct[k];
30
+ if (!(gap <= tol || gap / meanAbs <= tol))
31
+ cuts.push(distinct[k + 1]);
32
+ }
33
+ return time.map((t) => {
34
+ if (!Number.isFinite(t))
35
+ return t;
36
+ // the largest cut point not above t
37
+ let lo = 0;
38
+ let hi = cuts.length - 1;
39
+ while (lo < hi) {
40
+ const mid = (lo + hi + 1) >> 1;
41
+ if (cuts[mid] <= t)
42
+ lo = mid;
43
+ else
44
+ hi = mid - 1;
45
+ }
46
+ return cuts[lo];
47
+ });
48
+ }
49
+ function evaluate(data, beta, efron) {
50
+ const { time, event, weight, x, stratumEnd } = data;
51
+ const n = time.length;
52
+ const p = beta.length;
53
+ const zeros = () => new Array(p).fill(0);
54
+ const zeroMatrix = () => Array.from({ length: p }, zeros);
55
+ const score = zeros();
56
+ const info = zeroMatrix();
57
+ let loglik = 0;
58
+ let riskSum = 0;
59
+ let riskX = zeros();
60
+ let riskXX = zeroMatrix();
61
+ const deathX = zeros();
62
+ const deathXX = zeroMatrix();
63
+ for (let k = n - 1; k >= 0;) {
64
+ if (stratumEnd[k]) {
65
+ riskSum = 0;
66
+ riskX = zeros();
67
+ riskXX = zeroMatrix();
68
+ }
69
+ const t = time[k];
70
+ let deaths = 0;
71
+ let deathWeight = 0;
72
+ let deathRisk = 0;
73
+ let j = k;
74
+ do {
75
+ const xj = x[j];
76
+ let eta = 0;
77
+ for (let i = 0; i < p; i++)
78
+ eta += beta[i] * xj[i];
79
+ const w = weight[j];
80
+ const r = Math.exp(eta) * w;
81
+ if (!event[j]) {
82
+ riskSum += r;
83
+ for (let i = 0; i < p; i++) {
84
+ riskX[i] += r * xj[i];
85
+ const row = riskXX[i];
86
+ for (let l = 0; l <= i; l++)
87
+ row[l] += r * xj[i] * xj[l];
88
+ }
89
+ }
90
+ else {
91
+ deaths++;
92
+ deathWeight += w;
93
+ deathRisk += r;
94
+ loglik += w * eta;
95
+ for (let i = 0; i < p; i++) {
96
+ score[i] += w * xj[i];
97
+ deathX[i] += r * xj[i];
98
+ const row = deathXX[i];
99
+ for (let l = 0; l <= i; l++)
100
+ row[l] += r * xj[i] * xj[l];
101
+ }
102
+ }
103
+ j--;
104
+ } while (j >= 0 && time[j] === t && !stratumEnd[j]);
105
+ if (deaths > 0) {
106
+ const steps = efron ? deaths : 1;
107
+ const share = efron ? deaths : 1;
108
+ const stepWeight = deathWeight / steps;
109
+ for (let s = 0; s < steps; s++) {
110
+ riskSum += efron ? deathRisk / share : deathRisk;
111
+ loglik -= stepWeight * Math.log(riskSum);
112
+ for (let i = 0; i < p; i++) {
113
+ riskX[i] += efron ? deathX[i] / share : deathX[i];
114
+ const mean = riskX[i] / riskSum;
115
+ score[i] -= stepWeight * mean;
116
+ const row = riskXX[i];
117
+ const drow = deathXX[i];
118
+ const irow = info[i];
119
+ for (let l = 0; l <= i; l++) {
120
+ row[l] += efron ? drow[l] / share : drow[l];
121
+ irow[l] += (stepWeight * (row[l] - mean * riskX[l])) / riskSum;
122
+ }
123
+ }
124
+ }
125
+ deathX.fill(0);
126
+ for (const row of deathXX)
127
+ row.fill(0);
128
+ }
129
+ k = j;
130
+ }
131
+ for (let i = 0; i < p; i++)
132
+ for (let l = 0; l < i; l++)
133
+ info[l][i] = info[i][l];
134
+ return { loglik, score, info };
135
+ }
136
+ /**
137
+ * Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
138
+ * set to 0. Returns the rank (negative when M is not non-negative definite).
139
+ */
140
+ function cholFactor(m, tol) {
141
+ const p = m.length;
142
+ let scale = 0;
143
+ let anyPositive = false;
144
+ for (let i = 0; i < p; i++) {
145
+ const d = m[i][i];
146
+ if (d > 0) {
147
+ if (!anyPositive || d > scale)
148
+ scale = d;
149
+ anyPositive = true;
150
+ }
151
+ }
152
+ const limit = anyPositive ? scale * tol : tol;
153
+ let rank = 0;
154
+ let nonNegative = true;
155
+ for (let i = 0; i < p; i++) {
156
+ const pivot = m[i][i];
157
+ if (!Number.isFinite(pivot) || pivot < limit) {
158
+ m[i][i] = 0;
159
+ if (pivot < -8 * limit)
160
+ nonNegative = false;
161
+ continue;
162
+ }
163
+ rank++;
164
+ for (let j = i + 1; j < p; j++) {
165
+ const t = m[j][i] / pivot;
166
+ m[j][i] = t;
167
+ m[j][j] -= t * t * pivot;
168
+ for (let k = j + 1; k < p; k++)
169
+ m[k][j] -= t * m[k][i];
170
+ }
171
+ }
172
+ return nonNegative ? rank : -rank;
173
+ }
174
+ /** Solves M y = b with the factor of {@link cholFactor} (0 for the dropped pivots) */
175
+ function cholSolve(m, b) {
176
+ const p = m.length;
177
+ const y = b.slice();
178
+ for (let i = 0; i < p; i++) {
179
+ let v = y[i];
180
+ for (let j = 0; j < i; j++)
181
+ v -= y[j] * m[i][j];
182
+ y[i] = v;
183
+ }
184
+ for (let i = p - 1; i >= 0; i--) {
185
+ if (m[i][i] === 0) {
186
+ y[i] = 0;
187
+ continue;
188
+ }
189
+ let v = y[i] / m[i][i];
190
+ for (let j = i + 1; j < p; j++)
191
+ v -= y[j] * m[j][i];
192
+ y[i] = v;
193
+ }
194
+ return y;
195
+ }
196
+ /** The (generalised) inverse from the factor of {@link cholFactor}, in place; returns the full symmetric matrix */
197
+ function cholInverse(m) {
198
+ const p = m.length;
199
+ for (let i = 0; i < p; i++) {
200
+ if (!(m[i][i] > 0))
201
+ continue;
202
+ m[i][i] = 1 / m[i][i];
203
+ for (let j = i + 1; j < p; j++) {
204
+ m[j][i] = -m[j][i];
205
+ for (let k = 0; k < i; k++)
206
+ m[j][k] += m[j][i] * m[i][k];
207
+ }
208
+ }
209
+ for (let i = 0; i < p; i++) {
210
+ if (m[i][i] === 0) {
211
+ for (let j = 0; j < p; j++) {
212
+ m[i][j] = 0;
213
+ m[j][i] = 0;
214
+ }
215
+ continue;
216
+ }
217
+ for (let j = i + 1; j < p; j++) {
218
+ const t = m[j][i] * m[j][j];
219
+ m[i][j] = t;
220
+ for (let k = i; k < j; k++)
221
+ m[i][k] += t * m[j][k];
222
+ }
223
+ }
224
+ for (let i = 0; i < p; i++)
225
+ for (let j = 0; j < i; j++)
226
+ m[i][j] = m[j][i];
227
+ return m;
228
+ }
229
+ /** A test statistic with its upper chi-squared tail */
230
+ const chisqTest = (statistic, df) => ({
231
+ statistic,
232
+ df,
233
+ pValue: pchisq(statistic, df, { lowerTail: false }),
234
+ });
235
+ /**
236
+ * Cox proportional hazards regression. Equivalent to R's `coxph(Surv(time, status) ~ x [+ strata(strata)], weights,
237
+ * ties, init, control)` (package survival) for right-censored data, with the values of `summary(fit)`.
238
+ *
239
+ * Rows with a missing time, status, covariate, weight or stratum are dropped. Times within sqrt(eps) of each other are
240
+ * treated as tied. Covariates whose values all lie in `nocenter` are not centred; the others are centred by their
241
+ * weighted means, which only shifts the linear predictors. R's warnings (non-convergence, possibly infinite
242
+ * coefficients) are returned in `warnings`.
243
+ *
244
+ * @param time Follow-up times.
245
+ * @param status 1 for an event, 0 for a censored time.
246
+ * @param x The covariate matrix, one row per observation (at least one column).
247
+ * @param options See {@link CoxphOptions}.
248
+ *
249
+ * @example
250
+ * ```ts
251
+ * coxph([5, 3, 8, 1, 9, 4], [1, 1, 0, 1, 0, 1], [[1.2], [0.3], [-0.5], [2], [0.7], [0.1]]).coefficients;
252
+ * ```
253
+ */
254
+ export function coxph(time, status, x, options = {}) {
255
+ const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95 } = options;
256
+ const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
257
+ const tolerInf = control.tolerInf ?? Math.sqrt(eps);
258
+ if (ties !== "efron" && ties !== "breslow")
259
+ throw new RangeError(`invalid 'ties': ${String(ties)}`);
260
+ if (!(eps > 0))
261
+ throw new RangeError("'eps' must be positive");
262
+ if (!(Number.isInteger(iterMax) && iterMax >= 0))
263
+ throw new RangeError("'iterMax' must be a non-negative integer");
264
+ if (!(confLevel > 0 && confLevel < 1))
265
+ throw new RangeError("'confLevel' must be between 0 and 1");
266
+ const nIn = time.length;
267
+ if (status.length !== nIn || x.length !== nIn)
268
+ throw new RangeError("'time', 'status' and 'x' must have the same length");
269
+ if (weights !== undefined && weights.length !== nIn)
270
+ throw new RangeError("'weights' must have the same length as 'time'");
271
+ if (strata !== undefined && strata.length !== nIn)
272
+ throw new RangeError("'strata' must have the same length as 'time'");
273
+ const p = nIn === 0 ? 0 : x[0].length;
274
+ if (p < 1)
275
+ throw new RangeError("'x' must have at least one column");
276
+ if (x.some((row) => row.length !== p))
277
+ throw new RangeError("the rows of 'x' must have the same length");
278
+ if (init !== undefined && init.length !== p)
279
+ throw new RangeError("'init' must have one value per column of 'x'");
280
+ // 1. the rows used
281
+ const keep = [];
282
+ for (let i = 0; i < nIn; i++) {
283
+ if (Number.isNaN(time[i]) || Number.isNaN(status[i]) || x[i].some((v) => Number.isNaN(v)))
284
+ continue;
285
+ if (weights !== undefined && Number.isNaN(weights[i]))
286
+ continue;
287
+ if (strata !== undefined && isMissingLabel(strata[i]))
288
+ continue;
289
+ const s = status[i];
290
+ if (s !== 0 && s !== 1)
291
+ throw new RangeError("'status' must be 0 (censored) or 1 (event)");
292
+ keep.push(i);
293
+ }
294
+ const n = keep.length;
295
+ if (n === 0)
296
+ throw new RangeError("no observations without missing values");
297
+ const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
298
+ if (w.some((v) => !(v > 0)))
299
+ throw new RangeError("Invalid weights, must be >0");
300
+ if (w.some((v) => !Number.isInteger(v)))
301
+ throw new RangeError("non-integer weights (robust variance) are not supported yet");
302
+ let nevent = 0;
303
+ for (const i of keep)
304
+ nevent += status[i];
305
+ const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
306
+ let stratumOf = new Array(n).fill(0);
307
+ if (strata !== undefined) {
308
+ const labels = Array.from(new Set(keep.map((i) => strata[i]))).sort(compareLabels);
309
+ const index = new Map();
310
+ labels.forEach((l, k) => index.set(l, k));
311
+ stratumOf = keep.map((i) => index.get(strata[i]));
312
+ }
313
+ const order = Array.from({ length: n }, (_, k) => k).sort((a, b) => stratumOf[a] - stratumOf[b] || mergedTime[a] - mergedTime[b] || a - b);
314
+ // 2. centring and scaling (sums over the sorted observations)
315
+ let totalWeight = 0;
316
+ for (const v of w)
317
+ totalWeight += v;
318
+ const sortedW = order.map((k) => w[k]);
319
+ const xs = order.map((k) => x[keep[k]].slice());
320
+ const means = new Array(p).fill(0);
321
+ const scales = new Array(p).fill(1);
322
+ const exempt = new Set(nocenter);
323
+ for (let j = 0; j < p; j++) {
324
+ if (xs.every((row) => exempt.has(row[j])))
325
+ continue;
326
+ let sum = 0;
327
+ for (let k = 0; k < n; k++)
328
+ sum += sortedW[k] * xs[k][j];
329
+ const m = sum / totalWeight;
330
+ let absSum = 0;
331
+ for (let k = 0; k < n; k++) {
332
+ xs[k][j] -= m;
333
+ absSum += sortedW[k] * Math.abs(xs[k][j]);
334
+ }
335
+ const s = absSum === 0 ? 1 : totalWeight / absSum;
336
+ for (let k = 0; k < n; k++)
337
+ xs[k][j] *= s;
338
+ means[j] = m;
339
+ scales[j] = s;
340
+ }
341
+ const data = {
342
+ time: order.map((k) => mergedTime[k]),
343
+ event: order.map((k) => status[keep[k]] === 1),
344
+ weight: sortedW,
345
+ x: xs,
346
+ stratumEnd: order.map((k, r) => r === n - 1 || stratumOf[order[r + 1]] !== stratumOf[k]),
347
+ };
348
+ const efron = ties === "efron";
349
+ // 3.-5. Newton-Raphson on the scaled coefficients
350
+ let beta = init === undefined ? new Array(p).fill(0) : init.map((v, j) => v / scales[j]);
351
+ let ev = evaluate(data, beta, efron);
352
+ const loglik = [ev.loglik, ev.loglik];
353
+ let factor = ev.info.map((row) => row.slice());
354
+ let rank = cholFactor(factor, tolerChol);
355
+ let step = cholSolve(factor, ev.score);
356
+ let scoreTest = 0;
357
+ for (let i = 0; i < p; i++)
358
+ scoreTest += ev.score[i] * step[i];
359
+ let iter = 0;
360
+ let inverse;
361
+ let ranOut = false;
362
+ if (iterMax === 0 || !Number.isFinite(ev.loglik)) {
363
+ inverse = cholInverse(factor);
364
+ }
365
+ else {
366
+ let best = ev.loglik;
367
+ let next = beta.map((b, i) => b + step[i]);
368
+ let halvings = 0;
369
+ let converged = false;
370
+ for (iter = 1; iter <= iterMax; iter++) {
371
+ ev = evaluate(data, next, efron);
372
+ factor = ev.info.map((row) => row.slice());
373
+ rank = cholFactor(factor, tolerChol);
374
+ const finite = Number.isFinite(ev.loglik) && ev.score.every(Number.isFinite) && ev.info.every((row) => row.every(Number.isFinite));
375
+ if (finite && Math.abs(1 - best / ev.loglik) <= eps) {
376
+ converged = true;
377
+ loglik[1] = ev.loglik;
378
+ beta = next;
379
+ break;
380
+ }
381
+ if (!finite || ev.loglik < best) {
382
+ halvings++;
383
+ next = next.map((b, i) => (b + halvings * beta[i]) / (halvings + 1));
384
+ }
385
+ else {
386
+ halvings = 0;
387
+ best = ev.loglik;
388
+ loglik[1] = best;
389
+ step = cholSolve(factor, ev.score);
390
+ beta = next;
391
+ next = next.map((b, i) => b + step[i]);
392
+ }
393
+ }
394
+ if (converged) {
395
+ inverse = cholInverse(factor);
396
+ }
397
+ else {
398
+ iter = iterMax + 1;
399
+ ranOut = true;
400
+ if (iterMax > 1) {
401
+ // R recomputes at the last accepted point and applies the inverse step without factorising: that step reads
402
+ // the triangle the accumulation leaves at zero, so only the diagonal survives (off-diagonal entries -0)
403
+ ev = evaluate(data, beta, efron);
404
+ loglik[1] = ev.loglik;
405
+ inverse = ev.info.map((row, i) => row.map((_, j) => (i === j ? (row[i] > 0 ? 1 / row[i] : 0) : -0)));
406
+ }
407
+ else {
408
+ inverse = cholInverse(factor);
409
+ }
410
+ }
411
+ }
412
+ // back to the original scale
413
+ const internal = beta.map((b, j) => b * scales[j]);
414
+ const u = ev.score.map((v, j) => v / scales[j]);
415
+ const variance = inverse.map((row, i) => row.map((v, j) => v * scales[i] * scales[j]));
416
+ // 6. output
417
+ const coefficients = internal.slice();
418
+ if (iterMax > 0 && Math.abs(rank) < p) {
419
+ for (let j = 0; j < p; j++)
420
+ if (variance[j][j] === 0)
421
+ coefficients[j] = NaN;
422
+ }
423
+ let centre = 0;
424
+ for (let j = 0; j < p; j++)
425
+ centre += internal[j] * means[j];
426
+ const linearPredictors = keep.map((i) => {
427
+ let s = 0;
428
+ for (let j = 0; j < p; j++)
429
+ s += x[i][j] * internal[j];
430
+ return s - centre;
431
+ });
432
+ const warnings = new Warnings();
433
+ if (iterMax > 1) {
434
+ const infinity = variance.map((_, j) => {
435
+ let s = 0;
436
+ for (let i = 0; i < p; i++)
437
+ s += u[i] * variance[i][j];
438
+ return Math.abs(s);
439
+ });
440
+ if (ranOut) {
441
+ warnings.add("Ran out of iterations and did not converge");
442
+ if (Math.max(...linearPredictors) > 500 || infinity.some((f) => !Number.isFinite(f))) {
443
+ warnings.add("one or more coefficients may be infinite");
444
+ }
445
+ }
446
+ else {
447
+ const flagged = [];
448
+ for (let j = 0; j < p; j++) {
449
+ const f = infinity[j];
450
+ if (!Number.isFinite(u[j]) || (f > eps && f > tolerInf * Math.abs(internal[j])))
451
+ flagged.push(j + 1);
452
+ }
453
+ if (flagged.length > 0) {
454
+ warnings.add(`Loglik converged before variable ${flagged.join(",")} ; coefficient may be infinite. `);
455
+ }
456
+ }
457
+ }
458
+ // 7. tests and the summary
459
+ const used = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
460
+ const k = used.length;
461
+ const b = used.map((j) => coefficients[j] - (init === undefined ? 0 : init[j]));
462
+ let wald = 0;
463
+ if (k === 1) {
464
+ wald = (b[0] * b[0]) / variance[used[0]][used[0]];
465
+ }
466
+ else if (k > 1) {
467
+ const v = used.map((i) => used.map((j) => variance[i][j]));
468
+ cholFactor(v, tolerChol);
469
+ const y = cholSolve(v, b);
470
+ for (let i = 0; i < k; i++)
471
+ wald += b[i] * y[i];
472
+ }
473
+ const q = qnorm((1 + confLevel) / 2);
474
+ const se = variance.map((row, j) => Math.sqrt(row[j]));
475
+ const z = coefficients.map((c, j) => c / se[j]);
476
+ const pz = z.map((v) => pchisq(v * v, 1, { lowerTail: false }));
477
+ const lower = coefficients.map((c, j) => Math.exp(c - q * se[j]));
478
+ const upper = coefficients.map((c, j) => Math.exp(c + q * se[j]));
479
+ const lr = -2 * (loglik[0] - loglik[1]);
480
+ return {
481
+ coefficients,
482
+ var: variance,
483
+ loglik,
484
+ score: scoreTest,
485
+ wald,
486
+ iter,
487
+ means,
488
+ n,
489
+ nevent,
490
+ linearPredictors,
491
+ se,
492
+ z,
493
+ p: pz,
494
+ lower,
495
+ upper,
496
+ logtest: chisqTest(lr, k),
497
+ sctest: chisqTest(scoreTest, k),
498
+ waldtest: chisqTest(wald, k),
499
+ rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglik[0]) / n) },
500
+ warnings: warnings.list,
501
+ };
502
+ }
@@ -0,0 +1,30 @@
1
+ import { type DD } from "../special/dd.js";
2
+ export declare function ddSqrt(a: DD): DD;
3
+ /** Square roots of the weights in double-double (1 without weights) */
4
+ export declare function ddSqrtWeights(w: readonly number[] | undefined, n: number): DD[];
5
+ /** Result of {@link ddLeastSquares}. */
6
+ export interface DDLeastSquares {
7
+ /** Q'y, one element per row: the effects of the columns, then the residual coordinates. */
8
+ qty: DD[];
9
+ /** Coefficients of the columns, in the order given. */
10
+ coef: DD[];
11
+ }
12
+ /**
13
+ * Least squares of y on the given columns (all assumed linearly independent; rows already scaled by the square roots
14
+ * of the weights).
15
+ *
16
+ * @param cols The columns (each with one entry per row).
17
+ * @param y The response.
18
+ */
19
+ export declare function ddLeastSquares(cols: readonly (readonly DD[])[], y: readonly DD[]): DDLeastSquares;
20
+ /**
21
+ * {@link ddLeastSquares}, and Q'v for more vectors (with the same decomposition of the columns).
22
+ *
23
+ * @param vectors More vectors (each with one entry per row) to transform by Q'.
24
+ */
25
+ export declare function ddLeastSquaresMulti(cols: readonly (readonly DD[])[], y: readonly DD[], vectors: readonly (readonly DD[])[]): {
26
+ fit: DDLeastSquares;
27
+ qtv: DD[][];
28
+ };
29
+ /** Sum of squares of the elements from..to-1 */
30
+ export declare function ddSumSquares(v: readonly DD[], from?: number, to?: number): DD;