@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.
Files changed (101) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.ja.md +6 -5
  3. package/README.md +6 -5
  4. package/dist/chunks/chunk-3K5KP3M2.js +2 -0
  5. package/dist/chunks/chunk-46DELNLN.js +2 -0
  6. package/dist/chunks/chunk-6VIOWV53.js +2 -0
  7. package/dist/chunks/{chunk-MT7XELUM.js → chunk-BA32XHDA.js} +2 -2
  8. package/dist/chunks/{chunk-DEAU6HWA.js → chunk-BGY7Y3P4.js} +1 -1
  9. package/dist/chunks/chunk-BKH5GQNA.js +2 -0
  10. package/dist/chunks/{chunk-BX47HGID.js → chunk-BNHMQU7V.js} +2 -2
  11. package/dist/chunks/chunk-BZBPPRSH.js +2 -0
  12. package/dist/chunks/{chunk-G3XMR7PA.js → chunk-DMT423BG.js} +2 -2
  13. package/dist/chunks/chunk-EV7ZQC6D.js +2 -0
  14. package/dist/chunks/chunk-HCHZ6M34.js +2 -0
  15. package/dist/chunks/chunk-HIPKYBZ3.js +2 -0
  16. package/dist/chunks/chunk-HPWRADJM.js +2 -0
  17. package/dist/chunks/chunk-IRO6MXW2.js +2 -0
  18. package/dist/chunks/{chunk-5C7XHQKP.js → chunk-JD6JHIVV.js} +1 -1
  19. package/dist/chunks/{chunk-UUZVQS4O.js → chunk-JFZOKMZA.js} +2 -2
  20. package/dist/chunks/chunk-JWMVP7XO.js +2 -0
  21. package/dist/chunks/chunk-KICTA3JY.js +3 -0
  22. package/dist/chunks/{chunk-2SO7Z3NV.js → chunk-M4SLTLOX.js} +2 -2
  23. package/dist/chunks/chunk-MJLK2RIQ.js +2 -0
  24. package/dist/chunks/{chunk-XCKQQVN7.js → chunk-NO675KX4.js} +2 -2
  25. package/dist/chunks/chunk-OG5FTIWF.js +2 -0
  26. package/dist/chunks/chunk-OWOBNS75.js +2 -0
  27. package/dist/chunks/chunk-P23KCD67.js +2 -0
  28. package/dist/chunks/chunk-PF6LEBKO.js +2 -0
  29. package/dist/chunks/chunk-QRUQEJJ5.js +2 -0
  30. package/dist/chunks/chunk-QY4OBLXK.js +2 -0
  31. package/dist/chunks/{chunk-RNK6EHEK.js → chunk-S5JZMHAW.js} +2 -2
  32. package/dist/chunks/chunk-SV6SLUVB.js +2 -0
  33. package/dist/chunks/{chunk-2COJEI44.js → chunk-TNU4SMV3.js} +2 -2
  34. package/dist/chunks/chunk-W27XXELU.js +2 -0
  35. package/dist/chunks/chunk-W2D6IDBY.js +2 -0
  36. package/dist/chunks/{chunk-MNIICUNF.js → chunk-WHKUEZQI.js} +2 -2
  37. package/dist/chunks/{chunk-ANGKH5D4.js → chunk-XKQSKVCL.js} +2 -2
  38. package/dist/chunks/chunk-XLBSUUWY.js +2 -0
  39. package/dist/chunks/{chunk-7F7PY35D.js → chunk-Y2SS3GX2.js} +2 -2
  40. package/dist/chunks/chunk-YPDFCKL4.js +2 -0
  41. package/dist/chunks/{chunk-I7E5J5PG.js → chunk-Z6UI6ON2.js} +2 -2
  42. package/dist/chunks/{chunk-4IHHZ3F4.js → chunk-ZW5OCUIY.js} +1 -1
  43. package/dist/descriptive.js +2 -2
  44. package/dist/distributions.js +2 -2
  45. package/dist/entries/multivariate.d.ts +8 -0
  46. package/dist/entries/multivariate.js +8 -0
  47. package/dist/entries/timeseries.d.ts +1 -0
  48. package/dist/entries/timeseries.js +2 -0
  49. package/dist/linalg/symmetricLeading.d.ts +8 -0
  50. package/dist/linalg/symmetricLeading.js +231 -0
  51. package/dist/linalg.js +2 -2
  52. package/dist/mixed.js +2 -2
  53. package/dist/multivariate/ca.d.ts +120 -0
  54. package/dist/multivariate/ca.js +230 -0
  55. package/dist/multivariate/cmdscale.d.ts +40 -0
  56. package/dist/multivariate/cmdscale.js +171 -0
  57. package/dist/multivariate/dist.d.ts +63 -0
  58. package/dist/multivariate/dist.js +218 -0
  59. package/dist/multivariate/hclust.d.ts +58 -0
  60. package/dist/multivariate/hclust.js +264 -0
  61. package/dist/multivariate/isoMDS.d.ts +55 -0
  62. package/dist/multivariate/isoMDS.js +409 -0
  63. package/dist/multivariate/kmeans.d.ts +58 -0
  64. package/dist/multivariate/kmeans.js +392 -0
  65. package/dist/multivariate/mjca.d.ts +125 -0
  66. package/dist/multivariate/mjca.js +243 -0
  67. package/dist/multivariate/sammon.d.ts +66 -0
  68. package/dist/multivariate/sammon.js +231 -0
  69. package/dist/multivariate.js +2 -2
  70. package/dist/numerics.js +2 -2
  71. package/dist/regression.js +2 -2
  72. package/dist/rstats.js +1 -1
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +2 -2
  75. package/dist/timeseries/acf.d.ts +80 -0
  76. package/dist/timeseries/acf.js +314 -0
  77. package/dist/timeseries.js +2 -0
  78. package/llms.txt +53 -2
  79. package/package.json +6 -1
  80. package/dist/chunks/chunk-3J2HFC4A.js +0 -2
  81. package/dist/chunks/chunk-3LDUKHJZ.js +0 -3
  82. package/dist/chunks/chunk-4QWW62QN.js +0 -2
  83. package/dist/chunks/chunk-575F6RXJ.js +0 -2
  84. package/dist/chunks/chunk-7VPO2LTR.js +0 -2
  85. package/dist/chunks/chunk-CWS62KPG.js +0 -2
  86. package/dist/chunks/chunk-D3CWLSLS.js +0 -2
  87. package/dist/chunks/chunk-DRSA7ITF.js +0 -2
  88. package/dist/chunks/chunk-IEATFACS.js +0 -2
  89. package/dist/chunks/chunk-IXK3JA2R.js +0 -2
  90. package/dist/chunks/chunk-J3TS4PGN.js +0 -2
  91. package/dist/chunks/chunk-OGHJJKUR.js +0 -2
  92. package/dist/chunks/chunk-T3NUXZRL.js +0 -2
  93. package/dist/chunks/chunk-TKMNASCD.js +0 -2
  94. package/dist/chunks/chunk-UA66IB37.js +0 -2
  95. package/dist/chunks/chunk-VO2NIKVB.js +0 -2
  96. package/dist/chunks/chunk-WFE52E6F.js +0 -2
  97. package/dist/chunks/chunk-WOZEQS2I.js +0 -2
  98. package/dist/chunks/chunk-XNLZFKL5.js +0 -2
  99. package/dist/chunks/chunk-YFZBGUIT.js +0 -2
  100. package/dist/chunks/chunk-YK7Q6CNX.js +0 -2
  101. package/dist/chunks/chunk-Z47NJMYU.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,55 @@
