@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
@@ -31,6 +31,63 @@ export interface ProfiledDevianceOptions {
31
31
  /** Also (R_X' R_X)⁻¹. */
32
32
  rxInverse?: boolean;
33
33
  }
34
+ /** What does not depend on θ: the cross-products, Z by rows, the groups of columns and the pattern of the factor */
35
+ export interface SparseSystem {
36
+ n: number;
37
+ p: number;
38
+ q: number;
39
+ /** Number of groups of columns (one per level of each term) */
40
+ nGroups: number;
41
+ /** First column of each group, and q at the end (nGroups + 1) */
42
+ groupStart: Int32Array;
43
+ /** The term of each group */
44
+ groupTerm: Int32Array;
45
+ /** For each term: nc, and the index into θ of each element of T_k (nc × nc, column-major; −1 above the diagonal) */
46
+ termNc: number[];
47
+ termTheta: Int32Array[];
48
+ /**
49
+ * Z'Z by blocks, lower part: the blocks of column group h are blockStart[h] .. blockStart[h + 1] − 1, the diagonal
50
+ * block first, then the row groups blockRow[b] > h increasing; block b is nc(row group) × nc(h), column-major, at
51
+ * zz[blockValueStart[b]] (the diagonal block in full)
52
+ */
53
+ blockStart: Int32Array;
54
+ blockRow: Int32Array;
55
+ blockValueStart: Int32Array;
56
+ zz: Float64Array;
57
+ /** Z'X, q × p, column-major */
58
+ zx: Float64Array;
59
+ /** Z'y */
60
+ zy: Float64Array;
61
+ /** X'y */
62
+ xy: Float64Array;
63
+ /** The nonzero entries of Z by rows: the columns and the values of row i are at rowStart[i] .. rowStart[i + 1] − 1 */
64
+ rowStart: Int32Array;
65
+ rowCols: Int32Array;
66
+ rowValues: Float64Array;
67
+ /** The pattern of L by columns: the rows of column j at colStart[j] .. colStart[j + 1] − 1, the diagonal first */
68
+ colStart: Int32Array;
69
+ colRows: Int32Array;
70
+ /** The entries L[j, k], k < j, of row j: their columns k (increasing) and positions in colRows, at rowListStart[j] .. */
71
+ rowListStart: Int32Array;
72
+ rowListCol: Int32Array;
73
+ rowListPos: Int32Array;
74
+ /**
75
+ * For each block b of Z'Z off the diagonal (row group g, column group h): the number of rows of L's column groups
76
+ * before g in the pattern of h, so that the entry (row r of g, column c of h) of L (and of the selected inverse) is
77
+ * at colStart[column] + (rows of the diagonal block from the column) + blockPatternOffset[b] + r (0 on the diagonal)
78
+ */
79
+ blockPatternOffset: Int32Array;
80
+ }
81
+ /** Λ_θ w (q-vector) */
82
+ export declare function lambdaTimes(sys: SparseSystem, t: Float64Array[], w: Float64Array): Float64Array;
83
+ /** Λ_θ' M for a q × ncol column-major M */
84
+ export declare function lambdaTransposeTimes(sys: SparseSystem, t: Float64Array[], m: Float64Array, ncol?: number): Float64Array;
85
+ /** Solves L x = v in place (v of length q, at an offset) */
86
+ export declare function solveL(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
87
+ /** Solves L' x = v in place */
88
+ export declare function solveLt(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
89
+ /** The full symmetric inverse of R'R from an upper-triangular factor R (column-major, k × k; R is not changed) */
90
+ export declare function inverseFromFactor(r: Float64Array, k: number): Float64Array;
34
91
  /**
35
92
  * The profiled deviance of a linear mixed model at `theta`, with the penalised least-squares solution
36
93
  * (oracle/lmer-behaviour.md, stage 1b; computed sparsely). Internal: not exported from the package.
@@ -42,3 +99,58 @@ export interface ProfiledDevianceOptions {
42
99
  * @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
43
100
  */
44
101
  export declare function profiledDeviance(structure: MixedModelStructure, theta: readonly number[], reml: boolean, options?: ProfiledDevianceOptions): ProfiledDeviance;
102
+ /**
103
+ * The state of the penalised least-squares solution at a given θ (internal): the system of the structure, the blocks
104
+ * T_k, the sparse factor L of A, C_X = L⁻¹ Λ'Z'X, the Cholesky factor R_X (upper triangle, column-major, p × p) of
105
+ * R_X'R_X = E'E + W'W, the columns of W = A⁻¹ Λ'Z'X and of E = X − ZΛW, the residual y − Xβ̂ − ZΛû, û, β̂, b = Λû,
106
+ * and the solver of the normal equations of the penalised least squares. {@link profiledDeviance} is computed from
107
+ * it, and src/models/mixedDerivatives.ts takes the second derivatives from it.
108
+ */
109
+ export interface PlsState {
110
+ sys: SparseSystem;
111
+ t: Float64Array[];
112
+ l: Float64Array;
113
+ cx: Float64Array;
114
+ rx: Float64Array;
115
+ ws: Float64Array[];
116
+ xResiduals: Float64Array[];
117
+ res: Float64Array;
118
+ uv: Float64Array;
119
+ beta: Float64Array;
120
+ b: Float64Array;
121
+ /** Solves [A, Λ'Z'X; X'ZΛ, X'X] (u, β) = (gu, gβ) with the two factors, overwriting gu with u and gβ with β */
122
+ solveNormal: (gu: Float64Array, gb: Float64Array) => void;
123
+ }
124
+ /** The penalised least-squares solution at θ and the factors it was computed with (see {@link PlsState}) */
125
+ export declare function plsState(structure: MixedModelStructure, theta: readonly number[]): PlsState;
126
+ /**
127
+ * 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
128
+ * the recurrences of Takahashi, Fagan and Chin (1973). Since L' A⁻¹ = L⁻¹ is lower triangular with diagonal 1 / L_jj,
129
+ * row j of it gives, for i > j in the pattern of column j,
130
+ * 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],
131
+ * 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
132
+ * Cholesky pattern), so every A⁻¹[k, i] needed is on the pattern, in column min(k, i), already computed when the
133
+ * columns are taken from the last to the first. The cost is that of the factorisation.
134
+ */
135
+ export declare function selectedInverse(sys: SparseSystem, l: Float64Array): Float64Array;
136
+ /**
137
+ * The derivative ∂L of the Cholesky factor L of A along a direction in which A changes by ∂A (`da`, the layout of the
138
+ * blocks of A, both triangles of the diagonal blocks): {@link factorise} differentiated step by step (forward mode).
139
+ * In column j, after the columns k < j are subtracted, the work vector holds L_jj L[r, j] (L_jj² at r = j), so with
140
+ * ∂ of the same subtractions (∂L[r, k] L[j, k] + L[r, k] ∂L[j, k]),
141
+ * ∂L_jj = ∂work[j] / (2 L_jj), ∂L[r, j] = (∂work[r] − L[r, j] ∂L_jj) / L_jj.
142
+ * An entry L[j, k] that is 0 (a column of Λ_θ that is 0) is not skipped: its derivative need not be 0.
143
+ */
144
+ export declare function factoriseSystemTangent(sys: SparseSystem, l: Float64Array, da: Float64Array): Float64Array;
145
+ /**
146
+ * The derivative of the selected inverse `inv` of A = L L' given the derivative ∂L of L (`dl`): the recurrences of
147
+ * {@link selectedInverse} differentiated step by step (forward mode). It is ∂(A⁻¹) = −A⁻¹ ∂A A⁻¹ on the pattern of L.
148
+ */
149
+ export declare function selectedInverseTangent(sys: SparseSystem, l: Float64Array, dl: Float64Array, inv: Float64Array): Float64Array;
150
+ /**
151
+ * S_k = Σ over the levels G of term k of (Y Λ' Z'Z) on G's columns (nc_k × nc_k, column-major), for Y = A⁻¹ given by
152
+ * its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
153
+ * in `inv` and in `t`, so that the derivatives of the sums (src/models/mixedDerivatives.ts) come from the derivative
154
+ * of the selected inverse and of the blocks.
155
+ */
156
+ export declare function levelTraceSums(sys: SparseSystem, inv: Float64Array, t: Float64Array[]): Float64Array[];
@@ -52,6 +52,10 @@
52
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
53
  // Takahashi's recurrences; K by blocks of Z'Z, never formed), so the gradient costs about one more factorisation, and
54
54
  // memory of the order of the nonzeros of L, Z and Z'X.
55
+ //
56
+ // The second derivatives that lmerTest's tests need (src/models/mixedDerivatives.ts) are computed from the same state
57
+ // (plsState): the selected inverse, the sums of levelTraceSums, and the derivatives of the factor and of the selected
58
+ // inverse along an element of θ (factoriseSystemTangent, selectedInverseTangent).
55
59
  import { potf2, potri } from "../linalg/chol.js";
56
60
  /** Steps of iterative refinement of the penalised least-squares solution */
57
61
  const REFINEMENT_STEPS = 1;
@@ -309,7 +313,7 @@ function blocksOf(sys, theta) {
309
313
  return sys.termTheta.map((idx) => Float64Array.from(idx, (t) => (t < 0 ? 0 : theta[t])));
310
314
  }
311
315
  /** Λ_θ w (q-vector) */
312
- function lambdaTimes(sys, t, w) {
316
+ export function lambdaTimes(sys, t, w) {
313
317
  const out = new Float64Array(sys.q);
314
318
  for (let g = 0; g < sys.nGroups; g++) {
315
319
  const k = sys.groupTerm[g];
@@ -327,7 +331,7 @@ function lambdaTimes(sys, t, w) {
327
331
  return out;
328
332
  }
329
333
  /** Λ_θ' M for a q × ncol column-major M */
330
- function lambdaTransposeTimes(sys, t, m, ncol = 1) {
334
+ export function lambdaTransposeTimes(sys, t, m, ncol = 1) {
331
335
  const q = sys.q;
332
336
  const out = new Float64Array(q * ncol);
333
337
  for (let g = 0; g < sys.nGroups; g++) {
@@ -437,7 +441,7 @@ function factorise(sys, a) {
437
441
  return l;
438
442
  }
439
443
  /** Solves L x = v in place (v of length q, at an offset) */
440
- function solveL(sys, l, v, offset = 0) {
444
+ export function solveL(sys, l, v, offset = 0) {
441
445
  const { q, colStart, colRows } = sys;
442
446
  for (let j = 0; j < q; j++) {
443
447
  const start = colStart[j];
@@ -449,7 +453,7 @@ function solveL(sys, l, v, offset = 0) {
449
453
  }
450
454
  }
451
455
  /** Solves L' x = v in place */
452
- function solveLt(sys, l, v, offset = 0) {
456
+ export function solveLt(sys, l, v, offset = 0) {
453
457
  const { q, colStart, colRows } = sys;
454
458
  for (let j = q - 1; j >= 0; j--) {
455
459
  const start = colStart[j];
@@ -479,7 +483,7 @@ function backSolve(r, k, v) {
479
483
  }
480
484
  }
481
485
  /** 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) {
486
+ export function inverseFromFactor(r, k) {
483
487
  const inv = r.slice();
484
488
  for (let j = 0; j < k; j++)
485
489
  for (let i = j + 1; i < k; i++)
@@ -501,6 +505,41 @@ function inverseFromFactor(r, k) {
501
505
  * @param options What to compute besides: the gradient with respect to θ, (R_X' R_X)⁻¹.
502
506
  */
503
507
  export function profiledDeviance(structure, theta, reml, options = {}) {
508
+ const state = plsState(structure, theta);
509
+ const { sys, t, l, rx, ws, xResiduals, res, uv } = state;
510
+ const { n, p, q } = sys;
511
+ const beta = Array.from(state.beta);
512
+ const u = Array.from(uv);
513
+ const b = Array.from(state.b);
514
+ let rss = 0;
515
+ for (const e of res)
516
+ rss += e * e;
517
+ let ussq = 0;
518
+ for (const v of u)
519
+ ussq += v * v;
520
+ const prss = rss + ussq;
521
+ let logDetL = 0;
522
+ for (let j = 0; j < q; j++)
523
+ logDetL += Math.log(l[sys.colStart[j]]);
524
+ logDetL *= 2;
525
+ let logDetRX = 0;
526
+ for (let k = 0; k < p; k++)
527
+ logDetRX += Math.log(rx[k + k * p]);
528
+ logDetRX *= 2;
529
+ const df = reml ? n - p : n;
530
+ const deviance = (reml ? logDetL + logDetRX : logDetL) + df * (1 + Math.log((2 * Math.PI * prss) / df));
531
+ const out = { deviance, beta, u, b, rss, ussq, prss, logDetL, logDetRX };
532
+ const sInverse = options.gradient === true || options.rxInverse === true ? inverseFromFactor(rx, p) : undefined;
533
+ if (options.rxInverse === true) {
534
+ out.rxInverse = Array.from({ length: p }, (_, i) => Array.from({ length: p }, (_, j) => sInverse[i + j * p]));
535
+ }
536
+ if (options.gradient === true) {
537
+ out.gradient = sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws, xResiduals, sInverse: sInverse });
538
+ }
539
+ return out;
540
+ }
541
+ /** The penalised least-squares solution at θ and the factors it was computed with (see {@link PlsState}) */
542
+ export function plsState(structure, theta) {
504
543
  if (theta.length !== structure.theta.length) {
505
544
  throw new RangeError(`theta must have length ${structure.theta.length}, not ${theta.length}`);
506
545
  }
@@ -643,35 +682,7 @@ export function profiledDeviance(structure, theta, reml, options = {}) {
643
682
  bv = lambdaTimes(sys, t, uv);
644
683
  res = residual(betav, bv);
645
684
  }
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;
685
+ return { sys, t, l, cx, rx, ws, xResiduals, res, uv, beta: betav, b: bv, solveNormal };
675
686
  }
676
687
  /**
677
688
  * 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
@@ -682,7 +693,7 @@ export function profiledDeviance(structure, theta, reml, options = {}) {
682
693
  * Cholesky pattern), so every A⁻¹[k, i] needed is on the pattern, in column min(k, i), already computed when the
683
694
  * columns are taken from the last to the first. The cost is that of the factorisation.
684
695
  */
685
- function selectedInverse(sys, l) {
696
+ export function selectedInverse(sys, l) {
686
697
  const { q, colStart, colRows } = sys;
687
698
  const inv = new Float64Array(l.length);
688
699
  const inColumn = new Int32Array(q).fill(-1);
@@ -725,6 +736,116 @@ function selectedInverse(sys, l) {
725
736
  }
726
737
  return inv;
727
738
  }
739
+ /**
740
+ * The derivative ∂L of the Cholesky factor L of A along a direction in which A changes by ∂A (`da`, the layout of the
741
+ * blocks of A, both triangles of the diagonal blocks): {@link factorise} differentiated step by step (forward mode).
742
+ * In column j, after the columns k < j are subtracted, the work vector holds L_jj L[r, j] (L_jj² at r = j), so with
743
+ * ∂ of the same subtractions (∂L[r, k] L[j, k] + L[r, k] ∂L[j, k]),
744
+ * ∂L_jj = ∂work[j] / (2 L_jj), ∂L[r, j] = (∂work[r] − L[r, j] ∂L_jj) / L_jj.
745
+ * An entry L[j, k] that is 0 (a column of Λ_θ that is 0) is not skipped: its derivative need not be 0.
746
+ */
747
+ export function factoriseSystemTangent(sys, l, da) {
748
+ const { q, colStart, colRows, rowListStart, rowListCol, rowListPos } = sys;
749
+ const dl = new Float64Array(l.length);
750
+ const work = new Float64Array(q);
751
+ for (let h = 0; h < sys.nGroups; h++) {
752
+ const ncc = sys.termNc[sys.groupTerm[h]];
753
+ const first = sys.groupStart[h];
754
+ for (let c = 0; c < ncc; c++) {
755
+ const j = first + c;
756
+ for (let b = sys.blockStart[h]; b < sys.blockStart[h + 1]; b++) {
757
+ const g = sys.blockRow[b];
758
+ const ncr = sys.termNc[sys.groupTerm[g]];
759
+ const base = sys.blockValueStart[b] + c * ncr;
760
+ const r0 = sys.groupStart[g];
761
+ for (let r = g === h ? c : 0; r < ncr; r++)
762
+ work[r0 + r] = da[base + r];
763
+ }
764
+ for (let e = rowListStart[j]; e < rowListStart[j + 1]; e++) {
765
+ const k = rowListCol[e];
766
+ const pos = rowListPos[e];
767
+ const ljk = l[pos];
768
+ const dljk = dl[pos];
769
+ if (ljk === 0 && dljk === 0)
770
+ continue;
771
+ const end = colStart[k + 1];
772
+ for (let t = pos; t < end; t++)
773
+ work[colRows[t]] -= dl[t] * ljk + l[t] * dljk;
774
+ }
775
+ const start = colStart[j];
776
+ const ljj = l[start];
777
+ const dljj = work[j] / (2 * ljj);
778
+ dl[start] = dljj;
779
+ work[j] = 0;
780
+ for (let t = start + 1; t < colStart[j + 1]; t++) {
781
+ const r = colRows[t];
782
+ dl[t] = (work[r] - l[t] * dljj) / ljj;
783
+ work[r] = 0;
784
+ }
785
+ }
786
+ }
787
+ return dl;
788
+ }
789
+ /**
790
+ * The derivative of the selected inverse `inv` of A = L L' given the derivative ∂L of L (`dl`): the recurrences of
791
+ * {@link selectedInverse} differentiated step by step (forward mode). It is ∂(A⁻¹) = −A⁻¹ ∂A A⁻¹ on the pattern of L.
792
+ */
793
+ export function selectedInverseTangent(sys, l, dl, inv) {
794
+ const { q, colStart, colRows } = sys;
795
+ const dinv = new Float64Array(l.length);
796
+ const inColumn = new Int32Array(q).fill(-1);
797
+ const lj = new Float64Array(q);
798
+ const dlj = new Float64Array(q);
799
+ const acc = new Float64Array(q);
800
+ const dacc = new Float64Array(q);
801
+ for (let j = q - 1; j >= 0; j--) {
802
+ const start = colStart[j];
803
+ const end = colStart[j + 1];
804
+ for (let t = start + 1; t < end; t++) {
805
+ const r = colRows[t];
806
+ inColumn[r] = j;
807
+ lj[r] = l[t];
808
+ dlj[r] = dl[t];
809
+ acc[r] = 0;
810
+ dacc[r] = 0;
811
+ }
812
+ for (let t = start + 1; t < end; t++) {
813
+ const k = colRows[t];
814
+ const lkj = l[t];
815
+ const dlkj = dl[t];
816
+ const kStart = colStart[k];
817
+ let sum = inv[kStart] * lkj;
818
+ let dsum = dinv[kStart] * lkj + inv[kStart] * dlkj;
819
+ for (let e = kStart + 1; e < colStart[k + 1]; e++) {
820
+ const r = colRows[e];
821
+ if (inColumn[r] !== j)
822
+ continue;
823
+ const v = inv[e];
824
+ const dv = dinv[e];
825
+ acc[r] += v * lkj;
826
+ dacc[r] += dv * lkj + v * dlkj;
827
+ sum += v * lj[r];
828
+ dsum += dv * lj[r] + v * dlj[r];
829
+ }
830
+ acc[k] += sum;
831
+ dacc[k] += dsum;
832
+ }
833
+ const d = l[start];
834
+ const dd = dl[start];
835
+ let diagonal = 1 / d;
836
+ let ddiagonal = -dd / (d * d);
837
+ for (let t = start + 1; t < end; t++) {
838
+ const r = colRows[t];
839
+ const v = inv[t];
840
+ const dv = -dacc[r] / d + (acc[r] * dd) / (d * d);
841
+ dinv[t] = dv;
842
+ diagonal -= l[t] * v;
843
+ ddiagonal -= dl[t] * v + l[t] * dv;
844
+ }
845
+ dinv[start] = ddiagonal / d - (diagonal * dd) / (d * d);
846
+ }
847
+ return dinv;
848
+ }
728
849
  /**
729
850
  * The gradient of the criterion with respect to θ (see the header), sparse. The log-determinant term
730
851
  * 2 Σ_(r,c) (A⁻¹ K)[c, r] (K = Λ'Z'Z) involves, for the entries (r, c) of Λ_θ in group G,
@@ -734,9 +855,65 @@ function selectedInverse(sys, l) {
734
855
  * place of T_k in every level. The other terms need Z'res (q), W S⁻¹ (q × p) and E'Z (p × q).
735
856
  */
736
857
  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)
858
+ const { n, p, q } = sys;
859
+ const sums = levelTraceSums(sys, selectedInverse(sys, l), t);
860
+ const gradient = new Array(theta.length).fill(0);
861
+ sys.termTheta.forEach((idx, k) => {
862
+ const nc = sys.termNc[k];
863
+ for (let cl = 0; cl < nc; cl++) {
864
+ for (let rl = cl; rl < nc; rl++)
865
+ gradient[idx[rl + cl * nc]] += 2 * sums[k][cl + rl * nc];
866
+ }
867
+ });
868
+ // Z' res
869
+ const zRes = new Float64Array(q);
870
+ for (let i = 0; i < n; i++) {
871
+ const ri = res[i];
872
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
873
+ zRes[sys.rowCols[c]] += sys.rowValues[c] * ri;
874
+ }
875
+ // REML: V = W S⁻¹ (q × p) and E'Z (p × q), both column-major
876
+ let v;
877
+ let ez;
878
+ if (reml && p > 0) {
879
+ v = new Float64Array(q * p);
880
+ for (let m = 0; m < p; m++) {
881
+ for (let k = 0; k < p; k++) {
882
+ const skm = sInverse[k + m * p];
883
+ const wk = ws[k];
884
+ for (let c = 0; c < q; c++)
885
+ v[c + m * q] += wk[c] * skm;
886
+ }
887
+ }
888
+ ez = new Float64Array(p * q);
889
+ for (let i = 0; i < n; i++) {
890
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++) {
891
+ const zr = sys.rowCols[c];
892
+ const val = sys.rowValues[c];
893
+ for (let m = 0; m < p; m++)
894
+ ez[m + zr * p] += xResiduals[m][i] * val;
895
+ }
896
+ }
897
+ }
898
+ const df = reml ? n - p : n;
899
+ const prssFactor = (2 * df) / prss;
900
+ for (const { row: rr, col: c, theta: ti } of structure.lambda) {
901
+ let tr = 0;
902
+ if (v !== undefined && ez !== undefined)
903
+ for (let m = 0; m < p; m++)
904
+ tr += v[c + m * q] * ez[m + rr * p];
905
+ gradient[ti] -= 2 * tr + prssFactor * zRes[rr] * uv[c];
906
+ }
907
+ return gradient;
908
+ }
909
+ /**
910
+ * S_k = Σ over the levels G of term k of (Y Λ' Z'Z) on G's columns (nc_k × nc_k, column-major), for Y = A⁻¹ given by
911
+ * its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
912
+ * in `inv` and in `t`, so that the derivatives of the sums (src/models/mixedDerivatives.ts) come from the derivative
913
+ * of the selected inverse and of the blocks.
914
+ */
915
+ export function levelTraceSums(sys, inv, t) {
916
+ const { colStart, zz } = sys;
740
917
  const sums = sys.termNc.map((nc) => new Float64Array(nc * nc));
741
918
  let y = new Float64Array(16);
742
919
  let f = new Float64Array(16);
@@ -821,52 +998,5 @@ function sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws,
821
998
  }
822
999
  }
823
1000
  }
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;
1001
+ return sums;
872
1002
  }
@@ -1,5 +1,5 @@
1
1
  import { type DataFrame } from "./modelFrame.js";
2
- import { type ModelMatrixOptions } from "./modelMatrix.js";
2
+ import { type DesignContrast, type ModelMatrixOptions } from "./modelMatrix.js";
3
3
  /** A random-effects term of a mixed model, after the expansion of its grouping expression and of `||`. */
4
4
  export interface RandomEffectsTerm {
5
5
  /** The term as R deparses it, such as `"1 | g"`, `"0 + x | b:a"`. */
@@ -68,8 +68,10 @@ export interface MixedModelStructure {
68
68
  /** R's warnings (predictors on very different scales). */
69
69
  warnings: string[];
70
70
  }
71
- /** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix. */
72
- export type MixedModelStructureOptions = ModelMatrixOptions;
71
+ /** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix (contr.poly accepted too). */
72
+ export type MixedModelStructureOptions = Omit<ModelMatrixOptions, "contrasts"> & {
73
+ contrasts?: Record<string, DesignContrast>;
74
+ };
73
75
  /**
74
76
  * The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
75
77
  * layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
@@ -4,8 +4,10 @@
4
4
  //
5
5
  // Written for rStats.js (no ported code) from oracle/lmer-behaviour.md (stage 1a) and the notation of D. Bates,
6
6
  // M. Mächler, B. Bolker, S. Walker (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of Statistical
7
- // Software 67(1). The fixed-effects part is coded as in lm (src/models/modelMatrix.ts); each random-effects term's
8
- // left-hand side is a model matrix with treatment contrasts; its grouping expression is expanded as a right-hand side
7
+ // Software 67(1). The fixed-effects part is the formula without the random-effects terms, coded as lm codes it
8
+ // (src/models/modelMatrix.ts; the order of its own variables names the interaction columns: `y ~ (z | g) + x * z` has
9
+ // `x:z`), on the model frame of the whole formula; each random-effects term's left-hand side is a model matrix with
10
+ // treatment contrasts (a term without columns is an error); its grouping expression is expanded as a right-hand side
9
11
  // into grouping factors (`a/b` gives `b:a` and `a`); `||` splits a term into one term per column group. The terms are
10
12
  // then ordered by their number of levels (decreasing, when not already non-increasing; ties reversed). Z is
11
13
  // level-major within each term, and Λ_θ is block diagonal with one lower-triangular block per level of each term,
@@ -92,19 +94,21 @@ export function mixedModelStructure(formula, data, options = {}) {
92
94
  const { fixed, bars } = splitBarTerms(parsed.rhs);
93
95
  if (typeof data !== "object" || data === null)
94
96
  throw new TypeError("data must be an object of columns");
95
- // the fixed-effects part (its terms collect the variables of the whole formula, so that every model matrix below
96
- // uses the same rows)
97
+ // the fixed-effects part: the formula without the random-effects terms, `response ~ fixed part`, as lm codes it (the
98
+ // order of its variables names the interaction columns); its model frame has the variables of the whole formula too,
99
+ // so that every model matrix below uses the same rows
97
100
  const frameOptions = {
98
101
  ...(options.levels === undefined ? {} : { levels: options.levels }),
99
102
  dropUnusedLevels: true,
100
103
  };
101
104
  // (if nothing is left of the right-hand side, the fixed part is `1`)
102
105
  const fixedRhs = fixed ?? { type: "num", value: 1, text: "1" };
106
+ const fixedFormula = { response: parsed.response, rhs: fixedRhs };
107
+ // the variables of the whole formula (in the model frame, those of the fixed part come first, in its order)
108
+ const allVariables = termsOf(parsed, Object.keys(data), fixedRhs).variables;
103
109
  // (a contrast is for a variable of the fixed-effects part: a grouping variable alone counts as absent)
104
- const contrastOptions = options.contrasts === undefined
105
- ? {}
106
- : { contrasts: options.contrasts, contrastVariables: termsOf({ response: parsed.response, rhs: fixedRhs }, Object.keys(data)).variables };
107
- const fixedDesign = design(parsed, data, { ...frameOptions, ...contrastOptions }, fixedRhs);
110
+ const contrastOptions = options.contrasts === undefined ? {} : { contrasts: options.contrasts };
111
+ const fixedDesign = design(fixedFormula, data, { ...frameOptions, ...contrastOptions, extraVariables: allVariables }, fixedRhs);
108
112
  const { frame } = fixedDesign;
109
113
  const n = frame.rows.length;
110
114
  if (n === 0)
@@ -112,24 +116,28 @@ export function mixedModelStructure(formula, data, options = {}) {
112
116
  // (the model frame's errors, above, come before this check)
113
117
  if (bars.length === 0)
114
118
  throw new Error("No random effects terms specified in formula");
115
- const variables = fixedDesign.terms.variables;
119
+ const variables = [...fixedDesign.terms.variables, ...allVariables.filter((v) => !fixedDesign.terms.variables.includes(v))];
116
120
  // (lhs || group) split into one term per term of lhs, then each term expanded by its grouping factors
117
121
  const expanded = [];
118
- for (const bar of bars) {
122
+ /** The first bar term (in the formula's order) without columns */
123
+ let noColumns;
124
+ bars.forEach((bar, barIndex) => {
119
125
  let lhsList = [bar.lhs];
120
126
  if (bar.double) {
121
127
  const lhsTerms = termsOf(parsed, Object.keys(data), bar.lhs);
122
128
  lhsList = lhsTerms.intercept ? [{ type: "num", value: 1, text: "1" }] : [];
123
129
  for (const t of lhsTerms.terms) {
124
- const term = t.map((v) => ({ type: "var", name: variables[v] })).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r }));
130
+ const term = t.map((v) => ({ type: "var", name: lhsTerms.variables[v] })).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r }));
125
131
  lhsList.push({ type: "binary", op: "+", left: { type: "num", value: 0, text: "0" }, right: term });
126
132
  }
133
+ if (lhsList.length === 0)
134
+ noColumns ??= barIndex;
127
135
  }
128
136
  const factors = groupingFactorsOf(bar.group);
129
137
  for (const lhs of lhsList)
130
138
  for (const groupVariables of factors)
131
- expanded.push({ lhs, groupVariables });
132
- }
139
+ expanded.push({ lhs, groupVariables, bar: barIndex });
140
+ });
133
141
  // the grouping factors (levels present, ordered by the levels of the first variable, then the second, ...)
