File: DbMolSupplier.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 (166 lines) | stat: -rw-r--r-- 4,093 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
#
# Copyright (C) 2003-2006 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.
#
"""
Supplies a class for working with molecules from databases
"""
import sys

from rdkit import Chem
from rdkit.Chem.Suppliers.MolSupplier import MolSupplier


def warning(msg, dest=sys.stderr):
  dest.write(msg)


class DbMolSupplier(MolSupplier):
  """
    new molecules come back with all additional fields from the
    database set in a "_fieldsFromDb" data member

  """

  def __init__(self, dbResults, molColumnFormats={'SMILES': 'SMI',
                                                  'SMI': 'SMI',
                                                  'MOLPKL': 'PKL'}, nameCol='', transformFunc=None,
               **kwargs):
    """

      DbResults should be a subclass of Dbase.DbResultSet.DbResultBase

    """
    self._data = dbResults
    self._colNames = [x.upper() for x in self._data.GetColumnNames()]
    nameCol = nameCol.upper()
    self.molCol = -1
    self.transformFunc = transformFunc
    try:
      self.nameCol = self._colNames.index(nameCol)
    except ValueError:
      self.nameCol = -1
    for name in molColumnFormats:
      name = name.upper()
      try:
        idx = self._colNames.index(name)
      except ValueError:
        pass
      else:
        self.molCol = idx
        self.molFmt = molColumnFormats[name]
        break
    if self.molCol < 0:
      raise ValueError('DbResultSet has no recognizable molecule column')
    del self._colNames[self.molCol]
    self._colNames = tuple(self._colNames)
    self._numProcessed = 0

  def GetColumnNames(self):
    return self._colNames

  def _BuildMol(self, data):
    data = list(data)
    molD = data[self.molCol]
    del data[self.molCol]
    self._numProcessed += 1
    try:
      if self.molFmt == 'SMI':
        newM = Chem.MolFromSmiles(str(molD))
        if not newM:
          warning('Problems processing mol %d, smiles: %s\n' % (self._numProcessed, molD))
      elif self.molFmt == 'PKL':
        newM = Chem.Mol(str(molD))
    except Exception:
      import traceback
      traceback.print_exc()
      newM = None
    else:
      if newM and self.transformFunc:
        try:
          newM = self.transformFunc(newM, data)
        except Exception:
          import traceback
          traceback.print_exc()
          newM = None
      if newM:
        newM._fieldsFromDb = data
        nFields = len(data)
        for i in range(nFields):
          newM.SetProp(self._colNames[i], str(data[i]))
        if self.nameCol >= 0:
          newM.SetProp('_Name', str(data[self.nameCol]))
    return newM


class ForwardDbMolSupplier(DbMolSupplier):
  """ DbMol supplier supporting only forward iteration


    new molecules come back with all additional fields from the
    database set in a "_fieldsFromDb" data member

  """

  def __init__(self, dbResults, **kwargs):
    """

      DbResults should be an iterator for Dbase.DbResultSet.DbResultBase

    """
    DbMolSupplier.__init__(self, dbResults, **kwargs)
    self.Reset()

  def Reset(self):
    self._dataIter = iter(self._data)

  def NextMol(self):
    """

      NOTE: this has side effects

    """
    try:
      d = self._dataIter.next()
    except StopIteration:
      d = None
    if d is not None:
      newM = self._BuildMol(d)
    else:
      newM = None

    return newM


class RandomAccessDbMolSupplier(DbMolSupplier):

  def __init__(self, dbResults, **kwargs):
    """

      DbResults should be a Dbase.DbResultSet.RandomAccessDbResultSet

    """
    DbMolSupplier.__init__(self, dbResults, **kwargs)
    self._pos = -1

  def __len__(self):
    return len(self._data)

  def __getitem__(self, idx):
    newD = self._data[idx]
    return self._BuildMol(newD)

  def Reset(self):
    self._pos = -1

  def NextMol(self):
    self._pos += 1
    res = None
    if self._pos < len(self):
      res = self[self._pos]
    return res