Cleaned up BBP and improved documentation of include/dai/bbp.h
[libdai.git] / include / dai / daialg.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) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 /// \file
13 /// \brief Defines abstract base class InfAlg, its descendant DAIAlg<>, the specializations DAIAlgFG and DAIAlgRG and some generic inference methods.
14
15
16 #ifndef __defined_libdai_daialg_h
17 #define __defined_libdai_daialg_h
18
19
20 #include <string>
21 #include <iostream>
22 #include <vector>
23 #include <dai/factorgraph.h>
24 #include <dai/regiongraph.h>
25 #include <dai/properties.h>
26
27
28 namespace dai {
29
30
31 /// InfAlg is an abstract base class, defining the common interface of all inference algorithms in libDAI.
32 /** \todo General marginalization functions like calcMarginal() now copy a complete InfAlg object. Instead,
33 * it would make more sense that they construct a new object without copying the FactorGraph or RegionGraph.
34 * Or they can simply be made methods of the general InfAlg class.
35 * \idea Use a PropertySet as output of an InfAlg, instead of functions like maxDiff() and Iterations().
36 */
37 class InfAlg {
38 public:
39 /// \name Constructors/destructors
40 //@{
41 /// Virtual destructor (needed because this class contains virtual functions)
42 virtual ~InfAlg() {}
43
44 /// Returns a pointer to a new, cloned copy of \c *this (i.e., virtual copy constructor)
45 virtual InfAlg* clone() const = 0;
46 //@}
47
48 /// \name Queries
49 //@{
50 /// Identifies itself for logging purposes
51 virtual std::string identify() const = 0;
52
53 /// Returns reference to underlying FactorGraph.
54 virtual FactorGraph &fg() = 0;
55
56 /// Returns constant reference to underlying FactorGraph.
57 virtual const FactorGraph &fg() const = 0;
58 //@}
59
60 /// \name Inference interface
61 //@{
62 /// Initializes all data structures of the approximate inference algorithm.
63 /** \note This method should be called at least once before run() is called.
64 */
65 virtual void init() = 0;
66
67 /// Initializes all data structures corresponding to some set of variables.
68 /** This method can be used to do a partial initialization after a part of the factor graph has changed.
69 * Instead of initializing all data structures, it only initializes those involving the variables in \a vs.
70 */
71 virtual void init( const VarSet &vs ) = 0;
72
73 /// Runs the approximate inference algorithm.
74 /** \note Before run() is called the first time, init() should have been called.
75 */
76 virtual Real run() = 0;
77
78 /// Returns the (approximate) marginal probability distribution of a variable.
79 /** \note Before this method is called, run() should have been called.
80 */
81 virtual Factor belief( const Var &v ) const = 0;
82
83 /// Returns the (approximate) marginal probability distribution of a set of variables.
84 /** \note Before this method is called, run() should have been called.
85 */
86 virtual Factor belief( const VarSet &vs ) const = 0;
87
88 /// Returns the (approximate) marginal probability distribution of the variable with index \a i.
89 /** For some approximate inference algorithms, using beliefV() is preferred to belief() for performance reasons.
90 * \note Before this method is called, run() should have been called.
91 */
92 virtual Factor beliefV( size_t i ) const { return belief( fg().var(i) ); }
93
94 /// Returns the (approximate) marginal probability distribution of the variables on which factor \a I depends.
95 /** For some approximate inference algorithms, using beliefF() is preferred to belief() for performance reasons.
96 * \note Before this method is called, run() should have been called.
97 */
98 virtual Factor beliefF( size_t I ) const { return belief( fg().factor(I).vars() ); }
99
100 /// Returns all beliefs (approximate marginal probability distributions) calculated by the algorithm.
101 /** \note Before this method is called, run() should have been called.
102 */
103 virtual std::vector<Factor> beliefs() const = 0;
104
105 /// Returns the logarithm of the (approximated) partition sum (normalizing constant of the factor graph).
106 /** \note Before this method is called, run() should have been called.
107 * \throw NOT_IMPLEMENTED if not implemented/supported
108 */
109 virtual Real logZ() const = 0;
110
111 /// Returns maximum difference between single variable beliefs in the last iteration.
112 /** \throw NOT_IMPLEMENTED if not implemented/supported
113 */
114 virtual Real maxDiff() const = 0;
115
116 /// Returns number of iterations done (one iteration passes over the complete factorgraph).
117 /** \throw NOT_IMPLEMENTED if not implemented/supported
118 */
119 virtual size_t Iterations() const = 0;
120 //@}
121
122 /// \name Changing the factor graph
123 //@{
124 /// Clamp variable with index \a i to value \a x (i.e. multiply with a Kronecker delta \f$\delta_{x_i, x}\f$)
125 /** If \a backup == \c true, make a backup of all factors that are changed.
126 */
127 virtual void clamp( size_t i, size_t x, bool backup = false ) = 0;
128
129 // OBSOLETE
130 /// Clamp variable \a v to value \a x (i.e. multiply with a Kronecker delta \f$\delta_{v, x}\f$)
131 /** \deprecated Please use dai::InfAlg::clamp(size_t,size_t,bool) instead
132 */
133 virtual void clamp( const Var &v, size_t x, bool backup = false ) = 0;
134
135 /// Sets all factors interacting with variable with index \a i to one.
136 /** If \a backup == \c true, make a backup of all factors that are changed.
137 */
138 virtual void makeCavity( size_t i, bool backup = false ) = 0;
139 //@}
140
141 /// \name Backup/restore mechanism for factors
142 //@{
143 /// Make a backup copy of factor \a I
144 virtual void backupFactor( size_t I ) = 0;
145 /// Make backup copies of all factors involving the variables in \a vs
146 virtual void backupFactors( const VarSet &vs ) = 0;
147
148 /// Restore factor \a I from its backup copy
149 virtual void restoreFactor( size_t I ) = 0;
150 /// Restore the factors involving the variables in \a vs from their backup copies
151 virtual void restoreFactors( const VarSet &vs ) = 0;
152 //@}
153
154 /// \name Managing parameters
155 //@{
156 /// Set parameters of this inference algorithm.
157 /** The parameters are set according to the PropertySet \a opts.
158 * The values can be stored either as std::string or as the type of the corresponding MF::props member.
159 */
160 virtual void setProperties( const PropertySet &opts ) = 0;
161 /// Returns parameters of this inference algorithm converted into a PropertySet.
162 virtual PropertySet getProperties() const = 0;
163 /// Returns parameters of this inference algorithm formatted as a string in the format "[key1=val1,key2=val2,...,keyn=valn]".
164 virtual std::string printProperties() const = 0;
165 //@}
166 };
167
168
169 /// Combines the abstract base class InfAlg with a graphical model (e.g., a FactorGraph or RegionGraph).
170 /** Inference algorithms in libDAI directly inherit from a DAIAlg, currently either
171 * from a DAIAlg<FactorGraph> or from a DAIAlg<RegionGraph>.
172 *
173 * \tparam GRM Should be castable to FactorGraph
174 * \todo A DAIAlg should not inherit from a FactorGraph or RegionGraph, but should
175 * store a reference to the graphical model object. This prevents needless copying
176 * of (possibly large) data structures. Disadvantage: the caller must not change
177 * the graphical model between calls to the inference algorithm (maybe a smart_ptr
178 * or some locking mechanism would help here?).
179 */
180 template <class GRM>
181 class DAIAlg : public InfAlg, public GRM {
182 public:
183 /// \name Constructors/destructors
184 //@{
185 /// Default constructor
186 DAIAlg() : InfAlg(), GRM() {}
187
188 /// Construct from GRM
189 DAIAlg( const GRM &grm ) : InfAlg(), GRM(grm) {}
190 //@}
191
192 /// \name Queries
193 //@{
194 /// Returns reference to underlying FactorGraph.
195 FactorGraph &fg() { return (FactorGraph &)(*this); }
196
197 /// Returns constant reference to underlying FactorGraph.
198 const FactorGraph &fg() const { return (const FactorGraph &)(*this); }
199 //@}
200
201 /// \name Changing the factor graph
202 //@{
203 /// Clamp variable with index \a i to value \a x (i.e. multiply with a Kronecker delta \f$\delta_{x_i, x}\f$)
204 /** If \a backup == \c true, make a backup of all factors that are changed.
205 */
206 void clamp( size_t i, size_t x, bool backup = false ) { GRM::clamp( i, x, backup ); }
207
208 // OBSOLETE
209 /// Clamp variable \a v to value \a x (i.e. multiply with a Kronecker delta \f$\delta_{v, x}\f$)
210 /** \deprecated Please use dai::DAIAlg<>::clamp(size_t,size_t,bool) instead
211 */
212 void clamp( const Var &v, size_t x, bool backup = false ) {
213 GRM::clamp( v, x, backup );
214 std::cerr << "Warning: this DAIAlg<...>::clamp(const Var&,...) interface is obsolete!" << std::endl;
215 }
216
217 /// Sets all factors interacting with variable with index \a i to one.
218 /** If \a backup == \c true, make a backup of all factors that are changed.
219 */
220 void makeCavity( size_t i, bool backup = false ) { GRM::makeCavity( i, backup ); }
221 //@}
222
223 /// \name Backup/restore mechanism for factors
224 //@{
225 /// Make a backup copy of factor \a I
226 void backupFactor( size_t I ) { GRM::backupFactor( I ); }
227 /// Make backup copies of all factors involving the variables in \a vs
228 void backupFactors( const VarSet &vs ) { GRM::backupFactors( vs ); }
229
230 /// Restore factor \a I from its backup copy
231 void restoreFactor( size_t I ) { GRM::restoreFactor( I ); }
232 /// Restore the factors involving the variables in \a vs from their backup copies
233 void restoreFactors( const VarSet &vs ) { GRM::restoreFactors( vs ); }
234 //@}
235 };
236
237
238 /// Base class for inference algorithms that operate on a FactorGraph
239 typedef DAIAlg<FactorGraph> DAIAlgFG;
240
241 /// Base class for inference algorithms that operate on a RegionGraph
242 typedef DAIAlg<RegionGraph> DAIAlgRG;
243
244
245 /// Calculates the marginal probability distribution for \a vs using inference algorithm \a obj.
246 /** calcMarginal() works by clamping all variables in \a vs and calculating the partition sum for each clamped state.
247 * Therefore, it can be used in combination with any inference algorithm that can calculate/approximate partition sums.
248 * \param obj instance of inference algorithm to be used
249 * \param vs variables for which the marginal should be calculated
250 * \param reInit should be set to \c true if at least one of the possible clamped states would be invalid (leading to a factor graph with zero partition sum).
251 */
252 Factor calcMarginal( const InfAlg& obj, const VarSet& vs, bool reInit );
253
254 /// Calculates beliefs for all pairs of variables in \a vs using inference algorithm \a obj.
255 /** calcPairBeliefs() works by
256 * - clamping single variables in \a vs and calculating the partition sum and the single variable beliefs for each clamped state, if \a accurate == \c false;
257 * - clamping pairs of variables in \a vs and calculating the partition sum for each clamped state, if \a accurate == \c true.
258 *
259 * Therefore, it can be used in combination with any inference algorithm that can calculate/approximate partition sums (and single variable beliefs, if
260 * \a accurate == \c true).
261 * \param obj instance of inference algorithm to be used
262 * \param vs variables for which the pair beliefs should be calculated
263 * \param reInit should be set to \c true if at least one of the possible clamped states would be invalid (leading to a factor graph with zero partition sum).
264 * \param accurate if \c true, uses a slower but more accurate approximation algorithm
265 */
266 std::vector<Factor> calcPairBeliefs( const InfAlg& obj, const VarSet& vs, bool reInit, bool accurate=false );
267
268 // OBSOLETE
269 /// Calculates beliefs for all pairs of variables in \a vs using inference algorithm \a obj.
270 /** \deprecated Please use dai::calcPairBeliefs() instead with \a accurate == \c true
271 */
272 std::vector<Factor> calcPairBeliefsNew( const InfAlg& obj, const VarSet& vs, bool reInit );
273
274 // OBSOLETE
275 /// Calculates marginal probability distribution for \a vs up to second order interactions using inference algorithm \a obj
276 /** \deprecated Functionality is not widely used
277 */
278 Factor calcMarginal2ndO( const InfAlg& obj, const VarSet& vs, bool reInit );
279
280
281 } // end of namespace dai
282
283
284 #endif