Fixed regression FBP and bugs in TRWBP
[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-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 class BP, which implements (Loopy) Belief Propagation
14
15
16 #ifndef __defined_libdai_bp_h
17 #define __defined_libdai_bp_h
18
19
20 #include <string>
21 #include <dai/daialg.h>
22 #include <dai/factorgraph.h>
23 #include <dai/properties.h>
24 #include <dai/enum.h>
25
26
27 namespace dai {
28
29
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 * \todo Merge duplicate code in calcNewMessage() and calcBeliefF()
62 */
63 class BP : public DAIAlgFG {
64 protected:
65 /// Type used for index cache
66 typedef std::vector<size_t> ind_t;
67 /// Type used for storing edge properties
68 struct EdgeProp {
69 /// Index cached for this edge
70 ind_t index;
71 /// Old message living on this edge
72 Prob message;
73 /// New message living on this edge
74 Prob newMessage;
75 /// Residual for this edge
76 Real residual;
77 };
78 /// Stores all edge properties
79 std::vector<std::vector<EdgeProp> > _edges;
80 /// Type of lookup table (only used for maximum-residual BP)
81 typedef std::multimap<Real, std::pair<std::size_t, std::size_t> > LutType;
82 /// Lookup table (only used for maximum-residual BP)
83 std::vector<std::vector<LutType::iterator> > _edge2lut;
84 /// Lookup table (only used for maximum-residual BP)
85 LutType _lut;
86 /// Maximum difference between variable beliefs encountered so far
87 Real _maxdiff;
88 /// Number of iterations needed
89 size_t _iters;
90 /// The history of message updates (only recorded if \a recordSentMessages is \c true)
91 std::vector<std::pair<std::size_t, std::size_t> > _sentMessages;
92
93 public:
94 /// Parameters for BP
95 struct Properties {
96 /// Enumeration of possible update schedules
97 /** The following update schedules have been defined:
98 * - PARALL parallel updates
99 * - SEQFIX sequential updates using a fixed sequence
100 * - SEQRND sequential updates using a random sequence
101 * - SEQMAX maximum-residual updates [\ref EMK06]
102 */
103 DAI_ENUM(UpdateType,SEQFIX,SEQRND,SEQMAX,PARALL);
104
105 /// Enumeration of inference variants
106 /** There are two inference variants:
107 * - SUMPROD Sum-Product
108 * - MAXPROD Max-Product (equivalent to Min-Sum)
109 */
110 DAI_ENUM(InfType,SUMPROD,MAXPROD);
111
112 /// Verbosity (amount of output sent to stderr)
113 size_t verbose;
114
115 /// Maximum number of iterations
116 size_t maxiter;
117
118 /// Tolerance for convergence test
119 Real tol;
120
121 /// Whether updates should be done in logarithmic domain or not
122 bool logdomain;
123
124 /// Damping constant (0.0 means no damping, 1.0 is maximum damping)
125 Real damping;
126
127 /// Message update schedule
128 UpdateType updates;
129
130 /// Inference variant
131 InfType inference;
132 } props;
133
134 /// Name of this inference algorithm
135 static const char *Name;
136
137 /// Specifies whether the history of message updates should be recorded
138 bool recordSentMessages;
139
140 public:
141 /// \name Constructors/destructors
142 //@{
143 /// Default constructor
144 BP() : DAIAlgFG(), _edges(), _edge2lut(), _lut(), _maxdiff(0.0), _iters(0U), _sentMessages(), props(), recordSentMessages(false) {}
145
146 /// Construct from FactorGraph \a fg and PropertySet \a opts
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 updated message from the \a _I 'th neighbor of variable \a i to variable \a i
236 virtual void calcNewMessage( size_t i, size_t _I );
237 /// Replace the "old" message from the \a _I 'th neighbor of variable \a i to variable \a i by the "new" (updated) message
238 void updateMessage( size_t i, size_t _I );
239 /// 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
240 void updateResidual( size_t i, size_t _I, Real r );
241 /// Finds the edge which has the maximum residual (difference between new and old message)
242 void findMaxResidual( size_t &i, size_t &_I );
243 /// Calculates unnormalized belief of variable \a i
244 virtual void calcBeliefV( size_t i, Prob &p ) const;
245 /// Calculates unnormalized belief of factor \a I
246 virtual void calcBeliefF( size_t I, Prob &p ) const;
247
248 /// Helper function for constructors
249 virtual void construct();
250 };
251
252
253 } // end of namespace dai
254
255
256 #endif