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
30 #include <dai/factorgraph.h>
40 FactorGraph::FactorGraph( const std::vector
<Factor
> &P
) : G(), _undoProbs(), _normtype(Prob::NORMPROB
) {
41 // add factors, obtain variables
43 factors
.reserve( P
.size() );
45 for( vector
<Factor
>::const_iterator p2
= P
.begin(); p2
!= P
.end(); p2
++ ) {
46 factors
.push_back( *p2
);
47 copy( p2
->vars().begin(), p2
->vars().end(), inserter( _vars
, _vars
.begin() ) );
48 nrEdges
+= p2
->vars().size();
52 vars
.reserve( _vars
.size() );
53 for( set
<Var
>::const_iterator p1
= _vars
.begin(); p1
!= _vars
.end(); p1
++ )
54 vars
.push_back( *p1
);
56 // create graph structure
57 createGraph( nrEdges
);
61 /// Part of constructors (creates edges, neighbours and adjacency matrix)
62 void FactorGraph::createGraph( size_t nrEdges
) {
63 // create a mapping for indices
64 hash_map
<size_t, size_t> hashmap
;
66 for( size_t i
= 0; i
< vars
.size(); i
++ )
67 hashmap
[var(i
).label()] = i
;
71 edges
.reserve( nrEdges
);
72 for( size_t i2
= 0; i2
< nrFactors(); i2
++ ) {
73 const VarSet
& ns
= factor(i2
).vars();
74 for( VarSet::const_iterator q
= ns
.begin(); q
!= ns
.end(); q
++ )
75 edges
.push_back( Edge(hashmap
[q
->label()], i2
) );
78 // create bipartite graph
79 G
.create( nrVars(), nrFactors(), edges
.begin(), edges
.end() );
83 ostream
& operator << (ostream
& os
, const FactorGraph
& fg
) {
84 os
<< fg
.nrFactors() << endl
;
86 for( size_t I
= 0; I
< fg
.nrFactors(); I
++ ) {
88 os
<< fg
.factor(I
).vars().size() << endl
;
89 for( VarSet::const_iterator i
= fg
.factor(I
).vars().begin(); i
!= fg
.factor(I
).vars().end(); i
++ )
90 os
<< i
->label() << " ";
92 for( VarSet::const_iterator i
= fg
.factor(I
).vars().begin(); i
!= fg
.factor(I
).vars().end(); i
++ )
93 os
<< i
->states() << " ";
95 size_t nr_nonzeros
= 0;
96 for( size_t k
= 0; k
< fg
.factor(I
).states(); k
++ )
97 if( fg
.factor(I
)[k
] != 0.0 )
99 os
<< nr_nonzeros
<< endl
;
100 for( size_t k
= 0; k
< fg
.factor(I
).states(); k
++ )
101 if( fg
.factor(I
)[k
] != 0.0 ) {
103 sprintf(buf
,"%18.14g", fg
.factor(I
)[k
]);
104 os
<< k
<< " " << buf
<< endl
;
112 istream
& operator >> (istream
& is
, FactorGraph
& fg
) {
116 vector
<Factor
> factors
;
120 while( (is
.peek()) == '#' )
124 throw "ReadFromFile: unable to read number of Factors";
126 cout
<< "Reading " << nr_f
<< " factors..." << endl
;
130 throw "ReadFromFile: empty line expected";
132 for( size_t I
= 0; I
< nr_f
; I
++ ) {
134 cout
<< "Reading factor " << I
<< "..." << endl
;
136 while( (is
.peek()) == '#' )
140 cout
<< " nr_members: " << nr_members
<< endl
;
143 for( size_t mi
= 0; mi
< nr_members
; mi
++ ) {
145 while( (is
.peek()) == '#' )
148 labels
.push_back(mi_label
);
152 copy (labels
.begin(), labels
.end(), ostream_iterator
<int>(cout
, " "));
157 for( size_t mi
= 0; mi
< nr_members
; mi
++ ) {
159 while( (is
.peek()) == '#' )
162 dims
.push_back(mi_dim
);
165 cout
<< " dimensions: ";
166 copy (dims
.begin(), dims
.end(), ostream_iterator
<int>(cout
, " "));
172 for( size_t mi
= 0; mi
< nr_members
; mi
++ )
173 I_vars
|= Var(labels
[mi
], dims
[mi
]);
174 factors
.push_back(Factor(I_vars
,0.0));
176 // calculate permutation sigma (internally, members are sorted)
177 vector
<size_t> sigma(nr_members
,0);
178 VarSet::iterator j
= I_vars
.begin();
179 for( size_t mi
= 0; mi
< nr_members
; mi
++,j
++ ) {
180 long search_for
= j
->label();
181 vector
<long>::iterator j_loc
= find(labels
.begin(),labels
.end(),search_for
);
182 sigma
[mi
] = j_loc
- labels
.begin();
186 copy( sigma
.begin(), sigma
.end(), ostream_iterator
<int>(cout
," "));
190 // calculate multindices
191 Permute
permindex( dims
, sigma
);
195 while( (is
.peek()) == '#' )
199 cout
<< " nonzeroes: " << nr_nonzeros
<< endl
;
200 for( size_t k
= 0; k
< nr_nonzeros
; k
++ ) {
203 while( (is
.peek()) == '#' )
206 while( (is
.peek()) == '#' )
210 // store value, but permute indices first according
211 // to internal representation
212 factors
.back()[permindex
.convert_linear_index( li
)] = val
;
217 cout
<< "factors:" << endl
;
218 copy(factors
.begin(), factors
.end(), ostream_iterator
<Factor
>(cout
,"\n"));
221 fg
= FactorGraph(factors
);
230 VarSet
FactorGraph::delta( unsigned i
) const {
231 // calculate Markov Blanket
233 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
234 foreach( const Neighbor
&j
, nbF(I
) ) // for all neighboring variables j of I
242 VarSet
FactorGraph::Delta( unsigned i
) const {
243 return( delta(i
) | var(i
) );
247 void FactorGraph::makeCavity( unsigned i
) {
248 // fills all Factors that include var(i) with ones
249 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
250 factor(I
).fill( 1.0 );
254 bool FactorGraph::hasNegatives() const {
256 for( size_t I
= 0; I
< nrFactors() && !result
; I
++ )
257 if( factor(I
).hasNegatives() )
263 long FactorGraph::ReadFromFile(const char *filename
) {
265 infile
.open (filename
);
266 if (infile
.is_open()) {
271 cout
<< "ERROR OPENING FILE" << endl
;
277 long FactorGraph::WriteToFile(const char *filename
) const {
279 outfile
.open (filename
);
280 if (outfile
.is_open()) {
290 cout
<< "ERROR OPENING FILE" << endl
;
296 long FactorGraph::WriteToDotFile(const char *filename
) const {
298 outfile
.open (filename
);
299 if (outfile
.is_open()) {
301 outfile
<< "graph G {" << endl
;
302 outfile
<< "graph[size=\"9,9\"];" << endl
;
303 outfile
<< "node[shape=circle,width=0.4,fixedsize=true];" << endl
;
304 for( size_t i
= 0; i
< nrVars(); i
++ )
305 outfile
<< "\tx" << var(i
).label() << ";" << endl
;
306 outfile
<< "node[shape=box,style=filled,color=lightgrey,width=0.3,height=0.3,fixedsize=true];" << endl
;
307 for( size_t I
= 0; I
< nrFactors(); I
++ )
308 outfile
<< "\tp" << I
<< ";" << endl
;
309 for( size_t i
= 0; i
< nrVars(); i
++ )
310 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
311 outfile
<< "\tx" << var(i
).label() << " -- p" << I
<< ";" << endl
;
312 outfile
<< "}" << endl
;
320 cout
<< "ERROR OPENING FILE" << endl
;
326 bool hasShortLoops( const vector
<Factor
> &P
) {
328 vector
<Factor
>::const_iterator I
, J
;
329 for( I
= P
.begin(); I
!= P
.end(); I
++ ) {
332 for( ; J
!= P
.end(); J
++ )
333 if( (I
->vars() & J
->vars()).size() >= 2 ) {
344 void RemoveShortLoops(vector
<Factor
> &P
) {
348 vector
<Factor
>::iterator I
, J
;
349 for( I
= P
.begin(); I
!= P
.end(); I
++ ) {
352 for( ; J
!= P
.end(); J
++ )
353 if( (I
->vars() & J
->vars()).size() >= 2 ) {
361 cout
<< "Merging factors " << I
->vars() << " and " << J
->vars() << endl
;
369 vector
<VarSet
> FactorGraph::Cliques() const {
370 vector
<VarSet
> result
;
372 for( size_t I
= 0; I
< nrFactors(); I
++ ) {
374 for( size_t J
= 0; (J
< nrFactors()) && maximal
; J
++ )
375 if( (factor(J
).vars() >> factor(I
).vars()) && !(factor(J
).vars() == factor(I
).vars()) )
379 result
.push_back( factor(I
).vars() );
386 void FactorGraph::clamp( const Var
& n
, size_t i
) {
387 assert( i
<= n
.states() );
389 // Multiply each factor that contains the variable with a delta function
391 Factor
delta_n_i(n
,0.0);
394 // For all factors that contain n
395 for( size_t I
= 0; I
< nrFactors(); I
++ )
396 if( factor(I
).vars().contains( n
) )
397 // Multiply it with a delta function
398 factor(I
) *= delta_n_i
;
404 void FactorGraph::saveProb( size_t I
) {
405 map
<size_t,Prob
>::iterator it
= _undoProbs
.find( I
);
406 if( it
!= _undoProbs
.end() )
407 cout
<< "FactorGraph::saveProb: WARNING: _undoProbs[I] already defined!" << endl
;
408 _undoProbs
[I
] = factor(I
).p();
412 void FactorGraph::undoProb( size_t I
) {
413 map
<size_t,Prob
>::iterator it
= _undoProbs
.find( I
);
414 if( it
!= _undoProbs
.end() ) {
415 factor(I
).p() = (*it
).second
;
416 _undoProbs
.erase(it
);
421 void FactorGraph::saveProbs( const VarSet
&ns
) {
422 if( !_undoProbs
.empty() )
423 cout
<< "FactorGraph::saveProbs: WARNING: _undoProbs not empy!" << endl
;
424 for( size_t I
= 0; I
< nrFactors(); I
++ )
425 if( factor(I
).vars().intersects( ns
) )
426 _undoProbs
[I
] = factor(I
).p();
430 void FactorGraph::undoProbs( const VarSet
&ns
) {
431 for( map
<size_t,Prob
>::iterator uI
= _undoProbs
.begin(); uI
!= _undoProbs
.end(); ) {
432 if( factor((*uI
).first
).vars().intersects( ns
) ) {
433 // cout << "undoing " << factor((*uI).first).vars() << endl;
434 // cout << "from " << factor((*uI).first).p() << " to " << (*uI).second << endl;
435 factor((*uI
).first
).p() = (*uI
).second
;
436 _undoProbs
.erase(uI
++);
443 } // end of namespace dai