Merged tests/*, matlab/*, utils/* from SVN head...
[libdai.git] / tests / test.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 <fstream>
24 #include <map>
25 #include <numeric>
26 #include <cmath>
27 #include <cstdlib>
28 #include <cstring>
29 #include <boost/program_options.hpp>
30 #include <dai/util.h>
31 #include <dai/alldai.h>
32
33
34 using namespace std;
35 using namespace dai;
36 namespace po = boost::program_options;
37
38
39 class TestDAI {
40 protected:
41 InfAlg *obj;
42 string name;
43 vector<double> err;
44
45 public:
46 vector<Factor> q;
47 double logZ;
48 double maxdiff;
49 double time;
50 size_t iters;
51 bool has_logZ;
52 bool has_maxdiff;
53 bool has_iters;
54
55 TestDAI( const FactorGraph &fg, const string &_name, const PropertySet &opts ) : obj(NULL), name(_name), err(), q(), logZ(0.0), maxdiff(0.0), time(0), iters(0U), has_logZ(false), has_maxdiff(false), has_iters(false) {
56 double tic = toc();
57 if( name == "LDPC" ) {
58 double zero[2] = {1.0, 0.0};
59 q.clear();
60 for( size_t i = 0; i < fg.nrVars(); i++ )
61 q.push_back( Factor(Var(i,2), zero) );
62 logZ = NAN;
63 maxdiff = 0.0;
64 iters = 1;
65 } else
66 obj = newInfAlg( name, fg, opts );
67 time += toc() - tic;
68 }
69
70 ~TestDAI() {
71 if( obj != NULL )
72 delete obj;
73 }
74
75 string identify() {
76 if( obj != NULL )
77 return obj->identify();
78 else
79 return "NULL";
80 }
81
82 vector<Factor> allBeliefs() {
83 vector<Factor> result;
84 for( size_t i = 0; i < obj->fg().nrVars(); i++ )
85 result.push_back( obj->belief( obj->fg().var(i) ) );
86 return result;
87 }
88
89 void doDAI() {
90 double tic = toc();
91 if( obj != NULL ) {
92 obj->init();
93 obj->run();
94 time += toc() - tic;
95 try {
96 logZ = obj->logZ();
97 has_logZ = true;
98 } catch( Exception &e ) {
99 has_logZ = false;
100 }
101 try {
102 maxdiff = obj->maxDiff();
103 has_maxdiff = true;
104 } catch( Exception &e ) {
105 has_maxdiff = false;
106 }
107 has_iters = false;
108 iters = 0;
109 q = allBeliefs();
110 };
111 }
112
113 void calcErrs( const TestDAI &x ) {
114 err.clear();
115 err.reserve( q.size() );
116 for( size_t i = 0; i < q.size(); i++ )
117 err.push_back( dist( q[i], x.q[i], Prob::DISTTV ) );
118 }
119
120 void calcErrs( const vector<Factor> &x ) {
121 err.clear();
122 err.reserve( q.size() );
123 for( size_t i = 0; i < q.size(); i++ )
124 err.push_back( dist( q[i], x[i], Prob::DISTTV ) );
125 }
126
127 double maxErr() {
128 return( *max_element( err.begin(), err.end() ) );
129 }
130
131 double avgErr() {
132 return( accumulate( err.begin(), err.end(), 0.0 ) / err.size() );
133 }
134 };
135
136
137 pair<string, PropertySet> parseMethod( const string &_s, const map<string,string> & aliases ) {
138 // s = first part of _s, until '['
139 string::size_type pos = _s.find_first_of('[');
140 string s;
141 if( pos == string::npos )
142 s = _s;
143 else
144 s = _s.substr(0,pos);
145
146 // if the first part is an alias, substitute
147 if( aliases.find(s) != aliases.end() )
148 s = aliases.find(s)->second;
149
150 // attach second part, merging properties if necessary
151 if( pos != string::npos ) {
152 if( s.at(s.length()-1) == ']' ) {
153 s = s.erase(s.length()-1,1) + ',' + _s.substr(pos+1);
154 } else
155 s = s + _s.substr(pos);
156 }
157
158 pair<string, PropertySet> result;
159 string & name = result.first;
160 PropertySet & opts = result.second;
161
162 pos = s.find_first_of('[');
163 if( pos == string::npos )
164 throw "Malformed method";
165 name = s.substr( 0, pos );
166 size_t n = 0;
167 for( ; strlen( DAINames[n] ) != 0; n++ )
168 if( name == DAINames[n] )
169 break;
170 if( strlen( DAINames[n] ) == 0 && (name != "LDPC") )
171 DAI_THROW(UNKNOWN_DAI_ALGORITHM);
172
173 stringstream ss;
174 ss << s.substr(pos,s.length());
175 ss >> opts;
176
177 return result;
178 }
179
180
181 double clipdouble( double x, double minabs ) {
182 if( fabs(x) < minabs )
183 return minabs;
184 else
185 return x;
186 }
187
188
189 int main( int argc, char *argv[] ) {
190 try {
191 string filename;
192 string aliases;
193 vector<string> methods;
194 double tol;
195 size_t maxiter;
196 size_t verbose;
197 bool marginals = false;
198 bool report_time = true;
199
200 po::options_description opts_required("Required options");
201 opts_required.add_options()
202 ("filename", po::value< string >(&filename), "Filename of FactorGraph")
203 ("methods", po::value< vector<string> >(&methods)->multitoken(), "DAI methods to test")
204 ;
205
206 po::options_description opts_optional("Allowed options");
207 opts_optional.add_options()
208 ("help", "produce help message")
209 ("aliases", po::value< string >(&aliases), "Filename for aliases")
210 ("tol", po::value< double >(&tol), "Override tolerance")
211 ("maxiter", po::value< size_t >(&maxiter), "Override maximum number of iterations")
212 ("verbose", po::value< size_t >(&verbose), "Override verbosity")
213 ("marginals", po::value< bool >(&marginals), "Output single node marginals?")
214 ("report-time", po::value< bool >(&report_time), "Report calculation time")
215 ;
216
217 po::options_description cmdline_options;
218 cmdline_options.add(opts_required).add(opts_optional);
219
220 po::variables_map vm;
221 po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
222 po::notify(vm);
223
224 if( vm.count("help") || !(vm.count("filename") && vm.count("methods")) ) {
225 cout << "Reads factorgraph <filename.fg> and performs the approximate" << endl;
226 cout << "inference algorithms <method*>, reporting calculation time, max and average" << endl;
227 cout << "error and relative logZ error (comparing with the results of" << endl;
228 cout << "<method0>, the base method, for which one can use JTREE_HUGIN)." << endl << endl;
229 cout << opts_required << opts_optional << endl;
230 return 1;
231 }
232
233 // Read aliases
234 map<string,string> Aliases;
235 if( !aliases.empty() ) {
236 ifstream infile;
237 infile.open (aliases.c_str());
238 if (infile.is_open()) {
239 while( true ) {
240 string line;
241 getline(infile,line);
242 if( infile.fail() )
243 break;
244 if( (!line.empty()) && (line[0] != '#') ) {
245 string::size_type pos = line.find(':',0);
246 if( pos == string::npos )
247 throw "Invalid alias";
248 else {
249 string::size_type posl = line.substr(0, pos).find_last_not_of(" \t");
250 string key = line.substr(0, posl + 1);
251 string::size_type posr = line.substr(pos + 1, line.length()).find_first_not_of(" \t");
252 string val = line.substr(pos + 1 + posr, line.length());
253 Aliases[key] = val;
254 }
255 }
256 }
257 infile.close();
258 } else
259 throw "Error opening aliases file";
260 }
261
262 FactorGraph fg;
263 fg.ReadFromFile( filename.c_str() );
264
265 vector<Factor> q0;
266 double logZ0 = 0.0;
267
268 cout << "# " << filename << endl;
269 cout.width( 40 );
270 cout << left << "# METHOD" << " ";
271 if( report_time ) {
272 cout.width( 10 );
273 cout << right << "SECONDS" << " ";
274 }
275 cout.width( 10 );
276 cout << "MAX ERROR" << " ";
277 cout.width( 10 );
278 cout << "AVG ERROR" << " ";
279 cout.width( 10 );
280 cout << "LOGZ ERROR" << " ";
281 cout.width( 10 );
282 cout << "MAXDIFF" << " ";
283 cout.width( 10 );
284 cout << "ITERS" << endl;
285
286 for( size_t m = 0; m < methods.size(); m++ ) {
287 pair<string, PropertySet> meth = parseMethod( methods[m], Aliases );
288
289 if( vm.count("tol") )
290 meth.second.Set("tol",tol);
291 if( vm.count("maxiter") )
292 meth.second.Set("maxiter",maxiter);
293 if( vm.count("verbose") )
294 meth.second.Set("verbose",verbose);
295 TestDAI piet(fg, meth.first, meth.second );
296 piet.doDAI();
297 if( m == 0 ) {
298 q0 = piet.q;
299 logZ0 = piet.logZ;
300 }
301 piet.calcErrs(q0);
302
303 cout.width( 40 );
304 // cout << left << piet.identify() << " ";
305 cout << left << methods[m] << " ";
306 if( report_time ) {
307 cout.width( 10 );
308 cout << right << piet.time << " ";
309 }
310
311 if( m > 0 ) {
312 cout.setf( ios_base::scientific );
313 cout.precision( 3 );
314 cout.width( 10 );
315 double me = clipdouble( piet.maxErr(), 1e-9 );
316 cout << me << " ";
317 cout.width( 10 );
318 double ae = clipdouble( piet.avgErr(), 1e-9 );
319 cout << ae << " ";
320 cout.width( 10 );
321 if( piet.has_logZ ) {
322 double le = clipdouble( piet.logZ / logZ0 - 1.0, 1e-9 );
323 cout << le << " ";
324 } else {
325 cout << "N/A ";
326 }
327 cout.width( 10 );
328 if( piet.has_maxdiff ) {
329 double md = clipdouble( piet.maxdiff, 1e-9 );
330 if( isnan( me ) )
331 md = me;
332 if( isnan( ae ) )
333 md = ae;
334 cout << md << " ";
335 } else {
336 cout << "N/A ";
337 }
338 cout.width( 10 );
339 if( piet.has_iters ) {
340 cout << piet.iters << " " << endl;
341 } else {
342 cout << "N/A ";
343 }
344 }
345 cout << endl;
346
347 if( marginals ) {
348 for( size_t i = 0; i < piet.q.size(); i++ )
349 cout << "# " << piet.q[i] << endl;
350 }
351 }
352 } catch(const char *e) {
353 cerr << "Exception: " << e << endl;
354 return 1;
355 } catch(exception& e) {
356 cerr << "Exception: " << e.what() << endl;
357 return 1;
358 }
359 catch(...) {
360 cerr << "Exception of unknown type!" << endl;
361 }
362
363 return 0;
364 }