@numero-uno-jpn/rstats 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.ja.md +60 -11
  3. package/README.md +59 -10
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-2XKG3DX4.js} +1 -1
  6. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-4NM37MGA.js} +2 -2
  7. package/dist/chunks/chunk-7HPVUVZB.js +2 -0
  8. package/dist/chunks/{chunk-YC4JWUKG.js → chunk-AECGWZHD.js} +2 -2
  9. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-ENL43FNO.js} +2 -2
  10. package/dist/chunks/chunk-EWC6I75B.js +2 -0
  11. package/dist/chunks/chunk-IT354SHV.js +3 -0
  12. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-LIMZKONM.js} +2 -2
  13. package/dist/chunks/chunk-O6PT7IVU.js +2 -0
  14. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-QFULZNHL.js} +1 -1
  15. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-QJJWGNJP.js} +2 -2
  16. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-QULPY6YM.js} +1 -1
  17. package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
  18. package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
  19. package/dist/descriptive/factanal.d.ts +56 -0
  20. package/dist/descriptive/factanal.js +186 -0
  21. package/dist/descriptive/omega.d.ts +56 -0
  22. package/dist/descriptive/omega.js +323 -0
  23. package/dist/descriptive.js +2 -2
  24. package/dist/distributions/bvnorm.d.ts +15 -0
  25. package/dist/distributions/bvnorm.js +131 -0
  26. package/dist/distributions/nbeta.js +34 -1
  27. package/dist/distributions/nchisq.d.ts +10 -0
  28. package/dist/distributions/nchisq.js +46 -0
  29. package/dist/distributions.js +2 -2
  30. package/dist/entries/distributions.d.ts +1 -0
  31. package/dist/entries/distributions.js +1 -0
  32. package/dist/entries/linalg.d.ts +2 -0
  33. package/dist/entries/linalg.js +2 -0
  34. package/dist/entries/numerics.d.ts +2 -0
  35. package/dist/entries/numerics.js +1 -0
  36. package/dist/entries/tests.d.ts +22 -1
  37. package/dist/entries/tests.js +19 -1
  38. package/dist/htest/agreement.d.ts +141 -0
  39. package/dist/htest/agreement.js +274 -0
  40. package/dist/htest/aov.d.ts +19 -0
  41. package/dist/htest/aov.js +22 -15
  42. package/dist/htest/core/simulate.d.ts +2 -0
  43. package/dist/htest/core/simulate.js +1 -1
  44. package/dist/htest/dunnett.d.ts +5 -0
  45. package/dist/htest/dunnett.js +89 -0
  46. package/dist/htest/effectSize.d.ts +112 -0
  47. package/dist/htest/effectSize.js +385 -0
  48. package/dist/htest/leveneTest.d.ts +30 -0
  49. package/dist/htest/leveneTest.js +41 -0
  50. package/dist/htest/multipleComparisons.d.ts +147 -0
  51. package/dist/htest/multipleComparisons.js +369 -0
  52. package/dist/htest/normalityTests.d.ts +44 -0
  53. package/dist/htest/normalityTests.js +164 -0
  54. package/dist/htest/polycor.d.ts +117 -0
  55. package/dist/htest/polycor.js +468 -0
  56. package/dist/htest/power.d.ts +132 -0
  57. package/dist/htest/power.js +227 -0
  58. package/dist/htest/pwr.d.ts +263 -0
  59. package/dist/htest/pwr.js +440 -0
  60. package/dist/htest/rankTests.d.ts +7 -0
  61. package/dist/htest/rankTests.js +11 -1
  62. package/dist/htest/trendTests.d.ts +57 -0
  63. package/dist/htest/trendTests.js +167 -0
  64. package/dist/linalg/eigen.d.ts +8 -0
  65. package/dist/linalg/eigen.js +5 -4
  66. package/dist/linalg/expm.d.ts +48 -0
  67. package/dist/linalg/expm.js +472 -0
  68. package/dist/linalg/schur.d.ts +48 -0
  69. package/dist/linalg/schur.js +225 -0
  70. package/dist/linalg.js +2 -2
  71. package/dist/models/anovaSequential.d.ts +58 -0
  72. package/dist/models/anovaSequential.js +138 -0
  73. package/dist/models/aovEz.d.ts +64 -0
  74. package/dist/models/aovEz.js +332 -0
  75. package/dist/models/aovStrata.d.ts +32 -0
  76. package/dist/models/aovStrata.js +104 -0
  77. package/dist/models/carAnova.d.ts +30 -0
  78. package/dist/models/carAnova.js +121 -0
  79. package/dist/models/coxph.d.ts +101 -0
  80. package/dist/models/coxph.js +502 -0
  81. package/dist/models/ddLeastSquares.d.ts +30 -0
  82. package/dist/models/ddLeastSquares.js +90 -0
  83. package/dist/models/ddMatrix.d.ts +10 -0
  84. package/dist/models/ddMatrix.js +91 -0
  85. package/dist/models/formula.d.ts +83 -0
  86. package/dist/models/formula.js +333 -0
  87. package/dist/models/lm.d.ts +84 -3
  88. package/dist/models/lm.js +141 -44
  89. package/dist/models/mauchly.d.ts +48 -0
  90. package/dist/models/mauchly.js +123 -0
  91. package/dist/models/modelFrame.d.ts +40 -0
  92. package/dist/models/modelFrame.js +131 -0
  93. package/dist/models/modelMatrix.d.ts +88 -0
  94. package/dist/models/modelMatrix.js +170 -0
  95. package/dist/models/survival.d.ts +87 -0
  96. package/dist/models/survival.js +238 -0
  97. package/dist/numerics.js +2 -2
  98. package/dist/optim/lbfgsb.d.ts +20 -0
  99. package/dist/optim/lbfgsb.js +1240 -0
  100. package/dist/optim/optim.d.ts +85 -0
  101. package/dist/optim/optim.js +610 -0
  102. package/dist/rstats.js +19 -4
  103. package/dist/special.js +2 -2
  104. package/dist/tests.js +18 -4
  105. package/llms.txt +102 -0
  106. package/package.json +3 -2
  107. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  108. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  109. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  110. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  111. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  112. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -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
