@numero-uno-jpn/rstats 1.8.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.ja.md +7 -6
  3. package/README.md +6 -5
  4. package/dist/chunks/{chunk-TUL6UFLQ.js → chunk-2COJEI44.js} +2 -2
  5. package/dist/chunks/{chunk-YT62DNDS.js → chunk-2SO7Z3NV.js} +2 -2
  6. package/dist/chunks/{chunk-73IRLCTF.js → chunk-3J2HFC4A.js} +2 -2
  7. package/dist/chunks/chunk-3LDUKHJZ.js +3 -0
  8. package/dist/chunks/{chunk-YD4U3QZ3.js → chunk-4IHHZ3F4.js} +1 -1
  9. package/dist/chunks/chunk-4QWW62QN.js +2 -0
  10. package/dist/chunks/chunk-575F6RXJ.js +2 -0
  11. package/dist/chunks/{chunk-IJST2ZGT.js → chunk-5C7XHQKP.js} +1 -1
  12. package/dist/chunks/{chunk-7ODUCEGX.js → chunk-7F7PY35D.js} +2 -2
  13. package/dist/chunks/{chunk-RWZ6ICYN.js → chunk-7VPO2LTR.js} +2 -2
  14. package/dist/chunks/{chunk-45HUI3M4.js → chunk-ANGKH5D4.js} +2 -2
  15. package/dist/chunks/{chunk-JXJDCQYE.js → chunk-BX47HGID.js} +2 -2
  16. package/dist/chunks/chunk-CWS62KPG.js +2 -0
  17. package/dist/chunks/chunk-D3CWLSLS.js +2 -0
  18. package/dist/chunks/{chunk-QQHF5T2A.js → chunk-DEAU6HWA.js} +1 -1
  19. package/dist/chunks/chunk-DRSA7ITF.js +2 -0
  20. package/dist/chunks/chunk-G3XMR7PA.js +2 -0
  21. package/dist/chunks/chunk-I7E5J5PG.js +3 -0
  22. package/dist/chunks/{chunk-2ZQ2TSZS.js → chunk-IEATFACS.js} +2 -2
  23. package/dist/chunks/{chunk-TYMC2D5I.js → chunk-IXK3JA2R.js} +2 -2
  24. package/dist/chunks/{chunk-LZB43TUL.js → chunk-J3TS4PGN.js} +2 -2
  25. package/dist/chunks/{chunk-V7ECXPWY.js → chunk-MNIICUNF.js} +2 -2
  26. package/dist/chunks/chunk-MT7XELUM.js +2 -0
  27. package/dist/chunks/{chunk-2X6PE6JF.js → chunk-OGHJJKUR.js} +2 -2
  28. package/dist/chunks/{chunk-52RWDNO6.js → chunk-RNK6EHEK.js} +2 -2
  29. package/dist/chunks/{chunk-D3LKPD4H.js → chunk-T3NUXZRL.js} +2 -2
  30. package/dist/chunks/chunk-TKMNASCD.js +2 -0
  31. package/dist/chunks/chunk-UA66IB37.js +2 -0
  32. package/dist/chunks/chunk-UUZVQS4O.js +2 -0
  33. package/dist/chunks/chunk-VO2NIKVB.js +2 -0
  34. package/dist/chunks/chunk-WFE52E6F.js +2 -0
  35. package/dist/chunks/{chunk-GRTQ7FYQ.js → chunk-WOZEQS2I.js} +2 -2
  36. package/dist/chunks/{chunk-DG2RTNIR.js → chunk-XCKQQVN7.js} +2 -2
  37. package/dist/chunks/chunk-XNLZFKL5.js +2 -0
  38. package/dist/chunks/chunk-YFZBGUIT.js +2 -0
  39. package/dist/chunks/{chunk-Y4KNH43T.js → chunk-YK7Q6CNX.js} +2 -2
  40. package/dist/chunks/{chunk-JIAFWEED.js → chunk-Z47NJMYU.js} +2 -2
  41. package/dist/descriptive.js +2 -2
  42. package/dist/distributions.js +2 -2
  43. package/dist/entries/multivariate.d.ts +3 -0
  44. package/dist/entries/multivariate.js +4 -0
  45. package/dist/entries/tests.d.ts +3 -1
  46. package/dist/entries/tests.js +3 -1
  47. package/dist/htest/grubbs.d.ts +68 -0
  48. package/dist/htest/grubbs.js +151 -0
  49. package/dist/htest/multipleComparisons.d.ts +21 -0
  50. package/dist/htest/multipleComparisons.js +47 -0
  51. package/dist/htest/rankTests.d.ts +35 -0
  52. package/dist/htest/rankTests.js +89 -1
  53. package/dist/internal/summary.js +8 -2
  54. package/dist/linalg.js +2 -2
  55. package/dist/mixed.js +2 -2
  56. package/dist/multivariate/cancor.d.ts +55 -0
  57. package/dist/multivariate/cancor.js +167 -0
  58. package/dist/multivariate/lda.d.ts +146 -0
  59. package/dist/multivariate/lda.js +325 -0
  60. package/dist/multivariate/manova.d.ts +106 -0
  61. package/dist/multivariate/manova.js +303 -0
  62. package/dist/multivariate.js +2 -0
  63. package/dist/numerics.js +2 -2
  64. package/dist/regression.js +2 -2
  65. package/dist/rstats.js +16 -16
  66. package/dist/special.js +2 -2
  67. package/dist/tests.js +15 -15
  68. package/llms.txt +2 -1
  69. package/package.json +6 -1
  70. package/dist/chunks/chunk-3DO726WZ.js +0 -3
  71. package/dist/chunks/chunk-53OM63EU.js +0 -2
  72. package/dist/chunks/chunk-ANZUXEMH.js +0 -3
  73. package/dist/chunks/chunk-BHQGMZTI.js +0 -2
  74. package/dist/chunks/chunk-HXYH5ZMB.js +0 -2
  75. package/dist/chunks/chunk-HYJ4MIZE.js +0 -2
  76. package/dist/chunks/chunk-MLNWWGGE.js +0 -2
  77. package/dist/chunks/chunk-TQM6KGKT.js +0 -2
  78. package/dist/chunks/chunk-VB6PVRSN.js +0 -2
