Fixed regression in scripts/regenerate-properties
[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 vector<Real> diffs( nrVars(), INFINITY );
236 Real maxDiff = INFINITY;
237
238 vector<Factor> old_beliefs;
239 old_beliefs.reserve( nrVars() );
240 for( size_t i = 0; i < nrVars(); ++i )
241 old_beliefs.push_back( beliefV(i) );
242
243 size_t nredges = nrEdges();
244 vector<Edge> update_seq;
245 if( props.updates == Properties::UpdateType::SEQMAX ) {
246 // do the first pass
247 for( size_t i = 0; i < nrVars(); ++i )
248 foreach( const Neighbor &I, nbV(i) )
249 calcNewMessage( i, I.iter );
250 } else {
251 update_seq.reserve( nredges );
252 /// \todo Investigate whether performance increases by switching the order of the following two loops:
253 for( size_t i = 0; i < nrVars(); ++i )
254 foreach( const Neighbor &I, nbV(i) )
255 update_seq.push_back( Edge( i, I.iter ) );
256 }
257
258 // do several passes over the network until maximum number of iterations has
259 // been reached or until the maximum belief difference is smaller than tolerance
260 for( _iters=0; _iters < props.maxiter && maxDiff > props.tol; ++_iters ) {
261 if( props.updates == Properties::UpdateType::SEQMAX ) {
262 // Residuals-BP by Koller et al.
263 for( size_t t = 0; t < nredges; ++t ) {
264 // update the message with the largest residual
265 size_t i, _I;
266 findMaxResidual( i, _I );
267 updateMessage( i, _I );
268
269 // I->i has been updated, which means that residuals for all
270 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
271 foreach( const Neighbor &J, nbV(i) ) {
272 if( J.iter != _I ) {
273 foreach( const Neighbor &j, nbF(J) ) {
274 size_t _J = j.dual;
275 if( j != i )
276 calcNewMessage( j, _J );
277 }
278 }
279 }
280 }
281 } else if( props.updates == Properties::UpdateType::PARALL ) {
282 // Parallel updates
283 for( size_t i = 0; i < nrVars(); ++i )
284 foreach( const Neighbor &I, nbV(i) )
285 calcNewMessage( i, I.iter );
286
287 for( size_t i = 0; i < nrVars(); ++i )
288 foreach( const Neighbor &I, nbV(i) )
289 updateMessage( i, I.iter );
290 } else {
291 // Sequential updates
292 if( props.updates == Properties::UpdateType::SEQRND )
293 random_shuffle( update_seq.begin(), update_seq.end() );
294
295 foreach( const Edge &e, update_seq ) {
296 calcNewMessage( e.first, e.second );
297 updateMessage( e.first, e.second );
298 }
299 }
300
301 // calculate new beliefs and compare with old ones
302 for( size_t i = 0; i < nrVars(); ++i ) {
303 Factor nb( beliefV(i) );
304 diffs[i] = dist( nb, old_beliefs[i], Prob::DISTLINF );
305 old_beliefs[i] = nb;
306 }
307 maxDiff = max( diffs );
308
309 if( props.verbose >= 3 )
310 cerr << Name << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
311 }
312
313 if( maxDiff > _maxdiff )
314 _maxdiff = maxDiff;
315
316 if( props.verbose >= 1 ) {
317 if( maxDiff > props.tol ) {
318 if( props.verbose == 1 )
319 cerr << endl;
320 cerr << Name << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
321 } else {
322 if( props.verbose >= 3 )
323 cerr << Name << "::run: ";
324 cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
325 }
326 }
327
328 return maxDiff;
329 }
330
331
332 void BP::calcBeliefV( size_t i, Prob &p ) const {
333 p = Prob( var(i).states(), props.logdomain ? 0.0 : 1.0 );
334 foreach( const Neighbor &I, nbV(i) )
335 if( props.logdomain )
336 p += newMessage( i, I.iter );
337 else
338 p *= newMessage( i, I.iter );
339 }
340
341
342 void BP::calcBeliefF( size_t I, Prob &p ) const {
343 Factor Fprod( factor( I ) );
344 Prob &prod = Fprod.p();
345
346 if( props.logdomain )
347 prod.takeLog();
348
349 foreach( const Neighbor &j, nbF(I) ) {
350 // prod_j will be the product of messages coming into j
351 Prob prod_j( var(j).states(), props.logdomain ? 0.0 : 1.0 );
352 foreach( const Neighbor &J, nbV(j) )
353 if( J != I ) { // for all J in nb(j) \ I
354 if( props.logdomain )
355 prod_j += newMessage( j, J.iter );
356 else
357 prod_j *= newMessage( j, J.iter );
358 }
359
360 // multiply prod with prod_j
361 if( !DAI_BP_FAST ) {
362 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
363 if( props.logdomain )
364 Fprod += Factor( var(j), prod_j );
365 else
366 Fprod *= Factor( var(j), prod_j );
367 } else {
368 /* OPTIMIZED VERSION */
369 size_t _I = j.dual;
370 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
371 const ind_t & ind = index(j, _I);
372
373 for( size_t r = 0; r < prod.size(); ++r ) {
374 if( props.logdomain )
375 prod[r] += prod_j[ind[r]];
376 else
377 prod[r] *= prod_j[ind[r]];
378 }
379 }
380 }
381
382 p = prod;
383 }
384
385
386 Factor BP::beliefV( size_t i ) const {
387 Prob p;
388 calcBeliefV( i, p );
389
390 if( props.logdomain ) {
391 p -= p.max();
392 p.takeExp();
393 }
394 p.normalize();
395
396 return( Factor( var(i), p ) );
397 }
398
399
400 Factor BP::beliefF( size_t I ) const {
401 Prob p;
402 calcBeliefF( I, p );
403
404 if( props.logdomain ) {
405 p -= p.max();
406 p.takeExp();
407 }
408 p.normalize();
409
410 return( Factor( factor(I).vars(), p ) );
411 }
412
413
414 Factor BP::belief( const Var &n ) const {
415 return( beliefV( findVar( n ) ) );
416 }
417
418
419 vector<Factor> BP::beliefs() const {
420 vector<Factor> result;
421 for( size_t i = 0; i < nrVars(); ++i )
422 result.push_back( beliefV(i) );
423 for( size_t I = 0; I < nrFactors(); ++I )
424 result.push_back( beliefF(I) );
425 return result;
426 }
427
428
429 Factor BP::belief( const VarSet &ns ) const {
430 if( ns.size() == 1 )
431 return belief( *(ns.begin()) );
432 else {
433 size_t I;
434 for( I = 0; I < nrFactors(); I++ )
435 if( factor(I).vars() >> ns )
436 break;
437 DAI_ASSERT( I != nrFactors() );
438 return beliefF(I).marginal(ns);
439 }
440 }
441
442
443 Real BP::logZ() const {
444 Real sum = 0.0;
445 for(size_t i = 0; i < nrVars(); ++i )
446 sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
447 for( size_t I = 0; I < nrFactors(); ++I )
448 sum -= dist( beliefF(I), factor(I), Prob::DISTKL );
449 return sum;
450 }
451
452
453 string BP::identify() const {
454 return string(Name) + printProperties();
455 }
456
457
458 void BP::init( const VarSet &ns ) {
459 for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
460 size_t ni = findVar( *n );
461 foreach( const Neighbor &I, nbV( ni ) ) {
462 Real val = props.logdomain ? 0.0 : 1.0;
463 message( ni, I.iter ).fill( val );
464 newMessage( ni, I.iter ).fill( val );
465 if( props.updates == Properties::UpdateType::SEQMAX )
466 updateResidual( ni, I.iter, 0.0 );
467 }
468 }
469 }
470
471
472 void BP::updateMessage( size_t i, size_t _I ) {
473 if( recordSentMessages )
474 _sentMessages.push_back(make_pair(i,_I));
475 if( props.damping == 0.0 ) {
476 message(i,_I) = newMessage(i,_I);
477 if( props.updates == Properties::UpdateType::SEQMAX )
478 updateResidual( i, _I, 0.0 );
479 } else {
480 message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
481 if( props.updates == Properties::UpdateType::SEQMAX )
482 updateResidual( i, _I, dist( newMessage(i,_I), message(i,_I), Prob::DISTLINF ) );
483 }
484 }
485
486
487 void BP::updateResidual( size_t i, size_t _I, Real r ) {
488 EdgeProp* pEdge = &_edges[i][_I];
489 pEdge->residual = r;
490
491 // rearrange look-up table (delete and reinsert new key)
492 _lut.erase( _edge2lut[i][_I] );
493 _edge2lut[i][_I] = _lut.insert( make_pair( r, make_pair(i, _I) ) );
494 }
495
496
497 std::vector<size_t> BP::findMaximum() const {
498 vector<size_t> maximum( nrVars() );
499 vector<bool> visitedVars( nrVars(), false );
500 vector<bool> visitedFactors( nrFactors(), false );
501 stack<size_t> scheduledFactors;
502 for( size_t i = 0; i < nrVars(); ++i ) {
503 if( visitedVars[i] )
504 continue;
505 visitedVars[i] = true;
506
507 // Maximise with respect to variable i
508 Prob prod;
509 calcBeliefV( i, prod );
510 maximum[i] = prod.argmax().first;
511
512 foreach( const Neighbor &I, nbV(i) )
513 if( !visitedFactors[I] )
514 scheduledFactors.push(I);
515
516 while( !scheduledFactors.empty() ){
517 size_t I = scheduledFactors.top();
518 scheduledFactors.pop();
519 if( visitedFactors[I] )
520 continue;
521 visitedFactors[I] = true;
522
523 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
524 bool allDetermined = true;
525 foreach( const Neighbor &j, nbF(I) )
526 if( !visitedVars[j.node] ) {
527 allDetermined = false;
528 break;
529 }
530 if( allDetermined )
531 continue;
532
533 // Calculate product of incoming messages on factor I
534 Prob prod2;
535 calcBeliefF( I, prod2 );
536
537 // The allowed configuration is restrained according to the variables assigned so far:
538 // pick the argmax amongst the allowed states
539 Real maxProb = numeric_limits<Real>::min();
540 State maxState( factor(I).vars() );
541 for( State s( factor(I).vars() ); s.valid(); ++s ){
542 // First, calculate whether this state is consistent with variables that
543 // have been assigned already
544 bool allowedState = true;
545 foreach( const Neighbor &j, nbF(I) )
546 if( visitedVars[j.node] && maximum[j.node] != s(var(j.node)) ) {
547 allowedState = false;
548 break;
549 }
550 // If it is consistent, check if its probability is larger than what we have seen so far
551 if( allowedState && prod2[s] > maxProb ) {
552 maxState = s;
553 maxProb = prod2[s];
554 }
555 }
556
557 // Decode the argmax
558 foreach( const Neighbor &j, nbF(I) ) {
559 if( visitedVars[j.node] ) {
560 // We have already visited j earlier - hopefully our state is consistent
561 if( maximum[j.node] != maxState(var(j.node)) && props.verbose >= 1 )
562 cerr << "BP::findMaximum - warning: maximum not consistent due to loops." << endl;
563 } else {
564 // We found a consistent state for variable j
565 visitedVars[j.node] = true;
566 maximum[j.node] = maxState( var(j.node) );
567 foreach( const Neighbor &J, nbV(j) )
568 if( !visitedFactors[J] )
569 scheduledFactors.push(J);
570 }
571 }
572 }
573 }
574 return maximum;
575 }
576
577
578 } // end of namespace dai