RDKit
Open-source cheminformatics and machine learning.
Reaction.h
Go to the documentation of this file.
1 //
2 // Copyright (c) 2007-2018, Novartis Institutes for BioMedical Research Inc.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following
13 // disclaimer in the documentation and/or other materials provided
14 // with the distribution.
15 // * Neither the name of Novartis Institutes for BioMedical Research Inc.
16 // nor the names of its contributors may be used to endorse or promote
17 // products derived from this software without specific prior written
18 // permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 //
32 
33 #include <RDGeneral/export.h>
34 #ifndef RD_REACTION_H_17Aug2006
35 #define RD_REACTION_H_17Aug2006
36 
37 #include <GraphMol/RDKitBase.h>
38 #include <RDGeneral/RDProps.h>
40 #include <vector>
41 
42 namespace RDKit {
43 class ReactionPickler;
44 
45 //! used to indicate an error in the chemical reaction engine
47  public:
48  //! construct with an error message
49  explicit ChemicalReactionException(const char *msg) : _msg(msg){};
50  //! construct with an error message
51  explicit ChemicalReactionException(const std::string msg) : _msg(msg){};
52  //! get the error message
53  const char *message() const { return _msg.c_str(); };
55 
56  private:
57  std::string _msg;
58 };
59 
60 //! This is a class for storing and applying general chemical reactions.
61 /*!
62  basic usage will be something like:
63 
64  \verbatim
65  ChemicalReaction rxn;
66  rxn.addReactantTemplate(r1);
67  rxn.addReactantTemplate(r2);
68  rxn.addProductTemplate(p1);
69  rxn.initReactantMatchers();
70 
71  MOL_SPTR_VECT prods;
72  for(MOL_SPTR_VECT::const_iterator r1It=reactantSet1.begin();
73  r1It!=reactantSet1.end();++r1It;){
74  for(MOL_SPTR_VECT::const_iterator r2It=reactantSet2.begin();
75  r2It!=reactantSet2.end();++r2It;){
76  MOL_SPTR_VECT rVect(2);
77  rVect[0] = *r1It;
78  rVect[1] = *r2It;
79 
80  std::vector<MOL_SPTR_VECT> lprods;
81  lprods = rxn.runReactants(rVect);
82  for(std::vector<MOL_SPTR_VECT>::const_iterator lpIt=lprods.begin();
83  lpIt!=lprods.end();++lpIt){
84  // we know this is a single-product reaction:
85  prods.push_back((*lpIt)[0]);
86  }
87  }
88  }
89  \endverbatim
90 
91  NOTES:
92  - to allow more control over the reaction, it is possible to flag reactant
93  atoms as being protected by setting the common_properties::_protected
94  property on those
95  atoms. Here's an example:
96  \verbatim
97  std::string smi="[O:1]>>[N:1]";
98  ChemicalReaction *rxn = RxnSmartsToChemicalReaction(smi);
99  rxn->initReactantMatchers();
100 
101  MOL_SPTR_VECT reacts;
102  reacts.clear();
103  smi = "OCO";
104  ROMol *mol = SmilesToMol(smi);
105  reacts.push_back(ROMOL_SPTR(mol));
106  std::vector<MOL_SPTR_VECT> prods;
107  prods = rxn->runReactants(reacts);
108  // here prods has two entries, because there are two Os in the
109  // reactant.
110 
111  reacts[0]->getAtomWithIdx(0)->setProp(common_properties::_protected,1);
112  prods = rxn->runReactants(reacts);
113  // here prods only has one entry, the reaction at atom 0
114  // has been blocked by the _protected property
115  \endverbatim
116 
117 */
119  friend class ReactionPickler;
120 
121  public:
123  : RDProps(), df_needsInit(true), df_implicitProperties(false){};
125  df_needsInit = other.df_needsInit;
126  df_implicitProperties = other.df_implicitProperties;
127  for (MOL_SPTR_VECT::const_iterator iter = other.beginReactantTemplates();
128  iter != other.endReactantTemplates(); ++iter) {
129  ROMol *reactant = new ROMol(**iter);
130  m_reactantTemplates.push_back(ROMOL_SPTR(reactant));
131  }
132  for (MOL_SPTR_VECT::const_iterator iter = other.beginProductTemplates();
133  iter != other.endProductTemplates(); ++iter) {
134  ROMol *product = new ROMol(**iter);
135  m_productTemplates.push_back(ROMOL_SPTR(product));
136  }
137  for (MOL_SPTR_VECT::const_iterator iter = other.beginAgentTemplates();
138  iter != other.endAgentTemplates(); ++iter) {
139  ROMol *agent = new ROMol(**iter);
140  m_agentTemplates.push_back(ROMOL_SPTR(agent));
141  }
142  dp_props = other.dp_props;
143  }
144  //! construct a reaction from a pickle string
145  ChemicalReaction(const std::string &binStr);
146 
147  //! Adds a new reactant template
148  /*!
149  \return the number of reactants
150 
151  */
152  unsigned int addReactantTemplate(ROMOL_SPTR mol) {
153  this->df_needsInit = true;
154  this->m_reactantTemplates.push_back(mol);
155  return rdcast<unsigned int>(this->m_reactantTemplates.size());
156  }
157 
158  //! Adds a new agent template
159  /*!
160  \return the number of agent
161 
162  */
163  unsigned int addAgentTemplate(ROMOL_SPTR mol) {
164  this->m_agentTemplates.push_back(mol);
165  return rdcast<unsigned int>(this->m_agentTemplates.size());
166  }
167 
168  //! Adds a new product template
169  /*!
170  \return the number of products
171 
172  */
173  unsigned int addProductTemplate(ROMOL_SPTR mol) {
174  this->m_productTemplates.push_back(mol);
175  return rdcast<unsigned int>(this->m_productTemplates.size());
176  }
177 
178  //! Removes the reactant templates from a reaction if atom mapping ratio is
179  // below a given threshold
180  /*! By default the removed reactant templates were attached to the agent
181  templates.
182  An alternative will be to provide a pointer to a molecule vector where
183  these reactants should be saved.
184  */
185  void removeUnmappedReactantTemplates(double thresholdUnmappedAtoms = 0.2,
186  bool moveToAgentTemplates = true,
187  MOL_SPTR_VECT *targetVector = NULL);
188 
189  //! Removes the product templates from a reaction if its atom mapping ratio is
190  // below a given threshold
191  /*! By default the removed products templates were attached to the agent
192  templates.
193  An alternative will be to provide a pointer to a molecule vector where
194  these products should be saved.
195  */
196  void removeUnmappedProductTemplates(double thresholdUnmappedAtoms = 0.2,
197  bool moveToAgentTemplates = true,
198  MOL_SPTR_VECT *targetVector = NULL);
199 
200  /*! Removes the agent templates from a reaction if a pointer to a
201  molecule vector is provided the agents are stored therein.*/
202  void removeAgentTemplates(MOL_SPTR_VECT *targetVector = NULL);
203 
204  //! Runs the reaction on a set of reactants
205  /*!
206 
207  \param reactants the reactants to be used. The length of this must be equal
208  to
209  this->getNumReactantTemplates()
210  \param maxProducts: if non zero, the maximum number of products to generate
211  before stopping. If hit a warning will be generated.
212 
213  \return a vector of vectors of products. Each subvector will be
214  this->getNumProductTemplates() long.
215 
216  We return a vector of vectors of products because each individual template
217  may
218  map multiple times onto its reactant. This leads to multiple possible result
219  sets.
220  */
221  std::vector<MOL_SPTR_VECT> runReactants(const MOL_SPTR_VECT reactants,
222  unsigned int numProducts=1000) const;
223 
224  //! Runs a single reactant against a single reactant template
225  /*!
226  \param reactant The single reactant to use
227 
228  \param reactantTemplateIdx the reactant template to target in the reaction
229  */
230  std::vector<MOL_SPTR_VECT> runReactant(
231  ROMOL_SPTR reactant, unsigned int reactantTemplateIdx) const;
232 
233  const MOL_SPTR_VECT &getReactants() const {
234  return this->m_reactantTemplates;
235  }
236  const MOL_SPTR_VECT &getAgents() const { return this->m_agentTemplates; }
237  const MOL_SPTR_VECT &getProducts() const { return this->m_productTemplates; }
238 
239  MOL_SPTR_VECT::const_iterator beginReactantTemplates() const {
240  return this->m_reactantTemplates.begin();
241  }
242  MOL_SPTR_VECT::const_iterator endReactantTemplates() const {
243  return this->m_reactantTemplates.end();
244  }
245 
246  MOL_SPTR_VECT::const_iterator beginProductTemplates() const {
247  return this->m_productTemplates.begin();
248  }
249  MOL_SPTR_VECT::const_iterator endProductTemplates() const {
250  return this->m_productTemplates.end();
251  }
252 
253  MOL_SPTR_VECT::const_iterator beginAgentTemplates() const {
254  return this->m_agentTemplates.begin();
255  }
256  MOL_SPTR_VECT::const_iterator endAgentTemplates() const {
257  return this->m_agentTemplates.end();
258  }
259 
260  MOL_SPTR_VECT::iterator beginReactantTemplates() {
261  return this->m_reactantTemplates.begin();
262  }
263  MOL_SPTR_VECT::iterator endReactantTemplates() {
264  return this->m_reactantTemplates.end();
265  }
266 
267  MOL_SPTR_VECT::iterator beginProductTemplates() {
268  return this->m_productTemplates.begin();
269  }
270  MOL_SPTR_VECT::iterator endProductTemplates() {
271  return this->m_productTemplates.end();
272  }
273 
274  MOL_SPTR_VECT::iterator beginAgentTemplates() {
275  return this->m_agentTemplates.begin();
276  }
277  MOL_SPTR_VECT::iterator endAgentTemplates() {
278  return this->m_agentTemplates.end();
279  }
280  unsigned int getNumReactantTemplates() const {
281  return rdcast<unsigned int>(this->m_reactantTemplates.size());
282  };
283  unsigned int getNumProductTemplates() const {
284  return rdcast<unsigned int>(this->m_productTemplates.size());
285  };
286  unsigned int getNumAgentTemplates() const {
287  return rdcast<unsigned int>(this->m_agentTemplates.size());
288  };
289 
290  //! initializes our internal reactant-matching datastructures.
291  /*!
292  This must be called after adding reactants and before calling
293  runReactants.
294  */
295  void initReactantMatchers();
296 
297  bool isInitialized() const { return !df_needsInit; };
298 
299  //! validates the reactants and products to make sure the reaction seems
300  //"reasonable"
301  /*!
302  \return true if the reaction validates without errors (warnings do not
303  stop
304  validation)
305 
306  \param numWarnings used to return the number of validation warnings
307  \param numErrors used to return the number of validation errors
308 
309  \param silent: If this bool is true, no messages will be logged during the
310  validation.
311  By default, validation problems are reported to the warning
312  and error
313  logs depending on their severity.
314 
315  */
316  bool validate(unsigned int &numWarnings, unsigned int &numErrors,
317  bool silent = false) const;
318 
319  //! returns whether or not the reaction uses implicit
320  //! properties on the product atoms
321  /*!
322 
323  This toggles whether or not unspecified atomic properties in the
324  products are considered to be implicit and should be copied from
325  the actual reactants. This is necessary due to a semantic difference
326  between the "reaction SMARTS" approach and the MDL RXN
327  approach:
328  In "reaction SMARTS", this reaction:
329  [C:1]-[Br:2].[O-:3]>>[C:1]-[O:3].[Br-:2]
330  applied to [CH4+]Br should yield [CH4+]O
331  Something similar drawn in an rxn file, and applied to
332  [CH4+]Br should yield [CH3]O.
333  In rxn there is no charge on the product C because nothing is
334  specified in the rxn file; in "SMARTS" the charge from the
335  actual reactants is not *removed* because no charge is
336  specified in the reaction.
337 
338  */
339  bool getImplicitPropertiesFlag() const { return df_implicitProperties; };
340  //! sets the implicit properties flag. See the documentation for
341  //! getImplicitProertiesFlag() for a discussion of what this means.
342  void setImplicitPropertiesFlag(bool val) { df_implicitProperties = val; };
343 
344  private:
345  bool df_needsInit;
346  bool df_implicitProperties;
347  MOL_SPTR_VECT m_reactantTemplates, m_productTemplates, m_agentTemplates;
348  ChemicalReaction &operator=(const ChemicalReaction &); // disable assignment
349 };
350 
351 //! tests whether or not the molecule has a substructure match
352 //! to any of the reaction's reactants
353 //! the \c which argument is used to return which of the reactants
354 //! the molecule matches. If there's no match, it is equal to the number
355 //! of reactants on return
357  unsigned int &which);
358 //! \overload
360  const ROMol &mol);
361 
362 //! tests whether or not the molecule has a substructure match
363 //! to any of the reaction's products
364 //! the \c which argument is used to return which of the products
365 //! the molecule matches. If there's no match, it is equal to the number
366 //! of products on return
368  unsigned int &which);
369 //! \overload
371 
372 //! tests whether or not the molecule has a substructure match
373 //! to any of the reaction's agents
374 //! the \c which argument is used to return which of the agents
375 //! the molecule matches. If there's no match, it is equal to the number
376 //! of agents on return
378  unsigned int &which);
379 //! \overload
381 
382 //! returns indices of the atoms in each reactant that are changed
383 //! in the reaction
384 /*!
385  \param rxn the reaction we are interested in
386 
387  \param mappedAtomsOnly if set, atoms that are not mapped will not be included
388  in
389  the list of changed atoms (otherwise they are automatically included)
390 
391  How are changed atoms recognized?
392  1) Atoms whose degree changes
393  2) Atoms whose bonding pattern changes
394  3) unmapped atoms (unless the mappedAtomsOnly flag is set)
395  4) Atoms connected to unmapped atoms
396  5) Atoms whose atomic number changes (unless the
397  corresponding product atom is a dummy)
398  6) Atoms with more than one atomic number query (unless the
399  corresponding product atom is a dummy)
400 
401  Note that the atomic number of a query atom depends on how it's constructed.
402  When coming from SMARTS: if the first query is an atomic label/number that
403  sets the atomic number, otherwise it's zero.
404  For example [O;$(OC)] is atomic number 8 while [$(OC);O] is atomic
405  number 0.
406  When coming from RXN: the atomic number of the atom in the rxn file sets
407  the value.
408  */
410  bool mappedAtomsOnly = false);
411 
412 //! add the recursive queries to the reactants of a reaction
413 /*!
414  This does its work using RDKit::addRecursiveQueries()
415 
416  \param rxn the reaction we are interested in
417  \param queries - the dictionary of named queries to add
418  \param propName - the atom property to use to get query names
419  optional:
420  \param reactantLabels - to store pairs of (atom index, query string)
421  per reactant
422 
423  NOTES:
424  - existing query information, if present, will be supplemented (AND logic)
425  - non-query atoms will be replaced with query atoms using only the query
426  logic
427  - query names can be present as comma separated lists, they will then
428  be combined using OR logic.
429  - throws a KeyErrorException if a particular query name is not present
430  in \c queries
431 
432  */
434  ChemicalReaction &rxn, const std::map<std::string, ROMOL_SPTR> &queries,
435  const std::string &propName,
436  std::vector<std::vector<std::pair<unsigned int, std::string>>>
437  *reactantLabels = NULL);
438 
439 } // end of RDKit namespace
440 
441 namespace RDDepict {
442 //! \brief Generate 2D coordinates (a depiction) for a reaction
443 /*!
444 
445  \param rxn the reaction we are interested in
446 
447  \param spacing the spacing between components of the reaction
448 
449  \param updateProps if set, properties such as conjugation and
450  hybridization will be calculated for the reactant and product
451  templates before generating coordinates. This should result in
452  better depictions, but can lead to errors in some cases.
453 
454  \param canonOrient canonicalize the orientation so that the long
455  axes align with the x-axis etc.
456 
457  \param nFlipsPerSample - the number of rotatable bonds that are
458  flipped at random for each sample
459 
460  \param nSamples - the number of samples
461 
462  \param sampleSeed - seed for the random sampling process
463 
464  \param permuteDeg4Nodes - try permuting the drawing order of bonds around
465  atoms with four neighbors in order to improve the depiction
466 
467  for the other parameters see the documentation for compute2DCoords()
468 
469 */
471  double spacing = 2.0, bool updateProps = true,
472  bool canonOrient = false,
473  unsigned int nFlipsPerSample = 0,
474  unsigned int nSamples = 0, int sampleSeed = 0,
475  bool permuteDeg4Nodes = false);
476 
477 } // end of RDDepict namespace
478 
479 #endif
MOL_SPTR_VECT::iterator beginProductTemplates()
Definition: Reaction.h:267
Dict dp_props
Definition: RDProps.h:12
const MOL_SPTR_VECT & getAgents() const
Definition: Reaction.h:236
MOL_SPTR_VECT::const_iterator endReactantTemplates() const
Definition: Reaction.h:242
bool getImplicitPropertiesFlag() const
Definition: Reaction.h:339
const MOL_SPTR_VECT & getReactants() const
Definition: Reaction.h:233
ChemicalReaction(const ChemicalReaction &other)
Definition: Reaction.h:124
void setImplicitPropertiesFlag(bool val)
Definition: Reaction.h:342
RDKIT_CHEMREACTIONS_EXPORT bool isMoleculeAgentOfReaction(const ChemicalReaction &rxn, const ROMol &mol, unsigned int &which)
unsigned int addAgentTemplate(ROMOL_SPTR mol)
Adds a new agent template.
Definition: Reaction.h:163
This is a class for storing and applying general chemical reactions.
Definition: Reaction.h:118
pulls in the core RDKit functionality
std::vector< boost::shared_ptr< ROMol > > MOL_SPTR_VECT
Definition: FragCatParams.h:20
MOL_SPTR_VECT::iterator endProductTemplates()
Definition: Reaction.h:270
std::vector< INT_VECT > VECT_INT_VECT
Definition: types.h:261
RDKIT_CHEMREACTIONS_EXPORT 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)
Generate 2D coordinates (a depiction) for a reaction.
RDKIT_CHEMREACTIONS_EXPORT void addRecursiveQueriesToReaction(ChemicalReaction &rxn, const std::map< std::string, ROMOL_SPTR > &queries, const std::string &propName, std::vector< std::vector< std::pair< unsigned int, std::string >>> *reactantLabels=NULL)
add the recursive queries to the reactants of a reaction
MOL_SPTR_VECT::iterator beginReactantTemplates()
Definition: Reaction.h:260
MOL_SPTR_VECT::const_iterator endProductTemplates() const
Definition: Reaction.h:249
MOL_SPTR_VECT::const_iterator beginProductTemplates() const
Definition: Reaction.h:246
const char * message() const
get the error message
Definition: Reaction.h:53
unsigned int getNumProductTemplates() const
Definition: Reaction.h:283
const MOL_SPTR_VECT & getProducts() const
Definition: Reaction.h:237
boost::shared_ptr< ROMol > ROMOL_SPTR
Std stuff.
Definition: Atom.h:30
used to indicate an error in the chemical reaction engine
Definition: Reaction.h:46
MOL_SPTR_VECT::const_iterator beginReactantTemplates() const
Definition: Reaction.h:239
unsigned int addProductTemplate(ROMOL_SPTR mol)
Adds a new product template.
Definition: Reaction.h:173
unsigned int addReactantTemplate(ROMOL_SPTR mol)
Adds a new reactant template.
Definition: Reaction.h:152
RDKIT_CHEMREACTIONS_EXPORT VECT_INT_VECT getReactingAtoms(const ChemicalReaction &rxn, bool mappedAtomsOnly=false)
bool isInitialized() const
Definition: Reaction.h:297
MOL_SPTR_VECT::const_iterator beginAgentTemplates() const
Definition: Reaction.h:253
ChemicalReactionException(const std::string msg)
construct with an error message
Definition: Reaction.h:51
#define RDKIT_CHEMREACTIONS_EXPORT
Definition: export.h:60
RDKIT_CHEMREACTIONS_EXPORT bool isMoleculeReactantOfReaction(const ChemicalReaction &rxn, const ROMol &mol, unsigned int &which)
MOL_SPTR_VECT::iterator endReactantTemplates()
Definition: Reaction.h:263
handles pickling (serializing) reactions
MOL_SPTR_VECT::iterator beginAgentTemplates()
Definition: Reaction.h:274
unsigned int getNumAgentTemplates() const
Definition: Reaction.h:286
RDKIT_CHEMREACTIONS_EXPORT bool isMoleculeProductOfReaction(const ChemicalReaction &rxn, const ROMol &mol, unsigned int &which)
MOL_SPTR_VECT::iterator endAgentTemplates()
Definition: Reaction.h:277
ChemicalReactionException(const char *msg)
construct with an error message
Definition: Reaction.h:49
MOL_SPTR_VECT::const_iterator endAgentTemplates() const
Definition: Reaction.h:256
unsigned int getNumReactantTemplates() const
Definition: Reaction.h:280