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/clpbn/bp/FgBpSolver.cpp

497 lines
13 KiB
C++
Raw Normal View History

2011-12-12 15:29:51 +00:00
#include <cassert>
#include <limits>
#include <algorithm>
#include <iostream>
#include "FgBpSolver.h"
#include "FactorGraph.h"
#include "Factor.h"
2012-03-22 11:33:24 +00:00
#include "Indexer.h"
#include "Horus.h"
2011-12-12 15:29:51 +00:00
FgBpSolver::FgBpSolver (const FactorGraph& fg) : Solver (&fg)
{
factorGraph_ = &fg;
}
FgBpSolver::~FgBpSolver (void)
{
for (unsigned i = 0; i < varsI_.size(); i++) {
delete varsI_[i];
}
for (unsigned i = 0; i < facsI_.size(); i++) {
delete facsI_[i];
}
for (unsigned i = 0; i < links_.size(); i++) {
delete links_[i];
}
}
void
FgBpSolver::runSolver (void)
{
clock_t start;
2012-03-31 23:27:37 +01:00
if (Constants::COLLECT_STATS) {
2011-12-12 15:29:51 +00:00
start = clock();
}
2012-03-22 11:33:24 +00:00
runLoopySolver();
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
2012-03-22 11:33:24 +00:00
cout << endl;
if (nIters_ < BpOptions::maxIter) {
cout << "Sum-Product converged in " ;
cout << nIters_ << " iterations" << endl;
} else {
cout << "The maximum number of iterations was hit, terminating..." ;
2011-12-12 15:29:51 +00:00
cout << endl;
}
}
unsigned size = factorGraph_->getVarNodes().size();
2012-03-31 23:27:37 +01:00
if (Constants::COLLECT_STATS) {
2011-12-12 15:29:51 +00:00
unsigned nIters = 0;
bool loopy = factorGraph_->isTree() == false;
if (loopy) nIters = nIters_;
double time = (double (clock() - start)) / CLOCKS_PER_SEC;
Statistics::updateStatistics (size, loopy, nIters, time);
}
}
2012-03-22 11:33:24 +00:00
Params
2011-12-12 15:29:51 +00:00
FgBpSolver::getPosterioriOf (VarId vid)
{
assert (factorGraph_->getFgVarNode (vid));
FgVarNode* var = factorGraph_->getFgVarNode (vid);
2012-03-22 11:33:24 +00:00
Params probs;
2011-12-12 15:29:51 +00:00
if (var->hasEvidence()) {
2012-03-31 23:27:37 +01:00
probs.resize (var->nrStates(), LogAware::noEvidence());
probs[var->getEvidence()] = LogAware::withEvidence();
2011-12-12 15:29:51 +00:00
} else {
2012-03-31 23:27:37 +01:00
probs.resize (var->nrStates(), LogAware::multIdenty());
2011-12-12 15:29:51 +00:00
const SpLinkSet& links = ninf(var)->getLinks();
2012-03-22 11:33:24 +00:00
if (Globals::logDomain) {
for (unsigned i = 0; i < links.size(); i++) {
Util::add (probs, links[i]->getMessage());
}
2012-03-31 23:27:37 +01:00
LogAware::normalize (probs);
2012-03-22 11:33:24 +00:00
Util::fromLog (probs);
} else {
for (unsigned i = 0; i < links.size(); i++) {
Util::multiply (probs, links[i]->getMessage());
}
2012-03-31 23:27:37 +01:00
LogAware::normalize (probs);
2011-12-12 15:29:51 +00:00
}
}
return probs;
}
2012-03-22 11:33:24 +00:00
Params
FgBpSolver::getJointDistributionOf (const VarIds& jointVarIds)
2011-12-12 15:29:51 +00:00
{
2012-03-31 23:27:37 +01:00
int idx = -1;
2012-03-22 11:33:24 +00:00
FgVarNode* vn = factorGraph_->getFgVarNode (jointVarIds[0]);
const FgFacSet& factorNodes = vn->neighbors();
for (unsigned i = 0; i < factorNodes.size(); i++) {
if (factorNodes[i]->factor()->contains (jointVarIds)) {
idx = i;
break;
2011-12-12 15:29:51 +00:00
}
}
2012-03-22 11:33:24 +00:00
if (idx == -1) {
return getJointByConditioning (jointVarIds);
} else {
2012-03-31 23:27:37 +01:00
Factor res (*factorNodes[idx]->factor());
2012-03-22 11:33:24 +00:00
const SpLinkSet& links = ninf(factorNodes[idx])->getLinks();
for (unsigned i = 0; i < links.size(); i++) {
Factor msg (links[i]->getVariable()->varId(),
links[i]->getVariable()->nrStates(),
getVar2FactorMsg (links[i]));
2012-03-31 23:27:37 +01:00
res.multiply (msg);
2012-03-22 11:33:24 +00:00
}
2012-03-31 23:27:37 +01:00
res.sumOutAllExcept (jointVarIds);
res.reorderArguments (jointVarIds);
res.normalize();
Params jointDist = res.params();
2012-03-22 11:33:24 +00:00
if (Globals::logDomain) {
Util::fromLog (jointDist);
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
return jointDist;
2011-12-12 15:29:51 +00:00
}
}
void
FgBpSolver::runLoopySolver (void)
{
initializeSolver();
nIters_ = 0;
while (!converged() && nIters_ < BpOptions::maxIter) {
nIters_ ++;
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
Util::printHeader (" Iteration " + nIters_);
2011-12-12 15:29:51 +00:00
cout << endl;
}
switch (BpOptions::schedule) {
case BpOptions::Schedule::SEQ_RANDOM:
random_shuffle (links_.begin(), links_.end());
// no break
case BpOptions::Schedule::SEQ_FIXED:
for (unsigned i = 0; i < links_.size(); i++) {
calculateAndUpdateMessage (links_[i]);
}
break;
case BpOptions::Schedule::PARALLEL:
for (unsigned i = 0; i < links_.size(); i++) {
calculateMessage (links_[i]);
}
for (unsigned i = 0; i < links_.size(); i++) {
updateMessage(links_[i]);
}
break;
case BpOptions::Schedule::MAX_RESIDUAL:
maxResidualSchedule();
break;
}
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
2011-12-12 15:29:51 +00:00
cout << endl;
}
}
}
void
FgBpSolver::initializeSolver (void)
{
const FgVarSet& varNodes = factorGraph_->getVarNodes();
for (unsigned i = 0; i < varsI_.size(); i++) {
delete varsI_[i];
}
varsI_.reserve (varNodes.size());
for (unsigned i = 0; i < varNodes.size(); i++) {
varsI_.push_back (new SPNodeInfo());
}
const FgFacSet& facNodes = factorGraph_->getFactorNodes();
for (unsigned i = 0; i < facsI_.size(); i++) {
delete facsI_[i];
}
facsI_.reserve (facNodes.size());
for (unsigned i = 0; i < facNodes.size(); i++) {
facsI_.push_back (new SPNodeInfo());
}
for (unsigned i = 0; i < links_.size(); i++) {
delete links_[i];
}
createLinks();
for (unsigned i = 0; i < links_.size(); i++) {
FgFacNode* src = links_[i]->getFactor();
FgVarNode* dst = links_[i]->getVariable();
ninf (dst)->addSpLink (links_[i]);
ninf (src)->addSpLink (links_[i]);
}
}
void
FgBpSolver::createLinks (void)
{
const FgFacSet& facNodes = factorGraph_->getFactorNodes();
for (unsigned i = 0; i < facNodes.size(); i++) {
const FgVarSet& neighbors = facNodes[i]->neighbors();
for (unsigned j = 0; j < neighbors.size(); j++) {
links_.push_back (new SpLink (facNodes[i], neighbors[j]));
}
}
}
bool
FgBpSolver::converged (void)
{
if (links_.size() == 0) {
return true;
}
if (nIters_ == 0 || nIters_ == 1) {
return false;
}
bool converged = true;
if (BpOptions::schedule == BpOptions::Schedule::MAX_RESIDUAL) {
2012-03-22 11:33:24 +00:00
double maxResidual = (*(sortedOrder_.begin()))->getResidual();
2011-12-12 15:29:51 +00:00
if (maxResidual > BpOptions::accuracy) {
converged = false;
} else {
converged = true;
}
} else {
for (unsigned i = 0; i < links_.size(); i++) {
double residual = links_[i]->getResidual();
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
2011-12-12 15:29:51 +00:00
cout << links_[i]->toString() + " residual = " << residual << endl;
}
if (residual > BpOptions::accuracy) {
converged = false;
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG == 0) break;
2011-12-12 15:29:51 +00:00
}
}
}
return converged;
}
void
FgBpSolver::maxResidualSchedule (void)
{
if (nIters_ == 1) {
for (unsigned i = 0; i < links_.size(); i++) {
calculateMessage (links_[i]);
SortedOrder::iterator it = sortedOrder_.insert (links_[i]);
linkMap_.insert (make_pair (links_[i], it));
}
return;
}
for (unsigned c = 0; c < links_.size(); c++) {
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
2011-12-12 15:29:51 +00:00
cout << "current residuals:" << endl;
for (SortedOrder::iterator it = sortedOrder_.begin();
it != sortedOrder_.end(); it ++) {
cout << " " << setw (30) << left << (*it)->toString();
cout << "residual = " << (*it)->getResidual() << endl;
}
}
SortedOrder::iterator it = sortedOrder_.begin();
SpLink* link = *it;
if (link->getResidual() < BpOptions::accuracy) {
return;
}
updateMessage (link);
link->clearResidual();
sortedOrder_.erase (it);
linkMap_.find (link)->second = sortedOrder_.insert (link);
// update the messages that depend on message source --> destin
const FgFacSet& factorNeighbors = link->getVariable()->neighbors();
for (unsigned i = 0; i < factorNeighbors.size(); i++) {
if (factorNeighbors[i] != link->getFactor()) {
const SpLinkSet& links = ninf(factorNeighbors[i])->getLinks();
for (unsigned j = 0; j < links.size(); j++) {
if (links[j]->getVariable() != link->getVariable()) {
calculateMessage (links[j]);
SpLinkMap::iterator iter = linkMap_.find (links[j]);
sortedOrder_.erase (iter->second);
iter->second = sortedOrder_.insert (links[j]);
}
}
}
}
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 2) {
Util::printDashedLine();
2011-12-12 15:29:51 +00:00
}
}
}
void
FgBpSolver::calculateFactor2VariableMsg (SpLink* link) const
{
const FgFacNode* src = link->getFactor();
const FgVarNode* dst = link->getVariable();
const SpLinkSet& links = ninf(src)->getLinks();
// calculate the product of messages that were sent
// to factor `src', except from var `dst'
unsigned msgSize = 1;
for (unsigned i = 0; i < links.size(); i++) {
msgSize *= links[i]->getVariable()->nrStates();
}
unsigned repetitions = 1;
2012-03-31 23:27:37 +01:00
Params msgProduct (msgSize, LogAware::multIdenty());
2012-03-22 11:33:24 +00:00
if (Globals::logDomain) {
for (int i = links.size() - 1; i >= 0; i--) {
if (links[i]->getVariable() != dst) {
Util::add (msgProduct, getVar2FactorMsg (links[i]), repetitions);
repetitions *= links[i]->getVariable()->nrStates();
} else {
unsigned ds = links[i]->getVariable()->nrStates();
Util::add (msgProduct, Params (ds, 1.0), repetitions);
repetitions *= ds;
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
}
} else {
for (int i = links.size() - 1; i >= 0; i--) {
if (links[i]->getVariable() != dst) {
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
2012-03-22 11:33:24 +00:00
cout << " message from " << links[i]->getVariable()->label();
cout << ": " << endl;
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
Util::multiply (msgProduct, getVar2FactorMsg (links[i]), repetitions);
repetitions *= links[i]->getVariable()->nrStates();
} else {
unsigned ds = links[i]->getVariable()->nrStates();
Util::multiply (msgProduct, Params (ds, 1.0), repetitions);
repetitions *= ds;
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
}
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
2012-03-31 23:27:37 +01:00
Factor result (src->factor()->arguments(),
src->factor()->ranges(),
2011-12-12 15:29:51 +00:00
msgProduct);
2012-03-22 11:33:24 +00:00
result.multiply (*(src->factor()));
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
cout << " message product: " << msgProduct << endl;
cout << " original factor: " << src->params() << endl;
cout << " factor product: " << result.params() << endl;
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
result.sumOutAllExcept (dst->varId());
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
2011-12-12 15:29:51 +00:00
cout << " marginalized: " ;
2012-03-31 23:27:37 +01:00
cout << result.params() << endl;
2011-12-12 15:29:51 +00:00
}
2012-03-31 23:27:37 +01:00
const Params& resultParams = result.params();
2012-03-22 11:33:24 +00:00
Params& message = link->getNextMessage();
2011-12-12 15:29:51 +00:00
for (unsigned i = 0; i < resultParams.size(); i++) {
message[i] = resultParams[i];
}
2012-03-31 23:27:37 +01:00
LogAware::normalize (message);
if (Constants::DEBUG >= 5) {
cout << " curr msg: " << link->getMessage() << endl;
cout << " next msg: " << message << endl;
2011-12-12 15:29:51 +00:00
}
}
2012-03-22 11:33:24 +00:00
Params
2011-12-12 15:29:51 +00:00
FgBpSolver::getVar2FactorMsg (const SpLink* link) const
{
const FgVarNode* src = link->getVariable();
const FgFacNode* dst = link->getFactor();
2012-03-22 11:33:24 +00:00
Params msg;
2011-12-12 15:29:51 +00:00
if (src->hasEvidence()) {
2012-03-31 23:27:37 +01:00
msg.resize (src->nrStates(), LogAware::noEvidence());
msg[src->getEvidence()] = LogAware::withEvidence();
if (Constants::DEBUG >= 5) {
cout << msg;
2011-12-12 15:29:51 +00:00
}
} else {
2012-03-31 23:27:37 +01:00
msg.resize (src->nrStates(), LogAware::one());
2011-12-12 15:29:51 +00:00
}
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
cout << msg;
2011-12-12 15:29:51 +00:00
}
const SpLinkSet& links = ninf (src)->getLinks();
2012-03-22 11:33:24 +00:00
if (Globals::logDomain) {
for (unsigned i = 0; i < links.size(); i++) {
if (links[i]->getFactor() != dst) {
Util::add (msg, links[i]->getMessage());
2011-12-12 15:29:51 +00:00
}
2012-03-22 11:33:24 +00:00
}
} else {
for (unsigned i = 0; i < links.size(); i++) {
if (links[i]->getFactor() != dst) {
Util::multiply (msg, links[i]->getMessage());
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
cout << " x " << links[i]->getMessage();
2011-12-12 15:29:51 +00:00
}
}
2012-03-22 11:33:24 +00:00
}
2011-12-12 15:29:51 +00:00
}
2012-03-31 23:27:37 +01:00
if (Constants::DEBUG >= 5) {
cout << " = " << msg;
2011-12-12 15:29:51 +00:00
}
return msg;
}
2012-03-22 11:33:24 +00:00
Params
FgBpSolver::getJointByConditioning (const VarIds& jointVarIds) const
{
FgVarSet jointVars;
for (unsigned i = 0; i < jointVarIds.size(); i++) {
assert (factorGraph_->getFgVarNode (jointVarIds[i]));
jointVars.push_back (factorGraph_->getFgVarNode (jointVarIds[i]));
}
FactorGraph* fg = new FactorGraph (*factorGraph_);
FgBpSolver solver (*fg);
solver.runSolver();
Params prevBeliefs = solver.getPosterioriOf (jointVarIds[0]);
VarIds observedVids = {jointVars[0]->varId()};
for (unsigned i = 1; i < jointVarIds.size(); i++) {
assert (jointVars[i]->hasEvidence() == false);
Params newBeliefs;
VarNodes observedVars;
for (unsigned j = 0; j < observedVids.size(); j++) {
observedVars.push_back (fg->getFgVarNode (observedVids[j]));
}
StatesIndexer idx (observedVars, false);
while (idx.valid()) {
for (unsigned j = 0; j < observedVars.size(); j++) {
observedVars[j]->setEvidence (idx[j]);
}
++ idx;
FgBpSolver solver (*fg);
solver.runSolver();
Params beliefs = solver.getPosterioriOf (jointVarIds[i]);
for (unsigned k = 0; k < beliefs.size(); k++) {
newBeliefs.push_back (beliefs[k]);
}
}
int count = -1;
for (unsigned j = 0; j < newBeliefs.size(); j++) {
if (j % jointVars[i]->nrStates() == 0) {
count ++;
}
newBeliefs[j] *= prevBeliefs[count];
}
prevBeliefs = newBeliefs;
observedVids.push_back (jointVars[i]->varId());
}
return prevBeliefs;
}
2011-12-12 15:29:51 +00:00
void
FgBpSolver::printLinkInformation (void) const
{
for (unsigned i = 0; i < links_.size(); i++) {
SpLink* l = links_[i];
cout << l->toString() << ":" << endl;
cout << " curr msg = " ;
2012-03-31 23:27:37 +01:00
cout << l->getMessage() << endl;
2011-12-12 15:29:51 +00:00
cout << " next msg = " ;
2012-03-31 23:27:37 +01:00
cout << l->getNextMessage() << endl;
2011-12-12 15:29:51 +00:00
cout << " residual = " << l->getResidual() << endl;
}
}