@numero-uno-jpn/rstats 0.15.3 → 0.17.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.
- package/CHANGELOG.md +294 -0
- package/README.ja.md +68 -35
- package/README.md +65 -30
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/chunk-4WE3OO62.js +2 -0
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/chunk-H3WVPZDL.js +2 -0
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/chunk-NSYZTS26.js +2 -0
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/chunk-SE7V2KLO.js +2 -0
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/chunk-Z37NELOS.js +2 -0
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +26 -7
- package/dist/descriptive/basic.js +110 -8
- package/dist/descriptive/cov.js +23 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +69 -23
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +26 -9
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +77 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +86 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +74 -10
- package/dist/descriptive/pivot.d.ts +25 -10
- package/dist/descriptive/pivot.js +182 -42
- package/dist/descriptive/quantile.js +10 -1
- package/dist/descriptive/rank.js +8 -1
- package/dist/descriptive/table.d.ts +23 -3
- package/dist/descriptive/table.js +36 -21
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +27 -2
- package/dist/distributions/beta.js +33 -4
- package/dist/distributions/binomial.js +46 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +21 -4
- package/dist/distributions/chisq.js +16 -3
- package/dist/distributions/exponential.js +14 -0
- package/dist/distributions/f.js +41 -17
- package/dist/distributions/gamma.js +35 -3
- package/dist/distributions/geometric.js +58 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +101 -6
- package/dist/distributions/invgamma.js +10 -1
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +36 -6
- package/dist/distributions/logistic.js +13 -1
- package/dist/distributions/lognormal.js +16 -2
- package/dist/distributions/multinomial.js +58 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +102 -17
- package/dist/distributions/normal.js +17 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +12 -1
- package/dist/distributions/poisson.js +37 -3
- package/dist/distributions/signrank.js +16 -4
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +481 -61
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +19 -5
- package/dist/distributions/tukey.js +11 -2
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +18 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +164 -26
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +3 -1
- package/dist/entries/descriptive.js +1 -1
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +2 -0
- package/dist/entries/linalg.d.ts +3 -1
- package/dist/entries/mixed.d.ts +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +16 -2
- package/dist/htest/agreement.js +122 -21
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/ansariTest.js +116 -18
- package/dist/htest/aov.d.ts +29 -23
- package/dist/htest/aov.js +90 -47
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +47 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +12 -5
- package/dist/htest/chisqTest.d.ts +5 -2
- package/dist/htest/chisqTest.js +151 -46
- package/dist/htest/cor.d.ts +9 -2
- package/dist/htest/cor.js +57 -26
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +5 -0
- package/dist/htest/effectSize.js +117 -35
- package/dist/htest/fisherTest.d.ts +4 -3
- package/dist/htest/fisherTest.js +88 -24
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +7 -1
- package/dist/htest/ksTest.js +36 -6
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +28 -6
- package/dist/htest/mantelhaenTest.js +132 -25
- package/dist/htest/mcnemarTest.js +40 -11
- package/dist/htest/multipleComparisons.d.ts +24 -26
- package/dist/htest/multipleComparisons.js +70 -64
- package/dist/htest/normalityTests.js +54 -14
- package/dist/htest/onewayTest.js +106 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +42 -6
- package/dist/htest/pairwise.d.ts +3 -1
- package/dist/htest/pairwise.js +46 -21
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +117 -59
- package/dist/htest/polycor.js +47 -17
- package/dist/htest/power.d.ts +15 -1
- package/dist/htest/power.js +128 -10
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +44 -6
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +159 -39
- package/dist/htest/rankTests.js +36 -6
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +53 -21
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +28 -4
- package/dist/htest/trendTests.js +124 -35
- package/dist/htest/types.d.ts +7 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +52 -14
- package/dist/htest/wilcoxTest.js +164 -29
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +58 -7
- package/dist/linalg/chol.js +10 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +75 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +113 -15
- package/dist/linalg/kappa.js +64 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +40 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +74 -26
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +105 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +156 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +33 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +32 -2
- package/dist/models/anovaSequential.js +170 -28
- package/dist/models/aovEz.js +154 -39
- package/dist/models/aovStrata.js +68 -24
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +78 -33
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +166 -69
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +57 -7
- package/dist/models/glm.js +427 -74
- package/dist/models/glmAnova.js +90 -14
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +121 -29
- package/dist/models/glmFamily.d.ts +11 -6
- package/dist/models/glmFamily.js +247 -62
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +246 -37
- package/dist/models/lmer.d.ts +31 -7
- package/dist/models/lmer.js +129 -42
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +47 -9
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +13 -6
- package/dist/models/lmerTest.js +82 -29
- package/dist/models/mauchly.d.ts +6 -1
- package/dist/models/mauchly.js +41 -15
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +10 -4
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +47 -17
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +12 -1
- package/dist/models/survival.js +75 -28
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +72 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +111 -16
- package/dist/numerics/interp.d.ts +40 -9
- package/dist/numerics/interp.js +375 -55
- package/dist/numerics/ode.js +59 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +97 -10
- package/dist/random/beta.js +58 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +50 -5
- package/dist/random/extra.js +55 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +47 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +31 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +63 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +175 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +24 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +15 -6
- package/package.json +19 -10
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-VLUL2HFW.js +0 -3
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/models/carAnova.js
CHANGED
|
@@ -8,14 +8,22 @@
|
|
|
8
8
|
// without the cancellation of a difference; the rank is decided in double precision as lm does, the effects are
|
|
9
9
|
// computed in double-double (src/models/ddLeastSquares.ts).
|
|
10
10
|
import { pf1 } from "../distributions/f.js";
|
|
11
|
+
import { ldexp } from "../internal/summary.js";
|
|
11
12
|
import { qr } from "../linalg/qr.js";
|
|
12
13
|
import { ddAdd, ddMul, ddMulNum } from "../special/dd.js";
|
|
13
14
|
import { ddLeastSquares, ddSqrtWeights } from "./ddLeastSquares.js";
|
|
15
|
+
import { evenWeightExponent, responseScale, rssWithinRounding, scaledRss, weightedResponse } from "./anovaSequential.js";
|
|
16
|
+
import { reported } from "../internal/warnings.js";
|
|
17
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
18
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
19
|
+
const ANOVA_KEYS = ["type"];
|
|
14
20
|
/**
|
|
15
21
|
* The sum of the squared effects of the columns `added` after the columns `base`, and the number of added columns
|
|
16
|
-
* that are not aliased (the decrease of the residual sum of squares and the increase of the rank)
|
|
22
|
+
* that are not aliased (the decrease of the residual sum of squares and the increase of the rank), for the response
|
|
23
|
+
* scaled by 2^-k (src/internal/summary.ts) and the weights by 2^-kw (kw even, so that their square roots are scaled
|
|
24
|
+
* exactly)
|
|
17
25
|
*/
|
|
18
|
-
function addedSS(fit, base, added) {
|
|
26
|
+
function addedSS(fit, base, added, k, kw = 0) {
|
|
19
27
|
const cols = [...base, ...added];
|
|
20
28
|
if (cols.length === 0)
|
|
21
29
|
return { ss: 0, df: 0 };
|
|
@@ -24,9 +32,9 @@ function addedSS(fit, base, added) {
|
|
|
24
32
|
const sw = rows.map((i) => (fit.weights === undefined ? 1 : Math.sqrt(fit.weights[i])));
|
|
25
33
|
const q = qr(rows.map((i, k) => cols.map((j) => fit.x[i][j] * sw[k])));
|
|
26
34
|
// the effects in double-double
|
|
27
|
-
const swd = ddSqrtWeights(fit.weights === undefined ? undefined : rows.map((i) => fit.weights[i]), rows.length);
|
|
35
|
+
const swd = ddSqrtWeights(fit.weights === undefined ? undefined : rows.map((i) => ldexp(fit.weights[i], -kw)), rows.length);
|
|
28
36
|
const kept = q.pivot.slice(0, q.rank);
|
|
29
|
-
const { qty } = ddLeastSquares(kept.map((c) => rows.map((i, k) => ddMulNum(swd[k], fit.x[i][cols[c]]))), rows.map((i,
|
|
37
|
+
const { qty } = ddLeastSquares(kept.map((c) => rows.map((i, k) => ddMulNum(swd[k], fit.x[i][cols[c]]))), rows.map((i, r) => ddMulNum(swd[r], ldexp(fit.y[i], -k))));
|
|
30
38
|
let ss = [0, 0];
|
|
31
39
|
let df = 0;
|
|
32
40
|
kept.forEach((c, k) => {
|
|
@@ -62,6 +70,7 @@ function addedSS(fit, base, added) {
|
|
|
62
70
|
* @category Linear models and ANOVA
|
|
63
71
|
*/
|
|
64
72
|
export function Anova(fit, options = {}) {
|
|
73
|
+
checkOptions(options, ANOVA_KEYS, "Anova"); // generated: option-keys.mjs
|
|
65
74
|
if (typeof fit !== "object" || fit === null || !Array.isArray(fit.effects)) {
|
|
66
75
|
throw new TypeError("Anova() needs a fit from lm() with a formula");
|
|
67
76
|
}
|
|
@@ -74,12 +83,36 @@ export function Anova(fit, options = {}) {
|
|
|
74
83
|
else
|
|
75
84
|
throw new RangeError(`invalid type (${String(t0)}): use 2 or 3`);
|
|
76
85
|
const rdf = fit.dfResidual;
|
|
77
|
-
|
|
86
|
+
// sums of squares of the response scaled by 2^-k: F and p from them, the Sum Sq column scaled back
|
|
87
|
+
const k = responseScale([fit]);
|
|
88
|
+
const rss = scaledRss([fit], k)[0];
|
|
78
89
|
if (rdf === 0)
|
|
79
90
|
throw new Error("residual df = 0");
|
|
80
|
-
|
|
91
|
+
// car compares the residual sum of squares with sqrt(eps) in the units of the data, which depends on them; here it
|
|
92
|
+
// is 0 within rounding error below 1e-24 times the (weighted, uncentred) sum of squares of the response, residuals
|
|
93
|
+
// below 1e-12 of the response's size (the level of aovEz's dataSS). sqrt(eps) times the centred total rejected data
|
|
94
|
+
// with R^2 above 1 - 1.5e-8 that car computes (revision of review 4)
|
|
95
|
+
const wy = weightedResponse(fit, k);
|
|
96
|
+
// Where a sum over the weights overflows (the total of the weights of 1e308, #347), the weights are divided by an
|
|
97
|
+
// even power of 2 2^kw: the sums of squares are then in units of 2^(2k + kw). kw is 0 otherwise (the same bits)
|
|
98
|
+
const weightedTss = (kw) => {
|
|
99
|
+
const ws = wy.map(([w, v]) => [ldexp(w, -kw), v]);
|
|
100
|
+
const sw = ws.reduce((a, [w]) => a + w, 0);
|
|
101
|
+
const my = ws.reduce((a, [w, v]) => a + w * v, 0) / sw;
|
|
102
|
+
return Number.isFinite(sw) && Number.isFinite(my) ? ws.reduce((a, [w, v]) => a + w * (v - my) ** 2, 0) : NaN;
|
|
103
|
+
};
|
|
104
|
+
let kw = 0;
|
|
105
|
+
let tss = weightedTss(0);
|
|
106
|
+
if (!Number.isFinite(tss)) {
|
|
107
|
+
kw = evenWeightExponent(wy);
|
|
108
|
+
tss = weightedTss(kw);
|
|
109
|
+
}
|
|
110
|
+
// (kw from the centred total as before, which the sums of squares of the terms use; the uncentred sum, at most
|
|
111
|
+
// 16 times the total weight, takes its own even power of 2 where it overflows)
|
|
112
|
+
if (rssWithinRounding(wy, rss, kw) || rss === 0)
|
|
81
113
|
throw new Error("residual sum of squares is 0 (within rounding error)");
|
|
82
|
-
|
|
114
|
+
// the fit's warnings (from its model matrix and summary) first, as for aov with Error(); R gives them when fitting
|
|
115
|
+
const warnings = [...fit.warnings];
|
|
83
116
|
const nTerms = fit.termLabels.length;
|
|
84
117
|
if (type === 2 && nTerms === 0 && fit.intercept) {
|
|
85
118
|
warnings.push("the model contains only an intercept: Type III test substituted");
|
|
@@ -88,36 +121,48 @@ export function Anova(fit, options = {}) {
|
|
|
88
121
|
const columnsOf = (terms) => fit.assign.flatMap((a, j) => (terms.has(a) ? [j] : []));
|
|
89
122
|
const allTerms = [...new Set(fit.assign)];
|
|
90
123
|
const names = [];
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
124
|
+
let rows = [];
|
|
125
|
+
const termRows = (kw) => {
|
|
126
|
+
names.length = 0;
|
|
127
|
+
const out = [];
|
|
128
|
+
if (type === 3) {
|
|
129
|
+
if (fit.coefficients.some((c) => Number.isNaN(c)))
|
|
130
|
+
throw new Error("there are aliased coefficients in the model");
|
|
131
|
+
for (const t of allTerms) {
|
|
132
|
+
const added = columnsOf(new Set([t]));
|
|
133
|
+
const base = columnsOf(new Set(allTerms.filter((u) => u !== t)));
|
|
134
|
+
names.push(t === 0 ? "(Intercept)" : fit.termLabels[t - 1]);
|
|
135
|
+
out.push({ ss: addedSS(fit, base, added, k, kw).ss, df: added.length });
|
|
136
|
+
}
|
|
100
137
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
138
|
+
else {
|
|
139
|
+
// the variables of each term (from the factors attribute)
|
|
140
|
+
const varsOf = (t) => fit.factors.flatMap((codes, v) => (codes[t - 1] > 0 ? [v] : []));
|
|
141
|
+
for (const t of allTerms) {
|
|
142
|
+
if (t === 0)
|
|
143
|
+
continue;
|
|
144
|
+
const vt = varsOf(t);
|
|
145
|
+
const containing = allTerms.filter((u) => u !== 0 && u !== t && vt.every((v) => fit.factors[v][u - 1] > 0));
|
|
146
|
+
const base = columnsOf(new Set(allTerms.filter((u) => u !== t && !containing.includes(u))));
|
|
147
|
+
const r = addedSS(fit, base, columnsOf(new Set([t])), k, kw);
|
|
148
|
+
names.push(fit.termLabels[t - 1]);
|
|
149
|
+
out.push(r);
|
|
150
|
+
}
|
|
114
151
|
}
|
|
152
|
+
return out;
|
|
153
|
+
};
|
|
154
|
+
rows = termRows(kw);
|
|
155
|
+
if (kw === 0 && fit.weights !== undefined && rows.some((r) => !Number.isFinite(r.ss))) {
|
|
156
|
+
kw = evenWeightExponent(wy);
|
|
157
|
+
rows = termRows(kw);
|
|
115
158
|
}
|
|
116
|
-
const
|
|
159
|
+
const back = (v) => ldexp(v, 2 * k + kw);
|
|
160
|
+
const rssW = ldexp(rss, -kw);
|
|
161
|
+
const rms = rssW / rdf;
|
|
117
162
|
const table = rows.map(({ ss, df }) => {
|
|
118
163
|
const f = ss / df / rms;
|
|
119
|
-
return [ss, df, f, pf1(f, df, rdf, false, false)];
|
|
164
|
+
return [back(ss), df, f, pf1(f, df, rdf, false, false)];
|
|
120
165
|
});
|
|
121
|
-
table.push([
|
|
122
|
-
return { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings };
|
|
166
|
+
table.push([back(rssW), rdf, NaN, NaN]);
|
|
167
|
+
return reported("Anova", { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings }, fit);
|
|
123
168
|
}
|
package/dist/models/coxph.d.ts
CHANGED
|
@@ -80,6 +80,12 @@ export interface CoxphResult {
|
|
|
80
80
|
z: number[];
|
|
81
81
|
/** Two-sided p-values `Pr(>|z|)` */
|
|
82
82
|
p: number[];
|
|
83
|
+
/** Alias of `se`: the same array. */
|
|
84
|
+
stdError: number[];
|
|
85
|
+
/** Alias of `z`: the same array. */
|
|
86
|
+
zValue: number[];
|
|
87
|
+
/** Alias of `p`: the same array. */
|
|
88
|
+
pValue: number[];
|
|
83
89
|
/** Lower confidence limits of exp(coef) */
|
|
84
90
|
lower: number[];
|
|
85
91
|
/** Upper confidence limits of exp(coef) */
|
package/dist/models/coxph.js
CHANGED
|
@@ -12,41 +12,18 @@
|
|
|
12
12
|
import { pchisq } from "../distributions/chisq.js";
|
|
13
13
|
import { qnorm } from "../distributions/normal.js";
|
|
14
14
|
import { numberLevels } from "../internal/levels.js";
|
|
15
|
-
import {
|
|
15
|
+
import { ldexp, mean, scaleToUnit } from "../internal/summary.js";
|
|
16
|
+
import { mergeTiedTimes } from "./tiedTimes.js";
|
|
17
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
18
|
+
import { maxOf } from "../internal/extremes.js";
|
|
19
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
20
|
+
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
21
|
+
const COXPH_KEYS = ["ties", "weights", "strata", "init", "control", "nocenter", "confLevel"];
|
|
22
|
+
const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf"];
|
|
16
23
|
const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
17
24
|
const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
const tol = Math.sqrt(2 ** -52);
|
|
21
|
-
const distinct = Array.from(new Set(time.filter((t) => Number.isFinite(t)))).sort((a, b) => a - b);
|
|
22
|
-
if (distinct.length < 2)
|
|
23
|
-
return time.slice();
|
|
24
|
-
let meanAbs = 0;
|
|
25
|
-
for (const y of distinct)
|
|
26
|
-
meanAbs += Math.abs(y);
|
|
27
|
-
meanAbs /= distinct.length;
|
|
28
|
-
const cuts = [distinct[0]];
|
|
29
|
-
for (let k = 0; k + 1 < distinct.length; k++) {
|
|
30
|
-
const gap = distinct[k + 1] - distinct[k];
|
|
31
|
-
if (!(gap <= tol || gap / meanAbs <= tol))
|
|
32
|
-
cuts.push(distinct[k + 1]);
|
|
33
|
-
}
|
|
34
|
-
return time.map((t) => {
|
|
35
|
-
if (!Number.isFinite(t))
|
|
36
|
-
return t;
|
|
37
|
-
// the largest cut point not above t
|
|
38
|
-
let lo = 0;
|
|
39
|
-
let hi = cuts.length - 1;
|
|
40
|
-
while (lo < hi) {
|
|
41
|
-
const mid = (lo + hi + 1) >> 1;
|
|
42
|
-
if (cuts[mid] <= t)
|
|
43
|
-
lo = mid;
|
|
44
|
-
else
|
|
45
|
-
hi = mid - 1;
|
|
46
|
-
}
|
|
47
|
-
return cuts[lo];
|
|
48
|
-
});
|
|
49
|
-
}
|
|
25
|
+
/** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
|
|
26
|
+
const SHIFT_LIMIT = 700;
|
|
50
27
|
function evaluate(data, beta, efron) {
|
|
51
28
|
const { time, event, weight, x, stratumEnd } = data;
|
|
52
29
|
const n = time.length;
|
|
@@ -61,8 +38,31 @@ function evaluate(data, beta, efron) {
|
|
|
61
38
|
let riskXX = zeroMatrix();
|
|
62
39
|
const deathX = zeros();
|
|
63
40
|
const deathXX = zeroMatrix();
|
|
41
|
+
let deathRisk = 0;
|
|
42
|
+
// The risk sums (and the sums of the deaths at one time) are held as e^-shift times their values. shift stays 0,
|
|
43
|
+
// and the arithmetic is the plain one, unless a finite exp(eta) would overflow (or, with the sums still empty,
|
|
44
|
+
// underflow): then the sums are rescaled to the new shift, so a log partial likelihood that is finite is not lost
|
|
45
|
+
// to Inf (issue #367). The means and the information are ratios of the sums and do not depend on the shift
|
|
46
|
+
let shift = 0;
|
|
47
|
+
const rescale = (to) => {
|
|
48
|
+
const f = Math.exp(shift - to);
|
|
49
|
+
riskSum *= f;
|
|
50
|
+
deathRisk *= f;
|
|
51
|
+
for (let i = 0; i < p; i++) {
|
|
52
|
+
riskX[i] *= f;
|
|
53
|
+
deathX[i] *= f;
|
|
54
|
+
const row = riskXX[i];
|
|
55
|
+
const drow = deathXX[i];
|
|
56
|
+
for (let l = 0; l <= i; l++) {
|
|
57
|
+
row[l] *= f;
|
|
58
|
+
drow[l] *= f;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
shift = to;
|
|
62
|
+
};
|
|
64
63
|
for (let k = n - 1; k >= 0;) {
|
|
65
64
|
if (stratumEnd[k]) {
|
|
65
|
+
shift = 0;
|
|
66
66
|
riskSum = 0;
|
|
67
67
|
riskX = zeros();
|
|
68
68
|
riskXX = zeroMatrix();
|
|
@@ -70,7 +70,7 @@ function evaluate(data, beta, efron) {
|
|
|
70
70
|
const t = time[k];
|
|
71
71
|
let deaths = 0;
|
|
72
72
|
let deathWeight = 0;
|
|
73
|
-
|
|
73
|
+
deathRisk = 0;
|
|
74
74
|
let j = k;
|
|
75
75
|
do {
|
|
76
76
|
const xj = x[j];
|
|
@@ -78,7 +78,13 @@ function evaluate(data, beta, efron) {
|
|
|
78
78
|
for (let i = 0; i < p; i++)
|
|
79
79
|
eta += beta[i] * xj[i];
|
|
80
80
|
const w = weight[j];
|
|
81
|
-
|
|
81
|
+
if (Number.isFinite(eta)) {
|
|
82
|
+
if (eta - shift > SHIFT_LIMIT)
|
|
83
|
+
rescale(eta);
|
|
84
|
+
else if (eta - shift < -SHIFT_LIMIT && riskSum === 0 && deathRisk === 0)
|
|
85
|
+
shift = eta;
|
|
86
|
+
}
|
|
87
|
+
const r = Math.exp(eta - shift) * w;
|
|
82
88
|
if (!event[j]) {
|
|
83
89
|
riskSum += r;
|
|
84
90
|
for (let i = 0; i < p; i++) {
|
|
@@ -109,7 +115,7 @@ function evaluate(data, beta, efron) {
|
|
|
109
115
|
const stepWeight = deathWeight / steps;
|
|
110
116
|
for (let s = 0; s < steps; s++) {
|
|
111
117
|
riskSum += efron ? deathRisk / share : deathRisk;
|
|
112
|
-
loglik -= stepWeight * Math.log(riskSum);
|
|
118
|
+
loglik -= stepWeight * (Math.log(riskSum) + shift);
|
|
113
119
|
for (let i = 0; i < p; i++) {
|
|
114
120
|
riskX[i] += efron ? deathX[i] / share : deathX[i];
|
|
115
121
|
const mean = riskX[i] / riskSum;
|
|
@@ -159,6 +165,11 @@ function cholFactor(m, tol) {
|
|
|
159
165
|
m[i][i] = 0;
|
|
160
166
|
if (pivot < -8 * limit)
|
|
161
167
|
nonNegative = false;
|
|
168
|
+
// the column dropped as a whole: its residual cross-products below were left (as survival's cholesky2) and the
|
|
169
|
+
// forward substitution of cholSolve and cholInverse used them, so a nearly aliased column still entered the
|
|
170
|
+
// solution and the variance (by about the tolerance; issue #13). With them 0 the fit is that without the column
|
|
171
|
+
for (let j = i + 1; j < p; j++)
|
|
172
|
+
m[j][i] = 0;
|
|
162
173
|
continue;
|
|
163
174
|
}
|
|
164
175
|
rank++;
|
|
@@ -233,6 +244,40 @@ const chisqTest = (statistic, df) => ({
|
|
|
233
244
|
df,
|
|
234
245
|
pValue: pchisq(statistic, df, { lowerTail: false }),
|
|
235
246
|
});
|
|
247
|
+
/** R's result for data without events (survival's coxph returns it before fitting), with summary(fit)'s values */
|
|
248
|
+
function zeroEventResult(rows, p) {
|
|
249
|
+
const n = rows.length;
|
|
250
|
+
const nans = () => new Array(p).fill(NaN);
|
|
251
|
+
const test = chisqTest(0, 0);
|
|
252
|
+
const se = new Array(p).fill(0);
|
|
253
|
+
const z = nans();
|
|
254
|
+
const pz = nans();
|
|
255
|
+
return {
|
|
256
|
+
coefficients: nans(),
|
|
257
|
+
var: Array.from({ length: p }, () => new Array(p).fill(0)),
|
|
258
|
+
loglik: [0, 0],
|
|
259
|
+
score: 0,
|
|
260
|
+
wald: 0,
|
|
261
|
+
iter: 0,
|
|
262
|
+
means: Array.from({ length: p }, (_, j) => mean(rows.map((row) => row[j]))),
|
|
263
|
+
n,
|
|
264
|
+
nevent: 0,
|
|
265
|
+
linearPredictors: new Array(n).fill(0),
|
|
266
|
+
se,
|
|
267
|
+
z,
|
|
268
|
+
p: pz,
|
|
269
|
+
stdError: se,
|
|
270
|
+
zValue: z,
|
|
271
|
+
pValue: pz,
|
|
272
|
+
lower: nans(),
|
|
273
|
+
upper: nans(),
|
|
274
|
+
logtest: test,
|
|
275
|
+
sctest: { ...test },
|
|
276
|
+
waldtest: { ...test },
|
|
277
|
+
rsq: { rsq: 0, maxrsq: 0 },
|
|
278
|
+
warnings: [],
|
|
279
|
+
};
|
|
280
|
+
}
|
|
236
281
|
/**
|
|
237
282
|
* Cox proportional hazards regression. Equivalent to R's `survival::coxph()`. As
|
|
238
283
|
* `coxph(Surv(time, status) ~ x [+ strata(strata)], weights, ties, init, control)` for right-censored data, with the
|
|
@@ -258,13 +303,19 @@ const chisqTest = (statistic, df) => ({
|
|
|
258
303
|
* @category Survival analysis
|
|
259
304
|
*/
|
|
260
305
|
export function coxph(time, status, x, options = {}) {
|
|
306
|
+
checkOptions(options, COXPH_KEYS, "coxph"); // generated: option-keys.mjs
|
|
307
|
+
checkOptions(nestedOptions(options, "control"), COXPH_CONTROL_KEYS, "coxph", "control"); // generated: option-keys.mjs
|
|
261
308
|
const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95 } = options;
|
|
262
309
|
const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
|
|
263
310
|
const tolerInf = control.tolerInf ?? Math.sqrt(eps);
|
|
264
311
|
if (ties !== "efron" && ties !== "breslow")
|
|
265
312
|
throw new RangeError(`invalid 'ties': ${String(ties)}`);
|
|
266
|
-
if (!(eps > 0))
|
|
267
|
-
throw new RangeError("'eps' must be positive");
|
|
313
|
+
if (!(eps > 0 && eps < Infinity))
|
|
314
|
+
throw new RangeError("'eps' must be a positive finite number");
|
|
315
|
+
if (!(tolerChol > 0 && tolerChol < Infinity))
|
|
316
|
+
throw new RangeError("'tolerChol' must be a positive finite number");
|
|
317
|
+
if (!(tolerInf > 0 && tolerInf < Infinity))
|
|
318
|
+
throw new RangeError("'tolerInf' must be a positive finite number");
|
|
268
319
|
if (!(Number.isInteger(iterMax) && iterMax >= 0))
|
|
269
320
|
throw new RangeError("'iterMax' must be a non-negative integer");
|
|
270
321
|
if (!(confLevel > 0 && confLevel < 1))
|
|
@@ -283,6 +334,8 @@ export function coxph(time, status, x, options = {}) {
|
|
|
283
334
|
throw new RangeError("the rows of 'x' must have the same length");
|
|
284
335
|
if (init !== undefined && init.length !== p)
|
|
285
336
|
throw new RangeError("'init' must have one value per column of 'x'");
|
|
337
|
+
if (init?.some((v) => !Number.isFinite(v)))
|
|
338
|
+
throw new RangeError("'init' must contain finite values");
|
|
286
339
|
// 1. the rows used
|
|
287
340
|
const keep = [];
|
|
288
341
|
for (let i = 0; i < nIn; i++) {
|
|
@@ -295,11 +348,17 @@ export function coxph(time, status, x, options = {}) {
|
|
|
295
348
|
const s = status[i];
|
|
296
349
|
if (s !== 0 && s !== 1)
|
|
297
350
|
throw new RangeError("'status' must be 0 (censored) or 1 (event)");
|
|
351
|
+
// a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
|
|
352
|
+
// infinite time, nor anything at -Infinity (as survdiff and survfit)
|
|
353
|
+
if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
|
|
354
|
+
throw new RangeError("event times must be finite");
|
|
298
355
|
keep.push(i);
|
|
299
356
|
}
|
|
300
357
|
const n = keep.length;
|
|
301
358
|
if (n === 0)
|
|
302
359
|
throw new RangeError("no observations without missing values");
|
|
360
|
+
if (keep.some((i) => x[i].some((v) => !Number.isFinite(v))))
|
|
361
|
+
throw new RangeError("'x' contains infinite values");
|
|
303
362
|
const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
|
|
304
363
|
if (w.some((v) => !(v > 0)))
|
|
305
364
|
throw new RangeError("Invalid weights, must be >0");
|
|
@@ -308,6 +367,11 @@ export function coxph(time, status, x, options = {}) {
|
|
|
308
367
|
let nevent = 0;
|
|
309
368
|
for (const i of keep)
|
|
310
369
|
nevent += status[i];
|
|
370
|
+
// no events: R's coxph returns before the fit (issue #472) with NA coefficients, a zero variance, zero log likelihood,
|
|
371
|
+
// score, Wald statistic and iterations, and the unweighted column means of all covariates (nocenter ignored); `init`
|
|
372
|
+
// is not an estimate here
|
|
373
|
+
if (nevent === 0)
|
|
374
|
+
return zeroEventResult(keep.map((i) => x[i]), p);
|
|
311
375
|
const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
|
|
312
376
|
let stratumOf = new Array(n).fill(0);
|
|
313
377
|
if (strata !== undefined) {
|
|
@@ -326,25 +390,39 @@ export function coxph(time, status, x, options = {}) {
|
|
|
326
390
|
const sortedW = order.map((k) => w[k]);
|
|
327
391
|
const xs = order.map((k) => x[keep[k]].slice());
|
|
328
392
|
const means = new Array(p).fill(0);
|
|
393
|
+
// the scale of column j is scales[j] 2^-shift[j]
|
|
329
394
|
const scales = new Array(p).fill(1);
|
|
395
|
+
const shift = new Array(p).fill(0);
|
|
330
396
|
const exempt = new Set(nocenter);
|
|
331
397
|
for (let j = 0; j < p; j++) {
|
|
332
398
|
if (xs.every((row) => exempt.has(row[j])))
|
|
333
399
|
continue;
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
sum
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
400
|
+
const column = xs.map((row) => row[j]);
|
|
401
|
+
const centreScale = (col) => {
|
|
402
|
+
let sum = 0;
|
|
403
|
+
for (let k = 0; k < n; k++)
|
|
404
|
+
sum += sortedW[k] * col[k];
|
|
405
|
+
const m = sum / totalWeight;
|
|
406
|
+
let absSum = 0;
|
|
407
|
+
const d = col.map((v, k) => {
|
|
408
|
+
absSum += sortedW[k] * Math.abs(v - m);
|
|
409
|
+
return v - m;
|
|
410
|
+
});
|
|
411
|
+
const s = absSum === 0 ? 1 : totalWeight / absSum;
|
|
412
|
+
return { m, s, d, ok: Number.isFinite(m) && s >= 2 ** -1022 && s < Infinity };
|
|
413
|
+
};
|
|
414
|
+
let fit = centreScale(column);
|
|
415
|
+
// the sums overflow for covariates around 1e308, and the scale for subnormal ones (#87; the column became 0 or
|
|
416
|
+
// NaN): then in the units 2^c of the column's largest value, where the scaled column (x - m) s is the same
|
|
417
|
+
if (!fit.ok) {
|
|
418
|
+
const { groups, k: c } = scaleToUnit([column]);
|
|
419
|
+
fit = centreScale(groups[0]);
|
|
420
|
+
shift[j] = c;
|
|
342
421
|
}
|
|
343
|
-
const s = absSum === 0 ? 1 : totalWeight / absSum;
|
|
344
422
|
for (let k = 0; k < n; k++)
|
|
345
|
-
xs[k][j]
|
|
346
|
-
means[j] = m;
|
|
347
|
-
scales[j] = s;
|
|
423
|
+
xs[k][j] = fit.d[k] * fit.s;
|
|
424
|
+
means[j] = ldexp(fit.m, shift[j]);
|
|
425
|
+
scales[j] = fit.s;
|
|
348
426
|
}
|
|
349
427
|
const data = {
|
|
350
428
|
time: order.map((k) => mergedTime[k]),
|
|
@@ -355,7 +433,7 @@ export function coxph(time, status, x, options = {}) {
|
|
|
355
433
|
};
|
|
356
434
|
const efron = ties === "efron";
|
|
357
435
|
// 3.-5. Newton-Raphson on the scaled coefficients
|
|
358
|
-
let beta = init === undefined ? new Array(p).fill(0) : init.map((v, j) => v / scales[j]);
|
|
436
|
+
let beta = init === undefined ? new Array(p).fill(0) : init.map((v, j) => ldexp(v / scales[j], shift[j]));
|
|
359
437
|
let ev = evaluate(data, beta, efron);
|
|
360
438
|
const loglik = [ev.loglik, ev.loglik];
|
|
361
439
|
let factor = ev.info.map((row) => row.slice());
|
|
@@ -380,7 +458,9 @@ export function coxph(time, status, x, options = {}) {
|
|
|
380
458
|
factor = ev.info.map((row) => row.slice());
|
|
381
459
|
rank = cholFactor(factor, tolerChol);
|
|
382
460
|
const finite = Number.isFinite(ev.loglik) && ev.score.every(Number.isFinite) && ev.info.every((row) => row.every(Number.isFinite));
|
|
383
|
-
|
|
461
|
+
// an unchanged log likelihood is converged too (both 0, as for coxph([1], [1], [[0]]), made the ratio 0/0 = NaN and
|
|
462
|
+
// ran out of iterations, as R)
|
|
463
|
+
if (finite && (ev.loglik === best || Math.abs(1 - best / ev.loglik) <= eps)) {
|
|
384
464
|
converged = true;
|
|
385
465
|
loglik[1] = ev.loglik;
|
|
386
466
|
beta = next;
|
|
@@ -417,15 +497,24 @@ export function coxph(time, status, x, options = {}) {
|
|
|
417
497
|
}
|
|
418
498
|
}
|
|
419
499
|
}
|
|
420
|
-
// back to the original scale
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
500
|
+
// back to the original scale. Each column's scale s_j is split as s~_j 2^e_j (s~_j in [1, 2)): the coefficients,
|
|
501
|
+
// the variance and the score are first formed in units of 2^e_j, where they stay in range whatever the units of the
|
|
502
|
+
// covariates, and scaled back by powers of 2 only for the output. Unitless quantities (z, the Wald test, the check
|
|
503
|
+
// for infinite coefficients) are computed in these units: the same bits as in the original units when nothing
|
|
504
|
+
// overflows, and the Wald test's Cholesky pivots are not dropped because the covariates have different units
|
|
505
|
+
const scaleExpo = scales.map((s) => Math.floor(Math.log2(s)));
|
|
506
|
+
const mant = scales.map((s, j) => ldexp(s, -scaleExpo[j]));
|
|
507
|
+
const expo = scaleExpo.map((e, j) => e - shift[j]);
|
|
508
|
+
const coefUnit = beta.map((b, j) => b * mant[j]);
|
|
509
|
+
const uUnit = ev.score.map((v, j) => v / mant[j]);
|
|
510
|
+
const varUnit = inverse.map((row, i) => row.map((v, j) => v * mant[i] * mant[j]));
|
|
511
|
+
const internal = coefUnit.map((c, j) => ldexp(c, expo[j]));
|
|
512
|
+
const variance = varUnit.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j])));
|
|
424
513
|
// 6. output
|
|
425
514
|
const coefficients = internal.slice();
|
|
426
515
|
if (iterMax > 0 && Math.abs(rank) < p) {
|
|
427
516
|
for (let j = 0; j < p; j++)
|
|
428
|
-
if (
|
|
517
|
+
if (inverse[j][j] === 0)
|
|
429
518
|
coefficients[j] = NaN;
|
|
430
519
|
}
|
|
431
520
|
let centre = 0;
|
|
@@ -439,15 +528,16 @@ export function coxph(time, status, x, options = {}) {
|
|
|
439
528
|
});
|
|
440
529
|
const warnings = new Warnings();
|
|
441
530
|
if (iterMax > 1) {
|
|
442
|
-
|
|
531
|
+
// abs(u' var) in units of 2^-e_j
|
|
532
|
+
const infinity = varUnit.map((_, j) => {
|
|
443
533
|
let s = 0;
|
|
444
534
|
for (let i = 0; i < p; i++)
|
|
445
|
-
s +=
|
|
535
|
+
s += uUnit[i] * varUnit[i][j];
|
|
446
536
|
return Math.abs(s);
|
|
447
537
|
});
|
|
448
538
|
if (ranOut) {
|
|
449
539
|
warnings.add("Ran out of iterations and did not converge");
|
|
450
|
-
if (
|
|
540
|
+
if (maxOf(linearPredictors) > 500 || infinity.some((f) => !Number.isFinite(f))) {
|
|
451
541
|
warnings.add("one or more coefficients may be infinite");
|
|
452
542
|
}
|
|
453
543
|
}
|
|
@@ -455,7 +545,7 @@ export function coxph(time, status, x, options = {}) {
|
|
|
455
545
|
const flagged = [];
|
|
456
546
|
for (let j = 0; j < p; j++) {
|
|
457
547
|
const f = infinity[j];
|
|
458
|
-
if (!Number.isFinite(
|
|
548
|
+
if (!Number.isFinite(uUnit[j]) || (ldexp(f, expo[j]) > eps && f > tolerInf * Math.abs(coefUnit[j])))
|
|
459
549
|
flagged.push(j + 1);
|
|
460
550
|
}
|
|
461
551
|
if (flagged.length > 0) {
|
|
@@ -466,26 +556,30 @@ export function coxph(time, status, x, options = {}) {
|
|
|
466
556
|
// 7. tests and the summary
|
|
467
557
|
const used = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
|
|
468
558
|
const k = used.length;
|
|
469
|
-
|
|
559
|
+
// (in units of 2^e_j)
|
|
560
|
+
const b = used.map((j) => coefUnit[j] - (init === undefined ? 0 : ldexp(init[j], -expo[j])));
|
|
470
561
|
let wald = 0;
|
|
471
562
|
if (k === 1) {
|
|
472
|
-
wald = (b[0] * b[0]) /
|
|
563
|
+
wald = (b[0] * b[0]) / varUnit[used[0]][used[0]];
|
|
473
564
|
}
|
|
474
565
|
else if (k > 1) {
|
|
475
|
-
const v = used.map((i) => used.map((j) =>
|
|
566
|
+
const v = used.map((i) => used.map((j) => varUnit[i][j]));
|
|
476
567
|
cholFactor(v, tolerChol);
|
|
477
568
|
const y = cholSolve(v, b);
|
|
478
569
|
for (let i = 0; i < k; i++)
|
|
479
570
|
wald += b[i] * y[i];
|
|
480
571
|
}
|
|
481
|
-
|
|
482
|
-
const
|
|
483
|
-
const
|
|
572
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
573
|
+
const a2 = (1 - confLevel) / 2;
|
|
574
|
+
const q = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2);
|
|
575
|
+
const seUnit = varUnit.map((row, j) => Math.sqrt(row[j]));
|
|
576
|
+
const se = seUnit.map((v, j) => ldexp(v, expo[j]));
|
|
577
|
+
const z = coefficients.map((c, j) => (Number.isNaN(c) ? c : coefUnit[j]) / seUnit[j]);
|
|
484
578
|
const pz = z.map((v) => pchisq(v * v, 1, { lowerTail: false }));
|
|
485
579
|
const lower = coefficients.map((c, j) => Math.exp(c - q * se[j]));
|
|
486
580
|
const upper = coefficients.map((c, j) => Math.exp(c + q * se[j]));
|
|
487
581
|
const lr = -2 * (loglik[0] - loglik[1]);
|
|
488
|
-
return {
|
|
582
|
+
return reported("coxph", {
|
|
489
583
|
coefficients,
|
|
490
584
|
var: variance,
|
|
491
585
|
loglik,
|
|
@@ -499,6 +593,9 @@ export function coxph(time, status, x, options = {}) {
|
|
|
499
593
|
se,
|
|
500
594
|
z,
|
|
501
595
|
p: pz,
|
|
596
|
+
stdError: se,
|
|
597
|
+
zValue: z,
|
|
598
|
+
pValue: pz,
|
|
502
599
|
lower,
|
|
503
600
|
upper,
|
|
504
601
|
logtest: chisqTest(lr, k),
|
|
@@ -506,5 +603,5 @@ export function coxph(time, status, x, options = {}) {
|
|
|
506
603
|
waldtest: chisqTest(wald, k),
|
|
507
604
|
rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglik[0]) / n) },
|
|
508
605
|
warnings: warnings.list,
|
|
509
|
-
};
|
|
606
|
+
});
|
|
510
607
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type QR } from "../linalg/qr.js";
|
|
2
|
+
/** The warning R gives when some rows are not estimable */
|
|
3
|
+
export declare const NON_ESTIMABLE_WARNING = "prediction from rank-deficient fit; attr(*, \"non-estim\") has doubtful cases";
|
|
4
|
+
/**
|
|
5
|
+
* 0-based indices of the rows of X (full rows, one value per coefficient) whose prediction is not estimable: |x · n|
|
|
6
|
+
* above sqrt(eps) |x| |n| for a null-space vector n. Empty for a full-rank fit.
|
|
7
|
+
*/
|
|
8
|
+
export declare function nonEstimableRows(qr: QR | undefined, rank: number, X: readonly (readonly number[])[]): number[];
|
|
9
|
+
/**
|
|
10
|
+
* Whether the columns of the model matrix `small` lie in the column space of `large` (the same rows): the smaller model
|
|
11
|
+
* is then a special case of the larger one, and their comparison by an F or likelihood ratio test has its usual
|
|
12
|
+
* meaning. Judged by the rank of [large, small] against that of large (LINPACK's tolerance 1e-7, relative to each
|
|
13
|
+
* column's norm, so the units of the predictors do not matter)
|
|
14
|
+
*/
|
|
15
|
+
export declare function nestedColumns(small: readonly (readonly number[])[], large: readonly (readonly number[])[]): boolean;
|