dc133afaab34e21739f12869deba744467bf1416
[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
92 public:
93 /// Parameters for BP
94 struct Properties {
95 /// Enumeration of possible update schedules
96 /** The following update schedules have been defined:
97 * - PARALL parallel updates
98 * - SEQFIX sequential updates using a fixed sequence
99 * - SEQRND sequential updates using a random sequence
100 * - SEQMAX maximum-residual updates [\ref EMK06]
101 */
102 DAI_ENUM(UpdateType,SEQFIX,SEQRND,SEQMAX,PARALL);
103
104 /// Enumeration of inference variants
105 /** There are two inference variants:
106 * - SUMPROD Sum-Product
107 * - MAXPROD Max-Product (equivalent to Min-Sum)
108 */
109 DAI_ENUM(InfType,SUMPROD,MAXPROD);
110
111 /// Verbosity (amount of output sent to stderr)
112 size_t verbose;
113
114 /// Maximum number of iterations
115 size_t maxiter;
116
117 /// Tolerance for convergence test
118 Real tol;
119
120 /// Whether updates should be done in logarithmic domain or not
121 bool logdomain;
122
123 /// Damping constant (0.0 means no damping, 1.0 is maximum damping)
124 Real damping;
125
126 /// Message update schedule
127 UpdateType updates;
128
129 /// Inference variant
130 InfType inference;
131 } props;
132
133 /// Name of this inference algorithm
134 static const char *Name;
135
136 /// Specifies whether the history of message updates should be recorded
137 bool recordSentMessages;
138
139 public:
140 /// \name Constructors/destructors
141 //@{
142 /// Default constructor
143 BP() : DAIAlgFG(), _edges(), _edge2lut(), _lut(), _maxdiff(0.0), _iters(0U), _sentMessages(), props(), recordSentMessages(false) {}
144
145 /// Construct from FactorGraph \a fg and PropertySet \a opts
146 /** \param fg Factor graph.
147 * \param opts Parameters @see Properties
148 */
149 BP( const FactorGraph & fg, const PropertySet &opts ) : DAIAlgFG(fg), _edges(), _maxdiff(0.0), _iters(0U), _sentMessages(), props(), recordSentMessages(false) {
150 setProperties( opts );
151 construct();
152 }
153
154 /// Copy constructor
155 BP( const BP &x ) : DAIAlgFG(x), _edges(x._edges), _edge2lut(x._edge2lut),
156 _lut(x._lut), _maxdiff(x._maxdiff), _iters(x._iters), _sentMessages(x._sentMessages),
157 props(x.props), recordSentMessages(x.recordSentMessages)
158 {
159 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
160 _edge2lut[l->second.first][l->second.second] = l;
161 }
162
163 /// Assignment operator
164 BP& operator=( const BP &x ) {
165 if( this != &x ) {
166 DAIAlgFG::operator=( x );
167 _edges = x._edges;
168 _lut = x._lut;
169 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
170 _edge2lut[l->second.first][l->second.second] = l;
171 _maxdiff = x._maxdiff;
172 _iters = x._iters;
173 _sentMessages = x._sentMessages;
174 props = x.props;
175 recordSentMessages = x.recordSentMessages;
176 }
177 return *this;
178 }
179 //@}
180
181 /// \name General InfAlg interface
182 //@{
183 virtual BP* clone() const { return new BP(*this); }
184 virtual std::string identify() const;
185 virtual Factor belief( const Var &v ) const { return beliefV( findVar( v ) ); }
186 virtual Factor belief( const VarSet &vs ) const;
187 virtual Factor beliefV( size_t i ) const;
188 virtual Factor beliefF( size_t I ) const;
189 virtual std::vector<Factor> beliefs() const;
190 virtual Real logZ() const;
191 virtual void init();
192 virtual void init( const VarSet &ns );
193 virtual Real run();
194 virtual Real maxDiff() const { return _maxdiff; }
195 virtual size_t Iterations() const { return _iters; }
196 virtual void setProperties( const PropertySet &opts );
197 virtual PropertySet getProperties() const;
198 virtual std::string printProperties() const;
199 //@}
200
201 /// \name Additional interface specific for BP
202 //@{
203 /// Calculates the joint state of all variables that has maximum probability
204 /** \pre Assumes that run() has been called and that \a props.inference == \c MAXPROD
205 */
206 std::vector<std::size_t> findMaximum() const;
207
208 /// Returns history of which messages have been updated
209 const std::vector<std::pair<std::size_t, std::size_t> >& getSentMessages() const {
210 return _sentMessages;
211 }
212
213 /// Clears history of which messages have been updated
214 void clearSentMessages() { _sentMessages.clear(); }
215 //@}
216
217 protected:
218 /// Returns constant reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
219 const Prob & message(size_t i, size_t _I) const { return _edges[i][_I].message; }
220 /// Returns reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
221 Prob & message(size_t i, size_t _I) { return _edges[i][_I].message; }
222 /// Returns constant reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
223 const Prob & newMessage(size_t i, size_t _I) const { return _edges[i][_I].newMessage; }
224 /// Returns reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
225 Prob & newMessage(size_t i, size_t _I) { return _edges[i][_I].newMessage; }
226 /// Returns constant reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
227 const ind_t & index(size_t i, size_t _I) const { return _edges[i][_I].index; }
228 /// Returns reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
229 ind_t & index(size_t i, size_t _I) { return _edges[i][_I].index; }
230 /// Returns constant reference to residual for the edge between variable \a i and its \a _I 'th neighbor
231 const Real & residual(size_t i, size_t _I) const { return _edges[i][_I].residual; }
232 /// Returns reference to residual for the edge between variable \a i and its \a _I 'th neighbor
233 Real & residual(size_t i, size_t _I) { return _edges[i][_I].residual; }
234
235 /// Calculate the product of factor \a I and the incoming messages
236 /** If \a without_i == \c true, the message coming from variable \a i is omitted from the product
237 * \note This function is used by calcNewMessage() and calcBeliefF()
238 */
239 virtual Prob calcIncomingMessageProduct( size_t I, bool without_i, size_t i ) const;
240 /// Calculate the updated message from the \a _I 'th neighbor of variable \a i to variable \a i
241 virtual void calcNewMessage( size_t i, size_t _I );
242 /// Replace the "old" message from the \a _I 'th neighbor of variable \a i to variable \a i by the "new" (updated) message
243 void updateMessage( size_t i, size_t _I );
244 /// 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
245 void updateResidual( size_t i, size_t _I, Real r );
246 /// Finds the edge which has the maximum residual (difference between new and old message)
247 void findMaxResidual( size_t &i, size_t &_I );
248 /// Calculates unnormalized belief of variable \a i
249 virtual void calcBeliefV( size_t i, Prob &p ) const;
250 /// Calculates unnormalized belief of factor \a I
251 virtual void calcBeliefF( size_t I, Prob &p ) const {
252 p = calcIncomingMessageProduct( I, false, 0 );
253 }
254
255 /// Helper function for constructors
256 virtual void construct();
257 };
258
259
260 } // end of namespace dai
261
262
263 #endif