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