Improved prob.h/cpp code:
[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 useful for calculating the Hellinger distance
139 template<typename T> struct fo_Hellinger : public std::binary_function<T, T, T> {
140 /// Returns (sqrt(\a p) - sqrt(\a q))^2
141 T operator()( const T &p, const T &q ) const {
142 T x = sqrt(p) - sqrt(q);
143 return x * x;
144 }
145 };
146
147
148 /// Function object that returns x to the power y
149 template<typename T> struct fo_pow : public std::binary_function<T, T, T> {
150 /// Returns (\a x ^ \a y)
151 T operator()( const T &x, const T &y ) const {
152 if( y != 1 )
153 return std::pow( x, y );
154 else
155 return x;
156 }
157 };
158
159
160 /// Function object that returns the maximum of two values
161 template<typename T> struct fo_max : public std::binary_function<T, T, T> {
162 /// Returns (\a x > y ? x : y)
163 T operator()( const T &x, const T &y ) const {
164 return (x > y) ? x : y;
165 }
166 };
167
168
169 /// Function object that returns the minimum of two values
170 template<typename T> struct fo_min : public std::binary_function<T, T, T> {
171 /// Returns (\a x > y ? y : x)
172 T operator()( const T &x, const T &y ) const {
173 return (x > y) ? y : x;
174 }
175 };
176
177
178 /// Function object that returns the absolute difference of x and y
179 template<typename T> struct fo_absdiff : public std::binary_function<T, T, T> {
180 /// Returns abs( \a x - \a y )
181 T operator()( const T &x, const T &y ) const {
182 return dai::abs( x - y );
183 }
184 };
185
186
187 /// Represents a vector with entries of type \a T.
188 /** It is simply a <tt>std::vector</tt><<em>T</em>> with an interface designed for dealing with probability mass functions.
189 *
190 * It is mainly used for representing measures on a finite outcome space, for example, the probability
191 * distribution of a discrete random variable. However, entries are not necessarily non-negative; it is also used to
192 * represent logarithms of probability mass functions.
193 *
194 * \tparam T Should be a scalar that is castable from and to dai::Real and should support elementary arithmetic operations.
195 */
196 template <typename T>
197 class TProb {
198 public:
199 /// Type of data structure used for storing the values
200 typedef std::vector<T> container_type;
201 typedef TProb<T> this_type;
202
203 private:
204 /// The data structure that stores the values
205 container_type _p;
206
207 public:
208 /// Enumerates different ways of normalizing a probability measure.
209 /**
210 * - NORMPROB means that the sum of all entries should be 1;
211 * - NORMLINF means that the maximum absolute value of all entries should be 1.
212 * \deprecated Please use dai::ProbNormType instead.
213 */
214 typedef enum { NORMPROB, NORMLINF } NormType;
215 /// Enumerates different distance measures between probability measures.
216 /**
217 * - DISTL1 is the \f$\ell_1\f$ distance (sum of absolute values of pointwise difference);
218 * - DISTLINF is the \f$\ell_\infty\f$ distance (maximum absolute value of pointwise difference);
219 * - DISTTV is the total variation distance (half of the \f$\ell_1\f$ distance);
220 * - DISTKL is the Kullback-Leibler distance (\f$\sum_i p_i (\log p_i - \log q_i)\f$).
221 * - DISTHEL is the Hellinger distance (\f$\frac{1}{2}\sum_i (\sqrt{p_i}-\sqrt{q_i})^2\f$).
222 * \deprecated Please use dai::ProbDistType instead.
223 */
224 typedef enum { DISTL1, DISTLINF, DISTTV, DISTKL, DISTHEL } DistType;
225
226 /// \name Constructors and destructors
227 //@{
228 /// Default constructor (constructs empty vector)
229 TProb() : _p() {}
230
231 /// 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$)
232 explicit TProb( size_t n ) : _p( n, (T)1 / n ) {}
233
234 /// Construct vector of length \a n with each entry set to \a p
235 explicit TProb( size_t n, T p ) : _p( n, p ) {}
236
237 /// Construct vector from a range
238 /** \tparam TIterator Iterates over instances that can be cast to \a T
239 * \param begin Points to first instance to be added.
240 * \param end Points just beyond last instance to be added.
241 * \param sizeHint For efficiency, the number of entries can be speficied by \a sizeHint;
242 * the value 0 can be given if the size is unknown, but this will result in a performance penalty.
243 * \deprecated In future libDAI versions, the \a sizeHint argument will no longer default to 0.
244 */
245 template <typename TIterator>
246 TProb( TIterator begin, TIterator end, size_t sizeHint=0 ) : _p() {
247 _p.reserve( sizeHint );
248 _p.insert( _p.begin(), begin, end );
249 }
250
251 /// Construct vector from another vector
252 /** \tparam S type of elements in \a v (should be castable to type \a T)
253 * \param v vector used for initialization.
254 */
255 template <typename S>
256 TProb( const std::vector<S> &v ) : _p() {
257 _p.reserve( v.size() );
258 _p.insert( _p.begin(), v.begin(), v.end() );
259 }
260 //@}
261
262 /// Constant iterator over the elements
263 typedef typename container_type::const_iterator const_iterator;
264 /// Iterator over the elements
265 typedef typename container_type::iterator iterator;
266 /// Constant reverse iterator over the elements
267 typedef typename container_type::const_reverse_iterator const_reverse_iterator;
268 /// Reverse iterator over the elements
269 typedef typename container_type::reverse_iterator reverse_iterator;
270
271 /// \name Iterator interface
272 //@{
273 /// Returns iterator that points to the first element
274 iterator begin() { return _p.begin(); }
275 /// Returns constant iterator that points to the first element
276 const_iterator begin() const { return _p.begin(); }
277
278 /// Returns iterator that points beyond the last element
279 iterator end() { return _p.end(); }
280 /// Returns constant iterator that points beyond the last element
281 const_iterator end() const { return _p.end(); }
282
283 /// Returns reverse iterator that points to the last element
284 reverse_iterator rbegin() { return _p.rbegin(); }
285 /// Returns constant reverse iterator that points to the last element
286 const_reverse_iterator rbegin() const { return _p.rbegin(); }
287
288 /// Returns reverse iterator that points beyond the first element
289 reverse_iterator rend() { return _p.rend(); }
290 /// Returns constant reverse iterator that points beyond the first element
291 const_reverse_iterator rend() const { return _p.rend(); }
292 //@}
293
294 /// \name Miscellaneous operations
295 //@{
296 void resize( size_t sz ) {
297 _p.resize( sz );
298 }
299 //@}
300
301 /// \name Get/set individual entries
302 //@{
303 /// Gets \a i 'th entry
304 T get( size_t i ) const {
305 #ifdef DAI_DEBUG
306 return _p.at(i);
307 #else
308 return _p[i];
309 #endif
310 }
311
312 /// Sets \a i 'th entry to \a val
313 void set( size_t i, T val ) {
314 DAI_DEBASSERT( i < _p.size() );
315 _p[i] = val;
316 }
317 //@}
318
319 /// \name Queries
320 //@{
321 /// Returns a const reference to the wrapped container
322 const container_type& p() const { return _p; }
323
324 /// Returns a reference to the wrapped container
325 container_type& p() { return _p; }
326
327 /// Returns a copy of the \a i 'th entry
328 T operator[]( size_t i ) const { return get(i); }
329
330 /// Returns reference to the \a i 'th entry
331 /** \deprecated Please use dai::TProb::set() instead
332 */
333 T& operator[]( size_t i ) { return _p[i]; }
334
335 /// Returns length of the vector (i.e., the number of entries)
336 size_t size() const { return _p.size(); }
337
338 /// Accumulate over all values, similar to std::accumulate
339 /** The following calculation is done:
340 * \code
341 * T t = op2(init);
342 * for( const_iterator it = begin(); it != end(); it++ )
343 * t = op1( t, op2(*it) );
344 * return t;
345 * \endcode
346 * \deprecated Please use dai::TProb::accumulateSum or dai::TProb::accumulateMax instead
347 */
348 template<typename binOp, typename unOp> T accumulate( T init, binOp op1, unOp op2 ) const {
349 T t = op2(init);
350 for( const_iterator it = begin(); it != end(); it++ )
351 t = op1( t, op2(*it) );
352 return t;
353 }
354
355
356 /// Accumulate all values (similar to std::accumulate) by summing
357 /** The following calculation is done:
358 * \code
359 * T t = op(init);
360 * for( const_iterator it = begin(); it != end(); it++ )
361 * t += op(*it);
362 * return t;
363 * \endcode
364 */
365 template<typename unOp> T accumulateSum( T init, unOp op ) const {
366 T t = op(init);
367 for( const_iterator it = begin(); it != end(); it++ )
368 t += op(*it);
369 return t;
370 }
371
372 /// Accumulate all values (similar to std::accumulate) by maximization/minimization
373 /** The following calculation is done (with "max" replaced by "min" if \a minimize == \c true):
374 * \code
375 * T t = op(init);
376 * for( const_iterator it = begin(); it != end(); it++ )
377 * t = std::max( t, op(*it) );
378 * return t;
379 * \endcode
380 */
381 template<typename unOp> T accumulateMax( T init, unOp op, bool minimize ) const {
382 T t = op(init);
383 if( minimize ) {
384 for( const_iterator it = begin(); it != end(); it++ )
385 t = std::min( t, op(*it) );
386 } else {
387 for( const_iterator it = begin(); it != end(); it++ )
388 t = std::max( t, op(*it) );
389 }
390 return t;
391 }
392
393 /// Returns the Shannon entropy of \c *this, \f$-\sum_i p_i \log p_i\f$
394 T entropy() const { return -accumulateSum( (T)0, fo_plog0p<T>() ); }
395
396 /// Returns maximum value of all entries
397 T max() const { return accumulateMax( (T)(-INFINITY), fo_id<T>(), false ); }
398
399 /// Returns minimum value of all entries
400 T min() const { return accumulateMax( (T)INFINITY, fo_id<T>(), true ); }
401
402 /// Returns sum of all entries
403 T sum() const { return accumulateSum( (T)0, fo_id<T>() ); }
404
405 /// Return sum of absolute value of all entries
406 T sumAbs() const { return accumulateSum( (T)0, fo_abs<T>() ); }
407
408 /// Returns maximum absolute value of all entries
409 T maxAbs() const { return accumulateMax( (T)0, fo_abs<T>(), false ); }
410
411 /// Returns \c true if one or more entries are NaN
412 bool hasNaNs() const {
413 bool foundnan = false;
414 for( const_iterator x = _p.begin(); x != _p.end(); x++ )
415 if( isnan( *x ) ) {
416 foundnan = true;
417 break;
418 }
419 return foundnan;
420 }
421
422 /// Returns \c true if one or more entries are negative
423 bool hasNegatives() const {
424 return (std::find_if( _p.begin(), _p.end(), std::bind2nd( std::less<T>(), (T)0 ) ) != _p.end());
425 }
426
427 /// Returns a pair consisting of the index of the maximum value and the maximum value itself
428 std::pair<size_t,T> argmax() const {
429 T max = _p[0];
430 size_t arg = 0;
431 for( size_t i = 1; i < size(); i++ ) {
432 if( _p[i] > max ) {
433 max = _p[i];
434 arg = i;
435 }
436 }
437 return std::make_pair( arg, max );
438 }
439
440 /// Returns a random index, according to the (normalized) distribution described by *this
441 size_t draw() {
442 Real x = rnd_uniform() * sum();
443 T s = 0;
444 for( size_t i = 0; i < size(); i++ ) {
445 s += get(i);
446 if( s > x )
447 return i;
448 }
449 return( size() - 1 );
450 }
451
452 /// Lexicographical comparison
453 /** \pre <tt>this->size() == q.size()</tt>
454 */
455 bool operator<( const this_type& q ) const {
456 DAI_DEBASSERT( size() == q.size() );
457 return lexicographical_compare( begin(), end(), q.begin(), q.end() );
458 }
459
460 /// Comparison
461 bool operator==( const this_type& q ) const {
462 if( size() != q.size() )
463 return false;
464 return p() == q.p();
465 }
466 //@}
467
468 /// \name Unary transformations
469 //@{
470 /// Returns the result of applying operation \a op pointwise on \c *this
471 template<typename unaryOp> this_type pwUnaryTr( unaryOp op ) const {
472 this_type r;
473 r._p.reserve( size() );
474 std::transform( _p.begin(), _p.end(), back_inserter( r._p ), op );
475 return r;
476 }
477
478 /// Returns negative of \c *this
479 this_type operator- () const { return pwUnaryTr( std::negate<T>() ); }
480
481 /// Returns pointwise absolute value
482 this_type abs() const { return pwUnaryTr( fo_abs<T>() ); }
483
484 /// Returns pointwise exponent
485 this_type exp() const { return pwUnaryTr( fo_exp<T>() ); }
486
487 /// Returns pointwise logarithm
488 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
489 */
490 this_type log(bool zero=false) const {
491 if( zero )
492 return pwUnaryTr( fo_log0<T>() );
493 else
494 return pwUnaryTr( fo_log<T>() );
495 }
496
497 /// Returns pointwise inverse
498 /** If \a zero == \c true, uses <tt>1/0==0</tt>; otherwise, <tt>1/0==Inf</tt>.
499 */
500 this_type inverse(bool zero=true) const {
501 if( zero )
502 return pwUnaryTr( fo_inv0<T>() );
503 else
504 return pwUnaryTr( fo_inv<T>() );
505 }
506
507 /// Returns normalized copy of \c *this, using the specified norm
508 /** \throw NOT_NORMALIZABLE if the norm is zero
509 */
510 this_type normalized( ProbNormType norm = dai::NORMPROB ) const {
511 T Z = 0;
512 if( norm == dai::NORMPROB )
513 Z = sum();
514 else if( norm == dai::NORMLINF )
515 Z = maxAbs();
516 if( Z == (T)0 ) {
517 DAI_THROW(NOT_NORMALIZABLE);
518 return *this;
519 } else
520 return pwUnaryTr( std::bind2nd( std::divides<T>(), Z ) );
521 }
522 //@}
523
524 /// \name Unary operations
525 //@{
526 /// Applies unary operation \a op pointwise
527 template<typename unaryOp> this_type& pwUnaryOp( unaryOp op ) {
528 std::transform( _p.begin(), _p.end(), _p.begin(), op );
529 return *this;
530 }
531
532 /// Draws all entries i.i.d. from a uniform distribution on [0,1)
533 this_type& randomize() {
534 std::generate( _p.begin(), _p.end(), rnd_uniform );
535 return *this;
536 }
537
538 /// Sets all entries to \f$1/n\f$ where \a n is the length of the vector
539 this_type& setUniform () {
540 fill( (T)1 / size() );
541 return *this;
542 }
543
544 /// Applies absolute value pointwise
545 this_type& takeAbs() { return pwUnaryOp( fo_abs<T>() ); }
546
547 /// Applies exponent pointwise
548 this_type& takeExp() { return pwUnaryOp( fo_exp<T>() ); }
549
550 /// Applies logarithm pointwise
551 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
552 */
553 this_type& takeLog(bool zero=false) {
554 if( zero ) {
555 return pwUnaryOp( fo_log0<T>() );
556 } else
557 return pwUnaryOp( fo_log<T>() );
558 }
559
560 /// Normalizes vector using the specified norm
561 /** \throw NOT_NORMALIZABLE if the norm is zero
562 */
563 T normalize( ProbNormType norm=dai::NORMPROB ) {
564 T Z = 0;
565 if( norm == dai::NORMPROB )
566 Z = sum();
567 else if( norm == dai::NORMLINF )
568 Z = maxAbs();
569 if( Z == (T)0 )
570 DAI_THROW(NOT_NORMALIZABLE);
571 else
572 *this /= Z;
573 return Z;
574 }
575 //@}
576
577 /// \name Operations with scalars
578 //@{
579 /// Sets all entries to \a x
580 this_type& fill( T x ) {
581 std::fill( _p.begin(), _p.end(), x );
582 return *this;
583 }
584
585 /// Adds scalar \a x to each entry
586 this_type& operator+= (T x) {
587 if( x != 0 )
588 return pwUnaryOp( std::bind2nd( std::plus<T>(), x ) );
589 else
590 return *this;
591 }
592
593 /// Subtracts scalar \a x from each entry
594 this_type& operator-= (T x) {
595 if( x != 0 )
596 return pwUnaryOp( std::bind2nd( std::minus<T>(), x ) );
597 else
598 return *this;
599 }
600
601 /// Multiplies each entry with scalar \a x
602 this_type& operator*= (T x) {
603 if( x != 1 )
604 return pwUnaryOp( std::bind2nd( std::multiplies<T>(), x ) );
605 else
606 return *this;
607 }
608
609 /// Divides each entry by scalar \a x, where division by 0 yields 0
610 this_type& operator/= (T x) {
611 if( x != 1 )
612 return pwUnaryOp( std::bind2nd( fo_divides0<T>(), x ) );
613 else
614 return *this;
615 }
616
617 /// Raises entries to the power \a x
618 this_type& operator^= (T x) {
619 if( x != (T)1 )
620 return pwUnaryOp( std::bind2nd( fo_pow<T>(), x) );
621 else
622 return *this;
623 }
624 //@}
625
626 /// \name Transformations with scalars
627 //@{
628 /// Returns sum of \c *this and scalar \a x
629 this_type operator+ (T x) const { return pwUnaryTr( std::bind2nd( std::plus<T>(), x ) ); }
630
631 /// Returns difference of \c *this and scalar \a x
632 this_type operator- (T x) const { return pwUnaryTr( std::bind2nd( std::minus<T>(), x ) ); }
633
634 /// Returns product of \c *this with scalar \a x
635 this_type operator* (T x) const { return pwUnaryTr( std::bind2nd( std::multiplies<T>(), x ) ); }
636
637 /// Returns quotient of \c *this and scalar \a x, where division by 0 yields 0
638 this_type operator/ (T x) const { return pwUnaryTr( std::bind2nd( fo_divides0<T>(), x ) ); }
639
640 /// Returns \c *this raised to the power \a x
641 this_type operator^ (T x) const { return pwUnaryTr( std::bind2nd( fo_pow<T>(), x ) ); }
642 //@}
643
644 /// \name Operations with other equally-sized vectors
645 //@{
646 /// Applies binary operation pointwise on two vectors
647 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
648 * \param q Right operand
649 * \param op Operation of type \a binaryOp
650 */
651 template<typename binaryOp> this_type& pwBinaryOp( const this_type &q, binaryOp op ) {
652 DAI_DEBASSERT( size() == q.size() );
653 std::transform( _p.begin(), _p.end(), q._p.begin(), _p.begin(), op );
654 return *this;
655 }
656
657 /// Pointwise addition with \a q
658 /** \pre <tt>this->size() == q.size()</tt>
659 */
660 this_type& operator+= (const this_type & q) { return pwBinaryOp( q, std::plus<T>() ); }
661
662 /// Pointwise subtraction of \a q
663 /** \pre <tt>this->size() == q.size()</tt>
664 */
665 this_type& operator-= (const this_type & q) { return pwBinaryOp( q, std::minus<T>() ); }
666
667 /// Pointwise multiplication with \a q
668 /** \pre <tt>this->size() == q.size()</tt>
669 */
670 this_type& operator*= (const this_type & q) { return pwBinaryOp( q, std::multiplies<T>() ); }
671
672 /// Pointwise division by \a q, where division by 0 yields 0
673 /** \pre <tt>this->size() == q.size()</tt>
674 * \see divide(const TProb<T> &)
675 */
676 this_type& operator/= (const this_type & q) { return pwBinaryOp( q, fo_divides0<T>() ); }
677
678 /// Pointwise division by \a q, where division by 0 yields +Inf
679 /** \pre <tt>this->size() == q.size()</tt>
680 * \see operator/=(const TProb<T> &)
681 */
682 this_type& divide (const this_type & q) { return pwBinaryOp( q, std::divides<T>() ); }
683
684 /// Pointwise power
685 /** \pre <tt>this->size() == q.size()</tt>
686 */
687 this_type& operator^= (const this_type & q) { return pwBinaryOp( q, fo_pow<T>() ); }
688 //@}
689
690 /// \name Transformations with other equally-sized vectors
691 //@{
692 /// Returns the result of applying binary operation \a op pointwise on \c *this and \a q
693 /** \tparam binaryOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
694 * \param q Right operand
695 * \param op Operation of type \a binaryOp
696 */
697 template<typename binaryOp> this_type pwBinaryTr( const this_type &q, binaryOp op ) const {
698 DAI_DEBASSERT( size() == q.size() );
699 TProb<T> r;
700 r._p.reserve( size() );
701 std::transform( _p.begin(), _p.end(), q._p.begin(), back_inserter( r._p ), op );
702 return r;
703 }
704
705 /// Returns sum of \c *this and \a q
706 /** \pre <tt>this->size() == q.size()</tt>
707 */
708 this_type operator+ ( const this_type& q ) const { return pwBinaryTr( q, std::plus<T>() ); }
709
710 /// Return \c *this minus \a q
711 /** \pre <tt>this->size() == q.size()</tt>
712 */
713 this_type operator- ( const this_type& q ) const { return pwBinaryTr( q, std::minus<T>() ); }
714
715 /// Return product of \c *this with \a q
716 /** \pre <tt>this->size() == q.size()</tt>
717 */
718 this_type operator* ( const this_type &q ) const { return pwBinaryTr( q, std::multiplies<T>() ); }
719
720 /// Returns quotient of \c *this with \a q, where division by 0 yields 0
721 /** \pre <tt>this->size() == q.size()</tt>
722 * \see divided_by(const TProb<T> &)
723 */
724 this_type operator/ ( const this_type &q ) const { return pwBinaryTr( q, fo_divides0<T>() ); }
725
726 /// Pointwise division by \a q, where division by 0 yields +Inf
727 /** \pre <tt>this->size() == q.size()</tt>
728 * \see operator/(const TProb<T> &)
729 */
730 this_type divided_by( const this_type &q ) const { return pwBinaryTr( q, std::divides<T>() ); }
731
732 /// Returns \c *this to the power \a q
733 /** \pre <tt>this->size() == q.size()</tt>
734 */
735 this_type operator^ ( const this_type &q ) const { return pwBinaryTr( q, fo_pow<T>() ); }
736 //@}
737
738 /// Performs a generalized inner product, similar to std::inner_product
739 /** \pre <tt>this->size() == q.size()</tt>
740 */
741 template<typename binOp1, typename binOp2> T innerProduct( const this_type &q, T init, binOp1 binaryOp1, binOp2 binaryOp2 ) const {
742 DAI_DEBASSERT( size() == q.size() );
743 return std::inner_product( begin(), end(), q.begin(), init, binaryOp1, binaryOp2 );
744 }
745 };
746
747
748 /// Returns distance between \a p and \a q, measured using distance measure \a dt
749 /** \relates TProb
750 * \pre <tt>this->size() == q.size()</tt>
751 */
752 template<typename T> T dist( const TProb<T> &p, const TProb<T> &q, ProbDistType dt ) {
753 switch( dt ) {
754 case DISTL1:
755 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() );
756 case DISTLINF:
757 return p.innerProduct( q, (T)0, fo_max<T>(), fo_absdiff<T>() );
758 case DISTTV:
759 return p.innerProduct( q, (T)0, std::plus<T>(), fo_absdiff<T>() ) / 2;
760 case DISTKL:
761 return p.innerProduct( q, (T)0, std::plus<T>(), fo_KL<T>() );
762 case DISTHEL:
763 return p.innerProduct( q, (T)0, std::plus<T>(), fo_Hellinger<T>() ) / 2;
764 default:
765 DAI_THROW(UNKNOWN_ENUM_VALUE);
766 return INFINITY;
767 }
768 }
769
770
771 /// Writes a TProb<T> to an output stream
772 /** \relates TProb
773 */
774 template<typename T> std::ostream& operator<< (std::ostream& os, const TProb<T>& p) {
775 os << "(";
776 for( size_t i = 0; i < p.size(); i++ )
777 os << ((i != 0) ? ", " : "") << p.get(i);
778 os << ")";
779 return os;
780 }
781
782
783 /// Returns the pointwise minimum of \a a and \a b
784 /** \relates TProb
785 * \pre <tt>this->size() == q.size()</tt>
786 */
787 template<typename T> TProb<T> min( const TProb<T> &a, const TProb<T> &b ) {
788 return a.pwBinaryTr( b, fo_min<T>() );
789 }
790
791
792 /// Returns the pointwise maximum of \a a and \a b
793 /** \relates TProb
794 * \pre <tt>this->size() == q.size()</tt>
795 */
796 template<typename T> TProb<T> max( const TProb<T> &a, const TProb<T> &b ) {
797 return a.pwBinaryTr( b, fo_max<T>() );
798 }
799
800
801 /// Represents a vector with entries of type dai::Real.
802 typedef TProb<Real> Prob;
803
804
805 } // end of namespace dai
806
807
808 #endif