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