Merge branch 'joris'
[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 /// Sets entries that are smaller than epsilon to epsilon
155 TProb<T>& makePositive( Real epsilon ) {
156 for( size_t i = 0; i < size(); i++ )
157 if( (0 < (Real)_p[i]) && ((Real)_p[i] < epsilon) )
158 _p[i] = epsilon;
159 return *this;
160 }
161
162 /// Multiplies each entry with scalar x
163 TProb<T>& operator*= (T x) {
164 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::multiplies<T>(), x) );
165 return *this;
166 }
167
168 /// Returns product of *this with scalar x
169 TProb<T> operator* (T x) const {
170 TProb<T> prod( *this );
171 prod *= x;
172 return prod;
173 }
174
175 /// Divides each entry by scalar x
176 TProb<T>& operator/= (T x) {
177 #ifdef DAI_DEBUG
178 assert( x != 0.0 );
179 #endif
180 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::divides<T>(), x ) );
181 return *this;
182 }
183
184 /// Returns quotient of *this and scalar x
185 TProb<T> operator/ (T x) const {
186 TProb<T> quot( *this );
187 quot /= x;
188 return quot;
189 }
190
191 /// Adds scalar x to each entry
192 TProb<T>& operator+= (T x) {
193 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::plus<T>(), x ) );
194 return *this;
195 }
196
197 /// Returns sum of *this and scalar x
198 TProb<T> operator+ (T x) const {
199 TProb<T> sum( *this );
200 sum += x;
201 return sum;
202 }
203
204 /// Subtracts scalar x from each entry
205 TProb<T>& operator-= (T x) {
206 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::minus<T>(), x ) );
207 return *this;
208 }
209
210 /// Returns difference of *this and scalar x
211 TProb<T> operator- (T x) const {
212 TProb<T> diff( *this );
213 diff -= x;
214 return diff;
215 }
216
217 /// Lexicographical comparison (sizes should be identical)
218 bool operator<= (const TProb<T> & q) const {
219 #ifdef DAI_DEBUG
220 assert( size() == q.size() );
221 #endif
222 for( size_t i = 0; i < size(); i++ )
223 if( !(_p[i] <= q[i]) )
224 return false;
225 return true;
226 }
227
228 /// Pointwise multiplication with q (sizes should be identical)
229 TProb<T>& operator*= (const TProb<T> & q) {
230 #ifdef DAI_DEBUG
231 assert( size() == q.size() );
232 #endif
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 #ifdef DAI_DEBUG
240 assert( size() == q.size() );
241 #endif
242 TProb<T> prod( *this );
243 prod *= q;
244 return prod;
245 }
246
247 /// Pointwise addition with q (sizes should be identical)
248 TProb<T>& operator+= (const TProb<T> & q) {
249 #ifdef DAI_DEBUG
250 assert( size() == q.size() );
251 #endif
252 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::plus<T>() );
253 return *this;
254 }
255
256 /// Returns sum of *this and q (sizes should be identical)
257 TProb<T> operator+ (const TProb<T> & q) const {
258 #ifdef DAI_DEBUG
259 assert( size() == q.size() );
260 #endif
261 TProb<T> sum( *this );
262 sum += q;
263 return sum;
264 }
265
266 /// Pointwise subtraction of q (sizes should be identical)
267 TProb<T>& operator-= (const TProb<T> & q) {
268 #ifdef DAI_DEBUG
269 assert( size() == q.size() );
270 #endif
271 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::minus<T>() );
272 return *this;
273 }
274
275 /// Return *this minus q (sizes should be identical)
276 TProb<T> operator- (const TProb<T> & q) const {
277 #ifdef DAI_DEBUG
278 assert( size() == q.size() );
279 #endif
280 TProb<T> diff( *this );
281 diff -= q;
282 return diff;
283 }
284
285 /// Pointwise division by q, where division by 0 yields 0 (sizes should be identical)
286 TProb<T>& operator/= (const TProb<T> & q) {
287 #ifdef DAI_DEBUG
288 assert( size() == q.size() );
289 #endif
290 for( size_t i = 0; i < size(); i++ ) {
291 if( q[i] == 0.0 )
292 _p[i] = 0.0;
293 else
294 _p[i] /= q[i];
295 }
296 return *this;
297 }
298
299 /// Pointwise division by q, where division by 0 yields +Inf (sizes should be identical)
300 TProb<T>& divide (const TProb<T> & q) {
301 #ifdef DAI_DEBUG
302 assert( size() == q.size() );
303 #endif
304 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), std::divides<T>() );
305 return *this;
306 }
307
308 /// Returns quotient of *this with q (sizes should be identical)
309 TProb<T> operator/ (const TProb<T> & q) const {
310 #ifdef DAI_DEBUG
311 assert( size() == q.size() );
312 #endif
313 TProb<T> quot( *this );
314 quot /= q;
315 return quot;
316 }
317
318 /// Returns pointwise inverse
319 /** If zero==true; uses 1/0==0, otherwise 1/0==Inf.
320 */
321 TProb<T> inverse(bool zero=true) const {
322 TProb<T> inv;
323 inv._p.reserve( size() );
324 if( zero )
325 for( size_t i = 0; i < size(); i++ )
326 inv._p.push_back( _p[i] == 0.0 ? 0.0 : 1.0 / _p[i] );
327 else
328 for( size_t i = 0; i < size(); i++ )
329 inv._p.push_back( 1.0 / _p[i] );
330 return inv;
331 }
332
333 /// Raises entries to the power a
334 TProb<T>& operator^= (Real a) {
335 if( a != 1.0 )
336 std::transform( _p.begin(), _p.end(), _p.begin(), std::bind2nd( std::ptr_fun<T, Real, T>(std::pow), a) );
337 return *this;
338 }
339
340 /// Returns *this raised to the power a
341 TProb<T> operator^ (Real a) const {
342 TProb<T> power(*this);
343 power ^= a;
344 return power;
345 }
346
347 /// Returns pointwise signum
348 TProb<T> sgn() const {
349 TProb<T> x;
350 x._p.reserve( size() );
351 for( size_t i = 0; i < size(); i++ ) {
352 T s = 0;
353 if( _p[i] > 0 )
354 s = 1;
355 else if( _p[i] < 0 )
356 s = -1;
357 x._p.push_back( s );
358 }
359 return x;
360 }
361
362 /// Returns pointwise absolute value
363 TProb<T> abs() const {
364 TProb<T> x;
365 x._p.reserve( size() );
366 for( size_t i = 0; i < size(); i++ )
367 x._p.push_back( _p[i] < 0 ? (-p[i]) : p[i] );
368 return x;
369 }
370
371 /// Applies exp pointwise
372 const TProb<T>& takeExp() {
373 std::transform( _p.begin(), _p.end(), _p.begin(), std::ptr_fun<T, T>(std::exp) );
374 return *this;
375 }
376
377 /// Applies log pointwise
378 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
379 */
380 const TProb<T>& takeLog(bool zero=false) {
381 if( zero ) {
382 for( size_t i = 0; i < size(); i++ )
383 _p[i] = ( (_p[i] == 0.0) ? 0.0 : std::log( _p[i] ) );
384 } else
385 std::transform( _p.begin(), _p.end(), _p.begin(), std::ptr_fun<T, T>(std::log) );
386 return *this;
387 }
388
389 /// Returns pointwise exp
390 TProb<T> exp() const {
391 TProb<T> e(*this);
392 e.takeExp();
393 return e;
394 }
395
396 /// Returns pointwise log
397 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
398 */
399 TProb<T> log(bool zero=false) const {
400 TProb<T> l(*this);
401 l.takeLog(zero);
402 return l;
403 }
404
405 /// Returns sum of all entries
406 T totalSum() const {
407 T Z = std::accumulate( _p.begin(), _p.end(), (T)0 );
408 return Z;
409 }
410
411 /// Returns maximum absolute value of all entries
412 T maxAbs() const {
413 T Z = 0;
414 for( size_t i = 0; i < size(); i++ ) {
415 Real mag = fabs( (Real) _p[i] );
416 if( mag > Z )
417 Z = mag;
418 }
419 return Z;
420 }
421
422 /// Returns maximum value of all entries
423 T maxVal() const {
424 T Z = *std::max_element( _p.begin(), _p.end() );
425 return Z;
426 }
427
428 /// Returns minimum value of all entries
429 T minVal() const {
430 T Z = *std::min_element( _p.begin(), _p.end() );
431 return Z;
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 = totalSum();
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() * totalSum();
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 #ifdef DAI_DEBUG
498 assert( p.size() == q.size() );
499 #endif
500 Real result = 0.0;
501 switch( dt ) {
502 case TProb<T>::DISTL1:
503 for( size_t i = 0; i < p.size(); i++ )
504 result += fabs((Real)p[i] - (Real)q[i]);
505 break;
506
507 case TProb<T>::DISTLINF:
508 for( size_t i = 0; i < p.size(); i++ ) {
509 Real z = fabs((Real)p[i] - (Real)q[i]);
510 if( z > result )
511 result = z;
512 }
513 break;
514
515 case TProb<T>::DISTTV:
516 for( size_t i = 0; i < p.size(); i++ )
517 result += fabs((Real)p[i] - (Real)q[i]);
518 result *= 0.5;
519 break;
520
521 case TProb<T>::DISTKL:
522 for( size_t i = 0; i < p.size(); i++ ) {
523 if( p[i] != 0.0 )
524 result += p[i] * (std::log(p[i]) - std::log(q[i]));
525 }
526 }
527 return result;
528 }
529
530
531 /// Writes a TProb<T> to an output stream
532 /** \relates TProb
533 */
534 template<typename T> std::ostream& operator<< (std::ostream& os, const TProb<T>& P) {
535 os << "[";
536 std::copy( P.p().begin(), P.p().end(), std::ostream_iterator<T>(os, " ") );
537 os << "]";
538 return os;
539 }
540
541
542 /// Returns the TProb<T> containing the pointwise minimum of a and b (which should have equal size)
543 /** \relates TProb
544 */
545 template<typename T> TProb<T> min( const TProb<T> &a, const TProb<T> &b ) {
546 assert( a.size() == b.size() );
547 TProb<T> result( a.size() );
548 for( size_t i = 0; i < a.size(); i++ )
549 if( a[i] < b[i] )
550 result[i] = a[i];
551 else
552 result[i] = b[i];
553 return result;
554 }
555
556
557 /// Returns the TProb<T> containing the pointwise maximum of a and b (which should have equal size)
558 /** \relates TProb
559 */
560 template<typename T> TProb<T> max( const TProb<T> &a, const TProb<T> &b ) {
561 assert( a.size() == b.size() );
562 TProb<T> result( a.size() );
563 for( size_t i = 0; i < a.size(); i++ )
564 if( a[i] > b[i] )
565 result[i] = a[i];
566 else
567 result[i] = b[i];
568 return result;
569 }
570
571
572 /// Represents a vector with entries of type Real.
573 typedef TProb<Real> Prob;
574
575
576 } // end of namespace dai
577
578
579 #endif