Cleaned up error handling by introducing the DAI_THROWE macro.
[libdai.git] / include / dai / factor.h
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
4
5 Copyright (C) 2002 Martijn Leisink [martijn@mbfys.kun.nl]
6 Radboud University Nijmegen, The Netherlands
7
8 This file is part of libDAI.
9
10 libDAI is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
14
15 libDAI is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with libDAI; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25
26 /// \file
27 /// \brief Defines TFactor<T> and Factor classes
28
29
30 #ifndef __defined_libdai_factor_h
31 #define __defined_libdai_factor_h
32
33
34 #include <iostream>
35 #include <functional>
36 #include <cmath>
37 #include <dai/prob.h>
38 #include <dai/varset.h>
39 #include <dai/index.h>
40 #include <dai/util.h>
41
42
43 namespace dai {
44
45
46 /// Function object similar to std::divides(), but different in that dividing by zero results in zero
47 template<typename T> struct divides0 : public std::binary_function<T, T, T> {
48 T operator()(const T& i, const T& j) const {
49 if( j == (T)0 )
50 return (T)0;
51 else
52 return i / j;
53 }
54 };
55
56
57 /// Represents a (probability) factor.
58 /** Mathematically, a \e factor is a function mapping joint states of some
59 * variables to the nonnegative real numbers.
60 * More formally, denoting a discrete variable with label \f$l\f$ by
61 * \f$x_l\f$ and its state space by \f$X_l = \{0,1,\dots,S_l-1\}\f$,
62 * then a factor depending on the variables \f$\{x_l\}_{l\in L}\f$ is
63 * a function \f$f_L : \prod_{l\in L} X_l \to [0,\infty)\f$.
64 *
65 * In libDAI, a factor is represented by a TFactor<\a T> object, which has two
66 * components:
67 * \arg a VarSet, corresponding with the set of variables \f$\{x_l\}_{l\in L}\f$
68 * that the factor depends on;
69 * \arg a TProb<\a T>, a vector containing the value of the factor for each possible
70 * joint state of the variables.
71 *
72 * The factor values are stored in the entries of the TProb<\a T> in a particular
73 * ordering, which is defined by the one-to-one correspondence of a joint state
74 * in \f$\prod_{l\in L} X_l\f$ with a linear index in
75 * \f$\{0,1,\dots,\prod_{l\in L} S_l-1\}\f$ according to the mapping \f$\sigma\f$
76 * induced by VarSet::calcState(const std::map<Var,size_t> &).
77 *
78 * \tparam T Should be a scalar that is castable from and to double and should support elementary arithmetic operations.
79 * \todo Define a better fileformat for .fg files (maybe using XML)?
80 * \todo Add support for sparse factors.
81 */
82 template <typename T> class TFactor {
83 private:
84 VarSet _vs;
85 TProb<T> _p;
86
87 public:
88 /// Iterator over factor entries
89 typedef typename TProb<T>::iterator iterator;
90
91 /// Const iterator over factor entries
92 typedef typename TProb<T>::const_iterator const_iterator;
93
94 /// Constructs TFactor depending on no variables, with value p
95 TFactor ( Real p = 1.0 ) : _vs(), _p(1,p) {}
96
97 /// Constructs TFactor depending on variables in ns, with uniform distribution
98 TFactor( const VarSet& ns ) : _vs(ns), _p(_vs.nrStates()) {}
99
100 /// Constructs TFactor depending on variables in ns, with all values set to p
101 TFactor( const VarSet& ns, Real p ) : _vs(ns), _p(_vs.nrStates(),p) {}
102
103 /// Constructs TFactor depending on variables in ns, copying the values from the range starting at begin
104 /** \param ns contains the variables that the new TFactor should depend on.
105 * \tparam Iterator Iterates over instances of type T; should support addition of size_t.
106 * \param begin Points to first element to be added.
107 */
108 template<typename TIterator>
109 TFactor( const VarSet& ns, TIterator begin ) : _vs(ns), _p(begin, begin + _vs.nrStates(), _vs.nrStates()) {}
110
111 /// Constructs TFactor depending on variables in ns, with values set to the TProb p
112 TFactor( const VarSet& ns, const TProb<T>& p ) : _vs(ns), _p(p) {
113 DAI_DEBASSERT( _vs.nrStates() == _p.size() );
114 }
115
116 /// Constructs TFactor depending on the variable n, with uniform distribution
117 TFactor( const Var& n ) : _vs(n), _p(n.states()) {}
118
119 /// Returns const reference to value vector
120 const TProb<T> & p() const { return _p; }
121 /// Returns reference to value vector
122 TProb<T> & p() { return _p; }
123
124 /// Returns const reference to variable set
125 const VarSet & vars() const { return _vs; }
126
127 /// Returns the number of possible joint states of the variables
128 /** \note This is equal to the length of the value vector.
129 */
130 size_t states() const { return _p.size(); }
131
132 /// Returns a copy of the i'th entry of the value vector
133 T operator[] (size_t i) const { return _p[i]; }
134
135 /// Returns a reference to the i'th entry of the value vector
136 T& operator[] (size_t i) { return _p[i]; }
137
138 /// Returns iterator pointing to first entry
139 iterator begin() { return _p.begin(); }
140 /// Returns const iterator pointing to first entry
141 const_iterator begin() const { return _p.begin(); }
142 /// Returns iterator pointing beyond last entry
143 iterator end() { return _p.end(); }
144 /// Returns const iterator pointing beyond last entry
145 const_iterator end() const { return _p.end(); }
146
147 /// Sets all values to p
148 TFactor<T> & fill (T p) { _p.fill( p ); return(*this); }
149
150 /// Draws all values i.i.d. from a uniform distribution on [0,1)
151 TFactor<T> & randomize () { _p.randomize(); return(*this); }
152
153
154 /// Multiplies *this with scalar t
155 TFactor<T>& operator*= (T t) {
156 _p *= t;
157 return *this;
158 }
159
160 /// Divides *this by scalar t
161 TFactor<T>& operator/= (T t) {
162 _p /= t;
163 return *this;
164 }
165
166 /// Adds scalar t to *this
167 TFactor<T>& operator+= (T t) {
168 _p += t;
169 return *this;
170 }
171
172 /// Subtracts scalar t from *this
173 TFactor<T>& operator-= (T t) {
174 _p -= t;
175 return *this;
176 }
177
178 /// Raises *this to the power a
179 TFactor<T>& operator^= (Real a) { _p ^= a; return *this; }
180
181
182 /// Returns product of *this with scalar t
183 TFactor<T> operator* (T t) const {
184 TFactor<T> result = *this;
185 result.p() *= t;
186 return result;
187 }
188
189 /// Returns quotient of *this with scalar t
190 TFactor<T> operator/ (T t) const {
191 TFactor<T> result = *this;
192 result.p() /= t;
193 return result;
194 }
195
196 /// Returns sum of *this and scalar t
197 TFactor<T> operator+ (T t) const {
198 TFactor<T> result(*this);
199 result._p += t;
200 return result;
201 }
202
203 /// Returns *this minus scalar t
204 TFactor<T> operator- (T t) const {
205 TFactor<T> result(*this);
206 result._p -= t;
207 return result;
208 }
209
210 /// Returns *this raised to the power a
211 TFactor<T> operator^ (Real a) const {
212 TFactor<T> x;
213 x._vs = _vs;
214 x._p = _p^a;
215 return x;
216 }
217
218 /// Multiplies *this with the TFactor f
219 TFactor<T>& operator*= (const TFactor<T>& f) {
220 if( f._vs == _vs ) // optimize special case
221 _p *= f._p;
222 else
223 *this = (*this * f);
224 return *this;
225 }
226
227 /// Divides *this by the TFactor f
228 TFactor<T>& operator/= (const TFactor<T>& f) {
229 if( f._vs == _vs ) // optimize special case
230 _p /= f._p;
231 else
232 *this = (*this / f);
233 return *this;
234 }
235
236 /// Adds the TFactor f to *this
237 TFactor<T>& operator+= (const TFactor<T>& f) {
238 if( f._vs == _vs ) // optimize special case
239 _p += f._p;
240 else
241 *this = (*this + f);
242 return *this;
243 }
244
245 /// Subtracts the TFactor f from *this
246 TFactor<T>& operator-= (const TFactor<T>& f) {
247 if( f._vs == _vs ) // optimize special case
248 _p -= f._p;
249 else
250 *this = (*this - f);
251 return *this;
252 }
253
254 /// Returns product of *this with the TFactor f
255 /** The product of two factors is defined as follows: if
256 * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
257 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
258 */
259 TFactor<T> operator* (const TFactor<T>& f) const {
260 return pointwiseOp(*this,f,std::multiplies<T>());
261 }
262
263 /// Returns quotient of *this by the TFactor f
264 /** The quotient of two factors is defined as follows: if
265 * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
266 * \f[\frac{f}{g} : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto \frac{f(x_L)}{g(x_M)}.\f]
267 */
268 TFactor<T> operator/ (const TFactor<T>& f) const {
269 return pointwiseOp(*this,f,divides0<T>());
270 }
271
272 /// Returns sum of *this and the TFactor f
273 /** The sum of two factors is defined as follows: if
274 * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
275 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
276 */
277 TFactor<T> operator+ (const TFactor<T>& f) const {
278 return pointwiseOp(*this,f,std::plus<T>());
279 }
280
281 /// Returns *this minus the TFactor f
282 /** The difference of two factors is defined as follows: if
283 * \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$g : \prod_{m\in M} X_m \to [0,\infty)\f$, then
284 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
285 */
286 TFactor<T> operator- (const TFactor<T>& f) const {
287 return pointwiseOp(*this,f,std::minus<T>());
288 }
289
290
291 /// Sets all values that are smaller than epsilon to 0
292 TFactor<T>& makeZero( T epsilon ) {
293 _p.makeZero( epsilon );
294 return *this;
295 }
296
297 /// Sets all values that are smaller than epsilon to epsilon
298 TFactor<T>& makePositive( T epsilon ) {
299 _p.makePositive( epsilon );
300 return *this;
301 }
302
303 /// Returns pointwise inverse of *this.
304 /** If zero == true, uses 1 / 0 == 0; otherwise 1 / 0 == Inf.
305 */
306 TFactor<T> inverse(bool zero=true) const {
307 TFactor<T> inv;
308 inv._vs = _vs;
309 inv._p = _p.inverse(zero);
310 return inv;
311 }
312
313 /// Returns pointwise exp of *this
314 TFactor<T> exp() const {
315 TFactor<T> e;
316 e._vs = _vs;
317 e._p = _p.exp();
318 return e;
319 }
320
321 /// Returns pointwise logarithm of *this
322 /** If zero==true, uses log(0)==0; otherwise, log(0)=-Inf.
323 */
324 TFactor<T> log(bool zero=false) const {
325 TFactor<T> l;
326 l._vs = _vs;
327 l._p = _p.log(zero);
328 return l;
329 }
330
331 /// Returns pointwise absolute value of *this
332 TFactor<T> abs() const {
333 TFactor<T> e;
334 e._vs = _vs;
335 e._p = _p.abs();
336 return e;
337 }
338
339 /// Normalizes *this TFactor according to the specified norm
340 T normalize( typename Prob::NormType norm=Prob::NORMPROB ) { return _p.normalize( norm ); }
341
342 /// Returns a normalized copy of *this, according to the specified norm
343 TFactor<T> normalized( typename Prob::NormType norm=Prob::NORMPROB ) const {
344 TFactor<T> result;
345 result._vs = _vs;
346 result._p = _p.normalized( norm );
347 return result;
348 }
349
350 /// Returns a slice of this TFactor, where the subset ns is in state nsState
351 /** \pre \a ns sould be a subset of vars()
352 * \pre \a nsState < ns.states()
353 *
354 * The result is a TFactor that depends on the variables in this->vars() except those in \a ns,
355 * obtained by setting the variables in \a ns to the joint state specified by the linear index
356 * \a nsState. Formally, if *this corresponds with the factor \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$,
357 * \f$M \subset L\f$ corresponds with \a ns and \a nsState corresponds with a mapping \f$s\f$ that
358 * maps a variable \f$x_m\f$ with \f$m\in M\f$ to its state \f$s(x_m) \in X_m\f$, then the slice
359 * returned corresponds with the factor \f$g : \prod_{l \in L \setminus M} X_l \to [0,\infty)\f$
360 * defined by \f$g(\{x_l\}_{l\in L \setminus M}) = f(\{x_l\}_{l\in L \setminus M}, \{s(x_m)\}_{m\in M})\f$.
361 */
362 TFactor<T> slice( const VarSet& ns, size_t nsState ) const {
363 assert( ns << _vs );
364 VarSet nsrem = _vs / ns;
365 TFactor<T> result( nsrem, T(0) );
366
367 // OPTIMIZE ME
368 IndexFor i_ns (ns, _vs);
369 IndexFor i_nsrem (nsrem, _vs);
370 for( size_t i = 0; i < states(); i++, ++i_ns, ++i_nsrem )
371 if( (size_t)i_ns == nsState )
372 result._p[i_nsrem] = _p[i];
373
374 return result;
375 }
376
377 /// Returns marginal on ns, obtained by summing out all variables except those in ns, and normalizing the result if normed==true
378 TFactor<T> marginal(const VarSet & ns, bool normed=true) const;
379
380 /// Returns max-marginal on ns, obtained by maximizing all variables except those in ns, and normalizing the result if normed==true
381 TFactor<T> maxMarginal(const VarSet & ns, bool normed=true) const;
382
383 /// Embeds this factor in a larger VarSet
384 /** \pre vars() should be a subset of ns
385 *
386 * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then
387 * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$.
388 */
389 TFactor<T> embed(const VarSet & ns) const {
390 assert( ns >> _vs );
391 if( _vs == ns )
392 return *this;
393 else
394 return (*this) * TFactor<T>(ns / _vs, (T)1);
395 }
396
397 /// Returns true if *this has NaN values
398 bool hasNaNs() const { return _p.hasNaNs(); }
399
400 /// Returns true if *this has negative values
401 bool hasNegatives() const { return _p.hasNegatives(); }
402
403 /// Returns total sum of values
404 T sum() const { return _p.sum(); }
405
406 /// Returns maximum absolute value
407 T maxAbs() const { return _p.maxAbs(); }
408
409 /// Returns maximum value
410 T max() const { return _p.max(); }
411
412 /// Returns minimum value
413 T min() const { return _p.min(); }
414
415 /// Returns entropy of *this TFactor
416 Real entropy() const { return _p.entropy(); }
417
418 /// Returns strength of *this TFactor (between variables i and j), as defined in eq. (52) of [\ref MoK07b]
419 T strength( const Var &i, const Var &j ) const;
420 };
421
422
423 template<typename T> TFactor<T> TFactor<T>::marginal(const VarSet & ns, bool normed) const {
424 VarSet res_ns = ns & _vs;
425
426 TFactor<T> res( res_ns, 0.0 );
427
428 IndexFor i_res( res_ns, _vs );
429 for( size_t i = 0; i < _p.size(); i++, ++i_res )
430 res._p[i_res] += _p[i];
431
432 if( normed )
433 res.normalize( Prob::NORMPROB );
434
435 return res;
436 }
437
438
439 template<typename T> TFactor<T> TFactor<T>::maxMarginal(const VarSet & ns, bool normed) const {
440 VarSet res_ns = ns & _vs;
441
442 TFactor<T> res( res_ns, 0.0 );
443
444 IndexFor i_res( res_ns, _vs );
445 for( size_t i = 0; i < _p.size(); i++, ++i_res )
446 if( _p[i] > res._p[i_res] )
447 res._p[i_res] = _p[i];
448
449 if( normed )
450 res.normalize( Prob::NORMPROB );
451
452 return res;
453 }
454
455
456 /// Apply binary operator pointwise on two factors
457 template<typename T, typename binaryOp> TFactor<T> pointwiseOp( const TFactor<T> &f, const TFactor<T> &g, binaryOp op ) {
458 if( f.vars() == g.vars() ) { // optimizate special case
459 TFactor<T> result(f);
460 for( size_t i = 0; i < result.states(); i++ )
461 result[i] = op( result[i], g[i] );
462 return result;
463 } else {
464 TFactor<T> result( f.vars() | g.vars(), 0.0 );
465
466 IndexFor i1(f.vars(), result.vars());
467 IndexFor i2(g.vars(), result.vars());
468
469 for( size_t i = 0; i < result.states(); i++, ++i1, ++i2 )
470 result[i] = op( f[i1], g[i2] );
471
472 return result;
473 }
474 }
475
476
477 template<typename T> T TFactor<T>::strength( const Var &i, const Var &j ) const {
478 DAI_DEBASSERT( _vs.contains( i ) );
479 DAI_DEBASSERT( _vs.contains( j ) );
480 DAI_DEBASSERT( i != j );
481 VarSet ij(i, j);
482
483 T max = 0.0;
484 for( size_t alpha1 = 0; alpha1 < i.states(); alpha1++ )
485 for( size_t alpha2 = 0; alpha2 < i.states(); alpha2++ )
486 if( alpha2 != alpha1 )
487 for( size_t beta1 = 0; beta1 < j.states(); beta1++ )
488 for( size_t beta2 = 0; beta2 < j.states(); beta2++ )
489 if( beta2 != beta1 ) {
490 size_t as = 1, bs = 1;
491 if( i < j )
492 bs = i.states();
493 else
494 as = j.states();
495 T f1 = slice( ij, alpha1 * as + beta1 * bs ).p().divide( slice( ij, alpha2 * as + beta1 * bs ).p() ).max();
496 T f2 = slice( ij, alpha2 * as + beta2 * bs ).p().divide( slice( ij, alpha1 * as + beta2 * bs ).p() ).max();
497 T f = f1 * f2;
498 if( f > max )
499 max = f;
500 }
501
502 return std::tanh( 0.25 * std::log( max ) );
503 }
504
505
506 /// Writes a TFactor to an output stream
507 /** \relates TFactor
508 */
509 template<typename T> std::ostream& operator<< (std::ostream& os, const TFactor<T>& P) {
510 os << "(" << P.vars() << ", (";
511 for( size_t i = 0; i < P.states(); i++ )
512 os << (i == 0 ? "" : ", ") << P[i];
513 os << "))";
514 return os;
515 }
516
517
518 /// Returns distance between two TFactors f and g, according to the distance measure dt
519 /** \relates TFactor
520 * \pre f.vars() == g.vars()
521 */
522 template<typename T> Real dist( const TFactor<T> &f, const TFactor<T> &g, Prob::DistType dt ) {
523 if( f.vars().empty() || g.vars().empty() )
524 return -1;
525 else {
526 DAI_DEBASSERT( f.vars() == g.vars() );
527 return dist( f.p(), g.p(), dt );
528 }
529 }
530
531
532 /// Returns the pointwise maximum of two TFactors
533 /** \relates TFactor
534 * \pre f.vars() == g.vars()
535 */
536 template<typename T> TFactor<T> max( const TFactor<T> &f, const TFactor<T> &g ) {
537 assert( f._vs == g._vs );
538 return TFactor<T>( f._vs, min( f.p(), g.p() ) );
539 }
540
541
542 /// Returns the pointwise minimum of two TFactors
543 /** \relates TFactor
544 * \pre f.vars() == g.vars()
545 */
546 template<typename T> TFactor<T> min( const TFactor<T> &f, const TFactor<T> &g ) {
547 assert( f._vs == g._vs );
548 return TFactor<T>( f._vs, max( f.p(), g.p() ) );
549 }
550
551
552 /// Calculates the mutual information between the two variables that f depends on, under the distribution given by f
553 /** \relates TFactor
554 * \pre f.vars().size() == 2
555 */
556 template<typename T> Real MutualInfo(const TFactor<T> &f) {
557 assert( f.vars().size() == 2 );
558 VarSet::const_iterator it = f.vars().begin();
559 Var i = *it; it++; Var j = *it;
560 TFactor<T> projection = f.marginal(i) * f.marginal(j);
561 return dist( f.normalized(), projection, Prob::DISTKL );
562 }
563
564
565 /// Represents a factor with values of type Real.
566 typedef TFactor<Real> Factor;
567
568
569 } // end of namespace dai
570
571
572 #endif