1 /* This file is part of libDAI - http://www.libdai.org/
2 *
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2002 Martijn Leisink [martijn@mbfys.kun.nl]
8 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
10 */
13 /// \file
14 /// \brief Defines TFactor<> and Factor classes which represent factors in probability distributions.
17 #ifndef __defined_libdai_factor_h
18 #define __defined_libdai_factor_h
21 #include <iostream>
22 #include <functional>
23 #include <cmath>
24 #include <dai/prob.h>
25 #include <dai/varset.h>
26 #include <dai/index.h>
27 #include <dai/util.h>
30 namespace dai {
33 /// Represents a (probability) factor.
34 /** Mathematically, a \e factor is a function mapping joint states of some
35 * variables to the nonnegative real numbers.
36 * More formally, denoting a discrete variable with label \f$l\f$ by
37 * \f$x_l\f$ and its state space by \f$X_l = \{0,1,\dots,S_l-1\}\f$,
38 * a factor depending on the variables \f$\{x_l\}_{l\in L}\f$ is
39 * a function \f$f_L : \prod_{l\in L} X_l \to [0,\infty)\f$.
40 *
41 * In libDAI, a factor is represented by a TFactor<T> object, which has two
42 * components:
43 * \arg a VarSet, corresponding with the set of variables \f$\{x_l\}_{l\in L}\f$
44 * that the factor depends on;
45 * \arg a TProb, a vector containing the value of the factor for each possible
46 * joint state of the variables.
47 *
48 * The factor values are stored in the entries of the TProb in a particular
49 * ordering, which is defined by the one-to-one correspondence of a joint state
50 * in \f$\prod_{l\in L} X_l\f$ with a linear index in
51 * \f$\{0,1,\dots,\prod_{l\in L} S_l-1\}\f$ according to the mapping \f$\sigma\f$
52 * induced by dai::calcLinearState().
53 *
54 * \tparam T Should be a scalar that is castable from and to double and should support elementary arithmetic operations.
55 * \todo Define a better fileformat for .fg files (maybe using XML)?
56 * \todo Add support for sparse factors.
57 */
58 template <typename T>
59 class TFactor {
60 private:
61 /// Stores the variables on which the factor depends
62 VarSet _vs;
63 /// Stores the factor values
64 TProb<T> _p;
66 public:
67 /// \name Constructors and destructors
68 //@{
69 /// Constructs factor depending on no variables with value \a p
70 TFactor ( T p = 1 ) : _vs(), _p(1,p) {}
72 /// Constructs factor depending on the variable \a v with uniform distribution
73 TFactor( const Var &v ) : _vs(v), _p(v.states()) {}
75 /// Constructs factor depending on variables in \a vars with uniform distribution
76 TFactor( const VarSet& vars ) : _vs(vars), _p(_vs.nrStates()) {}
78 /// Constructs factor depending on variables in \a vars with all values set to \a p
79 TFactor( const VarSet& vars, T p ) : _vs(vars), _p(_vs.nrStates(),p) {}
81 /// Constructs factor depending on variables in \a vars, copying the values from a std::vector<>
82 /** \tparam S Type of values of \a x
83 * \param vars contains the variables that the new factor should depend on.
84 * \param x Vector with values to be copied.
85 */
86 template<typename S>
87 TFactor( const VarSet& vars, const std::vector<S> &x ) : _vs(vars), _p() {
88 DAI_ASSERT( x.size() == vars.nrStates() );
89 _p = TProb<T>( x.begin(), x.begin() + _vs.nrStates(), _vs.nrStates() );
90 }
92 /// Constructs factor depending on variables in \a vars, copying the values from an array
93 /** \param vars contains the variables that the new factor should depend on.
94 * \param p Points to array of values to be added.
95 */
96 TFactor( const VarSet& vars, const T* p ) : _vs(vars), _p(p, p + _vs.nrStates(), _vs.nrStates()) {}
98 /// Constructs factor depending on variables in \a vars, copying the values from \a p
99 TFactor( const VarSet& vars, const TProb<T> &p ) : _vs(vars), _p(p) {
100 DAI_ASSERT( _vs.nrStates() == _p.size() );
101 }
103 /// Constructs factor depending on variables in \a vars, permuting the values given in \a p accordingly
104 TFactor( const std::vector<Var> &vars, const std::vector<T> &p ) : _vs(vars.begin(), vars.end(), vars.size()), _p(p.size()) {
105 size_t nrStates = 1;
106 for( size_t i = 0; i < vars.size(); i++ )
107 nrStates *= vars[i].states();
108 DAI_ASSERT( nrStates == p.size() );
109 Permute permindex(vars);
110 for( size_t li = 0; li < p.size(); ++li )
111 _p.set( permindex.convertLinearIndex(li), p[li] );
112 }
113 //@}
115 /// \name Get/set individual entries
116 //@{
117 /// Sets \a i 'th entry to \a val
118 void set( size_t i, T val ) { _p.set( i, val ); }
120 /// Gets \a i 'th entry
121 T get( size_t i ) const { return _p[i]; }
122 //@}
124 /// \name Queries
125 //@{
126 /// Returns constant reference to value vector
127 const TProb<T>& p() const { return _p; }
129 /// Returns reference to value vector
130 TProb<T>& p() { return _p; }
132 /// Returns a copy of the \a i 'th entry of the value vector
133 T operator[] (size_t i) const { return _p[i]; }
135 /// Returns constant reference to variable set (i.e., the variables on which the factor depends)
136 const VarSet& vars() const { return _vs; }
138 /// Returns reference to variable set (i.e., the variables on which the factor depends)
139 VarSet& vars() { return _vs; }
141 /// Returns the number of possible joint states of the variables on which the factor depends, \f$\prod_{l\in L} S_l\f$
142 /** \note This is equal to the length of the value vector.
143 */
144 size_t nrStates() const { return _p.size(); }
146 /// Returns the Shannon entropy of \c *this, \f$-\sum_i p_i \log p_i\f$
147 T entropy() const { return _p.entropy(); }
149 /// Returns maximum of all values
150 T max() const { return _p.max(); }
152 /// Returns minimum of all values
153 T min() const { return _p.min(); }
155 /// Returns sum of all values
156 T sum() const { return _p.sum(); }
158 /// Returns sum of absolute values
159 T sumAbs() const { return _p.sumAbs(); }
161 /// Returns maximum absolute value of all values
162 T maxAbs() const { return _p.maxAbs(); }
164 /// Returns \c true if one or more values are NaN
165 bool hasNaNs() const { return _p.hasNaNs(); }
167 /// Returns \c true if one or more values are negative
168 bool hasNegatives() const { return _p.hasNegatives(); }
170 /// Returns strength of this factor (between variables \a i and \a j), as defined in eq. (52) of [\ref MoK07b]
171 T strength( const Var &i, const Var &j ) const;
173 /// Comparison
174 bool operator==( const TFactor<T>& y ) const {
175 return (_vs == y._vs) && (_p == y._p);
176 }
177 //@}
179 /// \name Unary transformations
180 //@{
181 /// Returns negative of \c *this
182 TFactor<T> operator- () const {
183 // Note: the alternative (shorter) way of implementing this,
184 // return TFactor<T>( _vs, _p.abs() );
185 // is slower because it invokes the copy constructor of TProb<T>
186 TFactor<T> x;
187 x._vs = _vs;
188 x._p = -_p;
189 return x;
190 }
192 /// Returns pointwise absolute value
193 TFactor<T> abs() const {
194 TFactor<T> x;
195 x._vs = _vs;
196 x._p = _p.abs();
197 return x;
198 }
200 /// Returns pointwise exponent
201 TFactor<T> exp() const {
202 TFactor<T> x;
203 x._vs = _vs;
204 x._p = _p.exp();
205 return x;
206 }
208 /// Returns pointwise logarithm
209 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
210 */
211 TFactor<T> log(bool zero=false) const {
212 TFactor<T> x;
213 x._vs = _vs;
214 x._p = _p.log(zero);
215 return x;
216 }
218 /// Returns pointwise inverse
219 /** If \a zero == \c true, uses <tt>1/0==0</tt>; otherwise, <tt>1/0==Inf</tt>.
220 */
221 TFactor<T> inverse(bool zero=true) const {
222 TFactor<T> x;
223 x._vs = _vs;
224 x._p = _p.inverse(zero);
225 return x;
226 }
228 /// Returns normalized copy of \c *this, using the specified norm
229 /** \throw NOT_NORMALIZABLE if the norm is zero
230 */
231 TFactor<T> normalized( ProbNormType norm=NORMPROB ) const {
232 TFactor<T> x;
233 x._vs = _vs;
234 x._p = _p.normalized( norm );
235 return x;
236 }
237 //@}
239 /// \name Unary operations
240 //@{
241 /// Draws all values i.i.d. from a uniform distribution on [0,1)
242 TFactor<T>& randomize() { _p.randomize(); return *this; }
244 /// Sets all values to \f$1/n\f$ where \a n is the number of states
245 TFactor<T>& setUniform() { _p.setUniform(); return *this; }
247 /// Applies absolute value pointwise
248 TFactor<T>& takeAbs() { _p.takeAbs(); return *this; }
250 /// Applies exponent pointwise
251 TFactor<T>& takeExp() { _p.takeExp(); return *this; }
253 /// Applies logarithm pointwise
254 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
255 */
256 TFactor<T>& takeLog( bool zero = false ) { _p.takeLog(zero); return *this; }
258 /// Normalizes factor using the specified norm
259 /** \throw NOT_NORMALIZABLE if the norm is zero
260 */
261 T normalize( ProbNormType norm=NORMPROB ) { return _p.normalize( norm ); }
262 //@}
264 /// \name Operations with scalars
265 //@{
266 /// Sets all values to \a x
267 TFactor<T>& fill (T x) { _p.fill( x ); return *this; }
269 /// Adds scalar \a x to each value
270 TFactor<T>& operator+= (T x) { _p += x; return *this; }
272 /// Subtracts scalar \a x from each value
273 TFactor<T>& operator-= (T x) { _p -= x; return *this; }
275 /// Multiplies each value with scalar \a x
276 TFactor<T>& operator*= (T x) { _p *= x; return *this; }
278 /// Divides each entry by scalar \a x
279 TFactor<T>& operator/= (T x) { _p /= x; return *this; }
281 /// Raises values to the power \a x
282 TFactor<T>& operator^= (T x) { _p ^= x; return *this; }
283 //@}
285 /// \name Transformations with scalars
286 //@{
287 /// Returns sum of \c *this and scalar \a x
288 TFactor<T> operator+ (T x) const {
289 // Note: the alternative (shorter) way of implementing this,
290 // TFactor<T> result(*this);
291 // result._p += x;
292 // is slower because it invokes the copy constructor of TFactor<T>
293 TFactor<T> result;
294 result._vs = _vs;
295 result._p = p() + x;
296 return result;
297 }
299 /// Returns difference of \c *this and scalar \a x
300 TFactor<T> operator- (T x) const {
301 TFactor<T> result;
302 result._vs = _vs;
303 result._p = p() - x;
304 return result;
305 }
307 /// Returns product of \c *this with scalar \a x
308 TFactor<T> operator* (T x) const {
309 TFactor<T> result;
310 result._vs = _vs;
311 result._p = p() * x;
312 return result;
313 }
315 /// Returns quotient of \c *this with scalar \a x
316 TFactor<T> operator/ (T x) const {
317 TFactor<T> result;
318 result._vs = _vs;
319 result._p = p() / x;
320 return result;
321 }
323 /// Returns \c *this raised to the power \a x
324 TFactor<T> operator^ (T x) const {
325 TFactor<T> result;
326 result._vs = _vs;
327 result._p = p() ^ x;
328 return result;
329 }
330 //@}
332 /// \name Operations with other factors
333 //@{
334 /// Applies binary operation \a op on two factors, \c *this and \a g
335 /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
336 * \param g Right operand
337 * \param op Operation of type \a binOp
338 */
339 template<typename binOp> TFactor<T>& binaryOp( const TFactor<T> &g, binOp op ) {
340 if( _vs == g._vs ) // optimize special case
341 _p.pwBinaryOp( g._p, op );
342 else {
343 TFactor<T> f(*this); // make a copy
344 _vs |= g._vs;
345 size_t N = _vs.nrStates();
347 IndexFor i_f( f._vs, _vs );
348 IndexFor i_g( g._vs, _vs );
350 _p.p().clear();
351 _p.p().reserve( N );
352 for( size_t i = 0; i < N; i++, ++i_f, ++i_g )
353 _p.p().push_back( op( f._p[i_f], g._p[i_g] ) );
354 }
355 return *this;
356 }
358 /// Adds \a g to \c *this
359 /** The sum of two factors is defined as follows: if
360 * \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
361 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
362 */
363 TFactor<T>& operator+= (const TFactor<T>& g) { return binaryOp( g, std::plus<T>() ); }
365 /// Subtracts \a g from \c *this
366 /** The difference of two factors is defined as follows: if
367 * \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
368 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
369 */
370 TFactor<T>& operator-= (const TFactor<T>& g) { return binaryOp( g, std::minus<T>() ); }
372 /// Multiplies \c *this with \a g
373 /** The product of two factors is defined as follows: if
374 * \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
375 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
376 */
377 TFactor<T>& operator*= (const TFactor<T>& g) { return binaryOp( g, std::multiplies<T>() ); }
379 /// Divides \c *this by \a g (where division by zero yields zero)
380 /** The quotient of two factors is defined as follows: if
381 * \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
382 * \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]
383 */
384 TFactor<T>& operator/= (const TFactor<T>& g) { return binaryOp( g, fo_divides0<T>() ); }
385 //@}
387 /// \name Transformations with other factors
388 //@{
389 /// Returns result of applying binary operation \a op on two factors, \c *this and \a g
390 /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
391 * \param g Right operand
392 * \param op Operation of type \a binOp
393 */
394 template<typename binOp> TFactor<T> binaryTr( const TFactor<T> &g, binOp op ) const {
395 // Note that to prevent a copy to be made, it is crucial
396 // that the result is declared outside the if-else construct.
397 TFactor<T> result;
398 if( _vs == g._vs ) { // optimize special case
399 result._vs = _vs;
400 result._p = _p.pwBinaryTr( g._p, op );
401 } else {
402 result._vs = _vs | g._vs;
403 size_t N = result._vs.nrStates();
405 IndexFor i_f( _vs, result.vars() );
406 IndexFor i_g( g._vs, result.vars() );
408 result._p.p().clear();
409 result._p.p().reserve( N );
410 for( size_t i = 0; i < N; i++, ++i_f, ++i_g )
411 result._p.p().push_back( op( _p[i_f], g[i_g] ) );
412 }
413 return result;
414 }
416 /// Returns sum of \c *this and \a g
417 /** The sum of two factors is defined as follows: if
418 * \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
419 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
420 */
421 TFactor<T> operator+ (const TFactor<T>& g) const {
422 return binaryTr(g,std::plus<T>());
423 }
425 /// Returns \c *this minus \a g
426 /** The difference of two factors is defined as follows: if
427 * \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
428 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
429 */
430 TFactor<T> operator- (const TFactor<T>& g) const {
431 return binaryTr(g,std::minus<T>());
432 }
434 /// Returns product of \c *this with \a g
435 /** The product of two factors is defined as follows: if
436 * \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
437 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
438 */
439 TFactor<T> operator* (const TFactor<T>& g) const {
440 return binaryTr(g,std::multiplies<T>());
441 }
443 /// Returns quotient of \c *this by \a f (where division by zero yields zero)
444 /** The quotient of two factors is defined as follows: if
445 * \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
446 * \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]
447 */
448 TFactor<T> operator/ (const TFactor<T>& g) const {
449 return binaryTr(g,fo_divides0<T>());
450 }
451 //@}
453 /// \name Miscellaneous operations
454 //@{
455 /// Returns a slice of \c *this, where the subset \a vars is in state \a varsState
456 /** \pre \a vars sould be a subset of vars()
457 * \pre \a varsState < vars.nrStates()
458 *
459 * The result is a factor that depends on the variables of *this except those in \a vars,
460 * obtained by setting the variables in \a vars to the joint state specified by the linear index
461 * \a varsState. Formally, if \c *this corresponds with the factor \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$,
462 * \f$M \subset L\f$ corresponds with \a vars and \a varsState corresponds with a mapping \f$s\f$ that
463 * 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
464 * returned corresponds with the factor \f$g : \prod_{l \in L \setminus M} X_l \to [0,\infty)\f$
465 * 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$.
466 */
467 TFactor<T> slice( const VarSet& vars, size_t varsState ) const;
469 /// Embeds this factor in a larger VarSet
470 /** \pre vars() should be a subset of \a vars
471 *
472 * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then
473 * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$.
474 */
475 TFactor<T> embed(const VarSet & vars) const {
476 DAI_ASSERT( vars >> _vs );
477 if( _vs == vars )
478 return *this;
479 else
480 return (*this) * TFactor<T>(vars / _vs, (T)1);
481 }
483 /// Returns marginal on \a vars, obtained by summing out all variables except those in \a vars, and normalizing the result if \a normed == \c true
484 TFactor<T> marginal(const VarSet &vars, bool normed=true) const;
486 /// Returns max-marginal on \a vars, obtained by maximizing all variables except those in \a vars, and normalizing the result if \a normed == \c true
487 TFactor<T> maxMarginal(const VarSet &vars, bool normed=true) const;
488 //@}
489 };
492 template<typename T> TFactor<T> TFactor<T>::slice( const VarSet& vars, size_t varsState ) const {
493 DAI_ASSERT( vars << _vs );
494 VarSet varsrem = _vs / vars;
495 TFactor<T> result( varsrem, T(0) );
497 // OPTIMIZE ME
498 IndexFor i_vars (vars, _vs);
499 IndexFor i_varsrem (varsrem, _vs);
500 for( size_t i = 0; i < nrStates(); i++, ++i_vars, ++i_varsrem )
501 if( (size_t)i_vars == varsState )
502 result.set( i_varsrem, _p[i] );
504 return result;
505 }
508 template<typename T> TFactor<T> TFactor<T>::marginal(const VarSet &vars, bool normed) const {
509 VarSet res_vars = vars & _vs;
511 TFactor<T> res( res_vars, 0.0 );
513 IndexFor i_res( res_vars, _vs );
514 for( size_t i = 0; i < _p.size(); i++, ++i_res )
515 res.set( i_res, res[i_res] + _p[i] );
517 if( normed )
518 res.normalize( NORMPROB );
520 return res;
521 }
524 template<typename T> TFactor<T> TFactor<T>::maxMarginal(const VarSet &vars, bool normed) const {
525 VarSet res_vars = vars & _vs;
527 TFactor<T> res( res_vars, 0.0 );
529 IndexFor i_res( res_vars, _vs );
530 for( size_t i = 0; i < _p.size(); i++, ++i_res )
531 if( _p[i] > res._p[i_res] )
532 res.set( i_res, _p[i] );
534 if( normed )
535 res.normalize( NORMPROB );
537 return res;
538 }
541 template<typename T> T TFactor<T>::strength( const Var &i, const Var &j ) const {
542 DAI_DEBASSERT( _vs.contains( i ) );
543 DAI_DEBASSERT( _vs.contains( j ) );
544 DAI_DEBASSERT( i != j );
545 VarSet ij(i, j);
547 T max = 0.0;
548 for( size_t alpha1 = 0; alpha1 < i.states(); alpha1++ )
549 for( size_t alpha2 = 0; alpha2 < i.states(); alpha2++ )
550 if( alpha2 != alpha1 )
551 for( size_t beta1 = 0; beta1 < j.states(); beta1++ )
552 for( size_t beta2 = 0; beta2 < j.states(); beta2++ )
553 if( beta2 != beta1 ) {
554 size_t as = 1, bs = 1;
555 if( i < j )
556 bs = i.states();
557 else
558 as = j.states();
559 T f1 = slice( ij, alpha1 * as + beta1 * bs ).p().divide( slice( ij, alpha2 * as + beta1 * bs ).p() ).max();
560 T f2 = slice( ij, alpha2 * as + beta2 * bs ).p().divide( slice( ij, alpha1 * as + beta2 * bs ).p() ).max();
561 T f = f1 * f2;
562 if( f > max )
563 max = f;
564 }
566 return std::tanh( 0.25 * std::log( max ) );
567 }
570 /// Writes a factor to an output stream
571 /** \relates TFactor
572 */
573 template<typename T> std::ostream& operator<< (std::ostream& os, const TFactor<T>& f) {
574 os << "(" << f.vars() << ", (";
575 for( size_t i = 0; i < f.nrStates(); i++ )
576 os << (i == 0 ? "" : ", ") << f[i];
577 os << "))";
578 return os;
579 }
582 /// Returns distance between two factors \a f and \a g, according to the distance measure \a dt
583 /** \relates TFactor
584 * \pre f.vars() == g.vars()
585 */
586 template<typename T> T dist( const TFactor<T> &f, const TFactor<T> &g, ProbDistType dt ) {
587 if( f.vars().empty() || g.vars().empty() )
588 return -1;
589 else {
590 DAI_DEBASSERT( f.vars() == g.vars() );
591 return dist( f.p(), g.p(), dt );
592 }
593 }
596 /// Returns the pointwise maximum of two factors
597 /** \relates TFactor
598 * \pre f.vars() == g.vars()
599 */
600 template<typename T> TFactor<T> max( const TFactor<T> &f, const TFactor<T> &g ) {
601 DAI_ASSERT( f.vars() == g.vars() );
602 return TFactor<T>( f.vars(), max( f.p(), g.p() ) );
603 }
606 /// Returns the pointwise minimum of two factors
607 /** \relates TFactor
608 * \pre f.vars() == g.vars()
609 */
610 template<typename T> TFactor<T> min( const TFactor<T> &f, const TFactor<T> &g ) {
611 DAI_ASSERT( f.vars() == g.vars() );
612 return TFactor<T>( f.vars(), min( f.p(), g.p() ) );
613 }
616 /// Calculates the mutual information between the two variables that \a f depends on, under the distribution given by \a f
617 /** \relates TFactor
618 * \pre f.vars().size() == 2
619 */
620 template<typename T> T MutualInfo(const TFactor<T> &f) {
621 DAI_ASSERT( f.vars().size() == 2 );
622 VarSet::const_iterator it = f.vars().begin();
623 Var i = *it; it++; Var j = *it;
624 TFactor<T> projection = f.marginal(i) * f.marginal(j);
625 return dist( f.normalized(), projection, DISTKL );
626 }
629 /// Represents a factor with values of type dai::Real.
630 typedef TFactor<Real> Factor;
633 /// Returns a binary unnormalized single-variable factor \f$\exp(hx) \f$ where \f$x = \pm 1 \f$
634 /** \param x Variable (should be binary)
635 * \param h Field strength
636 */
637 Factor createFactorIsing( const Var &x, Real h );
640 /// Returns a binary unnormalized pairwise factor \f$\exp(J x_1 x_2) \f$ where \f$x_1, x_2 = \pm 1 \f$
641 /** \param x1 First variable (should be binary)
642 * \param x2 Second variable (should be binary)
643 * \param J Coupling strength
644 */
645 Factor createFactorIsing( const Var &x1, const Var &x2, Real J );
648 /// Returns a random factor on the variables \a vs with strength \a beta
649 /** Each entry are set by drawing a normally distributed random with mean
650 * 0 and standard-deviation \a beta, and taking its exponent.
651 * \param vs Variables
652 * \param beta Factor strength (inverse temperature)
653 */
654 Factor createFactorExpGauss( const VarSet &vs, Real beta );
657 /// Returns a pairwise Potts factor \f$\exp( J \delta_{x_1, x_2} ) \f$
658 /** \param x1 First variable
659 * \param x2 Second variable (should have the same number of states as \a x1)
660 * \param J Factor strength
661 */
662 Factor createFactorPotts( const Var &x1, const Var &x2, Real J );
665 /// Returns a Kronecker delta point mass
666 /** \param v Variable
667 * \param state The state of \a v that should get value 1
668 */
669 Factor createFactorDelta( const Var &v, size_t state );
672 } // end of namespace dai
675 #endif