File: FeatMapParser.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 (191 lines) | stat: -rw-r--r-- 5,307 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
# $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 import Geometry
from rdkit.Chem.FeatMaps import FeatMaps, FeatMapPoint
import re
"""

ScoreMode=All
DirScoreMode=Ignore

BeginParams
  family=Aromatic radius=2.5 width=1.0 profile=Gaussian
  family=Acceptor radius=1.5
EndParams

# optional
BeginPoints
  family=Acceptor pos=(1.0, 0.0, 5.0) weight=1.25 dir=(1, 1, 0)
  family=Aromatic pos=(0.0,1.0,0.0) weight=2.0 dir=(0,0,1) dir=(0,0,-1)
  family=Acceptor pos=(1.0,1.0,2.0) weight=1.25
EndPoints

"""


class FeatMapParseError(ValueError):
  pass


class FeatMapParser(object):
  data = None

  def __init__(self, file=None, data=None):
    if file:
      self.data = file.readlines()
    elif data:
      self.SetData(data)
    self._lineNum = 0

  def SetData(self, data):
    if isinstance(data, str):
      self.data = data.split('\n')
    else:
      self.data = data
    self._lineNum = 0

  def _NextLine(self):
    txt = ''
    while 1:
      try:
        l = self.data[self._lineNum].split('#')[0].strip()
      except IndexError:
        break
      self._lineNum += 1
      if l:
        txt += l
        if l[-1] != '\\':
          break
    return txt

  def Parse(self, featMap=None):
    if featMap is None:
      featMap = FeatMaps.FeatMap()

    l = self._NextLine().strip()
    while l:
      splitL = l.split('=')
      if len(splitL) == 1:
        keyword = splitL[0].strip().lower()
        if keyword == 'beginpoints':
          pts = self.ParseFeatPointBlock()
          for pt in pts:
            featMap.AddFeatPoint(pt)
        elif keyword == 'beginparams':
          featMap.params = self.ParseParamBlock()
        else:
          raise FeatMapParseError('Unrecognized keyword %s on line %d' % (keyword, self._lineNum))
      else:
        keyword = splitL[0].strip().lower()
        val = splitL[1].strip()
        if keyword == 'scoremode':
          try:
            featMap.scoreMode = getattr(FeatMaps.FeatMapScoreMode, val)
          except AttributeError:
            raise FeatMapParseError('ScoreMode %s not recognized on line %d' % (val, self._lineNum))
        elif keyword == 'dirscoremode':
          try:
            featMap.dirScoreMode = getattr(FeatMaps.FeatDirScoreMode, val)
          except AttributeError:
            raise FeatMapParseError('DirScoreMode %s not recognized on line %d' %
                                    (val, self._lineNum))
        else:
          raise FeatMapParseError('Unrecognized keyword %s on line %d' % (keyword, self._lineNum))
      l = self._NextLine().strip()
    return featMap

  def ParseParamBlock(self):
    paramLineSplitter = re.compile(r'([a-zA-Z]+) *= *(\S+)')
    params = {}

    l = self._NextLine()
    while l and l != 'EndParams':
      param = FeatMaps.FeatMapParams()
      vals = paramLineSplitter.findall(l)
      for name, val in vals:
        name = name.lower()
        if name == 'family':
          family = val
        elif name == 'radius':
          param.radius = float(val)
        elif name == 'width':
          param.width = float(val)
        elif name == 'profile':
          try:
            param.featProfile = getattr(param.FeatProfile, val)
          except AttributeError:
            raise FeatMapParseError('Profile %s not recognized on line %d' % (val, self._lineNum))
        else:
          raise FeatMapParseError('FeatMapParam option %s not recognized on line %d' %
                                  (name, self._lineNum))
      params[family] = param
      l = self._NextLine()

    if l != 'EndParams':
      raise FeatMapParseError('EndParams line not found')

    return params

  def _parsePoint(self, txt):
    txt = txt.strip()
    startP = 0
    endP = len(txt)
    if txt[0] == '(':
      startP += 1
    if txt[-1] == ')':
      endP -= 1
    txt = txt[startP:endP]
    splitL = txt.split(',')
    if len(splitL) != 3:
      raise ValueError('Bad location string')
    vs = [float(x) for x in splitL]
    pt = Geometry.Point3D(vs[0], vs[1], vs[2])
    return pt

  def ParseFeatPointBlock(self):
    featLineSplitter = re.compile(r'([a-zA-Z]+) *= *')
    feats = []

    l = self._NextLine()
    while l and l != 'EndPoints':
      vals = featLineSplitter.split(l)
      while vals.count(''):
        vals.remove('')
      p = FeatMapPoint.FeatMapPoint()

      i = 0
      while i < len(vals):
        name = vals[i].lower()
        if name == 'family':
          i += 1
          val = vals[i].strip()
          p.SetFamily(val)
        elif name == 'weight':
          i += 1
          val = float(vals[i])
          p.weight = val
        elif name == 'pos':
          i += 1
          val = vals[i]
          pos = self._parsePoint(val)
          p.SetPos(pos)
        elif name == 'dir':
          i += 1
          val = vals[i]
          pos = self._parsePoint(val)
          p.featDirs.append(pos)
        else:
          raise FeatMapParseError('FeatPoint option %s not recognized on line %d' %
                                  (name, self._lineNum))
        i += 1
      feats.append(p)
      l = self._NextLine()
    return feats