Merged mf.* from SVN head (which implements damping)...
[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 fg.ReadFromFile(argv[1]);
39
40 size_t maxiter = 10000;
41 double tol = 1e-9;
42 size_t verb = 1;
43
44 PropertySet opts;
45 opts.Set("maxiter",maxiter);
46 opts.Set("tol",tol);
47 opts.Set("verbose",verb);
48
49 JTree jt( fg, opts("updates",string("HUGIN")) );
50 jt.init();
51 jt.run();
52
53 BP bp(fg, opts("updates",string("SEQFIX"))("logdomain",false));
54 bp.init();
55 bp.run();
56
57 cout << "Exact single node marginals:" << endl;
58 for( size_t i = 0; i < fg.nrVars(); i++ )
59 cout << jt.belief(fg.var(i)) << endl;
60
61 cout << "Approximate (loopy belief propagation) single node marginals:" << endl;
62 for( size_t i = 0; i < fg.nrVars(); i++ )
63 cout << bp.belief(fg.var(i)) << endl;
64
65 cout << "Exact factor marginals:" << endl;
66 for( size_t I = 0; I < fg.nrFactors(); I++ )
67 cout << jt.belief(fg.factor(I).vars()) << endl;
68
69 cout << "Approximate (loopy belief propagation) factor marginals:" << endl;
70 for( size_t I = 0; I < fg.nrFactors(); I++ )
71 cout << bp.belief(fg.factor(I).vars()) << "=" << bp.beliefF(I) << endl;
72
73 cout << "Exact log partition sum: " << jt.logZ() << endl;
74 cout << "Approximate (loopy belief propagation) log partition sum: " << bp.logZ() << endl;
75 }
76
77 return 0;
78 }