This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
yap-6.3/packages/CLPBN/horus/BeliefProp.cpp

577 lines
14 KiB
C++
Raw Normal View History

2012-05-23 14:56:01 +01:00
#include <cassert>
#include <algorithm>
#include <iostream>
#include <iomanip>
2013-02-07 20:09:10 +00:00
#include <sstream>
2012-05-23 14:56:01 +01:00
#include "BeliefProp.h"
2012-05-23 14:56:01 +01:00
#include "Indexer.h"
#include "Horus.h"
namespace Horus {
2013-02-07 23:53:13 +00:00
double BeliefProp::accuracy_ = 0.0001;
unsigned BeliefProp::maxIter_ = 1000;
BeliefProp::MsgSchedule BeliefProp::schedule_ =
MsgSchedule::seqFixedSch;
2013-02-13 23:47:00 +00:00
BeliefProp::BeliefProp (const FactorGraph& fg)
: GroundSolver (fg), nIters_(0), runned_(false)
2012-05-23 14:56:01 +01:00
{
2013-03-09 17:14:00 +00:00
2012-05-23 14:56:01 +01:00
}
BeliefProp::~BeliefProp()
2012-05-23 14:56:01 +01:00
{
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-23 14:56:01 +01:00
delete links_[i];
}
links_.clear();
2012-05-23 14:56:01 +01:00
}
Params
BeliefProp::solveQuery (VarIds queryVids)
2012-05-23 14:56:01 +01:00
{
assert (queryVids.empty() == false);
2012-05-28 18:26:15 +01:00
return queryVids.size() == 1
? getPosterioriOf (queryVids[0])
: getJointDistributionOf (queryVids);
2012-05-23 14:56:01 +01:00
}
void
BeliefProp::printSolverFlags() const
2012-05-23 14:56:01 +01:00
{
2013-02-07 13:37:15 +00:00
std::stringstream ss;
2012-05-23 14:56:01 +01:00
ss << "belief propagation [" ;
2013-01-08 17:06:40 +00:00
ss << "bp_msg_schedule=" ;
switch (schedule_) {
case MsgSchedule::seqFixedSch: ss << "seq_fixed"; break;
case MsgSchedule::seqRandomSch: ss << "seq_random"; break;
case MsgSchedule::parallelSch: ss << "parallel"; break;
case MsgSchedule::maxResidualSch: ss << "max_residual"; break;
}
ss << ",bp_max_iter=" << Util::toString (maxIter_);
ss << ",bp_accuracy=" << Util::toString (accuracy_);
ss << ",log_domain=" << Util::toString (Globals::logDomain);
2012-05-23 14:56:01 +01:00
ss << "]" ;
2013-02-07 13:37:15 +00:00
std::cout << ss.str() << std::endl;
2012-05-23 14:56:01 +01:00
}
Params
BeliefProp::getPosterioriOf (VarId vid)
2012-05-23 14:56:01 +01:00
{
if (runned_ == false) {
runSolver();
}
2012-05-31 21:24:40 +01:00
assert (fg.getVarNode (vid));
VarNode* var = fg.getVarNode (vid);
2012-05-23 14:56:01 +01:00
Params probs;
if (var->hasEvidence()) {
probs.resize (var->range(), LogAware::noEvidence());
probs[var->getEvidence()] = LogAware::withEvidence();
2012-05-23 14:56:01 +01:00
} else {
probs.resize (var->range(), LogAware::multIdenty());
2013-03-09 16:41:53 +00:00
const BpLinks& links = getLinks (var);
if (Globals::logDomain) {
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links.size(); i++) {
2012-05-28 19:41:24 +01:00
probs += links[i]->message();
2012-05-23 14:56:01 +01:00
}
LogAware::normalize (probs);
Util::exp (probs);
2012-05-23 14:56:01 +01:00
} else {
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links.size(); i++) {
2012-05-28 19:41:24 +01:00
probs *= links[i]->message();
2012-05-23 14:56:01 +01:00
}
LogAware::normalize (probs);
2012-05-23 14:56:01 +01:00
}
}
return probs;
}
Params
BeliefProp::getJointDistributionOf (const VarIds& jointVarIds)
2012-05-23 14:56:01 +01:00
{
if (runned_ == false) {
runSolver();
}
2012-05-31 21:24:40 +01:00
VarNode* vn = fg.getVarNode (jointVarIds[0]);
2012-05-23 14:56:01 +01:00
const FacNodes& facNodes = vn->neighbors();
2012-05-24 22:55:20 +01:00
size_t idx = facNodes.size();
for (size_t i = 0; i < facNodes.size(); i++) {
2012-05-23 14:56:01 +01:00
if (facNodes[i]->factor().contains (jointVarIds)) {
idx = i;
break;
}
}
2012-05-24 22:55:20 +01:00
if (idx == facNodes.size()) {
2012-05-23 14:56:01 +01:00
return getJointByConditioning (jointVarIds);
}
2012-09-11 18:48:16 +01:00
return getFactorJoint (facNodes[idx], jointVarIds);
}
Params
BeliefProp::getFactorJoint (
2012-09-11 18:48:16 +01:00
FacNode* fn,
const VarIds& jointVarIds)
{
if (runned_ == false) {
runSolver();
}
Factor res (fn->factor());
2013-03-09 16:41:53 +00:00
const BpLinks& links = getLinks( fn);
for (size_t i = 0; i < links.size(); i++) {
Factor msg ({links[i]->varNode()->varId()},
{links[i]->varNode()->range()},
getVarToFactorMsg (links[i]));
res.multiply (msg);
}
res.sumOutAllExcept (jointVarIds);
res.reorderArguments (jointVarIds);
res.normalize();
Params jointDist = res.params();
if (Globals::logDomain) {
Util::exp (jointDist);
}
2012-12-20 23:19:10 +00:00
return jointDist;
2012-05-23 14:56:01 +01:00
}
2013-02-20 23:59:03 +00:00
BeliefProp::BpLink::BpLink (FacNode* fn, VarNode* vn)
{
fac_ = fn;
var_ = vn;
v1_.resize (vn->range(), LogAware::log (1.0 / vn->range()));
v2_.resize (vn->range(), LogAware::log (1.0 / vn->range()));
currMsg_ = &v1_;
nextMsg_ = &v2_;
residual_ = 0.0;
}
void
BeliefProp::BpLink::clearResidual()
2013-02-20 23:59:03 +00:00
{
residual_ = 0.0;
}
void
BeliefProp::BpLink::updateResidual()
2013-02-20 23:59:03 +00:00
{
residual_ = LogAware::getMaxNorm (v1_, v2_);
}
void
BeliefProp::BpLink::updateMessage()
2013-02-20 23:59:03 +00:00
{
swap (currMsg_, nextMsg_);
}
std::string
BeliefProp::BpLink::toString() const
2013-02-20 23:59:03 +00:00
{
std::stringstream ss;
ss << fac_->getLabel();
ss << " -- " ;
ss << var_->label();
return ss.str();
}
void
BeliefProp::calculateAndUpdateMessage (BpLink* link, bool calcResidual)
{
if (Globals::verbosity > 2) {
2013-02-07 13:37:15 +00:00
std::cout << "calculating & updating " << link->toString();
std::cout << std::endl;
}
calcFactorToVarMsg (link);
if (calcResidual) {
link->updateResidual();
}
link->updateMessage();
}
void
BeliefProp::calculateMessage (BpLink* link, bool calcResidual)
{
if (Globals::verbosity > 2) {
2013-02-07 13:37:15 +00:00
std::cout << "calculating " << link->toString();
std::cout << std::endl;
}
calcFactorToVarMsg (link);
if (calcResidual) {
link->updateResidual();
}
}
void
BeliefProp::updateMessage (BpLink* link)
{
link->updateMessage();
if (Globals::verbosity > 2) {
2013-02-07 13:37:15 +00:00
std::cout << "updating " << link->toString();
std::cout << std::endl;
}
}
2012-05-23 14:56:01 +01:00
void
BeliefProp::runSolver()
2012-05-23 14:56:01 +01:00
{
initializeSolver();
nIters_ = 0;
while (!converged() && nIters_ < maxIter_) {
2012-05-23 14:56:01 +01:00
nIters_ ++;
if (Globals::verbosity > 1) {
Util::printHeader (std::string ("Iteration ")
+ Util::toString (nIters_));
2012-05-23 14:56:01 +01:00
}
switch (schedule_) {
case MsgSchedule::seqRandomSch:
2012-05-28 19:41:24 +01:00
std::random_shuffle (links_.begin(), links_.end());
2012-05-23 14:56:01 +01:00
// no break
case MsgSchedule::seqFixedSch:
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-23 14:56:01 +01:00
calculateAndUpdateMessage (links_[i]);
}
break;
case MsgSchedule::parallelSch:
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-23 14:56:01 +01:00
calculateMessage (links_[i]);
}
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-23 14:56:01 +01:00
updateMessage(links_[i]);
}
break;
case MsgSchedule::maxResidualSch:
2012-05-23 14:56:01 +01:00
maxResidualSchedule();
break;
}
}
if (Globals::verbosity > 0) {
if (nIters_ < maxIter_) {
2013-02-07 13:37:15 +00:00
std::cout << "Belief propagation converged in " ;
std::cout << nIters_ << " iterations" << std::endl;
2012-05-23 14:56:01 +01:00
} else {
2013-03-09 17:14:00 +00:00
std::cout << "The maximum number of iterations was hit," ;
std::cout << " terminating..." ;
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
runned_ = true;
}
void
BeliefProp::createLinks()
2012-05-23 14:56:01 +01:00
{
2012-05-31 21:24:40 +01:00
const FacNodes& facNodes = fg.facNodes();
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < facNodes.size(); i++) {
2012-05-23 14:56:01 +01:00
const VarNodes& neighbors = facNodes[i]->neighbors();
2012-05-24 22:55:20 +01:00
for (size_t j = 0; j < neighbors.size(); j++) {
links_.push_back (new BpLink (facNodes[i], neighbors[j]));
2012-05-23 14:56:01 +01:00
}
}
}
void
BeliefProp::maxResidualSchedule()
2012-05-23 14:56:01 +01:00
{
if (nIters_ == 1) {
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-23 14:56:01 +01:00
calculateMessage (links_[i]);
SortedOrder::iterator it = sortedOrder_.insert (links_[i]);
linkMap_.insert (make_pair (links_[i], it));
}
return;
}
2012-05-24 22:55:20 +01:00
for (size_t c = 0; c < links_.size(); c++) {
if (Globals::verbosity > 1) {
2013-02-07 13:37:15 +00:00
std::cout << "current residuals:" << std::endl;
2012-05-23 14:56:01 +01:00
for (SortedOrder::iterator it = sortedOrder_.begin();
2012-05-28 14:12:18 +01:00
it != sortedOrder_.end(); ++it) {
2013-02-07 13:37:15 +00:00
std::cout << " " << std::setw (30) << std::left;
std::cout << (*it)->toString();
std::cout << "residual = " << (*it)->residual();
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
}
SortedOrder::iterator it = sortedOrder_.begin();
BpLink* link = *it;
if (link->residual() < accuracy_) {
2012-05-23 14:56:01 +01:00
return;
}
updateMessage (link);
link->clearResidual();
sortedOrder_.erase (it);
linkMap_.find (link)->second = sortedOrder_.insert (link);
// update the messages that depend on message source --> destin
2012-05-28 19:41:24 +01:00
const FacNodes& factorNeighbors = link->varNode()->neighbors();
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < factorNeighbors.size(); i++) {
2012-05-28 19:41:24 +01:00
if (factorNeighbors[i] != link->facNode()) {
2013-03-09 16:41:53 +00:00
const BpLinks& links = getLinks (factorNeighbors[i]);
2012-05-24 22:55:20 +01:00
for (size_t j = 0; j < links.size(); j++) {
2012-05-28 19:41:24 +01:00
if (links[j]->varNode() != link->varNode()) {
2012-05-23 14:56:01 +01:00
calculateMessage (links[j]);
BpLinkMap::iterator iter = linkMap_.find (links[j]);
2012-05-23 14:56:01 +01:00
sortedOrder_.erase (iter->second);
iter->second = sortedOrder_.insert (links[j]);
}
}
}
}
if (Globals::verbosity > 1) {
Util::printDashedLine();
2012-05-23 14:56:01 +01:00
}
}
}
void
BeliefProp::calcFactorToVarMsg (BpLink* link)
2012-05-23 14:56:01 +01:00
{
2012-05-28 19:41:24 +01:00
FacNode* src = link->facNode();
const VarNode* dst = link->varNode();
2013-03-09 16:41:53 +00:00
const BpLinks& links = getLinks (src);
2012-05-23 14:56:01 +01:00
// calculate the product of messages that were sent
// to factor `src', except from var `dst'
2012-05-28 21:27:52 +01:00
unsigned reps = 1;
unsigned msgSize = Util::sizeExpected (src->factor().ranges());
Params msgProduct (msgSize, LogAware::multIdenty());
if (Globals::logDomain) {
2012-05-28 14:01:05 +01:00
for (size_t i = links.size(); i-- > 0; ) {
2012-05-28 19:41:24 +01:00
if (links[i]->varNode() != dst) {
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " message from " << links[i]->varNode()->label();
std::cout << ": " ;
2012-05-23 14:56:01 +01:00
}
Util::apply_n_times (msgProduct, getVarToFactorMsg (links[i]),
reps, std::plus<double>());
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
}
2012-05-28 19:47:20 +01:00
reps *= links[i]->varNode()->range();
2012-05-23 14:56:01 +01:00
}
} else {
2012-05-28 14:01:05 +01:00
for (size_t i = links.size(); i-- > 0; ) {
2012-05-28 19:41:24 +01:00
if (links[i]->varNode() != dst) {
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " message from " << links[i]->varNode()->label();
std::cout << ": " ;
2012-05-23 14:56:01 +01:00
}
Util::apply_n_times (msgProduct, getVarToFactorMsg (links[i]),
reps, std::multiplies<double>());
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
}
2012-05-28 19:47:20 +01:00
reps *= links[i]->varNode()->range();
2012-05-23 14:56:01 +01:00
}
}
Factor result (src->factor().arguments(),
src->factor().ranges(), msgProduct);
result.multiply (src->factor());
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " message product: " << msgProduct << std::endl;
std::cout << " original factor: " << src->factor().params();
std::cout << std::endl;
std::cout << " factor product: " << result.params() << std::endl;
2012-05-23 14:56:01 +01:00
}
result.sumOutAllExcept (dst->varId());
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " marginalized: " << result.params() << std::endl;
2012-05-23 14:56:01 +01:00
}
2012-05-28 19:41:24 +01:00
link->nextMessage() = result.params();
LogAware::normalize (link->nextMessage());
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " curr msg: " << link->message() << std::endl;
std::cout << " next msg: " << link->nextMessage() << std::endl;
2012-05-23 14:56:01 +01:00
}
}
Params
2013-03-09 16:41:53 +00:00
BeliefProp::getVarToFactorMsg (const BpLink* link)
2012-05-23 14:56:01 +01:00
{
2012-05-28 19:41:24 +01:00
const VarNode* src = link->varNode();
2012-05-23 14:56:01 +01:00
Params msg;
if (src->hasEvidence()) {
msg.resize (src->range(), LogAware::noEvidence());
msg[src->getEvidence()] = LogAware::withEvidence();
2012-05-23 14:56:01 +01:00
} else {
msg.resize (src->range(), LogAware::one());
2012-05-23 14:56:01 +01:00
}
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << msg;
2012-05-23 14:56:01 +01:00
}
BpLinks::const_iterator it;
2013-03-09 16:41:53 +00:00
const BpLinks& links = getLinks (src);
if (Globals::logDomain) {
2012-05-28 19:10:29 +01:00
for (it = links.begin(); it != links.end(); ++it) {
if (*it != link) {
msg += (*it)->message();
}
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " x " << (*it)->message();
2012-05-23 14:56:01 +01:00
}
}
} else {
2012-05-28 19:10:29 +01:00
for (it = links.begin(); it != links.end(); ++it) {
if (*it != link) {
msg *= (*it)->message();
}
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " x " << (*it)->message();
2012-05-23 14:56:01 +01:00
}
}
}
if (Constants::showBpCalcs) {
2013-02-07 13:37:15 +00:00
std::cout << " = " << msg;
2012-05-23 14:56:01 +01:00
}
return msg;
}
Params
BeliefProp::getJointByConditioning (const VarIds& jointVarIds) const
2012-05-23 14:56:01 +01:00
{
2012-11-14 21:55:51 +00:00
return GroundSolver::getJointByConditioning (
GroundSolverType::bpSolver, fg, jointVarIds);
2012-05-23 14:56:01 +01:00
}
void
BeliefProp::initializeSolver()
2012-05-23 14:56:01 +01:00
{
2012-05-31 21:24:40 +01:00
const VarNodes& varNodes = fg.varNodes();
2013-03-09 16:41:53 +00:00
varsLinks_.reserve (varNodes.size());
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < varNodes.size(); i++) {
2013-03-09 16:41:53 +00:00
varsLinks_.push_back (BpLinks());
2012-05-23 14:56:01 +01:00
}
2012-05-31 21:24:40 +01:00
const FacNodes& facNodes = fg.facNodes();
2013-03-09 16:41:53 +00:00
facsLinks_.reserve (facNodes.size());
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < facNodes.size(); i++) {
2013-03-09 16:41:53 +00:00
facsLinks_.push_back (BpLinks());
2012-05-23 14:56:01 +01:00
}
createLinks();
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-28 19:41:24 +01:00
FacNode* src = links_[i]->facNode();
VarNode* dst = links_[i]->varNode();
2013-03-09 16:41:53 +00:00
getLinks (dst).push_back (links_[i]);
getLinks (src).push_back (links_[i]);
2012-05-23 14:56:01 +01:00
}
}
bool
BeliefProp::converged()
2012-05-23 14:56:01 +01:00
{
2012-12-27 12:54:58 +00:00
if (links_.empty()) {
2012-05-23 14:56:01 +01:00
return true;
}
if (nIters_ == 0) {
return false;
}
if (Globals::verbosity > 2) {
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
if (nIters_ == 1) {
if (Globals::verbosity > 1) {
2013-02-07 13:37:15 +00:00
std::cout << "no residuals" << std::endl << std::endl;
2012-05-23 14:56:01 +01:00
}
return false;
}
bool converged = true;
if (schedule_ == MsgSchedule::maxResidualSch) {
2012-05-28 19:41:24 +01:00
double maxResidual = (*(sortedOrder_.begin()))->residual();
if (maxResidual > accuracy_) {
2012-05-23 14:56:01 +01:00
converged = false;
} else {
converged = true;
}
} else {
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-05-28 19:41:24 +01:00
double residual = links_[i]->residual();
if (Globals::verbosity > 1) {
2013-02-07 13:37:15 +00:00
std::cout << links_[i]->toString() + " residual = " << residual;
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
if (residual > accuracy_) {
2012-05-23 14:56:01 +01:00
converged = false;
if (Globals::verbosity < 2) {
2012-05-23 14:56:01 +01:00
break;
}
}
}
if (Globals::verbosity > 1) {
2013-02-07 13:37:15 +00:00
std::cout << std::endl;
2012-05-23 14:56:01 +01:00
}
}
return converged;
}
void
BeliefProp::printLinkInformation() const
2012-05-23 14:56:01 +01:00
{
2013-02-07 13:37:15 +00:00
using std::cout;
using std::endl;
2012-05-24 22:55:20 +01:00
for (size_t i = 0; i < links_.size(); i++) {
2012-12-20 23:19:10 +00:00
BpLink* l = links_[i];
2012-05-23 14:56:01 +01:00
cout << l->toString() << ":" << endl;
cout << " curr msg = " ;
2012-05-28 19:41:24 +01:00
cout << l->message() << endl;
2012-05-23 14:56:01 +01:00
cout << " next msg = " ;
2012-05-28 19:41:24 +01:00
cout << l->nextMessage() << endl;
cout << " residual = " << l->residual() << endl;
2012-05-23 14:56:01 +01:00
}
}
} // namespace Horus
2013-02-07 23:53:13 +00:00