gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 2 0
merge default
0 files changed with 97 insertions and 6 deletions:
↑ Collapse diff ↑
Ignore white space 1536 line context
1 1
dnl Process this file with autoconf to produce a configure script.
2 2

	
3 3
dnl Version information.
4
m4_define([lemon_version_major], [0])
5
m4_define([lemon_version_minor], [99])
6
m4_define([lemon_version_micro], [])
7
m4_define([lemon_version_nano], [])
8
m4_define([lemon_version_tag], [hg])
4
m4_define([lemon_version_number], [])
9 5
m4_define([lemon_hg_revision], [m4_normalize(esyscmd([hg id -i]))])
10
m4_define([lemon_version], [lemon_version_major().lemon_version_minor()ifelse(lemon_version_micro(), [], [], [.lemon_version_micro()])ifelse(lemon_version_nano(), [], [], [.lemon_version_nano()])ifelse(lemon_version_tag(), [], [], lemon_version_tag(), [hg], [[_]lemon_version_tag()[_]lemon_hg_revision()], [[_]lemon_version_tag()])])
6
m4_define([lemon_version], [ifelse(lemon_version_number(), [], [lemon_hg_revision()], [lemon_version_number()])])
11 7

	
12 8
AC_PREREQ([2.59])
13 9
AC_INIT([LEMON], [lemon_version()], [lemon-devel@lemon.cs.elte.hu], [lemon])
14 10
AC_CONFIG_AUX_DIR([build-aux])
15 11
AC_CONFIG_MACRO_DIR([m4])
16 12
AM_INIT_AUTOMAKE([-Wall -Werror foreign subdir-objects nostdinc])
17 13
AC_CONFIG_SRCDIR([lemon/list_graph.h])
18 14
AC_CONFIG_HEADERS([config.h lemon/config.h])
19 15

	
20 16
lx_cmdline_cxxflags_set=${CXXFLAGS+set}
21 17

	
22 18
dnl Checks for programs.
23 19
AC_PROG_CXX
24 20
AC_PROG_CXXCPP
25 21
AC_PROG_INSTALL
26 22
AC_DISABLE_SHARED
27 23
AC_PROG_LIBTOOL
28 24

	
29 25
AC_CHECK_PROG([doxygen_found],[doxygen],[yes],[no])
30 26
AC_CHECK_PROG([gs_found],[gs],[yes],[no])
31 27

	
32 28
if test x"$lx_cmdline_cxxflags_set" != x"set" -a "$GXX" = yes; then
33 29
  CXXFLAGS="$CXXFLAGS -Wall -W -Wall -W -Wunused -Wformat=2 -Wctor-dtor-privacy -Wnon-virtual-dtor -Wno-char-subscripts -Wwrite-strings -Wno-char-subscripts -Wreturn-type -Wcast-qual -Wcast-align -Wsign-promo -Woverloaded-virtual -Woverloaded-virtual -ansi -fno-strict-aliasing -Wold-style-cast -Wno-unknown-pragmas"
34 30
fi
35 31

	
36 32
dnl Checks for libraries.
37 33
LX_CHECK_GLPK
38 34
LX_CHECK_CPLEX
39 35
LX_CHECK_SOPLEX
40 36

	
41 37
dnl Disable/enable building the demo programs
42 38
AC_ARG_ENABLE([demo],
43 39
AS_HELP_STRING([--enable-demo], [build the demo programs])
44 40
AS_HELP_STRING([--disable-demo], [do not build the demo programs @<:@default@:>@]),
45 41
              [], [enable_demo=no])
46 42
AC_MSG_CHECKING([whether to build the demo programs])
47 43
if test x"$enable_demo" != x"no"; then
48 44
  AC_MSG_RESULT([yes])
49 45
else
50 46
  AC_MSG_RESULT([no])
51 47
fi
52 48
AM_CONDITIONAL([WANT_DEMO], [test x"$enable_demo" != x"no"])
53 49

	
54 50
dnl Disable/enable building the binary tools
55 51
AC_ARG_ENABLE([tools],
56 52
AS_HELP_STRING([--enable-tools], [build additional tools @<:@default@:>@])
57 53
AS_HELP_STRING([--disable-tools], [do not build additional tools]),
58 54
              [], [enable_tools=yes])
59 55
AC_MSG_CHECKING([whether to build the additional tools])
60 56
if test x"$enable_tools" != x"no"; then
61 57
  AC_MSG_RESULT([yes])
62 58
else
63 59
  AC_MSG_RESULT([no])
64 60
fi
65 61
AM_CONDITIONAL([WANT_TOOLS], [test x"$enable_tools" != x"no"])
66 62

	
67 63
dnl Disable/enable building the benchmarks
68 64
AC_ARG_ENABLE([benchmark],
69 65
AS_HELP_STRING([--enable-benchmark], [build the benchmarks])
70 66
AS_HELP_STRING([--disable-benchmark], [do not build the benchmarks @<:@default@:>@]),
71 67
              [], [enable_benchmark=no])
72 68
AC_MSG_CHECKING([whether to build the benchmarks])
73 69
if test x"$enable_benchmark" != x"no"; then
74 70
  AC_MSG_RESULT([yes])
75 71
else
76 72
  AC_MSG_RESULT([no])
