Merged mf.* from SVN head (which implements damping)...
[libdai.git] / include / dai / factorgraph.h
1 /* Copyright (C) 2006-2008 Joris Mooij [j dot mooij at science dot ru dot nl]
2 Radboud University Nijmegen, The Netherlands
3
4 This file is part of libDAI.
5
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.
10
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.
15
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
19 */
20
21
22 #ifndef __defined_libdai_factorgraph_h
23 #define __defined_libdai_factorgraph_h
24
25
26 #include <iostream>
27 #include <map>
28 #include <dai/bipgraph.h>
29 #include <dai/factor.h>
30
31
32 namespace dai {
33
34
35 class FactorGraph {
36 public:
37 BipartiteGraph G;
38 std::vector<Var> vars;
39 typedef BipartiteGraph::Neighbor Neighbor;
40 typedef BipartiteGraph::Neighbors Neighbors;
41 typedef BipartiteGraph::Edge Edge;
42
43 private:
44 std::vector<Factor> _factors;
45 std::map<size_t,Factor> _backup;
46
47 public:
48 /// Default constructor
49 FactorGraph() : G(), vars(), _factors(), _backup() {}
50 /// Copy constructor
51 FactorGraph(const FactorGraph & x) : G(x.G), vars(x.vars), _factors(x._factors), _backup(x._backup) {}
52 /// Construct FactorGraph from vector of Factors
53 FactorGraph(const std::vector<Factor> &P);
54 // Construct a FactorGraph from given factor and variable iterators
55 template<typename FactorInputIterator, typename VarInputIterator>
56 FactorGraph(FactorInputIterator fact_begin, FactorInputIterator fact_end, VarInputIterator var_begin, VarInputIterator var_end, size_t nr_fact_hint = 0, size_t nr_var_hint = 0 );
57
58 /// Assignment operator
59 FactorGraph & operator=(const FactorGraph & x) {
60 if( this != &x ) {
61 G = x.G;
62 vars = x.vars;
63 _factors = x._factors;
64 _backup = x._backup;
65 }
66 return *this;
67 }
68 virtual ~FactorGraph() {}
69
70 /// Create (virtual default constructor)
71 virtual FactorGraph* create() const { return new FactorGraph(*this); }
72
73 /// Clone (virtual copy constructor)
74 virtual FactorGraph* clone() const { return new FactorGraph(); }
75
76 // aliases
77 Var & var(size_t i) { return vars[i]; }
78 /// Get const reference to i'th variable
79 const Var & var(size_t i) const { return vars[i]; }
80 /// Get const reference to I'th factor
81 Factor & factor(size_t I) { return _factors[I]; }
82 /// Get const reference to I'th factor
83 const Factor & factor(size_t I) const { return _factors[I]; }
84 /// Get const reference to all factors
85 const std::vector<Factor> & factors() const { return _factors; }
86
87 /// Get number of variables
88 size_t nrVars() const { return vars.size(); }
89 /// Get number of factors
90 size_t nrFactors() const { return _factors.size(); }
91 size_t nrEdges() const { return G.nrEdges(); }
92
93 /// Provides read access to neighbors of variable
94 const Neighbors & nbV( size_t i ) const { return G.nb1(i); }
95 /// Provides full access to neighbors of variable
96 Neighbors & nbV( size_t i ) { return G.nb1(i); }
97 /// Provides read access to neighbors of factor
98 const Neighbors & nbF( size_t I ) const { return G.nb2(I); }
99 /// Provides full access to neighbors of factor
100 Neighbors & nbF( size_t I ) { return G.nb2(I); }
101 /// Provides read access to neighbor of variable
102 const Neighbor & nbV( size_t i, size_t _I ) const { return G.nb1(i)[_I]; }
103 /// Provides full access to neighbor of variable
104 Neighbor & nbV( size_t i, size_t _I ) { return G.nb1(i)[_I]; }
105 /// Provides read access to neighbor of factor
106 const Neighbor & nbF( size_t I, size_t _i ) const { return G.nb2(I)[_i]; }
107 /// Provides full access to neighbor of factor
108 Neighbor & nbF( size_t I, size_t _i ) { return G.nb2(I)[_i]; }
109
110 /// Get index of variable n
111 size_t findVar( const Var & n ) const {
112 size_t i = find( vars.begin(), vars.end(), n ) - vars.begin();
113 assert( i != nrVars() );
114 return i;
115 }
116
117 /// Get set of indexes for set of variables
118 std::set<size_t> findVars( VarSet &ns ) const {
119 std::set<size_t> indexes;
120 for( VarSet::const_iterator n = ns.begin(); n != ns.end(); n++ )
121 indexes.insert( findVar( *n ) );
122 return indexes;
123 }
124
125 /// Get index of first factor involving ns
126 size_t findFactor(const VarSet &ns) const {
127 size_t I;
128 for( I = 0; I < nrFactors(); I++ )
129 if( factor(I).vars() == ns )
130 break;
131 assert( I != nrFactors() );
132 return I;
133 }
134
135 /// Return all variables that occur in a factor involving the i'th variable, itself included
136 VarSet Delta( unsigned i ) const;
137
138 /// Return all variables that occur in a factor involving some variable in ns, ns itself included
139 VarSet Delta( const VarSet &ns ) const;
140
141 /// Return all variables that occur in a factor involving the i'th variable, n itself excluded
142 VarSet delta( unsigned i ) const;
143
144 /// Return all variables that occur in a factor involving some variable in ns, ns itself excluded
145 VarSet delta( const VarSet & ns ) const {
146 return Delta( ns ) / ns;
147 }
148
149 /// Set the content of the I'th factor and make a backup of its old content if backup == true
150 virtual void setFactor( size_t I, const Factor &newFactor, bool backup = false ) {
151 assert( newFactor.vars() == factor(I).vars() );
152 if( backup )
153 backupFactor( I );
154 _factors[I] = newFactor;
155 }
156
157 /// Set the contents of all factors as specified by facs and make a backup of the old contents if backup == true
158 virtual void setFactors( const std::map<size_t, Factor> & facs, bool backup = false ) {
159 for( std::map<size_t, Factor>::const_iterator fac = facs.begin(); fac != facs.end(); fac++ ) {
160 if( backup )
161 backupFactor( fac->first );
162 setFactor( fac->first, fac->second );
163 }
164 }
165
166 /// Clamp variable n to value i (i.e. multiply with a Kronecker delta \f$\delta_{x_n, i}\f$);
167 /// If backup == true, make a backup of all factors that are changed
168 virtual void clamp( const Var & n, size_t i, bool backup = false );
169
170 /// Set all factors interacting with the i'th variable 1
171 virtual void makeCavity( unsigned i, bool backup = false );
172
173 /// Backup the factors specified by indices in facs
174 virtual void backupFactors( const std::set<size_t> & facs );
175
176 /// Restore all factors to the backup copies
177 virtual void restoreFactors();
178
179 bool isConnected() const { return G.isConnected(); }
180 bool isTree() const { return G.isTree(); }
181
182 friend std::ostream& operator << (std::ostream& os, const FactorGraph& fg);
183 friend std::istream& operator >> (std::istream& is, FactorGraph& fg);
184
185 void ReadFromFile(const char *filename);
186 void WriteToFile(const char *filename) const;
187 void printDot( std::ostream& os ) const;
188
189 std::vector<VarSet> Cliques() const;
190
191 // Clamp variable v_i to value state (i.e. multiply with a Kronecker delta \f$\delta_{x_{v_i},x}\f$);
192 // This version changes the factor graph structure and thus returns a newly constructed FactorGraph
193 // and keeps the current one constant, contrary to clamp()
194 FactorGraph clamped( const Var & v_i, size_t x ) const;
195
196 FactorGraph maximalFactors() const;
197
198 bool isPairwise() const;
199 bool isBinary() const;
200
201 void restoreFactor( size_t I );
202 void backupFactor( size_t I );
203 void restoreFactors( const VarSet &ns );
204 void backupFactors( const VarSet &ns );
205 /// Part of constructors (creates edges, neighbors and adjacency matrix)
206 void constructGraph( size_t nrEdges );
207 };
208
209
210 // assumes that the set of variables in [var_begin,var_end) is the union of the variables in the factors in [fact_begin, fact_end)
211 template<typename FactorInputIterator, typename VarInputIterator>
212 FactorGraph::FactorGraph(FactorInputIterator fact_begin, FactorInputIterator fact_end, VarInputIterator var_begin, VarInputIterator var_end, size_t nr_fact_hint, size_t nr_var_hint ) : G(), _backup() {
213 // add factors
214 size_t nrEdges = 0;
215 _factors.reserve( nr_fact_hint );
216 for( FactorInputIterator p2 = fact_begin; p2 != fact_end; ++p2 ) {
217 _factors.push_back( *p2 );
218 nrEdges += p2->vars().size();
219 }
220
221 // add variables
222 vars.reserve( nr_var_hint );
223 for( VarInputIterator p1 = var_begin; p1 != var_end; ++p1 )
224 vars.push_back( *p1 );
225
226 // create graph structure
227 constructGraph( nrEdges );
228 }
229
230
231 } // end of namespace dai
232
233
234 #endif