@numero-uno-jpn/rstats 0.14.0 → 0.15.1

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 (49) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.ja.md +7 -7
  3. package/README.md +7 -7
  4. package/dist/chunks/{chunk-7PSGKKOP.js → chunk-3QTVXDUM.js} +2 -2
  5. package/dist/chunks/{chunk-A76XBA3D.js → chunk-4ILI2FSB.js} +1 -1
  6. package/dist/chunks/{chunk-RZIWVCHO.js → chunk-5OSQ76OO.js} +2 -2
  7. package/dist/chunks/{chunk-7T74KLE5.js → chunk-5SQFDLNG.js} +2 -2
  8. package/dist/chunks/{chunk-ACE64PMM.js → chunk-5XQZNKHZ.js} +2 -2
  9. package/dist/chunks/chunk-5YMP4WAJ.js +2 -0
  10. package/dist/chunks/{chunk-ZUESNU7W.js → chunk-735NNFAS.js} +2 -2
  11. package/dist/chunks/{chunk-WM33ADZV.js → chunk-7J4HW6VF.js} +2 -2
  12. package/dist/chunks/{chunk-6JRESWVF.js → chunk-BDJPSEA7.js} +2 -2
  13. package/dist/chunks/{chunk-7CPM3M6Q.js → chunk-GEJCBCMP.js} +2 -2
  14. package/dist/chunks/{chunk-SZ357HRC.js → chunk-H4CHJMFU.js} +1 -1
  15. package/dist/chunks/{chunk-Q4JF4QHS.js → chunk-IQOVOHZG.js} +2 -2
  16. package/dist/chunks/chunk-KO6QQPC6.js +2 -0
  17. package/dist/chunks/{chunk-FBDZ6B2G.js → chunk-LY2T6DA6.js} +2 -2
  18. package/dist/chunks/chunk-OLPTFKIZ.js +3 -0
  19. package/dist/chunks/{chunk-YTV3RFCA.js → chunk-SAZAEPZC.js} +1 -1
  20. package/dist/chunks/{chunk-DWNGNTS6.js → chunk-TYFGVCVQ.js} +2 -2
  21. package/dist/chunks/{chunk-XCAMWVNO.js → chunk-UWBYDIOH.js} +1 -1
  22. package/dist/chunks/{chunk-IGSR4GIF.js → chunk-UZHY5DWN.js} +2 -2
  23. package/dist/chunks/{chunk-NTETWLP3.js → chunk-VOIJKNL2.js} +1 -1
  24. package/dist/chunks/{chunk-IBJ7RI44.js → chunk-Z3C3G5XI.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions/nchisq.js +123 -25
  27. package/dist/distributions/signrank.js +73 -20
  28. package/dist/distributions.js +2 -2
  29. package/dist/linalg.js +2 -2
  30. package/dist/mixed.js +4 -4
  31. package/dist/models/glm.js +4 -2
  32. package/dist/models/glmFamily.js +16 -4
  33. package/dist/models/lmer.d.ts +28 -5
  34. package/dist/models/lmer.js +129 -20
  35. package/dist/models/lmerAnova.d.ts +8 -3
  36. package/dist/models/lmerAnova.js +10 -4
  37. package/dist/models/lmerHypotheses.d.ts +4 -3
  38. package/dist/models/lmerHypotheses.js +9 -7
  39. package/dist/models/lmerTest.d.ts +13 -7
  40. package/dist/models/lmerTest.js +16 -11
  41. package/dist/models/mixedStructure.js +30 -14
  42. package/dist/numerics.js +2 -2
  43. package/dist/rstats.js +13 -13
  44. package/dist/special.js +2 -2
  45. package/dist/tests.js +7 -7
  46. package/package.json +1 -1
  47. package/dist/chunks/chunk-DCGBYO44.js +0 -2
  48. package/dist/chunks/chunk-SD7ML5PE.js +0 -2
  49. package/dist/chunks/chunk-YQLEXH2Y.js +0 -3
@@ -49,6 +49,15 @@ function sqrtWarn(x) {
49
49
  currentWarnings?.add("NaNs produced");
50
50
  return Math.sqrt(x);
51
51
  }
52
+ /**
53
+ * Logarithm that warns as R's log does when it produces NaN (a negative argument, -Inf included; NaN does not warn).
54
+ * Used by the deviance contributions that R computes in R code (poisson, quasipoisson, Gamma, quasi "mu" and "mu^2")
55
+ */
56
+ function logWarn(x) {
57
+ if (x < 0)
58
+ currentWarnings?.add("NaNs produced");
59
+ return Math.log(x);
60
+ }
52
61
  /** A number as C's printf("%g") writes it: 6 significant digits, fixed or scientific, trailing zeros dropped */
53
62
  function formatG(v) {
54
63
  if (!Number.isFinite(v))
@@ -175,13 +184,14 @@ function quasiVariance(v) {
175
184
  return {
176
185
  variance: (m) => m,
177
186
  muOk: (m) => m > 0,
178
- dev: (y, mu, w) => 2 * w * ((y === 0 ? 0 : y * Math.log(y / mu)) - (y - mu)),
187
+ dev: (y, mu, w) => 2 * w * ((y === 0 ? 0 : y * logWarn(y / mu)) - (y - mu)),
179
188
  };
180
189
  case "mu^2":
181
190
  return {
182
191
  variance: (m) => m * m,
183
192
  muOk: (m) => m > 0,
184
- dev: (y, mu, w) => Math.max(-2 * w * (Math.log(y > 0 ? y / mu : 1 / mu) - (y - mu) / mu), 0),
193
+ // log(y/mu) for every y != 0 (NaN for a negative y, as in R), log(1/mu) for y = 0
194
+ dev: (y, mu, w) => Math.max(-2 * w * (logWarn(y !== 0 ? y / mu : 1 / mu) - (y - mu) / mu), 0),
185
195
  };
186
196
  case "mu^3":
187
197
  return { variance: (m) => m * m * m, muOk: (m) => m > 0, dev: inverseGaussianDev };
@@ -189,6 +199,7 @@ function quasiVariance(v) {
189
199
  throw new RangeError(`'variance' "${String(v)}" is invalid: possible values are "mu(1-mu)", "mu", "mu^2", "mu^3" and "constant"`);
190
200
  }
191
201
  }
202
+ /** (R computes this deviance in compiled code, so a mean outside (0, 1) gives NaN without "NaNs produced") */
192
203
  function binomialDev(y, mu, w) {
193
204
  const a = y === 0 ? 0 : y * Math.log(y / mu);
194
205
  const b = y === 1 ? 0 : (1 - y) * Math.log((1 - y) / (1 - mu));
@@ -243,14 +254,15 @@ export function makeFamily(family, link) {
243
254
  fixedDispersion: name === "poisson",
244
255
  variance: (m) => m,
245
256
  muOk: (m) => Number.isFinite(m) && m > 0,
246
- devContribution: (y, mu, w) => (y > 0 ? 2 * w * (y * Math.log(y / mu) - (y - mu)) : 2 * w * mu),
257
+ // (a row with y = 0 takes no logarithm, so a negative mean there does not warn, as in R)
258
+ devContribution: (y, mu, w) => (y > 0 ? 2 * w * (y * logWarn(y / mu) - (y - mu)) : 2 * w * mu),
247
259
  };
248
260
  case "Gamma":
249
261
  return {
250
262
  ...base,
251
263
  variance: (m) => m * m,
252
264
  muOk: (m) => Number.isFinite(m) && m > 0,
253
- devContribution: (y, mu, w) => -2 * w * ((y === 0 ? 0 : Math.log(y / mu)) - (y - mu) / mu),
265
+ devContribution: (y, mu, w) => -2 * w * ((y === 0 ? 0 : logWarn(y / mu)) - (y - mu) / mu),
254
266
  };
255
267
  case "inverse.gaussian":
256
268
  return { ...base, variance: (m) => m * m * m, muOk: () => true, devContribution: inverseGaussianDev };
@@ -9,12 +9,18 @@ import { type MixedModelStructure } from "./mixedStructure.js";
9
9
  */
10
10
  export type LmerContrastName = ContrastName | "contr.poly";
11
11
  /**
12
- * Options of {@link lmer}.
12
+ * Options of {@link lmer}. Only the keys below are accepted: R's `weights`, `offset`, `subset`, `naAction`,
13
+ * `na.action`, `control`, `start`, `verbose` and `devFunOnly` give the Error `lmer: argument '<key>' is not
14
+ * supported`, any other key the TypeError `unused argument (<key>)` (a key whose value is `undefined` included).
13
15
  *
14
16
  * @category Mixed models
15
17
  */
16
18
  export interface LmerOptions {
17
- /** Whether to minimise the REML criterion (default `true`) or the ML deviance (`false`). */
19
+ /**
20
+ * Whether to minimise the REML criterion (default `true`) or the ML deviance (`false`). As in R's conditions, a
21
+ * number is `false` for 0 and `true` otherwise; `null` and other values (the strings `"TRUE"`, `"FALSE"` included)
22
+ * are TypeErrors. The result's `REML` is the boolean.
23
+ */
18
24
  REML?: boolean;
19
25
  /**
20
26
  * A contrast per factor of the fixed-effects part: `"contr.treatment"` (default), `"contr.sum"`, `"contr.helmert"` or
@@ -126,6 +132,18 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
126
132
  f: number;
127
133
  g: number[];
128
134
  };
135
+ /**
136
+ * The option checks of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section 3):
137
+ * `options` must be an object when given (not null, not an array); its own keys, in order, may be neither among those
138
+ * of R that are not supported (the first gives an Error) nor unknown (a TypeError listing all of them). A key whose
139
+ * value is `undefined` counts as given. Returns the options as an object (`{}` when not given).
140
+ */
141
+ export declare function checkOptions<T extends object>(fn: string, options: T | undefined, accepted: readonly string[], unsupported: readonly string[]): T;
142
+ /**
143
+ * A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
144
+ * other than NaN `false` for 0 and `true` otherwise; `null` and anything else are TypeErrors.
145
+ */
146
+ export declare function logicalOption(value: unknown, defaultValue: boolean): boolean;
129
147
  /**
130
148
  * Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
131
149
  * quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
@@ -143,7 +161,7 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
143
161
  *
144
162
  * @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
145
163
  * @param data The data frame: an object of columns.
146
- * @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
164
+ * @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
147
165
  *
148
166
  * @example
149
167
  * ```ts
@@ -170,8 +188,13 @@ export declare function lmer(formula: string, data: DataFrame, options?: LmerOpt
170
188
  * (to refit, for example by maximum likelihood) and the criterion (so that a refit uses the same one).
171
189
  */
172
190
  export interface LmerInternals {
173
- /** The structure of the model (X, Z, the terms, the layout of θ, the model frame's rows) */
191
+ /**
192
+ * The structure of the model (X, Z, the terms, the layout of θ, the model frame's rows), with the response replaced
193
+ * by y − X β₀ (see `beta0`): the criterion and every derivative are those of the model, the fixed effects β̂ − β₀
194
+ */
174
195
  structure: MixedModelStructure;
196
+ /** β₀, the least-squares coefficients of y on X, to be added to the fixed effects computed from `structure` */
197
+ beta0: number[];
175
198
  /** The data frame given to lmer (the same object, not a copy) */
176
199
  data: DataFrame;
177
200
  /** The options given to lmer (a copy) */
@@ -192,4 +215,4 @@ export declare function lmerInternals(fit: LmerResult): LmerInternals;
192
215
  * {@link lmer} with the criterion and its gradient given (internal: not exported from the package). The regression
193
216
  * test of the sparse computation fits with the dense reference implementation through it.
194
217
  */
195
- export declare function lmerWithCriterion(formula: string, data: DataFrame, options: LmerOptions, criterion: MixedCriterion): LmerResult;
218
+ export declare function lmerWithCriterion(formula: string, data: DataFrame, options: LmerOptions | undefined, criterion: MixedCriterion): LmerResult;
@@ -39,6 +39,21 @@
39
39
  // of all the elements has a direction of negative curvature that moves it (then θ is moved a little along it).
40
40
  // lme4's own optimiser (and its convergence warnings) are not reproduced: the result is the exact minimiser, which
41
41
  // lme4 approaches to its tolerances.
42
+ //
43
+ // The criterion can have several local minima (crossed terms without a fixed intercept, for example, where one term
44
+ // can take the place of the missing intercept). So the local minimum θ* reached from the initial θ is compared with
45
+ // the boundary points of whole terms (oracle/report-0.14.0-behaviour.md, section 1): for each term whose block is not
46
+ // entirely 0 in θ*, the local minimum started at θ* with that term removed (its whole block set to 0) and held at 0.
47
+ // If the lowest of these is lower than θ*'s criterion by more than 1e-8 max(1, |criterion|), the minimisation starts
48
+ // again from it with every element free, and the comparison is repeated; otherwise θ* is the estimate (at most 50
49
+ // restarts). Only whole terms are removed, one at a time.
50
+ //
51
+ // The penalised least-squares problem is linear in y: y − X β₀ for any β₀ gives the same criterion, residuals,
52
+ // random effects and derivatives, and β̂ − β₀. So the fit works with y − X β₀, β₀ the least-squares coefficients of y
53
+ // on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
54
+ // from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
55
+ // 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
56
+ import { qr, qrCoef } from "../linalg/qr.js";
42
57
  import { profiledDeviance } from "./mixedDeviance.js";
43
58
  import { mixedModelStructure } from "./mixedStructure.js";
44
59
  /** Initial trust-region radius, relative to max(1, max |θ|) */
@@ -62,6 +77,13 @@ const GRADIENT_TOLERANCE = 1e-9;
62
77
  const MAX_ITERATIONS = 500;
63
78
  /** The Hessian is used again after a Newton step whose actual reduction is within this ratio of the predicted one */
64
79
  const HESSIAN_REUSE_RATIO = 0.75;
80
+ /** A restart from a boundary point must lower the criterion by more than this times max(1, |criterion|) ... */
81
+ const RESTART_THRESHOLD = 1e-8;
82
+ /** ... and there are at most this many restarts */
83
+ const MAX_RESTARTS = 50;
84
+ /** The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y| */
85
+ const EXACT_FIT = 1e-12;
86
+ const EXACT_FIT_ERROR = "lmer: the response is fitted exactly by the fixed effects (a constant response, for example), so the residual variance is 0";
65
87
  const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
66
88
  /** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
67
89
  function symmetricEigen(a0) {
@@ -185,11 +207,14 @@ const sparseCriterion = (s, theta, reml) => {
185
207
  const r = profiledDeviance(s, theta, reml, { gradient: true });
186
208
  return { f: r.deviance, g: r.gradient };
187
209
  };
188
- /** The minimiser of the criterion over θ, subject to the lower bounds (see the header) */
189
- function minimiseCriterion(s, reml, criterion) {
210
+ /**
211
+ * A local minimiser of the criterion over θ, subject to the lower bounds (see the header), started at `start`, with
212
+ * the elements in `held` kept at exactly 0 throughout (never free, never released); with its criterion
213
+ */
214
+ function localMinimum(s, reml, criterion, start, held = new Set()) {
190
215
  const diagonal = s.lower.map((b) => b === 0);
191
216
  const evaluate = (theta) => criterion(s, theta, reml);
192
- let theta = s.theta.slice();
217
+ let theta = start.map((v, j) => (held.has(j) ? 0 : v));
193
218
  let { f, g } = evaluate(theta);
194
219
  /** Diagonal elements held at exactly 0 */
195
220
  const fixed = new Set();
@@ -269,7 +294,7 @@ function minimiseCriterion(s, reml, criterion) {
269
294
  const leaveAlongNegativeCurvature = () => {
270
295
  if (fixed.size === 0)
271
296
  return false;
272
- const set = theta.map((_, j) => j);
297
+ const set = theta.map((_, j) => j).filter((j) => !held.has(j));
273
298
  const eig = symmetricEigen(hessian(set));
274
299
  const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
275
300
  const k = eig.values.indexOf(Math.min(...eig.values));
@@ -289,7 +314,7 @@ function minimiseCriterion(s, reml, criterion) {
289
314
  return true;
290
315
  };
291
316
  for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
292
- const free = theta.map((_, j) => j).filter((j) => !fixed.has(j));
317
+ const free = theta.map((_, j) => j).filter((j) => !fixed.has(j) && !held.has(j));
293
318
  if (free.length > 0 && !iterate(free))
294
319
  continue;
295
320
  // converged on the free elements. Diagonal elements that reached 0 (to rounding) are held at exactly 0
@@ -320,7 +345,7 @@ function minimiseCriterion(s, reml, criterion) {
320
345
  for (const j of column)
321
346
  theta[j] = -theta[j];
322
347
  }
323
- return theta.map((v) => (v === 0 ? 0 : v)); // no -0
348
+ return { theta: theta.map((v) => (v === 0 ? 0 : v)), f }; // no -0
324
349
  }
325
350
  radius = Math.max(radius, INITIAL_RADIUS * BOUNDARY_CANDIDATE * scaleOf());
326
351
  previousNewton = Infinity;
@@ -328,6 +353,70 @@ function minimiseCriterion(s, reml, criterion) {
328
353
  }
329
354
  throw new Error(OPTIMISATION_FAILED);
330
355
  }
356
+ /**
357
+ * The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
358
+ * its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
359
+ * minimisation, until none is.
360
+ */
361
+ function minimiseCriterion(s, reml, criterion) {
362
+ /** The θ indices of each term's block (its whole lower triangle) */
363
+ const blocks = s.terms.map((t) => {
364
+ const nc = t.columns.length;
365
+ return Array.from({ length: (nc * (nc + 1)) / 2 }, (_, i) => t.thetaOffset + i);
366
+ });
367
+ let best = localMinimum(s, reml, criterion, s.theta);
368
+ for (let round = 0; round < MAX_RESTARTS; round++) {
369
+ let candidate;
370
+ for (const block of blocks) {
371
+ if (block.every((j) => best.theta[j] === 0))
372
+ continue;
373
+ const removed = localMinimum(s, reml, criterion, best.theta, new Set(block));
374
+ if (candidate === undefined || removed.f < candidate.f)
375
+ candidate = removed;
376
+ }
377
+ if (candidate === undefined || !(candidate.f < best.f - RESTART_THRESHOLD * Math.max(1, Math.abs(best.f))))
378
+ return best.theta;
379
+ best = localMinimum(s, reml, criterion, candidate.theta);
380
+ }
381
+ throw new Error(OPTIMISATION_FAILED);
382
+ }
383
+ /**
384
+ * The option checks of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section 3):
385
+ * `options` must be an object when given (not null, not an array); its own keys, in order, may be neither among those
386
+ * of R that are not supported (the first gives an Error) nor unknown (a TypeError listing all of them). A key whose
387
+ * value is `undefined` counts as given. Returns the options as an object (`{}` when not given).
388
+ */
389
+ export function checkOptions(fn, options, accepted, unsupported) {
390
+ if (options === undefined)
391
+ return {};
392
+ if (typeof options !== "object" || options === null || Array.isArray(options))
393
+ throw new TypeError("options must be an object");
394
+ const keys = Object.keys(options);
395
+ const notSupported = keys.find((k) => unsupported.includes(k));
396
+ if (notSupported !== undefined)
397
+ throw new Error(`${fn}: argument '${notSupported}' is not supported`);
398
+ const unknown = keys.filter((k) => !accepted.includes(k));
399
+ if (unknown.length > 0)
400
+ throw new TypeError(`unused argument${unknown.length === 1 ? "" : "s"} (${unknown.join(", ")})`);
401
+ return options;
402
+ }
403
+ /**
404
+ * A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
405
+ * other than NaN `false` for 0 and `true` otherwise; `null` and anything else are TypeErrors.
406
+ */
407
+ export function logicalOption(value, defaultValue) {
408
+ if (value === undefined)
409
+ return defaultValue;
410
+ if (typeof value === "boolean")
411
+ return value;
412
+ if (typeof value === "number" && !Number.isNaN(value))
413
+ return value !== 0;
414
+ if (value === null)
415
+ throw new TypeError("argument is of length zero");
416
+ throw new TypeError("argument is not interpretable as logical");
417
+ }
418
+ const LMER_KEYS = ["REML", "contrasts", "levels"];
419
+ const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action", "control", "start", "verbose", "devFunOnly"];
331
420
  /**
332
421
  * Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
333
422
  * quantities of its methods: `fixef()`, `coef(summary())` (without p-values), `vcov()`, `sigma()`, `VarCorr()`,
@@ -345,7 +434,7 @@ function minimiseCriterion(s, reml, criterion) {
345
434
  *
346
435
  * @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
347
436
  * @param data The data frame: an object of columns.
348
- * @param options `REML`, and `contrasts` and `levels` as in {@link lm}.
437
+ * @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
349
438
  *
350
439
  * @example
351
440
  * ```ts
@@ -364,7 +453,7 @@ function minimiseCriterion(s, reml, criterion) {
364
453
  *
365
454
  * @category Mixed models
366
455
  */
367
- export function lmer(formula, data, options = {}) {
456
+ export function lmer(formula, data, options) {
368
457
  return lmerWithCriterion(formula, data, options, sparseCriterion);
369
458
  }
370
459
  /**
@@ -387,17 +476,28 @@ export function lmerInternals(fit) {
387
476
  * test of the sparse computation fits with the dense reference implementation through it.
388
477
  */
389
478
  export function lmerWithCriterion(formula, data, options, criterion) {
390
- const reml = options.REML ?? true;
479
+ const given = checkOptions("lmer", options, LMER_KEYS, LMER_UNSUPPORTED);
480
+ const reml = logicalOption(given.REML, true);
481
+ options = { ...given, REML: reml };
391
482
  const modelOptions = {};
392
483
  if (options.contrasts !== undefined)
393
484
  modelOptions.contrasts = options.contrasts;
394
485
  if (options.levels !== undefined)
395
486
  modelOptions.levels = options.levels;
396
- const s = mixedModelStructure(formula, data, modelOptions);
487
+ const original = mixedModelStructure(formula, data, modelOptions);
488
+ const n = original.y.length;
489
+ const p = original.xColNames.length;
490
+ // β₀, the least-squares coefficients of y on X, and the residuals y − X β₀ (see the header)
491
+ const beta0 = p === 0 ? [] : qrCoef(qr(original.x), original.y);
492
+ const yc = original.y.map((y, i) => y - original.x[i].reduce((sum, v, k) => sum + v * beta0[k], 0));
493
+ // a response in the column space of X: the criterion is −∞ for every θ (no estimate)
494
+ const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);
495
+ if (maxAbs(yc) <= EXACT_FIT * maxAbs(original.y))
496
+ throw new Error(EXACT_FIT_ERROR);
497
+ const s = { ...original, y: yc };
397
498
  const theta = minimiseCriterion(s, reml, criterion);
398
499
  const r = profiledDeviance(s, theta, reml, { rxInverse: true });
399
- const n = s.y.length;
400
- const p = s.xColNames.length;
500
+ const fixef = r.beta.map((b, k) => b + beta0[k]);
401
501
  const twoPi = 2 * Math.PI;
402
502
  const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n));
403
503
  const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)));
@@ -405,7 +505,8 @@ export function lmerWithCriterion(formula, data, options, criterion) {
405
505
  const sigma = Math.sqrt(sigma2);
406
506
  const vcov = r.rxInverse.map((row) => row.map((v) => sigma2 * v));
407
507
  const stdError = vcov.map((row, i) => Math.sqrt(row[i]));
408
- const tValue = r.beta.map((b, i) => b / stdError[i]);
508
+ // (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
509
+ const tValue = fixef.map((b, i) => b / stdError[i]);
409
510
  // the blocks T_k and the variance components
410
511
  const varCorr = s.terms.map((term) => {
411
512
  const nc = term.columns.length;
@@ -416,6 +517,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
416
517
  t[i][j] = theta[k++];
417
518
  const cov = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
418
519
  const sd = cov.map((row, i) => Math.sqrt(row[i]));
520
+ // (a column with variance 0 has the correlations 0/0 = NaN with the others, as lme4's VarCorr: not a bug)
419
521
  const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
420
522
  return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
421
523
  });
@@ -431,15 +533,22 @@ export function lmerWithCriterion(formula, data, options, criterion) {
431
533
  })),
432
534
  };
433
535
  });
