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