@numero-uno-jpn/rstats 0.15.3 → 0.17.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 (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -53,9 +53,15 @@
53
53
  // on X, and adds β₀ back to the fixed effects: with a response of large mean, the rounding error of the fixed effects
54
54
  // from the normal equations would otherwise be large next to the residuals, and the criterion noisy. If y − X β₀ is
55
55
  // 0 (to 1e-12 max |y|), the criterion is −∞ for every θ and there is no estimate: an error.
56
+ import { ldexp, norm2 } from "../internal/summary.js";
56
57
  import { qr, qrCoef } from "../linalg/qr.js";
57
58
  import { profiledDeviance } from "./mixedDeviance.js";
58
59
  import { mixedModelStructure } from "./mixedStructure.js";
60
+ import { maxOf, minOf } from "../internal/extremes.js";
61
+ import { reported } from "../internal/warnings.js";
62
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
63
+ import { checkOptions } from "../internal/checkOptions.js";
64
+ const LMER_KEYS = ["REML", "contrasts", "levels"];
59
65
  /** Initial trust-region radius, relative to max(1, max |θ|) */
60
66
  const INITIAL_RADIUS = 0.25;
61
67
  /** Step of the central differences of the gradient that give the Hessian, relative to |θ_j| ... */
@@ -81,12 +87,28 @@ const HESSIAN_REUSE_RATIO = 0.75;
81
87
  const RESTART_THRESHOLD = 1e-8;
82
88
  /** ... and there are at most this many restarts */
83
89
  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;
90
+ /**
91
+ * The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y|: a
92
+ * few times the rounding error of the residuals, so that a response with a large mean and a small spread (around
93
+ * 1e12 with residuals of 0.1, say) is not taken for an exact fit. (64 eps rejected 1e16 plus values 0 to 180, whose
94
+ * residuals of about 90 are 40 ulps; issue #12)
95
+ */
96
+ const EXACT_FIT = 16 * Number.EPSILON;
86
97
  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";
87
98
  const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
88
99
  /** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
89
100
  function symmetricEigen(a0) {
101
+ // entries of extreme magnitude are scaled by a power of 2 (exact) first and the eigenvalues scaled back: the sums of
102
+ // squares below overflowed for entries around 1e200 (Infinity <= 1e-32 Infinity ended the sweeps at once)
103
+ let mx = 0;
104
+ for (const row of a0)
105
+ for (const v of row)
106
+ mx = Math.max(mx, Math.abs(v));
107
+ const k = mx === 0 || !Number.isFinite(mx) || (mx >= 2 ** -256 && mx <= 2 ** 256) ? 0 : Math.floor(Math.log2(mx));
108
+ if (k !== 0) {
109
+ const r = symmetricEigen(a0.map((row) => row.map((v) => ldexp(v, -k))));
110
+ return { values: r.values.map((v) => ldexp(v, k)), vectors: r.vectors };
111
+ }
90
112
  const m = a0.length;
91
113
  const a = a0.map((row) => row.slice());
92
114
  const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
@@ -134,7 +156,8 @@ function symmetricEigen(a0) {
134
156
  }
135
157
  return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
136
158
  }
137
- const norm = (x) => Math.sqrt(x.reduce((sum, v) => sum + v * v, 0));
159
+ // without overflow of the squares (src/internal/summary.ts)
160
+ const norm = norm2;
138
161
  const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
139
162
  /**
140
163
  * The step p that minimises g'p + p'Hp/2 subject to ‖p‖ ≤ radius (H = V diag(λ) V'), and whether it is the Newton
@@ -151,7 +174,7 @@ function trustRegionStep(g, eig, radius, zero, gradientZero) {
151
174
  coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
152
175
  return p;
153
176
  };
154
- const minValue = Math.min(...values);
177
+ const minValue = minOf(values);
155
178
  // the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
156
179
  // directions, and the step is inside the region
157
180
  if (minValue > -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
@@ -161,11 +184,11 @@ function trustRegionStep(g, eig, radius, zero, gradientZero) {
161
184
  }
162
185
  // on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
163
186
  const lowest = Math.max(0, -minValue);
164
- const lengthAt = (mu) => Math.sqrt(values.reduce((sum, l, k) => sum + (gt[k] / (l + mu)) ** 2, 0));
165
- const tiny = Math.max(zero, 1e-12 * Math.max(...values.map(Math.abs), 1));
187
+ const lengthAt = (mu) => norm2(values.map((l, k) => gt[k] / (l + mu)));
188
+ const tiny = Math.max(zero, 1e-12 * Math.max(maxOf(values.map(Math.abs)), 1));
166
189
  if (lengthAt(lowest + tiny) >= radius) {
167
190
  let lo = lowest + tiny;
168
- let hi = lowest + norm(g) / radius + Math.max(...values.map(Math.abs)) + tiny;
191
+ let hi = lowest + norm(g) / radius + maxOf(values.map(Math.abs)) + tiny;
169
192
  for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
170
193
  const mid = (lo + hi) / 2;
171
194
  if (lengthAt(mid) > radius)
@@ -247,12 +270,12 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
247
270
  const h = fresh ? hessian(free) : reusable.h;
248
271
  reusable = undefined;
249
272
  const eig = symmetricEigen(h);
250
- const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
273
+ const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
251
274
  const gFree = free.map((j) => g[j]);
252
275
  const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
253
276
  const trial = theta.slice();
254
277
  free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
255
- const size = Math.max(...step.map(Math.abs)) / scaleOf();
278
+ const size = maxOf(step.map(Math.abs)) / scaleOf();
256
279
  const next = evaluate(trial);
257
280
  if (!Number.isFinite(next.f))
258
281
  throw new Error(OPTIMISATION_FAILED);
@@ -296,8 +319,8 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
296
319
  return false;
297
320
  const set = theta.map((_, j) => j).filter((j) => !held.has(j));
298
321
  const eig = symmetricEigen(hessian(set));
299
- const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
300
- const k = eig.values.indexOf(Math.min(...eig.values));
322
+ const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
323
+ const k = eig.values.indexOf(minOf(eig.values));
301
324
  if (!(eig.values[k] < -zero))
302
325
  return false;
303
326
  const v = eig.vectors[k];
@@ -358,6 +381,51 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
358
381
  * its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
359
382
  * minimisation, until none is.
360
383
  */
384
+ /**
385
+ * The exponent e_k of 2 of each element of θ (internal; issue #11): that of the largest |value| of the column of Z of
386
+ * its row in the term (over the levels). With the columns of Z divided by c_i = 2^e_i, Λ' = C Λ: θ'_k = c_i θ_k, the
387
+ * blocks stay lower triangular with the same signs, and the model (and its criterion) is the same
388
+ */
389
+ export function thetaColumnExponents(s) {
390
+ const theta = new Array(s.theta.length).fill(0);
391
+ const z = new Array(s.z.length).fill(0);
392
+ for (const t of s.terms) {
393
+ const nc = t.columns.length;
394
+ const levels = s.groups[t.group].levels.length;
395
+ const e = Array.from({ length: nc }, (_, i) => {
396
+ let top = 0;
397
+ for (let l = 0; l < levels; l++)
398
+ for (const v of s.z[t.zOffset + l * nc + i].values)
399
+ top = Math.max(top, Math.abs(v));
400
+ return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
401
+ });
402
+ for (let l = 0; l < levels; l++)
403
+ for (let i = 0; i < nc; i++)
404
+ z[t.zOffset + l * nc + i] = e[i];
405
+ let k = t.thetaOffset;
406
+ for (let j = 0; j < nc; j++)
407
+ for (let i = j; i < nc; i++)
408
+ theta[k++] = e[i];
409
+ }
410
+ return { theta, z };
411
+ }
412
+ /**
413
+ * The minimiser over θ, computed on Z with its columns divided by powers of 2 (thetaColumnExponents) and returned in
414
+ * the units of the given Z: a column of x times 1e6 (or 1e-5) made θ of the slope 1e-6 (1e5) and the minimisation, whose
415
+ * steps and tolerances do not tell the elements apart, failed (issue #11; lme4 stops elsewhere with a warning)
416
+ */
417
+ function minimiseCriterionScaled(s, reml, criterion) {
418
+ const e = thetaColumnExponents(s);
419
+ if (e.z.every((v) => v === 0))
420
+ return minimiseCriterion(s, reml, criterion);
421
+ // (both Z and the terms' left-hand side matrices, from which the criterion forms its products)
422
+ const scaled = {
423
+ ...s,
424
+ z: s.z.map((col, j) => ({ rows: col.rows, values: col.values.map((v) => ldexp(v, -e.z[j])) })),
425
+ terms: s.terms.map((t) => ({ ...t, matrix: t.matrix.map((row) => row.map((v, i) => ldexp(v, -e.z[t.zOffset + i]))) })),
426
+ };
427
+ return minimiseCriterion(scaled, reml, criterion).map((v, k) => ldexp(v, -e.theta[k]));
428
+ }
361
429
  function minimiseCriterion(s, reml, criterion) {
362
430
  /** The θ indices of each term's block (its whole lower triangle) */
363
431
  const blocks = s.terms.map((t) => {
@@ -381,24 +449,20 @@ function minimiseCriterion(s, reml, criterion) {
381
449
  throw new Error(OPTIMISATION_FAILED);
382
450
  }
383
451
  /**
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).
452
+ * The first option check of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section
453
+ * 3): `options` must be an object when given (not null, not an array), and none of its own keys, in order, among those
454
+ * of R that are not supported (the first gives an Error naming it). A key whose value is `undefined` counts as given.
455
+ * The unknown keys are checked after it (a RangeError of checkOptions, generated by scripts/option-keys.mjs, which
456
+ * keeps a first statement calling this function before its checks).
388
457
  */
389
- export function checkOptions(fn, options, accepted, unsupported) {
458
+ export function checkLmerOptions(fn, options, unsupported) {
390
459
  if (options === undefined)
391
- return {};
460
+ return;
392
461
  if (typeof options !== "object" || options === null || Array.isArray(options))
393
462
  throw new TypeError("options must be an object");
394
- const keys = Object.keys(options);
395
- const notSupported = keys.find((k) => unsupported.includes(k));
463
+ const notSupported = Object.keys(options).find((k) => unsupported.includes(k));
396
464
  if (notSupported !== undefined)
397
465
  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
466
  }
403
467
  /**
404
468
  * A logical option as R's conditions take it (internal): `undefined` gives the default, a boolean itself, a number
@@ -415,7 +479,6 @@ export function logicalOption(value, defaultValue) {
415
479
  throw new TypeError("argument is of length zero");
416
480
  throw new TypeError("argument is not interpretable as logical");
417
481
  }
418
- const LMER_KEYS = ["REML", "contrasts", "levels"];
419
482
  const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action", "control", "start", "verbose", "devFunOnly"];
420
483
  /**
421
484
  * Fit a linear mixed model by REML (default) or maximum likelihood. Equivalent to `lme4::lmer()` in R. With the
@@ -432,6 +495,10 @@ const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action"
432
495
  * differ in the 5th to 9th significant digit). Elements on the boundary are exactly 0, and the fit is then singular.
433
496
  * The computation is sparse (a sparse Cholesky factorisation, as in lme4), so many groups are handled quickly.
434
497
  *
498
+ * The functions that take the fit ({@link lmerSummary}, {@link lmerAnova}, {@link lmerContest} and the others) need
499
+ * the object `lmer` returned itself: a copy of it (`structuredClone`, `{ ...fit }`, JSON or `postMessage`) lacks the
500
+ * internal values they use and is a TypeError. The fields of a copy keep their values.
501
+ *
435
502
  * @param formula A formula such as `"Reaction ~ Days + (Days | Subject)"`.
436
503
  * @param data The data frame: an object of columns.
437
504
  * @param options `REML`, and `contrasts` and `levels` as in {@link lm} (see {@link LmerOptions} for the keys accepted).
@@ -454,7 +521,9 @@ const LMER_UNSUPPORTED = ["weights", "offset", "subset", "naAction", "na.action"
454
521
  * @category Mixed models
455
522
  */
456
523
  export function lmer(formula, data, options) {
457
- return lmerWithCriterion(formula, data, options, sparseCriterion);
524
+ checkLmerOptions("lmer", options, LMER_UNSUPPORTED);
525
+ checkOptions(options, LMER_KEYS, "lmer"); // generated: option-keys.mjs
526
+ return reported("lmer", lmerWithCriterion(formula, data, options, sparseCriterion));
458
527
  }
459
528
  /**
460
529
  * The internals of every result returned by {@link lmer} (and {@link lmerWithCriterion}), keyed by the result object
@@ -476,7 +545,7 @@ export function lmerInternals(fit) {
476
545
  * test of the sparse computation fits with the dense reference implementation through it.
477
546
  */
478
547
  export function lmerWithCriterion(formula, data, options, criterion) {
479
- const given = checkOptions("lmer", options, LMER_KEYS, LMER_UNSUPPORTED);
548
+ const given = options ?? {};
480
549
  const reml = logicalOption(given.REML, true);
481
550
  options = { ...given, REML: reml };
482
551
  const modelOptions = {};
@@ -485,6 +554,9 @@ export function lmerWithCriterion(formula, data, options, criterion) {
485
554
  if (options.levels !== undefined)
486
555
  modelOptions.levels = options.levels;
487
556
  const original = mixedModelStructure(formula, data, modelOptions);
557
+ // as R (#297: an infinite response passed the exact-fit check below as Infinity <= Infinity, or failed inside the QR)
558
+ if (original.y.some((v) => !Number.isFinite(v)))
559
+ throw new RangeError("NA/NaN/Inf in 'y'");
488
560
  const n = original.y.length;
489
561
  const p = original.xColNames.length;
490
562
  // β₀, the least-squares coefficients of y on X, and the residuals y − X β₀ (see the header)
@@ -492,19 +564,29 @@ export function lmerWithCriterion(formula, data, options, criterion) {
492
564
  const yc = original.y.map((y, i) => y - original.x[i].reduce((sum, v, k) => sum + v * beta0[k], 0));
493
565
  // a response in the column space of X: the criterion is −∞ for every θ (no estimate)
494
566
  const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);
495
- if (maxAbs(yc) <= EXACT_FIT * maxAbs(original.y))
567
+ const ycMax = maxAbs(yc);
568
+ if (ycMax <= EXACT_FIT * maxAbs(original.y))
496
569
  throw new Error(EXACT_FIT_ERROR);
497
570
  const s = { ...original, y: yc };
498
- const theta = minimiseCriterion(s, reml, criterion);
499
- const r = profiledDeviance(s, theta, reml, { rxInverse: true });
500
- const fixef = r.beta.map((b, k) => b + beta0[k]);
571
+ // A response whose squares overflow or underflow (|y − X β₀| beyond 2^±500; 1e200 made the penalised sum of squares
572
+ // Infinity and the minimisation fail, R's sigma Inf) is fitted divided by 2^ky (exact): θ does not depend on it, and
573
+ // β, b, σ and the residuals scale back by 2^ky, the variances by 4^ky, the criteria shift by 2 n ky log 2. Otherwise
574
+ // ky = 0 and nothing changes (issue #9)
575
+ const ky = ycMax > 2 ** 500 || ycMax < 2 ** -500 ? Math.floor(Math.log2(ycMax)) : 0;
576
+ const sScaled = ky === 0 ? s : { ...s, y: yc.map((v) => ldexp(v, -ky)) };
577
+ const theta = minimiseCriterionScaled(sScaled, reml, criterion);
578
+ const r = profiledDeviance(sScaled, theta, reml, { rxInverse: true });
579
+ const up = (v) => ldexp(v, ky);
580
+ const fixef = r.beta.map((b, k) => up(b) + beta0[k]);
501
581
  const twoPi = 2 * Math.PI;
502
- const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n));
503
- const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)));
582
+ const logScale = 2 * ky * Math.LN2;
583
+ const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n) + logScale);
584
+ const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)) + logScale);
585
+ // (σ² of the scaled response; the variances below are 4^ky times what is formed from it)
504
586
  const sigma2 = r.prss / (reml ? n - p : n);
