07c54bc0c370987304633b3c8454db06af97bb39
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
6 This file is part of libDAI.
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.
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.
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
32 #include <dai/properties.h>
41 const char *BP::Name
= "BP";
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") );
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");
58 if( opts
.hasKey("verbose") )
59 props
.verbose
= opts
.getStringAs
<size_t>("verbose");
62 if( opts
.hasKey("damping") )
63 props
.damping
= opts
.getStringAs
<double>("damping");
66 if( opts
.hasKey("inference") )
67 props
.inference
= opts
.getStringAs
<Properties::InfType
>("inference");
69 props
.inference
= Properties::InfType::SUMPROD
;
73 PropertySet
BP::getProperties() const {
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
);
86 string
BP::printProperties() const {
87 stringstream
s( stringstream::out
);
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
<< "]";
100 void BP::construct() {
101 // create edge properties
103 _edges
.reserve( nrVars() );
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() );
114 foreach( const Neighbor
&I
, nbV(i
) ) {
116 newEP
.message
= Prob( var(i
).states() );
117 newEP
.newMessage
= Prob( var(i
).states() );
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
);
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( make_pair( newEP
.residual
, make_pair( i
, _edges
[i
].size() - 1 ))) );
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 );
147 void BP::findMaxResidual( size_t &i
, size_t &_I
) {
148 assert( !_lut
.empty() );
149 LutType::const_iterator largestEl
= _lut
.end();
151 i
= largestEl
->second
.first
;
152 _I
= largestEl
->second
.second
;
156 void BP::calcNewMessage( size_t i
, size_t _I
) {
157 // calculate updated message I->i
158 size_t I
= nbV(i
,_I
);
160 Factor
Fprod( factor(I
) );
161 Prob
&prod
= Fprod
.p();
162 if( props
.logdomain
)
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
);
175 prod_j
*= message( j
, J
.iter
);
178 // multiply prod with prod_j
180 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
181 if( props
.logdomain
)
182 Fprod
+= Factor( var(j
), prod_j
);
184 Fprod
*= Factor( var(j
), prod_j
);
186 /* OPTIMIZED VERSION */
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
]];
194 prod
[r
] *= prod_j
[ind
[r
]];
198 if( props
.logdomain
) {
203 // Marginalize onto i
206 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
207 if( props
.inference
== Properties::InfType::SUMPROD
)
208 marg
= Fprod
.marginal( var(i
) ).p();
210 marg
= Fprod
.maxMarginal( var(i
) ).p();
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
];
220 for( size_t r
= 0; r
< prod
.size(); ++r
)
221 if( prod
[r
] > marg
[ind
[r
]] )
222 marg
[ind
[r
]] = prod
[r
];
227 if( props
.logdomain
)
228 newMessage(i
,_I
) = marg
.log();
230 newMessage(i
,_I
) = marg
;
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
) );
238 // BP::run does not check for NANs for performance reasons
239 // Somehow NaNs do not often occur in BP...
241 if( props
.verbose
>= 1 )
242 cerr
<< "Starting " << identify() << "...";
243 if( props
.verbose
>= 3)
247 Diffs
diffs(nrVars(), 1.0);
249 vector
<Edge
> update_seq
;
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
) );
256 size_t nredges
= nrEdges();
258 if( props
.updates
== Properties::UpdateType::SEQMAX
) {
260 for( size_t i
= 0; i
< nrVars(); ++i
)
261 foreach( const Neighbor
&I
, nbV(i
) ) {
262 calcNewMessage( i
, I
.iter
);
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
) );
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
280 findMaxResidual( i
, _I
);
281 updateMessage( i
, _I
);
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
) ) {
287 foreach( const Neighbor
&j
, nbF(J
) ) {
290 calcNewMessage( j
, _J
);
295 } else if( props
.updates
== Properties::UpdateType::PARALL
) {
297 for( size_t i
= 0; i
< nrVars(); ++i
)
298 foreach( const Neighbor
&I
, nbV(i
) )
299 calcNewMessage( i
, I
.iter
);
301 for( size_t i
= 0; i
< nrVars(); ++i
)
302 foreach( const Neighbor
&I
, nbV(i
) )
303 updateMessage( i
, I
.iter
);
305 // Sequential updates
306 if( props
.updates
== Properties::UpdateType::SEQRND
)
307 random_shuffle( update_seq
.begin(), update_seq
.end() );
309 foreach( const Edge
&e
, update_seq
) {
310 calcNewMessage( e
.first
, e
.second
);
311 updateMessage( e
.first
, e
.second
);
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
) );
322 if( props
.verbose
>= 3 )
323 cerr
<< Name
<< "::run: maxdiff " << diffs
.maxDiff() << " after " << _iters
+1 << " passes" << endl
;
326 if( diffs
.maxDiff() > _maxdiff
)
327 _maxdiff
= diffs
.maxDiff();
329 if( props
.verbose
>= 1 ) {
330 if( diffs
.maxDiff() > props
.tol
) {
331 if( props
.verbose
== 1 )
333 cerr
<< Name
<< "::run: WARNING: not converged within " << props
.maxiter
<< " passes (" << toc() - tic
<< " seconds)...final maxdiff:" << diffs
.maxDiff() << endl
;
335 if( props
.verbose
>= 3 )
336 cerr
<< Name
<< "::run: ";
337 cerr
<< "converged in " << _iters
<< " passes (" << toc() - tic
<< " seconds)." << endl
;
341 return diffs
.maxDiff();
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
);
351 p
*= newMessage( i
, I
.iter
);
355 void BP::calcBeliefF( size_t I
, Prob
&p
) const {
356 Factor
Fprod( factor( I
) );
357 Prob
&prod
= Fprod
.p();
359 if( props
.logdomain
)
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
);
370 prod_j
*= newMessage( j
, J
.iter
);
373 // multiply prod with prod_j
375 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
376 if( props
.logdomain
)
377 Fprod
+= Factor( var(j
), prod_j
);
379 Fprod
*= Factor( var(j
), prod_j
);
381 /* OPTIMIZED VERSION */
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
);
386 for( size_t r
= 0; r
< prod
.size(); ++r
) {
387 if( props
.logdomain
)
388 prod
[r
] += prod_j
[ind
[r
]];
390 prod
[r
] *= prod_j
[ind
[r
]];
399 Factor
BP::beliefV( size_t i
) const {
403 if( props
.logdomain
) {
409 return( Factor( var(i
), p
) );
413 Factor
BP::beliefF( size_t I
) const {
417 if( props
.logdomain
) {
423 return( Factor( factor(I
).vars(), p
) );
427 Factor
BP::belief( const Var
&n
) const {
428 return( beliefV( findVar( n
) ) );
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
) );
442 Factor
BP::belief( const VarSet
&ns
) const {
444 return belief( *(ns
.begin()) );
447 for( I
= 0; I
< nrFactors(); I
++ )
448 if( factor(I
).vars() >> ns
)
450 assert( I
!= nrFactors() );
451 return beliefF(I
).marginal(ns
);
456 Real
BP::logZ() const {
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
);
466 string
BP::identify() const {
467 return string(Name
) + printProperties();
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 );
485 void BP::updateMessage( size_t i
, size_t _I
) {
486 if( recordSentMessages
)
487 _sentMessages
.push_back(make_pair(i
,_I
));
488 if( props
.damping
== 0.0 ) {
489 message(i
,_I
) = newMessage(i
,_I
);
490 if( props
.updates
== Properties::UpdateType::SEQMAX
)
491 updateResidual( i
, _I
, 0.0 );
493 message(i
,_I
) = (message(i
,_I
) ^ props
.damping
) * (newMessage(i
,_I
) ^ (1.0 - props
.damping
));
494 if( props
.updates
== Properties::UpdateType::SEQMAX
)
495 updateResidual( i
, _I
, dist( newMessage(i
,_I
), message(i
,_I
), Prob::DISTLINF
) );
500 void BP::updateResidual( size_t i
, size_t _I
, double r
) {
501 EdgeProp
* pEdge
= &_edges
[i
][_I
];
504 // rearrange look-up table (delete and reinsert new key)
505 _lut
.erase( _edge2lut
[i
][_I
] );
506 _edge2lut
[i
][_I
] = _lut
.insert( make_pair( r
, make_pair(i
, _I
) ) );
510 std::vector
<size_t> BP::findMaximum() const {
511 vector
<size_t> maximum( nrVars() );
512 vector
<bool> visitedVars( nrVars(), false );
513 vector
<bool> visitedFactors( nrFactors(), false );
514 stack
<size_t> scheduledFactors
;
515 for( size_t i
= 0; i
< nrVars(); ++i
) {
518 visitedVars
[i
] = true;
520 // Maximise with respect to variable i
522 calcBeliefV( i
, prod
);
523 maximum
[i
] = max_element( prod
.begin(), prod
.end() ) - prod
.begin();
525 foreach( const Neighbor
&I
, nbV(i
) )
526 if( !visitedFactors
[I
] )
527 scheduledFactors
.push(I
);
529 while( !scheduledFactors
.empty() ){
530 size_t I
= scheduledFactors
.top();
531 scheduledFactors
.pop();
532 if( visitedFactors
[I
] )
534 visitedFactors
[I
] = true;
536 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
537 bool allDetermined
= true;
538 foreach( const Neighbor
&j
, nbF(I
) )
539 if( !visitedVars
[j
.node
] ) {
540 allDetermined
= false;
546 // Calculate product of incoming messages on factor I
548 calcBeliefF( I
, prod2
);
550 // The allowed configuration is restrained according to the variables assigned so far:
551 // pick the argmax amongst the allowed states
552 Real maxProb
= numeric_limits
<Real
>::min();
553 State
maxState( factor(I
).vars() );
554 for( State
s( factor(I
).vars() ); s
.valid(); ++s
){
555 // First, calculate whether this state is consistent with variables that
556 // have been assigned already
557 bool allowedState
= true;
558 foreach( const Neighbor
&j
, nbF(I
) )
559 if( visitedVars
[j
.node
] && maximum
[j
.node
] != s(var(j
.node
)) ) {
560 allowedState
= false;
563 // If it is consistent, check if its probability is larger than what we have seen so far
564 if( allowedState
&& prod2
[s
] > maxProb
) {
571 foreach( const Neighbor
&j
, nbF(I
) ) {
572 if( visitedVars
[j
.node
] ) {
573 // We have already visited j earlier - hopefully our state is consistent
574 if( maximum
[j
.node
] != maxState(var(j
.node
)) && props
.verbose
>= 1 )
575 cerr
<< "BP::findMaximum - warning: maximum not consistent due to loops." << endl
;
577 // We found a consistent state for variable j
578 visitedVars
[j
.node
] = true;
579 maximum
[j
.node
] = maxState( var(j
.node
) );
580 foreach( const Neighbor
&J
, nbV(j
) )
581 if( !visitedFactors
[J
] )
582 scheduledFactors
.push(J
);
591 } // end of namespace dai