Debian Codegraph @

src/dr/math/MersenneTwisterFast.java

raw symbols SCIP
1 /*
2 * MersenneTwisterFast.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math;
27
28 import java.io.Serializable;
29
30
31 /**
32 * MersenneTwisterFast:
33 * <p/>
34 * A simulation quality fast random number generator (MT19937)
35 * with the same public methods as java.util.Random.
36 * <p/>
37 * <p>About the Mersenne Twister.
38 * This is a Java version of the C-program for MT19937: Integer version.
39 * next(32) generates one pseudorandom unsigned integer (32bit)
40 * which is uniformly distributed among 0 to 2^32-1 for each
41 * call. next(int bits) >>>'s by (32-bits) to get a value ranging
42 * between 0 and 2^bits-1 long inclusive; hope that's correct.
43 * setSeed(seed) set initial values to the working area
44 * of 624 words. For setSeed(seed), seed is any 32-bit integer
45 * except for 0.
46 * <p/>
47 * Reference.
48 * M. Matsumoto and T. Nishimura,
49 * "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
50 * Pseudo-Random Number Generator",
51 * <i>ACM Transactions on Modeling and Computer Simulation,</i>
52 * Vol. 8, No. 1, January 1998, pp 3--30.
53 * <p/>
54 * <p>Bug Fixes. This implementation implements the bug fixes made
55 * in Java 1.2's version of Random, which means it can be used with
56 * earlier versions of Java. See
57 * <a href="http://www.javasoft.com/products/jdk/1.2/docs/api/java/util/Random.html">
58 * the JDK 1.2 java.util.Random documentation</a> for further documentation
59 * on the random-number generation contracts made. Additionally, there's
60 * an undocumented bug in the JDK java.util.Random.nextBytes() method,
61 * which this code fixes.
62 * <p/>
63 * <p> Important Note. Just like java.util.Random, this
64 * generator accepts a long seed but doesn't use all of it. java.util.Random
65 * uses 48 bits. The Mersenne Twister instead uses 32 bits (int size).
66 * So it's best if your seed does not exceed the int range.
67 * <p/>
68 * <p><a href="http://www.cs.umd.edu/users/seanl/">Sean Luke's web page</a>
69 * <p/>
70 * <p/>
71 * - added shuffling method (Alexei Drummond)
72 * <p/>
73 * - added gamma RV method (Marc Suchard)
74 * <p/>
75 * This is now package private - it should be accessed using the instance in Random
76 */
77 class MersenneTwisterFast implements Serializable {
78 /**
79 *
80 */
81 private static final long serialVersionUID = 6185086957226269797L;
82 // Period parameters
83 private static final int N = 624;
84 private static final int M = 397;
85 private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a
86 private static final int UPPER_MASK = 0x80000000; // most significant w-r bits
87 private static final int LOWER_MASK = 0x7fffffff; // least significant r bits
88
89 // mag01[x] = x * MATRIX_A for x=0,1
90 private static final int MAG_01[] = { 0x0, MATRIX_A };
91
92 // Tempering parameters
93 private static final int TEMPERING_MASK_B = 0x9d2c5680;
94 private static final int TEMPERING_MASK_C = 0xefc60000;
95
96 // #define TEMPERING_SHIFT_U(y) (y >>> 11)
97 // #define TEMPERING_SHIFT_S(y) (y << 7)
98 // #define TEMPERING_SHIFT_T(y) (y << 15)
99 // #define TEMPERING_SHIFT_L(y) (y >>> 18)
100
101 private int mt[]; // the array for the state vector
102 private int mti; // mti==N+1 means mt[N] is not initialized
103
104 // a good initial seed (of int size, though stored in a long)
105 private static final long GOOD_SEED = 4357;
106
107 private double nextNextGaussian;
108 private boolean haveNextNextGaussian;
109
110 // The following can be accessed externally by the static accessor methods which
111 // inforce synchronization
112 public static final MersenneTwisterFast DEFAULT_INSTANCE = new MersenneTwisterFast();
113
114 // Added to curernt time in default constructor, and then adjust to allow for programs that construct
115 // multiple MersenneTwisterFast in a short amount of time.
116 private static long seedAdditive_ = 0;
117
118 private long initializationSeed;
119
120 /**
121 * Constructor using the time of day as default seed.
122 */
123 public MersenneTwisterFast() {
124 this(System.currentTimeMillis() + seedAdditive_);
125 seedAdditive_ += nextInt();
126 }
127
128 /**
129 * Constructor using a given seed. Though you pass this seed in
130 * as a long, it's best to make sure it's actually an integer.
131 *
132 * @param seed generator starting number, often the time of day.
133 */
134 private MersenneTwisterFast(long seed) {
135 if (seed == 0) {
136 setSeed(GOOD_SEED);
137 } else {
138 setSeed(seed);
139 }
140 }
141
142
143 /**
144 * Initalize the pseudo random number generator.
145 * The Mersenne Twister only uses an integer for its seed;
146 * It's best that you don't pass in a long that's bigger
147 * than an int.
148 *
149 * @param seed from constructor
150 */
151 public final void setSeed(long seed) {
152 if (seed == 0) {
153 throw new IllegalArgumentException("Non zero random seed required.");
154 }
155 initializationSeed = seed;
156 haveNextNextGaussian = false;
157
158 mt = new int[N];
159
160 // setting initial seeds to mt[N] using
161 // the generator Line 25 of Table 1 in
162 // [KNUTH 1981, The Art of Computer Programming
163 // Vol. 2 (2nd Ed.), pp102]
164
165 // the 0xffffffff is commented out because in Java
166 // ints are always 32 bits; hence i & 0xffffffff == i
167
168 mt[0] = ((int) seed); // & 0xffffffff;
169
170 for (mti = 1; mti < N; mti++)
171 mt[mti] = (69069 * mt[mti - 1]); //& 0xffffffff;
172
173 }
174
175 public final long getSeed() {
176 return initializationSeed;
177 }
178
179 public final int nextInt() {
180 int y;
181
182 if (mti >= N) // generate N words at one time
183 {
184 int kk;
185
186 for (kk = 0; kk < N - M; kk++) {
187 y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
188 mt[kk] = mt[kk + M] ^ (y >>> 1) ^ MAG_01[y & 0x1];
189 }
190 for (; kk < N - 1; kk++) {
191 y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
192 mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ MAG_01[y & 0x1];
193 }
194 y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
195 mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ MAG_01[y & 0x1];
196
197 mti = 0;
198 }
199
200 y = mt[mti++];
201 y ^= y >>> 11; // TEMPERING_SHIFT_U(y)
202 y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y)
203 y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y)
204 y ^= (y >>> 18); // TEMPERING_SHIFT_L(y)
205
206 return y;
207 }
208
209
210 public final short nextShort() {
211 int y = nextInt();
212 return (short) (y >>> 16);
213 }
214
215
216 public final char nextChar() {
217 int y = nextInt();
218
219 return (char) (y >>> 16);
220 }
221
222
223 public final boolean nextBoolean() {
224 int y = nextInt();
225
226 return ((y >>> 31) != 0);
227 }
228
229
230 public final byte nextByte() {
231 int y = nextInt();
232
233 return (byte) (y >>> 24);
234 }
235
236
237 public final void nextBytes(byte[] bytes) {
238 for (int x = 0; x < bytes.length; x++) {
239 int y = nextInt();
240
241 bytes[x] = (byte) (y >>> 24);
242 }
243 }
244
245
246 public final long nextLong() {
247 int y = nextInt();
248 int z = nextInt();
249
250 return (((long) y) << 32) + (long) z;
251 }
252
253
254 public final double nextDouble() {
255 int y = nextInt();
256 int z = nextInt();
257
258 /* derived from nextDouble documentation in jdk 1.2 docs, see top */
259 return ((((long) (y >>> 6)) << 27) + (z >>> 5)) / (double) (1L << 53);
260 }
261
262 public final double nextGaussian() {
263 if (haveNextNextGaussian) {
264 haveNextNextGaussian = false;
265 return nextNextGaussian;
266 } else {
267 double v1, v2, s;
268 do {
269 /* derived from nextDouble documentation in jdk 1.2 docs, see top */
270 v1 = 2.0 * nextDouble() - 1;
271 v2 = 2.0 * nextDouble() - 1;
272 s = v1 * v1 + v2 * v2;
273 } while (s >= 1);
274
275 double multiplier = Math.sqrt(-2 * Math.log(s) / s);
276 nextNextGaussian = v2 * multiplier;
277 haveNextNextGaussian = true;
278 return v1 * multiplier;
279 }
280 }
281
282 public final float nextFloat() {
283 int y = nextInt();
284
285 return (y >>> 8) / ((float) (1 << 24));
286 }
287
288
289 /**
290 * Returns an integer drawn uniformly from 0 to n-1. Suffice it to say,
291 * n must be > 0, or an IllegalArgumentException is raised.
292 */
293 public int nextInt(int n) {
294 if (n <= 0)
295 throw new IllegalArgumentException("n must be positive");
296
297 if ((n & -n) == n) // i.e., n is a power of 2
298 {
299 int y = nextInt();
300
301 return (int) ((n * (long) (y >>> 1)) >> 31);
302 }
303
304 int bits, val;
305 do {
306 int y = nextInt();
307
308 bits = (y >>> 1);
309 val = bits % n;
310 } while (bits - val + (n - 1) < 0);
311 return val;
312 }
313
314 /**
315 * Returns a uniform random permutation of int objects in array
316 */
317 public final void permute(int[] array) {
318 int l = array.length;
319 for (int i = 0; i < l; i++) {
320 int index = nextInt(l - i) + i;
321 int temp = array[index];
322 array[index] = array[i];
323 array[i] = temp;
324 }
325 }
326
327
328 /**
329 * Shuffles an array.
330 */
331 public final void shuffle(int[] array) {
332 int l = array.length;
333 for (int i = 0; i < l; i++) {
334 int index = nextInt(l - i) + i;
335 int temp = array[index];
336 array[index] = array[i];
337 array[i] = temp;
338 }
339 }
340
341 /**
342 * Shuffles an array. Shuffles numberOfShuffles times
343 */
344 public final void shuffle(int[] array, int numberOfShuffles) {
345 int i, j, temp, l = array.length;
346 for (int shuffle = 0; shuffle < numberOfShuffles; shuffle++) {
347 do {
348 i = nextInt(l);
349 j = nextInt(l);
350 } while (i != j);
351 temp = array[j];
352 array[j] = array[i];
353 array[i] = temp;
354 }
355 }
356
357 /**
358 * Returns an array of shuffled indices of length l.
359 *
360 * @param l length of the array required.
361 */
362 public int[] shuffled(int l) {
363
364 int[] array = new int[l];
365
366 // initialize array
367 for (int i = 0; i < l; i++) {
368 array[i] = i;
369 }
370 shuffle(array);
371
372 return array;
373 }
374
375 /**
376 * Returns a uniform random permutation of ints 0,...,l-1
377 *
378 * @param l length of the array required.
379 */
380 public int[] permuted(int l) {
381
382 int[] array = new int[l];
383
384 // initialize array
385 for (int i = 0; i < l; i++) {
386 array[i] = i;
387 }
388 permute(array);
389
390 return array;
391 }
392
393
394 public double nextGamma(double alpha, double lambda) {
395 /******************************************************************
396 * *
397 * Gamma Distribution - Acceptance Rejection combined with *
398 * Acceptance Complement *
399 * *
400 ******************************************************************
401 * *
402 * FUNCTION: - gds samples a random number from the standard *
403 * gamma distribution with parameter a > 0. *
404 * Acceptance Rejection gs for a < 1 , *
405 * Acceptance Complement gd for a >= 1 . *
406 * REFERENCES: - J.H. Ahrens, U. Dieter (1974): Computer methods *
407 * for sampling from gamma, beta, Poisson and *
408 * binomial distributions, Computing 12, 223-246. *
409 * - J.H. Ahrens, U. Dieter (1982): Generating gamma *
410 * variates by a modified rejection technique, *
411 * Communications of the ACM 25, 47-54. *
412 * SUBPROGRAMS: - drand(seed) ... (0,1)-Uniform generator with *
413 * unsigned long integer *seed *
414 * - NORMAL(seed) ... Normal generator N(0,1). *
415 * *
416 ******************************************************************/
417 double a = alpha;
418 double aa = -1.0, aaa = -1.0,
419 b = 0.0, c = 0.0, d = 0.0, e, r, s = 0.0, si = 0.0, ss = 0.0, q0 = 0.0,
420 q1 = 0.0416666664, q2 = 0.0208333723, q3 = 0.0079849875,
421 q4 = 0.0015746717, q5 = -0.0003349403, q6 = 0.0003340332,
422 q7 = 0.0006053049, q8 = -0.0004701849, q9 = 0.0001710320,
423 a1 = 0.333333333, a2 = -0.249999949, a3 = 0.199999867,
424 a4 = -0.166677482, a5 = 0.142873973, a6 = -0.124385581,
425 a7 = 0.110368310, a8 = -0.112750886, a9 = 0.104089866,
426 e1 = 1.000000000, e2 = 0.499999994, e3 = 0.166666848,
427 e4 = 0.041664508, e5 = 0.008345522, e6 = 0.001353826,
428 e7 = 0.000247453;
429
430 double gds, p, q, t, sign_u, u, v, w, x;
431 double v1, v2, v12;
432
433 // Check for invalid input values
434
435 if (a <= 0.0) throw new IllegalArgumentException();
436 if (lambda <= 0.0) new IllegalArgumentException();
437
438 if (a < 1.0) { // CASE A: Acceptance rejection algorithm gs
439 b = 1.0 + 0.36788794412 * a; // Step 1
440 for (; ;) {
441 p = b * nextDouble();
442 if (p <= 1.0) { // Step 2. Case gds <= 1
443 gds = Math.exp(Math.log(p) / a);
444 if (Math.log(nextDouble()) <= -gds) return (gds / lambda);
445 } else { // Step 3. Case gds > 1
446 gds = -Math.log((b - p) / a);
447 if (Math.log(nextDouble()) <= ((a - 1.0) * Math.log(gds))) return (gds / lambda);
448 }
449 }
450 } else { // CASE B: Acceptance complement algorithm gd (gaussian distribution, box muller transformation)
451 if (a != aa) { // Step 1. Preparations
452 aa = a;
453 ss = a - 0.5;
454 s = Math.sqrt(ss);
455 d = 5.656854249 - 12.0 * s;
456 }
457 // Step 2. Normal deviate
458 do {
459 v1 = 2.0 * nextDouble() - 1.0;
460 v2 = 2.0 * nextDouble() - 1.0;
461 v12 = v1 * v1 + v2 * v2;
462 } while (v12 > 1.0);
463 t = v1 * Math.sqrt(-2.0 * Math.log(v12) / v12);
464 x = s + 0.5 * t;
465 gds = x * x;
466 if (t >= 0.0) return (gds / lambda); // Immediate acceptance
467
468 u = nextDouble(); // Step 3. Uniform random number
469 if (d * u <= t * t * t) return (gds / lambda); // Squeeze acceptance
470
471 if (a != aaa) { // Step 4. Set-up for hat case
472 aaa = a;
473 r = 1.0 / a;
474 q0 = ((((((((q9 * r + q8) * r + q7) * r + q6) * r + q5) * r + q4) *
475 r + q3) * r + q2) * r + q1) * r;
476 if (a > 3.686) {
477 if (a > 13.022) {
478 b = 1.77;
479 si = 0.75;
480 c = 0.1515 / s;
481 } else {
482 b = 1.654 + 0.0076 * ss;
483 si = 1.68 / s + 0.275;
484 c = 0.062 / s + 0.024;
485 }
486 } else {
487 b = 0.463 + s - 0.178 * ss;
488 si = 1.235;
489 c = 0.195 / s - 0.079 + 0.016 * s;
490 }
491 }
492 if (x > 0.0) { // Step 5. Calculation of q
493 v = t / (s + s); // Step 6.
494 if (Math.abs(v) > 0.25) {
495 q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v);
496 } else {
497 q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) *
498 v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
499 } // Step 7. Quotient acceptance
500 if (Math.log(1.0 - u) <= q) return (gds / lambda);
501 }
502
503 for (; ;) { // Step 8. Double exponential deviate t
504 do {
505 e = -Math.log(nextDouble());
506 u = nextDouble();
507 u = u + u - 1.0;
508 sign_u = (u > 0) ? 1.0 : -1.0;
509 t = b + (e * si) * sign_u;
510 } while (t <= -0.71874483771719); // Step 9. Rejection of t
511 v = t / (s + s); // Step 10. New q(t)
512 if (Math.abs(v) > 0.25) {
513 q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v);
514 } else {
515 q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) *
516 v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
517 }
518 if (q <= 0.0) continue; // Step 11.
519 if (q > 0.5) {
520 w = Math.exp(q) - 1.0;
521 } else {
522 w = ((((((e7 * q + e6) * q + e5) * q + e4) * q + e3) * q + e2) *
523 q + e1) * q;
524 } // Step 12. Hat acceptance
525 if (c * u * sign_u <= w * Math.exp(e - 0.5 * t * t)) {
526 x = s + 0.5 * t;
527 return (x * x / lambda);
528 }
529 }
530 }
531 }
532
533 public int[] getRandomState() {
534 int[] state = new int[mt.length + 1];
535 state[0] = mti;
536 System.arraycopy(mt, 0, state, 1, mt.length);
537
538 return state;
539 }
540
541 public void setRandomState(int[] rngState) {
542 mti = rngState[0];
543 System.arraycopy(rngState, 1, mt, 0, mt.length);
544 }
545
546 }