File: rdChemReactions.cpp

package info (click to toggle)
rdkit 201403-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 62,288 kB
  • ctags: 15,156
  • sloc: cpp: 125,376; python: 55,674; java: 4,831; ansic: 4,178; xml: 2,499; sql: 1,775; yacc: 1,551; lex: 1,051; makefile: 353; fortran: 183; sh: 148; cs: 93
file content (344 lines) | stat: -rw-r--r-- 15,553 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// $Id$
//
//  Copyright (c) 2007, Novartis Institutes for BioMedical Research Inc.
//  All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: 
//
//     * Redistributions of source code must retain the above copyright 
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following 
//       disclaimer in the documentation and/or other materials provided 
//       with the distribution.
//     * Neither the name of Novartis Institutues for BioMedical Research Inc. 
//       nor the names of its contributors may be used to endorse or promote 
//       products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <boost/python.hpp>
#include <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/ChemReactions/ReactionPickler.h>
#include <GraphMol/ChemReactions/ReactionParser.h>
#include <GraphMol/Depictor/DepictUtils.h>

#include <RDBoost/Wrap.h>
#include <RDBoost/Exceptions.h>
#include <GraphMol/SanitException.h>
#include <RDGeneral/FileParseException.h>

namespace python = boost::python;


void rdChemicalReactionParserExceptionTranslator(RDKit::ChemicalReactionParserException const& x){
  std::ostringstream ss;
  ss << "ChemicalReactionParserException: " << x.message();
  PyErr_SetString(PyExc_ValueError,ss.str().c_str());
}
void rdChemicalReactionExceptionTranslator(RDKit::ChemicalReactionException const& x){
  std::ostringstream ss;
  ss << "ChemicalParserException: " << x.message();
  PyErr_SetString(PyExc_ValueError,ss.str().c_str());
}

namespace RDKit {
  std::string ReactionToBinary(const ChemicalReaction &self){
    std::string res;
    ReactionPickler::pickleReaction(self,res);
    return res;
  }
  //
  // allows reactions to be pickled.
  //
  struct reaction_pickle_suite : python::pickle_suite
  {
    static python::tuple
    getinitargs(const ChemicalReaction & self)
    {
      return python::make_tuple(ReactionToBinary(self));
    };
  };


  template <typename T>
  PyObject* RunReactants(ChemicalReaction *self,T reactants){
    if(!self->isInitialized()){
      self->initReactantMatchers();
    }
    MOL_SPTR_VECT reacts;
    unsigned int len1 = python::extract<unsigned int>(reactants.attr("__len__")());
    reacts.resize(len1);
    for(unsigned int i=0;i<len1;++i){
      reacts[i] = python::extract<ROMOL_SPTR>(reactants[i]);
      if(!reacts[i]) throw_value_error("reaction called with None reactants");
    }
    std::vector<MOL_SPTR_VECT> mols;
    mols = self->runReactants(reacts);
    PyObject *res=PyTuple_New(mols.size());
    
    for(unsigned int i=0;i<mols.size();++i){
      PyObject *lTpl =PyTuple_New(mols[i].size());
      for(unsigned int j=0;j<mols[i].size();++j){
        PyTuple_SetItem(lTpl,j,
          python::converter::shared_ptr_to_python(mols[i][j]));
      }
      PyTuple_SetItem(res,i,lTpl);
    }
    return res;
  }

  python::tuple ValidateReaction(const ChemicalReaction *self,bool silent=false){
    unsigned int numWarn,numError;
    self->validate(numWarn,numError,silent);
    return python::make_tuple(numWarn,numError);
  }

  ROMol * GetProductTemplate(const ChemicalReaction *self,unsigned int which){
    if(which>=self->getNumProductTemplates()){
      throw_value_error("requested template index too high");
    }
    MOL_SPTR_VECT::const_iterator iter=self->beginProductTemplates();
    iter += which;
    ROMol *res = const_cast<ROMol *>(iter->get());
    return res;
  }
  ROMol * GetReactantTemplate(const ChemicalReaction *self,unsigned int which){
    if(which>=self->getNumReactantTemplates()){
      throw_value_error("requested template index too high");
    }
    MOL_SPTR_VECT::const_iterator iter=self->beginReactantTemplates();
    iter += which;
    ROMol *res = const_cast<ROMol *>(iter->get());
    return res;
  }

  void Compute2DCoordsForReaction(RDKit::ChemicalReaction &rxn,
                                  double spacing=2.0,
                                  bool updateProps=true,
                                  bool canonOrient=false,
                                  unsigned int nFlipsPerSample=0,
                                  unsigned int nSamples=0,
                                  int sampleSeed=0,
                                  bool permuteDeg4Nodes=false,
                                  double bondLength=-1){
    double oBondLen=RDDepict::BOND_LEN;
    if(bondLength>0){
      RDDepict::BOND_LEN=bondLength;
    }
    RDDepict::compute2DCoordsForReaction(rxn,spacing,updateProps,canonOrient,
                                         nFlipsPerSample,nSamples,sampleSeed,
                                         permuteDeg4Nodes);
    if(bondLength>0){
      RDDepict::BOND_LEN=oBondLen;
    }
  }

