Merge branch 'eaton'
[libdai.git] / tests / testem / testem.cpp
1 /* Copyright (C) 2009 Charles Vaske [cvaske at soe dot ucsc dot edu]
2 University of California Santa Cruz
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 <string>
25
26 #include <dai/factorgraph.h>
27 #include <dai/evidence.h>
28 #include <dai/alldai.h>
29
30
31 using namespace std;
32 using namespace dai;
33
34
35 void usage( const string &msg ) {
36 cerr << msg << endl;
37 cerr << "Usage:" << endl;
38 cerr << " testem factorgraph.fg evidence.tab emconfig.em" << endl;
39 exit( 1 );
40 }
41
42
43 int main( int argc, char** argv ) {
44 if( argc != 4 )
45 usage("Incorrect number of arguments.");
46
47 FactorGraph fg;
48 fg.ReadFromFile( argv[1] );
49
50 PropertySet infprops;
51 infprops.Set( "verbose", (size_t)1 );
52 infprops.Set( "updates", string("HUGIN") );
53 InfAlg* inf = newInfAlg( "JTREE", fg, infprops );
54 inf->init();
55
56 Evidence e;
57 ifstream estream( argv[2] );
58 e.addEvidenceTabFile( estream, fg );
59
60 cout << "Number of samples: " << e.nrSamples() << endl;
61 for( Evidence::iterator ps = e.begin(); ps != e.end(); ps++ )
62 cout << "Sample #" << (ps - e.begin()) << " has " << ps->observations().size() << " observations." << endl;
63
64 ifstream emstream( argv[3] );
65 EMAlg em(e, *inf, emstream);
66
67 while( !em.hasSatisfiedTermConditions() ) {
68 Real l = em.iterate();
69 cout << "Iteration " << em.getCurrentIters() << " likelihood: " << l <<endl;
70 }
71
72 cout << endl << "Inferred Factor Graph:" << endl << "######################" << endl;
73 cout.precision(12);
74 cout << inf->fg();
75
76 delete inf;
77
78 return 0;
79 }