Merge branch 'master' of git.tuebingen.mpg.de:libdai
[libdai.git] / examples / example_sprinkler_gibbs.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2010 Joris Mooij [joris dot mooij at libdai dot org]
8 */
9
10
11 #include <dai/factorgraph.h>
12 #include <dai/gibbs.h>
13 #include <dai/properties.h>
14 #include <iostream>
15 #include <fstream>
16
17 using namespace std;
18 using namespace dai;
19
20 int main() {
21 // This example program illustrates how to use Gibbs sampling
22 // to sample from a joint probability distribution described
23 // by a factor graph, using the sprinkler network example discussed at
24 // http://www.cs.ubc.ca/~murphyk/Bayes/bnintro.html
25 //
26 // The file sprinkler.fg has to be generated by first running
27 // example_sprinkler
28
29 // Read the factorgraph from the file
30 FactorGraph SprinklerNetwork;
31 SprinklerNetwork.ReadFromFile( "sprinkler.fg" );
32 cout << "Sprinkler network read from sprinkler.fg" << endl;
33
34 // Output some information about the factorgraph
35 cout << SprinklerNetwork.nrVars() << " variables" << endl;
36 cout << SprinklerNetwork.nrFactors() << " factors" << endl;
37
38 // Prepare a Gibbs sampler
39 PropertySet gibbsProps;
40 gibbsProps.set("iters", size_t(100)); // number of Gibbs sampler iterations
41 gibbsProps.set("burnin", size_t(0));
42 gibbsProps.set("verbose", size_t(0));
43 Gibbs gibbsSampler( SprinklerNetwork, gibbsProps );
44
45 // Open a .tab file for writing
46 ofstream outfile;
47 outfile.open( "sprinkler.tab" );
48 if( !outfile.is_open() )
49 throw "Cannot write to file!";
50
51 // Write header (consisting of variable labels)
52 for( size_t i = 0; i < SprinklerNetwork.nrVars(); i++ )
53 outfile << (i == 0 ? "" : "\t") << SprinklerNetwork.var(i).label();
54 outfile << endl << endl;
55
56 // Draw samples from joint distribution using Gibbs sampling
57 // and write them to the .tab file
58 size_t nrSamples = 1000;
59 std::vector<size_t> state;
60 for( size_t t = 0; t < nrSamples; t++ ) {
61 gibbsSampler.run();
62 state = gibbsSampler.state();
63 for( size_t i = 0; i < state.size(); i++ )
64 outfile << (i == 0 ? "" : "\t") << state[i];
65 outfile << endl;
66 }
67 cout << nrSamples << " samples written to sprinkler.tab" << endl;
68
69 // Close the .tab file
70 outfile.close();
71
72 return 0;
73 }