Cleaned up some code in TreeEP and JTree
[libdai.git] / src / treeep.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 <fstream>
14 #include <vector>
15 #include <dai/jtree.h>
16 #include <dai/treeep.h>
17 #include <dai/util.h>
18
19
20 namespace dai {
21
22
23 using namespace std;
24
25
26 const char *TreeEP::Name = "TREEEP";
27
28
29 void TreeEP::setProperties( const PropertySet &opts ) {
30 DAI_ASSERT( opts.hasKey("tol") );
31 DAI_ASSERT( opts.hasKey("maxiter") );
32 DAI_ASSERT( opts.hasKey("verbose") );
33 DAI_ASSERT( opts.hasKey("type") );
34
35 props.tol = opts.getStringAs<Real>("tol");
36 props.maxiter = opts.getStringAs<size_t>("maxiter");
37 props.verbose = opts.getStringAs<size_t>("verbose");
38 props.type = opts.getStringAs<Properties::TypeType>("type");
39 }
40
41
42 PropertySet TreeEP::getProperties() const {
43 PropertySet opts;
44 opts.Set( "tol", props.tol );
45 opts.Set( "maxiter", props.maxiter );
46 opts.Set( "verbose", props.verbose );
47 opts.Set( "type", props.type );
48 return opts;
49 }
50
51
52 string TreeEP::printProperties() const {
53 stringstream s( stringstream::out );
54 s << "[";
55 s << "tol=" << props.tol << ",";
56 s << "maxiter=" << props.maxiter << ",";
57 s << "verbose=" << props.verbose << ",";
58 s << "type=" << props.type << "]";
59 return s.str();
60 }
61
62
63 TreeEP::TreeEP( const FactorGraph &fg, const PropertySet &opts ) : JTree(fg, opts("updates",string("HUGIN")), false), _maxdiff(0.0), _iters(0), props(), _Q() {
64 setProperties( opts );
65
66 if( !isConnected() )
67 DAI_THROW(FACTORGRAPH_NOT_CONNECTED);
68
69 if( opts.hasKey("tree") ) {
70 construct( opts.GetAs<RootedTree>("tree") );
71 } else {
72 if( props.type == Properties::TypeType::ORG || props.type == Properties::TypeType::ALT ) {
73 // ORG: construct weighted graph with as weights a crude estimate of the
74 // mutual information between the nodes
75 // ALT: construct weighted graph with as weights an upper bound on the
76 // effective interaction strength between pairs of nodes
77
78 WeightedGraph<Real> wg;
79 for( size_t i = 0; i < nrVars(); ++i ) {
80 Var v_i = var(i);
81 VarSet di = delta(i);
82 for( VarSet::const_iterator j = di.begin(); j != di.end(); j++ )
83 if( v_i < *j ) {
84 VarSet ij(v_i,*j);
85 Factor piet;
86 for( size_t I = 0; I < nrFactors(); I++ ) {
87 VarSet Ivars = factor(I).vars();
88 if( props.type == Properties::TypeType::ORG ) {
89 if( (Ivars == v_i) || (Ivars == *j) )
90 piet *= factor(I);
91 else if( Ivars >> ij )
92 piet *= factor(I).marginal( ij );
93 } else {
94 if( Ivars >> ij )
95 piet *= factor(I);
96 }
97 }
98 if( props.type == Properties::TypeType::ORG ) {
99 if( piet.vars() >> ij ) {
100 piet = piet.marginal( ij );
101 Factor pietf = piet.marginal(v_i) * piet.marginal(*j);
102 wg[UEdge(i,findVar(*j))] = dist( piet, pietf, Prob::DISTKL );
103 } else
104 wg[UEdge(i,findVar(*j))] = 0;
105 } else {
106 wg[UEdge(i,findVar(*j))] = piet.strength(v_i, *j);
107 }
108 }
109 }
110
111 // find maximal spanning tree
112 construct( MaxSpanningTreePrims( wg ) );
113 } else
114 DAI_THROW(UNKNOWN_ENUM_VALUE);
115 }
116 }
117
118
119 void TreeEP::construct( const RootedTree &tree ) {
120 vector<VarSet> cl;
121 for( size_t i = 0; i < tree.size(); i++ )
122 cl.push_back( VarSet( var(tree[i].n1), var(tree[i].n2) ) );
123
124 // If no outer region can be found subsuming that factor, label the
125 // factor as off-tree.
126 JTree::construct( cl, false );
127
128 // Create factor approximations
129 _Q.clear();
130 size_t PreviousRoot = (size_t)-1;
131 // Second repetition: previous root of first off-tree factor should be the root of the last off-tree factor
132 for( size_t repeats = 0; repeats < 2; repeats++ )
133 for( size_t I = 0; I < nrFactors(); I++ )
134 if( offtree(I) ) {
135 // find efficient subtree
136 RootedTree subTree;
137 /*size_t subTreeSize =*/ findEfficientTree( factor(I).vars(), subTree, PreviousRoot );
138 PreviousRoot = subTree[0].n1;
139 //subTree.resize( subTreeSize ); // FIXME
140 //cerr << "subtree " << I << " has size " << subTreeSize << endl;
141 _Q[I] = TreeEPSubTree( subTree, RTree, Qa, Qb, &factor(I) );
142 if( repeats == 1 )
143 break;
144 }
145
146 if( props.verbose >= 3 )
147 cerr << "Resulting regiongraph: " << *this << endl;
148 }
149
150
151 string TreeEP::identify() const {
152 return string(Name) + printProperties();
153 }
154
155
156 void TreeEP::init() {
157 runHUGIN();
158
159 // Init factor approximations
160 for( size_t I = 0; I < nrFactors(); I++ )
161 if( offtree(I) )
162 _Q[I].init();
163 }
164
165
166 Real TreeEP::run() {
167 if( props.verbose >= 1 )
168 cerr << "Starting " << identify() << "...";
169 if( props.verbose >= 3 )
170 cerr << endl;
171
172 double tic = toc();
173
174 vector<Factor> oldBeliefs = beliefs();
175
176 // do several passes over the network until maximum number of iterations has
177 // been reached or until the maximum belief difference is smaller than tolerance
178 Real maxDiff = INFINITY;
179 for( _iters = 0; _iters < props.maxiter && maxDiff > props.tol; _iters++ ) {
180 for( size_t I = 0; I < nrFactors(); I++ )
181 if( offtree(I) ) {
182 _Q[I].InvertAndMultiply( Qa, Qb );
183 _Q[I].HUGIN_with_I( Qa, Qb );
184 _Q[I].InvertAndMultiply( Qa, Qb );
185 }
186
187 // calculate new beliefs and compare with old ones
188 vector<Factor> newBeliefs = beliefs();
189 maxDiff = -INFINITY;
190 for( size_t t = 0; t < oldBeliefs.size(); t++ )
191 maxDiff = std::max( maxDiff, dist( newBeliefs[t], oldBeliefs[t], Prob::DISTLINF ) );
192 swap( newBeliefs, oldBeliefs );
193
194 if( props.verbose >= 3 )
195 cerr << Name << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
196 }
197
198 if( maxDiff > _maxdiff )
199 _maxdiff = maxDiff;
200
201 if( props.verbose >= 1 ) {
202 if( maxDiff > props.tol ) {
203 if( props.verbose == 1 )
204 cerr << endl;
205 cerr << Name << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
206 } else {
207 if( props.verbose >= 3 )
208 cerr << Name << "::run: ";
209 cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
210 }
211 }
212
213 return maxDiff;
214 }
215
216
217 Real TreeEP::logZ() const {
218 Real s = 0.0;
219
220 // entropy of the tree
221 for( size_t beta = 0; beta < nrIRs(); beta++ )
222 s -= Qb[beta].entropy();
223 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
224 s += Qa[alpha].entropy();
225
226 // energy of the on-tree factors
227 for( size_t alpha = 0; alpha < nrORs(); alpha++ )
228 s += (OR(alpha).log(true) * Qa[alpha]).sum();
229
230 // energy of the off-tree factors
231 for( size_t I = 0; I < nrFactors(); I++ )
232 if( offtree(I) )
233 s += (_Q.find(I))->second.logZ( Qa, Qb );
234
235 return s;
236 }
237
238
239 TreeEP::TreeEPSubTree::TreeEPSubTree( const RootedTree &subRTree, const RootedTree &jt_RTree, const std::vector<Factor> &jt_Qa, const std::vector<Factor> &jt_Qb, const Factor *I ) : _Qa(), _Qb(), _RTree(), _a(), _b(), _I(I), _ns(), _nsrem(), _logZ(0.0) {
240 _ns = _I->vars();
241
242 // Make _Qa, _Qb, _a and _b corresponding to the subtree
243 _b.reserve( subRTree.size() );
244 _Qb.reserve( subRTree.size() );
245 _RTree.reserve( subRTree.size() );
246 for( size_t i = 0; i < subRTree.size(); i++ ) {
247 size_t alpha1 = subRTree[i].n1; // old index 1
248 size_t alpha2 = subRTree[i].n2; // old index 2
249 size_t beta; // old sep index
250 for( beta = 0; beta < jt_RTree.size(); beta++ )
251 if( UEdge( jt_RTree[beta].n1, jt_RTree[beta].n2 ) == UEdge( alpha1, alpha2 ) )
252 break;
253 DAI_ASSERT( beta != jt_RTree.size() );
254
255 size_t newalpha1 = find(_a.begin(), _a.end(), alpha1) - _a.begin();
256 if( newalpha1 == _a.size() ) {
257 _Qa.push_back( Factor( jt_Qa[alpha1].vars(), 1.0 ) );
258 _a.push_back( alpha1 ); // save old index in index conversion table
259 }
260
261 size_t newalpha2 = find(_a.begin(), _a.end(), alpha2) - _a.begin();
262 if( newalpha2 == _a.size() ) {
263 _Qa.push_back( Factor( jt_Qa[alpha2].vars(), 1.0 ) );
264 _a.push_back( alpha2 ); // save old index in index conversion table
265 }
266
267 _RTree.push_back( DEdge( newalpha1, newalpha2 ) );
268 _Qb.push_back( Factor( jt_Qb[beta].vars(), 1.0 ) );
269 _b.push_back( beta );
270 }
271
272 // Find remaining variables (which are not in the new root)
273 _nsrem = _ns / _Qa[0].vars();
274 }
275
276
277 void TreeEP::TreeEPSubTree::init() {
278 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ )
279 _Qa[alpha].fill( 1.0 );
280 for( size_t beta = 0; beta < _Qb.size(); beta++ )
281 _Qb[beta].fill( 1.0 );
282 }
283
284
285 void TreeEP::TreeEPSubTree::InvertAndMultiply( const std::vector<Factor> &Qa, const std::vector<Factor> &Qb ) {
286 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ )
287 _Qa[alpha] = Qa[_a[alpha]] / _Qa[alpha];
288
289 for( size_t beta = 0; beta < _Qb.size(); beta++ )
290 _Qb[beta] = Qb[_b[beta]] / _Qb[beta];
291 }
292
293
294 void TreeEP::TreeEPSubTree::HUGIN_with_I( std::vector<Factor> &Qa, std::vector<Factor> &Qb ) {
295 // Backup _Qa and _Qb
296 vector<Factor> _Qa_old(_Qa);
297 vector<Factor> _Qb_old(_Qb);
298
299 // Clear Qa and Qb
300 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ )
301 Qa[_a[alpha]].fill( 0.0 );
302 for( size_t beta = 0; beta < _Qb.size(); beta++ )
303 Qb[_b[beta]].fill( 0.0 );
304
305 // For all states of _nsrem
306 for( State s(_nsrem); s.valid(); s++ ) {
307 // Multiply root with slice of I
308 _Qa[0] *= _I->slice( _nsrem, s );
309
310 // CollectEvidence
311 for( size_t i = _RTree.size(); (i--) != 0; ) {
312 // clamp variables in nsrem
313 for( VarSet::const_iterator n = _nsrem.begin(); n != _nsrem.end(); n++ )
314 if( _Qa[_RTree[i].n2].vars() >> *n ) {
315 Factor delta( *n, 0.0 );
316 delta[s(*n)] = 1.0;
317 _Qa[_RTree[i].n2] *= delta;
318 }
319 Factor new_Qb = _Qa[_RTree[i].n2].marginal( _Qb[i].vars(), false );
320 _Qa[_RTree[i].n1] *= new_Qb / _Qb[i];
321 _Qb[i] = new_Qb;
322 }
323
324 // DistributeEvidence
325 for( size_t i = 0; i < _RTree.size(); i++ ) {
326 Factor new_Qb = _Qa[_RTree[i].n1].marginal( _Qb[i].vars(), false );
327 _Qa[_RTree[i].n2] *= new_Qb / _Qb[i];
328 _Qb[i] = new_Qb;
329 }
330
331 // Store Qa's and Qb's
332 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ )
333 Qa[_a[alpha]].p() += _Qa[alpha].p();
334 for( size_t beta = 0; beta < _Qb.size(); beta++ )
335 Qb[_b[beta]].p() += _Qb[beta].p();
336
337 // Restore _Qa and _Qb
338 _Qa = _Qa_old;
339 _Qb = _Qb_old;
340 }
341
342 // Normalize Qa and Qb
343 _logZ = 0.0;
344 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ ) {
345 _logZ += log(Qa[_a[alpha]].sum());
346 Qa[_a[alpha]].normalize();
347 }
348 for( size_t beta = 0; beta < _Qb.size(); beta++ ) {
349 _logZ -= log(Qb[_b[beta]].sum());
350 Qb[_b[beta]].normalize();
351 }
352 }
353
354
355 Real TreeEP::TreeEPSubTree::logZ( const std::vector<Factor> &Qa, const std::vector<Factor> &Qb ) const {
356 Real s = 0.0;
357 for( size_t alpha = 0; alpha < _Qa.size(); alpha++ )
358 s += (Qa[_a[alpha]] * _Qa[alpha].log(true)).sum();
359 for( size_t beta = 0; beta < _Qb.size(); beta++ )
360 s -= (Qb[_b[beta]] * _Qb[beta].log(true)).sum();
361 return s + _logZ;
362 }
363
364
365 } // end of namespace dai