@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
@@ -7,6 +7,10 @@
7
7
  import { expRand, normRand, unifRand } from "./rng.js";
8
8
  import { generate } from "./common.js";
9
9
  import { rgamma1 } from "./gamma.js";
10
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
11
+ import { checkOptions } from "../internal/checkOptions.js";
12
+ const RNBINOM_KEYS = ["prob", "mu"];
13
+ // Generated by `node scripts/option-keys.mjs --write` (end)
10
14
  const A0 = -0.5, A1 = 0.3333333, A2 = -0.2500068, A3 = 0.2000118;
11
15
  const A4 = -0.1661269, A5 = 0.1421878, A6 = -0.1384794, A7 = 0.125006;
12
16
  const ONE_7 = 1 / 7, ONE_12 = 1 / 12, ONE_24 = 1 / 24;
@@ -185,9 +189,27 @@ export function rgeom(n, prob) {
185
189
  return generate(n, () => {
186
190
  if (!Number.isFinite(prob) || prob <= 0 || prob > 1)
187
191
  return NaN;
188
- return rpois1(expRand() * ((1 - prob) / prob));
192
+ // for prob below about 5.6e-309, (1 - prob) / prob overflows while E (1 - prob) / prob is finite unless E is large
193
+ // (with probability 0.16 at prob = 1e-309; R gives NaN): the exponential draw first. A mean that overflows
194
+ // itself gives Infinity
195
+ const odds = (1 - prob) / prob;
196
+ const e = expRand();
197
+ const mu = Number.isFinite(odds) ? e * odds : (e * (1 - prob)) / prob;
198
+ return mu === Infinity ? Infinity : rpois1(mu);
189
199
  });
190
200
  }
201
+ /**
202
+ * A Poisson variate whose mean is a gamma variate with shape sz and scale num / den. Where the scale overflows (prob
203
+ * below about 5.6e-309, or mu / size; R gives NaN) the unit gamma variate is multiplied by num and divided by den, which
204
+ * is finite unless the variate is large; a mean that overflows itself gives Infinity
205
+ */
206
+ function poissonOfGamma(sz, num, den) {
207
+ const scale = num / den;
208
+ if (Number.isFinite(scale))
209
+ return rpois1(rgamma1(sz, scale));
210
+ const m = (rgamma1(sz, 1) * num) / den;
211
+ return m === Infinity ? Infinity : rpois1(m);
212
+ }
191
213
  /**
192
214
  * Random numbers from the negative binomial distribution. Equivalent to R's `rnbinom()`.
193
215
  *
@@ -208,6 +230,7 @@ export function rgeom(n, prob) {
208
230
  * @category Random numbers
209
231
  */
210
232
  export function rnbinom(n, size, options) {
233
+ checkOptions(options, RNBINOM_KEYS, "rnbinom"); // generated: option-keys.mjs
211
234
  const { prob, mu } = options;
212
235
  if ((prob === undefined) === (mu === undefined))
213
236
  throw new TypeError("specify exactly one of prob and mu");
@@ -216,13 +239,18 @@ export function rnbinom(n, size, options) {
216
239
  return generate(n, () => {
217
240
  if (!Number.isFinite(mu) || Number.isNaN(size) || size <= 0 || mu < 0)
218
241
  return NaN;
219
- return mu === 0 ? 0 : rpois1(rgamma1(sz, mu / sz));
242
+ return mu === 0 ? 0 : poissonOfGamma(sz, mu, sz);
220
243
  });
221
244
  }
222
245
  const p = prob;
223
246
  return generate(n, () => {
224
247
  if (!Number.isFinite(p) || Number.isNaN(size) || size <= 0 || p <= 0 || p > 1)
225
248
  return NaN;
226
- return p === 1 ? 0 : rpois1(rgamma1(sz, (1 - p) / p));
249
+ if (p === 1)
250
+ return 0;
251
+ const v = poissonOfGamma(sz, 1 - p, p);
252
+ // size = Inf with a fixed prob < 1 puts all the probability at infinity (dnbinom 0, qnbinom Inf): Infinity, where R
253
+ // returns the draw for size = MAX / 2 (about 9e307); the same variates are drawn, so the stream stays R's
254
+ return size === Infinity ? Infinity : v;
227
255
  });
228
256
  }
