1 /* This file is part of libDAI - http://www.libdai.org/
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
7 * Copyright (C) 2002 Martijn Leisink [martijn@mbfys.kun.nl]
8 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
9 * Copyright (C) 2002-2007 Radboud University Nijmegen, The Netherlands
14 /// \brief Defines TFactor<T> and Factor classes
17 #ifndef __defined_libdai_factor_h
18 #define __defined_libdai_factor_h
25 #include <dai/varset.h>
26 #include <dai/index.h>
33 // Function object similar to std::divides(), but different in that dividing by zero results in zero
34 template<typename T
> struct divides0
: public std::binary_function
<T
, T
, T
> {
35 // Returns (j == 0 ? 0 : (i/j))
36 T
operator()( const T
&i
, const T
&j
) const {
45 /// Represents a (probability) factor.
46 /** Mathematically, a \e factor is a function mapping joint states of some
47 * variables to the nonnegative real numbers.
48 * More formally, denoting a discrete variable with label \f$l\f$ by
49 * \f$x_l\f$ and its state space by \f$X_l = \{0,1,\dots,S_l-1\}\f$,
50 * then a factor depending on the variables \f$\{x_l\}_{l\in L}\f$ is
51 * a function \f$f_L : \prod_{l\in L} X_l \to [0,\infty)\f$.
53 * In libDAI, a factor is represented by a TFactor<\a T> object, which has two
55 * \arg a VarSet, corresponding with the set of variables \f$\{x_l\}_{l\in L}\f$
56 * that the factor depends on;
57 * \arg a TProb<\a T>, a vector containing the value of the factor for each possible
58 * joint state of the variables.
60 * The factor values are stored in the entries of the TProb<\a T> in a particular
61 * ordering, which is defined by the one-to-one correspondence of a joint state
62 * in \f$\prod_{l\in L} X_l\f$ with a linear index in
63 * \f$\{0,1,\dots,\prod_{l\in L} S_l-1\}\f$ according to the mapping \f$\sigma\f$
64 * induced by VarSet::calcState(const std::map<Var,size_t> &).
66 * \tparam T Should be a scalar that is castable from and to double and should support elementary arithmetic operations.
67 * \todo Define a better fileformat for .fg files (maybe using XML)?
68 * \todo Add support for sparse factors.
70 template <typename T
> class TFactor
{
76 /// Iterator over factor entries
77 typedef typename TProb
<T
>::iterator iterator
;
79 /// Const iterator over factor entries
80 typedef typename TProb
<T
>::const_iterator const_iterator
;
82 /// Constructs TFactor depending on no variables, with value p
83 TFactor ( Real p
= 1.0 ) : _vs(), _p(1,p
) {}
85 /// Constructs TFactor depending on variables in vars, with uniform distribution
86 TFactor( const VarSet
& vars
) : _vs(vars
), _p(_vs
.nrStates()) {}
88 /// Constructs TFactor depending on variables in vars, with all values set to p
89 TFactor( const VarSet
& vars
, Real p
) : _vs(vars
), _p(_vs
.nrStates(),p
) {}
91 /// Constructs TFactor depending on variables in vars, copying the values from the range starting at begin
92 /** \param vars contains the variables that the new TFactor should depend on.
93 * \tparam Iterator Iterates over instances of type T; should support addition of size_t.
94 * \param begin Points to first element to be added.
96 template<typename TIterator
>
97 TFactor( const VarSet
& vars
, TIterator begin
) : _vs(vars
), _p(begin
, begin
+ _vs
.nrStates(), _vs
.nrStates()) {}
99 /// Constructs TFactor depending on variables in vars, with values set to the TProb p
100 TFactor( const VarSet
& vars
, const TProb
<T
> &p
) : _vs(vars
), _p(p
) {
101 DAI_DEBASSERT( _vs
.nrStates() == _p
.size() );
104 /// Constructs TFactor depending on variables in vars, permuting the values given in TProb p
105 TFactor( const std::vector
<Var
> &vars
, const std::vector
<T
> &p
) : _vs(vars
.begin(), vars
.end(), vars
.size()), _p(p
.size()) {
106 Permute
permindex(vars
);
107 for( size_t li
= 0; li
< p
.size(); ++li
)
108 _p
[permindex
.convert_linear_index(li
)] = p
[li
];
111 /// Constructs TFactor depending on the variable v, with uniform distribution
112 TFactor( const Var
&v
) : _vs(v
), _p(v
.states()) {}
114 /// Returns const reference to value vector
115 const TProb
<T
>& p() const { return _p
; }
116 /// Returns reference to value vector
117 TProb
<T
>& p() { return _p
; }
119 /// Returns const reference to variable set
120 const VarSet
& vars() const { return _vs
; }
122 /// Returns the number of possible joint states of the variables
123 /** \note This is equal to the length of the value vector.
125 size_t states() const { return _p
.size(); }
127 /// Returns a copy of the i'th entry of the value vector
128 T
operator[] (size_t i
) const { return _p
[i
]; }
130 /// Returns a reference to the i'th entry of the value vector
131 T
& operator[] (size_t i
) { return _p
[i
]; }
133 /// Returns iterator pointing to first entry
134 iterator
begin() { return _p
.begin(); }
135 /// Returns const iterator pointing to first entry
136 const_iterator
begin() const { return _p
.begin(); }
137 /// Returns iterator pointing beyond last entry
138 iterator
end() { return _p
.end(); }
139 /// Returns const iterator pointing beyond last entry
140 const_iterator
end() const { return _p
.end(); }
142 /// Sets all values to p
143 TFactor
<T
> & fill (T p
) { _p
.fill( p
); return(*this); }
145 /// Draws all values i.i.d. from a uniform distribution on [0,1)
146 TFactor
<T
> & randomize () { _p
.randomize(); return(*this); }
149 /// Multiplies *this with scalar t
150 TFactor
<T
>& operator*= (T t
) {
155 /// Divides *this by scalar t
156 TFactor
<T
>& operator/= (T t
) {
161 /// Adds scalar t to *this
162 TFactor
<T
>& operator+= (T t
) {
167 /// Subtracts scalar t from *this
168 TFactor
<T
>& operator-= (T t
) {
173 /// Raises *this to the power a
174 TFactor
<T
>& operator^= (Real a
) { _p
^= a
; return *this; }
177 /// Returns product of *this with scalar t
178 TFactor
<T
> operator* (T t
) const {
179 TFactor
<T
> result
= *this;
184 /// Returns quotient of *this with scalar t
185 TFactor
<T
> operator/ (T t
) const {
186 TFactor
<T
> result
= *this;
191 /// Returns sum of *this and scalar t
192 TFactor
<T
> operator+ (T t
) const {
193 TFactor
<T
> result(*this);
198 /// Returns *this minus scalar t
199 TFactor
<T
> operator- (T t
) const {
200 TFactor
<T
> result(*this);
205 /// Returns *this raised to the power a
206 TFactor
<T
> operator^ (Real a
) const {
213 /// Multiplies *this with the TFactor f
214 TFactor
<T
>& operator*= (const TFactor
<T
>& f
) {
215 if( f
._vs
== _vs
) // optimize special case
222 /// Divides *this by the TFactor f
223 TFactor
<T
>& operator/= (const TFactor
<T
>& f
) {
224 if( f
._vs
== _vs
) // optimize special case
231 /// Adds the TFactor f to *this
232 TFactor
<T
>& operator+= (const TFactor
<T
>& f
) {
233 if( f
._vs
== _vs
) // optimize special case
240 /// Subtracts the TFactor f from *this
241 TFactor
<T
>& operator-= (const TFactor
<T
>& f
) {
242 if( f
._vs
== _vs
) // optimize special case
249 /// Returns product of *this with the TFactor f
250 /** The product of two factors is defined as follows: if
251 * \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
252 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
254 TFactor
<T
> operator* (const TFactor
<T
>& f
) const {
255 return pointwiseOp(*this,f
,std::multiplies
<T
>());
258 /// Returns quotient of *this by the TFactor f
259 /** The quotient of two factors is defined as follows: if
260 * \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
261 * \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]
263 TFactor
<T
> operator/ (const TFactor
<T
>& f
) const {
264 return pointwiseOp(*this,f
,divides0
<T
>());
267 /// Returns sum of *this and the TFactor f
268 /** The sum of two factors is defined as follows: if
269 * \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
270 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
272 TFactor
<T
> operator+ (const TFactor
<T
>& f
) const {
273 return pointwiseOp(*this,f
,std::plus
<T
>());
276 /// Returns *this minus the TFactor f
277 /** The difference of two factors is defined as follows: if
278 * \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
279 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
281 TFactor
<T
> operator- (const TFactor
<T
>& f
) const {
282 return pointwiseOp(*this,f
,std::minus
<T
>());
286 /// Sets all values that are smaller than epsilon to 0
287 TFactor
<T
>& makeZero( T epsilon
) {
288 _p
.makeZero( epsilon
);
292 /// Sets all values that are smaller than epsilon to epsilon
293 TFactor
<T
>& makePositive( T epsilon
) {
294 _p
.makePositive( epsilon
);
298 /// Returns pointwise inverse of *this.
299 /** If zero == true, uses 1 / 0 == 0; otherwise 1 / 0 == Inf.
301 TFactor
<T
> inverse(bool zero
=true) const {
304 inv
._p
= _p
.inverse(zero
);
308 /// Returns pointwise exp of *this
309 TFactor
<T
> exp() const {
316 /// Returns pointwise logarithm of *this
317 /** If zero==true, uses log(0)==0; otherwise, log(0)=-Inf.
319 TFactor
<T
> log(bool zero
=false) const {
326 /// Returns pointwise absolute value of *this
327 TFactor
<T
> abs() const {
334 /// Normalizes *this TFactor according to the specified norm
335 T
normalize( typename
Prob::NormType norm
=Prob::NORMPROB
) { return _p
.normalize( norm
); }
337 /// Returns a normalized copy of *this, according to the specified norm
338 TFactor
<T
> normalized( typename
Prob::NormType norm
=Prob::NORMPROB
) const {
341 result
._p
= _p
.normalized( norm
);
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()
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$.
357 TFactor
<T
> slice( const VarSet
& ns
, size_t nsState
) const {
358 DAI_ASSERT( ns
<< _vs
);
359 VarSet nsrem
= _vs
/ ns
;
360 TFactor
<T
> result( nsrem
, T(0) );
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
];
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;
375 /// Returns max-marginal on ns, obtained by maximizing all variables except those in ns, and normalizing the result if normed==true
376 TFactor
<T
> maxMarginal(const VarSet
& ns
, bool normed
=true) const;
378 /// Embeds this factor in a larger VarSet
379 /** \pre vars() should be a subset of ns
381 * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then
382 * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$.
384 TFactor
<T
> embed(const VarSet
& ns
) const {
385 DAI_ASSERT( ns
>> _vs
);
389 return (*this) * TFactor
<T
>(ns
/ _vs
, (T
)1);
392 /// Returns true if *this has NaN values
393 bool hasNaNs() const { return _p
.hasNaNs(); }
395 /// Returns true if *this has negative values
396 bool hasNegatives() const { return _p
.hasNegatives(); }
398 /// Returns total sum of values
399 T
sum() const { return _p
.sum(); }
401 /// Returns maximum absolute value
402 T
maxAbs() const { return _p
.maxAbs(); }
404 /// Returns maximum value
405 T
max() const { return _p
.max(); }
407 /// Returns minimum value
408 T
min() const { return _p
.min(); }
410 /// Returns entropy of *this TFactor
411 Real
entropy() const { return _p
.entropy(); }
413 /// Returns strength of *this TFactor (between variables i and j), as defined in eq. (52) of [\ref MoK07b]
414 T
strength( const Var
&i
, const Var
&j
) const;
418 template<typename T
> TFactor
<T
> TFactor
<T
>::marginal(const VarSet
& ns
, bool normed
) const {
419 VarSet res_ns
= ns
& _vs
;
421 TFactor
<T
> res( res_ns
, 0.0 );
423 IndexFor
i_res( res_ns
, _vs
);
424 for( size_t i
= 0; i
< _p
.size(); i
++, ++i_res
)
425 res
._p
[i_res
] += _p
[i
];
428 res
.normalize( Prob::NORMPROB
);
434 template<typename T
> TFactor
<T
> TFactor
<T
>::maxMarginal(const VarSet
& ns
, bool normed
) const {
435 VarSet res_ns
= ns
& _vs
;
437 TFactor
<T
> res( res_ns
, 0.0 );
439 IndexFor
i_res( res_ns
, _vs
);
440 for( size_t i
= 0; i
< _p
.size(); i
++, ++i_res
)
441 if( _p
[i
] > res
._p
[i_res
] )
442 res
._p
[i_res
] = _p
[i
];
445 res
.normalize( Prob::NORMPROB
);
451 /// Apply binary operator pointwise on two factors
452 template<typename T
, typename binaryOp
> TFactor
<T
> pointwiseOp( const TFactor
<T
> &f
, const TFactor
<T
> &g
, binaryOp op
) {
453 if( f
.vars() == g
.vars() ) { // optimizate special case
454 TFactor
<T
> result(f
);
455 for( size_t i
= 0; i
< result
.states(); i
++ )
456 result
[i
] = op( result
[i
], g
[i
] );
459 TFactor
<T
> result( f
.vars() | g
.vars(), 0.0 );
461 IndexFor
i1(f
.vars(), result
.vars());
462 IndexFor
i2(g
.vars(), result
.vars());
464 for( size_t i
= 0; i
< result
.states(); i
++, ++i1
, ++i2
)
465 result
[i
] = op( f
[i1
], g
[i2
] );
472 template<typename T
> T TFactor
<T
>::strength( const Var
&i
, const Var
&j
) const {
473 DAI_DEBASSERT( _vs
.contains( i
) );
474 DAI_DEBASSERT( _vs
.contains( j
) );
475 DAI_DEBASSERT( i
!= j
);
479 for( size_t alpha1
= 0; alpha1
< i
.states(); alpha1
++ )
480 for( size_t alpha2
= 0; alpha2
< i
.states(); alpha2
++ )
481 if( alpha2
!= alpha1
)
482 for( size_t beta1
= 0; beta1
< j
.states(); beta1
++ )
483 for( size_t beta2
= 0; beta2
< j
.states(); beta2
++ )
484 if( beta2
!= beta1
) {
485 size_t as
= 1, bs
= 1;
490 T f1
= slice( ij
, alpha1
* as
+ beta1
* bs
).p().divide( slice( ij
, alpha2
* as
+ beta1
* bs
).p() ).max();
491 T f2
= slice( ij
, alpha2
* as
+ beta2
* bs
).p().divide( slice( ij
, alpha1
* as
+ beta2
* bs
).p() ).max();
497 return std::tanh( 0.25 * std::log( max
) );
501 /// Writes a TFactor to an output stream
504 template<typename T
> std::ostream
& operator<< (std::ostream
& os
, const TFactor
<T
>& P
) {
505 os
<< "(" << P
.vars() << ", (";
506 for( size_t i
= 0; i
< P
.states(); i
++ )
507 os
<< (i
== 0 ? "" : ", ") << P
[i
];
513 /// Returns distance between two TFactors f and g, according to the distance measure dt
515 * \pre f.vars() == g.vars()
517 template<typename T
> Real
dist( const TFactor
<T
> &f
, const TFactor
<T
> &g
, Prob::DistType dt
) {
518 if( f
.vars().empty() || g
.vars().empty() )
521 DAI_DEBASSERT( f
.vars() == g
.vars() );
522 return dist( f
.p(), g
.p(), dt
);
527 /// Returns the pointwise maximum of two TFactors
529 * \pre f.vars() == g.vars()
531 template<typename T
> TFactor
<T
> max( const TFactor
<T
> &f
, const TFactor
<T
> &g
) {
532 DAI_ASSERT( f
._vs
== g
._vs
);
533 return TFactor
<T
>( f
._vs
, min( f
.p(), g
.p() ) );
537 /// Returns the pointwise minimum of two TFactors
539 * \pre f.vars() == g.vars()
541 template<typename T
> TFactor
<T
> min( const TFactor
<T
> &f
, const TFactor
<T
> &g
) {
542 DAI_ASSERT( f
._vs
== g
._vs
);
543 return TFactor
<T
>( f
._vs
, max( f
.p(), g
.p() ) );
547 /// Calculates the mutual information between the two variables that f depends on, under the distribution given by f
549 * \pre f.vars().size() == 2
551 template<typename T
> Real
MutualInfo(const TFactor
<T
> &f
) {
552 DAI_ASSERT( f
.vars().size() == 2 );
553 VarSet::const_iterator it
= f
.vars().begin();
554 Var i
= *it
; it
++; Var j
= *it
;
555 TFactor
<T
> projection
= f
.marginal(i
) * f
.marginal(j
);
556 return dist( f
.normalized(), projection
, Prob::DISTKL
);
560 /// Represents a factor with values of type Real.
561 typedef TFactor
<Real
> Factor
;
564 } // end of namespace dai