@numero-uno-jpn/rstats 0.17.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.ja.md +18 -10
  3. package/README.md +20 -10
  4. package/dist/chunks/{chunk-Z37NELOS.js → chunk-3W5NFFAA.js} +1 -1
  5. package/dist/chunks/{chunk-2C33MXSW.js → chunk-4F2IALD4.js} +2 -2
  6. package/dist/chunks/{chunk-H3WVPZDL.js → chunk-4OLDGML4.js} +2 -2
  7. package/dist/chunks/{chunk-WM7VFXTV.js → chunk-63OPBEYO.js} +1 -1
  8. package/dist/chunks/{chunk-TNMJPQPV.js → chunk-6XJBCRBV.js} +2 -2
  9. package/dist/chunks/{chunk-RFE7MVP7.js → chunk-BQSIBJVX.js} +2 -2
  10. package/dist/chunks/{chunk-C7V2FH6L.js → chunk-BWKHYRM6.js} +1 -1
  11. package/dist/chunks/{chunk-SE7V2KLO.js → chunk-CKV4JWW2.js} +1 -1
  12. package/dist/chunks/{chunk-CZI7KUO3.js → chunk-DCAWMF4K.js} +2 -2
  13. package/dist/chunks/{chunk-5AYHCITP.js → chunk-F7YGX7PN.js} +2 -2
  14. package/dist/chunks/chunk-H7I32ZZE.js +2 -0
  15. package/dist/chunks/chunk-IEOD5GWC.js +3 -0
  16. package/dist/chunks/{chunk-XLSFJTTK.js → chunk-KICBQGFN.js} +2 -2
  17. package/dist/chunks/chunk-LROMWFAK.js +2 -0
  18. package/dist/chunks/{chunk-DXI5N2ET.js → chunk-NSWENS3S.js} +1 -1
  19. package/dist/chunks/chunk-O2SQMGE3.js +2 -0
  20. package/dist/chunks/{chunk-FY3FVOBM.js → chunk-QQX46TCI.js} +2 -2
  21. package/dist/chunks/{chunk-ZFQWB222.js → chunk-QZK3CCBA.js} +2 -2
  22. package/dist/chunks/{chunk-6JJQL6HL.js → chunk-UJ66VQIG.js} +2 -2
  23. package/dist/chunks/{chunk-ONY5CISH.js → chunk-UKNDX4BA.js} +2 -2
  24. package/dist/chunks/chunk-WIBKS73G.js +2 -0
  25. package/dist/chunks/{chunk-4WE3OO62.js → chunk-WQWZ7FND.js} +2 -2
  26. package/dist/chunks/{chunk-LHUIJQHY.js → chunk-WWVMVZUL.js} +2 -2
  27. package/dist/chunks/{chunk-LV3W2F7N.js → chunk-YG5S5AVP.js} +2 -2
  28. package/dist/chunks/{chunk-34S5SQY6.js → chunk-YHNMBYSW.js} +2 -2
  29. package/dist/descriptive.js +2 -2
  30. package/dist/distributions.js +2 -2
  31. package/dist/entries/mixed.d.ts +6 -0
  32. package/dist/entries/mixed.js +6 -1
  33. package/dist/linalg.js +2 -2
  34. package/dist/mixed.js +5 -4
  35. package/dist/models/formula.d.ts +5 -2
  36. package/dist/models/formula.js +31 -8
  37. package/dist/models/glmer.d.ts +255 -0
  38. package/dist/models/glmer.js +635 -0
  39. package/dist/models/glmerAnova.d.ts +81 -0
  40. package/dist/models/glmerAnova.js +139 -0
  41. package/dist/models/glmerDeviance.d.ts +98 -0
  42. package/dist/models/glmerDeviance.js +576 -0
  43. package/dist/models/glmerFamily.d.ts +57 -0
  44. package/dist/models/glmerFamily.js +236 -0
  45. package/dist/models/glmerGradient.d.ts +46 -0
  46. package/dist/models/glmerGradient.js +301 -0
  47. package/dist/models/glmerStructure.d.ts +45 -0
  48. package/dist/models/glmerStructure.js +168 -0
  49. package/dist/models/glmerSummary.d.ts +102 -0
  50. package/dist/models/glmerSummary.js +94 -0
  51. package/dist/models/lmer.d.ts +16 -0
  52. package/dist/models/lmer.js +55 -306
  53. package/dist/models/lmerAnova.d.ts +49 -0
  54. package/dist/models/lmerAnova.js +91 -40
  55. package/dist/models/lmerTest.d.ts +8 -1
  56. package/dist/models/lmerTest.js +21 -8
  57. package/dist/models/mixedDeviance.d.ts +28 -2
  58. package/dist/models/mixedDeviance.js +84 -56
  59. package/dist/models/mixedMinimiser.d.ts +83 -0
  60. package/dist/models/mixedMinimiser.js +438 -0
  61. package/dist/models/mixedPredict.d.ts +121 -0
  62. package/dist/models/mixedPredict.js +530 -0
  63. package/dist/models/mixedStructure.d.ts +62 -3
  64. package/dist/models/mixedStructure.js +74 -29
  65. package/dist/models/modelMatrix.d.ts +8 -1
  66. package/dist/models/modelMatrix.js +49 -37
  67. package/dist/numerics.js +2 -2
  68. package/dist/rstats.js +11 -11
  69. package/dist/special.js +2 -2
  70. package/dist/tests.js +13 -14
  71. package/llms.txt +10 -2
  72. package/package.json +1 -1
  73. package/dist/chunks/chunk-M4ITG7YR.js +0 -2
  74. package/dist/chunks/chunk-NSYZTS26.js +0 -2
  75. package/dist/chunks/chunk-THIGHOKK.js +0 -2
  76. package/dist/chunks/chunk-WMDYDTVQ.js +0 -2