@@ -1,3 +1,9 @@
1
+ /**
2
+ * The largest grand total for which the table of log factorials (total + 1 doubles, 128 MB at the limit) is built:
3
+ * r2dtable and the simulated p-values of chisqTest and fisherTest (#285, #286, #336); the same 2^24 as the exact
4
+ * supports of fisherTest and mantelhaenTest (#232)
5
+ */
6
+ export declare const MAX_TABLE_TOTAL: number;
1
7
  /** log k! for k = 0..n, accumulated as sums of logs (the table AS 159 uses) */
2
8
  export declare function logFactorialTable(n: number): Float64Array;
3
9
  /**
@@ -15,7 +21,8 @@ export declare function rcont2(r: readonly number[], c: readonly number[], fact:
15
21
  * @param r Row totals (non-negative integers, at least two).
16
22
  * @param c Column totals (non-negative integers, at least two), with the same sum as `r`.
17
23
  * @returns An array of `n` tables, each `r.length` rows of `c.length` counts.
18
- * @throws RangeError for invalid arguments or totals that differ.
24
+ * @throws RangeError for invalid arguments or totals that differ, and (when n >= 1) for a grand total above 2^24
25
+ * (16777216; R allows up to 2147483647), as the table of log factorials has total + 1 entries.
19
26
  *
20
27
  * @example
21
28
  * ```ts
@@ -12,6 +12,12 @@
12
12
  // whose remaining total ie is 0 (all later rows and columns empty) is 0 without a draw. This consumes uniforms as R's
13
13
  // r2dtable does (checked against R's output).
14
14
  import { unifRand } from "./rng.js";
15
+ /**
16
+ * The largest grand total for which the table of log factorials (total + 1 doubles, 128 MB at the limit) is built:
17
+ * r2dtable and the simulated p-values of chisqTest and fisherTest (#285, #286, #336); the same 2^24 as the exact
18
+ * supports of fisherTest and mantelhaenTest (#232)
19
+ */
20
+ export const MAX_TABLE_TOTAL = 2 ** 24;
15
21
  /** log k! for k = 0..n, accumulated as sums of logs (the table AS 159 uses) */
