Improved documentation...
[libdai.git] / examples / example_varset.cpp
1 #include <dai/varset.h>
2 #include <iostream>
3
4 using namespace std;
5 using namespace dai;
6
7 int main() {
8 Var x0(0, 2); // Define binary variable x0 (with label 0)
9 Var x1(1, 3); // Define ternary variable x1 (with label 1)
10
11 // Define set X = {x0, x1}
12 VarSet X; // empty
13 X |= x1; // X = {x1}
14 X |= x0; // X = {x1, x0}
15 cout << "X = " << X << endl << endl; // Note that the elements of X are ordered according to their labels
16
17 // Output some information about x0, x1 and X
18 cout << "Var " << x0 << " has " << x0.states() << " states (possible values)." << endl;
19 cout << "Var " << x1 << " has " << x1.states() << " states." << endl << endl;
20 cout << "VarSet " << X << " has " << X.nrStates() << " states (joint assignments of its variables)." << endl << endl;
21
22 cout << "States of VarSets correspond to states of their constituent Vars:" << endl;
23 cout << " state of x0: state of x1: state of X:" << endl;
24 for( size_t s1 = 0; s1 < x1.states(); s1++ ) // for all states s1 of x1
25 for( size_t s0 = 0; s0 < x0.states(); s0++ ) { // for all states s0 of x0
26 // store s0 and s1 in a map "states"
27 map<Var,size_t> states;
28 states[x0] = s0;
29 states[x1] = s1;
30
31 // output states of x0, x1 and corresponding state of X
32 cout << " " << s0 << " " << s1 << " " << X.calcState(states) << endl;
33
34 // VarSet::calcStates is the inverse of VarSet::calcState
35 assert( X.calcStates(X.calcState(states)) == states );
36 }
37
38 cout << endl << "And vice versa:" << endl;
39 cout << " state of x0: state of x1: state of X:" << endl;
40 for( size_t S = 0; S < X.nrStates(); S++ ) { // for all (joint) states of X
41 // calculate states of x0 and x1 corresponding to state S of X
42 map<Var,size_t> states = X.calcStates(S);
43
44 // output state of X and corresponding states of x0, x1
45 cout << " " << states[x0] << " " << states[x1] << " " << S << endl;
46
47 // VarSet::calcState is the inverse of VarSet::calcStates
48 assert( X.calcState(X.calcStates(S)) == S );
49 }
50
51 return 0;
52 }