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