@numero-uno-jpn/rstats 1.8.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.
Files changed (87) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.ja.md +7 -6
  3. package/README.md +6 -5
  4. package/dist/chunks/chunk-3QUOB47N.js +2 -0
  5. package/dist/chunks/{chunk-73IRLCTF.js → chunk-5PVS6TF2.js} +2 -2
  6. package/dist/chunks/chunk-6BDTLUNM.js +2 -0
  7. package/dist/chunks/{chunk-YD4U3QZ3.js → chunk-6U2ICRN3.js} +1 -1
  8. package/dist/chunks/chunk-6Y7OKIIM.js +2 -0
  9. package/dist/chunks/chunk-AQ7H4RJH.js +2 -0
  10. package/dist/chunks/{chunk-3DO726WZ.js → chunk-CN5D6ITZ.js} +2 -2
  11. package/dist/chunks/{chunk-V7ECXPWY.js → chunk-DC2FP6ZH.js} +2 -2
  12. package/dist/chunks/{chunk-IJST2ZGT.js → chunk-EDHAQHB7.js} +1 -1
  13. package/dist/chunks/chunk-F232C4SB.js +3 -0
  14. package/dist/chunks/{chunk-7ODUCEGX.js → chunk-F3WMBL5R.js} +2 -2
  15. package/dist/chunks/{chunk-QQHF5T2A.js → chunk-F5K2UXKW.js} +1 -1
  16. package/dist/chunks/{chunk-YT62DNDS.js → chunk-GYLFMAD6.js} +2 -2
  17. package/dist/chunks/{chunk-JXJDCQYE.js → chunk-IFFGJN5L.js} +2 -2
  18. package/dist/chunks/{chunk-TUL6UFLQ.js → chunk-ISNGTKVZ.js} +2 -2
  19. package/dist/chunks/chunk-JPQEOHZG.js +2 -0
  20. package/dist/chunks/{chunk-2ZQ2TSZS.js → chunk-JRMISESC.js} +2 -2
  21. package/dist/chunks/{chunk-LZB43TUL.js → chunk-K25FNCFH.js} +2 -2
  22. package/dist/chunks/{chunk-D3LKPD4H.js → chunk-KGDCQ2RV.js} +2 -2
  23. package/dist/chunks/{chunk-TYMC2D5I.js → chunk-LQWAHXHZ.js} +2 -2
  24. package/dist/chunks/{chunk-TQM6KGKT.js → chunk-MBQJWNPX.js} +2 -2
  25. package/dist/chunks/chunk-MULNGWZY.js +2 -0
  26. package/dist/chunks/{chunk-2X6PE6JF.js → chunk-MVIBJA2I.js} +2 -2
  27. package/dist/chunks/chunk-NAUAW5TO.js +2 -0
  28. package/dist/chunks/{chunk-RWZ6ICYN.js → chunk-NMVFSSEZ.js} +2 -2
  29. package/dist/chunks/{chunk-45HUI3M4.js → chunk-NNJGXB5K.js} +2 -2
  30. package/dist/chunks/{chunk-52RWDNO6.js → chunk-OQFZKQVT.js} +2 -2
  31. package/dist/chunks/chunk-OXYMJNVJ.js +2 -0
  32. package/dist/chunks/chunk-PJ73WRSA.js +2 -0
  33. package/dist/chunks/chunk-R5BXUEH3.js +2 -0
  34. package/dist/chunks/chunk-RPEFV4FR.js +2 -0
  35. package/dist/chunks/chunk-T3XFVWOW.js +2 -0
  36. package/dist/chunks/{chunk-GRTQ7FYQ.js → chunk-Y5M7NEJ5.js} +2 -2
  37. package/dist/chunks/chunk-Y7SXBQZY.js +2 -0
  38. package/dist/chunks/chunk-YCBQQHCB.js +2 -0
  39. package/dist/chunks/{chunk-JIAFWEED.js → chunk-YGKM6PIJ.js} +2 -2
  40. package/dist/chunks/{chunk-DG2RTNIR.js → chunk-ZUHBIFAJ.js} +2 -2
  41. package/dist/descriptive.js +2 -2
  42. package/dist/distributions.js +2 -2
  43. package/dist/entries/multivariate.d.ts +7 -0
  44. package/dist/entries/multivariate.js +8 -0
  45. package/dist/entries/tests.d.ts +3 -1
  46. package/dist/entries/tests.js +3 -1
  47. package/dist/htest/grubbs.d.ts +68 -0
  48. package/dist/htest/grubbs.js +151 -0
  49. package/dist/htest/multipleComparisons.d.ts +21 -0
  50. package/dist/htest/multipleComparisons.js +47 -0
  51. package/dist/htest/rankTests.d.ts +35 -0
  52. package/dist/htest/rankTests.js +89 -1
  53. package/dist/internal/summary.js +8 -2
  54. package/dist/linalg/symmetricLeading.d.ts +8 -0
  55. package/dist/linalg/symmetricLeading.js +231 -0
  56. package/dist/linalg.js +2 -2
  57. package/dist/mixed.js +2 -2
  58. package/dist/multivariate/cancor.d.ts +55 -0
  59. package/dist/multivariate/cancor.js +167 -0
  60. package/dist/multivariate/cmdscale.d.ts +40 -0
  61. package/dist/multivariate/cmdscale.js +171 -0
  62. package/dist/multivariate/dist.d.ts +63 -0
  63. package/dist/multivariate/dist.js +218 -0
  64. package/dist/multivariate/hclust.d.ts +58 -0
  65. package/dist/multivariate/hclust.js +264 -0
  66. package/dist/multivariate/kmeans.d.ts +58 -0
  67. package/dist/multivariate/kmeans.js +392 -0
  68. package/dist/multivariate/lda.d.ts +146 -0
  69. package/dist/multivariate/lda.js +325 -0
  70. package/dist/multivariate/manova.d.ts +106 -0
  71. package/dist/multivariate/manova.js +303 -0
  72. package/dist/multivariate.js +2 -0
  73. package/dist/numerics.js +2 -2
  74. package/dist/regression.js +2 -2
  75. package/dist/rstats.js +16 -16
  76. package/dist/special.js +2 -2
  77. package/dist/tests.js +15 -15
  78. package/llms.txt +4 -1
  79. package/package.json +6 -1
  80. package/dist/chunks/chunk-53OM63EU.js +0 -2
  81. package/dist/chunks/chunk-ANZUXEMH.js +0 -3
  82. package/dist/chunks/chunk-BHQGMZTI.js +0 -2
  83. package/dist/chunks/chunk-HXYH5ZMB.js +0 -2
  84. package/dist/chunks/chunk-HYJ4MIZE.js +0 -2
  85. package/dist/chunks/chunk-MLNWWGGE.js +0 -2
  86. package/dist/chunks/chunk-VB6PVRSN.js +0 -2
  87. package/dist/chunks/chunk-Y4KNH43T.js +0 -2
