Merged tests/*, matlab/*, utils/* from SVN head...
[libdai.git] / src / lc.cpp
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 #include <iostream>
23 #include <algorithm>
24 #include <map>
25 #include <set>
26 #include <dai/lc.h>
27 #include <dai/diffs.h>
28 #include <dai/util.h>
29 #include <dai/alldai.h>
30 #include <dai/x2x.h>
31
32
33 namespace dai {
34
35
36 using namespace std;
37
38
39 const char *LC::Name = "LC";
40
41
42 void LC::setProperties( const PropertySet &opts ) {
43 assert( opts.hasKey("tol") );
44 assert( opts.hasKey("maxiter") );
45 assert( opts.hasKey("verbose") );
46 assert( opts.hasKey("cavity") );
47 assert( opts.hasKey("updates") );
48
49 props.tol = opts.getStringAs<double>("tol");
50 props.maxiter = opts.getStringAs<size_t>("maxiter");
51 props.verbose = opts.getStringAs<size_t>("verbose");
52 props.cavity = opts.getStringAs<Properties::CavityType>("cavity");
53 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
54 if( opts.hasKey("cavainame") )
55 props.cavainame = opts.getStringAs<string>("cavainame");
56 if( opts.hasKey("cavaiopts") )
57 props.cavaiopts = opts.getStringAs<PropertySet>("cavaiopts");
58 if( opts.hasKey("reinit") )
59 props.reinit = opts.getStringAs<bool>("reinit");
60 }
61
62
63 PropertySet LC::getProperties() const {
64 PropertySet opts;
65 opts.Set( "tol", props.tol );
66 opts.Set( "maxiter", props.maxiter );
67 opts.Set( "verbose", props.verbose );
68 opts.Set( "cavity", props.cavity );
69 opts.Set( "updates", props.updates );
70 opts.Set( "cavainame", props.cavainame );
71 opts.Set( "cavaiopts", props.cavaiopts );
72 opts.Set( "reinit", props.reinit );
73 return opts;
74 }
75
76
77 string LC::printProperties() const {
78 stringstream s( stringstream::out );
79 s << "[";
80 s << "tol=" << props.tol << ",";
81 s << "maxiter=" << props.maxiter << ",";
82 s << "verbose=" << props.verbose << ",";
83 s << "cavity=" << props.cavity << ",";
84 s << "updates=" << props.updates << ",";
85 s << "cavainame=" << props.cavainame << ",";
86 s << "cavaiopts=" << props.cavaiopts << ",";
87 s << "reinit=" << props.reinit << "]";
88 return s.str();
89 }
90
91
92 LC::LC( const FactorGraph & fg, const PropertySet &opts ) : DAIAlgFG(fg), _pancakes(), _cavitydists(), _phis(), _beliefs(), props(), maxdiff(0.0) {
93 setProperties( opts );
94
95 // create pancakes
96 _pancakes.resize(nrVars());
97
98 // create cavitydists
99 for( size_t i=0; i < nrVars(); i++ )
100 _cavitydists.push_back(Factor(delta(i)));
101
102 // create phis
103 _phis.reserve( nrVars() );
104 for( size_t i = 0; i < nrVars(); i++ ) {
105 _phis.push_back( vector<Factor>() );
106 _phis[i].reserve( nbV(i).size() );
107 foreach( const Neighbor &I, nbV(i) )
108 _phis[i].push_back( Factor( factor(I).vars() / var(i) ) );
109 }
110
111 // create beliefs
112 for( size_t i=0; i < nrVars(); i++ )
113 _beliefs.push_back(Factor(var(i)));
114 }
115
116
117 string LC::identify() const {
118 return string(Name) + printProperties();
119 }
120
121
122 void LC::CalcBelief (size_t i) {
123 _beliefs[i] = _pancakes[i].marginal(var(i));
124 }
125
126
127 double LC::CalcCavityDist (size_t i, const std::string &name, const PropertySet &opts) {
128 Factor Bi;
129 double maxdiff = 0;
130
131 if( props.verbose >= 2 )
132 cout << "Initing cavity " << var(i) << "(" << delta(i).size() << " vars, " << delta(i).states() << " states)" << endl;
133
134 if( props.cavity == Properties::CavityType::UNIFORM )
135 Bi = Factor(delta(i));
136 else {
137 InfAlg *cav = newInfAlg( name, *this, opts );
138 cav->makeCavity( i );
139
140 if( props.cavity == Properties::CavityType::FULL )
141 Bi = calcMarginal( *cav, cav->fg().delta(i), props.reinit );
142 else if( props.cavity == Properties::CavityType::PAIR )
143 Bi = calcMarginal2ndO( *cav, cav->fg().delta(i), props.reinit );
144 else if( props.cavity == Properties::CavityType::PAIR2 ) {
145 vector<Factor> pairbeliefs = calcPairBeliefsNew( *cav, cav->fg().delta(i), props.reinit );
146 for( size_t ij = 0; ij < pairbeliefs.size(); ij++ )
147 Bi *= pairbeliefs[ij];
148 }
149 maxdiff = cav->maxDiff();
150 delete cav;
151 }
152 Bi.normalize( Prob::NORMPROB );
153 _cavitydists[i] = Bi;
154
155 return maxdiff;
156 }
157
158
159 double LC::InitCavityDists( const std::string &name, const PropertySet &opts ) {
160 double tic = toc();
161
162 if( props.verbose >= 1 ) {
163 cout << "LC::InitCavityDists: ";
164 if( props.cavity == Properties::CavityType::UNIFORM )
165 cout << "Using uniform initial cavity distributions" << endl;
166 else if( props.cavity == Properties::CavityType::FULL )
167 cout << "Using full " << name << opts << "...";
168 else if( props.cavity == Properties::CavityType::PAIR )
169 cout << "Using pairwise " << name << opts << "...";
170 else if( props.cavity == Properties::CavityType::PAIR2 )
171 cout << "Using pairwise(new) " << name << opts << "...";
172 }
173
174 double maxdiff = 0.0;
175 for( size_t i = 0; i < nrVars(); i++ ) {
176 double md = CalcCavityDist(i, name, opts);
177 if( md > maxdiff )
178 maxdiff = md;
179 }
180 init();
181
182 if( props.verbose >= 1 ) {
183 cout << "used " << toc() - tic << " clocks." << endl;
184 }
185
186 return maxdiff;
187 }
188
189
190 long LC::SetCavityDists( std::vector<Factor> &Q ) {
191 if( props.verbose >= 1 )
192 cout << "LC::SetCavityDists: Setting initial cavity distributions" << endl;
193 if( Q.size() != nrVars() )
194 return -1;
195 for( size_t i = 0; i < nrVars(); i++ ) {
196 if( _cavitydists[i].vars() != Q[i].vars() ) {
197 return i+1;
198 } else
199 _cavitydists[i] = Q[i];
200 }
201 init();
202 return 0;
203 }
204
205
206 void LC::init() {
207 for( size_t i = 0; i < nrVars(); ++i )
208 foreach( const Neighbor &I, nbV(i) )
209 if( props.updates == Properties::UpdateType::SEQRND )
210 _phis[i][I.iter].randomize();
211 else
212 _phis[i][I.iter].fill(1.0);
213 for( size_t i = 0; i < nrVars(); i++ ) {
214 _pancakes[i] = _cavitydists[i];
215
216 foreach( const Neighbor &I, nbV(i) ) {
217 _pancakes[i] *= factor(I);
218 if( props.updates == Properties::UpdateType::SEQRND )
219 _pancakes[i] *= _phis[i][I.iter];
220 }
221
222 _pancakes[i].normalize( Prob::NORMPROB );
223
224 CalcBelief(i);
225 }
226 }
227
228
229 Factor LC::NewPancake (size_t i, size_t _I, bool & hasNaNs) {
230 size_t I = nbV(i)[_I];
231 Factor piet = _pancakes[i];
232
233 // recalculate _pancake[i]
234 VarSet Ivars = factor(I).vars();
235 Factor A_I;
236 for( VarSet::const_iterator k = Ivars.begin(); k != Ivars.end(); k++ )
237 if( var(i) != *k )
238 A_I *= (_pancakes[findVar(*k)] * factor(I).inverse()).partSum( Ivars / var(i) );
239 if( Ivars.size() > 1 )
240 A_I ^= (1.0 / (Ivars.size() - 1));
241 Factor A_Ii = (_pancakes[i] * factor(I).inverse() * _phis[i][_I].inverse()).partSum( Ivars / var(i) );
242 Factor quot = A_I.divided_by(A_Ii);
243
244 piet *= quot.divided_by( _phis[i][_I] ).normalized( Prob::NORMPROB );
245 _phis[i][_I] = quot.normalized( Prob::NORMPROB );
246
247 piet.normalize( Prob::NORMPROB );
248
249 if( piet.hasNaNs() ) {
250 cout << "LC::NewPancake(" << i << ", " << _I << "): has NaNs!" << endl;
251 hasNaNs = true;
252 }
253
254 return piet;
255 }
256
257
258 double LC::run() {
259 if( props.verbose >= 1 )
260 cout << "Starting " << identify() << "...";
261 if( props.verbose >= 2 )
262 cout << endl;
263
264 double tic = toc();
265 Diffs diffs(nrVars(), 1.0);
266
267 double md = InitCavityDists( props.cavainame, props.cavaiopts );
268 if( md > maxdiff )
269 maxdiff = md;
270
271 vector<Factor> old_beliefs;
272 for(size_t i=0; i < nrVars(); i++ )
273 old_beliefs.push_back(belief(i));
274
275 bool hasNaNs = false;
276 for( size_t i=0; i < nrVars(); i++ )
277 if( _pancakes[i].hasNaNs() ) {
278 hasNaNs = true;
279 break;
280 }
281 if( hasNaNs ) {
282 cout << "LC::run: initial _pancakes has NaNs!" << endl;
283 return -1.0;
284 }
285
286 size_t nredges = nrEdges();
287 vector<Edge> update_seq;
288 update_seq.reserve( nredges );
289 for( size_t i = 0; i < nrVars(); ++i )
290 foreach( const Neighbor &I, nbV(i) )
291 update_seq.push_back( Edge( i, I.iter ) );
292
293 size_t iter = 0;
294
295 // do several passes over the network until maximum number of iterations has
296 // been reached or until the maximum belief difference is smaller than tolerance
297 for( iter=0; iter < props.maxiter && diffs.maxDiff() > props.tol; iter++ ) {
298 // Sequential updates
299 if( props.updates == Properties::UpdateType::SEQRND )
300 random_shuffle( update_seq.begin(), update_seq.end() );
301
302 for( size_t t=0; t < nredges; t++ ) {
303 size_t i = update_seq[t].first;
304 size_t _I = update_seq[t].second;
305 _pancakes[i] = NewPancake( i, _I, hasNaNs);
306 if( hasNaNs )
307 return -1.0;
308 CalcBelief( i );
309 }
310
311 // compare new beliefs with old ones
312 for(size_t i=0; i < nrVars(); i++ ) {
313 diffs.push( dist( belief(i), old_beliefs[i], Prob::DISTLINF ) );
314 old_beliefs[i] = belief(i);
315 }
316
317 if( props.verbose >= 3 )
318 cout << "LC::run: maxdiff " << diffs.maxDiff() << " after " << iter+1 << " passes" << endl;
319 }
320
321 if( diffs.maxDiff() > maxdiff )
322 maxdiff = diffs.maxDiff();
323
324 if( props.verbose >= 1 ) {
325 if( diffs.maxDiff() > props.tol ) {
326 if( props.verbose == 1 )
327 cout << endl;
328 cout << "LC::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " clocks)...final maxdiff:" << diffs.maxDiff() << endl;
329 } else {
330 if( props.verbose >= 2 )
331 cout << "LC::run: ";
332 cout << "converged in " << iter << " passes (" << toc() - tic << " clocks)." << endl;
333 }
334 }
335
336 return diffs.maxDiff();
337 }
338
339
340 } // end of namespace dai