@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.
- package/CHANGELOG.md +88 -0
- package/README.ja.md +89 -13
- package/README.md +90 -13
- package/THIRD_PARTY_NOTICES.md +12 -2
- package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
- package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
- package/dist/chunks/chunk-7HPVUVZB.js +2 -0
- package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
- package/dist/chunks/chunk-ENL43FNO.js +2 -0
- package/dist/chunks/chunk-EWC6I75B.js +2 -0
- package/dist/chunks/chunk-IT354SHV.js +3 -0
- package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
- package/dist/chunks/chunk-O6PT7IVU.js +2 -0
- package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
- package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
- package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
- package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
- package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +25 -1
- package/dist/entries/tests.js +22 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +7 -0
- package/dist/htest/rankTests.js +11 -1
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/glm.d.ts +226 -0
- package/dist/models/glm.js +546 -0
- package/dist/models/glmAnova.d.ts +31 -0
- package/dist/models/glmAnova.js +146 -0
- package/dist/models/glmConfint.d.ts +25 -0
- package/dist/models/glmConfint.js +139 -0
- package/dist/models/glmFamily.d.ts +66 -0
- package/dist/models/glmFamily.js +359 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -3
- package/dist/special.js +2 -2
- package/dist/tests.js +18 -3
- package/llms.txt +102 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-EJRCDJ76.js +0 -2
- package/dist/chunks/chunk-JERGQKZM.js +0 -2
- package/dist/chunks/chunk-JVYV4633.js +0 -2
- package/dist/chunks/chunk-LXMMKO26.js +0 -2
- package/dist/chunks/chunk-MJQLKEO5.js +0 -2
- package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
- package/dist/chunks/chunk-SPQC445Q.js +0 -2
- package/dist/chunks/chunk-U633VFH3.js +0 -2
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Least squares in double-double arithmetic for the fits from a formula and their analyses of variance.
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js (no ported code): a textbook Householder QR decomposition (Golub and Van Loan, Matrix
|
|
4
|
+
// Computations, 5.2) of columns already known to be linearly independent (the columns kept, in pivoted order, by the
|
|
5
|
+
// double-precision decomposition of src/linalg/qr.ts, which decides the rank and the aliased columns exactly as lm
|
|
6
|
+
// does), carried out in double-double (src/special/dd.ts). The reflections use LINPACK's sign convention (the
|
|
7
|
+
// diagonal of R has the opposite sign of the column's leading element), so the effects Q'y have the signs of R's.
|
|
8
|
+
// Sums of squares that are small differences of large numbers (data with a large mean) are then accurate to about
|
|
9
|
+
// 1e-30 relative to the data's sum of squares instead of 1e-16.
|
|
10
|
+
import { ddAdd, ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
|
|
11
|
+
const ZERO = [0, 0];
|
|
12
|
+
export function ddSqrt(a) {
|
|
13
|
+
if (!(a[0] > 0))
|
|
14
|
+
return [Math.sqrt(a[0]), 0];
|
|
15
|
+
const s = Math.sqrt(a[0]);
|
|
16
|
+
const e = ddSub(a, twoProd(s, s));
|
|
17
|
+
return twoSum(s, e[0] / (2 * s));
|
|
18
|
+
}
|
|
19
|
+
/** Square roots of the weights in double-double (1 without weights) */
|
|
20
|
+
export function ddSqrtWeights(w, n) {
|
|
21
|
+
return Array.from({ length: n }, (_, i) => (w === undefined ? [1, 0] : ddSqrt([w[i], 0])));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Least squares of y on the given columns (all assumed linearly independent; rows already scaled by the square roots
|
|
25
|
+
* of the weights).
|
|
26
|
+
*
|
|
27
|
+
* @param cols The columns (each with one entry per row).
|
|
28
|
+
* @param y The response.
|
|
29
|
+
*/
|
|
30
|
+
export function ddLeastSquares(cols, y) {
|
|
31
|
+
return ddLeastSquaresMulti(cols, y, []).fit;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* {@link ddLeastSquares}, and Q'v for more vectors (with the same decomposition of the columns).
|
|
35
|
+
*
|
|
36
|
+
* @param vectors More vectors (each with one entry per row) to transform by Q'.
|
|
37
|
+
*/
|
|
38
|
+
export function ddLeastSquaresMulti(cols, y, vectors) {
|
|
39
|
+
const n = y.length;
|
|
40
|
+
const p = Math.min(cols.length, n);
|
|
41
|
+
const a = cols.map((c) => c.slice());
|
|
42
|
+
const b = y.slice();
|
|
43
|
+
const extra = vectors.map((v) => v.slice());
|
|
44
|
+
const diag = [];
|
|
45
|
+
for (let k = 0; k < p; k++) {
|
|
46
|
+
const v = a[k];
|
|
47
|
+
let s = ZERO;
|
|
48
|
+
for (let i = k; i < n; i++)
|
|
49
|
+
s = ddAdd(s, ddMul(v[i], v[i]));
|
|
50
|
+
if (s[0] === 0) {
|
|
51
|
+
diag.push(ZERO);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const norm = ddSqrt(s);
|
|
55
|
+
const alpha = v[k][0] < 0 ? [-norm[0], -norm[1]] : norm;
|
|
56
|
+
// H = I - u u' / (alpha u_k) with u = v + alpha e_k; H v = -alpha e_k
|
|
57
|
+
v[k] = ddAdd(v[k], alpha);
|
|
58
|
+
const denom = ddMul(alpha, v[k]);
|
|
59
|
+
const reflect = (c) => {
|
|
60
|
+
let t = ZERO;
|
|
61
|
+
for (let i = k; i < n; i++)
|
|
62
|
+
t = ddAdd(t, ddMul(v[i], c[i]));
|
|
63
|
+
const f = ddDiv(t, denom);
|
|
64
|
+
for (let i = k; i < n; i++)
|
|
65
|
+
c[i] = ddSub(c[i], ddMul(f, v[i]));
|
|
66
|
+
};
|
|
67
|
+
for (let j = k + 1; j < cols.length; j++)
|
|
68
|
+
reflect(a[j]);
|
|
69
|
+
reflect(b);
|
|
70
|
+
for (const c of extra)
|
|
71
|
+
reflect(c);
|
|
72
|
+
diag.push([-alpha[0], -alpha[1]]);
|
|
73
|
+
}
|
|
74
|
+
// back substitution with R (diagonal in diag, above it the transformed columns)
|
|
75
|
+
const coef = new Array(p).fill(ZERO);
|
|
76
|
+
for (let j = p - 1; j >= 0; j--) {
|
|
77
|
+
let s = b[j];
|
|
78
|
+
for (let k = j + 1; k < p; k++)
|
|
79
|
+
s = ddSub(s, ddMul(a[k][j], coef[k]));
|
|
80
|
+
coef[j] = ddDiv(s, diag[j]);
|
|
81
|
+
}
|
|
82
|
+
return { fit: { qty: b, coef }, qtv: extra };
|
|
83
|
+
}
|
|
84
|
+
/** Sum of squares of the elements from..to-1 */
|
|
85
|
+
export function ddSumSquares(v, from = 0, to = v.length) {
|
|
86
|
+
let s = ZERO;
|
|
87
|
+
for (let i = from; i < to; i++)
|
|
88
|
+
s = ddAdd(s, ddMul(v[i], v[i]));
|
|
89
|
+
return s;
|
|
90
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type DD } from "../special/dd.js";
|
|
2
|
+
export type DDMatrix = DD[][];
|
|
3
|
+
export declare const ddOf: (m: readonly (readonly number[])[]) => DDMatrix;
|
|
4
|
+
export declare const ddHi: (m: DDMatrix) => number[][];
|
|
5
|
+
export declare function ddTranspose(a: DDMatrix): DDMatrix;
|
|
6
|
+
export declare function ddMatMul(a: DDMatrix, b: DDMatrix): DDMatrix;
|
|
7
|
+
export declare function ddTrace(a: DDMatrix): DD;
|
|
8
|
+
export declare function ddDet(m: DDMatrix): DD;
|
|
9
|
+
/** Inverse of a non-singular matrix */
|
|
10
|
+
export declare function ddInverse(m: DDMatrix): DDMatrix;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Small dense matrices in double-double: products, traces, inverse and determinant (Gaussian elimination with
|
|
2
|
+
// partial pivoting), for the sums of squares and the sphericity statistics of the repeated-measures analyses.
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js (no ported code), textbook algorithms (Golub and Van Loan, Matrix Computations, 3.2-3.4) on
|
|
5
|
+
// the arithmetic of src/special/dd.ts.
|
|
6
|
+
import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
|
|
7
|
+
const ZERO = [0, 0];
|
|
8
|
+
export const ddOf = (m) => m.map((r) => r.map((v) => [v, 0]));
|
|
9
|
+
export const ddHi = (m) => m.map((r) => r.map((v) => v[0]));
|
|
10
|
+
export function ddTranspose(a) {
|
|
11
|
+
const nc = a[0]?.length ?? 0;
|
|
12
|
+
return Array.from({ length: nc }, (_, j) => a.map((r) => r[j]));
|
|
13
|
+
}
|
|
14
|
+
export function ddMatMul(a, b) {
|
|
15
|
+
const m = b[0]?.length ?? 0;
|
|
16
|
+
return a.map((r) => {
|
|
17
|
+
const out = new Array(m).fill(ZERO);
|
|
18
|
+
r.forEach((v, k) => {
|
|
19
|
+
const bk = b[k];
|
|
20
|
+
for (let j = 0; j < m; j++)
|
|
21
|
+
out[j] = ddAdd(out[j], ddMul(v, bk[j]));
|
|
22
|
+
});
|
|
23
|
+
return out;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
export function ddTrace(a) {
|
|
27
|
+
let s = ZERO;
|
|
28
|
+
a.forEach((r, i) => (s = ddAdd(s, r[i])));
|
|
29
|
+
return s;
|
|
30
|
+
}
|
|
31
|
+
/** LU factorisation with partial pivoting; returns the factors in place, the permutation sign, and whether singular */
|
|
32
|
+
function lu(a0) {
|
|
33
|
+
const n = a0.length;
|
|
34
|
+
const a = a0.map((r) => r.slice());
|
|
35
|
+
const perm = Array.from({ length: n }, (_, i) => i);
|
|
36
|
+
let sign = 1;
|
|
37
|
+
let singular = false;
|
|
38
|
+
for (let k = 0; k < n; k++) {
|
|
39
|
+
let piv = k;
|
|
40
|
+
for (let i = k + 1; i < n; i++)
|
|
41
|
+
if (Math.abs(a[i][k][0]) > Math.abs(a[piv][k][0]))
|
|
42
|
+
piv = i;
|
|
43
|
+
if (a[piv][k][0] === 0) {
|
|
44
|
+
singular = true;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (piv !== k) {
|
|
48
|
+
[a[k], a[piv]] = [a[piv], a[k]];
|
|
49
|
+
[perm[k], perm[piv]] = [perm[piv], perm[k]];
|
|
50
|
+
sign = -sign;
|
|
51
|
+
}
|
|
52
|
+
for (let i = k + 1; i < n; i++) {
|
|
53
|
+
const f = ddDiv(a[i][k], a[k][k]);
|
|
54
|
+
a[i][k] = f;
|
|
55
|
+
for (let j = k + 1; j < n; j++)
|
|
56
|
+
a[i][j] = ddSub(a[i][j], ddMul(f, a[k][j]));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return { a, perm, sign, singular };
|
|
60
|
+
}
|
|
61
|
+
export function ddDet(m) {
|
|
62
|
+
const { a, sign, singular } = lu(m);
|
|
63
|
+
if (singular)
|
|
64
|
+
return ZERO;
|
|
65
|
+
let d = [sign, 0];
|
|
66
|
+
a.forEach((r, i) => (d = ddMul(d, r[i])));
|
|
67
|
+
return d;
|
|
68
|
+
}
|
|
69
|
+
/** Inverse of a non-singular matrix */
|
|
70
|
+
export function ddInverse(m) {
|
|
71
|
+
const n = m.length;
|
|
72
|
+
const { a, perm, singular } = lu(m);
|
|
73
|
+
if (singular)
|
|
74
|
+
throw new Error("singular matrix");
|
|
75
|
+
const inv = Array.from({ length: n }, () => new Array(n).fill(ZERO));
|
|
76
|
+
for (let c = 0; c < n; c++) {
|
|
77
|
+
// solve L U x = P e_c
|
|
78
|
+
const x = perm.map((p) => [p === c ? 1 : 0, 0]);
|
|
79
|
+
for (let i = 0; i < n; i++)
|
|
80
|
+
for (let k = 0; k < i; k++)
|
|
81
|
+
x[i] = ddSub(x[i], ddMul(a[i][k], x[k]));
|
|
82
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
83
|
+
for (let k = i + 1; k < n; k++)
|
|
84
|
+
x[i] = ddSub(x[i], ddMul(a[i][k], x[k]));
|
|
85
|
+
x[i] = ddDiv(x[i], a[i][i]);
|
|
86
|
+
}
|
|
87
|
+
for (let i = 0; i < n; i++)
|
|
88
|
+
inv[i][c] = x[i];
|
|
89
|
+
}
|
|
90
|
+
return inv;
|
|
91
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** A node of a parsed formula. */
|
|
2
|
+
export type FormulaNode = {
|
|
3
|
+
type: "var";
|
|
4
|
+
name: string;
|
|
5
|
+
} | {
|
|
6
|
+
type: "dot";
|
|
7
|
+
} | {
|
|
8
|
+
type: "num";
|
|
9
|
+
value: number;
|
|
10
|
+
text: string;
|
|
11
|
+
} | {
|
|
12
|
+
type: "binary";
|
|
13
|
+
op: "+" | "-" | "*" | "/" | ":" | "%in%" | "^";
|
|
14
|
+
left: FormulaNode;
|
|
15
|
+
right: FormulaNode;
|
|
16
|
+
} | {
|
|
17
|
+
type: "unary";
|
|
18
|
+
op: "+" | "-";
|
|
19
|
+
arg: FormulaNode;
|
|
20
|
+
} | {
|
|
21
|
+
type: "paren";
|
|
22
|
+
arg: FormulaNode;
|
|
23
|
+
} | {
|
|
24
|
+
type: "Error";
|
|
25
|
+
arg: FormulaNode;
|
|
26
|
+
};
|
|
27
|
+
/** A parsed formula before expansion. */
|
|
28
|
+
export interface ParsedFormula {
|
|
29
|
+
/** The response's name (undefined for `~ rhs`). */
|
|
30
|
+
response: string | undefined;
|
|
31
|
+
/** The right-hand side. */
|
|
32
|
+
rhs: FormulaNode;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Parses a formula string. Throws a SyntaxError whose message starts with "invalid formula" if it cannot be parsed
|
|
36
|
+
* or uses something that is not supported (function calls other than Error(), backquoted names, ...).
|
|
37
|
+
*
|
|
38
|
+
* @param allowError Accept `Error(...)` terms (aov only).
|
|
39
|
+
*/
|
|
40
|
+
export declare function parseFormula(formula: string, allowError?: boolean): ParsedFormula;
|
|
41
|
+
/** The `Error()` terms of a right-hand side (top-level summands) and the right-hand side without them. */
|
|
42
|
+
export declare function splitErrorTerms(rhs: FormulaNode): {
|
|
43
|
+
treatment: FormulaNode | undefined;
|
|
44
|
+
errors: FormulaNode[];
|
|
45
|
+
};
|
|
46
|
+
/** Terms of a model: the variables of each term as indices into `variables`, in increasing order. */
|
|
47
|
+
export interface Terms {
|
|
48
|
+
/** The variable names: the response first (if any), then in order of first appearance in the formula. */
|
|
49
|
+
variables: string[];
|
|
50
|
+
/** Index of the response in `variables` (0), or -1 without response. */
|
|
51
|
+
response: number;
|
|
52
|
+
/** The terms, sorted by degree (stably); each lists its variables' indices in increasing order. */
|
|
53
|
+
terms: number[][];
|
|
54
|
+
/** Labels of the terms (variable names joined by ':'). */
|
|
55
|
+
termLabels: string[];
|
|
56
|
+
/** Degree of each term. */
|
|
57
|
+
order: number[];
|
|
58
|
+
/** Whether the model has an intercept. */
|
|
59
|
+
intercept: boolean;
|
|
60
|
+
/** R's "factors" attribute: for each variable, one code per term (0 not in the term, 1 contrasts, 2 indicators). */
|
|
61
|
+
factors: number[][];
|
|
62
|
+
/** Index of the term that consists of the response alone (it gets no columns), or -1. */
|
|
63
|
+
responseTerm: number;
|
|
64
|
+
/** Warnings of the expansion. */
|
|
65
|
+
warnings: string[];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Expands a right-hand side into terms (variable indices, increasing) and the intercept flag.
|
|
69
|
+
*
|
|
70
|
+
* @param index Variable index of a name.
|
|
71
|
+
* @param dot The variables `.` stands for.
|
|
72
|
+
*/
|
|
73
|
+
export declare function expandRhs(rhs: FormulaNode | undefined, index: (name: string) => number, dot: readonly string[]): {
|
|
74
|
+
terms: number[][];
|
|
75
|
+
intercept: boolean;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* The terms of a formula: expansion, sorting by degree, labels, and R's factor codes.
|
|
79
|
+
*
|
|
80
|
+
* @param columns The columns of the data (for `.`).
|
|
81
|
+
* @param rhs The right-hand side to expand (default: the parsed formula's).
|
|
82
|
+
*/
|
|
83
|
+
export declare function termsOf(parsed: ParsedFormula, columns: readonly string[], rhs?: FormulaNode | undefined): Terms;
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Model formulas: parsing `response ~ right-hand side` and expanding the right-hand side into terms, as R's terms().
|
|
2
|
+
//
|
|
3
|
+
// Written for rStats.js (no ported code) from oracle/anova-behaviour.md ("Formulas" and "Coding"). The parser is an
|
|
4
|
+
// operator-precedence parser with R's precedences (^, then unary - and +, then :, then %in%, then * and /, then binary
|
|
5
|
+
// + and -). The expansion follows the rules listed there: + concatenates, : forms the unions of pairs, * is a + b + a:b,
|
|
6
|
+
// ^n the unions of n terms, / and %in% nest, - removes terms (and in its right operand 0 and 1 swap meanings). The
|
|
7
|
+
// terms are then sorted stably by degree, and the variables of each term listed in order of first appearance in the
|
|
8
|
+
// formula. `codes` gives R's "factors" attribute (1: contrasts, 2: indicators) from the rule on earlier terms.
|
|
9
|
+
const invalid = (why) => new SyntaxError(`invalid formula: ${why}`);
|
|
10
|
+
function tokenize(s) {
|
|
11
|
+
const out = [];
|
|
12
|
+
let i = 0;
|
|
13
|
+
while (i < s.length) {
|
|
14
|
+
const c = s[i];
|
|
15
|
+
if (/\s/.test(c)) {
|
|
16
|
+
i++;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(s[i + 1] ?? ""))) {
|
|
20
|
+
const m = /^(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(s.slice(i));
|
|
21
|
+
out.push({ kind: "num", text: m[0] });
|
|
22
|
+
i += m[0].length;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (/[A-Za-z.]/.test(c)) {
|
|
26
|
+
const m = /^[A-Za-z.][A-Za-z0-9._]*/.exec(s.slice(i));
|
|
27
|
+
out.push({ kind: "name", text: m[0] });
|
|
28
|
+
i += m[0].length;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (s.startsWith("%in%", i)) {
|
|
32
|
+
out.push({ kind: "op", text: "%in%" });
|
|
33
|
+
i += 4;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if ("~+-*/:^()".includes(c)) {
|
|
37
|
+
out.push({ kind: "op", text: c });
|
|
38
|
+
i++;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
throw invalid(`unexpected '${c}'`);
|
|
42
|
+
}
|
|
43
|
+
out.push({ kind: "end" });
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
/** Binding powers of the binary operators (higher binds tighter); ^ is right associative */
|
|
47
|
+
const BINARY = { "+": 1, "-": 1, "*": 2, "/": 2, "%in%": 3, ":": 4, "^": 6 };
|
|
48
|
+
const UNARY = 5;
|
|
49
|
+
/**
|
|
50
|
+
* Parses a formula string. Throws a SyntaxError whose message starts with "invalid formula" if it cannot be parsed
|
|
51
|
+
* or uses something that is not supported (function calls other than Error(), backquoted names, ...).
|
|
52
|
+
*
|
|
53
|
+
* @param allowError Accept `Error(...)` terms (aov only).
|
|
54
|
+
*/
|
|
55
|
+
export function parseFormula(formula, allowError = false) {
|
|
56
|
+
if (typeof formula !== "string")
|
|
57
|
+
throw new TypeError("the formula must be a string");
|
|
58
|
+
const toks = tokenize(formula);
|
|
59
|
+
let pos = 0;
|
|
60
|
+
const peek = () => toks[pos];
|
|
61
|
+
const next = () => toks[pos++];
|
|
62
|
+
const isOp = (t, text) => t.kind === "op" && t.text === text;
|
|
63
|
+
function primary() {
|
|
64
|
+
const t = next();
|
|
65
|
+
if (t.kind === "name") {
|
|
66
|
+
if (isOp(peek(), "(")) {
|
|
67
|
+
if (t.text !== "Error" || !allowError)
|
|
68
|
+
throw invalid(`function calls are not supported (${t.text})`);
|
|
69
|
+
next();
|
|
70
|
+
const arg = expr(0);
|
|
71
|
+
if (!isOp(next(), ")"))
|
|
72
|
+
throw invalid("missing ')'");
|
|
73
|
+
return { type: "Error", arg };
|
|
74
|
+
}
|
|
75
|
+
if (t.text === ".")
|
|
76
|
+
return { type: "dot" };
|
|
77
|
+
if (/^\.[0-9]/.test(t.text))
|
|
78
|
+
throw invalid(`unexpected '${t.text}'`);
|
|
79
|
+
return { type: "var", name: t.text };
|
|
80
|
+
}
|
|
81
|
+
if (t.kind === "num")
|
|
82
|
+
return { type: "num", value: Number(t.text), text: t.text };
|
|
83
|
+
if (t.kind === "op" && t.text === "(") {
|
|
84
|
+
const arg = expr(0);
|
|
85
|
+
if (!isOp(next(), ")"))
|
|
86
|
+
throw invalid("missing ')'");
|
|
87
|
+
return { type: "paren", arg };
|
|
88
|
+
}
|
|
89
|
+
if (t.kind === "op" && (t.text === "-" || t.text === "+")) {
|
|
90
|
+
return { type: "unary", op: t.text, arg: expr(UNARY) };
|
|
91
|
+
}
|
|
92
|
+
throw invalid(t.kind === "end" ? "unexpected end of input" : `unexpected '${t.kind === "op" ? t.text : ""}'`);
|
|
93
|
+
}
|
|
94
|
+
function expr(minBp) {
|
|
95
|
+
let left = primary();
|
|
96
|
+
for (;;) {
|
|
97
|
+
const t = peek();
|
|
98
|
+
if (t.kind !== "op")
|
|
99
|
+
break;
|
|
100
|
+
const bp = BINARY[t.text];
|
|
101
|
+
if (bp === undefined || bp <= minBp)
|
|
102
|
+
break;
|
|
103
|
+
next();
|
|
104
|
+
// ^ is right associative: its right operand may contain another ^
|
|
105
|
+
const right = expr(t.text === "^" ? bp - 1 : bp);
|
|
106
|
+
left = { type: "binary", op: t.text, left, right };
|
|
107
|
+
}
|
|
108
|
+
return left;
|
|
109
|
+
}
|
|
110
|
+
let response;
|
|
111
|
+
if (!isOp(peek(), "~")) {
|
|
112
|
+
const t = next();
|
|
113
|
+
if (t.kind !== "name" || t.text === "." || !isOp(peek(), "~"))
|
|
114
|
+
throw invalid("the response must be a variable name followed by '~'");
|
|
115
|
+
response = t.text;
|
|
116
|
+
}
|
|
117
|
+
next(); // ~
|
|
118
|
+
const rhs = expr(0);
|
|
119
|
+
if (peek().kind !== "end")
|
|
120
|
+
throw invalid("unexpected input after the formula");
|
|
121
|
+
return { response, rhs };
|
|
122
|
+
}
|
|
123
|
+
/** The `Error()` terms of a right-hand side (top-level summands) and the right-hand side without them. */
|
|
124
|
+
export function splitErrorTerms(rhs) {
|
|
125
|
+
const errors = [];
|
|
126
|
+
const strip = (n) => {
|
|
127
|
+
if (n.type === "Error") {
|
|
128
|
+
errors.push(n.arg);
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
if (n.type === "binary" && n.op === "+") {
|
|
132
|
+
const l = strip(n.left);
|
|
133
|
+
const r = strip(n.right);
|
|
134
|
+
if (l === undefined)
|
|
135
|
+
return r;
|
|
136
|
+
if (r === undefined)
|
|
137
|
+
return l;
|
|
138
|
+
return { ...n, left: l, right: r };
|
|
139
|
+
}
|
|
140
|
+
if (n.type === "binary" && n.op === "-") {
|
|
141
|
+
// y ~ W + Error(id) - 1: the Error() term is a summand of the left operand
|
|
142
|
+
const l = strip(n.left);
|
|
143
|
+
if (l === undefined)
|
|
144
|
+
return { type: "unary", op: "-", arg: n.right };
|
|
145
|
+
return { ...n, left: l };
|
|
146
|
+
}
|
|
147
|
+
return n;
|
|
148
|
+
};
|
|
149
|
+
const treatment = strip(rhs);
|
|
150
|
+
const check = (n) => {
|
|
151
|
+
if (n.type === "Error")
|
|
152
|
+
throw invalid("Error() must be a term of the right-hand side");
|
|
153
|
+
if (n.type === "binary") {
|
|
154
|
+
check(n.left);
|
|
155
|
+
check(n.right);
|
|
156
|
+
}
|
|
157
|
+
else if (n.type === "unary" || n.type === "paren")
|
|
158
|
+
check(n.arg);
|
|
159
|
+
};
|
|
160
|
+
if (treatment !== undefined)
|
|
161
|
+
check(treatment);
|
|
162
|
+
errors.forEach(check);
|
|
163
|
+
return { treatment, errors };
|
|
164
|
+
}
|
|
165
|
+
/** The variable names of a node, in order of first appearance (`.` expands to `dot`) */
|
|
166
|
+
function collectVariables(n, dot, out) {
|
|
167
|
+
if (n === undefined)
|
|
168
|
+
return;
|
|
169
|
+
switch (n.type) {
|
|
170
|
+
case "var":
|
|
171
|
+
if (!out.includes(n.name))
|
|
172
|
+
out.push(n.name);
|
|
173
|
+
return;
|
|
174
|
+
case "dot":
|
|
175
|
+
for (const v of dot)
|
|
176
|
+
if (!out.includes(v))
|
|
177
|
+
out.push(v);
|
|
178
|
+
return;
|
|
179
|
+
case "num":
|
|
180
|
+
return;
|
|
181
|
+
case "binary":
|
|
182
|
+
collectVariables(n.left, dot, out);
|
|
183
|
+
// the exponent of ^ is a number, not a variable
|
|
184
|
+
if (n.op !== "^")
|
|
185
|
+
collectVariables(n.right, dot, out);
|
|
186
|
+
return;
|
|
187
|
+
case "unary":
|
|
188
|
+
case "paren":
|
|
189
|
+
case "Error":
|
|
190
|
+
collectVariables(n.arg, dot, out);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const keyOf = (t) => t.join(",");
|
|
194
|
+
function dedupe(terms) {
|
|
195
|
+
const seen = new Set();
|
|
196
|
+
return terms.filter((t) => {
|
|
197
|
+
const k = keyOf(t);
|
|
198
|
+
if (seen.has(k))
|
|
199
|
+
return false;
|
|
200
|
+
seen.add(k);
|
|
201
|
+
return true;
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
const union = (a, b) => [...new Set([...a, ...b])].sort((x, y) => x - y);
|
|
205
|
+
/**
|
|
206
|
+
* Expands a right-hand side into terms (variable indices, increasing) and the intercept flag.
|
|
207
|
+
*
|
|
208
|
+
* @param index Variable index of a name.
|
|
209
|
+
* @param dot The variables `.` stands for.
|
|
210
|
+
*/
|
|
211
|
+
export function expandRhs(rhs, index, dot) {
|
|
212
|
+
let intercept = true;
|
|
213
|
+
const L = (n, negated) => {
|
|
214
|
+
switch (n.type) {
|
|
215
|
+
case "var":
|
|
216
|
+
return [[index(n.name)]];
|
|
217
|
+
case "dot":
|
|
218
|
+
return dot.map((v) => [index(v)]);
|
|
219
|
+
case "num":
|
|
220
|
+
if (n.value === 1)
|
|
221
|
+
intercept = !negated;
|
|
222
|
+
else if (n.value === 0)
|
|
223
|
+
intercept = negated;
|
|
224
|
+
else
|
|
225
|
+
throw invalid(`a number (${n.text}) is not a term`);
|
|
226
|
+
return [];
|
|
227
|
+
case "paren":
|
|
228
|
+
return L(n.arg, negated);
|
|
229
|
+
case "Error":
|
|
230
|
+
throw invalid("Error() must be a term of the right-hand side");
|
|
231
|
+
case "unary":
|
|
232
|
+
if (n.op === "+")
|
|
233
|
+
return L(n.arg, negated);
|
|
234
|
+
L(n.arg, !negated);
|
|
235
|
+
return [];
|
|
236
|
+
case "binary": {
|
|
237
|
+
if (n.op === "^") {
|
|
238
|
+
const a = L(n.left, negated);
|
|
239
|
+
let e = n.right;
|
|
240
|
+
while (e.type === "paren")
|
|
241
|
+
e = e.arg;
|
|
242
|
+
const p = e.type === "num" ? e.value : NaN;
|
|
243
|
+
if (!Number.isInteger(p) || p < 2)
|
|
244
|
+
throw new Error("invalid power in formula");
|
|
245
|
+
let cur = a;
|
|
246
|
+
for (let k = 1; k < p; k++) {
|
|
247
|
+
const nxt = [];
|
|
248
|
+
for (const s of a)
|
|
249
|
+
for (const t of cur)
|
|
250
|
+
nxt.push(union(s, t));
|
|
251
|
+
cur = dedupe(nxt);
|
|
252
|
+
}
|
|
253
|
+
return cur;
|
|
254
|
+
}
|
|
255
|
+
if (n.op === "-") {
|
|
256
|
+
const a = L(n.left, negated);
|
|
257
|
+
const drop = new Set(L(n.right, !negated).map(keyOf));
|
|
258
|
+
return a.filter((t) => !drop.has(keyOf(t)));
|
|
259
|
+
}
|
|
260
|
+
const a = L(n.left, negated);
|
|
261
|
+
const b = L(n.right, negated);
|
|
262
|
+
const cross = () => {
|
|
263
|
+
const out = [];
|
|
264
|
+
for (const s of a)
|
|
265
|
+
for (const t of b)
|
|
266
|
+
out.push(union(s, t));
|
|
267
|
+
return out;
|
|
268
|
+
};
|
|
269
|
+
const allOf = (ts) => ts.reduce((acc, t) => union(acc, t), []);
|
|
270
|
+
switch (n.op) {
|
|
271
|
+
case "+":
|
|
272
|
+
return dedupe([...a, ...b]);
|
|
273
|
+
case ":":
|
|
274
|
+
return dedupe(cross());
|
|
275
|
+
case "*":
|
|
276
|
+
return dedupe([...a, ...b, ...cross()]);
|
|
277
|
+
case "/": {
|
|
278
|
+
const va = allOf(a);
|
|
279
|
+
return dedupe([...a, ...b.map((t) => union(t, va))]);
|
|
280
|
+
}
|
|
281
|
+
case "%in%": {
|
|
282
|
+
const vb = allOf(b);
|
|
283
|
+
return dedupe(a.map((t) => union(t, vb)));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
throw invalid("unsupported expression");
|
|
289
|
+
};
|
|
290
|
+
const terms = rhs === undefined ? [] : L(rhs, false);
|
|
291
|
+
return { terms, intercept };
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The terms of a formula: expansion, sorting by degree, labels, and R's factor codes.
|
|
295
|
+
*
|
|
296
|
+
* @param columns The columns of the data (for `.`).
|
|
297
|
+
* @param rhs The right-hand side to expand (default: the parsed formula's).
|
|
298
|
+
*/
|
|
299
|
+
export function termsOf(parsed, columns, rhs = parsed.rhs) {
|
|
300
|
+
const { response } = parsed;
|
|
301
|
+
const dot = columns.filter((c) => c !== response);
|
|
302
|
+
const variables = response === undefined ? [] : [response];
|
|
303
|
+
collectVariables(parsed.rhs, dot, variables);
|
|
304
|
+
const index = (name) => variables.indexOf(name);
|
|
305
|
+
const expanded = expandRhs(rhs, index, dot);
|
|
306
|
+
// stable sort by degree
|
|
307
|
+
const terms = expanded.terms.map((t, i) => [t, i]).sort((a, b) => a[0].length - b[0].length || a[1] - b[1]).map(([t]) => t);
|
|
308
|
+
const warnings = [];
|
|
309
|
+
const responseTerm = response === undefined ? -1 : terms.findIndex((t) => t.length === 1 && t[0] === 0);
|
|
310
|
+
if (responseTerm >= 0) {
|
|
311
|
+
warnings.push("the response appeared on the right-hand side and was dropped");
|
|
312
|
+
warnings.push(`problem with term ${responseTerm + 1} in model.matrix: no columns are assigned`);
|
|
313
|
+
}
|
|
314
|
+
const factors = variables.map(() => terms.map(() => 0));
|
|
315
|
+
terms.forEach((t, j) => {
|
|
316
|
+
for (const v of t) {
|
|
317
|
+
const rest = t.filter((u) => u !== v);
|
|
318
|
+
const byContrasts = rest.length === 0 || terms.slice(0, j).some((s) => rest.every((u) => s.includes(u)));
|
|
319
|
+
factors[v][j] = byContrasts ? 1 : 2;
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
return {
|
|
323
|
+
variables,
|
|
324
|
+
response: response === undefined ? -1 : 0,
|
|
325
|
+
terms,
|
|
326
|
+
termLabels: terms.map((t) => t.map((v) => variables[v]).join(":")),
|
|
327
|
+
order: terms.map((t) => t.length),
|
|
328
|
+
intercept: expanded.intercept,
|
|
329
|
+
factors,
|
|
330
|
+
responseTerm,
|
|
331
|
+
warnings,
|
|
332
|
+
};
|
|
333
|
+
}
|