[Benjamin Piwowarski] Renamed "foreach" macro into "bforeach" to avoid conflicts...
[libdai.git] / include / dai / util.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4 *
5 * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6 */
7
8
9 /// \file
10 /// \brief Defines general utility functions and adds an abstraction layer for platform-dependent functionality
11
12
13 #ifndef __defined_libdai_util_h
14 #define __defined_libdai_util_h
15
16
17 #include <string>
18 #include <vector>
19 #include <set>
20 #include <map>
21 #include <iostream>
22 #include <boost/foreach.hpp>
23 #include <boost/functional/hash.hpp>
24 #include <boost/lexical_cast.hpp>
25 #include <algorithm>
26 #include <cerrno>
27 #include <gmpxx.h>
28
29 #include <dai/exceptions.h>
30
31
32 #if defined(WINDOWS)
33 #include <boost/tr1/unordered_map.hpp> // only present in boost 1.37 and higher
34 #elif defined(CYGWIN)
35 #include <boost/tr1/unordered_map.hpp> // only present in boost 1.37 and higher
36 #elif defined(MACOSX)
37 #include <boost/tr1/unordered_map.hpp> // only present in boost 1.37 and higher
38 #else
39 #include <tr1/unordered_map> // only present in modern GCC distributions
40 #endif
41
42
43 /// An alias to the BOOST_FOREACH macro from the boost::bforeach library
44 #define bforeach BOOST_FOREACH
45
46 #ifdef DAI_DEBUG
47 /// \brief "Print variable". Prints the text of an expression, followed by its value (only if DAI_DEBUG is defined)
48 /**
49 * Useful debugging macro to see what your code is doing.
50 * Example: \code DAI_PV(3+4) \endcode
51 * Output: \code 3+4= 7 \endcode
52 */
53 #define DAI_PV(x) do {std::cerr << #x "= " << (x) << std::endl;} while(0)
54 /// "Debugging message": Prints a message (only if DAI_DEBUG is defined)
55 #define DAI_DMSG(str) do {std::cerr << str << std::endl;} while(0)
56 #else
57 #define DAI_PV(x) do {} while(0)
58 #define DAI_DMSG(str) do {} while(0)
59 #endif
60
61 /// Macro to write message \a stmt to \c std::cerr if \a props.verbose >= \a n
62 #define DAI_IFVERB(n, stmt) if(props.verbose>=n) { std::cerr << stmt; }
63
64
65 #ifdef WINDOWS
66 /// Returns inverse hyperbolic tangent of argument
67 double atanh( double x );
68
69 /// Returns log(1+x)
70 double log1p( double x );
71
72 /// Define INFINITY
73 #define INFINITY (std::numeric_limits<Real>::infinity())
74 #endif
75
76
77 namespace dai {
78
79
80 /// Real number (alias for \c double, which could be changed to <tt>long double</tt> if necessary)
81 typedef double Real;
82
83 /// Arbitrary precision integer number
84 typedef mpz_class BigInt;
85
86 /// Safe down-cast of big integer to size_t
87 inline size_t BigInt_size_t( const BigInt &N ) {
88 DAI_ASSERT( N <= std::numeric_limits<std::size_t>::max() );
89 return N.get_ui();
90 }
91
92 /// Returns true if argument is NAN (Not A Number)
93 bool isnan( Real x );
94
95 /// Returns logarithm of \a x
96 inline Real log( Real x ) {
97 return std::log(x);
98 }
99
100 /// Returns logarithm of \a x, or 0 if \a x == 0
101 inline Real log0( Real x ) {
102 return x ? std::log(x) : 0;
103 }
104
105 /// Returns exponent of \a x
106 inline Real exp( Real x ) {
107 return std::exp(x);
108 }
109
110 /// Returns \a to the power \a y
111 inline Real pow( Real x, Real y ) {
112 errno = 0;
113 Real result = std::pow(x, y);
114 DAI_DEBASSERT( errno == 0 );
115 return result;
116 }
117
118
119 /// hash_map is an alias for \c std::tr1::unordered_map.
120 /** We use the (experimental) TR1 unordered_map implementation included in modern GCC distributions or in boost versions 1.37 and higher.
121 */
122 template <typename T, typename U, typename H = boost::hash<T> >
123 class hash_map : public std::tr1::unordered_map<T,U,H> {};
124
125
126 /// Returns wall clock time in seconds
127 double toc();
128
129
130 /// Returns absolute value of \a t
131 template<class T>
132 inline T abs( const T &t ) {
133 return (t < 0) ? (-t) : t;
134 }
135
136
137 /// Sets the random seed
138 void rnd_seed( size_t seed );
139
140 /// Returns a real number, distributed uniformly on [0,1)
141 Real rnd_uniform();
142
143 /// Returns a real number from a standard-normal distribution
144 Real rnd_stdnormal();
145
146 /// Returns a random integer in interval [\a min, \a max]
147 int rnd_int( int min, int max );
148
149 /// Returns a random integer in the half-open interval [0, \a n)
150 inline int rnd( int n ) {
151 return rnd_int( 0, n-1 );
152 }
153
154
155 /// Converts a variable of type \a T to a \c std::string by using a \c boost::lexical_cast
156 template<class T>
157 std::string toString( const T& x ) {
158 return boost::lexical_cast<std::string>(x);
159 }
160
161
162 /// Converts a variable of type std::string to \a T by using a \c boost::lexical_cast
163 template<class T>
164 T fromString( const std::string& x ) {
165 return boost::lexical_cast<T>(x);
166 }
167
168
169 /// Writes a \c std::vector<> to a \c std::ostream
170 template<class T>
171 std::ostream& operator << (std::ostream& os, const std::vector<T> & x) {
172 os << "(";
173 for( typename std::vector<T>::const_iterator it = x.begin(); it != x.end(); it++ )
174 os << (it != x.begin() ? ", " : "") << *it;
175 os << ")";
176 return os;
177 }
178
179 /// Writes a \c std::set<> to a \c std::ostream
180 template<class T>
181 std::ostream& operator << (std::ostream& os, const std::set<T> & x) {
182 os << "{";
183 for( typename std::set<T>::const_iterator it = x.begin(); it != x.end(); it++ )
184 os << (it != x.begin() ? ", " : "") << *it;
185 os << "}";
186 return os;
187 }
188
189 /// Writes a \c std::map<> to a \c std::ostream
190 template<class T1, class T2>
191 std::ostream& operator << (std::ostream& os, const std::map<T1,T2> & x) {
192 os << "{";
193 for( typename std::map<T1,T2>::const_iterator it = x.begin(); it != x.end(); it++ )
194 os << (it != x.begin() ? ", " : "") << it->first << "->" << it->second;
195 os << "}";
196 return os;
197 }
198
199 /// Writes a \c std::pair<> to a \c std::ostream
200 template<class T1, class T2>
201 std::ostream& operator << (std::ostream& os, const std::pair<T1,T2> & x) {
202 os << "(" << x.first << ", " << x.second << ")";
203 return os;
204 }
205
206 /// Concatenates two vectors
207 template<class T>
208 std::vector<T> concat( const std::vector<T>& u, const std::vector<T>& v ) {
209 std::vector<T> w;
210 w.reserve( u.size() + v.size() );
211 for( size_t i = 0; i < u.size(); i++ )
212 w.push_back( u[i] );
213 for( size_t i = 0; i < v.size(); i++ )
214 w.push_back( v[i] );
215 return w;
216 }
217
218 /// Split a string into tokens delimited by one of the characters in \a delim
219 /** \param s the string to be split into tokens
220 * \param singleDelim if \c true, any single delimiter forms a boundary between two tokens;
221 * if \c false, a maximal group of consecutive delimiters forms a boundary between two tokens
222 * \param delim delimiter characters
223 */
224 std::vector<std::string> tokenizeString( const std::string& s, bool singleDelim, const std::string& delim="\t\n" );
225
226
227 /// Enumerates different ways of normalizing a probability measure.
228 /**
229 * - NORMPROB means that the sum of all entries should be 1;
230 * - NORMLINF means that the maximum absolute value of all entries should be 1.
231 */
232 typedef enum { NORMPROB, NORMLINF } ProbNormType;
233
234 /// Enumerates different distance measures between probability measures.
235 /**
236 * - DISTL1 is the \f$\ell_1\f$ distance (sum of absolute values of pointwise difference);
237 * - DISTLINF is the \f$\ell_\infty\f$ distance (maximum absolute value of pointwise difference);
238 * - DISTTV is the total variation distance (half of the \f$\ell_1\f$ distance);
239 * - DISTKL is the Kullback-Leibler distance (\f$\sum_i p_i (\log p_i - \log q_i)\f$).
240 * - DISTHEL is the Hellinger distance (\f$\frac{1}{2}\sum_i (\sqrt{p_i}-\sqrt{q_i})^2\f$).
241 */
242 typedef enum { DISTL1, DISTLINF, DISTTV, DISTKL, DISTHEL } ProbDistType;
243
244
245 } // end of namespace dai
246
247
248 #endif