@@ -0,0 +1,146 @@
1
+ import { type VectorOrMatrix } from "../linalg/matrix.js";
2
+ import { type GroupLabel } from "../htest/groups.js";
3
+ import type { DataFrame } from "../models/modelFrame.js";
4
+ /** Options for LDA fitting.
5
+ * @category Multivariate analysis
6
+ */
7
+ export interface LdaOptions {
8
+ /** Fitting method; only "moment" is supported. Default "moment". */
9
+ method?: "moment" | string;
10
+ /** Prior class probabilities, in class-level order. Defaults to observed class proportions. */
11
+ prior?: readonly number[];
12
+ /** Numerical tolerance for rank determination and within-class covariance calculations. Default 1e-4. */
13
+ tol?: number;
14
+ /** Return leave-one-out cross-validation predictions instead of a fitted model. Default false. */
15
+ CV?: boolean;
16
+ /** Names for predictor columns in matrix input. */
17
+ xNames?: readonly string[];
18
+ /** Declared class levels; unused levels remain in `lev` and produce warnings. */
19
+ groupLevels?: readonly GroupLabel[];
20
+ /** Explicit factor levels for formula variables. */
21
+ levels?: Record<string, readonly string[]>;
22
+ }
23
+ /** Options for LDA prediction.
24
+ * @category Multivariate analysis
25
+ */
26
+ export interface LdaPredictionOptions {
27
+ /** Prediction method; only "plug-in" is supported. Default "plug-in". */
28
+ method?: "plug-in" | string;
29
+ /** New predictor rows; omitted to predict the observations used to fit the model. */
30
+ newdata?: VectorOrMatrix;
31
+ /** Prior class probabilities for this prediction. Defaults to the fitted priors. */
32
+ prior?: readonly number[];
33
+ /** Number of discriminant score dimensions to return. Defaults to all available dimensions. */
34
+ dimen?: number;
35
+ }
36
+ /** A labelled LDA result matrix.
37
+ * @category Multivariate analysis
38
+ */
39
+ export interface LdaTable {
40
+ /** Row labels, or null when rows are observations without labels. */
41
+ rows: string[] | null;
42
+ /** Column labels, or null when columns are not named. */
43
+ cols: string[] | null;
44
+ /** Numeric matrix entries in row-major order. */
45
+ values: number[][];
46
+ }
47
+ /** A fitted linear discriminant model.
48
+ * @category Multivariate analysis
49
+ */
50
+ export interface LdaFit {
51
+ /** Prior class probabilities in the order of `lev`. */
52
+ prior: number[];
53
+ /** Number of training observations in each class. */
54
+ counts: number[];
55
+ /** Class means, with classes in rows and predictors in columns. */
56
+ means: LdaTable;
57
+ /** Metric-normalised discriminant directions, with predictors in rows and dimensions in columns. */
58
+ scaling: LdaTable;
59
+ /** Singular values associated with the discriminant dimensions. */
60
+ svd: number[];
61
+ /** Number of observations used to fit the model. */
62
+ N: number;
63
+ /** Class labels in prediction and prior order. */
64
+ lev: string[];
65
+ /** Warnings produced while fitting the model. */
66
+ warnings: string[];
67
+ /** @internal Unscaled class means retained for prediction. */
68
+ _means: number[][];
69
+ /** @internal Class labels with non-empty training observations. */
70
+ _activeLev: string[];
71
+ /** @internal Prior-weighted center of the predictor columns. */
72
+ _center: number[];
73
+ /** @internal Internal discriminant directions in scaled predictor coordinates. */
74
+ _scaling: number[][];
75
+ /** @internal Inverse pooled within-class covariance matrix. */
76
+ _covInverse: number[][];
77
+ /** @internal Predictor scale factors used internally. */
78
+ _scale: number[];
79
+ /** @internal Column origins in coordinates divided by `_scale`. */
80
+ _origin: number[];
81
+ /** @internal Column spread factors after removing a dominant offset. */
82
+ _spread: number[];
83
+ /** @internal Scaled training predictor matrix. */
84
+ _x: number[][];
85
+ /** @internal Predictor column names. */
86
+ _xNames: string[];
87
+ /** @internal Rank tolerance used to fit the model. */
88
+ _tol: number;
89
+ }
90
+ /** Plug-in prediction from an LDA fit.
91
+ * @category Multivariate analysis
92
+ */
93
+ export interface LdaPrediction {
94
+ /** Predicted class label for each observation. */
95
+ class: string[];
96
+ /** Posterior class probabilities, with classes in columns. */
97
+ posterior: LdaTable;
98
+ /** Discriminant scores for each observation. */
99
+ x: LdaTable;
100
+ }
101
+ /** Leave-one-out LDA predictions.
102
+ * @category Multivariate analysis
103
+ */
104
+ export interface LdaCVResult {
105
+ /** Leave-one-out predicted class label for each training observation. */
106
+ class: string[];
107
+ /** Leave-one-out posterior class probabilities, with classes in columns. */
108
+ posterior: LdaTable;
109
+ }
110
+ /**
111
+ * Linear discriminant analysis (moment method). Equivalent to R's `MASS::lda()`. The moment method only. Supports matrix/group and formula/data-frame inputs.
112
+ * Directions are metric-normalised and their signs are deterministic.
113
+ *
114
+ * @param x Predictor matrix.
115
+ * @param grouping Class labels.
116
+ * @param options Prior probabilities, tolerance, and leave-one-out CV.
117
+ * @category Multivariate analysis
118
+ */
119
+ export declare function lda(x: VectorOrMatrix, grouping: readonly GroupLabel[], options?: LdaOptions & {
120
+ CV?: false;
121
+ }): LdaFit;
122
+ /** Leave-one-out cross-validation result overload. */
123
+ export declare function lda(x: VectorOrMatrix, grouping: readonly GroupLabel[], options: LdaOptions & {
124
+ CV: true;
125
+ }): LdaCVResult;
126
+ /**
127
+ * Linear discriminant analysis from a formula, e.g. `"class ~ x1 + x2"` or `"class ~ ."`.
128
+ *
129
+ * @param formula Formula.
130
+ * @param data Data frame.
131
+ * @param options Prior probabilities, tolerance, and leave-one-out CV.
132
+ */
133
+ export declare function lda(formula: string, data: DataFrame, options?: LdaOptions & {
134
+ CV?: false;
135
+ }): LdaFit;
136
+ export declare function lda(formula: string, data: DataFrame, options: LdaOptions & {
137
+ CV: true;
138
+ }): LdaCVResult;
139
+ /**
140
+ * Plug-in prediction for a fitted {@link lda} model. Equivalent to R's `predict.lda()`. The plug-in method only.
141
+ *
142
+ * @param fit A fitted LDA model.
143
+ * @param options New observations, prior override, and number of discriminant scores.
144
+ * @category Multivariate analysis
145
+ */
146
+ export declare function ldaPredict(fit: LdaFit, options?: LdaPredictionOptions): LdaPrediction;
@@ -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;