[Frederik Eaton] Major cleanup of BBP and CBP code and documentation
[libdai.git] / src / lc.cpp
1 /* Copyright (C) 2006-2008 Joris Mooij [joris dot mooij at tuebingen dot mpg dot de]
2 Radboud University Nijmegen, The Netherlands /
3 Max Planck Institute for Biological Cybernetics, Germany
4
5 This file is part of libDAI.
6
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22
23 #include <iostream>
24 #include <algorithm>
25 #include <map>
26 #include <set>
27 #include <dai/lc.h>
28 #include <dai/util.h>
29 #include <dai/alldai.h>
30
31
32 namespace dai {
33
34
35 using namespace std;
36
37
38 const char *LC::Name = "LC";
39
40
41 void LC::setProperties( const PropertySet &opts ) {
42 assert( opts.hasKey("tol") );
43 assert( opts.hasKey("maxiter") );
44 assert( opts.hasKey("verbose") );
45 assert( opts.hasKey("cavity") );
46 assert( opts.hasKey("updates") );
47
48 props.tol = opts.getStringAs<double>("tol");
49 props.maxiter = opts.getStringAs<size_t>("maxiter");
50 props.verbose = opts.getStringAs<size_t>("verbose");
51 props.cavity = opts.getStringAs<Properties::CavityType>("cavity");
52 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
53 if( opts.hasKey("cavainame") )
54 props.cavainame = opts.getStringAs<string>("cavainame");
55 if( opts.hasKey("cavaiopts") )
56 props.cavaiopts = opts.getStringAs<PropertySet>("cavaiopts");
57 if( opts.hasKey("reinit") )
58 props.reinit = opts.getStringAs<bool>("reinit");
59 if( opts.hasKey("damping") )
60 props.damping = opts.getStringAs<double>("damping");
61 else
62 props.damping = 0.0;
63 }
64
65
66 PropertySet LC::getProperties() const {
67 PropertySet opts;
68 opts.Set( "tol", props.tol );
69 opts.Set( "maxiter", props.maxiter );
70 opts.Set( "verbose", props.verbose );
71 opts.Set( "cavity", props.cavity );
72 opts.Set( "updates", props.updates );
73 opts.Set( "cavainame", props.cavainame );
74 opts.Set( "cavaiopts", props.cavaiopts );
75 opts.Set( "reinit", props.reinit );
76 opts.Set( "damping", props.damping );
77 return opts;
78 }
79
80
81 string LC::printProperties() const {
82 stringstream s( stringstream::out );
83 s << "[";
84 s << "tol=" << props.tol << ",";
85 s << "maxiter=" << props.maxiter << ",";
86 s << "verbose=" << props.verbose << ",";
87 s << "cavity=" << props.cavity << ",";
88 s << "updates=" << props.updates << ",";
89 s << "cavainame=" << props.cavainame << ",";
90 s << "cavaiopts=" << props.cavaiopts << ",";
91 s << "reinit=" << props.reinit << ",";
92 s << "damping=" << props.damping << "]";
93 return s.str();
94 }
95
96
97 LC::LC( const FactorGraph & fg, const PropertySet &opts ) : DAIAlgFG(fg), _pancakes(), _cavitydists(), _phis(), _beliefs(), _maxdiff(0.0), _iters(0), props() {
98 setProperties( opts );
99
100 // create pancakes
101 _pancakes.resize( nrVars() );
102
103 // create cavitydists
104 for( size_t i=0; i < nrVars(); i++ )
105 _cavitydists.push_back(Factor( delta(i) ));
106
107 // create phis
108 _phis.reserve( nrVars() );
109 for( size_t i = 0; i < nrVars(); i++ ) {
110 _phis.push_back( vector<Factor>() );
111 _phis[i].reserve( nbV(i).size() );
112 foreach( const Neighbor &I, nbV(i) )
113 _phis[i].push_back( Factor( factor(I).vars() / var(i) ) );
114 }
115
116 // create beliefs
117 _beliefs.reserve( nrVars() );
118 for( size_t i=0; i < nrVars(); i++ )
119 _beliefs.push_back(Factor(var(i)));
120 }
121
122
123 string LC::identify() const {
124 return string(Name) + printProperties();
125 }
126
127
128 void LC::CalcBelief (size_t i) {
129 _beliefs[i] = _pancakes[i].marginal(var(i));
130 }
131
132
133 double LC::CalcCavityDist (size_t i, const std::string &name, const PropertySet &opts) {
134 Factor Bi;
135 double maxdiff = 0;
136
137 if( props.verbose >= 2 )
138 cerr << "Initing cavity " << var(i) << "(" << delta(i).size() << " vars, " << delta(i).nrStates() << " states)" << endl;
139
140 if( props.cavity == Properties::CavityType::UNIFORM )
141 Bi = Factor(delta(i));
142 else {
143 InfAlg *cav = newInfAlg( name, *this, opts );
144 cav->makeCavity( i );
145
146 if( props.cavity == Properties::CavityType::FULL )
147 Bi = calcMarginal( *cav, cav->fg().delta(i), props.reinit );
148 else if( props.cavity == Properties::CavityType::PAIR )
149 Bi = calcMarginal2ndO( *cav, cav->fg().delta(i), props.reinit );
150 else if( props.cavity == Properties::CavityType::PAIR2 ) {
151 vector<Factor> pairbeliefs = calcPairBeliefsNew( *cav, cav->fg().delta(i), props.reinit );
152 for( size_t ij = 0; ij < pairbeliefs.size(); ij++ )
153 Bi *= pairbeliefs[ij];
154 }
155 maxdiff = cav->maxDiff();
156 delete cav;
157 }
158 Bi.normalize();
159 _cavitydists[i] = Bi;
160
161 return maxdiff;
162 }
163
164
165 double LC::InitCavityDists( const std::string &name, const PropertySet &opts ) {
166 double tic = toc();
167
168 if( props.verbose >= 1 ) {
169 cerr << Name << "::InitCavityDists: ";
170 if( props.cavity == Properties::CavityType::UNIFORM )
171 cerr << "Using uniform initial cavity distributions" << endl;
172 else if( props.cavity == Properties::CavityType::FULL )
173 cerr << "Using full " << name << opts << "...";
174 else if( props.cavity == Properties::CavityType::PAIR )
175 cerr << "Using pairwise " << name << opts << "...";
176 else if( props.cavity == Properties::CavityType::PAIR2 )
177 cerr << "Using pairwise(new) " << name << opts << "...";
178 }
179
180 double maxdiff = 0.0;
181 for( size_t i = 0; i < nrVars(); i++ ) {
182 double md = CalcCavityDist(i, name, opts);
183 if( md > maxdiff )
184 maxdiff = md;
185 }
186
187 if( props.verbose >= 1 ) {
188 cerr << Name << "::InitCavityDists used " << toc() - tic << " seconds." << endl;
189 }
190
191 return maxdiff;
192 }
193
194
195 long LC::SetCavityDists( std::vector<Factor> &Q ) {
196 if( props.verbose >= 1 )
197 cerr << Name << "::SetCavityDists: Setting initial cavity distributions" << endl;
198 if( Q.size() != nrVars() )
199 return -1;
200 for( size_t i = 0; i < nrVars(); i++ ) {
201 if( _cavitydists[i].vars() != Q[i].vars() ) {
202 return i+1;
203 } else
204 _cavitydists[i] = Q[i];
205 }
206 return 0;
207 }
208
209
210 void LC::init() {
211 for( size_t i = 0; i < nrVars(); ++i )
212 foreach( const Neighbor &I, nbV(i) )
213 if( props.updates == Properties::UpdateType::SEQRND )
214 _phis[i][I.iter].randomize();
215 else
216 _phis[i][I.iter].fill(1.0);
217 }
218
219
220 Factor LC::NewPancake (size_t i, size_t _I, bool & hasNaNs) {
221 size_t I = nbV(i)[_I];
222 Factor piet = _pancakes[i];
223
224 // recalculate _pancake[i]
225 VarSet Ivars = factor(I).vars();
226 Factor A_I;
227 for( VarSet::const_iterator k = Ivars.begin(); k != Ivars.end(); k++ )
228 if( var(i) != *k )
229 A_I *= (_pancakes[findVar(*k)] * factor(I).inverse()).marginal( Ivars / var(i), false );
230 if( Ivars.size() > 1 )
231 A_I ^= (1.0 / (Ivars.size() - 1));
232 Factor A_Ii = (_pancakes[i] * factor(I).inverse() * _phis[i][_I].inverse()).marginal( Ivars / var(i), false );
233 Factor quot = A_I / A_Ii;
234 if( props.damping != 0.0 )
235 quot = (quot^(1.0 - props.damping)) * (_phis[i][_I]^props.damping);
236
237 piet *= quot / _phis[i][_I].normalized();
238 _phis[i][_I] = quot.normalized();
239
240 piet.normalize();
241
242 if( piet.hasNaNs() ) {
243 cerr << Name << "::NewPancake(" << i << ", " << _I << "): has NaNs!" << endl;
244 hasNaNs = true;
245 }
246
247 return piet;
248 }
249
250
251 double LC::run() {
252 if( props.verbose >= 1 )
253 cerr << "Starting " << identify() << "...";
254 if( props.verbose >= 2 )
255 cerr << endl;
256
257 double tic = toc();
258 Diffs diffs(nrVars(), 1.0);
259
260 double md = InitCavityDists( props.cavainame, props.cavaiopts );
261 if( md > _maxdiff )
262 _maxdiff = md;
263
264 for( size_t i = 0; i < nrVars(); i++ ) {
265 _pancakes[i] = _cavitydists[i];
266
267 foreach( const Neighbor &I, nbV(i) ) {
268 _pancakes[i] *= factor(I);
269 if( props.updates == Properties::UpdateType::SEQRND )
270 _pancakes[i] *= _phis[i][I.iter];
271 }
272
273 _pancakes[i].normalize();
274
275 CalcBelief(i);
276 }
277
278 vector<Factor> old_beliefs;
279 for(size_t i=0; i < nrVars(); i++ )
280 old_beliefs.push_back(belief(i));
281
282 bool hasNaNs = false;
283 for( size_t i=0; i < nrVars(); i++ )
284 if( _pancakes[i].hasNaNs() ) {
285 hasNaNs = true;
286 break;
287 }
288 if( hasNaNs ) {
289 cerr << Name << "::run: initial _pancakes has NaNs!" << endl;
290 return 1.0;
291 }
292
293 size_t nredges = nrEdges();
294 vector<Edge> update_seq;
295 update_seq.reserve( nredges );
296 for( size_t i = 0; i < nrVars(); ++i )
297 foreach( const Neighbor &I, nbV(i) )
298 update_seq.push_back( Edge( i, I.iter ) );
299
300 // do several passes over the network until maximum number of iterations has
301 // been reached or until the maximum belief difference is smaller than tolerance
302 for( _iters=0; _iters < props.maxiter && diffs.maxDiff() > props.tol; _iters++ ) {
303 // Sequential updates
304 if( props.updates == Properties::UpdateType::SEQRND )
305 random_shuffle( update_seq.begin(), update_seq.end() );
306
307 for( size_t t=0; t < nredges; t++ ) {
308 size_t i = update_seq[t].first;
309 size_t _I = update_seq[t].second;
310 _pancakes[i] = NewPancake( i, _I, hasNaNs);
311 if( hasNaNs )
312 return 1.0;
313 CalcBelief( i );
314 }
315
316 // compare new beliefs with old ones
317 for(size_t i=0; i < nrVars(); i++ ) {
318 diffs.push( dist( belief(i), old_beliefs[i], Prob::DISTLINF ) );
319 old_beliefs[i] = belief(i);
320 }
321
322 if( props.verbose >= 3 )
323 cerr << Name << "::run: maxdiff " << diffs.maxDiff() << " after " << _iters+1 << " passes" << endl;
324 }
325
326 if( diffs.maxDiff() > _maxdiff )
327 _maxdiff = diffs.maxDiff();
328
329 if( props.verbose >= 1 ) {
330 if( diffs.maxDiff() > props.tol ) {
331 if( props.verbose == 1 )
332 cerr << endl;
333 cerr << Name << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << diffs.maxDiff() << endl;
334 } else {
335 if( props.verbose >= 2 )
336 cerr << Name << "::run: ";
337 cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
338 }
339 }
340
341 return diffs.maxDiff();
342 }
343
344
345 } // end of namespace dai