CLHEP 2.4.6.4
C++ Class Library for High Energy Physics
Loading...
Searching...
No Matches
MTwistEngine.cc
Go to the documentation of this file.
1// -*- C++ -*-
2//
3// -----------------------------------------------------------------------
4// HEP Random
5// --- MTwistEngine ---
6// class implementation file
7// -----------------------------------------------------------------------
8// A "fast, compact, huge-period generator" based on M. Matsumoto and
9// T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed
10// uniform pseudorandom number generator", to appear in ACM Trans. on
11// Modeling and Computer Simulation. It is a twisted GFSR generator
12// with a Mersenne-prime period of 2^19937-1, uniform on open interval (0,1)
13// =======================================================================
14// Ken Smith - Started initial draft: 14th Jul 1998
15// - Optimized to get std::pow() out of flat() method
16// - Added conversion operators: 6th Aug 1998
17// J. Marraffino - Added some explicit casts to deal with
18// machines where sizeof(int) != sizeof(long) 22 Aug 1998
19// M. Fischler - Modified constructors such that no two
20// seeds will match sequences, no single/double
21// seeds will match, explicit seeds give
22// determined results, and default will not
23// match any of the above or other defaults.
24// - Modified use of the various exponents of 2
25// to avoid per-instance space overhead and
26// correct the rounding procedure 16 Sep 1998
27// J. Marraffino - Remove dependence on hepString class 13 May 1999
28// M. Fischler - In restore, checkFile for file not found 03 Dec 2004
29// M. Fischler - Methods for distrib. instacne save/restore 12/8/04
30// M. Fischler - split get() into tag validation and
31// getState() for anonymous restores 12/27/04
32// M. Fischler - put/get for vectors of ulongs 3/14/05
33// M. Fischler - State-saving using only ints, for portability 4/12/05
34// M. Fischler - Improved seeding in setSeed (Savanah bug #17479) 11/15/06
35// - (Possible optimization - now that the seeding is improved,
36// is it still necessary for ctor to "warm up" by discarding
37// 2000 iterations?)
38//
39// =======================================================================
40
41#include "CLHEP/Random/defs.h"
42#include "CLHEP/Random/Random.h"
43#include "CLHEP/Random/MTwistEngine.h"
44#include "CLHEP/Random/engineIDulong.h"
45#include "CLHEP/Utility/atomic_int.h"
46
47#include <atomic>
48#include <cmath>
49#include <iostream>
50#include <string.h> // for strcmp
51#include <vector>
52
53namespace CLHEP {
54
55namespace {
56 // Number of instances with automatic seed selection
57 CLHEP_ATOMIC_INT_TYPE numberOfEngines(0);
58
59 // Maximum index into the seed table
60 const int maxIndex = 215;
61}
62
63static const int MarkerLen = 64; // Enough room to hold a begin or end marker.
64
65std::string MTwistEngine::name() const {return "MTwistEngine";}
66
69{
70 int numEngines = numberOfEngines++;
71 int cycle = std::abs(int(numEngines/maxIndex));
72 int curIndex = std::abs(int(numEngines%maxIndex));
73 long mask = ((cycle & 0x007fffff) << 8);
74 long seedlist[2];
75 HepRandom::getTheTableSeeds( seedlist, curIndex );
76 seedlist[0] = (seedlist[0])^mask;
77 seedlist[1] = 0;
78 setSeeds( seedlist, numEngines );
79 count624=0;
80
81 for( int i=0; i < 2000; ++i ) flat(); // Warm up just a bit
82}
83
86{
87 long seedlist[2]={seed,17587};
88 setSeeds( seedlist, 0 );
89 count624=0;
90 for( int i=0; i < 2000; ++i ) flat(); // Warm up just a bit
91}
92
93MTwistEngine::MTwistEngine(int rowIndex, int colIndex)
95{
96 int cycle = std::abs(int(rowIndex/maxIndex));
97 int row = std::abs(int(rowIndex%maxIndex));
98 int col = std::abs(int(colIndex%2));
99 long mask = (( cycle & 0x000007ff ) << 20 );
100 long seedlist[2];
101 HepRandom::getTheTableSeeds( seedlist, row );
102 seedlist[0] = (seedlist[col])^mask;
103 seedlist[1] = 690691;
104 setSeeds(seedlist, 4444772);
105 count624=0;
106 for( int i=0; i < 2000; ++i ) flat(); // Warm up just a bit
107}
108
109MTwistEngine::MTwistEngine( std::istream& is )
111{
112 is >> *this;
113}
114
116
118 unsigned int y;
119
120 if( count624 >= N ) {
121 int i;
122
123 for( i=0; i < NminusM; ++i ) {
124 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
125 mt[i] = mt[i+M] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
126 }
127
128 for( ; i < N-1 ; ++i ) {
129 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
130 mt[i] = mt[i-NminusM] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
131 }
132
133 y = (mt[i] & 0x80000000) | (mt[0] & 0x7fffffff);
134 mt[i] = mt[M-1] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
135
136 count624 = 0;
137 }
138
139 y = mt[count624];
140 y ^= ( y >> 11);
141 y ^= ((y << 7 ) & 0x9d2c5680);
142 y ^= ((y << 15) & 0xefc60000);
143 y ^= ( y >> 18);
144
145 return y * twoToMinus_32() + // Scale to range
146 (mt[count624++] >> 11) * twoToMinus_53() + // fill remaining bits
147 nearlyTwoToMinus_54(); // make sure non-zero
148}
149
150void MTwistEngine::flatArray( const int size, double *vect ) {
151 for( int i=0; i < size; ++i) vect[i] = flat();
152}
153
154void MTwistEngine::setSeed(long seed, int k) {
155
156 // MF 11/15/06 - Change seeding algorithm to a newer one recommended
157 // by Matsumoto: The original algorithm was
158 // mt[i] = (69069 * mt[i-1]) & 0xffffffff and this gives
159 // problems when the seed bit pattern has lots of zeros
160 // (for example, 0x08000000). Savanah bug #17479.
161
162 theSeed = seed ? seed : 4357;
163 int mti;
164 const int N1=624;
165 mt[0] = (unsigned int) (theSeed&0xffffffffUL);
166 for (mti=1; mti<N1; mti++) {
167 mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
168 /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
169 /* In the previous versions, MSBs of the seed affect */
170 /* only MSBs of the array mt[]. */
171 /* 2002/01/09 modified by Makoto Matsumoto */
172 mt[mti] &= 0xffffffffUL;
173 /* for >32 bit machines */
174 }
175 for( int i=1; i < 624; ++i ) {
176 mt[i] ^= k; // MF 9/16/98: distinguish starting points
177 }
178 // MF 11/15/06 This distinction of starting points based on values of k
179 // is kept even though the seeding algorithm itself is improved.
180}
181
182void MTwistEngine::setSeeds(const long *seeds, int k) {
183 setSeed( (*seeds ? *seeds : 43571346), k );
184 int i;
185 for( i=1; i < 624; ++i ) {
186 mt[i] = ( seeds[1] + mt[i] ) & 0xffffffff; // MF 9/16/98
187 }
188 theSeeds = seeds;
189}
190
191void MTwistEngine::saveStatus( const char filename[] ) const
192{
193 std::ofstream outFile( filename, std::ios::out ) ;
194 if (!outFile.bad()) {
195 outFile << theSeed << std::endl;
196 for (int i=0; i<624; ++i) outFile <<std::setprecision(20) << mt[i] << " ";
197 outFile << std::endl;
198 outFile << count624 << std::endl;
199 }
200}
201
202void MTwistEngine::restoreStatus( const char filename[] )
203{
204 std::ifstream inFile( filename, std::ios::in);
205 if (!checkFile ( inFile, filename, engineName(), "restoreStatus" )) {
206 std::cerr << " -- Engine state remains unchanged\n";
207 return;
208 }
209
210 if (!inFile.bad() && !inFile.eof()) {
211 inFile >> theSeed;
212 for (int i=0; i<624; ++i) inFile >> mt[i];
213 inFile >> count624;
214 }
215}
216
218{
219 std::cout << std::endl;
220 std::cout << "--------- MTwist engine status ---------" << std::endl;
221 std::cout << std::setprecision(20);
222 std::cout << " Initial seed = " << theSeed << std::endl;
223 std::cout << " Current index = " << count624 << std::endl;
224 std::cout << " Array status mt[] = " << std::endl;
225 // 2014/06/06 L Garren
226 // the final line has 4 elements, not 5
227 for (int i=0; i<620; i+=5) {
228 std::cout << mt[i] << " " << mt[i+1] << " " << mt[i+2] << " "
229 << mt[i+3] << " " << mt[i+4] << "\n";
230 }
231 std::cout << mt[620] << " " << mt[621] << " " << mt[622] << " "
232 << mt[623] << std::endl;
233 std::cout << "----------------------------------------" << std::endl;
234}
235
236MTwistEngine::operator double() {
237 return flat();
238}
239
240MTwistEngine::operator float() {
241 unsigned int y;
242
243 if( count624 >= N ) {
244 int i;
245
246 for( i=0; i < NminusM; ++i ) {
247 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
248 mt[i] = mt[i+M] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
249 }
250
251 for( ; i < N-1 ; ++i ) {
252 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
253 mt[i] = mt[i-NminusM] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
254 }
255
256 y = (mt[i] & 0x80000000) | (mt[0] & 0x7fffffff);
257 mt[i] = mt[M-1] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
258
259 count624 = 0;
260 }
261
262 y = mt[count624++];
263 y ^= ( y >> 11);
264 y ^= ((y << 7 ) & 0x9d2c5680);
265 y ^= ((y << 15) & 0xefc60000);
266 y ^= ( y >> 18);
267
268 return (float)(y * twoToMinus_32());
269}
270
271MTwistEngine::operator unsigned int() {
272 unsigned int y;
273
274 if( count624 >= N ) {
275 int i;
276
277 for( i=0; i < NminusM; ++i ) {
278 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
279 mt[i] = mt[i+M] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
280 }
281
282 for( ; i < N-1 ; ++i ) {
283 y = (mt[i] & 0x80000000) | (mt[i+1] & 0x7fffffff);
284 mt[i] = mt[i-NminusM] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
285 }
286
287 y = (mt[i] & 0x80000000) | (mt[0] & 0x7fffffff);
288 mt[i] = mt[M-1] ^ (y >> 1) ^ ((y & 0x1) ? 0x9908b0df : 0x0 );
289
290 count624 = 0;
291 }
292
293 y = mt[count624++];
294 y ^= ( y >> 11);
295 y ^= ((y << 7 ) & 0x9d2c5680);
296 y ^= ((y << 15) & 0xefc60000);
297 y ^= ( y >> 18);
298
299 return y;
300}
301
302std::ostream & MTwistEngine::put ( std::ostream& os ) const
303{
304 char beginMarker[] = "MTwistEngine-begin";
305 char endMarker[] = "MTwistEngine-end";
306
307 long pr = os.precision(20);
308 os << " " << beginMarker << " ";
309 os << theSeed << " ";
310 for (int i=0; i<624; ++i) {
311 os << mt[i] << "\n";
312 }
313 os << count624 << " ";
314 os << endMarker << "\n";
315 os.precision(pr);
316 return os;
317}
318
319std::vector<unsigned long> MTwistEngine::put () const {
320 std::vector<unsigned long> v;
321 v.push_back (engineIDulong<MTwistEngine>());
322 for (int i=0; i<624; ++i) {
323 v.push_back(static_cast<unsigned long>(mt[i]));
324 }
325 v.push_back(count624);
326 return v;
327}
328
329std::istream & MTwistEngine::get ( std::istream& is )
330{
331 char beginMarker [MarkerLen];
332 is >> std::ws;
333 is.width(MarkerLen); // causes the next read to the char* to be <=
334 // that many bytes, INCLUDING A TERMINATION \0
335 // (Stroustrup, section 21.3.2)
336 is >> beginMarker;
337 if (strcmp(beginMarker,"MTwistEngine-begin")) {
338 is.clear(std::ios::badbit | is.rdstate());
339 std::cerr << "\nInput stream mispositioned or"
340 << "\nMTwistEngine state description missing or"
341 << "\nwrong engine type found." << std::endl;
342 return is;
343 }
344 return getState(is);
345}
346
347std::string MTwistEngine::beginTag ( ) {
348 return "MTwistEngine-begin";
349}
350
351std::istream & MTwistEngine::getState ( std::istream& is )
352{
353 char endMarker [MarkerLen];
354 is >> theSeed;
355 for (int i=0; i<624; ++i) is >> mt[i];
356 is >> count624;
357 is >> std::ws;
358 is.width(MarkerLen);
359 is >> endMarker;
360 if (strcmp(endMarker,"MTwistEngine-end")) {
361 is.clear(std::ios::badbit | is.rdstate());
362 std::cerr << "\nMTwistEngine state description incomplete."
363 << "\nInput stream is probably mispositioned now." << std::endl;
364 return is;
365 }
366 return is;
367}
368
369bool MTwistEngine::get (const std::vector<unsigned long> & v) {
370 if ((v[0] & 0xffffffffUL) != engineIDulong<MTwistEngine>()) {
371 std::cerr <<
372 "\nMTwistEngine get:state vector has wrong ID word - state unchanged\n";
373 return false;
374 }
375 return getState(v);
376}
377
378bool MTwistEngine::getState (const std::vector<unsigned long> & v) {
379 if (v.size() != VECTOR_STATE_SIZE ) {
380 std::cerr <<
381 "\nMTwistEngine get:state vector has wrong length - state unchanged\n";
382 return false;
383 }
384 for (int i=0; i<624; ++i) {
385 mt[i]=(unsigned int)v[i+1];
386 }
387 count624 = (int)v[625];
388 return true;
389}
390
391} // namespace CLHEP
#define CLHEP_ATOMIC_INT_TYPE
Definition: atomic_int.h:25
static double twoToMinus_32()
static double twoToMinus_53()
static double nearlyTwoToMinus_54()
static bool checkFile(std::istream &file, const std::string &filename, const std::string &classname, const std::string &methodname)
Definition: RandomEngine.cc:49
static void getTheTableSeeds(long *seeds, int index)
Definition: Random.cc:256
virtual std::istream & get(std::istream &is)
virtual std::istream & getState(std::istream &is)
void flatArray(const int size, double *vect)
void restoreStatus(const char filename[]="MTwist.conf")
static std::string engineName()
Definition: MTwistEngine.h:79
void setSeeds(const long *seeds, int)
void showStatus() const
void saveStatus(const char filename[]="MTwist.conf") const
std::vector< unsigned long > put() const
std::string name() const
Definition: MTwistEngine.cc:65
static const unsigned int VECTOR_STATE_SIZE
Definition: MTwistEngine.h:85
void setSeed(long seed, int)
static std::string beginTag()
#define double(obj)
Definition: excDblThrow.cc:32