505
- const sigma = Math.sqrt(sigma2);
506
- const vcov = r.rxInverse.map((row) => row.map((v) => sigma2 * v));
507
- const stdError = vcov.map((row, i) => Math.sqrt(row[i]));
587
+ const sigma = up(Math.sqrt(sigma2));
588
+ const vcov = r.rxInverse.map((row) => row.map((v) => ldexp(sigma2 * v, 2 * ky)));
589
+ const stdError = r.rxInverse.map((row, i) => up(Math.sqrt(sigma2 * row[i])));
508
590
  // (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
509
591
  const tValue = fixef.map((b, i) => b / stdError[i]);
510
592
  // the blocks T_k and the variance components
@@ -515,10 +597,11 @@ export function lmerWithCriterion(formula, data, options, criterion) {
515
597
  for (let j = 0; j < nc; j++)
516
598
  for (let i = j; i < nc; i++)
517
599
  t[i][j] = theta[k++];
518
- const cov = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
519
- const sd = cov.map((row, i) => Math.sqrt(row[i]));
600
+ const covScaled = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
601
+ const sdScaled = covScaled.map((row, i) => Math.sqrt(row[i]));
602
+ const sd = sdScaled.map(up);
520
603
  // (a column with variance 0 has the correlations 0/0 = NaN with the others, as lme4's VarCorr: not a bug)
521
- const corr = cov.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
604
+ const corr = covScaled.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sdScaled[i] * sdScaled[j]))));
522
605
  return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
