@numero-uno-jpn/rstats 0.8.0 → 0.10.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 (122) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.ja.md +89 -13
  3. package/README.md +90 -13
  4. package/THIRD_PARTY_NOTICES.md +12 -2
  5. package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
  6. package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
  7. package/dist/chunks/chunk-7HPVUVZB.js +2 -0
  8. package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
  9. package/dist/chunks/chunk-ENL43FNO.js +2 -0
  10. package/dist/chunks/chunk-EWC6I75B.js +2 -0
  11. package/dist/chunks/chunk-IT354SHV.js +3 -0
  12. package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
  13. package/dist/chunks/chunk-O6PT7IVU.js +2 -0
  14. package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
  15. package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
  16. package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
  17. package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
  18. package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
  19. package/dist/descriptive/factanal.d.ts +56 -0
  20. package/dist/descriptive/factanal.js +186 -0
  21. package/dist/descriptive/omega.d.ts +56 -0
  22. package/dist/descriptive/omega.js +323 -0
  23. package/dist/descriptive.js +2 -2
  24. package/dist/distributions/bvnorm.d.ts +15 -0
  25. package/dist/distributions/bvnorm.js +131 -0
  26. package/dist/distributions/nbeta.js +34 -1
  27. package/dist/distributions/nchisq.d.ts +10 -0
  28. package/dist/distributions/nchisq.js +46 -0
  29. package/dist/distributions.js +2 -2
  30. package/dist/entries/distributions.d.ts +1 -0
  31. package/dist/entries/distributions.js +1 -0
  32. package/dist/entries/linalg.d.ts +2 -0
  33. package/dist/entries/linalg.js +2 -0
  34. package/dist/entries/numerics.d.ts +2 -0
  35. package/dist/entries/numerics.js +1 -0
  36. package/dist/entries/tests.d.ts +25 -1
  37. package/dist/entries/tests.js +22 -1
  38. package/dist/htest/agreement.d.ts +141 -0
  39. package/dist/htest/agreement.js +274 -0
  40. package/dist/htest/aov.d.ts +19 -0
  41. package/dist/htest/aov.js +22 -15
  42. package/dist/htest/core/simulate.d.ts +2 -0
  43. package/dist/htest/core/simulate.js +1 -1
  44. package/dist/htest/dunnett.d.ts +5 -0
  45. package/dist/htest/dunnett.js +89 -0
  46. package/dist/htest/effectSize.d.ts +112 -0
  47. package/dist/htest/effectSize.js +385 -0
  48. package/dist/htest/leveneTest.d.ts +30 -0
  49. package/dist/htest/leveneTest.js +41 -0
  50. package/dist/htest/multipleComparisons.d.ts +147 -0
  51. package/dist/htest/multipleComparisons.js +369 -0
  52. package/dist/htest/normalityTests.d.ts +44 -0
  53. package/dist/htest/normalityTests.js +164 -0
  54. package/dist/htest/polycor.d.ts +117 -0
  55. package/dist/htest/polycor.js +468 -0
  56. package/dist/htest/power.d.ts +132 -0
  57. package/dist/htest/power.js +227 -0
  58. package/dist/htest/pwr.d.ts +263 -0
  59. package/dist/htest/pwr.js +440 -0
  60. package/dist/htest/rankTests.d.ts +7 -0
  61. package/dist/htest/rankTests.js +11 -1
  62. package/dist/htest/trendTests.d.ts +57 -0
  63. package/dist/htest/trendTests.js +167 -0
  64. package/dist/linalg/eigen.d.ts +8 -0
  65. package/dist/linalg/eigen.js +5 -4
  66. package/dist/linalg/expm.d.ts +48 -0
  67. package/dist/linalg/expm.js +472 -0
  68. package/dist/linalg/schur.d.ts +48 -0
  69. package/dist/linalg/schur.js +225 -0
  70. package/dist/linalg.js +2 -2
  71. package/dist/models/anovaSequential.d.ts +58 -0
  72. package/dist/models/anovaSequential.js +138 -0
  73. package/dist/models/aovEz.d.ts +64 -0
  74. package/dist/models/aovEz.js +332 -0
  75. package/dist/models/aovStrata.d.ts +32 -0
  76. package/dist/models/aovStrata.js +104 -0
  77. package/dist/models/carAnova.d.ts +30 -0
  78. package/dist/models/carAnova.js +121 -0
  79. package/dist/models/coxph.d.ts +101 -0
  80. package/dist/models/coxph.js +502 -0
  81. package/dist/models/ddLeastSquares.d.ts +30 -0
  82. package/dist/models/ddLeastSquares.js +90 -0
  83. package/dist/models/ddMatrix.d.ts +10 -0
  84. package/dist/models/ddMatrix.js +91 -0
  85. package/dist/models/formula.d.ts +83 -0
  86. package/dist/models/formula.js +333 -0
  87. package/dist/models/glm.d.ts +226 -0
  88. package/dist/models/glm.js +546 -0
  89. package/dist/models/glmAnova.d.ts +31 -0
  90. package/dist/models/glmAnova.js +146 -0
  91. package/dist/models/glmConfint.d.ts +25 -0
  92. package/dist/models/glmConfint.js +139 -0
  93. package/dist/models/glmFamily.d.ts +66 -0
  94. package/dist/models/glmFamily.js +359 -0
  95. package/dist/models/lm.d.ts +84 -3
  96. package/dist/models/lm.js +141 -44
  97. package/dist/models/mauchly.d.ts +48 -0
  98. package/dist/models/mauchly.js +123 -0
  99. package/dist/models/modelFrame.d.ts +40 -0
  100. package/dist/models/modelFrame.js +131 -0
  101. package/dist/models/modelMatrix.d.ts +88 -0
  102. package/dist/models/modelMatrix.js +170 -0
  103. package/dist/models/survival.d.ts +87 -0
  104. package/dist/models/survival.js +238 -0
  105. package/dist/numerics.js +2 -2
  106. package/dist/optim/lbfgsb.d.ts +20 -0
  107. package/dist/optim/lbfgsb.js +1240 -0
  108. package/dist/optim/optim.d.ts +85 -0
  109. package/dist/optim/optim.js +610 -0
  110. package/dist/rstats.js +19 -3
  111. package/dist/special.js +2 -2
  112. package/dist/tests.js +18 -3
  113. package/llms.txt +102 -0
  114. package/package.json +3 -2
  115. package/dist/chunks/chunk-EJRCDJ76.js +0 -2
  116. package/dist/chunks/chunk-JERGQKZM.js +0 -2
  117. package/dist/chunks/chunk-JVYV4633.js +0 -2
  118. package/dist/chunks/chunk-LXMMKO26.js +0 -2
  119. package/dist/chunks/chunk-MJQLKEO5.js +0 -2
  120. package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
  121. package/dist/chunks/chunk-SPQC445Q.js +0 -2
  122. package/dist/chunks/chunk-U633VFH3.js +0 -2
