@numero-uno-jpn/rstats 1.9.0 → 1.10.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 +8 -0
- package/README.ja.md +3 -3
- package/README.md +3 -3
- package/dist/chunks/{chunk-CWS62KPG.js → chunk-3QUOB47N.js} +2 -2
- package/dist/chunks/{chunk-3J2HFC4A.js → chunk-5PVS6TF2.js} +2 -2
- package/dist/chunks/{chunk-G3XMR7PA.js → chunk-6BDTLUNM.js} +2 -2
- package/dist/chunks/{chunk-4IHHZ3F4.js → chunk-6U2ICRN3.js} +1 -1
- package/dist/chunks/{chunk-MT7XELUM.js → chunk-6Y7OKIIM.js} +2 -2
- package/dist/chunks/{chunk-TKMNASCD.js → chunk-AQ7H4RJH.js} +2 -2
- package/dist/chunks/chunk-CN5D6ITZ.js +3 -0
- package/dist/chunks/{chunk-MNIICUNF.js → chunk-DC2FP6ZH.js} +2 -2
- package/dist/chunks/{chunk-5C7XHQKP.js → chunk-EDHAQHB7.js} +1 -1
- package/dist/chunks/{chunk-3LDUKHJZ.js → chunk-F232C4SB.js} +2 -2
- package/dist/chunks/{chunk-7F7PY35D.js → chunk-F3WMBL5R.js} +2 -2
- package/dist/chunks/{chunk-DEAU6HWA.js → chunk-F5K2UXKW.js} +1 -1
- package/dist/chunks/{chunk-2SO7Z3NV.js → chunk-GYLFMAD6.js} +2 -2
- package/dist/chunks/{chunk-BX47HGID.js → chunk-IFFGJN5L.js} +2 -2
- package/dist/chunks/{chunk-2COJEI44.js → chunk-ISNGTKVZ.js} +2 -2
- package/dist/chunks/{chunk-WFE52E6F.js → chunk-JPQEOHZG.js} +2 -2
- package/dist/chunks/{chunk-IEATFACS.js → chunk-JRMISESC.js} +1 -1
- package/dist/chunks/{chunk-J3TS4PGN.js → chunk-K25FNCFH.js} +2 -2
- package/dist/chunks/{chunk-T3NUXZRL.js → chunk-KGDCQ2RV.js} +2 -2
- package/dist/chunks/{chunk-IXK3JA2R.js → chunk-LQWAHXHZ.js} +2 -2
- package/dist/chunks/chunk-MBQJWNPX.js +2 -0
- package/dist/chunks/{chunk-XNLZFKL5.js → chunk-MULNGWZY.js} +2 -2
- package/dist/chunks/{chunk-OGHJJKUR.js → chunk-MVIBJA2I.js} +2 -2
- package/dist/chunks/chunk-NAUAW5TO.js +2 -0
- package/dist/chunks/{chunk-7VPO2LTR.js → chunk-NMVFSSEZ.js} +2 -2
- package/dist/chunks/{chunk-ANGKH5D4.js → chunk-NNJGXB5K.js} +2 -2
- package/dist/chunks/{chunk-RNK6EHEK.js → chunk-OQFZKQVT.js} +2 -2
- package/dist/chunks/{chunk-UA66IB37.js → chunk-OXYMJNVJ.js} +2 -2
- package/dist/chunks/chunk-PJ73WRSA.js +2 -0
- package/dist/chunks/{chunk-4QWW62QN.js → chunk-R5BXUEH3.js} +2 -2
- package/dist/chunks/{chunk-VO2NIKVB.js → chunk-RPEFV4FR.js} +2 -2
- package/dist/chunks/{chunk-YFZBGUIT.js → chunk-T3XFVWOW.js} +2 -2
- package/dist/chunks/{chunk-WOZEQS2I.js → chunk-Y5M7NEJ5.js} +2 -2
- package/dist/chunks/{chunk-UUZVQS4O.js → chunk-Y7SXBQZY.js} +2 -2
- package/dist/chunks/{chunk-D3CWLSLS.js → chunk-YCBQQHCB.js} +2 -2
- package/dist/chunks/{chunk-Z47NJMYU.js → chunk-YGKM6PIJ.js} +2 -2
- package/dist/chunks/{chunk-XCKQQVN7.js → chunk-ZUHBIFAJ.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/multivariate.d.ts +4 -0
- package/dist/entries/multivariate.js +4 -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/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/kmeans.d.ts +58 -0
- package/dist/multivariate/kmeans.js +392 -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/llms.txt +3 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-575F6RXJ.js +0 -2
- package/dist/chunks/chunk-DRSA7ITF.js +0 -2
- package/dist/chunks/chunk-I7E5J5PG.js +0 -3
- package/dist/chunks/chunk-YK7Q6CNX.js +0 -2
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// Pairwise dissimilarities and conversion to condensed form.
|
|
2
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
3
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
4
|
+
const DIST_KEYS = ["method", "p", "diag", "upper", "labels"];
|
|
5
|
+
const AS_DIST_KEYS = ["labels", "diag", "upper"];
|
|
6
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
7
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
8
|
+
function methodName(method) {
|
|
9
|
+
const methods = ["euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski"];
|
|
10
|
+
const matches = methods.filter((name) => name.startsWith(method));
|
|
11
|
+
if (matches.length !== 1)
|
|
12
|
+
throw new RangeError("invalid distance method");
|
|
13
|
+
return matches[0];
|
|
14
|
+
}
|
|
15
|
+
function inputMatrix(input) {
|
|
16
|
+
if (Array.isArray(input)) {
|
|
17
|
+
if (input.length === 0)
|
|
18
|
+
throw new RangeError("x must be a non-empty matrix or vector");
|
|
19
|
+
if (!Array.isArray(input[0])) {
|
|
20
|
+
const rows = input.map((v) => [coerce(v)]);
|
|
21
|
+
return { rows, labels: null, warning: input.some((v) => typeof v === "string") };
|
|
22
|
+
}
|
|
23
|
+
const raw = input;
|
|
24
|
+
const width = raw[0].length;
|
|
25
|
+
if (raw.some((r) => r.length !== width))
|
|
26
|
+
throw new RangeError("inconsistent number of columns");
|
|
27
|
+
const warning = raw.some((r) => r.some((v) => typeof v === "string"));
|
|
28
|
+
return { rows: raw.map((r) => r.map(coerce)), labels: null, warning };
|
|
29
|
+
}
|
|
30
|
+
if (typeof input === "object" && input !== null) {
|
|
31
|
+
const columns = Object.entries(input);
|
|
32
|
+
if (columns.length === 0)
|
|
33
|
+
throw new RangeError("x must have at least one column");
|
|
34
|
+
const n = columns[0][1].length;
|
|
35
|
+
if (columns.some(([, v]) => v.length !== n))
|
|
36
|
+
throw new RangeError("columns must have equal lengths");
|
|
37
|
+
const rows = Array.from({ length: n }, (_, i) => columns.map(([, v]) => coerce(v[i])));
|
|
38
|
+
return { rows, labels: null, warning: columns.some(([, v]) => Array.from(v).some((x) => typeof x === "string")) };
|
|
39
|
+
}
|
|
40
|
+
throw new TypeError("x must be a numeric vector, matrix, or data frame");
|
|
41
|
+
}
|
|
42
|
+
function coerce(value) {
|
|
43
|
+
if (value === null || value === undefined)
|
|
44
|
+
return NaN;
|
|
45
|
+
if (typeof value === "boolean")
|
|
46
|
+
return value ? 1 : 0;
|
|
47
|
+
if (typeof value === "number")
|
|
48
|
+
return value;
|
|
49
|
+
if (typeof value === "string")
|
|
50
|
+
return value.trim() === "" ? 0 : Number(value);
|
|
51
|
+
return Number(value);
|
|
52
|
+
}
|
|
53
|
+
function scaledPowerSum(diffs, p) {
|
|
54
|
+
let scale = 0;
|
|
55
|
+
for (const d of diffs)
|
|
56
|
+
scale = Math.max(scale, Math.abs(d));
|
|
57
|
+
if (scale === 0)
|
|
58
|
+
return 0;
|
|
59
|
+
let sum = 0;
|
|
60
|
+
for (const d of diffs)
|
|
61
|
+
sum += (Math.abs(d) / scale) ** p;
|
|
62
|
+
return scale * sum ** (1 / p);
|
|
63
|
+
}
|
|
64
|
+
function pairDistance(a, b, method, p) {
|
|
65
|
+
const diffs = [];
|
|
66
|
+
const canberra = [];
|
|
67
|
+
let binaryUnion = 0;
|
|
68
|
+
let binaryDifferent = 0;
|
|
69
|
+
let binaryObserved = 0;
|
|
70
|
+
let binaryWarning = false;
|
|
71
|
+
for (let j = 0; j < a.length; j++) {
|
|
72
|
+
const x = a[j], y = b[j];
|
|
73
|
+
if (method === "binary") {
|
|
74
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
75
|
+
if (x === Infinity || x === -Infinity || y === Infinity || y === -Infinity)
|
|
76
|
+
binaryWarning = true;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
binaryObserved++;
|
|
80
|
+
const ax = x !== 0, by = y !== 0;
|
|
81
|
+
if (ax || by)
|
|
82
|
+
binaryUnion++;
|
|
83
|
+
if (ax !== by)
|
|
84
|
+
binaryDifferent++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (Number.isNaN(x) || Number.isNaN(y))
|
|
88
|
+
continue;
|
|
89
|
+
if (!Number.isFinite(x) && !Number.isFinite(y) && x === y)
|
|
90
|
+
continue;
|
|
91
|
+
if (method === "canberra") {
|
|
92
|
+
if (x === y && !Number.isFinite(x))
|
|
93
|
+
continue;
|
|
94
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
|
95
|
+
canberra.push(1);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const ax = Math.abs(x), ay = Math.abs(y);
|
|
99
|
+
const den = ax + ay;
|
|
100
|
+
if (den > 0) {
|
|
101
|
+
const numerator = Math.abs(x - y);
|
|
102
|
+
if (Number.isFinite(den) && Number.isFinite(numerator))
|
|
103
|
+
canberra.push(numerator / den);
|
|
104
|
+
else {
|
|
105
|
+
// Scale only the overflow case; ordinary values retain the fixture arithmetic.
|
|
106
|
+
const scale = Math.max(ax, ay);
|
|
107
|
+
canberra.push(Math.abs(x / scale - y / scale) / (ax / scale + ay / scale));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
diffs.push(Math.abs(x - y));
|
|
113
|
+
}
|
|
114
|
+
if (method === "binary")
|
|
115
|
+
return binaryObserved === 0 ? NaN : binaryUnion === 0 ? 0 : binaryDifferent / binaryUnion;
|
|
116
|
+
if (method === "canberra") {
|
|
117
|
+
if (canberra.length === 0)
|
|
118
|
+
return NaN;
|
|
119
|
+
return canberra.reduce((s, v) => s + v, 0) / (canberra.length / a.length);
|
|
120
|
+
}
|
|
121
|
+
if (diffs.length === 0)
|
|
122
|
+
return NaN;
|
|
123
|
+
if (diffs.some((d) => d === Infinity))
|
|
124
|
+
return Infinity;
|
|
125
|
+
if (method === "maximum") {
|
|
126
|
+
let max = 0;
|
|
127
|
+
for (const d of diffs)
|
|
128
|
+
max = Math.max(max, d);
|
|
129
|
+
return max;
|
|
130
|
+
}
|
|
131
|
+
if (method === "manhattan") {
|
|
132
|
+
let sum = 0;
|
|
133
|
+
for (const d of diffs)
|
|
134
|
+
sum += d;
|
|
135
|
+
const result = sum / (diffs.length / a.length);
|
|
136
|
+
if (Number.isFinite(result) || !diffs.some((d) => Number.isFinite(d)))
|
|
137
|
+
return result;
|
|
138
|
+
let scale = 0;
|
|
139
|
+
for (const d of diffs)
|
|
140
|
+
scale = Math.max(scale, d);
|
|
141
|
+
if (!Number.isFinite(scale))
|
|
142
|
+
return Infinity;
|
|
143
|
+
return scale * ((a.length / diffs.length) * diffs.reduce((s, d) => s + d / scale, 0));
|
|
144
|
+
}
|
|
145
|
+
let sum = 0;
|
|
146
|
+
for (const d of diffs)
|
|
147
|
+
sum += method === "minkowski" ? d ** p : d * d;
|
|
148
|
+
const power = method === "minkowski" ? p : 2;
|
|
149
|
+
const ordinary = method === "euclidean"
|
|
150
|
+
? Math.sqrt(sum / (diffs.length / a.length))
|
|
151
|
+
: (sum / (diffs.length / a.length)) ** (1 / power);
|
|
152
|
+
const nonzero = diffs.some((d) => d !== 0);
|
|
153
|
+
if (Number.isFinite(ordinary) && !(ordinary === 0 && nonzero) && !(sum > 0 && sum < MIN_NORMAL))
|
|
154
|
+
return ordinary;
|
|
155
|
+
const stable = scaledPowerSum(diffs, power) * (a.length / diffs.length) ** (1 / power);
|
|
156
|
+
return stable;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Compute pairwise dissimilarities in lower-triangle column order. Equivalent to R's `dist()`.
|
|
160
|
+
*
|
|
161
|
+
* @param x Numeric vector, matrix (rows are observations), or data-frame-like object of columns.
|
|
162
|
+
* @param options Distance method and display metadata.
|
|
163
|
+
* @category Multivariate analysis
|
|
164
|
+
*/
|
|
165
|
+
export function dist(x, options = {}) {
|
|
166
|
+
checkOptions(options, DIST_KEYS, "dist"); // generated: option-keys.mjs
|
|
167
|
+
const method = methodName(options.method ?? "euclidean");
|
|
168
|
+
const p = options.p ?? 2;
|
|
169
|
+
if (method === "minkowski" && !(Number.isFinite(p) && p > 0))
|
|
170
|
+
throw new RangeError("distance(): invalid p");
|
|
171
|
+
const input = inputMatrix(x);
|
|
172
|
+
const n = input.rows.length;
|
|
173
|
+
if (options.labels !== undefined && options.labels.length !== n)
|
|
174
|
+
throw new RangeError("labels must have one entry per row");
|
|
175
|
+
const labels = options.labels === undefined ? input.labels : [...options.labels];
|
|
176
|
+
const values = [];
|
|
177
|
+
const warnings = [];
|
|
178
|
+
for (let j = 0; j < n - 1; j++) {
|
|
179
|
+
for (let i = j + 1; i < n; i++) {
|
|
180
|
+
const a = input.rows[i], b = input.rows[j];
|
|
181
|
+
if (method === "binary" && a.some((v) => !Number.isFinite(v) && !Number.isNaN(v)) ||
|
|
182
|
+
method === "binary" && b.some((v) => !Number.isFinite(v) && !Number.isNaN(v))) {
|
|
183
|
+
warnings.push("treating non-finite values as NA");
|
|
184
|
+
}
|
|
185
|
+
values.push(pairDistance(a, b, method, p));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (input.warning)
|
|
189
|
+
warnings.unshift("NAs introduced by coercion");
|
|
190
|
+
return { values, size: n, labels, method, diag: options.diag ?? false, upper: options.upper ?? false, warnings };
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Convert a square matrix using only its lower triangle. Equivalent to R's `as.dist()`.
|
|
194
|
+
* An existing DistResult is returned unchanged.
|
|
195
|
+
* @category Multivariate analysis
|
|
196
|
+
*/
|
|
197
|
+
export function asDist(x, options = {}) {
|
|
198
|
+
checkOptions(options, AS_DIST_KEYS, "asDist"); // generated: option-keys.mjs
|
|
199
|
+
if (isDistObject(x))
|
|
200
|
+
return x;
|
|
201
|
+
const n = x.length;
|
|
202
|
+
if (n === 0 || x.some((r) => r.length !== n))
|
|
203
|
+
throw new RangeError("matrix must be square");
|
|
204
|
+
if (options.labels !== undefined && options.labels.length !== n)
|
|
205
|
+
throw new RangeError("labels must have one entry per row");
|
|
206
|
+
const values = [];
|
|
207
|
+
for (let j = 0; j < n - 1; j++)
|
|
208
|
+
for (let i = j + 1; i < n; i++)
|
|
209
|
+
values.push(Number(x[i][j]));
|
|
210
|
+
return { values, size: n, labels: options.labels === undefined ? null : [...options.labels], method: null,
|
|
211
|
+
diag: options.diag ?? false, upper: options.upper ?? false, warnings: [] };
|
|
212
|
+
}
|
|
213
|
+
function isDistObject(x) {
|
|
214
|
+
if (typeof x !== "object" || x === null || Array.isArray(x))
|
|
215
|
+
return false;
|
|
216
|
+
const v = x;
|
|
217
|
+
return Array.isArray(v.values) && typeof v.size === "number" && "method" in v;
|
|
218
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { DistResult } from "./dist.js";
|
|
2
|
+
/** @category Multivariate analysis */
|
|
3
|
+
export type HclustMethod = "ward.D" | "ward.D2" | "single" | "complete" | "average" | "mcquitty" | "median" | "centroid";
|
|
4
|
+
/** @category Multivariate analysis */
|
|
5
|
+
export interface HclustOptions {
|
|
6
|
+
/** Linkage method; a unique prefix and the alias ward are accepted. */
|
|
7
|
+
method?: HclustMethod | string;
|
|
8
|
+
/** Initial cluster sizes for the objects represented by the dissimilarities. */
|
|
9
|
+
members?: readonly number[];
|
|
10
|
+
}
|
|
11
|
+
/** @category Multivariate analysis */
|
|
12
|
+
export interface HclustFit {
|
|
13
|
+
/** (n - 1) by 2 merge matrix using negative observation and positive merge-row indices. */
|
|
14
|
+
merge: number[][];
|
|
15
|
+
/** Dissimilarity at each successive merge. */
|
|
16
|
+
height: number[];
|
|
17
|
+
/** Observation indices in left-to-right dendrogram order (1-based). */
|
|
18
|
+
order: number[];
|
|
19
|
+
/** Observation labels, or null when the input had no labels. */
|
|
20
|
+
labels: string[] | null;
|
|
21
|
+
/** Canonical linkage method used to construct the tree. */
|
|
22
|
+
method: HclustMethod;
|
|
23
|
+
/** Distance method attribute inherited from the input, or null. */
|
|
24
|
+
distMethod: string | null;
|
|
25
|
+
/** Informational messages produced while resolving the method. */
|
|
26
|
+
warnings: string[];
|
|
27
|
+
}
|
|
28
|
+
/** @category Multivariate analysis */
|
|
29
|
+
export interface CutreeOptions {
|
|
30
|
+
/** Requested number of clusters; a vector requests one partition per element. */
|
|
31
|
+
k?: number | readonly number[];
|
|
32
|
+
/** Merge-height cutoff; a vector requests one partition per element. */
|
|
33
|
+
h?: number | readonly number[];
|
|
34
|
+
}
|
|
35
|
+
/** @category Multivariate analysis */
|
|
36
|
+
export interface CutreeResult {
|
|
37
|
+
/** Cluster labels by observation, or a matrix with one column per requested cutoff. */
|
|
38
|
+
values: number[] | number[][];
|
|
39
|
+
/** Observation names for a single partition, or null when names are unavailable. */
|
|
40
|
+
names: string[] | null;
|
|
41
|
+
/** Observation names for the rows of a multi-cutoff result. */
|
|
42
|
+
rows?: string[] | null;
|
|
43
|
+
/** String labels for the requested k or h columns of a multi-cutoff result. */
|
|
44
|
+
columns?: string[];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Hierarchical agglomerative clustering of a dissimilarity structure by one of eight linkage methods.
|
|
48
|
+
* Equivalent to R's `hclust()`.
|
|
49
|
+
* @category Multivariate analysis
|
|
50
|
+
*/
|
|
51
|
+
export declare function hclust(d: DistResult, options?: HclustOptions): HclustFit;
|
|
52
|
+
/** Cut a hierarchical clustering tree by cluster count or merge height. */
|
|
53
|
+
/**
|
|
54
|
+
* Cuts a hierarchical clustering tree into groups, by number of groups or by height.
|
|
55
|
+
* Equivalent to R's `cutree()`.
|
|
56
|
+
* @category Multivariate analysis
|
|
57
|
+
*/
|
|
58
|
+
export declare function cutree(tree: HclustFit, options?: CutreeOptions): CutreeResult;
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
2
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
3
|
+
const HCLUST_KEYS = ["method", "members"];
|
|
4
|
+
const CUTREE_KEYS = ["k", "h"];
|
|
5
|
+
const METHODS = ["ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid"];
|
|
6
|
+
function resolveMethod(input) {
|
|
7
|
+
const raw = input ?? "complete";
|
|
8
|
+
if (raw === "ward")
|
|
9
|
+
return { method: "ward.D", warning: ['The "ward" method has been renamed to "ward.D"; note new "ward.D2"'] };
|
|
10
|
+
if (METHODS.includes(raw))
|
|
11
|
+
return { method: raw, warning: [] };
|
|
12
|
+
const matches = METHODS.filter((m) => m.startsWith(raw));
|
|
13
|
+
if (matches.length !== 1)
|
|
14
|
+
throw new RangeError("invalid clustering method");
|
|
15
|
+
return { method: matches[0], warning: [] };
|
|
16
|
+
}
|
|
17
|
+
function index(n, a, b) { return a * n + b; }
|
|
18
|
+
function updateDistance(method, dAB, dAC, dBC, a, b, c) {
|
|
19
|
+
const n = a + b + c;
|
|
20
|
+
if (method === "single")
|
|
21
|
+
return Math.min(dAC, dBC);
|
|
22
|
+
if (method === "complete")
|
|
23
|
+
return Math.max(dAC, dBC);
|
|
24
|
+
if (method === "average")
|
|
25
|
+
return (a * dAC + b * dBC) / (a + b);
|
|
26
|
+
if (method === "mcquitty")
|
|
27
|
+
return (dAC + dBC) / 2;
|
|
28
|
+
if (method === "ward.D")
|
|
29
|
+
return ((a + c) * dAC + (b + c) * dBC - c * dAB) / n;
|
|
30
|
+
if (method === "ward.D2") {
|
|
31
|
+
const scale = Math.max(Math.abs(dAB), Math.abs(dAC), Math.abs(dBC));
|
|
32
|
+
if (scale === 0)
|
|
33
|
+
return 0;
|
|
34
|
+
const ab = dAB / scale, ac = dAC / scale, bc = dBC / scale;
|
|
35
|
+
const v = ((a + c) * ac * ac + (b + c) * bc * bc - c * ab * ab) / n;
|
|
36
|
+
return Math.sqrt(Math.max(0, v)) * scale;
|
|
37
|
+
}
|
|
38
|
+
if (method === "median")
|
|
39
|
+
return (dAC + dBC) / 2 - dAB / 4;
|
|
40
|
+
const ab = a + b;
|
|
41
|
+
return (a * dAC + b * dBC) / ab - (a * b * dAB) / (ab * ab);
|
|
42
|
+
}
|
|
43
|
+
function encode(node, n) { return node < n ? -(node + 1) : node - n + 1; }
|
|
44
|
+
/**
|
|
45
|
+
* Hierarchical agglomerative clustering of a dissimilarity structure by one of eight linkage methods.
|
|
46
|
+
* Equivalent to R's `hclust()`.
|
|
47
|
+
* @category Multivariate analysis
|
|
48
|
+
*/
|
|
49
|
+
export function hclust(d, options = {}) {
|
|
50
|
+
checkOptions(options, HCLUST_KEYS, "hclust"); // generated: option-keys.mjs
|
|
51
|
+
if (!d || typeof d !== "object" || !Array.isArray(d.values) || !Number.isInteger(d.size)) {
|
|
52
|
+
throw new TypeError("d must be a dist object; use asDist() for a square matrix");
|
|
53
|
+
}
|
|
54
|
+
const n = d.size;
|
|
55
|
+
if (n < 2)
|
|
56
|
+
throw new RangeError("must have n >= 2 objects to cluster");
|
|
57
|
+
if (d.values.length !== n * (n - 1) / 2)
|
|
58
|
+
throw new RangeError("invalid dissimilarity object");
|
|
59
|
+
if (d.values.some((v) => !Number.isFinite(v)))
|
|
60
|
+
throw new RangeError("dissimilarities must be finite");
|
|
61
|
+
if (options.members !== undefined && (options.members.length !== n || options.members.some((v) => !Number.isFinite(v) || v <= 0))) {
|
|
62
|
+
throw new RangeError("invalid length or values of members");
|
|
63
|
+
}
|
|
64
|
+
const resolved = resolveMethod(options.method);
|
|
65
|
+
const method = resolved.method;
|
|
66
|
+
const capacity = n;
|
|
67
|
+
const distances = new Float64Array(capacity * capacity);
|
|
68
|
+
let p = 0;
|
|
69
|
+
for (let j = 0; j < n - 1; j++) {
|
|
70
|
+
for (let i = j + 1; i < n; i++) {
|
|
71
|
+
const v = d.values[p++];
|
|
72
|
+
distances[index(n, i, j)] = v;
|
|
73
|
+
distances[index(n, j, i)] = v;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const active = new Uint8Array(n);
|
|
77
|
+
active.fill(1);
|
|
78
|
+
const rank = new Int32Array(n);
|
|
79
|
+
const node = new Int32Array(n);
|
|
80
|
+
const sizes = new Float64Array(n);
|
|
81
|
+
const minLeaf = new Int32Array(n);
|
|
82
|
+
for (let i = 0; i < n; i++) {
|
|
83
|
+
rank[i] = i;
|
|
84
|
+
node[i] = i;
|
|
85
|
+
sizes[i] = options.members?.[i] ?? 1;
|
|
86
|
+
minLeaf[i] = i;
|
|
87
|
+
}
|
|
88
|
+
const merge = new Array(n - 1);
|
|
89
|
+
const height = new Array(n - 1);
|
|
90
|
+
const nnc = n > 200;
|
|
91
|
+
let chain = [];
|
|
92
|
+
for (let step = 0; step < n - 1; step++) {
|
|
93
|
+
let a = -1, b = -1, best = Infinity;
|
|
94
|
+
if (!nnc) {
|
|
95
|
+
let bestLo = Infinity, bestHi = Infinity;
|
|
96
|
+
for (let i = 0; i < n; i++)
|
|
97
|
+
if (active[i]) {
|
|
98
|
+
for (let j = i + 1; j < n; j++)
|
|
99
|
+
if (active[j]) {
|
|
100
|
+
const value = distances[index(n, i, j)];
|
|
101
|
+
const lo = Math.min(minLeaf[i], minLeaf[j]);
|
|
102
|
+
const hi = Math.max(minLeaf[i], minLeaf[j]);
|
|
103
|
+
if (value < best || (value === best && (lo < bestLo || (lo === bestLo && hi < bestHi)))) {
|
|
104
|
+
best = value;
|
|
105
|
+
a = i;
|
|
106
|
+
b = j;
|
|
107
|
+
bestLo = lo;
|
|
108
|
+
bestHi = hi;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
if (chain.length === 0) {
|
|
115
|
+
let first = -1, firstRank = Infinity;
|
|
116
|
+
for (let i = 0; i < n; i++)
|
|
117
|
+
if (active[i] && rank[i] < firstRank) {
|
|
118
|
+
first = i;
|
|
119
|
+
firstRank = rank[i];
|
|
120
|
+
}
|
|
121
|
+
chain.push(first);
|
|
122
|
+
}
|
|
123
|
+
while (true) {
|
|
124
|
+
const last = chain[chain.length - 1];
|
|
125
|
+
let nearest = -1, nearestDistance = Infinity, nearestLeaf = Infinity;
|
|
126
|
+
for (let j = 0; j < n; j++)
|
|
127
|
+
if (active[j] && j !== last) {
|
|
128
|
+
const value = distances[index(n, last, j)];
|
|
129
|
+
if (value < nearestDistance || (value === nearestDistance && minLeaf[j] < nearestLeaf)) {
|
|
130
|
+
nearest = j;
|
|
131
|
+
nearestDistance = value;
|
|
132
|
+
nearestLeaf = minLeaf[j];
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (chain.length > 1 && nearest === chain[chain.length - 2]) {
|
|
136
|
+
a = last;
|
|
137
|
+
b = nearest;
|
|
138
|
+
best = nearestDistance;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
chain.push(nearest);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (a < 0 || b < 0)
|
|
145
|
+
throw new Error("unable to find a finite pair of clusters");
|
|
146
|
+
if (rank[a] > rank[b])
|
|
147
|
+
[a, b] = [b, a];
|
|
148
|
+
const nodeA = node[a], nodeB = node[b];
|
|
149
|
+
merge[step] = [encode(nodeA, n), encode(nodeB, n)];
|
|
150
|
+
height[step] = best;
|
|
151
|
+
const sizeA = sizes[a], sizeB = sizes[b];
|
|
152
|
+
const newNode = n + step;
|
|
153
|
+
for (let c = 0; c < n; c++)
|
|
154
|
+
if (active[c] && c !== a && c !== b) {
|
|
155
|
+
const oldA = distances[index(n, a, c)];
|
|
156
|
+
const oldB = distances[index(n, b, c)];
|
|
157
|
+
const value = updateDistance(method, best, oldA, oldB, sizeA, sizeB, sizes[c]);
|
|
158
|
+
distances[index(n, a, c)] = value;
|
|
159
|
+
distances[index(n, c, a)] = value;
|
|
160
|
+
}
|
|
161
|
+
active[b] = 0;
|
|
162
|
+
node[a] = newNode;
|
|
163
|
+
sizes[a] = sizeA + sizeB;
|
|
164
|
+
minLeaf[a] = Math.min(minLeaf[a], minLeaf[b]);
|
|
165
|
+
rank[a] = n + step;
|
|
166
|
+
if (nnc) {
|
|
167
|
+
// The prefix still describes the same nearest-neighbor path: only the last two
|
|
168
|
+
// clusters were merged, so resume from the preceding cluster instead of
|
|
169
|
+
// rebuilding the path from its first active leaf after every merge.
|
|
170
|
+
chain.length -= 2;
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
chain = [];
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const order = [];
|
|
177
|
+
const left = new Int32Array(n * 2 - 1);
|
|
178
|
+
const right = new Int32Array(n * 2 - 1);
|
|
179
|
+
for (let i = 0; i < n - 1; i++) {
|
|
180
|
+
const l = merge[i][0], r = merge[i][1];
|
|
181
|
+
left[n + i] = l < 0 ? -l - 1 : n + l - 1;
|
|
182
|
+
right[n + i] = r < 0 ? -r - 1 : n + r - 1;
|
|
183
|
+
}
|
|
184
|
+
const stack = [2 * n - 2];
|
|
185
|
+
while (stack.length) {
|
|
186
|
+
const current = stack.pop();
|
|
187
|
+
if (current < n)
|
|
188
|
+
order.push(current + 1);
|
|
189
|
+
else {
|
|
190
|
+
stack.push(right[current]);
|
|
191
|
+
stack.push(left[current]);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return { merge, height, order, labels: d.labels === null ? null : [...d.labels], method,
|
|
195
|
+
distMethod: d.method, warnings: resolved.warning };
|
|
196
|
+
}
|
|
197
|
+
/** Cut a hierarchical clustering tree by cluster count or merge height. */
|
|
198
|
+
/**
|
|
199
|
+
* Cuts a hierarchical clustering tree into groups, by number of groups or by height.
|
|
200
|
+
* Equivalent to R's `cutree()`.
|
|
201
|
+
* @category Multivariate analysis
|
|
202
|
+
*/
|
|
203
|
+
export function cutree(tree, options = {}) {
|
|
204
|
+
checkOptions(options, CUTREE_KEYS, "cutree"); // generated: option-keys.mjs
|
|
205
|
+
const n = tree.order.length;
|
|
206
|
+
if (options.k === undefined && options.h === undefined)
|
|
207
|
+
throw new RangeError("either 'k' or 'h' must be specified");
|
|
208
|
+
const byK = options.k !== undefined;
|
|
209
|
+
const requested = byK ? options.k : options.h;
|
|
210
|
+
const values = Array.isArray(requested) ? [...requested] : [requested];
|
|
211
|
+
if (values.some((v) => !Number.isFinite(v)))
|
|
212
|
+
throw new RangeError("k and h must be finite");
|
|
213
|
+
if (!byK && tree.height.some((v, i) => i > 0 && v < tree.height[i - 1])) {
|
|
214
|
+
throw new RangeError("the 'height' component of 'tree' is not sorted (increasingly)");
|
|
215
|
+
}
|
|
216
|
+
const columns = values.map((v) => {
|
|
217
|
+
let merges = 0;
|
|
218
|
+
if (byK) {
|
|
219
|
+
const k = Math.trunc(v);
|
|
220
|
+
if (k < 1 || k > n)
|
|
221
|
+
throw new RangeError(`elements of 'k' must be between 1 and ${n}`);
|
|
222
|
+
merges = n - k;
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
while (merges < n - 1 && tree.height[merges] <= v)
|
|
226
|
+
merges++;
|
|
227
|
+
}
|
|
228
|
+
const parent = new Int32Array(2 * n - 1);
|
|
229
|
+
for (let i = 0; i < parent.length; i++)
|
|
230
|
+
parent[i] = i;
|
|
231
|
+
const find = (x) => {
|
|
232
|
+
let root = x;
|
|
233
|
+
while (parent[root] !== root)
|
|
234
|
+
root = parent[root];
|
|
235
|
+
while (parent[x] !== x) {
|
|
236
|
+
const next = parent[x];
|
|
237
|
+
parent[x] = root;
|
|
238
|
+
x = next;
|
|
239
|
+
}
|
|
240
|
+
return root;
|
|
241
|
+
};
|
|
242
|
+
for (let i = 0; i < merges; i++) {
|
|
243
|
+
const pair = tree.merge[i];
|
|
244
|
+
const root = n + i;
|
|
245
|
+
const l = pair[0] < 0 ? -pair[0] - 1 : n + pair[0] - 1;
|
|
246
|
+
const r = pair[1] < 0 ? -pair[1] - 1 : n + pair[1] - 1;
|
|
247
|
+
parent[find(l)] = root;
|
|
248
|
+
parent[find(r)] = root;
|
|
249
|
+
}
|
|
250
|
+
const labels = [];
|
|
251
|
+
const map = new Map();
|
|
252
|
+
for (let i = 0; i < n; i++) {
|
|
253
|
+
const root = find(i);
|
|
254
|
+
if (!map.has(root))
|
|
255
|
+
map.set(root, map.size + 1);
|
|
256
|
+
labels.push(map.get(root));
|
|
257
|
+
}
|
|
258
|
+
return labels;
|
|
259
|
+
});
|
|
260
|
+
const matrix = Array.isArray(requested);
|
|
261
|
+
return { values: matrix ? columns[0]?.map((_, i) => columns.map((col) => col[i])) ?? [] : columns[0] ?? [],
|
|
262
|
+
names: matrix || tree.labels === null ? null : [...tree.labels],
|
|
263
|
+
...(matrix ? { rows: tree.labels === null ? null : [...tree.labels], columns: values.map(String) } : {}) };
|
|
264
|
+
}
|
|
@@ -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;
|