@numero-uno-jpn/rstats 0.17.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.ja.md +20 -12
  3. package/README.md +22 -12
  4. package/THIRD_PARTY_NOTICES.md +3 -2
  5. package/dist/chunks/{chunk-4WE3OO62.js → chunk-4KCSBTR5.js} +2 -2
  6. package/dist/chunks/chunk-4VRMAYPY.js +3 -0
  7. package/dist/chunks/{chunk-RFE7MVP7.js → chunk-7IJCUSA5.js} +2 -2
  8. package/dist/chunks/chunk-7KJ24LYK.js +2 -0
  9. package/dist/chunks/{chunk-Z37NELOS.js → chunk-DR4GQ7PW.js} +1 -1
  10. package/dist/chunks/chunk-DTJG2IL2.js +2 -0
  11. package/dist/chunks/{chunk-C7V2FH6L.js → chunk-EJYCDE4Z.js} +1 -1
  12. package/dist/chunks/{chunk-LV3W2F7N.js → chunk-GGJA3JRO.js} +2 -2
  13. package/dist/chunks/{chunk-H3WVPZDL.js → chunk-GJEKNJP7.js} +2 -2
  14. package/dist/chunks/{chunk-2C33MXSW.js → chunk-GRUQRNX7.js} +2 -2
  15. package/dist/chunks/chunk-GYGQUYEP.js +2 -0
  16. package/dist/chunks/chunk-HRA7PCQT.js +2 -0
  17. package/dist/chunks/{chunk-WM7VFXTV.js → chunk-HUWOSLKE.js} +1 -1
  18. package/dist/chunks/{chunk-TNMJPQPV.js → chunk-HZLSNJQM.js} +2 -2
  19. package/dist/chunks/{chunk-ZFQWB222.js → chunk-JNWWLNE3.js} +2 -2
  20. package/dist/chunks/{chunk-DXI5N2ET.js → chunk-N5BDSMXS.js} +1 -1
  21. package/dist/chunks/{chunk-LHUIJQHY.js → chunk-NDTJ23A6.js} +2 -2
  22. package/dist/chunks/{chunk-SE7V2KLO.js → chunk-OG7UORIX.js} +1 -1
  23. package/dist/chunks/{chunk-ONY5CISH.js → chunk-QUTJEYDX.js} +2 -2
  24. package/dist/chunks/chunk-U7BRXOUS.js +2 -0
  25. package/dist/chunks/{chunk-FY3FVOBM.js → chunk-UMLMY4XS.js} +2 -2
  26. package/dist/chunks/{chunk-6JJQL6HL.js → chunk-X4J6UJHN.js} +2 -2
  27. package/dist/chunks/{chunk-34S5SQY6.js → chunk-Y4YWLSWU.js} +2 -2
  28. package/dist/chunks/{chunk-5AYHCITP.js → chunk-YN5MLKDL.js} +2 -2
  29. package/dist/chunks/{chunk-CZI7KUO3.js → chunk-Z2HGLFZN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions/signrank.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/mixed.d.ts +6 -0
  34. package/dist/entries/mixed.js +6 -1
  35. package/dist/entries/tests.d.ts +1 -1
  36. package/dist/htest/ansariTest.js +32 -34
  37. package/dist/htest/cor.d.ts +2 -2
  38. package/dist/htest/cor.js +2 -1
  39. package/dist/htest/core/scoreDistribution.d.ts +39 -0
  40. package/dist/htest/core/scoreDistribution.js +151 -0
  41. package/dist/htest/wilcoxTest.d.ts +23 -8
  42. package/dist/htest/wilcoxTest.js +521 -199
  43. package/dist/linalg/chol.d.ts +3 -3
  44. package/dist/linalg/chol.js +10 -2
  45. package/dist/linalg/qr.js +39 -15
  46. package/dist/linalg.js +2 -2
  47. package/dist/mixed.js +5 -4
  48. package/dist/models/anovaSequential.d.ts +16 -1
  49. package/dist/models/anovaSequential.js +40 -5
  50. package/dist/models/aovStrata.js +21 -4
  51. package/dist/models/formula.d.ts +5 -2
  52. package/dist/models/formula.js +31 -8
  53. package/dist/models/glm.d.ts +15 -4
  54. package/dist/models/glm.js +13 -6
  55. package/dist/models/glmer.d.ts +255 -0
  56. package/dist/models/glmer.js +635 -0
  57. package/dist/models/glmerAnova.d.ts +81 -0
  58. package/dist/models/glmerAnova.js +139 -0
  59. package/dist/models/glmerDeviance.d.ts +98 -0
  60. package/dist/models/glmerDeviance.js +576 -0
  61. package/dist/models/glmerFamily.d.ts +57 -0
  62. package/dist/models/glmerFamily.js +236 -0
  63. package/dist/models/glmerGradient.d.ts +46 -0
  64. package/dist/models/glmerGradient.js +301 -0
  65. package/dist/models/glmerStructure.d.ts +45 -0
  66. package/dist/models/glmerStructure.js +168 -0
  67. package/dist/models/glmerSummary.d.ts +102 -0
  68. package/dist/models/glmerSummary.js +94 -0
  69. package/dist/models/lmer.d.ts +16 -0
  70. package/dist/models/lmer.js +55 -306
  71. package/dist/models/lmerAnova.d.ts +49 -0
  72. package/dist/models/lmerAnova.js +91 -40
  73. package/dist/models/lmerTest.d.ts +8 -1
  74. package/dist/models/lmerTest.js +21 -8
  75. package/dist/models/mixedDeviance.d.ts +28 -2
  76. package/dist/models/mixedDeviance.js +84 -56
  77. package/dist/models/mixedMinimiser.d.ts +83 -0
  78. package/dist/models/mixedMinimiser.js +438 -0
  79. package/dist/models/mixedPredict.d.ts +121 -0
  80. package/dist/models/mixedPredict.js +530 -0
  81. package/dist/models/mixedStructure.d.ts +62 -3
  82. package/dist/models/mixedStructure.js +74 -29
  83. package/dist/models/modelMatrix.d.ts +8 -1
  84. package/dist/models/modelMatrix.js +49 -37
  85. package/dist/models/survival.d.ts +4 -1
  86. package/dist/models/survival.js +7 -1
  87. package/dist/numerics.js +2 -2
  88. package/dist/rstats.js +16 -16
  89. package/dist/special.js +2 -2
  90. package/dist/tests.js +13 -14
  91. package/llms.txt +11 -3
  92. package/package.json +1 -1
  93. package/dist/chunks/chunk-M4ITG7YR.js +0 -2
  94. package/dist/chunks/chunk-NSYZTS26.js +0 -2
  95. package/dist/chunks/chunk-THIGHOKK.js +0 -2
  96. package/dist/chunks/chunk-WMDYDTVQ.js +0 -2
  97. package/dist/chunks/chunk-XLSFJTTK.js +0 -2
@@ -84,32 +84,74 @@ function sameFrame(a, b) {
84
84
  return v !== undefined && u.length === v.length && Array.prototype.every.call(u, (x, i) => Object.is(x, v[i]));
85
85
  });