  bool IsMoleculeReactantOfReaction(const ChemicalReaction &rxn,const ROMol &mol){
    unsigned int which;
    return isMoleculeReactantOfReaction(rxn,mol,which);
  }
  bool IsMoleculeProductOfReaction(const ChemicalReaction &rxn,const ROMol &mol){
    unsigned int which;
    return isMoleculeProductOfReaction(rxn,mol,which);
  }
  

  ChemicalReaction *ReactionFromSmarts(const char *smarts,
                                       python::dict replDict,
                                       bool useSmiles){
    PRECONDITION(smarts,"null SMARTS string");
    std::map<std::string,std::string> replacements;
    for(unsigned int i=0;i<python::extract<unsigned int>(replDict.keys().attr("__len__")());++i){
      replacements[python::extract<std::string>(replDict.keys()[i])]=python::extract<std::string>(replDict.values()[i]);
    }
    ChemicalReaction *res; 
    res = RxnSmartsToChemicalReaction(smarts,&replacements,useSmiles);
    return res;
  }
  
  python::object GetReactingAtoms(const ChemicalReaction &self,bool mappedAtomsOnly){
    python::list res;
    VECT_INT_VECT rAs=getReactingAtoms(self,mappedAtomsOnly);
    for(VECT_INT_VECT_I rIt=rAs.begin();rIt!=rAs.end();++rIt){
      res.append(python::tuple(*rIt));
    }
    return python::tuple(res);
  }

  python::object AddRecursiveQueriesToReaction(ChemicalReaction &self, python::dict queryDict,
                                     std::string propName, bool getLabels=false){
    // transform dictionary into map
    std::map<std::string, ROMOL_SPTR> queries;
    for(unsigned int i=0;i<python::extract<unsigned int>(queryDict.keys().attr("__len__")());++i){
      ROMol *m = python::extract<ROMol *>(queryDict.values()[i]);
      ROMOL_SPTR nm(new ROMol(*m));
      std::string k = python::extract<std::string>(queryDict.keys()[i]);
      queries[k]=nm;
    }

    if (getLabels) {
      std::vector<std::vector<std::pair<unsigned int, std::string> > > labels;
      addRecursiveQueriesToReaction(self, queries, propName, &labels);

      // transform labels into python::tuple(python::tuple(python::tuple))
      python::list reactantLabels;
      for (unsigned int i=0; i<labels.size(); ++i) {
        python::list tmpLabels;
        for (unsigned int j=0; j<labels[i].size(); ++j) {
          python::list tmpPair;
          tmpPair.append(labels[i][j].first);
          tmpPair.append(labels[i][j].second);
          tmpLabels.append(python::tuple(tmpPair));
        }
        reactantLabels.append(python::tuple(tmpLabels));
      }
      return python::tuple(reactantLabels);
    } else {
      addRecursiveQueriesToReaction(self, queries, propName);
      return python::object(); // this is None
    }
  }
}

