Fixed example_imagesegmentation by adding InfAlg::setMaxIter(size_t)
[libdai.git] / include / dai / bp.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-2010 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 class BP, which implements (Loopy) Belief Propagation
14 /// \todo Consider using a priority_queue for maximum residual schedule
15
16
17 #ifndef __defined_libdai_bp_h
18 #define __defined_libdai_bp_h
19
20
21 #include <string>
22 #include <dai/daialg.h>
23 #include <dai/factorgraph.h>
24 #include <dai/properties.h>
25 #include <dai/enum.h>
26
27
28 namespace dai {
29
30
31 /// Approximate inference algorithm "(Loopy) Belief Propagation"
32 /** The Loopy Belief Propagation algorithm uses message passing
33 * to approximate marginal probability distributions ("beliefs") for variables
34 * and factors (more precisely, for the subset of variables depending on the factor).
35 * There are two variants, the sum-product algorithm (corresponding to
36 * finite temperature) and the max-product algorithm (corresponding to
37 * zero temperature).
38 *
39 * The messages \f$m_{I\to i}(x_i)\f$ are passed from factors \f$I\f$ to variables \f$i\f$.
40 * In case of the sum-product algorith, the update equation is:
41 * \f[ m_{I\to i}(x_i) \propto \sum_{x_{N_I\setminus\{i\}}} f_I(x_I) \prod_{j\in N_I\setminus\{i\}} \prod_{J\in N_j\setminus\{I\}} m_{J\to j}\f]
42 * and in case of the max-product algorithm:
43 * \f[ m_{I\to i}(x_i) \propto \max_{x_{N_I\setminus\{i\}}} f_I(x_I) \prod_{j\in N_I\setminus\{i\}} \prod_{J\in N_j\setminus\{I\}} m_{J\to j}\f]
44 * In order to improve convergence, the updates can be damped. For improved numerical stability,
45 * the updates can be done in the log-domain alternatively.
46 *
47 * After convergence, the variable beliefs are calculated by:
48 * \f[ b_i(x_i) \propto \prod_{I\in N_i} m_{I\to i}(x_i)\f]
49 * and the factor beliefs are calculated by:
50 * \f[ b_I(x_I) \propto f_I(x_I) \prod_{j\in N_I} \prod_{J\in N_j\setminus\{I\}} m_{J\to j}(x_j) \f]
51 * The logarithm of the partition sum is calculated by:
52 * \f[ \log Z = \sum_i (1 - |N_i|) \sum_{x_i} b_i(x_i) \log b_i(x_i) - \sum_I \sum_{x_I} b_I(x_I) \log \frac{b_I(x_I)}{f_I(x_I)} \f]
53 *
54 * For the max-product algorithm, a heuristic way of finding the MAP state (the
55 * joint configuration of all variables which has maximum probability) is provided
56 * by the findMaximum() method, which can be called after convergence.
57 *
58 * \note There are two implementations, an optimized one (the default) which caches IndexFor objects,
59 * and a slower, less complicated one which is easier to maintain/understand. The slower one can be
60 * enabled by defining DAI_BP_FAST as false in the source file.
61 */
62 class BP : public DAIAlgFG {
63 protected:
64 /// Type used for index cache
65 typedef std::vector<size_t> ind_t;
66 /// Type used for storing edge properties
67 struct EdgeProp {
68 /// Index cached for this edge
69 ind_t index;
70 /// Old message living on this edge
71 Prob message;
72 /// New message living on this edge
73 Prob newMessage;
74 /// Residual for this edge
75 Real residual;
76 };
77 /// Stores all edge properties
78 std::vector<std::vector<EdgeProp> > _edges;
79 /// Type of lookup table (only used for maximum-residual BP)
80 typedef std::multimap<Real, std::pair<std::size_t, std::size_t> > LutType;
81 /// Lookup table (only used for maximum-residual BP)
82 std::vector<std::vector<LutType::iterator> > _edge2lut;
83 /// Lookup table (only used for maximum-residual BP)
84 LutType _lut;
85 /// Maximum difference between variable beliefs encountered so far
86 Real _maxdiff;
87 /// Number of iterations needed
88 size_t _iters;
89 /// The history of message updates (only recorded if \a recordSentMessages is \c true)
90 std::vector<std::pair<std::size_t, std::size_t> > _sentMessages;
91 /// Stores variable beliefs of previous iteration
92 std::vector<Factor> _oldBeliefsV;
93 /// Stores factor beliefs of previous iteration
94 std::vector<Factor> _oldBeliefsF;
95 /// Stores the update schedule
96 std::vector<Edge> _updateSeq;
97
98 public:
99 /// Parameters for BP
100 struct Properties {
101 /// Enumeration of possible update schedules
102 /** The following update schedules have been defined:
103 * - PARALL parallel updates
104 * - SEQFIX sequential updates using a fixed sequence
105 * - SEQRND sequential updates using a random sequence
106 * - SEQMAX maximum-residual updates [\ref EMK06]
107 */
108 DAI_ENUM(UpdateType,SEQFIX,SEQRND,SEQMAX,PARALL);
109
110 /// Enumeration of inference variants
111 /** There are two inference variants:
112 * - SUMPROD Sum-Product
113 * - MAXPROD Max-Product (equivalent to Min-Sum)
114 */
115 DAI_ENUM(InfType,SUMPROD,MAXPROD);
116
117 /// Verbosity (amount of output sent to stderr)
118 size_t verbose;
119
120 /// Maximum number of iterations
121 size_t maxiter;
122
123 /// Maximum time (in seconds)
124 double maxtime;
125
126 /// Tolerance for convergence test
127 Real tol;
128
129 /// Whether updates should be done in logarithmic domain or not
130 bool logdomain;
131
132 /// Damping constant (0.0 means no damping, 1.0 is maximum damping)
133 Real damping;
134
135 /// Message update schedule
136 UpdateType updates;
137
138 /// Inference variant
139 InfType inference;
140 } props;
141
142 /// Name of this inference algorithm
143 static const char *Name;
144
145 /// Specifies whether the history of message updates should be recorded
146 bool recordSentMessages;
147
148 public:
149 /// \name Constructors/destructors
150 //@{
151 /// Default constructor
152 BP() : DAIAlgFG(), _edges(), _edge2lut(), _lut(), _maxdiff(0.0), _iters(0U), _sentMessages(), _oldBeliefsV(), _oldBeliefsF(), _updateSeq(), props(), recordSentMessages(false) {}
153
154 /// Construct from FactorGraph \a fg and PropertySet \a opts
155 /** \param fg Factor graph.
156 * \param opts Parameters @see Properties
157 */
158 BP( const FactorGraph & fg, const PropertySet &opts ) : DAIAlgFG(fg), _edges(), _maxdiff(0.0), _iters(0U), _sentMessages(), _oldBeliefsV(), _oldBeliefsF(), _updateSeq(), props(), recordSentMessages(false) {
159 setProperties( opts );
160 construct();
161 }
162
163 /// Copy constructor
164 BP( const BP &x ) : DAIAlgFG(x), _edges(x._edges), _edge2lut(x._edge2lut), _lut(x._lut), _maxdiff(x._maxdiff), _iters(x._iters), _sentMessages(x._sentMessages), _oldBeliefsV(x._oldBeliefsV), _oldBeliefsF(x._oldBeliefsF), _updateSeq(x._updateSeq), props(x.props), recordSentMessages(x.recordSentMessages) {
165 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
166 _edge2lut[l->second.first][l->second.second] = l;
167 }
168
169 /// Assignment operator
170 BP& operator=( const BP &x ) {
171 if( this != &x ) {
172 DAIAlgFG::operator=( x );
173 _edges = x._edges;
174 _lut = x._lut;
175 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
176 _edge2lut[l->second.first][l->second.second] = l;
177 _maxdiff = x._maxdiff;
178 _iters = x._iters;
179 _sentMessages = x._sentMessages;
180 _oldBeliefsV = x._oldBeliefsV;
181 _oldBeliefsF = x._oldBeliefsF;
182 _updateSeq = x._updateSeq;
183 props = x.props;
184 recordSentMessages = x.recordSentMessages;
185 }
186 return *this;
187 }
188 //@}
189
190 /// \name General InfAlg interface
191 //@{
192 virtual BP* clone() const { return new BP(*this); }
193 virtual std::string identify() const;
194 virtual Factor belief( const Var &v ) const { return beliefV( findVar( v ) ); }
195 virtual Factor belief( const VarSet &vs ) const;
196 virtual Factor beliefV( size_t i ) const;
197 virtual Factor beliefF( size_t I ) const;
198 virtual std::vector<Factor> beliefs() const;
199 virtual Real logZ() const;
200 /** \pre Assumes that run() has been called and that \a props.inference == \c MAXPROD
201 */
202 std::vector<std::size_t> findMaximum() const;
203 virtual void init();
204 virtual void init( const VarSet &ns );
205 virtual Real run();
206 virtual Real maxDiff() const { return _maxdiff; }
207 virtual size_t Iterations() const { return _iters; }
208 virtual void setMaxIter( size_t maxiter ) { props.maxiter = maxiter; }
209 virtual void setProperties( const PropertySet &opts );
210 virtual PropertySet getProperties() const;
211 virtual std::string printProperties() const;
212 //@}
213
214 /// \name Additional interface specific for BP
215 //@{
216 /// Returns history of which messages have been updated
217 const std::vector<std::pair<std::size_t, std::size_t> >& getSentMessages() const {
218 return _sentMessages;
219 }
220
221 /// Clears history of which messages have been updated
222 void clearSentMessages() { _sentMessages.clear(); }
223 //@}
224
225 protected:
226 /// Returns constant reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
227 const Prob & message(size_t i, size_t _I) const { return _edges[i][_I].message; }
228 /// Returns reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
229 Prob & message(size_t i, size_t _I) { return _edges[i][_I].message; }
230 /// Returns constant reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
231 const Prob & newMessage(size_t i, size_t _I) const { return _edges[i][_I].newMessage; }
232 /// Returns reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
233 Prob & newMessage(size_t i, size_t _I) { return _edges[i][_I].newMessage; }
234 /// Returns constant reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
235 const ind_t & index(size_t i, size_t _I) const { return _edges[i][_I].index; }
236 /// Returns reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
237 ind_t & index(size_t i, size_t _I) { return _edges[i][_I].index; }
238 /// Returns constant reference to residual for the edge between variable \a i and its \a _I 'th neighbor
239 const Real & residual(size_t i, size_t _I) const { return _edges[i][_I].residual; }
240 /// Returns reference to residual for the edge between variable \a i and its \a _I 'th neighbor
241 Real & residual(size_t i, size_t _I) { return _edges[i][_I].residual; }
242
243 /// Calculate the product of factor \a I and the incoming messages
244 /** If \a without_i == \c true, the message coming from variable \a i is omitted from the product
245 * \note This function is used by calcNewMessage() and calcBeliefF()
246 */
247 virtual Prob calcIncomingMessageProduct( size_t I, bool without_i, size_t i ) const;
248 /// Calculate the updated message from the \a _I 'th neighbor of variable \a i to variable \a i
249 virtual void calcNewMessage( size_t i, size_t _I );
250 /// Replace the "old" message from the \a _I 'th neighbor of variable \a i to variable \a i by the "new" (updated) message
251 void updateMessage( size_t i, size_t _I );
252 /// Set the residual (difference between new and old message) for the edge between variable \a i and its \a _I 'th neighbor to \a r
253 void updateResidual( size_t i, size_t _I, Real r );
254 /// Finds the edge which has the maximum residual (difference between new and old message)
255 void findMaxResidual( size_t &i, size_t &_I );
256 /// Calculates unnormalized belief of variable \a i
257 virtual void calcBeliefV( size_t i, Prob &p ) const;
258 /// Calculates unnormalized belief of factor \a I
259 virtual void calcBeliefF( size_t I, Prob &p ) const {
260 p = calcIncomingMessageProduct( I, false, 0 );
261 }
262
263 /// Helper function for constructors
264 virtual void construct();
265 };
266
267
268 } // end of namespace dai
269
270
271 #endif