@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
@@ -0,0 +1,530 @@
1
+ // Predictions of mixed models fitted by lmer and glmer (lme4's predict.merMod): at the fit's rows or at new data, with
2
+ // all, some or none of the random-effects terms, the random part only, on the link or the response scale, with the
3
+ // standard errors from the conditional covariance of (b, β).
4
+ //
5
+ // Written for rStats.js (no ported code) from oracle/glmer-behaviour.md ("Prediction: glmerPredict and lmerPredict
6
+ // (stage 4)" and "rStats.js's choices", G14, G16, G17) and the notation of D. Bates, M. Mächler, B. Bolker, S. Walker
7
+ // (2015), "Fitting Linear Mixed-Effects Models Using lme4", Journal of Statistical Software 67(1).
8
+ //
9
+ // The prediction of a row is η = o + x'β̂ + Σ_t z_t' b̂(t, level) over the random-effects terms t selected, x the
10
+ // row of the fixed-effects model matrix built from the row as the fit built X (the fit's terms, contrasts, factor
11
+ // levels and dropped columns), z_t the row of the term's left-hand side model matrix and the level that of the row's
12
+ // grouping factor. The standard error (se.fit) is √(v'Cv) with v = (z, x), z the row's columns of the fit's Z, and
13
+ // C = σ² A K⁻¹ A', K = [Λ'Z'WZΛ + I, Λ'Z'WX; X'WZΛ, X'WX], A = diag(Λ, I) (W the Fisher weights at the conditional
14
+ // mode, 1 for lmer), computed from the sparse factor L of Λ'Z'WZΛ + I, C_X = L⁻¹Λ'Z'WX and R_X:
15
+ // v'Cv = σ² (‖c‖² + ‖R_X⁻ᵀ(x − C_X'c)‖²) with c = L⁻¹Λ'z.
16
+ import { potf2 } from "../linalg/chol.js";
17
+ import { checkDot, checkedDot } from "../linalg/dot.js";
18
+ import { levelText } from "../internal/levels.js";
19
+ import { Warnings, reported } from "../internal/warnings.js";
20
+ import { deparseFormula, parseFormula, splitBarTerms } from "./formula.js";
21
+ import { glmerInternals } from "./glmer.js";
22
+ import { workingWeight } from "./glmerFamily.js";
23
+ import { checkLmerOptions, lmerInternals, logicalOption } from "./lmer.js";
24
+ import { blocksOf, blocksOfA, factorise, forwardSolve, lambdaTransposeTimes, plsState, solveL, sparseSystemOf, weightedCrossProduct, zTransposeTimes, } from "./mixedDeviance.js";
25
+ import { expandRandomTerms, fixedPartDesign } from "./mixedStructure.js";
26
+ import { design } from "./modelMatrix.js";
27
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
28
+ import { checkOptions } from "../internal/checkOptions.js";
29
+ const GLMER_PREDICT_KEYS = ["newoffset", "newdata", "reForm", "allowNewLevels", "randomOnly", "type", "seFit"];
30
+ const LMER_PREDICT_KEYS = ["newdata", "reForm", "allowNewLevels", "randomOnly", "type", "seFit"];
31
+ const PREDICT_UNSUPPORTED = ["re.form", "allow.new.levels", "random.only", "se.fit", "newparams", "terms", "na.action", "naAction"];
32
+ const SE_WARNING = "se.fit computation uses an approximation to estimate the sampling distribution of the parameters";
33
+ /** A column of a data frame, or undefined */
34
+ function columnOf(data, name) {
35
+ return Object.hasOwn(data, name) ? data[name] : undefined;
36
+ }
37
+ /** A value as the label of a factor level (as the model frame forms them), or null if missing */
38
+ function labelOf(x) {
39
+ if (x === null || (typeof x === "number" && Number.isNaN(x)))
40
+ return null;
41
+ return typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : levelText(x);
42
+ }
43
+ /** R's type name of a value, for the message of a numeric variable given other values */
44
+ function rType(x) {
45
+ return typeof x === "string" ? "character" : typeof x === "boolean" ? "logical" : typeof x;
46
+ }
47
+ /** The common prediction of lmer and glmer fits (see the header) */
48
+ function predictModel(m, options) {
49
+ const s = m.structure;
50
+ // the options' values, in the order of the table of options
51
+ const { newdata } = options;
52
+ if (newdata !== undefined && (typeof newdata !== "object" || newdata === null || Array.isArray(newdata))) {
53
+ throw new TypeError("newdata must be a data frame (an object of columns)");
54
+ }
55
+ const reForm = options.reForm;
56
+ if (reForm !== undefined && reForm !== null && reForm !== false && typeof reForm !== "string") {
57
+ throw new TypeError("reForm must be null, false or a formula string such as \"~ (1 | g)\"");
58
+ }
59
+ const allowNewLevels = logicalOption(options.allowNewLevels, false);
60
+ const randomOnly = logicalOption(options.randomOnly, false);
61
+ const type = options.type ?? "link";
62
+ if (type !== "link" && type !== "response")
63
+ throw new RangeError(`invalid 'type': ${String(type)}`);
64
+ const seFit = logicalOption(options.seFit, false);
65
+ // newoffset (glmer only: lmer's options do not have it)
66
+ let newoffset;
67
+ if (options.newoffset !== undefined) {
68
+ const given = options.newoffset;
69
+ if (!Array.isArray(given) && !(given instanceof Float64Array))
70
+ throw new TypeError("newoffset must be an array of numbers");
71
+ newoffset = Array.from(given, (v) => {
72
+ if (typeof v !== "number")
73
+ throw new TypeError("newoffset must be an array of numbers");
74
+ return v;
75
+ });
76
+ if (newdata === undefined)
77
+ throw new RangeError("newoffset needs newdata (without it the fit's offset is used)");
78
+ if (m.offsetColumn !== undefined) {
79
+ throw new RangeError(`newoffset cannot be given: the fit's offset is the column '${m.offsetColumn}', read from newdata`);
80
+ }
81
+ if (newoffset.length !== (Object.values(newdata)[0]?.length ?? 0))
82
+ throw new RangeError("newoffset must have one value per row of newdata");
83
+ }
84
+ // the fit's data at its rows, from which every model matrix of the prediction takes its terms and levels
85
+ const fitRows = s.rows;
86
+ const fitData = Object.fromEntries(Object.entries(m.snapshot).map(([k, col]) => [k, col instanceof Float64Array ? Float64Array.from(fitRows, (i) => col[i]) : fitRows.map((i) => col[i])]));
87
+ const fixed = fixedPartDesign(m.formula, fitData, m.structureOptions, m.generalised);
88
+ // the random-effects terms selected (all with re.form NULL; R's errors for re.form before the data is looked at)
89
+ const selected = selectTerms(m, fixed.parsed, fixed.bars, fitData, reForm);
90
+ // the rows: newdata's, or the fit's (their data and offset)
91
+ const data = newdata ?? fitData;
92
+ const nRows = newdata === undefined ? fitRows.length : (Object.values(newdata)[0]?.length ?? 0);
93
+ const fetch = (name) => {
94
+ const col = columnOf(data, name);
95
+ if (col === undefined)
96
+ throw new RangeError(`object '${name}' not found`);
97
+ if (!Array.isArray(col) && !(col instanceof Float64Array))
98
+ throw new TypeError(`column '${name}' must be an array`);
99
+ if (col.length !== nRows)
100
+ throw new RangeError(`variable lengths differ (found for '${name}')`);
101
+ return col;
102
+ };
103
+ /** The values of a column as the frame variable `fv` of the fit (a factor's codes in the fit's levels; -1 missing) */
104
+ const variableOf = (name, fv) => {
105
+ const col = fetch(name);
106
+ if (fv.kind === "numeric") {
107
+ const values = Array.from(col, (x) => {
108
+ if (x === null)
109
+ return NaN;
110
+ // (R's message of predict for lm, which checks the classes of newdata's variables)
111
+ if (typeof x !== "number")
112
+ throw new TypeError(`variable '${name}' was fitted with type "numeric" but type "${rType(x)}" was supplied`);
113
+ return x;
114
+ });
115
+ return { kind: "numeric", values };
116
+ }
117
+ const index = new Map(fv.levels.map((l, k) => [l, k]));
118
+ const codes = Array.from(col, (x) => {
119
+ const label = labelOf(x);
120
+ if (label === null)
121
+ return -1;
122
+ const k = index.get(label);
123
+ // (R: lme4 adds the value as a level and fails with "non-conformable arguments"; here the message of R's
124
+ // predict for lm. To differences-from-r)
125
+ if (k === undefined)
126
+ throw new RangeError(`factor ${name} has new level ${label}`);
127
+ return k;
128
+ });
129
+ return { kind: "factor", levels: fv.levels, codes };
130
+ };
131
+ /** The variables of a design's terms with columns, from the data (each column checked first, then converted) */
132
+ const variablesOf = (d) => {
133
+ const usedVariables = new Set();
134
+ d.terms.terms.forEach((t, j) => {
135
+ if (j !== d.terms.responseTerm)
136
+ for (const v of t)
137
+ usedVariables.add(v);
138
+ });
139
+ const order = [...usedVariables].sort((a, b) => a - b);
140
+ for (const v of order)
141
+ fetch(d.terms.variables[v]);
142
+ const out = d.frame.variables.map(() => undefined);
143
+ for (const v of order)
144
+ out[v] = variableOf(d.terms.variables[v], d.frame.variables[v]);
145
+ return out;
146
+ };
147
+ // the fixed part: the rows of X (the fit's dropped columns left out)
148
+ const fd = fixed.fixedDesign;
149
+ const xFull = fd.rowsOf(variablesOf(fd), nRows);
150
+ const keep = s.xColNames.map((name) => fd.colNames.indexOf(name));
151
+ const x = xFull.map((row) => keep.map((j) => row[j]));
152
+ // the offset (glmer): the fit's (no newdata), a column of newdata (an offset given as a column name), or newoffset
153
+ let offset = new Array(nRows).fill(0);
154
+ if (newdata === undefined)
155
+ offset = m.fitOffset ?? offset;
156
+ else if (m.offsetColumn !== undefined) {
157
+ const name = m.offsetColumn;
158
+ offset = Array.from(fetch(name), (v) => {
159
+ if (v === null)
160
+ return NaN;
161
+ if (typeof v !== "number")
162
+ throw new TypeError(`the offset column '${name}' must be numeric`);
163
+ return v;
164
+ });
165
+ }
166
+ else if (newoffset !== undefined)
167
+ offset = newoffset;
168
+ // the random part: for each selected term, the rows of its left-hand side and the level of each row; the grouping
169
+ // columns first, then the covariates
170
+ for (const t of selected)
171
+ for (const v of t.groupVariables)
172
+ fetch(v);
173
+ const lhsDesigns = selected.map((t) => design({ response: undefined, rhs: t.lhs }, fitData, fixed.frameOptions, t.lhs));
174
+ const zRows = lhsDesigns.map((d) => d.rowsOf(variablesOf(d), nRows));
175
+ /** For each selected term, the level of each row (−1 a missing grouping value, −2 a new level) */
176
+ const missing = selected.map((t) => {
177
+ const cols = t.groupVariables.map((v) => fetch(v));
178
+ return Array.from({ length: nRows }, (_, i) => cols.some((c) => labelOf(c[i]) === null));
179
+ });
180
+ if (!allowNewLevels && missing.some((rows) => rows.some(Boolean))) {
181
+ throw new RangeError("NAs are not allowed in prediction data for grouping variables unless allow.new.levels is TRUE");
182
+ }
183
+ const levels = selected.map((t, k) => {
184
+ const g = s.groups[t.group];
185
+ const index = new Map(g.levels.map((l, j) => [l, j]));
186
+ const cols = t.groupVariables.map((v) => fetch(v));
187
+ const newLevels = [];
188
+ const codes = Array.from({ length: nRows }, (_, i) => {
189
+ if (missing[k][i])
190
+ return -1;
191
+ const label = cols.map((c) => labelOf(c[i])).join(":");
192
+ const j = index.get(label);
193
+ if (j !== undefined)
194
+ return j;
195
+ if (!newLevels.includes(label))
196
+ newLevels.push(label);
197
+ return -2;
198
+ });
199
+ return { codes, newLevels };
200
+ });
201
+ if (!allowNewLevels) {
202
+ const first = levels.find((l) => l.newLevels.length > 0);
203
+ if (first !== undefined)
204
+ throw new RangeError(`new levels detected in newdata: ${shortList(first.newLevels.join(", "))}`);
205
+ }
206
+ // η, and the columns of Z of each row (for the standard errors)
207
+ const terms = s.terms;
208
+ const random = new Array(nRows).fill(0);
209
+ const zEntries = Array.from({ length: nRows }, () => []);
210
+ selected.forEach((t, k) => {
211
+ const codes = levels[k].codes;
212
+ const z = zRows[k];
213
+ for (let i = 0; i < nRows; i++) {
214
+ const level = codes[i];
215
+ // (a new level or a missing grouping value with allowNewLevels: the term adds 0)
216
+ if (level < 0)
217
+ continue;
218
+ t.columns.forEach(({ term, column }, j) => {
219
+ const st = terms[term];
220
+ const col = st.zOffset + level * st.columns.length + column;
221
+ const value = z[i][j];
222
+ random[i] += value * m.b[col];
223
+ zEntries[i].push({ col, value });
224
+ });
225
+ }
226
+ });
227
+ const p = s.xColNames.length;
228
+ const fixedPart = x.map((row, i) => (randomOnly ? 0 : offset[i] + row.reduce((sum, v, k) => sum + v * m.beta[k], 0)));
229
+ let eta = fixedPart.map((f, i) => {
230
+ const plain = f + random[i];
231
+ if (!checkDot(plain, 0))
232
+ return plain;
233
+ // products of finite values may overflow while η is in range (bx x + bz z with x = 1e308 and z cancelling it):
234
+ // the exact inner product of (offset, x, z) and (1, β, b), as predict for lm and glm (#174, #182, #195); also
235
+ // where products underflow while the sum is tiny (#395)
236
+ const factors = randomOnly ? [] : [1, ...x[i]];
237
+ const coefficients = randomOnly ? [] : [offset[i], ...m.beta];
238
+ for (const { col, value } of zEntries[i]) {
239
+ factors.push(value);
240
+ coefficients.push(m.b[col]);
241
+ }
242
+ return checkedDot(factors, coefficients, plain);
243
+ });
244
+ // no newdata, all terms, not random.only: the fit's own linear predictor and means (lme4's clamped inverse link)
245
+ const fitted = newdata === undefined && (reForm === undefined || reForm === null) && !randomOnly ? m.fitted : undefined;
246
+ if (fitted !== undefined)
247
+ eta = [...fitted.eta];
248
+ const warnings = new Warnings();
249
+ let se;
250
+ if (seFit) {
251
+ if (m.generalised)
252
+ warnings.add(SE_WARNING);
253
+ const { sys, t, l, cx, rx } = m.seFactors();
254
+ const q = sys.q;
255
+ se = x.map((row, i) => {
256
+ const zv = new Float64Array(q);
257
+ for (const { col, value } of zEntries[i])
258
+ zv[col] += value;
259
+ const c = lambdaTransposeTimes(sys, t, zv);
260
+ solveL(sys, l, c);
261
+ let ss = 0;
262
+ for (let j = 0; j < q; j++)
263
+ ss += c[j] * c[j];
264
+ const d = new Float64Array(p);
265
+ for (let k = 0; k < p; k++) {
266
+ let sum = randomOnly ? 0 : row[k];
267
+ for (let j = 0; j < q; j++)
268
+ sum -= cx[j + k * q] * c[j];
269
+ d[k] = sum;
270
+ }
271
+ forwardSolve(rx, p, d);
272
+ for (let k = 0; k < p; k++)
273
+ ss += d[k] * d[k];
274
+ if (!(ss >= 2 ** -1022 && ss < Infinity)) {
275
+ // the squares overflowed (newdata 1e200: Infinity, R too) or underflowed: the norm divided by its largest
276
+ // element, σ applied before that element is multiplied back (σ 1e-200 times a norm 1e200), as glmPredict
277
+ // (#175, #196)
278
+ let top = 0;
279
+ for (const v of c)
280
+ top = Math.max(top, Math.abs(v));
281
+ for (const v of d)
282
+ top = Math.max(top, Math.abs(v));
283
+ if (top > 0 && Number.isFinite(top)) {
284
+ let scaled = 0;
285
+ for (const v of c)
286
+ scaled += (v / top) ** 2;
287
+ for (const v of d)
288
+ scaled += (v / top) ** 2;
289
+ return m.sigma * Math.sqrt(scaled) * top;
290
+ }
291
+ }
292
+ return m.sigma * Math.sqrt(ss);
293
+ });
294
+ }
295
+ let values = eta;
296
+ if (m.generalised && type === "response") {
297
+ const fam = m.family.glm;
298
+ // R's family linkinv and mu.eta (glm's), not lme4's clamped ones, except for the fit's own means
299
+ values = fitted !== undefined ? [...fitted.mu] : eta.map((e) => fam.linkinv(e));
300
+ if (se !== undefined)
301
+ se = se.map((v, i) => v * Math.abs(fam.muEta(eta[i])));
302
+ }
303
+ const result = { fit: values };
304
+ if (se !== undefined)
305
+ result.seFit = se;
306
+ if (warnings.list.length > 0)
307
+ result.warnings = warnings.list;
308
+ return reported(m.fn, result);
309
+ }
310
+ /**
311
+ * lme4's list of new levels: cut to its first 60 characters with everything from the last comma replaced by `, ...`
312
+ * when longer (no `, ...` if those 60 characters have no comma)
313
+ */
314
+ function shortList(text) {
315
+ if (text.length <= 60)
316
+ return text;
317
+ const cut = text.slice(0, 60);
318
+ const comma = cut.lastIndexOf(",");
319
+ return comma < 0 ? cut : `${cut.slice(0, comma)}, ...`;
320
+ }
321
+ /** The random-effects terms selected by reForm (see {@link LmerPredictOptions.reForm}), with R's errors */
322
+ function selectTerms(m, parsed, bars, fitData, reForm) {
323
+ const s = m.structure;
324
+ const columns = Object.keys(m.snapshot);
325
+ if (reForm === false)
326
+ return [];
327
+ if (reForm === undefined || reForm === null) {
328
+ // the fit's terms, each with its own columns (matched to the expansion of the formula by their labels)
329
+ const { expanded } = expandRandomTerms(parsed, columns, bars);
330
+ return s.terms.map((term, k) => {
331
+ const e = expanded.find((x) => `${deparseFormula(x.lhs)} | ${x.groupVariables.join(":")}` === term.label);
332
+ return { lhs: e.lhs, groupVariables: e.groupVariables, group: term.group, columns: term.columns.map((_, j) => ({ term: k, column: j })) };
333
+ });
334
+ }
335
+ const re = parseFormula(reForm, false, true);
336
+ const split = splitBarTerms(re.rhs);
337
+ if (split.bars.length === 0) {
338
+ if (deparseFormula(re.rhs) === "0")
339
+ return [];
340
+ throw new Error("No random effects terms specified in formula");
341
+ }
342
+ const { expanded } = expandRandomTerms(re, columns, split.bars);
343
+ const groupOf = (e) => s.groups.findIndex((g) => g.name === e.groupVariables.join(":"));
344
+ if (expanded.some((e) => groupOf(e) < 0))
345
+ throw new RangeError("grouping factors specified in re.form that were not present in original model");
346
+ // the columns of each term (named as the fit names them; a variable that is not in the data as a numeric one)
347
+ const missingNames = [];
348
+ const out = expanded.map((e) => {
349
+ const group = groupOf(e);
350
+ const lhsParsed = { response: undefined, rhs: e.lhs };
351
+ const absent = termsVariables(lhsParsed, columns).filter((v) => !Object.hasOwn(fitData, v));
352
+ const namesData = absent.length === 0 ? fitData : { ...fitData, ...Object.fromEntries(absent.map((v) => [v, new Array(s.rows.length).fill(0)])) };
353
+ const names = design(lhsParsed, namesData, { ...(m.structureOptions.levels === undefined ? {} : { levels: m.structureOptions.levels }), dropUnusedLevels: true }, e.lhs).colNames;
354
+ const cols = names.map((name) => {
355
+ const term = s.terms.findIndex((t) => t.group === group && t.columns.includes(name));
356
+ if (term < 0) {
357
+ if (!missingNames.includes(name))
358
+ missingNames.push(name);
359
+ return { term: -1, column: -1 };
360
+ }
361
+ return { term, column: s.terms[term].columns.indexOf(name) };
362
+ });
363
+ return { lhs: e.lhs, groupVariables: e.groupVariables, group, columns: cols };
364
+ });
365
+ if (missingNames.length > 0)
366
+ throw new RangeError(`random effects specified in re.form that were not present in original model ${missingNames.join(", ")}`);
367
+ return out;
368
+ }
369
+ /** The variables of a one-sided formula's right-hand side */
370
+ function termsVariables(parsed, columns) {
371
+ const vars = [];
372
+ const collect = (n) => {
373
+ if (n.type === "var") {
374
+ if (!vars.includes(n.name))
375
+ vars.push(n.name);
376
+ }
377
+ else if (n.type === "binary") {
378
+ collect(n.left);
379
+ collect(n.right);
380
+ }
381
+ else if (n.type === "unary" || n.type === "paren" || n.type === "Error")
382
+ collect(n.arg);
383
+ else if (n.type === "dot")
384
+ for (const c of columns)
385
+ if (!vars.includes(c))
386
+ vars.push(c);
387
+ };
388
+ collect(parsed.rhs);
389
+ return vars;
390
+ }
391
+ /**
392
+ * Predictions of a linear mixed model fitted by {@link lmer}, at the rows of the fit or at new data, with all, some
393
+ * or none of the random-effects terms, optionally with their standard errors. Equivalent to `lme4::predict()` in R.
394
+ *
395
+ * The prediction of a row is x'β̂ + Σ z'b̂ over the selected terms, x built from the row as the fit built its
396
+ * fixed-effects matrix (its terms, contrasts, factor levels and dropped columns) and b̂ the conditional mode of the
397
+ * row's level. A missing value in a variable gives NaN for its row; a factor level of the fixed part that the fit did
398
+ * not have is the RangeError `factor <name> has new level <value>` (R: `non-conformable arguments`). The standard
399
+ * errors are those of the conditional covariance σ² A K⁻¹ A' of (b, β) at θ̂ (Henderson's equations), computed
400
+ * correctly also where lme4's are wrong (crossed grouping factors, some `reForm` subsets).
401
+ *
402
+ * @param fit The object returned by {@link lmer} (not a copy of it).
403
+ * @param options `newdata`, `reForm`, `allowNewLevels`, `randomOnly`, `type` and `seFit` (see {@link LmerPredictOptions}).
404
+ *
405
+ * @example
406
+ * ```ts
407
+ * const data = {
408
+ * y: [9.8, 10.4, 10.1, 12.3, 12.9, 12.0, 8.1, 7.6, 8.4],
409
+ * g: ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
410
+ * };
411
+ * const fit = lmer("y ~ 1 + (1 | g)", data);
412
+ * lmerPredict(fit, { newdata: { g: ["a", "c"] } }).fit; // [10.101, 8.0565]
413
+ * lmerPredict(fit, { reForm: false }).fit[0]; // 10.178
414
+ * ```
415
+ *
416
+ * @category Mixed models
417
+ */
418
+ export function lmerPredict(fit, options) {
419
+ checkLmerOptions("lmerPredict", options, PREDICT_UNSUPPORTED);
420
+ checkOptions(options, LMER_PREDICT_KEYS, "lmerPredict"); // generated: option-keys.mjs
421
+ const internals = lmerInternals(fit);
422
+ const s = internals.structure;
423
+ const structureOptions = {};
424
+ if (internals.options.contrasts !== undefined)
425
+ structureOptions.contrasts = internals.options.contrasts;
426
+ if (internals.options.levels !== undefined)
427
+ structureOptions.levels = internals.options.levels;
428
+ return predictModel({
429
+ fn: "lmerPredict",
430
+ formula: fit.formula,
431
+ generalised: false,
432
+ snapshot: internals.snapshot,
433
+ structureOptions,
434
+ structure: s,
435
+ beta: internals.fixef,
436
+ b: internals.b,
437
+ sigma: internals.sigma,
438
+ seFactors: () => {
439
+ // (L, C_X and R_X do not depend on the response)
440
+ const { sys, t, l, cx, rx } = plsState(s, internals.theta);
441
+ return { sys, t, l, cx, rx };
442
+ },
443
+ }, options ?? {});
444
+ }
445
+ /**
446
+ * Predictions of a generalized linear mixed model fitted by {@link glmer}, at the rows of the fit or at new data, with
447
+ * all, some or none of the random-effects terms, on the link or the response scale, optionally with their standard
448
+ * errors. Equivalent to `lme4::predict()` in R.
449
+ *
450
+ * The rules are those of {@link lmerPredict}, with the offset: without `newdata` the fit's; with it, an offset given
451
+ * to glmer as a column name is read from that column of `newdata`, one given as an array is replaced by `newoffset`
452
+ * (default 0: R ignores glmer's `offset` argument in prediction). `type: "response"` applies R's inverse link (at the
453
+ * fit's rows with all terms, the fitted means). The standard errors use the Fisher weights at the conditional mode,
454
+ * with R's warning that they are an approximation; on the response scale they are multiplied by |dμ/dη|.
455
+ *
456
+ * @param fit The object returned by {@link glmer} (not a copy of it).
457
+ * @param options `newdata`, `reForm`, `allowNewLevels`, `randomOnly`, `type`, `seFit` and `newoffset` (see
458
+ * {@link GlmerPredictOptions}).
459
+ *
460
+ * @example
461
+ * ```ts
462
+ * const data = {
463
+ * y: [2, 3, 6, 7, 8, 1, 0, 3, 2, 5, 4, 6, 9, 8, 13, 0, 2, 1, 4, 3],
464
+ * x: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
465
+ * g: ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d"],
466
+ * };
467
+ * const fit = glmer("y ~ x + (1 | g)", data, { family: "poisson" });
468
+ * glmerPredict(fit, { newdata: { x: [6], g: ["c"] }, type: "response" }).fit; // [17.970]
469
+ * glmerPredict(fit, { newdata: { x: [6], g: ["c"] }, reForm: false }).fit; // [2.1967]
470
+ * ```
471
+ *
472
+ * @category Mixed models
473
+ */
474
+ export function glmerPredict(fit, options) {
475
+ checkLmerOptions("glmerPredict", options, PREDICT_UNSUPPORTED);
476
+ checkOptions(options, GLMER_PREDICT_KEYS, "glmerPredict"); // generated: option-keys.mjs
477
+ const internals = glmerInternals(fit);
478
+ const s = internals.structure;
479
+ const structureOptions = {};
480
+ if (internals.options.contrasts !== undefined)
481
+ structureOptions.contrasts = internals.options.contrasts;
482
+ if (internals.options.levels !== undefined)
483
+ structureOptions.levels = internals.options.levels;
484
+ const givenOffset = internals.options.offset;
485
+ return predictModel({
486
+ fn: "glmerPredict",
487
+ formula: fit.formula,
488
+ generalised: true,
489
+ snapshot: internals.snapshot,
490
+ structureOptions,
491
+ structure: s,
492
+ beta: internals.beta,
493
+ b: internals.b,
494
+ sigma: internals.sigma,
495
+ family: s.family,
496
+ ...(typeof givenOffset === "string" ? { offsetColumn: givenOffset } : {}),
497
+ fitOffset: s.offset,
498
+ fitted: { eta: internals.eta, mu: internals.mu },
499
+ seFactors: () => {
500
+ // L of Λ'Z'WZΛ + I and C_X = L⁻¹Λ'Z'WX with the Fisher weights at the mode, R_X from R_X'R_X (that of vcov
501
+ // from RX)
502
+ const sys = sparseSystemOf(s);
503
+ const { n, p, q } = sys;
504
+ const t = blocksOf(sys, internals.theta);
505
+ const fam = s.family;
506
+ const ww = new Float64Array(n);
507
+ for (let i = 0; i < n; i++) {
508
+ const wi = s.weights[i];
509
+ if (wi === 0)
510
+ continue;
511
+ ww[i] = workingWeight(fam, wi, fam.muEta(internals.eta[i]), internals.mu[i]);
512
+ }
513
+ const l = factorise(sys, blocksOfA(sys, t, weightedCrossProduct(sys, s, ww)));
514
+ const cx = new Float64Array(q * p);
515
+ for (let k = 0; k < p; k++) {
516
+ const col = lambdaTransposeTimes(sys, t, zTransposeTimes(sys, Float64Array.from(s.x, (row, i) => ww[i] * row[k])));
517
+ solveL(sys, l, col);
518
+ cx.set(col, k * q);
519
+ }
520
+ const rx = new Float64Array(p * p);
521
+ for (let j = 0; j < p; j++)
522
+ for (let i = 0; i < p; i++)
523
+ rx[i + j * p] = internals.rxtrx[i][j];
524
+ // (R_X'R_X not positive definite: the standard errors are NaN)
525
+ if (p > 0 && potf2({ nrow: p, ncol: p, data: rx }) > 0)
526
+ rx.fill(NaN);
527
+ return { sys, t, l, cx, rx };
528
+ },
529
+ }, options ?? {});
530
+ }
@@ -1,5 +1,6 @@
1
- import { type DataFrame } from "./modelFrame.js";
2
- import { type DesignContrast, type ModelMatrixOptions } from "./modelMatrix.js";
1
+ import { type FormulaNode, type ParsedFormula } from "./formula.js";
2
+ import { type DataFrame, type FrameVariable } from "./modelFrame.js";
3
+ import { type Design, type DesignContrast, type ModelMatrixOptions } from "./modelMatrix.js";
3
4
  /** A random-effects term of a mixed model, after the expansion of its grouping expression and of `||`. */
