File: FeatMaps.py

package info (click to toggle)
rdkit 202009.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 129,624 kB
  • sloc: cpp: 288,030; python: 75,571; java: 6,999; ansic: 5,481; sql: 1,968; yacc: 1,842; lex: 1,254; makefile: 572; javascript: 461; xml: 229; fortran: 183; sh: 134; cs: 93
file content (246 lines) | stat: -rw-r--r-- 7,458 bytes parent folder | download | duplicates (3)
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
# $Id$
#
# Copyright (C) 2006 Greg Landrum
#
#   @@ 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.
#
from rdkit.Chem.FeatMaps.FeatMapPoint import FeatMapPoint
import math


class FeatMapScoreMode(object):
  All = 0
  """ score each feature in the probe against every matching
      feature in the FeatMap.
  """

  Closest = 1
  """ score each feature in the probe against the closest
      matching feature in the FeatMap.
  """

  Best = 2
  """ score each feature in the probe against the matching
      feature in the FeatMap that leads to the highest score
  """


class FeatDirScoreMode(object):
  Ignore = 0
  """ ignore feature directions
  """

  DotFullRange = 1
  """ Use the dot product and allow negative contributions when
      directions are anti-parallel.
      e.g. score = dot(f1Dir,f2Dir)
  """

  DotPosRange = 2
  """ Use the dot product and scale contributions to lie between
      zero and one.
      e.g. score = ( dot(f1Dir,f2Dir) + 1 ) / 2
  """


class FeatMapParams(object):
  """ one of these should be instantiated for each
  feature type in the feature map
  """
  radius = 2.5
  " cutoff radius "

  width = 1.0
  " width parameter (e.g. the gaussian sigma) "

  class FeatProfile(object):
    " scoring profile of the feature "
    Gaussian = 0
    Triangle = 1
    Box = 2

  featProfile = FeatProfile.Gaussian


