Improved documentation of include/dai/index.h
[libdai.git] / examples / example_varset.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) 2008-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 */
9
10
11 #include <dai/varset.h>
12 #include <dai/index.h>
13 #include <iostream>
14
15 using namespace std;
16 using namespace dai;
17
18 int main() {
19 Var x0(0, 2); // Define binary variable x0 (with label 0)
20 Var x1(1, 3); // Define ternary variable x1 (with label 1)
21
22 // Define set X = {x0, x1}
23 VarSet X; // empty
24 X |= x1; // X = {x1}
25 X |= x0; // X = {x1, x0}
26 cout << "X = " << X << endl << endl; // Note that the elements of X are ordered according to their labels
27
28 // Output some information about x0, x1 and X
29 cout << "Var " << x0 << " has " << x0.states() << " states (possible values)." << endl;
30 cout << "Var " << x1 << " has " << x1.states() << " states." << endl << endl;
31 cout << "VarSet " << X << " has " << X.nrStates() << " states (joint assignments of its variables)." << endl << endl;
32
33 cout << "States of VarSets correspond to states of their constituent Vars:" << endl;
34 cout << " state of x0: state of x1: (linear) state of X:" << endl;
35 for( size_t s1 = 0; s1 < x1.states(); s1++ ) // for all states s1 of x1
36 for( size_t s0 = 0; s0 < x0.states(); s0++ ) { // for all states s0 of x0
37 // store s0 and s1 in a map "states"
38 map<Var,size_t> states;
39 states[x0] = s0;
40 states[x1] = s1;
41
42 // output states of x0, x1 and corresponding state of X
43 cout << " " << s0 << " " << s1 << " " << X.calcState(states) << endl;
44
45 // VarSet::calcStates is the inverse of VarSet::calcState
46 DAI_ASSERT( X.calcStates(X.calcState(states)) == states );
47 }
48
49 cout << endl << "And vice versa:" << endl;
50 cout << " state of x0: state of x1: (linear) state of X:" << endl;
51 for( size_t S = 0; S < X.nrStates(); S++ ) { // for all (joint) states of X
52 // calculate states of x0 and x1 corresponding to state S of X
53 map<Var,size_t> states = X.calcStates(S);
54
55 // output state of X and corresponding states of x0, x1
56 cout << " " << states[x0] << " " << states[x1] << " " << S << endl;
57
58 // VarSet::calcState is the inverse of VarSet::calcStates
59 DAI_ASSERT( X.calcState(X.calcStates(S)) == S );
60 }
61
62 cout << endl << "Iterating over all joint states using the State class:" << endl;
63 cout << " state of x0: state of x1: (linear) state of X: state of X (as a map):" << endl;
64 for( State S(X); S.valid(); S++ ) {
65 // output state of X and corresponding states of x0, x1
66 cout << " " << S(x0) << " " << S(x1) << " " << S << " " << S.get() << endl;
67 }
68
69 return 0;
70 }