File: Reaction.cpp

package info (click to toggle)
rdkit 201809.1%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 123,688 kB
  • sloc: cpp: 230,509; python: 70,501; java: 6,329; ansic: 5,427; sql: 1,899; yacc: 1,739; lex: 1,243; makefile: 445; xml: 229; fortran: 183; sh: 123; cs: 93
file content (685 lines) | stat: -rw-r--r-- 25,052 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//
//  Copyright (c) 2007-2017, 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 Institutes 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 <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/ChemReactions/ReactionPickler.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/QueryOps.h>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
#include <map>
#include <algorithm>
#include <GraphMol/ChemTransforms/ChemTransforms.h>
#include <GraphMol/Descriptors/MolDescriptors.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/ChemReactions/ReactionUtils.h>
#include "GraphMol/ChemReactions/ReactionRunner.h"

namespace RDKit {

std::vector<MOL_SPTR_VECT> ChemicalReaction::runReactants(
    const MOL_SPTR_VECT reactants, unsigned int maxProducts) const {
  return run_Reactants(*this, reactants, maxProducts);
}

std::vector<MOL_SPTR_VECT> ChemicalReaction::runReactant(
    const ROMOL_SPTR reactant, unsigned int reactionTemplateIdx) const {
  return run_Reactant(*this, reactant, reactionTemplateIdx);
}

ChemicalReaction::ChemicalReaction(const std::string &pickle) {
  ReactionPickler::reactionFromPickle(pickle, this);
}

void ChemicalReaction::initReactantMatchers() {
  unsigned int nWarnings, nErrors;
  if (!this->validate(nWarnings, nErrors)) {
    BOOST_LOG(rdErrorLog) << "initialization failed\n";
    this->df_needsInit = true;
  } else {
    this->df_needsInit = false;
  }
}

bool ChemicalReaction::validate(unsigned int &numWarnings,
                                unsigned int &numErrors, bool silent) const {
  bool res = true;
  numWarnings = 0;
  numErrors = 0;

  if (!this->getNumReactantTemplates()) {
    if (!silent) {
      BOOST_LOG(rdErrorLog) << "reaction has no reactants\n";
    }
    numErrors++;
    res = false;
  }

  if (!this->getNumProductTemplates()) {
    if (!silent) {
      BOOST_LOG(rdErrorLog) << "reaction has no products\n";
    }
    numErrors++;
    res = false;
  }

  std::vector<int> mapNumbersSeen;
  std::map<int, const Atom *> reactingAtoms;
  unsigned int molIdx = 0;
  for (auto molIter = this->beginReactantTemplates();
       molIter != this->endReactantTemplates(); ++molIter) {
    bool thisMolMapped = false;
    for (ROMol::AtomIterator atomIt = (*molIter)->beginAtoms();
         atomIt != (*molIter)->endAtoms(); ++atomIt) {
      int mapNum;
      if ((*atomIt)->getPropIfPresent(common_properties::molAtomMapNumber,
                                      mapNum)) {
        thisMolMapped = true;
        if (std::find(mapNumbersSeen.begin(), mapNumbersSeen.end(), mapNum) !=
            mapNumbersSeen.end()) {
          if (!silent) {
            BOOST_LOG(rdErrorLog) << "reactant atom-mapping number " << mapNum
                                  << " found multiple times.\n";
          }
          numErrors++;
          res = false;
        } else {
          mapNumbersSeen.push_back(mapNum);
          reactingAtoms[mapNum] = *atomIt;
        }
      }
    }
    if (!thisMolMapped) {
      if (!silent) {
        BOOST_LOG(rdWarningLog) << "reactant " << molIdx
                                << " has no mapped atoms.\n";
      }
      numWarnings++;
    }
    molIdx++;
  }

  std::vector<int> productNumbersSeen;
  molIdx = 0;
  for (auto molIter = this->beginProductTemplates();
       molIter != this->endProductTemplates(); ++molIter) {
    // clear out some possible cached properties to prevent
    // misleading warnings
    for (ROMol::AtomIterator atomIt = (*molIter)->beginAtoms();
         atomIt != (*molIter)->endAtoms(); ++atomIt) {
      if ((*atomIt)->hasProp(common_properties::_QueryFormalCharge))
        (*atomIt)->clearProp(common_properties::_QueryFormalCharge);
      if ((*atomIt)->hasProp(common_properties::_QueryHCount))
        (*atomIt)->clearProp(common_properties::_QueryHCount);
      if ((*atomIt)->hasProp(common_properties::_QueryMass))
        (*atomIt)->clearProp(common_properties::_QueryMass);
      if ((*atomIt)->hasProp(common_properties::_QueryIsotope))
        (*atomIt)->clearProp(common_properties::_QueryIsotope);
    }
    bool thisMolMapped = false;
    for (ROMol::AtomIterator atomIt = (*molIter)->beginAtoms();
         atomIt != (*molIter)->endAtoms(); ++atomIt) {
      int mapNum;
      if ((*atomIt)->getPropIfPresent(common_properties::molAtomMapNumber,
                                      mapNum)) {
        thisMolMapped = true;
        bool seenAlready =
            std::find(productNumbersSeen.begin(), productNumbersSeen.end(),
                      mapNum) != productNumbersSeen.end();
        if (seenAlready) {
          if (!silent) {
            BOOST_LOG(rdWarningLog) << "product atom-mapping number " << mapNum
                                    << " found multiple times.\n";
          }
          numWarnings++;
          // ------------
          //   Always check to see if the atoms connectivity changes independent
          //   if it is mapped multiple times
          // ------------
          const Atom *rAtom = reactingAtoms[mapNum];
          CHECK_INVARIANT(rAtom, "missing atom");
          if (rAtom->getDegree() != (*atomIt)->getDegree()) {
            (*atomIt)->setProp(common_properties::_ReactionDegreeChanged, 1);
          }

        } else {
          productNumbersSeen.push_back(mapNum);
        }
        auto ivIt =
            std::find(mapNumbersSeen.begin(), mapNumbersSeen.end(), mapNum);
        if (ivIt == mapNumbersSeen.end()) {
          if (!seenAlready) {
            if (!silent) {
              BOOST_LOG(rdWarningLog) << "product atom-mapping number "
                                      << mapNum << " not found in reactants.\n";
            }
            numWarnings++;
          }
        } else {
          mapNumbersSeen.erase(ivIt);

          // ------------
          //   The atom is mapped, check to see if its connectivity changes
          // ------------
          const Atom *rAtom = reactingAtoms[mapNum];
          CHECK_INVARIANT(rAtom, "missing atom");
          if (rAtom->getDegree() != (*atomIt)->getDegree()) {
            (*atomIt)->setProp(common_properties::_ReactionDegreeChanged, 1);
          }
        }
      }

      // ------------
      //    Deal with queries
      // ------------
      if ((*atomIt)->hasQuery()) {
        std::list<const Atom::QUERYATOM_QUERY *> queries;
        queries.push_back((*atomIt)->getQuery());
        while (!queries.empty()) {
          const Atom::QUERYATOM_QUERY *query = queries.front();
          queries.pop_front();
          for (auto qIter = query->beginChildren();
               qIter != query->endChildren(); ++qIter) {
            queries.push_back((*qIter).get());
          }
          if (query->getDescription() == "AtomFormalCharge") {
            int qval;
            if ((*atomIt)->getPropIfPresent(
                    common_properties::_QueryFormalCharge, qval) &&
                qval !=
                    static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal()) {
              if (!silent) {
                BOOST_LOG(rdWarningLog)
                    << "atom " << (*atomIt)->getIdx() << " in product "
                    << molIdx << " has multiple charge specifications.\n";
              }
              numWarnings++;
            } else {
              (*atomIt)->setProp(
                  common_properties::_QueryFormalCharge,
                  static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal());
            }
          } else if (query->getDescription() == "AtomHCount") {
            int qval;
            if ((*atomIt)->getPropIfPresent(common_properties::_QueryHCount,
                                            qval) &&
                qval !=
                    static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal()) {
              if (!silent) {
                BOOST_LOG(rdWarningLog)
                    << "atom " << (*atomIt)->getIdx() << " in product "
                    << molIdx << " has multiple H count specifications.\n";
              }
              numWarnings++;
            } else {
              (*atomIt)->setProp(
                  common_properties::_QueryHCount,
                  static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal());
            }
          } else if (query->getDescription() == "AtomMass") {
            int qval;
            if ((*atomIt)->getPropIfPresent(common_properties::_QueryMass,
                                            qval) &&
                qval !=
                    static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal()) {
              if (!silent) {
                BOOST_LOG(rdWarningLog)
                    << "atom " << (*atomIt)->getIdx() << " in product "
                    << molIdx << " has multiple mass specifications.\n";
              }
              numWarnings++;
            } else {
              (*atomIt)->setProp(
                  common_properties::_QueryMass,
                  static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal() /
                      massIntegerConversionFactor);
            }
          } else if (query->getDescription() == "AtomIsotope") {
            int qval;
            if ((*atomIt)->getPropIfPresent(common_properties::_QueryIsotope,
                                            qval) &&
                qval !=
                    static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal()) {
              if (!silent) {
                BOOST_LOG(rdWarningLog)
                    << "atom " << (*atomIt)->getIdx() << " in product "
                    << molIdx << " has multiple isotope specifications.\n";
              }
              numWarnings++;
            } else {
              (*atomIt)->setProp(
                  common_properties::_QueryIsotope,
                  static_cast<const ATOM_EQUALS_QUERY *>(query)->getVal());
            }
          }
        }
      }
    }
    if (!thisMolMapped) {
      if (!silent) {
        BOOST_LOG(rdWarningLog) << "product " << molIdx
                                << " has no mapped atoms.\n";
      }
      numWarnings++;
    }
    molIdx++;
  }
  if (!mapNumbersSeen.empty()) {
    if (!silent) {
      std::ostringstream ostr;
      ostr
          << "mapped atoms in the reactants were not mapped in the products.\n";
      ostr << "  unmapped numbers are: ";
      for (std::vector<int>::const_iterator ivIt = mapNumbersSeen.begin();
           ivIt != mapNumbersSeen.end(); ++ivIt) {
        ostr << *ivIt << " ";
      }
      ostr << "\n";
      BOOST_LOG(rdWarningLog) << ostr.str();
    }
    numWarnings++;
  }

  return res;
}

bool isMoleculeReactantOfReaction(const ChemicalReaction &rxn, const ROMol &mol,
                                  unsigned int &which) {
  if (!rxn.isInitialized()) {
    throw ChemicalReactionException(
        "initReactantMatchers() must be called first");
  }
  which = 0;
  for (auto iter = rxn.beginReactantTemplates();
       iter != rxn.endReactantTemplates(); ++iter, ++which) {
    MatchVectType tvect;
    if (SubstructMatch(mol, **iter, tvect)) {
      return true;
    }
  }
  return false;
}
bool isMoleculeReactantOfReaction(const ChemicalReaction &rxn,
                                  const ROMol &mol) {
  unsigned int ignore;
  return isMoleculeReactantOfReaction(rxn, mol, ignore);
}

bool isMoleculeProductOfReaction(const ChemicalReaction &rxn, const ROMol &mol,
                                 unsigned int &which) {
  if (!rxn.isInitialized()) {
    throw ChemicalReactionException(
        "initReactantMatchers() must be called first");
  }
  which = 0;
  for (auto iter = rxn.beginProductTemplates();
       iter != rxn.endProductTemplates(); ++iter, ++which) {
    MatchVectType tvect;
    if (SubstructMatch(mol, **iter, tvect)) {
      return true;
    }
  }
  return false;
}
bool isMoleculeProductOfReaction(const ChemicalReaction &rxn,
                                 const ROMol &mol) {
  unsigned int ignore;
  return isMoleculeProductOfReaction(rxn, mol, ignore);
}

bool isMoleculeAgentOfReaction(const ChemicalReaction &rxn, const ROMol &mol,
                               unsigned int &which) {
  if (!rxn.isInitialized()) {
    throw ChemicalReactionException(
        "initReactantMatchers() must be called first");
  }
  which = 0;
  for (auto iter = rxn.beginAgentTemplates(); iter != rxn.endAgentTemplates();
       ++iter, ++which) {
    if (iter->get()->getNumHeavyAtoms() != mol.getNumHeavyAtoms()) {
      continue;
    }
    if (iter->get()->getNumBonds() != mol.getNumBonds()) {
      continue;
    }
    // not possible, update property cache not possible for const molecules
    //      if(iter->get()->getRingInfo()->numRings() !=
    //      mol.getRingInfo()->numRings()){
    //          return false;
    //      }
    if (RDKit::Descriptors::calcAMW(*iter->get()) !=
        RDKit::Descriptors::calcAMW(mol)) {
      continue;
    }
    MatchVectType tvect;
    if (SubstructMatch(mol, **iter, tvect)) {
      return true;
    }
  }
  return false;
}

bool isMoleculeAgentOfReaction(const ChemicalReaction &rxn, const ROMol &mol) {
  unsigned int ignore;
  return isMoleculeAgentOfReaction(rxn, mol, ignore);
}

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) {
  if (!rxn.isInitialized()) {
    throw ChemicalReactionException(
        "initReactantMatchers() must be called first");
  }

  if (reactantLabels != nullptr) {
    (*reactantLabels).resize(0);
  }

  for (MOL_SPTR_VECT::const_iterator rIt = rxn.beginReactantTemplates();
       rIt != rxn.endReactantTemplates(); ++rIt) {
    if (reactantLabels != nullptr) {
      std::vector<std::pair<unsigned int, std::string> > labels;
      addRecursiveQueries(**rIt, queries, propName, &labels);
      (*reactantLabels).push_back(labels);
    } else {
      addRecursiveQueries(**rIt, queries, propName);
    }
  }
}

