VariableState Class Reference

Represents the state of propositional variables and clauses. More...

#include <variablestate.h>

List of all members.

Public Member Functions

 VariableState (GroundPredicateHashArray *const &unknownQueries, GroundPredicateHashArray *const &knownQueries, Array< TruthValue > *const &knownQueryValues, const Array< int > *const &allPredGndingsAreQueries, const bool &markHardGndClauses, const bool &trackParentClauseWts, const MLN *const &mln, const Domain *const &domain, const bool &lazy)
 Constructor for a VariableState.
 ~VariableState ()
 Destructor.
void addNewClauses (bool initial)
 New clauses are added to the state.
void init ()
 Information about the state is reset and initialized.
void initRandom ()
 Makes a random truth assigment to all (active) atoms.
void initBlocksRandom ()
 Sets one atom in each block to true and the rest to false.
void initMakeBreakCostWatch (const int &startClause)
 Initialize makeCost and breakCost and watch arrays based on the current variable assignment.
int getNumAtoms ()
int getNumClauses ()
int getNumDeadClauses ()
int getIndexOfRandomAtom ()
 Returns the absolute index of a random atom.
int getIndexOfAtomInRandomFalseClause ()
 Returns the absolute index of a random atom in a random unsatisfied pos.
int getRandomFalseClauseIndex ()
 Returns the index of a random unsatisfied pos.
long double getCostOfFalseClauses ()
 Returns the cost of the unsatisfied positive and satisfied negative clauses.
int getNumFalseClauses ()
 Returns the number of the unsatisfied positive and satisfied negative clauses.
bool getValueOfAtom (const int &atomIdx)
 Returns the truth value of an atom.
bool getValueOfLowAtom (const int &atomIdx)
 Returns the truth value of an atom in the best state.
void setValueOfAtom (const int &atomIdx, const bool &value)
 Sets the truth value of an atom.
Array< int > & getNegOccurenceArray (const int &atomIdx)
 Retrieves the negative occurence array of an atom.
Array< int > & getPosOccurenceArray (const int &atomIdx)
 Retrieves the positive occurence array of an atom.
void flipAtom (const int &toFlip)
 Flip the truth value of an atom and update info arrays.
void flipAtomValue (const int &atomIdx)
 Flips the truth value of an atom.
long double getImprovementByFlipping (const int &atomIdx)
 Calculates the improvement achieved by flipping an atom.
void activateAtom (const int &atomIdx, const bool &ignoreActivePreds)
 If in lazy mode, an atom is activated and all clauses activated by this atom are added to the state.
bool isActive (const int &atomIdx)
 Checks if an atom is active.
bool isActive (const Predicate *pred)
 Checks if an atom is active.
Array< int > & getOccurenceArray (const int &idx)
 Retrieves the occurence array of an atom.
int incrementNumTrueLits (const int &clauseIdx)
 Increments the number of true literals in a clause.
int decrementNumTrueLits (const int &clauseIdx)
 Decrements the number of true literals in a clause.
int getNumTrueLits (const int &clauseIdx)
 Retrieves the number of true literals in a clause.
long double getClauseCost (const int &clauseIdx)
 Retrieves the cost associated with a clause.
Array< int > & getAtomsInClause (const int &clauseIdx)
 Retrieves the atoms in a clauses as an Array of ints.
void addFalseClause (const int &clauseIdx)
 Marks a clause as false in the state.
void removeFalseClause (const int &clauseIdx)
 Unmarks a clause as false in the state.
void addBreakCost (const int &atomIdx, const long double &cost)
 Increases the breakcost of an atom.
void subtractBreakCost (const int &atomIdx, const long double &cost)
 Decreases the breakcost of an atom.
void addBreakCostToAtomsInClause (const int &clauseIdx, const long double &cost)
 Increases breakCost of all atoms in a given clause.
void subtractBreakCostFromAtomsInClause (const int &clauseIdx, const long double &cost)
 Decreases breakCost of all atoms in a given clause.
void addMakeCost (const int &atomIdx, const long double &cost)
 Increases makeCost of an atom.
void subtractMakeCost (const int &atomIdx, const long double &cost)
 Decreases makeCost of an atom.
void addMakeCostToAtomsInClause (const int &clauseIdx, const long double &cost)
 Increases makeCost of all atoms in a given clause.
void subtractMakeCostFromAtomsInClause (const int &clauseIdx, const long double &cost)
 Decreases makeCost of all atoms in a given clause.
const int getTrueLiteralOtherThan (const int &clauseIdx, const int &atomIdx1, const int &atomIdx2)
 Retrieves a true literal in a clause other than the two given.
const bool isTrueLiteral (const int &literal)
 Checks if a literal is true (Negated and false or non-negated an true).
const int getAtomInClause (const int &atomIdxInClause, const int &clauseIdx)
 Retrieves the absolute index of the nth atom in a clause.
const int getRandomAtomInClause (const int &clauseIdx)
 Retrieves the absolute index of a random atom in a clause.
const int getRandomTrueLitInClause (const int &clauseIdx)
 Retrieves the index of a random true literal in a clause.
const double getMaxClauseWeight ()
const long double getMakeCost (const int &atomIdx)
const long double getBreakCost (const int &atomIdx)
const int getClauseSize (const int &clauseIdx)
const int getWatch1 (const int &clauseIdx)
void setWatch1 (const int &clauseIdx, const int &atomIdx)
const int getWatch2 (const int &clauseIdx)
void setWatch2 (const int &clauseIdx, const int &atomIdx)
const bool isBlockEvidence (const int &blockIdx)
const int getBlockSize (const int &blockIdx)
const int getBlockIndex (const int &atomIdx)
 Returns the index of the block which the atom with index atomIdx is in.
Array< int > & getBlockArray (const int &blockIdx)
bool getBlockEvidence (const int &blockIdx)
int getNumBlocks ()
const long double getLowCost ()
 Returns the cost of bad clauses in the optimum state.
const int getLowBad ()
 Returns the number of bad clauses in the optimum state.
void makeUnitCosts ()
 Turns all costs into units.
void saveLowState ()
 Save current assignment as an optimum state.
int getTrueFixedAtomInBlock (const int blockIdx)
 Returns index in block if a true fixed atom is in block, otherwise -1.
const GroundPredicateHashArraygetGndPredHashArrayPtr () const
const GroundPredicateHashArraygetUnePreds () const
const GroundPredicateHashArraygetKnePreds () const
const Array< TruthValue > * getKnePredValues () const
void setGndClausesWtsToSumOfParentWts ()
 Sets the weight of a ground clause to the sum of its parents' weights.
void getNumClauseGndings (Array< double > *const &numGndings, bool tv)
 Gets the number of (true or false) clause groundings in this state.
void getNumClauseGndings (double numGndings[], int clauseCnt, bool tv)
 Gets the number of (true or false) clause groundings in this state.
void getNumClauseGndingsWithUnknown (double numGndings[], int clauseCnt, bool tv, const Array< bool > *const &unknownPred)
 Gets the number of (true or false) clause groundings in this state.
void setOthersInBlockToFalse (const int &atomIdx, const int &blockIdx)
 Sets the truth values of all atoms in a block except for the one given.
void fixAtom (const int &atomIdx, const bool &value)
 Fixes an atom to a truth value.
Array< int > * simplifyClauseFromFixedAtoms (const int &clauseIdx)
 Simplifies a clause using atoms which have been fixed.
const bool isDeadClause (const int &clauseIdx)
 Checks if a clause is dead.
void eliminateSoftClauses ()
 Marks soft clauses as dead.
void killClauses (const int &startClause)
 Marks clauses as dead which were not good in the previous iteration of inference or are not picked according to a weighted coin flip.
const bool clauseGoodInPrevious (const int &clauseIdx)
 Checks if a clause was good in the previous iteration of inference, i.e.
void resetDeadClauses ()
 Resets all dead clauses to be alive again.
void resetFixedAtoms ()
 Resets all fixed atoms to be not fixed again.
void setLazy (const bool &l)
const bool getLazy ()
void setUseThreshold (const bool &t)
const bool getUseThreshold ()
long double getHardWt ()
const DomaingetDomain ()
const MLNgetMLN ()
void printLowState (ostream &out)
 Prints the best state found to a stream.
void printGndPred (const int &predIndex, ostream &out)
 Prints a ground predicate to a stream.
GroundPredicategetGndPred (const int &index)
 Gets a pointer to a GroundPredicate.
GroundClausegetGndClause (const int &index)
 Gets a pointer to a GroundClause.
void saveLowStateToGndPreds ()
 The atom assignment in the best state is saved to the ground predicates.
void saveLowStateToDB ()
 The atom assignment in the best state is saved to the database.
const int getGndPredIndex (GroundPredicate *const &gndPred)
 Gets the index of a GroundPredicate in this state.
