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