@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
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
// Generalized linear mixed models fitted by the Laplace approximation, by adaptive Gauss-Hermite quadrature or with the
|
|
2
|
+
// fixed effects from the penalised IRLS (lme4's glmer with nAGQ = 1, > 1 or 0): the exact minimiser of the deviance
|
|
3
|
+
// (Laplace or quadrature) computed at the exact
|
|
4
|
+
// conditional mode, and the fit's results at it (fixed effects and their covariance, the variance components, the
|
|
5
|
+
// conditional modes of the random effects, fitted values and the four kinds of residuals, log-likelihood and
|
|
6
|
+
// information criteria).
|
|
7
|
+
//
|
|
8
|
+
// Written for rStats.js (no ported code) from oracle/glmer-behaviour.md ("The fit and its results (stage 2c)",
|
|
9
|
+
// "Adaptive Gauss-Hermite quadrature (stage 2e)" and "rStats.js's choices") and D. Bates, M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models
|
|
10
|
+
// Using lme4", Journal of Statistical Software 67(1). The structure comes from src/models/glmerStructure.ts, the
|
|
11
|
+
// deviance at given parameters from src/models/glmerDeviance.ts and the minimiser from src/models/mixedMinimiser.ts
|
|
12
|
+
// (lmer's, with its treatment of the boundary: see the header of src/models/lmer.ts).
|
|
13
|
+
//
|
|
14
|
+
// The estimate (G6) minimises d₀(θ) (nAGQ = 0; β from the joint mode) or d₁(θ, β) (nAGQ = 1), not lme4's
|
|
15
|
+
// early-stopped values: first d₀ from the initial θ (or the start), as lme4's first phase; for nAGQ = 1 then d₁ from
|
|
16
|
+
// that θ and the β of the joint mode there (or the start); for nAGQ = K > 1 the same with the AGQ deviance D_K(θ, β)
|
|
17
|
+
// in place of d₁ (one scalar term; binomial and poisson only, G13). Each minimisation compares its local minimum with the
|
|
18
|
+
// boundary points of whole terms, as lmer's. The gradient is analytic (src/models/glmerGradient.ts: implicit
|
|
19
|
+
// differentiation through the conditional mode; oracle/glmer-behaviour.md, "The gradient (rStats.js)"), the Hessian
|
|
20
|
+
// of the Newton steps from central differences of it, with lmer's settings and glmer's safeguards of the minimiser
|
|
21
|
+
// (`robust`: failed boundary sub-problems left out, the best point of phase 1 where it fails, no stalling at the
|
|
22
|
+
// smallest trust radius). The minimisation is on X and Z with their columns divided by powers of 2 (θ' as lmer's,
|
|
23
|
+
// thetaColumnExponents; β' = 2^f β), and on β' in the metric of its approximate covariance, β' = β_s + R⁻¹ z with
|
|
24
|
+
// β_s the start and R the Cholesky factor of R_X'R_X / φ of the joint mode at the θ of nAGQ = 0, so that one step and
|
|
25
|
+
// one tolerance suit every element, whatever the scales, shifts and correlations of the predictors. An evaluation that
|
|
26
|
+
// fails (NaN, step halving that does not reduce the penalised deviance) counts as +Infinity.
|
|
27
|
+
//
|
|
28
|
+
// Before any of this, lme4's initial PIRLS (nAGQ = 0 at the structure's initial θ, from the family's starting means)
|
|
29
|
+
// is run: its errors are glmer's errors, with lme4's messages.
|
|
30
|
+
//
|
|
31
|
+
// vcov (G9): 2 [H⁻¹]_ββ with H the Hessian of d₁ (or D_K) in (θ, β) at the optimum, when lme4 uses its Hessian (nAGQ ≥ 1, the
|
|
32
|
+
// fit not singular, n < 10000, length(θ) + p < 20); H from 5-point differences of the analytic gradient (step 1e-3 of
|
|
33
|
+
// max(1, |x_j|) in the units of the minimisation), accurate to about 1e-11. Otherwise, and with R's warning when H is
|
|
34
|
+
// not positive definite, σ² (R_X'R_X)⁻¹ with the working weights at the mode.
|
|
35
|
+
//
|
|
36
|
+
// logLik for nAGQ > 1 (G12): R's is −D_K / 2, relative to the saturated model; here the saturated model's constant
|
|
37
|
+
// is added back so that it is the log-likelihood, comparable with nAGQ = 1 and with glm.
|
|
38
|
+
import { nonInteger } from "../distributions/poisson.js";
|
|
39
|
+
import { potf2, potri } from "../linalg/chol.js";
|
|
40
|
+
import { ldexp } from "../internal/summary.js";
|
|
41
|
+
import { reported, Warnings } from "../internal/warnings.js";
|
|
42
|
+
import { familyAic } from "./glmFamily.js";
|
|
43
|
+
import { pearsonResidualOf, workingResidualOf, workingWeight } from "./glmerFamily.js";
|
|
44
|
+
import { glmerAgqDeviance, glmerDeviance } from "./glmerDeviance.js";
|
|
45
|
+
import { glmerStructure } from "./glmerStructure.js";
|
|
46
|
+
import { checkLmerOptions, columnsOfTheta, thetaColumnExponents } from "./lmer.js";
|
|
47
|
+
import { LMER_SETTINGS, minimiseWithRestarts } from "./mixedMinimiser.js";
|
|
48
|
+
import { backSolve, forwardSolve } from "./mixedDeviance.js";
|
|
49
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
50
|
+
import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
|
|
51
|
+
const GLMER_KEYS = ["family", "link", "weights", "offset", "nAGQ", "start", "contrasts", "levels"];
|
|
52
|
+
const GLMER_START_KEYS = ["theta", "fixef"];
|
|
53
|
+
const GLMER_UNSUPPORTED = ["subset", "naAction", "na.action", "control", "verbose", "devFunOnly", "mustart", "etastart"];
|
|
54
|
+
const OPTIMISATION_FAILED = "glmer: the minimisation of the deviance did not converge";
|
|
55
|
+
const SINGULAR_MESSAGE = "boundary (singular) fit: see help('isSingular')";
|
|
56
|
+
export const VCOV_FALLBACK = "variance-covariance matrix computed from finite-difference Hessian is\nnot positive definite or contains NA values: falling back to var-cov estimated from RX";
|
|
57
|
+
/** The internals of every result returned by {@link glmer}, keyed by the result object itself (a copy has none) */
|
|
58
|
+
const internalsByFit = new WeakMap();
|
|
59
|
+
/** Whether an object is a result returned by {@link glmer} (internal) */
|
|
60
|
+
export function isGlmerFit(fit) {
|
|
61
|
+
return typeof fit === "object" && fit !== null && internalsByFit.has(fit);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The internals of a fit (see {@link GlmerInternals}). Internal. Throws a TypeError for an object that is not a result
|
|
65
|
+
* returned by {@link glmer}.
|
|
66
|
+
*/
|
|
67
|
+
export function glmerInternals(fit) {
|
|
68
|
+
const internals = typeof fit === "object" && fit !== null ? internalsByFit.get(fit) : undefined;
|
|
69
|
+
if (internals === undefined)
|
|
70
|
+
throw new TypeError("fit must be a result returned by glmer (not a copy of one)");
|
|
71
|
+
return internals;
|
|
72
|
+
}
|
|
73
|
+
/** Step of the 5-point differences of the analytic gradient that give the Hessian of vcov, relative to max(1, |x_j|) */
|
|
74
|
+
const VCOV_HESSIAN_STEP = 1e-3;
|
|
75
|
+
/**
|
|
76
|
+
* The minimiser's settings for glmer's analytic gradient: lmer's, except that an element held at 0 is released only
|
|
77
|
+
* for a derivative above 1e-10 max(1, |deviance|) (the gradient at the exact mode is accurate to about 1e-12 of the
|
|
78
|
+
* deviance, a little less than lmer's)
|
|
79
|
+
*/
|
|
80
|
+
const GLMER_SETTINGS = { ...LMER_SETTINGS, releaseTolerance: 1e-10 };
|
|
81
|
+
/** lme4's thresholds for its use of the Hessian (and for the singular message) */
|
|
82
|
+
const HESSIAN_MAX_N = 10000;
|
|
83
|
+
const HESSIAN_MAX_PARAMETERS = 20;
|
|
84
|
+
/** The inverse of a small symmetric positive definite matrix (array of rows), or undefined if it is not (Cholesky) */
|
|
85
|
+
function spdInverse(a) {
|
|
86
|
+
const m = a.length;
|
|
87
|
+
const data = new Float64Array(m * m);
|
|
88
|
+
for (let j = 0; j < m; j++)
|
|
89
|
+
for (let i = 0; i < m; i++)
|
|
90
|
+
data[i + j * m] = a[i][j];
|
|
91
|
+
if (data.some((v) => !Number.isFinite(v)))
|
|
92
|
+
return undefined;
|
|
93
|
+
if (potf2({ nrow: m, ncol: m, data }) > 0)
|
|
94
|
+
return undefined;
|
|
95
|
+
potri({ nrow: m, ncol: m, data });
|
|
96
|
+
return Array.from({ length: m }, (_, i) => Array.from({ length: m }, (_, j) => (i <= j ? data[i + j * m] : data[j + i * m])));
|
|
97
|
+
}
|
|
98
|
+
/** A number array option (start's theta or fixef) as numbers, with a TypeError for anything else */
|
|
99
|
+
function numbersOption(value, name) {
|
|
100
|
+
if (value === undefined)
|
|
101
|
+
return undefined;
|
|
102
|
+
if (!Array.isArray(value) && !(value instanceof Float64Array))
|
|
103
|
+
throw new TypeError(`start.${name} must be an array of numbers`);
|
|
104
|
+
const out = Array.from(value, (v) => {
|
|
105
|
+
if (typeof v !== "number" || !Number.isFinite(v))
|
|
106
|
+
throw new TypeError(`start.${name} must be an array of finite numbers`);
|
|
107
|
+
return v;
|
|
108
|
+
});
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
/** The exponent of 2 of the largest |value| of each column of X (0 for a column of zeros) */
|
|
112
|
+
function columnExponents(x, p) {
|
|
113
|
+
return Array.from({ length: p }, (_, k) => {
|
|
114
|
+
let top = 0;
|
|
115
|
+
for (const row of x)
|
|
116
|
+
top = Math.max(top, Math.abs(row[k]));
|
|
117
|
+
return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The structure with the columns of Z divided by 2^e (thetaColumnExponents) and those of X by 2^f (exact), with its
|
|
122
|
+
* own sparse system
|
|
123
|
+
*/
|
|
124
|
+
function scaledStructure(s, ez, ex) {
|
|
125
|
+
if (ez.every((v) => v === 0) && ex.every((v) => v === 0))
|
|
126
|
+
return s;
|
|
127
|
+
return {
|
|
128
|
+
...s,
|
|
129
|
+
x: s.x.map((row) => row.map((v, k) => ldexp(v, -ex[k]))),
|
|
130
|
+
z: s.z.map((col, j) => ({ rows: col.rows, values: col.values.map((v) => ldexp(v, -ez[j])) })),
|
|
131
|
+
terms: s.terms.map((t) => ({ ...t, matrix: t.matrix.map((row) => row.map((v, i) => ldexp(v, -ez[t.zOffset + i]))) })),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The upper-triangular Cholesky factor R (column-major) of M / φ, M = R_X'R_X: the metric of the fixed effects in the
|
|
136
|
+
* minimisation. Where M is not positive definite (to rounding), the diagonal of the square roots of its diagonal
|
|
137
|
+
* (1 where that is not positive).
|
|
138
|
+
*/
|
|
139
|
+
function metricFactor(m, phi) {
|
|
140
|
+
const p = m.length;
|
|
141
|
+
const data = new Float64Array(p * p);
|
|
142
|
+
for (let j = 0; j < p; j++)
|
|
143
|
+
for (let i = 0; i < p; i++)
|
|
144
|
+
data[i + j * p] = m[i][j] / phi;
|
|
145
|
+
if (data.every(Number.isFinite) && (p === 0 || potf2({ nrow: p, ncol: p, data }) === 0)) {
|
|
146
|
+
for (let j = 0; j < p; j++)
|
|
147
|
+
for (let i = j + 1; i < p; i++)
|
|
148
|
+
data[i + j * p] = 0;
|
|
149
|
+
return data;
|
|
150
|
+
}
|
|
151
|
+
data.fill(0);
|
|
152
|
+
for (let k = 0; k < p; k++) {
|
|
153
|
+
const v = Math.sqrt(m[k][k] / phi);
|
|
154
|
+
data[k + k * p] = Number.isFinite(v) && v > 0 ? v : 1;
|
|
155
|
+
}
|
|
156
|
+
return data;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Fit a generalized linear mixed model by the Laplace approximation (`nAGQ = 1`, default), by adaptive Gauss-Hermite
|
|
160
|
+
* quadrature (`nAGQ` from 2 to 100) or with the fixed effects from the penalised IRLS (`nAGQ = 0`). Equivalent to `lme4::glmer()` in R. With the quantities of its methods:
|
|
161
|
+
* `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`, `ranef()`, `fitted()`,
|
|
162
|
+
* `predict()`, `residuals()` of the four types, `deviance()`, `logLik()`, `AIC()`, `BIC()` and `isSingular()`.
|
|
163
|
+
*
|
|
164
|
+
* The families are binomial, poisson, Gamma, inverse.gaussian and gaussian (not with the identity link: that is
|
|
165
|
+
* {@link lmer}), with the links of {@link glm} and lme4's own inverse links and variance functions. The formula is
|
|
166
|
+
* as in {@link lmer}; a binomial response may be 0/1 values, booleans, strings or a factor (the first level failure),
|
|
167
|
+
* proportions with the numbers of trials as `weights`, or `cbind(successes, failures)` with two column names on the
|
|
168
|
+
* left-hand side.
|
|
169
|
+
*
|
|
170
|
+
* The estimate is the exact minimiser of the Laplace deviance computed at the exact conditional mode of the random
|
|
171
|
+
* effects (lme4's optimiser and its penalised IRLS stop early, so lme4's values typically differ in the 4th to 6th
|
|
172
|
+
* significant digit, its standard errors by up to about 1%). Elements of θ on the boundary are exactly 0, and the fit
|
|
173
|
+
* is then singular. lme4's warnings about its optimiser and its convergence checks are not given.
|
|
174
|
+
*
|
|
175
|
+
* The scale of the response: lme4's Laplace criterion leaves out the dispersion, so for the poisson,
|
|
176
|
+
* inverse.gaussian and gaussian families it is not invariant to the scale of the response (or of the prior weights).
|
|
177
|
+
* Where the information about the random effects at the start, Σ W z² of a column of Z (W the working weights at
|
|
178
|
+
* the starting means), is above 2^40 (the penalised system then loses about 40 of its 53 bits), or below 2^-40 and
|
|
179
|
+
* the fit fails or a term ends at θ = 0 on a criterion flat to rounding, the result is a RangeError saying so. For
|
|
180
|
+
* data like the example below: poisson counts up to about 1e11 (prior weights up to about 2^34), inverse.gaussian
|
|
181
|
+
* with the log link up to about 1e13, gaussian with the log link from about 1e-6 to 5e4 fit; beyond, the RangeError.
|
|
182
|
+
* Gamma fits are not limited by the scale of the response (its criterion is invariant; with the log link a tiny
|
|
183
|
+
* response is rescaled).
|
|
184
|
+
*
|
|
185
|
+
* Adaptive Gauss-Hermite quadrature (`nAGQ > 1`) needs a single scalar random-effects term such as `(1 | g)`, with
|
|
186
|
+
* R's errors otherwise. It is offered for binomial and poisson only: for Gamma, inverse.gaussian and gaussian it is a
|
|
187
|
+
* RangeError, since lme4 holds the dispersion at 1 there, so that its estimates would not be maximum likelihood. Its
|
|
188
|
+
* `logLik`, `AIC` and `BIC` are those of the log-likelihood, unlike R's, which leave out the constant of the
|
|
189
|
+
* saturated model (`aic − Σ` deviance residuals) for nAGQ > 1: they differ from R's by that constant and are
|
|
190
|
+
* comparable with the Laplace fit's.
|
|
191
|
+
*
|
|
192
|
+
* @param formula A formula such as `"cbind(inc, notinc) ~ period + (1 | herd)"` or `"y ~ x + (1 | g)"`.
|
|
193
|
+
* @param data The data frame: an object of columns.
|
|
194
|
+
* @param options `family`, `link`, `weights`, `offset`, `nAGQ`, `start`, and `contrasts` and `levels` as in
|
|
195
|
+
* {@link lmer} (see {@link GlmerOptions} for the keys accepted).
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* ```ts
|
|
199
|
+
* // R: lme4::glmer(y ~ x + (1 | g), data, family = poisson)
|
|
200
|
+
* const fit = glmer("y ~ x + (1 | g)", {
|
|
201
|
+
* y: [2, 3, 6, 7, 8, 1, 0, 3, 2, 5, 4, 6, 9, 8, 13, 0, 2, 1, 4, 3],
|
|
202
|
+
* x: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
|
|
203
|
+
* g: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d"],
|
|
204
|
+
* }, { family: "poisson" });
|
|
205
|
+
* fit.fixef; // [0.2512, 0.3242]
|
|
206
|
+
* fit.coefTable.stdError; // [0.4183, 0.08098]
|
|
207
|
+
* fit.varCorr[0].sd; // [0.5423]
|
|
208
|
+
* fit.ranef[0].values; // [[0.2840], [-0.4170], [0.6920], [-0.4819]]
|
|
209
|
+
* fit.logLik; // -39.392
|
|
210
|
+
* ```
|
|
211
|
+
*
|
|
212
|
+
* @category Mixed models
|
|
213
|
+
*/
|
|
214
|
+
export function glmer(formula, data, options) {
|
|
215
|
+
checkLmerOptions("glmer", options, GLMER_UNSUPPORTED);
|
|
216
|
+
checkOptions(options, GLMER_KEYS, "glmer"); // generated: option-keys.mjs
|
|
217
|
+
checkOptions(nestedOptions(options, "start"), GLMER_START_KEYS, "glmer", "start"); // generated: option-keys.mjs
|
|
218
|
+
return reported("glmer", fitGlmer(formula, data, options ?? {}));
|
|
219
|
+
}
|
|
220
|
+
function fitGlmer(formula, data, options) {
|
|
221
|
+
const { family, link, weights, offset, nAGQ: nAGQgiven, contrasts, levels } = options;
|
|
222
|
+
const s = glmerStructure(formula, data, {
|
|
223
|
+
...(family === undefined ? {} : { family }),
|
|
224
|
+
...(link === undefined ? {} : { link }),
|
|
225
|
+
...(weights === undefined ? {} : { weights }),
|
|
226
|
+
...(offset === undefined ? {} : { offset }),
|
|
227
|
+
...(nAGQgiven === undefined ? {} : { nAGQ: nAGQgiven }),
|
|
228
|
+
...(contrasts === undefined ? {} : { contrasts }),
|
|
229
|
+
...(levels === undefined ? {} : { levels }),
|
|
230
|
+
});
|
|
231
|
+
const nAGQ = s.nAGQ;
|
|
232
|
+
if (nAGQ > 1 && s.family.family !== "binomial" && s.family.family !== "poisson") {
|
|
233
|
+
// (G13: R fits these, but its AGQ deviance holds the dispersion at 1, so its estimates are not maximum likelihood)
|
|
234
|
+
throw new RangeError(`glmer: nAGQ > 1 is not available for the ${s.family.family} family (lme4 holds the dispersion at 1 there, so its estimates would not be maximum likelihood)`);
|
|
235
|
+
}
|
|
236
|
+
const n = s.y.length;
|
|
237
|
+
const p = s.xColNames.length;
|
|
238
|
+
const nTheta = s.theta.length;
|
|
239
|
+
// Non-integer poisson counts: R's dpois is 0 there, so the aic term is +Infinity and the Laplace deviance infinite
|
|
240
|
+
// at every θ and β (R warns "non-integer x = ..." at each evaluation and returns its starting values with logLik
|
|
241
|
+
// −Inf): no estimate (rule 1). The quadrature deviance (nAGQ > 1) leaves the aic term out: R's estimates, with
|
|
242
|
+
// R's warning and the log-likelihood −Inf (G12)
|
|
243
|
+
const nonIntegerCount = s.family.family === "poisson" ? s.y.find((v, i) => s.weights[i] > 0 && nonInteger(v)) : undefined;
|
|
244
|
+
if (nonIntegerCount !== undefined && nAGQ <= 1) {
|
|
245
|
+
throw new RangeError(`glmer: the poisson response has a non-integer count (${nonIntegerCount}), where the log-likelihood is -Inf for every parameter: no estimate (R warns "non-integer x = ${nonIntegerCount.toFixed(6)}" and returns its starting values)`);
|
|
246
|
+
}
|
|
247
|
+
// the computation is on X and Z with their columns divided by powers of 2 (exact; the same model): θ' = 2^e θ as
|
|
248
|
+
// lmer's (thetaColumnExponents) and β' = 2^f β, so that the steps and tolerances suit predictors of any scale and
|
|
249
|
+
// no cross-product of X or Z overflows (a predictor times 1e160 made X'WX overflow, times 1e-160 the vcov)
|
|
250
|
+
const exponents = thetaColumnExponents(s);
|
|
251
|
+
const xExponents = columnExponents(s.x, p);
|
|
252
|
+
// a Gamma response with the log link below 2^-40 is fitted divided by 2^ky (see responseExponent): the same model
|
|
253
|
+
// with the offset shifted by −ky log 2, so that θ, β and b are those of the response as given
|
|
254
|
+
const ky = responseExponent(s);
|
|
255
|
+
const sy = ky === 0
|
|
256
|
+
? s
|
|
257
|
+
: { ...s, y: s.y.map((v) => ldexp(v, -ky)), mustart: s.mustart.map((v) => ldexp(v, -ky)), offset: s.offset.map((o) => o - ky * Math.LN2) };
|
|
258
|
+
const sc = scaledStructure(sy, exponents.z, xExponents);
|
|
259
|
+
const toScaled = (theta) => theta.map((v, k) => ldexp(v, exponents.theta[k]));
|
|
260
|
+
const fromScaled = (theta) => theta.map((v, k) => ldexp(v, -exponents.theta[k]));
|
|
261
|
+
// The scale of the response against the Laplace criterion (G21): the information about the random effects at the
|
|
262
|
+
// start, Σ W z² of the largest column of Z (startInformation). Above 2^40 it is an error at once: Λ'Z'WZΛ + I and
|
|
263
|
+
// the fixed effects' system then lose about log2 of it of their 53 bits, so that the criterion is resolved to
|
|
264
|
+
// 1e-4 or worse and whether the minimisation converges depends on the last bits of the platform's arithmetic
|
|
265
|
+
// (prior weights 2^40 fitted on Linux x86_64 and failed on arm64; the θ of weights 2^38 differed at 1e-6). Below
|
|
266
|
+
// 2^-40 it is checked where the fit fails or ends at θ = 0 (θ' far from 1 may still be resolved there)
|
|
267
|
+
const information = startInformation(sc);
|
|
268
|
+
const scaleError = () => new RangeError(`glmer: the scale of the response (or of the prior weights) is outside what the Laplace criterion can resolve: the information about the random effects at the start is ${information} (about 2^-40 to 2^40 is supported; lme4's Laplace criterion leaves out the dispersion, so for poisson, inverse.gaussian and gaussian it is not invariant to the scale of the response)`);
|
|
269
|
+
if (information > MAX_INFORMATION)
|
|
270
|
+
throw scaleError();
|
|
271
|
+
const fit = () => {
|
|
272
|
+
// lme4's initial PIRLS (nAGQ = 0 at the initial θ, from the starting means): its errors are glmer's. Where it fails
|
|
273
|
+
// on columns of Z of extreme scale (θ = 1 for a column of 1e160 overflows), the minimisation starts from θ' = 1
|
|
274
|
+
// instead (θ = 1 in the units of the scaled columns, as lmer's), if the PIRLS succeeds there
|
|
275
|
+
let initialTheta = toScaled(s.theta);
|
|
276
|
+
try {
|
|
277
|
+
glmerDeviance(sc, initialTheta, undefined, 0);
|
|
278
|
+
}
|
|
279
|
+
catch (e) {
|
|
280
|
+
if (exponents.theta.every((v) => v === 0))
|
|
281
|
+
throw e;
|
|
282
|
+
try {
|
|
283
|
+
glmerDeviance(sc, s.theta, undefined, 0);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
throw e;
|
|
287
|
+
}
|
|
288
|
+
initialTheta = [...s.theta];
|
|
289
|
+
}
|
|
290
|
+
// the start, with R's errors in R's order (checked in R: the names first, then θ's length and bounds, then β's
|
|
291
|
+
// length)
|
|
292
|
+
const start = options.start;
|
|
293
|
+
if (start !== undefined && (typeof start !== "object" || start === null || Array.isArray(start))) {
|
|
294
|
+
throw new TypeError("start must be an object with theta and fixef");
|
|
295
|
+
}
|
|
296
|
+
const startTheta = numbersOption(start?.theta, "theta");
|
|
297
|
+
const startFixef = numbersOption(start?.fixef, "fixef");
|
|
298
|
+
if (nAGQ === 0 && startFixef !== undefined)
|
|
299
|
+
throw new RangeError(`'start' has invalid names "fixef"`);
|
|
300
|
+
if (startTheta !== undefined && startTheta.length !== nTheta)
|
|
301
|
+
throw new RangeError(`starting value of 'par' has length not equal to ${nTheta}`);
|
|
302
|
+
if (startTheta?.some((v, j) => s.lower[j] === 0 && v < 0))
|
|
303
|
+
throw new RangeError("Starting values violate bounds");
|
|
304
|
+
if (startFixef !== undefined && startFixef.length !== p)
|
|
305
|
+
throw new RangeError(`starting value of 'fixef' has length not equal to ${p}`);
|
|
306
|
+
const diagonal = s.lower.map((b) => b === 0);
|
|
307
|
+
const columns = columnsOfTheta(s);
|
|
308
|
+
const blocks = s.terms.map((t) => {
|
|
309
|
+
const nc = t.columns.length;
|
|
310
|
+
return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
|
|
311
|
+
});
|
|
312
|
+
/** The deviance and its gradient, undefined where the evaluation fails */
|
|
313
|
+
const safely = (evaluate) => {
|
|
314
|
+
try {
|
|
315
|
+
const r = evaluate();
|
|
316
|
+
return Number.isFinite(r.deviance) && r.gradient.every(Number.isFinite) ? r : undefined;
|
|
317
|
+
}
|
|
318
|
+
catch (e) {
|
|
319
|
+
// (glmerDeviance's failures: lme4's PIRLS errors, plain Errors, and RangeErrors; anything else is a bug)
|
|
320
|
+
if (e instanceof RangeError || (e instanceof Error && e.constructor === Error))
|
|
321
|
+
return undefined;
|
|
322
|
+
throw e;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
/** The minimisation problem of a deviance of x (θ' first) with its analytic gradient */
|
|
326
|
+
const problemOf = (f, m) => ({
|
|
327
|
+
evaluate: (x) => {
|
|
328
|
+
const r = safely(() => f(x));
|
|
329
|
+
return r === undefined ? { f: Infinity, g: new Array(m).fill(NaN) } : { f: r.deviance, g: r.gradient };
|
|
330
|
+
},
|
|
331
|
+
diagonal: [...diagonal, ...new Array(m - nTheta).fill(false)],
|
|
332
|
+
columns,
|
|
333
|
+
settings: GLMER_SETTINGS,
|
|
334
|
+
rejectNonFinite: true,
|
|
335
|
+
failure: OPTIMISATION_FAILED,
|
|
336
|
+
robust: true,
|
|
337
|
+
});
|
|
338
|
+
// nAGQ = 0: d₀(θ). For nAGQ ≥ 1 it only gives the start of d₁: where it fails (its region of evaluation may end
|
|
339
|
+
// before its minimum), its best point is the start
|
|
340
|
+
const d0 = (x) => {
|
|
341
|
+
const r = glmerDeviance(sc, x, undefined, 0, { gradient: true });
|
|
342
|
+
return { deviance: r.deviance, gradient: r.gradient };
|
|
343
|
+
};
|
|
344
|
+
const thetaStart = startTheta === undefined ? initialTheta : toScaled(startTheta);
|
|
345
|
+
// (non-integer counts with nAGQ > 1: d₀ is infinite everywhere, so the start, as R's first phase ends there)
|
|
346
|
+
const theta0 = nonIntegerCount !== undefined ? thetaStart : minimiseWithRestarts(problemOf(d0, nTheta), thetaStart, blocks, { bestOnFailure: nAGQ >= 1 }).theta;
|
|
347
|
+
let thetaScaled = theta0;
|
|
348
|
+
let betaScaled;
|
|
349
|
+
let vcovHessian;
|
|
350
|
+
if (nAGQ >= 1) {
|
|
351
|
+
// β' = β_s + R⁻¹ z, R the Cholesky factor of R_X'R_X / φ of the joint mode at θ₀ (φ the dispersion of the aic
|
|
352
|
+
// term, Σ d_i / Σ w, which sets the curvature of the deviance in β; not lme4's sigma², which includes ‖u‖²): z
|
|
353
|
+
// is β' in the metric of its approximate covariance, so that one step and one tolerance suit every element,
|
|
354
|
+
// whatever the scales and the correlations of the predictors (shifting x by 2000 made the intercept and the
|
|
355
|
+
// slope correlated by −1 and the minimisation crawl)
|
|
356
|
+
const r0 = glmerDeviance(sc, theta0, undefined, 0, { rx: true });
|
|
357
|
+
const betaStart = startFixef?.map((b, k) => ldexp(b, xExponents[k])) ?? r0.beta;
|
|
358
|
+
const phi = s.family.family === "binomial" || s.family.family === "poisson" ? 1 : r0.devResid / s.weights.reduce((a, b) => a + b, 0);
|
|
359
|
+
const rFactor = metricFactor(r0.rxtrx, phi);
|
|
360
|
+
const betaOf = (x) => {
|
|
361
|
+
const z = Float64Array.from(x.slice(nTheta));
|
|
362
|
+
backSolve(rFactor, p, z);
|
|
363
|
+
return betaStart.map((b, k) => b + z[k]);
|
|
364
|
+
};
|
|
365
|
+
// d₁(θ, β), or the AGQ deviance D_K(θ, β) for nAGQ = K > 1, with the gradient in z = R (β' − β_s)
|
|
366
|
+
const d1 = (x) => {
|
|
367
|
+
const theta = x.slice(0, nTheta);
|
|
368
|
+
const r = nAGQ === 1 ? glmerDeviance(sc, theta, betaOf(x), 1, { gradient: true }) : glmerAgqDeviance(sc, theta, betaOf(x), nAGQ, { gradient: true });
|
|
369
|
+
const g = r.gradient;
|
|
370
|
+
const gz = Float64Array.from(g.slice(nTheta));
|
|
371
|
+
forwardSolve(rFactor, p, gz);
|
|
372
|
+
return { deviance: r.deviance, gradient: [...g.slice(0, nTheta), ...gz] };
|
|
373
|
+
};
|
|
374
|
+
const best = minimiseWithRestarts(problemOf(d1, nTheta + p), [...theta0, ...new Array(p).fill(0)], blocks).theta;
|
|
375
|
+
thetaScaled = best.slice(0, nTheta);
|
|
376
|
+
betaScaled = betaOf(best);
|
|
377
|
+
// the Hessian of vcov in (θ', z) from 5-point differences of the analytic gradient, then 2 [H⁻¹]_ββ' =
|
|
378
|
+
// 2 R⁻¹ [H⁻¹]_zz R⁻ᵀ (the scaling of θ does not enter); in the units of β'
|
|
379
|
+
vcovHessian = () => {
|
|
380
|
+
const cols = best.map((_, j) => {
|
|
381
|
+
const h = VCOV_HESSIAN_STEP * Math.max(1, Math.abs(best[j]));
|
|
382
|
+
const g = (d) => {
|
|
383
|
+
const y = best.slice();
|
|
384
|
+
y[j] = best[j] + d;
|
|
385
|
+
return safely(() => d1(y))?.gradient ?? new Array(best.length).fill(NaN);
|
|
386
|
+
};
|
|
387
|
+
const gp1 = g(h);
|
|
388
|
+
const gm1 = g(-h);
|
|
389
|
+
const gp2 = g(2 * h);
|
|
390
|
+
const gm2 = g(-2 * h);
|
|
391
|
+
return gp1.map((_, i) => (8 * (gp1[i] - gm1[i]) - (gp2[i] - gm2[i])) / (12 * h));
|
|
392
|
+
});
|
|
393
|
+
const hz = cols.map((col, a) => col.map((v, b) => (v + cols[b][a]) / 2));
|
|
394
|
+
const inverse = spdInverse(hz);
|
|
395
|
+
if (inverse === undefined)
|
|
396
|
+
return undefined;
|
|
397
|
+
const rInverse = Array.from({ length: p }, (_, k) => {
|
|
398
|
+
const e = new Float64Array(p);
|
|
399
|
+
e[k] = 1;
|
|
400
|
+
backSolve(rFactor, p, e);
|
|
401
|
+
return e; // column k of R⁻¹
|
|
402
|
+
});
|
|
403
|
+
// R⁻¹ M R⁻ᵀ: entry (a, b) = Σ_cd R⁻¹[a, c] M[c, d] R⁻¹[b, d]
|
|
404
|
+
return Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => {
|
|
405
|
+
let sum = 0;
|
|
406
|
+
for (let c = 0; c < p; c++) {
|
|
407
|
+
const rac = rInverse[c][a];
|
|
408
|
+
if (rac === 0)
|
|
409
|
+
continue;
|
|
410
|
+
for (let d = 0; d < p; d++)
|
|
411
|
+
sum += rac * inverse[nTheta + c][nTheta + d] * rInverse[d][b];
|
|
412
|
+
}
|
|
413
|
+
return 2 * sum;
|
|
414
|
+
}));
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
// the fit at the estimate (on the scaled structure; β, b and R_X'R_X back in the given units)
|
|
418
|
+
const theta = fromScaled(thetaScaled).map((v) => (v === 0 ? 0 : v));
|
|
419
|
+
const r = nAGQ > 1 ? glmerAgqDeviance(sc, thetaScaled, betaScaled, nAGQ, { rx: true }) : glmerDeviance(sc, thetaScaled, betaScaled, nAGQ === 0 ? 0 : 1, { rx: true });
|
|
420
|
+
const fixef = r.beta.map((b, k) => ldexp(b, -xExponents[k]));
|
|
421
|
+
const bFit = r.b.map((v, j) => ldexp(v, -exponents.z[j]));
|
|
422
|
+
const fam = s.family;
|
|
423
|
+
const { y, weights: w } = s;
|
|
424
|
+
// (the means and the linear predictor of the response as given: 2^ky μ, η + ky log 2)
|
|
425
|
+
const mu = ky === 0 ? r.mu : r.mu.map((m) => ldexp(m, ky));
|
|
426
|
+
const eta = ky === 0 ? r.eta : r.eta.map((e) => e + ky * Math.LN2);
|
|
427
|
+
const devResid = y.map((yi, i) => fam.devResid(yi, mu[i], w[i]));
|
|
428
|
+
const residuals = devResid.map((d, i) => {
|
|
429
|
+
const v = Math.sqrt(Math.max(0, d));
|
|
430
|
+
return v === 0 ? 0 : y[i] > mu[i] ? v : -v;
|
|
431
|
+
});
|
|
432
|
+
const pearsonResiduals = y.map((yi, i) => pearsonResidualOf(fam, w[i], yi, mu[i]));
|
|
433
|
+
const workingResiduals = y.map((yi, i) => workingResidualOf(fam, yi, eta[i], mu[i]));
|
|
434
|
+
const responseResiduals = y.map((yi, i) => yi - mu[i]);
|
|
435
|
+
const deviance = devResid.reduce((sum, d) => sum + Math.max(0, d), 0);
|
|
436
|
+
const dispersionFamily = fam.family !== "binomial" && fam.family !== "poisson";
|
|
437
|
+
const sigma = dispersionFamily ? Math.sqrt(dispersionOf(sy, r)) : 1;
|
|
438
|
+
// (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4)
|
|
439
|
+
const singular = theta.some((v, j) => s.lower[j] === 0 && v < 1e-4);
|
|
440
|
+
const nParameters = nTheta + (nAGQ >= 1 ? p : 0);
|
|
441
|
+
// (lme4 gives the singular message from its convergence checks, which it runs only for these sizes)
|
|
442
|
+
const checked = n < HESSIAN_MAX_N && nParameters < HESSIAN_MAX_PARAMETERS;
|
|
443
|
+
const messages = [...s.messages];
|
|
444
|
+
if (singular && checked)
|
|
445
|
+
messages.push(SINGULAR_MESSAGE);
|
|
446
|
+
const warnings = new Warnings();
|
|
447
|
+
for (const m of s.warnings)
|
|
448
|
+
warnings.add(m);
|
|
449
|
+
for (const m of r.warnings)
|
|
450
|
+
warnings.add(m);
|
|
451
|
+
// vcov in the units of β' (then each entry times 2^(−f_a − f_b), the standard errors 2^(−f_k) times the root of the
|
|
452
|
+
// diagonal: an entry may overflow where the standard error does not)
|
|
453
|
+
let vcovScaled;
|
|
454
|
+
let vcovFrom = "RX";
|
|
455
|
+
if (vcovHessian !== undefined && !singular && n < HESSIAN_MAX_N && nTheta + p < HESSIAN_MAX_PARAMETERS) {
|
|
456
|
+
vcovScaled = vcovHessian();
|
|
457
|
+
if (vcovScaled === undefined)
|
|
458
|
+
warnings.add(VCOV_FALLBACK);
|
|
459
|
+
else
|
|
460
|
+
vcovFrom = "hessian";
|
|
461
|
+
}
|
|
462
|
+
if (vcovScaled === undefined) {
|
|
463
|
+
const inverse = spdInverse(r.rxtrx);
|
|
464
|
+
vcovScaled = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => sigma * sigma * (inverse?.[a][b] ?? NaN)));
|
|
465
|
+
}
|
|
466
|
+
const vcov = vcovScaled.map((row, a) => row.map((v, b) => ldexp(v, -xExponents[a] - xExponents[b])));
|
|
467
|
+
const stdError = vcovScaled.map((row, i) => ldexp(Math.sqrt(row[i]), -xExponents[i]));
|
|
468
|
+
// (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
|
|
469
|
+
const zValue = fixef.map((b, i) => b / stdError[i]);
|
|
470
|
+
const rxtrx = r.rxtrx.map((row, a) => row.map((v, b) => ldexp(v, xExponents[a] + xExponents[b])));
|
|
471
|
+
// the blocks T_k and the variance components (not scaled by sigma, as lme4's VarCorr for glmer), from the blocks of
|
|
472
|
+
// θ' (cov = C⁻¹ T'T'ᵀ C⁻¹ with C the powers of 2 of the term's columns: no overflow of the squares of θ)
|
|
473
|
+
const thetaFit = thetaScaled.map((v) => (v === 0 ? 0 : v));
|
|
474
|
+
const varCorr = s.terms.map((term) => {
|
|
475
|
+
const nc = term.columns.length;
|
|
476
|
+
const t = Array.from({ length: nc }, () => new Array(nc).fill(0));
|
|
477
|
+
let k = term.thetaOffset;
|
|
478
|
+
for (let j = 0; j < nc; j++)
|
|
479
|
+
for (let i = j; i < nc; i++)
|
|
480
|
+
t[i][j] = thetaFit[k++];
|
|
481
|
+
const e = Array.from({ length: nc }, (_, i) => exponents.z[term.zOffset + i]);
|
|
482
|
+
const cov = t.map((ti) => t.map((tj) => ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
|
|
483
|
+
const sdScaled = cov.map((row, i) => Math.sqrt(row[i]));
|
|
484
|
+
const sd = sdScaled.map((v, i) => ldexp(v, -e[i]));
|
|
485
|
+
// (a column with variance 0 has the correlations 0/0 = NaN with the others, as lme4's VarCorr: not a bug)
|
|
486
|
+
const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sdScaled[i] * sdScaled[j]))));
|
|
487
|
+
return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
|
|
488
|
+
});
|
|
489
|
+
const ranef = s.groups.map((g, gi) => {
|
|
490
|
+
const terms = s.terms.filter((t) => t.group === gi);
|
|
491
|
+
return {
|
|
492
|
+
group: g.name,
|
|
493
|
+
levels: [...g.levels],
|
|
494
|
+
columns: terms.flatMap((t) => t.columns),
|
|
495
|
+
values: g.levels.map((_, l) => terms.flatMap((t) => {
|
|
496
|
+
const nc = t.columns.length;
|
|
497
|
+
return t.columns.map((_, j) => bFit[t.zOffset + l * nc + j]);
|
|
498
|
+
})),
|
|
499
|
+
};
|
|
500
|
+
});
|
|
501
|
+
// nAGQ > 1 (binomial and poisson only, G13): the AGQ deviance has no aic term, so R's logLik is relative to the
|
|
502
|
+
// saturated model; here the saturated model's constant aic − Σ d_i (which does not depend on μ for these families)
|
|
503
|
+
// is added back, so that logLik is the log-likelihood (G12; R's logLik differs by it)
|
|
504
|
+
// (+ 0: a deviance of 0, binomial weights so small that the aic term is 0, gives logLik 0, as R prints, not −0)
|
|
505
|
+
// (a response divided by 2^ky: the aic term of the response as given; the rest of the deviance does not change)
|
|
506
|
+
const fitDeviance = ky === 0 ? r.deviance : r.ldL2 + r.ussq + familyAic(fam.glm, y, mu, w, s.size, r.devResid, new Warnings());
|
|
507
|
+
const logLik = -(fitDeviance + (nAGQ > 1 ? r.aic - r.devResid : 0)) / 2 + 0;
|
|
508
|
+
const df = p + nTheta + (dispersionFamily ? 1 : 0);
|
|
509
|
+
const result = {
|
|
510
|
+
formula,
|
|
511
|
+
family: fam.family,
|
|
512
|
+
link: fam.link,
|
|
513
|
+
nAGQ,
|
|
514
|
+
nObs: n,
|
|
515
|
+
rows: [...s.rows],
|
|
516
|
+
theta,
|
|
517
|
+
fixefNames: [...s.xColNames],
|
|
518
|
+
fixef,
|
|
519
|
+
coefTable: { estimate: [...fixef], stdError, zValue },
|
|
520
|
+
vcov,
|
|
521
|
+
vcovFrom,
|
|
522
|
+
sigma,
|
|
523
|
+
varCorr,
|
|
524
|
+
ranef,
|
|
525
|
+
fitted: mu,
|
|
526
|
+
linearPredictor: eta,
|
|
527
|
+
residuals,
|
|
528
|
+
pearsonResiduals,
|
|
529
|
+
workingResiduals,
|
|
530
|
+
responseResiduals,
|
|
531
|
+
deviance,
|
|
532
|
+
logLik,
|
|
533
|
+
df,
|
|
534
|
+
AIC: -2 * logLik + 2 * df,
|
|
535
|
+
BIC: -2 * logLik + Math.log(n) * df,
|
|
536
|
+
singular,
|
|
537
|
+
messages,
|
|
538
|
+
warnings: warnings.list,
|
|
539
|
+
};
|
|
540
|
+
const copyOf = (v) => (Array.isArray(v) || v instanceof Float64Array ? v.slice() : v);
|
|
541
|
+
const given = { ...options };
|
|
542
|
+
if (options.weights !== undefined)
|
|
543
|
+
given.weights = copyOf(options.weights);
|
|
544
|
+
if (options.offset !== undefined)
|
|
545
|
+
given.offset = copyOf(options.offset);
|
|
546
|
+
const snapshot = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.slice()]));
|
|
547
|
+
internalsByFit.set(result, { structure: s, data, snapshot, options: given, theta: [...theta],
|
|
548
|
+
beta: [...fixef],
|
|
549
|
+
rxtrx,
|
|
550
|
+
b: [...bFit],
|
|
551
|
+
eta: [...eta],
|
|
552
|
+
mu: [...mu],
|
|
553
|
+
sigma,
|
|
554
|
+
});
|
|
555
|
+
return result;
|
|
556
|
+
};
|
|
557
|
+
let result;
|
|
558
|
+
try {
|
|
559
|
+
result = fit();
|
|
560
|
+
}
|
|
561
|
+
catch (e) {
|
|
562
|
+
// (a failure of the penalised IRLS or of the minimisation where the information is extreme: lme4's messages, or
|
|
563
|
+
// "did not converge", would blame the algorithm)
|
|
564
|
+
if (e instanceof Error && e.constructor === Error && !(information >= MIN_INFORMATION))
|
|
565
|
+
throw scaleError();
|
|
566
|
+
throw e;
|
|
567
|
+
}
|
|
568
|
+
// A term at θ = 0 where the criterion is flat to rounding in θ (θ'² Σ W z² below 1e-10 of the deviance at θ' = 1:
|
|
569
|
+
// inverse.gaussian with the log link and responses of 1e200, whose optimum is near θ = 1e100) is not an estimate
|
|
570
|
+
const criterion = -2 * result.logLik;
|
|
571
|
+
if (result.theta.some((v, j) => v === 0 && s.lower[j] === 0) && Number.isFinite(criterion) && information < FLAT_INFORMATION * Math.abs(criterion)) {
|
|
572
|
+
throw scaleError();
|
|
573
|
+
}
|
|
574
|
+
return result;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* The largest information of a column of Z about its random effect at the start, Σ_i W_i z_ij² over the rows of the
|
|
578
|
+
* column (Z scaled as in the fit, so that θ' = 1 is the start of the minimisation; W the working weights at the
|
|
579
|
+
* family's starting means). The Laplace criterion resolves θ' where θ'² times this is neither negligible against the
|
|
580
|
+
* 1 of Λ'Z'WZΛ + I nor so large that the system loses its digits against the fixed effects (internal; exported for
|
|
581
|
+
* the tests)
|
|
582
|
+
*/
|
|
583
|
+
export function startInformation(s) {
|
|
584
|
+
const fam = s.family;
|
|
585
|
+
const ww = s.mustart.map((m, i) => (s.weights[i] > 0 ? workingWeight(fam, s.weights[i], fam.muEta(fam.linkfun(m)), m) : 0));
|
|
586
|
+
let top = 0;
|
|
587
|
+
for (const col of s.z) {
|
|
588
|
+
let sum = 0;
|
|
589
|
+
col.rows.forEach((i, k) => (sum += ww[i] * col.values[k] * col.values[k]));
|
|
590
|
+
top = Math.max(top, sum);
|
|
591
|
+
}
|
|
592
|
+
return top;
|
|
593
|
+
}
|
|
594
|
+
/** The range of startInformation outside which a failure of the fit is reported as a matter of scale (G21) */
|
|
595
|
+
const MIN_INFORMATION = 2 ** -40;
|
|
596
|
+
const MAX_INFORMATION = 2 ** 40;
|
|
597
|
+
/** startInformation below this times |deviance| makes the criterion flat to rounding in θ near the start */
|
|
598
|
+
const FLAT_INFORMATION = 1e-10;
|
|
599
|
+
/** Below this smallest response (of positive weight), a Gamma fit with the log link is fitted scaled (responseExponent) */
|
|
600
|
+
const SMALL_GAMMA_RESPONSE = 2 ** -40;
|
|
601
|
+
/**
|
|
602
|
+
* The power of 2 by which the response is divided for the fit: 0 except for the Gamma family with the log link and a
|
|
603
|
+
* response (of positive weight) below 2^-40, where lme4's lower bound of the mean, μ ≥ 2^-52, comes into reach (a
|
|
604
|
+
* response of 1e-20 makes lme4's penalised IRLS fail to converge, one of 1e-150 gives a fit with θ 0 and the slope
|
|
605
|
+
* 0). That model is exactly invariant under a scaling of the response, which shifts η by its log (the working weights
|
|
606
|
+
* w μ'² / V are w, the deviance residuals and the dispersion do not change): the response is brought to the middle
|
|
607
|
+
* of its range on the scale of powers of 2, and the fit is the same as the response's as given, without the bound
|
|
608
|
+
*/
|
|
609
|
+
function responseExponent(s) {
|
|
610
|
+
if (s.family.family !== "Gamma" || s.family.link !== "log")
|
|
611
|
+
return 0;
|
|
612
|
+
let low = Infinity;
|
|
613
|
+
let high = 0;
|
|
614
|
+
s.y.forEach((v, i) => {
|
|
615
|
+
if (!(s.weights[i] > 0) || !(v > 0))
|
|
616
|
+
return;
|
|
617
|
+
low = Math.min(low, v);
|
|
618
|
+
high = Math.max(high, v);
|
|
619
|
+
});
|
|
620
|
+
if (!(low < SMALL_GAMMA_RESPONSE))
|
|
621
|
+
return 0;
|
|
622
|
+
return Math.floor((Math.floor(Math.log2(low)) + Math.floor(Math.log2(high))) / 2);
|
|
623
|
+
}
|
|
624
|
+
/** (Σ w (y − μ)² / V(μ) + ‖u‖²) / n at an evaluation: σ² of lme4's sigma for the families with a dispersion */
|
|
625
|
+
function dispersionOf(s, r) {
|
|
626
|
+
let sum = r.ussq;
|
|
627
|
+
s.y.forEach((yi, i) => {
|
|
628
|
+
const mu = r.mu[i];
|
|
629
|
+
const v = s.family.variance(mu);
|
|
630
|
+
const term = (s.weights[i] * (yi - mu) ** 2) / v;
|
|
631
|
+
// (the square of the Pearson residual where V or the square is out of range: a Gamma mean of 1e200)
|
|
632
|
+
sum += Number.isFinite(term) && Math.abs(v) >= 2 ** -1022 && v < Infinity ? term : pearsonResidualOf(s.family, s.weights[i], yi, mu) ** 2;
|
|
633
|
+
});
|
|
634
|
+
return sum / s.y.length;
|
|
635
|
+
}
|