@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,409 @@
|
|
|
1
|
+
// Non-metric multidimensional scaling using Kruskal Stress-1 and R's fixed pair order.
|
|
2
|
+
import { cmdscale } from "./cmdscale.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 ISO_MDS_KEYS = ["k", "y", "maxit", "tol", "p"];
|
|
6
|
+
function readD(input) {
|
|
7
|
+
if (Array.isArray(input)) {
|
|
8
|
+
const n = input.length;
|
|
9
|
+
if (n < 2 || input.some((r) => r.length !== n))
|
|
10
|
+
throw new RangeError("dissimilarity matrix must be square");
|
|
11
|
+
const d = input.map((r) => Array.from(r, Number));
|
|
12
|
+
return { d, missing: d.some((r) => r.some((v) => !Number.isFinite(v))), labels: null };
|
|
13
|
+
}
|
|
14
|
+
if (typeof input !== "object" || input === null || !Array.isArray(input.values)) {
|
|
15
|
+
throw new TypeError("d must be a dist object or a square matrix");
|
|
16
|
+
}
|
|
17
|
+
const value = input;
|
|
18
|
+
const n = value.size;
|
|
19
|
+
if (!Number.isInteger(n) || n < 2 || value.values.length !== n * (n - 1) / 2)
|
|
20
|
+
throw new RangeError("invalid dissimilarity object");
|
|
21
|
+
const d = Array.from({ length: n }, () => new Array(n).fill(0));
|
|
22
|
+
let at = 0;
|
|
23
|
+
for (let j = 0; j < n - 1; j++)
|
|
24
|
+
for (let i = j + 1; i < n; i++) {
|
|
25
|
+
d[i][j] = value.values[at];
|
|
26
|
+
d[j][i] = value.values[at];
|
|
27
|
+
at++;
|
|
28
|
+
}
|
|
29
|
+
return { d, missing: d.some((r) => r.some((v) => !Number.isFinite(v))), labels: value.labels === null ? null : [...value.labels] };
|
|
30
|
+
}
|
|
31
|
+
function distance(a, b, p) {
|
|
32
|
+
let scale = 0, sum = 1;
|
|
33
|
+
for (let q = 0; q < a.length; q++) {
|
|
34
|
+
const value = Math.abs(a[q] - b[q]);
|
|
35
|
+
if (value === 0)
|
|
36
|
+
continue;
|
|
37
|
+
if (scale < value) {
|
|
38
|
+
sum = 1 + sum * (scale / value) ** p;
|
|
39
|
+
scale = value;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
sum += (value / scale) ** p;
|
|
43
|
+
}
|
|
44
|
+
return scale === 0 ? 0 : scale * sum ** (1 / p);
|
|
45
|
+
}
|
|
46
|
+
function center(y) {
|
|
47
|
+
const p = y[0].length;
|
|
48
|
+
for (let q = 0; q < p; q++) {
|
|
49
|
+
let m = 0;
|
|
50
|
+
for (const row of y)
|
|
51
|
+
m += row[q];
|
|
52
|
+
m /= y.length;
|
|
53
|
+
for (const row of y)
|
|
54
|
+
row[q] = row[q] - m;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function pairsFor(d, missing) {
|
|
58
|
+
const n = d.length;
|
|
59
|
+
const pairs = [];
|
|
60
|
+
for (let i = 0; i < n; i++)
|
|
61
|
+
for (let j = i + 1; j < n; j++) {
|
|
62
|
+
const delta = d[i][j];
|
|
63
|
+
if (!Number.isFinite(delta))
|
|
64
|
+
continue;
|
|
65
|
+
if (delta <= 0)
|
|
66
|
+
throw new RangeError("zero or negative distance between objects");
|
|
67
|
+
pairs.push({ i, j, delta, group: 0 });
|
|
68
|
+
}
|
|
69
|
+
void missing;
|
|
70
|
+
// R's as.vector(dist) visits the lower triangle column by column. Keep that
|
|
71
|
+
// order for equal dissimilarities; the same ordered pairs feed disparities
|
|
72
|
+
// and the gradient, so a different tie order changes the optimization path.
|
|
73
|
+
pairs.sort((a, b) => a.delta - b.delta || a.i - b.i || a.j - b.j);
|
|
74
|
+
let groups = 0;
|
|
75
|
+
for (const pair of pairs)
|
|
76
|
+
pair.group = groups++;
|
|
77
|
+
return { pairs, groups };
|
|
78
|
+
}
|
|
79
|
+
/** Pool-adjacent-violators regression in stable lower-triangle pair order. */
|
|
80
|
+
function disparitiesFor(pairs, groups, distances) {
|
|
81
|
+
// Each pair is an individual observation. Equal dissimilarities retain their
|
|
82
|
+
// lower-triangle order; they are not pooled into a single tie-block mean.
|
|
83
|
+
const starts = [], ends = [], values = [], weights = [];
|
|
84
|
+
for (let g = 0; g < groups; g++) {
|
|
85
|
+
starts.push(g);
|
|
86
|
+
ends.push(g);
|
|
87
|
+
values.push(distances[g]);
|
|
88
|
+
weights.push(1);
|
|
89
|
+
while (values.length > 1 && values[values.length - 2] > values[values.length - 1]) {
|
|
90
|
+
const last = values.length - 1;
|
|
91
|
+
const w = weights[last - 1] + weights[last];
|
|
92
|
+
values[last - 1] = (values[last - 1] * weights[last - 1] + values[last] * weights[last]) / w;
|
|
93
|
+
weights[last - 1] = w;
|
|
94
|
+
ends[last - 1] = ends[last];
|
|
95
|
+
starts.pop();
|
|
96
|
+
ends.pop();
|
|
97
|
+
values.pop();
|
|
98
|
+
weights.pop();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const fitted = new Array(groups);
|
|
102
|
+
for (let b = 0; b < values.length; b++)
|
|
103
|
+
for (let g = starts[b]; g <= ends[b]; g++)
|
|
104
|
+
fitted[g] = values[b];
|
|
105
|
+
return pairs.map((pair) => fitted[pair.group]);
|
|
106
|
+
}
|
|
107
|
+
function evaluate(y, pairs, groups, p) {
|
|
108
|
+
const distances = pairs.map((pair) => distance(y[pair.i], y[pair.j], p));
|
|
109
|
+
const disparities = disparitiesFor(pairs, groups.length, distances);
|
|
110
|
+
let numerator = 0, denominator = 0;
|
|
111
|
+
for (let i = 0; i < distances.length; i++) {
|
|
112
|
+
const d = distances[i], diff = d - disparities[i];
|
|
113
|
+
numerator += diff * diff;
|
|
114
|
+
denominator += d * d;
|
|
115
|
+
}
|
|
116
|
+
return { stress: denominator === 0 ? 0 : 100 * Math.sqrt(numerator / denominator), distances, disparities };
|
|
117
|
+
}
|
|
118
|
+
function gradient(y, pairs, current, p) {
|
|
119
|
+
const n = y.length, dim = y[0].length;
|
|
120
|
+
const out = Array.from({ length: n }, () => new Array(dim).fill(0));
|
|
121
|
+
let numerator = 0, denominator = 0;
|
|
122
|
+
for (let at = 0; at < current.distances.length; at++) {
|
|
123
|
+
const d = current.distances[at];
|
|
124
|
+
const diff = d - current.disparities[at];
|
|
125
|
+
numerator += diff * diff;
|
|
126
|
+
denominator += d * d;
|
|
127
|
+
}
|
|
128
|
+
if (numerator === 0 || denominator === 0)
|
|
129
|
+
return out;
|
|
130
|
+
const ratio = numerator / denominator;
|
|
131
|
+
const common = 100 / (Math.sqrt(ratio) * denominator);
|
|
132
|
+
for (let at = 0; at < pairs.length; at++) {
|
|
133
|
+
const pair = pairs[at], d = current.distances[at];
|
|
134
|
+
if (d === 0)
|
|
135
|
+
continue;
|
|
136
|
+
const factor = common * (d - current.disparities[at] - ratio * d) / (d ** (p - 1));
|
|
137
|
+
for (let q = 0; q < dim; q++) {
|
|
138
|
+
const diff = y[pair.i][q] - y[pair.j][q];
|
|
139
|
+
const v = diff === 0 ? 0 : factor * Math.sign(diff) * (Math.abs(diff) ** (p - 1));
|
|
140
|
+
out[pair.i][q] = out[pair.i][q] + v;
|
|
141
|
+
out[pair.j][q] = out[pair.j][q] - v;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
function flatten(y) {
|
|
147
|
+
const out = new Float64Array(y.length * y[0].length);
|
|
148
|
+
let at = 0;
|
|
149
|
+
for (const row of y)
|
|
150
|
+
for (const value of row)
|
|
151
|
+
out[at++] = value;
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
function unflatten(x, n, dim) {
|
|
155
|
+
return Array.from({ length: n }, (_, i) => Array.from({ length: dim }, (_, q) => x[i * dim + q]));
|
|
156
|
+
}
|
|
157
|
+
function identity(size, diagonal = 1) {
|
|
158
|
+
const out = new Float64Array(size * size);
|
|
159
|
+
for (let i = 0; i < size; i++)
|
|
160
|
+
out[i * size + i] = diagonal;
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
function multiply(matrix, vector, size) {
|
|
164
|
+
const out = new Float64Array(size);
|
|
165
|
+
for (let i = 0; i < size; i++) {
|
|
166
|
+
let value = 0, offset = i * size;
|
|
167
|
+
for (let j = 0; j < size; j++)
|
|
168
|
+
value += matrix[offset + j] * vector[j];
|
|
169
|
+
out[i] = value;
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
/** Full inverse-Hessian BFGS update, with a symmetric rank-two correction. */
|
|
174
|
+
function updateInverseHessian(h, step, change, size, resetDiagonal) {
|
|
175
|
+
let curvature = 0;
|
|
176
|
+
for (let i = 0; i < size; i++)
|
|
177
|
+
curvature += step[i] * change[i];
|
|
178
|
+
if (!(curvature > 0) || !Number.isFinite(curvature))
|
|
179
|
+
return identity(size, resetDiagonal);
|
|
180
|
+
const hy = multiply(h, change, size);
|
|
181
|
+
let yhy = 0;
|
|
182
|
+
for (let i = 0; i < size; i++)
|
|
183
|
+
yhy += change[i] * hy[i];
|
|
184
|
+
const coefficient = (curvature + yhy) / (curvature * curvature);
|
|
185
|
+
const out = new Float64Array(h.length);
|
|
186
|
+
for (let i = 0; i < size; i++) {
|
|
187
|
+
const row = i * size;
|
|
188
|
+
for (let j = 0; j < size; j++) {
|
|
189
|
+
out[row + j] = h[row + j] + coefficient * step[i] * step[j]
|
|
190
|
+
- (hy[i] * step[j] + step[i] * hy[j]) / curvature;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
function orient(y) {
|
|
196
|
+
const p = y[0].length;
|
|
197
|
+
for (let q = 0; q < p; q++) {
|
|
198
|
+
let at = 0, largest = -1;
|
|
199
|
+
for (let i = 0; i < y.length; i++)
|
|
200
|
+
if (Math.abs(y[i][q]) > largest) {
|
|
201
|
+
largest = Math.abs(y[i][q]);
|
|
202
|
+
at = i;
|
|
203
|
+
}
|
|
204
|
+
if (y[at][q] < 0)
|
|
205
|
+
for (const row of y)
|
|
206
|
+
row[q] = -row[q];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Kruskal's non-metric multidimensional scaling.
|
|
211
|
+
* Equivalent to R's `MASS::isoMDS()`.
|
|
212
|
+
* @category Multivariate analysis
|
|
213
|
+
*/
|
|
214
|
+
export function isoMDS(input, options = {}) {
|
|
215
|
+
checkOptions(options, ISO_MDS_KEYS, "isoMDS"); // generated: option-keys.mjs
|
|
216
|
+
const parsed = readD(input);
|
|
217
|
+
const n = parsed.d.length;
|
|
218
|
+
const k = options.k ?? 2;
|
|
219
|
+
if (!Number.isInteger(k) || k < 1 || k >= n)
|
|
220
|
+
throw new RangeError(`'k' must be in {1, 2, .. ${n - 1}}`);
|
|
221
|
+
const p = options.p ?? 2;
|
|
222
|
+
if (!Number.isFinite(p) || p <= 0)
|
|
223
|
+
throw new RangeError("'p' must be positive");
|
|
224
|
+
const maxit = options.maxit ?? 50;
|
|
225
|
+
const tol = options.tol ?? 1e-3;
|
|
226
|
+
if (!Number.isInteger(maxit) || maxit < 0)
|
|
227
|
+
throw new RangeError("'maxit' must be non-negative");
|
|
228
|
+
if (!Number.isFinite(tol) || tol <= 0)
|
|
229
|
+
throw new RangeError("'tol' must be positive");
|
|
230
|
+
if (parsed.missing && options.y === undefined)
|
|
231
|
+
throw new RangeError("an initial configuration must be supplied with NA/Infs in 'd'");
|
|
232
|
+
if (Array.isArray(input))
|
|
233
|
+
throw new TypeError("d must be a dist object");
|
|
234
|
+
const built = pairsFor(parsed.d, parsed.missing);
|
|
235
|
+
if (options.y !== undefined && (options.y.length !== n || options.y.some((r) => r.length !== k))) {
|
|
236
|
+
throw new RangeError("invalid initial configuration");
|
|
237
|
+
}
|
|
238
|
+
const condensed = [];
|
|
239
|
+
for (let j = 0; j < n - 1; j++)
|
|
240
|
+
for (let i = j + 1; i < n; i++)
|
|
241
|
+
condensed.push(parsed.d[i][j]);
|
|
242
|
+
let y = options.y === undefined
|
|
243
|
+
? cmdscale({ values: condensed, size: n, labels: null, method: null, diag: false, upper: false, warnings: [] }, { k }).points.values
|
|
244
|
+
: options.y.map((r) => Array.from(r));
|
|
245
|
+
if (y.length !== n || y.some((r) => r.length !== k))
|
|
246
|
+
throw new RangeError("invalid initial configuration");
|
|
247
|
+
if (y.some((r) => r.some((v) => !Number.isFinite(v))))
|
|
248
|
+
throw new RangeError("initial configuration must be finite");
|
|
249
|
+
center(y);
|
|
250
|
+
const groups = Array.from({ length: built.groups }, (_, i) => i);
|
|
251
|
+
let x = flatten(y);
|
|
252
|
+
let current = evaluate(y, built.pairs, groups, p);
|
|
253
|
+
const trace = [{ iteration: 0, stress: current.stress, converged: current.stress === 0 || maxit === 0 }];
|
|
254
|
+
const recordProgress = (iteration, stress) => {
|
|
255
|
+
const previous = trace[trace.length - 1];
|
|
256
|
+
// R's printed progress is to six decimals; repeated internal steps that
|
|
257
|
+
// print the same iteration and value are one observable progress record.
|
|
258
|
+
if (previous?.iteration === iteration && previous.stress.toFixed(6) === stress.toFixed(6))
|
|
259
|
+
return;
|
|
260
|
+
trace.push({ iteration, stress, converged: false });
|
|
261
|
+
};
|
|
262
|
+
let converged = current.stress === 0 || maxit === 0;
|
|
263
|
+
let lastIter = 0;
|
|
264
|
+
const size = x.length;
|
|
265
|
+
// R starts BFGS from the identity in the original coordinates (choice 13).
|
|
266
|
+
const resetDiagonal = 1;
|
|
267
|
+
let inverseHessian = identity(size, resetDiagonal);
|
|
268
|
+
// R performs one initial BFGS update for maxit=1 and maxit=2; thereafter
|
|
269
|
+
// each additional requested iteration contributes one update.
|
|
270
|
+
const steps = maxit === 0 ? 0 : maxit === 1 ? 1 : maxit - 1;
|
|
271
|
+
let failedSearchWasReset = false;
|
|
272
|
+
// Whether the inverse Hessian is the identity: at the start, after a non-descent direction, a failed line search or
|
|
273
|
+
// an update with a nonpositive curvature. R's extra step at the tol stop happens only when it is not (Claude,
|
|
274
|
+
// 2026-11-24: swiss_y stops at its 4th update without the extra step; swiss at tol 1e-3, 1e-4, 1e-8 takes it)
|
|
275
|
+
let hessianIsIdentity = true;
|
|
276
|
+
for (let stepIndex = 0; stepIndex < steps && !converged; stepIndex++) {
|
|
277
|
+
const iteration = maxit === 1 ? 1 : stepIndex + 2;
|
|
278
|
+
lastIter = iteration;
|
|
279
|
+
// A zero configuration distance leaves the gradient undefined. R then does not move: it returns the start, printing
|
|
280
|
+
// "stopped after 1 iterations" for maxit = 1 and "converged" otherwise, without a warning (swiss_y_k1: the start has
|
|
281
|
+
// two equal values; experiments/isomds111-diverge-more, Claude 2026-11-24)
|
|
282
|
+
if (current.distances.some((v) => v === 0)) {
|
|
283
|
+
converged = maxit > 1;
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
const grad = flatten(gradient(y, built.pairs, current, p));
|
|
287
|
+
let direction = multiply(inverseHessian, grad, size);
|
|
288
|
+
for (let i = 0; i < size; i++)
|
|
289
|
+
direction[i] = -direction[i];
|
|
290
|
+
let directionalDerivative = 0;
|
|
291
|
+
for (let i = 0; i < size; i++)
|
|
292
|
+
directionalDerivative += grad[i] * direction[i];
|
|
293
|
+
if (!(directionalDerivative < 0) || !Number.isFinite(directionalDerivative)) {
|
|
294
|
+
inverseHessian = identity(size, resetDiagonal);
|
|
295
|
+
hessianIsIdentity = true;
|
|
296
|
+
direction = grad.map((v) => -v);
|
|
297
|
+
directionalDerivative = 0;
|
|
298
|
+
for (let i = 0; i < size; i++)
|
|
299
|
+
directionalDerivative += grad[i] * direction[i];
|
|
300
|
+
}
|
|
301
|
+
if (!(directionalDerivative < 0)) {
|
|
302
|
+
converged = true;
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
const lineSearch = (searchDirection, slope) => {
|
|
306
|
+
let stepLength = 1;
|
|
307
|
+
for (let trial = 0; trial < 100; trial++) {
|
|
308
|
+
const candidateX = new Float64Array(size);
|
|
309
|
+
let changed = false;
|
|
310
|
+
for (let i = 0; i < size; i++) {
|
|
311
|
+
candidateX[i] = x[i] + stepLength * searchDirection[i];
|
|
312
|
+
if (candidateX[i] !== x[i])
|
|
313
|
+
changed = true;
|
|
314
|
+
}
|
|
315
|
+
if (!changed)
|
|
316
|
+
return null;
|
|
317
|
+
const candidate = unflatten(candidateX, n, k);
|
|
318
|
+
const next = evaluate(candidate, built.pairs, groups, p);
|
|
319
|
+
if (Number.isFinite(next.stress) && next.stress <= current.stress + 1e-4 * stepLength * slope) {
|
|
320
|
+
return { x: candidateX, y: candidate, evaluation: next };
|
|
321
|
+
}
|
|
322
|
+
stepLength *= 0.2;
|
|
323
|
+
}
|
|
324
|
+
return null;
|
|
325
|
+
};
|
|
326
|
+
let accepted = lineSearch(direction, directionalDerivative);
|
|
327
|
+
if (accepted === null) {
|
|
328
|
+
inverseHessian = identity(size, resetDiagonal);
|
|
329
|
+
hessianIsIdentity = true;
|
|
330
|
+
if (failedSearchWasReset) {
|
|
331
|
+
converged = true;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
failedSearchWasReset = true;
|
|
335
|
+
direction = grad.map((v) => -v);
|
|
336
|
+
directionalDerivative = 0;
|
|
337
|
+
for (let i = 0; i < size; i++)
|
|
338
|
+
directionalDerivative += grad[i] * direction[i];
|
|
339
|
+
accepted = lineSearch(direction, directionalDerivative);
|
|
340
|
+
if (accepted === null) {
|
|
341
|
+
converged = true;
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const previousStress = current.stress;
|
|
346
|
+
const nextGradient = flatten(gradient(accepted.y, built.pairs, accepted.evaluation, p));
|
|
347
|
+
const displacement = new Float64Array(size);
|
|
348
|
+
const gradientChange = new Float64Array(size);
|
|
349
|
+
for (let i = 0; i < size; i++) {
|
|
350
|
+
displacement[i] = accepted.x[i] - x[i];
|
|
351
|
+
gradientChange[i] = nextGradient[i] - grad[i];
|
|
352
|
+
}
|
|
353
|
+
const wasIdentity = hessianIsIdentity;
|
|
354
|
+
let curvature = 0;
|
|
355
|
+
for (let i = 0; i < size; i++)
|
|
356
|
+
curvature += displacement[i] * gradientChange[i];
|
|
357
|
+
hessianIsIdentity = !(curvature > 0) || !Number.isFinite(curvature);
|
|
358
|
+
inverseHessian = updateInverseHessian(inverseHessian, displacement, gradientChange, size, resetDiagonal);
|
|
359
|
+
x = accepted.x;
|
|
360
|
+
y = accepted.y;
|
|
361
|
+
current = accepted.evaluation;
|
|
362
|
+
failedSearchWasReset = false;
|
|
363
|
+
if (iteration % 5 === 0)
|
|
364
|
+
recordProgress(iteration, current.stress);
|
|
365
|
+
const relativeChange = (previousStress - current.stress) / Math.max(Math.abs(previousStress), Number.MIN_VALUE);
|
|
366
|
+
if (current.stress === 0) {
|
|
367
|
+
converged = true;
|
|
368
|
+
}
|
|
369
|
+
else if (relativeChange >= 0 && relativeChange < tol) {
|
|
370
|
+
// R's public results show a final extra step after a later (not the first)
|
|
371
|
+
// BFGS update. It uses the previous point's gradient again, from the new
|
|
372
|
+
// configuration, rather than the freshly evaluated gradient or -H*g.
|
|
373
|
+
// On swiss this gives 4.492668758998103 (R: 4.4926687589981045);
|
|
374
|
+
// at tol=1e-8 it gives 4.219287127030445 (R: 4.21928712703045).
|
|
375
|
+
if (!wasIdentity && !hessianIsIdentity) {
|
|
376
|
+
const finalDirection = grad.map((value) => -value);
|
|
377
|
+
let finalSlope = 0;
|
|
378
|
+
for (let i = 0; i < size; i++)
|
|
379
|
+
finalSlope += grad[i] * finalDirection[i];
|
|
380
|
+
const finalStep = lineSearch(finalDirection, finalSlope);
|
|
381
|
+
if (finalStep !== null) {
|
|
382
|
+
// R prints the extra final step with the preceding iteration number.
|
|
383
|
+
// If the threshold step is just after a five-iteration report, both
|
|
384
|
+
// the threshold point and this final point appear under that number.
|
|
385
|
+
const reportIteration = iteration % 5 === 0 ? iteration : iteration - 1;
|
|
386
|
+
if (iteration % 5 !== 0 && reportIteration % 5 === 0) {
|
|
387
|
+
recordProgress(reportIteration, current.stress);
|
|
388
|
+
}
|
|
389
|
+
x = finalStep.x;
|
|
390
|
+
y = finalStep.y;
|
|
391
|
+
current = finalStep.evaluation;
|
|
392
|
+
if (reportIteration % 5 === 0) {
|
|
393
|
+
recordProgress(reportIteration, current.stress);
|
|
394
|
+
}
|
|
395
|
+
lastIter = reportIteration;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// R prints no "iter" line for the iteration at which it stops without the extra step (swiss_y at 5)
|
|
399
|
+
if (!(!wasIdentity && !hessianIsIdentity) && iteration % 5 === 0 && trace.at(-1)?.iteration === iteration)
|
|
400
|
+
trace.pop();
|
|
401
|
+
converged = true;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (maxit > 0)
|
|
405
|
+
trace.push({ iteration: lastIter, stress: current.stress, converged });
|
|
406
|
+
orient(y);
|
|
407
|
+
return { points: { rows: parsed.labels, cols: null,
|
|
408
|
+
values: y.map((r) => [...r]) }, stress: current.stress, trace };
|
|
409
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** @category Multivariate analysis */
|
|
2
|
+
export interface KmeansOptions {
|
|
3
|
+
/** Clustering algorithm; a unique prefix is accepted. */
|
|
4
|
+
algorithm?: "Hartigan-Wong" | "Lloyd" | "Forgy" | "MacQueen" | string;
|
|
5
|
+
/** Maximum number of algorithm iterations (R's iter.max). */
|
|
6
|
+
iterMax?: number;
|
|
7
|
+
/** Number of random initial starts when centers is a count. */
|
|
8
|
+
nstart?: number;
|
|
9
|
+
}
|
|
10
|
+
/** @category Multivariate analysis */
|
|
11
|
+
export interface KmeansInputTable {
|
|
12
|
+
/** Optional observation names, one per row. */
|
|
13
|
+
rows: string[] | null;
|
|
14
|
+
/** Optional variable names, one per column. */
|
|
15
|
+
cols: string[] | null;
|
|
16
|
+
/** Numeric observations arranged by row. */
|
|
17
|
+
values: readonly (readonly number[])[];
|
|
18
|
+
}
|
|
19
|
+
/** @category Multivariate analysis */
|
|
20
|
+
export interface KmeansTable {
|
|
21
|
+
/** Cluster labels corresponding to the rows of the center matrix. */
|
|
22
|
+
rows: string[];
|
|
23
|
+
/** Variable names, or null when the input had no column names. */
|
|
24
|
+
cols: string[] | null;
|
|
25
|
+
/** Cluster centers arranged by row. */
|
|
26
|
+
values: number[][];
|
|
27
|
+
}
|
|
28
|
+
/** @category Multivariate analysis */
|
|
29
|
+
export interface KmeansFit {
|
|
30
|
+
/** 1-based cluster assignment for each observation. */
|
|
31
|
+
cluster: number[];
|
|
32
|
+
/** Observation names, present when the input supplied row names. */
|
|
33
|
+
names?: string[];
|
|
34
|
+
/** Matrix of final cluster centers. */
|
|
35
|
+
centers: KmeansTable;
|
|
36
|
+
/** Total sum of squares around the overall sample mean. */
|
|
37
|
+
totss: number;
|
|
38
|
+
/** Within-cluster sums of squares, one per cluster. */
|
|
39
|
+
withinss: number[];
|
|
40
|
+
/** Sum of all within-cluster sums of squares. */
|
|
41
|
+
totWithinss: number;
|
|
42
|
+
/** Between-cluster sum of squares (totss minus totWithinss). */
|
|
43
|
+
betweenss: number;
|
|
44
|
+
/** Number of observations assigned to each cluster. */
|
|
45
|
+
size: number[];
|
|
46
|
+
/** Number of iterations reported by the selected algorithm. */
|
|
47
|
+
iter: number;
|
|
48
|
+
/** Hartigan-Wong fault code, or null for algorithms without one. */
|
|
49
|
+
ifault: number | null;
|
|
50
|
+
/** Warnings produced during clustering. */
|
|
51
|
+
warnings: string[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* K-means clustering by the Hartigan-Wong, Lloyd, Forgy or MacQueen algorithm.
|
|
55
|
+
* Equivalent to R's `kmeans()`.
|
|
56
|
+
* @category Multivariate analysis
|
|
57
|
+
*/
|
|
58
|
+
export declare function kmeans(x: readonly unknown[] | readonly (readonly unknown[])[] | Record<string, ArrayLike<unknown>> | KmeansInputTable, centersInput: number | readonly number[] | readonly (readonly number[])[], options?: KmeansOptions): KmeansFit;
|