@numero-uno-jpn/rstats 0.15.3 → 0.16.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 (285) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -53,9 +53,11 @@
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";
59
61
  /** Initial trust-region radius, relative to max(1, max |θ|) */
60
62
  const INITIAL_RADIUS = 0.25;
61
63
  /** Step of the central differences of the gradient that give the Hessian, relative to |θ_j| ... */
@@ -81,12 +83,28 @@ const HESSIAN_REUSE_RATIO = 0.75;
81
83
  const RESTART_THRESHOLD = 1e-8;
82
84
  /** ... and there are at most this many restarts */
83
85
  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
+ /**
87
+ * The response is fitted exactly by the fixed effects when its least-squares residuals are below this × max |y|: a
88
+ * few times the rounding error of the residuals, so that a response with a large mean and a small spread (around
89
+ * 1e12 with residuals of 0.1, say) is not taken for an exact fit. (64 eps rejected 1e16 plus values 0 to 180, whose
90
+ * residuals of about 90 are 40 ulps; issue #12)
91
+ */
92
+ const EXACT_FIT = 16 * Number.EPSILON;
86
93
  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
94
  const OPTIMISATION_FAILED = "lmer: the minimisation of the criterion over theta did not converge";
88
95
  /** Eigenvalues and eigenvectors of a small symmetric matrix by cyclic Jacobi rotations; vectors[k] is the k-th vector */
89
96
  function symmetricEigen(a0) {
97
+ // entries of extreme magnitude are scaled by a power of 2 (exact) first and the eigenvalues scaled back: the sums of
98
+ // squares below overflowed for entries around 1e200 (Infinity <= 1e-32 Infinity ended the sweeps at once)
99
+ let mx = 0;
100
+ for (const row of a0)
101
+ for (const v of row)
102
+ mx = Math.max(mx, Math.abs(v));
103
+ const k = mx === 0 || !Number.isFinite(mx) || (mx >= 2 ** -256 && mx <= 2 ** 256) ? 0 : Math.floor(Math.log2(mx));
104
+ if (k !== 0) {
105
+ const r = symmetricEigen(a0.map((row) => row.map((v) => ldexp(v, -k))));
106
+ return { values: r.values.map((v) => ldexp(v, k)), vectors: r.vectors };
107
+ }
90
108
  const m = a0.length;
91
109
  const a = a0.map((row) => row.slice());
92
110
  const v = a.map((_, i) => a.map((_, j) => (i === j ? 1 : 0)));
@@ -134,7 +152,8 @@ function symmetricEigen(a0) {
134
152
  }
135
153
  return { values: a.map((row, i) => row[i]), vectors: a.map((_, k) => v.map((row) => row[k])) };
136
154
  }
137
- const norm = (x) => Math.sqrt(x.reduce((sum, v) => sum + v * v, 0));
155
+ // without overflow of the squares (src/internal/summary.ts)
156
+ const norm = norm2;
138
157
  const dot = (x, y) => x.reduce((sum, v, i) => sum + v * y[i], 0);
