@numero-uno-jpn/rstats 0.9.0 → 0.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 (142) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.ja.md +64 -12
  3. package/README.md +63 -11
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/chunk-5WDJPHYY.js +2 -0
  6. package/dist/chunks/chunk-7GQMKH3Z.js +2 -0
  7. package/dist/chunks/chunk-AHHS6AC4.js +3 -0
  8. package/dist/chunks/chunk-ALM3VHFP.js +2 -0
  9. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-C5XTWMGB.js} +1 -1
  10. package/dist/chunks/chunk-CGBNKHNZ.js +2 -0
  11. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-EZAFN5CD.js} +1 -1
  12. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-EZWBRCJL.js} +1 -1
  13. package/dist/chunks/chunk-F5EDJFEO.js +2 -0
  14. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-JWBO5WVN.js} +2 -2
  15. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-TOGXTCZO.js} +2 -2
  16. package/dist/chunks/chunk-VJ4BDBMU.js +3 -0
  17. package/dist/chunks/chunk-Y5CNQ266.js +2 -0
  18. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-Y5PYRAYP.js} +2 -2
  19. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-YSWGDOWK.js} +2 -2
  20. package/dist/data/grouping.d.ts +79 -0
  21. package/dist/data/grouping.js +262 -0
  22. package/dist/descriptive/dataFrames.d.ts +110 -0
  23. package/dist/descriptive/dataFrames.js +392 -0
  24. package/dist/descriptive/factanal.d.ts +56 -0
  25. package/dist/descriptive/factanal.js +186 -0
  26. package/dist/descriptive/missing.d.ts +35 -0
  27. package/dist/descriptive/missing.js +50 -0
  28. package/dist/descriptive/omega.d.ts +56 -0
  29. package/dist/descriptive/omega.js +323 -0
  30. package/dist/descriptive/pivot.d.ts +89 -0
  31. package/dist/descriptive/pivot.js +343 -0
  32. package/dist/descriptive.js +2 -2
  33. package/dist/distributions/bvnorm.d.ts +15 -0
  34. package/dist/distributions/bvnorm.js +131 -0
  35. package/dist/distributions/nbeta.js +34 -1
  36. package/dist/distributions/nchisq.d.ts +10 -0
  37. package/dist/distributions/nchisq.js +46 -0
  38. package/dist/distributions.js +2 -2
  39. package/dist/entries/descriptive.d.ts +4 -0
  40. package/dist/entries/descriptive.js +4 -0
  41. package/dist/entries/distributions.d.ts +1 -0
  42. package/dist/entries/distributions.js +1 -0
  43. package/dist/entries/linalg.d.ts +2 -0
  44. package/dist/entries/linalg.js +2 -0
  45. package/dist/entries/numerics.d.ts +2 -0
  46. package/dist/entries/numerics.js +1 -0
  47. package/dist/entries/tests.d.ts +22 -1
  48. package/dist/entries/tests.js +19 -1
  49. package/dist/htest/agreement.d.ts +141 -0
  50. package/dist/htest/agreement.js +274 -0
  51. package/dist/htest/ansariTest.d.ts +12 -0
  52. package/dist/htest/ansariTest.js +5 -17
  53. package/dist/htest/aov.d.ts +19 -0
  54. package/dist/htest/aov.js +22 -15
  55. package/dist/htest/cor.d.ts +12 -0
  56. package/dist/htest/cor.js +9 -27
  57. package/dist/htest/core/simulate.d.ts +2 -0
  58. package/dist/htest/core/simulate.js +1 -1
  59. package/dist/htest/dunnett.d.ts +5 -0
  60. package/dist/htest/dunnett.js +89 -0
  61. package/dist/htest/effectSize.d.ts +112 -0
  62. package/dist/htest/effectSize.js +385 -0
  63. package/dist/htest/ksTest.d.ts +13 -0
  64. package/dist/htest/ksTest.js +5 -8
  65. package/dist/htest/leveneTest.d.ts +30 -0
  66. package/dist/htest/leveneTest.js +41 -0
  67. package/dist/htest/multipleComparisons.d.ts +147 -0
  68. package/dist/htest/multipleComparisons.js +369 -0
  69. package/dist/htest/normalityTests.d.ts +44 -0
  70. package/dist/htest/normalityTests.js +164 -0
  71. package/dist/htest/onewayTest.d.ts +14 -0
  72. package/dist/htest/onewayTest.js +5 -7
  73. package/dist/htest/polycor.d.ts +117 -0
  74. package/dist/htest/polycor.js +468 -0
  75. package/dist/htest/power.d.ts +132 -0
  76. package/dist/htest/power.js +227 -0
  77. package/dist/htest/pwr.d.ts +263 -0
  78. package/dist/htest/pwr.js +440 -0
  79. package/dist/htest/rankTests.d.ts +64 -0
  80. package/dist/htest/rankTests.js +27 -29
  81. package/dist/htest/tTest.d.ts +20 -0
  82. package/dist/htest/tTest.js +19 -24
  83. package/dist/htest/testFormula.d.ts +57 -0
  84. package/dist/htest/testFormula.js +171 -0
  85. package/dist/htest/trendTests.d.ts +57 -0
  86. package/dist/htest/trendTests.js +167 -0
  87. package/dist/htest/varTest.d.ts +23 -0
  88. package/dist/htest/varTest.js +11 -21
  89. package/dist/htest/wilcoxTest.d.ts +14 -0
  90. package/dist/htest/wilcoxTest.js +9 -24
  91. package/dist/linalg/eigen.d.ts +8 -0
  92. package/dist/linalg/eigen.js +5 -4
  93. package/dist/linalg/expm.d.ts +48 -0
  94. package/dist/linalg/expm.js +472 -0
  95. package/dist/linalg/ops.d.ts +13 -2
  96. package/dist/linalg/ops.js +20 -5
  97. package/dist/linalg/schur.d.ts +48 -0
  98. package/dist/linalg/schur.js +225 -0
  99. package/dist/linalg.js +2 -2
  100. package/dist/models/anovaSequential.d.ts +58 -0
  101. package/dist/models/anovaSequential.js +138 -0
  102. package/dist/models/aovEz.d.ts +64 -0
  103. package/dist/models/aovEz.js +332 -0
  104. package/dist/models/aovStrata.d.ts +32 -0
  105. package/dist/models/aovStrata.js +104 -0
  106. package/dist/models/carAnova.d.ts +30 -0
  107. package/dist/models/carAnova.js +121 -0
  108. package/dist/models/coxph.d.ts +101 -0
  109. package/dist/models/coxph.js +502 -0
  110. package/dist/models/ddLeastSquares.d.ts +30 -0
  111. package/dist/models/ddLeastSquares.js +90 -0
  112. package/dist/models/ddMatrix.d.ts +10 -0
  113. package/dist/models/ddMatrix.js +91 -0
  114. package/dist/models/formula.d.ts +83 -0
  115. package/dist/models/formula.js +333 -0
  116. package/dist/models/lm.d.ts +84 -3
  117. package/dist/models/lm.js +141 -44
  118. package/dist/models/mauchly.d.ts +48 -0
  119. package/dist/models/mauchly.js +123 -0
  120. package/dist/models/modelFrame.d.ts +40 -0
  121. package/dist/models/modelFrame.js +131 -0
  122. package/dist/models/modelMatrix.d.ts +88 -0
  123. package/dist/models/modelMatrix.js +170 -0
  124. package/dist/models/survival.d.ts +87 -0
  125. package/dist/models/survival.js +238 -0
  126. package/dist/numerics.js +2 -2
  127. package/dist/optim/lbfgsb.d.ts +20 -0
  128. package/dist/optim/lbfgsb.js +1240 -0
  129. package/dist/optim/optim.d.ts +85 -0
  130. package/dist/optim/optim.js +610 -0
  131. package/dist/rstats.js +19 -4
  132. package/dist/special.js +2 -2
  133. package/dist/tests.js +17 -4
  134. package/llms.txt +114 -0
  135. package/package.json +3 -2
  136. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  137. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  138. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  139. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  140. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  141. package/dist/chunks/chunk-YC4JWUKG.js +0 -2
  142. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -23,32 +23,17 @@ import { pwilcox1, qwilcox1 } from "../distributions/wilcox.js";
