File: SubgraphUtils.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 (242 lines) | stat: -rw-r--r-- 8,576 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
// $Id$
//
//  Copyright (C) 2003-2013 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 "SubgraphUtils.h"
#include "Subgraphs.h"
#include <RDGeneral/utils.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/QueryAtom.h>
#include <GraphMol/QueryBond.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <boost/tuple/tuple_comparison.hpp>
#include <RDGeneral/hash/hash.hpp>

namespace RDKit {
namespace Subgraphs {
ROMol *pathToSubmol(const ROMol &mol, const PATH_TYPE &path, bool useQuery) {
  INT_MAP_INT aIdxMap;
  return pathToSubmol(mol, path, useQuery, aIdxMap);
}

ROMol *pathToSubmol(const ROMol &mol, const PATH_TYPE &path, bool useQuery,
                    INT_MAP_INT &atomIdxMap) {
  auto *subMol = new RWMol();
  PATH_TYPE::const_iterator pathIter;
  atomIdxMap.clear();

  if (useQuery) {
    // have to do this in two different blocks because of issues with variable
    // scopes.
    for (pathIter = path.begin(); pathIter != path.end(); ++pathIter) {
      QueryBond *bond;
      bond = new QueryBond(*(mol.getBondWithIdx(*pathIter)));

      int begIdx = bond->getBeginAtomIdx();
      int endIdx = bond->getEndAtomIdx();

      if (atomIdxMap.find(begIdx) == atomIdxMap.end()) {
        auto *atom = new QueryAtom(*(mol.getAtomWithIdx(begIdx)));
        int newAtomIdx = subMol->addAtom(atom, false, true);
        atomIdxMap[begIdx] = newAtomIdx;
      }
      begIdx = atomIdxMap.find(begIdx)->second;
      if (atomIdxMap.find(endIdx) == atomIdxMap.end()) {
        auto *atom = new QueryAtom(*(mol.getAtomWithIdx(endIdx)));
        int newAtomIdx = subMol->addAtom(atom, false, true);
        atomIdxMap[endIdx] = newAtomIdx;
      }
      endIdx = atomIdxMap.find(endIdx)->second;

      bond->setOwningMol(subMol);
      bond->setBeginAtomIdx(begIdx);
      bond->setEndAtomIdx(endIdx);
      subMol->addBond(bond, true);
    }
  } else {
    for (pathIter = path.begin(); pathIter != path.end(); ++pathIter) {
      Bond *bond;
      bond = mol.getBondWithIdx(*pathIter)->copy();

      int begIdx = bond->getBeginAtomIdx();
      int endIdx = bond->getEndAtomIdx();

      if (atomIdxMap.find(begIdx) == atomIdxMap.end()) {
        Atom *atom = mol.getAtomWithIdx(begIdx)->copy();
        int newAtomIdx = subMol->addAtom(atom, false, true);
        atomIdxMap[begIdx] = newAtomIdx;
      }
      begIdx = atomIdxMap.find(begIdx)->second;
      if (atomIdxMap.find(endIdx) == atomIdxMap.end()) {
        Atom *atom = mol.getAtomWithIdx(endIdx)->copy();
        int newAtomIdx = subMol->addAtom(atom, false, true);
        atomIdxMap[endIdx] = newAtomIdx;
      }
      endIdx = atomIdxMap.find(endIdx)->second;

      bond->setOwningMol(subMol);
      bond->setBeginAtomIdx(begIdx);
      bond->setEndAtomIdx(endIdx);
      subMol->addBond(bond, true);
    }
  }
  if (mol.getNumConformers()) {
    // copy coordinates over:
    for (auto confIt = mol.beginConformers(); confIt != mol.endConformers();
         ++confIt) {
      auto *conf = new Conformer(subMol->getNumAtoms());
      conf->set3D((*confIt)->is3D());
      for (INT_MAP_INT::const_iterator mapIt = atomIdxMap.begin();
           mapIt != atomIdxMap.end(); ++mapIt) {
        conf->setAtomPos(mapIt->second, (*confIt)->getAtomPos(mapIt->first));
      }
      conf->setId((*confIt)->getId());
      subMol->addConformer(conf, false);
    }
  }
  // clear computed properties
  subMol->clearComputedProps(true);

  return subMol;
}

PATH_TYPE bondListFromAtomList(const ROMol &mol, const PATH_TYPE &atomIds) {
  PATH_TYPE bids;
  unsigned int natms = atomIds.size();
  if (natms <= 1) {
    return bids;  // FIX: should probably throw an exception
  }
  for (unsigned int i = 0; i < natms; i++) {
    for (unsigned int j = i + 1; j < natms; j++) {
      const Bond *bnd = mol.getBondBetweenAtoms(atomIds[i], atomIds[j]);
      if (bnd) {
        int bid = bnd->getIdx();
        bids.push_back(bid);
      }
    }
  }
  return bids;
}

using boost::uint32_t;
using boost::int32_t;
DiscrimTuple calcPathDiscriminators(const ROMol &mol, const PATH_TYPE &path,
                                    bool useBO,
                                    std::vector<boost::uint32_t> *extraInvars) {
  if (extraInvars)
    CHECK_INVARIANT(extraInvars->size() == mol.getNumAtoms(),
                    "bad extra invars");
  DiscrimTuple res;

  // Start by collecting the atoms in the path and their degrees
  std::vector<int32_t> atomsUsed(mol.getNumAtoms(),
                                 -1);  // map from atom index->path index
  std::vector<const Atom *> atoms;     // to contain the atoms in the path
  std::vector<uint32_t> pathDegrees;   // degrees of each atom *in the path*
  for (int pathIter : path) {
    const Bond *bond = mol.getBondWithIdx(pathIter);
    if (atomsUsed[bond->getBeginAtomIdx()] < 0) {
      atomsUsed[bond->getBeginAtomIdx()] = static_cast<int>(atoms.size());
      atoms.push_back(bond->getBeginAtom());
      pathDegrees.push_back(1);
    } else {
      pathDegrees[atomsUsed[bond->getBeginAtomIdx()]] += 1;
    }
    if (atomsUsed[bond->getEndAtomIdx()] < 0) {
      atomsUsed[bond->getEndAtomIdx()] = static_cast<int>(atoms.size());
      atoms.push_back(bond->getEndAtom());
      pathDegrees.push_back(1);
    } else {
      pathDegrees[atomsUsed[bond->getEndAtomIdx()]] += 1;
    }
  }

  // Calculate the atomic invariants
  unsigned int nAtoms = atoms.size();
  std::vector<uint32_t> invars(nAtoms);
  for (unsigned int i = 0; i < nAtoms; ++i) {
    const Atom *atom = atoms[i];
    uint32_t invar = atom->getAtomicNum();
    gboost::hash_combine(invar, pathDegrees[i]);
    gboost::hash_combine(invar, atom->getFormalCharge());
    int deltaMass = static_cast<int>(
        atom->getMass() -
        PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum()));
    gboost::hash_combine(invar, deltaMass);
    if (atom->getIsAromatic()) {
      gboost::hash_combine(invar, 1);
    }
    if (extraInvars) {
      gboost::hash_combine(invar, (*extraInvars)[atom->getIdx()]);
    }
    invars[i] = invar;
  }

