@numero-uno-jpn/rstats 1.5.0 → 1.6.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 (51) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.ja.md +8 -3
  3. package/README.md +8 -3
  4. package/dist/chunks/{chunk-CX4XK7WC.js → chunk-2I7Z7L5J.js} +2 -2
  5. package/dist/chunks/{chunk-73QCE2CI.js → chunk-2TVHT4PF.js} +2 -2
  6. package/dist/chunks/{chunk-2MYUAEYE.js → chunk-3PCHPKBD.js} +2 -2
  7. package/dist/chunks/{chunk-WBEYJ5W5.js → chunk-55XSRONZ.js} +2 -2
  8. package/dist/chunks/{chunk-MXOGMN4P.js → chunk-5AITXV3T.js} +2 -2
  9. package/dist/chunks/{chunk-AIXJAVDS.js → chunk-7ZNFRZO4.js} +2 -2
  10. package/dist/chunks/{chunk-L7PDJNJ3.js → chunk-ABSUQPOG.js} +2 -2
  11. package/dist/chunks/{chunk-UJM7AJII.js → chunk-AHFMBHZW.js} +1 -1
  12. package/dist/chunks/chunk-BJTGQ52J.js +2 -0
  13. package/dist/chunks/{chunk-2IYY74LX.js → chunk-BMEO5X5F.js} +2 -2
  14. package/dist/chunks/chunk-F7G74UNI.js +3 -0
  15. package/dist/chunks/{chunk-MJV5G7FG.js → chunk-FLITCXLY.js} +2 -2
  16. package/dist/chunks/{chunk-DYCWYHYV.js → chunk-KAAUNR3G.js} +1 -1
  17. package/dist/chunks/chunk-KND2BFD5.js +2 -0
  18. package/dist/chunks/{chunk-JBJTXMRJ.js → chunk-N2PNW4HR.js} +2 -2
  19. package/dist/chunks/{chunk-YK2EJU6T.js → chunk-NVIJXWS6.js} +2 -2
  20. package/dist/chunks/{chunk-TP4PRPVQ.js → chunk-O5CMNUJL.js} +2 -2
  21. package/dist/chunks/{chunk-GDMNF4P3.js → chunk-OZLDZOOA.js} +1 -1
  22. package/dist/chunks/chunk-RSTU6CX7.js +2 -0
  23. package/dist/chunks/{chunk-BJOZZ5J6.js → chunk-SFZF44G6.js} +2 -2
  24. package/dist/chunks/{chunk-Q32WODL4.js → chunk-TPBVVP32.js} +2 -2
  25. package/dist/chunks/{chunk-FCF6FBJP.js → chunk-WAMHZ47G.js} +2 -2
  26. package/dist/chunks/chunk-XNWSQVXS.js +2 -0
  27. package/dist/chunks/{chunk-VAWD57ZB.js → chunk-Z2XN4NN7.js} +2 -2
  28. package/dist/chunks/{chunk-MYRCEQ2R.js → chunk-ZL7EAPO5.js} +1 -1
  29. package/dist/descriptive.js +2 -2
  30. package/dist/distributions.js +2 -2
  31. package/dist/entries/mixed.d.ts +2 -0
  32. package/dist/entries/mixed.js +2 -0
  33. package/dist/linalg.js +2 -2
  34. package/dist/mixed.js +5 -5
  35. package/dist/models/mixedConfint.d.ts +42 -0
  36. package/dist/models/mixedConfint.js +573 -0
  37. package/dist/models/mixedSimulate.d.ts +36 -0
  38. package/dist/models/mixedSimulate.js +232 -0
  39. package/dist/numerics.js +2 -2
  40. package/dist/rstats.js +1 -1
  41. package/dist/special.js +2 -2
  42. package/dist/tests.js +2 -2
  43. package/llms.txt +3 -1
  44. package/package.json +1 -1
  45. package/dist/chunks/chunk-3BEE6BHN.js +0 -2
  46. package/dist/chunks/chunk-E5M5RAVB.js +0 -2
  47. package/dist/chunks/chunk-F2MURX2Y.js +0 -2
  48. package/dist/chunks/chunk-F7SQG6BV.js +0 -2
  49. package/dist/chunks/chunk-FMLFYM7N.js +0 -2
  50. package/dist/chunks/chunk-LVB22NKV.js +0 -2
  51. package/dist/chunks/chunk-RZBX6VYO.js +0 -3
