@numero-uno-jpn/rstats 1.7.0 → 1.9.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 +38 -0
- package/README.ja.md +8 -7
- package/README.md +7 -6
- package/dist/chunks/{chunk-CB7STL5Z.js → chunk-2COJEI44.js} +2 -2
- package/dist/chunks/{chunk-V2Y2W7LE.js → chunk-2SO7Z3NV.js} +2 -2
- package/dist/chunks/{chunk-MOJ2KIQE.js → chunk-3J2HFC4A.js} +2 -2
- package/dist/chunks/chunk-3LDUKHJZ.js +3 -0
- package/dist/chunks/{chunk-VALULDEX.js → chunk-4IHHZ3F4.js} +1 -1
- package/dist/chunks/chunk-4QWW62QN.js +2 -0
- package/dist/chunks/chunk-575F6RXJ.js +2 -0
- package/dist/chunks/{chunk-CUT3IHMY.js → chunk-5C7XHQKP.js} +1 -1
- package/dist/chunks/{chunk-J7ZVV4DN.js → chunk-7F7PY35D.js} +2 -2
- package/dist/chunks/{chunk-PLQQ4VFN.js → chunk-7VPO2LTR.js} +2 -2
- package/dist/chunks/{chunk-THSV22QF.js → chunk-ANGKH5D4.js} +2 -2
- package/dist/chunks/{chunk-TY3IFCLI.js → chunk-BX47HGID.js} +2 -2
- package/dist/chunks/chunk-CWS62KPG.js +2 -0
- package/dist/chunks/chunk-D3CWLSLS.js +2 -0
- package/dist/chunks/{chunk-HSJ4OT3H.js → chunk-DEAU6HWA.js} +1 -1
- package/dist/chunks/chunk-DRSA7ITF.js +2 -0
- package/dist/chunks/{chunk-56AMJQ27.js → chunk-G3XMR7PA.js} +2 -2
- package/dist/chunks/chunk-I7E5J5PG.js +3 -0
- package/dist/chunks/{chunk-YKNRDPIB.js → chunk-IEATFACS.js} +2 -2
- package/dist/chunks/{chunk-HORF36FD.js → chunk-IXK3JA2R.js} +2 -2
- package/dist/chunks/{chunk-CZUOG2U5.js → chunk-J3TS4PGN.js} +2 -2
- package/dist/chunks/{chunk-BJMPSDJ7.js → chunk-MNIICUNF.js} +2 -2
- package/dist/chunks/chunk-MT7XELUM.js +2 -0
- package/dist/chunks/{chunk-76FLTZVF.js → chunk-OGHJJKUR.js} +2 -2
- package/dist/chunks/{chunk-QWDK3ZC2.js → chunk-RNK6EHEK.js} +2 -2
- package/dist/chunks/{chunk-RIP2RKAW.js → chunk-T3NUXZRL.js} +2 -2
- package/dist/chunks/chunk-TKMNASCD.js +2 -0
- package/dist/chunks/chunk-UA66IB37.js +2 -0
- package/dist/chunks/chunk-UUZVQS4O.js +2 -0
- package/dist/chunks/chunk-VO2NIKVB.js +2 -0
- package/dist/chunks/chunk-WFE52E6F.js +2 -0
- package/dist/chunks/{chunk-SDT3YHAG.js → chunk-WOZEQS2I.js} +2 -2
- package/dist/chunks/{chunk-FQRNZEH2.js → chunk-XCKQQVN7.js} +2 -2
- package/dist/chunks/chunk-XNLZFKL5.js +2 -0
- package/dist/chunks/chunk-YFZBGUIT.js +2 -0
- package/dist/chunks/{chunk-YVJ4LDDE.js → chunk-YK7Q6CNX.js} +2 -2
- package/dist/chunks/{chunk-B7XZMIQO.js → chunk-Z47NJMYU.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/multivariate.d.ts +3 -0
- package/dist/entries/multivariate.js +4 -0
- package/dist/entries/regression.d.ts +4 -0
- package/dist/entries/regression.js +6 -0
- package/dist/entries/tests.d.ts +3 -1
- package/dist/entries/tests.js +3 -1
- package/dist/htest/grubbs.d.ts +68 -0
- package/dist/htest/grubbs.js +151 -0
- package/dist/htest/multipleComparisons.d.ts +21 -0
- package/dist/htest/multipleComparisons.js +47 -0
- package/dist/htest/rankTests.d.ts +35 -0
- package/dist/htest/rankTests.js +89 -1
- package/dist/internal/summary.js +8 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/gee.d.ts +280 -0
- package/dist/models/gee.js +704 -0
- package/dist/models/glmnet.d.ts +259 -0
- package/dist/models/glmnet.js +1112 -0
- package/dist/models/modelMatrix.d.ts +2 -0
- package/dist/models/rq.d.ts +203 -0
- package/dist/models/rq.js +1089 -0
- package/dist/multivariate/cancor.d.ts +55 -0
- package/dist/multivariate/cancor.js +167 -0
- package/dist/multivariate/lda.d.ts +146 -0
- package/dist/multivariate/lda.js +325 -0
- package/dist/multivariate/manova.d.ts +106 -0
- package/dist/multivariate/manova.js +303 -0
- package/dist/multivariate.js +2 -0
- package/dist/numerics.js +2 -2
- package/dist/regression.js +3 -3
- package/dist/rstats.js +16 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/llms.txt +5 -1
- package/package.json +6 -1
- package/dist/chunks/chunk-AIEPW6DX.js +0 -2
- package/dist/chunks/chunk-B6KJ4RWG.js +0 -2
- package/dist/chunks/chunk-JXEXOD7K.js +0 -2
- package/dist/chunks/chunk-KSH43GX4.js +0 -2
- package/dist/chunks/chunk-LMRCFKVK.js +0 -2
- package/dist/chunks/chunk-PCTRVBEJ.js +0 -3
- package/dist/chunks/chunk-R5BMFVIH.js +0 -2
- package/dist/chunks/chunk-R7F7ELS7.js +0 -3
- package/dist/chunks/chunk-RX6MZO2Y.js +0 -2
- package/dist/chunks/chunk-VQOU7U7R.js +0 -2
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// Linear discriminant analysis using weighted between-class moments and the pooled within-class metric.
|
|
2
|
+
import { eigen } from "../linalg/eigen.js";
|
|
3
|
+
import { qr } from "../linalg/qr.js";
|
|
4
|
+
import { fromMat, toMatOrColumn } from "../linalg/matrix.js";
|
|
5
|
+
import { mean } from "../internal/summary.js";
|
|
6
|
+
import { compareLabels, factorLabels } from "../htest/groups.js";
|
|
7
|
+
import { design } from "../models/modelMatrix.js";
|
|
8
|
+
import { parseFormula } from "../models/formula.js";
|
|
9
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
10
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
11
|
+
const LDA_KEYS = ["method", "prior", "tol", "CV", "xNames", "groupLevels", "levels"];
|
|
12
|
+
const LDA_PREDICT_KEYS = ["method", "newdata", "prior", "dimen"];
|
|
13
|
+
function zeros(r, c) { return Array.from({ length: r }, () => new Array(c).fill(0)); }
|
|
14
|
+
function cross(a) {
|
|
15
|
+
const out = zeros(a[0]?.length ?? 0, a[0]?.length ?? 0);
|
|
16
|
+
for (const row of a)
|
|
17
|
+
for (let i = 0; i < row.length; i++)
|
|
18
|
+
for (let j = 0; j < row.length; j++)
|
|
19
|
+
out[i][j] += row[i] * row[j];
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
function mul(a, b) {
|
|
23
|
+
const out = zeros(a.length, b[0]?.length ?? 0);
|
|
24
|
+
for (let i = 0; i < a.length; i++)
|
|
25
|
+
for (let k = 0; k < (a[0]?.length ?? 0); k++)
|
|
26
|
+
for (let j = 0; j < (b[0]?.length ?? 0); j++)
|
|
27
|
+
out[i][j] += a[i][k] * b[k][j];
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
function inverseFromEigen(a, tol) {
|
|
31
|
+
const e = eigen(a, { symmetric: true });
|
|
32
|
+
const max = Math.max(0, ...e.values);
|
|
33
|
+
const keep = e.values.map((v, i) => v > max * tol ? i : -1).filter((i) => i >= 0);
|
|
34
|
+
const q = e.vectors;
|
|
35
|
+
const inv = zeros(a.length, a.length), invs = zeros(a.length, a.length);
|
|
36
|
+
for (const k of keep)
|
|
37
|
+
for (let i = 0; i < a.length; i++)
|
|
38
|
+
for (let j = 0; j < a.length; j++) {
|
|
39
|
+
inv[i][j] += q[i][k] * q[j][k] / e.values[k];
|
|
40
|
+
invs[i][j] += q[i][k] * q[j][k] / Math.sqrt(e.values[k]);
|
|
41
|
+
}
|
|
42
|
+
return { inverse: inv, inverseSqrt: invs, rank: keep.length, values: e.values, vectors: q };
|
|
43
|
+
}
|
|
44
|
+
function normalisePrior(prior, counts) {
|
|
45
|
+
const p = prior === undefined ? counts.map((n) => n / counts.reduce((a, b) => a + b, 0)) : Array.from(prior);
|
|
46
|
+
if (p.length !== counts.length || p.some((v) => !Number.isFinite(v) || v <= 0))
|
|
47
|
+
throw new RangeError("prior must contain one positive finite value per group");
|
|
48
|
+
const sum = p.reduce((a, b) => a + b, 0);
|
|
49
|
+
if (Number.isFinite(sum))
|
|
50
|
+
return p.map((v) => v / sum);
|
|
51
|
+
const max = p.reduce((a, b) => Math.max(a, b), 0);
|
|
52
|
+
const scaled = p.map((v) => v / max);
|
|
53
|
+
const scaledSum = scaled.reduce((a, b) => a + b, 0);
|
|
54
|
+
return scaled.map((v) => v / scaledSum);
|
|
55
|
+
}
|
|
56
|
+
function matrixInput(x) { return fromMat(toMatOrColumn(x)); }
|
|
57
|
+
function fitCore(x0, g0, options, xNames, declaredLevels) {
|
|
58
|
+
if (x0.length !== g0.length)
|
|
59
|
+
throw new RangeError("x and grouping factor must have the same length");
|
|
60
|
+
const keep = x0.map((r, i) => ({ r, g: g0[i] })).filter(({ r, g }) => !r.some(Number.isNaN) && !(typeof g === "number" && Number.isNaN(g)));
|
|
61
|
+
if (keep.some(({ r }) => r.some((v) => !Number.isFinite(v))))
|
|
62
|
+
throw new RangeError("x must contain finite values");
|
|
63
|
+
const labels = factorLabels(keep.map((v) => v.g));
|
|
64
|
+
const observed = new Set(labels.map(String));
|
|
65
|
+
const declared = declaredLevels === undefined ? undefined : Array.from(new Set(declaredLevels.map(String)));
|
|
66
|
+
const levels = declared === undefined
|
|
67
|
+
? Array.from(observed).sort((a, b) => compareLabels(a, b))
|
|
68
|
+
: declared.filter((level) => observed.has(level));
|
|
69
|
+
const emptyLevels = declared?.filter((level) => !observed.has(level)) ?? [];
|
|
70
|
+
if (levels.length < 2)
|
|
71
|
+
throw new RangeError("grouping factor must have at least 2 levels");
|
|
72
|
+
const x = keep.map((v) => v.r);
|
|
73
|
+
const groups = labels.map(String);
|
|
74
|
+
const p = x[0]?.length ?? 0, n = x.length, g = levels.length;
|
|
75
|
+
if (p === 0 || x.some((r) => r.length !== p))
|
|
76
|
+
throw new RangeError("x must be a non-empty matrix with equal row lengths");
|
|
77
|
+
const scale = Array.from({ length: p }, (_, j) => { let m = 0; for (const r of x)
|
|
78
|
+
m = Math.max(m, Math.abs(r[j])); return m || 1; });
|
|
79
|
+
const origin = new Array(p).fill(0);
|
|
80
|
+
const spread = new Array(p).fill(1);
|
|
81
|
+
for (let j = 0; j < p; j++) {
|
|
82
|
+
const first = x[0][j];
|
|
83
|
+
let range = 0;
|
|
84
|
+
for (const row of x)
|
|
85
|
+
range = Math.max(range, Math.abs(row[j] - first));
|
|
86
|
+
// When a large common offset dwarfs the within-column variation, subtract it in
|
|
87
|
+
// the original coordinates before scaling. Keep historical coordinates otherwise.
|
|
88
|
+
if (range > 0 && Number.isFinite(range) && range < 1e-4 * scale[j]) {
|
|
89
|
+
origin[j] = first;
|
|
90
|
+
spread[j] = range;
|
|
91
|
+
scale[j] = 1;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const xs = x.map((r) => r.map((v, j) => (v / scale[j] - origin[j]) / spread[j]));
|
|
95
|
+
const by = levels.map((l) => xs.filter((_, i) => groups[i] === l));
|
|
96
|
+
const counts = by.map((a) => a.length);
|
|
97
|
+
const means = by.map((a) => Array.from({ length: p }, (_, j) => mean(a.map((r) => r[j]))));
|
|
98
|
+
let priorInput = options.prior;
|
|
99
|
+
if (priorInput !== undefined && declared !== undefined && priorInput.length === declared.length && declared.length !== levels.length) {
|
|
100
|
+
priorInput = declared.map((level, i) => observed.has(level) ? priorInput[i] : 0).filter((v) => v > 0);
|
|
101
|
+
}
|
|
102
|
+
const prior = normalisePrior(priorInput, counts);
|
|
103
|
+
const center = Array.from({ length: p }, (_, j) => prior.reduce((s, w, i) => s + w * means[i][j], 0));
|
|
104
|
+
const within = zeros(p, p), between = zeros(p, p);
|
|
105
|
+
const allDeviations = [];
|
|
106
|
+
for (let k = 0; k < g; k++) {
|
|
107
|
+
const deviations = by[k].map((r) => r.map((v, j) => v - means[k][j]));
|
|
108
|
+
allDeviations.push(...deviations);
|
|
109
|
+
const w = cross(deviations);
|
|
110
|
+
for (let i = 0; i < p; i++)
|
|
111
|
+
for (let j = 0; j < p; j++)
|
|
112
|
+
within[i][j] += w[i][j];
|
|
113
|
+
const d = means[k].map((v, j) => v - center[j]);
|
|
114
|
+
for (let i = 0; i < p; i++)
|
|
115
|
+
for (let j = 0; j < p; j++)
|
|
116
|
+
between[i][j] += n * prior[k] * d[i] * d[j];
|
|
117
|
+
}
|
|
118
|
+
const tol = options.tol ?? 1e-4;
|
|
119
|
+
if (!(Number.isFinite(tol) && tol >= 0))
|
|
120
|
+
throw new RangeError("'tol' must be a non-negative finite number");
|
|
121
|
+
const withinSd = Array.from({ length: p }, (_, j) => {
|
|
122
|
+
const df = Math.max(1, n - g);
|
|
123
|
+
if (origin[j] !== 0 || spread[j] !== 1) {
|
|
124
|
+
return Math.sqrt(within[j][j] / df) * spread[j] * scale[j];
|
|
125
|
+
}
|
|
126
|
+
if (scale[j] >= 1e-100 && scale[j] <= 1e100) {
|
|
127
|
+
return Math.sqrt(within[j][j] * scale[j] * scale[j] / df);
|
|
128
|
+
}
|
|
129
|
+
return Math.sqrt(within[j][j] / df) * scale[j];
|
|
130
|
+
});
|
|
131
|
+
const constant = withinSd.map((sd, i) => sd === 0 ? i + 1 : 0).filter((i) => i > 0);
|
|
132
|
+
const belowTolerance = options.tol === undefined ? [] : withinSd.map((sd, i) => sd < tol ? i + 1 : 0).filter((i) => i > 0);
|
|
133
|
+
const rejected = Array.from(new Set([...constant, ...belowTolerance])).sort((a, b) => a - b);
|
|
134
|
+
if (rejected.length)
|
|
135
|
+
throw new RangeError(`variable${rejected.length > 1 ? "s" : ""} ${rejected.join(" ")} appear${rejected.length === 1 ? "s" : ""} to be constant within groups`);
|
|
136
|
+
const rankDeviations = allDeviations.map((row) => row.map((v, j) => v / Math.sqrt(within[j][j])));
|
|
137
|
+
const exactRank = qr(rankDeviations, { tol: 1e-12 }).rank;
|
|
138
|
+
const rankTol = Math.sqrt(tol);
|
|
139
|
+
const toleranceQr = qr(rankDeviations, { tol: rankTol }).rank;
|
|
140
|
+
if (toleranceQr < exactRank) {
|
|
141
|
+
const q = qr(rankDeviations, { tol: rankTol });
|
|
142
|
+
const dropped = q.pivot.slice(q.rank).map((i) => i + 1).sort((a, b) => a - b);
|
|
143
|
+
throw new RangeError(`variables ${dropped.join(" ")} appear to be constant within groups`);
|
|
144
|
+
}
|
|
145
|
+
const metric = inverseFromEigen(within, tol);
|
|
146
|
+
if (metric.rank === 0)
|
|
147
|
+
throw new RangeError("variables are constant within groups");
|
|
148
|
+
const warnings = emptyLevels.map((level) => `group ${level} is empty`);
|
|
149
|
+
if (exactRank < p || metric.rank < p)
|
|
150
|
+
warnings.push("variables are collinear");
|
|
151
|
+
const whitened = mul(mul(metric.inverseSqrt, between), metric.inverseSqrt);
|
|
152
|
+
const be = eigen(whitened, { symmetric: true });
|
|
153
|
+
const max = Math.max(0, ...be.values);
|
|
154
|
+
const keepRoots = be.values.map((v, i) => v > max * tol ? i : -1).filter((i) => i >= 0).slice(0, g - 1);
|
|
155
|
+
const scaleFactor = Math.sqrt(Math.max(0, n - g));
|
|
156
|
+
const scalingNorm = mul(metric.inverseSqrt, be.vectors.map((r) => keepRoots.map((j) => r[j]))).map((r) => r.map((v) => v * scaleFactor));
|
|
157
|
+
const scaling = scalingNorm.map((r, i) => r.map((v) => v / spread[i] / scale[i]));
|
|
158
|
+
for (let j = 0; j < (scaling[0]?.length ?? 0); j++) {
|
|
159
|
+
let imax = 0;
|
|
160
|
+
for (let i = 1; i < scaling.length; i++)
|
|
161
|
+
if (Math.abs(scaling[i][j]) > Math.abs(scaling[imax][j]))
|
|
162
|
+
imax = i;
|
|
163
|
+
if (scaling[imax][j] < 0) {
|
|
164
|
+
for (const row of scalingNorm)
|
|
165
|
+
row[j] = -row[j];
|
|
166
|
+
for (const row of scaling)
|
|
167
|
+
row[j] = -row[j];
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const originalMeans = means.map((r) => r.map((v, j) => (origin[j] + v * spread[j]) * scale[j]));
|
|
171
|
+
const covInv = metric.inverse.map((r) => r.map((v) => v * (n - g)));
|
|
172
|
+
const names = xNames.length === p ? xNames : Array.from({ length: p }, (_, i) => `x${i + 1}`);
|
|
173
|
+
return {
|
|
174
|
+
prior, counts, means: { rows: levels, cols: names, values: originalMeans },
|
|
175
|
+
scaling: { rows: names, cols: keepRoots.map((_, i) => `LD${i + 1}`), values: scaling },
|
|
176
|
+
svd: (() => { const v = keepRoots.map((i) => Math.sqrt(Math.max(0, be.values[i]) * (n - g) / Math.max(1, g - 1))); return v; })(),
|
|
177
|
+
N: n, lev: declared ?? levels, warnings, _means: means, _activeLev: levels, _center: center, _scaling: scalingNorm, _covInverse: covInv,
|
|
178
|
+
_scale: scale, _origin: origin, _spread: spread, _x: xs, _xNames: names, _tol: tol,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
export function lda(x, grouping, options = {}) {
|
|
182
|
+
checkOptions(options, LDA_KEYS, "lda"); // generated: option-keys.mjs
|
|
183
|
+
if (options.method !== undefined && options.method !== "moment")
|
|
184
|
+
throw new RangeError("only method = 'moment' is supported");
|
|
185
|
+
let values, groups, names;
|
|
186
|
+
if (typeof x === "string") {
|
|
187
|
+
const parsed = parseFormula(x);
|
|
188
|
+
const response = parsed.response;
|
|
189
|
+
if (!response || !Object.prototype.hasOwnProperty.call(grouping, response))
|
|
190
|
+
throw new RangeError("formula response must name a grouping column in data");
|
|
191
|
+
const tilde = x.indexOf("~");
|
|
192
|
+
if (tilde < 0)
|
|
193
|
+
throw new SyntaxError("invalid LDA formula");
|
|
194
|
+
const predictors = Object.keys(grouping).filter((name) => name !== response);
|
|
195
|
+
const rhsText = x.slice(tilde + 1).replace(/(^|[\s+*:/()-])\.(?=$|[\s+*:/()-])/g, (_match, prefix) => prefix + predictors.join(" + "));
|
|
196
|
+
const d = design(parseFormula(`~ ${rhsText}`), grouping, {
|
|
197
|
+
extraVariables: [response], dropUnusedLevels: false, ...(options.levels === undefined ? {} : { levels: options.levels }),
|
|
198
|
+
});
|
|
199
|
+
const offset = d.terms.intercept ? 1 : 0;
|
|
200
|
+
const values = d.x.map((row) => row.slice(offset));
|
|
201
|
+
const responseValues = Array.from(grouping[response]);
|
|
202
|
+
const groups = d.frame.rows.map((row) => responseValues[row]);
|
|
203
|
+
names = d.colNames.slice(offset);
|
|
204
|
+
const responseVariable = d.frame.variables[d.terms.variables.length];
|
|
205
|
+
const declared = options.groupLevels ?? (responseVariable?.kind === "factor" ? responseVariable.levels : undefined);
|
|
206
|
+
const fit = fitCore(values, groups, options, names, declared);
|
|
207
|
+
if (!options.CV)
|
|
208
|
+
return fit;
|
|
209
|
+
const classes = [];
|
|
210
|
+
const posterior = [];
|
|
211
|
+
const fullPrior = fit.prior;
|
|
212
|
+
for (let i = 0; i < values.length; i++) {
|
|
213
|
+
const xx = values.filter((_, j) => j !== i);
|
|
214
|
+
const gg = groups.filter((_, j) => j !== i);
|
|
215
|
+
const sub = fitCore(xx, gg, { ...options, prior: fullPrior, CV: false }, names, declared);
|
|
216
|
+
const pred = ldaPredict(sub, { newdata: [values[i]], prior: fullPrior });
|
|
217
|
+
classes.push(pred.class[0]);
|
|
218
|
+
posterior.push(pred.posterior.values[0]);
|
|
219
|
+
}
|
|
220
|
+
return { class: classes, posterior: { rows: null, cols: fit._activeLev, values: posterior } };
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
values = matrixInput(x);
|
|
224
|
+
groups = Array.from(grouping);
|
|
225
|
+
names = options.xNames ? Array.from(options.xNames) : Array.from({ length: values[0]?.length ?? 0 }, (_, i) => `x${i + 1}`);
|
|
226
|
+
if (values.some((row) => row.some((v) => !Number.isFinite(v)))) {
|
|
227
|
+
throw new RangeError("infinite, NA or NaN values in 'x'");
|
|
228
|
+
}
|
|
229
|
+
if (groups.some((v) => typeof v === "number" && Number.isNaN(v))) {
|
|
230
|
+
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const fit = fitCore(values, groups, options, names, options.groupLevels);
|
|
234
|
+
if (!options.CV)
|
|
235
|
+
return fit;
|
|
236
|
+
const classes = [];
|
|
237
|
+
const posterior = [];
|
|
238
|
+
const fullPrior = fit.prior;
|
|
239
|
+
for (let i = 0; i < values.length; i++) {
|
|
240
|
+
const xx = values.filter((_, j) => j !== i);
|
|
241
|
+
const gg = groups.filter((_, j) => j !== i);
|
|
242
|
+
const sub = fitCore(xx, gg, { ...options, prior: fullPrior, CV: false }, names, options.groupLevels);
|
|
243
|
+
const pred = ldaPredict(sub, { newdata: [values[i]], prior: fullPrior });
|
|
244
|
+
classes.push(pred.class[0]);
|
|
245
|
+
posterior.push(pred.posterior.values[0]);
|
|
246
|
+
}
|
|
247
|
+
return { class: classes, posterior: { rows: null, cols: fit.lev, values: posterior } };
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Plug-in prediction for a fitted {@link lda} model. Equivalent to R's `predict.lda()`. The plug-in method only.
|
|
251
|
+
*
|
|
252
|
+
* @param fit A fitted LDA model.
|
|
253
|
+
* @param options New observations, prior override, and number of discriminant scores.
|
|
254
|
+
* @category Multivariate analysis
|
|
255
|
+
*/
|
|
256
|
+
export function ldaPredict(fit, options = {}) {
|
|
257
|
+
checkOptions(options, LDA_PREDICT_KEYS, "ldaPredict"); // generated: option-keys.mjs
|
|
258
|
+
if (options.method !== undefined && options.method !== "plug-in")
|
|
259
|
+
throw new RangeError("only method = 'plug-in' is supported");
|
|
260
|
+
const raw = options.newdata === undefined ? undefined : matrixInput(options.newdata);
|
|
261
|
+
const x = raw === undefined ? fit._x : raw.map((r) => r.map((v, j) => (v / fit._scale[j] - fit._origin[j]) / fit._spread[j]));
|
|
262
|
+
const p = fit._xNames.length;
|
|
263
|
+
if (x.some((r) => r.length !== p || r.some((v) => !Number.isFinite(v))))
|
|
264
|
+
throw new RangeError("newdata must be a finite matrix with the fitted number of columns");
|
|
265
|
+
const prior = normalisePrior(options.prior ?? fit.prior, fit.counts);
|
|
266
|
+
const center = Array.from({ length: p }, (_, j) => prior.reduce((s, w, i) => s + w * fit._means[i][j], 0));
|
|
267
|
+
const maxDim = fit._scaling[0]?.length ?? 0;
|
|
268
|
+
const dimen = options.dimen ?? maxDim;
|
|
269
|
+
if (!Number.isInteger(dimen) || dimen < 1 || dimen > maxDim)
|
|
270
|
+
throw new RangeError("dimen must be between 1 and the number of discriminant dimensions");
|
|
271
|
+
const fullScores = x.map((r) => Array.from({ length: dimen }, (_, k) => r.reduce((s, v, j) => s + (v - center[j]) * fit._scaling[j][k], 0)));
|
|
272
|
+
const meanScores = fit._means.map((mu) => Array.from({ length: dimen }, (_, k) => mu.reduce((s, v, j) => s + (v - center[j]) * fit._scaling[j][k], 0)));
|
|
273
|
+
const stableScores = (row) => {
|
|
274
|
+
const scale = row.reduce((m, v, j) => Math.max(m, Math.abs(v - center[j])), 0);
|
|
275
|
+
if (scale === 0)
|
|
276
|
+
return { values: new Array(dimen).fill(0), scale: 0 };
|
|
277
|
+
return {
|
|
278
|
+
scale,
|
|
279
|
+
values: Array.from({ length: dimen }, (_, k) => row.reduce((sum, v, j) => sum + ((v - center[j]) / scale) * fit._scaling[j][k], 0)),
|
|
280
|
+
};
|
|
281
|
+
};
|
|
282
|
+
const posteriorRows = fullScores.map((row, i) => {
|
|
283
|
+
const distances = fit._activeLev.map((_, g) => {
|
|
284
|
+
let distance = 0;
|
|
285
|
+
for (let k = 0; k < dimen; k++) {
|
|
286
|
+
const d = row[k] - meanScores[g][k];
|
|
287
|
+
distance += d * d;
|
|
288
|
+
}
|
|
289
|
+
return distance;
|
|
290
|
+
});
|
|
291
|
+
if (distances.every(Number.isFinite)) {
|
|
292
|
+
const logp = distances.map((distance, g) => Math.log(prior[g]) - 0.5 * distance);
|
|
293
|
+
const m = logp.reduce((a, b) => Math.max(a, b), -Infinity);
|
|
294
|
+
const ex = logp.map((v) => Math.exp(v - m));
|
|
295
|
+
const total = ex.reduce((a, b) => a + b, 0);
|
|
296
|
+
return { posterior: ex.map((v) => v / total), score: row };
|
|
297
|
+
}
|
|
298
|
+
// For extreme new observations, the squared score distances can overflow even though the input is finite.
|
|
299
|
+
// Cancel the common -||score||^2 / 2 term and form the discriminant log weights in scaled score coordinates.
|
|
300
|
+
const z = stableScores(x[i]);
|
|
301
|
+
const projections = meanScores.map((mu, g) => ({
|
|
302
|
+
linear: z.values.reduce((sum, v, k) => sum + v * mu[k], 0),
|
|
303
|
+
offset: Math.log(prior[g]) - 0.5 * mu.reduce((sum, v) => sum + v * v, 0),
|
|
304
|
+
}));
|
|
305
|
+
const maxLinear = projections.reduce((m, v) => Math.max(m, v.linear), -Infinity);
|
|
306
|
+
const logp = projections.map(({ linear, offset }) => {
|
|
307
|
+
const delta = z.scale * (linear - maxLinear);
|
|
308
|
+
return offset + (Number.isFinite(delta) ? delta : -Infinity);
|
|
309
|
+
});
|
|
310
|
+
const m = logp.reduce((a, b) => Math.max(a, b), -Infinity);
|
|
311
|
+
const ex = logp.map((v) => Math.exp(v - m));
|
|
312
|
+
const total = ex.reduce((a, b) => a + b, 0);
|
|
313
|
+
return {
|
|
314
|
+
posterior: ex.map((v) => v / total),
|
|
315
|
+
score: z.values.map((v) => v * z.scale),
|
|
316
|
+
};
|
|
317
|
+
});
|
|
318
|
+
const posterior = posteriorRows.map((r) => r.posterior);
|
|
319
|
+
const scores = posteriorRows.map((r) => r.score);
|
|
320
|
+
return {
|
|
321
|
+
class: posterior.map((r) => fit._activeLev[r.indexOf(Math.max(...r))]),
|
|
322
|
+
posterior: { rows: null, cols: fit._activeLev, values: posterior },
|
|
323
|
+
x: { rows: null, cols: Array.from({ length: dimen }, (_, i) => `LD${i + 1}`), values: scores },
|
|
324
|
+
};
|
|
325
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { DataFrame } from "../models/modelFrame.js";
|
|
2
|
+
/** Name of a multivariate test statistic.
|
|
3
|
+
* @category Multivariate analysis
|
|
4
|
+
*/
|
|
5
|
+
export type ManovaTestName = "Pillai" | "Wilks" | "Hotelling-Lawley" | "Roy";
|
|
6
|
+
/** Numerical options for MANOVA.
|
|
7
|
+
* @category Multivariate analysis
|
|
8
|
+
*/
|
|
9
|
+
export interface ManovaOptions {
|
|
10
|
+
/** Numerical tolerance used to determine matrix and residual ranks. Default 1e-7. */
|
|
11
|
+
tol?: number;
|
|
12
|
+
}
|
|
13
|
+
/** Options for MANOVA summary tables.
|
|
14
|
+
* @category Multivariate analysis
|
|
15
|
+
*/
|
|
16
|
+
export interface ManovaSummaryOptions {
|
|
17
|
+
/** Numerical tolerance used when recomputing the generalized roots. Default 1e-7. */
|
|
18
|
+
tol?: number;
|
|
19
|
+
/** Include the sequential intercept row when the fitted model has one. Default false. */
|
|
20
|
+
intercept?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** A labelled matrix table.
|
|
23
|
+
* @category Multivariate analysis
|
|
24
|
+
*/
|
|
25
|
+
export interface MatrixTable {
|
|
26
|
+
/** Row labels; a scalar string is used for a one-row table. */
|
|
27
|
+
rows: string[];
|
|
28
|
+
/** Column labels, or null for a matrix without named columns. */
|
|
29
|
+
cols: string[] | null;
|
|
30
|
+
/** Numeric table entries in row-major order. */
|
|
31
|
+
values: number[][];
|
|
32
|
+
}
|
|
33
|
+
/** A fitted sequential MANOVA model.
|
|
34
|
+
* @category Multivariate analysis
|
|
35
|
+
*/
|
|
36
|
+
export interface ManovaFit {
|
|
37
|
+
/** Formula used to fit the model. */
|
|
38
|
+
formula: string;
|
|
39
|
+
/** Names or expressions of the response variables in formula order. */
|
|
40
|
+
responseNames: string[];
|
|
41
|
+
/** Sequential model terms in formula order. */
|
|
42
|
+
termNames: string[];
|
|
43
|
+
/** Degrees of freedom contributed by each sequential term. */
|
|
44
|
+
termDf: number[];
|
|
45
|
+
/** Residual degrees of freedom. */
|
|
46
|
+
residualDf: number;
|
|
47
|
+
/** Residual sum-of-squares-and-cross-products matrix on the original response scales. */
|
|
48
|
+
residualSSP: number[][];
|
|
49
|
+
/** Sum-of-squares-and-cross-products matrix for each fitted term, keyed by term name. */
|
|
50
|
+
termSSP: Record<string, number[][]>;
|
|
51
|
+
/** Generalized roots for each fitted term, keyed by term name. */
|
|
52
|
+
termRoots: Record<string, number[]>;
|
|
53
|
+
/** Regression coefficient matrix, with terms in rows and responses in columns. */
|
|
54
|
+
coefficients: number[][];
|
|
55
|
+
/** Names of the coefficient rows. */
|
|
56
|
+
coefficientNames: string[];
|
|
57
|
+
/** Power-of-two scale factors used internally for each response. */
|
|
58
|
+
responseScales: number[];
|
|
59
|
+
/** Warnings produced while fitting the model. */
|
|
60
|
+
warnings: string[];
|
|
61
|
+
/** @internal Scaled residual SSP retained for numerically stable summary calculations. */
|
|
62
|
+
_residualSSPScaled: number[][];
|
|
63
|
+
/** @internal Scaled term SSP matrices retained for numerically stable summary calculations. */
|
|
64
|
+
_termSSPScaled: Record<string, number[][]>;
|
|
65
|
+
}
|
|
66
|
+
/** Four multivariate test tables and associated matrices.
|
|
67
|
+
* @category Multivariate analysis
|
|
68
|
+
*/
|
|
69
|
+
export interface ManovaSummary {
|
|
70
|
+
/** Pillai's trace test table. */
|
|
71
|
+
Pillai: MatrixTable;
|
|
72
|
+
/** Wilks' lambda test table. */
|
|
73
|
+
Wilks: MatrixTable;
|
|
74
|
+
/** Hotelling-Lawley trace test table. */
|
|
75
|
+
"Hotelling-Lawley": MatrixTable;
|
|
76
|
+
/** Roy's largest-root test table. */
|
|
77
|
+
Roy: MatrixTable;
|
|
78
|
+
/** Sum-of-squares-and-cross-products matrices, keyed by model term and residuals. */
|
|
79
|
+
SS: Record<string, MatrixTable>;
|
|
80
|
+
/** Generalized roots for each displayed model term. */
|
|
81
|
+
Eigenvalues: MatrixTable;
|
|
82
|
+
/** Regression coefficient matrix with labelled rows and response columns. */
|
|
83
|
+
coef: MatrixTable;
|
|
84
|
+
/** Roy largest-root F approximation is an upper bound. */
|
|
85
|
+
royFIsUpperBound: true;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Fit a multivariate analysis of variance model with sequential (Type I) terms. Equivalent to R's `stats::manova()`.
|
|
89
|
+
* The response is `cbind(y1, y2, ...)`; all four classical MANOVA statistics are available in {@link manovaSummary}.
|
|
90
|
+
*
|
|
91
|
+
* @param formula Multivariate formula, e.g. `"cbind(y1, y2, y3) ~ group + covariate"`.
|
|
92
|
+
* @param data Data frame.
|
|
93
|
+
* @param options Numerical rank tolerance.
|
|
94
|
+
*
|
|
95
|
+
* @category Multivariate analysis
|
|
96
|
+
*/
|
|
97
|
+
export declare function manova(formula: string, data: DataFrame, options?: ManovaOptions): ManovaFit;
|
|
98
|
+
/**
|
|
99
|
+
* Summary tables for all four MANOVA statistics, with optional sequential intercept row. Equivalent to R's `summary.manova()`.
|
|
100
|
+
*
|
|
101
|
+
* @param fit A result of {@link manova}.
|
|
102
|
+
* @param options Select a statistic or request the intercept row.
|
|
103
|
+
*
|
|
104
|
+
* @category Multivariate analysis
|
|
105
|
+
*/
|
|
106
|
+
export declare function manovaSummary(fit: ManovaFit, options?: ManovaSummaryOptions): ManovaSummary;
|