@numero-uno-jpn/rstats 0.17.0 → 1.1.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 (97) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.ja.md +20 -12
  3. package/README.md +22 -12
  4. package/THIRD_PARTY_NOTICES.md +3 -2
  5. package/dist/chunks/{chunk-4WE3OO62.js → chunk-4KCSBTR5.js} +2 -2
  6. package/dist/chunks/chunk-4VRMAYPY.js +3 -0
  7. package/dist/chunks/{chunk-RFE7MVP7.js → chunk-7IJCUSA5.js} +2 -2
  8. package/dist/chunks/chunk-7KJ24LYK.js +2 -0
  9. package/dist/chunks/{chunk-Z37NELOS.js → chunk-DR4GQ7PW.js} +1 -1
  10. package/dist/chunks/chunk-DTJG2IL2.js +2 -0
  11. package/dist/chunks/{chunk-C7V2FH6L.js → chunk-EJYCDE4Z.js} +1 -1
  12. package/dist/chunks/{chunk-LV3W2F7N.js → chunk-GGJA3JRO.js} +2 -2
  13. package/dist/chunks/{chunk-H3WVPZDL.js → chunk-GJEKNJP7.js} +2 -2
  14. package/dist/chunks/{chunk-2C33MXSW.js → chunk-GRUQRNX7.js} +2 -2
  15. package/dist/chunks/chunk-GYGQUYEP.js +2 -0
  16. package/dist/chunks/chunk-HRA7PCQT.js +2 -0
  17. package/dist/chunks/{chunk-WM7VFXTV.js → chunk-HUWOSLKE.js} +1 -1
  18. package/dist/chunks/{chunk-TNMJPQPV.js → chunk-HZLSNJQM.js} +2 -2
  19. package/dist/chunks/{chunk-ZFQWB222.js → chunk-JNWWLNE3.js} +2 -2
  20. package/dist/chunks/{chunk-DXI5N2ET.js → chunk-N5BDSMXS.js} +1 -1
  21. package/dist/chunks/{chunk-LHUIJQHY.js → chunk-NDTJ23A6.js} +2 -2
  22. package/dist/chunks/{chunk-SE7V2KLO.js → chunk-OG7UORIX.js} +1 -1
  23. package/dist/chunks/{chunk-ONY5CISH.js → chunk-QUTJEYDX.js} +2 -2
  24. package/dist/chunks/chunk-U7BRXOUS.js +2 -0
  25. package/dist/chunks/{chunk-FY3FVOBM.js → chunk-UMLMY4XS.js} +2 -2
  26. package/dist/chunks/{chunk-6JJQL6HL.js → chunk-X4J6UJHN.js} +2 -2
  27. package/dist/chunks/{chunk-34S5SQY6.js → chunk-Y4YWLSWU.js} +2 -2
  28. package/dist/chunks/{chunk-5AYHCITP.js → chunk-YN5MLKDL.js} +2 -2
  29. package/dist/chunks/{chunk-CZI7KUO3.js → chunk-Z2HGLFZN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions/signrank.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/mixed.d.ts +6 -0
  34. package/dist/entries/mixed.js +6 -1
  35. package/dist/entries/tests.d.ts +1 -1
  36. package/dist/htest/ansariTest.js +32 -34
  37. package/dist/htest/cor.d.ts +2 -2
  38. package/dist/htest/cor.js +2 -1
  39. package/dist/htest/core/scoreDistribution.d.ts +39 -0
  40. package/dist/htest/core/scoreDistribution.js +151 -0
  41. package/dist/htest/wilcoxTest.d.ts +23 -8
  42. package/dist/htest/wilcoxTest.js +521 -199
  43. package/dist/linalg/chol.d.ts +3 -3
  44. package/dist/linalg/chol.js +10 -2
  45. package/dist/linalg/qr.js +39 -15
  46. package/dist/linalg.js +2 -2
  47. package/dist/mixed.js +5 -4
  48. package/dist/models/anovaSequential.d.ts +16 -1
  49. package/dist/models/anovaSequential.js +40 -5
  50. package/dist/models/aovStrata.js +21 -4
  51. package/dist/models/formula.d.ts +5 -2
  52. package/dist/models/formula.js +31 -8
  53. package/dist/models/glm.d.ts +15 -4
  54. package/dist/models/glm.js +13 -6
  55. package/dist/models/glmer.d.ts +255 -0
  56. package/dist/models/glmer.js +635 -0
  57. package/dist/models/glmerAnova.d.ts +81 -0
  58. package/dist/models/glmerAnova.js +139 -0
  59. package/dist/models/glmerDeviance.d.ts +98 -0
  60. package/dist/models/glmerDeviance.js +576 -0
  61. package/dist/models/glmerFamily.d.ts +57 -0
  62. package/dist/models/glmerFamily.js +236 -0
  63. package/dist/models/glmerGradient.d.ts +46 -0
  64. package/dist/models/glmerGradient.js +301 -0
  65. package/dist/models/glmerStructure.d.ts +45 -0
  66. package/dist/models/glmerStructure.js +168 -0
  67. package/dist/models/glmerSummary.d.ts +102 -0
  68. package/dist/models/glmerSummary.js +94 -0
  69. package/dist/models/lmer.d.ts +16 -0
  70. package/dist/models/lmer.js +55 -306
  71. package/dist/models/lmerAnova.d.ts +49 -0
  72. package/dist/models/lmerAnova.js +91 -40
  73. package/dist/models/lmerTest.d.ts +8 -1
  74. package/dist/models/lmerTest.js +21 -8
  75. package/dist/models/mixedDeviance.d.ts +28 -2
  76. package/dist/models/mixedDeviance.js +84 -56
  77. package/dist/models/mixedMinimiser.d.ts +83 -0
  78. package/dist/models/mixedMinimiser.js +438 -0
  79. package/dist/models/mixedPredict.d.ts +121 -0
  80. package/dist/models/mixedPredict.js +530 -0
  81. package/dist/models/mixedStructure.d.ts +62 -3
  82. package/dist/models/mixedStructure.js +74 -29
  83. package/dist/models/modelMatrix.d.ts +8 -1
  84. package/dist/models/modelMatrix.js +49 -37
  85. package/dist/models/survival.d.ts +4 -1
  86. package/dist/models/survival.js +7 -1
  87. package/dist/numerics.js +2 -2
  88. package/dist/rstats.js +16 -16
  89. package/dist/special.js +2 -2
  90. package/dist/tests.js +13 -14
  91. package/llms.txt +11 -3
  92. package/package.json +1 -1
  93. package/dist/chunks/chunk-M4ITG7YR.js +0 -2
  94. package/dist/chunks/chunk-NSYZTS26.js +0 -2
  95. package/dist/chunks/chunk-THIGHOKK.js +0 -2
  96. package/dist/chunks/chunk-WMDYDTVQ.js +0 -2
  97. package/dist/chunks/chunk-XLSFJTTK.js +0 -2
@@ -6,7 +6,8 @@
6
6
  // Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1c, "The fit and its results") and
7
7
  // D. Bates, M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of
8
8
  // Statistical Software 67(1). The structure comes from src/models/mixedStructure.ts and the criterion with its
9
- // analytic gradient from src/models/mixedDeviance.ts.
9
+ // analytic gradient from src/models/mixedDeviance.ts. The minimiser described below is in src/models/mixedMinimiser.ts
10
+ // (shared with glmer).
10
11
  //
11
12
  // The criterion does not change when a column of a block T_k changes sign (Λ_θ → Λ_θ D with D = diag(±1) per level,
12
13
  // matched by u → D u), so the bounds θ_jj ≥ 0 on the diagonal elements only choose one of equivalent parameter
@@ -53,40 +54,15 @@
53
54
  // on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
54
55
  // from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
55
56
  // 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
56
- import { ldexp, norm2 } from "../internal/summary.js";
57
+ import { ldexp } from "../internal/summary.js";
57
58
  import { qr, qrCoef } from "../linalg/qr.js";
58
59
  import { profiledDeviance } from "./mixedDeviance.js";
59
60
  import { mixedModelStructure } from "./mixedStructure.js";
60
- import { maxOf, minOf } from "../internal/extremes.js";
61
+ import { LMER_SETTINGS, minimiseWithRestarts } from "./mixedMinimiser.js";
61
62
  import { reported } from "../internal/warnings.js";
62
63
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
63
64
  import { checkOptions } from "../internal/checkOptions.js";
64
65
  const LMER_KEYS = ["REML", "contrasts", "levels"];
65
- /** Initial trust-region radius, relative to max(1, max |θ|) */
66
- const INITIAL_RADIUS = 0.25;
67
- /** Step of the central differences of the gradient that give the Hessian, relative to |θ_j| ... */
68
- const HESSIAN_STEP = 1e-4;
69
- /** ... and at least this (relative to max(1, max |θ|)), for elements at or near 0 */
70
- const HESSIAN_STEP_FLOOR = 1e-6;
71
- /** Eigenvalues of the Hessian below this times the largest are treated as 0 (the Hessian's own accuracy) */
72
- const EIGENVALUE_TOLERANCE = 1e-6;
73
- /** Diagonal elements below this (relative to max(1, max |θ|)) at convergence are candidates for the boundary */
74
- const BOUNDARY_CANDIDATE = 1e-4;
75
- /** The move along a direction of negative curvature that leaves the boundary (relative to max(1, max |θ|)) */
76
- const NEGATIVE_CURVATURE_MOVE = 1e-3;
77
- /** Converged when the Newton step is below this, relative to max(1, max |θ|) ... */
78
- const STEP_TOLERANCE = 1e-13;
79
- /** ... or when the steps stop decreasing (rounding level) below this; steps this small are always accepted */
80
- const STEP_FLOOR = 1e-10;
81
- /** The gradient on the free elements at convergence must be below this times max(1, |criterion|) */
82
- const GRADIENT_TOLERANCE = 1e-9;
83
- const MAX_ITERATIONS = 500;
84
- /** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
85
- const HESSIAN_REUSE_RATIO = 0.75;
86
- /** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
87
- const RESTART_THRESHOLD = 1e-8;
88
- /** ... and there are at most this many restarts */
89
- const MAX_RESTARTS = 50;
90
66
  /**
91
67
  * The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y|: a
92
68
  * few times the rounding error of the residuals, so that a response with a large mean and a small spread (around
@@ -96,122 +72,11 @@ const MAX_RESTARTS = 50;
96
72
  const EXACT_FIT = 16 * Number.EPSILON;
97
73
  const EXACT_FIT_ERROR = "lmer: the response is fitted exactly by the fixed effects (a constant response, for example), so the residual variance is 0";
98
74
  const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
99
- /** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
100
- function symmetricEigen(a0) {
101
- // entries of extreme magnitude are scaled by a power of 2 (exact) first and the eigenvalues scaled back: the sums of
102
- // squares below overflowed for entries around 1e200 (Infinity <= 1e-32 Infinity ended the sweeps at once)
103
- let mx = 0;
104
- for (const row of a0)
105
- for (const v of row)
106
- mx = Math.max(mx, Math.abs(v));
107
- const k = mx === 0 || !Number.isFinite(mx) || (mx >= 2 ** -256 && mx <= 2 ** 256) ? 0 : Math.floor(Math.log2(mx));
108
- if (k !== 0) {
109
- const r = symmetricEigen(a0.map((row) => row.map((v) => ldexp(v, -k))));
110
- return { values: r.values.map((v) => ldexp(v, k)), vectors: r.vectors };
111
- }
112
- const m = a0.length;
113
- const a = a0.map((row) => row.slice());
114
- const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
115
- for (let sweep = 0; sweep < 100; sweep++) {
116
- let off = 0;
117
- let total = 0;
118
- for (let i = 0; i < m; i++) {
119
- for (let j = 0; j < m; j++) {
120
- total += a[i][j] ** 2;
121
- if (i !== j)
122
- off += a[i][j] ** 2;
123
- }
124
- }
125
- if (off <= 1e-32 * total)
126
- break;
127
- for (let p = 0; p < m - 1; p++) {
128
- for (let q = p + 1; q < m; q++) {
129
- const apq = a[p][q];
130
- if (apq === 0)
131
- continue;
132
- const tau = (a[q][q] - a[p][p]) / (2 * apq);
133
- const t = Math.sign(tau || 1) / (Math.abs(tau) + Math.sqrt(1 + tau * tau));
134
- const c = 1 / Math.sqrt(1 + t * t);
135
- const sn = t * c;
136
- for (let k = 0; k < m; k++) {
137
- const akp = a[k][p];
138
- const akq = a[k][q];
139
- a[k][p] = c * akp - sn * akq;
140
- a[k][q] = sn * akp + c * akq;
141
- }
142
- for (let k = 0; k < m; k++) {
143
- const apk = a[p][k];
144
- const aqk = a[q][k];
145
- a[p][k] = c * apk - sn * aqk;
146
- a[q][k] = sn * apk + c * aqk;
147
- }
148
- for (let k = 0; k < m; k++) {
149
- const vkp = v[k][p];
150
- const vkq = v[k][q];
151
- v[k][p] = c * vkp - sn * vkq;
152
- v[k][q] = sn * vkp + c * vkq;
153
- }
154
- }
155
- }
156
- }
157
- return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
158
- }
159
- // without overflow of the squares (src/internal/summary.ts)
160
- const norm = norm2;
161
- const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
162
- /**
163
- * The step p that minimises g'p + p'Hp/2 subject to ‖p‖ ≤ radius (H = V diag(λ) V'), and whether it is the Newton
164
- * step. Eigenvalues within `zero` of 0 are treated as 0: along their eigenvectors the criterion is flat to the
165
- * accuracy of the Hessian (as along a set of equivalent minimisers), and the Newton step leaves them out when the
166
- * gradient's component there is below `gradientZero`.
167
- */
168
- function trustRegionStep(g, eig, radius, zero, gradientZero) {
169
- const m = g.length;
170
- const { values, vectors } = eig;
171
- const gt = vectors.map((v) => dot(v, g));
172
- const combine = (coef) => {
173
- const p = new Array(m).fill(0);
174
- coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
175
- return p;
176
- };
177
- const minValue = minOf(values);
178
- // the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
179
- // directions, and the step is inside the region
180
- if (minValue > -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
181
- const p = combine(values.map((l, k) => (l > zero ? -gt[k] / l : 0)));
182
- if (norm(p) <= radius)
183
- return { step: p, newton: true };
184
- }
185
- // on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
186
- const lowest = Math.max(0, -minValue);
187
- const lengthAt = (mu) => norm2(values.map((l, k) => gt[k] / (l + mu)));
188
- const tiny = Math.max(zero, 1e-12 * Math.max(maxOf(values.map(Math.abs)), 1));
189
- if (lengthAt(lowest + tiny) >= radius) {
190
- let lo = lowest + tiny;
191
- let hi = lowest + norm(g) / radius + maxOf(values.map(Math.abs)) + tiny;
192
- for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
193
- const mid = (lo + hi) / 2;
194
- if (lengthAt(mid) > radius)
195
- lo = mid;
196
- else
197
- hi = mid;
198
- }
199
- return { step: combine(values.map((l, k) => -gt[k] / (l + hi))), newton: false };
200
- }
201
- // the "hard case": the gradient has (almost) no component along the eigenvectors of the lowest eigenvalue; the
202
- // step at μ = −λ_min is completed to the boundary along such an eigenvector
203
- const low = values.map((l) => l + lowest <= tiny);
204
- const p = combine(values.map((l, k) => (low[k] ? 0 : -gt[k] / (l + lowest))));
205
- const k0 = values.indexOf(minValue);
206
- const rest = Math.sqrt(Math.max(0, radius * radius - dot(p, p)));
207
- const direction = -Math.sign(gt[k0]) || 1;
208
- return { step: p.map((pi, i) => pi + direction * rest * vectors[k0][i]), newton: false };
209
- }
210
75
  /**
211
76
  * The columns of the blocks T_k as lists of θ indices, the diagonal element first: changing the sign of a column
212
77
  * leaves the criterion unchanged (Λ_θ → Λ_θ D with D = diag(±1) per level, matched by u → D u)
213
78
  */
