Various cleanups
[libdai.git] / include / dai / cbp.h
1 /* Copyright (C) 2009 Frederik Eaton [frederik at ofb dot net]
2
3 This file is part of libDAI.
4
5 libDAI is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 libDAI is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with libDAI; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20
21 /// \file
22 /// \brief Defines class CBP [\ref EaG09]
23 /// \todo Improve documentation
24 /// \todo Clean up
25
26
27 #ifndef __defined_libdai_cbp_h
28 #define __defined_libdai_cbp_h
29
30
31 #include <fstream>
32
33 #include <boost/shared_ptr.hpp>
34
35 #include <dai/daialg.h>
36
37 #include <dai/cbp.h>
38 #include <dai/bbp.h>
39
40
41 namespace dai {
42
43
44 /// Find a variable to clamp using BBP (goes with maximum adjoint)
45 /// \see BBP
46 std::pair<size_t, size_t> bbpFindClampVar(const InfAlg &in_bp, bool clampingVar,
47 const PropertySet &bbp_props, bbp_cfn_t cfn,
48 Real *maxVarOut);
49
50
51 /// Class for CBP (Clamped Belief Propagation)
52 /** This algorithm uses configurable heuristics to choose a variable
53 * x_i and a state x_i*. Inference is done with x_i "clamped" to x_i*
54 * (e.g. conditional on x_i==x_i*), and also with the negation of this
55 * condition. Clamping is done recursively up to a fixed number of
56 * levels (other stopping criteria are also implemented, see
57 * "recursion" property). The resulting approximate marginals are
58 * combined using logZ estimates.
59 */
60 class CBP : public DAIAlgFG {
61 std::vector<Factor> _beliefsV;
62 std::vector<Factor> _beliefsF;
63 double _logZ;
64 double _est_logZ;
65 double _old_est_logZ;
66
67 double _sum_level;
68 size_t _num_leaves;
69
70 boost::shared_ptr<std::ofstream> _clamp_ofstream;
71
72 bbp_cfn_t BBP_cost_function() {
73 return props.bbp_cfn;
74 }
75
76 void printDebugInfo();
77
78 /// Called by 'run', and by itself. Implements the main algorithm.
79 /** Chooses a variable to clamp, recurses, combines the logZ and
80 * beliefs estimates of the children, and returns the improved
81 * estimates in \a lz_out and \a beliefs_out to its parent
82 */
83 void runRecurse(InfAlg *bp,
84 double orig_logZ,
85 std::vector<size_t> clamped_vars_list,
86 size_t &num_leaves,
87 size_t &choose_count,
88 double &sum_level,
89 Real &lz_out,
90 std::vector<Factor>& beliefs_out);
91
92 /// Choose the next variable to clamp
93 /** Choose the next variable to clamp, given a converged InfAlg (\a bp),
94 * and a vector of variables that are already clamped (\a
95 * clamped_vars_list). Returns the chosen variable in \a i, and
96 * the set of states in \a xis. If \a maxVarOut is non-NULL and
97 * props.choose==CHOOSE_BBP then it is used to store the
98 * adjoint of the chosen variable
99 */
100 virtual bool chooseNextClampVar(InfAlg* bp,
101 std::vector<size_t> &clamped_vars_list,
102 size_t &i, std::vector<size_t> &xis, Real *maxVarOut);
103
104 /// Return the InfAlg to use at each step of the recursion.
105 /// \todo At present, only returns a BP instance
106 InfAlg* getInfAlg();
107
108 size_t _iters;
109 double _maxdiff;
110
111 void setBeliefs(const std::vector<Factor>& bs, double logZ) {
112 size_t i=0;
113 _beliefsV.clear(); _beliefsV.reserve(nrVars());
114 _beliefsF.clear(); _beliefsF.reserve(nrFactors());
115 for(i=0; i<nrVars(); i++) _beliefsV.push_back(bs[i]);
116 for(; i<nrVars()+nrFactors(); i++) _beliefsF.push_back(bs[i]);
117 _logZ = logZ;
118 }
119
120 void construct();
121
122 public:
123
124 //----------------------------------------------------------------
125
126 /// construct CBP object from FactorGraph
127 CBP(const FactorGraph &fg, const PropertySet &opts) : DAIAlgFG(fg) {
128 props.set(opts);
129 construct();
130 }
131
132 static const char *Name;
133
134 /// @name General InfAlg interface
135 //@{
136 virtual CBP* clone() const { return new CBP(*this); }
137 virtual CBP* create() const { DAI_THROW(NOT_IMPLEMENTED); }
138 virtual std::string identify() const { return std::string(Name) + props.toString(); }
139 virtual Factor belief (const Var &n) const { return _beliefsV[findVar(n)]; }
140 virtual Factor belief (const VarSet &) const { DAI_THROW(NOT_IMPLEMENTED); }
141 virtual std::vector<Factor> beliefs() const { return concat(_beliefsV, _beliefsF); }
142 virtual Real logZ() const { return _logZ; }
143 virtual void init() {};
144 virtual void init( const VarSet & ) {};
145 virtual double run();
146 virtual double maxDiff() const { return _maxdiff; }
147 virtual size_t Iterations() const { return _iters; }
148 //@}
149
150 Factor beliefV (size_t i) const { return _beliefsV[i]; }
151 Factor beliefF (size_t I) const { return _beliefsF[I]; }
152
153 //----------------------------------------------------------------
154
155 public:
156 /// Parameters of this inference algorithm
157 /* PROPERTIES(props,CBP) {
158 typedef BP::Properties::UpdateType UpdateType;
159 DAI_ENUM(RecurseType,REC_FIXED,REC_LOGZ,REC_BDIFF);
160 DAI_ENUM(ChooseMethodType,CHOOSE_RANDOM,CHOOSE_MAXENT,CHOOSE_BBP,CHOOSE_BP_L1,CHOOSE_BP_CFN);
161 DAI_ENUM(ClampType,CLAMP_VAR,CLAMP_FACTOR);
162
163 size_t verbose = 0;
164
165 /// Tolerance to use in BP
166 double tol;
167 /// Update style for BP
168 UpdateType updates;
169 /// Maximum number of iterations for BP
170 size_t maxiter;
171
172 /// Tolerance to use for controlling recursion depth (\a recurse
173 /// is REC_LOGZ or REC_BDIFF)
174 double rec_tol;
175 /// Maximum number of levels of recursion (\a recurse is REC_FIXED)
176 size_t max_levels = 10;
177 /// If choose=CHOOSE_BBP and maximum adjoint is less than this value, don't recurse
178 double min_max_adj;
179 /// Heuristic for choosing clamping variable
180 ChooseMethodType choose;
181 /// Method for deciding when to stop recursing
182 RecurseType recursion;
183 /// Whether to clamp variables or factors
184 ClampType clamp;
185 /// Properties to pass to BBP
186 PropertySet bbp_props;
187 /// Cost function to use for BBP
188 bbp_cfn_t bbp_cfn;
189 /// Random seed
190 size_t rand_seed = 0;
191
192 /// If non-empty, write clamping choices to this file
193 std::string clamp_outfile = "";
194 }
195 */
196 /* {{{ GENERATED CODE: DO NOT EDIT. Created by
197 ./scripts/regenerate-properties include/dai/cbp.h src/cbp.cpp
198 */
199 struct Properties {
200 typedef BP::Properties::UpdateType UpdateType;
201 DAI_ENUM(RecurseType,REC_FIXED,REC_LOGZ,REC_BDIFF);
202 DAI_ENUM(ChooseMethodType,CHOOSE_RANDOM,CHOOSE_MAXENT,CHOOSE_BBP,CHOOSE_BP_L1,CHOOSE_BP_CFN);
203 DAI_ENUM(ClampType,CLAMP_VAR,CLAMP_FACTOR);
204 size_t verbose;
205 /// Tolerance to use in BP
206 double tol;
207 /// Update style for BP
208 UpdateType updates;
209 /// Maximum number of iterations for BP
210 size_t maxiter;
211 /// Tolerance to use for controlling recursion depth (\a recurse
212 /// is REC_LOGZ or REC_BDIFF)
213 double rec_tol;
214 /// Maximum number of levels of recursion (\a recurse is REC_FIXED)
215 size_t max_levels;
216 /// If choose=CHOOSE_BBP and maximum adjoint is less than this value, don't recurse
217 double min_max_adj;
218 /// Heuristic for choosing clamping variable
219 ChooseMethodType choose;
220 /// Method for deciding when to stop recursing
221 RecurseType recursion;
222 /// Whether to clamp variables or factors
223 ClampType clamp;
224 /// Properties to pass to BBP
225 PropertySet bbp_props;
226 /// Cost function to use for BBP
227 bbp_cfn_t bbp_cfn;
228 /// Random seed
229 size_t rand_seed;
230 /// If non-empty, write clamping choices to this file
231 std::string clamp_outfile;
232
233 /// Set members from PropertySet
234 void set(const PropertySet &opts);
235 /// Get members into PropertySet
236 PropertySet get() const;
237 /// Convert to a string which can be parsed as a PropertySet
238 std::string toString() const;
239 } props;
240 /* }}} END OF GENERATED CODE */
241
242 Properties::ChooseMethodType ChooseMethod() { return props.choose; }
243 Properties::RecurseType Recursion() { return props.recursion; }
244 Properties::ClampType Clamping() { return props.clamp; }
245 size_t maxClampLevel() { return props.max_levels; }
246 double minMaxAdj() { return props.min_max_adj; }
247 double recTol() { return props.rec_tol; }
248 };
249
250 /// Given a sorted vector of states \a xis and total state count \a n_states, return a vector of states not in \a xis
251 std::vector<size_t> complement( std::vector<size_t>& xis, size_t n_states );
252
253 /// Computes \f$\frac{\exp(a)}{\exp(a)+\exp(b)}\f$
254 Real unSoftMax( Real a, Real b );
255
256 /// Computes log of sum of exponents, i.e., \f$\log\left(\exp(a) + \exp(b)\right)\f$
257 Real logSumExp( Real a, Real b );
258
259 /// Compute sum of pairwise L-infinity distances of the first \a nv factors in each vector
260 Real dist( const std::vector<Factor>& b1, const std::vector<Factor>& b2, size_t nv );
261
262
263 } // end of namespace dai
264
265
266 #endif