@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
package/dist/models/lm.js CHANGED
@@ -1,4 +1,4 @@
1
- // Linear models with a matrix interface: R's lm (with summary.lm's table), confint and predict.
1
+ // Linear models: R's lm (with summary.lm's table) from a matrix or from a formula, confint and predict.
2
2
  //
3
3
  // Written for rStats.js (no ported code). The fit is the QR decomposition of the model matrix (a column of ones
4
4
  // first unless `intercept` is false, rows scaled by sqrt(weights)) with R's LINPACK pivoting (src/linalg/qr.ts,
@@ -7,27 +7,65 @@
7
7
  // covariance of the estimates sigma^2 (R'R)^-1 from the triangular factor, t tests on n - rank degrees of freedom,
8
8
  // R^2 from the (weighted) mean-corrected model sum of squares when there is an intercept, and the overall F test.
9
9
  // Rows of weight 0 are left out of the fit and of the counts of observations, but get fitted values (and residuals)
10
- // from the coefficients, as in R.
10
+ // from the coefficients, as in R. The formula form fits the model matrix of src/models/modelMatrix.ts the same way
11
+ // (the same decomposition decides the rank and the aliased columns), recomputes the coefficients, fitted values,
12
+ // residuals, effects Q'y and sums of squares in double-double on the columns kept (src/models/ddLeastSquares.ts), and
13
+ // keeps what the analyses of variance need (the effects, the model matrix, the terms).
11
14
  import { pf1 } from "../distributions/f.js";
12
15
  import { pt1, qt1 } from "../distributions/t.js";
13
16
  import { chol2inv } from "../linalg/chol.js";
14
17
  import { qr, qrCoef, qrResid } from "../linalg/qr.js";
