Some cleanups of include/dai/prob.h
[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
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 /** \note Obsolete, to be removed soon
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 TProb<T> normalized( NormType norm = NORMPROB ) const {
428 T Z = 0;
429 if( norm == NORMPROB )
430 Z = sum();
431 else if( norm == NORMLINF )
432 Z = maxAbs();
433 if( Z == (T)0 ) {
434 DAI_THROW(NOT_NORMALIZABLE);
435 return *this;
436 } else
437 return pwUnaryTr( std::bind2nd( std::divides<T>(), Z ) );
438 }
439 //@}
440
441 /// \name Unary operations
442 //@{
443 /// Applies unary operation \a op pointwise
444 template<typename unaryOp> TProb<T>& pwUnaryOp( unaryOp op ) {
445 std::transform( _p.begin(), _p.end(), _p.begin(), op );
446 return *this;
447 }
448
449 /// Draws all entries i.i.d. from a uniform distribution on [0,1)
450 TProb<T>& randomize() {
451 std::generate( _p.begin(), _p.end(), rnd_uniform );
452 return *this;
453 }
454
455 /// Sets all entries to \f$1/n\f$ where \a n is the length of the vector
456 TProb<T>& setUniform () {
457 fill( (T)1 / size() );
458 return *this;
459 }
460
461 /// Applies absolute value pointwise
462 const TProb<T>& takeAbs() { return pwUnaryOp( fo_abs<T>() ); }
463
464 /// Applies exponent pointwise
465 const TProb<T>& takeExp() { return pwUnaryOp( fo_exp<T>() ); }
466
467 /// Applies logarithm pointwise
468 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
469 */
470 const TProb<T>& takeLog(bool zero=false) {
471 if( zero ) {
472 return pwUnaryOp( fo_log0<T>() );
473 } else
474 return pwUnaryOp( fo_log<T>() );
475 }
476
477 /// Normalizes vector using the specified norm
478 T normalize( NormType norm=NORMPROB ) {
479 T Z = 0;
480 if( norm == NORMPROB )
481 Z = sum();
482 else if( norm == NORMLINF )
483 Z = maxAbs();
484 if( Z == (T)0 )
485 DAI_THROW(NOT_NORMALIZABLE);
486 else
487 *this /= Z;
488 return Z;
489 }
490 //@}
491
492 /// \name Operations with scalars
493 //@{
494 /// Sets all entries to \a x
495 TProb<T> & fill(T x) {
496 std::fill( _p.begin(), _p.end(), x );
497 return *this;
498 }
499
500 // OBSOLETE
501 /// Sets entries that are smaller (in absolute value) than \a epsilon to 0
502 /** \note Obsolete, to be removed soon
503 */
504 TProb<T>& makeZero( T epsilon ) {
505 for( size_t i = 0; i < size(); i++ )
506 if( (_p[i] < epsilon) && (_p[i] > -epsilon) )
507 _p[i] = 0;
508 return *this;
509 }
510
511 // OBSOLETE
512 /// Sets entries that are smaller than \a epsilon to \a epsilon
513 /** \note Obsolete, to be removed soon
514 */
515 TProb<T>& makePositive( T epsilon ) {
516 for( size_t i = 0; i < size(); i++ )
517 if( (0 < _p[i]) && (_p[i] < epsilon) )
518 _p[i] = epsilon;
519 return *this;
520 }
521
522 /// Adds scalar \a x to each entry
523 TProb<T>& operator+= (T x) {
524 if( x != 0 )
525 return pwUnaryOp( std::bind2nd( std::plus<T>(), x ) );
526 else
527 return *this;
528 }
529
530 /// Subtracts scalar \a x from each entry
531 TProb<T>& operator-= (T x) {
532 if( x != 0 )
533 return pwUnaryOp( std::bind2nd( std::minus<T>(), x ) );
534 else
535 return *this;
536 }
537
538 /// Multiplies each entry with scalar \a x
539 TProb<T>& operator*= (T x) {
540 if( x != 1 )
541 return pwUnaryOp( std::bind2nd( std::multiplies<T>(), x ) );
542 else
543 return *this;
544 }
545
546 /// Divides each entry by scalar \a x
547 TProb<T>& operator/= (T x) {
548 DAI_DEBASSERT( x != 0 );
549 if( x != 1 )
550 return pwUnaryOp( std::bind2nd( std::divides<T>(), x ) );
551 else
552 return *this;
553 }
554
555 /// Raises entries to the power \a x
556 TProb<T>& operator^= (T x) {
557 if( x != (T)1 )
558 return pwUnaryOp( std::bind2nd( fo_pow<T>(), x) );
559 else
560 return *this;
561 }
562 //@}
563
564 /// \name Transformations with scalars
565 //@{
566 /// Returns sum of \c *this and scalar \a x
567 TProb<T> operator+ (T x) const { return pwUnaryTr( std::bind2nd( std::plus<T>(), x ) ); }
568
569 /// Returns difference of \c *this and scalar \a x
570 TProb<T> operator- (T x) const { return pwUnaryTr( std::bind2nd( std::minus<T>(), x ) ); }
571
572 /// Returns product of \c *this with scalar \a x
573 TProb<T> operator* (T x) const { return pwUnaryTr( std::bind2nd( std::multiplies<T>(), x ) ); }
574
575 /// Returns quotient of \c *this and scalar \a x, where division by 0 yields 0
576 TProb<T> operator/ (T x) const { return pwUnaryTr( std::bind2nd( fo_divides0<T>(), x ) ); }
577
578 /// Returns \c *this raised to the power \a x
579 TProb<T> operator^ (T x) const { return pwUnaryTr( std::bind2nd( fo_pow<T>(), x ) ); }
580 //@}
581
582 /// \name Operations with other equally-sized vectors
583 //@{
584 /// Applies binary operation pointwise on two vectors
585 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
586 * \param q Right operand
587 * \param op Operation of type \a binaryOp
588 */
589 template<typename binaryOp> TProb<T>& pwBinaryOp( const TProb<T> &q, binaryOp op ) {
590 DAI_DEBASSERT( size() == q.size() );
591 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), op );
592 return *this;
593 }
594
595 /// Pointwise addition with \a q
596 /** \pre <tt>this->size() == q.size()</tt>
597 */
598 TProb<T>& operator+= (const TProb<T> & q) { return pwBinaryOp( q, std::plus<T>() ); }
599
600 /// Pointwise subtraction of \a q
601 /** \pre <tt>this->size() == q.size()</tt>
602 */
603 TProb<T>& operator-= (const TProb<T> & q) { return pwBinaryOp( q, std::minus<T>() ); }
604
605 /// Pointwise multiplication with \a q
606 /** \pre <tt>this->size() == q.size()</tt>
607 */
608 TProb<T>& operator*= (const TProb<T> & q) { return pwBinaryOp( q, std::multiplies<T>() ); }
609
610 /// Pointwise division by \a q, where division by 0 yields 0
611 /** \pre <tt>this->size() == q.size()</tt>
612 * \see divide(const TProb<T> &)
613 */
614 TProb<T>& operator/= (const TProb<T> & q) { return pwBinaryOp( q, fo_divides0<T>() ); }
615
616 /// Pointwise division by \a q, where division by 0 yields +Inf
617 /** \pre <tt>this->size() == q.size()</tt>
618 * \see operator/=(const TProb<T> &)
619 */
620 TProb<T>& divide (const TProb<T> & q) { return pwBinaryOp( q, std::divides<T>() ); }
621
622 /// Pointwise power
623 /** \pre <tt>this->size() == q.size()</tt>
624 */
625 TProb<T>& operator^= (const TProb<T> & q) { return pwBinaryOp( q, fo_pow<T>() ); }
626 //@}
627
628 /// \name Transformations with other equally-sized vectors
629 //@{
630 /// Returns the result of applying binary operation \a op pointwise on \c *this and \a q
631 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
632 * \param q Right operand
633 * \param op Operation of type \a binaryOp
634 */
635 template<typename binaryOp> TProb<T> pwBinaryTr( const TProb<T> &q, binaryOp op ) const {
636 DAI_DEBASSERT( size() == q.size() );
637 TProb<T> r;
638 r._p.reserve( size() );
639 std::transform( _p.begin(), _p.end(), q._p.begin(), back_inserter( r._p ), op );
640 return r;
641 }
642
643 /// Returns sum of \c *this and \a q
644 /** \pre <tt>this->size() == q.size()</tt>
645 */
646 TProb<T> operator+ ( const TProb<T>& q ) const { return pwBinaryTr( q, std::plus<T>() ); }
647
648 /// Return \c *this minus \a q
649 /** \pre <tt>this->size() == q.size()</tt>
650 */
651 TProb<T> operator- ( const TProb<T>& q ) const { return pwBinaryTr( q, std::minus<T>() ); }
652
653 /// Return product of \c *this with \a q
654 /** \pre <tt>this->size() == q.size()</tt>
655 */
656 TProb<T> operator* ( const TProb<T> &q ) const { return pwBinaryTr( q, std::multiplies<T>() ); }
657
658 /// Returns quotient of \c *this with \a q, where division by 0 yields 0
659 /** \pre <tt>this->size() == q.size()</tt>
660 * \see divided_by(const TProb<T> &)
661 */
662 TProb<T> operator/ ( const TProb<T> &q ) const { return pwBinaryTr( q, fo_divides0<T>() ); }
663
664 /// Pointwise division by \a q, where division by 0 yields +Inf
665 /** \pre <tt>this->size() == q.size()</tt>
666 * \see operator/(const TProb<T> &)
667 */
668 TProb<T> divided_by( const TProb<T> &q ) const { return pwBinaryTr( q, std::divides<T>() ); }
669
670 /// Returns \c *this to the power \a q
671 /** \pre <tt>this->size() == q.size()</tt>
672 */
673 TProb<T> operator^ ( const TProb<T> &q ) const { return pwBinaryTr( q, fo_pow<T>() ); }
674 //@}
675
676 /// Performs a generalized inner product, similar to std::inner_product
677 /** \pre <tt>this->size() == q.size()</tt>
678 */
679 template<typename binOp1, typename binOp2> T innerProduct( const TProb<T> &q, T init, binOp1 binaryOp1, binOp2 binaryOp2 ) const {
680 DAI_DEBASSERT( size() == q.size() );
681 return std::inner_product( begin(), end(), q.begin(), init, binaryOp1, binaryOp2 );
682 }
683 };
684
685
686 /// Returns distance between \a p and \a q, measured using distance measure \a dt
687 /** \relates TProb
688 * \pre <tt>this->size() == q.size()</tt>
689 */
690 template<typename T> T dist( const TProb<T> &p, const TProb<T> &q, typename TProb<T>::DistType dt ) {
691 switch( dt ) {
692 case TProb<T>::DISTL1:
693 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() );
694 case TProb<T>::DISTLINF:
695 return p.innerProduct( q, (T)0, fo_max<T>(), fo_absdiff<T>() );
696 case TProb<T>::DISTTV:
697 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() ) / 2;
698 case TProb<T>::DISTKL:
699 return p.innerProduct( q, (T)0, std::plus<T>(), fo_KL<T>() );
700 default:
701 DAI_THROW(UNKNOWN_ENUM_VALUE);
702 return INFINITY;
703 }
704 }
705
706
707 /// Writes a TProb<T> to an output stream
708 /** \relates TProb
709 */
710 template<typename T> std::ostream& operator<< (std::ostream& os, const TProb<T>& p) {
711 os << "[";
712 std::copy( p.p().begin(), p.p().end(), std::ostream_iterator<T>(os, " ") );
713 os << "]";
714 return os;
715 }
716
717
718 /// Returns the pointwise minimum of \a a and \a b
719 /** \relates TProb
720 * \pre <tt>this->size() == q.size()</tt>
721 */
722 template<typename T> TProb<T> min( const TProb<T> &a, const TProb<T> &b ) {
723 return a.pwBinaryTr( b, fo_min<T>() );
724 }
725
726
727 /// Returns the pointwise maximum of \a a and \a b
728 /** \relates TProb
729 * \pre <tt>this->size() == q.size()</tt>
730 */
731 template<typename T> TProb<T> max( const TProb<T> &a, const TProb<T> &b ) {
732 return a.pwBinaryTr( b, fo_max<T>() );
733 }
734
735
736 /// Represents a vector with entries of type dai::Real.
737 typedef TProb<Real> Prob;
738
739
740 } // end of namespace dai
741
742
743 #endif