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