15
- /**
16
- * Fit a linear model by least squares. Equivalent to R's `lm(y ~ x)` (or `y ~ x - 1` without intercept, with
17
- * `weights` for weighted least squares) together with `summary()`; the predictors are given as a matrix instead of a
18
- * formula. Rows with a missing value in `x`, `y` or the weights are dropped.
19
- *
20
- * @param x Predictors: a matrix (array of rows, one column per predictor) or a vector (one predictor).
21
- * @param y Response.
22
- *
23
- * @example
24
- * ```ts
25
- * const fit = lm([1, 2, 3, 4, 5], [2.1, 3.9, 6.2, 7.8, 10.1]);
26
- * fit.coefficients; // [intercept, slope]
27
- * fit.rSquared;
28
- * ```
29
- */
18
+ import { ddAdd, ddDiv, ddMul, ddMulNum, ddSub } from "../special/dd.js";
19
+ import { ddLeastSquares, ddSqrtWeights, ddSumSquares } from "./ddLeastSquares.js";
20
+ import { parseFormula } from "./formula.js";
21
+ import { design } from "./modelMatrix.js";
22
+ /** The formula fit (lm, and aov without Error()) */
23
+ export function lmFormulaFit(formula, d, aov) {
24
+ const y = d.y;
25
+ if (y === undefined)
26
+ throw new TypeError("the formula has no response");
27
+ const core = fitLm(d.x, y, d.frame.weights, d.terms.intercept, true);
28
+ const r = core.result;
29
+ const warnings = [...d.warnings];
30
+ if (!aov) {
31
+ // summary.lm: residual variance negligible against the fitted values' mean square and variance
32
+ const f = core.fitRows.map((i) => r.fittedValues[i]);
33
+ const m = f.reduce((s, v) => s + v, 0) / f.length;
34
+ const v = f.length > 1 ? f.reduce((s, t) => s + (t - m) ** 2, 0) / (f.length - 1) : NaN;
35
+ const resvar = core.rss / r.dfResidual;
36
+ if (Number.isFinite(resvar) && resvar < 1e-30 * (m * m + v))
37
+ warnings.push("essentially perfect fit: summary may be unreliable");
38
+ }
39
+ const out = {
40
+ ...r,
41
+ formula,
42
+ response: d.terms.variables[0],
43
+ coefNames: d.colNames,
44
+ assign: d.assign,
45
+ termLabels: d.terms.termLabels,
46
+ order: d.terms.order,
47
+ variables: d.terms.variables,
48
+ factors: d.terms.factors,
49
+ rows: d.frame.rows,
50
+ x: d.x,
51
+ y,
52
+ effects: core.effects,
53
+ rss: core.rss,
54
+ nObs: core.fitRows.length,
55
+ aov,
56
+ warnings,
57
+ };
58
+ if (d.frame.weights !== undefined)
59
+ out.weights = d.frame.weights;
60
+ return out;
61
+ }
30
62
  export function lm(x, y, options = {}) {
63
+ if (typeof x === "string") {
64
+ return lmFormulaFit(x, design(parseFormula(x), y, { ...options, dropUnusedLevels: true }), false);
65
+ }
66
+ return lmMatrix(x, y, options);
67
+ }
68
+ function lmMatrix(x, y, options) {
31
69
  const intercept = options.intercept ?? true;
32
70
  const xr = x.length > 0 && typeof x[0] !== "number" ? x.map((r) => Array.from(r)) : Array.from(x, (v) => [v]);
33
71
  const ys = Array.from(y);
@@ -42,6 +80,58 @@ export function lm(x, y, options = {}) {
42
80
  const Xall = xr.filter((_, i) => keep[i]).map((r) => (intercept ? [1, ...r] : r));
43
81
  const Yall = ys.filter((_, i) => keep[i]);
44
82
  const Wall = wsAll?.filter((_, i) => keep[i]);
83
+ return fitLm(Xall, Yall, Wall, intercept).result;
84
+ }
85
+ /**
86
+ * The coefficients, fitted values, residuals, effects and sums of squares of a fit recomputed in double-double on the
87
+ * columns kept by the double-precision decomposition q (its rank and pivoting decide what is aliased)
88
+ */
89
+ function preciseFit(Xall, Yall, Wall, fitRows, q, intercept) {
90
+ const rank = q.rank;
91
+ const piv = q.pivot.slice(0, rank);
92
+ const sw = ddSqrtWeights(Wall === undefined ? undefined : fitRows.map((i) => Wall[i]), fitRows.length);
93
+ const cols = piv.map((j) => fitRows.map((i, k) => ddMulNum(sw[k], Xall[i][j])));
94
+ const { qty, coef } = ddLeastSquares(cols, fitRows.map((i, k) => ddMulNum(sw[k], Yall[i])));
95
+ const coefficients = Xall[0]?.map(() => NaN) ?? [];
96
+ piv.forEach((j, k) => (coefficients[j] = coef[k][0]));
97
+ // fitted values x'b of every row (aliased coefficients count as 0)
98
+ const fitted = Xall.map((r) => {
99
+ let f = [0, 0];
100
+ piv.forEach((j, k) => (f = ddAdd(f, ddMulNum(coef[k], r[j]))));
101
+ return f;
102
+ });
103
+ const rss = ddSumSquares(qty, rank)[0];
104
+ // model sum of squares (about the weighted mean with an intercept)
105
+ const w = fitRows.map((i) => Wall?.[i] ?? 1);
106
+ let center = [0, 0];
107
+ if (intercept) {
108
+ let sw0 = [0, 0];
109
+ let sf = [0, 0];
110
+ fitRows.forEach((i, k) => {
111
+ sw0 = ddAdd(sw0, [w[k], 0]);
112
+ sf = ddAdd(sf, ddMulNum(fitted[i], w[k]));
113
+ });
114
+ center = ddDiv(sf, sw0);
115
+ }
116
+ let mss = [0, 0];
117
+ fitRows.forEach((i, k) => {
118
+ const d = ddSub(fitted[i], center);
119
+ mss = ddAdd(mss, ddMulNum(ddMul(d, d), w[k]));
120
+ });
121
+ return {
122
+ coefficients,
123
+ fittedValues: fitted.map((f) => f[0]),
124
+ residuals: fitted.map((f, i) => ddSub([Yall[i], 0], f)[0]),
125
+ effects: qty.map((e) => e[0]),
126
+ rss,
127
+ mss: mss[0],
128
+ };
129
+ }
130
+ /**
131
+ * Least squares on a full model matrix (the column of ones included when `intercept` is true). Rows of weight 0 are
132
+ * left out of the fit and of the counts.
133
+ */
134
+ export function fitLm(Xall, Yall, Wall, intercept, precise = false) {
45
135
  if (Yall.length === 0)
46
136
  throw new RangeError("0 (non-NA) cases");
47
137
  // the fit uses the rows of non-zero weight only
@@ -52,37 +142,41 @@ export function lm(x, y, options = {}) {
52
142
  const n = Y.length;
53
143
  if (n === 0)
54
144
  throw new RangeError("all weights are zero");
145
+ const fitRows = Yall.flatMap((_, i) => (fitRow[i] ? [i] : []));
55
146
  const sw = W?.map(Math.sqrt);
56
147
  const Xw = sw === undefined ? X : X.map((r, i) => r.map((v) => v * sw[i]));
57
148
  const Yw = sw === undefined ? Y : Y.map((v, i) => v * sw[i]);
58
149
  const q = qr(Xw);
59
150
  const rank = q.rank;
60
- const coefficients = qrCoef(q, Yw);
61
- // residuals from Q (the part of Q'y beyond the rank), so a saturated model has residuals of exactly 0, as in R
62
- const rw = qrResid(q, Yw);
63
- const fitResiduals = sw === undefined ? rw : rw.map((v, i) => v / sw[i]);
64
- // rows of weight 0: fitted values x'b (aliased coefficients count as 0), residuals y - fitted
65
- const residuals = [];
66
- const fittedValues = [];
67
- let k = 0;
68
- Yall.forEach((v, i) => {
69
- if (fitRow[i]) {
70
- residuals.push(fitResiduals[k]);
71
- fittedValues.push(v - fitResiduals[k]);
72
- k++;
73
- }
74
- else {
75
- const fv = Xall[i].reduce((s, t, j) => (Number.isNaN(coefficients[j]) ? s : s + t * coefficients[j]), 0);
76
- fittedValues.push(fv);
77
- residuals.push(v - fv);
78
- }
79
- });
80
- const fitted = fittedValues.filter((_, i) => fitRow[i]);
151
+ const pf = precise ? preciseFit(Xall, Yall, Wall, fitRows, q, intercept) : undefined;
152
+ const coefficients = pf?.coefficients ?? qrCoef(q, Yw);
153
+ const residuals = pf?.residuals ?? [];
154
+ const fittedValues = pf?.fittedValues ?? [];
81
155
  const dfResidual = n - rank;
82
156
  const w = W ?? new Array(n).fill(1);
83
- let rss = 0;
84
- for (let i = 0; i < n; i++)
85
- rss += w[i] * fitResiduals[i] ** 2;
157
+ let rss = pf?.rss ?? 0;
158
+ if (pf === undefined) {
159
+ // residuals from Q (the part of Q'y beyond the rank), so a saturated model has residuals of exactly 0, as in R
160
+ const rw = qrResid(q, Yw);
161
+ const fitResiduals = sw === undefined ? rw : rw.map((v, i) => v / sw[i]);
162
+ // rows of weight 0: fitted values x'b (aliased coefficients count as 0), residuals y - fitted
163
+ let k = 0;
164
+ Yall.forEach((v, i) => {
165
+ if (fitRow[i]) {
166
+ residuals.push(fitResiduals[k]);
167
+ fittedValues.push(v - fitResiduals[k]);
168
+ k++;
169
+ }
170
+ else {
171
+ const fv = Xall[i].reduce((s, t, j) => (Number.isNaN(coefficients[j]) ? s : s + t * coefficients[j]), 0);
172
+ fittedValues.push(fv);
173
+ residuals.push(v - fv);
174
+ }
175
+ });
176
+ for (let i = 0; i < n; i++)
177
+ rss += w[i] * fitResiduals[i] ** 2;
178
+ }
179
+ const fitted = fittedValues.filter((_, i) => fitRow[i]);
86
180
  const resvar = rss / dfResidual;
87
181
  const sigma = Math.sqrt(resvar);
88
182
  // (R'R)^-1 of the leading rank x rank block, in pivot order
@@ -109,11 +203,14 @@ export function lm(x, y, options = {}) {
109
203
  };
110
204
  const dfInt = intercept ? 1 : 0;
111
205
  const numdf = rank - dfInt;
206
+ const core = { result, fitRows, effects: pf?.effects ?? [], rss };
112
207
  // nothing beyond the intercept: R^2 = 0 and no F test, as in summary.lm
113
208
  if (numdf === 0)
114
- return result;
209
+ return core;
115
210
  let mss = 0;
116
- if (intercept) {
211
+ if (pf !== undefined)
212
+ mss = pf.mss;
213
+ else if (intercept) {
117
214
  const sumw = w.reduce((a, b) => a + b, 0);
118
215
  let m = 0;
119
216
  for (let i = 0; i < n; i++)
@@ -129,7 +226,7 @@ export function lm(x, y, options = {}) {
129
226
  const fValue = mss / numdf / resvar;
130
227
  result.fStatistic = { value: fValue, numdf, dendf: dfResidual };
131
228
  result.fPValue = pf1(fValue, numdf, dfResidual, false, false);
132
- return result;
229
+ return core;
133
230
  }
134
231
  /**
135
232
  * Confidence intervals for the coefficients of a linear model (NaN for aliased columns). Equivalent to R's
@@ -0,0 +1,48 @@
1
+ import type { MatrixInput } from "../linalg/matrix.js";
2
+ import { type DDMatrix } from "./ddMatrix.js";
3
+ import { type DataFrame } from "./modelFrame.js";
4
+ /** Options for {@link mauchlyTest}. */
5
+ export interface MauchlyTestOptions {
6
+ /** Between-subjects group labels, parallel to the rows of `y` (the residuals are taken from the group means). */
7
+ group?: readonly (string | number)[];
8
+ /** The within-subject design: a data frame with one row per column of `y`. Default: a column `index` = 1 ... k. */
9
+ idata?: DataFrame;
10
+ /** Formula over `idata` whose model matrix spans the space tested. Default: all k dimensions (the identity). */
11
+ M?: string;
12
+ /** Formula over `idata` whose space is projected out. Default `"~0"` (nothing). */
13
+ X?: string;
14
+ }
15
+ /** Result of {@link mauchlyTest}. */
16
+ export interface MauchlyTestResult {
17
+ /** Mauchly's W. */
18
+ statistic: number;
19
+ statisticName: "W";
20
+ pValue: number;
21
+ method: "Mauchly's test of sphericity";
22
+ }
23
+ /** W = det(U) / (trace(U)/p)^p of a p x p matrix U */
24
+ export declare function sphericityW(U: DDMatrix): number;
25
+ /**
26
+ * The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the
27
+ * cross-products, k the number of measurements per subject.
28
+ */
29
+ export declare function mauchlyPValue(W: number, pp: number, n: number, k: number): number;
30
+ /**
31
+ * The matrix T S T' for an orthonormal basis T (rows) of the part of span(Mcols) orthogonal to span(Xcols), S a
32
+ * symmetric k x k matrix. Throws if span(X) is not inside span(M).
33
+ */
34
+ export declare function contrastCrossprod(S: DDMatrix, mcols: number[][], xcols: number[][]): DDMatrix;
35
+ /**
36
+ * Mauchly's test of sphericity of the measurements of each subject (a row of `y`), on the contrasts spanned by `M`
37
+ * and orthogonal to `X` (both formulas over `idata`). Equivalent to R's `mauchly.test(lm(y ~ 1), X = ~1)` and its
38
+ * variants (`group` for `lm(y ~ group)`, `M`, `X`, `idata`).
39
+ *
40
+ * @param y One row per subject, one column per measurement.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const y = [[10.5, 9.8, 8.8], [11.2, 10.1, 9.9], [9.7, 9.5, 9.0], [10.9, 10.6, 9.1], [10.1, 9.2, 9.4]];
45
+ * mauchlyTest(y, { X: "~1" }).statistic; // W
46
+ * ```
47
+ */
48
+ export declare function mauchlyTest(y: MatrixInput, options?: MauchlyTestOptions): MauchlyTestResult;
@@ -0,0 +1,123 @@
1
+ // Mauchly's test of sphericity: R's mauchly.test(lm(y ~ 1 or y ~ group), X, M, idata), and the statistic and p-value
2
+ // shared with the repeated-measures analysis of aovEz.
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("mauchlyTest") and Mauchly (1940), "Significance
5
+ // test for sphericity of a normal n-variate distribution", Annals of Mathematical Statistics 11, 204-209. The contrasts
6
+ // tested are an orthonormal basis of the part of the column space of M's model matrix orthogonal to that of X's
7
+ // (Householder QR in double-double); the residual cross-products, U and its determinant are computed in double-double
8
+ // (src/models/ddMatrix.ts).
9
+ import { pgamma1 } from "../distributions/gamma.js";
10
+ import { qr } from "../linalg/qr.js";
11
+ import { ddAdd, ddDiv, ddDivNum, ddMul, ddSub } from "../special/dd.js";
12
+ import { ddLeastSquaresMulti } from "./ddLeastSquares.js";
13
+ import { ddDet, ddTrace } from "./ddMatrix.js";
14
+ import { compareCodePoints } from "./modelFrame.js";
15
+ import { modelMatrix } from "./modelMatrix.js";
16
+ const upperChisq = (q, df) => pgamma1(q, df / 2, 2, false, false);
17
+ /** W = det(U) / (trace(U)/p)^p of a p x p matrix U */
18
+ export function sphericityW(U) {
19
+ const p = U.length;
20
+ let m = ddDivNum(ddTrace(U), p);
21
+ let pow = [1, 0];
22
+ for (let i = 0; i < p; i++)
23
+ pow = ddMul(pow, m);
24
+ m = ddDiv(ddDet(U), pow);
25
+ return m[0];
26
+ }
27
+ /**
28
+ * The p-value of Mauchly's W by the asymptotic expansion: pp the dimension tested, n the degrees of freedom of the
29
+ * cross-products, k the number of measurements per subject.
30
+ */
31
+ export function mauchlyPValue(W, pp, n, k) {
32
+ const rho = 1 - (2 * pp * pp + pp + 2) / (6 * pp * n);
33
+ const w2 = ((pp + 2) * (pp - 1) * (pp - 2) * (2 * pp ** 3 + 6 * pp * pp + 3 * k + 2)) / (288 * (n * pp * rho) ** 2);
34
+ const z = -n * rho * Math.log(W);
35
+ const f = (pp * (pp + 1)) / 2 - 1;
36
+ const p1 = upperChisq(z, f);
37
+ const p2 = upperChisq(z, f + 4);
38
+ return p1 + w2 * (p2 - p1);
39
+ }
40
+ /** Columns of a matrix given as rows */
41
+ const columnsOf = (rows, nc) => Array.from({ length: nc }, (_, j) => rows.map((r) => r[j]));
42
+ /**
43
+ * The matrix T S T' for an orthonormal basis T (rows) of the part of span(Mcols) orthogonal to span(Xcols), S a
44
+ * symmetric k x k matrix. Throws if span(X) is not inside span(M).
45
+ */
46
+ export function contrastCrossprod(S, mcols, xcols) {
47
+ const k = S.length;
48
+ const rank = (cols) => (cols.length === 0 ? 0 : qr(Array.from({ length: k }, (_, i) => cols.map((c) => c[i]))).rank);
49
+ const qx = xcols.length === 0 ? undefined : qr(Array.from({ length: k }, (_, i) => xcols.map((c) => c[i])));
50
+ const xkept = qx === undefined ? [] : qx.pivot.slice(0, qx.rank).map((j) => xcols[j]);
51
+ const rx = xkept.length;
52
+ const all = [...xkept, ...mcols];
53
+ const q = qr(Array.from({ length: k }, (_, i) => all.map((c) => c[i])));
54
+ if (q.rank > rank(mcols))
55
+ throw new Error("X does not define a subspace of M");
56
+ const order = q.pivot.slice(0, q.rank).map((j) => all[j]);
57
+ const toDD = (v) => v.map((t) => [t, 0]);
58
+ const zero = new Array(k).fill([0, 0]);
59
+ // A = Q'S, then B = Q'SQ from Q' applied to the rows of A
60
+ const a = ddLeastSquaresMulti(order.map(toDD), zero, S.map((_, j) => S.map((r) => r[j]))).qtv; // a[j] = Q' S[, j]
61
+ const rowsA = Array.from({ length: k }, (_, i) => a.map((col) => col[i]));
62
+ const b = ddLeastSquaresMulti(order.map(toDD), zero, rowsA).qtv; // b[i][j] = (Q'SQ)[i][j]
63
+ const idx = Array.from({ length: q.rank - rx }, (_, i) => rx + i);
64
+ return idx.map((i) => idx.map((j) => b[i][j]));
65
+ }
66
+ /**
67
+ * Mauchly's test of sphericity of the measurements of each subject (a row of `y`), on the contrasts spanned by `M`
68
+ * and orthogonal to `X` (both formulas over `idata`). Equivalent to R's `mauchly.test(lm(y ~ 1), X = ~1)` and its
69
+ * variants (`group` for `lm(y ~ group)`, `M`, `X`, `idata`).
70
+ *
71
+ * @param y One row per subject, one column per measurement.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const y = [[10.5, 9.8, 8.8], [11.2, 10.1, 9.9], [9.7, 9.5, 9.0], [10.9, 10.6, 9.1], [10.1, 9.2, 9.4]];
76
+ * mauchlyTest(y, { X: "~1" }).statistic; // W
77
+ * ```
78
+ */
79
+ export function mauchlyTest(y, options = {}) {
80
+ const rows = y.map((r) => Array.from(r));
81
+ const nsub = rows.length;
82
+ const k = rows[0]?.length ?? 0;
83
+ if (k === 0 || rows.some((r) => r.length !== k))
84
+ throw new TypeError("y must be a matrix with at least one column");
85
+ const group = options.group;
86
+ if (group !== undefined && group.length !== nsub)
87
+ throw new RangeError("'group' must have one label per row of y");
88
+ const labels = group?.map(String) ?? rows.map(() => "");
89
+ const levels = [...new Set(labels)].sort(compareCodePoints);
90
+ // residuals from the group means (double-double), and their cross-products
91
+ const res = rows.map((r) => r.map(() => [0, 0]));
92
+ for (const l of levels) {
93
+ const members = labels.flatMap((g, i) => (g === l ? [i] : []));
94
+ for (let j = 0; j < k; j++) {
95
+ let s = [0, 0];
96
+ for (const i of members)
97
+ s = ddAdd(s, [rows[i][j], 0]);
98
+ const m = ddDivNum(s, members.length);
99
+ for (const i of members)
100
+ res[i][j] = ddSub([rows[i][j], 0], m);
101
+ }
102
+ }
103
+ const n = nsub - levels.length;
104
+ const S = Array.from({ length: k }, (_, a) => Array.from({ length: k }, (_, b) => {
105
+ let s = [0, 0];
106
+ for (const r of res)
107
+ s = ddAdd(s, ddMul(r[a], r[b]));
108
+ return s;
109
+ }));
110
+ const idata = options.idata ?? { index: Array.from({ length: k }, (_, i) => i + 1) };
111
+ const design = (f) => {
112
+ const m = modelMatrix(f, idata);
113
+ if (m.x.length !== k)
114
+ throw new RangeError("idata must have one row per column of y");
115
+ return columnsOf(m.x, m.colNames.length);
116
+ };
117
+ const mcols = options.M === undefined ? Array.from({ length: k }, (_, j) => Array.from({ length: k }, (_, i) => (i === j ? 1 : 0))) : design(options.M);
118
+ const xcols = design(options.X ?? "~0");
119
+ const U = contrastCrossprod(S, mcols, xcols);
120
+ const pp = U.length;
121
+ const W = sphericityW(U);
122
+ return { statistic: W, statisticName: "W", pValue: mauchlyPValue(W, pp, n, k), method: "Mauchly's test of sphericity" };
123
+ }
@@ -0,0 +1,40 @@
1
+ import type { Sample } from "../htest/types.js";
2
+ /** A data frame: an object of columns of equal length. `null` (and `NaN` in a numeric column) is a missing value. */
3
+ export type DataFrame = Record<string, readonly (number | string | boolean | null)[] | Float64Array>;
4
+ /** A variable of a model frame: numeric values, or a factor (level index per row). */
5
+ export type FrameVariable = {
6
+ kind: "numeric";
7
+ values: number[];
8
+ } | {
9
+ kind: "factor";
10
+ levels: string[];
11
+ codes: number[];
12
+ };
13
+ /** Result of {@link modelFrame}. */
14
+ export interface ModelFrame {
15
+ /** 0-based indices of the rows of the data that were kept. */
16
+ rows: number[];
17
+ /** One entry per variable (in the order given), restricted to the rows kept. */
18
+ variables: FrameVariable[];
19
+ /** The weights of the rows kept (absent without weights). */
20
+ weights?: number[];
21
+ }
22
+ /** Options for {@link modelFrame}. */
23
+ export interface ModelFrameOptions {
24
+ /** The order of the levels of factors (`factor(x, levels = ...)`); values not among them are missing. */
25
+ levels?: Record<string, readonly string[]>;
26
+ /** Weights: an array parallel to the rows of the data, or the name of a numeric column. */
27
+ weights?: Sample | string;
28
+ /** Drop levels that have no row left. */
29
+ dropUnusedLevels?: boolean;
30
+ }
31
+ /** Comparison of strings by code point (not by UTF-16 code unit) */
32
+ export declare function compareCodePoints(a: string, b: string): number;
33
+ /**
34
+ * The model frame of the given variables: each variable taken from the data, the rows with a missing value in any
35
+ * of them (or in the weights) dropped.
36
+ *
37
+ * Errors as R: `object 'Q' not found` for a variable that is not a column, `variable lengths differ (found for 'x')`
38
+ * for columns of different lengths.
39
+ */
40
+ export declare function modelFrame(data: DataFrame, names: readonly string[], options?: ModelFrameOptions): ModelFrame;
@@ -0,0 +1,131 @@
1
+ // Model frames: the variables of a formula taken from a data frame, with the rows that have a missing value dropped
2
+ // and string and boolean columns turned into factors (R's model.frame with na.omit).
3
+ //
4
+ // Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Data and missing values"). Levels of a
5
+ // string column are its distinct values sorted by code point unless `levels` gives them; a boolean column has the
6
+ // levels FALSE and TRUE; numeric columns stay numeric. `dropUnusedLevels` removes the levels without a row left
7
+ // (R's drop.unused.levels = TRUE, used by lm and aov).
8
+ /** Comparison of strings by code point (not by UTF-16 code unit) */
9
+ export function compareCodePoints(a, b) {
10
+ const ia = a[Symbol.iterator]();
11
+ const ib = b[Symbol.iterator]();
12
+ for (;;) {
13
+ const x = ia.next();
14
+ const y = ib.next();
15
+ if (x.done)
16
+ return y.done ? 0 : -1;
17
+ if (y.done)
18
+ return 1;
19
+ const d = x.value.codePointAt(0) - y.value.codePointAt(0);
20
+ if (d !== 0)
21
+ return d;
22
+ }
23
+ }
24
+ /** A column as a variable over all rows, with a missing flag per row */
25
+ function convert(name, col, levels) {
26
+ if (col instanceof Float64Array && levels === undefined) {
27
+ const values = Array.from(col);
28
+ return { v: { kind: "numeric", values }, missing: values.map((x) => Number.isNaN(x)) };
29
+ }
30
+ const vals = Array.from(col);
31
+ const kinds = new Set(vals.filter((x) => x !== null).map((x) => typeof x));
32
+ if (kinds.size > 1)
33
+ throw new TypeError(`column '${name}' mixes ${[...kinds].join(" and ")} values`);
34
+ const kind = [...kinds][0] ?? "number";
35
+ if (kind !== "number" && kind !== "string" && kind !== "boolean")
36
+ throw new TypeError(`column '${name}' has values of an unsupported type`);
37
+ if (kind === "number" && levels === undefined) {
38
+ const values = vals.map((x) => (x === null ? NaN : x));
39
+ return { v: { kind: "numeric", values }, missing: values.map((x) => Number.isNaN(x)) };
40
+ }
41
+ const str = (x) => x === null || (typeof x === "number" && Number.isNaN(x)) ? null : typeof x === "boolean" ? (x ? "TRUE" : "FALSE") : String(x);
42
+ const labels = vals.map(str);
43
+ let lev;
44
+ if (levels !== undefined)
45
+ lev = Array.from(levels, String);
46
+ else if (kind === "boolean")
47
+ lev = ["FALSE", "TRUE"];
48
+ else
49
+ lev = [...new Set(labels.filter((x) => x !== null))].sort(compareCodePoints);
50
+ const pos = new Map(lev.map((l, i) => [l, i]));
51
+ const codes = labels.map((l) => (l === null ? -1 : (pos.get(l) ?? -1)));
52
+ return { v: { kind: "factor", levels: lev, codes }, missing: codes.map((c) => c < 0) };
53
+ }
54
+ /**
55
+ * The model frame of the given variables: each variable taken from the data, the rows with a missing value in any
56
+ * of them (or in the weights) dropped.
57
+ *
58
+ * Errors as R: `object 'Q' not found` for a variable that is not a column, `variable lengths differ (found for 'x')`
59
+ * for columns of different lengths.
60
+ */
61
+ export function modelFrame(data, names, options = {}) {
62
+ if (typeof data !== "object" || data === null)
63
+ throw new TypeError("data must be an object of columns");
64
+ const cols = names.map((v) => {
65
+ const c = Object.prototype.hasOwnProperty.call(data, v) ? data[v] : undefined;
66
+ if (c === undefined)
67
+ throw new Error(`object '${v}' not found`);
68
+ if (!Array.isArray(c) && !(c instanceof Float64Array))
69
+ throw new TypeError(`column '${v}' must be an array`);
70
+ return c;
71
+ });
72
+ let w;
73
+ if (typeof options.weights === "string") {
74
+ const c = Object.prototype.hasOwnProperty.call(data, options.weights) ? data[options.weights] : undefined;
75
+ if (c === undefined)
76
+ throw new Error(`object '${options.weights}' not found`);
77
+ w = c;
78
+ }
79
+ else if (options.weights !== undefined)
80
+ w = Array.from(options.weights);
81
+ const n = cols.length > 0 ? cols[0].length : (w?.length ?? Object.values(data)[0]?.length ?? 0);
82
+ names.forEach((v, i) => {
83
+ if (cols[i].length !== n)
84
+ throw new RangeError(`variable lengths differ (found for '${v}')`);
85
+ });
86
+ if (w !== undefined && w.length !== n)
87
+ throw new RangeError("variable lengths differ (found for '(weights)')");
88
+ const conv = names.map((v, i) => convert(v, cols[i], options.levels?.[v]));
89
+ let weights;
90
+ if (w !== undefined) {
91
+ weights = Array.from(w, (x) => {
92
+ if (x === null)
93
+ return NaN;
94
+ if (typeof x !== "number")
95
+ throw new TypeError("the weights must be numeric");
96
+ return x;
97
+ });
98
+ }
99
+ const rows = [];
100
+ for (let i = 0; i < n; i++) {
101
+ if (conv.some((c) => c.missing[i]) || (weights !== undefined && Number.isNaN(weights[i])))
102
+ continue;
103
+ rows.push(i);
104
+ }
105
+ const variables = conv.map(({ v }) => {
106
+ if (v.kind === "numeric")
107
+ return { kind: "numeric", values: rows.map((i) => v.values[i]) };
108
+ let codes = rows.map((i) => v.codes[i]);
109
+ let levels = v.levels;
110
+ if (options.dropUnusedLevels) {
111
+ const used = levels.map(() => false);
112
+ for (const c of codes)
113
+ used[c] = true;
114
+ const map = new Map();
115
+ levels = levels.filter((_, k) => {
116
+ if (used[k])
117
+ map.set(k, map.size);
118
+ return used[k];
119
+ });
120
+ codes = codes.map((c) => map.get(c));
121
+ }
122
+ return { kind: "factor", levels, codes };
123
+ });
124
+ const out = { rows, variables };
125
+ if (weights !== undefined) {
126
+ out.weights = rows.map((i) => weights[i]);
127
+ if (out.weights.some((x) => x < 0))
128
+ throw new RangeError("missing or negative weights not allowed");
129
+ }
130
+ return out;
131
+ }
@@ -0,0 +1,88 @@
1
+ import { type FormulaNode, type ParsedFormula, type Terms } from "./formula.js";
2
+ import { type DataFrame, type ModelFrame } from "./modelFrame.js";
3
+ import type { Sample } from "../htest/types.js";
4
+ /** A contrast of a factor: R's `contr.treatment`, `contr.sum` or `contr.helmert`. */
5
+ export type ContrastName = "contr.treatment" | "contr.sum" | "contr.helmert";
6
+ /** Options for {@link modelMatrix}. */
7
+ export interface ModelMatrixOptions {
8
+ /** A contrast per factor (default `"contr.treatment"`). */
9
+ contrasts?: Record<string, ContrastName>;
10
+ /** The order of the levels of a factor (`{ A: ["c", "a", "b"] }`), as `factor(x, levels = ...)` in R. */
11
+ levels?: Record<string, readonly string[]>;
12
+ }
13
+ /** Result of {@link modelMatrix}. */
14
+ export interface ModelMatrixResult {
15
+ /** Column names, such as `"(Intercept)"`, `"Ab"`, `"Ab:Bq"`, `"x"`. */
16
+ colNames: string[];
17
+ /** The term of each column (0 for the intercept, 1 for the first term). */
18
+ assign: number[];
19
+ /** The model matrix (array of rows). */
20
+ x: number[][];
21
+ /** 0-based indices of the rows of the data used (rows with a missing value are dropped). */
22
+ rows: number[];
23
+ /** Labels of the terms (variables joined by `:`). */
24
+ termLabels: string[];
25
+ /** Degree of each term. */
26
+ order: number[];
27
+ /** Whether the model has an intercept. */
28
+ intercept: boolean;
29
+ /** The variables of the formula, the response first. */
30
+ variables: string[];
31
+ /** R's factors attribute: one array per variable, one code per term (0 not in it, 1 contrasts, 2 indicators). */
32
+ factors: number[][];
33
+ /** R's warnings. */
34
+ warnings: string[];
35
+ }
36
+ /** A contrast matrix (one row per level) and its column names */
37
+ export declare function contrastMatrix(levels: readonly string[], contrast: ContrastName | "indicators"): {
38
+ m: number[][];
39
+ names: string[];
40
+ };
41
+ /** A model matrix with what the fits need. */
42
+ export interface Design {
43
+ terms: Terms;
44
+ frame: ModelFrame;
45
+ /** The model matrix (array of rows) */
46
+ x: number[][];
47
+ colNames: string[];
48
+ assign: number[];
49
+ /** The response's values (rows kept), if the formula has one */
50
+ y?: number[];
51
+ warnings: string[];
52
+ }
53
+ /** Options of {@link design} */
54
+ export interface DesignOptions extends ModelMatrixOptions {
55
+ weights?: Sample | string;
56
+ dropUnusedLevels?: boolean;
57
+ /** Contrast used for every factor instead of `contrasts` (the error model of aov) */
58
+ allContrasts?: ContrastName;
59
+ /** The intercept flag to use instead of the formula's (the error model of aov) */
60
+ intercept?: boolean;
61
+ /** More variables whose missing values drop rows (the rest of the formula, for the error model of aov) */
62
+ extraVariables?: readonly string[];
63
+ }
64
+ /**
65
+ * The model matrix of a parsed formula on the data.
66
+ *
67
+ * @param rhs The right-hand side to use (default: the formula's; aov passes it without the Error() term).
68
+ */
69
+ export declare function design(parsed: ParsedFormula, data: DataFrame, options?: DesignOptions, rhs?: FormulaNode | undefined): Design;
70
+ /**
71
+ * The model matrix of a formula on a data frame, with the attributes of R's `terms()`. Equivalent to R's
72
+ * `model.matrix(formula, data)` (with `contrasts.arg`), together with `attr(terms(formula), ...)`.
73
+ *
74
+ * Strings are factors (levels sorted by code point unless `levels` gives them), booleans factors with levels FALSE
75
+ * and TRUE, numbers numeric. Rows with a missing value (`null`, or `NaN` in a numeric column) in any variable of the
76
+ * formula are dropped; levels without rows are kept (their columns are 0).
77
+ *
78
+ * @param formula A formula such as `"y ~ A * B"`, `"y ~ x + A - 1"` or `"~ A"`.
79
+ * @param data The data frame: an object of columns.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * const m = modelMatrix("y ~ A", { y: [1, 2, 3, 4], A: ["a", "b", "a", "b"] });
84
+ * m.colNames; // ["(Intercept)", "Ab"]
85
+ * m.x; // [[1, 0], [1, 1], [1, 0], [1, 1]]
86
+ * ```
87
+ */
88
+ export declare function modelMatrix(formula: string, data: DataFrame, options?: ModelMatrixOptions): ModelMatrixResult;