8d35bf60b3f7809a0d013d46a88c64fbcfb039ea
[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 /// Specifies whether the history of message updates should be recorded
143 bool recordSentMessages;
144
145 public:
146 /// \name Constructors/destructors
147 //@{
148 /// Default constructor
149 BP() : DAIAlgFG(), _edges(), _edge2lut(), _lut(), _maxdiff(0.0), _iters(0U), _sentMessages(), _oldBeliefsV(), _oldBeliefsF(), _updateSeq(), props(), recordSentMessages(false) {}
150
151 /// Construct from FactorGraph \a fg and PropertySet \a opts
152 /** \param fg Factor graph.
153 * \param opts Parameters @see Properties
154 */
155 BP( const FactorGraph & fg, const PropertySet &opts ) : DAIAlgFG(fg), _edges(), _maxdiff(0.0), _iters(0U), _sentMessages(), _oldBeliefsV(), _oldBeliefsF(), _updateSeq(), props(), recordSentMessages(false) {
156 setProperties( opts );
157 construct();
158 }
159
160 /// Copy constructor
161 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) {
162 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
163 _edge2lut[l->second.first][l->second.second] = l;
164 }
165
166 /// Assignment operator
167 BP& operator=( const BP &x ) {
168 if( this != &x ) {
169 DAIAlgFG::operator=( x );
170 _edges = x._edges;
171 _lut = x._lut;
172 for( LutType::iterator l = _lut.begin(); l != _lut.end(); ++l )
173 _edge2lut[l->second.first][l->second.second] = l;
174 _maxdiff = x._maxdiff;
175 _iters = x._iters;
176 _sentMessages = x._sentMessages;
177 _oldBeliefsV = x._oldBeliefsV;
178 _oldBeliefsF = x._oldBeliefsF;
179 _updateSeq = x._updateSeq;
180 props = x.props;
181 recordSentMessages = x.recordSentMessages;
182 }
183 return *this;
184 }
185 //@}
186
187 /// \name General InfAlg interface
188 //@{
189 virtual BP* clone() const { return new BP(*this); }
190 virtual std::string name() const { return "BP"; }
191 virtual Factor belief( const Var &v ) const { return beliefV( findVar( v ) ); }
192 virtual Factor belief( const VarSet &vs ) const;
193 virtual Factor beliefV( size_t i ) const;
194 virtual Factor beliefF( size_t I ) const;
195 virtual std::vector<Factor> beliefs() const;
196 virtual Real logZ() const;
197 /** \pre Assumes that run() has been called and that \a props.inference == \c MAXPROD
198 */
199 std::vector<std::size_t> findMaximum() const { return dai::findMaximum( *this ); }
200 virtual void init();
201 virtual void init( const VarSet &ns );
202 virtual Real run();
203 virtual Real maxDiff() const { return _maxdiff; }
204 virtual size_t Iterations() const { return _iters; }
205 virtual void setMaxIter( size_t maxiter ) { props.maxiter = maxiter; }
206 virtual void setProperties( const PropertySet &opts );
207 virtual PropertySet getProperties() const;
208 virtual std::string printProperties() const;
209 //@}
210
211 /// \name Additional interface specific for BP
212 //@{
213 /// Returns history of which messages have been updated
214 const std::vector<std::pair<std::size_t, std::size_t> >& getSentMessages() const {
215 return _sentMessages;
216 }
217
218 /// Clears history of which messages have been updated
219 void clearSentMessages() { _sentMessages.clear(); }
220 //@}
221
222 protected:
223 /// Returns constant reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
224 const Prob & message(size_t i, size_t _I) const { return _edges[i][_I].message; }
225 /// Returns reference to message from the \a _I 'th neighbor of variable \a i to variable \a i
226 Prob & message(size_t i, size_t _I) { return _edges[i][_I].message; }
227 /// Returns constant reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
228 const Prob & newMessage(size_t i, size_t _I) const { return _edges[i][_I].newMessage; }
229 /// Returns reference to updated message from the \a _I 'th neighbor of variable \a i to variable \a i
230 Prob & newMessage(size_t i, size_t _I) { return _edges[i][_I].newMessage; }
231 /// Returns constant reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
232 const ind_t & index(size_t i, size_t _I) const { return _edges[i][_I].index; }
233 /// Returns reference to cached index for the edge between variable \a i and its \a _I 'th neighbor
234 ind_t & index(size_t i, size_t _I) { return _edges[i][_I].index; }
235 /// Returns constant reference to residual for the edge between variable \a i and its \a _I 'th neighbor
236 const Real & residual(size_t i, size_t _I) const { return _edges[i][_I].residual; }
237 /// Returns reference to residual for the edge between variable \a i and its \a _I 'th neighbor
238 Real & residual(size_t i, size_t _I) { return _edges[i][_I].residual; }
239
240 /// Calculate the product of factor \a I and the incoming messages
241 /** If \a without_i == \c true, the message coming from variable \a i is omitted from the product
242 * \note This function is used by calcNewMessage() and calcBeliefF()
243 */
244 virtual Prob calcIncomingMessageProduct( size_t I, bool without_i, size_t i ) const;
245 /// Calculate the updated message from the \a _I 'th neighbor of variable \a i to variable \a i
246 virtual void calcNewMessage( size_t i, size_t _I );
247 /// Replace the "old" message from the \a _I 'th neighbor of variable \a i to variable \a i by the "new" (updated) message
248 void updateMessage( size_t i, size_t _I );
249 /// 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
250 void updateResidual( size_t i, size_t _I, Real r );
251 /// Finds the edge which has the maximum residual (difference between new and old message)
252 void findMaxResidual( size_t &i, size_t &_I );
253 /// Calculates unnormalized belief of variable \a i
254 virtual void calcBeliefV( size_t i, Prob &p ) const;
255 /// Calculates unnormalized belief of factor \a I
256 virtual void calcBeliefF( size_t I, Prob &p ) const {
257 p = calcIncomingMessageProduct( I, false, 0 );
258 }
259
260 /// Helper function for constructors
261 virtual void construct();
262 };
263
264
265 } // end of namespace dai
266
267
268 #endif