16
22
  export function logFactorialTable(n) {
17
23
  const f = new Float64Array(n + 1);
@@ -125,7 +131,8 @@ function margins(v, name) {
125
131
  * @param r Row totals (non-negative integers, at least two).
126
132
  * @param c Column totals (non-negative integers, at least two), with the same sum as `r`.
127
133
  * @returns An array of `n` tables, each `r.length` rows of `c.length` counts.
128
- * @throws RangeError for invalid arguments or totals that differ.
134
+ * @throws RangeError for invalid arguments or totals that differ, and (when n >= 1) for a grand total above 2^24
135
+ * (16777216; R allows up to 2147483647), as the table of log factorials has total + 1 entries.
129
136
  *
130
137
  * @example
131
138
  * ```ts
@@ -136,14 +143,28 @@ function margins(v, name) {
136
143
  * @category Random numbers
137
144
  */
138
145
  export function r2dtable(n, r, c) {
139
- const count = Math.trunc(n);
140
- if (!(count >= 0))
146
+ // as R's as.integer(n): infinite values and values beyond the integer range are NA there, an error (an infinite n
147
+ // ran the loop below forever); the truncation comes first, so -0.5 is 0 and 2147483647.5 is 2147483647 (#93)
148
+ if (!(Number.isFinite(n) && n > -1 && n < 2 ** 31))
141
149
  throw new RangeError("invalid argument 'n'");
150
+ const count = Math.trunc(n);
142
151
  const rows = margins(r, "r");
143
152
  const cols = margins(c, "c");
144
153
  const total = rows.reduce((a, b) => a + b, 0);
145
154
  if (total !== cols.reduce((a, b) => a + b, 0))
146
155
  throw new RangeError("arguments 'r' and 'c' must have the same sums");
156
+ // the table of log factorials has total + 1 entries: a total beyond the integer range (R's integer sum overflows and
157
+ // the allocation fails) would take tens of gigabytes
158
+ if (total > 2147483647)
159
+ throw new RangeError("the sum of 'r' must be at most 2147483647");
160
+ // no table asked for: the margins are checked (as R) but the table of log factorials, total + 1 entries, is not
161
+ // built (16 GB for a total of 2e9) (#219)
162
+ if (count === 0)
163
+ return [];
164
+ // the table of log factorials is limited to 2^24 + 1 entries (128 MB); R builds it for any total up to 2147483647
165
+ // (8 GB for r2dtable(1, c(5e8, 5e8), c(5e8, 5e8))) (#336)
166
+ if (total > MAX_TABLE_TOTAL)
167
+ throw new RangeError("the sum of 'r' must be at most 16777216 (2^24) to generate tables");
147
168
  const fact = logFactorialTable(total);
148
169
  const out = new Int32Array(rows.length * cols.length);
149
170
  const tables = [];
@@ -23,6 +23,8 @@ export declare function rsignrank(nn: number, n: number): number[];
23
23
  * @param m Number of observations in the first sample.
24
24
  * @param n Number of observations in the second sample.
25
25
  * @returns An array of `nn` values; `NaN` for invalid parameters.
26
+ * @throws RangeError if `m + n` exceeds 2147483647 or `n` exceeds 2^24 (one uniform is drawn per value of the second
27
+ * sample), before drawing.
26
28
  *
27
29
  * @example
28
30
  * ```ts
@@ -3,6 +3,7 @@
3
3
  // Uniform consumption follows observed R output.
4
4
  import { unifIndex, unifRand } from "./rng.js";
5
5
  import { generate } from "./common.js";
6
+ import { roundHalfEven } from "../internal/integer.js";
6
7
  /**
7
8
  * Random numbers from the distribution of the Wilcoxon signed rank statistic.
8
9
  * Equivalent to R's `rsignrank()`.
@@ -21,13 +22,18 @@ import { generate } from "./common.js";
21
22
  */
22
23
  export function rsignrank(nn, n) {
23
24
  return generate(nn, () => {
24
- if (Number.isNaN(n))
25
+ // an infinite n would never end the loop below (R's (int) cast of it is undefined)
26
+ if (!Number.isFinite(n))
25
27
  return NaN;
26
- const k = Math.round(n);
28
+ // as R's R_forceint (nearbyint): halves go to the even integer
29
+ const k = roundHalfEven(n);
27
30
  if (k < 0)
28
31
  return NaN;
29
32
  if (k === 0)
30
33
  return 0;
34
+ // one uniform per rank: bounded to the domain of dsignrank (about 4 s here; R runs to 2147483647)
35
+ if (k >= 2 ** 27)
36
+ throw new RangeError("n must be less than 2^27 (134217728)");
31
37
  let r = 0;
32
38
  // Choose the sign of rank i with a uniform
33
39
  for (let i = 1; i <= k; i++)
@@ -35,6 +41,29 @@ export function rsignrank(nn, n) {
35
41
  return r;
36
42
  });
37
43
  }
44
+ /** Bound on n of rwilcox, and on the m + n ranks held in an array (beyond, the swapped ones in a Map) */
45
+ const MAX_RWILCOX_N = 2 ** 24;
46
+ /**
47
+ * The sum of n of the ranks 0..k-1 drawn without replacement, as the array version of rwilcox (the same uniforms and
48
+ * the same value) with only the slots that hold another rank than their own kept, in a Map: at most n - 1 of them, as
49
+ * the last draw updates none (an Int32Array of m + n, up to 8 GB, was filled for each value)
50
+ */
51
+ function sparseRankSum(k, n) {
52
+ const moved = new Map();
53
+ let r = 0;
54
+ for (let i = 0; i < n; i++) {
55
+ const j = unifIndex(k);
56
+ r += moved.get(j) ?? j;
57
+ k--;
58
+ if (i === n - 1)
59
+ break;
60
+ // x[j] = x[k]; the slot k is out of reach from now on
61
+ if (j !== k)
62
+ moved.set(j, moved.get(k) ?? k);
63
+ moved.delete(k);
64
+ }
65
+ return r;
66
+ }
38
67
  /**
39
68
  * Random numbers from the distribution of the Wilcoxon rank sum statistic.
40
69
  * Equivalent to R's `rwilcox()`.
@@ -43,6 +72,8 @@ export function rsignrank(nn, n) {
43
72
  * @param m Number of observations in the first sample.
44
73
  * @param n Number of observations in the second sample.
45
74
  * @returns An array of `nn` values; `NaN` for invalid parameters.
75
+ * @throws RangeError if `m + n` exceeds 2147483647 or `n` exceeds 2^24 (one uniform is drawn per value of the second
76
+ * sample), before drawing.
46
77
  *
47
78
  * @example
48
79
  * ```ts
@@ -56,14 +87,23 @@ export function rwilcox(nn, m, n) {
56
87
  return generate(nn, () => {
57
88
  if (Number.isNaN(m) || Number.isNaN(n))
58
89
  return NaN;
59
- const mm = Math.round(m);
60
- const ny = Math.round(n);
90
+ // as R's R_forceint (nearbyint): halves go to the even integer
91
+ const mm = roundHalfEven(m);
92
+ const ny = roundHalfEven(n);
61
93
  if (mm < 0 || ny < 0)
62
94
  return NaN;
63
95
  if (mm === 0 || ny === 0)
64
96
  return 0;
97
+ // R holds the m + n ranks in an array, whose allocation fails beyond its integer range
98
+ if (!(mm + ny <= 2147483647))
99
+ throw new RangeError("m + n must be at most 2147483647");
100
+ // one uniform per rank drawn (about 3.5 s at 2^24), before drawing
101
+ if (ny > MAX_RWILCOX_N)
102
+ throw new RangeError("n must be at most 2^24 (16777216)");
65
103
  // Choose n of 0..m+n-1 without replacement and subtract the minimum n(n-1)/2 from their sum
66
104
  let k = mm + ny;
105
+ if (k > MAX_RWILCOX_N)
106
+ return sparseRankSum(k, ny) - (ny * (ny - 1)) / 2;
67
107
  const x = new Int32Array(k);
68
108
  for (let i = 0; i < k; i++)
69
109
  x[i] = i;
@@ -7,6 +7,9 @@
7
7
  import { MersenneTwister } from "./mt.js";
8
8
  import { Mrg32k3a, checkState } from "./lecuyer.js";
9
9
  import { ppnd16 } from "./as241.js";
10
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
11
+ import { checkOptions } from "../internal/checkOptions.js";
12
+ const RNGKIND_KEYS = ["kind", "sampleKind"];
10
13
  const mt = new MersenneTwister();
11
14
  /** The current uniform generator: mt, or an L'Ecuyer-CMRG generator */
12
15
  let gen = mt;
@@ -105,6 +108,7 @@ function lookup(table, name, what) {
105
108
  * @category Random numbers
106
109
  */
107
110
  export function RNGkind(options = {}) {
111
+ checkOptions(options, RNGKIND_KEYS, "RNGkind"); // generated: option-keys.mjs
108
112
  const previous = {
109
113
  kind: gen === mt ? "Mersenne-Twister" : "L'Ecuyer-CMRG",
110
114
  normalKind: "Inversion",
@@ -4,7 +4,10 @@
4
4
  * @category Random numbers
5
5
  */
6
6
  export interface SampleOptions {
7
- /** Number of items to draw. Default: the number of candidates (a random permutation). */
7
+ /**
8
+ * Number of items to draw (truncated, as R; below 2^31 with `prob`). Default: the number of candidates (a random
9
+ * permutation).
10
+ */
8
11
  size?: number;
9
12
  /** Sample with replacement. Default `false`. */
10
13
  replace?: boolean;
@@ -17,7 +20,8 @@ export interface SampleOptions {
17
20
  * The result is R's `sample.int(n, ...)` minus 1, so it can be used directly as array
18
21
  * indices. It consumes the same random numbers as R (default `sample.kind = "Rejection"`).
19
22
  *
20
- * @param n Number of candidates (a non-negative number less than 2^31).
23
+ * @param n Number of candidates: a non-negative number up to 4.5e15 (2^52, as R); below 2^31 with `prob`, and for
24
+ * sampling without replacement more than n / 2 of them.
21
25
  * @param options See {@link SampleOptions}.
22
26
  * @returns The drawn integers, each in `0..n-1`.
23
27
  *
@@ -30,6 +34,12 @@ export interface SampleOptions {
30
34
  * @category Random numbers
31
35
  */
32
36
  export declare function sampleInt(n: number, options?: SampleOptions): number[];
37
+ /**
38
+ * One draw at a time from 0..n-1 with replacement and weights `prob`: the same draws, from the same uniforms, as
39
+ * consecutive elements of `sampleInt(n, { size, replace: true, prob })` (the method depends only on n and prob), with
40
+ * the same checks of n and prob. For simulations that count draws without keeping them (internal; #287)
41
+ */
42
+ export declare function sampleIntReplaceDrawer(n: number, prob: readonly number[]): () => number;
33
43
  /**
34
44
  * Random sample of the elements of an array. Equivalent to R's `sample()`.
35
45
  *
@@ -7,13 +7,19 @@
7
7
  // and the order of equal weights also matches R.
8
8
  // All of this was verified against observed R output.
9
9
  import { isRounding, unifIndex, unifRand } from "./rng.js";
10
+ import { maxOf } from "../internal/extremes.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 SAMPLE_KEYS = ["size", "replace", "prob"];
14
+ const SAMPLE_INT_KEYS = ["size", "replace", "prob"];
10
15
  /**
11
16
  * Random sample of integers from `0..n-1`. Equivalent to R's `sample.int()`. Unlike R, it is 0-based.
12
17
  *
13
18
  * The result is R's `sample.int(n, ...)` minus 1, so it can be used directly as array
14
19
  * indices. It consumes the same random numbers as R (default `sample.kind = "Rejection"`).
15
20
  *
16
- * @param n Number of candidates (a non-negative number less than 2^31).
21
+ * @param n Number of candidates: a non-negative number up to 4.5e15 (2^52, as R); below 2^31 with `prob`, and for
22
+ * sampling without replacement more than n / 2 of them.
17
23
  * @param options See {@link SampleOptions}.
18
24
  * @returns The drawn integers, each in `0..n-1`.
19
25
  *
@@ -26,6 +32,7 @@ import { isRounding, unifIndex, unifRand } from "./rng.js";
26
32
  * @category Random numbers
27
33
  */
28
34
  export function sampleInt(n, options = {}) {
35
+ checkOptions(options, SAMPLE_INT_KEYS, "sampleInt"); // generated: option-keys.mjs
29
36
  return sampleInt1(n, options).map((v) => v - 1);
30
37
  }
31
38
  /** Sample from 1..n (1-based values as in R; internal) */
@@ -36,21 +43,27 @@ function sampleInt1(n, options) {
36
43
  const { replace = false, prob } = options;
37
44
  const sizeGiven = options.size !== undefined;
38
45
  const size = sizeGiven ? options.size : n;
39
- if (!Number.isFinite(size) || size < 0)
46
+ // truncated first, as R: a size in (-1, 0) is 0 (#94)
47
+ if (!Number.isFinite(size) || size <= -1)
40
48
  throw new RangeError("size must be a non-negative number");
41
49
  const k = Math.trunc(size);
50
+ if (n === 0 && k > 0)
51
+ throw new RangeError("cannot take a sample from an empty population");
42
52
  if (prob !== undefined) {
53
+ // R's weighted path takes size as an integer: 2^31 or more is rejected before any allocation or draw (#414)
54
+ if (k >= 2 ** 31)
55
+ throw new RangeError("size must be less than 2^31 with prob");
43
56
  if (n >= 2 ** 31)
44
57
  throw new RangeError("n must be less than 2^31 with prob");
45
58
  if (prob.length !== n)
46
59
  throw new TypeError("prob must have length n");
47
60
  const p = fixupProb(prob, k, replace);
48
61
  if (replace) {
49
- let nc = 0;
50
- for (let i = 0; i < n; i++)
51
- if (n * p[i] > 0.1)
52
- nc++;
53
- return nc > 200 ? walkerSample(p, k) : probSampleReplace(p, k);
62
+ const draw = replaceDrawer(p);
63
+ const out = new Array(k);
64
+ for (let i = 0; i < k; i++)
65
+ out[i] = draw();
66
+ return out;
54
67
  }
55
68
  if (k > n)
56
69
  throw new RangeError("cannot take a sample larger than the population when replace is false");
@@ -90,6 +103,31 @@ function sampleInt1(n, options) {
90
103
  }
91
104
  return out;
92
105
  }
106
+ /**
107
+ * One draw at a time from 0..n-1 with replacement and weights `prob`: the same draws, from the same uniforms, as
108
+ * consecutive elements of `sampleInt(n, { size, replace: true, prob })` (the method depends only on n and prob), with
109
+ * the same checks of n and prob. For simulations that count draws without keeping them (internal; #287)
110
+ */
111
+ export function sampleIntReplaceDrawer(n, prob) {
112
+ if (!Number.isFinite(n) || n < 0 || n > 4.5e15)
113
+ throw new RangeError("n must be a non-negative number up to 4.5e15");
114
+ n = Math.trunc(n);
115
+ if (n >= 2 ** 31)
116
+ throw new RangeError("n must be less than 2^31 with prob");
117
+ if (prob.length !== n)
118
+ throw new TypeError("prob must have length n");
119
+ const draw = replaceDrawer(fixupProb(prob, 0, true));
120
+ return () => draw() - 1;
121
+ }
122
+ /** The weighted draw with replacement (1-based): Walker's alias method with more than 200 large weights, as R */
123
+ function replaceDrawer(p) {
124
+ const n = p.length;
125
+ let nc = 0;
126
+ for (let i = 0; i < n; i++)
127
+ if (n * p[i] > 0.1)
128
+ nc++;
129
+ return nc > 200 ? walkerDrawer(p) : probReplaceDrawer(p);
130
+ }
93
131
  /**
94
132
  * Random sample of the elements of an array. Equivalent to R's `sample()`.
95
133
  *
@@ -111,6 +149,7 @@ function sampleInt1(n, options) {
111
149
  * @category Random numbers
112
150
  */
113
151
  export function sample(x, options = {}) {
152
+ checkOptions(options, SAMPLE_KEYS, "sample"); // generated: option-keys.mjs
114
153
  return sampleInt1(x.length, options).map((i) => x[i - 1]);
115
154
  }
116
155
  /** Validate the weights and normalise them to sum to 1 */
@@ -129,6 +168,14 @@ function fixupProb(prob, k, replace) {
129
168
  }
130
169
  if (npos === 0 || (!replace && k > npos))
131
170
  throw new RangeError("too few positive probabilities");
171
+ if (sum === Infinity) {
172
+ // Finite weights whose sum overflows: rescale by the largest before summing
173
+ const mx = maxOf(prob);
174
+ sum = 0;
175
+ for (const v of prob)
176
+ sum += v / mx;
177
+ return Float64Array.from(prob, (v) => v / mx / sum);
178
+ }
132
179
  return Float64Array.from(prob, (v) => v / sum);
133
180
  }
134
181
  /** Sort a in decreasing order, permuting ib alongside (heapsort; ties end up in the same order as R) */
@@ -185,22 +232,20 @@ function sortedByWeight(p) {
185
232
  revsort(p, perm);
186
233
  return perm;
187
234
  }
188
- function probSampleReplace(prob, k) {
235
+ function probReplaceDrawer(prob) {
189
236
  const p = Float64Array.from(prob);
190
237
  const n = p.length;
191
238
  const perm = sortedByWeight(p);
192
239
  for (let i = 1; i < n; i++)
193
240
  p[i] += p[i - 1];
194
- const out = new Array(k);
195
- for (let i = 0; i < k; i++) {
241
+ return () => {
196
242
  const rU = unifRand();
197
243
  let j = 0;
198
244
  for (; j < n - 1; j++)
199
245
  if (rU <= p[j])
200
246
  break;
201
- out[i] = perm[j];
202
- }
203
- return out;
247
+ return perm[j];
248
+ };
204
249
  }
205
250
  function probSampleNoReplace(prob, k) {
206
251
  const p = Float64Array.from(prob);
@@ -226,8 +271,8 @@ function probSampleNoReplace(prob, k) {
226
271
  }
227
272
  return out;
228
273
  }
229
- /** Sampling with replacement by Walker's alias method */
230
- function walkerSample(p, k) {
274
+ /** Sampling with replacement by Walker's alias method (one draw per call) */
275
+ function walkerDrawer(p) {
231
276
  const n = p.length;
232
277
  const q = new Float64Array(n);
233
278
  const a = new Int32Array(n);
@@ -258,8 +303,7 @@ function walkerSample(p, k) {
258
303
  // is n times one uniform; otherwise t is a uniform integer and u another uniform. The comparison is made on t + u
259
304
  // and q[t] + t, as R does (in doubles)
260
305
  const rounding = isRounding();
261
- const out = new Array(k);
262
- for (let i = 0; i < k; i++) {
306
+ return () => {
263
307
  let t;
264
308
  let rU;
265
309
  if (rounding) {
@@ -270,7 +314,6 @@ function walkerSample(p, k) {
270
314
  t = unifIndex(n);
271
315
  rU = t + unifRand();
272
316
  }
273
- out[i] = rU < q[t] + t ? t + 1 : a[t] + 1;
274
- }
275
- return out;
317
+ return rU < q[t] + t ? t + 1 : a[t] + 1;
318
+ };
276
319
  }
@@ -18,8 +18,10 @@ function mulMod(a, b, m) {
18
18
  }
19
19
  function jump(state, a1, a2) {
20
20
  const code = state[0];
21
- if (!Number.isInteger(code) || code % 100 !== 7)
22
- throw new RangeError("the state must be a .Random.seed of L'Ecuyer-CMRG (kind code ending in 07)");
21
+ // the kind codes setRandomSeed takes for L'Ecuyer-CMRG (R accepts any code ending in 07, such as 7, which would give a
22
+ // state setRandomSeed cannot restore)
23
+ if (code !== 10407 && code !== 407)
24
+ throw new RangeError("the state must be a .Random.seed of L'Ecuyer-CMRG (kind code 10407 or 407)");
23
25
  const s = checkState(state);
24
26
  const out = new Int32Array(7);
25
27
  out[0] = code;