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) 2009 Frederik Eaton [frederik at ofb dot net]
8 */
11 /// \file
12 /// \brief Defines class CBP, which implements Conditioned Belief Propagation
15 #ifndef __defined_libdai_cbp_h
16 #define __defined_libdai_cbp_h
19 #include <fstream>
20 #include <boost/shared_ptr.hpp>
22 #include <dai/daialg.h>
23 #include <dai/bbp.h>
26 namespace dai {
29 /// Class for CBP (Conditioned Belief Propagation) [\ref EaG09]
30 /** This approximate inference algorithm uses configurable heuristics to choose a variable
31 * \f$x_i \f$ and a state \f$x_i^* \f$. Inference is done with \f$x_i \f$ "clamped" to \f$x_i^* \f$
32 * (i.e., conditional on \f$x_i = x_i^* \f$), and also with the negation of this condition.
33 * Clamping is done recursively up to a fixed number of levels (other stopping criteria are
34 * also implemented, see the CBP::Properties::RecurseType property). The resulting approximate
35 * marginals are combined using estimates of the partition sum.
36 *
37 * \author Frederik Eaton
38 */
39 class CBP : public DAIAlgFG {
40 private:
41 /// Variable beliefs
42 std::vector<Factor> _beliefsV;
43 /// Factor beliefs
44 std::vector<Factor> _beliefsF;
45 /// Logarithm of partition sum
46 Real _logZ;
48 /// Numer of iterations needed
49 size_t _iters;
50 /// Maximum difference encountered so far
51 Real _maxdiff;
53 /// Number of clampings at each leaf node
54 Real _sum_level;
55 /// Number of leaves of recursion tree
56 size_t _num_leaves;
58 /// Output stream where information about the clampings is written
59 boost::shared_ptr<std::ofstream> _clamp_ofstream;
62 public:
63 /// Default constructor
64 CBP() : DAIAlgFG(), _beliefsV(), _beliefsF(), _logZ(0.0), _iters(0), _maxdiff(0.0), _sum_level(0.0), _num_leaves(0), _clamp_ofstream() {}
66 /// Construct CBP object from FactorGraph \a fg and PropertySet \a opts
67 /** \param fg Factor graph.
68 * \param opts Parameters @see Properties
69 */
70 CBP( const FactorGraph &fg, const PropertySet &opts ) : DAIAlgFG(fg) {
71 props.set( opts );
72 construct();
73 }
75 /// \name General InfAlg interface
76 //@{
77 virtual CBP* clone() const { return new CBP(*this); }
78 virtual std::string name() const { return "CBP"; }
79 virtual Factor belief( const Var &v ) const { return beliefV( findVar( v ) ); }
80 virtual Factor belief( const VarSet & ) const { DAI_THROW(NOT_IMPLEMENTED); }
81 virtual Factor beliefV( size_t i ) const { return _beliefsV[i]; }
82 virtual Factor beliefF( size_t I ) const { return _beliefsF[I]; }
83 virtual std::vector<Factor> beliefs() const { return concat(_beliefsV, _beliefsF); }
84 virtual Real logZ() const { return _logZ; }
85 virtual void init() {};
86 virtual void init( const VarSet & ) {};
87 virtual Real run();
88 virtual Real maxDiff() const { return _maxdiff; }
89 virtual size_t Iterations() const { return _iters; }
90 virtual void setMaxIter( size_t maxiter ) { props.maxiter = maxiter; }
91 virtual void setProperties( const PropertySet &opts ) { props.set( opts ); }
92 virtual PropertySet getProperties() const { return props.get(); }
93 virtual std::string printProperties() const { return props.toString(); }
94 //@}
96 //----------------------------------------------------------------
98 /// Parameters for CBP
99 /* PROPERTIES(props,CBP) {
100 /// Enumeration of possible update schedules
101 typedef BP::Properties::UpdateType UpdateType;
102 /// Enumeration of possible methods for deciding when to stop recursing
103 DAI_ENUM(RecurseType,REC_FIXED,REC_LOGZ,REC_BDIFF);
104 /// Enumeration of possible heuristics for choosing clamping variable
105 DAI_ENUM(ChooseMethodType,CHOOSE_RANDOM,CHOOSE_MAXENT,CHOOSE_BBP,CHOOSE_BP_L1,CHOOSE_BP_CFN);
106 /// Enumeration of possible clampings: variables or factors
107 DAI_ENUM(ClampType,CLAMP_VAR,CLAMP_FACTOR);
109 /// Verbosity (amount of output sent to stderr)
110 size_t verbose = 0;
112 /// Tolerance for BP convergence test
113 Real tol;
114 /// Update style for BP
116 /// Maximum number of iterations for BP
117 size_t maxiter;
119 /// Tolerance used for controlling recursion depth (\a recurse is REC_LOGZ or REC_BDIFF)
120 Real rec_tol;
121 /// Maximum number of levels of recursion (\a recurse is REC_FIXED)
122 size_t max_levels = 10;
123 /// If choose==CHOOSE_BBP and maximum adjoint is less than this value, don't recurse
125 /// Heuristic for choosing clamping variable
126 ChooseMethodType choose;
127 /// Method for deciding when to stop recursing
128 RecurseType recursion;
129 /// Whether to clamp variables or factors
130 ClampType clamp;
131 /// Properties to pass to BBP
132 PropertySet bbp_props;
133 /// Cost function to use for BBP
134 BBPCostFunction bbp_cfn;
135 /// Random seed
136 size_t rand_seed = 0;
138 /// If non-empty, write clamping choices to this file
139 std::string clamp_outfile = "";
140 }
141 */
142 /* {{{ GENERATED CODE: DO NOT EDIT. Created by
143 ./scripts/regenerate-properties include/dai/cbp.h src/cbp.cpp
144 */
145 struct Properties {
146 /// Enumeration of possible update schedules
147 typedef BP::Properties::UpdateType UpdateType;
148 /// Enumeration of possible methods for deciding when to stop recursing
149 DAI_ENUM(RecurseType,REC_FIXED,REC_LOGZ,REC_BDIFF);
150 /// Enumeration of possible heuristics for choosing clamping variable
151 DAI_ENUM(ChooseMethodType,CHOOSE_RANDOM,CHOOSE_MAXENT,CHOOSE_BBP,CHOOSE_BP_L1,CHOOSE_BP_CFN);
152 /// Enumeration of possible clampings: variables or factors
153 DAI_ENUM(ClampType,CLAMP_VAR,CLAMP_FACTOR);
154 /// Verbosity (amount of output sent to stderr)
155 size_t verbose;
156 /// Tolerance for BP convergence test
157 Real tol;
158 /// Update style for BP
160 /// Maximum number of iterations for BP
161 size_t maxiter;
162 /// Tolerance used for controlling recursion depth (\a recurse is REC_LOGZ or REC_BDIFF)
163 Real rec_tol;
164 /// Maximum number of levels of recursion (\a recurse is REC_FIXED)
165 size_t max_levels;
166 /// If choose==CHOOSE_BBP and maximum adjoint is less than this value, don't recurse
168 /// Heuristic for choosing clamping variable
169 ChooseMethodType choose;
170 /// Method for deciding when to stop recursing
171 RecurseType recursion;
172 /// Whether to clamp variables or factors
173 ClampType clamp;
174 /// Properties to pass to BBP
175 PropertySet bbp_props;
176 /// Cost function to use for BBP
177 BBPCostFunction bbp_cfn;
178 /// Random seed
179 size_t rand_seed;
180 /// If non-empty, write clamping choices to this file
181 std::string clamp_outfile;
183 /// Set members from PropertySet
184 /** \throw UNKNOWN_PROPERTY if a Property key is not recognized
185 * \throw NOT_ALL_PROPERTIES_SPECIFIED if an expected Property is missing
186 */
187 void set(const PropertySet &opts);
188 /// Get members into PropertySet
189 PropertySet get() const;
190 /// Convert to a string which can be parsed as a PropertySet
191 std::string toString() const;
192 } props;
193 /* }}} END OF GENERATED CODE */
195 private:
196 /// Prints beliefs, variables and partition sum, in case of a debugging build
197 void printDebugInfo();
199 /// Called by run(), and by itself. Implements the main algorithm.
200 /** Chooses a variable to clamp, recurses, combines the partition sum
201 * and belief estimates of the children, and returns the improved
202 * estimates in \a lz_out and \a beliefs_out to its parent.
203 */
204 void runRecurse( InfAlg *bp, Real orig_logZ, std::vector<size_t> clamped_vars_list, size_t &num_leaves,
205 size_t &choose_count, Real &sum_level, Real &lz_out, std::vector<Factor> &beliefs_out );
207 /// Choose the next variable to clamp.
208 /** Choose the next variable to clamp, given a converged InfAlg \a bp,
209 * and a vector of variables that are already clamped (\a
210 * clamped_vars_list). Returns the chosen variable in \a i, and
211 * the set of states in \a xis. If \a maxVarOut is non-NULL and
212 * \a props.choose == \c CHOOSE_BBP then it is used to store the
213 * adjoint of the chosen variable.
214 */
215 virtual bool chooseNextClampVar( InfAlg* bp, std::vector<size_t> &clamped_vars_list, size_t &i, std::vector<size_t> &xis, Real *maxVarOut );
217 /// Return the InfAlg to use at each step of the recursion.
218 /** \todo At present, CBP::getInfAlg() only returns a BP instance;
219 * it should be possible to select other inference algorithms via a property
220 */
221 InfAlg* getInfAlg();
223 /// Sets variable beliefs, factor beliefs and log partition sum to the specified values
224 /** \param bs should be a concatenation of the variable beliefs followed by the factor beliefs
225 * \param logZ log partition sum
226 */
227 void setBeliefs( const std::vector<Factor> &bs, Real logZ );
229 /// Constructor helper function
230 void construct();
231 };
234 /// Find the best variable/factor to clamp using BBP.
235 /** Takes a converged inference algorithm as input, runs Gibbs and BP_dual, creates
236 * and runs a BBP object, finds the best variable/factor (the one with the maximum
237 * factor adjoint), and returns the corresponding (index,state) pair.
238 * \param in_bp inference algorithm (compatible with BP) that should have converged;
239 * \param clampingVar if \c true, finds best variable, otherwise, finds best factor;
240 * \param bbp_props BBP parameters to use;
241 * \param cfn BBP cost function to use;
242 * \param maxVarOut maximum adjoint value (only set if not NULL).
243 * \see BBP
244 * \relates CBP
245 */
246 std::pair<size_t, size_t> BBPFindClampVar( const InfAlg &in_bp, bool clampingVar, const PropertySet &bbp_props, const BBPCostFunction &cfn, Real *maxVarOut );
249 } // end of namespace dai
252 #endif