77 73
fi
78 74
AM_CONDITIONAL([WANT_BENCHMARK], [test x"$enable_benchmark" != x"no"])
79 75

	
80 76
dnl Checks for header files.
81 77
AC_CHECK_HEADERS(limits.h sys/time.h sys/times.h unistd.h)
82 78

	
83 79
dnl Checks for typedefs, structures, and compiler characteristics.
84 80
AC_C_CONST
85 81
AC_C_INLINE
86 82
AC_TYPE_SIZE_T
87 83
AC_HEADER_TIME
88 84
AC_STRUCT_TM
89 85

	
90 86
dnl Checks for library functions.
91 87
AC_HEADER_STDC
92 88
AC_CHECK_FUNCS(gettimeofday times ctime_r)
93 89

	
94 90
AC_CONFIG_FILES([
95 91
Makefile
96 92
doc/Doxyfile
97 93
lemon/lemon.pc
98 94
])
99 95

	
100 96
AC_OUTPUT
101 97

	
102 98
echo
103 99
echo '****************************** SUMMARY ******************************'
104 100
echo
105 101
echo Package version............... : $PACKAGE-$VERSION
106 102
echo
107 103
echo C++ compiler.................. : $CXX
108 104
echo C++ compiles flags............ : $CXXFLAGS
109 105
echo
110 106
echo GLPK support.................. : $lx_glpk_found
111 107
echo CPLEX support................. : $lx_cplex_found
112 108
echo SOPLEX support................ : $lx_soplex_found
113 109
echo
114 110
echo Build benchmarks.............. : $enable_benchmark
115 111
echo Build demo programs........... : $enable_demo
116 112
echo Build additional tools........ : $enable_tools
117 113
echo
118 114
echo The packace will be installed in
119 115
echo -n '  '
120 116
echo $prefix.
121 117
echo
122 118
echo '*********************************************************************'
123 119

	
124 120
echo
125 121
echo Configure complete, now type \'make\' and then \'make install\'.
126 122
echo
Ignore white space 6 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
/*
20 20
 * This file contains the reimplemented version of the Mersenne Twister
21 21
 * Generator of Matsumoto and Nishimura.
22 22
 *
23 23
 * See the appropriate copyright notice below.
24 24
 * 
25 25
 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
26 26
 * All rights reserved.                          
27 27
 *
28 28
 * Redistribution and use in source and binary forms, with or without
29 29
 * modification, are permitted provided that the following conditions
30 30
 * are met:
31 31
 *
32 32
 * 1. Redistributions of source code must retain the above copyright
33 33
 *    notice, this list of conditions and the following disclaimer.
34 34
 *
35 35
 * 2. Redistributions in binary form must reproduce the above copyright
36 36
 *    notice, this list of conditions and the following disclaimer in the
37 37
 *    documentation and/or other materials provided with the distribution.
38 38
 *
39 39
 * 3. The names of its contributors may not be used to endorse or promote 
40 40
 *    products derived from this software without specific prior written 
41 41
 *    permission.
42 42
 *
43 43
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44 44
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
45 45
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
46 46
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
47 47
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
48 48
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49 49
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50 50
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 51
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52 52
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53 53
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54 54
 * OF THE POSSIBILITY OF SUCH DAMAGE.
55 55
 *
56 56
 *
57 57
 * Any feedback is very welcome.
58 58
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
59 59
 * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
60 60
 */
