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>
32 #include <dai/exceptions.h>
41 FactorGraph::FactorGraph( const std::vector
<Factor
> &P
) : G(), _backup() {
42 // add factors, obtain variables
44 _factors
.reserve( P
.size() );
46 for( vector
<Factor
>::const_iterator p2
= P
.begin(); p2
!= P
.end(); p2
++ ) {
47 _factors
.push_back( *p2
);
48 copy( p2
->vars().begin(), p2
->vars().end(), inserter( _vars
, _vars
.begin() ) );
49 nrEdges
+= p2
->vars().size();
53 vars
.reserve( _vars
.size() );
54 for( set
<Var
>::const_iterator p1
= _vars
.begin(); p1
!= _vars
.end(); p1
++ )
55 vars
.push_back( *p1
);
57 // create graph structure
58 constructGraph( nrEdges
);
62 /// Part of constructors (creates edges, neighbours and adjacency matrix)
63 void FactorGraph::constructGraph( size_t nrEdges
) {
64 // create a mapping for indices
65 hash_map
<size_t, size_t> hashmap
;
67 for( size_t i
= 0; i
< vars
.size(); i
++ )
68 hashmap
[var(i
).label()] = i
;
72 edges
.reserve( nrEdges
);
73 for( size_t i2
= 0; i2
< nrFactors(); i2
++ ) {
74 const VarSet
& ns
= factor(i2
).vars();
75 for( VarSet::const_iterator q
= ns
.begin(); q
!= ns
.end(); q
++ )
76 edges
.push_back( Edge(hashmap
[q
->label()], i2
) );
79 // create bipartite graph
80 G
.construct( nrVars(), nrFactors(), edges
.begin(), edges
.end() );
84 ostream
& operator << (ostream
& os
, const FactorGraph
& fg
) {
85 os
<< fg
.nrFactors() << endl
;
87 for( size_t I
= 0; I
< fg
.nrFactors(); I
++ ) {
89 os
<< fg
.factor(I
).vars().size() << endl
;
90 for( VarSet::const_iterator i
= fg
.factor(I
).vars().begin(); i
!= fg
.factor(I
).vars().end(); i
++ )
91 os
<< i
->label() << " ";
93 for( VarSet::const_iterator i
= fg
.factor(I
).vars().begin(); i
!= fg
.factor(I
).vars().end(); i
++ )
94 os
<< i
->states() << " ";
96 size_t nr_nonzeros
= 0;
97 for( size_t k
= 0; k
< fg
.factor(I
).states(); k
++ )
98 if( fg
.factor(I
)[k
] != 0.0 )
100 os
<< nr_nonzeros
<< endl
;
101 for( size_t k
= 0; k
< fg
.factor(I
).states(); k
++ )
102 if( fg
.factor(I
)[k
] != 0.0 ) {
104 sprintf(buf
,"%18.14g", fg
.factor(I
)[k
]);
105 os
<< k
<< " " << buf
<< endl
;
113 istream
& operator >> (istream
& is
, FactorGraph
& fg
) {
121 while( (is
.peek()) == '#' )
125 DAI_THROW(INVALID_FACTORGRAPH_FILE
);
127 cout
<< "Reading " << nr_Factors
<< " factors..." << endl
;
131 DAI_THROW(INVALID_FACTORGRAPH_FILE
);
133 map
<long,size_t> vardims
;
134 for( size_t I
= 0; I
< nr_Factors
; I
++ ) {
136 cout
<< "Reading factor " << I
<< "..." << endl
;
138 while( (is
.peek()) == '#' )
142 cout
<< " nr_members: " << nr_members
<< endl
;
145 for( size_t mi
= 0; mi
< nr_members
; mi
++ ) {
147 while( (is
.peek()) == '#' )
150 labels
.push_back(mi_label
);
153 cout
<< " labels: " << labels
<< endl
;
156 for( size_t mi
= 0; mi
< nr_members
; mi
++ ) {
158 while( (is
.peek()) == '#' )
161 dims
.push_back(mi_dim
);
164 cout
<< " dimensions: " << dims
<< endl
;
168 for( size_t mi
= 0; mi
< nr_members
; mi
++ ) {
169 map
<long,size_t>::iterator vdi
= vardims
.find( labels
[mi
] );
170 if( vdi
!= vardims
.end() ) {
171 // check whether dimensions are consistent
172 if( vdi
->second
!= dims
[mi
] )
173 DAI_THROW(INVALID_FACTORGRAPH_FILE
);
175 vardims
[labels
[mi
]] = dims
[mi
];
176 I_vars
|= Var(labels
[mi
], dims
[mi
]);
178 facs
.push_back( Factor( I_vars
, 0.0 ) );
180 // calculate permutation sigma (internally, members are sorted)
181 vector
<size_t> sigma(nr_members
,0);
182 VarSet::iterator j
= I_vars
.begin();
183 for( size_t mi
= 0; mi
< nr_members
; mi
++,j
++ ) {
184 long search_for
= j
->label();
185 vector
<long>::iterator j_loc
= find(labels
.begin(),labels
.end(),search_for
);
186 sigma
[mi
] = j_loc
- labels
.begin();
189 cout
<< " sigma: " << sigma
<< endl
;
191 // calculate multindices
192 Permute
permindex( dims
, sigma
);
196 while( (is
.peek()) == '#' )
200 cout
<< " nonzeroes: " << nr_nonzeros
<< endl
;
201 for( size_t k
= 0; k
< nr_nonzeros
; k
++ ) {
204 while( (is
.peek()) == '#' )
207 while( (is
.peek()) == '#' )
211 // store value, but permute indices first according
212 // to internal representation
213 facs
.back()[permindex
.convert_linear_index( li
)] = val
;
218 cout
<< "factors:" << facs
<< endl
;
220 fg
= FactorGraph(facs
);
229 VarSet
FactorGraph::delta( unsigned i
) const {
230 return( Delta(i
) / var(i
) );
234 VarSet
FactorGraph::Delta( unsigned i
) const {
235 // calculate Markov Blanket
237 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
238 foreach( const Neighbor
&j
, nbF(I
) ) // for all neighboring variables j of I
245 VarSet
FactorGraph::Delta( const VarSet
&ns
) const {
247 for( VarSet::const_iterator n
= ns
.begin(); n
!= ns
.end(); n
++ )
248 result
|= Delta(findVar(*n
));
253 void FactorGraph::makeCavity( unsigned i
, bool backup
) {
254 // fills all Factors that include var(i) with ones
255 map
<size_t,Factor
> newFacs
;
256 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
257 newFacs
[I
] = Factor(factor(I
).vars(), 1.0);
258 setFactors( newFacs
, backup
);
262 void FactorGraph::ReadFromFile( const char *filename
) {
264 infile
.open( filename
);
265 if( infile
.is_open() ) {
269 DAI_THROW(CANNOT_READ_FILE
);
273 void FactorGraph::WriteToFile( const char *filename
) const {
275 outfile
.open( filename
);
276 if( outfile
.is_open() ) {
280 DAI_THROW(CANNOT_WRITE_FILE
);
284 void FactorGraph::printDot( std::ostream
&os
) const {
285 os
<< "graph G {" << endl
;
286 os
<< "node[shape=circle,width=0.4,fixedsize=true];" << endl
;
287 for( size_t i
= 0; i
< nrVars(); i
++ )
288 os
<< "\tv" << var(i
).label() << ";" << endl
;
289 os
<< "node[shape=box,width=0.3,height=0.3,fixedsize=true];" << endl
;
290 for( size_t I
= 0; I
< nrFactors(); I
++ )
291 os
<< "\tf" << I
<< ";" << endl
;
292 for( size_t i
= 0; i
< nrVars(); i
++ )
293 foreach( const Neighbor
&I
, nbV(i
) ) // for all neighboring factors I of i
294 os
<< "\tv" << var(i
).label() << " -- f" << I
<< ";" << endl
;
299 vector
<VarSet
> FactorGraph::Cliques() const {
300 vector
<VarSet
> result
;
302 for( size_t I
= 0; I
< nrFactors(); I
++ ) {
304 for( size_t J
= 0; (J
< nrFactors()) && maximal
; J
++ )
305 if( (factor(J
).vars() >> factor(I
).vars()) && (factor(J
).vars() != factor(I
).vars()) )
309 result
.push_back( factor(I
).vars() );
316 void FactorGraph::clamp( const Var
& n
, size_t i
, bool backup
) {
317 assert( i
<= n
.states() );
319 // Multiply each factor that contains the variable with a delta function
321 Factor
delta_n_i(n
,0.0);
324 map
<size_t, Factor
> newFacs
;
325 // For all factors that contain n
326 for( size_t I
= 0; I
< nrFactors(); I
++ )
327 if( factor(I
).vars().contains( n
) )
328 // Multiply it with a delta function
329 newFacs
[I
] = factor(I
) * delta_n_i
;
330 setFactors( newFacs
, backup
);
336 void FactorGraph::backupFactor( size_t I
) {
337 map
<size_t,Factor
>::iterator it
= _backup
.find( I
);
338 if( it
!= _backup
.end() )
339 DAI_THROW( MULTIPLE_UNDO
);
340 _backup
[I
] = factor(I
);
344 void FactorGraph::restoreFactor( size_t I
) {
345 map
<size_t,Factor
>::iterator it
= _backup
.find( I
);
346 if( it
!= _backup
.end() ) {
347 setFactor(I
, it
->second
);
353 void FactorGraph::backupFactors( const VarSet
&ns
) {
354 for( size_t I
= 0; I
< nrFactors(); I
++ )
355 if( factor(I
).vars().intersects( ns
) )
360 void FactorGraph::restoreFactors( const VarSet
&ns
) {
361 map
<size_t,Factor
> facs
;
362 for( map
<size_t,Factor
>::iterator uI
= _backup
.begin(); uI
!= _backup
.end(); ) {
363 if( factor(uI
->first
).vars().intersects( ns
) ) {
373 void FactorGraph::restoreFactors() {
374 setFactors( _backup
);
378 void FactorGraph::backupFactors( const std::set
<size_t> & facs
) {
379 for( std::set
<size_t>::const_iterator fac
= facs
.begin(); fac
!= facs
.end(); fac
++ )
380 backupFactor( *fac
);
384 bool FactorGraph::isPairwise() const {
385 bool pairwise
= true;
386 for( size_t I
= 0; I
< nrFactors() && pairwise
; I
++ )
387 if( factor(I
).vars().size() > 2 )
393 bool FactorGraph::isBinary() const {
395 for( size_t i
= 0; i
< nrVars() && binary
; i
++ )
396 if( var(i
).states() > 2 )
402 FactorGraph
FactorGraph::clamped( const Var
& v_i
, size_t state
) const {
403 Real zeroth_order
= 1.0;
404 vector
<Factor
> clamped_facs
;
405 for( size_t I
= 0; I
< nrFactors(); I
++ ) {
406 VarSet v_I
= factor(I
).vars();
408 if( v_I
.intersects( v_i
) )
409 new_factor
= factor(I
).slice( v_i
, state
);
411 new_factor
= factor(I
);
413 if( new_factor
.vars().size() != 0 ) {
415 // if it can be merged with a previous one, do that
416 for( J
= 0; J
< clamped_facs
.size(); J
++ )
417 if( clamped_facs
[J
].vars() == new_factor
.vars() ) {
418 clamped_facs
[J
] *= new_factor
;
421 // otherwise, push it back
422 if( J
== clamped_facs
.size() || clamped_facs
.size() == 0 )
423 clamped_facs
.push_back( new_factor
);
425 zeroth_order
*= new_factor
[0];
427 *(clamped_facs
.begin()) *= zeroth_order
;
428 return FactorGraph( clamped_facs
);
432 FactorGraph
FactorGraph::maximalFactors() const {
433 vector
<size_t> maxfac( nrFactors() );
434 map
<size_t,size_t> newindex
;
436 for( size_t I
= 0; I
< nrFactors(); I
++ ) {
438 VarSet maxfacvars
= factor(maxfac
[I
]).vars();
439 for( size_t J
= 0; J
< nrFactors(); J
++ ) {
440 VarSet Jvars
= factor(J
).vars();
441 if( Jvars
>> maxfacvars
&& (Jvars
!= maxfacvars
) ) {
443 maxfacvars
= factor(maxfac
[I
]).vars();
447 newindex
[I
] = nrmax
++;
450 vector
<Factor
> facs( nrmax
);
451 for( size_t I
= 0; I
< nrFactors(); I
++ )
452 facs
[newindex
[maxfac
[I
]]] *= factor(I
);
454 return FactorGraph( facs
.begin(), facs
.end(), vars
.begin(), vars
.end(), facs
.size(), nrVars() );
458 } // end of namespace dai