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