File: SubstructMatch.cpp

package info (click to toggle)
rdkit 201203-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 37,840 kB
  • sloc: cpp: 93,902; python: 51,897; java: 5,192; ansic: 3,497; xml: 2,499; sql: 1,641; yacc: 1,518; lex: 1,076; makefile: 325; fortran: 183; sh: 153; cs: 51
file content (284 lines) | stat: -rw-r--r-- 9,219 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// $Id: SubstructMatch.cpp 1625 2011-01-13 04:22:56Z glandrum $
//
//  Copyright (C) 2001-2010 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#include <RDGeneral/utils.h>
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/RDKitQueries.h>
#include "SubstructMatch.h"
#include "SubstructUtils.h"
#include <boost/smart_ptr.hpp>
#include <map>

#include "ullmann.hpp"
#include "vf2.hpp"

namespace RDKit{
  namespace detail {
    typedef std::map<unsigned int,QueryAtom::QUERYATOM_QUERY *> SUBQUERY_MAP;
    
    void MatchSubqueries(const ROMol &mol,QueryAtom::QUERYATOM_QUERY *q,bool useChirality,
			 SUBQUERY_MAP &subqueryMap );

    typedef std::list<std::pair<MolGraph::vertex_descriptor,MolGraph::vertex_descriptor> > ssPairType;

    class AtomLabelFunctor{
    public:
      AtomLabelFunctor(const ROMol &query,const ROMol &mol, bool useChirality) :
        d_query(query), d_mol(mol), df_useChirality(useChirality) {};
      bool operator()(unsigned int i,unsigned int j) const{
        bool res=false;
        if(!df_useChirality){
          res=atomCompat(d_query[i],d_mol[j]);
        } else {
          res=chiralAtomCompat(d_query[i],d_mol[j]);
        }
        //std::cerr<<" alf: "<<i<<" - "<<j<<"? "<<res<<std::endl;
        return res;
      }
    private:
      const ROMol &d_query;
      const ROMol &d_mol;
      bool df_useChirality;
    };
    class BondLabelFunctor{
    public:
      BondLabelFunctor(const ROMol &query,const ROMol &mol) :
        d_query(query), d_mol(mol) {};
      bool operator()(MolGraph::edge_descriptor i,MolGraph::edge_descriptor j) const{
        bool res=bondCompat(d_query[i],d_mol[j]);
        //std::cerr<<" blf: "<<i<<" - "<<j<<"? "<<res<<std::endl;
        return res;
      }
    private:
      const ROMol &d_query;
      const ROMol &d_mol;
    };
  }    
  
  // ----------------------------------------------
  //
  // find one match
  //
  bool SubstructMatch(const ROMol &mol,const ROMol &query,MatchVectType &matchVect,
                      bool recursionPossible,bool useChirality)
  {

    //std::cerr<<"begin match"<<std::endl;
    if(recursionPossible){
      ROMol::ConstAtomIterator atIt;
      detail::SUBQUERY_MAP subqueryMap;
      for(atIt=query.beginAtoms();atIt!=query.endAtoms();atIt++){
        if((*atIt)->getQuery()){
	  detail::MatchSubqueries(mol,(*atIt)->getQuery(),useChirality,
				  subqueryMap);
        }
      }
    }
    //std::cerr<<"main matching"<<std::endl;

    matchVect.clear();
    matchVect.resize(0);

    detail::AtomLabelFunctor atomLabeler(query,mol,useChirality);
    detail::BondLabelFunctor bondLabeler(query,mol);

    detail::ssPairType match;
#if 0
    bool res=boost::ullmann(query.getTopology(),mol.getTopology(),
                            atomLabeler,bondLabeler,match);
#else
    bool res=boost::vf2(query.getTopology(),mol.getTopology(),
                        atomLabeler,bondLabeler,match);
#endif
    if(res){
     matchVect.resize(query.getNumAtoms());
     for(detail::ssPairType::const_iterator iter=match.begin();iter!=match.end();++iter){
       matchVect[iter->first]=std::pair<int,int>(iter->first,iter->second);
     }
    }    

    return res;
  }


  // ----------------------------------------------
  //
  // find all matches
  //
  //  NOTE: this blows out the contents of matches
  //
  unsigned int SubstructMatch(const ROMol &mol,const ROMol &query,
			      std::vector< MatchVectType > &matches,
			      bool uniquify,bool recursionPossible,
			      bool useChirality){

    if(recursionPossible){
      detail::SUBQUERY_MAP subqueryMap;
      ROMol::ConstAtomIterator atIt;
      for(atIt=query.beginAtoms();atIt!=query.endAtoms();atIt++){
        if((*atIt)->getQuery()){
          //std::cerr<<"recurse from atom "<<(*atIt)->getIdx()<<std::endl;
	  detail::MatchSubqueries(mol,(*atIt)->getQuery(),useChirality,subqueryMap);
        }
      }
    }

    matches.clear();
    matches.resize(0);

    detail::AtomLabelFunctor atomLabeler(query,mol,useChirality);
    detail::BondLabelFunctor bondLabeler(query,mol);
    
    std::list<detail::ssPairType> pms;
#if 0
    bool found=boost::ullmann_all(query.getTopology(),mol.getTopology(),
                                  atomLabeler,bondLabeler,pms);
#else
    bool found=boost::vf2_all(query.getTopology(),mol.getTopology(),
                                  atomLabeler,bondLabeler,pms);
#endif
    unsigned int res=0;
    if(found){
      unsigned int nQueryAtoms=query.getNumAtoms();
      matches.reserve(pms.size());
      for(std::list<detail::ssPairType>::const_iterator iter1=pms.begin();
          iter1!=pms.end();++iter1){
        MatchVectType matchVect;
        matchVect.resize(nQueryAtoms);
        for(detail::ssPairType::const_iterator iter2=iter1->begin();
            iter2!=iter1->end();++iter2){
          matchVect[iter2->first]=std::pair<int,int>(iter2->first,iter2->second);
        }
        matches.push_back(matchVect);
      }
      if(uniquify){
        removeDuplicates(matches,mol.getNumAtoms());
      }
      res = matches.size();
    } 
    return res;
  }