namespace {
// recursively looks for atomic number queries anywhere in this set of children
// or its children
int numComplexQueries(
    Queries::Query<int, Atom const *, true>::CHILD_VECT_CI childIt,
    Queries::Query<int, Atom const *, true>::CHILD_VECT_CI endChildren) {
  int res = 0;
  while (childIt != endChildren) {
    std::string descr = (*childIt)->getDescription();
    if (descr == "AtomAtomicNum" || descr == "AtomNull") {
      ++res;
    } else {
      res += numComplexQueries((*childIt)->beginChildren(),
                               (*childIt)->endChildren());
    }
    ++childIt;
  }
  return res;
}
#if 0
// FIX: this is adapted from Fingerprints.cpp and we really should have code
// like this centralized
bool isComplexQuery(const Atom &a) {
  if (!a.hasQuery()) return false;
  // negated things are always complex:
  if (a.getQuery()->getNegation()) return true;
  std::string descr = a.getQuery()->getDescription();
  if (descr == "AtomAtomicNum") return false;
  if (descr == "AtomOr" || descr == "AtomXor") return true;
  if (descr == "AtomAnd") {
    auto childIt = a.getQuery()->beginChildren();
    int ncq = numComplexQueries(childIt, a.getQuery()->endChildren());
    if (ncq == 1) {
      return false;
    }
  }
  return true;
}
#endif
bool isChangedAtom(const Atom &rAtom, const Atom &pAtom, int mapNum,
                   const std::map<int, const Atom *> &mappedProductAtoms) {
  PRECONDITION(mappedProductAtoms.find(mapNum) != mappedProductAtoms.end(),
               "atom not mapped in products");

  if (rAtom.getAtomicNum() != pAtom.getAtomicNum() &&
      pAtom.getAtomicNum() > 0) {
    // the atomic number changed and the product wasn't a dummy
    return true;
  } else if (rAtom.getDegree() != pAtom.getDegree()) {
    // the degree changed
    return true;
  } else if (pAtom.getAtomicNum() > 0 && isComplexQuery(&rAtom)) {
    // more than a simple query
    return true;
  }

  // now check bond layout:
  std::map<unsigned int, const Bond *> reactantBonds;
  ROMol::ADJ_ITER nbrIdx, endNbrs;
  boost::tie(nbrIdx, endNbrs) = rAtom.getOwningMol().getAtomNeighbors(&rAtom);
  while (nbrIdx != endNbrs) {
    const Atom *nbr = rAtom.getOwningMol()[*nbrIdx];
    int mapNum;
    if (nbr->getPropIfPresent(common_properties::molAtomMapNumber, mapNum)) {
      reactantBonds[mapNum] = rAtom.getOwningMol().getBondBetweenAtoms(
          rAtom.getIdx(), nbr->getIdx());
    } else {
      // if we have an un-mapped neighbor, we are automatically a reacting atom:
      return true;
    }
    ++nbrIdx;
  }
  boost::tie(nbrIdx, endNbrs) = pAtom.getOwningMol().getAtomNeighbors(&pAtom);
  while (nbrIdx != endNbrs) {
    const Atom * nbr = pAtom.getOwningMol()[*nbrIdx];
    int mapNum;
    if (nbr->getPropIfPresent(common_properties::molAtomMapNumber, mapNum)) {
      // if we don't have a bond to a similarly mapped atom in the reactant,
      // we're done:
      if (reactantBonds.find(mapNum) == reactantBonds.end()) {
        return true;
      }
      const Bond *rBond = reactantBonds[mapNum];
      const Bond *pBond = pAtom.getOwningMol().getBondBetweenAtoms(
          pAtom.getIdx(), nbr->getIdx());

      // bond comparison logic:
      if (rBond->hasQuery()) {
        if (!pBond->hasQuery()) {
          // reactant query, product not query: always a change
          return true;
        } else {
          if (pBond->getQuery()->getDescription() == "BondNull") {
            // null queries are trump, they match everything
          } else if (rBond->getBondType() == Bond::SINGLE &&
                     pBond->getBondType() == Bond::SINGLE &&
                     ((rBond->getQuery()->getDescription() == "BondOr" &&
                       pBond->getQuery()->getDescription() == "BondOr") ||
                      (rBond->getQuery()->getDescription() == "SingleOrAromaticBond" &&
                       pBond->getQuery()->getDescription() == "SingleOrAromaticBond"))
                   ) {
            // The SMARTS parser tags unspecified bonds as single, but then adds
            // a query so that they match single or double.
            // these cases match
          } else {
            if (rBond->getBondType() == pBond->getBondType() &&
                rBond->getQuery()->getDescription() == "BondOrder" &&
                pBond->getQuery()->getDescription() == "BondOrder" &&
                static_cast<BOND_EQUALS_QUERY *>(rBond->getQuery())->getVal() ==
                    static_cast<BOND_EQUALS_QUERY *>(pBond->getQuery())
                        ->getVal()) {
              // bond order queries with equal orders also match
            } else {
              // anything else does not match
              return true;
            }
          }
        }
      } else if (pBond->hasQuery()) {
        // reactant not query, product query
        // if product is anything other than the null query
        // it's a change:
        if (pBond->getQuery()->getDescription() != "BondNull") {
          return true;
        }

      } else {
        // neither has a query, just compare the types
        if (rBond->getBondType() != pBond->getBondType()) {
          return true;
        }
      }
    }
    ++nbrIdx;
  }

  // haven't found anything to say that we are changed, so we must
  // not be
  return false;
}

template <class T>
bool getMappedAtoms(T &rIt, std::map<int, const Atom *> &mappedAtoms) {
  ROMol::ATOM_ITER_PAIR atItP = rIt->getVertices();
  while (atItP.first != atItP.second) {
    const Atom *oAtom = (*rIt)[*(atItP.first++)];
    // we only worry about mapped atoms:
    int mapNum;
    if (oAtom->getPropIfPresent(common_properties::molAtomMapNumber, mapNum)) {
      mappedAtoms[mapNum] = oAtom;
    } else {
      // unmapped atom, return it
      return false;
    }
  }
  return true;
}
}  // end of anonymous namespace

