File: UnitTestPandasTools.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 (407 lines) | stat: -rw-r--r-- 13,642 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
from rdkit import RDConfig, rdBase, Chem
from io import StringIO, BytesIO
from rdkit.Chem import PandasTools
import numpy
import unittest
import tempfile
import shutil
import os
import gzip
import doctest
if (getattr(doctest, 'ELLIPSIS_MARKER')):
  doctest.ELLIPSIS_MARKER = '*...*'

try:
  import IPython
except ImportError:
  IPython = None

# We make sure that we don't mess up the Mol methods for the rest of the tests
PandasTools.UninstallPandasTools()


@unittest.skipIf(PandasTools.pd is None, 'Pandas not installed, skipping')
class TestPandasTools(unittest.TestCase):

  def __init__(self, methodName='runTest'):
    self.df = getTestFrame()
    self.df.index.name = 'IndexName'
    super(TestPandasTools, self).__init__(methodName=methodName)

  def setUp(self):
    PandasTools.InstallPandasTools()
    PandasTools.ChangeMoleculeRendering(renderer='PNG')
    PandasTools.pd.set_option('display.max_columns', None)
    self._molRepresentation = PandasTools.molRepresentation
    self._highlightSubstructures = PandasTools.highlightSubstructures

  def tearDown(self):
    PandasTools.molRepresentation = self._molRepresentation
    PandasTools.highlightSubstructures = self._highlightSubstructures
    PandasTools.UninstallPandasTools()

  def testDoctest(self):
    # We need to do it like this to ensure that default RDkit functionality is restored
    failed, _ = doctest.testmod(PandasTools,
                                optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE)
    self.assertFalse(failed)

  def test_RestoreMonkeyPatch(self):
    sio = getStreamIO(methane + peroxide)
    df = PandasTools.LoadSDF(sio)
    html = df.to_html()
    self.assertIn('data:image/png;base64', html)
    self.assertIn('table', html)

    PandasTools.UninstallPandasTools()
    html = df.to_html()
    self.assertNotIn('data:image/png;base64', html)
    self.assertIn('rdkit.Chem.rdchem.Mol', html)
    self.assertIn('table', html)

    PandasTools.InstallPandasTools()
    html = df.to_html()
    self.assertIn('data:image/png;base64', html)
    self.assertIn('table', html)

    PandasTools.UninstallPandasTools()
    html = df.to_html()
    self.assertNotIn('data:image/png;base64', html)
    self.assertIn('rdkit.Chem.rdchem.Mol', html)
    self.assertIn('table', html)

  def test_FrameToGridImage(self):
    # This test only makes sure that we get no exception. To see the created images, set
    # interactive to True
    interactive = False
    self.assertTrue(True)
    df = self.df

    result = PandasTools.FrameToGridImage(df)
    if interactive:
      result.show()

    result = PandasTools.FrameToGridImage(df, legendsCol='PUBCHEM_IUPAC_INCHIKEY')
    if interactive:
      result.show()

    result = PandasTools.FrameToGridImage(df, legendsCol=df.index.name)
    if interactive:
      result.show()

  def test_AddMurckoToFrame(self):
    df = self.df.copy()
    self.assertIn('ROMol', df.columns)
    self.assertNotIn('Murcko_SMILES', df.columns)
    PandasTools.AddMurckoToFrame(df)
    self.assertIn('ROMol', df.columns)
    self.assertIn('Murcko_SMILES', df.columns)
    self.assertEqual(df['Murcko_SMILES'][10], 'O=C(CCn1c(-c2ccccc2)n[nH]c1=S)Nc1ccccn1')

    PandasTools.AddMurckoToFrame(df, Generic=True)
    self.assertIn('ROMol', df.columns)
    self.assertIn('Murcko_SMILES', df.columns)
    self.assertEqual(df['Murcko_SMILES'][10], 'CC(CCC1C(C)CCC1C1CCCCC1)CC1CCCCC1')

  def test_SaveSMILESFromFrame(self):
    sio = StringIO()
    PandasTools.SaveSMILESFromFrame(self.df, sio)
    result = sio.getvalue()
    self.assertIn(self.df['SMILES'][10], result)
    self.assertIn(self.df['ID'][10], result)

    sio = StringIO()
    PandasTools.SaveSMILESFromFrame(self.df, sio, NamesCol='PUBCHEM_IUPAC_INCHIKEY')
    result = sio.getvalue()
    self.assertIn(self.df['SMILES'][10], result)
    self.assertIn(self.df['PUBCHEM_IUPAC_INCHIKEY'][10], result)

  @unittest.skipIf(IPython is None, 'Package IPython required for testing')
  def test_svgRendering(self):
    df = PandasTools.LoadSDF(getStreamIO(methane + peroxide))
    self.assertIn('image/png', df.to_html())
    self.assertNotIn('svg', df.to_html())

    PandasTools.molRepresentation = 'svg'
    self.assertIn('svg', df.to_html())
    self.assertNotIn('image/png', df.to_html())

    # we can use upper case for the molRepresentation
    PandasTools.molRepresentation = 'PNG'
    self.assertNotIn('svg', df.to_html())
    self.assertIn('image/png', df.to_html())

  def test_patchHeadFrame(self):
    df = self.df.copy()
    result = str(df.head())
    self.assertIn('35024984', result)
    self.assertNotIn('35024985', result)

  def test_AddMoleculeColumnToFrame(self):
    df = PandasTools.LoadSDF(getStreamIO(methane + peroxide), isomericSmiles=True,
                             smilesName='Smiles')
    PandasTools.ChangeMoleculeRendering(frame=df, renderer='String')
    del df['ROMol']
    self.assertNotIn('ROMol', str(df))
    PandasTools.AddMoleculeColumnToFrame(df, includeFingerprints=False)
    self.assertIn('ROMol', str(df))

  def test_molge(self):
    # We want to have the default RDkit functionality for testing
    PandasTools.UninstallPandasTools()
    molge = PandasTools._molge
    mol1 = Chem.MolFromSmiles('CCC')
    mol2 = Chem.MolFromSmiles('CC')
    mol3 = Chem.MolFromSmiles('CN')

    self.assertFalse(molge(mol1, None))
    self.assertFalse(molge(None, mol1))

    self.assertFalse(hasattr(mol1, '_substructfp'))
    self.assertFalse(hasattr(mol2, '_substructfp'))
    self.assertFalse(hasattr(mol1, '__sssAtoms'))
    self.assertFalse(hasattr(mol2, '__sssAtoms'))

    self.assertTrue(molge(mol1, mol2))
    self.assertEqual(mol1.__dict__['__sssAtoms'], [0, 1])
    PandasTools.highlightSubstructures = False
    self.assertTrue(molge(mol1, mol2))
    self.assertEqual(mol1.__dict__['__sssAtoms'], [])

    PandasTools.highlightSubstructures = True
    self.assertFalse(molge(mol2, mol1))
    self.assertEqual(mol2.__dict__['__sssAtoms'], [])

    self.assertFalse(molge(mol1, mol3))
    self.assertEqual(mol1.__dict__['__sssAtoms'], [])

  @unittest.skipIf(IPython is None, 'Package IPython required for testing')
  def test_github2380(self):
    from rdkit.Chem.Draw import IPythonConsole
    IPythonConsole.ipython_useSVG = True
    df = PandasTools.LoadSDF(getStreamIO(methane + peroxide))
    _ = PandasTools.FrameToGridImage(df)

  def test_RGD(self):
    from rdkit.Chem import rdRGroupDecomposition
    scaffold = Chem.MolFromSmiles('c1ccccn1')
    mols = [
      Chem.MolFromSmiles(smi)
      for smi in 'c1c(F)cccn1 c1c(Cl)c(C)ccn1 c1c(O)cccn1 c1c(F)c(C)ccn1 c1cc(Cl)c(F)cn1'.split()
    ]
    groups, _ = rdRGroupDecomposition.RGroupDecompose([scaffold], mols, asSmiles=True, asRows=False)
    df = PandasTools.RGroupDecompositionToFrame(groups, mols, include_core=True)
    self.assertEqual(len(df), len(mols))
    self.assertEqual(list(df.columns), ['Mol', 'Core', 'R1', 'R2'])
    self.assertEqual(list(df.R1), ['F[*:1]', 'Cl[*:1]', 'O[*:1]', 'F[*:1]', 'F[*:1]'])

    groups, _ = rdRGroupDecomposition.RGroupDecompose([scaffold], mols, asSmiles=False,
                                                      asRows=False)
    df = PandasTools.RGroupDecompositionToFrame(groups, mols, include_core=True)
    self.assertEqual(len(df), len(mols))
    self.assertEqual(list(df.columns), ['Mol', 'Core', 'R1', 'R2'])
    self.assertEqual([Chem.MolToSmiles(x) for x in df.R1],
                     ['F[*:1]', 'Cl[*:1]', 'O[*:1]', 'F[*:1]', 'F[*:1]'])


