Merged prob.h, factorgraph.h, factograph.cpp from SVN head (broken!)
[libdai.git] / example.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 <dai/alldai.h>
24
25
26 using namespace dai;
27 using namespace std;
28
29
30 int main( int argc, char *argv[] ) {
31 if ( argc != 2 ) {
32 cout << "Usage: " << argv[0] << " <filename.fg>" << endl << endl;
33 cout << "Reads factor graph <filename.fg> and runs" << endl;
34 cout << "Belief Propagation and JunctionTree on it." << endl << endl;
35 return 1;
36 } else {
37 FactorGraph fg;
38
39 if( fg.ReadFromFile(argv[1]) ) {
40 cout << "Error reading " << argv[1] << endl;
41 return 2;
42 } else {
43 size_t maxiter = 10000;
44 double tol = 1e-9;
45 size_t verb = 1;
46
47 PropertySet opts;
48 opts.Set("maxiter",maxiter);
49 opts.Set("tol",tol);
50 opts.Set("verbose",verb);
51
52 JTree jt( fg, opts("updates",string("HUGIN")) );
53 jt.init();
54 jt.run();
55
56 BP bp(fg, opts("updates",string("SEQFIX"))("logdomain",false));
57 bp.init();
58 bp.run();
59
60 cout << "Exact single node marginals:" << endl;
61 for( size_t i = 0; i < fg.nrVars(); i++ )
62 cout << jt.belief(fg.var(i)) << endl;
63
64 cout << "Approximate (loopy belief propagation) single node marginals:" << endl;
65 for( size_t i = 0; i < fg.nrVars(); i++ )
66 cout << bp.belief(fg.var(i)) << endl;
67
68 cout << "Exact factor marginals:" << endl;
69 for( size_t I = 0; I < fg.nrFactors(); I++ )
70 cout << jt.belief(fg.factor(I).vars()) << endl;
71
72 cout << "Approximate (loopy belief propagation) factor marginals:" << endl;
73 for( size_t I = 0; I < fg.nrFactors(); I++ )
74 cout << bp.belief(fg.factor(I).vars()) << "=" << bp.beliefF(I) << endl;
75
76 cout << "Exact log partition sum: " << jt.logZ() << endl;
77 cout << "Approximate (loopy belief propagation) log partition sum: " << bp.logZ() << endl;
78 }
79 }
80
81 return 0;
82 }