grid_potts.cxx
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/graphicalmodel/space/simplediscretespace.hxx>
#include <opengm/functions/potts.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/inference/messagepassing/messagepassing.hxx>
#include <opengm/inference/gibbs.hxx>
using namespace std;
using namespace opengm;
const size_t nx = 30;
const size_t ny = 30;
const size_t numberOfLabels = 5;
double lambda = 0.1;
inline size_t variableIndex(const size_t x, const size_t y) {
return x + nx * y;
}
int main() {
typedef SimpleDiscreteSpace<size_t, size_t> Space;
Space space(nx * ny, numberOfLabels);
typedef GraphicalModel<double, Adder, OPENGM_TYPELIST_2(ExplicitFunction<double> , PottsFunction<double> ) , Space> Model;
Model gm(space);
for(size_t y = 0; y < ny; ++y)
for(size_t x = 0; x < nx; ++x) {
const size_t shape[] = {numberOfLabels};
ExplicitFunction<double> f(shape, shape + 1);
for(size_t s = 0; s < numberOfLabels; ++s) {
f(s) = (1.0 - lambda) * rand() / RAND_MAX;
}
Model::FunctionIdentifier fid = gm.addFunction(f);
size_t variableIndices[] = {variableIndex(x, y)};
gm.addFactor(fid, variableIndices, variableIndices + 1);
}
PottsFunction<double> f(numberOfLabels, numberOfLabels, 0.0, lambda);
Model::FunctionIdentifier fid = gm.addFunction(f);
for(size_t y = 0; y < ny; ++y)
for(size_t x = 0; x < nx; ++x) {
if(x + 1 < nx) {
size_t variableIndices[] = {variableIndex(x, y), variableIndex(x + 1, y)};
sort(variableIndices, variableIndices + 2);
gm.addFactor(fid, variableIndices, variableIndices + 2);
}
if(y + 1 < ny) {
size_t variableIndices[] = {variableIndex(x, y), variableIndex(x, y + 1)};
sort(variableIndices, variableIndices + 2);
gm.addFactor(fid, variableIndices, variableIndices + 2);
}
}
typedef BeliefPropagationUpdateRules<Model, opengm::Minimizer> UpdateRules;
typedef MessagePassing<Model, opengm::Minimizer, UpdateRules, opengm::MaxDistance> BeliefPropagation;
const size_t maxNumberOfIterations = 40;
const double convergenceBound = 1e-7;
const double damping = 0.5;
BeliefPropagation::Parameter parameter(maxNumberOfIterations, convergenceBound, damping);
BeliefPropagation bp(gm, parameter);
BeliefPropagation::VerboseVisitorType visitor;
bp.infer(visitor);
vector<size_t> labeling(nx * ny);
bp.arg(labeling);
size_t variableIndex = 0;
for(size_t y = 0; y < ny; ++y) {
for(size_t x = 0; x < nx; ++x) {
cout << labeling[variableIndex] << ' ';
++variableIndex;
}
cout << endl;
}
}