139
158
  /**
140
159
  * 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 +170,7 @@ function trustRegionStep(g, eig, radius, zero, gradientZero) {
151
170
  coef.forEach((c, k) => vectors[k].forEach((vi, i) => (p[i] += c * vi)));
152
171
  return p;
153
172
  };
154
- const minValue = Math.min(...values);
173
+ const minValue = minOf(values);
155
174
  // the Newton step, if the Hessian is positive semidefinite, the gradient has no component along its null
156
175
  // directions, and the step is inside the region
157
176
  if (minValue > -zero && values.every((l, k) => l > zero || Math.abs(gt[k]) <= gradientZero)) {
@@ -161,11 +180,11 @@ function trustRegionStep(g, eig, radius, zero, gradientZero) {
161
180
  }
162
181
  // on the boundary: p(μ) = −Σ gt_k / (λ_k + μ) v_k with ‖p(μ)‖ = radius, μ > max(0, −λ_min), by bisection
163
182
  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));
183
+ const lengthAt = (mu) => norm2(values.map((l, k) => gt[k] / (l + mu)));
184
+ const tiny = Math.max(zero, 1e-12 * Math.max(maxOf(values.map(Math.abs)), 1));
166
185
  if (lengthAt(lowest + tiny) >= radius) {
167
186
  let lo = lowest + tiny;
168
- let hi = lowest + norm(g) / radius + Math.max(...values.map(Math.abs)) + tiny;
187
+ let hi = lowest + norm(g) / radius + maxOf(values.map(Math.abs)) + tiny;
169
188
  for (let k = 0; k < 200 && hi - lo > 1e-15 * hi; k++) {
170
189
  const mid = (lo + hi) / 2;
171
190
  if (lengthAt(mid) > radius)
@@ -247,12 +266,12 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
247
266
  const h = fresh ? hessian(free) : reusable.h;
248
267
  reusable = undefined;
249
268
  const eig = symmetricEigen(h);
250
- const zero = EIGENVALUE_TOLERANCE * Math.max(...eig.values.map(Math.abs));
269
+ const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
251
270
  const gFree = free.map((j) => g[j]);
252
271
  const { step, newton } = trustRegionStep(gFree, eig, radius, zero, gradientTolerance());
253
272
  const trial = theta.slice();
254
273
  free.forEach((j, a) => (trial[j] = theta[j] + step[a]));
255
- const size = Math.max(...step.map(Math.abs)) / scaleOf();
274
+ const size = maxOf(step.map(Math.abs)) / scaleOf();
256
275
  const next = evaluate(trial);
257
276
  if (!Number.isFinite(next.f))
258
277
  throw new Error(OPTIMISATION_FAILED);
@@ -296,8 +315,8 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
296
315
  return false;
297
316
  const set = theta.map((_, j) => j).filter((j) => !held.has(j));
298
317
  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));
318
+ const zero = EIGENVALUE_TOLERANCE * maxOf(eig.values.map(Math.abs));
319
+ const k = eig.values.indexOf(minOf(eig.values));
301
320
  if (!(eig.values[k] < -zero))
302
321
  return false;
303
322
  const v = eig.vectors[k];
@@ -358,6 +377,51 @@ function localMinimum(s, reml, criterion, start, held = new Set()) {
358
377
  * its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
359
378
  * minimisation, until none is.
360
379
  */
