Soar Kernel  9.3.2 08-06-12
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
soar_rand.h
Go to the documentation of this file.
1 /*************************************************************************
2  * PLEASE SEE THE FILE "license.txt" (INCLUDED WITH THIS SOFTWARE PACKAGE)
3  * AND BELOW FOR LICENSE AND COPYRIGHT INFORMATION.
4  *************************************************************************/
5 
6 /*************************************************************************
7  *
8  * file: soar_rand.h
9  *
10  * =======================================================================
11  * The ANSI rand and srand functions (at least the implementations
12  * provided with Visual Studio) cause problems for us, mostly because
13  * of threading issues (see bug 595).
14  * This is a replacement random number generator that doesn't suffer
15  * from those issues. It also automatically seeds itself, so we don't
16  * have to do that.
17  * Usage: SoarRand() will return a double in [0,1].
18  * SoarRand.RandInt(n) will return an integer in [0,n].
19  * See implementation for complete list of available functions.
20  * =======================================================================
21  */
22 
23 // Mersenne Twister random number generator -- a C++ class MTRand
24 // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
25 // Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com
26 
27 // The Mersenne Twister is an algorithm for generating random numbers. It
28 // was designed with consideration of the flaws in various other generators.
29 // The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
30 // are far greater. The generator is also fast; it avoids multiplication and
31 // division, and it benefits from caches and pipelines. For more information
32 // see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html
33 
34 // Reference
35 // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
36 // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
37 // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
38 
39 // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
40 // Copyright (C) 2000 - 2003, Richard J. Wagner
41 // All rights reserved.
42 //
43 // Redistribution and use in source and binary forms, with or without
44 // modification, are permitted provided that the following conditions
45 // are met:
46 //
47 // 1. Redistributions of source code must retain the above copyright
48 // notice, this list of conditions and the following disclaimer.
49 //
50 // 2. Redistributions in binary form must reproduce the above copyright
51 // notice, this list of conditions and the following disclaimer in the
52 // documentation and/or other materials provided with the distribution.
53 //
54 // 3. The names of its contributors may not be used to endorse or promote
55 // products derived from this software without specific prior written
56 // permission.
57 //
58 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
59 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
60 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
61 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
62 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
63 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
64 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
65 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
66 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
67 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
68 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69 
70 // The original code included the following notice:
71 //
72 // When you use this, send an email to: matumoto@math.keio.ac.jp
73 // with an appropriate reference to your work.
74 //
75 // It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu
76 // when you write.
77 
78 #ifndef SOAR_RAND_H
79 #define SOAR_RAND_H
80 
81 // Not thread safe (unless auto-initialization is avoided and each thread has
82 // its own MTRand object)
83 
84 #include <iostream>
85 #include <limits.h>
86 #include <stdio.h>
87 #include <time.h>
88 #include <math.h>
89 #include "Export.h"
90 
91 class MTRand {
92 // Data
93 public:
94  enum { N = 624 }; // length of state vector
95  enum { SAVE = N + 1 }; // length of array for save()
96 
97 protected:
98  enum { M = 397 }; // period parameter
99 
100  uint32_t state[N]; // internal state
101  uint32_t *pNext; // next value to get from state
102  int left; // number of values left before reload needed
103 
104 
105 //Methods
106 public:
107  MTRand( const uint32_t& oneSeed ); // initialize with a simple uint32
108  MTRand( uint32_t *const bigSeed, uint32_t const seedLength = N ); // or an array
109  MTRand(); // auto-initialize with /dev/urandom or time() and clock()
110 
111  // Do NOT use for CRYPTOGRAPHY without securely hashing several returned
112  // values together, otherwise the generator state can be learned after
113  // reading 624 consecutive values.
114 
115  // Access to 32-bit random numbers
116  double rand(); // real number in [0,1]
117  double rand( const double& n ); // real number in [0,n]
118  double randExc(); // real number in [0,1)
119  double randExc( const double& n ); // real number in [0,n)
120  double randDblExc(); // real number in (0,1)
121  double randDblExc( const double& n ); // real number in (0,n)
122  uint32_t randInt(); // integer in [0,2^32-1]
123  uint32_t randInt( const uint32_t& n ); // integer in [0,n] for n < 2^32
124  double operator()() { return rand(); } // same as rand()
125 
126  // Access to 53-bit random numbers (capacity of IEEE double precision)
127  double rand53(); // real number in [0,1)
128 
129  // Access to nonuniform random number distributions
130  double randNorm( const double& mean = 0.0, const double& stddeviation = 0.0 );
131 
132  // Re-seeding functions with same behavior as initializers
133  void seed( const uint32_t oneSeed );
134  void seed( uint32_t *const bigSeed, const uint32_t seedLength = N );
135  void seed();
136 
137  // Saving and loading generator state
138  void save( uint32_t* saveArray ) const; // to array of size SAVE
139  void load( uint32_t* const loadArray ); // from such array
140  friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand );
141  friend std::istream& operator>>( std::istream& is, MTRand& mtrand );
142 
143 protected:
144  void initialize( const uint32_t oneSeed );
145  void reload();
146  uint32_t hiBit( const uint32_t& u ) const { return u & 0x80000000U; }
147  uint32_t loBit( const uint32_t& u ) const { return u & 0x00000001U; }
148  uint32_t loBits( const uint32_t& u ) const { return u & 0x7fffffffU; }
149  uint32_t mixBits( const uint32_t& u, const uint32_t& v ) const
150  { return hiBit(u) | loBits(v); }
151 #ifdef _MSC_VER
152 #pragma warning( push ) // save current warning settings
153 #pragma warning( disable : 4146 ) // warning C4146: unary minus operator applied to unsigned type, result still unsigned
154 #endif
155  uint32_t twist( const uint32_t& m, const uint32_t& s0, const uint32_t& s1 ) const
156  { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfU); } // RPM 1/06 this line causes Visual Studio warning C4146, but is actually safe
157 #ifdef _MSC_VER
158 #pragma warning( pop ) // return warning settings to what they were
159 #endif
160 
161  static uint32_t hash( time_t t, clock_t c );
162 };
163 
164 
165 inline MTRand::MTRand( const uint32_t& oneSeed )
166  { seed(oneSeed); }
167 
168 inline MTRand::MTRand( uint32_t *const bigSeed, const uint32_t seedLength )
169  { seed(bigSeed,seedLength); }
170 
172  { seed(); }
173 
174 inline double MTRand::rand()
175  { return double(randInt()) * (1.0/4294967295.0); }
176 
177 inline double MTRand::rand( const double& n )
178  { return rand() * n; }
179 
180 inline double MTRand::randExc()
181  { return double(randInt()) * (1.0/4294967296.0); }
182 
183 inline double MTRand::randExc( const double& n )
184  { return randExc() * n; }
185 
186 inline double MTRand::randDblExc()
187  { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); }
188 
189 inline double MTRand::randDblExc( const double& n )
190  { return randDblExc() * n; }
191 
192 inline double MTRand::rand53()
193 {
194  uint32_t a = randInt() >> 5, b = randInt() >> 6;
195  return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada
196 }
197 
198 inline double MTRand::randNorm( const double& mean, const double& stddeviation )
199 {
200  // Return a real number from a normal (Gaussian) distribution with given
201  // mean and variance by Box-Muller method
202  double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * stddeviation;
203  double phi = 2.0 * 3.14159265358979323846264338328 * randExc();
204  return mean + r * cos(phi);
205 }
206 
208 {
209  // Pull a 32-bit integer from the generator state
210  // Every other access function simply transforms the numbers extracted here
211 
212  if( left == 0 ) reload();
213  --left;
214 
215  register uint32_t s1;
216  s1 = *pNext++;
217  s1 ^= (s1 >> 11);
218  s1 ^= (s1 << 7) & 0x9d2c5680U;
219  s1 ^= (s1 << 15) & 0xefc60000U;
220  return ( s1 ^ (s1 >> 18) );
221 }
222 
224 {
225  // Find which bits are used in n
226  // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
227  uint32_t used = n;
228  used |= used >> 1;
229  used |= used >> 2;
230  used |= used >> 4;
231  used |= used >> 8;
232  used |= used >> 16;
233 
234  // Draw numbers until one is found in [0,n]
235  uint32_t i;
236  do
237  i = randInt() & used; // toss unused bits to shorten search
238  while( i > n );
239  return i;
240 }
241 
242 
243 inline void MTRand::seed( const uint32_t oneSeed )
244 {
245  // Seed the generator with a simple uint32
246  initialize(oneSeed);
247  reload();
248 }
249 
250 
251 inline void MTRand::seed( uint32_t *const bigSeed, const uint32_t seedLength )
252 {
253  // Seed the generator with an array of uint32's
254  // There are 2^19937-1 possible initial states. This function allows
255  // all of those to be accessed by providing at least 19937 bits (with a
256  // default seed length of N = 624 uint32's). Any bits above the lower 32
257  // in each element are discarded.
258  // Just call seed() if you want to get array from /dev/urandom
259  initialize(19650218U);
260  register int i = 1;
261  register uint32_t j = 0;
262  register int k = ( N > seedLength ? N : seedLength );
263  for( ; k; --k )
264  {
265  state[i] =
266  state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525U );
267  state[i] += ( bigSeed[j] & 0xffffffffU ) + j;
268  state[i] &= 0xffffffffU;
269  ++i; ++j;
270  if( i >= N ) { state[0] = state[N-1]; i = 1; }
271  if( j >= seedLength ) j = 0;
272  }
273  for( k = N - 1; k; --k )
274  {
275  state[i] =
276  state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941U );
277  state[i] -= i;
278  state[i] &= 0xffffffffU;
279  ++i;
280  if( i >= N ) { state[0] = state[N-1]; i = 1; }
281  }
282  state[0] = 0x80000000U; // MSB is 1, assuring non-zero initial array
283  reload();
284 }
285 
286 
287 inline void MTRand::seed()
288 {
289  // Seed the generator with an array from /dev/urandom if available
290  // Otherwise use a hash of time() and clock() values
291 
292  // First try getting an array from /dev/urandom
293  FILE* urandom = fopen( "/dev/urandom", "rb" );
294  if( urandom )
295  {
296  uint32_t bigSeed[N];
297  register uint32_t* s = bigSeed;
298  register int i = N;
299  register bool success = true;
300  while( success && i-- )
301  //success = fread( s++, sizeof(uint32_t), 1, urandom );
302  success = (fread( s++, sizeof(uint32_t), 1, urandom ) == 0); // RPM 1/06 modified to eliminate Visual Studio warning C4800
303  fclose(urandom);
304  if( success ) { seed( bigSeed, N ); return; }
305  }
306 
307  // Was not successful, so use time() and clock() instead
308  seed( hash( time(NULL), clock() ) );
309 }
310 
311 
312 inline void MTRand::initialize( const uint32_t seed )
313 {
314  // Initialize generator state with seed
315  // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
316  // In previous versions, most significant bits (MSBs) of the seed affect
317  // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto.
318  register uint32_t* s = state;
319  register uint32_t* r = state;
320  register int i = 1;
321  *s++ = seed & 0xffffffffU;
322  for( ; i < N; ++i )
323  {
324  *s++ = ( 1812433253U * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffU;
325  r++;
326  }
327 }
328 
329 
330 inline void MTRand::reload()
331 {
332  // Generate N new values in state
333  // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
334  register uint32_t *p = state;
335  register int i;
336  for( i = N - M; i--; ++p )
337  *p = twist( p[M], p[0], p[1] );
338  for( i = M; --i; ++p )
339  *p = twist( p[M-N], p[0], p[1] );
340  *p = twist( p[M-N], p[0], state[0] );
341 
342  left = N, pNext = state;
343 }
344 
345 
346 inline uint32_t MTRand::hash( time_t t, clock_t c )
347 {
348  // Get a uint32 from t and c
349  // Better than uint32(x) in case x is floating point in [0,1]
350  // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk)
351 
352  static uint32_t differ = 0; // guarantee time-based seeds will change
353 
354  uint32_t h1 = 0;
355  unsigned char *p = (unsigned char *) &t;
356  for( size_t i = 0; i < sizeof(t); ++i )
357  {
358  h1 *= UCHAR_MAX + 2U;
359  h1 += p[i];
360  }
361  uint32_t h2 = 0;
362  p = (unsigned char *) &c;
363  for( size_t j = 0; j < sizeof(c); ++j )
364  {
365  h2 *= UCHAR_MAX + 2U;
366  h2 += p[j];
367  }
368  return ( h1 + differ++ ) ^ h2;
369 }
370 
371 
372 inline void MTRand::save( uint32_t* saveArray ) const
373 {
374  register uint32_t* sa = saveArray;
375  register const uint32_t* s = state;
376  register int i = N;
377  for( ; i--; *sa++ = *s++ ) {}
378  *sa = left;
379 }
380 
381 
382 inline void MTRand::load( uint32_t* const loadArray )
383 {
384  register uint32_t* s = state;
385  register uint32_t* la = loadArray;
386  register int i = N;
387  for( ; i--; *s++ = *la++ ) {}
388  left = *la;
389  pNext = &state[N-left];
390 }
391 
392 
393 inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand )
394 {
395  register const uint32_t* s = mtrand.state;
396  register int i = mtrand.N;
397  for( ; i--; os << *s++ << "\t" ) {}
398  return os << mtrand.left;
399 }
400 
401 
402 inline std::istream& operator>>( std::istream& is, MTRand& mtrand )
403 {
404  register uint32_t* s = mtrand.state;
405  register int i = mtrand.N;
406  for( ; i--; is >> *s++ ) {}
407  is >> mtrand.left;
408  mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left];
409  return is;
410 }
411 
412 // real number in [0,1]
413 EXPORT double SoarRand();
414 
415 // real number in [0,n]
416 EXPORT double SoarRand(const double& max);
417 
418 // integer in [0,2^32-1]
419 EXPORT uint32_t SoarRandInt();
420 
421 // integer in [0,n] for n < 2^32
422 EXPORT uint32_t SoarRandInt(const uint32_t& max);
423 
424 // automatically seed with a value based on the time or /dev/urandom
425 EXPORT void SoarSeedRNG();
426 
427 // seed with a provided value
428 EXPORT void SoarSeedRNG(const uint32_t seed);
429 
430 #endif // SOAR_RAND_H
431 
432 // Change log:
433 //
434 // v0.1 - First release on 15 May 2000
435 // - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
436 // - Translated from C to C++
437 // - Made completely ANSI compliant
438 // - Designed convenient interface for initialization, seeding, and
439 // obtaining numbers in default or user-defined ranges
440 // - Added automatic seeding from /dev/urandom or time() and clock()
441 // - Provided functions for saving and loading generator state
442 //
443 // v0.2 - Fixed bug which reloaded generator one step too late
444 //
445 // v0.3 - Switched to clearer, faster reload() code from Matthew Bellew
446 //
447 // v0.4 - Removed trailing newline in saved generator format to be consistent
448 // with output format of built-in types
449 //
450 // v0.5 - Improved portability by replacing static const int's with enum's and
451 // clarifying return values in seed(); suggested by Eric Heimburg
452 // - Removed MAXINT constant; use 0xffffffffUL instead
453 //
454 // v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits
455 // - Changed integer [0,n] generator to give better uniformity
456 //
457 // v0.7 - Fixed operator precedence ambiguity in reload()
458 // - Added access for real numbers in (0,1) and (0,n)
459 //
460 // v0.8 - Included time.h header to properly support time_t and clock_t
461 //
462 // v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto
463 // - Allowed for seeding with arrays of any length
464 // - Added access for real numbers in [0,1) with 53-bit resolution
465 // - Added access for real numbers from normal (Gaussian) distributions
466 // - Increased overall speed by optimizing twist()
467 // - Doubled speed of integer [0,n] generation
468 // - Fixed out-of-range number generation on 64-bit machines
469 // - Improved portability by substituting literal constants for long enum's
470 // - Changed license from GNU LGPL to BSD