void getActiveClauses (Predicate *inputPred, Array< GroundClause * > &activeClauses, bool const &active, bool const &ignoreActivePreds)
 Gets clauses and weights activated by the predicate inputPred, if active is true.
void getActiveClauses (Array< GroundClause * > &allClauses, bool const &ignoreActivePreds)
 Get all the active clauses in the database.
int getNumActiveAtoms ()
void addOneAtomToEachBlock ()
 Selects one atom in each block in the domain and adds it to the block here and sets it to true.
void initLazyBlocks ()
 Initializes the block structures for the lazy version.
void fillLazyBlocks ()
 Fills the blocks with the predicates in the domain blocks.


Detailed Description

Represents the state of propositional variables and clauses.

Some of this code is based on the MaxWalkSat package of Kautz et al.

All inference algorithms should have a VariableState to access the information needed in its predicates and clauses.

Each atom has its own index starting at 1. The negation of an atom with index a is represented by -a (this is why the indices do not start at 0). Each clause has its own index starting at 0.

A VariableState is either eager or lazy. Eager states build an MRF upfront based on an MLN and a domain. Thus, all ground clauses and predicates are in memory after building the MRF. Lazy states activate atoms and clauses as they are needed from the MLN and domain. An atom is activated if it is in an unsatisfied clause with the assumption of all atoms being false or if it is looked at during inference (it is flipped or the cost of flipping it is computed). Active clauses are those which contain active atoms.

Definition at line 93 of file variablestate.h.


Constructor & Destructor Documentation

VariableState::VariableState ( GroundPredicateHashArray *const &  unknownQueries,
GroundPredicateHashArray *const &  knownQueries,
Array< TruthValue > *const &  knownQueryValues,
const Array< int > *const &  allPredGndingsAreQueries,
const bool &  markHardGndClauses,
const bool &  trackParentClauseWts,
const MLN *const &  mln,
const Domain *const &  domain,
const bool &  lazy 
) [inline]

Constructor for a VariableState.

The hard clause weight is set. In lazy mode, the initial active atoms and clauses are retrieved and in eager mode, the MRF is built and the atoms and clauses are retrieved from it. In addition, all information arrays are filled with information.

Parameters:
unknownQueries Query predicates with unknown values used to build MRF in eager mode.
knownQueries Query predicates with known values used to build MRF in eager mode.
knownQueryValues Truth values of the known query predicates.
allPredGndingsAreQueries Array used to build MRF in eager mode.
mln mln and domain are used to build MRF in eager state and to retrieve active atoms in lazy state.
domain mln and domain are used to build MRF in eager state and to retrieve active atoms in lazy state.
lazy Flag stating whether lazy mode is used or not.

Definition at line 115 of file variablestate.h.

References addNewClauses(), addOneAtomToEachBlock(), HashArray< Type, HashFn, EqualFn >::append(), Array< Type >::clear(), MRF::deleteGndPredsGndClauseSets(), fillLazyBlocks(), getActiveClauses(), MRF::getBlockEvidence(), MRF::getBlocks(), Domain::getDB(), MRF::getGndClauses(), MRF::getGndPreds(), getNumClauses(), initLazyBlocks(), Database::setActiveStatus(), Database::setPerformingInference(), HashArray< Type, HashFn, EqualFn >::size(), and Array< Type >::size().

00123   {
00124     this->mln_ = (MLN*)mln;
00125     this->domain_ = (Domain*)domain;
00126     this->lazy_ = lazy;
00127 
00128       // Instantiate information
00129     baseNumAtoms_ = 0;
00130     activeAtoms_ = 0;
00131     numFalseClauses_ = 0;
00132     costOfFalseClauses_ = 0.0;
00133     lowCost_ = LDBL_MAX;
00134     lowBad_ = INT_MAX;
00135 
00136       // Clauses and preds are stored in gndClauses_ and gndPreds_
00137     gndClauses_ = new Array<GroundClause*>;
00138     gndPreds_ = new Array<GroundPredicate*>;
00139 
00140       // Set the hard clause weight
00141     setHardClauseWeight();
00142 
00143       // Lazy version: Produce state with initial active atoms and clauses
00144     if (lazy_)
00145     {
00146         // Unknown preds are treated as false
00147       domain_->getDB()->setPerformingInference(true);
00148 
00149         // Blocks are copied from the domain
00150       initLazyBlocks();
00151 
00152       clauseLimit_ = INT_MAX;
00153       noApprox_ = false;
00154       haveDeactivated_ = false;
00155 
00157         // Get initial set of active atoms (atoms in unsat. clauses)
00158         // Assumption is: all atoms are initially false except those in blocks
00159 
00160         // One atom in each block is set to true and activated
00161       addOneAtomToEachBlock();
00162 
00163 //cout << "After addOneAtomToEachBlock" << endl;
00164 //for (int i = 1; i < atom_.size(); i++)
00165 //  cout << atom_[i] << endl;
00166 
00167       bool ignoreActivePreds = false;
00168       getActiveClauses(newClauses_, ignoreActivePreds);
00169       int defaultCnt = newClauses_.size();
00170       long double defaultCost = 0;
00171 
00172       for (int i = 0; i < defaultCnt; i++)
00173       {
00174         if (newClauses_[i]->isHardClause())
00175           defaultCost += hardWt_;
00176         else
00177           defaultCost += abs(newClauses_[i]->getWt());
00178       }
00179 
00180         // Clear ground clauses in the ground preds
00181       for (int i = 0; i < gndPredHashArray_.size(); i++)
00182         gndPredHashArray_[i]->removeGndClauses();
00183 
00184         // Delete new clauses
00185       for (int i = 0; i < newClauses_.size(); i++)
00186         delete newClauses_[i];
00187       newClauses_.clear();
00188 
00189       baseNumAtoms_ = gndPredHashArray_.size();
00190       cout << "Number of Baseatoms = " << baseNumAtoms_ << endl;
00191       cout << "Default => Cost\t" << "******\t" << " Clause Cnt\t" << endl;
00192       cout << "           " << defaultCost << "\t" << "******\t" << defaultCnt
00193            << "\t" << endl << endl;
00194 
00195         // Set base atoms as active in DB
00196       for (int i = 0; i < baseNumAtoms_; i++)
00197       {
00198         domain_->getDB()->setActiveStatus(gndPredHashArray_[i], true);
00199         activeAtoms_++;        
00200       }
00201 
00202         // Add the rest of the atoms in the blocks, but don't activate
00203       fillLazyBlocks();
00204 
00205         // Get the initial set of active clauses
00206       ignoreActivePreds = false;
00207       getActiveClauses(newClauses_, ignoreActivePreds);      
00208     } // End lazy version
00209       // Eager version: Use KBMC to produce the state
00210     else
00211     {
00212       unePreds_ = unknownQueries;
00213       knePreds_ = knownQueries;
00214       knePredValues_ = knownQueryValues;
00215 
00216         // MRF is built on known and unknown queries
00217       int size = 0;
00218       if (unknownQueries) size += unknownQueries->size();
00219       if (knownQueries) size += knownQueries->size();
00220       GroundPredicateHashArray* queries = new GroundPredicateHashArray(size);
00221       if (unknownQueries) queries->append(unknownQueries);
00222       if (knownQueries) queries->append(knownQueries);
00223       mrf_ = new MRF(queries, allPredGndingsAreQueries, domain_,
00224                      domain_->getDB(), mln_, markHardGndClauses,
00225                      trackParentClauseWts, -1);
00226         //delete to save space. Can be deleted because no more gndClauses are
00227         //appended to gndPreds beyond this point
00228       mrf_->deleteGndPredsGndClauseSets();
00229         //do not delete the intArrRep in gndPreds_;
00230       delete queries;
00231 
00232         // Blocks built in MRF
00233       blocks_ = mrf_->getBlocks();
00234       blockEvidence_ = mrf_->getBlockEvidence();
00235         
00236         // Put ground clauses in newClauses_
00237       newClauses_ = *(Array<GroundClause*>*)mrf_->getGndClauses();
00238         // Put ground preds in the hash array
00239       //const Array<GroundPredicate*>* gndPreds = mrf_->getGndPreds();
00240       const GroundPredicateHashArray* gndPreds = mrf_->getGndPreds();
00241       for (int i = 0; i < gndPreds->size(); i++)
00242         gndPredHashArray_.append((*gndPreds)[i]);
00243     
00244         // baseNumAtoms_ are all atoms in eager version
00245       baseNumAtoms_ = gndPredHashArray_.size();        
00246     } // End eager version
00247     
00248       // At this point, ground clauses are held in newClauses_
00249       // and ground predicates are held in gndPredHashArray_
00250       // for both versions
00251     
00252       // Add the clauses and preds and fill info arrays
00253     bool initial = true;
00254     addNewClauses(initial);
00255     
00256     cout << "Initial num. of clauses: " << getNumClauses() << endl;
00257   }

