File: SmilesParse.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 (220 lines) | stat: -rw-r--r-- 6,787 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
// $Id: SmilesParse.cpp 1981 2012-03-01 09:49:40Z 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.
//

// ----------------------------------------------------------------------------------
//  Despite the name of this file, both SMILES and SMARTS parsers are exposed here
//
//  General comments about the parsers:
//   - Atom numbering will be preserved, so input order of atoms==internal order
//
//   - Bond ordering is not, in general, preserved.  Specifically, ring closure
//     bonds will occur at the end of the bond list in general.  Basically ring
//     closure bonds are not constructed until fragments are closed.  This forces
//     some form of reordering.
//     
//
//
#include <GraphMol/RDKitBase.h>
#include "SmilesParse.h"
#include "SmilesParseOps.h"
#include <RDGeneral/RDLog.h>
#include <RDGeneral/Invariant.h>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

int yysmiles_parse (const char *,std::vector<RDKit::RWMol *>*,void *);
int yysmiles_lex_init (void **);
int yysmiles_lex_destroy (void *);
void setup_smiles_string(const std::string &text,void *);
extern int yysmiles_debug; 

int yysmarts_parse (const char *,std::vector<RDKit::RWMol *>*,void *);
int yysmarts_lex_init (void **);
int yysmarts_lex_destroy (void *);
void setup_smarts_string(const std::string &text,void *);
extern int yysmarts_debug; 
namespace RDKit{
  namespace {
    int smiles_parse(const std::string &inp,
		     std::vector<RDKit::RWMol *> &molVect){
      void *scanner;
      TEST_ASSERT(!yysmiles_lex_init(&scanner));
      setup_smiles_string(inp,scanner);
      int res=yysmiles_parse(inp.c_str(),&molVect,scanner);
      yysmiles_lex_destroy(scanner);
      return res;
    }
    int smarts_parse(const std::string &inp,
		     std::vector<RDKit::RWMol *> &molVect){
      void *scanner;
      TEST_ASSERT(!yysmarts_lex_init(&scanner));
      setup_smarts_string(inp,scanner);
      int res=yysmarts_parse(inp.c_str(),&molVect,scanner);
      yysmarts_lex_destroy(scanner);
      return res;
    }

    typedef enum {
      BASE=0,
      BRANCH,
      RECURSE
    } SmaState;

    std::string labelRecursivePatterns(std::string sma){
#ifndef NO_AUTOMATIC_SMARTS_RELABELLING
      std::list<SmaState> state;
      std::list<unsigned int> startRecurse;
      std::map<std::string, std::string> patterns;
      std::string res="";

      state.push_back(BASE);

      unsigned int pos=0;
      while(pos<sma.size()){
	res += sma[pos];
	if(sma[pos]=='$' && pos+1<sma.size() && sma[pos+1]=='('){
	  state.push_back(RECURSE);
	  startRecurse.push_back(pos);
	  ++pos;
	  res += sma[pos];
	} else if(sma[pos]=='('){
	  state.push_back(BRANCH);
	} else if(sma[pos]==')'){
	  SmaState currState=state.back();
	  state.pop_back();
	  if(currState==RECURSE){
	    unsigned int dollarPos=startRecurse.back();
	    startRecurse.pop_back();
	    if(pos+1>=sma.size() || sma[pos+1] !='_'){
	      std::string recurs = sma.substr(dollarPos,pos-dollarPos+1);
	      std::string label;
	      if(patterns.find(recurs)!=patterns.end()){
		// seen this one before, add the label
		label=patterns[recurs];
	      } else {
		label=boost::lexical_cast<std::string>(patterns.size()+100);
		patterns[recurs]=label;
	      }
	      res += "_" + label;
	    }
	  } else if(currState==BRANCH) {
	    // no need to do anything here.
	  }
	}
	++pos;
      }
      //std::cerr<< " >"<<sma<<"->"<<res<<std::endl;
      return res;
#else
      return sma;
#endif
    }
  } // end of local namespace

  RWMol *toMol(std::string inp,int func(const std::string &,
					std::vector<RDKit::RWMol *> &),
               std::string origInp){
    RWMol *res;
    std::vector<RDKit::RWMol *> molVect;
    try {
      func(inp,molVect);
      if(molVect.size()<=0){
	res = 0;
      } else {
	res = molVect[0];
	molVect[0]=0;
	SmilesParseOps::CloseMolRings(res,false);
	SmilesParseOps::AdjustAtomChiralityFlags(res);
	// No sense leaving this bookmark intact:
	if(res->hasAtomBookmark(ci_RIGHTMOST_ATOM)){
	  res->clearAtomBookmark(ci_RIGHTMOST_ATOM);
	}
      }
    } catch (SmilesParseException &e) {
      std::string nm="SMILES";
      if(func==smarts_parse){
        nm="SMARTS";
        
      }
      BOOST_LOG(rdErrorLog) << nm<<" Parse Error: "<< e.message() << " for input: "<< origInp << std::endl;
      res = 0;
    }
    BOOST_FOREACH(RDKit::RWMol *molPtr,molVect){
      if(molPtr) delete molPtr;
    }

    return res;
  }

  RWMol *SmilesToMol(std::string smi,int debugParse,bool sanitize,
                     std::map<std::string,std::string> *replacements){
    yysmiles_debug = debugParse;
    // strip any leading/trailing whitespace:
    boost::trim_if(smi,boost::is_any_of(" \t\r\n"));

    if(replacements){
      bool loopAgain=true;
      while(loopAgain){
        loopAgain=false;
        for(std::map<std::string, std::string>::const_iterator replIt=replacements->begin();
            replIt!=replacements->end();++replIt){
          if(boost::find_first(smi,replIt->first)){
            loopAgain=true;
            boost::replace_all(smi,replIt->first,replIt->second);
          }
        }
      }
    }

    RWMol *res = toMol(smi,smiles_parse,smi);
    if(sanitize && res){
      // we're going to remove explicit Hs from the graph,
      // this triggers a sanitization, so we do not need to
      // worry about doing one here:
      ROMol *tmp = MolOps::removeHs(*res,false,false);
      delete res;
      res = static_cast<RWMol *>(tmp);
      // figure out stereochemistry:
      MolOps::assignStereochemistry(*res,true);
    }

    return res;
  };
  RWMol *SmartsToMol(std::string sma,int debugParse,bool mergeHs,
                     std::map<std::string, std::string> *replacements){
    yysmarts_debug = debugParse;
    boost::trim_if(sma,boost::is_any_of(" \t\r\n"));
    if(replacements){
      bool loopAgain=true;
      while(loopAgain){
        loopAgain=false;
        for(std::map<std::string, std::string>::const_iterator replIt=replacements->begin();
            replIt!=replacements->end();++replIt){
          if(boost::find_first(sma,replIt->first)){
            loopAgain=true;
            boost::replace_all(sma,replIt->first,replIt->second);
          }
        }
      }
    }
    std::string oInput=sma;
    sma=labelRecursivePatterns(sma);

    RWMol *res = toMol(sma,smarts_parse,oInput);
    if(res && mergeHs){
      ROMol *tmp = MolOps::mergeQueryHs(*res);
      delete res;
      res = static_cast<RWMol *>(tmp);
    }
    return res;
  };
}