Updated copyright headers
[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 <iostream>
13
14 using namespace std;
15 using namespace dai;
16
17 int main() {
18 Var x0(0, 2); // Define binary variable x0 (with label 0)
19 Var x1(1, 3); // Define ternary variable x1 (with label 1)
20
21 // Define set X = {x0, x1}
22 VarSet X; // empty
23 X |= x1; // X = {x1}
24 X |= x0; // X = {x1, x0}
25 cout << "X = " << X << endl << endl; // Note that the elements of X are ordered according to their labels
26
27 // Output some information about x0, x1 and X
28 cout << "Var " << x0 << " has " << x0.states() << " states (possible values)." << endl;
29 cout << "Var " << x1 << " has " << x1.states() << " states." << endl << endl;
30 cout << "VarSet " << X << " has " << X.nrStates() << " states (joint assignments of its variables)." << endl << endl;
31
32 cout << "States of VarSets correspond to states of their constituent Vars:" << endl;
33 cout << " state of x0: state of x1: state of X:" << endl;
34 for( size_t s1 = 0; s1 < x1.states(); s1++ ) // for all states s1 of x1
35 for( size_t s0 = 0; s0 < x0.states(); s0++ ) { // for all states s0 of x0
36 // store s0 and s1 in a map "states"
37 map<Var,size_t> states;
38 states[x0] = s0;
39 states[x1] = s1;
40
41 // output states of x0, x1 and corresponding state of X
42 cout << " " << s0 << " " << s1 << " " << X.calcState(states) << endl;
43
44 // VarSet::calcStates is the inverse of VarSet::calcState
45 assert( X.calcStates(X.calcState(states)) == states );
46 }
47
48 cout << endl << "And vice versa:" << endl;
49 cout << " state of x0: state of x1: state of X:" << endl;
50 for( size_t S = 0; S < X.nrStates(); S++ ) { // for all (joint) states of X
51 // calculate states of x0 and x1 corresponding to state S of X
52 map<Var,size_t> states = X.calcStates(S);
53
54 // output state of X and corresponding states of x0, x1
55 cout << " " << states[x0] << " " << states[x1] << " " << S << endl;
56
57 // VarSet::calcState is the inverse of VarSet::calcStates
58 assert( X.calcState(X.calcStates(S)) == S );
59 }
60
61 return 0;
62 }