Generalized VarSet to "template<typename T> small_set<T>"
[libdai.git] / src / jtree.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 <dai/jtree.h>
24
25
26 namespace dai {
27
28
29 using namespace std;
30
31
32 const char *JTree::Name = "JTREE";
33
34
35 void JTree::setProperties( const PropertySet &opts ) {
36 assert( opts.hasKey("verbose") );
37 assert( opts.hasKey("updates") );
38
39 props.verbose = opts.getStringAs<size_t>("verbose");
40 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
41 }
42
43
44 PropertySet JTree::getProperties() const {
45 PropertySet opts;
46 opts.Set( "verbose", props.verbose );
47 opts.Set( "updates", props.updates );
48 return opts;
49 }
50
51
52 string JTree::printProperties() const {
53 stringstream s( stringstream::out );
54 s << "[";
55 s << "verbose=" << props.verbose << ",";
56 s << "updates=" << props.updates << "]";
57 return s.str();
58 }
59
60
61 JTree::JTree( const FactorGraph &fg, const PropertySet &opts, bool automatic ) : DAIAlgRG(fg), _mes(), _logZ(), RTree(), Qa(), Qb(), props() {
62 setProperties( opts );
63
64 if( !isConnected() )
65 DAI_THROW(FACTORGRAPH_NOT_CONNECTED);
66
67 if( automatic ) {
68 // Create ClusterGraph which contains factors as clusters
69 vector<VarSet> cl;
70 cl.reserve( fg.nrFactors() );
71 for( size_t I = 0; I < nrFactors(); I++ )
72 cl.push_back( factor(I).vars() );
73 ClusterGraph _cg( cl );
74
75 if( props.verbose >= 3 )
76 cout << "Initial clusters: " << _cg << endl;
77
78 // Retain only maximal clusters
79 _cg.eraseNonMaximal();
80 if( props.verbose >= 3 )
81 cout << "Maximal clusters: " << _cg << endl;
82
83 vector<VarSet> ElimVec = _cg.VarElim_MinFill().eraseNonMaximal().toVector();
84 if( props.verbose >= 3 )
85 cout << "VarElim_MinFill result: " << ElimVec << endl;
86
87 GenerateJT( ElimVec );
88 }
89 }
90
91
92 void JTree::GenerateJT( const std::vector<VarSet> &Cliques ) {
93 // Construct a weighted graph (each edge is weighted with the cardinality
94 // of the intersection of the nodes, where the nodes are the elements of
95 // Cliques).
96 WeightedGraph<int> JuncGraph;
97 for( size_t i = 0; i < Cliques.size(); i++ )
98 for( size_t j = i+1; j < Cliques.size(); j++ ) {
99 size_t w = (Cliques[i] & Cliques[j]).size();
100 if( w )
101 JuncGraph[UEdge(i,j)] = w;
102 }
103
104 // Construct maximal spanning tree using Prim's algorithm
105 RTree = MaxSpanningTreePrims( JuncGraph );
106
107 // Construct corresponding region graph
108
109 // Create outer regions
110 ORs.reserve( Cliques.size() );
111 for( size_t i = 0; i < Cliques.size(); i++ )
112 ORs.push_back( FRegion( Factor(Cliques[i], 1.0), 1.0 ) );
113
114 // For each factor, find an outer region that subsumes that factor.
115 // Then, multiply the outer region with that factor.
116 for( size_t I = 0; I < nrFactors(); I++ ) {
117 size_t alpha;
118 for( alpha = 0; alpha < nrORs(); alpha++ )
119 if( OR(alpha).vars() >> factor(I).vars() ) {
120 fac2OR.push_back( alpha );
121 break;
122 }
123 assert( alpha != nrORs() );
124 }
125 RecomputeORs();
126
127 // Create inner regions and edges
128 IRs.reserve( RTree.size() );
129 vector<Edge> edges;
130 edges.reserve( 2 * RTree.size() );
131 for( size_t i = 0; i < RTree.size(); i++ ) {
132 edges.push_back( Edge( RTree[i].n1, nrIRs() ) );
133 edges.push_back( Edge( RTree[i].n2, nrIRs() ) );
134 // inner clusters have counting number -1
135 IRs.push_back( Region( Cliques[RTree[i].n1] & Cliques[RTree[i].n2], -1.0 ) );
136 }
137
138 // create bipartite graph
139 G.construct( nrORs(), nrIRs(), edges.begin(), edges.end() );
140
141 // Create messages and beliefs
142 Qa.clear();
143 Qa.reserve( nrORs() );
144 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
145 Qa.push_back( OR(alpha) );
146
147 Qb.clear();
148 Qb.reserve( nrIRs() );
149 for( size_t beta = 0; beta < nrIRs(); beta++ )
150 Qb.push_back( Factor( IR(beta), 1.0 ) );
151
152 _mes.clear();
153 _mes.reserve( nrORs() );
154 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
155 _mes.push_back( vector<Factor>() );
156 _mes[alpha].reserve( nbOR(alpha).size() );
157 foreach( const Neighbor &beta, nbOR(alpha) )
158 _mes[alpha].push_back( Factor( IR(beta), 1.0 ) );
159 }
160
161 // Check counting numbers
162 Check_Counting_Numbers();
163
164 if( props.verbose >= 3 ) {
165 cout << "Resulting regiongraph: " << *this << endl;
166 }
167 }
168
169
170 string JTree::identify() const {
171 return string(Name) + printProperties();
172 }
173
174
175 Factor JTree::belief( const VarSet &ns ) const {
176 vector<Factor>::const_iterator beta;
177 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
178 if( beta->vars() >> ns )
179 break;
180 if( beta != Qb.end() )
181 return( beta->marginal(ns) );
182 else {
183 vector<Factor>::const_iterator alpha;
184 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
185 if( alpha->vars() >> ns )
186 break;
187 assert( alpha != Qa.end() );
188 return( alpha->marginal(ns) );
189 }
190 }
191
192
193 vector<Factor> JTree::beliefs() const {
194 vector<Factor> result;
195 for( size_t beta = 0; beta < nrIRs(); beta++ )
196 result.push_back( Qb[beta] );
197 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
198 result.push_back( Qa[alpha] );
199 return result;
200 }
201
202
203 Factor JTree::belief( const Var &n ) const {
204 return belief( (VarSet)n );
205 }
206
207
208 // Needs no init
209 void JTree::runHUGIN() {
210 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
211 Qa[alpha] = OR(alpha);
212
213 for( size_t beta = 0; beta < nrIRs(); beta++ )
214 Qb[beta].fill( 1.0 );
215
216 // CollectEvidence
217 _logZ = 0.0;
218 for( size_t i = RTree.size(); (i--) != 0; ) {
219 // Make outer region RTree[i].n1 consistent with outer region RTree[i].n2
220 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
221 Factor new_Qb = Qa[RTree[i].n2].partSum( IR( i ) );
222 _logZ += log(new_Qb.normalize());
223 Qa[RTree[i].n1] *= new_Qb.divided_by( Qb[i] );
224 Qb[i] = new_Qb;
225 }
226 if( RTree.empty() )
227 _logZ += log(Qa[0].normalize() );
228 else
229 _logZ += log(Qa[RTree[0].n1].normalize());
230
231 // DistributeEvidence
232 for( size_t i = 0; i < RTree.size(); i++ ) {
233 // Make outer region RTree[i].n2 consistent with outer region RTree[i].n1
234 // IR(i) = seperator OR(RTree[i].n1) && OR(RTree[i].n2)
235 Factor new_Qb = Qa[RTree[i].n1].marginal( IR( i ) );
236 Qa[RTree[i].n2] *= new_Qb.divided_by( Qb[i] );
237 Qb[i] = new_Qb;
238 }
239
240 // Normalize
241 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
242 Qa[alpha].normalize();
243 }
244
245
246 // Really needs no init! Initial messages can be anything.
247 void JTree::runShaferShenoy() {
248 // First pass
249 _logZ = 0.0;
250 for( size_t e = nrIRs(); (e--) != 0; ) {
251 // send a message from RTree[e].n2 to RTree[e].n1
252 // or, actually, from the seperator IR(e) to RTree[e].n1
253
254 size_t i = nbIR(e)[1].node; // = RTree[e].n2
255 size_t j = nbIR(e)[0].node; // = RTree[e].n1
256 size_t _e = nbIR(e)[0].dual;
257
258 Factor piet = OR(i);
259 foreach( const Neighbor &k, nbOR(i) )
260 if( k != e )
261 piet *= message( i, k.iter );
262 message( j, _e ) = piet.partSum( IR(e) );
263 _logZ += log( message(j,_e).normalize() );
264 }
265
266 // Second pass
267 for( size_t e = 0; e < nrIRs(); e++ ) {
268 size_t i = nbIR(e)[0].node; // = RTree[e].n1
269 size_t j = nbIR(e)[1].node; // = RTree[e].n2
270 size_t _e = nbIR(e)[1].dual;
271
272 Factor piet = OR(i);
273 foreach( const Neighbor &k, nbOR(i) )
274 if( k != e )
275 piet *= message( i, k.iter );
276 message( j, _e ) = piet.marginal( IR(e) );
277 }
278
279 // Calculate beliefs
280 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
281 Factor piet = OR(alpha);
282 foreach( const Neighbor &k, nbOR(alpha) )
283 piet *= message( alpha, k.iter );
284 if( nrIRs() == 0 ) {
285 _logZ += log( piet.normalize() );
286 Qa[alpha] = piet;
287 } else if( alpha == nbIR(0)[0].node /*RTree[0].n1*/ ) {
288 _logZ += log( piet.normalize() );
289 Qa[alpha] = piet;
290 } else
291 Qa[alpha] = piet.normalized();
292 }
293
294 // Only for logZ (and for belief)...
295 for( size_t beta = 0; beta < nrIRs(); beta++ )
296 Qb[beta] = Qa[nbIR(beta)[0].node].marginal( IR(beta) );
297 }
298
299
300 double JTree::run() {
301 if( props.updates == Properties::UpdateType::HUGIN )
302 runHUGIN();
303 else if( props.updates == Properties::UpdateType::SHSH )
304 runShaferShenoy();
305 return 0.0;
306 }
307
308
309 Real JTree::logZ() const {
310 Real sum = 0.0;
311 for( size_t beta = 0; beta < nrIRs(); beta++ )
312 sum += IR(beta).c() * Qb[beta].entropy();
313 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
314 sum += OR(alpha).c() * Qa[alpha].entropy();
315 sum += (OR(alpha).log0() * Qa[alpha]).totalSum();
316 }
317 return sum;
318 }
319
320
321
322 size_t JTree::findEfficientTree( const VarSet& ns, DEdgeVec &Tree, size_t PreviousRoot ) const {
323 // find new root clique (the one with maximal statespace overlap with ns)
324 size_t maxval = 0, maxalpha = 0;
325 for( size_t alpha = 0; alpha < nrORs(); alpha++ ) {
326 size_t val = nrStates( ns & OR(alpha).vars() );
327 if( val > maxval ) {
328 maxval = val;
329 maxalpha = alpha;
330 }
331 }
332
333 // grow new tree
334 Graph oldTree;
335 for( DEdgeVec::const_iterator e = RTree.begin(); e != RTree.end(); e++ )
336 oldTree.insert( UEdge(e->n1, e->n2) );
337 DEdgeVec newTree = GrowRootedTree( oldTree, maxalpha );
338
339 // identify subtree that contains variables of ns which are not in the new root
340 VarSet nsrem = ns / OR(maxalpha).vars();
341 set<DEdge> subTree;
342 // for each variable in ns that is not in the root clique
343 for( VarSet::const_iterator n = nsrem.begin(); n != nsrem.end(); n++ ) {
344 // find first occurence of *n in the tree, which is closest to the root
345 size_t e = 0;
346 for( ; e != newTree.size(); e++ ) {
347 if( OR(newTree[e].n2).vars().contains( *n ) )
348 break;
349 }
350 assert( e != newTree.size() );
351
352 // track-back path to root and add edges to subTree
353 subTree.insert( newTree[e] );
354 size_t pos = newTree[e].n1;
355 for( ; e > 0; e-- )
356 if( newTree[e-1].n2 == pos ) {
357 subTree.insert( newTree[e-1] );
358 pos = newTree[e-1].n1;
359 }
360 }
361 if( PreviousRoot != (size_t)-1 && PreviousRoot != maxalpha) {
362 // find first occurence of PreviousRoot in the tree, which is closest to the new root
363 size_t e = 0;
364 for( ; e != newTree.size(); e++ ) {
365 if( newTree[e].n2 == PreviousRoot )
366 break;
367 }
368 assert( e != newTree.size() );
369
370 // track-back path to root and add edges to subTree
371 subTree.insert( newTree[e] );
372 size_t pos = newTree[e].n1;
373 for( ; e > 0; e-- )
374 if( newTree[e-1].n2 == pos ) {
375 subTree.insert( newTree[e-1] );
376 pos = newTree[e-1].n1;
377 }
378 }
379
380 // Resulting Tree is a reordered copy of newTree
381 // First add edges in subTree to Tree
382 Tree.clear();
383 for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
384 if( subTree.count( *e ) ) {
385 Tree.push_back( *e );
386 }
387 // Then add edges pointing away from nsrem
388 // FIXME
389 /* for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
390 for( set<DEdge>::const_iterator sTi = subTree.begin(); sTi != subTree.end(); sTi++ )
391 if( *e != *sTi ) {
392 if( e->n1 == sTi->n1 || e->n1 == sTi->n2 ||
393 e->n2 == sTi->n1 || e->n2 == sTi->n2 ) {
394 Tree.push_back( *e );
395 }
396 }*/
397 // FIXME
398 /* for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
399 if( find( Tree.begin(), Tree.end(), *e) == Tree.end() ) {
400 bool found = false;
401 for( VarSet::const_iterator n = nsrem.begin(); n != nsrem.end(); n++ )
402 if( (OR(e->n1).vars() && *n) ) {
403 found = true;
404 break;
405 }
406 if( found ) {
407 Tree.push_back( *e );
408 }
409 }*/
410 size_t subTreeSize = Tree.size();
411 // Then add remaining edges
412 for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
413 if( find( Tree.begin(), Tree.end(), *e ) == Tree.end() )
414 Tree.push_back( *e );
415
416 return subTreeSize;
417 }
418
419
420 // Cutset conditioning
421 // assumes that run() has been called already
422 Factor JTree::calcMarginal( const VarSet& ns ) {
423 vector<Factor>::const_iterator beta;
424 for( beta = Qb.begin(); beta != Qb.end(); beta++ )
425 if( beta->vars() >> ns )
426 break;
427 if( beta != Qb.end() )
428 return( beta->marginal(ns) );
429 else {
430 vector<Factor>::const_iterator alpha;
431 for( alpha = Qa.begin(); alpha != Qa.end(); alpha++ )
432 if( alpha->vars() >> ns )
433 break;
434 if( alpha != Qa.end() )
435 return( alpha->marginal(ns) );
436 else {
437 // Find subtree to do efficient inference
438 DEdgeVec T;
439 size_t Tsize = findEfficientTree( ns, T );
440
441 // Find remaining variables (which are not in the new root)
442 VarSet nsrem = ns / OR(T.front().n1).vars();
443 Factor Pns (ns, 0.0);
444
445 // Save Qa and Qb on the subtree
446 map<size_t,Factor> Qa_old;
447 map<size_t,Factor> Qb_old;
448 vector<size_t> b(Tsize, 0);
449 for( size_t i = Tsize; (i--) != 0; ) {
450 size_t alpha1 = T[i].n1;
451 size_t alpha2 = T[i].n2;
452 size_t beta;
453 for( beta = 0; beta < nrIRs(); beta++ )
454 if( UEdge( RTree[beta].n1, RTree[beta].n2 ) == UEdge( alpha1, alpha2 ) )
455 break;
456 assert( beta != nrIRs() );
457 b[i] = beta;
458
459 if( !Qa_old.count( alpha1 ) )
460 Qa_old[alpha1] = Qa[alpha1];
461 if( !Qa_old.count( alpha2 ) )
462 Qa_old[alpha2] = Qa[alpha2];
463 if( !Qb_old.count( beta ) )
464 Qb_old[beta] = Qb[beta];
465 }
466
467 // For all states of nsrem
468 for( State s(nsrem); s.valid(); s++ ) {
469 // CollectEvidence
470 double logZ = 0.0;
471 for( size_t i = Tsize; (i--) != 0; ) {
472 // Make outer region T[i].n1 consistent with outer region T[i].n2
473 // IR(i) = seperator OR(T[i].n1) && OR(T[i].n2)
474
475 for( VarSet::const_iterator n = nsrem.begin(); n != nsrem.end(); n++ )
476 if( Qa[T[i].n2].vars() >> *n ) {
477 Factor piet( *n, 0.0 );
478 piet[s(*n)] = 1.0;
479 Qa[T[i].n2] *= piet;
480 }
481
482 Factor new_Qb = Qa[T[i].n2].partSum( IR( b[i] ) );
483 logZ += log(new_Qb.normalize());
484 Qa[T[i].n1] *= new_Qb.divided_by( Qb[b[i]] );
485 Qb[b[i]] = new_Qb;
486 }
487 logZ += log(Qa[T[0].n1].normalize());
488
489 Factor piet( nsrem, 0.0 );
490 piet[s] = exp(logZ);
491 Pns += piet * Qa[T[0].n1].partSum( ns / nsrem ); // OPTIMIZE ME
492
493 // Restore clamped beliefs
494 for( map<size_t,Factor>::const_iterator alpha = Qa_old.begin(); alpha != Qa_old.end(); alpha++ )
495 Qa[alpha->first] = alpha->second;
496 for( map<size_t,Factor>::const_iterator beta = Qb_old.begin(); beta != Qb_old.end(); beta++ )
497 Qb[beta->first] = beta->second;
498 }
499
500 return( Pns.normalized() );
501 }
502 }
503 }
504
505
506 // first return value is treewidth
507 // second return value is number of states in largest clique
508 pair<size_t,size_t> treewidth( const FactorGraph & fg ) {
509 ClusterGraph _cg;
510
511 // Copy factors
512 for( size_t I = 0; I < fg.nrFactors(); I++ )
513 _cg.insert( fg.factor(I).vars() );
514
515 // Retain only maximal clusters
516 _cg.eraseNonMaximal();
517
518 // Obtain elimination sequence
519 vector<VarSet> ElimVec = _cg.VarElim_MinFill().eraseNonMaximal().toVector();
520
521 // Calculate treewidth
522 size_t treewidth = 0;
523 size_t nrstates = 0;
524 for( size_t i = 0; i < ElimVec.size(); i++ ) {
525 if( ElimVec[i].size() > treewidth )
526 treewidth = ElimVec[i].size();
527 size_t s = nrStates(ElimVec[i]);
528 if( s > nrstates )
529 nrstates = s;
530 }
531
532 return pair<size_t,size_t>(treewidth, nrstates);
533 }
534
535
536 } // end of namespace dai