@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.
Files changed (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. 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
+ }
@@ -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;
@@ -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
- out.data[i + j * a.ncol] = s;
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
- b[o + i] -= bk * a[i + k * lda];
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
- b[o + i] -= bk * a[i + k * lda];
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
- t -= a[k + i * lda] * b[o + k];
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
- t -= a[k + i * lda] * b[o + k];
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
+ }
@@ -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 { pivot, rank } = pstf2(a, options.tol ?? -1);
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
+ }
@@ -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
- /** Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)) */
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;
@@ -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
- const symmetric = options.symmetric ?? isSymmetric(a);
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
- return symmetric ? symmetricEigen(a, wantVectors) : generalEigen(a, wantVectors);
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
- /** Same test as R's isSymmetric (all.equal(A, t(A), tolerance = 100 ε)) */
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
- let diff = 0;
63
- let size = 0;
64
- for (let j = 0; j < n; j++) {
65
- for (let i = 0; i < n; i++) {
66
- diff += Math.abs(a.data[i + j * n] - a.data[j + i * n]);
67
- size += Math.abs(a.data[i + j * n]);
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 N = n * n;
72
- const xn = size / N;
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
- const norm = Math.sqrt(ss);
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
@@ -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), used only by `"Pade"`, `"Taylor"`,
23
- * `"PadeO"` and `"TaylorO"`. Default: 8.
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
  }