VariableState::~VariableState (  )  [inline]

Destructor.

Blocks are deleted in lazy version; MRF is deleted in eager version.

Definition at line 263 of file variablestate.h.

References Array< Type >::size().

00264   {
00265     if (lazy_)
00266     {
00267         // Block information from lazy version is deleted
00268       for (int i = 0; i < blocks_->size(); i++)
00269         (*blocks_)[i].clearAndCompress();
00270       delete blocks_;
00271     
00272       delete blockEvidence_;  
00273     }
00274     else
00275     {
00276         // MRF from eager version is deleted
00277       if (mrf_) delete mrf_;
00278       //if (unePreds_) delete unePreds_;
00279       //if (knePreds_) delete knePreds_;
00280       //if (knePredValues_) delete knePredValues_;
00281     }    
00282   }


Member Function Documentation

void VariableState::addNewClauses ( bool  initial  )  [inline]

New clauses are added to the state.

If not the initialization, then makecost and breakcost are updated for the new atoms.

Parameters:
initial If true, this is the first time new clauses have been added.

Definition at line 292 of file variablestate.h.

References Array< Type >::append(), Array< Type >::clear(), Domain::getDB(), getNumAtoms(), getNumClauses(), Database::getValue(), Array< Type >::growToSize(), initMakeBreakCostWatch(), killClauses(), HashArray< Type, HashFn, EqualFn >::size(), and Array< Type >::size().

Referenced by activateAtom(), addOneAtomToEachBlock(), fillLazyBlocks(), and VariableState().

00293   {
00294     if (vsdebug)
00295       cout << "Adding " << newClauses_.size() << " new clauses.." << endl;
00296 
00297       // Store the old number of clauses and atoms
00298     int oldNumClauses = getNumClauses();
00299     int oldNumAtoms = getNumAtoms();
00300 
00301     gndClauses_->append(newClauses_);
00302     gndPreds_->growToSize(gndPredHashArray_.size());
00303 
00304     int numAtoms = getNumAtoms();
00305     int numClauses = getNumClauses();
00306       // If no new atoms or clauses have been added, then do nothing
00307     if (numAtoms == oldNumAtoms && numClauses == oldNumClauses) return;
00308 
00309     if (vsdebug) cout << "Clauses: " << numClauses << endl;
00310 
00311       // atomIdx starts at 1
00312     atom_.growToSize(numAtoms + 1, false);
00313     makeCost_.growToSize(numAtoms + 1, 0.0);
00314     breakCost_.growToSize(numAtoms + 1, 0.0);
00315     lowAtom_.growToSize(numAtoms + 1, false);
00316     fixedAtom_.growToSize(numAtoms + 1, 0);
00317 
00318       // Copy ground preds to gndPreds_ and set values in atom and lowAtom
00319     for (int i = oldNumAtoms; i < gndPredHashArray_.size(); i++)
00320     {
00321       (*gndPreds_)[i] = gndPredHashArray_[i];
00322 
00323       if (vsdebug)
00324       {
00325         cout << "New pred: ";
00326         (*gndPreds_)[i]->print(cout, domain_);
00327         cout << endl;
00328       }
00329 
00330       lowAtom_[i + 1] = atom_[i + 1] = 
00331         (domain_->getDB()->getValue((*gndPreds_)[i]) == TRUE) ? true : false;
00332     }
00333     newClauses_.clear();
00334 
00335     clause_.growToSize(numClauses);
00336     clauseCost_.growToSize(numClauses);
00337     falseClause_.growToSize(numClauses);
00338     whereFalse_.growToSize(numClauses);
00339     numTrueLits_.growToSize(numClauses);
00340     watch1_.growToSize(numClauses);
00341     watch2_.growToSize(numClauses);
00342     isSatisfied_.growToSize(numClauses, false);
00343     deadClause_.growToSize(numClauses, false);
00344     threshold_.growToSize(numClauses, false);
00345 
00346     occurence_.growToSize(2*numAtoms + 1);
00347 
00348     for (int i = oldNumClauses; i < numClauses; i++)
00349     {
00350       GroundClause* gndClause = (*gndClauses_)[i];
00351 
00352       if (vsdebug)
00353       {
00354         cout << "New clause: ";
00355         gndClause->print(cout, domain_, &gndPredHashArray_);
00356         cout << endl;
00357       }
00358       
00359         // Set thresholds for clause selection
00360       if (gndClause->isHardClause()) threshold_[i] = RAND_MAX;
00361       else
00362       {
00363         double w = gndClause->getWt();
00364         threshold_[i] = RAND_MAX*(1 - exp(-abs(w)));
00365         if (vsdebug)
00366         {
00367           cout << "Weight: " << w << endl;            
00368         }
00369       }
00370       if (vsdebug)
00371         cout << "Threshold: " << threshold_[i] << endl;            
00372       
00373       int numGndPreds = gndClause->getNumGroundPredicates();
00374       clause_[i].growToSize(numGndPreds);
00375 
00376       for (int j = 0; j < numGndPreds; j++) 
00377       {
00378           // idx in gndClause + 1 (negated if neg. literal)
00379         //int idx = gndClause->getGroundPredicateIndex(j);
00380         //assert(idx >= 0);
00381         //int lit = (gndClause->getGroundPredicateSense(j)) ?
00382         //          idx + 1 : -(idx + 1);
00383         int lit = gndClause->getGroundPredicateIndex(j);
00384         clause_[i][j] = lit;
00385         int litIdx = 2*abs(lit) - (lit > 0);
00386         occurence_[litIdx].append(i);
00387       }
00388 
00389         // Hard clause weight has been previously determined
00390       if (gndClause->isHardClause())
00391         clauseCost_[i] = hardWt_;
00392       else
00393         clauseCost_[i] = gndClause->getWt();
00394     }
00395 
00396     if (!initial)
00397     {
00398       //initNumSatLiterals(1, oldNumClauses);
00399       if (useThreshold_)
00400       {
00401         killClauses(oldNumClauses);
00402       }
00403       else
00404       {
00405         initMakeBreakCostWatch(oldNumClauses);
00406       }
00407     }
00408     if (vsdebug) cout << "Done adding new clauses.." << endl;
00409   }

void VariableState::initRandom (  )  [inline]

Makes a random truth assigment to all (active) atoms.

Blocks are taken into account: exactly one atom in the block is set to true and the others are set to false.

Definition at line 432 of file variablestate.h.

References getBlockIndex(), init(), initBlocksRandom(), and setValueOfAtom().

Referenced by MaxWalkSat::init().

00433   {
00434       // Set one in each block to true randomly
00435     initBlocksRandom();
00436 
00437       // Random truth value for all not in blocks
00438     for (int i = 1; i <= baseNumAtoms_; i++)
00439     {
00440         // fixedAtom_[i] = -1: false, fixedAtom_[i] = 1: true
00441       if (fixedAtom_[i] != 0) setValueOfAtom(i, (fixedAtom_[i] == 1));
00442         // Blocks are initialized above
00443       if (getBlockIndex(i - 1) >= 0)
00444       {
00445         if (vsdebug) cout << "Atom " << i << " in block" << endl;
00446         continue;
00447       }
00448         // Not fixed and not in block
00449       else
00450       {
00451         if (vsdebug) cout << "Atom " << i << " not in block" << endl;
00452         setValueOfAtom(i, random() % 2);
00453       }
00454     }
00455     init();
00456   }

void VariableState::initMakeBreakCostWatch ( const int &  startClause  )  [inline]

Initialize makeCost and breakCost and watch arrays based on the current variable assignment.

Parameters:
startClause All clauses with index of this or greater are initialized.

Definition at line 515 of file variablestate.h.

References getClauseSize(), getNumClauses(), and isTrueLiteral().

Referenced by addNewClauses(), eliminateSoftClauses(), init(), killClauses(), and resetDeadClauses().

