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