  namespace detail {
    unsigned int RecursiveMatcher(const ROMol &mol,const ROMol &query,
				  std::vector< int > &matches,bool useChirality,
				  SUBQUERY_MAP &subqueryMap)
    {
      ROMol::ConstAtomIterator atIt;
      for(atIt=query.beginAtoms();atIt!=query.endAtoms();atIt++){
	if((*atIt)->getQuery()){
	  MatchSubqueries(mol,(*atIt)->getQuery(),useChirality,subqueryMap);
	}
      }
 
      detail::AtomLabelFunctor atomLabeler(query,mol,useChirality);
      detail::BondLabelFunctor bondLabeler(query,mol);

      matches.clear();
      matches.resize(0);
      std::list<detail::ssPairType> pms;
#if 0
      bool found=boost::ullmann_all(query.getTopology(),mol.getTopology(),
				    atomLabeler,bondLabeler,pms);
#else
      bool found=boost::vf2_all(query.getTopology(),mol.getTopology(),
				atomLabeler,bondLabeler,pms);
#endif
      unsigned int res=0;
      if(found){
	matches.reserve(pms.size());
	for(std::list<detail::ssPairType>::const_iterator iter1=pms.begin();
	    iter1!=pms.end();++iter1){
	  if(!query.hasProp("_queryRootAtom")){
	    matches.push_back(iter1->begin()->second);
	  } else {
	    int rootIdx;
	    query.getProp("_queryRootAtom",rootIdx);
	    bool found=false;
	    for(detail::ssPairType::const_iterator pairIter=iter1->begin();
		pairIter!=iter1->end();++pairIter){
	      if(pairIter->first==rootIdx){
		matches.push_back(pairIter->second);
		found=true;
		break;
	      }
	    }
	    if(!found){
	      BOOST_LOG(rdErrorLog)<<"no match found for queryRootAtom"<<std::endl;
	    }
	  }
	}
	res = matches.size();
      } 
      //std::cout << " <<< RecursiveMatcher: " << int(query) << std::endl;
      return res;
    }

    void MatchSubqueries(const ROMol &mol,QueryAtom::QUERYATOM_QUERY *query,bool useChirality,
			 SUBQUERY_MAP &subqueryMap){
      PRECONDITION(query,"bad query");
      //std::cout << "*-*-* MS: " << (int)query << std::endl;
      //std::cout << "\t\t" << typeid(*query).name() << std::endl;
      if(query->getDescription()=="RecursiveStructure"){
	RecursiveStructureQuery *rsq=(RecursiveStructureQuery *)query;
	rsq->clear();

	bool matchDone=false;
	if(rsq->getSerialNumber() &&
	   subqueryMap.find(rsq->getSerialNumber()) != subqueryMap.end()){
	  // we've matched an equivalent serial number before, just
	  // copy in the matches:
	  matchDone=true;
	  const RecursiveStructureQuery *orsq=
	    (const RecursiveStructureQuery *)subqueryMap[rsq->getSerialNumber()];
	  for(RecursiveStructureQuery::CONTAINER_TYPE::const_iterator setIter=orsq->beginSet();
	      setIter!=orsq->endSet();++setIter){
	    rsq->insert(*setIter);
	  }
	  //std::cerr<<" copying results for query serial number: "<<rsq->getSerialNumber()<<std::endl;
	}
	
	if(!matchDone){
	  ROMol const *queryMol = rsq->getQueryMol();
	  // in case we are reusing this query, clear its contents now.
	  if(queryMol){
	    std::vector< int > matchStarts;
	    unsigned int res = RecursiveMatcher(mol,*queryMol,matchStarts,useChirality,
						subqueryMap);
	    if(res){
	      for(std::vector<int>::iterator i=matchStarts.begin();
		  i!=matchStarts.end();
		  i++){
		rsq->insert(*i);
	      }
	    }
	  }
	  if(rsq->getSerialNumber()){
	    subqueryMap[rsq->getSerialNumber()]=query;
	    //std::cerr<<" storing results for query serial number: "<<rsq->getSerialNumber()<<std::endl;
	  }

	}
      } else {
	//std::cout << "\tmsq1: "; 
      }
  
      // now recurse over our children (these things can be nested)
      Queries::Query<int,Atom const*,true>::CHILD_VECT_CI childIt;
      //std::cout << query << " " << query->endChildren()-query->beginChildren() <<  std::endl;
      for(childIt=query->beginChildren();childIt!=query->endChildren();childIt++){
	MatchSubqueries(mol,childIt->get(),useChirality,subqueryMap);
      }
      //std::cout << "<<- back " << (int)query << std::endl;
    }
  } // end of namespace detail
}