Introduced DAI_DEBASSERT macro to abbreviate a common pattern
[libdai.git] / include / dai / prob.h
1 /* Copyright (C) 2006-2008 Joris Mooij [joris dot mooij at tuebingen dot mpg dot de]
2 Radboud University Nijmegen, The Netherlands /
3 Max Planck Institute for Biological Cybernetics, Germany
4
5 This file is part of libDAI.
6
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22
23 /// \file
24 /// \brief Defines TProb<T> and Prob classes
25 /// \todo Rename to Vector<T>
26
27
28 #ifndef __defined_libdai_prob_h
29 #define __defined_libdai_prob_h
30
31
32 #include <cmath>
33 #include <vector>
34 #include <ostream>
35 #include <cassert>
36 #include <algorithm>
37 #include <numeric>
38 #include <functional>
39 #include <dai/util.h>
40 #include <dai/exceptions.h>
41
42
43 namespace dai {
44
45
46 /// Represents a vector with entries of type \a T.
47 /** A TProb<T> is a std::vector<T> with an interface designed for dealing with probability mass functions.
48 * It is mainly used for representing measures on a finite outcome space, e.g., the probability
49 * distribution of a discrete random variable.
50 * \tparam T Should be a scalar that is castable from and to double and should support elementary arithmetic operations.
51 */
52 template <typename T> class TProb {
53 private:
54 /// The vector
55 std::vector<T> _p;
56
57 public:
58 /// Iterator over entries
59 typedef typename std::vector<T>::iterator iterator;
60 /// Const iterator over entries
61 typedef typename std::vector<T>::const_iterator const_iterator;
62
63 /// Enumerates different ways of normalizing a probability measure.
64 /**
65 * - NORMPROB means that the sum of all entries should be 1;
66 * - NORMLINF means that the maximum absolute value of all entries should be 1.
67 */
68 typedef enum { NORMPROB, NORMLINF } NormType;
69 /// Enumerates different distance measures between probability measures.
70 /**
71 * - DISTL1 is the L-1 distance (sum of absolute values of pointwise difference);
72 * - DISTLINF is the L-inf distance (maximum absolute value of pointwise difference);
73 * - DISTTV is the Total Variation distance;
74 * - DISTKL is the Kullback-Leibler distance.
75 */
76 typedef enum { DISTL1, DISTLINF, DISTTV, DISTKL } DistType;
77
78 /// Default constructor
79 TProb() : _p() {}
80
81 /// Construct uniform distribution over n outcomes, i.e., a vector of length n with each entry set to 1/n
82 explicit TProb( size_t n ) : _p(std::vector<T>(n, 1.0 / n)) {}
83
84 /// Construct vector of length n with each entry set to p
85 explicit TProb( size_t n, Real p ) : _p(n, (T)p) {}
86
87 /// Construct vector from a range
88 /** \tparam Iterator Iterates over instances that can be cast to T.
89 * \param begin Points to first instance to be added.
90 * \param end Points just beyond last instance to be added.
91 * \param sizeHint For efficiency, the number of entries can be speficied by sizeHint.
92 */
93 template <typename Iterator>
94 TProb( Iterator begin, Iterator end, size_t sizeHint=0 ) : _p() {
95 _p.reserve( sizeHint );
96 _p.insert( _p.begin(), begin, end );
97 }
98
99 /// Returns a const reference to the vector
100 const std::vector<T> & p() const { return _p; }
101
102 /// Returns a reference to the vector
103 std::vector<T> & p() { return _p; }
104
105 /// Returns a copy of the i'th entry
106 T operator[]( size_t i ) const {
107 #ifdef DAI_DEBUG
108 return _p.at(i);
109 #else
110 return _p[i];
111 #endif
112 }
113
114 /// Returns reference to the i'th entry
115 T& operator[]( size_t i ) { return _p[i]; }
116
117 /// Returns iterator pointing to first entry
118 iterator begin() { return _p.begin(); }
119
120 /// Returns const iterator pointing to first entry
121 const_iterator begin() const { return _p.begin(); }
122
123 /// Returns iterator pointing beyond last entry
124 iterator end() { return _p.end(); }
125
126 /// Returns const iterator pointing beyond last entry
127 const_iterator end() const { return _p.end(); }
128
129 /// Sets all entries to x
130 TProb<T> & fill(T x) {
131 std::fill( _p.begin(), _p.end(), x );
132 return *this;
133 }
134
135 /// Draws all entries i.i.d. from a uniform distribution on [0,1)
136 TProb<T> & randomize() {
137 std::generate(_p.begin(), _p.end(), rnd_uniform);
138 return *this;
139 }
140
141 /// Returns length of the vector, i.e., the number of entries
142 size_t size() const {
143 return _p.size();
144 }
145
146 /// Sets entries that are smaller than epsilon to 0
147 TProb<T>& makeZero( Real epsilon ) {
148 for( size_t i = 0; i < size(); i++ )
149 if( fabs(_p[i]) < epsilon )
150 _p[i] = 0;
151 return *this;
152 }
153
154 /// Set all entries to 1.0/size()
155 TProb<T>& setUniform () {
156 fill(1.0/size());
157 return *this;
158 }
159
160 /// Sets entries that are smaller than epsilon to epsilon
161 TProb<T>& makePositive( Real epsilon ) {
162 for( size_t i = 0; i < size(); i++ )
163 if( (0 < (Real)_p[i]) && ((Real)_p[i] < epsilon) )
164 _p[i] = epsilon;
165 return *this;
166 }
167
168 /// Multiplies each entry with scalar x
169 TProb<T>& operator*= (T x) {
170 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::multiplies<T>(), x) );
171 return *this;
172 }
173
174 /// Returns product of *this with scalar x
175 TProb<T> operator* (T x) const {
176 TProb<T> prod( *this );
177 prod *= x;
178 return prod;
179 }
180
181 /// Divides each entry by scalar x
182 TProb<T>& operator/= (T x) {
183 DAI_DEBASSERT( x != 0.0 );
184 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::divides<T>(), x ) );
185 return *this;
186 }
187
188 /// Returns quotient of *this and scalar x
189 TProb<T> operator/ (T x) const {
190 TProb<T> quot( *this );
191 quot /= x;
192 return quot;
193 }
194
195 /// Adds scalar x to each entry
196 TProb<T>& operator+= (T x) {
197 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::plus<T>(), x ) );
198 return *this;
199 }
200
201 /// Returns sum of *this and scalar x
202 TProb<T> operator+ (T x) const {
203 TProb<T> sum( *this );
204 sum += x;
205 return sum;
206 }
207
208 /// Subtracts scalar x from each entry
209 TProb<T>& operator-= (T x) {
210 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::minus<T>(), x ) );
211 return *this;
212 }
213
214 /// Returns difference of *this and scalar x
215 TProb<T> operator- (T x) const {
216 TProb<T> diff( *this );
217 diff -= x;
218 return diff;
219 }
220
221 /// Lexicographical comparison (sizes should be identical)
222 bool operator<= (const TProb<T> & q) const {
223 DAI_DEBASSERT( size() == q.size() );
224 for( size_t i = 0; i < size(); i++ )
225 if( !(_p[i] <= q[i]) )
226 return false;
227 return true;
228 }
229
230 /// Pointwise multiplication with q (sizes should be identical)
231 TProb<T>& operator*= (const TProb<T> & q) {
232 DAI_DEBASSERT( size() == q.size() );
233 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::multiplies<T>() );
234 return *this;
235 }
236
237 /// Return product of *this with q (sizes should be identical)
238 TProb<T> operator* (const TProb<T> & q) const {
239 DAI_DEBASSERT( size() == q.size() );
240 TProb<T> prod( *this );
241 prod *= q;
242 return prod;
243 }
244
245 /// Pointwise addition with q (sizes should be identical)
246 TProb<T>& operator+= (const TProb<T> & q) {
247 DAI_DEBASSERT( size() == q.size() );
248 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::plus<T>() );
249 return *this;
250 }
251
252 /// Returns sum of *this and q (sizes should be identical)
253 TProb<T> operator+ (const TProb<T> & q) const {
254 DAI_DEBASSERT( size() == q.size() );
255 TProb<T> sum( *this );
256 sum += q;
257 return sum;
258 }
259
260 /// Pointwise subtraction of q (sizes should be identical)
261 TProb<T>& operator-= (const TProb<T> & q) {
262 DAI_DEBASSERT( size() == q.size() );
263 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::minus<T>() );
264 DAI_DEBASSERT( size() == q.size() );
265 TProb<T> diff( *this );
266 diff -= q;
267 return diff;
268 }
269
270 /// Pointwise division by q, where division by 0 yields 0 (sizes should be identical)
271 TProb<T>& operator/= (const TProb<T> & q) {
272 DAI_DEBASSERT( size() == q.size() );
273 for( size_t i = 0; i < size(); i++ ) {
274 if( q[i] == 0.0 )
275 _p[i] = 0.0;
276 else
277 _p[i] /= q[i];
278 }
279 return *this;
280 }
281
282 /// Pointwise division by q, where division by 0 yields +Inf (sizes should be identical)
283 TProb<T>& divide (const TProb<T> & q) {
284 DAI_DEBASSERT( size() == q.size() );
285 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::divides<T>() );
286 return *this;
287 }
288
289 /// Returns quotient of *this with q (sizes should be identical)
290 TProb<T> operator/ (const TProb<T> & q) const {
291 DAI_DEBASSERT( size() == q.size() );
292 TProb<T> quot( *this );
293 quot /= q;
294 return quot;
295 }
296
297 /// Returns pointwise inverse
298 /** If zero==true; uses 1/0==0, otherwise 1/0==Inf.
299 */
300 TProb<T> inverse(bool zero=true) const {
301 TProb<T> inv;
302 inv._p.reserve( size() );
303 if( zero )
304 for( size_t i = 0; i < size(); i++ )
305 inv._p.push_back( _p[i] == 0.0 ? 0.0 : 1.0 / _p[i] );
306 else
307 for( size_t i = 0; i < size(); i++ )
308 inv._p.push_back( 1.0 / _p[i] );
309 return inv;
310 }
311
312 /// Raises entries to the power a
313 TProb<T>& operator^= (Real a) {
314 if( a != 1.0 )
315 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::ptr_fun<T, Real, T>(std::pow), a) );
316 return *this;
317 }
318
319 /// Returns *this raised to the power a
320 TProb<T> operator^ (Real a) const {
321 TProb<T> power(*this);
322 power ^= a;
323 return power;
324 }
325
326 /// Returns pointwise signum
327 TProb<T> sgn() const {
328 TProb<T> x;
329 x._p.reserve( size() );
330 for( size_t i = 0; i < size(); i++ ) {
331 T s = 0;
332 if( _p[i] > 0 )
333 s = 1;
334 else if( _p[i] < 0 )
335 s = -1;
336 x._p.push_back( s );
337 }
338 return x;
339 }
340
341 /// Returns pointwise absolute value
342 TProb<T> abs() const {
343 TProb<T> x;
344 x._p.reserve( size() );
345 for( size_t i = 0; i < size(); i++ )
346 x._p.push_back( _p[i] < 0 ? (-_p[i]) : _p[i] );
347 return x;
348 }
349
350 /// Applies exp pointwise
351 const TProb<T>& takeExp() {
352 std::transform( _p.begin(), _p.end(), _p.begin(), std::ptr_fun<T, T>(std::exp) );
353 return *this;
354 }
355
356 /// Applies log pointwise
357 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
358 */
359 const TProb<T>& takeLog(bool zero=false) {
360 if( zero ) {
361 for( size_t i = 0; i < size(); i++ )
362 _p[i] = ( (_p[i] == 0.0) ? 0.0 : std::log( _p[i] ) );
363 } else
364 std::transform( _p.begin(), _p.end(), _p.begin(), std::ptr_fun<T, T>(std::log) );
365 return *this;
366 }
367
368 /// Returns pointwise exp
369 TProb<T> exp() const {
370 TProb<T> e(*this);
371 e.takeExp();
372 return e;
373 }
374
375 /// Returns pointwise log
376 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
377 */
378 TProb<T> log(bool zero=false) const {
379 TProb<T> l(*this);
380 l.takeLog(zero);
381 return l;
382 }
383
384 /// Returns sum of all entries
385 T sum() const {
386 T Z = std::accumulate( _p.begin(), _p.end(), (T)0 );
387 return Z;
388 }
389
390 /// Return sum of absolute value of all entries
391 T sumAbs() const {
392 T s = 0;
393 for( size_t i = 0; i < size(); i++ )
394 s += fabs( (Real) _p[i] );
395 return s;
396 }
397
398 /// Returns maximum absolute value of all entries
399 T maxAbs() const {
400 T Z = 0;
401 for( size_t i = 0; i < size(); i++ ) {
402 Real mag = fabs( (Real) _p[i] );
403 if( mag > Z )
404 Z = mag;
405 }
406 return Z;
407 }
408
409 /// Returns maximum value of all entries
410 T max() const {
411 T Z = *std::max_element( _p.begin(), _p.end() );
412 return Z;
413 }
414
415 /// Returns minimum value of all entries
416 T min() const {
417 T Z = *std::min_element( _p.begin(), _p.end() );
418 return Z;
419 }
420
421 /// Returns {arg,}maximum value
422 std::pair<size_t,T> argmax() const {
423 T max = _p[0];
424 size_t arg = 0;
425 for( size_t i = 1; i < size(); i++ ) {
426 if( _p[i] > max ) {
427 max = _p[i];
428 arg = i;
429 }
430 }
431 return std::make_pair(arg,max);
432 }
433
434 /// Normalizes vector using the specified norm
435 T normalize( NormType norm=NORMPROB ) {
436 T Z = 0.0;
437 if( norm == NORMPROB )
438 Z = sum();
439 else if( norm == NORMLINF )
440 Z = maxAbs();
441 if( Z == 0.0 )
442 DAI_THROW(NOT_NORMALIZABLE);
443 else
444 *this /= Z;
445 return Z;
446 }
447
448 /// Returns normalized copy of *this, using the specified norm
449 TProb<T> normalized( NormType norm = NORMPROB ) const {
450 TProb<T> result(*this);
451 result.normalize( norm );
452 return result;
453 }
454
455 /// Returns true if one or more entries are NaN
456 bool hasNaNs() const {
457 bool foundnan = false;
458 for( typename std::vector<T>::const_iterator x = _p.begin(); x != _p.end(); x++ )
459 if( isnan( *x ) ) {
460 foundnan = true;
461 break;
462 }
463 return foundnan;
464 }
465
466 /// Returns true if one or more entries are negative
467 bool hasNegatives() const {
468 return (std::find_if( _p.begin(), _p.end(), std::bind2nd( std::less<Real>(), 0.0 ) ) != _p.end());
469 }
470
471 /// Returns entropy of *this
472 Real entropy() const {
473 Real S = 0.0;
474 for( size_t i = 0; i < size(); i++ )
475 S -= (_p[i] == 0 ? 0 : _p[i] * std::log(_p[i]));
476 return S;
477 }
478
479 /// Returns a random index, according to the (normalized) distribution described by *this
480 size_t draw() {
481 double x = rnd_uniform() * sum();
482 T s = 0;
483 for( size_t i = 0; i < size(); i++ ) {
484 s += _p[i];
485 if( s > x )
486 return i;
487 }
488 return( size() - 1 );
489 }
490 };
491
492
493 /// Returns distance of p and q (sizes should be identical), measured using distance measure dt
494 /** \relates TProb
495 */
496 template<typename T> Real dist( const TProb<T> &p, const TProb<T> &q, typename TProb<T>::DistType dt ) {
497 DAI_DEBASSERT( p.size() == q.size() );
498 Real result = 0.0;
499 switch( dt ) {
500 case TProb<T>::DISTL1:
501 for( size_t i = 0; i < p.size(); i++ )
502 result += fabs((Real)p[i] - (Real)q[i]);
503 break;
504
505 case TProb<T>::DISTLINF:
506 for( size_t i = 0; i < p.size(); i++ ) {
507 Real z = fabs((Real)p[i] - (Real)q[i]);
508 if( z > result )
509 result = z;
510 }
511 break;
512
513 case TProb<T>::DISTTV:
514 for( size_t i = 0; i < p.size(); i++ )
515 result += fabs((Real)p[i] - (Real)q[i]);
516 result *= 0.5;
517 break;
518
519 case TProb<T>::DISTKL:
520 for( size_t i = 0; i < p.size(); i++ ) {
521 if( p[i] != 0.0 )
522 result += p[i] * (std::log(p[i]) - std::log(q[i]));
523 }
524 }
525 return result;
526 }
527
528
529 /// Writes a TProb<T> to an output stream
530 /** \relates TProb
531 */
532 template<typename T> std::ostream& operator<< (std::ostream& os, const TProb<T>& P) {
533 os << "[";
534 std::copy( P.p().begin(), P.p().end(), std::ostream_iterator<T>(os, " ") );
535 os << "]";
536 return os;
537 }
538
539
540 /// Returns the TProb<T> containing the pointwise minimum of a and b (which should have equal size)
541 /** \relates TProb
542 */
543 template<typename T> TProb<T> min( const TProb<T> &a, const TProb<T> &b ) {
544 assert( a.size() == b.size() );
545 TProb<T> result( a.size() );
546 for( size_t i = 0; i < a.size(); i++ )
547 if( a[i] < b[i] )
548 result[i] = a[i];
549 else
550 result[i] = b[i];
551 return result;
552 }
553
554
555 /// Returns the TProb<T> containing the pointwise maximum of a and b (which should have equal size)
556 /** \relates TProb
557 */
558 template<typename T> TProb<T> max( const TProb<T> &a, const TProb<T> &b ) {
559 assert( a.size() == b.size() );
560 TProb<T> result( a.size() );
561 for( size_t i = 0; i < a.size(); i++ )
562 if( a[i] > b[i] )
563 result[i] = a[i];
564 else
565 result[i] = b[i];
566 return result;
567 }
568
569
570 /// Represents a vector with entries of type Real.
571 typedef TProb<Real> Prob;
572
573
574 } // end of namespace dai
575
576
577 #endif