b5b02e8b0647df123e4b339b10ea2a0d025b69f5
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
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 */
11 #include <dai/factorgraph.h>
12 #include <dai/gibbs.h>
13 #include <dai/properties.h>
14 #include <iostream>
15 #include <fstream>
17 using namespace std;
18 using namespace dai;
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
29 // Read the factorgraph from the file
30 FactorGraph SprinklerNetwork;
32 cout << "Sprinkler network read from sprinkler.fg" << endl;
34 // Output some information about the factorgraph
35 cout << SprinklerNetwork.nrVars() << " variables" << endl;
36 cout << SprinklerNetwork.nrFactors() << " factors" << endl;
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 );
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!";
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;
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;
69 // Close the .tab file
70 outfile.close();
72 return 0;
73 }