Removed stuff from InfAlg, moved it to individual inference algorithms
[libdai.git] / src / util.cpp
1 /* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
2 Radboud University Nijmegen, The Netherlands
3
4 This file is part of libDAI.
5
6 libDAI is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 libDAI is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with libDAI; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21
22 #include <dai/util.h>
23 #include <boost/random/linear_congruential.hpp>
24 #include <boost/random/uniform_real.hpp>
25 #include <boost/random/normal_distribution.hpp>
26 #include <boost/random/variate_generator.hpp>
27
28 #ifdef WINDOWS
29 #include <windows.h>
30 #else
31 // Assume POSIX compliant system. We need the following for querying the CPU time for this process
32 #include <sys/times.h>
33 #include <sys/param.h>
34 #endif
35
36
37 namespace dai {
38
39
40 // Returns user+system time in seconds
41 double toc() {
42 #ifdef WINDOWS
43 SYSTEMTIME tbuf;
44 GetSystemTime(&tbuf);
45 return( (double)(tbuf.wSecond + (double)tbuf.wMilliseconds / 1000.0) );
46 #else
47 tms tbuf;
48 times(&tbuf);
49 return( (double)(tbuf.tms_utime + tbuf.tms_stime) / HZ );
50 #endif
51 }
52
53
54 // This is a typedef for a random number generator.
55 // Try boost::mt19937 or boost::ecuyer1988 instead of boost::minstd_rand
56 typedef boost::minstd_rand _rnd_gen_type;
57
58 _rnd_gen_type _rnd_gen(42U);
59
60 // Define a uniform random number distribution which produces
61 // values between 0 and 1 (0 inclusive, 1 exclusive).
62 boost::uniform_real<> _uni_dist(0,1);
63 boost::variate_generator<_rnd_gen_type&, boost::uniform_real<> > _uni_rnd(_rnd_gen, _uni_dist);
64
65 // Define a normal distribution with mean 0 and standard deviation 1.
66 boost::normal_distribution<> _normal_dist;
67 boost::variate_generator<_rnd_gen_type&, boost::normal_distribution<> > _normal_rnd(_rnd_gen, _normal_dist);
68
69
70 void rnd_seed( size_t seed ) {
71 _rnd_gen.seed(seed);
72 }
73
74 double rnd_uniform() {
75 return _uni_rnd();
76 }
77
78 double rnd_stdnormal() {
79 return _normal_rnd();
80 }
81
82 // Returns integer in interval [min, max]
83 int rnd_int( int min, int max ) {
84 return (int)floor(_uni_rnd() * (max + 1 - min) + min);
85 }
86
87
88 } // end of namespace dai