class FeatMap(object):
  dirScoreMode = FeatDirScoreMode.Ignore
  scoreMode = FeatMapScoreMode.All
  params = {}

  def __init__(self, params=None, feats=None, weights=None):
    if params:
      self.params = params
    self._initializeFeats(feats, weights)

  def _initializeFeats(self, feats, weights):
    self._feats = []
    if feats:
      if len(feats) != len(weights):
        raise ValueError('feats and weights lists must be the same length')
      for feat, weight in zip(feats, weights):
        self.AddFeature(feat, weight)

  def AddFeature(self, feat, weight=None):
    if self.params and not feat.GetFamily() in self.params:
      raise ValueError('feature family %s not found in params' % feat.GetFamily())

    newFeat = FeatMapPoint()
    newFeat.initFromFeat(feat)
    newFeat.weight = weight

    self.AddFeatPoint(newFeat)

  def AddFeatPoint(self, featPt):
    if not isinstance(featPt, FeatMapPoint):
      raise ValueError('addFeatPoint() must be called with a FeatMapPoint instance')
    if self.params and not featPt.GetFamily() in self.params:
      raise ValueError('feature family %s not found in params' % featPt.GetFamily())
    self._feats.append(featPt)

  def GetFeatures(self):
    return self._feats

  def GetNumFeatures(self):
    return len(self._feats)

  def GetFeature(self, i):
    return self._feats[i]

  def DropFeature(self, i):
    del self._feats[i]

  def _loopOverMatchingFeats(self, oFeat):
    for sIdx, sFeat in enumerate(self._feats):
      if sFeat.GetFamily() == oFeat.GetFamily():
        yield sIdx, sFeat

  def GetFeatFeatScore(self, feat1, feat2, typeMatch=True):
    """ feat1 is one of our feats
        feat2 is any Feature


    """
    if typeMatch and feat1.GetFamily() != feat2.GetFamily():
      return 0.0
    d2 = feat1.GetDist2(feat2)
    params = self.params[feat1.GetFamily()]
    if d2 > params.radius * params.radius:
      return 0.0

    if params.featProfile == FeatMapParams.FeatProfile.Gaussian:
      score = math.exp(-d2 / params.width)
    elif params.featProfile == FeatMapParams.FeatProfile.Triangle:
      d = math.sqrt(d2)
      if d < params.width:
        score = 1. - d / params.width
      else:
        score = 0.0
    elif params.featProfile == FeatMapParams.FeatProfile.Box:
      score = 1.0
    weight = feat1.weight
    score *= weight

    if self.dirScoreMode != FeatDirScoreMode.Ignore:
      dirScore = feat1.GetDirMatch(feat2)
      if self.dirScoreMode == FeatDirScoreMode.DotPosRange:
        dirScore = (dirScore + 1.0) / 2.0
      elif self.dirScoreMode != FeatDirScoreMode.DotFullRange:
        raise NotImplementedError('bad feature dir score mode')
      score *= dirScore

    return score

  def ScoreFeats(self, featsToScore, mapScoreVect=[], featsScoreVect=[], featsToFeatMapIdx=[]):
    nFeats = len(self._feats)
    if mapScoreVect and len(mapScoreVect) != nFeats:
      raise ValueError('if provided, len(mapScoreVect) should equal numFeats')
    nToScore = len(featsToScore)
    if featsScoreVect and len(featsScoreVect) != nToScore:
      raise ValueError('if provided, len(featsScoreVect) should equal len(featsToScore)')
    if featsToFeatMapIdx and len(featsToFeatMapIdx) != nToScore:
      raise ValueError('if provided, len(featsToFeatMapIdx) should equal len(featsToScore)')

    if mapScoreVect:
      for i in range(nFeats):
        mapScoreVect[i] = 0.0
    else:
      mapScoreVect = [0.0] * nFeats

    if self.scoreMode == FeatMapScoreMode.Closest:
      defScore = 1000.0
    else:
      defScore = 0.0
    if featsScoreVect:
      for i in range(nToScore):
        featsScoreVect[i] = defScore
    else:
      featsScoreVect = [defScore] * nToScore

    if not featsToFeatMapIdx:
      featsToFeatMapIdx = [None] * nToScore

    for i in range(nToScore):
      if self.scoreMode != FeatMapScoreMode.All:
        featsToFeatMapIdx[i] = [-1]
      else:
        featsToFeatMapIdx[i] = []

    for oIdx, oFeat in enumerate(featsToScore):
      for sIdx, sFeat in self._loopOverMatchingFeats(oFeat):
        if self.scoreMode == FeatMapScoreMode.Closest:
          d = sFeat.GetDist2(oFeat)
          if d < featsScoreVect[oIdx]:
            featsScoreVect[oIdx] = d
            featsToFeatMapIdx[oIdx][0] = sIdx
        else:
          lScore = self.GetFeatFeatScore(sFeat, oFeat, typeMatch=False)
          if self.scoreMode == FeatMapScoreMode.Best:
            if lScore > featsScoreVect[oIdx]:
              featsScoreVect[oIdx] = lScore
              featsToFeatMapIdx[oIdx][0] = sIdx
          elif self.scoreMode == FeatMapScoreMode.All:
            featsScoreVect[oIdx] += lScore
            mapScoreVect[sIdx] += lScore
            featsToFeatMapIdx[oIdx].append(sIdx)
          else:
            raise ValueError('bad score mode')

    totScore = 0.0
    if self.scoreMode == FeatMapScoreMode.Closest:
      for oIdx, oFeat in enumerate(featsToScore):
        sIdx = featsToFeatMapIdx[oIdx][0]
        if sIdx > -1:
          lScore = self.GetFeatFeatScore(sFeat, oFeat, typeMatch=False)
          featsScoreVect[oIdx] = lScore
          mapScoreVect[sIdx] = lScore
          totScore += lScore
        else:
          featsScoreVect[oIdx] = 0

    else:
      totScore = sum(featsScoreVect)
      if self.scoreMode == FeatMapScoreMode.Best:
        for oIdx, lScore in enumerate(featsScoreVect):
          sIdx = featsToFeatMapIdx[oIdx][0]
          if sIdx > -1:
            mapScoreVect[sIdx] = lScore

    # replace placeholders:
    if self.scoreMode != FeatMapScoreMode.All:
      for elem in featsToFeatMapIdx:
        if elem == [-1]:
          elem.pop()
    return totScore

  def __str__(self):
    res = ''
    for i, feat in enumerate(self._feats):
      weight = feat.weight
      pos = feat.GetPos()
      res += '% 3d % 12s % 6.4f % 6.4f % 6.4f % 6.4f\n' % (i + 1, feat.GetFamily(), pos.x, pos.y,
                                                           pos.z, weight)
    return res