61 61

	
62 62
#ifndef LEMON_RANDOM_H
63 63
#define LEMON_RANDOM_H
64 64

	
65 65
#include <algorithm>
66 66
#include <iterator>
67 67
#include <vector>
68 68
#include <limits>
69
#include <fstream>
69 70

	
70 71
#include <lemon/math.h>
71 72
#include <lemon/dim2.h>
72 73

	
74
#ifndef WIN32
75
#include <sys/time.h>
76
#include <ctime>
77
#include <sys/types.h>
78
#include <unistd.h>
79
#else
80
#include <windows.h>
81
#endif
82

	
73 83
///\ingroup misc
74 84
///\file
75 85
///\brief Mersenne Twister random number generator
76 86

	
77 87
namespace lemon {
78 88

	
79 89
  namespace _random_bits {
80 90
    
81 91
    template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
82 92
    struct RandomTraits {};
83 93

	
84 94
    template <typename _Word>
85 95
    struct RandomTraits<_Word, 32> {
86 96

	
87 97
      typedef _Word Word;
88 98
      static const int bits = 32;
89 99

	
90 100
      static const int length = 624;
91 101
      static const int shift = 397;
92 102
      
93 103
      static const Word mul = 0x6c078965u;
94 104
      static const Word arrayInit = 0x012BD6AAu;
95 105
      static const Word arrayMul1 = 0x0019660Du;
96 106
      static const Word arrayMul2 = 0x5D588B65u;
97 107

	
98 108
      static const Word mask = 0x9908B0DFu;
99 109
      static const Word loMask = (1u << 31) - 1;
100 110
      static const Word hiMask = ~loMask;
101 111

	
102 112

	
103 113
      static Word tempering(Word rnd) {
104 114
        rnd ^= (rnd >> 11);
105 115
        rnd ^= (rnd << 7) & 0x9D2C5680u;
106 116
        rnd ^= (rnd << 15) & 0xEFC60000u;
107 117
        rnd ^= (rnd >> 18);
108 118
        return rnd;
109 119
      }
110 120

	
111 121
    };
112 122

	
113 123
    template <typename _Word>
114 124
    struct RandomTraits<_Word, 64> {
115 125

	
116 126
      typedef _Word Word;
117 127
      static const int bits = 64;
118 128

	
119 129
      static const int length = 312;
120 130
      static const int shift = 156;
121 131

	
122 132
      static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
123 133
      static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
124 134
      static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
125 135
      static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
126 136

	
127 137
      static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
128 138
      static const Word loMask = (Word(1u) << 31) - 1;
129 139
      static const Word hiMask = ~loMask;
130 140

	
131 141
      static Word tempering(Word rnd) {
132 142
        rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
133 143
        rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
134 144
        rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
135 145
        rnd ^= (rnd >> 43);
136 146
        return rnd;
137 147
      }
138 148

	
139 149
    };
140 150

	
141 151
    template <typename _Word>
142 152
    class RandomCore {
143 153
    public:
144 154

	
145 155
      typedef _Word Word;
146 156

	
147 157
    private:
148 158

	
149 159
      static const int bits = RandomTraits<Word>::bits;
150 160

	
151 161
      static const int length = RandomTraits<Word>::length;
152 162
      static const int shift = RandomTraits<Word>::shift;
153 163

	
154 164
    public:
155 165

	
156 166
      void initState() {
157 167
        static const Word seedArray[4] = {
158 168
          0x12345u, 0x23456u, 0x34567u, 0x45678u
159 169
        };
160 170
    
161 171
        initState(seedArray, seedArray + 4);
162 172
      }
163 173

	
164 174
      void initState(Word seed) {
165 175

	
166 176
        static const Word mul = RandomTraits<Word>::mul;
167 177

	
168 178
        current = state; 
169 179

	
170 180
        Word *curr = state + length - 1;
171 181
        curr[0] = seed; --curr;
172 182
        for (int i = 1; i < length; ++i) {
173 183
          curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
174 184
          --curr;
175 185
        }
176 186
      }
177 187

	
178 188
      template <typename Iterator>
179 189
      void initState(Iterator begin, Iterator end) {
180 190

	
181 191
        static const Word init = RandomTraits<Word>::arrayInit;
182 192
        static const Word mul1 = RandomTraits<Word>::arrayMul1;
183 193
        static const Word mul2 = RandomTraits<Word>::arrayMul2;
184 194

	
185 195

	
186 196
        Word *curr = state + length - 1; --curr;
187 197
        Iterator it = begin; int cnt = 0;
188 198
        int num;
189 199

	
190 200
        initState(init);
191 201

	
192 202
        num = length > end - begin ? length : end - begin;
193 203
        while (num--) {
194 204
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 
195 205
            + *it + cnt;
196 206
          ++it; ++cnt;
197 207
          if (it == end) {
198 208
            it = begin; cnt = 0;
199 209
          }
200 210
          if (curr == state) {
201 211
            curr = state + length - 1; curr[0] = state[0];
202 212
          }
203 213
          --curr;
204 214
        }
205 215

	
206 216
        num = length - 1; cnt = length - (curr - state) - 1;
207 217
        while (num--) {
208 218
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
209 219
            - cnt;
210 220
          --curr; ++cnt;
211 221
          if (curr == state) {
212 222
            curr = state + length - 1; curr[0] = state[0]; --curr;
213 223
            cnt = 1;
214 224
          }
215 225
        }
216 226
        
217 227
        state[length - 1] = Word(1) << (bits - 1);
218 228
      }
219 229
      
220 230
      void copyState(const RandomCore& other) {
221 231
        std::copy(other.state, other.state + length, state);
222 232
        current = state + (other.current - other.state);
223 233
      }
224 234

	
225 235
      Word operator()() {
226 236
        if (current == state) fillState();
227 237
        --current;
228 238
        Word rnd = *current;
229 239
        return RandomTraits<Word>::tempering(rnd);
230 240
      }
231 241

	
232 242
    private:
233 243

	
234 244
  
235 245
      void fillState() {
236 246
        static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
237 247
        static const Word loMask = RandomTraits<Word>::loMask;
238 248
        static const Word hiMask = RandomTraits<Word>::hiMask;
239 249

	
240 250
        current = state + length; 
241 251

	
242 252
        register Word *curr = state + length - 1;
243 253
        register long num;
244 254
      
245 255
        num = length - shift;
246 256
        while (num--) {
247 257
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
248 258
            curr[- shift] ^ mask[curr[-1] & 1ul];
249 259
          --curr;
250 260
        }
251 261
        num = shift - 1;
252 262
        while (num--) {
253 263
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
254 264
            curr[length - shift] ^ mask[curr[-1] & 1ul];
255 265
          --curr;
256 266
        }
257 267
        state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
258 268
          curr[length - shift] ^ mask[curr[length - 1] & 1ul];
259 269

	
260 270
      }
261 271

	
262 272
  
263 273
      Word *current;
264 274
      Word state[length];
265 275
      
266 276
    };
267 277

	
268 278

	
269 279
    template <typename Result, 
270 280
              int shift = (std::numeric_limits<Result>::digits + 1) / 2>
271 281
    struct Masker {
272 282
      static Result mask(const Result& result) {
273 283
        return Masker<Result, (shift + 1) / 2>::
274 284
          mask(static_cast<Result>(result | (result >> shift)));
275 285
      }
276 286
    };
277 287
    
278 288
    template <typename Result>
279 289
    struct Masker<Result, 1> {
280 290
      static Result mask(const Result& result) {
281 291
        return static_cast<Result>(result | (result >> 1));
282 292
      }
283 293
    };
284 294

	
285 295
    template <typename Result, typename Word, 
286 296
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
287 297
              bool last = rest <= std::numeric_limits<Word>::digits>
288 298
    struct IntConversion {
289 299
      static const int bits = std::numeric_limits<Word>::digits;
290 300
    
291 301
      static Result convert(RandomCore<Word>& rnd) {
292 302
        return static_cast<Result>(rnd() >> (bits - rest)) << shift;
293 303
      }
294 304
      
295 305
    }; 
296 306

	
297 307
    template <typename Result, typename Word, int rest, int shift> 
298 308
    struct IntConversion<Result, Word, rest, shift, false> {
299 309
      static const int bits = std::numeric_limits<Word>::digits;
300 310

	
301 311
      static Result convert(RandomCore<Word>& rnd) {
302 312
        return (static_cast<Result>(rnd()) << shift) | 
303 313
          IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
304 314
      }
305 315
    };
306 316

	
307 317

	
308 318
    template <typename Result, typename Word,
309 319
              bool one_word = (std::numeric_limits<Word>::digits < 
310 320
			       std::numeric_limits<Result>::digits) >
311 321
    struct Mapping {
312 322
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
313 323
        Word max = Word(bound - 1);
314 324
        Result mask = Masker<Result>::mask(bound - 1);
315 325
        Result num;
316 326
        do {
317 327
          num = IntConversion<Result, Word>::convert(rnd) & mask; 
318 328
        } while (num > max);
319 329
        return num;
320 330
      }
321 331
    };
322 332

	
323 333
    template <typename Result, typename Word>
324 334
    struct Mapping<Result, Word, false> {
325 335
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
326 336
        Word max = Word(bound - 1);
327 337
        Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
328 338
          ::mask(max);
329 339
        Word num;
330 340
        do {
331 341
          num = rnd() & mask;
332 342
        } while (num > max);
333 343
        return num;
334 344
      }
335 345
    };
