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