86
86
  }
87
- function compareFits(fits, options) {
88
- if (fits.length < 2)
89
- throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
90
- const internals = fits.map(lmerInternals);
87
+ /** The model of an lmer fit in a comparison (internal) */
88
+ export function comparedLmer(fit) {
89
+ const internals = lmerInternals(fit);
90
+ const { snapshot, data } = internals;
91
+ const lhs = fit.formula.slice(0, fit.formula.indexOf("~"));
92
+ const ones = () => new Array(fit.nObs).fill(1);
93
+ return {
94
+ nObs: fit.nObs,
95
+ df: fit.df,
96
+ logLik: fit.logLik,
97
+ reml: fit.REML,
98
+ refitLogLik: () => lmerWithCriterion(fit.formula, snapshot, { ...internals.options, REML: false }, internals.criterion).logLik,
99
+ mixed: { data, snapshot, rows: fit.rows, response: lhs.replace(/\s+/g, "") },
100
+ // (the left-hand side of lmer's formula is a column name)
101
+ response: () => fit.rows.map((i) => Number(snapshot[lhs.trim()]?.[i] ?? NaN)),
102
+ weights: ones,
103
+ family: "gaussian",
104
+ link: "identity",
105
+ offset: () => new Array(fit.nObs).fill(0),
106
+ x: () => internals.structure.x,
107
+ randomTerms: fit.varCorr,
108
+ };
109
+ }
110
+ /** Whether two vectors are equal element by element */
111
+ function sameValues(a, b) {
112
+ return a.length === b.length && a.every((v, i) => v === b[i] || (Number.isNaN(v) && Number.isNaN(b[i])));
113
+ }
114
+ /**
115
+ * lme4's likelihood-ratio comparison of fits (internal; lmerAnova's and glmerAnova's): the checks that the fits are of
116
+ * the same observations, the names, the ML refits of REML fits, the rows sorted by the number of parameters and the
117
+ * test where the fit of the row before is nested in the row's. `fn` names the function in its error for fewer than
118
+ * two fits.
119
+ */
120
+ export function compareModels(fn, models, options) {
121
+ if (models.length < 2)
122
+ throw new TypeError(`${fn} needs one fit, or an array of at least two fits to compare`);
91
123
  // (only the number of observations is compared, as lme4 does; the fits must also share the data object below)
92
- if (fits.some((f) => f.nObs !== fits[0].nObs))
124
+ if (models.some((f) => f.nObs !== models[0].nObs))
93
125
  throw new Error("models were not all fitted to the same size of dataset");
94
- if (internals.some((i) => i.data !== internals[0].data))
95
- throw new Error("all models must be fit to the same data object");
96
- // (the same object changed between the fits holds different data)
97
- if (internals.some((i) => !sameFrame(i.snapshot, internals[0].snapshot)))
98
- throw new Error("all models must be fit to the same data object");
99
- // A likelihood ratio compares likelihoods of the same observations: the same rows of the data and the same response
100
- // (lme4 compares only the number of rows, and returns a test for fits of different rows or responses)
101
- const sameRows = (r) => r.length === fits[0].rows.length && r.every((v, i) => v === fits[0].rows[i]);
102
- if (fits.some((f) => !sameRows(f.rows)))
103
- throw new Error("models were not all fitted to the same rows of the data");
104
- const response = (f) => f.formula.slice(0, f.formula.indexOf("~")).replace(/\s+/g, "");
105
- if (fits.some((f) => response(f) !== response(fits[0])))
126
+ const mixed = models.flatMap((m) => (m.mixed === undefined ? [] : [m.mixed]));
127
+ const first = mixed[0];
128
+ if (first !== undefined) {
129
+ if (mixed.some((i) => i.data !== first.data))
130
+ throw new Error("all models must be fit to the same data object");
131
+ // (the same object changed between the fits holds different data)
132
+ if (mixed.some((i) => !sameFrame(i.snapshot, first.snapshot)))
133
+ throw new Error("all models must be fit to the same data object");
134
+ // A likelihood ratio compares likelihoods of the same observations: the same rows of the data and the same response
135
+ // (lme4 compares only the number of rows, and returns a test for fits of different rows or responses)
136
+ const sameRows = (r) => r.length === first.rows.length && r.every((v, i) => v === first.rows[i]);
137
+ if (mixed.some((i) => !sameRows(i.rows)))
138
+ throw new Error("models were not all fitted to the same rows of the data");
139
+ }
140
+ // the response: by the formulas' left-hand sides between fits with a formula, by value against a fit without (glm)
141
+ const reference = models.find((m) => m.mixed !== undefined) ?? models[0];
142
+ const sameResponse = (m) => m.mixed !== undefined && reference.mixed !== undefined ? m.mixed.response === reference.mixed.response : sameValues(m.response(), reference.response());
143
+ if (models.some((m) => m !== reference && !sameResponse(m)))
106
144
  throw new Error("models were not all fitted to the same response");
145
+ // (the prior weights are part of the data: a binomial proportion with weights m and a 0/1 response differ)
146
+ if (models.some((m) => m !== reference && !sameValues(m.weights(), reference.weights()))) {
147
+ throw new Error("models were not all fitted with the same prior weights");
148
+ }
107
149
  const warnings = new Warnings();
108
150
  const messages = [];
109
- let names = fits.map((_, i) => `MODEL${i + 1}`);
151
+ let names = models.map((_, i) => `MODEL${i + 1}`);
110
152
  if (options.names !== undefined) {
111
- if (options.names.length !== fits.length || options.names.some((n) => typeof n !== "string")) {
112
- throw new TypeError(`names must be ${fits.length} strings, one per fit`);
153
+ if (options.names.length !== models.length || options.names.some((n) => typeof n !== "string")) {
154
+ throw new TypeError(`names must be ${models.length} strings, one per fit`);
113
155
  }
114
156
  if (new Set(options.names).size === options.names.length)
115
157
  names = [...options.names];
@@ -119,34 +161,38 @@ function compareFits(fits, options) {
119
161
  const refit = logicalOption(options.refit, true);
120
162
  let logLik;
121
163
  if (refit) {
122
- if (fits.some((f) => f.REML))
164
+ if (models.some((f) => f.reml))
123
165
  messages.push("refitting model(s) with ML (instead of REML)");
124
- logLik = fits.map((f, i) => {
125
- if (!f.REML)
126
- return f.logLik;
127
- const { snapshot, options: o, criterion } = internals[i];
128
- return lmerWithCriterion(f.formula, snapshot, { ...o, REML: false }, criterion).logLik;
129
- });
166
+ logLik = models.map((f) => (f.reml && f.refitLogLik !== undefined ? f.refitLogLik() : f.logLik));
130
167
  }
131
168
  else {
132
- if (fits.some((f) => f.REML) && fits.some((f) => !f.REML))
169
+ if (models.some((f) => f.reml) && models.some((f) => !f.reml))
133
170
  warnings.add("some models fit with REML = TRUE, some not");
134
- logLik = fits.map((f) => f.logLik);
171
+ logLik = models.map((f) => f.logLik);
135
172
  }
136
173
  // sorted by the number of parameters (stable)
137
- const order = fits.map((_, i) => i).sort((a, b) => fits[a].df - fits[b].df || a - b);
138
- const n = fits[0].nObs;
139
- const npar = order.map((i) => fits[i].df);
174
+ const order = models.map((_, i) => i).sort((a, b) => models[a].df - models[b].df || a - b);
175
+ const n = models[0].nObs;
176
+ const npar = order.map((i) => models[i].df);
140
177
  const ll = order.map((i) => logLik[i]);
141
178
  // A likelihood ratio test needs the smaller fit to be a special case of the larger one (lme4 gives a p-value for any
142
- // pair): its fixed-effect columns among the larger fit's, and each of its random-effect terms within a term of the
143
- // same grouping factor there ((1 | g) + (0 + x | g) within (1 + x | g), not the converse). Otherwise no test (AIC
144
- // and BIC still compare the fits). The fixed effects are compared as column spaces (the fits use the same rows of the
145
- // same data): by their names, the same factor in other contrasts (contr.sum against contr.treatment) looked not
146
- // nested and was not tested (issue #8)
147
- const nestedIn = (small, large) => nestedColumns(lmerInternals(small).structure.x, lmerInternals(large).structure.x) &&
148
- small.varCorr.every((t) => large.varCorr.some((u) => u.group === t.group && t.columns.every((c) => u.columns.includes(c))));
149
- const nested = order.map((i, k) => k > 0 && nestedIn(fits[order[k - 1]], fits[i]));
179
+ // pair): the same family and link (an lmer fit is gaussian with the identity link) and the same offset, its
180
+ // fixed-effect columns among the larger fit's, and each of its random-effect terms within a term of the same grouping
181
+ // factor there ((1 | g) + (0 + x | g) within (1 + x | g), not the converse). Otherwise no test (AIC and BIC still
182
+ // compare the fits). The fixed effects are compared as column spaces (the fits use the same rows of the same data):
183
+ // by their names, the same factor in other contrasts (contr.sum against contr.treatment) looked not nested and was
184
+ // not tested (issue #8)
185
+ // The offsets and the columns are compared on the rows of positive weight only (the fits share their weights): rows
186
+ // of weight 0 are not in the likelihoods, and one of them made nested columns look otherwise, as in glmAnova and
187
+ // anovaSequential (#509)
188
+ const positive = reference.weights().map((w) => w !== 0);
189
+ const counted = (rows) => rows.filter((_, i) => positive[i]);
190
+ const nestedIn = (small, large) => small.family === large.family &&
191
+ small.link === large.link &&
192
+ sameValues(counted(small.offset()), counted(large.offset())) &&
193
+ nestedColumns(counted(small.x()), counted(large.x())) &&
194
+ small.randomTerms.every((t) => large.randomTerms.some((u) => u.group === t.group && t.columns.every((c) => u.columns.includes(c))));
195
+ const nested = order.map((i, k) => k > 0 && nestedIn(models[order[k - 1]], models[i]));
150
196
  const Chisq = ll.map((v, k) => (k === 0 || !nested[k] ? NaN : 2 * Math.max(0, v - ll[k - 1])));
151
197
  const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
152
198
  const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
@@ -164,6 +210,11 @@ function compareFits(fits, options) {
164
210
  warnings: warnings.list,
165
211
  };
166
212
  }
213
+ function compareFits(fits, options) {
214
+ if (fits.length < 2)
215
+ throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
216
+ return compareModels("lmerAnova", fits.map(comparedLmer), options);
217
+ }
167
218
  export function lmerAnova(fit, options) {
168
219
  if (Array.isArray(fit)) {
169
220
  checkLmerOptions("lmerAnova", options, ["modelNames", "model.names"]);
@@ -21,6 +21,13 @@ export interface LmerSatterthwaite {
21
21
  * #9): estimates, standard errors and right-hand sides are scaled by it in the tests, sums of squares by 4^scale
22
22
  */
23
23
  scale: number;
24
+ /**
25
+ * The quantities above are also those of X with column k divided by 2^xScale[k] (β, vcov and the jacobian in the
26
+ * units of β'_k = 2^xScale[k] β_k): 0 unless the column's largest |value| is beyond 2^±500, where the cross-products
27
+ * of X overflow or underflow (predictors times 1e-160 gave a vcov of Infinity and standard errors NaN). The tests
28
+ * take their contrasts to these units (L β = (L D⁻¹) β' with D = diag(2^xScale))
29
+ */
30
+ xScale: number[];
24
31
  }
25
32
  /** The warnings about the Hessian's eigenvalues (negative, or close to 0; internal) */
26
33
  export declare function hessianWarnings(values: readonly number[]): string[];
@@ -44,7 +51,7 @@ export interface TRow {
44
51
  pValue: number;
45
52
  }
46
53
  /** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
47
- export declare function tTestOf(s: LmerSatterthwaite, l0: readonly number[], rhs0: number, beta?: readonly number[]): TRow;
54
+ export declare function tTestOf(s: LmerSatterthwaite, l0: readonly number[], rhs0: number): TRow;
48
55
  /** One row of an F table (internal): lmerTest's `Sum Sq`, `Mean Sq`, `NumDF`, `DenDF`, `F value`, `Pr(>F)` */
49
56
  export interface LmerFRow {
50
57
  sumSq: number;
@@ -19,7 +19,7 @@ import { ginv } from "../linalg/kappa.js";
19
19
  import { rangeExponent } from "../linalg/matrix.js";
20
20
  import { reported, Warnings } from "../internal/warnings.js";
21
21
  import { ldexp } from "../internal/summary.js";
22
- import { checkLmerOptions, lmerInternals, logicalOption, thetaColumnExponents } from "./lmer.js";
22
+ import { checkLmerOptions, extremeColumnExponents, lmerInternals, logicalOption, thetaColumnExponents } from "./lmer.js";
23
23
  import { varparDerivatives } from "./mixedDerivatives.js";
24
24
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
25
25
  import { checkOptions } from "../internal/checkOptions.js";
@@ -32,6 +32,10 @@ const HESSIAN_TOLERANCE = 1e-8;
32
32
  const RANK_TOLERANCE = Math.sqrt(Number.EPSILON);
33
33
  /** Satterthwaite's degrees of freedom of a joint test are averaged when they differ by less than this */
34
34
  const EQUAL_DF_TOLERANCE = 1e-8;
35
+ /** A contrast in the units of the scaled columns of X (see LmerSatterthwaite.xScale) */
36
+ function scaledContrast(s, l) {
37
+ return s.xScale.every((e) => e === 0) ? l : l.map((v, k) => ldexp(v, -s.xScale[k]));
38
+ }
35
39
  const satterthwaiteByFit = new WeakMap();
36
40
  /** A number as C's printf("%1.1e") writes it: "-3.2e-04" */
37
41
  function formatE1(v) {
@@ -79,7 +83,10 @@ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
79
83
  for (const v of structure.y)
80
84
  top = Math.max(top, Math.abs(v));
81
85
  const scale = top > 2 ** 500 || top < 2 ** -500 ? Math.floor(Math.log2(top)) : 0;
82
- const st = scale === 0 ? structure : { ...structure, y: structure.y.map((v) => ldexp(v, -scale)) };
86
+ const scaledY = scale === 0 ? structure : { ...structure, y: structure.y.map((v) => ldexp(v, -scale)) };
87
+ // columns of X of extreme scale divided by powers of 2 (exact; see LmerSatterthwaite.xScale): otherwise nothing changes
88
+ const xScale = extremeColumnExponents(structure.x, structure.xColNames.length);
89
+ const st = xScale.every((e) => e === 0) ? scaledY : { ...scaledY, x: scaledY.x.map((row) => row.map((v, k) => ldexp(v, -xScale[k]))) };
83
90
  const d = varparDerivatives(st, theta, reml);
84
91
  const m = d.varpar.length;
85
92
  // The Hessian in coordinates of comparable scale, D H D: θ_k times 2^e_k (the columns of Z of its row; see
@@ -110,12 +117,13 @@ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
110
117
  hessian: d.hessian,
111
118
  hessianEigenvalues: values,
112
119
  vcovVarpar,
113
- beta: d.beta.map((b, k) => b + ldexp(beta0[k] ?? 0, -scale)),
120
+ beta: d.beta.map((b, k) => b + ldexp(beta0[k] ?? 0, xScale[k] - scale)),
114
121
  sigma: d.varpar[m - 1],
115
122
  vcov: d.vcov,
116
123
  jacobian: d.jacobian,
117
124
  warnings: hessianWarnings(values),
118
125
  scale,
126
+ xScale,
119
127
  };
120
128
  }
121
129
  const quadraticForm = (l, m) => {
@@ -132,7 +140,11 @@ const quadraticForm = (l, m) => {
132
140
  };
133
141
  const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
134
142
  /** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
135
- export function tTestOf(s, l0, rhs0, beta = s.beta) {
143
+ export function tTestOf(s, l0, rhs0) {
144
+ return tTestScaled(s, scaledContrast(s, l0), rhs0, s.beta);
145
+ }
146
+ /** {@link tTestOf} with l in the units of the scaled columns of X (see LmerSatterthwaite.xScale) */
147
+ function tTestScaled(s, l0, rhs0, beta) {
136
148
  if (l0.some(Number.isNaN) || Number.isNaN(rhs0))
137
149
  return { estimate: NaN, stdError: NaN, df: NaN, tValue: NaN, pValue: NaN };
138
150
  // a contrast of extreme magnitude (1e160, 1e-200) divided by 2^k with its rhs: the test does not depend on it, and
@@ -184,8 +196,9 @@ export function fTestOf(s, L0, rhs, warnings) {
184
196
  // L of extreme magnitude and its rhs divided by one power of 2 (the test does not depend on it; the same factor for
185
197
  // every row keeps the eigenvectors of L V L', and with them the rotated contrasts and the df). L V L' overflowed or
186
198
  // underflowed (#58)
187
- const k = rangeExponent(L0.flat());
188
- const L = k === 0 ? L0 : L0.map((row) => row.map((v) => ldexp(v, -k)));
199
+ const L1 = L0.map((row) => scaledContrast(s, row));
200
+ const k = rangeExponent(L1.flat());
201
+ const L = k === 0 ? L1 : L1.map((row) => row.map((v) => ldexp(v, -k)));
189
202
  // (the right-hand side in the units of the scaled response: tTestOf scales its own, the joint test below uses these)
190
203
  const given = (rhs ?? new Array(r).fill(0)).map((v) => ldexp(v, -k));
191
204
  const right = given.map((v) => ldexp(v, -s.scale));
@@ -194,7 +207,7 @@ export function fTestOf(s, L0, rhs, warnings) {
194
207
  const l = L[0];
195
208
  if (!l.some(Number.isNaN) && !(l.reduce((sum, v, j) => sum + v * l.reduce((t, w, k) => t + s.vcov[j][k] * w, 0), 0) > 0))
196
209
  return undefined;
197
- const t = tTestOf(s, l, given[0]);
210
+ const t = tTestScaled(s, l, given[0], s.beta);
198
211
  return fRowOf(s, t.tValue * t.tValue, 1, t.df);
199
212
  }
200
213
  if (L.some((row) => row.some(Number.isNaN)) || right.some(Number.isNaN))
@@ -220,7 +233,7 @@ export function fTestOf(s, L0, rhs, warnings) {
220
233
  const p = s.beta.length;
221
234
  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)));
222
235
  if (kept === 1) {
223
- const t = tTestOf(s, rotated[0], 0, beta);
236
+ const t = tTestScaled(s, rotated[0], 0, beta);
224
237
  return fRowOf(s, t.tValue * t.tValue, 1, t.df);
225
238
  }
226
239
  let f = 0;
@@ -77,15 +77,41 @@ export interface SparseSystem {
77
77
  * at colStart[column] + (rows of the diagonal block from the column) + blockPatternOffset[b] + r (0 on the diagonal)
78
78
  */
79
79
  blockPatternOffset: Int32Array;
80
+ /**
81
+ * For each row i and each pair of terms k ≥ l, the block of Z'Z (its index in the sorted blocks) that the row adds
82
+ * to, at i nPairs + k (k + 1) / 2 + l: the weighted cross-product Z'WZ of glmer is formed with it
83
+ */
84
+ rowBlocks: Int32Array;
80
85
  }
86
+ /** The groups of columns, the cross-products and the pattern of the factor of a structure (cached) */
87
+ export declare function sparseSystemOf(s: MixedModelStructure): SparseSystem;
88
+ /** Z'WZ by blocks, in the layout of the system's Z'Z (glmer's working weights `w`, one per row) */
89
+ export declare function weightedCrossProduct(sys: SparseSystem, s: MixedModelStructure, w: ArrayLike<number>): Float64Array;
90
+ /** Z v (n-vector) from the sparse Z, for a q-vector v */
91
+ export declare function zTimes(sys: SparseSystem, v: ArrayLike<number>): Float64Array;
92
+ /** Z' v (q-vector) from the sparse Z, for an n-vector v */
93
+ export declare function zTransposeTimes(sys: SparseSystem, v: ArrayLike<number>): Float64Array;
94
+ /** The blocks T_k at θ (nc × nc, column-major, lower triangular) */
95
+ export declare function blocksOf(sys: SparseSystem, theta: readonly number[]): Float64Array[];
81
96
  /** Λ_θ w (q-vector) */
82
97
  export declare function lambdaTimes(sys: SparseSystem, t: Float64Array[], w: Float64Array): Float64Array;
83
98
  /** Λ_θ' M for a q × ncol column-major M */
84
99
  export declare function lambdaTransposeTimes(sys: SparseSystem, t: Float64Array[], m: Float64Array, ncol?: number): Float64Array;
100
+ /**
101
+ * 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
102
+ * (with `zz`, Z'WZ by blocks instead of Z'Z: glmer's Λ_θ' Z'WZ Λ_θ + I)
103
+ */
104
+ export declare function blocksOfA(sys: SparseSystem, t: Float64Array[], zz?: Float64Array): Float64Array;
105
+ /** The values of the Cholesky factor L of A (A = L L', the pattern of the system), from the blocks of A */
106
+ export declare function factorise(sys: SparseSystem, a: Float64Array): Float64Array;
85
107
  /** Solves L x = v in place (v of length q, at an offset) */
86
108
  export declare function solveL(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
87
109
  /** Solves L' x = v in place */
88
110
  export declare function solveLt(sys: SparseSystem, l: Float64Array, v: Float64Array, offset?: number): void;
111
+ /** Solves L x = v in place, with L = R' and R the upper-triangular factor (column-major, k × k) */
112
+ export declare function forwardSolve(r: Float64Array, k: number, v: Float64Array): void;
113
+ /** Solves R x = v in place, R upper triangular (column-major, k × k) */
114
+ export declare function backSolve(r: Float64Array, k: number, v: Float64Array): void;
89
115
  /** The full symmetric inverse of R'R from an upper-triangular factor R (column-major, k × k; R is not changed) */
90
116
  export declare function inverseFromFactor(r: Float64Array, k: number): Float64Array;
91
117
  /**
@@ -151,6 +177,6 @@ export declare function selectedInverseTangent(sys: SparseSystem, l: Float64Arra
151
177
  * 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
178
  * its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
153
179
  * 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.
180
+ * of the selected inverse and of the blocks. With `zz` (Z'WZ by blocks, glmer's gradient), Λ'Z'WZ in place of Λ'Z'Z.
155
181
  */
156
- export declare function levelTraceSums(sys: SparseSystem, inv: Float64Array, t: Float64Array[]): Float64Array[];
182
+ export declare function levelTraceSums(sys: SparseSystem, inv: Float64Array, t: Float64Array[], zz?: Float64Array): Float64Array[];
@@ -61,7 +61,7 @@ import { potf2, potri } from "../linalg/chol.js";
61
61
  const REFINEMENT_STEPS = 1;
62
62
  const systemCache = new WeakMap();
63
63
  /** The groups of columns, the cross-products and the pattern of the factor of a structure (cached) */
64
- function sparseSystemOf(s) {
64
+ export function sparseSystemOf(s) {
65
65
  const cached = systemCache.get(s);
66
66
  if (cached !== undefined)
67
67
  return cached;
@@ -171,31 +171,14 @@ function sparseSystemOf(s) {
171
171
  });
172
172
  for (let h = 0; h < nGroups; h++)
173
173
  blockStart[h + 1] += blockStart[h];
174
- const zz = new Float64Array(blockValueStart[nBlocks]);
174
+ const rowBlocks = rowPairs.map((b) => position[b]);
175
+ const zz = crossProductBlocks(s, termNc, blockValueStart, rowBlocks, undefined);
175
176
  const zx = new Float64Array(q * p);
176
177
  const zy = new Float64Array(q);
177
178
  const xy = new Float64Array(p);
178
179
  for (let i = 0; i < n; i++) {
179
180
  const xi = s.x[i];
180
181
  const yi = s.y[i];
181
- for (let k = 0; k < nTerms; k++) {
182
- const mk = s.terms[k].matrix[i];
183
- const nck = termNc[k];
184
- for (let l = 0; l <= k; l++) {
185
- const ml = s.terms[l].matrix[i];
186
- const ncl = termNc[l];
187
- const at = position[rowPairs[i * nPairs + (k * (k + 1)) / 2 + l]];
188
- const base = blockValueStart[at];
189
- // block (group of k, group of l): nck × ncl, column-major
190
- for (let c = 0; c < ncl; c++) {
191
- const v = ml[c];
192
- if (v === 0)
193
- continue;
194
- for (let r = 0; r < nck; r++)
195
- zz[base + r + c * nck] += mk[r] * v;
196
- }
197
- }
198
- }
199
182
  for (let a = rowStart[i]; a < rowStart[i + 1]; a++) {
200
183
  const ja = rowCols[a];
201
184
  const va = rowValues[a];
@@ -304,12 +287,71 @@ function sparseSystemOf(s) {
304
287
  rowListCol,
305
288
  rowListPos,
306
289
  blockPatternOffset,
290
+ rowBlocks,
307
291
  };
308
292
  systemCache.set(s, result);
309
293
  return result;
310
294
  }
295
+ /**
296
+ * Z'WZ by blocks, in the layout of the system's Z'Z (W the diagonal matrix of the weights `w`; Z'Z without them),
297
+ * from the terms' left-hand side matrices and the block of each row and pair of terms
298
+ */
299
+ function crossProductBlocks(s, termNc, blockValueStart, rowBlocks, w) {
300
+ const n = s.y.length;
301
+ const nTerms = s.terms.length;
302
+ const nPairs = (nTerms * (nTerms + 1)) / 2;
303
+ const zz = new Float64Array(blockValueStart[blockValueStart.length - 1]);
304
+ for (let i = 0; i < n; i++) {
305
+ const wi = w === undefined ? 1 : w[i];
306
+ if (wi === 0)
307
+ continue;
308
+ for (let k = 0; k < nTerms; k++) {
309
+ const mk = s.terms[k].matrix[i];
310
+ const nck = termNc[k];
311
+ for (let l = 0; l <= k; l++) {
312
+ const ml = s.terms[l].matrix[i];
313
+ const ncl = termNc[l];
314
+ const base = blockValueStart[rowBlocks[i * nPairs + (k * (k + 1)) / 2 + l]];
315
+ // block (group of k, group of l): nck × ncl, column-major
316
+ for (let c = 0; c < ncl; c++) {
317
+ const v = w === undefined ? ml[c] : wi * ml[c];
318
+ if (v === 0)
319
+ continue;
320
+ for (let r = 0; r < nck; r++)
321
+ zz[base + r + c * nck] += mk[r] * v;
322
+ }
323
+ }
324
+ }
325
+ }
326
+ return zz;
327
+ }
328
+ /** Z'WZ by blocks, in the layout of the system's Z'Z (glmer's working weights `w`, one per row) */
329
+ export function weightedCrossProduct(sys, s, w) {
330
+ return crossProductBlocks(s, sys.termNc, sys.blockValueStart, sys.rowBlocks, w);
331
+ }
332
+ /** Z v (n-vector) from the sparse Z, for a q-vector v */
333
+ export function zTimes(sys, v) {
334
+ const out = new Float64Array(sys.n);
335
+ for (let i = 0; i < sys.n; i++) {
336
+ let sum = 0;
337
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
338
+ sum += sys.rowValues[c] * v[sys.rowCols[c]];
339
+ out[i] = sum;
340
+ }
341
+ return out;
342
+ }
343
+ /** Z' v (q-vector) from the sparse Z, for an n-vector v */
344
+ export function zTransposeTimes(sys, v) {
345
+ const zv = new Float64Array(sys.q);
346
+ for (let i = 0; i < sys.n; i++) {
347
+ const vi = v[i];
348
+ for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
349
+ zv[sys.rowCols[c]] += sys.rowValues[c] * vi;
350
+ }
351
+ return zv;
352
+ }
311
353
  /** The blocks T_k at θ (nc × nc, column-major, lower triangular) */
312
- function blocksOf(sys, theta) {
354
+ export function blocksOf(sys, theta) {
313
355
  return sys.termTheta.map((idx) => Float64Array.from(idx, (t) => (t < 0 ? 0 : theta[t])));
314
356
  }
315
357
  /** Λ_θ w (q-vector) */
@@ -351,9 +393,12 @@ export function lambdaTransposeTimes(sys, t, m, ncol = 1) {
351
393
  }
352
394
  return out;
353
395
  }
354
- /** 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 */
355
- function blocksOfA(sys, t) {
356
- const a = new Float64Array(sys.zz.length);
396
+ /**
397
+ * 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
398
+ * (with `zz`, Z'WZ by blocks instead of Z'Z: glmer's Λ_θ' Z'WZ Λ_θ + I)
399
+ */
400
+ export function blocksOfA(sys, t, zz = sys.zz) {
401
+ const a = new Float64Array(zz.length);
357
402
  const tmp = new Float64Array(64);
358
403
  for (let h = 0; h < sys.nGroups; h++) {
359
404
  const kc = sys.groupTerm[h];
@@ -365,7 +410,7 @@ function blocksOfA(sys, t) {
365
410
  const tr = t[kr];
366
411
  const base = sys.blockValueStart[b];
367
412
  if (ncr === 1 && ncc === 1) {
368
- a[base] = tr[0] * sys.zz[base] * tc[0];
413
+ a[base] = tr[0] * zz[base] * tc[0];
369
414
  }
370
415
  else {
371
416
  // tmp = Z'Z(g, h) T_h (ncr × ncc), then T_g' tmp
@@ -374,7 +419,7 @@ function blocksOfA(sys, t) {
374
419
  for (let r = 0; r < ncr; r++) {
375
420
  let sum = 0;
376
421
  for (let m = c; m < ncc; m++)
377
- sum += sys.zz[base + r + m * ncr] * tc[m + c * ncc];
422
+ sum += zz[base + r + m * ncr] * tc[m + c * ncc];
378
423
  work[r + c * ncr] = sum;
379
424
  }
380
425
  }
@@ -395,7 +440,7 @@ function blocksOfA(sys, t) {
395
440
  return a;
396
441
  }
397
442
  /** The values of the Cholesky factor L of A (A = L L', the pattern of the system), from the blocks of A */
398
- function factorise(sys, a) {
443
+ export function factorise(sys, a) {
399
444
  const { q, colStart, colRows, rowListStart, rowListCol, rowListPos } = sys;
400
445
  const l = new Float64Array(colRows.length);
401
446
  const work = new Float64Array(q);
@@ -464,7 +509,7 @@ export function solveLt(sys, l, v, offset = 0) {
464
509
  }
465
510
  }
466
511
  /** Solves L x = v in place, with L = R' and R the upper-triangular factor (column-major, k × k) */
467
- function forwardSolve(r, k, v) {
512
+ export function forwardSolve(r, k, v) {
468
513
  for (let i = 0; i < k; i++) {
469
514
  const ci = i * k;
470
515
  let sum = v[i];
@@ -474,7 +519,7 @@ function forwardSolve(r, k, v) {
474
519
  }
475
520
  }
476
521
  /** Solves R x = v in place, R upper triangular (column-major, k × k) */
477
- function backSolve(r, k, v) {
522
+ export function backSolve(r, k, v) {
478
523
  for (let i = k - 1; i >= 0; i--) {
479
524
  const xi = (v[i] /= r[i + i * k]);
480
525
  const ci = i * k;
@@ -549,26 +594,9 @@ export function plsState(structure, theta) {
549
594
  const { n, p, q } = sys;
550
595
  const t = blocksOf(sys, theta);
551
596
  const l = factorise(sys, blocksOfA(sys, t));
552
- // Z v (from the sparse Z) and Λ'Z' v
553
- const zTimes = (v) => {
554
- const out = new Float64Array(n);
555
- for (let i = 0; i < n; i++) {
556
- let sum = 0;
557
- for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
558
- sum += sys.rowValues[c] * v[sys.rowCols[c]];
559
- out[i] = sum;
560
- }
561
- return out;
562
- };
563
- const zTransposeTimes = (v) => {
564
- const zv = new Float64Array(q);
565
- for (let i = 0; i < n; i++) {
566
- const vi = v[i];
567
- for (let c = sys.rowStart[i]; c < sys.rowStart[i + 1]; c++)
568
- zv[sys.rowCols[c]] += sys.rowValues[c] * vi;
569
- }
570
- return zv;
571
- };
597
+ // Z v (from the sparse Z) and Z' v
598
+ const zTimesV = (v) => zTimes(sys, v);
599
+ const zTransposeTimesV = (v) => zTransposeTimes(sys, v);
572
600
  /** Solves A w = v in place */
573
601
  const solveA = (v) => {
574
602
  solveL(sys, l, v);
@@ -587,12 +615,12 @@ export function plsState(structure, theta) {
587
615
  solveLt(sys, l, w);
588
616
  const xk = Float64Array.from(structure.x, (row) => row[k]);
589
617
  const residualOf = () => {
590
- const fitted = zTimes(lambdaTimes(sys, t, w));
618
+ const fitted = zTimesV(lambdaTimes(sys, t, w));
591
619
  return xk.map((v, i) => v - fitted[i]);
592
620
  };
593
621
  let e = residualOf();
594
622
  for (let step = 0; step < REFINEMENT_STEPS; step++) {
595
- const g = lambdaTransposeTimes(sys, t, zTransposeTimes(e));
623
+ const g = lambdaTransposeTimes(sys, t, zTransposeTimesV(e));
596
624
  for (let i = 0; i < q; i++)
597
625
  g[i] -= w[i];
598
626
  solveA(g);
@@ -643,7 +671,7 @@ export function plsState(structure, theta) {
643
671
  };
644
672
  // the residual y − Xβ − ZΛu, from X and the sparse Z (not from the cross-products)
645
673
  const residual = (beta, bv) => {
646
- const zb = zTimes(bv);
674
+ const zb = zTimesV(bv);
647
675
  const res = new Float64Array(n);
648
676
  for (let i = 0; i < n; i++) {
649
677
  const xi = structure.x[i];
@@ -664,7 +692,7 @@ export function plsState(structure, theta) {
664
692
  let res = residual(betav, bv);
665
693
  for (let step = 0; step < REFINEMENT_STEPS; step++) {
666
694
  // the gradient of the penalised residual sum of squares: (Λ'Z'res − u, X'res)
667
- const du = lambdaTransposeTimes(sys, t, zTransposeTimes(res));
695
+ const du = lambdaTransposeTimes(sys, t, zTransposeTimesV(res));
668
696
  for (let i = 0; i < q; i++)
669
697
  du[i] -= uv[i];
670
698
  const db = new Float64Array(p);
@@ -910,10 +938,10 @@ function sparseGradient(structure, sys, t, l, theta, reml, { res, uv, prss, ws,
910
938
  * 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
939
  * its selected inverse `inv` (the layout of L's values) and Λ by its blocks `t` (see {@link sparseGradient}). Linear
912
940
  * 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.
941
+ * of the selected inverse and of the blocks. With `zz` (Z'WZ by blocks, glmer's gradient), Λ'Z'WZ in place of Λ'Z'Z.
914
942
  */
915
- export function levelTraceSums(sys, inv, t) {
916
- const { colStart, zz } = sys;
943
+ export function levelTraceSums(sys, inv, t, zz = sys.zz) {
944
+ const { colStart } = sys;
917
945
  const sums = sys.termNc.map((nc) => new Float64Array(nc * nc));
918
946
  let y = new Float64Array(16);
919
947
  let f = new Float64Array(16);