@numero-uno-jpn/rstats 0.11.1 → 0.12.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.ja.md +42 -12
  3. package/README.md +40 -10
  4. package/dist/chunks/{chunk-FVPDVRJQ.js → chunk-3VMBBQLV.js} +2 -2
  5. package/dist/chunks/chunk-4OKAZJJG.js +3 -0
  6. package/dist/chunks/{chunk-GG4BJMJW.js → chunk-6BH65HGN.js} +1 -1
  7. package/dist/chunks/chunk-ATC4F4BX.js +2 -0
  8. package/dist/chunks/{chunk-6I6QKTFK.js → chunk-EDH53DXN.js} +2 -2
  9. package/dist/chunks/{chunk-ZRJQD7VS.js → chunk-EZ2KD5NA.js} +2 -2
  10. package/dist/chunks/{chunk-KK4GE65D.js → chunk-GSPOO2G3.js} +2 -2
  11. package/dist/chunks/{chunk-36GVER3O.js → chunk-K7AZ65H7.js} +2 -2
  12. package/dist/chunks/{chunk-2X7JYQBI.js → chunk-LEIH4U5X.js} +2 -2
  13. package/dist/chunks/{chunk-ETOEZTGL.js → chunk-OX3SBG5X.js} +1 -1
  14. package/dist/chunks/chunk-SGZQDJRR.js +2 -0
  15. package/dist/chunks/{chunk-PHHUHR7T.js → chunk-UH2N3ZQW.js} +1 -1
  16. package/dist/chunks/chunk-UV2MZYDQ.js +2 -0
  17. package/dist/chunks/{chunk-WQPFDDIY.js → chunk-VQHEOBTM.js} +2 -2
  18. package/dist/chunks/chunk-WJQZZYOI.js +2 -0
  19. package/dist/chunks/chunk-WKEFHOFR.js +2 -0
  20. package/dist/chunks/{chunk-X2AWQSVS.js → chunk-WXC25OPJ.js} +2 -2
  21. package/dist/chunks/{chunk-HITD7CX6.js → chunk-XJQKSR52.js} +1 -1
  22. package/dist/data/grouping.d.ts +6 -3
  23. package/dist/data/grouping.js +19 -22
  24. package/dist/descriptive.js +2 -2
  25. package/dist/distributions.js +2 -2
  26. package/dist/entries/mixed.d.ts +1 -0
  27. package/dist/entries/mixed.js +2 -0
  28. package/dist/htest/testFormula.js +6 -3
  29. package/dist/linalg.js +2 -2
  30. package/dist/mixed.js +3 -0
  31. package/dist/models/aovStrata.d.ts +1 -1
  32. package/dist/models/aovStrata.js +5 -1
  33. package/dist/models/formula.d.ts +26 -1
  34. package/dist/models/formula.js +125 -9
  35. package/dist/models/lm.d.ts +2 -2
  36. package/dist/models/lmer.d.ts +162 -0
  37. package/dist/models/lmer.js +457 -0
  38. package/dist/models/mixedDeviance.d.ts +44 -0
  39. package/dist/models/mixedDeviance.js +872 -0
  40. package/dist/models/mixedStructure.d.ts +82 -0
  41. package/dist/models/mixedStructure.js +309 -0
  42. package/dist/models/modelFrame.d.ts +12 -1
  43. package/dist/models/modelFrame.js +36 -21
  44. package/dist/models/modelMatrix.d.ts +15 -4
  45. package/dist/models/modelMatrix.js +18 -4
  46. package/dist/numerics.js +2 -2
  47. package/dist/rstats.js +14 -14
  48. package/dist/special.js +2 -2
  49. package/dist/tests.js +12 -12
  50. package/llms.txt +11 -3
  51. package/package.json +5 -1
  52. package/dist/chunks/chunk-3WUXRSM6.js +0 -2
  53. package/dist/chunks/chunk-LAUYSGV4.js +0 -3
  54. package/dist/chunks/chunk-M6GDXKKS.js +0 -2
