-
Notifications
You must be signed in to change notification settings - Fork 774
/
UGM_small.cpp
86 lines (65 loc) · 2.58 KB
/
UGM_small.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file UGM_small.cpp
* @brief UGM (undirected graphical model) examples: small
* @author Frank Dellaert
*
* See http://www.di.ens.fr/~mschmidt/Software/UGM/small.html
*/
#include <gtsam/base/Vector.h>
#include <gtsam/discrete/DiscreteFactorGraph.h>
#include <gtsam/discrete/DiscreteMarginals.h>
using namespace std;
using namespace gtsam;
int main(int argc, char** argv) {
// We will assume 2-state variables, where, to conform to the "small" example
// we have 0 == "right answer" and 1 == "wrong answer"
size_t nrStates = 2;
// define variables
DiscreteKey Cathy(1, nrStates), Heather(2, nrStates), Mark(3, nrStates),
Allison(4, nrStates);
// create graph
DiscreteFactorGraph graph;
// add node potentials
graph.add(Cathy, "1 3");
graph.add(Heather, "9 1");
graph.add(Mark, "1 3");
graph.add(Allison, "9 1");
// add edge potentials
graph.add(Cathy & Heather, "2 1 1 2");
graph.add(Heather & Mark, "2 1 1 2");
graph.add(Mark & Allison, "2 1 1 2");
// Print the UGM distribution
cout << "\nUGM distribution:" << endl;
auto allPosbValues =
DiscreteValues::CartesianProduct(Cathy & Heather & Mark & Allison);
for (size_t i = 0; i < allPosbValues.size(); ++i) {
DiscreteFactor::Values values = allPosbValues[i];
double prodPot = graph(values);
cout << values[Cathy.first] << " " << values[Heather.first] << " "
<< values[Mark.first] << " " << values[Allison.first] << " :\t"
<< prodPot << "\t" << prodPot / 3790 << endl;
}
// "Decoding", i.e., configuration with largest value (MPE)
// Uses max-product
auto optimalDecoding = graph.optimize();
GTSAM_PRINT(optimalDecoding);
// "Inference" Computing marginals
cout << "\nComputing Node Marginals .." << endl;
DiscreteMarginals marginals(graph);
Vector margProbs = marginals.marginalProbabilities(Cathy);
print(margProbs, "Cathy's Node Marginal:");
margProbs = marginals.marginalProbabilities(Heather);
print(margProbs, "Heather's Node Marginal");
margProbs = marginals.marginalProbabilities(Mark);
print(margProbs, "Mark's Node Marginal");
margProbs = marginals.marginalProbabilities(Allison);
print(margProbs, "Allison's Node Marginal");
return 0;
}