Replaced complex numbers by real numbers
[libdai.git] / src / bp.cpp
1 /* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
2 Radboud University Nijmegen, The Netherlands
3
4 This file is part of libDAI.
5
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.
10
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.
15
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
19 */
20
21
22 #include <iostream>
23 #include <sstream>
24 #include <map>
25 #include <set>
26 #include <algorithm>
27 #include <dai/bp.h>
28 #include <dai/diffs.h>
29 #include <dai/util.h>
30 #include <dai/properties.h>
31
32
33 namespace dai {
34
35
36 using namespace std;
37
38
39 const char *BP::Name = "BP";
40
41
42 bool BP::checkProperties() {
43 if( !HasProperty("updates") )
44 return false;
45 if( !HasProperty("tol") )
46 return false;
47 if (!HasProperty("maxiter") )
48 return false;
49 if (!HasProperty("verbose") )
50 return false;
51 if (!HasProperty("logdomain") )
52 return false;
53
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");
60
61 return true;
62 }
63
64
65 void BP::create() {
66 // create edge properties
67 edges.clear();
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) ) {
73 EdgeProp newEP;
74 newEP.message = Prob( var(i).states() );
75 newEP.newMessage = Prob( var(i).states() );
76
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 );
80
81 newEP.residual = 0.0;
82 edges[i].push_back( newEP );
83 }
84 }
85 }
86
87
88 void BP::init() {
89 assert( checkProperties() );
90 for( size_t i = 0; i < nrVars(); ++i ) {
91 foreach( const Neighbor &I, nbV(i) ) {
92 if( logDomain ) {
93 message( i, I.iter ).fill( 0.0 );
94 newMessage( i, I.iter ).fill( 0.0 );
95 } else {
96 message( i, I.iter ).fill( 1.0 );
97 newMessage( i, I.iter ).fill( 1.0 );
98 }
99 }
100 }
101 }
102
103
104 void BP::findMaxResidual( size_t &i, size_t &_I ) {
105 i = 0;
106 _I = 0;
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 ) {
111 i = j;
112 _I = I.iter;
113 maxres = residual( i, _I );
114 }
115 }
116
117
118 void BP::calcNewMessage( size_t i, size_t _I ) {
119 // calculate updated message I->i
120 size_t I = nbV(i,_I);
121
122 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION
123
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));
131 */
132
133 Prob prod( factor(I).p() );
134 if( logDomain )
135 prod.takeLog();
136
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
140 size_t _I = j.dual;
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);
143
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
148 if( logDomain )
149 prod_j += message( j, J.iter );
150 else
151 prod_j *= message( j, J.iter );
152 }
153
154 // multiply prod with prod_j
155 for( size_t r = 0; r < prod.size(); ++r )
156 if( logDomain )
157 prod[r] += prod_j[ind[r]];
158 else
159 prod[r] *= prod_j[ind[r]];
160 }
161 }
162 if( logDomain ) {
163 prod -= prod.maxVal();
164 prod.takeExp();
165 }
166
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 );
174
175 // Store result
176 if( logDomain )
177 newMessage(i,_I) = marg.log();
178 else
179 newMessage(i,_I) = marg;
180 }
181
182
183 // BP::run does not check for NANs for performance reasons
184 // Somehow NaNs do not often occur in BP...
185 double BP::run() {
186 if( Verbose() >= 1 )
187 cout << "Starting " << identify() << "...";
188 if( Verbose() >= 3)
189 cout << endl;
190
191 double tic = toc();
192 Diffs diffs(nrVars(), 1.0);
193
194 vector<Edge> update_seq;
195
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) );
200
201 size_t iter = 0;
202 size_t nredges = nrEdges();
203
204 if( Updates() == UpdateType::SEQMAX ) {
205 // do the first pass
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 );
211 }
212 } else {
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 ) );
217 }
218
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
226
227 size_t i, _I;
228 findMaxResidual( i, _I );
229 message( i, _I ) = newMessage( i, _I );
230 residual( i, _I ) = 0.0;
231
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) ) {
235 if( J.iter != _I ) {
236 foreach( const Neighbor &j, nbF(J) ) {
237 size_t _J = j.dual;
238 if( j != i ) {
239 calcNewMessage( j, _J );
240 residual( j, _J ) = dist( newMessage( j, _J ), message( j, _J ), Prob::DISTLINF );
241 }
242 }
243 }
244 }
245 }
246 } else if( Updates() == UpdateType::PARALL ) {
247 // Parallel updates
248 for( size_t i = 0; i < nrVars(); ++i )
249 foreach( const Neighbor &I, nbV(i) )
250 calcNewMessage( i, I.iter );
251
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 );
255 } else {
256 // Sequential updates
257 if( Updates() == UpdateType::SEQRND )
258 random_shuffle( update_seq.begin(), update_seq.end() );
259
260 foreach( const Edge &e, update_seq ) {
261 calcNewMessage( e.first, e.second );
262 message( e.first, e.second ) = newMessage( e.first, e.second );
263 }
264 }
265
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 ) );
270 old_beliefs[i] = nb;
271 }
272
273 if( Verbose() >= 3 )
274 cout << "BP::run: maxdiff " << diffs.maxDiff() << " after " << iter+1 << " passes" << endl;
275 }
276
277 updateMaxDiff( diffs.maxDiff() );
278
279 if( Verbose() >= 1 ) {
280 if( diffs.maxDiff() > Tol() ) {
281 if( Verbose() == 1 )
282 cout << endl;
283 cout << "BP::run: WARNING: not converged within " << MaxIter() << " passes (" << toc() - tic << " clocks)...final maxdiff:" << diffs.maxDiff() << endl;
284 } else {
285 if( Verbose() >= 3 )
286 cout << "BP::run: ";
287 cout << "converged in " << iter << " passes (" << toc() - tic << " clocks)." << endl;
288 }
289 }
290
291 return diffs.maxDiff();
292 }
293
294
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) )
298 if( logDomain )
299 prod += newMessage( i, I.iter );
300 else
301 prod *= newMessage( i, I.iter );
302 if( logDomain ) {
303 prod -= prod.maxVal();
304 prod.takeExp();
305 }
306
307 prod.normalize( Prob::NORMPROB );
308 return( Factor( var(i), prod ) );
309 }
310
311
312 Factor BP::belief (const Var &n) const {
313 return( beliefV( findVar( n ) ) );
314 }
315
316
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) );
323 return result;
324 }
325
326
327 Factor BP::belief( const VarSet &ns ) const {
328 if( ns.size() == 1 )
329 return belief( *(ns.begin()) );
330 else {
331 size_t I;
332 for( I = 0; I < nrFactors(); I++ )
333 if( factor(I).vars() >> ns )
334 break;
335 assert( I != nrFactors() );
336 return beliefF(I).marginal(ns);
337 }
338 }
339
340
341 Factor BP::beliefF (size_t I) const {
342 Prob prod( factor(I).p() );
343 if( logDomain )
344 prod.takeLog();
345
346 foreach( const Neighbor &j, nbF(I) ) {
347 size_t _I = j.dual;
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);
350
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
355 if( logDomain )
356 prod_j += newMessage( j, J.iter );
357 else
358 prod_j *= newMessage( j, J.iter );
359 }
360 }
361
362 // multiply prod with prod_j
363 for( size_t r = 0; r < prod.size(); ++r ) {
364 if( logDomain )
365 prod[r] += prod_j[ind[r]];
366 else
367 prod[r] *= prod_j[ind[r]];
368 }
369 }
370
371 if( logDomain ) {
372 prod -= prod.maxVal();
373 prod.takeExp();
374 }
375
376 Factor result( factor(I).vars(), prod );
377 result.normalize( Prob::NORMPROB );
378
379 return( result );
380
381 /* UNOPTIMIZED VERSION
382
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++ )
386 if( *J != I )
387 prod *= Factor( var(*i), newMessage(*i,*J)) );
388 }
389 return prod.normalize( Prob::NORMPROB );*/
390 }
391
392
393 Real BP::logZ() const {
394 Real sum = 0.0;
395 for(size_t i = 0; i < nrVars(); ++i )
396 sum += (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) );
399 return sum;
400 }
401
402
403 string BP::identify() const {
404 stringstream result (stringstream::out);
405 result << Name << GetProperties();
406 return result.str();
407 }
408
409
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 );
415 }
416 }
417
418
419 } // end of namespace dai