@numero-uno-jpn/rstats 0.15.3 → 0.17.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 +294 -0
- package/README.ja.md +68 -35
- package/README.md +65 -30
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/chunk-4WE3OO62.js +2 -0
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/chunk-H3WVPZDL.js +2 -0
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/chunk-NSYZTS26.js +2 -0
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/chunk-SE7V2KLO.js +2 -0
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/chunk-Z37NELOS.js +2 -0
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +26 -7
- package/dist/descriptive/basic.js +110 -8
- package/dist/descriptive/cov.js +23 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +69 -23
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +26 -9
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +77 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +86 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +74 -10
- package/dist/descriptive/pivot.d.ts +25 -10
- package/dist/descriptive/pivot.js +182 -42
- package/dist/descriptive/quantile.js +10 -1
- package/dist/descriptive/rank.js +8 -1
- package/dist/descriptive/table.d.ts +23 -3
- package/dist/descriptive/table.js +36 -21
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +27 -2
- package/dist/distributions/beta.js +33 -4
- package/dist/distributions/binomial.js +46 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +21 -4
- package/dist/distributions/chisq.js +16 -3
- package/dist/distributions/exponential.js +14 -0
- package/dist/distributions/f.js +41 -17
- package/dist/distributions/gamma.js +35 -3
- package/dist/distributions/geometric.js +58 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +101 -6
- package/dist/distributions/invgamma.js +10 -1
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +36 -6
- package/dist/distributions/logistic.js +13 -1
- package/dist/distributions/lognormal.js +16 -2
- package/dist/distributions/multinomial.js +58 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +102 -17
- package/dist/distributions/normal.js +17 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +12 -1
- package/dist/distributions/poisson.js +37 -3
- package/dist/distributions/signrank.js +16 -4
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +481 -61
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +19 -5
- package/dist/distributions/tukey.js +11 -2
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +18 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +164 -26
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +3 -1
- package/dist/entries/descriptive.js +1 -1
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +2 -0
- package/dist/entries/linalg.d.ts +3 -1
- package/dist/entries/mixed.d.ts +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +16 -2
- package/dist/htest/agreement.js +122 -21
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/ansariTest.js +116 -18
- package/dist/htest/aov.d.ts +29 -23
- package/dist/htest/aov.js +90 -47
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +47 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +12 -5
- package/dist/htest/chisqTest.d.ts +5 -2
- package/dist/htest/chisqTest.js +151 -46
- package/dist/htest/cor.d.ts +9 -2
- package/dist/htest/cor.js +57 -26
- 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/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +5 -0
- package/dist/htest/effectSize.js +117 -35
- package/dist/htest/fisherTest.d.ts +4 -3
- package/dist/htest/fisherTest.js +88 -24
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +7 -1
- package/dist/htest/ksTest.js +36 -6
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +28 -6
- package/dist/htest/mantelhaenTest.js +132 -25
- package/dist/htest/mcnemarTest.js +40 -11
- package/dist/htest/multipleComparisons.d.ts +24 -26
- package/dist/htest/multipleComparisons.js +70 -64
- package/dist/htest/normalityTests.js +54 -14
- package/dist/htest/onewayTest.js +106 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +42 -6
- package/dist/htest/pairwise.d.ts +3 -1
- package/dist/htest/pairwise.js +46 -21
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +117 -59
- package/dist/htest/polycor.js +47 -17
- package/dist/htest/power.d.ts +15 -1
- package/dist/htest/power.js +128 -10
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +44 -6
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +159 -39
- package/dist/htest/rankTests.js +36 -6
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +53 -21
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +28 -4
- package/dist/htest/trendTests.js +124 -35
- package/dist/htest/types.d.ts +7 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +52 -14
- package/dist/htest/wilcoxTest.js +164 -29
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- 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/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- 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/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +58 -7
- package/dist/linalg/chol.js +10 -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 +75 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +113 -15
- package/dist/linalg/kappa.js +64 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +40 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +74 -26
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +105 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +156 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +33 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +32 -2
- package/dist/models/anovaSequential.js +170 -28
- package/dist/models/aovEz.js +154 -39
- package/dist/models/aovStrata.js +68 -24
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +78 -33
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +166 -69
- 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 +57 -7
- package/dist/models/glm.js +427 -74
- package/dist/models/glmAnova.js +90 -14
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +121 -29
- package/dist/models/glmFamily.d.ts +11 -6
- package/dist/models/glmFamily.js +247 -62
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +246 -37
- package/dist/models/lmer.d.ts +31 -7
- package/dist/models/lmer.js +129 -42
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +47 -9
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +13 -6
- package/dist/models/lmerTest.js +82 -29
- package/dist/models/mauchly.d.ts +6 -1
- package/dist/models/mauchly.js +41 -15
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +10 -4
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +47 -17
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +12 -1
- package/dist/models/survival.js +75 -28
- 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 +72 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +111 -16
- package/dist/numerics/interp.d.ts +40 -9
- package/dist/numerics/interp.js +375 -55
- package/dist/numerics/ode.js +59 -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 +97 -10
- package/dist/random/beta.js +58 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +50 -5
- package/dist/random/extra.js +55 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +47 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +31 -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/rng.js +4 -0
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +63 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +175 -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 +24 -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/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +15 -6
- package/package.json +19 -10
- 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-VLUL2HFW.js +0 -3
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// R's warnings: the collection of a call's warnings (each once, in order) and the handler that receives them when a
|
|
2
|
+
// public function returns (setWarningHandler).
|
|
3
|
+
//
|
|
4
|
+
// Every function that returns warnings in its result passes them to the handler at its end: `return reported("glm",
|
|
5
|
+
// result)` (or `reportWarnings("pivotLonger", warnings)` where the result has no `warnings`). A public function that
|
|
6
|
+
// calls another one that reports (pairwiseWilcoxTest calling wilcoxTest, aovEz calling lm) makes that call through
|
|
7
|
+
// `unreported`, so that only the outer call passes its warnings, which include the inner ones it keeps. A function
|
|
8
|
+
// that takes a fit or a table (anova, glmSummary, etaSquared) keeps the given object's warnings in its result but
|
|
9
|
+
// passes only those it adds: `reported("anova", table, fit)`; the fit's were passed when it was fitted. Nothing runs
|
|
10
|
+
// at the top level (package.json has sideEffects: false).
|
|
11
|
+
/** The key of the handler on globalThis, shared by every copy of the library on a page */
|
|
12
|
+
const HANDLER_KEY = "@numero-uno-jpn/rstats.warningHandler";
|
|
13
|
+
/** The handler set by setWarningHandler (null when none) */
|
|
14
|
+
function currentHandler() {
|
|
15
|
+
return globalThis[Symbol.for(HANDLER_KEY)] ?? null;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Sets the function that receives R's warnings, and returns the one it replaces (`null` when there was none). Not an
|
|
19
|
+
* R function. It plays the part of R's printing of warnings (and, by throwing, of `options(warn = 2)`).
|
|
20
|
+
*
|
|
21
|
+
* Every test, model and fit returns R's warnings in its result's `warnings` whatever the handler. With a handler
|
|
22
|
+
* set, each call of such a function (and `pivotLonger` without `onWarning`) also passes its warnings to the handler
|
|
23
|
+
* once it has computed its result: each distinct warning once, in order, with the name of the function called (a
|
|
24
|
+
* function that calls another, such as `pairwiseWilcoxTest`, passes the warnings once, under its own name). A fit's
|
|
25
|
+
* warnings are passed once, when it is fitted (`lm`, `glm`, `aov`, `lmer`, ...): a function given a fit or a table
|
|
26
|
+
* (`anova`, `aovSummary`, `Anova`, `glmSummary`, `etaSquared`, `lmerSummary`, ...) keeps them in its result's
|
|
27
|
+
* `warnings` but passes only the warnings it adds. An error thrown by the handler propagates to the caller. By default
|
|
28
|
+
* there is no handler and nothing is printed.
|
|
29
|
+
*
|
|
30
|
+
* To print the warnings as R does, set `(message, source) => console.warn(source + ": " + message)`. A handler that
|
|
31
|
+
* throws (`(message) => { throw new Error(message); }`) turns each warning into an error, as R's `options(warn = 2)`.
|
|
32
|
+
*
|
|
33
|
+
* The handler is kept on `globalThis`, so it is one setting for every copy of the library loaded on a page.
|
|
34
|
+
*
|
|
35
|
+
* @param handler The function that receives the warnings, or `null` to stop passing them.
|
|
36
|
+
* @returns The handler set before, or `null`.
|
|
37
|
+
* @throws TypeError if `handler` is neither a function nor `null`.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* const seen: string[] = [];
|
|
42
|
+
* const previous = setWarningHandler((message, source) => { seen.push(`${source}: ${message}`); });
|
|
43
|
+
* optim([1, 1], (p) => (p[0] - 2) ** 2 + (p[1] - 3) ** 2, { lower: [0, 0] }).warnings;
|
|
44
|
+
* // ["bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
45
|
+
* setWarningHandler(previous);
|
|
46
|
+
* seen; // ["optim: bounds can only be used with method L-BFGS-B (or Brent)"]
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @category Hypothesis tests
|
|
50
|
+
*/
|
|
51
|
+
export function setWarningHandler(handler) {
|
|
52
|
+
if (handler !== null && typeof handler !== "function")
|
|
53
|
+
throw new TypeError("handler must be a function or null");
|
|
54
|
+
const previous = currentHandler();
|
|
55
|
+
globalThis[Symbol.for(HANDLER_KEY)] = handler;
|
|
56
|
+
return previous;
|
|
57
|
+
}
|
|
58
|
+
/** How many calls of public functions through `unreported` are running: their warnings go to the outer call only */
|
|
59
|
+
let depth = 0;
|
|
60
|
+
/**
|
|
61
|
+
* Passes a call's warnings to the handler (each distinct one once, in order), unless the call is inside another
|
|
62
|
+
* public function (`unreported`) or no handler is set. An error of the handler propagates.
|
|
63
|
+
*/
|
|
64
|
+
export function reportWarnings(source, warnings) {
|
|
65
|
+
if (depth > 0 || warnings.length === 0)
|
|
66
|
+
return;
|
|
67
|
+
const handler = currentHandler();
|
|
68
|
+
if (handler === null)
|
|
69
|
+
return;
|
|
70
|
+
for (const message of new Set(warnings))
|
|
71
|
+
handler(message, source);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Passes the warnings of a result to the handler (reportWarnings) and returns the result. The warnings of `given` (the
|
|
75
|
+
* fits or tables the function was given, whose warnings the result keeps) are left out: they were passed by the call
|
|
76
|
+
* that made them.
|
|
77
|
+
*/
|
|
78
|
+
export function reported(source, result, ...given) {
|
|
79
|
+
const old = new Set(given.flatMap((g) => warningsOf(g)));
|
|
80
|
+
reportWarnings(source, (result.warnings ?? []).filter((w) => !old.has(w)));
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
/** The `warnings` of an object given to a function (a fit or a table), or none */
|
|
84
|
+
function warningsOf(g) {
|
|
85
|
+
const w = typeof g === "object" && g !== null ? g.warnings : undefined;
|
|
86
|
+
return Array.isArray(w) ? w.filter((m) => typeof m === "string") : [];
|
|
87
|
+
}
|
|
88
|
+
/** Runs a call of a public function inside another one: its warnings are not passed to the handler */
|
|
89
|
+
export function unreported(f) {
|
|
90
|
+
depth++;
|
|
91
|
+
try {
|
|
92
|
+
return f();
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
depth--;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Collects warnings in order of first appearance, each once (as the fixtures list R's warnings) */
|
|
99
|
+
export class Warnings {
|
|
100
|
+
list = [];
|
|
101
|
+
add(message) {
|
|
102
|
+
if (!this.list.includes(message))
|
|
103
|
+
this.list.push(message);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** The warnings sink of the link functions that warn ("NaNs produced"); set while a fit runs */
|
|
107
|
+
let currentWarnings;
|
|
108
|
+
/** Runs f with `sink` as the sink of `warn` */
|
|
109
|
+
export function withWarnings(sink, f) {
|
|
110
|
+
const saved = currentWarnings;
|
|
111
|
+
currentWarnings = sink;
|
|
112
|
+
try {
|
|
113
|
+
return f();
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
currentWarnings = saved;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** Adds a warning to the sink set by withWarnings (none outside it) */
|
|
120
|
+
export function warn(message) {
|
|
121
|
+
currentWarnings?.add(message);
|
|
122
|
+
}
|
package/dist/linalg/basic.d.ts
CHANGED
|
@@ -124,6 +124,8 @@ export declare function forwardsolve(l: MatrixInput, x: MatrixInput, options?: B
|
|
|
124
124
|
export declare function forwardsolve(l: MatrixInput, x: VectorOrMatrix, options?: BacksolveOptions): number[] | number[][];
|
|
125
125
|
/**
|
|
126
126
|
* Solve op(A) X = B, overwriting B with X (dtrsm with SIDE = 'L', DIAG = 'N').
|
|
127
|
-
* Only the upper-left n x n triangle of A is used. B has n rows
|
|
127
|
+
* Only the upper-left n x n triangle of A is used. B has n rows. Coefficients of exactly 0 are skipped: an overflowed
|
|
128
|
+
* component stands for a finite value, and 0 * Infinity = NaN spoiled the components that do not depend on it
|
|
129
|
+
* (backsolve(diag(1e-308, 2), c(1, 2)) gave NaN, Infinity; R too)
|
|
128
130
|
*/
|
|
129
131
|
export declare function trsm(A: Mat, n: number, B: Mat, upper: boolean, trans: boolean): void;
|
package/dist/linalg/basic.js
CHANGED
|
@@ -6,7 +6,13 @@
|
|
|
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";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
const BACKSOLVE_KEYS = ["k", "upperTri", "transpose"];
|
|
14
|
+
const FORWARDSOLVE_KEYS = ["k", "upperTri", "transpose"];
|
|
15
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
10
16
|
/**
|
|
11
17
|
* Matrix cross-product `t(x) %*% y`, or `t(x) %*% x` when `y` is omitted. Equivalent to R's `crossprod()`.
|
|
12
18
|
*
|
|
@@ -31,6 +37,8 @@ export function crossprod(x, y) {
|
|
|
31
37
|
throw new TypeError(`non-conformable arguments (${a.nrow} and ${b.nrow} rows)`);
|
|
32
38
|
const n = a.nrow;
|
|
33
39
|
const out = newMat(a.ncol, b.ncol);
|
|
40
|
+
// the smallest nonzero |entry| of each column: the inner products of tiny sums checked for underflow only (#395)
|
|
41
|
+
const minA = minAbsColumns(a), minB = y === undefined ? minA : minAbsColumns(b);
|
|
34
42
|
for (let j = 0; j < b.ncol; j++) {
|
|
35
43
|
for (let i = 0; i < a.ncol; i++) {
|
|
36
44
|
// When the result is symmetric (y omitted), compute only the upper triangle and copy it to the lower later
|
|
@@ -39,7 +47,8 @@ export function crossprod(x, y) {
|
|
|
39
47
|
let s = 0;
|
|
40
48
|
for (let k = 0; k < n; k++)
|
|
41
49
|
s += a.data[k + i * n] * b.data[k + j * n];
|
|
42
|
-
|
|
50
|
+
// (products of finite entries may overflow while the sum is in range, or underflow: as matMul)
|
|
51
|
+
out.data[i + j * a.ncol] = checkDot(s, minA[i] * minB[j]) ? checkedDot(column(a, i), column(b, j), s) : s;
|
|
43
52
|
}
|
|
44
53
|
}
|
|
45
54
|
if (y === undefined)
|
|
@@ -68,6 +77,7 @@ export function tcrossprod(x, y) {
|
|
|
68
77
|
if (a.ncol !== b.ncol)
|
|
69
78
|
throw new TypeError(`non-conformable arguments (${a.ncol} and ${b.ncol} columns)`);
|
|
70
79
|
const out = newMat(a.nrow, b.nrow);
|
|
80
|
+
const minA = minAbsRows(a), minB = y === undefined ? minA : minAbsRows(b);
|
|
71
81
|
for (let j = 0; j < b.nrow; j++) {
|
|
72
82
|
for (let i = 0; i < a.nrow; i++) {
|
|
73
83
|
// When the result is symmetric (y omitted), compute only the upper triangle and copy it to the lower later
|
|
@@ -76,13 +86,21 @@ export function tcrossprod(x, y) {
|
|
|
76
86
|
let s = 0;
|
|
77
87
|
for (let k = 0; k < a.ncol; k++)
|
|
78
88
|
s += a.data[i + k * a.nrow] * b.data[j + k * b.nrow];
|
|
79
|
-
out.data[i + j * a.nrow] = s;
|
|
89
|
+
out.data[i + j * a.nrow] = checkDot(s, minA[i] * minB[j]) ? checkedDot(row(a, i), row(b, j), s) : s;
|
|
80
90
|
}
|
|
81
91
|
}
|
|
82
92
|
if (y === undefined)
|
|
83
93
|
mirrorUpper(out);
|
|
84
94
|
return fromMat(out);
|
|
85
95
|
}
|
|
96
|
+
/** Column j of a matrix */
|
|
97
|
+
function column(m, j) {
|
|
98
|
+
return Array.from(m.data.subarray(j * m.nrow, (j + 1) * m.nrow));
|
|
99
|
+
}
|
|
100
|
+
/** Row i of a matrix */
|
|
101
|
+
function row(m, i) {
|
|
102
|
+
return Array.from({ length: m.ncol }, (_, k) => m.data[i + k * m.nrow]);
|
|
103
|
+
}
|
|
86
104
|
/** Copy the upper triangle of a square matrix to the lower triangle */
|
|
87
105
|
function mirrorUpper(m) {
|
|
88
106
|
const n = m.nrow;
|
|
@@ -91,9 +109,11 @@ function mirrorUpper(m) {
|
|
|
91
109
|
m.data[i + j * n] = m.data[j + i * n];
|
|
92
110
|
}
|
|
93
111
|
export function backsolve(r, x, options = {}) {
|
|
112
|
+
checkOptions(options, BACKSOLVE_KEYS, "backsolve"); // generated: option-keys.mjs
|
|
94
113
|
return triangularSolve(r, x, options.k, options.upperTri ?? true, options.transpose ?? false);
|
|
95
114
|
}
|
|
96
115
|
export function forwardsolve(l, x, options = {}) {
|
|
116
|
+
checkOptions(options, FORWARDSOLVE_KEYS, "forwardsolve"); // generated: option-keys.mjs
|
|
97
117
|
return triangularSolve(l, x, options.k, options.upperTri ?? false, options.transpose ?? false);
|
|
98
118
|
}
|
|
99
119
|
function triangularSolve(r, x, k, upper, trans) {
|
|
@@ -118,7 +138,9 @@ function triangularSolve(r, x, k, upper, trans) {
|
|
|
118
138
|
}
|
|
119
139
|
/**
|
|
120
140
|
* 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
|
|
141
|
+
* Only the upper-left n x n triangle of A is used. B has n rows. Coefficients of exactly 0 are skipped: an overflowed
|
|
142
|
+
* component stands for a finite value, and 0 * Infinity = NaN spoiled the components that do not depend on it
|
|
143
|
+
* (backsolve(diag(1e-308, 2), c(1, 2)) gave NaN, Infinity; R too)
|
|
122
144
|
*/
|
|
123
145
|
export function trsm(A, n, B, upper, trans) {
|
|
124
146
|
const lda = A.nrow;
|
|
@@ -133,7 +155,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
133
155
|
b[o + k] /= a[k + k * lda];
|
|
134
156
|
const bk = b[o + k];
|
|
135
157
|
for (let i = 0; i < k; i++)
|
|
136
|
-
|
|
158
|
+
if (a[i + k * lda] !== 0)
|
|
159
|
+
b[o + i] -= bk * a[i + k * lda];
|
|
137
160
|
}
|
|
138
161
|
}
|
|
139
162
|
}
|
|
@@ -143,7 +166,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
143
166
|
b[o + k] /= a[k + k * lda];
|
|
144
167
|
const bk = b[o + k];
|
|
145
168
|
for (let i = k + 1; i < n; i++)
|
|
146
|
-
|
|
169
|
+
if (a[i + k * lda] !== 0)
|
|
170
|
+
b[o + i] -= bk * a[i + k * lda];
|
|
147
171
|
}
|
|
148
172
|
}
|
|
149
173
|
}
|
|
@@ -151,7 +175,8 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
151
175
|
for (let i = 0; i < n; i++) {
|
|
152
176
|
let t = b[o + i];
|
|
153
177
|
for (let k = 0; k < i; k++)
|
|
154
|
-
|
|
178
|
+
if (a[k + i * lda] !== 0)
|
|
179
|
+
t -= a[k + i * lda] * b[o + k];
|
|
155
180
|
b[o + i] = t / a[i + i * lda];
|
|
156
181
|
}
|
|
157
182
|
}
|
|
@@ -159,9 +184,35 @@ export function trsm(A, n, B, upper, trans) {
|
|
|
159
184
|
for (let i = n - 1; i >= 0; i--) {
|
|
160
185
|
let t = b[o + i];
|
|
161
186
|
for (let k = i + 1; k < n; k++)
|
|
162
|
-
|
|
187
|
+
if (a[k + i * lda] !== 0)
|
|
188
|
+
t -= a[k + i * lda] * b[o + k];
|
|
163
189
|
b[o + i] = t / a[i + i * lda];
|
|
164
190
|
}
|
|
165
191
|
}
|
|
166
192
|
}
|
|
167
193
|
}
|
|
194
|
+
/** The smallest nonzero |entry| of each column (Infinity if none) */
|
|
195
|
+
function minAbsColumns(m) {
|
|
196
|
+
const out = [];
|
|
197
|
+
for (let c = 0; c < m.ncol; c++) {
|
|
198
|
+
let lo = Infinity;
|
|
199
|
+
for (let r = 0; r < m.nrow; r++) {
|
|
200
|
+
const v = Math.abs(m.data[r + c * m.nrow]);
|
|
201
|
+
if (v !== 0 && v < lo)
|
|
202
|
+
lo = v;
|
|
203
|
+
}
|
|
204
|
+
out.push(lo);
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
/** The smallest nonzero |entry| of each row (Infinity if none) */
|
|
209
|
+
function minAbsRows(m) {
|
|
210
|
+
const out = new Array(m.nrow).fill(Infinity);
|
|
211
|
+
for (let c = 0; c < m.ncol; c++)
|
|
212
|
+
for (let r = 0; r < m.nrow; r++) {
|
|
213
|
+
const v = Math.abs(m.data[r + c * m.nrow]);
|
|
214
|
+
if (v !== 0 && v < out[r])
|
|
215
|
+
out[r] = v;
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
}
|
package/dist/linalg/chol.js
CHANGED
|
@@ -12,13 +12,21 @@
|
|
|
12
12
|
// - pivot is 0-based to suit JS (R's pivot minus 1)
|
|
13
13
|
// - chol2inv uses only the upper-left size x size upper triangle of x. A zero on the diagonal is an error
|
|
14
14
|
import { fromMat, newMat, requireSquare, toMat, toMatOrColumn } from "./matrix.js";
|
|
15
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
16
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
17
|
+
const CHOL_KEYS = ["pivot", "tol"];
|
|
18
|
+
const CHOL2INV_KEYS = ["size"];
|
|
15
19
|
export function chol(x, options = {}) {
|
|
20
|
+
checkOptions(options, CHOL_KEYS, "chol"); // generated: option-keys.mjs
|
|
16
21
|
const a = toMat(x);
|
|
17
22
|
requireSquare(a);
|
|
18
23
|
if (a.nrow === 0)
|
|
19
24
|
throw new RangeError("the matrix has zero dimension");
|
|
20
25
|
if (options.pivot) {
|
|
21
|
-
const
|
|
26
|
+
const tol = options.tol ?? -1;
|
|
27
|
+
if (Number.isNaN(tol))
|
|
28
|
+
throw new RangeError("'tol' must not be NaN");
|
|
29
|
+
const { pivot, rank } = pstf2(a, tol);
|
|
22
30
|
zeroLower(a);
|
|
23
31
|
return { r: fromMat(a), pivot: pivot.map((v) => v - 1), rank };
|
|
24
32
|
}
|
|
@@ -137,6 +145,7 @@ function pstf2(A, tol) {
|
|
|
137
145
|
* @category Linear algebra
|
|
138
146
|
*/
|
|
139
147
|
export function chol2inv(x, options = {}) {
|
|
148
|
+
checkOptions(options, CHOL2INV_KEYS, "chol2inv"); // generated: option-keys.mjs
|
|
140
149
|
const m = toMatOrColumn(x);
|
|
141
150
|
const size = options.size ?? m.ncol;
|
|
142
151
|
if (!Number.isInteger(size) || size < 1)
|
|
@@ -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,12 @@
|
|
|
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";
|
|
23
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
24
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
25
|
+
const EIGEN_KEYS = ["symmetric", "onlyValues"];
|
|
22
26
|
/**
|
|
23
27
|
* Eigenvalues and eigenvectors of a square matrix. Equivalent to R's `eigen()`.
|
|
24
28
|
*
|
|
@@ -45,6 +49,7 @@ import { fromMat, newMat, requireSquare, toMat } from "./matrix.js";
|
|
|
45
49
|
* @category Linear algebra
|
|
46
50
|
*/
|
|
47
51
|
export function eigen(x, options = {}) {
|
|
52
|
+
checkOptions(options, EIGEN_KEYS, "eigen"); // generated: option-keys.mjs
|
|
48
53
|
const a = toMat(x);
|
|
49
54
|
requireSquare(a);
|
|
50
55
|
if (a.nrow === 0)
|
|
@@ -52,25 +57,73 @@ export function eigen(x, options = {}) {
|
|
|
52
57
|
for (const v of a.data)
|
|
53
58
|
if (!Number.isFinite(v))
|
|
54
59
|
throw new RangeError("the matrix contains NaN or infinite values");
|
|
55
|
-
|
|
60
|
+
// A matrix of extreme magnitude is scaled by a power of 2 (exact) and the eigenvalues scaled back, so that the
|
|
61
|
+
// iterations neither overflow nor underflow; other matrices are used as given. A large matrix is brought down only to
|
|
62
|
+
// 2^459, as dgeev does, so that entries down to 2^-1481 of the largest stay normal for the balancing that follows:
|
|
63
|
+
// 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)
|
|
64
|
+
const k = decompositionExponent(a.data, 459);
|
|
65
|
+
const as = k === 0 ? a : { ...a, data: a.data.map((v) => ldexp(v, -k)) };
|
|
66
|
+
// The automatic symmetry test is made on the matrix normalised by a power of 2 near its largest |a_ij|, so that it
|
|
67
|
+
// is relative at every scale: R's (all.equal) falls back to an absolute difference when mean |a_ij| <= 100 eps, and
|
|
68
|
+
// takes a small nonsymmetric matrix (such as [[1, 2], [3, 4]] * 1e-60) for a symmetric one
|
|
69
|
+
const symmetric = options.symmetric ?? isSymmetric(normalized(a));
|
|
56
70
|
const wantVectors = !(options.onlyValues ?? false);
|
|
57
|
-
|
|
71
|
+
const out = symmetric ? symmetricEigen(as, wantVectors) : generalEigen(as, wantVectors);
|
|
72
|
+
if (k !== 0) {
|
|
73
|
+
out.values = out.values.map((v) => ldexp(v, k));
|
|
74
|
+
if (out.valuesIm)
|
|
75
|
+
out.valuesIm = out.valuesIm.map((v) => ldexp(v, k));
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
/** The matrix divided by 2^floor(log2(max |a_ij|)) (exact), or the matrix itself when it is all zero */
|
|
80
|
+
function normalized(a) {
|
|
81
|
+
let mx = 0;
|
|
82
|
+
for (const v of a.data)
|
|
83
|
+
mx = Math.max(mx, Math.abs(v));
|
|
84
|
+
if (mx === 0)
|
|
85
|
+
return a;
|
|
86
|
+
const f = 2 ** Math.min(1023, -Math.floor(Math.log2(mx)));
|
|
87
|
+
return f === 1 ? a : { ...a, data: a.data.map((v) => v * f) };
|
|
58
88
|
}
|
|
59
|
-
/**
|
|
89
|
+
/**
|
|
90
|
+
* Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)): the mean absolute difference over the entries
|
|
91
|
+
* that differ from their transposes (all.equal's countEQ = FALSE leaves the equal ones out; counting them, as the
|
|
92
|
+
* diagonal, diluted the scale: [[4, 1], [1 + 1e-13, 4]] passed, issue #99), relative to their mean absolute value
|
|
93
|
+
* when that exceeds the tolerance, absolute otherwise
|
|
94
|
+
*/
|
|
60
95
|
export function isSymmetric(a) {
|
|
61
96
|
const n = a.nrow;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
97
|
+
const sums = (f) => {
|
|
98
|
+
let diff = 0;
|
|
99
|
+
let size = 0;
|
|
100
|
+
let count = 0;
|
|
101
|
+
let mx = 0;
|
|
102
|
+
for (let j = 0; j < n; j++) {
|
|
103
|
+
for (let i = 0; i < n; i++) {
|
|
104
|
+
const t = a.data[i + j * n];
|
|
105
|
+
const c = a.data[j + i * n];
|
|
106
|
+
if (t === c)
|
|
107
|
+
continue;
|
|
108
|
+
diff += Math.abs(t * f - c * f);
|
|
109
|
+
size += Math.abs(t * f);
|
|
110
|
+
count++;
|
|
111
|
+
mx = Math.max(mx, Math.abs(t));
|
|
112
|
+
}
|
|
68
113
|
}
|
|
114
|
+
return { diff, size, count, mx };
|
|
115
|
+
};
|
|
116
|
+
let { diff, size, count, mx } = sums(1);
|
|
117
|
+
if (count === 0)
|
|
118
|
+
return true;
|
|
119
|
+
if (!Number.isFinite(diff) || !Number.isFinite(size)) {
|
|
120
|
+
// R's mean accumulates in long double and does not overflow here: divide by the largest of these |a_ij| (a power
|
|
121
|
+
// of 2, exact); the means are then large, so the test is the relative one, which this leaves unchanged
|
|
122
|
+
({ diff, size } = sums(2 ** -Math.floor(Math.log2(mx))));
|
|
69
123
|
}
|
|
70
124
|
const tol = 100 * Number.EPSILON;
|
|
71
|
-
const
|
|
72
|
-
const
|
|
73
|
-
const xy = diff / N;
|
|
125
|
+
const xn = size / count;
|
|
126
|
+
const xy = diff / count;
|
|
74
127
|
return (Number.isFinite(xn) && xn > tol ? xy / xn : xy) <= tol;
|
|
75
128
|
}
|
|
76
129
|
function symmetricEigen(A, wantVectors) {
|
|
@@ -339,7 +392,15 @@ function normalizeVectors(re, im) {
|
|
|
339
392
|
k = i;
|
|
340
393
|
}
|
|
341
394
|
}
|
|
342
|
-
|
|
395
|
+
// where the sum of squares overflows or leaves the normal range (gebak can scale a component by 2^664 or more:
|
|
396
|
+
// [0, 1e200; 1e-200, 0] gave 6.1e199 and a zero vector), the norm is taken relative to the largest modulus
|
|
397
|
+
let norm = Math.sqrt(ss);
|
|
398
|
+
if (big > 0 && !(ss >= 2 ** -1022 && ss < Infinity)) {
|
|
399
|
+
let rs = 0;
|
|
400
|
+
for (let i = 0; i < n; i++)
|
|
401
|
+
rs += (Math.hypot(re.data[o + i], im.data[o + i]) / big) ** 2;
|
|
402
|
+
norm = big * Math.sqrt(rs);
|
|
403
|
+
}
|
|
343
404
|
if (norm === 0)
|
|
344
405
|
continue;
|
|
345
406
|
// 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
|
}
|