1 /* Copyright (C) 2006-2008 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
5 This file is part of libDAI.
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
30 #include <dai/properties.h>
39 const char *BP::Name
= "BP";
45 void BP::setProperties( const PropertySet
&opts
) {
46 assert( opts
.hasKey("tol") );
47 assert( opts
.hasKey("maxiter") );
48 assert( opts
.hasKey("logdomain") );
49 assert( opts
.hasKey("updates") );
51 props
.tol
= opts
.getStringAs
<double>("tol");
52 props
.maxiter
= opts
.getStringAs
<size_t>("maxiter");
53 props
.logdomain
= opts
.getStringAs
<bool>("logdomain");
54 props
.updates
= opts
.getStringAs
<Properties::UpdateType
>("updates");
56 if( opts
.hasKey("verbose") )
57 props
.verbose
= opts
.getStringAs
<size_t>("verbose");
60 if( opts
.hasKey("damping") )
61 props
.damping
= opts
.getStringAs
<double>("damping");
64 if( opts
.hasKey("inference") )
65 props
.inference
= opts
.getStringAs
<Properties::InfType
>("inference");
67 props
.inference
= Properties::InfType::SUMPROD
;
71 PropertySet
BP::getProperties() const {
73 opts
.Set( "tol", props
.tol
);
74 opts
.Set( "maxiter", props
.maxiter
);
75 opts
.Set( "verbose", props
.verbose
);
76 opts
.Set( "logdomain", props
.logdomain
);
77 opts
.Set( "updates", props
.updates
);
78 opts
.Set( "damping", props
.damping
);
79 opts
.Set( "inference", props
.inference
);
84 string
BP::printProperties() const {
85 stringstream
s( stringstream::out
);
87 s
<< "tol=" << props
.tol
<< ",";
88 s
<< "maxiter=" << props
.maxiter
<< ",";
89 s
<< "verbose=" << props
.verbose
<< ",";
90 s
<< "logdomain=" << props
.logdomain
<< ",";
91 s
<< "updates=" << props
.updates
<< ",";
92 s
<< "damping=" << props
.damping
<< ",";
93 s
<< "inference=" << props
.inference
<< "]";
98 void BP::construct() {
99 // create edge properties
101 _edges
.reserve( nrVars() );
102 for( size_t i
= 0; i
< nrVars(); ++i
) {
103 _edges
.push_back( vector
<EdgeProp
>() );
104 _edges
[i
].reserve( nbV(i
).size() );
105 foreach( const Neighbor
&I
, nbV(i
) ) {
107 newEP
.message
= Prob( var(i
).states() );
108 newEP
.newMessage
= Prob( var(i
).states() );
111 newEP
.index
.reserve( factor(I
).states() );
112 for( IndexFor
k( var(i
), factor(I
).vars() ); k
>= 0; ++k
)
113 newEP
.index
.push_back( k
);
116 newEP
.residual
= 0.0;
117 _edges
[i
].push_back( newEP
);
124 double c
= props
.logdomain
? 0.0 : 1.0;
125 for( size_t i
= 0; i
< nrVars(); ++i
) {
126 foreach( const Neighbor
&I
, nbV(i
) ) {
127 message( i
, I
.iter
).fill( c
);
128 newMessage( i
, I
.iter
).fill( c
);
134 void BP::findMaxResidual( size_t &i
, size_t &_I
) {
137 double maxres
= residual( i
, _I
);
138 for( size_t j
= 0; j
< nrVars(); ++j
)
139 foreach( const Neighbor
&I
, nbV(j
) )
140 if( residual( j
, I
.iter
) > maxres
) {
143 maxres
= residual( i
, _I
);
148 void BP::calcNewMessage( size_t i
, size_t _I
) {
149 // calculate updated message I->i
150 size_t I
= nbV(i
,_I
);
153 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
154 Factor
prod( factor( I
) );
155 foreach( const Neighbor
&j
, nbF(I
) )
156 if( j
!= i
) { // for all j in I \ i
157 foreach( const Neighbor
&J
, nbV(j
) )
158 if( J
!= I
) { // for all J in nb(j) \ I
159 prod
*= Factor( var(j
), message(j
, J
.iter
) );
162 newMessage(i
,_I
) = prod
.marginal( var(i
) ).p();
164 /* OPTIMIZED VERSION */
165 Prob
prod( factor(I
).p() );
166 if( props
.logdomain
)
169 // Calculate product of incoming messages and factor I
170 foreach( const Neighbor
&j
, nbF(I
) ) {
171 if( j
!= i
) { // for all j in I \ i
173 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
174 const ind_t
&ind
= index(j
, _I
);
176 // prod_j will be the product of messages coming into j
177 Prob
prod_j( var(j
).states(), props
.logdomain
? 0.0 : 1.0 );
178 foreach( const Neighbor
&J
, nbV(j
) )
179 if( J
!= I
) { // for all J in nb(j) \ I
180 if( props
.logdomain
)
181 prod_j
+= message( j
, J
.iter
);
183 prod_j
*= message( j
, J
.iter
);
186 // multiply prod with prod_j
187 for( size_t r
= 0; r
< prod
.size(); ++r
)
188 if( props
.logdomain
)
189 prod
[r
] += prod_j
[ind
[r
]];
191 prod
[r
] *= prod_j
[ind
[r
]];
194 if( props
.logdomain
) {
195 prod
-= prod
.maxVal();
199 // Marginalize onto i
200 Prob
marg( var(i
).states(), 0.0 );
201 // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
202 const ind_t ind
= index(i
,_I
);
203 if( props
.inference
== Properties::InfType::SUMPROD
)
204 for( size_t r
= 0; r
< prod
.size(); ++r
)
205 marg
[ind
[r
]] += prod
[r
];
207 for( size_t r
= 0; r
< prod
.size(); ++r
)
208 if( prod
[r
] > marg
[ind
[r
]] )
209 marg
[ind
[r
]] = prod
[r
];
213 if( props
.logdomain
)
214 newMessage(i
,_I
) = marg
.log();
216 newMessage(i
,_I
) = marg
;
221 // BP::run does not check for NANs for performance reasons
222 // Somehow NaNs do not often occur in BP...
224 if( props
.verbose
>= 1 )
225 cout
<< "Starting " << identify() << "...";
226 if( props
.verbose
>= 3)
230 Diffs
diffs(nrVars(), 1.0);
232 vector
<Edge
> update_seq
;
234 vector
<Factor
> old_beliefs
;
235 old_beliefs
.reserve( nrVars() );
236 for( size_t i
= 0; i
< nrVars(); ++i
)
237 old_beliefs
.push_back( beliefV(i
) );
239 size_t nredges
= nrEdges();
241 if( props
.updates
== Properties::UpdateType::SEQMAX
) {
243 for( size_t i
= 0; i
< nrVars(); ++i
)
244 foreach( const Neighbor
&I
, nbV(i
) ) {
245 calcNewMessage( i
, I
.iter
);
246 // calculate initial residuals
247 residual( i
, I
.iter
) = dist( newMessage( i
, I
.iter
), message( i
, I
.iter
), Prob::DISTLINF
);
250 update_seq
.reserve( nredges
);
251 for( size_t i
= 0; i
< nrVars(); ++i
)
252 foreach( const Neighbor
&I
, nbV(i
) )
253 update_seq
.push_back( Edge( i
, I
.iter
) );
256 // do several passes over the network until maximum number of iterations has
257 // been reached or until the maximum belief difference is smaller than tolerance
258 for( _iters
=0; _iters
< props
.maxiter
&& diffs
.maxDiff() > props
.tol
; ++_iters
) {
259 if( props
.updates
== Properties::UpdateType::SEQMAX
) {
260 // Residuals-BP by Koller et al.
261 for( size_t t
= 0; t
< nredges
; ++t
) {
262 // update the message with the largest residual
264 findMaxResidual( i
, _I
);
265 updateMessage( i
, _I
);
267 // I->i has been updated, which means that residuals for all
268 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
269 foreach( const Neighbor
&J
, nbV(i
) ) {
271 foreach( const Neighbor
&j
, nbF(J
) ) {
274 calcNewMessage( j
, _J
);
275 residual( j
, _J
) = dist( newMessage( j
, _J
), message( j
, _J
), Prob::DISTLINF
);
281 } else if( props
.updates
== Properties::UpdateType::PARALL
) {
283 for( size_t i
= 0; i
< nrVars(); ++i
)
284 foreach( const Neighbor
&I
, nbV(i
) )
285 calcNewMessage( i
, I
.iter
);
287 for( size_t i
= 0; i
< nrVars(); ++i
)
288 foreach( const Neighbor
&I
, nbV(i
) )
289 updateMessage( i
, I
.iter
);
291 // Sequential updates
292 if( props
.updates
== Properties::UpdateType::SEQRND
)
293 random_shuffle( update_seq
.begin(), update_seq
.end() );
295 foreach( const Edge
&e
, update_seq
) {
296 calcNewMessage( e
.first
, e
.second
);
297 updateMessage( e
.first
, e
.second
);
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
.push( dist( nb
, old_beliefs
[i
], Prob::DISTLINF
) );
308 if( props
.verbose
>= 3 )
309 cout
<< Name
<< "::run: maxdiff " << diffs
.maxDiff() << " after " << _iters
+1 << " passes" << endl
;
312 if( diffs
.maxDiff() > _maxdiff
)
313 _maxdiff
= diffs
.maxDiff();
315 if( props
.verbose
>= 1 ) {
316 if( diffs
.maxDiff() > props
.tol
) {
317 if( props
.verbose
== 1 )
319 cout
<< Name
<< "::run: WARNING: not converged within " << props
.maxiter
<< " passes (" << toc() - tic
<< " seconds)...final maxdiff:" << diffs
.maxDiff() << endl
;
321 if( props
.verbose
>= 3 )
322 cout
<< Name
<< "::run: ";
323 cout
<< "converged in " << _iters
<< " passes (" << toc() - tic
<< " seconds)." << endl
;
327 return diffs
.maxDiff();
331 Factor
BP::beliefV( size_t i
) const {
332 Prob
prod( var(i
).states(), props
.logdomain
? 0.0 : 1.0 );
333 foreach( const Neighbor
&I
, nbV(i
) )
334 if( props
.logdomain
)
335 prod
+= newMessage( i
, I
.iter
);
337 prod
*= newMessage( i
, I
.iter
);
338 if( props
.logdomain
) {
339 prod
-= prod
.maxVal();
344 return( Factor( var(i
), prod
) );
348 Factor
BP::belief (const Var
&n
) const {
349 return( beliefV( findVar( n
) ) );
353 vector
<Factor
> BP::beliefs() const {
354 vector
<Factor
> result
;
355 for( size_t i
= 0; i
< nrVars(); ++i
)
356 result
.push_back( beliefV(i
) );
357 for( size_t I
= 0; I
< nrFactors(); ++I
)
358 result
.push_back( beliefF(I
) );
363 Factor
BP::belief( const VarSet
&ns
) const {
365 return belief( *(ns
.begin()) );
368 for( I
= 0; I
< nrFactors(); I
++ )
369 if( factor(I
).vars() >> ns
)
371 assert( I
!= nrFactors() );
372 return beliefF(I
).marginal(ns
);
377 Factor
BP::beliefF (size_t I
) const {
379 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
381 Factor
prod( factor(I
) );
382 foreach( const Neighbor
&j
, nbF(I
) ) {
383 foreach( const Neighbor
&J
, nbV(j
) ) {
384 if( J
!= I
) // for all J in nb(j) \ I
385 prod
*= Factor( var(j
), newMessage(j
, J
.iter
) );
388 return prod
.normalized();
390 /* OPTIMIZED VERSION */
391 Prob
prod( factor(I
).p() );
392 if( props
.logdomain
)
395 foreach( const Neighbor
&j
, nbF(I
) ) {
397 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
398 const ind_t
& ind
= index(j
, _I
);
400 // prod_j will be the product of messages coming into j
401 Prob
prod_j( var(j
).states(), props
.logdomain
? 0.0 : 1.0 );
402 foreach( const Neighbor
&J
, nbV(j
) ) {
403 if( J
!= I
) { // for all J in nb(j) \ I
404 if( props
.logdomain
)
405 prod_j
+= newMessage( j
, J
.iter
);
407 prod_j
*= newMessage( j
, J
.iter
);
411 // multiply prod with prod_j
412 for( size_t r
= 0; r
< prod
.size(); ++r
) {
413 if( props
.logdomain
)
414 prod
[r
] += prod_j
[ind
[r
]];
416 prod
[r
] *= prod_j
[ind
[r
]];
420 if( props
.logdomain
) {
421 prod
-= prod
.maxVal();
425 Factor
result( factor(I
).vars(), prod
);
433 Real
BP::logZ() const {
435 for(size_t i
= 0; i
< nrVars(); ++i
)
436 sum
+= (1.0 - nbV(i
).size()) * beliefV(i
).entropy();
437 for( size_t I
= 0; I
< nrFactors(); ++I
)
438 sum
-= dist( beliefF(I
), factor(I
), Prob::DISTKL
);
443 string
BP::identify() const {
444 return string(Name
) + printProperties();
448 void BP::init( const VarSet
&ns
) {
449 for( VarSet::const_iterator n
= ns
.begin(); n
!= ns
.end(); ++n
) {
450 size_t ni
= findVar( *n
);
451 foreach( const Neighbor
&I
, nbV( ni
) )
452 message( ni
, I
.iter
).fill( props
.logdomain
? 0.0 : 1.0 );
457 } // end of namespace dai