-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
random.ts
438 lines (392 loc) · 11.7 KB
/
random.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import RNG from './rng'
import RNGFactory from './rng-factory'
import uniform from './distributions/uniform'
import uniformInt from './distributions/uniform-int'
import uniformBoolean from './distributions/uniform-boolean'
import normal from './distributions/normal'
import logNormal from './distributions/log-normal'
import bernoulli from './distributions/bernoulli'
import binomial from './distributions/binomial'
import geometric from './distributions/geometric'
import poisson from './distributions/poisson'
import exponential from './distributions/exponential'
import irwinHall from './distributions/irwin-hall'
import bates from './distributions/bates'
import pareto from './distributions/pareto'
import RNGMathRandom from './generators/math-random'
/**
* Distribution function
*/
interface IDistFn<R> {
(random: Random, ...argv: any): R
}
/**
* Distribution
*/
interface IDist<R> {
(): R
}
/**
* Keyed cache entry
*/
interface ICacheEntry<T> {
key: string
distribution: () => T
}
export { RNG, RNGFactory }
/**
* Seedable random number generator supporting many common distributions.
*
* Defaults to Math.random as its underlying pseudorandom number generator.
*
* @name Random
* @class
*
* @param {RNG|function} [rng=Math.random] - Underlying pseudorandom number generator.
*/
export class Random {
protected _rng: RNG
protected _patch: typeof Math.random | undefined
protected _cache: {
[k: string]: ICacheEntry<any>
} = {}
constructor(rng?: RNG) {
if (rng && rng instanceof RNG) {
this.use(rng)
} else {
this.use(new RNGMathRandom())
}
this._cache = {}
}
/**
* @member {RNG} Underlying pseudo-random number generator
*/
get rng() {
return this._rng
}
/**
* Creates a new `Random` instance, optionally specifying parameters to
* set a new seed.
*
* @see RNG.clone
*
* @param {string} [seed] - Optional seed for new RNG.
* @param {object} [opts] - Optional config for new RNG options.
* @return {Random}
*/
clone<T>(...args: [T]): Random {
if (args.length) {
return new Random(RNGFactory(...args))
} else {
return new Random(this.rng.clone())
}
}
/**
* Sets the underlying pseudorandom number generator used via
* either an instance of `seedrandom`, a custom instance of RNG
* (for PRNG plugins), or a string specifying the PRNG to use
* along with an optional `seed` and `opts` to initialize the
* RNG.
*
* @example
* import random from 'random'
*
* random.use('example_seedrandom_string')
* // or
* random.use(seedrandom('kittens'))
* // or
* random.use(Math.random)
*
* @param {...*} args
*/
use(...args: [RNG]) {
this._rng = RNGFactory(...args)
}
/**
* Patches `Math.random` with this Random instance's PRNG.
*/
patch() {
if (this._patch) {
throw new Error('Math.random already patched')
}
this._patch = Math.random
Math.random = this.uniform()
}
/**
* Restores a previously patched `Math.random` to its original value.
*/
unpatch() {
if (this._patch) {
Math.random = this._patch
delete this._patch
}
}
// --------------------------------------------------------------------------
// Uniform utility functions
// --------------------------------------------------------------------------
/**
* Convenience wrapper around `this.rng.next()`
*
* Returns a floating point number in [0, 1).
*
* @return {number}
*/
next = (): number => {
return this._rng.next()
}
/**
* Samples a uniform random floating point number, optionally specifying
* lower and upper bounds.
*
* Convence wrapper around `random.uniform()`
*
* @param {number} [min=0] - Lower bound (float, inclusive)
* @param {number} [max=1] - Upper bound (float, exclusive)
* @return {number}
*/
float = (min?: number, max?: number): number => {
return this.uniform(min, max)()
}
/**
* Samples a uniform random integer, optionally specifying lower and upper
* bounds.
*
* Convence wrapper around `random.uniformInt()`
*
* @param {number} [min=0] - Lower bound (integer, inclusive)
* @param {number} [max=1] - Upper bound (integer, inclusive)
* @return {number}
*/
int = (min?: number, max?: number) => {
return this.uniformInt(min, max)()
}
/**
* Samples a uniform random integer, optionally specifying lower and upper
* bounds.
*
* Convence wrapper around `random.uniformInt()`
*
* @alias `random.int`
*
* @param {number} [min=0] - Lower bound (integer, inclusive)
* @param {number} [max=1] - Upper bound (integer, inclusive)
* @return {number}
*/
integer = (min?: number, max?: number) => {
return this.uniformInt(min, max)()
}
/**
* Samples a uniform random boolean value.
*
* Convence wrapper around `random.uniformBoolean()`
*
* @alias `random.boolean`
*
* @return {boolean}
*/
bool = () => {
return this.uniformBoolean()()
}
/**
* Samples a uniform random boolean value.
*
* Convence wrapper around `random.uniformBoolean()`
*
* @return {boolean}
*/
boolean = () => {
return this.uniformBoolean()()
}
/**
* Returns an item chosen uniformly at trandom from the given array.
*
* Convence wrapper around `random.uniformInt()`
*
* @param {Array<T>} [array] - Lower bound (integer, inclusive)
* @return {T | undefined}
*/
choice<T>(array: Array<T>): T | undefined {
if (!Array.isArray(array)) {
throw new Error(
`Random.choice expected input to be an array, got ${typeof array}`
)
}
const length = array?.length
if (length > 0) {
const index = this.uniformInt(0, length - 1)()
return array[index]
} else {
return undefined
}
}
// --------------------------------------------------------------------------
// Uniform distributions
// --------------------------------------------------------------------------
/**
* Generates a [Continuous uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)).
*
* @param {number} [min=0] - Lower bound (float, inclusive)
* @param {number} [max=1] - Upper bound (float, exclusive)
* @return {function}
*/
uniform = (min?: number, max?: number) => {
return this._memoize<number>('uniform', uniform, min, max)
}
/**
* Generates a [Discrete uniform distribution](https://en.wikipedia.org/wiki/Discrete_uniform_distribution).
*
* @param {number} [min=0] - Lower bound (integer, inclusive)
* @param {number} [max=1] - Upper bound (integer, inclusive)
* @return {function}
*/
uniformInt = (min?: number, max?: number) => {
return this._memoize<number>('uniformInt', uniformInt, min, max)
}
/**
* Generates a [Discrete uniform distribution](https://en.wikipedia.org/wiki/Discrete_uniform_distribution),
* with two possible outcomes, `true` or `false.
*
* This method is analogous to flipping a coin.
*
* @return {function}
*/
uniformBoolean = () => {
return this._memoize<boolean>('uniformBoolean', uniformBoolean)
}
// --------------------------------------------------------------------------
// Normal distributions
// --------------------------------------------------------------------------
/**
* Generates a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution).
*
* @param {number} [mu=0] - Mean
* @param {number} [sigma=1] - Standard deviation
* @return {function}
*/
normal = (mu?: number, sigma?: number) => {
return normal(this, mu, sigma)
}
/**
* Generates a [Log-normal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution).
*
* @param {number} [mu=0] - Mean of underlying normal distribution
* @param {number} [sigma=1] - Standard deviation of underlying normal distribution
* @return {function}
*/
logNormal = (mu?: number, sigma?: number) => {
return logNormal(this, mu, sigma)
}
// --------------------------------------------------------------------------
// Bernoulli distributions
// --------------------------------------------------------------------------
/**
* Generates a [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution).
*
* @param {number} [p=0.5] - Success probability of each trial.
* @return {function}
*/
bernoulli = (p?: number) => {
return bernoulli(this, p)
}
/**
* Generates a [Binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution).
*
* @param {number} [n=1] - Number of trials.
* @param {number} [p=0.5] - Success probability of each trial.
* @return {function}
*/
binomial = (n?: number, p?: number) => {
return binomial(this, n, p)
}
/**
* Generates a [Geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution).
*
* @param {number} [p=0.5] - Success probability of each trial.
* @return {function}
*/
geometric = (p?: number) => {
return geometric(this, p)
}
// --------------------------------------------------------------------------
// Poisson distributions
// --------------------------------------------------------------------------
/**
* Generates a [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution).
*
* @param {number} [lambda=1] - Mean (lambda > 0)
* @return {function}
*/
poisson = (lambda?: number) => {
return poisson(this, lambda)
}
/**
* Generates an [Exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution).
*
* @param {number} [lambda=1] - Inverse mean (lambda > 0)
* @return {function}
*/
exponential = (lambda?: number) => {
return exponential(this, lambda)
}
// --------------------------------------------------------------------------
// Misc distributions
// --------------------------------------------------------------------------
/**
* Generates an [Irwin Hall distribution](https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution).
*
* @param {number} [n=1] - Number of uniform samples to sum (n >= 0)
* @return {function}
*/
irwinHall = (n?: number) => {
return irwinHall(this, n)
}
/**
* Generates a [Bates distribution](https://en.wikipedia.org/wiki/Bates_distribution).
*
* @param {number} [n=1] - Number of uniform samples to average (n >= 1)
* @return {function}
*/
bates = (n?: number) => {
return bates(this, n)
}
/**
* Generates a [Pareto distribution](https://en.wikipedia.org/wiki/Pareto_distribution).
*
* @param {number} [alpha=1] - Alpha
* @return {function}
*/
pareto = (alpha?: number) => {
return pareto(this, alpha)
}
// --------------------------------------------------------------------------
// Internal
// --------------------------------------------------------------------------
/**
* Memoizes distributions to ensure they're only created when necessary.
*
* Returns a thunk which that returns independent, identically distributed
* samples from the specified distribution.
*
* @private
*
* @param {string} label - Name of distribution
* @param {function} getter - Function which generates a new distribution
* @param {...*} args - Distribution-specific arguments
*
* @return {function}
*/
_memoize<T>(label: string, getter: IDistFn<any>, ...args: any[]): IDist<T> {
const key = `${args.join(';')}`
let value = this._cache[label]
if (value === undefined || value.key !== key) {
value = {
key,
distribution: getter(this, ...args)
}
this._cache[label] = value
}
return value.distribution
}
}
// defaults to Math.random as its RNG
export default new Random()