1 /* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
2 Radboud University Nijmegen, The Netherlands
4 This file is part of libDAI.
6 libDAI is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 libDAI is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with libDAI; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <dai/diffs.h>
30 #include <dai/properties.h>
39 const char *BP::Name
= "BP";
42 void BP::setProperties( const PropertySet
&opts
) {
43 assert( opts
.hasKey("tol") );
44 assert( opts
.hasKey("maxiter") );
45 assert( opts
.hasKey("logdomain") );
46 assert( opts
.hasKey("updates") );
48 props
.tol
= opts
.getStringAs
<double>("tol");
49 props
.maxiter
= opts
.getStringAs
<size_t>("maxiter");
50 props
.logdomain
= opts
.getStringAs
<bool>("logdomain");
51 props
.updates
= opts
.getStringAs
<Properties::UpdateType
>("updates");
53 if( opts
.hasKey("verbose") )
54 props
.verbose
= opts
.getStringAs
<size_t>("verbose");
57 if( opts
.hasKey("damping") )
58 props
.damping
= opts
.getStringAs
<double>("damping");
64 PropertySet
BP::getProperties() const {
66 opts
.Set( "tol", props
.tol
);
67 opts
.Set( "maxiter", props
.maxiter
);
68 opts
.Set( "verbose", props
.verbose
);
69 opts
.Set( "logdomain", props
.logdomain
);
70 opts
.Set( "updates", props
.updates
);
71 opts
.Set( "damping", props
.damping
);
76 string
BP::printProperties() const {
77 stringstream
s( stringstream::out
);
79 s
<< "tol=" << props
.tol
<< ",";
80 s
<< "maxiter=" << props
.maxiter
<< ",";
81 s
<< "verbose=" << props
.verbose
<< ",";
82 s
<< "logdomain=" << props
.logdomain
<< ",";
83 s
<< "updates=" << props
.updates
<< ",";
84 s
<< "damping=" << props
.damping
<< "]";
89 void BP::construct() {
90 // create edge properties
92 _edges
.reserve( nrVars() );
93 for( size_t i
= 0; i
< nrVars(); ++i
) {
94 _edges
.push_back( vector
<EdgeProp
>() );
95 _edges
[i
].reserve( nbV(i
).size() );
96 foreach( const Neighbor
&I
, nbV(i
) ) {
98 newEP
.message
= Prob( var(i
).states() );
99 newEP
.newMessage
= Prob( var(i
).states() );
101 newEP
.index
.reserve( factor(I
).states() );
102 for( IndexFor
k( var(i
), factor(I
).vars() ); k
>= 0; ++k
)
103 newEP
.index
.push_back( k
);
105 newEP
.residual
= 0.0;
106 _edges
[i
].push_back( newEP
);
113 double c
= props
.logdomain
? 0.0 : 1.0;
114 for( size_t i
= 0; i
< nrVars(); ++i
) {
115 foreach( const Neighbor
&I
, nbV(i
) ) {
116 message( i
, I
.iter
).fill( c
);
117 newMessage( i
, I
.iter
).fill( c
);
123 void BP::findMaxResidual( size_t &i
, size_t &_I
) {
126 double maxres
= residual( i
, _I
);
127 for( size_t j
= 0; j
< nrVars(); ++j
)
128 foreach( const Neighbor
&I
, nbV(j
) )
129 if( residual( j
, I
.iter
) > maxres
) {
132 maxres
= residual( i
, _I
);
137 void BP::calcNewMessage( size_t i
, size_t _I
) {
138 // calculate updated message I->i
139 size_t I
= nbV(i
,_I
);
142 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
143 Factor
prod( factor( I
) );
144 foreach( const Neighbor
&j
, nbF(I
) )
145 if( j
!= i
) { // for all j in I \ i
146 foreach( const Neighbor
&J
, nbV(j
) )
147 if( J
!= I
) { // for all J in nb(j) \ I
148 prod
*= Factor( var(j
), message(j
, J
.iter
) );
151 newMessage(i
,_I
) = prod
.marginal( var(i
) ).p();
153 /* OPTIMIZED VERSION */
154 Prob
prod( factor(I
).p() );
155 if( props
.logdomain
)
158 // Calculate product of incoming messages and factor I
159 foreach( const Neighbor
&j
, nbF(I
) ) {
160 if( j
!= i
) { // for all j in I \ i
162 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
163 const ind_t
&ind
= index(j
, _I
);
165 // prod_j will be the product of messages coming into j
166 Prob
prod_j( var(j
).states(), props
.logdomain
? 0.0 : 1.0 );
167 foreach( const Neighbor
&J
, nbV(j
) )
168 if( J
!= I
) { // for all J in nb(j) \ I
169 if( props
.logdomain
)
170 prod_j
+= message( j
, J
.iter
);
172 prod_j
*= message( j
, J
.iter
);
175 // multiply prod with prod_j
176 for( size_t r
= 0; r
< prod
.size(); ++r
)
177 if( props
.logdomain
)
178 prod
[r
] += prod_j
[ind
[r
]];
180 prod
[r
] *= prod_j
[ind
[r
]];
183 if( props
.logdomain
) {
184 prod
-= prod
.maxVal();
188 // Marginalize onto i
189 Prob
marg( var(i
).states(), 0.0 );
190 // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
191 const ind_t ind
= index(i
,_I
);
192 for( size_t r
= 0; r
< prod
.size(); ++r
)
193 marg
[ind
[r
]] += prod
[r
];
197 if( props
.logdomain
)
198 newMessage(i
,_I
) = marg
.log();
200 newMessage(i
,_I
) = marg
;
205 // BP::run does not check for NANs for performance reasons
206 // Somehow NaNs do not often occur in BP...
208 if( props
.verbose
>= 1 )
209 cout
<< "Starting " << identify() << "...";
210 if( props
.verbose
>= 3)
214 Diffs
diffs(nrVars(), 1.0);
216 vector
<Edge
> update_seq
;
218 vector
<Factor
> old_beliefs
;
219 old_beliefs
.reserve( nrVars() );
220 for( size_t i
= 0; i
< nrVars(); ++i
)
221 old_beliefs
.push_back( beliefV(i
) );
223 size_t nredges
= nrEdges();
225 if( props
.updates
== Properties::UpdateType::SEQMAX
) {
227 for( size_t i
= 0; i
< nrVars(); ++i
)
228 foreach( const Neighbor
&I
, nbV(i
) ) {
229 calcNewMessage( i
, I
.iter
);
230 // calculate initial residuals
231 residual( i
, I
.iter
) = dist( newMessage( i
, I
.iter
), message( i
, I
.iter
), Prob::DISTLINF
);
234 update_seq
.reserve( nredges
);
235 for( size_t i
= 0; i
< nrVars(); ++i
)
236 foreach( const Neighbor
&I
, nbV(i
) )
237 update_seq
.push_back( Edge( i
, I
.iter
) );
240 // do several passes over the network until maximum number of iterations has
241 // been reached or until the maximum belief difference is smaller than tolerance
242 for( _iters
=0; _iters
< props
.maxiter
&& diffs
.maxDiff() > props
.tol
; ++_iters
) {
243 if( props
.updates
== Properties::UpdateType::SEQMAX
) {
244 // Residuals-BP by Koller et al.
245 for( size_t t
= 0; t
< nredges
; ++t
) {
246 // update the message with the largest residual
248 findMaxResidual( i
, _I
);
249 updateMessage( i
, _I
);
251 // I->i has been updated, which means that residuals for all
252 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
253 foreach( const Neighbor
&J
, nbV(i
) ) {
255 foreach( const Neighbor
&j
, nbF(J
) ) {
258 calcNewMessage( j
, _J
);
259 residual( j
, _J
) = dist( newMessage( j
, _J
), message( j
, _J
), Prob::DISTLINF
);
265 } else if( props
.updates
== Properties::UpdateType::PARALL
) {
267 for( size_t i
= 0; i
< nrVars(); ++i
)
268 foreach( const Neighbor
&I
, nbV(i
) )
269 calcNewMessage( i
, I
.iter
);
271 for( size_t i
= 0; i
< nrVars(); ++i
)
272 foreach( const Neighbor
&I
, nbV(i
) )
273 updateMessage( i
, I
.iter
);
275 // Sequential updates
276 if( props
.updates
== Properties::UpdateType::SEQRND
)
277 random_shuffle( update_seq
.begin(), update_seq
.end() );
279 foreach( const Edge
&e
, update_seq
) {
280 calcNewMessage( e
.first
, e
.second
);
281 updateMessage( e
.first
, e
.second
);
285 // calculate new beliefs and compare with old ones
286 for( size_t i
= 0; i
< nrVars(); ++i
) {
287 Factor
nb( beliefV(i
) );
288 diffs
.push( dist( nb
, old_beliefs
[i
], Prob::DISTLINF
) );
292 if( props
.verbose
>= 3 )
293 cout
<< Name
<< "::run: maxdiff " << diffs
.maxDiff() << " after " << _iters
+1 << " passes" << endl
;
296 if( diffs
.maxDiff() > _maxdiff
)
297 _maxdiff
= diffs
.maxDiff();
299 if( props
.verbose
>= 1 ) {
300 if( diffs
.maxDiff() > props
.tol
) {
301 if( props
.verbose
== 1 )
303 cout
<< Name
<< "::run: WARNING: not converged within " << props
.maxiter
<< " passes (" << toc() - tic
<< " seconds)...final maxdiff:" << diffs
.maxDiff() << endl
;
305 if( props
.verbose
>= 3 )
306 cout
<< Name
<< "::run: ";
307 cout
<< "converged in " << _iters
<< " passes (" << toc() - tic
<< " seconds)." << endl
;
311 return diffs
.maxDiff();
315 Factor
BP::beliefV( size_t i
) const {
316 Prob
prod( var(i
).states(), props
.logdomain
? 0.0 : 1.0 );
317 foreach( const Neighbor
&I
, nbV(i
) )
318 if( props
.logdomain
)
319 prod
+= newMessage( i
, I
.iter
);
321 prod
*= newMessage( i
, I
.iter
);
322 if( props
.logdomain
) {
323 prod
-= prod
.maxVal();
328 return( Factor( var(i
), prod
) );
332 Factor
BP::belief (const Var
&n
) const {
333 return( beliefV( findVar( n
) ) );
337 vector
<Factor
> BP::beliefs() const {
338 vector
<Factor
> result
;
339 for( size_t i
= 0; i
< nrVars(); ++i
)
340 result
.push_back( beliefV(i
) );
341 for( size_t I
= 0; I
< nrFactors(); ++I
)
342 result
.push_back( beliefF(I
) );
347 Factor
BP::belief( const VarSet
&ns
) const {
349 return belief( *(ns
.begin()) );
352 for( I
= 0; I
< nrFactors(); I
++ )
353 if( factor(I
).vars() >> ns
)
355 assert( I
!= nrFactors() );
356 return beliefF(I
).marginal(ns
);
361 Factor
BP::beliefF (size_t I
) const {
363 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
365 Factor
prod( factor(I
) );
366 foreach( const Neighbor
&j
, nbF(I
) ) {
367 foreach( const Neighbor
&J
, nbV(j
) ) {
368 if( J
!= I
) // for all J in nb(j) \ I
369 prod
*= Factor( var(j
), newMessage(j
, J
.iter
) );
372 return prod
.normalized();
374 /* OPTIMIZED VERSION */
375 Prob
prod( factor(I
).p() );
376 if( props
.logdomain
)
379 foreach( const Neighbor
&j
, nbF(I
) ) {
381 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
382 const ind_t
& ind
= index(j
, _I
);
384 // prod_j will be the product of messages coming into j
385 Prob
prod_j( var(j
).states(), props
.logdomain
? 0.0 : 1.0 );
386 foreach( const Neighbor
&J
, nbV(j
) ) {
387 if( J
!= I
) { // for all J in nb(j) \ I
388 if( props
.logdomain
)
389 prod_j
+= newMessage( j
, J
.iter
);
391 prod_j
*= newMessage( j
, J
.iter
);
395 // multiply prod with prod_j
396 for( size_t r
= 0; r
< prod
.size(); ++r
) {
397 if( props
.logdomain
)
398 prod
[r
] += prod_j
[ind
[r
]];
400 prod
[r
] *= prod_j
[ind
[r
]];
404 if( props
.logdomain
) {
405 prod
-= prod
.maxVal();
409 Factor
result( factor(I
).vars(), prod
);
417 Real
BP::logZ() const {
419 for(size_t i
= 0; i
< nrVars(); ++i
)
420 sum
+= (1.0 - nbV(i
).size()) * beliefV(i
).entropy();
421 for( size_t I
= 0; I
< nrFactors(); ++I
)
422 sum
-= KL_dist( beliefF(I
), factor(I
) );
427 string
BP::identify() const {
428 return string(Name
) + printProperties();
432 void BP::init( const VarSet
&ns
) {
433 for( VarSet::const_iterator n
= ns
.begin(); n
!= ns
.end(); ++n
) {
434 size_t ni
= findVar( *n
);
435 foreach( const Neighbor
&I
, nbV( ni
) )
436 message( ni
, I
.iter
).fill( props
.logdomain
? 0.0 : 1.0 );
441 } // end of namespace dai