380
+ /**
381
+ * The exponent e_k of 2 of each element of θ (internal; issue #11): that of the largest |value| of the column of Z of
382
+ * 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
383
+ * blocks stay lower triangular with the same signs, and the model (and its criterion) is the same
384
+ */
385
+ export function thetaColumnExponents(s) {
386
+ const theta = new Array(s.theta.length).fill(0);
387
+ const z = new Array(s.z.length).fill(0);
388
+ for (const t of s.terms) {
389
+ const nc = t.columns.length;
390
+ const levels = s.groups[t.group].levels.length;
391
+ const e = Array.from({ length: nc }, (_, i) => {
392
+ let top = 0;
393
+ for (let l = 0; l < levels; l++)
394
+ for (const v of s.z[t.zOffset + l * nc + i].values)
395
+ top = Math.max(top, Math.abs(v));
396
+ return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
397
+ });
398
+ for (let l = 0; l < levels; l++)
399
+ for (let i = 0; i < nc; i++)
400
+ z[t.zOffset + l * nc + i] = e[i];
401
+ let k = t.thetaOffset;
402
+ for (let j = 0; j < nc; j++)
403
+ for (let i = j; i < nc; i++)
404
+ theta[k++] = e[i];
405
+ }
406
+ return { theta, z };
407
+ }
408
+ /**
409
+ * The minimiser over θ, computed on Z with its columns divided by powers of 2 (thetaColumnExponents) and returned in
410
+ * 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
411
+ * steps and tolerances do not tell the elements apart, failed (issue #11; lme4 stops elsewhere with a warning)
412
+ */
413
+ function minimiseCriterionScaled(s, reml, criterion) {
414
+ const e = thetaColumnExponents(s);
415
+ if (e.z.every((v) => v === 0))
416
+ return minimiseCriterion(s, reml, criterion);
417
+ // (both Z and the terms' left-hand side matrices, from which the criterion forms its products)
418
+ const scaled = {
419
+ ...s,
420
+ z: s.z.map((col, j) => ({ rows: col.rows, values: col.values.map((v) => ldexp(v, -e.z[j])) })),
421
+ terms: s.terms.map((t) => ({ ...t, matrix: t.matrix.map((row) => row.map((v, i) => ldexp(v, -e.z[t.zOffset + i]))) })),
422
+ };
423
+ return minimiseCriterion(scaled, reml, criterion).map((v, k) => ldexp(v, -e.theta[k]));
424
+ }
361
425
  function minimiseCriterion(s, reml, criterion) {
362
426
  /** The θ indices of each term's block (its whole lower triangle) */
363
427
  const blocks = s.terms.map((t) => {
@@ -485,6 +549,9 @@ export function lmerWithCriterion(formula, data, options, criterion) {
485
549
  if (options.levels !== undefined)
486
550
  modelOptions.levels = options.levels;
487
551
  const original = mixedModelStructure(formula, data, modelOptions);
552
+ // as R (#297: an infinite response passed the exact-fit check below as Infinity <= Infinity, or failed inside the QR)
553
+ if (original.y.some((v) => !Number.isFinite(v)))
554
+ throw new RangeError("NA/NaN/Inf in 'y'");
488
555
  const n = original.y.length;
489
556
  const p = original.xColNames.length;
490
557
  // β₀, the least-squares coefficients of y on X, and the residuals y − X β₀ (see the header)
@@ -492,19 +559,29 @@ export function lmerWithCriterion(formula, data, options, criterion) {
492
559
  const yc = original.y.map((y, i) => y - original.x[i].reduce((sum, v, k) => sum + v * beta0[k], 0));
493
560
  // a response in the column space of X: the criterion is −∞ for every θ (no estimate)
494
561
  const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);
495
- if (maxAbs(yc) <= EXACT_FIT * maxAbs(original.y))
562
+ const ycMax = maxAbs(yc);
563
+ if (ycMax <= EXACT_FIT * maxAbs(original.y))
496
564
  throw new Error(EXACT_FIT_ERROR);
497
565
  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]);
566
+ // A response whose squares overflow or underflow (|y − X β₀| beyond 2^±500; 1e200 made the penalised sum of squares
567
+ // Infinity and the minimisation fail, R's sigma Inf) is fitted divided by 2^ky (exact): θ does not depend on it, and
568
+ // β, b, σ and the residuals scale back by 2^ky, the variances by 4^ky, the criteria shift by 2 n ky log 2. Otherwise
569
+ // ky = 0 and nothing changes (issue #9)
570
+ const ky = ycMax > 2 ** 500 || ycMax < 2 ** -500 ? Math.floor(Math.log2(ycMax)) : 0;
571
+ const sScaled = ky === 0 ? s : { ...s, y: yc.map((v) => ldexp(v, -ky)) };
572
+ const theta = minimiseCriterionScaled(sScaled, reml, criterion);
573
+ const r = profiledDeviance(sScaled, theta, reml, { rxInverse: true });
574
+ const up = (v) => ldexp(v, ky);
575
+ const fixef = r.beta.map((b, k) => up(b) + beta0[k]);
501
576
  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)));
577
+ const logScale = 2 * ky * Math.LN2;
578
+ const deviance = r.logDetL + n * (1 + Math.log((twoPi * r.prss) / n) + logScale);
579
+ const REMLcrit = r.logDetL + r.logDetRX + (n - p) * (1 + Math.log((twoPi * r.prss) / (n - p)) + logScale);
580
+ // (σ² of the scaled response; the variances below are 4^ky times what is formed from it)
504
581
  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]));
582
+ const sigma = up(Math.sqrt(sigma2));
583
+ const vcov = r.rxInverse.map((row) => row.map((v) => ldexp(sigma2 * v, 2 * ky)));
584
+ const stdError = r.rxInverse.map((row, i) => up(Math.sqrt(sigma2 * row[i])));
508
585
  // (a standard error of 0 gives ±Infinity or NaN, as R's division does: not guarded on purpose)
509
586
  const tValue = fixef.map((b, i) => b / stdError[i]);
510
587
  // the blocks T_k and the variance components
@@ -515,10 +592,11 @@ export function lmerWithCriterion(formula, data, options, criterion) {
515
592
  for (let j = 0; j < nc; j++)
516
593
  for (let i = j; i < nc; i++)
517
594
  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]));
