Improved documentation of bipgraph.h and added example_bipgraph.cpp
[libdai.git] / examples / example.cpp
1 /* Copyright (C) 2006-2008 Joris Mooij [joris dot mooij at tuebingen dot mpg dot de]
2 Radboud University Nijmegen, The Netherlands /
3 Max Planck Institute for Biological Cybernetics, Germany
4
5 This file is part of libDAI.
6
7 libDAI is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 libDAI is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with libDAI; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22
23 #include <iostream>
24 #include <dai/alldai.h>
25
26
27 using namespace dai;
28 using namespace std;
29
30
31 int main( int argc, char *argv[] ) {
32 if ( argc != 2 ) {
33 cout << "Usage: " << argv[0] << " <filename.fg>" << endl << endl;
34 cout << "Reads factor graph <filename.fg> and runs" << endl;
35 cout << "Belief Propagation and JunctionTree on it." << endl << endl;
36 return 1;
37 } else {
38 FactorGraph fg;
39 fg.ReadFromFile(argv[1]);
40
41 size_t maxiter = 10000;
42 double tol = 1e-9;
43 size_t verb = 1;
44
45 PropertySet opts;
46 opts.Set("maxiter",maxiter);
47 opts.Set("tol",tol);
48 opts.Set("verbose",verb);
49
50 JTree jt( fg, opts("updates",string("HUGIN")) );
51 jt.init();
52 jt.run();
53
54 BP bp(fg, opts("updates",string("SEQFIX"))("logdomain",false));
55 bp.init();
56 bp.run();
57
58 cout << "Exact single node marginals:" << endl;
59 for( size_t i = 0; i < fg.nrVars(); i++ )
60 cout << jt.belief(fg.var(i)) << endl;
61
62 cout << "Approximate (loopy belief propagation) single node marginals:" << endl;
63 for( size_t i = 0; i < fg.nrVars(); i++ )
64 cout << bp.belief(fg.var(i)) << endl;
65
66 cout << "Exact factor marginals:" << endl;
67 for( size_t I = 0; I < fg.nrFactors(); I++ )
68 cout << jt.belief(fg.factor(I).vars()) << endl;
69
70 cout << "Approximate (loopy belief propagation) factor marginals:" << endl;
71 for( size_t I = 0; I < fg.nrFactors(); I++ )
72 cout << bp.belief(fg.factor(I).vars()) << "=" << bp.beliefF(I) << endl;
73
74 cout << "Exact log partition sum: " << jt.logZ() << endl;
75 cout << "Approximate (loopy belief propagation) log partition sum: " << bp.logZ() << endl;
76 }
77
78 return 0;
79 }