00516   {
00517     int theTrueLit = -1;
00518       // Initialize breakCost and makeCost in the following:
00519     for (int i = startClause; i < getNumClauses(); i++)
00520     {
00521         // Don't look at dead clauses
00522       if (deadClause_[i]) continue;
00523       int trueLit1 = 0;
00524       int trueLit2 = 0;
00525       long double cost = clauseCost_[i];
00526       numTrueLits_[i] = 0;
00527       for (int j = 0; j < getClauseSize(i); j++)
00528       {
00529         if (isTrueLiteral(clause_[i][j]))
00530         { // ij is true lit
00531           numTrueLits_[i]++;
00532           theTrueLit = abs(clause_[i][j]);
00533           if (!trueLit1) trueLit1 = theTrueLit;
00534           else if (trueLit1 && !trueLit2) trueLit2 = theTrueLit;
00535         }
00536       }
00537 
00538         // Unsatisfied positive-weighted clauses or
00539         // Satisfied negative-weighted clauses
00540       if ((numTrueLits_[i] == 0 && cost > 0) ||
00541           (numTrueLits_[i] > 0 && cost < 0))
00542       {
00543         whereFalse_[i] = numFalseClauses_;
00544         falseClause_[numFalseClauses_] = i;
00545         numFalseClauses_++;
00546         costOfFalseClauses_ += abs(cost);
00547         if (highestCost_ == abs(cost)) {eqHighest_ = true; numHighest_++;}
00548 
00549           // Unsat. pos. clause: increase makeCost_ of all atoms
00550         if (numTrueLits_[i] == 0)
00551           for (int j = 0; j < getClauseSize(i); j++)
00552           {
00553             makeCost_[abs(clause_[i][j])] += cost;
00554           }
00555 
00556           // Sat. neg. clause: increase makeCost_ if one true literal
00557         if (numTrueLits_[i] == 1)
00558         {
00559             // Subtract neg. cost
00560           makeCost_[theTrueLit] -= cost;
00561           watch1_[i] = theTrueLit;
00562         }
00563         else if (numTrueLits_[i] > 1)
00564         {
00565           watch1_[i] = trueLit1;
00566           watch2_[i] = trueLit2;
00567         }
00568       }
00569         // Pos. clauses satisfied by one true literal
00570       else if (numTrueLits_[i] == 1 && cost > 0)
00571       {
00572         breakCost_[theTrueLit] += cost;
00573         watch1_[i] = theTrueLit;
00574       }
00575         // Pos. clauses satisfied by 2 or more true literals
00576       else if (cost > 0)
00577       { /*if (numtruelit[i] == 2)*/
00578         watch1_[i] = trueLit1;
00579         watch2_[i] = trueLit2;
00580       }
00581         // Unsat. neg. clauses: increase breakCost of all atoms
00582       else if (numTrueLits_[i] == 0 && cost < 0)
00583       {
00584         for (int j = 0; j < getClauseSize(i); j++)
00585           breakCost_[abs(clause_[i][j])] -= cost;
00586       }
00587     } // for all clauses
00588   }

int VariableState::getIndexOfAtomInRandomFalseClause (  )  [inline]

Returns the absolute index of a random atom in a random unsatisfied pos.

clause or the absolute index of a random true literal in a random satisfied clause.

Definition at line 617 of file variablestate.h.

References getClauseSize(), and getRandomTrueLitInClause().

Referenced by MaxWalkSat::pickRandom().

00618   {
00619     if (numFalseClauses_ == 0) return NOVALUE;
00620     int clauseIdx = falseClause_[random()%numFalseClauses_];
00621       // Pos. clause: return index of random atom
00622     if (clauseCost_[clauseIdx] > 0)
00623       return abs(clause_[clauseIdx][random()%getClauseSize(clauseIdx)]);
00624       // Neg. clause: find random true lit
00625     else
00626       return getRandomTrueLitInClause(clauseIdx);
00627   }

int VariableState::getRandomFalseClauseIndex (  )  [inline]

Returns the index of a random unsatisfied pos.

clause or a random satisfied neg. clause.

Definition at line 633 of file variablestate.h.

Referenced by MaxWalkSat::pickBest(), and MaxWalkSat::pickTabu().

00634   {
00635     if (numFalseClauses_ == 0) return NOVALUE;
00636     return falseClause_[random()%numFalseClauses_];
00637   }

bool VariableState::getValueOfAtom ( const int &  atomIdx  )  [inline]

Returns the truth value of an atom.

Index of atom whose truth value is returned.

Returns:
Truth value of atom.

Definition at line 663 of file variablestate.h.

Referenced by MaxWalkSat::calculateImprovement(), flipAtom(), and MaxWalkSat::pickRandom().

00664   {
00665     return atom_[atomIdx];
00666   }

bool VariableState::getValueOfLowAtom ( const int &  atomIdx  )  [inline]

Returns the truth value of an atom in the best state.

Index of atom whose truth value is returned.

Returns:
Truth value of atom.

Definition at line 674 of file variablestate.h.

Referenced by UnitPropagation::getProbability(), SAT::getProbability(), UnitPropagation::printProbabilities(), SAT::printProbabilities(), UnitPropagation::printTruePreds(), SAT::printTruePreds(), and MCMC::saveLowStateToChain().

00675   {
00676     return lowAtom_[atomIdx];
00677   }

void VariableState::setValueOfAtom ( const int &  atomIdx,
const bool &  value 
) [inline]

Sets the truth value of an atom.

The truth value is propagated to the database.

Parameters:
atomIdx Index of atom whose value is to be set.
value Truth value being set.

Definition at line 686 of file variablestate.h.

References activateAtom(), Domain::getDB(), isActive(), and Database::setValue().

Referenced by addOneAtomToEachBlock(), fixAtom(), flipAtomValue(), initBlocksRandom(), initRandom(), and setOthersInBlockToFalse().

00687   {
00688     if (vsdebug) cout << "Setting value of atom " << atomIdx 
00689                       << " to " << value << endl;
00690       // If atom already has this value, then do nothing
00691     if (atom_[atomIdx] == value) return;
00692       // Propagate assigment to DB
00693     GroundPredicate* p = gndPredHashArray_[atomIdx - 1];
00694     if (value)
00695     {
00696       domain_->getDB()->setValue(p, TRUE);
00697     }
00698     else
00699     {
00700       domain_->getDB()->setValue(p, FALSE);
00701     }
00702       // If not active, then activate it
00703     if (lazy_ && !isActive(atomIdx))
00704     {
00705       bool ignoreActivePreds = false;
00706       activateAtom(atomIdx, ignoreActivePreds);
00707     }
00708     atom_[atomIdx] = value;
00709   }

void VariableState::flipAtom ( const int &  toFlip  )  [inline]

Flip the truth value of an atom and update info arrays.

Parameters:
toFlip Index of atom to be flipped.

Definition at line 734 of file variablestate.h.

References addBreakCost(), addBreakCostToAtomsInClause(), addFalseClause(), addMakeCost(), addMakeCostToAtomsInClause(), decrementNumTrueLits(), flipAtomValue(), getClauseCost(), getOccurenceArray(), getTrueLiteralOtherThan(), getValueOfAtom(), getWatch1(), getWatch2(), incrementNumTrueLits(), removeFalseClause(), setWatch1(), setWatch2(), and Array< Type >::size().

Referenced by MaxWalkSat::flipAtom(), and getImprovementByFlipping().

