84c62e49104a6b14b914df1cdf4e9454b2a20ddb
1 #include <dai/factorgraph.h>
8 // This example program illustrates how to construct a factorgraph
9 // by means of the sprinkler network example discussed at
10 // http://www.cs.ubc.ca/~murphyk/Bayes/bnintro.html
12 Var
C(0, 2); // Define binary variable Cloudy (with label 0)
13 Var
S(1, 2); // Define binary variable Sprinkler (with label 1)
14 Var
R(2, 2); // Define binary variable Rain (with label 2)
15 Var
W(3, 2); // Define binary variable Wetgrass (with label 3)
17 // Define probability distribution for C
19 P_C
[0] = 0.5; // C = 0
20 P_C
[1] = 0.5; // C = 1
22 // Define conditional probability of S given C
23 Factor
P_S_given_C( VarSet( S
, C
) );
24 P_S_given_C
[0] = 0.5; // C = 0, S = 0
25 P_S_given_C
[1] = 0.9; // C = 1, S = 0
26 P_S_given_C
[2] = 0.5; // C = 0, S = 1
27 P_S_given_C
[3] = 0.1; // C = 1, S = 1
29 // Define conditional probability of R given C
30 Factor
P_R_given_C( VarSet( R
, C
) );
31 P_R_given_C
[0] = 0.8; // C = 0, R = 0
32 P_R_given_C
[1] = 0.2; // C = 1, R = 0
33 P_R_given_C
[2] = 0.2; // C = 0, R = 1
34 P_R_given_C
[3] = 0.8; // C = 1, R = 1
36 // Define conditional probability of W given S and R
37 Factor
P_W_given_S_R( VarSet( S
, R
) | W
);
38 P_W_given_S_R
[0] = 1.0; // S = 0, R = 0, W = 0
39 P_W_given_S_R
[1] = 0.1; // S = 1, R = 0, W = 0
40 P_W_given_S_R
[2] = 0.1; // S = 0, R = 1, W = 0
41 P_W_given_S_R
[3] = 0.01; // S = 1, R = 1, W = 0
42 P_W_given_S_R
[4] = 0.0; // S = 0, R = 0, W = 1
43 P_W_given_S_R
[5] = 0.9; // S = 1, R = 0, W = 1
44 P_W_given_S_R
[6] = 0.9; // S = 0, R = 1, W = 1
45 P_W_given_S_R
[7] = 0.99; // S = 1, R = 1, W = 1
47 // Build factor graph consisting of those four factors
48 vector
<Factor
> SprinklerFactors
;
49 SprinklerFactors
.push_back( P_C
);
50 SprinklerFactors
.push_back( P_R_given_C
);
51 SprinklerFactors
.push_back( P_S_given_C
);
52 SprinklerFactors
.push_back( P_W_given_S_R
);
53 FactorGraph
SprinklerNetwork( SprinklerFactors
);
55 // Write factorgraph to a file
56 SprinklerNetwork
.WriteToFile( "sprinkler.fg" );
58 // Reread the factorgraph from the file
59 SprinklerNetwork
.ReadFromFile( "sprinkler.fg" );
61 // Output some information about the factorgraph
62 cout
<< SprinklerNetwork
.nrVars() << " variables" << endl
;
63 cout
<< SprinklerNetwork
.nrFactors() << " factors" << endl
;
65 // Calculate joint probability of all four variables
67 for( size_t I
= 0; I
< SprinklerNetwork
.nrFactors(); I
++ ) {
68 P
*= SprinklerNetwork
.factor( I
);
70 // P.normalize(); // Not necessary: a Bayesian network is already normalized by definition
72 // Calculate some probabilities
73 double denom
= P
.marginal( W
)[1];
74 cout
<< "P(W=1) = " << denom
<< endl
;
75 cout
<< "P(S=1 | W=1) = " << P
.marginal( VarSet( S
, W
) )[3] / denom
<< endl
;
76 cout
<< "P(R=1 | W=1) = " << P
.marginal( VarSet( R
, W
) )[3] / denom
<< endl
;