336 346

	
337 347
    template <typename Result, int exp, bool pos = (exp >= 0)>
338 348
    struct ShiftMultiplier {
339 349
      static const Result multiplier() {
340 350
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
341 351
        res *= res;
342 352
        if ((exp & 1) == 1) res *= static_cast<Result>(2.0);
343 353
        return res; 
344 354
      }
345 355
    };
346 356

	
347 357
    template <typename Result, int exp>
348 358
    struct ShiftMultiplier<Result, exp, false> {
349 359
      static const Result multiplier() {
350 360
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
351 361
        res *= res;
352 362
        if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
353 363
        return res; 
354 364
      }
355 365
    };
356 366

	
357 367
    template <typename Result>
358 368
    struct ShiftMultiplier<Result, 0, true> {
359 369
      static const Result multiplier() {
360 370
        return static_cast<Result>(1.0); 
361 371
      }
362 372
    };
363 373

	
364 374
    template <typename Result>
365 375
    struct ShiftMultiplier<Result, -20, true> {
366 376
      static const Result multiplier() {
367 377
        return static_cast<Result>(1.0/1048576.0); 
368 378
      }
369 379
    };
370 380
    
371 381
    template <typename Result>
372 382
    struct ShiftMultiplier<Result, -32, true> {
373 383
      static const Result multiplier() {
374 384
        return static_cast<Result>(1.0/424967296.0); 
375 385
      }
376 386
    };
377 387

	
378 388
    template <typename Result>
379 389
    struct ShiftMultiplier<Result, -53, true> {
380 390
      static const Result multiplier() {
381 391
        return static_cast<Result>(1.0/9007199254740992.0); 
382 392
      }
383 393
    };
384 394

	
385 395
    template <typename Result>
386 396
    struct ShiftMultiplier<Result, -64, true> {
387 397
      static const Result multiplier() {
388 398
        return static_cast<Result>(1.0/18446744073709551616.0); 
389 399
      }
390 400
    };
391 401

	
392 402
    template <typename Result, int exp>
393 403
    struct Shifting {
394 404
      static Result shift(const Result& result) {
395 405
        return result * ShiftMultiplier<Result, exp>::multiplier();
396 406
      }
397 407
    };
398 408

	
399 409
    template <typename Result, typename Word,
400 410
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
401 411
              bool last = rest <= std::numeric_limits<Word>::digits>
402 412
    struct RealConversion{ 
403 413
      static const int bits = std::numeric_limits<Word>::digits;
404 414

	
405 415
      static Result convert(RandomCore<Word>& rnd) {
406 416
        return Shifting<Result, - shift - rest>::
407 417
          shift(static_cast<Result>(rnd() >> (bits - rest)));
408 418
      }
409 419
    };
410 420

	
411 421
    template <typename Result, typename Word, int rest, int shift>
