@numero-uno-jpn/rstats 0.7.0 → 0.8.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 +74 -0
- package/README.ja.md +17 -11
- package/README.md +17 -11
- package/THIRD_PARTY_NOTICES.md +30 -0
- package/dist/chunks/{chunk-ZYA4ISAT.js → chunk-32PRRONF.js} +1 -1
- package/dist/chunks/chunk-3I6EKGB6.js +2 -0
- package/dist/chunks/{chunk-BI5RSUZ2.js → chunk-EJRCDJ76.js} +2 -2
- package/dist/chunks/{chunk-JCZAB6C5.js → chunk-I3LAZE6C.js} +2 -2
- package/dist/chunks/chunk-JERGQKZM.js +2 -0
- package/dist/chunks/{chunk-UIOAWLAN.js → chunk-JVYV4633.js} +1 -1
- package/dist/chunks/chunk-LXMMKO26.js +2 -0
- package/dist/chunks/{chunk-YKN6OGJL.js → chunk-MJQLKEO5.js} +2 -2
- package/dist/chunks/{chunk-ZW52Z3GY.js → chunk-OHPHNE3O.js} +1 -1
- package/dist/chunks/{chunk-AFKYWGKN.js → chunk-RZ7SBJEG.js} +2 -2
- package/dist/chunks/{chunk-QNQJA6KZ.js → chunk-SPQC445Q.js} +2 -2
- package/dist/chunks/{chunk-SXSJXDD3.js → chunk-U633VFH3.js} +2 -2
- package/dist/chunks/{chunk-MVG5LUZU.js → chunk-VIPSPG3Y.js} +2 -2
- package/dist/chunks/{chunk-J3SNI7KY.js → chunk-XU4BGFZ6.js} +2 -2
- package/dist/chunks/{chunk-XYXHHF5L.js → chunk-YGWPU67I.js} +1 -1
- package/dist/descriptive.js +2 -2
- package/dist/distributions/beta.js +21 -5
- package/dist/distributions.js +2 -2
- package/dist/entries/distributions.d.ts +2 -1
- package/dist/entries/distributions.js +2 -1
- package/dist/entries/tests.d.ts +1 -0
- package/dist/entries/tests.js +1 -0
- package/dist/htest/brunnerMunzelTest.d.ts +28 -0
- package/dist/htest/brunnerMunzelTest.js +86 -0
- package/dist/linalg.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/random/lecuyer.d.ts +20 -0
- package/dist/random/lecuyer.js +71 -0
- package/dist/random/rng.d.ts +78 -11
- package/dist/random/rng.js +128 -26
- package/dist/random/sample.js +24 -7
- package/dist/random/streams.d.ts +34 -0
- package/dist/random/streams.js +75 -0
- package/dist/rstats.js +3 -3
- package/dist/special/igam.d.ts +1 -0
- package/dist/special/igam.js +1 -1
- package/dist/special/incbet.js +487 -6
- package/dist/special/incbetLargeA.d.ts +15 -0
- package/dist/special/incbetLargeA.js +200 -0
- package/dist/special/incbetTemme.d.ts +19 -0
- package/dist/special/incbetTemme.js +216 -0
- package/dist/special/loader.js +151 -118
- package/dist/special.js +2 -2
- package/dist/tests.js +3 -3
- package/package.json +1 -1
- package/dist/chunks/chunk-6R7YDHA2.js +0 -2
- package/dist/chunks/chunk-ANYGLFT4.js +0 -2
- package/dist/chunks/chunk-PTPPP4TI.js +0 -2
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// L'Ecuyer's MRG32k3a combined multiple recursive generator (R's RNGkind("L'Ecuyer-CMRG")).
|
|
2
|
+
//
|
|
3
|
+
// The recurrences and their constants are those of P. L'Ecuyer (1999) "Good parameters and implementations for
|
|
4
|
+
// combined multiple recursive random number generators" (Operations Research 47(1)). How set.seed() fills the six
|
|
5
|
+
// seeds, how the state maps to a uniform and which states R accepts were verified against R's ?RNG documentation and
|
|
6
|
+
// observed .Random.seed and runif() output (test/fixtures/rngLecuyer.json).
|
|
7
|
+
/** Moduli of the two components */
|
|
8
|
+
export const M1 = 4294967087;
|
|
9
|
+
export const M2 = 4294944443;
|
|
10
|
+
/** 1 / (M1 + 1) */
|
|
11
|
+
const NORM = 2.328306549295727688e-10;
|
|
12
|
+
/** x ↦ 69069 x + 1 (mod 2^32), the congruential generator that set.seed() uses to scramble the seed */
|
|
13
|
+
const lcg = (x) => (Math.imul(69069, x) + 1) >>> 0;
|
|
14
|
+
/**
|
|
15
|
+
* MRG32k3a state: s[0..2] for the first component (mod M1), s[3..5] for the second (mod M2), oldest first.
|
|
16
|
+
* Reading and checking R's .Random.seed are separate functions (below), so that they are left out of bundles
|
|
17
|
+
* that do not use them
|
|
18
|
+
*/
|
|
19
|
+
export class Mrg32k3a {
|
|
20
|
+
s = new Float64Array(6);
|
|
21
|
+
/** Set the same state as R's set.seed(seed, kind = "L'Ecuyer-CMRG") */
|
|
22
|
+
setSeed(seed) {
|
|
23
|
+
// Scramble the seed 50 times, then take the following values of the same sequence, skipping those of M2 or more
|
|
24
|
+
let x = seed >>> 0;
|
|
25
|
+
for (let j = 0; j < 50; j++)
|
|
26
|
+
x = lcg(x);
|
|
27
|
+
for (let j = 0; j < 6; j++) {
|
|
28
|
+
do
|
|
29
|
+
x = lcg(x);
|
|
30
|
+
while (x >= M2);
|
|
31
|
+
this.s[j] = x;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Uniform on (0, 1) (R's unif_rand: never 0 or 1, no further correction needed) */
|
|
35
|
+
nextDouble() {
|
|
36
|
+
const s = this.s;
|
|
37
|
+
// Products are below 2^53, so the arithmetic is exact in doubles
|
|
38
|
+
let p1 = (1403580 * s[1] - 810728 * s[0]) % M1;
|
|
39
|
+
if (p1 < 0)
|
|
40
|
+
p1 += M1;
|
|
41
|
+
s[0] = s[1];
|
|
42
|
+
s[1] = s[2];
|
|
43
|
+
s[2] = p1;
|
|
44
|
+
let p2 = (527612 * s[5] - 1370589 * s[3]) % M2;
|
|
45
|
+
if (p2 < 0)
|
|
46
|
+
p2 += M2;
|
|
47
|
+
s[3] = s[4];
|
|
48
|
+
s[4] = s[5];
|
|
49
|
+
s[5] = p2;
|
|
50
|
+
return (p1 > p2 ? p1 - p2 : p1 - p2 + M1) * NORM;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The six seeds of a .Random.seed for L'Ecuyer-CMRG, as unsigned integers. R accepts a state whose first three seeds
|
|
55
|
+
* are below M1 and not all zero and whose last three are below M2 (and reseeds from the clock otherwise)
|
|
56
|
+
*/
|
|
57
|
+
export function checkState(state) {
|
|
58
|
+
if (state.length !== 7)
|
|
59
|
+
throw new RangeError("the random seed state of L'Ecuyer-CMRG must have 7 integers");
|
|
60
|
+
const s = [];
|
|
61
|
+
for (let i = 1; i <= 6; i++) {
|
|
62
|
+
const v = state[i];
|
|
63
|
+
if (!Number.isInteger(v) || v < -2147483648 || v > 4294967295)
|
|
64
|
+
throw new RangeError("the random seed state must hold 32-bit integers");
|
|
65
|
+
s.push(v >>> 0);
|
|
66
|
+
}
|
|
67
|
+
if ((s[0] === 0 && s[1] === 0 && s[2] === 0) || s.slice(0, 3).some((v) => v >= M1) || s.slice(3).some((v) => v >= M2)) {
|
|
68
|
+
throw new RangeError("invalid L'Ecuyer-CMRG state: the first three seeds must be below 4294967087 and not all zero, the last three below 4294944443");
|
|
69
|
+
}
|
|
70
|
+
return s;
|
|
71
|
+
}
|
package/dist/random/rng.d.ts
CHANGED
|
@@ -1,10 +1,35 @@
|
|
|
1
|
+
/** A uniform random number generator, R's `RNGkind(kind)`. */
|
|
2
|
+
export type RNGKindName = "Mersenne-Twister" | "L'Ecuyer-CMRG";
|
|
3
|
+
/** How `sample` turns uniforms into indices, R's `RNGkind(sample.kind)`. */
|
|
4
|
+
export type SampleKindName = "Rejection" | "Rounding";
|
|
5
|
+
/** Options for {@link RNGkind}. Omitted entries keep the current setting, as in R. */
|
|
6
|
+
export interface RNGKindOptions {
|
|
7
|
+
/** Uniform generator: `"Mersenne-Twister"` (R's default), `"L'Ecuyer-CMRG"`, or `"default"`. */
|
|
8
|
+
kind?: RNGKindName | "default" | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* `"Rejection"` (R's default since 3.6.0), `"Rounding"` (the `sample` of R before 3.6.0, to
|
|
11
|
+
* reproduce older results), or `"default"`.
|
|
12
|
+
*/
|
|
13
|
+
sampleKind?: SampleKindName | "default" | undefined;
|
|
14
|
+
}
|
|
15
|
+
/** The kinds in effect, as returned by {@link RNGkind}. */
|
|
16
|
+
export interface RNGKinds {
|
|
17
|
+
/** The uniform generator. */
|
|
18
|
+
kind: RNGKindName;
|
|
19
|
+
/** Always `"Inversion"` (the only normal kind supported). */
|
|
20
|
+
normalKind: "Inversion";
|
|
21
|
+
/** How `sample` draws indices. */
|
|
22
|
+
sampleKind: SampleKindName;
|
|
23
|
+
}
|
|
1
24
|
/**
|
|
2
25
|
* Seeds the random number generator. Equivalent to R's `set.seed()`.
|
|
3
26
|
*
|
|
4
|
-
*
|
|
5
|
-
* so every `r*` function and `sample`/`sampleInt` produce the
|
|
6
|
-
*
|
|
7
|
-
*
|
|
27
|
+
* Seeds the current generator, R's default `RNGkind("Mersenne-Twister", "Inversion", "Rejection")`
|
|
28
|
+
* unless {@link RNGkind} chose another, so every `r*` function and `sample`/`sampleInt` produce the
|
|
29
|
+
* same numbers as in R after the same seed. R's `set.seed(seed, kind, sample.kind = ...)` is
|
|
30
|
+
* `RNGkind({ kind, sampleKind })` followed by `setSeed(seed)` (R itself does the same). As in R
|
|
31
|
+
* there is a single global stream shared by all functions; if no seed is set, one is chosen from
|
|
32
|
+
* the clock or `crypto.getRandomValues`.
|
|
8
33
|
*
|
|
9
34
|
* @param seed A 32-bit integer. Fractions are truncated toward zero.
|
|
10
35
|
* @throws RangeError if `seed` is not finite or does not fit in a 32-bit integer.
|
|
@@ -17,24 +42,66 @@
|
|
|
17
42
|
* ```
|
|
18
43
|
*/
|
|
19
44
|
export declare function setSeed(seed: number): void;
|
|
45
|
+
/**
|
|
46
|
+
* Reads or changes the kinds of random number generation. Equivalent to R's `RNGkind()`.
|
|
47
|
+
*
|
|
48
|
+
* - `kind: "Mersenne-Twister"` (or `"default"`): R's default generator.
|
|
49
|
+
* - `kind: "L'Ecuyer-CMRG"`: L'Ecuyer's MRG32k3a, with independent streams for parallel work
|
|
50
|
+
* ({@link nextRNGStream}, {@link nextRNGSubStream}).
|
|
51
|
+
* - `sampleKind: "Rounding"`: indices drawn as `floor(n * u)`, as `sample`, `sampleInt` and
|
|
52
|
+
* `rwilcox` did in R before 3.6.0 (slightly non-uniform for large n; R warns about it, rStats.js
|
|
53
|
+
* does not). `"Rejection"` (or `"default"`) is R's default since 3.6.0. Other functions are not
|
|
54
|
+
* affected.
|
|
55
|
+
*
|
|
56
|
+
* As in R, changing `kind` seeds the new generator from the next uniform of the current one (also
|
|
57
|
+
* when the kind does not change), so a stream stays reproducible from the last {@link setSeed};
|
|
58
|
+
* changing only `sampleKind` keeps the stream. Call {@link setSeed} afterwards to seed the new
|
|
59
|
+
* generator directly: `RNGkind({ kind }); setSeed(seed)` is R's `set.seed(seed, kind)`.
|
|
60
|
+
*
|
|
61
|
+
* @param options The kinds to change; omitted entries are kept. Default: change nothing.
|
|
62
|
+
* @returns The kinds in effect before the call (the current ones when called without options), as R.
|
|
63
|
+
* @throws RangeError for an unsupported kind (nothing is changed then).
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* RNGkind(); // { kind: "Mersenne-Twister", normalKind: "Inversion", sampleKind: "Rejection" }
|
|
68
|
+
* RNGkind({ kind: "L'Ecuyer-CMRG" });
|
|
69
|
+
* setSeed(1);
|
|
70
|
+
* runif(2); // [0.6775328286287442, 0.4273457228876442]
|
|
71
|
+
* // R: set.seed(1, kind = "L'Ecuyer-CMRG"); runif(2)
|
|
72
|
+
* RNGkind({ kind: "default", sampleKind: "Rounding" });
|
|
73
|
+
* setSeed(1);
|
|
74
|
+
* sampleInt(10, { size: 3 }); // [2, 3, 4]
|
|
75
|
+
* // R: set.seed(1, kind = "default", sample.kind = "Rounding"); sample.int(10, 3) - 1
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function RNGkind(options?: RNGKindOptions): RNGKinds;
|
|
20
79
|
/**
|
|
21
80
|
* Returns a copy of the current generator state. Equivalent to reading R's `.Random.seed`.
|
|
22
81
|
*
|
|
23
|
-
* @returns
|
|
24
|
-
*
|
|
82
|
+
* @returns The same integers as R's `.Random.seed`: the kind code (`10403` for R's default,
|
|
83
|
+
* `403` with `sampleKind: "Rounding"`, `10407` for L'Ecuyer-CMRG), followed by 625 integers
|
|
84
|
+
* for Mersenne-Twister or 6 for L'Ecuyer-CMRG (unsigned seeds of 2^31 or more appear as
|
|
85
|
+
* negative numbers, as in R). Pass it to {@link setRandomSeed} to restore the state.
|
|
25
86
|
*/
|
|
26
87
|
export declare function getRandomSeed(): Int32Array;
|
|
27
88
|
/**
|
|
28
|
-
* Restores a generator state. Equivalent to assigning R's `.Random.seed`.
|
|
89
|
+
* Restores a generator state, including its kinds. Equivalent to assigning R's `.Random.seed`.
|
|
29
90
|
*
|
|
30
|
-
* @param state
|
|
31
|
-
*
|
|
32
|
-
*
|
|
91
|
+
* @param state The integers returned by {@link getRandomSeed}, or copied from R's `.Random.seed`.
|
|
92
|
+
* @throws RangeError for a kind code other than those of Mersenne-Twister or L'Ecuyer-CMRG with
|
|
93
|
+
* Inversion and Rejection or Rounding (`10403`, `403`, `10407`, `407`), a state of the wrong
|
|
94
|
+
* length, or an invalid L'Ecuyer-CMRG state (R reseeds from the clock in these cases).
|
|
33
95
|
*/
|
|
34
96
|
export declare function setRandomSeed(state: ArrayLike<number>): void;
|
|
35
97
|
/** One uniform on (0, 1) (R's unif_rand) */
|
|
36
98
|
export declare function unifRand(): number;
|
|
37
|
-
/**
|
|
99
|
+
/** Whether sample.kind is "Rounding" (for weighted sampling by Walker's alias method) */
|
|
100
|
+
export declare const isRounding: () => boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Uniform integer in [0, dn) (R's R_unif_index): rejection sampling from random bits (sample.kind = "Rejection"),
|
|
103
|
+
* or floor(dn * u) (sample.kind = "Rounding"), with u made of two uniforms above 2^31 - 1
|
|
104
|
+
*/
|
|
38
105
|
export declare function unifIndex(dn: number): number;
|
|
39
106
|
/** One standard normal variate (R's norm_rand; inversion, using two uniforms for resolution finer than 2^-27) */
|
|
40
107
|
export declare function normRand(): number;
|
package/dist/random/rng.js
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
// RNG state and the basic generators underlying each distribution's variates.
|
|
2
2
|
//
|
|
3
|
-
// As in R, there is a single state (set by setSeed)
|
|
4
|
-
// RNGkind("Mersenne-Twister", "Inversion", "Rejection")
|
|
3
|
+
// As in R, there is a single state (set by setSeed). The default is R's
|
|
4
|
+
// RNGkind("Mersenne-Twister", "Inversion", "Rejection"); the uniform generator can be switched to
|
|
5
|
+
// "L'Ecuyer-CMRG" and the sample kind to "Rounding" (R before 3.6.0).
|
|
5
6
|
// The procedures were verified against R's ?RNG and ?Random documentation and observed output.
|
|
6
7
|
import { MersenneTwister } from "./mt.js";
|
|
8
|
+
import { Mrg32k3a, checkState } from "./lecuyer.js";
|
|
7
9
|
import { ppnd16 } from "./as241.js";
|
|
8
|
-
/** Value of .Random.seed[1]: uniform 3 (Mersenne-Twister) + 100 × normal 4 (Inversion) + 10000 × sample 1 (Rejection) */
|
|
9
|
-
const KIND = 10403;
|
|
10
10
|
const mt = new MersenneTwister();
|
|
11
|
+
/** The current uniform generator: mt, or an L'Ecuyer-CMRG generator */
|
|
12
|
+
let gen = mt;
|
|
13
|
+
let rounding = false;
|
|
11
14
|
let seeded = false;
|
|
15
|
+
/** Seeds the current generator (seed taken as an unsigned 32-bit integer, as R's RNG_Init) */
|
|
16
|
+
function initSeed(seed) {
|
|
17
|
+
gen.setSeed(seed);
|
|
18
|
+
seeded = true;
|
|
19
|
+
}
|
|
12
20
|
function ensureSeeded() {
|
|
13
21
|
if (seeded)
|
|
14
22
|
return;
|
|
@@ -17,16 +25,17 @@ function ensureSeeded() {
|
|
|
17
25
|
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
18
26
|
s = globalThis.crypto.getRandomValues(new Uint32Array(1))[0];
|
|
19
27
|
}
|
|
20
|
-
|
|
21
|
-
seeded = true;
|
|
28
|
+
initSeed(s);
|
|
22
29
|
}
|
|
23
30
|
/**
|
|
24
31
|
* Seeds the random number generator. Equivalent to R's `set.seed()`.
|
|
25
32
|
*
|
|
26
|
-
*
|
|
27
|
-
* so every `r*` function and `sample`/`sampleInt` produce the
|
|
28
|
-
*
|
|
29
|
-
*
|
|
33
|
+
* Seeds the current generator, R's default `RNGkind("Mersenne-Twister", "Inversion", "Rejection")`
|
|
34
|
+
* unless {@link RNGkind} chose another, so every `r*` function and `sample`/`sampleInt` produce the
|
|
35
|
+
* same numbers as in R after the same seed. R's `set.seed(seed, kind, sample.kind = ...)` is
|
|
36
|
+
* `RNGkind({ kind, sampleKind })` followed by `setSeed(seed)` (R itself does the same). As in R
|
|
37
|
+
* there is a single global stream shared by all functions; if no seed is set, one is chosen from
|
|
38
|
+
* the clock or `crypto.getRandomValues`.
|
|
30
39
|
*
|
|
31
40
|
* @param seed A 32-bit integer. Fractions are truncated toward zero.
|
|
32
41
|
* @throws RangeError if `seed` is not finite or does not fit in a 32-bit integer.
|
|
@@ -44,49 +53,142 @@ export function setSeed(seed) {
|
|
|
44
53
|
const s = Math.trunc(seed);
|
|
45
54
|
if (Math.abs(s) > 2147483647)
|
|
46
55
|
throw new RangeError("seed must be a 32-bit integer");
|
|
47
|
-
|
|
48
|
-
|
|
56
|
+
initSeed(s);
|
|
57
|
+
}
|
|
58
|
+
/** R's names of the kinds: true for L'Ecuyer-CMRG and for Rounding */
|
|
59
|
+
const KINDS = { default: false, "Mersenne-Twister": false, "L'Ecuyer-CMRG": true };
|
|
60
|
+
const SAMPLE_KINDS = { default: false, Rejection: false, Rounding: true };
|
|
61
|
+
/** The value of an option in its table (undefined if omitted) */
|
|
62
|
+
function lookup(table, name, what) {
|
|
63
|
+
if (name === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const v = table[name];
|
|
66
|
+
if (typeof v !== "boolean")
|
|
67
|
+
throw new RangeError(`unsupported ${what} "${name}"`);
|
|
68
|
+
return v;
|
|
49
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Reads or changes the kinds of random number generation. Equivalent to R's `RNGkind()`.
|
|
72
|
+
*
|
|
73
|
+
* - `kind: "Mersenne-Twister"` (or `"default"`): R's default generator.
|
|
74
|
+
* - `kind: "L'Ecuyer-CMRG"`: L'Ecuyer's MRG32k3a, with independent streams for parallel work
|
|
75
|
+
* ({@link nextRNGStream}, {@link nextRNGSubStream}).
|
|
76
|
+
* - `sampleKind: "Rounding"`: indices drawn as `floor(n * u)`, as `sample`, `sampleInt` and
|
|
77
|
+
* `rwilcox` did in R before 3.6.0 (slightly non-uniform for large n; R warns about it, rStats.js
|
|
78
|
+
* does not). `"Rejection"` (or `"default"`) is R's default since 3.6.0. Other functions are not
|
|
79
|
+
* affected.
|
|
80
|
+
*
|
|
81
|
+
* As in R, changing `kind` seeds the new generator from the next uniform of the current one (also
|
|
82
|
+
* when the kind does not change), so a stream stays reproducible from the last {@link setSeed};
|
|
83
|
+
* changing only `sampleKind` keeps the stream. Call {@link setSeed} afterwards to seed the new
|
|
84
|
+
* generator directly: `RNGkind({ kind }); setSeed(seed)` is R's `set.seed(seed, kind)`.
|
|
85
|
+
*
|
|
86
|
+
* @param options The kinds to change; omitted entries are kept. Default: change nothing.
|
|
87
|
+
* @returns The kinds in effect before the call (the current ones when called without options), as R.
|
|
88
|
+
* @throws RangeError for an unsupported kind (nothing is changed then).
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* ```ts
|
|
92
|
+
* RNGkind(); // { kind: "Mersenne-Twister", normalKind: "Inversion", sampleKind: "Rejection" }
|
|
93
|
+
* RNGkind({ kind: "L'Ecuyer-CMRG" });
|
|
94
|
+
* setSeed(1);
|
|
95
|
+
* runif(2); // [0.6775328286287442, 0.4273457228876442]
|
|
96
|
+
* // R: set.seed(1, kind = "L'Ecuyer-CMRG"); runif(2)
|
|
97
|
+
* RNGkind({ kind: "default", sampleKind: "Rounding" });
|
|
98
|
+
* setSeed(1);
|
|
99
|
+
* sampleInt(10, { size: 3 }); // [2, 3, 4]
|
|
100
|
+
* // R: set.seed(1, kind = "default", sample.kind = "Rounding"); sample.int(10, 3) - 1
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
export function RNGkind(options = {}) {
|
|
104
|
+
const previous = {
|
|
105
|
+
kind: gen === mt ? "Mersenne-Twister" : "L'Ecuyer-CMRG",
|
|
106
|
+
normalKind: "Inversion",
|
|
107
|
+
sampleKind: rounding ? "Rounding" : "Rejection",
|
|
108
|
+
};
|
|
109
|
+
const useLec = lookup(KINDS, options.kind, "RNG kind");
|
|
110
|
+
const useRounding = lookup(SAMPLE_KINDS, options.sampleKind, "sample kind");
|
|
111
|
+
if (useLec !== undefined) {
|
|
112
|
+
// The new generator is seeded with the next uniform u (0 < u < 1) times 2^32 - 1, truncated to an unsigned integer
|
|
113
|
+
const seed = Math.trunc(unifRand() * 4294967295);
|
|
114
|
+
gen = useLec ? (gen === mt ? new Mrg32k3a() : gen) : mt;
|
|
115
|
+
initSeed(seed);
|
|
116
|
+
}
|
|
117
|
+
if (useRounding !== undefined)
|
|
118
|
+
rounding = useRounding;
|
|
119
|
+
return previous;
|
|
120
|
+
}
|
|
121
|
+
/** Value of .Random.seed[1]: uniform kind (3 Mersenne-Twister, 7 L'Ecuyer-CMRG) + 100 × normal 4 (Inversion) + 10000 × sample kind (0 Rounding, 1 Rejection) */
|
|
122
|
+
const kindCode = () => (gen === mt ? 3 : 7) + 400 + (rounding ? 0 : 10000);
|
|
50
123
|
/**
|
|
51
124
|
* Returns a copy of the current generator state. Equivalent to reading R's `.Random.seed`.
|
|
52
125
|
*
|
|
53
|
-
* @returns
|
|
54
|
-
*
|
|
126
|
+
* @returns The same integers as R's `.Random.seed`: the kind code (`10403` for R's default,
|
|
127
|
+
* `403` with `sampleKind: "Rounding"`, `10407` for L'Ecuyer-CMRG), followed by 625 integers
|
|
128
|
+
* for Mersenne-Twister or 6 for L'Ecuyer-CMRG (unsigned seeds of 2^31 or more appear as
|
|
129
|
+
* negative numbers, as in R). Pass it to {@link setRandomSeed} to restore the state.
|
|
55
130
|
*/
|
|
56
131
|
export function getRandomSeed() {
|
|
57
132
|
ensureSeeded();
|
|
58
|
-
|
|
133
|
+
if (gen === mt)
|
|
134
|
+
return mt.getRandomSeed(kindCode());
|
|
135
|
+
// The six seeds of L'Ecuyer-CMRG, as signed 32-bit integers
|
|
136
|
+
return Int32Array.of(kindCode(), ...gen.s);
|
|
59
137
|
}
|
|
60
138
|
/**
|
|
61
|
-
* Restores a generator state. Equivalent to assigning R's `.Random.seed`.
|
|
139
|
+
* Restores a generator state, including its kinds. Equivalent to assigning R's `.Random.seed`.
|
|
62
140
|
*
|
|
63
|
-
* @param state
|
|
64
|
-
*
|
|
65
|
-
*
|
|
141
|
+
* @param state The integers returned by {@link getRandomSeed}, or copied from R's `.Random.seed`.
|
|
142
|
+
* @throws RangeError for a kind code other than those of Mersenne-Twister or L'Ecuyer-CMRG with
|
|
143
|
+
* Inversion and Rejection or Rounding (`10403`, `403`, `10407`, `407`), a state of the wrong
|
|
144
|
+
* length, or an invalid L'Ecuyer-CMRG state (R reseeds from the clock in these cases).
|
|
66
145
|
*/
|
|
67
146
|
export function setRandomSeed(state) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
147
|
+
const code = state[0];
|
|
148
|
+
const uniform = code % 100;
|
|
149
|
+
if (!Number.isInteger(code) || code < 0 || code > 10407 || (uniform !== 3 && uniform !== 7) || Math.floor(code / 100) % 100 !== 4) {
|
|
150
|
+
throw new RangeError(`unsupported RNG kind code ${String(code)} (supported: 10403, 403, 10407, 407)`);
|
|
151
|
+
}
|
|
152
|
+
if (uniform === 7) {
|
|
153
|
+
const g = new Mrg32k3a();
|
|
154
|
+
g.s.set(checkState(state));
|
|
155
|
+
gen = g;
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
mt.setRandomSeed(state);
|
|
159
|
+
gen = mt;
|
|
160
|
+
}
|
|
161
|
+
rounding = code < 10000;
|
|
71
162
|
seeded = true;
|
|
72
163
|
}
|
|
73
164
|
/** One uniform on (0, 1) (R's unif_rand) */
|
|
74
165
|
export function unifRand() {
|
|
75
166
|
ensureSeeded();
|
|
76
|
-
return
|
|
167
|
+
return gen.nextDouble();
|
|
77
168
|
}
|
|
169
|
+
/** Whether sample.kind is "Rounding" (for weighted sampling by Walker's alias method) */
|
|
170
|
+
export const isRounding = () => rounding;
|
|
78
171
|
/** Build a bits-bit integer from uniforms (taking 16 bits at a time) */
|
|
79
172
|
function rbits(bits) {
|
|
173
|
+
// Only the low bits bits are kept. Reducing v modulo 2^(bits - 16) before each shift keeps it below 2^53
|
|
174
|
+
// (exact in doubles) without changing those bits
|
|
175
|
+
const mask = 2 ** Math.max(bits - 16, 0);
|
|
80
176
|
let v = 0;
|
|
81
177
|
for (let n = 0; n <= bits; n += 16) {
|
|
82
178
|
const v1 = Math.floor(unifRand() * 65536);
|
|
83
|
-
v = 65536 * v + v1;
|
|
179
|
+
v = 65536 * (v % mask) + v1;
|
|
84
180
|
}
|
|
85
|
-
// Keep only the low bits bits (v is below 2^53, so take the remainder modulo 2^bits)
|
|
86
181
|
return v % 2 ** bits;
|
|
87
182
|
}
|
|
88
|
-
/**
|
|
183
|
+
/** 2^25 */
|
|
184
|
+
const U25 = 33554432;
|
|
185
|
+
/**
|
|
186
|
+
* Uniform integer in [0, dn) (R's R_unif_index): rejection sampling from random bits (sample.kind = "Rejection"),
|
|
187
|
+
* or floor(dn * u) (sample.kind = "Rounding"), with u made of two uniforms above 2^31 - 1
|
|
188
|
+
*/
|
|
89
189
|
export function unifIndex(dn) {
|
|
190
|
+
if (rounding)
|
|
191
|
+
return Math.floor(dn * (dn > 2147483647 ? (Math.floor(U25 * unifRand()) + unifRand()) / U25 : unifRand()));
|
|
90
192
|
if (dn <= 0)
|
|
91
193
|
return 0;
|
|
92
194
|
const bits = Math.ceil(Math.log2(dn));
|
package/dist/random/sample.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// Random sampling: sample and sampleInt.
|
|
2
2
|
//
|
|
3
|
-
// Uses uniforms the same way as R
|
|
3
|
+
// Uses uniforms the same way as R (with sample.kind "Rejection", the default, or "Rounding") and returns the same
|
|
4
|
+
// results as R.
|
|
4
5
|
// Weighted sampling sorts the weights in decreasing order and selects by cumulative probability (with replacement,
|
|
5
6
|
// when more than 200 candidates have large weights, Walker's (1977) alias method). The sort is a heapsort,
|
|
6
7
|
// and the order of equal weights also matches R.
|
|
7
8
|
// All of this was verified against observed R output.
|
|
8
|
-
import { unifIndex, unifRand } from "./rng.js";
|
|
9
|
+
import { isRounding, unifIndex, unifRand } from "./rng.js";
|
|
9
10
|
/**
|
|
10
11
|
* Random sample of integers from `0..n-1`. Equivalent to R's `sample.int()`, but 0-based.
|
|
11
12
|
*
|
|
@@ -27,8 +28,8 @@ export function sampleInt(n, options = {}) {
|
|
|
27
28
|
}
|
|
28
29
|
/** Sample from 1..n (1-based values as in R; internal) */
|
|
29
30
|
function sampleInt1(n, options) {
|
|
30
|
-
if (!Number.isFinite(n) || n < 0 || n
|
|
31
|
-
throw new RangeError("n must be a non-negative number
|
|
31
|
+
if (!Number.isFinite(n) || n < 0 || n > 4.5e15)
|
|
32
|
+
throw new RangeError("n must be a non-negative number up to 4.5e15");
|
|
32
33
|
n = Math.trunc(n);
|
|
33
34
|
const { replace = false, prob } = options;
|
|
34
35
|
const sizeGiven = options.size !== undefined;
|
|
@@ -37,6 +38,8 @@ function sampleInt1(n, options) {
|
|
|
37
38
|
throw new RangeError("size must be a non-negative number");
|
|
38
39
|
const k = Math.trunc(size);
|
|
39
40
|
if (prob !== undefined) {
|
|
41
|
+
if (n >= 2 ** 31)
|
|
42
|
+
throw new RangeError("n must be less than 2^31 with prob");
|
|
40
43
|
if (prob.length !== n)
|
|
41
44
|
throw new TypeError("prob must have length n");
|
|
42
45
|
const p = fixupProb(prob, k, replace);
|
|
@@ -72,6 +75,8 @@ function sampleInt1(n, options) {
|
|
|
72
75
|
out[i] = unifIndex(n) + 1;
|
|
73
76
|
return out;
|
|
74
77
|
}
|
|
78
|
+
if (n >= 2 ** 31)
|
|
79
|
+
throw new RangeError("n must be less than 2^31 to sample without replacement with size above n / 2");
|
|
75
80
|
const x = new Int32Array(n);
|
|
76
81
|
for (let i = 0; i < n; i++)
|
|
77
82
|
x[i] = i;
|
|
@@ -245,11 +250,23 @@ function walkerSample(p, k) {
|
|
|
245
250
|
break;
|
|
246
251
|
}
|
|
247
252
|
}
|
|
248
|
-
// Pick candidate t
|
|
253
|
+
// Pick candidate t, then use the fraction of t + u to choose t or its alias a[t]. With sample.kind "Rounding", t + u
|
|
254
|
+
// is n times one uniform; otherwise t is a uniform integer and u another uniform. The comparison is made on t + u
|
|
255
|
+
// and q[t] + t, as R does (in doubles)
|
|
256
|
+
const rounding = isRounding();
|
|
249
257
|
const out = new Array(k);
|
|
250
258
|
for (let i = 0; i < k; i++) {
|
|
251
|
-
|
|
252
|
-
|
|
259
|
+
let t;
|
|
260
|
+
let rU;
|
|
261
|
+
if (rounding) {
|
|
262
|
+
rU = unifRand() * n;
|
|
263
|
+
t = Math.trunc(rU);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
t = unifIndex(n);
|
|
267
|
+
rU = t + unifRand();
|
|
268
|
+
}
|
|
269
|
+
out[i] = rU < q[t] + t ? t + 1 : a[t] + 1;
|
|
253
270
|
}
|
|
254
271
|
return out;
|
|
255
272
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The start of the next stream of L'Ecuyer-CMRG: the state advanced by 2^127 steps.
|
|
3
|
+
* Equivalent to R's `parallel::nextRNGStream()`.
|
|
4
|
+
*
|
|
5
|
+
* Streams started this way do not overlap for any practical length, so each parallel task
|
|
6
|
+
* (a worker, or one replicate of a simulation) can be given its own stream, reproducibly.
|
|
7
|
+
* Within a stream, {@link nextRNGSubStream} gives substreams of 2^76 steps.
|
|
8
|
+
*
|
|
9
|
+
* @param state A 7-integer state as returned by {@link getRandomSeed} after
|
|
10
|
+
* `RNGkind({ kind: "L'Ecuyer-CMRG" })`, or copied from R's `.Random.seed`.
|
|
11
|
+
* @returns A new state of the same form (the first element, the kind code, is unchanged).
|
|
12
|
+
* Pass it to {@link setRandomSeed} to draw from that stream.
|
|
13
|
+
* @throws RangeError if `state` is not a valid L'Ecuyer-CMRG state.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* RNGkind({ kind: "L'Ecuyer-CMRG" });
|
|
18
|
+
* setSeed(1);
|
|
19
|
+
* const s1 = getRandomSeed();
|
|
20
|
+
* const s2 = nextRNGStream(s1); // R: s2 <- parallel::nextRNGStream(.Random.seed)
|
|
21
|
+
* setRandomSeed(s2);
|
|
22
|
+
* runif(2); // [0.31369782407981056, 0.9280126525616814]
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function nextRNGStream(state: ArrayLike<number>): Int32Array;
|
|
26
|
+
/**
|
|
27
|
+
* The start of the next substream of L'Ecuyer-CMRG: the state advanced by 2^76 steps.
|
|
28
|
+
* Equivalent to R's `parallel::nextRNGSubStream()`.
|
|
29
|
+
*
|
|
30
|
+
* @param state A 7-integer state, as for {@link nextRNGStream}.
|
|
31
|
+
* @returns A new state of the same form.
|
|
32
|
+
* @throws RangeError if `state` is not a valid L'Ecuyer-CMRG state.
|
|
33
|
+
*/
|
|
34
|
+
export declare function nextRNGSubStream(state: ArrayLike<number>): Int32Array;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Independent streams and substreams of L'Ecuyer-CMRG: R's parallel::nextRNGStream() and nextRNGSubStream().
|
|
2
|
+
//
|
|
3
|
+
// Jumping ahead by 2^127 (stream) or 2^76 (substream) steps multiplies each component's state vector by a power of
|
|
4
|
+
// its transition matrix, modulo the component's modulus. The matrices are those published in P. L'Ecuyer,
|
|
5
|
+
// R. Simard, E. J. Chen and W. D. Kelton (2002) "An object-oriented random-number package with many long streams
|
|
6
|
+
// and substreams" (Operations Research 50(6)); test/random-kinds.test.ts recomputes them from the recurrences of
|
|
7
|
+
// L'Ecuyer (1999). The layout of the state (R's .Random.seed) follows test/fixtures/rngStreams.json.
|
|
8
|
+
import { M1, M2, checkState } from "./lecuyer.js";
|
|
9
|
+
// Row by row; A1 acts on the first component (mod M1), A2 on the second (mod M2)
|
|
10
|
+
const A1P76 = [82758667, 1871391091, 4127413238, 3672831523, 69195019, 1871391091, 3672091415, 3528743235, 69195019];
|
|
11
|
+
const A2P76 = [1511326704, 3759209742, 1610795712, 4292754251, 1511326704, 3889917532, 3859662829, 4292754251, 3708466080];
|
|
12
|
+
const A1P127 = [2427906178, 3580155704, 949770784, 226153695, 1230515664, 3580155704, 1988835001, 986791581, 1230515664];
|
|
13
|
+
const A2P127 = [1464411153, 277697599, 1610723613, 32183930, 1464411153, 1022607788, 2824425944, 32183930, 2093834863];
|
|
14
|
+
/** a b mod m for a, b below 2^32, exactly (splitting b into 16-bit halves keeps every product below 2^53) */
|
|
15
|
+
function mulMod(a, b, m) {
|
|
16
|
+
const hi = Math.floor(b / 65536);
|
|
17
|
+
return (((a * hi) % m) * 65536 + a * (b - hi * 65536)) % m;
|
|
18
|
+
}
|
|
19
|
+
function jump(state, a1, a2) {
|
|
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)");
|
|
23
|
+
const s = checkState(state);
|
|
24
|
+
const out = new Int32Array(7);
|
|
25
|
+
out[0] = code;
|
|
26
|
+
for (let c = 0; c < 2; c++) {
|
|
27
|
+
const a = c === 0 ? a1 : a2;
|
|
28
|
+
const m = c === 0 ? M1 : M2;
|
|
29
|
+
for (let i = 0; i < 3; i++) {
|
|
30
|
+
let t = 0;
|
|
31
|
+
for (let j = 0; j < 3; j++)
|
|
32
|
+
t = (t + mulMod(a[3 * i + j], s[3 * c + j], m)) % m;
|
|
33
|
+
out[1 + 3 * c + i] = t | 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The start of the next stream of L'Ecuyer-CMRG: the state advanced by 2^127 steps.
|
|
40
|
+
* Equivalent to R's `parallel::nextRNGStream()`.
|
|
41
|
+
*
|
|
42
|
+
* Streams started this way do not overlap for any practical length, so each parallel task
|
|
43
|
+
* (a worker, or one replicate of a simulation) can be given its own stream, reproducibly.
|
|
44
|
+
* Within a stream, {@link nextRNGSubStream} gives substreams of 2^76 steps.
|
|
45
|
+
*
|
|
46
|
+
* @param state A 7-integer state as returned by {@link getRandomSeed} after
|
|
47
|
+
* `RNGkind({ kind: "L'Ecuyer-CMRG" })`, or copied from R's `.Random.seed`.
|
|
48
|
+
* @returns A new state of the same form (the first element, the kind code, is unchanged).
|
|
49
|
+
* Pass it to {@link setRandomSeed} to draw from that stream.
|
|
50
|
+
* @throws RangeError if `state` is not a valid L'Ecuyer-CMRG state.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* RNGkind({ kind: "L'Ecuyer-CMRG" });
|
|
55
|
+
* setSeed(1);
|
|
56
|
+
* const s1 = getRandomSeed();
|
|
57
|
+
* const s2 = nextRNGStream(s1); // R: s2 <- parallel::nextRNGStream(.Random.seed)
|
|
58
|
+
* setRandomSeed(s2);
|
|
59
|
+
* runif(2); // [0.31369782407981056, 0.9280126525616814]
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
export function nextRNGStream(state) {
|
|
63
|
+
return jump(state, A1P127, A2P127);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The start of the next substream of L'Ecuyer-CMRG: the state advanced by 2^76 steps.
|
|
67
|
+
* Equivalent to R's `parallel::nextRNGSubStream()`.
|
|
68
|
+
*
|
|
69
|
+
* @param state A 7-integer state, as for {@link nextRNGStream}.
|
|
70
|
+
* @returns A new state of the same form.
|
|
71
|
+
* @throws RangeError if `state` is not a valid L'Ecuyer-CMRG state.
|
|
72
|
+
*/
|
|
73
|
+
export function nextRNGSubStream(state) {
|
|
74
|
+
return jump(state, A1P76, A2P76);
|
|
75
|
+
}
|