@numero-uno-jpn/rstats 0.15.2 → 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.
- package/CHANGELOG.md +280 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +35 -5
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +87 -8
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +11 -1
- package/dist/distributions/f.js +73 -22
- package/dist/distributions/gamma.js +61 -6
- package/dist/distributions/geometric.js +53 -14
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +6 -1
- package/dist/distributions/kumaraswamy.js +22 -4
- package/dist/distributions/laplace.js +31 -7
- package/dist/distributions/logistic.js +11 -2
- package/dist/distributions/lognormal.js +20 -3
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +128 -35
- package/dist/distributions/nchisq.js +85 -14
- package/dist/distributions/negbinomial.js +100 -18
- package/dist/distributions/normal.js +35 -5
- package/dist/distributions/nt.d.ts +28 -3
- package/dist/distributions/nt.js +536 -35
- package/dist/distributions/pareto.js +9 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/t.js +55 -3
- package/dist/distributions/triangular.js +45 -13
- package/dist/distributions/tukey.js +21 -2
- package/dist/distributions/uniform.js +2 -0
- package/dist/distributions/weibull.js +33 -3
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +23 -1
- package/dist/internal/ddexp.js +86 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.d.ts +5 -0
- package/dist/internal/invert.js +25 -7
- package/dist/internal/noncentral.d.ts +7 -0
- package/dist/internal/noncentral.js +9 -0
- package/dist/internal/poissonMixture.js +29 -6
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +11 -1
- package/dist/special/choose.js +17 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +15 -2
- package/dist/special/igam.js +33 -6
- package/dist/special/incbet.js +100 -10
- package/dist/special/incbetLargeA.js +7 -2
- package/dist/special/incbetPrefactor.d.ts +5 -0
- package/dist/special/incbetPrefactor.js +14 -3
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +179 -33
- package/dist/special/log1pmx.js +4 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- package/dist/chunks/chunk-2CUKVVRO.js +0 -2
- package/dist/chunks/chunk-3WQCKGKP.js +0 -2
- package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
- package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
- package/dist/chunks/chunk-D4F7GQAY.js +0 -2
- package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
- package/dist/chunks/chunk-HBMHR5SS.js +0 -2
- package/dist/chunks/chunk-IBPWRQIF.js +0 -2
- package/dist/chunks/chunk-JLAH3X77.js +0 -2
- package/dist/chunks/chunk-LG74QY5U.js +0 -2
- package/dist/chunks/chunk-PEYGUK32.js +0 -2
- package/dist/chunks/chunk-Q4PGYESP.js +0 -2
- package/dist/chunks/chunk-RCAL4VHM.js +0 -3
- package/dist/chunks/chunk-SREPSVTT.js +0 -2
- package/dist/chunks/chunk-UFT662QZ.js +0 -2
- package/dist/chunks/chunk-VWJ74UHC.js +0 -2
- package/dist/chunks/chunk-XNPU54NH.js +0 -2
- package/dist/chunks/chunk-XPLDEK6D.js +0 -2
- package/dist/chunks/chunk-YGT4P7EU.js +0 -2
- package/dist/chunks/chunk-YVREYVI2.js +0 -2
package/dist/models/aovEz.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
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) =>
|
|
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) =>
|
|
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 = [...
|
|
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
|
-
|
|
101
|
-
|
|
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((
|
|
107
|
-
const wcols = within.map((
|
|
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 [
|
|
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
|
-
|
|
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
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
272
|
-
|
|
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
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
}
|
package/dist/models/aovStrata.js
CHANGED
|
@@ -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-
|
|
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] >
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
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
|
-
|
|
93
|
-
|
|
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
|
|
107
|
-
|
|
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
|
}
|
package/dist/models/carAnova.js
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
|
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([
|
|
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
|
}
|