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