412 422
    struct RealConversion<Result, Word, rest, shift, false> { 
413 423
      static const int bits = std::numeric_limits<Word>::digits;
414 424

	
415 425
      static Result convert(RandomCore<Word>& rnd) {
416 426
        return Shifting<Result, - shift - bits>::
417 427
          shift(static_cast<Result>(rnd())) +
418 428
          RealConversion<Result, Word, rest-bits, shift + bits>::
419 429
          convert(rnd);
420 430
      }
421 431
    };
422 432

	
423 433
    template <typename Result, typename Word>
424 434
    struct Initializer {
425 435

	
426 436
      template <typename Iterator>
427 437
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
428 438
        std::vector<Word> ws;
429 439
        for (Iterator it = begin; it != end; ++it) {
430 440
          ws.push_back(Word(*it));
431 441
        }
432 442
        rnd.initState(ws.begin(), ws.end());
433 443
      }
434 444

	
435 445
      static void init(RandomCore<Word>& rnd, Result seed) {
436 446
        rnd.initState(seed);
437 447
      }
438 448
    };
439 449

	
440 450
    template <typename Word>
441 451
    struct BoolConversion {
442 452
      static bool convert(RandomCore<Word>& rnd) {
443 453
        return (rnd() & 1) == 1;
444 454
      }
445 455
    };
446 456

	
447 457
    template <typename Word>
448 458
    struct BoolProducer {
449 459
      Word buffer;
450 460
      int num;
451 461
      
452 462
      BoolProducer() : num(0) {}
453 463

	
454 464
      bool convert(RandomCore<Word>& rnd) {
455 465
        if (num == 0) {
456 466
          buffer = rnd();
457 467
          num = RandomTraits<Word>::bits;
458 468
        }
459 469
        bool r = (buffer & 1);
460 470
        buffer >>= 1;
461 471
        --num;
462 472
        return r;
463 473
      }
464 474
    };
465 475

	
466 476
  }
467 477

	
468 478
  /// \ingroup misc
469 479
  ///
470 480
  /// \brief Mersenne Twister random number generator
471 481
  ///
472 482
  /// The Mersenne Twister is a twisted generalized feedback
473 483
  /// shift-register generator of Matsumoto and Nishimura. The period
474 484
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
475 485
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
476 486
  /// performance of this generator is comparable to the commonly used
477 487
  /// generators.
478 488
  ///
479 489
  /// This implementation is specialized for both 32-bit and 64-bit
480 490
  /// architectures. The generators differ sligthly in the
481 491
  /// initialization and generation phase so they produce two
482 492
  /// completly different sequences.
483 493
  ///
484 494
  /// The generator gives back random numbers of serveral types. To
485 495
  /// get a random number from a range of a floating point type you
486 496
  /// can use one form of the \c operator() or the \c real() member
487 497
  /// function. If you want to get random number from the {0, 1, ...,
488 498
  /// n-1} integer range use the \c operator[] or the \c integer()
489 499
  /// method. And to get random number from the whole range of an
490 500
  /// integer type you can use the argumentless \c integer() or \c
491 501
  /// uinteger() functions. After all you can get random bool with
492 502
  /// equal chance of true and false or given probability of true
493 503
  /// result with the \c boolean() member functions.
494 504
  ///
495 505
  ///\code
496 506
  /// // The commented code is identical to the other
497 507
  /// double a = rnd();                     // [0.0, 1.0)
498 508
  /// // double a = rnd.real();             // [0.0, 1.0)
499 509
  /// double b = rnd(100.0);                // [0.0, 100.0)
500 510
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
501 511
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
502 512
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
503 513
  /// int d = rnd[100000];                  // 0..99999
504 514
  /// // int d = rnd.integer(100000);       // 0..99999
505 515
  /// int e = rnd[6] + 1;                   // 1..6
506 516
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
507 517
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
508 518
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
509 519
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
510 520
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
511 521
  ///\endcode
512 522
  ///
513 523
  /// LEMON provides a global instance of the random number
514 524
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
515 525
  /// good programming convenience to use this global generator to get
516 526
  /// random numbers.