214
- function columnsOfTheta(s) {
79
+ export function columnsOfTheta(s) {
215
80
  const out = [];
216
81
  for (const t of s.terms) {
217
82
  const nc = t.columns.length;
@@ -230,151 +95,16 @@ const sparseCriterion = (s, theta, reml) => {
230
95
  const r = profiledDeviance(s, theta, reml, { gradient: true });
231
96
  return { f: r.deviance, g: r.gradient };
232
97
  };
233
- /**
234
- * A local minimiser of the criterion over θ, subject to the lower bounds (see the header), started at `start`, with
235
- * the elements in `held` kept at exactly 0 throughout (never free, never released); with its criterion
236
- */
237
- function localMinimum(s, reml, criterion, start, held = new Set()) {
238
- const diagonal = s.lower.map((b) => b === 0);
239
- const evaluate = (theta) => criterion(s, theta, reml);
240
- let theta = start.map((v, j) => (held.has(j) ? 0 : v));
241
- let { f, g } = evaluate(theta);
242
- /** Diagonal elements held at exactly 0 */
243
- const fixed = new Set();
244
- /** Diagonal elements released from 0 (not set to 0 again: their minimiser is near 0 but not at it) */
245
- const released = new Set();
246
- const scaleOf = () => Math.max(1, ...theta.map(Math.abs));
247
- const gradientTolerance = () => GRADIENT_TOLERANCE * Math.max(1, Math.abs(f));
248
- let radius = INITIAL_RADIUS * scaleOf();
249
- let previousNewton = Infinity;
250
- /** The Hessian of the last iteration, when it may be used again (see iterate) */
251
- let reusable;
252
- /** The Hessian on the elements `set`, from central differences of the gradient */
253
- const hessian = (set) => {
254
- const floor = HESSIAN_STEP_FLOOR * scaleOf();
255
- const cols = set.map((j) => {
256
- const h = Math.max(HESSIAN_STEP * Math.abs(theta[j]), floor);
257
- const plus = theta.slice();
258
- plus[j] = theta[j] + h;
259
- const minus = theta.slice();
260
- minus[j] = theta[j] - h;
261
- const gp = evaluate(plus).g;
262
- const gm = evaluate(minus).g;
263
- return set.map((i) => (gp[i] - gm[i]) / (2 * h));
264
- });
265
- return set.map((_, a) => set.map((_, b) => (cols[a][b] + cols[b][a]) / 2));
266
- };
267
- /** One trust-region iteration on the free elements; returns whether it converged */
268
- const iterate = (free) => {
269
- const fresh = reusable === undefined || reusable.free.length !== free.length || reusable.free.some((j, a) => j !== free[a]);
270
- const h = fresh ? hessian(free) : reusable.h;
271
- reusable = undefined;
272
- const eig = symmetricEigen(h);
273
- const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
274
- const gFree = free.map((j) => g[j]);
275
- const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
276
- const trial = theta.slice();
277
- free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
278
- const size = maxOf(step.map(Math.abs)) / scaleOf();
279
- const next = evaluate(trial);
280
- if (!Number.isFinite(next.f))
281
- throw new Error(OPTIMISATION_FAILED);
282
- const predicted = -(dot(gFree, step) + dot(step, h.map((row) => dot(row, step))) / 2);
283
- // the actual reduction from the values, or, where they are equal to rounding, from the gradients (trapezoid)
284
- 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;
285
- const ratio = predicted > 0 ? actual / predicted : actual >= 0 ? 1 : -1;
286
- if (ratio > 0.1 || size <= STEP_FLOOR) {
287
- theta = trial;
288
- f = next.f;
289
- g = next.g;
290
- }
291
- const length = norm(step);
292
- if (ratio < 0.25)
293
- radius = Math.max(length / 4, STEP_TOLERANCE * scaleOf());
294
- else if (ratio > 0.75 && length >= 0.99 * radius)
295
- radius *= 2;
296
- if (!newton) {
297
- previousNewton = Infinity;
298
- return false;
299
- }
300
- const gradientSmall = free.every((j) => Math.abs(g[j]) <= gradientTolerance());
301
- // (the steps stopping decreasing is taken as rounding level only with a fresh Hessian)
302
- const done = gradientSmall && (size <= STEP_TOLERANCE || (fresh && size <= STEP_FLOOR && size >= 0.5 * previousNewton));
303
- // the Hessian is kept for the next iteration after a Newton step that was accepted, predicted well and at most
304
- // half the previous one (the model is still good; convergence stays fast)
305
- if (ratio > HESSIAN_REUSE_RATIO && ratio < 1 / HESSIAN_REUSE_RATIO && size < 0.5 * previousNewton)
306
- reusable = { free, h };
307
- previousNewton = size;
308
- return done;
309
- };
310
- /**
311
- * At a converged point with elements held at 0: a direction of negative curvature of the elements held there
312
- * whose derivative vanishes, together with the free ones, is a way down (in a block whose leading diagonal element
313
- * is 0, the criterion depends on it and the element below through their product, so neither alone shows the
314
- * descent; for a single even element it is its own curvature at 0). If there is one, the elements held at 0 along
315
- * it are released and θ is moved a little along it; returns whether it did.
316
- */
317
- const leaveAlongNegativeCurvature = () => {
318
- if (fixed.size === 0)
319
- return false;
320
- const set = theta.map((_, j) => j).filter((j) => !held.has(j));
321
- const eig = symmetricEigen(hessian(set));
322
- const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
323
- const k = eig.values.indexOf(minOf(eig.values));
324
- if (!(eig.values[k] < -zero))
325
- return false;
326
- const v = eig.vectors[k];
327
- const leaving = set.filter((j, a) => fixed.has(j) && Math.abs(v[a]) > 1e-8);
328
- if (leaving.length === 0)
329
- return false;
330
- for (const j of leaving) {
331
- fixed.delete(j);
332
- released.add(j);
333
- }
334
- const move = NEGATIVE_CURVATURE_MOVE * scaleOf();
335
- set.forEach((j, a) => (theta[j] = theta[j] + move * v[a]));
336
- ({ f, g } = evaluate(theta));
337
- return true;
98
+ /** The minimisation problem of lmer's criterion over θ (src/models/mixedMinimiser.ts) */
99
+ function lmerProblem(s, reml, criterion) {
100
+ return {
101
+ evaluate: (theta) => criterion(s, theta, reml),
102
+ diagonal: s.lower.map((b) => b === 0),
103
+ columns: columnsOfTheta(s),
104
+ settings: LMER_SETTINGS,
105
+ rejectNonFinite: false,
106
+ failure: OPTIMISATION_FAILED,
338
107
  };
339
- for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
340
- const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
341
- if (free.length > 0 && !iterate(free))
342
- continue;
343
- // converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
344
- const toZero = free.filter((j) => diagonal[j] && !released.has(j) && Math.abs(theta[j]) < BOUNDARY_CANDIDATE * scaleOf());
345
- if (toZero.length > 0) {
346
- for (const j of toZero) {
347
- theta[j] = 0;
348
- fixed.add(j);
349
- }
350
- ({ f, g } = evaluate(theta));
351
- previousNewton = Infinity;
352
- reusable = undefined;
353
- continue;
354
- }
355
- // elements held at 0 with a derivative, or with a direction of negative curvature, are released
356
- const tolerance = 1e-12 * Math.max(1, Math.abs(f));
357
- const release = [...fixed].filter((j) => Math.abs(g[j]) > tolerance);
358
- if (release.length > 0) {
359
- for (const j of release) {
360
- fixed.delete(j);
361
- released.add(j);
362
- }
363
- }
364
- else if (!leaveAlongNegativeCurvature()) {
365
- // the minimiser: each column of T_k with a negative diagonal element changes sign (an equivalent θ)
366
- for (const column of columnsOfTheta(s)) {
367
- if (theta[column[0]] < 0)
368
- for (const j of column)
369
- theta[j] = -theta[j];
370
- }
371
- return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
372
- }
373
- radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
374
- previousNewton = Infinity;
375
- reusable = undefined;
376
- }
377
- throw new Error(OPTIMISATION_FAILED);
378
108
  }
379
109
  /**
380
110
  * The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
@@ -432,21 +162,7 @@ function minimiseCriterion(s, reml, criterion) {
432
162
  const nc = t.columns.length;
433
163
  return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
434
164
  });
435
- let best = localMinimum(s, reml, criterion, s.theta);
436
- for (let round = 0; round < MAX_RESTARTS; round++) {
437
- let candidate;
438
- for (const block of blocks) {
439
- if (block.every((j) => best.theta[j] === 0))
440
- continue;
441
- const removed = localMinimum(s, reml, criterion, best.theta, new Set(block));
442
- if (candidate === undefined || removed.f < candidate.f)
443
- candidate = removed;
444
- }
445
- if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
446
- return best.theta;
447
- best = localMinimum(s, reml, criterion, candidate.theta);
448
- }
449
- throw new Error(OPTIMISATION_FAILED);
165
+ return minimiseWithRestarts(lmerProblem(s, reml, criterion), s.theta, blocks).theta;
450
166
  }
451
167
  /**
452
168
  * The first option check of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section
@@ -540,6 +256,18 @@ export function lmerInternals(fit) {
540
256
  throw new TypeError("fit must be a result returned by lmer (not a copy of one)");
541
257
  return internals;
542
258
  }
259
+ /**
260
+ * The exponent of 2 of each column of X whose largest |value| is beyond 2^±500, where the cross-products of X overflow
261
+ * or underflow; 0 for the other columns (internal: lmer's standard errors and lmerTest's quantities)
262
+ */
263
+ export function extremeColumnExponents(x, p) {
264
+ return Array.from({ length: p }, (_, k) => {
265
+ let top = 0;
266
+ for (const row of x)
267
+ top = Math.max(top, Math.abs(row[k]));
268
+ return top > 2 ** 500 || (top > 0 && top < 2 ** -500) ? Math.floor(Math.log2(top)) : 0;
269
+ });
270
+ }
543
271
  /**
544
272
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
545
273
  * test of the sparse computation fits with the dense reference implementation through it.
@@ -573,20 +301,29 @@ export function lmerWithCriterion(formula, data, options, criterion) {
573
301
  // β, b, σ and the residuals scale back by 2^ky, the variances by 4^ky, the criteria shift by 2 n ky log 2. Otherwise
574
302
  // ky = 0 and nothing changes (issue #9)
575
303
  const ky = ycMax > 2 ** 500 || ycMax < 2 ** -500 ? Math.floor(Math.log2(ycMax)) : 0;
576
- const sScaled = ky === 0 ? s : { ...s, y: yc.map((v) => ldexp(v, -ky)) };
304
+ const sResponse = ky === 0 ? s : { ...s, y: yc.map((v) => ldexp(v, -ky)) };
305
+ // Columns of X beyond 2^±500 (predictors times 1e160 or 1e-160: X'X overflowed to NaN in the minimiser, or was
306
+ // subnormal and lost its digits, and (R_X'R_X)⁻¹ overflowed) are divided by their powers of 2 (exact; as Z's columns
307
+ // in issue #11): θ does not depend on it, β_k scales back by 2^-f_k, vcov by 2^(-f_a - f_b), and the REML criterion
308
+ // shifts by 2 Σ f log 2 (log det R_X'R_X). Otherwise f = 0 and nothing changes
309
+ const xScale = extremeColumnExponents(s.x, p);
310
+ const xScaled = xScale.some((e) => e !== 0);
311
+ const sScaled = xScaled ? { ...sResponse, x: sResponse.x.map((row) => row.map((v, k) => ldexp(v, -xScale[k]))) } : sResponse;
577
312
  const theta = minimiseCriterionScaled(sScaled, reml, criterion);
578
313
  const r = profiledDeviance(sScaled, theta, reml, { rxInverse: true });
579
314
  const up = (v) => ldexp(v, ky);
580
- const fixef = r.beta.map((b, k) => up(b) + beta0[k]);
315
+ const fixef = r.beta.map((b, k) => (xScaled ? ldexp(up(b), -xScale[k]) : up(b)) + beta0[k]);
581
316
  const twoPi = 2 * Math.PI;
582
317
  const logScale = 2 * ky * Math.LN2;
318
+ const logDetRX = xScaled ? r.logDetRX + 2 * xScale.reduce((a, b) => a + b, 0) * Math.LN2 : r.logDetRX;
583
319
  const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n) + logScale);
584
- const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)) + logScale);
320
+ const REMLcrit = r.logDetL + logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)) + logScale);
585
321
  // (σ² of the scaled response; the variances below are 4^ky times what is formed from it)
586
322
  const sigma2 = r.prss / (reml ? n - p : n);
587
323
  const sigma = up(Math.sqrt(sigma2));
588
- const vcov = r.rxInverse.map((row) => row.map((v) => ldexp(sigma2 * v, 2 * ky)));
589
- const stdError = r.rxInverse.map((row, i) => up(Math.sqrt(sigma2 * row[i])));
324
+ // (an entry of vcov may overflow where the standard error does not)
325
+ const vcov = r.rxInverse.map((row, a) => row.map((v, b) => ldexp(sigma2 * v, 2 * ky - (xScaled ? xScale[a] + xScale[b] : 0))));
326
+ const stdError = r.rxInverse.map((row, i) => (xScaled ? ldexp(up(Math.sqrt(sigma2 * row[i])), -xScale[i]) : up(Math.sqrt(sigma2 * row[i]))));
590
327
  // (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
591
328
  const tValue = fixef.map((b, i) => b / stdError[i]);
592
329
  // the blocks T_k and the variance components
@@ -619,7 +356,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
619
356
  // the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
620
357
  const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * fixef[k], 0));
621
358
  // (the residuals on the scaled response, scaled back)
622
- const residuals = s.x.map((xi, i) => sScaled.y[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
359
+ const residuals = sScaled.x.map((xi, i) => sScaled.y[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
623
360
  s.z.forEach((col, j) => {
624
361
  const bj = r.b[j];
625
362
  if (bj !== 0) {
@@ -665,6 +402,18 @@ export function lmerWithCriterion(formula, data, options, criterion) {
665
402
  warnings: [...s.warnings],
666
403
  };
667
404
  const snapshot = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.slice()]));
668
- internalsByFit.set(result, { structure: s, beta0, data, snapshot, options, reml, criterion, theta: [...theta] });
405
+ internalsByFit.set(result, {
406
+ structure: s,
407
+ beta0,
408
+ data,
409
+ snapshot,
410
+ options,
411
+ reml,
412
+ criterion,
413
+ theta: [...theta],
414
+ fixef: [...fixef],
415
+ b: r.b.map(up),
416
+ sigma,
417
+ });
669
418
  return result;
670
419
  }
@@ -2,6 +2,7 @@ import { Warnings } from "../internal/warnings.js";
2
2
  import { type LmerResult } from "./lmer.js";
3
3
  import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
4
4
  import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
5
+ import type { DataFrame } from "./modelFrame.js";
5
6
  /**
6
7
  * Options of {@link lmerAnova} for one fit. R's `ddf` gives the Error `lmerAnova: argument 'ddf' is not supported`,
7
8
  * any other key a RangeError.
@@ -100,6 +101,54 @@ export declare function anovaRowsOf(s: LmerSatterthwaite, { hypotheses }: LmerHy
100
101
  terms: string[];
101
102
  rows: LmerFRow[];
102
103
  };
104
+ /**
105
+ * A fit in a likelihood-ratio comparison (internal): of lmer, glmer (src/models/glmerAnova.ts) or glm, with what the
106
+ * checks and the test of nesting need
107
+ */
108
+ export interface ComparedModel {
109
+ /** The number of observations (R's nobs: rows used, rows of prior weight 0 included) */
110
+ nObs: number;
111
+ /** The number of parameters (the fit's df) */
112
+ df: number;
113
+ /** The fit's log-likelihood */
114
+ logLik: number;
115
+ /** Whether it is an lmer fit by REML */
116
+ reml: boolean;
117
+ /** The log-likelihood of the maximum-likelihood refit (lmer REML fits) */
118
+ refitLogLik?: () => number;
119
+ /** For lmer and glmer fits: the data object, its snapshot, the rows used and the formula's left-hand side */
120
+ mixed?: {
121
+ data: DataFrame;
122
+ snapshot: DataFrame;
123
+ rows: readonly number[];
124
+ response: string;
125
+ };
126
+ /** The response as the family reads it, one per row used (compared by value where a fit has no formula) */
127
+ response: () => readonly number[];
128
+ /** The prior weights, one per row used (all 1 for lmer) */
129
+ weights: () => readonly number[];
130
+ /** The family and link (lmer: gaussian, identity) */
131
+ family: string;
132
+ link: string;
133
+ /** The offset, one per row used (all 0 without) */
134
+ offset: () => readonly number[];
135
+ /** The fixed-effects model matrix (array of rows) */
136
+ x: () => readonly (readonly number[])[];
137
+ /** The random-effects terms (grouping factor and columns; none for glm) */
138
+ randomTerms: readonly {
139
+ group: string;
140
+ columns: readonly string[];
141
+ }[];
142
+ }
143
+ /** The model of an lmer fit in a comparison (internal) */
144
+ export declare function comparedLmer(fit: LmerResult): ComparedModel;
145
+ /**
146
+ * lme4's likelihood-ratio comparison of fits (internal; lmerAnova's and glmerAnova's): the checks that the fits are of
147
+ * the same observations, the names, the ML refits of REML fits, the rows sorted by the number of parameters and the
148
+ * test where the fit of the row before is nested in the row's. `fn` names the function in its error for fewer than
149
+ * two fits.
150
+ */
151
+ export declare function compareModels(fn: string, models: readonly ComparedModel[], options: LmerCompareOptions): LmerCompareTable;
103
152
  /**
104
153
  * The ANOVA table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's denominator degrees of freedom
105
154
  * (lmerTest's `anova()`), or, given an array of fits, the likelihood-ratio comparison of the models (lme4's