Manually sort some includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / random / random.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2008, The GROMACS development team.
6  * Copyright (c) 2012,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "random.h"
40
41 #include <math.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <time.h>
45
46 #include "config.h"
47
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51 #ifdef GMX_NATIVE_WINDOWS
52 #include <process.h>
53 #endif
54
55 #include "gromacs/math/utilities.h"
56 #include "gromacs/random/random_gausstable.h"
57
58 #include "external/Random123-1.08/include/Random123/threefry.h"
59
60 #define RNG_N 624
61 #define RNG_M 397
62 #define RNG_MATRIX_A 0x9908b0dfUL   /* constant vector a */
63 #define RNG_UPPER_MASK 0x80000000UL /* most significant w-r bits */
64 #define RNG_LOWER_MASK 0x7fffffffUL /* least significant r bits */
65
66 /* Note that if you change the size of the Gaussian table you will
67  * also have to generate new initialization data for the table in
68  * gmx_random_gausstable.h
69  *
70  * A routine print_gaussian_table() is in contrib/random.c
71  * for convenience - use it if you need a different size of the table.
72  */
73 #define GAUSS_TABLE 14 /* the size of the gauss table is 2^GAUSS_TABLE */
74 #define GAUSS_MASK  ((1 << GAUSS_TABLE) - 1)
75
76
77 struct gmx_rng {
78     unsigned int  mt[RNG_N];
79     int           mti;
80     int           has_saved;
81     double        gauss_saved;
82 };
83
84
85
86 int
87 gmx_rng_n(void)
88 {
89     return RNG_N;
90 }
91
92
93 gmx_rng_t
94 gmx_rng_init(unsigned int seed)
95 {
96     struct gmx_rng *rng;
97
98     if ((rng = (struct gmx_rng *)malloc(sizeof(struct gmx_rng))) == NULL)
99     {
100         return NULL;
101     }
102
103     rng->has_saved = 0; /* no saved gaussian number yet */
104
105     rng->mt[0] = seed & 0xffffffffUL;
106     for (rng->mti = 1; rng->mti < RNG_N; rng->mti++)
107     {
108         rng->mt[rng->mti] =
109             (1812433253UL * (rng->mt[rng->mti-1] ^
110                              (rng->mt[rng->mti-1] >> 30)) + rng->mti);
111         /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
112         /* In the previous versions, MSBs of the seed affect   */
113         /* only MSBs of the array mt[].                        */
114         /* 2002/01/09 modified by Makoto Matsumoto             */
115         rng->mt[rng->mti] &= 0xffffffffUL;
116         /* for >32 bit machines */
117     }
118     return rng;
119 }
120
121 gmx_rng_t
122 gmx_rng_init_array(unsigned int seed[], int seed_length)
123 {
124     int       i, j, k;
125     gmx_rng_t rng;
126
127     if ((rng = gmx_rng_init(19650218UL)) == NULL)
128     {
129         return NULL;
130     }
131
132     i = 1; j = 0;
133     k = (RNG_N > seed_length ? RNG_N : seed_length);
134     for (; k; k--)
135     {
136         rng->mt[i] = (rng->mt[i] ^ ((rng->mt[i-1] ^
137                                      (rng->mt[i-1] >> 30)) * 1664525UL))
138             + seed[j] + j;          /* non linear */
139         rng->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
140         i++; j++;
141         if (i >= RNG_N)
142         {
143             rng->mt[0] = rng->mt[RNG_N-1]; i = 1;
144         }
145         if (j >= seed_length)
146         {
147             j = 0;
148         }
149     }
150     for (k = RNG_N-1; k; k--)
151     {
152         rng->mt[i] = (rng->mt[i] ^ ((rng->mt[i-1] ^
153                                      (rng->mt[i-1] >> 30)) *
154                                     1566083941UL))
155             - i;                    /* non linear */
156         rng->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
157         i++;
158         if (i >= RNG_N)
159         {
160             rng->mt[0] = rng->mt[RNG_N-1]; i = 1;
161         }
162     }
163
164     rng->mt[0] = 0x80000000UL;
165     /* MSB is 1; assuring non-zero initial array */
166     return rng;
167 }
168
169
170 void
171 gmx_rng_destroy(gmx_rng_t rng)
172 {
173     if (rng)
174     {
175         free(rng);
176     }
177 }
178
179
180 void
181 gmx_rng_get_state(gmx_rng_t rng, unsigned int *mt, int *mti)
182 {
183     int i;
184
185     for (i = 0; i < RNG_N; i++)
186     {
187         mt[i] = rng->mt[i];
188     }
189     *mti = rng->mti;
190 }
191
192
193 void
194 gmx_rng_set_state(gmx_rng_t rng,  unsigned int *mt, int mti)
195 {
196     int i;
197
198     for (i = 0; i < RNG_N; i++)
199     {
200         rng->mt[i] = mt[i];
201     }
202     rng->mti = mti;
203 }
204
205
206 unsigned int
207 gmx_rng_make_seed(void)
208 {
209     FILE        *fp;
210     unsigned int data;
211     int          ret;
212     long         my_pid;
213
214 #ifdef HAVE_UNISTD_H
215     /* We never want Gromacs execution to halt 10-20 seconds while
216      * waiting for enough entropy in the random number generator.
217      * For this reason we should NOT use /dev/random, which will
218      * block in cases like that. That will cause all sorts of
219      * Gromacs programs to block ~20 seconds while waiting for a
220      * super-random-number to generate cool quotes. Apart from the
221      * minor irritation, it is really bad behavior of a program
222      * to abuse the system random numbers like that - other programs
223      * need them too.
224      * For this reason, we ONLY try to get random numbers from
225      * the pseudo-random stream /dev/urandom, and use other means
226      * if it is not present (in this case fopen() returns NULL).
227      */
228     fp = fopen("/dev/urandom", "rb");
229 #else
230     fp = NULL;
231 #endif
232     if (fp != NULL)
233     {
234         ret = fread(&data, sizeof(unsigned int), 1, fp);
235         fclose(fp);
236     }
237     else
238     {
239         /* No random device available, use time-of-day and process id */
240 #ifdef GMX_NATIVE_WINDOWS
241         my_pid = (long)_getpid();
242 #else
243         my_pid = (long)getpid();
244 #endif
245         data = (unsigned int)(((long)time(NULL)+my_pid) % (long)1000000);
246     }
247     return data;
248 }
249
250
251 /* The random number state contains RNG_N entries that are returned one by
252  * one as random numbers. When we run out of them, this routine is called to
253  * regenerate RNG_N new entries.
254  */
255 static void
256 gmx_rng_update(gmx_rng_t rng)
257 {
258     unsigned int       lastx, x1, x2, y, *mt;
259     int                mti, k;
260     const unsigned int mag01[2] = {0x0UL, RNG_MATRIX_A};
261     /* mag01[x] = x * MATRIX_A  for x=0,1 */
262
263     /* update random numbers */
264     mt  = rng->mt;  /* pointer to array - avoid repeated dereferencing */
265     mti = rng->mti;
266
267     x1        = mt[0];
268     for (k = 0; k < RNG_N-RNG_M-3; k += 4)
269     {
270         x2      = mt[k+1];
271         y       = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
272         mt[k]   = mt[k+RNG_M]   ^ (y >> 1) ^ mag01[y & 0x1UL];
273         x1      = mt[k+2];
274         y       = (x2 & RNG_UPPER_MASK) | (x1 & RNG_LOWER_MASK);
275         mt[k+1] = mt[k+RNG_M+1] ^ (y >> 1) ^ mag01[y & 0x1UL];
276         x2      = mt[k+3];
277         y       = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
278         mt[k+2] = mt[k+RNG_M+2] ^ (y >> 1) ^ mag01[y & 0x1UL];
279         x1      = mt[k+4];
280         y       = (x2 & RNG_UPPER_MASK) | (x1 & RNG_LOWER_MASK);
281         mt[k+3] = mt[k+RNG_M+3] ^ (y >> 1) ^ mag01[y & 0x1UL];
282     }
283     x2        = mt[k+1];
284     y         = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
285     mt[k]     = mt[k+RNG_M] ^ (y >> 1) ^ mag01[y & 0x1UL];
286     k++;
287     x1        = mt[k+1];
288     y         = (x2 & RNG_UPPER_MASK) | (x1 & RNG_LOWER_MASK);
289     mt[k]     = mt[k+RNG_M] ^ (y >> 1) ^ mag01[y & 0x1UL];
290     k++;
291     x2        = mt[k+1];
292     y         = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
293     mt[k]     = mt[k+RNG_M] ^ (y >> 1) ^ mag01[y & 0x1UL];
294     k++;
295     for (; k < RNG_N-1; k += 4)
296     {
297         x1      = mt[k+1];
298         y       = (x2 & RNG_UPPER_MASK) | (x1 & RNG_LOWER_MASK);
299         mt[k]   = mt[k+(RNG_M-RNG_N)]   ^ (y >> 1) ^ mag01[y & 0x1UL];
300         x2      = mt[k+2];
301         y       = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
302         mt[k+1] = mt[k+(RNG_M-RNG_N)+1] ^ (y >> 1) ^ mag01[y & 0x1UL];
303         x1      = mt[k+3];
304         y       = (x2 & RNG_UPPER_MASK) | (x1 & RNG_LOWER_MASK);
305         mt[k+2] = mt[k+(RNG_M-RNG_N)+2] ^ (y >> 1) ^ mag01[y & 0x1UL];
306         x2      = mt[k+4];
307         y       = (x1 & RNG_UPPER_MASK) | (x2 & RNG_LOWER_MASK);
308         mt[k+3] = mt[k+(RNG_M-RNG_N)+3] ^ (y >> 1) ^ mag01[y & 0x1UL];
309     }
310     y           = (x2 & RNG_UPPER_MASK) | (mt[0] & RNG_LOWER_MASK);
311     mt[RNG_N-1] = mt[RNG_M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
312
313     rng->mti = 0;
314 }
315
316
317 real
318 gmx_rng_gaussian_real(gmx_rng_t rng)
319 {
320     real x, y, r;
321
322     if (rng->has_saved)
323     {
324         rng->has_saved = 0;
325         return rng->gauss_saved;
326     }
327     else
328     {
329         do
330         {
331             x = 2.0*gmx_rng_uniform_real(rng)-1.0;
332             y = 2.0*gmx_rng_uniform_real(rng)-1.0;
333             r = x*x+y*y;
334         }
335         while (r > 1.0 || r == 0.0);
336
337         r                = sqrt(-2.0*log(r)/r);
338         rng->gauss_saved = y*r; /* save second random number */
339         rng->has_saved   = 1;
340         return x*r;             /* return first random number */
341     }
342 }
343
344
345
346
347 /* Return a random unsigned integer, i.e. 0..4294967295
348  * Provided in header file for performace reasons.
349  * Unfortunately this function cannot be inlined, since
350  * it needs to refer the internal-linkage gmx_rng_update().
351  */
352 unsigned int
353 gmx_rng_uniform_uint32(gmx_rng_t rng)
354 {
355     unsigned int y;
356
357     if (rng->mti == RNG_N)
358     {
359         gmx_rng_update(rng);
360     }
361     y = rng->mt[rng->mti++];
362
363     y ^= (y >> 11);
364     y ^= (y << 7) & 0x9d2c5680UL;
365     y ^= (y << 15) & 0xefc60000UL;
366     y ^= (y >> 18);
367
368     return y;
369 }
370
371
372
373
374
375 /* Return a uniform floating point number on the interval 0<=x<1 */
376 real
377 gmx_rng_uniform_real(gmx_rng_t rng)
378 {
379     if (sizeof(real) == sizeof(double))
380     {
381         return ((double)gmx_rng_uniform_uint32(rng))*(1.0/4294967296.0);
382     }
383     else
384     {
385         return ((float)gmx_rng_uniform_uint32(rng))*(1.0/4294967423.0);
386     }
387     /* divided by the smallest number that will generate a
388      * single precision real number on 0<=x<1.
389      * This needs to be slightly larger than MAX_UNIT since
390      * we are limited to an accuracy of 1e-7.
391      */
392 }
393 real
394
395 gmx_rng_gaussian_table(gmx_rng_t rng)
396 {
397     unsigned int i;
398
399     i = gmx_rng_uniform_uint32(rng);
400
401     /* The Gaussian table is a static constant in this file */
402     return gaussian_table[i >> (32 - GAUSS_TABLE)];
403 }
404
405 void
406 gmx_rng_cycle_2uniform(gmx_int64_t ctr1, gmx_int64_t ctr2,
407                        gmx_int64_t key1, gmx_int64_t key2,
408                        double* rnd)
409 {
410     const gmx_int64_t  mask_53bits     = 0x1FFFFFFFFFFFFF;
411     const double       two_power_min53 = 1.0/9007199254740992.0;
412
413     threefry2x64_ctr_t ctr  = {{ctr1, ctr2}};
414     threefry2x64_key_t key  = {{key1, key2}};
415     threefry2x64_ctr_t rand = threefry2x64(ctr, key);
416
417     rnd[0] = (rand.v[0] & mask_53bits)*two_power_min53;
418     rnd[1] = (rand.v[1] & mask_53bits)*two_power_min53;
419 }
420
421 void
422 gmx_rng_cycle_3gaussian_table(gmx_int64_t ctr1, gmx_int64_t ctr2,
423                               gmx_int64_t key1, gmx_int64_t key2,
424                               real* rnd)
425 {
426     threefry2x64_ctr_t ctr  = {{ctr1, ctr2}};
427     threefry2x64_key_t key  = {{key1, key2}};
428     threefry2x64_ctr_t rand = threefry2x64(ctr, key);
429
430     rnd[0] = gaussian_table[(rand.v[0] >> 48) & GAUSS_MASK];
431     rnd[1] = gaussian_table[(rand.v[0] >> 32) & GAUSS_MASK];
432     rnd[2] = gaussian_table[(rand.v[0] >> 16) & GAUSS_MASK];
433 }
434
435 void
436 gmx_rng_cycle_6gaussian_table(gmx_int64_t ctr1, gmx_int64_t ctr2,
437                               gmx_int64_t key1, gmx_int64_t key2,
438                               real* rnd)
439 {
440     threefry2x64_ctr_t ctr  = {{ctr1, ctr2}};
441     threefry2x64_key_t key  = {{key1, key2}};
442     threefry2x64_ctr_t rand = threefry2x64(ctr, key);
443
444     rnd[0] = gaussian_table[(rand.v[0] >> 48) & GAUSS_MASK];
445     rnd[1] = gaussian_table[(rand.v[0] >> 32) & GAUSS_MASK];
446     rnd[2] = gaussian_table[(rand.v[0] >> 16) & GAUSS_MASK];
447     rnd[3] = gaussian_table[(rand.v[1] >> 48) & GAUSS_MASK];
448     rnd[4] = gaussian_table[(rand.v[1] >> 32) & GAUSS_MASK];
449     rnd[5] = gaussian_table[(rand.v[1] >> 16) & GAUSS_MASK];
450 }