@numero-uno-jpn/rstats 1.10.0 → 1.12.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 (108) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.ja.md +8 -6
  3. package/README.md +8 -6
  4. package/dist/causal/balance.d.ts +106 -0
  5. package/dist/causal/balance.js +216 -0
  6. package/dist/causal/match.d.ts +86 -0
  7. package/dist/causal/match.js +155 -0
  8. package/dist/causal/scale.d.ts +8 -0
  9. package/dist/causal/scale.js +26 -0
  10. package/dist/causal.js +2 -0
  11. package/dist/chunks/chunk-2P42OXYW.js +2 -0
  12. package/dist/chunks/{chunk-GYLFMAD6.js → chunk-3QOW56EJ.js} +2 -2
  13. package/dist/chunks/chunk-3QSYPBUM.js +2 -0
  14. package/dist/chunks/chunk-4B7NEJCE.js +2 -0
  15. package/dist/chunks/{chunk-PJ73WRSA.js → chunk-4GRV66HW.js} +2 -2
  16. package/dist/chunks/chunk-4U65I4J2.js +2 -0
  17. package/dist/chunks/chunk-52KGBGFL.js +2 -0
  18. package/dist/chunks/{chunk-Y7SXBQZY.js → chunk-5AR4V7MW.js} +2 -2
  19. package/dist/chunks/chunk-7FXBOYIH.js +2 -0
  20. package/dist/chunks/{chunk-ZUHBIFAJ.js → chunk-7K2LMKZR.js} +2 -2
  21. package/dist/chunks/chunk-7UI4PW32.js +2 -0
  22. package/dist/chunks/{chunk-IFFGJN5L.js → chunk-CHKBDZC4.js} +2 -2
  23. package/dist/chunks/chunk-CKBUE4FV.js +2 -0
  24. package/dist/chunks/chunk-CMTCPLIA.js +2 -0
  25. package/dist/chunks/chunk-DWVTVOQS.js +2 -0
  26. package/dist/chunks/chunk-FFMMKXMK.js +2 -0
  27. package/dist/chunks/chunk-HF3QOIZX.js +2 -0
  28. package/dist/chunks/chunk-JG26HC2H.js +2 -0
  29. package/dist/chunks/chunk-L54WIMTZ.js +3 -0
  30. package/dist/chunks/{chunk-ISNGTKVZ.js → chunk-MAFZ5FGL.js} +2 -2
  31. package/dist/chunks/{chunk-F3WMBL5R.js → chunk-MJ7IY7AF.js} +2 -2
  32. package/dist/chunks/chunk-MUYGPZ37.js +3 -0
  33. package/dist/chunks/chunk-NAACMR7H.js +2 -0
  34. package/dist/chunks/chunk-NGDBJR3K.js +2 -0
  35. package/dist/chunks/chunk-NQT7ZWL6.js +2 -0
  36. package/dist/chunks/{chunk-6U2ICRN3.js → chunk-O6OMXX5U.js} +1 -1
  37. package/dist/chunks/chunk-PYFASERO.js +2 -0
  38. package/dist/chunks/chunk-QT32BMYA.js +2 -0
  39. package/dist/chunks/{chunk-6BDTLUNM.js → chunk-SKQHW2GD.js} +2 -2
  40. package/dist/chunks/{chunk-EDHAQHB7.js → chunk-SLMS3FQD.js} +1 -1
  41. package/dist/chunks/{chunk-6Y7OKIIM.js → chunk-SZR5HAMB.js} +2 -2
  42. package/dist/chunks/chunk-T5TE5KCP.js +2 -0
  43. package/dist/chunks/chunk-ULQXNAI6.js +2 -0
  44. package/dist/chunks/chunk-UPFMYDF7.js +2 -0
  45. package/dist/chunks/{chunk-DC2FP6ZH.js → chunk-WACTNIKS.js} +2 -2
  46. package/dist/chunks/{chunk-F5K2UXKW.js → chunk-WSDLT4AR.js} +1 -1
  47. package/dist/chunks/chunk-WUNTM7PJ.js +2 -0
  48. package/dist/chunks/chunk-XQSYV3IZ.js +2 -0
  49. package/dist/chunks/chunk-YKCZF4ES.js +2 -0
  50. package/dist/chunks/{chunk-NNJGXB5K.js → chunk-ZHAT6244.js} +2 -2
  51. package/dist/chunks/{chunk-OQFZKQVT.js → chunk-ZK7FW5UX.js} +2 -2
  52. package/dist/descriptive.js +2 -2
  53. package/dist/distributions.js +2 -2
  54. package/dist/entries/causal.d.ts +2 -0
  55. package/dist/entries/causal.js +3 -0
  56. package/dist/entries/multivariate.d.ts +4 -0
  57. package/dist/entries/multivariate.js +4 -0
  58. package/dist/entries/tests.d.ts +1 -0
  59. package/dist/entries/tests.js +1 -0
  60. package/dist/entries/timeseries.d.ts +1 -0
  61. package/dist/entries/timeseries.js +2 -0
  62. package/dist/linalg.js +2 -2
  63. package/dist/mixed.js +2 -2
  64. package/dist/models/clogit.d.ts +80 -0
  65. package/dist/models/clogit.js +211 -0
  66. package/dist/models/coxph.d.ts +9 -0
  67. package/dist/models/coxph.js +3 -3
  68. package/dist/multivariate/ca.d.ts +120 -0
  69. package/dist/multivariate/ca.js +230 -0
  70. package/dist/multivariate/isoMDS.d.ts +55 -0
  71. package/dist/multivariate/isoMDS.js +409 -0
  72. package/dist/multivariate/mjca.d.ts +125 -0
  73. package/dist/multivariate/mjca.js +243 -0
  74. package/dist/multivariate/sammon.d.ts +66 -0
  75. package/dist/multivariate/sammon.js +231 -0
  76. package/dist/multivariate.js +2 -2
  77. package/dist/numerics.js +2 -2
  78. package/dist/regression.js +2 -2
  79. package/dist/rstats.js +18 -18
  80. package/dist/special.js +2 -2
  81. package/dist/tests.js +15 -15
  82. package/dist/timeseries/acf.d.ts +80 -0
  83. package/dist/timeseries/acf.js +314 -0
  84. package/dist/timeseries.js +2 -0
  85. package/llms.txt +51 -2
  86. package/package.json +11 -1
  87. package/dist/chunks/chunk-3QUOB47N.js +0 -2
  88. package/dist/chunks/chunk-5PVS6TF2.js +0 -2
  89. package/dist/chunks/chunk-AQ7H4RJH.js +0 -2
  90. package/dist/chunks/chunk-CN5D6ITZ.js +0 -3
  91. package/dist/chunks/chunk-F232C4SB.js +0 -3
  92. package/dist/chunks/chunk-JPQEOHZG.js +0 -2
  93. package/dist/chunks/chunk-JRMISESC.js +0 -2
  94. package/dist/chunks/chunk-K25FNCFH.js +0 -2
  95. package/dist/chunks/chunk-KGDCQ2RV.js +0 -2
  96. package/dist/chunks/chunk-LQWAHXHZ.js +0 -2
  97. package/dist/chunks/chunk-MBQJWNPX.js +0 -2
  98. package/dist/chunks/chunk-MULNGWZY.js +0 -2
  99. package/dist/chunks/chunk-MVIBJA2I.js +0 -2
  100. package/dist/chunks/chunk-NAUAW5TO.js +0 -2
  101. package/dist/chunks/chunk-NMVFSSEZ.js +0 -2
  102. package/dist/chunks/chunk-OXYMJNVJ.js +0 -2
  103. package/dist/chunks/chunk-R5BXUEH3.js +0 -2
  104. package/dist/chunks/chunk-RPEFV4FR.js +0 -2
  105. package/dist/chunks/chunk-T3XFVWOW.js +0 -2
  106. package/dist/chunks/chunk-Y5M7NEJ5.js +0 -2
  107. package/dist/chunks/chunk-YCBQQHCB.js +0 -2
  108. package/dist/chunks/chunk-YGKM6PIJ.js +0 -2