134
142
  const factorCache = new Map();
135
143
  const factorOf = (vs) => {
@@ -187,6 +195,8 @@ export function mixedModelStructure(formula, data, options = {}) {
187
195
  // the left-hand side: treatment contrasts whatever the options say
188
196
  const lhsDesign = design(parsed, data, frameOptions, t.lhs);
189
197
  const nc = lhsDesign.colNames.length;
198
+ if (nc === 0 && (noColumns === undefined || t.bar < noColumns))
199
+ noColumns = t.bar;
190
200
  const nLevels = t.factor.levels.length;
191
201
  terms.push({
192
202
  label: `${deparseFormula(t.lhs)} | ${t.name}`,
@@ -200,7 +210,11 @@ export function mixedModelStructure(formula, data, options = {}) {
200
210
  zOffset += nLevels * nc;
201
211
  thetaOffset += (nc * (nc + 1)) / 2;
202
212
  }
203
- // checks
213
+ // checks: a term without columns (its bar term as written), then the grouping factors and the numbers of effects
214
+ if (noColumns !== undefined) {
215
+ const bar = bars[noColumns];
216
+ throw new Error(`lmer: the random-effects term '${deparseFormula(bar.lhs)} ${bar.double ? "||" : "|"} ${deparseFormula(bar.group)}' has no columns`);
217
+ }
204
218
  if (groups.some((g) => g.levels.length < 2))
205
219
  throw new RangeError("grouping factors must have > 1 sampled level");
206
220
  const tooMany = groups.filter((g) => g.levels.length >= n).map((g) => g.name);
@@ -286,6 +300,8 @@ export function mixedModelStructure(formula, data, options = {}) {
286
300
  sds.push(sd);
287
301
  }
288
302
  const limit = Math.log(1000);
303
+ // (a constant column other than 0/1 has sd 0, so log(0) = -Infinity and the warning is given: lme4's check includes
304
+ // such columns too, so this is intended)
289
305
  const badScale = sds.some((a, i) => Math.abs(Math.log(a)) > limit || sds.some((b, k) => k !== i && Math.abs(Math.log(a / b)) > limit));
290
306
  if (badScale) {
291
307
  warnings.push("Some predictor variables are on very different scales: consider rescaling. \nYou may also use (g)lmerControl(autoscale = TRUE) to improve numerical stability.");
@@ -49,8 +49,13 @@ export interface ModelMatrixResult {
49
49
  /** R's warnings. */
50
50
  warnings: string[];
51
51
  }
52
+ /**
53
+ * A contrast the internal model-matrix code accepts: those of {@link ContrastName} and R's `contr.poly` (orthogonal
54
+ * polynomials in the level scores 1, 2, ..., columns `.L`, `.Q`, `.C`, `^4`, ...), which lmer's fixed effects may use.
55
+ */
56
+ export type DesignContrast = ContrastName | "contr.poly";
52
57
  /** A contrast matrix (one row per level) and its column names */
53
- export declare function contrastMatrix(levels: readonly string[], contrast: ContrastName | "indicators"): {
58
+ export declare function contrastMatrix(levels: readonly string[], contrast: DesignContrast | "indicators"): {
54
59
  m: number[][];
55
60
  names: string[];
56
61
  };
@@ -67,11 +72,13 @@ export interface Design {
67
72
  warnings: string[];
68
73
  }
69
74
  /** Options of {@link design} */
70
- export interface DesignOptions extends ModelMatrixOptions {
75
+ export interface DesignOptions extends Omit<ModelMatrixOptions, "contrasts"> {
76
+ /** A contrast per factor, as {@link ModelMatrixOptions.contrasts} (`contr.poly` too) */
77
+ contrasts?: Record<string, DesignContrast>;
71
78
  weights?: Sample | string;
72
79
  dropUnusedLevels?: boolean;
73
80
  /** Contrast used for every factor instead of `contrasts` (the error model of aov) */
74
- allContrasts?: ContrastName;
81
+ allContrasts?: DesignContrast;
75
82
  /** The intercept flag to use instead of the formula's (the error model of aov) */
76
83
  intercept?: boolean;
77
84
  /** More variables whose missing values drop rows (the rest of the formula, for the error model of aov) */