@@ -0,0 +1,332 @@
1
+ // Repeated-measures and mixed analysis of variance as afex's aov_ez computes it (its anova_table), with car's
2
+ // univariate tests, sphericity corrections and Mauchly tests for the multivariate linear model of the wide data.
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("aovEz"); the source of afex and car was not
5
+ // read. The long data are put in wide form (one row per subject, one column per combination of the within-subject
6
+ // levels, the first within factor varying slowest). For each within term (columns P of its contr.sum coding over the
7
+ // cells) and each between term b, P'S_bP and P'EP are the cross-products of the coordinates of YP in orthonormal bases
8
+ // of the between model's columns (Householder QR in double-double, src/models/ddLeastSquares.ts): the columns of b
9
+ // orthogonal to the others for the hypothesis, the residual space for the error. The sums of squares are the traces
10
+ // of these matrices times (P'P)^-1, and the epsilons and Mauchly's W follow from P'EP (src/models/ddMatrix.ts).
11
+ import { pf1 } from "../distributions/f.js";
12
+ import { eigen } from "../linalg/eigen.js";
13
+ import { qr } from "../linalg/qr.js";
14
+ import { ddAdd, ddDiv, ddDivNum, ddMul, ddMulNum } from "../special/dd.js";
15
+ import { Anova } from "./carAnova.js";
16
+ import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
17
+ import { ddHi, ddInverse, ddMatMul, ddTrace } from "./ddMatrix.js";
18
+ import { lm } from "./lm.js";
19
+ import { mauchlyPValue, sphericityW } from "./mauchly.js";
20
+ import { compareCodePoints } from "./modelFrame.js";
21
+ import { modelMatrix } from "./modelMatrix.js";
22
+ const list = (v) => (v === undefined ? [] : typeof v === "string" ? [v] : [...v]);
23
+ const SQRT_EPS = Math.sqrt(2.220446049250313e-16);
24
+ function column(data, name) {
25
+ const c = Object.prototype.hasOwnProperty.call(data, name) ? data[name] : undefined;
26
+ if (c === undefined)
27
+ throw new Error(`object '${name}' not found`);
28
+ return Array.from(c);
29
+ }
30
+ const label = (v) => (typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : String(v));
31
+ /** Levels sorted (numbers as numbers, strings by code point) */
32
+ function sortedLevels(values) {
33
+ const distinct = [...new Set(values)];
34
+ if (distinct.every((v) => typeof v === "number"))
35
+ return distinct.sort((a, b) => a - b).map(label);
36
+ return [...new Set(distinct.map(label))].sort(compareCodePoints);
37
+ }
38
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
39
+ /**
40
+ * The anova table from the rows (intercept excluded) with the effect sizes; `errorSS` are the error sums of squares of
41
+ * all rows of the univariate table (intercept included)
42
+ */
43
+ function anovaTable(rows, errorSS, es, observed) {
44
+ const isObserved = (name) => observed.some((o) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(name));
45
+ for (const o of observed) {
46
+ if (!rows.some((r) => new RegExp(`\\b${escapeRegExp(o)}\\b`).test(r.name)))
47
+ throw new Error(`Observed variable not in data: ${o}`);
48
+ }
49
+ const distinctError = [...new Set(errorSS)].reduce((s, v) => s + v, 0);
50
+ const O = rows.reduce((s, r) => (isObserved(r.name) ? s + r.ss : s), 0);
51
+ const want = ["pes", "ges"].filter((e) => es.includes(e));
52
+ return {
53
+ colNames: ["num Df", "den Df", "MSE", "F", ...want, "Pr(>F)"],
54
+ rowNames: rows.map((r) => r.name),
55
+ table: rows.map((r) => {
56
+ 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)));
57
+ return [r.numDf, r.denDf, r.errSS / r.denDf, r.f, ...effects, r.p];
58
+ }),
59
+ };
60
+ }
61
+ /**
62
+ * Repeated-measures (within-subjects), between-subjects and mixed analysis of variance from long data, as afex's
63
+ * `aov_ez(id, dv, data, between, within, type, observed, anova_table = list(correction, es))`. Returns afex's
64
+ * anova table and car's univariate tests, sphericity corrections (Greenhouse-Geisser, Huynh-Feldt) and Mauchly tests.
65
+ *
66
+ * Between-subjects factors use `contr.sum` and sorted levels; the levels of within-subjects factors are taken in order
67
+ * of first appearance. Several rows for a subject and a cell are averaged (with afex's warning); subjects that miss
68
+ * a cell are removed (with a warning).
69
+ *
70
+ * @param data Long data: one row per observation.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * const data = {
75
+ * id: ["s1", "s1", "s2", "s2", "s3", "s3", "s4", "s4"],
76
+ * W: ["a", "b", "a", "b", "a", "b", "a", "b"],
77
+ * y: [4.1, 5.0, 3.8, 4.9, 4.4, 5.6, 4.0, 4.7],
78
+ * };
79
+ * aovEz(data, { id: "id", dv: "y", within: "W" }).anova.rowNames; // ["W"]
80
+ * ```
81
+ */
82
+ export function aovEz(data, options) {
83
+ const between = list(options.between);
84
+ const within = list(options.within);
85
+ if (between.length === 0 && within.length === 0)
86
+ throw new Error("Either between or within need to be non-NULL!");
87
+ const type = options.type ?? 3;
88
+ if (type !== 2 && type !== 3)
89
+ throw new RangeError(`invalid type (${String(type)}): use 2 or 3`);
90
+ const correction = options.correction ?? "GG";
91
+ const es = list(options.es ?? "ges");
92
+ const observed = list(options.observed);
93
+ const warnings = [];
94
+ // 1. the columns as factors
95
+ const ids = column(data, options.id).map(label);
96
+ const dv = column(data, options.dv).map((v) => {
97
+ if (typeof v !== "number")
98
+ throw new TypeError(`the response '${options.dv}' must be numeric`);
99
+ return v;
100
+ });
101
+ const bcols = between.map((b) => column(data, b));
102
+ const wcols = within.map((w) => column(data, w));
103
+ const nrow = ids.length;
104
+ for (const c of [dv, ...bcols, ...wcols])
105
+ if (c.length !== nrow)
106
+ throw new RangeError("the columns must have the same length");
107
+ const blevels = bcols.map((c) => sortedLevels(c));
108
+ const blabels = bcols.map((c) => c.map(label));
109
+ const wlabels = wcols.map((c) => c.map(label));
110
+ const wlevels = wlabels.map((c) => [...new Set(c)]);
111
+ // 2. a between factor with one level
112
+ blevels.forEach((l, k) => {
113
+ if (l.length < 2)
114
+ throw new Error(`Factor "${between[k]}" consists of one level only. Remove factor from model?`);
115
+ });
116
+ // 3. ids in more than one between cell
117
+ const idOrder = [...new Set(ids)];
118
+ const cellOf = new Map();
119
+ const multiple = new Set();
120
+ ids.forEach((id, i) => {
121
+ const key = JSON.stringify(blabels.map((c) => c[i]));
122
+ const seen = cellOf.get(id);
123
+ if (seen === undefined)
124
+ cellOf.set(id, key);
125
+ else if (seen !== key)
126
+ multiple.add(id);
127
+ });
128
+ if (multiple.size > 0) {
129
+ throw new Error(`Following ids are in more than one between subjects condition:\n${idOrder.filter((id) => multiple.has(id)).join(", ")}`);
130
+ }
131
+ // 4. the within cells, the first factor varying slowest; a cell without rows is an error
132
+ let cells = [[]];
133
+ for (const lv of wlevels)
134
+ cells = cells.flatMap((c) => lv.map((l) => [...c, l]));
135
+ const cellKey = (i) => JSON.stringify(wlabels.map((c) => c[i]));
136
+ const cellIndex = new Map(cells.map((c, k) => [JSON.stringify(c), k]));
137
+ const present = new Set(ids.map((_, i) => cellKey(i)));
138
+ if (cells.some((c) => !present.has(JSON.stringify(c))))
139
+ throw new Error("Empty cells in within-subjects design (i.e., bad data structure).");
140
+ // 5. the wide data (means of the rows of an id and a cell)
141
+ const nc = cells.length;
142
+ const sums = new Map();
143
+ ids.forEach((id, i) => {
144
+ let e = sums.get(id);
145
+ if (e === undefined)
146
+ sums.set(id, (e = { s: cells.map(() => [0, 0]), n: cells.map(() => 0) }));
147
+ const k = cellIndex.get(cellKey(i));
148
+ e.s[k] = ddAdd(e.s[k], [dv[i], 0]);
149
+ e.n[k]++;
150
+ });
151
+ if ([...sums.values()].some((e) => e.n.some((v) => v > 1))) {
152
+ 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.");
153
+ }
154
+ // 6. ids that miss a cell are removed
155
+ const missing = idOrder.filter((id) => sums.get(id).n.some((v) => v === 0));
156
+ if (missing.length > 0) {
157
+ // the ids sorted as the levels of a factor; afex goes on with a printout of the data, which is not reproduced
158
+ const sorted = [...missing].sort(compareCodePoints);
159
+ const shown = sorted.length >= 10 ? `${sorted.slice(0, 10).join(", ")}, ... [showing first 10 only]` : sorted.join(", ");
160
+ warnings.push(`Missing values for ${missing.length} ID(s), which were removed before analysis:\n${shown}`);
161
+ }
162
+ const subjects = idOrder.filter((id) => !missing.includes(id));
163
+ const firstRow = new Map();
164
+ ids.forEach((id, i) => firstRow.has(id) || firstRow.set(id, i));
165
+ const Y = subjects.map((id) => {
166
+ const e = sums.get(id);
167
+ return e.s.map((s, k) => ddDivNum(s, e.n[k]));
168
+ });
169
+ // the between data, one row per subject
170
+ const bdata = {};
171
+ between.forEach((b, k) => (bdata[b] = subjects.map((id) => blabels[k][firstRow.get(id)])));
172
+ const sum = Object.fromEntries(between.map((b) => [b, "contr.sum"]));
173
+ const blevelOpt = Object.fromEntries(between.map((b, k) => [b, blevels[k]]));
174
+ const rankDeficient = "Rank deficient model matrix; insufficient data to estimate full model.";
175
+ if (nc === 1)
176
+ return betweenOnly();
177
+ return withinAnalysis();
178
+ /** Without within-subject factors (or a single within cell): lm on one value per subject and car's Anova */
179
+ function betweenOnly() {
180
+ const dvName = between.includes("y") ? "y_" : "y";
181
+ const frame = { ...bdata, [dvName]: Y.map((r) => r[0][0]) };
182
+ const fit = lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt });
183
+ if (fit.rank < fit.coefNames.length)
184
+ throw new Error(rankDeficient);
185
+ const tab = Anova(fit, { type });
186
+ warnings.push(...tab.warnings.filter((w) => !warnings.includes(w)));
187
+ const rdf = fit.dfResidual;
188
+ const rows = tab.rowNames.flatMap((name, i) => {
189
+ if (name === "(Intercept)" || name === "Residuals")
190
+ return [];
191
+ const [ss, df, f, p] = tab.table[i];
192
+ return [{ name, ss: ss, numDf: df, errSS: fit.rss, denDf: rdf, f: f, p: p }];
193
+ });
194
+ return {
195
+ anova: anovaTable(rows, [fit.rss], es, observed),
196
+ univariate: { colNames: tab.colNames, rowNames: tab.rowNames, table: tab.table },
197
+ within,
198
+ warnings,
199
+ };
200
+ }
201
+ function withinAnalysis() {
202
+ const n = subjects.length;
203
+ // without between factors (an empty data frame) the model matrix is the column of ones
204
+ const X = between.length > 0
205
+ ? modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt })
206
+ : { colNames: ["(Intercept)"], assign: [0], x: subjects.map(() => [1]), termLabels: [], factors: [] };
207
+ const px = X.colNames.length;
208
+ if (n === 0 || qr(X.x).rank < px)
209
+ throw new Error(rankDeficient);
210
+ const d = n - px;
211
+ const bterms = [0, ...X.termLabels.map((_, j) => j + 1)];
212
+ const blabs = ["(Intercept)", ...X.termLabels];
213
+ const colsOf = (terms) => X.assign.flatMap((a, j) => (terms.includes(a) ? [j] : []));
214
+ const varsOf = (t) => X.factors.flatMap((codes, v) => (codes[t - 1] > 0 ? [v] : []));
215
+ const xcol = (j) => X.x.map((r) => [r[j], 0]);
216
+ const zero = new Array(n).fill([0, 0]);
217
+ /** Coordinates of the vectors in the columns `added` after the columns `base` (rows: one per added column) */
218
+ const coordinates = (base, added, vectors) => {
219
+ const { qtv } = ddLeastSquaresMulti([...base, ...added].map(xcol), zero, vectors);
220
+ return qtv.map((v) => v.slice(base.length, base.length + added.length));
221
+ };
222
+ const residualCoordinates = (vectors) => {
223
+ const { qtv } = ddLeastSquaresMulti(X.colNames.map((_, j) => xcol(j)), zero, vectors);
224
+ return qtv.map((v) => v.slice(px));
225
+ };
226
+ // the within design over the cells
227
+ const cdata = Object.fromEntries(within.map((w, k) => [w, cells.map((c) => c[k])]));
228
+ const W = modelMatrix(`~ ${within.join(" * ")}`, cdata, {
229
+ contrasts: Object.fromEntries(within.map((w) => [w, "contr.sum"])),
230
+ levels: Object.fromEntries(within.map((w, k) => [w, wlevels[k]])),
231
+ });
232
+ const wterms = [0, ...W.termLabels.map((_, j) => j + 1)];
233
+ const wlabs = ["(Intercept)", ...W.termLabels];
234
+ const cross = (C) => {
235
+ // C: one array per column of YP (its coordinates); returns C'C
236
+ return C.map((a) => C.map((b) => {
237
+ let s = [0, 0];
238
+ a.forEach((v, i) => (s = ddAdd(s, ddMul(v, b[i]))));
239
+ return s;
240
+ }));
241
+ };
242
+ const uni = [];
243
+ const uniNames = [];
244
+ const corr = [];
245
+ const sph = [];
246
+ const corrNames = [];
247
+ const rows = [];
248
+ const errorSS = [];
249
+ let hfAbove = false;
250
+ for (const wt of wterms) {
251
+ const wc = W.assign.flatMap((a, j) => (a === wt ? [j] : []));
252
+ const p = wc.length;
253
+ // YP, one array per column of P
254
+ const YP = wc.map((j) => Y.map((r) => r.reduce((s, v, c) => ddAdd(s, ddMulNum(v, W.x[c][j])), [0, 0])));
255
+ const PtP = wc.map((a) => wc.map((b) => [W.x.reduce((s, r) => s + r[a] * r[b], 0), 0]));
256
+ const M = ddInverse(PtP);
257
+ const PEP = cross(residualCoordinates(YP));
258
+ const A = ddMatMul(PEP, M);
259
+ const errSS = ddTrace(A)[0];
260
+ let gg = NaN;
261
+ let hf = NaN;
262
+ let mw = NaN;
263
+ let mp = NaN;
264
+ let corrected = false;
265
+ if (p >= 2) {
266
+ const ev = eigen(ddHi(PEP), { symmetric: true, onlyValues: true }).values;
267
+ if (ev.filter((v) => v >= SQRT_EPS).length === p) {
268
+ corrected = true;
269
+ const tA = ddTrace(A);
270
+ gg = ddDiv(ddMul(tA, tA), ddMulNum(ddTrace(ddMatMul(A, A)), p))[0];
271
+ hf = ((d + 1) * p * gg - 2) / (p * (d - p * gg));
272
+ mw = sphericityW(ddMatMul(M, PEP));
273
+ mp = mauchlyPValue(mw, p, d, nc);
274
+ }
275
+ }
276
+ for (let bi = 0; bi < bterms.length; bi++) {
277
+ const bt = bterms[bi];
278
+ let C;
279
+ if (type === 3)
280
+ C = coordinates(colsOf(bterms.filter((u) => u !== bt)), colsOf([bt]), YP);
281
+ else if (bt === 0)
282
+ C = coordinates([], colsOf([0]), YP);
283
+ else {
284
+ const vt = varsOf(bt);
285
+ const rel = bterms.filter((u) => u !== 0 && u !== bt && vt.every((v) => X.factors[v][u - 1] > 0));
286
+ C = coordinates(colsOf(bterms.filter((u) => u !== bt && !rel.includes(u))), colsOf([bt]), YP);
287
+ }
288
+ const ss = ddTrace(ddMatMul(cross(C), M))[0];
289
+ const dfb = bt === 0 ? 1 : colsOf([bt]).length;
290
+ const numDf = dfb * p;
291
+ const denDf = d * p;
292
+ const f = ss / numDf / (errSS / denDf);
293
+ const pval = pf1(f, numDf, denDf, false, false);
294
+ const name = wt === 0 ? blabs[bi] : bt === 0 ? wlabs[wt] : `${blabs[bi]}:${wlabs[wt]}`;
295
+ uni.push([ss, numDf, errSS, denDf, f, pval]);
296
+ uniNames.push(name);
297
+ errorSS.push(errSS);
298
+ let row = { name, ss, numDf, errSS, denDf, f, p: pval };
299
+ if (corrected) {
300
+ const hf1 = Math.min(1, hf);
301
+ const pgg = pf1(f, gg * numDf, gg * denDf, false, false);
302
+ const phf = pf1(f, hf1 * numDf, hf1 * denDf, false, false);
303
+ corr.push([gg, pgg, hf, phf]);
304
+ sph.push([mw, mp]);
305
+ corrNames.push(name);
306
+ if (correction === "GG")
307
+ row = { ...row, numDf: gg * numDf, denDf: gg * denDf, p: pgg };
308
+ else if (correction === "HF") {
309
+ if (hf > 1)
310
+ hfAbove = true;
311
+ row = { ...row, numDf: hf1 * numDf, denDf: hf1 * denDf, p: phf };
312
+ }
313
+ }
314
+ if (!(wt === 0 && bt === 0))
315
+ rows.push(row);
316
+ }
317
+ }
318
+ if (hfAbove)
319
+ warnings.push("HF eps > 1 treated as 1");
320
+ const out = {
321
+ anova: anovaTable(rows, errorSS, es, observed),
322
+ univariate: { colNames: ["Sum Sq", "num Df", "Error SS", "den Df", "F value", "Pr(>F)"], rowNames: uniNames, table: uni },
323
+ within,
324
+ warnings,
325
+ };
326
+ if (corr.length > 0) {
327
+ out.corrections = { colNames: ["GG eps", "Pr(>F[GG])", "HF eps", "Pr(>F[HF])"], rowNames: corrNames, table: corr };
328
+ out.sphericity = { colNames: ["Test statistic", "p-value"], rowNames: [...corrNames], table: sph };
329
+ }
330
+ return out;
331
+ }
332
+ }
@@ -0,0 +1,32 @@
1
+ import type { FormulaNode, ParsedFormula } from "./formula.js";
2
+ import type { LmFormulaOptions } from "./lm.js";
3
+ import type { DataFrame } from "./modelFrame.js";
4
+ /** The table of one error stratum, as `summary(aov(...))` prints it. */
5
+ export interface AovStratum {
6
+ /** `"Error: id"`, `"Error: id:W"`, `"Error: Within"`. */
7
+ stratum: string;
8
+ colNames: string[];
9
+ rowNames: string[];
10
+ /** One array per row; NaN where R prints nothing. */
11
+ table: number[][];
12
+ }
13
+ /** Result of {@link aov} with an `Error()` term. */
14
+ export interface AovStrataFit {
15
+ /** The formula. */
16
+ formula: string;
17
+ /** Always true: the fit has error strata (pass it to {@link aovSummary}). */
18
+ multistratum: true;
19
+ /** The tables of the strata, in order (the intercept stratum included when the model has one). */
20
+ strata: AovStratum[];
21
+ /** 0-based indices of the rows of `data` used. */
22
+ rows: number[];
23
+ /** R's warnings, such as `Error() model is singular`. */
24
+ warnings: string[];
25
+ }
26
+ /**
27
+ * The multistratum fit of `y ~ treatment + Error(e)`.
28
+ *
29
+ * @param treatment The right-hand side without the Error() term.
30
+ * @param errorRhs The argument of Error().
31
+ */
32
+ export declare function aovStrataFit(formula: string, parsed: ParsedFormula, treatment: FormulaNode | undefined, errorRhs: FormulaNode, data: DataFrame, options: LmFormulaOptions): AovStrataFit;
@@ -0,0 +1,104 @@
1
+ // Analysis of variance with an Error() term (several error strata): R's aov(y ~ treatment + Error(e), data) and the
2
+ // tables of summary() for it.
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Error strata"). The error model y ~ e is
5
+ // coded with contr.helmert and decomposed by the pivoting QR of src/linalg/qr.ts (rank and aliased columns as lm);
6
+ // its orthonormal Q, computed in double-double (src/models/ddLeastSquares.ts), splits the space of the observations
7
+ // into strata: the columns of each term of the error model orthogonal to the earlier ones, and the rest ("Within").
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
10
+ // is fitted on them in order with the same pivoting QR (tolerance 1e-7) as lm; the effects give the sums of squares.
11
+ import { pf1 } from "../distributions/f.js";
12
+ import { qr } from "../linalg/qr.js";
13
+ import { ddAdd, ddMul } from "../special/dd.js";
14
+ import { ddLeastSquares, ddLeastSquaresMulti, ddSumSquares } from "./ddLeastSquares.js";
15
+ import { design } from "./modelMatrix.js";
16
+ /** The table of a stratum: terms that have columns in it, then Residuals when its df is positive */
17
+ function stratumTable(name, zy, zcols, assign, labels) {
18
+ const dim = zy.length;
19
+ const kept = zcols.flatMap((c, j) => (ddSumSquares(c)[0] > 1e-5 ? [j] : []));
20
+ let rank = 0;
21
+ let order = [];
22
+ let qty = zy.slice();
23
+ if (kept.length > 0) {
24
+ const q = qr(Array.from({ length: dim }, (_, i) => kept.map((j) => zcols[j][i][0])));
25
+ rank = q.rank;
26
+ order = q.pivot.slice(0, rank).map((k) => kept[k]);
27
+ qty = ddLeastSquares(order.map((j) => zcols[j]), zy).qty;
28
+ }
29
+ const terms = [];
30
+ order.forEach((j, k) => {
31
+ const t = assign[j];
32
+ let row = terms.find((r) => r.term === t);
33
+ if (row === undefined)
34
+ terms.push((row = { term: t, df: 0, ss: [0, 0] }));
35
+ row.df++;
36
+ row.ss = ddAdd(row.ss, ddMul(qty[k], qty[k]));
37
+ });
38
+ const rdf = dim - rank;
39
+ const rss = ddSumSquares(qty, rank)[0];
40
+ const rows = terms.filter((r) => r.term !== 0);
41
+ const rowNames = rows.map((r) => labels[r.term - 1]);
42
+ if (rdf > 0) {
43
+ const rms = rss / rdf;
44
+ const table = rows.map(({ df, ss }) => {
45
+ const f = ss[0] / df / rms;
46
+ return [df, ss[0], ss[0] / df, f, pf1(f, df, rdf, false, false)];
47
+ });
48
+ table.push([rdf, rss, rms, NaN, NaN]);
49
+ return { stratum: `Error: ${name}`, colNames: ["Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)"], rowNames: [...rowNames, "Residuals"], table };
50
+ }
51
+ return {
52
+ stratum: `Error: ${name}`,
53
+ colNames: ["Df", "Sum Sq", "Mean Sq"],
54
+ rowNames,
55
+ table: rows.map(({ df, ss }) => [df, ss[0], ss[0] / df]),
56
+ };
57
+ }
58
+ /**
59
+ * The multistratum fit of `y ~ treatment + Error(e)`.
60
+ *
61
+ * @param treatment The right-hand side without the Error() term.
62
+ * @param errorRhs The argument of Error().
63
+ */
64
+ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options) {
65
+ if (options.weights !== undefined)
66
+ throw new Error("weights are not supported in a multistratum aov() fit");
67
+ // y ~ Error(id): no treatment terms, the intercept only
68
+ const dt = design(parsed, data, { ...options, dropUnusedLevels: true }, treatment ?? { type: "num", value: 1, text: "1" });
69
+ const y = dt.y;
70
+ if (y === undefined)
71
+ throw new TypeError("the formula has no response");
72
+ const de = design({ response: parsed.response, rhs: errorRhs }, data, {
73
+ ...(options.levels === undefined ? {} : { levels: options.levels }),
74
+ allContrasts: "contr.helmert",
75
+ intercept: dt.terms.intercept,
76
+ extraVariables: dt.terms.variables,
77
+ dropUnusedLevels: true,
78
+ });
79
+ const n = y.length;
80
+ const warnings = [...dt.warnings, ...de.warnings.filter((w) => !dt.warnings.includes(w))];
81
+ const pe = de.colNames.length;
82
+ const qe = pe > 0 ? qr(de.x) : undefined;
83
+ const re = qe?.rank ?? 0;
84
+ if (re < pe)
85
+ warnings.push("Error() model is singular");
86
+ const kept = qe?.pivot.slice(0, re) ?? [];
87
+ const toDD = (v) => v.map((t) => [t, 0]);
88
+ const tcols = dt.colNames.map((_, j) => toDD(dt.x.map((r) => r[j])));
89
+ const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(de.x.map((r) => r[j]))), toDD(y), tcols);
90
+ // the strata: positions of Q's columns by term of the error model, then the rest
91
+ const groups = [];
92
+ kept.forEach((j, k) => {
93
+ const a = de.assign[j];
94
+ const name = a === 0 ? "(Intercept)" : de.terms.termLabels[a - 1];
95
+ let g = groups.find((x) => x.name === name);
96
+ if (g === undefined)
97
+ groups.push((g = { name, idx: [] }));
98
+ g.idx.push(k);
99
+ });
100
+ if (n > re)
101
+ groups.push({ name: "Within", idx: Array.from({ length: n - re }, (_, i) => re + i) });
102
+ 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));
103
+ return { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
104
+ }
@@ -0,0 +1,30 @@
1
+ import type { AnovaTable } from "./anovaSequential.js";
2
+ import type { LmFormulaResult } from "./lm.js";
3
+ /** Options for {@link Anova}. */
4
+ export interface AnovaOptions {
5
+ /** The type of the tests: 2 (default, as car) or 3; `"II"` and `"III"` are accepted too. */
6
+ type?: 2 | 3 | "II" | "III";
7
+ }
8
+ /**
9
+ * Type II or type III tests of the terms of a linear model, equivalent to `car::Anova(fit, type = 2)` or `type = 3`
10
+ * for an `lm` fit. Columns `Sum Sq`, `Df`, `F value`, `Pr(>F)`; rows the terms (type III: `(Intercept)` first when the
11
+ * model has one) and `Residuals`.
12
+ *
13
+ * Type II tests each term after all the others except the terms that contain it (car's marginality; it does not
14
+ * depend on the contrasts). Type III tests each column set of the model's own matrix after all the other columns, so
15
+ * it depends on the contrasts (`contr.sum` is the usual choice).
16
+ *
17
+ * Errors as car: `residual df = 0`, `residual sum of squares is 0 (within rounding error)`, and for type III `there
18
+ * are aliased coefficients in the model`. Type II of a model with only an intercept gives the type III table with a
19
+ * warning.
20
+ *
21
+ * @param fit A fit from {@link lm} with a formula.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const data = { y: [4.2, 5.1, 6.3, 5.8, 7.9, 8.4, 6.1, 7.2], A: ["a", "a", "b", "b", "a", "a", "b", "b"], B: ["p", "q", "p", "q", "p", "q", "p", "q"] };
26
+ * const t = Anova(lm("y ~ A * B", data, { contrasts: { A: "contr.sum", B: "contr.sum" } }), { type: 3 });
27
+ * t.rowNames; // ["(Intercept)", "A", "B", "A:B", "Residuals"]
28
+ * ```
29
+ */
30
+ export declare function Anova(fit: LmFormulaResult, options?: AnovaOptions): AnovaTable;
@@ -0,0 +1,121 @@
1
+ // Type II and type III tests of linear models fitted from a formula, as car's Anova(fit, type = 2 or 3).
2
+ //
3
+ // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Anova(fit, { type })"); car's source was
4
+ // not read. Both tests compare the least squares fit on a subset of the model matrix's columns with the fit that adds
5
+ // the columns of the term tested: type II drops the term and the terms that contain it, type III the term alone.
6
+ // The difference of the residual sums of squares is computed as the sum of the squared effects of the added columns
7
+ // in a QR decomposition (same pivoting and tolerance as lm) with the other columns first, which is the same quantity
8
+ // without the cancellation of a difference; the rank is decided in double precision as lm does, the effects are
9
+ // computed in double-double (src/models/ddLeastSquares.ts).
10
+ import { pf1 } from "../distributions/f.js";
11
+ import { qr } from "../linalg/qr.js";
12
+ import { ddAdd, ddMul, ddMulNum } from "../special/dd.js";
13
+ import { ddLeastSquares, ddSqrtWeights } from "./ddLeastSquares.js";
14
+ /**
15
+ * 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)
17
+ */
18
+ function addedSS(fit, base, added) {
19
+ const cols = [...base, ...added];
20
+ if (cols.length === 0)
21
+ return { ss: 0, df: 0 };
22
+ const rows = fit.y.flatMap((_, i) => (fit.weights === undefined || fit.weights[i] !== 0 ? [i] : []));
23
+ // the rank and the aliased columns as lm decides them (double precision, sqrt(w) rounded as lm does)
24
+ const sw = rows.map((i) => (fit.weights === undefined ? 1 : Math.sqrt(fit.weights[i])));
25
+ const q = qr(rows.map((i, k) => cols.map((j) => fit.x[i][j] * sw[k])));
26
+ // the effects in double-double
27
+ const swd = ddSqrtWeights(fit.weights === undefined ? undefined : rows.map((i) => fit.weights[i]), rows.length);
28
+ 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])));
30
+ let ss = [0, 0];
31
+ let df = 0;
32
+ kept.forEach((c, k) => {
33
+ if (c >= base.length) {
34
+ ss = ddAdd(ss, ddMul(qty[k], qty[k]));
35
+ df++;
36
+ }
37
+ });
38
+ return { ss: ss[0], df };
39
+ }
40
+ /**
41
+ * Type II or type III tests of the terms of a linear model, equivalent to `car::Anova(fit, type = 2)` or `type = 3`
42
+ * for an `lm` fit. Columns `Sum Sq`, `Df`, `F value`, `Pr(>F)`; rows the terms (type III: `(Intercept)` first when the
43
+ * model has one) and `Residuals`.
44
+ *
45
+ * Type II tests each term after all the others except the terms that contain it (car's marginality; it does not
46
+ * depend on the contrasts). Type III tests each column set of the model's own matrix after all the other columns, so
47
+ * it depends on the contrasts (`contr.sum` is the usual choice).
48
+ *
49
+ * Errors as car: `residual df = 0`, `residual sum of squares is 0 (within rounding error)`, and for type III `there
50
+ * are aliased coefficients in the model`. Type II of a model with only an intercept gives the type III table with a
51
+ * warning.
52
+ *
53
+ * @param fit A fit from {@link lm} with a formula.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const data = { y: [4.2, 5.1, 6.3, 5.8, 7.9, 8.4, 6.1, 7.2], A: ["a", "a", "b", "b", "a", "a", "b", "b"], B: ["p", "q", "p", "q", "p", "q", "p", "q"] };
58
+ * const t = Anova(lm("y ~ A * B", data, { contrasts: { A: "contr.sum", B: "contr.sum" } }), { type: 3 });
59
+ * t.rowNames; // ["(Intercept)", "A", "B", "A:B", "Residuals"]
60
+ * ```
61
+ */
62
+ export function Anova(fit, options = {}) {
63
+ if (typeof fit !== "object" || fit === null || !Array.isArray(fit.effects)) {
64
+ throw new TypeError("Anova() needs a fit from lm() with a formula");
65
+ }
66
+ const t0 = options.type ?? 2;
67
+ let type;
68
+ if (t0 === 2 || t0 === "II")
69
+ type = 2;
70
+ else if (t0 === 3 || t0 === "III")
71
+ type = 3;
72
+ else
73
+ throw new RangeError(`invalid type (${String(t0)}): use 2 or 3`);
74
+ const rdf = fit.dfResidual;
75
+ const rss = fit.rss;
76
+ if (rdf === 0)
77
+ throw new Error("residual df = 0");
78
+ if (rss < Math.sqrt(2.220446049250313e-16))
79
+ throw new Error("residual sum of squares is 0 (within rounding error)");
80
+ const warnings = [];
81
+ const nTerms = fit.termLabels.length;
82
+ if (type === 2 && nTerms === 0 && fit.intercept) {
83
+ warnings.push("the model contains only an intercept: Type III test substituted");
84
+ type = 3;
85
+ }
86
+ const columnsOf = (terms) => fit.assign.flatMap((a, j) => (terms.has(a) ? [j] : []));
87
+ const allTerms = [...new Set(fit.assign)];
88
+ const names = [];
89
+ const rows = [];
90
+ if (type === 3) {
91
+ if (fit.coefficients.some((c) => Number.isNaN(c)))
92
+ throw new Error("there are aliased coefficients in the model");
93
+ for (const t of allTerms) {
94
+ const added = columnsOf(new Set([t]));
95
+ const base = columnsOf(new Set(allTerms.filter((u) => u !== t)));
96
+ names.push(t === 0 ? "(Intercept)" : fit.termLabels[t - 1]);
97
+ rows.push({ ss: addedSS(fit, base, added).ss, df: added.length });
98
+ }
99
+ }
100
+ else {
101
+ // the variables of each term (from the factors attribute)
102
+ const varsOf = (t) => fit.factors.flatMap((codes, v) => (codes[t - 1] > 0 ? [v] : []));
103
+ for (const t of allTerms) {
104
+ if (t === 0)
105
+ continue;
106
+ const vt = varsOf(t);
107
+ const containing = allTerms.filter((u) => u !== 0 && u !== t && vt.every((v) => fit.factors[v][u - 1] > 0));
108
+ const base = columnsOf(new Set(allTerms.filter((u) => u !== t && !containing.includes(u))));
109
+ const r = addedSS(fit, base, columnsOf(new Set([t])));
110
+ names.push(fit.termLabels[t - 1]);
111
+ rows.push(r);
112
+ }
113
+ }
114
+ const rms = rss / rdf;
115
+ const table = rows.map(({ ss, df }) => {
116
+ const f = ss / df / rms;
117
+ return [ss, df, f, pf1(f, df, rdf, false, false)];
118
+ });
119
+ table.push([rss, rdf, NaN, NaN]);
120
+ return { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings };
121
+ }