@numero-uno-jpn/rstats 0.13.0 → 0.14.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 +20 -0
- package/README.ja.md +17 -8
- package/README.md +17 -8
- package/dist/chunks/{chunk-CQNVEA22.js → chunk-6JRESWVF.js} +2 -2
- package/dist/chunks/chunk-7CPM3M6Q.js +2 -0
- package/dist/chunks/chunk-7PSGKKOP.js +2 -0
- package/dist/chunks/{chunk-4AQNVF3Z.js → chunk-7T74KLE5.js} +2 -2
- package/dist/chunks/{chunk-F44XUHWI.js → chunk-A76XBA3D.js} +1 -1
- package/dist/chunks/{chunk-VG67L3JA.js → chunk-ACE64PMM.js} +2 -2
- package/dist/chunks/chunk-DCGBYO44.js +2 -0
- package/dist/chunks/chunk-DWNGNTS6.js +2 -0
- package/dist/chunks/{chunk-SVWU5T7C.js → chunk-FBDZ6B2G.js} +2 -2
- package/dist/chunks/chunk-IBJ7RI44.js +2 -0
- package/dist/chunks/{chunk-4GNJEYXR.js → chunk-IGSR4GIF.js} +2 -2
- package/dist/chunks/{chunk-BJHBYEEU.js → chunk-NTETWLP3.js} +1 -1
- package/dist/chunks/{chunk-2IAT6MT2.js → chunk-Q4JF4QHS.js} +2 -2
- package/dist/chunks/{chunk-JGFUZKLJ.js → chunk-RZIWVCHO.js} +2 -2
- package/dist/chunks/chunk-SD7ML5PE.js +2 -0
- package/dist/chunks/{chunk-3AKA4KEL.js → chunk-SZ357HRC.js} +1 -1
- package/dist/chunks/{chunk-SLSDFIW2.js → chunk-WM33ADZV.js} +2 -2
- package/dist/chunks/{chunk-MEMYFTYS.js → chunk-XCAMWVNO.js} +1 -1
- package/dist/chunks/chunk-YQLEXH2Y.js +3 -0
- package/dist/chunks/chunk-YTV3RFCA.js +2 -0
- package/dist/chunks/{chunk-BSOUJPDF.js → chunk-ZUESNU7W.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +3 -1
- package/dist/entries/mixed.js +4 -1
- package/dist/internal/fround.d.ts +12 -0
- package/dist/internal/fround.js +89 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -3
- package/dist/models/lmer.d.ts +37 -4
- package/dist/models/lmer.js +18 -1
- package/dist/models/lmerAnova.d.ts +138 -0
- package/dist/models/lmerAnova.js +134 -0
- package/dist/models/lmerHypotheses.d.ts +105 -0
- package/dist/models/lmerHypotheses.js +303 -0
- package/dist/models/lmerTest.d.ts +233 -0
- package/dist/models/lmerTest.js +306 -0
- package/dist/models/mixedDerivatives.d.ts +27 -0
- package/dist/models/mixedDerivatives.js +342 -0
- package/dist/models/mixedDeviance.d.ts +112 -0
- package/dist/models/mixedDeviance.js +216 -86
- package/dist/models/mixedStructure.d.ts +5 -3
- package/dist/models/modelMatrix.d.ts +10 -3
- package/dist/models/modelMatrix.js +23 -2
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +13 -13
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -12
- package/llms.txt +6 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-22SXZNR6.js +0 -2
- package/dist/chunks/chunk-AGRKZXLG.js +0 -2
- package/dist/chunks/chunk-N3FV6H3C.js +0 -2
- package/dist/chunks/chunk-NRV3BH7I.js +0 -2
- package/dist/chunks/chunk-RTWLZPPG.js +0 -2
- package/dist/chunks/chunk-VWGJYRE6.js +0 -2
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { DataFrame, FrameVariable } from "./modelFrame.js";
|
|
2
|
+
import { type DesignContrast } from "./modelMatrix.js";
|
|
3
|
+
/** A term of the fixed-effects formula. */
|
|
4
|
+
export interface FixedEffectsTerm {
|
|
5
|
+
/** The term's label, such as `"A"`, `"x:f"`. */
|
|
6
|
+
label: string;
|
|
7
|
+
/** Its variables, in the order of the label. */
|
|
8
|
+
variables: string[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The fixed-effects design of a mixed model, everything the hypothesis matrices depend on.
|
|
12
|
+
*/
|
|
13
|
+
export interface FixedEffectsDescription {
|
|
14
|
+
/** The model matrix X (array of rows, the rows used), aliased columns dropped. */
|
|
15
|
+
x: number[][];
|
|
16
|
+
/** Names of the columns of X, such as `"(Intercept)"`, `"Aa2"`, `"x:flo"`. */
|
|
17
|
+
colNames: string[];
|
|
18
|
+
/** The term of each column of X: 0 for the intercept, k + 1 for `terms[k]`. */
|
|
19
|
+
assign: number[];
|
|
20
|
+
/** Whether the model has an intercept. */
|
|
21
|
+
intercept: boolean;
|
|
22
|
+
/** The terms of the fixed-effects formula, in the order of the formula's terms (sorted by order). */
|
|
23
|
+
terms: FixedEffectsTerm[];
|
|
24
|
+
/**
|
|
25
|
+
* The variables of the terms, in the order of the formula (that of their first appearance), each with its
|
|
26
|
+
* column of the model frame (rows used): numeric values, or a factor's levels and codes.
|
|
27
|
+
*/
|
|
28
|
+
variables: {
|
|
29
|
+
name: string;
|
|
30
|
+
frame: FrameVariable;
|
|
31
|
+
}[];
|
|
32
|
+
/** The contrast of each factor among `variables` (`"contr.treatment"` unless another was given). */
|
|
33
|
+
contrasts: Record<string, DesignContrast>;
|
|
34
|
+
}
|
|
35
|
+
/** Options of {@link fixedEffectsDescription}: those of lmer that shape X. */
|
|
36
|
+
export interface FixedEffectsDescriptionOptions {
|
|
37
|
+
/** A contrast per factor of the fixed-effects part (default `"contr.treatment"`). */
|
|
38
|
+
contrasts?: Record<string, DesignContrast>;
|
|
39
|
+
/** The order of the levels of a factor. */
|
|
40
|
+
levels?: Record<string, readonly string[]>;
|
|
41
|
+
}
|
|
42
|
+
/** The hypothesis matrix of one term. */
|
|
43
|
+
export interface TermHypothesis {
|
|
44
|
+
/** The term's label. */
|
|
45
|
+
term: string;
|
|
46
|
+
/** The names of the rows (columns of X for Types I and II, of X with treatment contrasts for Type III). */
|
|
47
|
+
rows: string[];
|
|
48
|
+
/** The names of the columns: the columns of X. */
|
|
49
|
+
columns: string[];
|
|
50
|
+
/** The matrix (array of rows). */
|
|
51
|
+
values: number[][];
|
|
52
|
+
}
|
|
53
|
+
/** The type of an ANOVA table. */
|
|
54
|
+
export type HypothesisType = "I" | "II" | "III";
|
|
55
|
+
/** Result of {@link lmerHypotheses}. */
|
|
56
|
+
export interface LmerHypotheses {
|
|
57
|
+
/** One hypothesis per term with columns in X, in the order of the terms (a term with no rows included). */
|
|
58
|
+
hypotheses: TermHypothesis[];
|
|
59
|
+
/** R's messages (Type III: "Missing cells for: ..."). */
|
|
60
|
+
messages: string[];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula's fixed part coded on the model frame of
|
|
64
|
+
* the whole formula (rows with a missing value in any of its variables dropped, unused levels dropped), the
|
|
65
|
+
* contrasts given, and the aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
|
|
66
|
+
*/
|
|
67
|
+
export declare function fixedEffectsDescription(formula: string, data: DataFrame, options?: FixedEffectsDescriptionOptions): FixedEffectsDescription;
|
|
68
|
+
/**
|
|
69
|
+
* The Doolittle factorisation S = L U of a symmetric matrix without pivoting: L unit lower triangular, U upper
|
|
70
|
+
* triangular; a column of L below a pivot |U_ii| < 1e-6 is 0, and entries below 1e-6 in absolute value are set to 0
|
|
71
|
+
* at the end.
|
|
72
|
+
*/
|
|
73
|
+
export declare function doolittle(s: readonly (readonly number[])[]): {
|
|
74
|
+
L: number[][];
|
|
75
|
+
U: number[][];
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* For each term, the indices of the terms that contain it: those whose variables include all of its own and at
|
|
79
|
+
* least one more, with the same numeric variables (in the order of the terms).
|
|
80
|
+
*/
|
|
81
|
+
export declare function containingTerms(desc: FixedEffectsDescription): number[][];
|
|
82
|
+
/**
|
|
83
|
+
* The full-dummy matrix rdX: an intercept column (with an intercept), then for each term the columns of its model
|
|
84
|
+
* matrix with every level of each factor (the first variable varying fastest, numeric variables multiplying), and
|
|
85
|
+
* the "Missing cells" message for its columns that are all 0.
|
|
86
|
+
*/
|
|
87
|
+
export declare function fullDummyMatrix(desc: FixedEffectsDescription): {
|
|
88
|
+
x: number[][];
|
|
89
|
+
colNames: string[];
|
|
90
|
+
messages: string[];
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* X remade from the same terms and model frame with treatment contrasts for every factor, restricted (if it is not
|
|
94
|
+
* of full column rank) to the first r pivot columns of its pivoted QR decomposition (tolerance 1e-7), r its rank.
|
|
95
|
+
*/
|
|
96
|
+
export declare function treatmentModelMatrix(desc: FixedEffectsDescription): {
|
|
97
|
+
x: number[][];
|
|
98
|
+
colNames: string[];
|
|
99
|
+
assign: number[];
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* The hypothesis matrices of lmerTest's ANOVA table of the given type, one per term (oracle/lmertest-behaviour.md,
|
|
103
|
+
* section 2). If X has at most one column or the formula at most one term, every type is built as Type I.
|
|
104
|
+
*/
|
|
105
|
+
export declare function lmerHypotheses(desc: FixedEffectsDescription, type?: HypothesisType): LmerHypotheses;
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// The hypothesis matrices of the Type I, II and III ANOVA tables of an lmer fit (lmerTest's anova): one matrix per
|
|
2
|
+
// term of the fixed-effects formula, its rows contrasts of the fixed effects. They depend only on the design (the
|
|
3
|
+
// model matrix X, the terms and the model frame), never on the fit.
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code) from oracle/lmertest-behaviour.md (section 2). Type I: the transposed unit
|
|
6
|
+
// lower triangular factor of the Doolittle factorisation of X'X, its rows grouped by term (sequential sums of
|
|
7
|
+
// squares). Type II: for a term contained in no other (containment: the variables of the other include its own and
|
|
8
|
+
// more, the numeric variables being the same), the identity's rows for its columns; otherwise the Doolittle factor of
|
|
9
|
+
// X'X with the columns reordered so that the term and the terms containing it come last. Type III: the full-dummy
|
|
10
|
+
// matrix rdX (all levels of every factor), mapped to the coefficients of X with treatment contrasts by ginv, rounded
|
|
11
|
+
// (R's zapsmall), with the columns of each contained term made orthogonal to those of the terms containing it, then
|
|
12
|
+
// mapped back to the coding of X when it does not use treatment contrasts.
|
|
13
|
+
//
|
|
14
|
+
// The construction is a function of an explicit description of the fixed-effects design
|
|
15
|
+
// ({@link FixedEffectsDescription}); {@link fixedEffectsDescription} builds it from lmer's inputs (formula, data,
|
|
16
|
+
// contrasts and levels) as lmer does (src/models/mixedStructure.ts), aliased columns of X dropped.
|
|
17
|
+
import { zapsmall } from "../internal/fround.js";
|
|
18
|
+
import { ginv } from "../linalg/kappa.js";
|
|
19
|
+
import { qr, qrResid } from "../linalg/qr.js";
|
|
20
|
+
import { parseFormula, splitBarTerms, termsOf } from "./formula.js";
|
|
21
|
+
import { design } from "./modelMatrix.js";
|
|
22
|
+
const ONE = { type: "num", value: 1, text: "1" };
|
|
23
|
+
/**
|
|
24
|
+
* The fixed-effects design of an lmer fit, from lmer's inputs: the formula's fixed part coded on the model frame of
|
|
25
|
+
* the whole formula (rows with a missing value in any of its variables dropped, unused levels dropped), the
|
|
26
|
+
* contrasts given, and the aliased columns of X (pivoted QR, tolerance 1e-7) dropped, as lmer's `fixefNames`.
|
|
27
|
+
*/
|
|
28
|
+
export function fixedEffectsDescription(formula, data, options = {}) {
|
|
29
|
+
const parsed = parseFormula(formula, false, true);
|
|
30
|
+
if (parsed.response === undefined)
|
|
31
|
+
throw new TypeError("the formula has no response");
|
|
32
|
+
if (typeof data !== "object" || data === null)
|
|
33
|
+
throw new TypeError("data must be an object of columns");
|
|
34
|
+
const { fixed } = splitBarTerms(parsed.rhs);
|
|
35
|
+
const fixedRhs = fixed ?? ONE;
|
|
36
|
+
const contrastOptions = options.contrasts === undefined
|
|
37
|
+
? {}
|
|
38
|
+
: { contrasts: options.contrasts, contrastVariables: termsOf({ response: parsed.response, rhs: fixedRhs }, Object.keys(data)).variables };
|
|
39
|
+
const d = design(parsed, data, { ...(options.levels === undefined ? {} : { levels: options.levels }), dropUnusedLevels: true, ...contrastOptions }, fixedRhs);
|
|
40
|
+
const { terms, frame } = d;
|
|
41
|
+
let keep = d.colNames.map((_, j) => j);
|
|
42
|
+
if (keep.length > 0) {
|
|
43
|
+
const decomposition = qr(d.x);
|
|
44
|
+
const aliased = new Set(decomposition.pivot.slice(decomposition.rank));
|
|
45
|
+
keep = keep.filter((j) => !aliased.has(j));
|
|
46
|
+
}
|
|
47
|
+
const used = new Set(terms.terms.flat());
|
|
48
|
+
const variables = terms.variables.map((name, v) => ({ name, v })).filter(({ v }) => used.has(v));
|
|
49
|
+
const contrasts = {};
|
|
50
|
+
for (const { name, v } of variables) {
|
|
51
|
+
if (frame.variables[v].kind === "factor")
|
|
52
|
+
contrasts[name] = options.contrasts?.[name] ?? "contr.treatment";
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
x: d.x.map((row) => keep.map((j) => row[j])),
|
|
56
|
+
colNames: keep.map((j) => d.colNames[j]),
|
|
57
|
+
assign: keep.map((j) => d.assign[j]),
|
|
58
|
+
intercept: terms.intercept,
|
|
59
|
+
terms: terms.terms.map((t, k) => ({ label: terms.termLabels[k], variables: t.map((v) => terms.variables[v]) })),
|
|
60
|
+
variables: variables.map(({ name, v }) => ({ name, frame: frame.variables[v] })),
|
|
61
|
+
contrasts,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
// ---- small matrix helpers ----
|
|
65
|
+
const transpose = (m, ncol = m[0]?.length ?? 0) => Array.from({ length: ncol }, (_, j) => m.map((row) => row[j]));
|
|
66
|
+
function multiply(a, b, ncol = b[0]?.length ?? 0) {
|
|
67
|
+
return a.map((row) => {
|
|
68
|
+
const out = new Array(ncol).fill(0);
|
|
69
|
+
row.forEach((v, k) => {
|
|
70
|
+
const bk = b[k];
|
|
71
|
+
for (let j = 0; j < ncol; j++)
|
|
72
|
+
out[j] += v * bk[j];
|
|
73
|
+
});
|
|
74
|
+
return out;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** X'X */
|
|
78
|
+
function crossprod(x, p) {
|
|
79
|
+
const s = Array.from({ length: p }, () => new Array(p).fill(0));
|
|
80
|
+
for (let i = 0; i < p; i++) {
|
|
81
|
+
for (let j = i; j < p; j++) {
|
|
82
|
+
let sum = 0;
|
|
83
|
+
for (const row of x)
|
|
84
|
+
sum += row[i] * row[j];
|
|
85
|
+
s[i][j] = sum;
|
|
86
|
+
s[j][i] = sum;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return s;
|
|
90
|
+
}
|
|
91
|
+
const columnsOf = (m, cols) => m.map((row) => cols.map((j) => row[j]));
|
|
92
|
+
const DOOLITTLE_ZERO = 1e-6;
|
|
93
|
+
/**
|
|
94
|
+
* The Doolittle factorisation S = L U of a symmetric matrix without pivoting: L unit lower triangular, U upper
|
|
95
|
+
* triangular; a column of L below a pivot |U_ii| < 1e-6 is 0, and entries below 1e-6 in absolute value are set to 0
|
|
96
|
+
* at the end.
|
|
97
|
+
*/
|
|
98
|
+
export function doolittle(s) {
|
|
99
|
+
const k = s.length;
|
|
100
|
+
const L = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (__, j) => (i === j ? 1 : 0)));
|
|
101
|
+
const U = Array.from({ length: k }, () => new Array(k).fill(0));
|
|
102
|
+
for (let i = 0; i < k; i++) {
|
|
103
|
+
for (let j = 0; j < k; j++) {
|
|
104
|
+
let v = s[i][j];
|
|
105
|
+
for (let t = 0; t < i; t++)
|
|
106
|
+
v -= L[i][t] * U[t][j];
|
|
107
|
+
U[i][j] = v;
|
|
108
|
+
}
|
|
109
|
+
const pivot = U[i][i];
|
|
110
|
+
for (let j = i + 1; j < k; j++) {
|
|
111
|
+
if (Math.abs(pivot) < DOOLITTLE_ZERO) {
|
|
112
|
+
L[j][i] = 0;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
let v = s[j][i];
|
|
116
|
+
for (let t = 0; t < i; t++)
|
|
117
|
+
v -= L[j][t] * U[t][i];
|
|
118
|
+
L[j][i] = v / pivot;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
for (const m of [L, U]) {
|
|
122
|
+
for (const row of m) {
|
|
123
|
+
row.forEach((v, j) => {
|
|
124
|
+
if (Math.abs(v) < DOOLITTLE_ZERO)
|
|
125
|
+
row[j] = 0;
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { L, U };
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* For each term, the indices of the terms that contain it: those whose variables include all of its own and at
|
|
133
|
+
* least one more, with the same numeric variables (in the order of the terms).
|
|
134
|
+
*/
|
|
135
|
+
export function containingTerms(desc) {
|
|
136
|
+
const numeric = new Set(desc.variables.filter((v) => v.frame.kind === "numeric").map((v) => v.name));
|
|
137
|
+
const numericOf = (t) => t.variables.filter((v) => numeric.has(v)).sort().join("\u0000");
|
|
138
|
+
return desc.terms.map((a) => desc.terms
|
|
139
|
+
.map((b, k) => ({ b, k }))
|
|
140
|
+
.filter(({ b }) => a.variables.every((v) => b.variables.includes(v)) && b.variables.length > a.variables.length && numericOf(a) === numericOf(b))
|
|
141
|
+
.map(({ k }) => k));
|
|
142
|
+
}
|
|
143
|
+
/** The columns (0-based) of a term (index into terms) given the assign of the columns */
|
|
144
|
+
const termColumns = (assign, term) => assign.flatMap((a, j) => (a === term + 1 ? [j] : []));
|
|
145
|
+
/** Rows `rows` of a matrix with the names of those rows */
|
|
146
|
+
function hypothesis(term, m, rows, rowNames, columns) {
|
|
147
|
+
return { term, rows: rows.map((i) => rowNames[i]), columns: [...columns], values: rows.map((i) => [...m[i]]) };
|
|
148
|
+
}
|
|
149
|
+
/** Type I: the rows of the transposed Doolittle factor of X'X, by term */
|
|
150
|
+
function typeI(desc) {
|
|
151
|
+
const p = desc.colNames.length;
|
|
152
|
+
if (p === 0 || (p === 1 && desc.intercept))
|
|
153
|
+
return [];
|
|
154
|
+
const Lt = p === 1 ? [[1]] : transpose(doolittle(crossprod(desc.x, p)).L, p);
|
|
155
|
+
return desc.terms.map((t, k) => hypothesis(t.label, Lt, termColumns(desc.assign, k), desc.colNames, desc.colNames));
|
|
156
|
+
}
|
|
157
|
+
/** Type II: marginal for the terms contained in no other, otherwise the Doolittle factor with the term last */
|
|
158
|
+
function typeII(desc) {
|
|
159
|
+
const p = desc.colNames.length;
|
|
160
|
+
const containing = containingTerms(desc);
|
|
161
|
+
return desc.terms.map((t, k) => {
|
|
162
|
+
const cols = termColumns(desc.assign, k);
|
|
163
|
+
if (containing[k].length === 0) {
|
|
164
|
+
const identity = cols.map((i) => Array.from({ length: p }, (_, j) => (i === j ? 1 : 0)));
|
|
165
|
+
return { term: t.label, rows: cols.map((i) => desc.colNames[i]), columns: [...desc.colNames], values: identity };
|
|
166
|
+
}
|
|
167
|
+
const related = [k, ...containing[k]].flatMap((term) => termColumns(desc.assign, term));
|
|
168
|
+
const relatedSet = new Set(related);
|
|
169
|
+
const order = [...desc.colNames.map((_, j) => j).filter((j) => !relatedSet.has(j)), ...related];
|
|
170
|
+
const Lt = transpose(doolittle(crossprod(columnsOf(desc.x, order), p)).L, p);
|
|
171
|
+
const mine = new Set(cols);
|
|
172
|
+
const positions = order.flatMap((j, pos) => (mine.has(j) ? [pos] : []));
|
|
173
|
+
const values = positions.map((pos) => {
|
|
174
|
+
const row = new Array(p).fill(0);
|
|
175
|
+
order.forEach((j, q) => (row[j] = Lt[pos][q]));
|
|
176
|
+
return row;
|
|
177
|
+
});
|
|
178
|
+
return { term: t.label, rows: positions.map((pos) => desc.colNames[order[pos]]), columns: [...desc.colNames], values };
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* The full-dummy matrix rdX: an intercept column (with an intercept), then for each term the columns of its model
|
|
183
|
+
* matrix with every level of each factor (the first variable varying fastest, numeric variables multiplying), and
|
|
184
|
+
* the "Missing cells" message for its columns that are all 0.
|
|
185
|
+
*/
|
|
186
|
+
export function fullDummyMatrix(desc) {
|
|
187
|
+
const n = desc.x.length;
|
|
188
|
+
const frameOf = new Map(desc.variables.map((v) => [v.name, v.frame]));
|
|
189
|
+
const columns = [];
|
|
190
|
+
const colNames = [];
|
|
191
|
+
if (desc.intercept) {
|
|
192
|
+
columns.push(new Array(n).fill(1));
|
|
193
|
+
colNames.push("(Intercept)");
|
|
194
|
+
}
|
|
195
|
+
const partsOf = (name) => {
|
|
196
|
+
const fv = frameOf.get(name);
|
|
197
|
+
if (fv.kind === "numeric")
|
|
198
|
+
return [{ name, values: fv.values }];
|
|
199
|
+
return fv.levels.map((level, l) => ({ name: name + level, values: fv.codes.map((c) => (c === l ? 1 : 0)) }));
|
|
200
|
+
};
|
|
201
|
+
for (const t of desc.terms) {
|
|
202
|
+
let cur = partsOf(t.variables[0]);
|
|
203
|
+
for (const v of t.variables.slice(1)) {
|
|
204
|
+
const next = [];
|
|
205
|
+
for (const part of partsOf(v))
|
|
206
|
+
for (const c of cur)
|
|
207
|
+
next.push({ name: `${c.name}:${part.name}`, values: c.values.map((x, i) => x * part.values[i]) });
|
|
208
|
+
cur = next;
|
|
209
|
+
}
|
|
210
|
+
for (const c of cur) {
|
|
211
|
+
columns.push(c.values);
|
|
212
|
+
colNames.push(c.name);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const empty = colNames.filter((_, j) => columns[j].every((v) => v === 0));
|
|
216
|
+
const messages = empty.length > 0 ? [`Missing cells for: ${empty.join(", ")}. \nInterpret type III hypotheses with care.`] : [];
|
|
217
|
+
return { x: Array.from({ length: n }, (_, i) => columns.map((c) => c[i])), colNames, messages };
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* X remade from the same terms and model frame with treatment contrasts for every factor, restricted (if it is not
|
|
221
|
+
* of full column rank) to the first r pivot columns of its pivoted QR decomposition (tolerance 1e-7), r its rank.
|
|
222
|
+
*/
|
|
223
|
+
export function treatmentModelMatrix(desc) {
|
|
224
|
+
const data = {};
|
|
225
|
+
const levels = {};
|
|
226
|
+
for (const { name, frame } of desc.variables) {
|
|
227
|
+
if (frame.kind === "numeric")
|
|
228
|
+
data[name] = frame.values;
|
|
229
|
+
else {
|
|
230
|
+
data[name] = frame.codes.map((c) => frame.levels[c]);
|
|
231
|
+
levels[name] = frame.levels;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const sum = (nodes) => nodes.reduce((l, r) => (l === undefined ? r : { type: "binary", op: "+", left: l, right: r }), undefined);
|
|
235
|
+
const variable = (name) => ({ type: "var", name });
|
|
236
|
+
// the variables listed in the order of the formula (for the names of the columns), the terms expanded
|
|
237
|
+
const parsed = { response: undefined, rhs: sum(desc.variables.map((v) => variable(v.name))) ?? ONE };
|
|
238
|
+
const termNodes = desc.terms.map((t) => t.variables.map(variable).reduce((l, r) => ({ type: "binary", op: ":", left: l, right: r })));
|
|
239
|
+
const d = design(parsed, data, { levels, intercept: desc.intercept }, sum(termNodes) ?? ONE);
|
|
240
|
+
let keep = d.colNames.map((_, j) => j);
|
|
241
|
+
if (keep.length > 0) {
|
|
242
|
+
const decomposition = qr(d.x);
|
|
243
|
+
if (decomposition.rank < keep.length)
|
|
244
|
+
keep = decomposition.pivot.slice(0, decomposition.rank);
|
|
245
|
+
}
|
|
246
|
+
return { x: columnsOf(d.x, keep), colNames: keep.map((j) => d.colNames[j]), assign: keep.map((j) => d.assign[j]) };
|
|
247
|
+
}
|
|
248
|
+
const ROW_ZERO = 1e-8;
|
|
249
|
+
/** Type III (and its messages) */
|
|
250
|
+
function typeIII(desc) {
|
|
251
|
+
const treatment = Object.values(desc.contrasts).every((c) => c === "contr.treatment");
|
|
252
|
+
const xt = treatment ? { x: desc.x, colNames: desc.colNames, assign: desc.assign } : treatmentModelMatrix(desc);
|
|
253
|
+
const pt = xt.colNames.length;
|
|
254
|
+
const rd = fullDummyMatrix(desc);
|
|
255
|
+
const gInverse = ginv(xt.x);
|
|
256
|
+
// rows: the columns of rdX; columns: the columns of X_t
|
|
257
|
+
const L0 = zapsmall(transpose(multiply(gInverse, rd.x, rd.colNames.length), rd.colNames.length));
|
|
258
|
+
const containing = containingTerms(desc);
|
|
259
|
+
const byOrder = desc.terms.map((t, k) => ({ k, order: t.variables.length })).sort((a, b) => b.order - a.order || a.k - b.k);
|
|
260
|
+
for (const { k } of byOrder) {
|
|
261
|
+
if (containing[k].length === 0)
|
|
262
|
+
continue;
|
|
263
|
+
const cols = termColumns(xt.assign, k);
|
|
264
|
+
if (cols.length === 0)
|
|
265
|
+
continue;
|
|
266
|
+
const others = containing[k].flatMap((term) => termColumns(xt.assign, term));
|
|
267
|
+
let block = columnsOf(L0, cols);
|
|
268
|
+
if (others.length > 0)
|
|
269
|
+
block = qrResid(qr(columnsOf(L0, others)), block);
|
|
270
|
+
const zapped = zapsmall(block);
|
|
271
|
+
L0.forEach((row, i) => cols.forEach((j, c) => (row[j] = zapped[i][c])));
|
|
272
|
+
}
|
|
273
|
+
const rowOf = new Map(rd.colNames.map((name, i) => [name, i]));
|
|
274
|
+
const L1 = xt.colNames.map((name) => {
|
|
275
|
+
const i = rowOf.get(name);
|
|
276
|
+
if (i === undefined)
|
|
277
|
+
throw new Error(`lmerHypotheses: the column '${name}' of the model matrix is not a column of the full-dummy matrix`);
|
|
278
|
+
return L0[i];
|
|
279
|
+
});
|
|
280
|
+
const mapping = treatment ? undefined : zapsmall(multiply(gInverse, desc.x, desc.colNames.length));
|
|
281
|
+
const hypotheses = desc.terms.map((t, k) => {
|
|
282
|
+
const cols = termColumns(xt.assign, k).filter((j) => L1.reduce((s, row) => s + Math.abs(row[j]), 0) > ROW_ZERO);
|
|
283
|
+
const values = cols.map((j) => L1.map((row) => row[j]));
|
|
284
|
+
return {
|
|
285
|
+
term: t.label,
|
|
286
|
+
rows: cols.map((j) => xt.colNames[j]),
|
|
287
|
+
columns: [...desc.colNames],
|
|
288
|
+
values: mapping === undefined ? values : multiply(values, mapping, desc.colNames.length),
|
|
289
|
+
};
|
|
290
|
+
});
|
|
291
|
+
return { hypotheses, messages: rd.messages };
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The hypothesis matrices of lmerTest's ANOVA table of the given type, one per term (oracle/lmertest-behaviour.md,
|
|
295
|
+
* section 2). If X has at most one column or the formula at most one term, every type is built as Type I.
|
|
296
|
+
*/
|
|
297
|
+
export function lmerHypotheses(desc, type = "III") {
|
|
298
|
+
if (desc.colNames.length <= 1 || desc.terms.length <= 1 || type === "I")
|
|
299
|
+
return { hypotheses: typeI(desc), messages: [] };
|
|
300
|
+
if (type === "II")
|
|
301
|
+
return { hypotheses: typeII(desc), messages: [] };
|
|
302
|
+
return typeIII(desc);
|
|
303
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { Warnings } from "./glmFamily.js";
|
|
2
|
+
import { type LmerResult } from "./lmer.js";
|
|
3
|
+
import type { MixedModelStructure } from "./mixedStructure.js";
|
|
4
|
+
/**
|
|
5
|
+
* The Satterthwaite quantities of a fit (internal): the variance parameters varpar = (θ, σ), the Hessian H of the
|
|
6
|
+
* deviance in them with its eigenvalues, their asymptotic covariance A = 2 H⁺ (lmerTest's `vcov_varpar`), the fixed
|
|
7
|
+
* effects β̂ with their covariance V = C(varpar) and its Jacobians J_k = ∂C/∂varpar_k, and the warnings of the Hessian.
|
|
8
|
+
*/
|
|
9
|
+
export interface LmerSatterthwaite {
|
|
10
|
+
varpar: number[];
|
|
11
|
+
hessian: number[][];
|
|
12
|
+
hessianEigenvalues: number[];
|
|
13
|
+
vcovVarpar: number[][];
|
|
14
|
+
beta: number[];
|
|
15
|
+
sigma: number;
|
|
16
|
+
vcov: number[][];
|
|
17
|
+
jacobian: number[][][];
|
|
18
|
+
warnings: string[];
|
|
19
|
+
}
|
|
20
|
+
/** The warnings about the Hessian's eigenvalues (negative, or close to 0; internal) */
|
|
21
|
+
export declare function hessianWarnings(values: readonly number[]): string[];
|
|
22
|
+
/**
|
|
23
|
+
* The Satterthwaite quantities of a fit by {@link lmer} (see {@link LmerSatterthwaite}), computed once per fit.
|
|
24
|
+
* Internal: the summary, the contrasts and the ANOVA tables use it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function lmerSatterthwaite(fit: LmerResult): LmerSatterthwaite;
|
|
27
|
+
/**
|
|
28
|
+
* The Satterthwaite quantities at any θ (σ from the penalised residual sum of squares there). Internal: the test
|
|
29
|
+
* evaluates them at lme4's optimum too, to compare with lmerTest's numerical derivatives at the same point.
|
|
30
|
+
*/
|
|
31
|
+
export declare function satterthwaiteAt(structure: MixedModelStructure, theta: readonly number[], reml: boolean): LmerSatterthwaite;
|
|
32
|
+
/** The one-dimensional test of a contrast l (internal) */
|
|
33
|
+
export interface TRow {
|
|
34
|
+
estimate: number;
|
|
35
|
+
stdError: number;
|
|
36
|
+
df: number;
|
|
37
|
+
tValue: number;
|
|
38
|
+
pValue: number;
|
|
39
|
+
}
|
|
40
|
+
/** l'β̂ − rhs over its standard error, with Satterthwaite's degrees of freedom 2 var² / (g'Ag), g_k = l'J_k l */
|
|
41
|
+
export declare function tTestOf(s: LmerSatterthwaite, l: readonly number[], rhs: number, beta?: readonly number[]): TRow;
|
|
42
|
+
/** One row of an F table (internal): lmerTest's `Sum Sq`, `Mean Sq`, `NumDF`, `DenDF`, `F value`, `Pr(>F)` */
|
|
43
|
+
export interface LmerFRow {
|
|
44
|
+
sumSq: number;
|
|
45
|
+
meanSq: number;
|
|
46
|
+
numDF: number;
|
|
47
|
+
denDF: number;
|
|
48
|
+
F: number;
|
|
49
|
+
pValue: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The joint F-test of the rows of L (r × p) with Satterthwaite's denominator degrees of freedom (internal; the ANOVA
|
|
53
|
+
* tables use it): undefined when the rows have rank 0 (no test). `rhs` has one value per row (default 0); a non-zero
|
|
54
|
+
* right-hand side with a rank-deficient L adds the warning to `warnings`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function lmerFTest(fit: LmerResult, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
|
|
57
|
+
/** {@link lmerFTest} with the Satterthwaite quantities given (internal) */
|
|
58
|
+
export declare function fTestOf(s: LmerSatterthwaite, L: readonly (readonly number[])[], rhs: readonly number[] | undefined, warnings: Warnings): LmerFRow | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* Options of {@link lmerSummary}.
|
|
61
|
+
*
|
|
62
|
+
* @category Mixed models
|
|
63
|
+
*/
|
|
64
|
+
export interface LmerSummaryOptions {
|
|
65
|
+
/**
|
|
66
|
+
* The denominator degrees of freedom: `"Satterthwaite"` (default; with df and p-values) or `"lme4"` (lme4's table:
|
|
67
|
+
* estimates, standard errors and t values only).
|
|
68
|
+
*/
|
|
69
|
+
ddf?: "Satterthwaite" | "lme4";
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Result of {@link lmerSummary}: the coefficient table of lmerTest's `summary()`.
|
|
73
|
+
*
|
|
74
|
+
* @category Mixed models
|
|
75
|
+
*/
|
|
76
|
+
export interface LmerSummary {
|
|
77
|
+
/** The method of the degrees of freedom. */
|
|
78
|
+
ddf: "Satterthwaite" | "lme4";
|
|
79
|
+
/** The names of the fixed effects (R's row names). */
|
|
80
|
+
names: string[];
|
|
81
|
+
/** Estimates (R's `Estimate`). */
|
|
82
|
+
estimate: number[];
|
|
83
|
+
/** Standard errors (R's `Std. Error`). */
|
|
84
|
+
stdError: number[];
|
|
85
|
+
/** Satterthwaite's degrees of freedom (R's `df`; not with `ddf: "lme4"`). */
|
|
86
|
+
df?: number[];
|
|
87
|
+
/** t statistics (R's `t value`). */
|
|
88
|
+
tValue: number[];
|
|
89
|
+
/** Two-sided p-values (R's `Pr(>|t|)`; not with `ddf: "lme4"`). */
|
|
90
|
+
pValue?: number[];
|
|
91
|
+
/** R's messages (none so far). */
|
|
92
|
+
messages: string[];
|
|
93
|
+
/** R's warnings: those about the eigenvalues of the Hessian of the deviance in the variance parameters. */
|
|
94
|
+
warnings: string[];
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The coefficient table of a linear mixed model fitted by {@link lmer}, with Satterthwaite's degrees of freedom and
|
|
98
|
+
* the p-values of the t-tests: the `summary()` of a fit by lmerTest. Equivalent to `lmerTest::summary()` in R.
|
|
99
|
+
*
|
|
100
|
+
* The degrees of freedom of each coefficient are Satterthwaite's: 2 var² / (g'Ag), with var its variance, g its
|
|
101
|
+
* derivative in the variance parameters (θ, σ) and A their asymptotic covariance (twice the inverse Hessian of the
|
|
102
|
+
* deviance). The derivatives are computed analytically at the exact optimum (lmerTest differentiates numerically at
|
|
103
|
+
* lme4's optimum, so its degrees of freedom typically differ in the 5th to 8th significant digit). With
|
|
104
|
+
* `ddf: "lme4"` the table is lme4's (as `coefTable` of the fit), without degrees of freedom and p-values.
|
|
105
|
+
*
|
|
106
|
+
* @param fit A result of {@link lmer} (the object it returned, not a copy).
|
|
107
|
+
* @param options `ddf`: `"Satterthwaite"` (default) or `"lme4"`.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* // R: summary(lmerTest::lmer(y ~ x + (1 | g), data))
|
|
112
|
+
* const fit = lmer("y ~ x + (1 | g)", {
|
|
113
|
+
* y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4],
|
|
114
|
+
* x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
|
|
115
|
+
* g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d"],
|
|
116
|
+
* });
|
|
117
|
+
* const s = lmerSummary(fit);
|
|
118
|
+
* s.names; // ["(Intercept)", "x"]
|
|
119
|
+
* s.df; // [3.2717, 7]
|
|
120
|
+
* s.pValue; // [0.032598, 7.9895e-5]
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @category Mixed models
|
|
124
|
+
*/
|
|
125
|
+
export declare function lmerSummary(fit: LmerResult, options?: LmerSummaryOptions): LmerSummary;
|
|
126
|
+
/**
|
|
127
|
+
* Options of {@link lmerContest}.
|
|
128
|
+
*
|
|
129
|
+
* @category Mixed models
|
|
130
|
+
*/
|
|
131
|
+
export interface LmerContestOptions {
|
|
132
|
+
/** The right-hand side of the hypothesis L β = rhs: one value, or one per row of L (default 0). */
|
|
133
|
+
rhs?: number | readonly number[];
|
|
134
|
+
/** Test the rows jointly with one F-test (default `true`), or each row with its own t-test (`false`). */
|
|
135
|
+
joint?: boolean;
|
|
136
|
+
/** With `joint: false`, whether to add the confidence intervals (default `true`). */
|
|
137
|
+
confint?: boolean;
|
|
138
|
+
/** The confidence level of the intervals (default 0.95). */
|
|
139
|
+
level?: number;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Result of {@link lmerContest} with `joint: true` (the default): one row of an F table, or none when the rows of L
|
|
143
|
+
* have rank 0.
|
|
144
|
+
*
|
|
145
|
+
* @category Mixed models
|
|
146
|
+
*/
|
|
147
|
+
export interface LmerContestF {
|
|
148
|
+
/** Whether the rows were tested jointly: always `true` here. */
|
|
149
|
+
joint: true;
|
|
150
|
+
/** R's `Sum Sq`: F σ² NumDF. */
|
|
151
|
+
sumSq: number[];
|
|
152
|
+
/** R's `Mean Sq`: F σ². */
|
|
153
|
+
meanSq: number[];
|
|
154
|
+
/** R's `NumDF`: the rank of the hypothesis. */
|
|
155
|
+
numDF: number[];
|
|
156
|
+
/** R's `DenDF`: Satterthwaite's denominator degrees of freedom. */
|
|
157
|
+
denDF: number[];
|
|
158
|
+
/** R's `F value`. */
|
|
159
|
+
F: number[];
|
|
160
|
+
/** R's `Pr(>F)`. */
|
|
161
|
+
pValue: number[];
|
|
162
|
+
/** R's messages (none so far). */
|
|
163
|
+
messages: string[];
|
|
164
|
+
/** R's warnings (about the Hessian's eigenvalues; `Contrast is rank deficient and test may be affected`). */
|
|
165
|
+
warnings: string[];
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Result of {@link lmerContest} with `joint: false`: one t-test per row of L.
|
|
169
|
+
*
|
|
170
|
+
* @category Mixed models
|
|
171
|
+
*/
|
|
172
|
+
export interface LmerContestT {
|
|
173
|
+
/** Whether the rows were tested jointly: always `false` here. */
|
|
174
|
+
joint: false;
|
|
175
|
+
/** R's `Estimate`: l'β̂. */
|
|
176
|
+
estimate: number[];
|
|
177
|
+
/** R's `Std. Error`. */
|
|
178
|
+
stdError: number[];
|
|
179
|
+
/** R's `df`: Satterthwaite's degrees of freedom. */
|
|
180
|
+
df: number[];
|
|
181
|
+
/** R's `t value`: (estimate − rhs) / stdError. */
|
|
182
|
+
tValue: number[];
|
|
183
|
+
/** R's `Pr(>|t|)`. */
|
|
184
|
+
pValue: number[];
|
|
185
|
+
/** R's `lower`: the lower limit of the confidence interval of the estimate (unless `confint: false`). */
|
|
186
|
+
lower?: number[];
|
|
187
|
+
/** R's `upper`: the upper limit of the confidence interval (unless `confint: false`). */
|
|
188
|
+
upper?: number[];
|
|
189
|
+
/** R's messages (none so far). */
|
|
190
|
+
messages: string[];
|
|
191
|
+
/** R's warnings (about the Hessian's eigenvalues). */
|
|
192
|
+
warnings: string[];
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Tests of contrasts L β = rhs of the fixed effects of a linear mixed model fitted by {@link lmer}, with Satterthwaite's
|
|
196
|
+
* degrees of freedom. Equivalent to `lmerTest::contest()` in R.
|
|
197
|
+
*
|
|
198
|
+
* `L` is one contrast (a vector, one value per fixed effect) or several (an array of rows). By default the rows are
|
|
199
|
+
* tested jointly: an F-test of the hypothesis, rotated to its eigenvectors (rows that are linearly dependent count
|
|
200
|
+
* once; a row set of rank 0 gives an empty table). With `joint: false` each row has its own t-test, with a confidence
|
|
201
|
+
* interval at `level` unless `confint` is false. The degrees of freedom come from the analytic derivatives at the exact
|
|
202
|
+
* optimum (see {@link lmerSummary}).
|
|
203
|
+
*
|
|
204
|
+
* @param fit A result of {@link lmer} (the object it returned, not a copy).
|
|
205
|
+
* @param L A contrast, or an array of contrasts (rows).
|
|
206
|
+
* @param options `rhs`, `joint`, `confint`, `level`.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* ```ts
|
|
210
|
+
* // R: contest(lmerTest::lmer(y ~ x + (1 | g), data), c(0, 1), joint = FALSE)
|
|
211
|
+
* const fit = lmer("y ~ x + (1 | g)", {
|
|
212
|
+
* y: [3.1, 4.0, 5.2, 6.8, 7.1, 8.3, 2.2, 3.5, 3.9, 5.9, 6.1, 7.4],
|
|
213
|
+
* x: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
|
|
214
|
+
* g: ["a", "a", "a", "b", "b", "b", "c", "c", "c", "d", "d", "d"],
|
|
215
|
+
* });
|
|
216
|
+
* const t = lmerContest(fit, [0, 1], { joint: false });
|
|
217
|
+
* t.estimate; // [0.85]
|
|
218
|
+
* t.lower; // [0.60388]
|
|
219
|
+
* // R: contest(fit, diag(2))
|
|
220
|
+
* const f = lmerContest(fit, [[1, 0], [0, 1]]);
|
|
221
|
+
* f.numDF; // [2]
|
|
222
|
+
* f.F; // [47.804]
|
|
223
|
+
* ```
|
|
224
|
+
*
|
|
225
|
+
* @category Mixed models
|
|
226
|
+
*/
|
|
227
|
+
export declare function lmerContest(fit: LmerResult, L: readonly number[] | readonly (readonly number[])[], options?: LmerContestOptions & {
|
|
228
|
+
joint?: true;
|
|
229
|
+
}): LmerContestF;
|
|
230
|
+
export declare function lmerContest(fit: LmerResult, L: readonly number[] | readonly (readonly number[])[], options: LmerContestOptions & {
|
|
231
|
+
joint: false;
|
|
232
|
+
}): LmerContestT;
|
|
233
|
+
export declare function lmerContest(fit: LmerResult, L: readonly number[] | readonly (readonly number[])[], options?: LmerContestOptions): LmerContestF | LmerContestT;
|