@numero-uno-jpn/rstats 0.13.0 → 0.15.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 (62) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.ja.md +18 -9
  3. package/README.md +18 -9
  4. package/dist/chunks/{chunk-MEMYFTYS.js → chunk-4EOKNOXP.js} +1 -1
  5. package/dist/chunks/chunk-4XGKAHD3.js +2 -0
  6. package/dist/chunks/chunk-7GEYDIQC.js +2 -0
  7. package/dist/chunks/{chunk-F44XUHWI.js → chunk-7XHAE2LG.js} +1 -1
  8. package/dist/chunks/{chunk-BSOUJPDF.js → chunk-A3XZUJCP.js} +2 -2
  9. package/dist/chunks/{chunk-SVWU5T7C.js → chunk-AEFWSUZ2.js} +2 -2
  10. package/dist/chunks/chunk-CJ5ETQCK.js +2 -0
  11. package/dist/chunks/{chunk-4GNJEYXR.js → chunk-CMPDE3SZ.js} +2 -2
  12. package/dist/chunks/chunk-GZTLODPK.js +3 -0
  13. package/dist/chunks/{chunk-3AKA4KEL.js → chunk-HNLKOICT.js} +1 -1
  14. package/dist/chunks/{chunk-SLSDFIW2.js → chunk-HS7KIFMR.js} +2 -2
  15. package/dist/chunks/{chunk-CQNVEA22.js → chunk-LU5FHU2O.js} +2 -2
  16. package/dist/chunks/chunk-LVXAWWUX.js +2 -0
  17. package/dist/chunks/{chunk-BJHBYEEU.js → chunk-LWUTCYTZ.js} +1 -1
  18. package/dist/chunks/chunk-NYGWVZOC.js +2 -0
  19. package/dist/chunks/{chunk-4AQNVF3Z.js → chunk-PRDF6IU6.js} +2 -2
  20. package/dist/chunks/{chunk-VG67L3JA.js → chunk-QQIWOGHR.js} +2 -2
  21. package/dist/chunks/chunk-VAPGDPHM.js +2 -0
  22. package/dist/chunks/chunk-VSKWQMSG.js +2 -0
  23. package/dist/chunks/{chunk-JGFUZKLJ.js → chunk-WEWXYHPR.js} +2 -2
  24. package/dist/chunks/{chunk-2IAT6MT2.js → chunk-XMTYTJT6.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions.js +2 -2
  27. package/dist/entries/mixed.d.ts +3 -1
  28. package/dist/entries/mixed.js +4 -1
  29. package/dist/internal/fround.d.ts +12 -0
  30. package/dist/internal/fround.js +89 -0
  31. package/dist/linalg.js +2 -2
  32. package/dist/mixed.js +4 -3
  33. package/dist/models/glm.js +4 -2
  34. package/dist/models/glmFamily.js +16 -4
  35. package/dist/models/lmer.d.ts +64 -8
  36. package/dist/models/lmer.js +146 -20
  37. package/dist/models/lmerAnova.d.ts +143 -0
  38. package/dist/models/lmerAnova.js +140 -0
  39. package/dist/models/lmerHypotheses.d.ts +106 -0
  40. package/dist/models/lmerHypotheses.js +305 -0
  41. package/dist/models/lmerTest.d.ts +239 -0
  42. package/dist/models/lmerTest.js +311 -0
  43. package/dist/models/mixedDerivatives.d.ts +27 -0
  44. package/dist/models/mixedDerivatives.js +342 -0
  45. package/dist/models/mixedDeviance.d.ts +112 -0
  46. package/dist/models/mixedDeviance.js +216 -86
  47. package/dist/models/mixedStructure.d.ts +5 -3
  48. package/dist/models/mixedStructure.js +30 -14
  49. package/dist/models/modelMatrix.d.ts +10 -3
  50. package/dist/models/modelMatrix.js +23 -2
  51. package/dist/numerics.js +2 -2
  52. package/dist/rstats.js +13 -13
  53. package/dist/special.js +2 -2
  54. package/dist/tests.js +11 -12
  55. package/llms.txt +6 -1
  56. package/package.json +1 -1
  57. package/dist/chunks/chunk-22SXZNR6.js +0 -2
  58. package/dist/chunks/chunk-AGRKZXLG.js +0 -2
  59. package/dist/chunks/chunk-N3FV6H3C.js +0 -2
  60. package/dist/chunks/chunk-NRV3BH7I.js +0 -2
  61. package/dist/chunks/chunk-RTWLZPPG.js +0 -2
  62. package/dist/chunks/chunk-VWGJYRE6.js +0 -2
@@ -0,0 +1,311 @@
1
+ // lmerTest's tests for the fixed effects of a linear mixed model fitted by lmer (src/models/lmer.ts): t- and F-tests
2
+ // of contrasts with Satterthwaite's approximation of the denominator degrees of freedom, the coefficient table of
3
+ // lmerTest's summary, and lmerTest's contest.
4
+ //
5
+ // Written for rStats.js (no ported code) from oracle/lmertest-behaviour.md (section 1, "The Satterthwaite machinery")
6
+ // and A. Kuznetsova, P. B. Brockhoff, R. H. B. Christensen (2017), "lmerTest Package: Tests in Linear Mixed Effects
7
+ // Models", Journal of Statistical Software 82(13). The derivatives (the Hessian of the deviance in the variance
8
+ // parameters and the Jacobians of the covariance of the fixed effects) are computed analytically at the exact optimum
9
+ // by src/models/mixedDerivatives.ts; lmerTest differentiates numerically at lme4's approximate optimum, so its numbers
10
+ // typically differ from these in the 4th to 8th significant digit.
11
+ //
12
+ // The Satterthwaite quantities of a fit are computed once and kept with the fit (a WeakMap keyed by the result), so
13
+ // that the summary, the contrasts and the ANOVA tables of the same fit share them (and the Hessian's warnings are the
14
+ // same in every result).
15
+ import { pf1 } from "../distributions/f.js";
16
+ import { pt1, qt1 } from "../distributions/t.js";
17
+ import { eigen } from "../linalg/eigen.js";
18
+ import { ginv } from "../linalg/kappa.js";
19
+ import { Warnings } from "./glmFamily.js";
20
+ import { checkOptions, lmerInternals, logicalOption } from "./lmer.js";
21
+ import { varparDerivatives } from "./mixedDerivatives.js";
22
+ /** Eigenvalues of the Hessian within this of 0 (or below) are left out of its inverse and warned about */
23
+ const HESSIAN_TOLERANCE = 1e-8;
24
+ /** Eigenvalues of L V L' at most this times the largest are left out of a joint test */
25
+ const RANK_TOLERANCE = Math.sqrt(Number.EPSILON);
26
+ /** Satterthwaite's degrees of freedom of a joint test are averaged when they differ by less than this */
27
+ const EQUAL_DF_TOLERANCE = 1e-8;
28
+ const satterthwaiteByFit = new WeakMap();
29
+ /** A number as C's printf("%1.1e") writes it: "-3.2e-04" */
30
+ function formatE1(v) {
31
+ if (!Number.isFinite(v))
32
+ return Number.isNaN(v) ? "nan" : v > 0 ? "inf" : "-inf";
33
+ const [mantissa, exponent] = v.toExponential(1).split("e");
34
+ const e = Number(exponent);
35
+ return `${mantissa}e${e < 0 ? "-" : "+"}${String(Math.abs(e)).padStart(2, "0")}`;
36
+ }
37
+ /** The warnings about the Hessian's eigenvalues (negative, or close to 0; internal) */
38
+ export function hessianWarnings(values) {
39
+ const out = [];
40
+ const negative = values.filter((v) => v < -HESSIAN_TOLERANCE);
41
+ const zero = values.filter((v) => Math.abs(v) < HESSIAN_TOLERANCE);
42
+ const plural = (k) => (k === 1 ? "eigenvalue" : "eigenvalues");
43
+ if (negative.length > 0) {
44
+ out.push(`Model failed to converge with ${negative.length} negative ${plural(negative.length)}: ${negative.map(formatE1).join(" ")}`);
45
+ }
46
+ if (zero.length > 0) {
47
+ out.push(`Model may not have converged with ${zero.length} ${plural(zero.length)} close to zero: ${zero.map(formatE1).join(" ")}`);
48
+ }
49
+ return out;
50
+ }
51
+ /**
52
+ * The Satterthwaite quantities of a fit by {@link lmer} (see {@link LmerSatterthwaite}), computed once per fit.
53
+ * Internal: the summary, the contrasts and the ANOVA tables use it.
54
+ */
55
+ export function lmerSatterthwaite(fit) {
56
+ const cached = satterthwaiteByFit.get(fit);
57
+ if (cached !== undefined)
58
+ return cached;
59
+ const internals = lmerInternals(fit);
60
+ const result = satterthwaiteAt(internals.structure, internals.theta, internals.reml, internals.beta0);
61
+ satterthwaiteByFit.set(fit, result);
62
+ return result;
63
+ }
64
+ /**
65
+ * The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there), `beta0` added to the
66
+ * fixed effects (those of a fit's structure, whose response is y − X β₀). Internal: the test evaluates them at lme4's
67
+ * optimum too, to compare with lmerTest's numerical derivatives at the same point.
68
+ */
69
+ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
70
+ const d = varparDerivatives(structure, theta, reml);
71
+ const m = d.varpar.length;
72
+ const e = eigen(d.hessian, { symmetric: true });
73
+ const values = e.values;
74
+ const vectors = e.vectors;
75
+ const vcovVarpar = Array.from({ length: m }, () => new Array(m).fill(0));
76
+ values.forEach((lambda, k) => {
77
+ if (!(lambda > HESSIAN_TOLERANCE))
78
+ return;
79
+ for (let i = 0; i < m; i++) {
80
+ const vi = (2 * vectors[i][k]) / lambda;
81
+ for (let j = 0; j < m; j++)
82
+ vcovVarpar[i][j] += vi * vectors[j][k];
83
+ }
84
+ });
85
+ return {
86
+ varpar: d.varpar,
87
+ hessian: d.hessian,
88
+ hessianEigenvalues: values,
89
+ vcovVarpar,
90
+ beta: d.beta.map((b, k) => b + (beta0[k] ?? 0)),
91
+ sigma: d.varpar[m - 1],
92
+ vcov: d.vcov,
93
+ jacobian: d.jacobian,
94
+ warnings: hessianWarnings(values),
95
+ };
96
+ }
97
+ const quadraticForm = (l, m) => {
98
+ let s = 0;
99
+ for (let i = 0; i < l.length; i++) {
100
+ const li = l[i];
101
+ if (li === 0)
102
+ continue;
103
+ const row = m[i];
104
+ for (let j = 0; j < l.length; j++)
105
+ s += li * row[j] * l[j];
106
+ }
107
+ return s;
108
+ };
109
+ const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
110
+ /** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
111
+ export function tTestOf(s, l, rhs, beta = s.beta) {
112
+ if (l.some(Number.isNaN) || Number.isNaN(rhs))
113
+ return { estimate: NaN, stdError: NaN, df: NaN, tValue: NaN, pValue: NaN };
114
+ const estimate = dot(l, beta);
115
+ const variance = quadraticForm(l, s.vcov);
116
+ const stdError = Math.sqrt(variance);
117
+ const g = s.jacobian.map((j) => quadraticForm(l, j));
118
+ const df = (2 * variance * variance) / quadraticForm(g, s.vcovVarpar);
119
+ const tValue = (estimate - rhs) / stdError;
120
+ const pValue = 2 * pt1(Math.abs(tValue), df, false, false);
121
+ return { estimate, stdError, df, tValue, pValue };
122
+ }
123
+ function fRowOf(s, f, numDF, denDF) {
124
+ const s2 = s.sigma * s.sigma;
125
+ return { sumSq: f * s2 * numDF, meanSq: f * s2, numDF, denDF, F: f, pValue: pf1(f, numDF, denDF, false, false) };
126
+ }
127
+ /** The denominator degrees of freedom of a joint test from those of its rotated contrasts */
128
+ function jointDenDF(nu) {
129
+ if (nu.length === 1)
130
+ return nu[0];
131
+ if (nu.every((v, i) => i === 0 || Math.abs(v - nu[i - 1]) < EQUAL_DF_TOLERANCE))
132
+ return nu.reduce((a, b) => a + b, 0) / nu.length;
133
+ if (nu.some((v) => v <= 2))
134
+ return 2;
135
+ // (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive)
136
+ const e = nu.reduce((sum, v) => sum + v / (v - 2), 0);
137
+ return (2 * e) / (e - nu.length);
138
+ }
139
+ /**
140
+ * The joint F-test of the rows of L (r × p) with Satterthwaite's denominator degrees of freedom (internal; the ANOVA
141
+ * tables use it): undefined when the rows have rank 0 (no test). `rhs` has one value per row (default 0); a non-zero
142
+ * right-hand side with a rank-deficient L adds the warning to `warnings`.
143
+ */
144
+ export function lmerFTest(fit, L, rhs, warnings) {
145
+ return fTestOf(lmerSatterthwaite(fit), L, rhs, warnings);
146
+ }
147
+ /** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
148
+ export function fTestOf(s, L, rhs, warnings) {
149
+ const r = L.length;
150
+ if (r === 0)
151
+ return undefined;
152
+ const right = rhs ?? new Array(r).fill(0);
153
+ if (r === 1) {
154
+ const t = tTestOf(s, L[0], right[0]);
155
+ return fRowOf(s, t.tValue * t.tValue, 1, t.df);
156
+ }
157
+ if (L.some((row) => row.some(Number.isNaN)) || right.some(Number.isNaN))
158
+ return fRowOf(s, NaN, NaN, NaN);
159
+ // L V L' and its eigendecomposition
160
+ const lv = L.map((row) => s.vcov.map((_, j) => row.reduce((sum, v, k) => sum + v * s.vcov[k][j], 0)));
161
+ const e = eigen(lv.map((a) => L.map((rj) => dot(a, rj))), { symmetric: true });
162
+ const d = e.values;
163
+ const cut = Math.max(RANK_TOLERANCE * d[0], 0);
164
+ let kept = 0;
165
+ while (kept < r && d[kept] > cut)
166
+ kept++;
167
+ if (kept === 0)
168
+ return undefined;
169
+ if (kept < r && right.some((v) => v !== 0))
170
+ warnings.add("Contrast is rank deficient and test may be affected");
171
+ // β̂ − b0 with b0 = ginv(L) rhs, the minimum-norm solution of L b0 = rhs
172
+ let beta = s.beta;
173
+ if (right.some((v) => v !== 0)) {
174
+ const g = ginv(L.map((row) => [...row]));
175
+ beta = s.beta.map((b, i) => b - dot(g[i], right));
176
+ }
177
+ const p = s.beta.length;
178
+ const rotated = Array.from({ length: kept }, (_, k) => Array.from({ length: p }, (_, j) => L.reduce((sum, row, i) => sum + e.vectors[i][k] * row[j], 0)));
179
+ if (kept === 1) {
180
+ const t = tTestOf(s, rotated[0], 0, beta);
181
+ return fRowOf(s, t.tValue * t.tValue, 1, t.df);
182
+ }
183
+ let f = 0;
184
+ const nu = [];
185
+ rotated.forEach((row, i) => {
186
+ f += dot(row, beta) ** 2 / d[i];
187
+ const g = s.jacobian.map((j) => quadraticForm(row, j));
188
+ nu.push((2 * d[i] * d[i]) / quadraticForm(g, s.vcovVarpar));
189
+ });
190
+ return fRowOf(s, f / kept, kept, jointDenDF(nu));
191
+ }
192
+ /**
193
+ * The coefficient table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's degrees of freedom and
194
+ * the p-values of the t-tests: the `summary()` of a fit by lmerTest. Equivalent to `lmerTest::summary()` in R.
195
+ *
196
+ * The degrees of freedom of each coefficient are Satterthwaite's: 2 var² / (g'Ag), with var its variance, g its
197
+ * derivative in the variance parameters (θ, σ) and A their asymptotic covariance (twice the inverse Hessian of the
198
+ * deviance). The derivatives are computed analytically at the exact optimum (lmerTest differentiates numerically at
199
+ * lme4's optimum, so its degrees of freedom typically differ in the 5th to 8th significant digit). With
200
+ * `ddf: "lme4"` the table is lme4's (as `coefTable` of the fit), without degrees of freedom and p-values.
201
+ *
202
+ * @param fit A result of {@link lmer} (the object it returned, not a copy).
203
+ * @param options `ddf`: `"Satterthwaite"` (default) or `"lme4"`.
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * // R: summary(lmerTest::lmer(y ~ x + (1 | g), data))
208
+ * const fit = lmer("y ~ x + (1 | g)", {
209
+ * y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4],
210
+ * x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
211
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d"],
212
+ * });
213
+ * const s = lmerSummary(fit);
214
+ * s.names; // ["(Intercept)", "x"]
215
+ * s.df; // [3.2717, 7]
216
+ * s.pValue; // [0.032598, 7.9895e-5]
217
+ * ```
218
+ *
219
+ * @category Mixed models
220
+ */
221
+ export function lmerSummary(fit, options) {
222
+ const ddf = checkOptions("lmerSummary", options, ["ddf"], []).ddf ?? "Satterthwaite";
223
+ if (ddf !== "Satterthwaite" && ddf !== "lme4")
224
+ throw new RangeError(`ddf must be "Satterthwaite" or "lme4", not ${JSON.stringify(ddf)}`);
225
+ const internals = lmerInternals(fit);
226
+ const names = [...internals.structure.xColNames];
227
+ if (ddf === "lme4") {
228
+ const { estimate, stdError, tValue } = fit.coefTable;
229
+ return { ddf, names, estimate: [...estimate], stdError: [...stdError], tValue: [...tValue], messages: [], warnings: [] };
230
+ }
231
+ const s = lmerSatterthwaite(fit);
232
+ const p = names.length;
233
+ const rows = names.map((_, i) => tTestOf(s, Array.from({ length: p }, (_, j) => (j === i ? 1 : 0)), 0));
234
+ return {
235
+ ddf,
236
+ names,
237
+ estimate: rows.map((r) => r.estimate),
238
+ stdError: rows.map((r) => r.stdError),
239
+ df: rows.map((r) => r.df),
240
+ tValue: rows.map((r) => r.tValue),
241
+ pValue: rows.map((r) => r.pValue),
242
+ messages: [],
243
+ warnings: [...s.warnings],
244
+ };
245
+ }
246
+ const CONTEST_KEYS = ["rhs", "joint", "confint", "level"];
247
+ const CONTEST_UNSUPPORTED = ["collect", "checkEstimability", "check_estimability", "ddf"];
248
+ /** The rows of a contrast argument: a vector is one row; each row must have one value per fixed effect */
249
+ function contrastRows(L, p) {
250
+ if (!Array.isArray(L))
251
+ throw new TypeError("L must be an array of numbers or an array of rows");
252
+ const rows = L.length > 0 && Array.isArray(L[0]) ? L.map((r) => [...r]) : [[...L]];
253
+ for (const row of rows) {
254
+ if (!Array.isArray(row) || row.some((v) => typeof v !== "number"))
255
+ throw new TypeError("L must be an array of numbers or an array of rows");
256
+ if (row.length !== p)
257
+ throw new TypeError(`each contrast must have ${p} values (one per fixed effect), not ${row.length}`);
258
+ }
259
+ return rows;
260
+ }
261
+ export function lmerContest(fit, L, options) {
262
+ options = checkOptions("lmerContest", options, CONTEST_KEYS, CONTEST_UNSUPPORTED);
263
+ const joint = logicalOption(options.joint, true);
264
+ const confint = logicalOption(options.confint, true);
265
+ const internals = lmerInternals(fit);
266
+ const p = internals.structure.xColNames.length;
267
+ const rows = contrastRows(L, p);
268
+ const level = options.level ?? 0.95;
269
+ if (typeof level !== "number" || !(level >= 0 && level <= 1))
270
+ throw new RangeError("level must be a number between 0 and 1");
271
+ const rhsOption = options.rhs ?? 0;
272
+ const rhs = typeof rhsOption === "number" ? new Array(rows.length).fill(rhsOption) : [...rhsOption];
273
+ if (rhs.length !== rows.length || rhs.some((v) => typeof v !== "number")) {
274
+ throw new TypeError(`rhs must be a number or have one value per contrast (${rows.length})`);
275
+ }
276
+ const warnings = new Warnings();
277
+ const s = lmerSatterthwaite(fit);
278
+ s.warnings.forEach((w) => warnings.add(w));
279
+ if (joint) {
280
+ const row = p === 0 ? undefined : lmerFTest(fit, rows, rhs, warnings);
281
+ const pick = (k) => (row === undefined ? [] : [row[k]]);
282
+ return {
283
+ joint: true,
284
+ sumSq: pick("sumSq"),
285
+ meanSq: pick("meanSq"),
286
+ numDF: pick("numDF"),
287
+ denDF: pick("denDF"),
288
+ F: pick("F"),
289
+ pValue: pick("pValue"),
290
+ messages: [],
291
+ warnings: warnings.list,
292
+ };
293
+ }
294
+ const tests = p === 0 ? [] : rows.map((row, i) => tTestOf(s, row, rhs[i]));
295
+ const out = {
296
+ joint: false,
297
+ estimate: tests.map((t) => t.estimate),
298
+ stdError: tests.map((t) => t.stdError),
299
+ df: tests.map((t) => t.df),
300
+ tValue: tests.map((t) => t.tValue),
301
+ pValue: tests.map((t) => t.pValue),
302
+ messages: [],
303
+ warnings: warnings.list,
304
+ };
305
+ if (confint) {
306
+ const quantiles = tests.map((t) => qt1((1 - level) / 2, t.df, false, false));
307
+ out.lower = tests.map((t, i) => t.estimate - t.stdError * quantiles[i]);
308
+ out.upper = tests.map((t, i) => t.estimate + t.stdError * quantiles[i]);
309
+ }
310
+ return out;
311
+ }
@@ -0,0 +1,27 @@
1
+ import type { MixedModelStructure } from "./mixedStructure.js";
2
+ /** The derivatives of {@link varparDerivatives} */
3
+ export interface VarparDerivatives {
4
+ /** varpar = (θ, σ), σ = sqrt(r² / ν) */
5
+ varpar: number[];
6
+ /** The deviance d(θ, σ) at varpar */
7
+ deviance: number;
8
+ /** Its gradient in varpar (0 at the optimum) */
9
+ gradient: number[];
10
+ /** The derivatives of Φ (the log determinants) and of r² in θ, and r² */
11
+ phiGradient: number[];
12
+ prssGradient: number[];
13
+ prss: number;
14
+ /** Its Hessian in varpar (m × m, array of rows) */
15
+ hessian: number[][];
16
+ /** β̂ at θ */
17
+ beta: number[];
18
+ /** C = σ² S⁻¹ at varpar (p × p, array of rows) */
19
+ vcov: number[][];
20
+ /** J_k = ∂C/∂varpar_k, one p × p matrix (array of rows) per element of varpar */
21
+ jacobian: number[][][];
22
+ }
23
+ /**
24
+ * The deviance d(θ, σ) in the variance parameters, its gradient and Hessian, and the covariance of β̂ with its
25
+ * Jacobians, at θ with σ = sqrt(r²(θ) / ν) (see the header). Internal.
26
+ */
27
+ export declare function varparDerivatives(structure: MixedModelStructure, theta: readonly number[], reml: boolean): VarparDerivatives;
@@ -0,0 +1,342 @@
1
+ // The derivatives that lmerTest's Satterthwaite approximation needs (oracle/lmertest-behaviour.md, section 1): the
2
+ // Hessian H of the deviance d(θ, σ) in the variance parameters varpar = (θ, σ), and the Jacobians J_k of the covariance
3
+ // of the fixed effects C(varpar) = σ² (R_X'R_X)⁻¹, at a given θ (σ from the penalised residual sum of squares).
4
+ // Computed analytically and sparsely; nothing is differentiated numerically.
5
+ //
6
+ // Written for rStats.js (no ported code) from the specification and the penalised least squares of D. Bates,
7
+ // M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of Statistical
8
+ // Software 67(1). The notation is that of src/models/mixedDeviance.ts: A = Λ'Z'ZΛ + I = L L', S = R_X'R_X,
9
+ // W = A⁻¹ Λ'Z'X (q × p), E = X − ZΛW (n × p), res = y − Xβ̂ − ZΛû, r² = ‖res‖² + ‖û‖² (the penalised residual sum of
10
+ // squares). Λ is linear in θ, Λ = Σ_k θ_k D_k with D_k the 0/1 pattern of θ_k's entries.
11
+ //
12
+ // The deviance. With ν = n − p (REML) or n (ML) and Φ(θ) = log det A [+ log det S for REML],
13
+ // d(θ, σ) = Φ(θ) + r²(θ) / σ² + ν log(2π σ²),
14
+ // so ∂²d/∂θ_k∂θ_l = Φ_kl + r²_kl / σ², ∂²d/∂θ_k∂σ = −2 r²_k / σ³, ∂²d/∂σ² = 6 r² / σ⁴ − 2ν / σ².
15
+ //
16
+ // r²: r² is a minimum over (u, β), so r²_k = −2 res'Z D_k û (only the explicit dependence counts), and
17
+ // r²_kl = −2 (∂_l res' Z D_k û + res' Z D_k ∂_l û), ∂_l res = −Z D_l û − ZΛ ∂_l û − X ∂_l β,
18
+ // with (∂_l û, ∂_l β) from the normal equations M (∂u, ∂β) = (D_l'Z'res − Λ'Z'Z D_l û, −X'Z D_l û) (the derivative of
19
+ // M γ = G'y, G = [ZΛ, X]), solved with the factors of the fit and refined once with residuals from the data.
20
+ //
21
+ // log det A: ∂_k log det A = 2 tr(A⁻¹ Λ'Z'Z D_k) = 2 Σ_(r,c) (A⁻¹ Λ'Z'Z)[c, r] over the entries (r, c) of D_k (the
22
+ // gradient of mixedDeviance.ts), and its derivative along θ_l is
23
+ // 2 Σ_(r,c) (∂_l(A⁻¹) Λ'Z'Z + A⁻¹ D_l'Z'Z)[c, r].
24
+ // Both terms need their first factor only on the blocks of Z'Z, which lie on the pattern of L: A⁻¹ there is the selected
25
+ // inverse, and ∂_l(A⁻¹) there is the derivative of the selected inverse, obtained by differentiating, step by step, the
26
+ // left-looking factorisation (∂L from ∂A = D_l'Z'ZΛ + Λ'Z'Z D_l, a sparse matrix on the same pattern) and Takahashi's
27
+ // recurrences (forward-mode differentiation of the algorithms, exact up to rounding). Each direction costs about one
28
+ // factorisation and one selected inverse more.
29
+ //
30
+ // log det S (REML): ∂_k S = −E'Z D_k W − (E'Z D_k W)', so ∂_k log det S = tr(S⁻¹ ∂_k S), and
31
+ // ∂_kl log det S = tr(S⁻¹ ∂_l ∂_k S) − tr(S⁻¹ ∂_k S S⁻¹ ∂_l S),
32
+ // ∂_l ∂_k S = −(∂_l E' Z D_k W + E'Z D_k ∂_l W) − (...)',
33
+ // ∂_l W = A⁻¹ (D_l'Z'E − Λ'Z'Z D_l W), ∂_l E = −Z D_l W − ZΛ ∂_l W.
34
+ //
35
+ // The Jacobians: J_k = −σ² S⁻¹ ∂_k S S⁻¹ for θ_k and J_σ = 2σ S⁻¹.
36
+ import { factoriseSystemTangent, inverseFromFactor, lambdaTimes, lambdaTransposeTimes, levelTraceSums, plsState, selectedInverse, selectedInverseTangent, solveL, solveLt, } from "./mixedDeviance.js";
37
+ /** T1_g' Z'Z(g, h) T2_h for every block (g, h) of Z'Z (the layout of the blocks of A), from the blocks T1 and T2 */
38
+ function sandwich(sys, t1, t2) {
39
+ const out = new Float64Array(sys.zz.length);
40
+ let work = new Float64Array(64);
41
+ for (let h = 0; h < sys.nGroups; h++) {
42
+ const kc = sys.groupTerm[h];
43
+ const ncc = sys.termNc[kc];
44
+ const tc = t2[kc];
45
+ for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
46
+ const kr = sys.groupTerm[sys.blockRow[b]];
47
+ const ncr = sys.termNc[kr];
48
+ const tr = t1[kr];
49
+ const base = sys.blockValueStart[b];
50
+ if (work.length < ncr * ncc)
51
+ work = new Float64Array(ncr * ncc);
52
+ for (let c = 0; c < ncc; c++) {
53
+ for (let r = 0; r < ncr; r++) {
54
+ let sum = 0;
55
+ for (let m = 0; m < ncc; m++)
56
+ sum += sys.zz[base + r + m * ncr] * tc[m + c * ncc];
57
+ work[r + c * ncr] = sum;
58
+ }
59
+ }
60
+ for (let c = 0; c < ncc; c++) {
61
+ for (let r = 0; r < ncr; r++) {
62
+ let sum = 0;
63
+ for (let m = 0; m < ncr; m++)
64
+ sum += tr[m + r * ncr] * work[m + c * ncr];
65
+ out[base + r + c * ncr] = sum;
66
+ }
67
+ }
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ /** p × p column-major products */
73
+ function matMul(a, b, p) {
74
+ const out = new Float64Array(p * p);
75
+ for (let j = 0; j < p; j++) {
76
+ for (let k = 0; k < p; k++) {
77
+ const bkj = b[k + j * p];
78
+ if (bkj === 0)
79
+ continue;
80
+ for (let i = 0; i < p; i++)
81
+ out[i + j * p] += a[i + k * p] * bkj;
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+ const trace = (a, p) => {
87
+ let s = 0;
88
+ for (let i = 0; i < p; i++)
89
+ s += a[i + i * p];
90
+ return s;
91
+ };
92
+ const rowsOf = (a, p) => Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => a[i + j * p]));
93
+ /**
94
+ * The deviance d(θ, σ) in the variance parameters, its gradient and Hessian, and the covariance of β̂ with its
95
+ * Jacobians, at θ with σ = sqrt(r²(θ) / ν) (see the header). Internal.
96
+ */
97
+ export function varparDerivatives(structure, theta, reml) {
98
+ const st = plsState(structure, theta);
99
+ const { sys, t, l, rx, ws, xResiduals, res, uv } = st;
100
+ const { n, p, q } = sys;
101
+ const nt = theta.length;
102
+ const m = nt + 1;
103
+ // Z v, Z' v
104
+ const zTimes = (v) => {
105
+ const out = new Float64Array(n);
106
+ for (let i = 0; i < n; i++) {
107
+ let sum = 0;
108
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
109
+ sum += sys.rowValues[c] * v[sys.rowCols[c]];
110
+ out[i] = sum;
111
+ }
112
+ return out;
113
+ };
114
+ const zTransposeTimes = (v) => {
115
+ const out = new Float64Array(q);
116
+ for (let i = 0; i < n; i++) {
117
+ const vi = v[i];
118
+ if (vi === 0)
119
+ continue;
120
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
121
+ out[sys.rowCols[c]] += sys.rowValues[c] * vi;
122
+ }
123
+ return out;
124
+ };
125
+ const xTransposeTimes = (v) => {
126
+ const out = new Float64Array(p);
127
+ for (let i = 0; i < n; i++) {
128
+ const xi = structure.x[i];
129
+ const vi = v[i];
130
+ for (let k = 0; k < p; k++)
131
+ out[k] += xi[k] * vi;
132
+ }
133
+ return out;
134
+ };
135
+ const xTimes = (v) => {
136
+ const out = new Float64Array(n);
137
+ for (let i = 0; i < n; i++) {
138
+ const xi = structure.x[i];
139
+ let sum = 0;
140
+ for (let k = 0; k < p; k++)
141
+ sum += xi[k] * v[k];
142
+ out[i] = sum;
143
+ }
144
+ return out;
145
+ };
146
+ const solveA = (v) => {
147
+ solveL(sys, l, v);
148
+ solveLt(sys, l, v);
149
+ };
150
+ // the entries (r, c) of each D_k
151
+ const entryRows = Array.from({ length: nt }, () => []);
152
+ const entryCols = Array.from({ length: nt }, () => []);
153
+ for (const { row, col, theta: k } of structure.lambda) {
154
+ entryRows[k].push(row);
155
+ entryCols[k].push(col);
156
+ }
157
+ /** D_k w */
158
+ const dTimes = (k, w) => {
159
+ const out = new Float64Array(q);
160
+ const rs = entryRows[k];
161
+ const cs = entryCols[k];
162
+ for (let e = 0; e < rs.length; e++)
163
+ out[rs[e]] += w[cs[e]];
164
+ return out;
165
+ };
166
+ /** D_k' v */
167
+ const dTransposeTimes = (k, v) => {
168
+ const out = new Float64Array(q);
169
+ const rs = entryRows[k];
170
+ const cs = entryCols[k];
171
+ for (let e = 0; e < rs.length; e++)
172
+ out[cs[e]] += v[rs[e]];
173
+ return out;
174
+ };
175
+ /** Σ over the entries (r, c) of D_k of a[r] b[c] */
176
+ const entrySum = (k, a, b) => {
177
+ const rs = entryRows[k];
178
+ const cs = entryCols[k];
179
+ let s = 0;
180
+ for (let e = 0; e < rs.length; e++)
181
+ s += a[rs[e]] * b[cs[e]];
182
+ return s;
183
+ };
184
+ /** −(F'Z D_k G) − (...)' for q-vectors per column: F = the columns zf (Z'·), G = the columns g (p × p, column-major) */
185
+ const symmetricEntryProduct = (k, zf, g, out, scale) => {
186
+ for (let a = 0; a < p; a++) {
187
+ for (let b = 0; b < p; b++) {
188
+ const v = scale * entrySum(k, zf[a], g[b]);
189
+ out[a + b * p] += v;
190
+ out[b + a * p] += v;
191
+ }
192
+ }
193
+ };
194
+ let rss = 0;
195
+ for (const e of res)
196
+ rss += e * e;
197
+ let ussq = 0;
198
+ for (const v of uv)
199
+ ussq += v * v;
200
+ const prss = rss + ussq;
201
+ const nu = reml ? n - p : n;
202
+ const sigma2 = prss / nu;
203
+ const sigma = Math.sqrt(sigma2);
204
+ let logDetL = 0;
205
+ for (let j = 0; j < q; j++)
206
+ logDetL += Math.log(l[sys.colStart[j]]);
207
+ logDetL *= 2;
208
+ let logDetRX = 0;
209
+ for (let k = 0; k < p; k++)
210
+ logDetRX += Math.log(rx[k + k * p]);
211
+ logDetRX *= 2;
212
+ const phi = reml ? logDetL + logDetRX : logDetL;
213
+ const deviance = phi + prss / sigma2 + nu * Math.log(2 * Math.PI * sigma2);
214
+ const sInverse = inverseFromFactor(rx, p);
215
+ const inv = selectedInverse(sys, l);
216
+ const zRes = zTransposeTimes(res);
217
+ const zE = xResiduals.map(zTransposeTimes);
218
+ // first derivatives: Φ_k and r²_k; ∂_k S
219
+ const sums = levelTraceSums(sys, inv, t);
220
+ const phiGrad = new Array(nt).fill(0);
221
+ const addTrace = (s, into, factor) => {
222
+ sys.termTheta.forEach((idx, k) => {
223
+ const nc = sys.termNc[k];
224
+ for (let cl = 0; cl < nc; cl++)
225
+ for (let rl = cl; rl < nc; rl++)
226
+ into[idx[rl + cl * nc]] += factor * s[k][cl + rl * nc];
227
+ });
228
+ };
229
+ addTrace(sums, phiGrad, 2);
230
+ const r2Grad = Array.from({ length: nt }, (_, k) => -2 * entrySum(k, zRes, uv));
231
+ const dS = Array.from({ length: nt }, (_, k) => {
232
+ const out = new Float64Array(p * p);
233
+ symmetricEntryProduct(k, zE, ws, out, -1);
234
+ return out;
235
+ });
236
+ if (reml)
237
+ for (let k = 0; k < nt; k++)
238
+ phiGrad[k] += trace(matMul(sInverse, dS[k], p), p);
239
+ const sInvDS = dS.map((d) => matMul(sInverse, d, p));
240
+ const hessian = Array.from({ length: m }, () => new Array(m).fill(0));
241
+ for (let dir = 0; dir < nt; dir++) {
242
+ // ∂T along θ_dir
243
+ const dt = sys.termTheta.map((idx) => Float64Array.from(idx, (k) => (k === dir ? 1 : 0)));
244
+ // log det A
245
+ const da = sandwich(sys, dt, t);
246
+ const daT = sandwich(sys, t, dt);
247
+ for (let i = 0; i < da.length; i++)
248
+ da[i] += daT[i];
249
+ const dl = factoriseSystemTangent(sys, l, da);
250
+ const dInv = selectedInverseTangent(sys, l, dl, inv);
251
+ const column = new Array(nt).fill(0);
252
+ const s1 = levelTraceSums(sys, dInv, t);
253
+ const s2 = levelTraceSums(sys, inv, dt);
254
+ addTrace(s1, column, 2);
255
+ addTrace(s2, column, 2);
256
+ // log det S (REML)
257
+ if (reml && p > 0) {
258
+ const dW = [];
259
+ const zdE = [];
260
+ for (let a = 0; a < p; a++) {
261
+ const dw = dTransposeTimes(dir, zE[a]);
262
+ const zdw = lambdaTransposeTimes(sys, t, zTransposeTimes(zTimes(dTimes(dir, ws[a]))));
263
+ for (let i = 0; i < q; i++)
264
+ dw[i] -= zdw[i];
265
+ solveA(dw);
266
+ dW.push(dw);
267
+ const inner = dTimes(dir, ws[a]);
268
+ const lw = lambdaTimes(sys, t, dw);
269
+ for (let i = 0; i < q; i++)
270
+ inner[i] += lw[i];
271
+ const de = zTimes(inner);
272
+ for (let i = 0; i < n; i++)
273
+ de[i] = -de[i];
274
+ zdE.push(zTransposeTimes(de));
275
+ }
276
+ for (let k = 0; k < nt; k++) {
277
+ const d2 = new Float64Array(p * p);
278
+ symmetricEntryProduct(k, zdE, ws, d2, -1);
279
+ symmetricEntryProduct(k, zE, dW, d2, -1);
280
+ column[k] += trace(matMul(sInverse, d2, p), p) - trace(matMul(sInvDS[k], sInvDS[dir], p), p);
281
+ }
282
+ }
283
+ // r²: the derivative of the penalised least-squares solution along θ_dir
284
+ const zdu = zTimes(dTimes(dir, uv));
285
+ const gu = dTransposeTimes(dir, zRes);
286
+ const lzz = lambdaTransposeTimes(sys, t, zTransposeTimes(zdu));
287
+ for (let i = 0; i < q; i++)
288
+ gu[i] -= lzz[i];
289
+ const gb = xTransposeTimes(zdu);
290
+ for (let k = 0; k < p; k++)
291
+ gb[k] = -gb[k];
292
+ const du = gu.slice();
293
+ const db = gb.slice();
294
+ st.solveNormal(du, db);
295
+ {
296
+ // one step of refinement: the residual of the normal equations, M (du, db) from the data
297
+ const fit = zTimes(lambdaTimes(sys, t, du));
298
+ const xdb = xTimes(db);
299
+ for (let i = 0; i < n; i++)
300
+ fit[i] += xdb[i];
301
+ const ru = lambdaTransposeTimes(sys, t, zTransposeTimes(fit));
302
+ const rb = xTransposeTimes(fit);
303
+ for (let i = 0; i < q; i++)
304
+ ru[i] = gu[i] - ru[i] - du[i];
305
+ for (let k = 0; k < p; k++)
306
+ rb[k] = gb[k] - rb[k];
307
+ st.solveNormal(ru, rb);
308
+ for (let i = 0; i < q; i++)
309
+ du[i] += ru[i];
310
+ for (let k = 0; k < p; k++)
311
+ db[k] += rb[k];
312
+ }
313
+ const dres = zTimes(lambdaTimes(sys, t, du));
314
+ const xdb = xTimes(db);
315
+ for (let i = 0; i < n; i++)
316
+ dres[i] = -(zdu[i] + dres[i] + xdb[i]);
317
+ const zdres = zTransposeTimes(dres);
318
+ for (let k = 0; k < nt; k++) {
319
+ const r2kl = -2 * (entrySum(k, zdres, uv) + entrySum(k, zRes, du));
320
+ hessian[k][dir] = column[k] + r2kl / sigma2;
321
+ }
322
+ }
323
+ // symmetric
324
+ for (let k = 0; k < nt; k++) {
325
+ for (let j = k + 1; j < nt; j++) {
326
+ const v = (hessian[k][j] + hessian[j][k]) / 2;
327
+ hessian[k][j] = v;
328
+ hessian[j][k] = v;
329
+ }
330
+ const v = (-2 * r2Grad[k]) / (sigma2 * sigma);
331
+ hessian[k][nt] = v;
332
+ hessian[nt][k] = v;
333
+ }
334
+ hessian[nt][nt] = (6 * prss) / (sigma2 * sigma2) - (2 * nu) / sigma2;
335
+ const gradient = [...phiGrad.map((g, k) => g + r2Grad[k] / sigma2), (-2 * prss) / (sigma2 * sigma) + (2 * nu) / sigma];
336
+ const vcov = rowsOf(sInverse.map((v) => sigma2 * v), p);
337
+ const jacobian = [
338
+ ...dS.map((_, k) => rowsOf(matMul(sInvDS[k], sInverse, p).map((v) => -sigma2 * v), p)),
339
+ rowsOf(sInverse.map((v) => 2 * sigma * v), p),
340
+ ];
341
+ return { varpar: [...theta, sigma], deviance, gradient, phiGradient: phiGrad, prssGradient: r2Grad, prss, hessian, beta: Array.from(st.beta), vcov, jacobian };
342
+ }