@@ -0,0 +1,211 @@
1
+ // Conditional logistic regression, after survival's clogit(case ~ x + strata(set), method): "exact" maximises the
2
+ // exact conditional likelihood (Gail, Lubin & Rubinstein (1981), "Likelihood calculations for matched case-control
3
+ // studies and survival studies with tied death times", Biometrika 68, 703-707), "approximate" (= "breslow") is the
4
+ // Cox partial likelihood with Breslow's ties on equal times (coxph). Newton-Raphson as coxph (Therneau & Grambsch
5
+ // 2000, chapter 3). Written for rStats.js from the documentation and the published output (no ported code).
6
+ import { pchisq } from "../distributions/chisq.js";
7
+ import { qnorm } from "../distributions/normal.js";
8
+ import { cholFactor, cholInverse, cholSolve, coxph } from "./coxph.js";
9
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
10
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
11
+ const CLOGIT_KEYS = ["method", "confLevel", "control"];
12
+ const CLOGIT_CONTROL_KEYS = ["eps", "iterMax"];
13
+ /**
14
+ * Log likelihood, score and information of the exact conditional likelihood at beta (covariates centred). For each set,
15
+ * B_k (the sum over the subsets of size k of the products of r = exp(eta - max eta)) and its first and second
16
+ * derivatives D_k, H_k are built one member at a time (B_k += r B_{k-1}, from the largest k down). B_k grows like the
17
+ * binomial coefficient, past the doubles for large sets (a set of 2000 with 1000 cases): each k keeps its own power of 2.
18
+ */
19
+ function evaluateExact(sets, beta) {
20
+ const p = beta.length;
21
+ let loglik = 0;
22
+ const score = new Array(p).fill(0);
23
+ const info = Array.from({ length: p }, () => new Array(p).fill(0));
24
+ for (const { x, cases: d } of sets) {
25
+ const m = x.length;
26
+ if (d === 0 || d === m)
27
+ continue; // a set of cases only or controls only carries no information
28
+ const eta = x.map((row) => row.reduce((acc, v, j) => acc + v * beta[j], 0));
29
+ const top = Math.max(...eta);
30
+ const B = new Array(d + 1).fill(0);
31
+ const E = new Array(d + 1).fill(0); // B_k, D_k, H_k are stored divided by 2^E[k]
32
+ const D = Array.from({ length: d + 1 }, () => new Array(p).fill(0));
33
+ const H = Array.from({ length: d + 1 }, () => Array.from({ length: p }, () => new Array(p).fill(0)));
34
+ B[0] = 1;
35
+ for (let i = 0; i < m; i++) {
36
+ const xi = x[i];
37
+ const r = Math.exp(eta[i] - top);
38
+ for (let k = Math.min(d, i + 1); k >= 1; k--) {
39
+ // new_k = old_k + r old_{k-1}, the two in the common unit 2^e
40
+ const e = B[k] === 0 ? E[k - 1] : Math.max(E[k], E[k - 1]);
41
+ const fa = B[k] === 0 ? 0 : 2 ** (E[k] - e);
42
+ const fb = r * 2 ** (E[k - 1] - e);
43
+ const bPrev = B[k - 1], dPrev = D[k - 1], hPrev = H[k - 1], dk = D[k], hk = H[k];
44
+ B[k] = B[k] * fa + fb * bPrev;
45
+ for (let a = 0; a < p; a++) {
46
+ const da = dk[a];
47
+ dk[a] = da * fa + fb * (xi[a] * bPrev + dPrev[a]);
48
+ for (let b = 0; b < p; b++) {
49
+ hk[a][b] = hk[a][b] * fa + fb * (xi[a] * xi[b] * bPrev + xi[a] * dPrev[b] + xi[b] * dPrev[a] + hPrev[a][b]);
50
+ }
51
+ }
52
+ E[k] = e;
53
+ // keep the stored B_k near 1 (D_k and H_k are of the same order times the covariates)
54
+ if (B[k] > 2 ** 256 || (B[k] > 0 && B[k] < 2 ** -256)) {
55
+ const shift = Math.floor(Math.log2(B[k]));
56
+ const f = 2 ** -shift;
57
+ B[k] = B[k] * f;
58
+ for (let a = 0; a < p; a++) {
59
+ dk[a] = dk[a] * f;
60
+ for (let b = 0; b < p; b++)
61
+ hk[a][b] = hk[a][b] * f;
62
+ }
63
+ E[k] = e + shift;
64
+ }
65
+ }
66
+ }
67
+ let num = 0;
68
+ for (let i = 0; i < d; i++)
69
+ num += eta[i] - top;
70
+ loglik += num - (Math.log(B[d]) + E[d] * Math.LN2);
71
+ for (let a = 0; a < p; a++) {
72
+ let sx = 0;
73
+ for (let i = 0; i < d; i++)
74
+ sx += x[i][a];
75
+ const ma = D[d][a] / B[d];
76
+ score[a] += sx - ma;
77
+ for (let b = 0; b < p; b++)
78
+ info[a][b] += H[d][a][b] / B[d] - ma * (D[d][b] / B[d]);
79
+ }
80
+ }
81
+ return { loglik, score, info };
82
+ }
83
+ function test(statistic, df) {
84
+ return { statistic, df, pValue: pchisq(statistic, df, { lowerTail: false }) };
85
+ }
86
+ /**
87
+ * Conditional logistic regression for matched sets (1:1, 1:M or several cases per set). Equivalent to
88
+ * `survival::clogit()` in R. The call followed is `clogit(y ~ x1 + ... + strata(set), method)`.
89
+ *
90
+ * `y` is 1 for a case and 0 for a control, `x` one row of covariates per observation, `strata` the matched set of
91
+ * each observation (for matched pairs from {@link match}, the pair number). Sets with only cases or only controls
92
+ * carry no information. `"exact"` (R's default) uses the exact conditional likelihood, summing over the subsets of each
93
+ * set with as many members as it has cases; `"approximate"` is Breslow's approximation, the same as {@link coxph}
94
+ * with equal times, `ties: "breslow"` and these strata.
95
+ * @category Survival analysis
96
+ * @example
97
+ * ```ts
98
+ * const y = [1, 0, 1, 0, 1, 0, 0, 1];
99
+ * const x = [[1], [0], [1], [0], [0], [0], [1], [0]];
100
+ * const fit = clogit(y, x, [1, 1, 2, 2, 3, 3, 4, 4]);
101
+ * fit.coefficients; // [0.6931471805599454] (log 2: two discordant pairs for x, one against)
102
+ * ```
103
+ */
104
+ export function clogit(y, x, strata, options = {}) {
105
+ checkOptions(options, CLOGIT_KEYS, "clogit"); // generated: option-keys.mjs
106
+ checkOptions(nestedOptions(options, "control"), CLOGIT_CONTROL_KEYS, "clogit", "control"); // generated: option-keys.mjs
107
+ const { method = "exact", confLevel = 0.95, control = {} } = options;
108
+ const { eps = 1e-9, iterMax = 20 } = control;
109
+ const n = y.length;
110
+ if (x.length !== n || strata.length !== n)
111
+ throw new RangeError("'y', 'x' and 'strata' must have the same length");
112
+ if (method !== "exact" && method !== "approximate" && method !== "breslow")
113
+ throw new RangeError(`invalid 'method': ${String(method)}`);
114
+ y.forEach((v, i) => { if (v !== 0 && v !== 1)
115
+ throw new RangeError(`'y' must be 0 or 1 (element ${i + 1})`); });
116
+ const p = x[0]?.length ?? 0;
117
+ if (p === 0 || x.some((row) => row.length !== p || row.some((v) => !Number.isFinite(v)))) {
118
+ throw new RangeError("'x' must have the same positive number of finite covariates in every row");
119
+ }
120
+ const zq = qnorm((1 + confLevel) / 2);
121
+ const finish = (coefficients, variance, loglik, score, wald, iter, m, warnings) => {
122
+ const se = variance.map((row, i) => Math.sqrt(row[i]));
123
+ const z = coefficients.map((c, i) => c / se[i]);
124
+ return {
125
+ coefficients, var: variance, loglik, score, wald, iter, n, nevent: y.reduce((s, v) => s + v, 0), method: m, se, z,
126
+ p: z.map((v) => pchisq(v * v, 1, { lowerTail: false })),
127
+ lower: coefficients.map((c, i) => Math.exp(c - zq * se[i])), upper: coefficients.map((c, i) => Math.exp(c + zq * se[i])),
128
+ logtest: test(2 * (loglik[1] - loglik[0]), p), sctest: test(score, p), waldtest: test(wald, p), warnings,
129
+ };
130
+ };
131
+ if (method !== "exact") {
132
+ const fit = coxph(new Array(n).fill(1), y, x, { ties: "breslow", strata, confLevel, control: { eps, iterMax } });
133
+ return finish(fit.coefficients, fit.var, fit.loglik, fit.score, fit.wald, fit.iter, "breslow", fit.warnings);
134
+ }
135
+ // matched sets with the cases first; covariates centred on the overall means (the likelihood does not change)
136
+ const means = Array.from({ length: p }, (_, j) => x.reduce((s, row) => s + row[j], 0) / n);
137
+ const groups = new Map();
138
+ for (let i = 0; i < n; i++) {
139
+ let g = groups.get(strata[i]);
140
+ if (g === undefined) {
141
+ g = { cases: [], controls: [] };
142
+ groups.set(strata[i], g);
143
+ }
144
+ (y[i] === 1 ? g.cases : g.controls).push(x[i].map((v, j) => v - means[j]));
145
+ }
146
+ const sets = [...groups.values()].map((g) => ({ x: [...g.cases, ...g.controls], cases: g.cases.length }));
147
+ // Newton-Raphson with step halving, as coxph; the pivots of the information below 2^-39 of the largest are dropped
148
+ // (an aliased covariate gets NaN, as R's NA)
149
+ const tolerChol = 2 ** -39;
150
+ const factorOf = (info) => {
151
+ const f = info.map((row) => row.slice());
152
+ return { f, rank: cholFactor(f, tolerChol) };
153
+ };
154
+ let beta = new Array(p).fill(0);
155
+ let ev = evaluateExact(sets, beta);
156
+ const loglik = [ev.loglik, ev.loglik];
157
+ let { f: factor } = factorOf(ev.info);
158
+ let step = cholSolve(factor, ev.score);
159
+ const score = ev.score.reduce((acc, u, i) => acc + u * step[i], 0);
160
+ const warnings = [];
161
+ // the coefficients accepted at each iteration (0: the start), for the iterations-ran-out case below
162
+ const accepted = [beta];
163
+ let best = ev.loglik;
164
+ let next = beta.map((b, i) => b + step[i]);
165
+ let halvings = 0;
166
+ let converged = false;
167
+ let iter = 0;
168
+ for (iter = 1; iter <= iterMax; iter++) {
169
+ ev = evaluateExact(sets, next);
170
+ const finite = Number.isFinite(ev.loglik) && ev.score.every(Number.isFinite);
171
+ // (no shortcut for an unchanged log likelihood: R's exact fit with only uninformative sets, 0 / 0, runs out)
172
+ if (finite && Math.abs(1 - best / ev.loglik) <= eps) {
173
+ converged = true;
174
+ beta = next;
175
+ break;
176
+ }
177
+ if (!finite || ev.loglik < best) {
178
+ halvings++;
179
+ next = next.map((b, i) => (b + halvings * beta[i]) / (halvings + 1));
180
+ accepted.push(beta);
181
+ }
182
+ else {
183
+ halvings = 0;
184
+ best = ev.loglik;
185
+ ({ f: factor } = factorOf(ev.info));
186
+ step = cholSolve(factor, ev.score);
187
+ beta = next;
188
+ accepted.push(beta);
189
+ next = next.map((b, i) => b + step[i]);
190
+ }
191
+ }
192
+ if (!converged) {
193
+ // R's exact fit reports iter.max iterations with the coefficients accepted at iteration max(1, iter.max - 1)
194
+ // (experiments/psm112-edge-iter.txt: iter.max = 1, 2, 3, 5 give the approximate fit's coefficients after 1, 1, 2, 4)
195
+ iter = iterMax;
196
+ beta = accepted[Math.max(1, iterMax - 1)] ?? beta;
197
+ warnings.push("Ran out of iterations and did not converge");
198
+ }
199
+ ev = evaluateExact(sets, beta);
200
+ loglik[1] = ev.loglik;
201
+ const fin = factorOf(ev.info);
202
+ const inverse = cholInverse(fin.f);
203
+ const coefficients = beta.map((b, j) => (fin.rank < p && inverse[j][j] === 0 ? NaN : b));
204
+ // Wald statistic beta' var^-1 beta over the coefficients kept
205
+ const kept = coefficients.map((c, j) => (Number.isNaN(c) ? -1 : j)).filter((j) => j >= 0);
206
+ let wald = 0;
207
+ for (const a of kept)
208
+ for (const b of kept)
209
+ wald += beta[a] * ev.info[a][b] * beta[b];
210
+ return finish(coefficients, inverse, loglik, score, wald, iter, "exact", warnings);
211
+ }
@@ -174,6 +174,15 @@ export interface CoxphResult {
174
174
  /** R's warnings, each once, in order of first appearance. */
175
175
  warnings: string[];
176
176
  }