595
+ const covScaled = t.map((ti) => t.map((tj) => sigma2 * ti.reduce((sum, v, m) => sum + v * tj[m], 0)));
596
+ const sdScaled = covScaled.map((row, i) => Math.sqrt(row[i]));
597
+ const sd = sdScaled.map(up);
520
598
  // (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]))));
599
+ const corr = covScaled.map((row, i) => row.map((v, j) => (i === j ? 1 : v / (sdScaled[i] * sdScaled[j]))));
522
600
  return { group: s.groups[term.group].name, columns: [...term.columns], sd, corr };
523
601
  });
524
602
  const ranef = s.groups.map((g, gi) => {
@@ -529,22 +607,25 @@ export function lmerWithCriterion(formula, data, options, criterion) {
529
607
  columns: terms.flatMap((t) => t.columns),
530
608
  values: g.levels.map((_, l) => terms.flatMap((t) => {
531
609
  const nc = t.columns.length;
532
- return t.columns.map((_, j) => r.b[t.zOffset + l * nc + j]);
610
+ return t.columns.map((_, j) => up(r.b[t.zOffset + l * nc + j]));
533
611
  })),
534
612
  };
535
613
  });
536
614
  // the residuals from y − X β₀ (the more accurate), the fitted values with the whole fixed effects
537
615
  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));
616
+ // (the residuals on the scaled response, scaled back)
617
+ const residuals = s.x.map((xi, i) => sScaled.y[i] - xi.reduce((sum, v, k) => sum + v * r.beta[k], 0));
539
618
  s.z.forEach((col, j) => {
540
619
  const bj = r.b[j];
541
620
  if (bj !== 0) {
542
621
  col.rows.forEach((i, k) => {
543
- fitted[i] += col.values[k] * bj;
622
+ fitted[i] += col.values[k] * up(bj);
544
623
  residuals[i] -= col.values[k] * bj;
545
624
  });
546
625
  }
547
626
  });
627
+ if (ky !== 0)
628
+ residuals.forEach((v, i) => (residuals[i] = up(v)));
548
629
  const logLik = -(reml ? REMLcrit : deviance) / 2;
549
630
  const df = p + theta.length + 1;
550
631
  // (an absolute threshold on θ's diagonal elements, as lme4's isSingular with its default tolerance 1e-4; it is not
@@ -578,6 +659,7 @@ export function lmerWithCriterion(formula, data, options, criterion) {
578
659
  messages,
579
660
  warnings: [...s.warnings],
580
661
  };
581
- internalsByFit.set(result, { structure: s, beta0, data, options, reml, criterion, theta: [...theta] });
662
+ const snapshot = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v.slice()]));
663
+ internalsByFit.set(result, { structure: s, beta0, data, snapshot, options, reml, criterion, theta: [...theta] });
582
664
  return result;
583
665
  }
@@ -6,6 +6,7 @@
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 { nestedColumns } from "./estimable.js";
9
10
  import { Warnings } from "./glmFamily.js";
10
11
  import { checkOptions, lmerInternals, lmerWithCriterion, logicalOption } from "./lmer.js";
11
12
  import { fixedEffectsDescription, lmerHypotheses } from "./lmerHypotheses.js";
@@ -13,7 +14,8 @@ import { fTestOf, lmerSatterthwaite } from "./lmerTest.js";
13
14
  const TYPES = { I: "I", II: "II", III: "III", 1: "I", 2: "II", 3: "III" };
14
15
  /** The hypotheses of a fit's ANOVA table of the given type (internal; the test uses them at other points too) */
15
16
  export function anovaHypotheses(fit, type) {
16
- const { structure, data, options } = lmerInternals(fit);
17
+ // the hypotheses from the data as it was at the fit (the data object may have changed since)
18
+ const { structure, snapshot: data, options } = lmerInternals(fit);
17
19
  const descOptions = {};
18
20
  if (options.contrasts !== undefined)
19
21
  descOptions.contrasts = options.contrasts;
@@ -70,6 +72,17 @@ function anovaOfFit(fit, options) {
70
72
  warnings: warnings.list,
71
73
  };
72
74
  }
