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 Copyright (C) 2002 Martijn Leisink [martijn@mbfys.kun.nl]
6 Radboud University Nijmegen, The Netherlands
8 This file is part of libDAI.
10 libDAI is free software; you can redistribute it and/or modify
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
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.
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 */
26 /// \file
27 /// \brief Defines TFactor<T> and Factor classes
30 #ifndef __defined_libdai_factor_h
31 #define __defined_libdai_factor_h
34 #include <iostream>
35 #include <cmath>
36 #include <dai/prob.h>
37 #include <dai/varset.h>
38 #include <dai/index.h>
41 namespace dai {
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;
74 public:
75 /// Iterator over factor entries
76 typedef typename TProb<T>::iterator iterator;
78 /// Const iterator over factor entries
79 typedef typename TProb<T>::const_iterator const_iterator;
81 /// Constructs TFactor depending on no variables, with value p
82 TFactor ( Real p = 1.0 ) : _vs(), _p(1,p) {}
84 /// Constructs TFactor depending on variables in ns, with uniform distribution
85 TFactor( const VarSet& ns ) : _vs(ns), _p(_vs.nrStates()) {}
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) {}
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()) {}
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 }
105 /// Constructs TFactor depending on the variable n, with uniform distribution
106 TFactor( const Var& n ) : _vs(n), _p(n.states()) {}
108 /// Copy constructor
109 TFactor( const TFactor<T> &x ) : _vs(x._vs), _p(x._p) {}
111 /// Assignment operator
112 TFactor<T> & operator= (const TFactor<T> &x) {
113 if( this != &x ) {
114 _vs = x._vs;
115 _p = x._p;
116 }
117 return *this;
118 }
120 /// Returns const reference to value vector
121 const TProb<T> & p() const { return _p; }
122 /// Returns reference to value vector
123 TProb<T> & p() { return _p; }
125 /// Returns const reference to variable set
126 const VarSet & vars() const { return _vs; }
128 /// Returns the number of possible joint states of the variables
129 /** \note This is equal to the length of the value vector.
130 */
131 size_t states() const { return _p.size(); }
133 /// Returns a copy of the i'th entry of the value vector
134 T operator[] (size_t i) const { return _p[i]; }
136 /// Returns a reference to the i'th entry of the value vector
137 T& operator[] (size_t i) { return _p[i]; }
139 /// Returns iterator pointing to first entry
140 iterator begin() { return _p.begin(); }
141 /// Returns const iterator pointing to first entry
142 const_iterator begin() const { return _p.begin(); }
143 /// Returns iterator pointing beyond last entry
144 iterator end() { return _p.end(); }
145 /// Returns const iterator pointing beyond last entry
146 const_iterator end() const { return _p.end(); }
148 /// Sets all values to p
149 TFactor<T> & fill (T p) { _p.fill( p ); return(*this); }
151 /// Draws all values i.i.d. from a uniform distribution on [0,1)
152 TFactor<T> & randomize () { _p.randomize(); return(*this); }
155 /// Multiplies *this with scalar t
156 TFactor<T>& operator*= (T t) {
157 _p *= t;
158 return *this;
159 }
161 /// Divides *this by scalar t
162 TFactor<T>& operator/= (T t) {
163 _p /= t;
164 return *this;
165 }
167 /// Adds scalar t to *this
168 TFactor<T>& operator+= (T t) {
169 _p += t;
170 return *this;
171 }
173 /// Subtracts scalar t from *this
174 TFactor<T>& operator-= (T t) {
175 _p -= t;
176 return *this;
177 }
179 /// Raises *this to the power a
180 TFactor<T>& operator^= (Real a) { _p ^= a; return *this; }
183 /// Returns product of *this with scalar t
184 TFactor<T> operator* (T t) const {
185 TFactor<T> result = *this;
186 result.p() *= t;
187 return result;
188 }
190 /// Returns quotient of *this with scalar t
191 TFactor<T> operator/ (T t) const {
192 TFactor<T> result = *this;
193 result.p() /= t;
194 return result;
195 }
197 /// Returns sum of *this and scalar t
198 TFactor<T> operator+ (T t) const {
199 TFactor<T> result(*this);
200 result._p += t;
201 return result;
202 }
204 /// Returns *this minus scalar t
205 TFactor<T> operator- (T t) const {
206 TFactor<T> result(*this);
207 result._p -= t;
208 return result;
209 }
211 /// Returns *this raised to the power a
212 TFactor<T> operator^ (Real a) const {
213 TFactor<T> x;
214 x._vs = _vs;
215 x._p = _p^a;
216 return x;
217 }
219 /// Multiplies *this with the TFactor f
220 TFactor<T>& operator*= (const TFactor<T>& f) {
221 if( f._vs == _vs ) // optimize special case
222 _p *= f._p;
223 else
224 *this = (*this * f);
225 return *this;
226 }
228 /// Divides *this by the TFactor f
229 TFactor<T>& operator/= (const TFactor<T>& f) {
230 if( f._vs == _vs ) // optimize special case
231 _p /= f._p;
232 else
233 *this = (*this / f);
234 return *this;
235 }
237 /// Returns product of *this with the TFactor f
238 /** The product of two factors is defined as follows: if
239 * \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
240 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
241 */
242 TFactor<T> operator* (const TFactor<T>& f) const;
244 /// Returns quotient of *this by the TFactor f
245 /** The quotient of two factors is defined as follows: if
246 * \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
247 * \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]
248 */
249 TFactor<T> operator/ (const TFactor<T>& f) const;
251 /// Adds the TFactor f to *this
252 /** \pre this->vars() == f.vars()
253 */
254 TFactor<T>& operator+= (const TFactor<T>& f) {
255 #ifdef DAI_DEBUG
256 assert( f._vs == _vs );
257 #endif
258 _p += f._p;
259 return *this;
260 }
262 /// Subtracts the TFactor f from *this
263 /** \pre this->vars() == f.vars()
264 */
265 TFactor<T>& operator-= (const TFactor<T>& f) {
266 #ifdef DAI_DEBUG
267 assert( f._vs == _vs );
268 #endif
269 _p -= f._p;
270 return *this;
271 }
273 /// Returns sum of *this and 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 }
285 /// Returns *this minus the TFactor f
286 /** \pre this->vars() == f.vars()
287 */
288 TFactor<T> operator- (const TFactor<T>& f) const {
289 #ifdef DAI_DEBUG
290 assert( f._vs == _vs );
291 #endif
292 TFactor<T> sum(*this);
293 sum._p -= f._p;
294 return sum;
295 }
298 /// Sets all values that are smaller than epsilon to 0
299 TFactor<T>& makeZero( T epsilon ) {
300 _p.makeZero( epsilon );
301 return *this;
302 }
304 /// Sets all values that are smaller than epsilon to epsilon
305 TFactor<T>& makePositive( T epsilon ) {
306 _p.makePositive( epsilon );
307 return *this;
308 }
310 /// Returns pointwise inverse of *this.
311 /** If zero == true, uses 1 / 0 == 0; otherwise 1 / 0 == Inf.
312 */
313 TFactor<T> inverse(bool zero=true) const {
314 TFactor<T> inv;
315 inv._vs = _vs;
316 inv._p = _p.inverse(zero);
317 return inv;
318 }
320 /// Returns pointwise exp of *this
321 TFactor<T> exp() const {
322 TFactor<T> e;
323 e._vs = _vs;
324 e._p = _p.exp();
325 return e;
326 }
328 /// Returns pointwise logarithm of *this
329 /** If zero==true, uses log(0)==0; otherwise, log(0)=-Inf.
330 */
331 TFactor<T> log(bool zero=false) const {
332 TFactor<T> l;
333 l._vs = _vs;
334 l._p = _p.log(zero);
335 return l;
336 }
338 /// Returns pointwise absolute value of *this
339 TFactor<T> abs() const {
340 TFactor<T> e;
341 e._vs = _vs;
342 e._p = _p.abs();
343 return e;
344 }
346 /// Normalizes *this TFactor according to the specified norm
347 T normalize( typename Prob::NormType norm=Prob::NORMPROB ) { return _p.normalize( norm ); }
349 /// Returns a normalized copy of *this, according to the specified norm
350 TFactor<T> normalized( typename Prob::NormType norm=Prob::NORMPROB ) const {
351 TFactor<T> result;
352 result._vs = _vs;
353 result._p = _p.normalized( norm );
354 return result;
355 }
357 /// Returns a slice of this TFactor, where the subset ns is in state nsState
358 /** \pre \a ns sould be a subset of vars()
359 * \pre \a nsState < ns.states()
360 *
361 * The result is a TFactor that depends on the variables in this->vars() except those in \a ns,
362 * obtained by setting the variables in \a ns to the joint state specified by the linear index
363 * \a nsState. Formally, if *this corresponds with the factor \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$,
364 * \f$M \subset L\f$ corresponds with \a ns and \a nsState corresponds with a mapping \f$s\f$ that
365 * 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
366 * returned corresponds with the factor \f$g : \prod_{l \in L \setminus M} X_l \to [0,\infty)\f$
367 * 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$.
368 */
369 TFactor<T> slice( const VarSet& ns, size_t nsState ) const {
370 assert( ns << _vs );
371 VarSet nsrem = _vs / ns;
372 TFactor<T> result( nsrem, T(0) );
374 // OPTIMIZE ME
375 IndexFor i_ns (ns, _vs);
376 IndexFor i_nsrem (nsrem, _vs);
377 for( size_t i = 0; i < states(); i++, ++i_ns, ++i_nsrem )
378 if( (size_t)i_ns == nsState )
379 result._p[i_nsrem] = _p[i];
381 return result;
382 }
384 /// Returns marginal on ns, obtained by summing out all variables except those in ns, and normalizing the result if normed==true
385 TFactor<T> marginal(const VarSet & ns, bool normed=true) const;
387 /// Embeds this factor in a larger VarSet
388 /** \pre vars() should be a subset of ns
389 *
390 * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then
391 * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$.
392 */
393 TFactor<T> embed(const VarSet & ns) const {
394 assert( ns >> _vs );
395 if( _vs == ns )
396 return *this;
397 else
398 return (*this) * TFactor<T>(ns / _vs, 1);
399 }
401 /// Returns true if *this has NaN values
402 bool hasNaNs() const { return _p.hasNaNs(); }
404 /// Returns true if *this has negative values
405 bool hasNegatives() const { return _p.hasNegatives(); }
407 /// Returns total sum of values
408 T totalSum() const { return _p.totalSum(); }
410 /// Returns maximum absolute value
411 T maxAbs() const { return _p.maxAbs(); }
413 /// Returns maximum value
414 T maxVal() const { return _p.maxVal(); }
416 /// Returns minimum value
417 T minVal() const { return _p.minVal(); }
419 /// Returns entropy of *this TFactor
420 Real entropy() const { return _p.entropy(); }
422 /// Returns strength of *this TFactor (between variables i and j), as defined in eq. (52) of [\ref MoK07b]
423 T strength( const Var &i, const Var &j ) const;
424 };
427 template<typename T> TFactor<T> TFactor<T>::marginal(const VarSet & ns, bool normed) const {
428 VarSet res_ns = ns & _vs;
430 TFactor<T> res( res_ns, 0.0 );
432 IndexFor i_res( res_ns, _vs );
433 for( size_t i = 0; i < _p.size(); i++, ++i_res )
434 res._p[i_res] += _p[i];
436 if( normed )
437 res.normalize( Prob::NORMPROB );
439 return res;
440 }
443 template<typename T> TFactor<T> TFactor<T>::operator* (const TFactor<T>& f) const {
444 if( f._vs == _vs ) { // optimizate special case
445 TFactor<T> prod(*this);
446 prod._p *= f._p;
447 return prod;
448 } else {
449 TFactor<T> prod( _vs | f._vs, 0.0 );
451 IndexFor i1(_vs, prod._vs);
452 IndexFor i2(f._vs, prod._vs);
454 for( size_t i = 0; i < prod._p.size(); i++, ++i1, ++i2 )
455 prod._p[i] += _p[i1] * f._p[i2];
457 return prod;
458 }
459 }
462 template<typename T> TFactor<T> TFactor<T>::operator/ (const TFactor<T>& f) const {
463 if( f._vs == _vs ) { // optimizate special case
464 TFactor<T> quot(*this);
465 quot._p /= f._p;
466 return quot;
467 } else {
468 TFactor<T> quot( _vs | f._vs, 0.0 );
470 IndexFor i1(_vs, quot._vs);
471 IndexFor i2(f._vs, quot._vs);
473 for( size_t i = 0; i < quot._p.size(); i++, ++i1, ++i2 )
474 quot._p[i] += _p[i1] / f._p[i2];
476 return quot;
477 }
478 }
481 template<typename T> T TFactor<T>::strength( const Var &i, const Var &j ) const {
482 #ifdef DAI_DEBUG
483 assert( _vs.contains( i ) );
484 assert( _vs.contains( j ) );
485 assert( i != j );
486 #endif
487 VarSet ij(i, j);
489 T max = 0.0;
490 for( size_t alpha1 = 0; alpha1 < i.states(); alpha1++ )
491 for( size_t alpha2 = 0; alpha2 < i.states(); alpha2++ )
492 if( alpha2 != alpha1 )
493 for( size_t beta1 = 0; beta1 < j.states(); beta1++ )
494 for( size_t beta2 = 0; beta2 < j.states(); beta2++ )
495 if( beta2 != beta1 ) {
496 size_t as = 1, bs = 1;
497 if( i < j )
498 bs = i.states();
499 else
500 as = j.states();
501 T f1 = slice( ij, alpha1 * as + beta1 * bs ).p().divide( slice( ij, alpha2 * as + beta1 * bs ).p() ).maxVal();
502 T f2 = slice( ij, alpha2 * as + beta2 * bs ).p().divide( slice( ij, alpha1 * as + beta2 * bs ).p() ).maxVal();
503 T f = f1 * f2;
504 if( f > max )
505 max = f;
506 }
508 return std::tanh( 0.25 * std::log( max ) );
509 }
512 /// Writes a TFactor to an output stream
513 /** \relates TFactor
514 */
515 template<typename T> std::ostream& operator<< (std::ostream& os, const TFactor<T>& P) {
516 os << "(" << P.vars() << ", (";
517 for( size_t i = 0; i < P.states(); i++ )
518 os << (i == 0 ? "" : ", ") << P[i];
519 os << "))";
520 return os;
521 }
524 /// Returns distance between two TFactors f and g, according to the distance measure dt
525 /** \relates TFactor
526 * \pre f.vars() == g.vars()
527 */
528 template<typename T> Real dist( const TFactor<T> &f, const TFactor<T> &g, Prob::DistType dt ) {
529 if( f.vars().empty() || g.vars().empty() )
530 return -1;
531 else {
532 #ifdef DAI_DEBUG
533 assert( f.vars() == g.vars() );
534 #endif
535 return dist( f.p(), g.p(), dt );
536 }
537 }
540 /// Returns the pointwise maximum of two TFactors
541 /** \relates TFactor
542 * \pre f.vars() == g.vars()
543 */
544 template<typename T> TFactor<T> max( const TFactor<T> &f, const TFactor<T> &g ) {
545 assert( f._vs == g._vs );
546 return TFactor<T>( f._vs, min( f.p(), g.p() ) );
547 }
550 /// Returns the pointwise minimum of two TFactors
551 /** \relates TFactor
552 * \pre f.vars() == g.vars()
553 */
554 template<typename T> TFactor<T> min( const TFactor<T> &f, const TFactor<T> &g ) {
555 assert( f._vs == g._vs );
556 return TFactor<T>( f._vs, max( f.p(), g.p() ) );
557 }
560 /// Calculates the mutual information between the two variables that f depends on, under the distribution given by f
561 /** \relates TFactor
562 * \pre f.vars().size() == 2
563 */
564 template<typename T> Real MutualInfo(const TFactor<T> &f) {
565 assert( f.vars().size() == 2 );
566 VarSet::const_iterator it = f.vars().begin();
567 Var i = *it; it++; Var j = *it;
568 TFactor<T> projection = f.marginal(i) * f.marginal(j);
569 return real( dist( f.normalized(), projection, Prob::DISTKL ) );
570 }
573 /// Represents a factor with values of type Real.
574 typedef TFactor<Real> Factor;
577 } // end of namespace dai
580 #endif