@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/lm.js
CHANGED
|
@@ -13,12 +13,25 @@
|
|
|
13
13
|
// keeps what the analyses of variance need (the effects, the model matrix, the terms).
|
|
14
14
|
import { pf1 } from "../distributions/f.js";
|
|
15
15
|
import { pt1, qt1 } from "../distributions/t.js";
|
|
16
|
-
import {
|
|
16
|
+
import { chol2invColumns } from "../internal/scaledInverse.js";
|
|
17
|
+
import { rangeExponent } from "../linalg/matrix.js";
|
|
17
18
|
import { qr, qrCoef, qrResid } from "../linalg/qr.js";
|
|
19
|
+
import { ldexp, norm2, scaleToUnit } from "../internal/summary.js";
|
|
20
|
+
import { maxOf } from "../internal/extremes.js";
|
|
18
21
|
import { ddAdd, ddDiv, ddMul, ddMulNum, ddSub } from "../special/dd.js";
|
|
19
|
-
import { ddLeastSquares, ddSqrtWeights, ddSumSquares } from "./ddLeastSquares.js";
|
|
22
|
+
import { ddLeastSquares, ddSqrt, ddSqrtWeights, ddSumSquares } from "./ddLeastSquares.js";
|
|
20
23
|
import { parseFormula } from "./formula.js";
|
|
21
24
|
import { design } from "./modelMatrix.js";
|
|
25
|
+
import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
|
|
26
|
+
import { checkDot, checkedDot } from "../linalg/dot.js";
|
|
27
|
+
import { reported } from "../internal/warnings.js";
|
|
28
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
29
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
30
|
+
const LM_KEYS = ["weights", "contrasts", "levels", "intercept"];
|
|
31
|
+
const CONFINT_KEYS = ["level"];
|
|
32
|
+
const PREDICT_KEYS = ["interval", "level"];
|
|
33
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
34
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
22
35
|
/** The formula fit (lm, and aov without Error()) */
|
|
23
36
|
export function lmFormulaFit(formula, d, aov) {
|
|
24
37
|
const y = d.y;
|
|
@@ -28,11 +41,13 @@ export function lmFormulaFit(formula, d, aov) {
|
|
|
28
41
|
const r = core.result;
|
|
29
42
|
const warnings = [...d.warnings];
|
|
30
43
|
if (!aov) {
|
|
31
|
-
// summary.lm: residual variance negligible against the fitted values' mean square and variance
|
|
32
|
-
|
|
44
|
+
// summary.lm: residual variance negligible against the fitted values' mean square and variance (all of the
|
|
45
|
+
// response scaled by 2^-k, as fitted)
|
|
46
|
+
const k = core.yScale ?? 0;
|
|
47
|
+
const f = core.fitRows.map((i) => ldexp(r.fittedValues[i], -k));
|
|
33
48
|
const m = f.reduce((s, v) => s + v, 0) / f.length;
|
|
34
49
|
const v = f.length > 1 ? f.reduce((s, t) => s + (t - m) ** 2, 0) / (f.length - 1) : NaN;
|
|
35
|
-
const resvar = core.rss / r.dfResidual;
|
|
50
|
+
const resvar = (core.rssScaled ?? core.rss) / r.dfResidual;
|
|
36
51
|
if (Number.isFinite(resvar) && resvar < 1e-30 * (m * m + v))
|
|
37
52
|
warnings.push("essentially perfect fit: summary may be unreliable");
|
|
38
53
|
}
|
|
@@ -60,8 +75,9 @@ export function lmFormulaFit(formula, d, aov) {
|
|
|
60
75
|
return out;
|
|
61
76
|
}
|
|
62
77
|
export function lm(x, y, options = {}) {
|
|
78
|
+
checkOptions(options, LM_KEYS, "lm"); // generated: option-keys.mjs
|
|
63
79
|
if (typeof x === "string") {
|
|
64
|
-
return lmFormulaFit(x, design(parseFormula(x), y, { ...options, dropUnusedLevels: true }), false);
|
|
80
|
+
return reported("lm", lmFormulaFit(x, design(parseFormula(x), y, { ...options, dropUnusedLevels: true }), false));
|
|
65
81
|
}
|
|
66
82
|
return lmMatrix(x, y, options);
|
|
67
83
|
}
|
|
@@ -69,29 +85,53 @@ function lmMatrix(x, y, options) {
|
|
|
69
85
|
const intercept = options.intercept ?? true;
|
|
70
86
|
const xr = x.length > 0 && typeof x[0] !== "number" ? x.map((r) => Array.from(r)) : Array.from(x, (v) => [v]);
|
|
71
87
|
const ys = Array.from(y);
|
|
88
|
+
// the shape of all the rows given, before the rows with a missing value are dropped (#463)
|
|
89
|
+
if (xr.some((r) => r.length !== xr[0].length))
|
|
90
|
+
throw new TypeError("all rows of the matrix must have the same length");
|
|
72
91
|
if (xr.length !== ys.length)
|
|
73
92
|
throw new RangeError("variable lengths differ (found for 'x')");
|
|
74
93
|
const wsAll = options.weights === undefined ? undefined : Array.from(options.weights);
|
|
75
94
|
if (wsAll !== undefined && wsAll.length !== ys.length)
|
|
76
95
|
throw new RangeError("variable lengths differ (found for '(weights)')");
|
|
77
|
-
if (wsAll?.some((w) => w < 0))
|
|
78
|
-
throw new RangeError("missing or negative weights not allowed");
|
|
79
96
|
const keep = ys.map((v, i) => !Number.isNaN(v) && xr[i].every((t) => !Number.isNaN(t)) && (wsAll === undefined || !Number.isNaN(wsAll[i])));
|
|
97
|
+
const Wall = wsAll?.filter((_, i) => keep[i]);
|
|
98
|
+
// negative weights among the rows kept only, as the formula interface and R (#455)
|
|
99
|
+
if (Wall?.some((w) => w < 0))
|
|
100
|
+
throw new RangeError("missing or negative weights not allowed");
|
|
80
101
|
const Xall = xr.filter((_, i) => keep[i]).map((r) => (intercept ? [1, ...r] : r));
|
|
81
102
|
const Yall = ys.filter((_, i) => keep[i]);
|
|
82
|
-
const Wall = wsAll?.filter((_, i) => keep[i]);
|
|
83
103
|
return fitLm(Xall, Yall, Wall, intercept).result;
|
|
84
104
|
}
|
|
85
105
|
/**
|
|
86
106
|
* The coefficients, fitted values, residuals, effects and sums of squares of a fit recomputed in double-double on the
|
|
87
|
-
* columns kept by the double-precision decomposition q (its rank and pivoting decide what is aliased)
|
|
107
|
+
* columns kept by the double-precision decomposition q (its rank and pivoting decide what is aliased), with the
|
|
108
|
+
* weights divided by 2^kw (kw even)
|
|
88
109
|
*/
|
|
89
|
-
function preciseFit(Xall, Yall,
|
|
110
|
+
function preciseFit(Xall, Yall, WallGiven, kw, fitRows, q, intercept) {
|
|
90
111
|
const rank = q.rank;
|
|
91
112
|
const piv = q.pivot.slice(0, rank);
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
113
|
+
const Wall = WallGiven?.map((v) => ldexp(v, -kw));
|
|
114
|
+
// sqrt(w 2^-kw); where w 2^-kw falls below the normal range, sqrt(w) 2^(-kw/2) (#194: with weights 1e308 and
|
|
115
|
+
// 1e-308, 1e-308 2^-1022 underflowed to 0 before the square root and the row was left out, its column aliased)
|
|
116
|
+
const sw = ddSqrtWeights(Wall === undefined ? undefined : fitRows.map((i) => Wall[i]), fitRows.length).map((s, k) => {
|
|
117
|
+
if (WallGiven === undefined || Wall === undefined)
|
|
118
|
+
return s;
|
|
119
|
+
const w = WallGiven[fitRows[k]];
|
|
120
|
+
if (w === 0 || Wall[fitRows[k]] >= MIN_NORMAL)
|
|
121
|
+
return s;
|
|
122
|
+
const r = ddSqrt([w, 0]);
|
|
123
|
+
return [ldexp(r[0], -kw / 2), ldexp(r[1], -kw / 2)];
|
|
124
|
+
});
|
|
125
|
+
// a column whose largest entry is outside [2^-256, 2^256] divided by its power of 2 (exact; Q'y does not change, the
|
|
126
|
+
// coefficient is divided back): its squares underflowed in the decomposition (#194, a column of 1e-308 sqrt(w)
|
|
127
|
+
// gave the norm 0 and NaN coefficients)
|
|
128
|
+
const cols = piv.map((j) => {
|
|
129
|
+
const c = fitRows.map((i, k) => ddMulNum(sw[k], Xall[i][j]));
|
|
130
|
+
const e = rangeExponent(c.map((d) => d[0]));
|
|
131
|
+
return { c: e === 0 ? c : c.map((d) => [ldexp(d[0], -e), ldexp(d[1], -e)]), e };
|
|
132
|
+
});
|
|
133
|
+
const { qty, coef: coefScaled } = ddLeastSquares(cols.map(({ c }) => c), fitRows.map((i, k) => ddMulNum(sw[k], Yall[i])));
|
|
134
|
+
const coef = coefScaled.map((b, k) => (cols[k].e === 0 ? b : [ldexp(b[0], -cols[k].e), ldexp(b[1], -cols[k].e)]));
|
|
95
135
|
const coefficients = Xall[0]?.map(() => NaN) ?? [];
|
|
96
136
|
piv.forEach((j, k) => (coefficients[j] = coef[k][0]));
|
|
97
137
|
// fitted values x'b of every row (aliased coefficients count as 0)
|
|
@@ -130,8 +170,64 @@ function preciseFit(Xall, Yall, Wall, fitRows, q, intercept) {
|
|
|
130
170
|
/**
|
|
131
171
|
* Least squares on a full model matrix (the column of ones included when `intercept` is true). Rows of weight 0 are
|
|
132
172
|
* left out of the fit and of the counts.
|
|
173
|
+
*
|
|
174
|
+
* The response is scaled by a power of 2, 2^-k, before the fit (exact; see src/internal/summary.ts), so that its sums
|
|
175
|
+
* of squares stay in range: t, F, R^2 and the p-values come from the scaled fit, and the coefficients, residuals,
|
|
176
|
+
* fitted values, effects, sigma and standard errors are multiplied by 2^k, the residual sum of squares by 2^2k.
|
|
133
177
|
*/
|
|
134
178
|
export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
179
|
+
const k = scaleToUnit([Yall.filter((_, i) => Wall === undefined || Wall[i] !== 0)]).k;
|
|
180
|
+
if (k === 0)
|
|
181
|
+
return zeroWeightRows(fitLmUnit(Xall, Yall, Wall, intercept, precise), Xall, Yall, Wall);
|
|
182
|
+
const core = fitLmUnit(Xall, Yall.map((v) => ldexp(v, -k)), Wall, intercept, precise);
|
|
183
|
+
const r = core.result;
|
|
184
|
+
const back = (v) => ldexp(v, k);
|
|
185
|
+
r.coefficients = r.coefficients.map(back);
|
|
186
|
+
r.residuals = r.residuals.map(back);
|
|
187
|
+
r.fittedValues = r.fittedValues.map(back);
|
|
188
|
+
r.sigma = back(r.sigma);
|
|
189
|
+
r.coefTable.estimate = r.coefTable.estimate.map(back);
|
|
190
|
+
r.coefTable.stdError = r.coefTable.stdError.map(back);
|
|
191
|
+
return zeroWeightRows({ ...core, effects: core.effects.map(back), rss: ldexp(core.rss, 2 * k), yScale: k, rssScaled: core.rss }, Xall, Yall, Wall);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The rows of weight 0 whose fitted value or residual is not finite, taken again in the units of the response (#193):
|
|
195
|
+
* the response is scaled by the 2^-k of the rows in the fit, so a finite response or x'b of a row left out could
|
|
196
|
+
* overflow in the scaled units (y = (1e-308, 1e308), weights (1, 0): the residual 1e308 was Infinity). The fitted
|
|
197
|
+
* value is x'b from the coefficients (aliased ones count as 0), by the exact inner product where the plain sum is not
|
|
198
|
+
* finite (as predict, #195); the residual is y minus it. Rows with finite values keep their bits
|
|
199
|
+
*/
|
|
200
|
+
function zeroWeightRows(core, Xall, Yall, Wall) {
|
|
201
|
+
if (Wall === undefined)
|
|
202
|
+
return core;
|
|
203
|
+
const r = core.result;
|
|
204
|
+
const used = r.coefficients.flatMap((c, j) => (Number.isNaN(c) ? [] : [j]));
|
|
205
|
+
Wall.forEach((w, i) => {
|
|
206
|
+
if (w !== 0)
|
|
207
|
+
return;
|
|
208
|
+
let refit = false;
|
|
209
|
+
if (!Number.isFinite(r.fittedValues[i])) {
|
|
210
|
+
const x = Xall[i];
|
|
211
|
+
const s = used.reduce((t, j) => t + x[j] * r.coefficients[j], 0);
|
|
212
|
+
r.fittedValues[i] = checkDot(s, 0) ? checkedDot(used.map((j) => x[j]), used.map((j) => r.coefficients[j]), s) : s;
|
|
213
|
+
refit = true;
|
|
214
|
+
}
|
|
215
|
+
if (refit || !Number.isFinite(r.residuals[i]))
|
|
216
|
+
r.residuals[i] = Yall[i] - r.fittedValues[i];
|
|
217
|
+
});
|
|
218
|
+
return core;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The exponent qw of a QR decomposition of the model matrix of an lm fit with the weights divided by 2^qw (#199);
|
|
222
|
+
* absent for the decomposition with the weights given
|
|
223
|
+
*/
|
|
224
|
+
const QR_WEIGHT_EXPONENT = new WeakMap();
|
|
225
|
+
/** Whether every entry of a decomposition is finite */
|
|
226
|
+
function finiteQR(q) {
|
|
227
|
+
return q.qr.every((r) => r.every(Number.isFinite)) && q.qraux.every(Number.isFinite);
|
|
228
|
+
}
|
|
229
|
+
/** fitLm on a response already in [1, 2) in absolute value (or one whose scale needs no change) */
|
|
230
|
+
function fitLmUnit(Xall, Yall, Wall, intercept, precise) {
|
|
135
231
|
if (Yall.length === 0)
|
|
136
232
|
throw new RangeError("0 (non-NA) cases");
|
|
137
233
|
// the fit uses the rows of non-zero weight only
|
|
@@ -142,18 +238,48 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
|
142
238
|
const n = Y.length;
|
|
143
239
|
if (n === 0)
|
|
144
240
|
throw new RangeError("all weights are zero");
|
|
241
|
+
// As R's lm.fit and lm.wfit (on the rows of non-zero weight)
|
|
242
|
+
if (X.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
243
|
+
throw new RangeError("NA/NaN/Inf in 'x'");
|
|
244
|
+
if (Y.some((v) => !Number.isFinite(v)))
|
|
245
|
+
throw new RangeError("NA/NaN/Inf in 'y'");
|
|
246
|
+
// an infinite weight (#302): R stops with "NA/NaN/Inf in 'x'" from the weighted columns, but with no columns returns
|
|
247
|
+
// the residuals y and sigma Inf; here an error in both cases (as glm)
|
|
248
|
+
if (W?.some((v) => !Number.isFinite(v)))
|
|
249
|
+
throw new RangeError("non-finite weights not allowed");
|
|
145
250
|
const fitRows = Yall.flatMap((_, i) => (fitRow[i] ? [i] : []));
|
|
146
|
-
|
|
147
|
-
|
|
251
|
+
// The sums of squares are formed with the weights divided by 2^kw (kw even, the largest weight then in [1, 4)):
|
|
252
|
+
// rss, mss and the residual variance below are those of the scaled weights, and sigma, the standard errors, rss and
|
|
253
|
+
// the effects are scaled back (exact powers of 2, so the values are the same wherever nothing overflows). The sums
|
|
254
|
+
// with weights near 1e308 overflowed: R^2 and F were NaN, and sigma too in the formula interface, as R's
|
|
255
|
+
const maxW = W === undefined ? 1 : maxOf(W);
|
|
256
|
+
const kw = Number.isFinite(maxW) ? 2 * Math.floor(Math.floor(Math.log2(maxW)) / 2) : 0;
|
|
257
|
+
// The QR decomposition of the model matrix with rows scaled by sqrt(w), as R's. Where that is not finite and the
|
|
258
|
+
// largest weight is at least 1, it is the decomposition with the weights divided by 2^qw instead (qw = kw + 2, the
|
|
259
|
+
// largest weight then in [1/4, 1), so no entry of sqrt(w) x exceeds x): the coefficients and the residuals do not
|
|
260
|
+
// depend on a common factor of the weights (#199: x near 0.9e308 with weights 2, the column norm 1.97e308
|
|
261
|
+
// overflowed and the coefficients were -Inf and 1e-307, R NaN). `qr` of the result is then that decomposition,
|
|
262
|
+
// recorded in QR_WEIGHT_EXPONENT for predict
|
|
263
|
+
let qw = 0;
|
|
264
|
+
let sw = W?.map(Math.sqrt);
|
|
265
|
+
let Xw = sw === undefined ? X : X.map((r, i) => r.map((v) => v * sw[i]));
|
|
266
|
+
let q = qr(Xw);
|
|
267
|
+
if (W !== undefined && Number.isFinite(maxW) && kw + 2 > 0 && !finiteQR(q)) {
|
|
268
|
+
qw = kw + 2;
|
|
269
|
+
sw = W.map((v) => ldexp(Math.sqrt(v), -qw / 2));
|
|
270
|
+
Xw = X.map((r, i) => r.map((v) => v * sw[i]));
|
|
271
|
+
q = qr(Xw);
|
|
272
|
+
QR_WEIGHT_EXPONENT.set(q, qw);
|
|
273
|
+
}
|
|
148
274
|
const Yw = sw === undefined ? Y : Y.map((v, i) => v * sw[i]);
|
|
149
|
-
const q = qr(Xw);
|
|
150
275
|
const rank = q.rank;
|
|
151
|
-
const
|
|
276
|
+
const scaleW = (v) => ldexp(v, -kw);
|
|
277
|
+
const pf = precise ? preciseFit(Xall, Yall, Wall, kw, fitRows, q, intercept) : undefined;
|
|
152
278
|
const coefficients = pf?.coefficients ?? qrCoef(q, Yw);
|
|
153
279
|
const residuals = pf?.residuals ?? [];
|
|
154
280
|
const fittedValues = pf?.fittedValues ?? [];
|
|
155
281
|
const dfResidual = n - rank;
|
|
156
|
-
const w = W ?? new Array(n).fill(1);
|
|
282
|
+
const w = W?.map(scaleW) ?? new Array(n).fill(1);
|
|
157
283
|
let rss = pf?.rss ?? 0;
|
|
158
284
|
if (pf === undefined) {
|
|
159
285
|
// residuals from Q (the part of Q'y beyond the rank), so a saturated model has residuals of exactly 0, as in R
|
|
@@ -177,15 +303,42 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
|
177
303
|
rss += w[i] * fitResiduals[i] ** 2;
|
|
178
304
|
}
|
|
179
305
|
const fitted = fittedValues.filter((_, i) => fitRow[i]);
|
|
306
|
+
// The residual sum of squares for the weights divided by 2^kw is rss 2^rs. rs is 0 unless a positive weight falls
|
|
307
|
+
// below the normal range when divided by 2^kw (#388: weights 1e308 and 5e-324, the second row's contribution was
|
|
308
|
+
// lost and sigma 0): rss is then the sum of w r^2 with the original weights, each term formed as
|
|
309
|
+
// (w 2^(2a - ks)) (r 2^-a)^2 (a the exponent of r) so that nothing overflows, in units of 2^ks (ks even, from the
|
|
310
|
+
// largest term)
|
|
311
|
+
let rs = 0;
|
|
312
|
+
if (W !== undefined && W.some((v) => v !== 0 && ldexp(v, -kw) < MIN_NORMAL)) {
|
|
313
|
+
const terms = fitRows.flatMap((i, k) => {
|
|
314
|
+
const r = residuals[i];
|
|
315
|
+
return r === 0 ? [] : [{ w: W[k], r, a: Math.floor(Math.log2(Math.abs(r))) }];
|
|
316
|
+
});
|
|
317
|
+
if (terms.length > 0 && terms.every((t) => Number.isFinite(t.r))) {
|
|
318
|
+
const top = Math.max(...terms.map((t) => Math.log2(t.w) + 2 * t.a));
|
|
319
|
+
const ks = 2 * Math.floor(Math.floor(top) / 2);
|
|
320
|
+
let sum = 0;
|
|
321
|
+
for (const t of terms)
|
|
322
|
+
sum += ldexp(t.w, 2 * t.a - ks) * ldexp(t.r, -t.a) ** 2;
|
|
323
|
+
rss = sum;
|
|
324
|
+
rs = ks - kw;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
180
327
|
const resvar = rss / dfResidual;
|
|
181
|
-
const sigma = Math.sqrt(resvar);
|
|
182
|
-
// (R'R)^-1 of the leading rank x rank block, in pivot order
|
|
183
|
-
|
|
184
|
-
|
|
328
|
+
const sigma = ldexp(Math.sqrt(resvar), (kw + rs) / 2);
|
|
329
|
+
// (R'R)^-1 of the leading rank x rank block, in pivot order, for the weights divided by 2^kw (R scaled by 2^-kw/2,
|
|
330
|
+
// exact): (R'R)^-1 of the given weights overflowed for weights below 1e-308, making the standard errors Infinity
|
|
331
|
+
// (R too), though they do not depend on a common factor of the weights
|
|
332
|
+
// (and the columns far from 1 divided by powers of 2 too, review 64: a column of 1e-200 made a standard error Infinity)
|
|
333
|
+
// (with the decomposition of the weights divided by 2^qw, #199, R is used as it is and the standard errors are divided
|
|
334
|
+
// by 2^((qw - kw) / 2): R times that factor could overflow)
|
|
335
|
+
const rShift = qw === 0 ? 0 : (qw - kw) / 2;
|
|
336
|
+
const Rr = q.qr.slice(0, rank).map((row) => row.slice(0, rank).map((v) => (qw === 0 ? ldexp(v, -kw / 2) : v)));
|
|
337
|
+
const { inv: covUnscaled, e: colScale } = rank > 0 ? chol2invColumns(Rr) : { inv: [], e: [] };
|
|
185
338
|
const piv = q.pivot.slice(0, rank);
|
|
186
339
|
const order = piv.map((col, k) => [col, k]).sort((a, b) => a[0] - b[0]);
|
|
187
340
|
const estimate = order.map(([col]) => coefficients[col]);
|
|
188
|
-
const stdError = order.map(([, k]) => Math.sqrt(covUnscaled[k][k] * resvar));
|
|
341
|
+
const stdError = order.map(([, k]) => ldexp(Math.sqrt(covUnscaled[k][k] * resvar), rs / 2 - colScale[k] - rShift));
|
|
189
342
|
const tValue = estimate.map((e, i) => e / stdError[i]);
|
|
190
343
|
const pValue = tValue.map((t) => 2 * pt1(-Math.abs(t), dfResidual, true, false));
|
|
191
344
|
const result = {
|
|
@@ -203,7 +356,7 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
|
203
356
|
};
|
|
204
357
|
const dfInt = intercept ? 1 : 0;
|
|
205
358
|
const numdf = rank - dfInt;
|
|
206
|
-
const core = { result, fitRows, effects: pf?.effects ?? [], rss };
|
|
359
|
+
const core = { result, fitRows, effects: (pf?.effects ?? []).map((e) => ldexp(e, kw / 2)), rss: ldexp(rss, kw + rs) };
|
|
207
360
|
// nothing beyond the intercept: R^2 = 0 and no F test, as in summary.lm
|
|
208
361
|
if (numdf === 0)
|
|
209
362
|
return core;
|
|
@@ -221,13 +374,21 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
|
221
374
|
else
|
|
222
375
|
for (let i = 0; i < n; i++)
|
|
223
376
|
mss += w[i] * fitted[i] ** 2;
|
|
224
|
-
result.rSquared = mss / (mss + rss);
|
|
377
|
+
result.rSquared = mss / (mss + ldexp(rss, rs));
|
|
225
378
|
result.adjRSquared = 1 - (1 - result.rSquared) * ((n - dfInt) / dfResidual);
|
|
226
|
-
const fValue = mss / numdf / resvar;
|
|
379
|
+
const fValue = ldexp(mss / numdf / resvar, -rs);
|
|
227
380
|
result.fStatistic = { value: fValue, numdf, dendf: dfResidual };
|
|
228
381
|
result.fPValue = pf1(fValue, numdf, dfResidual, false, false);
|
|
229
382
|
return core;
|
|
230
383
|
}
|
|
384
|
+
/**
|
|
385
|
+
* The t quantile at (1 + level) / 2. For alpha = (1 - level) / 2 below 1e-8 the upper probability itself: 1 - alpha
|
|
386
|
+
* loses its digits and rounds to 1 below 1.1e-16 (review 58)
|
|
387
|
+
*/
|
|
388
|
+
function tQuantile(level, df) {
|
|
389
|
+
const a2 = (1 - level) / 2;
|
|
390
|
+
return a2 < 1e-8 ? qt1(a2, df, false, false) : qt1((1 + level) / 2, df, true, false);
|
|
391
|
+
}
|
|
231
392
|
/**
|
|
232
393
|
* Confidence intervals for the coefficients of a linear model (NaN for aliased columns), for an `lm` fit.
|
|
233
394
|
* Equivalent to R's `confint()`.
|
|
@@ -242,8 +403,12 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
|
|
|
242
403
|
* @category Linear models and ANOVA
|
|
243
404
|
*/
|
|
244
405
|
export function confint(fit, options = {}) {
|
|
406
|
+
checkOptions(options, CONFINT_KEYS, "confint"); // generated: option-keys.mjs
|
|
245
407
|
const level = options.level ?? 0.95;
|
|
246
|
-
|
|
408
|
+
// R's confint gives NaN limits for a level outside (0, 1) and predict an interval of some other coverage; an error
|
|
409
|
+
if (!(level > 0 && level < 1))
|
|
410
|
+
throw new RangeError("'level' must be between 0 and 1");
|
|
411
|
+
const t = tQuantile(level, fit.dfResidual);
|
|
247
412
|
const { estimate, stdError } = fit.coefTable;
|
|
248
413
|
const lower = fit.coefficients.map(() => NaN);
|
|
249
414
|
const upper = fit.coefficients.map(() => NaN);
|
|
@@ -257,6 +422,14 @@ export function confint(fit, options = {}) {
|
|
|
257
422
|
});
|
|
258
423
|
return { lower, upper };
|
|
259
424
|
}
|
|
425
|
+
/** a b 2^s, formed so that no intermediate step overflows or underflows (a > 0 finite) */
|
|
426
|
+
function scaledProduct(a, b, s) {
|
|
427
|
+
if (b === 0 || !Number.isFinite(b))
|
|
428
|
+
return a * b;
|
|
429
|
+
const ea = Math.floor(Math.log2(a));
|
|
430
|
+
const eb = Math.floor(Math.log2(Math.abs(b)));
|
|
431
|
+
return ldexp(ldexp(a, -ea) * ldexp(b, -eb), ea + eb + s);
|
|
432
|
+
}
|
|
260
433
|
/**
|
|
261
434
|
* Predictions of a linear model at new values of the predictors, with standard errors and optionally intervals, for
|
|
262
435
|
* an `lm` fit (`se.fit = TRUE`). Equivalent to R's `predict()`. Aliased columns are left out, as R does.
|
|
@@ -273,30 +446,66 @@ export function confint(fit, options = {}) {
|
|
|
273
446
|
* @category Linear models and ANOVA
|
|
274
447
|
*/
|
|
275
448
|
export function predict(fit, newdata, options = {}) {
|
|
449
|
+
checkOptions(options, PREDICT_KEYS, "predict"); // generated: option-keys.mjs
|
|
276
450
|
const rows = newdata.length > 0 && typeof newdata[0] !== "number"
|
|
277
451
|
? newdata.map((r) => Array.from(r))
|
|
278
452
|
: Array.from(newdata, (v) => [v]);
|
|
279
453
|
const X = rows.map((r) => (fit.intercept ? [1, ...r] : r));
|
|
454
|
+
if (X.some((r) => r.length !== fit.coefficients.length))
|
|
455
|
+
throw new RangeError("newdata must have one column per predictor of the fit");
|
|
280
456
|
const rank = fit.rank;
|
|
281
457
|
const piv = fit.qr.pivot.slice(0, rank);
|
|
282
458
|
const Rr = fit.qr.qr.slice(0, rank).map((row) => row.slice(0, rank));
|
|
283
|
-
|
|
284
|
-
const
|
|
459
|
+
// R from the weights divided by 2^qw (#199): z is 2^(qw/2) times that of the weights given
|
|
460
|
+
const qrHalf = -(QR_WEIGHT_EXPONENT.get(fit.qr) ?? 0) / 2;
|
|
461
|
+
const used = fit.coefficients.flatMap((c, j) => (Number.isNaN(c) ? [] : [j]));
|
|
462
|
+
const values = X.map((r) => {
|
|
463
|
+
const s = r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0);
|
|
464
|
+
// products of finite values may overflow while x'b is in range (2 * 1e308 - 2 * 1e308), or underflow while the
|
|
465
|
+
// sum is tiny (#395): the exact inner product
|
|
466
|
+
return checkDot(s, 0) ? checkedDot(used.map((j) => r[j]), used.map((j) => fit.coefficients[j]), s) : s;
|
|
467
|
+
});
|
|
285
468
|
// se: || R^-T x_piv || sigma, by forward substitution with R^T
|
|
286
|
-
const
|
|
469
|
+
const forward = (x) => {
|
|
287
470
|
const z = new Array(rank).fill(0);
|
|
288
471
|
for (let i = 0; i < rank; i++) {
|
|
289
|
-
let s =
|
|
472
|
+
let s = x[i];
|
|
290
473
|
for (let k = 0; k < i; k++)
|
|
291
474
|
s -= Rr[k][i] * z[k];
|
|
292
475
|
z[i] = s / Rr[i][i];
|
|
293
476
|
}
|
|
294
|
-
return
|
|
477
|
+
return z;
|
|
478
|
+
};
|
|
479
|
+
const seFit = X.map((r) => {
|
|
480
|
+
const x = piv.map((j) => r[j]);
|
|
481
|
+
const n = norm2(forward(x));
|
|
482
|
+
// sqrt(z'z) sigma, not sqrt(z'z sigma^2): sigma^2 can overflow or underflow where sigma does not
|
|
483
|
+
if ((n >= MIN_NORMAL && n < Infinity) || !x.every(Number.isFinite) || x.every((v) => v === 0)) {
|
|
484
|
+
return qrHalf === 0 || !(n > 0 && n < Infinity) ? n * fit.sigma : scaledProduct(n, fit.sigma, qrHalf);
|
|
485
|
+
}
|
|
486
|
+
// z overflowed or fell below the normal range although x is finite (#196: x = 1e200 on a column of 1e-200 made z
|
|
487
|
+
// about 1e400, Infinity before sigma 4e-201 was applied): z is linear in x, so solve with x divided by the power
|
|
488
|
+
// of 2 of its largest entry (by 2^600 more if that still overflows) and multiply back with sigma in exponent form
|
|
489
|
+
const e = Math.floor(Math.log2(maxOf(x.map(Math.abs))));
|
|
490
|
+
for (const extra of [0, 600]) {
|
|
491
|
+
const ns = norm2(forward(x.map((v) => ldexp(v, -(e + extra)))));
|
|
492
|
+
if (ns < Infinity)
|
|
493
|
+
return ns === 0 ? ns * fit.sigma : scaledProduct(ns, fit.sigma, e + extra + qrHalf);
|
|
494
|
+
}
|
|
495
|
+
return n * fit.sigma;
|
|
295
496
|
});
|
|
296
497
|
const interval = options.interval ?? "none";
|
|
498
|
+
if (interval !== "none" && interval !== "confidence" && interval !== "prediction")
|
|
499
|
+
throw new RangeError(`invalid 'interval': ${String(interval)}`);
|
|
500
|
+
// R's predict.lm (rankdeficient = "warnif"): the rows that are not estimable from a rank-deficient fit
|
|
501
|
+
const nonEstimable = nonEstimableRows(fit.qr, fit.rank, X);
|
|
502
|
+
const extra = nonEstimable.length > 0 ? { nonEstimable, warnings: [NON_ESTIMABLE_WARNING] } : {};
|
|
297
503
|
if (interval === "none")
|
|
298
|
-
return { fit: values, seFit };
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
504
|
+
return reported("predict", { fit: values, seFit, ...extra }, fit);
|
|
505
|
+
const level = options.level ?? 0.95;
|
|
506
|
+
if (!(level > 0 && level < 1))
|
|
507
|
+
throw new RangeError("'level' must be between 0 and 1");
|
|
508
|
+
const t = tQuantile(level, fit.dfResidual);
|
|
509
|
+
const half = seFit.map((s) => t * (interval === "prediction" ? Math.hypot(s, fit.sigma) : s));
|
|
510
|
+
return reported("predict", { fit: values, seFit, lwr: values.map((v, i) => v - half[i]), upr: values.map((v, i) => v + half[i]), ...extra }, fit);
|
|
302
511
|
}
|
package/dist/models/lmer.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export type LmerContrastName = ContrastName | "contr.poly";
|
|
|
11
11
|
/**
|
|
12
12
|
* Options of {@link lmer}. Only the keys below are accepted: R's `weights`, `offset`, `subset`, `naAction`,
|
|
13
13
|
* `na.action`, `control`, `start`, `verbose` and `devFunOnly` give the Error `lmer: argument '<key>' is not
|
|
14
|
-
* supported`, any other key
|
|
14
|
+
* supported`, any other key a RangeError (a key whose value is `undefined` included).
|
|
15
15
|
*
|
|
16
16
|
* @category Mixed models
|
|
17
17
|
*/
|
|
@@ -133,12 +133,27 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
|
|
|
133
133
|
g: number[];
|
|
134
134
|
};
|
|
135
135
|
/**
|
|
136
|
-
* The
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
* value is `undefined` counts as given. Returns the options as an object (`{}` when not given).
|
|
136
|
+
* The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
|
|
137
|
+
* its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
|
|
138
|
+
* minimisation, until none is.
|
|
140
139
|
*/
|
|
141
|
-
|
|
140
|
+
/**
|
|
141
|
+
* The exponent e_k of 2 of each element of θ (internal; issue #11): that of the largest |value| of the column of Z of
|
|
142
|
+
* its row in the term (over the levels). With the columns of Z divided by c_i = 2^e_i, Λ' = C Λ: θ'_k = c_i θ_k, the
|
|
143
|
+
* blocks stay lower triangular with the same signs, and the model (and its criterion) is the same
|
|
144
|
+
*/
|
|
145
|
+
export declare function thetaColumnExponents(s: MixedModelStructure): {
|
|
146
|
+
theta: number[];
|
|
147
|
+
z: number[];
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* The first option check of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section
|
|
151
|
+
* 3): `options` must be an object when given (not null, not an array), and none of its own keys, in order, among those
|
|
152
|
+
* of R that are not supported (the first gives an Error naming it). A key whose value is `undefined` counts as given.
|
|
153
|
+
* The unknown keys are checked after it (a RangeError of checkOptions, generated by scripts/option-keys.mjs, which
|
|
154
|
+
* keeps a first statement calling this function before its checks).
|
|
155
|
+
*/
|
|
156
|
+
export declare function checkLmerOptions(fn: string, options: unknown, unsupported: readonly string[]): void;
|
|
142
157
|
/**
|
|
143
158
|
* A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
|
|
144
159
|
* other than NaN `false` for 0 and `true` otherwise; `null` and anything else are TypeErrors.
|
|
@@ -159,6 +174,10 @@ export declare function logicalOption(value: unknown, defaultValue: boolean): bo
|
|
|
159
174
|
* differ in the 5th to 9th significant digit). Elements on the boundary are exactly 0, and the fit is then singular.
|
|
160
175
|
* The computation is sparse (a sparse Cholesky factorisation, as in lme4), so many groups are handled quickly.
|
|
161
176
|
*
|
|
177
|
+
* The functions that take the fit ({@link lmerSummary}, {@link lmerAnova}, {@link lmerContest} and the others) need
|
|
178
|
+
* the object `lmer` returned itself: a copy of it (`structuredClone`, `{ ...fit }`, JSON or `postMessage`) lacks the
|
|
179
|
+
* internal values they use and is a TypeError. The fields of a copy keep their values.
|
|
180
|
+
*
|
|
162
181
|
* @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
|
|
163
182
|
* @param data The data frame: an object of columns.
|
|
164
183
|
* @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
|
|
@@ -195,8 +214,13 @@ export interface LmerInternals {
|
|
|
195
214
|
structure: MixedModelStructure;
|
|
196
215
|
/** β₀, the least-squares coefficients of y on X, to be added to the fixed effects computed from `structure` */
|
|
197
216
|
beta0: number[];
|
|
198
|
-
/** The data frame given to lmer (the same object, not a copy) */
|
|
217
|
+
/** The data frame given to lmer (the same object, not a copy: fits are compared on the same data object) */
|
|
199
218
|
data: DataFrame;
|
|
219
|
+
/**
|
|
220
|
+
* A copy of the columns of `data` at the time of the fit, from which the analyses rebuild the model (changes to
|
|
221
|
+
* `data` after the fit changed lmerAnova's type I hypotheses silently)
|
|
222
|
+
*/
|
|
223
|
+
snapshot: DataFrame;
|
|
200
224
|
/** The options given to lmer (a copy) */
|
|
201
225
|
options: LmerOptions;
|
|
202
226
|
/** Whether the REML criterion was minimised */
|