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