434
- const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
536
+ // the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
537
+ const fitted = s.x.map((xi) => xi.reduce((sum, v, k) => sum + v * fixef[k], 0));
538
+ const residuals = s.x.map((xi, i) => yc[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
435
539
  s.z.forEach((col, j) => {
436
540
  const bj = r.b[j];
437
- if (bj !== 0)
438
- col.rows.forEach((i, k) => (fitted[i] += col.values[k] * bj));
541
+ if (bj !== 0) {
542
+ col.rows.forEach((i, k) => {
543
+ fitted[i] += col.values[k] * bj;
544
+ residuals[i] -= col.values[k] * bj;
545
+ });
546
+ }
439
547
  });
440
- const residuals = s.y.map((y, i) => y - fitted[i]);
441
548
  const logLik = -(reml ? REMLcrit : deviance) / 2;
442
549
  const df = p + theta.length + 1;
550
+ // (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4; it is not
551
+ // meant to match the minimiser's relative boundary test)
443
552
  const singular = theta.some((v, j) => s.lower[j] === 0 && v < 1e-4);
444
553
  const messages = [...s.messages];
445
554
  if (singular)
@@ -451,8 +560,8 @@ export function lmerWithCriterion(formula, data, options, criterion) {
451
560
  rows: [...s.rows],
452
561
  theta,
453
562
  fixefNames: [...s.xColNames],
454
- fixef: r.beta,
455
- coefTable: { estimate: [...r.beta], stdError, tValue },
563
+ fixef,
564
+ coefTable: { estimate: [...fixef], stdError, tValue },
456
565
  vcov,
457
566
  sigma,
458
567
  varCorr,
@@ -469,6 +578,6 @@ export function lmerWithCriterion(formula, data, options, criterion) {
469
578
  messages,
470
579
  warnings: [...s.warnings],
471
580
  };
472
- internalsByFit.set(result, { structure: s, data, options: { ...options }, reml, criterion, theta: [...theta] });
581
+ internalsByFit.set(result, { structure: s, beta0, data, options, reml, criterion, theta: [...theta] });
473
582
  return result;
474
583
  }
@@ -3,7 +3,8 @@ import { type LmerResult } from "./lmer.js";
3
3
  import { type HypothesisType, type LmerHypotheses } from "./lmerHypotheses.js";
4
4
  import { type LmerFRow, type LmerSatterthwaite } from "./lmerTest.js";
5
5
  /**
6
- * Options of {@link lmerAnova} for one fit.
6
+ * Options of {@link lmerAnova} for one fit. R's `ddf` gives the Error `lmerAnova: argument 'ddf' is not supported`,
7
+ * any other key the TypeError `unused argument (<key>)`.
7
8
  *
8
9
  * @category Mixed models
9
10
  */
@@ -39,12 +40,16 @@ export interface LmerAnovaTable {
39
40
  warnings: string[];
40
41
  }
41
42
  /**
42
- * Options of {@link lmerAnova} for several fits.
43
+ * Options of {@link lmerAnova} for several fits. R's `modelNames` and `model.names` give the Error
44
+ * `lmerAnova: argument '<key>' is not supported`, any other key the TypeError `unused argument (<key>)`.
43
45
  *
44
46
  * @category Mixed models
45
47
  */
46
48
  export interface LmerCompareOptions {
47
- /** Refit the REML fits by maximum likelihood before comparing them (default `true`). */
49
+ /**
50
+ * Refit the REML fits by maximum likelihood before comparing them (default `true`). As in R's conditions, a number
51
+ * is `false` for 0 and `true` otherwise; `null` and other values are TypeErrors.
52
+ */
48
53
  refit?: boolean;
49
54
  /** The names of the models, in the order given (default `"MODEL1"`, `"MODEL2"`, ...). */
50
55
  names?: readonly string[];
@@ -7,7 +7,7 @@
7
7
  // fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
8
8
  import { pgamma1 } from "../distributions/gamma.js";
9
9
  import { Warnings } from "./glmFamily.js";
10
- import { lmerInternals, lmerWithCriterion } from "./lmer.js";
10
+ import { checkOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
11
11
  import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
12
12
  import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
13
13
  const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
@@ -74,6 +74,7 @@ function compareFits(fits, options) {
74
74
  if (fits.length < 2)
75
75
  throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
76
76
  const internals = fits.map(lmerInternals);
77
+ // (only the number of observations is compared, as lme4 does; the fits must also share the data object below)
77
78
  if (fits.some((f) => f.nObs !== fits[0].nObs))
78
79
  throw new Error("models were not all fitted to the same size of dataset");
79
80
  if (internals.some((i) => i.data !== internals[0].data))
@@ -90,7 +91,7 @@ function compareFits(fits, options) {
90
91
  else
91
92
  warnings.add("failed to find model names, assigning generic names");
92
93
  }
93
- const refit = options.refit ?? true;
94
+ const refit = logicalOption(options.refit, true);
94
95
  let logLik;
95
96
  if (refit) {
96
97
  if (fits.some((f) => f.REML))
@@ -129,6 +130,11 @@ function compareFits(fits, options) {
129
130
  warnings: warnings.list,
130
131
  };
131
132
  }
132
- export function lmerAnova(fit, options = {}) {
133
- return Array.isArray(fit) ? compareFits(fit, options) : anovaOfFit(fit, options);
133
+ export function lmerAnova(fit, options) {
134
+ if (Array.isArray(fit)) {
135
+ const checked = checkOptions("lmerAnova", options, ["refit", "names"], ["modelNames", "model.names"]);
136
+ // (the logical value is checked with the options, before the fits)
137
+ return compareFits(fit, { ...checked, refit: logicalOption(checked.refit, true) });
138
+ }
139
+ return anovaOfFit(fit, checkOptions("lmerAnova", options, ["type"], ["ddf"]));
134
140
  }
@@ -60,9 +60,10 @@ export interface LmerHypotheses {
60
60
  messages: string[];
61
61
  }
62
62
  /**
63
- * The fixed-effects design of an lmer fit, from lmer's inputs: the formula's fixed part coded on the model frame of
64
- * the whole formula (rows with a missing value in any of its variables dropped, unused levels dropped), the
65
- * contrasts given, and the aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
63
+ * The fixed-effects design of an lmer fit, from lmer's inputs: the formula without its random-effects terms (whose
64
+ * order of the variables names the terms and the interaction columns) coded on the model frame of the whole formula
65
+ * (rows with a missing value in any of its variables dropped, unused levels dropped), the contrasts given, and the
66
+ * aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
66
67
  */
67
68
  export declare function fixedEffectsDescription(formula: string, data: DataFrame, options?: FixedEffectsDescriptionOptions): FixedEffectsDescription;
68
69
  /**
@@ -21,9 +21,10 @@ import { parseFormula, splitBarTerms, termsOf } from "./formula.js";
21
21
  import { design } from "./modelMatrix.js";
22
22
  const ONE = { type: "num", value: 1, text: "1" };
23
23
  /**
24
- * The fixed-effects design of an lmer fit, from lmer's inputs: the formula's fixed part coded on the model frame of
25
- * the whole formula (rows with a missing value in any of its variables dropped, unused levels dropped), the
26
- * contrasts given, and the aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
24
+ * The fixed-effects design of an lmer fit, from lmer's inputs: the formula without its random-effects terms (whose
25
+ * order of the variables names the terms and the interaction columns) coded on the model frame of the whole formula
26
+ * (rows with a missing value in any of its variables dropped, unused levels dropped), the contrasts given, and the
27
+ * aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
27
28
  */
28
29
  export function fixedEffectsDescription(formula, data, options = {}) {
29
30
  const parsed = parseFormula(formula, false, true);
@@ -33,10 +34,11 @@ export function fixedEffectsDescription(formula, data, options = {}) {
33
34
  throw new TypeError("data must be an object of columns");
34
35
  const { fixed } = splitBarTerms(parsed.rhs);
35
36
  const fixedRhs = fixed ?? ONE;
36
- const contrastOptions = options.contrasts === undefined
37
- ? {}
38
- : { contrasts: options.contrasts, contrastVariables: termsOf({ response: parsed.response, rhs: fixedRhs }, Object.keys(data)).variables };
39
- const d = design(parsed, data, { ...(options.levels === undefined ? {} : { levels: options.levels }), dropUnusedLevels: true, ...contrastOptions }, fixedRhs);
37
+ // as lmer (src/models/mixedStructure.ts): the formula without the random-effects terms, on the model frame of the
38
+ // whole formula
39
+ const extraVariables = termsOf(parsed, Object.keys(data), fixedRhs).variables;
40
+ const contrastOptions = options.contrasts === undefined ? {} : { contrasts: options.contrasts };
41
+ const d = design({ response: parsed.response, rhs: fixedRhs }, data, { ...(options.levels === undefined ? {} : { levels: options.levels }), dropUnusedLevels: true, ...contrastOptions, extraVariables }, fixedRhs);
40
42
  const { terms, frame } = d;
41
43
  let keep = d.colNames.map((_, j) => j);
42
44
  if (keep.length > 0) {
@@ -25,10 +25,11 @@ export declare function hessianWarnings(values: readonly number[]): string[];
25
25
  */
26
26
  export declare function lmerSatterthwaite(fit: LmerResult): LmerSatterthwaite;
27
27
  /**
28
- * The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there). Internal: the test
29
- * evaluates them at lme4's optimum too, to compare with lmerTest's numerical derivatives at the same point.
28
+ * The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there), `beta0` added to the
29
+ * fixed effects (those of a fit's structure, whose response is y − X β₀). Internal: the test evaluates them at lme4's
30
+ * optimum too, to compare with lmerTest's numerical derivatives at the same point.
30
31
  */
31
- export declare function satterthwaiteAt(structure: MixedModelStructure, theta: readonly number[], reml: boolean): LmerSatterthwaite;
32
+ export declare function satterthwaiteAt(structure: MixedModelStructure, theta: readonly number[], reml: boolean, beta0?: readonly number[]): LmerSatterthwaite;
32
33
  /** The one-dimensional test of a contrast l (internal) */
33
34
  export interface TRow {
34
35
  estimate: number;
@@ -57,7 +58,8 @@ export declare function lmerFTest(fit: LmerResult, L: readonly (readonly number[
57
58
  /** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
58
59
  export declare function fTestOf(s: LmerSatterthwaite, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
59
60
  /**
60
- * Options of {@link lmerSummary}.
61
+ * Options of {@link lmerSummary}. Any other key is the TypeError `unused argument (<key>)` (R's lmerTest ignores
62
+ * unknown arguments with a warning).
61
63
  *
62
64
  * @category Mixed models
63
65
  */
@@ -124,16 +126,20 @@ export interface LmerSummary {
124
126
  */
125
127
  export declare function lmerSummary(fit: LmerResult, options?: LmerSummaryOptions): LmerSummary;
126
128
  /**
127
- * Options of {@link lmerContest}.
129
+ * Options of {@link lmerContest}. R's `collect`, `checkEstimability`, `check_estimability` and `ddf` give the Error
130
+ * `lmerContest: argument '<key>' is not supported`, any other key the TypeError `unused argument (<key>)`.
128
131
  *
129
132
  * @category Mixed models
130
133
  */
131
134
  export interface LmerContestOptions {
132
135
  /** The right-hand side of the hypothesis L β = rhs: one value, or one per row of L (default 0). */
133
136
  rhs?: number | readonly number[];
134
- /** Test the rows jointly with one F-test (default `true`), or each row with its own t-test (`false`). */
137
+ /**
138
+ * Test the rows jointly with one F-test (default `true`), or each row with its own t-test (`false`). As in R's
139
+ * conditions, a number is `false` for 0 and `true` otherwise; `null` and other values are TypeErrors.
140
+ */
135
141
  joint?: boolean;
136
- /** With `joint: false`, whether to add the confidence intervals (default `true`). */
142
+ /** With `joint: false`, whether to add the confidence intervals (default `true`; a logical value as `joint`). */
137
143
  confint?: boolean;
138
144
  /** The confidence level of the intervals (default 0.95). */
139
145
  level?: number;
@@ -17,7 +17,7 @@ import { pt1, qt1 } from "../distributions/t.js";
17
17
  import { eigen } from "../linalg/eigen.js";
18
18
  import { ginv } from "../linalg/kappa.js";
19
19
  import { Warnings } from "./glmFamily.js";
20
- import { lmerInternals } from "./lmer.js";
20
+ import { checkOptions, lmerInternals, logicalOption } from "./lmer.js";
21
21
  import { varparDerivatives } from "./mixedDerivatives.js";
22
22
  /** Eigenvalues of the Hessian within this of 0 (or below) are left out of its inverse and warned about */
23
23
  const HESSIAN_TOLERANCE = 1e-8;
@@ -57,15 +57,16 @@ export function lmerSatterthwaite(fit) {
57
57
  if (cached !== undefined)
58
58
  return cached;
59
59
  const internals = lmerInternals(fit);
60
- const result = satterthwaiteAt(internals.structure, internals.theta, internals.reml);
60
+ const result = satterthwaiteAt(internals.structure, internals.theta, internals.reml, internals.beta0);
61
61
  satterthwaiteByFit.set(fit, result);
62
62
  return result;
63
63
  }
64
64
  /**
65
- * The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there). Internal: the test
66
- * evaluates them at lme4's optimum too, to compare with lmerTest's numerical derivatives at the same point.
65
+ * The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there), `beta0` added to the
66
+ * fixed effects (those of a fit's structure, whose response is y − X β₀). Internal: the test evaluates them at lme4's
67
+ * optimum too, to compare with lmerTest's numerical derivatives at the same point.
67
68
  */
68
- export function satterthwaiteAt(structure, theta, reml) {
69
+ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
69
70
  const d = varparDerivatives(structure, theta, reml);
70
71
  const m = d.varpar.length;
71
72
  const e = eigen(d.hessian, { symmetric: true });
@@ -86,7 +87,7 @@ export function satterthwaiteAt(structure, theta, reml) {
86
87
  hessian: d.hessian,
87
88
  hessianEigenvalues: values,
88
89
  vcovVarpar,
89
- beta: d.beta,
90
+ beta: d.beta.map((b, k) => b + (beta0[k] ?? 0)),
90
91
  sigma: d.varpar[m - 1],
91
92
  vcov: d.vcov,
92
93
  jacobian: d.jacobian,
@@ -131,6 +132,7 @@ function jointDenDF(nu) {
131
132
  return nu.reduce((a, b) => a + b, 0) / nu.length;
132
133
  if (nu.some((v) => v <= 2))
133
134
  return 2;
135
+ // (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive)
134
136
  const e = nu.reduce((sum, v) => sum + v / (v - 2), 0);
135
137
  return (2 * e) / (e - nu.length);
136
138
  }
@@ -216,8 +218,8 @@ export function fTestOf(s, L, rhs, warnings) {
216
218
  *
217
219
  * @category Mixed models
218
220
  */
219
- export function lmerSummary(fit, options = {}) {
220
- const ddf = options.ddf ?? "Satterthwaite";
221
+ export function lmerSummary(fit, options) {
222
+ const ddf = checkOptions("lmerSummary", options, ["ddf"], []).ddf ?? "Satterthwaite";
221
223
  if (ddf !== "Satterthwaite" && ddf !== "lme4")
222
224
  throw new RangeError(`ddf must be "Satterthwaite" or "lme4", not ${JSON.stringify(ddf)}`);
223
225
  const internals = lmerInternals(fit);
@@ -241,6 +243,8 @@ export function lmerSummary(fit, options = {}) {
241
243
  warnings: [...s.warnings],
242
244
  };
243
245
  }
246
+ const CONTEST_KEYS = ["rhs", "joint", "confint", "level"];
247
+ const CONTEST_UNSUPPORTED = ["collect", "checkEstimability", "check_estimability", "ddf"];
244
248
  /** The rows of a contrast argument: a vector is one row; each row must have one value per fixed effect */
245
249
  function contrastRows(L, p) {
246
250
  if (!Array.isArray(L))
@@ -254,12 +258,13 @@ function contrastRows(L, p) {
254
258
  }
255
259
  return rows;
256
260
  }
257
- export function lmerContest(fit, L, options = {}) {
261
+ export function lmerContest(fit, L, options) {
262
+ options = checkOptions("lmerContest", options, CONTEST_KEYS, CONTEST_UNSUPPORTED);
263
+ const joint = logicalOption(options.joint, true);
264
+ const confint = logicalOption(options.confint, true);
258
265
  const internals = lmerInternals(fit);
259
266
  const p = internals.structure.xColNames.length;
260
267
  const rows = contrastRows(L, p);
261
- const joint = options.joint ?? true;
262
- const confint = options.confint ?? true;
263
268
  const level = options.level ?? 0.95;
264
269
  if (typeof level !== "number" || !(level >= 0 && level <= 1))
265
270
  throw new RangeError("level must be a number between 0 and 1");