@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
@@ -10,18 +10,27 @@
10
10
  // of these matrices times (P'P)^-1, and the epsilons and Mauchly's W follow from P'EP (src/models/ddMatrix.ts).
11
11
  import { pf1 } from "../distributions/f.js";
12
12
  import { levelText, numberLevels } from "../internal/levels.js";
13
+ import { ldexp, scaleToUnit } from "../internal/summary.js";
14
+ import { chol } from "../linalg/chol.js";
13
15
  import { eigen } from "../linalg/eigen.js";
14
16
  import { qr } from "../linalg/qr.js";
15
17
  import { ddAdd, ddDiv, ddDivNum, ddMul, ddMulNum } from "../special/dd.js";
16
18
  import { Anova } from "./carAnova.js";
17
19
  import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
18
- import { ddHi, ddInverse, ddMatMul, ddTrace } from "./ddMatrix.js";
20
+ import { ddHi, ddInverse, ddMatMul, ddTrace, ddTranspose } from "./ddMatrix.js";
19
21
  import { lm } from "./lm.js";
20
22
  import { mauchlyPValue, sphericityW } from "./mauchly.js";
21
23
  import { compareCodePoints } from "./modelFrame.js";
22
24
  import { modelMatrix } from "./modelMatrix.js";
25
+ import { scaledTables } from "./scaledTables.js";
23
26
  const list = (v) => (v === undefined ? [] : typeof v === "string" ? [v] : [...v]);
