@numero-uno-jpn/rstats 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.ja.md +42 -12
  3. package/README.md +40 -10
  4. package/dist/chunks/{chunk-FVPDVRJQ.js → chunk-3VMBBQLV.js} +2 -2
  5. package/dist/chunks/chunk-4OKAZJJG.js +3 -0
  6. package/dist/chunks/{chunk-GG4BJMJW.js → chunk-6BH65HGN.js} +1 -1
  7. package/dist/chunks/chunk-ATC4F4BX.js +2 -0
  8. package/dist/chunks/{chunk-6I6QKTFK.js → chunk-EDH53DXN.js} +2 -2
  9. package/dist/chunks/{chunk-ZRJQD7VS.js → chunk-EZ2KD5NA.js} +2 -2
  10. package/dist/chunks/{chunk-KK4GE65D.js → chunk-GSPOO2G3.js} +2 -2
  11. package/dist/chunks/{chunk-36GVER3O.js → chunk-K7AZ65H7.js} +2 -2
  12. package/dist/chunks/{chunk-2X7JYQBI.js → chunk-LEIH4U5X.js} +2 -2
  13. package/dist/chunks/{chunk-ETOEZTGL.js → chunk-OX3SBG5X.js} +1 -1
  14. package/dist/chunks/chunk-SGZQDJRR.js +2 -0
  15. package/dist/chunks/{chunk-PHHUHR7T.js → chunk-UH2N3ZQW.js} +1 -1
  16. package/dist/chunks/chunk-UV2MZYDQ.js +2 -0
  17. package/dist/chunks/{chunk-WQPFDDIY.js → chunk-VQHEOBTM.js} +2 -2
  18. package/dist/chunks/chunk-WJQZZYOI.js +2 -0
  19. package/dist/chunks/chunk-WKEFHOFR.js +2 -0
  20. package/dist/chunks/{chunk-X2AWQSVS.js → chunk-WXC25OPJ.js} +2 -2
  21. package/dist/chunks/{chunk-HITD7CX6.js → chunk-XJQKSR52.js} +1 -1
  22. package/dist/data/grouping.d.ts +6 -3
  23. package/dist/data/grouping.js +19 -22
  24. package/dist/descriptive.js +2 -2
  25. package/dist/distributions.js +2 -2
  26. package/dist/entries/mixed.d.ts +1 -0
  27. package/dist/entries/mixed.js +2 -0
  28. package/dist/htest/testFormula.js +6 -3
  29. package/dist/linalg.js +2 -2
  30. package/dist/mixed.js +3 -0
  31. package/dist/models/aovStrata.d.ts +1 -1
  32. package/dist/models/aovStrata.js +5 -1
  33. package/dist/models/formula.d.ts +26 -1
  34. package/dist/models/formula.js +125 -9
  35. package/dist/models/lm.d.ts +2 -2
  36. package/dist/models/lmer.d.ts +162 -0
  37. package/dist/models/lmer.js +457 -0
  38. package/dist/models/mixedDeviance.d.ts +44 -0
  39. package/dist/models/mixedDeviance.js +872 -0
  40. package/dist/models/mixedStructure.d.ts +82 -0
  41. package/dist/models/mixedStructure.js +309 -0
  42. package/dist/models/modelFrame.d.ts +12 -1
  43. package/dist/models/modelFrame.js +36 -21
  44. package/dist/models/modelMatrix.d.ts +15 -4
  45. package/dist/models/modelMatrix.js +18 -4
  46. package/dist/numerics.js +2 -2
  47. package/dist/rstats.js +14 -14
  48. package/dist/special.js +2 -2
  49. package/dist/tests.js +12 -12
  50. package/llms.txt +11 -3
  51. package/package.json +5 -1
  52. package/dist/chunks/chunk-3WUXRSM6.js +0 -2
  53. package/dist/chunks/chunk-LAUYSGV4.js +0 -3
  54. package/dist/chunks/chunk-M6GDXKKS.js +0 -2
