diff --git a/cpp/BinaryConditional.h b/cpp/BinaryConditional.h index 0a9001d40..064587e9a 100644 --- a/cpp/BinaryConditional.h +++ b/cpp/BinaryConditional.h @@ -54,15 +54,19 @@ namespace gtsam { BinaryConditional(const std::string& key, const std::string& parent, const std::vector& cpt) : Conditional(key) { parents_.push_back(parent); - cpt_ = cpt; + for( int i = 0 ; i < cpt.size() ; i++ ) + cpt_.push_back(1-cpt[i]); // p(!x|parents) + cpt_.insert(cpt_.end(),cpt.begin(),cpt.end()); // p(x|parents) } double probability( std::map config) { - int index = 0, count = 0; - BOOST_FOREACH( std::string parent, parents_) - index += pow(2,count++)*(int)(config[parent]); + int index = 0, count = 1; + BOOST_FOREACH( std::string parent, parents_){ + index += count*(int)(config[parent]); + count = count << 1; + } if( config.find(key_)->second ) - index += pow(2,count); + index += count; return cpt_[index]; } diff --git a/cpp/testBinaryBayesNet.cpp b/cpp/testBinaryBayesNet.cpp index 131b0c01b..2b67939e7 100644 --- a/cpp/testBinaryBayesNet.cpp +++ b/cpp/testBinaryBayesNet.cpp @@ -31,7 +31,7 @@ using namespace gtsam; /** A Bayes net made from binary conditional probability tables */ typedef BayesNet BinaryBayesNet; -/* ************************************************************************* */ +/************************************************************************** */ TEST( BinaryBayesNet, constructor ) { // small Bayes Net x <- y @@ -40,19 +40,19 @@ TEST( BinaryBayesNet, constructor ) // p(x|y=1) = 0.6 map config; - config["y"] = false; - config["x"] = false; + config["y"] = true; + config["x"] = true; // unary conditional for y boost::shared_ptr py(new BinaryConditional("y",0.2)); py->print("py"); - DOUBLES_EQUAL(0.8,py->probability(config),0.01); + DOUBLES_EQUAL(0.2,py->probability(config),0.01); // single parent conditional for x vector cpt; - cpt += 0.7, 0.4, 0.3, 0.6 ; // array index corresponds to binary parent configuration + cpt += 0.3, 0.6 ; // array index corresponds to binary parent configuration boost::shared_ptr px_y(new BinaryConditional("x","y",cpt)); px_y->print("px_y"); - DOUBLES_EQUAL(0.7,px_y->probability(config),0.01); + DOUBLES_EQUAL(0.6,px_y->probability(config),0.01); // push back conditionals in topological sort order (parents last) BinaryBayesNet bbn;