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 bool BP::checkProperties() {
43 if( !HasProperty("updates") )
45 if( !HasProperty("tol") )
47 if (!HasProperty("maxiter") )
49 if (!HasProperty("verbose") )
51 if (!HasProperty("logdomain") )
54 ConvertPropertyTo
<double>("tol");
55 ConvertPropertyTo
<size_t>("maxiter");
56 ConvertPropertyTo
<size_t>("verbose");
57 ConvertPropertyTo
<UpdateType
>("updates");
58 ConvertPropertyTo
<bool>("logdomain");
59 logDomain
= GetPropertyAs
<bool>("logdomain");
66 // create edge properties
68 edges
.reserve( nrVars() );
69 for( size_t i
= 0; i
< nrVars(); ++i
) {
70 edges
.push_back( vector
<EdgeProp
>() );
71 edges
[i
].reserve( nbV(i
).size() );
72 foreach( const Neighbor
&I
, nbV(i
) ) {
74 newEP
.message
= Prob( var(i
).states() );
75 newEP
.newMessage
= Prob( var(i
).states() );
77 newEP
.index
.reserve( factor(I
).states() );
78 for( IndexFor
k( var(i
), factor(I
).vars() ); k
>= 0; ++k
)
79 newEP
.index
.push_back( k
);
82 edges
[i
].push_back( newEP
);
89 assert( checkProperties() );
90 for( size_t i
= 0; i
< nrVars(); ++i
) {
91 foreach( const Neighbor
&I
, nbV(i
) ) {
93 message( i
, I
.iter
).fill( 0.0 );
94 newMessage( i
, I
.iter
).fill( 0.0 );
96 message( i
, I
.iter
).fill( 1.0 );
97 newMessage( i
, I
.iter
).fill( 1.0 );
104 void BP::findMaxResidual( size_t &i
, size_t &_I
) {
107 double maxres
= residual( i
, _I
);
108 for( size_t j
= 0; j
< nrVars(); ++j
)
109 foreach( const Neighbor
&I
, nbV(j
) )
110 if( residual( j
, I
.iter
) > maxres
) {
113 maxres
= residual( i
, _I
);
118 void BP::calcNewMessage( size_t i
, size_t _I
) {
119 // calculate updated message I->i
120 size_t I
= nbV(i
,_I
);
122 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION
124 Factor prod( factor( I ) );
125 for( _nb_cit j = nb2(I).begin(); j != nb2(I).end(); j++ )
126 if( *j != i ) { // for all j in I \ i
127 for( _nb_cit J = nb1(*j).begin(); J != nb1(*j).end(); J++ )
128 if( *J != I ) { // for all J in nb(j) \ I
129 prod *= Factor( *j, message(*j,*J) );
130 Factor marg = prod.marginal(var(i));
133 Prob
prod( factor(I
).p() );
137 // Calculate product of incoming messages and factor I
138 foreach( const Neighbor
&j
, nbF(I
) ) {
139 if( j
!= i
) { // for all j in I \ i
141 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
142 const ind_t
& ind
= index(j
, _I
);
144 // prod_j will be the product of messages coming into j
145 Prob
prod_j( var(j
).states(), logDomain
? 0.0 : 1.0 );
146 foreach( const Neighbor
&J
, nbV(j
) )
147 if( J
!= I
) { // for all J in nb(j) \ I
149 prod_j
+= message( j
, J
.iter
);
151 prod_j
*= message( j
, J
.iter
);
154 // multiply prod with prod_j
155 for( size_t r
= 0; r
< prod
.size(); ++r
)
157 prod
[r
] += prod_j
[ind
[r
]];
159 prod
[r
] *= prod_j
[ind
[r
]];
163 prod
-= prod
.maxVal();
167 // Marginalize onto i
168 Prob
marg( var(i
).states(), 0.0 );
169 // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
170 const ind_t ind
= index(i
,_I
);
171 for( size_t r
= 0; r
< prod
.size(); ++r
)
172 marg
[ind
[r
]] += prod
[r
];
173 marg
.normalize( _normtype
);
177 newMessage(i
,_I
) = marg
.log();
179 newMessage(i
,_I
) = marg
;
183 // BP::run does not check for NANs for performance reasons
184 // Somehow NaNs do not often occur in BP...
187 cout
<< "Starting " << identify() << "...";
192 Diffs
diffs(nrVars(), 1.0);
194 vector
<Edge
> update_seq
;
196 vector
<Factor
> old_beliefs
;
197 old_beliefs
.reserve( nrVars() );
198 for( size_t i
= 0; i
< nrVars(); ++i
)
199 old_beliefs
.push_back( beliefV(i
) );
202 size_t nredges
= nrEdges();
204 if( Updates() == UpdateType::SEQMAX
) {
206 for( size_t i
= 0; i
< nrVars(); ++i
)
207 foreach( const Neighbor
&I
, nbV(i
) ) {
208 calcNewMessage( i
, I
.iter
);
209 // calculate initial residuals
210 residual( i
, I
.iter
) = dist( newMessage( i
, I
.iter
), message( i
, I
.iter
), Prob::DISTLINF
);
213 update_seq
.reserve( nredges
);
214 for( size_t i
= 0; i
< nrVars(); ++i
)
215 foreach( const Neighbor
&I
, nbV(i
) )
216 update_seq
.push_back( Edge( i
, I
.iter
) );
219 // do several passes over the network until maximum number of iterations has
220 // been reached or until the maximum belief difference is smaller than tolerance
221 for( iter
=0; iter
< MaxIter() && diffs
.maxDiff() > Tol(); ++iter
) {
222 if( Updates() == UpdateType::SEQMAX
) {
223 // Residuals-BP by Koller et al.
224 for( size_t t
= 0; t
< nredges
; ++t
) {
225 // update the message with the largest residual
228 findMaxResidual( i
, _I
);
229 message( i
, _I
) = newMessage( i
, _I
);
230 residual( i
, _I
) = 0.0;
232 // I->i has been updated, which means that residuals for all
233 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
234 foreach( const Neighbor
&J
, nbV(i
) ) {
236 foreach( const Neighbor
&j
, nbF(J
) ) {
239 calcNewMessage( j
, _J
);
240 residual( j
, _J
) = dist( newMessage( j
, _J
), message( j
, _J
), Prob::DISTLINF
);
246 } else if( Updates() == UpdateType::PARALL
) {
248 for( size_t i
= 0; i
< nrVars(); ++i
)
249 foreach( const Neighbor
&I
, nbV(i
) )
250 calcNewMessage( i
, I
.iter
);
252 for( size_t i
= 0; i
< nrVars(); ++i
)
253 foreach( const Neighbor
&I
, nbV(i
) )
254 message( i
, I
.iter
) = newMessage( i
, I
.iter
);
256 // Sequential updates
257 if( Updates() == UpdateType::SEQRND
)
258 random_shuffle( update_seq
.begin(), update_seq
.end() );
260 foreach( const Edge
&e
, update_seq
) {
261 calcNewMessage( e
.first
, e
.second
);
262 message( e
.first
, e
.second
) = newMessage( e
.first
, e
.second
);
266 // calculate new beliefs and compare with old ones
267 for( size_t i
= 0; i
< nrVars(); ++i
) {
268 Factor
nb( beliefV(i
) );
269 diffs
.push( dist( nb
, old_beliefs
[i
], Prob::DISTLINF
) );
274 cout
<< "BP::run: maxdiff " << diffs
.maxDiff() << " after " << iter
+1 << " passes" << endl
;
277 updateMaxDiff( diffs
.maxDiff() );
279 if( Verbose() >= 1 ) {
280 if( diffs
.maxDiff() > Tol() ) {
283 cout
<< "BP::run: WARNING: not converged within " << MaxIter() << " passes (" << toc() - tic
<< " clocks)...final maxdiff:" << diffs
.maxDiff() << endl
;
287 cout
<< "converged in " << iter
<< " passes (" << toc() - tic
<< " clocks)." << endl
;
291 return diffs
.maxDiff();
295 Factor
BP::beliefV( size_t i
) const {
296 Prob
prod( var(i
).states(), logDomain
? 0.0 : 1.0 );
297 foreach( const Neighbor
&I
, nbV(i
) )
299 prod
+= newMessage( i
, I
.iter
);
301 prod
*= newMessage( i
, I
.iter
);
303 prod
-= prod
.maxVal();
307 prod
.normalize( Prob::NORMPROB
);
308 return( Factor( var(i
), prod
) );
312 Factor
BP::belief (const Var
&n
) const {
313 return( beliefV( findVar( n
) ) );
317 vector
<Factor
> BP::beliefs() const {
318 vector
<Factor
> result
;
319 for( size_t i
= 0; i
< nrVars(); ++i
)
320 result
.push_back( beliefV(i
) );
321 for( size_t I
= 0; I
< nrFactors(); ++I
)
322 result
.push_back( beliefF(I
) );
327 Factor
BP::belief( const VarSet
&ns
) const {
329 return belief( *(ns
.begin()) );
332 for( I
= 0; I
< nrFactors(); I
++ )
333 if( factor(I
).vars() >> ns
)
335 assert( I
!= nrFactors() );
336 return beliefF(I
).marginal(ns
);
341 Factor
BP::beliefF (size_t I
) const {
342 Prob
prod( factor(I
).p() );
346 foreach( const Neighbor
&j
, nbF(I
) ) {
348 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
349 const ind_t
& ind
= index(j
, _I
);
351 // prod_j will be the product of messages coming into j
352 Prob
prod_j( var(j
).states(), logDomain
? 0.0 : 1.0 );
353 foreach( const Neighbor
&J
, nbV(j
) ) {
354 if( J
!= I
) { // for all J in nb(j) \ I
356 prod_j
+= newMessage( j
, J
.iter
);
358 prod_j
*= newMessage( j
, J
.iter
);
362 // multiply prod with prod_j
363 for( size_t r
= 0; r
< prod
.size(); ++r
) {
365 prod
[r
] += prod_j
[ind
[r
]];
367 prod
[r
] *= prod_j
[ind
[r
]];
372 prod
-= prod
.maxVal();
376 Factor
result( factor(I
).vars(), prod
);
377 result
.normalize( Prob::NORMPROB
);
381 /* UNOPTIMIZED VERSION
383 Factor prod( factor(I) );
384 for( _nb_cit i = nb2(I).begin(); i != nb2(I).end(); i++ ) {
385 for( _nb_cit J = nb1(*i).begin(); J != nb1(*i).end(); J++ )
387 prod *= Factor( var(*i), newMessage(*i,*J)) );
389 return prod.normalize( Prob::NORMPROB );*/
393 Complex
BP::logZ() const {
395 for(size_t i
= 0; i
< nrVars(); ++i
)
396 sum
+= Complex(1.0 - nbV(i
).size()) * beliefV(i
).entropy();
397 for( size_t I
= 0; I
< nrFactors(); ++I
)
398 sum
-= KL_dist( beliefF(I
), factor(I
) );
403 string
BP::identify() const {
404 stringstream
result (stringstream::out
);
405 result
<< Name
<< GetProperties();
410 void BP::init( const VarSet
&ns
) {
411 for( VarSet::const_iterator n
= ns
.begin(); n
!= ns
.end(); ++n
) {
412 size_t ni
= findVar( *n
);
413 foreach( const Neighbor
&I
, nbV( ni
) )
414 message( ni
, I
.iter
).fill( logDomain
? 0.0 : 1.0 );
419 } // end of namespace dai