@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
package/dist/models/lm.js CHANGED
@@ -13,12 +13,18 @@
13
13
  // keeps what the analyses of variance need (the effects, the model matrix, the terms).
14
14
  import { pf1 } from "../distributions/f.js";
15
15
  import { pt1, qt1 } from "../distributions/t.js";
16
- import { chol2inv } from "../linalg/chol.js";
16
+ import { chol2invColumns } from "../internal/scaledInverse.js";
17
+ import { rangeExponent } from "../linalg/matrix.js";
17
18
  import { qr, qrCoef, qrResid } from "../linalg/qr.js";
19
+ import { ldexp, norm2, scaleToUnit } from "../internal/summary.js";
20
+ import { maxOf } from "../internal/extremes.js";
18
21
  import { ddAdd, ddDiv, ddMul, ddMulNum, ddSub } from "../special/dd.js";
19
- import { ddLeastSquares, ddSqrtWeights, ddSumSquares } from "./ddLeastSquares.js";
22
+ import { ddLeastSquares, ddSqrt, ddSqrtWeights, ddSumSquares } from "./ddLeastSquares.js";
20
23
  import { parseFormula } from "./formula.js";
21
24
  import { design } from "./modelMatrix.js";
25
+ import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
26
+ import { checkDot, checkedDot } from "../linalg/dot.js";
27
+ const MIN_NORMAL = 2 ** -1022;
22
28
  /** The formula fit (lm, and aov without Error()) */