00735   {
00736     bool toFlipValue = getValueOfAtom(toFlip);
00737     register int clauseIdx;
00738     int sign;
00739     int oppSign;
00740     int litIdx;
00741     if (toFlipValue)
00742       sign = 1;
00743     else
00744       sign = 0;
00745     oppSign = sign ^ 1;
00746 
00747     flipAtomValue(toFlip);
00748     
00749       // Update all clauses in which the atom occurs as a true literal
00750     litIdx = 2*toFlip - sign;
00751     Array<int>& posOccArray = getOccurenceArray(litIdx);
00752     for (int i = 0; i < posOccArray.size(); i++)
00753     {
00754       clauseIdx = posOccArray[i];
00755         // Don't look at dead clauses
00756       if (deadClause_[clauseIdx]) continue;
00757         // The true lit became a false lit
00758       int numTrueLits = decrementNumTrueLits(clauseIdx);
00759       long double cost = getClauseCost(clauseIdx);
00760       int watch1 = getWatch1(clauseIdx);
00761       int watch2 = getWatch2(clauseIdx);
00762 
00763         // 1. If last true lit was flipped, then we have to update
00764         // the makecost / breakcost info accordingly        
00765       if (numTrueLits == 0)
00766       {
00767           // Pos. clause
00768         if (cost > 0)
00769         {
00770             // Add this clause as false in the state
00771           addFalseClause(clauseIdx);
00772             // Decrease toFlip's breakcost (add neg. cost)
00773           addBreakCost(toFlip, -cost);
00774             // Increase makecost of all vars in clause (add pos. cost)
00775           addMakeCostToAtomsInClause(clauseIdx, cost);
00776         }
00777           // Neg. clause
00778         else
00779         {
00780           assert(cost < 0);
00781             // Remove this clause as false in the state
00782           removeFalseClause(clauseIdx);
00783             // Increase breakcost of all vars in clause (add pos. cost)
00784           addBreakCostToAtomsInClause(clauseIdx, -cost);        
00785             // Decrease toFlip's makecost (add neg. cost)
00786           addMakeCost(toFlip, cost);
00787         }
00788       }
00789         // 2. If there is now one true lit left, then move watch2
00790         // up to watch1 and increase the breakcost / makecost of watch1
00791       else if (numTrueLits == 1)
00792       {
00793         if (watch1 == toFlip)
00794         {
00795           assert(watch1 != watch2);
00796           setWatch1(clauseIdx, watch2);
00797           watch1 = getWatch1(clauseIdx);
00798         }
00799 
00800           // Pos. clause: Increase toFlip's breakcost (add pos. cost)
00801         if (cost > 0)
00802         {
00803           addBreakCost(watch1, cost);
00804         }
00805           // Neg. clause: Increase toFlip's makecost (add pos. cost)
00806         else
00807         {
00808           assert(cost < 0);
00809           addMakeCost(watch1, -cost);
00810         }
00811       }
00812         // 3. If there are 2 or more true lits left, then we have to
00813         // find a new true lit to watch if one was flipped
00814       else
00815       { /* numtruelit[clauseIdx] >= 2 */
00816           // If watch1[clauseIdx] has been flipped
00817         if (watch1 == toFlip)
00818         {
00819             // find a different true literal to watch
00820           int diffTrueLit = getTrueLiteralOtherThan(clauseIdx, watch1, watch2);
00821           setWatch1(clauseIdx, diffTrueLit);
00822         }
00823           // If watch2[clauseIdx] has been flipped
00824         else if (watch2 == toFlip)
00825         {
00826             // find a different true literal to watch
00827           int diffTrueLit = getTrueLiteralOtherThan(clauseIdx, watch1, watch2);
00828           setWatch2(clauseIdx, diffTrueLit);
00829         }
00830       }
00831     }
00832         
00833       // Update all clauses in which the atom occurs as a false literal
00834     litIdx = 2*toFlip - oppSign;
00835     Array<int>& negOccArray = getOccurenceArray(litIdx);
00836     for (int i = 0; i < negOccArray.size(); i++)
00837     {
00838       clauseIdx = negOccArray[i];
00839         // Don't look at dead clauses
00840       if (deadClause_[clauseIdx]) continue;
00841         // The false lit became a true lit
00842       int numTrueLits = incrementNumTrueLits(clauseIdx);
00843       long double cost = getClauseCost(clauseIdx);
00844       int watch1 = getWatch1(clauseIdx);
00845 
00846         // 1. If this is the only true lit, then we have to update
00847         // the makecost / breakcost info accordingly        
00848       if (numTrueLits == 1)
00849       {
00850           // Pos. clause
00851         if (cost > 0)
00852         {
00853             // Remove this clause as false in the state
00854           removeFalseClause(clauseIdx);
00855             // Increase toFlip's breakcost (add pos. cost)
00856           addBreakCost(toFlip, cost);        
00857             // Decrease makecost of all vars in clause (add neg. cost)
00858           addMakeCostToAtomsInClause(clauseIdx, -cost);
00859         }
00860           // Neg. clause
00861         else
00862         {
00863           assert(cost < 0);
00864             // Add this clause as false in the state
00865           addFalseClause(clauseIdx);
00866             // Decrease breakcost of all vars in clause (add neg. cost)
00867           addBreakCostToAtomsInClause(clauseIdx, cost);
00868             // Increase toFlip's makecost (add pos. cost)
00869           addMakeCost(toFlip, -cost);
00870         }
00871           // Watch this atom
00872         setWatch1(clauseIdx, toFlip);
00873       }
00874         // 2. If there are now exactly 2 true lits, then watch second atom
00875         // and update breakcost
00876       else
00877       if (numTrueLits == 2)
00878       {
00879         if (cost > 0)
00880         {
00881             // Pos. clause
00882             // Decrease breakcost of first atom being watched (add neg. cost)
00883           addBreakCost(watch1, -cost);
00884         }
00885         else
00886         {
00887             // Neg. clause
00888           assert(cost < 0);
00889             // Decrease makecost of first atom being watched (add neg. cost)
00890           addMakeCost(watch1, cost);
00891         }
00892         
00893           // Watch second atom
00894         setWatch2(clauseIdx, toFlip);
00895       }
00896     }
00897   }

void VariableState::flipAtomValue ( const int &  atomIdx  )  [inline]

Flips the truth value of an atom.

If in lazy mode, the truth value is propagated to the database.

Definition at line 903 of file variablestate.h.

References setValueOfAtom().

Referenced by flipAtom(), and MaxWalkSat::reconstructLowState().

00904   {
00905     bool opposite = !atom_[atomIdx];
00906     setValueOfAtom(atomIdx, opposite);
00907   }

long double VariableState::getImprovementByFlipping ( const int &  atomIdx  )  [inline]

Calculates the improvement achieved by flipping an atom.

This is the cost of clauses which flipping the atom makes good minus the cost of clauses which flipping the atom makes bad. In lazy mode, if the atom is not active, then the atom is activated and the makecost and breakcost are updated.

Parameters:
atomIdx Index of atom to flip.
Returns:
Improvement achieved by flipping the atom.

Definition at line 920 of file variablestate.h.

References flipAtom(), and isActive().

Referenced by MaxWalkSat::calculateImprovement().

00921   {
00922     if (lazy_ && !isActive(atomIdx))
00923     {
00924         // First flip the atom to activate it, then flip it back
00925       flipAtom(atomIdx);
00926       flipAtom(atomIdx);
00927     }
00928     long double improvement = makeCost_[atomIdx] - breakCost_[atomIdx];
00929     return improvement;
00930   }

void VariableState::activateAtom ( const int &  atomIdx,
const bool &  ignoreActivePreds 
) [inline]

If in lazy mode, an atom is activated and all clauses activated by this atom are added to the state.

If in eager mode, nothing happens.

Parameters:
atomIdx Index of atom to be activated.

Definition at line 938 of file variablestate.h.

References addNewClauses(), getActiveClauses(), Domain::getDB(), isActive(), and Database::setActiveStatus().

Referenced by setValueOfAtom().

00939   {
00940       // Lazy version: if atom is not active, we need to activate clauses
00941       // and take their cost into account
00942     if (lazy_ && !isActive(atomIdx))
00943     {
00944       Predicate* p =
00945         gndPredHashArray_[atomIdx - 1]->createEquivalentPredicate(domain_);
00946       getActiveClauses(p, newClauses_, true, ignoreActivePreds);
00947         // Add the clauses and preds and fill info arrays
00948       bool initial = false;
00949       addNewClauses(initial);
00950         // Set active status in db
00951       domain_->getDB()->setActiveStatus(p, true);
00952       activeAtoms_++;
00953       delete p;
00954     }        
00955   }

bool VariableState::isActive ( const int &  atomIdx  )  [inline]

Checks if an atom is active.

Parameters:
atomIdx Index of atom to be checked.
Returns:
true, if atom is active, otherwise false.

Definition at line 963 of file variablestate.h.

References Database::getActiveStatus(), and Domain::getDB().

Referenced by activateAtom(), getImprovementByFlipping(), and setValueOfAtom().

00964   {
00965     return domain_->getDB()->getActiveStatus(gndPredHashArray_[atomIdx-1]);
00966   }

bool VariableState::isActive ( const Predicate pred  )  [inline]

Checks if an atom is active.

Parameters:
pred Predicate to be checked.
Returns:
true, if atom is active, otherwise false.

Definition at line 974 of file variablestate.h.

References Database::getActiveStatus(), and Domain::getDB().

00975   {
00976     return domain_->getDB()->getActiveStatus(pred);
00977   }

void VariableState::addBreakCostToAtomsInClause ( const int &  clauseIdx,
const long double &  cost 
) [inline]

Increases breakCost of all atoms in a given clause.

Parameters:
clauseIdx Index of clause whose atoms' breakCost is altered.
cost Cost to be added to atoms' breakCost.

Definition at line 1071 of file variablestate.h.

References getClauseSize().

Referenced by flipAtom().

01073   {
01074     register int size = getClauseSize(clauseIdx);
01075     for (int i = 0; i < size; i++)
01076     {
01077       register int lit = clause_[clauseIdx][i];
01078       breakCost_[abs(lit)] += cost;
01079     }
01080   }

void VariableState::subtractBreakCostFromAtomsInClause ( const int &  clauseIdx,
const long double &  cost 
) [inline]

Decreases breakCost of all atoms in a given clause.

Parameters:
clauseIdx Index of clause whose atoms' breakCost is altered.
cost Cost to be subtracted from atoms' breakCost.

Definition at line 1088 of file variablestate.h.

References getClauseSize().

01090   {
01091     register int size = getClauseSize(clauseIdx);
01092     for (int i = 0; i < size; i++)
01093     {
01094       register int lit = clause_[clauseIdx][i];
01095       breakCost_[abs(lit)] -= cost;
01096     }
01097   }

void VariableState::addMakeCost ( const int &  atomIdx,
const long double &  cost 
) [inline]

Increases makeCost of an atom.