VECT_INT_VECT getReactingAtoms(const ChemicalReaction &rxn,
                               bool mappedAtomsOnly) {
  if (!rxn.isInitialized()) {
    throw ChemicalReactionException(
        "initReactantMatchers() must be called first");
  }
  VECT_INT_VECT res;
  res.resize(rxn.getNumReactantTemplates());

  // find mapped atoms in the products :
  std::map<int, const Atom *> mappedProductAtoms;
  for (auto rIt = rxn.beginProductTemplates(); rIt != rxn.endProductTemplates();
       ++rIt) {
    getMappedAtoms(*rIt, mappedProductAtoms);
  }

  // now loop over mapped atoms in the reactants, keeping track of
  // which reactant they are associated with, and check for changes.
  auto resIt = res.begin();
  for (auto rIt = rxn.beginReactantTemplates();
       rIt != rxn.endReactantTemplates(); ++rIt, ++resIt) {
    ROMol::ATOM_ITER_PAIR atItP = (*rIt)->getVertices();
    while (atItP.first != atItP.second) {
      const Atom *oAtom = (**rIt)[*(atItP.first++)];
      // unmapped atoms are definitely changing:
      int mapNum;
      if (!oAtom->getPropIfPresent(common_properties::molAtomMapNumber,
                                   mapNum)) {
        if (!mappedAtomsOnly) {
          resIt->push_back(oAtom->getIdx());
        }
      } else {
        // but mapped ones require more careful consideration
        // if this is found in a reactant:
        if (mappedProductAtoms.find(mapNum) != mappedProductAtoms.end()) {
          if (isChangedAtom(*oAtom, *(mappedProductAtoms[mapNum]), mapNum,
                            mappedProductAtoms)) {
            resIt->push_back(oAtom->getIdx());
          }
        }
      }
    }
  }
  return res;
}