517 527
  class Random {
518 528
  private:
519 529

	
520 530
    // Architecture word
521 531
    typedef unsigned long Word;
522 532
    
523 533
    _random_bits::RandomCore<Word> core;
524 534
    _random_bits::BoolProducer<Word> bool_producer;
525 535
    
526 536

	
527 537
  public:
528 538

	
539
    ///\name Initialization
540
    ///
541
    /// @{
542

	
543
    ///\name Initialization
544
    ///
545
    /// @{
546

	
529 547
    /// \brief Default constructor
530 548
    ///
531 549
    /// Constructor with constant seeding.
532 550
    Random() { core.initState(); }
533 551

	
534 552
    /// \brief Constructor with seed
535 553
    ///
536 554
    /// Constructor with seed. The current number type will be converted
537 555
    /// to the architecture word type.
538 556
    template <typename Number>
539 557
    Random(Number seed) { 
540 558
      _random_bits::Initializer<Number, Word>::init(core, seed);
541 559
    }
542 560

	
543 561
    /// \brief Constructor with array seeding
544 562
    ///
545 563
    /// Constructor with array seeding. The given range should contain
546 564
    /// any number type and the numbers will be converted to the
547 565
    /// architecture word type.
548 566
    template <typename Iterator>
549 567
    Random(Iterator begin, Iterator end) { 
550 568
      typedef typename std::iterator_traits<Iterator>::value_type Number;
551 569
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
552 570
    }
553 571

	
554 572
    /// \brief Copy constructor
555 573
    ///
556 574
    /// Copy constructor. The generated sequence will be identical to
557 575
    /// the other sequence. It can be used to save the current state
558 576
    /// of the generator and later use it to generate the same
559 577
    /// sequence.
560 578
    Random(const Random& other) {
561 579
      core.copyState(other.core);
562 580
    }
563 581

	
564 582
    /// \brief Assign operator
565 583
    ///
566 584
    /// Assign operator. The generated sequence will be identical to
567 585
    /// the other sequence. It can be used to save the current state
568 586
    /// of the generator and later use it to generate the same
569 587
    /// sequence.
570 588
    Random& operator=(const Random& other) {
571 589
      if (&other != this) {
572 590
        core.copyState(other.core);
573 591
      }
574 592
      return *this;
575 593
    }
576 594

	
577 595
    /// \brief Seeding random sequence
578 596
    ///
579 597
    /// Seeding the random sequence. The current number type will be
580 598
    /// converted to the architecture word type.
581 599
    template <typename Number>
582 600
    void seed(Number seed) { 
583 601
      _random_bits::Initializer<Number, Word>::init(core, seed);
584 602
    }
585 603

	
586 604
    /// \brief Seeding random sequence
587 605
    ///
588 606
    /// Seeding the random sequence. The given range should contain
589 607
    /// any number type and the numbers will be converted to the
590 608
    /// architecture word type.
591 609
    template <typename Iterator>
592 610
    void seed(Iterator begin, Iterator end) { 
593 611
      typedef typename std::iterator_traits<Iterator>::value_type Number;
594 612
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
595 613
    }
596 614

	
615
    /// \brief Seeding from file or from process id and time
616
    ///
617
    /// By default, this function calls the \c seedFromFile() member
618
    /// function with the <tt>/dev/urandom</tt> file. If it does not success,
619
    /// it uses the \c seedFromTime().
620
    /// \return Currently always true.
621
    bool seed() {
622
#ifndef WIN32
623
      if (seedFromFile("/dev/urandom", 0)) return true;
624
#endif
625
      if (seedFromTime()) return true;
626
      return false;
627
    }
628
    
629
    /// \brief Seeding from file
630
    ///
631
    /// Seeding the random sequence from file. The linux kernel has two
632
    /// devices, <tt>/dev/random</tt> and <tt>/dev/urandom</tt> which
633
    /// could give good seed values for pseudo random generators (The
634
    /// difference between two devices is that the <tt>random</tt> may
635
    /// block the reading operation while the kernel can give good
636
    /// source of randomness, while the <tt>urandom</tt> does not
637
    /// block the input, but it could give back bytes with worse
638
    /// entropy).
639
    /// \param file The source file
640
    /// \param offset The offset, from the file read.
641
    /// \return True when the seeding successes.
642
#ifndef WIN32
643
    bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0) 
644
#else
645
    bool seedFromFile(const std::string& file = "", int offset = 0) 
646
#endif
647
    {
648
      std::ifstream rs(file.c_str());
649
      const int size = 4;
650
      Word buf[size];
651
      if (offset != 0 && !rs.seekg(offset)) return false;
652
      if (!rs.read(reinterpret_cast<char*>(buf), sizeof(buf))) return false;
653
      seed(buf, buf + size);
654
      return true;
655
    }
656

	
657
    /// \brief Seding from process id and time
658
    ///
659
    /// Seding from process id and time. This function uses the
660
    /// current process id and the current time for initialize the
661
    /// random sequence.
662
    /// \return Currently always true.
663
    bool seedFromTime() { 	
664
#ifndef WIN32
665
      timeval tv;
666
      gettimeofday(&tv, 0);
667
      seed(getpid() + tv.tv_sec + tv.tv_usec);
668
#else
669
      FILETIME time;
670
      GetSystemTimeAsFileTime(&time);
671
      seed(GetCurrentProcessId() + time.dwHighDateTime + time.dwLowDateTime);
672
#endif
673
      return true;
674
    }
675

	
676
    /// @}
677

	
678
    ///\name Uniform distributions
679
    ///
680
    /// @{
681

	
597 682
    /// \brief Returns a random real number from the range [0, 1)
598 683
    ///
599 684
    /// It returns a random real number from the range [0, 1). The
600 685
    /// default Number type is \c double.
601 686
    template <typename Number>
602 687
    Number real() {
603 688
      return _random_bits::RealConversion<Number, Word>::convert(core);
604 689
    }
605 690

	
606 691
    double real() {
607 692
      return real<double>();
608 693
    }
609 694

	
610 695
    /// \brief Returns a random real number the range [0, b)
611 696
    ///
612 697
    /// It returns a random real number from the range [0, b).
613 698
    template <typename Number>
614 699
    Number real(Number b) { 
615 700
      return real<Number>() * b; 
616 701
    }
617 702

	
618 703
    /// \brief Returns a random real number from the range [a, b)
619 704
    ///
620 705
    /// It returns a random real number from the range [a, b).
621 706
    template <typename Number>
622 707
    Number real(Number a, Number b) { 
623 708
      return real<Number>() * (b - a) + a; 
624 709
    }
625 710

	
711
    /// @}
712

	
713
    ///\name Uniform distributions
