@numero-uno-jpn/rstats 0.16.0 → 1.0.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 +205 -0
- package/README.ja.md +57 -23
- package/README.md +60 -23
- package/dist/chunks/{chunk-5UQCRBAG.js → chunk-3W5NFFAA.js} +1 -1
- package/dist/chunks/chunk-4F2IALD4.js +3 -0
- package/dist/chunks/{chunk-QNNL7AZ3.js → chunk-4OLDGML4.js} +2 -2
- package/dist/chunks/chunk-63OPBEYO.js +2 -0
- package/dist/chunks/chunk-6XJBCRBV.js +2 -0
- package/dist/chunks/chunk-BQSIBJVX.js +2 -0
- package/dist/chunks/chunk-BWKHYRM6.js +3 -0
- package/dist/chunks/{chunk-W26LRYOJ.js → chunk-CKV4JWW2.js} +1 -1
- package/dist/chunks/chunk-DCAWMF4K.js +2 -0
- package/dist/chunks/chunk-F7YGX7PN.js +2 -0
- package/dist/chunks/chunk-H7I32ZZE.js +2 -0
- package/dist/chunks/chunk-IEOD5GWC.js +3 -0
- package/dist/chunks/chunk-KICBQGFN.js +2 -0
- package/dist/chunks/chunk-LROMWFAK.js +2 -0
- package/dist/chunks/chunk-NSWENS3S.js +2 -0
- package/dist/chunks/chunk-O2SQMGE3.js +2 -0
- package/dist/chunks/chunk-QQX46TCI.js +2 -0
- package/dist/chunks/chunk-QZK3CCBA.js +2 -0
- package/dist/chunks/chunk-UJ66VQIG.js +2 -0
- package/dist/chunks/chunk-UKNDX4BA.js +2 -0
- package/dist/chunks/chunk-WIBKS73G.js +2 -0
- package/dist/chunks/{chunk-URIO5LY5.js → chunk-WQWZ7FND.js} +2 -2
- package/dist/chunks/chunk-WWVMVZUL.js +2 -0
- package/dist/chunks/chunk-YG5S5AVP.js +2 -0
- package/dist/chunks/chunk-YHNMBYSW.js +2 -0
- package/dist/data/grouping.js +6 -2
- package/dist/descriptive/basic.js +20 -0
- package/dist/descriptive/cov.js +11 -0
- package/dist/descriptive/dataFrames.js +13 -5
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +10 -2
- package/dist/descriptive/hist.js +6 -0
- package/dist/descriptive/moments.js +14 -0
- package/dist/descriptive/omega.js +8 -3
- package/dist/descriptive/pivot.d.ts +4 -1
- package/dist/descriptive/pivot.js +27 -13
- package/dist/descriptive/quantile.js +8 -0
- package/dist/descriptive/rank.js +4 -0
- package/dist/descriptive/table.d.ts +20 -1
- package/dist/descriptive/table.js +14 -14
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +8 -0
- package/dist/distributions/beta.js +9 -0
- package/dist/distributions/binomial.js +9 -0
- package/dist/distributions/cauchy.js +9 -0
- package/dist/distributions/chisq.js +9 -0
- package/dist/distributions/exponential.js +9 -0
- package/dist/distributions/f.js +9 -0
- package/dist/distributions/gamma.js +8 -0
- package/dist/distributions/geometric.js +9 -0
- package/dist/distributions/hypergeometric.js +8 -0
- package/dist/distributions/invgamma.js +8 -0
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +9 -0
- package/dist/distributions/logistic.js +9 -0
- package/dist/distributions/lognormal.js +8 -0
- package/dist/distributions/multinomial.js +4 -0
- package/dist/distributions/negbinomial.js +8 -0
- package/dist/distributions/normal.js +8 -0
- package/dist/distributions/pareto.js +8 -0
- package/dist/distributions/poisson.js +9 -0
- package/dist/distributions/signrank.js +9 -0
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +31 -1
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +9 -0
- package/dist/distributions/tukey.js +6 -0
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +8 -0
- package/dist/distributions/wilcox.js +9 -0
- 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 +9 -0
- package/dist/entries/mixed.js +8 -1
- 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 +13 -0
- package/dist/htest/agreement.js +46 -7
- package/dist/htest/ansariTest.d.ts +2 -1
- package/dist/htest/ansariTest.js +43 -12
- package/dist/htest/aov.d.ts +28 -22
- package/dist/htest/aov.js +42 -13
- package/dist/htest/binomTest.js +6 -0
- package/dist/htest/brunnerMunzelTest.js +5 -0
- package/dist/htest/chisqTest.d.ts +3 -1
- package/dist/htest/chisqTest.js +21 -3
- package/dist/htest/cor.d.ts +7 -1
- package/dist/htest/cor.js +40 -7
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/effectSize.d.ts +3 -0
- package/dist/htest/effectSize.js +28 -8
- package/dist/htest/fisherTest.d.ts +2 -1
- package/dist/htest/fisherTest.js +52 -6
- package/dist/htest/ksTest.d.ts +4 -0
- package/dist/htest/ksTest.js +13 -4
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +9 -3
- package/dist/htest/mantelhaenTest.js +7 -0
- package/dist/htest/mcnemarTest.js +8 -0
- package/dist/htest/multipleComparisons.d.ts +16 -25
- package/dist/htest/multipleComparisons.js +26 -43
- package/dist/htest/normalityTests.js +10 -4
- package/dist/htest/onewayTest.js +10 -0
- package/dist/htest/pAdjust.js +4 -0
- package/dist/htest/pairwise.d.ts +2 -0
- package/dist/htest/pairwise.js +29 -6
- package/dist/htest/poissonTest.js +6 -0
- package/dist/htest/polycor.js +20 -10
- package/dist/htest/power.d.ts +4 -0
- package/dist/htest/power.js +16 -2
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +23 -2
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +38 -15
- package/dist/htest/rankTests.js +7 -1
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +9 -0
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +21 -1
- package/dist/htest/trendTests.js +13 -18
- package/dist/htest/types.d.ts +2 -0
- package/dist/htest/varTest.js +7 -0
- package/dist/htest/wilcoxTest.js +51 -9
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.js +7 -0
- package/dist/linalg/chol.js +6 -0
- package/dist/linalg/eigen.js +4 -0
- package/dist/linalg/expm.js +4 -0
- package/dist/linalg/kappa.js +6 -0
- package/dist/linalg/lu.js +5 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +14 -13
- package/dist/linalg/qr.js +14 -0
- package/dist/linalg/solve.js +9 -0
- package/dist/linalg/svd.js +6 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +5 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +50 -7
- package/dist/models/aovEz.js +16 -11
- package/dist/models/aovStrata.js +15 -4
- package/dist/models/carAnova.js +11 -17
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +21 -6
- package/dist/models/formula.d.ts +5 -2
- package/dist/models/formula.js +31 -8
- package/dist/models/glm.d.ts +22 -2
- package/dist/models/glm.js +32 -22
- package/dist/models/glmAnova.js +8 -3
- package/dist/models/glmConfint.js +6 -2
- package/dist/models/glmFamily.d.ts +1 -6
- package/dist/models/glmFamily.js +3 -22
- package/dist/models/glmer.d.ts +255 -0
- package/dist/models/glmer.js +635 -0
- package/dist/models/glmerAnova.d.ts +81 -0
- package/dist/models/glmerAnova.js +139 -0
- package/dist/models/glmerDeviance.d.ts +98 -0
- package/dist/models/glmerDeviance.js +576 -0
- package/dist/models/glmerFamily.d.ts +57 -0
- package/dist/models/glmerFamily.js +236 -0
- package/dist/models/glmerGradient.d.ts +46 -0
- package/dist/models/glmerGradient.js +301 -0
- package/dist/models/glmerStructure.d.ts +45 -0
- package/dist/models/glmerStructure.js +168 -0
- package/dist/models/glmerSummary.d.ts +102 -0
- package/dist/models/glmerSummary.js +94 -0
- package/dist/models/lm.js +13 -3
- package/dist/models/lmer.d.ts +27 -6
- package/dist/models/lmer.js +75 -321
- package/dist/models/lmerAnova.d.ts +52 -3
- package/dist/models/lmerAnova.js +101 -45
- package/dist/models/lmerTest.d.ts +12 -5
- package/dist/models/lmerTest.js +39 -18
- package/dist/models/mauchly.d.ts +2 -0
- package/dist/models/mauchly.js +7 -2
- package/dist/models/mixedDeviance.d.ts +28 -2
- package/dist/models/mixedDeviance.js +84 -56
- package/dist/models/mixedMinimiser.d.ts +83 -0
- package/dist/models/mixedMinimiser.js +438 -0
- package/dist/models/mixedPredict.d.ts +121 -0
- package/dist/models/mixedPredict.js +530 -0
- package/dist/models/mixedStructure.d.ts +62 -3
- package/dist/models/mixedStructure.js +74 -29
- package/dist/models/modelFrame.js +2 -2
- package/dist/models/modelMatrix.d.ts +8 -1
- package/dist/models/modelMatrix.js +56 -39
- package/dist/models/survival.d.ts +6 -0
- package/dist/models/survival.js +9 -2
- package/dist/numerics/deriv.js +8 -0
- package/dist/numerics/integrate.js +8 -0
- package/dist/numerics/interp.d.ts +32 -7
- package/dist/numerics/interp.js +27 -9
- package/dist/numerics/ode.js +4 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/optim.js +17 -2
- package/dist/random/beta.js +5 -0
- package/dist/random/continuous.js +17 -0
- package/dist/random/extra.js +13 -0
- package/dist/random/gamma.js +11 -0
- package/dist/random/poisson.js +5 -0
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.js +6 -0
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.js +7 -0
- package/dist/special/choose.js +7 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +14 -11
- package/llms.txt +15 -4
- package/package.json +19 -10
- package/dist/chunks/chunk-2D2IQWUQ.js +0 -2
- package/dist/chunks/chunk-6CSTWA5E.js +0 -2
- package/dist/chunks/chunk-72Y3HZID.js +0 -2
- package/dist/chunks/chunk-BG2KLEHM.js +0 -2
- package/dist/chunks/chunk-CMEKBNHQ.js +0 -2
- package/dist/chunks/chunk-FLJNSXSW.js +0 -2
- package/dist/chunks/chunk-GM53LWSR.js +0 -2
- package/dist/chunks/chunk-JBCA56ZS.js +0 -3
- package/dist/chunks/chunk-K3RJAD2T.js +0 -2
- package/dist/chunks/chunk-KAZRWIB5.js +0 -2
- package/dist/chunks/chunk-KBVVIMXX.js +0 -3
- package/dist/chunks/chunk-N3SIFCZX.js +0 -2
- package/dist/chunks/chunk-SC6CV4Z3.js +0 -2
- package/dist/chunks/chunk-SYWOBOTR.js +0 -2
- package/dist/chunks/chunk-VTUGG2SV.js +0 -2
- package/dist/chunks/chunk-XHETEYVC.js +0 -2
- package/dist/chunks/chunk-YRZWONZB.js +0 -3
- package/dist/chunks/chunk-ZGABZMWX.js +0 -2
package/dist/models/lmer.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
// Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1c, "The fit and its results") and
|
|
7
7
|
// D. Bates, M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of
|
|
8
8
|
// Statistical Software 67(1). The structure comes from src/models/mixedStructure.ts and the criterion with its
|
|
9
|
-
// analytic gradient from src/models/mixedDeviance.ts.
|
|
9
|
+
// analytic gradient from src/models/mixedDeviance.ts. The minimiser described below is in src/models/mixedMinimiser.ts
|
|
10
|
+
// (shared with glmer).
|
|
10
11
|
//
|
|
11
12
|
// The criterion does not change when a column of a block T_k changes sign (Λ_θ → Λ_θ D with D = diag(±1) per level,
|
|
12
13
|
// matched by u → D u), so the bounds θ_jj ≥ 0 on the diagonal elements only choose one of equivalent parameter
|
|
@@ -53,36 +54,15 @@
|
|
|
53
54
|
// on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
|
|
54
55
|
// from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
|
|
55
56
|
// 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
|
|
56
|
-
import { ldexp
|
|
57
|
+
import { ldexp } from "../internal/summary.js";
|
|
57
58
|
import { qr, qrCoef } from "../linalg/qr.js";
|
|
58
59
|
import { profiledDeviance } from "./mixedDeviance.js";
|
|
59
60
|
import { mixedModelStructure } from "./mixedStructure.js";
|
|
60
|
-
import {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
/** ... and at least this (relative to max(1, max |θ|)), for elements at or near 0 */
|
|
66
|
-
const HESSIAN_STEP_FLOOR = 1e-6;
|
|
67
|
-
/** Eigenvalues of the Hessian below this times the largest are treated as 0 (the Hessian's own accuracy) */
|
|
68
|
-
const EIGENVALUE_TOLERANCE = 1e-6;
|
|
69
|
-
/** Diagonal elements below this (relative to max(1, max |θ|)) at convergence are candidates for the boundary */
|
|
70
|
-
const BOUNDARY_CANDIDATE = 1e-4;
|
|
71
|
-
/** The move along a direction of negative curvature that leaves the boundary (relative to max(1, max |θ|)) */
|
|
72
|
-
const NEGATIVE_CURVATURE_MOVE = 1e-3;
|
|
73
|
-
/** Converged when the Newton step is below this, relative to max(1, max |θ|) ... */
|
|
74
|
-
const STEP_TOLERANCE = 1e-13;
|
|
75
|
-
/** ... or when the steps stop decreasing (rounding level) below this; steps this small are always accepted */
|
|
76
|
-
const STEP_FLOOR = 1e-10;
|
|
77
|
-
/** The gradient on the free elements at convergence must be below this times max(1, |criterion|) */
|
|
78
|
-
const GRADIENT_TOLERANCE = 1e-9;
|
|
79
|
-
const MAX_ITERATIONS = 500;
|
|
80
|
-
/** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
|
|
81
|
-
const HESSIAN_REUSE_RATIO = 0.75;
|
|
82
|
-
/** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
|
|
83
|
-
const RESTART_THRESHOLD = 1e-8;
|
|
84
|
-
/** ... and there are at most this many restarts */
|
|
85
|
-
const MAX_RESTARTS = 50;
|
|
61
|
+
import { LMER_SETTINGS, minimiseWithRestarts } from "./mixedMinimiser.js";
|
|
62
|
+
import { reported } from "../internal/warnings.js";
|
|
63
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
64
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
65
|
+
const LMER_KEYS = ["REML", "contrasts", "levels"];
|
|
86
66
|
/**
|
|
87
67
|
* The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y|: a
|
|
88
68
|
* few times the rounding error of the residuals, so that a response with a large mean and a small spread (around
|
|
@@ -92,122 +72,11 @@ const MAX_RESTARTS = 50;
|
|
|
92
72
|
const EXACT_FIT = 16 * Number.EPSILON;
|
|
93
73
|
const EXACT_FIT_ERROR = "lmer: the response is fitted exactly by the fixed effects (a constant response, for example), so the residual variance is 0";
|
|
94
74
|
const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
|
|
95
|
-
/** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
|
|
96
|
-
function symmetricEigen(a0) {
|
|
97
|
-
// entries of extreme magnitude are scaled by a power of 2 (exact) first and the eigenvalues scaled back: the sums of
|
|
98
|
-
// squares below overflowed for entries around 1e200 (Infinity <= 1e-32 Infinity ended the sweeps at once)
|
|
99
|
-
let mx = 0;
|
|
100
|
-
for (const row of a0)
|
|
101
|
-
for (const v of row)
|
|
102
|
-
mx = Math.max(mx, Math.abs(v));
|
|
103
|
-
const k = mx === 0 || !Number.isFinite(mx) || (mx >= 2 ** -256 && mx <= 2 ** 256) ? 0 : Math.floor(Math.log2(mx));
|
|
104
|
-
if (k !== 0) {
|
|
105
|
-
const r = symmetricEigen(a0.map((row) => row.map((v) => ldexp(v, -k))));
|
|
106
|
-
return { values: r.values.map((v) => ldexp(v, k)), vectors: r.vectors };
|
|
107
|
-
}
|
|
108
|
-
const m = a0.length;
|
|
109
|
-
const a = a0.map((row) => row.slice());
|
|
110
|
-
const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
|
|
111
|
-
for (let sweep = 0; sweep < 100; sweep++) {
|
|
112
|
-
let off = 0;
|
|
113
|
-
let total = 0;
|
|
114
|
-
for (let i = 0; i < m; i++) {
|
|
115
|
-
for (let j = 0; j < m; j++) {
|
|
116
|
-
total += a[i][j] ** 2;
|
|
117
|
-
if (i !== j)
|
|
118
|
-
off += a[i][j] ** 2;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
if (off <= 1e-32 * total)
|
|
122
|
-
break;
|
|
123
|
-
for (let p = 0; p < m - 1; p++) {
|
|
124
|
-
for (let q = p + 1; q < m; q++) {
|
|
125
|
-
const apq = a[p][q];
|
|
126
|
-
if (apq === 0)
|
|
127
|
-
continue;
|
|
128
|
-
const tau = (a[q][q] - a[p][p]) / (2 * apq);
|
|
129
|
-
const t = Math.sign(tau || 1) / (Math.abs(tau) + Math.sqrt(1 + tau * tau));
|
|
130
|
-
const c = 1 / Math.sqrt(1 + t * t);
|
|
131
|
-
const sn = t * c;
|
|
132
|
-
for (let k = 0; k < m; k++) {
|
|
133
|
-
const akp = a[k][p];
|
|
134
|
-
const akq = a[k][q];
|
|
135
|
-
a[k][p] = c * akp - sn * akq;
|
|
136
|
-
a[k][q] = sn * akp + c * akq;
|
|
137
|
-
}
|
|
138
|
-
for (let k = 0; k < m; k++) {
|
|
139
|
-
const apk = a[p][k];
|
|
140
|
-
const aqk = a[q][k];
|
|
141
|
-
a[p][k] = c * apk - sn * aqk;
|
|
142
|
-
a[q][k] = sn * apk + c * aqk;
|
|
143
|
-
}
|
|
144
|
-
for (let k = 0; k < m; k++) {
|
|
145
|
-
const vkp = v[k][p];
|
|
146
|
-
const vkq = v[k][q];
|
|
147
|
-
v[k][p] = c * vkp - sn * vkq;
|
|
148
|
-
v[k][q] = sn * vkp + c * vkq;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
|
|
154
|
-
}
|
|
155
|
-
// without overflow of the squares (src/internal/summary.ts)
|
|
156
|
-
const norm = norm2;
|
|
157
|
-
const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
|
|
158
|
-
/**
|
|
159
|
-
* The step p that minimises g'p + p'Hp/2 subject to ‖p‖ ≤ radius (H = V diag(λ) V'), and whether it is the Newton
|
|
160
|
-
* step. Eigenvalues within `zero` of 0 are treated as 0: along their eigenvectors the criterion is flat to the
|
|
161
|
-
* accuracy of the Hessian (as along a set of equivalent minimisers), and the Newton step leaves them out when the
|
|
162
|
-
* gradient's component there is below `gradientZero`.
|
|
163
|
-
*/
|
|
164
|
-
function trustRegionStep(g, eig, radius, zero, gradientZero) {
|
|
165
|
-
const m = g.length;
|
|
166
|
-
const { values, vectors } = eig;
|
|
167
|
-
const gt = vectors.map((v) => dot(v, g));
|
|
168
|
-
const combine = (coef) => {
|
|
169
|
-
const p = new Array(m).fill(0);
|
|
170
|
-
coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
|
|
171
|
-
return p;
|
|
172
|
-
};
|
|
173
|
-
const minValue = minOf(values);
|
|
174
|
-
// the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
|
|
175
|
-
// directions, and the step is inside the region
|
|
176
|
-
if (minValue > -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
|
|
177
|
-
const p = combine(values.map((l, k) => (l > zero ? -gt[k] / l : 0)));
|
|
178
|
-
if (norm(p) <= radius)
|
|
179
|
-
return { step: p, newton: true };
|
|
180
|
-
}
|
|
181
|
-
// on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
|
|
182
|
-
const lowest = Math.max(0, -minValue);
|
|
183
|
-
const lengthAt = (mu) => norm2(values.map((l, k) => gt[k] / (l + mu)));
|
|
184
|
-
const tiny = Math.max(zero, 1e-12 * Math.max(maxOf(values.map(Math.abs)), 1));
|
|
185
|
-
if (lengthAt(lowest + tiny) >= radius) {
|
|
186
|
-
let lo = lowest + tiny;
|
|
187
|
-
let hi = lowest + norm(g) / radius + maxOf(values.map(Math.abs)) + tiny;
|
|
188
|
-
for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
|
|
189
|
-
const mid = (lo + hi) / 2;
|
|
190
|
-
if (lengthAt(mid) > radius)
|
|
191
|
-
lo = mid;
|
|
192
|
-
else
|
|
193
|
-
hi = mid;
|
|
194
|
-
}
|
|
195
|
-
return { step: combine(values.map((l, k) => -gt[k] / (l + hi))), newton: false };
|
|
196
|
-
}
|
|
197
|
-
// the "hard case": the gradient has (almost) no component along the eigenvectors of the lowest eigenvalue; the
|
|
198
|
-
// step at μ = −λ_min is completed to the boundary along such an eigenvector
|
|
199
|
-
const low = values.map((l) => l + lowest <= tiny);
|
|
200
|
-
const p = combine(values.map((l, k) => (low[k] ? 0 : -gt[k] / (l + lowest))));
|
|
201
|
-
const k0 = values.indexOf(minValue);
|
|
202
|
-
const rest = Math.sqrt(Math.max(0, radius * radius - dot(p, p)));
|
|
203
|
-
const direction = -Math.sign(gt[k0]) || 1;
|
|
204
|
-
return { step: p.map((pi, i) => pi + direction * rest * vectors[k0][i]), newton: false };
|
|
205
|
-
}
|
|
206
75
|
/**
|
|
207
76
|
* The columns of the blocks T_k as lists of θ indices, the diagonal element first: changing the sign of a column
|
|
208
77
|
* leaves the criterion unchanged (Λ_θ → Λ_θ D with D = diag(±1) per level, matched by u → D u)
|
|
209
78
|
*/
|
|
210
|
-
function columnsOfTheta(s) {
|
|
79
|
+
export function columnsOfTheta(s) {
|
|
211
80
|
const out = [];
|
|
212
81
|
for (const t of s.terms) {
|
|
213
82
|
const nc = t.columns.length;
|
|
@@ -226,151 +95,16 @@ const sparseCriterion = (s, theta, reml) => {
|
|
|
226
95
|
const r = profiledDeviance(s, theta, reml, { gradient: true });
|
|
227
96
|
return { f: r.deviance, g: r.gradient };
|
|
228
97
|
};
|
|
229
|
-
/**
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
/** Diagonal elements held at exactly 0 */
|
|
239
|
-
const fixed = new Set();
|
|
240
|
-
/** Diagonal elements released from 0 (not set to 0 again: their minimiser is near 0 but not at it) */
|
|
241
|
-
const released = new Set();
|
|
242
|
-
const scaleOf = () => Math.max(1, ...theta.map(Math.abs));
|
|
243
|
-
const gradientTolerance = () => GRADIENT_TOLERANCE * Math.max(1, Math.abs(f));
|
|
244
|
-
let radius = INITIAL_RADIUS * scaleOf();
|
|
245
|
-
let previousNewton = Infinity;
|
|
246
|
-
/** The Hessian of the last iteration, when it may be used again (see iterate) */
|
|
247
|
-
let reusable;
|
|
248
|
-
/** The Hessian on the elements `set`, from central differences of the gradient */
|
|
249
|
-
const hessian = (set) => {
|
|
250
|
-
const floor = HESSIAN_STEP_FLOOR * scaleOf();
|
|
251
|
-
const cols = set.map((j) => {
|
|
252
|
-
const h = Math.max(HESSIAN_STEP * Math.abs(theta[j]), floor);
|
|
253
|
-
const plus = theta.slice();
|
|
254
|
-
plus[j] = theta[j] + h;
|
|
255
|
-
const minus = theta.slice();
|
|
256
|
-
minus[j] = theta[j] - h;
|
|
257
|
-
const gp = evaluate(plus).g;
|
|
258
|
-
const gm = evaluate(minus).g;
|
|
259
|
-
return set.map((i) => (gp[i] - gm[i]) / (2 * h));
|
|
260
|
-
});
|
|
261
|
-
return set.map((_, a) => set.map((_, b) => (cols[a][b] + cols[b][a]) / 2));
|
|
98
|
+
/** The minimisation problem of lmer's criterion over θ (src/models/mixedMinimiser.ts) */
|
|
99
|
+
function lmerProblem(s, reml, criterion) {
|
|
100
|
+
return {
|
|
101
|
+
evaluate: (theta) => criterion(s, theta, reml),
|
|
102
|
+
diagonal: s.lower.map((b) => b === 0),
|
|
103
|
+
columns: columnsOfTheta(s),
|
|
104
|
+
settings: LMER_SETTINGS,
|
|
105
|
+
rejectNonFinite: false,
|
|
106
|
+
failure: OPTIMISATION_FAILED,
|
|
262
107
|
};
|
|
263
|
-
/** One trust-region iteration on the free elements; returns whether it converged */
|
|
264
|
-
const iterate = (free) => {
|
|
265
|
-
const fresh = reusable === undefined || reusable.free.length !== free.length || reusable.free.some((j, a) => j !== free[a]);
|
|
266
|
-
const h = fresh ? hessian(free) : reusable.h;
|
|
267
|
-
reusable = undefined;
|
|
268
|
-
const eig = symmetricEigen(h);
|
|
269
|
-
const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
|
|
270
|
-
const gFree = free.map((j) => g[j]);
|
|
271
|
-
const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
|
|
272
|
-
const trial = theta.slice();
|
|
273
|
-
free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
|
|
274
|
-
const size = maxOf(step.map(Math.abs)) / scaleOf();
|
|
275
|
-
const next = evaluate(trial);
|
|
276
|
-
if (!Number.isFinite(next.f))
|
|
277
|
-
throw new Error(OPTIMISATION_FAILED);
|
|
278
|
-
const predicted = -(dot(gFree, step) + dot(step, h.map((row) => dot(row, step))) / 2);
|
|
279
|
-
// the actual reduction from the values, or, where they are equal to rounding, from the gradients (trapezoid)
|
|
280
|
-
const actual = Math.abs(f - next.f) > 1e-10 * Math.abs(f) ? f - next.f : -(dot(gFree, step) + dot(free.map((j) => next.g[j]), step)) / 2;
|
|
281
|
-
const ratio = predicted > 0 ? actual / predicted : actual >= 0 ? 1 : -1;
|
|
282
|
-
if (ratio > 0.1 || size <= STEP_FLOOR) {
|
|
283
|
-
theta = trial;
|
|
284
|
-
f = next.f;
|
|
285
|
-
g = next.g;
|
|
286
|
-
}
|
|
287
|
-
const length = norm(step);
|
|
288
|
-
if (ratio < 0.25)
|
|
289
|
-
radius = Math.max(length / 4, STEP_TOLERANCE * scaleOf());
|
|
290
|
-
else if (ratio > 0.75 && length >= 0.99 * radius)
|
|
291
|
-
radius *= 2;
|
|
292
|
-
if (!newton) {
|
|
293
|
-
previousNewton = Infinity;
|
|
294
|
-
return false;
|
|
295
|
-
}
|
|
296
|
-
const gradientSmall = free.every((j) => Math.abs(g[j]) <= gradientTolerance());
|
|
297
|
-
// (the steps stopping decreasing is taken as rounding level only with a fresh Hessian)
|
|
298
|
-
const done = gradientSmall && (size <= STEP_TOLERANCE || (fresh && size <= STEP_FLOOR && size >= 0.5 * previousNewton));
|
|
299
|
-
// the Hessian is kept for the next iteration after a Newton step that was accepted, predicted well and at most
|
|
300
|
-
// half the previous one (the model is still good; convergence stays fast)
|
|
301
|
-
if (ratio > HESSIAN_REUSE_RATIO && ratio < 1 / HESSIAN_REUSE_RATIO && size < 0.5 * previousNewton)
|
|
302
|
-
reusable = { free, h };
|
|
303
|
-
previousNewton = size;
|
|
304
|
-
return done;
|
|
305
|
-
};
|
|
306
|
-
/**
|
|
307
|
-
* At a converged point with elements held at 0: a direction of negative curvature of the elements held there
|
|
308
|
-
* whose derivative vanishes, together with the free ones, is a way down (in a block whose leading diagonal element
|
|
309
|
-
* is 0, the criterion depends on it and the element below through their product, so neither alone shows the
|
|
310
|
-
* descent; for a single even element it is its own curvature at 0). If there is one, the elements held at 0 along
|
|
311
|
-
* it are released and θ is moved a little along it; returns whether it did.
|
|
312
|
-
*/
|
|
313
|
-
const leaveAlongNegativeCurvature = () => {
|
|
314
|
-
if (fixed.size === 0)
|
|
315
|
-
return false;
|
|
316
|
-
const set = theta.map((_, j) => j).filter((j) => !held.has(j));
|
|
317
|
-
const eig = symmetricEigen(hessian(set));
|
|
318
|
-
const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
|
|
319
|
-
const k = eig.values.indexOf(minOf(eig.values));
|
|
320
|
-
if (!(eig.values[k] < -zero))
|
|
321
|
-
return false;
|
|
322
|
-
const v = eig.vectors[k];
|
|
323
|
-
const leaving = set.filter((j, a) => fixed.has(j) && Math.abs(v[a]) > 1e-8);
|
|
324
|
-
if (leaving.length === 0)
|
|
325
|
-
return false;
|
|
326
|
-
for (const j of leaving) {
|
|
327
|
-
fixed.delete(j);
|
|
328
|
-
released.add(j);
|
|
329
|
-
}
|
|
330
|
-
const move = NEGATIVE_CURVATURE_MOVE * scaleOf();
|
|
331
|
-
set.forEach((j, a) => (theta[j] = theta[j] + move * v[a]));
|
|
332
|
-
({ f, g } = evaluate(theta));
|
|
333
|
-
return true;
|
|
334
|
-
};
|
|
335
|
-
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
|
336
|
-
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
|
|
337
|
-
if (free.length > 0 && !iterate(free))
|
|
338
|
-
continue;
|
|
339
|
-
// converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
|
|
340
|
-
const toZero = free.filter((j) => diagonal[j] && !released.has(j) && Math.abs(theta[j]) < BOUNDARY_CANDIDATE * scaleOf());
|
|
341
|
-
if (toZero.length > 0) {
|
|
342
|
-
for (const j of toZero) {
|
|
343
|
-
theta[j] = 0;
|
|
344
|
-
fixed.add(j);
|
|
345
|
-
}
|
|
346
|
-
({ f, g } = evaluate(theta));
|
|
347
|
-
previousNewton = Infinity;
|
|
348
|
-
reusable = undefined;
|
|
349
|
-
continue;
|
|
350
|
-
}
|
|
351
|
-
// elements held at 0 with a derivative, or with a direction of negative curvature, are released
|
|
352
|
-
const tolerance = 1e-12 * Math.max(1, Math.abs(f));
|
|
353
|
-
const release = [...fixed].filter((j) => Math.abs(g[j]) > tolerance);
|
|
354
|
-
if (release.length > 0) {
|
|
355
|
-
for (const j of release) {
|
|
356
|
-
fixed.delete(j);
|
|
357
|
-
released.add(j);
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
else if (!leaveAlongNegativeCurvature()) {
|
|
361
|
-
// the minimiser: each column of T_k with a negative diagonal element changes sign (an equivalent θ)
|
|
362
|
-
for (const column of columnsOfTheta(s)) {
|
|
363
|
-
if (theta[column[0]] < 0)
|
|
364
|
-
for (const j of column)
|
|
365
|
-
theta[j] = -theta[j];
|
|
366
|
-
}
|
|
367
|
-
return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
|
|
368
|
-
}
|
|
369
|
-
radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
|
|
370
|
-
previousNewton = Infinity;
|
|
371
|
-
reusable = undefined;
|
|
372
|
-
}
|
|
373
|
-
throw new Error(OPTIMISATION_FAILED);
|
|
374
108
|
}
|
|
375
109
|
/**
|
|
376
110
|
* The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
|
|
@@ -428,41 +162,23 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
428
162
|
const nc = t.columns.length;
|
|
429
163
|
return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
|
|
430
164
|
});
|
|
431
|
-
|
|
432
|
-
for (let round = 0; round < MAX_RESTARTS; round++) {
|
|
433
|
-
let candidate;
|
|
434
|
-
for (const block of blocks) {
|
|
435
|
-
if (block.every((j) => best.theta[j] === 0))
|
|
436
|
-
continue;
|
|
437
|
-
const removed = localMinimum(s, reml, criterion, best.theta, new Set(block));
|
|
438
|
-
if (candidate === undefined || removed.f < candidate.f)
|
|
439
|
-
candidate = removed;
|
|
440
|
-
}
|
|
441
|
-
if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
|
|
442
|
-
return best.theta;
|
|
443
|
-
best = localMinimum(s, reml, criterion, candidate.theta);
|
|
444
|
-
}
|
|
445
|
-
throw new Error(OPTIMISATION_FAILED);
|
|
165
|
+
return minimiseWithRestarts(lmerProblem(s, reml, criterion), s.theta, blocks).theta;
|
|
446
166
|
}
|
|
447
167
|
/**
|
|
448
|
-
* The option
|
|
449
|
-
* `options` must be an object when given (not null, not an array)
|
|
450
|
-
* of R that are not supported (the first gives an Error
|
|
451
|
-
*
|
|
168
|
+
* The first option check of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section
|
|
169
|
+
* 3): `options` must be an object when given (not null, not an array), and none of its own keys, in order, among those
|
|
170
|
+
* of R that are not supported (the first gives an Error naming it). A key whose value is `undefined` counts as given.
|
|
171
|
+
* The unknown keys are checked after it (a RangeError of checkOptions, generated by scripts/option-keys.mjs, which
|
|
172
|
+
* keeps a first statement calling this function before its checks).
|
|
452
173
|
*/
|
|
453
|
-
export function
|
|
174
|
+
export function checkLmerOptions(fn, options, unsupported) {
|
|
454
175
|
if (options === undefined)
|
|
455
|
-
return
|
|
176
|
+
return;
|
|
456
177
|
if (typeof options !== "object" || options === null || Array.isArray(options))
|
|
457
178
|
throw new TypeError("options must be an object");
|
|
458
|
-
const
|
|
459
|
-
const notSupported = keys.find((k) => unsupported.includes(k));
|
|
179
|
+
const notSupported = Object.keys(options).find((k) => unsupported.includes(k));
|
|
460
180
|
if (notSupported !== undefined)
|
|
461
181
|
throw new Error(`${fn}: argument '${notSupported}' is not supported`);
|
|
462
|
-
const unknown = keys.filter((k) => !accepted.includes(k));
|
|
463
|
-
if (unknown.length > 0)
|
|
464
|
-
throw new TypeError(`unused argument${unknown.length === 1 ? "" : "s"} (${unknown.join(", ")})`);
|
|
465
|
-
return options;
|
|
466
182
|
}
|
|
467
183
|
/**
|
|
468
184
|
* A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
|
|
@@ -479,7 +195,6 @@ export function logicalOption(value, defaultValue) {
|
|
|
479
195
|
throw new TypeError("argument is of length zero");
|
|
480
196
|
throw new TypeError("argument is not interpretable as logical");
|
|
481
197
|
}
|
|
482
|
-
const LMER_KEYS = ["REML", "contrasts", "levels"];
|
|
483
198
|
const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action", "control", "start", "verbose", "devFunOnly"];
|
|
484
199
|
/**
|
|
485
200
|
* Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
|
|
@@ -496,6 +211,10 @@ const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action"
|
|
|
496
211
|
* differ in the 5th to 9th significant digit). Elements on the boundary are exactly 0, and the fit is then singular.
|
|
497
212
|
* The computation is sparse (a sparse Cholesky factorisation, as in lme4), so many groups are handled quickly.
|
|
498
213
|
*
|
|
214
|
+
* The functions that take the fit ({@link lmerSummary}, {@link lmerAnova}, {@link lmerContest} and the others) need
|
|
215
|
+
* the object `lmer` returned itself: a copy of it (`structuredClone`, `{ ...fit }`, JSON or `postMessage`) lacks the
|
|
216
|
+
* internal values they use and is a TypeError. The fields of a copy keep their values.
|
|
217
|
+
*
|
|
499
218
|
* @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
|
|
500
219
|
* @param data The data frame: an object of columns.
|
|
501
220
|
* @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
|
|
@@ -518,7 +237,9 @@ const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action"
|
|
|
518
237
|
* @category Mixed models
|
|
519
238
|
*/
|
|
520
239
|
export function lmer(formula, data, options) {
|
|
521
|
-
|
|
240
|
+
checkLmerOptions("lmer", options, LMER_UNSUPPORTED);
|
|
241
|
+
checkOptions(options, LMER_KEYS, "lmer"); // generated: option-keys.mjs
|
|
242
|
+
return reported("lmer", lmerWithCriterion(formula, data, options, sparseCriterion));
|
|
522
243
|
}
|
|
523
244
|
/**
|
|
524
245
|
* The internals of every result returned by {@link lmer} (and {@link lmerWithCriterion}), keyed by the result object
|
|
@@ -535,12 +256,24 @@ export function lmerInternals(fit) {
|
|
|
535
256
|
throw new TypeError("fit must be a result returned by lmer (not a copy of one)");
|
|
536
257
|
return internals;
|
|
537
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* The exponent of 2 of each column of X whose largest |value| is beyond 2^±500, where the cross-products of X overflow
|
|
261
|
+
* or underflow; 0 for the other columns (internal: lmer's standard errors and lmerTest's quantities)
|
|
262
|
+
*/
|
|
263
|
+
export function extremeColumnExponents(x, p) {
|
|
264
|
+
return Array.from({ length: p }, (_, k) => {
|
|
265
|
+
let top = 0;
|
|
266
|
+
for (const row of x)
|
|
267
|
+
top = Math.max(top, Math.abs(row[k]));
|
|
268
|
+
return top > 2 ** 500 || (top > 0 && top < 2 ** -500) ? Math.floor(Math.log2(top)) : 0;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
538
271
|
/**
|
|
539
272
|
* {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
|
|
540
273
|
* test of the sparse computation fits with the dense reference implementation through it.
|
|
541
274
|
*/
|
|
542
275
|
export function lmerWithCriterion(formula, data, options, criterion) {
|
|
543
|
-
const given =
|
|
276
|
+
const given = options ?? {};
|
|
544
277
|
const reml = logicalOption(given.REML, true);
|
|
545
278
|
options = { ...given, REML: reml };
|
|
546
279
|
const modelOptions = {};
|
|
@@ -568,20 +301,29 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
568
301
|
// β, b, σ and the residuals scale back by 2^ky, the variances by 4^ky, the criteria shift by 2 n ky log 2. Otherwise
|
|
569
302
|
// ky = 0 and nothing changes (issue #9)
|
|
570
303
|
const ky = ycMax > 2 ** 500 || ycMax < 2 ** -500 ? Math.floor(Math.log2(ycMax)) : 0;
|
|
571
|
-
const
|
|
304
|
+
const sResponse = ky === 0 ? s : { ...s, y: yc.map((v) => ldexp(v, -ky)) };
|
|
305
|
+
// Columns of X beyond 2^±500 (predictors times 1e160 or 1e-160: X'X overflowed to NaN in the minimiser, or was
|
|
306
|
+
// subnormal and lost its digits, and (R_X'R_X)⁻¹ overflowed) are divided by their powers of 2 (exact; as Z's columns
|
|
307
|
+
// in issue #11): θ does not depend on it, β_k scales back by 2^-f_k, vcov by 2^(-f_a - f_b), and the REML criterion
|
|
308
|
+
// shifts by 2 Σ f log 2 (log det R_X'R_X). Otherwise f = 0 and nothing changes
|
|
309
|
+
const xScale = extremeColumnExponents(s.x, p);
|
|
310
|
+
const xScaled = xScale.some((e) => e !== 0);
|
|
311
|
+
const sScaled = xScaled ? { ...sResponse, x: sResponse.x.map((row) => row.map((v, k) => ldexp(v, -xScale[k]))) } : sResponse;
|
|
572
312
|
const theta = minimiseCriterionScaled(sScaled, reml, criterion);
|
|
573
313
|
const r = profiledDeviance(sScaled, theta, reml, { rxInverse: true });
|
|
574
314
|
const up = (v) => ldexp(v, ky);
|
|
575
|
-
const fixef = r.beta.map((b, k) => up(b) + beta0[k]);
|
|
315
|
+
const fixef = r.beta.map((b, k) => (xScaled ? ldexp(up(b), -xScale[k]) : up(b)) + beta0[k]);
|
|
576
316
|
const twoPi = 2 * Math.PI;
|
|
577
317
|
const logScale = 2 * ky * Math.LN2;
|
|
318
|
+
const logDetRX = xScaled ? r.logDetRX + 2 * xScale.reduce((a, b) => a + b, 0) * Math.LN2 : r.logDetRX;
|
|
578
319
|
const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n) + logScale);
|
|
579
|
-
const REMLcrit = r.logDetL +
|
|
320
|
+
const REMLcrit = r.logDetL + logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)) + logScale);
|
|
580
321
|
// (σ² of the scaled response; the variances below are 4^ky times what is formed from it)
|
|
581
322
|
const sigma2 = r.prss / (reml ? n - p : n);
|
|
582
323
|
const sigma = up(Math.sqrt(sigma2));
|
|
583
|
-
|
|
584
|
-
const
|
|
324
|
+
// (an entry of vcov may overflow where the standard error does not)
|
|
325
|
+
const vcov = r.rxInverse.map((row, a) => row.map((v, b) => ldexp(sigma2 * v, 2 * ky - (xScaled ? xScale[a] + xScale[b] : 0))));
|
|
326
|
+
const stdError = r.rxInverse.map((row, i) => (xScaled ? ldexp(up(Math.sqrt(sigma2 * row[i])), -xScale[i]) : up(Math.sqrt(sigma2 * row[i]))));
|
|
585
327
|
// (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
|
|
586
328
|
const tValue = fixef.map((b, i) => b / stdError[i]);
|
|
587
329
|
// the blocks T_k and the variance components
|
|
@@ -614,7 +356,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
614
356
|
// the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
|
|
615
357
|
const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * fixef[k], 0));
|
|
616
358
|
// (the residuals on the scaled response, scaled back)
|
|
617
|
-
const residuals =
|
|
359
|
+
const residuals = sScaled.x.map((xi, i) => sScaled.y[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
|
|
618
360
|
s.z.forEach((col, j) => {
|
|
619
361
|
const bj = r.b[j];
|
|
620
362
|
if (bj !== 0) {
|
|
@@ -660,6 +402,18 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
660
402
|
warnings: [...s.warnings],
|
|
661
403
|
};
|
|
662
404
|
const snapshot = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.slice()]));
|
|
663
|
-
internalsByFit.set(result, {
|
|
405
|
+
internalsByFit.set(result, {
|
|
406
|
+
structure: s,
|
|
407
|
+
beta0,
|
|
408
|
+
data,
|
|
409
|
+
snapshot,
|
|
410
|
+
options,
|
|
411
|
+
reml,
|
|
412
|
+
criterion,
|
|
413
|
+
theta: [...theta],
|
|
414
|
+
fixef: [...fixef],
|
|
415
|
+
b: r.b.map(up),
|
|
416
|
+
sigma,
|
|
417
|
+
});
|
|
664
418
|
return result;
|
|
665
419
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { Warnings } from "
|
|
1
|
+
import { Warnings } from "../internal/warnings.js";
|
|
2
2
|
import { type LmerResult } from "./lmer.js";
|
|
3
3
|
import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
|
|
4
4
|
import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
|
|
5
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
5
6
|
/**
|
|
6
7
|
* Options of {@link lmerAnova} for one fit. R's `ddf` gives the Error `lmerAnova: argument 'ddf' is not supported`,
|
|
7
|
-
* any other key
|
|
8
|
+
* any other key a RangeError.
|
|
8
9
|
*
|
|
9
10
|
* @category Mixed models
|
|
10
11
|
*/
|
|
@@ -41,7 +42,7 @@ export interface LmerAnovaTable {
|
|
|
41
42
|
}
|
|
42
43
|
/**
|
|
43
44
|
* Options of {@link lmerAnova} for several fits. R's `modelNames` and `model.names` give the Error
|
|
44
|
-
* `lmerAnova: argument '<key>' is not supported`, any other key
|
|
45
|
+
* `lmerAnova: argument '<key>' is not supported`, any other key a RangeError.
|
|
45
46
|
*
|
|
46
47
|
* @category Mixed models
|
|
47
48
|
*/
|
|
@@ -100,6 +101,54 @@ export declare function anovaRowsOf(s: LmerSatterthwaite, { hypotheses }: LmerHy
|
|
|
100
101
|
terms: string[];
|
|
101
102
|
rows: LmerFRow[];
|
|
102
103
|
};
|
|
104
|
+
/**
|
|
105
|
+
* A fit in a likelihood-ratio comparison (internal): of lmer, glmer (src/models/glmerAnova.ts) or glm, with what the
|
|
106
|
+
* checks and the test of nesting need
|
|
107
|
+
*/
|
|
108
|
+
export interface ComparedModel {
|
|
109
|
+
/** The number of observations (R's nobs: rows used, rows of prior weight 0 included) */
|
|
110
|
+
nObs: number;
|
|
111
|
+
/** The number of parameters (the fit's df) */
|
|
112
|
+
df: number;
|
|
113
|
+
/** The fit's log-likelihood */
|
|
114
|
+
logLik: number;
|
|
115
|
+
/** Whether it is an lmer fit by REML */
|
|
116
|
+
reml: boolean;
|
|
117
|
+
/** The log-likelihood of the maximum-likelihood refit (lmer REML fits) */
|
|
118
|
+
refitLogLik?: () => number;
|
|
119
|
+
/** For lmer and glmer fits: the data object, its snapshot, the rows used and the formula's left-hand side */
|
|
120
|
+
mixed?: {
|
|
121
|
+
data: DataFrame;
|
|
122
|
+
snapshot: DataFrame;
|
|
123
|
+
rows: readonly number[];
|
|
124
|
+
response: string;
|
|
125
|
+
};
|
|
126
|
+
/** The response as the family reads it, one per row used (compared by value where a fit has no formula) */
|
|
127
|
+
response: () => readonly number[];
|
|
128
|
+
/** The prior weights, one per row used (all 1 for lmer) */
|
|
129
|
+
weights: () => readonly number[];
|
|
130
|
+
/** The family and link (lmer: gaussian, identity) */
|
|
131
|
+
family: string;
|
|
132
|
+
link: string;
|
|
133
|
+
/** The offset, one per row used (all 0 without) */
|
|
134
|
+
offset: () => readonly number[];
|
|
135
|
+
/** The fixed-effects model matrix (array of rows) */
|
|
136
|
+
x: () => readonly (readonly number[])[];
|
|
137
|
+
/** The random-effects terms (grouping factor and columns; none for glm) */
|
|
138
|
+
randomTerms: readonly {
|
|
139
|
+
group: string;
|
|
140
|
+
columns: readonly string[];
|
|
141
|
+
}[];
|
|
142
|
+
}
|
|
143
|
+
/** The model of an lmer fit in a comparison (internal) */
|
|
144
|
+
export declare function comparedLmer(fit: LmerResult): ComparedModel;
|
|
145
|
+
/**
|
|
146
|
+
* lme4's likelihood-ratio comparison of fits (internal; lmerAnova's and glmerAnova's): the checks that the fits are of
|
|
147
|
+
* the same observations, the names, the ML refits of REML fits, the rows sorted by the number of parameters and the
|
|
148
|
+
* test where the fit of the row before is nested in the row's. `fn` names the function in its error for fewer than
|
|
149
|
+
* two fits.
|
|
150
|
+
*/
|
|
151
|
+
export declare function compareModels(fn: string, models: readonly ComparedModel[], options: LmerCompareOptions): LmerCompareTable;
|
|
103
152
|
/**
|
|
104
153
|
* The ANOVA table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's denominator degrees of freedom
|
|
105
154
|
* (lmerTest's `anova()`), or, given an array of fits, the likelihood-ratio comparison of the models (lme4's
|