@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/lmerTest.js
CHANGED
|
@@ -16,9 +16,16 @@ import { pf1 } from "../distributions/f.js";
|
|
|
16
16
|
import { pt1, qt1 } from "../distributions/t.js";
|
|
17
17
|
import { eigen } from "../linalg/eigen.js";
|
|
18
18
|
import { ginv } from "../linalg/kappa.js";
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
19
|
+
import { rangeExponent } from "../linalg/matrix.js";
|
|
20
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
21
|
+
import { ldexp } from "../internal/summary.js";
|
|
22
|
+
import { checkLmerOptions, lmerInternals, logicalOption, thetaColumnExponents } from "./lmer.js";
|
|
21
23
|
import { varparDerivatives } from "./mixedDerivatives.js";
|
|
24
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
25
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
26
|
+
const LMER_CONTEST_KEYS = ["rhs", "joint", "confint", "level"];
|
|
27
|
+
const LMER_SUMMARY_KEYS = ["ddf"];
|
|
28
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
22
29
|
/** Eigenvalues of the Hessian within this of 0 (or below) are left out of its inverse and warned about */
|
|
23
30
|
const HESSIAN_TOLERANCE = 1e-8;
|
|
24
31
|
/** Eigenvalues of L V L' at most this times the largest are left out of a joint test */
|
|
@@ -67,9 +74,24 @@ export function lmerSatterthwaite(fit) {
|
|
|
67
74
|
* optimum too, to compare with lmerTest's numerical derivatives at the same point.
|
|
68
75
|
*/
|
|
69
76
|
export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
|
|
70
|
-
|
|
77
|
+
// a response whose squares overflow or underflow: the derivatives of the response divided by 2^scale (as lmer fits it)
|
|
78
|
+
let top = 0;
|
|
79
|
+
for (const v of structure.y)
|
|
80
|
+
top = Math.max(top, Math.abs(v));
|
|
81
|
+
const scale = top > 2 ** 500 || top < 2 ** -500 ? Math.floor(Math.log2(top)) : 0;
|
|
82
|
+
const st = scale === 0 ? structure : { ...structure, y: structure.y.map((v) => ldexp(v, -scale)) };
|
|
83
|
+
const d = varparDerivatives(st, theta, reml);
|
|
71
84
|
const m = d.varpar.length;
|
|
72
|
-
|
|
85
|
+
// The Hessian in coordinates of comparable scale, D H D: θ_k times 2^e_k (the columns of Z of its row; see
|
|
86
|
+
// thetaColumnExponents) and σ over a power of 2 near σ̂. Its eigenvalues are cut at the tolerance there, A' = 2 H'⁺
|
|
87
|
+
// and A = D A' D. In (θ, σ) themselves the curvature in σ scales as 1/σ² and that in θ with the columns of Z, so the
|
|
88
|
+
// absolute cut dropped directions by the units alone (response × 1e6: the df of x 7.4e8 for 31, as lmerTest's;
|
|
89
|
+
// issue #10)
|
|
90
|
+
const sigmaHat = d.varpar[m - 1];
|
|
91
|
+
const kSigma = sigmaHat > 0 && Number.isFinite(sigmaHat) ? Math.round(Math.log2(sigmaHat)) : 0;
|
|
92
|
+
const ex = [...thetaColumnExponents(structure).theta.map((v) => -v), kSigma];
|
|
93
|
+
const hScaled = d.hessian.map((row, i) => row.map((v, j) => ldexp(v, ex[i] + ex[j])));
|
|
94
|
+
const e = eigen(hScaled, { symmetric: true });
|
|
73
95
|
const values = e.values;
|
|
74
96
|
const vectors = e.vectors;
|
|
75
97
|
const vcovVarpar = Array.from({ length: m }, () => new Array(m).fill(0));
|
|
@@ -82,16 +104,18 @@ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
|
|
|
82
104
|
vcovVarpar[i][j] += vi * vectors[j][k];
|
|
83
105
|
}
|
|
84
106
|
});
|
|
107
|
+
vcovVarpar.forEach((row, i) => row.forEach((v, j) => (row[j] = ldexp(v, ex[i] + ex[j]))));
|
|
85
108
|
return {
|
|
86
109
|
varpar: d.varpar,
|
|
87
110
|
hessian: d.hessian,
|
|
88
111
|
hessianEigenvalues: values,
|
|
89
112
|
vcovVarpar,
|
|
90
|
-
beta: d.beta.map((b, k) => b + (beta0[k] ?? 0)),
|
|
113
|
+
beta: d.beta.map((b, k) => b + ldexp(beta0[k] ?? 0, -scale)),
|
|
91
114
|
sigma: d.varpar[m - 1],
|
|
92
115
|
vcov: d.vcov,
|
|
93
116
|
jacobian: d.jacobian,
|
|
94
117
|
warnings: hessianWarnings(values),
|
|
118
|
+
scale,
|
|
95
119
|
};
|
|
96
120
|
}
|
|
97
121
|
const quadraticForm = (l, m) => {
|
|
@@ -108,32 +132,40 @@ const quadraticForm = (l, m) => {
|
|
|
108
132
|
};
|
|
109
133
|
const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
|
|
110
134
|
/** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
|
|
111
|
-
export function tTestOf(s,
|
|
112
|
-
if (
|
|
135
|
+
export function tTestOf(s, l0, rhs0, beta = s.beta) {
|
|
136
|
+
if (l0.some(Number.isNaN) || Number.isNaN(rhs0))
|
|
113
137
|
return { estimate: NaN, stdError: NaN, df: NaN, tValue: NaN, pValue: NaN };
|
|
138
|
+
// a contrast of extreme magnitude (1e160, 1e-200) divided by 2^k with its rhs: the test does not depend on it, and
|
|
139
|
+
// l'Vl overflowed or underflowed (#58); the estimate and the standard error are scaled back by 2^k
|
|
140
|
+
const k = rangeExponent(l0);
|
|
141
|
+
const l = k === 0 ? l0 : l0.map((v) => ldexp(v, -k));
|
|
142
|
+
const rhs = ldexp(rhs0, -k);
|
|
143
|
+
// (in the units of the scaled response, the estimate and the standard error scaled back; see LmerSatterthwaite.scale)
|
|
114
144
|
const estimate = dot(l, beta);
|
|
115
145
|
const variance = quadraticForm(l, s.vcov);
|
|
116
146
|
const stdError = Math.sqrt(variance);
|
|
117
147
|
const g = s.jacobian.map((j) => quadraticForm(l, j));
|
|
118
148
|
const df = (2 * variance * variance) / quadraticForm(g, s.vcovVarpar);
|
|
119
|
-
const tValue = (estimate - rhs) / stdError;
|
|
149
|
+
const tValue = (estimate - ldexp(rhs, -s.scale)) / stdError;
|
|
120
150
|
const pValue = 2 * pt1(Math.abs(tValue), df, false, false);
|
|
121
|
-
return { estimate, stdError, df, tValue, pValue };
|
|
151
|
+
return { estimate: ldexp(estimate, s.scale + k), stdError: ldexp(stdError, s.scale + k), df, tValue, pValue };
|
|
122
152
|
}
|
|
123
153
|
function fRowOf(s, f, numDF, denDF) {
|
|
124
154
|
const s2 = s.sigma * s.sigma;
|
|
125
|
-
return { sumSq: f * s2 * numDF, meanSq: f * s2, numDF, denDF, F: f, pValue: pf1(f, numDF, denDF, false, false) };
|
|
155
|
+
return { sumSq: ldexp(f * s2 * numDF, 2 * s.scale), meanSq: ldexp(f * s2, 2 * s.scale), numDF, denDF, F: f, pValue: pf1(f, numDF, denDF, false, false) };
|
|
126
156
|
}
|
|
127
|
-
/** The denominator degrees of freedom of a joint test from those of its rotated contrasts */
|
|
128
|
-
function jointDenDF(nu) {
|
|
157
|
+
/** The denominator degrees of freedom of a joint test from those of its rotated contrasts (exported for the tests) */
|
|
158
|
+
export function jointDenDF(nu) {
|
|
129
159
|
if (nu.length === 1)
|
|
130
160
|
return nu[0];
|
|
131
|
-
|
|
161
|
+
// (equal infinite df are equal: Inf - Inf is NaN, and all Inf gave NaN, an error in lmerTest)
|
|
162
|
+
if (nu.every((v, i) => i === 0 || v === nu[i - 1] || Math.abs(v - nu[i - 1]) < EQUAL_DF_TOLERANCE))
|
|
132
163
|
return nu.reduce((a, b) => a + b, 0) / nu.length;
|
|
133
164
|
if (nu.some((v) => v <= 2))
|
|
134
165
|
return 2;
|
|
135
|
-
// (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive
|
|
136
|
-
|
|
166
|
+
// (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive; the term
|
|
167
|
+
// of an infinite ν is its limit 1, where Inf / Inf was NaN)
|
|
168
|
+
const e = nu.reduce((sum, v) => sum + (v === Infinity ? 1 : v / (v - 2)), 0);
|
|
137
169
|
return (2 * e) / (e - nu.length);
|
|
138
170
|
}
|
|
139
171
|
/**
|
|
@@ -145,13 +177,24 @@ export function lmerFTest(fit, L, rhs, warnings) {
|
|
|
145
177
|
return fTestOf(lmerSatterthwaite(fit), L, rhs, warnings);
|
|
146
178
|
}
|
|
147
179
|
/** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
|
|
148
|
-
export function fTestOf(s,
|
|
149
|
-
const r =
|
|
180
|
+
export function fTestOf(s, L0, rhs, warnings) {
|
|
181
|
+
const r = L0.length;
|
|
150
182
|
if (r === 0)
|
|
151
183
|
return undefined;
|
|
152
|
-
|
|
184
|
+
// L of extreme magnitude and its rhs divided by one power of 2 (the test does not depend on it; the same factor for
|
|
185
|
+
// every row keeps the eigenvectors of L V L', and with them the rotated contrasts and the df). L V L' overflowed or
|
|
186
|
+
// underflowed (#58)
|
|
187
|
+
const k = rangeExponent(L0.flat());
|
|
188
|
+
const L = k === 0 ? L0 : L0.map((row) => row.map((v) => ldexp(v, -k)));
|
|
189
|
+
// (the right-hand side in the units of the scaled response: tTestOf scales its own, the joint test below uses these)
|
|
190
|
+
const given = (rhs ?? new Array(r).fill(0)).map((v) => ldexp(v, -k));
|
|
191
|
+
const right = given.map((v) => ldexp(v, -s.scale));
|
|
153
192
|
if (r === 1) {
|
|
154
|
-
|
|
193
|
+
// A contrast of rank 0 (L V L' = 0, such as a row of zeros) has no hypothesis to test, as for several rows below
|
|
194
|
+
const l = L[0];
|
|
195
|
+
if (!l.some(Number.isNaN) && !(l.reduce((sum, v, j) => sum + v * l.reduce((t, w, k) => t + s.vcov[j][k] * w, 0), 0) > 0))
|
|
196
|
+
return undefined;
|
|
197
|
+
const t = tTestOf(s, l, given[0]);
|
|
155
198
|
return fRowOf(s, t.tValue * t.tValue, 1, t.df);
|
|
156
199
|
}
|
|
157
200
|
if (L.some((row) => row.some(Number.isNaN)) || right.some(Number.isNaN))
|
|
@@ -219,19 +262,21 @@ export function fTestOf(s, L, rhs, warnings) {
|
|
|
219
262
|
* @category Mixed models
|
|
220
263
|
*/
|
|
221
264
|
export function lmerSummary(fit, options) {
|
|
222
|
-
|
|
265
|
+
checkLmerOptions("lmerSummary", options, []);
|
|
266
|
+
checkOptions(options, LMER_SUMMARY_KEYS, "lmerSummary"); // generated: option-keys.mjs
|
|
267
|
+
const ddf = options?.ddf ?? "Satterthwaite";
|
|
223
268
|
if (ddf !== "Satterthwaite" && ddf !== "lme4")
|
|
224
269
|
throw new RangeError(`ddf must be "Satterthwaite" or "lme4", not ${JSON.stringify(ddf)}`);
|
|
225
270
|
const internals = lmerInternals(fit);
|
|
226
271
|
const names = [...internals.structure.xColNames];
|
|
227
272
|
if (ddf === "lme4") {
|
|
228
273
|
const { estimate, stdError, tValue } = fit.coefTable;
|
|
229
|
-
return { ddf, names, estimate: [...estimate], stdError: [...stdError], tValue: [...tValue], messages: [], warnings: [] };
|
|
274
|
+
return reported("lmerSummary", { ddf, names, estimate: [...estimate], stdError: [...stdError], tValue: [...tValue], messages: [], warnings: [] }, fit);
|
|
230
275
|
}
|
|
231
276
|
const s = lmerSatterthwaite(fit);
|
|
232
277
|
const p = names.length;
|
|
233
278
|
const rows = names.map((_, i) => tTestOf(s, Array.from({ length: p }, (_, j) => (j === i ? 1 : 0)), 0));
|
|
234
|
-
return {
|
|
279
|
+
return reported("lmerSummary", {
|
|
235
280
|
ddf,
|
|
236
281
|
names,
|
|
237
282
|
estimate: rows.map((r) => r.estimate),
|
|
@@ -241,9 +286,8 @@ export function lmerSummary(fit, options) {
|
|
|
241
286
|
pValue: rows.map((r) => r.pValue),
|
|
242
287
|
messages: [],
|
|
243
288
|
warnings: [...s.warnings],
|
|
244
|
-
};
|
|
289
|
+
}, fit);
|
|
245
290
|
}
|
|
246
|
-
const CONTEST_KEYS = ["rhs", "joint", "confint", "level"];
|
|
247
291
|
const CONTEST_UNSUPPORTED = ["collect", "checkEstimability", "check_estimability", "ddf"];
|
|
248
292
|
/** The rows of a contrast argument: a vector is one row; each row must have one value per fixed effect */
|
|
249
293
|
function contrastRows(L, p) {
|
|
@@ -255,31 +299,40 @@ function contrastRows(L, p) {
|
|
|
255
299
|
throw new TypeError("L must be an array of numbers or an array of rows");
|
|
256
300
|
if (row.length !== p)
|
|
257
301
|
throw new TypeError(`each contrast must have ${p} values (one per fixed effect), not ${row.length}`);
|
|
302
|
+
// an infinite contrast tests nothing (it gave an empty table silently), nor does a NaN one (lmerTest's row of NA)
|
|
303
|
+
if (!row.every(Number.isFinite))
|
|
304
|
+
throw new RangeError("L must not contain NaN or infinite values");
|
|
258
305
|
}
|
|
259
306
|
return rows;
|
|
260
307
|
}
|
|
261
308
|
export function lmerContest(fit, L, options) {
|
|
262
|
-
|
|
309
|
+
checkLmerOptions("lmerContest", options, CONTEST_UNSUPPORTED);
|
|
310
|
+
checkOptions(options, LMER_CONTEST_KEYS, "lmerContest"); // generated: option-keys.mjs
|
|
311
|
+
options ??= {};
|
|
263
312
|
const joint = logicalOption(options.joint, true);
|
|
264
313
|
const confint = logicalOption(options.confint, true);
|
|
265
314
|
const internals = lmerInternals(fit);
|
|
266
315
|
const p = internals.structure.xColNames.length;
|
|
267
316
|
const rows = contrastRows(L, p);
|
|
268
317
|
const level = options.level ?? 0.95;
|
|
269
|
-
|
|
318
|
+
// 0 and 1 give an interval of width 0 or with infinite ends; lmerTest stops on them ("level > 0 is not TRUE")
|
|
319
|
+
if (typeof level !== "number" || !(level > 0 && level < 1))
|
|
270
320
|
throw new RangeError("level must be a number between 0 and 1");
|
|
271
321
|
const rhsOption = options.rhs ?? 0;
|
|
272
322
|
const rhs = typeof rhsOption === "number" ? new Array(rows.length).fill(rhsOption) : [...rhsOption];
|
|
273
323
|
if (rhs.length !== rows.length || rhs.some((v) => typeof v !== "number")) {
|
|
274
324
|
throw new TypeError(`rhs must be a number or have one value per contrast (${rows.length})`);
|
|
275
325
|
}
|
|
326
|
+
// (lmerTest gives F Inf and p 0 for an infinite rhs, t and p NaN for NaN)
|
|
327
|
+
if (!rhs.every(Number.isFinite))
|
|
328
|
+
throw new RangeError("rhs must not contain NaN or infinite values");
|
|
276
329
|
const warnings = new Warnings();
|
|
277
330
|
const s = lmerSatterthwaite(fit);
|
|
278
331
|
s.warnings.forEach((w) => warnings.add(w));
|
|
279
332
|
if (joint) {
|
|
280
333
|
const row = p === 0 ? undefined : lmerFTest(fit, rows, rhs, warnings);
|
|
281
334
|
const pick = (k) => (row === undefined ? [] : [row[k]]);
|
|
282
|
-
return {
|
|
335
|
+
return reported("lmerContest", {
|
|
283
336
|
joint: true,
|
|
284
337
|
sumSq: pick("sumSq"),
|
|
285
338
|
meanSq: pick("meanSq"),
|
|
@@ -289,7 +342,7 @@ export function lmerContest(fit, L, options) {
|
|
|
289
342
|
pValue: pick("pValue"),
|
|
290
343
|
messages: [],
|
|
291
344
|
warnings: warnings.list,
|
|
292
|
-
};
|
|
345
|
+
}, fit);
|
|
293
346
|
}
|
|
294
347
|
const tests = p === 0 ? [] : rows.map((row, i) => tTestOf(s, row, rhs[i]));
|
|
295
348
|
const out = {
|
|
@@ -307,5 +360,5 @@ export function lmerContest(fit, L, options) {
|
|
|
307
360
|
out.lower = tests.map((t, i) => t.estimate - t.stdError * quantiles[i]);
|
|
308
361
|
out.upper = tests.map((t, i) => t.estimate + t.stdError * quantiles[i]);
|
|
309
362
|
}
|
|
310
|
-
return out;
|
|
363
|
+
return reported("lmerContest", out, fit);
|
|
311
364
|
}
|
package/dist/models/mauchly.d.ts
CHANGED
|
@@ -30,8 +30,13 @@ export interface MauchlyTestResult {
|
|
|
30
30
|
pValue: number;
|
|
31
31
|
/** Name of the test (R's `method`). */
|
|
32
32
|
method: "Mauchly's test of sphericity";
|
|
33
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
34
|
+
warnings: string[];
|
|
33
35
|
}
|
|
34
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* W = det(U) / (trace(U)/p)^p of a p x p matrix U, as det(U / (trace(U)/p)): the scaled matrix has trace p, so
|
|
38
|
+
* neither the determinant nor the power overflows or underflows when W itself is in range
|
|
39
|
+
*/
|
|
35
40
|
export declare function sphericityW(U: DDMatrix): number;
|
|
36
41
|
/**
|
|
37
42
|
* The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the
|
package/dist/models/mauchly.js
CHANGED
|
@@ -8,22 +8,26 @@
|
|
|
8
8
|
// (src/models/ddMatrix.ts).
|
|
9
9
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
10
10
|
import { levelText } from "../internal/levels.js";
|
|
11
|
+
import { scaleToUnit } from "../internal/summary.js";
|
|
11
12
|
import { qr } from "../linalg/qr.js";
|
|
12
13
|
import { ddAdd, ddDiv, ddDivNum, ddMul, ddSub } from "../special/dd.js";
|
|
13
14
|
import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
|
|
14
15
|
import { ddDet, ddTrace } from "./ddMatrix.js";
|
|
15
16
|
import { compareCodePoints } from "./modelFrame.js";
|
|
16
17
|
import { modelMatrix } from "./modelMatrix.js";
|
|
18
|
+
import { unreported } from "../internal/warnings.js";
|
|
19
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
20
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
21
|
+
const MAUCHLY_TEST_KEYS = ["group", "idata", "M", "X"];
|
|
17
22
|
const upperChisq = (q, df) => pgamma1(q, df / 2, 2, false, false);
|
|
18
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* W = det(U) / (trace(U)/p)^p of a p x p matrix U, as det(U / (trace(U)/p)): the scaled matrix has trace p, so
|
|
25
|
+
* neither the determinant nor the power overflows or underflows when W itself is in range
|
|
26
|
+
*/
|
|
19
27
|
export function sphericityW(U) {
|
|
20
28
|
const p = U.length;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
for (let i = 0; i < p; i++)
|
|
24
|
-
pow = ddMul(pow, m);
|
|
25
|
-
m = ddDiv(ddDet(U), pow);
|
|
26
|
-
return m[0];
|
|
29
|
+
const m = ddDivNum(ddTrace(U), p);
|
|
30
|
+
return ddDet(U.map((r) => r.map((v) => ddDiv(v, m))))[0];
|
|
27
31
|
}
|
|
28
32
|
/**
|
|
29
33
|
* The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the
|
|
@@ -82,15 +86,23 @@ export function contrastCrossprod(S, mcols, xcols) {
|
|
|
82
86
|
* @category Linear models and ANOVA
|
|
83
87
|
*/
|
|
84
88
|
export function mauchlyTest(y, options = {}) {
|
|
85
|
-
|
|
86
|
-
const
|
|
87
|
-
const k =
|
|
88
|
-
if (k === 0 ||
|
|
89
|
+
checkOptions(options, MAUCHLY_TEST_KEYS, "mauchlyTest"); // generated: option-keys.mjs
|
|
90
|
+
const all = y.map((r) => Array.from(r));
|
|
91
|
+
const k = all[0]?.length ?? 0;
|
|
92
|
+
if (k === 0 || all.some((r) => r.length !== k))
|
|
89
93
|
throw new TypeError("y must be a matrix with at least one column");
|
|
90
94
|
const group = options.group;
|
|
91
|
-
if (group !== undefined && group.length !==
|
|
95
|
+
if (group !== undefined && group.length !== all.length)
|
|
92
96
|
throw new RangeError("'group' must have one label per row of y");
|
|
93
|
-
|
|
97
|
+
// as for lm(y ~ group): rows with a missing value (NaN or null) in y or a missing group are dropped
|
|
98
|
+
const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
|
|
99
|
+
const keep = all.map((r, i) => !r.some(isMissing) && (group === undefined || !isMissing(group[i])));
|
|
100
|
+
if (all.some((r, i) => keep[i] && r.some((v) => !Number.isFinite(v))))
|
|
101
|
+
throw new RangeError("y must not contain infinite values");
|
|
102
|
+
// scaled by a power of 2 (exact) so that the cross-products stay in range; W does not depend on the units
|
|
103
|
+
const rows = scaleToUnit(all.filter((_, i) => keep[i])).groups;
|
|
104
|
+
const nsub = rows.length;
|
|
105
|
+
const labels = group?.filter((_, i) => keep[i]).map(levelText) ?? rows.map(() => "");
|
|
94
106
|
const levels = [...new Set(labels)].sort(compareCodePoints);
|
|
95
107
|
// residuals from the group means (double-double), and their cross-products
|
|
96
108
|
const res = rows.map((r) => r.map(() => [0, 0]));
|
|
@@ -106,6 +118,8 @@ export function mauchlyTest(y, options = {}) {
|
|
|
106
118
|
}
|
|
107
119
|
}
|
|
108
120
|
const n = nsub - levels.length;
|
|
121
|
+
if (n <= 0)
|
|
122
|
+
throw new RangeError(`no residual degrees of freedom: ${nsub} complete row(s) for ${levels.length} group(s)`);
|
|
109
123
|
const S = Array.from({ length: k }, (_, a) => Array.from({ length: k }, (_, b) => {
|
|
110
124
|
let s = [0, 0];
|
|
111
125
|
for (const r of res)
|
|
@@ -114,7 +128,7 @@ export function mauchlyTest(y, options = {}) {
|
|
|
114
128
|
}));
|
|
115
129
|
const idata = options.idata ?? { index: Array.from({ length: k }, (_, i) => i + 1) };
|
|
116
130
|
const design = (f) => {
|
|
117
|
-
const m = modelMatrix(f, idata);
|
|
131
|
+
const m = unreported(() => modelMatrix(f, idata));
|
|
118
132
|
if (m.x.length !== k)
|
|
119
133
|
throw new RangeError("idata must have one row per column of y");
|
|
120
134
|
return columnsOf(m.x, m.colNames.length);
|
|
@@ -123,6 +137,18 @@ export function mauchlyTest(y, options = {}) {
|
|
|
123
137
|
const xcols = design(options.X ?? "~0");
|
|
124
138
|
const U = contrastCrossprod(S, mcols, xcols);
|
|
125
139
|
const pp = U.length;
|
|
140
|
+
// X spanning M leaves nothing to test (W was 1 and the p-value NaN; R stops with "'a' is 0-diml")
|
|
141
|
+
if (pp === 0)
|
|
142
|
+
throw new RangeError("X spans M: the test has no dimensions");
|
|
143
|
+
// one dimension is spherical whatever the data: W is 1 and the chi-squared df pp (pp + 1) / 2 - 1 is 0, so there is
|
|
144
|
+
// nothing to test (R returns W 1 and p 1, #342)
|
|
145
|
+
if (pp === 1)
|
|
146
|
+
throw new RangeError("one tested dimension: sphericity holds trivially and the test has no degrees of freedom");
|
|
147
|
+
// with fewer residual degrees of freedom than dimensions the covariance is singular whatever the data, and the test
|
|
148
|
+
// is not defined (W was rounding noise, even negative, and p NaN or 1, as R's); n >= pp also keeps the correction's
|
|
149
|
+
// rho positive
|
|
150
|
+
if (n < pp)
|
|
151
|
+
throw new RangeError(`too few residual degrees of freedom for the test: ${n} for ${pp} dimension(s)`);
|
|
126
152
|
const W = sphericityW(U);
|
|
127
|
-
return { statistic: W, statisticName: "W", pValue: mauchlyPValue(W, pp, n, k), method: "Mauchly's test of sphericity" };
|
|
153
|
+
return { statistic: W, statisticName: "W", pValue: mauchlyPValue(W, pp, n, k), method: "Mauchly's test of sphericity", warnings: [] };
|
|
128
154
|
}
|
|
@@ -228,6 +228,12 @@ export function mixedModelStructure(formula, data, options = {}) {
|
|
|
228
228
|
"the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable");
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
+
// a column of a random-effects term not finite (#298: an infinite x in (x | g) reached the factorisation; R stops
|
|
232
|
+
// with "objective in x0 returns NA")
|
|
233
|
+
for (const t of terms) {
|
|
234
|
+
if (t.matrix.some((row) => row.some((v) => !Number.isFinite(v))))
|
|
235
|
+
throw new RangeError(`NA/NaN/Inf in the random-effects term (${t.label})`);
|
|
236
|
+
}
|
|
231
237
|
// Z (level-major within each term), and Λ_θ, θ and its bounds
|
|
232
238
|
const z = [];
|
|
233
239
|
const zColLevels = [];
|
|
@@ -45,8 +45,12 @@ function convert(name, col, levels) {
|
|
|
45
45
|
const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : levelText(x);
|
|
46
46
|
const labels = vals.map(str);
|
|
47
47
|
let lev;
|
|
48
|
-
if (levels !== undefined)
|
|
48
|
+
if (levels !== undefined) {
|
|
49
49
|
lev = Array.from(levels, String);
|
|
50
|
+
const dup = lev.findIndex((l, i) => lev.indexOf(l) !== i);
|
|
51
|
+
if (dup >= 0)
|
|
52
|
+
throw new RangeError(`factor level [${dup + 1}] is duplicated`);
|
|
53
|
+
}
|
|
50
54
|
else if (kind === "boolean")
|
|
51
55
|
lev = ["FALSE", "TRUE"];
|
|
52
56
|
else
|
|
@@ -89,7 +93,7 @@ export function modelFrame(data, names, options = {}) {
|
|
|
89
93
|
const cols = names.map((v) => {
|
|
90
94
|
const c = Object.prototype.hasOwnProperty.call(data, v) ? data[v] : undefined;
|
|
91
95
|
if (c === undefined)
|
|
92
|
-
throw new
|
|
96
|
+
throw new RangeError(`object '${v}' not found`);
|
|
93
97
|
if (!Array.isArray(c) && !(c instanceof Float64Array))
|
|
94
98
|
throw new TypeError(`column '${v}' must be an array`);
|
|
95
99
|
return c;
|
|
@@ -98,7 +102,7 @@ export function modelFrame(data, names, options = {}) {
|
|
|
98
102
|
if (typeof options.weights === "string") {
|
|
99
103
|
const c = Object.prototype.hasOwnProperty.call(data, options.weights) ? data[options.weights] : undefined;
|
|
100
104
|
if (c === undefined)
|
|
101
|
-
throw new
|
|
105
|
+
throw new RangeError(`object '${options.weights}' not found`);
|
|
102
106
|
w = c;
|
|
103
107
|
}
|
|
104
108
|
else if (options.weights !== undefined)
|
|
@@ -110,7 +114,9 @@ export function modelFrame(data, names, options = {}) {
|
|
|
110
114
|
});
|
|
111
115
|
if (w !== undefined && w.length !== n)
|
|
112
116
|
throw new RangeError("variable lengths differ (found for '(weights)')");
|
|
113
|
-
|
|
117
|
+
// own properties only: a column named toString has no given levels unless they are given
|
|
118
|
+
const { levels } = options;
|
|
119
|
+
const conv = names.map((v, i) => convert(v, cols[i], levels !== undefined && Object.hasOwn(levels, v) ? levels[v] : undefined));
|
|
114
120
|
let weights;
|
|
115
121
|
if (w !== undefined) {
|
|
116
122
|
weights = Array.from(w, (x) => {
|
|
@@ -89,6 +89,8 @@ export interface DesignOptions extends Omit<ModelMatrixOptions, "contrasts"> {
|
|
|
89
89
|
* of the formula without the Error() term)
|
|
90
90
|
*/
|
|
91
91
|
contrastVariables?: readonly string[];
|
|
92
|
+
/** Accept a response of any type, without `y` unless it is numeric (modelMatrix, as R's model.matrix) */
|
|
93
|
+
anyResponse?: boolean;
|
|
92
94
|
}
|
|
93
95
|
/**
|
|
94
96
|
* The model matrix of a parsed formula on the data.
|
|
@@ -103,7 +105,7 @@ export declare function design(parsed: ParsedFormula, data: DataFrame, options?:
|
|
|
103
105
|
* Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
|
|
104
106
|
* Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
|
|
105
107
|
* are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
|
|
106
|
-
* and TRUE; numbers are numeric.
|
|
108
|
+
* and TRUE; numbers are numeric. The response may be of any type: it only drops its rows with a missing value.
|
|
107
109
|
*
|
|
108
110
|
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
109
111
|
* @param data The data frame: an object of columns.
|
|
@@ -7,19 +7,44 @@
|
|
|
7
7
|
// indicators.
|
|
8
8
|
import { parseFormula, termsOf } from "./formula.js";
|
|
9
9
|
import { modelFrame } from "./modelFrame.js";
|
|
10
|
-
import {
|
|
10
|
+
import { reported } from "../internal/warnings.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const MODEL_MATRIX_KEYS = ["contrasts", "levels"];
|
|
11
14
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* the
|
|
15
|
+
* The orthonormal polynomials of degrees 1..k-1 in the centred scores, as columns (one row per level): P_0 = 1/sqrt(k)
|
|
16
|
+
* and P_d from x P_(d-1) orthogonalised twice against every earlier P (the Stieltjes three-term recurrence spans the
|
|
17
|
+
* same space; the full re-orthogonalisation keeps its rounding from accumulating), normalised. The coefficient of the
|
|
18
|
+
* highest power stays positive (x P_(d-1) has P_(d-1)'s positive leading coefficient), as for the QR.
|
|
15
19
|
*/
|
|
16
|
-
function
|
|
20
|
+
function polyRecurrence(k) {
|
|
17
21
|
const mean = (k + 1) / 2;
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
const x = Array.from({ length: k }, (_, i) => i + 1 - mean);
|
|
23
|
+
const cols = [new Array(k).fill(1 / Math.sqrt(k))];
|
|
24
|
+
const dot = (a, b) => a.reduce((s, ai, i) => s + ai * b[i], 0);
|
|
25
|
+
for (let d = 1; d < k; d++) {
|
|
26
|
+
const v = cols[d - 1].map((c, i) => c * x[i]);
|
|
27
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
28
|
+
for (const q of cols) {
|
|
29
|
+
const c = dot(q, v);
|
|
30
|
+
for (let i = 0; i < k; i++)
|
|
31
|
+
v[i] -= c * q[i];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const norm = Math.sqrt(dot(v, v));
|
|
35
|
+
cols.push(v.map((vi) => vi / norm));
|
|
36
|
+
}
|
|
37
|
+
return x.map((_, i) => cols.slice(1).map((c) => c[i]));
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* contr.poly for k levels (scores 1..k): the orthonormal polynomials of degrees 1..k-1 in the scores, each signed so
|
|
41
|
+
* that its coefficient of the highest power is positive. R takes Q of the QR of the powers 0..k-1 of the centred
|
|
42
|
+
* scores, which is ill-conditioned in doubles (elements off by 3e-13 at 14 levels, 1e-10 at 20, and from 23 levels
|
|
43
|
+
* the high-degree columns are other vectors altogether); this uses {@link polyRecurrence} for every k, within 1e-15
|
|
44
|
+
* of the exact values (issue #351).
|
|
45
|
+
*/
|
|
46
|
+
function polyContrasts(k) {
|
|
47
|
+
return polyRecurrence(k);
|
|
23
48
|
}
|
|
24
49
|
/** A contrast matrix (one row per level) and its column names */
|
|
25
50
|
export function contrastMatrix(levels, contrast) {
|
|
@@ -133,7 +158,9 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
133
158
|
const name = terms.variables[v];
|
|
134
159
|
if (fv.kind === "numeric")
|
|
135
160
|
return [{ name, values: fv.values }];
|
|
136
|
-
|
|
161
|
+
// own properties only: a factor named toString has the default contrast unless one is given
|
|
162
|
+
const given = options.contrasts !== undefined && Object.hasOwn(options.contrasts, name) ? options.contrasts[name] : undefined;
|
|
163
|
+
const contrast = code === 2 ? "indicators" : (options.allContrasts ?? given ?? "contr.treatment");
|
|
137
164
|
const { m, names } = contrastMatrix(fv.levels, contrast);
|
|
138
165
|
return names.map((cn, j) => ({ name: name + cn, values: fv.codes.map((c) => m[c][j]) }));
|
|
139
166
|
};
|
|
@@ -162,9 +189,10 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
162
189
|
const out = { terms, frame, x, colNames, assign, warnings };
|
|
163
190
|
if (terms.response >= 0) {
|
|
164
191
|
const r = vars[terms.response];
|
|
165
|
-
if (r.kind
|
|
192
|
+
if (r.kind === "numeric")
|
|
193
|
+
out.y = r.values;
|
|
194
|
+
else if (options.anyResponse !== true)
|
|
166
195
|
throw new TypeError("the response must be numeric");
|
|
167
|
-
out.y = r.values;
|
|
168
196
|
}
|
|
169
197
|
return out;
|
|
170
198
|
}
|
|
@@ -175,7 +203,7 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
175
203
|
* Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the formula are dropped first.
|
|
176
204
|
* Strings are factors of the values in the rows kept (sorted by code point), unless `levels` gives the levels, which
|
|
177
205
|
* are then all kept even without a row (their columns are 0); booleans are factors with always the two levels FALSE
|
|
178
|
-
* and TRUE; numbers are numeric.
|
|
206
|
+
* and TRUE; numbers are numeric. The response may be of any type: it only drops its rows with a missing value.
|
|
179
207
|
*
|
|
180
208
|
* @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
|
|
181
209
|
* @param data The data frame: an object of columns.
|
|
@@ -190,8 +218,10 @@ export function design(parsed, data, options = {}, rhs = parsed.rhs) {
|
|
|
190
218
|
* @category Linear models and ANOVA
|
|
191
219
|
*/
|
|
192
220
|
export function modelMatrix(formula, data, options = {}) {
|
|
193
|
-
|
|
194
|
-
|
|
221
|
+
checkOptions(options, MODEL_MATRIX_KEYS, "modelMatrix"); // generated: option-keys.mjs
|
|
222
|
+
// the response only drops the rows where it is missing: any type, as R's model.matrix (#453)
|
|
223
|
+
const d = design(parseFormula(formula), data, { ...options, anyResponse: true });
|
|
224
|
+
return reported("modelMatrix", {
|
|
195
225
|
colNames: d.colNames,
|
|
196
226
|
assign: d.assign,
|
|
197
227
|
x: d.x,
|
|
@@ -203,5 +233,5 @@ export function modelMatrix(formula, data, options = {}) {
|
|
|
203
233
|
// R's factors attribute is empty for a model without terms
|
|
204
234
|
factors: d.terms.terms.length > 0 ? d.terms.factors : [],
|
|
205
235
|
warnings: d.warnings,
|
|
206
|
-
};
|
|
236
|
+
});
|
|
207
237
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A table with the columns of the returned one, its sums of squares in the units of the fit */
|
|
2
|
+
export interface ScaledTable {
|
|
3
|
+
colNames: string[];
|
|
4
|
+
rowNames: string[];
|
|
5
|
+
table: number[][];
|
|
6
|
+
}
|
|
7
|
+
/** The scaled table of anova(), aovSummary() and aovEz() results; the scaled strata of aov() with Error() and its summary */
|
|
8
|
+
export declare const scaledTables: WeakMap<object, ScaledTable[] | ScaledTable>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Tables of sums of squares in the units of the response as fitted (divided by 2^k, so that 2^2k scales the tables
|
|
2
|
+
// that the functions return), kept by result object for the effect sizes: those are ratios of sums of squares, which
|
|
3
|
+
// the returned tables can no longer give where their sums of squares overflow (data around 1e154). Written for
|
|
4
|
+
// rStats.js.
|
|
5
|
+
/** The scaled table of anova(), aovSummary() and aovEz() results; the scaled strata of aov() with Error() and its summary */
|
|
6
|
+
export const scaledTables = new WeakMap();
|
|
@@ -26,8 +26,17 @@ export interface SurvdiffResult {
|
|
|
26
26
|
var: number[][];
|
|
27
27
|
/** Chi-squared statistic */
|
|
28
28
|
chisq: number;
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Degrees of freedom: (number of groups with a positive expected count) - 1, or the rank of the variance matrix of
|
|
31
|
+
* those groups (all but the first) when it is singular
|
|
32
|
+
*/
|
|
33
|
+
df: number;
|
|
34
|
+
/** Upper chi-squared tail on `df` degrees of freedom (NaN for df = 0: the data carry no information on the groups) */
|
|
30
35
|
pvalue: number;
|
|
36
|
+
/** Alias of `pvalue`: the same value. */
|
|
37
|
+
pValue: number;
|
|
38
|
+
/** R's warnings, each once, in R's order (an empty array when there are none). */
|
|
39
|
+
warnings: string[];
|
|
31
40
|
}
|
|
32
41
|
/**
|
|
33
42
|
* Confidence interval type of {@link survfit}.
|
|
@@ -68,6 +77,8 @@ export interface SurvfitResult {
|
|
|
68
77
|
surv: number[];
|
|
69
78
|
/** Standard error of S(t) (S times the standard error of log S) */
|
|
70
79
|
stdErr: number[];
|
|
80
|
+
/** Alias of `stdErr`: the same array. */
|
|
81
|
+
stdError: number[];
|
|
71
82
|
/** Lower limit of the pointwise confidence interval of S(t) */
|
|
72
83
|
lower: number[];
|
|
73
84
|
/** Upper limit of the pointwise confidence interval of S(t) */
|