Parameters:
atomIdx Index of atom whose makeCost is altered.
cost Cost to be added to atom's makeCost.

Definition at line 1105 of file variablestate.h.

Referenced by flipAtom().

01106   {
01107     makeCost_[atomIdx] += cost;
01108   }

void VariableState::subtractMakeCost ( const int &  atomIdx,
const long double &  cost 
) [inline]

Decreases makeCost of an atom.

Parameters:
atomIdx Index of atom whose makeCost is altered.
cost Cost to be subtracted from atom's makeCost.

Definition at line 1116 of file variablestate.h.

01117   {
01118     makeCost_[atomIdx] -= cost;
01119   }

void VariableState::addMakeCostToAtomsInClause ( const int &  clauseIdx,
const long double &  cost 
) [inline]

Increases makeCost of all atoms in a given clause.

Parameters:
clauseIdx Index of clause whose atoms' makeCost is altered.
cost Cost to be added to atoms' makeCost.

Definition at line 1127 of file variablestate.h.

References getClauseSize().

Referenced by flipAtom().

01129   {
01130     register int size = getClauseSize(clauseIdx);
01131     for (int i = 0; i < size; i++)
01132     {
01133       register int lit = clause_[clauseIdx][i];
01134       makeCost_[abs(lit)] += cost;
01135     }
01136   }

void VariableState::subtractMakeCostFromAtomsInClause ( const int &  clauseIdx,
const long double &  cost 
) [inline]

Decreases makeCost of all atoms in a given clause.

Parameters:
clauseIdx Index of clause whose atoms' makeCost is altered.
cost Cost to be subtracted from atoms' makeCost.

Definition at line 1144 of file variablestate.h.

References getClauseSize().

01146   {
01147     register int size = getClauseSize(clauseIdx);
01148     for (int i = 0; i < size; i++)
01149     {
01150       register int lit = clause_[clauseIdx][i];
01151       makeCost_[abs(lit)] -= cost;
01152     }
01153   }

const int VariableState::getTrueLiteralOtherThan ( const int &  clauseIdx,
const int &  atomIdx1,
const int &  atomIdx2 
) [inline]

Retrieves a true literal in a clause other than the two given.

Parameters:
clauseIdx Index of clause from which literal is retrieved.
atomIdx1 Index of first atom excluded from search.
atomIdx2 Index of second atom excluded from search.
Returns:
Index of atom found.

Definition at line 1164 of file variablestate.h.

References getClauseSize(), and isTrueLiteral().

Referenced by flipAtom().

01167   {
01168     register int size = getClauseSize(clauseIdx);
01169     for (int i = 0; i < size; i++)
01170     {
01171       register int lit = clause_[clauseIdx][i];
01172       register int v = abs(lit);
01173       if (isTrueLiteral(lit) && v != atomIdx1 && v != atomIdx2)
01174         return v;
01175     }
01176       // If we're here, then no other true lit exists
01177     assert(false);
01178     return -1;
01179   }

const int VariableState::getRandomTrueLitInClause ( const int &  clauseIdx  )  [inline]

Retrieves the index of a random true literal in a clause.

Parameters:
clauseIdx Index of clause from which the literal is retrieved.
Returns:
Index of the atom retrieved.

Definition at line 1211 of file variablestate.h.

References getClauseSize(), and isTrueLiteral().

Referenced by getIndexOfAtomInRandomFalseClause(), and MaxWalkSat::pickBest().

01212   {
01213     assert(numTrueLits_[clauseIdx] > 0);
01214     int trueLit = random()%numTrueLits_[clauseIdx];
01215     int whichTrueLit = 0;
01216     for (int i = 0; i < getClauseSize(clauseIdx); i++)
01217     {
01218       int lit = clause_[clauseIdx][i];
01219       int atm = abs(lit);
01220         // True literal
01221       if (isTrueLiteral(lit))
01222         if (trueLit == whichTrueLit++)
01223           return atm;
01224     }
01225       // If we're here, then no other true lit exists
01226     assert(false);
01227     return -1;
01228   }

const int VariableState::getBlockIndex ( const int &  atomIdx  )  [inline]

Returns the index of the block which the atom with index atomIdx is in.

If not in any, returns -1.

Definition at line 1294 of file variablestate.h.

References Array< Type >::size().

Referenced by MaxWalkSat::calculateImprovement(), SimulatedTempering::infer(), initRandom(), MCMC::performGibbsStep(), MaxWalkSat::pickRandom(), and MCMC::randomInitGndPredsTruthValues().

01295   {
01296     for (int i = 0; i < blocks_->size(); i++)
01297     {
01298       int blockIdx = (*blocks_)[i].find(atomIdx);
01299       if (blockIdx >= 0)
01300         return i;
01301     }
01302     return -1;
01303   }

void VariableState::makeUnitCosts (  )  [inline]

Turns all costs into units.

Positive costs are converted to 1, negative costs are converted to -1

Definition at line 1340 of file variablestate.h.

References Array< Type >::size().

Referenced by MCSAT::init().

01341   {
01342     for (int i = 0; i < clauseCost_.size(); i++)
01343     {
01344       if (clauseCost_[i] > 0) clauseCost_[i] = 1.0;
01345       else
01346       {
01347         assert(clauseCost_[i] < 0);
01348         clauseCost_[i] = -1.0;
01349       }
01350     }
01351   }

void VariableState::getNumClauseGndings ( Array< double > *const &  numGndings,
bool  tv 
) [inline]

Gets the number of (true or false) clause groundings in this state.

If eager, the first order clause frequencies in the mrf are used.

Parameters:
numGndings Array being filled with values
clauseCnt 
tv 

Definition at line 1421 of file variablestate.h.

References MLN::getNumClauses(), getNumTrueLits(), and Array< Type >::size().

Referenced by SimulatedTempering::infer(), MaxWalkSat::infer(), and MCMC::performGibbsStep().

01422   {
01423     // TODO: lazy version
01424     IntPairItr itr;
01425     IntPair *clauseFrequencies;
01426     
01427       // numGndings should have been initialized with non-negative values
01428     int clauseCnt = numGndings->size();
01429     assert(clauseCnt == mln_->getNumClauses());
01430     for (int clauseno = 0; clauseno < clauseCnt; clauseno++)
01431       assert ((*numGndings)[clauseno] >= 0);
01432     
01433     for (int i = 0; i < gndClauses_->size(); i++)
01434     {
01435       GroundClause *gndClause = (*gndClauses_)[i];
01436       int satLitcnt = getNumTrueLits(i);
01437       if (tv && satLitcnt == 0)
01438         continue;
01439       if (!tv && satLitcnt > 0)
01440         continue;
01441 
01442       clauseFrequencies = gndClause->getClauseFrequencies();
01443       for (itr = clauseFrequencies->begin();
01444            itr != clauseFrequencies->end(); itr++)
01445       {
01446         int clauseno = itr->first;
01447         int frequency = itr->second;
01448         (*numGndings)[clauseno] += frequency;
01449       }
01450     }
01451   }

void VariableState::getNumClauseGndings ( double  numGndings[],
int  clauseCnt,
bool  tv 
) [inline]

Gets the number of (true or false) clause groundings in this state.

If eager, the first order clause frequencies in the mrf are used.

Parameters:
numGndings 
clauseCnt 
tv 

Definition at line 1461 of file variablestate.h.

References getNumTrueLits(), and Array< Type >::size().

01462   {
01463     // TODO: lazy version
01464     IntPairItr itr;
01465     IntPair *clauseFrequencies;
01466     
01467     for (int clauseno = 0; clauseno < clauseCnt; clauseno++)
01468       numGndings[clauseno] = 0;
01469     
01470     for (int i = 0; i < gndClauses_->size(); i++)
01471     {
01472       GroundClause *gndClause = (*gndClauses_)[i];
01473       int satLitcnt = getNumTrueLits(i);
01474       if (tv && satLitcnt == 0)
01475         continue;
01476       if (!tv && satLitcnt > 0)
01477         continue;
01478 
01479       clauseFrequencies = gndClause->getClauseFrequencies();
01480       for (itr = clauseFrequencies->begin();
01481            itr != clauseFrequencies->end(); itr++)
01482       {
01483         int clauseno = itr->first;
01484         int frequency = itr->second;
01485         numGndings[clauseno] += frequency;
01486       }
01487     }
01488   }

void VariableState::getNumClauseGndingsWithUnknown ( double  numGndings[],
int  clauseCnt,
bool  tv,
const Array< bool > *const &  unknownPred 
) [inline]

Gets the number of (true or false) clause groundings in this state.

If eager, the first order clause frequencies in the mrf are used.

Parameters:
numGndings Will hold the number of groundings for each first-order clause.
clauseCnt Number of first-order clauses whose groundings are being counted.
tv If true, true groundings are counted, otherwise false groundings.
unknownPred If pred is marked as unknown, it is ignored in the count

