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
45 /// Real number (alias for double, which could be changed to long double if necessary)
49 template<typename T
> class TProb
;
51 /// Represents a probability measure, with entries of type Real.
52 typedef TProb
<Real
> Prob
;
55 /// Represents a vector with entries of type \a T.
56 /** A TProb<T> is a std::vector<T> with an interface designed for dealing with probability mass functions.
57 * It is mainly used for representing measures on a finite outcome space, e.g., the probability
58 * distribution of a discrete random variable.
59 * \tparam T Should be a scalar that is castable from and to double and should support elementary arithmetic operations.
61 template <typename T
> class TProb
{
67 /// Enumerates different ways of normalizing a probability measure.
69 * - NORMPROB means that the sum of all entries should be 1;
70 * - NORMLINF means that the maximum absolute value of all entries should be 1.
72 typedef enum { NORMPROB
, NORMLINF
} NormType
;
73 /// Enumerates different distance measures between probability measures.
75 * - DISTL1 is the L-1 distance (sum of absolute values of pointwise difference);
76 * - DISTLINF is the L-inf distance (maximum absolute value of pointwise difference);
77 * - DISTTV is the Total Variation distance;
78 * - DISTKL is the Kullback-Leibler distance.
80 typedef enum { DISTL1
, DISTLINF
, DISTTV
, DISTKL
} DistType
;
82 /// Default constructor
85 /// Construct uniform distribution over n outcomes, i.e., a vector of length n with each entry set to 1/n
86 explicit TProb( size_t n
) : _p(std::vector
<T
>(n
, 1.0 / n
)) {}
88 /// Construct vector of length n with each entry set to p
89 explicit TProb( size_t n
, Real p
) : _p(n
, (T
)p
) {}
91 /// Construct vector of length n by copying the elements between p and p+n
92 TProb( size_t n
, const Real
* p
) : _p(p
, p
+ n
) {}
94 /// Returns a const reference to the vector
95 const std::vector
<T
> & p() const { return _p
; }
97 /// Returns a reference to the vector
98 std::vector
<T
> & p() { return _p
; }
100 /// Returns a copy of the i'th entry
101 T
operator[]( size_t i
) const {
109 /// Returns reference to the i'th entry
110 T
& operator[]( size_t i
) { return _p
[i
]; }
112 /// Sets all entries to x
113 TProb
<T
> & fill(T x
) {
114 std::fill( _p
.begin(), _p
.end(), x
);
118 /// Sets all entries to i.i.d. random numbers from a uniform[0,1) distribution
119 TProb
<T
> & randomize() {
120 std::generate(_p
.begin(), _p
.end(), rnd_uniform
);
124 /// Returns length of the vector, i.e., the number of entries
125 size_t size() const {
129 /// Sets entries that are smaller than epsilon to 0
130 TProb
<T
>& makeZero( Real epsilon
) {
131 for( size_t i
= 0; i
< size(); i
++ )
132 if( fabs(_p
[i
]) < epsilon
)
137 /// Sets entries that are smaller than epsilon to epsilon
138 TProb
<T
>& makePositive( Real epsilon
) {
139 for( size_t i
= 0; i
< size(); i
++ )
140 if( (0 < (Real
)_p
[i
]) && ((Real
)_p
[i
] < epsilon
) )
145 /// Multiplies each entry with scalar x
146 TProb
<T
>& operator*= (T x
) {
147 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::multiplies
<T
>(), x
) );
151 /// Returns product of *this with scalar x
152 TProb
<T
> operator* (T x
) const {
153 TProb
<T
> prod( *this );
158 /// Divides each entry by scalar x
159 TProb
<T
>& operator/= (T x
) {
163 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::divides
<T
>(), x
) );
167 /// Returns quotient of *this and scalar x
168 TProb
<T
> operator/ (T x
) const {
169 TProb
<T
> quot( *this );
174 /// Adds scalar x to each entry
175 TProb
<T
>& operator+= (T x
) {
176 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::plus
<T
>(), x
) );
180 /// Returns sum of *this and scalar x
181 TProb
<T
> operator+ (T x
) const {
182 TProb
<T
> sum( *this );
187 /// Subtracts scalar x from each entry
188 TProb
<T
>& operator-= (T x
) {
189 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::minus
<T
>(), x
) );
193 /// Returns difference of *this and scalar x
194 TProb
<T
> operator- (T x
) const {
195 TProb
<T
> diff( *this );
200 /// Lexicographical comparison (sizes should be identical)
201 bool operator<= (const TProb
<T
> & q
) const {
203 assert( size() == q
.size() );
205 for( size_t i
= 0; i
< size(); i
++ )
206 if( !(_p
[i
] <= q
[i
]) )
211 /// Pointwise multiplication with q (sizes should be identical)
212 TProb
<T
>& operator*= (const TProb
<T
> & q
) {
214 assert( size() == q
.size() );
216 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::multiplies
<T
>() );
220 /// Return product of *this with q (sizes should be identical)
221 TProb
<T
> operator* (const TProb
<T
> & q
) const {
223 assert( size() == q
.size() );
225 TProb
<T
> prod( *this );
230 /// Pointwise addition with q (sizes should be identical)
231 TProb
<T
>& operator+= (const TProb
<T
> & q
) {
233 assert( size() == q
.size() );
235 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::plus
<T
>() );
239 /// Returns sum of *this and q (sizes should be identical)
240 TProb
<T
> operator+ (const TProb
<T
> & q
) const {
242 assert( size() == q
.size() );
244 TProb
<T
> sum( *this );
249 /// Pointwise subtraction of q (sizes should be identical)
250 TProb
<T
>& operator-= (const TProb
<T
> & q
) {
252 assert( size() == q
.size() );
254 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::minus
<T
>() );
258 /// Return *this minus q (sizes should be identical)
259 TProb
<T
> operator- (const TProb
<T
> & q
) const {
261 assert( size() == q
.size() );
263 TProb
<T
> diff( *this );
268 /// Pointwise division by q, where division by 0 yields 0 (sizes should be identical)
269 TProb
<T
>& operator/= (const TProb
<T
> & q
) {
271 assert( size() == q
.size() );
273 for( size_t i
= 0; i
< size(); i
++ ) {
282 /// Pointwise division by q, where division by 0 yields +Inf (sizes should be identical)
283 TProb
<T
>& divide (const TProb
<T
> & q
) {
285 assert( size() == q
.size() );
287 std::transform( _p
.begin(), _p
.end(), q
._p
.begin(), _p
.begin(), std::divides
<T
>() );
291 /// Returns quotient of *this with q (sizes should be identical)
292 TProb
<T
> operator/ (const TProb
<T
> & q
) const {
294 assert( size() == q
.size() );
296 TProb
<T
> quot( *this );
301 /// Returns pointwise inverse
302 /** If zero==true; uses 1/0==0, otherwise 1/0==Inf.
304 TProb
<T
> inverse(bool zero
=true) const {
306 inv
._p
.reserve( size() );
308 for( size_t i
= 0; i
< size(); i
++ )
309 inv
._p
.push_back( _p
[i
] == 0.0 ? 0.0 : 1.0 / _p
[i
] );
311 for( size_t i
= 0; i
< size(); i
++ )
312 inv
._p
.push_back( 1.0 / _p
[i
] );
316 /// Raises entries to the power a
317 TProb
<T
>& operator^= (Real a
) {
319 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::bind2nd( std::ptr_fun
<T
, Real
, T
>(std::pow
), a
) );
323 /// Returns *this raised to the power a
324 TProb
<T
> operator^ (Real a
) const {
325 TProb
<T
> power(*this);
330 /// Returns pointwise signum
331 TProb
<T
> sgn() const {
333 x
._p
.reserve( size() );
334 for( size_t i
= 0; i
< size(); i
++ ) {
345 /// Returns pointwise absolute value
346 TProb
<T
> abs() const {
348 x
._p
.reserve( size() );
349 for( size_t i
= 0; i
< size(); i
++ )
350 x
._p
.push_back( _p
[i
] < 0 ? (-p
[i
]) : p
[i
] );
354 /// Applies exp pointwise
355 const TProb
<T
>& takeExp() {
356 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::ptr_fun
<T
, T
>(std::exp
) );
360 /// Applies log pointwise
361 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
363 const TProb
<T
>& takeLog(bool zero
=false) {
365 for( size_t i
= 0; i
< size(); i
++ )
366 _p
[i
] = ( (_p
[i
] == 0.0) ? 0.0 : std::log( _p
[i
] ) );
368 std::transform( _p
.begin(), _p
.end(), _p
.begin(), std::ptr_fun
<T
, T
>(std::log
) );
372 /// Returns pointwise exp
373 TProb
<T
> exp() const {
379 /// Returns pointwise log
380 /** If zero==true, uses log(0)==0; otherwise, log(0)==-Inf.
382 TProb
<T
> log(bool zero
=false) const {
388 /// Returns sum of all entries
390 T Z
= std::accumulate( _p
.begin(), _p
.end(), (T
)0 );
394 /// Returns maximum absolute value of all entries
397 for( size_t i
= 0; i
< size(); i
++ ) {
398 Real mag
= fabs( (Real
) _p
[i
] );
405 /// Returns maximum value of all entries
407 T Z
= *std::max_element( _p
.begin(), _p
.end() );
411 /// Returns minimum value of all entries
413 T Z
= *std::min_element( _p
.begin(), _p
.end() );
417 /// Normalizes vector using the specified norm
418 T
normalize( NormType norm
=NORMPROB
) {
420 if( norm
== NORMPROB
)
422 else if( norm
== NORMLINF
)
431 /// Returns normalized copy of *this, using the specified norm
432 TProb
<T
> normalized( NormType norm
= NORMPROB
) const {
433 TProb
<T
> result(*this);
434 result
.normalize( norm
);
438 /// Returns true if one or more entries are NaN
439 bool hasNaNs() const {
440 return (std::find_if( _p
.begin(), _p
.end(), isnan
) != _p
.end());
443 /// Returns true if one or more entries are negative
444 bool hasNegatives() const {
445 return (std::find_if( _p
.begin(), _p
.end(), std::bind2nd( std::less
<Real
>(), 0.0 ) ) != _p
.end());
448 /// Returns entropy of *this
449 Real
entropy() const {
451 for( size_t i
= 0; i
< size(); i
++ )
452 S
-= (_p
[i
] == 0 ? 0 : _p
[i
] * std::log(_p
[i
]));
458 /// Returns distance of p and q (sizes should be identical), measured using distance measure dt
461 template<typename T
> Real
dist( const TProb
<T
> &p
, const TProb
<T
> &q
, typename TProb
<T
>::DistType dt
) {
463 assert( p
.size() == q
.size() );
467 case TProb
<T
>::DISTL1
:
468 for( size_t i
= 0; i
< p
.size(); i
++ )
469 result
+= fabs((Real
)p
[i
] - (Real
)q
[i
]);
472 case TProb
<T
>::DISTLINF
:
473 for( size_t i
= 0; i
< p
.size(); i
++ ) {
474 Real z
= fabs((Real
)p
[i
] - (Real
)q
[i
]);
480 case TProb
<T
>::DISTTV
:
481 for( size_t i
= 0; i
< p
.size(); i
++ )
482 result
+= fabs((Real
)p
[i
] - (Real
)q
[i
]);
486 case TProb
<T
>::DISTKL
:
487 for( size_t i
= 0; i
< p
.size(); i
++ ) {
489 result
+= p
[i
] * (std::log(p
[i
]) - std::log(q
[i
]));
496 /// Writes a TProb<T> to an output stream
499 template<typename T
> std::ostream
& operator<< (std::ostream
& os
, const TProb
<T
>& P
) {
501 std::copy( P
.p().begin(), P
.p().end(), std::ostream_iterator
<T
>(os
, " ") );
507 /// Returns the TProb<T> containing the pointwise minimum of a and b (which should have equal size)
510 template<typename T
> TProb
<T
> min( const TProb
<T
> &a
, const TProb
<T
> &b
) {
511 assert( a
.size() == b
.size() );
512 TProb
<T
> result( a
.size() );
513 for( size_t i
= 0; i
< a
.size(); i
++ )
522 /// Returns the TProb<T> containing the pointwise maximum of a and b (which should have equal size)
525 template<typename T
> TProb
<T
> max( const TProb
<T
> &a
, const TProb
<T
> &b
) {
526 assert( a
.size() == b
.size() );
527 TProb
<T
> result( a
.size() );
528 for( size_t i
= 0; i
< a
.size(); i
++ )
537 } // end of namespace dai