177
+ /**
178
+ * Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
179
+ * set to 0. Returns the rank (negative when M is not non-negative definite).
180
+ */
181
+ export declare function cholFactor(m: number[][], tol: number): number;
182
+ /** Solves M y = b with the factor of {@link cholFactor} (0 for the dropped pivots) */
183
+ export declare function cholSolve(m: readonly number[][], b: readonly number[]): number[];
184
+ /** The (generalised) inverse from the factor of {@link cholFactor}, in place; returns the full symmetric matrix */
185
+ export declare function cholInverse(m: number[][]): number[][];
177
186
  /**
178
187
  * Cox proportional hazards regression. Equivalent to R's `survival::coxph()`. As
179
188
  * `coxph(Surv(time, status) ~ x ...)` for right-censored data and `coxph(Surv(start, stop, status) ~ x ...)` for
@@ -441,7 +441,7 @@ function scoreResidualsCounting(data, beta, efron) {
441
441
  * Generalised Cholesky factorisation M = L D L' in place (D on the diagonal, L below it), pivots below the tolerance
442
442
  * set to 0. Returns the rank (negative when M is not non-negative definite).
443
443
  */
444
- function cholFactor(m, tol) {
444
+ export function cholFactor(m, tol) {
445
445
  const p = m.length;
446
446
  let scale = 0;
447
447
  let anyPositive = false;
@@ -481,7 +481,7 @@ function cholFactor(m, tol) {
481
481
  return nonNegative ? rank : -rank;
482
482
  }
483
483
  /** Solves M y = b with the factor of {@link cholFactor} (0 for the dropped pivots) */
484
- function cholSolve(m, b) {
484
+ export function cholSolve(m, b) {
485
485
  const p = m.length;
486
486
  const y = b.slice();
487
487
  for (let i = 0; i < p; i++) {
@@ -503,7 +503,7 @@ function cholSolve(m, b) {
503
503
  return y;
504
504
  }
505
505
  /** The (generalised) inverse from the factor of {@link cholFactor}, in place; returns the full symmetric matrix */
506
- function cholInverse(m) {
506
+ export function cholInverse(m) {
507
507
  const p = m.length;
508
508
  for (let i = 0; i < p; i++) {
509
509
  if (!(m[i][i] > 0))
@@ -0,0 +1,120 @@
1
+ /** A contingency table with optional row and column labels.
2
+ * @category Multivariate analysis
3
+ */
4
+ export interface CaInputTable {
5
+ /** Row labels, or null when the rows are unnamed. */
6
+ rows: string[] | null;
7
+ /** Column labels, or null when the columns are unnamed. */
8
+ cols: string[] | null;
9
+ /** Non-negative cell counts, arranged as rows. */
10
+ values: readonly (readonly number[])[];
11
+ }
12
+ /** Options for simple correspondence analysis. Equivalent to R's ca::ca().
13
+ * @category Multivariate analysis
14
+ */
15
+ export interface CaOptions {
16
+ /** Number of dimensions to retain in the returned coordinates. */
17
+ nd?: number;
18
+ /** One-based indices of supplementary rows, excluded from the active analysis. */
19
+ suprow?: number | readonly number[];
20
+ /** One-based indices of supplementary columns, excluded from the active analysis. */
21
+ supcol?: number | readonly number[];
22
+ }
23
+ /** A labelled numeric matrix returned by correspondence analysis.
24
+ * @category Multivariate analysis
25
+ */
26
+ export interface CaMatrix {
27
+ /** Row labels, or null when unnamed. */
28
+ rows: string[] | null;
29
+ /** Column labels, or null when unnamed. */
30
+ cols: string[] | null;
31
+ /** Matrix values in row-major order. */
32
+ values: number[][];
33
+ }
34
+ /** Result of simple correspondence analysis.
35
+ * @category Multivariate analysis
36
+ */
37
+ export interface CaFit {
38
+ /** Singular values of the standardized residual matrix. */
39
+ sv: number[];
40
+ /** Number of retained dimensions, or "NA" when not specified. */
41
+ nd: number | "NA";
42
+ /** Original row labels. */
43
+ rownames: string[] | null;
44
+ /** Row masses in the active table. */
45
+ rowmass: number[];
46
+ /** Chi-square distances of rows from the column profile centroid. */
47
+ rowdist: number[];
48
+ /** Row contributions to total inertia. */
49
+ rowinertia: number[];
50
+ /** Standard row coordinates, including supplementary rows. */
51
+ rowcoord: CaMatrix;
52
+ /** One-based indices of supplementary rows. */
53
+ rowsup: number[];
54
+ /** Original column labels. */
55
+ colnames: string[] | null;
56
+ /** Column masses in the active table. */
57
+ colmass: number[];
58
+ /** Chi-square distances of columns from the row profile centroid. */
59
+ coldist: number[];
60
+ /** Column contributions to total inertia. */
61
+ colinertia: number[];
62
+ /** Standard column coordinates, including supplementary columns. */
63
+ colcoord: CaMatrix;
64
+ /** One-based indices of supplementary columns. */
65
+ colsup: number[];
66
+ /** Active contingency table after supplementary rows and columns are removed. */
67
+ N: CaMatrix;
68
+ }
69
+ /** Summary tables for eigenvalues, rows and columns.
70
+ * @category Multivariate analysis
71
+ */
72
+ export interface CaSummary {
73
+ /** Eigenvalues, percentages of inertia and cumulative percentages. */
74
+ scree: CaMatrix;
75
+ /** Row mass, quality, inertia and axis contributions. */
76
+ rows: CaMatrix;
77
+ /** Column mass, quality, inertia and axis contributions. */
78
+ columns: CaMatrix;
79
+ }
80
+ /** Options for constructing a correspondence-analysis map.
81
+ * @category Multivariate analysis
82
+ */
83
+ export interface CaCoordOptions {
84
+ /** Coordinate scaling convention for the row and column maps. */
85
+ type?: "standard" | "principal" | "symmetric" | "rowprincipal" | "colprincipal" | "symbiplot" | "rowgab" | "colgab" | "rowgreen" | "colgreen";
86
+ /** One-based dimensions to include. */
87
+ dim?: readonly number[];
88
+ /** Whether to return only row coordinates. */
89
+ rows?: boolean;
90
+ /** Whether to return only column coordinates. */
91
+ cols?: boolean;
92
+ }
93
+ /**
94
+ * Computes simple correspondence analysis of a contingency table.
95
+ * Equivalent to R's `ca::ca()`.
96
+ * @category Multivariate analysis
97
+ */
98
+ export declare function ca(input: readonly (readonly number[])[] | CaInputTable, options?: CaOptions): CaFit;
99
+ /**
100
+ * Summarizes eigenvalues and row and column contributions from correspondence analysis.
101
+ * Equivalent to R's `summary.ca()`.
102
+ * @category Multivariate analysis
103
+ */
104
+ export declare function caSummary(result: CaFit): CaSummary;
105
+ /**
106
+ * The row and column coordinates of a correspondence-analysis map, returned by `caCoord` when both are requested.
107
+ * @category Multivariate analysis
108
+ */
109
+ export interface CaCoordMaps {
110
+ /** Row coordinates (one row per active and supplementary row, one column per dimension). */
111
+ rows: CaMatrix;
112
+ /** Column coordinates (one row per active and supplementary column, one column per dimension). */
113
+ columns: CaMatrix;
114
+ }
115
+ /**
116
+ * Computes row and column coordinates for a correspondence-analysis map.
117
+ * Equivalent to R's `ca::cacoord()`.
118
+ * @category Multivariate analysis
119
+ */
120
+ export declare function caCoord(result: CaFit, options?: CaCoordOptions): CaMatrix | CaCoordMaps;
@@ -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,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;