@numero-uno-jpn/rstats 0.9.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 +63 -0
- package/README.ja.md +60 -11
- package/README.md +59 -10
- package/THIRD_PARTY_NOTICES.md +7 -2
- package/dist/chunks/{chunk-H2AP6TCR.js → chunk-2XKG3DX4.js} +1 -1
- package/dist/chunks/{chunk-FC2TLHZC.js → chunk-4NM37MGA.js} +2 -2
- package/dist/chunks/chunk-7HPVUVZB.js +2 -0
- package/dist/chunks/{chunk-YC4JWUKG.js → chunk-AECGWZHD.js} +2 -2
- package/dist/chunks/{chunk-LE7TBHNI.js → chunk-ENL43FNO.js} +2 -2
- package/dist/chunks/chunk-EWC6I75B.js +2 -0
- package/dist/chunks/chunk-IT354SHV.js +3 -0
- package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-LIMZKONM.js} +2 -2
- package/dist/chunks/chunk-O6PT7IVU.js +2 -0
- package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-QFULZNHL.js} +1 -1
- package/dist/chunks/{chunk-5K4PS7IV.js → chunk-QJJWGNJP.js} +2 -2
- package/dist/chunks/{chunk-LWUSYIQ4.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 +22 -1
- package/dist/entries/tests.js +19 -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/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 -4
- package/dist/special.js +2 -2
- package/dist/tests.js +18 -4
- package/llms.txt +102 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-24U4DKRY.js +0 -2
- package/dist/chunks/chunk-IVOBWYLV.js +0 -2
- package/dist/chunks/chunk-JLSTEMSN.js +0 -2
- package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
- package/dist/chunks/chunk-MSAUU6PY.js +0 -2
- package/dist/chunks/chunk-ZRO446BP.js +0 -2
package/dist/models/lm.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { MatrixInput } from "../linalg/matrix.js";
|
|
2
2
|
import { type QR } from "../linalg/qr.js";
|
|
3
3
|
import type { Sample } from "../htest/types.js";
|
|
4
|
+
import type { DataFrame } from "./modelFrame.js";
|
|
5
|
+
import { type Design, type ModelMatrixOptions } from "./modelMatrix.js";
|
|
4
6
|
/** Options for {@link lm}. */
|
|
5
7
|
export interface LmOptions {
|
|
6
8
|
/** Include an intercept (a column of ones before the columns of `x`). Default `true`. */
|
|
@@ -48,10 +50,74 @@ export interface LmResult {
|
|
|
48
50
|
/** The QR decomposition of the (weighted) model matrix. */
|
|
49
51
|
qr: QR;
|
|
50
52
|
}
|
|
53
|
+
/** Options of {@link lm} with a formula. */
|
|
54
|
+
export interface LmFormulaOptions extends ModelMatrixOptions {
|
|
55
|
+
/** Weights: an array parallel to the rows of `data`, or the name of a numeric column. */
|
|
56
|
+
weights?: Sample | string;
|
|
57
|
+
}
|
|
58
|
+
/** Result of {@link lm} with a formula: the fit of the model matrix, with the formula's terms. */
|
|
59
|
+
export interface LmFormulaResult extends LmResult {
|
|
60
|
+
/** The formula. */
|
|
61
|
+
formula: string;
|
|
62
|
+
/** The response's name. */
|
|
63
|
+
response: string;
|
|
64
|
+
/** Names of the coefficients (the model matrix's column names). */
|
|
65
|
+
coefNames: string[];
|
|
66
|
+
/** The term of each coefficient (0 for the intercept). */
|
|
67
|
+
assign: number[];
|
|
68
|
+
/** Labels of the terms. */
|
|
69
|
+
termLabels: string[];
|
|
70
|
+
/** Degree of each term. */
|
|
71
|
+
order: number[];
|
|
72
|
+
/** The variables of the formula, the response first. */
|
|
73
|
+
variables: string[];
|
|
74
|
+
/** R's factors attribute of the terms (one array per variable, one code per term). */
|
|
75
|
+
factors: number[][];
|
|
76
|
+
/** 0-based indices of the rows of `data` used. */
|
|
77
|
+
rows: number[];
|
|
78
|
+
/** The model matrix (rows used). */
|
|
79
|
+
x: number[][];
|
|
80
|
+
/** The response (rows used). */
|
|
81
|
+
y: number[];
|
|
82
|
+
/** The weights (rows used), if any. */
|
|
83
|
+
weights?: number[];
|
|
84
|
+
/** The effects Q'y of the (weighted) fit, one per row of non-zero weight. */
|
|
85
|
+
effects: number[];
|
|
86
|
+
/** The weighted residual sum of squares. */
|
|
87
|
+
rss: number;
|
|
88
|
+
/** Number of rows of non-zero weight. */
|
|
89
|
+
nObs: number;
|
|
90
|
+
/** Whether this is an `aov` fit. */
|
|
91
|
+
aov: boolean;
|
|
92
|
+
/** R's warnings (from the model matrix and from `summary()`). */
|
|
93
|
+
warnings: string[];
|
|
94
|
+
}
|
|
95
|
+
/** The formula fit (lm, and aov without Error()) */
|
|
96
|
+
export declare function lmFormulaFit(formula: string, d: Design, aov: boolean): LmFormulaResult;
|
|
51
97
|
/**
|
|
52
|
-
* Fit a linear model
|
|
53
|
-
*
|
|
54
|
-
*
|
|
98
|
+
* Fit a linear model from a formula. Equivalent to R's `lm(formula, data)` (with `weights` and `contrasts`)
|
|
99
|
+
* together with `summary()`.
|
|
100
|
+
*
|
|
101
|
+
* The model matrix is that of {@link modelMatrix} (but levels without rows are dropped, as R's
|
|
102
|
+
* `drop.unused.levels`); the fit is that of the matrix form (same pivoting and tolerance), its sums of squares computed
|
|
103
|
+
* in double-double so that data with a large mean keep their accuracy. Rows with a missing value in a variable of the
|
|
104
|
+
* formula or in the weights are dropped (`rows` lists those used).
|
|
105
|
+
*
|
|
106
|
+
* @param formula A formula such as `"y ~ A * B + x"`.
|
|
107
|
+
* @param data The data frame: an object of columns.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* const fit = lm("y ~ g", { y: [2.1, 3.9, 6.2, 7.8, 10.1, 11.8], g: ["a", "a", "b", "b", "c", "c"] });
|
|
112
|
+
* fit.coefNames; // ["(Intercept)", "gb", "gc"]
|
|
113
|
+
* fit.coefficients; // [3, 4, 7.95]
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export declare function lm(formula: string, data: DataFrame, options?: LmFormulaOptions): LmFormulaResult;
|
|
117
|
+
/**
|
|
118
|
+
* Fit a linear model by least squares, the predictors given as a matrix. Equivalent to R's `lm(y ~ x)` (or
|
|
119
|
+
* `y ~ x - 1` without intercept, with `weights` for weighted least squares) together with `summary()`. Rows with a
|
|
120
|
+
* missing value in `x`, `y` or the weights are dropped.
|
|
55
121
|
*
|
|
56
122
|
* @param x Predictors: a matrix (array of rows, one column per predictor) or a vector (one predictor).
|
|
57
123
|
* @param y Response.
|
|
@@ -64,6 +130,21 @@ export interface LmResult {
|
|
|
64
130
|
* ```
|
|
65
131
|
*/
|
|
66
132
|
export declare function lm(x: MatrixInput | Sample, y: Sample, options?: LmOptions): LmResult;
|
|
133
|
+
/** The quantities of a fit that the formula interface and the analyses of variance need besides the result */
|
|
134
|
+
export interface LmCore {
|
|
135
|
+
result: LmResult;
|
|
136
|
+
/** The rows of non-zero weight (indices into the rows given) */
|
|
137
|
+
fitRows: number[];
|
|
138
|
+
/** The effects Q'y of the (weighted) fit, one per row of non-zero weight (only for a precise fit) */
|
|
139
|
+
effects: number[];
|
|
140
|
+
/** The weighted residual sum of squares */
|
|
141
|
+
rss: number;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Least squares on a full model matrix (the column of ones included when `intercept` is true). Rows of weight 0 are
|
|
145
|
+
* left out of the fit and of the counts.
|
|
146
|
+
*/
|
|
147
|
+
export declare function fitLm(Xall: number[][], Yall: number[], Wall: number[] | undefined, intercept: boolean, precise?: boolean): LmCore;
|
|
67
148
|
/** Options for {@link confint}. */
|
|
68
149
|
export interface ConfintOptions {
|
|
69
150
|
/** Confidence level. Default `0.95`. */
|
package/dist/models/lm.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Linear models
|
|
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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
const
|
|
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
|
-
|
|
85
|
-
|
|
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
|
|
209
|
+
return core;
|
|
115
210
|
let mss = 0;
|
|
116
|
-
if (
|
|
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
|
|
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;
|