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