@numero-uno-jpn/rstats 0.13.0 → 0.15.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 +47 -0
- package/README.ja.md +18 -9
- package/README.md +18 -9
- package/dist/chunks/{chunk-MEMYFTYS.js → chunk-4EOKNOXP.js} +1 -1
- package/dist/chunks/chunk-4XGKAHD3.js +2 -0
- package/dist/chunks/chunk-7GEYDIQC.js +2 -0
- package/dist/chunks/{chunk-F44XUHWI.js → chunk-7XHAE2LG.js} +1 -1
- package/dist/chunks/{chunk-BSOUJPDF.js → chunk-A3XZUJCP.js} +2 -2
- package/dist/chunks/{chunk-SVWU5T7C.js → chunk-AEFWSUZ2.js} +2 -2
- package/dist/chunks/chunk-CJ5ETQCK.js +2 -0
- package/dist/chunks/{chunk-4GNJEYXR.js → chunk-CMPDE3SZ.js} +2 -2
- package/dist/chunks/chunk-GZTLODPK.js +3 -0
- package/dist/chunks/{chunk-3AKA4KEL.js → chunk-HNLKOICT.js} +1 -1
- package/dist/chunks/{chunk-SLSDFIW2.js → chunk-HS7KIFMR.js} +2 -2
- package/dist/chunks/{chunk-CQNVEA22.js → chunk-LU5FHU2O.js} +2 -2
- package/dist/chunks/chunk-LVXAWWUX.js +2 -0
- package/dist/chunks/{chunk-BJHBYEEU.js → chunk-LWUTCYTZ.js} +1 -1
- package/dist/chunks/chunk-NYGWVZOC.js +2 -0
- package/dist/chunks/{chunk-4AQNVF3Z.js → chunk-PRDF6IU6.js} +2 -2
- package/dist/chunks/{chunk-VG67L3JA.js → chunk-QQIWOGHR.js} +2 -2
- package/dist/chunks/chunk-VAPGDPHM.js +2 -0
- package/dist/chunks/chunk-VSKWQMSG.js +2 -0
- package/dist/chunks/{chunk-JGFUZKLJ.js → chunk-WEWXYHPR.js} +2 -2
- package/dist/chunks/{chunk-2IAT6MT2.js → chunk-XMTYTJT6.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +3 -1
- package/dist/entries/mixed.js +4 -1
- package/dist/internal/fround.d.ts +12 -0
- package/dist/internal/fround.js +89 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -3
- package/dist/models/glm.js +4 -2
- package/dist/models/glmFamily.js +16 -4
- package/dist/models/lmer.d.ts +64 -8
- package/dist/models/lmer.js +146 -20
- package/dist/models/lmerAnova.d.ts +143 -0
- package/dist/models/lmerAnova.js +140 -0
- package/dist/models/lmerHypotheses.d.ts +106 -0
- package/dist/models/lmerHypotheses.js +305 -0
- package/dist/models/lmerTest.d.ts +239 -0
- package/dist/models/lmerTest.js +311 -0
- package/dist/models/mixedDerivatives.d.ts +27 -0
- package/dist/models/mixedDerivatives.js +342 -0
- package/dist/models/mixedDeviance.d.ts +112 -0
- package/dist/models/mixedDeviance.js +216 -86
- package/dist/models/mixedStructure.d.ts +5 -3
- package/dist/models/mixedStructure.js +30 -14
- package/dist/models/modelMatrix.d.ts +10 -3
- package/dist/models/modelMatrix.js +23 -2
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +13 -13
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -12
- package/llms.txt +6 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-22SXZNR6.js +0 -2
- package/dist/chunks/chunk-AGRKZXLG.js +0 -2
- package/dist/chunks/chunk-N3FV6H3C.js +0 -2
- package/dist/chunks/chunk-NRV3BH7I.js +0 -2
- package/dist/chunks/chunk-RTWLZPPG.js +0 -2
- package/dist/chunks/chunk-VWGJYRE6.js +0 -2
package/dist/models/lmer.js
CHANGED
|
@@ -39,6 +39,21 @@
|
|
|
39
39
|
// of all the elements has a direction of negative curvature that moves it (then θ is moved a little along it).
|
|
40
40
|
// lme4's own optimiser (and its convergence warnings) are not reproduced: the result is the exact minimiser, which
|
|
41
41
|
// lme4 approaches to its tolerances.
|
|
42
|
+
//
|
|
43
|
+
// The criterion can have several local minima (crossed terms without a fixed intercept, for example, where one term
|
|
44
|
+
// can take the place of the missing intercept). So the local minimum θ* reached from the initial θ is compared with
|
|
45
|
+
// the boundary points of whole terms (oracle/report-0.14.0-behaviour.md, section 1): for each term whose block is not
|
|
46
|
+
// entirely 0 in θ*, the local minimum started at θ* with that term removed (its whole block set to 0) and held at 0.
|
|
47
|
+
// If the lowest of these is lower than θ*'s criterion by more than 1e-8 max(1, |criterion|), the minimisation starts
|
|
48
|
+
// again from it with every element free, and the comparison is repeated; otherwise θ* is the estimate (at most 50
|
|
49
|
+
// restarts). Only whole terms are removed, one at a time.
|
|
50
|
+
//
|
|
51
|
+
// The penalised least-squares problem is linear in y: y − X β₀ for any β₀ gives the same criterion, residuals,
|
|
52
|
+
// random effects and derivatives, and β̂ − β₀. So the fit works with y − X β₀, β₀ the least-squares coefficients of y
|
|
53
|
+
// on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
|
|
54
|
+
// from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
|
|
55
|
+
// 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
|
|
56
|
+
import { qr, qrCoef } from "../linalg/qr.js";
|
|
42
57
|
import { profiledDeviance } from "./mixedDeviance.js";
|
|
43
58
|
import { mixedModelStructure } from "./mixedStructure.js";
|
|
44
59
|
/** Initial trust-region radius, relative to max(1, max |θ|) */
|
|
@@ -62,6 +77,13 @@ const GRADIENT_TOLERANCE = 1e-9;
|
|
|
62
77
|
const MAX_ITERATIONS = 500;
|
|
63
78
|
/** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
|
|
64
79
|
const HESSIAN_REUSE_RATIO = 0.75;
|
|
80
|
+
/** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
|
|
81
|
+
const RESTART_THRESHOLD = 1e-8;
|
|
82
|
+
/** ... and there are at most this many restarts */
|
|
83
|
+
const MAX_RESTARTS = 50;
|
|
84
|
+
/** The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y| */
|
|
85
|
+
const EXACT_FIT = 1e-12;
|
|
86
|
+
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";
|
|
65
87
|
const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
|
|
66
88
|
/** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
|
|
67
89
|
function symmetricEigen(a0) {
|
|
@@ -185,11 +207,14 @@ const sparseCriterion = (s, theta, reml) => {
|
|
|
185
207
|
const r = profiledDeviance(s, theta, reml, { gradient: true });
|
|
186
208
|
return { f: r.deviance, g: r.gradient };
|
|
187
209
|
};
|
|
188
|
-
/**
|
|
189
|
-
|
|
210
|
+
/**
|
|
211
|
+
* A local minimiser of the criterion over θ, subject to the lower bounds (see the header), started at `start`, with
|
|
212
|
+
* the elements in `held` kept at exactly 0 throughout (never free, never released); with its criterion
|
|
213
|
+
*/
|
|
214
|
+
function localMinimum(s, reml, criterion, start, held = new Set()) {
|
|
190
215
|
const diagonal = s.lower.map((b) => b === 0);
|
|
191
216
|
const evaluate = (theta) => criterion(s, theta, reml);
|
|
192
|
-
let theta =
|
|
217
|
+
let theta = start.map((v, j) => (held.has(j) ? 0 : v));
|
|
193
218
|
let { f, g } = evaluate(theta);
|
|
194
219
|
/** Diagonal elements held at exactly 0 */
|
|
195
220
|
const fixed = new Set();
|
|
@@ -269,7 +294,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
269
294
|
const leaveAlongNegativeCurvature = () => {
|
|
270
295
|
if (fixed.size === 0)
|
|
271
296
|
return false;
|
|
272
|
-
const set = theta.map((_, j) => j);
|
|
297
|
+
const set = theta.map((_, j) => j).filter((j) => !held.has(j));
|
|
273
298
|
const eig = symmetricEigen(hessian(set));
|
|
274
299
|
const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
|
|
275
300
|
const k = eig.values.indexOf(Math.min(...eig.values));
|
|
@@ -289,7 +314,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
289
314
|
return true;
|
|
290
315
|
};
|
|
291
316
|
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
|
292
|
-
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j));
|
|
317
|
+
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
|
|
293
318
|
if (free.length > 0 && !iterate(free))
|
|
294
319
|
continue;
|
|
295
320
|
// converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
|
|
@@ -320,7 +345,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
320
345
|
for (const j of column)
|
|
321
346
|
theta[j] = -theta[j];
|
|
322
347
|
}
|
|
323
|
-
return theta.map((v) => (v === 0 ? 0 : v)); // no -0
|
|
348
|
+
return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
|
|
324
349
|
}
|
|
325
350
|
radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
|
|
326
351
|
previousNewton = Infinity;
|
|
@@ -328,6 +353,70 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
328
353
|
}
|
|
329
354
|
throw new Error(OPTIMISATION_FAILED);
|
|
330
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
|
|
358
|
+
* its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
|
|
359
|
+
* minimisation, until none is.
|
|
360
|
+
*/
|
|
361
|
+
function minimiseCriterion(s, reml, criterion) {
|
|
362
|
+
/** The θ indices of each term's block (its whole lower triangle) */
|
|
363
|
+
const blocks = s.terms.map((t) => {
|
|
364
|
+
const nc = t.columns.length;
|
|
365
|
+
return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
|
|
366
|
+
});
|
|
367
|
+
let best = localMinimum(s, reml, criterion, s.theta);
|
|
368
|
+
for (let round = 0; round < MAX_RESTARTS; round++) {
|
|
369
|
+
let candidate;
|
|
370
|
+
for (const block of blocks) {
|
|
371
|
+
if (block.every((j) => best.theta[j] === 0))
|
|
372
|
+
continue;
|
|
373
|
+
const removed = localMinimum(s, reml, criterion, best.theta, new Set(block));
|
|
374
|
+
if (candidate === undefined || removed.f < candidate.f)
|
|
375
|
+
candidate = removed;
|
|
376
|
+
}
|
|
377
|
+
if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
|
|
378
|
+
return best.theta;
|
|
379
|
+
best = localMinimum(s, reml, criterion, candidate.theta);
|
|
380
|
+
}
|
|
381
|
+
throw new Error(OPTIMISATION_FAILED);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The option checks of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section 3):
|
|
385
|
+
* `options` must be an object when given (not null, not an array); its own keys, in order, may be neither among those
|
|
386
|
+
* of R that are not supported (the first gives an Error) nor unknown (a TypeError listing all of them). A key whose
|
|
387
|
+
* value is `undefined` counts as given. Returns the options as an object (`{}` when not given).
|
|
388
|
+
*/
|
|
389
|
+
export function checkOptions(fn, options, accepted, unsupported) {
|
|
390
|
+
if (options === undefined)
|
|
391
|
+
return {};
|
|
392
|
+
if (typeof options !== "object" || options === null || Array.isArray(options))
|
|
393
|
+
throw new TypeError("options must be an object");
|
|
394
|
+
const keys = Object.keys(options);
|
|
395
|
+
const notSupported = keys.find((k) => unsupported.includes(k));
|
|
396
|
+
if (notSupported !== undefined)
|
|
397
|
+
throw new Error(`${fn}: argument '${notSupported}' is not supported`);
|
|
398
|
+
const unknown = keys.filter((k) => !accepted.includes(k));
|
|
399
|
+
if (unknown.length > 0)
|
|
400
|
+
throw new TypeError(`unused argument${unknown.length === 1 ? "" : "s"} (${unknown.join(", ")})`);
|
|
401
|
+
return options;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
|
|
405
|
+
* other than NaN `false` for 0 and `true` otherwise; `null` and anything else are TypeErrors.
|
|
406
|
+
*/
|
|
407
|
+
export function logicalOption(value, defaultValue) {
|
|
408
|
+
if (value === undefined)
|
|
409
|
+
return defaultValue;
|
|
410
|
+
if (typeof value === "boolean")
|
|
411
|
+
return value;
|
|
412
|
+
if (typeof value === "number" && !Number.isNaN(value))
|
|
413
|
+
return value !== 0;
|
|
414
|
+
if (value === null)
|
|
415
|
+
throw new TypeError("argument is of length zero");
|
|
416
|
+
throw new TypeError("argument is not interpretable as logical");
|
|
417
|
+
}
|
|
418
|
+
const LMER_KEYS = ["REML", "contrasts", "levels"];
|
|
419
|
+
const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action", "control", "start", "verbose", "devFunOnly"];
|
|
331
420
|
/**
|
|
332
421
|
* Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
|
|
333
422
|
* quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
|
|
@@ -345,7 +434,7 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
345
434
|
*
|
|
346
435
|
* @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
|
|
347
436
|
* @param data The data frame: an object of columns.
|
|
348
|
-
* @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
|
|
437
|
+
* @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
|
|
349
438
|
*
|
|
350
439
|
* @example
|
|
351
440
|
* ```ts
|
|
@@ -364,25 +453,51 @@ function minimiseCriterion(s, reml, criterion) {
|
|
|
364
453
|
*
|
|
365
454
|
* @category Mixed models
|
|
366
455
|
*/
|
|
367
|
-
export function lmer(formula, data, options
|
|
456
|
+
export function lmer(formula, data, options) {
|
|
368
457
|
return lmerWithCriterion(formula, data, options, sparseCriterion);
|
|
369
458
|
}
|
|
459
|
+
/**
|
|
460
|
+
* The internals of every result returned by {@link lmer} (and {@link lmerWithCriterion}), keyed by the result object
|
|
461
|
+
* itself: a copy of a result (`{ ...fit }`) has none.
|
|
462
|
+
*/
|
|
463
|
+
const internalsByFit = new WeakMap();
|
|
464
|
+
/**
|
|
465
|
+
* The internals of a fit (see {@link LmerInternals}). Internal. Throws a TypeError for an object that is not a result
|
|
466
|
+
* returned by {@link lmer}.
|
|
467
|
+
*/
|
|
468
|
+
export function lmerInternals(fit) {
|
|
469
|
+
const internals = typeof fit === "object" && fit !== null ? internalsByFit.get(fit) : undefined;
|
|
470
|
+
if (internals === undefined)
|
|
471
|
+
throw new TypeError("fit must be a result returned by lmer (not a copy of one)");
|
|
472
|
+
return internals;
|
|
473
|
+
}
|
|
370
474
|
/**
|
|
371
475
|
* {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
|
|
372
476
|
* test of the sparse computation fits with the dense reference implementation through it.
|
|
373
477
|
*/
|
|
374
478
|
export function lmerWithCriterion(formula, data, options, criterion) {
|
|
375
|
-
const
|
|
479
|
+
const given = checkOptions("lmer", options, LMER_KEYS, LMER_UNSUPPORTED);
|
|
480
|
+
const reml = logicalOption(given.REML, true);
|
|
481
|
+
options = { ...given, REML: reml };
|
|
376
482
|
const modelOptions = {};
|
|
377
483
|
if (options.contrasts !== undefined)
|
|
378
484
|
modelOptions.contrasts = options.contrasts;
|
|
379
485
|
if (options.levels !== undefined)
|
|
380
486
|
modelOptions.levels = options.levels;
|
|
381
|
-
const
|
|
487
|
+
const original = mixedModelStructure(formula, data, modelOptions);
|
|
488
|
+
const n = original.y.length;
|
|
489
|
+
const p = original.xColNames.length;
|
|
490
|
+
// β₀, the least-squares coefficients of y on X, and the residuals y − X β₀ (see the header)
|
|
491
|
+
const beta0 = p === 0 ? [] : qrCoef(qr(original.x), original.y);
|
|
492
|
+
const yc = original.y.map((y, i) => y - original.x[i].reduce((sum, v, k) => sum + v * beta0[k], 0));
|
|
493
|
+
// a response in the column space of X: the criterion is −∞ for every θ (no estimate)
|
|
494
|
+
const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);
|
|
495
|
+
if (maxAbs(yc) <= EXACT_FIT * maxAbs(original.y))
|
|
496
|
+
throw new Error(EXACT_FIT_ERROR);
|
|
497
|
+
const s = { ...original, y: yc };
|
|
382
498
|
const theta = minimiseCriterion(s, reml, criterion);
|
|
383
499
|
const r = profiledDeviance(s, theta, reml, { rxInverse: true });
|
|
384
|
-
const
|
|
385
|
-
const p = s.xColNames.length;
|
|
500
|
+
const fixef = r.beta.map((b, k) => b + beta0[k]);
|
|
386
501
|
const twoPi = 2 * Math.PI;
|
|
387
502
|
const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n));
|
|
388
503
|
const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)));
|
|
@@ -390,7 +505,8 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
390
505
|
const sigma = Math.sqrt(sigma2);
|
|
391
506
|
const vcov = r.rxInverse.map((row) => row.map((v) => sigma2 * v));
|
|
392
507
|
const stdError = vcov.map((row, i) => Math.sqrt(row[i]));
|
|
393
|
-
|
|
508
|
+
// (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
|
|
509
|
+
const tValue = fixef.map((b, i) => b / stdError[i]);
|
|
394
510
|
// the blocks T_k and the variance components
|
|
395
511
|
const varCorr = s.terms.map((term) => {
|
|
396
512
|
const nc = term.columns.length;
|
|
@@ -401,6 +517,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
401
517
|
t[i][j] = theta[k++];
|
|
402
518
|
const cov = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
|
|
403
519
|
const sd = cov.map((row, i) => Math.sqrt(row[i]));
|
|
520
|
+
// (a column with variance 0 has the correlations 0/0 = NaN with the others, as lme4's VarCorr: not a bug)
|
|
404
521
|
const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
|
|
405
522
|
return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
|
|
406
523
|
});
|
|
@@ -416,28 +533,35 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
416
533
|
})),
|
|
417
534
|
};
|
|
418
535
|
});
|
|
419
|
-
|
|
536
|
+
// the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
|
|
537
|
+
const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * fixef[k], 0));
|
|
538
|
+
const residuals = s.x.map((xi, i) => yc[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
|
|
420
539
|
s.z.forEach((col, j) => {
|
|
421
540
|
const bj = r.b[j];
|
|
422
|
-
if (bj !== 0)
|
|
423
|
-
col.rows.forEach((i, k) =>
|
|
541
|
+
if (bj !== 0) {
|
|
542
|
+
col.rows.forEach((i, k) => {
|
|
543
|
+
fitted[i] += col.values[k] * bj;
|
|
544
|
+
residuals[i] -= col.values[k] * bj;
|
|
545
|
+
});
|
|
546
|
+
}
|
|
424
547
|
});
|
|
425
|
-
const residuals = s.y.map((y, i) => y - fitted[i]);
|
|
426
548
|
const logLik = -(reml ? REMLcrit : deviance) / 2;
|
|
427
549
|
const df = p + theta.length + 1;
|
|
550
|
+
// (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4; it is not
|
|
551
|
+
// meant to match the minimiser's relative boundary test)
|
|
428
552
|
const singular = theta.some((v, j) => s.lower[j] === 0 && v < 1e-4);
|
|
429
553
|
const messages = [...s.messages];
|
|
430
554
|
if (singular)
|
|
431
555
|
messages.push("boundary (singular) fit: see help('isSingular')");
|
|
432
|
-
|
|
556
|
+
const result = {
|
|
433
557
|
formula,
|
|
434
558
|
REML: reml,
|
|
435
559
|
nObs: n,
|
|
436
560
|
rows: [...s.rows],
|
|
437
561
|
theta,
|
|
438
562
|
fixefNames: [...s.xColNames],
|
|
439
|
-
fixef
|
|
440
|
-
coefTable: { estimate: [...
|
|
563
|
+
fixef,
|
|
564
|
+
coefTable: { estimate: [...fixef], stdError, tValue },
|
|
441
565
|
vcov,
|
|
442
566
|
sigma,
|
|
443
567
|
varCorr,
|
|
@@ -454,4 +578,6 @@ export function lmerWithCriterion(formula, data, options, criterion) {
|
|
|
454
578
|
messages,
|
|
455
579
|
warnings: [...s.warnings],
|
|
456
580
|
};
|
|
581
|
+
internalsByFit.set(result, { structure: s, beta0, data, options, reml, criterion, theta: [...theta] });
|
|
582
|
+
return result;
|
|
457
583
|
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { Warnings } from "./glmFamily.js";
|
|
2
|
+
import { type LmerResult } from "./lmer.js";
|
|
3
|
+
import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
|
|
4
|
+
import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
|
|
5
|
+
/**
|
|
6
|
+
* Options of {@link lmerAnova} for one fit. R's `ddf` gives the Error `lmerAnova: argument 'ddf' is not supported`,
|
|
7
|
+
* any other key the TypeError `unused argument (<key>)`.
|
|
8
|
+
*
|
|
9
|
+
* @category Mixed models
|
|
10
|
+
*/
|
|
11
|
+
export interface LmerAnovaOptions {
|
|
12
|
+
/** The type of the sums of squares: `"III"` (default), `"II"` or `"I"` (also `3`, `2`, `1`). */
|
|
13
|
+
type?: LmerAnovaType | 1 | 2 | 3;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Result of {@link lmerAnova} for one fit: lmerTest's ANOVA table, one row per term of the fixed effects.
|
|
17
|
+
*
|
|
18
|
+
* @category Mixed models
|
|
19
|
+
*/
|
|
20
|
+
export interface LmerAnovaTable {
|
|
21
|
+
/** The type of the sums of squares. */
|
|
22
|
+
type: LmerAnovaType;
|
|
23
|
+
/** The terms (R's row names), in the order of the formula's terms; terms without a test come last. */
|
|
24
|
+
terms: string[];
|
|
25
|
+
/** R's `Sum Sq`: F σ² NumDF. */
|
|
26
|
+
sumSq: number[];
|
|
27
|
+
/** R's `Mean Sq`: F σ². */
|
|
28
|
+
meanSq: number[];
|
|
29
|
+
/** R's `NumDF`. */
|
|
30
|
+
numDF: number[];
|
|
31
|
+
/** R's `DenDF`: Satterthwaite's denominator degrees of freedom. */
|
|
32
|
+
denDF: number[];
|
|
33
|
+
/** R's `F value`. */
|
|
34
|
+
F: number[];
|
|
35
|
+
/** R's `Pr(>F)`. */
|
|
36
|
+
pValue: number[];
|
|
37
|
+
/** R's messages (Type III: `Missing cells for: ...`). */
|
|
38
|
+
messages: string[];
|
|
39
|
+
/** R's warnings (about the eigenvalues of the Hessian of the deviance in the variance parameters). */
|
|
40
|
+
warnings: string[];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 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 the TypeError `unused argument (<key>)`.
|
|
45
|
+
*
|
|
46
|
+
* @category Mixed models
|
|
47
|
+
*/
|
|
48
|
+
export interface LmerCompareOptions {
|
|
49
|
+
/**
|
|
50
|
+
* Refit the REML fits by maximum likelihood before comparing them (default `true`). As in R's conditions, a number
|
|
51
|
+
* is `false` for 0 and `true` otherwise; `null` and other values are TypeErrors.
|
|
52
|
+
*/
|
|
53
|
+
refit?: boolean;
|
|
54
|
+
/** The names of the models, in the order given (default `"MODEL1"`, `"MODEL2"`, ...). */
|
|
55
|
+
names?: readonly string[];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Result of {@link lmerAnova} for several fits: lme4's comparison table, one row per model, sorted by the number of
|
|
59
|
+
* parameters.
|
|
60
|
+
*
|
|
61
|
+
* @category Mixed models
|
|
62
|
+
*/
|
|
63
|
+
export interface LmerCompareTable {
|
|
64
|
+
/** The models' names (R's row names), in the order of the rows. */
|
|
65
|
+
names: string[];
|
|
66
|
+
/** The number of parameters of each model (fixed effects, θ and σ). */
|
|
67
|
+
npar: number[];
|
|
68
|
+
/** Akaike's information criterion, −2 logLik + 2 npar. */
|
|
69
|
+
AIC: number[];
|
|
70
|
+
/** Schwarz's criterion, −2 logLik + log(n) npar. */
|
|
71
|
+
BIC: number[];
|
|
72
|
+
/** The log-likelihood (of the ML refit, or the fit's own with `refit: false`). */
|
|
73
|
+
logLik: number[];
|
|
74
|
+
/** −2 logLik (R's `-2*log(L)`). */
|
|
75
|
+
deviance: number[];
|
|
76
|
+
/** The likelihood-ratio statistic against the row before (NaN in the first row). */
|
|
77
|
+
Chisq: number[];
|
|
78
|
+
/** The difference of npar from the row before (NaN in the first row). */
|
|
79
|
+
Df: number[];
|
|
80
|
+
/** R's `Pr(>Chisq)` (NaN in the first row and where Df is 0). */
|
|
81
|
+
pValue: number[];
|
|
82
|
+
/** R's messages (`refitting model(s) with ML (instead of REML)`). */
|
|
83
|
+
messages: string[];
|
|
84
|
+
/** R's warnings (duplicated names, a mix of REML and ML fits without refitting). */
|
|
85
|
+
warnings: string[];
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The type of the sums of squares of an ANOVA table of {@link lmerAnova}.
|
|
89
|
+
*
|
|
90
|
+
* @category Mixed models
|
|
91
|
+
*/
|
|
92
|
+
export type LmerAnovaType = "I" | "II" | "III";
|
|
93
|
+
/** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
|
|
94
|
+
export declare function anovaHypotheses(fit: LmerResult, type: HypothesisType): {
|
|
95
|
+
hypotheses: LmerHypotheses;
|
|
96
|
+
termLabels: string[];
|
|
97
|
+
};
|
|
98
|
+
/** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
|
|
99
|
+
export declare function anovaRowsOf(s: LmerSatterthwaite, { hypotheses }: LmerHypotheses, termLabels: readonly string[], warnings: Warnings): {
|
|
100
|
+
terms: string[];
|
|
101
|
+
rows: LmerFRow[];
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* The ANOVA table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's denominator degrees of freedom
|
|
105
|
+
* (lmerTest's `anova()`), or, given an array of fits, the likelihood-ratio comparison of the models (lme4's
|
|
106
|
+
* `anova()` of several fits). Equivalent to `lmerTest::anova()` in R.
|
|
107
|
+
*
|
|
108
|
+
* For one fit: each term of the fixed effects is tested jointly (an F-test of its hypothesis matrix, of Type III by
|
|
109
|
+
* default, II or I as in lmerTest; see {@link lmerContest} for the test). Type III with an empty cell of an
|
|
110
|
+
* interaction gives the message `Missing cells for: ...`. A term without a test is listed last, with NaN.
|
|
111
|
+
*
|
|
112
|
+
* For several fits (fitted to the same data object, with the same rows): REML fits are first refitted by maximum
|
|
113
|
+
* likelihood (unless `refit: false`), the models are sorted by their number of parameters, and each is compared with
|
|
114
|
+
* the one before by the likelihood-ratio test.
|
|
115
|
+
*
|
|
116
|
+
* @param fit A result of {@link lmer} (the object it returned, not a copy), or an array of at least two.
|
|
117
|
+
* @param options For one fit `type`; for several `refit` and `names`.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```ts
|
|
121
|
+
* // R: anova(lmerTest::lmer(y ~ x * f + (1 | g), data))
|
|
122
|
+
* const data = {
|
|
123
|
+
* y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4, 4.4, 5.0, 6.9, 3.0, 4.1, 4.9],
|
|
124
|
+
* x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
|
|
125
|
+
* f: ["u", "u", "v", "v", "u", "v", "u", "v", "v", "u", "v", "u", "v", "u", "u", "v", "u", "v"],
|
|
126
|
+
* g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d", "e", "e", "e", "f", "f", "f"],
|
|
127
|
+
* };
|
|
128
|
+
* const fit = lmer("y ~ x * f + (1 | g)", data);
|
|
129
|
+
* const t = lmerAnova(fit);
|
|
130
|
+
* t.terms; // ["x", "f", "x:f"]
|
|
131
|
+
* t.numDF; // [1, 1, 1]
|
|
132
|
+
* t.F; // [82.027, 0.44207, 0.53285]
|
|
133
|
+
* // R: anova(lme4::lmer(y ~ x + (1 | g), data), fit)
|
|
134
|
+
* const c = lmerAnova([lmer("y ~ x + (1 | g)", data), fit], { names: ["small", "full"] });
|
|
135
|
+
* c.npar; // [4, 6]
|
|
136
|
+
* c.Chisq; // [NaN, 0.6817]
|
|
137
|
+
* c.messages; // ["refitting model(s) with ML (instead of REML)"]
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* @category Mixed models
|
|
141
|
+
*/
|
|
142
|
+
export declare function lmerAnova(fit: LmerResult, options?: LmerAnovaOptions): LmerAnovaTable;
|
|
143
|
+
export declare function lmerAnova(fits: readonly LmerResult[], options?: LmerCompareOptions): LmerCompareTable;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// ANOVA tables of linear mixed models fitted by lmer (src/models/lmer.ts): lmerTest's Type I, II and III tables of one
|
|
2
|
+
// fit (each term's hypothesis tested jointly with Satterthwaite's denominator degrees of freedom), and lme4's
|
|
3
|
+
// likelihood-ratio comparison of several fits.
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code) from oracle/lmertest-behaviour.md (sections 2 and 3). The hypothesis
|
|
6
|
+
// matrices come from src/models/lmerHypotheses.ts, the F-tests from src/models/lmerTest.ts; the comparison refits REML
|
|
7
|
+
// fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
|
|
8
|
+
import { pgamma1 } from "../distributions/gamma.js";
|
|
9
|
+
import { Warnings } from "./glmFamily.js";
|
|
10
|
+
import { checkOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
|
|
11
|
+
import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
|
|
12
|
+
import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
|
|
13
|
+
const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
|
|
14
|
+
/** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
|
|
15
|
+
export function anovaHypotheses(fit, type) {
|
|
16
|
+
const { structure, data, options } = lmerInternals(fit);
|
|
17
|
+
const descOptions = {};
|
|
18
|
+
if (options.contrasts !== undefined)
|
|
19
|
+
descOptions.contrasts = options.contrasts;
|
|
20
|
+
if (options.levels !== undefined)
|
|
21
|
+
descOptions.levels = options.levels;
|
|
22
|
+
const desc = fixedEffectsDescription(fit.formula, data, descOptions);
|
|
23
|
+
if (desc.colNames.length !== structure.xColNames.length || desc.colNames.some((c, j) => c !== structure.xColNames[j])) {
|
|
24
|
+
throw new Error("lmerAnova: the columns of the hypotheses differ from the fit's fixed effects");
|
|
25
|
+
}
|
|
26
|
+
// an intercept-only model (or one without fixed effects) has an empty table
|
|
27
|
+
if (desc.terms.length === 0)
|
|
28
|
+
return { hypotheses: { hypotheses: [], messages: [] }, termLabels: [] };
|
|
29
|
+
return { hypotheses: lmerHypotheses(desc, type), termLabels: desc.terms.map((t) => t.label) };
|
|
30
|
+
}
|
|
31
|
+
/** The rows of an ANOVA table from the hypotheses and given Satterthwaite quantities (internal) */
|
|
32
|
+
export function anovaRowsOf(s, { hypotheses }, termLabels, warnings) {
|
|
33
|
+
const terms = [];
|
|
34
|
+
const rows = [];
|
|
35
|
+
for (const h of hypotheses) {
|
|
36
|
+
const row = h.values.length === 0 ? undefined : fTestOf(s, h.values, undefined, warnings);
|
|
37
|
+
if (row === undefined)
|
|
38
|
+
continue;
|
|
39
|
+
terms.push(h.term);
|
|
40
|
+
rows.push(row);
|
|
41
|
+
}
|
|
42
|
+
for (const label of termLabels) {
|
|
43
|
+
if (terms.includes(label))
|
|
44
|
+
continue;
|
|
45
|
+
terms.push(label);
|
|
46
|
+
rows.push({ sumSq: NaN, meanSq: NaN, numDF: NaN, denDF: NaN, F: NaN, pValue: NaN });
|
|
47
|
+
}
|
|
48
|
+
return { terms, rows };
|
|
49
|
+
}
|
|
50
|
+
function anovaOfFit(fit, options) {
|
|
51
|
+
const type = TYPES[String(options.type ?? "III")];
|
|
52
|
+
if (type === undefined)
|
|
53
|
+
throw new RangeError(`type must be "I", "II" or "III", not ${JSON.stringify(options.type)}`);
|
|
54
|
+
const { hypotheses, termLabels } = anovaHypotheses(fit, type);
|
|
55
|
+
const s = lmerSatterthwaite(fit);
|
|
56
|
+
const warnings = new Warnings();
|
|
57
|
+
s.warnings.forEach((w) => warnings.add(w));
|
|
58
|
+
const { terms, rows } = anovaRowsOf(s, hypotheses, termLabels, warnings);
|
|
59
|
+
const column = (k) => rows.map((r) => r[k]);
|
|
60
|
+
return {
|
|
61
|
+
type,
|
|
62
|
+
terms,
|
|
63
|
+
sumSq: column("sumSq"),
|
|
64
|
+
meanSq: column("meanSq"),
|
|
65
|
+
numDF: column("numDF"),
|
|
66
|
+
denDF: column("denDF"),
|
|
67
|
+
F: column("F"),
|
|
68
|
+
pValue: column("pValue"),
|
|
69
|
+
messages: [...hypotheses.messages],
|
|
70
|
+
warnings: warnings.list,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function compareFits(fits, options) {
|
|
74
|
+
if (fits.length < 2)
|
|
75
|
+
throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
|
|
76
|
+
const internals = fits.map(lmerInternals);
|
|
77
|
+
// (only the number of observations is compared, as lme4 does; the fits must also share the data object below)
|
|
78
|
+
if (fits.some((f) => f.nObs !== fits[0].nObs))
|
|
79
|
+
throw new Error("models were not all fitted to the same size of dataset");
|
|
80
|
+
if (internals.some((i) => i.data !== internals[0].data))
|
|
81
|
+
throw new Error("all models must be fit to the same data object");
|
|
82
|
+
const warnings = new Warnings();
|
|
83
|
+
const messages = [];
|
|
84
|
+
let names = fits.map((_, i) => `MODEL${i + 1}`);
|
|
85
|
+
if (options.names !== undefined) {
|
|
86
|
+
if (options.names.length !== fits.length || options.names.some((n) => typeof n !== "string")) {
|
|
87
|
+
throw new TypeError(`names must be ${fits.length} strings, one per fit`);
|
|
88
|
+
}
|
|
89
|
+
if (new Set(options.names).size === options.names.length)
|
|
90
|
+
names = [...options.names];
|
|
91
|
+
else
|
|
92
|
+
warnings.add("failed to find model names, assigning generic names");
|
|
93
|
+
}
|
|
94
|
+
const refit = logicalOption(options.refit, true);
|
|
95
|
+
let logLik;
|
|
96
|
+
if (refit) {
|
|
97
|
+
if (fits.some((f) => f.REML))
|
|
98
|
+
messages.push("refitting model(s) with ML (instead of REML)");
|
|
99
|
+
logLik = fits.map((f, i) => {
|
|
100
|
+
if (!f.REML)
|
|
101
|
+
return f.logLik;
|
|
102
|
+
const { data, options: o, criterion } = internals[i];
|
|
103
|
+
return lmerWithCriterion(f.formula, data, { ...o, REML: false }, criterion).logLik;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
if (fits.some((f) => f.REML) && fits.some((f) => !f.REML))
|
|
108
|
+
warnings.add("some models fit with REML = TRUE, some not");
|
|
109
|
+
logLik = fits.map((f) => f.logLik);
|
|
110
|
+
}
|
|
111
|
+
// sorted by the number of parameters (stable)
|
|
112
|
+
const order = fits.map((_, i) => i).sort((a, b) => fits[a].df - fits[b].df || a - b);
|
|
113
|
+
const n = fits[0].nObs;
|
|
114
|
+
const npar = order.map((i) => fits[i].df);
|
|
115
|
+
const ll = order.map((i) => logLik[i]);
|
|
116
|
+
const Chisq = ll.map((v, k) => (k === 0 ? NaN : 2 * Math.max(0, v - ll[k - 1])));
|
|
117
|
+
const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
|
|
118
|
+
const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
|
|
119
|
+
return {
|
|
120
|
+
names: order.map((i) => names[i]),
|
|
121
|
+
npar,
|
|
122
|
+
AIC: ll.map((v, k) => -2 * v + 2 * npar[k]),
|
|
123
|
+
BIC: ll.map((v, k) => -2 * v + Math.log(n) * npar[k]),
|
|
124
|
+
logLik: ll,
|
|
125
|
+
deviance: ll.map((v) => -2 * v),
|
|
126
|
+
Chisq,
|
|
127
|
+
Df,
|
|
128
|
+
pValue,
|
|
129
|
+
messages,
|
|
130
|
+
warnings: warnings.list,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
export function lmerAnova(fit, options) {
|
|
134
|
+
if (Array.isArray(fit)) {
|
|
135
|
+
const checked = checkOptions("lmerAnova", options, ["refit", "names"], ["modelNames", "model.names"]);
|
|
136
|
+
// (the logical value is checked with the options, before the fits)
|
|
137
|
+
return compareFits(fit, { ...checked, refit: logicalOption(checked.refit, true) });
|
|
138
|
+
}
|
|
139
|
+
return anovaOfFit(fit, checkOptions("lmerAnova", options, ["type"], ["ddf"]));
|
|
140
|
+
}
|