BOOST_PYTHON_MODULE(rdChemReactions) {
  python::scope().attr("__doc__") =
    "Module containing classes and functions for working with chemical reactions."
    ;

  python::register_exception_translator<RDKit::ChemicalReactionParserException>(&rdChemicalReactionParserExceptionTranslator);
  python::register_exception_translator<RDKit::ChemicalReactionException>(&rdChemicalReactionExceptionTranslator);
    
  std::string docString = "A class for storing and applying chemical reactions.\n\
\n\
Sample Usage:\n\
>>> rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]')\n\
>>> reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('CNC'))\n\
>>> products = rxn.RunReactants(reacts)\n\
>>> len(products)\n\
1\n\
>>> len(products[0])\n\
1\n\
>>> Chem.MolToSmiles(products[0])\n\
'CN(C)C=O'\n\
\n\
";
  python::class_<RDKit::ChemicalReaction>("ChemicalReaction",docString.c_str(),
                                          python::init<>("Constructor, takes no arguments"))
    .def(python::init<const std::string &>())
    .def("GetNumReactantTemplates",&RDKit::ChemicalReaction::getNumReactantTemplates,
         "returns the number of reactants this reaction expects")
    .def("GetNumProductTemplates",&RDKit::ChemicalReaction::getNumProductTemplates,
         "returns the number of products this reaction generates")
    .def("AddReactantTemplate",&RDKit::ChemicalReaction::addReactantTemplate,
         "adds a reactant (a Molecule) to the reaction")
    .def("AddProductTemplate",&RDKit::ChemicalReaction::addProductTemplate,
         "adds a product (a Molecule)")
    .def("RunReactants",(PyObject *(*)(RDKit::ChemicalReaction *,python::tuple))RDKit::RunReactants,
         "apply the reaction to a sequence of reactant molecules and return the products as a tuple of tuples")
    .def("RunReactants",(PyObject *(*)(RDKit::ChemicalReaction *,python::list))RDKit::RunReactants,
         "apply the reaction to a sequence of reactant molecules and return the products as a tuple of tuples")
    .def("Initialize",&RDKit::ChemicalReaction::initReactantMatchers,
         "initializes the reaction so that it can be used")
    .def("IsInitialized",&RDKit::ChemicalReaction::isInitialized,
         "checks if the reaction is ready for use")
    .def("Validate",&RDKit::ValidateReaction,
         (python::arg("self"),python::arg("silent")=false),
         "checks the reaction for potential problems, returns (numWarnings,numErrors)")
    .def("GetProductTemplate",&RDKit::GetProductTemplate,
         (python::arg("self"),python::arg("which")),
         python::return_value_policy<python::reference_existing_object>(),
         "returns one of our product templates")
    .def("GetReactantTemplate",&RDKit::GetReactantTemplate,
         (python::arg("self"),python::arg("which")),
         python::return_value_policy<python::reference_existing_object>(),
         "returns one of our reactant templates")
    .def("_setImplicitPropertiesFlag",&RDKit::ChemicalReaction::setImplicitPropertiesFlag,
         (python::arg("self"),python::arg("val")),
         "EXPERT USER: indicates that the reaction can have implicit properties")
    .def("_getImplicitPropertiesFlag",&RDKit::ChemicalReaction::getImplicitPropertiesFlag,
         (python::arg("self")),
         "EXPERT USER: returns whether or not the reaction can have implicit properties")
    .def("ToBinary",RDKit::ReactionToBinary,
         "Returns a binary string representation of the reaction.")
    .def("IsMoleculeReactant",RDKit::IsMoleculeReactantOfReaction,
         "returns whether or not the molecule has a substructure match to one of the reactants.")
    .def("IsMoleculeProduct",RDKit::IsMoleculeProductOfReaction,
         "returns whether or not the molecule has a substructure match to one of the products.")
    .def("GetReactingAtoms",&RDKit::GetReactingAtoms,
         (python::arg("self"),python::arg("mappedAtomsOnly")=false),
         "returns a sequence of sequences with the atoms that change in the reaction")
    .def("AddRecursiveQueriesToReaction", RDKit::AddRecursiveQueriesToReaction,
         (python::arg("reaction"), python::arg("queries")=python::dict(),
          python::arg("propName")="molFileValue", python::arg("getLabels")=false),
         "adds recursive queries and returns reactant labels")
    // enable pickle support
    .def_pickle(RDKit::reaction_pickle_suite())
  ;


  python::def("ReactionFromSmarts",RDKit::ReactionFromSmarts,
              (python::arg("SMARTS"),
               python::arg("replacements")=python::dict(),
               python::arg("useSmiles")=false),
              "construct a ChemicalReaction from a reaction SMARTS string. \n\
see the documentation for rdkit.Chem.MolFromSmiles for an explanation\n\
of the replacements argument.",
      python::return_value_policy<python::manage_new_object>());
  python::def("ReactionFromRxnFile",RDKit::RxnFileToChemicalReaction,
      "construct a ChemicalReaction from an MDL rxn file",
      python::return_value_policy<python::manage_new_object>());
  python::def("ReactionFromRxnBlock",RDKit::RxnBlockToChemicalReaction,
      "construct a ChemicalReaction from an string in MDL rxn format",
      python::return_value_policy<python::manage_new_object>());

  python::def("ReactionToSmarts",RDKit::ChemicalReactionToRxnSmarts,
      (python::arg("reaction")),
      "construct a reaction SMARTS string for a ChemicalReaction");
  python::def("ReactionToRxnBlock",RDKit::ChemicalReactionToRxnBlock,
      (python::arg("reaction")),
      "construct a string in MDL rxn format for a ChemicalReaction");

  docString = "Compute 2D coordinates for a reaction. \n\
  ARGUMENTS: \n\n\
     reaction - the reaction of interest\n\
     spacing - the amount of space left between components of the reaction\n\
     canonOrient - orient the reactants and products in a canonical way\n\
     updateProps - if set, properties such as conjugation and\n\
        hybridization will be calculated for the reactant and product\n\
        templates before generating coordinates. This should result in\n\
        better depictions, but can lead to errors in some cases.\n\
     nFlipsPerSample - number of rotatable bonds that are\n\
                flipped at random at a time.\n\
     nSample - Number of random samplings of rotatable bonds.\n\
     sampleSeed - seed for the random sampling process.\n\
     permuteDeg4Nodes - allow permutation of bonds at a degree 4\n\
                 node during the sampling process \n\
     bondLength - change the default bond length for depiction \n\n";
  python::def("Compute2DCoordsForReaction",
              RDKit::Compute2DCoordsForReaction,
	      (python::arg("reaction"),
	       python::arg("spacing")=2.0,
	       python::arg("updateProps")=true,
	       python::arg("canonOrient")=true,
               python::arg("nFlipsPerSample")=0,
               python::arg("nSample")=0,
               python::arg("sampleSeed")=0,
               python::arg("permuteDeg4Nodes")=false,
               python::arg("bondLength")=-1.0),
	      docString.c_str());

}