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