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