  // now do the Morgan iterations:
  // the most number of cycles we need for the atoms on the edges
  // to feel each other is pathSize/2
  // EFF: it may be worth revisiting this at some point to see
  // if the iteration count can be even smaller (and if it
  // makes a difference in runtime)
  unsigned int nCycles = path.size() / 2 + 1;
  gboost::hash<std::vector<uint32_t> > vectHasher;
  for (unsigned int cycle = 0; cycle < nCycles; ++cycle) {
    // let each atom feel it's neighbors:
    std::vector<std::vector<uint32_t> > locInvars(nAtoms);
    for (int pathIter : path) {
      const Bond *bond = mol.getBondWithIdx(pathIter);
      uint32_t v1 = invars[atomsUsed[bond->getBeginAtomIdx()]];
      uint32_t v2 = invars[atomsUsed[bond->getEndAtomIdx()]];
      if (useBO) {
        gboost::hash_combine(v1, static_cast<uint32_t>(bond->getBondType()));
        gboost::hash_combine(v2, static_cast<uint32_t>(bond->getBondType()));
      }
      locInvars[atomsUsed[bond->getBeginAtomIdx()]].push_back(v2);
      locInvars[atomsUsed[bond->getEndAtomIdx()]].push_back(v1);
    }
    // we need to sort by the neighbor invariants to be order
    // independent:
    for (unsigned int i = 0; i < nAtoms; ++i) {
      std::sort(locInvars[i].begin(), locInvars[i].end());
      invars[i] = vectHasher(locInvars[i]);
    }
  }

  // again, a sort for order independence:
  std::sort(invars.begin(), invars.end());
  uint32_t pathInvar = vectHasher(invars);

  // also include the path size (bond count) and number of atoms
  // in the discriminator
  return boost::make_tuple(pathInvar, path.size(), nAtoms);
}

//
// This is intended for use on either subgraphs or paths.
//  The entries in PATH_LIST should refer to bonds though (not
//  atoms)
//
PATH_LIST uniquifyPaths(const ROMol &mol, const PATH_LIST &allPaths,
                        bool useBO) {
  PATH_LIST res;
  std::vector<DiscrimTuple> discrimsSeen;
  for (const auto &allPath : allPaths) {
    DiscrimTuple discrims = calcPathDiscriminators(mol, allPath, useBO);
    if (std::find(discrimsSeen.begin(), discrimsSeen.end(), discrims) ==
        discrimsSeen.end()) {
      discrimsSeen.push_back(discrims);
      res.push_back(allPath);
    }
  }
  return res;
}
}  // end of namespace Subgraphs
}  // end of namespace RDKit