714
    ///
715
    /// @{
716

	
626 717
    /// \brief Returns a random real number from the range [0, 1)
627 718
    ///
628 719
    /// It returns a random double from the range [0, 1).
629 720
    double operator()() {
630 721
      return real<double>();
631 722
    }
632 723

	
633 724
    /// \brief Returns a random real number from the range [0, b)
634 725
    ///
635 726
    /// It returns a random real number from the range [0, b).
636 727
    template <typename Number>
637 728
    Number operator()(Number b) { 
638 729
      return real<Number>() * b; 
639 730
    }
640 731

	
641 732
    /// \brief Returns a random real number from the range [a, b)
642 733
    ///
643 734
    /// It returns a random real number from the range [a, b).
644 735
    template <typename Number>
645 736
    Number operator()(Number a, Number b) { 
646 737
      return real<Number>() * (b - a) + a; 
647 738
    }
648 739

	
649 740
    /// \brief Returns a random integer from a range
650 741
    ///
651 742
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
652 743
    template <typename Number>
653 744
    Number integer(Number b) {
654 745
      return _random_bits::Mapping<Number, Word>::map(core, b);
655 746
    }
656 747

	
657 748
    /// \brief Returns a random integer from a range
658 749
    ///
659 750
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
660 751
    template <typename Number>
661 752
    Number integer(Number a, Number b) {
662 753
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
663 754
    }
664 755

	
665 756
    /// \brief Returns a random integer from a range
666 757
    ///
667 758
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
668 759
    template <typename Number>
669 760
    Number operator[](Number b) {
670 761
      return _random_bits::Mapping<Number, Word>::map(core, b);
671 762
    }
672 763

	
673 764
    /// \brief Returns a random non-negative integer
674 765
    ///
675 766
    /// It returns a random non-negative integer uniformly from the
676 767
    /// whole range of the current \c Number type. The default result
677 768
    /// type of this function is <tt>unsigned int</tt>.
678 769
    template <typename Number>
679 770
    Number uinteger() {
680 771
      return _random_bits::IntConversion<Number, Word>::convert(core);
681 772
    }
682 773

	
774
    /// @}
775

	
683 776
    unsigned int uinteger() {
684 777
      return uinteger<unsigned int>();
685 778
    }
686 779

	
687 780
    /// \brief Returns a random integer
688 781
    ///
689 782
    /// It returns a random integer uniformly from the whole range of
690 783
    /// the current \c Number type. The default result type of this
691 784
    /// function is \c int.
692 785
    template <typename Number>
693 786
    Number integer() {
694 787
      static const int nb = std::numeric_limits<Number>::digits + 
695 788
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
696 789
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
697 790
    }
698 791

	
699 792
    int integer() {
700 793
      return integer<int>();
701 794
    }
702 795
    
703 796
    /// \brief Returns a random bool
704 797
    ///
705 798
    /// It returns a random bool. The generator holds a buffer for
706 799
    /// random bits. Every time when it become empty the generator makes
707 800
    /// a new random word and fill the buffer up.
708 801
    bool boolean() {
709 802
      return bool_producer.convert(core);
710 803
    }
711 804

	
805
    /// @}
806

	
712 807
    ///\name Non-uniform distributions
713 808
    ///
714 809
    
715 810
    ///@{
716 811
    
717 812
    /// \brief Returns a random bool
718 813
    ///
719 814
    /// It returns a random bool with given probability of true result.
720 815
    bool boolean(double p) {
721 816
      return operator()() < p;
722 817
    }
723 818

	
724 819
    /// Standard Gauss distribution
725 820

	
726 821
    /// Standard Gauss distribution.
727 822
    /// \note The Cartesian form of the Box-Muller
728 823
    /// transformation is used to generate a random normal distribution.
729 824
    /// \todo Consider using the "ziggurat" method instead.
730 825
    double gauss() 
731 826
    {
732 827
      double V1,V2,S;
733 828
      do {
734 829
	V1=2*real<double>()-1;
735 830
	V2=2*real<double>()-1;
736 831
	S=V1*V1+V2*V2;
737 832
      } while(S>=1);
738 833
      return std::sqrt(-2*std::log(S)/S)*V1;
739 834
    }
740 835
    /// Gauss distribution with given mean and standard deviation
741 836

	
742 837
    /// Gauss distribution with given mean and standard deviation.
743 838
    /// \sa gauss()
744 839
    double gauss(double mean,double std_dev)
745 840
    {
746 841
      return gauss()*std_dev+mean;
747 842
    }
748 843

	
749 844
    /// Exponential distribution with given mean
750 845

	
751 846
    /// This function generates an exponential distribution random number
752 847
    /// with mean <tt>1/lambda</tt>.
753 848
    ///
754 849
    double exponential(double lambda=1.0)
755 850
    {
756 851
      return -std::log(1.0-real<double>())/lambda;
757 852
    }
758 853

	
759 854
    /// Gamma distribution with given integer shape
760 855

	
761 856
    /// This function generates a gamma distribution random number.
762 857
    /// 
763 858
    ///\param k shape parameter (<tt>k>0</tt> integer)
764 859
    double gamma(int k) 
765 860
    {
766 861
      double s = 0;
767 862
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
768 863
      return s;
769 864
    }
770 865
    