@@ -0,0 +1,171 @@
1
+ // Classical multidimensional scaling (Torgerson-Gower) with the Cailliez additive constant.
2
+ import { symmetricLeading } from "../linalg/symmetricLeading.js";
3
+ import { eigen } from "../linalg/eigen.js";
4
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
5
+ import { checkOptions } from "../internal/checkOptions.js";
6
+ const CMDSCALE_KEYS = ["k", "add", "xRet"];
7
+ function readDistances(input) {
8
+ if (Array.isArray(input)) {
9
+ const n = input.length;
10
+ if (n === 0 || input.some((r) => r.length !== n))
11
+ throw new RangeError("distance matrix must be square");
12
+ const matrix = input.map((r) => Array.from(r, Number));
13
+ if (matrix.some((r) => r.some((v) => !Number.isFinite(v))))
14
+ throw new RangeError("NA values not allowed in 'd'");
15
+ return { matrix, labels: null };
16
+ }
17
+ if (typeof input !== "object" || input === null || !Array.isArray(input.values)) {
18
+ throw new TypeError("d must be a dist object or a square matrix");
19
+ }
20
+ const rawValues = input.values;
21
+ if (rawValues.length > 0 && Array.isArray(rawValues[0])) {
22
+ const table = input;
23
+ const n = table.values.length;
24
+ if (n === 0 || table.values.some((r) => r.length !== n))
25
+ throw new RangeError("distance matrix must be square");
26
+ const matrix = table.values.map((r) => Array.from(r, Number));
27
+ if (matrix.some((r) => r.some((v) => !Number.isFinite(v))))
28
+ throw new RangeError("NA values not allowed in 'd'");
29
+ return { matrix, labels: table.rows === null ? null : [...table.rows] };
30
+ }
31
+ const d = input;
32
+ const n = d.size;
33
+ if (!Number.isInteger(n) || n < 1 || d.values.length !== n * (n - 1) / 2)
34
+ throw new RangeError("invalid dissimilarity object");
35
+ if (d.values.some((v) => !Number.isFinite(v)))
36
+ throw new RangeError("NA values not allowed in 'd'");
37
+ const matrix = Array.from({ length: n }, () => new Array(n).fill(0));
38
+ let p = 0;
39
+ for (let j = 0; j < n - 1; j++)
40
+ for (let i = j + 1; i < n; i++) {
41
+ matrix[i][j] = d.values[p];
42
+ matrix[j][i] = d.values[p];
43
+ p++;
44
+ }
45
+ return { matrix, labels: d.labels === null ? null : [...d.labels] };
46
+ }
47
+ function centerMatrix(d) {
48
+ const n = d.length;
49
+ const rowMeans = new Array(n).fill(0);
50
+ const colMeans = new Array(n).fill(0);
51
+ let grand = 0;
52
+ for (let i = 0; i < n; i++)
53
+ for (let j = 0; j < n; j++) {
54
+ rowMeans[i] = rowMeans[i] + d[i][j];
55
+ colMeans[j] = colMeans[j] + d[i][j];
56
+ }
57
+ for (let i = 0; i < n; i++) {
58
+ rowMeans[i] = rowMeans[i] / n;
59
+ colMeans[i] = colMeans[i] / n;
60
+ grand += rowMeans[i];
61
+ }
62
+ grand /= n;
63
+ return d.map((row, i) => row.map((v, j) => v - rowMeans[i] - colMeans[j] + grand));
64
+ }
65
+ function gramFromDistances(d) {
66
+ const squared = d.map((row) => row.map((v) => v * v));
67
+ const x = centerMatrix(squared);
68
+ const n = d.length;
69
+ const gram = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => i >= j ? -x[i][j] / 2 : -x[j][i] / 2));
70
+ return { x, gram };
71
+ }
72
+ function cailliez(d) {
73
+ const n = d.length;
74
+ let scale = 0;
75
+ for (const row of d)
76
+ for (const value of row)
77
+ scale = Math.max(scale, Math.abs(value));
78
+ const rescale = scale > 2 ** 450 || (scale > 0 && scale < 2 ** -450);
79
+ const work = rescale ? d.map((row) => row.map((value) => value / scale)) : d;
80
+ const multiplier = rescale ? scale : 1;
81
+ // Cailliez (1983): c is the largest real eigenvalue of
82
+ // [[0, 2 B0], [-I, -4 B1]], with B0/B1 the double-centered D^2/D
83
+ // matrices multiplied by -1/2.
84
+ const B0 = centerMatrix(work.map((row) => row.map((v) => v * v))).map((row) => row.map((v) => -v / 2));
85
+ const B1 = centerMatrix(work).map((row) => row.map((v) => -v / 2));
86
+ const size = 2 * n;
87
+ const companion = Array.from({ length: size }, () => new Array(size).fill(0));
88
+ for (let i = 0; i < n; i++) {
89
+ for (let j = 0; j < n; j++) {
90
+ companion[i][n + j] = 2 * B0[i][j];
91
+ companion[n + i][n + j] = -4 * B1[i][j];
92
+ }
93
+ companion[n + i][i] = -1;
94
+ }
95
+ const values = eigen(companion, { symmetric: false, onlyValues: true });
96
+ let largest = 0;
97
+ for (let i = 0; i < values.values.length; i++) {
98
+ const real = values.values[i];
99
+ const imaginary = values.valuesIm?.[i] ?? 0;
100
+ if (Math.abs(imaginary) <= 1e-10 * Math.max(1, Math.abs(real)) && real > largest)
101
+ largest = real;
102
+ }
103
+ return largest * multiplier;
104
+ }
105
+ function orient(points) {
106
+ if (points.length === 0)
107
+ return;
108
+ const k = points[0].length;
109
+ for (let j = 0; j < k; j++) {
110
+ let at = 0, largest = -1;
111
+ for (let i = 0; i < points.length; i++) {
112
+ const value = Math.abs(points[i][j]);
113
+ if (value > largest) {
114
+ largest = value;
115
+ at = i;
116
+ }
117
+ }
118
+ if (points[at][j] < 0)
119
+ for (let i = 0; i < points.length; i++)
120
+ points[i][j] = -points[i][j];
121
+ }
122
+ }
123
+ /**
124
+ * Classical (metric) multidimensional scaling of a dissimilarity structure.
125
+ * Equivalent to R's `cmdscale()`.
126
+ * @category Multivariate analysis
127
+ */
128
+ export function cmdscale(input, options = {}) {
129
+ checkOptions(options, CMDSCALE_KEYS, "cmdscale"); // generated: option-keys.mjs
130
+ const parsed = readDistances(input);
131
+ const n = parsed.matrix.length;
132
+ if (n < 2)
133
+ throw new RangeError("'k' must be in {1, 2, .. n - 1}");
134
+ const k = options.k ?? 2;
135
+ if (!Number.isFinite(k) || !Number.isInteger(k) || k < 1 || k >= n) {
136
+ throw new RangeError(`'k' must be in {1, 2, .. ${n - 1}}`);
137
+ }
138
+ // Squaring extreme dissimilarities can erase their Gram matrix even when the coordinates
139
+ // themselves are representable. Normalize only outside the safe square range; ordinary inputs
140
+ // retain the original operation order and bit patterns.
141
+ let magnitude = 0;
142
+ for (const row of parsed.matrix)
143
+ for (const value of row)
144
+ magnitude = Math.max(magnitude, Math.abs(value));
145
+ const rescale = magnitude > 2 ** 512 || (magnitude > 0 && magnitude < 2 ** -512);
146
+ const workMatrix = rescale ? parsed.matrix.map((row) => row.map((value) => value / magnitude)) : parsed.matrix;
147
+ const acWork = options.add ? cailliez(workMatrix) : 0;
148
+ const adjusted = workMatrix.map((row, i) => row.map((v, j) => i === j ? v : v + acWork));
149
+ const centered = gramFromDistances(adjusted);
150
+ // all eigenvalues but only the k leading eigenvectors (several times faster than eigen's full decomposition at large n)
151
+ const leading = symmetricLeading(centered.gram, k);
152
+ const decomposition = { values: leading.values };
153
+ const positive = decomposition.values.filter((v) => v > 0);
154
+ const dimensions = Math.min(k, positive.length);
155
+ const points = Array.from({ length: n }, (_, i) => Array.from({ length: dimensions }, (_, j) => {
156
+ const coordinate = leading.vectors[j][i] * Math.sqrt(positive[j]);
157
+ return rescale ? coordinate * magnitude : coordinate;
158
+ }));
159
+ orient(points);
160
+ const absSum = decomposition.values.reduce((s, v) => s + Math.abs(v), 0);
161
+ const positiveSum = positive.reduce((s, v) => s + v, 0);
162
+ const retained = positive.slice(0, dimensions).reduce((s, v) => s + v, 0);
163
+ const warnings = dimensions < k ? [`only ${dimensions} of the first ${k} eigenvalues are > 0`] : [];
164
+ const restoreSquare = (value) => value === 0 ? 0 : (value * magnitude) * magnitude;
165
+ const eigenvalues = rescale ? decomposition.values.map(restoreSquare) : [...decomposition.values];
166
+ const x = rescale ? centered.x.map((row) => row.map(restoreSquare)) : centered.x;
167
+ const ac = rescale ? acWork * magnitude : acWork;
168
+ return { points: { rows: parsed.labels, cols: null, values: points }, eig: eigenvalues,
169
+ x: options.xRet ? { rows: null, cols: null, values: x } : null, ac,
170
+ GOF: [absSum === 0 ? NaN : retained / absSum, positiveSum === 0 ? NaN : retained / positiveSum], warnings };
171
+ }
@@ -0,0 +1,63 @@
1
+ /** Distance metric used by {@link dist}.
2
+ * @category Multivariate analysis
3
+ */
4
+ export type DistMethod = "euclidean" | "maximum" | "manhattan" | "canberra" | "binary" | "minkowski";
5
+ /** A condensed dissimilarity object, in lower-triangle column order.
6
+ * @category Multivariate analysis
7
+ */
8
+ export interface DistResult {
9
+ /** Pairwise dissimilarities in lower-triangle column order. */
10
+ values: number[];
11
+ /** Number of observations represented by the dissimilarities. */
12
+ size: number;
13
+ /** Observation labels, or null when no labels were supplied. */
14
+ labels: string[] | null;
15
+ /** Distance method used, or null for a matrix converted by asDist. */
16
+ method: DistMethod | null;
17
+ /** Whether diagonal display was requested. */
18
+ diag: boolean;
19
+ /** Whether upper-triangle display was requested. */
20
+ upper: boolean;
21
+ /** Messages generated while coercing or processing the input. */
22
+ warnings: string[];
23
+ }
24
+ /** Options for pairwise dissimilarities.
25
+ * @category Multivariate analysis
26
+ */
27
+ export interface DistOptions {
28
+ /** Distance metric; a unique prefix is accepted. */
29
+ method?: DistMethod | string;
30
+ /** Minkowski power, required to be finite and positive when method is minkowski. */
31
+ p?: number;
32
+ /** Store the diagonal display flag in the result. */
33
+ diag?: boolean;
34
+ /** Store the upper-triangle display flag in the result. */
35
+ upper?: boolean;
36
+ /** Labels for the observations (one per row). */
37
+ labels?: readonly string[];
38
+ }
39
+ /** Options for converting a square matrix to condensed dissimilarities.
40
+ * @category Multivariate analysis
41
+ */
42
+ export interface AsDistOptions {
43
+ /** Labels for the rows and columns of the square matrix. */
44
+ labels?: readonly string[];
45
+ /** Store the diagonal display flag in the result. */
46
+ diag?: boolean;
47
+ /** Store the upper-triangle display flag in the result. */
48
+ upper?: boolean;
49
+ }
50
+ /**
51
+ * Compute pairwise dissimilarities in lower-triangle column order. Equivalent to R's `dist()`.
52
+ *
53
+ * @param x Numeric vector, matrix (rows are observations), or data-frame-like object of columns.
54
+ * @param options Distance method and display metadata.
55
+ * @category Multivariate analysis
56
+ */
57
+ export declare function dist(x: readonly unknown[] | readonly (readonly unknown[])[] | Record<string, ArrayLike<unknown>>, options?: DistOptions): DistResult;
58
+ /**
59
+ * Convert a square matrix using only its lower triangle. Equivalent to R's `as.dist()`.
60
+ * An existing DistResult is returned unchanged.
61
+ * @category Multivariate analysis
62
+ */
63
+ export declare function asDist(x: DistResult | readonly (readonly number[])[], options?: AsDistOptions): DistResult;
@@ -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;