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
5 This file is part of libDAI.
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.
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.
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
24 /// \brief Defines TProb<T> and Prob classes
25 /// \todo Rename to Vector<T>
28 #ifndef __defined_libdai_prob_h
29 #define __defined_libdai_prob_h
40 #include <dai/exceptions.h>
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.
52 template <typename T
> class TProb
{
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
;
63 /// Enumerates different ways of normalizing a probability measure.
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.
68 typedef enum { NORMPROB
, NORMLINF
} NormType
;
69 /// Enumerates different distance measures between probability measures.
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.
76 typedef enum { DISTL1
, DISTLINF
, DISTTV
, DISTKL
} DistType
;
78 /// Default constructor
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
)) {}
84 /// Construct vector of length n with each entry set to p
85 explicit TProb( size_t n
, Real p
) : _p(n
, (T
)p
) {}
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.
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
);
99 /// Returns a const reference to the vector
100 const std::vector
<T
> & p() const { return _p
; }
102 /// Returns a reference to the vector
103 std::vector
<T
> & p() { return _p
; }
105 /// Returns a copy of the i'th entry
106 T
operator[]( size_t i
) const {
114 /// Returns reference to the i'th entry
115 T
& operator[]( size_t i
) { return _p
[i
]; }
117 /// Returns iterator pointing to first entry
118 iterator
begin() { return _p
.begin(); }
120 /// Returns const iterator pointing to first entry
121 const_iterator
begin() const { return _p
.begin(); }
123 /// Returns iterator pointing beyond last entry
124 iterator
end() { return _p
.end(); }
126 /// Returns const iterator pointing beyond last entry
127 const_iterator
end() const { return _p
.end(); }
129 /// Sets all entries to x
130 TProb
<T
> & fill(T x
) {
131 std::fill( _p
.begin(), _p
.end(), x
);
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
);
141 /// Returns length of the vector, i.e., the number of entries
142 size_t size() const {
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
)
154 /// Set all entries to 1.0/size()
155 TProb
<T
>& setUniform () {
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
) )
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
) );
174 /// Returns product of *this with scalar x
175 TProb
<T
> operator* (T x
) const {
176 TProb
<T
> prod( *this );
181 /// Divides each entry by scalar x
182 TProb
<T
>& operator/= (T x
) {
186 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::divides
<T
>(), x
) );
190 /// Returns quotient of *this and scalar x
191 TProb
<T
> operator/ (T x
) const {
192 TProb
<T
> quot( *this );
197 /// Adds scalar x to each entry
198 TProb
<T
>& operator+= (T x
) {
199 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::plus
<T
>(), x
) );
203 /// Returns sum of *this and scalar x
204 TProb
<T
> operator+ (T x
) const {
205 TProb
<T
> sum( *this );
210 /// Subtracts scalar x from each entry
211 TProb
<T
>& operator-= (T x
) {
212 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::minus
<T
>(), x
) );
216 /// Returns difference of *this and scalar x
217 TProb
<T
> operator- (T x
) const {
218 TProb
<T
> diff( *this );
223 /// Lexicographical comparison (sizes should be identical)
224 bool operator<= (const TProb
<T
> & q
) const {
226 assert( size() == q
.size() );
228 for( size_t i
= 0; i
< size(); i
++ )
229 if( !(_p
[i
] <= q
[i
]) )
234 /// Pointwise multiplication with q (sizes should be identical)
235 TProb
<T
>& operator*= (const TProb
<T
> & q
) {
237 assert( size() == q
.size() );
239 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::multiplies
<T
>() );
243 /// Return product of *this with q (sizes should be identical)
244 TProb
<T
> operator* (const TProb
<T
> & q
) const {
246 assert( size() == q
.size() );
248 TProb
<T
> prod( *this );
253 /// Pointwise addition with q (sizes should be identical)
254 TProb
<T
>& operator+= (const TProb
<T
> & q
) {
256 assert( size() == q
.size() );
258 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::plus
<T
>() );
262 /// Returns sum of *this and q (sizes should be identical)
263 TProb
<T
> operator+ (const TProb
<T
> & q
) const {
265 assert( size() == q
.size() );
267 TProb
<T
> sum( *this );
272 /// Pointwise subtraction of q (sizes should be identical)
273 TProb
<T
>& operator-= (const TProb
<T
> & q
) {
275 assert( size() == q
.size() );
277 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::minus
<T
>() );
281 /// Return *this minus q (sizes should be identical)
282 TProb
<T
> operator- (const TProb
<T
> & q
) const {
284 assert( size() == q
.size() );
286 TProb
<T
> diff( *this );
291 /// Pointwise division by q, where division by 0 yields 0 (sizes should be identical)
292 TProb
<T
>& operator/= (const TProb
<T
> & q
) {
294 assert( size() == q
.size() );
296 for( size_t i
= 0; i
< size(); i
++ ) {
305 /// Pointwise division by q, where division by 0 yields +Inf (sizes should be identical)
306 TProb
<T
>& divide (const TProb
<T
> & q
) {
308 assert( size() == q
.size() );
310 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::divides
<T
>() );
314 /// Returns quotient of *this with q (sizes should be identical)
315 TProb
<T
> operator/ (const TProb
<T
> & q
) const {
317 assert( size() == q
.size() );
319 TProb
<T
> quot( *this );
324 /// Returns pointwise inverse
325 /** If zero==true; uses 1/0==0, otherwise 1/0==Inf.
327 TProb
<T
> inverse(bool zero
=true) const {
329 inv
._p
.reserve( size() );
331 for( size_t i
= 0; i
< size(); i
++ )
332 inv
._p
.push_back( _p
[i
] == 0.0 ? 0.0 : 1.0 / _p
[i
] );
334 for( size_t i
= 0; i
< size(); i
++ )
335 inv
._p
.push_back( 1.0 / _p
[i
] );
339 /// Raises entries to the power a
340 TProb
<T
>& operator^= (Real a
) {
342 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::ptr_fun
<T
, Real
, T
>(std::pow
), a
) );
346 /// Returns *this raised to the power a
347 TProb
<T
> operator^ (Real a
) const {
348 TProb
<T
> power(*this);
353 /// Returns pointwise signum
354 TProb
<T
> sgn() const {
356 x
._p
.reserve( size() );
357 for( size_t i
= 0; i
< size(); i
++ ) {
368 /// Returns pointwise absolute value
369 TProb
<T
> abs() const {
371 x
._p
.reserve( size() );
372 for( size_t i
= 0; i
< size(); i
++ )
373 x
._p
.push_back( _p
[i
] < 0 ? (-_p
[i
]) : _p
[i
] );
377 /// Applies exp pointwise
378 const TProb
<T
>& takeExp() {
379 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::ptr_fun
<T
, T
>(std::exp
) );
383 /// Applies log pointwise
384 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
386 const TProb
<T
>& takeLog(bool zero
=false) {
388 for( size_t i
= 0; i
< size(); i
++ )
389 _p
[i
] = ( (_p
[i
] == 0.0) ? 0.0 : std::log( _p
[i
] ) );
391 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::ptr_fun
<T
, T
>(std::log
) );
395 /// Returns pointwise exp
396 TProb
<T
> exp() const {
402 /// Returns pointwise log
403 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
405 TProb
<T
> log(bool zero
=false) const {
411 /// Returns sum of all entries
413 T Z
= std::accumulate( _p
.begin(), _p
.end(), (T
)0 );
417 /// Return sum of absolute value of all entries
420 for( size_t i
= 0; i
< size(); i
++ )
421 s
+= fabs( (Real
) _p
[i
] );
425 /// Returns maximum absolute value of all entries
428 for( size_t i
= 0; i
< size(); i
++ ) {
429 Real mag
= fabs( (Real
) _p
[i
] );
436 /// Returns maximum value of all entries
438 T Z
= *std::max_element( _p
.begin(), _p
.end() );
442 /// Returns minimum value of all entries
444 T Z
= *std::min_element( _p
.begin(), _p
.end() );
448 /// Returns {arg,}maximum value
449 std::pair
<size_t,T
> argmax() const {
452 for( size_t i
= 1; i
< size(); i
++ ) {
458 return std::make_pair(arg
,max
);
461 /// Normalizes vector using the specified norm
462 T
normalize( NormType norm
=NORMPROB
) {
464 if( norm
== NORMPROB
)
466 else if( norm
== NORMLINF
)
469 DAI_THROW(NOT_NORMALIZABLE
);
475 /// Returns normalized copy of *this, using the specified norm
476 TProb
<T
> normalized( NormType norm
= NORMPROB
) const {
477 TProb
<T
> result(*this);
478 result
.normalize( norm
);
482 /// Returns true if one or more entries are NaN
483 bool hasNaNs() const {
484 bool foundnan
= false;
485 for( typename
std::vector
<T
>::const_iterator x
= _p
.begin(); x
!= _p
.end(); x
++ )
493 /// Returns true if one or more entries are negative
494 bool hasNegatives() const {
495 return (std::find_if( _p
.begin(), _p
.end(), std::bind2nd( std::less
<Real
>(), 0.0 ) ) != _p
.end());
498 /// Returns entropy of *this
499 Real
entropy() const {
501 for( size_t i
= 0; i
< size(); i
++ )
502 S
-= (_p
[i
] == 0 ? 0 : _p
[i
] * std::log(_p
[i
]));
506 /// Returns a random index, according to the (normalized) distribution described by *this
508 double x
= rnd_uniform() * sum();
510 for( size_t i
= 0; i
< size(); i
++ ) {
515 return( size() - 1 );
520 /// Returns distance of p and q (sizes should be identical), measured using distance measure dt
523 template<typename T
> Real
dist( const TProb
<T
> &p
, const TProb
<T
> &q
, typename TProb
<T
>::DistType dt
) {
525 assert( p
.size() == q
.size() );
529 case TProb
<T
>::DISTL1
:
530 for( size_t i
= 0; i
< p
.size(); i
++ )
531 result
+= fabs((Real
)p
[i
] - (Real
)q
[i
]);
534 case TProb
<T
>::DISTLINF
:
535 for( size_t i
= 0; i
< p
.size(); i
++ ) {
536 Real z
= fabs((Real
)p
[i
] - (Real
)q
[i
]);
542 case TProb
<T
>::DISTTV
:
543 for( size_t i
= 0; i
< p
.size(); i
++ )
544 result
+= fabs((Real
)p
[i
] - (Real
)q
[i
]);
548 case TProb
<T
>::DISTKL
:
549 for( size_t i
= 0; i
< p
.size(); i
++ ) {
551 result
+= p
[i
] * (std::log(p
[i
]) - std::log(q
[i
]));
558 /// Writes a TProb<T> to an output stream
561 template<typename T
> std::ostream
& operator<< (std::ostream
& os
, const TProb
<T
>& P
) {
563 std::copy( P
.p().begin(), P
.p().end(), std::ostream_iterator
<T
>(os
, " ") );
569 /// Returns the TProb<T> containing the pointwise minimum of a and b (which should have equal size)
572 template<typename T
> TProb
<T
> min( const TProb
<T
> &a
, const TProb
<T
> &b
) {
573 assert( a
.size() == b
.size() );
574 TProb
<T
> result( a
.size() );
575 for( size_t i
= 0; i
< a
.size(); i
++ )
584 /// Returns the TProb<T> containing the pointwise maximum of a and b (which should have equal size)
587 template<typename T
> TProb
<T
> max( const TProb
<T
> &a
, const TProb
<T
> &b
) {
588 assert( a
.size() == b
.size() );
589 TProb
<T
> result( a
.size() );
590 for( size_t i
= 0; i
< a
.size(); i
++ )
599 /// Represents a vector with entries of type Real.
600 typedef TProb
<Real
> Prob
;
603 } // end of namespace dai