771 866
    /// Gamma distribution with given shape and scale parameter
772 867

	
773 868
    /// This function generates a gamma distribution random number.
774 869
    /// 
775 870
    ///\param k shape parameter (<tt>k>0</tt>)
776 871
    ///\param theta scale parameter
777 872
    ///
778 873
    double gamma(double k,double theta=1.0)
779 874
    {
780 875
      double xi,nu;
781 876
      const double delta = k-std::floor(k);
782 877
      const double v0=E/(E-delta);
783 878
      do {
784 879
	double V0=1.0-real<double>();
785 880
	double V1=1.0-real<double>();
786 881
	double V2=1.0-real<double>();
787 882
	if(V2<=v0) 
788 883
	  {
789 884
	    xi=std::pow(V1,1.0/delta);
790 885
	    nu=V0*std::pow(xi,delta-1.0);
791 886
	  }
792 887
	else 
793 888
	  {
794 889
	    xi=1.0-std::log(V1);
795 890
	    nu=V0*std::exp(-xi);
796 891
	  }
797 892
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
798 893
      return theta*(xi+gamma(int(std::floor(k))));
799 894
    }
800 895
    
801 896
    /// Weibull distribution
802 897

	
803 898
    /// This function generates a Weibull distribution random number.
804 899
    /// 
805 900
    ///\param k shape parameter (<tt>k>0</tt>)
806 901
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
807 902
    ///
808 903
    double weibull(double k,double lambda)
809 904
    {
810 905
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
811 906
    }  
812 907
      
813 908
    /// Pareto distribution
814 909

	
815 910
    /// This function generates a Pareto distribution random number.
816 911
    /// 
817 912
    ///\param k shape parameter (<tt>k>0</tt>)
818 913
    ///\param x_min location parameter (<tt>x_min>0</tt>)
819 914
    ///
820 915
    double pareto(double k,double x_min)
821 916
    {
822 917
      return exponential(gamma(k,1.0/x_min))+x_min;
823 918
    }  
824 919
      
825 920
    /// Poisson distribution
826 921

	
827 922
    /// This function generates a Poisson distribution random number with
828 923
    /// parameter \c lambda.
829 924
    /// 
830 925
    /// The probability mass function of this distribusion is
831 926
    /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
832 927
    /// \note The algorithm is taken from the book of Donald E. Knuth titled
833 928
    /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
834 929
    /// return value.
835 930
    
836 931
    int poisson(double lambda)
837 932
    {
838 933
      const double l = std::exp(-lambda);
839 934
      int k=0;
840 935
      double p = 1.0;
841 936
      do {
842 937
	k++;
843 938
	p*=real<double>();
844 939
      } while (p>=l);
845 940
      return k-1;
846 941
    }  
847 942
      
848 943
    ///@}
849 944
    
850 945
    ///\name Two dimensional distributions
851 946
    ///
852 947

	
853 948
    ///@{
854 949
    
855 950
    /// Uniform distribution on the full unit circle
856 951

	
857 952
    /// Uniform distribution on the full unit circle.
858 953
    ///
859 954
    dim2::Point<double> disc() 
860 955
    {
861 956
      double V1,V2;
862 957
      do {
863 958
	V1=2*real<double>()-1;
864 959
	V2=2*real<double>()-1;
865 960
	
866 961
      } while(V1*V1+V2*V2>=1);
867 962
      return dim2::Point<double>(V1,V2);
868 963
    }
869 964
    /// A kind of two dimensional Gauss distribution
870 965

	
871 966
    /// This function provides a turning symmetric two-dimensional distribution.
872 967
    /// Both coordinates are of standard normal distribution, but they are not
873 968
    /// independent.
874 969
    ///
875 970
    /// \note The coordinates are the two random variables provided by
876 971
    /// the Box-Muller method.
877 972
    dim2::Point<double> gauss2()
878 973
    {
879 974
      double V1,V2,S;
880 975
      do {
881 976
	V1=2*real<double>()-1;
882 977
	V2=2*real<double>()-1;
883 978
	S=V1*V1+V2*V2;
884 979
      } while(S>=1);
885 980
      double W=std::sqrt(-2*std::log(S)/S);
886 981
      return dim2::Point<double>(W*V1,W*V2);
887 982
    }
888 983
    /// A kind of two dimensional exponential distribution
889 984

	
890 985
    /// This function provides a turning symmetric two-dimensional distribution.
891 986
    /// The x-coordinate is of conditionally exponential distribution
892 987
    /// with the condition that x is positive and y=0. If x is negative and 
893 988
    /// y=0 then, -x is of exponential distribution. The same is true for the
894 989
    /// y-coordinate.
895 990
    dim2::Point<double> exponential2() 
896 991
    {
897 992
      double V1,V2,S;
898 993
      do {
899 994
	V1=2*real<double>()-1;
900 995
	V2=2*real<double>()-1;
901 996
	S=V1*V1+V2*V2;
902 997
      } while(S>=1);
903 998
      double W=-std::log(S)/S;
904 999
      return dim2::Point<double>(W*V1,W*V2);
905 1000
    }
906 1001

	
907 1002
    ///@}    
908 1003
  };
909 1004

	
910 1005

	
911 1006
  extern Random rnd;
912 1007

	
913 1008
}
914 1009

	
915 1010
#endif
0 comments (0 inline)