75
+ /** Whether two copies of a data frame hold the same columns and values (NaN equal to NaN) */
76
+ function sameFrame(a, b) {
77
+ const keys = Object.keys(a);
78
+ if (keys.length !== Object.keys(b).length)
79
+ return false;
80
+ return keys.every((k) => {
81
+ const u = a[k];
82
+ const v = b[k];
83
+ return v !== undefined && u.length === v.length && Array.prototype.every.call(u, (x, i) => Object.is(x, v[i]));
84
+ });
85
+ }
73
86
  function compareFits(fits, options) {
74
87
  if (fits.length < 2)
75
88
  throw new TypeError("lmerAnova needs one fit, or an array of at least two fits to compare");
@@ -79,6 +92,17 @@ function compareFits(fits, options) {
79
92
  throw new Error("models were not all fitted to the same size of dataset");
80
93
  if (internals.some((i) => i.data !== internals[0].data))
81
94
  throw new Error("all models must be fit to the same data object");
95
+ // (the same object changed between the fits holds different data)
96
+ if (internals.some((i) => !sameFrame(i.snapshot, internals[0].snapshot)))
97
+ throw new Error("all models must be fit to the same data object");
98
+ // A likelihood ratio compares likelihoods of the same observations: the same rows of the data and the same response
99
+ // (lme4 compares only the number of rows, and returns a test for fits of different rows or responses)
100
+ const sameRows = (r) => r.length === fits[0].rows.length && r.every((v, i) => v === fits[0].rows[i]);
101
+ if (fits.some((f) => !sameRows(f.rows)))
102
+ throw new Error("models were not all fitted to the same rows of the data");
103
+ const response = (f) => f.formula.slice(0, f.formula.indexOf("~")).replace(/\s+/g, "");
104
+ if (fits.some((f) => response(f) !== response(fits[0])))
105
+ throw new Error("models were not all fitted to the same response");
82
106
  const warnings = new Warnings();
83
107
  const messages = [];
84
108
  let names = fits.map((_, i) => `MODEL${i + 1}`);
@@ -99,8 +123,8 @@ function compareFits(fits, options) {
99
123
  logLik = fits.map((f, i) => {
100
124
  if (!f.REML)
101
125
  return f.logLik;
102
- const { data, options: o, criterion } = internals[i];
103
- return lmerWithCriterion(f.formula, data, { ...o, REML: false }, criterion).logLik;
126
+ const { snapshot, options: o, criterion } = internals[i];
127
+ return lmerWithCriterion(f.formula, snapshot, { ...o, REML: false }, criterion).logLik;
104
128
  });
105
129
  }
106
130
  else {
@@ -113,7 +137,16 @@ function compareFits(fits, options) {
113
137
  const n = fits[0].nObs;
114
138
  const npar = order.map((i) => fits[i].df);
115
139
  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])));
140
+ // A likelihood ratio test needs the smaller fit to be a special case of the larger one (lme4 gives a p-value for any
141
+ // pair): its fixed-effect columns among the larger fit's, and each of its random-effect terms within a term of the
142
+ // same grouping factor there ((1 | g) + (0 + x | g) within (1 + x | g), not the converse). Otherwise no test (AIC
143
+ // and BIC still compare the fits). The fixed effects are compared as column spaces (the fits use the same rows of the
144
+ // same data): by their names, the same factor in other contrasts (contr.sum against contr.treatment) looked not
145
+ // nested and was not tested (issue #8)
146
+ const nestedIn = (small, large) => nestedColumns(lmerInternals(small).structure.x, lmerInternals(large).structure.x) &&
147
+ small.varCorr.every((t) => large.varCorr.some((u) => u.group === t.group && t.columns.every((c) => u.columns.includes(c))));
148
+ const nested = order.map((i, k) => k > 0 && nestedIn(fits[order[k - 1]], fits[i]));
149
+ const Chisq = ll.map((v, k) => (k === 0 || !nested[k] ? NaN : 2 * Math.max(0, v - ll[k - 1])));
117
150
  const Df = npar.map((v, k) => (k === 0 ? NaN : v - npar[k - 1]));
118
151
  const pValue = Chisq.map((x, k) => (k === 0 || Df[k] === 0 ? NaN : pgamma1(x, Df[k] / 2, 2, false, false)));
119
152
  return {
@@ -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));
@@ -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,7 +63,7 @@ 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
68
  * Options of {@link lmerSummary}. Any other key is the TypeError `unused argument (<key>)` (R's lmerTest ignores
62
69
  * unknown arguments with a warning).