23
29
  export function lmFormulaFit(formula, d, aov) {
24
30
  const y = d.y;
@@ -28,11 +34,13 @@ export function lmFormulaFit(formula, d, aov) {
28
34
  const r = core.result;
29
35
  const warnings = [...d.warnings];
30
36
  if (!aov) {
31
- // summary.lm: residual variance negligible against the fitted values' mean square and variance
32
- const f = core.fitRows.map((i) => r.fittedValues[i]);
37
+ // summary.lm: residual variance negligible against the fitted values' mean square and variance (all of the
38
+ // response scaled by 2^-k, as fitted)
39
+ const k = core.yScale ?? 0;
40
+ const f = core.fitRows.map((i) => ldexp(r.fittedValues[i], -k));
33
41
  const m = f.reduce((s, v) => s + v, 0) / f.length;
34
42
  const v = f.length > 1 ? f.reduce((s, t) => s + (t - m) ** 2, 0) / (f.length - 1) : NaN;
35
- const resvar = core.rss / r.dfResidual;
43
+ const resvar = (core.rssScaled ?? core.rss) / r.dfResidual;
36
44
  if (Number.isFinite(resvar) && resvar < 1e-30 * (m * m + v))
37
45
  warnings.push("essentially perfect fit: summary may be unreliable");
38
46
  }
@@ -69,29 +77,53 @@ function lmMatrix(x, y, options) {
69
77
  const intercept = options.intercept ?? true;
70
78
  const xr = x.length > 0 && typeof x[0] !== "number" ? x.map((r) => Array.from(r)) : Array.from(x, (v) => [v]);
71
79
  const ys = Array.from(y);
80
+ // the shape of all the rows given, before the rows with a missing value are dropped (#463)
81
+ if (xr.some((r) => r.length !== xr[0].length))
82
+ throw new TypeError("all rows of the matrix must have the same length");
72
83
  if (xr.length !== ys.length)
73
84
  throw new RangeError("variable lengths differ (found for 'x')");
74
85
  const wsAll = options.weights === undefined ? undefined : Array.from(options.weights);
75
86
  if (wsAll !== undefined && wsAll.length !== ys.length)
76
87
  throw new RangeError("variable lengths differ (found for '(weights)')");
77
- if (wsAll?.some((w) => w < 0))
78
- throw new RangeError("missing or negative weights not allowed");
79
88
  const keep = ys.map((v, i) => !Number.isNaN(v) && xr[i].every((t) => !Number.isNaN(t)) && (wsAll === undefined || !Number.isNaN(wsAll[i])));
89
+ const Wall = wsAll?.filter((_, i) => keep[i]);
90
+ // negative weights among the rows kept only, as the formula interface and R (#455)
91
+ if (Wall?.some((w) => w < 0))
92
+ throw new RangeError("missing or negative weights not allowed");
80
93
  const Xall = xr.filter((_, i) => keep[i]).map((r) => (intercept ? [1, ...r] : r));
81
94
  const Yall = ys.filter((_, i) => keep[i]);
82
- const Wall = wsAll?.filter((_, i) => keep[i]);
83
95
  return fitLm(Xall, Yall, Wall, intercept).result;
84
96
  }
85
97
  /**
86
98
  * The coefficients, fitted values, residuals, effects and sums of squares of a fit recomputed in double-double on the
87
- * columns kept by the double-precision decomposition q (its rank and pivoting decide what is aliased)
99
+ * columns kept by the double-precision decomposition q (its rank and pivoting decide what is aliased), with the
100
+ * weights divided by 2^kw (kw even)
88
101
  */
89
- function preciseFit(Xall, Yall, Wall, fitRows, q, intercept) {
102
+ function preciseFit(Xall, Yall, WallGiven, kw, fitRows, q, intercept) {
90
103
  const rank = q.rank;
91
104
  const piv = q.pivot.slice(0, rank);
92
- const sw = ddSqrtWeights(Wall === undefined ? undefined : fitRows.map((i) => Wall[i]), fitRows.length);
93
- const cols = piv.map((j) => fitRows.map((i, k) => ddMulNum(sw[k], Xall[i][j])));
94
- const { qty, coef } = ddLeastSquares(cols, fitRows.map((i, k) => ddMulNum(sw[k], Yall[i])));
105
+ const Wall = WallGiven?.map((v) => ldexp(v, -kw));
106
+ // sqrt(w 2^-kw); where w 2^-kw falls below the normal range, sqrt(w) 2^(-kw/2) (#194: with weights 1e308 and
107
+ // 1e-308, 1e-308 2^-1022 underflowed to 0 before the square root and the row was left out, its column aliased)
108
+ const sw = ddSqrtWeights(Wall === undefined ? undefined : fitRows.map((i) => Wall[i]), fitRows.length).map((s, k) => {
109
+ if (WallGiven === undefined || Wall === undefined)
110
+ return s;
111
+ const w = WallGiven[fitRows[k]];
112
+ if (w === 0 || Wall[fitRows[k]] >= MIN_NORMAL)
113
+ return s;
114
+ const r = ddSqrt([w, 0]);
115
+ return [ldexp(r[0], -kw / 2), ldexp(r[1], -kw / 2)];
116
+ });
117
+ // a column whose largest entry is outside [2^-256, 2^256] divided by its power of 2 (exact; Q'y does not change, the
118
+ // coefficient is divided back): its squares underflowed in the decomposition (#194, a column of 1e-308 sqrt(w)
119
+ // gave the norm 0 and NaN coefficients)
120
+ const cols = piv.map((j) => {
121
+ const c = fitRows.map((i, k) => ddMulNum(sw[k], Xall[i][j]));
122
+ const e = rangeExponent(c.map((d) => d[0]));
123
+ return { c: e === 0 ? c : c.map((d) => [ldexp(d[0], -e), ldexp(d[1], -e)]), e };
124
+ });
125
+ const { qty, coef: coefScaled } = ddLeastSquares(cols.map(({ c }) => c), fitRows.map((i, k) => ddMulNum(sw[k], Yall[i])));
126
+ const coef = coefScaled.map((b, k) => (cols[k].e === 0 ? b : [ldexp(b[0], -cols[k].e), ldexp(b[1], -cols[k].e)]));
95
127
  const coefficients = Xall[0]?.map(() => NaN) ?? [];
96
128
  piv.forEach((j, k) => (coefficients[j] = coef[k][0]));
97
129
  // fitted values x'b of every row (aliased coefficients count as 0)
@@ -130,8 +162,64 @@ function preciseFit(Xall, Yall, Wall, fitRows, q, intercept) {
130
162
  /**
131
163
  * Least squares on a full model matrix (the column of ones included when `intercept` is true). Rows of weight 0 are
132
164
  * left out of the fit and of the counts.
165
+ *
166
+ * The response is scaled by a power of 2, 2^-k, before the fit (exact; see src/internal/summary.ts), so that its sums
167
+ * of squares stay in range: t, F, R^2 and the p-values come from the scaled fit, and the coefficients, residuals,
168
+ * fitted values, effects, sigma and standard errors are multiplied by 2^k, the residual sum of squares by 2^2k.
133
169
  */
134
170
  export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
171
+ const k = scaleToUnit([Yall.filter((_, i) => Wall === undefined || Wall[i] !== 0)]).k;
172
+ if (k === 0)
173
+ return zeroWeightRows(fitLmUnit(Xall, Yall, Wall, intercept, precise), Xall, Yall, Wall);
174
+ const core = fitLmUnit(Xall, Yall.map((v) => ldexp(v, -k)), Wall, intercept, precise);
175
+ const r = core.result;
176
+ const back = (v) => ldexp(v, k);
177
+ r.coefficients = r.coefficients.map(back);
178
+ r.residuals = r.residuals.map(back);
179
+ r.fittedValues = r.fittedValues.map(back);
180
+ r.sigma = back(r.sigma);
181
+ r.coefTable.estimate = r.coefTable.estimate.map(back);
182
+ r.coefTable.stdError = r.coefTable.stdError.map(back);
183
+ return zeroWeightRows({ ...core, effects: core.effects.map(back), rss: ldexp(core.rss, 2 * k), yScale: k, rssScaled: core.rss }, Xall, Yall, Wall);
184
+ }
185
+ /**
186
+ * The rows of weight 0 whose fitted value or residual is not finite, taken again in the units of the response (#193):
187
+ * the response is scaled by the 2^-k of the rows in the fit, so a finite response or x'b of a row left out could
188
+ * overflow in the scaled units (y = (1e-308, 1e308), weights (1, 0): the residual 1e308 was Infinity). The fitted
189
+ * value is x'b from the coefficients (aliased ones count as 0), by the exact inner product where the plain sum is not
190
+ * finite (as predict, #195); the residual is y minus it. Rows with finite values keep their bits
191
+ */
192
+ function zeroWeightRows(core, Xall, Yall, Wall) {
193
+ if (Wall === undefined)
194
+ return core;
195
+ const r = core.result;
196
+ const used = r.coefficients.flatMap((c, j) => (Number.isNaN(c) ? [] : [j]));
197
+ Wall.forEach((w, i) => {
198
+ if (w !== 0)
199
+ return;
200
+ let refit = false;
201
+ if (!Number.isFinite(r.fittedValues[i])) {
202
+ const x = Xall[i];
203
+ const s = used.reduce((t, j) => t + x[j] * r.coefficients[j], 0);
204
+ r.fittedValues[i] = checkDot(s, 0) ? checkedDot(used.map((j) => x[j]), used.map((j) => r.coefficients[j]), s) : s;
205
+ refit = true;
206
+ }
207
+ if (refit || !Number.isFinite(r.residuals[i]))
208
+ r.residuals[i] = Yall[i] - r.fittedValues[i];
209
+ });
210
+ return core;
211
+ }
212
+ /**
213
+ * The exponent qw of a QR decomposition of the model matrix of an lm fit with the weights divided by 2^qw (#199);
214
+ * absent for the decomposition with the weights given
215
+ */
216
+ const QR_WEIGHT_EXPONENT = new WeakMap();
217
+ /** Whether every entry of a decomposition is finite */
218
+ function finiteQR(q) {
219
+ return q.qr.every((r) => r.every(Number.isFinite)) && q.qraux.every(Number.isFinite);
220
+ }
221
+ /** fitLm on a response already in [1, 2) in absolute value (or one whose scale needs no change) */
222
+ function fitLmUnit(Xall, Yall, Wall, intercept, precise) {
135
223
  if (Yall.length === 0)
136
224
  throw new RangeError("0 (non-NA) cases");
137
225
  // the fit uses the rows of non-zero weight only
@@ -142,18 +230,48 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
142
230
  const n = Y.length;
143
231
  if (n === 0)
144
232
  throw new RangeError("all weights are zero");
233
+ // As R's lm.fit and lm.wfit (on the rows of non-zero weight)
234
+ if (X.some((r) => r.some((v) => !Number.isFinite(v))))
235
+ throw new RangeError("NA/NaN/Inf in 'x'");
236
+ if (Y.some((v) => !Number.isFinite(v)))
237
+ throw new RangeError("NA/NaN/Inf in 'y'");
238
+ // an infinite weight (#302): R stops with "NA/NaN/Inf in 'x'" from the weighted columns, but with no columns returns
239
+ // the residuals y and sigma Inf; here an error in both cases (as glm)
240
+ if (W?.some((v) => !Number.isFinite(v)))
241
+ throw new RangeError("non-finite weights not allowed");
145
242
  const fitRows = Yall.flatMap((_, i) => (fitRow[i] ? [i] : []));
146
- const sw = W?.map(Math.sqrt);
147
- const Xw = sw === undefined ? X : X.map((r, i) => r.map((v) => v * sw[i]));
243
+ // The sums of squares are formed with the weights divided by 2^kw (kw even, the largest weight then in [1, 4)):
244
+ // rss, mss and the residual variance below are those of the scaled weights, and sigma, the standard errors, rss and
245
+ // the effects are scaled back (exact powers of 2, so the values are the same wherever nothing overflows). The sums
246
+ // with weights near 1e308 overflowed: R^2 and F were NaN, and sigma too in the formula interface, as R's
247
+ const maxW = W === undefined ? 1 : maxOf(W);
248
+ const kw = Number.isFinite(maxW) ? 2 * Math.floor(Math.floor(Math.log2(maxW)) / 2) : 0;
249
+ // The QR decomposition of the model matrix with rows scaled by sqrt(w), as R's. Where that is not finite and the
250
+ // largest weight is at least 1, it is the decomposition with the weights divided by 2^qw instead (qw = kw + 2, the
251
+ // largest weight then in [1/4, 1), so no entry of sqrt(w) x exceeds x): the coefficients and the residuals do not
252
+ // depend on a common factor of the weights (#199: x near 0.9e308 with weights 2, the column norm 1.97e308
253
+ // overflowed and the coefficients were -Inf and 1e-307, R NaN). `qr` of the result is then that decomposition,
254
+ // recorded in QR_WEIGHT_EXPONENT for predict
255
+ let qw = 0;
256
+ let sw = W?.map(Math.sqrt);
257
+ let Xw = sw === undefined ? X : X.map((r, i) => r.map((v) => v * sw[i]));
258
+ let q = qr(Xw);
259
+ if (W !== undefined && Number.isFinite(maxW) && kw + 2 > 0 && !finiteQR(q)) {
260
+ qw = kw + 2;
261
+ sw = W.map((v) => ldexp(Math.sqrt(v), -qw / 2));
262
+ Xw = X.map((r, i) => r.map((v) => v * sw[i]));
263
+ q = qr(Xw);
264
+ QR_WEIGHT_EXPONENT.set(q, qw);
265
+ }
148
266
  const Yw = sw === undefined ? Y : Y.map((v, i) => v * sw[i]);
149
- const q = qr(Xw);
150
267
  const rank = q.rank;
151
- const pf = precise ? preciseFit(Xall, Yall, Wall, fitRows, q, intercept) : undefined;
268
+ const scaleW = (v) => ldexp(v, -kw);
269
+ const pf = precise ? preciseFit(Xall, Yall, Wall, kw, fitRows, q, intercept) : undefined;
152
270
  const coefficients = pf?.coefficients ?? qrCoef(q, Yw);
153
271
  const residuals = pf?.residuals ?? [];
154
272
  const fittedValues = pf?.fittedValues ?? [];
155
273
  const dfResidual = n - rank;
156
- const w = W ?? new Array(n).fill(1);
274
+ const w = W?.map(scaleW) ?? new Array(n).fill(1);
157
275
  let rss = pf?.rss ?? 0;
158
276
  if (pf === undefined) {
159
277
  // residuals from Q (the part of Q'y beyond the rank), so a saturated model has residuals of exactly 0, as in R
@@ -177,15 +295,42 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
177
295
  rss += w[i] * fitResiduals[i] ** 2;
178
296
  }
179
297
  const fitted = fittedValues.filter((_, i) => fitRow[i]);
298
+ // The residual sum of squares for the weights divided by 2^kw is rss 2^rs. rs is 0 unless a positive weight falls
299
+ // below the normal range when divided by 2^kw (#388: weights 1e308 and 5e-324, the second row's contribution was
300
+ // lost and sigma 0): rss is then the sum of w r^2 with the original weights, each term formed as
301
+ // (w 2^(2a - ks)) (r 2^-a)^2 (a the exponent of r) so that nothing overflows, in units of 2^ks (ks even, from the
302
+ // largest term)
303
+ let rs = 0;
304
+ if (W !== undefined && W.some((v) => v !== 0 && ldexp(v, -kw) < MIN_NORMAL)) {
305
+ const terms = fitRows.flatMap((i, k) => {
306
+ const r = residuals[i];
307
+ return r === 0 ? [] : [{ w: W[k], r, a: Math.floor(Math.log2(Math.abs(r))) }];
308
+ });
309
+ if (terms.length > 0 && terms.every((t) => Number.isFinite(t.r))) {
310
+ const top = Math.max(...terms.map((t) => Math.log2(t.w) + 2 * t.a));
311
+ const ks = 2 * Math.floor(Math.floor(top) / 2);
312
+ let sum = 0;
313
+ for (const t of terms)
314
+ sum += ldexp(t.w, 2 * t.a - ks) * ldexp(t.r, -t.a) ** 2;
315
+ rss = sum;
316
+ rs = ks - kw;
317
+ }
318
+ }
180
319
  const resvar = rss / dfResidual;
181
- const sigma = Math.sqrt(resvar);
182
- // (R'R)^-1 of the leading rank x rank block, in pivot order
183
- const Rr = q.qr.slice(0, rank).map((row) => row.slice(0, rank));
184
- const covUnscaled = rank > 0 ? chol2inv(Rr) : [];
320
+ const sigma = ldexp(Math.sqrt(resvar), (kw + rs) / 2);
321
+ // (R'R)^-1 of the leading rank x rank block, in pivot order, for the weights divided by 2^kw (R scaled by 2^-kw/2,
322
+ // exact): (R'R)^-1 of the given weights overflowed for weights below 1e-308, making the standard errors Infinity
323
+ // (R too), though they do not depend on a common factor of the weights
324
+ // (and the columns far from 1 divided by powers of 2 too, review 64: a column of 1e-200 made a standard error Infinity)
325
+ // (with the decomposition of the weights divided by 2^qw, #199, R is used as it is and the standard errors are divided
326
+ // by 2^((qw - kw) / 2): R times that factor could overflow)
327
+ const rShift = qw === 0 ? 0 : (qw - kw) / 2;
328
+ const Rr = q.qr.slice(0, rank).map((row) => row.slice(0, rank).map((v) => (qw === 0 ? ldexp(v, -kw / 2) : v)));
329
+ const { inv: covUnscaled, e: colScale } = rank > 0 ? chol2invColumns(Rr) : { inv: [], e: [] };
185
330
  const piv = q.pivot.slice(0, rank);
186
331
  const order = piv.map((col, k) => [col, k]).sort((a, b) => a[0] - b[0]);
187
332
  const estimate = order.map(([col]) => coefficients[col]);
188
- const stdError = order.map(([, k]) => Math.sqrt(covUnscaled[k][k] * resvar));
333
+ const stdError = order.map(([, k]) => ldexp(Math.sqrt(covUnscaled[k][k] * resvar), rs / 2 - colScale[k] - rShift));
189
334
  const tValue = estimate.map((e, i) => e / stdError[i]);
190
335
  const pValue = tValue.map((t) => 2 * pt1(-Math.abs(t), dfResidual, true, false));
191
336
  const result = {
@@ -203,7 +348,7 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
203
348
  };
204
349
  const dfInt = intercept ? 1 : 0;
205
350
  const numdf = rank - dfInt;
206
- const core = { result, fitRows, effects: pf?.effects ?? [], rss };
351
+ const core = { result, fitRows, effects: (pf?.effects ?? []).map((e) => ldexp(e, kw / 2)), rss: ldexp(rss, kw + rs) };
207
352
  // nothing beyond the intercept: R^2 = 0 and no F test, as in summary.lm
208
353
  if (numdf === 0)
209
354
  return core;
@@ -221,13 +366,21 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
221
366
  else
222
367
  for (let i = 0; i < n; i++)
223
368
  mss += w[i] * fitted[i] ** 2;
224
- result.rSquared = mss / (mss + rss);
369
+ result.rSquared = mss / (mss + ldexp(rss, rs));
225
370
  result.adjRSquared = 1 - (1 - result.rSquared) * ((n - dfInt) / dfResidual);
226
- const fValue = mss / numdf / resvar;
371
+ const fValue = ldexp(mss / numdf / resvar, -rs);
227
372
  result.fStatistic = { value: fValue, numdf, dendf: dfResidual };
228
373
  result.fPValue = pf1(fValue, numdf, dfResidual, false, false);
229
374
  return core;
230
375
  }
376
+ /**
377
+ * The t quantile at (1 + level) / 2. For alpha = (1 - level) / 2 below 1e-8 the upper probability itself: 1 - alpha
378
+ * loses its digits and rounds to 1 below 1.1e-16 (review 58)
379
+ */
380
+ function tQuantile(level, df) {
381
+ const a2 = (1 - level) / 2;
382
+ return a2 < 1e-8 ? qt1(a2, df, false, false) : qt1((1 + level) / 2, df, true, false);
383
+ }
231
384
  /**
232
385
  * Confidence intervals for the coefficients of a linear model (NaN for aliased columns), for an `lm` fit.
233
386
  * Equivalent to R's `confint()`.
@@ -243,7 +396,10 @@ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
243
396
  */
244
397
  export function confint(fit, options = {}) {
245
398
  const level = options.level ?? 0.95;
246
- const t = qt1((1 + level) / 2, fit.dfResidual, true, false);
399
+ // R's confint gives NaN limits for a level outside (0, 1) and predict an interval of some other coverage; an error
400
+ if (!(level > 0 && level < 1))
401
+ throw new RangeError("'level' must be between 0 and 1");
402
+ const t = tQuantile(level, fit.dfResidual);
247
403
  const { estimate, stdError } = fit.coefTable;
248
404
  const lower = fit.coefficients.map(() => NaN);
249
405
  const upper = fit.coefficients.map(() => NaN);
@@ -257,6 +413,14 @@ export function confint(fit, options = {}) {
257
413
  });
258
414
  return { lower, upper };
259
415
  }
416
+ /** a b 2^s, formed so that no intermediate step overflows or underflows (a > 0 finite) */
417
+ function scaledProduct(a, b, s) {
418
+ if (b === 0 || !Number.isFinite(b))
419
+ return a * b;
420
+ const ea = Math.floor(Math.log2(a));
421
+ const eb = Math.floor(Math.log2(Math.abs(b)));
422
+ return ldexp(ldexp(a, -ea) * ldexp(b, -eb), ea + eb + s);
423
+ }
260
424
  /**
261
425
  * Predictions of a linear model at new values of the predictors, with standard errors and optionally intervals, for
262
426
  * an `lm` fit (`se.fit = TRUE`). Equivalent to R's `predict()`. Aliased columns are left out, as R does.
@@ -277,26 +441,61 @@ export function predict(fit, newdata, options = {}) {
277
441
  ? newdata.map((r) => Array.from(r))
278
442
  : Array.from(newdata, (v) => [v]);
279
443
  const X = rows.map((r) => (fit.intercept ? [1, ...r] : r));
444
+ if (X.some((r) => r.length !== fit.coefficients.length))
445
+ throw new RangeError("newdata must have one column per predictor of the fit");
280
446
  const rank = fit.rank;
281
447
  const piv = fit.qr.pivot.slice(0, rank);
282
448
  const Rr = fit.qr.qr.slice(0, rank).map((row) => row.slice(0, rank));
283
- const resvar = fit.sigma ** 2;
284
- const values = X.map((r) => r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0));
449
+ // R from the weights divided by 2^qw (#199): z is 2^(qw/2) times that of the weights given
450
+ const qrHalf = -(QR_WEIGHT_EXPONENT.get(fit.qr) ?? 0) / 2;
451
+ const used = fit.coefficients.flatMap((c, j) => (Number.isNaN(c) ? [] : [j]));
452
+ const values = X.map((r) => {
453
+ const s = r.reduce((s, v, j) => (Number.isNaN(fit.coefficients[j]) ? s : s + v * fit.coefficients[j]), 0);
454
+ // products of finite values may overflow while x'b is in range (2 * 1e308 - 2 * 1e308), or underflow while the
455
+ // sum is tiny (#395): the exact inner product
456
+ return checkDot(s, 0) ? checkedDot(used.map((j) => r[j]), used.map((j) => fit.coefficients[j]), s) : s;
457
+ });
285
458
  // se: || R^-T x_piv || sigma, by forward substitution with R^T
286
- const seFit = X.map((r) => {
459
+ const forward = (x) => {
287
460
  const z = new Array(rank).fill(0);
288
461
  for (let i = 0; i < rank; i++) {
289
- let s = r[piv[i]];
462
+ let s = x[i];
290
463
  for (let k = 0; k < i; k++)
291
464
  s -= Rr[k][i] * z[k];
292
465
  z[i] = s / Rr[i][i];
293
466
  }
294
- return Math.sqrt(z.reduce((a, v) => a + v * v, 0) * resvar);
467
+ return z;
468
+ };
469
+ const seFit = X.map((r) => {
470
+ const x = piv.map((j) => r[j]);
471
+ const n = norm2(forward(x));
472
+ // sqrt(z'z) sigma, not sqrt(z'z sigma^2): sigma^2 can overflow or underflow where sigma does not
473
+ if ((n >= MIN_NORMAL && n < Infinity) || !x.every(Number.isFinite) || x.every((v) => v === 0)) {
474
+ return qrHalf === 0 || !(n > 0 && n < Infinity) ? n * fit.sigma : scaledProduct(n, fit.sigma, qrHalf);
475
+ }
476
+ // z overflowed or fell below the normal range although x is finite (#196: x = 1e200 on a column of 1e-200 made z
477
+ // about 1e400, Infinity before sigma 4e-201 was applied): z is linear in x, so solve with x divided by the power
478
+ // of 2 of its largest entry (by 2^600 more if that still overflows) and multiply back with sigma in exponent form
479
+ const e = Math.floor(Math.log2(maxOf(x.map(Math.abs))));
480
+ for (const extra of [0, 600]) {
481
+ const ns = norm2(forward(x.map((v) => ldexp(v, -(e + extra)))));
482
+ if (ns < Infinity)
483
+ return ns === 0 ? ns * fit.sigma : scaledProduct(ns, fit.sigma, e + extra + qrHalf);
484
+ }
485
+ return n * fit.sigma;
295
486
  });
296
487
  const interval = options.interval ?? "none";
488
+ if (interval !== "none" && interval !== "confidence" && interval !== "prediction")
489
+ throw new RangeError(`invalid 'interval': ${String(interval)}`);
490
+ // R's predict.lm (rankdeficient = "warnif"): the rows that are not estimable from a rank-deficient fit
491
+ const nonEstimable = nonEstimableRows(fit.qr, fit.rank, X);
492
+ const extra = nonEstimable.length > 0 ? { nonEstimable, warnings: [NON_ESTIMABLE_WARNING] } : {};
297
493
  if (interval === "none")
298
- return { fit: values, seFit };
299
- const t = qt1((1 + (options.level ?? 0.95)) / 2, fit.dfResidual, true, false);
300
- const half = seFit.map((s) => t * Math.sqrt(s * s + (interval === "prediction" ? resvar : 0)));
301
- return { fit: values, seFit, lwr: values.map((v, i) => v - half[i]), upr: values.map((v, i) => v + half[i]) };
494
+ return { fit: values, seFit, ...extra };
495
+ const level = options.level ?? 0.95;
496
+ if (!(level > 0 && level < 1))
497
+ throw new RangeError("'level' must be between 0 and 1");
498
+ const t = tQuantile(level, fit.dfResidual);
499
+ const half = seFit.map((s) => t * (interval === "prediction" ? Math.hypot(s, fit.sigma) : s));
500
+ return { fit: values, seFit, lwr: values.map((v, i) => v - half[i]), upr: values.map((v, i) => v + half[i]), ...extra };
302
501
  }
@@ -132,6 +132,20 @@ export type MixedCriterion = (s: MixedModelStructure, theta: readonly number[],
132
132
  f: number;
133
133
  g: number[];
134
134
  };
135
+ /**
136
+ * The estimate of θ: the local minimum reached from the initial θ, then compared with the local minima reached from
137
+ * its boundary points with one whole term removed (see the header); a clearly better one is the start of a new local
138
+ * minimisation, until none is.
139
+ */
140
+ /**
141
+ * The exponent e_k of 2 of each element of θ (internal; issue #11): that of the largest |value| of the column of Z of
142
+ * 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
143
+ * blocks stay lower triangular with the same signs, and the model (and its criterion) is the same
144
+ */
145
+ export declare function thetaColumnExponents(s: MixedModelStructure): {
146
+ theta: number[];
147
+ z: number[];
148
+ };
135
149
  /**
136
150
  * The option checks of lmer and of lmerTest's functions (internal; oracle/report-0.14.0-behaviour.md, section 3):
137
151
  * `options` must be an object when given (not null, not an array); its own keys, in order, may be neither among those
@@ -195,8 +209,13 @@ export interface LmerInternals {
195
209
  structure: MixedModelStructure;
196
210
  /** β₀, the least-squares coefficients of y on X, to be added to the fixed effects computed from `structure` */
197
211
  beta0: number[];
198
- /** The data frame given to lmer (the same object, not a copy) */
212
+ /** The data frame given to lmer (the same object, not a copy: fits are compared on the same data object) */
199
213
  data: DataFrame;
214
+ /**
215
+ * A copy of the columns of `data` at the time of the fit, from which the analyses rebuild the model (changes to
216
+ * `data` after the fit changed lmerAnova's type I hypotheses silently)
217
+ */
218
+ snapshot: DataFrame;
200
219
  /** The options given to lmer (a copy) */
201
220
  options: LmerOptions;
202
221
  /** Whether the REML criterion was minimised */