1
+ import type { DistResult } from "./dist.js";
2
+ /** Options for Kruskal non-metric multidimensional scaling. Equivalent to R's MASS::isoMDS().
3
+ * @category Multivariate analysis
4
+ */
5
+ export interface IsoMDSOptions {
6
+ /** Number of output dimensions. */
7
+ k?: number;
8
+ /** Initial configuration with one row per object and k columns. */
9
+ y?: readonly (readonly number[])[];
10
+ /** Maximum number of reported iterations. */
11
+ maxit?: number;
12
+ /** Relative stress-change tolerance for stopping. */
13
+ tol?: number;
14
+ /** Minkowski power used to measure distances between configuration points. */
15
+ p?: number;
16
+ }
17
+ /** One recorded isoMDS stress value.
18
+ * @category Multivariate analysis
19
+ */
20
+ export interface IsoMDSTrace {
21
+ /** Reported iteration number. */
22
+ iteration: number;
23
+ /** Kruskal Stress-1, expressed as a percentage. */
24
+ stress: number;
25
+ /** Whether the stopping condition has been met. */
26
+ converged: boolean;
27
+ }
28
+ /** A labelled coordinate matrix from isoMDS.
29
+ * @category Multivariate analysis
30
+ */
31
+ export interface IsoMDSMatrix {
32
+ /** Object labels, or null when unnamed. */
33
+ rows: string[] | null;
34
+ /** Coordinate labels, or null when unnamed. */
35
+ cols: string[] | null;
36
+ /** Object coordinates. */
37
+ values: number[][];
38
+ }
39
+ /** Result of non-metric multidimensional scaling.
40
+ * @category Multivariate analysis
41
+ */
42
+ export interface IsoMDSResult {
43
+ /** Final low-dimensional coordinates. */
44
+ points: IsoMDSMatrix;
45
+ /** Final Kruskal Stress-1, expressed as a percentage. */
46
+ stress: number;
47
+ /** Initial, periodic and final stress values. */
48
+ trace: IsoMDSTrace[];
49
+ }
50
+ /**
51
+ * Kruskal's non-metric multidimensional scaling.
52
+ * Equivalent to R's `MASS::isoMDS()`.
53
+ * @category Multivariate analysis
54
+ */
55
+ export declare function isoMDS(input: DistResult | readonly (readonly number[])[], options?: IsoMDSOptions): IsoMDSResult;