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
23 #include <dai/jtree.h>
32 const char *JTree::Name
= "JTREE";
35 void JTree::setProperties( const PropertySet
&opts
) {
36 assert( opts
.hasKey("verbose") );
37 assert( opts
.hasKey("updates") );
39 props
.verbose
= opts
.getStringAs
<size_t>("verbose");
40 props
.updates
= opts
.getStringAs
<Properties::UpdateType
>("updates");
44 PropertySet
JTree::getProperties() const {
46 opts
.Set( "verbose", props
.verbose
);
47 opts
.Set( "updates", props
.updates
);
52 JTree::JTree( const FactorGraph
&fg
, const PropertySet
&opts
, bool automatic
) : DAIAlgRG(fg
), _RTree(), _Qa(), _Qb(), _mes(), _logZ(), props() {
53 setProperties( opts
);
56 // Copy VarSets of factors
58 cl
.reserve( fg
.nrFactors() );
59 for( size_t I
= 0; I
< nrFactors(); I
++ )
60 cl
.push_back( factor(I
).vars() );
61 ClusterGraph
_cg( cl
);
63 if( props
.verbose
>= 3 )
64 cout
<< "Initial clusters: " << _cg
<< endl
;
66 // Retain only maximal clusters
67 _cg
.eraseNonMaximal();
68 if( props
.verbose
>= 3 )
69 cout
<< "Maximal clusters: " << _cg
<< endl
;
71 vector
<VarSet
> ElimVec
= _cg
.VarElim_MinFill().eraseNonMaximal().toVector();
72 if( props
.verbose
>= 3 )
73 cout
<< "VarElim_MinFill result: " << ElimVec
<< endl
;
75 GenerateJT( ElimVec
);
80 void JTree::GenerateJT( const std::vector
<VarSet
> &Cliques
) {
81 // Construct a weighted graph (each edge is weighted with the cardinality
82 // of the intersection of the nodes, where the nodes are the elements of
84 WeightedGraph
<int> JuncGraph
;
85 for( size_t i
= 0; i
< Cliques
.size(); i
++ )
86 for( size_t j
= i
+1; j
< Cliques
.size(); j
++ ) {
87 size_t w
= (Cliques
[i
] & Cliques
[j
]).size();
88 JuncGraph
[UEdge(i
,j
)] = w
;
91 // Construct maximal spanning tree using Prim's algorithm
92 _RTree
= MaxSpanningTreePrims( JuncGraph
);
94 // Construct corresponding region graph
96 // Create outer regions
97 ORs
.reserve( Cliques
.size() );
98 for( size_t i
= 0; i
< Cliques
.size(); i
++ )
99 ORs
.push_back( FRegion( Factor(Cliques
[i
], 1.0), 1.0 ) );
101 // For each factor, find an outer region that subsumes that factor.
102 // Then, multiply the outer region with that factor.
103 for( size_t I
= 0; I
< nrFactors(); I
++ ) {
105 for( alpha
= 0; alpha
< nrORs(); alpha
++ )
106 if( OR(alpha
).vars() >> factor(I
).vars() ) {
107 // OR(alpha) *= factor(I);
108 fac2OR
.push_back( alpha
);
111 assert( alpha
!= nrORs() );
115 // Create inner regions and edges
116 IRs
.reserve( _RTree
.size() );
118 edges
.reserve( 2 * _RTree
.size() );
119 for( size_t i
= 0; i
< _RTree
.size(); i
++ ) {
120 edges
.push_back( Edge( _RTree
[i
].n1
, nrIRs() ) );
121 edges
.push_back( Edge( _RTree
[i
].n2
, nrIRs() ) );
122 // inner clusters have counting number -1
123 IRs
.push_back( Region( Cliques
[_RTree
[i
].n1
] & Cliques
[_RTree
[i
].n2
], -1.0 ) );
126 // create bipartite graph
127 G
.create( nrORs(), nrIRs(), edges
.begin(), edges
.end() );
129 // Create messages and beliefs
131 _Qa
.reserve( nrORs() );
132 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ )
133 _Qa
.push_back( OR(alpha
) );
136 _Qb
.reserve( nrIRs() );
137 for( size_t beta
= 0; beta
< nrIRs(); beta
++ )
138 _Qb
.push_back( Factor( IR(beta
), 1.0 ) );
141 _mes
.reserve( nrORs() );
142 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ ) {
143 _mes
.push_back( vector
<Factor
>() );
144 _mes
[alpha
].reserve( nbOR(alpha
).size() );
145 foreach( const Neighbor
&beta
, nbOR(alpha
) )
146 _mes
[alpha
].push_back( Factor( IR(beta
), 1.0 ) );
149 // Check counting numbers
150 Check_Counting_Numbers();
152 if( props
.verbose
>= 3 ) {
153 cout
<< "Resulting regiongraph: " << *this << endl
;
158 string
JTree::identify() const {
159 stringstream
result (stringstream::out
);
160 result
<< Name
<< getProperties();
165 Factor
JTree::belief( const VarSet
&ns
) const {
166 vector
<Factor
>::const_iterator beta
;
167 for( beta
= _Qb
.begin(); beta
!= _Qb
.end(); beta
++ )
168 if( beta
->vars() >> ns
)
170 if( beta
!= _Qb
.end() )
171 return( beta
->marginal(ns
) );
173 vector
<Factor
>::const_iterator alpha
;
174 for( alpha
= _Qa
.begin(); alpha
!= _Qa
.end(); alpha
++ )
175 if( alpha
->vars() >> ns
)
177 assert( alpha
!= _Qa
.end() );
178 return( alpha
->marginal(ns
) );
183 vector
<Factor
> JTree::beliefs() const {
184 vector
<Factor
> result
;
185 for( size_t beta
= 0; beta
< nrIRs(); beta
++ )
186 result
.push_back( _Qb
[beta
] );
187 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ )
188 result
.push_back( _Qa
[alpha
] );
193 Factor
JTree::belief( const Var
&n
) const {
194 return belief( (VarSet
)n
);
199 void JTree::runHUGIN() {
200 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ )
201 _Qa
[alpha
] = OR(alpha
);
203 for( size_t beta
= 0; beta
< nrIRs(); beta
++ )
204 _Qb
[beta
].fill( 1.0 );
208 for( size_t i
= _RTree
.size(); (i
--) != 0; ) {
209 // Make outer region _RTree[i].n1 consistent with outer region _RTree[i].n2
210 // IR(i) = seperator OR(_RTree[i].n1) && OR(_RTree[i].n2)
211 Factor new_Qb
= _Qa
[_RTree
[i
].n2
].part_sum( IR( i
) );
212 _logZ
+= log(new_Qb
.normalize( Prob::NORMPROB
));
213 _Qa
[_RTree
[i
].n1
] *= new_Qb
.divided_by( _Qb
[i
] );
217 _logZ
+= log(_Qa
[0].normalize( Prob::NORMPROB
) );
219 _logZ
+= log(_Qa
[_RTree
[0].n1
].normalize( Prob::NORMPROB
));
221 // DistributeEvidence
222 for( size_t i
= 0; i
< _RTree
.size(); i
++ ) {
223 // Make outer region _RTree[i].n2 consistent with outer region _RTree[i].n1
224 // IR(i) = seperator OR(_RTree[i].n1) && OR(_RTree[i].n2)
225 Factor new_Qb
= _Qa
[_RTree
[i
].n1
].marginal( IR( i
) );
226 _Qa
[_RTree
[i
].n2
] *= new_Qb
.divided_by( _Qb
[i
] );
231 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ )
232 _Qa
[alpha
].normalize( Prob::NORMPROB
);
236 // Really needs no init! Initial messages can be anything.
237 void JTree::runShaferShenoy() {
240 for( size_t e
= nrIRs(); (e
--) != 0; ) {
241 // send a message from _RTree[e].n2 to _RTree[e].n1
242 // or, actually, from the seperator IR(e) to _RTree[e].n1
244 size_t i
= nbIR(e
)[1].node
; // = _RTree[e].n2
245 size_t j
= nbIR(e
)[0].node
; // = _RTree[e].n1
246 size_t _e
= nbIR(e
)[0].dual
;
249 foreach( const Neighbor
&k
, nbOR(i
) )
251 piet
*= message( i
, k
.iter
);
252 message( j
, _e
) = piet
.part_sum( IR(e
) );
253 _logZ
+= log( message(j
,_e
).normalize( Prob::NORMPROB
) );
257 for( size_t e
= 0; e
< nrIRs(); e
++ ) {
258 size_t i
= nbIR(e
)[0].node
; // = _RTree[e].n1
259 size_t j
= nbIR(e
)[1].node
; // = _RTree[e].n2
260 size_t _e
= nbIR(e
)[1].dual
;
263 foreach( const Neighbor
&k
, nbOR(i
) )
265 piet
*= message( i
, k
.iter
);
266 message( j
, _e
) = piet
.marginal( IR(e
) );
270 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ ) {
271 Factor piet
= OR(alpha
);
272 foreach( const Neighbor
&k
, nbOR(alpha
) )
273 piet
*= message( alpha
, k
.iter
);
275 _logZ
+= log( piet
.normalize( Prob::NORMPROB
) );
277 } else if( alpha
== nbIR(0)[0].node
/*_RTree[0].n1*/ ) {
278 _logZ
+= log( piet
.normalize( Prob::NORMPROB
) );
281 _Qa
[alpha
] = piet
.normalized( Prob::NORMPROB
);
284 // Only for logZ (and for belief)...
285 for( size_t beta
= 0; beta
< nrIRs(); beta
++ )
286 _Qb
[beta
] = _Qa
[nbIR(beta
)[0].node
].marginal( IR(beta
) );
290 double JTree::run() {
291 if( props
.updates
== Properties::UpdateType::HUGIN
)
293 else if( props
.updates
== Properties::UpdateType::SHSH
)
299 Complex
JTree::logZ() const {
301 for( size_t beta
= 0; beta
< nrIRs(); beta
++ )
302 sum
+= Complex(IR(beta
).c()) * _Qb
[beta
].entropy();
303 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ ) {
304 sum
+= Complex(OR(alpha
).c()) * _Qa
[alpha
].entropy();
305 sum
+= (OR(alpha
).log0() * _Qa
[alpha
]).totalSum();
312 size_t JTree::findEfficientTree( const VarSet
& ns
, DEdgeVec
&Tree
, size_t PreviousRoot
) const {
313 // find new root clique (the one with maximal statespace overlap with ns)
314 size_t maxval
= 0, maxalpha
= 0;
315 for( size_t alpha
= 0; alpha
< nrORs(); alpha
++ ) {
316 size_t val
= (ns
& OR(alpha
).vars()).states();
323 // for( size_t e = 0; e < _RTree.size(); e++ )
324 // cout << OR(_RTree[e].n1).vars() << "->" << OR(_RTree[e].n2).vars() << ", ";
328 for( DEdgeVec::const_iterator e
= _RTree
.begin(); e
!= _RTree
.end(); e
++ )
329 oldTree
.insert( UEdge(e
->n1
, e
->n2
) );
330 DEdgeVec newTree
= GrowRootedTree( oldTree
, maxalpha
);
331 // cout << ns << ": ";
332 // for( size_t e = 0; e < newTree.size(); e++ )
333 // cout << OR(newTree[e].n1).vars() << "->" << OR(newTree[e].n2).vars() << ", ";
336 // identify subtree that contains variables of ns which are not in the new root
337 VarSet nsrem
= ns
/ OR(maxalpha
).vars();
338 // cout << "nsrem:" << nsrem << endl;
340 // for each variable in ns that is not in the root clique
341 for( VarSet::const_iterator n
= nsrem
.begin(); n
!= nsrem
.end(); n
++ ) {
342 // find first occurence of *n in the tree, which is closest to the root
344 for( ; e
!= newTree
.size(); e
++ ) {
345 if( OR(newTree
[e
].n2
).vars().contains( *n
) )
348 assert( e
!= newTree
.size() );
350 // track-back path to root and add edges to subTree
351 subTree
.insert( newTree
[e
] );
352 size_t pos
= newTree
[e
].n1
;
354 if( newTree
[e
-1].n2
== pos
) {
355 subTree
.insert( newTree
[e
-1] );
356 pos
= newTree
[e
-1].n1
;
359 if( PreviousRoot
!= (size_t)-1 && PreviousRoot
!= maxalpha
) {
360 // find first occurence of PreviousRoot in the tree, which is closest to the new root
362 for( ; e
!= newTree
.size(); e
++ ) {
363 if( newTree
[e
].n2
== PreviousRoot
)
366 assert( e
!= newTree
.size() );
368 // track-back path to root and add edges to subTree
369 subTree
.insert( newTree
[e
] );
370 size_t pos
= newTree
[e
].n1
;
372 if( newTree
[e
-1].n2
== pos
) {
373 subTree
.insert( newTree
[e
-1] );
374 pos
= newTree
[e
-1].n1
;
377 // cout << "subTree: " << endl;
378 // for( set<DEdge>::const_iterator sTi = subTree.begin(); sTi != subTree.end(); sTi++ )
379 // cout << OR(sTi->n1).vars() << "->" << OR(sTi->n2).vars() << ", ";
382 // Resulting Tree is a reordered copy of newTree
383 // First add edges in subTree to Tree
385 for( DEdgeVec::const_iterator e
= newTree
.begin(); e
!= newTree
.end(); e
++ )
386 if( subTree
.count( *e
) ) {
387 Tree
.push_back( *e
);
388 // cout << OR(e->n1).vars() << "->" << OR(e->n2).vars() << ", ";
391 // Then add edges pointing away from nsrem
393 /* for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
394 for( set<DEdge>::const_iterator sTi = subTree.begin(); sTi != subTree.end(); sTi++ )
396 if( e->n1 == sTi->n1 || e->n1 == sTi->n2 ||
397 e->n2 == sTi->n1 || e->n2 == sTi->n2 ) {
398 Tree.push_back( *e );
399 // cout << OR(e->n1).vars() << "->" << OR(e->n2).vars() << ", ";
403 /* for( DEdgeVec::const_iterator e = newTree.begin(); e != newTree.end(); e++ )
404 if( find( Tree.begin(), Tree.end(), *e) == Tree.end() ) {
406 for( VarSet::const_iterator n = nsrem.begin(); n != nsrem.end(); n++ )
407 if( (OR(e->n1).vars() && *n) ) {
412 Tree.push_back( *e );
413 cout << OR(e->n1).vars() << "->" << OR(e->n2).vars() << ", ";
417 size_t subTreeSize
= Tree
.size();
418 // Then add remaining edges
419 for( DEdgeVec::const_iterator e
= newTree
.begin(); e
!= newTree
.end(); e
++ )
420 if( find( Tree
.begin(), Tree
.end(), *e
) == Tree
.end() )
421 Tree
.push_back( *e
);
427 // Cutset conditioning
428 // assumes that run() has been called already
429 Factor
JTree::calcMarginal( const VarSet
& ns
) {
430 vector
<Factor
>::const_iterator beta
;
431 for( beta
= _Qb
.begin(); beta
!= _Qb
.end(); beta
++ )
432 if( beta
->vars() >> ns
)
434 if( beta
!= _Qb
.end() )
435 return( beta
->marginal(ns
) );
437 vector
<Factor
>::const_iterator alpha
;
438 for( alpha
= _Qa
.begin(); alpha
!= _Qa
.end(); alpha
++ )
439 if( alpha
->vars() >> ns
)
441 if( alpha
!= _Qa
.end() )
442 return( alpha
->marginal(ns
) );
444 // Find subtree to do efficient inference
446 size_t Tsize
= findEfficientTree( ns
, T
);
448 // Find remaining variables (which are not in the new root)
449 VarSet nsrem
= ns
/ OR(T
.front().n1
).vars();
450 Factor
Pns (ns
, 0.0);
452 // Save _Qa and _Qb on the subtree
453 map
<size_t,Factor
> _Qa_old
;
454 map
<size_t,Factor
> _Qb_old
;
455 vector
<size_t> b(Tsize
, 0);
456 for( size_t i
= Tsize
; (i
--) != 0; ) {
457 size_t alpha1
= T
[i
].n1
;
458 size_t alpha2
= T
[i
].n2
;
460 for( beta
= 0; beta
< nrIRs(); beta
++ )
461 if( UEdge( _RTree
[beta
].n1
, _RTree
[beta
].n2
) == UEdge( alpha1
, alpha2
) )
463 assert( beta
!= nrIRs() );
466 if( !_Qa_old
.count( alpha1
) )
467 _Qa_old
[alpha1
] = _Qa
[alpha1
];
468 if( !_Qa_old
.count( alpha2
) )
469 _Qa_old
[alpha2
] = _Qa
[alpha2
];
470 if( !_Qb_old
.count( beta
) )
471 _Qb_old
[beta
] = _Qb
[beta
];
474 // For all states of nsrem
475 for( State
s(nsrem
); s
.valid(); s
++ ) {
479 for( size_t i
= Tsize
; (i
--) != 0; ) {
480 // Make outer region T[i].n1 consistent with outer region T[i].n2
481 // IR(i) = seperator OR(T[i].n1) && OR(T[i].n2)
483 for( VarSet::const_iterator n
= nsrem
.begin(); n
!= nsrem
.end(); n
++ )
484 if( _Qa
[T
[i
].n2
].vars() >> *n
) {
485 Factor
piet( *n
, 0.0 );
487 _Qa
[T
[i
].n2
] *= piet
;
490 Factor new_Qb
= _Qa
[T
[i
].n2
].part_sum( IR( b
[i
] ) );
491 logZ
+= log(new_Qb
.normalize( Prob::NORMPROB
));
492 _Qa
[T
[i
].n1
] *= new_Qb
.divided_by( _Qb
[b
[i
]] );
495 logZ
+= log(_Qa
[T
[0].n1
].normalize( Prob::NORMPROB
));
497 Factor
piet( nsrem
, 0.0 );
499 Pns
+= piet
* _Qa
[T
[0].n1
].part_sum( ns
/ nsrem
); // OPTIMIZE ME
501 // Restore clamped beliefs
502 for( map
<size_t,Factor
>::const_iterator alpha
= _Qa_old
.begin(); alpha
!= _Qa_old
.end(); alpha
++ )
503 _Qa
[alpha
->first
] = alpha
->second
;
504 for( map
<size_t,Factor
>::const_iterator beta
= _Qb_old
.begin(); beta
!= _Qb_old
.end(); beta
++ )
505 _Qb
[beta
->first
] = beta
->second
;
508 return( Pns
.normalized(Prob::NORMPROB
) );
514 } // end of namespace dai