@@ -0,0 +1,576 @@
1
+ // The Laplace deviance of a generalised linear mixed model (lme4's glmer) at given parameters: the conditional mode
2
+ // of the spherical random effects by penalised iteratively reweighted least squares (PIRLS), the log determinant of
3
+ // L_θ at the mode, and the family's aic term. Nothing is optimised here. At the end of the file: the Gauss-Hermite
4
+ // rule and the adaptive Gauss-Hermite quadrature deviance of nAGQ > 1 (stage 2e), built on the mode of nAGQ = 1.
5
+ //
6
+ // Written for rStats.js (no ported code) from oracle/glmer-behaviour.md ("The Laplace deviance", stage 2a) and the
7
+ // notation of D. Bates, M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4",
8
+ // Journal of Statistical Software 67(1).
9
+ //
10
+ // With M = ZΛ_θ, η = o + Xβ + M u and μ = μ(η), the conditional mode ũ minimises the penalised deviance
11
+ // pdev(u) = Σ d_i + ‖u‖² (for nAGQ = 0, (ũ, β̃) minimise it jointly). Each PIRLS iteration is a Fisher scoring step,
12
+ // written here as an increment: with the working weights W_i = w_i μ'_i² / V(μ_i) and the score
13
+ // s_i = w_i (y_i − μ_i) μ'_i / V(μ_i),
14
+ // (M'WM + I) δu = M's − u (nAGQ = 1)
15
+ // [M'WM + I, M'WX; X'WM, X'WX] (δu, δβ) = (M's − u, X's) (nAGQ = 0)
16
+ // which is lme4's update u_new = (M'WM + I)⁻¹ M'W z (z the working response) in exact arithmetic, but whose fixed
17
+ // point (the score equations) does not depend on the accuracy of the solve. M'WM + I is factorised sparsely with the
18
+ // pattern of lmer's Λ'Z'ZΛ + I (src/models/mixedDeviance.ts), Z'WZ formed by blocks at each iteration.
19
+ //
20
+ // Unlike lme4, which stops when the relative change of pdev is below 1e-7 and takes the log determinant from the
21
+ // weights of the means before its last update (so that its deviance is off by up to about 1e-5), the iteration goes
22
+ // on to the exact mode: until the Fisher step is below 1e-13 (relative to the largest element of u and β, at least
23
+ // 1), or stops shrinking once below 1e-10 (rounding); the weights, the factor and the aic term are then those at the
24
+ // mode. Every evaluation starts from the same point, whatever was evaluated before: u = 0 for nAGQ = 1; for
25
+ // nAGQ = 0, the first step is lme4's first PIRLS step from the family's starting means (η0 = o + g(μ0)), or, where
26
+ // the iteration from there fails (an offset far from the data: lme4 fails too), glm.fit's (η0 = g(μ0)). A step that
27
+ // makes pdev NaN or larger is halved (up to 20 times, towards the previous iterate; the first step of nAGQ = 0, which
28
+ // has no previous pdev, only for NaN, towards u = 0, β = 0), with lme4's errors where that fails (an increase beyond
29
+ // 1e-7 relative to pdev, where lme4's tolerance is absolute). A step that stops shrinking while the decrease of pdev it
30
+ // predicts is at the level of rounding (nearly collinear predictors) ends the iteration too. The working weights and
31
+ // scores are formed from the powers of μ where μ'² or V overflow (src/models/glmerFamily.ts).
32
+ import { potf2 } from "../linalg/chol.js";
33
+ import { Warnings, withWarnings } from "../internal/warnings.js";
34
+ import { familyAic } from "./glmFamily.js";
35
+ import { workingScore, workingWeight } from "./glmerFamily.js";
36
+ import { laplaceGradient, rowWeights } from "./glmerGradient.js";
37
+ import { backSolve, blocksOf, blocksOfA, factorise, forwardSolve, lambdaTimes, lambdaTransposeTimes, solveL, solveLt, sparseSystemOf, weightedCrossProduct, zTimes, zTransposeTimes, } from "./mixedDeviance.js";
38
+ /** lme4's maximum number of step halvings */
39
+ const MAX_HALVINGS = 20;
40
+ /** The largest number of iterations (more than lme4's 100: Fisher scoring converges linearly for non-canonical links) */
41
+ const MAX_ITERATIONS = 500;
42
+ /** The step (relative to the largest element of u and β, at least 1) at which the mode is reached */
43
+ const STEP_TOLERANCE = 1e-13;
44
+ /** Below this step, a step that does not shrink means rounding: the mode is reached */
45
+ const ROUNDING_STEP = 1e-10;
46
+ /** A step that does not shrink and predicts a decrease of pdev below this (relative) means rounding too */
47
+ const FLAT_DECREASE = 1e-13;
48
+ /**
49
+ * lme4's tolPwrss, here relative: an increase of pdev larger than this times pdev after the halvings is an error.
50
+ * (lme4's is absolute, which made the rounding of a pdev of 1e10, prior weights 2^30, an error: the deviance scales
51
+ * with the weights)
52
+ */
53
+ const TOL_PWRSS = 1e-7;
54
+ /**
55
+ * The Laplace deviance of a generalised linear mixed model at `theta` (and `beta` for nAGQ = 1), at the exact
56
+ * conditional mode (oracle/glmer-behaviour.md, stage 2a). Internal: not exported from the package.
57
+ *
58
+ * @param structure The structure from {@link glmerStructure}.
59
+ * @param theta The covariance parameters (finite, of the length of `structure.theta`; values below the lower bounds
60
+ * are accepted).
61
+ * @param beta The fixed effects (one per column of X) for nAGQ = 1; ignored for nAGQ = 0.
62
+ * @param nAGQ 1: the deviance is a function of (θ, β), the mode is found for u; 0: a function of θ, the mode is found
63
+ * for u and β jointly.
64
+ * @param options `rx`: also return R_X'R_X at the mode (for the covariance of the fixed effects); `gradient`: also
65
+ * return the gradient of the deviance.
66
+ */
67
+ export function glmerDeviance(structure, theta, beta, nAGQ = 1, options = {}) {
68
+ if (nAGQ !== 0 && nAGQ !== 1)
69
+ throw new RangeError("nAGQ must be 0 or 1 here");
70
+ if (theta.length !== structure.theta.length)
71
+ throw new RangeError(`theta must have length ${structure.theta.length}, not ${theta.length}`);
72
+ if (theta.some((v) => !Number.isFinite(v)))
73
+ throw new RangeError("theta must be finite");
74
+ const sys = sparseSystemOf(structure);
75
+ const { n, p, q } = sys;
76
+ if (nAGQ === 1) {
77
+ if (beta === undefined || beta.length !== p)
78
+ throw new RangeError(`beta must have length ${p}`);
79
+ if (beta.some((v) => !Number.isFinite(v)))
80
+ throw new RangeError("beta must be finite");
81
+ }
82
+ const joint = nAGQ === 0;
83
+ const fam = structure.family;
84
+ const { x, y, weights: w, offset } = structure;
85
+ const t = blocksOf(sys, theta);
86
+ const warnings = new Warnings();
87
+ return withWarnings(warnings, () => {
88
+ const pointAt = (u, b) => {
89
+ const mb = zTimes(sys, lambdaTimes(sys, t, u));
90
+ const eta = new Float64Array(n);
91
+ const mu = new Float64Array(n);
92
+ let devResid = 0;
93
+ for (let i = 0; i < n; i++) {
94
+ const xi = x[i];
95
+ let e = offset[i] + mb[i];
96
+ for (let k = 0; k < p; k++)
97
+ e += xi[k] * b[k];
98
+ eta[i] = e;
99
+ const m = fam.linkinv(e);
100
+ mu[i] = m;
101
+ devResid += fam.devResid(y[i], m, w[i]);
102
+ }
103
+ let ussq = 0;
104
+ for (const v of u)
105
+ ussq += v * v;
106
+ return { u, beta: b, eta, mu, devResid, pdev: devResid + ussq };
107
+ };
108
+ /** The working weights and W(η − o − Xβ_base) + s (the right-hand side's data part) at η, μ */
109
+ const weightsAt = (eta, mu) => {
110
+ const ww = new Float64Array(n);
111
+ const score = new Float64Array(n);
112
+ for (let i = 0; i < n; i++) {
113
+ const wi = w[i];
114
+ if (wi === 0)
115
+ continue;
116
+ const me = fam.muEta(eta[i]);
117
+ ww[i] = workingWeight(fam, wi, me, mu[i]);
118
+ score[i] = workingScore(fam, wi, y[i], me, mu[i]);
119
+ }
120
+ return { ww, score };
121
+ };
122
+ /**
123
+ * Factorises the system at the weights `ww` and returns its factor L and the solver of the step: overwrites gu
124
+ * with δu (and gb with δβ for nAGQ = 0)
125
+ */
126
+ const systemAt = (ww) => {
127
+ const l = factorise(sys, blocksOfA(sys, t, weightedCrossProduct(sys, structure, ww)));
128
+ if (!joint) {
129
+ return {
130
+ l,
131
+ solve: (gu) => {
132
+ solveL(sys, l, gu);
133
+ solveLt(sys, l, gu);
134
+ },
135
+ };
136
+ }
137
+ // C = L⁻¹ Λ'Z'WX (q × p, column-major) and R_X'R_X = X'WX − C'C (the matrix of the step only: its accuracy
138
+ // affects the speed of the iteration, not its fixed point)
139
+ const c = new Float64Array(q * p);
140
+ for (let k = 0; k < p; k++) {
141
+ const col = lambdaTransposeTimes(sys, t, zTransposeTimes(sys, Float64Array.from(x, (row, i) => ww[i] * row[k])));
142
+ solveL(sys, l, col);
143
+ c.set(col, k * q);
144
+ }
145
+ const rx = new Float64Array(p * p);
146
+ for (let k = 0; k < p; k++) {
147
+ for (let m = k; m < p; m++) {
148
+ let sum = 0;
149
+ for (let i = 0; i < n; i++)
150
+ sum += ww[i] * x[i][k] * x[i][m];
151
+ for (let i = 0; i < q; i++)
152
+ sum -= c[i + k * q] * c[i + m * q];
153
+ rx[k + m * p] = sum;
154
+ rx[m + k * p] = sum;
155
+ }
156
+ }
157
+ if (p > 0 && potf2({ nrow: p, ncol: p, data: rx }) > 0) {
158
+ throw new Error("the fixed-effects matrix of the penalised least squares is not positive definite");
159
+ }
160
+ return {
161
+ l,
162
+ solve: (gu, gb) => {
163
+ solveL(sys, l, gu);
164
+ for (let k = 0; k < p; k++) {
165
+ let sum = gb[k];
166
+ for (let i = 0; i < q; i++)
167
+ sum -= c[i + k * q] * gu[i];
168
+ gb[k] = sum;
169
+ }
170
+ forwardSolve(rx, p, gb);
171
+ backSolve(rx, p, gb);
172
+ for (let k = 0; k < p; k++) {
173
+ const bk = gb[k];
174
+ for (let i = 0; i < q; i++)
175
+ gu[i] -= c[i + k * q] * bk;
176
+ }
177
+ solveLt(sys, l, gu);
178
+ },
179
+ };
180
+ };
181
+ const infNorm = (v) => {
182
+ let m = 0;
183
+ for (const e of v)
184
+ m = Math.max(m, Math.abs(e));
185
+ return m;
186
+ };
187
+ const fixedBeta = Float64Array.from(beta ?? new Array(p).fill(0));
188
+ /**
189
+ * The iteration to the mode from its starting point: u = 0 (nAGQ = 1); for nAGQ = 0, η0 = o + g(μ0) (lme4's), or
190
+ * η0 = g(μ0) without the offset (glm.fit's) when `withOffset` is false; η0 is not of the form o + Xβ + Mu: the
191
+ * first step solves for (u, β) from it (base u = 0, β = 0)
192
+ */
193
+ const iterate = (withOffset) => {
194
+ let cur;
195
+ let first = joint;
196
+ if (joint) {
197
+ const eta = Float64Array.from(structure.mustart, (m, i) => (withOffset ? offset[i] : 0) + fam.linkfun(m));
198
+ const mu = eta.map((e) => fam.linkinv(e));
199
+ cur = { u: new Float64Array(q), beta: new Float64Array(p), eta, mu, devResid: NaN, pdev: Infinity };
200
+ }
201
+ else
202
+ cur = pointAt(new Float64Array(q), fixedBeta);
203
+ let prevSize = Infinity;
204
+ let l;
205
+ let iterations = 0;
206
+ for (;;) {
207
+ if (iterations >= MAX_ITERATIONS)
208
+ throw new Error("pwrssUpdate did not converge in (maxit) iterations");
209
+ const { ww, score } = weightsAt(cur.eta, cur.mu);
210
+ const system = systemAt(ww);
211
+ l = system.l;
212
+ // the right-hand side: (M's − u, X's); for the first step of nAGQ = 0 (from η0, base 0) (M'r, X'r) with
213
+ // r = W(η0 − o) + s, the working response times the weights
214
+ let rhs = score;
215
+ if (first)
216
+ rhs = score.map((s, i) => s + ww[i] * (cur.eta[i] - offset[i]));
217
+ const du = lambdaTransposeTimes(sys, t, zTransposeTimes(sys, rhs));
218
+ if (!first)
219
+ for (let i = 0; i < q; i++)
220
+ du[i] -= cur.u[i];
221
+ const db = new Float64Array(p);
222
+ if (joint) {
223
+ for (let i = 0; i < n; i++) {
224
+ const xi = x[i];
225
+ const r = rhs[i];
226
+ for (let k = 0; k < p; k++)
227
+ db[k] += xi[k] * r;
228
+ }
229
+ }
230
+ const gu = du.slice();
231
+ const gb = db.slice();
232
+ system.solve(du, db);
233
+ iterations++;
234
+ const base = first ? { u: new Float64Array(q), beta: new Float64Array(p) } : cur;
235
+ if (!first) {
236
+ const size = Math.max(infNorm(du) / Math.max(1, infNorm(cur.u)), joint ? infNorm(db) / Math.max(1, infNorm(cur.beta)) : 0);
237
+ // the mode: the step is negligible, or has stopped shrinking at the level of rounding
238
+ if (size <= STEP_TOLERANCE || (size < ROUNDING_STEP && size >= prevSize))
239
+ break;
240
+ if (size >= prevSize) {
241
+ // a step that has stopped shrinking above that level, along a direction in which pdev is flat (nearly
242
+ // collinear columns of X: the steps wander along it, by the rounding of the solve, while pdev does not
243
+ // change): the mode is reached where the decrease of pdev that the step predicts, g'δ, is at the
244
+ // level of rounding of pdev (only here: the steps of an ordinary iteration shrink to the tolerance)
245
+ let decrease = 0;
246
+ for (let i = 0; i < q; i++)
247
+ decrease += gu[i] * du[i];
248
+ for (let k = 0; k < p; k++)
249
+ decrease += gb[k] * db[k];
250
+ if (decrease <= FLAT_DECREASE * Math.abs(cur.pdev))
251
+ break;
252
+ }
253
+ prevSize = size;
254
+ }
255
+ const candidate = () => {
256
+ const u = base.u.map((v, i) => v + du[i]);
257
+ const b = joint ? base.beta.map((v, k) => v + db[k]) : fixedBeta;
258
+ return pointAt(u, b);
259
+ };
260
+ let next = candidate();
261
+ // step halving: for NaN, or (after the first step of nAGQ = 0) an increase beyond rounding
262
+ const pdevOld = cur.pdev;
263
+ const slack = Number.isFinite(pdevOld) ? 1e-13 * pdevOld : 0;
264
+ for (let k = 0; k < MAX_HALVINGS && (Number.isNaN(next.pdev) || next.pdev > pdevOld + slack); k++) {
265
+ for (let i = 0; i < q; i++)
266
+ du[i] /= 2;
267
+ for (let i = 0; i < p; i++)
268
+ db[i] /= 2;
269
+ next = candidate();
270
+ }
271
+ if (Number.isNaN(next.pdev))
272
+ throw new Error("PIRLS loop resulted in NaN value");
273
+ if (next.pdev - pdevOld > TOL_PWRSS * Math.abs(pdevOld))
274
+ throw new Error("(maxstephalfit) PIRLS step-halvings failed to reduce deviance in pwrssUpdate");
275
+ cur = next;
276
+ first = false;
277
+ }
278
+ return { cur, l, iterations };
279
+ };
280
+ let mode;
281
+ try {
282
+ mode = iterate(true);
283
+ }
284
+ catch (e) {
285
+ // nAGQ = 0 with an offset far from the data (log(exposure), a constant −4: μ0 times e^o): lme4's start fails
286
+ // (lme4 fails there too), glm.fit's start η0 = g(μ0) leads to the same mode. Where both fail, lme4's error
287
+ if (!joint || !(e instanceof Error) || e.constructor !== Error || offset.every((o) => o === 0))
288
+ throw e;
289
+ try {
290
+ mode = iterate(false);
291
+ }
292
+ catch {
293
+ throw e;
294
+ }
295
+ }
296
+ const { cur, l, iterations } = mode;
297
+ // at the mode: the factor of the last iteration was formed with the weights at the mode
298
+ let ldL2 = 0;
299
+ for (let j = 0; j < q; j++)
300
+ ldL2 += Math.log(l[sys.colStart[j]]);
301
+ ldL2 *= 2;
302
+ const mu = Array.from(cur.mu);
303
+ const aic = familyAic(fam.glm, y, mu, w, structure.size, cur.devResid, warnings);
304
+ let ussq = 0;
305
+ for (const v of cur.u)
306
+ ussq += v * v;
307
+ let rxtrx;
308
+ if (options.rx === true) {
309
+ // X'WX − C'C with C = L⁻¹ Λ'Z'WX, L the factor at the weights of the mode (that of the last iteration)
310
+ const { ww } = weightsAt(cur.eta, cur.mu);
311
+ const c = Array.from({ length: p }, (_, k) => {
312
+ const col = lambdaTransposeTimes(sys, t, zTransposeTimes(sys, Float64Array.from(x, (row, i) => ww[i] * row[k])));
313
+ solveL(sys, l, col);
314
+ return col;
315
+ });
316
+ rxtrx = Array.from({ length: p }, (_, k) => Array.from({ length: p }, (_, m) => {
317
+ let sum = 0;
318
+ for (let i = 0; i < n; i++)
319
+ sum += ww[i] * x[i][k] * x[i][m];
320
+ for (let i = 0; i < q; i++)
321
+ sum -= c[k][i] * c[m][i];
322
+ return sum;
323
+ }));
324
+ }
325
+ const gradient = options.gradient === true
326
+ ? laplaceGradient({ structure, sys, t, l, u: cur.u, eta: cur.eta, mu: cur.mu, devResid: cur.devResid, joint })
327
+ : undefined;
328
+ return {
329
+ deviance: ldL2 + ussq + aic,
330
+ beta: Array.from(cur.beta),
331
+ u: Array.from(cur.u),
332
+ b: Array.from(lambdaTimes(sys, t, cur.u)),
333
+ mu,
334
+ eta: Array.from(cur.eta),
335
+ devResid: cur.devResid,
336
+ ussq,
337
+ pdev: cur.devResid + ussq,
338
+ ldL2,
339
+ aic,
340
+ iterations,
341
+ warnings: warnings.list,
342
+ ...(rxtrx === undefined ? {} : { rxtrx }),
343
+ ...(gradient === undefined ? {} : { gradient }),
344
+ };
345
+ });
346
+ }
347
+ const ruleCache = new Map();
348
+ /**
349
+ * The orthonormal Hermite polynomials h_j = He_j / √(j!) at x for j = 0..K by their recurrence
350
+ * h_(j+1) = (x h_j − √j h_(j−1)) / √(j+1): returns h_K, h_(K−1) and Σ_(j<K) h_j²
351
+ */
352
+ function hermiteAt(x, k) {
353
+ let prev = 0;
354
+ let cur = 1;
355
+ let sum = 0;
356
+ for (let j = 0; j < k; j++) {
357
+ sum += cur * cur;
358
+ const next = (x * cur - Math.sqrt(j) * prev) / Math.sqrt(j + 1);
359
+ prev = cur;
360
+ cur = next;
361
+ }
362
+ return { hk: cur, hk1: prev, sum };
363
+ }
364
+ /**
365
+ * The K-point Gauss-Hermite rule for the standard normal density (K = 1..100): the nodes are the zeros of the
366
+ * probabilists' Hermite polynomial He_K, the weights 1 / Σ_(j<K) He_j(z)² / j!. The positive zeros are bracketed by a
367
+ * scan of the sign of He_K (step 0.01, well below the smallest spacing of the zeros, about π / √(2K + 1) = 0.22 for
368
+ * K = 100), narrowed by bisection and finished by Newton's method (He_K' = K He_(K−1)); the negative nodes are their
369
+ * mirror images and the middle node of an odd rule is exactly 0, so the rule is symmetric as lme4's symmetrised table
370
+ * is. Cached per K.
371
+ */
372
+ export function gaussHermiteRule(k) {
373
+ const cached = ruleCache.get(k);
374
+ if (cached !== undefined)
375
+ return cached;
376
+ if (!Number.isInteger(k) || k < 1 || k > 100)
377
+ throw new RangeError("the number of quadrature points must be an integer from 1 to 100");
378
+ const positive = [];
379
+ // (the largest zero of He_K is below √(4K + 2))
380
+ const end = Math.sqrt(4 * k + 2) + 0.5;
381
+ const step = 0.01;
382
+ const valueAt = (x) => hermiteAt(x, k).hk;
383
+ let a = k % 2 === 1 ? step / 2 : 0;
384
+ let fa = valueAt(a);
385
+ while (a < end && positive.length < Math.floor(k / 2)) {
386
+ const b = a + step;
387
+ const fb = valueAt(b);
388
+ if (fb === 0 || Math.sign(fa) !== Math.sign(fb)) {
389
+ // bisection to a bracket of 1e-6, then Newton's method to convergence
390
+ let lo = a;
391
+ let hi = b;
392
+ let flo = fa;
393
+ while (hi - lo > 1e-6) {
394
+ const mid = (lo + hi) / 2;
395
+ const fm = valueAt(mid);
396
+ if (Math.sign(fm) === Math.sign(flo)) {
397
+ lo = mid;
398
+ flo = fm;
399
+ }
400
+ else
401
+ hi = mid;
402
+ }
403
+ let z = (lo + hi) / 2;
404
+ for (let it = 0; it < 20; it++) {
405
+ const { hk, hk1 } = hermiteAt(z, k);
406
+ const dz = hk / (Math.sqrt(k) * hk1);
407
+ z -= dz;
408
+ if (Math.abs(dz) <= 1e-17 * Math.max(1, Math.abs(z)))
409
+ break;
410
+ }
411
+ positive.push(z);
412
+ }
413
+ a = b;
414
+ fa = fb;
415
+ }
416
+ if (positive.length !== Math.floor(k / 2))
417
+ throw new Error(`gaussHermiteRule: found ${positive.length} positive zeros for K = ${k}`);
418
+ const weightOf = (z) => 1 / hermiteAt(z, k).sum;
419
+ const nodes = [...positive.map((z) => -z).reverse(), ...(k % 2 === 1 ? [0] : []), ...positive];
420
+ const weights = nodes.map((z) => weightOf(Math.abs(z)));
421
+ const rule = { nodes, weights };
422
+ ruleCache.set(k, rule);
423
+ return rule;
424
+ }
425
+ /**
426
+ * The adaptive Gauss-Hermite quadrature deviance D_K(θ, β) of a model with one scalar random-effects term, at the
427
+ * exact conditional mode (that of nAGQ = 1, {@link glmerDeviance}) with the rule of {@link gaussHermiteRule}
428
+ * (oracle/glmer-behaviour.md, "The deviance at given (θ, β)"). Internal: not exported from the package.
429
+ *
430
+ * @param structure The structure (one random-effects term with one column).
431
+ * @param theta θ (one value).
432
+ * @param beta The fixed effects.
433
+ * @param nAGQ The number of points K (2 to 100).
434
+ * @param options `rx`: also return R_X'R_X at the mode; `gradient`: also the gradient in (θ, β).
435
+ */
436
+ export function glmerAgqDeviance(structure, theta, beta, nAGQ, options = {}) {
437
+ if (structure.terms.length !== 1 || structure.terms[0].columns.length !== 1)
438
+ throw new RangeError("AGQ only defined for a single scalar random-effects term");
439
+ const rule = gaussHermiteRule(nAGQ);
440
+ const mode = glmerDeviance(structure, theta, beta, 1, { ...(options.rx === true ? { rx: true } : {}) });
441
+ const fam = structure.family;
442
+ const { y, weights: w } = structure;
443
+ const th = theta[0];
444
+ // (the log weights plus z²/2, which stay below 0 for every K ≤ 100)
445
+ const logWeights = rule.nodes.map((z, k) => Math.log(rule.weights[k]) + (z * z) / 2);
446
+ let ldL2 = 0;
447
+ let quad = 0;
448
+ // the gradient (options.gradient): ∂D_K/∂e_i and ∂D_K/∂c_i for the fixed part e_i = o_i + x_i'β and c_i = z_i θ of
449
+ // each row (see gradientOfLevel), then by the chain rule in β and θ; a row outside every level only through d_i
450
+ const grad = options.gradient === true ? { ...rowWeights(structure, mode.eta, mode.mu), ge: new Float64Array(y.length), gc: new Float64Array(y.length) } : undefined;
451
+ if (grad !== undefined)
452
+ for (let i = 0; i < y.length; i++)
453
+ grad.ge[i] = -2 * grad.score[i];
454
+ const condSd = structure.z.map((col, j) => {
455
+ const uj = mode.u[j];
456
+ const c = col.values.map((v) => v * th);
457
+ // L_j² = 1 + Σ W_i c_i² with the Fisher weights at the mode
458
+ let l2 = 1;
459
+ col.rows.forEach((i, m) => {
460
+ if (w[i] === 0)
461
+ return;
462
+ l2 += workingWeight(fam, w[i], fam.muEta(mode.eta[i]), mode.mu[i]) * c[m] * c[m];
463
+ });
464
+ ldL2 += Math.log(l2);
465
+ const sd = 1 / Math.sqrt(l2);
466
+ const d0 = col.rows.map((i) => fam.devResid(y[i], mode.mu[i], w[i]));
467
+ let sum = 0;
468
+ rule.nodes.forEach((z, k) => {
469
+ let delta = 0;
470
+ if (z !== 0) {
471
+ const t = z * sd;
472
+ delta = t * (2 * uj + t);
473
+ col.rows.forEach((i, m) => {
474
+ if (c[m] === 0)
475
+ return;
476
+ delta += fam.devResid(y[i], fam.linkinv(mode.eta[i] + c[m] * t), w[i]) - d0[m];
477
+ });
478
+ }
479
+ sum += Math.exp(logWeights[k] - delta / 2);
480
+ });
481
+ quad -= 2 * Math.log(sum);
482
+ if (grad !== undefined)
483
+ gradientOfLevel(structure, rule, logWeights, col.rows, c, uj, l2, mode.eta, grad);
484
+ return sd;
485
+ });
486
+ let gradient;
487
+ if (grad !== undefined) {
488
+ // β: Σ ∂D/∂e_i x_i; θ: Σ ∂D/∂c_i z_i
489
+ const p = beta.length;
490
+ gradient = new Array(1 + p).fill(0);
491
+ for (let i = 0; i < y.length; i++)
492
+ for (let k = 0; k < p; k++)
493
+ gradient[1 + k] += grad.ge[i] * structure.x[i][k];
494
+ for (const col of structure.z)
495
+ col.rows.forEach((i, m) => (gradient[0] += grad.gc[i] * col.values[m]));
496
+ }
497
+ return { ...mode, deviance: mode.devResid + mode.ussq + ldL2 + quad, ldL2, quad, condSd, ...(gradient === undefined ? {} : { gradient }) };
498
+ }
499
+ /**
500
+ * The derivatives of one level's part of the AGQ deviance with respect to e_i = o_i + x_i'β and c_i = z_i θ of its
501
+ * rows (oracle/glmer-behaviour.md, "The gradient (rStats.js)"). The level's part is
502
+ * D_j = log L² − 2 log Σ_k ω_k exp(−P(v_k) / 2), v_k = u + z_k / L, ω_k = w_k exp(z_k² / 2),
503
+ * with P(v) = Σ d_i(e_i + c_i v) + v², L² = 1 + Σ W_i c_i² at the mode u, which solves Σ s_i c_i = u. With π_k the
504
+ * normalised terms, P'(v) = 2v − 2 Σ s_i c_i, κ = Σ π_k P'(v_k) z_k / (2L³) and H = 1 + Σ Ŵ_i c_i²:
505
+ * ∂D_j/∂e_i = (1/L² − κ) W'_i c_i² − 2 Σ_k π_k s_i(v_k) + A_u ∂u/∂e_i, ∂u/∂e_i = −Ŵ_i c_i / H,
506
+ * ∂D_j/∂c_i = (1/L² − κ)(W'_i c_i² u + 2 W_i c_i) − 2 Σ_k π_k s_i(v_k) v_k + A_u ∂u/∂c_i, ∂u/∂c_i = (s_i − Ŵ_i c_i u) / H,
507
+ * A_u = (1/L² − κ) Σ W'_i c_i³ + Σ_k π_k P'(v_k) (the derivative in u at fixed e and c).
508
+ * Writes ge and gc of the level's rows.
509
+ */
510
+ function gradientOfLevel(structure, rule, logWeights, rows, c, u, l2, eta, grad) {
511
+ const fam = structure.family;
512
+ const { y, weights: w } = structure;
513
+ const lv = Math.sqrt(l2);
514
+ const nr = rows.length;
515
+ const d0 = rows.map((i) => fam.devResid(y[i], fam.linkinv(eta[i]), w[i]));
516
+ // the terms of each node: log of ω_k exp(−(P(v_k) − P(u)) / 2), P'(v_k), and the scores at the node
517
+ const nodes = rule.nodes.length;
518
+ const logTerm = new Float64Array(nodes);
519
+ const slope = new Float64Array(nodes);
520
+ const scores = [];
521
+ rule.nodes.forEach((z, k) => {
522
+ const t = z / lv;
523
+ let delta = t * (2 * u + t);
524
+ let sc = 0;
525
+ const sk = new Float64Array(nr);
526
+ rows.forEach((i, m) => {
527
+ if (w[i] === 0)
528
+ return;
529
+ const e = eta[i] + c[m] * t;
530
+ const mu = fam.linkinv(e);
531
+ if (c[m] !== 0 && z !== 0)
532
+ delta += fam.devResid(y[i], mu, w[i]) - d0[m];
533
+ const s = workingScore(fam, w[i], y[i], fam.muEta(e), mu);
534
+ sk[m] = s;
535
+ sc += s * c[m];
536
+ });
537
+ logTerm[k] = logWeights[k] - delta / 2;
538
+ slope[k] = 2 * (u + t) - 2 * sc;
539
+ scores.push(sk);
540
+ });
541
+ let top = -Infinity;
542
+ for (const v of logTerm)
543
+ top = Math.max(top, v);
544
+ let total = 0;
545
+ const pi = logTerm.map((v) => Math.exp(v - top));
546
+ for (const v of pi)
547
+ total += v;
548
+ let kappa = 0;
549
+ let slopeMean = 0;
550
+ rule.nodes.forEach((z, k) => {
551
+ pi[k] /= total;
552
+ kappa += (pi[k] * slope[k] * z) / (2 * l2 * lv);
553
+ slopeMean += pi[k] * slope[k];
554
+ });
555
+ const factor = 1 / l2 - kappa;
556
+ let h = 1;
557
+ let cubic = 0;
558
+ rows.forEach((i, m) => {
559
+ h += grad.observed[i] * c[m] * c[m];
560
+ cubic += grad.dww[i] * c[m] * c[m] * c[m];
561
+ });
562
+ const au = factor * cubic + slopeMean;
563
+ rows.forEach((i, m) => {
564
+ let sMean = 0;
565
+ let svMean = 0;
566
+ rule.nodes.forEach((z, k) => {
567
+ const s = scores[k][m];
568
+ sMean += pi[k] * s;
569
+ svMean += pi[k] * s * (u + z / lv);
570
+ });
571
+ const ci = c[m];
572
+ const wd = grad.dww[i];
573
+ grad.ge[i] = factor * wd * ci * ci - 2 * sMean + (au * -grad.observed[i] * ci) / h;
574
+ grad.gc[i] = factor * (wd * ci * ci * u + 2 * grad.ww[i] * ci) - 2 * svMean + (au * (grad.score[i] - grad.observed[i] * ci * u)) / h;
575
+ });
576
+ }
@@ -0,0 +1,57 @@
1
+ import { type Family, type GlmFamilyName, type GlmFamilySpec, type GlmLink, type GlmLinkName } from "./glmFamily.js";
2
+ /**
3
+ * The families that {@link glmer} fits (the glm families without the quasi ones).
4
+ *
5
+ * @category Mixed models
6
+ */
7
+ export type GlmerFamilyName = "binomial" | "poisson" | "Gamma" | "inverse.gaussian" | "gaussian";
8
+ /** A family of glmer resolved to its functions. */
9
+ export interface GlmerFamily {
10
+ family: GlmerFamilyName;
11
+ /** The link's name. */
12
+ link: GlmLinkName;
13
+ /** eta = g(mu): R's link function (used for the starting linear predictor only). */
14
+ linkfun(mu: number): number;
15
+ /** mu = g^-1(eta), lme4's. */
16
+ linkinv(eta: number): number;
17
+ /** d mu / d eta, lme4's. */
18
+ muEta(eta: number): number;
19
+ /** The variance function, lme4's. */
20
+ variance(mu: number): number;
21
+ /**
22
+ * d² mu / d eta², the derivative of {@link muEta} (0 where lme4 clamps muEta to a constant): for the analytic
23
+ * gradient of the deviance (src/models/glmerGradient.ts).
24
+ */
25
+ muEta2(eta: number): number;
26
+ /** dV / d mu, the derivative of {@link variance} (0 where lme4 clamps it). */
27
+ varianceDerivative(mu: number): number;
28
+ /** The deviance residual of one observation with prior weight w. */
29
+ devResid(y: number, mu: number, w: number): number;
30
+ /** R's family object (glm's), for the checks of the response, the starting means and the aic term. */
31
+ glm: Family;
32
+ }
33
+ /**
34
+ * The family of glmer from a family name or specification and a link given separately (glm's arguments): the quasi
35
+ * families are an error (lme4's first check), and so is gaussian with the identity link, which R fits with lmer
36
+ * (rStats.js's choice G3).
37
+ */
38
+ export declare function glmerFamily(family: GlmFamilyName | GlmFamilySpec | undefined, link?: GlmLink): GlmerFamily;
39
+ /** The working weight w μ'² / V(μ) of a row of prior weight w > 0 (as w c² μ^(2a − p) where that overflows) */
40
+ export declare function workingWeight(fam: GlmerFamily, w: number, me: number, mu: number): number;
41
+ /** The score w (y − μ) μ' / V(μ) of a row (as w (y − μ) c μ^(a − p) where that overflows) */
42
+ export declare function workingScore(fam: GlmerFamily, w: number, y: number, me: number, mu: number): number;
43
+ /**
44
+ * The weights of the gradient of a row of prior weight w > 0 (src/models/glmerGradient.ts rowWeights): W, dW/dη, the
45
+ * score s and the observed weight Ŵ = W − w (y − μ)(μ''/V − (μ'/V)² V'), in R's form, or from the powers of μ
46
+ * (dW/dη = w c³ (2a − p) μ^(3a − p − 1), Ŵ = W − w (y − μ) c² (a − p) μ^(2a − p − 1)) where that overflows
47
+ */
48
+ export declare function gradientWeights(fam: GlmerFamily, w: number, y: number, eta: number, mu: number, canonical: boolean): {
49
+ ww: number;
50
+ dww: number;
51
+ score: number;
52
+ observed: number;
53
+ };
54
+ /** The Pearson residual √w (y − μ) / √V(μ) (as ((y − μ)/h) √w / h, h = μ^(p/4), where V is out of range) */
55
+ export declare function pearsonResidualOf(fam: GlmerFamily, w: number, y: number, mu: number): number;
56
+ /** The working residual (y − μ) / μ' (as ((y − μ)/c)/μ^(a/2)/μ^(a/2) where μ' is out of range) */
57
+ export declare function workingResidualOf(fam: GlmerFamily, y: number, eta: number, mu: number): number;