+ }
@@ -0,0 +1,48 @@
1
+ import { type MatrixInput } from "./matrix.js";
2
+ /** Result of {@link schur}: `x = Q T Q'`. */
3
+ export interface SchurResult {
4
+ /** The upper quasi-triangular factor (array of rows). */
5
+ T: number[][];
6
+ /** The orthogonal factor (array of rows). */
7
+ Q: number[][];
8
+ /** Real parts of the eigenvalues, in the order of T's diagonal blocks. */
9
+ valuesRe: number[];
10
+ /** Imaginary parts of the eigenvalues (0 for real ones; a complex pair has the positive one first). */
11
+ valuesIm: number[];
12
+ }
13
+ /**
14
+ * Real Schur decomposition of a square matrix. Equivalent to R's `Matrix::Schur(x)`.
15
+ *
16
+ * Returns an orthogonal `Q` and an upper quasi-triangular `T` with `x = Q T Q'`. `T` has 1 x 1 diagonal blocks for
17
+ * real eigenvalues and standardised 2 x 2 blocks `[[a, b], [c, a]]` (`b c < 0`) for complex conjugate pairs
18
+ * `a ± sqrt(-b c) i`. The decomposition is not unique: the order of the diagonal blocks and the signs of `Q`'s
19
+ * columns may differ from R's (both are correct). Throws on `NaN` or infinite values.
20
+ *
21
+ * @param x A square matrix (array of rows).
22
+ * @returns `T`, `Q` and the eigenvalues read off `T`. See {@link SchurResult}.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * schur([[0, -1], [1, 0]]);
27
+ * // T: [[0, -1], [1, 0]], Q: [[1, 0], [0, 1]], valuesRe: [0, 0], valuesIm: [1, -1]
28
+ * ```
29
+ */
30
+ export declare function schur(x: MatrixInput): SchurResult;
31
+ /**
32
+ * Schur factorisation of a real 2 x 2 matrix in standard form (dlanv2):
33
+ * [[a, b], [c, d]] = [[cs, -sn], [sn, cs]] [[aa, bb], [cc, dd]] [[cs, sn], [-sn, cs]], where either cc = 0 (real
34
+ * eigenvalues aa, dd) or aa = dd and bb cc < 0 (complex pair). Returns the standardised entries, the rotation and the
35
+ * eigenvalues
36
+ */
37
+ export declare function lanv2(a: number, b: number, c: number, d: number): {
38
+ a: number;
39
+ b: number;
40
+ c: number;
41
+ d: number;
42
+ cs: number;
43
+ sn: number;
44
+ rt1r: number;
45
+ rt1i: number;
46
+ rt2r: number;
47
+ rt2i: number;
48
+ };