Improved HAK (added 'maxtime' property)
[libdai.git] / src / gibbs.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2008 Frederik Eaton [frederik at ofb dot net]
8 * Copyright (C) 2008-2010 Joris Mooij [joris dot mooij at libdai dot org]
9 */
10
11
12 #include <iostream>
13 #include <sstream>
14 #include <map>
15 #include <set>
16 #include <algorithm>
17 #include <dai/gibbs.h>
18 #include <dai/util.h>
19 #include <dai/properties.h>
20
21
22 namespace dai {
23
24
25 using namespace std;
26
27
28 const char *Gibbs::Name = "GIBBS";
29
30
31 void Gibbs::setProperties( const PropertySet &opts ) {
32 DAI_ASSERT( opts.hasKey("maxiter") );
33 props.maxiter = opts.getStringAs<size_t>("maxiter");
34
35 if( opts.hasKey("restart") )
36 props.restart = opts.getStringAs<size_t>("restart");
37 else
38 props.restart = props.maxiter;
39 if( opts.hasKey("burnin") )
40 props.burnin = opts.getStringAs<size_t>("burnin");
41 else
42 props.burnin = 0;
43 if( opts.hasKey("maxtime") )
44 props.maxtime = opts.getStringAs<Real>("maxtime");
45 else
46 props.maxtime = INFINITY;
47 if( opts.hasKey("verbose") )
48 props.verbose = opts.getStringAs<size_t>("verbose");
49 else
50 props.verbose = 0;
51 }
52
53
54 PropertySet Gibbs::getProperties() const {
55 PropertySet opts;
56 opts.set( "maxiter", props.maxiter );
57 opts.set( "maxtime", props.maxtime );
58 opts.set( "restart", props.restart );
59 opts.set( "burnin", props.burnin );
60 opts.set( "verbose", props.verbose );
61 return opts;
62 }
63
64
65 string Gibbs::printProperties() const {
66 stringstream s( stringstream::out );
67 s << "[";
68 s << "maxiter=" << props.maxiter << ",";
69 s << "maxtime=" << props.maxtime << ",";
70 s << "restart=" << props.restart << ",";
71 s << "burnin=" << props.burnin << ",";
72 s << "verbose=" << props.verbose << "]";
73 return s.str();
74 }
75
76
77 void Gibbs::construct() {
78 _sample_count = 0;
79
80 _var_counts.clear();
81 _var_counts.reserve( nrVars() );
82 for( size_t i = 0; i < nrVars(); i++ )
83 _var_counts.push_back( _count_t( var(i).states(), 0 ) );
84
85 _factor_counts.clear();
86 _factor_counts.reserve( nrFactors() );
87 for( size_t I = 0; I < nrFactors(); I++ )
88 _factor_counts.push_back( _count_t( factor(I).nrStates(), 0 ) );
89
90 _iters = 0;
91
92 _state.clear();
93 _state.resize( nrVars(), 0 );
94
95 _max_state.clear();
96 _max_state.resize( nrVars(), 0 );
97
98 _max_score = logScore( _max_state );
99 }
100
101
102 void Gibbs::updateCounts() {
103 _sample_count++;
104 for( size_t i = 0; i < nrVars(); i++ )
105 _var_counts[i][_state[i]]++;
106 for( size_t I = 0; I < nrFactors(); I++ )
107 _factor_counts[I][getFactorEntry(I)]++;
108 Real score = logScore( _state );
109 if( score > _max_score ) {
110 _max_state = _state;
111 _max_score = score;
112 }
113 }
114
115
116 size_t Gibbs::getFactorEntry( size_t I ) {
117 size_t f_entry = 0;
118 for( int _j = nbF(I).size() - 1; _j >= 0; _j-- ) {
119 // note that iterating over nbF(I) yields the same ordering
120 // of variables as iterating over factor(I).vars()
121 size_t j = nbF(I)[_j];
122 f_entry *= var(j).states();
123 f_entry += _state[j];
124 }
125 return f_entry;
126 }
127
128
129 size_t Gibbs::getFactorEntryDiff( size_t I, size_t i ) {
130 size_t skip = 1;
131 for( size_t _j = 0; _j < nbF(I).size(); _j++ ) {
132 // note that iterating over nbF(I) yields the same ordering
133 // of variables as iterating over factor(I).vars()
134 size_t j = nbF(I)[_j];
135 if( i == j )
136 break;
137 else
138 skip *= var(j).states();
139 }
140 return skip;
141 }
142
143
144 Prob Gibbs::getVarDist( size_t i ) {
145 DAI_ASSERT( i < nrVars() );
146 size_t i_states = var(i).states();
147 Prob i_given_MB( i_states, 1.0 );
148
149 // use Markov blanket of var(i) to calculate distribution
150 foreach( const Neighbor &I, nbV(i) ) {
151 const Factor &f_I = factor(I);
152 size_t I_skip = getFactorEntryDiff( I, i );
153 size_t I_entry = getFactorEntry(I) - (_state[i] * I_skip);
154 for( size_t st_i = 0; st_i < i_states; st_i++ ) {
155 i_given_MB.set( st_i, i_given_MB[st_i] * f_I[I_entry] );
156 I_entry += I_skip;
157 }
158 }
159
160 if( i_given_MB.sum() == 0.0 )
161 // If no state of i is allowed, use uniform distribution
162 // FIXME is that indeed the right thing to do?
163 i_given_MB = Prob( i_states );
164 else
165 i_given_MB.normalize();
166 return i_given_MB;
167 }
168
169
170 void Gibbs::resampleVar( size_t i ) {
171 _state[i] = getVarDist(i).draw();
172 }
173
174
175 void Gibbs::randomizeState() {
176 for( size_t i = 0; i < nrVars(); i++ )
177 _state[i] = rnd( var(i).states() );
178 }
179
180
181 void Gibbs::init() {
182 _sample_count = 0;
183 for( size_t i = 0; i < nrVars(); i++ )
184 fill( _var_counts[i].begin(), _var_counts[i].end(), 0 );
185 for( size_t I = 0; I < nrFactors(); I++ )
186 fill( _factor_counts[I].begin(), _factor_counts[I].end(), 0 );
187 _iters = 0;
188 }
189
190
191 Real Gibbs::run() {
192 if( props.verbose >= 1 )
193 cerr << "Starting " << identify() << "...";
194 if( props.verbose >= 3 )
195 cerr << endl;
196
197 double tic = toc();
198
199 for( ; _iters < props.maxiter && (toc() - tic) < props.maxtime; _iters++ ) {
200 if( (_iters % props.restart) == 0 )
201 randomizeState();
202 for( size_t i = 0; i < nrVars(); i++ )
203 resampleVar( i );
204 if( (_iters % props.restart) > props.burnin )
205 updateCounts();
206 }
207
208 if( props.verbose >= 3 ) {
209 for( size_t i = 0; i < nrVars(); i++ ) {
210 cerr << "Belief for variable " << var(i) << ": " << beliefV(i) << endl;
211 cerr << "Counts for variable " << var(i) << ": " << Prob( _var_counts[i] ) << endl;
212 }
213 }
214
215 if( props.verbose >= 3 )
216 cerr << Name << "::run: ran " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
217
218 if( _iters == 0 )
219 return INFINITY;
220 else
221 return std::pow( _iters, -0.5 );
222 }
223
224
225 Factor Gibbs::beliefV( size_t i ) const {
226 if( _sample_count == 0 )
227 return Factor( var(i) );
228 else
229 return Factor( var(i), _var_counts[i] ).normalized();
230 }
231
232
233 Factor Gibbs::beliefF( size_t I ) const {
234 if( _sample_count == 0 )
235 return Factor( factor(I).vars() );
236 else
237 return Factor( factor(I).vars(), _factor_counts[I] ).normalized();
238 }
239
240
241 vector<Factor> Gibbs::beliefs() const {
242 vector<Factor> result;
243 for( size_t i = 0; i < nrVars(); ++i )
244 result.push_back( beliefV(i) );
245 for( size_t I = 0; I < nrFactors(); ++I )
246 result.push_back( beliefF(I) );
247 return result;
248 }
249
250
251 Factor Gibbs::belief( const VarSet &ns ) const {
252 if( ns.size() == 0 )
253 return Factor();
254 else if( ns.size() == 1 )
255 return beliefV( findVar( *(ns.begin()) ) );
256 else {
257 size_t I;
258 for( I = 0; I < nrFactors(); I++ )
259 if( factor(I).vars() >> ns )
260 break;
261 if( I == nrFactors() )
262 DAI_THROW(BELIEF_NOT_AVAILABLE);
263 return beliefF(I).marginal(ns);
264 }
265 }
266
267
268 std::vector<size_t> getGibbsState( const FactorGraph &fg, size_t iters ) {
269 PropertySet gibbsProps;
270 gibbsProps.set( "maxiter", iters );
271 gibbsProps.set( "burnin", size_t(0) );
272 gibbsProps.set( "verbose", size_t(0) );
273 Gibbs gibbs( fg, gibbsProps );
274 gibbs.run();
275 return gibbs.state();
276 }
277
278
279 } // end of namespace dai