b24cf39cccd6d35f714d5e8e8b2598c561344773
[libdai.git] / include / dai / bbp.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) 2009 Frederik Eaton [frederik at ofb dot net]
8 */
9
10
11 /// \file
12 /// \brief Defines class BBP, which implements Back-Belief-Propagation
13
14
15 #ifndef ___defined_libdai_bbp_h
16 #define ___defined_libdai_bbp_h
17
18
19 #include <vector>
20 #include <utility>
21
22 #include <dai/prob.h>
23 #include <dai/daialg.h>
24 #include <dai/factorgraph.h>
25 #include <dai/enum.h>
26 #include <dai/bp_dual.h>
27
28
29 namespace dai {
30
31
32 /// Enumeration of several cost functions that can be used with BBP
33 /** \note This class is meant as a base class for BBPCostFunction, which provides additional functionality.
34 */
35 DAI_ENUM(BBPCostFunctionBase,CFN_GIBBS_B,CFN_GIBBS_B2,CFN_GIBBS_EXP,CFN_GIBBS_B_FACTOR,CFN_GIBBS_B2_FACTOR,CFN_GIBBS_EXP_FACTOR,CFN_VAR_ENT,CFN_FACTOR_ENT,CFN_BETHE_ENT);
36
37
38 /// Predefined cost functions that can be used with BBP
39 class BBPCostFunction : public BBPCostFunctionBase {
40 public:
41 /// Default constructor
42 BBPCostFunction() : BBPCostFunctionBase() {}
43
44 /// Construct from BBPCostFunctionBase \a x
45 BBPCostFunction( const BBPCostFunctionBase &x ) : BBPCostFunctionBase(x) {}
46
47 /// Returns whether this cost function depends on having a Gibbs state
48 bool needGibbsState() const;
49
50 /// Evaluates cost function in state \a stateP using the information in inference algorithm \a ia
51 Real evaluate( const InfAlg &ia, const std::vector<size_t> *stateP ) const;
52
53 /// Assignment operator
54 BBPCostFunction& operator=( const BBPCostFunctionBase &x ) {
55 if( this != &x ) {
56 (BBPCostFunctionBase)*this = x;
57 }
58 return *this;
59 }
60 };
61
62
63 /// Implements BBP (Back-Belief-Propagation) [\ref EaG09]
64 /** \author Frederik Eaton
65 */
66 class BBP {
67 private:
68 /// \name Input variables
69 //@{
70 /// Stores a BP_dual helper object
71 BP_dual _bp_dual;
72 /// Pointer to the factor graph
73 const FactorGraph *_fg;
74 /// Pointer to the approximate inference algorithm (currently, only BP objects are supported)
75 const InfAlg *_ia;
76 //@}
77
78 /// \name Output variables
79 //@{
80 /// Variable factor adjoints
81 std::vector<Prob> _adj_psi_V;
82 /// Factor adjoints
83 std::vector<Prob> _adj_psi_F;
84 /// Variable->factor message adjoints (indexed [i][_I])
85 std::vector<std::vector<Prob> > _adj_n;
86 /// Factor->variable message adjoints (indexed [i][_I])
87 std::vector<std::vector<Prob> > _adj_m;
88 /// Normalized variable belief adjoints
89 std::vector<Prob> _adj_b_V;
90 /// Normalized factor belief adjoints
91 std::vector<Prob> _adj_b_F;
92 //@}
93
94 /// \name Internal state variables
95 //@{
96 /// Initial variable factor adjoints
97 std::vector<Prob> _init_adj_psi_V;
98 /// Initial factor adjoints
99 std::vector<Prob> _init_adj_psi_F;
100
101 /// Unnormalized variable->factor message adjoint (indexed [i][_I])
102 std::vector<std::vector<Prob> > _adj_n_unnorm;
103 /// Unnormalized factor->variable message adjoint (indexed [i][_I])
104 std::vector<std::vector<Prob> > _adj_m_unnorm;
105 /// Updated normalized variable->factor message adjoint (indexed [i][_I])
106 std::vector<std::vector<Prob> > _new_adj_n;
107 /// Updated normalized factor->variable message adjoint (indexed [i][_I])
108 std::vector<std::vector<Prob> > _new_adj_m;
109 /// Unnormalized variable belief adjoints
110 std::vector<Prob> _adj_b_V_unnorm;
111 /// Unnormalized factor belief adjoints
112 std::vector<Prob> _adj_b_F_unnorm;
113
114 /// _Tmsg[i][_I] (see eqn. (41) in [\ref EaG09])
115 std::vector<std::vector<Prob > > _Tmsg;
116 /// _Umsg[I][_i] (see eqn. (42) in [\ref EaG09])
117 std::vector<std::vector<Prob > > _Umsg;
118 /// _Smsg[i][_I][_j] (see eqn. (43) in [\ref EaG09])
119 std::vector<std::vector<std::vector<Prob > > > _Smsg;
120 /// _Rmsg[I][_i][_J] (see eqn. (44) in [\ref EaG09])
121 std::vector<std::vector<std::vector<Prob > > > _Rmsg;
122
123 /// Number of iterations done
124 size_t _iters;
125 //@}
126
127 /// \name Index cache management (for performance)
128 //@{
129 /// Index type
130 typedef std::vector<size_t> _ind_t;
131 /// Cached indices (indexed [i][_I])
132 std::vector<std::vector<_ind_t> > _indices;
133 /// Prepares index cache _indices
134 /** \see bp.cpp
135 */
136 void RegenerateInds();
137 /// Returns an index from the cache
138 const _ind_t& _index(size_t i, size_t _I) const { return _indices[i][_I]; }
139 //@}
140
141 /// \name Initialization helper functions
142 //@{
143 /// Calculate T values; see eqn. (41) in [\ref EaG09]
144 void RegenerateT();
145 /// Calculate U values; see eqn. (42) in [\ref EaG09]
146 void RegenerateU();
147 /// Calculate S values; see eqn. (43) in [\ref EaG09]
148 void RegenerateS();
149 /// Calculate R values; see eqn. (44) in [\ref EaG09]
150 void RegenerateR();
151 /// Calculate _adj_b_V_unnorm and _adj_b_F_unnorm from _adj_b_V and _adj_b_F
152 void RegenerateInputs();
153 /// Initialise members for factor adjoints
154 /** \pre RegenerateInputs() should be called first
155 */
156 void RegeneratePsiAdjoints();
157 /// Initialise members for message adjoints for parallel algorithm
158 /** \pre RegenerateInputs() should be called first
159 */
160 void RegenerateParMessageAdjoints();
161 /// Initialise members for message adjoints for sequential algorithm
162 /** Same as RegenerateMessageAdjoints, but calls sendSeqMsgN rather
163 * than updating _adj_n (and friends) which are unused in the sequential algorithm.
164 * \pre RegenerateInputs() should be called first
165 */
166 void RegenerateSeqMessageAdjoints();
167 /// Called by \a init, recalculates intermediate values
168 void Regenerate();
169 //@}
170
171 /// \name Accessors/mutators
172 //@{
173 /// Returns reference to T value; see eqn. (41) in [\ref EaG09]
174 Prob & T(size_t i, size_t _I) { return _Tmsg[i][_I]; }
175 /// Returns constant reference to T value; see eqn. (41) in [\ref EaG09]
176 const Prob & T(size_t i, size_t _I) const { return _Tmsg[i][_I]; }
177 /// Returns reference to U value; see eqn. (42) in [\ref EaG09]
178 Prob & U(size_t I, size_t _i) { return _Umsg[I][_i]; }
179 /// Returns constant reference to U value; see eqn. (42) in [\ref EaG09]
180 const Prob & U(size_t I, size_t _i) const { return _Umsg[I][_i]; }
181 /// Returns reference to S value; see eqn. (43) in [\ref EaG09]
182 Prob & S(size_t i, size_t _I, size_t _j) { return _Smsg[i][_I][_j]; }
183 /// Returns constant reference to S value; see eqn. (43) in [\ref EaG09]
184 const Prob & S(size_t i, size_t _I, size_t _j) const { return _Smsg[i][_I][_j]; }
185 /// Returns reference to R value; see eqn. (44) in [\ref EaG09]
186 Prob & R(size_t I, size_t _i, size_t _J) { return _Rmsg[I][_i][_J]; }
187 /// Returns constant reference to R value; see eqn. (44) in [\ref EaG09]
188 const Prob & R(size_t I, size_t _i, size_t _J) const { return _Rmsg[I][_i][_J]; }
189
190 /// Returns reference to variable->factor message adjoint
191 Prob& adj_n(size_t i, size_t _I) { return _adj_n[i][_I]; }
192 /// Returns constant reference to variable->factor message adjoint
193 const Prob& adj_n(size_t i, size_t _I) const { return _adj_n[i][_I]; }
194 /// Returns reference to factor->variable message adjoint
195 Prob& adj_m(size_t i, size_t _I) { return _adj_m[i][_I]; }
196 /// Returns constant reference to factor->variable message adjoint
197 const Prob& adj_m(size_t i, size_t _I) const { return _adj_m[i][_I]; }
198 //@}
199
200 /// \name Parallel algorithm
201 //@{
202 /// Calculates new variable->factor message adjoint
203 /** Increases variable factor adjoint according to eqn. (27) in [\ref EaG09] and
204 * calculates the new variable->factor message adjoint according to eqn. (29) in [\ref EaG09].
205 */
206 void calcNewN( size_t i, size_t _I );
207 /// Calculates new factor->variable message adjoint
208 /** Increases factor adjoint according to eqn. (28) in [\ref EaG09] and
209 * calculates the new factor->variable message adjoint according to the r.h.s. of eqn. (30) in [\ref EaG09].
210 */
211 void calcNewM( size_t i, size_t _I );
212 /// Calculates unnormalized variable->factor message adjoint from the normalized one
213 void calcUnnormMsgN( size_t i, size_t _I );
214 /// Calculates unnormalized factor->variable message adjoint from the normalized one
215 void calcUnnormMsgM( size_t i, size_t _I );
216 /// Updates (un)normalized variable->factor message adjoints
217 void upMsgN( size_t i, size_t _I );
218 /// Updates (un)normalized factor->variable message adjoints
219 void upMsgM( size_t i, size_t _I );
220 /// Do one parallel update of all message adjoints
221 void doParUpdate();
222 //@}
223
224 /// \name Sequential algorithm
225 //@{
226 /// Helper function for sendSeqMsgM(): increases factor->variable message adjoint by \a p and calculates the corresponding unnormalized adjoint
227 void incrSeqMsgM( size_t i, size_t _I, const Prob& p );
228 // DISABLED BECAUSE IT IS BUGGY:
229 // void updateSeqMsgM( size_t i, size_t _I );
230 /// Sets normalized factor->variable message adjoint and calculates the corresponding unnormalized adjoint
231 void setSeqMsgM( size_t i, size_t _I, const Prob &p );
232 /// Implements routine Send-n in Figure 5 in [\ref EaG09]
233 void sendSeqMsgN( size_t i, size_t _I, const Prob &f );
234 /// Implements routine Send-m in Figure 5 in [\ref EaG09]
235 void sendSeqMsgM( size_t i, size_t _I );
236 //@}
237
238 /// Computes the adjoint of the unnormed probability vector from the normalizer and the adjoint of the normalized probability vector
239 /** \see eqn. (13) in [\ref EaG09]
240 */
241 Prob unnormAdjoint( const Prob &w, Real Z_w, const Prob &adj_w );
242
243 /// Calculates averaged L1 norm of unnormalized message adjoints
244 Real getUnMsgMag();
245 /// Calculates averaged L1 norms of current and new normalized message adjoints
246 void getMsgMags( Real &s, Real &new_s );
247 /// Returns indices and magnitude of the largest normalized factor->variable message adjoint
248 void getArgmaxMsgM( size_t &i, size_t &_I, Real &mag );
249 /// Returns magnitude of the largest (in L1-norm) normalized factor->variable message adjoint
250 Real getMaxMsgM();
251
252 /// Calculates sum of L1 norms of all normalized factor->variable message adjoints
253 Real getTotalMsgM();
254 /// Calculates sum of L1 norms of all updated normalized factor->variable message adjoints
255 Real getTotalNewMsgM();
256 /// Calculates sum of L1 norms of all normalized variable->factor message adjoints
257 Real getTotalMsgN();
258
259 /// Returns a vector of Probs (filled with zeroes) with state spaces corresponding to the factors in the factor graph \a fg
260 std::vector<Prob> getZeroAdjF( const FactorGraph &fg );
261 /// Returns a vector of Probs (filled with zeroes) with state spaces corresponding to the variables in the factor graph \a fg
262 std::vector<Prob> getZeroAdjV( const FactorGraph &fg );
263
264 public:
265 /// \name Constructors/destructors
266 //@{
267 /// Construct BBP object from a InfAlg \a ia and a PropertySet \a opts
268 /** \param ia should be a BP object or something compatible
269 * \param opts Parameters @see Properties
270 */
271 BBP( const InfAlg *ia, const PropertySet &opts ) : _bp_dual(ia), _fg(&(ia->fg())), _ia(ia) {
272 props.set(opts);
273 }
274 //@}
275
276 /// \name Initialization
277 //@{
278 /// Initializes from given belief adjoints \a adj_b_V, \a adj_b_F and initial factor adjoints \a adj_psi_V, \a adj_psi_F
279 void init( const std::vector<Prob> &adj_b_V, const std::vector<Prob> &adj_b_F, const std::vector<Prob> &adj_psi_V, const std::vector<Prob> &adj_psi_F ) {
280 _adj_b_V = adj_b_V;
281 _adj_b_F = adj_b_F;
282 _init_adj_psi_V = adj_psi_V;
283 _init_adj_psi_F = adj_psi_F;
284 Regenerate();
285 }
286
287 /// Initializes from given belief adjoints \a adj_b_V and \a adj_b_F (setting initial factor adjoints to zero)
288 void init( const std::vector<Prob> &adj_b_V, const std::vector<Prob> &adj_b_F ) {
289 init( adj_b_V, adj_b_F, getZeroAdjV(*_fg), getZeroAdjF(*_fg) );
290 }
291
292 /// Initializes variable belief adjoints \a adj_b_V (and sets factor belief adjoints and initial factor adjoints to zero)
293 void init_V( const std::vector<Prob> &adj_b_V ) {
294 init( adj_b_V, getZeroAdjF(*_fg) );
295 }
296
297 /// Initializes factor belief adjoints \a adj_b_F (and sets variable belief adjoints and initial factor adjoints to zero)
298 void init_F( const std::vector<Prob> &adj_b_F ) {
299 init( getZeroAdjV(*_fg), adj_b_F );
300 }
301
302 /// Initializes with adjoints calculated from cost function \a cfn, and state \a stateP
303 /** Uses the internal pointer to an inference algorithm in combination with the cost function and state for initialization.
304 * \param cfn Cost function used for initialization;
305 * \param stateP is a Gibbs state and can be NULL; it will be initialised using a Gibbs run.
306 */
307 void initCostFnAdj( const BBPCostFunction &cfn, const std::vector<size_t> *stateP );
308 //@}
309
310 /// \name BBP Algorithm
311 //@{
312 /// Perform iterative updates until change is less than given tolerance
313 void run();
314 //@}
315
316 /// \name Query results
317 //@{
318 /// Returns reference to variable factor adjoint
319 Prob& adj_psi_V(size_t i) { return _adj_psi_V[i]; }
320 /// Returns constant reference to variable factor adjoint
321 const Prob& adj_psi_V(size_t i) const { return _adj_psi_V[i]; }
322 /// Returns reference to factor adjoint
323 Prob& adj_psi_F(size_t I) { return _adj_psi_F[I]; }
324 /// Returns constant reference to factor adjoint
325 const Prob& adj_psi_F(size_t I) const { return _adj_psi_F[I]; }
326 /// Returns reference to variable belief adjoint
327 Prob& adj_b_V(size_t i) { return _adj_b_V[i]; }
328 /// Returns constant reference to variable belief adjoint
329 const Prob& adj_b_V(size_t i) const { return _adj_b_V[i]; }
330 /// Returns reference to factor belief adjoint
331 Prob& adj_b_F(size_t I) { return _adj_b_F[I]; }
332 /// Returns constant reference to factor belief adjoint
333 const Prob& adj_b_F(size_t I) const { return _adj_b_F[I]; }
334 /// Return number of iterations done so far
335 size_t Iterations() { return _iters; }
336 //@}
337
338 public:
339 /// Parameters for BBP
340 /* PROPERTIES(props,BBP) {
341 /// \brief Enumeration of possible update schedules
342 /// - SEQ_FIX fixed sequential updates
343 /// - SEQ_MAX maximum residual updates (inspired by [\ref EMK06])
344 /// - SEQ_BP_REV schedule used by BP, but reversed
345 /// - SEQ_BP_FWD schedule used by BP
346 /// - PAR parallel updates
347 DAI_ENUM(UpdateType,SEQ_FIX,SEQ_MAX,SEQ_BP_REV,SEQ_BP_FWD,PAR);
348
349 /// Verbosity (amount of output sent to stderr)
350 size_t verbose;
351
352 /// Maximum number of iterations
353 size_t maxiter;
354
355 /// Tolerance for convergence test
356 /// \note Not used for updates = SEQ_BP_REV, SEQ_BP_FWD
357 Real tol;
358
359 /// Damping constant (0 for none); damping = 1 - lambda where lambda is the damping constant used in [\ref EaG09]
360 Real damping;
361
362 /// Update schedule
363 UpdateType updates;
364
365 // DISABLED BECAUSE IT IS BUGGY:
366 // bool clean_updates;
367 }
368 */
369 /* {{{ GENERATED CODE: DO NOT EDIT. Created by
370 ./scripts/regenerate-properties include/dai/bbp.h src/bbp.cpp
371 */
372 struct Properties {
373 /// Enumeration of possible update schedules
374 /** The following update schedules are defined:
375 * - SEQ_FIX fixed sequential updates
376 * - SEQ_MAX maximum residual updates (inspired by [\ref EMK06])
377 * - SEQ_BP_REV schedule used by BP, but reversed
378 * - SEQ_BP_FWD schedule used by BP
379 * - PAR parallel updates
380 */
381 DAI_ENUM(UpdateType,SEQ_FIX,SEQ_MAX,SEQ_BP_REV,SEQ_BP_FWD,PAR);
382 /// Verbosity (amount of output sent to stderr)
383 size_t verbose;
384 /// Maximum number of iterations
385 size_t maxiter;
386 /// Tolerance for convergence test
387 /** \note Not used for updates = SEQ_BP_REV, SEQ_BP_FWD
388 */
389 Real tol;
390 /// Damping constant (0 for none); damping = 1 - lambda where lambda is the damping constant used in [\ref EaG09]
391 Real damping;
392 /// Update schedule
393 UpdateType updates;
394
395 /// Set members from PropertySet
396 /** \throw UNKNOWN_PROPERTY_TYPE if a Property key is not recognized
397 * \throw NOT_ALL_PROPERTIES_SPECIFIED if an expected Property is missing
398 */
399 void set(const PropertySet &opts);
400 /// Get members into PropertySet
401 PropertySet get() const;
402 /// Convert to a string which can be parsed as a PropertySet
403 std::string toString() const;
404 } props;
405 /* }}} END OF GENERATED CODE */
406 };
407
408
409 /// Function to verify the validity of adjoints computed by BBP using numerical differentiation.
410 /** Factors containing a variable are multiplied by small adjustments to verify accuracy of calculated variable factor adjoints.
411 * \param bp BP object;
412 * \param state Global state of all variables;
413 * \param bbp_props BBP parameters;
414 * \param cfn Cost function to be used;
415 * \param h Size of perturbation.
416 * \relates BBP
417 */
418 Real numericBBPTest( const InfAlg &bp, const std::vector<size_t> *state, const PropertySet &bbp_props, const BBPCostFunction &cfn, Real h );
419
420
421 } // end of namespace dai
422
423
424 #endif