@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/kappa.js
CHANGED
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
// "1", "O" and "I"; the library does not report warnings). rcond (method "direct") accepts "1", "O" and "I" in
|
|
18
18
|
// either case and rejects any other with R's message
|
|
19
19
|
// ginv is the Moore-Penrose generalised inverse via the SVD; singular values at most largest singular value × tol are treated as 0.
|
|
20
|
-
import { fromMat, newMat, toMat, transpose } from "./matrix.js";
|
|
20
|
+
import { fromMat, newMat, rangeExponent, toMat, transpose } from "./matrix.js";
|
|
21
21
|
import { norm } from "./norm.js";
|
|
22
22
|
import { qr, qrR } from "./qr.js";
|
|
23
23
|
import { rcond, solve } from "./solve.js";
|
|
24
|
-
import {
|
|
24
|
+
import { svdScaled } from "./svd.js";
|
|
25
|
+
import { ldexp } from "../internal/summary.js";
|
|
26
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
25
27
|
/**
|
|
26
28
|
* Condition number of a matrix, estimated or exact. Equivalent to R's `kappa()`.
|
|
27
29
|
*
|
|
@@ -42,21 +44,49 @@ import { svd } from "./svd.js";
|
|
|
42
44
|
* @category Linear algebra
|
|
43
45
|
*/
|
|
44
46
|
export function kappa(z, options = {}) {
|
|
47
|
+
// scale-free: a finite matrix outside [2^-256, 2^256] is divided by a power of 2 first, as in rcond (the condition
|
|
48
|
+
// number does not change; for entries near 1e308 the norms overflowed: Infinity from the triangular estimate and the
|
|
49
|
+
// exact 1- and inf-norms, NaN through the QR). Matrices in range are used as given, and so is one whose smallest
|
|
50
|
+
// nonzero entry would leave the normal range (diag(1e-200, 1, 1e200): its condition number of 1e400 still stops
|
|
51
|
+
// solve, as in R, instead of the entry 1e-200 becoming 0)
|
|
52
|
+
const zm0 = toMat(z);
|
|
53
|
+
let zm = zm0;
|
|
54
|
+
if (zm0.data.every(Number.isFinite)) {
|
|
55
|
+
// (brought near 1, not only down to 2^256 as in the decompositions (decompositionExponent): LINPACK's triangular
|
|
56
|
+
// estimate depends on the scale, and kept its values for the matrices it already scaled)
|
|
57
|
+
const e = rangeExponent(zm0.data);
|
|
58
|
+
const scaled = e === 0 ? undefined : { ...zm0, data: zm0.data.map((v) => ldexp(v, -e)) };
|
|
59
|
+
if (scaled !== undefined && scaled.data.every((v, i) => v === 0 ? zm0.data[i] === 0 : Math.abs(v) >= 2 ** -1022))
|
|
60
|
+
zm = scaled;
|
|
61
|
+
}
|
|
62
|
+
const zs = zm === zm0 ? z : fromMat(zm);
|
|
45
63
|
if (options.exact) {
|
|
46
64
|
// The default norm is "2" if exact, "1" if estimated
|
|
47
65
|
const nrm = options.norm === undefined ? "2" : normalize(options.norm);
|
|
48
66
|
if (nrm === "2") {
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
67
|
+
// the ratio of the scaled singular values (those of a matrix around 1e308 can overflow: Inf / Inf)
|
|
68
|
+
const d = svdScaled(z, { nu: 0, nv: 0 }).d;
|
|
69
|
+
const min = minOf(d);
|
|
70
|
+
return min === 0 ? Infinity : maxOf(d) / min;
|
|
71
|
+
}
|
|
72
|
+
// an exactly singular matrix gives Inf, as the 2-norm (R stops with "exactly singular"); a computationally singular
|
|
73
|
+
// one still stops, as in R (its inverse has no accurate norm)
|
|
74
|
+
let inverse;
|
|
75
|
+
try {
|
|
76
|
+
inverse = solve(zs);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
if (e instanceof Error && e.message.startsWith("the system is exactly singular"))
|
|
80
|
+
return Infinity;
|
|
81
|
+
throw e;
|
|
52
82
|
}
|
|
53
|
-
return norm(
|
|
83
|
+
return norm(zs, { type: nrm }) * norm(inverse, { type: nrm });
|
|
54
84
|
}
|
|
55
85
|
// Through a triangular factor, only "I" itself is the infinity norm; any other norm becomes the 1-norm (as in R)
|
|
56
86
|
const triNorm = options.norm === "I" ? "I" : "O";
|
|
57
87
|
if ((options.method ?? "qr") === "direct") {
|
|
58
88
|
if (options.triangular)
|
|
59
|
-
return 1 / triangularEstimate(
|
|
89
|
+
return 1 / triangularEstimate(zm, (options.uplo ?? "U") === "U", triNorm);
|
|
60
90
|
const t = options.norm ?? "O";
|
|
61
91
|
const u = t.toUpperCase();
|
|
62
92
|
if (u !== "1" && u !== "O" && u !== "I")
|
|
@@ -64,8 +94,7 @@ export function kappa(z, options = {}) {
|
|
|
64
94
|
return 1 / rcond(z, { norm: u === "I" ? "I" : "O" });
|
|
65
95
|
}
|
|
66
96
|
// If wide, transpose before the QR decomposition (from R's output)
|
|
67
|
-
const
|
|
68
|
-
const zz = zm.nrow < zm.ncol ? fromMat(transpose(zm)) : z;
|
|
97
|
+
const zz = zm.nrow < zm.ncol ? fromMat(transpose(zm)) : zs;
|
|
69
98
|
return 1 / triangularEstimate(toMat(qrR(qr(zz))), true, triNorm);
|
|
70
99
|
}
|
|
71
100
|
/**
|
|
@@ -205,20 +234,39 @@ function asum(z) {
|
|
|
205
234
|
export function ginv(x, options = {}) {
|
|
206
235
|
const tol = options.tol ?? Math.sqrt(Number.EPSILON);
|
|
207
236
|
const a = toMat(x);
|
|
208
|
-
|
|
237
|
+
// in the units of the scaled singular values d (x 2^-s), the result scaled by 2^-s at the end: singular values that
|
|
238
|
+
// overflow made the cut-off Inf and the result 0
|
|
239
|
+
const { d, u, v, s } = svdScaled(x);
|
|
209
240
|
const n = a.nrow;
|
|
210
241
|
const p = a.ncol;
|
|
211
242
|
const out = newMat(p, n);
|
|
212
243
|
const cut = Math.max(tol * (d[0] ?? 0), 0);
|
|
244
|
+
// a singular value whose reciprocal overflows (d below 2^-1024 in the scaled units) is inverted as 1/(d 2^600) and
|
|
245
|
+
// its terms are added in the original units, ldexp(…, 600 - s), after the others: ginv(diag(1e308, 1e-80), tol = 0)
|
|
246
|
+
// gave NaN and Inf (0 × Inf), for 1e80 (#127). The other terms are computed as before
|
|
247
|
+
const extra = [];
|
|
213
248
|
for (let k = 0; k < d.length; k++) {
|
|
214
249
|
if (!(d[k] > cut))
|
|
215
250
|
continue;
|
|
216
251
|
const inv = 1 / d[k];
|
|
252
|
+
if (!Number.isFinite(inv)) {
|
|
253
|
+
extra.push([k, 1 / ldexp(d[k], 600)]);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
217
256
|
for (let j = 0; j < n; j++) {
|
|
218
257
|
const ujk = u[j][k] * inv;
|
|
219
258
|
for (let i = 0; i < p; i++)
|
|
220
259
|
out.data[i + j * p] += v[i][k] * ujk;
|
|
221
260
|
}
|
|
222
261
|
}
|
|
262
|
+
if (s !== 0)
|
|
263
|
+
out.data = out.data.map((t) => ldexp(t, -s));
|
|
264
|
+
for (const [k, inv] of extra) {
|
|
265
|
+
for (let j = 0; j < n; j++) {
|
|
266
|
+
const ujk = u[j][k] * inv;
|
|
267
|
+
for (let i = 0; i < p; i++)
|
|
268
|
+
out.data[i + j * p] += ldexp(v[i][k] * ujk, 600 - s);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
223
271
|
return fromMat(out);
|
|
224
272
|
}
|
package/dist/linalg/lu.d.ts
CHANGED
|
@@ -14,7 +14,8 @@ export interface LuResult {
|
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
16
|
* LU decomposition with partial (row) pivoting, `x = P L U`. Equivalent to R's `Matrix::lu()`. The factors are those
|
|
17
|
-
* of `Matrix::expand(Matrix::lu(x))` (LAPACK's dgetrf).
|
|
17
|
+
* of `Matrix::expand(Matrix::lu(x))` (LAPACK's dgetrf). Throws on `NaN` or infinite values (`Matrix::lu` returns factors
|
|
18
|
+
* with NaN or infinite values).
|
|
18
19
|
*
|
|
19
20
|
* @example
|
|
20
21
|
* ```ts
|
package/dist/linalg/lu.js
CHANGED
|
@@ -9,11 +9,14 @@
|
|
|
9
9
|
import { scale as scaleColumns } from "../descriptive/moments.js";
|
|
10
10
|
import { svd } from "./svd.js";
|
|
11
11
|
import { matMul } from "./ops.js";
|
|
12
|
+
import { maxOf } from "../internal/extremes.js";
|
|
13
|
+
import { ldexp } from "../internal/summary.js";
|
|
12
14
|
/** Smallest normal double (LAPACK's dlamch("S")): below it, 1 / pivot would overflow. */
|
|
13
15
|
const SFMIN = 2.2250738585072014e-308;
|
|
14
16
|
/**
|
|
15
17
|
* LU decomposition with partial (row) pivoting, `x = P L U`. Equivalent to R's `Matrix::lu()`. The factors are those
|
|
16
|
-
* of `Matrix::expand(Matrix::lu(x))` (LAPACK's dgetrf).
|
|
18
|
+
* of `Matrix::expand(Matrix::lu(x))` (LAPACK's dgetrf). Throws on `NaN` or infinite values (`Matrix::lu` returns factors
|
|
19
|
+
* with NaN or infinite values).
|
|
17
20
|
*
|
|
18
21
|
* @example
|
|
19
22
|
* ```ts
|
|
@@ -29,6 +32,9 @@ export function lu(x) {
|
|
|
29
32
|
const a = x.map((r) => {
|
|
30
33
|
if (r.length !== n)
|
|
31
34
|
throw new TypeError("all rows of the matrix must have the same length");
|
|
35
|
+
// the factors of a matrix with NaN or an infinite value do not give back x = P L U: an error, as svd, qr and eigen (#343)
|
|
36
|
+
if (!r.every(Number.isFinite))
|
|
37
|
+
throw new RangeError("the matrix contains NaN or infinite values");
|
|
32
38
|
return Array.from(r);
|
|
33
39
|
});
|
|
34
40
|
const perm = Array.from({ length: m }, (_, i) => i);
|
|
@@ -90,21 +96,45 @@ export function prcomp(x, options = {}) {
|
|
|
90
96
|
throw new RangeError("as.integer(rank.) > 0 is not TRUE");
|
|
91
97
|
}
|
|
92
98
|
const rows = x.map((r) => Array.from(r));
|
|
93
|
-
const
|
|
99
|
+
const center = options.center ?? true;
|
|
100
|
+
const scale = options.scale ?? false;
|
|
101
|
+
let s = scaleColumns(rows, { center, scale });
|
|
94
102
|
if (s.scale?.some((v) => v === 0))
|
|
95
103
|
throw new RangeError("cannot rescale a constant/zero column to unit variance");
|
|
96
|
-
const dec = svd(s.scaled, { nu: 0 });
|
|
97
104
|
const n = rows.length;
|
|
98
|
-
const
|
|
105
|
+
const finite = (m) => m.every((r) => r.every(Number.isFinite));
|
|
106
|
+
let dec = finite(rows) && finite(s.scaled) ? svd(s.scaled, { nu: 0 }) : undefined;
|
|
107
|
+
// 2^unit: the factor of sdev and the scores (the unit of the data, when the columns are not divided by a scale)
|
|
108
|
+
let unit = 0;
|
|
109
|
+
if (finite(rows) && (dec === undefined || dec.d.some((d) => d === Infinity))) {
|
|
110
|
+
// the deviations (1.5e308 from a mean of -5e307) or a singular value overflow while sdev may be in range (sdev
|
|
111
|
+
// 1.15e308 of c(1e308, -1e308, 1e308, -1e308) was Infinity, R too): all in the coordinates 2^-e (exact)
|
|
112
|
+
const e = Math.floor(Math.log2(maxOf(rows.flat().map(Math.abs))));
|
|
113
|
+
const down = (o) => (typeof o === "boolean" ? o : o.map((v) => ldexp(v, -e)));
|
|
114
|
+
const r = scaleColumns(rows.map((row) => row.map((v) => ldexp(v, -e))), { center: down(center), scale: down(scale) });
|
|
115
|
+
dec = svd(r.scaled, { nu: 0 });
|
|
116
|
+
if (scale === false)
|
|
117
|
+
unit = e;
|
|
118
|
+
s = { scaled: r.scaled };
|
|
119
|
+
if (r.center !== undefined)
|
|
120
|
+
s.center = r.center.map((v) => ldexp(v, e));
|
|
121
|
+
if (r.scale !== undefined)
|
|
122
|
+
s.scale = r.scale.map((v) => ldexp(v, e));
|
|
123
|
+
}
|
|
124
|
+
// a non-finite value in the data: an error from svd, as before
|
|
125
|
+
dec ??= svd(s.scaled, { nu: 0 });
|
|
126
|
+
const sdev = dec.d.map((d) => ldexp(d / Math.sqrt(Math.max(1, n - 1)), unit));
|
|
99
127
|
// Components kept: at most rank, and with tol only those whose sdev is greater than tol times the first
|
|
100
128
|
let k = rank === undefined ? sdev.length : Math.min(Math.trunc(rank), sdev.length);
|
|
129
|
+
if (Number.isNaN(tol))
|
|
130
|
+
throw new RangeError("'tol' must not be NaN");
|
|
101
131
|
if (tol !== undefined)
|
|
102
132
|
k = Math.min(k, sdev.filter((d) => d > sdev[0] * tol).length);
|
|
103
133
|
const rotation = dec.v.map((r) => r.slice(0, k));
|
|
104
134
|
const out = {
|
|
105
135
|
sdev,
|
|
106
136
|
rotation,
|
|
107
|
-
x: matMul(s.scaled, dec.v).map((r) => r.slice(0, k)),
|
|
137
|
+
x: matMul(s.scaled, dec.v).map((r) => r.slice(0, k).map((v) => ldexp(v, unit))),
|
|
108
138
|
};
|
|
109
139
|
if (s.center !== undefined)
|
|
110
140
|
out.center = s.center;
|
package/dist/linalg/matrix.d.ts
CHANGED
|
@@ -31,3 +31,17 @@ export declare function column(m: Mat, j: number): number[];
|
|
|
31
31
|
export declare function transpose(m: Mat): Mat;
|
|
32
32
|
export declare function hasNonFinite(m: Mat): boolean;
|
|
33
33
|
export declare function requireSquare(m: Mat, what?: string): void;
|
|
34
|
+
/**
|
|
35
|
+
* 0 when the largest absolute value is within [2^-256, 2^256] (or all are 0); otherwise its binary exponent, the
|
|
36
|
+
* power of 2 to divide by to bring the values near 1
|
|
37
|
+
*/
|
|
38
|
+
export declare function rangeExponent(data: ArrayLike<number>): number;
|
|
39
|
+
/**
|
|
40
|
+
* The power of 2 to divide a matrix by before a decomposition (eigen, schur, svd, and the condition estimates of
|
|
41
|
+
* rcond, solve and kappa): 0 within [2^-256, 2^256]; a smaller matrix is brought up near 1, a larger one only down to
|
|
42
|
+
* [2^256, 2^257), the top of the range used as given (#127, #131, #132). Bringing it down to 1 put every entry below
|
|
43
|
+
* 2 of a matrix near 1e308 into the subnormal range: svd(diag(1e308, 1e-15)) gave 8.9e-16 and ginv's 1/d overflowed.
|
|
44
|
+
* Division by a power of 2 is exact, so a matrix whose result was finite and correct gives the same bits. eigen passes
|
|
45
|
+
* top = 459, LAPACK's dgeev bound (see eigen)
|
|
46
|
+
*/
|
|
47
|
+
export declare function decompositionExponent(data: ArrayLike<number>, top?: number): number;
|
package/dist/linalg/matrix.js
CHANGED
|
@@ -63,3 +63,27 @@ export function requireSquare(m, what = "the matrix") {
|
|
|
63
63
|
if (m.nrow !== m.ncol)
|
|
64
64
|
throw new TypeError(`${what} must be square (got ${m.nrow} x ${m.ncol})`);
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* 0 when the largest absolute value is within [2^-256, 2^256] (or all are 0); otherwise its binary exponent, the
|
|
68
|
+
* power of 2 to divide by to bring the values near 1
|
|
69
|
+
*/
|
|
70
|
+
export function rangeExponent(data) {
|
|
71
|
+
let mx = 0;
|
|
72
|
+
for (let i = 0; i < data.length; i++)
|
|
73
|
+
mx = Math.max(mx, Math.abs(data[i]));
|
|
74
|
+
if (mx === 0 || (mx >= 2 ** -256 && mx <= 2 ** 256))
|
|
75
|
+
return 0;
|
|
76
|
+
return Math.floor(Math.log2(mx));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The power of 2 to divide a matrix by before a decomposition (eigen, schur, svd, and the condition estimates of
|
|
80
|
+
* rcond, solve and kappa): 0 within [2^-256, 2^256]; a smaller matrix is brought up near 1, a larger one only down to
|
|
81
|
+
* [2^256, 2^257), the top of the range used as given (#127, #131, #132). Bringing it down to 1 put every entry below
|
|
82
|
+
* 2 of a matrix near 1e308 into the subnormal range: svd(diag(1e308, 1e-15)) gave 8.9e-16 and ginv's 1/d overflowed.
|
|
83
|
+
* Division by a power of 2 is exact, so a matrix whose result was finite and correct gives the same bits. eigen passes
|
|
84
|
+
* top = 459, LAPACK's dgeev bound (see eigen)
|
|
85
|
+
*/
|
|
86
|
+
export function decompositionExponent(data, top = 256) {
|
|
87
|
+
const k = rangeExponent(data);
|
|
88
|
+
return k > 0 ? Math.max(0, k - top) : k;
|
|
89
|
+
}
|
package/dist/linalg/ops.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
// vector, which R treats as a row or a column as the operation needs. Element-wise operations recycle a shorter
|
|
7
7
|
// vector over a matrix in column-major order (R's storage order), as R does.
|
|
8
8
|
import { cbindFrames, rbindFrames } from "../descriptive/dataFrames.js";
|
|
9
|
+
import { maxOf } from "../internal/extremes.js";
|
|
10
|
+
import { checkDot, checkedDot } from "./dot.js";
|
|
9
11
|
function isMatrix(x) {
|
|
10
12
|
return typeof x !== "number" && x.length > 0 && Array.isArray(x[0]);
|
|
11
13
|
}
|
|
@@ -70,14 +72,29 @@ export function matMul(x, y) {
|
|
|
70
72
|
if (a.length === 0 || b.length !== n)
|
|
71
73
|
throw new RangeError("non-conformable arguments");
|
|
72
74
|
checkRows(a);
|
|
73
|
-
|
|
75
|
+
// an inner dimension of 0 (an n x 0 matrix times an empty vector) gives n x 1 zeros, as R (b[0] was read)
|
|
76
|
+
const p = b.length > 0 ? checkRows(b) : 1;
|
|
77
|
+
// the smallest nonzero |entry| of each column of b and row of a: tiny sums checked for underflow only (#395)
|
|
78
|
+
const minB = new Array(p).fill(Infinity);
|
|
79
|
+
for (const r of b)
|
|
80
|
+
for (let j = 0; j < p; j++) {
|
|
81
|
+
const v = Math.abs(r[j]);
|
|
82
|
+
if (v !== 0 && v < minB[j])
|
|
83
|
+
minB[j] = v;
|
|
84
|
+
}
|
|
74
85
|
return a.map((row) => {
|
|
86
|
+
let minRow = Infinity;
|
|
87
|
+
for (const t of row) {
|
|
88
|
+
const v = Math.abs(t);
|
|
89
|
+
if (v !== 0 && v < minRow)
|
|
90
|
+
minRow = v;
|
|
91
|
+
}
|
|
75
92
|
const out = new Array(p).fill(0);
|
|
76
93
|
for (let j = 0; j < p; j++) {
|
|
77
94
|
let s = 0;
|
|
78
95
|
for (let k = 0; k < n; k++)
|
|
79
96
|
s += row[k] * b[k][j];
|
|
80
|
-
out[j] = s;
|
|
97
|
+
out[j] = checkDot(s, minRow * minB[j]) ? checkedDot(row, b.map((r) => r[j]), s) : s;
|
|
81
98
|
}
|
|
82
99
|
return out;
|
|
83
100
|
});
|
|
@@ -245,20 +262,26 @@ export function diag(x, options = {}) {
|
|
|
245
262
|
}
|
|
246
263
|
else {
|
|
247
264
|
values = v;
|
|
248
|
-
nrow = options.nrow ?? v.length;
|
|
265
|
+
nrow = dimArg(options.nrow, "nrow") ?? v.length;
|
|
249
266
|
}
|
|
250
|
-
const ncol = options.ncol ?? nrow;
|
|
267
|
+
const ncol = dimArg(options.ncol, "ncol") ?? nrow;
|
|
268
|
+
// as R: no values for a diagonal of positive length (i % 0 put undefined on it)
|
|
269
|
+
if (values.length === 0 && Math.min(nrow, ncol) > 0)
|
|
270
|
+
throw new RangeError("'x' must have positive length");
|
|
251
271
|
const out = Array.from({ length: nrow }, () => new Array(ncol).fill(0));
|
|
252
272
|
for (let i = 0; i < Math.min(nrow, ncol); i++)
|
|
253
273
|
out[i][i] = values[i % values.length];
|
|
254
274
|
return nrow === 0 ? [] : out;
|
|
255
275
|
}
|
|
256
276
|
/** Columns of an operand for binding: a matrix's columns, or a vector (scalar) as one column of `n` values */
|
|
257
|
-
function bindParts(
|
|
277
|
+
function bindParts(all, byColumn) {
|
|
278
|
+
// as R, vectors of length 0 are left out when anything else is given (recycling them put undefined in the result)
|
|
279
|
+
const given = (a) => isMatrix(a) || asVector(a).length > 0;
|
|
280
|
+
const args = all.some(given) ? all.filter(given) : all;
|
|
258
281
|
const parts = args.map((a) => (isMatrix(a) ? (byColumn ? t(a) : a.map((r) => [...r])) : [asVector(a)]));
|
|
259
282
|
// the common length: the matrices' rows (cbind) or columns (rbind), else the longest vector
|
|
260
283
|
const mats = args.filter(isMatrix);
|
|
261
|
-
const len = mats.length > 0 ? (byColumn ? mats[0].length : checkRows(mats[0])) :
|
|
284
|
+
const len = mats.length > 0 ? (byColumn ? mats[0].length : checkRows(mats[0])) : maxOf(parts.map((p) => p[0].length));
|
|
262
285
|
mats.forEach((m, k) => {
|
|
263
286
|
const l = byColumn ? m.length : checkRows(m);
|
|
264
287
|
if (l !== len) {
|
|
@@ -288,6 +311,14 @@ export function rbind(...args) {
|
|
|
288
311
|
const frames = framesOf(args);
|
|
289
312
|
return frames === undefined ? bindParts(args, false) : rbindFrames(frames);
|
|
290
313
|
}
|
|
314
|
+
/** A dimension argument truncated to an integer as R's as.integer does; a negative or non-finite one is an error */
|
|
315
|
+
function dimArg(d, name) {
|
|
316
|
+
if (d === undefined)
|
|
317
|
+
return undefined;
|
|
318
|
+
if (!Number.isFinite(d) || d <= -1)
|
|
319
|
+
throw new RangeError(`invalid '${name}' value`);
|
|
320
|
+
return Math.trunc(d) + 0;
|
|
321
|
+
}
|
|
291
322
|
/**
|
|
292
323
|
* Build a matrix from data, recycled to fill it. Equivalent to R's `matrix()`. Filled by columns unless `byrow`.
|
|
293
324
|
*
|
|
@@ -302,7 +333,8 @@ export function rbind(...args) {
|
|
|
302
333
|
export function matrix(data, options = {}) {
|
|
303
334
|
const v = asVector(data);
|
|
304
335
|
const len = v.length;
|
|
305
|
-
let
|
|
336
|
+
let nrow = dimArg(options.nrow, "nrow");
|
|
337
|
+
let ncol = dimArg(options.ncol, "ncol");
|
|
306
338
|
if (nrow === undefined && ncol === undefined) {
|
|
307
339
|
nrow = len;
|
|
308
340
|
ncol = 1;
|
|
@@ -368,24 +400,32 @@ export function seq(from, to, options = {}) {
|
|
|
368
400
|
return colon(from ?? 1, to ?? 1);
|
|
369
401
|
const a = from ?? 1;
|
|
370
402
|
const b = to ?? 1;
|
|
371
|
-
|
|
403
|
+
// Finite ends whose difference overflows: in half coordinates, doubled (exact scalings, so the values round as
|
|
404
|
+
// they would without the overflow; seq(-1e308, 1e308, { by: 1e308 }) was an error, R gives -1e308, 0, 1e308)
|
|
405
|
+
const half = !Number.isFinite(b - a);
|
|
406
|
+
const f = half ? 0.5 : 1;
|
|
407
|
+
const del = b * f - a * f;
|
|
372
408
|
if (del === 0 && b === 0)
|
|
373
409
|
return [b];
|
|
374
|
-
const n = del / by;
|
|
410
|
+
const n = del / (by * f);
|
|
375
411
|
if (!Number.isFinite(n)) {
|
|
376
412
|
if (by === 0 && del === 0)
|
|
377
413
|
return [a];
|
|
378
414
|
throw new RangeError("invalid '(to - from)/by'");
|
|
379
415
|
}
|
|
380
|
-
|
|
416
|
+
// an infinite `by` makes n a signed zero, which passes n < 0: its direction is checked against `to - from` (#274)
|
|
417
|
+
if (n < 0 || (!Number.isFinite(by) && del !== 0 && del > 0 !== by > 0)) {
|
|
381
418
|
throw new RangeError("wrong sign in 'by' argument");
|
|
382
|
-
|
|
419
|
+
}
|
|
420
|
+
if (Math.abs(del) / Math.max(Math.abs(b * f), Math.abs(a * f)) < 100 * Number.EPSILON)
|
|
383
421
|
return [a];
|
|
384
422
|
const k = Math.trunc(n + 1e-10);
|
|
423
|
+
const at = half ? (i) => 2 * (a / 2 + i * (by / 2)) : (i) => a + i * by;
|
|
385
424
|
// the last value may overshoot `to` by rounding: hold it at `to`
|
|
386
|
-
return Array.from({ length: k + 1 }, (_, i) => (by > 0 ? Math.min(
|
|
425
|
+
return Array.from({ length: k + 1 }, (_, i) => (i === 0 ? a : by > 0 ? Math.min(at(i), b) : Math.max(at(i), b)));
|
|
387
426
|
}
|
|
388
|
-
|
|
427
|
+
// rounded up first, as R: a length in (-1, 0) is 0 (#98)
|
|
428
|
+
if (!Number.isFinite(lengthOut) || lengthOut <= -1)
|
|
389
429
|
throw new RangeError("'length.out' must be a non-negative number");
|
|
390
430
|
const len = Math.ceil(lengthOut);
|
|
391
431
|
if (len === 0)
|
|
@@ -397,6 +437,13 @@ export function seq(from, to, options = {}) {
|
|
|
397
437
|
return [a, b].slice(0, len);
|
|
398
438
|
if (a === b)
|
|
399
439
|
return new Array(len).fill(a);
|
|
440
|
+
if (!Number.isFinite(b - a)) {
|
|
441
|
+
// finite ends whose difference overflows: in half coordinates, doubled (as seqLength in src/internal/seq.ts;
|
|
442
|
+
// the interior values were NaN)
|
|
443
|
+
const h = a / 2;
|
|
444
|
+
const halfStep = (b / 2 - h) / (len - 1);
|
|
445
|
+
return Array.from({ length: len }, (_, i) => (i === 0 ? a : i === len - 1 ? b : 2 * (h + i * halfStep)));
|
|
446
|
+
}
|
|
400
447
|
const step = (b - a) / (len - 1);
|
|
401
448
|
return Array.from({ length: len }, (_, i) => (i === 0 ? a : i === len - 1 ? b : a + i * step));
|
|
402
449
|
}
|
package/dist/linalg/qr.d.ts
CHANGED
|
@@ -304,7 +304,8 @@ export declare function qrR(q: QR, options?: {
|
|
|
304
304
|
*
|
|
305
305
|
* @param q A QR decomposition from {@link qr}.
|
|
306
306
|
* @param options `complete`: whether the default `ncol` is the number of rows (`true`) or `min(nrow, ncol)` (`false`, the default).
|
|
307
|
-
* `ncol`: the number of columns to return
|
|
307
|
+
* `ncol`: the number of columns to return, from 0 to `max(nrow, ncol)`; columns beyond the original ones are taken
|
|
308
|
+
* from `Q` (as in R). A larger `ncol` is an error (R pads zero columns).
|
|
308
309
|
* @returns The reconstructed matrix as an array of rows.
|
|
309
310
|
*
|
|
310
311
|
* @example
|
package/dist/linalg/qr.js
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
// - Columns are processed left to right. Before processing a column, if its remaining norm is below its original norm × tol
|
|
8
8
|
// (always, for a column whose original norm is 0), it is moved to the right end and the rest shift left. rank drops by the number moved
|
|
9
9
|
// - Columns moved to the right end are still transformed when their turn comes (only the column at the last row is left unprocessed)
|
|
10
|
-
// - Remaining norms are updated after each transformation by the LINPACK method, and recomputed when cancellation occurs
|
|
10
|
+
// - Remaining norms are updated after each transformation by the LINPACK method, and recomputed when cancellation occurs:
|
|
11
|
+
// when 1 - (|x|/norm)^2 is below 1e-6, as R's output shows (the rule from issue #57; LINPACK's own test missed the
|
|
12
|
+
// cancellation near the rank tolerance and dropped an independent column)
|
|
11
13
|
// - rank = min(number of columns - number moved, number of rows). The public pivot is 0-based to suit JS (internally 1-based)
|
|
12
14
|
// lapack: true is the same column-pivoted decomposition as the LAPACK 3.12.0 reference SRC/dgeqp3.f
|
|
13
15
|
// (dlaqp2.f, dlarfg.f, dlarf.f). rank is always min(rows, cols) (as in R; rank is not determined).
|
|
@@ -15,7 +17,8 @@
|
|
|
15
17
|
//
|
|
16
18
|
// Difference from R: with lapack: true, results for matrices containing NaN or Inf are not necessarily the same as R
|
|
17
19
|
// (R does not raise an error either and returns meaningless values).
|
|
18
|
-
import {
|
|
20
|
+
import { ldexp } from "../internal/summary.js";
|
|
21
|
+
import { decompositionExponent, fromMat, isMatrixInput, newMat, rangeExponent, toMat, toMatOrColumn } from "./matrix.js";
|
|
19
22
|
/**
|
|
20
23
|
* QR decomposition. Equivalent to R's `qr()`.
|
|
21
24
|
*
|
|
@@ -43,7 +46,23 @@ import { fromMat, isMatrixInput, newMat, toMat, toMatOrColumn } from "./matrix.j
|
|
|
43
46
|
export function qr(x, options = {}) {
|
|
44
47
|
const a = toMat(x);
|
|
45
48
|
if (options.lapack) {
|
|
46
|
-
const
|
|
49
|
+
const a0 = a.data.slice();
|
|
50
|
+
let { tau, pivot } = geqp3(a);
|
|
51
|
+
// Where the decomposition of a finite matrix overflowed (entries near 1e308), it is made again of the matrix divided
|
|
52
|
+
// by a power of 2 (as in svd; the whole matrix, since the pivoting compares the columns' norms), and R scaled back;
|
|
53
|
+
// the Householder vectors and tau have no units (#130). A finite result is kept as it is
|
|
54
|
+
if (a0.every(Number.isFinite) && !(a.data.every(Number.isFinite) && tau.every(Number.isFinite))) {
|
|
55
|
+
const k = decompositionExponent(a0);
|
|
56
|
+
if (k !== 0) {
|
|
57
|
+
const m = a.nrow;
|
|
58
|
+
for (let i = 0; i < a0.length; i++)
|
|
59
|
+
a.data[i] = ldexp(a0[i], -k);
|
|
60
|
+
({ tau, pivot } = geqp3(a));
|
|
61
|
+
for (let j = 0; j < a.ncol; j++)
|
|
62
|
+
for (let i = 0; i <= Math.min(j, m - 1); i++)
|
|
63
|
+
a.data[i + j * m] = ldexp(a.data[i + j * m], k);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
47
66
|
// One Householder scalar per reflection: min(nrow, ncol) elements, as in R
|
|
48
67
|
const qraux = Array.from(tau);
|
|
49
68
|
return { qr: fromMat(a), rank: Math.min(a.nrow, a.ncol), qraux, pivot: pivot.map((v) => v - 1), useLapack: true };
|
|
@@ -51,7 +70,38 @@ export function qr(x, options = {}) {
|
|
|
51
70
|
for (const v of a.data)
|
|
52
71
|
if (!Number.isFinite(v))
|
|
53
72
|
throw new RangeError("the matrix contains NaN or infinite values");
|
|
54
|
-
const
|
|
73
|
+
const tol = options.tol ?? 1e-7;
|
|
74
|
+
// a negative tolerance has no meaning (R accepts it, and no column is then ever dependent); Infinity is an error, as
|
|
75
|
+
// R's "NA/NaN/Inf in foreign function call" (it took every column as dependent, rank 0)
|
|
76
|
+
if (!(tol >= 0 && tol < Infinity))
|
|
77
|
+
throw new RangeError("'tol' must be a non-negative finite number");
|
|
78
|
+
const a0 = a.data.slice();
|
|
79
|
+
let { qraux, pivot, rank, transformed } = linpackQR(a, tol);
|
|
80
|
+
// Where the decomposition overflowed (sums of products of entries near 1e308: qr(matrix(1e308, 2, 2)) had rank 2 and
|
|
81
|
+
// -Inf in R, as in R, and lm on such a predictor gave NaN coefficients), it is made again with each column outside
|
|
82
|
+
// [2^-256, 2^256] divided by the power of 2 of its largest entry (exact). LINPACK's tests are relative to each column,
|
|
83
|
+
// so the pivoting and the rank are those of the exact decomposition; the upper triangle (R) and the norms kept in
|
|
84
|
+
// qraux for columns not transformed are scaled back, the Householder vectors and the other qraux have no units (#130).
|
|
85
|
+
// A finite result is kept as it is
|
|
86
|
+
if (!(a.data.every(Number.isFinite) && qraux.every(Number.isFinite))) {
|
|
87
|
+
const n = a.nrow;
|
|
88
|
+
const e = Array.from({ length: a.ncol }, (_, j) => rangeExponent(a0.subarray(j * n, (j + 1) * n)));
|
|
89
|
+
if (e.some((v) => v !== 0)) {
|
|
90
|
+
for (let j = 0; j < a.ncol; j++)
|
|
91
|
+
for (let i = 0; i < n; i++)
|
|
92
|
+
a.data[i + j * n] = ldexp(a0[i + j * n], -e[j]);
|
|
93
|
+
({ qraux, pivot, rank, transformed } = linpackQR(a, tol));
|
|
94
|
+
for (let j = 0; j < a.ncol; j++) {
|
|
95
|
+
const ej = e[pivot[j] - 1];
|
|
96
|
+
if (ej === 0)
|
|
97
|
+
continue;
|
|
98
|
+
for (let i = 0; i <= Math.min(j, n - 1); i++)
|
|
99
|
+
a.data[i + j * n] = ldexp(a.data[i + j * n], ej);
|
|
100
|
+
if (!transformed[j])
|
|
101
|
+
qraux[j] = ldexp(qraux[j], ej);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
55
105
|
return { qr: fromMat(a), rank, qraux: Array.from(qraux), pivot: pivot.map((v) => v - 1), useLapack: false };
|
|
56
106
|
}
|
|
57
107
|
/** 2-norm (divide by the largest absolute value before squaring and summing, to avoid overflow and underflow) */
|
|
@@ -74,12 +124,11 @@ function linpackQR(A, tol) {
|
|
|
74
124
|
const p = A.ncol;
|
|
75
125
|
const a = A.data;
|
|
76
126
|
const qraux = new Float64Array(p);
|
|
77
|
-
const work = new Float64Array(p); // norms used for updating (replaced when recomputed)
|
|
78
127
|
const orig = new Float64Array(p); // original norms (used for the test; 1 if 0)
|
|
128
|
+
const transformed = new Uint8Array(p); // 1 where qraux holds a Householder vector's leading element (not a norm)
|
|
79
129
|
const pivot = Array.from({ length: p }, (_, j) => j + 1);
|
|
80
130
|
for (let j = 0; j < p; j++) {
|
|
81
131
|
qraux[j] = nrm2(a, j * n, n);
|
|
82
|
-
work[j] = qraux[j];
|
|
83
132
|
orig[j] = qraux[j] === 0 ? 1 : qraux[j];
|
|
84
133
|
}
|
|
85
134
|
const col = new Float64Array(n);
|
|
@@ -89,15 +138,13 @@ function linpackQR(A, tol) {
|
|
|
89
138
|
// Move columns whose norm has become small to the right end (shifting the rest left)
|
|
90
139
|
while (l < k && qraux[l] < orig[l] * tol) {
|
|
91
140
|
col.set(a.subarray(l * n, (l + 1) * n));
|
|
92
|
-
const [q0,
|
|
141
|
+
const [q0, o0, p0] = [qraux[l], orig[l], pivot[l]];
|
|
93
142
|
a.copyWithin(l * n, (l + 1) * n, p * n);
|
|
94
143
|
a.set(col, (p - 1) * n);
|
|
95
144
|
qraux.copyWithin(l, l + 1);
|
|
96
|
-
work.copyWithin(l, l + 1);
|
|
97
145
|
orig.copyWithin(l, l + 1);
|
|
98
146
|
pivot.copyWithin(l, l + 1);
|
|
99
147
|
qraux[p - 1] = q0;
|
|
100
|
-
work[p - 1] = w0;
|
|
101
148
|
orig[p - 1] = o0;
|
|
102
149
|
pivot[p - 1] = p0;
|
|
103
150
|
k--;
|
|
@@ -125,22 +172,17 @@ function linpackQR(A, tol) {
|
|
|
125
172
|
a[cj + i] += t * a[cl + i];
|
|
126
173
|
if (qraux[j] === 0)
|
|
127
174
|
continue;
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const t2 = tt;
|
|
131
|
-
tt = 1 + 0.05 * tt * (qraux[j] / work[j]) ** 2;
|
|
132
|
-
if (tt !== 1) {
|
|
133
|
-
qraux[j] *= Math.sqrt(t2);
|
|
134
|
-
}
|
|
135
|
-
else {
|
|
175
|
+
const tt = Math.max(1 - (Math.abs(a[cj + l]) / qraux[j]) ** 2, 0);
|
|
176
|
+
if (tt < 1e-6)
|
|
136
177
|
qraux[j] = nrm2(a, cj + l + 1, n - l - 1);
|
|
137
|
-
|
|
138
|
-
|
|
178
|
+
else
|
|
179
|
+
qraux[j] *= Math.sqrt(tt);
|
|
139
180
|
}
|
|
140
181
|
qraux[l] = a[cl + l];
|
|
182
|
+
transformed[l] = 1;
|
|
141
183
|
a[cl + l] = -nrmxl;
|
|
142
184
|
}
|
|
143
|
-
return { qraux, pivot, rank: Math.min(k, n) };
|
|
185
|
+
return { qraux, pivot, rank: Math.min(k, n), transformed };
|
|
144
186
|
}
|
|
145
187
|
/** Column-pivoted Householder QR (dlaqp2, the unblocked version of dgeqp3). Returns tau and pivot */
|
|
146
188
|
function geqp3(A) {
|
|
@@ -449,7 +491,8 @@ export function qrR(q, options = {}) {
|
|
|
449
491
|
*
|
|
450
492
|
* @param q A QR decomposition from {@link qr}.
|
|
451
493
|
* @param options `complete`: whether the default `ncol` is the number of rows (`true`) or `min(nrow, ncol)` (`false`, the default).
|
|
452
|
-
* `ncol`: the number of columns to return
|
|
494
|
+
* `ncol`: the number of columns to return, from 0 to `max(nrow, ncol)`; columns beyond the original ones are taken
|
|
495
|
+
* from `Q` (as in R). A larger `ncol` is an error (R pads zero columns).
|
|
453
496
|
* @returns The reconstructed matrix as an array of rows.
|
|
454
497
|
*
|
|
455
498
|
* @example
|
|
@@ -467,6 +510,9 @@ export function qrX(q, options = {}) {
|
|
|
467
510
|
const ncol = options.ncol ?? (complete ? n : Math.min(n, p));
|
|
468
511
|
if (!Number.isInteger(ncol) || ncol < 0)
|
|
469
512
|
throw new RangeError(`invalid ncol (got ${ncol})`);
|
|
513
|
+
// Columns beyond max(n, p) are neither columns of x nor of an orthogonal completion (R pads them with zeros)
|
|
514
|
+
if (ncol > Math.max(n, p))
|
|
515
|
+
throw new RangeError(`ncol must be at most max(nrow, ncol of x) = ${Math.max(n, p)} (got ${ncol})`);
|
|
470
516
|
const pivoted = d.pivot.some((v, j) => v !== j + 1);
|
|
471
517
|
if (pivoted && ncol < p)
|
|
472
518
|
throw new RangeError("ncol must be at least the number of columns because the decomposition is pivoted");
|
|
@@ -516,10 +562,32 @@ export function qrSolve(a, b, options = {}) {
|
|
|
516
562
|
const p = n === 0 ? 0 : q.qr[0].length;
|
|
517
563
|
if (q.rank !== Math.min(n, p))
|
|
518
564
|
throw new Error("singular matrix in qrSolve");
|
|
565
|
+
// a LAPACK decomposition has no rank (always min(n, p)): with column pivoting the diagonal of R decreases, and a
|
|
566
|
+
// matrix whose |R_kk| is at most tol |R_11| is singular too (R returns a meaningless solution: (8, -2.5) for
|
|
567
|
+
// [[1, 2], [2, 4]] x = (3, 6))
|
|
568
|
+
if (q.useLapack) {
|
|
569
|
+
const tol = options.tol ?? 1e-7;
|
|
570
|
+
const r11 = Math.abs(q.qr[0]?.[0] ?? 0);
|
|
571
|
+
for (let k = 0; k < Math.min(n, p); k++)
|
|
572
|
+
if (!(Math.abs(q.qr[k][k]) > tol * r11))
|
|
573
|
+
throw new Error("singular matrix in qrSolve");
|
|
574
|
+
}
|
|
519
575
|
if (b === undefined && n !== p)
|
|
520
576
|
throw new TypeError("only square matrices can be inverted");
|
|
521
577
|
const y = b ?? Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)));
|
|
522
578
|
const res = qrCoef(q, y);
|
|
523
|
-
|
|
524
|
-
|
|
579
|
+
// The coefficients of the columns the decomposition leaves out (pivot[min(n, p)..], those of a wide matrix) are 0;
|
|
580
|
+
// a NaN from the solve itself (a NaN in the response) stays (R's res[is.na(res)] <- 0 makes it 0: qr.solve of the
|
|
581
|
+
// identity with b = (NaN, 1) is (0, 0))
|
|
582
|
+
const unused = new Set(q.pivot.slice(Math.min(n, p)));
|
|
583
|
+
if (isMatrixInput(y)) {
|
|
584
|
+
const m = res;
|
|
585
|
+
for (const j of unused)
|
|
586
|
+
m[j].fill(0);
|
|
587
|
+
return m;
|
|
588
|
+
}
|
|
589
|
+
const v = res;
|
|
590
|
+
for (const j of unused)
|
|
591
|
+
v[j] = 0;
|
|
592
|
+
return v;
|
|
525
593
|
}
|
package/dist/linalg/schur.js
CHANGED
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
// (no balancing, a different QR iteration)
|
|
13
13
|
// - NaN or Inf is an error, as in eigen
|
|
14
14
|
import { orthes, hqr2 } from "./eigen.js";
|
|
15
|
-
import { fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
15
|
+
import { decompositionExponent, fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
16
|
+
import { ldexp } from "../internal/summary.js";
|
|
16
17
|
/**
|
|
17
18
|
* Real Schur decomposition of a square matrix. Equivalent to R's `Matrix::Schur(x)`.
|
|
18
19
|
*
|
|
@@ -41,7 +42,11 @@ export function schur(x) {
|
|
|
41
42
|
for (const v of A.data)
|
|
42
43
|
if (!Number.isFinite(v))
|
|
43
44
|
throw new RangeError("the matrix contains NaN or infinite values");
|
|
44
|
-
|
|
45
|
+
// scaled by a power of 2 as in eigen and svd (exact): T and the eigenvalues are scaled back, Q has no units. With
|
|
46
|
+
// entries near 1e308, sums in the reduction overflowed: schur([[1e308, 0], [1e308, 1e308]]) lost T's off-diagonal
|
|
47
|
+
// entry, and a 3 x 3 matrix did not converge
|
|
48
|
+
const k = decompositionExponent(A.data);
|
|
49
|
+
const H = { nrow: n, ncol: n, data: k === 0 ? A.data.slice() : A.data.map((v) => ldexp(v, -k)) };
|
|
45
50
|
const V = newMat(n, n);
|
|
46
51
|
const d = new Float64Array(n);
|
|
47
52
|
const e = new Float64Array(n);
|
|
@@ -99,7 +104,10 @@ export function schur(x) {
|
|
|
99
104
|
valuesIm[j + 1] = s.rt2i;
|
|
100
105
|
j++;
|
|
101
106
|
}
|
|
102
|
-
|
|
107
|
+
if (k === 0)
|
|
108
|
+
return { T: fromMat(H), Q: fromMat(V), valuesRe, valuesIm };
|
|
109
|
+
const back = (x) => ldexp(x, k);
|
|
110
|
+
return { T: fromMat(H).map((r) => r.map(back)), Q: fromMat(V), valuesRe: valuesRe.map(back), valuesIm: valuesIm.map(back) };
|
|
103
111
|
}
|
|
104
112
|
const sign = (a, b) => (b >= 0 && !Object.is(b, -0) ? Math.abs(a) : -Math.abs(a));
|
|
105
113
|
/**
|