libDAI
factorgraph.h
Go to the documentation of this file.
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 
11 
12 
13 #ifndef __defined_libdai_factorgraph_h
14 #define __defined_libdai_factorgraph_h
15 
16 
17 #include <iostream>
18 #include <map>
19 #include <dai/bipgraph.h>
20 #include <dai/graph.h>
21 #include <dai/factor.h>
22 
23 
24 namespace dai {
25 
26 
28 
65 class FactorGraph {
66  private:
70  std::vector<Var> _vars;
72  std::vector<Factor> _factors;
74  std::map<size_t,Factor> _backup;
75 
76  public:
78 
79  FactorGraph() : _G(), _vars(), _factors(), _backup() {}
81 
83  FactorGraph( const std::vector<Factor>& P );
84 
86 
90  template<typename FactorInputIterator, typename VarInputIterator>
91  FactorGraph(FactorInputIterator facBegin, FactorInputIterator facEnd, VarInputIterator varBegin, VarInputIterator varEnd, size_t nrFacHint = 0, size_t nrVarHint = 0 );
92 
94  virtual ~FactorGraph() {}
95 
97  virtual FactorGraph* clone() const { return new FactorGraph(*this); }
99 
101 
102  const Var& var( size_t i ) const {
104  DAI_DEBASSERT( i < nrVars() );
105  return _vars[i];
106  }
107 
109  const std::vector<Var>& vars() const { return _vars; }
110 
112  const Factor& factor( size_t I ) const {
113  DAI_DEBASSERT( I < nrFactors() );
114  return _factors[I];
115  }
117  const std::vector<Factor>& factors() const { return _factors; }
118 
120  const Neighbors& nbV( size_t i ) const { return _G.nb1(i); }
122  const Neighbors& nbF( size_t I ) const { return _G.nb2(I); }
124  const Neighbor& nbV( size_t i, size_t _I ) const { return _G.nb1(i)[_I]; }
126  const Neighbor& nbF( size_t I, size_t _i ) const { return _G.nb2(I)[_i]; }
128 
130 
131  const BipartiteGraph& bipGraph() const { return _G; }
134  size_t nrVars() const { return vars().size(); }
136  size_t nrFactors() const { return factors().size(); }
138 
140  size_t nrEdges() const { return _G.nrEdges(); }
141 
143 
146  size_t findVar( const Var& n ) const {
147  size_t i = find( vars().begin(), vars().end(), n ) - vars().begin();
148  if( i == nrVars() )
149  DAI_THROW(OBJECT_NOT_FOUND);
150  return i;
151  }
152 
154 
157  SmallSet<size_t> findVars( const VarSet& ns ) const {
158  SmallSet<size_t> result;
159  for( VarSet::const_iterator n = ns.begin(); n != ns.end(); n++ )
160  result.insert( findVar( *n ) );
161  return result;
162  }
163 
165 
168  size_t findFactor( const VarSet& ns ) const {
169  size_t I;
170  for( I = 0; I < nrFactors(); I++ )
171  if( factor(I).vars() == ns )
172  break;
173  if( I == nrFactors() )
174  DAI_THROW(OBJECT_NOT_FOUND);
175  return I;
176  }
177 
179  VarSet inds2vars( const std::vector<size_t>& inds ) const {
180  VarSet vs;
181  for( std::vector<size_t>::const_iterator it = inds.begin(); it != inds.end(); it++ )
182  vs.insert( var(*it) );
183  return vs;
184  }
185 
187  VarSet Delta( size_t i ) const;
188 
190  VarSet Delta( const VarSet& vs ) const;
191 
193  VarSet delta( size_t i ) const {
194  return( Delta( i ) / var( i ) );
195  }
196 
198  VarSet delta( const VarSet& vs ) const {
199  return Delta( vs ) / vs;
200  }
201 
203  SmallSet<size_t> Deltai( size_t i ) const;
204 
206  SmallSet<size_t> deltai( size_t i ) const {
207  return( Deltai( i ) / i );
208  }
209 
211  bool isConnected() const { return _G.isConnected(); }
212 
214  bool isTree() const { return _G.isTree(); }
215 
217  bool isPairwise() const;
218 
220  bool isBinary() const;
221 
223 
226  GraphAL MarkovGraph() const;
227 
229 
232  bool isMaximal( size_t I ) const;
233 
235 
238  size_t maximalFactor( size_t I ) const;
239 
241 
244  std::vector<VarSet> maximalFactorDomains() const;
245 
247  Real logScore( const std::vector<size_t>& statevec ) const;
249 
251 
252  virtual void setFactor( size_t I, const Factor& newFactor, bool backup = false ) {
254  DAI_ASSERT( newFactor.vars() == factor(I).vars() );
255  if( backup )
256  backupFactor( I );
257  _factors[I] = newFactor;
258  }
259 
261  virtual void setFactors( const std::map<size_t, Factor>& facs, bool backup = false ) {
262  for( std::map<size_t, Factor>::const_iterator fac = facs.begin(); fac != facs.end(); fac++ ) {
263  if( backup )
264  backupFactor( fac->first );
265  setFactor( fac->first, fac->second );
266  }
267  }
268 
270 
272  void backupFactor( size_t I );
273 
275 
277  void restoreFactor( size_t I );
278 
280 
282  virtual void backupFactors( const std::set<size_t>& facs );
283 
285  virtual void restoreFactors();
286 
288 
290  void backupFactors( const VarSet& ns );
291 
293  void restoreFactors( const VarSet& ns );
295 
297 
298  FactorGraph maximalFactors() const;
300 
302 
305  FactorGraph clamped( size_t i, size_t x ) const;
307 
309 
310 
313  virtual void clamp( size_t i, size_t x, bool backup = false );
314 
316 
318  void clampVar( size_t i, const std::vector<size_t>& xis, bool backup = false );
319 
321 
323  void clampFactor( size_t I, const std::vector<size_t>& xIs, bool backup = false );
324 
326 
328  virtual void makeCavity( size_t i, bool backup = false );
329 
331 
333  virtual void makeRegionCavity( std::vector<size_t> facInds, bool backup );
335 
337 
338 
343  virtual void ReadFromFile( const char *filename );
344 
346 
349  virtual void WriteToFile( const char *filename, size_t precision=15 ) const;
350 
352 
354  friend std::ostream& operator<< (std::ostream& os, const FactorGraph& fg );
355 
357 
360  friend std::istream& operator>> (std::istream& is, FactorGraph& fg );
361 
363  virtual void printDot( std::ostream& os ) const;
364 
366  std::string toString() const {
367  std::stringstream ss;
368  ss << *this;
369  return ss.str();
370  }
371 
373  void fromString( const std::string& s ) {
374  std::stringstream ss( s );
375  ss >> *this;
376  }
378 
379  private:
381  void constructGraph( size_t nrEdges );
382 };
383 
384 
385 template<typename FactorInputIterator, typename VarInputIterator>
386 FactorGraph::FactorGraph(FactorInputIterator facBegin, FactorInputIterator facEnd, VarInputIterator varBegin, VarInputIterator varEnd, size_t nrFacHint, size_t nrVarHint ) : _G(), _backup() {
387  // add factors
388  size_t nrEdges = 0;
389  _factors.reserve( nrFacHint );
390  for( FactorInputIterator p2 = facBegin; p2 != facEnd; ++p2 ) {
391  _factors.push_back( *p2 );
392  nrEdges += p2->vars().size();
393  }
394 
395  // add variables
396  _vars.reserve( nrVarHint );
397  for( VarInputIterator p1 = varBegin; p1 != varEnd; ++p1 )
398  _vars.push_back( *p1 );
399 
400  // create graph structure
401  constructGraph( nrEdges );
402 }
403 
404 
411 } // end of namespace dai
412 
413 
414 #endif
SmallSet< size_t > findVars(const VarSet &ns) const
Returns a set of indexes corresponding to a set of variables.
Definition: factorgraph.h:157
std::vector< VarSet > maximalFactorDomains() const
Returns the maximal factor domains in this factorgraph.
Definition: factorgraph.cpp:345
std::vector< Neighbor > Neighbors
Describes the set of neighbors of some node in a graph.
Definition: graph.h:92
const Neighbor & nbF(size_t I, size_t _i) const
Returns constant reference to the _i 'th neighbor of the I 'th factor.
Definition: factorgraph.h:126
bool isBinary() const
Returns true if each variable has only two possible values.
Definition: factorgraph.cpp:477
const VarSet & vars() const
Returns constant reference to variable set (i.e., the variables on which the factor depends) ...
Definition: factor.h:139
SmallSet< size_t > deltai(size_t i) const
Return all the indices of variables that occur in a factor involving the i 'th variable, itself excluded.
Definition: factorgraph.h:206
iterator end()
Returns iterator that points beyond the last element.
Definition: smallset.h:198
std::vector< Var > _vars
Stores the variables.
Definition: factorgraph.h:70
bool isTree() const
Returns true if the factor graph is a tree (i.e., has no cycles and is connected) ...
Definition: factorgraph.h:214
const BipartiteGraph & bipGraph() const
Returns neighborhood structure.
Definition: factorgraph.h:132
bool isTree() const
Returns true if the graph is a tree, i.e., if it is singly connected and connected.
Definition: bipgraph.cpp:230
GraphAL MarkovGraph() const
Constructs the corresponding Markov graph.
Definition: factorgraph.cpp:288
virtual void makeCavity(size_t i, bool backup=false)
Set all factors interacting with the i 'th variable to 1.
Definition: factorgraph.cpp:233
VarSet delta(size_t i) const
Return all variables that occur in a factor involving the i 'th variable, itself excluded.
Definition: factorgraph.h:193
const Neighbor & nb1(size_t i1, size_t _i2) const
Returns constant reference to the _i2 'th neighbor of node i1 of type 1.
Definition: bipgraph.h:87
Represents a factor graph.
Definition: factorgraph.h:65
iterator begin()
Returns iterator that points to the first element.
Definition: smallset.h:193
size_t maximalFactor(size_t I) const
Returns the index of a maximal factor that contains the I 'th factor.
Definition: factorgraph.cpp:322
SmallSet & insert(const T &t)
Inserts t into *this.
Definition: smallset.h:80
double Real
Real number (alias for double, which could be changed to long double if necessary) ...
Definition: util.h:98
size_t nrEdges() const
Calculates the number of edges, time complexity: O(nrNodes1())
Definition: bipgraph.h:227
bool isConnected() const
Returns true if the factor graph is connected.
Definition: factorgraph.h:211
Represents a (probability) factor.
Definition: factor.h:55
const Var & var(size_t i) const
Returns constant reference the i 'th variable.
Definition: factorgraph.h:103
Represents the neighborhood structure of nodes in an undirected, bipartite graph. ...
Definition: bipgraph.h:45
BipartiteGraph _G
Stores the neighborhood structure.
Definition: factorgraph.h:68
VarSet inds2vars(const std::vector< size_t > &inds) const
Returns the VarSet corresponding to a vector of variable indices.
Definition: factorgraph.h:179
virtual ~FactorGraph()
Destructor.
Definition: factorgraph.h:94
virtual void ReadFromFile(const char *filename)
Reads a factor graph from a file.
Definition: factorgraph.cpp:250
VarSet Delta(size_t i) const
Return all variables that occur in a factor involving the i 'th variable, itself included.
Definition: factorgraph.cpp:203
size_t findVar(const Var &n) const
Returns the index of a particular variable.
Definition: factorgraph.h:146
void restoreFactor(size_t I)
Restores the I 'th factor from the backup (it should be backed up first)
Definition: factorgraph.cpp:426
SmallSet< size_t > Deltai(size_t i) const
Return all the indices of variables that occur in a factor involving the i 'th variable, itself included.
Definition: factorgraph.cpp:222
bool isMaximal(size_t I) const
Returns whether the I 'th factor is maximal.
Definition: factorgraph.cpp:299
virtual void clamp(size_t i, size_t x, bool backup=false)
Clamp the i 'th variable to value x (i.e. multiply with a Kronecker delta )
Definition: factorgraph.cpp:375
std::vector< Var >::const_iterator const_iterator
Constant iterator over the elements.
Definition: smallset.h:182
const Factor & factor(size_t I) const
Returns constant reference to I 'th factor.
Definition: factorgraph.h:112
void clampFactor(size_t I, const std::vector< size_t > &xIs, bool backup=false)
Clamp a factor in a factor graph to have one out of a list of values.
Definition: factorgraph.cpp:405
virtual void restoreFactors()
Restore all factors to the backup copies.
Definition: factorgraph.cpp:456
friend std::istream & operator>>(std::istream &is, FactorGraph &fg)
Reads a factor graph from an input stream.
Definition: factorgraph.cpp:100
const Neighbor & nb2(size_t i2, size_t _i1) const
Returns constant reference to the _i1 'th neighbor of node i2 of type 2.
Definition: bipgraph.h:100
Represents a set of variables.
Definition: varset.h:94
size_t nrVars() const
Returns number of variables.
Definition: factorgraph.h:134
VarSet delta(const VarSet &vs) const
Return all variables that occur in a factor involving some variable in vs, vs itself excluded...
Definition: factorgraph.h:198
const Neighbor & nbV(size_t i, size_t _I) const
Returns constant reference to the _I 'th neighbor of the i 'th variable.
Definition: factorgraph.h:124
std::vector< Factor > _factors
Stores the factors.
Definition: factorgraph.h:72
friend std::ostream & operator<<(std::ostream &os, const FactorGraph &fg)
Writes a factor graph to an output stream.
Definition: factorgraph.cpp:73
virtual FactorGraph * clone() const
Virtual copy constructor.
Definition: factorgraph.h:97
void clampVar(size_t i, const std::vector< size_t > &xis, bool backup=false)
Clamp a variable in a factor graph to have one out of a list of values.
Definition: factorgraph.cpp:389
std::map< size_t, Factor > _backup
Stores backups of some factors.
Definition: factorgraph.h:74
const std::vector< Var > & vars() const
Returns constant reference to all variables.
Definition: factorgraph.h:109
bool isPairwise() const
Returns true if each factor depends on at most two variables.
Definition: factorgraph.cpp:468
virtual void WriteToFile(const char *filename, size_t precision=15) const
Writes a factor graph to a file.
Definition: factorgraph.cpp:261
Defines the GraphAL class, which represents an undirected graph as an adjacency list.
const Neighbors & nbV(size_t i) const
Returns constant reference to neighbors of the i 'th variable.
Definition: factorgraph.h:120
Describes the neighbor relationship of two nodes in a graph.
Definition: graph.h:73
size_t findFactor(const VarSet &ns) const
Returns index of the first factor that depends on the variables.
Definition: factorgraph.h:168
FactorGraph maximalFactors() const
Returns a copy of *this, where all factors that are subsumed by some larger factor are merged with th...
Definition: factorgraph.cpp:518
virtual void backupFactors(const std::set< size_t > &facs)
Backup the factors specified by indices in facs.
Definition: factorgraph.cpp:462
virtual void makeRegionCavity(std::vector< size_t > facInds, bool backup)
Set all factors indexed by facInds to 1.
Definition: factorgraph.cpp:242
FactorGraph clamped(size_t i, size_t x) const
Returns a copy of *this, where the i 'th variable has been clamped to value x.
Definition: factorgraph.cpp:486
Represents a discrete random variable.
Definition: var.h:37
Namespace for libDAI.
Definition: alldai.cpp:16
void backupFactor(size_t I)
Makes a backup of the I 'th factor.
Definition: factorgraph.cpp:418
const Neighbors & nbF(size_t I) const
Returns constant reference to neighbors of the I 'th factor.
Definition: factorgraph.h:122
#define DAI_ASSERT(condition)
Assertion mechanism, similar to the standard assert() macro. It is always active, even if NDEBUG is d...
Definition: exceptions.h:60
Defines TFactor<> and Factor classes which represent factors in probability distributions.
#define DAI_DEBASSERT(x)
Assertion mechanism similar to DAI_ASSERT which is only active if DAI_DEBUG is defined.
Definition: exceptions.h:65
virtual void setFactors(const std::map< size_t, Factor > &facs, bool backup=false)
Set the contents of all factors as specified by facs and make a backup of the old contents if backup ...
Definition: factorgraph.h:261
Represents the neighborhood structure of nodes in an undirected graph.
Definition: graph.h:114
std::string toString() const
Formats a factor graph as a string.
Definition: factorgraph.h:366
Defines the BipartiteGraph class, which represents a bipartite graph.
virtual void printDot(std::ostream &os) const
Writes a factor graph to a GraphViz .dot file.
Definition: factorgraph.cpp:273
virtual void setFactor(size_t I, const Factor &newFactor, bool backup=false)
Set the content of the I 'th factor and make a backup of its old content if backup == true...
Definition: factorgraph.h:253
void constructGraph(size_t nrEdges)
Part of constructors (creates edges, neighbors and adjacency matrix)
Definition: factorgraph.cpp:51
size_t nrFactors() const
Returns number of factors.
Definition: factorgraph.h:136
bool isConnected() const
Returns true if the graph is connected.
Definition: bipgraph.cpp:157
FactorGraph()
Default constructor.
Definition: factorgraph.h:80
Real logScore(const std::vector< size_t > &statevec) const
Evaluates the log score (i.e., minus the energy) of the joint configuration statevec.
Definition: factorgraph.cpp:358
size_t nrEdges() const
Calculates number of edges.
Definition: factorgraph.h:140
const std::vector< Factor > & factors() const
Returns constant reference to all factors.
Definition: factorgraph.h:117
void fromString(const std::string &s)
Reads a factor graph from a string.
Definition: factorgraph.h:373