@@ -0,0 +1,573 @@
1
+ // Wald and likelihood-profile confidence intervals for mixed-model fits.
2
+ import { qnorm } from "../distributions/normal.js";
3
+ import { reportWarnings } from "../internal/warnings.js";
4
+ import { glmerInternals } from "./glmer.js";
5
+ import { glmerDeviance } from "./glmerDeviance.js";
6
+ import { lmer, lmerInternals, logicalOption } from "./lmer.js";
7
+ import { profiledDeviance } from "./mixedDeviance.js";
8
+ import { LMER_SETTINGS, minimiseWithRestarts } from "./mixedMinimiser.js";
9
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
10
+ import { checkOptions } from "../internal/checkOptions.js";
11
+ const CONFINT_LMER_KEYS = ["level", "method", "parm", "signames"];
12
+ const CONFINT_GLMER_KEYS = ["level", "method", "parm", "signames"];
13
+ const GLMER_PROFILE_SETTINGS = { ...LMER_SETTINGS, releaseTolerance: 1e-10 };
14
+ function parameterSet(terms, groups, varCorr, beta, fixefNames, sigma) {
15
+ const parameters = [];
16
+ let serial = 1;
17
+ for (let t = 0; t < terms.length; t++) {
18
+ const term = terms[t];
19
+ const vc = varCorr[t];
20
+ for (let i = 0; i < term.columns.length; i++) {
21
+ parameters.push({
22
+ name: `.sig${String(serial++).padStart(2, "0")}`,
23
+ descriptive: `sd_${term.columns[i]}|${groups[term.group].name}`,
24
+ kind: "sd",
25
+ value: vc.sd[i],
26
+ term: t,
27
+ row: i,
28
+ });
29
+ }
30
+ for (let i = 1; i < term.columns.length; i++) {
31
+ for (let j = 0; j < i; j++) {
32
+ parameters.push({
33
+ name: `.sig${String(serial++).padStart(2, "0")}`,
34
+ descriptive: `cor_${term.columns[i]}.${term.columns[j]}|${groups[term.group].name}`,
35
+ kind: "cor",
36
+ value: Number.isFinite(vc.corr[i][j]) ? vc.corr[i][j] : 0,
37
+ term: t,
38
+ row: i,
39
+ col: j,
40
+ });
41
+ }
42
+ }
43
+ }
44
+ if (sigma !== undefined)
45
+ parameters.push({ name: ".sigma", descriptive: "sigma", kind: "sigma", value: sigma });
46
+ beta.forEach((value, i) => parameters.push({
47
+ name: fixefNames[i],
48
+ descriptive: fixefNames[i],
49
+ kind: "beta",
50
+ value,
51
+ beta: i,
52
+ }));
53
+ return { parameters };
54
+ }
55
+ function parameterNames(parameters, signames) {
56
+ return parameters.map((p) => (p.kind === "beta" || !signames ? p.descriptive : p.name));
57
+ }
58
+ function transform(p) {
59
+ if (p.kind === "sd" || p.kind === "sigma")
60
+ return Math.log(p.value);
61
+ if (p.kind === "cor")
62
+ return Math.atanh(Math.max(-1 + 1e-12, Math.min(1 - 1e-12, p.value)));
63
+ return p.value;
64
+ }
65
+ function inverseTransform(p, value) {
66
+ if (p.kind === "sd" || p.kind === "sigma")
67
+ return Math.exp(value);
68
+ if (p.kind === "cor")
69
+ return Math.tanh(value);
70
+ return value;
71
+ }
72
+ function choleskyCorrelation(corr) {
73
+ const n = corr.length;
74
+ const l = Array.from({ length: n }, () => new Array(n).fill(0));
75
+ for (let i = 0; i < n; i++) {
76
+ for (let j = 0; j <= i; j++) {
77
+ let value = corr[i][j];
78
+ for (let k = 0; k < j; k++)
79
+ value -= l[i][k] * l[j][k];
80
+ if (i === j) {
81
+ if (value < -1e-12 || !Number.isFinite(value))
82
+ return undefined;
83
+ l[i][j] = Math.sqrt(Math.max(0, value));
84
+ }
85
+ else {
86
+ const diagonal = l[j][j];
87
+ if (diagonal === 0) {
88
+ if (Math.abs(value) > 1e-12)
89
+ return undefined;
90
+ l[i][j] = 0;
91
+ }
92
+ else {
93
+ l[i][j] = value / diagonal;
94
+ }
95
+ }
96
+ }
97
+ }
98
+ return l;
99
+ }
100
+ function thetaOf(terms, parameters, values, sigma, scaleBySigma) {
101
+ const theta = [];
102
+ for (let t = 0; t < terms.length; t++) {
103
+ const nc = terms[t].columns.length;
104
+ const sd = new Array(nc);
105
+ const corr = Array.from({ length: nc }, (_, i) => Array.from({ length: nc }, (_, j) => (i === j ? 1 : 0)));
106
+ for (let k = 0; k < parameters.length; k++) {
107
+ const p = parameters[k];
108
+ if (p.term !== t)
109
+ continue;
110
+ if (p.kind === "sd")
111
+ sd[p.row] = values[k];
112
+ else if (p.kind === "cor")
113
+ corr[p.row][p.col] = corr[p.col][p.row] = values[k];
114
+ }
115
+ const l = choleskyCorrelation(corr);
116
+ if (l === undefined)
117
+ return undefined;
118
+ const scale = scaleBySigma ? sigma : 1;
119
+ for (let j = 0; j < nc; j++)
120
+ for (let i = j; i < nc; i++)
121
+ theta.push((sd[i] / scale) * l[i][j]);
122
+ }
123
+ return theta;
124
+ }
125
+ function selectParameters(parameters, names, raw, warnings) {
126
+ if (raw === undefined)
127
+ return parameters.map((_, i) => i);
128
+ const requested = Array.isArray(raw) ? raw : [raw];
129
+ const selected = new Set();
130
+ for (const item of requested) {
131
+ if (typeof item === "number" || (typeof item === "string" && /^\d+$/.test(item))) {
132
+ const index = (typeof item === "number" ? Math.trunc(item) : Number(item)) - 1;
133
+ if (index >= 0 && index < parameters.length)
134
+ selected.add(index);
135
+ continue;
136
+ }
137
+ if (item === "theta_") {
138
+ parameters.forEach((p, i) => { if (p.kind !== "beta")
139
+ selected.add(i); });
140
+ continue;
141
+ }
142
+ if (item === "beta_") {
143
+ parameters.forEach((p, i) => { if (p.kind === "beta")
144
+ selected.add(i); });
145
+ continue;
146
+ }
147
+ const index = typeof item === "string" ? names.indexOf(item) : -1;
148
+ if (index >= 0)
149
+ selected.add(index);
150
+ else
151
+ warnings.push(`Nothing selected by 'which="${String(item)}"'`);
152
+ }
153
+ return [...selected].sort((a, b) => a - b);
154
+ }
155
+ /** Minimise the profile criterion with one user-scale parameter fixed. */
156
+ function profileAt(kind, parameters, evaluate, target, targetValue) {
157
+ const free = parameters.map((p, i) => (i === target ||
158
+ (kind === "lmer" && p.kind === "beta") ||
159
+ ((p.kind === "sd" || p.kind === "sigma") && p.value === 0)
160
+ ? -1
161
+ : i)).filter((i) => i >= 0);
162
+ const start = free.map((i) => transform(parameters[i]));
163
+ const valueAt = (x) => {
164
+ const values = parameters.map((p) => p.value);
165
+ free.forEach((i, j) => (values[i] = inverseTransform(parameters[i], x[j])));
166
+ values[target] = targetValue;
167
+ return evaluate(values, target, targetValue);
168
+ };
169
+ if (free.length === 0)
170
+ return valueAt([]);
171
+ const problem = {
172
+ evaluate: (x) => {
173
+ const f = valueAt(x);
174
+ const g = x.map((v, j) => {
175
+ let h = (kind === "glmer" ? 1e-4 : 2e-5) * Math.max(1, Math.abs(v));
176
+ for (let attempt = 0; attempt < 8; attempt++, h *= 0.5) {
177
+ const plus = x.slice();
178
+ const minus = x.slice();
179
+ plus[j] = v + h;
180
+ minus[j] = v - h;
181
+ const fp = valueAt(plus);
182
+ const fm = valueAt(minus);
183
+ if (Number.isFinite(fp) && Number.isFinite(fm))
184
+ return (fp - fm) / (2 * h);
185
+ if (Number.isFinite(fp) && Number.isFinite(f))
186
+ return (fp - f) / h;
187
+ if (Number.isFinite(fm) && Number.isFinite(f))
188
+ return (f - fm) / h;
189
+ }
190
+ // No finite difference is not a zero gradient: report the failure to the robust minimiser.
191
+ return NaN;
192
+ });
193
+ return { f, g };
194
+ },
195
+ diagonal: new Array(free.length).fill(false),
196
+ columns: [],
197
+ settings: kind === "glmer" ? GLMER_PROFILE_SETTINGS : LMER_SETTINGS,
198
+ rejectNonFinite: true,
199
+ failure: "mixed-model profile minimisation did not converge",
200
+ robust: true,
201
+ };
202
+ // A profile point can be harder to minimise than the fitted model. If the trust-region
203
+ // iteration stalls, restart from its best finite point; never treat an unconverged value as a profile.
204
+ let from = start;
205
+ for (let attempt = 0; attempt < 2; attempt++) {
206
+ try {
207
+ const result = minimiseWithRestarts(problem, from, [], { bestOnFailure: true });
208
+ if (result.converged)
209
+ return result.f;
210
+ if (result.theta.every((v, i) => v === from[i]))
211
+ break;
212
+ from = result.theta;
213
+ }
214
+ catch {
215
+ return Infinity;
216
+ }
217
+ }
218
+ return Infinity;
219
+ }
220
+ /** Find one profile endpoint by bracketing and bisection of the signed likelihood-root equation. */
221
+ function profileLimit(estimate, parameter, cutoff, targetRoot, direction, scale, profile) {
222
+ // Standard deviations and sigma have only a lower boundary; their upper endpoints are unbounded.
223
+ const boundary = parameter.kind === "sd" || parameter.kind === "sigma"
224
+ ? (direction < 0 ? 0 : undefined)
225
+ : parameter.kind === "cor" ? (direction < 0 ? -1 : 1) : undefined;
226
+ if (boundary !== undefined && estimate === boundary)
227
+ return boundary;
228
+ const dHat = profile(estimate);
229
+ // Keep ζ itself: adding ζ² to a large deviance can round the increment to exactly zero.
230
+ const targetDelta = targetRoot * targetRoot;
231
+ const resolution = 1e-8 * Math.max(1, Math.abs(dHat));
232
+ // When the requested likelihood increment is below the deviance's floating-point resolution,
233
+ // bracket in signed likelihood-root (ζ) space instead. Near the maximum, ζ is locally
234
+ // proportional to the parameter; a well-resolved point avoids subtracting nearly equal deviances.
235
+ if (Number.isFinite(dHat) && targetDelta >= 0 && targetDelta < resolution) {
236
+ const resolvedDelta = Math.max(100 * resolution, 1e-4);
237
+ let step = parameter.kind === "cor"
238
+ ? Math.max(Math.abs(estimate) * 0.05, 0.01)
239
+ : scale * 0.05;
240
+ let candidate = estimate + direction * step;
241
+ for (let i = 0; i < 40; i++) {
242
+ if (boundary !== undefined)
243
+ candidate = direction < 0 ? Math.max(boundary, candidate) : Math.min(boundary, candidate);
244
+ if (candidate === estimate)
245
+ return boundary !== undefined ? boundary : NaN;
246
+ const delta = profile(candidate) - dHat;
247
+ if (Number.isFinite(delta) && delta >= resolvedDelta) {
248
+ const root = Math.sqrt(delta);
249
+ const endpoint = estimate + direction * (Math.abs(candidate - estimate) * Math.sqrt(targetDelta) / root);
250
+ if (boundary !== undefined)
251
+ return direction < 0 ? Math.max(boundary, endpoint) : Math.min(boundary, endpoint);
252
+ return endpoint;
253
+ }
254
+ if (boundary !== undefined && candidate === boundary)
255
+ return boundary;
256
+ const next = estimate + direction * step * 2;
257
+ if (next === candidate)
258
+ break;
259
+ step *= 2;
260
+ candidate = next;
261
+ }
262
+ return NaN;
263
+ }
264
+ const at = (x) => profile(x) - cutoff;
265
+ let inside = estimate;
266
+ let step = parameter.kind === "cor"
267
+ ? Math.max(Math.abs(estimate) * 0.2, 0.05)
268
+ : scale * (parameter.kind === "beta" ? 0.25 : 0.2);
269
+ let outside = estimate + direction * step;
270
+ if (boundary !== undefined)
271
+ outside = direction < 0 ? Math.max(boundary, outside) : Math.min(boundary, outside);
272
+ const fInside = at(inside);
273
+ if (!Number.isFinite(fInside) || !(fInside < 0))
274
+ return NaN;
275
+ let fOutside = at(outside);
276
+ // A failed nuisance minimisation is not evidence that the profile crossed the cutoff. Move closer until
277
+ // the profile is finite; only finite values below the cutoff justify expanding the bracket.
278
+ for (let i = 0; i < 36 && !(Number.isFinite(fOutside) && fOutside >= 0); i++) {
279
+ if (boundary !== undefined && outside === boundary) {
280
+ // If the profile reaches a parameter boundary before its likelihood cutoff, report that boundary.
281
+ return boundary;
282
+ }
283
+ const previous = outside;
284
+ step = Number.isFinite(fOutside) ? step * 1.8 : step * 0.5;
285
+ outside = estimate + direction * step;
286
+ if (boundary !== undefined)
287
+ outside = direction < 0 ? Math.max(boundary, outside) : Math.min(boundary, outside);
288
+ if (outside === previous || outside === inside)
289
+ break;
290
+ fOutside = at(outside);
291
+ }
292
+ if (!Number.isFinite(fOutside) || !(fOutside >= 0)) {
293
+ return boundary !== undefined && outside === boundary ? boundary : NaN;
294
+ }
295
+ // Illinois' safeguarded secant method usually needs far fewer profile minimisations than bisection.
296
+ // The bracket is retained; a bisection fallback guarantees the requested endpoint precision.
297
+ let a = inside;
298
+ let b = outside;
299
+ let fa = fInside;
300
+ let fb = fOutside;
301
+ let wa = fa;
302
+ let wb = fb;
303
+ for (let i = 0; i < 24; i++) {
304
+ let candidate = a - wa * (b - a) / (wb - wa);
305
+ const low = Math.min(a, b);
306
+ const high = Math.max(a, b);
307
+ const margin = 0.05 * (high - low);
308
+ if (!Number.isFinite(candidate) || candidate <= low + margin || candidate >= high - margin) {
309
+ candidate = a + (b - a) / 2;
310
+ }
311
+ let fc = at(candidate);
312
+ if (!Number.isFinite(fc)) {
313
+ candidate = a + (b - a) / 2;
314
+ fc = at(candidate);
315
+ if (!Number.isFinite(fc))
316
+ return NaN;
317
+ }
318
+ if (fc === 0)
319
+ return candidate;
320
+ if (fc >= 0) {
321
+ b = candidate;
322
+ fb = fc;
323
+ wb = fb;
324
+ wa *= 0.5;
325
+ }
326
+ else {
327
+ a = candidate;
328
+ fa = fc;
329
+ wa = fa;
330
+ wb *= 0.5;
331
+ }
332
+ const toleranceScale = parameter.kind === "cor" ? Math.max(1, Math.abs(candidate)) : Math.max(scale, Math.abs(candidate));
333
+ if (Math.abs(b - a) <= 2e-10 * toleranceScale)
334
+ return a + (b - a) / 2;
335
+ }
336
+ for (let i = 0; i < 56; i++) {
337
+ const candidate = a + (b - a) / 2;
338
+ const fc = at(candidate);
339
+ if (!Number.isFinite(fc))
340
+ return NaN;
341
+ if (fc >= 0) {
342
+ b = candidate;
343
+ fb = fc;
344
+ }
345
+ else {
346
+ a = candidate;
347
+ fa = fc;
348
+ }
349
+ const toleranceScale = parameter.kind === "cor" ? Math.max(1, Math.abs(candidate)) : Math.max(scale, Math.abs(candidate));
350
+ if (Math.abs(b - a) <= 2e-10 * toleranceScale)
351
+ break;
352
+ }
353
+ const root = a + (b - a) / 2;
354
+ const toleranceScale = parameter.kind === "cor" ? Math.max(1, Math.abs(root)) : Math.max(scale, Math.abs(root));
355
+ if (Math.abs(b - a) > 2e-10 * toleranceScale)
356
+ return NaN;
357
+ return root;
358
+ }
359
+ function profileIntervals(kind, parameters, evaluate, selected, level, parameterScales, cache, warnings) {
360
+ const z = qnorm((1 + level) / 2);
361
+ const lower = new Array(parameters.length).fill(NaN);
362
+ const upper = new Array(parameters.length).fill(NaN);
363
+ for (const index of selected) {
364
+ const cached = cache.get(index);
365
+ if (cached !== undefined) {
366
+ lower[index] = cached[0];
367
+ upper[index] = cached[1];
368
+ if ((Number.isNaN(cached[0]) || Number.isNaN(cached[1])) && !warnings.includes("NAs detected in profiling"))
369
+ warnings.push("NAs detected in profiling");
370
+ continue;
371
+ }
372
+ const parameter = parameters[index];
373
+ const estimate = parameter.value;
374
+ // At the fitted estimate, ζ is exactly zero by definition. Do not re-minimise nuisance
375
+ // parameters here: numerical noise in that redundant refit can exceed a very small cutoff.
376
+ const dHat = evaluate(parameters.map((p) => p.value), index, estimate);
377
+ const pointCache = new Map([[estimate, dHat]]);
378
+ const profile = (value) => {
379
+ const cached = pointCache.get(value);
380
+ if (cached !== undefined)
381
+ return cached;
382
+ const result = profileAt(kind, parameters, evaluate, index, value);
383
+ pointCache.set(value, result);
384
+ return result;
385
+ };
386
+ if (!Number.isFinite(dHat)) {
387
+ if (!warnings.includes("NAs detected in profiling"))
388
+ warnings.push("NAs detected in profiling");
389
+ cache.set(index, [NaN, NaN]);
390
+ continue;
391
+ }
392
+ const cutoff = dHat + z * z;
393
+ const scale = parameterScales[index];
394
+ const lo = profileLimit(estimate, parameter, cutoff, z, -1, scale, profile);
395
+ const hi = profileLimit(estimate, parameter, cutoff, z, 1, scale, profile);
396
+ lower[index] = lo;
397
+ upper[index] = hi;
398
+ cache.set(index, [lo, hi]);
399
+ if ((Number.isNaN(lo) || Number.isNaN(hi)) && !warnings.includes("NAs detected in profiling"))
400
+ warnings.push("NAs detected in profiling");
401
+ }
402
+ return { lower, upper };
403
+ }
404
+ function finish(parameters, names, selected, level, method, profile, standardErrors, warnings) {
405
+ const lowerAll = new Array(parameters.length).fill(NaN);
406
+ const upperAll = new Array(parameters.length).fill(NaN);
407
+ if (!(level > 0 && level < 1)) {
408
+ warnings.push("NaNs produced");
409
+ }
410
+ else if (method === "Wald") {
411
+ const z = qnorm((1 + level) / 2);
412
+ parameters.forEach((p, i) => {
413
+ if (p.kind !== "beta")
414
+ return;
415
+ const se = standardErrors[i];
416
+ lowerAll[i] = p.value - z * se;
417
+ upperAll[i] = p.value + z * se;
418
+ });
419
+ }
420
+ else if (profile !== undefined && selected.length > 0) {
421
+ const r = profile();
422
+ r.lower.forEach((v, i) => (lowerAll[i] = v));
423
+ r.upper.forEach((v, i) => (upperAll[i] = v));
424
+ }
425
+ return {
426
+ names: selected.map((i) => names[i]),
427
+ lower: selected.map((i) => lowerAll[i]),
428
+ upper: selected.map((i) => upperAll[i]),
429
+ warnings,
430
+ };
431
+ }
432
+ const lmerCache = new WeakMap();
433
+ function confintLmerImpl(fit, options) {
434
+ const internals = lmerInternals(fit);
435
+ const level = options.level ?? 0.95;
436
+ const method = options.method ?? "profile";
437
+ if (method !== "profile" && method !== "Wald")
438
+ throw new RangeError(`invalid 'method': ${String(method)}`);
439
+ const set = parameterSet(internals.structure.terms, internals.structure.groups, fit.varCorr, fit.fixef, fit.fixefNames, fit.sigma);
440
+ const signames = logicalOption(options.signames, true);
441
+ const names = parameterNames(set.parameters, signames);
442
+ const warnings = [];
443
+ const selected = selectParameters(set.parameters, names, options.parm, warnings);
444
+ // lme4 profiles a REML fit on the ML criterion, centred at the ML estimates. Refit with the same
445
+ // captured data and model options so the profile coordinates and the likelihood maximum use one fit.
446
+ const profileFit = method === "profile" && fit.REML
447
+ ? lmer(fit.formula, internals.snapshot, { ...internals.options, REML: false })
448
+ : fit;
449
+ const profileInternals = lmerInternals(profileFit);
450
+ const s = profileInternals.structure;
451
+ const profileSet = method === "profile"
452
+ ? parameterSet(s.terms, s.groups, profileFit.varCorr, profileFit.fixef, profileFit.fixefNames, profileFit.sigma)
453
+ : set;
454
+ const evaluate = (values, target, targetValue) => {
455
+ const sigmaIndex = profileSet.parameters.findIndex((p) => p.kind === "sigma");
456
+ const sigma = values[sigmaIndex];
457
+ const theta = thetaOf(s.terms, profileSet.parameters, values, sigma, true);
458
+ if (theta === undefined)
459
+ return Infinity;
460
+ const targetParameter = profileSet.parameters[target];
461
+ let structure = s;
462
+ const reml = false;
463
+ if (targetParameter.kind === "beta") {
464
+ const j = targetParameter.beta;
465
+ const delta = targetValue - profileInternals.beta0[j];
466
+ structure = {
467
+ ...s,
468
+ y: s.y.map((v, i) => v - s.x[i][j] * delta),
469
+ x: s.x.map((row) => row.filter((_, k) => k !== j)),
470
+ xColNames: s.xColNames.filter((_, k) => k !== j),
471
+ xAssign: s.xAssign.filter((_, k) => k !== j),
472
+ };
473
+ }
474
+ const r = profiledDeviance(structure, theta, reml);
475
+ const n = structure.y.length;
476
+ const p = structure.xColNames.length;
477
+ const df = reml ? n - p : n;
478
+ return r.logDetL + (reml ? r.logDetRX : 0) + r.prss / (sigma * sigma) + df * Math.log(2 * Math.PI * sigma * sigma);
479
+ };
480
+ const byLevel = lmerCache.get(fit) ?? new Map();
481
+ lmerCache.set(fit, byLevel);
482
+ const cache = byLevel.get(level) ?? new Map();
483
+ byLevel.set(level, cache);
484
+ const residualScale = profileSet.parameters.find((p) => p.kind === "sigma")?.value ?? 1;
485
+ const parameterScales = profileSet.parameters.map((p) => {
486
+ if (p.kind === "beta")
487
+ return profileFit.coefTable.stdError[p.beta];
488
+ if (p.kind === "sd")
489
+ return p.value > 0 ? p.value : residualScale;
490
+ if (p.kind === "sigma")
491
+ return p.value;
492
+ return 1;
493
+ });
494
+ const profile = () => profileIntervals("lmer", profileSet.parameters, evaluate, selected, level, parameterScales, cache, warnings);
495
+ const standardErrors = set.parameters.map((p) => (p.kind === "beta" ? fit.coefTable.stdError[p.beta] : NaN));
496
+ const result = finish(set.parameters, names, selected, level, method, profile, standardErrors, warnings);
497
+ reportWarnings("confintLmer", result.warnings);
498
+ return result;
499
+ }
500
+ /**
501
+ * Confidence intervals for a linear mixed-model fit. Equivalent to `lme4::confint.merMod()` in R.
502
+ *
503
+ * @category Mixed models
504
+ */
505
+ export function confintLmer(fit, options = {}) {
506
+ checkOptions(options, CONFINT_LMER_KEYS, "confintLmer"); // generated: option-keys.mjs
507
+ return confintLmerImpl(fit, options);
508
+ }
509
+ /**
510
+ * Confidence intervals for a generalized linear mixed-model fit. Equivalent to R's `lme4::confint.merMod()`.
511
+ *
512
+ * @category Mixed models
513
+ */
514
+ export function confintGlmer(fit, options = {}) {
515
+ checkOptions(options, CONFINT_GLMER_KEYS, "confintGlmer"); // generated: option-keys.mjs
516
+ const level = options.level ?? 0.95;
517
+ const method = options.method ?? "profile";
518
+ if (method !== "profile" && method !== "Wald")
519
+ throw new RangeError(`invalid 'method': ${String(method)}`);
520
+ if (method === "profile" && fit.nAGQ !== 1)
521
+ throw new RangeError("profile intervals for glmer require nAGQ = 1");
522
+ const internals = glmerInternals(fit);
523
+ const s = internals.structure;
524
+ const hasDispersion = s.family.family !== "binomial" && s.family.family !== "poisson";
525
+ // The dispersion estimate is reported for Wald intervals, but its interval is a separate
526
+ // profiling problem (kept out of this parameter set until that method is specified).
527
+ const set = parameterSet(s.terms, s.groups, fit.varCorr, fit.fixef, fit.fixefNames, method === "Wald" && hasDispersion ? fit.sigma : undefined);
528
+ const signames = logicalOption(options.signames, true);
529
+ const names = parameterNames(set.parameters, signames);
530
+ const warnings = [];
531
+ // Profile intervals of a family with a dispersion keep R's row of .sigma (and R's numbering for parm), but
532
+ // its interval is not computed: the dispersion stays a nuisance parameter of the profiles of the other rows
533
+ // (user's decision, 2026-11-18; R refuses to profile these fits at all). The row is NaN, with a warning.
534
+ const withSigma = method === "profile" && hasDispersion
535
+ ? parameterSet(s.terms, s.groups, fit.varCorr, fit.fixef, fit.fixefNames, fit.sigma).parameters
536
+ : undefined;
537
+ const sigmaAt = withSigma?.findIndex((p) => p.kind === "sigma") ?? -1;
538
+ const selectedFull = withSigma === undefined
539
+ ? selectParameters(set.parameters, names, options.parm, warnings)
540
+ : selectParameters(withSigma, parameterNames(withSigma, signames), options.parm, warnings);
541
+ const selected = withSigma === undefined
542
+ ? selectedFull
543
+ : selectedFull.filter((i) => i !== sigmaAt).map((i) => (i > sigmaAt ? i - 1 : i));
544
+ const evaluate = (values, target, targetValue) => {
545
+ const theta = thetaOf(s.terms, set.parameters, values, 1, false);
546
+ if (theta === undefined)
547
+ return Infinity;
548
+ const beta = set.parameters.filter((p) => p.kind === "beta").map((p) => values[set.parameters.indexOf(p)]);
549
+ const targetParameter = set.parameters[target];
550
+ if (targetParameter.kind === "beta")
551
+ beta[targetParameter.beta] = targetValue;
552
+ return glmerDeviance(s, theta, beta, 1).deviance;
553
+ };
554
+ const parameterScales = set.parameters.map((p) => {
555
+ if (p.kind === "beta")
556
+ return fit.coefTable.stdError[p.beta];
557
+ if (p.kind === "sd")
558
+ return p.value > 0 ? p.value : 1;
559
+ return 1;
560
+ });
561
+ const profile = () => profileIntervals("glmer", set.parameters, evaluate, selected, level, parameterScales, new Map(), warnings);
562
+ const standardErrors = set.parameters.map((p) => (p.kind === "beta" ? fit.coefTable.stdError[p.beta] : NaN));
563
+ const result = finish(set.parameters, names, selected, level, method, profile, standardErrors, warnings);
564
+ if (withSigma !== undefined && selectedFull.includes(sigmaAt)) {
565
+ const at = selectedFull.indexOf(sigmaAt);
566
+ result.names.splice(at, 0, parameterNames(withSigma, signames)[sigmaAt]);
567
+ result.lower.splice(at, 0, NaN);
568
+ result.upper.splice(at, 0, NaN);
569
+ result.warnings.push("the profile interval of the dispersion (.sigma) is not computed");
570
+ }
571
+ reportWarnings("confintGlmer", result.warnings);
572
+ return result;
573
+ }
@@ -0,0 +1,36 @@
1
+ import { type LmerResult } from "./lmer.js";
2
+ import { type GlmerResult } from "./glmer.js";
3
+ /** Options of {@link simulateLmer} and {@link simulateGlmer}.
4
+ *
5
+ * @category Mixed models
6
+ */
7
+ export interface MixedSimulateOptions {
8
+ /** Number of simulated response vectors. Default 1. */
9
+ nsim?: number;
10
+ /** Set the shared R-compatible random stream before simulation. Null or omitted uses its current state. */
11
+ seed?: number | null;
12
+ /** Condition on all fitted random effects, or generate new effects. Cannot be combined with reForm. */
13
+ useU?: boolean | number;
14
+ /** Random-effects terms to condition on: null (all), "NA" or "~0" (none), or a formula selecting whole terms. */
15
+ reForm?: string | null;
16
+ }
17
+ /** Simulations from a mixed-model fit: one response vector per simulation, with R's simulation column names.
18
+ *
19
+ * @category Mixed models
20
+ */
21
+ export interface MixedSimulations extends Array<number[] | [number, number][]> {
22
+ /** Names of the simulation columns, "sim_1", ... */
23
+ names: string[];
24
+ }
25
+ /**
26
+ * Simulations from a linear mixed-model fit. Equivalent to R's `lme4::simulate.merMod()`.
27
+ *
28
+ * @category Mixed models
29
+ */
30
+ export declare function simulateLmer(fit: LmerResult, options?: MixedSimulateOptions): MixedSimulations;
31
+ /**
32
+ * Simulations from a generalized linear mixed-model fit. Equivalent to R's `lme4::simulate.merMod()`.
33
+ *
34
+ * @category Mixed models
35
+ */
36
+ export declare function simulateGlmer(fit: GlmerResult, options?: MixedSimulateOptions): MixedSimulations;