Cleaned up variable elimination code in ClusterGraph
[libdai.git] / src / bp.cpp
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) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 #include <iostream>
13 #include <sstream>
14 #include <map>
15 #include <set>
16 #include <algorithm>
17 #include <stack>
18 #include <dai/bp.h>
19 #include <dai/util.h>
20 #include <dai/properties.h>
21
22
23 namespace dai {
24
25
26 using namespace std;
27
28
29 const char *BP::Name = "BP";
30
31
32 #define DAI_BP_FAST 1
33
34
35 void BP::setProperties( const PropertySet &opts ) {
36 DAI_ASSERT( opts.hasKey("tol") );
37 DAI_ASSERT( opts.hasKey("maxiter") );
38 DAI_ASSERT( opts.hasKey("logdomain") );
39 DAI_ASSERT( opts.hasKey("updates") );
40
41 props.tol = opts.getStringAs<Real>("tol");
42 props.maxiter = opts.getStringAs<size_t>("maxiter");
43 props.logdomain = opts.getStringAs<bool>("logdomain");
44 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
45
46 if( opts.hasKey("verbose") )
47 props.verbose = opts.getStringAs<size_t>("verbose");
48 else
49 props.verbose = 0;
50 if( opts.hasKey("damping") )
51 props.damping = opts.getStringAs<Real>("damping");
52 else
53 props.damping = 0.0;
54 if( opts.hasKey("inference") )
55 props.inference = opts.getStringAs<Properties::InfType>("inference");
56 else
57 props.inference = Properties::InfType::SUMPROD;
58 }
59
60
61 PropertySet BP::getProperties() const {
62 PropertySet opts;
63 opts.Set( "tol", props.tol );
64 opts.Set( "maxiter", props.maxiter );
65 opts.Set( "verbose", props.verbose );
66 opts.Set( "logdomain", props.logdomain );
67 opts.Set( "updates", props.updates );
68 opts.Set( "damping", props.damping );
69 opts.Set( "inference", props.inference );
70 return opts;
71 }
72
73
74 string BP::printProperties() const {
75 stringstream s( stringstream::out );
76 s << "[";
77 s << "tol=" << props.tol << ",";
78 s << "maxiter=" << props.maxiter << ",";
79 s << "verbose=" << props.verbose << ",";
80 s << "logdomain=" << props.logdomain << ",";
81 s << "updates=" << props.updates << ",";
82 s << "damping=" << props.damping << ",";
83 s << "inference=" << props.inference << "]";
84 return s.str();
85 }
86
87
88 void BP::construct() {
89 // create edge properties
90 _edges.clear();
91 _edges.reserve( nrVars() );
92 _edge2lut.clear();
93 if( props.updates == Properties::UpdateType::SEQMAX )
94 _edge2lut.reserve( nrVars() );
95 for( size_t i = 0; i < nrVars(); ++i ) {
96 _edges.push_back( vector<EdgeProp>() );
97 _edges[i].reserve( nbV(i).size() );
98 if( props.updates == Properties::UpdateType::SEQMAX ) {
99 _edge2lut.push_back( vector<LutType::iterator>() );
100 _edge2lut[i].reserve( nbV(i).size() );
101 }
102 foreach( const Neighbor &I, nbV(i) ) {
103 EdgeProp newEP;
104 newEP.message = Prob( var(i).states() );
105 newEP.newMessage = Prob( var(i).states() );
106
107 if( DAI_BP_FAST ) {
108 newEP.index.reserve( factor(I).states() );
109 for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
110 newEP.index.push_back( k );
111 }
112
113 newEP.residual = 0.0;
114 _edges[i].push_back( newEP );
115 if( props.updates == Properties::UpdateType::SEQMAX )
116 _edge2lut[i].push_back( _lut.insert( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))) );
117 }
118 }
119 }
120
121
122 void BP::init() {
123 Real c = props.logdomain ? 0.0 : 1.0;
124 for( size_t i = 0; i < nrVars(); ++i ) {
125 foreach( const Neighbor &I, nbV(i) ) {
126 message( i, I.iter ).fill( c );
127 newMessage( i, I.iter ).fill( c );
128 if( props.updates == Properties::UpdateType::SEQMAX )
129 updateResidual( i, I.iter, 0.0 );
130 }
131 }
132 }
133
134
135 void BP::findMaxResidual( size_t &i, size_t &_I ) {
136 DAI_ASSERT( !_lut.empty() );
137 LutType::const_iterator largestEl = _lut.end();
138 --largestEl;
139 i = largestEl->second.first;
140 _I = largestEl->second.second;
141 }
142
143
144 void BP::calcNewMessage( size_t i, size_t _I ) {
145 // calculate updated message I->i
146 size_t I = nbV(i,_I);
147
148 Factor Fprod( factor(I) );
149 Prob &prod = Fprod.p();
150 if( props.logdomain )
151 prod.takeLog();
152
153 // Calculate product of incoming messages and factor I
154 foreach( const Neighbor &j, nbF(I) )
155 if( j != i ) { // for all j in I \ i
156 // prod_j will be the product of messages coming into j
157 Prob prod_j( var(j).states(), props.logdomain ? 0.0 : 1.0 );
158 foreach( const Neighbor &J, nbV(j) )
159 if( J != I ) { // for all J in nb(j) \ I
160 if( props.logdomain )
161 prod_j += message( j, J.iter );
162 else
163 prod_j *= message( j, J.iter );
164 }
165
166 // multiply prod with prod_j
167 if( !DAI_BP_FAST ) {
168 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
169 if( props.logdomain )
170 Fprod += Factor( var(j), prod_j );
171 else
172 Fprod *= Factor( var(j), prod_j );
173 } else {
174 /* OPTIMIZED VERSION */
175 size_t _I = j.dual;
176 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
177 const ind_t &ind = index(j, _I);
178 for( size_t r = 0; r < prod.size(); ++r )
179 if( props.logdomain )
180 prod[r] += prod_j[ind[r]];
181 else
182 prod[r] *= prod_j[ind[r]];
183 }
184 }
185
186 if( props.logdomain ) {
187 prod -= prod.max();
188 prod.takeExp();
189 }
190
191 // Marginalize onto i
192 Prob marg;
193 if( !DAI_BP_FAST ) {
194 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
195 if( props.inference == Properties::InfType::SUMPROD )
196 marg = Fprod.marginal( var(i) ).p();
197 else
198 marg = Fprod.maxMarginal( var(i) ).p();
199 } else {
200 /* OPTIMIZED VERSION */
201 marg = Prob( var(i).states(), 0.0 );
202 // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
203 const ind_t ind = index(i,_I);
204 if( props.inference == Properties::InfType::SUMPROD )
205 for( size_t r = 0; r < prod.size(); ++r )
206 marg[ind[r]] += prod[r];
207 else
208 for( size_t r = 0; r < prod.size(); ++r )
209 if( prod[r] > marg[ind[r]] )
210 marg[ind[r]] = prod[r];
211 marg.normalize();
212 }
213
214 // Store result
215 if( props.logdomain )
216 newMessage(i,_I) = marg.log();
217 else
218 newMessage(i,_I) = marg;
219
220 // Update the residual if necessary
221 if( props.updates == Properties::UpdateType::SEQMAX )
222 updateResidual( i, _I , dist( newMessage( i, _I ), message( i, _I ), Prob::DISTLINF ) );
223 }
224
225
226 // BP::run does not check for NANs for performance reasons
227 // Somehow NaNs do not often occur in BP...
228 Real BP::run() {
229 if( props.verbose >= 1 )
230 cerr << "Starting " << identify() << "...";
231 if( props.verbose >= 3)
232 cerr << endl;
233
234 double tic = toc();
235 Real maxDiff = INFINITY;
236
237 vector<Factor> oldBeliefsV, oldBeliefsF;
238 oldBeliefsV.reserve( nrVars() );
239 for( size_t i = 0; i < nrVars(); ++i )
240 oldBeliefsV.push_back( beliefV(i) );
241 oldBeliefsF.reserve( nrFactors() );
242 for( size_t I = 0; I < nrFactors(); ++I )
243 oldBeliefsF.push_back( beliefF(I) );
244
245 size_t nredges = nrEdges();
246 vector<Edge> update_seq;
247 if( props.updates == Properties::UpdateType::SEQMAX ) {
248 // do the first pass
249 for( size_t i = 0; i < nrVars(); ++i )
250 foreach( const Neighbor &I, nbV(i) )
251 calcNewMessage( i, I.iter );
252 } else {
253 update_seq.reserve( nredges );
254 for( size_t I = 0; I < nrFactors(); I++ )
255 foreach( const Neighbor &i, nbF(I) )
256 update_seq.push_back( Edge( i, i.dual ) );
257 }
258
259 // do several passes over the network until maximum number of iterations has
260 // been reached or until the maximum belief difference is smaller than tolerance
261 for( _iters=0; _iters < props.maxiter && maxDiff > props.tol; ++_iters ) {
262 if( props.updates == Properties::UpdateType::SEQMAX ) {
263 // Residuals-BP by Koller et al.
264 for( size_t t = 0; t < nredges; ++t ) {
265 // update the message with the largest residual
266 size_t i, _I;
267 findMaxResidual( i, _I );
268 updateMessage( i, _I );
269
270 // I->i has been updated, which means that residuals for all
271 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
272 foreach( const Neighbor &J, nbV(i) ) {
273 if( J.iter != _I ) {
274 foreach( const Neighbor &j, nbF(J) ) {
275 size_t _J = j.dual;
276 if( j != i )
277 calcNewMessage( j, _J );
278 }
279 }
280 }
281 }
282 } else if( props.updates == Properties::UpdateType::PARALL ) {
283 // Parallel updates
284 for( size_t i = 0; i < nrVars(); ++i )
285 foreach( const Neighbor &I, nbV(i) )
286 calcNewMessage( i, I.iter );
287
288 for( size_t i = 0; i < nrVars(); ++i )
289 foreach( const Neighbor &I, nbV(i) )
290 updateMessage( i, I.iter );
291 } else {
292 // Sequential updates
293 if( props.updates == Properties::UpdateType::SEQRND )
294 random_shuffle( update_seq.begin(), update_seq.end() );
295
296 foreach( const Edge &e, update_seq ) {
297 calcNewMessage( e.first, e.second );
298 updateMessage( e.first, e.second );
299 }
300 }
301
302 // calculate new beliefs and compare with old ones
303 maxDiff = -INFINITY;
304 for( size_t i = 0; i < nrVars(); ++i ) {
305 Factor b( beliefV(i) );
306 maxDiff = std::max( maxDiff, dist( b, oldBeliefsV[i], Prob::DISTLINF ) );
307 oldBeliefsV[i] = b;
308 }
309 for( size_t I = 0; I < nrFactors(); ++I ) {
310 Factor b( beliefF(I) );
311 maxDiff = std::max( maxDiff, dist( b, oldBeliefsF[I], Prob::DISTLINF ) );
312 oldBeliefsF[I] = b;
313 }
314
315 if( props.verbose >= 3 )
316 cerr << Name << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
317 }
318
319 if( maxDiff > _maxdiff )
320 _maxdiff = maxDiff;
321
322 if( props.verbose >= 1 ) {
323 if( maxDiff > props.tol ) {
324 if( props.verbose == 1 )
325 cerr << endl;
326 cerr << Name << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
327 } else {
328 if( props.verbose >= 3 )
329 cerr << Name << "::run: ";
330 cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
331 }
332 }
333
334 return maxDiff;
335 }
336
337
338 void BP::calcBeliefV( size_t i, Prob &p ) const {
339 p = Prob( var(i).states(), props.logdomain ? 0.0 : 1.0 );
340 foreach( const Neighbor &I, nbV(i) )
341 if( props.logdomain )
342 p += newMessage( i, I.iter );
343 else
344 p *= newMessage( i, I.iter );
345 }
346
347
348 void BP::calcBeliefF( size_t I, Prob &p ) const {
349 Factor Fprod( factor( I ) );
350 Prob &prod = Fprod.p();
351
352 if( props.logdomain )
353 prod.takeLog();
354
355 foreach( const Neighbor &j, nbF(I) ) {
356 // prod_j will be the product of messages coming into j
357 Prob prod_j( var(j).states(), props.logdomain ? 0.0 : 1.0 );
358 foreach( const Neighbor &J, nbV(j) )
359 if( J != I ) { // for all J in nb(j) \ I
360 if( props.logdomain )
361 prod_j += newMessage( j, J.iter );
362 else
363 prod_j *= newMessage( j, J.iter );
364 }
365
366 // multiply prod with prod_j
367 if( !DAI_BP_FAST ) {
368 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
369 if( props.logdomain )
370 Fprod += Factor( var(j), prod_j );
371 else
372 Fprod *= Factor( var(j), prod_j );
373 } else {
374 /* OPTIMIZED VERSION */
375 size_t _I = j.dual;
376 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
377 const ind_t & ind = index(j, _I);
378
379 for( size_t r = 0; r < prod.size(); ++r ) {
380 if( props.logdomain )
381 prod[r] += prod_j[ind[r]];
382 else
383 prod[r] *= prod_j[ind[r]];
384 }
385 }
386 }
387
388 p = prod;
389 }
390
391
392 Factor BP::beliefV( size_t i ) const {
393 Prob p;
394 calcBeliefV( i, p );
395
396 if( props.logdomain ) {
397 p -= p.max();
398 p.takeExp();
399 }
400 p.normalize();
401
402 return( Factor( var(i), p ) );
403 }
404
405
406 Factor BP::beliefF( size_t I ) const {
407 Prob p;
408 calcBeliefF( I, p );
409
410 if( props.logdomain ) {
411 p -= p.max();
412 p.takeExp();
413 }
414 p.normalize();
415
416 return( Factor( factor(I).vars(), p ) );
417 }
418
419
420 vector<Factor> BP::beliefs() const {
421 vector<Factor> result;
422 for( size_t i = 0; i < nrVars(); ++i )
423 result.push_back( beliefV(i) );
424 for( size_t I = 0; I < nrFactors(); ++I )
425 result.push_back( beliefF(I) );
426 return result;
427 }
428
429
430 Factor BP::belief( const VarSet &ns ) const {
431 if( ns.size() == 0 )
432 return Factor();
433 else if( ns.size() == 1 )
434 return beliefV( findVar( *(ns.begin() ) ) );
435 else {
436 size_t I;
437 for( I = 0; I < nrFactors(); I++ )
438 if( factor(I).vars() >> ns )
439 break;
440 if( I == nrFactors() )
441 DAI_THROW(BELIEF_NOT_AVAILABLE);
442 return beliefF(I).marginal(ns);
443 }
444 }
445
446
447 Real BP::logZ() const {
448 Real sum = 0.0;
449 for( size_t i = 0; i < nrVars(); ++i )
450 sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
451 for( size_t I = 0; I < nrFactors(); ++I )
452 sum -= dist( beliefF(I), factor(I), Prob::DISTKL );
453 return sum;
454 }
455
456
457 string BP::identify() const {
458 return string(Name) + printProperties();
459 }
460
461
462 void BP::init( const VarSet &ns ) {
463 for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
464 size_t ni = findVar( *n );
465 foreach( const Neighbor &I, nbV( ni ) ) {
466 Real val = props.logdomain ? 0.0 : 1.0;
467 message( ni, I.iter ).fill( val );
468 newMessage( ni, I.iter ).fill( val );
469 if( props.updates == Properties::UpdateType::SEQMAX )
470 updateResidual( ni, I.iter, 0.0 );
471 }
472 }
473 }
474
475
476 void BP::updateMessage( size_t i, size_t _I ) {
477 if( recordSentMessages )
478 _sentMessages.push_back(make_pair(i,_I));
479 if( props.damping == 0.0 ) {
480 message(i,_I) = newMessage(i,_I);
481 if( props.updates == Properties::UpdateType::SEQMAX )
482 updateResidual( i, _I, 0.0 );
483 } else {
484 if( props.logdomain )
485 message(i,_I) = (message(i,_I) * props.damping) + (newMessage(i,_I) * (1.0 - props.damping));
486 else
487 message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
488 if( props.updates == Properties::UpdateType::SEQMAX )
489 updateResidual( i, _I, dist( newMessage(i,_I), message(i,_I), Prob::DISTLINF ) );
490 }
491 }
492
493
494 void BP::updateResidual( size_t i, size_t _I, Real r ) {
495 EdgeProp* pEdge = &_edges[i][_I];
496 pEdge->residual = r;
497
498 // rearrange look-up table (delete and reinsert new key)
499 _lut.erase( _edge2lut[i][_I] );
500 _edge2lut[i][_I] = _lut.insert( make_pair( r, make_pair(i, _I) ) );
501 }
502
503
504 std::vector<size_t> BP::findMaximum() const {
505 vector<size_t> maximum( nrVars() );
506 vector<bool> visitedVars( nrVars(), false );
507 vector<bool> visitedFactors( nrFactors(), false );
508 stack<size_t> scheduledFactors;
509 for( size_t i = 0; i < nrVars(); ++i ) {
510 if( visitedVars[i] )
511 continue;
512 visitedVars[i] = true;
513
514 // Maximise with respect to variable i
515 Prob prod;
516 calcBeliefV( i, prod );
517 maximum[i] = prod.argmax().first;
518
519 foreach( const Neighbor &I, nbV(i) )
520 if( !visitedFactors[I] )
521 scheduledFactors.push(I);
522
523 while( !scheduledFactors.empty() ){
524 size_t I = scheduledFactors.top();
525 scheduledFactors.pop();
526 if( visitedFactors[I] )
527 continue;
528 visitedFactors[I] = true;
529
530 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
531 bool allDetermined = true;
532 foreach( const Neighbor &j, nbF(I) )
533 if( !visitedVars[j.node] ) {
534 allDetermined = false;
535 break;
536 }
537 if( allDetermined )
538 continue;
539
540 // Calculate product of incoming messages on factor I
541 Prob prod2;
542 calcBeliefF( I, prod2 );
543
544 // The allowed configuration is restrained according to the variables assigned so far:
545 // pick the argmax amongst the allowed states
546 Real maxProb = numeric_limits<Real>::min();
547 State maxState( factor(I).vars() );
548 for( State s( factor(I).vars() ); s.valid(); ++s ){
549 // First, calculate whether this state is consistent with variables that
550 // have been assigned already
551 bool allowedState = true;
552 foreach( const Neighbor &j, nbF(I) )
553 if( visitedVars[j.node] && maximum[j.node] != s(var(j.node)) ) {
554 allowedState = false;
555 break;
556 }
557 // If it is consistent, check if its probability is larger than what we have seen so far
558 if( allowedState && prod2[s] > maxProb ) {
559 maxState = s;
560 maxProb = prod2[s];
561 }
562 }
563
564 // Decode the argmax
565 foreach( const Neighbor &j, nbF(I) ) {
566 if( visitedVars[j.node] ) {
567 // We have already visited j earlier - hopefully our state is consistent
568 if( maximum[j.node] != maxState(var(j.node)) && props.verbose >= 1 )
569 cerr << "BP::findMaximum - warning: maximum not consistent due to loops." << endl;
570 } else {
571 // We found a consistent state for variable j
572 visitedVars[j.node] = true;
573 maximum[j.node] = maxState( var(j.node) );
574 foreach( const Neighbor &J, nbV(j) )
575 if( !visitedFactors[J] )
576 scheduledFactors.push(J);
577 }
578 }
579 }
580 }
581 return maximum;
582 }
583
584
585 } // end of namespace dai