4
5
  export interface RandomEffectsTerm {
5
6
  /** The term as R deparses it, such as `"1 | g"`, `"0 + x | b:a"`. */
@@ -47,6 +48,10 @@ export interface MixedModelStructure {
47
48
  xColNames: string[];
48
49
  /** The fixed-effects model matrix X (array of rows). */
49
50
  x: number[][];
51
+ /** The term of each column of X (0 for the intercept, k for the k-th of `xTermLabels`), aliased columns dropped. */
52
+ xAssign: number[];
53
+ /** The labels of the terms of the fixed-effects part, in the formula's order (`"x"`, `"f"`, `"x:f"`). */
54
+ xTermLabels: string[];
50
55
  /** The random-effects terms, in their final order. */
51
56
  terms: RandomEffectsTerm[];
52
57
  /** The distinct grouping factors, in order of first use by the terms. */
@@ -67,11 +72,64 @@ export interface MixedModelStructure {
67
72
  messages: string[];
68
73
  /** R's warnings (predictors on very different scales). */
69
74
  warnings: string[];
75
+ /**
76
+ * The response variables of the model frame (rows kept), for a generalised model only: one, or the two columns of
77
+ * `cbind(a, b)`. `y` is then the first one's values if it is numeric, zeros otherwise.
78
+ */
79
+ response?: FrameVariable[];
70
80
  }
71
81
  /** Options of {@link mixedModelStructure}: those of the fixed-effects model matrix (contr.poly accepted too). */
72
82
  export type MixedModelStructureOptions = Omit<ModelMatrixOptions, "contrasts"> & {
73
83
  contrasts?: Record<string, DesignContrast>;
74
84
  };
85
+ /** The fixed-effects part of a mixed model's formula on its data (see {@link fixedPartDesign}) */
86
+ export interface FixedPartDesign {
87
+ /** The parsed formula */
88
+ parsed: ParsedFormula;
89
+ /** Its random-effects terms as written */
90
+ bars: Extract<FormulaNode, {
91
+ type: "bar";
92
+ }>[];
93
+ /** The model matrix of the fixed-effects part, on the model frame of every variable of the formula */
94
+ fixedDesign: Design;
95
+ /** The variables of that model frame, in its order (those of the fixed part first) */
96
+ variables: string[];
97
+ /** The options of the model frame of every model matrix of the structure */
98
+ frameOptions: {
99
+ levels?: Record<string, readonly string[]>;
100
+ dropUnusedLevels: true;
101
+ };
102
+ /** The option of a generalised model's response (any type) */
103
+ responseOptions: {
104
+ anyResponse?: true;
105
+ };
106
+ }
107
+ /**
108
+ * The fixed-effects part of a mixed model (internal, also for prediction): the formula without the random-effects
109
+ * terms, `response ~ fixed part`, as lm codes it (the order of its variables names the interaction columns); its model
110
+ * frame has the variables of the whole formula too, so that every model matrix of the structure uses the same rows.
111
+ */
112
+ export declare function fixedPartDesign(formula: string, data: DataFrame, options?: MixedModelStructureOptions, generalised?: boolean): FixedPartDesign;
113
+ /** A random-effects term after the expansion of `||` and of its grouping expression (internal, also for prediction) */
114
+ export interface ExpandedRandomTerm {
115
+ /** The left-hand side */
116
+ lhs: FormulaNode;
117
+ /** The index of its bar term in the formula */
118
+ bar: number;
119
+ /** The variables of the grouping factor, in the order of its name */
120
+ groupVariables: string[];
121
+ }
122
+ /**
123
+ * The random-effects terms `bars` of a formula expanded (internal): `(lhs || group)` split into one term per term of
124
+ * lhs, then each term by the grouping factors of its expression; `noColumns` is the first bar term (in the formula's
125
+ * order) that `||` leaves without columns.
126
+ */
127
+ export declare function expandRandomTerms(parsed: ParsedFormula, columns: readonly string[], bars: readonly Extract<FormulaNode, {
128
+ type: "bar";
129
+ }>[]): {
130
+ expanded: ExpandedRandomTerm[];
131
+ noColumns: number | undefined;
132
+ };
75
133
  /**
76
134
  * The structure of a linear mixed model `response ~ fixed part + (lhs | group) + ...`: the model frame, X, Z, the
77
135
  * layout of Λ_θ, the initial θ and its lower bounds, with lme4's checks, errors, messages and warnings
@@ -80,5 +138,6 @@ export type MixedModelStructureOptions = Omit<ModelMatrixOptions, "contrasts"> &
80
138
  * @param formula A formula such as `"y ~ x + (x | g)"`, `"y ~ (1 | a/b)"` or `"y ~ (x || g)"`.
81
139
  * @param data The data frame: an object of columns.
82
140
  * @param options The contrasts (fixed-effects part only) and the level order of factors.
141
+ * @param generalised The structure of a generalised model (glmer): its checks, a response of any type or `cbind(a, b)`.
83
142
  */
84
- export declare function mixedModelStructure(formula: string, data: DataFrame, options?: MixedModelStructureOptions): MixedModelStructure;
143
+ export declare function mixedModelStructure(formula: string, data: DataFrame, options?: MixedModelStructureOptions, generalised?: boolean): MixedModelStructure;