Debian Codegraph @

easel/esl_random.c

raw symbols SCIP
1 /* Portable, threadsafe Mersenne Twister random number generator
2 *
3 * 1. The ESL_RANDOMNESS object.
4 * 2. The generators, esl_random().
5 * 3. Debugging/development tools.
6 * 4. Other fundamental sampling (including Gaussian, gamma).
7 * 5. Multinomial sampling from discrete probability n-vectors.
8 * 6. Random data generators (unit testing, etc.)
9 * 7. Benchmark driver
10 * 8. Unit tests.
11 * 9. Test driver.
12 * 10. Example.
13 *
14 * NIST test suite for validating random number generators:
15 * https://csrc.nist.gov/projects/random-bit-generation/documentation-and-software
16 *
17 * It'd be nice if we had a debugging/unit testing mode in which
18 * esl_random() deliberately generated extreme values, such as 0 for
19 * example. Routines that use esl_random() can be sensitive to whether
20 * the interval 0,1 is open or closed. We should be able to test for
21 * problems with interval endpoints without taking enormous numbers of
22 * samples.
23 *
24 * Competitive alternatives to MT exist, including PCG [http://www.pcg-random.org/].
25 */
26 #include <esl_config.h>
27
28 #include <stdlib.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <math.h>
34 #include <time.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38
39 #include "easel.h"
40 #include "esl_random.h"
41
42 static uint32_t choose_arbitrary_seed(void);
43 static uint32_t knuth (ESL_RANDOMNESS *r);
44 static uint32_t mersenne_twister (ESL_RANDOMNESS *r);
45 static void mersenne_seed_table(ESL_RANDOMNESS *r, uint32_t seed);
46 static void mersenne_fill_table(ESL_RANDOMNESS *r);
47
48 /*****************************************************************
49 *# 1. The <ESL_RANDOMNESS> object.
50 *****************************************************************/
51
52 /* Function: esl_randomness_Create()
53 * Synopsis: Create the default strong random number generator.
54 *
55 * Purpose: Create a random number generator using
56 * a given random seed.
57 *
58 * The default random number generator uses the Mersenne
59 * Twister MT19937 algorithm \citep{Matsumoto98}. It has a
60 * period of $2^{19937}-1$, and equidistribution over
61 * $2^{32}$ values.
62 *
63 * If <seed> is $>0$, the random number generator is
64 * reproducibly initialized with that seed. Two RNGs
65 * created with the same nonzero seed will give exactly the
66 * same stream of pseudorandom numbers. This allows you to
67 * make reproducible stochastic simulations, for example.
68 *
69 * If <seed> is 0, an arbitrary seed is chosen.
70 * Internally, this comes from hashing together the current
71 * <time()>, <clock()>, and process id. Two RNGs created
72 * with <seed>=0 probably (but not assuredly) give
73 * different streams of pseudorandom numbers. The true seed
74 * can be retrieved from the <ESL_RANDOMNESS> object using
75 * <esl_randomness_GetSeed()>. The strategy used for
76 * choosing the arbitrary seed is predictable; it should
77 * not be considered cryptographically secure.
78 *
79 * Args: seed $>= 0$.
80 *
81 * Returns: an initialized <ESL_RANDOMNESS *> on success.
82 * Caller free's with <esl_randomness_Destroy()>.
83 *
84 * Throws: <NULL> on failure.
85 *
86 * Xref: SRE:STL8/p57.
87 * SRE:J5/21: Mersenne Twister.
88 */
89 ESL_RANDOMNESS *
90 esl_randomness_Create(uint32_t seed)
91 {
92 ESL_RANDOMNESS *r = NULL;
93 int status;
94
95 ESL_ALLOC(r, sizeof(ESL_RANDOMNESS));
96 r->type = eslRND_MERSENNE;
97 r->mti = 0;
98 r->x = 0;
99 r->seed = 0;
100 esl_randomness_Init(r, seed);
101 return r;
102
103 ERROR:
104 return NULL;
105 }
106
107 /* Function: esl_randomness_CreateFast()
108 * Synopsis: Create the alternative fast generator.
109 *
110 * THIS FUNCTION IS DEPRECATED. USE esl_randomness_Create() INSTEAD.
111 *
112 * Purpose: Same as <esl_randomness_Create()>, except that a simple
113 * linear congruential generator (LCG) will be used.
114 * This is a $(a=69069, c=1)$ LCG, with a period of
115 * $2^{32}$.
116 *
117 * This is a low quality RNG. It fails several standard
118 * NIST statistical tests. Successive samples from an LCG
119 * are correlated, and it has a relatively short period. IT
120 * SHOULD NOT BE USED (period). It is present in Easel for
121 * legacy reasons. It used to be substantially faster than
122 * our high quality RNG, but now our default Mersenne
123 * Twister is plenty fast. We have regression and unit
124 * tests that use the LCG and depend on a fixed seed and a
125 * particular pseudorandom number sequence; they would have
126 * to be re-studied carefully to upgrade them to a
127 * different RNG.
128 *
129 * Here's an example of how serial correlation arises in an
130 * LCG, and how it can lead to serious (and difficult to
131 * diagnose) failure in a Monte Carlo simulation. An LCG
132 * calculates $x_{i+1} = ax_i + c$. Suppose $x_i$ is small:
133 * in the range 0..6000, say, as a specific example. Now
134 * $x_{i+1}$ cannot be larger than 4.1e8, for an LCG with
135 * $a=69069$,$c=1$. So if you take a sample and test
136 * whether it is $< 1e-6$ (say), the next sample will be in
137 * a range of about 0..0.1, rather than being uniform on
138 * 0..1.
139 *
140 * Args: seed $>= 0$.
141 *
142 * Returns: an initialized <ESL_RANDOMNESS *> on success.
143 * Caller free's with <esl_randomness_Destroy()>.
144 *
145 * Throws: <NULL> on failure.
146 *
147 * Xref: SRE:J5/44: for accidental proof that period is indeed 2^32.
148 */
149 ESL_RANDOMNESS *
150 esl_randomness_CreateFast(uint32_t seed)
151 {
152 ESL_RANDOMNESS *r = NULL;
153 int status;
154
155 ESL_ALLOC(r, sizeof(ESL_RANDOMNESS));
156 r->type = eslRND_FAST;
157 r->mti = 0;
158 r->x = 0;
159 r->seed = 0;
160 esl_randomness_Init(r, seed);
161 return r;
162
163 ERROR:
164 return NULL;
165 }
166
167
168 /* Function: esl_randomness_CreateTimeseeded()
169 * Synopsis: Create an RNG with a quasirandom seed.
170 *
171 * THIS FUNCTION IS DEPRECATED. USE esl_randomness_Create(0).
172 *
173 * Purpose: Like <esl_randomness_Create()>, but it initializes the
174 * the random number generator using a POSIX <time()> call
175 * (number of seconds since the POSIX epoch).
176 *
177 * This function is deprecated. Use
178 * <esl_randomness_Create(0)> instead.
179 *
180 * Returns: an initialized <ESL_RANDOMNESS *> on success.
181 * Caller free's with <esl_randomness_Destroy()>.
182 *
183 * Throws: <NULL> on failure.
184 *
185 * Xref: SRE:STL8/p57.
186 */
187 ESL_RANDOMNESS *
188 esl_randomness_CreateTimeseeded(void)
189 {
190 return esl_randomness_Create(0);
191 }
192
193
194 /* Function: esl_randomness_Init()
195 * Synopsis: Reinitialize a RNG.
196 *
197 * Purpose: Reset and reinitialize an existing <ESL_RANDOMNESS>
198 * object with a new seed.
199 *
200 * Sometimes it's useful to reseed an RNG to guarantee a
201 * particular reproducible series of pseudorandom numbers
202 * at an arbitrary point in a program; HMMER does this, for
203 * example, to guarantee the same results from the same
204 * HMM/sequence comparison regardless of where in a search
205 * the HMM or sequence occurs.
206 *
207 * Args: r - randomness object
208 * seed - new seed to use; >=0.
209 *
210 * Returns: <eslOK> on success.
211 *
212 * Xref: SRE:STL8/p57.
213 */
214 int
215 esl_randomness_Init(ESL_RANDOMNESS *r, uint32_t seed)
216 {
217 if (seed == 0) seed = choose_arbitrary_seed();
218 if (r->type == eslRND_MERSENNE)
219 {
220 mersenne_seed_table(r, seed);
221 mersenne_fill_table(r);
222 }
223 else
224 {
225 r->seed = seed;
226 r->x = esl_mix3(seed, 87654321, 12345678); /* arbitrary dispersion of the seed */
227 if (r->x == 0) r->x = 42; /* make sure we don't have a zero */
228 }
229 return eslOK;
230 }
231
232 /* Function: esl_randomness_GetSeed()
233 * Synopsis: Returns the value of RNG's seed.
234 *
235 * Purpose: Return the value of the seed.
236 */
237 uint32_t
238 esl_randomness_GetSeed(const ESL_RANDOMNESS *r)
239 {
240 return r->seed;
241 }
242
243
244 /* Function: esl_randomness_Destroy()
245 * Synopsis: Free an RNG.
246 *
247 * Purpose: Frees an <ESL_RANDOMNESS> object.
248 */
249 void
250 esl_randomness_Destroy(ESL_RANDOMNESS *r)
251 {
252 free(r);
253 return;
254 }
255
256 /*----------- end of ESL_RANDOMNESS object functions --------------*/
257
258
259
260 /*****************************************************************
261 *# 2. The generators and <esl_random()>
262 *****************************************************************/
263
264 /* Function: esl_random()
265 * Synopsis: Generate a uniform random deviate on [0,1)
266 *
267 * Purpose: Returns a uniform deviate x, $0.0 \leq x < 1.0$, given
268 * RNG <r>.
269 *
270 * This new u \in [0,1) still has 2^32-1 possible values.
271 * The base RNG generates a uint32 on range d = [0,2^32).
272 * All of these integers d are exactly representable in a
273 * double, and so is d/2^32.
274 *
275 * Don't cast the return value to float. The [0,1) interval
276 * guarantee will be lost because values close to 1 will
277 * round to 1.0. More subtly, roundoff also affects other
278 * values; the significand of a float has only 23 bits.
279 *
280 * Returns: a uniformly distributed random deviate on interval
281 * $0.0 \leq x < 1.0$.
282 */
283 double
284 esl_random(ESL_RANDOMNESS *r)
285 {
286 uint32_t x = (r->type == eslRND_MERSENNE) ? mersenne_twister(r) : knuth(r);
287 return ((double) x / 4294967296.0); // 2^32: [0,1). Original MT code has * (1.0/ 4294967296.0), which I believe (and tested) to be identical.
288 }
289
290
291 /* Function: esl_random_uint32()
292 * Synopsis: Generate a uniform random deviate on 0..2^32-1
293 * Incept: SRE, Wed Jan 13 10:59:26 2016
294 *
295 * Purpose: Returns a uniform deviate x, a 32-bit unsigned
296 * integer $0 \leq x < 2^{32}$, given RNG <r>.
297 */
298 uint32_t
299 esl_random_uint32(ESL_RANDOMNESS *r)
300 {
301 return (r->type == eslRND_MERSENNE) ? mersenne_twister(r) : knuth(r);
302 }
303
304
305 /* Function: esl_rnd_Roll()
306 * Synopsis: Generate a uniform random integer 0..n-1.
307 * Incept: SRE, Mon 31 Jul 2023
308 *
309 * Purpose: Generate a uniformly distributed integer on range
310 * 0..n-1, for n>0 and n<2^31.
311 */
312 int
313 esl_rnd_Roll(ESL_RANDOMNESS *r, int n)
314 {
315 ESL_DASSERT1(( n>0 ));
316 uint32_t factor = UINT32_MAX / (uint32_t) n;
317 uint32_t u;
318
319 do { u = esl_random_uint32(r) / factor; } while (u >= n);
320 return (int) u;
321 }
322
323
324 static uint32_t
325 knuth(ESL_RANDOMNESS *r)
326 {
327 r->x *= 69069;
328 r->x += 1;
329 return r->x;
330 }
331
332 /* mersenne_twister() and other mersenne_*() functions below:
333 * A simple serial implementation of the original Mersenne Twister
334 * algorithm [Matsumoto98].
335 *
336 * There are more sophisticated and faster implementations of MT, using
337 * vector instructions and/or directly generating IEEE754 doubles
338 * bitwise rather than doing an expensive normalization. We can
339 * improve the implementation later if necessary, but even the basic
340 * MT offers ~10x speed improvement over Easel's previous RNG.
341 * [SRE, 30 May 09, Stockholm]
342 */
343 static uint32_t
344 mersenne_twister(ESL_RANDOMNESS *r)
345 {
346 uint32_t x;
347 if (r->mti >= 624) mersenne_fill_table(r);
348
349 x = r->mt[r->mti++];
350 x ^= (x >> 11);
351 x ^= (x << 7) & 0x9d2c5680;
352 x ^= (x << 15) & 0xefc60000;
353 x ^= (x >> 18);
354 return x;
355 }
356
357 /* mersenne_seed_table()
358 * Initialize the state of the RNG from a seed, using a Knuth LCG.
359 *
360 * TODO: In January 2002, Nishimura and Matsumoto replaced this with a
361 * better initialization. (Why did I use their ~1999 initialization
362 * when I adapted MT in June 2009?) They say that the problem with
363 * this version is that the seed's most significant bit has little
364 * effect on the MT state vector. Upgrading this will require effort
365 * though: any change to the output of our RNG will break numerous
366 * unit tests and regressions that use fixed RNG seeds to get
367 * reproducible streams.
368 */
369 static void
370 mersenne_seed_table(ESL_RANDOMNESS *r, uint32_t seed)
371 {
372 int z;
373
374 r->seed = seed;
375 r->mt[0] = seed;
376 for (z = 1; z < 624; z++)
377 r->mt[z] = 69069 * r->mt[z-1];
378 return;
379 }
380
381 /* mersenne_fill_table()
382 * Refill the table with 624 new random numbers.
383 * We do this whenever we've reseeded, or when we
384 * run out of numbers.
385 */
386 static void
387 mersenne_fill_table(ESL_RANDOMNESS *r)
388 {
389 uint32_t y;
390 int z;
391 static uint32_t mag01[2] = { 0x0, 0x9908b0df };
392
393 for (z = 0; z < 227; z++) /* 227 = N-M = 624-397 */
394 {
395 y = (r->mt[z] & 0x80000000) | (r->mt[z+1] & 0x7fffffff);
396 r->mt[z] = r->mt[z+397] ^ (y>>1) ^ mag01[(int)(y & 0x1)]; /* yes, the (int) cast is necessary; xref bug #e7; some compilers may try to cast y to signed int otherwise, to use it in an array index */
397 }
398 for (; z < 623; z++)
399 {
400 y = (r->mt[z] & 0x80000000) | (r->mt[z+1] & 0x7fffffff);
401 r->mt[z] = r->mt[z-227] ^ (y>>1) ^ mag01[(int)(y & 0x1)];
402 }
403 y = (r->mt[623] & 0x80000000) | (r->mt[0] & 0x7fffffff);
404 r->mt[623] = r->mt[396] ^ (y>>1) ^ mag01[(int)(y & 0x1)];
405 r->mti = 0;
406
407 return;
408 }
409
410
411 /* choose_arbitrary_seed()
412 * Return a 'quasirandom' seed > 0, concocted by hashing time(),
413 * clock(), and getpid() together.
414 * See RFC1750 for a discussion of securely seeding RNGs.
415 */
416 static uint32_t
417 choose_arbitrary_seed(void)
418 {
419 uint32_t a = (uint32_t) time ((time_t *) NULL);
420 uint32_t b = 87654321; // we'll use getpid() below, if we can
421 uint32_t c = (uint32_t) clock(); // clock() gives time since process invocation, in msec at least, if not usec
422 uint32_t seed;
423 #ifdef HAVE_GETPID
424 b = (uint32_t) getpid(); // preferable b choice, if we have POSIX getpid()
425 #endif
426 seed = esl_mix3(a,b,c); // try to decorrelate closely spaced choices of pid/times
427 return (seed == 0) ? 42 : seed; // 42 is arbitrary, just to avoid seed==0.
428 }
429
430
431 /*----------- end of esl_random() --------------*/
432
433
434
435 /*****************************************************************
436 *# 3. Debugging and development tools
437 *****************************************************************/
438
439 /* Function: esl_randomness_Dump()
440 * Synopsis: Dump ESL_RANDOMNESS object to stream, for debugging/examination.
441 */
442 int
443 esl_randomness_Dump(FILE *fp, ESL_RANDOMNESS *r)
444 {
445 if (r->type == eslRND_FAST)
446 {
447 fputs ("type = knuth\n", fp );
448 fprintf(fp, "state = %" PRIu32 "\n", r->x);
449 fprintf(fp, "seed = %" PRIu32 "\n", r->seed);
450 }
451 else if (r->type == eslRND_MERSENNE)
452 {
453 int i,j;
454
455 fputs ("type = mersenne twister\n", fp );
456 fprintf(fp, "mti = %d (0..623)\n", r->mti);
457 fprintf(fp, "mt[mti] = %" PRIu32 "\n", r->mt[r->mti]);
458
459 fprintf(fp, "%6d: ", 0);
460 for (i = 0, j=0; i < 624; i++)
461 {
462 fprintf(fp, "%11" PRIu32 " ", r->mt[i]);
463 if (++j == 20) { fprintf(fp, "\n%6d: ", i+1); j=0; }
464 }
465 fputs("\n", fp);
466 }
467 return eslOK;
468 }
469 /*----------- end, debugging/development tools ------------------*/
470
471
472 /*****************************************************************
473 *# 4. Other fundamental sampling (including Gaussian, gamma)
474 *****************************************************************/
475
476 /* Function: esl_rnd_UniformPositive()
477 * Synopsis: Generate a uniform positive random deviate on interval (0,1).
478 *
479 * Purpose: Same as <esl_random()>, but assure $0 < x < 1$;
480 * (positive uniform deviate).
481 */
482 double
483 esl_rnd_UniformPositive(ESL_RANDOMNESS *r)
484 {
485 double x;
486 do { x = esl_random(r); } while (x == 0.0);
487 return x;
488 }
489
490
491 /* Function: esl_rnd_Gaussian()
492 * Synopsis: Generate a Gaussian-distributed sample.
493 *
494 * Purpose: Pick a Gaussian-distributed random variable
495 * with a given <mean> and standard deviation <stddev>, and
496 * return it.
497 *
498 * Implementation is derived from the public domain
499 * RANLIB.c <gennor()> function, written by Barry W. Brown
500 * and James Lovato (M.D. Anderson Cancer Center, Texas
501 * USA) using the method described in
502 * \citep{AhrensDieter73}.
503 *
504 * Original algorithm said to use uniform deviates on [0,1)
505 * interval (i.e. <esl_random()>), but this appears to be
506 * wrong. Use uniform deviates on (0,1) interval instead
507 * (i.e., <esl_rnd_UniformPositive()>). RANLIB, GNU Octave
508 * have made this alteration, possibly inadvertently.
509 * [xref cryptogenomicon post, 13 Oct 2014].
510 *
511 * Method: Impenetrability of the code is to be blamed on
512 * FORTRAN/f2c lineage.
513 *
514 * Args: r - ESL_RANDOMNESS object
515 * mean - mean of the Gaussian we're sampling from
516 * stddev - standard deviation of the Gaussian
517 */
518 double
519 esl_rnd_Gaussian(ESL_RANDOMNESS *r, double mean, double stddev)
520 {
521 long i;
522 double snorm,u,s,ustar,aa,w,y,tt;
523
524 /* These static's are threadsafe: they are magic constants
525 * we will not touch.
526 */
527 static double a[32] = {
528 0.0,3.917609E-2,7.841241E-2,0.11777,0.1573107,0.1970991,0.2372021,0.2776904,
529 0.3186394,0.36013,0.4022501,0.4450965,0.4887764,0.5334097,0.5791322,
530 0.626099,0.6744898,0.7245144,0.7764218,0.8305109,0.8871466,0.9467818,
531 1.00999,1.077516,1.150349,1.229859,1.318011,1.417797,1.534121,1.67594,
532 1.862732,2.153875
533 };
534 static double d[31] = {
535 0.0,0.0,0.0,0.0,0.0,0.2636843,0.2425085,0.2255674,0.2116342,0.1999243,
536 0.1899108,0.1812252,0.1736014,0.1668419,0.1607967,0.1553497,0.1504094,
537 0.1459026,0.14177,0.1379632,0.1344418,0.1311722,0.128126,0.1252791,
538 0.1226109,0.1201036,0.1177417,0.1155119,0.1134023,0.1114027,0.1095039
539 };
540 static double t[31] = {
541 7.673828E-4,2.30687E-3,3.860618E-3,5.438454E-3,7.0507E-3,8.708396E-3,
542 1.042357E-2,1.220953E-2,1.408125E-2,1.605579E-2,1.81529E-2,2.039573E-2,
543 2.281177E-2,2.543407E-2,2.830296E-2,3.146822E-2,3.499233E-2,3.895483E-2,
544 4.345878E-2,4.864035E-2,5.468334E-2,6.184222E-2,7.047983E-2,8.113195E-2,
545 9.462444E-2,0.1123001,0.136498,0.1716886,0.2276241,0.330498,0.5847031
546 };
547 static double h[31] = {
548 3.920617E-2,3.932705E-2,3.951E-2,3.975703E-2,4.007093E-2,4.045533E-2,
549 4.091481E-2,4.145507E-2,4.208311E-2,4.280748E-2,4.363863E-2,4.458932E-2,
550 4.567523E-2,4.691571E-2,4.833487E-2,4.996298E-2,5.183859E-2,5.401138E-2,
551 5.654656E-2,5.95313E-2,6.308489E-2,6.737503E-2,7.264544E-2,7.926471E-2,
552 8.781922E-2,9.930398E-2,0.11556,0.1404344,0.1836142,0.2790016,0.7010474
553 };
554
555 u = esl_rnd_UniformPositive(r);
556 s = 0.0;
557 if(u > 0.5) s = 1.0;
558 u += (u-s);
559 u = 32.0*u;
560 i = (long) (u);
561 if(i == 32) i = 31;
562 if(i == 0) goto S100;
563 /*
564 * START CENTER
565 */
566 ustar = u-(double)i;
567 aa = a[i-1];
568 S40:
569 if (ustar <= t[i-1]) goto S60;
570 w = (ustar - t[i-1]) * h[i-1];
571 S50:
572 /*
573 * EXIT (BOTH CASES)
574 */
575 y = aa+w;
576 snorm = y;
577 if(s == 1.0) snorm = -y;
578 return (stddev*snorm + mean);
579 S60:
580 /*
581 * CENTER CONTINUED
582 */
583 u = esl_rnd_UniformPositive(r);
584 w = u*(a[i]-aa);
585 tt = (0.5*w+aa)*w;
586 goto S80;
587 S70:
588 tt = u;
589 ustar = esl_rnd_UniformPositive(r);
590 S80:
591 if(ustar > tt) goto S50;
592 u = esl_rnd_UniformPositive(r);
593 if(ustar >= u) goto S70;
594 ustar = esl_rnd_UniformPositive(r);
595 goto S40;
596 S100:
597 /*
598 * START TAIL
599 */
600 i = 6;
601 aa = a[31];
602 goto S120;
603 S110:
604 aa += d[i-1];
605 i += 1;
606 ESL_DASSERT1(( i <= 31 ));
607 S120:
608 u += u;
609 if(u < 1.0) goto S110;
610 u -= 1.0;
611 S140:
612 w = u*d[i-1];
613 tt = (0.5*w+aa)*w;
614 goto S160;
615 S150:
616 tt = u;
617 S160:
618 ustar = esl_rnd_UniformPositive(r);
619 if(ustar > tt) goto S50;
620 u = esl_rnd_UniformPositive(r);
621 if(ustar >= u) goto S150;
622 u = esl_rnd_UniformPositive(r);
623 goto S140;
624 }
625
626
627
628 /* subfunctions that esl_rnd_Gamma() is going to call:
629 */
630 static double
631 gamma_ahrens(ESL_RANDOMNESS *r, double a) /* for a >= 3 */
632 {
633 double V; /* uniform deviates */
634 double X,Y;
635 double test;
636
637 do {
638 do { /* generate candidate X */
639 Y = tan(eslCONST_PI * esl_random(r));
640 X = Y * sqrt(2.*a -1.) + a - 1.;
641 } while (X <= 0.);
642 /* accept/reject X */
643 V = esl_random(r);
644 test = (1+Y*Y) * exp( (a-1.)* log(X/(a-1.)) - Y*sqrt(2.*a-1.));
645 } while (V > test);
646 return X;
647 }
648 static double
649 gamma_integer(ESL_RANDOMNESS *r, unsigned int a) /* for small integer a, a < 12 */
650 {
651 int i;
652 double U,X;
653
654 U = 1.;
655 for (i = 0; i < a; i++)
656 U *= esl_rnd_UniformPositive(r);
657 X = -log(U);
658
659 return X;
660 }
661 static double
662 gamma_fraction(ESL_RANDOMNESS *r, double a) /* for fractional a, 0 < a < 1 */
663 { /* Knuth 3.4.1, exercise 16, pp. 586-587 */
664 double p, U, V, X, q;
665
666 p = eslCONST_E / (a + eslCONST_E);
667 do {
668 U = esl_random(r);
669 V = esl_rnd_UniformPositive(r);
670 if (U < p) {
671 X = pow(V, 1./a);
672 q = exp(-X);
673 } else {
674 X = 1. - log(V);
675 q = pow(X, a-1.);
676 }
677 U = esl_random(r);
678 } while (U >= q);
679 return X;
680 }
681
682
683 /* Function: esl_rnd_Gamma()
684 * Synopsis: Returns a random deviate from a Gamma(a, 1) distribution.
685 *
686 * Purpose: Return a random deviate distributed as Gamma(a, 1.)
687 * \citep[pp. 133--134]{Knu-81a}.
688 *
689 * The implementation follows not only Knuth \citep{Knu-81a},
690 * but also relied on examination of the implementation in
691 * the GNU Scientific Library (libgsl) \citep{Galassi06}.
692 *
693 * Args: r - random number generation seed
694 * a - order of the gamma function; a > 0
695 */
696 double
697 esl_rnd_Gamma(ESL_RANDOMNESS *r, double a)
698 {
699 double aint;
700
701 ESL_DASSERT1(( a > 0. ));
702
703 aint = floor(a);
704 if (a == aint && a < 12.)
705 return gamma_integer(r, (unsigned int) a);
706 else if (a > 3.)
707 return gamma_ahrens(r, a);
708 else if (a < 1.)
709 return gamma_fraction(r, a);
710 else
711 return gamma_integer(r, aint) + gamma_fraction(r, a-aint);
712 }
713
714
715 /* Function: esl_rnd_Dirichlet()
716 * Synopsis: Sample a Dirichlet-distributed random probability vector
717 * Incept: SRE, Wed Feb 17 12:20:53 2016 [H1/76]
718 *
719 * Purpose: Using generator <rng>, sample a Dirichlet-distributed
720 * probabilty vector <p> of <K> elements, using Dirichlet
721 * parameters <alpha> (also of <K> elements).
722 *
723 * Caller provides the allocated space for <p>.
724 *
725 * <alpha> is optional. If it isn't provided (i.e. is
726 * <NULL>), sample <p> uniformly. (That is, use <alpha[i] =
727 * 1.> for all i=0..K-1.)
728 *
729 * This routine is redundant with <esl_dirichlet_DSample()>
730 * and <esl_dirichlet_DSampleUniform()> in the dirichlet
731 * module. Provided here because there's cases where we
732 * just want to sample a probability vector without
733 * introducing a dependency on all the stats/dirichlet code
734 * in Easel.
735 *
736 * Args: rng : random number generator
737 * alpha : OPTIONAL: Dirichlet parameters 0..K-1, or NULL to use alpha[i]=1 for all i
738 * K : number of elements in alpha, p
739 * p : RESULT: sampled probability vector
740 *
741 * Returns: <eslOK> on success, and <p> is a sampled probability vector.
742 */
743 int
744 esl_rnd_Dirichlet(ESL_RANDOMNESS *rng, const double *alpha, int K, double *p)
745 {
746 int i;
747 double norm = 0.;
748
749 for (i = 0; i < K; i++)
750 {
751 p[i] = esl_rnd_Gamma(rng, (alpha ? alpha[i] : 1.0));
752 norm += p[i];
753 }
754 for (i = 0; i < K; i++)
755 p[i] /= norm;
756
757 return eslOK;
758 }
759
760
761 /* Function: esl_rnd_Deal()
762 * Synopsis: Sequential random sample of <m> random integers in range <n>
763 * Incept: SRE, Sun 17 Mar 2019
764 *
765 * Purpose: Obtain a random sequential sample of <m> integers without
766 * replacement from <n> possible ones, like dealing a hand
767 * of m=5 cards from a deck of n=52 possible cards with
768 * cards numbered <0..n-1>. Caller provides allocated space
769 * <deal>, allocated for at least <m> elements. Return the
770 * sample in <deal>, in sorted order (smallest to largest).
771 *
772 * Uses the selection sampling algorithm [Knuth, 3.4.2],
773 * which is O(n) time. For more impressive O(m)
774 * performance, see <esl_rand64_Deal()>.
775 *
776 * As a special case, if m = 0 (for whatever reason,
777 * probably an edge-case-exercising unit test), do
778 * nothing. <deal> is untouched, and can even be <NULL>.
779 *
780 * Args: m - number of integers to sample
781 * n - range: each sample is 0..n-1
782 * deal - RESULT: allocated space for <m> sampled integers
783 *
784 * Returns: <eslOK> on success, and the sample of <m> integers
785 * is in <deal>.
786 *
787 * Throws: (no abnormal error conditions)
788 */
789 int
790 esl_rnd_Deal(ESL_RANDOMNESS *rng, int m, int n, int *deal)
791 {
792 int i = 0;
793 int j = 0;
794
795 ESL_DASSERT1(( m >= 0 )); // m=0 is a special case where <deal> can be NULL.
796 ESL_DASSERT1(( n >= 1 ));
797 ESL_DASSERT1(( m <= n ));
798
799 for (j = 0; j < n && i < m; j++)
800 if ( ((double) (n - j)) * esl_random(rng) < (double) (m - i)) deal[i++] = j;
801 return eslOK;
802 }
803
804
805
806 /*****************************************************************
807 *# 5. Multinomial sampling from discrete probability n-vectors
808 *****************************************************************/
809
810 /* Function: esl_rnd_DChoose()
811 * Synopsis: Return random choice from discrete multinomial distribution.
812 *
813 * Purpose: Make a random choice from a normalized discrete
814 * distribution <p> of <N> elements, where <p>
815 * is double-precision. Returns the index of the
816 * selected element, $0..N-1$.
817 *
818 * <p> must be a normalized probability distribution
819 * (i.e. must sum to one). Sampling distribution is
820 * undefined otherwise: that is, a choice will always
821 * be returned, but it might be an arbitrary one.
822 *
823 * All $p_i$ must be $>$ <DBL_EPSILON> in order to
824 * have a non-zero probability of being sampled.
825 *
826 * <esl_rnd_FChoose()> is the same, but for floats in <p>,
827 * and all $p_i$ must be $>$ <FLT_EPSILON>.
828 */
829 int
830 esl_rnd_DChoose(ESL_RANDOMNESS *r, const double *p, int N)
831 {
832 double norm = 0.0; /* ~ 1.0 */
833 double sum = 0.0; /* integrated prob */
834 double roll = esl_random(r); /* random fraction */
835 int i; /* counter over the probs */
836
837 /* we need to deal with finite roundoff error in p's sum */
838 for (i = 0; i < N; i++) norm += p[i];
839 ESL_DASSERT1((norm > 0.999 && norm < 1.001));
840
841 for (i = 0; i < N; i++)
842 {
843 sum += p[i];
844 if (roll < (sum / norm) ) return i;
845 }
846 esl_fatal("unreached code was reached. universe collapses.");
847 return 0; /*notreached*/
848 }
849 int
850 esl_rnd_FChoose(ESL_RANDOMNESS *r, const float *p, int N)
851 {
852 /* Computing in double precision is important:
853 * casting <roll> to (float) gives a [0,1] number instead of [0,1).
854 */
855 double norm = 0.0; /* ~ 1.0 */
856 double sum = 0.0; /* integrated prob */
857 double roll = esl_random(r); /* random fraction */
858 int i; /* counter over the probs */
859
860 for (i = 0; i < N; i++) norm += p[i];
861 ESL_DASSERT1((norm > 0.99 && norm < 1.01));
862
863 for (i = 0; i < N; i++)
864 {
865 sum += (double) p[i];
866 if (roll < (sum / norm) ) return i;
867 }
868 esl_fatal("unreached code was reached. universe collapses.");
869 return 0; /*notreached*/
870 }
871
872
873 /* Function: esl_rnd_DChooseCDF()
874 * Synopsis: Return random choice from cumulative multinomial distribution.
875 *
876 * Purpose: Given a random number generator <r> and a cumulative
877 * multinomial distribution <cdf[0..N-1]>, sample an element
878 * <0..N-1> from that distribution. Return the index <0..N-1>.
879 *
880 * Caller should be sure that <cdf[0..N-1]> is indeed a
881 * cumulative multinomial distribution -- in particular, that
882 * <cdf[N-1]> is tolerably close to 1.0 (within roundoff error).
883 *
884 * When sampling many times from the same multinomial
885 * distribution <p>, it will generally be faster to
886 * calculate the CDF once using <esl_vec_DCDF(p, N, cdf)>,
887 * then sampling many times from the CDF with
888 * <esl_rnd_DChooseCDF(r, cdf, N)>, as opposed to calling
889 * <esl_rnd_DChoose(r, p, N)> many times, because
890 * <esl_rnd_DChoose()> has to calculated the CDF before
891 * sampling. This also gives you a bit more control over
892 * error detection: you can make sure that the CDF is ok (p
893 * does sum to ~1.0) before doing a lot of sampling from
894 * it.
895 *
896 * <esl_rnd_FChooseCDF()> is the same, but for
897 * a single-precision float <cdf>.
898 *
899 * Args: r - random number generator
900 * cdf - cumulative multinomial distribution, cdf[0..N-1]
901 * N - number of elements in <cdf>
902 *
903 * Returns: index 0..N-1 of the randomly sampled choice from <cdf>.
904 *
905 * Note: For large N, it might be advantageous to bisection search the
906 * cdf. For typical N in Easel (up to 20, for amino acid
907 * prob vectors, for example), the naive code below is
908 * faster. We could revisit this if we start sampling
909 * larger vectors.
910 */
911 int
912 esl_rnd_DChooseCDF(ESL_RANDOMNESS *r, const double *cdf, int N)
913 {
914 double roll = esl_random(r); /* uniform 0.0 <= x < 1.0 */
915 int i;
916
917 ESL_DASSERT1((cdf[0] >= 0.0));
918 ESL_DASSERT1((cdf[N-1] > 0.999 && cdf[N-1] < 1.001));
919
920 for (i = 0; i < N; i++)
921 if (roll < cdf[i] / cdf[N-1]) return i;
922 esl_fatal("unreached code is reached. universe goes foom");
923 return 0; /*notreached*/
924 }
925 int
926 esl_rnd_FChooseCDF(ESL_RANDOMNESS *r, const float *cdf, int N)
927 {
928 double roll = esl_random(r); /* uniform 0.0 <= x < 1.0. must be double, not float, to guarantee x <1 */
929 int i;
930
931 ESL_DASSERT1((cdf[0] >= 0.0));
932 ESL_DASSERT1((cdf[N-1] > 0.99 && cdf[N-1] < 1.01));
933
934 for (i = 0; i < N; i++)
935 if (roll < (double) cdf[i] / (double) cdf[N-1]) return i; // yes, the casts are NECESSARY. Without them, you get a heisenbug on icc/linux.
936 esl_fatal("unreached code is reached. universe goes foom");
937 return 0; /*notreached*/
938 }
939
940
941 /*****************************************************************
942 * 6. Random data generators (unit testing, etc.)
943 *****************************************************************/
944
945
946
947 /* Function: esl_rnd_mem()
948 * Synopsis: Overwrite a buffer with random garbage.
949 * Incept: SRE, Fri Feb 19 08:53:07 2016
950 *
951 * Purpose: Write <n> bytes of random garbage into buffer
952 * <buf>, by uniform sampling of values 0..255,
953 * using generator <rng>.
954 *
955 * Used in unit tests that are reusing memory, and that
956 * want to make sure that there's no favorable side effects
957 * from that reuse.
958 */
959 int
960 esl_rnd_mem(ESL_RANDOMNESS *rng, void *buf, int n)
961 {
962 unsigned char *p = (unsigned char *) buf;
963 int i;
964
965 for (i = 0; i < n; i++)
966 p[i] = (unsigned char) esl_rnd_Roll(rng, 256);
967 return eslOK;
968 }
969
970
971 /* Function: esl_rnd_floatstring()
972 * Synopsis: Generate a string representation of a floating point number.
973 * Incept: SRE, Wed 15 Aug 2018 [Hamilton, It's Quiet Uptown]
974 *
975 * Purpose: Generate a string decimal representation of a random
976 * floating point number in <s>, which is space provided
977 * by the caller, allocated for at least 20 characters.
978 *
979 * The string representation of the number consists of:
980 * * an optional - sign (50%)
981 * * a 1-6 digit integer part; (1/7 '0'; else 1/7 for each len, [1-9][0-9]* uniformly)
982 * * an optional fractional part (50%), consisting of:
983 * - '.'
984 * - a 1-7 digit fractional part; 1/7 for each len, [0-9]* uniformly
985 * * an optional exponent (50%), consisting of:
986 * - 'e'
987 * - -20..e20, 1/41 uniformly.
988 * * '\0' terminator.
989 *
990 * Maximum length is 1+6+1+7+4+1 = 20.
991 *
992 * The string representation is an intersection of what's
993 * valid for <strtod()>, JSON number values, and C. JSON
994 * number values do not permit numbers like "1." (a
995 * decimal part, decimal point, no fractional part), nor
996 * hexadecimal representations, nor leading or trailing
997 * whitespace.
998 *
999 * The generated number does not attempt to exercise
1000 * extreme values. The absolute magnitude of non-zero
1001 * numbers ranges from 0.0000001e-20..999999e20 (1e-27 to
1002 * ~1e27), well within IEEE754 FLT_MIN..FLT_MAX
1003 * range. Special values "infinity" and "nan" are not
1004 * generated. Zero can be represented by many different
1005 * patterns <-?0.0+(e-?..)?>.
1006 *
1007 * Returns: <eslOK> on success.
1008 */
1009 int
1010 esl_rnd_floatstring(ESL_RANDOMNESS *rng, char *s)
1011 {
1012 int i = 0;
1013 int n;
1014 int exponent;
1015
1016 if (esl_rnd_Roll(rng, 2)) s[i++] = '-';
1017 n = esl_rnd_Roll(rng, 7); // length of integer part.
1018 s[i++] = (n-- == 0) ? '0' : '0' + (1 + esl_rnd_Roll(rng, 9)); // No 0 prefix except "0."
1019 while (n-- > 0) s[i++] = '0' + esl_rnd_Roll(rng, 10);
1020 if (esl_rnd_Roll(rng, 2)) // optional fractional part
1021 {
1022 n = 1 + esl_rnd_Roll(rng, 7);
1023 s[i++] = '.';
1024 while (n--) s[i++] = '0' + esl_rnd_Roll(rng, 10);
1025 }
1026 if (esl_rnd_Roll(rng, 2)) // optional exponent
1027 {
1028 s[i++] = 'e';
1029 exponent = -20 + esl_rnd_Roll(rng, 41);
1030 i += snprintf(s+i, 20-i, "%d", exponent);
1031 }
1032 s[i++] = '\0';
1033 return eslOK;
1034 }
1035
1036
1037
1038
1039 /*****************************************************************
1040 * 7. Benchmark driver
1041 *****************************************************************/
1042 #ifdef eslRANDOM_BENCHMARK
1043 /*
1044 gcc -O3 -malign-double -o esl_random_benchmark -I. -L. -DeslRANDOM_BENCHMARK esl_random.c -leasel -lm
1045 ./esl_random_benchmark -N 1000000000
1046 ./esl_random_benchmark -f -N 1000000000
1047 ./esl_random_benchmark -r -N1000000
1048 ./esl_random_benchmark -fr -N 1000000000
1049 esl_random() esl_randomness_Init()
1050 iter cpu time per call iter cpu time per call
1051 ---- -------- -------- ---- ---------- ---------
1052 27 Dec 08 on wanderoo: 1e7 0.78s 78 nsec 1e6 2.08s 2.1 usec ran2() from NR
1053 30 May 09 on wanderoo: 1e9 8.39s 8 nsec 1e6 5.98s 6.0 usec Mersenne Twister
1054 1e9 5.73s 6 nsec 1e8 2.51s 0.03 usec Knuth
1055 22 Aug 18 on wyvern: 1e9 3.31s 3 nsec 1e7 8.71s 0.8 usec Mersenne Twister
1056
1057 */
1058 #include "easel.h"
1059 #include "esl_composition.h"
1060 #include "esl_getopts.h"
1061 #include "esl_random.h"
1062 #include "esl_stopwatch.h"
1063 #include "esl_vectorops.h"
1064
1065 static ESL_OPTIONS options[] = {
1066 /* name type default env range toggles reqs incomp help docgroup*/
1067 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1068 { "-c", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark DChooseCDF()", 0 },
1069 { "-d", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark DChoose()", 0 },
1070 { "-f", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "run fast version instead of MT19937", 0 },
1071 { "-r", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark _Init(), not just random()", 0 },
1072 { "-N", eslARG_INT, "10000000",NULL, NULL, NULL, NULL, NULL, "number of trials", 0 },
1073 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1074 };
1075 static char usage[] = "[-options]";
1076 static char banner[] = "benchmarking speed of random number generator";
1077
1078 int
1079 main(int argc, char **argv)
1080 {
1081 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1082 ESL_RANDOMNESS *r = (esl_opt_GetBoolean(go, "-f") == TRUE ? esl_randomness_CreateFast(42) : esl_randomness_Create(42));
1083 ESL_STOPWATCH *w = esl_stopwatch_Create();
1084 int N = esl_opt_GetInteger(go, "-N");
1085 double p[20];
1086 double cdf[20];
1087
1088 esl_composition_BL62(p);
1089 esl_vec_DCDF(p, 20, cdf);
1090
1091 esl_stopwatch_Start(w);
1092 if (esl_opt_GetBoolean(go, "-c")) { while (N--) esl_rnd_DChoose(r, p, 20); }
1093 else if (esl_opt_GetBoolean(go, "-d")) { while (N--) esl_rnd_DChooseCDF(r, cdf, 20); }
1094 else if (esl_opt_GetBoolean(go, "-r")) { while (N--) esl_randomness_Init(r, 42); }
1095 else { while (N--) esl_random(r); }
1096
1097 esl_stopwatch_Stop(w);
1098 esl_stopwatch_Display(stdout, w, "# CPU Time: ");
1099
1100 esl_stopwatch_Destroy(w);
1101 esl_randomness_Destroy(r);
1102 esl_getopts_Destroy(go);
1103 return 0;
1104 }
1105 #endif /*eslRANDOM_BENCHMARK*/
1106 /*----------------- end, benchmark driver -----------------------*/
1107
1108
1109
1110
1111 /*****************************************************************
1112 * 8. Unit tests.
1113 *****************************************************************/
1114
1115 #ifdef eslRANDOM_TESTDRIVE
1116 #include "esl_vectorops.h"
1117 #include "esl_stats.h"
1118 #include "esl_dirichlet.h"
1119
1120
1121 /* The esl_random() unit test:
1122 * a binned frequency test.
1123 */
1124 static void
1125 utest_random(ESL_RANDOMNESS *r, int n, int nbins, int be_verbose)
1126 {
1127 char msg[] = "esl_random() unit test failed";
1128 int *counts = NULL;
1129 double X2p = 0.;
1130 int i;
1131 int sample;
1132 double X2, exp, diff;
1133
1134 if ((counts = malloc(sizeof(int) * nbins)) == NULL) esl_fatal(msg);
1135 esl_vec_ISet(counts, nbins, 0);
1136
1137 for (i = 0; i < n; i++)
1138 {
1139 sample = esl_rnd_Roll(r, nbins);
1140 if (sample < 0 || sample >= nbins) esl_fatal(msg);
1141 counts[sample]++;
1142 }
1143
1144 /* X^2 value: \sum (o_i - e_i)^2 / e_i */
1145 for (X2 = 0., i = 0; i < nbins; i++) {
1146 exp = (double) n / (double) nbins;
1147 diff = (double) counts[i] - exp;
1148 X2 += diff*diff/exp;
1149 }
1150 if (esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal(msg);
1151 if (be_verbose) printf("random(): \t%g\n", X2p);
1152 if (X2p < 0.01) esl_fatal(msg);
1153
1154 free(counts);
1155 return;
1156 }
1157
1158 /* The DChoose() and FChoose() unit tests.
1159 */
1160 static void
1161 utest_choose(ESL_RANDOMNESS *r, int n, int nbins, int be_verbose)
1162 {
1163 double *pd = NULL; /* probability vector, double */
1164 double *pdc = NULL; /* CDF, double */
1165 float *pf = NULL; /* probability vector, float */
1166 float *pfc = NULL; /* CDF, float */
1167 int *ct = NULL;
1168 int i;
1169 double X2, diff, exp, X2p;
1170
1171 if ((pd = malloc(sizeof(double) * nbins)) == NULL) esl_fatal("malloc failed");
1172 if ((pdc = malloc(sizeof(double) * nbins)) == NULL) esl_fatal("malloc failed");
1173 if ((pf = malloc(sizeof(float) * nbins)) == NULL) esl_fatal("malloc failed");
1174 if ((pfc = malloc(sizeof(float) * nbins)) == NULL) esl_fatal("malloc failed");
1175 if ((ct = malloc(sizeof(int) * nbins)) == NULL) esl_fatal("malloc failed");
1176
1177 /* Sample a random multinomial probability vector. */
1178 if (esl_dirichlet_DSampleUniform(r, nbins, pd) != eslOK) esl_fatal("dirichlet sample failed");
1179 esl_vec_D2F(pd, nbins, pf);
1180
1181 /* Test esl_rnd_DChoose():
1182 * sample observed counts, chi-squared test against expected
1183 */
1184 esl_vec_ISet(ct, nbins, 0);
1185 for (i = 0; i < n; i++)
1186 ct[esl_rnd_DChoose(r, pd, nbins)]++;
1187 for (X2 = 0., i=0; i < nbins; i++) {
1188 exp = (double) n * pd[i];
1189 diff = (double) ct[i] - exp;
1190 X2 += diff*diff/exp;
1191 }
1192 if (esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal("chi square eval failed");
1193 if (be_verbose) printf("DChoose(): \t%g\n", X2p);
1194 if (X2p < 0.01) esl_fatal("chi squared test failed");
1195
1196 /* Repeat above for FChoose(). */
1197 esl_vec_ISet(ct, nbins, 0);
1198 for (i = 0; i < n; i++)
1199 ct[esl_rnd_FChoose(r, pf, nbins)]++;
1200 for (X2 = 0., i=0; i < nbins; i++) {
1201 exp = (double) n * pd[i];
1202 diff = (double) ct[i] - exp;
1203 X2 += diff*diff/exp;
1204 }
1205 if (esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal("chi square eval failed");
1206 if (be_verbose) printf("FChoose(): \t%g\n", X2p);
1207 if (X2p < 0.01) esl_fatal("chi squared test failed");
1208
1209 /* esl_rnd_DChooseCDF(). */
1210 esl_vec_ISet(ct, nbins, 0);
1211 esl_vec_DCDF(pd, nbins, pdc);
1212 for (i = 0; i < n; i++)
1213 ct[esl_rnd_DChooseCDF(r, pdc, nbins)]++;
1214 for (X2 = 0., i=0; i < nbins; i++) {
1215 exp = (double) n * pd[i];
1216 diff = (double) ct[i] - exp;
1217 X2 += diff*diff/exp;
1218 }
1219 if (esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal("chi square eval failed");
1220 if (be_verbose) printf("DChoose(): \t%g\n", X2p);
1221 if (X2p < 0.01) esl_fatal("chi squared test failed");
1222
1223 /* esl_rnd_FChooseCDF() */
1224 esl_vec_ISet(ct, nbins, 0);
1225 esl_vec_FCDF(pf, nbins, pfc);
1226 for (i = 0; i < n; i++)
1227 ct[esl_rnd_FChooseCDF(r, pfc, nbins)]++;
1228 for (X2 = 0., i=0; i < nbins; i++) {
1229 exp = (double) n * pf[i];
1230 diff = (double) ct[i] - exp;
1231 X2 += diff*diff/exp;
1232 }
1233 if (esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal("chi square eval failed");
1234 if (be_verbose) printf("DChoose(): \t%g\n", X2p);
1235 if (X2p < 0.01) esl_fatal("chi squared test failed");
1236
1237 free(pd);
1238 free(pdc);
1239 free(pf);
1240 free(pfc);
1241 free(ct);
1242 return;
1243 }
1244
1245
1246 /* utest_Deal()
1247 * tests esl_rnd_Deal()
1248 *
1249 * If deals are random, each possible integer is sampled uniformly.
1250 * Take <nsamp> deals of <m> integers from possible <n>.
1251 * Expected count of each integer = nsamp * (m/n), +/- s.d. \sqrt(u)
1252 * Test that min, max are within +/- 6 sd.
1253 *
1254 * Can fail stochastically, so caller should default to an <rng>
1255 * with a fixed RNG seed.
1256 */
1257 static void
1258 utest_Deal(ESL_RANDOMNESS *rng)
1259 {
1260 char msg[] = "esl_random deal unit test failed";
1261 int m = 100;
1262 int n = 1000;
1263 int nsamp = 10000;
1264 int *deal = malloc(sizeof(int) * m);
1265 int *ct = malloc(sizeof(int) * n);
1266 double expected_mean = ((double) m / (double) n) * (double) nsamp;
1267 double expected_sd = sqrt(expected_mean);
1268 int max_allowed = (int) round( expected_mean + 6. * expected_sd);
1269 int min_allowed = (int) round( expected_mean - 6. * expected_sd);
1270 int i;
1271
1272 if (deal == NULL || ct == NULL) esl_fatal(msg);
1273 esl_vec_ISet(ct, n, 0);
1274
1275 while (nsamp--)
1276 {
1277 esl_rnd_Deal(rng, m, n, deal);
1278 for (i = 0; i < m; i++) ct[deal[i]]++;
1279 }
1280 if (esl_vec_IMax(ct, n) > max_allowed) esl_fatal(msg);
1281 if (esl_vec_IMin(ct, n) < min_allowed) esl_fatal(msg);
1282
1283 free(deal);
1284 free(ct);
1285 }
1286 #endif /*eslRANDOM_TESTDRIVE*/
1287 /*-------------------- end, unit tests --------------------------*/
1288
1289
1290 /*****************************************************************
1291 * 9. Test driver.
1292 *****************************************************************/
1293 #ifdef eslRANDOM_TESTDRIVE
1294 #include <esl_config.h>
1295
1296 #include <stdio.h>
1297
1298 #include "easel.h"
1299 #include "esl_dirichlet.h"
1300 #include "esl_getopts.h"
1301 #include "esl_random.h"
1302 #include "esl_randomseq.h"
1303 #include "esl_vectorops.h"
1304
1305 static ESL_OPTIONS options[] = {
1306 /* name type default env range togs reqs incomp help docgrp */
1307 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
1308 {"-b", eslARG_INT, "20", NULL, "n>0",NULL, NULL, NULL, "number of test bins", 0},
1309 {"-n", eslARG_INT, "1000000", NULL, "n>0",NULL, NULL, NULL, "number of samples", 0},
1310 {"-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
1311 {"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show verbose output", 0},
1312 {"--mtbits",eslARG_STRING,NULL,NULL, NULL, NULL, NULL, NULL, "save MT bit file for NIST benchmark",0},
1313 {"--kbits", eslARG_STRING,NULL,NULL, NULL, NULL, NULL, NULL, "save Knuth bit file for NIST benchmark",0},
1314 { 0,0,0,0,0,0,0,0,0,0},
1315 };
1316 static char usage[] = "[-options]";
1317 static char banner[] = "test driver for random module";
1318
1319 static int save_bitfile(char *bitfile, ESL_RANDOMNESS *r, int n);
1320
1321 int
1322 main(int argc, char **argv)
1323 {
1324 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1325 ESL_RANDOMNESS *r1 = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1326 ESL_RANDOMNESS *r2 = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
1327 char *mtbitfile = esl_opt_GetString (go, "--mtbits");
1328 char *kbitfile = esl_opt_GetString (go, "--kbits");
1329 int nbins = esl_opt_GetInteger(go, "-b");
1330 int n = esl_opt_GetInteger(go, "-n");
1331 int be_verbose = esl_opt_GetBoolean(go, "-v");
1332
1333 fprintf(stderr, "## %s\n", argv[0]);
1334 fprintf(stderr, "# rng seed 1 (slow) = %" PRIu32 "\n", esl_randomness_GetSeed(r1));
1335 fprintf(stderr, "# rng seed 2 (fast) = %" PRIu32 "\n", esl_randomness_GetSeed(r2));
1336
1337 utest_random(r1, n, nbins, be_verbose);
1338 utest_choose(r1, n, nbins, be_verbose);
1339 utest_random(r2, n, nbins, be_verbose);
1340 utest_choose(r2, n, nbins, be_verbose);
1341
1342 utest_Deal(r1);
1343
1344 if (mtbitfile) save_bitfile(mtbitfile, r1, n);
1345 if (kbitfile) save_bitfile(kbitfile, r2, n);
1346
1347 fprintf(stderr, "# status = ok\n");
1348
1349 esl_randomness_Destroy(r1);
1350 esl_randomness_Destroy(r2);
1351 esl_getopts_Destroy(go);
1352 return 0;
1353 }
1354
1355 static int
1356 save_bitfile(char *bitfile, ESL_RANDOMNESS *r, int n)
1357 {
1358 FILE *fp = NULL;
1359 int b,i;
1360 long x;
1361
1362 /* Open the file.
1363 */
1364 if ((fp = fopen(bitfile, "w")) == NULL)
1365 esl_fatal("failed to open %s for writing", bitfile);
1366
1367 /* Sample <n> random numbers, output 32n random bits to the file.
1368 */
1369 for (i = 0; i < n; i++)
1370 {
1371 x = (r->type == eslRND_FAST ? knuth(r) : mersenne_twister(r)); /* generate a 32 bit random variate by MT19937 */
1372 for (b = 0; b < 32; b++)
1373 {
1374 if (x & 01) fprintf(fp, "1");
1375 else fprintf(fp, "0");
1376 x >>= 1;
1377 }
1378 fprintf(fp, "\n");
1379 }
1380 fclose(fp);
1381 return eslOK;
1382 }
1383 #endif /*eslRANDOM_TESTDRIVE*/
1384
1385
1386
1387 /*****************************************************************
1388 * 10. Example.
1389 *****************************************************************/
1390 #ifdef eslRANDOM_EXAMPLE
1391 /*::cexcerpt::random_example::begin::*/
1392 /* compile: cc -I. -o esl_random_example -DeslRANDOM_EXAMPLE esl_random.c esl_getopts.c easel.c -lm
1393 * run: ./random_example 42
1394 */
1395 #include <stdio.h>
1396 #include "easel.h"
1397 #include "esl_getopts.h"
1398 #include "esl_random.h"
1399
1400 /* In Easel and HMMER, the option for setting the seed is typically -s, sometimes --seed.
1401 * Default is usually 0 because we want a "random" seed. Less commonly, "42" for a fixed seed;
1402 * rarely, a different fixed seed.
1403 *
1404 * Generally you want to use esl_randomness_Create(), to get a Mersenne Twister. The "fast"
1405 * RNG you get from esl_randomness_CreateFast() isn't all that much faster (~25% per sample)
1406 * but has much worse quality in its randomness.
1407 */
1408 static ESL_OPTIONS options[] = {
1409 /* name type default env range toggles reqs incomp help docgroup*/
1410 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1411 { "-i", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "sample uint32's instead of doubles", 0 },
1412 { "-n", eslARG_INT, "20", NULL, NULL, NULL, NULL, NULL, "number of random samples to show", 0 },
1413 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1414 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1415 };
1416 static char usage[] = "[-options]";
1417 static char banner[] = "example of using random module";
1418
1419 int
1420 main(int argc, char **argv)
1421 {
1422 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1423 ESL_RANDOMNESS *rng = esl_randomness_Create( esl_opt_GetInteger(go, "-s") );
1424 int do_uint32 = esl_opt_GetBoolean(go, "-i");
1425 int n = esl_opt_GetInteger(go, "-n");
1426
1427 printf("RNG seed: %" PRIu32 "\n", esl_randomness_GetSeed(rng));
1428 printf("\nA sequence of %d pseudorandom numbers:\n", n);
1429 if (do_uint32) while (n--) printf("%" PRIu32 "\n", esl_random_uint32(rng));
1430 else while (n--) printf("%f\n", esl_random(rng));
1431
1432 printf("\nInternal dump of RNG state:\n");
1433 esl_randomness_Dump(stdout, rng);
1434
1435 esl_randomness_Destroy(rng);
1436 esl_getopts_Destroy(go);
1437 return 0;
1438 }
1439 /*::cexcerpt::random_example::end::*/
1440 #endif /*eslRANDOM_EXAMPLE*/
1441
1442
1443