@@ -0,0 +1,872 @@
1
+ // The profiled deviance of a linear mixed model (lme4's lmer) at a given θ: the penalised least-squares solution
2
+ // (β̂, û), the random effects b = Λ_θ û, the residual and penalty sums of squares, the log determinants of L_θ and
3
+ // R_X, and the REML criterion or the ML deviance. Nothing is optimised here.
4
+ //
5
+ // Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1b, "The profiled deviance", and
6
+ // "Sparse computation (stages S1 and S2)") and the penalised least squares (equations (13)-(19)) 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 sparse Cholesky factorisation follows the textbook description (elimination tree, symbolic
9
+ // factorisation by merging the patterns of the children, left-looking numeric factorisation), as in J. W. H. Liu
10
+ // (1990), "The role of elimination trees in sparse factorization", SIAM J. Matrix Anal. Appl. 11(1).
11
+ //
12
+ // Sparse implementation. The columns of Z come in groups: one group of nc_k contiguous columns per level of each term
13
+ // k (level-major, as in Z), and Λ_θ is block diagonal with the block T_k on each group of term k. So
14
+ // A = Λ_θ' Z'Z Λ_θ + I
15
+ // is made of dense blocks A(g, h) = T' Z'Z(g, h) T between groups g and h that share rows, and it is stored by blocks.
16
+ // Z'Z by blocks, Z'X (q × p), Z'y and X'y do not depend on θ and are formed once per structure, together with
17
+ // the pattern of the Cholesky factor L (A = L L'). Nothing of size q × q or n × q is stored.
18
+ //
19
+ // Ordering: the columns are factorised in their own order (the permutation P of the paper is the identity). The terms
20
+ // are ordered by decreasing number of levels, so the first term is the one with the most groups, and its block of A
21
+ // is block diagonal (a row has one level per term): eliminating its groups first creates no fill among them, only
22
+ // among the groups of later terms that share rows with one of its levels. Models with one grouping factor, or with
23
+ // nested factors, have no fill-in at all; crossed factors fill in the blocks of the later terms (dense for a fully
24
+ // crossed design, whatever the ordering).
25
+ //
26
+ // Symbolic factorisation (once per structure), on the groups: the elimination tree of the group graph, and the
27
+ // pattern of each group's columns below its diagonal block (the groups adjacent to it in A after it, merged with the
28
+ // patterns of its children in the tree). A group's columns share that pattern, so L is stored by columns (compressed
29
+ // sparse columns, rows increasing, the diagonal first) with each column holding the rest of its diagonal block and
30
+ // the columns of the groups of its pattern. Numeric factorisation (at each θ), left-looking by columns: column j of A
31
+ // is scattered into a work vector, the columns k < j with L[j, k] ≠ 0 (row lists formed with the pattern) are
32
+ // subtracted, and column j of L is the result divided by the square root of its diagonal element.
33
+ //
34
+ // With L, the computation is that of the dense implementation (the reference in test/helpers/mixedDense.ts), with
35
+ // triangular solves by L instead of dense ones:
36
+ // C_X = L⁻¹ Λ_θ' Z'X, W = L'⁻¹ C_X = A⁻¹ Λ_θ' Z'X (q × p)
37
+ // R_X' R_X = E'E + W'W, with E = X − ZΛ_θ W (n × p, as X; Cholesky, p × p)
38
+ // (û, β̂) from the normal equations of the penalised least squares, solved with L, C_X and R_X.
39
+ // Forming the normal equations squares the condition number, and X'X − C_X'C_X loses digits by cancellation, so W and
40
+ // the solution are refined once with residuals computed from the data and the sparse Z (E, and y − Xβ̂ − ZΛ_θ û),
41
+ // which recovers the accuracy of an orthogonal decomposition (the corrected semi-normal equations), and R_X' R_X is
42
+ // formed as the sum of squares E'E + W'W.
43
+ //
44
+ // On request, the gradient of the criterion with respect to θ (for the fit, stage 1c), derived from the formulas
45
+ // above. With ∂Λ the derivative of Λ_θ with respect to one element of θ (the entries (r, c) of Λ_θ that hold it),
46
+ // K = Λ_θ'Z'Z and the residual res = y − Xβ̂ − ZΛ_θ û:
47
+ // ∂ prss = −2 res'Z ∂Λ û (prss is a minimum over (β, u), so only its explicit dependence on θ counts),
48
+ // ∂ log det A = 2 tr(A⁻¹ K ∂Λ) = 2 Σ_(r,c) (A⁻¹K)[c, r],
49
+ // ∂ (log det A + log det R_X'R_X) = ∂ log det M, M = [A, Λ'Z'X; X'ZΛ, X'X], which adds −2 Σ_(r,c) (W S⁻¹ E'Z)[c, r]
50
+ // (S = R_X'R_X; the blocks of M⁻¹ are A⁻¹ + W S⁻¹ W' and −W S⁻¹, and X'Z − W'K = E'Z).
51
+ // The criterion's derivative is then the log-determinant terms plus (n or n − p) ∂ prss / prss. The trace term needs
52
+ // A⁻¹ only on the blocks of Z'Z, which lie on the pattern of L: the selected inverse (A⁻¹ on the pattern of L, by
53
+ // Takahashi's recurrences; K by blocks of Z'Z, never formed), so the gradient costs about one more factorisation, and
54
+ // memory of the order of the nonzeros of L, Z and Z'X.
55
+ import { potf2, potri } from "../linalg/chol.js";
56
+ /** Steps of iterative refinement of the penalised least-squares solution */
57
+ const REFINEMENT_STEPS = 1;
58
+ const systemCache = new WeakMap();
59
+ /** The groups of columns, the cross-products and the pattern of the factor of a structure (cached) */
60
+ function sparseSystemOf(s) {
61
+ const cached = systemCache.get(s);
62
+ if (cached !== undefined)
63
+ return cached;
64
+ const n = s.y.length;
65
+ const p = s.xColNames.length;
66
+ const q = s.q;
67
+ const nTerms = s.terms.length;
68
+ // the groups of columns, in the order of the columns
69
+ const nGroups = s.terms.reduce((sum, t) => sum + t.nLevels, 0);
70
+ const groupStart = new Int32Array(nGroups + 1);
71
+ const groupTerm = new Int32Array(nGroups);
72
+ const termFirstGroup = [];
73
+ const termNc = [];
74
+ let g = 0;
75
+ s.terms.forEach((t, k) => {
76
+ const nc = t.columns.length;
77
+ termFirstGroup.push(g);
78
+ termNc.push(nc);
79
+ for (let l = 0; l < t.nLevels; l++, g++) {
80
+ groupStart[g] = t.zOffset + l * nc;
81
+ groupTerm[g] = k;
82
+ }
83
+ });
84
+ groupStart[nGroups] = q;
85
+ // the elements of each T_k, from the entries of Λ_θ in the first level of the term
86
+ const termTheta = s.terms.map((t, k) => {
87
+ const nc = termNc[k];
88
+ const idx = new Int32Array(nc * nc).fill(-1);
89
+ for (const { row, col, theta } of s.lambda) {
90
+ if (col >= t.zOffset && col < t.zOffset + nc)
91
+ idx[row - t.zOffset + (col - t.zOffset) * nc] = theta;
92
+ }
93
+ return idx;
94
+ });
95
+ // for each row: its group in each term and the term's left-hand side values; Z by rows (nonzero entries)
96
+ const codesOf = s.terms.map((t) => s.groups[t.group].codes);
97
+ const counts = new Int32Array(n + 1);
98
+ for (let i = 0; i < n; i++) {
99
+ let c = 0;
100
+ for (const t of s.terms)
101
+ for (const v of t.matrix[i])
102
+ if (v !== 0)
103
+ c++;
104
+ counts[i + 1] = counts[i] + c;
105
+ }
106
+ const rowStart = counts;
107
+ const nnz = rowStart[n];
108
+ const rowCols = new Int32Array(nnz);
109
+ const rowValues = new Float64Array(nnz);
110
+ {
111
+ let at = 0;
112
+ for (let i = 0; i < n; i++) {
113
+ s.terms.forEach((t, k) => {
114
+ const base = t.zOffset + codesOf[k][i] * termNc[k];
115
+ t.matrix[i].forEach((v, j) => {
116
+ if (v === 0)
117
+ return;
118
+ rowCols[at] = base + j;
119
+ rowValues[at++] = v;
120
+ });
121
+ });
122
+ }
123
+ }
124
+ // Z'Z by blocks: the blocks (g, h), g ≥ h, of groups that share a row (all diagonal blocks)
125
+ const blockKeys = new Map();
126
+ const pairRow = [];
127
+ const pairCol = [];
128
+ const addPair = (gr, gc) => {
129
+ const key = gc * nGroups + gr;
130
+ let b = blockKeys.get(key);
131
+ if (b === undefined) {
132
+ b = pairRow.length;
133
+ blockKeys.set(key, b);
134
+ pairRow.push(gr);
135
+ pairCol.push(gc);
136
+ }
137
+ return b;
138
+ };
139
+ for (let h = 0; h < nGroups; h++)
140
+ addPair(h, h);
141
+ const rowGroups = new Int32Array(nTerms);
142
+ // for each row, the block of each pair of its terms k ≥ l, at i nPairs + k (k + 1) / 2 + l (the groups of later
143
+ // terms come later in the columns)
144
+ const nPairs = (nTerms * (nTerms + 1)) / 2;
145
+ const rowPairs = new Int32Array(n * nPairs);
146
+ for (let i = 0; i < n; i++) {
147
+ for (let k = 0; k < nTerms; k++)
148
+ rowGroups[k] = termFirstGroup[k] + codesOf[k][i];
149
+ for (let k = 0; k < nTerms; k++) {
150
+ for (let l = 0; l <= k; l++)
151
+ rowPairs[i * nPairs + (k * (k + 1)) / 2 + l] = addPair(rowGroups[k], rowGroups[l]);
152
+ }
153
+ }
154
+ // sorted by column group, then row group (the diagonal block first)
155
+ const nBlocks = pairRow.length;
156
+ const order = Array.from({ length: nBlocks }, (_, b) => b).sort((a, b) => pairCol[a] - pairCol[b] || pairRow[a] - pairRow[b]);
157
+ const position = new Int32Array(nBlocks);
158
+ order.forEach((b, at) => (position[b] = at));
159
+ const blockStart = new Int32Array(nGroups + 1);
160
+ const blockRow = new Int32Array(nBlocks);
161
+ const blockValueStart = new Int32Array(nBlocks + 1);
162
+ order.forEach((b, at) => {
163
+ blockRow[at] = pairRow[b];
164
+ blockStart[pairCol[b] + 1]++;
165
+ const size = termNc[groupTerm[pairRow[b]]] * termNc[groupTerm[pairCol[b]]];
166
+ blockValueStart[at + 1] = blockValueStart[at] + size;
167
+ });
168
+ for (let h = 0; h < nGroups; h++)
169
+ blockStart[h + 1] += blockStart[h];
170
+ const zz = new Float64Array(blockValueStart[nBlocks]);
171
+ const zx = new Float64Array(q * p);
172
+ const zy = new Float64Array(q);
173
+ const xy = new Float64Array(p);
174
+ for (let i = 0; i < n; i++) {
175
+ const xi = s.x[i];
176
+ const yi = s.y[i];
177
+ for (let k = 0; k < nTerms; k++) {
178
+ const mk = s.terms[k].matrix[i];
179
+ const nck = termNc[k];
180
+ for (let l = 0; l <= k; l++) {
181
+ const ml = s.terms[l].matrix[i];
182
+ const ncl = termNc[l];
183
+ const at = position[rowPairs[i * nPairs + (k * (k + 1)) / 2 + l]];
184
+ const base = blockValueStart[at];
185
+ // block (group of k, group of l): nck × ncl, column-major
186
+ for (let c = 0; c < ncl; c++) {
187
+ const v = ml[c];
188
+ if (v === 0)
189
+ continue;
190
+ for (let r = 0; r < nck; r++)
191
+ zz[base + r + c * nck] += mk[r] * v;
192
+ }
193
+ }
194
+ }
195
+ for (let a = rowStart[i]; a < rowStart[i + 1]; a++) {
196
+ const ja = rowCols[a];
197
+ const va = rowValues[a];
198
+ for (let k = 0; k < p; k++)
199
+ zx[ja + k * q] += va * xi[k];
200
+ zy[ja] += va * yi;
201
+ }
202
+ for (let k = 0; k < p; k++)
203
+ xy[k] += xi[k] * yi;
204
+ }
205
+ // symbolic factorisation on the groups: the pattern of each group below its diagonal block (groups, increasing)
206
+ const groupPattern = new Array(nGroups);
207
+ const children = Array.from({ length: nGroups }, () => []);
208
+ const mark = new Int32Array(nGroups).fill(-1);
209
+ for (let h = 0; h < nGroups; h++) {
210
+ const members = [];
211
+ const add = (r) => {
212
+ if (r !== h && mark[r] !== h) {
213
+ mark[r] = h;
214
+ members.push(r);
215
+ }
216
+ };
217
+ for (let b = blockStart[h] + 1; b < blockStart[h + 1]; b++)
218
+ add(blockRow[b]);
219
+ for (const c of children[h])
220
+ for (const r of groupPattern[c])
221
+ add(r);
222
+ const pattern = Int32Array.from(members).sort();
223
+ groupPattern[h] = pattern;
224
+ if (pattern.length > 0)
225
+ children[pattern[0]].push(h);
226
+ }
227
+ // the position of each off-diagonal block of Z'Z in the pattern of its column group
228
+ const blockPatternOffset = new Int32Array(nBlocks);
229
+ {
230
+ const offsetOf = new Int32Array(nGroups);
231
+ for (let h = 0; h < nGroups; h++) {
232
+ let at = 0;
233
+ for (const r of groupPattern[h]) {
234
+ offsetOf[r] = at;
235
+ at += groupStart[r + 1] - groupStart[r];
236
+ }
237
+ for (let b = blockStart[h] + 1; b < blockStart[h + 1]; b++)
238
+ blockPatternOffset[b] = offsetOf[blockRow[b]];
239
+ }
240
+ }
241
+ // the pattern of L by columns
242
+ const colStart = new Int32Array(q + 1);
243
+ for (let h = 0; h < nGroups; h++) {
244
+ let below = 0;
245
+ for (const r of groupPattern[h])
246
+ below += groupStart[r + 1] - groupStart[r];
247
+ for (let j = groupStart[h]; j < groupStart[h + 1]; j++)
248
+ colStart[j + 1] = colStart[j] + (groupStart[h + 1] - j) + below;
249
+ }
250
+ const colRows = new Int32Array(colStart[q]);
251
+ const rowCounts = new Int32Array(q + 1);
252
+ for (let h = 0; h < nGroups; h++) {
253
+ for (let j = groupStart[h]; j < groupStart[h + 1]; j++) {
254
+ let at = colStart[j];
255
+ for (let r = j; r < groupStart[h + 1]; r++)
256
+ colRows[at++] = r;
257
+ for (const rg of groupPattern[h])
258
+ for (let r = groupStart[rg]; r < groupStart[rg + 1]; r++)
259
+ colRows[at++] = r;
260
+ }
261
+ }
262
+ for (let j = 0; j < q; j++)
263
+ for (let t = colStart[j] + 1; t < colStart[j + 1]; t++)
264
+ rowCounts[colRows[t] + 1]++;
265
+ for (let j = 0; j < q; j++)
266
+ rowCounts[j + 1] += rowCounts[j];
267
+ const rowListStart = rowCounts.slice();
268
+ const fillAt = rowCounts.slice(0, q);
269
+ const rowListCol = new Int32Array(rowListStart[q]);
270
+ const rowListPos = new Int32Array(rowListStart[q]);
271
+ for (let k = 0; k < q; k++) {
272
+ for (let t = colStart[k] + 1; t < colStart[k + 1]; t++) {
273
+ const at = fillAt[colRows[t]]++;
274
+ rowListCol[at] = k;
275
+ rowListPos[at] = t;
276
+ }
277
+ }
278
+ const result = {
279
+ n,
280
+ p,
281
+ q,
282
+ nGroups,
283
+ groupStart,
284
+ groupTerm,
285
+ termNc,
286
+ termTheta,
287
+ blockStart,
288
+ blockRow,
289
+ blockValueStart,
290
+ zz,
291
+ zx,
292
+ zy,
293
+ xy,
294
+ rowStart,
295
+ rowCols,
296
+ rowValues,
297
+ colStart,
298
+ colRows,
299
+ rowListStart,
300
+ rowListCol,
301
+ rowListPos,
302
+ blockPatternOffset,
303
+ };
304
+ systemCache.set(s, result);
305
+ return result;
306
+ }
307
+ /** The blocks T_k at θ (nc × nc, column-major, lower triangular) */
308
+ function blocksOf(sys, theta) {
309
+ return sys.termTheta.map((idx) => Float64Array.from(idx, (t) => (t < 0 ? 0 : theta[t])));
310
+ }
311
+ /** Λ_θ w (q-vector) */
312
+ function lambdaTimes(sys, t, w) {
313
+ const out = new Float64Array(sys.q);
314
+ for (let g = 0; g < sys.nGroups; g++) {
315
+ const k = sys.groupTerm[g];
316
+ const nc = sys.termNc[k];
317
+ const tk = t[k];
318
+ const base = sys.groupStart[g];
319
+ for (let c = 0; c < nc; c++) {
320
+ const wc = w[base + c];
321
+ if (wc === 0)
322
+ continue;
323
+ for (let r = c; r < nc; r++)
324
+ out[base + r] += tk[r + c * nc] * wc;
325
+ }
326
+ }
327
+ return out;
328
+ }
329
+ /** Λ_θ' M for a q × ncol column-major M */
330
+ function lambdaTransposeTimes(sys, t, m, ncol = 1) {
331
+ const q = sys.q;
332
+ const out = new Float64Array(q * ncol);
333
+ for (let g = 0; g < sys.nGroups; g++) {
334
+ const k = sys.groupTerm[g];
335
+ const nc = sys.termNc[k];
336
+ const tk = t[k];
337
+ const base = sys.groupStart[g];
338
+ for (let col = 0; col < ncol; col++) {
339
+ const off = base + col * q;
340
+ for (let c = 0; c < nc; c++) {
341
+ let sum = 0;
342
+ for (let r = c; r < nc; r++)
343
+ sum += tk[r + c * nc] * m[off + r];
344
+ out[off + c] = sum;
345
+ }
346
+ }
347
+ }
348
+ return out;
349
+ }
350
+ /** The blocks of A = Λ_θ' Z'Z Λ_θ + I (the layout of Z'Z), each T_g' Z'Z(g, h) T_h, the identity added on the diagonal */
351
+ function blocksOfA(sys, t) {
352
+ const a = new Float64Array(sys.zz.length);
353
+ const tmp = new Float64Array(64);
354
+ for (let h = 0; h < sys.nGroups; h++) {
355
+ const kc = sys.groupTerm[h];
356
+ const ncc = sys.termNc[kc];
357
+ const tc = t[kc];
358
+ for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
359
+ const kr = sys.groupTerm[sys.blockRow[b]];
360
+ const ncr = sys.termNc[kr];
361
+ const tr = t[kr];
362
+ const base = sys.blockValueStart[b];
363
+ if (ncr === 1 && ncc === 1) {
364
+ a[base] = tr[0] * sys.zz[base] * tc[0];
365
+ }
366
+ else {
367
+ // tmp = Z'Z(g, h) T_h (ncr × ncc), then T_g' tmp
368
+ const work = tmp.length >= ncr * ncc ? tmp : new Float64Array(ncr * ncc);
369
+ for (let c = 0; c < ncc; c++) {
370
+ for (let r = 0; r < ncr; r++) {
371
+ let sum = 0;
372
+ for (let m = c; m < ncc; m++)
373
+ sum += sys.zz[base + r + m * ncr] * tc[m + c * ncc];
374
+ work[r + c * ncr] = sum;
375
+ }
376
+ }
377
+ for (let c = 0; c < ncc; c++) {
378
+ for (let r = 0; r < ncr; r++) {
379
+ let sum = 0;
380
+ for (let m = r; m < ncr; m++)
381
+ sum += tr[m + r * ncr] * work[m + c * ncr];
382
+ a[base + r + c * ncr] = sum;
383
+ }
384
+ }
385
+ }
386
+ if (b === sys.blockStart[h])
387
+ for (let c = 0; c < ncc; c++)
388
+ a[base + c + c * ncc] += 1;
389
+ }
390
+ }
391
+ return a;
392
+ }
393
+ /** The values of the Cholesky factor L of A (A = L L', the pattern of the system), from the blocks of A */
394
+ function factorise(sys, a) {
395
+ const { q, colStart, colRows, rowListStart, rowListCol, rowListPos } = sys;
396
+ const l = new Float64Array(colRows.length);
397
+ const work = new Float64Array(q);
398
+ for (let h = 0; h < sys.nGroups; h++) {
399
+ const ncc = sys.termNc[sys.groupTerm[h]];
400
+ const first = sys.groupStart[h];
401
+ for (let c = 0; c < ncc; c++) {
402
+ const j = first + c;
403
+ // column j of A, on and below the diagonal
404
+ for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
405
+ const g = sys.blockRow[b];
406
+ const ncr = sys.termNc[sys.groupTerm[g]];
407
+ const base = sys.blockValueStart[b] + c * ncr;
408
+ const r0 = sys.groupStart[g];
409
+ for (let r = g === h ? c : 0; r < ncr; r++)
410
+ work[r0 + r] = a[base + r];
411
+ }
412
+ // minus the columns k < j with L[j, k] ≠ 0
413
+ for (let e = rowListStart[j]; e < rowListStart[j + 1]; e++) {
414
+ const k = rowListCol[e];
415
+ const pos = rowListPos[e];
416
+ const ljk = l[pos];
417
+ if (ljk === 0)
418
+ continue;
419
+ const end = colStart[k + 1];
420
+ for (let t = pos; t < end; t++)
421
+ work[colRows[t]] -= l[t] * ljk;
422
+ }
423
+ const d = work[j];
424
+ if (!(d > 0))
425
+ throw new Error("the penalised least-squares matrix is not positive definite");
426
+ const ljj = Math.sqrt(d);
427
+ const start = colStart[j];
428
+ l[start] = ljj;
429
+ work[j] = 0;
430
+ for (let t = start + 1; t < colStart[j + 1]; t++) {
431
+ const r = colRows[t];
432
+ l[t] = work[r] / ljj;
433
+ work[r] = 0;
434
+ }
435
+ }
436
+ }
437
+ return l;
438
+ }
439
+ /** Solves L x = v in place (v of length q, at an offset) */
440
+ function solveL(sys, l, v, offset = 0) {
441
+ const { q, colStart, colRows } = sys;
442
+ for (let j = 0; j < q; j++) {
443
+ const start = colStart[j];
444
+ const xj = (v[offset + j] /= l[start]);
445
+ if (xj === 0)
446
+ continue;
447
+ for (let t = start + 1; t < colStart[j + 1]; t++)
448
+ v[offset + colRows[t]] -= l[t] * xj;
449
+ }
450
+ }
451
+ /** Solves L' x = v in place */
452
+ function solveLt(sys, l, v, offset = 0) {
453
+ const { q, colStart, colRows } = sys;
454
+ for (let j = q - 1; j >= 0; j--) {
455
+ const start = colStart[j];
456
+ let sum = v[offset + j];
457
+ for (let t = start + 1; t < colStart[j + 1]; t++)
458
+ sum -= l[t] * v[offset + colRows[t]];
459
+ v[offset + j] = sum / l[start];
460
+ }
461
+ }
462
+ /** Solves L x = v in place, with L = R' and R the upper-triangular factor (column-major, k × k) */
463
+ function forwardSolve(r, k, v) {
464
+ for (let i = 0; i < k; i++) {
465
+ const ci = i * k;
466
+ let sum = v[i];
467
+ for (let j = 0; j < i; j++)
468
+ sum -= r[j + ci] * v[j];
469
+ v[i] = sum / r[i + ci];
470
+ }
471
+ }
472
+ /** Solves R x = v in place, R upper triangular (column-major, k × k) */
473
+ function backSolve(r, k, v) {
474
+ for (let i = k - 1; i >= 0; i--) {
475
+ const xi = (v[i] /= r[i + i * k]);
476
+ const ci = i * k;
477
+ for (let j = 0; j < i; j++)
478
+ v[j] -= r[j + ci] * xi;
479
+ }
480
+ }
481
+ /** The full symmetric inverse of R'R from an upper-triangular factor R (column-major, k × k; R is not changed) */
482
+ function inverseFromFactor(r, k) {
483
+ const inv = r.slice();
484
+ for (let j = 0; j < k; j++)
485
+ for (let i = j + 1; i < k; i++)
486
+ inv[i + j * k] = 0;
487
+ potri({ nrow: k, ncol: k, data: inv });
488
+ for (let j = 0; j < k; j++)
489
+ for (let i = j + 1; i < k; i++)
490
+ inv[i + j * k] = inv[j + i * k];
491
+ return inv;
492
+ }
493
+ /**
494
+ * The profiled deviance of a linear mixed model at `theta`, with the penalised least-squares solution
495
+ * (oracle/lmer-behaviour.md, stage 1b; computed sparsely). Internal: not exported from the package.
496
+ *
497
+ * @param structure The structure from {@link mixedModelStructure}.
498
+ * @param theta The covariance parameters (finite, of the length of `structure.theta`; values below the lower bounds
499
+ * are accepted).
500
+ * @param reml Whether to return the REML criterion (true) or the ML deviance (false).
501
+ * @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
502
+ */
503
+ export function profiledDeviance(structure, theta, reml, options = {}) {
504
+ if (theta.length !== structure.theta.length) {
505
+ throw new RangeError(`theta must have length ${structure.theta.length}, not ${theta.length}`);
506
+ }
507
+ if (theta.some((t) => !Number.isFinite(t)))
508
+ throw new RangeError("theta must be finite");
509
+ const sys = sparseSystemOf(structure);
510
+ const { n, p, q } = sys;
511
+ const t = blocksOf(sys, theta);
512
+ const l = factorise(sys, blocksOfA(sys, t));
513
+ // Z v (from the sparse Z) and Λ'Z' v
514
+ const zTimes = (v) => {
515
+ const out = new Float64Array(n);
516
+ for (let i = 0; i < n; i++) {
517
+ let sum = 0;
518
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
519
+ sum += sys.rowValues[c] * v[sys.rowCols[c]];
520
+ out[i] = sum;
521
+ }
522
+ return out;
523
+ };
524
+ const zTransposeTimes = (v) => {
525
+ const zv = new Float64Array(q);
526
+ for (let i = 0; i < n; i++) {
527
+ const vi = v[i];
528
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
529
+ zv[sys.rowCols[c]] += sys.rowValues[c] * vi;
530
+ }
531
+ return zv;
532
+ };
533
+ /** Solves A w = v in place */
534
+ const solveA = (v) => {
535
+ solveL(sys, l, v);
536
+ solveLt(sys, l, v);
537
+ };
538
+ // C_X = L⁻¹ Λ' Z'X
539
+ const cx = lambdaTransposeTimes(sys, t, sys.zx, p);
540
+ for (let k = 0; k < p; k++)
541
+ solveL(sys, l, cx, k * q);
542
+ // R_X' R_X = X'X − C_X' C_X, computed without the cancellation of that difference: with W = A⁻¹ Λ'Z'X (= L'⁻¹ C_X)
543
+ // and the residual E = X − ZΛW, it is E'E + W'W (as Λ'Z'E = W). W is refined once with E computed from the data.
544
+ const xResiduals = [];
545
+ const ws = [];
546
+ for (let k = 0; k < p; k++) {
547
+ const w = cx.slice(k * q, (k + 1) * q);
548
+ solveLt(sys, l, w);
549
+ const xk = Float64Array.from(structure.x, (row) => row[k]);
550
+ const residualOf = () => {
551
+ const fitted = zTimes(lambdaTimes(sys, t, w));
552
+ return xk.map((v, i) => v - fitted[i]);
553
+ };
554
+ let e = residualOf();
555
+ for (let step = 0; step < REFINEMENT_STEPS; step++) {
556
+ const g = lambdaTransposeTimes(sys, t, zTransposeTimes(e));
557
+ for (let i = 0; i < q; i++)
558
+ g[i] -= w[i];
559
+ solveA(g);
560
+ for (let i = 0; i < q; i++)
561
+ w[i] += g[i];
562
+ e = residualOf();
563
+ }
564
+ xResiduals.push(e);
565
+ ws.push(w);
566
+ }
567
+ const rx = new Float64Array(p * p);
568
+ for (let k = 0; k < p; k++) {
569
+ for (let m = k; m < p; m++) {
570
+ let sum = 0;
571
+ const ek = xResiduals[k];
572
+ const em = xResiduals[m];
573
+ for (let i = 0; i < n; i++)
574
+ sum += ek[i] * em[i];
575
+ const wk = ws[k];
576
+ const wm = ws[m];
577
+ for (let i = 0; i < q; i++)
578
+ sum += wk[i] * wm[i];
579
+ rx[k + m * p] = sum;
580
+ rx[m + k * p] = sum;
581
+ }
582
+ }
583
+ const factorRX = { nrow: p, ncol: p, data: rx };
584
+ if (p > 0 && potf2(factorRX) > 0)
585
+ throw new Error("the fixed-effects matrix of the penalised least squares is not positive definite");
586
+ // The normal equations of the penalised least squares, [A, Λ'Z'X; X'ZΛ, X'X] (u, β) = (gu, gβ), solved with the
587
+ // two factors: c = L⁻¹ gu, R_X' R_X β = gβ − C_X' c, L' u = c − C_X β. Overwrites gu with u and gβ with β.
588
+ const solveNormal = (gu, gb) => {
589
+ solveL(sys, l, gu);
590
+ for (let k = 0; k < p; k++) {
591
+ let sum = gb[k];
592
+ for (let i = 0; i < q; i++)
593
+ sum -= cx[i + k * q] * gu[i];
594
+ gb[k] = sum;
595
+ }
596
+ forwardSolve(rx, p, gb);
597
+ backSolve(rx, p, gb);
598
+ for (let k = 0; k < p; k++) {
599
+ const bk = gb[k];
600
+ for (let i = 0; i < q; i++)
601
+ gu[i] -= cx[i + k * q] * bk;
602
+ }
603
+ solveLt(sys, l, gu);
604
+ };
605
+ // the residual y − Xβ − ZΛu, from X and the sparse Z (not from the cross-products)
606
+ const residual = (beta, bv) => {
607
+ const zb = zTimes(bv);
608
+ const res = new Float64Array(n);
609
+ for (let i = 0; i < n; i++) {
610
+ const xi = structure.x[i];
611
+ let fitted = zb[i];
612
+ for (let k = 0; k < p; k++)
613
+ fitted += xi[k] * beta[k];
614
+ res[i] = structure.y[i] - fitted;
615
+ }
616
+ return res;
617
+ };
618
+ // the solution from the cross-products, then refined with the residual computed from the data (the corrected
619
+ // semi-normal equations): the normal equations squared the condition number, the refinement recovers the accuracy
620
+ // of an orthogonal decomposition
621
+ const uv = lambdaTransposeTimes(sys, t, sys.zy);
622
+ const betav = Float64Array.from(sys.xy);
623
+ solveNormal(uv, betav);
624
+ let bv = lambdaTimes(sys, t, uv);
625
+ let res = residual(betav, bv);
626
+ for (let step = 0; step < REFINEMENT_STEPS; step++) {
627
+ // the gradient of the penalised residual sum of squares: (Λ'Z'res − u, X'res)
628
+ const du = lambdaTransposeTimes(sys, t, zTransposeTimes(res));
629
+ for (let i = 0; i < q; i++)
630
+ du[i] -= uv[i];
631
+ const db = new Float64Array(p);
632
+ for (let i = 0; i < n; i++) {
633
+ const xi = structure.x[i];
634
+ const ri = res[i];
635
+ for (let k = 0; k < p; k++)
636
+ db[k] += xi[k] * ri;
637
+ }
638
+ solveNormal(du, db);
639
+ for (let i = 0; i < q; i++)
640
+ uv[i] += du[i];
641
+ for (let k = 0; k < p; k++)
642
+ betav[k] += db[k];
643
+ bv = lambdaTimes(sys, t, uv);
644
+ res = residual(betav, bv);
645
+ }
646
+ const beta = Array.from(betav);
647
+ const u = Array.from(uv);
648
+ const b = Array.from(bv);
649
+ let rss = 0;
650
+ for (const e of res)
651
+ rss += e * e;
652
+ let ussq = 0;
653
+ for (const v of u)
654
+ ussq += v * v;
655
+ const prss = rss + ussq;
656
+ let logDetL = 0;
657
+ for (let j = 0; j < q; j++)
658
+ logDetL += Math.log(l[sys.colStart[j]]);
659
+ logDetL *= 2;
660
+ let logDetRX = 0;
661
+ for (let k = 0; k < p; k++)
662
+ logDetRX += Math.log(rx[k + k * p]);
663
+ logDetRX *= 2;
664
+ const df = reml ? n - p : n;
665
+ const deviance = (reml ? logDetL + logDetRX : logDetL) + df * (1 + Math.log((2 * Math.PI * prss) / df));
666
+ const out = { deviance, beta, u, b, rss, ussq, prss, logDetL, logDetRX };
667
+ const sInverse = options.gradient === true || options.rxInverse === true ? inverseFromFactor(rx, p) : undefined;
668
+ if (options.rxInverse === true) {
669
+ out.rxInverse = Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => sInverse[i + j * p]));
670
+ }
671
+ if (options.gradient === true) {
672
+ out.gradient = sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse: sInverse });
673
+ }
674
+ return out;
675
+ }
676
+ /**
677
+ * The selected inverse of A = L L': the entries of A⁻¹ on the pattern of L (lower part, the layout of L's values), by
678
+ * the recurrences of Takahashi, Fagan and Chin (1973). Since L' A⁻¹ = L⁻¹ is lower triangular with diagonal 1 / L_jj,
679
+ * row j of it gives, for i > j in the pattern of column j,
680
+ * A⁻¹[i, j] = −(1 / L_jj) Σ_k L[k, j] A⁻¹[k, i], A⁻¹[j, j] = 1 / L_jj² − (1 / L_jj) Σ_k L[k, j] A⁻¹[k, j],
681
+ * the sums over the rows k > j of column j. The rows of column j form a clique in the pattern of L (the closure of a
682
+ * Cholesky pattern), so every A⁻¹[k, i] needed is on the pattern, in column min(k, i), already computed when the
683
+ * columns are taken from the last to the first. The cost is that of the factorisation.
684
+ */
685
+ function selectedInverse(sys, l) {
686
+ const { q, colStart, colRows } = sys;
687
+ const inv = new Float64Array(l.length);
688
+ const inColumn = new Int32Array(q).fill(-1);
689
+ const lj = new Float64Array(q);
690
+ const acc = new Float64Array(q);
691
+ for (let j = q - 1; j >= 0; j--) {
692
+ const start = colStart[j];
693
+ const end = colStart[j + 1];
694
+ for (let t = start + 1; t < end; t++) {
695
+ const r = colRows[t];
696
+ inColumn[r] = j;
697
+ lj[r] = l[t];
698
+ acc[r] = 0;
699
+ }
700
+ // acc[i] = Σ_k L[k, j] A⁻¹[k, i] for the rows i of column j: column k of the selected inverse holds A⁻¹[r, k],
701
+ // r ≥ k, which counts once for A⁻¹[k, r] (i = r) and once for A⁻¹[r, k] (i = k)
702
+ for (let t = start + 1; t < end; t++) {
703
+ const k = colRows[t];
704
+ const lkj = l[t];
705
+ const kStart = colStart[k];
706
+ let sum = inv[kStart] * lkj;
707
+ for (let e = kStart + 1; e < colStart[k + 1]; e++) {
708
+ const r = colRows[e];
709
+ if (inColumn[r] !== j)
710
+ continue;
711
+ const v = inv[e];
712
+ acc[r] += v * lkj;
713
+ sum += v * lj[r];
714
+ }
715
+ acc[k] += sum;
716
+ }
717
+ const d = l[start];
718
+ let diagonal = 1 / d;
719
+ for (let t = start + 1; t < end; t++) {
720
+ const v = -acc[colRows[t]] / d;
721
+ inv[t] = v;
722
+ diagonal -= l[t] * v;
723
+ }
724
+ inv[start] = diagonal / d;
725
+ }
726
+ return inv;
727
+ }
728
+ /**
729
+ * The gradient of the criterion with respect to θ (see the header), sparse. The log-determinant term
730
+ * 2 Σ_(r,c) (A⁻¹ K)[c, r] (K = Λ'Z'Z) involves, for the entries (r, c) of Λ_θ in group G,
731
+ * (A⁻¹ K)[c, r] = Σ_H (A⁻¹(G, H) T_H' Z'Z(H, G))[c, r]
732
+ * over the groups H that share rows with G: the blocks of A⁻¹ on the pattern of A, hence of L, given by the selected
733
+ * inverse. These nc × nc products are summed over the levels of each term, as the same element of θ sits at the same
734
+ * place of T_k in every level. The other terms need Z'res (q), W S⁻¹ (q × p) and E'Z (p × q).
735
+ */
736
+ function sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse }) {
737
+ const { n, p, q, colStart, zz } = sys;
738
+ const inv = selectedInverse(sys, l);
739
+ // S_k = Σ over the levels G of term k of (A⁻¹ K) on G's columns (nc_k × nc_k, column-major)
740
+ const sums = sys.termNc.map((nc) => new Float64Array(nc * nc));
741
+ let y = new Float64Array(16);
742
+ let f = new Float64Array(16);
743
+ for (let h = 0; h < sys.nGroups; h++) {
744
+ const kh = sys.groupTerm[h];
745
+ const nch = sys.termNc[kh];
746
+ const th = t[kh];
747
+ const c0 = sys.groupStart[h];
748
+ for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
749
+ const g = sys.blockRow[b];
750
+ const kg = sys.groupTerm[g];
751
+ const ncg = sys.termNc[kg];
752
+ const tg = t[kg];
753
+ const base = sys.blockValueStart[b];
754
+ if (nch === 1 && ncg === 1) {
755
+ // Y = A⁻¹(g, h), B = Z'Z(g, h): Y T_g B to S_h and, off the diagonal, Y T_h B to S_g
756
+ const at = g === h ? colStart[c0] : colStart[c0] + 1 + sys.blockPatternOffset[b];
757
+ const yb = inv[at] * zz[base];
758
+ sums[kh][0] += yb * tg[0];
759
+ if (g !== h)
760
+ sums[kg][0] += yb * th[0];
761
+ continue;
762
+ }
763
+ const size = ncg * nch;
764
+ if (y.length < size) {
765
+ y = new Float64Array(size);
766
+ f = new Float64Array(Math.max(size, ncg * ncg, nch * nch));
767
+ }
768
+ // Y = A⁻¹(g, h) (ncg × nch), from the selected inverse (the diagonal block from its lower triangle)
769
+ for (let cc = 0; cc < nch; cc++) {
770
+ const col = colStart[c0 + cc];
771
+ if (g === h) {
772
+ for (let rr = cc; rr < ncg; rr++) {
773
+ const v = inv[col + rr - cc];
774
+ y[rr + cc * ncg] = v;
775
+ y[cc + rr * ncg] = v;
776
+ }
777
+ }
778
+ else {
779
+ const at = col + (nch - cc) + sys.blockPatternOffset[b];
780
+ for (let rr = 0; rr < ncg; rr++)
781
+ y[rr + cc * ncg] = inv[at + rr];
782
+ }
783
+ }
784
+ // S_h += Y' T_g' B: F = T_g' B (ncg × nch), then Y' F
785
+ for (let cc = 0; cc < nch; cc++) {
786
+ for (let a = 0; a < ncg; a++) {
787
+ let sum = 0;
788
+ for (let m = a; m < ncg; m++)
789
+ sum += tg[m + a * ncg] * zz[base + m + cc * ncg];
790
+ f[a + cc * ncg] = sum;
791
+ }
792
+ }
793
+ const sh = sums[kh];
794
+ for (let x = 0; x < nch; x++) {
795
+ for (let z = 0; z < nch; z++) {
796
+ let sum = 0;
797
+ for (let a = 0; a < ncg; a++)
798
+ sum += y[a + x * ncg] * f[a + z * ncg];
799
+ sh[x + z * nch] += sum;
800
+ }
801
+ }
802
+ if (g === h)
803
+ continue;
804
+ // S_g += Y T_h' B': F = T_h' B' (nch × ncg), then Y F
805
+ for (let rr = 0; rr < ncg; rr++) {
806
+ for (let a = 0; a < nch; a++) {
807
+ let sum = 0;
808
+ for (let m = a; m < nch; m++)
809
+ sum += th[m + a * nch] * zz[base + rr + m * ncg];
810
+ f[a + rr * nch] = sum;
811
+ }
812
+ }
813
+ const sg = sums[kg];
814
+ for (let x = 0; x < ncg; x++) {
815
+ for (let z = 0; z < ncg; z++) {
816
+ let sum = 0;
817
+ for (let a = 0; a < nch; a++)
818
+ sum += y[x + a * ncg] * f[a + z * nch];
819
+ sg[x + z * ncg] += sum;
820
+ }
821
+ }
822
+ }
823
+ }
824
+ const gradient = new Array(theta.length).fill(0);
825
+ sys.termTheta.forEach((idx, k) => {
826
+ const nc = sys.termNc[k];
827
+ for (let cl = 0; cl < nc; cl++) {
828
+ for (let rl = cl; rl < nc; rl++)
829
+ gradient[idx[rl + cl * nc]] += 2 * sums[k][cl + rl * nc];
830
+ }
831
+ });
832
+ // Z' res
833
+ const zRes = new Float64Array(q);
834
+ for (let i = 0; i < n; i++) {
835
+ const ri = res[i];
836
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
837
+ zRes[sys.rowCols[c]] += sys.rowValues[c] * ri;
838
+ }
839
+ // REML: V = W S⁻¹ (q × p) and E'Z (p × q), both column-major
840
+ let v;
841
+ let ez;
842
+ if (reml && p > 0) {
843
+ v = new Float64Array(q * p);
844
+ for (let m = 0; m < p; m++) {
845
+ for (let k = 0; k < p; k++) {
846
+ const skm = sInverse[k + m * p];
847
+ const wk = ws[k];
848
+ for (let c = 0; c < q; c++)
849
+ v[c + m * q] += wk[c] * skm;
850
+ }
851
+ }
852
+ ez = new Float64Array(p * q);
853
+ for (let i = 0; i < n; i++) {
854
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++) {
855
+ const zr = sys.rowCols[c];
856
+ const val = sys.rowValues[c];
857
+ for (let m = 0; m < p; m++)
858
+ ez[m + zr * p] += xResiduals[m][i] * val;
859
+ }
860
+ }
861
+ }
862
+ const df = reml ? n - p : n;
863
+ const prssFactor = (2 * df) / prss;
864
+ for (const { row: rr, col: c, theta: ti } of structure.lambda) {
865
+ let tr = 0;
866
+ if (v !== undefined && ez !== undefined)
867
+ for (let m = 0; m < p; m++)
868
+ tr += v[c + m * q] * ez[m + rr * p];
869
+ gradient[ti] -= 2 * tr + prssFactor * zRes[rr] * uv[c];
870
+ }
871
+ return gradient;
872
+ }