@numero-uno-jpn/rstats 0.15.3 → 0.16.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 +166 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +24 -4
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +12 -4
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +5 -0
- package/dist/distributions/f.js +32 -17
- package/dist/distributions/gamma.js +27 -3
- package/dist/distributions/geometric.js +49 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +2 -1
- package/dist/distributions/laplace.js +27 -6
- package/dist/distributions/logistic.js +4 -1
- package/dist/distributions/lognormal.js +8 -2
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +94 -17
- package/dist/distributions/normal.js +9 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +4 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/triangular.js +10 -5
- package/dist/distributions/tukey.js +5 -2
- package/dist/distributions/weibull.js +10 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- 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/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- 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/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/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -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 +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- 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 +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- 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 +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -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 +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -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/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -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 +17 -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.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- 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-ZIX7NYQF.js +0 -2
package/dist/models/coxph.js
CHANGED
|
@@ -12,41 +12,14 @@
|
|
|
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 { ldexp, mean, scaleToUnit } from "../internal/summary.js";
|
|
16
|
+
import { mergeTiedTimes } from "./tiedTimes.js";
|
|
15
17
|
import { Warnings } from "./glmFamily.js";
|
|
18
|
+
import { maxOf } from "../internal/extremes.js";
|
|
16
19
|
const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
17
20
|
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
|
-
}
|
|
21
|
+
/** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
|
|
22
|
+
const SHIFT_LIMIT = 700;
|
|
50
23
|
function evaluate(data, beta, efron) {
|
|
51
24
|
const { time, event, weight, x, stratumEnd } = data;
|
|
52
25
|
const n = time.length;
|
|
@@ -61,8 +34,31 @@ function evaluate(data, beta, efron) {
|
|
|
61
34
|
let riskXX = zeroMatrix();
|
|
62
35
|
const deathX = zeros();
|
|
63
36
|
const deathXX = zeroMatrix();
|
|
37
|
+
let deathRisk = 0;
|
|
38
|
+
// The risk sums (and the sums of the deaths at one time) are held as e^-shift times their values. shift stays 0,
|
|
39
|
+
// and the arithmetic is the plain one, unless a finite exp(eta) would overflow (or, with the sums still empty,
|
|
40
|
+
// underflow): then the sums are rescaled to the new shift, so a log partial likelihood that is finite is not lost
|
|
41
|
+
// to Inf (issue #367). The means and the information are ratios of the sums and do not depend on the shift
|
|
42
|
+
let shift = 0;
|
|
43
|
+
const rescale = (to) => {
|
|
44
|
+
const f = Math.exp(shift - to);
|
|
45
|
+
riskSum *= f;
|
|
46
|
+
deathRisk *= f;
|
|
47
|
+
for (let i = 0; i < p; i++) {
|
|
48
|
+
riskX[i] *= f;
|
|
49
|
+
deathX[i] *= f;
|
|
50
|
+
const row = riskXX[i];
|
|
51
|
+
const drow = deathXX[i];
|
|
52
|
+
for (let l = 0; l <= i; l++) {
|
|
53
|
+
row[l] *= f;
|
|
54
|
+
drow[l] *= f;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
shift = to;
|
|
58
|
+
};
|
|
64
59
|
for (let k = n - 1; k >= 0;) {
|
|
65
60
|
if (stratumEnd[k]) {
|
|
61
|
+
shift = 0;
|
|
66
62
|
riskSum = 0;
|
|
67
63
|
riskX = zeros();
|
|
68
64
|
riskXX = zeroMatrix();
|
|
@@ -70,7 +66,7 @@ function evaluate(data, beta, efron) {
|
|
|
70
66
|
const t = time[k];
|
|
71
67
|
let deaths = 0;
|
|
72
68
|
let deathWeight = 0;
|
|
73
|
-
|
|
69
|
+
deathRisk = 0;
|
|
74
70
|
let j = k;
|
|
75
71
|
do {
|
|
76
72
|
const xj = x[j];
|
|
@@ -78,7 +74,13 @@ function evaluate(data, beta, efron) {
|
|
|
78
74
|
for (let i = 0; i < p; i++)
|
|
79
75
|
eta += beta[i] * xj[i];
|
|
80
76
|
const w = weight[j];
|
|
81
|
-
|
|
77
|
+
if (Number.isFinite(eta)) {
|
|
78
|
+
if (eta - shift > SHIFT_LIMIT)
|
|
79
|
+
rescale(eta);
|
|
80
|
+
else if (eta - shift < -SHIFT_LIMIT && riskSum === 0 && deathRisk === 0)
|
|
81
|
+
shift = eta;
|
|
82
|
+
}
|
|
83
|
+
const r = Math.exp(eta - shift) * w;
|
|
82
84
|
if (!event[j]) {
|
|
83
85
|
riskSum += r;
|
|
84
86
|
for (let i = 0; i < p; i++) {
|
|
@@ -109,7 +111,7 @@ function evaluate(data, beta, efron) {
|
|
|
109
111
|
const stepWeight = deathWeight / steps;
|
|
110
112
|
for (let s = 0; s < steps; s++) {
|
|
111
113
|
riskSum += efron ? deathRisk / share : deathRisk;
|
|
112
|
-
loglik -= stepWeight * Math.log(riskSum);
|
|
114
|
+
loglik -= stepWeight * (Math.log(riskSum) + shift);
|
|
113
115
|
for (let i = 0; i < p; i++) {
|
|
114
116
|
riskX[i] += efron ? deathX[i] / share : deathX[i];
|
|
115
117
|
const mean = riskX[i] / riskSum;
|
|
@@ -159,6 +161,11 @@ function cholFactor(m, tol) {
|
|
|
159
161
|
m[i][i] = 0;
|
|
160
162
|
if (pivot < -8 * limit)
|
|
161
163
|
nonNegative = false;
|
|
164
|
+
// the column dropped as a whole: its residual cross-products below were left (as survival's cholesky2) and the
|
|
165
|
+
// forward substitution of cholSolve and cholInverse used them, so a nearly aliased column still entered the
|
|
166
|
+
// solution and the variance (by about the tolerance; issue #13). With them 0 the fit is that without the column
|
|
167
|
+
for (let j = i + 1; j < p; j++)
|
|
168
|
+
m[j][i] = 0;
|
|
162
169
|
continue;
|
|
163
170
|
}
|
|
164
171
|
rank++;
|
|
@@ -233,6 +240,34 @@ const chisqTest = (statistic, df) => ({
|
|
|
233
240
|
df,
|
|
234
241
|
pValue: pchisq(statistic, df, { lowerTail: false }),
|
|
235
242
|
});
|
|
243
|
+
/** R's result for data without events (survival's coxph returns it before fitting), with summary(fit)'s values */
|
|
244
|
+
function zeroEventResult(rows, p) {
|
|
245
|
+
const n = rows.length;
|
|
246
|
+
const nans = () => new Array(p).fill(NaN);
|
|
247
|
+
const test = chisqTest(0, 0);
|
|
248
|
+
return {
|
|
249
|
+
coefficients: nans(),
|
|
250
|
+
var: Array.from({ length: p }, () => new Array(p).fill(0)),
|
|
251
|
+
loglik: [0, 0],
|
|
252
|
+
score: 0,
|
|
253
|
+
wald: 0,
|
|
254
|
+
iter: 0,
|
|
255
|
+
means: Array.from({ length: p }, (_, j) => mean(rows.map((row) => row[j]))),
|
|
256
|
+
n,
|
|
257
|
+
nevent: 0,
|
|
258
|
+
linearPredictors: new Array(n).fill(0),
|
|
259
|
+
se: new Array(p).fill(0),
|
|
260
|
+
z: nans(),
|
|
261
|
+
p: nans(),
|
|
262
|
+
lower: nans(),
|
|
263
|
+
upper: nans(),
|
|
264
|
+
logtest: test,
|
|
265
|
+
sctest: { ...test },
|
|
266
|
+
waldtest: { ...test },
|
|
267
|
+
rsq: { rsq: 0, maxrsq: 0 },
|
|
268
|
+
warnings: [],
|
|
269
|
+
};
|
|
270
|
+
}
|
|
236
271
|
/**
|
|
237
272
|
* Cox proportional hazards regression. Equivalent to R's `survival::coxph()`. As
|
|
238
273
|
* `coxph(Surv(time, status) ~ x [+ strata(strata)], weights, ties, init, control)` for right-censored data, with the
|
|
@@ -263,8 +298,12 @@ export function coxph(time, status, x, options = {}) {
|
|
|
263
298
|
const tolerInf = control.tolerInf ?? Math.sqrt(eps);
|
|
264
299
|
if (ties !== "efron" && ties !== "breslow")
|
|
265
300
|
throw new RangeError(`invalid 'ties': ${String(ties)}`);
|
|
266
|
-
if (!(eps > 0))
|
|
267
|
-
throw new RangeError("'eps' must be positive");
|
|
301
|
+
if (!(eps > 0 && eps < Infinity))
|
|
302
|
+
throw new RangeError("'eps' must be a positive finite number");
|
|
303
|
+
if (!(tolerChol > 0 && tolerChol < Infinity))
|
|
304
|
+
throw new RangeError("'tolerChol' must be a positive finite number");
|
|
305
|
+
if (!(tolerInf > 0 && tolerInf < Infinity))
|
|
306
|
+
throw new RangeError("'tolerInf' must be a positive finite number");
|
|
268
307
|
if (!(Number.isInteger(iterMax) && iterMax >= 0))
|
|
269
308
|
throw new RangeError("'iterMax' must be a non-negative integer");
|
|
270
309
|
if (!(confLevel > 0 && confLevel < 1))
|
|
@@ -283,6 +322,8 @@ export function coxph(time, status, x, options = {}) {
|
|
|
283
322
|
throw new RangeError("the rows of 'x' must have the same length");
|
|
284
323
|
if (init !== undefined && init.length !== p)
|
|
285
324
|
throw new RangeError("'init' must have one value per column of 'x'");
|
|
325
|
+
if (init?.some((v) => !Number.isFinite(v)))
|
|
326
|
+
throw new RangeError("'init' must contain finite values");
|
|
286
327
|
// 1. the rows used
|
|
287
328
|
const keep = [];
|
|
288
329
|
for (let i = 0; i < nIn; i++) {
|
|
@@ -295,11 +336,17 @@ export function coxph(time, status, x, options = {}) {
|
|
|
295
336
|
const s = status[i];
|
|
296
337
|
if (s !== 0 && s !== 1)
|
|
297
338
|
throw new RangeError("'status' must be 0 (censored) or 1 (event)");
|
|
339
|
+
// a subject censored at Infinity is at risk throughout (R stops on any infinite time); an event cannot happen at an
|
|
340
|
+
// infinite time, nor anything at -Infinity (as survdiff and survfit)
|
|
341
|
+
if (time[i] === -Infinity || (time[i] === Infinity && s === 1))
|
|
342
|
+
throw new RangeError("event times must be finite");
|
|
298
343
|
keep.push(i);
|
|
299
344
|
}
|
|
300
345
|
const n = keep.length;
|
|
301
346
|
if (n === 0)
|
|
302
347
|
throw new RangeError("no observations without missing values");
|
|
348
|
+
if (keep.some((i) => x[i].some((v) => !Number.isFinite(v))))
|
|
349
|
+
throw new RangeError("'x' contains infinite values");
|
|
303
350
|
const w = keep.map((i) => (weights === undefined ? 1 : weights[i]));
|
|
304
351
|
if (w.some((v) => !(v > 0)))
|
|
305
352
|
throw new RangeError("Invalid weights, must be >0");
|
|
@@ -308,6 +355,11 @@ export function coxph(time, status, x, options = {}) {
|
|
|
308
355
|
let nevent = 0;
|
|
309
356
|
for (const i of keep)
|
|
310
357
|
nevent += status[i];
|
|
358
|
+
// no events: R's coxph returns before the fit (issue #472) with NA coefficients, a zero variance, zero log likelihood,
|
|
359
|
+
// score, Wald statistic and iterations, and the unweighted column means of all covariates (nocenter ignored); `init`
|
|
360
|
+
// is not an estimate here
|
|
361
|
+
if (nevent === 0)
|
|
362
|
+
return zeroEventResult(keep.map((i) => x[i]), p);
|
|
311
363
|
const mergedTime = mergeTiedTimes(keep.map((i) => time[i]));
|
|
312
364
|
let stratumOf = new Array(n).fill(0);
|
|
313
365
|
if (strata !== undefined) {
|
|
@@ -326,25 +378,39 @@ export function coxph(time, status, x, options = {}) {
|
|
|
326
378
|
const sortedW = order.map((k) => w[k]);
|
|
327
379
|
const xs = order.map((k) => x[keep[k]].slice());
|
|
328
380
|
const means = new Array(p).fill(0);
|
|
381
|
+
// the scale of column j is scales[j] 2^-shift[j]
|
|
329
382
|
const scales = new Array(p).fill(1);
|
|
383
|
+
const shift = new Array(p).fill(0);
|
|
330
384
|
const exempt = new Set(nocenter);
|
|
331
385
|
for (let j = 0; j < p; j++) {
|
|
332
386
|
if (xs.every((row) => exempt.has(row[j])))
|
|
333
387
|
continue;
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
sum
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
388
|
+
const column = xs.map((row) => row[j]);
|
|
389
|
+
const centreScale = (col) => {
|
|
390
|
+
let sum = 0;
|
|
391
|
+
for (let k = 0; k < n; k++)
|
|
392
|
+
sum += sortedW[k] * col[k];
|
|
393
|
+
const m = sum / totalWeight;
|
|
394
|
+
let absSum = 0;
|
|
395
|
+
const d = col.map((v, k) => {
|
|
396
|
+
absSum += sortedW[k] * Math.abs(v - m);
|
|
397
|
+
return v - m;
|
|
398
|
+
});
|
|
399
|
+
const s = absSum === 0 ? 1 : totalWeight / absSum;
|
|
400
|
+
return { m, s, d, ok: Number.isFinite(m) && s >= 2 ** -1022 && s < Infinity };
|
|
401
|
+
};
|
|
402
|
+
let fit = centreScale(column);
|
|
403
|
+
// the sums overflow for covariates around 1e308, and the scale for subnormal ones (#87; the column became 0 or
|
|
404
|
+
// NaN): then in the units 2^c of the column's largest value, where the scaled column (x - m) s is the same
|
|
405
|
+
if (!fit.ok) {
|
|
406
|
+
const { groups, k: c } = scaleToUnit([column]);
|
|
407
|
+
fit = centreScale(groups[0]);
|
|
408
|
+
shift[j] = c;
|
|
342
409
|
}
|
|
343
|
-
const s = absSum === 0 ? 1 : totalWeight / absSum;
|
|
344
410
|
for (let k = 0; k < n; k++)
|
|
345
|
-
xs[k][j]
|
|
346
|
-
means[j] = m;
|
|
347
|
-
scales[j] = s;
|
|
411
|
+
xs[k][j] = fit.d[k] * fit.s;
|
|
412
|
+
means[j] = ldexp(fit.m, shift[j]);
|
|
413
|
+
scales[j] = fit.s;
|
|
348
414
|
}
|
|
349
415
|
const data = {
|
|
350
416
|
time: order.map((k) => mergedTime[k]),
|
|
@@ -355,7 +421,7 @@ export function coxph(time, status, x, options = {}) {
|
|
|
355
421
|
};
|
|
356
422
|
const efron = ties === "efron";
|
|
357
423
|
// 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]);
|
|
424
|
+
let beta = init === undefined ? new Array(p).fill(0) : init.map((v, j) => ldexp(v / scales[j], shift[j]));
|
|
359
425
|
let ev = evaluate(data, beta, efron);
|
|
360
426
|
const loglik = [ev.loglik, ev.loglik];
|
|
361
427
|
let factor = ev.info.map((row) => row.slice());
|
|
@@ -380,7 +446,9 @@ export function coxph(time, status, x, options = {}) {
|
|
|
380
446
|
factor = ev.info.map((row) => row.slice());
|
|
381
447
|
rank = cholFactor(factor, tolerChol);
|
|
382
448
|
const finite = Number.isFinite(ev.loglik) && ev.score.every(Number.isFinite) && ev.info.every((row) => row.every(Number.isFinite));
|
|
383
|
-
|
|
449
|
+
// an unchanged log likelihood is converged too (both 0, as for coxph([1], [1], [[0]]), made the ratio 0/0 = NaN and
|
|
450
|
+
// ran out of iterations, as R)
|
|
451
|
+
if (finite && (ev.loglik === best || Math.abs(1 - best / ev.loglik) <= eps)) {
|
|
384
452
|
converged = true;
|
|
385
453
|
loglik[1] = ev.loglik;
|
|
386
454
|
beta = next;
|
|
@@ -417,15 +485,24 @@ export function coxph(time, status, x, options = {}) {
|
|
|
417
485
|
}
|
|
418
486
|
}
|
|
419
487
|
}
|
|
420
|
-
// back to the original scale
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
488
|
+
// 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,
|
|
489
|
+
// the variance and the score are first formed in units of 2^e_j, where they stay in range whatever the units of the
|
|
490
|
+
// covariates, and scaled back by powers of 2 only for the output. Unitless quantities (z, the Wald test, the check
|
|
491
|
+
// for infinite coefficients) are computed in these units: the same bits as in the original units when nothing
|
|
492
|
+
// overflows, and the Wald test's Cholesky pivots are not dropped because the covariates have different units
|
|
493
|
+
const scaleExpo = scales.map((s) => Math.floor(Math.log2(s)));
|
|
494
|
+
const mant = scales.map((s, j) => ldexp(s, -scaleExpo[j]));
|
|
495
|
+
const expo = scaleExpo.map((e, j) => e - shift[j]);
|
|
496
|
+
const coefUnit = beta.map((b, j) => b * mant[j]);
|
|
497
|
+
const uUnit = ev.score.map((v, j) => v / mant[j]);
|
|
498
|
+
const varUnit = inverse.map((row, i) => row.map((v, j) => v * mant[i] * mant[j]));
|
|
499
|
+
const internal = coefUnit.map((c, j) => ldexp(c, expo[j]));
|
|
500
|
+
const variance = varUnit.map((row, i) => row.map((v, j) => ldexp(v, expo[i] + expo[j])));
|
|
424
501
|
// 6. output
|
|
425
502
|
const coefficients = internal.slice();
|
|
426
503
|
if (iterMax > 0 && Math.abs(rank) < p) {
|
|
427
504
|
for (let j = 0; j < p; j++)
|
|
428
|
-
if (
|
|
505
|
+
if (inverse[j][j] === 0)
|
|
429
506
|
coefficients[j] = NaN;
|
|
430
507
|
}
|
|
431
508
|
let centre = 0;
|
|
@@ -439,15 +516,16 @@ export function coxph(time, status, x, options = {}) {
|
|
|
439
516
|
});
|
|
440
517
|
const warnings = new Warnings();
|
|
441
518
|
if (iterMax > 1) {
|
|
442
|
-
|
|
519
|
+
// abs(u' var) in units of 2^-e_j
|
|
520
|
+
const infinity = varUnit.map((_, j) => {
|
|
443
521
|
let s = 0;
|
|
444
522
|
for (let i = 0; i < p; i++)
|
|
445
|
-
s +=
|
|
523
|
+
s += uUnit[i] * varUnit[i][j];
|
|
446
524
|
return Math.abs(s);
|
|
447
525
|
});
|
|
448
526
|
if (ranOut) {
|
|
449
527
|
warnings.add("Ran out of iterations and did not converge");
|
|
450
|
-
if (
|
|
528
|
+
if (maxOf(linearPredictors) > 500 || infinity.some((f) => !Number.isFinite(f))) {
|
|
451
529
|
warnings.add("one or more coefficients may be infinite");
|
|
452
530
|
}
|
|
453
531
|
}
|
|
@@ -455,7 +533,7 @@ export function coxph(time, status, x, options = {}) {
|
|
|
455
533
|
const flagged = [];
|
|
456
534
|
for (let j = 0; j < p; j++) {
|
|
457
535
|
const f = infinity[j];
|
|
458
|
-
if (!Number.isFinite(
|
|
536
|
+
if (!Number.isFinite(uUnit[j]) || (ldexp(f, expo[j]) > eps && f > tolerInf * Math.abs(coefUnit[j])))
|
|
459
537
|
flagged.push(j + 1);
|
|
460
538
|
}
|
|
461
539
|
if (flagged.length > 0) {
|
|
@@ -466,21 +544,25 @@ export function coxph(time, status, x, options = {}) {
|
|
|
466
544
|
// 7. tests and the summary
|
|
467
545
|
const used = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
|
|
468
546
|
const k = used.length;
|
|
469
|
-
|
|
547
|
+
// (in units of 2^e_j)
|
|
548
|
+
const b = used.map((j) => coefUnit[j] - (init === undefined ? 0 : ldexp(init[j], -expo[j])));
|
|
470
549
|
let wald = 0;
|
|
471
550
|
if (k === 1) {
|
|
472
|
-
wald = (b[0] * b[0]) /
|
|
551
|
+
wald = (b[0] * b[0]) / varUnit[used[0]][used[0]];
|
|
473
552
|
}
|
|
474
553
|
else if (k > 1) {
|
|
475
|
-
const v = used.map((i) => used.map((j) =>
|
|
554
|
+
const v = used.map((i) => used.map((j) => varUnit[i][j]));
|
|
476
555
|
cholFactor(v, tolerChol);
|
|
477
556
|
const y = cholSolve(v, b);
|
|
478
557
|
for (let i = 0; i < k; i++)
|
|
479
558
|
wald += b[i] * y[i];
|
|
480
559
|
}
|
|
481
|
-
|
|
482
|
-
const
|
|
483
|
-
const
|
|
560
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
561
|
+
const a2 = (1 - confLevel) / 2;
|
|
562
|
+
const q = a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2);
|
|
563
|
+
const seUnit = varUnit.map((row, j) => Math.sqrt(row[j]));
|
|
564
|
+
const se = seUnit.map((v, j) => ldexp(v, expo[j]));
|
|
565
|
+
const z = coefficients.map((c, j) => (Number.isNaN(c) ? c : coefUnit[j]) / seUnit[j]);
|
|
484
566
|
const pz = z.map((v) => pchisq(v * v, 1, { lowerTail: false }));
|
|
485
567
|
const lower = coefficients.map((c, j) => Math.exp(c - q * se[j]));
|
|
486
568
|
const upper = coefficients.map((c, j) => Math.exp(c + q * se[j]));
|
|
@@ -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;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Estimability of predictions from a rank-deficient fit (R's predict.lm with rankdeficient = "warnif"). Written for
|
|
2
|
+
// rStats.js: a row x of the model matrix gives an estimable prediction when it is orthogonal to the null space of the
|
|
3
|
+
// fit's model matrix, whose basis follows from the pivoted QR decomposition: for each aliased column k (pivoted
|
|
4
|
+
// position >= rank), the vector with 1 at k and -R11^-1 R12[, k] on the first rank pivoted positions.
|
|
5
|
+
import { qr } from "../linalg/qr.js";
|
|
6
|
+
import { scaleToUnit } from "../internal/summary.js";
|
|
7
|
+
/** The warning R gives when some rows are not estimable */
|
|
8
|
+
export const NON_ESTIMABLE_WARNING = 'prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';
|
|
9
|
+
/**
|
|
10
|
+
* 0-based indices of the rows of X (full rows, one value per coefficient) whose prediction is not estimable: |x · n|
|
|
11
|
+
* above sqrt(eps) |x| |n| for a null-space vector n. Empty for a full-rank fit.
|
|
12
|
+
*/
|
|
13
|
+
export function nonEstimableRows(qr, rank, X) {
|
|
14
|
+
if (qr === undefined)
|
|
15
|
+
return [];
|
|
16
|
+
const p = qr.pivot.length;
|
|
17
|
+
if (rank >= p)
|
|
18
|
+
return [];
|
|
19
|
+
const R = qr.qr;
|
|
20
|
+
const piv = qr.pivot;
|
|
21
|
+
const basis = [];
|
|
22
|
+
for (let k = rank; k < p; k++) {
|
|
23
|
+
// z = -R11^-1 R12[, k] by back substitution; the vector in coefficient order
|
|
24
|
+
const z = new Array(rank).fill(0);
|
|
25
|
+
for (let i = rank - 1; i >= 0; i--) {
|
|
26
|
+
let s = -R[i][k];
|
|
27
|
+
for (let j = i + 1; j < rank; j++)
|
|
28
|
+
s -= R[i][j] * z[j];
|
|
29
|
+
z[i] = s / R[i][i];
|
|
30
|
+
}
|
|
31
|
+
const v = new Array(p).fill(0);
|
|
32
|
+
for (let i = 0; i < rank; i++)
|
|
33
|
+
v[piv[i]] = z[i];
|
|
34
|
+
v[piv[k]] = 1;
|
|
35
|
+
basis.push(v);
|
|
36
|
+
}
|
|
37
|
+
const tol = Math.sqrt(Number.EPSILON);
|
|
38
|
+
const norm = (v) => Math.hypot(...v);
|
|
39
|
+
// the test does not depend on the units of x and v: each is divided by a power of 2 that brings its largest entry
|
|
40
|
+
// into [1, 2), so that the dot product and the product of the norms cannot overflow (with x of 1e308, both were
|
|
41
|
+
// Infinity and the row counted as estimable, #260). The division is exact, so where nothing overflowed or
|
|
42
|
+
// underflowed the comparison is the same
|
|
43
|
+
const unit = (v) => scaleToUnit([v]).groups[0];
|
|
44
|
+
const units = basis.map((v) => {
|
|
45
|
+
const u = unit(v);
|
|
46
|
+
return { u, n: norm(u) };
|
|
47
|
+
});
|
|
48
|
+
const out = [];
|
|
49
|
+
X.forEach((row, r) => {
|
|
50
|
+
const x = unit(row);
|
|
51
|
+
const nx = norm(x);
|
|
52
|
+
if (units.some(({ u, n }) => Math.abs(x.reduce((s, xi, j) => s + xi * u[j], 0)) > tol * nx * n))
|
|
53
|
+
out.push(r);
|
|
54
|
+
});
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Whether the columns of the model matrix `small` lie in the column space of `large` (the same rows): the smaller model
|
|
59
|
+
* is then a special case of the larger one, and their comparison by an F or likelihood ratio test has its usual
|
|
60
|
+
* meaning. Judged by the rank of [large, small] against that of large (LINPACK's tolerance 1e-7, relative to each
|
|
61
|
+
* column's norm, so the units of the predictors do not matter)
|
|
62
|
+
*/
|
|
63
|
+
export function nestedColumns(small, large) {
|
|
64
|
+
if (small.length === 0 || small[0].length === 0)
|
|
65
|
+
return true;
|
|
66
|
+
const rl = large.length === 0 || large[0].length === 0 ? 0 : qr(large).rank;
|
|
67
|
+
return qr(large.map((r, i) => [...r, ...small[i]])).rank === rl;
|
|
68
|
+
}
|
package/dist/models/formula.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export interface ParsedFormula {
|
|
|
46
46
|
* @param allowBars Accept the random-effects terms `(lhs | group)` and `(lhs || group)` (mixed models only).
|
|
47
47
|
*/
|
|
48
48
|
export declare function parseFormula(formula: string, allowError?: boolean, allowBars?: boolean): ParsedFormula;
|
|
49
|
-
/** The `Error()` terms of a right-hand side (
|
|
49
|
+
/** The `Error()` terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
|
|
50
50
|
export declare function splitErrorTerms(rhs: FormulaNode): {
|
|
51
51
|
treatment: FormulaNode | undefined;
|
|
52
52
|
errors: FormulaNode[];
|
package/dist/models/formula.js
CHANGED
|
@@ -14,6 +14,13 @@
|
|
|
14
14
|
// R deparses it (for the terms' labels).
|
|
15
15
|
import { formatR } from "../htest/core/simulate.js";
|
|
16
16
|
const invalid = (why) => new SyntaxError(`invalid formula: ${why}`);
|
|
17
|
+
/**
|
|
18
|
+
* A syntactic name (#461): it starts with a letter, a letter number, `.` or a digit that is not ASCII (an ASCII digit,
|
|
19
|
+
* or `.` and an ASCII digit, starts a number; `_` cannot start a name), and goes on with letters, numbers that are not
|
|
20
|
+
* symbols, combining marks, `.` and `_`. The classes are Unicode properties: R on Windows takes the same letters and
|
|
21
|
+
* digits, but no combining marks and nothing outside the BMP (R on Linux takes both, from glibc's tables).
|
|
22
|
+
*/
|
|
23
|
+
const NAME = /^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;
|
|
17
24
|
function tokenize(s, allowBars) {
|
|
18
25
|
const out = [];
|
|
19
26
|
let i = 0;
|
|
@@ -29,10 +36,10 @@ function tokenize(s, allowBars) {
|
|
|
29
36
|
i += m[0].length;
|
|
30
37
|
continue;
|
|
31
38
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
out.push({ kind: "name", text:
|
|
35
|
-
i +=
|
|
39
|
+
const name = NAME.exec(s.slice(i));
|
|
40
|
+
if (name !== null) {
|
|
41
|
+
out.push({ kind: "name", text: name[0] });
|
|
42
|
+
i += name[0].length;
|
|
36
43
|
continue;
|
|
37
44
|
}
|
|
38
45
|
if (s.startsWith("%in%", i)) {
|
|
@@ -134,7 +141,7 @@ export function parseFormula(formula, allowError = false, allowBars = false) {
|
|
|
134
141
|
throw invalid("unexpected input after the formula");
|
|
135
142
|
return { response, rhs };
|
|
136
143
|
}
|
|
137
|
-
/** The `Error()` terms of a right-hand side (
|
|
144
|
+
/** The `Error()` terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
|
|
138
145
|
export function splitErrorTerms(rhs) {
|
|
139
146
|
const errors = [];
|
|
140
147
|
const strip = (n) => {
|
|
@@ -142,6 +149,11 @@ export function splitErrorTerms(rhs) {
|
|
|
142
149
|
errors.push(n.arg);
|
|
143
150
|
return undefined;
|
|
144
151
|
}
|
|
152
|
+
if (n.type === "paren") {
|
|
153
|
+
// y ~ x + (Error(id)) and y ~ (x + Error(id)): parentheses do not hide the term, as R's terms()
|
|
154
|
+
const a = strip(n.arg);
|
|
155
|
+
return a === undefined ? undefined : { ...n, arg: a };
|
|
156
|
+
}
|
|
145
157
|
if (n.type === "binary" && n.op === "+") {
|
|
146
158
|
const l = strip(n.left);
|
|
147
159
|
const r = strip(n.right);
|
|
@@ -350,9 +362,9 @@ export function expandRhs(rhs, index, dot) {
|
|
|
350
362
|
let e = n.right;
|
|
351
363
|
while (e.type === "paren")
|
|
352
364
|
e = e.arg;
|
|
353
|
-
// n is truncated towards zero (R's asInteger: ^2.5 is ^2)
|
|
365
|
+
// n is truncated towards zero (R's asInteger: ^2.5 is ^2; beyond the int range, as 1e999, NA and an error)
|
|
354
366
|
const p = e.type === "num" ? Math.trunc(e.value) : NaN;
|
|
355
|
-
if (!(p >= 2))
|
|
367
|
+
if (!(p >= 2 && p <= 2147483647))
|
|
356
368
|
throw new Error("invalid power in formula");
|
|
357
369
|
let cur = a;
|
|
358
370
|
for (let k = 1; k < p; k++) {
|
|
@@ -360,7 +372,13 @@ export function expandRhs(rhs, index, dot) {
|
|
|
360
372
|
for (const s of a)
|
|
361
373
|
for (const t of cur)
|
|
362
374
|
nxt.push(union(s, t));
|
|
363
|
-
|
|
375
|
+
const next = dedupe(nxt);
|
|
376
|
+
// a fixed point (the same terms in the same order) stays one: the remaining steps change nothing, so a
|
|
377
|
+
// large power ends after at most as many steps as there are variables (#294)
|
|
378
|
+
const same = next.length === cur.length && next.every((t, i) => keyOf(t) === keyOf(cur[i]));
|
|
379
|
+
cur = next;
|
|
380
|
+
if (same)
|
|
381
|
+
break;
|
|
364
382
|
}
|
|
365
383
|
return cur;
|
|
366
384
|
}
|
package/dist/models/glm.d.ts
CHANGED
|
@@ -61,6 +61,8 @@ export interface GlmModel {
|
|
|
61
61
|
maxit: number;
|
|
62
62
|
/** Starting coefficients, if given. */
|
|
63
63
|
start: number[] | undefined;
|
|
64
|
+
/** k when the fit was computed on the response scaled by 2^-k (gaussian on the identity link; see scaledView). */
|
|
65
|
+
yScale?: number;
|
|
64
66
|
}
|
|
65
67
|
/**
|
|
66
68
|
* Result of {@link glm}: R's `glm` object.
|
|
@@ -147,7 +149,6 @@ export interface IrlsFit {
|
|
|
147
149
|
workingWeights: number[];
|
|
148
150
|
workingResiduals: number[];
|
|
149
151
|
}
|
|
150
|
-
/** Iteratively reweighted least squares (glm-behaviour.md, "Fitting") */
|
|
151
152
|
export declare function irls(inp: IrlsInput, warnings: Warnings): IrlsFit;
|
|
152
153
|
/** Fits a model from its stored data, with the columns `cols` of the model matrix (all by default) */
|
|
153
154
|
export declare function refit(model: GlmModel, cols: number[], warnings: Warnings, control?: {
|
|
@@ -186,6 +187,15 @@ export declare function refit(model: GlmModel, cols: number[], warnings: Warning
|
|
|
186
187
|
* @category Generalized linear models
|
|
187
188
|
*/
|
|
188
189
|
export declare function glm(x: MatrixInput | Sample, y: Sample | MatrixInput, options?: GlmOptions): GlmResult;
|
|
190
|
+
/**
|
|
191
|
+
* The fit to compute with and its scale k: for a fit of a response scaled by 2^-k (see glm), that scaled fit, whose
|
|
192
|
+
* quantities with units are 2^-k (or 2^-2k) times the fit's; otherwise the fit itself with k = 0. The functions on a
|
|
193
|
+
* fit compute on it (statistics without units unchanged) and scale back only what has units
|
|
194
|
+
*/
|
|
195
|
+
export declare function scaledView(fit: GlmResult): {
|
|
196
|
+
fit: GlmResult;
|
|
197
|
+
k: number;
|
|
198
|
+
};
|
|
189
199
|
/** The family object of a fit */
|
|
190
200
|
export declare function familyOf(fit: GlmResult): Family;
|
|
191
201
|
/** Pearson dispersion of summary.glm (1 for binomial and poisson) */
|
|
@@ -226,6 +236,22 @@ export interface GlmSummary {
|
|
|
226
236
|
/** Warnings (such as "observations with zero weight not used for calculating dispersion"). */
|
|
227
237
|
warnings: string[];
|
|
228
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* A dispersion given by the user: a non-negative finite number (a negative one gave NaN standard errors, as R's with a
|
|
241
|
+
* warning; 0 gives standard errors of 0, as R)
|
|
242
|
+
*/
|
|
243
|
+
export declare function checkDispersion(d: number): number;
|
|
244
|
+
/**
|
|
245
|
+
* A dispersion d given by the user, in the units of a fit computed on the response scaled by 2^-k (scaledView), as
|
|
246
|
+
* m 4^s: d 2^-2k with s = 0 where that is 0 or in the normal range (the old value, the same bits); where it underflows
|
|
247
|
+
* or overflows although d does not (k = 1023 for a response of 1e308, where d = 1 gave 0 and standard errors 0,
|
|
248
|
+
* #349), m is d brought to [1, 4) by an even power of 2, 4^h, and s = h - k, for the callers to apply 2^s and 4^s
|
|
249
|
+
* where the result is in range
|
|
250
|
+
*/
|
|
251
|
+
export declare function scaledDispersion(d: number, k: number): {
|
|
252
|
+
m: number;
|
|
253
|
+
s: number;
|
|
254
|
+
};
|
|
229
255
|
/**
|
|
230
256
|
* Summary of a generalized linear model: the dispersion, the coefficient table and the covariance of the estimates,
|
|
231
257
|
* for a `glm` fit. Equivalent to R's `summary()`.
|
|
@@ -241,7 +267,7 @@ export interface GlmSummary {
|
|
|
241
267
|
*
|
|
242
268
|
* @category Generalized linear models
|
|
243
269
|
*/
|
|
244
|
-
export declare function glmSummary(
|
|
270
|
+
export declare function glmSummary(given: GlmResult, options?: GlmSummaryOptions): GlmSummary;
|
|
245
271
|
/**
|
|
246
272
|
* Kinds of residuals of {@link glmResiduals}.
|
|
247
273
|
*
|
|
@@ -287,7 +313,7 @@ export declare function glmHatvalues(fit: GlmResult): number[];
|
|
|
287
313
|
*
|
|
288
314
|
* @category Generalized linear models
|
|
289
315
|
*/
|
|
290
|
-
export declare function glmRstandard(
|
|
316
|
+
export declare function glmRstandard(given: GlmResult, options?: GlmSummaryOptions): number[];
|
|
291
317
|
/**
|
|
292
318
|
* Cook's distances, for the rows of non-zero prior weight, for a `glm` fit. Equivalent to R's `cooks.distance()`.
|
|
293
319
|
*
|
|
@@ -299,7 +325,7 @@ export declare function glmRstandard(fit: GlmResult, options?: GlmSummaryOptions
|
|
|
299
325
|
*
|
|
300
326
|
* @category Generalized linear models
|
|
301
327
|
*/
|
|
302
|
-
export declare function glmCooksDistance(
|
|
328
|
+
export declare function glmCooksDistance(given: GlmResult, options?: GlmSummaryOptions): number[];
|
|
303
329
|
/**
|
|
304
330
|
* Options for {@link glmPredict}.
|
|
305
331
|
*
|
|
@@ -328,9 +354,13 @@ export interface GlmPredictOptions {
|
|
|
328
354
|
*
|
|
329
355
|
* @category Generalized linear models
|
|
330
356
|
*/
|
|
331
|
-
export declare function glmPredict(
|
|
357
|
+
export declare function glmPredict(given: GlmResult, options?: GlmPredictOptions): {
|
|
332
358
|
/** Predictions on the scale of `type`, one per row. */
|
|
333
359
|
fit: number[];
|
|
334
360
|
/** Their standard errors (R's `se.fit`). */
|
|
335
361
|
seFit: number[];
|
|
362
|
+
/** 0-based rows of `newdata` whose prediction is not estimable from a rank-deficient fit (R's `attr(, "non-estim")`); present only when there are some. */
|
|
363
|
+
nonEstimable?: number[];
|
|
364
|
+
/** R's warning for those rows; present only when there are some. */
|
|
365
|
+
warnings?: string[];
|
|
336
366
|
};
|