Definition at line 1501 of file variablestate.h.

References getNumAtoms(), isTrueLiteral(), and Array< Type >::size().

01504   {
01505     assert(unknownPred->size() == getNumAtoms());
01506     IntPairItr itr;
01507     IntPair *clauseFrequencies;
01508     
01509     for (int clauseno = 0; clauseno < clauseCnt; clauseno++)
01510       numGndings[clauseno] = 0;
01511     
01512     for (int i = 0; i < gndClauses_->size(); i++)
01513     {
01514       GroundClause *gndClause = (*gndClauses_)[i];
01515       int satLitcnt = 0;
01516       bool unknown = false;
01517       for (int j = 0; j < gndClause->getNumGroundPredicates(); j++)
01518       {
01519         int lit = gndClause->getGroundPredicateIndex(j);
01520         if ((*unknownPred)[abs(lit) - 1])
01521         {
01522           unknown = true;
01523           continue;
01524         }
01525         if (isTrueLiteral(lit)) satLitcnt++;
01526       }
01527       
01528       if (tv && satLitcnt == 0)
01529         continue;
01530       if (!tv && (satLitcnt > 0 || unknown))
01531         continue;
01532 
01533       clauseFrequencies = gndClause->getClauseFrequencies();
01534       for (itr = clauseFrequencies->begin();
01535            itr != clauseFrequencies->end(); itr++)
01536       {
01537         int clauseno = itr->first;
01538         int frequency = itr->second;
01539         numGndings[clauseno] += frequency;
01540       }
01541     }
01542   }

void VariableState::setOthersInBlockToFalse ( const int &  atomIdx,
const int &  blockIdx 
) [inline]

Sets the truth values of all atoms in a block except for the one given.

Parameters:
atomIdx Index of atom in block exempt from being set to false.
blockIdx Index of block whose atoms are set to false.

Definition at line 1550 of file variablestate.h.

References setValueOfAtom(), and Array< Type >::size().

Referenced by addOneAtomToEachBlock(), and initBlocksRandom().

01552   {
01553     Array<int>& block = (*blocks_)[blockIdx];
01554     for (int i = 0; i < block.size(); i++)
01555     {
01556         // Atom not the one specified and not fixed
01557       if (i != atomIdx && fixedAtom_[block[i] + 1] == 0)
01558         setValueOfAtom(block[i] + 1, false);
01559     }
01560   }

void VariableState::fixAtom ( const int &  atomIdx,
const bool &  value 
) [inline]

Fixes an atom to a truth value.

This means the atom can not change its truth values again. If the atom has already been fixed to the opposite value, then we have a contradiction and the program terminates.

Parameters:
atomIdx Index of atom to be fixed.
value Truth value to which the atom is fixed.

Definition at line 1571 of file variablestate.h.

References setValueOfAtom().

Referenced by UnitPropagation::infer().

01572   {
01573     assert(atomIdx > 0);
01574       // If already fixed to opp. sense, then contradiction
01575     if ((fixedAtom_[atomIdx] == 1 && value == false) ||
01576         (fixedAtom_[atomIdx] == -1 && value == true))
01577     {
01578       cout << "Contradiction: Tried to fix atom " << atomIdx <<
01579       " to true and false ... exiting." << endl;
01580       exit(0);
01581     }
01582 
01583     if (vsdebug)
01584     {
01585       cout << "Fixing ";
01586       (*gndPreds_)[atomIdx - 1]->print(cout, domain_);
01587       cout << " to " << value << endl;
01588     }
01589     
01590     setValueOfAtom(atomIdx, value);
01591     fixedAtom_[atomIdx] = (value) ? 1 : -1;
01592   }

Array<int>* VariableState::simplifyClauseFromFixedAtoms ( const int &  clauseIdx  )  [inline]

Simplifies a clause using atoms which have been fixed.

If clause is satisfied from the fixed atoms, this is marked in isSatisfied_ and an empty array is returned. If clause is empty and not satisfied, then a contradiction has occured. Otherwise, the simplified clause is returned.

Returned array should be deleted.

Parameters:
clauseIdx Index of the clause to be simplified
Returns:
Simplified clause

Definition at line 1605 of file variablestate.h.

References Array< Type >::append(), Array< Type >::clear(), and getClauseSize().

Referenced by UnitPropagation::infer().

01606   {
01607     Array<int>* returnArray = new Array<int>;
01608       // If already satisfied from fixed atoms, then return empty array
01609     if (isSatisfied_[clauseIdx]) return returnArray;
01610 
01611       // Keeps track of pos. clause being satisfied or 
01612       // neg. clause being unsatisfied due to fixed atoms
01613     bool isGood = (clauseCost_[clauseIdx] > 0) ? false : true;
01614       // Keeps track of all atoms being fixed to false in a pos. clause
01615     bool allFalseAtoms = (clauseCost_[clauseIdx] > 0) ? true : false;
01616       // Check each literal in clause
01617     for (int i = 0; i < getClauseSize(clauseIdx); i++)
01618     {
01619       int lit = clause_[clauseIdx][i];
01620       int fixedValue = fixedAtom_[abs(lit)];
01621 
01622       if (clauseCost_[clauseIdx] > 0)
01623       { // Pos. clause: check if clause is satisfied
01624         if ((fixedValue == 1 && lit > 0) ||
01625             (fixedValue == -1 && lit < 0))
01626         { // True fixed lit
01627           isGood = true;
01628           allFalseAtoms = false;
01629           returnArray->clear();
01630           break;
01631         }
01632         else if (fixedValue == 0)
01633         { // Lit not fixed
01634           allFalseAtoms = false;
01635           returnArray->append(lit);
01636         }
01637       }
01638       else
01639       { // Neg. clause:
01640         assert(clauseCost_[clauseIdx] < 0);
01641         if ((fixedValue == 1 && lit > 0) ||
01642             (fixedValue == -1 && lit < 0))
01643         { // True fixed lit
01644           cout << "Contradiction: Tried to fix atom " << abs(lit) <<
01645           " to true in a negative clause ... exiting." << endl;
01646           exit(0);
01647         }
01648         else
01649         { // False fixed lit or non-fixed lit
01650           returnArray->append(lit);
01651             // Non-fixed lit
01652           if (fixedValue == 0) isGood = false;          
01653         }
01654       }
01655     }
01656     if (allFalseAtoms)
01657     {
01658       cout << "Contradiction: All atoms in clause " << clauseIdx <<
01659       " fixed to false ... exiting." << endl;
01660       exit(0);
01661     }
01662     if (isGood) isSatisfied_[clauseIdx] = true;
01663     return returnArray;
01664   }

const bool VariableState::isDeadClause ( const int &  clauseIdx  )  [inline]

Checks if a clause is dead.

Parameters:
clauseIdx Index of clause being checked.
Returns:
True, if clause is dead, otherwise false.

Definition at line 1672 of file variablestate.h.

Referenced by UnitPropagation::infer().

01673   {
01674     return deadClause_[clauseIdx];
01675   }

void VariableState::killClauses ( const int &  startClause  )  [inline]

Marks clauses as dead which were not good in the previous iteration of inference or are not picked according to a weighted coin flip.

Parameters:
startClause All clauses with index of this or greater are looked at to be killed.

Definition at line 1701 of file variablestate.h.

References clauseGoodInPrevious(), getNumClauses(), and initMakeBreakCostWatch().

Referenced by addNewClauses().

01702   {
01703     for (int i = startClause; i < getNumClauses(); i++)
01704     {
01705       GroundClause* clause = (*gndClauses_)[i];
01706       if ((clauseGoodInPrevious(i)) &&
01707           (clause->isHardClause() || random() <= threshold_[i]))
01708       {
01709         if (vsdebug)
01710         {
01711           cout << "Keeping clause "<< i << " ";
01712           clause->print(cout, domain_, &gndPredHashArray_);
01713           cout << endl;
01714         }
01715         deadClause_[i] = false;
01716       }
01717       else
01718       {
01719         deadClause_[i] = true;
01720       }
01721     }
01722     initMakeBreakCostWatch(startClause);
01723   }

const bool VariableState::clauseGoodInPrevious ( const int &  clauseIdx  )  [inline]

Checks if a clause was good in the previous iteration of inference, i.e.

if it is positive and satisfied or negative and unsatisfied.

Parameters:
clauseIdx Index of clause being checked.
Returns:
true, if clause was good, otherwise false.

Definition at line 1733 of file variablestate.h.

Referenced by killClauses().

