Debian Codegraph @

easel/esl_rand64.c

raw symbols SCIP
1 /* 64-bit Mersenne Twister random number generator: portable, threadsafe.
2 *
3 * Contents:
4 * 1. <ESL_RAND64> object
5 * 2. Base esl_rand64_*() number generators
6 * 3. Other sampling routines
7 * 4. Internal functions implementing Mersenne Twister MT19937-64
8 * 5. Debugging and development tools
9 * 6. Benchmark driver
10 * 7. Unit tests
11 * 8. Test driver
12 * 9. Example
13 *
14 * See also:
15 * esl_random : Easel's standard RNG, a 32-bit Mersenne Twister
16 *
17 * The ESL_RAND64 generator is derived from MT19937-64 (2004/9/29) by
18 * Takuji Nishimura and Makoto Matsumoto.
19 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/mt19937-64.c
20 * Copyright (C) 2004, Makoto Matsumoto and Takuji Nishimura.
21 * All rights reserved.
22 *
23 * esl_rand64_Deal() is derived from code by Kevin Lawler (Brave
24 * Software; brave.com).
25 * Copyright (2016) Kevin Lawler. Released under ISC License.
26 *
27 * In addition to the automated unit tests, external tests also verified that:
28 * 1. esl_rand64() stream matches mt19937-64.c stream
29 * 2. esl_rand64() passes NIST sts-2.1.2 (2014) RNG statistical test suite
30 */
31 #include <esl_config.h>
32
33 #include <stdlib.h>
34 #include <stdint.h>
35 #include <stdio.h>
36 #include <time.h> // time(), clock()
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h> // getpid()
39 #endif
40
41 #include "easel.h"
42 #include "esl_rand64.h"
43
44
45
46 #if !defined(eslRAND64_BENCHMARK) && !defined(eslRAND64_TESTDRIVE) && !defined(eslRAND64_EXAMPLE)
47 /* Usually we don't need to #if out the main code block(s) in our
48 idiom for compiling Easel driver programs. This particular #if is
49 a workaround for a bug that cropped up in esl_rand64 in a specific
50 case of the Intel (2023.0.0) icx compiler with -O3 optimization
51 (but not -O2 or less) and -fp-model=precise (but not default or
52 strict), which caused a baffling failure in the
53 esl_rand64_utest::utest_rand64() test. It's unclear why the #if
54 fixes the problem, but it does. [xref 2023/0803-h3-icx-fpmodel]
55 */
56
57
58 static void mt64_seed_table(ESL_RAND64 *rng, uint64_t seed);
59 static void mt64_fill_table(ESL_RAND64 *rng);
60 static uint64_t choose_arbitrary_seed(void);
61
62 /*****************************************************************
63 * 1. The <ESL_RAND64> object.
64 *****************************************************************/
65
66 /* Function: esl_rand64_Create()
67 * Synopsis: Create a 64-bit Mersenne Twister RNG.
68 * Incept: SRE, Tue 21 Aug 2018
69 *
70 * Purpose: Create a new RNG, seeding it with <seed>.
71 *
72 * If <seed> is $>0$, the RNG is reproducibly initialized
73 * with that seed. Two RNGs created with the same nonzero seed
74 * will give exactly the same stream of pseudorandom numbers.
75 *
76 * If <seed> is 0, an arbitrary seed is chosen. Two RNGs
77 * created with seed=0 will very probably (though not
78 * assuredly) give different streams of pseudorandom
79 * numbers. The seed that was used can be retrieved with
80 * <esl_rand64_GetSeed()>. The strategy used for choosing
81 * the arbitrary seed is predictable (a hash of the current
82 * time and the process id), so it is not cryptographically
83 * secure.
84 *
85 * Returns: <eslOK> on success.
86 *
87 * Throws: <NULL> on allocation failure.
88 *
89 * Notes: Initializing a new RNG takes negligible time. If you find
90 * yourself obsessively worrying about it, don't.
91 */
92 ESL_RAND64 *
93 esl_rand64_Create(uint64_t seed)
94 {
95 ESL_RAND64 *rng = NULL;
96 int status;
97
98 ESL_ALLOC(rng, sizeof(ESL_RAND64));
99 rng->mti = 0;
100 rng->seed = 0;
101 esl_rand64_Init(rng, seed);
102 return rng;
103
104 ERROR:
105 return NULL;
106 }
107
108 /* Function: esl_rand64_Init()
109 * Synopsis: Reinitialize an RNG with a new seed.
110 * Incept: SRE, Tue 21 Aug 2018
111 *
112 * Purpose: Reinitialize <rng> with a new <seed>.
113 *
114 * Sometimes it's useful to reseed an RNG to generate a
115 * reproducible series of random numbers at an arbitrary
116 * point in a program that's already consumed an unknown
117 * number of random numbers. Our unit test code has
118 * frequent examples of this, where a given unit test
119 * function wants to control its RNG stream, regardless of
120 * what has executed before it.
121 *
122 * Returns <eslOK> on success.
123 *
124 * Throws: (no abnormal error conditions)
125 */
126 int
127 esl_rand64_Init(ESL_RAND64 *rng, uint64_t seed)
128 {
129 if (seed == 0ULL) seed = choose_arbitrary_seed();
130 mt64_seed_table(rng, seed);
131 mt64_fill_table(rng);
132 return eslOK;
133 }
134
135
136 /* Function: esl_rand64_GetSeed()
137 * Synopsis: Return the value of the RNG's seed.
138 * Incept: SRE, Tue 21 Aug 2018
139 *
140 * Purpose: Returns the value of the seed that <rng> used. This is
141 * useful when <rng> was created with an arbitrary seed,
142 * but you want to know what it was, so you can reproduce
143 * whatever happens. Our unit tests generally select
144 * arbitrary seeds and report them in output, for example.
145 */
146 uint64_t
147 esl_rand64_GetSeed(ESL_RAND64 *rng)
148 {
149 return rng->seed;
150 }
151
152
153 /* Function: esl_rand64_Destroy()
154 * Synopsis: Frees an <ESL_RAND64>.
155 * Incept: SRE, Tue 21 Aug 2018
156 */
157 void
158 esl_rand64_Destroy(ESL_RAND64 *rng)
159 {
160 free(rng);
161 }
162
163
164
165
166 /*****************************************************************
167 * 2. Base esl_rand64_*() number generators
168 *****************************************************************/
169
170 /* Function: esl_rand64()
171 * Synopsis: Generate a random number on [0,2^{64}-1]
172 * Incept: SRE, Tue 21 Aug 2018 [Hans Zimmer, Inception, We Built Our Own World]
173 */
174 uint64_t
175 esl_rand64(ESL_RAND64 *rng)
176 {
177 uint64_t x;
178 if (rng->mti >= 312) mt64_fill_table(rng);
179
180 x = rng->mt[rng->mti++];
181 x ^= (x >> 29) & 0x5555555555555555ULL;
182 x ^= (x << 17) & 0x71D67FFFEDA60000ULL;
183 x ^= (x << 37) & 0xFFF7EEE000000000ULL;
184 x ^= (x >> 43);
185 return x;
186 }
187
188
189 /* Function: esl_rand64_int64()
190 * Synopsis: Generate a random signed int64 on [0,2^63-1]
191 * Incept: SRE, Fri 24 Aug 2018
192 *
193 * Note: Starting with a 64-bit uint64_t, discards the most
194 * significant bit and returns the low-order 63 bits. This
195 * makes an assumption about the binary representation of
196 * unsigned/signed integers, but the assumption is safe. It
197 * will work correctly for two's-complement, one's
198 * complement, and sign/magnitude integer systems. C99
199 * allows any of the three systems (C99 6.2.6.2) for an
200 * <int>; exact-width types such as <int64_t> are required
201 * to use two's complement (C99 7.18.1.1).
202 */
203 int64_t
204 esl_rand64_int64(ESL_RAND64 *rng)
205 {
206 return ((int64_t) (esl_rand64(rng) >> 1));
207 }
208
209
210 /* Function: esl_rand64_Roll()
211 * Synopsis: Generate a uniform random integer 0..n-1.
212 * Incept: SRE, Tue 21 Aug 2018
213 */
214 uint64_t
215 esl_rand64_Roll(ESL_RAND64 *rng, uint64_t n)
216 {
217 uint64_t factor = UINT64_MAX / n;
218 uint64_t x;
219 do { x = esl_rand64(rng) / factor; } while (x >= n);
220 return x;
221 }
222
223 /* Function: esl_rand64_double()
224 * Synopsis: Generate a uniformly distributed double on half-open interval [0,1)
225 * Incept: SRE, Tue 21 Aug 2018
226 *
227 * Purpose: Generate a uniformly distributed double $x$ on the half-open
228 * interval $0 \leq x < 1$.
229 */
230 double
231 esl_rand64_double(ESL_RAND64 *rng)
232 {
233 return (double) (esl_rand64(rng) >> 11) * (1.0/9007199254740992.0); // (0..2^53-1) / 2^53
234 }
235
236
237 /* Function: esl_rand64_double_closed()
238 * Synopsis: Generate a uniformly distributed double on closed interval [0,1]
239 * Incept: SRE, Tue 21 Aug 2018
240 *
241 * Purpose: Generate a uniformly distributed double $x$ on the closed
242 * interval $0 \leq x \leq 1$.
243 */
244 double
245 esl_rand64_double_closed(ESL_RAND64 *rng)
246 {
247 return ((double) (esl_rand64(rng) >> 11)) * (1.0/9007199254740991.0); // (0..2^53-1) / (2^53-1)
248 }
249
250
251 /* Function: esl_rand64_double_open()
252 * Synopsis: Generate a uniformly distributed double on open interval (0,1)
253 * Incept: SRE, Tue 21 Aug 2018
254 *
255 * Purpose: Generate a uniformly distributed double $x$ on the open
256 * interval $0 < x < 1$.
257 */
258 double
259 esl_rand64_double_open(ESL_RAND64 *rng)
260 {
261 return ((double) (esl_rand64(rng) >> 12) + 0.5) * (1.0/4503599627370496.0); // (0.5..(2^52-1).5 / 2^52
262 }
263
264
265 /*****************************************************************
266 * 3. Other sampling routines
267 *****************************************************************/
268
269 /* vitter_a()
270 * Vitter [1987] "Method A", needed inside the main "Method D" below.
271 *
272 * Sample the remaining <m'> integers from the remaining <n'>, where the
273 * last one we sampled was <j>; store the sampled numbers in <deal'>.
274 *
275 * The primes (e.g. m' not m) there indicate that this function is
276 * implemented for finishing off a sample in progress, at the end of
277 * Method D (below). Method D is sampling m from n. It decrements m
278 * and n as it goes, and it's also incrementing a counter i as it
279 * stores sampled integers in deal[i]. As it nears the end it may
280 * switch to Method A by calling:
281 * vitter_a(rng, m', n', j, deal+i)
282 * to sample the remaining m' from the remaining n'. Because the
283 * algorithm works by sampling skip distances between sampled integers
284 * (<S> in the code below), we only need to know how many n' are left;
285 * we don't need to know the maximum n. We get the samples by adding
286 * the sampled skip distance to <j>.
287 *
288 */
289 static int
290 vitter_a(ESL_RAND64 *rng, int64_t m, int64_t n, int64_t j, int64_t *deal)
291 {
292 int64_t i = 0; // will count over remaining m samples
293 int64_t S = 0; // sampled skip distance
294 double top = (double) (n - m);
295 double nreal = (double) n;
296 double U, quot;
297
298 while (m >= 2)
299 {
300 U = esl_rand64_double_open(rng); // (0,1) unit open interval. Lawler uses [0,1) but Vitter says (0,1).
301 S = 0;
302 quot = top/nreal;
303 while (quot > U) // sample this S in O(S+1) time; so O(n) over all sampling
304 {
305 S++;
306 top -= 1.;
307 nreal -= 1.;
308 quot = (quot * top)/nreal;
309 }
310 j += S+1; // skip S to next sampled integer j
311 deal[i++] = j;
312 nreal -= 1;
313 m--;
314 }
315 S = floor(round(nreal) * esl_rand64_double(rng)); // last sample (0..n'-1) uniform, with n' >= 1
316 j += S+1;
317 deal[i++] = j;
318 return eslOK;
319 }
320
321
322 /* Function: esl_rand64_Deal()
323 * Synopsis: Sequential random sample of <m> integers from <n>.
324 * Incept: SRE, Wed 13 Mar 2019 (John Prine, No Ordinary Blue)
325 *
326 * Purpose: Obtain a random sample of <m> integers without replacement
327 * from <n> possible ones, like dealing a hand of m=5 cards
328 * from a deck of n=52 possible cards with cards numbered
329 * <0..n-1>. Caller provides allocated space <deal>,
330 * allocated for at least <m> elements. Return the sample
331 * in <deal>, in sorted order (smallest to largest).
332 *
333 * Uses the Vitter sequential random sampling algorithm
334 * [[Vitter, 1987]](https://dl.acm.org/citation.cfm?id=23003),
335 * which is $O(m)$ time and $O(1)$ additional memory. Selection
336 * sampling and reservoir sampling algorithms are simpler,
337 * but less efficient when the range $n$ is large because
338 * they are $O(n)$ time.
339 *
340 * Args: m - number of integers to sample
341 * n - range: each sample is 0..n-1
342 * deal - RESULT: allocated space for <m> sampled integers
343 *
344 * Returns: <eslOK> on success, and the sample of <m> integers
345 * is in <deal>.
346 *
347 * Throws: (no abnormal error conditions)
348 *
349 * Xref: J.S. Vitter, "An Efficient Algorithm for Sequential
350 * Random Sampling", ACM Trans Math Software 13:58-67
351 * (1987).
352 *
353 * Derived from code by Kevin Lawler (Brave Software; brave.com).
354 * https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/
355 * Copyright (2016) Kevin Lawler. Released under ISC License.
356 * Lawler's implementation closely follows Vitter (1987).
357 * I've only made cosmetic changes to be more Easel-ish.
358 */
359 int
360 esl_rand64_Deal(ESL_RAND64 *rng, int64_t m, int64_t n, int64_t *deal)
361 {
362 int64_t i = 0; // index over samples going into <deal>
363 int64_t j = -1; // index of last sample we took.
364 int64_t S; // randomly sampled gap size. j' = j+S+1.
365 int64_t qu1 = n - m + 1;
366 int64_t negalphainv = -13; // 1/a, where a is free parameter controlling switch to method "A"
367 int64_t threshold = -negalphainv*m; // controls switchover to "method A"
368 double mreal = (double) m;
369 double nreal = (double) n;
370 double minv = 1.0 / (double) m;
371 double mmin1inv = 1.0 / (double) (m-1);
372 double Vprime = exp(minv * log(esl_rand64_double(rng)));
373 double qu1real = nreal - mreal + 1.0;
374 int64_t t, limit;
375 double negSreal, U, X, y1, y2, top, bottom;
376
377 ESL_DASSERT1(( m <= n ));
378
379 while (m > 1 && n > threshold)
380 {
381 mmin1inv = 1.0 / (-1.0 + mreal);
382 while (1)
383 {
384 while (1)
385 {
386 X = nreal * (-Vprime + 1.0);
387 if ((S = floor(X)) < qu1) break;
388 Vprime = exp(minv * log(esl_rand64_double_open(rng)));
389 }
390 U = esl_rand64_double_open(rng);
391 negSreal = -S;
392 y1 = exp(mmin1inv * log(U*nreal/qu1real));
393 Vprime = y1 * (-X/nreal + 1.0) * (qu1real / (negSreal + qu1real));
394 if (Vprime <= 1.) break;
395
396 y2 = 1.;
397 top = nreal - 1.;
398
399 if (n-1 > S) { bottom = nreal - mreal; limit = n - S; }
400 else { bottom = nreal + negSreal - 1.; limit = qu1; }
401
402 for (t = n-1; t >= limit; t--)
403 { y2 = (y2 * top) / bottom; top--; bottom--; }
404
405 if (nreal / (nreal-X) >= y1 * exp(mmin1inv * log(y2)))
406 { Vprime = exp(mmin1inv * log(esl_rand64_double_open(rng))); break; }
407
408 Vprime = exp(minv * log(esl_rand64_double_open(rng)));
409 }
410 j += S+1;
411 deal[i++] = j;
412 n = n - S - 1;
413 nreal = nreal + negSreal - 1.;
414 m -= 1;
415 mreal -= 1.0;
416 minv = mmin1inv;
417 qu1 = qu1 - S;
418 qu1real = qu1real + negSreal;
419 threshold += negalphainv;
420 }
421
422 if (m > 1) vitter_a(rng, m, n, j, deal+i);
423 else {
424 S = floor(n * Vprime);
425 j += S+1;
426 deal[i++] = j;
427 }
428 return eslOK;
429 }
430
431
432
433
434
435 /*****************************************************************
436 * 4. Internal functions implementing MT19937-64
437 *****************************************************************/
438
439 /* mt64_seed_table()
440 * Initialize the state of the RNG from a seed.
441 */
442 static void
443 mt64_seed_table(ESL_RAND64 *rng, uint64_t seed)
444 {
445 int z;
446 rng->mt[0] = rng->seed = seed;
447 for (z = 1; z < 312; z++)
448 rng->mt[z] = 6364136223846793005ULL * (rng->mt[z-1] ^ (rng->mt[z-1] >> 62)) + z;
449 }
450
451 /* mt64_fill_table()
452 * Refill the table with 312 new random numbers.
453 * We do this when we've reseeded, or when we run out of numbers.
454 */
455 static void
456 mt64_fill_table(ESL_RAND64 *rng)
457 {
458 static uint64_t mag01[2] = { 0ULL, 0xB5026F5AA96619E9ULL };
459 uint64_t x;
460 int z;
461
462 for (z = 0; z < 156; z++) // 156 = NN-MM = 312-156
463 {
464 x = (rng->mt[z] & 0xFFFFFFFF80000000ULL) | (rng->mt[z+1] & 0x7FFFFFFFULL);
465 rng->mt[z] = rng->mt[z+156] ^ (x>>1) ^ mag01[(int)(x & 1ULL)];
466 }
467 for (; z < 311; z++) // 311 = NN-1
468 {
469 x = (rng->mt[z] & 0xFFFFFFFF80000000ULL) | (rng->mt[z+1] & 0x7FFFFFFFULL);
470 rng->mt[z] = rng->mt[z-156] ^ (x>>1) ^ mag01[(int)(x & 1ULL)];
471 }
472 x = (rng->mt[311] & 0xFFFFFFFF80000000ULL) | (rng->mt[0] & 0x7FFFFFFFULL);
473 rng->mt[311] = rng->mt[155] ^ (x>>1) ^ mag01[(int)(x & 1ULL)];
474 rng->mti = 0;
475 }
476
477
478 /* choose_arbitrary_seed()
479 * Return a `quasirandom` seed > 0.
480 * Generated by mixing time(), clock(), and getpid().
481 *
482 * The combined entropy of the three sources is substantial, though
483 * not straightforward to calculate because each source is
484 * non-uniformly distributed and we could obtain useful information
485 * about them. One way to Fermi-ballpark it: suppose uniform
486 * distributions over ~10^7 sec in a given year for time(), over 10^6
487 * microseconds for a second since invocation for clock(), and over
488 * ~100,000 possible pids: that's log_2 1e18 = 60 bits. This argues
489 * that it's non-stupid to generate the high and low order 32 bits
490 * of the seed using different mixings of the same three sources.
491 */
492 static uint64_t
493 choose_arbitrary_seed(void)
494 {
495 uint32_t a = (uint32_t) time ((time_t *) NULL); // seconds since the epoch.
496 uint32_t b = 87654321; // we'll use getpid() below, if we can
497 uint32_t c = (uint32_t) clock(); // clock() gives time since process invocation, in msec at least, if not usec
498 uint64_t seed;
499 #ifdef HAVE_GETPID
500 b = (uint32_t) getpid(); // preferable b choice, if we have POSIX getpid()
501 #endif
502 seed = (uint64_t) esl_mix3(a,b,c); // high bits
503 seed = (seed << 32) + (uint64_t) esl_mix3(c,a,b); // low bits: same #'s mixed in a different order
504 return (seed == 0 ? 42 : seed); // 42 is arbitrary, just to avoid seed==0.
505 }
506
507
508 /*****************************************************************
509 * 5. Debugging and development tools
510 *****************************************************************/
511
512 /* Function: esl_rand64_Dump()
513 * Synopsis: Dump ESL_RAND64 internal state to a stream.
514 * Incept: SRE, Wed 22 Aug 2018
515 */
516 int
517 esl_rand64_Dump(FILE *fp, ESL_RAND64 *rng)
518 {
519 int i;
520
521 fprintf(fp, "MT19937-64 RNG state:\n");
522 fprintf(fp, "mti = %d (0..311)\n", rng->mti);
523 fprintf(fp, "seed = %" PRIu64 "\n", rng->seed);
524 for (i = 0; i < 312; i++)
525 {
526 fprintf(fp, "%20" PRIu64 " ", rng->mt[i]);
527 if (i % 10 == 9) fprintf(fp, "\n");
528 }
529 fprintf(fp, "\n");
530 return eslOK;
531 }
532
533 #endif // !defined(eslRAND64_BENCHMARK) && !defined(eslRAND64_TESTDRIVE) && !defined(eslRAND64_EXAMPLE)
534
535
536 /*****************************************************************
537 * 6. Benchmark driver
538 *****************************************************************/
539 #ifdef eslRAND64_BENCHMARK
540
541 #include "easel.h"
542 #include "esl_getopts.h"
543 #include "esl_rand64.h"
544 #include "esl_stopwatch.h"
545
546 /* The 32-bit and 64-bit Mersenne Twisters have similar performance per call.
547 * They can produce about 300M random numbers per second (wyvern: Intel Core i7 3.1Ghz)
548 *
549 * ./esl_rand64_benchmark -N 1000000000
550 * esl_rand64() esl_random()
551 * iter cpu time per call iter cpu time per call
552 * ---- -------- -------- ---- -------- --------
553 * 22 Aug 18, wyvern : 1e9 3.31s 3 nsec 1e9 3.34s 3 nsec
554 */
555 static ESL_OPTIONS options[] = {
556 /* name type default env range toggles reqs incomp help docgroup*/
557 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
558 { "-N", eslARG_INT, "1000000000", NULL, NULL, NULL, NULL, NULL, "number of trials", 0 },
559 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
560 };
561 static char usage[] = "[-options]";
562 static char banner[] = "benchmarking speed of esl_rand64 generator";
563
564 int
565 main(int argc, char **argv)
566 {
567 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
568 ESL_RAND64 *rng = esl_rand64_Create(42);
569 ESL_STOPWATCH *w = esl_stopwatch_Create();
570 int N = esl_opt_GetInteger(go, "-N");
571
572 esl_stopwatch_Start(w);
573 while (N--) esl_rand64(rng);
574 esl_stopwatch_Stop(w);
575 esl_stopwatch_Display(stdout, w, "# CPU Time: ");
576
577 esl_stopwatch_Destroy(w);
578 esl_rand64_Destroy(rng);
579 esl_getopts_Destroy(go);
580 return 0;
581 }
582 #endif // eslRAND64_BENCHMARK
583
584
585
586 /*****************************************************************
587 * 7. Unit tests
588 *****************************************************************/
589 #ifdef eslRAND64_TESTDRIVE
590
591 #include "esl_stats.h"
592 #include "esl_vectorops.h"
593
594
595 /* utest_rand64() uses the same binned-chi-squared-test, six ways */
596 enum esl_rand64_utest_e {
597 eslRAND64_LOWBITS, // esl_rand64(), low-order bits
598 eslRAND64_HIGHBITS, // esl_rand64(), high-order bits
599 eslRAND64_ROLL, // esl_rand64_Roll()
600 eslRAND64_DOUBLE, // esl_rand64_double()
601 eslRAND64_DOUBLE_CLOSED, // esl_rand64_double_closed()
602 eslRAND64_DOUBLE_OPEN, // esl_rand64_double_open()
603 };
604
605 /* utest_rand64()
606 *
607 * Test for uniform distribution of random numbers into bins,
608 * using a chi-squared test. This won't detect subtle problems,
609 * but it should detect show-stopping ones.
610 */
611 static void
612 utest_rand64(ESL_RAND64 *rng, enum esl_rand64_utest_e whichtest)
613 {
614 char msg[] = "rand64 unit test failed";
615 int n = 2000000;
616 int nbins = 1024; // must be a power of two, to get equal-size bins
617 uint64_t divisor = (UINT64_MAX / nbins) + 1; // = 2^64 / nbins, but we can't hold 2^64 in a uint64
618 int *counts = NULL; // binned histogram
619 uint64_t x;
620 double xd;
621 int b;
622 double expect, diff, X2, X2p;
623 int i;
624
625 if (( counts = malloc(sizeof(int) * nbins) ) == NULL) esl_fatal(msg);
626 esl_vec_ISet(counts, nbins, 0);
627
628 if (whichtest == eslRAND64_LOWBITS || whichtest == eslRAND64_HIGHBITS)
629 {
630 for (i = 0; i < n; i++)
631 {
632 x = esl_rand64(rng);
633 if (whichtest == eslRAND64_HIGHBITS) b = (int) (x / divisor);
634 else b = (int) (x % nbins);
635 counts[b]++;
636 }
637 }
638 else if (whichtest == eslRAND64_ROLL)
639 {
640 for (i = 0; i < n; i++)
641 {
642 b = esl_rand64_Roll(rng, nbins);
643 if (b < 0 || b >= nbins) esl_fatal(msg);
644 counts[b]++;
645 }
646 }
647 else // one of the three _double* functions
648 {
649 for (i = 0; i < n; i++)
650 {
651 if (whichtest == eslRAND64_DOUBLE) { xd = esl_rand64_double(rng); if (xd < 0.0 || xd >= 1.0) esl_fatal(msg); }
652 else if (whichtest == eslRAND64_DOUBLE_CLOSED) { xd = esl_rand64_double_closed(rng); if (xd < 0.0 || xd > 1.0) esl_fatal(msg); }
653 else if (whichtest == eslRAND64_DOUBLE_OPEN) { xd = esl_rand64_double_open(rng); if (xd <= 0.0 || xd >= 1.0) esl_fatal(msg); }
654 b = (int) (xd * nbins);
655 if (b < 0 || b >= nbins) esl_fatal(msg); // inconceivable, given the test above on <xd>, but.
656 counts[b] ++;
657 }
658 }
659
660 /* chi-squared test */
661 expect = (double) n / (double) nbins;
662 X2 = 0.;
663 for (i = 0; i < nbins; i++)
664 {
665 diff = (double) counts[i] - expect;
666 X2 += diff * diff / expect;
667 }
668
669 if ( esl_stats_ChiSquaredTest(nbins, X2, &X2p) != eslOK) esl_fatal(msg);
670 if (X2p < 0.01) esl_fatal(msg); // P < 0.01 happens 1% of the time; hence our fixed RNG seed
671 free(counts);
672 }
673
674
675 /* utest_Deal()
676 * Tests the esl_rand64_Deal() sequential sampling algorithm.
677 *
678 * If deals are random, each possible integer is sampled uniformly.
679 * Take <nsamp> deals of <m> integers from possible <n>.
680 * Expected count of each integer = nsamp * (m/n), +/- s.d. \sqrt(u)
681 * Test that min, max are within +/- 6 sd.
682 *
683 * Can fail stochastically, so default test driver uses a fixed RNG seed.
684 */
685 static void
686 utest_Deal(ESL_RAND64 *rng)
687 {
688 char msg[] = "esl_rand64 deal unit test failed";
689 int64_t m = 100;
690 int64_t n = 1000;
691 int64_t nsamp = 10000;
692 int64_t *deal = malloc(sizeof(int64_t) * m);
693 int64_t *ct = malloc(sizeof(int64_t) * n);
694 double expected_mean = ((double) m / (double) n) * (double) nsamp;
695 double expected_sd = sqrt(expected_mean);
696 int64_t max_allowed = (int64_t) round( expected_mean + 6. * expected_sd);
697 int64_t min_allowed = (int64_t) round( expected_mean - 6. * expected_sd);
698 int64_t i;
699
700 if (deal == NULL || ct == NULL) esl_fatal(msg);
701 esl_vec_LSet(ct, n, 0);
702
703 while (nsamp--)
704 {
705 esl_rand64_Deal(rng, m, n, deal);
706 for (i = 0; i < m; i++) ct[deal[i]]++;
707 }
708 if (esl_vec_LMax(ct, n) > max_allowed) esl_fatal(msg);
709 if (esl_vec_LMin(ct, n) < min_allowed) esl_fatal(msg);
710
711 free(deal);
712 free(ct);
713 }
714 #endif // eslRAND64_TESTDRIVE
715
716
717
718 /*****************************************************************
719 * 8. Test driver
720 *****************************************************************/
721 #ifdef eslRAND64_TESTDRIVE
722
723 #include "easel.h"
724 #include "esl_getopts.h"
725 #include "esl_rand64.h"
726
727 /* Default seed is 42, not 0, because this test can fail normally just by stochastic chance */
728 static ESL_OPTIONS options[] = {
729 /* name type default env range togs reqs incomp help docgrp */
730 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
731 { "--bitfile", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "save bit file for NIST tests", 0},
732 { "--seed", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
733 { 0,0,0,0,0,0,0,0,0,0},
734 };
735 static char usage[] = "[-options]";
736 static char banner[] = "test driver for rand64 module";
737
738 static int save_bitfile(char *bitfile, ESL_RAND64 *rng);
739
740 int
741 main(int argc, char **argv)
742 {
743 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
744 ESL_RAND64 *rng = esl_rand64_Create(esl_opt_GetInteger(go, "--seed"));
745 char *bitfile = esl_opt_GetString(go, "--bitfile");
746
747 if (bitfile)
748 { // alternative mode: save NIST bitfile instead of running unit tests
749 save_bitfile(bitfile, rng);
750 }
751 else
752 {
753 fprintf(stderr, "## %s\n", argv[0]);
754 fprintf(stderr, "# rng seed = %" PRIu64 "\n", esl_rand64_GetSeed(rng));
755
756 utest_rand64(rng, eslRAND64_LOWBITS);
757 utest_rand64(rng, eslRAND64_HIGHBITS);
758 utest_rand64(rng, eslRAND64_ROLL);
759 utest_rand64(rng, eslRAND64_DOUBLE);
760 utest_rand64(rng, eslRAND64_DOUBLE_CLOSED);
761 utest_rand64(rng, eslRAND64_DOUBLE_OPEN);
762
763 utest_Deal(rng);
764
765 fprintf(stderr, "# status = ok\n");
766 }
767
768 esl_rand64_Destroy(rng);
769 esl_getopts_Destroy(go);
770 return 0;
771 }
772
773 /* save_bitfile()
774 *
775 * The --bitfile option saves an ASCII file of random 0's and 1's,
776 * instead of running the unit tests. This "bitfile" is suitable for
777 * input to the NIST RNG statistical test suite. [xref H5/140]
778 */
779 static int
780 save_bitfile(char *bitfile, ESL_RAND64 *rng)
781 {
782 FILE *fp = NULL;
783 uint64_t u;
784 int n = 400000; // 4e5 samples x 64 = 2.56e7 bits. Suffices for 20 bitstreams of 10^6 bits.
785 int i,b;
786
787 if (( fp = fopen(bitfile, "w")) == NULL)
788 esl_fatal("failed to open bitfile %s for writing", bitfile);
789
790 for (i = 0; i < n; i++)
791 {
792 u = esl_rand64(rng);
793 for (b = 0; b < 64; b++)
794 {
795 if (u & 0x1) fprintf(fp, "1");
796 else fprintf(fp, "0");
797 u >>= 1;
798 }
799 fprintf(fp, "\n");
800 }
801 fclose(fp);
802 return eslOK;
803 }
804 #endif // eslRAND64_TESTDRIVE
805
806
807
808 /*****************************************************************
809 * 9. Example
810 *****************************************************************/
811 #ifdef eslRAND64_EXAMPLE
812
813 #include "easel.h"
814 #include "esl_getopts.h"
815 #include "esl_rand64.h"
816
817 static ESL_OPTIONS options[] = {
818 /* name type default env range togs reqs incomp help docgrp */
819 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
820 {"--seed", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
821 { 0,0,0,0,0,0,0,0,0,0},
822 };
823 static char usage[] = "[-options]";
824 static char banner[] = "example driver for rand64";
825
826 int
827 main(int argc, char **argv)
828 {
829 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
830 ESL_RAND64 *rng = esl_rand64_Create(esl_opt_GetInteger(go, "--seed"));
831 int i;
832
833 for (i = 0; i < 1000; i++)
834 printf("%20" PRIu64 "\n", esl_rand64(rng));
835
836 esl_rand64_Destroy(rng);
837 esl_getopts_Destroy(go);
838 return 0;
839 }
840 #endif // eslRAND64_EXAMPLE
841
842
843