File: UnitTestSDMolSupplier.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 (180 lines) | stat: -rwxr-xr-x 5,595 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
# $Id$
#
#  Copyright (C) 2002-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.
#
"""
unit testing code for the SD file handling stuff
"""
import os
import tempfile
import unittest

from rdkit import Chem
from rdkit import RDConfig


class TestCase(unittest.TestCase):

    def setUp(self):
        self.fName = os.path.join(RDConfig.RDDataDir, 'NCI', 'first_200.props.sdf')
        with open(self.fName, 'r') as inf:
            inD = inf.read()
        self.nMolecules = inD.count('$$$$')

    def assertMolecule(self, mol, i):
        """ Assert that we have a valid molecule """
        self.assertIsNotNone(mol, 'read %d failed' % i)
        self.assertGreater(mol.GetNumAtoms(), 0, 'no atoms in mol %d' % i)

    def test_SDMolSupplier(self):
        # tests reads using a file name (file contains 200 molecules)
        supp = Chem.SDMolSupplier(self.fName)

        # Can use as an iterator
        for i in range(10):
            mol = next(supp)
            self.assertMolecule(mol, i)

        # Can access directly
        i = 100
        mol = supp[i - 1]
        self.assertMolecule(mol, i)

        # We can access the number of molecules
        self.assertEqual(len(supp), self.nMolecules, 'bad supplier length')

        # We know the number and can still access directly
        i = 12
        mol = supp[i - 1]
        self.assertMolecule(mol, i)

        # Get an exception if we access an invalid number
        with self.assertRaises(IndexError):
            _ = supp[self.nMolecules]  # out of bound read must fail

        # and we can access with negative numbers
        mol1 = supp[len(supp) - 1]
        mol2 = supp[-1]
        self.assertEqual(Chem.MolToSmiles(mol1), Chem.MolToSmiles(mol2))

    def test_SDWriter(self):
        # tests writes using a file name
        supp = Chem.SDMolSupplier(self.fName)
        outName = tempfile.NamedTemporaryFile(suffix='.sdf', delete=False).name
        writer = Chem.SDWriter(outName)
        m1 = next(supp)
        writer.SetProps(m1.GetPropNames())
        for m in supp:
            writer.write(m)
        writer.flush()
        writer.close()

        # The writer does not have an explicit "close()" so need to
        # let the garbage collector kick in to close the file.
        writer = None
        with open(outName, 'r') as inf:
            outD = inf.read()
        # The file should be closed, but if it isn't, and this
        # is Windows, then the unlink() can fail. Wait and try again.
        try:
            os.unlink(outName)
        except Exception:
            import time
            time.sleep(1)
            try:
                os.unlink(outName)
            except Exception:
                pass
        self.assertEqual(self.nMolecules, outD.count('$$$$'), 'bad nMols in output')

#   def _testStreamRoundtrip(self):
#     inD = open(self.fName).read()
#     supp = Chem.SDMolSupplier(self.fName)
#     outName = tempfile.mktemp('.sdf')
#     writer = Chem.SDWriter(outName)
#     _ = next(supp)
#     for m in supp:
#       writer.write(m)
#     writer.flush()
#     writer = None
#     outD = open(outName, 'r').read()
#     try:
#       os.unlink(outName)
#     except Exception:
#       import time
#       time.sleep(1)
#       try:
#         os.unlink(outName)
#       except Exception:
#         pass
#     assert inD.count('$$$$') == outD.count('$$$$'), 'bad nMols in output'
#     io = StringIO(outD)
#     supp = Chem.SDMolSupplier(stream=io)
#     outD2 = supp.Dump()
#     assert outD2.count('$$$$') == len(supp), 'bad nMols in output'
#     assert outD2.count('$$$$') == outD.count('$$$$'), 'bad nMols in output'
#     assert outD2 == outD, 'bad outd'

#   def _testLazyDataRoundtrip(self):
#     inD = open(self.fName).read()
#     supp = Chem.SDMolSupplier(self.fName)
#     outName = tempfile.mktemp('.sdf')
#     writer = Chem.SDWriter(outName)
#     _ = next(supp)
#     for m in supp:
#       writer.write(m)
#     writer.flush()
#     writer = None
#     outD = open(outName, 'r').read()
#     try:
#       os.unlink(outName)
#     except Exception:
#       import time
#       time.sleep(1)
#       try:
#         os.unlink(outName)
#       except Exception:
#         pass
#     assert inD.count('$$$$') == outD.count('$$$$'), 'bad nMols in output'
#     supp = Chem.SDMolSupplier.LazySDMolSupplier(inD=outD)
#     outD2 = supp.Dump()
#     assert outD2.count('$$$$') == len(supp), 'bad nMols in output'
#     assert outD2.count('$$$$') == outD.count('$$$$'), 'bad nMols in output'
#     assert outD2 == outD, 'bad outd'

#   def _testLazyIter(self):
#     " tests lazy reads using the iterator interface "
#     supp = Chem.SDMolSupplier.LazySDMolSupplier(fileN=self.fName)
#
#     nDone = 0
#     for mol in supp:
#       assert mol, 'read %d failed' % nDone
#       assert mol.GetNumAtoms(), 'no atoms in mol %d' % nDone
#       nDone += 1
#     assert nDone == 200, 'bad number of molecules: %d' % (nDone)
#
#     l = len(supp)
#     assert l == 200, 'bad supplier length: %d' % (l)
#
#     i = 12
#     m = supp[i - 1]
#     assert m, 'back index %d failed' % i
#     assert m.GetNumAtoms(), 'no atoms in mol %d' % i
#
#     try:
#       m = supp[201]
#     except IndexError:
#       fail = 1
#     else:
#       fail = 0
#     assert fail, 'out of bound read did not fail'


if __name__ == '__main__':  # pragma: nocover
    unittest.main()