01734   {
01735     //GroundClause* clause = (*gndClauses_)[clauseIdx];
01736     int numSatLits = numTrueLits_[clauseIdx];
01737       // Num. of satisfied lits in previous iteration is stored in clause
01738     if ((numSatLits > 0 && clauseCost_[clauseIdx] > 0.0) ||
01739         (numSatLits == 0 && clauseCost_[clauseIdx] < 0.0))
01740       return true;
01741     else
01742       return false;
01743   }

void VariableState::printLowState ( ostream &  out  )  [inline]

Prints the best state found to a stream.

Parameters:
out Stream to which the state is printed.

Definition at line 1783 of file variablestate.h.

References getNumAtoms().

Referenced by MCSAT::init().

01784   {
01785     for (int i = 0; i < getNumAtoms(); i++)
01786     {
01787       (*gndPreds_)[i]->print(out, domain_);
01788       out << " " << lowAtom_[i + 1] << endl;
01789     }
01790   }

void VariableState::printGndPred ( const int &  predIndex,
ostream &  out 
) [inline]

Prints a ground predicate to a stream.

Parameters:
predIndex Index of predicate to be printed.
out Stream to which predicate is printed.

Definition at line 1798 of file variablestate.h.

Referenced by UnitPropagation::printProbabilities(), SAT::printProbabilities(), MCMC::printProbabilities(), UnitPropagation::printTruePreds(), SAT::printTruePreds(), and MCMC::printTruePreds().

01799   {
01800     (*gndPreds_)[predIndex]->print(out, domain_);
01801   }

GroundPredicate* VariableState::getGndPred ( const int &  index  )  [inline]

Gets a pointer to a GroundPredicate.

Parameters:
index Index of the GroundPredicate to be retrieved.
Returns:
Pointer to the GroundPredicate

Definition at line 1811 of file variablestate.h.

Referenced by MCMC::getProbabilityOfPred(), MCMC::gndPredFlippedUpdates(), SimulatedTempering::infer(), MCSAT::infer(), GibbsSampler::infer(), and MCMC::performGibbsStep().

01812   {
01813     return (*gndPreds_)[index];
01814   }

GroundClause* VariableState::getGndClause ( const int &  index  )  [inline]

Gets a pointer to a GroundClause.

Parameters:
index Index of the GroundClause to be retrieved.
Returns:
Pointer to the GroundClause

Definition at line 1822 of file variablestate.h.

Referenced by MCMC::gndPredFlippedUpdates(), MCMC::initNumTrueLits(), and MCMC::updateWtsForGndPreds().

01823   {
01824     return (*gndClauses_)[index];
01825   }

const int VariableState::getGndPredIndex ( GroundPredicate *const &  gndPred  )  [inline]

Gets the index of a GroundPredicate in this state.

Parameters:
gndPred GroundPredicate whose index is being found.
Returns:
Index of the GroundPredicate, if found; otherwise -1.

Definition at line 1862 of file variablestate.h.

References Array< Type >::find().

Referenced by UnitPropagation::getProbability(), SAT::getProbability(), and MCMC::getProbability().

01863   {
01864     return gndPreds_->find(gndPred);
01865   }

void VariableState::getActiveClauses ( Predicate inputPred,
Array< GroundClause * > &  activeClauses,
bool const &  active,
bool const &  ignoreActivePreds 
) [inline]

Gets clauses and weights activated by the predicate inputPred, if active is true.

If false, inactive clauses (and their weights) containing inputPred are retrieved. If inputPred is NULL, then all active (or inactive) clauses and their weights are retrieved.

Parameters:
inputPred Only clauses containing this Predicate are looked at. If NULL, then all active clauses are retrieved.
activeClauses New active clauses are put here.
active If true, active clauses are retrieved, otherwise inactive.
ignoreActivePreds If true, active preds are not taken into account. This results in the retrieval of all unsatisfied clauses.

Definition at line 1886 of file variablestate.h.

References Array< Type >::append(), HashArray< Type, HashFn, EqualFn >::append(), GroundClause::appendParentWtPtr(), GroundClause::appendToGndPreds(), Array< Type >::clear(), HashArray< Type, HashFn, EqualFn >::find(), MLN::findClauseIdx(), Clause::getActiveClauses(), MLN::getClause(), MLN::getClausesContainingPred(), Domain::getDB(), Database::getDeactivatedStatus(), Predicate::getId(), MLN::getNumClauses(), GroundClause::getWt(), Clause::getWt(), Clause::getWtPtr(), GroundClause::incrementClauseFrequency(), Clause::isHardClause(), GroundClause::print(), Clause::print(), GroundClause::setWt(), HashArray< Type, HashFn, EqualFn >::size(), and Array< Type >::size().

Referenced by activateAtom(), getActiveClauses(), and VariableState().

01890   {
01891     Clause *fclause;
01892     GroundClause* newClause;
01893     int clauseCnt;
01894     GroundClauseHashArray clauseHashArray;
01895 
01896     Array<GroundClause*>* newClauses = new Array<GroundClause*>; 
01897   
01898     const Array<IndexClause*>* indexClauses = NULL;
01899       
01900       // inputPred is null: all active clauses should be retrieved
01901     if (inputPred == NULL)
01902     {
01903       clauseCnt = mln_->getNumClauses();
01904     }
01905       // Otherwise, look at all first order clauses containing the pred
01906     else
01907     {
01908       if (domain_->getDB()->getDeactivatedStatus(inputPred)) return;
01909       int predId = inputPred->getId();
01910       indexClauses = mln_->getClausesContainingPred(predId);
01911       clauseCnt = indexClauses->size();
01912     }
01913 
01914       // Look at each first-order clause and get active groundings
01915     int clauseno = 0;
01916     while (clauseno < clauseCnt)
01917     {
01918       if (inputPred)
01919         fclause = (Clause *) (*indexClauses)[clauseno]->clause;           
01920       else
01921         fclause = (Clause *) mln_->getClause(clauseno);
01922 
01923       if (vsdebug)
01924       {
01925         cout << "Getting active clauses for FO clause: ";
01926         fclause->print(cout, domain_);
01927         cout << endl;
01928       }
01929       
01930       long double wt = fclause->getWt();
01931       const double* parentWtPtr = NULL;
01932       if (!fclause->isHardClause()) parentWtPtr = fclause->getWtPtr();
01933       const int clauseId = mln_->findClauseIdx(fclause);
01934       newClauses->clear();
01935 
01936       fclause->getActiveClauses(inputPred, domain_, newClauses,
01937                                 &gndPredHashArray_, ignoreActivePreds);
01938 
01939       for (int i = 0; i < newClauses->size(); i++)
01940       {
01941         newClause = (*newClauses)[i];
01942         int pos = clauseHashArray.find(newClause);
01943           // If clause already present, then just add weight
01944         if (pos >= 0)
01945         {
01946           if (vsdebug)
01947           {
01948             cout << "Adding weight " << wt << " to clause ";
01949             clauseHashArray[pos]->print(cout, domain_, &gndPredHashArray_);
01950             cout << endl;
01951           }
01952           clauseHashArray[pos]->addWt(wt);
01953           if (parentWtPtr)
01954           {
01955             clauseHashArray[pos]->appendParentWtPtr(parentWtPtr);
01956             clauseHashArray[pos]->incrementClauseFrequency(clauseId, 1);
01957           }
01958           delete newClause;
01959           continue;
01960         }
01961 
01962           // If here, then clause is not yet present        
01963         newClause->setWt(wt);
01964         newClause->appendToGndPreds(&gndPredHashArray_);
01965         if (parentWtPtr)
01966         {
01967           newClause->appendParentWtPtr(parentWtPtr);
01968           newClause->incrementClauseFrequency(clauseId, 1);
01969           assert(newClause->getWt() == *parentWtPtr);
01970         }      
01971 
01972         if (vsdebug)
01973         {
01974           cout << "Appending clause ";
01975           newClause->print(cout, domain_, &gndPredHashArray_);
01976           cout << endl;
01977         }
01978         clauseHashArray.append(newClause);
01979       }
01980       clauseno++; 
01981     } //while (clauseno < clauseCnt)
01982 
01983     for (int i = 0; i < clauseHashArray.size(); i++)
01984     {
01985       newClause = clauseHashArray[i];
01986       activeClauses.append(newClause);
01987     }
01988     delete newClauses;
01989   }

void VariableState::getActiveClauses ( Array< GroundClause * > &  allClauses,
bool const &  ignoreActivePreds 
) [inline]

Get all the active clauses in the database.

Parameters:
allClauses Active clauses are retrieved into this Array.
ignoreActivePreds If true, active preds are ignored; this means all unsatisfied clauses are retrieved.

Definition at line 1998 of file variablestate.h.

References getActiveClauses().

02000   {
02001     getActiveClauses(NULL, allClauses, true, ignoreActivePreds);
02002   }


The documentation for this class was generated from the following file:
Generated on Tue Jan 16 05:30:06 2007 for Alchemy by  doxygen 1.5.1