File: SimilarityScreener.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 (177 lines) | stat: -rw-r--r-- 5,016 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
# $Id$
#
# 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.
#
""" class definitions for similarity screening

See _SimilarityScreener_ for overview of required API

"""
from rdkit import DataStructs
from rdkit.DataStructs import TopNContainer


class SimilarityScreener(object):
    """  base class

     important attributes:
        probe: the probe fingerprint against which we screen.

        metric: a function that takes two arguments and returns a similarity
                measure between them

        dataSource: the source pool from which to draw, needs to support
                a next() method

        fingerprinter: a function that takes a molecule and returns a
               fingerprint of the appropriate format


      **Notes**
         subclasses must support either an iterator interface
         or __len__ and __getitem__
    """

    def __init__(self, probe=None, metric=None, dataSource=None, fingerprinter=None):
        self.metric = metric
        self.dataSource = dataSource
        self.fingerprinter = fingerprinter
        self.probe = probe

    def Reset(self):
        """ used to reset screeners that behave as iterators """
        pass

    # FIX: add setters/getters for attributes
    def SetProbe(self, probeFingerprint):
        """ sets our probe fingerprint """
        self.probe = probeFingerprint

    def GetSingleFingerprint(self, probe):
        """ returns a fingerprint for a single probe object

         This is potentially useful in initializing our internal
         probe object.

        """
        return self.fingerprinter(probe)


class ThresholdScreener(SimilarityScreener):
    """ Used to return all compounds that have a similarity
      to the probe beyond a threshold value

     **Notes**:

       - This is as lazy as possible, so the data source isn't
         queried until the client asks for a hit.

       - In addition to being lazy, this class is as thin as possible.
         (Who'd have thought it was possible!)
         Hits are *not* stored locally, so if a client resets
         the iteration and starts over, the same amount of work must
         be done to retrieve the hits.

       - The thinness and laziness forces us to support only forward
         iteration (not random access)

    """

    def __init__(self, threshold, **kwargs):
        SimilarityScreener.__init__(self, **kwargs)
        self.threshold = threshold
        self.dataIter = iter(self.dataSource)
    # FIX: add setters/getters for attributes

    def _nextMatch(self):
        """ *Internal use only* """
        done = 0
        res = None
        sim = 0
        while not done:
            # this is going to crap out when the data source iterator finishes,
            #  that's how we stop when no match is found
            obj = next(self.dataIter)
            fp = self.fingerprinter(obj)
            sim = DataStructs.FingerprintSimilarity(fp, self.probe, self.metric)
            if sim >= self.threshold:
                res = obj
                done = 1
        return sim, res

    def Reset(self):
        """ used to reset our internal state so that iteration
          starts again from the beginning
        """
        self.dataSource.reset()
        self.dataIter = iter(self.dataSource)

    def __iter__(self):
        """ returns an iterator for this screener
        """
        self.Reset()
        return self

    def next(self):
        """ required part of iterator interface """
        return self._nextMatch()

    __next__ = next


class TopNScreener(SimilarityScreener):
    """ A screener that only returns the top N hits found

      **Notes**

        - supports forward iteration and getitem

    """

    def __init__(self, num, **kwargs):
        SimilarityScreener.__init__(self, **kwargs)
        self.numToGet = num
        self.topN = None
        self._pos = 0

    def Reset(self):
        self._pos = 0

    def __iter__(self):
        if self.topN is None:
            self._initTopN()
        self.Reset()
        return self

    def next(self):
        if self._pos >= self.numToGet:
            raise StopIteration
        else:
            res = self.topN[self._pos]
            self._pos += 1
            return res

    __next__ = next

    def _initTopN(self):
        self.topN = TopNContainer.TopNContainer(self.numToGet)
        for obj in self.dataSource:
            fp = self.fingerprinter(obj)
            sim = DataStructs.FingerprintSimilarity(fp, self.probe, self.metric)
            self.topN.Insert(sim, obj)

    def __len__(self):
        if self.topN is None:
            self._initTopN()
        return self.numToGet

    def __getitem__(self, idx):
        if self.topN is None:
            self._initTopN()
        return self.topN[idx]