@@ -16,8 +16,10 @@ import { pf1 } from "../distributions/f.js";
16
16
  import { pt1, qt1 } from "../distributions/t.js";
17
17
  import { eigen } from "../linalg/eigen.js";
18
18
  import { ginv } from "../linalg/kappa.js";
19
+ import { rangeExponent } from "../linalg/matrix.js";
19
20
  import { Warnings } from "./glmFamily.js";
20
- import { checkOptions, lmerInternals, logicalOption } from "./lmer.js";
21
+ import { ldexp } from "../internal/summary.js";
22
+ import { checkOptions, lmerInternals, logicalOption, thetaColumnExponents } from "./lmer.js";
21
23
  import { varparDerivatives } from "./mixedDerivatives.js";
22
24
  /** Eigenvalues of the Hessian within this of 0 (or below) are left out of its inverse and warned about */
23
25
  const HESSIAN_TOLERANCE = 1e-8;
@@ -67,9 +69,24 @@ export function lmerSatterthwaite(fit) {
67
69
  * optimum too, to compare with lmerTest's numerical derivatives at the same point.
68
70
  */
69
71
  export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
70
- const d = varparDerivatives(structure, theta, reml);
72
+ // a response whose squares overflow or underflow: the derivatives of the response divided by 2^scale (as lmer fits it)
73
+ let top = 0;
74
+ for (const v of structure.y)
75
+ top = Math.max(top, Math.abs(v));
76
+ const scale = top > 2 ** 500 || top < 2 ** -500 ? Math.floor(Math.log2(top)) : 0;
77
+ const st = scale === 0 ? structure : { ...structure, y: structure.y.map((v) => ldexp(v, -scale)) };
78
+ const d = varparDerivatives(st, theta, reml);
71
79
  const m = d.varpar.length;
72
- const e = eigen(d.hessian, { symmetric: true });
80
+ // The Hessian in coordinates of comparable scale, D H D: θ_k times 2^e_k (the columns of Z of its row; see
81
+ // thetaColumnExponents) and σ over a power of 2 near σ̂. Its eigenvalues are cut at the tolerance there, A' = 2 H'⁺
82
+ // and A = D A' D. In (θ, σ) themselves the curvature in σ scales as 1/σ² and that in θ with the columns of Z, so the
83
+ // absolute cut dropped directions by the units alone (response × 1e6: the df of x 7.4e8 for 31, as lmerTest's;
84
+ // issue #10)
85
+ const sigmaHat = d.varpar[m - 1];
86
+ const kSigma = sigmaHat > 0 && Number.isFinite(sigmaHat) ? Math.round(Math.log2(sigmaHat)) : 0;
87
+ const ex = [...thetaColumnExponents(structure).theta.map((v) => -v), kSigma];
88
+ const hScaled = d.hessian.map((row, i) => row.map((v, j) => ldexp(v, ex[i] + ex[j])));
89
+ const e = eigen(hScaled, { symmetric: true });
73
90
  const values = e.values;
74
91
  const vectors = e.vectors;
75
92
  const vcovVarpar = Array.from({ length: m }, () => new Array(m).fill(0));
@@ -82,16 +99,18 @@ export function satterthwaiteAt(structure, theta, reml, beta0 = []) {
82
99
  vcovVarpar[i][j] += vi * vectors[j][k];
83
100
  }
84
101
  });
102
+ vcovVarpar.forEach((row, i) => row.forEach((v, j) => (row[j] = ldexp(v, ex[i] + ex[j]))));
85
103
  return {
86
104
  varpar: d.varpar,
87
105
  hessian: d.hessian,
88
106
  hessianEigenvalues: values,
89
107
  vcovVarpar,
90
- beta: d.beta.map((b, k) => b + (beta0[k] ?? 0)),
108
+ beta: d.beta.map((b, k) => b + ldexp(beta0[k] ?? 0, -scale)),
91
109
  sigma: d.varpar[m - 1],
92
110
  vcov: d.vcov,
93
111
  jacobian: d.jacobian,
94
112
  warnings: hessianWarnings(values),
113
+ scale,
95
114
  };
96
115
  }
