Documented all exceptions and did some general cleanups
[libdai.git] / include / dai / prob.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 /// \file
13 /// \brief Defines TProb<> and Prob classes which represent (probability) vectors (e.g., probability distributions of discrete random variables)
14
15
16 #ifndef __defined_libdai_prob_h
17 #define __defined_libdai_prob_h
18
19
20 #include <cmath>
21 #include <vector>
22 #include <ostream>
23 #include <algorithm>
24 #include <numeric>
25 #include <functional>
26 #include <dai/util.h>
27 #include <dai/exceptions.h>
28
29
30 namespace dai {
31
32
33 /// Function object that returns the value itself
34 template<typename T> struct fo_id : public std::unary_function<T, T> {
35 /// Returns \a x
36 T operator()( const T &x ) const {
37 return x;
38 }
39 };
40
41
42 /// Function object that takes the absolute value
43 template<typename T> struct fo_abs : public std::unary_function<T, T> {
44 /// Returns abs(\a x)
45 T operator()( const T &x ) const {
46 if( x < (T)0 )
47 return -x;
48 else
49 return x;
50 }
51 };
52
53
54 /// Function object that takes the exponent
55 template<typename T> struct fo_exp : public std::unary_function<T, T> {
56 /// Returns exp(\a x)
57 T operator()( const T &x ) const {
58 return exp( x );
59 }
60 };
61
62
63 /// Function object that takes the logarithm
64 template<typename T> struct fo_log : public std::unary_function<T, T> {
65 /// Returns log(\a x)
66 T operator()( const T &x ) const {
67 return log( x );
68 }
69 };
70
71
72 /// Function object that takes the logarithm, except that log(0) is defined to be 0
73 template<typename T> struct fo_log0 : public std::unary_function<T, T> {
74 /// Returns (\a x == 0 ? 0 : log(\a x))
75 T operator()( const T &x ) const {
76 if( x )
77 return log( x );
78 else
79 return 0;
80 }
81 };
82
83
84 /// Function object that takes the inverse
85 template<typename T> struct fo_inv : public std::unary_function<T, T> {
86 /// Returns 1 / \a x
87 T operator()( const T &x ) const {
88 return 1 / x;
89 }
90 };
91
92
93 /// Function object that takes the inverse, except that 1/0 is defined to be 0
94 template<typename T> struct fo_inv0 : public std::unary_function<T, T> {
95 /// Returns (\a x == 0 ? 0 : (1 / \a x))
96 T operator()( const T &x ) const {
97 if( x )
98 return 1 / x;
99 else
100 return 0;
101 }
102 };
103
104
105 /// Function object that returns p*log0(p)
106 template<typename T> struct fo_plog0p : public std::unary_function<T, T> {
107 /// Returns \a p * log0(\a p)
108 T operator()( const T &p ) const {
109 return p * dai::log0(p);
110 }
111 };
112
113
114 /// Function object similar to std::divides(), but different in that dividing by zero results in zero
115 template<typename T> struct fo_divides0 : public std::binary_function<T, T, T> {
116 /// Returns (\a y == 0 ? 0 : (\a x / \a y))
117 T operator()( const T &x, const T &y ) const {
118 if( y == (T)0 )
119 return (T)0;
120 else
121 return x / y;
122 }
123 };
124
125
126 /// Function object useful for calculating the KL distance
127 template<typename T> struct fo_KL : public std::binary_function<T, T, T> {
128 /// Returns (\a p == 0 ? 0 : (\a p * (log(\a p) - log(\a q))))
129 T operator()( const T &p, const T &q ) const {
130 if( p == (T)0 )
131 return (T)0;
132 else
133 return p * (log(p) - log(q));
134 }
135 };
136
137
138 /// Function object that returns x to the power y
139 template<typename T> struct fo_pow : public std::binary_function<T, T, T> {
140 /// Returns (\a x ^ \a y)
141 T operator()( const T &x, const T &y ) const {
142 if( y != 1 )
143 return std::pow( x, y );
144 else
145 return x;
146 }
147 };
148
149
150 /// Function object that returns the maximum of two values
151 template<typename T> struct fo_max : public std::binary_function<T, T, T> {
152 /// Returns (\a x > y ? x : y)
153 T operator()( const T &x, const T &y ) const {
154 return (x > y) ? x : y;
155 }
156 };
157
158
159 /// Function object that returns the minimum of two values
160 template<typename T> struct fo_min : public std::binary_function<T, T, T> {
161 /// Returns (\a x > y ? y : x)
162 T operator()( const T &x, const T &y ) const {
163 return (x > y) ? y : x;
164 }
165 };
166
167
168 /// Function object that returns the absolute difference of x and y
169 template<typename T> struct fo_absdiff : public std::binary_function<T, T, T> {
170 /// Returns abs( \a x - \a y )
171 T operator()( const T &x, const T &y ) const {
172 return dai::abs( x - y );
173 }
174 };
175
176
177 /// Represents a vector with entries of type \a T.
178 /** It is simply a <tt>std::vector</tt><<em>T</em>> with an interface designed for dealing with probability mass functions.
179 *
180 * It is mainly used for representing measures on a finite outcome space, for example, the probability
181 * distribution of a discrete random variable. However, entries are not necessarily non-negative; it is also used to
182 * represent logarithms of probability mass functions.
183 *
184 * \tparam T Should be a scalar that is castable from and to dai::Real and should support elementary arithmetic operations.
185 */
186 template <typename T> class TProb {
187 private:
188 /// The vector
189 std::vector<T> _p;
190
191 public:
192 /// Enumerates different ways of normalizing a probability measure.
193 /**
194 * - NORMPROB means that the sum of all entries should be 1;
195 * - NORMLINF means that the maximum absolute value of all entries should be 1.
196 */
197 typedef enum { NORMPROB, NORMLINF } NormType;
198 /// Enumerates different distance measures between probability measures.
199 /**
200 * - DISTL1 is the \f$\ell_1\f$ distance (sum of absolute values of pointwise difference);
201 * - DISTLINF is the \f$\ell_\infty\f$ distance (maximum absolute value of pointwise difference);
202 * - DISTTV is the total variation distance (half of the \f$\ell_1\f$ distance);
203 * - DISTKL is the Kullback-Leibler distance (\f$\sum_i p_i (\log p_i - \log q_i)\f$).
204 */
205 typedef enum { DISTL1, DISTLINF, DISTTV, DISTKL } DistType;
206
207 /// \name Constructors and destructors
208 //@{
209 /// Default constructor (constructs empty vector)
210 TProb() : _p() {}
211
212 /// Construct uniform probability distribution over \a n outcomes (i.e., a vector of length \a n with each entry set to \f$1/n\f$)
213 explicit TProb( size_t n ) : _p(std::vector<T>(n, (T)1 / n)) {}
214
215 /// Construct vector of length \a n with each entry set to \a p
216 explicit TProb( size_t n, T p ) : _p(n, p) {}
217
218 /// Construct vector from a range
219 /** \tparam TIterator Iterates over instances that can be cast to \a T
220 * \param begin Points to first instance to be added.
221 * \param end Points just beyond last instance to be added.
222 * \param sizeHint For efficiency, the number of entries can be speficied by \a sizeHint.
223 */
224 template <typename TIterator>
225 TProb( TIterator begin, TIterator end, size_t sizeHint=0 ) : _p() {
226 _p.reserve( sizeHint );
227 _p.insert( _p.begin(), begin, end );
228 }
229
230 /// Construct vector from another vector
231 /** \tparam S type of elements in \a v (should be castable to type \a T)
232 * \param v vector used for initialization
233 */
234 template <typename S>
235 TProb( const std::vector<S> &v ) : _p() {
236 _p.reserve( v.size() );
237 _p.insert( _p.begin(), v.begin(), v.end() );
238 }
239 //@}
240
241 /// Constant iterator over the elements
242 typedef typename std::vector<T>::const_iterator const_iterator;
243 /// Iterator over the elements
244 typedef typename std::vector<T>::iterator iterator;
245 /// Constant reverse iterator over the elements
246 typedef typename std::vector<T>::const_reverse_iterator const_reverse_iterator;
247 /// Reverse iterator over the elements
248 typedef typename std::vector<T>::reverse_iterator reverse_iterator;
249
250 /// \name Iterator interface
251 //@{
252 /// Returns iterator that points to the first element
253 iterator begin() { return _p.begin(); }
254 /// Returns constant iterator that points to the first element
255 const_iterator begin() const { return _p.begin(); }
256
257 /// Returns iterator that points beyond the last element
258 iterator end() { return _p.end(); }
259 /// Returns constant iterator that points beyond the last element
260 const_iterator end() const { return _p.end(); }
261
262 /// Returns reverse iterator that points to the last element
263 reverse_iterator rbegin() { return _p.rbegin(); }
264 /// Returns constant reverse iterator that points to the last element
265 const_reverse_iterator rbegin() const { return _p.rbegin(); }
266
267 /// Returns reverse iterator that points beyond the first element
268 reverse_iterator rend() { return _p.rend(); }
269 /// Returns constant reverse iterator that points beyond the first element
270 const_reverse_iterator rend() const { return _p.rend(); }
271 //@}
272
273 /// \name Queries
274 //@{
275 /// Returns a const reference to the wrapped vector
276 const std::vector<T> & p() const { return _p; }
277
278 /// Returns a reference to the wrapped vector
279 std::vector<T> & p() { return _p; }
280
281 /// Returns a copy of the \a i 'th entry
282 T operator[]( size_t i ) const {
283 #ifdef DAI_DEBUG
284 return _p.at(i);
285 #else
286 return _p[i];
287 #endif
288 }
289
290 /// Returns reference to the \a i 'th entry
291 T& operator[]( size_t i ) { return _p[i]; }
292
293 /// Returns length of the vector (i.e., the number of entries)
294 size_t size() const { return _p.size(); }
295
296 /// Accumulate over all values, similar to std::accumulate
297 template<typename binOp, typename unOp> T accumulate( T init, binOp op1, unOp op2 ) const {
298 T t = init;
299 for( const_iterator it = begin(); it != end(); it++ )
300 t = op1( t, op2(*it) );
301 return t;
302 }
303
304 /// Returns the Shannon entropy of \c *this, \f$-\sum_i p_i \log p_i\f$
305 T entropy() const { return -accumulate( (T)0, std::plus<T>(), fo_plog0p<T>() ); }
306
307 /// Returns maximum value of all entries
308 T max() const { return accumulate( (T)(-INFINITY), fo_max<T>(), fo_id<T>() ); }
309
310 /// Returns minimum value of all entries
311 T min() const { return accumulate( (T)INFINITY, fo_min<T>(), fo_id<T>() ); }
312
313 /// Returns sum of all entries
314 T sum() const { return accumulate( (T)0, std::plus<T>(), fo_id<T>() ); }
315
316 /// Return sum of absolute value of all entries
317 T sumAbs() const { return accumulate( (T)0, std::plus<T>(), fo_abs<T>() ); }
318
319 /// Returns maximum absolute value of all entries
320 T maxAbs() const { return accumulate( (T)0, fo_max<T>(), fo_abs<T>() ); }
321
322 /// Returns \c true if one or more entries are NaN
323 bool hasNaNs() const {
324 bool foundnan = false;
325 for( typename std::vector<T>::const_iterator x = _p.begin(); x != _p.end(); x++ )
326 if( isnan( *x ) ) {
327 foundnan = true;
328 break;
329 }
330 return foundnan;
331 }
332
333 /// Returns \c true if one or more entries are negative
334 bool hasNegatives() const {
335 return (std::find_if( _p.begin(), _p.end(), std::bind2nd( std::less<T>(), (T)0 ) ) != _p.end());
336 }
337
338 /// Returns a pair consisting of the index of the maximum value and the maximum value itself
339 std::pair<size_t,T> argmax() const {
340 T max = _p[0];
341 size_t arg = 0;
342 for( size_t i = 1; i < size(); i++ ) {
343 if( _p[i] > max ) {
344 max = _p[i];
345 arg = i;
346 }
347 }
348 return std::make_pair(arg,max);
349 }
350
351 /// Returns a random index, according to the (normalized) distribution described by *this
352 size_t draw() {
353 Real x = rnd_uniform() * sum();
354 T s = 0;
355 for( size_t i = 0; i < size(); i++ ) {
356 s += _p[i];
357 if( s > x )
358 return i;
359 }
360 return( size() - 1 );
361 }
362
363 /// Lexicographical comparison
364 /** \pre <tt>this->size() == q.size()</tt>
365 */
366 bool operator<= (const TProb<T> & q) const {
367 DAI_DEBASSERT( size() == q.size() );
368 return lexicographical_compare( begin(), end(), q.begin(), q.end() );
369 }
370 //@}
371
372 /// \name Unary transformations
373 //@{
374 /// Returns the result of applying operation \a op pointwise on \c *this
375 template<typename unaryOp> TProb<T> pwUnaryTr( unaryOp op ) const {
376 TProb<T> r;
377 r._p.reserve( size() );
378 std::transform( _p.begin(), _p.end(), back_inserter( r._p ), op );
379 return r;
380 }
381
382 // OBSOLETE
383 /// Returns pointwise signum
384 /** \deprecated Functionality was not widely used
385 */
386 TProb<T> sgn() const {
387 TProb<T> x;
388 x._p.reserve( size() );
389 for( size_t i = 0; i < size(); i++ ) {
390 T s = 0;
391 if( _p[i] > 0 )
392 s = 1;
393 else if( _p[i] < 0 )
394 s = -1;
395 x._p.push_back( s );
396 }
397 return x;
398 }
399
400 /// Returns pointwise absolute value
401 TProb<T> abs() const { return pwUnaryTr( fo_abs<T>() ); }
402
403 /// Returns pointwise exponent
404 TProb<T> exp() const { return pwUnaryTr( fo_exp<T>() ); }
405
406 /// Returns pointwise logarithm
407 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
408 */
409 TProb<T> log(bool zero=false) const {
410 if( zero )
411 return pwUnaryTr( fo_log0<T>() );
412 else
413 return pwUnaryTr( fo_log<T>() );
414 }
415
416 /// Returns pointwise inverse
417 /** If \a zero == \c true, uses <tt>1/0==0</tt>; otherwise, <tt>1/0==Inf</tt>.
418 */
419 TProb<T> inverse(bool zero=true) const {
420 if( zero )
421 return pwUnaryTr( fo_inv0<T>() );
422 else
423 return pwUnaryTr( fo_inv<T>() );
424 }
425
426 /// Returns normalized copy of \c *this, using the specified norm
427 /** \throw NOT_NORMALIZABLE if the norm is zero
428 */
429 TProb<T> normalized( NormType norm = NORMPROB ) const {
430 T Z = 0;
431 if( norm == NORMPROB )
432 Z = sum();
433 else if( norm == NORMLINF )
434 Z = maxAbs();
435 if( Z == (T)0 ) {
436 DAI_THROW(NOT_NORMALIZABLE);
437 return *this;
438 } else
439 return pwUnaryTr( std::bind2nd( std::divides<T>(), Z ) );
440 }
441 //@}
442
443 /// \name Unary operations
444 //@{
445 /// Applies unary operation \a op pointwise
446 template<typename unaryOp> TProb<T>& pwUnaryOp( unaryOp op ) {
447 std::transform( _p.begin(), _p.end(), _p.begin(), op );
448 return *this;
449 }
450
451 /// Draws all entries i.i.d. from a uniform distribution on [0,1)
452 TProb<T>& randomize() {
453 std::generate( _p.begin(), _p.end(), rnd_uniform );
454 return *this;
455 }
456
457 /// Sets all entries to \f$1/n\f$ where \a n is the length of the vector
458 TProb<T>& setUniform () {
459 fill( (T)1 / size() );
460 return *this;
461 }
462
463 /// Applies absolute value pointwise
464 const TProb<T>& takeAbs() { return pwUnaryOp( fo_abs<T>() ); }
465
466 /// Applies exponent pointwise
467 const TProb<T>& takeExp() { return pwUnaryOp( fo_exp<T>() ); }
468
469 /// Applies logarithm pointwise
470 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
471 */
472 const TProb<T>& takeLog(bool zero=false) {
473 if( zero ) {
474 return pwUnaryOp( fo_log0<T>() );
475 } else
476 return pwUnaryOp( fo_log<T>() );
477 }
478
479 /// Normalizes vector using the specified norm
480 /** \throw NOT_NORMALIZABLE if the norm is zero
481 */
482 T normalize( NormType norm=NORMPROB ) {
483 T Z = 0;
484 if( norm == NORMPROB )
485 Z = sum();
486 else if( norm == NORMLINF )
487 Z = maxAbs();
488 if( Z == (T)0 )
489 DAI_THROW(NOT_NORMALIZABLE);
490 else
491 *this /= Z;
492 return Z;
493 }
494 //@}
495
496 /// \name Operations with scalars
497 //@{
498 /// Sets all entries to \a x
499 TProb<T> & fill(T x) {
500 std::fill( _p.begin(), _p.end(), x );
501 return *this;
502 }
503
504 // OBSOLETE
505 /// Sets entries that are smaller (in absolute value) than \a epsilon to 0
506 /** \deprecated Functionality was not widely used
507 */
508 TProb<T>& makeZero( T epsilon ) {
509 for( size_t i = 0; i < size(); i++ )
510 if( (_p[i] < epsilon) && (_p[i] > -epsilon) )
511 _p[i] = 0;
512 return *this;
513 }
514
515 // OBSOLETE
516 /// Sets entries that are smaller than \a epsilon to \a epsilon
517 /** \deprecated Functionality was not widely used
518 */
519 TProb<T>& makePositive( T epsilon ) {
520 for( size_t i = 0; i < size(); i++ )
521 if( (0 < _p[i]) && (_p[i] < epsilon) )
522 _p[i] = epsilon;
523 return *this;
524 }
525
526 /// Adds scalar \a x to each entry
527 TProb<T>& operator+= (T x) {
528 if( x != 0 )
529 return pwUnaryOp( std::bind2nd( std::plus<T>(), x ) );
530 else
531 return *this;
532 }
533
534 /// Subtracts scalar \a x from each entry
535 TProb<T>& operator-= (T x) {
536 if( x != 0 )
537 return pwUnaryOp( std::bind2nd( std::minus<T>(), x ) );
538 else
539 return *this;
540 }
541
542 /// Multiplies each entry with scalar \a x
543 TProb<T>& operator*= (T x) {
544 if( x != 1 )
545 return pwUnaryOp( std::bind2nd( std::multiplies<T>(), x ) );
546 else
547 return *this;
548 }
549
550 /// Divides each entry by scalar \a x
551 TProb<T>& operator/= (T x) {
552 DAI_DEBASSERT( x != 0 );
553 if( x != 1 )
554 return pwUnaryOp( std::bind2nd( std::divides<T>(), x ) );
555 else
556 return *this;
557 }
558
559 /// Raises entries to the power \a x
560 TProb<T>& operator^= (T x) {
561 if( x != (T)1 )
562 return pwUnaryOp( std::bind2nd( fo_pow<T>(), x) );
563 else
564 return *this;
565 }
566 //@}
567
568 /// \name Transformations with scalars
569 //@{
570 /// Returns sum of \c *this and scalar \a x
571 TProb<T> operator+ (T x) const { return pwUnaryTr( std::bind2nd( std::plus<T>(), x ) ); }
572
573 /// Returns difference of \c *this and scalar \a x
574 TProb<T> operator- (T x) const { return pwUnaryTr( std::bind2nd( std::minus<T>(), x ) ); }
575
576 /// Returns product of \c *this with scalar \a x
577 TProb<T> operator* (T x) const { return pwUnaryTr( std::bind2nd( std::multiplies<T>(), x ) ); }
578
579 /// Returns quotient of \c *this and scalar \a x, where division by 0 yields 0
580 TProb<T> operator/ (T x) const { return pwUnaryTr( std::bind2nd( fo_divides0<T>(), x ) ); }
581
582 /// Returns \c *this raised to the power \a x
583 TProb<T> operator^ (T x) const { return pwUnaryTr( std::bind2nd( fo_pow<T>(), x ) ); }
584 //@}
585
586 /// \name Operations with other equally-sized vectors
587 //@{
588 /// Applies binary operation pointwise on two vectors
589 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
590 * \param q Right operand
591 * \param op Operation of type \a binaryOp
592 */
593 template<typename binaryOp> TProb<T>& pwBinaryOp( const TProb<T> &q, binaryOp op ) {
594 DAI_DEBASSERT( size() == q.size() );
595 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), op );
596 return *this;
597 }
598
599 /// Pointwise addition with \a q
600 /** \pre <tt>this->size() == q.size()</tt>
601 */
602 TProb<T>& operator+= (const TProb<T> & q) { return pwBinaryOp( q, std::plus<T>() ); }
603
604 /// Pointwise subtraction of \a q
605 /** \pre <tt>this->size() == q.size()</tt>
606 */
607 TProb<T>& operator-= (const TProb<T> & q) { return pwBinaryOp( q, std::minus<T>() ); }
608
609 /// Pointwise multiplication with \a q
610 /** \pre <tt>this->size() == q.size()</tt>
611 */
612 TProb<T>& operator*= (const TProb<T> & q) { return pwBinaryOp( q, std::multiplies<T>() ); }
613
614 /// Pointwise division by \a q, where division by 0 yields 0
615 /** \pre <tt>this->size() == q.size()</tt>
616 * \see divide(const TProb<T> &)
617 */
618 TProb<T>& operator/= (const TProb<T> & q) { return pwBinaryOp( q, fo_divides0<T>() ); }
619
620 /// Pointwise division by \a q, where division by 0 yields +Inf
621 /** \pre <tt>this->size() == q.size()</tt>
622 * \see operator/=(const TProb<T> &)
623 */
624 TProb<T>& divide (const TProb<T> & q) { return pwBinaryOp( q, std::divides<T>() ); }
625
626 /// Pointwise power
627 /** \pre <tt>this->size() == q.size()</tt>
628 */
629 TProb<T>& operator^= (const TProb<T> & q) { return pwBinaryOp( q, fo_pow<T>() ); }
630 //@}
631
632 /// \name Transformations with other equally-sized vectors
633 //@{
634 /// Returns the result of applying binary operation \a op pointwise on \c *this and \a q
635 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
636 * \param q Right operand
637 * \param op Operation of type \a binaryOp
638 */
639 template<typename binaryOp> TProb<T> pwBinaryTr( const TProb<T> &q, binaryOp op ) const {
640 DAI_DEBASSERT( size() == q.size() );
641 TProb<T> r;
642 r._p.reserve( size() );
643 std::transform( _p.begin(), _p.end(), q._p.begin(), back_inserter( r._p ), op );
644 return r;
645 }
646
647 /// Returns sum of \c *this and \a q
648 /** \pre <tt>this->size() == q.size()</tt>
649 */
650 TProb<T> operator+ ( const TProb<T>& q ) const { return pwBinaryTr( q, std::plus<T>() ); }
651
652 /// Return \c *this minus \a q
653 /** \pre <tt>this->size() == q.size()</tt>
654 */
655 TProb<T> operator- ( const TProb<T>& q ) const { return pwBinaryTr( q, std::minus<T>() ); }
656
657 /// Return product of \c *this with \a q
658 /** \pre <tt>this->size() == q.size()</tt>
659 */
660 TProb<T> operator* ( const TProb<T> &q ) const { return pwBinaryTr( q, std::multiplies<T>() ); }
661
662 /// Returns quotient of \c *this with \a q, where division by 0 yields 0
663 /** \pre <tt>this->size() == q.size()</tt>
664 * \see divided_by(const TProb<T> &)
665 */
666 TProb<T> operator/ ( const TProb<T> &q ) const { return pwBinaryTr( q, fo_divides0<T>() ); }
667
668 /// Pointwise division by \a q, where division by 0 yields +Inf
669 /** \pre <tt>this->size() == q.size()</tt>
670 * \see operator/(const TProb<T> &)
671 */
672 TProb<T> divided_by( const TProb<T> &q ) const { return pwBinaryTr( q, std::divides<T>() ); }
673
674 /// Returns \c *this to the power \a q
675 /** \pre <tt>this->size() == q.size()</tt>
676 */
677 TProb<T> operator^ ( const TProb<T> &q ) const { return pwBinaryTr( q, fo_pow<T>() ); }
678 //@}
679
680 /// Performs a generalized inner product, similar to std::inner_product
681 /** \pre <tt>this->size() == q.size()</tt>
682 */
683 template<typename binOp1, typename binOp2> T innerProduct( const TProb<T> &q, T init, binOp1 binaryOp1, binOp2 binaryOp2 ) const {
684 DAI_DEBASSERT( size() == q.size() );
685 return std::inner_product( begin(), end(), q.begin(), init, binaryOp1, binaryOp2 );
686 }
687 };
688
689
690 /// Returns distance between \a p and \a q, measured using distance measure \a dt
691 /** \relates TProb
692 * \pre <tt>this->size() == q.size()</tt>
693 */
694 template<typename T> T dist( const TProb<T> &p, const TProb<T> &q, typename TProb<T>::DistType dt ) {
695 switch( dt ) {
696 case TProb<T>::DISTL1:
697 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() );
698 case TProb<T>::DISTLINF:
699 return p.innerProduct( q, (T)0, fo_max<T>(), fo_absdiff<T>() );
700 case TProb<T>::DISTTV:
701 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() ) / 2;
702 case TProb<T>::DISTKL:
703 return p.innerProduct( q, (T)0, std::plus<T>(), fo_KL<T>() );
704 default:
705 DAI_THROW(UNKNOWN_ENUM_VALUE);
706 return INFINITY;
707 }
708 }
709
710
711 /// Writes a TProb<T> to an output stream
712 /** \relates TProb
713 */
714 template<typename T> std::ostream& operator<< (std::ostream& os, const TProb<T>& p) {
715 os << "[";
716 std::copy( p.p().begin(), p.p().end(), std::ostream_iterator<T>(os, " ") );
717 os << "]";
718 return os;
719 }
720
721
722 /// Returns the pointwise minimum of \a a and \a b
723 /** \relates TProb
724 * \pre <tt>this->size() == q.size()</tt>
725 */
726 template<typename T> TProb<T> min( const TProb<T> &a, const TProb<T> &b ) {
727 return a.pwBinaryTr( b, fo_min<T>() );
728 }
729
730
731 /// Returns the pointwise maximum of \a a and \a b
732 /** \relates TProb
733 * \pre <tt>this->size() == q.size()</tt>
734 */
735 template<typename T> TProb<T> max( const TProb<T> &a, const TProb<T> &b ) {
736 return a.pwBinaryTr( b, fo_max<T>() );
737 }
738
739
740 /// Represents a vector with entries of type dai::Real.
741 typedef TProb<Real> Prob;
742
743
744 } // end of namespace dai
745
746
747 #endif