@numero-uno-jpn/rstats 1.9.0 → 1.11.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 +17 -0
- package/README.ja.md +6 -5
- package/README.md +6 -5
- package/dist/chunks/chunk-3K5KP3M2.js +2 -0
- package/dist/chunks/chunk-46DELNLN.js +2 -0
- package/dist/chunks/chunk-6VIOWV53.js +2 -0
- package/dist/chunks/{chunk-MT7XELUM.js → chunk-BA32XHDA.js} +2 -2
- package/dist/chunks/{chunk-DEAU6HWA.js → chunk-BGY7Y3P4.js} +1 -1
- package/dist/chunks/chunk-BKH5GQNA.js +2 -0
- package/dist/chunks/{chunk-BX47HGID.js → chunk-BNHMQU7V.js} +2 -2
- package/dist/chunks/chunk-BZBPPRSH.js +2 -0
- package/dist/chunks/{chunk-G3XMR7PA.js → chunk-DMT423BG.js} +2 -2
- package/dist/chunks/chunk-EV7ZQC6D.js +2 -0
- package/dist/chunks/chunk-HCHZ6M34.js +2 -0
- package/dist/chunks/chunk-HIPKYBZ3.js +2 -0
- package/dist/chunks/chunk-HPWRADJM.js +2 -0
- package/dist/chunks/chunk-IRO6MXW2.js +2 -0
- package/dist/chunks/{chunk-5C7XHQKP.js → chunk-JD6JHIVV.js} +1 -1
- package/dist/chunks/{chunk-UUZVQS4O.js → chunk-JFZOKMZA.js} +2 -2
- package/dist/chunks/chunk-JWMVP7XO.js +2 -0
- package/dist/chunks/chunk-KICTA3JY.js +3 -0
- package/dist/chunks/{chunk-2SO7Z3NV.js → chunk-M4SLTLOX.js} +2 -2
- package/dist/chunks/chunk-MJLK2RIQ.js +2 -0
- package/dist/chunks/{chunk-XCKQQVN7.js → chunk-NO675KX4.js} +2 -2
- package/dist/chunks/chunk-OG5FTIWF.js +2 -0
- package/dist/chunks/chunk-OWOBNS75.js +2 -0
- package/dist/chunks/chunk-P23KCD67.js +2 -0
- package/dist/chunks/chunk-PF6LEBKO.js +2 -0
- package/dist/chunks/chunk-QRUQEJJ5.js +2 -0
- package/dist/chunks/chunk-QY4OBLXK.js +2 -0
- package/dist/chunks/{chunk-RNK6EHEK.js → chunk-S5JZMHAW.js} +2 -2
- package/dist/chunks/chunk-SV6SLUVB.js +2 -0
- package/dist/chunks/{chunk-2COJEI44.js → chunk-TNU4SMV3.js} +2 -2
- package/dist/chunks/chunk-W27XXELU.js +2 -0
- package/dist/chunks/chunk-W2D6IDBY.js +2 -0
- package/dist/chunks/{chunk-MNIICUNF.js → chunk-WHKUEZQI.js} +2 -2
- package/dist/chunks/{chunk-ANGKH5D4.js → chunk-XKQSKVCL.js} +2 -2
- package/dist/chunks/chunk-XLBSUUWY.js +2 -0
- package/dist/chunks/{chunk-7F7PY35D.js → chunk-Y2SS3GX2.js} +2 -2
- package/dist/chunks/chunk-YPDFCKL4.js +2 -0
- package/dist/chunks/{chunk-I7E5J5PG.js → chunk-Z6UI6ON2.js} +2 -2
- package/dist/chunks/{chunk-4IHHZ3F4.js → chunk-ZW5OCUIY.js} +1 -1
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/multivariate.d.ts +8 -0
- package/dist/entries/multivariate.js +8 -0
- package/dist/entries/timeseries.d.ts +1 -0
- package/dist/entries/timeseries.js +2 -0
- package/dist/linalg/symmetricLeading.d.ts +8 -0
- package/dist/linalg/symmetricLeading.js +231 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/multivariate/ca.d.ts +120 -0
- package/dist/multivariate/ca.js +230 -0
- package/dist/multivariate/cmdscale.d.ts +40 -0
- package/dist/multivariate/cmdscale.js +171 -0
- package/dist/multivariate/dist.d.ts +63 -0
- package/dist/multivariate/dist.js +218 -0
- package/dist/multivariate/hclust.d.ts +58 -0
- package/dist/multivariate/hclust.js +264 -0
- package/dist/multivariate/isoMDS.d.ts +55 -0
- package/dist/multivariate/isoMDS.js +409 -0
- package/dist/multivariate/kmeans.d.ts +58 -0
- package/dist/multivariate/kmeans.js +392 -0
- package/dist/multivariate/mjca.d.ts +125 -0
- package/dist/multivariate/mjca.js +243 -0
- package/dist/multivariate/sammon.d.ts +66 -0
- package/dist/multivariate/sammon.js +231 -0
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +2 -2
- package/dist/rstats.js +1 -1
- package/dist/special.js +2 -2
- package/dist/tests.js +2 -2
- package/dist/timeseries/acf.d.ts +80 -0
- package/dist/timeseries/acf.js +314 -0
- package/dist/timeseries.js +2 -0
- package/llms.txt +53 -2
- package/package.json +6 -1
- package/dist/chunks/chunk-3J2HFC4A.js +0 -2
- package/dist/chunks/chunk-3LDUKHJZ.js +0 -3
- package/dist/chunks/chunk-4QWW62QN.js +0 -2
- package/dist/chunks/chunk-575F6RXJ.js +0 -2
- package/dist/chunks/chunk-7VPO2LTR.js +0 -2
- package/dist/chunks/chunk-CWS62KPG.js +0 -2
- package/dist/chunks/chunk-D3CWLSLS.js +0 -2
- package/dist/chunks/chunk-DRSA7ITF.js +0 -2
- package/dist/chunks/chunk-IEATFACS.js +0 -2
- package/dist/chunks/chunk-IXK3JA2R.js +0 -2
- package/dist/chunks/chunk-J3TS4PGN.js +0 -2
- package/dist/chunks/chunk-OGHJJKUR.js +0 -2
- package/dist/chunks/chunk-T3NUXZRL.js +0 -2
- package/dist/chunks/chunk-TKMNASCD.js +0 -2
- package/dist/chunks/chunk-UA66IB37.js +0 -2
- package/dist/chunks/chunk-VO2NIKVB.js +0 -2
- package/dist/chunks/chunk-WFE52E6F.js +0 -2
- package/dist/chunks/chunk-WOZEQS2I.js +0 -2
- package/dist/chunks/chunk-XNLZFKL5.js +0 -2
- package/dist/chunks/chunk-YFZBGUIT.js +0 -2
- package/dist/chunks/chunk-YK7Q6CNX.js +0 -2
- package/dist/chunks/chunk-Z47NJMYU.js +0 -2
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// K-means clustering: batch Lloyd/Forgy, online MacQueen, and point-transfer Hartigan-Wong.
|
|
2
|
+
import { sampleInt } from "../random/sample.js";
|
|
3
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
4
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
5
|
+
const KMEANS_KEYS = ["algorithm", "iterMax", "nstart"];
|
|
6
|
+
function readData(x) {
|
|
7
|
+
if (Array.isArray(x)) {
|
|
8
|
+
if (x.length === 0)
|
|
9
|
+
throw new RangeError("x must be a non-empty numeric matrix");
|
|
10
|
+
if (!Array.isArray(x[0]))
|
|
11
|
+
return { rows: x.map((v) => [Number(v)]), rowNames: null, colNames: null };
|
|
12
|
+
const raw = x;
|
|
13
|
+
const p = raw[0].length;
|
|
14
|
+
if (p === 0 || raw.some((r) => r.length !== p))
|
|
15
|
+
throw new RangeError("x must be a non-empty matrix with equal row lengths");
|
|
16
|
+
return { rows: raw.map((r) => r.map(Number)), rowNames: null, colNames: null };
|
|
17
|
+
}
|
|
18
|
+
if (typeof x === "object" && x !== null) {
|
|
19
|
+
const table = x;
|
|
20
|
+
if (Array.isArray(table.values)) {
|
|
21
|
+
const raw = table.values;
|
|
22
|
+
const p = raw[0]?.length ?? 0;
|
|
23
|
+
if (p === 0 || raw.some((r) => r.length !== p))
|
|
24
|
+
throw new RangeError("x must be a non-empty matrix with equal row lengths");
|
|
25
|
+
return { rows: raw.map((r) => r.map(Number)), rowNames: table.rows ?? null, colNames: table.cols ?? null };
|
|
26
|
+
}
|
|
27
|
+
const cols = Object.entries(x);
|
|
28
|
+
if (cols.length === 0)
|
|
29
|
+
throw new RangeError("x must have at least one column");
|
|
30
|
+
const n = cols[0][1].length;
|
|
31
|
+
if (cols.some(([, v]) => v.length !== n))
|
|
32
|
+
throw new RangeError("columns must have equal lengths");
|
|
33
|
+
return { rows: Array.from({ length: n }, (_, i) => cols.map(([, v]) => Number(v[i]))), rowNames: null,
|
|
34
|
+
colNames: cols.map(([name]) => name) };
|
|
35
|
+
}
|
|
36
|
+
throw new TypeError("x must be a numeric vector, matrix, or data frame");
|
|
37
|
+
}
|
|
38
|
+
function sameRow(a, b) {
|
|
39
|
+
return a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
|
|
40
|
+
}
|
|
41
|
+
function squared(a, b) {
|
|
42
|
+
let s = 0;
|
|
43
|
+
for (let j = 0; j < a.length; j++) {
|
|
44
|
+
const d = a[j] - b[j];
|
|
45
|
+
s += d * d;
|
|
46
|
+
}
|
|
47
|
+
return s;
|
|
48
|
+
}
|
|
49
|
+
function nearest(row, centers) {
|
|
50
|
+
let best = 0, value = squared(row, centers[0]);
|
|
51
|
+
for (let j = 1; j < centers.length; j++) {
|
|
52
|
+
const d = squared(row, centers[j]);
|
|
53
|
+
if (d < value) {
|
|
54
|
+
best = j;
|
|
55
|
+
value = d;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return best;
|
|
59
|
+
}
|
|
60
|
+
function means(rows, cluster, k, p) {
|
|
61
|
+
const centers = Array.from({ length: k }, () => new Array(p).fill(0));
|
|
62
|
+
const size = new Array(k).fill(0);
|
|
63
|
+
for (let i = 0; i < rows.length; i++) {
|
|
64
|
+
const g = cluster[i];
|
|
65
|
+
size[g] = size[g] + 1;
|
|
66
|
+
for (let j = 0; j < p; j++)
|
|
67
|
+
centers[g][j] = centers[g][j] + rows[i][j];
|
|
68
|
+
}
|
|
69
|
+
for (let g = 0; g < k; g++)
|
|
70
|
+
if (size[g] > 0) {
|
|
71
|
+
for (let j = 0; j < p; j++)
|
|
72
|
+
centers[g][j] = centers[g][j] / size[g];
|
|
73
|
+
}
|
|
74
|
+
return { centers, size };
|
|
75
|
+
}
|
|
76
|
+
function totalSS(rows, p) {
|
|
77
|
+
const center = new Array(p).fill(0);
|
|
78
|
+
for (const row of rows)
|
|
79
|
+
for (let j = 0; j < p; j++)
|
|
80
|
+
center[j] = center[j] + row[j];
|
|
81
|
+
for (let j = 0; j < p; j++)
|
|
82
|
+
center[j] = center[j] / rows.length;
|
|
83
|
+
let sum = 0;
|
|
84
|
+
for (const row of rows)
|
|
85
|
+
sum += squared(row, center);
|
|
86
|
+
return sum;
|
|
87
|
+
}
|
|
88
|
+
function fitStats(rows, cluster, k, colNames, rowNames, iter, ifault, warnings) {
|
|
89
|
+
const p = rows[0].length;
|
|
90
|
+
const { centers, size } = means(rows, cluster, k, p);
|
|
91
|
+
// R reports the center of an empty cluster as NaN (the mean of no rows; kmeans_empty_Lloyd)
|
|
92
|
+
for (let g = 0; g < k; g++)
|
|
93
|
+
if (size[g] === 0)
|
|
94
|
+
centers[g] = new Array(p).fill(NaN);
|
|
95
|
+
const withinss = new Array(k).fill(0);
|
|
96
|
+
for (let i = 0; i < rows.length; i++)
|
|
97
|
+
withinss[cluster[i]] += squared(rows[i], centers[cluster[i]]);
|
|
98
|
+
const totss = totalSS(rows, p);
|
|
99
|
+
const totWithinss = withinss.reduce((a, b) => a + b, 0);
|
|
100
|
+
const out = { cluster: cluster.map((v) => v + 1), centers: {
|
|
101
|
+
rows: Array.from({ length: k }, (_, i) => String(i + 1)), cols: colNames, values: centers,
|
|
102
|
+
}, totss, withinss, totWithinss, betweenss: totss - totWithinss, size, iter, ifault, warnings };
|
|
103
|
+
if (rowNames !== null)
|
|
104
|
+
out.names = [...rowNames];
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
function lloyd(rows, initial, iterMax) {
|
|
108
|
+
// Batch updates: assign every row to its nearest center, stop when no assignment changed, else move each nonempty
|
|
109
|
+
// center to its mean. R counts the assignment passes (the last one confirms convergence) and reports
|
|
110
|
+
// iter.max + 1 when it stops at the limit (kmeans_iter_Lloyd_1..5, kmeans_vector_Lloyd)
|
|
111
|
+
const k = initial.length;
|
|
112
|
+
const centers = initial.map((r) => [...r]);
|
|
113
|
+
let cluster = new Array(rows.length).fill(-1);
|
|
114
|
+
for (let iter = 1; iter <= iterMax; iter++) {
|
|
115
|
+
const next = rows.map((row) => nearest(row, centers));
|
|
116
|
+
const changed = next.some((v, i) => v !== cluster[i]);
|
|
117
|
+
cluster = next;
|
|
118
|
+
if (!changed)
|
|
119
|
+
return { cluster, iter, converged: true };
|
|
120
|
+
const stats = means(rows, cluster, k, rows[0].length);
|
|
121
|
+
for (let g = 0; g < k; g++)
|
|
122
|
+
if (stats.size[g] > 0)
|
|
123
|
+
centers[g] = stats.centers[g];
|
|
124
|
+
}
|
|
125
|
+
return { cluster, iter: iterMax + 1, converged: false };
|
|
126
|
+
}
|
|
127
|
+
function macqueen(rows, initial, iterMax) {
|
|
128
|
+
const k = initial.length, p = rows[0].length;
|
|
129
|
+
let cluster = rows.map((row) => nearest(row, initial));
|
|
130
|
+
const { centers, size } = means(rows, cluster, k, p);
|
|
131
|
+
// an empty cluster keeps its initial center (R: kmeans_empty_MacQueen), not the mean of no rows
|
|
132
|
+
for (let g = 0; g < k; g++)
|
|
133
|
+
if (size[g] === 0)
|
|
134
|
+
centers[g] = [...initial[g]];
|
|
135
|
+
let converged = false, iter = 0;
|
|
136
|
+
for (let pass = 0; pass < iterMax; pass++) {
|
|
137
|
+
let moved = false;
|
|
138
|
+
// MacQueen's sequential update: each transfer changes the two means and
|
|
139
|
+
// their counts immediately, so subsequent observations see the new fit.
|
|
140
|
+
for (let i = 0; i < rows.length; i++) {
|
|
141
|
+
const from = cluster[i];
|
|
142
|
+
if (size[from] <= 1)
|
|
143
|
+
continue;
|
|
144
|
+
const to = nearest(rows[i], centers);
|
|
145
|
+
if (to === from)
|
|
146
|
+
continue;
|
|
147
|
+
const row = rows[i];
|
|
148
|
+
const oldN = size[from], newN = size[to];
|
|
149
|
+
for (let j = 0; j < p; j++) {
|
|
150
|
+
centers[from][j] = (oldN * centers[from][j] - row[j]) / (oldN - 1);
|
|
151
|
+
centers[to][j] = (newN * centers[to][j] + row[j]) / (newN + 1);
|
|
152
|
+
}
|
|
153
|
+
size[from] = oldN - 1;
|
|
154
|
+
size[to] = newN + 1;
|
|
155
|
+
cluster[i] = to;
|
|
156
|
+
moved = true;
|
|
157
|
+
}
|
|
158
|
+
iter = pass + 1;
|
|
159
|
+
if (!moved) {
|
|
160
|
+
converged = true;
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { cluster, iter: converged ? iter : iterMax + 1, converged };
|
|
165
|
+
}
|
|
166
|
+
function hartiganWong(rows, initial, iterMax) {
|
|
167
|
+
// Hartigan & Wong (1979), from the paper's description (not from AS 136's code): an optimal-transfer stage over a
|
|
168
|
+
// live set of clusters, then a quick-transfer stage between each point's closest and second-closest clusters,
|
|
169
|
+
// repeated until an optimal-transfer pass moves nothing. iter counts the optimal-transfer passes; R reports
|
|
170
|
+
// iter.max + 1 at the limit (kmeans_iter_Hartigan-Wong_1..5)
|
|
171
|
+
const n = rows.length, k = initial.length, p = rows[0].length;
|
|
172
|
+
const ic1 = new Array(n), ic2 = new Array(n);
|
|
173
|
+
for (let i = 0; i < n; i++) {
|
|
174
|
+
let b1 = 0, b2 = 1, d1 = squared(rows[i], initial[0]), d2 = squared(rows[i], initial[1]);
|
|
175
|
+
if (d2 < d1) {
|
|
176
|
+
[b1, b2, d1, d2] = [1, 0, d2, d1];
|
|
177
|
+
}
|
|
178
|
+
for (let g = 2; g < k; g++) {
|
|
179
|
+
const d = squared(rows[i], initial[g]);
|
|
180
|
+
if (d < d1) {
|
|
181
|
+
b2 = b1;
|
|
182
|
+
d2 = d1;
|
|
183
|
+
b1 = g;
|
|
184
|
+
d1 = d;
|
|
185
|
+
}
|
|
186
|
+
else if (d < d2) {
|
|
187
|
+
b2 = g;
|
|
188
|
+
d2 = d;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
ic1[i] = b1;
|
|
192
|
+
ic2[i] = b2;
|
|
193
|
+
}
|
|
194
|
+
const { centers, size } = means(rows, ic1, k, p);
|
|
195
|
+
if (size.some((v) => v === 0))
|
|
196
|
+
throw new RangeError("empty cluster: try a better set of initial centers");
|
|
197
|
+
const move = (i, from, to) => {
|
|
198
|
+
const row = rows[i], oldN = size[from], newN = size[to];
|
|
199
|
+
for (let j = 0; j < p; j++) {
|
|
200
|
+
centers[from][j] = (oldN * centers[from][j] - row[j]) / (oldN - 1);
|
|
201
|
+
centers[to][j] = (newN * centers[to][j] + row[j]) / (newN + 1);
|
|
202
|
+
}
|
|
203
|
+
size[from] = oldN - 1;
|
|
204
|
+
size[to] = newN + 1;
|
|
205
|
+
ic1[i] = to;
|
|
206
|
+
ic2[i] = from;
|
|
207
|
+
};
|
|
208
|
+
const removeCost = (i, g) => size[g] / (size[g] - 1) * squared(rows[i], centers[g]);
|
|
209
|
+
const addCost = (i, g) => size[g] / (size[g] + 1) * squared(rows[i], centers[g]);
|
|
210
|
+
// live set: cluster g is live at optimal-transfer step t when it was updated within the last n steps
|
|
211
|
+
const updated = new Array(k).fill(0);
|
|
212
|
+
let t = 0;
|
|
213
|
+
for (let iter = 1; iter <= iterMax; iter++) {
|
|
214
|
+
let moved = false;
|
|
215
|
+
for (let i = 0; i < n; i++) {
|
|
216
|
+
t++;
|
|
217
|
+
const l1 = ic1[i];
|
|
218
|
+
if (size[l1] === 1)
|
|
219
|
+
continue;
|
|
220
|
+
const live = (g) => updated[g] >= t - n;
|
|
221
|
+
const l1Live = live(l1);
|
|
222
|
+
let best = ic2[i], bestCost = addCost(i, best);
|
|
223
|
+
for (let g = 0; g < k; g++) {
|
|
224
|
+
if (g === l1 || g === ic2[i] || !(l1Live || live(g)))
|
|
225
|
+
continue;
|
|
226
|
+
const c = addCost(i, g);
|
|
227
|
+
if (c < bestCost) {
|
|
228
|
+
best = g;
|
|
229
|
+
bestCost = c;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (bestCost < removeCost(i, l1)) {
|
|
233
|
+
move(i, l1, best);
|
|
234
|
+
updated[l1] = t;
|
|
235
|
+
updated[best] = t;
|
|
236
|
+
moved = true;
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
ic2[i] = best;
|
|
240
|
+
}
|
|
241
|
+
if (!moved)
|
|
242
|
+
return { cluster: ic1, iter, converged: true };
|
|
243
|
+
// quick transfer: until n consecutive steps move nothing
|
|
244
|
+
let quiet = 0;
|
|
245
|
+
for (let i = 0; quiet < n; i = (i + 1) % n) {
|
|
246
|
+
const l1 = ic1[i], l2 = ic2[i];
|
|
247
|
+
if (size[l1] > 1 && addCost(i, l2) < removeCost(i, l1)) {
|
|
248
|
+
move(i, l1, l2);
|
|
249
|
+
updated[l1] = t;
|
|
250
|
+
updated[l2] = t;
|
|
251
|
+
quiet = 0;
|
|
252
|
+
}
|
|
253
|
+
else
|
|
254
|
+
quiet++;
|
|
255
|
+
}
|
|
256
|
+
// with two clusters the quick-transfer stage has tried every transfer: no need to return to the optimal-transfer
|
|
257
|
+
// stage (Hartigan & Wong 1979; kmeans_equal_best_seed_*)
|
|
258
|
+
if (k === 2)
|
|
259
|
+
return { cluster: ic1, iter, converged: true };
|
|
260
|
+
}
|
|
261
|
+
return { cluster: ic1, iter: iterMax + 1, converged: false };
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* K-means clustering by the Hartigan-Wong, Lloyd, Forgy or MacQueen algorithm.
|
|
265
|
+
* Equivalent to R's `kmeans()`.
|
|
266
|
+
* @category Multivariate analysis
|
|
267
|
+
*/
|
|
268
|
+
export function kmeans(x, centersInput, options = {}) {
|
|
269
|
+
checkOptions(options, KMEANS_KEYS, "kmeans"); // generated: option-keys.mjs
|
|
270
|
+
const data = readData(x);
|
|
271
|
+
const rows = data.rows, n = rows.length, p = rows[0]?.length ?? 0;
|
|
272
|
+
if (n < 1 || p < 1 || rows.some((r) => r.length !== p))
|
|
273
|
+
throw new RangeError("x must be a non-empty matrix");
|
|
274
|
+
if (rows.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
275
|
+
throw new RangeError("NA/NaN/Inf in foreign function call (arg 1)");
|
|
276
|
+
const algorithms = ["Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"];
|
|
277
|
+
const requested = options.algorithm ?? "Hartigan-Wong";
|
|
278
|
+
const matches = algorithms.filter((v) => v.startsWith(requested));
|
|
279
|
+
if (matches.length !== 1)
|
|
280
|
+
throw new RangeError("invalid algorithm");
|
|
281
|
+
const algorithm = matches[0];
|
|
282
|
+
const iterMax = options.iterMax ?? 10;
|
|
283
|
+
if (!Number.isFinite(iterMax) || iterMax < 1)
|
|
284
|
+
throw new RangeError("'iter.max' must be positive");
|
|
285
|
+
const maxIterations = Math.trunc(iterMax);
|
|
286
|
+
const nstart = Math.max(1, Math.trunc(options.nstart ?? 1));
|
|
287
|
+
let initialSets = [];
|
|
288
|
+
if (typeof centersInput === "number") {
|
|
289
|
+
const k = Math.trunc(centersInput);
|
|
290
|
+
if (k < 1 || k > n)
|
|
291
|
+
throw new RangeError("centers must be between 1 and nrow(x)");
|
|
292
|
+
const distinct = new Set(rows.map((r) => JSON.stringify(r))).size;
|
|
293
|
+
if (k > distinct)
|
|
294
|
+
throw new RangeError("more cluster centers than distinct data points.");
|
|
295
|
+
// R's first start (kmeans_dup_start_seed_1..12, checked by the random state afterwards): k rows by
|
|
296
|
+
// sample.int(nrow, k); when those rows are not distinct, one draw of k rows from the distinct rows (in order of
|
|
297
|
+
// first appearance)
|
|
298
|
+
const unique = [];
|
|
299
|
+
const seen = new Set();
|
|
300
|
+
for (const r of rows) {
|
|
301
|
+
const key = JSON.stringify(r);
|
|
302
|
+
if (!seen.has(key)) {
|
|
303
|
+
seen.add(key);
|
|
304
|
+
unique.push(r);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const draw = () => {
|
|
308
|
+
let chosen = sampleInt(n, { size: k }).map((i) => [...rows[i]]);
|
|
309
|
+
if (new Set(chosen.map((r) => JSON.stringify(r))).size !== k) {
|
|
310
|
+
chosen = sampleInt(unique.length, { size: k }).map((i) => [...unique[i]]);
|
|
311
|
+
}
|
|
312
|
+
return chosen;
|
|
313
|
+
};
|
|
314
|
+
// with nstart >= 2 every start draws k of the distinct rows (kmeans_equal_best_dup_seed_1..8 and
|
|
315
|
+
// experiments/cluster110-nstart-rng.json: the random state after nstart = 2..5 for 8 seeds)
|
|
316
|
+
if (nstart === 1)
|
|
317
|
+
initialSets.push(draw());
|
|
318
|
+
else
|
|
319
|
+
for (let start = 0; start < nstart; start++) {
|
|
320
|
+
initialSets.push(sampleInt(unique.length, { size: k }).map((i) => [...unique[i]]));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
const initial = centersInput.length > 0 && typeof centersInput[0] === "number"
|
|
325
|
+
? centersInput.map((v) => [Number(v)])
|
|
326
|
+
: centersInput.map((r) => Array.from(r, Number));
|
|
327
|
+
if (initial.length < 1 || initial.some((r) => r.length !== p))
|
|
328
|
+
throw new RangeError("must have same number of columns in 'x' and 'centers'");
|
|
329
|
+
if (initial.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
330
|
+
throw new RangeError("initial centers must be finite");
|
|
331
|
+
for (let i = 0; i < initial.length; i++)
|
|
332
|
+
for (let j = 0; j < i; j++) {
|
|
333
|
+
if (sameRow(initial[i], initial[j]))
|
|
334
|
+
throw new RangeError("initial centers are not distinct");
|
|
335
|
+
}
|
|
336
|
+
initialSets = [initial];
|
|
337
|
+
}
|
|
338
|
+
const k = initialSets[0].length;
|
|
339
|
+
if (algorithm === "Hartigan-Wong" && k === n)
|
|
340
|
+
throw new RangeError("number of cluster centres must lie between 1 and nrow(x)");
|
|
341
|
+
// Normalize only extreme magnitudes before computing squared distances. This keeps assignments and
|
|
342
|
+
// center updates scale-equivariant when squaring would overflow or underflow; ordinary inputs keep
|
|
343
|
+
// the exact arithmetic path used by the R fixtures. Starts are selected above from the original rows,
|
|
344
|
+
// so this transformation does not alter the random stream or duplicate-row decisions.
|
|
345
|
+
let magnitude = 0;
|
|
346
|
+
for (const row of rows)
|
|
347
|
+
for (const value of row)
|
|
348
|
+
magnitude = Math.max(magnitude, Math.abs(value));
|
|
349
|
+
for (const initial of initialSets)
|
|
350
|
+
for (const row of initial)
|
|
351
|
+
for (const value of row)
|
|
352
|
+
magnitude = Math.max(magnitude, Math.abs(value));
|
|
353
|
+
const rescale = magnitude > 2 ** 512 || (magnitude > 0 && magnitude < 2 ** -512);
|
|
354
|
+
const workRows = rescale ? rows.map((row) => row.map((value) => value / magnitude)) : rows;
|
|
355
|
+
const workInitialSets = rescale ? initialSets.map((set) => set.map((row) => row.map((value) => value / magnitude))) : initialSets;
|
|
356
|
+
let best = null;
|
|
357
|
+
let bestW = Infinity;
|
|
358
|
+
let anyNotConverged = false;
|
|
359
|
+
for (const initial of workInitialSets) {
|
|
360
|
+
// One cluster: R does no iteration (iter 1, ifault NULL for every algorithm; kmeans_k1_*)
|
|
361
|
+
const result = k === 1 ? { cluster: new Array(n).fill(0), iter: 1, converged: true }
|
|
362
|
+
: algorithm === "Hartigan-Wong" ? hartiganWong(workRows, initial, maxIterations)
|
|
363
|
+
: algorithm === "MacQueen" ? macqueen(workRows, initial, maxIterations) : lloyd(workRows, initial, maxIterations);
|
|
364
|
+
const warnings = [];
|
|
365
|
+
const stats = means(workRows, result.cluster, k, p);
|
|
366
|
+
if (stats.size.some((v) => v === 0)) {
|
|
367
|
+
if (algorithm === "Hartigan-Wong")
|
|
368
|
+
throw new RangeError("empty cluster: try a better set of initial centers");
|
|
369
|
+
warnings.push("empty cluster: try a better set of initial centers", "empty cluster: try a better set of initial centers");
|
|
370
|
+
}
|
|
371
|
+
if (!result.converged)
|
|
372
|
+
anyNotConverged = true;
|
|
373
|
+
const fit = fitStats(workRows, result.cluster, k, data.colNames, data.rowNames, result.iter, algorithm === "Hartigan-Wong" && k > 1 ? (result.converged ? 0 : 2) : (result.converged ? null : 2), warnings);
|
|
374
|
+
if (fit.totWithinss < bestW) {
|
|
375
|
+
best = fit;
|
|
376
|
+
bestW = fit.totWithinss;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// Return centers and sums of squares on the caller's original scale.
|
|
380
|
+
if (rescale) {
|
|
381
|
+
const restoreSquare = (value) => value === 0 ? 0 : (value * magnitude) * magnitude;
|
|
382
|
+
best.centers.values = best.centers.values.map((row) => row.map((value) => value * magnitude));
|
|
383
|
+
best.totss = restoreSquare(best.totss);
|
|
384
|
+
best.withinss = best.withinss.map(restoreSquare);
|
|
385
|
+
best.totWithinss = restoreSquare(best.totWithinss);
|
|
386
|
+
best.betweenss = restoreSquare(best.betweenss);
|
|
387
|
+
}
|
|
388
|
+
// R warns once when any start stopped at iter.max, even when the kept start converged (kmeans_seed_nstart_lloyd)
|
|
389
|
+
if (anyNotConverged)
|
|
390
|
+
best.warnings.push(`did not converge in ${maxIterations} ${maxIterations === 1 ? "iteration" : "iterations"}`);
|
|
391
|
+
return best;
|
|
392
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/** A categorical data frame for multiple correspondence analysis.
|
|
2
|
+
* @category Multivariate analysis
|
|
3
|
+
*/
|
|
4
|
+
export interface MjcaInputTable {
|
|
5
|
+
/** Row labels, or null to use one-based row numbers. */
|
|
6
|
+
rows: string[] | null;
|
|
7
|
+
/** Names of the categorical variables. */
|
|
8
|
+
cols: string[];
|
|
9
|
+
/** Categorical values; null and non-string entries are omitted as incomplete rows. */
|
|
10
|
+
values: readonly (readonly (string | number | null)[])[];
|
|
11
|
+
}
|
|
12
|
+
/** Options for multiple correspondence analysis. Equivalent to R's ca::mjca().
|
|
13
|
+
* @category Multivariate analysis
|
|
14
|
+
*/
|
|
15
|
+
export interface MjcaOptions {
|
|
16
|
+
/** Analysis variant: adjusted (default), indicator or Burt; JCA is explicitly unsupported. */
|
|
17
|
+
lambda?: "adjusted" | "indicator" | "Burt" | "JCA";
|
|
18
|
+
/** Number of dimensions requested in the result. */
|
|
19
|
+
nd?: number;
|
|
20
|
+
/** One-based variable indices treated as supplementary. */
|
|
21
|
+
supcol?: number | readonly number[];
|
|
22
|
+
/** One-based category indices in variable/level order to include in the active analysis. */
|
|
23
|
+
subsetcat?: number | readonly number[];
|
|
24
|
+
/** Whether to include the indicator matrix in the result. */
|
|
25
|
+
reti?: boolean;
|
|
26
|
+
/** Separator used when constructing category labels. */
|
|
27
|
+
ps?: string;
|
|
28
|
+
}
|
|
29
|
+
/** A labelled matrix returned by multiple correspondence analysis.
|
|
30
|
+
* @category Multivariate analysis
|
|
31
|
+
*/
|
|
32
|
+
export interface MjcaMatrix {
|
|
33
|
+
/** Row labels, or null when unnamed. */
|
|
34
|
+
rows: string[] | null;
|
|
35
|
+
/** Column labels, or null when unnamed. */
|
|
36
|
+
cols: string[] | null;
|
|
37
|
+
/** Matrix values. */
|
|
38
|
+
values: (number | string)[][];
|
|
39
|
+
}
|
|
40
|
+
/** Variable names and observed category counts.
|
|
41
|
+
* @category Multivariate analysis
|
|
42
|
+
*/
|
|
43
|
+
export interface MjcaLevelsN {
|
|
44
|
+
/** Names of the categorical variables. */
|
|
45
|
+
names: string[];
|
|
46
|
+
/** Number of observed levels for each variable. */
|
|
47
|
+
values: number[];
|
|
48
|
+
}
|
|
49
|
+
/** Result of multiple correspondence analysis.
|
|
50
|
+
* @category Multivariate analysis
|
|
51
|
+
*/
|
|
52
|
+
export interface MjcaFit {
|
|
53
|
+
/** Singular values or adjusted eigenvalue roots, according to lambda. */
|
|
54
|
+
sv: number[];
|
|
55
|
+
/** Analysis variant used. */
|
|
56
|
+
lambda: "adjusted" | "indicator" | "Burt";
|
|
57
|
+
/** Percentage contributions to total inertia for the retained axes. */
|
|
58
|
+
inertiaE: number[];
|
|
59
|
+
/** Total inertia for the selected analysis variant. */
|
|
60
|
+
inertiaT: number;
|
|
61
|
+
/** Inertia adjustment metadata, or "NA" when not applicable. */
|
|
62
|
+
inertiaEt: number | "NA";
|
|
63
|
+
/** Category labels in analysis order. */
|
|
64
|
+
levelnames: string[];
|
|
65
|
+
/** Factor and level names for the complete category set. */
|
|
66
|
+
factors: MjcaMatrix;
|
|
67
|
+
/** Variable names and observed level counts. */
|
|
68
|
+
levelsN: MjcaLevelsN;
|
|
69
|
+
/** Number of dimensions requested. */
|
|
70
|
+
nd: number;
|
|
71
|
+
/** Maximum available number of dimensions. */
|
|
72
|
+
ndMax: number;
|
|
73
|
+
/** Names of the categorical variables. */
|
|
74
|
+
colnames: string[];
|
|
75
|
+
/** Category masses. */
|
|
76
|
+
colmass: number[];
|
|
77
|
+
/** Chi-square distances of categories from the centroid. */
|
|
78
|
+
coldist: number[];
|
|
79
|
+
/** Category contributions to inertia. */
|
|
80
|
+
colinertia: number[];
|
|
81
|
+
/** Standard category coordinates. */
|
|
82
|
+
colcoord: MjcaMatrix;
|
|
83
|
+
/** Principal category coordinates. */
|
|
84
|
+
colpcoord: MjcaMatrix;
|
|
85
|
+
/** Category contributions by axis. */
|
|
86
|
+
colctr: MjcaMatrix;
|
|
87
|
+
/** Squared correlations of categories with axes. */
|
|
88
|
+
colcor: MjcaMatrix;
|
|
89
|
+
/** One-based indices of supplementary categories, or "NA". */
|
|
90
|
+
colsup: number[] | "NA";
|
|
91
|
+
/** One-based selected category indices, or "NA" for the full set. */
|
|
92
|
+
subsetcol: number[] | "NA";
|
|
93
|
+
/** Burt cross-product table. */
|
|
94
|
+
Burt: MjcaMatrix;
|
|
95
|
+
/** Updated Burt table, or "NA" when not returned. */
|
|
96
|
+
BurtUpd: number[][] | "NA";
|
|
97
|
+
/** Within-variable sub-inertia table. */
|
|
98
|
+
subinertia: MjcaMatrix;
|
|
99
|
+
/** Row labels when row results are available. */
|
|
100
|
+
rownames?: string[] | null;
|
|
101
|
+
/** Row masses when row results are available. */
|
|
102
|
+
rowmass?: number[];
|
|
103
|
+
/** Row chi-square distances when row results are available. */
|
|
104
|
+
rowdist?: number[];
|
|
105
|
+
/** Row contributions to inertia when row results are available. */
|
|
106
|
+
rowinertia?: number[];
|
|
107
|
+
/** Standard row coordinates when available. */
|
|
108
|
+
rowcoord?: MjcaMatrix;
|
|
109
|
+
/** Principal row coordinates when available. */
|
|
110
|
+
rowpcoord?: MjcaMatrix;
|
|
111
|
+
/** Row contributions by axis, or "NA" for unsupported variants. */
|
|
112
|
+
rowctr?: MjcaMatrix | "NA";
|
|
113
|
+
/** Squared row correlations by axis, or "NA" for unsupported variants. */
|
|
114
|
+
rowcor?: MjcaMatrix | "NA";
|
|
115
|
+
/** Indicator matrix when reti is true, or "NA" otherwise. */
|
|
116
|
+
indmat?: MjcaMatrix | "NA";
|
|
117
|
+
/** Number of incomplete rows omitted from the analysis. */
|
|
118
|
+
omitted: number;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Computes multiple correspondence analysis for categorical columns.
|
|
122
|
+
* Equivalent to R's `ca::mjca()`.
|
|
123
|
+
* @category Multivariate analysis
|
|
124
|
+
*/
|
|
125
|
+
export declare function mjca(input: MjcaInputTable, options?: MjcaOptions): MjcaFit;
|