24
- const SQRT_EPS = Math.sqrt(2.220446049250313e-16);
27
+ /** Eigenvalues of the error SSP matrix below this fraction of the largest one count as 0 */
28
+ const REL_RANK_TOL = 1e-12;
29
+ /**
30
+ * Eigenvalues of the error SSP matrix below this fraction of the sum of squares of the wide data count as 0: the
31
+ * rounding of the data (relative 2^-53 of each value) alone makes eigenvalues near 1e-32 of it
32
+ */
33
+ const ABS_RANK_TOL = 1e-24;
25
34
  function column(data, name) {
26
35
  const c = Object.prototype.hasOwnProperty.call(data, name) ? data[name] : undefined;
27
36
  if (c === undefined)
@@ -36,18 +45,22 @@ function sortedLevels(values) {
36
45
  return distinct.sort((a, b) => a - b).map(label);
37
46
  return [...new Set(distinct.map(label))].sort(compareCodePoints);
38
47
  }
39
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
+ // Whether a variable is one of the components of a term name such as "a:b" (compared as names, so that a name that is
49
+ // not a run of word characters, such as ".grp", is found too)
50
+ const inTerm = (variable, term) => term.split(":").includes(variable);
40
51
  /**
41
52
  * The anova table from the rows (intercept excluded) with the effect sizes; `errorSS` are the error sums of squares of
42
- * all rows of the univariate table (intercept included)
53
+ * each error stratum (keyed by its within-subject term, so that two strata whose sums happen to be equal both count).
54
+ * The sums of squares are those of the scaled response: the
55
+ * effect sizes are ratios of them, and only the MSE is scaled back (`unscale`)
43
56
  */
44
- function anovaTable(rows, errorSS, es, observed) {
45
- const isObserved = (name) => observed.some((o) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(name));
57
+ function anovaTable(rows, errorSS, es, observed, unscale) {
58
+ const isObserved = (name) => observed.some((o) => inTerm(o, name));
46
59
  for (const o of observed) {
47
- if (!rows.some((r) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(r.name)))
60
+ if (!rows.some((r) => inTerm(o, r.name)))
48
61
  throw new Error(`Observed variable not in data: ${o}`);
49
62
  }
50
- const distinctError = [...new Set(errorSS)].reduce((s, v) => s + v, 0);
63
+ const distinctError = [...errorSS.values()].reduce((s, v) => s + v, 0);
51
64
  const O = rows.reduce((s, r) => (isObserved(r.name) ? s + r.ss : s), 0);
52
65
  const want = ["pes", "ges"].filter((e) => es.includes(e));
53
66
  return {
@@ -55,7 +68,7 @@ function anovaTable(rows, errorSS, es, observed) {
55
68
  rowNames: rows.map((r) => r.name),
56
69
  table: rows.map((r) => {
57
70
  const effects = want.map((e) => e === "pes" ? r.ss / (r.ss + r.errSS) : r.ss / (r.ss + distinctError + O - (isObserved(r.name) ? r.ss : 0)));
58
- return [r.numDf, r.denDf, r.errSS / r.denDf, r.f, ...effects, r.p];
71
+ return [r.numDf, r.denDf, unscale(r.errSS / r.denDf), r.f, ...effects, r.p];
59
72
  }),
60
73
  };
61
74
  }
@@ -88,25 +101,53 @@ export function aovEz(data, options) {
88
101
  const within = list(options.within);
89
102
  if (between.length === 0 && within.length === 0)
90
103
  throw new Error("Either between or within need to be non-NULL!");
104
+ // A repeated name is an error, not one factor (afex drops repeats silently; #296)
105
+ for (const [name, names] of [["between", between], ["within", within]]) {
106
+ const repeated = names.filter((n, i) => names.indexOf(n) !== i);
107
+ if (repeated.length > 0)
108
+ throw new Error(`duplicated factor names in '${name}': ${[...new Set(repeated)].join(", ")}`);
109
+ }
110
+ const both = between.filter((n) => within.includes(n));
111
+ if (both.length > 0)
112
+ throw new Error(`factors in both 'between' and 'within': ${both.join(", ")}`);
91
113
  const type = options.type ?? 3;
92
114
  if (type !== 2 && type !== 3)
93
115
  throw new RangeError(`invalid type (${String(type)}): use 2 or 3`);
94
116
  const correction = options.correction ?? "GG";
117
+ if (!["GG", "HF", "none"].includes(correction))
118
+ throw new RangeError(`invalid 'correction': ${String(correction)}`);
95
119
  const es = list(options.es ?? "ges");
120
+ for (const e of es)
121
+ if (e !== "ges" && e !== "pes")
122
+ throw new RangeError(`invalid 'es': ${String(e)}`);
96
123
  const observed = list(options.observed);
97
124
  const warnings = [];
98
125
  // 1. the columns as factors
99
126
  // (the id and factor columns as R's factor() makes them: numbers with the same 15-digit text are one level)
100
- const ids = numberLevels(column(data, options.id)).map(label);
101
- const dv = column(data, options.dv).map((v) => {
127
+ // Rows with a missing id or factor value (null, undefined or NaN) are dropped, as from a model frame. A missing
128
+ // response (null or NaN) makes its cell missing, so that its id is removed in step 6, as afex does
129
+ const isMissing = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
130
+ const dvRaw = column(data, options.dv);
131
+ const keyCols = [options.id, ...between, ...within].map((c) => column(data, c));
132
+ for (const c of keyCols)
133
+ if (c.length !== dvRaw.length)
134
+ throw new RangeError("the columns must have the same length");
135
+ const keep = dvRaw.map((_, i) => keyCols.every((c) => !isMissing(c[i])));
136
+ const used = (c) => c.filter((_, i) => keep[i]);
137
+ const ids = numberLevels(used(keyCols[0])).map(label);
138
+ const dvUsed = used(dvRaw).map((v) => {
139
+ if (isMissing(v))
140
+ return NaN;
102
141
  if (typeof v !== "number")
103
142
  throw new TypeError(`the response '${options.dv}' must be numeric`);
143
+ if (!Number.isFinite(v))
144
+ throw new RangeError(`the response '${options.dv}' must be finite`);
104
145
  return v;
105
146
  });
106
- const bcols = between.map((b) => numberLevels(column(data, b)));
107
- const wcols = within.map((w) => numberLevels(column(data, w)));
147
+ const bcols = between.map((_, k) => numberLevels(used(keyCols[1 + k])));
148
+ const wcols = within.map((_, k) => numberLevels(used(keyCols[1 + between.length + k])));
108
149
  const nrow = ids.length;
109
- for (const c of [dv, ...bcols, ...wcols])
150
+ for (const c of [dvUsed, ...bcols, ...wcols])
110
151
  if (c.length !== nrow)
111
152
  throw new RangeError("the columns must have the same length");
112
153
  const blevels = bcols.map((c) => sortedLevels(c));
@@ -118,6 +159,11 @@ export function aovEz(data, options) {
118
159
  if (l.length < 2)
119
160
  throw new Error(`Factor "${between[k]}" consists of one level only. Remove factor from model?`);
120
161
  });
162
+ // a within factor with one level is also an error (afex returns an empty table, which hides the mistake)
163
+ wlevels.forEach((l, k) => {
164
+ if (l.length < 2)
165
+ throw new Error(`Factor "${within[k]}" consists of one level only. Remove factor from model?`);
166
+ });
121
167
  // 3. ids in more than one between cell
122
168
  const idOrder = [...new Set(ids)];
123
169
  const cellOf = new Map();
@@ -142,6 +188,25 @@ export function aovEz(data, options) {
142
188
  const present = new Set(ids.map((_, i) => cellKey(i)));
143
189
  if (cells.some((c) => !present.has(JSON.stringify(c))))
144
190
  throw new Error("Empty cells in within-subjects design (i.e., bad data structure).");
191
+ // the ids removed in step 6: a cell without rows, or a missing response in one
192
+ const seen = new Map();
193
+ const withNaN = new Set();
194
+ ids.forEach((id, i) => {
195
+ let s = seen.get(id);
196
+ if (s === undefined)
197
+ seen.set(id, (s = new Set()));
198
+ s.add(cellKey(i));
199
+ if (Number.isNaN(dvUsed[i]))
200
+ withNaN.add(id);
201
+ });
202
+ const missing = idOrder.filter((id) => withNaN.has(id) || seen.get(id).size < cells.length);
203
+ // The response scaled by 2^-k (exact), so that its cross-products stay in range; sums of squares are scaled back by
204
+ // 2^2k for output, and F, the epsilons and Mauchly's W do not depend on the units. k is set by the ids kept: a
205
+ // removed id with an extreme response scaled the others into the subnormals (#508)
206
+ const removed = new Set(missing);
207
+ const dvExp = scaleToUnit([dvUsed.filter((_, i) => !removed.has(ids[i]))]).k;
208
+ const dv = dvExp === 0 ? dvUsed : dvUsed.map((v) => ldexp(v, -dvExp));
209
+ const unscale = (v) => ldexp(v, 2 * dvExp);
145
210
  // 5. the wide data (means of the rows of an id and a cell)
146
211
  const nc = cells.length;
147
212
  const sums = new Map();
@@ -156,8 +221,7 @@ export function aovEz(data, options) {
156
221
  if ([...sums.values()].some((e) => e.n.some((v) => v > 1))) {
157
222
  warnings.push("More than one observation per design cell, aggregating data using `fun_aggregate = mean`.\nTo turn off this warning, pass `fun_aggregate = mean` explicitly.");
158
223
  }
159
- // 6. ids that miss a cell are removed
160
- const missing = idOrder.filter((id) => sums.get(id).n.some((v) => v === 0));
224
+ // 6. ids that miss a cell (or have a missing response in one) are removed (found above)
161
225
  if (missing.length > 0) {
162
226
  // the ids sorted as the levels of a factor; afex goes on with a printout of the data, which is not reproduced
163
227
  const sorted = [...missing].sort(compareCodePoints);
@@ -182,11 +246,16 @@ export function aovEz(data, options) {
182
246
  return withinAnalysis();
183
247
  /** Without within-subject factors (or a single within cell): lm on one value per subject and car's Anova */
184
248
  function betweenOnly() {
185
- const dvName = between.includes("y") ? "y_" : "y";
249
+ // a response name that is none of the between factors (with factors y and y_, "y_" replaced the factor y_, #295)
250
+ let dvName = "y";
251
+ while (between.includes(dvName))
252
+ dvName += "_";
186
253
  const frame = { ...bdata, [dvName]: Y.map((r) => r[0][0]) };
187
254
  const fit = lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt });
188
255
  if (fit.rank < fit.coefNames.length)
189
256
  throw new Error(rankDeficient);
257
+ if (fit.dfResidual <= 0)
258
+ throw new RangeError(`no residual degrees of freedom: ${Y.length} subject(s) for ${fit.rank} parameter(s)`);
190
259
  const tab = Anova(fit, { type });
191
260
  warnings.push(...tab.warnings.filter((w) => !warnings.includes(w)));
192
261
  const rdf = fit.dfResidual;
@@ -196,15 +265,21 @@ export function aovEz(data, options) {
196
265
  const [ss, df, f, p] = tab.table[i];
197
266
  return [{ name, ss: ss, numDf: df, errSS: fit.rss, denDf: rdf, f: f, p: p }];
198
267
  });
199
- return {
200
- anova: anovaTable(rows, [fit.rss], es, observed),
201
- univariate: { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table },
268
+ const ssCol = tab.colNames.indexOf("Sum Sq");
269
+ const result = {
270
+ anova: anovaTable(rows, new Map([[0, fit.rss]]), es, observed, unscale),
271
+ univariate: { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table.map((r) => r.map((v, j) => (j === ssCol ? unscale(v) : v))) },
202
272
  within,
203
273
  warnings,
204
274
  };
275
+ // (tab has the sums of squares as fitted: scaledTables.ts)
276
+ scaledTables.set(result, { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table });
277
+ return result;
205
278
  }
206
279
  function withinAnalysis() {
207
280
  const n = subjects.length;
281
+ // the sum of squares of the wide data (scaled), the reference of the rounding of the data for the rank of P'EP
282
+ const dataSS = Y.reduce((s, r) => r.reduce((t, v) => t + v[0] * v[0], s), 0);
208
283
  // without between factors (an empty data frame) the model matrix is the column of ones
209
284
  const X = between.length > 0
210
285
  ? modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt })
@@ -213,6 +288,8 @@ export function aovEz(data, options) {
213
288
  if (n === 0 || qr(X.x).rank < px)
214
289
  throw new Error(rankDeficient);
215
290
  const d = n - px;
291
+ if (d <= 0)
292
+ throw new RangeError(`no residual degrees of freedom: ${n} subject(s) for ${px} between-subject parameter(s)`);
216
293
  const bterms = [0, ...X.termLabels.map((_, j) => j + 1)];
217
294
  const blabs = ["(Intercept)", ...X.termLabels];
218
295
  const colsOf = (terms) => X.assign.flatMap((a, j) => (terms.includes(a) ? [j] : []));
@@ -245,12 +322,14 @@ export function aovEz(data, options) {
245
322
  }));
246
323
  };
247
324
  const uni = [];
325
+ // (the same rows with the sums of squares as fitted, for the effect sizes: scaledTables.ts)
326
+ const uniScaled = [];
248
327
  const uniNames = [];
249
328
  const corr = [];
250
329
  const sph = [];
251
330
  const corrNames = [];
252
331
  const rows = [];
253
- const errorSS = [];
332
+ const errorSS = new Map();
254
333
  let hfAbove = false;
255
334
  for (const wt of wterms) {
256
335
  const wc = W.assign.flatMap((a, j) => (a === wt ? [j] : []));
@@ -268,15 +347,41 @@ export function aovEz(data, options) {
268
347
  let mp = NaN;
269
348
  let corrected = false;
270
349
  if (p >= 2) {
271
- const ev = eigen(ddHi(PEP), { symmetric: true, onlyValues: true }).values;
272
- if (ev.filter((v) => v >= SQRT_EPS).length === p) {
350
+ // Each correction is judged on its own condition (car gives none of them for a singular error SSP matrix):
351
+ // - GG: tr(A)^2 / (p tr(A^2)) is defined for any nonzero A, singular or not (1/p for rank 1)
352
+ // - HF: needs d - p GG > 0
353
+ // - Mauchly: needs a nonsingular matrix.
354
+ // The eigenvalues are those of R PEP R' (M = R'R), the same as those of A whatever the contrasts P, in the
355
+ // units of the squared response. An eigenvalue counts as 0 below a fraction of the largest one (exactly
356
+ // singular matrices, from d < p or collinear measurements, have eigenvalues near 1e-16 of it) or of the sum of
357
+ // squares of the wide data (an error SSP matrix made only of the rounding of additive data, at any scale).
358
+ // An absolute threshold, as car's, would depend on the units of the response.
359
+ const term = wlabs[wt];
360
+ const Rm = chol(ddHi(M)).map((r) => r.map((v) => [v, 0]));
361
+ const S = ddHi(ddMatMul(ddMatMul(Rm, PEP), ddTranspose(Rm)));
362
+ const ev = eigen(S, { symmetric: true, onlyValues: true }).values;
363
+ const top = ev.reduce((a, b) => Math.max(a, b), 0);
364
+ const zero = Math.max(top * REL_RANK_TOL, dataSS * ABS_RANK_TOL);
365
+ const tA = ddTrace(A);
366
+ const tAA = ddTrace(ddMatMul(A, A));
367
+ if (top > dataSS * ABS_RANK_TOL && tAA[0] > 0 && Number.isFinite(tAA[0])) {
273
368
  corrected = true;
274
- const tA = ddTrace(A);
275
- gg = ddDiv(ddMul(tA, tA), ddMulNum(ddTrace(ddMatMul(A, A)), p))[0];
276
- hf = ((d + 1) * p * gg - 2) / (p * (d - p * gg));
369
+ gg = ddDiv(ddMul(tA, tA), ddMulNum(tAA, p))[0];
370
+ if (d - p * gg > 0)
371
+ hf = ((d + 1) * p * gg - 2) / (p * (d - p * gg));
372
+ else
373
+ warnings.push(`The Huynh-Feldt epsilon of ${term} is undefined (d - p GG <= 0)${correction === "HF" ? ": corrected with GG" : ""}`);
374
+ }
375
+ else {
376
+ warnings.push(`The error SSP matrix of ${term} is 0 (or at the rounding level of the data): no sphericity corrections (the p-values are uncorrected)`);
377
+ }
378
+ if (corrected && ev.every((v) => v > zero)) {
277
379
  mw = sphericityW(ddMatMul(M, PEP));
278
380
  mp = mauchlyPValue(mw, p, d, nc);
279
381
  }
382
+ else if (corrected) {
383
+ warnings.push(`The error SSP matrix of ${term} is singular: no Mauchly test (the epsilons are still defined)`);
384
+ }
280
385
  }
281
386
  for (let bi = 0; bi < bterms.length; bi++) {
282
387
  const bt = bterms[bi];
@@ -297,9 +402,10 @@ export function aovEz(data, options) {
297
402
  const f = ss / numDf / (errSS / denDf);
298
403
  const pval = pf1(f, numDf, denDf, false, false);
299
404
  const name = wt === 0 ? blabs[bi] : bt === 0 ? wlabs[wt] : `${blabs[bi]}:${wlabs[wt]}`;
300
- uni.push([ss, numDf, errSS, denDf, f, pval]);
405
+ uni.push([unscale(ss), numDf, unscale(errSS), denDf, f, pval]);
406
+ uniScaled.push([ss, numDf, errSS, denDf, f, pval]);
301
407
  uniNames.push(name);
302
- errorSS.push(errSS);
408
+ errorSS.set(wt, errSS);
303
409
  let row = { name, ss, numDf, errSS, denDf, f, p: pval };
304
410
  if (corrected) {
305
411
  const hf1 = Math.min(1, hf);
@@ -313,7 +419,10 @@ export function aovEz(data, options) {
313
419
  else if (correction === "HF") {
314
420
  if (hf > 1)
315
421
  hfAbove = true;
316
- row = { ...row, numDf: hf1 * numDf, denDf: hf1 * denDf, p: phf };
422
+ // an undefined HF epsilon falls back on GG (with the warning above), not on the uncorrected test
423
+ row = Number.isNaN(hf)
424
+ ? { ...row, numDf: gg * numDf, denDf: gg * denDf, p: pgg }
425
+ : { ...row, numDf: hf1 * numDf, denDf: hf1 * denDf, p: phf };
317
426
  }
318
427
  }
319
428
  if (!(wt === 0 && bt === 0))
@@ -323,7 +432,7 @@ export function aovEz(data, options) {
323
432
  if (hfAbove)
324
433
  warnings.push("HF eps > 1 treated as 1");
325
434
  const out = {
326
- anova: anovaTable(rows, errorSS, es, observed),
435
+ anova: anovaTable(rows, errorSS, es, observed, unscale),
327
436
  univariate: { colNames: ["Sum Sq", "num Df", "Error SS", "den Df", "F value", "Pr(>F)"], rowNames: uniNames, table: uni },
328
437
  within,
329
438
  warnings,
@@ -332,6 +441,7 @@ export function aovEz(data, options) {
332
441
  out.corrections = { colNames: ["GG eps", "Pr(>F[GG])", "HF eps", "Pr(>F[HF])"], rowNames: corrNames, table: corr };
333
442
  out.sphericity = { colNames: ["Test statistic", "p-value"], rowNames: [...corrNames], table: sph };
334
443
  }
444
+ scaledTables.set(out, { colNames: out.univariate.colNames, rowNames: uniNames, table: uniScaled });
335
445
  return out;
336
446
  }
337
447
  }
@@ -6,18 +6,30 @@
6
6
  // its orthonormal Q, computed in double-double (src/models/ddLeastSquares.ts), splits the space of the observations
7
7
  // into strata: the columns of each term of the error model orthogonal to the earlier ones, and the rest ("Within").
8
8
  // In the coordinates of a stratum (Q'v restricted to it, which keeps lengths and inner products of the projections),
9
- // the treatment columns whose projection has a squared length greater than 1e-5 are kept, and the projected response
9
+ // the treatment columns whose projection has a squared length greater than 1e-14 times the column's own are kept, that
10
+ // is, those not orthogonal to the stratum up to rounding (R's aov compares the squared length with 1e-5 itself, which
11
+ // depends on the units: a covariate in small units lost its effect, and one in large units kept a projection that is
12
+ // rounding error; a threshold relative to the column's mean square instead dropped the small within-subject part of a
13
+ // covariate that varies mostly between subjects). Q is accurate to double-double, so the projection of a column
14
+ // lying in other strata is far below the threshold, and the projected response
10
15
  // is fitted on them in order with the same pivoting QR (tolerance 1e-7) as lm; the effects give the sums of squares.
11
16
  import { pf1 } from "../distributions/f.js";
17
+ import { ldexp, scaleToUnit } from "../internal/summary.js";
12
18
  import { qr } from "../linalg/qr.js";
13
19
  import { ddAdd, ddMul } from "../special/dd.js";
14
20
  import { ddLeastSquares, ddLeastSquaresMulti, ddSumSquares } from "./ddLeastSquares.js";
15
21
  import { termsOf } from "./formula.js";
16
22
  import { design } from "./modelMatrix.js";
23
+ import { scaledTables } from "./scaledTables.js";
24
+ /** Squared length of a column's projection on a stratum, relative to its own, below which it is not in the stratum */
25
+ const STRATUM_TOL = 1e-14;
17
26
  /** The table of a stratum: terms that have columns in it, then Residuals when its df is positive */
18
- function stratumTable(name, zy, zcols, assign, labels) {
27
+ function stratumTable(name, zy, zcols, assign, labels, columnSS, k) {
28
+ // zy is the response scaled by 2^-k: F and p come from it, the sums of squares are scaled back by 2^2k (the second
29
+ // table keeps them as fitted, for the effect sizes: see scaledTables.ts)
30
+ const scaleBack = (v) => ldexp(v, 2 * k);
19
31
  const dim = zy.length;
20
- const kept = zcols.flatMap((c, j) => (ddSumSquares(c)[0] > 1e-5 ? [j] : []));
32
+ const kept = zcols.flatMap((c, j) => (ddSumSquares(c)[0] > STRATUM_TOL * columnSS[j] ? [j] : []));
21
33
  let rank = 0;
22
34
  let order = [];
23
35
  let qty = zy.slice();
@@ -40,21 +52,24 @@ function stratumTable(name, zy, zcols, assign, labels) {
40
52
  const rss = ddSumSquares(qty, rank)[0];
41
53
  const rows = terms.filter((r) => r.term !== 0);
42
54
  const rowNames = rows.map((r) => labels[r.term - 1]);
43
- if (rdf > 0) {
44
- const rms = rss / rdf;
45
- const table = rows.map(({ df, ss }) => {
46
- const f = ss[0] / df / rms;
47
- return [df, ss[0], ss[0] / df, f, pf1(f, df, rdf, false, false)];
48
- });
49
- table.push([rdf, rss, rms, NaN, NaN]);
50
- return { stratum: `Error: ${name}`, colNames: ["Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"], rowNames: [...rowNames, "Residuals"], table };
51
- }
52
- return {
53
- stratum: `Error: ${name}`,
54
- colNames: ["Df", "Sum Sq", "Mean Sq"],
55
- rowNames,
56
- table: rows.map(({ df, ss }) => [df, ss[0], ss[0] / df]),
55
+ const build = (back) => {
56
+ if (rdf > 0) {
57
+ const rms = rss / rdf;
58
+ const table = rows.map(({ df, ss }) => {
59
+ const f = ss[0] / df / rms;
60
+ return [df, back(ss[0]), back(ss[0] / df), f, pf1(f, df, rdf, false, false)];
61
+ });
62
+ table.push([rdf, back(rss), back(rms), NaN, NaN]);
63
+ return { stratum: `Error: ${name}`, colNames: ["Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"], rowNames: [...rowNames, "Residuals"], table };
64
+ }
65
+ return {
66
+ stratum: `Error: ${name}`,
67
+ colNames: ["Df", "Sum Sq", "Mean Sq"],
68
+ rowNames,
69
+ table: rows.map(({ df, ss }) => [df, back(ss[0]), back(ss[0] / df)]),
70
+ };
57
71
  };
72
+ return [build(scaleBack), build((v) => v)];
58
73
  }
59
74
  /**
60
75
  * The multistratum fit of `y ~ treatment + Error(e)`.
@@ -73,6 +88,9 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
73
88
  const y = dt.y;
74
89
  if (y === undefined)
75
90
  throw new TypeError("the formula has no response");
91
+ // as R and the fit without Error() (#299: an infinite response gave NaN tables)
92
+ if (y.some((v) => !Number.isFinite(v)))
93
+ throw new RangeError("NA/NaN/Inf in 'y'");
76
94
  const de = design({ response: parsed.response, rhs: errorRhs }, data, {
77
95
  ...(options.levels === undefined ? {} : { levels: options.levels }),
78
96
  allContrasts: "contr.helmert",
@@ -83,14 +101,26 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
83
101
  const n = y.length;
84
102
  const warnings = [...dt.warnings, ...de.warnings.filter((w) => !dt.warnings.includes(w))];
85
103
  const pe = de.colNames.length;
86
- const qe = pe > 0 ? qr(de.x) : undefined;
104
+ // each column of the error model divided by its own power of 2 (exact): the strata depend only on the space the
105
+ // columns span, but the double-double decomposition squares them (a covariate around 1e-200 in Error() underflowed
106
+ // and gave other strata); columns of 0 and 1 are unchanged
107
+ const ecols = de.colNames.map((_, j) => scaleToUnit([de.x.map((r) => r[j])]).groups[0]);
108
+ const ex = de.x.map((_, i) => ecols.map((c) => c[i]));
109
+ const qe = pe > 0 ? qr(ex) : undefined;
87
110
  const re = qe?.rank ?? 0;
88
111
  if (re < pe)
89
112
  warnings.push("Error() model is singular");
90
113
  const kept = qe?.pivot.slice(0, re) ?? [];
91
114
  const toDD = (v) => v.map((t) => [t, 0]);
92
- const tcols = dt.colNames.map((_, j) => toDD(dt.x.map((r) => r[j])));
93
- const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(de.x.map((r) => r[j]))), toDD(y), tcols);
115
+ // each treatment column divided by its own power of 2 (exact): a stratum's sums of squares depend only on the space
116
+ // the columns span, and the test of a column's projection is a ratio, but its squares overflowed for a covariate
117
+ // around 1e200 and the term was dropped from every stratum
118
+ const tcols = dt.colNames.map((_, j) => toDD(scaleToUnit([dt.x.map((r) => r[j])]).groups[0]));
119
+ // the response scaled by 2^-k (exact, src/internal/summary.ts), so that its sums of squares stay in range
120
+ const { groups: scaledY, k: yScale } = scaleToUnit([y]);
121
+ const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(ecols[j])), toDD(scaledY[0]), tcols);
122
+ // the squared length of each treatment column (the scale of its threshold in stratumTable)
123
+ const columnSS = tcols.map((c) => ddSumSquares(c)[0]);
94
124
  // the strata: positions of Q's columns by term of the error model, then the rest
95
125
  const groups = [];
96
126
  kept.forEach((j, k) => {
@@ -103,6 +133,9 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
103
133
  });
104
134
  if (n > re)
105
135
  groups.push({ name: "Within", idx: Array.from({ length: n - re }, (_, i) => re + i) });
106
- const strata = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels));
107
- return { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
136
+ const both = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels, columnSS, yScale));
137
+ const strata = both.map((b) => b[0]);
138
+ const result = { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
139
+ scaledTables.set(result, both.map((b) => b[1]));
140
+ return result;
108
141
  }
@@ -1,4 +1,4 @@
1
- import type { AnovaTable } from "./anovaSequential.js";
1
+ import { type AnovaTable } from "./anovaSequential.js";
2
2
  import type { LmFormulaResult } from "./lm.js";
3
3
  /**
4
4
  * Options for {@link Anova}.
@@ -8,14 +8,18 @@
8
8
  // without the cancellation of a difference; the rank is decided in double precision as lm does, the effects are
9
9
  // computed in double-double (src/models/ddLeastSquares.ts).
10
10
  import { pf1 } from "../distributions/f.js";
11
+ import { ldexp } from "../internal/summary.js";
11
12
  import { qr } from "../linalg/qr.js";
12
13
  import { ddAdd, ddMul, ddMulNum } from "../special/dd.js";
13
14
  import { ddLeastSquares, ddSqrtWeights } from "./ddLeastSquares.js";
15
+ import { responseScale, scaledRss } from "./anovaSequential.js";
14
16
  /**
15
17
  * The sum of the squared effects of the columns `added` after the columns `base`, and the number of added columns
16
- * that are not aliased (the decrease of the residual sum of squares and the increase of the rank)
18
+ * that are not aliased (the decrease of the residual sum of squares and the increase of the rank), for the response
19
+ * scaled by 2^-k (src/internal/summary.ts) and the weights by 2^-kw (kw even, so that their square roots are scaled
20
+ * exactly)
17
21
  */
18
- function addedSS(fit, base, added) {
22
+ function addedSS(fit, base, added, k, kw = 0) {
19
23
  const cols = [...base, ...added];
20
24
  if (cols.length === 0)
21
25
  return { ss: 0, df: 0 };
@@ -24,9 +28,9 @@ function addedSS(fit, base, added) {
24
28
  const sw = rows.map((i) => (fit.weights === undefined ? 1 : Math.sqrt(fit.weights[i])));
25
29
  const q = qr(rows.map((i, k) => cols.map((j) => fit.x[i][j] * sw[k])));
26
30
  // the effects in double-double
27
- const swd = ddSqrtWeights(fit.weights === undefined ? undefined : rows.map((i) => fit.weights[i]), rows.length);
31
+ const swd = ddSqrtWeights(fit.weights === undefined ? undefined : rows.map((i) => ldexp(fit.weights[i], -kw)), rows.length);
28
32
  const kept = q.pivot.slice(0, q.rank);
29
- const { qty } = ddLeastSquares(kept.map((c) => rows.map((i, k) => ddMulNum(swd[k], fit.x[i][cols[c]]))), rows.map((i, k) => ddMulNum(swd[k], fit.y[i])));
33
+ const { qty } = ddLeastSquares(kept.map((c) => rows.map((i, k) => ddMulNum(swd[k], fit.x[i][cols[c]]))), rows.map((i, r) => ddMulNum(swd[r], ldexp(fit.y[i], -k))));
30
34
  let ss = [0, 0];
31
35
  let df = 0;
32
36
  kept.forEach((c, k) => {
@@ -74,12 +78,47 @@ export function Anova(fit, options = {}) {
74
78
  else
75
79
  throw new RangeError(`invalid type (${String(t0)}): use 2 or 3`);
76
80
  const rdf = fit.dfResidual;
77
- const rss = fit.rss;
81
+ // sums of squares of the response scaled by 2^-k: F and p from them, the Sum Sq column scaled back
82
+ const k = responseScale([fit]);
83
+ const rss = scaledRss([fit], k)[0];
78
84
  if (rdf === 0)
79
85
  throw new Error("residual df = 0");
80
- if (rss < Math.sqrt(2.220446049250313e-16))
86
+ // car compares the residual sum of squares with sqrt(eps) in the units of the data, which depends on them; here it
87
+ // is 0 within rounding error below 1e-24 times the (weighted, uncentred) sum of squares of the response, residuals
88
+ // below 1e-12 of the response's size (the level of aovEz's dataSS). sqrt(eps) times the centred total rejected data
89
+ // with R^2 above 1 - 1.5e-8 that car computes (revision of review 4)
90
+ const wy = fit.y.flatMap((v, i) => ((fit.weights?.[i] ?? 1) === 0 ? [] : [[fit.weights?.[i] ?? 1, ldexp(v, -k)]]));
91
+ // Where a sum over the weights overflows (the total of the weights of 1e308, #347), the weights are divided by an
92
+ // even power of 2 2^kw: the sums of squares are then in units of 2^(2k + kw). kw is 0 otherwise (the same bits)
93
+ const evenWeightExponent = () => {
94
+ const e = Math.floor(Math.log2(wy.reduce((a, [w]) => Math.max(a, w), 0)));
95
+ return e - (((e % 2) + 2) % 2);
96
+ };
97
+ const weightedTss = (kw) => {
98
+ const ws = wy.map(([w, v]) => [ldexp(w, -kw), v]);
99
+ const sw = ws.reduce((a, [w]) => a + w, 0);
100
+ const my = ws.reduce((a, [w, v]) => a + w * v, 0) / sw;
101
+ return Number.isFinite(sw) && Number.isFinite(my) ? ws.reduce((a, [w, v]) => a + w * (v - my) ** 2, 0) : NaN;
102
+ };
103
+ let kw = 0;
104
+ let tss = weightedTss(0);
105
+ if (!Number.isFinite(tss)) {
106
+ kw = evenWeightExponent();
107
+ tss = weightedTss(kw);
108
+ }
109
+ // (kw from the centred total as before, which the sums of squares of the terms use; the uncentred sum, at most
110
+ // 16 times the total weight, takes its own even power of 2 where it overflows)
111
+ const weightedSs = (kv) => wy.reduce((a, [w, v]) => a + ldexp(w, -kv) * v * v, 0);
112
+ let kss = kw;
113
+ let ss = weightedSs(kss);
114
+ if (!Number.isFinite(ss)) {
115
+ kss = evenWeightExponent();
116
+ ss = weightedSs(kss);
117
+ }
118
+ if (!(ldexp(rss, -kss) >= 1e-24 * ss) || rss === 0)
81
119
  throw new Error("residual sum of squares is 0 (within rounding error)");
82
- const warnings = [];
120
+ // the fit's warnings (from its model matrix and summary) first, as for aov with Error(); R gives them when fitting
121
+ const warnings = [...fit.warnings];
83
122
  const nTerms = fit.termLabels.length;
84
123
  if (type === 2 && nTerms === 0 && fit.intercept) {
85
124
  warnings.push("the model contains only an intercept: Type III test substituted");
@@ -88,36 +127,48 @@ export function Anova(fit, options = {}) {
88
127
  const columnsOf = (terms) => fit.assign.flatMap((a, j) => (terms.has(a) ? [j] : []));
89
128
  const allTerms = [...new Set(fit.assign)];
90
129
  const names = [];
91
- const rows = [];
92
- if (type === 3) {
93
- if (fit.coefficients.some((c) => Number.isNaN(c)))
94
- throw new Error("there are aliased coefficients in the model");
95
- for (const t of allTerms) {
96
- const added = columnsOf(new Set([t]));
97
- const base = columnsOf(new Set(allTerms.filter((u) => u !== t)));
98
- names.push(t === 0 ? "(Intercept)" : fit.termLabels[t - 1]);
99
- rows.push({ ss: addedSS(fit, base, added).ss, df: added.length });
130
+ let rows = [];
131
+ const termRows = (kw) => {
132
+ names.length = 0;
133
+ const out = [];
134
+ if (type === 3) {
135
+ if (fit.coefficients.some((c) => Number.isNaN(c)))
136
+ throw new Error("there are aliased coefficients in the model");
137
+ for (const t of allTerms) {
138
+ const added = columnsOf(new Set([t]));
139
+ const base = columnsOf(new Set(allTerms.filter((u) => u !== t)));
140
+ names.push(t === 0 ? "(Intercept)" : fit.termLabels[t - 1]);
141
+ out.push({ ss: addedSS(fit, base, added, k, kw).ss, df: added.length });
142
+ }
100
143
  }
101
- }
102
- else {
103
- // the variables of each term (from the factors attribute)
104
- const varsOf = (t) => fit.factors.flatMap((codes, v) => (codes[t - 1] > 0 ? [v] : []));
105
- for (const t of allTerms) {
106
- if (t === 0)
107
- continue;
108
- const vt = varsOf(t);
109
- const containing = allTerms.filter((u) => u !== 0 && u !== t && vt.every((v) => fit.factors[v][u - 1] > 0));
110
- const base = columnsOf(new Set(allTerms.filter((u) => u !== t && !containing.includes(u))));
111
- const r = addedSS(fit, base, columnsOf(new Set([t])));
112
- names.push(fit.termLabels[t - 1]);
113
- rows.push(r);
144
+ else {
145
+ // the variables of each term (from the factors attribute)
146
+ const varsOf = (t) => fit.factors.flatMap((codes, v) => (codes[t - 1] > 0 ? [v] : []));
147
+ for (const t of allTerms) {
148
+ if (t === 0)
149
+ continue;
150
+ const vt = varsOf(t);
151
+ const containing = allTerms.filter((u) => u !== 0 && u !== t && vt.every((v) => fit.factors[v][u - 1] > 0));
152
+ const base = columnsOf(new Set(allTerms.filter((u) => u !== t && !containing.includes(u))));
153
+ const r = addedSS(fit, base, columnsOf(new Set([t])), k, kw);
154
+ names.push(fit.termLabels[t - 1]);
155
+ out.push(r);
156
+ }
114
157
  }
158
+ return out;
159
+ };
160
+ rows = termRows(kw);
161
+ if (kw === 0 && fit.weights !== undefined && rows.some((r) => !Number.isFinite(r.ss))) {
162
+ kw = evenWeightExponent();
163
+ rows = termRows(kw);
115
164
  }
116
- const rms = rss / rdf;
165
+ const back = (v) => ldexp(v, 2 * k + kw);
166
+ const rssW = ldexp(rss, -kw);
167
+ const rms = rssW / rdf;
117
168
  const table = rows.map(({ ss, df }) => {
118
169
  const f = ss / df / rms;
119
- return [ss, df, f, pf1(f, df, rdf, false, false)];
170
+ return [back(ss), df, f, pf1(f, df, rdf, false, false)];
120
171
  });
121
- table.push([rss, rdf, NaN, NaN]);
172
+ table.push([back(rssW), rdf, NaN, NaN]);
122
173
  return { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings };
123
174
  }