Changeset ec87e4 for src


Ignore:
Timestamp:
Oct 25, 2011, 12:08:02 PM (13 years ago)
Author:
Frederik Heber <heber@…>
Branches:
Action_Thermostats, Add_AtomRandomPerturbation, Add_FitFragmentPartialChargesAction, Add_RotateAroundBondAction, Add_SelectAtomByNameAction, Added_ParseSaveFragmentResults, AddingActions_SaveParseParticleParameters, Adding_Graph_to_ChangeBondActions, Adding_MD_integration_tests, Adding_ParticleName_to_Atom, Adding_StructOpt_integration_tests, AtomFragments, Automaking_mpqc_open, AutomationFragmentation_failures, Candidate_v1.5.4, Candidate_v1.6.0, Candidate_v1.6.1, ChangeBugEmailaddress, ChangingTestPorts, ChemicalSpaceEvaluator, CombiningParticlePotentialParsing, Combining_Subpackages, Debian_Package_split, Debian_package_split_molecuildergui_only, Disabling_MemDebug, Docu_Python_wait, EmpiricalPotential_contain_HomologyGraph, EmpiricalPotential_contain_HomologyGraph_documentation, Enable_parallel_make_install, Enhance_userguide, Enhanced_StructuralOptimization, Enhanced_StructuralOptimization_continued, Example_ManyWaysToTranslateAtom, Exclude_Hydrogens_annealWithBondGraph, FitPartialCharges_GlobalError, Fix_BoundInBox_CenterInBox_MoleculeActions, Fix_ChargeSampling_PBC, Fix_ChronosMutex, Fix_FitPartialCharges, Fix_FitPotential_needs_atomicnumbers, Fix_ForceAnnealing, Fix_IndependentFragmentGrids, Fix_ParseParticles, Fix_ParseParticles_split_forward_backward_Actions, Fix_PopActions, Fix_QtFragmentList_sorted_selection, Fix_Restrictedkeyset_FragmentMolecule, Fix_StatusMsg, Fix_StepWorldTime_single_argument, Fix_Verbose_Codepatterns, Fix_fitting_potentials, Fixes, ForceAnnealing_goodresults, ForceAnnealing_oldresults, ForceAnnealing_tocheck, ForceAnnealing_with_BondGraph, ForceAnnealing_with_BondGraph_continued, ForceAnnealing_with_BondGraph_continued_betteresults, ForceAnnealing_with_BondGraph_contraction-expansion, FragmentAction_writes_AtomFragments, FragmentMolecule_checks_bonddegrees, GeometryObjects, Gui_Fixes, Gui_displays_atomic_force_velocity, ImplicitCharges, IndependentFragmentGrids, IndependentFragmentGrids_IndividualZeroInstances, IndependentFragmentGrids_IntegrationTest, IndependentFragmentGrids_Sole_NN_Calculation, JobMarket_RobustOnKillsSegFaults, JobMarket_StableWorkerPool, JobMarket_unresolvable_hostname_fix, MoreRobust_FragmentAutomation, ODR_violation_mpqc_open, PartialCharges_OrthogonalSummation, PdbParser_setsAtomName, PythonUI_with_named_parameters, QtGui_reactivate_TimeChanged_changes, Recreated_GuiChecks, Rewrite_FitPartialCharges, RotateToPrincipalAxisSystem_UndoRedo, SaturateAtoms_findBestMatching, SaturateAtoms_singleDegree, StoppableMakroAction, Subpackage_CodePatterns, Subpackage_JobMarket, Subpackage_LinearAlgebra, Subpackage_levmar, Subpackage_mpqc_open, Subpackage_vmg, Switchable_LogView, ThirdParty_MPQC_rebuilt_buildsystem, TrajectoryDependenant_MaxOrder, TremoloParser_IncreasedPrecision, TremoloParser_MultipleTimesteps, TremoloParser_setsAtomName, Ubuntu_1604_changes, stable
Children:
708798
Parents:
5fd0f4
git-author:
Frederik Heber <heber@…> (10/17/11 15:23:42)
git-committer:
Frederik Heber <heber@…> (10/25/11 12:08:02)
Message:

Rewrite of CheckAgainstAdjacencyFile.

  • we now construct two multimaps -- one from file, the other from World's selected atoms -- and compare these two.
  • added unit test on the class.
Location:
src
Files:
2 added
4 edited

Legend:

