045a46a20a5b66fb45c489499a5c0b29b6af5daf
[libdai.git] / src / factorgraph.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4 *
5 * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6 */
7
8
9 #include <iostream>
10 #include <iomanip>
11 #include <iterator>
12 #include <map>
13 #include <set>
14 #include <fstream>
15 #include <string>
16 #include <algorithm>
17 #include <functional>
18 #include <dai/factorgraph.h>
19 #include <dai/util.h>
20 #include <dai/exceptions.h>
21 #include <boost/lexical_cast.hpp>
22
23
24 namespace dai {
25
26
27 using namespace std;
28
29
30 FactorGraph::FactorGraph( const std::vector<Factor> &P ) : _G(), _backup() {
31 // add factors, obtain variables
32 set<Var> varset;
33 _factors.reserve( P.size() );
34 size_t nrEdges = 0;
35 for( vector<Factor>::const_iterator p2 = P.begin(); p2 != P.end(); p2++ ) {
36 _factors.push_back( *p2 );
37 copy( p2->vars().begin(), p2->vars().end(), inserter( varset, varset.begin() ) );
38 nrEdges += p2->vars().size();
39 }
40
41 // add vars
42 _vars.reserve( varset.size() );
43 for( set<Var>::const_iterator p1 = varset.begin(); p1 != varset.end(); p1++ )
44 _vars.push_back( *p1 );
45
46 // create graph structure
47 constructGraph( nrEdges );
48 }
49
50
51 void FactorGraph::constructGraph( size_t nrEdges ) {
52 // create a mapping for indices
53 hash_map<size_t, size_t> hashmap;
54
55 for( size_t i = 0; i < vars().size(); i++ )
56 hashmap[var(i).label()] = i;
57
58 // create edge list
59 vector<Edge> edges;
60 edges.reserve( nrEdges );
61 for( size_t i2 = 0; i2 < nrFactors(); i2++ ) {
62 const VarSet& ns = factor(i2).vars();
63 for( VarSet::const_iterator q = ns.begin(); q != ns.end(); q++ )
64 edges.push_back( Edge(hashmap[q->label()], i2) );
65 }
66
67 // create bipartite graph
68 _G.construct( nrVars(), nrFactors(), edges.begin(), edges.end() );
69 }
70
71
72 /// Writes a FactorGraph to an output stream
73 std::ostream& operator<< ( std::ostream &os, const FactorGraph &fg ) {
74 os << fg.nrFactors() << endl;
75
76 for( size_t I = 0; I < fg.nrFactors(); I++ ) {
77 os << endl;
78 os << fg.factor(I).vars().size() << endl;
79 for( VarSet::const_iterator i = fg.factor(I).vars().begin(); i != fg.factor(I).vars().end(); i++ )
80 os << i->label() << " ";
81 os << endl;
82 for( VarSet::const_iterator i = fg.factor(I).vars().begin(); i != fg.factor(I).vars().end(); i++ )
83 os << i->states() << " ";
84 os << endl;
85 size_t nr_nonzeros = 0;
86 for( size_t k = 0; k < fg.factor(I).nrStates(); k++ )
87 if( fg.factor(I)[k] != (Real)0 )
88 nr_nonzeros++;
89 os << nr_nonzeros << endl;
90 for( size_t k = 0; k < fg.factor(I).nrStates(); k++ )
91 if( fg.factor(I)[k] != (Real)0 )
92 os << k << " " << setw(os.precision()+4) << fg.factor(I)[k] << endl;
93 }
94
95 return(os);
96 }
97
98
99 /// Reads a FactorGraph from an input stream
100 std::istream& operator>> ( std::istream& is, FactorGraph &fg ) {
101 long verbose = 0;
102
103 vector<Factor> facs;
104 size_t nr_Factors;
105 string line;
106
107 while( (is.peek()) == '#' )
108 getline(is,line);
109 is >> nr_Factors;
110 if( is.fail() )
111 DAI_THROWE(INVALID_FACTORGRAPH_FILE,"Cannot read number of factors");
112 if( verbose >= 1 )
113 cerr << "Reading " << nr_Factors << " factors..." << endl;
114
115 getline (is,line);
116 if( is.fail() || line.size() > 0 )
117 DAI_THROWE(INVALID_FACTORGRAPH_FILE,"Expecting empty line");
118
119 map<long,size_t> vardims;
120 for( size_t I = 0; I < nr_Factors; I++ ) {
121 if( verbose >= 2 )
122 cerr << "Reading factor " << I << "..." << endl;
123 size_t nr_members;
124 while( (is.peek()) == '#' )
125 getline(is,line);
126 is >> nr_members;
127 if( verbose >= 2 )
128 cerr << " nr_members: " << nr_members << endl;
129
130 vector<long> labels;
131 for( size_t mi = 0; mi < nr_members; mi++ ) {
132 long mi_label;
133 while( (is.peek()) == '#' )
134 getline(is,line);
135 is >> mi_label;
136 labels.push_back(mi_label);
137 }
138 if( verbose >= 2 )
139 cerr << " labels: " << labels << endl;
140
141 vector<size_t> dims;
142 for( size_t mi = 0; mi < nr_members; mi++ ) {
143 size_t mi_dim;
144 while( (is.peek()) == '#' )
145 getline(is,line);
146 is >> mi_dim;
147 dims.push_back(mi_dim);
148 }
149 if( verbose >= 2 )
150 cerr << " dimensions: " << dims << endl;
151
152 // add the Factor
153 vector<Var> Ivars;
154 Ivars.reserve( nr_members );
155 for( size_t mi = 0; mi < nr_members; mi++ ) {
156 map<long,size_t>::iterator vdi = vardims.find( labels[mi] );
157 if( vdi != vardims.end() ) {
158 // check whether dimensions are consistent
159 if( vdi->second != dims[mi] )
160 DAI_THROWE(INVALID_FACTORGRAPH_FILE,"Variable with label " + boost::lexical_cast<string>(labels[mi]) + " has inconsistent dimensions.");
161 } else
162 vardims[labels[mi]] = dims[mi];
163 Ivars.push_back( Var(labels[mi], dims[mi]) );
164 }
165 facs.push_back( Factor( VarSet( Ivars.begin(), Ivars.end(), Ivars.size() ), (Real)0 ) );
166 if( verbose >= 2 )
167 cerr << " vardims: " << vardims << endl;
168
169 // calculate permutation object
170 Permute permindex( Ivars );
171
172 // read values
173 size_t nr_nonzeros;
174 while( (is.peek()) == '#' )
175 getline(is,line);
176 is >> nr_nonzeros;
177 if( verbose >= 2 )
178 cerr << " nonzeroes: " << nr_nonzeros << endl;
179 for( size_t k = 0; k < nr_nonzeros; k++ ) {
180 size_t li;
181 Real val;
182 while( (is.peek()) == '#' )
183 getline(is,line);
184 is >> li;
185 while( (is.peek()) == '#' )
186 getline(is,line);
187 is >> val;
188
189 // store value, but permute indices first according to internal representation
190 facs.back().set( permindex.convertLinearIndex( li ), val );
191 }
192 }
193
194 if( verbose >= 3 )
195 cerr << "factors:" << facs << endl;
196
197 fg = FactorGraph(facs);
198
199 return is;
200 }
201
202
203 VarSet FactorGraph::Delta( size_t i ) const {
204 // calculate Markov Blanket
205 VarSet Del;
206 bforeach( const Neighbor &I, nbV(i) ) // for all neighboring factors I of i
207 bforeach( const Neighbor &j, nbF(I) ) // for all neighboring variables j of I
208 Del |= var(j);
209
210 return Del;
211 }
212
213
214 VarSet FactorGraph::Delta( const VarSet &ns ) const {
215 VarSet result;
216 for( VarSet::const_iterator n = ns.begin(); n != ns.end(); n++ )
217 result |= Delta( findVar(*n) );
218 return result;
219 }
220
221
222 void FactorGraph::makeCavity( size_t i, bool backup ) {
223 // fills all Factors that include var(i) with ones
224 map<size_t,Factor> newFacs;
225 bforeach( const Neighbor &I, nbV(i) ) // for all neighboring factors I of i
226 newFacs[I] = Factor( factor(I).vars(), (Real)1 );
227 setFactors( newFacs, backup );
228 }
229
230
231 void FactorGraph::ReadFromFile( const char *filename ) {
232 ifstream infile;
233 infile.open( filename );
234 if( infile.is_open() ) {
235 infile >> *this;
236 infile.close();
237 } else
238 DAI_THROWE(CANNOT_READ_FILE,"Cannot read from file " + std::string(filename));
239 }
240
241
242 void FactorGraph::WriteToFile( const char *filename, size_t precision ) const {
243 ofstream outfile;
244 outfile.open( filename );
245 if( outfile.is_open() ) {
246 outfile.precision( precision );
247 outfile << *this;
248 outfile.close();
249 } else
250 DAI_THROWE(CANNOT_WRITE_FILE,"Cannot write to file " + std::string(filename));
251 }
252
253
254 void FactorGraph::printDot( std::ostream &os ) const {
255 os << "graph FactorGraph {" << endl;
256 os << "node[shape=circle,width=0.4,fixedsize=true];" << endl;
257 for( size_t i = 0; i < nrVars(); i++ )
258 os << "\tv" << var(i).label() << ";" << endl;
259 os << "node[shape=box,width=0.3,height=0.3,fixedsize=true];" << endl;
260 for( size_t I = 0; I < nrFactors(); I++ )
261 os << "\tf" << I << ";" << endl;
262 for( size_t i = 0; i < nrVars(); i++ )
263 bforeach( const Neighbor &I, nbV(i) ) // for all neighboring factors I of i
264 os << "\tv" << var(i).label() << " -- f" << I << ";" << endl;
265 os << "}" << endl;
266 }
267
268
269 GraphAL FactorGraph::MarkovGraph() const {
270 GraphAL G( nrVars() );
271 for( size_t i = 0; i < nrVars(); i++ )
272 bforeach( const Neighbor &I, nbV(i) )
273 bforeach( const Neighbor &j, nbF(I) )
274 if( i < j )
275 G.addEdge( i, j, true );
276 return G;
277 }
278
279
280 bool FactorGraph::isMaximal( size_t I ) const {
281 const VarSet& I_vars = factor(I).vars();
282 size_t I_size = I_vars.size();
283
284 if( I_size == 0 ) {
285 for( size_t J = 0; J < nrFactors(); J++ )
286 if( J != I )
287 if( factor(J).vars().size() > 0 )
288 return false;
289 return true;
290 } else {
291 bforeach( const Neighbor& i, nbF(I) ) {
292 bforeach( const Neighbor& J, nbV(i) ) {
293 if( J != I )
294 if( (factor(J).vars() >> I_vars) && (factor(J).vars().size() != I_size) )
295 return false;
296 }
297 }
298 return true;
299 }
300 }
301
302
303 size_t FactorGraph::maximalFactor( size_t I ) const {
304 const VarSet& I_vars = factor(I).vars();
305 size_t I_size = I_vars.size();
306
307 if( I_size == 0 ) {
308 for( size_t J = 0; J < nrFactors(); J++ )
309 if( J != I )
310 if( factor(J).vars().size() > 0 )
311 return maximalFactor( J );
312 return I;
313 } else {
314 bforeach( const Neighbor& i, nbF(I) ) {
315 bforeach( const Neighbor& J, nbV(i) ) {
316 if( J != I )
317 if( (factor(J).vars() >> I_vars) && (factor(J).vars().size() != I_size) )
318 return maximalFactor( J );
319 }
320 }
321 return I;
322 }
323 }
324
325
326 vector<VarSet> FactorGraph::maximalFactorDomains() const {
327 vector<VarSet> result;
328
329 for( size_t I = 0; I < nrFactors(); I++ )
330 if( isMaximal( I ) )
331 result.push_back( factor(I).vars() );
332
333 if( result.size() == 0 )
334 result.push_back( VarSet() );
335 return result;
336 }
337
338
339 Real FactorGraph::logScore( const std::vector<size_t>& statevec ) const {
340 // Construct a State object that represents statevec
341 // This decouples the representation of the joint state in statevec from the factor graph
342 map<Var, size_t> statemap;
343 for( size_t i = 0; i < statevec.size(); i++ )
344 statemap[var(i)] = statevec[i];
345 State S(statemap);
346
347 // Evaluate the log probability of the joint configuration in statevec
348 // by summing the log factor entries of the factors that correspond to this joint configuration
349 Real lS = 0.0;
350 for( size_t I = 0; I < nrFactors(); I++ )
351 lS += dai::log( factor(I)[BigInt_size_t(S(factor(I).vars()))] );
352 return lS;
353 }
354
355
356 void FactorGraph::clamp( size_t i, size_t x, bool backup ) {
357 DAI_ASSERT( x <= var(i).states() );
358 Factor mask( var(i), (Real)0 );
359 mask.set( x, (Real)1 );
360
361 map<size_t, Factor> newFacs;
362 bforeach( const Neighbor &I, nbV(i) )
363 newFacs[I] = factor(I) * mask;
364 setFactors( newFacs, backup );
365
366 return;
367 }
368
369
370 void FactorGraph::clampVar( size_t i, const vector<size_t> &is, bool backup ) {
371 Var n = var(i);
372 Factor mask_n( n, (Real)0 );
373
374 bforeach( size_t i, is ) {
375 DAI_ASSERT( i <= n.states() );
376 mask_n.set( i, (Real)1 );
377 }
378
379 map<size_t, Factor> newFacs;
380 bforeach( const Neighbor &I, nbV(i) )
381 newFacs[I] = factor(I) * mask_n;
382 setFactors( newFacs, backup );
383 }
384
385
386 void FactorGraph::clampFactor( size_t I, const vector<size_t> &is, bool backup ) {
387 size_t st = factor(I).nrStates();
388 Factor newF( factor(I).vars(), (Real)0 );
389
390 bforeach( size_t i, is ) {
391 DAI_ASSERT( i <= st );
392 newF.set( i, factor(I)[i] );
393 }
394
395 setFactor( I, newF, backup );
396 }
397
398
399 void FactorGraph::backupFactor( size_t I ) {
400 map<size_t,Factor>::iterator it = _backup.find( I );
401 if( it != _backup.end() )
402 DAI_THROW(MULTIPLE_UNDO);
403 _backup[I] = factor(I);
404 }
405
406
407 void FactorGraph::restoreFactor( size_t I ) {
408 map<size_t,Factor>::iterator it = _backup.find( I );
409 if( it != _backup.end() ) {
410 setFactor(I, it->second);
411 _backup.erase(it);
412 } else
413 DAI_THROW(OBJECT_NOT_FOUND);
414 }
415
416
417 void FactorGraph::backupFactors( const VarSet &ns ) {
418 for( size_t I = 0; I < nrFactors(); I++ )
419 if( factor(I).vars().intersects( ns ) )
420 backupFactor( I );
421 }
422
423
424 void FactorGraph::restoreFactors( const VarSet &ns ) {
425 map<size_t,Factor> facs;
426 for( map<size_t,Factor>::iterator uI = _backup.begin(); uI != _backup.end(); ) {
427 if( factor(uI->first).vars().intersects( ns ) ) {
428 facs.insert( *uI );
429 _backup.erase(uI++);
430 } else
431 uI++;
432 }
433 setFactors( facs );
434 }
435
436
437 void FactorGraph::restoreFactors() {
438 setFactors( _backup );
439 _backup.clear();
440 }
441
442
443 void FactorGraph::backupFactors( const std::set<size_t> & facs ) {
444 for( std::set<size_t>::const_iterator fac = facs.begin(); fac != facs.end(); fac++ )
445 backupFactor( *fac );
446 }
447
448
449 bool FactorGraph::isPairwise() const {
450 bool pairwise = true;
451 for( size_t I = 0; I < nrFactors() && pairwise; I++ )
452 if( factor(I).vars().size() > 2 )
453 pairwise = false;
454 return pairwise;
455 }
456
457
458 bool FactorGraph::isBinary() const {
459 bool binary = true;
460 for( size_t i = 0; i < nrVars() && binary; i++ )
461 if( var(i).states() > 2 )
462 binary = false;
463 return binary;
464 }
465
466
467 FactorGraph FactorGraph::clamped( size_t i, size_t state ) const {
468 Var v = var( i );
469 Real zeroth_order = (Real)1;
470 vector<Factor> clamped_facs;
471 clamped_facs.push_back( createFactorDelta( v, state ) );
472 for( size_t I = 0; I < nrFactors(); I++ ) {
473 VarSet v_I = factor(I).vars();
474 Factor new_factor;
475 if( v_I.intersects( v ) )
476 new_factor = factor(I).slice( v, state );
477 else
478 new_factor = factor(I);
479
480 if( new_factor.vars().size() != 0 ) {
481 size_t J = 0;
482 // if it can be merged with a previous one, do that
483 for( J = 0; J < clamped_facs.size(); J++ )
484 if( clamped_facs[J].vars() == new_factor.vars() ) {
485 clamped_facs[J] *= new_factor;
486 break;
487 }
488 // otherwise, push it back
489 if( J == clamped_facs.size() || clamped_facs.size() == 0 )
490 clamped_facs.push_back( new_factor );
491 } else
492 zeroth_order *= new_factor[0];
493 }
494 *(clamped_facs.begin()) *= zeroth_order;
495 return FactorGraph( clamped_facs );
496 }
497
498
499 FactorGraph FactorGraph::maximalFactors() const {
500 vector<size_t> maxfac( nrFactors() );
501 map<size_t,size_t> newindex;
502 size_t nrmax = 0;
503 for( size_t I = 0; I < nrFactors(); I++ ) {
504 maxfac[I] = I;
505 VarSet maxfacvars = factor(maxfac[I]).vars();
506 for( size_t J = 0; J < nrFactors(); J++ ) {
507 VarSet Jvars = factor(J).vars();
508 if( Jvars >> maxfacvars && (Jvars != maxfacvars) ) {
509 maxfac[I] = J;
510 maxfacvars = factor(maxfac[I]).vars();
511 }
512 }
513 if( maxfac[I] == I )
514 newindex[I] = nrmax++;
515 }
516
517 vector<Factor> facs( nrmax );
518 for( size_t I = 0; I < nrFactors(); I++ )
519 facs[newindex[maxfac[I]]] *= factor(I);
520
521 return FactorGraph( facs.begin(), facs.end(), vars().begin(), vars().end(), facs.size(), nrVars() );
522 }
523
524
525 } // end of namespace dai