@@ -0,0 +1,457 @@
1
+ // Linear mixed models fitted by REML or maximum likelihood (lme4's lmer): the estimate of θ that minimises the
2
+ // profiled REML criterion or ML deviance, and the fit's results at it (fixed effects and their covariance, σ, the
3
+ // variance components, the conditional modes of the random effects, fitted values, log-likelihood and information
4
+ // criteria).
5
+ //
6
+ // Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1c, "The fit and its results") and
7
+ // D. Bates, M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of
8
+ // Statistical Software 67(1). The structure comes from src/models/mixedStructure.ts and the criterion with its
9
+ // analytic gradient from src/models/mixedDeviance.ts.
10
+ //
11
+ // The criterion does not change when a column of a block T_k changes sign (Λ_θ → Λ_θ D with D = diag(±1) per level,
12
+ // matched by u → D u), so the bounds θ_jj ≥ 0 on the diagonal elements only choose one of equivalent parameter
13
+ // vectors. They are therefore not enforced during the minimisation: θ is minimised without bounds and, at the end,
14
+ // each column whose diagonal element is negative changes sign. This removes the difficulties of the bounds: the
15
+ // last diagonal element of a block is alone in its column, so the criterion is even in it, and 0 is a stationary
16
+ // point that may be a minimum (the optimum on the boundary) or a maximum along it (the optimum just inside, with a
17
+ // concave region between); a method that enforces the bound stops at 0 in both cases (its projected gradient is
18
+ // exactly 0, and L-BFGS-B's first step from θ = 1 lands exactly there in a one-element problem). And a leading
19
+ // diagonal element at 0 with a positive derivative satisfies the bound's optimality conditions without being a
20
+ // minimum of the model: with the elements below it changed in sign (the same model), the derivative is negative.
21
+ //
22
+ // The minimisation is a trust-region Newton method (θ has few elements): at each iteration the Hessian on the free
23
+ // elements from central differences of the analytic gradient (step 1e-4 |θ_j|, at least 1e-6 max(1, max |θ|)), its
24
+ // eigen-decomposition (Jacobi rotations), and the step that minimises the quadratic model within the region: the
25
+ // Newton step when the Hessian is positive definite and the step fits, otherwise a step on the boundary of the region
26
+ // that follows negative curvature where there is some, so that concave regions and stationary points that are not
27
+ // minima are left. The region starts at 0.25 max(1, max |θ|), so that the search stays local (as lme4's does) when
28
+ // the criterion has several minima. A step is accepted when the actual reduction is at least 0.1 of the predicted one;
29
+ // where the values of the criterion are equal to rounding (it can be that flat near 0), the actual reduction is taken
30
+ // from the gradients by the trapezoid rule. Eigenvalues below 1e-6 of the largest count as 0 (flat to the accuracy of
31
+ // the Hessian, as along a set of equivalent minimisers). Convergence: a Newton step below 1e-13 max(1, max |θ|), or
32
+ // steps at rounding level that stop decreasing (with a fresh Hessian), with the gradient below 1e-9 max(1, |criterion|).
33
+ // The Hessian is used again in the next iteration after a Newton step that was accepted with an actual reduction
34
+ // within 0.75 to 1/0.75 of the predicted one and at most half the previous Newton step: the model is still good there,
35
+ // and its 2m evaluations of the gradient are saved while the convergence stays fast.
36
+ //
37
+ // At convergence, diagonal elements below 1e-4 max(1, max |θ|) are set to exactly 0 and held there while the others
38
+ // converge again; an element held at 0 is released if the derivative there is not 0 (to rounding), or if the Hessian
39
+ // of all the elements has a direction of negative curvature that moves it (then θ is moved a little along it).
40
+ // lme4's own optimiser (and its convergence warnings) are not reproduced: the result is the exact minimiser, which
41
+ // lme4 approaches to its tolerances.
42
+ import { profiledDeviance } from "./mixedDeviance.js";
43
+ import { mixedModelStructure } from "./mixedStructure.js";
44
+ /** Initial trust-region radius, relative to max(1, max |θ|) */
45
+ const INITIAL_RADIUS = 0.25;
46
+ /** Step of the central differences of the gradient that give the Hessian, relative to |θ_j| ... */
47
+ const HESSIAN_STEP = 1e-4;
48
+ /** ... and at least this (relative to max(1, max |θ|)), for elements at or near 0 */
49
+ const HESSIAN_STEP_FLOOR = 1e-6;
50
+ /** Eigenvalues of the Hessian below this times the largest are treated as 0 (the Hessian's own accuracy) */
51
+ const EIGENVALUE_TOLERANCE = 1e-6;
52
+ /** Diagonal elements below this (relative to max(1, max |θ|)) at convergence are candidates for the boundary */
53
+ const BOUNDARY_CANDIDATE = 1e-4;
54
+ /** The move along a direction of negative curvature that leaves the boundary (relative to max(1, max |θ|)) */
55
+ const NEGATIVE_CURVATURE_MOVE = 1e-3;
56
+ /** Converged when the Newton step is below this, relative to max(1, max |θ|) ... */
57
+ const STEP_TOLERANCE = 1e-13;
58
+ /** ... or when the steps stop decreasing (rounding level) below this; steps this small are always accepted */
59
+ const STEP_FLOOR = 1e-10;
60
+ /** The gradient on the free elements at convergence must be below this times max(1, |criterion|) */
61
+ const GRADIENT_TOLERANCE = 1e-9;
62
+ const MAX_ITERATIONS = 500;
63
+ /** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
64
+ const HESSIAN_REUSE_RATIO = 0.75;
65
+ const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
66
+ /** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
67
+ function symmetricEigen(a0) {
68
+ const m = a0.length;
69
+ const a = a0.map((row) => row.slice());
70
+ const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
71
+ for (let sweep = 0; sweep < 100; sweep++) {
72
+ let off = 0;
73
+ let total = 0;
74
+ for (let i = 0; i < m; i++) {
75
+ for (let j = 0; j < m; j++) {
76
+ total += a[i][j] ** 2;
77
+ if (i !== j)
78
+ off += a[i][j] ** 2;
79
+ }
80
+ }
81
+ if (off <= 1e-32 * total)
82
+ break;
83
+ for (let p = 0; p < m - 1; p++) {
84
+ for (let q = p + 1; q < m; q++) {
85
+ const apq = a[p][q];
86
+ if (apq === 0)
87
+ continue;
88
+ const tau = (a[q][q] - a[p][p]) / (2 * apq);
89
+ const t = Math.sign(tau || 1) / (Math.abs(tau) + Math.sqrt(1 + tau * tau));
90
+ const c = 1 / Math.sqrt(1 + t * t);
91
+ const sn = t * c;
92
+ for (let k = 0; k < m; k++) {
93
+ const akp = a[k][p];
94
+ const akq = a[k][q];
95
+ a[k][p] = c * akp - sn * akq;
96
+ a[k][q] = sn * akp + c * akq;
97
+ }
98
+ for (let k = 0; k < m; k++) {
99
+ const apk = a[p][k];
100
+ const aqk = a[q][k];
101
+ a[p][k] = c * apk - sn * aqk;
102
+ a[q][k] = sn * apk + c * aqk;
103
+ }
104
+ for (let k = 0; k < m; k++) {
105
+ const vkp = v[k][p];
106
+ const vkq = v[k][q];
107
+ v[k][p] = c * vkp - sn * vkq;
108
+ v[k][q] = sn * vkp + c * vkq;
109
+ }
110
+ }
111
+ }
112
+ }
113
+ return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
114
+ }
115
+ const norm = (x) => Math.sqrt(x.reduce((sum, v) => sum + v * v, 0));
116
+ const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
117
+ /**
118
+ * The step p that minimises g'p + p'Hp/2 subject to ‖p‖ ≤ radius (H = V diag(λ) V'), and whether it is the Newton
119
+ * step. Eigenvalues within `zero` of 0 are treated as 0: along their eigenvectors the criterion is flat to the
120
+ * accuracy of the Hessian (as along a set of equivalent minimisers), and the Newton step leaves them out when the
121
+ * gradient's component there is below `gradientZero`.
122
+ */
123
+ function trustRegionStep(g, eig, radius, zero, gradientZero) {
124
+ const m = g.length;
125
+ const { values, vectors } = eig;
126
+ const gt = vectors.map((v) => dot(v, g));
127
+ const combine = (coef) => {
128
+ const p = new Array(m).fill(0);
129
+ coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
130
+ return p;
131
+ };
132
+ const minValue = Math.min(...values);
133
+ // the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
134
+ // directions, and the step is inside the region
135
+ if (minValue > -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
136
+ const p = combine(values.map((l, k) => (l > zero ? -gt[k] / l : 0)));
137
+ if (norm(p) <= radius)
138
+ return { step: p, newton: true };
139
+ }
140
+ // on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
141
+ const lowest = Math.max(0, -minValue);
142
+ const lengthAt = (mu) => Math.sqrt(values.reduce((sum, l, k) => sum + (gt[k] / (l + mu)) ** 2, 0));
143
+ const tiny = Math.max(zero, 1e-12 * Math.max(...values.map(Math.abs), 1));
144
+ if (lengthAt(lowest + tiny) >= radius) {
145
+ let lo = lowest + tiny;
146
+ let hi = lowest + norm(g) / radius + Math.max(...values.map(Math.abs)) + tiny;
147
+ for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
148
+ const mid = (lo + hi) / 2;
149
+ if (lengthAt(mid) > radius)
150
+ lo = mid;
151
+ else
152
+ hi = mid;
153
+ }
154
+ return { step: combine(values.map((l, k) => -gt[k] / (l + hi))), newton: false };
155
+ }
156
+ // the "hard case": the gradient has (almost) no component along the eigenvectors of the lowest eigenvalue; the
157
+ // step at μ = −λ_min is completed to the boundary along such an eigenvector
158
+ const low = values.map((l) => l + lowest <= tiny);
159
+ const p = combine(values.map((l, k) => (low[k] ? 0 : -gt[k] / (l + lowest))));
160
+ const k0 = values.indexOf(minValue);
161
+ const rest = Math.sqrt(Math.max(0, radius * radius - dot(p, p)));
162
+ const direction = -Math.sign(gt[k0]) || 1;
163
+ return { step: p.map((pi, i) => pi + direction * rest * vectors[k0][i]), newton: false };
164
+ }
165
+ /**
166
+ * The columns of the blocks T_k as lists of θ indices, the diagonal element first: changing the sign of a column
167
+ * leaves the criterion unchanged (Λ_θ → Λ_θ D with D = diag(±1) per level, matched by u → D u)
168
+ */
169
+ function columnsOfTheta(s) {
170
+ const out = [];
171
+ for (const t of s.terms) {
172
+ const nc = t.columns.length;
173
+ let k = t.thetaOffset;
174
+ for (let c = 0; c < nc; c++) {
175
+ const column = [];
176
+ for (let i = c; i < nc; i++)
177
+ column.push(k++);
178
+ out.push(column);
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+ /** The criterion and its gradient from the sparse {@link profiledDeviance} */
184
+ const sparseCriterion = (s, theta, reml) => {
185
+ const r = profiledDeviance(s, theta, reml, { gradient: true });
186
+ return { f: r.deviance, g: r.gradient };
187
+ };
188
+ /** The minimiser of the criterion over θ, subject to the lower bounds (see the header) */
189
+ function minimiseCriterion(s, reml, criterion) {
190
+ const diagonal = s.lower.map((b) => b === 0);
191
+ const evaluate = (theta) => criterion(s, theta, reml);
192
+ let theta = s.theta.slice();
193
+ let { f, g } = evaluate(theta);
194
+ /** Diagonal elements held at exactly 0 */
195
+ const fixed = new Set();
196
+ /** Diagonal elements released from 0 (not set to 0 again: their minimiser is near 0 but not at it) */
197
+ const released = new Set();
198
+ const scaleOf = () => Math.max(1, ...theta.map(Math.abs));
199
+ const gradientTolerance = () => GRADIENT_TOLERANCE * Math.max(1, Math.abs(f));
200
+ let radius = INITIAL_RADIUS * scaleOf();
201
+ let previousNewton = Infinity;
202
+ /** The Hessian of the last iteration, when it may be used again (see iterate) */
203
+ let reusable;
204
+ /** The Hessian on the elements `set`, from central differences of the gradient */
205
+ const hessian = (set) => {
206
+ const floor = HESSIAN_STEP_FLOOR * scaleOf();
207
+ const cols = set.map((j) => {
208
+ const h = Math.max(HESSIAN_STEP * Math.abs(theta[j]), floor);
209
+ const plus = theta.slice();
210
+ plus[j] = theta[j] + h;
211
+ const minus = theta.slice();
212
+ minus[j] = theta[j] - h;
213
+ const gp = evaluate(plus).g;
214
+ const gm = evaluate(minus).g;
215
+ return set.map((i) => (gp[i] - gm[i]) / (2 * h));
216
+ });
217
+ return set.map((_, a) => set.map((_, b) => (cols[a][b] + cols[b][a]) / 2));
218
+ };
219
+ /** One trust-region iteration on the free elements; returns whether it converged */
220
+ const iterate = (free) => {
221
+ const fresh = reusable === undefined || reusable.free.length !== free.length || reusable.free.some((j, a) => j !== free[a]);
222
+ const h = fresh ? hessian(free) : reusable.h;
223
+ reusable = undefined;
224
+ const eig = symmetricEigen(h);
225
+ const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
226
+ const gFree = free.map((j) => g[j]);
227
+ const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
228
+ const trial = theta.slice();
229
+ free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
230
+ const size = Math.max(...step.map(Math.abs)) / scaleOf();
231
+ const next = evaluate(trial);
232
+ if (!Number.isFinite(next.f))
233
+ throw new Error(OPTIMISATION_FAILED);
234
+ const predicted = -(dot(gFree, step) + dot(step, h.map((row) => dot(row, step))) / 2);
235
+ // the actual reduction from the values, or, where they are equal to rounding, from the gradients (trapezoid)
236
+ const actual = Math.abs(f - next.f) > 1e-10 * Math.abs(f) ? f - next.f : -(dot(gFree, step) + dot(free.map((j) => next.g[j]), step)) / 2;
237
+ const ratio = predicted > 0 ? actual / predicted : actual >= 0 ? 1 : -1;
238
+ if (ratio > 0.1 || size <= STEP_FLOOR) {
239
+ theta = trial;
240
+ f = next.f;
241
+ g = next.g;
242
+ }
243
+ const length = norm(step);
244
+ if (ratio < 0.25)
245
+ radius = Math.max(length / 4, STEP_TOLERANCE * scaleOf());
246
+ else if (ratio > 0.75 && length >= 0.99 * radius)
247
+ radius *= 2;
248
+ if (!newton) {
249
+ previousNewton = Infinity;
250
+ return false;
251
+ }
252
+ const gradientSmall = free.every((j) => Math.abs(g[j]) <= gradientTolerance());
253
+ // (the steps stopping decreasing is taken as rounding level only with a fresh Hessian)
254
+ const done = gradientSmall && (size <= STEP_TOLERANCE || (fresh && size <= STEP_FLOOR && size >= 0.5 * previousNewton));
255
+ // the Hessian is kept for the next iteration after a Newton step that was accepted, predicted well and at most
256
+ // half the previous one (the model is still good; convergence stays fast)
257
+ if (ratio > HESSIAN_REUSE_RATIO && ratio < 1 / HESSIAN_REUSE_RATIO && size < 0.5 * previousNewton)
258
+ reusable = { free, h };
259
+ previousNewton = size;
260
+ return done;
261
+ };
262
+ /**
263
+ * At a converged point with elements held at 0: a direction of negative curvature of the elements held there
264
+ * whose derivative vanishes, together with the free ones, is a way down (in a block whose leading diagonal element
265
+ * is 0, the criterion depends on it and the element below through their product, so neither alone shows the
266
+ * descent; for a single even element it is its own curvature at 0). If there is one, the elements held at 0 along
267
+ * it are released and θ is moved a little along it; returns whether it did.
268
+ */
269
+ const leaveAlongNegativeCurvature = () => {
270
+ if (fixed.size === 0)
271
+ return false;
272
+ const set = theta.map((_, j) => j);
273
+ const eig = symmetricEigen(hessian(set));
274
+ const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
275
+ const k = eig.values.indexOf(Math.min(...eig.values));
276
+ if (!(eig.values[k] < -zero))
277
+ return false;
278
+ const v = eig.vectors[k];
279
+ const leaving = set.filter((j, a) => fixed.has(j) && Math.abs(v[a]) > 1e-8);
280
+ if (leaving.length === 0)
281
+ return false;
282
+ for (const j of leaving) {
283
+ fixed.delete(j);
284
+ released.add(j);
285
+ }
286
+ const move = NEGATIVE_CURVATURE_MOVE * scaleOf();
287
+ set.forEach((j, a) => (theta[j] = theta[j] + move * v[a]));
288
+ ({ f, g } = evaluate(theta));
289
+ return true;
290
+ };
291
+ for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
292
+ const free = theta.map((_, j) => j).filter((j) => !fixed.has(j));
293
+ if (free.length > 0 && !iterate(free))
294
+ continue;
295
+ // converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
296
+ const toZero = free.filter((j) => diagonal[j] && !released.has(j) && Math.abs(theta[j]) < BOUNDARY_CANDIDATE * scaleOf());
297
+ if (toZero.length > 0) {
298
+ for (const j of toZero) {
299
+ theta[j] = 0;
300
+ fixed.add(j);
301
+ }
302
+ ({ f, g } = evaluate(theta));
303
+ previousNewton = Infinity;
304
+ reusable = undefined;
305
+ continue;
306
+ }
307
+ // elements held at 0 with a derivative, or with a direction of negative curvature, are released
308
+ const tolerance = 1e-12 * Math.max(1, Math.abs(f));
309
+ const release = [...fixed].filter((j) => Math.abs(g[j]) > tolerance);
310
+ if (release.length > 0) {
311
+ for (const j of release) {
312
+ fixed.delete(j);
313
+ released.add(j);
314
+ }
315
+ }
316
+ else if (!leaveAlongNegativeCurvature()) {
317
+ // the minimiser: each column of T_k with a negative diagonal element changes sign (an equivalent θ)
318
+ for (const column of columnsOfTheta(s)) {
319
+ if (theta[column[0]] < 0)
320
+ for (const j of column)
321
+ theta[j] = -theta[j];
322
+ }
323
+ return theta.map((v) => (v === 0 ? 0 : v)); // no -0
324
+ }
325
+ radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
326
+ previousNewton = Infinity;
327
+ reusable = undefined;
328
+ }
329
+ throw new Error(OPTIMISATION_FAILED);
330
+ }
331
+ /**
332
+ * Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
333
+ * quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
334
+ * `ranef()`, `fitted()`, `residuals()`, `logLik()`, `AIC()`, `BIC()`, `deviance()`, `REMLcrit()` and `isSingular()`.
335
+ *
336
+ * The formula has random-effects terms `(lhs | group)` (correlated effects of the columns of `lhs` within each level
337
+ * of `group`) or `(lhs || group)` (uncorrelated); `group` may be `a:b` (the combinations), `a/b` (nested: `b:a` and
338
+ * `a`) and so on, as in lme4. The fixed-effects part is coded as in {@link lm}; aliased columns are dropped (with a
339
+ * message). Rows with a missing value in a variable of the formula are dropped (`rows` lists those used).
340
+ *
341
+ * The covariance parameters θ are the lower triangles of the relative covariance factors of the terms; the estimate
342
+ * is the exact minimiser of the profiled criterion (lme4's optimiser stops close to it, so lme4's values typically
343
+ * differ in the 5th to 9th significant digit). Elements on the boundary are exactly 0, and the fit is then singular.
344
+ * The computation is sparse (a sparse Cholesky factorisation, as in lme4), so many groups are handled quickly.
345
+ *
346
+ * @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
347
+ * @param data The data frame: an object of columns.
348
+ * @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * // R: lme4::lmer(y ~ 1 + (1 | g), data)
353
+ * const fit = lmer("y ~ 1 + (1 | g)", {
354
+ * y: [9.8, 10.4, 10.1, 12.3, 12.9, 12.0, 8.1, 7.6, 8.4],
355
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
356
+ * });
357
+ * fit.fixef; // [10.177778]
358
+ * fit.sigma; // 0.39299
359
+ * fit.varCorr[0].sd; // [2.1726]
360
+ * fit.ranef[0].levels; // ["a", "b", "c"]
361
+ * fit.ranef[0].values; // [[-0.076939], [2.1982], [-2.1213]]
362
+ * fit.REMLcrit; // 19.015
363
+ * ```
364
+ *
365
+ * @category Mixed models
366
+ */
367
+ export function lmer(formula, data, options = {}) {
368
+ return lmerWithCriterion(formula, data, options, sparseCriterion);
369
+ }
370
+ /**
371
+ * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
372
+ * test of the sparse computation fits with the dense reference implementation through it.
373
+ */
374
+ export function lmerWithCriterion(formula, data, options, criterion) {
375
+ const reml = options.REML ?? true;
376
+ const modelOptions = {};
377
+ if (options.contrasts !== undefined)
378
+ modelOptions.contrasts = options.contrasts;
379
+ if (options.levels !== undefined)
380
+ modelOptions.levels = options.levels;
381
+ const s = mixedModelStructure(formula, data, modelOptions);
382
+ const theta = minimiseCriterion(s, reml, criterion);
383
+ const r = profiledDeviance(s, theta, reml, { rxInverse: true });
384
+ const n = s.y.length;
385
+ const p = s.xColNames.length;
386
+ const twoPi = 2 * Math.PI;
387
+ const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n));
388
+ const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)));
389
+ const sigma2 = r.prss / (reml ? n - p : n);
390
+ const sigma = Math.sqrt(sigma2);
391
+ const vcov = r.rxInverse.map((row) => row.map((v) => sigma2 * v));
392
+ const stdError = vcov.map((row, i) => Math.sqrt(row[i]));
393
+ const tValue = r.beta.map((b, i) => b / stdError[i]);
394
+ // the blocks T_k and the variance components
395
+ const varCorr = s.terms.map((term) => {
396
+ const nc = term.columns.length;
397
+ const t = Array.from({ length: nc }, () => new Array(nc).fill(0));
398
+ let k = term.thetaOffset;
399
+ for (let j = 0; j < nc; j++)
400
+ for (let i = j; i < nc; i++)
401
+ t[i][j] = theta[k++];
402
+ const cov = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
403
+ const sd = cov.map((row, i) => Math.sqrt(row[i]));
404
+ const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
405
+ return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
406
+ });
407
+ const ranef = s.groups.map((g, gi) => {
408
+ const terms = s.terms.filter((t) => t.group === gi);
409
+ return {
410
+ group: g.name,
411
+ levels: [...g.levels],
412
+ columns: terms.flatMap((t) => t.columns),
413
+ values: g.levels.map((_, l) => terms.flatMap((t) => {
414
+ const nc = t.columns.length;
415
+ return t.columns.map((_, j) => r.b[t.zOffset + l * nc + j]);
416
+ })),
417
+ };
418
+ });
419
+ const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
420
+ s.z.forEach((col, j) => {
421
+ const bj = r.b[j];
422
+ if (bj !== 0)
423
+ col.rows.forEach((i, k) => (fitted[i] += col.values[k] * bj));
424
+ });
425
+ const residuals = s.y.map((y, i) => y - fitted[i]);
426
+ const logLik = -(reml ? REMLcrit : deviance) / 2;
427
+ const df = p + theta.length + 1;
428
+ const singular = theta.some((v, j) => s.lower[j] === 0 && v < 1e-4);
429
+ const messages = [...s.messages];
430
+ if (singular)
431
+ messages.push("boundary (singular) fit: see help('isSingular')");
432
+ return {
433
+ formula,
434
+ REML: reml,
435
+ nObs: n,
436
+ rows: [...s.rows],
437
+ theta,
438
+ fixefNames: [...s.xColNames],
439
+ fixef: r.beta,
440
+ coefTable: { estimate: [...r.beta], stdError, tValue },
441
+ vcov,
442
+ sigma,
443
+ varCorr,
444
+ ranef,
445
+ fitted,
446
+ residuals,
447
+ logLik,
448
+ df,
449
+ AIC: -2 * logLik + 2 * df,
450
+ BIC: -2 * logLik + Math.log(n) * df,
451
+ deviance,
452
+ REMLcrit,
453
+ singular,
454
+ messages,
455
+ warnings: [...s.warnings],
456
+ };
457
+ }
@@ -0,0 +1,44 @@
1
+ import type { MixedModelStructure } from "./mixedStructure.js";
2
+ /** The penalised least-squares solution and the profiled deviance at a given θ. */
3
+ export interface ProfiledDeviance {
4
+ /** The REML criterion (`reml` true) or the ML deviance −2 log L (`reml` false), profiled over β and σ. */
5
+ deviance: number;
6
+ /** The fixed effects β̂ that minimise the penalised residual sum of squares (one per column of X). */
7
+ beta: number[];
8
+ /** The spherical random effects û (one per column of Z). */
9
+ u: number[];
10
+ /** The random effects b = Λ_θ û. */
11
+ b: number[];
12
+ /** The residual sum of squares ‖y − Xβ̂ − ZΛ_θ û‖². */
13
+ rss: number;
14
+ /** The penalty ‖û‖². */
15
+ ussq: number;
16
+ /** The penalised residual sum of squares rss + ussq. */
17
+ prss: number;
18
+ /** log det(Λ_θ' Z'Z Λ_θ + I): twice the log determinant of its Cholesky factor L_θ. */
19
+ logDetL: number;
20
+ /** log det(X'X − X'ZΛ_θ (Λ_θ'Z'ZΛ_θ + I)⁻¹ Λ_θ'Z'X): twice the log determinant of R_X. */
21
+ logDetRX: number;
22
+ /** The derivative of `deviance` with respect to each element of θ (with `options.gradient`). */
23
+ gradient?: number[];
24
+ /** (R_X' R_X)⁻¹, p × p, array of rows (with `options.rxInverse`): the covariance of β̂ divided by σ². */
25
+ rxInverse?: number[][];
26
+ }
27
+ /** What {@link profiledDeviance} computes beyond the deviance and the penalised least-squares solution. */
28
+ export interface ProfiledDevianceOptions {
29
+ /** Also the gradient of the criterion with respect to θ (from the selected inverse of A). */
30
+ gradient?: boolean;
31
+ /** Also (R_X' R_X)⁻¹. */
32
+ rxInverse?: boolean;
33
+ }
34
+ /**
35
+ * The profiled deviance of a linear mixed model at `theta`, with the penalised least-squares solution
36
+ * (oracle/lmer-behaviour.md, stage 1b; computed sparsely). Internal: not exported from the package.
37
+ *
38
+ * @param structure The structure from {@link mixedModelStructure}.
39
+ * @param theta The covariance parameters (finite, of the length of `structure.theta`; values below the lower bounds
40
+ * are accepted).
41
+ * @param reml Whether to return the REML criterion (true) or the ML deviance (false).
42
+ * @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
43
+ */
44
+ export declare function profiledDeviance(structure: MixedModelStructure, theta: readonly number[], reml: boolean, options?: ProfiledDevianceOptions): ProfiledDeviance;