523
606
  });
524
607
  const ranef = s.groups.map((g, gi) => {
@@ -529,22 +612,25 @@ export function lmerWithCriterion(formula, data, options, criterion) {
529
612
  columns: terms.flatMap((t) => t.columns),
530
613
  values: g.levels.map((_, l) => terms.flatMap((t) => {
531
614
  const nc = t.columns.length;
532
- return t.columns.map((_, j) => r.b[t.zOffset + l * nc + j]);
615
+ return t.columns.map((_, j) => up(r.b[t.zOffset + l * nc + j]));
533
616
  })),
534
617
  };
535
618
  });
536
619
  // the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
537
620
  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));
621
+ // (the residuals on the scaled response, scaled back)
622
+ const residuals = s.x.map((xi, i) => sScaled.y[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
539
623
  s.z.forEach((col, j) => {
540
624
  const bj = r.b[j];
541
625
  if (bj !== 0) {
542
626
  col.rows.forEach((i, k) => {
543
- fitted[i] += col.values[k] * bj;
627
+ fitted[i] += col.values[k] * up(bj);
544
628
  residuals[i] -= col.values[k] * bj;
545
629
  });
546
630
  }
547
631
  });
632
+ if (ky !== 0)
633
+ residuals.forEach((v, i) => (residuals[i] = up(v)));
548
634
  const logLik = -(reml ? REMLcrit : deviance) / 2;
549
635
  const df = p + theta.length + 1;
550
636
  // (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4; it is not
@@ -578,6 +664,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
578
664
  messages,
579
665
  warnings: [...s.warnings],
580
666
  };
581
- internalsByFit.set(result, { structure: s, beta0, data, options, reml, criterion, theta: [...theta] });
667
+ const snapshot = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.slice()]));
668
+ internalsByFit.set(result, { structure: s, beta0, data, snapshot, options, reml, criterion, theta: [...theta] });
582
669
  return result;