97
116
  const quadraticForm = (l, m) => {
@@ -108,32 +127,40 @@ const quadraticForm = (l, m) => {
108
127
  };
109
128
  const dot = (a, b) => a.reduce((s, v, i) => s + v * b[i], 0);
110
129
  /** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
111
- export function tTestOf(s, l, rhs, beta = s.beta) {
112
- if (l.some(Number.isNaN) || Number.isNaN(rhs))
130
+ export function tTestOf(s, l0, rhs0, beta = s.beta) {
131
+ if (l0.some(Number.isNaN) || Number.isNaN(rhs0))
113
132
  return { estimate: NaN, stdError: NaN, df: NaN, tValue: NaN, pValue: NaN };
133
+ // a contrast of extreme magnitude (1e160, 1e-200) divided by 2^k with its rhs: the test does not depend on it, and
134
+ // l'Vl overflowed or underflowed (#58); the estimate and the standard error are scaled back by 2^k
135
+ const k = rangeExponent(l0);
136
+ const l = k === 0 ? l0 : l0.map((v) => ldexp(v, -k));
137
+ const rhs = ldexp(rhs0, -k);
138
+ // (in the units of the scaled response, the estimate and the standard error scaled back; see LmerSatterthwaite.scale)
114
139
  const estimate = dot(l, beta);
115
140
  const variance = quadraticForm(l, s.vcov);
116
141
  const stdError = Math.sqrt(variance);
117
142
  const g = s.jacobian.map((j) => quadraticForm(l, j));
118
143
  const df = (2 * variance * variance) / quadraticForm(g, s.vcovVarpar);
119
- const tValue = (estimate - rhs) / stdError;
144
+ const tValue = (estimate - ldexp(rhs, -s.scale)) / stdError;
120
145
  const pValue = 2 * pt1(Math.abs(tValue), df, false, false);
121
- return { estimate, stdError, df, tValue, pValue };
146
+ return { estimate: ldexp(estimate, s.scale + k), stdError: ldexp(stdError, s.scale + k), df, tValue, pValue };
122
147
  }
123
148
  function fRowOf(s, f, numDF, denDF) {
124
149
  const s2 = s.sigma * s.sigma;
125
- return { sumSq: f * s2 * numDF, meanSq: f * s2, numDF, denDF, F: f, pValue: pf1(f, numDF, denDF, false, false) };
150
+ return { sumSq: ldexp(f * s2 * numDF, 2 * s.scale), meanSq: ldexp(f * s2, 2 * s.scale), numDF, denDF, F: f, pValue: pf1(f, numDF, denDF, false, false) };
126
151
  }
127
- /** The denominator degrees of freedom of a joint test from those of its rotated contrasts */
128
- function jointDenDF(nu) {
152
+ /** The denominator degrees of freedom of a joint test from those of its rotated contrasts (exported for the tests) */
153
+ export function jointDenDF(nu) {
129
154
  if (nu.length === 1)
130
155
  return nu[0];
131
- if (nu.every((v, i) => i === 0 || Math.abs(v - nu[i - 1]) < EQUAL_DF_TOLERANCE))
156
+ // (equal infinite df are equal: Inf - Inf is NaN, and all Inf gave NaN, an error in lmerTest)
157
+ if (nu.every((v, i) => i === 0 || v === nu[i - 1] || Math.abs(v - nu[i - 1]) < EQUAL_DF_TOLERANCE))
132
158
  return nu.reduce((a, b) => a + b, 0) / nu.length;
133
159
  if (nu.some((v) => v <= 2))
134
160
  return 2;
135
- // (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive)
136
- const e = nu.reduce((sum, v) => sum + v / (v - 2), 0);
161
+ // (as lmerTest: with every ν > 2 each term ν/(ν − 2) exceeds 1, so e > nu.length and the result is positive; the term
162
+ // of an infinite ν is its limit 1, where Inf / Inf was NaN)
163
+ const e = nu.reduce((sum, v) => sum + (v === Infinity ? 1 : v / (v - 2)), 0);
137
164
  return (2 * e) / (e - nu.length);
138
165
  }
139
166
  /**
@@ -145,13 +172,24 @@ export function lmerFTest(fit, L, rhs, warnings) {
145
172
  return fTestOf(lmerSatterthwaite(fit), L, rhs, warnings);
146
173
  }
147
174
  /** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
148
- export function fTestOf(s, L, rhs, warnings) {
149
- const r = L.length;
175
+ export function fTestOf(s, L0, rhs, warnings) {
176
+ const r = L0.length;
150
177
  if (r === 0)
151
178
  return undefined;
152
- const right = rhs ?? new Array(r).fill(0);
179
+ // L of extreme magnitude and its rhs divided by one power of 2 (the test does not depend on it; the same factor for
180
+ // every row keeps the eigenvectors of L V L', and with them the rotated contrasts and the df). L V L' overflowed or
181
+ // underflowed (#58)
182
+ const k = rangeExponent(L0.flat());
183
+ const L = k === 0 ? L0 : L0.map((row) => row.map((v) => ldexp(v, -k)));
184
+ // (the right-hand side in the units of the scaled response: tTestOf scales its own, the joint test below uses these)
185
+ const given = (rhs ?? new Array(r).fill(0)).map((v) => ldexp(v, -k));
186
+ const right = given.map((v) => ldexp(v, -s.scale));
153
187
  if (r === 1) {
154
- const t = tTestOf(s, L[0], right[0]);
188
+ // A contrast of rank 0 (L V L' = 0, such as a row of zeros) has no hypothesis to test, as for several rows below
189
+ const l = L[0];
190
+ if (!l.some(Number.isNaN) && !(l.reduce((sum, v, j) => sum + v * l.reduce((t, w, k) => t + s.vcov[j][k] * w, 0), 0) > 0))
191
+ return undefined;
192
+ const t = tTestOf(s, l, given[0]);
155
193
  return fRowOf(s, t.tValue * t.tValue, 1, t.df);
156
194
  }
157
195
  if (L.some((row) => row.some(Number.isNaN)) || right.some(Number.isNaN))
@@ -255,6 +293,9 @@ function contrastRows(L, p) {
255
293
  throw new TypeError("L must be an array of numbers or an array of rows");
256
294
  if (row.length !== p)
257
295
  throw new TypeError(`each contrast must have ${p} values (one per fixed effect), not ${row.length}`);
296
+ // an infinite contrast tests nothing (it gave an empty table silently), nor does a NaN one (lmerTest's row of NA)
297
+ if (!row.every(Number.isFinite))
298
+ throw new RangeError("L must not contain NaN or infinite values");
258
299
  }
259
300
  return rows;
260
301
  }
@@ -266,13 +307,17 @@ export function lmerContest(fit, L, options) {
266
307
  const p = internals.structure.xColNames.length;
267
308
  const rows = contrastRows(L, p);
268
309
  const level = options.level ?? 0.95;
269
- if (typeof level !== "number" || !(level >= 0 && level <= 1))
310
+ // 0 and 1 give an interval of width 0 or with infinite ends; lmerTest stops on them ("level > 0 is not TRUE")
311
+ if (typeof level !== "number" || !(level > 0 && level < 1))
270
312
  throw new RangeError("level must be a number between 0 and 1");
271
313
  const rhsOption = options.rhs ?? 0;
272
314
  const rhs = typeof rhsOption === "number" ? new Array(rows.length).fill(rhsOption) : [...rhsOption];
273
315
  if (rhs.length !== rows.length || rhs.some((v) => typeof v !== "number")) {
274
316
  throw new TypeError(`rhs must be a number or have one value per contrast (${rows.length})`);
275
317
  }
318
+ // (lmerTest gives F Inf and p 0 for an infinite rhs, t and p NaN for NaN)
319
+ if (!rhs.every(Number.isFinite))
320
+ throw new RangeError("rhs must not contain NaN or infinite values");
276
321
  const warnings = new Warnings();
277
322
  const s = lmerSatterthwaite(fit);
278
323
  s.warnings.forEach((w) => warnings.add(w));
@@ -31,7 +31,10 @@ export interface MauchlyTestResult {
31
31
  /** Name of the test (R's `method`). */
32
32
  method: "Mauchly's test of sphericity";
33
33
  }
34
- /** W = det(U) / (trace(U)/p)^p of a p x p matrix U */
34
+ /**
35
+ * W = det(U) / (trace(U)/p)^p of a p x p matrix U, as det(U / (trace(U)/p)): the scaled matrix has trace p, so
36
+ * neither the determinant nor the power overflows or underflows when W itself is in range
37
+ */
35
38
  export declare function sphericityW(U: DDMatrix): number;
36
39
  /**
37
40
  * The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the