Merge branch 'master' of git@git.tuebingen.mpg.de:libdai
[libdai.git] / include / dai / factor.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
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.
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]
9 * Copyright (C) 2002-2007 Radboud University Nijmegen, The Netherlands
10 */
11
12
13 /// \file
14 /// \brief Defines TFactor<> and Factor classes which represent factors in probability distributions.
15
16
17 #ifndef __defined_libdai_factor_h
18 #define __defined_libdai_factor_h
19
20
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>
28
29
30 namespace dai {
31
32
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> class TFactor {
59 private:
60 /// Stores the variables on which the factor depends
61 VarSet _vs;
62 /// Stores the factor values
63 TProb<T> _p;
64
65 public:
66 /// \name Constructors and destructors
67 //@{
68 /// Constructs factor depending on no variables with value \a p
69 TFactor ( T p = 1 ) : _vs(), _p(1,p) {}
70
71 /// Constructs factor depending on the variable \a v with uniform distribution
72 TFactor( const Var &v ) : _vs(v), _p(v.states()) {}
73
74 /// Constructs factor depending on variables in \a vars with uniform distribution
75 TFactor( const VarSet& vars ) : _vs(vars), _p(_vs.nrStates()) {}
76
77 /// Constructs factor depending on variables in \a vars with all values set to \a p
78 TFactor( const VarSet& vars, T p ) : _vs(vars), _p(_vs.nrStates(),p) {}
79
80 /// Constructs factor depending on variables in \a vars, copying the values from a std::vector<>
81 /** \tparam S Type of values of \a x
82 * \param vars contains the variables that the new factor should depend on.
83 * \param x Vector with values to be copied.
84 */
85 template<typename S>
86 TFactor( const VarSet& vars, const std::vector<S> &x ) : _vs(vars), _p(x.begin(), x.begin() + _vs.nrStates(), _vs.nrStates()) {
87 DAI_ASSERT( x.size() == vars.nrStates() );
88 }
89
90 /// Constructs factor depending on variables in \a vars, copying the values from an array
91 /** \param vars contains the variables that the new factor should depend on.
92 * \param p Points to array of values to be added.
93 */
94 TFactor( const VarSet& vars, const T* p ) : _vs(vars), _p(p, p + _vs.nrStates(), _vs.nrStates()) {}
95
96 /// Constructs factor depending on variables in \a vars, copying the values from \a p
97 TFactor( const VarSet& vars, const TProb<T> &p ) : _vs(vars), _p(p) {
98 DAI_DEBASSERT( _vs.nrStates() == _p.size() );
99 }
100
101 /// Constructs factor depending on variables in \a vars, permuting the values given in \a p accordingly
102 TFactor( const std::vector<Var> &vars, const std::vector<T> &p ) : _vs(vars.begin(), vars.end(), vars.size()), _p(p.size()) {
103 Permute permindex(vars);
104 for( size_t li = 0; li < p.size(); ++li )
105 _p.set( permindex.convertLinearIndex(li), p[li] );
106 }
107 //@}
108
109 /// \name Queries
110 //@{
111 /// Returns constant reference to value vector
112 const TProb<T>& p() const { return _p; }
113
114 /// Returns reference to value vector
115 TProb<T>& p() { return _p; }
116
117 /// Returns a copy of the \a i 'th entry of the value vector
118 T operator[] (size_t i) const { return _p[i]; }
119
120 /// Returns a reference to the \a i 'th entry of the value vector
121 /// \deprecated Please use dai::TFactor::set() instead
122 T& operator[] (size_t i) { return _p[i]; }
123
124 /// Gets \a i 'th entry of the value vector
125 T get( size_t i ) const { return _p[i]; }
126
127 /// Sets \a i 'th entry of the value vector to \a val
128 void set( size_t i, T val ) { _p.set( i, val ); }
129
130 /// Returns constant reference to variable set (i.e., the variables on which the factor depends)
131 const VarSet& vars() const { return _vs; }
132
133 /// Returns reference to variable set (i.e., the variables on which the factor depends)
134 VarSet& vars() { return _vs; }
135
136 /// Returns the number of possible joint states of the variables on which the factor depends, \f$\prod_{l\in L} S_l\f$
137 /** \note This is equal to the length of the value vector.
138 */
139 size_t states() const { return _p.size(); }
140
141 /// Returns the Shannon entropy of \c *this, \f$-\sum_i p_i \log p_i\f$
142 T entropy() const { return _p.entropy(); }
143
144 /// Returns maximum of all values
145 T max() const { return _p.max(); }
146
147 /// Returns minimum of all values
148 T min() const { return _p.min(); }
149
150 /// Returns sum of all values
151 T sum() const { return _p.sum(); }
152
153 /// Returns maximum absolute value of all values
154 T maxAbs() const { return _p.maxAbs(); }
155
156 /// Returns \c true if one or more values are NaN
157 bool hasNaNs() const { return _p.hasNaNs(); }
158
159 /// Returns \c true if one or more values are negative
160 bool hasNegatives() const { return _p.hasNegatives(); }
161
162 /// Returns strength of this factor (between variables \a i and \a j), as defined in eq. (52) of [\ref MoK07b]
163 T strength( const Var &i, const Var &j ) const;
164 //@}
165
166 /// \name Unary transformations
167 //@{
168 /// Returns pointwise absolute value
169 TFactor<T> abs() const {
170 // Note: the alternative (shorter) way of implementing this,
171 // return TFactor<T>( _vs, _p.abs() );
172 // is slower because it invokes the copy constructor of TProb<T>
173 TFactor<T> x;
174 x._vs = _vs;
175 x._p = _p.abs();
176 return x;
177 }
178
179 /// Returns pointwise exponent
180 TFactor<T> exp() const {
181 TFactor<T> x;
182 x._vs = _vs;
183 x._p = _p.exp();
184 return x;
185 }
186
187 /// Returns pointwise logarithm
188 /** If \a zero == \c true, uses <tt>log(0)==0</tt>; otherwise, <tt>log(0)==-Inf</tt>.
189 */
190 TFactor<T> log(bool zero=false) const {
191 TFactor<T> x;
192 x._vs = _vs;
193 x._p = _p.log(zero);
194 return x;
195 }
196
197 /// Returns pointwise inverse
198 /** If \a zero == \c true, uses <tt>1/0==0</tt>; otherwise, <tt>1/0==Inf</tt>.
199 */
200 TFactor<T> inverse(bool zero=true) const {
201 TFactor<T> x;
202 x._vs = _vs;
203 x._p = _p.inverse(zero);
204 return x;
205 }
206
207 /// Returns normalized copy of \c *this, using the specified norm
208 /** \throw NOT_NORMALIZABLE if the norm is zero
209 */
210 TFactor<T> normalized( typename TProb<T>::NormType norm=TProb<T>::NORMPROB ) const {
211 TFactor<T> x;
212 x._vs = _vs;
213 x._p = _p.normalized( norm );
214 return x;
215 }
216 //@}
217
218 /// \name Unary operations
219 //@{
220 /// Draws all values i.i.d. from a uniform distribution on [0,1)
221 TFactor<T> & randomize () { _p.randomize(); return *this; }
222
223 /// Sets all values to \f$1/n\f$ where \a n is the number of states
224 TFactor<T>& setUniform () { _p.setUniform(); return *this; }
225
226 /// Normalizes factor using the specified norm
227 /** \throw NOT_NORMALIZABLE if the norm is zero
228 */
229 T normalize( typename TProb<T>::NormType norm=TProb<T>::NORMPROB ) { return _p.normalize( norm ); }
230 //@}
231
232 /// \name Operations with scalars
233 //@{
234 /// Sets all values to \a x
235 TFactor<T> & fill (T x) { _p.fill( x ); return *this; }
236
237 /// Adds scalar \a x to each value
238 TFactor<T>& operator+= (T x) { _p += x; return *this; }
239
240 /// Subtracts scalar \a x from each value
241 TFactor<T>& operator-= (T x) { _p -= x; return *this; }
242
243 /// Multiplies each value with scalar \a x
244 TFactor<T>& operator*= (T x) { _p *= x; return *this; }
245
246 /// Divides each entry by scalar \a x
247 TFactor<T>& operator/= (T x) { _p /= x; return *this; }
248
249 /// Raises values to the power \a x
250 TFactor<T>& operator^= (T x) { _p ^= x; return *this; }
251 //@}
252
253 /// \name Transformations with scalars
254 //@{
255 /// Returns sum of \c *this and scalar \a x
256 TFactor<T> operator+ (T x) const {
257 // Note: the alternative (shorter) way of implementing this,
258 // TFactor<T> result(*this);
259 // result._p += x;
260 // is slower because it invokes the copy constructor of TFactor<T>
261 TFactor<T> result;
262 result._vs = _vs;
263 result._p = p() + x;
264 return result;
265 }
266
267 /// Returns difference of \c *this and scalar \a x
268 TFactor<T> operator- (T x) const {
269 TFactor<T> result;
270 result._vs = _vs;
271 result._p = p() - x;
272 return result;
273 }
274
275 /// Returns product of \c *this with scalar \a x
276 TFactor<T> operator* (T x) const {
277 TFactor<T> result;
278 result._vs = _vs;
279 result._p = p() * x;
280 return result;
281 }
282
283 /// Returns quotient of \c *this with scalar \a x
284 TFactor<T> operator/ (T x) const {
285 TFactor<T> result;
286 result._vs = _vs;
287 result._p = p() / x;
288 return result;
289 }
290
291 /// Returns \c *this raised to the power \a x
292 TFactor<T> operator^ (T x) const {
293 TFactor<T> result;
294 result._vs = _vs;
295 result._p = p() ^ x;
296 return result;
297 }
298 //@}
299
300 /// \name Operations with other factors
301 //@{
302 /// Applies binary operation \a op on two factors, \c *this and \a g
303 /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
304 * \param g Right operand
305 * \param op Operation of type \a binOp
306 */
307 template<typename binOp> TFactor<T>& binaryOp( const TFactor<T> &g, binOp op ) {
308 if( _vs == g._vs ) // optimize special case
309 _p.pwBinaryOp( g._p, op );
310 else {
311 TFactor<T> f(*this); // make a copy
312 _vs |= g._vs;
313 size_t N = _vs.nrStates();
314
315 IndexFor i_f( f._vs, _vs );
316 IndexFor i_g( g._vs, _vs );
317
318 _p.p().clear();
319 _p.p().reserve( N );
320 for( size_t i = 0; i < N; i++, ++i_f, ++i_g )
321 _p.p().push_back( op( f._p[i_f], g._p[i_g] ) );
322 }
323 return *this;
324 }
325
326 /// Adds \a g to \c *this
327 /** The sum of two factors is defined as follows: if
328 * \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
329 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
330 */
331 TFactor<T>& operator+= (const TFactor<T>& g) { return binaryOp( g, std::plus<T>() ); }
332
333 /// Subtracts \a g from \c *this
334 /** The difference of two factors is defined as follows: if
335 * \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
336 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
337 */
338 TFactor<T>& operator-= (const TFactor<T>& g) { return binaryOp( g, std::minus<T>() ); }
339
340 /// Multiplies \c *this with \a g
341 /** The product of two factors is defined as follows: if
342 * \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
343 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
344 */
345 TFactor<T>& operator*= (const TFactor<T>& g) { return binaryOp( g, std::multiplies<T>() ); }
346
347 /// Divides \c *this by \a g (where division by zero yields zero)
348 /** The quotient of two factors is defined as follows: if
349 * \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
350 * \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]
351 */
352 TFactor<T>& operator/= (const TFactor<T>& g) { return binaryOp( g, fo_divides0<T>() ); }
353 //@}
354
355 /// \name Transformations with other factors
356 //@{
357 /// Returns result of applying binary operation \a op on two factors, \c *this and \a g
358 /** \tparam binOp Type of function object that accepts two arguments of type \a T and outputs a type \a T
359 * \param g Right operand
360 * \param op Operation of type \a binOp
361 */
362 template<typename binOp> TFactor<T> binaryTr( const TFactor<T> &g, binOp op ) const {
363 // Note that to prevent a copy to be made, it is crucial
364 // that the result is declared outside the if-else construct.
365 TFactor<T> result;
366 if( _vs == g._vs ) { // optimize special case
367 result._vs = _vs;
368 result._p = _p.pwBinaryTr( g._p, op );
369 } else {
370 result._vs = _vs | g._vs;
371 size_t N = result._vs.nrStates();
372
373 IndexFor i_f( _vs, result.vars() );
374 IndexFor i_g( g._vs, result.vars() );
375
376 result._p.p().clear();
377 result._p.p().reserve( N );
378 for( size_t i = 0; i < N; i++, ++i_f, ++i_g )
379 result._p.p().push_back( op( _p[i_f], g._p[i_g] ) );
380 }
381 return result;
382 }
383
384 /// Returns sum of \c *this and \a g
385 /** The sum of two factors is defined as follows: if
386 * \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
387 * \f[f+g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) + g(x_M).\f]
388 */
389 TFactor<T> operator+ (const TFactor<T>& g) const {
390 return binaryTr(g,std::plus<T>());
391 }
392
393 /// Returns \c *this minus \a g
394 /** The difference of two factors is defined as follows: if
395 * \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
396 * \f[f-g : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) - g(x_M).\f]
397 */
398 TFactor<T> operator- (const TFactor<T>& g) const {
399 return binaryTr(g,std::minus<T>());
400 }
401
402 /// Returns product of \c *this with \a g
403 /** The product of two factors is defined as follows: if
404 * \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
405 * \f[fg : \prod_{l\in L\cup M} X_l \to [0,\infty) : x \mapsto f(x_L) g(x_M).\f]
406 */
407 TFactor<T> operator* (const TFactor<T>& g) const {
408 return binaryTr(g,std::multiplies<T>());
409 }
410
411 /// Returns quotient of \c *this by \a f (where division by zero yields zero)
412 /** The quotient of two factors is defined as follows: if
413 * \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
414 * \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]
415 */
416 TFactor<T> operator/ (const TFactor<T>& g) const {
417 return binaryTr(g,fo_divides0<T>());
418 }
419 //@}
420
421 /// \name Miscellaneous operations
422 //@{
423 /// Returns a slice of \c *this, where the subset \a vars is in state \a varsState
424 /** \pre \a vars sould be a subset of vars()
425 * \pre \a varsState < vars.states()
426 *
427 * The result is a factor that depends on the variables of *this except those in \a vars,
428 * obtained by setting the variables in \a vars to the joint state specified by the linear index
429 * \a varsState. Formally, if \c *this corresponds with the factor \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$,
430 * \f$M \subset L\f$ corresponds with \a vars and \a varsState corresponds with a mapping \f$s\f$ that
431 * 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
432 * returned corresponds with the factor \f$g : \prod_{l \in L \setminus M} X_l \to [0,\infty)\f$
433 * 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$.
434 */
435 TFactor<T> slice( const VarSet& vars, size_t varsState ) const;
436
437 /// Embeds this factor in a larger VarSet
438 /** \pre vars() should be a subset of \a vars
439 *
440 * If *this corresponds with \f$f : \prod_{l\in L} X_l \to [0,\infty)\f$ and \f$L \subset M\f$, then
441 * the embedded factor corresponds with \f$g : \prod_{m\in M} X_m \to [0,\infty) : x \mapsto f(x_L)\f$.
442 */
443 TFactor<T> embed(const VarSet & vars) const {
444 DAI_ASSERT( vars >> _vs );
445 if( _vs == vars )
446 return *this;
447 else
448 return (*this) * TFactor<T>(vars / _vs, (T)1);
449 }
450
451 /// 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
452 TFactor<T> marginal(const VarSet &vars, bool normed=true) const;
453
454 /// 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
455 TFactor<T> maxMarginal(const VarSet &vars, bool normed=true) const;
456 //@}
457 };
458
459
460 template<typename T> TFactor<T> TFactor<T>::slice( const VarSet& vars, size_t varsState ) const {
461 DAI_ASSERT( vars << _vs );
462 VarSet varsrem = _vs / vars;
463 TFactor<T> result( varsrem, T(0) );
464
465 // OPTIMIZE ME
466 IndexFor i_vars (vars, _vs);
467 IndexFor i_varsrem (varsrem, _vs);
468 for( size_t i = 0; i < states(); i++, ++i_vars, ++i_varsrem )
469 if( (size_t)i_vars == varsState )
470 result.set( i_varsrem, _p[i] );
471
472 return result;
473 }
474
475
476 template<typename T> TFactor<T> TFactor<T>::marginal(const VarSet &vars, bool normed) const {
477 VarSet res_vars = vars & _vs;
478
479 TFactor<T> res( res_vars, 0.0 );
480
481 IndexFor i_res( res_vars, _vs );
482 for( size_t i = 0; i < _p.size(); i++, ++i_res )
483 res.set( i_res, res[i_res] + _p[i] );
484
485 if( normed )
486 res.normalize( TProb<T>::NORMPROB );
487
488 return res;
489 }
490
491
492 template<typename T> TFactor<T> TFactor<T>::maxMarginal(const VarSet &vars, bool normed) const {
493 VarSet res_vars = vars & _vs;
494
495 TFactor<T> res( res_vars, 0.0 );
496
497 IndexFor i_res( res_vars, _vs );
498 for( size_t i = 0; i < _p.size(); i++, ++i_res )
499 if( _p[i] > res._p[i_res] )
500 res.set( i_res, _p[i] );
501
502 if( normed )
503 res.normalize( TProb<T>::NORMPROB );
504
505 return res;
506 }
507
508
509 template<typename T> T TFactor<T>::strength( const Var &i, const Var &j ) const {
510 DAI_DEBASSERT( _vs.contains( i ) );
511 DAI_DEBASSERT( _vs.contains( j ) );
512 DAI_DEBASSERT( i != j );
513 VarSet ij(i, j);
514
515 T max = 0.0;
516 for( size_t alpha1 = 0; alpha1 < i.states(); alpha1++ )
517 for( size_t alpha2 = 0; alpha2 < i.states(); alpha2++ )
518 if( alpha2 != alpha1 )
519 for( size_t beta1 = 0; beta1 < j.states(); beta1++ )
520 for( size_t beta2 = 0; beta2 < j.states(); beta2++ )
521 if( beta2 != beta1 ) {
522 size_t as = 1, bs = 1;
523 if( i < j )
524 bs = i.states();
525 else
526 as = j.states();
527 T f1 = slice( ij, alpha1 * as + beta1 * bs ).p().divide( slice( ij, alpha2 * as + beta1 * bs ).p() ).max();
528 T f2 = slice( ij, alpha2 * as + beta2 * bs ).p().divide( slice( ij, alpha1 * as + beta2 * bs ).p() ).max();
529 T f = f1 * f2;
530 if( f > max )
531 max = f;
532 }
533
534 return std::tanh( 0.25 * std::log( max ) );
535 }
536
537
538 /// Writes a factor to an output stream
539 /** \relates TFactor
540 */
541 template<typename T> std::ostream& operator<< (std::ostream& os, const TFactor<T>& f) {
542 os << "(" << f.vars() << ", (";
543 for( size_t i = 0; i < f.states(); i++ )
544 os << (i == 0 ? "" : ", ") << f[i];
545 os << "))";
546 return os;
547 }
548
549
550 /// Returns distance between two factors \a f and \a g, according to the distance measure \a dt
551 /** \relates TFactor
552 * \pre f.vars() == g.vars()
553 */
554 template<typename T> T dist( const TFactor<T> &f, const TFactor<T> &g, typename TProb<T>::DistType dt ) {
555 if( f.vars().empty() || g.vars().empty() )
556 return -1;
557 else {
558 DAI_DEBASSERT( f.vars() == g.vars() );
559 return dist( f.p(), g.p(), dt );
560 }
561 }
562
563
564 /// Returns the pointwise maximum of two factors
565 /** \relates TFactor
566 * \pre f.vars() == g.vars()
567 */
568 template<typename T> TFactor<T> max( const TFactor<T> &f, const TFactor<T> &g ) {
569 DAI_ASSERT( f._vs == g._vs );
570 return TFactor<T>( f._vs, max( f.p(), g.p() ) );
571 }
572
573
574 /// Returns the pointwise minimum of two factors
575 /** \relates TFactor
576 * \pre f.vars() == g.vars()
577 */
578 template<typename T> TFactor<T> min( const TFactor<T> &f, const TFactor<T> &g ) {
579 DAI_ASSERT( f._vs == g._vs );
580 return TFactor<T>( f._vs, min( f.p(), g.p() ) );
581 }
582
583
584 /// Calculates the mutual information between the two variables that \a f depends on, under the distribution given by \a f
585 /** \relates TFactor
586 * \pre f.vars().size() == 2
587 */
588 template<typename T> T MutualInfo(const TFactor<T> &f) {
589 DAI_ASSERT( f.vars().size() == 2 );
590 VarSet::const_iterator it = f.vars().begin();
591 Var i = *it; it++; Var j = *it;
592 TFactor<T> projection = f.marginal(i) * f.marginal(j);
593 return dist( f.normalized(), projection, TProb<T>::DISTKL );
594 }
595
596
597 /// Represents a factor with values of type dai::Real.
598 typedef TFactor<Real> Factor;
599
600
601 /// Returns a binary single-variable factor \f$ \exp(hx) \f$ where \f$ x = \pm 1 \f$
602 /** \param x Variable (should be binary)
603 * \param h Field strength
604 */
605 Factor createFactorIsing( const Var &x, Real h );
606
607
608 /// Returns a binary pairwise factor \f$ \exp(J x_1 x_2) \f$ where \f$ x_1, x_2 = \pm 1 \f$
609 /** \param x1 First variable (should be binary)
610 * \param x2 Second variable (should be binary)
611 * \param J Coupling strength
612 */
613 Factor createFactorIsing( const Var &x1, const Var &x2, Real J );
614
615
616 /// Returns a random factor on the variables \a vs with strength \a beta
617 /** Each entry are set by drawing a normally distributed random with mean
618 * 0 and standard-deviation \a beta, and taking its exponent.
619 * \param vs Variables
620 * \param beta Factor strength (inverse temperature)
621 */
622 Factor createFactorExpGauss( const VarSet &vs, Real beta );
623
624
625 /// Returns a pairwise Potts factor \f$ \exp( J \delta_{x_1, x_2} ) \f$
626 /** \param x1 First variable
627 * \param x2 Second variable (should have the same number of states as \a x1)
628 * \param J Factor strength
629 */
630 Factor createFactorPotts( const Var &x1, const Var &x2, Real J );
631
632
633 /// Returns a Kronecker delta point mass
634 /** \param v Variable
635 * \param state The state of \a v that should get value 1
636 */
637 Factor createFactorDelta( const Var &v, size_t state );
638
639
640 } // end of namespace dai
641
642
643 #endif