Unmodified
Added
Removed
  • src/Graph/CheckAgainstAdjacencyFile.cpp

    r5fd0f4 rec87e4  
    2828#include "CodePatterns/Assert.hpp"
    2929#include "CodePatterns/Log.hpp"
    30 #include "CodePatterns/Verbose.hpp"
     30#include "CodePatterns/Range.hpp"
     31#include "Descriptors/AtomIdDescriptor.hpp"
    3132#include "Helpers/defs.hpp"
    32 
    33 CheckAgainstAdjacencyFile::CheckAgainstAdjacencyFile() :
    34   CurrentBonds(new int[MAXBONDS]),
     33#include "World.hpp"
     34
     35CheckAgainstAdjacencyFile::CheckAgainstAdjacencyFile(World::AtomSet::const_iterator AtomMapBegin, World::AtomSet::const_iterator AtomMapEnd) :
    3536  status(true),
    3637  NonMatchNumber(0)
    3738{
    38   for(int i=0;i<MAXBONDS;i++)
    39     CurrentBonds[i] = 0;
     39  CreateInternalMap(AtomMapBegin, AtomMapEnd);
    4040}
    4141
    4242CheckAgainstAdjacencyFile::~CheckAgainstAdjacencyFile()
    4343{
    44   delete[](CurrentBonds);
    45 }
    46 
    47 void CheckAgainstAdjacencyFile::CompareBonds(const atom *&Walker, size_t &CurrentBondsOfAtom, int AtomNr, std::map<int, atom*> &ListOfAtoms)
    48 {
    49   size_t j = 0;
    50   int id = -1;
    51 
    52   //Log() << Verbose(2) << "Walker is " << *Walker << ", bond partners: ";
    53   const BondList& ListOfBonds = Walker->getListOfBonds();
    54   if (CurrentBondsOfAtom == ListOfBonds.size()) {
    55     for (BondList::const_iterator Runner = ListOfBonds.begin();
    56         Runner != ListOfBonds.end();
    57         ++Runner) {
    58       id = (*Runner)->GetOtherAtom(Walker)->getNr();
    59       j = 0;
    60       for (; (j < CurrentBondsOfAtom) && (CurrentBonds[j++] != id);)
    61         ; // check against all parsed bonds
    62       if (CurrentBonds[j - 1] != id) { // no match ? Then mark in ListOfAtoms
    63         ListOfAtoms[AtomNr] = NULL;
    64         NonMatchNumber++;
    65         status = false;
    66         ELOG(2, id << " can not be found in list." << endl);
    67       } else {
    68         //Log() << Verbose(0) << "[" << id << "]\t";
    69       }
    70     }
    71     //Log() << Verbose(0) << endl;
    72   } else {
    73     LOG(0, "STATUS: Number of bonds for Atom " << *Walker << " does not match, parsed " << CurrentBondsOfAtom << " against " << ListOfBonds.size() << ".");
    74     status = false;
    75   }
    76 }
    77 ;
    78 
    79 /** Checks contents of adjacency file against bond structure in structure molecule.
    80  * \param File file to parser
    81  * \param ListOfAtoms map from int (index in file) to atom
    82  * \return true - structure is equal, false - not equivalence
    83  */
    84 bool CheckAgainstAdjacencyFile::operator()(std::ifstream &File, std::map<int, atom*> ListOfAtoms)
    85 {
    86   LOG(0, "STATUS: Looking at bond structure stored in adjacency file and comparing to present one ... ");
     44  ExternalAtomBondMap.clear();
     45  InternalAtomBondMap.clear();
     46}
     47
     48/** Parses the bond partners of each atom from an external file into \a AtomBondMap.
     49 *
     50 * @param File file to parse
     51 * @return true - everything ok, false - error while parsing
     52 */
     53bool CheckAgainstAdjacencyFile::ParseInExternalMap(std::istream &File)
     54{
    8755  if (File.fail()) {
    8856    LOG(1, "STATUS: Adjacency file not found." << endl);
     
    9058  }
    9159
     60  ExternalAtomBondMap.clear();
    9261  char buffer[MAXSTRINGSIZE];
    9362  int tmp;
     
    9968    int AtomNr = -1;
    10069    line >> AtomNr;
    101     size_t CurrentBondsOfAtom = -1; // we count one too far due to line end
    10270    // parse into structure
    10371    if (AtomNr >= 0) {
    104       ASSERT(ListOfAtoms.count(AtomNr),
    105           "CheckAgainstAdjacencyFile::operator() - index "
    106           +toString(AtomNr)+" not present in ListOfAtoms.");
    107       const atom *Walker = ListOfAtoms[AtomNr];
     72      const atom *Walker = World::getInstance().getAtom(AtomById(AtomNr));
     73      ASSERT(Walker != NULL,
     74          "CheckAgainstAdjacencyFile::ParseInExternalMap() - there is no atom with id "+toString(AtomNr)+".");
     75      if (Walker == NULL)
     76        return false;
     77      // parse bond partner ids associated to AtomNr
    10878      while (line >> ws >> tmp) {
    10979        LOG(3, "INFO: Recognized bond partner " << tmp);
    110         CurrentBonds[++CurrentBondsOfAtom] = tmp;
    111         ASSERT(CurrentBondsOfAtom < MAXBONDS,
    112             "molecule::CheckAdjacencyFileAgainstMolecule() - encountered more bonds than allowed: "
    113             +toString(CurrentBondsOfAtom)+" >= "+toString(int(MAXBONDS))+"!");
     80        ExternalAtomBondMap.insert( std::make_pair(AtomNr, tmp) );
    11481      }
    115       // compare against present bonds
    116       CompareBonds(Walker, CurrentBondsOfAtom, AtomNr, ListOfAtoms);
    11782    } else {
    118       if (AtomNr != -1)
     83      if (AtomNr != -1) {
    11984        ELOG(2, AtomNr << " is negative.");
     85        return false;
     86      }
    12087    }
    12188  }
     89  return true;
     90}
     91
     92/** Fills the InternalAtomBondMap from the atoms given by the two iterators.
     93 *
     94 * @param AtomMapBegin iterator pointing to begin of map (think of World's SelectionIterator)
     95 * @param AtomMapEnd iterator pointing past end of map (think of World's SelectionIterator)
     96 */
     97void CheckAgainstAdjacencyFile::CreateInternalMap(World::AtomSet::const_iterator &AtomMapBegin, World::AtomSet::const_iterator &AtomMapEnd)
     98{
     99  InternalAtomBondMap.clear();
     100  // go through each atom in the list
     101  for (World::AtomSet::const_iterator iter = AtomMapBegin; iter != AtomMapEnd; ++iter) {
     102    const atom *Walker = iter->second;
     103    const atomId_t WalkerId = Walker->getId();
     104    ASSERT(WalkerId != (size_t)-1,
     105        "CheckAgainstAdjacencyFile::CreateInternalMap() - Walker has no id.");
     106    const BondList& ListOfBonds = Walker->getListOfBonds();
     107    // go through each of its bonds
     108    for (BondList::const_iterator Runner = ListOfBonds.begin();
     109        Runner != ListOfBonds.end();
     110        ++Runner) {
     111      const atomId_t id = (*Runner)->GetOtherAtom(Walker)->getId();
     112      ASSERT(id != (size_t)-1,
     113          "CheckAgainstAdjacencyFile::CreateInternalMap() - OtherAtom has not id.");
     114      InternalAtomBondMap.insert( std::make_pair(WalkerId, id) );
     115    }
     116  }
     117}
     118
     119/** Checks contents of adjacency file against bond structure in structure molecule.
     120 * \param File file to parser
     121 * \return true - structure is equal, false - not equivalence
     122 */
     123bool CheckAgainstAdjacencyFile::operator()(std::istream &File)
     124{
     125  LOG(0, "STATUS: Looking at bond structure stored in adjacency file and comparing to present one ... ");
     126
     127  bool status = true;
     128
     129  status = status && ParseInExternalMap(File);
     130  status = status && CompareInternalExternalMap();
    122131
    123132  if (status) { // if equal we parse the KeySetFile
     
    127136  return status;
    128137}
    129 ;
     138
     139template <class T>
     140CheckAgainstAdjacencyFile::KeysSet getKeys(const CheckAgainstAdjacencyFile::AtomBondRange &_range)
     141{
     142  CheckAgainstAdjacencyFile::KeysSet Keys;
     143  for (typename T::const_iterator iter = _range.first;
     144      iter != _range.second;
     145      ++iter) {
     146    Keys.insert( iter->first );
     147  }
     148  return Keys;
     149}
     150
     151template <class T>
     152CheckAgainstAdjacencyFile::ValuesSet getValues(const CheckAgainstAdjacencyFile::AtomBondRange&_range)
     153{
     154  CheckAgainstAdjacencyFile::ValuesSet Values;
     155  for (typename T::const_iterator iter = _range.first;
     156      iter != _range.second;
     157      ++iter) {
     158    Values.insert( iter->second );
     159  }
     160  return Values;
     161}
     162
     163/** Counts the number of mismatching items in each set.
     164 *
     165 * @param firstset first set
     166 * @param secondset second set
     167 * @return number of items that don't match between first and second set
     168 */
     169template <class T>
     170size_t getMismatchingItems(const T &firstset, const T &secondset)
     171{
     172  size_t Mismatch = 0;
     173  typename T::const_iterator firstiter = firstset.begin();
     174  typename T::const_iterator seconditer = secondset.begin();
     175  for (; (firstiter != firstset.end()) && (seconditer != secondset.end());
     176      ++firstiter, ++seconditer) {
     177    if (*firstiter != *seconditer)
     178      ++Mismatch;
     179  }
     180  return Mismatch;
     181}
     182
     183/** Compares InternalAtomBondMap and ExternalAtomBondMap and sets NonMatchNumber.
     184 *
     185 * @return true - both maps are the same, false - both maps diverge by NonMatchNumber counts.
     186 */
     187bool CheckAgainstAdjacencyFile::CompareInternalExternalMap()
     188{
     189  NonMatchNumber = 0;
     190  // check whether sizes match
     191  if (ExternalAtomBondMap.size() != InternalAtomBondMap.size()) {
     192    NonMatchNumber = abs((int)ExternalAtomBondMap.size() - (int)InternalAtomBondMap.size());
     193    LOG(2, "INFO: " << NonMatchNumber << " entries don't match.");
     194    return false;
     195  }
     196  // extract keys and check whether they match
     197  const AtomBondRange Intrange(InternalAtomBondMap.begin(), InternalAtomBondMap.end());
     198  const AtomBondRange Extrange(ExternalAtomBondMap.begin(), ExternalAtomBondMap.end());
     199  KeysSet InternalKeys( getKeys<AtomBondMap>(Intrange) );
     200  KeysSet ExternalKeys( getKeys<AtomBondMap>(Extrange) );
     201
     202//  std::cout << "InternalKeys: " << InternalKeys << std::endl;
     203//  std::cout << "ExternalKeys: " << ExternalKeys << std::endl;
     204
     205  // check for same amount of keys
     206  if (InternalKeys.size() != ExternalKeys.size()) {
     207    NonMatchNumber = abs((int)ExternalKeys.size() - (int)InternalKeys.size());
     208    LOG(2, "INFO: Number of keys don't match: "
     209        << InternalKeys.size() << " != " << ExternalKeys.size());
     210    return false;
     211  }
     212
     213  // check items against one another
     214  NonMatchNumber = getMismatchingItems(InternalKeys, ExternalKeys);
     215
     216  if (NonMatchNumber != 0) {
     217    LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
     218    return false;
     219  }
     220
     221  // now check each map per key
     222  for (KeysSet::const_iterator keyIter = InternalKeys.begin();
     223      keyIter != InternalKeys.end();
     224      ++keyIter) {
     225//    std::cout << "Current key is " << *keyIter << std::endl;
     226    const AtomBondRange IntRange( InternalAtomBondMap.equal_range(*keyIter) );
     227    const AtomBondRange ExtRange( ExternalAtomBondMap.equal_range(*keyIter) );
     228    ValuesSet InternalValues( getValues<AtomBondMap>(IntRange) );
     229    ValuesSet ExternalValues( getValues<AtomBondMap>(ExtRange) );
     230//    std::cout << "InternalValues: " << InternalValues << std::endl;
     231//    std::cout << "ExternalValues: " << ExternalValues << std::endl;
     232    NonMatchNumber += getMismatchingItems(InternalValues, ExternalValues);
     233  }
     234  if (NonMatchNumber != 0) {
     235    LOG(2, "INFO: " << NonMatchNumber << " keys are not the same.");
     236    return false;
     237  } else {
     238    LOG(2, "INFO: All keys are the same.");
     239    return true;
     240  }
     241}
  • src/Graph/CheckAgainstAdjacencyFile.hpp

    r5fd0f4 rec87e4  
    1616#include <iosfwd>
    1717#include <map>
     18#include <set>
     19
     20#include "types.hpp"
     21#include "World.hpp"
    1822
    1923class atom;
     
    2125class CheckAgainstAdjacencyFile
    2226{
     27  //!> Unit test is granted access to internal data
     28  friend class CheckAgainstAdjacencyFileTest;
    2329public:
    24   CheckAgainstAdjacencyFile();
     30  CheckAgainstAdjacencyFile(World::AtomSet::const_iterator AtomMapBegin, World::AtomSet::const_iterator AtomMapEnd);
    2531  ~CheckAgainstAdjacencyFile();
    2632
    27   bool operator()(std::ifstream &File, std::map<int, atom*> ListOfAtoms);
     33  bool operator()(std::istream &File);
    2834
    2935private:
    30   enum {MAXBONDS=8};
    31 
    32   int *CurrentBonds;
     36  typedef std::set<atomId_t> KeysSet;
     37  typedef std::set<atomId_t> ValuesSet;
     38  typedef std::pair<atomId_t, atomId_t> AtomBondPair;
     39  typedef std::multimap< atomId_t, atomId_t > AtomBondMap;
     40  typedef std::pair<AtomBondMap::const_iterator, AtomBondMap::const_iterator> AtomBondRange;
     41  AtomBondMap InternalAtomBondMap;
     42  AtomBondMap ExternalAtomBondMap;
    3343  bool status;
    3444  int NonMatchNumber;
    3545
    36   void CompareBonds(const atom *&Walker, size_t &CurrentBondsOfAtom, int AtomNr, std::map<int, atom*> &ListOfAtoms);
     46  void CreateInternalMap(World::AtomSet::const_iterator &AtomMapBegin, World::AtomSet::const_iterator &AtomMapEnd);
     47  bool ParseInExternalMap(std::istream &File);
     48  bool CompareInternalExternalMap();
    3749};
    3850
  • src/Graph/unittests/Makefile.am

    r5fd0f4 rec87e4  
    33
    44GRAPHTESTSSOURCES = \
    5         ../Graph/unittests/BondGraphUnitTest.cpp
     5        ../Graph/unittests/BondGraphUnitTest.cpp \
     6        ../Graph/unittests/CheckAgainstAdjacencyFileUnitTest.cpp
    67
    78GRAPHTESTSHEADERS = \
    8         ../Graph/unittests/BondGraphUnitTest.hpp
     9        ../Graph/unittests/BondGraphUnitTest.hpp \
     10        ../Graph/unittests/CheckAgainstAdjacencyFileUnitTest.hpp
    911
    1012GRAPHTESTS = \
    11   BondGraphUnitTest
     13        BondGraphUnitTest \
     14        CheckAgainstAdjacencyFileUnitTest
     15
    1216
    1317TESTS += $(GRAPHTESTS)
     
    2832BondGraphUnitTest_LDADD = ${GRAPHLIBS}
    2933
     34CheckAgainstAdjacencyFileUnitTest_SOURCES = $(top_srcdir)/src/unittests/UnitTestMain.cpp \
     35        ../Graph/unittests/CheckAgainstAdjacencyFileUnitTest.cpp \
     36        ../Graph/unittests/CheckAgainstAdjacencyFileUnitTest.hpp
     37CheckAgainstAdjacencyFileUnitTest_LDADD = ${ALLLIBS}
     38
    3039
    3140
  • src/molecule_fragmentation.cpp

    r5fd0f4 rec87e4  
    659659  {
    660660    std::ifstream File;
    661     string filename;
     661    std::string filename;
    662662    filename = prefix + ADJACENCYFILE;
    663663    File.open(filename.c_str(), ios::out);
    664664    DoLog(1) && (Log() << Verbose(1) << "Looking at bond structure stored in adjacency file and comparing to present one ... " << endl);
    665     std::map<int, atom*> ListOfAtoms;
    666     std::pair<std::map<int, atom*>::iterator, bool> inserter;
    667     for (const_iterator iter = begin();
    668         iter != end();
    669         ++iter) {
    670       atom *Walker = *iter;
    671       inserter = ListOfAtoms.insert( make_pair( Walker->GetTrueFather()->getNr(), Walker) );
    672       FragmentationToDo = FragmentationToDo && inserter.second;
    673     }
    674     CheckAgainstAdjacencyFile FileChecker;
    675     FragmentationToDo = FragmentationToDo && FileChecker(File, ListOfAtoms);
     665
     666    CheckAgainstAdjacencyFile FileChecker(World::getInstance().beginAtomSelection(), World::getInstance().endAtomSelection());
     667    FragmentationToDo = FragmentationToDo && FileChecker(File);
    676668  }
    677669
Note: See TracChangeset for help on using the changeset viewer.