void ChemicalReaction::removeUnmappedReactantTemplates(
    double thresholdUnmappedAtoms, bool moveToAgentTemplates,
    MOL_SPTR_VECT *targetVector) {
  MOL_SPTR_VECT res_reactantTemplates;
  for (auto iter = beginReactantTemplates(); iter != endReactantTemplates();
       ++iter) {
    if (isReactionTemplateMoleculeAgent(*iter->get(), thresholdUnmappedAtoms)) {
      if (moveToAgentTemplates) {
        m_agentTemplates.push_back(*iter);
      }
      if (targetVector) {
        targetVector->push_back(*iter);
      }
    } else {
      res_reactantTemplates.push_back(*iter);
    }
  }
  m_reactantTemplates.clear();
  m_reactantTemplates.insert(m_reactantTemplates.begin(),
                             res_reactantTemplates.begin(),
                             res_reactantTemplates.end());
  res_reactantTemplates.clear();
}

void ChemicalReaction::removeUnmappedProductTemplates(
    double thresholdUnmappedAtoms, bool moveToAgentTemplates,
    MOL_SPTR_VECT *targetVector) {
  MOL_SPTR_VECT res_productTemplates;
  for (auto iter = beginProductTemplates(); iter != endProductTemplates();
       ++iter) {
    if (isReactionTemplateMoleculeAgent(*iter->get(), thresholdUnmappedAtoms)) {
      if (moveToAgentTemplates) {
        m_agentTemplates.push_back(*iter);
      }
      if (targetVector) {
        targetVector->push_back(*iter);
      }
    } else {
      res_productTemplates.push_back(*iter);
    }
  }
  m_productTemplates.clear();
  m_productTemplates.insert(m_productTemplates.begin(),
                            res_productTemplates.begin(),
                            res_productTemplates.end());
  res_productTemplates.clear();
}

void ChemicalReaction::removeAgentTemplates(MOL_SPTR_VECT *targetVector) {
  if (targetVector) {
    for (auto iter = beginAgentTemplates(); iter != endAgentTemplates();
         ++iter) {
      targetVector->push_back(*iter);
    }
  }
  m_agentTemplates.clear();
}

}  // end of RDKit namespace