23
23
  import { pnorm, qnorm } from "../distributions/normal.js";
24
24
  import { completePairs, dropNaN, mean, rank, tieCounts, } from "../internal/summary.js";
25
25
  import { uniroot } from "../internal/uniroot.js";
26
+ import { twoSampleData } from "./testFormula.js";
26
27
  import { matchAlternative } from "./types.js";
27
- /**
28
- * Wilcoxon signed rank and rank sum (Mann-Whitney) tests. Equivalent to R's `wilcox.test()`.
29
- *
30
- * With one sample (or `paired: true`) performs the signed rank test; with two samples the
31
- * rank sum test. The choice between exact and normal-approximation p-values, the
32
- * Hodges-Lehmann estimates and the confidence intervals follow R, including R's behavior
33
- * when the requested confidence level cannot be reached. Only `NaN` is dropped; infinite
34
- * values are kept and ranked (as R actually does).
35
- *
36
- * @param x Sample.
37
- * @param y Second sample for a two-sample or paired test. May be omitted, and the options
38
- * passed in its place: `wilcoxTest(x, { mu: 1 })`.
39
- * @param options See {@link WilcoxTestOptions}.
40
- * @returns The test result; see {@link WilcoxTestResult}.
41
- *
42
- * @example
43
- * ```ts
44
- * const x = [1.83, 0.50, 1.62, 2.48, 1.68, 1.88, 1.55, 3.06, 1.30];
45
- * const y = [0.878, 0.647, 0.598, 2.05, 1.06, 1.29, 1.06, 3.14, 1.29];
46
- * const r = wilcoxTest(x, y, { paired: true, alternative: "greater" });
47
- * r.statistic; // 40 (V)
48
- * r.pValue; // 0.01953125
49
- * ```
50
- */
51
28
  export function wilcoxTest(x, y, options = {}) {
29
+ if (typeof x === "string") {
30
+ if (options.paired !== undefined)
31
+ throw new Error("cannot use 'paired' in formula method");
32
+ const d = twoSampleData(x, y, true);
33
+ if (d.kind === "one")
34
+ return wilcoxTest(d.x, options);
35
+ return wilcoxTest(d.x, d.y, d.kind === "paired" ? { ...options, paired: true } : options);
36
+ }
52
37
  // Also accept the form wilcoxTest(x, { mu: 1 })
53
38
  let ys;
54
39
  if (y !== undefined && !ArrayBuffer.isView(y) && !Array.isArray(y))
@@ -50,3 +50,11 @@ export interface EigenResult {
50
50
  export declare function eigen(x: MatrixInput, options?: EigenOptions): EigenResult;
51
51
  /** Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)) */
52
52
  export declare function isSymmetric(a: Mat): boolean;
53
+ /** Reduce to Hessenberg form by Householder transformations (orthes). V becomes the product of the transformations */
54
+ export declare function orthes(H: Mat, V: Mat): void;
55
+ /**
56
+ * Reduce a Hessenberg matrix to real Schur form by the double-shift QR method and compute eigenvalues (d + i e) and eigenvectors (columns of V) (hqr2).
57
+ * For a complex pair, the eigenvector of d[j] + i e[j] (e[j] > 0) is V[:, j] + i V[:, j+1].
58
+ * With schurOnly, stops at the real Schur form (H = V' A V up to the negligible subdiagonal elements, V orthogonal; used by schur)
59
+ */
60
+ export declare function hqr2(Hm: Mat, Vm: Mat, d: Float64Array, e: Float64Array, schurOnly?: boolean): void;
@@ -348,7 +348,7 @@ function normalizeVectors(re, im) {
348
348
  }
349
349
  }
350
350
  /** Reduce to Hessenberg form by Householder transformations (orthes). V becomes the product of the transformations */
351
- function orthes(H, V) {
351
+ export function orthes(H, V) {
352
352
  const n = H.nrow;
353
353
  const h = H.data;
354
354
  const v = V.data;
@@ -425,9 +425,10 @@ function cdiv(xr, xi, yr, yi) {
425
425
  }
426
426
  /**
427
427
  * Reduce a Hessenberg matrix to real Schur form by the double-shift QR method and compute eigenvalues (d + i e) and eigenvectors (columns of V) (hqr2).
428
- * For a complex pair, the eigenvector of d[j] + i e[j] (e[j] > 0) is V[:, j] + i V[:, j+1]
428
+ * For a complex pair, the eigenvector of d[j] + i e[j] (e[j] > 0) is V[:, j] + i V[:, j+1].
429
+ * With schurOnly, stops at the real Schur form (H = V' A V up to the negligible subdiagonal elements, V orthogonal; used by schur)
429
430
  */
430
- function hqr2(Hm, Vm, d, e) {
431
+ export function hqr2(Hm, Vm, d, e, schurOnly = false) {
431
432
  const nn = Hm.nrow;
432
433
  const H = Hm.data;
433
434
  const V = Vm.data;
@@ -644,7 +645,7 @@ function hqr2(Hm, Vm, d, e) {
644
645
  }
645
646
  }
646
647
  // Eigenvectors of the upper triangular (real Schur) form by back substitution
647
- if (norm === 0)
648
+ if (norm === 0 || schurOnly)
648
649
  return;
649
650
  for (n = nn - 1; n >= 0; n--) {
650
651
  p = d[n];
@@ -0,0 +1,48 @@
1
+ import { type Mat, type MatrixInput } from "./matrix.js";
2
+ /** Methods of {@link expm}. */
3
+ export type ExpmMethod = "Higham08.b" | "Higham08" | "Pade" | "Taylor" | "PadeO" | "TaylorO";
4
+ /** Options for {@link expm}. */
5
+ export interface ExpmOptions {
6
+ /**
7
+ * `"Higham08.b"` (default): Higham's scaling and squaring with Padé approximants after balancing (LAPACK's
8
+ * `dgebal`, permutation then scaling). `"Higham08"`: the same without balancing. `"Pade"` and `"Taylor"` (and
9
+ * `"PadeO"`, `"TaylorO"`, which compute the same): scaling and squaring with a diagonal Padé approximant or a
10
+ * Taylor polynomial of degree `order` (Shapira and Firth's code in the expm package).
11
+ */
12
+ method?: ExpmMethod;
13
+ /**
14
+ * Degree of the Padé approximant or the Taylor polynomial (a positive integer), used only by `"Pade"`, `"Taylor"`,
15
+ * `"PadeO"` and `"TaylorO"`. Default: 8.
16
+ */
17
+ order?: number;
18
+ }
19
+ /**
20
+ * Matrix exponential. Equivalent to R's `expm::expm(x, method, order)` with methods `"Higham08.b"` (the default),
21
+ * `"Higham08"`, `"Pade"`, `"Taylor"`, `"PadeO"` and `"TaylorO"`.
22
+ *
23
+ * `"Higham08.b"` and `"Higham08"` use the scaling and squaring method with Padé approximants of degree 3, 5, 7, 9 or
24
+ * 13 (Higham 2005), with or without balancing first, and throw if a linear system of the method is computationally
25
+ * singular. The other methods use scaling and squaring with a Taylor polynomial or a diagonal Padé approximant of
26
+ * degree `order` (the Padé quotient by the conjugate gradient squared method, as expm does).
27
+ *
28
+ * @param x A square matrix (array of rows).
29
+ * @param options See {@link ExpmOptions}.
30
+ * @returns `exp(x)` as an array of rows.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * expm([[0, 1], [0, 0]]); // [[1, 1], [0, 1]]
35
+ * expm([[0, -1], [1, 0]]); // [[cos 1, -sin 1], [sin 1, cos 1]] (up to rounding)
36
+ * ```
37
+ */
38
+ export declare function expm(x: MatrixInput, options?: ExpmOptions): number[][];
39
+ /**
40
+ * Balancing (dgebal) with job "P" (permute only) or "S" (scale only); A is overwritten. Indices are 0-based:
41
+ * scale[i] holds the index of the row and column interchanged with i for i < ilo and i > ihi, and the scaling factor
42
+ * for ilo <= i <= ihi
43
+ */
44
+ export declare function gebal(job: "P" | "S", A: Mat): {
45
+ ilo: number;
46
+ ihi: number;
47
+ scale: Float64Array;
48
+ };
@@ -0,0 +1,472 @@
1
+ // Matrix exponential (the expm package's expm, methods "Higham08.b", "Higham08", "Pade", "Taylor", "PadeO" and
2
+ // "TaylorO"). Written for rStats.js.
3
+ //
4
+ // Sources: the specification oracle/matfn-behaviour.md; the scaling and squaring method with Padé approximants of
5
+ // N. J. Higham, "The scaling and squaring method for the matrix exponential revisited", SIAM J. Matrix Anal. Appl.
6
+ // 26 (2005) 1179-1193 (degrees 3, 5, 7, 9 and 13, the bounds on the 1-norm and the Padé coefficients);
7
+ // the balancing is a port of LAPACK 3.12.0's SRC/dgebal.f (modified BSD; see THIRD_PARTY_NOTICES.md).
8
+ // - "Higham08.b" (default) balances first: dgebal with job "P" (permutation), then dgebal with job "S" (scaling) on
9
+ // the result, as two separate calls; "Higham08" does not balance
10
+ // - The Padé degree is chosen from the 1-norm of the (balanced) matrix; above 2.1, degree 13 with scaling by 2^-s
11
+ // - X = (V - U)^-1 (V + U) is solved by LU decomposition as solve (which throws if V - U is computationally
12
+ // singular), then squared s times, and the balancing is undone
13
+ // - dgebal's DNRM2 is computed with the classic scaled sum of squares rather than reference BLAS 3.12's algorithm
14
+ // (it only decides between powers of 2 in the scaling; the results may differ in rare borderline cases)
15
+ // - "Pade", "Taylor", "PadeO", "TaylorO" (Shapira and Firth's methods, as the specification describes them): scaling
16
+ // by N = 2^p with p from sqrt(1-norm x infinity-norm), a Taylor polynomial or a diagonal Padé approximant of degree
17
+ // order (default 8) by Horner's rule, the Padé quotient by the conjugate gradient squared method column by column,
18
+ // then squaring p times. In R the "O" variants differ only in using plain loops instead of BLAS; here all four use
19
+ // plain loops in index order
20
+ // - A 1 x 1 matrix gives exp of its entry, a 0 x 0 matrix gives a 0 x 0 matrix
21
+ import { fromMat, newMat, requireSquare, toMat } from "./matrix.js";
22
+ import { infNorm, oneNorm } from "./norm.js";
23
+ import { solve } from "./solve.js";
24
+ const METHODS = ["Higham08.b", "Higham08", "Pade", "Taylor", "PadeO", "TaylorO"];
25
+ /**
26
+ * Matrix exponential. Equivalent to R's `expm::expm(x, method, order)` with methods `"Higham08.b"` (the default),
27
+ * `"Higham08"`, `"Pade"`, `"Taylor"`, `"PadeO"` and `"TaylorO"`.
28
+ *
29
+ * `"Higham08.b"` and `"Higham08"` use the scaling and squaring method with Padé approximants of degree 3, 5, 7, 9 or
30
+ * 13 (Higham 2005), with or without balancing first, and throw if a linear system of the method is computationally
31
+ * singular. The other methods use scaling and squaring with a Taylor polynomial or a diagonal Padé approximant of
32
+ * degree `order` (the Padé quotient by the conjugate gradient squared method, as expm does).
33
+ *
34
+ * @param x A square matrix (array of rows).
35
+ * @param options See {@link ExpmOptions}.
36
+ * @returns `exp(x)` as an array of rows.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * expm([[0, 1], [0, 0]]); // [[1, 1], [0, 1]]
41
+ * expm([[0, -1], [1, 0]]); // [[cos 1, -sin 1], [sin 1, cos 1]] (up to rounding)
42
+ * ```
43
+ */
44
+ export function expm(x, options = {}) {
45
+ const method = options.method ?? "Higham08.b";
46
+ if (!METHODS.includes(method))
47
+ throw new RangeError(`unknown method: ${String(method)}`);
48
+ const order = options.order ?? 8;
49
+ if (!Number.isInteger(order) || order < 1)
50
+ throw new RangeError("order must be a positive integer");
51
+ const A = toMat(x);
52
+ requireSquare(A);
53
+ const n = A.nrow;
54
+ if (n === 0)
55
+ return [];
56
+ if (n === 1)
57
+ return [[Math.exp(A.data[0])]];
58
+ if (method === "Taylor" || method === "TaylorO")
59
+ return fromMat(taylorScaled(A, order));
60
+ if (method === "Pade" || method === "PadeO")
61
+ return fromMat(padeScaled(A, order));
62
+ let perm;
63
+ let scaling;
64
+ if (method === "Higham08.b") {
65
+ perm = gebal("P", A);
66
+ scaling = gebal("S", A);
67
+ }
68
+ const X = pade(A);
69
+ const x_ = X.data;
70
+ const at = (i, j) => i + j * n;
71
+ if (scaling) {
72
+ const d = scaling.scale;
73
+ for (let j = 0; j < n; j++)
74
+ for (let i = 0; i < n; i++)
75
+ x_[at(i, j)] = (x_[at(i, j)] * d[i]) / d[j];
76
+ }
77
+ if (perm) {
78
+ const p = perm.scale;
79
+ const swap = (i) => {
80
+ const k = p[i];
81
+ if (k === i)
82
+ return;
83
+ for (let r = 0; r < n; r++)
84
+ [x_[at(r, i)], x_[at(r, k)]] = [x_[at(r, k)], x_[at(r, i)]];
85
+ for (let c = 0; c < n; c++)
86
+ [x_[at(i, c)], x_[at(k, c)]] = [x_[at(k, c)], x_[at(i, c)]];
87
+ };
88
+ for (let i = perm.ilo - 1; i >= 0; i--)
89
+ swap(i);
90
+ for (let i = perm.ihi + 1; i < n; i++)
91
+ swap(i);
92
+ }
93
+ return fromMat(X);
94
+ }
95
+ /** Padé coefficients b_0 ... b_m (Higham 2005, Table 10.4) */
96
+ const PADE = {
97
+ 3: [120, 60, 12, 1],
98
+ 5: [30240, 15120, 3360, 420, 30, 1],
99
+ 7: [17297280, 8648640, 1995840, 277200, 25200, 1512, 56, 1],
100
+ 9: [17643225600, 8821612800, 2075673600, 302702400, 30270240, 2162160, 110880, 3960, 90, 1],
101
+ };
102
+ const PADE13 = [
103
+ 64764752532480000, 32382376266240000, 7771770303897600, 1187353796428800, 129060195264000, 10559470521600,
104
+ 670442572800, 33522128640, 1323241920, 40840800, 960960, 16380, 182, 1,
105
+ ];
106
+ /** Scaling and squaring with a Padé approximant: exp(A) for the (balanced) matrix A */
107
+ function pade(A) {
108
+ const n = A.nrow;
109
+ const nu = oneNorm(A);
110
+ const I = identity(n);
111
+ let U;
112
+ let V;
113
+ let s = 0;
114
+ if (nu <= 2.1) {
115
+ const m = nu <= 0.015 ? 3 : nu <= 0.25 ? 5 : nu <= 0.95 ? 7 : 9;
116
+ const b = PADE[m];
117
+ const A2 = mul(A, A);
118
+ // P_k = A2^k for k = 1 ... (m - 1) / 2, accumulated in increasing order
119
+ const u = comb([[b[1], I]]);
120
+ const v = comb([[b[0], I]]);
121
+ let P = A2;
122
+ for (let k = 1; k <= (m - 1) / 2; k++) {
123
+ if (k > 1)
124
+ P = mul(P, A2);
125
+ axpy(u, b[2 * k + 1], P);
126
+ axpy(v, b[2 * k], P);
127
+ }
128
+ U = mul(A, u);
129
+ V = v;
130
+ }
131
+ else {
132
+ s = Math.max(0, Math.ceil(Math.log2(nu / 5.4)));
133
+ const B = scale(A, 1 / 2 ** s);
134
+ const B2 = mul(B, B);
135
+ const B4 = mul(B2, B2);
136
+ const B6 = mul(B2, B4);
137
+ const c = PADE13;
138
+ const u1 = comb([[c[13], B6], [c[11], B4], [c[9], B2]]);
139
+ const u2 = mul(B6, u1);
140
+ for (const [k, M] of [[7, B6], [5, B4], [3, B2], [1, I]])
141
+ axpy(u2, c[k], M);
142
+ U = mul(B, u2);
143
+ const v1 = comb([[c[12], B6], [c[10], B4], [c[8], B2]]);
144
+ V = mul(B6, v1);
145
+ for (const [k, M] of [[6, B6], [4, B4], [2, B2], [0, I]])
146
+ axpy(V, c[k], M);
147
+ }
148
+ const vmu = newMat(n, n);
149
+ const vpu = newMat(n, n);
150
+ for (let i = 0; i < n * n; i++) {
151
+ vmu.data[i] = V.data[i] - U.data[i];
152
+ vpu.data[i] = V.data[i] + U.data[i];
153
+ }
154
+ let X = toMat(solve(fromMat(vmu), fromMat(vpu)));
155
+ for (let k = 0; k < s; k++)
156
+ X = mul(X, X);
157
+ return X;
158
+ }
159
+ /**
160
+ * Exponent p of the scaling by N = 2^p (Shapira and Firth): with nu = sqrt(|A|_1 |A|_inf), L >= 1 the smallest with
161
+ * 2^L >= nu, p = L + 4
162
+ */
163
+ function scalingExponent(A) {
164
+ const nu = Math.sqrt(oneNorm(A) * infNorm(A));
165
+ let L = 1;
166
+ while (2 ** L < nu)
167
+ L++;
168
+ return L + 4;
169
+ }
170
+ /** R <- R R, p times */
171
+ function squareRepeatedly(R, p) {
172
+ for (let k = 0; k < p; k++)
173
+ R = mul(R, R);
174
+ return R;
175
+ }
176
+ /** M_ii <- M_ii + 1 */
177
+ function addIdentity(M) {
178
+ const n = M.nrow;
179
+ for (let i = 0; i < n; i++)
180
+ M.data[i + i * n] = M.data[i + i * n] + 1;
181
+ }
182
+ /** "Taylor": S = I, then S <- (S A) (1 / (j N)) + I for j = order ... 1, then squared p times */
183
+ function taylorScaled(A, order) {
184
+ const p = scalingExponent(A);
185
+ const N = 2 ** p;
186
+ let S = identity(A.nrow);
187
+ for (let j = order; j >= 1; j--) {
188
+ S = scale(mul(S, A), 1 / (j * N));
189
+ addIdentity(S);
190
+ }
191
+ return squareRepeatedly(S, p);
192
+ }
193
+ /** Padé numerator (sign 1) or denominator (sign -1) by Horner's rule: P = I, then P <- (P (sign A)) c_j + I */
194
+ function padeHorner(A, order, N, sign) {
195
+ const signedA = sign === 1 ? A : scale(A, -1);
196
+ let P = identity(A.nrow);
197
+ for (let j = order; j >= 1; j--) {
198
+ const c = (order - j + 1) / (j * (2 * order - j + 1) * N);
199
+ P = scale(mul(P, signedA), c);
200
+ addIdentity(P);
201
+ }
202
+ return P;
203
+ }
204
+ /** "Pade": the diagonal Padé approximant of degree order, Q^-1 P column by column by CGS, then squared p times */
205
+ function padeScaled(A, order) {
206
+ const n = A.nrow;
207
+ const p = scalingExponent(A);
208
+ const N = 2 ** p;
209
+ const numer = padeHorner(A, order, N, 1);
210
+ const denom = padeHorner(A, order, N, -1);
211
+ const R = newMat(n, n);
212
+ for (let i = 0; i < n; i++) {
213
+ R.data.set(conjugateGradientSquared(denom, numer.data.subarray(i * n, (i + 1) * n)), i * n);
214
+ }
215
+ return squareRepeatedly(R, p);
216
+ }
217
+ /** Conjugate gradient squared for M x = f, at most n iterations (as Shapira and Firth's code) */
218
+ function conjugateGradientSquared(M, f) {
219
+ const n = M.nrow;
220
+ const TINY = 1e-100;
221
+ const matVec = (v) => {
222
+ const y = new Float64Array(n);
223
+ for (let i = 0; i < n; i++) {
224
+ let s = 0;
225
+ for (let l = 0; l < n; l++)
226
+ s += M.data[i + l * n] * v[l];
227
+ y[i] = s;
228
+ }
229
+ return y;
230
+ };
231
+ const dot = (u, v) => {
232
+ let s = 0;
233
+ for (let i = 0; i < n; i++)
234
+ s += u[i] * v[i];
235
+ return s;
236
+ };
237
+ /** u + a v */
238
+ const plus = (u, a, v) => {
239
+ const y = new Float64Array(n);
240
+ for (let i = 0; i < n; i++)
241
+ y[i] = u[i] + a * v[i];
242
+ return y;
243
+ };
244
+ let x = new Float64Array(n);
245
+ let rc = Float64Array.from(f);
246
+ let dir = Float64Array.from(f);
247
+ let u = Float64Array.from(f);
248
+ const rbar = Float64Array.from(f);
249
+ const omegaInit = Math.sqrt(dot(rc, rc));
250
+ let rho0 = dot(rbar, f);
251
+ if (Math.abs(rho0) <= TINY)
252
+ return x;
253
+ for (let iter = 0; iter < n; iter++) {
254
+ let v = matVec(dir);
255
+ const sigma = dot(rbar, v);
256
+ if (Math.abs(sigma) <= TINY)
257
+ return x;
258
+ const alpha = rho0 / sigma;
259
+ if (Math.abs(alpha) <= TINY)
260
+ return x;
261
+ const q = plus(u, -alpha, v);
262
+ v = plus(u, 1, q);
263
+ let s = matVec(v);
264
+ rc = plus(rc, -alpha, s);
265
+ const omega1 = Math.sqrt(dot(rc, rc));
266
+ x = plus(x, alpha, v);
267
+ if (Math.abs(omega1 / omegaInit) <= 1e-30)
268
+ return x;
269
+ const rho1 = dot(rbar, rc);
270
+ if (Math.abs(rho1) <= TINY)
271
+ return x;
272
+ const beta = rho1 / rho0;
273
+ rho0 = rho1;
274
+ u = plus(rc, beta, q);
275
+ s = plus(q, beta, dir);
276
+ dir = plus(u, beta, s);
277
+ }
278
+ return x;
279
+ }
280
+ function identity(n) {
281
+ const I = newMat(n, n);
282
+ for (let i = 0; i < n; i++)
283
+ I.data[i + i * n] = 1;
284
+ return I;
285
+ }
286
+ /** Matrix product (inner products in increasing order of the summation index) */
287
+ function mul(A, B) {
288
+ const n = A.nrow;
289
+ const p = A.ncol;
290
+ const q = B.ncol;
291
+ const C = newMat(n, q);
292
+ for (let j = 0; j < q; j++) {
293
+ for (let i = 0; i < n; i++) {
294
+ let s = 0;
295
+ for (let k = 0; k < p; k++)
296
+ s += A.data[i + k * n] * B.data[k + j * p];
297
+ C.data[i + j * n] = s;
298
+ }
299
+ }
300
+ return C;
301
+ }
302
+ function scale(A, f) {
303
+ return { nrow: A.nrow, ncol: A.ncol, data: A.data.map((v) => v * f) };
304
+ }
305
+ /** Y <- Y + a M */
306
+ function axpy(Y, a, M) {
307
+ for (let i = 0; i < Y.data.length; i++)
308
+ Y.data[i] = Y.data[i] + a * M.data[i];
309
+ }
310
+ /** a_1 M_1 + a_2 M_2 + ..., summed from left to right */
311
+ function comb(terms) {
312
+ const [a0, M0] = terms[0];
313
+ const Y = scale(M0, a0);
314
+ for (let t = 1; t < terms.length; t++)
315
+ axpy(Y, terms[t][0], terms[t][1]);
316
+ return Y;
317
+ }
318
+ /** 2-norm of n values a[o], a[o + stride], ... (scaled sum of squares) */
319
+ function nrm2(a, o, count, stride) {
320
+ let sc = 0;
321
+ let ssq = 1;
322
+ for (let k = 0; k < count; k++) {
323
+ const v = a[o + k * stride];
324
+ if (v === 0)
325
+ continue;
326
+ const av = Math.abs(v);
327
+ if (sc < av) {
328
+ ssq = 1 + ssq * (sc / av) ** 2;
329
+ sc = av;
330
+ }
331
+ else
332
+ ssq += (av / sc) ** 2;
333
+ }
334
+ return sc * Math.sqrt(ssq);
335
+ }
336
+ /**
337
+ * Balancing (dgebal) with job "P" (permute only) or "S" (scale only); A is overwritten. Indices are 0-based:
338
+ * scale[i] holds the index of the row and column interchanged with i for i < ilo and i > ihi, and the scaling factor
339
+ * for ilo <= i <= ihi
340
+ */
341
+ export function gebal(job, A) {
342
+ const n = A.nrow;
343
+ const a = A.data;
344
+ const at = (i, j) => i + j * n;
345
+ const scale = new Float64Array(n);
346
+ const swapCols = (i, j, rows) => {
347
+ for (let r = 0; r < rows; r++)
348
+ [a[at(r, i)], a[at(r, j)]] = [a[at(r, j)], a[at(r, i)]];
349
+ };
350
+ const swapRows = (i, j, from) => {
351
+ for (let c = from; c < n; c++)
352
+ [a[at(i, c)], a[at(j, c)]] = [a[at(j, c)], a[at(i, c)]];
353
+ };
354
+ // Permutation to isolate eigenvalues if possible
355
+ let k = 0;
356
+ let l = n - 1;
357
+ if (job === "P") {
358
+ // Search for rows isolating an eigenvalue and push them down (the loop bounds are fixed at entry, as in Fortran)
359
+ let noconv = true;
360
+ while (noconv) {
361
+ noconv = false;
362
+ for (let i = l; i >= 0; i--) {
363
+ let canswap = true;
364
+ for (let j = 0; j <= l; j++) {
365
+ if (i !== j && a[at(i, j)] !== 0) {
366
+ canswap = false;
367
+ break;
368
+ }
369
+ }
370
+ if (canswap) {
371
+ scale[l] = i;
372
+ if (i !== l) {
373
+ swapCols(i, l, l + 1);
374
+ swapRows(i, l, k);
375
+ }
376
+ noconv = true;
377
+ if (l === 0)
378
+ return { ilo: 0, ihi: 0, scale };
379
+ l--;
380
+ }
381
+ }
382
+ }
383
+ // Search for columns isolating an eigenvalue and push them left
384
+ noconv = true;
385
+ while (noconv) {
386
+ noconv = false;
387
+ for (let j = k, last = l; j <= last; j++) {
388
+ let canswap = true;
389
+ for (let i = k; i <= l; i++) {
390
+ if (i !== j && a[at(i, j)] !== 0) {
391
+ canswap = false;
392
+ break;
393
+ }
394
+ }
395
+ if (canswap) {
396
+ scale[k] = j;
397
+ if (j !== k) {
398
+ swapCols(j, k, l + 1);
399
+ swapRows(j, k, k);
400
+ }
401
+ noconv = true;
402
+ k++;
403
+ }
404
+ }
405
+ }
406
+ }
407
+ for (let i = k; i <= l; i++)
408
+ scale[i] = 1;
409
+ if (job === "P")
410
+ return { ilo: k, ihi: l, scale };
411
+ // Balance the submatrix in rows k to l by powers of 2 (iterative loop for norm reduction)
412
+ const SCLFAC = 2;
413
+ const FACTOR = 0.95;
414
+ const sfmin1 = 2 ** -1022 / Number.EPSILON;
415
+ const sfmax1 = 1 / sfmin1;
416
+ const sfmin2 = sfmin1 * SCLFAC;
417
+ const sfmax2 = 1 / sfmin2;
418
+ let noconv = true;
419
+ while (noconv) {
420
+ noconv = false;
421
+ for (let i = k; i <= l; i++) {
422
+ let c = nrm2(a, at(k, i), l - k + 1, 1);
423
+ let r = nrm2(a, at(i, k), l - k + 1, n);
424
+ let ca = 0;
425
+ for (let q = 0; q <= l; q++)
426
+ ca = Math.max(ca, Math.abs(a[at(q, i)]));
427
+ let ra = 0;
428
+ for (let q = k; q < n; q++)
429
+ ra = Math.max(ra, Math.abs(a[at(i, q)]));
430
+ // Guard against zero c or r due to underflow
431
+ if (c === 0 || r === 0)
432
+ continue;
433
+ if (Number.isNaN(c + ca + r + ra))
434
+ throw new RangeError("the matrix contains NaN or infinite values");
435
+ let g = r / SCLFAC;
436
+ let f = 1;
437
+ const s = c + r;
438
+ while (c < g && Math.max(f, c, ca) < sfmax2 && Math.min(r, g, ra) > sfmin2) {
439
+ f *= SCLFAC;
440
+ c *= SCLFAC;
441
+ ca *= SCLFAC;
442
+ r /= SCLFAC;
443
+ g /= SCLFAC;
444
+ ra /= SCLFAC;
445
+ }
446
+ g = c / SCLFAC;
447
+ while (g >= r && Math.max(r, ra) < sfmax2 && Math.min(f, c, g, ca) > sfmin2) {
448
+ f /= SCLFAC;
449
+ c /= SCLFAC;
450
+ g /= SCLFAC;
451
+ ca /= SCLFAC;
452
+ r *= SCLFAC;
453
+ ra *= SCLFAC;
454
+ }
455
+ // Now balance
456
+ if (c + r >= FACTOR * s)
457
+ continue;
458
+ if (f < 1 && scale[i] < 1 && f * scale[i] <= sfmin1)
459
+ continue;
460
+ if (f > 1 && scale[i] > 1 && scale[i] >= sfmax1 / f)
461
+ continue;
462
+ g = 1 / f;
463
+ scale[i] = scale[i] * f;
464
+ noconv = true;
465
+ for (let q = k; q < n; q++)
466
+ a[at(i, q)] = a[at(i, q)] * g;
467
+ for (let q = 0; q <= l; q++)
468
+ a[at(q, i)] = a[at(q, i)] * f;
469
+ }
470
+ }
471
+ return { ilo: k, ihi: l, scale };
472
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Sample } from "../htest/types.js";
2
+ import type { DataFrame } from "../models/modelFrame.js";
2
3
  /** A vector (plain array) or a matrix (array of rows). */
3
4
  export type Operand = number | Sample | readonly (readonly number[])[];
4
5
  type Matrix = number[][];
@@ -45,10 +46,20 @@ export interface DiagOptions {
45
46
  * ```
46
47
  */
47
48
  export declare function diag(x: Operand, options?: DiagOptions): number[] | Matrix;
48
- /** Combine vectors and matrices as columns. Equivalent to R's `cbind()` (vectors recycled to the number of rows). */
49
+ /**
50
+ * Combine vectors and matrices as columns. Equivalent to R's `cbind()` (vectors recycled to the number of rows).
51
+ * Given data frames (objects of columns), puts their columns side by side, as R's `cbind()` of data frames: all must
52
+ * have the same number of rows, and a column name may occur only once.
53
+ */
49
54
  export declare function cbind(...args: Operand[]): Matrix;
50
- /** Combine vectors and matrices as rows. Equivalent to R's `rbind()`. */
55
+ export declare function cbind(...frames: DataFrame[]): DataFrame;
56
+ /**
57
+ * Combine vectors and matrices as rows. Equivalent to R's `rbind()`. Given data frames (objects of columns), stacks
58
+ * their rows, as R's `rbind()` of data frames: all must have the same column names, matched by name (the result has
59
+ * the first frame's column order).
60
+ */
51
61
  export declare function rbind(...args: Operand[]): Matrix;
62
+ export declare function rbind(...frames: DataFrame[]): DataFrame;
52
63
  /** Options for {@link matrix}. */
53
64
  export interface MatrixOptions {
54
65
  nrow?: number;
@@ -1,9 +1,11 @@
1
1
  // Matrix arithmetic and construction: R's %*% (matMul), element-wise +, -, *, / with R's recycling (add, subtract,
2
- // multiply, divide), outer, t, diag, cbind, rbind, matrix, kronecker and seq.
2
+ // multiply, divide), outer, t, diag, cbind, rbind (also of data frames: src/descriptive/dataFrames.ts), matrix,
3
+ // kronecker and seq.
3
4
  //
4
5
  // Written for rStats.js (no ported code). Matrices are arrays of rows, as everywhere in rStats.js; a plain array is a
5
6
  // vector, which R treats as a row or a column as the operation needs. Element-wise operations recycle a shorter
6
7
  // vector over a matrix in column-major order (R's storage order), as R does.
8
+ import { cbindFrames, rbindFrames } from "../descriptive/dataFrames.js";
7
9
  function isMatrix(x) {
8
10
  return typeof x !== "number" && x.length > 0 && Array.isArray(x[0]);
9
11
  }
@@ -198,13 +200,26 @@ function bindParts(args, byColumn) {
198
200
  });
199
201
  return parts.flatMap((p) => p.map((v) => Array.from({ length: len }, (_, i) => v[i % v.length])));
200
202
  }
201
- /** Combine vectors and matrices as columns. Equivalent to R's `cbind()` (vectors recycled to the number of rows). */
203
+ /** A data frame (object of columns) rather than a number, vector or matrix */
204
+ function isDataFrame(x) {
205
+ return typeof x === "object" && !Array.isArray(x) && !ArrayBuffer.isView(x);
206
+ }
207
+ /** The data frames, if all arguments are data frames (and there is at least one); a mix is an error */
208
+ function framesOf(args) {
209
+ const frames = args.filter(isDataFrame);
210
+ if (frames.length === 0)
211
+ return undefined;
212
+ if (frames.length < args.length)
213
+ throw new TypeError("cannot combine data frames with vectors or matrices");
214
+ return frames;
215
+ }
202
216
  export function cbind(...args) {
203
- return t(bindParts(args, true));
217
+ const frames = framesOf(args);
218
+ return frames === undefined ? t(bindParts(args, true)) : cbindFrames(frames);
204
219
  }
205
- /** Combine vectors and matrices as rows. Equivalent to R's `rbind()`. */
206
220
  export function rbind(...args) {
207
- return bindParts(args, false);
221
+ const frames = framesOf(args);
222
+ return frames === undefined ? bindParts(args, false) : rbindFrames(frames);
208
223
  }
209
224
  /**
210
225
  * Build a matrix from data, recycled to fill it. Equivalent to R's `matrix()`: filled by columns unless `byrow`.