File: DbFpSupplier.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: -rwxr-xr-x 4,652 bytes parent folder | download | duplicates (2)
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
#
# 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 fingerprints from databases
#DOC

"""
from rdkit import DataStructs
from rdkit.VLib.Node import VLibNode
import pickle


class DbFpSupplier(VLibNode):
    """
      new fps come back with all additional fields from the
      database set in a "_fieldsFromDb" data member

    """

    def __init__(self, dbResults, fpColName='AutoFragmentFp', usePickles=True):
        """

          DbResults should be a subclass of Dbase.DbResultSet.DbResultBase

        """
        VLibNode.__init__(self)
        self._usePickles = usePickles
        self._data = dbResults
        self._fpColName = fpColName.upper()
        self._colNames = [x.upper() for x in self._data.GetColumnNames()]
        if self._fpColName not in self._colNames:
            raise ValueError('fp column name "%s" not found in result set: %s' %
                             (self._fpColName, str(self._colNames)))
        self.fpCol = self._colNames.index(self._fpColName)
        del self._colNames[self.fpCol]
        self._colNames = tuple(self._colNames)
        self._numProcessed = 0

    def GetColumnNames(self):
        return self._colNames

    def _BuildFp(self, data):
        data = list(data)
        pkl = bytes(data[self.fpCol], encoding='Latin1')
        del data[self.fpCol]
        self._numProcessed += 1
        try:
            if self._usePickles:
                newFp = pickle.loads(pkl, encoding='bytes')
            else:
                newFp = DataStructs.ExplicitBitVect(pkl)
        except Exception:
            import traceback
            traceback.print_exc()
            newFp = None
        if newFp:
            newFp._fieldsFromDb = data
        return newFp

    def next(self):
        itm = self.NextItem()
        if itm is None:
            raise StopIteration
        return itm

    __next__ = next  # py3


class ForwardDbFpSupplier(DbFpSupplier):
    """ DbFp supplier supporting only forward iteration

    >>> from rdkit import RDConfig
    >>> from rdkit.Dbase.DbConnection import DbConnect
    >>> fName = RDConfig.RDTestDatabase
    >>> conn = DbConnect(fName,'simple_combined')
    >>> suppl = ForwardDbFpSupplier(conn.GetData())

    we can loop over the supplied fingerprints:
    
    >>> fps = []
    >>> for fp in suppl:
    ...   fps.append(fp)
    >>> len(fps)
    12

    """

    def __init__(self, *args, **kwargs):
        DbFpSupplier.__init__(self, *args, **kwargs)
        self.reset()

    def reset(self):
        DbFpSupplier.reset(self)
        self._dataIter = iter(self._data)

    def NextItem(self):
        """

          NOTE: this has side effects

        """
        try:
            d = next(self._dataIter)
        except StopIteration:
            d = None
        if d is not None:
            newFp = self._BuildFp(d)
        else:
            newFp = None
        return newFp


class RandomAccessDbFpSupplier(DbFpSupplier):
  """ DbFp supplier supporting random access:

  >>> import os.path
  >>> from rdkit import RDConfig
  >>> from rdkit.Dbase.DbConnection import DbConnect
  >>> fName = RDConfig.RDTestDatabase
  >>> conn = DbConnect(fName,'simple_combined')
  >>> suppl = RandomAccessDbFpSupplier(conn.GetData())
  >>> len(suppl)
  12

  we can pull individual fingerprints:

  >>> fp = suppl[5]
  >>> fp.GetNumBits()
  128
  >>> fp.GetNumOnBits()
  54

  a standard loop over the fingerprints:

  >>> fps = []
  >>> for fp in suppl:
  ...   fps.append(fp)
  >>> len(fps)
  12

  or we can use an indexed loop:

  >>> fps = [None]*len(suppl)
  >>> for i in range(len(suppl)):
  ...   fps[i] = suppl[i]
  >>> len(fps)
  12

  """

  def __init__(self, *args, **kwargs):
    DbFpSupplier.__init__(self, *args, **kwargs)
    self.reset()

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

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

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

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


# ------------------------------------
#
#  doctest boilerplate
#
def _runDoctests(verbose=None):  # pragma: nocover
    import sys
    import doctest
    failed, _ = doctest.testmod(optionflags=doctest.ELLIPSIS, verbose=verbose)
    sys.exit(failed)


if __name__ == '__main__':  # pragma: nocover
    _runDoctests()