example_varset.cpp
This example shows how to use the Var, VarSet and State classes. It also explains the concept of "states" for VarSets.
X = {x0,x1}
Var x0 has 2 states (possible values).
Var x1 has 3 states.
VarSet {x0,x1} has 6 states (joint assignments of its variables).
States of VarSets correspond to states of their constituent Vars:
state of x0: state of x1: state of X:
0 0 0
1 0 1
0 1 2
1 1 3
0 2 4
1 2 5
And vice versa:
state of x0: state of x1: state of X:
0 0 0
1 0 1
0 1 2
1 1 3
0 2 4
1 2 5
#include <dai/varset.h>
#include <dai/index.h>
#include <iostream>
using namespace std;
using namespace dai;
int main() {
Var x0(0, 2);
Var x1(1, 3);
VarSet X;
X |= x1;
X |= x0;
cout << "X = " << X << endl << endl;
cout << "Var " << x0 << " has " << x0.states() << " states (possible values)." << endl;
cout << "Var " << x1 << " has " << x1.states() << " states." << endl << endl;
cout << "VarSet " << X << " has " << X.nrStates() << " states (joint assignments of its variables)." << endl << endl;
cout << "States of VarSets correspond to states of their constituent Vars:" << endl;
cout << " state of x0: state of x1: (linear) state of X:" << endl;
for( size_t s1 = 0; s1 < x1.states(); s1++ )
for( size_t s0 = 0; s0 < x0.states(); s0++ ) {
map<Var,size_t> states;
states[x0] = s0;
states[x1] = s1;
cout << " " << s0 << " " << s1 << " " << calcLinearState(X,states) << endl;
DAI_ASSERT( calcState(X, calcLinearState(X, states)) == states );
}
cout << endl << "And vice versa:" << endl;
cout << " state of x0: state of x1: (linear) state of X:" << endl;
for( size_t S = 0; S < X.nrStates(); S++ ) {
map<Var,size_t> states = calcState(X,S);
cout << " " << states[x0] << " " << states[x1] << " " << S << endl;
DAI_ASSERT( calcLinearState(X, calcState(X,S)) == S );
}
cout << endl << "Iterating over all joint states using the State class:" << endl;
cout << " state of x0: state of x1: (linear) state of X: state of X (as a map):" << endl;
for( State S(X); S.valid(); S++ ) {
cout << " " << S(x0) << " " << S(x1) << " " << S << " " << S.get() << endl;
}
return 0;
}