Improved error messages of Evidence::addEvidenceTabFile
[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 if( DAI_DEBUG )
162 checkCountingNumbers();
163
164 if( props.verbose >= 3 )
165 cerr << "Regiongraph generated by JTree::GenerateJT: " << *this << endl;
166 }
167
168
169 string JTree::identify() const {
170 return string(Name) + printProperties();
171 }
172
173
174 Factor JTree::belief( const VarSet &vs ) const {
175 vector<Factor>::const_iterator beta;
176 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
177 if( beta->vars() >> vs )
178 break;
179 if( beta != Qb.end() )
180 return( beta->marginal(vs) );
181 else {
182 vector<Factor>::const_iterator alpha;
183 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
184 if( alpha->vars() >> vs )
185 break;
186 DAI_ASSERT( alpha != Qa.end() );
187 return( alpha->marginal(vs) );
188 }
189 }
190
191
192 vector<Factor> JTree::beliefs() const {
193 vector<Factor> result;
194 for( size_t beta = 0; beta < nrIRs(); beta++ )
195 result.push_back( Qb[beta] );
196 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
197 result.push_back( Qa[alpha] );
198 return result;
199 }
200
201
202 Factor JTree::belief( const Var &v ) const {
203 return belief( (VarSet)v );
204 }
205
206
207 void JTree::runHUGIN() {
208 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
209 Qa[alpha] = OR(alpha);
210
211 for( size_t beta = 0; beta < nrIRs(); beta++ )
212 Qb[beta].fill( 1.0 );
213
214 // CollectEvidence
215 _logZ = 0.0;
216 for( size_t i = RTree.size(); (i--) != 0; ) {
217 // Make outer region RTree[i].n1 consistent with outer region RTree[i].n2
218 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
219 Factor new_Qb;
220 if( props.inference == Properties::InfType::SUMPROD )
221 new_Qb = Qa[RTree[i].n2].marginal( IR( i ), false );
222 else
223 new_Qb = Qa[RTree[i].n2].maxMarginal( IR( i ), false );
224
225 _logZ += log(new_Qb.normalize());
226 Qa[RTree[i].n1] *= new_Qb / Qb[i];
227 Qb[i] = new_Qb;
228 }
229 if( RTree.empty() )
230 _logZ += log(Qa[0].normalize() );
231 else
232 _logZ += log(Qa[RTree[0].n1].normalize());
233
234 // DistributeEvidence
235 for( size_t i = 0; i < RTree.size(); i++ ) {
236 // Make outer region RTree[i].n2 consistent with outer region RTree[i].n1
237 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
238 Factor new_Qb;
239 if( props.inference == Properties::InfType::SUMPROD )
240 new_Qb = Qa[RTree[i].n1].marginal( IR( i ) );
241 else
242 new_Qb = Qa[RTree[i].n1].maxMarginal( IR( i ) );
243
244 Qa[RTree[i].n2] *= new_Qb / Qb[i];
245 Qb[i] = new_Qb;
246 }
247
248 // Normalize
249 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
250 Qa[alpha].normalize();
251 }
252
253
254 void JTree::runShaferShenoy() {
255 // First pass
256 _logZ = 0.0;
257 for( size_t e = nrIRs(); (e--) != 0; ) {
258 // send a message from RTree[e].n2 to RTree[e].n1
259 // or, actually, from the seperator IR(e) to RTree[e].n1
260
261 size_t i = nbIR(e)[1].node; // = RTree[e].n2
262 size_t j = nbIR(e)[0].node; // = RTree[e].n1
263 size_t _e = nbIR(e)[0].dual;
264
265 Factor msg = OR(i);
266 foreach( const Neighbor &k, nbOR(i) )
267 if( k != e )
268 msg *= message( i, k.iter );
269 if( props.inference == Properties::InfType::SUMPROD )
270 message( j, _e ) = msg.marginal( IR(e), false );
271 else
272 message( j, _e ) = msg.maxMarginal( IR(e), false );
273 _logZ += log( message(j,_e).normalize() );
274 }
275
276 // Second pass
277 for( size_t e = 0; e < nrIRs(); e++ ) {
278 size_t i = nbIR(e)[0].node; // = RTree[e].n1
279 size_t j = nbIR(e)[1].node; // = RTree[e].n2
280 size_t _e = nbIR(e)[1].dual;
281
282 Factor msg = OR(i);
283 foreach( const Neighbor &k, nbOR(i) )
284 if( k != e )
285 msg *= message( i, k.iter );
286 if( props.inference == Properties::InfType::SUMPROD )
287 message( j, _e ) = msg.marginal( IR(e) );
288 else
289 message( j, _e ) = msg.maxMarginal( IR(e) );
290 }
291
292 // Calculate beliefs
293 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
294 Factor piet = OR(alpha);
295 foreach( const Neighbor &k, nbOR(alpha) )
296 piet *= message( alpha, k.iter );
297 if( nrIRs() == 0 ) {
298 _logZ += log( piet.normalize() );
299 Qa[alpha] = piet;
300 } else if( alpha == nbIR(0)[0].node /*RTree[0].n1*/ ) {
301 _logZ += log( piet.normalize() );
302 Qa[alpha] = piet;
303 } else
304 Qa[alpha] = piet.normalized();
305 }
306
307 // Only for logZ (and for belief)...
308 for( size_t beta = 0; beta < nrIRs(); beta++ ) {
309 if( props.inference == Properties::InfType::SUMPROD )
310 Qb[beta] = Qa[nbIR(beta)[0].node].marginal( IR(beta) );
311 else
312 Qb[beta] = Qa[nbIR(beta)[0].node].maxMarginal( IR(beta) );
313 }
314 }
315
316
317 Real JTree::run() {
318 if( props.updates == Properties::UpdateType::HUGIN )
319 runHUGIN();
320 else if( props.updates == Properties::UpdateType::SHSH )
321 runShaferShenoy();
322 return 0.0;
323 }
324
325
326 Real JTree::logZ() const {
327 Real s = 0.0;
328 for( size_t beta = 0; beta < nrIRs(); beta++ )
329 s += IR(beta).c() * Qb[beta].entropy();
330 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
331 s += OR(alpha).c() * Qa[alpha].entropy();
332 s += (OR(alpha).log(true) * Qa[alpha]).sum();
333 }
334 return s;
335 }
336
337
338 size_t JTree::findEfficientTree( const VarSet& vs, RootedTree &Tree, size_t PreviousRoot ) const {
339 // find new root clique (the one with maximal statespace overlap with vs)
340 size_t maxval = 0, maxalpha = 0;
341 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
342 size_t val = VarSet(vs & OR(alpha).vars()).nrStates();
343 if( val > maxval ) {
344 maxval = val;
345 maxalpha = alpha;
346 }
347 }
348
349 // reorder the tree edges such that maxalpha becomes the new root
350 RootedTree newTree( Graph( RTree.begin(), RTree.end() ), maxalpha );
351
352 // identify subtree that contains all variables of vs which are not in the new root
353 VarSet vsrem = vs / OR(maxalpha).vars();
354 set<DEdge> subTree;
355 // for each variable in vs that is not in the root clique
356 for( VarSet::const_iterator n = vsrem.begin(); n != vsrem.end(); n++ ) {
357 // find first occurence of *n in the tree, which is closest to the root
358 size_t e = 0;
359 for( ; e != newTree.size(); e++ ) {
360 if( OR(newTree[e].n2).vars().contains( *n ) )
361 break;
362 }
363 DAI_ASSERT( e != newTree.size() );
364
365 // track-back path to root and add edges to subTree
366 subTree.insert( newTree[e] );
367 size_t pos = newTree[e].n1;
368 for( ; e > 0; e-- )
369 if( newTree[e-1].n2 == pos ) {
370 subTree.insert( newTree[e-1] );
371 pos = newTree[e-1].n1;
372 }
373 }
374 if( PreviousRoot != (size_t)-1 && PreviousRoot != maxalpha) {
375 // find first occurence of PreviousRoot in the tree, which is closest to the new root
376 size_t e = 0;
377 for( ; e != newTree.size(); e++ ) {
378 if( newTree[e].n2 == PreviousRoot )
379 break;
380 }
381 DAI_ASSERT( e != newTree.size() );
382
383 // track-back path to root and add edges to subTree
384 subTree.insert( newTree[e] );
385 size_t pos = newTree[e].n1;
386 for( ; e > 0; e-- )
387 if( newTree[e-1].n2 == pos ) {
388 subTree.insert( newTree[e-1] );
389 pos = newTree[e-1].n1;
390 }
391 }
392
393 // Resulting Tree is a reordered copy of newTree
394 // First add edges in subTree to Tree
395 Tree.clear();
396 vector<DEdge> remTree;
397 for( RootedTree::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
398 if( subTree.count( *e ) )
399 Tree.push_back( *e );
400 else
401 remTree.push_back( *e );
402 size_t subTreeSize = Tree.size();
403 // Then add remaining edges
404 copy( remTree.begin(), remTree.end(), back_inserter( Tree ) );
405
406 return subTreeSize;
407 }
408
409
410 Factor JTree::calcMarginal( const VarSet& vs ) {
411 vector<Factor>::const_iterator beta;
412 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
413 if( beta->vars() >> vs )
414 break;
415 if( beta != Qb.end() )
416 return( beta->marginal(vs) );
417 else {
418 vector<Factor>::const_iterator alpha;
419 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
420 if( alpha->vars() >> vs )
421 break;
422 if( alpha != Qa.end() )
423 return( alpha->marginal(vs) );
424 else {
425 // Find subtree to do efficient inference
426 RootedTree T;
427 size_t Tsize = findEfficientTree( vs, T );
428
429 // Find remaining variables (which are not in the new root)
430 VarSet vsrem = vs / OR(T.front().n1).vars();
431 Factor Pvs (vs, 0.0);
432
433 // Save Qa and Qb on the subtree
434 map<size_t,Factor> Qa_old;
435 map<size_t,Factor> Qb_old;
436 vector<size_t> b(Tsize, 0);
437 for( size_t i = Tsize; (i--) != 0; ) {
438 size_t alpha1 = T[i].n1;
439 size_t alpha2 = T[i].n2;
440 size_t beta;
441 for( beta = 0; beta < nrIRs(); beta++ )
442 if( UEdge( RTree[beta].n1, RTree[beta].n2 ) == UEdge( alpha1, alpha2 ) )
443 break;
444 DAI_ASSERT( beta != nrIRs() );
445 b[i] = beta;
446
447 if( !Qa_old.count( alpha1 ) )
448 Qa_old[alpha1] = Qa[alpha1];
449 if( !Qa_old.count( alpha2 ) )
450 Qa_old[alpha2] = Qa[alpha2];
451 if( !Qb_old.count( beta ) )
452 Qb_old[beta] = Qb[beta];
453 }
454
455 // For all states of vsrem
456 for( State s(vsrem); s.valid(); s++ ) {
457 // CollectEvidence
458 Real logZ = 0.0;
459 for( size_t i = Tsize; (i--) != 0; ) {
460 // Make outer region T[i].n1 consistent with outer region T[i].n2
461 // IR(i) = seperator OR(T[i].n1) && OR(T[i].n2)
462
463 for( VarSet::const_iterator n = vsrem.begin(); n != vsrem.end(); n++ )
464 if( Qa[T[i].n2].vars() >> *n ) {
465 Factor piet( *n, 0.0 );
466 piet[s(*n)] = 1.0;
467 Qa[T[i].n2] *= piet;
468 }
469
470 Factor new_Qb = Qa[T[i].n2].marginal( IR( b[i] ), false );
471 logZ += log(new_Qb.normalize());
472 Qa[T[i].n1] *= new_Qb / Qb[b[i]];
473 Qb[b[i]] = new_Qb;
474 }
475 logZ += log(Qa[T[0].n1].normalize());
476
477 Factor piet( vsrem, 0.0 );
478 piet[s] = exp(logZ);
479 Pvs += piet * Qa[T[0].n1].marginal( vs / vsrem, false ); // OPTIMIZE ME
480
481 // Restore clamped beliefs
482 for( map<size_t,Factor>::const_iterator alpha = Qa_old.begin(); alpha != Qa_old.end(); alpha++ )
483 Qa[alpha->first] = alpha->second;
484 for( map<size_t,Factor>::const_iterator beta = Qb_old.begin(); beta != Qb_old.end(); beta++ )
485 Qb[beta->first] = beta->second;
486 }
487
488 return( Pvs.normalized() );
489 }
490 }
491 }
492
493
494 std::pair<size_t,size_t> boundTreewidth( const FactorGraph & fg ) {
495 ClusterGraph _cg;
496
497 // Copy factors
498 for( size_t I = 0; I < fg.nrFactors(); I++ )
499 _cg.insert( fg.factor(I).vars() );
500
501 // Retain only maximal clusters
502 _cg.eraseNonMaximal();
503
504 // Obtain elimination sequence
505 vector<VarSet> ElimVec = _cg.VarElim_MinFill().eraseNonMaximal().toVector();
506
507 // Calculate treewidth
508 size_t treewidth = 0;
509 size_t nrstates = 0;
510 for( size_t i = 0; i < ElimVec.size(); i++ ) {
511 if( ElimVec[i].size() > treewidth )
512 treewidth = ElimVec[i].size();
513 size_t s = ElimVec[i].nrStates();
514 if( s > nrstates )
515 nrstates = s;
516 }
517
518 return pair<size_t,size_t>(treewidth, nrstates);
519 }
520
521
522 std::pair<size_t,size_t> treewidth( const FactorGraph & fg )
523 {
524 return boundTreewidth( fg );
525 }
526
527
528 std::vector<size_t> JTree::findMaximum() const {
529 vector<size_t> maximum( nrVars() );
530 vector<bool> visitedVars( nrVars(), false );
531 vector<bool> visitedFactors( nrFactors(), false );
532 stack<size_t> scheduledFactors;
533 for( size_t i = 0; i < nrVars(); ++i ) {
534 if( visitedVars[i] )
535 continue;
536 visitedVars[i] = true;
537
538 // Maximise with respect to variable i
539 Prob prod = beliefV(i).p();
540 maximum[i] = prod.argmax().first;
541
542 foreach( const Neighbor &I, nbV(i) )
543 if( !visitedFactors[I] )
544 scheduledFactors.push(I);
545
546 while( !scheduledFactors.empty() ){
547 size_t I = scheduledFactors.top();
548 scheduledFactors.pop();
549 if( visitedFactors[I] )
550 continue;
551 visitedFactors[I] = true;
552
553 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
554 bool allDetermined = true;
555 foreach( const Neighbor &j, nbF(I) )
556 if( !visitedVars[j.node] ) {
557 allDetermined = false;
558 break;
559 }
560 if( allDetermined )
561 continue;
562
563 // Calculate product of incoming messages on factor I
564 Prob prod2 = beliefF(I).p();
565
566 // The allowed configuration is restrained according to the variables assigned so far:
567 // pick the argmax amongst the allowed states
568 Real maxProb = numeric_limits<Real>::min();
569 State maxState( factor(I).vars() );
570 for( State s( factor(I).vars() ); s.valid(); ++s ){
571 // First, calculate whether this state is consistent with variables that
572 // have been assigned already
573 bool allowedState = true;
574 foreach( const Neighbor &j, nbF(I) )
575 if( visitedVars[j.node] && maximum[j.node] != s(var(j.node)) ) {
576 allowedState = false;
577 break;
578 }
579 // If it is consistent, check if its probability is larger than what we have seen so far
580 if( allowedState && prod2[s] > maxProb ) {
581 maxState = s;
582 maxProb = prod2[s];
583 }
584 }
585
586 // Decode the argmax
587 foreach( const Neighbor &j, nbF(I) ) {
588 if( visitedVars[j.node] ) {
589 // We have already visited j earlier - hopefully our state is consistent
590 if( maximum[j.node] != maxState(var(j.node)) && props.verbose >= 1 )
591 cerr << "JTree::findMaximum - warning: maximum not consistent due to loops." << endl;
592 } else {
593 // We found a consistent state for variable j
594 visitedVars[j.node] = true;
595 maximum[j.node] = maxState( var(j.node) );
596 foreach( const Neighbor &J, nbV(j) )
597 if( !visitedFactors[J] )
598 scheduledFactors.push(J);
599 }
600 }
601 }
602 }
603 return maximum;
604 }
605
606
607 } // end of namespace dai