Strengthened convergence criteria of various algorithms
[libdai.git] / src / jtree.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 #include <iostream>
13 #include <stack>
14 #include <dai/jtree.h>
15
16
17 namespace dai {
18
19
20 using namespace std;
21
22
23 const char *JTree::Name = "JTREE";
24
25
26 void JTree::setProperties( const PropertySet &opts ) {
27 DAI_ASSERT( opts.hasKey("verbose") );
28 DAI_ASSERT( opts.hasKey("updates") );
29
30 props.verbose = opts.getStringAs<size_t>("verbose");
31 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
32 if( opts.hasKey("inference") )
33 props.inference = opts.getStringAs<Properties::InfType>("inference");
34 else
35 props.inference = Properties::InfType::SUMPROD;
36 }
37
38
39 PropertySet JTree::getProperties() const {
40 PropertySet opts;
41 opts.Set( "verbose", props.verbose );
42 opts.Set( "updates", props.updates );
43 opts.Set( "inference", props.inference );
44 return opts;
45 }
46
47
48 string JTree::printProperties() const {
49 stringstream s( stringstream::out );
50 s << "[";
51 s << "verbose=" << props.verbose << ",";
52 s << "updates=" << props.updates << ",";
53 s << "inference=" << props.inference << "]";
54 return s.str();
55 }
56
57
58 JTree::JTree( const FactorGraph &fg, const PropertySet &opts, bool automatic ) : DAIAlgRG(fg), _mes(), _logZ(), RTree(), Qa(), Qb(), props() {
59 setProperties( opts );
60
61 if( !isConnected() )
62 DAI_THROW(FACTORGRAPH_NOT_CONNECTED);
63
64 if( automatic ) {
65 // Create ClusterGraph which contains factors as clusters
66 vector<VarSet> cl;
67 cl.reserve( fg.nrFactors() );
68 for( size_t I = 0; I < nrFactors(); I++ )
69 cl.push_back( factor(I).vars() );
70 ClusterGraph _cg( cl );
71
72 if( props.verbose >= 3 )
73 cerr << "Initial clusters: " << _cg << endl;
74
75 // Retain only maximal clusters
76 _cg.eraseNonMaximal();
77 if( props.verbose >= 3 )
78 cerr << "Maximal clusters: " << _cg << endl;
79
80 // Use MinFill heuristic to guess optimal elimination sequence
81 vector<VarSet> ElimVec = _cg.VarElim_MinFill().eraseNonMaximal().toVector();
82 if( props.verbose >= 3 )
83 cerr << "VarElim_MinFill result: " << ElimVec << endl;
84
85 // Generate the junction tree corresponding to the elimination sequence
86 GenerateJT( ElimVec );
87 }
88 }
89
90
91 void JTree::GenerateJT( const std::vector<VarSet> &Cliques ) {
92 // Construct a weighted graph (each edge is weighted with the cardinality
93 // of the intersection of the nodes, where the nodes are the elements of
94 // Cliques).
95 WeightedGraph<int> JuncGraph;
96 for( size_t i = 0; i < Cliques.size(); i++ )
97 for( size_t j = i+1; j < Cliques.size(); j++ ) {
98 size_t w = (Cliques[i] & Cliques[j]).size();
99 if( w )
100 JuncGraph[UEdge(i,j)] = w;
101 }
102
103 // Construct maximal spanning tree using Prim's algorithm
104 RTree = MaxSpanningTreePrims( JuncGraph );
105
106 // Construct corresponding region graph
107
108 // Create outer regions
109 ORs.reserve( Cliques.size() );
110 for( size_t i = 0; i < Cliques.size(); i++ )
111 ORs.push_back( FRegion( Factor(Cliques[i], 1.0), 1.0 ) );
112
113 // For each factor, find an outer region that subsumes that factor.
114 // Then, multiply the outer region with that factor.
115 for( size_t I = 0; I < nrFactors(); I++ ) {
116 size_t alpha;
117 for( alpha = 0; alpha < nrORs(); alpha++ )
118 if( OR(alpha).vars() >> factor(I).vars() ) {
119 fac2OR.push_back( alpha );
120 break;
121 }
122 DAI_ASSERT( alpha != nrORs() );
123 }
124 RecomputeORs();
125
126 // Create inner regions and edges
127 IRs.reserve( RTree.size() );
128 vector<Edge> edges;
129 edges.reserve( 2 * RTree.size() );
130 for( size_t i = 0; i < RTree.size(); i++ ) {
131 edges.push_back( Edge( RTree[i].n1, nrIRs() ) );
132 edges.push_back( Edge( RTree[i].n2, nrIRs() ) );
133 // inner clusters have counting number -1
134 IRs.push_back( Region( Cliques[RTree[i].n1] & Cliques[RTree[i].n2], -1.0 ) );
135 }
136
137 // create bipartite graph
138 G.construct( nrORs(), nrIRs(), edges.begin(), edges.end() );
139
140 // Create messages and beliefs
141 Qa.clear();
142 Qa.reserve( nrORs() );
143 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
144 Qa.push_back( OR(alpha) );
145
146 Qb.clear();
147 Qb.reserve( nrIRs() );
148 for( size_t beta = 0; beta < nrIRs(); beta++ )
149 Qb.push_back( Factor( IR(beta), 1.0 ) );
150
151 _mes.clear();
152 _mes.reserve( nrORs() );
153 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
154 _mes.push_back( vector<Factor>() );
155 _mes[alpha].reserve( nbOR(alpha).size() );
156 foreach( const Neighbor &beta, nbOR(alpha) )
157 _mes[alpha].push_back( Factor( IR(beta), 1.0 ) );
158 }
159
160 // Check counting numbers
161 #ifdef DAI_DEBUG
162 checkCountingNumbers();
163 #endif
164
165 if( props.verbose >= 3 )
166 cerr << "Regiongraph generated by JTree::GenerateJT: " << *this << endl;
167 }
168
169
170 string JTree::identify() const {
171 return string(Name) + printProperties();
172 }
173
174
175 Factor JTree::belief( const VarSet &vs ) const {
176 vector<Factor>::const_iterator beta;
177 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
178 if( beta->vars() >> vs )
179 break;
180 if( beta != Qb.end() )
181 return( beta->marginal(vs) );
182 else {
183 vector<Factor>::const_iterator alpha;
184 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
185 if( alpha->vars() >> vs )
186 break;
187 if( alpha == Qa.end() ) {
188 DAI_THROW(BELIEF_NOT_AVAILABLE);
189 return Factor();
190 } else
191 return( alpha->marginal(vs) );
192 }
193 }
194
195
196 vector<Factor> JTree::beliefs() const {
197 vector<Factor> result;
198 for( size_t beta = 0; beta < nrIRs(); beta++ )
199 result.push_back( Qb[beta] );
200 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
201 result.push_back( Qa[alpha] );
202 return result;
203 }
204
205
206 void JTree::runHUGIN() {
207 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
208 Qa[alpha] = OR(alpha);
209
210 for( size_t beta = 0; beta < nrIRs(); beta++ )
211 Qb[beta].fill( 1.0 );
212
213 // CollectEvidence
214 _logZ = 0.0;
215 for( size_t i = RTree.size(); (i--) != 0; ) {
216 // Make outer region RTree[i].n1 consistent with outer region RTree[i].n2
217 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
218 Factor new_Qb;
219 if( props.inference == Properties::InfType::SUMPROD )
220 new_Qb = Qa[RTree[i].n2].marginal( IR( i ), false );
221 else
222 new_Qb = Qa[RTree[i].n2].maxMarginal( IR( i ), false );
223
224 _logZ += log(new_Qb.normalize());
225 Qa[RTree[i].n1] *= new_Qb / Qb[i];
226 Qb[i] = new_Qb;
227 }
228 if( RTree.empty() )
229 _logZ += log(Qa[0].normalize() );
230 else
231 _logZ += log(Qa[RTree[0].n1].normalize());
232
233 // DistributeEvidence
234 for( size_t i = 0; i < RTree.size(); i++ ) {
235 // Make outer region RTree[i].n2 consistent with outer region RTree[i].n1
236 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
237 Factor new_Qb;
238 if( props.inference == Properties::InfType::SUMPROD )
239 new_Qb = Qa[RTree[i].n1].marginal( IR( i ) );
240 else
241 new_Qb = Qa[RTree[i].n1].maxMarginal( IR( i ) );
242
243 Qa[RTree[i].n2] *= new_Qb / Qb[i];
244 Qb[i] = new_Qb;
245 }
246
247 // Normalize
248 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
249 Qa[alpha].normalize();
250 }
251
252
253 void JTree::runShaferShenoy() {
254 // First pass
255 _logZ = 0.0;
256 for( size_t e = nrIRs(); (e--) != 0; ) {
257 // send a message from RTree[e].n2 to RTree[e].n1
258 // or, actually, from the seperator IR(e) to RTree[e].n1
259
260 size_t i = nbIR(e)[1].node; // = RTree[e].n2
261 size_t j = nbIR(e)[0].node; // = RTree[e].n1
262 size_t _e = nbIR(e)[0].dual;
263
264 Factor msg = OR(i);
265 foreach( const Neighbor &k, nbOR(i) )
266 if( k != e )
267 msg *= message( i, k.iter );
268 if( props.inference == Properties::InfType::SUMPROD )
269 message( j, _e ) = msg.marginal( IR(e), false );
270 else
271 message( j, _e ) = msg.maxMarginal( IR(e), false );
272 _logZ += log( message(j,_e).normalize() );
273 }
274
275 // Second pass
276 for( size_t e = 0; e < nrIRs(); e++ ) {
277 size_t i = nbIR(e)[0].node; // = RTree[e].n1
278 size_t j = nbIR(e)[1].node; // = RTree[e].n2
279 size_t _e = nbIR(e)[1].dual;
280
281 Factor msg = OR(i);
282 foreach( const Neighbor &k, nbOR(i) )
283 if( k != e )
284 msg *= message( i, k.iter );
285 if( props.inference == Properties::InfType::SUMPROD )
286 message( j, _e ) = msg.marginal( IR(e) );
287 else
288 message( j, _e ) = msg.maxMarginal( IR(e) );
289 }
290
291 // Calculate beliefs
292 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
293 Factor piet = OR(alpha);
294 foreach( const Neighbor &k, nbOR(alpha) )
295 piet *= message( alpha, k.iter );
296 if( nrIRs() == 0 ) {
297 _logZ += log( piet.normalize() );
298 Qa[alpha] = piet;
299 } else if( alpha == nbIR(0)[0].node /*RTree[0].n1*/ ) {
300 _logZ += log( piet.normalize() );
301 Qa[alpha] = piet;
302 } else
303 Qa[alpha] = piet.normalized();
304 }
305
306 // Only for logZ (and for belief)...
307 for( size_t beta = 0; beta < nrIRs(); beta++ ) {
308 if( props.inference == Properties::InfType::SUMPROD )
309 Qb[beta] = Qa[nbIR(beta)[0].node].marginal( IR(beta) );
310 else
311 Qb[beta] = Qa[nbIR(beta)[0].node].maxMarginal( IR(beta) );
312 }
313 }
314
315
316 Real JTree::run() {
317 if( props.updates == Properties::UpdateType::HUGIN )
318 runHUGIN();
319 else if( props.updates == Properties::UpdateType::SHSH )
320 runShaferShenoy();
321 return 0.0;
322 }
323
324
325 Real JTree::logZ() const {
326 Real s = 0.0;
327 for( size_t beta = 0; beta < nrIRs(); beta++ )
328 s += IR(beta).c() * Qb[beta].entropy();
329 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
330 s += OR(alpha).c() * Qa[alpha].entropy();
331 s += (OR(alpha).log(true) * Qa[alpha]).sum();
332 }
333 return s;
334 }
335
336
337 size_t JTree::findEfficientTree( const VarSet& vs, RootedTree &Tree, size_t PreviousRoot ) const {
338 // find new root clique (the one with maximal statespace overlap with vs)
339 size_t maxval = 0, maxalpha = 0;
340 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
341 size_t val = VarSet(vs & OR(alpha).vars()).nrStates();
342 if( val > maxval ) {
343 maxval = val;
344 maxalpha = alpha;
345 }
346 }
347
348 // reorder the tree edges such that maxalpha becomes the new root
349 RootedTree newTree( Graph( RTree.begin(), RTree.end() ), maxalpha );
350
351 // identify subtree that contains all variables of vs which are not in the new root
352 VarSet vsrem = vs / OR(maxalpha).vars();
353 set<DEdge> subTree;
354 // for each variable in vs that is not in the root clique
355 for( VarSet::const_iterator n = vsrem.begin(); n != vsrem.end(); n++ ) {
356 // find first occurence of *n in the tree, which is closest to the root
357 size_t e = 0;
358 for( ; e != newTree.size(); e++ ) {
359 if( OR(newTree[e].n2).vars().contains( *n ) )
360 break;
361 }
362 DAI_ASSERT( e != newTree.size() );
363
364 // track-back path to root and add edges to subTree
365 subTree.insert( newTree[e] );
366 size_t pos = newTree[e].n1;
367 for( ; e > 0; e-- )
368 if( newTree[e-1].n2 == pos ) {
369 subTree.insert( newTree[e-1] );
370 pos = newTree[e-1].n1;
371 }
372 }
373 if( PreviousRoot != (size_t)-1 && PreviousRoot != maxalpha) {
374 // find first occurence of PreviousRoot in the tree, which is closest to the new root
375 size_t e = 0;
376 for( ; e != newTree.size(); e++ ) {
377 if( newTree[e].n2 == PreviousRoot )
378 break;
379 }
380 DAI_ASSERT( e != newTree.size() );
381
382 // track-back path to root and add edges to subTree
383 subTree.insert( newTree[e] );
384 size_t pos = newTree[e].n1;
385 for( ; e > 0; e-- )
386 if( newTree[e-1].n2 == pos ) {
387 subTree.insert( newTree[e-1] );
388 pos = newTree[e-1].n1;
389 }
390 }
391
392 // Resulting Tree is a reordered copy of newTree
393 // First add edges in subTree to Tree
394 Tree.clear();
395 vector<DEdge> remTree;
396 for( RootedTree::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
397 if( subTree.count( *e ) )
398 Tree.push_back( *e );
399 else
400 remTree.push_back( *e );
401 size_t subTreeSize = Tree.size();
402 // Then add remaining edges
403 copy( remTree.begin(), remTree.end(), back_inserter( Tree ) );
404
405 return subTreeSize;
406 }
407
408
409 Factor JTree::calcMarginal( const VarSet& vs ) {
410 vector<Factor>::const_iterator beta;
411 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
412 if( beta->vars() >> vs )
413 break;
414 if( beta != Qb.end() )
415 return( beta->marginal(vs) );
416 else {
417 vector<Factor>::const_iterator alpha;
418 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
419 if( alpha->vars() >> vs )
420 break;
421 if( alpha != Qa.end() )
422 return( alpha->marginal(vs) );
423 else {
424 // Find subtree to do efficient inference
425 RootedTree T;
426 size_t Tsize = findEfficientTree( vs, T );
427
428 // Find remaining variables (which are not in the new root)
429 VarSet vsrem = vs / OR(T.front().n1).vars();
430 Factor Pvs (vs, 0.0);
431
432 // Save Qa and Qb on the subtree
433 map<size_t,Factor> Qa_old;
434 map<size_t,Factor> Qb_old;
435 vector<size_t> b(Tsize, 0);
436 for( size_t i = Tsize; (i--) != 0; ) {
437 size_t alpha1 = T[i].n1;
438 size_t alpha2 = T[i].n2;
439 size_t beta;
440 for( beta = 0; beta < nrIRs(); beta++ )
441 if( UEdge( RTree[beta].n1, RTree[beta].n2 ) == UEdge( alpha1, alpha2 ) )
442 break;
443 DAI_ASSERT( beta != nrIRs() );
444 b[i] = beta;
445
446 if( !Qa_old.count( alpha1 ) )
447 Qa_old[alpha1] = Qa[alpha1];
448 if( !Qa_old.count( alpha2 ) )
449 Qa_old[alpha2] = Qa[alpha2];
450 if( !Qb_old.count( beta ) )
451 Qb_old[beta] = Qb[beta];
452 }
453
454 // For all states of vsrem
455 for( State s(vsrem); s.valid(); s++ ) {
456 // CollectEvidence
457 Real logZ = 0.0;
458 for( size_t i = Tsize; (i--) != 0; ) {
459 // Make outer region T[i].n1 consistent with outer region T[i].n2
460 // IR(i) = seperator OR(T[i].n1) && OR(T[i].n2)
461
462 for( VarSet::const_iterator n = vsrem.begin(); n != vsrem.end(); n++ )
463 if( Qa[T[i].n2].vars() >> *n ) {
464 Factor piet( *n, 0.0 );
465 piet[s(*n)] = 1.0;
466 Qa[T[i].n2] *= piet;
467 }
468
469 Factor new_Qb = Qa[T[i].n2].marginal( IR( b[i] ), false );
470 logZ += log(new_Qb.normalize());
471 Qa[T[i].n1] *= new_Qb / Qb[b[i]];
472 Qb[b[i]] = new_Qb;
473 }
474 logZ += log(Qa[T[0].n1].normalize());
475
476 Factor piet( vsrem, 0.0 );
477 piet[s] = exp(logZ);
478 Pvs += piet * Qa[T[0].n1].marginal( vs / vsrem, false ); // OPTIMIZE ME
479
480 // Restore clamped beliefs
481 for( map<size_t,Factor>::const_iterator alpha = Qa_old.begin(); alpha != Qa_old.end(); alpha++ )
482 Qa[alpha->first] = alpha->second;
483 for( map<size_t,Factor>::const_iterator beta = Qb_old.begin(); beta != Qb_old.end(); beta++ )
484 Qb[beta->first] = beta->second;
485 }
486
487 return( Pvs.normalized() );
488 }
489 }
490 }
491
492
493 std::pair<size_t,size_t> boundTreewidth( const FactorGraph & fg ) {
494 ClusterGraph _cg;
495
496 // Copy factors
497 for( size_t I = 0; I < fg.nrFactors(); I++ )
498 _cg.insert( fg.factor(I).vars() );
499
500 // Retain only maximal clusters
501 _cg.eraseNonMaximal();
502
503 // Obtain elimination sequence
504 vector<VarSet> ElimVec = _cg.VarElim_MinFill().eraseNonMaximal().toVector();
505
506 // Calculate treewidth
507 size_t treewidth = 0;
508 size_t nrstates = 0;
509 for( size_t i = 0; i < ElimVec.size(); i++ ) {
510 if( ElimVec[i].size() > treewidth )
511 treewidth = ElimVec[i].size();
512 size_t s = ElimVec[i].nrStates();
513 if( s > nrstates )
514 nrstates = s;
515 }
516
517 return pair<size_t,size_t>(treewidth, nrstates);
518 }
519
520
521 std::pair<size_t,size_t> treewidth( const FactorGraph & fg )
522 {
523 return boundTreewidth( fg );
524 }
525
526
527 std::vector<size_t> JTree::findMaximum() const {
528 vector<size_t> maximum( nrVars() );
529 vector<bool> visitedVars( nrVars(), false );
530 vector<bool> visitedFactors( nrFactors(), false );
531 stack<size_t> scheduledFactors;
532 for( size_t i = 0; i < nrVars(); ++i ) {
533 if( visitedVars[i] )
534 continue;
535 visitedVars[i] = true;
536
537 // Maximise with respect to variable i
538 Prob prod = beliefV(i).p();
539 maximum[i] = prod.argmax().first;
540
541 foreach( const Neighbor &I, nbV(i) )
542 if( !visitedFactors[I] )
543 scheduledFactors.push(I);
544
545 while( !scheduledFactors.empty() ){
546 size_t I = scheduledFactors.top();
547 scheduledFactors.pop();
548 if( visitedFactors[I] )
549 continue;
550 visitedFactors[I] = true;
551
552 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
553 bool allDetermined = true;
554 foreach( const Neighbor &j, nbF(I) )
555 if( !visitedVars[j.node] ) {
556 allDetermined = false;
557 break;
558 }
559 if( allDetermined )
560 continue;
561
562 // Calculate product of incoming messages on factor I
563 Prob prod2 = beliefF(I).p();
564
565 // The allowed configuration is restrained according to the variables assigned so far:
566 // pick the argmax amongst the allowed states
567 Real maxProb = numeric_limits<Real>::min();
568 State maxState( factor(I).vars() );
569 for( State s( factor(I).vars() ); s.valid(); ++s ){
570 // First, calculate whether this state is consistent with variables that
571 // have been assigned already
572 bool allowedState = true;
573 foreach( const Neighbor &j, nbF(I) )
574 if( visitedVars[j.node] && maximum[j.node] != s(var(j.node)) ) {
575 allowedState = false;
576 break;
577 }
578 // If it is consistent, check if its probability is larger than what we have seen so far
579 if( allowedState && prod2[s] > maxProb ) {
580 maxState = s;
581 maxProb = prod2[s];
582 }
583 }
584
585 // Decode the argmax
586 foreach( const Neighbor &j, nbF(I) ) {
587 if( visitedVars[j.node] ) {
588 // We have already visited j earlier - hopefully our state is consistent
589 if( maximum[j.node] != maxState(var(j.node)) && props.verbose >= 1 )
590 cerr << "JTree::findMaximum - warning: maximum not consistent due to loops." << endl;
591 } else {
592 // We found a consistent state for variable j
593 visitedVars[j.node] = true;
594 maximum[j.node] = maxState( var(j.node) );
595 foreach( const Neighbor &J, nbV(j) )
596 if( !visitedFactors[J] )
597 scheduledFactors.push(J);
598 }
599 }
600 }
601 }
602 return maximum;
603 }
604
605
606 } // end of namespace dai