@unittest.skipIf(PandasTools.pd is None, 'Pandas not installed, skipping')
class TestLoadSDF(unittest.TestCase):
  gz_filename = os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'pandas_load.sdf.gz')

  # the doctest tests loading from a ".sdf" file so there's no need for that test here

  def test_load_gzip_file(self):
    rdBase.DisableLog('rdApp.error')
    df = PandasTools.LoadSDF(self.gz_filename)
    rdBase.EnableLog('rdApp.error')
    self.assertEqual(len(df), 13)
    # The molecule with index 1 is invalid, so it should be missing form the index
    self.assertEqual(list(df.index), [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

  def test_load_from_sio(self):
    sio = getStreamIO(methane + peroxide)
    df = PandasTools.LoadSDF(sio)
    self.assertEqual(len(df), 2)
    self.assertEqual(list(df["ID"]), ["Methane", "Peroxide"])
    atom_counts = [mol.GetNumAtoms() for mol in df["ROMol"]]
    self.assertEqual(atom_counts, [1, 2])

  def test_load_specify_column_names(self):
    sio = getStreamIO(methane + peroxide)
    df = PandasTools.LoadSDF(sio, idName="CorpID", molColName="_rdmol")
    self.assertEqual(len(df), 2)
    self.assertEqual(list(df["CorpID"]), ["Methane", "Peroxide"])
    atom_counts = [mol.GetNumAtoms() for mol in df["_rdmol"]]
    self.assertEqual(atom_counts, [1, 2])

  def test_empty_file(self):
    # Should return an empty data frame with no rows or columns
    sio = getStreamIO(None)
    df = PandasTools.LoadSDF(sio)
    self.assertEqual(len(df), 0)
    self.assertEqual(len(df.index), 0)

  def test_passed_in_file_is_not_closed(self):
    sio = getStreamIO(methane)
    df = PandasTools.LoadSDF(sio)
    self.assertEqual(len(df), 1)
    self.assertFalse(sio.closed)

  def test_properties(self):
    sio = getStreamIO(peroxide + methane)
    df = PandasTools.LoadSDF(sio)
    self.assertEqual(set(df.columns), set("ROMol ID prop1 prop2 prop3".split()))
    prop1 = list(df["prop1"])
    self.assertTrue(numpy.isnan(prop1[0]), prop1[0])
    self.assertEqual(prop1[1], "12.34")

    self.assertEqual(list(df["prop2"]), ["rtz", "qwe"])

    prop3 = list(df["prop3"])
    self.assertEqual(prop3[0], "yxcv")
    self.assertTrue(numpy.isnan(prop3[1]), prop3[1])

  def test_ignore_mol_column(self):
    sio = getStreamIO(peroxide + methane)
    df = PandasTools.LoadSDF(sio, molColName=None)
    self.assertEqual(set(df.columns), set("ID prop1 prop2 prop3".split()))


@unittest.skipIf(PandasTools.pd is None, 'Pandas not installed, skipping')
class TestWriteSDF(unittest.TestCase):

  def setUp(self):
    self.df = PandasTools.LoadSDF(getStreamIO(methane + peroxide))

  def test_default_write_does_not_include_tags(self):
    sio = StringIO()
    PandasTools.WriteSDF(self.df, sio)
    s = sio.getvalue()
    self.assertNotIn(s, "prop2")

  def test_identifier_from_a_column(self):
    sio = StringIO()
    PandasTools.WriteSDF(self.df, sio, idName="prop2")
    s = sio.getvalue()
    first_line = s.split("\n", 1)[0]
    self.assertEqual(first_line, "qwe")

  def test_all_numeric_with_no_numeric_columns(self):
    sio = StringIO()
    PandasTools.WriteSDF(self.df, sio, allNumeric=True)
    s = sio.getvalue()
    self.assertFalse(">" in s, s)
    self.assertNotIn("7\n\n", s)  # double-check that the numeric tests don't pass by accident
    self.assertNotIn("8\n\n", s)

  def test_all_numeric_with_numeric_columns(self):
    sio = StringIO()
    df = self.df
    df["len"] = df["ID"].map(len)
    PandasTools.WriteSDF(df, sio, allNumeric=True)
    s = sio.getvalue()
    self.assertEqual(s.count("<len>"), 2)
    self.assertIn("7\n\n", s)
    self.assertIn("8\n\n", s)

  def test_specify_numeric_column(self):
    sio = StringIO()
    df = self.df
    df["len2"] = df["ID"].map(len)
    PandasTools.WriteSDF(df, sio, properties=["len2"])
    s = sio.getvalue()
    self.assertEqual(s.count("<len2>"), 2)
    self.assertIn("7\n\n", s)
    self.assertIn("8\n\n", s)

  def test_specify_numeric_column_2(self):
    sio = StringIO()
    df = self.df
    df["len2"] = df["ID"].map(len)
    df["len3"] = df["len2"].map(float)
    PandasTools.WriteSDF(df, sio, properties=["len2", "len3"])
    s = sio.getvalue()
    self.assertEqual(s.count("<len2>"), 2)
    self.assertEqual(s.count("<len3>"), 2)
    self.assertIn("7\n\n", s)
    self.assertIn("7.0\n\n", s)
    self.assertIn("8\n\n", s)
    self.assertIn("8.0\n\n", s)

  def test_write_to_sdf(self):
    dirname = tempfile.mkdtemp()
    try:
      filename = os.path.join(dirname, "test.sdf")
      PandasTools.WriteSDF(self.df, filename)
      with open(filename) as f:
        s = f.read()
      self.assertEqual(s.count("\n$$$$\n"), 2)
      self.assertEqual(s.split("\n", 1)[0], "Methane")
    finally:
      shutil.rmtree(dirname)

  def test_write_to_sdf_gz(self):
    dirname = tempfile.mkdtemp()
    try:
      filename = os.path.join(dirname, "test.sdf.gz")
      PandasTools.WriteSDF(self.df, filename)
      with gzip.open(filename) as f:
        s = f.read()
      s = s.decode('utf-8')
      s = s.replace(os.linesep, '\n')
      self.assertEqual(s.count("\n$$$$\n"), 2)
      self.assertEqual(s.split("\n", 1)[0], "Methane")
    finally:
      shutil.rmtree(dirname)


def getStreamIO(sdfString):
  """ Return a StringIO/BytesIO for the string """
  sio = BytesIO() if sdfString is None else BytesIO(sdfString.encode('utf-8'))
  return sio


def getTestFrame():
  rdBase.DisableLog('rdApp.error')
  sdfFile = os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', 'pandas_load.sdf.gz')
  df = PandasTools.LoadSDF(sdfFile, smilesName='SMILES')
  rdBase.EnableLog('rdApp.error')
  return df


methane = """\
Methane
     RDKit

  1  0  0  0  0  0  0  0  0  0999 V2000
    0.0000    0.0000    0.0000 C   0  0  0  0  0  0  0  0  0  0  0  0
M  END
> <prop1>
12.34

> <prop2>
qwe

$$$$
"""

peroxide = """\
Peroxide
     RDKit

  2  1  0  0  0  0  0  0  0  0999 V2000
    0.0000    0.0000    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0
    0.0000    0.0000    0.0000 O   0  0  0  0  0  0  0  0  0  0  0  0
  1  2  1  0
M  END
> <prop2>
rtz

> <prop3>
yxcv

$$$$
"""

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