@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,438 @@
|
|
|
1
|
+
// The minimiser of the mixed models (lmer's criterion over θ, glmer's Laplace deviance over θ or (θ, β)): a
|
|
2
|
+
// trust-region Newton method with lmer's treatment of the lower bounds of the diagonal elements of θ (the bounds are
|
|
3
|
+
// not enforced; columns of a block T_k whose diagonal element ends negative change sign; diagonal elements that reach
|
|
4
|
+
// 0 are held at exactly 0 and released when the derivative or a direction of negative curvature says so), and the
|
|
5
|
+
// comparison with the boundary points of whole terms. The method and its constants are described at the top of
|
|
6
|
+
// src/models/lmer.ts; this file only makes them independent of the criterion, so that glmer uses them as they are.
|
|
7
|
+
//
|
|
8
|
+
// Written for rStats.js (no ported code); moved from src/models/lmer.ts without changing lmer's computation.
|
|
9
|
+
import { ldexp, norm2 } from "../internal/summary.js";
|
|
10
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
11
|
+
/** lmer's settings (an analytic gradient) */
|
|
12
|
+
export const LMER_SETTINGS = {
|
|
13
|
+
hessianStep: 1e-4,
|
|
14
|
+
hessianStepFloor: 1e-6,
|
|
15
|
+
stepTolerance: 1e-13,
|
|
16
|
+
stepFloor: 1e-10,
|
|
17
|
+
gradientTolerance: 1e-9,
|
|
18
|
+
releaseTolerance: 1e-12,
|
|
19
|
+
};
|
|
20
|
+
/** robust: a Newton step below this (relative to max(1, max |x|)) with a small gradient is convergence (see iterate) */
|
|
21
|
+
const NOISE_STEP = 1e-8;
|
|
22
|
+
/** Initial trust-region radius, relative to max(1, max |x|) */
|
|
23
|
+
const INITIAL_RADIUS = 0.25;
|
|
24
|
+
/** Eigenvalues of the Hessian below this times the largest are treated as 0 (the Hessian's own accuracy) */
|
|
25
|
+
const EIGENVALUE_TOLERANCE = 1e-6;
|
|
26
|
+
/** Diagonal elements below this (relative to max(1, max |x|)) at convergence are candidates for the boundary */
|
|
27
|
+
const BOUNDARY_CANDIDATE = 1e-4;
|
|
28
|
+
/** The move along a direction of negative curvature that leaves the boundary (relative to max(1, max |x|)) */
|
|
29
|
+
const NEGATIVE_CURVATURE_MOVE = 1e-3;
|
|
30
|
+
const MAX_ITERATIONS = 500;
|
|
31
|
+
/** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
|
|
32
|
+
const HESSIAN_REUSE_RATIO = 0.75;
|
|
33
|
+
/** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
|
|
34
|
+
const RESTART_THRESHOLD = 1e-8;
|
|
35
|
+
/** ... and there are at most this many restarts */
|
|
36
|
+
const MAX_RESTARTS = 50;
|
|
37
|
+
/** The failure of a local minimisation, with the best point reached (internal) */
|
|
38
|
+
class MinimisationFailure extends Error {
|
|
39
|
+
best;
|
|
40
|
+
constructor(message, best) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.best = best;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Rejected steps in a row at the smallest radius after which a robust minimisation stops (see localMinimum) */
|
|
46
|
+
const MAX_STALLS = 3;
|
|
47
|
+
/** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
|
|
48
|
+
export function symmetricEigen(a0) {
|
|
49
|
+
// entries of extreme magnitude are scaled by a power of 2 (exact) first and the eigenvalues scaled back: the sums of
|
|
50
|
+
// squares below overflowed for entries around 1e200 (Infinity <= 1e-32 Infinity ended the sweeps at once)
|
|
51
|
+
let mx = 0;
|
|
52
|
+
for (const row of a0)
|
|
53
|
+
for (const v of row)
|
|
54
|
+
mx = Math.max(mx, Math.abs(v));
|
|
55
|
+
const k = mx === 0 || !Number.isFinite(mx) || (mx >= 2 ** -256 && mx <= 2 ** 256) ? 0 : Math.floor(Math.log2(mx));
|
|
56
|
+
if (k !== 0) {
|
|
57
|
+
const r = symmetricEigen(a0.map((row) => row.map((v) => ldexp(v, -k))));
|
|
58
|
+
return { values: r.values.map((v) => ldexp(v, k)), vectors: r.vectors };
|
|
59
|
+
}
|
|
60
|
+
const m = a0.length;
|
|
61
|
+
const a = a0.map((row) => row.slice());
|
|
62
|
+
const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
|
|
63
|
+
for (let sweep = 0; sweep < 100; sweep++) {
|
|
64
|
+
let off = 0;
|
|
65
|
+
let total = 0;
|
|
66
|
+
for (let i = 0; i < m; i++) {
|
|
67
|
+
for (let j = 0; j < m; j++) {
|
|
68
|
+
total += a[i][j] ** 2;
|
|
69
|
+
if (i !== j)
|
|
70
|
+
off += a[i][j] ** 2;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (off <= 1e-32 * total)
|
|
74
|
+
break;
|
|
75
|
+
for (let p = 0; p < m - 1; p++) {
|
|
76
|
+
for (let q = p + 1; q < m; q++) {
|
|
77
|
+
const apq = a[p][q];
|
|
78
|
+
if (apq === 0)
|
|
79
|
+
continue;
|
|
80
|
+
const tau = (a[q][q] - a[p][p]) / (2 * apq);
|
|
81
|
+
const t = Math.sign(tau || 1) / (Math.abs(tau) + Math.sqrt(1 + tau * tau));
|
|
82
|
+
const c = 1 / Math.sqrt(1 + t * t);
|
|
83
|
+
const sn = t * c;
|
|
84
|
+
for (let k = 0; k < m; k++) {
|
|
85
|
+
const akp = a[k][p];
|
|
86
|
+
const akq = a[k][q];
|
|
87
|
+
a[k][p] = c * akp - sn * akq;
|
|
88
|
+
a[k][q] = sn * akp + c * akq;
|
|
89
|
+
}
|
|
90
|
+
for (let k = 0; k < m; k++) {
|
|
91
|
+
const apk = a[p][k];
|
|
92
|
+
const aqk = a[q][k];
|
|
93
|
+
a[p][k] = c * apk - sn * aqk;
|
|
94
|
+
a[q][k] = sn * apk + c * aqk;
|
|
95
|
+
}
|
|
96
|
+
for (let k = 0; k < m; k++) {
|
|
97
|
+
const vkp = v[k][p];
|
|
98
|
+
const vkq = v[k][q];
|
|
99
|
+
v[k][p] = c * vkp - sn * vkq;
|
|
100
|
+
v[k][q] = sn * vkp + c * vkq;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
|
|
106
|
+
}
|
|
107
|
+
// without overflow of the squares (src/internal/summary.ts)
|
|
108
|
+
const norm = norm2;
|
|
109
|
+
const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
|
|
110
|
+
/**
|
|
111
|
+
* The step p that minimises g'p + p'Hp/2 subject to ‖p‖ ≤ radius (H = V diag(λ) V'), and whether it is the Newton
|
|
112
|
+
* step. Eigenvalues within `zero` of 0 are treated as 0: along their eigenvectors the criterion is flat to the
|
|
113
|
+
* accuracy of the Hessian (as along a set of equivalent minimisers), and the Newton step leaves them out when the
|
|
114
|
+
* gradient's component there is below `gradientZero`.
|
|
115
|
+
*/
|
|
116
|
+
function trustRegionStep(g, eig, radius, zero, gradientZero) {
|
|
117
|
+
const m = g.length;
|
|
118
|
+
const { values, vectors } = eig;
|
|
119
|
+
const gt = vectors.map((v) => dot(v, g));
|
|
120
|
+
const combine = (coef) => {
|
|
121
|
+
const p = new Array(m).fill(0);
|
|
122
|
+
coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
|
|
123
|
+
return p;
|
|
124
|
+
};
|
|
125
|
+
const minValue = minOf(values);
|
|
126
|
+
// the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
|
|
127
|
+
// directions, and the step is inside the region (≥: a Hessian of zeros, where zero is 0, is semidefinite; a flat
|
|
128
|
+
// criterion with a zero gradient, as glmer's in β where θ = 0 and the aic term is constant, is at a minimiser)
|
|
129
|
+
if (minValue >= -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
|
|
130
|
+
const p = combine(values.map((l, k) => (l > zero ? -gt[k] / l : 0)));
|
|
131
|
+
if (norm(p) <= radius)
|
|
132
|
+
return { step: p, newton: true };
|
|
133
|
+
}
|
|
134
|
+
// on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
|
|
135
|
+
const lowest = Math.max(0, -minValue);
|
|
136
|
+
const lengthAt = (mu) => norm2(values.map((l, k) => gt[k] / (l + mu)));
|
|
137
|
+
const tiny = Math.max(zero, 1e-12 * Math.max(maxOf(values.map(Math.abs)), 1));
|
|
138
|
+
if (lengthAt(lowest + tiny) >= radius) {
|
|
139
|
+
let lo = lowest + tiny;
|
|
140
|
+
let hi = lowest + norm(g) / radius + maxOf(values.map(Math.abs)) + tiny;
|
|
141
|
+
for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
|
|
142
|
+
const mid = (lo + hi) / 2;
|
|
143
|
+
if (lengthAt(mid) > radius)
|
|
144
|
+
lo = mid;
|
|
145
|
+
else
|
|
146
|
+
hi = mid;
|
|
147
|
+
}
|
|
148
|
+
return { step: combine(values.map((l, k) => -gt[k] / (l + hi))), newton: false };
|
|
149
|
+
}
|
|
150
|
+
// the "hard case": the gradient has (almost) no component along the eigenvectors of the lowest eigenvalue; the
|
|
151
|
+
// step at μ = −λ_min is completed to the boundary along such an eigenvector
|
|
152
|
+
const low = values.map((l) => l + lowest <= tiny);
|
|
153
|
+
const p = combine(values.map((l, k) => (low[k] ? 0 : -gt[k] / (l + lowest))));
|
|
154
|
+
const k0 = values.indexOf(minValue);
|
|
155
|
+
const rest = Math.sqrt(Math.max(0, radius * radius - dot(p, p)));
|
|
156
|
+
const direction = -Math.sign(gt[k0]) || 1;
|
|
157
|
+
return { step: p.map((pi, i) => pi + direction * rest * vectors[k0][i]), newton: false };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* A local minimiser of the criterion, subject to the lower bounds of the diagonal elements (see src/models/lmer.ts),
|
|
161
|
+
* started at `start`, with the elements in `held` kept at exactly 0 throughout (never free, never released); with its
|
|
162
|
+
* criterion
|
|
163
|
+
*/
|
|
164
|
+
export function localMinimum(problem, start, held = new Set()) {
|
|
165
|
+
const { diagonal, settings } = problem;
|
|
166
|
+
const robust = problem.robust === true;
|
|
167
|
+
let theta = start.map((v, j) => (held.has(j) ? 0 : v));
|
|
168
|
+
/** The lowest point evaluated with a finite criterion and gradient (robust: reported with a failure) */
|
|
169
|
+
let best;
|
|
170
|
+
const evaluate = (x) => {
|
|
171
|
+
const r = problem.evaluate(x);
|
|
172
|
+
if (robust && Number.isFinite(r.f) && r.g.every(Number.isFinite) && (best === undefined || r.f < best.f)) {
|
|
173
|
+
best = { theta: x.map((v) => (v === 0 ? 0 : v)), f: r.f };
|
|
174
|
+
}
|
|
175
|
+
return r;
|
|
176
|
+
};
|
|
177
|
+
const fail = () => {
|
|
178
|
+
throw robust ? new MinimisationFailure(problem.failure, best) : new Error(problem.failure);
|
|
179
|
+
};
|
|
180
|
+
let { f, g } = evaluate(theta);
|
|
181
|
+
// (glmer: an evaluation that fails where the search must go on is an error)
|
|
182
|
+
const check = () => {
|
|
183
|
+
if (problem.rejectNonFinite && !Number.isFinite(f))
|
|
184
|
+
fail();
|
|
185
|
+
};
|
|
186
|
+
check();
|
|
187
|
+
/** Diagonal elements held at exactly 0 */
|
|
188
|
+
const fixed = new Set();
|
|
189
|
+
/** Diagonal elements released from 0 (not set to 0 again: their minimiser is near 0 but not at it) */
|
|
190
|
+
const released = new Set();
|
|
191
|
+
const scaleOf = () => Math.max(1, ...theta.map(Math.abs));
|
|
192
|
+
const gradientTolerance = () => settings.gradientTolerance * Math.max(1, Math.abs(f));
|
|
193
|
+
let radius = INITIAL_RADIUS * scaleOf();
|
|
194
|
+
let previousNewton = Infinity;
|
|
195
|
+
/** The Hessian of the last iteration, when it may be used again (see iterate) */
|
|
196
|
+
let reusable;
|
|
197
|
+
/** The Hessian on the elements `set`, from central differences of the gradient (or the problem's own) */
|
|
198
|
+
const hessian = (set) => {
|
|
199
|
+
if (problem.hessian !== undefined) {
|
|
200
|
+
const h = problem.hessian(theta, set, scaleOf());
|
|
201
|
+
if (h.some((row) => row.some((v) => !Number.isFinite(v))))
|
|
202
|
+
fail();
|
|
203
|
+
return h;
|
|
204
|
+
}
|
|
205
|
+
const floor = settings.hessianStepFloor * scaleOf();
|
|
206
|
+
const cols = set.map((j) => {
|
|
207
|
+
const h = Math.max(settings.hessianStep * Math.abs(theta[j]), floor);
|
|
208
|
+
const plus = theta.slice();
|
|
209
|
+
plus[j] = theta[j] + h;
|
|
210
|
+
const minus = theta.slice();
|
|
211
|
+
minus[j] = theta[j] - h;
|
|
212
|
+
const gp = evaluate(plus).g;
|
|
213
|
+
const gm = evaluate(minus).g;
|
|
214
|
+
if (robust) {
|
|
215
|
+
// (glmer: where the gradient fails on one side, the one-sided difference with the gradient at θ)
|
|
216
|
+
const okP = set.every((i) => Number.isFinite(gp[i]));
|
|
217
|
+
const okM = set.every((i) => Number.isFinite(gm[i]));
|
|
218
|
+
if (!okP && !okM)
|
|
219
|
+
fail();
|
|
220
|
+
if (!okP || !okM)
|
|
221
|
+
return set.map((i) => (okP ? gp[i] - g[i] : g[i] - gm[i]) / h);
|
|
222
|
+
}
|
|
223
|
+
return set.map((i) => (gp[i] - gm[i]) / (2 * h));
|
|
224
|
+
});
|
|
225
|
+
return set.map((_, a) => set.map((_, b) => (cols[a][b] + cols[b][a]) / 2));
|
|
226
|
+
};
|
|
227
|
+
/** Rejected steps in a row taken at the smallest radius (robust) */
|
|
228
|
+
let stalls = 0;
|
|
229
|
+
/** One trust-region iteration on the free elements; returns whether it converged */
|
|
230
|
+
const iterate = (free) => {
|
|
231
|
+
const radiusFloor = settings.stepTolerance * scaleOf();
|
|
232
|
+
const atFloor = radius <= radiusFloor;
|
|
233
|
+
// (robust: at the smallest radius with a small gradient, the point is the minimiser to the accuracy of the
|
|
234
|
+
// criterion: the steps there are at the level of the gradient's rounding and need not become Newton steps)
|
|
235
|
+
if (robust && atFloor && free.every((j) => Math.abs(g[j]) <= gradientTolerance()))
|
|
236
|
+
return true;
|
|
237
|
+
const fresh = reusable === undefined || reusable.free.length !== free.length || reusable.free.some((j, a) => j !== free[a]);
|
|
238
|
+
const h = fresh ? hessian(free) : reusable.h;
|
|
239
|
+
reusable = undefined;
|
|
240
|
+
const eig = symmetricEigen(h);
|
|
241
|
+
// (a Hessian with NaN, from a criterion whose products overflowed, has no step: the minimisation's failure, not
|
|
242
|
+
// the TypeError of an eigenvalue that is never the smallest)
|
|
243
|
+
if (!eig.values.every(Number.isFinite))
|
|
244
|
+
fail();
|
|
245
|
+
const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
|
|
246
|
+
const gFree = free.map((j) => g[j]);
|
|
247
|
+
const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
|
|
248
|
+
if (robust && !newton && eig.values.every((l) => l > zero) && free.every((j) => Math.abs(g[j]) <= gradientTolerance())) {
|
|
249
|
+
// (robust: a small gradient with a positive definite Hessian whose full Newton step is below 1e-8 (relative to
|
|
250
|
+
// max(1, max |x|)) is the minimiser, although the trust radius has shrunk below that step: the criterion's
|
|
251
|
+
// noise (nearly collinear predictors: about 1e-12 of its value) rejected steps there, and the iteration would
|
|
252
|
+
// otherwise wander at that level until its limit, or not, by the last bits of the platform's arithmetic)
|
|
253
|
+
const gt = eig.vectors.map((v) => dot(v, gFree));
|
|
254
|
+
const newtonStep = eig.vectors[0].map((_, i) => eig.values.reduce((sum, l, k) => sum - (gt[k] / l) * eig.vectors[k][i], 0));
|
|
255
|
+
if (maxOf(newtonStep.map(Math.abs)) <= NOISE_STEP * scaleOf())
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
const trial = theta.slice();
|
|
259
|
+
free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
|
|
260
|
+
const size = maxOf(step.map(Math.abs)) / scaleOf();
|
|
261
|
+
const next = evaluate(trial);
|
|
262
|
+
const length = norm(step);
|
|
263
|
+
const stalled = () => {
|
|
264
|
+
// (robust: a step rejected at the smallest radius cannot become smaller; after MAX_STALLS of them the point
|
|
265
|
+
// is the minimiser to the accuracy of the criterion if the gradient is small, and a failure otherwise)
|
|
266
|
+
if (!robust || !atFloor)
|
|
267
|
+
return false;
|
|
268
|
+
stalls++;
|
|
269
|
+
if (stalls < MAX_STALLS)
|
|
270
|
+
return false;
|
|
271
|
+
if (free.every((j) => Math.abs(g[j]) <= gradientTolerance()))
|
|
272
|
+
return true;
|
|
273
|
+
return fail();
|
|
274
|
+
};
|
|
275
|
+
if (!Number.isFinite(next.f)) {
|
|
276
|
+
if (!problem.rejectNonFinite)
|
|
277
|
+
throw new Error(problem.failure);
|
|
278
|
+
// (a failed evaluation counts as +Infinity: the step is rejected and the region shrinks)
|
|
279
|
+
radius = Math.max(length / 4, settings.stepTolerance * scaleOf());
|
|
280
|
+
previousNewton = Infinity;
|
|
281
|
+
return stalled();
|
|
282
|
+
}
|
|
283
|
+
const predicted = -(dot(gFree, step) + dot(step, h.map((row) => dot(row, step))) / 2);
|
|
284
|
+
// the actual reduction from the values, or, where they are equal to rounding, from the gradients (trapezoid);
|
|
285
|
+
// robust (glmer): within 1e-8 max(1, |f|), as glmer's deviance is a sum of terms of order 1 where it is near 0
|
|
286
|
+
// and can be noisy at 1e-10 of its value (the aic term of a Gamma fit with a dispersion of 1e-16), while its
|
|
287
|
+
// analytic gradient is smooth
|
|
288
|
+
const roundingLevel = robust ? 1e-8 * Math.max(1, Math.abs(f)) : 1e-10 * Math.abs(f);
|
|
289
|
+
const actual = Math.abs(f - next.f) > roundingLevel ? f - next.f : -(dot(gFree, step) + dot(free.map((j) => next.g[j]), step)) / 2;
|
|
290
|
+
const ratio = predicted > 0 ? actual / predicted : actual >= 0 ? 1 : -1;
|
|
291
|
+
const accepted = ratio > 0.1 || size <= settings.stepFloor;
|
|
292
|
+
if (accepted) {
|
|
293
|
+
theta = trial;
|
|
294
|
+
f = next.f;
|
|
295
|
+
g = next.g;
|
|
296
|
+
stalls = 0;
|
|
297
|
+
}
|
|
298
|
+
else if (stalled())
|
|
299
|
+
return true;
|
|
300
|
+
if (ratio < 0.25)
|
|
301
|
+
radius = Math.max(length / 4, settings.stepTolerance * scaleOf());
|
|
302
|
+
else if (ratio > 0.75 && length >= 0.99 * radius)
|
|
303
|
+
radius *= 2;
|
|
304
|
+
if (!newton) {
|
|
305
|
+
previousNewton = Infinity;
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
const gradientSmall = free.every((j) => Math.abs(g[j]) <= gradientTolerance());
|
|
309
|
+
// (the steps stopping decreasing is taken as rounding level only with a fresh Hessian)
|
|
310
|
+
const done = gradientSmall && (size <= settings.stepTolerance || (fresh && size <= settings.stepFloor && size >= 0.5 * previousNewton));
|
|
311
|
+
// the Hessian is kept for the next iteration after a Newton step that was accepted, predicted well and at most
|
|
312
|
+
// half the previous one (the model is still good; convergence stays fast)
|
|
313
|
+
if (ratio > HESSIAN_REUSE_RATIO && ratio < 1 / HESSIAN_REUSE_RATIO && size < 0.5 * previousNewton)
|
|
314
|
+
reusable = { free, h };
|
|
315
|
+
previousNewton = size;
|
|
316
|
+
return done;
|
|
317
|
+
};
|
|
318
|
+
/**
|
|
319
|
+
* At a converged point with elements held at 0: a direction of negative curvature of the elements held there
|
|
320
|
+
* whose derivative vanishes, together with the free ones, is a way down (in a block whose leading diagonal element
|
|
321
|
+
* is 0, the criterion depends on it and the element below through their product, so neither alone shows the
|
|
322
|
+
* descent; for a single even element it is its own curvature at 0). If there is one, the elements held at 0 along
|
|
323
|
+
* it are released and θ is moved a little along it; returns whether it did.
|
|
324
|
+
*/
|
|
325
|
+
const leaveAlongNegativeCurvature = () => {
|
|
326
|
+
if (fixed.size === 0)
|
|
327
|
+
return false;
|
|
328
|
+
const set = theta.map((_, j) => j).filter((j) => !held.has(j));
|
|
329
|
+
const eig = symmetricEigen(hessian(set));
|
|
330
|
+
const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
|
|
331
|
+
const k = eig.values.indexOf(minOf(eig.values));
|
|
332
|
+
if (!(eig.values[k] < -zero))
|
|
333
|
+
return false;
|
|
334
|
+
const v = eig.vectors[k];
|
|
335
|
+
const leaving = set.filter((j, a) => fixed.has(j) && Math.abs(v[a]) > 1e-8);
|
|
336
|
+
if (leaving.length === 0)
|
|
337
|
+
return false;
|
|
338
|
+
for (const j of leaving) {
|
|
339
|
+
fixed.delete(j);
|
|
340
|
+
released.add(j);
|
|
341
|
+
}
|
|
342
|
+
const move = NEGATIVE_CURVATURE_MOVE * scaleOf();
|
|
343
|
+
set.forEach((j, a) => (theta[j] = theta[j] + move * v[a]));
|
|
344
|
+
({ f, g } = evaluate(theta));
|
|
345
|
+
check();
|
|
346
|
+
return true;
|
|
347
|
+
};
|
|
348
|
+
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
|
|
349
|
+
const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
|
|
350
|
+
if (free.length > 0 && !iterate(free))
|
|
351
|
+
continue;
|
|
352
|
+
// converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
|
|
353
|
+
const toZero = free.filter((j) => diagonal[j] && !released.has(j) && Math.abs(theta[j]) < BOUNDARY_CANDIDATE * scaleOf());
|
|
354
|
+
if (toZero.length > 0) {
|
|
355
|
+
for (const j of toZero) {
|
|
356
|
+
theta[j] = 0;
|
|
357
|
+
fixed.add(j);
|
|
358
|
+
}
|
|
359
|
+
({ f, g } = evaluate(theta));
|
|
360
|
+
check();
|
|
361
|
+
previousNewton = Infinity;
|
|
362
|
+
reusable = undefined;
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
// elements held at 0 with a derivative, or with a direction of negative curvature, are released
|
|
366
|
+
const tolerance = settings.releaseTolerance * Math.max(1, Math.abs(f));
|
|
367
|
+
const release = [...fixed].filter((j) => Math.abs(g[j]) > tolerance);
|
|
368
|
+
if (release.length > 0) {
|
|
369
|
+
for (const j of release) {
|
|
370
|
+
fixed.delete(j);
|
|
371
|
+
released.add(j);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
else if (!leaveAlongNegativeCurvature()) {
|
|
375
|
+
// the minimiser: each column of T_k with a negative diagonal element changes sign (an equivalent θ)
|
|
376
|
+
for (const column of problem.columns) {
|
|
377
|
+
if (theta[column[0]] < 0)
|
|
378
|
+
for (const j of column)
|
|
379
|
+
theta[j] = -theta[j];
|
|
380
|
+
}
|
|
381
|
+
return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
|
|
382
|
+
}
|
|
383
|
+
radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
|
|
384
|
+
previousNewton = Infinity;
|
|
385
|
+
reusable = undefined;
|
|
386
|
+
}
|
|
387
|
+
return fail();
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* The minimiser: the local minimum reached from `start`, then compared with the local minima reached from its
|
|
391
|
+
* boundary points with one whole term removed (`blocks`: the indices of each term's block); a clearly better one is
|
|
392
|
+
* the start of a new local minimisation, until none is (see src/models/lmer.ts). Returns the minimiser and its
|
|
393
|
+
* criterion.
|
|
394
|
+
*/
|
|
395
|
+
export function minimiseWithRestarts(problem, start, blocks, options = {}) {
|
|
396
|
+
/** A local minimisation; robust: a failure as undefined (with the best point reached in `lastBest`) */
|
|
397
|
+
let lastBest;
|
|
398
|
+
const local = (from, held) => {
|
|
399
|
+
if (problem.robust !== true)
|
|
400
|
+
return localMinimum(problem, from, held);
|
|
401
|
+
try {
|
|
402
|
+
return localMinimum(problem, from, held);
|
|
403
|
+
}
|
|
404
|
+
catch (e) {
|
|
405
|
+
if (!(e instanceof MinimisationFailure))
|
|
406
|
+
throw e;
|
|
407
|
+
lastBest = e.best;
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
const failed = () => {
|
|
412
|
+
if (options.bestOnFailure === true && lastBest !== undefined)
|
|
413
|
+
return { ...lastBest, converged: false };
|
|
414
|
+
throw new Error(problem.failure);
|
|
415
|
+
};
|
|
416
|
+
const first = local(start);
|
|
417
|
+
if (first === undefined)
|
|
418
|
+
return failed();
|
|
419
|
+
let best = first;
|
|
420
|
+
for (let round = 0; round < MAX_RESTARTS; round++) {
|
|
421
|
+
let candidate;
|
|
422
|
+
for (const block of blocks) {
|
|
423
|
+
if (block.every((j) => best.theta[j] === 0))
|
|
424
|
+
continue;
|
|
425
|
+
// (robust: a boundary sub-problem that fails is left out; the comparison is with those that converge)
|
|
426
|
+
const removed = local(best.theta, new Set(block));
|
|
427
|
+
if (removed !== undefined && (candidate === undefined || removed.f < candidate.f))
|
|
428
|
+
candidate = removed;
|
|
429
|
+
}
|
|
430
|
+
if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
|
|
431
|
+
return { ...best, converged: true };
|
|
432
|
+
const next = local(candidate.theta);
|
|
433
|
+
if (next === undefined)
|
|
434
|
+
return failed();
|
|
435
|
+
best = next;
|
|
436
|
+
}
|
|
437
|
+
throw new Error(problem.failure);
|
|
438
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { type GlmerResult } from "./glmer.js";
|
|
2
|
+
import { type LmerResult } from "./lmer.js";
|
|
3
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
4
|
+
/**
|
|
5
|
+
* Options of {@link lmerPredict}. Only the keys below are accepted: R's `re.form`, `allow.new.levels`, `random.only`,
|
|
6
|
+
* `se.fit`, `newparams`, `terms`, `na.action` and `naAction` give the Error `lmerPredict: argument '<key>' is not
|
|
7
|
+
* supported`, any other key a RangeError.
|
|
8
|
+
*
|
|
9
|
+
* @category Mixed models
|
|
10
|
+
*/
|
|
11
|
+
export interface LmerPredictOptions {
|
|
12
|
+
/**
|
|
13
|
+
* The rows to predict: a data frame with the columns of the fit's data that the prediction uses (the variables of
|
|
14
|
+
* the fixed-effects part and of the selected random-effects terms; not the response). Default: the rows of the fit.
|
|
15
|
+
*/
|
|
16
|
+
newdata?: DataFrame;
|
|
17
|
+
/**
|
|
18
|
+
* Which random-effects terms to include (R's `re.form`): `undefined` or `null` all of them (default); `false`,
|
|
19
|
+
* `"~0"` or `"~ 0"` none (the population-level prediction); a one-sided formula such as `"~ (1 | g)"` those written
|
|
20
|
+
* in it (its fixed part is ignored). Its grouping factors must be the fit's and its columns among the fit's columns
|
|
21
|
+
* for that factor; a term may have fewer columns than the fit's.
|
|
22
|
+
*/
|
|
23
|
+
reForm?: string | false | null;
|
|
24
|
+
/**
|
|
25
|
+
* Whether a level of a grouping factor not in the fit, or a missing grouping value, is allowed (default `false`, an
|
|
26
|
+
* error): that term then adds 0 for the row (the population level for that term). R's `allow.new.levels`.
|
|
27
|
+
*/
|
|
28
|
+
allowNewLevels?: boolean;
|
|
29
|
+
/** Whether to predict the random part only, without the fixed effects and the offset (default `false`; R's `random.only`). */
|
|
30
|
+
randomOnly?: boolean;
|
|
31
|
+
/** `"link"` (default) or `"response"`: for lmer both give the same values, as in R. */
|
|
32
|
+
type?: "link" | "response";
|
|
33
|
+
/** Whether to return the standard errors (default `false`; R's `se.fit`). */
|
|
34
|
+
seFit?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Options of {@link glmerPredict}: those of {@link LmerPredictOptions} and `newoffset`. Only these keys are accepted:
|
|
38
|
+
* R's `re.form`, `allow.new.levels`, `random.only`, `se.fit`, `newparams`, `terms`, `na.action` and `naAction` give
|
|
39
|
+
* the Error `glmerPredict: argument '<key>' is not supported`, any other key a RangeError.
|
|
40
|
+
*
|
|
41
|
+
* @category Mixed models
|
|
42
|
+
*/
|
|
43
|
+
export interface GlmerPredictOptions extends LmerPredictOptions {
|
|
44
|
+
/**
|
|
45
|
+
* The offset of the rows of `newdata` (one number per row; default all 0) when the fit's offset was given as an
|
|
46
|
+
* array (or not at all); an offset given to glmer as a column name is read from that column of `newdata` instead,
|
|
47
|
+
* and `newoffset` is then a RangeError, as it is without `newdata`.
|
|
48
|
+
*/
|
|
49
|
+
newoffset?: readonly number[] | Float64Array;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Result of {@link glmerPredict} and {@link lmerPredict}.
|
|
53
|
+
*
|
|
54
|
+
* @category Mixed models
|
|
55
|
+
*/
|
|
56
|
+
export interface MixedPrediction {
|
|
57
|
+
/** The predictions, one per row (of `newdata`, or of the fit), on the scale of `type`. */
|
|
58
|
+
fit: number[];
|
|
59
|
+
/** Their standard errors (only with `seFit: true`; R's `se.fit`). */
|
|
60
|
+
seFit?: number[];
|
|
61
|
+
/** R's warnings (only when there are some: glmer's warning about the standard errors). */
|
|
62
|
+
warnings?: string[];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Predictions of a linear mixed model fitted by {@link lmer}, at the rows of the fit or at new data, with all, some
|
|
66
|
+
* or none of the random-effects terms, optionally with their standard errors. Equivalent to `lme4::predict()` in R.
|
|
67
|
+
*
|
|
68
|
+
* The prediction of a row is x'β̂ + Σ z'b̂ over the selected terms, x built from the row as the fit built its
|
|
69
|
+
* fixed-effects matrix (its terms, contrasts, factor levels and dropped columns) and b̂ the conditional mode of the
|
|
70
|
+
* row's level. A missing value in a variable gives NaN for its row; a factor level of the fixed part that the fit did
|
|
71
|
+
* not have is the RangeError `factor <name> has new level <value>` (R: `non-conformable arguments`). The standard
|
|
72
|
+
* errors are those of the conditional covariance σ² A K⁻¹ A' of (b, β) at θ̂ (Henderson's equations), computed
|
|
73
|
+
* correctly also where lme4's are wrong (crossed grouping factors, some `reForm` subsets).
|
|
74
|
+
*
|
|
75
|
+
* @param fit The object returned by {@link lmer} (not a copy of it).
|
|
76
|
+
* @param options `newdata`, `reForm`, `allowNewLevels`, `randomOnly`, `type` and `seFit` (see {@link LmerPredictOptions}).
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const data = {
|
|
81
|
+
* y: [9.8, 10.4, 10.1, 12.3, 12.9, 12.0, 8.1, 7.6, 8.4],
|
|
82
|
+
* g: ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
|
|
83
|
+
* };
|
|
84
|
+
* const fit = lmer("y ~ 1 + (1 | g)", data);
|
|
85
|
+
* lmerPredict(fit, { newdata: { g: ["a", "c"] } }).fit; // [10.101, 8.0565]
|
|
86
|
+
* lmerPredict(fit, { reForm: false }).fit[0]; // 10.178
|
|
87
|
+
* ```
|
|
88
|
+
*
|
|
89
|
+
* @category Mixed models
|
|
90
|
+
*/
|
|
91
|
+
export declare function lmerPredict(fit: LmerResult, options?: LmerPredictOptions): MixedPrediction;
|
|
92
|
+
/**
|
|
93
|
+
* Predictions of a generalized linear mixed model fitted by {@link glmer}, at the rows of the fit or at new data, with
|
|
94
|
+
* all, some or none of the random-effects terms, on the link or the response scale, optionally with their standard
|
|
95
|
+
* errors. Equivalent to `lme4::predict()` in R.
|
|
96
|
+
*
|
|
97
|
+
* The rules are those of {@link lmerPredict}, with the offset: without `newdata` the fit's; with it, an offset given
|
|
98
|
+
* to glmer as a column name is read from that column of `newdata`, one given as an array is replaced by `newoffset`
|
|
99
|
+
* (default 0: R ignores glmer's `offset` argument in prediction). `type: "response"` applies R's inverse link (at the
|
|
100
|
+
* fit's rows with all terms, the fitted means). The standard errors use the Fisher weights at the conditional mode,
|
|
101
|
+
* with R's warning that they are an approximation; on the response scale they are multiplied by |dμ/dη|.
|
|
102
|
+
*
|
|
103
|
+
* @param fit The object returned by {@link glmer} (not a copy of it).
|
|
104
|
+
* @param options `newdata`, `reForm`, `allowNewLevels`, `randomOnly`, `type`, `seFit` and `newoffset` (see
|
|
105
|
+
* {@link GlmerPredictOptions}).
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```ts
|
|
109
|
+
* const data = {
|
|
110
|
+
* y: [2, 3, 6, 7, 8, 1, 0, 3, 2, 5, 4, 6, 9, 8, 13, 0, 2, 1, 4, 3],
|
|
111
|
+
* x: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
|
|
112
|
+
* g: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d"],
|
|
113
|
+
* };
|
|
114
|
+
* const fit = glmer("y ~ x + (1 | g)", data, { family: "poisson" });
|
|
115
|
+
* glmerPredict(fit, { newdata: { x: [6], g: ["c"] }, type: "response" }).fit; // [17.970]
|
|
116
|
+
* glmerPredict(fit, { newdata: { x: [6], g: ["c"] }, reForm: false }).fit; // [2.1967]
|
|
117
|
+
* ```
|
|
118
|
+
*
|
|
119
|
+
* @category Mixed models
|
|
120
|
+
*/
|
|
121
|
+
export declare function glmerPredict(fit: GlmerResult, options?: GlmerPredictOptions): MixedPrediction;
|