@numero-uno-jpn/rstats 0.15.3 → 0.16.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.
- package/CHANGELOG.md +166 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +24 -4
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +12 -4
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +5 -0
- package/dist/distributions/f.js +32 -17
- package/dist/distributions/gamma.js +27 -3
- package/dist/distributions/geometric.js +49 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +2 -1
- package/dist/distributions/laplace.js +27 -6
- package/dist/distributions/logistic.js +4 -1
- package/dist/distributions/lognormal.js +8 -2
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +94 -17
- package/dist/distributions/normal.js +9 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +4 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/triangular.js +10 -5
- package/dist/distributions/tukey.js +5 -2
- package/dist/distributions/weibull.js +10 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +17 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/linalg/basic.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// - A vector right-hand side gives a vector of length k; a matrix gives a matrix with k rows
|
|
7
7
|
// - Only the upper-left k x k triangle of r is used. Only the first k rows of the right-hand side are used
|
|
8
8
|
// - A zero on the diagonal is an error (as in R, only when exactly 0)
|
|
9
|
+
import { checkDot, checkedDot } from "./dot.js";
|
|
9
10
|
import { fromMat, isMatrixInput, newMat, toMat, toMatOrColumn } from "./matrix.js";
|
|
10
11
|
/**
|
|
11
12
|
* Matrix cross-product `t(x) %*% y`, or `t(x) %*% x` when `y` is omitted. Equivalent to R's `crossprod()`.
|
|
@@ -31,6 +32,8 @@ export function crossprod(x, y) {
|
|
|
31
32
|
throw new TypeError(`non-conformable arguments (${a.nrow} and ${b.nrow} rows)`);
|
|
32
33
|
const n = a.nrow;
|
|
33
34
|
const out = newMat(a.ncol, b.ncol);
|
|
35
|
+
// the smallest nonzero |entry| of each column: the inner products of tiny sums checked for underflow only (#395)
|
|
36
|
+
const minA = minAbsColumns(a), minB = y === undefined ? minA : minAbsColumns(b);
|
|
34
37
|
for (let j = 0; j < b.ncol; j++) {
|
|
35
38
|
for (let i = 0; i < a.ncol; i++) {
|
|
36
39
|
// When the result is symmetric (y omitted), compute only the upper triangle and copy it to the lower later
|
|
@@ -39,7 +42,8 @@ export function crossprod(x, y) {
|
|
|
39
42
|
let s = 0;
|
|
40
43
|
for (let k = 0; k < n; k++)
|
|
41
44
|
s += a.data[k + i * n] * b.data[k + j * n];
|
|
42
|
-
|
|
45
|
+
// (products of finite entries may overflow while the sum is in range, or underflow: as matMul)
|
|
46
|
+
out.data[i + j * a.ncol] = checkDot(s, minA[i] * minB[j]) ? checkedDot(column(a, i), column(b, j), s) : s;
|
|
43
47
|
}
|
|
44
48
|
}
|
|
45
49
|
if (y === undefined)
|
|
@@ -68,6 +72,7 @@ export function tcrossprod(x, y) {
|
|
|
68
72
|
if (a.ncol !== b.ncol)
|
|
69
73
|
throw new TypeError(`non-conformable arguments (${a.ncol} and ${b.ncol} columns)`);
|
|
70
74
|
const out = newMat(a.nrow, b.nrow);
|
|
75
|
+
const minA = minAbsRows(a), minB = y === undefined ? minA : minAbsRows(b);
|
|
71
76
|
for (let j = 0; j < b.nrow; j++) {
|
|
72
77
|
for (let i = 0; i < a.nrow; i++) {
|
|
73
78
|
// When the result is symmetric (y omitted), compute only the upper triangle and copy it to the lower later
|
|
@@ -76,13 +81,21 @@ export function tcrossprod(x, y) {
|
|
|
76
81
|
let s = 0;
|
|
77
82
|
for (let k = 0; k < a.ncol; k++)
|
|
78
83
|
s += a.data[i + k * a.nrow] * b.data[j + k * b.nrow];
|
|
79
|
-
out.data[i + j * a.nrow] = s;
|
|
84
|
+
out.data[i + j * a.nrow] = checkDot(s, minA[i] * minB[j]) ? checkedDot(row(a, i), row(b, j), s) : s;
|
|
80
85
|
}
|
|
81
86
|
}
|
|
82
87
|
if (y === undefined)
|
|
83
88
|
mirrorUpper(out);
|
|
84
89
|
return fromMat(out);
|
|
85
90
|
}
|
|
91
|
+
/** Column j of a matrix */
|
|
92
|
+
function column(m, j) {
|
|
93
|
+
return Array.from(m.data.subarray(j * m.nrow, (j + 1) * m.nrow));
|
|
94
|
+
}
|
|
95
|
+
/** Row i of a matrix */
|
|
96
|
+
function row(m, i) {
|
|
97
|
+
return Array.from({ length: m.ncol }, (_, k) => m.data[i + k * m.nrow]);
|
|
98
|
+
}
|
|
86
99
|
/** Copy the upper triangle of a square matrix to the lower triangle */
|
|
87
100
|
function mirrorUpper(m) {
|
|
88
101
|
const n = m.nrow;
|
|
@@ -118,7 +131,9 @@ function triangularSolve(r, x, k, upper, trans) {
|
|
|
118
131
|
}
|
|
119
132
|
/**
|
|
120
133
|
* Solve op(A) X = B, overwriting B with X (dtrsm with SIDE = 'L', DIAG = 'N').
|
|
121
|
-
* Only the upper-left n x n triangle of A is used. B has n rows
|
|
134
|
+
* Only the upper-left n x n triangle of A is used. B has n rows. Coefficients of exactly 0 are skipped: an overflowed
|
|
135
|
+
* component stands for a finite value, and 0 * Infinity = NaN spoiled the components that do not depend on it
|
|
136
|
+
* (backsolve(diag(1e-308, 2), c(1, 2)) gave NaN, Infinity; R too)
|
|
122
137
|
*/
|
|
123
138
|
export function trsm(A, n, B, upper, trans) {
|
|
124
139
|
const lda = A.nrow;
|
|
@@ -133,7 +148,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
133
148
|
b[o + k] /= a[k + k * lda];
|
|
134
149
|
const bk = b[o + k];
|
|
135
150
|
for (let i = 0; i < k; i++)
|
|
136
|
-
|
|
151
|
+
if (a[i + k * lda] !== 0)
|
|
152
|
+
b[o + i] -= bk * a[i + k * lda];
|
|
137
153
|
}
|
|
138
154
|
}
|
|
139
155
|
}
|
|
@@ -143,7 +159,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
143
159
|
b[o + k] /= a[k + k * lda];
|
|
144
160
|
const bk = b[o + k];
|
|
145
161
|
for (let i = k + 1; i < n; i++)
|
|
146
|
-
|
|
162
|
+
if (a[i + k * lda] !== 0)
|
|
163
|
+
b[o + i] -= bk * a[i + k * lda];
|
|
147
164
|
}
|
|
148
165
|
}
|
|
149
166
|
}
|
|
@@ -151,7 +168,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
151
168
|
for (let i = 0; i < n; i++) {
|
|
152
169
|
let t = b[o + i];
|
|
153
170
|
for (let k = 0; k < i; k++)
|
|
154
|
-
|
|
171
|
+
if (a[k + i * lda] !== 0)
|
|
172
|
+
t -= a[k + i * lda] * b[o + k];
|
|
155
173
|
b[o + i] = t / a[i + i * lda];
|
|
156
174
|
}
|
|
157
175
|
}
|
|
@@ -159,9 +177,35 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
159
177
|
for (let i = n - 1; i >= 0; i--) {
|
|
160
178
|
let t = b[o + i];
|
|
161
179
|
for (let k = i + 1; k < n; k++)
|
|
162
|
-
|
|
180
|
+
if (a[k + i * lda] !== 0)
|
|
181
|
+
t -= a[k + i * lda] * b[o + k];
|
|
163
182
|
b[o + i] = t / a[i + i * lda];
|
|
164
183
|
}
|
|
165
184
|
}
|
|
166
185
|
}
|
|
167
186
|
}
|
|
187
|
+
/** The smallest nonzero |entry| of each column (Infinity if none) */
|
|
188
|
+
function minAbsColumns(m) {
|
|
189
|
+
const out = [];
|
|
190
|
+
for (let c = 0; c < m.ncol; c++) {
|
|
191
|
+
let lo = Infinity;
|
|
192
|
+
for (let r = 0; r < m.nrow; r++) {
|
|
193
|
+
const v = Math.abs(m.data[r + c * m.nrow]);
|
|
194
|
+
if (v !== 0 && v < lo)
|
|
195
|
+
lo = v;
|
|
196
|
+
}
|
|
197
|
+
out.push(lo);
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
/** The smallest nonzero |entry| of each row (Infinity if none) */
|
|
202
|
+
function minAbsRows(m) {
|
|
203
|
+
const out = new Array(m.nrow).fill(Infinity);
|
|
204
|
+
for (let c = 0; c < m.ncol; c++)
|
|
205
|
+
for (let r = 0; r < m.nrow; r++) {
|
|
206
|
+
const v = Math.abs(m.data[r + c * m.nrow]);
|
|
207
|
+
if (v !== 0 && v < out[r])
|
|
208
|
+
out[r] = v;
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
}
|
package/dist/linalg/chol.js
CHANGED
|
@@ -18,7 +18,10 @@ export function chol(x, options = {}) {
|
|
|
18
18
|
if (a.nrow === 0)
|
|
19
19
|
throw new RangeError("the matrix has zero dimension");
|
|
20
20
|
if (options.pivot) {
|
|
21
|
-
const
|
|
21
|
+
const tol = options.tol ?? -1;
|
|
22
|
+
if (Number.isNaN(tol))
|
|
23
|
+
throw new RangeError("'tol' must not be NaN");
|
|
24
|
+
const { pivot, rank } = pstf2(a, tol);
|
|
22
25
|
zeroLower(a);
|
|
23
26
|
return { r: fromMat(a), pivot: pivot.map((v) => v - 1), rank };
|
|
24
27
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** A finite double as an integer mantissa m and an exponent e with v = m * 2^e (subnormals included) */
|
|
2
|
+
export declare function splitDouble(v: number): [bigint, number];
|
|
3
|
+
/**
|
|
4
|
+
* The inner product of u and v when the plain sum s is not finite: with finite factors, the products may have
|
|
5
|
+
* overflowed while the sum is in range (1e308 * 1e308 + 1e308 * -1e308 gave NaN, R too). Each product is formed
|
|
6
|
+
* exactly as an integer times a power of 2, the products are summed exactly in BigInt, and the sum is rounded once
|
|
7
|
+
* to the nearest double (ties to even, subnormals and overflow to Infinity included). Cancellation of the large
|
|
8
|
+
* products therefore leaves the exact remainder (matMul([[1e308, 1e308, 1e-308]], [[1e308], [-1e308], [1e308]]) is
|
|
9
|
+
* 0.9999999999999999, the double product 1e-308 * 1e308). With a factor that is not finite, s is returned as it is
|
|
10
|
+
*/
|
|
11
|
+
export declare function rescaledDot(u: readonly number[], v: readonly number[], s: number): number;
|
|
12
|
+
/**
|
|
13
|
+
* sum * 2^low rounded once to the nearest double (ties to even, subnormals and overflow to Infinity included).
|
|
14
|
+
* Callers whose sum is not exact pass it with a sticky last bit (at least 2 bits below the last kept one)
|
|
15
|
+
*/
|
|
16
|
+
export declare function roundScaled(sum: bigint, low: number): number;
|
|
17
|
+
/**
|
|
18
|
+
* Whether the plain sum s of an inner product is to be checked by checkedDot: s not finite, or |s| < 2^-969 and
|
|
19
|
+
* the product of the smallest nonzero |factors| (a lower bound of every nonzero product; 0 to always check) below
|
|
20
|
+
* 2^-1022. Otherwise s stands, with the bits of the plain sum
|
|
21
|
+
*/
|
|
22
|
+
export declare function checkDot(s: number, minProduct: number): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* The plain sum s of the inner product of u and v, or the exact inner product (rescaledDot) where s is not finite,
|
|
25
|
+
* or where |s| < 2^-969 and a product of nonzero factors fell below 2^-1022 (#395: 100 products 1e-162 * 1e-162
|
|
26
|
+
* round to 0 each, for 1e-322; R gives 0 too). A sum that cancels in the normal range (1e16 + 1 - 1e16 = 0) keeps
|
|
27
|
+
* its plain value
|
|
28
|
+
*/
|
|
29
|
+
export declare function checkedDot(u: readonly number[], v: readonly number[], s: number): number;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// The fallback for an inner product whose plain sum is not finite, or is tiny with products that underflowed (#395),
|
|
2
|
+
// shared by matMul (ops.ts), crossprod and tcrossprod (basic.ts), the rows of weight 0 and predict for lm
|
|
3
|
+
// (models/lm.ts) and predict for glm (models/glm.ts).
|
|
4
|
+
//
|
|
5
|
+
// Written for rStats.js (no ported code).
|
|
6
|
+
/** A finite double as an integer mantissa m and an exponent e with v = m * 2^e (subnormals included) */
|
|
7
|
+
export function splitDouble(v) {
|
|
8
|
+
const view = new DataView(new ArrayBuffer(8));
|
|
9
|
+
view.setFloat64(0, v);
|
|
10
|
+
const hi = view.getUint32(0);
|
|
11
|
+
const lo = view.getUint32(4);
|
|
12
|
+
const biased = (hi >>> 20) & 0x7ff;
|
|
13
|
+
let m = (BigInt(hi & 0xfffff) << 32n) | BigInt(lo);
|
|
14
|
+
if (biased !== 0)
|
|
15
|
+
m |= 1n << 52n;
|
|
16
|
+
if (hi >>> 31)
|
|
17
|
+
m = -m;
|
|
18
|
+
return [m, biased === 0 ? -1074 : biased - 1075];
|
|
19
|
+
}
|
|
20
|
+
/** m * 2^e as a double, with |m| < 2^54 so that Number(m) is exact; the scaling is split so that no step underflows */
|
|
21
|
+
function scaleExact(m, e) {
|
|
22
|
+
const a = Math.trunc(e / 2);
|
|
23
|
+
return Number(m) * 2 ** a * 2 ** (e - a);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The inner product of u and v when the plain sum s is not finite: with finite factors, the products may have
|
|
27
|
+
* overflowed while the sum is in range (1e308 * 1e308 + 1e308 * -1e308 gave NaN, R too). Each product is formed
|
|
28
|
+
* exactly as an integer times a power of 2, the products are summed exactly in BigInt, and the sum is rounded once
|
|
29
|
+
* to the nearest double (ties to even, subnormals and overflow to Infinity included). Cancellation of the large
|
|
30
|
+
* products therefore leaves the exact remainder (matMul([[1e308, 1e308, 1e-308]], [[1e308], [-1e308], [1e308]]) is
|
|
31
|
+
* 0.9999999999999999, the double product 1e-308 * 1e308). With a factor that is not finite, s is returned as it is
|
|
32
|
+
*/
|
|
33
|
+
export function rescaledDot(u, v, s) {
|
|
34
|
+
if (!u.every(Number.isFinite) || !v.every(Number.isFinite))
|
|
35
|
+
return s;
|
|
36
|
+
const mantissas = [];
|
|
37
|
+
const exponents = [];
|
|
38
|
+
let low = Infinity;
|
|
39
|
+
for (let k = 0; k < u.length; k++) {
|
|
40
|
+
if (u[k] === 0 || v[k] === 0)
|
|
41
|
+
continue;
|
|
42
|
+
const [ma, ea] = splitDouble(u[k]);
|
|
43
|
+
const [mb, eb] = splitDouble(v[k]);
|
|
44
|
+
mantissas.push(ma * mb);
|
|
45
|
+
exponents.push(ea + eb);
|
|
46
|
+
if (ea + eb < low)
|
|
47
|
+
low = ea + eb;
|
|
48
|
+
}
|
|
49
|
+
let sum = 0n;
|
|
50
|
+
for (let k = 0; k < mantissas.length; k++)
|
|
51
|
+
sum += mantissas[k] << BigInt(exponents[k] - low);
|
|
52
|
+
return roundScaled(sum, low);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* sum * 2^low rounded once to the nearest double (ties to even, subnormals and overflow to Infinity included).
|
|
56
|
+
* Callers whose sum is not exact pass it with a sticky last bit (at least 2 bits below the last kept one)
|
|
57
|
+
*/
|
|
58
|
+
export function roundScaled(sum, low) {
|
|
59
|
+
if (sum === 0n)
|
|
60
|
+
return 0;
|
|
61
|
+
const negative = sum < 0n;
|
|
62
|
+
const a = negative ? -sum : sum;
|
|
63
|
+
const bits = a.toString(2).length;
|
|
64
|
+
// a = 2^(bits - 1) * (1 + ...), so the value is in [2^top, 2^(top + 1))
|
|
65
|
+
const top = bits - 1 + low;
|
|
66
|
+
if (top > 1023)
|
|
67
|
+
return negative ? -Infinity : Infinity;
|
|
68
|
+
// the last kept bit is at 2^(top - 52), or at 2^-1074 for a subnormal result
|
|
69
|
+
const last = Math.max(top - 52, -1074);
|
|
70
|
+
const shift = last - low;
|
|
71
|
+
let q;
|
|
72
|
+
if (shift <= 0)
|
|
73
|
+
q = a;
|
|
74
|
+
else {
|
|
75
|
+
const sh = BigInt(shift);
|
|
76
|
+
q = a >> sh;
|
|
77
|
+
const rest = a - (q << sh);
|
|
78
|
+
const half = 1n << (sh - 1n);
|
|
79
|
+
if (rest > half || (rest === half && (q & 1n) === 1n))
|
|
80
|
+
q += 1n;
|
|
81
|
+
}
|
|
82
|
+
// rounding up to 2^53 (or past 2^1024) is exact here and overflows to Infinity in the scaling
|
|
83
|
+
const out = scaleExact(q, shift <= 0 ? low : last);
|
|
84
|
+
return negative ? -out : out;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Below this |s| the products that underflowed may matter: each is off by up to 2^-1075, n of them by n 2^-1075,
|
|
88
|
+
* which is n 2^-54 ulp of s at 2^-969 = 2^-1022 2^53 and lost in the rounding of the sum above it
|
|
89
|
+
*/
|
|
90
|
+
const UNDERFLOW_SUM = 2 ** -969;
|
|
91
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
92
|
+
/**
|
|
93
|
+
* Whether the plain sum s of an inner product is to be checked by checkedDot: s not finite, or |s| < 2^-969 and
|
|
94
|
+
* the product of the smallest nonzero |factors| (a lower bound of every nonzero product; 0 to always check) below
|
|
95
|
+
* 2^-1022. Otherwise s stands, with the bits of the plain sum
|
|
96
|
+
*/
|
|
97
|
+
export function checkDot(s, minProduct) {
|
|
98
|
+
// <=: a bound rounded up to 2^-1022 may be the product of factors whose exact product is below it (#465)
|
|
99
|
+
return !Number.isFinite(s) || (Math.abs(s) < UNDERFLOW_SUM && minProduct <= MIN_NORMAL);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether the exact product of the nonzero finite a and b is below 2^-1022 in absolute value. The rounded product
|
|
103
|
+
* decides, except where it is 2^-1022 itself: the exact product may be just below (rounded up, #465:
|
|
104
|
+
* 2^-511 (2^-511 (1 - 2^-53)) = 2^-1022 - 2^-1075) or just above, and is compared exactly
|
|
105
|
+
*/
|
|
106
|
+
function productBelowMinNormal(a, b) {
|
|
107
|
+
const p = Math.abs(a * b);
|
|
108
|
+
if (p !== MIN_NORMAL)
|
|
109
|
+
return p < MIN_NORMAL;
|
|
110
|
+
const [ma, ea] = splitDouble(Math.abs(a));
|
|
111
|
+
const [mb, eb] = splitDouble(Math.abs(b));
|
|
112
|
+
const shift = -1022 - (ea + eb);
|
|
113
|
+
return shift > 0 && ma * mb < 1n << BigInt(shift);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The plain sum s of the inner product of u and v, or the exact inner product (rescaledDot) where s is not finite,
|
|
117
|
+
* or where |s| < 2^-969 and a product of nonzero factors fell below 2^-1022 (#395: 100 products 1e-162 * 1e-162
|
|
118
|
+
* round to 0 each, for 1e-322; R gives 0 too). A sum that cancels in the normal range (1e16 + 1 - 1e16 = 0) keeps
|
|
119
|
+
* its plain value
|
|
120
|
+
*/
|
|
121
|
+
export function checkedDot(u, v, s) {
|
|
122
|
+
if (!Number.isFinite(s))
|
|
123
|
+
return rescaledDot(u, v, s);
|
|
124
|
+
if (!(Math.abs(s) < UNDERFLOW_SUM))
|
|
125
|
+
return s;
|
|
126
|
+
for (let k = 0; k < u.length; k++) {
|
|
127
|
+
const a = u[k], b = v[k];
|
|
128
|
+
if (a !== 0 && b !== 0 && productBelowMinNormal(a, b))
|
|
129
|
+
return rescaledDot(u, v, s);
|
|
130
|
+
}
|
|
131
|
+
return s;
|
|
132
|
+
}
|
package/dist/linalg/eigen.d.ts
CHANGED
|
@@ -57,7 +57,12 @@ export interface EigenResult {
|
|
|
57
57
|
* @category Linear algebra
|
|
58
58
|
*/
|
|
59
59
|
export declare function eigen(x: MatrixInput, options?: EigenOptions): EigenResult;
|
|
60
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)): the mean absolute difference over the entries
|
|
62
|
+
* that differ from their transposes (all.equal's countEQ = FALSE leaves the equal ones out; counting them, as the
|
|
63
|
+
* diagonal, diluted the scale: [[4, 1], [1 + 1e-13, 4]] passed, issue #99), relative to their mean absolute value
|
|
64
|
+
* when that exceeds the tolerance, absolute otherwise
|
|
65
|
+
*/
|
|
61
66
|
export declare function isSymmetric(a: Mat): boolean;
|
|
62
67
|
/** Reduce to Hessenberg form by Householder transformations (orthes). V becomes the product of the transformations */
|
|
63
68
|
export declare function orthes(H: Mat, V: Mat): void;
|
package/dist/linalg/eigen.js
CHANGED
|
@@ -17,8 +17,9 @@
|
|
|
17
17
|
// (LAPACK's dgeev only makes that component real; signs may differ from R)
|
|
18
18
|
// - If a nonsymmetric matrix has all real eigenvalues, valuesIm and vectorsIm are omitted (R also returns real results)
|
|
19
19
|
// - NaN or Inf is an error
|
|
20
|
+
import { ldexp } from "../internal/summary.js";
|
|
20
21
|
import { gebak, gebal } from "./balance.js";
|
|
21
|
-
import { fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
22
|
+
import { decompositionExponent, fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
22
23
|
/**
|
|
23
24
|
* Eigenvalues and eigenvectors of a square matrix. Equivalent to R's `eigen()`.
|
|
24
25
|
*
|
|
@@ -52,25 +53,73 @@ export function eigen(x, options = {}) {
|
|
|
52
53
|
for (const v of a.data)
|
|
53
54
|
if (!Number.isFinite(v))
|
|
54
55
|
throw new RangeError("the matrix contains NaN or infinite values");
|
|
55
|
-
|
|
56
|
+
// A matrix of extreme magnitude is scaled by a power of 2 (exact) and the eigenvalues scaled back, so that the
|
|
57
|
+
// iterations neither overflow nor underflow; other matrices are used as given. A large matrix is brought down only to
|
|
58
|
+
// 2^459, as dgeev does, so that entries down to 2^-1481 of the largest stay normal for the balancing that follows:
|
|
59
|
+
// at 2^256, [1, 1e200; 1e-200, 2] had 1e-200 subnormal (eigenvalues 2.609, 0.391; and 2, 1 when brought down to 1)
|
|
60
|
+
const k = decompositionExponent(a.data, 459);
|
|
61
|
+
const as = k === 0 ? a : { ...a, data: a.data.map((v) => ldexp(v, -k)) };
|
|
62
|
+
// The automatic symmetry test is made on the matrix normalised by a power of 2 near its largest |a_ij|, so that it
|
|
63
|
+
// is relative at every scale: R's (all.equal) falls back to an absolute difference when mean |a_ij| <= 100 eps, and
|
|
64
|
+
// takes a small nonsymmetric matrix (such as [[1, 2], [3, 4]] * 1e-60) for a symmetric one
|
|
65
|
+
const symmetric = options.symmetric ?? isSymmetric(normalized(a));
|
|
56
66
|
const wantVectors = !(options.onlyValues ?? false);
|
|
57
|
-
|
|
67
|
+
const out = symmetric ? symmetricEigen(as, wantVectors) : generalEigen(as, wantVectors);
|
|
68
|
+
if (k !== 0) {
|
|
69
|
+
out.values = out.values.map((v) => ldexp(v, k));
|
|
70
|
+
if (out.valuesIm)
|
|
71
|
+
out.valuesIm = out.valuesIm.map((v) => ldexp(v, k));
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
/** The matrix divided by 2^floor(log2(max |a_ij|)) (exact), or the matrix itself when it is all zero */
|
|
76
|
+
function normalized(a) {
|
|
77
|
+
let mx = 0;
|
|
78
|
+
for (const v of a.data)
|
|
79
|
+
mx = Math.max(mx, Math.abs(v));
|
|
80
|
+
if (mx === 0)
|
|
81
|
+
return a;
|
|
82
|
+
const f = 2 ** Math.min(1023, -Math.floor(Math.log2(mx)));
|
|
83
|
+
return f === 1 ? a : { ...a, data: a.data.map((v) => v * f) };
|
|
58
84
|
}
|
|
59
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)): the mean absolute difference over the entries
|
|
87
|
+
* that differ from their transposes (all.equal's countEQ = FALSE leaves the equal ones out; counting them, as the
|
|
88
|
+
* diagonal, diluted the scale: [[4, 1], [1 + 1e-13, 4]] passed, issue #99), relative to their mean absolute value
|
|
89
|
+
* when that exceeds the tolerance, absolute otherwise
|
|
90
|
+
*/
|
|
60
91
|
export function isSymmetric(a) {
|
|
61
92
|
const n = a.nrow;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
93
|
+
const sums = (f) => {
|
|
94
|
+
let diff = 0;
|
|
95
|
+
let size = 0;
|
|
96
|
+
let count = 0;
|
|
97
|
+
let mx = 0;
|
|
98
|
+
for (let j = 0; j < n; j++) {
|
|
99
|
+
for (let i = 0; i < n; i++) {
|
|
100
|
+
const t = a.data[i + j * n];
|
|
101
|
+
const c = a.data[j + i * n];
|
|
102
|
+
if (t === c)
|
|
103
|
+
continue;
|
|
104
|
+
diff += Math.abs(t * f - c * f);
|
|
105
|
+
size += Math.abs(t * f);
|
|
106
|
+
count++;
|
|
107
|
+
mx = Math.max(mx, Math.abs(t));
|
|
108
|
+
}
|
|
68
109
|
}
|
|
110
|
+
return { diff, size, count, mx };
|
|
111
|
+
};
|
|
112
|
+
let { diff, size, count, mx } = sums(1);
|
|
113
|
+
if (count === 0)
|
|
114
|
+
return true;
|
|
115
|
+
if (!Number.isFinite(diff) || !Number.isFinite(size)) {
|
|
116
|
+
// R's mean accumulates in long double and does not overflow here: divide by the largest of these |a_ij| (a power
|
|
117
|
+
// of 2, exact); the means are then large, so the test is the relative one, which this leaves unchanged
|
|
118
|
+
({ diff, size } = sums(2 ** -Math.floor(Math.log2(mx))));
|
|
69
119
|
}
|
|
70
120
|
const tol = 100 * Number.EPSILON;
|
|
71
|
-
const
|
|
72
|
-
const
|
|
73
|
-
const xy = diff / N;
|
|
121
|
+
const xn = size / count;
|
|
122
|
+
const xy = diff / count;
|
|
74
123
|
return (Number.isFinite(xn) && xn > tol ? xy / xn : xy) <= tol;
|
|
75
124
|
}
|
|
76
125
|
function symmetricEigen(A, wantVectors) {
|
|
@@ -339,7 +388,15 @@ function normalizeVectors(re, im) {
|
|
|
339
388
|
k = i;
|
|
340
389
|
}
|
|
341
390
|
}
|
|
342
|
-
|
|
391
|
+
// where the sum of squares overflows or leaves the normal range (gebak can scale a component by 2^664 or more:
|
|
392
|
+
// [0, 1e200; 1e-200, 0] gave 6.1e199 and a zero vector), the norm is taken relative to the largest modulus
|
|
393
|
+
let norm = Math.sqrt(ss);
|
|
394
|
+
if (big > 0 && !(ss >= 2 ** -1022 && ss < Infinity)) {
|
|
395
|
+
let rs = 0;
|
|
396
|
+
for (let i = 0; i < n; i++)
|
|
397
|
+
rs += (Math.hypot(re.data[o + i], im.data[o + i]) / big) ** 2;
|
|
398
|
+
norm = big * Math.sqrt(rs);
|
|
399
|
+
}
|
|
343
400
|
if (norm === 0)
|
|
344
401
|
continue;
|
|
345
402
|
// Multiplying by (cr - i ci) / (|v_k| norm) makes v_k a positive real
|
package/dist/linalg/expm.d.ts
CHANGED
|
@@ -19,8 +19,9 @@ export interface ExpmOptions {
|
|
|
19
19
|
*/
|
|
20
20
|
method?: ExpmMethod;
|
|
21
21
|
/**
|
|
22
|
-
* Degree of the Padé approximant or the Taylor polynomial (a positive integer
|
|
23
|
-
*
|
|
22
|
+
* Degree of the Padé approximant or the Taylor polynomial (a positive integer up to 2147483647, R's integer range,
|
|
23
|
+
* and with order * (n^3 + 64) at most 2^31 for an n x n matrix, a bound on the time), used only by `"Pade"`,
|
|
24
|
+
* `"Taylor"`, `"PadeO"` and `"TaylorO"`. Default: 8.
|
|
24
25
|
*/
|
|
25
26
|
order?: number;
|
|
26
27
|
}
|
package/dist/linalg/expm.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
// 26 (2005) 1179-1193 (degrees 3, 5, 7, 9 and 13, the bounds on the 1-norm and the Padé coefficients);
|
|
7
7
|
// the balancing is src/linalg/balance.ts (a port of LAPACK 3.12.0's SRC/dgebal.f, modified BSD).
|
|
8
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
|
|
9
|
+
// the result, as two separate calls; "Higham08" does not balance, except with job "S" where the scaling by 2^-s
|
|
10
|
+
// below would take a nonzero entry below the normal range (rStats.js; R loses the entry)
|
|
10
11
|
// - The Padé degree is chosen from the 1-norm of the (balanced) matrix; above 2.1, degree 13 with scaling by 2^-s
|
|
11
12
|
// - X = (V - U)^-1 (V + U) is solved by LU decomposition as solve (which throws if V - U is computationally
|
|
12
13
|
// singular), then squared s times, and the balancing is undone
|
|
@@ -18,6 +19,7 @@
|
|
|
18
19
|
// - A 1 x 1 matrix gives exp of its entry, a 0 x 0 matrix gives a 0 x 0 matrix
|
|
19
20
|
import { fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
20
21
|
import { infNorm, oneNorm } from "./norm.js";
|
|
22
|
+
import { ldexp } from "../internal/summary.js";
|
|
21
23
|
import { gebal } from "./balance.js";
|
|
22
24
|
import { solve } from "./solve.js";
|
|
23
25
|
const METHODS = ["Higham08.b", "Higham08", "Pade", "Taylor", "PadeO", "TaylorO"];
|
|
@@ -47,15 +49,29 @@ export function expm(x, options = {}) {
|
|
|
47
49
|
if (!METHODS.includes(method))
|
|
48
50
|
throw new RangeError(`unknown method: ${String(method)}`);
|
|
49
51
|
const order = options.order ?? 8;
|
|
50
|
-
|
|
51
|
-
|
|
52
|
+
// order is used by these four methods only (the Higham08 methods ignore it, as in R)
|
|
53
|
+
const usesOrder = method === "Pade" || method === "PadeO" || method === "Taylor" || method === "TaylorO";
|
|
54
|
+
// (up to R's integer range, beyond which R's expm fails too: from 2^53 on, the loops j = order, ..., 1 did not end)
|
|
55
|
+
if (usesOrder && !(Number.isInteger(order) && order >= 1 && order <= 2147483647)) {
|
|
56
|
+
throw new RangeError("order must be a positive integer at most 2147483647");
|
|
57
|
+
}
|
|
52
58
|
const A = toMat(x);
|
|
53
59
|
requireSquare(A);
|
|
54
60
|
const n = A.nrow;
|
|
55
61
|
if (n === 0)
|
|
56
62
|
return [];
|
|
63
|
+
// exp of the one entry, NaN and infinite ones included (as R)
|
|
57
64
|
if (n === 1)
|
|
58
65
|
return [[Math.exp(A.data[0])]];
|
|
66
|
+
// the loops make order matrix products of n^3 multiply-adds (plus a fixed cost per step): at most 2^31 in all,
|
|
67
|
+
// about 7 to 9 s on the development machine (order 29826161 at n = 2, 17171 at n = 50); the default 8 is far below
|
|
68
|
+
if (usesOrder && order * (n ** 3 + 64) > 2 ** 31) {
|
|
69
|
+
throw new RangeError(`order = ${order} is too large for a ${n} x ${n} matrix: order * (n^3 + 64) must be at most 2^31`);
|
|
70
|
+
}
|
|
71
|
+
// (the Padé and Taylor methods returned NaN silently; the Higham08 methods stopped later with other messages)
|
|
72
|
+
for (const v of A.data)
|
|
73
|
+
if (!Number.isFinite(v))
|
|
74
|
+
throw new RangeError("the matrix contains NaN or infinite values");
|
|
59
75
|
if (method === "Taylor" || method === "TaylorO")
|
|
60
76
|
return fromMat(taylorScaled(A, order));
|
|
61
77
|
if (method === "Pade" || method === "PadeO")
|
|
@@ -66,6 +82,13 @@ export function expm(x, options = {}) {
|
|
|
66
82
|
perm = gebal("P", A);
|
|
67
83
|
scaling = gebal("S", A);
|
|
68
84
|
}
|
|
85
|
+
else if (lostInSquaringScale(A)) {
|
|
86
|
+
// "Higham08" does not balance, but where A / 2^s would lose a nonzero entry below the normal range (the coupling
|
|
87
|
+
// 1e-308 of [[0, 1e308], [1e-308, 0]] became 0, and the result that of a nilpotent matrix, R too), the
|
|
88
|
+
// exponential is taken of the matrix balanced by dgebal's job "S" (a diagonal similarity by powers of 2) and
|
|
89
|
+
// transformed back, as "Higham08.b" does
|
|
90
|
+
scaling = gebal("S", A);
|
|
91
|
+
}
|
|
69
92
|
const X = pade(A);
|
|
70
93
|
const x_ = X.data;
|
|
71
94
|
const at = (i, j) => i + j * n;
|
|
@@ -104,6 +127,28 @@ const PADE13 = [
|
|
|
104
127
|
64764752532480000, 32382376266240000, 7771770303897600, 1187353796428800, 129060195264000, 10559470521600,
|
|
105
128
|
670442572800, 33522128640, 1323241920, 40840800, 960960, 16380, 182, 1,
|
|
106
129
|
];
|
|
130
|
+
/** log2 of the 1-norm of A (given as nu), from A divided by a power of 2 when nu overflows */
|
|
131
|
+
function log2OneNorm(A, nu) {
|
|
132
|
+
if (nu < Infinity)
|
|
133
|
+
return Math.log2(nu);
|
|
134
|
+
let mx = 0;
|
|
135
|
+
for (const v of A.data)
|
|
136
|
+
mx = Math.max(mx, Math.abs(v));
|
|
137
|
+
const k = Math.floor(Math.log2(mx));
|
|
138
|
+
return Math.log2(oneNorm({ ...A, data: A.data.map((v) => ldexp(v, -k)) })) + k;
|
|
139
|
+
}
|
|
140
|
+
/** The exponent s of the scaling A / 2^s before the Padé approximant of degree 13 (nu, the 1-norm of A, above 2.1) */
|
|
141
|
+
function squaringExponent(A, nu) {
|
|
142
|
+
return Math.max(0, Math.ceil(log2OneNorm(A, nu) - Math.log2(5.4)));
|
|
143
|
+
}
|
|
144
|
+
/** Whether the scaling A / 2^s of pade takes a nonzero entry of A below the normal range (2^-1022) */
|
|
145
|
+
function lostInSquaringScale(A) {
|
|
146
|
+
const nu = oneNorm(A);
|
|
147
|
+
if (nu <= 2.1)
|
|
148
|
+
return false;
|
|
149
|
+
const s = squaringExponent(A, nu);
|
|
150
|
+
return s > 0 && A.data.some((v) => v !== 0 && Math.abs(ldexp(v, -s)) < 2 ** -1022);
|
|
151
|
+
}
|
|
107
152
|
/** Scaling and squaring with a Padé approximant: exp(A) for the (balanced) matrix A */
|
|
108
153
|
function pade(A) {
|
|
109
154
|
const n = A.nrow;
|
|
@@ -130,8 +175,11 @@ function pade(A) {
|
|
|
130
175
|
V = v;
|
|
131
176
|
}
|
|
132
177
|
else {
|
|
133
|
-
s
|
|
134
|
-
|
|
178
|
+
// the norm's log from the matrix divided by a power of 2 when the column sums overflow (s was then Infinity, and
|
|
179
|
+
// the squaring below never ended), and A / 2^s formed in two steps (1 / 2^s is 0 from s = 1024 on, which made
|
|
180
|
+
// B = 0 and gave the identity instead of exp(A))
|
|
181
|
+
s = squaringExponent(A, nu);
|
|
182
|
+
const B = { ...A, data: A.data.map((v) => ldexp(v, -s)) };
|
|
135
183
|
const B2 = mul(B, B);
|
|
136
184
|
const B4 = mul(B2, B2);
|
|
137
185
|
const B6 = mul(B2, B4);
|
|
@@ -154,24 +202,45 @@ function pade(A) {
|
|
|
154
202
|
}
|
|
155
203
|
let X = toMat(solve(fromMat(vmu), fromMat(vpu)));
|
|
156
204
|
for (let k = 0; k < s; k++)
|
|
157
|
-
X =
|
|
205
|
+
X = mulSquaring(X, X);
|
|
158
206
|
return X;
|
|
159
207
|
}
|
|
160
208
|
/**
|
|
161
209
|
* Exponent p of the scaling by N = 2^p (Shapira and Firth): with nu = sqrt(|A|_1 |A|_inf), L >= 1 the smallest with
|
|
162
|
-
* 2^L >= nu, p = L + 4
|
|
210
|
+
* 2^L >= nu, p = L + 4. Where A / 2^p would take a nonzero entry below the normal range (2^-1022), the floor L >= 1
|
|
211
|
+
* is dropped (p >= 0 only), keeping 2^L >= nu, that is |A / N| <= 2^-4 (rStats.js, #404; R loses the entry)
|
|
163
212
|
*/
|
|
164
213
|
function scalingExponent(A) {
|
|
165
|
-
const
|
|
214
|
+
const n1 = oneNorm(A);
|
|
215
|
+
const nInf = infNorm(A);
|
|
216
|
+
// Finite norms whose product overflows: take the square roots first
|
|
217
|
+
const nu = n1 * nInf < Infinity ? Math.sqrt(n1 * nInf) : Math.sqrt(n1) * Math.sqrt(nInf);
|
|
166
218
|
let L = 1;
|
|
167
219
|
while (2 ** L < nu)
|
|
168
220
|
L++;
|
|
169
|
-
|
|
221
|
+
const p = L + 4;
|
|
222
|
+
if (!A.data.some((v) => v !== 0 && Math.abs(ldexp(v, -p)) < 2 ** -1022))
|
|
223
|
+
return p;
|
|
224
|
+
// The product of the norms underflows: nu from the logs
|
|
225
|
+
if (nu === 0 || n1 * nInf < 2 ** -1000)
|
|
226
|
+
return Math.max(0, Math.ceil((Math.log2(n1) + Math.log2(nInf)) / 2) + 4);
|
|
227
|
+
let L2 = L;
|
|
228
|
+
while (L2 > -4 && 2 ** (L2 - 1) >= nu)
|
|
229
|
+
L2--;
|
|
230
|
+
return Math.max(0, L2 + 4);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* A and N = 2^p for the scaled methods. When 2^p would overflow, part of the scaling (an exact power of 2) is moved
|
|
234
|
+
* into A, so that A / N is unchanged; below that the values are the same as with A and 2^p.
|
|
235
|
+
*/
|
|
236
|
+
function scaledPair(A, p) {
|
|
237
|
+
const q = Math.max(0, p - 1000);
|
|
238
|
+
return { A: q === 0 ? A : scale(A, 2 ** -q), N: 2 ** (p - q) };
|
|
170
239
|
}
|
|
171
240
|
/** R <- R R, p times */
|
|
172
241
|
function squareRepeatedly(R, p) {
|
|
173
242
|
for (let k = 0; k < p; k++)
|
|
174
|
-
R =
|
|
243
|
+
R = mulSquaring(R, R);
|
|
175
244
|
return R;
|
|
176
245
|
}
|
|
177
246
|
/** M_ii <- M_ii + 1 */
|
|
@@ -183,10 +252,10 @@ function addIdentity(M) {
|
|
|
183
252
|
/** "Taylor": S = I, then S <- (S A) (1 / (j N)) + I for j = order ... 1, then squared p times */
|
|
184
253
|
function taylorScaled(A, order) {
|
|
185
254
|
const p = scalingExponent(A);
|
|
186
|
-
const N =
|
|
255
|
+
const { A: As, N } = scaledPair(A, p);
|
|
187
256
|
let S = identity(A.nrow);
|
|
188
257
|
for (let j = order; j >= 1; j--) {
|
|
189
|
-
S = scale(mul(S,
|
|
258
|
+
S = scale(mul(S, As), 1 / (j * N));
|
|
190
259
|
addIdentity(S);
|
|
191
260
|
}
|
|
192
261
|
return squareRepeatedly(S, p);
|
|
@@ -206,9 +275,9 @@ function padeHorner(A, order, N, sign) {
|
|
|
206
275
|
function padeScaled(A, order) {
|
|
207
276
|
const n = A.nrow;
|
|
208
277
|
const p = scalingExponent(A);
|
|
209
|
-
const N =
|
|
210
|
-
const numer = padeHorner(
|
|
211
|
-
const denom = padeHorner(
|
|
278
|
+
const { A: As, N } = scaledPair(A, p);
|
|
279
|
+
const numer = padeHorner(As, order, N, 1);
|
|
280
|
+
const denom = padeHorner(As, order, N, -1);
|
|
212
281
|
const R = newMat(n, n);
|
|
213
282
|
for (let i = 0; i < n; i++) {
|
|
214
283
|
R.data.set(conjugateGradientSquared(denom, numer.data.subarray(i * n, (i + 1) * n)), i * n);
|
|
@@ -285,6 +354,31 @@ function identity(n) {
|
|
|
285
354
|
return I;
|
|
286
355
|
}
|
|
287
356
|
/** Matrix product (inner products in increasing order of the summation index) */
|
|
357
|
+
/**
|
|
358
|
+
* A B for the squaring phase, where entries may have overflowed to ±Infinity: such an entry stands for a finite value
|
|
359
|
+
* too large to represent, so its product with an exact 0 is 0, not NaN (exp(diag(1e308, 0)) is diag(Inf, 1)). The same
|
|
360
|
+
* as mul for finite entries; NaN still propagates
|
|
361
|
+
*/
|
|
362
|
+
function mulSquaring(A, B) {
|
|
363
|
+
const n = A.nrow;
|
|
364
|
+
const p = A.ncol;
|
|
365
|
+
const q = B.ncol;
|
|
366
|
+
const C = newMat(n, q);
|
|
367
|
+
for (let j = 0; j < q; j++) {
|
|
368
|
+
for (let i = 0; i < n; i++) {
|
|
369
|
+
let s = 0;
|
|
370
|
+
for (let k = 0; k < p; k++) {
|
|
371
|
+
const a = A.data[i + k * n];
|
|
372
|
+
const b = B.data[k + j * p];
|
|
373
|
+
if ((a === 0 && Math.abs(b) === Infinity) || (b === 0 && Math.abs(a) === Infinity))
|
|
374
|
+
continue;
|
|
375
|
+
s += a * b;
|
|
376
|
+
}
|
|
377
|
+
C.data[i + j * n] = s;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return C;
|
|
381
|
+
}
|
|
288
382
|
function mul(A, B) {
|
|
289
383
|
const n = A.nrow;
|
|
290
384
|
const p = A.ncol;
|