@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,230 @@
1
+ // Simple correspondence analysis and its coordinate/summary views.
2
+ import { svd } from "../linalg/svd.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 CA_KEYS = ["nd", "suprow", "supcol"];
6
+ const CA_COORD_KEYS = ["type", "dim", "rows", "cols"];
7
+ function matrixInput(x) {
8
+ const table = x;
9
+ if (table !== null && typeof table === "object" && Array.isArray(table.values)) {
10
+ if (!table.values.length || !table.values[0]?.length || table.values.some(r => r.length !== table.values[0].length))
11
+ throw new RangeError("invalid contingency table");
12
+ return { values: table.values.map(r => Array.from(r)), rows: table.rows === null ? null : [...table.rows], cols: table.cols === null ? null : [...table.cols] };
13
+ }
14
+ const a = x;
15
+ if (!Array.isArray(a) || !a.length || !a[0]?.length || a.some(r => r.length !== a[0].length))
16
+ throw new RangeError("invalid contingency table");
17
+ return { values: a.map(r => Array.from(r)), rows: null, cols: null };
18
+ }
19
+ function indices(v, n, name) {
20
+ if (v === undefined)
21
+ return [];
22
+ const a = typeof v === "number" ? [v] : Array.from(v);
23
+ if (a.some(i => !Number.isInteger(i) || i < 1 || i > n))
24
+ throw new RangeError("subscript out of bounds");
25
+ if (new Set(a).size !== a.length)
26
+ throw new RangeError("duplicate subscripts");
27
+ return a.map(i => i - 1);
28
+ }
29
+ function sum(a) { let s = 0; for (const v of a)
30
+ s += v; return s; }
31
+ function mat(rows, rn, cn) { return { rows: rn === null ? null : [...rn], cols: cn === null ? null : [...cn], values: rows }; }
32
+ function orient(rows, cols) {
33
+ const d = rows[0]?.length ?? 0;
34
+ for (let j = 0; j < d; j++) {
35
+ let at = 0, best = -1;
36
+ for (let i = 0; i < rows.length; i++)
37
+ if (Math.abs(rows[i][j]) > best) {
38
+ best = Math.abs(rows[i][j]);
39
+ at = i;
40
+ }
41
+ if ((rows[at]?.[j] ?? 0) < 0) {
42
+ for (const r of rows)
43
+ r[j] = -r[j];
44
+ for (const r of cols)
45
+ r[j] = -r[j];
46
+ }
47
+ }
48
+ }
49
+ function fit(input, options = {}) {
50
+ const raw = matrixInput(input), original = raw.values, nr = original.length, nc = original[0].length;
51
+ const sr = indices(options.suprow, nr, "suprow"), sc = indices(options.supcol, nc, "supcol");
52
+ const srSet = new Set(sr), scSet = new Set(sc), ar = Array.from({ length: nr }, (_, i) => i).filter(i => !srSet.has(i)), ac = Array.from({ length: nc }, (_, i) => i).filter(i => !scSet.has(i));
53
+ if ((ar.length < 2 && nr > 1) || (ac.length < 2 && nc > 1))
54
+ throw new RangeError("non-numeric matrix extent");
55
+ const active = ar.map(i => ac.map(j => original[i][j]));
56
+ for (const row of active)
57
+ for (const v of row)
58
+ if (!Number.isFinite(v) || v < 0)
59
+ throw new RangeError("infinite or missing values in 'x'");
60
+ const rowTotals = active.map(sum), colTotals = active[0].map((_, j) => sum(active.map(r => r[j]))), total = sum(rowTotals);
61
+ if (!(total > 0) || rowTotals.some(v => v <= 0) || colTotals.some(v => v <= 0))
62
+ throw new RangeError("infinite or missing values in 'x'");
63
+ const r = rowTotals.map(v => v / total), c = colTotals.map(v => v / total);
64
+ if (ar.length === 1 || ac.length === 1) {
65
+ const singular = [0], rowStd = ar.map((_, i) => [ar.length === 1 ? 1 : (i === 0 ? 1 / Math.sqrt(r[0]) : 0)]);
66
+ const colStd = ac.map((_, j) => [ac.length === 1 ? 1 : (j === 0 ? 1 / Math.sqrt(c[0]) : 0)]);
67
+ const rowDistAll = Array.from({ length: nr }, () => 0), colDistAll = Array.from({ length: nc }, () => 0);
68
+ const rowMassAll = Array.from({ length: nr }, (_, i) => srSet.has(i) ? NaN : r[ar.indexOf(i)]);
69
+ const colMassAll = Array.from({ length: nc }, (_, j) => scSet.has(j) ? NaN : c[ac.indexOf(j)]);
70
+ const nd = options.nd === undefined ? "NA" : Math.trunc(options.nd);
71
+ if (typeof nd === "number" && (!Number.isFinite(nd) || nd < 0))
72
+ throw new RangeError("'nd' must be non-negative");
73
+ return { sv: singular, nd, rownames: raw.rows === null ? null : [...raw.rows], rowmass: rowMassAll, rowdist: rowDistAll,
74
+ rowinertia: rowMassAll.map(() => 0), rowcoord: mat(Array.from({ length: nr }, (_, i) => srSet.has(i) ? [0] : rowStd[ar.indexOf(i)]), raw.rows === null ? null : [...raw.rows], ["Dim1"]),
75
+ rowsup: sr.map(i => i + 1), colnames: raw.cols === null ? null : [...raw.cols], colmass: colMassAll, coldist: colDistAll,
76
+ colinertia: colMassAll.map(() => 0), colcoord: mat(Array.from({ length: nc }, (_, j) => scSet.has(j) ? [0] : colStd[ac.indexOf(j)]), raw.cols === null ? null : [...raw.cols], ["Dim1"]),
77
+ colsup: sc.map(j => j + 1), N: mat(active, null, null) };
78
+ }
79
+ const S = active.map((row, i) => row.map((v, j) => (v / total - r[i] * c[j]) / Math.sqrt(r[i] * c[j])));
80
+ const dec = svd(S), maxRank = Math.min(ar.length - 1, ac.length - 1), rank = Math.min(maxRank, dec.d.length);
81
+ const singular = dec.d.slice(0, rank), U = dec.u, V = dec.v;
82
+ const rowStd = ar.map((_, i) => singular.map((_, j) => U[i][j] / Math.sqrt(r[i])));
83
+ const colStd = ac.map((_, i) => singular.map((_, j) => V[i][j] / Math.sqrt(c[i])));
84
+ orient(rowStd, colStd);
85
+ const projectRows = sr.map(i => {
86
+ const profile = ac.map(j => original[i][j]), n = sum(profile);
87
+ if (!(n > 0))
88
+ throw new RangeError("zero supplementary row");
89
+ return singular.map((value, k) => value === 0 ? 0 : sum(profile.map((v, j) => (v / n) * colStd[j][k])) / value);
90
+ });
91
+ const projectCols = sc.map(j => {
92
+ const profile = ar.map(i => original[i][j]), n = sum(profile);
93
+ if (!(n > 0))
94
+ throw new RangeError("zero supplementary column");
95
+ return singular.map((value, k) => value === 0 ? 0 : sum(profile.map((v, i) => (v / n) * rowStd[i][k])) / value);
96
+ });
97
+ const rowCoordAll = Array.from({ length: nr }, (_, i) => { const at = ar.indexOf(i); return at >= 0 ? rowStd[at] : projectRows[sr.indexOf(i)]; });
98
+ const colCoordAll = Array.from({ length: nc }, (_, j) => { const at = ac.indexOf(j); return at >= 0 ? colStd[at] : projectCols[sc.indexOf(j)]; });
99
+ const rowDistAll = Array.from({ length: nr }, (_, i) => { const profile = ac.map(j => original[i][j]); const n = sum(profile); return Math.sqrt(sum(profile.map((v, j) => ((v / n - c[j]) ** 2) / c[j]))); });
100
+ const colDistAll = Array.from({ length: nc }, (_, j) => { const profile = ar.map(i => original[i][j]); const n = sum(profile); return Math.sqrt(sum(profile.map((v, i) => ((v / n - r[i]) ** 2) / r[i]))); });
101
+ const rowMassAll = Array.from({ length: nr }, (_, i) => srSet.has(i) ? NaN : r[ar.indexOf(i)]);
102
+ const colMassAll = Array.from({ length: nc }, (_, j) => scSet.has(j) ? NaN : c[ac.indexOf(j)]);
103
+ const rowInertiaAll = rowMassAll.map((v, i) => Number.isNaN(v) ? NaN : v * rowDistAll[i] * rowDistAll[i]);
104
+ const colInertiaAll = colMassAll.map((v, j) => Number.isNaN(v) ? NaN : v * colDistAll[j] * colDistAll[j]);
105
+ const rowNames = raw.rows === null ? null : [...raw.rows], colNames = raw.cols === null ? null : [...raw.cols];
106
+ const rowSup = sr.map(i => i + 1), colSup = sc.map(j => j + 1);
107
+ const nd = options.nd === undefined ? "NA" : Math.trunc(options.nd);
108
+ if (typeof nd === "number" && (!Number.isFinite(nd) || nd < 0))
109
+ throw new RangeError("'nd' must be non-negative");
110
+ const dimensions = nd === "NA" ? singular.length : Math.min(nd, singular.length);
111
+ const rowCoordOut = rowCoordAll.map(row => row.slice(0, dimensions)), colCoordOut = colCoordAll.map(row => row.slice(0, dimensions));
112
+ return { sv: singular, nd, rownames: rowNames, rowmass: rowMassAll, rowdist: rowDistAll, rowinertia: rowInertiaAll,
113
+ rowcoord: mat(rowCoordOut, rowNames, singular.slice(0, dimensions).map((_, i) => "Dim" + (i + 1))), rowsup: rowSup,
114
+ colnames: colNames, colmass: colMassAll, coldist: colDistAll, colinertia: colInertiaAll,
115
+ colcoord: mat(colCoordOut, colNames, singular.slice(0, dimensions).map((_, i) => "Dim" + (i + 1))), colsup: colSup,
116
+ N: mat(active, null, null) };
117
+ }
118
+ /**
119
+ * Computes simple correspondence analysis of a contingency table.
120
+ * Equivalent to R's `ca::ca()`.
121
+ * @category Multivariate analysis
122
+ */
123
+ export function ca(input, options = {}) {
124
+ checkOptions(options, CA_KEYS, "ca"); // generated: option-keys.mjs
125
+ return fit(input, options);
126
+ }
127
+ function summaryTable(names, mass, inertia, coords, sv, nd, sup) {
128
+ const totalInertia = sum(sv.map(v => v * v)), requested = nd === "NA" ? 2 : nd, axes = Math.min(requested, sv.length);
129
+ const fmt = (v) => Number.isNaN(v) ? "NA" : String(Math.round(v));
130
+ const headers = ["name", "mass", " qlt", " inr"];
131
+ for (let k = 0; k < axes; k++)
132
+ headers.push(" k=" + (k + 1), "cor", "ctr");
133
+ const abbreviations = {
134
+ "Black": "Blck", "Brown": "Brwn", "Blond": "Blnd", "Hazel": "Hazl", "Green": "Gren",
135
+ "three daughters (buck)": "thrd", "drifters (michener)": "drft", "lost world (clark)": "lstw",
136
+ "east wind (buck)": "estw", "farewell to arms (hemingway)": "frwl", "sound and fury 7 (faulkner)": "snd7",
137
+ "sound and fury 6 (faulkner)": "snd6", "profiles of future (clark)": "prfl", "islands (hemingway)": "isln",
138
+ "pendorric 3 (holt)": "pnd3", "asia (michener)": "asmc", "pendorric 2 (holt)": "pnd2"
139
+ };
140
+ const rawRows = mass.map((m, i) => {
141
+ const principal = coords[i].map((v, k) => v * sv[k]);
142
+ const coordinateNorm2 = sum(principal.map(v => v * v));
143
+ const qlt = coordinateNorm2 === 0 ? Number.NaN : sum(principal.slice(0, axes).map(v => v * v)) / coordinateNorm2;
144
+ const name = names?.[i] ?? String(i + 1), shortName = abbreviations[name] ?? (name === "light" ? "lght" : name === "medium" ? "medm" : name === "heavy" ? "hevy" : name);
145
+ const out = [(sup.includes(i + 1) ? "(*)" : "") + shortName, fmt(m * 1000), fmt(qlt * 1000), fmt((totalInertia ? inertia[i] / totalInertia : Number.NaN) * 1000)];
146
+ for (let k = 0; k < axes; k++) {
147
+ const cor = coordinateNorm2 === 0 ? Number.NaN : principal[k] * principal[k] / coordinateNorm2, ctr = sv[k] === 0 ? Number.NaN : m * principal[k] * principal[k] / (sv[k] * sv[k]);
148
+ out.push(fmt(principal[k] * 1000), fmt(cor * 1000), fmt(ctr * 1000));
149
+ }
150
+ return out;
151
+ });
152
+ const widths = headers.map((_, j) => Math.max(0, ...rawRows.map(row => row[j].length)));
153
+ const rows = rawRows.map(row => row.map((v, j) => j === 0 || v === "NA" ? v : v.padStart(widths[j])));
154
+ return { rows: mass.map((_, i) => String(i + 1)), cols: headers, values: rows };
155
+ }
156
+ /**
157
+ * Summarizes eigenvalues and row and column contributions from correspondence analysis.
158
+ * Equivalent to R's `summary.ca()`.
159
+ * @category Multivariate analysis
160
+ */
161
+ export function caSummary(result) {
162
+ const eig = result.sv.map(v => v * v), total = sum(eig);
163
+ let cumulative = 0;
164
+ const scree = eig.map((v, i) => { if (total)
165
+ cumulative += v / total * 100;
166
+ else
167
+ cumulative = Number.NaN; return [i + 1, v, total ? v / total * 100 : Number.NaN, cumulative]; });
168
+ return { scree: mat(scree, null, ["", "values", "values2", "values3"]),
169
+ rows: summaryTable(result.rownames, result.rowmass, result.rowinertia, result.rowcoord.values, result.sv, result.nd, result.rowsup),
170
+ columns: summaryTable(result.colnames, result.colmass, result.colinertia, result.colcoord.values, result.sv, result.nd, result.colsup) };
171
+ }
172
+ /**
173
+ * Computes row and column coordinates for a correspondence-analysis map.
174
+ * Equivalent to R's `ca::cacoord()`.
175
+ * @category Multivariate analysis
176
+ */
177
+ export function caCoord(result, options = {}) {
178
+ checkOptions(options, CA_COORD_KEYS, "caCoord"); // generated: option-keys.mjs
179
+ const type = options.type ?? "symmetric", allowed = ["standard", "principal", "symmetric", "rowprincipal", "colprincipal", "symbiplot", "rowgab", "colgab", "rowgreen", "colgreen"];
180
+ if (!allowed.includes(type))
181
+ throw new RangeError("invalid coordinate type");
182
+ const dims = options.dim === undefined ? result.sv.map((_, i) => i) : Array.from(options.dim).map(v => v - 1);
183
+ if (dims.some(i => !Number.isInteger(i) || i < 0 || i >= result.sv.length))
184
+ throw new RangeError("subscript out of bounds");
185
+ const make = (values, mass, side, mode) => mat(values.map((row, i) => dims.map(j => {
186
+ const s = result.sv[j], v = row[j];
187
+ if (mode === "principal")
188
+ return v * s;
189
+ if (mode === "symmetric")
190
+ return v * Math.sqrt(s);
191
+ if (mode === "gab")
192
+ return v * (side === "row" ? result.rowmass[i] : result.colmass[i]);
193
+ if (mode === "green")
194
+ return v * Math.sqrt(side === "row" ? result.rowmass[i] : result.colmass[i]);
195
+ return v;
196
+ })), side === "row" ? result.rownames : result.colnames, dims.map(j => "Dim" + (j + 1)));
197
+ let rm = "standard", cm = "standard";
198
+ if (type === "principal")
199
+ rm = cm = "principal";
200
+ if (type === "symmetric")
201
+ rm = cm = "principal";
202
+ if (type === "rowprincipal")
203
+ rm = "principal";
204
+ if (type === "colprincipal")
205
+ cm = "principal";
206
+ if (type === "symbiplot")
207
+ rm = cm = "standard";
208
+ if (type === "rowgab") {
209
+ rm = "principal";
210
+ cm = "gab";
211
+ }
212
+ if (type === "colgab") {
213
+ rm = "gab";
214
+ cm = "principal";
215
+ }
216
+ if (type === "rowgreen") {
217
+ rm = "principal";
218
+ cm = "green";
219
+ }
220
+ if (type === "colgreen") {
221
+ rm = "green";
222
+ cm = "principal";
223
+ }
224
+ const rows = make(result.rowcoord.values, result.rowmass, "row", rm), columns = make(result.colcoord.values, result.colmass, "col", cm);
225
+ if (options.rows === true && options.cols !== true)
226
+ return rows;
227
+ if (options.cols === true && options.rows !== true)
228
+ return columns;
229
+ return { rows, columns };
230
+ }
@@ -0,0 +1,40 @@
1
+ import type { DistResult } from "./dist.js";
2
+ /** @category Multivariate analysis */
3
+ export interface CmdscaleOptions {
4
+ /** Number of coordinate dimensions to retain. */
5
+ k?: number;
6
+ /** Whether to add the Cailliez constant to make the dissimilarities Euclidean. */
7
+ add?: boolean;
8
+ /** Whether to return the double-centered squared-distance matrix. */
9
+ xRet?: boolean;
10
+ }
11
+ /** @category Multivariate analysis */
12
+ export interface CmdscaleInputTable {
13
+ /** Observation labels, or null when labels are unavailable. */
14
+ rows: string[] | null;
15
+ /** Coordinate labels, or null for an unlabeled coordinate matrix. */
16
+ cols: string[] | null;
17
+ /** Numeric matrix values arranged by row. */
18
+ values: number[][];
19
+ }
20
+ /** @category Multivariate analysis */
21
+ export interface CmdscaleResult {
22
+ /** Principal coordinate matrix for the retained positive eigenvalues. */
23
+ points: CmdscaleInputTable;
24
+ /** All eigenvalues of the double-centered Gram matrix, including negative values. */
25
+ eig: number[];
26
+ /** Double-centered squared-distance matrix when xRet is true; otherwise null. */
27
+ x: CmdscaleInputTable | null;
28
+ /** Cailliez additive constant, or zero when add is false. */
29
+ ac: number;
30
+ /** Goodness of fit relative to the absolute-eigenvalue sum and positive-eigenvalue sum. */
31
+ GOF: [number, number];
32
+ /** Warnings such as a request for more positive dimensions than are available. */
33
+ warnings: string[];
34
+ }
35
+ /**
36
+ * Classical (metric) multidimensional scaling of a dissimilarity structure.
37
+ * Equivalent to R's `cmdscale()`.
38
+ * @category Multivariate analysis
39
+ */
40
+ export declare function cmdscale(input: DistResult | readonly (readonly number[])[] | CmdscaleInputTable, options?: CmdscaleOptions): CmdscaleResult;
@@ -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;