583
670
  }
@@ -1,10 +1,10 @@
1
- import { Warnings } from "./glmFamily.js";
1
+ import { Warnings } from "../internal/warnings.js";
2
2
  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
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
+ * any other key a RangeError.
8
8
  *
9
9
  * @category Mixed models
10
10
  */
@@ -41,7 +41,7 @@ export interface LmerAnovaTable {
41
41
  }
42
42
  /**
43
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>)`.
44
+ * `lmerAnova: argument '<key>' is not supported`, any other key a RangeError.
45
45
  *
46
46
  * @category Mixed models
47
47
  */
@@ -6,14 +6,17 @@
6
6
  // matrices come from src/models/lmerHypotheses.ts, the F-tests from src/models/lmerTest.ts; the comparison refits REML
7
7
  // fits by maximum likelihood with lmer's own minimiser (the exact ML optimum).
8
8
  import { pgamma1 } from "../distributions/gamma.js";
9
- import { Warnings } from "./glmFamily.js";
10
- import { checkOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
9
+ import { checkOptions } from "../internal/checkOptions.js";
10
+ import { nestedColumns } from "./estimable.js";
11
+ import { reported, Warnings } from "../internal/warnings.js";
12
+ import { checkLmerOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
11
13
  import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
12
14
  import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
13
15
  const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
14
16
  /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
15
17
  export function anovaHypotheses(fit, type) {
16
- const { structure, data, options } = lmerInternals(fit);
18
+ // the hypotheses from the data as it was at the fit (the data object may have changed since)
19
+ const { structure, snapshot: data, options } = lmerInternals(fit);
17
20
  const descOptions = {};
18
21
  if (options.contrasts !== undefined)
19
22
  descOptions.contrasts = options.contrasts;
@@ -70,6 +73,17 @@ function anovaOfFit(fit, options) {
70
73
  warnings: warnings.list,
71
74
  };
72
75
  }
76
+ /** Whether two copies of a data frame hold the same columns and values (NaN equal to NaN) */
77
+ function sameFrame(a, b) {
78
+ const keys = Object.keys(a);
79
+ if (keys.length !== Object.keys(b).length)
80
+ return false;
81
+ return keys.every((k) => {
82
+ const u = a[k];
83
+ const v = b[k];
84
+ return v !== undefined && u.length === v.length && Array.prototype.every.call(u, (x, i) => Object.is(x, v[i]));
85
+ });
86
+ }
73
87
  function compareFits(fits, options) {
74
88
  if (fits.length < 2)
75
89
  throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
@@ -79,6 +93,17 @@ function compareFits(fits, options) {
79
93
  throw new Error("models were not all fitted to the same size of dataset");
80
94
  if (internals.some((i) => i.data !== internals[0].data))
81
95
  throw new Error("all models must be fit to the same data object");
96
+ // (the same object changed between the fits holds different data)
97
+ if (internals.some((i) => !sameFrame(i.snapshot, internals[0].snapshot)))
98
+ throw new Error("all models must be fit to the same data object");
99
+ // A likelihood ratio compares likelihoods of the same observations: the same rows of the data and the same response
100
+ // (lme4 compares only the number of rows, and returns a test for fits of different rows or responses)
101
+ const sameRows = (r) => r.length === fits[0].rows.length && r.every((v, i) => v === fits[0].rows[i]);
102
+ if (fits.some((f) => !sameRows(f.rows)))
103
+ throw new Error("models were not all fitted to the same rows of the data");
104
+ const response = (f) => f.formula.slice(0, f.formula.indexOf("~")).replace(/\s+/g, "");
105
+ if (fits.some((f) => response(f) !== response(fits[0])))
106
+ throw new Error("models were not all fitted to the same response");
82
107
  const warnings = new Warnings();
83
108
  const messages = [];
84
109
  let names = fits.map((_, i) => `MODEL${i + 1}`);
@@ -99,8 +124,8 @@ function compareFits(fits, options) {
99
124
  logLik = fits.map((f, i) => {
100
125
  if (!f.REML)
101
126
  return f.logLik;
102
- const { data, options: o, criterion } = internals[i];
103
- return lmerWithCriterion(f.formula, data, { ...o, REML: false }, criterion).logLik;
127
+ const { snapshot, options: o, criterion } = internals[i];
128
+ return lmerWithCriterion(f.formula, snapshot, { ...o, REML: false }, criterion).logLik;
104
129
  });
105
130
  }
106
131
  else {
@@ -113,7 +138,16 @@ function compareFits(fits, options) {
113
138
  const n = fits[0].nObs;
114
139
  const npar = order.map((i) => fits[i].df);
115
140
  const ll = order.map((i) => logLik[i]);
116
- const Chisq = ll.map((v, k) => (k === 0 ? NaN : 2 * Math.max(0, v - ll[k - 1])));
141
+ // A likelihood ratio test needs the smaller fit to be a special case of the larger one (lme4 gives a p-value for any
142
+ // pair): its fixed-effect columns among the larger fit's, and each of its random-effect terms within a term of the
143
+ // same grouping factor there ((1 | g) + (0 + x | g) within (1 + x | g), not the converse). Otherwise no test (AIC
144
+ // and BIC still compare the fits). The fixed effects are compared as column spaces (the fits use the same rows of the
145
+ // same data): by their names, the same factor in other contrasts (contr.sum against contr.treatment) looked not
146
+ // nested and was not tested (issue #8)
147
+ const nestedIn = (small, large) => nestedColumns(lmerInternals(small).structure.x, lmerInternals(large).structure.x) &&
148
+ small.varCorr.every((t) => large.varCorr.some((u) => u.group === t.group && t.columns.every((c) => u.columns.includes(c))));
149
+ const nested = order.map((i, k) => k > 0 && nestedIn(fits[order[k - 1]], fits[i]));
150
+ const Chisq = ll.map((v, k) => (k === 0 || !nested[k] ? NaN : 2 * Math.max(0, v - ll[k - 1])));
117
151
  const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
118
152
  const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
119
153
  return {
@@ -132,9 +166,13 @@ function compareFits(fits, options) {
132
166
  }
133
167
  export function lmerAnova(fit, options) {
134
168
  if (Array.isArray(fit)) {
135
- const checked = checkOptions("lmerAnova", options, ["refit", "names"], ["modelNames", "model.names"]);
169
+ checkLmerOptions("lmerAnova", options, ["modelNames", "model.names"]);
170
+ checkOptions(options, ["refit", "names"], "lmerAnova");
171
+ const checked = (options ?? {});
136
172
  // (the logical value is checked with the options, before the fits)
137
- return compareFits(fit, { ...checked, refit: logicalOption(checked.refit, true) });
173
+ return reported("lmerAnova", compareFits(fit, { ...checked, refit: logicalOption(checked.refit, true) }), ...fit);
138
174
  }
139
- return anovaOfFit(fit, checkOptions("lmerAnova", options, ["type"], ["ddf"]));
175
+ checkLmerOptions("lmerAnova", options, ["ddf"]);
176
+ checkOptions(options, ["type"], "lmerAnova");
177
+ return reported("lmerAnova", anovaOfFit(fit, (options ?? {})), fit);
140
178
  }
@@ -68,8 +68,12 @@ export interface LmerHypotheses {
68
68
  export declare function fixedEffectsDescription(formula: string, data: DataFrame, options?: FixedEffectsDescriptionOptions): FixedEffectsDescription;
69
69
  /**
70
70
  * The Doolittle factorisation S = L U of a symmetric matrix without pivoting: L unit lower triangular, U upper
71
- * triangular; a column of L below a pivot |U_ii| < 1e-6 is 0, and entries below 1e-6 in absolute value are set to 0
72
- * at the end.
71
+ * triangular. It is computed on S scaled to unit diagonal, D^-1/2 S D^-1/2 (D = diag S), where a column of L below a
72
+ * pivot |U_ii| < 1e-6 is 0 and entries below 1e-6 are set to 0; then L = D^1/2 L_n D^-1/2 and U = D^1/2 U_n D^1/2.
73
+ * lmerTest applies the thresholds to S itself, so its type I and II hypotheses depend on the units of the
74
+ * predictors: with a predictor scaled by 1e-6 its pivot fell below 1e-6 and the type I test of an earlier term turned
75
+ * into its type II test (R 4.5.2, lmerTest; docs/differences-from-r.md). Scaled, they only remove dependence and
76
+ * rounding
73
77
  */
74
78
  export declare function doolittle(s: readonly (readonly number[])[]): {
75
79
  L: number[][];
@@ -94,10 +94,22 @@ const columnsOf = (m, cols) => m.map((row) => cols.map((j) => row[j]));
94
94
  const DOOLITTLE_ZERO = 1e-6;
95
95
  /**
96
96
  * The Doolittle factorisation S = L U of a symmetric matrix without pivoting: L unit lower triangular, U upper
97
- * triangular; a column of L below a pivot |U_ii| < 1e-6 is 0, and entries below 1e-6 in absolute value are set to 0
98
- * at the end.
97
+ * triangular. It is computed on S scaled to unit diagonal, D^-1/2 S D^-1/2 (D = diag S), where a column of L below a
98
+ * pivot |U_ii| < 1e-6 is 0 and entries below 1e-6 are set to 0; then L = D^1/2 L_n D^-1/2 and U = D^1/2 U_n D^1/2.
99
+ * lmerTest applies the thresholds to S itself, so its type I and II hypotheses depend on the units of the
100
+ * predictors: with a predictor scaled by 1e-6 its pivot fell below 1e-6 and the type I test of an earlier term turned
101
+ * into its type II test (R 4.5.2, lmerTest; docs/differences-from-r.md). Scaled, they only remove dependence and
102
+ * rounding
99
103
  */
100
104
  export function doolittle(s) {
105
+ const r = s.map((row, i) => (row[i] > 0 ? Math.sqrt(row[i]) : 1));
106
+ const { L: Ln, U: Un } = doolittleUnit(s.map((row, i) => row.map((v, j) => v / r[i] / r[j])));
107
+ return {
108
+ L: Ln.map((row, i) => row.map((v, j) => (v * r[i]) / r[j])),
109
+ U: Un.map((row, i) => row.map((v, j) => v * r[i] * r[j])),
110
+ };
111
+ }
112
+ function doolittleUnit(s) {
101
113
  const k = s.length;
102
114
  const L = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (__, j) => (i === j ? 1 : 0)));
103
115
  const U = Array.from({ length: k }, () => new Array(k).fill(0));
@@ -1,4 +1,4 @@
1
- import { Warnings } from "./glmFamily.js";
1
+ import { Warnings } from "../internal/warnings.js";
2
2
  import { type LmerResult } from "./lmer.js";
3
3
  import type { MixedModelStructure } from "./mixedStructure.js";
4
4
  /**
@@ -16,6 +16,11 @@ export interface LmerSatterthwaite {
16
16
  vcov: number[][];
17
17
  jacobian: number[][][];
18
18
  warnings: string[];
19
+ /**
20
+ * The quantities above are those of the response divided by 2^scale (0 unless its squares overflow or underflow; issue
21
+ * #9): estimates, standard errors and right-hand sides are scaled by it in the tests, sums of squares by 4^scale
22
+ */
23
+ scale: number;
19
24
  }
20
25
  /** The warnings about the Hessian's eigenvalues (negative, or close to 0; internal) */
21
26
  export declare function hessianWarnings(values: readonly number[]): string[];
@@ -39,7 +44,7 @@ export interface TRow {
39
44
  pValue: number;
40
45
  }
41
46
  /** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
42
- export declare function tTestOf(s: LmerSatterthwaite, l: readonly number[], rhs: number, beta?: readonly number[]): TRow;
47
+ export declare function tTestOf(s: LmerSatterthwaite, l0: readonly number[], rhs0: number, beta?: readonly number[]): TRow;
43
48
  /** One row of an F table (internal): lmerTest's `Sum Sq`, `Mean Sq`, `NumDF`, `DenDF`, `F value`, `Pr(>F)` */
44
49
  export interface LmerFRow {
45
50
  sumSq: number;
@@ -49,6 +54,8 @@ export interface LmerFRow {
49
54
  F: number;
50
55
  pValue: number;
51
56
  }
57
+ /** The denominator degrees of freedom of a joint test from those of its rotated contrasts (exported for the tests) */
58
+ export declare function jointDenDF(nu: readonly number[]): number;
52
59
  /**
53
60
  * The joint F-test of the rows of L (r × p) with Satterthwaite's denominator degrees of freedom (internal; the ANOVA
54
61
  * tables use it): undefined when the rows have rank 0 (no test). `rhs` has one value per row (default 0); a non-zero
@@ -56,10 +63,10 @@ export interface LmerFRow {
56
63
  */
57
64
  export declare function lmerFTest(fit: LmerResult, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
58
65
  /** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
59
- export declare function fTestOf(s: LmerSatterthwaite, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
66
+ export declare function fTestOf(s: LmerSatterthwaite, L0: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
60
67
  /**
61
- * Options of {@link lmerSummary}. Any other key is the TypeError `unused argument (<key>)` (R's lmerTest ignores
62
- * unknown arguments with a warning).
68
+ * Options of {@link lmerSummary}. Any other key is a RangeError (R's lmerTest ignores unknown arguments with a
69
+ * warning).
63
70
  *
64
71
  * @category Mixed models
65
72
  */
@@ -127,7 +134,7 @@ export interface LmerSummary {
127
134
  export declare function lmerSummary(fit: LmerResult, options?: LmerSummaryOptions): LmerSummary;
128
135
  /**
129
136
  * 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>)`.
137
+ * `lmerContest: argument '<key>' is not supported`, any other key a RangeError.
131
138
  *
132
139
  * @category Mixed models
133
140
  */