diff --git a/CMakeLists.txt b/CMakeLists.txt index abf9f961b..b36b37b19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -124,7 +124,7 @@ if(RDK_BUILD_PYTHON_WRAPPERS) # From http://plplot.svn.sourceforge.net/viewvc/plplot/trunk/cmake/modules/python.cmake?revision=11014 execute_process( COMMAND - ${PYTHON_EXECUTABLE} -c "from distutils import sysconfig; print sysconfig.get_python_lib(1,0,prefix='${CMAKE_INSTALL_PREFIX}')" + ${PYTHON_EXECUTABLE} -c "from __future__ import print_function; from distutils import sysconfig; print(sysconfig.get_python_lib(1,0,prefix='${CMAKE_INSTALL_PREFIX}'))" OUTPUT_VARIABLE PYTHON_INSTDIR OUTPUT_STRIP_TRAILING_WHITESPACE ) diff --git a/Code/ChemicalFeatures/Wrap/testFeatures.py b/Code/ChemicalFeatures/Wrap/testFeatures.py index 3dfeb4160..609e245af 100644 --- a/Code/ChemicalFeatures/Wrap/testFeatures.py +++ b/Code/ChemicalFeatures/Wrap/testFeatures.py @@ -4,12 +4,13 @@ # # @@ All Rights Reserved @@ # -from rdkit import RDConfig +from __future__ import print_function import os +import unittest +from rdkit.six.moves import cPickle +from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import ChemicalFeatures -import unittest -import cPickle from rdkit.Geometry import rdGeometry as geom def feq(v1,v2,tol2=1e-4): @@ -36,52 +37,52 @@ class TestCase(unittest.TestCase): ffeat = ChemicalFeatures.FreeChemicalFeature() ffeat.SetId(123) pos = ffeat.GetId() - self.failUnless(pos == 123) + self.assertTrue(pos == 123) ffeat.SetFamily("HBondDonor") - self.failUnless(ffeat.GetFamily() == "HBondDonor") + self.assertTrue(ffeat.GetFamily() == "HBondDonor") ffeat.SetPos(geom.Point3D(1.0, 2.0, 3.0)) pos = ffeat.GetPos() - self.failUnless(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) + self.assertTrue(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) ffeat.SetType("HBondDonor1") - self.failUnless(ffeat.GetType() == "HBondDonor1") + self.assertTrue(ffeat.GetType() == "HBondDonor1") ffeat = ChemicalFeatures.FreeChemicalFeature("HBondDonor", "HBondDonor1", geom.Point3D(1.0, 2.0, 3.0)) - self.failUnless(ffeat.GetId() == -1) - self.failUnless(ffeat.GetFamily() == "HBondDonor") - self.failUnless(ffeat.GetType() == "HBondDonor1") + self.assertTrue(ffeat.GetId() == -1) + self.assertTrue(ffeat.GetFamily() == "HBondDonor") + self.assertTrue(ffeat.GetType() == "HBondDonor1") ffeat = ChemicalFeatures.FreeChemicalFeature("HBondDonor", "HBondDonor1", geom.Point3D(1.0, 2.0, 3.0),id=123) - self.failUnless(ffeat.GetId() == 123) - self.failUnless(ffeat.GetFamily() == "HBondDonor") - self.failUnless(ffeat.GetType() == "HBondDonor1") + self.assertTrue(ffeat.GetId() == 123) + self.assertTrue(ffeat.GetFamily() == "HBondDonor") + self.assertTrue(ffeat.GetType() == "HBondDonor1") pos = ffeat.GetPos() - self.failUnless(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) + self.assertTrue(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) ffeat = ChemicalFeatures.FreeChemicalFeature(id = 123, type="HBondDonor1", family="HBondDonor", loc=geom.Point3D(1.0, 2.0, 3.0)) - self.failUnless(ffeat.GetId() == 123) - self.failUnless(ffeat.GetFamily() == "HBondDonor") - self.failUnless(ffeat.GetType() == "HBondDonor1") + self.assertTrue(ffeat.GetId() == 123) + self.assertTrue(ffeat.GetFamily() == "HBondDonor") + self.assertTrue(ffeat.GetType() == "HBondDonor1") pos = ffeat.GetPos() - self.failUnless(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) + self.assertTrue(ptFeq(pos, geom.Point3D(1.0, 2.0, 3.0))) def testPickle(self): ffeat = ChemicalFeatures.FreeChemicalFeature("HBondDonor", "HBondDonor1", geom.Point3D(1.0, 2.0, 3.0),123) pkl = cPickle.dumps(ffeat) ffeat2 = cPickle.loads(pkl) - self.failUnless(ffeat2.GetId()==ffeat.GetId()); - self.failUnless(ffeat2.GetFamily()==ffeat.GetFamily()) - self.failUnless(ffeat2.GetType()==ffeat.GetType()) - self.failUnless(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) + self.assertTrue(ffeat2.GetId()==ffeat.GetId()); + self.assertTrue(ffeat2.GetFamily()==ffeat.GetFamily()) + self.assertTrue(ffeat2.GetType()==ffeat.GetType()) + self.assertTrue(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) # Check that the old pickled versions have not been broken inF = file(os.path.join(RDConfig.RDBaseDir, 'Code/ChemicalFeatures/Wrap/testData/feat.pkl'),'rb') ffeat2=cPickle.load(inF) # this version (1.0) does not have an id in the byte stream - self.failUnless(ffeat2.GetFamily()==ffeat.GetFamily()) - self.failUnless(ffeat2.GetType()==ffeat.GetType()) - self.failUnless(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) + self.assertTrue(ffeat2.GetFamily()==ffeat.GetFamily()) + self.assertTrue(ffeat2.GetType()==ffeat.GetType()) + self.assertTrue(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) # Test the new version also has the id and works as expected @@ -91,13 +92,13 @@ class TestCase(unittest.TestCase): inF = file(os.path.join(RDConfig.RDBaseDir, 'Code/ChemicalFeatures/Wrap/testData/featv2.pkl'),'rb') ffeat2=cPickle.load(inF) - self.failUnless(ffeat2.GetId()==ffeat.GetId()); - self.failUnless(ffeat2.GetFamily()==ffeat.GetFamily()) - self.failUnless(ffeat2.GetType()==ffeat.GetType()) - self.failUnless(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) + self.assertTrue(ffeat2.GetId()==ffeat.GetId()); + self.assertTrue(ffeat2.GetFamily()==ffeat.GetFamily()) + self.assertTrue(ffeat2.GetType()==ffeat.GetType()) + self.assertTrue(ptFeq(ffeat2.GetPos(),ffeat.GetPos())) if __name__ == '__main__': - print "Testing ChemicalFeatures Wrapper code:" + print("Testing ChemicalFeatures Wrapper code:") unittest.main() diff --git a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp index cfd2242bb..af99a48d7 100644 --- a/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp +++ b/Code/DataManip/MetricMatrixCalc/Wrap/rdMetricMatrixCalc.cpp @@ -15,6 +15,7 @@ #include #include +#include #include @@ -240,7 +241,7 @@ BOOST_PYTHON_MODULE(rdMetricMatrixCalc) "e.g. similarity and distance matrices" ; - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_index_error); python::register_exception_translator(&translate_value_error); diff --git a/Code/DataManip/MetricMatrixCalc/Wrap/testMatricCalc.py b/Code/DataManip/MetricMatrixCalc/Wrap/testMatricCalc.py index 6a369f973..da870773c 100755 --- a/Code/DataManip/MetricMatrixCalc/Wrap/testMatricCalc.py +++ b/Code/DataManip/MetricMatrixCalc/Wrap/testMatricCalc.py @@ -1,3 +1,4 @@ +from __future__ import division from rdkit import RDConfig import unittest from rdkit.DataManip.Metric import rdMetricMatrixCalc as rdmmc @@ -111,7 +112,7 @@ class TestCase(unittest.TestCase): assert numpy.shape(dmatArr) == numpy.shape(dmatLL) - for i in range(n*(n-1)/2): + for i in range(n*(n-1)//2): assert feq(dmatArr[i], dmatLL[i]) def test4ebv(self) : @@ -130,7 +131,7 @@ class TestCase(unittest.TestCase): sMat = rdmmc.GetTanimotoSimMat(lst) - for i in range(n*(n-1)/2) : + for i in range(n*(n-1)//2) : assert feq(sMat[i] + dMat[i], 1.0) def test5sbv(self) : @@ -149,7 +150,7 @@ class TestCase(unittest.TestCase): sMat = rdmmc.GetTanimotoSimMat(lst) - for i in range(n*(n-1)/2) : + for i in range(n*(n-1)//2) : assert feq(sMat[i] + dMat[i], 1.0) if __name__ == '__main__': diff --git a/Code/DataStructs/Wrap/DataStructs.cpp b/Code/DataStructs/Wrap/DataStructs.cpp index ba7fb9cff..279e2f161 100644 --- a/Code/DataStructs/Wrap/DataStructs.cpp +++ b/Code/DataStructs/Wrap/DataStructs.cpp @@ -18,7 +18,8 @@ #include #include #include - +#include +#include namespace python = boost::python; @@ -52,7 +53,7 @@ void convertToNumpyArray(const T &v,python::object destArray){ BOOST_PYTHON_MODULE(cDataStructs) { - import_array(); + rdkit_import_array(); python::scope().attr("__doc__") = "Module containing an assortment of functionality for basic data structures.\n" "\n" diff --git a/Code/DataStructs/Wrap/testBV.py b/Code/DataStructs/Wrap/testBV.py index b1f9eee0e..8e1e94e88 100755 --- a/Code/DataStructs/Wrap/testBV.py +++ b/Code/DataStructs/Wrap/testBV.py @@ -1,7 +1,7 @@ from rdkit import DataStructs from rdkit import RDConfig import unittest -import cPickle as pickle +from rdkit.six.moves import cPickle as pickle import random import numpy @@ -25,11 +25,11 @@ class TestCase(unittest.TestCase): for i in range(1000) : assert bv1.GetBit(i) == bv2.GetBit(i) - self.failUnless(bv1==bv2) + self.assertTrue(bv1==bv2) bv2.SetBit(1) - self.failUnless(bv1!=bv2) + self.assertTrue(bv1!=bv2) bv2.UnSetBit(1) - self.failUnless(bv1==bv2) + self.assertTrue(bv1==bv2) bv2.UnSetBitsFromList(obits) for i in range(1000) : @@ -102,16 +102,16 @@ class TestCase(unittest.TestCase): bv1.SetBit(i) if i < 3*sz/4: bv2.SetBit(i) - self.failUnless(DataStructs.AllProbeBitsMatch(bv1,bv1.ToBinary())) - self.failUnless(DataStructs.AllProbeBitsMatch(bv2,bv1.ToBinary())) - self.failIf(DataStructs.AllProbeBitsMatch(bv1,bv2.ToBinary())) - self.failUnless(DataStructs.AllProbeBitsMatch(bv2,bv2.ToBinary())) + self.assertTrue(DataStructs.AllProbeBitsMatch(bv1,bv1.ToBinary())) + self.assertTrue(DataStructs.AllProbeBitsMatch(bv2,bv1.ToBinary())) + self.assertFalse(DataStructs.AllProbeBitsMatch(bv1,bv2.ToBinary())) + self.assertTrue(DataStructs.AllProbeBitsMatch(bv2,bv2.ToBinary())) def test5FromBitString(self): s1 = '1010' bv = DataStructs.CreateFromBitString(s1) - self.failUnless(len(bv)==4) - self.failUnless(list(bv.GetOnBits())==[0,2]) + self.assertTrue(len(bv)==4) + self.assertTrue(list(bv.GetOnBits())==[0,2]) def test6BulkOps(self): nbits = 10000 @@ -125,41 +125,41 @@ class TestCase(unittest.TestCase): sims = DataStructs.BulkTanimotoSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkDiceSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkAllBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.AllBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkOnBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.OnBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkRogotGoldbergSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.RogotGoldbergSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,1,1) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],1,1) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,.5,.5) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],.5,.5) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) def test7FPS(self): bv = DataStructs.ExplicitBitVect(32) @@ -169,14 +169,14 @@ class TestCase(unittest.TestCase): bv.SetBit(23) bv.SetBit(31) - self.failUnlessEqual(DataStructs.BitVectToFPSText(bv),"03008280") + self.assertEqual(DataStructs.BitVectToFPSText(bv),"03008280") bv2 = DataStructs.CreateFromFPSText("03008280") - self.failUnlessEqual(bv,bv2) + self.assertEqual(bv,bv2) - self.failUnlessRaises(ValueError,lambda : DataStructs.CreateFromFPSText("030082801")) + self.assertRaises(ValueError,lambda : DataStructs.CreateFromFPSText("030082801")) bv2 = DataStructs.CreateFromFPSText("") - self.failUnlessEqual(bv2.GetNumBits(),0) + self.assertEqual(bv2.GetNumBits(),0) def test8BinText(self): @@ -188,10 +188,10 @@ class TestCase(unittest.TestCase): bv.SetBit(31) bv2 = DataStructs.CreateFromBinaryText(DataStructs.BitVectToBinaryText(bv)) - self.failUnlessEqual(bv,bv2) + self.assertEqual(bv,bv2) bv2 = DataStructs.CreateFromBinaryText("") - self.failUnlessEqual(bv2.GetNumBits(),0) + self.assertEqual(bv2.GetNumBits(),0) def test9ToNumpy(self): import numpy @@ -204,7 +204,7 @@ class TestCase(unittest.TestCase): arr = numpy.zeros((3,),'i') DataStructs.ConvertToNumpyArray(bv,arr) for i in range(bv.GetNumBits()): - self.failUnlessEqual(bv[i],arr[i]) + self.assertEqual(bv[i],arr[i]) def test10BulkOps2(self): nbits = 10000 @@ -219,41 +219,41 @@ class TestCase(unittest.TestCase): sims = DataStructs.BulkTanimotoSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkDiceSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkAllBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.AllBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkOnBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.OnBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkRogotGoldbergSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.RogotGoldbergSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,1,1) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],1,1) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,.5,.5) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],.5,.5) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) def test10BulkOps3(self): nbits = 10000 @@ -267,41 +267,41 @@ class TestCase(unittest.TestCase): sims = DataStructs.BulkTanimotoSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkDiceSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkAllBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.AllBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkOnBitSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.OnBitSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkRogotGoldbergSimilarity(bvs[0],bvs) for i in range(len(bvs)): sim = DataStructs.RogotGoldbergSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,1,1) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],1,1) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.TanimotoSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sims = DataStructs.BulkTverskySimilarity(bvs[0],bvs,.5,.5) for i in range(len(bvs)): sim = DataStructs.TverskySimilarity(bvs[0],bvs[i],.5,.5) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) sim = DataStructs.DiceSimilarity(bvs[0],bvs[i]) - self.failUnless(feq(sim,sims[i])) + self.assertTrue(feq(sim,sims[i])) if __name__ == '__main__': diff --git a/Code/DataStructs/Wrap/testDiscreteValueVect.py b/Code/DataStructs/Wrap/testDiscreteValueVect.py index 5d3f19261..7791a74b5 100644 --- a/Code/DataStructs/Wrap/testDiscreteValueVect.py +++ b/Code/DataStructs/Wrap/testDiscreteValueVect.py @@ -4,9 +4,12 @@ # # @@ All Rights Reserved @@ # -from rdkit import RDConfig -import os,sys,cPickle +import os +import sys import unittest + +from rdkit import RDConfig +from rdkit.six.moves import cPickle from rdkit import DataStructs as ds class TestCase(unittest.TestCase): @@ -18,66 +21,66 @@ class TestCase(unittest.TestCase): for i in range(15): v1[2*i] = 1; - self.failUnless(len(v1) == 30) - self.failUnless(v1.GetTotalVal() == 15) + self.assertTrue(len(v1) == 30) + self.assertTrue(v1.GetTotalVal() == 15) for i in range(len(v1)): - self.failUnless(v1[i] == (i+1)%2) + self.assertTrue(v1[i] == (i+1)%2) - self.failUnlessRaises(ValueError, lambda : v1.__setitem__(5, 2)) + self.assertRaises(ValueError, lambda : v1.__setitem__(5, 2)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) for i in range(len(v1)): v1[i] = i%4; - self.failUnless(len(v1) == 30) + self.assertTrue(len(v1) == 30) for i in range(len(v1)): - self.failUnless(v1[i] == i%4) + self.assertTrue(v1[i] == i%4) - self.failUnlessRaises(ValueError, lambda : v1.__setitem__(10, 6)) + self.assertRaises(ValueError, lambda : v1.__setitem__(10, 6)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 30) for i in range(len(v1)): v1[i] = i%16; - self.failUnless(len(v1) == 30) - self.failUnless(v1.GetTotalVal() == 211) + self.assertTrue(len(v1) == 30) + self.assertTrue(v1.GetTotalVal() == 211) for i in range(len(v1)): - self.failUnless(v1[i] == i%16) + self.assertTrue(v1[i] == i%16) - self.failUnlessRaises(ValueError, lambda : v1.__setitem__(10, 16)) + self.assertRaises(ValueError, lambda : v1.__setitem__(10, 16)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 32) for i in range(len(v1)): v1[i] = i%256; - self.failUnless(len(v1) == 32) - self.failUnless(v1.GetTotalVal() == 496) + self.assertTrue(len(v1) == 32) + self.assertTrue(v1.GetTotalVal() == 496) for i in range(len(v1)): - self.failUnless(v1[i] == i%256) + self.assertTrue(v1[i] == i%256) - self.failUnlessRaises(ValueError, lambda : v1.__setitem__(10, 256)) + self.assertRaises(ValueError, lambda : v1.__setitem__(10, 256)) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 300) for i in range(len(v1)): v1[i] = i%300; - self.failUnless(len(v1) == 300) - self.failUnless(v1.GetTotalVal() == 44850) - self.failUnlessRaises(ValueError, lambda : v1.__setitem__(10, 65536)) + self.assertTrue(len(v1) == 300) + self.assertTrue(v1.GetTotalVal() == 44850) + self.assertRaises(ValueError, lambda : v1.__setitem__(10, 65536)) def test2VectDistances(self): v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) for i in range(15): v1[2*i] = 1 v2[2*i] = 1 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) for i in range(30): if (i%3 == 0): v2[i] = 1 else: v2[i] = 0 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 15) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 15) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) @@ -86,14 +89,14 @@ class TestCase(unittest.TestCase): v1[i] = i%4 v2[i] = (i+1)%4 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 44) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 44) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) for i in range(16): v1[i] = i%16 v2[i] = i%5 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 90) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 90) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) @@ -108,7 +111,7 @@ class TestCase(unittest.TestCase): v2[2] = 103 v2[3] = 6 v2[4] = 228 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 370) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 370) v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) @@ -119,105 +122,108 @@ class TestCase(unittest.TestCase): v2[0] = 1345 v2[1] = 54578 v2[2] = 10034 - self.failUnless(ds.ComputeL1Norm(v1, v2) == 21000) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 21000) def test3Pickles(self): #outF = file('dvvs.pkl','wb+') - inF = file(os.path.join(RDConfig.RDBaseDir, - 'Code/DataStructs/Wrap/testData/dvvs.pkl'),'rb') - v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) - for i in range(15): - v1[2*i] = 1 - v2 = cPickle.loads(cPickle.dumps(v1)) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - #cPickle.dump(v1,outF) - v2=cPickle.load(inF) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - self.failUnless(v1.GetTotalVal()==v2.GetTotalVal()) - self.failUnless(v2.GetTotalVal()!=0) + with open( + os.path.join(RDConfig.RDBaseDir, + 'Code/DataStructs/Wrap/testData/dvvs.pkl'), + 'rb' + ) as inF: + + v1 = ds.DiscreteValueVect(ds.DiscreteValueType.ONEBITVALUE, 30) + for i in range(15): + v1[2*i] = 1 + v2 = cPickle.loads(cPickle.dumps(v1)) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + #cPickle.dump(v1,outF) + v2=cPickle.load(inF) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(v1.GetTotalVal()==v2.GetTotalVal()) + self.assertTrue(v2.GetTotalVal()!=0) - v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) - for i in range(30): - v1[i] = i%4 - v2 = cPickle.loads(cPickle.dumps(v1)) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - #cPickle.dump(v1,outF) - v2=cPickle.load(inF) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - self.failUnless(v1.GetTotalVal()==v2.GetTotalVal()) - self.failUnless(v2.GetTotalVal()!=0) + v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 30) + for i in range(30): + v1[i] = i%4 + v2 = cPickle.loads(cPickle.dumps(v1)) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + #cPickle.dump(v1,outF) + v2=cPickle.load(inF) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(v1.GetTotalVal()==v2.GetTotalVal()) + self.assertTrue(v2.GetTotalVal()!=0) + + v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) + for i in range(16): + v1[i] = i%16 + v2 = cPickle.loads(cPickle.dumps(v1)) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + #cPickle.dump(v1,outF) + v2=cPickle.load(inF) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(v1.GetTotalVal()==v2.GetTotalVal()) + self.assertTrue(v2.GetTotalVal()!=0) - v1 = ds.DiscreteValueVect(ds.DiscreteValueType.FOURBITVALUE, 16) - for i in range(16): - v1[i] = i%16 - v2 = cPickle.loads(cPickle.dumps(v1)) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - #cPickle.dump(v1,outF) - v2=cPickle.load(inF) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - self.failUnless(v1.GetTotalVal()==v2.GetTotalVal()) - self.failUnless(v2.GetTotalVal()!=0) + v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) + v1[0] = 34 + v1[1] = 167 + v1[2] = 3 + v1[3] = 56 + v1[4] = 128 + v2 = cPickle.loads(cPickle.dumps(v1)) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + #cPickle.dump(v1,outF) + v2=cPickle.load(inF) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(v1.GetTotalVal()==v2.GetTotalVal()) + self.assertTrue(v2.GetTotalVal()!=0) - v1 = ds.DiscreteValueVect(ds.DiscreteValueType.EIGHTBITVALUE, 5) - v1[0] = 34 - v1[1] = 167 - v1[2] = 3 - v1[3] = 56 - v1[4] = 128 - v2 = cPickle.loads(cPickle.dumps(v1)) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - #cPickle.dump(v1,outF) - v2=cPickle.load(inF) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - self.failUnless(v1.GetTotalVal()==v2.GetTotalVal()) - self.failUnless(v2.GetTotalVal()!=0) - - - v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) - v1[0] = 2345 - v1[1] = 64578 - v1[2] = 34 - v2 = cPickle.loads(cPickle.dumps(v1)) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - #cPickle.dump(v1,outF) - v2=cPickle.load(inF) - self.failUnless(ds.ComputeL1Norm(v1, v2) == 0) - self.failUnless(v1.GetTotalVal()==v2.GetTotalVal()) - self.failUnless(v2.GetTotalVal()!=0) + v1 = ds.DiscreteValueVect(ds.DiscreteValueType.SIXTEENBITVALUE, 3) + v1[0] = 2345 + v1[1] = 64578 + v1[2] = 34 + v2 = cPickle.loads(cPickle.dumps(v1)) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + #cPickle.dump(v1,outF) + v2=cPickle.load(inF) + self.assertTrue(ds.ComputeL1Norm(v1, v2) == 0) + self.assertTrue(v1.GetTotalVal()==v2.GetTotalVal()) + self.assertTrue(v2.GetTotalVal()!=0) def test4DiscreteVectOps(self): v1 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 8) for i in range(4): v1[2*i] = 2 - self.failUnless(v1.GetTotalVal()==8) + self.assertTrue(v1.GetTotalVal()==8) v2 = ds.DiscreteValueVect(ds.DiscreteValueType.TWOBITVALUE, 8) for i in range(4): v2[2*i+1] = 2 v2[2*i] = 1 - self.failUnless(v2.GetTotalVal()==12) + self.assertTrue(v2.GetTotalVal()==12) v3 = v1|v2 - self.failUnless(len(v3)==len(v2)) - self.failUnless(v3.GetTotalVal()==16) + self.assertTrue(len(v3)==len(v2)) + self.assertTrue(v3.GetTotalVal()==16) v3 = v1&v2 - self.failUnless(len(v3)==len(v2)) - self.failUnless(v3.GetTotalVal()==4) + self.assertTrue(len(v3)==len(v2)) + self.assertTrue(v3.GetTotalVal()==4) v4 = v1+v2 - self.failUnless(len(v4)==len(v2)) - self.failUnless(v4.GetTotalVal()==20) + self.assertTrue(len(v4)==len(v2)) + self.assertTrue(v4.GetTotalVal()==20) v4 = v1-v2 - self.failUnless(v4.GetTotalVal()==4) + self.assertTrue(v4.GetTotalVal()==4) v4 = v2-v1 - self.failUnless(v4.GetTotalVal()==8) + self.assertTrue(v4.GetTotalVal()==8) v4 = v2 v4 -= v1 - self.failUnless(v4.GetTotalVal()==8) + self.assertTrue(v4.GetTotalVal()==8) v4 -= v4 - self.failUnless(v4.GetTotalVal()==0) + self.assertTrue(v4.GetTotalVal()==0) def testIterator(self): """ @@ -228,10 +234,10 @@ class TestCase(unittest.TestCase): for i in range(15): v1[2*i] = 1; l1 = list(v1) - self.failUnless(len(l1)==len(v1)) + self.assertTrue(len(l1)==len(v1)) for i,v in enumerate(v1): - self.failUnless(l1[i]==v) - self.failUnlessRaises(IndexError,lambda :v1[40]) + self.assertTrue(l1[i]==v) + self.assertRaises(IndexError,lambda :v1[40]) def test9ToNumpy(self): import numpy @@ -244,7 +250,7 @@ class TestCase(unittest.TestCase): arr = numpy.zeros((3,),'i') ds.ConvertToNumpyArray(bv,arr) for i in range(len(bv)): - self.failUnlessEqual(bv[i],arr[i]) + self.assertEqual(bv[i],arr[i]) diff --git a/Code/DataStructs/Wrap/testSparseIntVect.py b/Code/DataStructs/Wrap/testSparseIntVect.py index 303389f1b..b793aacb5 100644 --- a/Code/DataStructs/Wrap/testSparseIntVect.py +++ b/Code/DataStructs/Wrap/testSparseIntVect.py @@ -4,9 +4,10 @@ # # @@ All Rights Reserved @@ # -from rdkit import RDConfig -import os,sys,cPickle +import os,sys import unittest +from rdkit.six.moves import cPickle +from rdkit import RDConfig from rdkit import DataStructs as ds def feq(v1,v2,tol=1e-4): @@ -20,111 +21,119 @@ class TestCase(unittest.TestCase): """ v1 = ds.IntSparseIntVect(5) - self.failUnlessRaises(IndexError,lambda:v1[5]) + self.assertRaises(IndexError,lambda:v1[5]) v1[0]=1 v1[2]=2 v1[3]=3 - self.failUnless(v1==v1) - self.failUnless(v1.GetLength()==5) + self.assertTrue(v1==v1) + self.assertTrue(v1.GetLength()==5) v2= ds.IntSparseIntVect(5) - self.failUnless(v1!=v2) + self.assertTrue(v1!=v2) v2|=v1 - self.failUnless(v2==v1) + self.assertTrue(v2==v1) v3=v2|v1 - self.failUnless(v3==v1) + self.assertTrue(v3==v1) onVs = v1.GetNonzeroElements() - self.failUnless(onVs=={0:1,2:2,3:3}) + self.assertTrue(onVs=={0:1,2:2,3:3}) def test2Long(self): """ """ - l=1L<<42 + l=1<<42 v1 = ds.LongSparseIntVect(l) - self.failUnlessRaises(IndexError,lambda:v1[l]) + self.assertRaises(IndexError,lambda:v1[l]) v1[0]=1 v1[2]=2 - v1[1L<<35]=3 - self.failUnless(v1==v1) - self.failUnless(v1.GetLength()==l) + v1[1<<35]=3 + self.assertTrue(v1==v1) + self.assertTrue(v1.GetLength()==l) v2= ds.LongSparseIntVect(l) - self.failUnless(v1!=v2) + self.assertTrue(v1!=v2) v2|=v1 - self.failUnless(v2==v1) + self.assertTrue(v2==v1) v3=v2|v1 - self.failUnless(v3==v1) + self.assertTrue(v3==v1) onVs = v1.GetNonzeroElements() - self.failUnless(onVs=={0L:1,2L:2,1L<<35:3}) + self.assertTrue(onVs=={0:1,2:2,1<<35:3}) def test3Pickle1(self): """ """ - l=1L<<42 + l=1<<42 v1 = ds.LongSparseIntVect(l) - self.failUnlessRaises(IndexError,lambda:v1[l+1]) + self.assertRaises(IndexError,lambda:v1[l+1]) v1[0]=1 v1[2]=2 - v1[1L<<35]=3 - self.failUnless(v1==v1) + v1[1<<35]=3 + self.assertTrue(v1==v1) v2= cPickle.loads(cPickle.dumps(v1)) - self.failUnless(v2==v1) + self.assertTrue(v2==v1) v3= ds.LongSparseIntVect(v2.ToBinary()) - self.failUnless(v2==v3) - self.failUnless(v1==v3) + self.assertTrue(v2==v3) + self.assertTrue(v1==v3) #cPickle.dump(v1,file('lsiv.pkl','wb+')) - v3 = cPickle.load(file(os.path.join(RDConfig.RDBaseDir, - 'Code/DataStructs/Wrap/testData/lsiv.pkl'),'rb')) - self.failUnless(v3==v1) + with open( + os.path.join(RDConfig.RDBaseDir, + 'Code/DataStructs/Wrap/testData/lsiv.pkl'), + 'rb' + ) as f: + v3 = cPickle.load(f) + self.assertTrue(v3==v1) def test3Pickle2(self): """ """ - l=1L<<21 + l=1<<21 v1 = ds.IntSparseIntVect(l) - self.failUnlessRaises(IndexError,lambda:v1[l+1]) + self.assertRaises(IndexError,lambda:v1[l+1]) v1[0]=1 v1[2]=2 v1[1<<12]=3 - self.failUnless(v1==v1) + self.assertTrue(v1==v1) v2= cPickle.loads(cPickle.dumps(v1)) - self.failUnless(v2==v1) + self.assertTrue(v2==v1) v3= ds.IntSparseIntVect(v2.ToBinary()) - self.failUnless(v2==v3) - self.failUnless(v1==v3) + self.assertTrue(v2==v3) + self.assertTrue(v1==v3) #cPickle.dump(v1,file('isiv.pkl','wb+')) - v3 = cPickle.load(file(os.path.join(RDConfig.RDBaseDir, - 'Code/DataStructs/Wrap/testData/isiv.pkl'),'rb')) - self.failUnless(v3==v1) + with open( + os.path.join(RDConfig.RDBaseDir, + 'Code/DataStructs/Wrap/testData/isiv.pkl'), + 'rb' + ) as f: + v3 = cPickle.load(f) + self.assertTrue(v3==v1) def test4Update(self): """ """ v1 = ds.IntSparseIntVect(5) - self.failUnlessRaises(IndexError,lambda:v1[6]) + self.assertRaises(IndexError,lambda:v1[6]) v1[0]=1 v1[2]=2 v1[3]=3 - self.failUnless(v1==v1) + self.assertTrue(v1==v1) v2 = ds.IntSparseIntVect(5) v2.UpdateFromSequence((0,2,3,3,2,3)) - self.failUnless(v1==v2) + self.assertTrue(v1==v2) def test5Dice(self): """ @@ -134,7 +143,7 @@ class TestCase(unittest.TestCase): v1[4]=4; v1[0]=2; v1[3]=1; - self.failUnless(feq(ds.DiceSimilarity(v1,v1),1.0)) + self.assertTrue(feq(ds.DiceSimilarity(v1,v1),1.0)) v1 = ds.IntSparseIntVect(5) v1[0]=2; @@ -146,8 +155,8 @@ class TestCase(unittest.TestCase): v2[2]=3; v2[3]=4; v2[4]=4; - self.failUnless(feq(ds.DiceSimilarity(v1,v2),18.0/26.)) - self.failUnless(feq(ds.DiceSimilarity(v2,v1),18.0/26.)) + self.assertTrue(feq(ds.DiceSimilarity(v1,v2),18.0/26.)) + self.assertTrue(feq(ds.DiceSimilarity(v2,v1),18.0/26.)) def test6BulkDice(self): """ @@ -167,7 +176,7 @@ class TestCase(unittest.TestCase): baseDs = [ds.DiceSimilarity(vs[0],vs[x]) for x in range(1,nVs)] bulkDs = ds.BulkDiceSimilarity(vs[0],vs[1:]) for i in range(len(baseDs)): - self.failUnless(feq(baseDs[i],bulkDs[i])) + self.assertTrue(feq(baseDs[i],bulkDs[i])) def test6BulkTversky(self): """ @@ -188,16 +197,16 @@ class TestCase(unittest.TestCase): bulkDs = ds.BulkTverskySimilarity(vs[0],vs[1:],0.5,0.5) diceDs = [ds.DiceSimilarity(vs[0],vs[x]) for x in range(1,nVs)] for i in range(len(baseDs)): - self.failUnless(feq(baseDs[i],bulkDs[i])) - self.failUnless(feq(baseDs[i],diceDs[i])) + self.assertTrue(feq(baseDs[i],bulkDs[i])) + self.assertTrue(feq(baseDs[i],diceDs[i])) bulkDs = ds.BulkTverskySimilarity(vs[0],vs[1:],1.0,1.0) taniDs = [ds.TanimotoSimilarity(vs[0],vs[x]) for x in range(1,nVs)] for i in range(len(bulkDs)): - self.failUnless(feq(bulkDs[i],taniDs[i])) + self.assertTrue(feq(bulkDs[i],taniDs[i])) taniDs = ds.BulkTanimotoSimilarity(vs[0],vs[1:]) for i in range(len(bulkDs)): - self.failUnless(feq(bulkDs[i],taniDs[i])) + self.assertTrue(feq(bulkDs[i],taniDs[i])) if __name__ == '__main__': diff --git a/Code/DistGeom/Wrap/DistGeom.cpp b/Code/DistGeom/Wrap/DistGeom.cpp index da3d2e372..c3fd0b513 100644 --- a/Code/DistGeom/Wrap/DistGeom.cpp +++ b/Code/DistGeom/Wrap/DistGeom.cpp @@ -14,6 +14,8 @@ #define PY_ARRAY_UNIQUE_SYMBOL DistGeom_array_API #include "numpy/arrayobject.h" #include +#include +#include #include #include @@ -169,7 +171,7 @@ BOOST_PYTHON_MODULE(DistGeom) { "Module containing functions for basic distance geometry operations" ; - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_value_error); std::string docString; diff --git a/Code/DistGeom/Wrap/rough_test.py b/Code/DistGeom/Wrap/rough_test.py index 4a50b7a39..9d272b220 100644 --- a/Code/DistGeom/Wrap/rough_test.py +++ b/Code/DistGeom/Wrap/rough_test.py @@ -22,50 +22,50 @@ class TestCase(unittest.TestCase): arr = Numeric.array([[0,1.0,5.0], [1.0,0,1.0], [0.0,1.0,0]],Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) - self.failUnless(feq(arr[0,2],2.0)) - self.failUnless(feq(arr[2,0],0.0)) - self.failUnless(feq(arr[0,1],1.0)) - self.failUnless(feq(arr[1,0],1.0)) - self.failUnless(feq(arr[1,2],1.0)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) + self.assertTrue(feq(arr[0,2],2.0)) + self.assertTrue(feq(arr[2,0],0.0)) + self.assertTrue(feq(arr[0,1],1.0)) + self.assertTrue(feq(arr[1,0],1.0)) + self.assertTrue(feq(arr[1,2],1.0)) def test2SmoothFail(self): arr = Numeric.array([[0,1.0,5.0], [1.0,0,1.0], [3.0,1.0,0]],Numeric.Float) - self.failIf(DG.DoTriangleSmoothing(arr)) + self.assertFalse(DG.DoTriangleSmoothing(arr)) def test3SmoothPass(self): arr = Numeric.array([[0,1.1,5.0], [0.9,0,1.1], [0.0,0.9,0]],Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) - self.failUnless(feq(arr[0,2],2.2)) - self.failUnless(feq(arr[2,0],0.0)) - self.failUnless(feq(arr[0,1],1.1)) - self.failUnless(feq(arr[1,0],0.9)) - self.failUnless(feq(arr[1,2],1.1)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) + self.assertTrue(feq(arr[0,2],2.2)) + self.assertTrue(feq(arr[2,0],0.0)) + self.assertTrue(feq(arr[0,1],1.1)) + self.assertTrue(feq(arr[1,0],0.9)) + self.assertTrue(feq(arr[1,2],1.1)) def test4Embed(self): arr = Numeric.array([[0,1.0,5.0], [1.0,0,1.0], [0.0,1.0,0]],Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) coords = DG.EmbedBoundsMatrix(arr,randomSeed=100); v1 = coords[0]-coords[1] v2 = coords[1]-coords[2] d1 = Numeric.dot(v1,v1) - self.failUnless(feq(d1,1.0, 0.001)); + self.assertTrue(feq(d1,1.0, 0.001)); d2 = Numeric.dot(v2,v2) - self.failUnless(feq(d2,1.0, 0.001)); + self.assertTrue(feq(d2,1.0, 0.001)); def test5EmbedFail(self): arr = Numeric.array([[0,1.0,5.0], [1.0,0,1.0], [3.0,1.0,0]],Numeric.Float) - self.failUnlessRaises(ValueError,lambda : DG.EmbedBoundsMatrix(arr)) + self.assertRaises(ValueError,lambda : DG.EmbedBoundsMatrix(arr)) #DG.EmbedBoundsMatrix(arr,randomizeOnFailure=0,randomSeed=1) DG.EmbedBoundsMatrix(arr,randomizeOnFailure=1); @@ -74,28 +74,28 @@ class TestCase(unittest.TestCase): [1.0,0.0,1.0], [0.99,1.0,0.0]], Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) coords = DG.EmbedBoundsMatrix(arr, randomSeed=100) v1 = coords[0]-coords[1] v2 = coords[1]-coords[2] d1 = Numeric.dot(v1,v1) - self.failUnless(feq(d1,1.0,2e-3)); + self.assertTrue(feq(d1,1.0,2e-3)); d2 = Numeric.dot(v2,v2) - self.failUnless(feq(d2,1.0,2e-3)); + self.assertTrue(feq(d2,1.0,2e-3)); arr = Numeric.array([[0.0,1.0,1.0,1.01], [1.0,0.0,1.0,1.0], [1.0,1.0,0.0,1.0], [0.99,1.0,1.0,0.0], ],Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) coords = DG.EmbedBoundsMatrix(arr) v1 = coords[0]-coords[1] v2 = coords[1]-coords[2] d1 = Numeric.dot(v1,v1) - self.failUnless(feq(d1,1.0,1e-3)); + self.assertTrue(feq(d1,1.0,1e-3)); d2 = Numeric.dot(v2,v2) - self.failUnless(feq(d2,1.0,1e-3)); + self.assertTrue(feq(d2,1.0,1e-3)); return # this test is currently (rev:4769) passing on windows and @@ -106,14 +106,14 @@ class TestCase(unittest.TestCase): [1.0,1.0,0.0,1.0], [1.0,1.0,1.0,0.0], ],Numeric.Float) - self.failUnless(DG.DoTriangleSmoothing(arr)) + self.assertTrue(DG.DoTriangleSmoothing(arr)) coords = DG.EmbedBoundsMatrix(arr,randomSeed=100) v1 = coords[0]-coords[1] v2 = coords[1]-coords[2] d1 = Numeric.dot(v1,v1) - self.failUnless(feq(d1,1.0,1e-3)); + self.assertTrue(feq(d1,1.0,1e-3)); d2 = Numeric.dot(v2,v2) - self.failUnless(feq(d2,1.0,1e-3)); + self.assertTrue(feq(d2,1.0,1e-3)); diff --git a/Code/ForceField/Wrap/testConstraints.py b/Code/ForceField/Wrap/testConstraints.py index 2b2cbd7f1..2be15bef5 100644 --- a/Code/ForceField/Wrap/testConstraints.py +++ b/Code/ForceField/Wrap/testConstraints.py @@ -49,171 +49,171 @@ M END""" def testUFFDistanceConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) ff.UFFAddDistanceConstraint(1, 3, False, 2.0, 2.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dist = rdMolTransforms.GetBondLength(conf, 1, 3) - self.failUnless(dist > 1.99) + self.assertTrue(dist > 1.99) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) ff.UFFAddDistanceConstraint(1, 3, True, -0.2, 0.2, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dist = rdMolTransforms.GetBondLength(conf, 1, 3) - self.failUnless(dist > 1.79) + self.assertTrue(dist > 1.79) def testUFFAngleConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) ff.UFFAddAngleConstraint(1, 3, 6, False, 90.0, 90.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() angle = rdMolTransforms.GetAngleDeg(conf, 1, 3, 6) - self.failUnless(int(angle) == 90) + self.assertTrue(int(angle) == 90) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) ff.UFFAddAngleConstraint(1, 3, 6, True, -10.0, 10.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() angle = rdMolTransforms.GetAngleDeg(conf, 1, 3, 6) - self.failUnless(int(angle) == 100) + self.assertTrue(int(angle) == 100) def testUFFTorsionConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() rdMolTransforms.SetDihedralDeg(conf, 1, 3, 6, 8, 60.0); ff.UFFAddTorsionConstraint(1, 3, 6, 8, False, 30.0, 30.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) dihedral = rdMolTransforms.GetDihedralDeg(conf, 1, 3, 6, 8) - self.failUnless(int(dihedral) == 30) + self.assertTrue(int(dihedral) == 30) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) ff.UFFAddTorsionConstraint(1, 3, 6, 8, True, -10.0, 10.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dihedral = rdMolTransforms.GetDihedralDeg(conf, 1, 3, 6, 8) - self.failUnless(int(dihedral) == 40) + self.assertTrue(int(dihedral) == 40) def testUFFPositionConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() p = conf.GetAtomPosition(1) ff.UFFAddPositionConstraint(1, 0.3, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) q = conf.GetAtomPosition(1) - self.failUnless((p - q).Length() < 0.3) + self.assertTrue((p - q).Length() < 0.3) def testUFFFixedAtoms(self) : m = Chem.MolFromMolBlock(self.molB, True, False) ff = ChemicalForceFields.UFFGetMoleculeForceField(m) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() fp = conf.GetAtomPosition(1) ff.AddFixedPoint(1) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) fq = conf.GetAtomPosition(1) - self.failUnless((fp - fq).Length() < 0.01) + self.assertTrue((fp - fq).Length() < 0.01) def testMMFFDistanceConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) mp = ChemicalForceFields.MMFFGetMoleculeProperties(m) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) ff.MMFFAddDistanceConstraint(1, 3, False, 2.0, 2.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dist = rdMolTransforms.GetBondLength(conf, 1, 3) - self.failUnless(dist > 1.99) + self.assertTrue(dist > 1.99) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) ff.MMFFAddDistanceConstraint(1, 3, True, -0.2, 0.2, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dist = rdMolTransforms.GetBondLength(conf, 1, 3) - self.failUnless(dist > 1.79) + self.assertTrue(dist > 1.79) def testMMFFAngleConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) mp = ChemicalForceFields.MMFFGetMoleculeProperties(m) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) ff.MMFFAddAngleConstraint(1, 3, 6, False, 90.0, 90.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() angle = rdMolTransforms.GetAngleDeg(conf, 1, 3, 6) - self.failUnless(int(angle) == 90) + self.assertTrue(int(angle) == 90) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) ff.MMFFAddAngleConstraint(1, 3, 6, True, -10.0, 10.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() angle = rdMolTransforms.GetAngleDeg(conf, 1, 3, 6) - self.failUnless(int(angle) == 100) + self.assertTrue(int(angle) == 100) def testMMFFTorsionConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) mp = ChemicalForceFields.MMFFGetMoleculeProperties(m) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() rdMolTransforms.SetDihedralDeg(conf, 1, 3, 6, 8, 60.0); ff.MMFFAddTorsionConstraint(1, 3, 6, 8, False, 30.0, 30.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) dihedral = rdMolTransforms.GetDihedralDeg(conf, 1, 3, 6, 8) - self.failUnless(int(dihedral) == 30) + self.assertTrue(int(dihedral) == 30) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) ff.MMFFAddTorsionConstraint(1, 3, 6, 8, True, -10.0, 10.0, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) conf = m.GetConformer() dihedral = rdMolTransforms.GetDihedralDeg(conf, 1, 3, 6, 8) - self.failUnless(int(dihedral) == 40) + self.assertTrue(int(dihedral) == 40) def testMMFFPositionConstraints(self) : m = Chem.MolFromMolBlock(self.molB, True, False) mp = ChemicalForceFields.MMFFGetMoleculeProperties(m) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() p = conf.GetAtomPosition(1) ff.MMFFAddPositionConstraint(1, 0.3, 1.0e5) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) q = conf.GetAtomPosition(1) - self.failUnless((p - q).Length() < 0.3) + self.assertTrue((p - q).Length() < 0.3) def testMMFFFixedAtoms(self) : m = Chem.MolFromMolBlock(self.molB, True, False) mp = ChemicalForceFields.MMFFGetMoleculeProperties(m) ff = ChemicalForceFields.MMFFGetMoleculeForceField(m, mp) - self.failUnless(ff) + self.assertTrue(ff) conf = m.GetConformer() fp = conf.GetAtomPosition(1) ff.AddFixedPoint(1) r = ff.Minimize() - self.failUnless(r == 0) + self.assertTrue(r == 0) fq = conf.GetAtomPosition(1) - self.failUnless((fp - fq).Length() < 0.01) + self.assertTrue((fp - fq).Length() < 0.01) diff --git a/Code/Geometry/Wrap/testGeometry.py b/Code/Geometry/Wrap/testGeometry.py index 4e33983ae..602ed27ee 100644 --- a/Code/Geometry/Wrap/testGeometry.py +++ b/Code/Geometry/Wrap/testGeometry.py @@ -1,10 +1,14 @@ -from rdkit import RDConfig +from __future__ import print_function import os,sys import unittest +import copy +import math + +from rdkit.six.moves import cPickle + +from rdkit import RDConfig from rdkit import DataStructs from rdkit.Geometry import rdGeometry as geom -import cPickle,copy -import math def feq(v1, v2, tol=1.0e-4): return abs(v1-v2) < tol @@ -15,150 +19,150 @@ class TestCase(unittest.TestCase): def test1aPoint3D(self): pt = geom.Point3D(); - self.failUnless(feq(pt.x, 0.0)) - self.failUnless(feq(pt.y, 0.0)) - self.failUnless(feq(pt.z, 0.0)) + self.assertTrue(feq(pt.x, 0.0)) + self.assertTrue(feq(pt.y, 0.0)) + self.assertTrue(feq(pt.z, 0.0)) pt = geom.Point3D(3., 4., 5.) - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) - self.failUnless(feq(pt.z, 5.0)) - self.failUnless(feq(pt[0], 3.0)) - self.failUnless(feq(pt[1], 4.0)) - self.failUnless(feq(pt[2], 5.0)) - self.failUnless(feq(pt[-3], 3.0)) - self.failUnless(feq(pt[-2], 4.0)) - self.failUnless(feq(pt[-1], 5.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.z, 5.0)) + self.assertTrue(feq(pt[0], 3.0)) + self.assertTrue(feq(pt[1], 4.0)) + self.assertTrue(feq(pt[2], 5.0)) + self.assertTrue(feq(pt[-3], 3.0)) + self.assertTrue(feq(pt[-2], 4.0)) + self.assertTrue(feq(pt[-1], 5.0)) lst = list(pt) - self.failUnless(feq(lst[0], 3.0)) - self.failUnless(feq(lst[1], 4.0)) - self.failUnless(feq(lst[2], 5.0)) + self.assertTrue(feq(lst[0], 3.0)) + self.assertTrue(feq(lst[1], 4.0)) + self.assertTrue(feq(lst[2], 5.0)) pt2 = geom.Point3D(1., 1., 1.) pt3 = pt+pt2 - self.failUnless(feq(pt3.x, 4.0)) - self.failUnless(feq(pt3.y, 5.0)) - self.failUnless(feq(pt3.z, 6.0)) + self.assertTrue(feq(pt3.x, 4.0)) + self.assertTrue(feq(pt3.y, 5.0)) + self.assertTrue(feq(pt3.z, 6.0)) pt += pt2 - self.failUnless(feq(pt.x, 4.0)) - self.failUnless(feq(pt.y, 5.0)) - self.failUnless(feq(pt.z, 6.0)) + self.assertTrue(feq(pt.x, 4.0)) + self.assertTrue(feq(pt.y, 5.0)) + self.assertTrue(feq(pt.z, 6.0)) pt3 = pt-pt2 - self.failUnless(feq(pt3.x, 3.0)) - self.failUnless(feq(pt3.y, 4.0)) - self.failUnless(feq(pt3.z, 5.0)) + self.assertTrue(feq(pt3.x, 3.0)) + self.assertTrue(feq(pt3.y, 4.0)) + self.assertTrue(feq(pt3.z, 5.0)) pt -= pt2 - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) - self.failUnless(feq(pt.z, 5.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.z, 5.0)) pt *= 2.0 - self.failUnless(feq(pt.x, 6.0)) - self.failUnless(feq(pt.y, 8.0)) - self.failUnless(feq(pt.z, 10.0)) + self.assertTrue(feq(pt.x, 6.0)) + self.assertTrue(feq(pt.y, 8.0)) + self.assertTrue(feq(pt.z, 10.0)) pt /= 2 - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) - self.failUnless(feq(pt.z, 5.0)) - self.failUnless(feq(pt.Length(), 7.0711)) - self.failUnless(feq(pt.LengthSq(), 50.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.z, 5.0)) + self.assertTrue(feq(pt.Length(), 7.0711)) + self.assertTrue(feq(pt.LengthSq(), 50.0)) pt.Normalize() - self.failUnless(feq(pt.Length(), 1.0)) + self.assertTrue(feq(pt.Length(), 1.0)) pt1 = geom.Point3D(1.0, 0.0, 0.0) pt2 = geom.Point3D(2.0*math.cos(math.pi/6), 2.0*math.sin(math.pi/6), 0.0) ang = pt1.AngleTo(pt2) - self.failUnless(feq(ang, math.pi/6)) + self.assertTrue(feq(ang, math.pi/6)) prod = pt1.DotProduct(pt2) - self.failUnless(feq(prod, 2.0*math.cos(math.pi/6))) + self.assertTrue(feq(prod, 2.0*math.cos(math.pi/6))) pt3 = pt1.CrossProduct(pt2) - self.failUnless(feq(pt3.x, 0.0)) - self.failUnless(feq(pt3.y, 0.0)) - self.failUnless(feq(pt3.z, 1.0)) + self.assertTrue(feq(pt3.x, 0.0)) + self.assertTrue(feq(pt3.y, 0.0)) + self.assertTrue(feq(pt3.z, 1.0)) def test1bPoint2D(self): pt = geom.Point2D(); - self.failUnless(feq(pt.x, 0.0)) - self.failUnless(feq(pt.y, 0.0)) + self.assertTrue(feq(pt.x, 0.0)) + self.assertTrue(feq(pt.y, 0.0)) pt = geom.Point2D(3., 4.) - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) - self.failUnless(feq(pt[0], 3.0)) - self.failUnless(feq(pt[1], 4.0)) - self.failUnless(feq(pt[-2], 3.0)) - self.failUnless(feq(pt[-1], 4.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) + self.assertTrue(feq(pt[0], 3.0)) + self.assertTrue(feq(pt[1], 4.0)) + self.assertTrue(feq(pt[-2], 3.0)) + self.assertTrue(feq(pt[-1], 4.0)) lst = list(pt) - self.failUnless(feq(lst[0], 3.0)) - self.failUnless(feq(lst[1], 4.0)) + self.assertTrue(feq(lst[0], 3.0)) + self.assertTrue(feq(lst[1], 4.0)) pt2 = geom.Point2D(1., 1.) pt3 = pt+pt2 - self.failUnless(feq(pt3.x, 4.0)) - self.failUnless(feq(pt3.y, 5.0)) + self.assertTrue(feq(pt3.x, 4.0)) + self.assertTrue(feq(pt3.y, 5.0)) pt += pt2 - self.failUnless(feq(pt.x, 4.0)) - self.failUnless(feq(pt.y, 5.0)) + self.assertTrue(feq(pt.x, 4.0)) + self.assertTrue(feq(pt.y, 5.0)) pt3 = pt-pt2 - self.failUnless(feq(pt3.x, 3.0)) - self.failUnless(feq(pt3.y, 4.0)) + self.assertTrue(feq(pt3.x, 3.0)) + self.assertTrue(feq(pt3.y, 4.0)) pt -= pt2 - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) pt *= 2.0 - self.failUnless(feq(pt.x, 6.0)) - self.failUnless(feq(pt.y, 8.0)) + self.assertTrue(feq(pt.x, 6.0)) + self.assertTrue(feq(pt.y, 8.0)) pt /= 2 - self.failUnless(feq(pt.x, 3.0)) - self.failUnless(feq(pt.y, 4.0)) - self.failUnless(feq(pt.Length(), 5.0)) - self.failUnless(feq(pt.LengthSq(), 25.0)) + self.assertTrue(feq(pt.x, 3.0)) + self.assertTrue(feq(pt.y, 4.0)) + self.assertTrue(feq(pt.Length(), 5.0)) + self.assertTrue(feq(pt.LengthSq(), 25.0)) pt.Normalize() - self.failUnless(feq(pt.Length(), 1.0)) + self.assertTrue(feq(pt.Length(), 1.0)) pt1 = geom.Point2D(1.0, 0.0) pt2 = geom.Point2D(2.0*math.cos(math.pi/6), 2.0*math.sin(math.pi/6)) ang = pt1.AngleTo(pt2) - self.failUnless(feq(ang, math.pi/6)) + self.assertTrue(feq(ang, math.pi/6)) prod = pt1.DotProduct(pt2) - self.failUnless(feq(prod, 2.0*math.cos(math.pi/6))) + self.assertTrue(feq(prod, 2.0*math.cos(math.pi/6))) def test1cPointND(self): dim=4 pt = geom.PointND(4); for i in range(dim): - self.failUnless(feq(pt[i], 0.0)) + self.assertTrue(feq(pt[i], 0.0)) pt[0]=3 pt[3]=4 - self.failUnless(feq(pt[0], 3.0)) - self.failUnless(feq(pt[3], 4.0)) - self.failUnless(feq(pt[-4], 3.0)) - self.failUnless(feq(pt[-1], 4.0)) + self.assertTrue(feq(pt[0], 3.0)) + self.assertTrue(feq(pt[3], 4.0)) + self.assertTrue(feq(pt[-4], 3.0)) + self.assertTrue(feq(pt[-1], 4.0)) lst = list(pt) - self.failUnless(feq(lst[0], 3.0)) - self.failUnless(feq(lst[3], 4.0)) + self.assertTrue(feq(lst[0], 3.0)) + self.assertTrue(feq(lst[3], 4.0)) pt2 = geom.PointND(4) @@ -166,58 +170,58 @@ class TestCase(unittest.TestCase): pt2[2]=1. pt3 = pt+pt2 - self.failUnless(feq(pt3[0], 4.0)) - self.failUnless(feq(pt3[2], 1.0)) - self.failUnless(feq(pt3[3], 4.0)) + self.assertTrue(feq(pt3[0], 4.0)) + self.assertTrue(feq(pt3[2], 1.0)) + self.assertTrue(feq(pt3[3], 4.0)) pt += pt2 - self.failUnless(feq(pt[0], 4.0)) - self.failUnless(feq(pt[2], 1.0)) - self.failUnless(feq(pt[3], 4.0)) + self.assertTrue(feq(pt[0], 4.0)) + self.assertTrue(feq(pt[2], 1.0)) + self.assertTrue(feq(pt[3], 4.0)) pt3 = pt-pt2 - self.failUnless(feq(pt3[0], 3.0)) - self.failUnless(feq(pt3[2], 0.0)) - self.failUnless(feq(pt3[3], 4.0)) + self.assertTrue(feq(pt3[0], 3.0)) + self.assertTrue(feq(pt3[2], 0.0)) + self.assertTrue(feq(pt3[3], 4.0)) pt -= pt2 - self.failUnless(feq(pt[0], 3.0)) - self.failUnless(feq(pt[2], 0.0)) - self.failUnless(feq(pt[3], 4.0)) + self.assertTrue(feq(pt[0], 3.0)) + self.assertTrue(feq(pt[2], 0.0)) + self.assertTrue(feq(pt[3], 4.0)) pt *= 2.0 - self.failUnless(feq(pt[0], 6.0)) - self.failUnless(feq(pt[1], 0.0)) - self.failUnless(feq(pt[2], 0.0)) - self.failUnless(feq(pt[3], 8.0)) + self.assertTrue(feq(pt[0], 6.0)) + self.assertTrue(feq(pt[1], 0.0)) + self.assertTrue(feq(pt[2], 0.0)) + self.assertTrue(feq(pt[3], 8.0)) pt /= 2 - self.failUnless(feq(pt[0], 3.0)) - self.failUnless(feq(pt[1], 0.0)) - self.failUnless(feq(pt[2], 0.0)) - self.failUnless(feq(pt[3], 4.0)) + self.assertTrue(feq(pt[0], 3.0)) + self.assertTrue(feq(pt[1], 0.0)) + self.assertTrue(feq(pt[2], 0.0)) + self.assertTrue(feq(pt[3], 4.0)) - self.failUnless(feq(pt.Length(), 5.0)) - self.failUnless(feq(pt.LengthSq(), 25.0)) + self.assertTrue(feq(pt.Length(), 5.0)) + self.assertTrue(feq(pt.LengthSq(), 25.0)) pt.Normalize() - self.failUnless(feq(pt.Length(), 1.0)) + self.assertTrue(feq(pt.Length(), 1.0)) pkl = cPickle.dumps(pt) pt2 = cPickle.loads(pkl) - self.failUnless(len(pt)==len(pt2)) + self.assertTrue(len(pt)==len(pt2)) for i in range(len(pt)): - self.failUnless(feq(pt2[i],pt[i])) + self.assertTrue(feq(pt2[i],pt[i])) def test3UniformGrid(self): ugrid = geom.UniformGrid3D(20, 18, 15) - self.failUnless(ugrid.GetNumX() == 40) - self.failUnless(ugrid.GetNumY() == 36) - self.failUnless(ugrid.GetNumZ() == 30) + self.assertTrue(ugrid.GetNumX() == 40) + self.assertTrue(ugrid.GetNumY() == 36) + self.assertTrue(ugrid.GetNumZ() == 30) dvect = ugrid.GetOccupancyVect() ugrid = geom.UniformGrid3D(20, 18, 15, 0.5, DataStructs.DiscreteValueType.TWOBITVALUE) dvect = ugrid.GetOccupancyVect() - self.failUnless(dvect.GetValueType() == DataStructs.DiscreteValueType.TWOBITVALUE) + self.assertTrue(dvect.GetValueType() == DataStructs.DiscreteValueType.TWOBITVALUE) grd = geom.UniformGrid3D(10.0, 10.0, 10.0, 0.5) grd.SetSphereOccupancy(geom.Point3D(-2.0, -2.0, 0.0), 1.5, 0.25) @@ -232,23 +236,23 @@ class TestCase(unittest.TestCase): grd2.SetSphereOccupancy(geom.Point3D(2.0, -2.0, 0.0), 1.5, 0.25) dist = geom.TanimotoDistance(grd, grd2) - self.failUnless(dist == 0.25) + self.assertTrue(dist == 0.25) dist = geom.ProtrudeDistance(grd, grd2) - self.failUnless(dist == 0.25) + self.assertTrue(dist == 0.25) dist = geom.ProtrudeDistance(grd2, grd) - self.failUnless(dist==0.0) + self.assertTrue(dist==0.0) grd2 = geom.UniformGrid3D(10.0, 10.0, 10.0, 0.5, DataStructs.DiscreteValueType.FOURBITVALUE) grd2.SetSphereOccupancy(geom.Point3D(-2.0, -2.0, 0.0), 1.5, 0.25, 3) grd2.SetSphereOccupancy(geom.Point3D(-2.0, 2.0, 0.0), 1.5, 0.25, 3) grd2.SetSphereOccupancy(geom.Point3D(2.0, -2.0, 0.0), 1.5, 0.25, 3) - self.failUnlessRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) + self.assertRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) grd2 = geom.UniformGrid3D(10.0, 10.0, 10.0, 1.0) - self.failUnlessRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) + self.assertRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) grd2 = geom.UniformGrid3D(11.0, 10.0, 10.0, 1.0) - self.failUnlessRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) + self.assertRaises(ValueError, lambda : geom.TanimotoDistance(grd, grd2)) def testSymmetry(self): grd = geom.UniformGrid3D(10.0, 10.0, 10.0, 0.5) @@ -266,7 +270,7 @@ class TestCase(unittest.TestCase): for i in range(8) : bPt1 += geom.Point3D(0.5, 0.0, 0.0) bPt2 -= geom.Point3D(0.5, 0.0, 0.0) - self.failUnless(grd.GetValPoint(bPt1) == grd.GetValPoint(bPt2)) + self.assertTrue(grd.GetValPoint(bPt1) == grd.GetValPoint(bPt2)) bPt1.x = -4.0 bPt2.x = 4.0 @@ -276,32 +280,32 @@ class TestCase(unittest.TestCase): def testPointPickles(self): pt = geom.Point3D(2.0,-3.0,1.0) pt2 = cPickle.loads(cPickle.dumps(pt)) - self.failUnless(feq(pt.x,pt2.x,1e-6)) - self.failUnless(feq(pt.y,pt2.y,1e-6)) - self.failUnless(feq(pt.z,pt2.z,1e-6)) + self.assertTrue(feq(pt.x,pt2.x,1e-6)) + self.assertTrue(feq(pt.y,pt2.y,1e-6)) + self.assertTrue(feq(pt.z,pt2.z,1e-6)) pt = geom.Point2D(2.0,-4.0) pt2 = cPickle.loads(cPickle.dumps(pt)) - self.failUnless(feq(pt.x,pt2.x,1e-6)) - self.failUnless(feq(pt.y,pt2.y,1e-6)) + self.assertTrue(feq(pt.x,pt2.x,1e-6)) + self.assertTrue(feq(pt.y,pt2.y,1e-6)) def test4GridPickles(self): grd = geom.UniformGrid3D(10.0, 9.0, 8.0, 0.5) - self.failUnless(grd.GetNumX() == 20) - self.failUnless(grd.GetNumY() == 18) - self.failUnless(grd.GetNumZ() == 16) + self.assertTrue(grd.GetNumX() == 20) + self.assertTrue(grd.GetNumY() == 18) + self.assertTrue(grd.GetNumZ() == 16) grd.SetSphereOccupancy(geom.Point3D(-2.0, -2.0, 0.0), 1.5, 0.25) grd.SetSphereOccupancy(geom.Point3D(-2.0, 2.0, 0.0), 1.5, 0.25) grd.SetSphereOccupancy(geom.Point3D(2.0, -2.0, 0.0), 1.5, 0.25) grd.SetSphereOccupancy(geom.Point3D(2.0, 2.0, 0.0), 1.5, 0.25) - self.failUnless(geom.TanimotoDistance(grd,grd)==0.0) + self.assertTrue(geom.TanimotoDistance(grd,grd)==0.0) grd2 = cPickle.loads(cPickle.dumps(grd)) - self.failUnless(grd2.GetNumX() == 20) - self.failUnless(grd2.GetNumY() == 18) - self.failUnless(grd2.GetNumZ() == 16) - self.failUnless(geom.TanimotoDistance(grd,grd2)==0.0) + self.assertTrue(grd2.GetNumX() == 20) + self.assertTrue(grd2.GetNumY() == 18) + self.assertTrue(grd2.GetNumZ() == 16) + self.assertTrue(geom.TanimotoDistance(grd,grd2)==0.0) def test5GridOps(self): grd = geom.UniformGrid3D(10, 10, 10) @@ -312,33 +316,33 @@ class TestCase(unittest.TestCase): grd2.SetSphereOccupancy(geom.Point3D(2.0, -2.0, 0.0), 1.0, 0.25) grd2.SetSphereOccupancy(geom.Point3D(2.0, 2.0, 0.0), 1.0, 0.25) - self.failUnless(geom.TanimotoDistance(grd,grd)==0.0) - self.failUnless(geom.TanimotoDistance(grd,grd2)==1.0) + self.assertTrue(geom.TanimotoDistance(grd,grd)==0.0) + self.assertTrue(geom.TanimotoDistance(grd,grd2)==1.0) grd3 = copy.deepcopy(grd) grd3 |= grd2 - self.failUnless(geom.TanimotoDistance(grd3,grd)==.5) - self.failUnless(geom.TanimotoDistance(grd3,grd2)==.5) + self.assertTrue(geom.TanimotoDistance(grd3,grd)==.5) + self.assertTrue(geom.TanimotoDistance(grd3,grd2)==.5) grd3 = copy.deepcopy(grd) grd3 += grd2 - self.failUnless(geom.TanimotoDistance(grd3,grd)==.5) - self.failUnless(geom.TanimotoDistance(grd3,grd2)==.5) + self.assertTrue(geom.TanimotoDistance(grd3,grd)==.5) + self.assertTrue(geom.TanimotoDistance(grd3,grd2)==.5) grd3 -= grd - self.failUnless(geom.TanimotoDistance(grd3,grd)==1.0) - self.failUnless(geom.TanimotoDistance(grd3,grd2)==0) + self.assertTrue(geom.TanimotoDistance(grd3,grd)==1.0) + self.assertTrue(geom.TanimotoDistance(grd3,grd2)==0) grd4 = geom.UniformGrid3D(10, 10, 10) grd4.SetSphereOccupancy(geom.Point3D(-2.0, -2.0, 0.0), 1.0, 0.25) grd4.SetSphereOccupancy(geom.Point3D(-2.0, 2.0, 0.0), 1.0, 0.25) grd4.SetSphereOccupancy(geom.Point3D(2.0, -2.0, 0.0), 1.0, 0.25) - self.failUnless(feq(geom.TanimotoDistance(grd4,grd),.3333)) - self.failUnless(feq(geom.TanimotoDistance(grd4,grd2),.75)) + self.assertTrue(feq(geom.TanimotoDistance(grd4,grd),.3333)) + self.assertTrue(feq(geom.TanimotoDistance(grd4,grd2),.75)) grd4&=grd2 - self.failUnless(feq(geom.TanimotoDistance(grd4,grd),1.0)) - self.failUnless(feq(geom.TanimotoDistance(grd4,grd2),.5)) + self.assertTrue(feq(geom.TanimotoDistance(grd4,grd),1.0)) + self.assertTrue(feq(geom.TanimotoDistance(grd4,grd2),.5)) def test6Dihedrals(self): @@ -348,60 +352,60 @@ class TestCase(unittest.TestCase): p4 = geom.Point3D(.5,1,.5) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/4,4) + self.assertAlmostEqual(ang,math.pi/4,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,-math.pi/4,4) + self.assertAlmostEqual(ang,-math.pi/4,4) p4 = geom.Point3D(-.5,1,.5) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,3*math.pi/4,4) + self.assertAlmostEqual(ang,3*math.pi/4,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,-3*math.pi/4,4) + self.assertAlmostEqual(ang,-3*math.pi/4,4) p4 = geom.Point3D(.5,1,-.5) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/4,4) + self.assertAlmostEqual(ang,math.pi/4,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/4,4) + self.assertAlmostEqual(ang,math.pi/4,4) p4 = geom.Point3D(-.5,1,-.5) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,3*math.pi/4,4) + self.assertAlmostEqual(ang,3*math.pi/4,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,3*math.pi/4,4) + self.assertAlmostEqual(ang,3*math.pi/4,4) p4 = geom.Point3D(0,1,1) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/2,4) + self.assertAlmostEqual(ang,math.pi/2,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,-math.pi/2,4) + self.assertAlmostEqual(ang,-math.pi/2,4) p4 = geom.Point3D(0,1,-1) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/2,4) + self.assertAlmostEqual(ang,math.pi/2,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi/2,4) + self.assertAlmostEqual(ang,math.pi/2,4) p4 = geom.Point3D(1,1,0) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,0,4) + self.assertAlmostEqual(ang,0,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,0,4) + self.assertAlmostEqual(ang,0,4) p4 = geom.Point3D(-1,1,0) ang = geom.ComputeDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi,4) + self.assertAlmostEqual(ang,math.pi,4) ang = geom.ComputeSignedDihedralAngle(p1,p2,p3,p4) - self.failUnlessAlmostEqual(ang,math.pi,4) + self.assertAlmostEqual(ang,math.pi,4) def test7UniformGridIndices(self): ugrid = geom.UniformGrid3D(20, 18, 15) idx = ugrid.GetGridIndex(3,2,1) xi,yi,zi=ugrid.GetGridIndices(idx) - self.failUnlessEqual(xi,3) - self.failUnlessEqual(yi,2) - self.failUnlessEqual(zi,1) + self.assertEqual(xi,3) + self.assertEqual(yi,2) + self.assertEqual(zi,1) if __name__=='__main__': - print "Testing Geometry wrapper" + print("Testing Geometry wrapper") unittest.main() diff --git a/Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py b/Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py index 5de6c18c0..febcfe1d5 100644 --- a/Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py +++ b/Code/GraphMol/ChemReactions/Wrap/testReactionWrapper.py @@ -29,14 +29,18 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +from __future__ import print_function + +import unittest +import os,sys + +from rdkit.six.moves import cPickle + from rdkit import rdBase from rdkit import Chem from rdkit.Chem import rdChemReactions from rdkit import Geometry from rdkit import RDConfig -import unittest -import os,sys -import cPickle def feq(v1,v2,tol2=1e-4): return abs(v1-v2)<=tol2 @@ -51,83 +55,84 @@ class TestCase(unittest.TestCase) : def test1Basics(self): rxn = rdChemReactions.ChemicalReaction() - self.failUnless(rxn.GetNumReactantTemplates()==0) - self.failUnless(rxn.GetNumProductTemplates()==0) + self.assertTrue(rxn.GetNumReactantTemplates()==0) + self.assertTrue(rxn.GetNumProductTemplates()==0) r1= Chem.MolFromSmarts('[C:1](=[O:2])O') rxn.AddReactantTemplate(r1) - self.failUnless(rxn.GetNumReactantTemplates()==1) + self.assertTrue(rxn.GetNumReactantTemplates()==1) r1= Chem.MolFromSmarts('[N:3]') rxn.AddReactantTemplate(r1) - self.failUnless(rxn.GetNumReactantTemplates()==2) + self.assertTrue(rxn.GetNumReactantTemplates()==2) r1= Chem.MolFromSmarts('[C:1](=[O:2])[N:3]') rxn.AddProductTemplate(r1) - self.failUnless(rxn.GetNumProductTemplates()==1) + self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==3) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==3) ps = rxn.RunReactants(list(reacts)) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==3) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==3) def test2DaylightParser(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') - self.failUnless(rxn) - self.failUnless(rxn.GetNumReactantTemplates()==2) - self.failUnless(rxn.GetNumProductTemplates()==1) - self.failUnless(rxn._getImplicitPropertiesFlag()) + self.assertTrue(rxn) + self.assertTrue(rxn.GetNumReactantTemplates()==2) + self.assertTrue(rxn.GetNumProductTemplates()==1) + self.assertTrue(rxn._getImplicitPropertiesFlag()) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==3) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==3) reacts = (Chem.MolFromSmiles('CC(=O)OC'),Chem.MolFromSmiles('CN')) ps = rxn.RunReactants(reacts) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==5) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==5) def test3MDLParsers(self): fileN = os.path.join(self.dataDir,'AmideBond.rxn') rxn = rdChemReactions.ReactionFromRxnFile(fileN) - self.failUnless(rxn) - self.failIf(rxn._getImplicitPropertiesFlag()) + self.assertTrue(rxn) + self.assertFalse(rxn._getImplicitPropertiesFlag()) - self.failUnless(rxn.GetNumReactantTemplates()==2) - self.failUnless(rxn.GetNumProductTemplates()==1) + self.assertTrue(rxn.GetNumReactantTemplates()==2) + self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==3) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==3) - rxnBlock = file(fileN,'r').read() + with open(fileN, 'r') as rxnF: + rxnBlock = rxnF.read() rxn = rdChemReactions.ReactionFromRxnBlock(rxnBlock) - self.failUnless(rxn) + self.assertTrue(rxn) - self.failUnless(rxn.GetNumReactantTemplates()==2) - self.failUnless(rxn.GetNumProductTemplates()==1) + self.assertTrue(rxn.GetNumReactantTemplates()==2) + self.assertTrue(rxn.GetNumProductTemplates()==1) reacts = (Chem.MolFromSmiles('C(=O)O'),Chem.MolFromSmiles('N')) ps = rxn.RunReactants(reacts) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - self.failUnless(ps[0][0].GetNumAtoms()==3) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + self.assertTrue(ps[0][0].GetNumAtoms()==3) def test4ErrorHandling(self): - self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])Q.[N:3]>>[C:1](=[O:2])[N:3]':rdChemReactions.ReactionFromSmarts(x)) - self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]Q':rdChemReactions.ReactionFromSmarts(x)) - self.failUnlessRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]>>CC':rdChemReactions.ReactionFromSmarts(x)) + self.assertRaises(ValueError,lambda x='[C:1](=[O:2])Q.[N:3]>>[C:1](=[O:2])[N:3]':rdChemReactions.ReactionFromSmarts(x)) + self.assertRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]Q':rdChemReactions.ReactionFromSmarts(x)) + self.assertRaises(ValueError,lambda x='[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]>>CC':rdChemReactions.ReactionFromSmarts(x)) block="""$RXN @@ -164,7 +169,7 @@ $MOL 2 3 2 0 0 0 0 M END """ - self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) + self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN @@ -201,7 +206,7 @@ $MOL 2 3 2 0 0 0 0 M END """ - #self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) + #self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) block="""$RXN @@ -238,99 +243,99 @@ $MOL 2 3 2 0 0 0 0 M END """ - #self.failUnlessRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) + #self.assertRaises(ValueError,lambda x=block:rdChemReactions.ReactionFromRxnBlock(x)) def test5Validation(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3]') - self.failUnless(rxn) - self.failUnless(rxn.Validate()==(0,0)) + self.assertTrue(rxn) + self.assertTrue(rxn.Validate()==(0,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:1])O.[N:3]>>[C:1](=[O:2])[N:3]') - self.failUnless(rxn) - self.failUnless(rxn.Validate()==(1,1)) + self.assertTrue(rxn) + self.assertTrue(rxn.Validate()==(1,1)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])[O:4].[N:3]>>[C:1](=[O:2])[N:3]') - self.failUnless(rxn) - self.failUnless(rxn.Validate()==(1,0)) + self.assertTrue(rxn) + self.assertTrue(rxn.Validate()==(1,0)) rxn = rdChemReactions.ReactionFromSmarts('[C:1](=[O:2])O.[N:3]>>[C:1](=[O:2])[N:3][C:5]') - self.failUnless(rxn) - self.failUnless(rxn.Validate()==(1,0)) + self.assertTrue(rxn) + self.assertTrue(rxn.Validate()==(1,0)) def test6Exceptions(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') - self.failUnless(rxn) - self.failUnlessRaises(ValueError,lambda x=rxn:x.RunReactants(())) - self.failUnlessRaises(ValueError,lambda x=rxn:x.RunReactants((Chem.MolFromSmiles('CC'),Chem.MolFromSmiles('C')))) + self.assertTrue(rxn) + self.assertRaises(ValueError,lambda x=rxn:x.RunReactants(())) + self.assertRaises(ValueError,lambda x=rxn:x.RunReactants((Chem.MolFromSmiles('CC'),Chem.MolFromSmiles('C')))) ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) def _test7Leak(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]Cl>>[C:1]') - self.failUnless(rxn) - print 'running: ' + self.assertTrue(rxn) + print('running: ') for i in range(1e5): ps=rxn.RunReactants((Chem.MolFromSmiles('CCCl'),)) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) - if not i%1000: print i + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) + if not i%1000: print(i) def test8Properties(self): rxn = rdChemReactions.ReactionFromSmarts('[O:1]>>[O:1][3#0]') - self.failUnless(rxn) + self.assertTrue(rxn) ps=rxn.RunReactants((Chem.MolFromSmiles('CO'),)) - self.failUnless(len(ps)==1) - self.failUnless(len(ps[0])==1) + self.assertTrue(len(ps)==1) + self.assertTrue(len(ps[0])==1) Chem.SanitizeMol(ps[0][0]) - self.failUnlessEqual(ps[0][0].GetAtomWithIdx(1).GetIsotope(),3); + self.assertEqual(ps[0][0].GetAtomWithIdx(1).GetIsotope(),3); def test9AromaticityTransfer(self): # this was issue 2664121 mol = Chem.MolFromSmiles('c1ccc(C2C3(Cc4c(cccc4)C2)CCCC3)cc1') rxn = rdChemReactions.ReactionFromSmarts('[A:1]1~[*:2]~[*:3]~[*:4]~[*:5]~[A:6]-;@1>>[*:1]~[*:2]~[*:3]~[*:4]~[*:5]~[*:6]') products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),6) + self.assertEqual(len(products),6) for p in products: - self.failUnlessEqual(len(p),1) + self.assertEqual(len(p),1) Chem.SanitizeMol(p[0]) def test10DotSeparation(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1]1[O:2].[N:3]1') mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(p[0].GetNumAtoms(),3) - self.failUnlessEqual(p[0].GetNumBonds(),2) + self.assertEqual(len(p),1) + self.assertEqual(p[0].GetNumAtoms(),3) + self.assertEqual(p[0].GetNumBonds(),2) def test11ImplicitProperties(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]O>>[C:1]') mol = Chem.MolFromSmiles('CCO') products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') + self.assertEqual(len(p),1) + self.assertEqual(Chem.MolToSmiles(p[0]),'CC') mol2 = Chem.MolFromSmiles('C[CH-]O') products = rxn.RunReactants([mol2]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(Chem.MolToSmiles(p[0]),'[CH2-]C') + self.assertEqual(len(p),1) + self.assertEqual(Chem.MolToSmiles(p[0]),'[CH2-]C') rxn._setImplicitPropertiesFlag(False) products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') + self.assertEqual(len(p),1) + self.assertEqual(Chem.MolToSmiles(p[0]),'CC') products = rxn.RunReactants([mol2]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(Chem.MolToSmiles(p[0]),'CC') + self.assertEqual(len(p),1) + self.assertEqual(Chem.MolToSmiles(p[0]),'CC') def test12Pickles(self): @@ -339,102 +344,102 @@ M END rxn = cPickle.loads(pkl) mol = Chem.MolFromSmiles('C1ON1') products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(p[0].GetNumAtoms(),3) - self.failUnlessEqual(p[0].GetNumBonds(),2) + self.assertEqual(len(p),1) + self.assertEqual(p[0].GetNumAtoms(),3) + self.assertEqual(p[0].GetNumBonds(),2) rxn = rdChemReactions.ChemicalReaction(rxn.ToBinary()) products = rxn.RunReactants([mol]) - self.failUnlessEqual(len(products),1) + self.assertEqual(len(products),1) for p in products: - self.failUnlessEqual(len(p),1) - self.failUnlessEqual(p[0].GetNumAtoms(),3) - self.failUnlessEqual(p[0].GetNumBonds(),2) + self.assertEqual(len(p),1) + self.assertEqual(p[0].GetNumAtoms(),3) + self.assertEqual(p[0].GetNumBonds(),2) def test13GetTemplates(self): rxn = rdChemReactions.ReactionFromSmarts('[C:1]1[O:2][N:3]1>>[C:1][O:2].[N:3]') r1 = rxn.GetReactantTemplate(0) sma=Chem.MolToSmarts(r1) - self.failUnlessEqual(sma,'[C:1]1-,:[O:2]-,:[N:3]-,:1') + self.assertEqual(sma,'[C:1]1-,:[O:2]-,:[N:3]-,:1') p1 = rxn.GetProductTemplate(0) sma=Chem.MolToSmarts(p1) - self.failUnlessEqual(sma,'[C:1]-,:[O:2]') + self.assertEqual(sma,'[C:1]-,:[O:2]') p2 = rxn.GetProductTemplate(1) sma=Chem.MolToSmarts(p2) - self.failUnlessEqual(sma,'[N:3]') + self.assertEqual(sma,'[N:3]') - self.failUnlessRaises(ValueError,lambda :rxn.GetProductTemplate(2)) - self.failUnlessRaises(ValueError,lambda :rxn.GetReactantTemplate(1)) + self.assertRaises(ValueError,lambda :rxn.GetProductTemplate(2)) + self.assertRaises(ValueError,lambda :rxn.GetReactantTemplate(1)) def test14Matchers(self): rxn = rdChemReactions.ReactionFromSmarts('[C;!$(C(-O)-O):1](=[O:2])[O;H,-1].[N;!H0:3]>>[C:1](=[O:2])[N:3]') - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() - self.failUnless(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)C'))) - self.failIf(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)O'))) - self.failUnless(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CNC'))) - self.failIf(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CN(C)C'))) - self.failUnless(rxn.IsMoleculeProduct(Chem.MolFromSmiles('NC(=O)C'))) - self.failUnless(rxn.IsMoleculeProduct(Chem.MolFromSmiles('CNC(=O)C'))) - self.failIf(rxn.IsMoleculeProduct(Chem.MolFromSmiles('COC(=O)C'))) + self.assertTrue(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)C'))) + self.assertFalse(rxn.IsMoleculeReactant(Chem.MolFromSmiles('OC(=O)O'))) + self.assertTrue(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CNC'))) + self.assertFalse(rxn.IsMoleculeReactant(Chem.MolFromSmiles('CN(C)C'))) + self.assertTrue(rxn.IsMoleculeProduct(Chem.MolFromSmiles('NC(=O)C'))) + self.assertTrue(rxn.IsMoleculeProduct(Chem.MolFromSmiles('CNC(=O)C'))) + self.assertFalse(rxn.IsMoleculeProduct(Chem.MolFromSmiles('COC(=O)C'))) def test15Replacements(self): rxn = rdChemReactions.ReactionFromSmarts('[{amine}:1]>>[*:1]-C', replacements={'{amine}':'$([N;!H0;$(N-[#6]);!$(N-[!#6;!#1]);!$(N-C=[O,N,S])])'}) - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() reactants = (Chem.MolFromSmiles('CCN'),) ps = rxn.RunReactants(reactants) - self.failUnlessEqual(len(ps),1) - self.failUnlessEqual(len(ps[0]),1) - self.failUnlessEqual(ps[0][0].GetNumAtoms(),4) + self.assertEqual(len(ps),1) + self.assertEqual(len(ps[0]),1) + self.assertEqual(ps[0][0].GetNumAtoms(),4) def test16GetReactingAtoms(self): rxn = rdChemReactions.ReactionFromSmarts("[O:1][C:2].[N:3]>>[N:1][C:2].[N:3]") - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() - self.failUnlessEqual(len(rAs),2) - self.failUnlessEqual(len(rAs[0]),1) - self.failUnlessEqual(len(rAs[1]),0) + self.assertEqual(len(rAs),2) + self.assertEqual(len(rAs[0]),1) + self.assertEqual(len(rAs[1]),0) rxn = rdChemReactions.ReactionFromSmarts("[O:1]C>>[O:1]C") - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() rAs = rxn.GetReactingAtoms() - self.failUnlessEqual(len(rAs),1) - self.failUnlessEqual(len(rAs[0]),2) + self.assertEqual(len(rAs),1) + self.assertEqual(len(rAs[0]),2) rAs = rxn.GetReactingAtoms(True) - self.failUnlessEqual(len(rAs),1) - self.failUnlessEqual(len(rAs[0]),1) + self.assertEqual(len(rAs),1) + self.assertEqual(len(rAs[0]),1) def test17AddRecursiveQueriesToReaction(self): rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() qs = {'aliphatic':Chem.MolFromSmiles('CC')} rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') rxn.AddRecursiveQueriesToReaction(qs,'query') q = rxn.GetReactantTemplate(0) m = Chem.MolFromSmiles('CCOC') - self.failUnless(m.HasSubstructMatch(q)) + self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CO') - self.failIf(m.HasSubstructMatch(q)) + self.assertFalse(m.HasSubstructMatch(q)) rxn = rdChemReactions.ReactionFromSmarts("[C:1][O:2].[N:3]>>[C:1][N:2]") rxn.Initialize() rxn.GetReactantTemplate(0).GetAtomWithIdx(0).SetProp('query', 'aliphatic') labels = rxn.AddRecursiveQueriesToReaction(qs,'query', getLabels=True) - self.failUnless(len(labels), 1) + self.assertTrue(len(labels), 1) def test18GithubIssue16(self): rxn = rdChemReactions.ReactionFromSmarts("[F:1]>>[Cl:1]") - self.failUnless(rxn) + self.assertTrue(rxn) rxn.Initialize() - self.failUnlessRaises(ValueError,lambda : rxn.RunReactants((None,))) + self.assertRaises(ValueError,lambda : rxn.RunReactants((None,))) if __name__ == '__main__': unittest.main() diff --git a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp index 151b9e7ce..6bed18fb0 100644 --- a/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp +++ b/Code/GraphMol/Depictor/Wrap/rdDepictor.cpp @@ -13,6 +13,7 @@ #define PY_ARRAY_UNIQUE_SYMBOL Depictor_array_API #include "numpy/oldnumeric.h" #include +#include #include #include @@ -113,7 +114,7 @@ BOOST_PYTHON_MODULE(rdDepictor) "Module containing the functionality to compute 2D coordinates for a molecule" ; - import_array(); + rdkit_import_array(); std::string docString; diff --git a/Code/GraphMol/Depictor/Wrap/testDepictor.py b/Code/GraphMol/Depictor/Wrap/testDepictor.py index 9fbec201d..91e9fe14e 100755 --- a/Code/GraphMol/Depictor/Wrap/testDepictor.py +++ b/Code/GraphMol/Depictor/Wrap/testDepictor.py @@ -3,13 +3,15 @@ # # $Id$ # +from __future__ import division +import unittest +import os,sys +from rdkit.six.moves import cPickle as pickle + from rdkit import Chem from rdkit.Chem import rdDepictor from rdkit import Geometry from rdkit import RDConfig -import unittest -import os,sys -import cPickle as pickle from rdkit.Chem.ChemUtils import AlignDepict import numpy.oldnumeric as Numeric @@ -22,12 +24,12 @@ def ptEq(pt1, pt2, tol=1e-4): def getDistMat(mol): conf = mol.GetConformer() nat = mol.GetNumAtoms() - nl = nat*(nat-1)/2 + nl = nat*(nat-1)//2 res = Numeric.zeros(nl, Numeric.Float) for i in range(1,nat): pi = conf.GetAtomPosition(i) - id = i*(i-1)/2 + id = i*(i-1)//2 for j in range(i): pj = conf.GetAtomPosition(j) pj -= pi @@ -129,9 +131,10 @@ class TestCase(unittest.TestCase) : rdDepictor.Compute2DCoords(m1,coordMap=coordMap) conf = m1.GetConformer(0) for i in range(4): - self.failUnless(ptEq(conf.GetAtomPosition(i),Geometry.Point3D(coordMap[i].x, - coordMap[i].y, - 0.0))) + self.assertTrue(ptEq(conf.GetAtomPosition(i), + Geometry.Point3D(coordMap[i].x, + coordMap[i].y, + 0.0))) m1 = Chem.MolFromSmiles('CCC') try: @@ -139,7 +142,7 @@ class TestCase(unittest.TestCase) : ok = 0 except ValueError: ok=1 - self.failUnless(ok) + self.assertTrue(ok) def test3IssueSF1526844(self): t = Chem.MolFromSmiles('c1nc(N)ccc1') @@ -161,7 +164,7 @@ class TestCase(unittest.TestCase) : conf = m2.GetConformer() for i in range(nat) : pos = conf.GetAtomPosition(i) - self.failUnless(ptEq(pos, expected[i], 0.001)) + self.assertTrue(ptEq(pos, expected[i], 0.001)) def test4SamplingSpread(self): mol= Chem.MolFromMolFile(os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_xtal.mol')) @@ -169,13 +172,13 @@ class TestCase(unittest.TestCase) : # default mode rdDepictor.Compute2DCoords(mol,canonOrient=False) - self.failUnless(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_default.mol'))) + self.assertTrue(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_default.mol'))) # spread the structure as much as possible by sampling rdDepictor.Compute2DCoords(mol,canonOrient=False, nFlipsPerSample=3, nSample=100, sampleSeed=100, permuteDeg4Nodes=1) - self.failUnless(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_spread.mol'))) + self.assertTrue(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_spread.mol'))) def test5SamplingMimic3D(self): @@ -184,11 +187,11 @@ class TestCase(unittest.TestCase) : # now mimic the coordinate with a very small weight rdDepictor.Compute2DCoordsMimicDistmat(mol, dmat3D, weightDistMat=0.001) - self.failUnless(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_mimic3D_1.mol'))) + self.assertTrue(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_mimic3D_1.mol'))) # now mimic the coordinate with a very small weight rdDepictor.Compute2DCoordsMimicDistmat(mol, dmat3D, weightDistMat=0.003) - self.failUnless(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_mimic3D_2.mol'))) + self.assertTrue(compareCoords(mol, os.path.join(RDConfig.RDBaseDir,'Code/GraphMol/Depictor','test_data/7UPJ_mimic3D_2.mol'))) #mb = Chem.MolToMolBlock(mol) #ofile = open('../test_data/7UPJ_mimic3D_2.mol', 'w') @@ -199,15 +202,15 @@ class TestCase(unittest.TestCase) : m =Chem.MolFromSmiles('CC') rdDepictor.Compute2DCoords(m) conf = m.GetConformer() - self.failUnlessAlmostEqual(conf.GetAtomPosition(0).x,-0.750,3) - self.failUnlessAlmostEqual(conf.GetAtomPosition(1).x,0.750,3) + self.assertAlmostEqual(conf.GetAtomPosition(0).x,-0.750,3) + self.assertAlmostEqual(conf.GetAtomPosition(1).x,0.750,3) rdDepictor.Compute2DCoords(m,bondLength=1.0) conf = m.GetConformer() - self.failUnlessAlmostEqual(conf.GetAtomPosition(0).x,-0.500,3) - self.failUnlessAlmostEqual(conf.GetAtomPosition(1).x,0.500,3) + self.assertAlmostEqual(conf.GetAtomPosition(0).x,-0.500,3) + self.assertAlmostEqual(conf.GetAtomPosition(1).x,0.500,3) rdDepictor.Compute2DCoords(m) conf = m.GetConformer() - self.failUnlessAlmostEqual(conf.GetAtomPosition(0).x,-0.750,3) - self.failUnlessAlmostEqual(conf.GetAtomPosition(1).x,0.750,3) + self.assertAlmostEqual(conf.GetAtomPosition(0).x,-0.750,3) + self.assertAlmostEqual(conf.GetAtomPosition(1).x,0.750,3) if __name__ == '__main__': unittest.main() diff --git a/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py b/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py index a0b99f62c..8cb823c71 100644 --- a/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py +++ b/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py @@ -17,23 +17,23 @@ class TestCase(unittest.TestCase) : def testAtomPairTypes(self): params = rdMD.AtomPairsParameters mol = Chem.MolFromSmiles("C=C"); - self.failUnless(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ + self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(1))) - self.failUnless(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ + self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ 1 | (1 | 1<0.0 and sim<1.0) + self.assertTrue(sim>0.0 and sim<1.0) m = Chem.MolFromSmiles('c1ccccn1') fp2 = rdMD.GetHashedAtomPairFingerprint(m,2048) sim= DataStructs.DiceSimilarity(fp1,fp2) - self.failUnless(sim>0.0 and sim<1.0) + self.assertTrue(sim>0.0 and sim<1.0) m = Chem.MolFromSmiles('c1ccccc1') @@ -69,7 +69,7 @@ class TestCase(unittest.TestCase) : m = Chem.MolFromSmiles('c1ccccn1') fp2 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m,2048) sim= DataStructs.DiceSimilarity(fp1,fp2) - self.failUnless(sim>0.0 and sim<1.0) + self.assertTrue(sim>0.0 and sim<1.0) def testRootedAtomPairs(self): @@ -78,36 +78,36 @@ class TestCase(unittest.TestCase) : fp2 = rdMD.GetAtomPairFingerprint(m,fromAtoms=(0,)) nz1 = fp1.GetNonzeroElements() nz2 = fp2.GetNonzeroElements() - for k,v in nz2.iteritems(): - self.failUnless(v<=nz1[k]) + for k,v in nz2.items(): + self.assertTrue(v<=nz1[k]) def testTopologicalTorsions(self): mol = Chem.MolFromSmiles("CC"); fp = rdMD.GetTopologicalTorsionFingerprint(mol) - self.failUnless(fp.GetTotalVal()==0) + self.assertTrue(fp.GetTotalVal()==0) mol = Chem.MolFromSmiles("CCCC"); fp = rdMD.GetTopologicalTorsionFingerprint(mol) - self.failUnless(fp.GetTotalVal()==1) + self.assertTrue(fp.GetTotalVal()==1) fp = rdMD.GetTopologicalTorsionFingerprint(mol,3) - self.failUnless(fp.GetTotalVal()==2) + self.assertTrue(fp.GetTotalVal()==2) mol = Chem.MolFromSmiles("CCCO"); fp = rdMD.GetTopologicalTorsionFingerprint(mol) - self.failUnless(fp.GetTotalVal()==1) + self.assertTrue(fp.GetTotalVal()==1) fp = rdMD.GetTopologicalTorsionFingerprint(mol,3) - self.failUnless(fp.GetTotalVal()==2) + self.assertTrue(fp.GetTotalVal()==2) mol = Chem.MolFromSmiles("CCCCCCCCCCC"); fp = rdMD.GetTopologicalTorsionFingerprint(mol,7) - self.failUnlessRaises(ValueError,lambda : rdMD.GetTopologicalTorsionFingerprint(mol,8)) + self.assertRaises(ValueError,lambda : rdMD.GetTopologicalTorsionFingerprint(mol,8)) def testHashedTopologicalTorsions(self): mol = Chem.MolFromSmiles("c1ncccc1"); fp1 = rdMD.GetHashedTopologicalTorsionFingerprint(mol) mol = Chem.MolFromSmiles("n1ccccc1"); fp2 = rdMD.GetHashedTopologicalTorsionFingerprint(mol) - self.failUnlessEqual(DataStructs.DiceSimilarity(fp1,fp2),1.0) + self.assertEqual(DataStructs.DiceSimilarity(fp1,fp2),1.0) def testRootedTorsions(self): m = Chem.MolFromSmiles('Oc1ccccc1') @@ -115,146 +115,146 @@ class TestCase(unittest.TestCase) : fp2 = rdMD.GetTopologicalTorsionFingerprint(m,fromAtoms=(0,)) nz1 = fp1.GetNonzeroElements() nz2 = fp2.GetNonzeroElements() - for k,v in nz2.iteritems(): - self.failUnless(v<=nz1[k]) + for k,v in nz2.items(): + self.assertTrue(v<=nz1[k]) m = Chem.MolFromSmiles('COCC') fp1 = rdMD.GetTopologicalTorsionFingerprint(m) - self.failUnlessEqual(len(fp1.GetNonzeroElements()),1) + self.assertEqual(len(fp1.GetNonzeroElements()),1) fp1 = rdMD.GetTopologicalTorsionFingerprint(m,fromAtoms=(0,)) - self.failUnlessEqual(len(fp1.GetNonzeroElements()),1) + self.assertEqual(len(fp1.GetNonzeroElements()),1) fp1 = rdMD.GetTopologicalTorsionFingerprint(m,fromAtoms=(1,)) - self.failUnlessEqual(len(fp1.GetNonzeroElements()),0) + self.assertEqual(len(fp1.GetNonzeroElements()),0) def testMorganFingerprints(self): mol = Chem.MolFromSmiles('CC(F)(Cl)C(F)(Cl)C') fp = rdMD.GetMorganFingerprint(mol,0) - self.failUnless(len(fp.GetNonzeroElements())==4) + self.assertTrue(len(fp.GetNonzeroElements())==4) mol = Chem.MolFromSmiles('CC') fp = rdMD.GetMorganFingerprint(mol,0) - self.failUnless(len(fp.GetNonzeroElements())==1) - self.failUnless(fp.GetNonzeroElements().values()[0]==2) + self.assertTrue(len(fp.GetNonzeroElements())==1) + self.assertTrue(list(fp.GetNonzeroElements().values())[0]==2) fp = rdMD.GetMorganFingerprint(mol,0,useCounts=False) - self.failUnless(len(fp.GetNonzeroElements())==1) - self.failUnless(fp.GetNonzeroElements().values()[0]==1) + self.assertTrue(len(fp.GetNonzeroElements())==1) + self.assertTrue(list(fp.GetNonzeroElements().values())[0]==1) mol = Chem.MolFromSmiles('CC(F)(Cl)C(F)(Cl)C') fp = rdMD.GetHashedMorganFingerprint(mol,0) - self.failUnless(len(fp.GetNonzeroElements())==4) + self.assertTrue(len(fp.GetNonzeroElements())==4) fp = rdMD.GetMorganFingerprint(mol,1) - self.failUnless(len(fp.GetNonzeroElements())==8) + self.assertTrue(len(fp.GetNonzeroElements())==8) fp = rdMD.GetHashedMorganFingerprint(mol,1) - self.failUnless(len(fp.GetNonzeroElements())==8) + self.assertTrue(len(fp.GetNonzeroElements())==8) fp = rdMD.GetMorganFingerprint(mol,2) - self.failUnless(len(fp.GetNonzeroElements())==9) + self.assertTrue(len(fp.GetNonzeroElements())==9) mol = Chem.MolFromSmiles('CC(F)(Cl)[C@](F)(Cl)C') fp = rdMD.GetMorganFingerprint(mol,0) - self.failUnless(len(fp.GetNonzeroElements())==4) + self.assertTrue(len(fp.GetNonzeroElements())==4) fp = rdMD.GetMorganFingerprint(mol,1) - self.failUnless(len(fp.GetNonzeroElements())==8) + self.assertTrue(len(fp.GetNonzeroElements())==8) fp = rdMD.GetMorganFingerprint(mol,2) - self.failUnless(len(fp.GetNonzeroElements())==9) + self.assertTrue(len(fp.GetNonzeroElements())==9) fp = rdMD.GetMorganFingerprint(mol,0,useChirality=True) - self.failUnless(len(fp.GetNonzeroElements())==4) + self.assertTrue(len(fp.GetNonzeroElements())==4) fp = rdMD.GetMorganFingerprint(mol,1,useChirality=True) - self.failUnless(len(fp.GetNonzeroElements())==9) + self.assertTrue(len(fp.GetNonzeroElements())==9) fp = rdMD.GetMorganFingerprint(mol,2,useChirality=True) - self.failUnless(len(fp.GetNonzeroElements())==10) + self.assertTrue(len(fp.GetNonzeroElements())==10) mol = Chem.MolFromSmiles('CCCCC') fp = rdMD.GetMorganFingerprint(mol,0,fromAtoms=(0,)) - self.failUnless(len(fp.GetNonzeroElements())==1) + self.assertTrue(len(fp.GetNonzeroElements())==1) mol = Chem.MolFromSmiles('CC1CC1') vs1 = rdMD.GetConnectivityInvariants(mol) - self.failUnlessEqual(len(vs1),mol.GetNumAtoms()) + self.assertEqual(len(vs1),mol.GetNumAtoms()) fp1 = rdMD.GetMorganFingerprint(mol,2,invariants=vs1) fp2 = rdMD.GetMorganFingerprint(mol,2) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) vs2 = rdMD.GetConnectivityInvariants(mol,False) - self.failUnlessEqual(len(vs2),mol.GetNumAtoms()) - self.failIfEqual(vs1,vs2) + self.assertEqual(len(vs2),mol.GetNumAtoms()) + self.assertNotEqual(vs1,vs2) fp1 = rdMD.GetMorganFingerprint(mol,2,invariants=vs2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) mol = Chem.MolFromSmiles('Cc1ccccc1') vs1 = rdMD.GetFeatureInvariants(mol) - self.failUnlessEqual(len(vs1),mol.GetNumAtoms()) - self.failUnlessEqual(vs1[0],0) - self.failIfEqual(vs1[1],0) - self.failUnlessEqual(vs1[1],vs1[2]) - self.failUnlessEqual(vs1[1],vs1[3]) - self.failUnlessEqual(vs1[1],vs1[4]) + self.assertEqual(len(vs1),mol.GetNumAtoms()) + self.assertEqual(vs1[0],0) + self.assertNotEqual(vs1[1],0) + self.assertEqual(vs1[1],vs1[2]) + self.assertEqual(vs1[1],vs1[3]) + self.assertEqual(vs1[1],vs1[4]) mol = Chem.MolFromSmiles('FCCCl') vs1 = rdMD.GetFeatureInvariants(mol) - self.failUnlessEqual(len(vs1),mol.GetNumAtoms()) - self.failUnlessEqual(vs1[1],0) - self.failUnlessEqual(vs1[2],0) - self.failIfEqual(vs1[0],0) - self.failUnlessEqual(vs1[0],vs1[3]) + self.assertEqual(len(vs1),mol.GetNumAtoms()) + self.assertEqual(vs1[1],0) + self.assertEqual(vs1[2],0) + self.assertNotEqual(vs1[0],0) + self.assertEqual(vs1[0],vs1[3]) fp1 = rdMD.GetMorganFingerprint(mol,0,invariants=vs1) fp2 = rdMD.GetMorganFingerprint(mol,0,useFeatures=True) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) def testCrippen(self): mol = Chem.MolFromSmiles("n1ccccc1CO"); contribs = rdMD._CalcCrippenContribs(mol) - self.failUnlessEqual(len(contribs),mol.GetNumAtoms()); + self.assertEqual(len(contribs),mol.GetNumAtoms()); ts = [0]*mol.GetNumAtoms() contribs = rdMD._CalcCrippenContribs(mol,force=True,atomTypes=ts) - self.failUnlessEqual(ts,[59, 25, 25, 25, 25, 28, 17, 69]) + self.assertEqual(ts,[59, 25, 25, 25, 25, 28, 17, 69]) ls = ['']*mol.GetNumAtoms() contribs = rdMD._CalcCrippenContribs(mol,force=True,atomTypeLabels=ls) - self.failUnlessEqual(ls,['N11', 'C18', 'C18', 'C18', 'C18', 'C21', 'C10', 'O2']) + self.assertEqual(ls,['N11', 'C18', 'C18', 'C18', 'C18', 'C21', 'C10', 'O2']) def testMolWt(self): mol = Chem.MolFromSmiles("C"); amw = rdMD._CalcMolWt(mol); - self.failUnless(feq(amw,16.043,.001)); + self.assertTrue(feq(amw,16.043,.001)); amw = rdMD._CalcMolWt(mol,True); - self.failUnless(feq(amw,12.011,.001)); + self.assertTrue(feq(amw,12.011,.001)); mol2 = Chem.AddHs(mol); amw = rdMD._CalcMolWt(mol2); - self.failUnless(feq(amw,16.043,.001)); + self.assertTrue(feq(amw,16.043,.001)); amw = rdMD._CalcMolWt(mol2,True); - self.failUnless(feq(amw,12.011,.001)); + self.assertTrue(feq(amw,12.011,.001)); mol = Chem.MolFromSmiles("C"); amw = rdMD.CalcExactMolWt(mol); - self.failUnless(feq(amw,16.031,.001)); + self.assertTrue(feq(amw,16.031,.001)); def testPairValues(self): import base64 - testD=(('CCCO','AQAAAAQAAAAAAIAABgAAACGECAABAAAAIoQIAAEAAABBhAgAAQAAACNEGAABAAAAQUQYAAEAAABC\nRBgAAQAAAA==\n'), - ('CNc1ccco1','AQAAAAQAAAAAAIAAEAAAACOECgABAAAAJIQKAAIAAABBhQoAAgAAAEKFCgABAAAAIsQKAAEAAABB\nxQoAAQAAAELFCgACAAAAIYQQAAEAAABChRAAAQAAAEOFEAACAAAAYYUQAAEAAAAjhBoAAQAAAEGF\nGgABAAAAQoUaAAIAAABhhRoAAQAAAEKIGgABAAAA\n'), + testD=(('CCCO',b'AQAAAAQAAAAAAIAABgAAACGECAABAAAAIoQIAAEAAABBhAgAAQAAACNEGAABAAAAQUQYAAEAAABC\nRBgAAQAAAA==\n'), + ('CNc1ccco1',b'AQAAAAQAAAAAAIAAEAAAACOECgABAAAAJIQKAAIAAABBhQoAAgAAAEKFCgABAAAAIsQKAAEAAABB\nxQoAAQAAAELFCgACAAAAIYQQAAEAAABChRAAAQAAAEOFEAACAAAAYYUQAAEAAAAjhBoAAQAAAEGF\nGgABAAAAQoUaAAIAAABhhRoAAQAAAEKIGgABAAAA\n'), ) for smi,txt in testD: pkl = base64.decodestring(txt) fp = rdMD.GetAtomPairFingerprint(Chem.MolFromSmiles(smi)) fp2 = DataStructs.IntSparseIntVect(pkl) - self.failUnlessEqual(DataStructs.DiceSimilarity(fp,fp2),1.0) - self.failUnlessEqual(fp,fp2) + self.assertEqual(DataStructs.DiceSimilarity(fp,fp2),1.0) + self.assertEqual(fp,fp2) def testTorsionValues(self): import base64 - testD=(('CCCO','AQAAAAgAAAD/////DwAAAAEAAAAAAAAAIECAAAMAAAABAAAA\n'), - ('CNc1ccco1','AQAAAAgAAAD/////DwAAAAkAAAAAAAAAIICkSAEAAAABAAAAKVKgSQEAAAABAAAAKVCgUAEAAAAB\nAAAAKVCgUQEAAAABAAAAKVCkCAIAAAABAAAAKdCkCAIAAAABAAAAKVCgSAMAAAABAAAAKVCkSAMA\nAAABAAAAIICkSAMAAAABAAAA\n'), + testD=(('CCCO',b'AQAAAAgAAAD/////DwAAAAEAAAAAAAAAIECAAAMAAAABAAAA\n'), + ('CNc1ccco1',b'AQAAAAgAAAD/////DwAAAAkAAAAAAAAAIICkSAEAAAABAAAAKVKgSQEAAAABAAAAKVCgUAEAAAAB\nAAAAKVCgUQEAAAABAAAAKVCkCAIAAAABAAAAKdCkCAIAAAABAAAAKVCgSAMAAAABAAAAKVCkSAMA\nAAABAAAAIICkSAMAAAABAAAA\n'), ) for smi,txt in testD: pkl = base64.decodestring(txt) fp = rdMD.GetTopologicalTorsionFingerprint(Chem.MolFromSmiles(smi)) fp2 = DataStructs.LongSparseIntVect(pkl) - self.failUnlessEqual(DataStructs.DiceSimilarity(fp,fp2),1.0) - self.failUnlessEqual(fp,fp2) + self.assertEqual(DataStructs.DiceSimilarity(fp,fp2),1.0) + self.assertEqual(fp,fp2) def testAtomPairOptions(self): m1 = Chem.MolFromSmiles('c1ccccc1') @@ -262,66 +262,66 @@ class TestCase(unittest.TestCase) : fp1 = rdMD.GetAtomPairFingerprint(m1) fp2 = rdMD.GetAtomPairFingerprint(m2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetAtomPairFingerprint(m1,atomInvariants=[1]*6) fp2 = rdMD.GetAtomPairFingerprint(m2,atomInvariants=[1]*6) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) fp1 = rdMD.GetAtomPairFingerprint(m1,atomInvariants=[1]*6) fp2 = rdMD.GetAtomPairFingerprint(m2,atomInvariants=[2]*6) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m1) fp2 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m1,atomInvariants=[1]*6) fp2 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m2,atomInvariants=[1]*6) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) fp1 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m1,atomInvariants=[1]*6) fp2 = rdMD.GetHashedAtomPairFingerprintAsBitVect(m2,atomInvariants=[2]*6) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetTopologicalTorsionFingerprint(m1) fp2 = rdMD.GetTopologicalTorsionFingerprint(m2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetTopologicalTorsionFingerprint(m1,atomInvariants=[1]*6) fp2 = rdMD.GetTopologicalTorsionFingerprint(m2,atomInvariants=[1]*6) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) fp1 = rdMD.GetTopologicalTorsionFingerprint(m1,atomInvariants=[1]*6) fp2 = rdMD.GetTopologicalTorsionFingerprint(m2,atomInvariants=[2]*6) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m1) fp2 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) fp1 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m1,atomInvariants=[1]*6) fp2 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m2,atomInvariants=[1]*6) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) fp1 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m1,atomInvariants=[1]*6) fp2 = rdMD.GetHashedTopologicalTorsionFingerprintAsBitVect(m2,atomInvariants=[2]*6) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) def testMolFormula(self): m = Chem.MolFromSmiles("[2H]C([3H])O") formula = rdMD.CalcMolFormula(m) - self.failUnlessEqual(formula,'CH4O') + self.assertEqual(formula,'CH4O') formula = rdMD.CalcMolFormula(m,separateIsotopes=True) - self.failUnlessEqual(formula,'CH2DTO') + self.assertEqual(formula,'CH2DTO') formula = rdMD.CalcMolFormula(m,separateIsotopes=True,abbreviateHIsotopes=False) - self.failUnlessEqual(formula,'CH2[2H][3H]O') + self.assertEqual(formula,'CH2[2H][3H]O') m = Chem.MolFromSmiles("[2H][13CH2]CO") formula = rdMD.CalcMolFormula(m) - self.failUnlessEqual(formula,'C2H6O') + self.assertEqual(formula,'C2H6O') formula = rdMD.CalcMolFormula(m,separateIsotopes=True) - self.failUnlessEqual(formula,'C[13C]H5DO') + self.assertEqual(formula,'C[13C]H5DO') diff --git a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp index 6b4b8845c..3243cc687 100644 --- a/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp +++ b/Code/GraphMol/DistGeomHelpers/Wrap/rdDistGeom.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -105,7 +106,7 @@ BOOST_PYTHON_MODULE(rdDistGeom) { "Module containing functions to compute atomic coordinates in 3D using distance geometry" ; - import_array(); + rdkit_import_array(); //RegisterListConverter(); diff --git a/Code/GraphMol/DistGeomHelpers/Wrap/testDistGeom.py b/Code/GraphMol/DistGeomHelpers/Wrap/testDistGeom.py index 22c66462f..88fc750bb 100644 --- a/Code/GraphMol/DistGeomHelpers/Wrap/testDistGeom.py +++ b/Code/GraphMol/DistGeomHelpers/Wrap/testDistGeom.py @@ -1,11 +1,14 @@ +from __future__ import print_function +import unittest +import os,copy +import math +import numpy + +from rdkit.six.moves import cPickle as pickle +from rdkit.six import next from rdkit import Chem from rdkit.Chem import rdDistGeom,ChemicalForceFields,rdMolAlign from rdkit import RDConfig -import unittest -import os,copy -import cPickle as pickle -import math -import numpy from rdkit.Geometry import rdGeometry as geom from rdkit.RDLogger import logger logger=logger() @@ -92,7 +95,7 @@ class TestCase(unittest.TestCase) : ofile = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','DistGeomHelpers', 'test_data','embedDistOpti.sdf') - self.failUnless(compareWithOld(fileN, ofile)) + self.assertTrue(compareWithOld(fileN, ofile)) def test1Small(self): #writer = Chem.SDWriter("test.sdf") @@ -100,22 +103,22 @@ class TestCase(unittest.TestCase) : mol = Chem.MolFromSmiles('O') rdDistGeom.EmbedMolecule(mol,10,1) conf = mol.GetConformer() - self.failUnless(lstEq(conf.GetAtomPosition(0), [0.0, 0.0, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(0), [0.0, 0.0, 0.0])) #writer.write(mol) mol = Chem.MolFromSmiles('CO') rdDistGeom.EmbedMolecule(mol, 10,1) conf = mol.GetConformer() - self.failUnless(lstEq(conf.GetAtomPosition(0), [0.69192, 0.0, 0.0])) - self.failUnless(lstEq(conf.GetAtomPosition(1), [-0.69192, 0.0, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(0), [0.69192, 0.0, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(1), [-0.69192, 0.0, 0.0])) #writer.write(mol) mol = Chem.MolFromSmiles('CCC') rdDistGeom.EmbedMolecule(mol,10,1) conf = mol.GetConformer() - self.failUnless(lstEq(conf.GetAtomPosition(0), [-1.21676, -0.2989, 0.0])) - self.failUnless(lstEq(conf.GetAtomPosition(1), [-0.00604, 0.59337, 0.0])) - self.failUnless(lstEq(conf.GetAtomPosition(2), [1.22281, -0.29446, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(0), [-1.21676, -0.2989, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(1), [-0.00604, 0.59337, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(2), [1.22281, -0.29446, 0.0])) #writer.write(mol) mol = Chem.MolFromSmiles('O=C=O') @@ -123,9 +126,9 @@ class TestCase(unittest.TestCase) : conf = mol.GetConformer() #writer.write(mol) - self.failUnless(lstEq(conf.GetAtomPosition(0), [-1.2180, -0.06088, 0.0])) - self.failUnless(lstEq(conf.GetAtomPosition(1), [-0.00408, 0.12116, 0.0])) - self.failUnless(lstEq(conf.GetAtomPosition(2), [1.22207, -0.060276, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(0), [-1.2180, -0.06088, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(1), [-0.00408, 0.12116, 0.0])) + self.assertTrue(lstEq(conf.GetAtomPosition(2), [1.22207, -0.060276, 0.0])) mol = Chem.MolFromSmiles('C=C=C=C') rdDistGeom.EmbedMolecule(mol,10,1) @@ -134,26 +137,26 @@ class TestCase(unittest.TestCase) : #writer.write(mol) d1 = computeDist(conf.GetAtomPosition(0), conf.GetAtomPosition(1)) - self.failUnless(feq(d1, 1.31, 0.01)) + self.assertTrue(feq(d1, 1.31, 0.01)) d2 = computeDist(conf.GetAtomPosition(0), conf.GetAtomPosition(2)) - self.failUnless(feq(d2, 2.59, 0.05)) + self.assertTrue(feq(d2, 2.59, 0.05)) d3 = computeDist(conf.GetAtomPosition(0), conf.GetAtomPosition(3)) - self.failUnless(feq(d3, 3.84, 0.1)) + self.assertTrue(feq(d3, 3.84, 0.1)) d4 = computeDist(conf.GetAtomPosition(1), conf.GetAtomPosition(2)) - self.failUnless(feq(d4, 1.29, 0.01)) + self.assertTrue(feq(d4, 1.29, 0.01)) d5 = computeDist(conf.GetAtomPosition(1), conf.GetAtomPosition(3)) - self.failUnless(feq(d5, 2.54, 0.1)) + self.assertTrue(feq(d5, 2.54, 0.1)) d6 = computeDist(conf.GetAtomPosition(2), conf.GetAtomPosition(3)) - self.failUnless(feq(d6, 1.31, 0.01)) + self.assertTrue(feq(d6, 1.31, 0.01)) def test2Utils(self): mol = Chem.MolFromSmiles('CC') bm = rdDistGeom.GetMoleculeBoundsMatrix(mol) - self.failUnless(bm[1,0]>0) - self.failUnless(bm[0,1]>0) - self.failUnless(bm[0,1]>=bm[1,0]) - self.failUnless(bm[1,0]<1.510) - self.failUnless(bm[0,1]>1.510) + self.assertTrue(bm[1,0]>0) + self.assertTrue(bm[0,1]>0) + self.assertTrue(bm[0,1]>=bm[1,0]) + self.assertTrue(bm[1,0]<1.510) + self.assertTrue(bm[0,1]>1.510) def test3MultiConf(self): mol = Chem.MolFromSmiles("CC(C)(C)c(cc12)n[n]2C(=O)/C=C(N1)/COC") @@ -165,18 +168,18 @@ class TestCase(unittest.TestCase) : ff = ChemicalForceFields.UFFGetMoleculeForceField(mol, 10.0, cid) ee = ff.CalcEnergy() nenergies.append(ee) - #print ['%.2f'%x for x in nenergies] - #print nenergies - self.failUnless(lstEq(energies, nenergies,tol=1e-2)) + #print(['%.2f'%x for x in nenergies]) + #print(nenergies) + self.assertTrue(lstEq(energies, nenergies,tol=1e-2)) def test4OrderDependence(self) : - self.failUnless(compareOrder("CC(C)(C)C(=O)NC(C1)CC(N2C)CCC12", + self.assertTrue(compareOrder("CC(C)(C)C(=O)NC(C1)CC(N2C)CCC12", "CN1C2CCC1CC(NC(=O)C(C)(C)C)C2")) #issue 230 - self.failUnless(compareOrder("C#CC(C)(C)N(CN1)C\N=C/1SC", + self.assertTrue(compareOrder("C#CC(C)(C)N(CN1)C\\N=C/1SC", "CSC1=NCN(C(C)(C)C#C)CN1")) #issue 232 - self.failUnless(compareOrder("CC(C)(C)C(=O)NC(C1)CC(N2C)CCC12", + self.assertTrue(compareOrder("CC(C)(C)C(=O)NC(C1)CC(N2C)CCC12", "CN1C2CCC1CC(NC(=O)C(C)(C)C)C2")) def test5Issue285(self): @@ -185,7 +188,7 @@ class TestCase(unittest.TestCase) : for i,ci in enumerate(cs): for j in range(i+1,len(cs)): cj = cs[j] - self.failUnless(Chem.MolToMolBlock(m,confId=ci)!=Chem.MolToMolBlock(m,confId=cj)) + self.assertTrue(Chem.MolToMolBlock(m,confId=ci)!=Chem.MolToMolBlock(m,confId=cj)) def test6RmsPruning(self): smiles = ['CC(C)CC(NC(C1[N+]CCC1)=O)C([O-])=O', @@ -206,7 +209,7 @@ class TestCase(unittest.TestCase) : d = [abs(x-y) for x,y in zip(expected,nconfs)] - self.failUnless(max(d)<=1) + self.assertTrue(max(d)<=1) def test6Chirality(self): # turn on chirality and we should get chiral volume that is pretty consistent and @@ -216,21 +219,21 @@ class TestCase(unittest.TestCase) : mol = Chem.MolFromSmiles(smiles) cids = rdDistGeom.EmbedMultipleConfs(mol, 30, maxAttempts=30, randomSeed=100) - self.failUnless(len(cids)==30) + self.assertTrue(len(cids)==30) for cid in cids: conf = mol.GetConformer(cid) vol = computeChiralVol(conf.GetAtomPosition(0), conf.GetAtomPosition(2), conf.GetAtomPosition(3), conf.GetAtomPosition(4)) - self.failUnless(abs(vol-tgtVol)<1) + self.assertTrue(abs(vol-tgtVol)<1) # turn of chirality and now we should see both chiral forms smiles = "ClC(C)(F)Br" mol = Chem.MolFromSmiles(smiles) cids = rdDistGeom.EmbedMultipleConfs(mol, 30, maxAttempts=30, randomSeed=120) - self.failUnless(len(cids)==30) + self.assertTrue(len(cids)==30) nPos=0 nNeg=0 for cid in cids: @@ -239,11 +242,11 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(2), conf.GetAtomPosition(3), conf.GetAtomPosition(4)) - self.failUnless(abs(vol-tgtVol)<1 or abs(vol+tgtVol)<1) + self.assertTrue(abs(vol-tgtVol)<1 or abs(vol+tgtVol)<1) if vol<0: nNeg+=1 else: nPos+=1 - self.failUnless(nPos>0) - self.failUnless(nNeg>0) + self.assertTrue(nPos>0) + self.assertTrue(nNeg>0) tgtVol=5.0 for i in range(10): @@ -255,7 +258,7 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(1), conf.GetAtomPosition(2), conf.GetAtomPosition(3)) - self.failUnless(abs(vol-tgtVol)<1,"%s %s"%(vol,tgtVol)) + self.assertTrue(abs(vol-tgtVol)<1,"%s %s"%(vol,tgtVol)) tgtVol=3.5 expected = [-3.62, -3.67, -3.72, 3.91, 3.95, 3.98, 3.90, 3.94, 3.98, 3.91] @@ -270,19 +273,19 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(1), conf.GetAtomPosition(2), conf.GetAtomPosition(3)) - self.failUnless(abs(vol-tgtVol)<1 or abs(vol+tgtVol)<1) + self.assertTrue(abs(vol-tgtVol)<1 or abs(vol+tgtVol)<1) if vol<0: nNeg+=1 else: nPos+=1 - self.failUnless(nPos>0) - self.failUnless(nNeg>0) + self.assertTrue(nPos>0) + self.assertTrue(nNeg>0) smiles = "Cl[C@H](F)Br" m = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(m) cids = rdDistGeom.EmbedMultipleConfs(mol, 10, maxAttempts=30, randomSeed=100) - self.failUnless(len(cids)==10) + self.assertTrue(len(cids)==10) tgtVol=10.5 for cid in cids: conf = mol.GetConformer(cid) @@ -290,7 +293,7 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(2), conf.GetAtomPosition(3), conf.GetAtomPosition(4)) - self.failUnless(abs(vol-tgtVol)<2.) + self.assertTrue(abs(vol-tgtVol)<2.) # let's try a little more complicated system expectedV1 = -2.0 @@ -308,7 +311,7 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(3), conf.GetAtomPosition(7), conf.GetAtomPosition(13)) - self.failUnless(abs(vol1-expectedV1)<1 or abs(vol1+expectedV1)<1) + self.assertTrue(abs(vol1-expectedV1)<1 or abs(vol1+expectedV1)<1) if vol1<0: nNeg+=1 else: nPos+=1 @@ -317,15 +320,15 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(16), conf.GetAtomPosition(18), conf.GetAtomPosition(19)) - self.failUnless(abs(vol2-expectedV2)<1 or abs(vol2+expectedV2)<1) + self.assertTrue(abs(vol2-expectedV2)<1 or abs(vol2+expectedV2)<1) # remove the chiral specification and we should see other chiral # forms of the compound expectedV1 = 2.0 #[-2.30, -2.31, -2.30, 2.30, -1.77] expectedV2 = 2.8 #[2.90, 2.89, 2.69, -2.90, -2.93] - self.failUnless(nPos>0) - self.failUnless(nNeg>0) + self.assertTrue(nPos>0) + self.assertTrue(nNeg>0) for i in range(5): smi = "C1=CC=C(C=C1)C(OC1=C[NH]N=C1)C(=O)[NH]CC(Cl)C1=CC=NC=C1" mol = Chem.MolFromSmiles(smi) @@ -342,26 +345,26 @@ class TestCase(unittest.TestCase) : conf.GetAtomPosition(16), conf.GetAtomPosition(18), conf.GetAtomPosition(19)) - self.failUnless(abs(abs(vol1)-expectedV1)<1.0) - self.failUnless(abs(abs(vol2)-expectedV2)<1.0) + self.assertTrue(abs(abs(vol1)-expectedV1)<1.0) + self.assertTrue(abs(abs(vol2)-expectedV2)<1.0) def test7ConstrainedEmbedding(self): ofile = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','DistGeomHelpers', 'test_data','constrain1.sdf') suppl = Chem.SDMolSupplier(ofile); - ref = suppl.next() + ref = next(suppl) probe = copy.deepcopy(ref) cMap={} for i in range(5): cMap[i]=ref.GetConformer().GetAtomPosition(i) ci = rdDistGeom.EmbedMolecule(probe,coordMap=cMap,randomSeed=23) - self.failUnless(ci>-1); + self.assertTrue(ci>-1); algMap = zip(range(5),range(5)) ssd = rdMolAlign.AlignMol(probe,ref,atomMap=algMap) - print 'ssd:',ssd - self.failUnless(ssd<0.1) + print('ssd:',ssd) + self.assertTrue(ssd<0.1) if __name__ == '__main__': unittest.main() diff --git a/Code/GraphMol/FragCatalog/Wrap/rough_test.py b/Code/GraphMol/FragCatalog/Wrap/rough_test.py index 9e80d635d..d1ba89687 100755 --- a/Code/GraphMol/FragCatalog/Wrap/rough_test.py +++ b/Code/GraphMol/FragCatalog/Wrap/rough_test.py @@ -9,13 +9,13 @@ it's intended to be shallow, but broad """ import unittest,os +from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit.RDLogger import logger logger=logger() from rdkit import Chem from rdkit.Chem import FragmentCatalog from rdkit import DataStructs -import cPickle class TestCase(unittest.TestCase): @@ -65,7 +65,8 @@ class TestCase(unittest.TestCase): assert tuple(fcat.GetEntryFuncGroupIds(id))==tuple(fcat.GetBitFuncGroupIds(id)) def test3FPgenerator(self) : - smiLines = open(self.smiName,'r').readlines() + with open(self.smiName,'r') as smiF: + smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(1, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() @@ -92,7 +93,8 @@ class TestCase(unittest.TestCase): def test4Serialize(self) : - smiLines = open(self.smiName,'r').readlines() + with open(self.smiName,'r') as smiF: + smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(1, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() @@ -120,7 +122,8 @@ class TestCase(unittest.TestCase): def test5FPsize(self) : - smiLines = open(self.smiName,'r').readlines() + with open(self.smiName,'r') as smiF: + smiLines = smiF.readlines() fparams = FragmentCatalog.FragCatParams(6, 6, self.fName) fcat = FragmentCatalog.FragCatalog(fparams) fgen = FragmentCatalog.FragCatGenerator() diff --git a/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp b/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp index 69d18ce30..01ef16661 100644 --- a/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp +++ b/Code/GraphMol/MolAlign/Wrap/rdMolAlign.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include @@ -363,7 +364,7 @@ namespace RDKit { } BOOST_PYTHON_MODULE(rdMolAlign) { - import_array(); + rdkit_import_array(); python::scope().attr("__doc__") = "Module containing functions to align a molecule to a second molecule"; diff --git a/Code/GraphMol/MolAlign/Wrap/testMolAlign.py b/Code/GraphMol/MolAlign/Wrap/testMolAlign.py index a74867c1b..3a5edc4b9 100644 --- a/Code/GraphMol/MolAlign/Wrap/testMolAlign.py +++ b/Code/GraphMol/MolAlign/Wrap/testMolAlign.py @@ -4,6 +4,7 @@ # # @@ All Rights Reserved @@ # +from __future__ import print_function from rdkit import RDConfig import os,sys,copy import unittest @@ -36,7 +37,7 @@ class TestCase(unittest.TestCase): mol2 = Chem.MolFromMolFile(file2) rmsd = rdMolAlign.AlignMol(mol2, mol1) - self.failUnless(feq(rmsd, 0.6578)) + self.assertTrue(feq(rmsd, 0.6578)) file3 = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', 'MolAlign', 'test_data', '1oir_trans.mol') @@ -45,10 +46,10 @@ class TestCase(unittest.TestCase): conf3 = mol3.GetConformer() for i in range(mol2.GetNumAtoms()): - self.failUnless(lstFeq(conf2.GetAtomPosition(i), conf3.GetAtomPosition(i))) + self.assertTrue(lstFeq(conf2.GetAtomPosition(i), conf3.GetAtomPosition(i))) rmsd, trans = rdMolAlign.GetAlignmentTransform(mol2, mol1) - self.failUnlessAlmostEqual(rmsd, 0.6579,4) + self.assertAlmostEqual(rmsd, 0.6579,4) def test2AtomMap(self) : atomMap = ((18,27), (13,23), (21,14), (24,7), (9,19), (16,30)) @@ -60,7 +61,7 @@ class TestCase(unittest.TestCase): mol1 = Chem.MolFromMolFile(file1) mol2 = Chem.MolFromMolFile(file2) rmsd = rdMolAlign.AlignMol(mol2, mol1, 0, 0, atomMap) - self.failUnlessAlmostEqual(rmsd, 0.8525,4) + self.assertAlmostEqual(rmsd, 0.8525,4) def test3Weights(self): atomMap = ((18,27), (13,23), (21,14), (24,7), (9,19), (16,30)) @@ -73,7 +74,7 @@ class TestCase(unittest.TestCase): mol2 = Chem.MolFromMolFile(file2) wts = (1.0, 1.0, 1.0, 1.0, 1.0, 2.0) rmsd = rdMolAlign.AlignMol(mol2, mol1, 0, 0, atomMap, wts) - self.failUnlessAlmostEqual(rmsd, 0.9513,4) + self.assertAlmostEqual(rmsd, 0.9513,4) def test4AlignConfs(self): mol = Chem.MolFromSmiles('C1CC1CNc(n2)nc(C)cc2Nc(cc34)ccc3[nH]nc4') @@ -104,7 +105,7 @@ class TestCase(unittest.TestCase): else : pos = list(conf.GetAtomPosition(aid)) - self.failUnless(lstFeq(mpos, pos, .5)) + self.assertTrue(lstFeq(mpos, pos, .5)) def test5MMFFO3A(self): sdf = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', @@ -126,8 +127,8 @@ class TestCase(unittest.TestCase): cumMsd += rmsd * rmsd # molW.write(prbMol) cumMsd /= len(molS) - self.failUnlessAlmostEqual(cumScore,6942,0) - self.failUnlessAlmostEqual(math.sqrt(cumMsd),.345,3) + self.assertAlmostEqual(cumScore,6942,0) + self.assertAlmostEqual(math.sqrt(cumMsd),.345,3) def test6MMFFO3A(self): " now test where the mmff parameters are generated on call " @@ -144,8 +145,8 @@ class TestCase(unittest.TestCase): rmsd = pyO3A.Align() cumMsd += rmsd * rmsd cumMsd /= len(molS) - self.failUnlessAlmostEqual(cumScore,6942,0) - self.failUnlessAlmostEqual(math.sqrt(cumMsd),.345,3) + self.assertAlmostEqual(cumScore,6942,0) + self.assertAlmostEqual(math.sqrt(cumMsd),.345,3) def test7MMFFO3A(self): " make sure we generate an error if parameters are missing (github issue 158) " @@ -155,8 +156,8 @@ class TestCase(unittest.TestCase): m2 = Chem.MolFromSmiles('c1ccccc1B(O)O') rdDistGeom.EmbedMolecule(m1) - self.failUnlessRaises(ValueError,lambda :rdMolAlign.GetO3A(m1, m2)) - self.failUnlessRaises(ValueError,lambda :rdMolAlign.GetO3A(m2, m1)) + self.assertRaises(ValueError,lambda :rdMolAlign.GetO3A(m1, m2)) + self.assertRaises(ValueError,lambda :rdMolAlign.GetO3A(m2, m1)) def test8MMFFO3A(self): " test MMFFO3A with constraints " @@ -184,12 +185,12 @@ class TestCase(unittest.TestCase): pyO3A.Align() d = m2.GetConformer().GetAtomPosition(cIdx). \ Distance(m1.GetConformer().GetAtomPosition(cIdx)) - self.failUnlessAlmostEqual(d, 0, 0) + self.assertAlmostEqual(d, 0, 0) pyO3A = rdMolAlign.GetO3A(m3, m1, constraintMap = [[cIdx, nIdx]]) pyO3A.Align() d = m3.GetConformer().GetAtomPosition(cIdx). \ Distance(m1.GetConformer().GetAtomPosition(cIdx)) - self.failUnlessAlmostEqual(d, 7, 0) + self.assertAlmostEqual(d, 7, 0) #alignedSdf = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', # 'MolAlign', 'test_data', # '4-phenylpyridines_MMFFO3A.sdf') @@ -231,7 +232,7 @@ class TestCase(unittest.TestCase): # molW.write(prbMol) d = prbMol.GetConformer().GetAtomPosition(prbOIdx). \ Distance(refMol.GetConformer().GetAtomPosition(refSIdx)) - self.failUnlessAlmostEqual(d, distOS[i], 1) + self.assertAlmostEqual(d, distOS[i], 1) # molW.close() def test10CrippenO3A(self): @@ -254,8 +255,8 @@ class TestCase(unittest.TestCase): cumMsd += rmsd * rmsd molW.write(prbMol) cumMsd /= len(molS) - self.failUnlessAlmostEqual(cumScore,4918,0) - self.failUnlessAlmostEqual(math.sqrt(cumMsd),.304,3) + self.assertAlmostEqual(cumScore,4918,0) + self.assertAlmostEqual(math.sqrt(cumMsd),.304,3) def test11CrippenO3A(self): " now test where the Crippen parameters are generated on call " @@ -272,8 +273,8 @@ class TestCase(unittest.TestCase): rmsd = pyO3A.Trans()[0] cumMsd += rmsd * rmsd cumMsd /= len(molS) - self.failUnlessAlmostEqual(cumScore,4918,0) - self.failUnlessAlmostEqual(math.sqrt(cumMsd),.304,3) + self.assertAlmostEqual(cumScore,4918,0) + self.assertAlmostEqual(math.sqrt(cumMsd),.304,3) def test12CrippenO3A(self): " test CrippenO3A with constraints " @@ -301,12 +302,12 @@ class TestCase(unittest.TestCase): pyO3A.Align() d = m2.GetConformer().GetAtomPosition(cIdx). \ Distance(m1.GetConformer().GetAtomPosition(cIdx)) - self.failUnlessAlmostEqual(d, 0, 0) + self.assertAlmostEqual(d, 0, 0) pyO3A = rdMolAlign.GetCrippenO3A(m3, m1, constraintMap = [[cIdx, nIdx]]) pyO3A.Align() d = m3.GetConformer().GetAtomPosition(cIdx). \ Distance(m1.GetConformer().GetAtomPosition(cIdx)) - self.failUnlessAlmostEqual(d, 7, 0) + self.assertAlmostEqual(d, 7, 0) #alignedSdf = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol', # 'MolAlign', 'test_data', # '4-phenylpyridines_CrippenO3A.sdf') @@ -347,10 +348,10 @@ class TestCase(unittest.TestCase): # molW.write(prbMol) d = prbMol.GetConformer().GetAtomPosition(prbOIdx). \ Distance(refMol.GetConformer().GetAtomPosition(refSIdx)) - self.failUnlessAlmostEqual(d, distOS[i], 1) + self.assertAlmostEqual(d, distOS[i], 1) # molW.close() if __name__ == '__main__': - print "Testing MolAlign Wrappers" + print("Testing MolAlign Wrappers") unittest.main() diff --git a/Code/GraphMol/MolCatalog/Wrap/rough_test.py b/Code/GraphMol/MolCatalog/Wrap/rough_test.py index b32392efa..b532ed8da 100755 --- a/Code/GraphMol/MolCatalog/Wrap/rough_test.py +++ b/Code/GraphMol/MolCatalog/Wrap/rough_test.py @@ -3,10 +3,10 @@ # Copyright (C) 2006 Greg Landrum # import unittest,os,sys +from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit import Chem from rdkit import DataStructs -import cPickle from rdkit.Chem import MolCatalog class TestCase(unittest.TestCase): @@ -17,24 +17,24 @@ class TestCase(unittest.TestCase): m = Chem.MolFromSmiles(smi) entry = MolCatalog.MolCatalogEntry() entry.SetMol(m) - self.failUnless(entry.GetMol()) + self.assertTrue(entry.GetMol()) eSmi = Chem.MolToSmiles(entry.GetMol()) - self.failUnless(eSmi==Chem.MolToSmiles(m)) + self.assertTrue(eSmi==Chem.MolToSmiles(m)) entry.SetDescription(smi) - self.failUnless(entry.GetDescription()==smi) + self.assertTrue(entry.GetDescription()==smi) es.append(entry) v=cat.AddEntry(es[0]) - self.failUnless(v==0) - self.failUnless(cat.GetNumEntries()==1) + self.assertTrue(v==0) + self.assertTrue(cat.GetNumEntries()==1) v=cat.AddEntry(es[1]) - self.failUnless(v==1) - self.failUnless(cat.GetNumEntries()==2) + self.assertTrue(v==1) + self.assertTrue(cat.GetNumEntries()==2) v=cat.AddEntry(es[2]) - self.failUnless(v==2) - self.failUnless(cat.GetNumEntries()==3) + self.assertTrue(v==2) + self.assertTrue(cat.GetNumEntries()==3) cat.AddEdge(0,1) cat.AddEdge(0,2) @@ -46,7 +46,7 @@ class TestCase(unittest.TestCase): cat=None cat = cPickle.loads(d) - self.failUnless(cat.GetNumEntries()==3) + self.assertTrue(cat.GetNumEntries()==3) cat=None diff --git a/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeature.cpp b/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeature.cpp index a5fbe5eaf..e57c3ad00 100644 --- a/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeature.cpp +++ b/Code/GraphMol/MolChemicalFeatures/Wrap/MolChemicalFeature.cpp @@ -11,8 +11,9 @@ #define NO_IMPORT_ARRAY #include -#include #include +#include +#include #include #include diff --git a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp index 8c71fb341..a6a0eb1c0 100644 --- a/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp +++ b/Code/GraphMol/MolTransforms/Wrap/rdMolTransforms.cpp @@ -13,6 +13,7 @@ #include "numpy/arrayobject.h" #include #include +#include #include #include #include @@ -58,7 +59,7 @@ BOOST_PYTHON_MODULE(rdMolTransforms) { python::scope().attr("__doc__") = "Module containing functions to perform 3D operations like rotate and translate conformations"; - import_array(); + rdkit_import_array(); std::string docString = "Compute the centroid of the conformation - hydrogens are ignored and no attention\n\ if paid to the difference in sizes of the heavy atoms\n"; diff --git a/Code/GraphMol/PartialCharges/Wrap/testPartialCharges.py b/Code/GraphMol/PartialCharges/Wrap/testPartialCharges.py index 52d153e7d..07e6975ec 100755 --- a/Code/GraphMol/PartialCharges/Wrap/testPartialCharges.py +++ b/Code/GraphMol/PartialCharges/Wrap/testPartialCharges.py @@ -1,9 +1,12 @@ +from __future__ import print_function +import unittest +import os + +from rdkit.six.moves import cPickle as pickle + from rdkit import Chem from rdkit.Chem import rdPartialCharges from rdkit import RDConfig -import unittest -import os -import cPickle as pickle def feq(v1,v2,tol2=1e-4): return abs(v1-v2)<=tol2 @@ -16,10 +19,9 @@ class TestCase(unittest.TestCase): smiSup = Chem.SmilesMolSupplier(os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','PartialCharges','Wrap','test_data','halgren.smi'),delimiter='\t') #parse the original file - infil = file(os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','PartialCharges','Wrap','test_data','halgren_out.txt'), - 'r') - lines = infil.readlines() - infil.close() + with open(os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','PartialCharges','Wrap','test_data','halgren_out.txt'), + 'r') as infil: + lines = infil.readlines() tab = Chem.GetPeriodicTable() @@ -39,8 +41,8 @@ class TestCase(unittest.TestCase): i = 0 for line in lines: - self.failUnless(line.strip() == olst[i]) - i += 1 + self.assertTrue(line.strip() == olst[i]) + i += 1 def test1PPDataset(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','PartialCharges','Wrap','test_data', 'PP_descrs_regress.2.csv') @@ -49,8 +51,8 @@ class TestCase(unittest.TestCase): infil.close() infile = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','PartialCharges','Wrap','test_data', 'PP_combi_charges.pkl') - cchFile = open(infile, 'rb') - combiCharges = pickle.load(cchFile) + with open(infile, 'rb') as cchFile: + combiCharges = pickle.load(cchFile) for lin in lines : if (lin[0] == '#') : @@ -66,9 +68,9 @@ class TestCase(unittest.TestCase): rdch = float(rdmol.GetAtomWithIdx(ai).GetProp('_GasteigerCharge')) if not feq(rdch, combiCharges[smi][ai], 1.e-2) : failed=True - print smi, ai, rdch, combiCharges[smi][ai] + print(smi, ai, rdch, combiCharges[smi][ai]) if failed: rdmol.Debug() - self.failIf(failed) + self.assertFalse(failed) def test2Params(self): """ tests handling of Issue187 """ @@ -84,7 +86,7 @@ class TestCase(unittest.TestCase): for i in range(m1.GetNumAtoms()): c1 = float(m1.GetAtomWithIdx(i).GetProp('_GasteigerCharge')) c2 = float(m2.GetAtomWithIdx(i).GetProp('_GasteigerCharge')) - self.failUnless(feq(c1,c2,1e-4)) + self.assertTrue(feq(c1,c2,1e-4)) def test3Params(self): @@ -105,7 +107,7 @@ class TestCase(unittest.TestCase): chgs=[-0.030,0.448,-0.427,-0.427] for i in range(m1.GetNumAtoms()): c1 = float(m1.GetAtomWithIdx(i).GetProp('_GasteigerCharge')) - self.failUnlessAlmostEqual(c1,chgs[i],3) + self.assertAlmostEqual(c1,chgs[i],3) if __name__== '__main__': unittest.main() diff --git a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp index 209993996..2a4091f35 100644 --- a/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp +++ b/Code/GraphMol/ShapeHelpers/Wrap/rdShapeHelpers.cpp @@ -13,6 +13,7 @@ #include "numpy/oldnumeric.h" #include #include +#include #include #include @@ -129,7 +130,7 @@ BOOST_PYTHON_MODULE(rdShapeHelpers) { "Module containing functions to encode and compare the shapes of molecules" ; - import_array(); + rdkit_import_array(); //RegisterListConverter(); diff --git a/Code/GraphMol/ShapeHelpers/Wrap/testShapeHelpers.py b/Code/GraphMol/ShapeHelpers/Wrap/testShapeHelpers.py index 6d26501ac..1b7f6e2af 100644 --- a/Code/GraphMol/ShapeHelpers/Wrap/testShapeHelpers.py +++ b/Code/GraphMol/ShapeHelpers/Wrap/testShapeHelpers.py @@ -1,13 +1,15 @@ -from rdkit import RDConfig +from __future__ import print_function import os,sys import unittest +import math + +from rdkit import RDConfig from rdkit import DataStructs from rdkit import Chem from rdkit.Chem import rdMolAlign from rdkit.Geometry import rdGeometry as geom from rdkit.Chem import rdShapeHelpers as rdshp from rdkit.Chem import rdMolTransforms as rdmt -import math def feq(v1, v2, tol=1.0e-4): return abs(v1-v2) < tol @@ -25,21 +27,21 @@ class TestCase(unittest.TestCase): grd = geom.UniformGrid3D(30.0, 16.0, 10.0) rdshp.EncodeShape(m, grd, 0); ovect = grd.GetOccupancyVect() - self.failUnless(ovect.GetTotalVal() == 9250) + self.assertTrue(ovect.GetTotalVal() == 9250) m = Chem.MolFromMolFile(fileN) trans = rdmt.ComputeCanonicalTransform(m.GetConformer()) dims, offset = rdshp.ComputeConfDimsAndOffset(m.GetConformer(), trans=trans) dims -= dims1 offset -= offset1; - self.failUnless(feq(dims.Length(), 0.0)) - self.failUnless(feq(offset.Length(), 0.0)) + self.assertTrue(feq(dims.Length(), 0.0)) + self.assertTrue(feq(offset.Length(), 0.0)) grd1 = geom.UniformGrid3D(30.0, 16.0, 10.0) rdshp.EncodeShape(m, grd1, 0, trans) ovect = grd1.GetOccupancyVect() - self.failUnless(ovect.GetTotalVal() == 9250) + self.assertTrue(ovect.GetTotalVal() == 9250) grd2 = geom.UniformGrid3D(30.0, 16.0, 10.0) rdshp.EncodeShape(m, grd2, 0) @@ -49,11 +51,11 @@ class TestCase(unittest.TestCase): m2 = Chem.MolFromMolFile(fileN2) rmsd = rdMolAlign.AlignMol(m, m2) - self.failUnless(feq(rdshp.ShapeTanimotoDist(m, m2),0.2813)) + self.assertTrue(feq(rdshp.ShapeTanimotoDist(m, m2),0.2813)) dist = rdshp.ShapeTanimotoDist(mol1=m, mol2=m2, confId1=0, confId2=0, gridSpacing=0.25, stepSize=0.125) - self.failUnless(feq(dist,0.3021)) + self.assertTrue(feq(dist,0.3021)) m = Chem.MolFromMolFile(fileN) cpt = rdmt.ComputeCentroid(m.GetConformer()) @@ -64,13 +66,13 @@ class TestCase(unittest.TestCase): offset) dims -= geom.Point3D(13.927, 16.97, 9.775) offset -= geom.Point3D(-4.353, 16.829, 2.782) - self.failUnless(feq(dims.Length(), 0.0)) - self.failUnless(feq(offset.Length(), 0.0)) + self.assertTrue(feq(dims.Length(), 0.0)) + self.assertTrue(feq(offset.Length(), 0.0)) rdshp.EncodeShape(m, grd, 0) ovect = grd.GetOccupancyVect() - self.failUnless(ovect.GetTotalVal() == 9275) + self.assertTrue(ovect.GetTotalVal() == 9275) geom.WriteGridToFile(grd, '1oir_shape.grd') m = Chem.MolFromMolFile(fileN) @@ -81,19 +83,19 @@ class TestCase(unittest.TestCase): lc2, uc2 = rdshp.ComputeUnionBox((lc, uc), (lc1, uc1)) lc -= geom.Point3D(-4.353, 16.829, 2.782) uc -= geom.Point3D(9.574, 33.799, 12.557) - self.failUnless(feq(lc.Length(), 0.0)) - self.failUnless(feq(uc.Length(), 0.0)) + self.assertTrue(feq(lc.Length(), 0.0)) + self.assertTrue(feq(uc.Length(), 0.0)) lc1 -= geom.Point3D(-10.7519, -6.0778, -3.0123) uc1 -= geom.Point3D(8.7163, 5.3279, 3.1621) - self.failUnless(feq(lc1.Length(), 0.0)) - self.failUnless(feq(uc1.Length(), 0.0)) + self.assertTrue(feq(lc1.Length(), 0.0)) + self.assertTrue(feq(uc1.Length(), 0.0)) lc2 -= geom.Point3D(-10.7519, -6.0778, -3.01226) uc2 -= geom.Point3D(9.574, 33.799, 12.557) - self.failUnless(feq(lc2.Length(), 0.0)) - self.failUnless(feq(uc2.Length(), 0.0)) + self.assertTrue(feq(lc2.Length(), 0.0)) + self.assertTrue(feq(uc2.Length(), 0.0)) if __name__=='__main__': - print "Testing Shape Helpers wrapper" + print("Testing Shape Helpers wrapper") unittest.main() diff --git a/Code/GraphMol/Wrap/ForwardSDMolSupplier.cpp b/Code/GraphMol/Wrap/ForwardSDMolSupplier.cpp index 39c2f367b..aa20b6200 100644 --- a/Code/GraphMol/Wrap/ForwardSDMolSupplier.cpp +++ b/Code/GraphMol/Wrap/ForwardSDMolSupplier.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include "MolSupplier.h" @@ -116,7 +117,8 @@ namespace RDKit { python::arg("sanitize")=true, python::arg("removeHs")=true, python::arg("strictParsing")=true))) - .def("next", (ROMol *(*)(LocalForwardSDMolSupplier *))&MolSupplNext, + .def(NEXT_METHOD, + (ROMol *(*)(LocalForwardSDMolSupplier *))&MolSupplNext, "Returns the next molecule in the file. Raises _StopIteration_ on EOF.\n", python::return_value_policy()) .def("atEnd", &ForwardSDMolSupplier::atEnd, diff --git a/Code/GraphMol/Wrap/Mol.cpp b/Code/GraphMol/Wrap/Mol.cpp index 1d4c759df..28a7b4927 100644 --- a/Code/GraphMol/Wrap/Mol.cpp +++ b/Code/GraphMol/Wrap/Mol.cpp @@ -15,6 +15,7 @@ #include "rdchem.h" #include "seqs.hpp" // ours +#include #include #include #include diff --git a/Code/GraphMol/Wrap/SDMolSupplier.cpp b/Code/GraphMol/Wrap/SDMolSupplier.cpp index 7132f9991..1b1413606 100644 --- a/Code/GraphMol/Wrap/SDMolSupplier.cpp +++ b/Code/GraphMol/Wrap/SDMolSupplier.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include "MolSupplier.h" @@ -79,7 +80,7 @@ namespace RDKit { python::arg("strictParsing")=true))) .def("__iter__", (SDMolSupplier *(*)(SDMolSupplier *))&MolSupplIter, python::return_internal_reference<1>() ) - .def("next", (ROMol *(*)(SDMolSupplier *))&MolSupplNextAcceptNullLastMolecule, + .def(NEXT_METHOD, (ROMol *(*)(SDMolSupplier *))&MolSupplNextAcceptNullLastMolecule, "Returns the next molecule in the file. Raises _StopIteration_ on EOF.\n", python::return_value_policy()) .def("__getitem__", (ROMol *(*)(SDMolSupplier *,int))&MolSupplGetItem, diff --git a/Code/GraphMol/Wrap/SmilesMolSupplier.cpp b/Code/GraphMol/Wrap/SmilesMolSupplier.cpp index 75b4419fb..64eef60c3 100644 --- a/Code/GraphMol/Wrap/SmilesMolSupplier.cpp +++ b/Code/GraphMol/Wrap/SmilesMolSupplier.cpp @@ -8,10 +8,11 @@ // which is included in the file license.txt, found at the root // of the RDKit source tree. // +#include #define NO_IMPORT_ARRAY #include -#include +#include //ours #include @@ -100,7 +101,7 @@ namespace RDKit { .def(python::init<>()) .def("__iter__", (SmilesMolSupplier *(*)(SmilesMolSupplier *))&MolSupplIter, python::return_internal_reference<1>() ) - .def("next", (ROMol *(*)(SmilesMolSupplier *))&MolSupplNext, + .def(NEXT_METHOD, (ROMol *(*)(SmilesMolSupplier *))&MolSupplNext, "Returns the next molecule in the file. Raises _StopIteration_ on EOF.\n", python::return_value_policy()) .def("__getitem__", (ROMol *(*)(SmilesMolSupplier *,int))&MolSupplGetItem, diff --git a/Code/GraphMol/Wrap/TDTMolSupplier.cpp b/Code/GraphMol/Wrap/TDTMolSupplier.cpp index 08e926579..e65741ab9 100644 --- a/Code/GraphMol/Wrap/TDTMolSupplier.cpp +++ b/Code/GraphMol/Wrap/TDTMolSupplier.cpp @@ -15,6 +15,7 @@ //ours #include #include +#include #include "MolSupplier.h" namespace python = boost::python; @@ -61,7 +62,7 @@ namespace RDKit { python::arg("sanitize")=true))) .def("__iter__", (TDTMolSupplier *(*)(TDTMolSupplier *))&MolSupplIter, python::return_internal_reference<1>() ) - .def("next", (ROMol *(*)(TDTMolSupplier *))&MolSupplNext, + .def(NEXT_METHOD, (ROMol *(*)(TDTMolSupplier *))&MolSupplNext, "Returns the next molecule in the file. Raises _StopIteration_ on EOF.\n", python::return_value_policy()) .def("__getitem__", (ROMol *(*)(TDTMolSupplier *,int))&MolSupplGetItem, diff --git a/Code/GraphMol/Wrap/rdchem.cpp b/Code/GraphMol/Wrap/rdchem.cpp index e26b59c79..bc826a62c 100644 --- a/Code/GraphMol/Wrap/rdchem.cpp +++ b/Code/GraphMol/Wrap/rdchem.cpp @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include @@ -55,7 +57,7 @@ BOOST_PYTHON_MODULE(rdchem) ; RegisterListConverter(); RegisterListConverter(); - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_index_error); python::register_exception_translator(&translate_value_error); python::register_exception_translator(&rdSanitExceptionTranslator); @@ -72,7 +74,7 @@ BOOST_PYTHON_MODULE(rdchem) .def("__iter__",&AtomIterSeq::__iter__, python::return_internal_reference<1, python::with_custodian_and_ward_postcall<0,1> >()) - .def("next",&AtomIterSeq::next, + .def(NEXT_METHOD,&AtomIterSeq::next, python::return_value_policy()) .def("__len__",&AtomIterSeq::len) @@ -85,7 +87,7 @@ BOOST_PYTHON_MODULE(rdchem) .def("__iter__",&QueryAtomIterSeq::__iter__, python::return_internal_reference<1, python::with_custodian_and_ward_postcall<0,1> >()) - .def("next",&QueryAtomIterSeq::next, + .def(NEXT_METHOD,&QueryAtomIterSeq::next, python::return_value_policy()) .def("__len__",&QueryAtomIterSeq::len) .def("__getitem__",&QueryAtomIterSeq::get_item, diff --git a/Code/GraphMol/Wrap/rdmolops.cpp b/Code/GraphMol/Wrap/rdmolops.cpp index 46ce883da..1c7eccece 100644 --- a/Code/GraphMol/Wrap/rdmolops.cpp +++ b/Code/GraphMol/Wrap/rdmolops.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -38,7 +39,7 @@ BOOST_PYTHON_MODULE(rdmolops) python::scope().attr("__doc__") = "Module containing RDKit functionality for manipulating molecules." ; - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_index_error); python::register_exception_translator(&translate_value_error); python::register_exception_translator(&rdSanitExceptionTranslator); diff --git a/Code/GraphMol/Wrap/rough_test.py b/Code/GraphMol/Wrap/rough_test.py index 183a10aae..d19948d7e 100755 --- a/Code/GraphMol/Wrap/rough_test.py +++ b/Code/GraphMol/Wrap/rough_test.py @@ -8,11 +8,13 @@ it's intended to be shallow, but broad """ -from rdkit import RDConfig,rdBase +from __future__ import print_function import os,sys,tempfile import unittest +from rdkit import RDConfig,rdBase from rdkit import DataStructs from rdkit import Chem +from rdkit import six def feq(v1,v2,tol2=1e-4): return abs(v1-v2)<=tol2 @@ -35,34 +37,34 @@ class TestCase(unittest.TestCase): def test1Table(self): tbl = Chem.GetPeriodicTable() - self.failUnless(tbl) + self.assertTrue(tbl) - self.failUnless(feq(tbl.GetAtomicWeight(6),12.011)) - self.failUnless(feq(tbl.GetAtomicWeight("C"),12.011)) - self.failUnless(tbl.GetAtomicNumber('C')==6) - self.failUnless(feq(tbl.GetRvdw(6),1.950)) - self.failUnless(feq(tbl.GetRvdw("C"),1.950)) - self.failUnless(feq(tbl.GetRcovalent(6),0.680)) - self.failUnless(feq(tbl.GetRcovalent("C"),0.680)) - self.failUnless(tbl.GetDefaultValence(6)==4) - self.failUnless(tbl.GetDefaultValence("C")==4) - self.failUnless(tuple(tbl.GetValenceList(6))==(4,)) - self.failUnless(tuple(tbl.GetValenceList("C"))==(4,)) - self.failUnless(tuple(tbl.GetValenceList(16))==(2,4,6)) - self.failUnless(tuple(tbl.GetValenceList("S"))==(2,4,6)) - self.failUnless(tbl.GetNOuterElecs(6)==4) - self.failUnless(tbl.GetNOuterElecs("C")==4) + self.assertTrue(feq(tbl.GetAtomicWeight(6),12.011)) + self.assertTrue(feq(tbl.GetAtomicWeight("C"),12.011)) + self.assertTrue(tbl.GetAtomicNumber('C')==6) + self.assertTrue(feq(tbl.GetRvdw(6),1.950)) + self.assertTrue(feq(tbl.GetRvdw("C"),1.950)) + self.assertTrue(feq(tbl.GetRcovalent(6),0.680)) + self.assertTrue(feq(tbl.GetRcovalent("C"),0.680)) + self.assertTrue(tbl.GetDefaultValence(6)==4) + self.assertTrue(tbl.GetDefaultValence("C")==4) + self.assertTrue(tuple(tbl.GetValenceList(6))==(4,)) + self.assertTrue(tuple(tbl.GetValenceList("C"))==(4,)) + self.assertTrue(tuple(tbl.GetValenceList(16))==(2,4,6)) + self.assertTrue(tuple(tbl.GetValenceList("S"))==(2,4,6)) + self.assertTrue(tbl.GetNOuterElecs(6)==4) + self.assertTrue(tbl.GetNOuterElecs("C")==4) def test2Atom(self): atom = Chem.Atom(6) - self.failUnless(atom) - self.failUnless(atom.GetAtomicNum()==6) + self.assertTrue(atom) + self.assertTrue(atom.GetAtomicNum()==6) atom.SetAtomicNum(8) - self.failUnless(atom.GetAtomicNum()==8) + self.assertTrue(atom.GetAtomicNum()==8) atom = Chem.Atom("C") - self.failUnless(atom) - self.failUnless(atom.GetAtomicNum()==6) + self.assertTrue(atom) + self.assertTrue(atom.GetAtomicNum()==6) def test3Bond(self): @@ -71,93 +73,93 @@ class TestCase(unittest.TestCase): def test4Mol(self): mol = Chem.Mol() - self.failUnless(mol) + self.assertTrue(mol) def test5Smiles(self): mol = Chem.MolFromSmiles('n1ccccc1') - self.failUnless(mol) - self.failUnless(mol.GetNumAtoms()==6) - self.failUnless(mol.GetNumAtoms(1)==6) - self.failUnless(mol.GetNumAtoms(0)==11) + self.assertTrue(mol) + self.assertTrue(mol.GetNumAtoms()==6) + self.assertTrue(mol.GetNumAtoms(1)==6) + self.assertTrue(mol.GetNumAtoms(0)==11) at = mol.GetAtomWithIdx(2) - self.failUnless(at.GetAtomicNum()==6) + self.assertTrue(at.GetAtomicNum()==6) at = mol.GetAtomWithIdx(0) - self.failUnless(at.GetAtomicNum()==7) + self.assertTrue(at.GetAtomicNum()==7) def _test6Bookmarks(self): mol = Chem.MolFromSmiles('n1ccccc1') - self.failUnless(mol) + self.assertTrue(mol) - self.failUnless(not mol.HasAtomBookmark(0)) + self.assertTrue(not mol.HasAtomBookmark(0)) mol.SetAtomBookmark(mol.GetAtomWithIdx(0),0) mol.SetAtomBookmark(mol.GetAtomWithIdx(1),1) - self.failUnless(mol.HasAtomBookmark(0)) - self.failUnless(mol.HasAtomBookmark(1)) + self.assertTrue(mol.HasAtomBookmark(0)) + self.assertTrue(mol.HasAtomBookmark(1)) if 1: - self.failUnless(not mol.HasBondBookmark(0)) - self.failUnless(not mol.HasBondBookmark(1)) + self.assertTrue(not mol.HasBondBookmark(0)) + self.assertTrue(not mol.HasBondBookmark(1)) mol.SetBondBookmark(mol.GetBondWithIdx(0),0) mol.SetBondBookmark(mol.GetBondWithIdx(1),1) - self.failUnless(mol.HasBondBookmark(0)) - self.failUnless(mol.HasBondBookmark(1)) + self.assertTrue(mol.HasBondBookmark(0)) + self.assertTrue(mol.HasBondBookmark(1)) at = mol.GetAtomWithBookmark(0) - self.failUnless(at) - self.failUnless(at.GetAtomicNum()==7) + self.assertTrue(at) + self.assertTrue(at.GetAtomicNum()==7) mol.ClearAtomBookmark(0) - self.failUnless(not mol.HasAtomBookmark(0)) - self.failUnless(mol.HasAtomBookmark(1)) + self.assertTrue(not mol.HasAtomBookmark(0)) + self.assertTrue(mol.HasAtomBookmark(1)) mol.ClearAllAtomBookmarks() - self.failUnless(not mol.HasAtomBookmark(0)) - self.failUnless(not mol.HasAtomBookmark(1)) + self.assertTrue(not mol.HasAtomBookmark(0)) + self.assertTrue(not mol.HasAtomBookmark(1)) mol.SetAtomBookmark(mol.GetAtomWithIdx(1),1) if 1: - self.failUnless(mol.HasBondBookmark(0)) - self.failUnless(mol.HasBondBookmark(1)) + self.assertTrue(mol.HasBondBookmark(0)) + self.assertTrue(mol.HasBondBookmark(1)) bond = mol.GetBondWithBookmark(0) - self.failUnless(bond) + self.assertTrue(bond) mol.ClearBondBookmark(0) - self.failUnless(not mol.HasBondBookmark(0)) - self.failUnless(mol.HasBondBookmark(1)) + self.assertTrue(not mol.HasBondBookmark(0)) + self.assertTrue(mol.HasBondBookmark(1)) mol.ClearAllBondBookmarks() - self.failUnless(not mol.HasBondBookmark(0)) - self.failUnless(not mol.HasBondBookmark(1)) + self.assertTrue(not mol.HasBondBookmark(0)) + self.assertTrue(not mol.HasBondBookmark(1)) - self.failUnless(mol.HasAtomBookmark(1)) + self.assertTrue(mol.HasAtomBookmark(1)) def test7Atom(self): mol = Chem.MolFromSmiles('n1ccccc1C[CH2-]') - self.failUnless(mol) + self.assertTrue(mol) Chem.SanitizeMol(mol) a0 = mol.GetAtomWithIdx(0) a1 = mol.GetAtomWithIdx(1) a6 = mol.GetAtomWithIdx(6) a7 = mol.GetAtomWithIdx(7) - self.failUnless(a0.GetAtomicNum()==7) - self.failUnless(a0.GetSymbol()=='N') - self.failUnless(a0.GetIdx()==0) + self.assertTrue(a0.GetAtomicNum()==7) + self.assertTrue(a0.GetSymbol()=='N') + self.assertTrue(a0.GetIdx()==0) aList = [a0,a1,a6,a7] - self.failUnless(a0.GetDegree()==2) - self.failUnless(a1.GetDegree()==2) - self.failUnless(a6.GetDegree()==2) - self.failUnless(a7.GetDegree()==1) - self.failUnless([x.GetDegree() for x in aList]==[2,2,2,1]) + self.assertTrue(a0.GetDegree()==2) + self.assertTrue(a1.GetDegree()==2) + self.assertTrue(a6.GetDegree()==2) + self.assertTrue(a7.GetDegree()==1) + self.assertTrue([x.GetDegree() for x in aList]==[2,2,2,1]) - self.failUnless([x.GetTotalNumHs() for x in aList]==[0,1,2,2]) - self.failUnless([x.GetNumImplicitHs() for x in aList]==[0,1,2,0]) - self.failUnless([x.GetExplicitValence() for x in aList]==[3,3,2,3]) - self.failUnless([x.GetImplicitValence() for x in aList]==[0,1,2,0]) - self.failUnless([x.GetFormalCharge() for x in aList]==[0,0,0,-1]) - self.failUnless([x.GetNoImplicit() for x in aList]==[0,0,0,1]) - self.failUnless([x.GetNumExplicitHs() for x in aList]==[0,0,0,2]) - self.failUnless([x.GetIsAromatic() for x in aList]==[1,1,0,0]) - self.failUnless([x.GetHybridization() for x in aList]==[Chem.HybridizationType.SP2,Chem.HybridizationType.SP2, + self.assertTrue([x.GetTotalNumHs() for x in aList]==[0,1,2,2]) + self.assertTrue([x.GetNumImplicitHs() for x in aList]==[0,1,2,0]) + self.assertTrue([x.GetExplicitValence() for x in aList]==[3,3,2,3]) + self.assertTrue([x.GetImplicitValence() for x in aList]==[0,1,2,0]) + self.assertTrue([x.GetFormalCharge() for x in aList]==[0,0,0,-1]) + self.assertTrue([x.GetNoImplicit() for x in aList]==[0,0,0,1]) + self.assertTrue([x.GetNumExplicitHs() for x in aList]==[0,0,0,2]) + self.assertTrue([x.GetIsAromatic() for x in aList]==[1,1,0,0]) + self.assertTrue([x.GetHybridization() for x in aList]==[Chem.HybridizationType.SP2,Chem.HybridizationType.SP2, Chem.HybridizationType.SP3,Chem.HybridizationType.SP3],\ [x.GetHybridization() for x in aList]) @@ -165,7 +167,7 @@ class TestCase(unittest.TestCase): def test8Bond(self): mol = Chem.MolFromSmiles('n1ccccc1CC(=O)O') - self.failUnless(mol) + self.assertTrue(mol) Chem.SanitizeMol(mol) # note bond numbering is funny because of ring closure b0 = mol.GetBondWithIdx(0) @@ -174,56 +176,56 @@ class TestCase(unittest.TestCase): b8 = mol.GetBondWithIdx(8) bList = [b0,b6,b7,b8] - self.failUnless([x.GetBondType() for x in bList] == + self.assertTrue([x.GetBondType() for x in bList] == [Chem.BondType.AROMATIC,Chem.BondType.SINGLE, Chem.BondType.DOUBLE,Chem.BondType.SINGLE]) - self.failUnless([x.GetIsAromatic() for x in bList] == + self.assertTrue([x.GetIsAromatic() for x in bList] == [1,0,0,0]) - self.failUnlessEqual(bList[0].GetBondTypeAsDouble(),1.5) - self.failUnlessEqual(bList[1].GetBondTypeAsDouble(),1.0) - self.failUnlessEqual(bList[2].GetBondTypeAsDouble(),2.0) + self.assertEqual(bList[0].GetBondTypeAsDouble(),1.5) + self.assertEqual(bList[1].GetBondTypeAsDouble(),1.0) + self.assertEqual(bList[2].GetBondTypeAsDouble(),2.0) - self.failUnless([x.GetIsConjugated()!=0 for x in bList] == + self.assertTrue([x.GetIsConjugated()!=0 for x in bList] == [1,0,1,1],[x.GetIsConjugated()!=0 for x in bList]) - self.failUnless([x.GetBeginAtomIdx() for x in bList] == + self.assertTrue([x.GetBeginAtomIdx() for x in bList] == [0,6,7,7],[x.GetBeginAtomIdx() for x in bList]) - self.failUnless([x.GetBeginAtom().GetIdx() for x in bList] == + self.assertTrue([x.GetBeginAtom().GetIdx() for x in bList] == [0,6,7,7]) - self.failUnless([x.GetEndAtomIdx() for x in bList] == + self.assertTrue([x.GetEndAtomIdx() for x in bList] == [1,7,8,9]) - self.failUnless([x.GetEndAtom().GetIdx() for x in bList] == + self.assertTrue([x.GetEndAtom().GetIdx() for x in bList] == [1,7,8,9]) def test9Smarts(self): query1 = Chem.MolFromSmarts('C(=O)O') - self.failUnless(query1) + self.assertTrue(query1) query2 = Chem.MolFromSmarts('C(=O)[O,N]') - self.failUnless(query2) + self.assertTrue(query2) query3 = Chem.MolFromSmarts('[$(C(=O)O)]') - self.failUnless(query3) + self.assertTrue(query3) mol = Chem.MolFromSmiles('CCC(=O)O') - self.failUnless(mol) + self.assertTrue(mol) - self.failUnless(mol.HasSubstructMatch(query1)) - self.failUnless(mol.HasSubstructMatch(query2)) - self.failUnless(mol.HasSubstructMatch(query3)) + self.assertTrue(mol.HasSubstructMatch(query1)) + self.assertTrue(mol.HasSubstructMatch(query2)) + self.assertTrue(mol.HasSubstructMatch(query3)) mol = Chem.MolFromSmiles('CCC(=O)N') - self.failUnless(mol) + self.assertTrue(mol) - self.failUnless(not mol.HasSubstructMatch(query1)) - self.failUnless(mol.HasSubstructMatch(query2)) - self.failUnless(not mol.HasSubstructMatch(query3)) + self.assertTrue(not mol.HasSubstructMatch(query1)) + self.assertTrue(mol.HasSubstructMatch(query2)) + self.assertTrue(not mol.HasSubstructMatch(query3)) def test10Iterators(self): mol = Chem.MolFromSmiles('CCOC') - self.failUnless(mol) + self.assertTrue(mol) for atom in mol.GetAtoms(): - self.failUnless(atom) + self.assertTrue(atom) ats = mol.GetAtoms() try: ats[1] @@ -231,18 +233,18 @@ class TestCase(unittest.TestCase): ok = 0 else: ok = 1 - self.failUnless(ok) + self.assertTrue(ok) try: ats[12] except IndexError: ok = 1 else: ok = 0 - self.failUnless(ok) + self.assertTrue(ok) if 0: for atom in mol.GetHeteros(): - self.failUnless(atom) + self.assertTrue(atom) ats = mol.GetHeteros() try: ats[0] @@ -250,19 +252,19 @@ class TestCase(unittest.TestCase): ok = 0 else: ok = 1 - self.failUnless(ok) - self.failUnless(ats[0].GetIdx()==2) + self.assertTrue(ok) + self.assertTrue(ats[0].GetIdx()==2) try: ats[12] except IndexError: ok = 1 else: ok = 0 - self.failUnless(ok) + self.assertTrue(ok) for bond in mol.GetBonds(): - self.failUnless(bond) + self.assertTrue(bond) bonds = mol.GetBonds() try: bonds[1] @@ -270,19 +272,19 @@ class TestCase(unittest.TestCase): ok = 0 else: ok = 1 - self.failUnless(ok) + self.assertTrue(ok) try: bonds[12] except IndexError: ok = 1 else: ok = 0 - self.failUnless(ok) + self.assertTrue(ok) if 0: mol = Chem.MolFromSmiles('c1ccccc1C') for atom in mol.GetAromaticAtoms(): - self.failUnless(atom) + self.assertTrue(atom) ats = mol.GetAromaticAtoms() try: ats[0] @@ -290,333 +292,333 @@ class TestCase(unittest.TestCase): ok = 0 else: ok = 1 - self.failUnless(ok) - self.failUnless(ats[0].GetIdx()==0) - self.failUnless(ats[1].GetIdx()==1) - self.failUnless(ats[2].GetIdx()==2) + self.assertTrue(ok) + self.assertTrue(ats[0].GetIdx()==0) + self.assertTrue(ats[1].GetIdx()==1) + self.assertTrue(ats[2].GetIdx()==2) try: ats[12] except IndexError: ok = 1 else: ok = 0 - self.failUnless(ok) + self.assertTrue(ok) def test11MolOps(self) : mol = Chem.MolFromSmiles('C1=CC=C(C=C1)P(C2=CC=CC=C2)C3=CC=CC=C3') - self.failUnless(mol) + self.assertTrue(mol) smi = Chem.MolToSmiles(mol) Chem.SanitizeMol(mol) nr = Chem.GetSymmSSSR(mol) - self.failUnless((len(nr) == 3)) + self.assertTrue((len(nr) == 3)) def test12Smarts(self): query1 = Chem.MolFromSmarts('C(=O)O') - self.failUnless(query1) + self.assertTrue(query1) query2 = Chem.MolFromSmarts('C(=O)[O,N]') - self.failUnless(query2) + self.assertTrue(query2) query3 = Chem.MolFromSmarts('[$(C(=O)O)]') - self.failUnless(query3) + self.assertTrue(query3) mol = Chem.MolFromSmiles('CCC(=O)O') - self.failUnless(mol) + self.assertTrue(mol) - self.failUnless(mol.HasSubstructMatch(query1)) - self.failUnless(mol.GetSubstructMatch(query1)==(2,3,4)) - self.failUnless(mol.HasSubstructMatch(query2)) - self.failUnless(mol.GetSubstructMatch(query2)==(2,3,4)) - self.failUnless(mol.HasSubstructMatch(query3)) - self.failUnless(mol.GetSubstructMatch(query3)==(2,)) + self.assertTrue(mol.HasSubstructMatch(query1)) + self.assertTrue(mol.GetSubstructMatch(query1)==(2,3,4)) + self.assertTrue(mol.HasSubstructMatch(query2)) + self.assertTrue(mol.GetSubstructMatch(query2)==(2,3,4)) + self.assertTrue(mol.HasSubstructMatch(query3)) + self.assertTrue(mol.GetSubstructMatch(query3)==(2,)) mol = Chem.MolFromSmiles('CCC(=O)N') - self.failUnless(mol) + self.assertTrue(mol) - self.failUnless(not mol.HasSubstructMatch(query1)) - self.failUnless(not mol.GetSubstructMatch(query1)) - self.failUnless(mol.HasSubstructMatch(query2)) - self.failUnless(mol.GetSubstructMatch(query2)==(2,3,4)) - self.failUnless(not mol.HasSubstructMatch(query3)) + self.assertTrue(not mol.HasSubstructMatch(query1)) + self.assertTrue(not mol.GetSubstructMatch(query1)) + self.assertTrue(mol.HasSubstructMatch(query2)) + self.assertTrue(mol.GetSubstructMatch(query2)==(2,3,4)) + self.assertTrue(not mol.HasSubstructMatch(query3)) mol = Chem.MolFromSmiles('OC(=O)CC(=O)O') - self.failUnless(mol) - self.failUnless(mol.HasSubstructMatch(query1)) - self.failUnless(mol.GetSubstructMatch(query1)==(1,2,0)) - self.failUnless(mol.GetSubstructMatches(query1)==((1,2,0),(4,5,6))) - self.failUnless(mol.HasSubstructMatch(query2)) - self.failUnless(mol.GetSubstructMatch(query2)==(1,2,0)) - self.failUnless(mol.GetSubstructMatches(query2)==((1,2,0),(4,5,6))) - self.failUnless(mol.HasSubstructMatch(query3)) - self.failUnless(mol.GetSubstructMatches(query3)==((1,),(4,))) + self.assertTrue(mol) + self.assertTrue(mol.HasSubstructMatch(query1)) + self.assertTrue(mol.GetSubstructMatch(query1)==(1,2,0)) + self.assertTrue(mol.GetSubstructMatches(query1)==((1,2,0),(4,5,6))) + self.assertTrue(mol.HasSubstructMatch(query2)) + self.assertTrue(mol.GetSubstructMatch(query2)==(1,2,0)) + self.assertTrue(mol.GetSubstructMatches(query2)==((1,2,0),(4,5,6))) + self.assertTrue(mol.HasSubstructMatch(query3)) + self.assertTrue(mol.GetSubstructMatches(query3)==((1,),(4,))) def test13Smarts(self): # previous smarts problems: query = Chem.MolFromSmarts('N(=,-C)') - self.failUnless(query) + self.assertTrue(query) mol = Chem.MolFromSmiles('N#C') - self.failUnless(not mol.HasSubstructMatch(query)) + self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('N=C') - self.failUnless(mol.HasSubstructMatch(query)) + self.assertTrue(mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('NC') - self.failUnless(mol.HasSubstructMatch(query)) + self.assertTrue(mol.HasSubstructMatch(query)) query = Chem.MolFromSmarts('[Cl,$(O)]') mol = Chem.MolFromSmiles('C(=O)O') - self.failUnless(len(mol.GetSubstructMatches(query))==2) + self.assertTrue(len(mol.GetSubstructMatches(query))==2) mol = Chem.MolFromSmiles('C(=N)N') - self.failUnless(len(mol.GetSubstructMatches(query))==0) + self.assertTrue(len(mol.GetSubstructMatches(query))==0) query = Chem.MolFromSmarts('[$([O,S]-[!$(*=O)])]') mol = Chem.MolFromSmiles('CC(S)C(=O)O') - self.failUnless(len(mol.GetSubstructMatches(query))==1) + self.assertTrue(len(mol.GetSubstructMatches(query))==1) mol = Chem.MolFromSmiles('C(=O)O') - self.failUnless(len(mol.GetSubstructMatches(query))==0) + self.assertTrue(len(mol.GetSubstructMatches(query))==0) def test14Hs(self): m = Chem.MolFromSmiles('CC(=O)[OH]') - self.failUnlessEqual(m.GetNumAtoms(),4) + self.assertEqual(m.GetNumAtoms(),4) m2 = Chem.AddHs(m) - self.failUnlessEqual(m2.GetNumAtoms(),8) + self.assertEqual(m2.GetNumAtoms(),8) m2 = Chem.RemoveHs(m2) - self.failUnlessEqual(m2.GetNumAtoms(),4) + self.assertEqual(m2.GetNumAtoms(),4) m = Chem.MolFromSmiles('CC[H]',False) - self.failUnlessEqual(m.GetNumAtoms(),3) + self.assertEqual(m.GetNumAtoms(),3) m2 = Chem.MergeQueryHs(m) - self.failUnlessEqual(m2.GetNumAtoms(),2) - self.failUnless(m2.GetAtomWithIdx(1).HasQuery()) + self.assertEqual(m2.GetNumAtoms(),2) + self.assertTrue(m2.GetAtomWithIdx(1).HasQuery()) def test15Neighbors(self): m = Chem.MolFromSmiles('CC(=O)[OH]') - self.failUnless(m.GetNumAtoms()==4) + self.assertTrue(m.GetNumAtoms()==4) a = m.GetAtomWithIdx(1) ns = a.GetNeighbors() - self.failUnless(len(ns)==3) + self.assertTrue(len(ns)==3) bs = a.GetBonds() - self.failUnless(len(bs)==3) + self.assertTrue(len(bs)==3) for b in bs: try: a2 = b.GetOtherAtom(a) except: a2=None - self.failUnless(a2) - self.failUnless(len(bs)==3) + self.assertTrue(a2) + self.assertTrue(len(bs)==3) def test16Pickle(self): - import cPickle + from rdkit.six.moves import cPickle m = Chem.MolFromSmiles('C1=CN=CC=C1') pkl = cPickle.dumps(m) m2 = cPickle.loads(pkl) smi1 = Chem.MolToSmiles(m) smi2 = Chem.MolToSmiles(m2) - self.failUnless(smi1==smi2) + self.assertTrue(smi1==smi2) def test16Props(self): m = Chem.MolFromSmiles('C1=CN=CC=C1') - self.failUnless(not m.HasProp('prop1')) - self.failUnless(not m.HasProp('prop2')) - self.failUnless(not m.HasProp('prop2')) + self.assertTrue(not m.HasProp('prop1')) + self.assertTrue(not m.HasProp('prop2')) + self.assertTrue(not m.HasProp('prop2')) m.SetProp('prop1','foob') - self.failUnless(not m.HasProp('prop2')) - self.failUnless(m.HasProp('prop1')) - self.failUnless(m.GetProp('prop1')=='foob') - self.failUnless(not m.HasProp('propo')) + self.assertTrue(not m.HasProp('prop2')) + self.assertTrue(m.HasProp('prop1')) + self.assertTrue(m.GetProp('prop1')=='foob') + self.assertTrue(not m.HasProp('propo')) try: m.GetProp('prop2') except KeyError: ok=1 else: ok=0 - self.failUnless(ok) + self.assertTrue(ok) # test computed properties m.SetProp('cprop1', 'foo', 1) m.SetProp('cprop2', 'foo2', 1) m.ClearComputedProps() - self.failUnless(not m.HasProp('cprop1')) - self.failUnless(not m.HasProp('cprop2')) + self.assertTrue(not m.HasProp('cprop1')) + self.assertTrue(not m.HasProp('cprop2')) def test17Kekulize(self): m = Chem.MolFromSmiles('c1ccccc1') smi = Chem.MolToSmiles(m) - self.failUnless(smi=='c1ccccc1') + self.assertTrue(smi=='c1ccccc1') Chem.Kekulize(m) smi = Chem.MolToSmiles(m) - self.failUnless(smi=='c1ccccc1') + self.assertTrue(smi=='c1ccccc1') m = Chem.MolFromSmiles('c1ccccc1') smi = Chem.MolToSmiles(m) - self.failUnless(smi=='c1ccccc1') + self.assertTrue(smi=='c1ccccc1') Chem.Kekulize(m,1) smi = Chem.MolToSmiles(m) - self.failUnless(smi=='C1=CC=CC=C1', smi) + self.assertTrue(smi=='C1=CC=CC=C1', smi) def test18Paths(self): m = Chem.MolFromSmiles("C1CC2C1CC2") - #self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) - #print Chem.FindAllPathsOfLengthN(m,3,useBonds=0) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==10, + #self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) + #print(Chem.FindAllPathsOfLengthN(m,3,useBonds=0)) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==10, Chem.FindAllPathsOfLengthN(m,2,useBonds=1)) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==14) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==14) m = Chem.MolFromSmiles('C1CC1C') - self.failUnless(m) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==4) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,4,useBonds=1))==1,Chem.FindAllPathsOfLengthN(m,4,useBonds=1)) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,5,useBonds=1))==0,Chem.FindAllPathsOfLengthN(m,5,useBonds=1)) + self.assertTrue(m) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==4) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,4,useBonds=1))==1,Chem.FindAllPathsOfLengthN(m,4,useBonds=1)) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,5,useBonds=1))==0,Chem.FindAllPathsOfLengthN(m,5,useBonds=1)) # # Hexane example from Hall-Kier Rev.Comp.Chem. paper # Rev. Comp. Chem. vol 2, 367-422, (1991) # m = Chem.MolFromSmiles("CCCCCC") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==4) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==4) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3) m = Chem.MolFromSmiles("CCC(C)CC") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==4,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==4,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) m = Chem.MolFromSmiles("CCCC(C)C") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3) m = Chem.MolFromSmiles("CC(C)C(C)C") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==6) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==4) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==6) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==4) m = Chem.MolFromSmiles("CC(C)(C)CC") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==7) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==5) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==7) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==3,Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) m = Chem.MolFromSmiles("C1CCCCC1") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==6) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==6) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==6) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==6) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==6) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==6) m = Chem.MolFromSmiles("C1CC2C1CC2") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==10, + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==10, Chem.FindAllPathsOfLengthN(m,2,useBonds=1)) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==14) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==14) m = Chem.MolFromSmiles("CC2C1CCC12") - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==11) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,1,useBonds=1))==7) + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,2,useBonds=1))==11) # FIX: this result disagrees with the paper (which says 13), # but it seems right - self.failUnless(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==15, + self.assertTrue(len(Chem.FindAllPathsOfLengthN(m,3,useBonds=1))==15, Chem.FindAllPathsOfLengthN(m,3,useBonds=1)) def test19Subgraphs(self): m = Chem.MolFromSmiles('C1CC1C') - self.failUnless(m) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1,0))==4) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==4) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,4))==1) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,5))==0) + self.assertTrue(m) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1,0))==4) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==4) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,4))==1) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,5))==0) # # Hexane example from Hall-Kier Rev.Comp.Chem. paper # Rev. Comp. Chem. vol 2, 367-422, (1991) # m = Chem.MolFromSmiles("CCCCCC") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==4) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==3) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==4) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==3) l = Chem.FindAllSubgraphsOfLengthMToN(m,1,3) - self.failUnlessEqual(len(l),3) - self.failUnlessEqual(len(l[0]),5) - self.failUnlessEqual(len(l[1]),4) - self.failUnlessEqual(len(l[2]),3) - self.failUnlessRaises(ValueError,lambda :Chem.FindAllSubgraphsOfLengthMToN(m,4,3)) + self.assertEqual(len(l),3) + self.assertEqual(len(l[0]),5) + self.assertEqual(len(l[1]),4) + self.assertEqual(len(l[2]),3) + self.assertRaises(ValueError,lambda :Chem.FindAllSubgraphsOfLengthMToN(m,4,3)) m = Chem.MolFromSmiles("CCC(C)CC") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==5) m = Chem.MolFromSmiles("CCCC(C)C") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==4) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==4) m = Chem.MolFromSmiles("CC(C)C(C)C") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==6) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==6) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==6) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==6) m = Chem.MolFromSmiles("CC(C)(C)CC") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==7) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==7,Chem.FindAllSubgraphsOfLengthN(m,3)) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==5) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==7) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==7,Chem.FindAllSubgraphsOfLengthN(m,3)) m = Chem.MolFromSmiles("C1CCCCC1") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==6) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==6) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==6) - #self.failUnless(len(Chem.FindUniqueSubgraphsOfLengthN(m,1))==1) - self.failUnless(len(Chem.FindUniqueSubgraphsOfLengthN(m,2))==1) - self.failUnless(len(Chem.FindUniqueSubgraphsOfLengthN(m,3))==1) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==6) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==6) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==6) + #self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m,1))==1) + self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m,2))==1) + self.assertTrue(len(Chem.FindUniqueSubgraphsOfLengthN(m,3))==1) m = Chem.MolFromSmiles("C1CC2C1CC2") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==7) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==10) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==16) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==7) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==10) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==16) m = Chem.MolFromSmiles("CC2C1CCC12") - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,1))==7) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,2))==11) - self.failUnless(len(Chem.FindAllSubgraphsOfLengthN(m,3))==18, + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,1))==7) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,2))==11) + self.assertTrue(len(Chem.FindAllSubgraphsOfLengthN(m,3))==18, len(Chem.FindAllSubgraphsOfLengthN(m,3))) def test20IsInRing(self): m = Chem.MolFromSmiles('C1CCC1C') - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(0).IsInRingSize(4)) - self.failUnless(m.GetAtomWithIdx(1).IsInRingSize(4)) - self.failUnless(m.GetAtomWithIdx(2).IsInRingSize(4)) - self.failUnless(m.GetAtomWithIdx(3).IsInRingSize(4)) - self.failUnless(not m.GetAtomWithIdx(4).IsInRingSize(4)) + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(0).IsInRingSize(4)) + self.assertTrue(m.GetAtomWithIdx(1).IsInRingSize(4)) + self.assertTrue(m.GetAtomWithIdx(2).IsInRingSize(4)) + self.assertTrue(m.GetAtomWithIdx(3).IsInRingSize(4)) + self.assertTrue(not m.GetAtomWithIdx(4).IsInRingSize(4)) - self.failUnless(not m.GetAtomWithIdx(0).IsInRingSize(3)) - self.failUnless(not m.GetAtomWithIdx(1).IsInRingSize(3)) - self.failUnless(not m.GetAtomWithIdx(2).IsInRingSize(3)) - self.failUnless(not m.GetAtomWithIdx(3).IsInRingSize(3)) - self.failUnless(not m.GetAtomWithIdx(4).IsInRingSize(3)) + self.assertTrue(not m.GetAtomWithIdx(0).IsInRingSize(3)) + self.assertTrue(not m.GetAtomWithIdx(1).IsInRingSize(3)) + self.assertTrue(not m.GetAtomWithIdx(2).IsInRingSize(3)) + self.assertTrue(not m.GetAtomWithIdx(3).IsInRingSize(3)) + self.assertTrue(not m.GetAtomWithIdx(4).IsInRingSize(3)) - self.failUnless(m.GetBondWithIdx(0).IsInRingSize(4)) - self.failUnless(not m.GetBondWithIdx(3).IsInRingSize(4)) - self.failUnless(not m.GetBondWithIdx(0).IsInRingSize(3)) - self.failUnless(not m.GetBondWithIdx(3).IsInRingSize(3)) + self.assertTrue(m.GetBondWithIdx(0).IsInRingSize(4)) + self.assertTrue(not m.GetBondWithIdx(3).IsInRingSize(4)) + self.assertTrue(not m.GetBondWithIdx(0).IsInRingSize(3)) + self.assertTrue(not m.GetBondWithIdx(3).IsInRingSize(3)) def test21Robustification(self): ok = False @@ -629,91 +631,92 @@ class TestCase(unittest.TestCase): # ok=True except: ok=True - self.failUnless(ok ) + self.assertTrue(ok ) def test22DeleteSubstruct(self) : query = Chem.MolFromSmarts('C(=O)O') mol = Chem.MolFromSmiles('CCC(=O)O') nmol = Chem.DeleteSubstructs(mol, query) - self.failUnless(Chem.MolToSmiles(nmol) == 'CC') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') # now delete only fragments nmol = Chem.DeleteSubstructs(mol, query, 1) - self.failUnless(Chem.MolToSmiles(nmol) == 'CCC(=O)O',Chem.MolToSmiles(nmol)) + self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O',Chem.MolToSmiles(nmol)) mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') nmol = Chem.DeleteSubstructs(mol, query, 0) - self.failUnless(Chem.MolToSmiles(nmol) == 'CC') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') mol = Chem.MolFromSmiles('CCCO') nmol = Chem.DeleteSubstructs(mol, query, 0) - self.failUnless(Chem.MolToSmiles(nmol) == 'CCCO') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CCCO') # Issue 96 prevented this from working: mol = Chem.MolFromSmiles('CCC(=O)O.O=CO') nmol = Chem.DeleteSubstructs(mol, query, 1) - self.failUnless(Chem.MolToSmiles(nmol) == 'CCC(=O)O') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O') nmol = Chem.DeleteSubstructs(nmol, query, 1) - self.failUnless(Chem.MolToSmiles(nmol) == 'CCC(=O)O') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CCC(=O)O') nmol = Chem.DeleteSubstructs(nmol, query, 0) - self.failUnless(Chem.MolToSmiles(nmol) == 'CC') + self.assertTrue(Chem.MolToSmiles(nmol) == 'CC') def test23MolFileParsing(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','triazine.mol') #fileN = "../FileParsers/test_data/triazine.mol" - inD = open(fileN,'r').read() + with open(fileN,'r') as inF: + inD = inF.read() m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==9) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==9) m1 = Chem.MolFromMolFile(fileN) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==9) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==9) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','triazine.mof') - self.failUnlessRaises(IOError,lambda :Chem.MolFromMolFile(fileN)) + self.assertRaises(IOError,lambda :Chem.MolFromMolFile(fileN)) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','list-query.mol') query = Chem.MolFromMolFile(fileN) smi = Chem.MolToSmiles(query) - self.failUnlessEqual(smi,'c1ccccc1') + self.assertEqual(smi,'c1ccccc1') smi = Chem.MolToSmarts(query) - self.failUnlessEqual(smi,'[#6]1:[#6]:[#6]:[#6]:[#6]:[#6,#7,#15]:1',smi) + self.assertEqual(smi,'[#6]1:[#6]:[#6]:[#6]:[#6]:[#6,#7,#15]:1',smi) query = Chem.MolFromMolFile(fileN,sanitize=False) smi = Chem.MolToSmiles(query) - self.failUnlessEqual(smi,'C1=CC=CC=C1') + self.assertEqual(smi,'C1=CC=CC=C1') query.UpdatePropertyCache() smi = Chem.MolToSmarts(query) - self.failUnlessEqual(smi,'[#6]1=[#6]-[#6]=[#6]-[#6]=[#6,#7,#15]-1') + self.assertEqual(smi,'[#6]1=[#6]-[#6]=[#6]-[#6]=[#6,#7,#15]-1') smi = "C1=CC=CC=C1" mol = Chem.MolFromSmiles(smi,0) - self.failUnless(mol.HasSubstructMatch(query)) + self.assertTrue(mol.HasSubstructMatch(query)) Chem.SanitizeMol(mol) - self.failUnless(not mol.HasSubstructMatch(query)) + self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('N1=CC=CC=C1',0) - self.failUnless(mol.HasSubstructMatch(query)) + self.assertTrue(mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('S1=CC=CC=C1',0) - self.failUnless(not mol.HasSubstructMatch(query)) + self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('P1=CC=CC=C1',0) - self.failUnless(mol.HasSubstructMatch(query)) + self.assertTrue(mol.HasSubstructMatch(query)) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','issue123.mol') mol = Chem.MolFromMolFile(fileN) - self.failUnless(mol) - self.failUnlessEqual(mol.GetNumAtoms(),23) + self.assertTrue(mol) + self.assertEqual(mol.GetNumAtoms(),23) mol = Chem.MolFromMolFile(fileN,removeHs=False) - self.failUnless(mol) - self.failUnlessEqual(mol.GetNumAtoms(),39) + self.assertTrue(mol) + self.assertEqual(mol.GetNumAtoms(),39) # test23 was for Chem.DaylightFingerprint, which is deprecated @@ -721,46 +724,46 @@ class TestCase(unittest.TestCase): from rdkit import DataStructs m1 = Chem.MolFromSmiles('C1=CC=CC=C1') fp1 = Chem.RDKFingerprint(m1) - self.failUnless(len(fp1)==2048) + self.assertTrue(len(fp1)==2048) m2 = Chem.MolFromSmiles('C1=CC=CC=C1') fp2 = Chem.RDKFingerprint(m2) tmp = DataStructs.TanimotoSimilarity(fp1,fp2) - self.failUnless(tmp==1.0,tmp) + self.assertTrue(tmp==1.0,tmp) m2 = Chem.MolFromSmiles('C1=CC=CC=N1') fp2 = Chem.RDKFingerprint(m2) - self.failUnless(len(fp2)==2048) + self.assertTrue(len(fp2)==2048) tmp = DataStructs.TanimotoSimilarity(fp1,fp2) - self.failUnless(tmp<1.0,tmp) - self.failUnless(tmp>0.0,tmp) + self.assertTrue(tmp<1.0,tmp) + self.assertTrue(tmp>0.0,tmp) fp3 = Chem.RDKFingerprint(m1,tgtDensity=0.3) - self.failUnless(len(fp3)<2048) + self.assertTrue(len(fp3)<2048) m1 = Chem.MolFromSmiles('C1=CC=CC=C1') fp1 = Chem.RDKFingerprint(m1) m2 = Chem.MolFromSmiles('C1=CC=CC=N1') fp2 = Chem.RDKFingerprint(m2) - self.failIfEqual(fp1,fp2) + self.assertNotEqual(fp1,fp2) atomInvariants=[1]*6 fp1 = Chem.RDKFingerprint(m1,atomInvariants=atomInvariants) fp2 = Chem.RDKFingerprint(m2,atomInvariants=atomInvariants) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) m2 = Chem.MolFromSmiles('C1CCCCN1') fp1 = Chem.RDKFingerprint(m1,atomInvariants=atomInvariants,useBondOrder=False) fp2 = Chem.RDKFingerprint(m2,atomInvariants=atomInvariants,useBondOrder=False) - self.failUnlessEqual(fp1,fp2) + self.assertEqual(fp1,fp2) # rooted at atom m1 = Chem.MolFromSmiles('CCCCCO') fp1 = Chem.RDKFingerprint(m1,1,4,nBitsPerHash=1,fromAtoms=[0]) - self.failUnlessEqual(fp1.GetNumOnBits(),4) + self.assertEqual(fp1.GetNumOnBits(),4) m1 = Chem.MolFromSmiles('CCCCCO') fp1 = Chem.RDKFingerprint(m1,1,4,nBitsPerHash=1,fromAtoms=[0,5]) - self.failUnlessEqual(fp1.GetNumOnBits(),8) + self.assertEqual(fp1.GetNumOnBits(),8) # test sf.net issue 270: fp1 = Chem.RDKFingerprint(m1,atomInvariants=[x.GetAtomicNum()+10 for x in m1.GetAtoms()]) @@ -769,12 +772,12 @@ class TestCase(unittest.TestCase): m1 = Chem.MolFromSmiles('CCCO') l=[] fp1 = Chem.RDKFingerprint(m1,minPath=1,maxPath=2,nBitsPerHash=1,atomBits=l) - self.failUnlessEqual(fp1.GetNumOnBits(),4) - self.failUnlessEqual(len(l),m1.GetNumAtoms()) - self.failUnlessEqual(len(l[0]),2) - self.failUnlessEqual(len(l[1]),3) - self.failUnlessEqual(len(l[2]),4) - self.failUnlessEqual(len(l[3]),2) + self.assertEqual(fp1.GetNumOnBits(),4) + self.assertEqual(len(l),m1.GetNumAtoms()) + self.assertEqual(len(l[0]),2) + self.assertEqual(len(l[1]),3) + self.assertEqual(len(l[2]),4) + self.assertEqual(len(l[3]),2) def test25SDMolSupplier(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', @@ -787,66 +790,67 @@ class TestCase(unittest.TestCase): chgs192 = {8:1, 11:1, 15:-1, 18:-1, 20:1, 21:1, 23:-1, 25:-1} i = 0 for mol in sdSup : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192") : # test parsed charges on one of the molecules for id in chgs192.keys() : - self.failUnless(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) - self.failUnlessRaises(StopIteration,lambda:sdSup.next()) + self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) + self.assertRaises(StopIteration,lambda:six.next(sdSup)) sdSup.reset() ns = [mol.GetProp("_Name") for mol in sdSup] - self.failUnless(ns == molNames) + self.assertTrue(ns == molNames) sdSup = Chem.SDMolSupplier(fileN, 0) for mol in sdSup : - self.failUnless(not mol.HasProp("numArom")) + self.assertTrue(not mol.HasProp("numArom")) sdSup = Chem.SDMolSupplier(fileN) - self.failUnless(len(sdSup) == 16) + self.assertTrue(len(sdSup) == 16) mol = sdSup[5] - self.failUnless(mol.GetProp("_Name") == "170") + self.assertTrue(mol.GetProp("_Name") == "170") # test handling of H removal: fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','withHs.sdf') sdSup = Chem.SDMolSupplier(fileN) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==23) - m = sdSup.next() - self.failUnless(m) - print m.GetNumAtoms() - self.failUnless(m.GetNumAtoms()==28) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==23) + m = six.next(sdSup) + self.assertTrue(m) + print(m.GetNumAtoms()) + self.assertTrue(m.GetNumAtoms()==28) sdSup = Chem.SDMolSupplier(fileN,removeHs=False) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==39) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==30) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==39) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==30) - d = file(fileN,'r').read() + with open(fileN,'r') as dFile: + d = dFile.read() sdSup.SetData(d) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==23) - m = sdSup.next() - self.failUnless(m) - print m.GetNumAtoms() - self.failUnless(m.GetNumAtoms()==28) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==23) + m = six.next(sdSup) + self.assertTrue(m) + print(m.GetNumAtoms()) + self.assertTrue(m.GetNumAtoms()==28) sdSup.SetData(d,removeHs=False) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==39) - m = sdSup.next() - self.failUnless(m) - self.failUnless(m.GetNumAtoms()==30) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==39) + m = six.next(sdSup) + self.assertTrue(m) + self.assertTrue(m.GetNumAtoms()==30) def test26SmiMolSupplier(self) : @@ -855,12 +859,12 @@ class TestCase(unittest.TestCase): #fileN = "../FileParsers/test_data/first_200.tpsa.csv" smiSup = Chem.SmilesMolSupplier(fileN, ",", 0, -1) mol = smiSup[16]; - self.failUnless(mol.GetProp("TPSA") == "46.25") + self.assertTrue(mol.GetProp("TPSA") == "46.25") mol = smiSup[8]; - self.failUnless(mol.GetProp("TPSA") == "65.18") + self.assertTrue(mol.GetProp("TPSA") == "65.18") - self.failUnless(len(smiSup) == 200) + self.assertTrue(len(smiSup) == 200) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','fewSmi.csv') @@ -871,16 +875,17 @@ class TestCase(unittest.TestCase): names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] i = 0 for mol in smiSup: - self.failUnless(mol.GetProp("_Name") == names[i]) + self.assertTrue(mol.GetProp("_Name") == names[i]) i += 1 mol = smiSup[3] - self.failUnless(mol.GetProp("_Name") == "4") - self.failUnless(mol.GetProp("Column_2") == "82.78") + self.assertTrue(mol.GetProp("_Name") == "4") + self.assertTrue(mol.GetProp("Column_2") == "82.78") # and test doing a supplier from text: - inD = open(fileN,'r').read() + with open(fileN,'r') as inF: + inD = inF.read() smiSup.SetData(inD, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) @@ -888,20 +893,20 @@ class TestCase(unittest.TestCase): i = 0 # iteration interface: for mol in smiSup: - self.failUnless(mol.GetProp("_Name") == names[i]) + self.assertTrue(mol.GetProp("_Name") == names[i]) i += 1 - self.failUnless(i==10) + self.assertTrue(i==10) # random access: mol = smiSup[3] - self.failUnless(len(smiSup)==10) - self.failUnless(mol.GetProp("_Name") == "4") - self.failUnless(mol.GetProp("Column_2") == "82.78") + self.assertTrue(len(smiSup)==10) + self.assertTrue(mol.GetProp("_Name") == "4") + self.assertTrue(mol.GetProp("Column_2") == "82.78") # issue 113: smiSup.SetData(inD, delimiter=",", smilesColumn=1, nameColumn=0, titleLine=0) - self.failUnless(len(smiSup)==10) + self.assertTrue(len(smiSup)==10) # and test failure handling: inD = """mol-1,CCC @@ -913,9 +918,9 @@ mol-4,CCOC smilesColumn=1, nameColumn=0, titleLine=0) # there are 4 entries in the supplier: - self.failUnless(len(smiSup)==4) + self.assertTrue(len(smiSup)==4) # but the 3rd is a None: - self.failUnless(smiSup[2] is None) + self.assertTrue(smiSup[2] is None) text="Id SMILES Column_2\n"+\ @@ -925,14 +930,14 @@ mol-4,CCOC smiSup.SetData(text, delimiter=" ", smilesColumn=1, nameColumn=0, titleLine=1) - self.failUnless(len(smiSup)==3) - self.failUnless(smiSup[0]) - self.failUnless(smiSup[1]) - self.failUnless(smiSup[2]) + self.assertTrue(len(smiSup)==3) + self.assertTrue(smiSup[0]) + self.assertTrue(smiSup[1]) + self.assertTrue(smiSup[2]) m = [x for x in smiSup] - self.failUnless(smiSup[2]) - self.failUnless(len(m)==3) - self.failUnless(m[0].GetProp("Column_2")=="1.0") + self.assertTrue(smiSup[2]) + self.assertTrue(len(m)==3) + self.assertTrue(m[0].GetProp("Column_2")=="1.0") # test simple parsing and Issue 114: smis = ['CC','CCC','CCOC','CCCOCC','CCCOCCC'] @@ -940,17 +945,17 @@ mol-4,CCOC smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) - self.failUnless(len(smiSup)==5) + self.assertTrue(len(smiSup)==5) m = [x for x in smiSup] - self.failUnless(smiSup[4]) - self.failUnless(len(m)==5) + self.assertTrue(smiSup[4]) + self.assertTrue(len(m)==5) # order dependance: smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) - self.failUnless(smiSup[4]) - self.failUnless(len(smiSup)==5) + self.assertTrue(smiSup[4]) + self.assertTrue(len(smiSup)==5) # this was a nasty BC: # asking for a particular entry with a higher index than what we've @@ -960,9 +965,9 @@ mol-4,CCOC smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, titleLine=0) - m = smiSup.next() + m = six.next(smiSup) m = smiSup[3] - self.failUnless(len(smiSup)==4) + self.assertTrue(len(smiSup)==4) try: smiSup[4] @@ -970,7 +975,7 @@ mol-4,CCOC ok=1 else: ok=0 - self.failUnless(ok) + self.assertTrue(ok) smiSup.SetData(inD, delimiter=",", smilesColumn=0, nameColumn=-1, @@ -981,9 +986,9 @@ mol-4,CCOC ok=1 else: ok=0 - self.failUnless(ok) + self.assertTrue(ok) sys.stderr.write('>>> This may result in an infinite loop. It should finish almost instantly\n') - self.failUnless(len(smiSup)==4) + self.assertTrue(len(smiSup)==4) sys.stderr.write('<<< OK, it finished.\n') @@ -1012,9 +1017,9 @@ mol-4,CCOC smiSup = Chem.SmilesMolSupplier(ofile) i = 0 for mol in smiSup: - #print [repr(x) for x in mol.GetPropNames()] - self.failUnless(mol.GetProp("_Name") == names[i]) - self.failUnless(mol.GetProp("Column_2") == props[i]) + #print([repr(x) for x in mol.GetPropNames()]) + self.assertTrue(mol.GetProp("_Name") == names[i]) + self.assertTrue(mol.GetProp("Column_2") == props[i]) i += 1 def writerSDFile(self) : @@ -1039,14 +1044,14 @@ mol-4,CCOC i = 0 for mol in sdSup : - #print 'mol:',mol - #print '\t',molNames[i] - self.failUnless(mol.GetProp("_Name") == molNames[i]) + #print('mol:',mol) + #print('\t',molNames[i]) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192") : # test parsed charges on one of the molecules for id in chgs192.keys() : - self.failUnless(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) + self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) def test30Issues109and110(self) : """ issues 110 and 109 were both related to handling of explicit Hs in @@ -1054,57 +1059,57 @@ mol-4,CCOC """ m1 = Chem.MolFromSmiles('N12[CH](SC(C)(C)[CH]1C(O)=O)[CH](C2=O)NC(=O)[CH](N)c3ccccc3') - self.failUnless(m1.GetNumAtoms()==24) + self.assertTrue(m1.GetNumAtoms()==24) m2 = Chem.MolFromSmiles('C1C=C([CH](N)C(=O)N[C]2([H])[C]3([H])SC(C)(C)[CH](C(=O)O)N3C(=O)2)C=CC=1') - self.failUnless(m2.GetNumAtoms()==24) + self.assertTrue(m2.GetNumAtoms()==24) smi1 = Chem.MolToSmiles(m1) smi2 = Chem.MolToSmiles(m2) - self.failUnless(smi1==smi2) + self.assertTrue(smi1==smi2) m1 = Chem.MolFromSmiles('[H]CCl') - self.failUnless(m1.GetNumAtoms()==2) - self.failUnless(m1.GetAtomWithIdx(0).GetNumExplicitHs()==0) + self.assertTrue(m1.GetNumAtoms()==2) + self.assertTrue(m1.GetAtomWithIdx(0).GetNumExplicitHs()==0) m1 = Chem.MolFromSmiles('[H][CH2]Cl') - self.failUnless(m1.GetNumAtoms()==2) - self.failUnless(m1.GetAtomWithIdx(0).GetNumExplicitHs()==3) + self.assertTrue(m1.GetNumAtoms()==2) + self.assertTrue(m1.GetAtomWithIdx(0).GetNumExplicitHs()==3) m2 = Chem.AddHs(m1) - self.failUnless(m2.GetNumAtoms()==5) + self.assertTrue(m2.GetNumAtoms()==5) m2 = Chem.RemoveHs(m2) - self.failUnless(m2.GetNumAtoms()==2) + self.assertTrue(m2.GetNumAtoms()==2) def test31ChiralitySmiles(self) : m1 = Chem.MolFromSmiles('F[C@](Br)(I)Cl') - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==5) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==5) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I',Chem.MolToSmiles(m1,1)) m1 = Chem.MolFromSmiles('CC1C[C@@]1(Cl)F') - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) m1 = Chem.MolFromSmiles('CC1C[C@]1(Cl)F') - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m1,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m1,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m1,1)) def test31aChiralitySubstructs(self) : m1 = Chem.MolFromSmiles('CC1C[C@@]1(Cl)F') - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) m2 = Chem.MolFromSmiles('CC1C[C@]1(Cl)F') - self.failUnless(m2 is not None) - self.failUnless(m2.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m2,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m2,1)) + self.assertTrue(m2 is not None) + self.assertTrue(m2.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m2,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m2,1)) - self.failUnless(m1.HasSubstructMatch(m1)) - self.failUnless(m1.HasSubstructMatch(m2)) - self.failUnless(m1.HasSubstructMatch(m1,useChirality=True)) - self.failUnless(not m1.HasSubstructMatch(m2,useChirality=True)) + self.assertTrue(m1.HasSubstructMatch(m1)) + self.assertTrue(m1.HasSubstructMatch(m2)) + self.assertTrue(m1.HasSubstructMatch(m1,useChirality=True)) + self.assertTrue(not m1.HasSubstructMatch(m2,useChirality=True)) @@ -1126,9 +1131,9 @@ mol-4,CCOC M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==5) - self.failUnless(smi=='F[C@](Cl)(Br)I',smi) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==5) + self.assertTrue(smi=='F[C@](Cl)(Br)I',smi) inD = """chiral2.cdxml ChemDraw10160314052D @@ -1146,9 +1151,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==5) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@@](Cl)(Br)I') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==5) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@@](Cl)(Br)I') inD = """chiral1.mol ChemDraw10160313232D @@ -1166,9 +1171,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==5) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==5) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I') inD = """chiral1.mol ChemDraw10160313232D @@ -1186,9 +1191,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==5) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==5) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@](Cl)(Br)I') inD = """chiral3.mol ChemDraw10160314362D @@ -1205,9 +1210,9 @@ M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==4) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==4) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') inD = """chiral4.mol ChemDraw10160314362D @@ -1224,9 +1229,9 @@ M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==4) - self.failUnless(Chem.MolToSmiles(m1,1)=='FN(Cl)Br') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==4) + self.assertTrue(Chem.MolToSmiles(m1,1)=='FN(Cl)Br') inD = """chiral5.mol ChemDraw10160314362D @@ -1244,9 +1249,9 @@ M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==4) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[N@H+](Cl)Br') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==4) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[N@H+](Cl)Br') inD="""Case 10-14-3 ChemDraw10140308512D @@ -1262,9 +1267,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==4) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==4) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') inD="""Case 10-14-4 ChemDraw10140308512D @@ -1281,9 +1286,9 @@ M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==4) - self.failUnless(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==4) + self.assertTrue(Chem.MolToSmiles(m1,1)=='F[C@H](Cl)Br') inD="""chiral4.mol ChemDraw10160315172D @@ -1304,9 +1309,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m1,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m1,1)=='CC1C[C@@]1(F)Cl',Chem.MolToSmiles(m1,1)) inD="""chiral4.mol ChemDraw10160315172D @@ -1327,9 +1332,9 @@ M END M END """ m1 = Chem.MolFromMolBlock(inD) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==6) - self.failUnless(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==6) + self.assertTrue(Chem.MolToSmiles(m1,1)=='CC1C[C@]1(F)Cl',Chem.MolToSmiles(m1,1)) def test33Issue65(self) : """ issue 65 relates to handling of [H] in SMARTS @@ -1342,17 +1347,17 @@ M END q2 = Chem.MolFromSmarts('O[C;H1]',1) q3 = Chem.MolFromSmarts('O[C;H1][H]',1) - self.failUnless(not m1.HasSubstructMatch(q1)) - self.failUnless(not m1.HasSubstructMatch(q2)) - self.failUnless(not m1.HasSubstructMatch(q3)) + self.assertTrue(not m1.HasSubstructMatch(q1)) + self.assertTrue(not m1.HasSubstructMatch(q2)) + self.assertTrue(not m1.HasSubstructMatch(q3)) - self.failUnless(m2.HasSubstructMatch(q1)) - self.failUnless(m2.HasSubstructMatch(q2)) - self.failUnless(m2.HasSubstructMatch(q3)) + self.assertTrue(m2.HasSubstructMatch(q1)) + self.assertTrue(m2.HasSubstructMatch(q2)) + self.assertTrue(m2.HasSubstructMatch(q3)) - self.failUnless(m3.HasSubstructMatch(q1)) - self.failUnless(not m3.HasSubstructMatch(q2)) - self.failUnless(not m3.HasSubstructMatch(q3)) + self.assertTrue(m3.HasSubstructMatch(q1)) + self.assertTrue(not m3.HasSubstructMatch(q2)) + self.assertTrue(not m3.HasSubstructMatch(q3)) m1H = Chem.AddHs(m1) m2H = Chem.AddHs(m2) @@ -1361,18 +1366,18 @@ M END q2 = Chem.MolFromSmarts('O[C;H1]') q3 = Chem.MolFromSmarts('O[C;H1][H]') - self.failUnless(not m1H.HasSubstructMatch(q1)) - self.failUnless(not m1H.HasSubstructMatch(q2)) - self.failUnless(not m1H.HasSubstructMatch(q3)) + self.assertTrue(not m1H.HasSubstructMatch(q1)) + self.assertTrue(not m1H.HasSubstructMatch(q2)) + self.assertTrue(not m1H.HasSubstructMatch(q3)) #m2H.Debug() - self.failUnless(m2H.HasSubstructMatch(q1)) - self.failUnless(m2H.HasSubstructMatch(q2)) - self.failUnless(m2H.HasSubstructMatch(q3)) + self.assertTrue(m2H.HasSubstructMatch(q1)) + self.assertTrue(m2H.HasSubstructMatch(q2)) + self.assertTrue(m2H.HasSubstructMatch(q3)) - self.failUnless(m3H.HasSubstructMatch(q1)) - self.failUnless(not m3H.HasSubstructMatch(q2)) - self.failUnless(not m3H.HasSubstructMatch(q3)) + self.assertTrue(m3H.HasSubstructMatch(q1)) + self.assertTrue(not m3H.HasSubstructMatch(q2)) + self.assertTrue(not m3H.HasSubstructMatch(q3)) def test34Issue124(self) : """ issue 124 relates to calculation of the distance matrix @@ -1380,62 +1385,62 @@ M END """ m = Chem.MolFromSmiles('CC=C') d = Chem.GetDistanceMatrix(m,0) - self.failUnless(feq(d[0,1],1.0)) - self.failUnless(feq(d[0,2],2.0)) + self.assertTrue(feq(d[0,1],1.0)) + self.assertTrue(feq(d[0,2],2.0)) # force an update: d = Chem.GetDistanceMatrix(m,1,0,1) - self.failUnless(feq(d[0,1],1.0)) - self.failUnless(feq(d[0,2],1.5)) + self.assertTrue(feq(d[0,1],1.0)) + self.assertTrue(feq(d[0,2],1.5)) def test35ChiralityPerception(self) : """ Test perception of chirality and CIP encoding """ m = Chem.MolFromSmiles('F[C@]([C@])(Cl)Br') Chem.AssignStereochemistry(m,1) - self.failUnless(m.GetAtomWithIdx(1).HasProp('_CIPCode')) - self.failIf(m.GetAtomWithIdx(2).HasProp('_CIPCode')) + self.assertTrue(m.GetAtomWithIdx(1).HasProp('_CIPCode')) + self.assertFalse(m.GetAtomWithIdx(2).HasProp('_CIPCode')) Chem.RemoveStereochemistry(m) - self.failIf(m.GetAtomWithIdx(1).HasProp('_CIPCode')) + self.assertFalse(m.GetAtomWithIdx(1).HasProp('_CIPCode')) m = Chem.MolFromSmiles('F[C@H](C)C') Chem.AssignStereochemistry(m,1) - self.failUnless(m.GetAtomWithIdx(1).GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED) - self.failIf(m.GetAtomWithIdx(1).HasProp('_CIPCode')) + self.assertTrue(m.GetAtomWithIdx(1).GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED) + self.assertFalse(m.GetAtomWithIdx(1).HasProp('_CIPCode')) m = Chem.MolFromSmiles('F\\C=C/Cl') - self.failUnless(m.GetBondWithIdx(0).GetStereo()==Chem.BondStereo.STEREONONE) - self.failUnless(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREOZ) + self.assertTrue(m.GetBondWithIdx(0).GetStereo()==Chem.BondStereo.STEREONONE) + self.assertTrue(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREOZ) atoms = m.GetBondWithIdx(1).GetStereoAtoms() - self.failUnless(0 in atoms) - self.failUnless(3 in atoms) - self.failUnless(m.GetBondWithIdx(2).GetStereo()==Chem.BondStereo.STEREONONE) + self.assertTrue(0 in atoms) + self.assertTrue(3 in atoms) + self.assertTrue(m.GetBondWithIdx(2).GetStereo()==Chem.BondStereo.STEREONONE) Chem.RemoveStereochemistry(m) - self.failUnless(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREONONE) + self.assertTrue(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREONONE) m = Chem.MolFromSmiles('F\\C=CCl') - self.failUnless(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREONONE) + self.assertTrue(m.GetBondWithIdx(1).GetStereo()==Chem.BondStereo.STEREONONE) def test36SubstructMatchStr(self): """ test the _SubstructMatchStr function """ query = Chem.MolFromSmarts('[n,p]1ccccc1') - self.failUnless(query) + self.assertTrue(query) mol = Chem.MolFromSmiles('N1=CC=CC=C1') - self.failUnless(mol.HasSubstructMatch(query)) - self.failUnless(Chem._HasSubstructMatchStr(mol.ToBinary(),query)) + self.assertTrue(mol.HasSubstructMatch(query)) + self.assertTrue(Chem._HasSubstructMatchStr(mol.ToBinary(),query)) mol = Chem.MolFromSmiles('S1=CC=CC=C1') - self.failUnless(not Chem._HasSubstructMatchStr(mol.ToBinary(),query)) - self.failUnless(not mol.HasSubstructMatch(query)) + self.assertTrue(not Chem._HasSubstructMatchStr(mol.ToBinary(),query)) + self.assertTrue(not mol.HasSubstructMatch(query)) mol = Chem.MolFromSmiles('P1=CC=CC=C1') - self.failUnless(mol.HasSubstructMatch(query)) - self.failUnless(Chem._HasSubstructMatchStr(mol.ToBinary(),query)) + self.assertTrue(mol.HasSubstructMatch(query)) + self.assertTrue(Chem._HasSubstructMatchStr(mol.ToBinary(),query)) def test37SanitException(self): mol = Chem.MolFromSmiles('CC(C)(C)(C)C',0) - self.failUnless(mol) - self.failUnlessRaises(ValueError,lambda:Chem.SanitizeMol(mol)) + self.assertTrue(mol) + self.assertRaises(ValueError,lambda:Chem.SanitizeMol(mol)) def test38TDTSuppliers(self): data="""$SMI @@ -1454,24 +1459,24 @@ CAS<~> suppl.SetData(data,"CAS") i=0; for mol in suppl: - self.failUnless(mol) - self.failUnless(mol.GetNumAtoms()) - self.failUnless(mol.HasProp("CAS")) - self.failUnless(mol.HasProp("_Name")) - self.failUnless(mol.GetProp("CAS")==mol.GetProp("_Name")) - self.failUnless(mol.GetNumConformers()==0) + self.assertTrue(mol) + self.assertTrue(mol.GetNumAtoms()) + self.assertTrue(mol.HasProp("CAS")) + self.assertTrue(mol.HasProp("_Name")) + self.assertTrue(mol.GetProp("CAS")==mol.GetProp("_Name")) + self.assertTrue(mol.GetNumConformers()==0) i+=1 - self.failUnless(i==4) - self.failUnless(len(suppl)==4) + self.assertTrue(i==4) + self.assertTrue(len(suppl)==4) def test38Issue266(self): """ test issue 266: generation of kekulized smiles""" mol = Chem.MolFromSmiles('c1ccccc1') Chem.Kekulize(mol) smi = Chem.MolToSmiles(mol) - self.failUnless(smi=='c1ccccc1') + self.assertTrue(smi=='c1ccccc1') smi = Chem.MolToSmiles(mol,kekuleSmiles=True) - self.failUnless(smi=='C1=CC=CC=C1') + self.assertTrue(smi=='C1=CC=CC=C1') def test39Issue273(self): """ test issue 273: MolFileComments and MolFileInfo props ending up in SD files @@ -1482,8 +1487,8 @@ CAS<~> suppl = Chem.SDMolSupplier(fileN) ms = [x for x in suppl] for m in ms: - self.failUnless(m.HasProp('_MolFileInfo')) - self.failUnless(m.HasProp('_MolFileComments')) + self.assertTrue(m.HasProp('_MolFileInfo')) + self.assertTrue(m.HasProp('_MolFileComments')) fName = tempfile.mktemp('.sdf') w = Chem.SDWriter(fName) w.SetProps(ms[0].GetPropNames()) @@ -1491,10 +1496,11 @@ CAS<~> w.write(m) w = None - txt= file(fName,'r').read() + with open(fName, 'r') as txtFile: + txt= txtFile.read() os.unlink(fName) - self.failUnless(txt.find('MolFileInfo')==-1) - self.failUnless(txt.find('MolFileComments')==-1) + self.assertTrue(txt.find('MolFileInfo')==-1) + self.assertTrue(txt.find('MolFileComments')==-1) def test40SmilesRootedAtAtom(self): @@ -1504,8 +1510,8 @@ CAS<~> smi = 'CN(C)C' m = Chem.MolFromSmiles(smi) - self.failUnless(Chem.MolToSmiles(m)=='CN(C)C') - self.failUnless(Chem.MolToSmiles(m,rootedAtAtom=1)=='N(C)(C)C') + self.assertTrue(Chem.MolToSmiles(m)=='CN(C)C') + self.assertTrue(Chem.MolToSmiles(m,rootedAtAtom=1)=='N(C)(C)C') def test41SetStreamIndices(self) : @@ -1517,68 +1523,69 @@ CAS<~> indices=[0, 2136, 6198, 8520, 11070, 12292, 14025, 15313, 17313, 20125, 22231, 23729, 26147, 28331, 32541, 33991] sdSup._SetStreamIndices(indices) - self.failUnless(len(sdSup) == 16) + self.assertTrue(len(sdSup) == 16) mol = sdSup[5] - self.failUnless(mol.GetProp("_Name") == "170") + self.assertTrue(mol.GetProp("_Name") == "170") i = 0 for mol in sdSup : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 ns = [mol.GetProp("_Name") for mol in sdSup] - self.failUnless(ns == molNames) + self.assertTrue(ns == molNames) # this can also be used to skip molecules in the file: indices=[0, 6198, 12292] sdSup._SetStreamIndices(indices) - self.failUnless(len(sdSup) == 3) + self.assertTrue(len(sdSup) == 3) mol = sdSup[2] - self.failUnless(mol.GetProp("_Name") == "170") + self.assertTrue(mol.GetProp("_Name") == "170") # or to reorder them: indices=[0, 12292, 6198] sdSup._SetStreamIndices(indices) - self.failUnless(len(sdSup) == 3) + self.assertTrue(len(sdSup) == 3) mol = sdSup[1] - self.failUnless(mol.GetProp("_Name") == "170") + self.assertTrue(mol.GetProp("_Name") == "170") def test42LifeTheUniverseAndEverything(self) : - self.failUnless(True) + self.assertTrue(True) def test43TplFileParsing(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','cmpd2.tpl') m1 = Chem.MolFromTPLFile(fileN) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==12) - self.failUnless(m1.GetNumConformers()==2) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==12) + self.assertTrue(m1.GetNumConformers()==2) m1 = Chem.MolFromTPLFile(fileN,skipFirstConf=True) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==12) - self.failUnless(m1.GetNumConformers()==1) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==12) + self.assertTrue(m1.GetNumConformers()==1) - block = file(fileN,'r').read() + with open(fileN, 'r') as blockFile: + block = blockFile.read() m1 = Chem.MolFromTPLBlock(block) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==12) - self.failUnless(m1.GetNumConformers()==2) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==12) + self.assertTrue(m1.GetNumConformers()==2) def test44TplFileWriting(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','cmpd2.tpl') m1 = Chem.MolFromTPLFile(fileN) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==12) - self.failUnless(m1.GetNumConformers()==2) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==12) + self.assertTrue(m1.GetNumConformers()==2) block = Chem.MolToTPLBlock(m1) m1 = Chem.MolFromTPLBlock(block) - self.failUnless(m1 is not None) - self.failUnless(m1.GetNumAtoms()==12) - self.failUnless(m1.GetNumConformers()==2) + self.assertTrue(m1 is not None) + self.assertTrue(m1.GetNumAtoms()==12) + self.assertTrue(m1.GetNumConformers()==2) def test45RingInfo(self): """ test the RingInfo class @@ -1587,27 +1594,27 @@ CAS<~> smi = 'CNC' m = Chem.MolFromSmiles(smi) ri = m.GetRingInfo() - self.failUnless(ri) - self.failUnless(ri.NumRings()==0) - self.failIf(ri.IsAtomInRingOfSize(0,3)) - self.failIf(ri.IsAtomInRingOfSize(1,3)) - self.failIf(ri.IsAtomInRingOfSize(2,3)) - self.failIf(ri.IsBondInRingOfSize(1,3)) - self.failIf(ri.IsBondInRingOfSize(2,3)) + self.assertTrue(ri) + self.assertTrue(ri.NumRings()==0) + self.assertFalse(ri.IsAtomInRingOfSize(0,3)) + self.assertFalse(ri.IsAtomInRingOfSize(1,3)) + self.assertFalse(ri.IsAtomInRingOfSize(2,3)) + self.assertFalse(ri.IsBondInRingOfSize(1,3)) + self.assertFalse(ri.IsBondInRingOfSize(2,3)) smi = 'C1CC2C1C2' m = Chem.MolFromSmiles(smi) ri = m.GetRingInfo() - self.failUnless(ri) - self.failUnless(ri.NumRings()==2) - self.failIf(ri.IsAtomInRingOfSize(0,3)) - self.failUnless(ri.IsAtomInRingOfSize(0,4)) - self.failIf(ri.IsBondInRingOfSize(0,3)) - self.failUnless(ri.IsBondInRingOfSize(0,4)) - self.failUnless(ri.IsAtomInRingOfSize(2,4)) - self.failUnless(ri.IsAtomInRingOfSize(2,3)) - self.failUnless(ri.IsBondInRingOfSize(2,3)) - self.failUnless(ri.IsBondInRingOfSize(2,4)) + self.assertTrue(ri) + self.assertTrue(ri.NumRings()==2) + self.assertFalse(ri.IsAtomInRingOfSize(0,3)) + self.assertTrue(ri.IsAtomInRingOfSize(0,4)) + self.assertFalse(ri.IsBondInRingOfSize(0,3)) + self.assertTrue(ri.IsBondInRingOfSize(0,4)) + self.assertTrue(ri.IsAtomInRingOfSize(2,4)) + self.assertTrue(ri.IsAtomInRingOfSize(2,3)) + self.assertTrue(ri.IsBondInRingOfSize(2,3)) + self.assertTrue(ri.IsBondInRingOfSize(2,4)) def test46ReplaceCore(self): """ test the ReplaceCore functionality @@ -1619,61 +1626,61 @@ CAS<~> smi = 'CCC=O' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m,core) - self.failUnless(r) - self.failUnlessEqual(Chem.MolToSmiles(r,True),'[1*]CC') + self.assertTrue(r) + self.assertEqual(Chem.MolToSmiles(r,True),'[1*]CC') smi = 'C1CC(=O)CC1' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m,core) - self.failUnless(r) - self.failUnlessEqual(Chem.MolToSmiles(r,True),'[1*]CCCC[2*]') + self.assertTrue(r) + self.assertEqual(Chem.MolToSmiles(r,True),'[1*]CCCC[2*]') smi = 'C1CC(=N)CC1' m = Chem.MolFromSmiles(smi) r = Chem.ReplaceCore(m,core) - self.failIf(r) + self.assertFalse(r) def test47RWMols(self): """ test the RWMol class """ mol = Chem.MolFromSmiles('C1CCC1') - self.failUnless(type(mol)==Chem.Mol) + self.assertTrue(type(mol)==Chem.Mol) rwmol = Chem.EditableMol(mol) - self.failUnless(type(rwmol)==Chem.EditableMol) + self.assertTrue(type(rwmol)==Chem.EditableMol) newAt = Chem.Atom(8) rwmol.ReplaceAtom(0,newAt) - self.failUnless(Chem.MolToSmiles(rwmol.GetMol())=='C1COC1') + self.assertTrue(Chem.MolToSmiles(rwmol.GetMol())=='C1COC1') rwmol.RemoveBond(0,1) - self.failUnless(Chem.MolToSmiles(rwmol.GetMol())=='CCCO') + self.assertTrue(Chem.MolToSmiles(rwmol.GetMol())=='CCCO') a = Chem.Atom(7) idx=rwmol.AddAtom(a) - self.failUnlessEqual(rwmol.GetMol().GetNumAtoms(),5) - self.failUnlessEqual(idx,4) + self.assertEqual(rwmol.GetMol().GetNumAtoms(),5) + self.assertEqual(idx,4) idx=rwmol.AddBond(0,4,order=Chem.BondType.SINGLE) - self.failUnlessEqual(idx,4) + self.assertEqual(idx,4) - self.failUnless(Chem.MolToSmiles(rwmol.GetMol())=='CCCON') + self.assertTrue(Chem.MolToSmiles(rwmol.GetMol())=='CCCON') rwmol.AddBond(4,1,order=Chem.BondType.SINGLE) - self.failUnless(Chem.MolToSmiles(rwmol.GetMol())=='C1CNOC1') + self.assertTrue(Chem.MolToSmiles(rwmol.GetMol())=='C1CNOC1') rwmol.RemoveAtom(3) - self.failUnless(Chem.MolToSmiles(rwmol.GetMol())=='CCNO') + self.assertTrue(Chem.MolToSmiles(rwmol.GetMol())=='CCNO') # practice shooting ourselves in the foot: m = Chem.MolFromSmiles('c1ccccc1') em=Chem.EditableMol(m) em.RemoveAtom(0) m2 = em.GetMol() - self.failUnlessRaises(ValueError,lambda : Chem.SanitizeMol(m2)) + self.assertRaises(ValueError,lambda : Chem.SanitizeMol(m2)) m = Chem.MolFromSmiles('c1ccccc1') em=Chem.EditableMol(m) em.RemoveBond(0,1) m2 = em.GetMol() - self.failUnlessRaises(ValueError,lambda : Chem.SanitizeMol(m2)) + self.assertRaises(ValueError,lambda : Chem.SanitizeMol(m2)) # boundary cases: @@ -1683,37 +1690,37 @@ CAS<~> em.RemoveBond(0,2) m2 = em.GetMol() Chem.SanitizeMol(m2) - self.failUnless(Chem.MolToSmiles(m2)=='c1ccccc1') + self.assertTrue(Chem.MolToSmiles(m2)=='c1ccccc1') # removing non-existent atoms: m = Chem.MolFromSmiles('c1ccccc1') em=Chem.EditableMol(m) - self.failUnlessRaises(RuntimeError,lambda:em.RemoveAtom(12)) + self.assertRaises(RuntimeError,lambda:em.RemoveAtom(12)) def test47SmartsPieces(self): """ test the GetAtomSmarts and GetBondSmarts functions """ m =Chem.MolFromSmarts("[C,N]C") - self.failUnless(m.GetAtomWithIdx(0).GetSmarts()=='[C,N]') - self.failUnless(m.GetAtomWithIdx(1).GetSmarts()=='C') - self.failUnless(m.GetBondBetweenAtoms(0,1).GetSmarts()=='-,:') + self.assertTrue(m.GetAtomWithIdx(0).GetSmarts()=='[C,N]') + self.assertTrue(m.GetAtomWithIdx(1).GetSmarts()=='C') + self.assertTrue(m.GetBondBetweenAtoms(0,1).GetSmarts()=='-,:') m =Chem.MolFromSmarts("[$(C=O)]-O") - self.failUnless(m.GetAtomWithIdx(0).GetSmarts()=='[$(C=O)]') - self.failUnless(m.GetAtomWithIdx(1).GetSmarts()=='O') - self.failUnless(m.GetBondBetweenAtoms(0,1).GetSmarts()=='-') + self.assertTrue(m.GetAtomWithIdx(0).GetSmarts()=='[$(C=O)]') + self.assertTrue(m.GetAtomWithIdx(1).GetSmarts()=='O') + self.assertTrue(m.GetBondBetweenAtoms(0,1).GetSmarts()=='-') m =Chem.MolFromSmiles("CO") - self.failUnless(m.GetAtomWithIdx(0).GetSmarts()=='C') - self.failUnless(m.GetAtomWithIdx(1).GetSmarts()=='O') - self.failUnless(m.GetBondBetweenAtoms(0,1).GetSmarts()=='') - self.failUnless(m.GetBondBetweenAtoms(0,1).GetSmarts(allBondsExplicit=True)=='-') + self.assertTrue(m.GetAtomWithIdx(0).GetSmarts()=='C') + self.assertTrue(m.GetAtomWithIdx(1).GetSmarts()=='O') + self.assertTrue(m.GetBondBetweenAtoms(0,1).GetSmarts()=='') + self.assertTrue(m.GetBondBetweenAtoms(0,1).GetSmarts(allBondsExplicit=True)=='-') m =Chem.MolFromSmiles("C=O") - self.failUnless(m.GetAtomWithIdx(0).GetSmarts()=='C') - self.failUnless(m.GetAtomWithIdx(1).GetSmarts()=='O') - self.failUnless(m.GetBondBetweenAtoms(0,1).GetSmarts()=='=') + self.assertTrue(m.GetAtomWithIdx(0).GetSmarts()=='C') + self.assertTrue(m.GetAtomWithIdx(1).GetSmarts()=='O') + self.assertTrue(m.GetBondBetweenAtoms(0,1).GetSmarts()=='=') def test48Issue1928819(self): """ test a crash involving looping directly over mol suppliers @@ -1721,50 +1728,50 @@ CAS<~> fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf') ms = [x for x in Chem.SDMolSupplier(fileN)] - self.failUnlessEqual(len(ms),16) + self.assertEqual(len(ms),16) count=0 for m in Chem.SDMolSupplier(fileN): count+=1 - self.failUnlessEqual(count,16) + self.assertEqual(count,16) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','fewSmi.csv') count=0 for m in Chem.SmilesMolSupplier(fileN,titleLine=False,smilesColumn=1,delimiter=','): count+=1 - self.failUnlessEqual(count,10) + self.assertEqual(count,10) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','acd_few.tdt') count=0 for m in Chem.TDTMolSupplier(fileN): count+=1 - self.failUnlessEqual(count,10) + self.assertEqual(count,10) def test49Issue1932365(self): """ test aromatic Se and Te from smiles/smarts """ m = Chem.MolFromSmiles('c1ccc[se]1') - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(0).GetIsAromatic()) - self.failUnless(m.GetAtomWithIdx(4).GetIsAromatic()) + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) + self.assertTrue(m.GetAtomWithIdx(4).GetIsAromatic()) m = Chem.MolFromSmiles('c1ccc[te]1') - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(0).GetIsAromatic()) - self.failUnless(m.GetAtomWithIdx(4).GetIsAromatic()) + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) + self.assertTrue(m.GetAtomWithIdx(4).GetIsAromatic()) m = Chem.MolFromSmiles('C1=C[Se]C=C1') - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(0).GetIsAromatic()) - self.failUnless(m.GetAtomWithIdx(2).GetIsAromatic()) + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) + self.assertTrue(m.GetAtomWithIdx(2).GetIsAromatic()) m = Chem.MolFromSmiles('C1=C[Te]C=C1') - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(0).GetIsAromatic()) - self.failUnless(m.GetAtomWithIdx(2).GetIsAromatic()) + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(0).GetIsAromatic()) + self.assertTrue(m.GetAtomWithIdx(2).GetIsAromatic()) p = Chem.MolFromSmarts('[se]') - self.failUnless(Chem.MolFromSmiles('c1ccc[se]1').HasSubstructMatch(p)) - self.failIf(Chem.MolFromSmiles('C1=CCC[Se]1').HasSubstructMatch(p)) + self.assertTrue(Chem.MolFromSmiles('c1ccc[se]1').HasSubstructMatch(p)) + self.assertFalse(Chem.MolFromSmiles('C1=CCC[Se]1').HasSubstructMatch(p)) p = Chem.MolFromSmarts('[te]') - self.failUnless(Chem.MolFromSmiles('c1ccc[te]1').HasSubstructMatch(p)) - self.failIf(Chem.MolFromSmiles('C1=CCC[Te]1').HasSubstructMatch(p)) + self.assertTrue(Chem.MolFromSmiles('c1ccc[te]1').HasSubstructMatch(p)) + self.assertFalse(Chem.MolFromSmiles('C1=CCC[Te]1').HasSubstructMatch(p)) def test50Issue1968608(self): """ test sf.net issue 1968608 @@ -1772,70 +1779,70 @@ CAS<~> smarts = Chem.MolFromSmarts("[r5]") mol = Chem.MolFromSmiles("N12CCC36C1CC(C(C2)=CCOC4CC5=O)C4C3N5c7ccccc76") count = len(mol.GetSubstructMatches(smarts, uniquify=0)) - self.failUnless(count==9) + self.assertTrue(count==9) def test51RadicalHandling(self): """ test handling of atoms with radicals """ mol = Chem.MolFromSmiles("[C]C") - self.failUnless(mol) + self.assertTrue(mol) atom=mol.GetAtomWithIdx(0) - self.failUnless(atom.GetNumRadicalElectrons()==3) - self.failUnless(atom.GetNoImplicit()) + self.assertTrue(atom.GetNumRadicalElectrons()==3) + self.assertTrue(atom.GetNoImplicit()) atom.SetNoImplicit(False) atom.SetNumRadicalElectrons(1) mol.UpdatePropertyCache() - self.failUnless(atom.GetNumRadicalElectrons()==1) - self.failUnless(atom.GetNumImplicitHs()==2) + self.assertTrue(atom.GetNumRadicalElectrons()==1) + self.assertTrue(atom.GetNumImplicitHs()==2) mol = Chem.MolFromSmiles("[c]1ccccc1") - self.failUnless(mol) + self.assertTrue(mol) atom=mol.GetAtomWithIdx(0) - self.failUnless(atom.GetNumRadicalElectrons()==1) - self.failUnless(atom.GetNoImplicit()) + self.assertTrue(atom.GetNumRadicalElectrons()==1) + self.assertTrue(atom.GetNoImplicit()) mol = Chem.MolFromSmiles("[n]1ccccc1") - self.failUnless(mol) + self.assertTrue(mol) atom=mol.GetAtomWithIdx(0) - self.failUnless(atom.GetNumRadicalElectrons()==0) - self.failUnless(atom.GetNoImplicit()) + self.assertTrue(atom.GetNumRadicalElectrons()==0) + self.assertTrue(atom.GetNoImplicit()) def test52MolFrags(self): """ test GetMolFrags functionality """ mol = Chem.MolFromSmiles("C.CC") - self.failUnless(mol) + self.assertTrue(mol) fs = Chem.GetMolFrags(mol) - self.failUnless(len(fs)==2) - self.failUnless(len(fs[0])==1) - self.failUnless(tuple(fs[0])==(0,)) - self.failUnless(len(fs[1])==2) - self.failUnless(tuple(fs[1])==(1,2)) + self.assertTrue(len(fs)==2) + self.assertTrue(len(fs[0])==1) + self.assertTrue(tuple(fs[0])==(0,)) + self.assertTrue(len(fs[1])==2) + self.assertTrue(tuple(fs[1])==(1,2)) fs = Chem.GetMolFrags(mol,True) - self.failUnless(len(fs)==2) - self.failUnless(fs[0].GetNumAtoms()==1) - self.failUnless(fs[1].GetNumAtoms()==2) + self.assertTrue(len(fs)==2) + self.assertTrue(fs[0].GetNumAtoms()==1) + self.assertTrue(fs[1].GetNumAtoms()==2) mol = Chem.MolFromSmiles("CCC") - self.failUnless(mol) + self.assertTrue(mol) fs = Chem.GetMolFrags(mol) - self.failUnless(len(fs)==1) - self.failUnless(len(fs[0])==3) - self.failUnless(tuple(fs[0])==(0,1,2)) + self.assertTrue(len(fs)==1) + self.assertTrue(len(fs[0])==3) + self.assertTrue(tuple(fs[0])==(0,1,2)) fs = Chem.GetMolFrags(mol,True) - self.failUnless(len(fs)==1) - self.failUnless(fs[0].GetNumAtoms()==3) + self.assertTrue(len(fs)==1) + self.assertTrue(fs[0].GetNumAtoms()==3) mol = Chem.MolFromSmiles("CO") em = Chem.EditableMol(mol) em.RemoveBond(0,1) nm = em.GetMol() fs = Chem.GetMolFrags(nm,asMols=True) - self.failUnlessEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs],[5,3]) + self.assertEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs],[5,3]) fs = Chem.GetMolFrags(nm,asMols=True,sanitizeFrags=False) - self.failUnlessEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs],[4,2]) + self.assertEqual([x.GetNumAtoms(onlyExplicit=False) for x in fs],[4,2]) @@ -1846,35 +1853,35 @@ CAS<~> """ m = Chem.MolFromSmiles('CC=C') d = Chem.GetDistanceMatrix(m,0) - self.failUnless(feq(d[0,1],1.0)) - self.failUnless(feq(d[0,2],2.0)) - self.failUnless(feq(d[1,0],1.0)) - self.failUnless(feq(d[2,0],2.0)) + self.assertTrue(feq(d[0,1],1.0)) + self.assertTrue(feq(d[0,2],2.0)) + self.assertTrue(feq(d[1,0],1.0)) + self.assertTrue(feq(d[2,0],2.0)) a = Chem.GetAdjacencyMatrix(m,0) - self.failUnless(a[0,1]==1) - self.failUnless(a[0,2]==0) - self.failUnless(a[1,2]==1) - self.failUnless(a[1,0]==1) - self.failUnless(a[2,0]==0) + self.assertTrue(a[0,1]==1) + self.assertTrue(a[0,2]==0) + self.assertTrue(a[1,2]==1) + self.assertTrue(a[1,0]==1) + self.assertTrue(a[2,0]==0) m = Chem.MolFromSmiles('C1CC1') d = Chem.GetDistanceMatrix(m,0) - self.failUnless(feq(d[0,1],1.0)) - self.failUnless(feq(d[0,2],1.0)) + self.assertTrue(feq(d[0,1],1.0)) + self.assertTrue(feq(d[0,2],1.0)) a = Chem.GetAdjacencyMatrix(m,0) - self.failUnless(a[0,1]==1) - self.failUnless(a[0,2]==1) - self.failUnless(a[1,2]==1) + self.assertTrue(a[0,1]==1) + self.assertTrue(a[0,2]==1) + self.assertTrue(a[1,2]==1) m = Chem.MolFromSmiles('CC.C') d = Chem.GetDistanceMatrix(m,0) - self.failUnless(feq(d[0,1],1.0)) - self.failUnless(d[0,2]>1000) - self.failUnless(d[1,2]>1000) + self.assertTrue(feq(d[0,1],1.0)) + self.assertTrue(d[0,2]>1000) + self.assertTrue(d[1,2]>1000) a = Chem.GetAdjacencyMatrix(m,0) - self.failUnless(a[0,1]==1) - self.failUnless(a[0,2]==0) - self.failUnless(a[1,2]==0) + self.assertTrue(a[0,1]==1) + self.assertTrue(a[0,2]==0) + self.assertTrue(a[1,2]==0) def test54Mol2Parser(self): """ test the mol2 parser @@ -1882,46 +1889,46 @@ CAS<~> fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','pyrazole_pyridine.mol2') m = Chem.MolFromMol2File(fileN) - self.failUnless(m.GetNumAtoms()==5) - self.failUnless(Chem.MolToSmiles(m)=='c1cn[nH]c1',Chem.MolToSmiles(m)) + self.assertTrue(m.GetNumAtoms()==5) + self.assertTrue(Chem.MolToSmiles(m)=='c1cn[nH]c1',Chem.MolToSmiles(m)) def test55LayeredFingerprint(self): m1 = Chem.MolFromSmiles('CC(C)C') fp1 = Chem.LayeredFingerprint(m1) - self.failUnlessEqual(len(fp1),2048) + self.assertEqual(len(fp1),2048) atomCounts=[0]*m1.GetNumAtoms() fp2 = Chem.LayeredFingerprint(m1,atomCounts=atomCounts) - self.failUnlessEqual(fp1,fp2) - self.failUnlessEqual(atomCounts,[4,7,4,4]) + self.assertEqual(fp1,fp2) + self.assertEqual(atomCounts,[4,7,4,4]) fp2 = Chem.LayeredFingerprint(m1,atomCounts=atomCounts) - self.failUnlessEqual(fp1,fp2) - self.failUnlessEqual(atomCounts,[8,14,8,8]) + self.assertEqual(fp1,fp2) + self.assertEqual(atomCounts,[8,14,8,8]) pbv=DataStructs.ExplicitBitVect(2048) fp3 = Chem.LayeredFingerprint(m1,setOnlyBits=pbv) - self.failUnlessEqual(fp3.GetNumOnBits(),0) + self.assertEqual(fp3.GetNumOnBits(),0) fp3 = Chem.LayeredFingerprint(m1,setOnlyBits=fp2) - self.failUnlessEqual(fp3,fp2) + self.assertEqual(fp3,fp2) m2=Chem.MolFromSmiles('CC') fp4 = Chem.LayeredFingerprint(m2) atomCounts=[0]*m1.GetNumAtoms() fp3 = Chem.LayeredFingerprint(m1,setOnlyBits=fp4,atomCounts=atomCounts) - self.failUnlessEqual(atomCounts,[1,3,1,1]) + self.assertEqual(atomCounts,[1,3,1,1]) m2=Chem.MolFromSmiles('CCC') fp4 = Chem.LayeredFingerprint(m2) atomCounts=[0]*m1.GetNumAtoms() fp3 = Chem.LayeredFingerprint(m1,setOnlyBits=fp4,atomCounts=atomCounts) - self.failUnlessEqual(atomCounts,[3,6,3,3]) + self.assertEqual(atomCounts,[3,6,3,3]) def test56LazySDMolSupplier(self) : if not hasattr(Chem,'CompressedSDMolSupplier'): return - self.failUnlessRaises(ValueError,lambda : Chem.CompressedSDMolSupplier('nosuchfile.sdf.gz')) + self.assertRaises(ValueError,lambda : Chem.CompressedSDMolSupplier('nosuchfile.sdf.gz')) fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf.gz') @@ -1932,22 +1939,22 @@ CAS<~> chgs192 = {8:1, 11:1, 15:-1, 18:-1, 20:1, 21:1, 23:-1, 25:-1} i = 0 for mol in sdSup : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 if (mol.GetProp("_Name") == "192") : # test parsed charges on one of the molecules for id in chgs192.keys() : - self.failUnless(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) - self.failUnlessEqual(i,16) + self.assertTrue(mol.GetAtomWithIdx(id).GetFormalCharge() == chgs192[id]) + self.assertEqual(i,16) sdSup = Chem.CompressedSDMolSupplier(fileN) ns = [mol.GetProp("_Name") for mol in sdSup] - self.failUnless(ns == molNames) + self.assertTrue(ns == molNames) sdSup = Chem.CompressedSDMolSupplier(fileN, 0) for mol in sdSup : - self.failUnless(not mol.HasProp("numArom")) + self.assertTrue(not mol.HasProp("numArom")) def test57AddRecursiveQuery(self): q1 = Chem.MolFromSmiles('CC') @@ -1955,36 +1962,36 @@ CAS<~> Chem.AddRecursiveQuery(q1,q2,1) m1 = Chem.MolFromSmiles('OCC') - self.failUnless(m1.HasSubstructMatch(q2)) - self.failUnless(m1.HasSubstructMatch(q1)) - self.failUnless(m1.HasSubstructMatch(q1)) - self.failUnless(m1.GetSubstructMatch(q1)==(2,1)) + self.assertTrue(m1.HasSubstructMatch(q2)) + self.assertTrue(m1.HasSubstructMatch(q1)) + self.assertTrue(m1.HasSubstructMatch(q1)) + self.assertTrue(m1.GetSubstructMatch(q1)==(2,1)) q3 = Chem.MolFromSmiles('CS') Chem.AddRecursiveQuery(q1,q3,1) - self.failIf(m1.HasSubstructMatch(q3)) - self.failIf(m1.HasSubstructMatch(q1)) + self.assertFalse(m1.HasSubstructMatch(q3)) + self.assertFalse(m1.HasSubstructMatch(q1)) m2 = Chem.MolFromSmiles('OC(S)C') - self.failUnless(m2.HasSubstructMatch(q1)) - self.failUnless(m2.GetSubstructMatch(q1)==(3,1)) + self.assertTrue(m2.HasSubstructMatch(q1)) + self.assertTrue(m2.GetSubstructMatch(q1)==(3,1)) m3 = Chem.MolFromSmiles('SCC') - self.failUnless(m3.HasSubstructMatch(q3)) - self.failIf(m3.HasSubstructMatch(q1)) + self.assertTrue(m3.HasSubstructMatch(q3)) + self.assertFalse(m3.HasSubstructMatch(q1)) q1 = Chem.MolFromSmiles('CC') Chem.AddRecursiveQuery(q1,q2,1) Chem.AddRecursiveQuery(q1,q3,1,False) - self.failUnless(m3.HasSubstructMatch(q1)) - self.failUnless(m3.GetSubstructMatch(q1)==(2,1)) + self.assertTrue(m3.HasSubstructMatch(q1)) + self.assertTrue(m3.GetSubstructMatch(q1)==(2,1)) def test58Issue2983794(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','Wrap', 'test_data','issue2983794.sdf') m1 = Chem.MolFromMolFile(fileN) - self.failUnless(m1) + self.assertTrue(m1) em = Chem.EditableMol(m1) em.RemoveAtom(0) m2 = em.GetMol() @@ -1994,12 +2001,12 @@ CAS<~> m = Chem.MolFromSmiles('CCC') a = m.GetAtomWithIdx(0) m=None - self.failUnlessEqual(Chem.MolToSmiles(a.GetOwningMol()),'CCC') + self.assertEqual(Chem.MolToSmiles(a.GetOwningMol()),'CCC') a=None m = Chem.MolFromSmiles('CCC') b = m.GetBondWithIdx(0) m=None - self.failUnlessEqual(Chem.MolToSmiles(b.GetOwningMol()),'CCC') + self.assertEqual(Chem.MolToSmiles(b.GetOwningMol()),'CCC') def test60SmilesWriterClose(self) : fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', @@ -2017,62 +2024,62 @@ CAS<~> newsup=Chem.SmilesMolSupplier(ofile) newms = [x for x in newsup] - self.failUnlessEqual(len(ms),len(newms)) + self.assertEqual(len(ms),len(newms)) def test61PathToSubmol(self): m = Chem.MolFromSmiles('CCCCCC1C(O)CC(O)N1C=CCO') env = Chem.FindAtomEnvironmentOfRadiusN(m,2,11) - self.failUnlessEqual(len(env),8) + self.assertEqual(len(env),8) amap={} submol = Chem.PathToSubmol(m,env,atomMap=amap) - self.failUnlessEqual(submol.GetNumAtoms(),len(amap.keys())) - self.failUnlessEqual(submol.GetNumAtoms(),9) + self.assertEqual(submol.GetNumAtoms(),len(amap.keys())) + self.assertEqual(submol.GetNumAtoms(),9) smi=Chem.MolToSmiles(submol,rootedAtAtom=amap[11]) - self.failUnlessEqual(smi[0],'N') + self.assertEqual(smi[0],'N') refsmi = Chem.MolToSmiles(Chem.MolFromSmiles('N(C=C)(C(C)C)C(O)C')) csmi = Chem.MolToSmiles(Chem.MolFromSmiles(smi)) - self.failUnlessEqual(refsmi,csmi) + self.assertEqual(refsmi,csmi) def test62SmilesAndSmartsReplacements(self): mol = Chem.MolFromSmiles('C{branch}C',replacements={'{branch}':'C1(CC1)'}) - self.failUnlessEqual(mol.GetNumAtoms(),5) + self.assertEqual(mol.GetNumAtoms(),5) mol = Chem.MolFromSmarts('C{branch}C',replacements={'{branch}':'C1(CC1)'}) - self.failUnlessEqual(mol.GetNumAtoms(),5) + self.assertEqual(mol.GetNumAtoms(),5) mol = Chem.MolFromSmiles('C{branch}C{acid}',replacements={'{branch}':'C1(CC1)', '{acid}':"C(=O)O"}) - self.failUnlessEqual(mol.GetNumAtoms(),8) + self.assertEqual(mol.GetNumAtoms(),8) def test63Issue3313539(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','rgroups1.mol') m = Chem.MolFromMolFile(fileN) - self.failUnless(m is not None) + self.assertTrue(m is not None) at = m.GetAtomWithIdx(3) - self.failUnless(at is not None) - self.failUnless(at.HasProp('_MolFileRLabel')) + self.assertTrue(at is not None) + self.assertTrue(at.HasProp('_MolFileRLabel')) p = at.GetProp('_MolFileRLabel') - self.failUnlessEqual(p,'2') + self.assertEqual(p,'2') at = m.GetAtomWithIdx(4) - self.failUnless(at is not None) - self.failUnless(at.HasProp('_MolFileRLabel')) + self.assertTrue(at is not None) + self.assertTrue(at.HasProp('_MolFileRLabel')) p = at.GetProp('_MolFileRLabel') - self.failUnlessEqual(p,'1') + self.assertEqual(p,'1') def test64MoleculeCleanup(self): m = Chem.MolFromSmiles('CN(=O)=O',False) - self.failUnless(m) - self.failUnless(m.GetAtomWithIdx(1).GetFormalCharge()==0 and \ + self.assertTrue(m) + self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==0 and \ m.GetAtomWithIdx(2).GetFormalCharge()==0 and \ m.GetAtomWithIdx(3).GetFormalCharge()==0) - self.failUnless(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.DOUBLE and \ + self.assertTrue(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.DOUBLE and \ m.GetBondBetweenAtoms(1,2).GetBondType()==Chem.BondType.DOUBLE ) Chem.Cleanup(m) m.UpdatePropertyCache() - self.failUnless(m.GetAtomWithIdx(1).GetFormalCharge()==1 and \ + self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==1 and \ (m.GetAtomWithIdx(2).GetFormalCharge()==-1 or \ m.GetAtomWithIdx(3).GetFormalCharge()==-1)) - self.failUnless(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.SINGLE or \ + self.assertTrue(m.GetBondBetweenAtoms(1,3).GetBondType()==Chem.BondType.SINGLE or \ m.GetBondBetweenAtoms(1,2).GetBondType()==Chem.BondType.SINGLE ) def test65StreamSupplier(self): @@ -2090,11 +2097,11 @@ CAS<~> i = 0 while not suppl.atEnd(): - mol = suppl.next() - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + mol = six.next(suppl) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) # make sure we have object ownership preserved inf = gzip.open(fileN) @@ -2102,11 +2109,11 @@ CAS<~> inf=None i = 0 while not suppl.atEnd(): - mol = suppl.next() - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + mol = six.next(suppl) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) def test66StreamSupplierIter(self): import gzip @@ -2123,26 +2130,31 @@ CAS<~> "192", "203", "210", "211", "213", "220", "229", "256"] i = 0 for mol in suppl : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) def test67StreamSupplierStringIO(self): - import gzip,StringIO + import gzip fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf.gz') - sio = StringIO.StringIO(gzip.open(fileN).read()) + if sys.version > '3': + from io import BytesIO + sio = BytesIO(gzip.open(fileN).read()) + else: + import StringIO + sio = StringIO.StringIO(gzip.open(fileN).read()) suppl = Chem.ForwardSDMolSupplier(sio) molNames = ["48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256"] i = 0 for mol in suppl: - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) def test68ForwardSupplierUsingFilename(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', @@ -2152,15 +2164,15 @@ CAS<~> "192", "203", "210", "211", "213", "220", "229", "256"] i = 0 for mol in suppl: - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) - self.failUnlessRaises(IOError,lambda : Chem.ForwardSDMolSupplier('nosuchfile.sdf')) + self.assertRaises(IOError,lambda : Chem.ForwardSDMolSupplier('nosuchfile.sdf')) def test69StreamSupplierStreambuf(self): - import gzip,StringIO + import gzip fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf.gz') sb = rdBase.streambuf(gzip.open(fileN)) @@ -2170,99 +2182,100 @@ CAS<~> "192", "203", "210", "211", "213", "220", "229", "256"] i = 0 for mol in suppl: - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) def test70StreamSDWriter(self): - import gzip,StringIO + import gzip + from rdkit.six.moves import cStringIO as StringIO fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf.gz') inf = gzip.open(fileN) suppl = Chem.ForwardSDMolSupplier(inf) - osio=StringIO.StringIO() + osio=StringIO() w = Chem.SDWriter(osio) molNames = ["48", "78", "128", "163", "164", "170", "180", "186", "192", "203", "210", "211", "213", "220", "229", "256"] i = 0 for mol in suppl : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) w.write(mol) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) w.flush() w=None - - isio=StringIO.StringIO(osio.getvalue()) + + isio=StringIO(osio.getvalue()) suppl = Chem.ForwardSDMolSupplier(isio) i = 0 for mol in suppl : - self.failUnless(mol) - self.failUnless(mol.GetProp("_Name") == molNames[i]) + self.assertTrue(mol) + self.assertTrue(mol.GetProp("_Name") == molNames[i]) i += 1 - self.failUnlessEqual(i,16) + self.assertEqual(i,16) def test71StreamSmilesWriter(self): - import StringIO + from rdkit.six.moves import StringIO fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','esters.sdf') suppl = Chem.ForwardSDMolSupplier(fileN) - osio=StringIO.StringIO() + osio=StringIO() w = Chem.SmilesWriter(osio) ms = [x for x in suppl] w.SetProps(ms[0].GetPropNames()) i=0 for mol in ms: - self.failUnless(mol) + self.assertTrue(mol) w.write(mol) i+=1 - self.failUnlessEqual(i,6) + self.assertEqual(i,6) w.flush() w=None txt = osio.getvalue() - self.failUnlessEqual(txt.count('ID'),1) - self.failUnlessEqual(txt.count('\n'),7) + self.assertEqual(txt.count('ID'),1) + self.assertEqual(txt.count('\n'),7) def test72StreamTDTWriter(self): - import StringIO + from rdkit.six.moves import StringIO fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','esters.sdf') suppl = Chem.ForwardSDMolSupplier(fileN) - osio=StringIO.StringIO() + osio=StringIO() w = Chem.TDTWriter(osio) ms = [x for x in suppl] w.SetProps(ms[0].GetPropNames()) i=0 for mol in ms: - self.failUnless(mol) + self.assertTrue(mol) w.write(mol) i+=1 - self.failUnlessEqual(i,6) + self.assertEqual(i,6) w.flush() w=None txt = osio.getvalue() - self.failUnlessEqual(txt.count('ID'),6) - self.failUnlessEqual(txt.count('NAME'),6) + self.assertEqual(txt.count('ID'),6) + self.assertEqual(txt.count('NAME'),6) def test73SanitizationOptions(self): m = Chem.MolFromSmiles('c1ccccc1',sanitize=False) res = Chem.SanitizeMol(m,catchErrors=True) - self.failUnlessEqual(res,0) + self.assertEqual(res,0) m = Chem.MolFromSmiles('c1cccc1',sanitize=False) res = Chem.SanitizeMol(m,catchErrors=True) - self.failUnlessEqual(res,Chem.SanitizeFlags.SANITIZE_KEKULIZE) + self.assertEqual(res,Chem.SanitizeFlags.SANITIZE_KEKULIZE) m = Chem.MolFromSmiles('CC(C)(C)(C)C',sanitize=False) res = Chem.SanitizeMol(m,catchErrors=True) - self.failUnlessEqual(res,Chem.SanitizeFlags.SANITIZE_PROPERTIES) + self.assertEqual(res,Chem.SanitizeFlags.SANITIZE_PROPERTIES) m = Chem.MolFromSmiles('c1cccc1',sanitize=False) res = Chem.SanitizeMol(m,sanitizeOps=Chem.SanitizeFlags.SANITIZE_ALL^Chem.SanitizeFlags.SANITIZE_KEKULIZE, catchErrors=True) - self.failUnlessEqual(res,Chem.SanitizeFlags.SANITIZE_NONE) + self.assertEqual(res,Chem.SanitizeFlags.SANITIZE_NONE) def test74Issue3510149(self): mol = Chem.MolFromSmiles("CCC1CNCC1CC") @@ -2288,73 +2301,73 @@ CAS<~> fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','NCI_aids_few.sdf') sdSup = Chem.SDMolSupplier(fileN) - mol = sdSup.next() + mol = six.next(sdSup) nats = mol.GetNumAtoms() conf = mol.GetConformer() mol=None - self.failUnlessEqual(nats,conf.GetNumAtoms()) + self.assertEqual(nats,conf.GetNumAtoms()) conf.GetOwningMol().GetProp("_Name") def test75AllBondsExplicit(self): m = Chem.MolFromSmiles("CCC") smi = Chem.MolToSmiles(m) - self.failUnlessEqual(smi,"CCC") + self.assertEqual(smi,"CCC") smi = Chem.MolToSmiles(m,allBondsExplicit=True) - self.failUnlessEqual(smi,"C-C-C") + self.assertEqual(smi,"C-C-C") m = Chem.MolFromSmiles("c1ccccc1") smi = Chem.MolToSmiles(m) - self.failUnlessEqual(smi,"c1ccccc1") + self.assertEqual(smi,"c1ccccc1") smi = Chem.MolToSmiles(m,allBondsExplicit=True) - self.failUnlessEqual(smi,"c1:c:c:c:c:c:1") + self.assertEqual(smi,"c1:c:c:c:c:c:1") def test76VeryLargeMolecule(self): # this is sf.net issue 3524984 smi = '[C@H](F)(Cl)'+'c1cc[nH]c1'*500+'[C@H](F)(Cl)' m = Chem.MolFromSmiles(smi) - self.failUnless(m) - self.failUnlessEqual(m.GetNumAtoms(),2506) + self.assertTrue(m) + self.assertEqual(m.GetNumAtoms(),2506) scs = Chem.FindMolChiralCenters(m) - self.failUnlessEqual(len(scs),2) + self.assertEqual(len(scs),2) def test77MolFragmentToSmiles(self): smi="OC1CC1CC" m = Chem.MolFromSmiles(smi) fsmi = Chem.MolFragmentToSmiles(m,[1,2,3]) - self.failUnlessEqual(fsmi,"C1CC1") + self.assertEqual(fsmi,"C1CC1") fsmi = Chem.MolFragmentToSmiles(m,[1,2,3],bondsToUse=[1,2,5]) - self.failUnlessEqual(fsmi,"C1CC1") + self.assertEqual(fsmi,"C1CC1") fsmi = Chem.MolFragmentToSmiles(m,[1,2,3],bondsToUse=[1,2]) - self.failUnlessEqual(fsmi,"CCC") + self.assertEqual(fsmi,"CCC") fsmi = Chem.MolFragmentToSmiles(m,[1,2,3],atomSymbols=["","[A]","[C]","[B]","",""]) - self.failUnlessEqual(fsmi,"[C]1[B][A]1") + self.assertEqual(fsmi,"[C]1[B][A]1") fsmi = Chem.MolFragmentToSmiles(m,[1,2,3],bondSymbols=["","%","%","","","%"]) - self.failUnlessEqual(fsmi,"C1%C%C%1") + self.assertEqual(fsmi,"C1%C%C%1") smi="c1ccccc1C" m = Chem.MolFromSmiles(smi) fsmi = Chem.MolFragmentToSmiles(m,range(6)) - self.failUnlessEqual(fsmi,"c1ccccc1") + self.assertEqual(fsmi,"c1ccccc1") Chem.Kekulize(m) fsmi = Chem.MolFragmentToSmiles(m,range(6),kekuleSmiles=True) - self.failUnlessEqual(fsmi,"C1=CC=CC=C1") + self.assertEqual(fsmi,"C1=CC=CC=C1") fsmi = Chem.MolFragmentToSmiles(m,range(6),atomSymbols=["[C]"]*7,kekuleSmiles=True) - self.failUnlessEqual(fsmi,"[C]1=[C][C]=[C][C]=[C]1") + self.assertEqual(fsmi,"[C]1=[C][C]=[C][C]=[C]1") self.assertRaises(ValueError,lambda : Chem.MolFragmentToSmiles(m,[])) def test78AtomAndBondProps(self): m = Chem.MolFromSmiles('c1ccccc1') at = m.GetAtomWithIdx(0) - self.failIf(at.HasProp('foo')) + self.assertFalse(at.HasProp('foo')) at.SetProp('foo','bar') - self.failUnless(at.HasProp('foo')) - self.failUnlessEqual(at.GetProp('foo'),'bar') + self.assertTrue(at.HasProp('foo')) + self.assertEqual(at.GetProp('foo'),'bar') bond = m.GetBondWithIdx(0) - self.failIf(bond.HasProp('foo')) + self.assertFalse(bond.HasProp('foo')) bond.SetProp('foo','bar') - self.failUnless(bond.HasProp('foo')) - self.failUnlessEqual(bond.GetProp('foo'),'bar') + self.assertTrue(bond.HasProp('foo')) + self.assertEqual(bond.GetProp('foo'),'bar') def test79AddRecursiveStructureQueries(self): qs = {'carbonyl':Chem.MolFromSmiles('CO'), @@ -2363,87 +2376,87 @@ CAS<~> q.GetAtomWithIdx(0).SetProp('query','carbonyl,amine') Chem.MolAddRecursiveQueries(q,qs,'query') m = Chem.MolFromSmiles('CCCO') - self.failUnless(m.HasSubstructMatch(q)) + self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CCCN') - self.failUnless(m.HasSubstructMatch(q)) + self.assertTrue(m.HasSubstructMatch(q)) m = Chem.MolFromSmiles('CCCC') - self.failIf(m.HasSubstructMatch(q)) + self.assertFalse(m.HasSubstructMatch(q)) def test80ParseMolQueryDefFile(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','ChemTransforms', 'testData','query_file1.txt') d = Chem.ParseMolQueryDefFile(fileN,standardize=False) - self.failUnless('CarboxylicAcid' in d) + self.assertTrue('CarboxylicAcid' in d) m = Chem.MolFromSmiles('CC(=O)O') - self.failUnless(m.HasSubstructMatch(d['CarboxylicAcid'])) - self.failIf(m.HasSubstructMatch(d['CarboxylicAcid.Aromatic'])) + self.assertTrue(m.HasSubstructMatch(d['CarboxylicAcid'])) + self.assertFalse(m.HasSubstructMatch(d['CarboxylicAcid.Aromatic'])) d = Chem.ParseMolQueryDefFile(fileN) - self.failUnless('carboxylicacid' in d) - self.failIf('CarboxylicAcid' in d) + self.assertTrue('carboxylicacid' in d) + self.assertFalse('CarboxylicAcid' in d) def test81Issue275(self): smi = Chem.MolToSmiles(Chem.MurckoDecompose(Chem.MolFromSmiles('CCCCC[C@H]1CC[C@H](C(=O)O)CC1'))) - self.failUnlessEqual(smi,'C1CCCCC1') + self.assertEqual(smi,'C1CCCCC1') def test82Issue288(self): m = Chem.MolFromSmiles('CC*') m.GetAtomWithIdx(2).SetProp('molAtomMapNumber','30') smi=Chem.MolToSmiles(m) - self.failUnlessEqual(smi,'[*:30]CC') + self.assertEqual(smi,'[*:30]CC') def test83GitHubIssue19(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','empty2.sdf') sdSup = Chem.SDMolSupplier(fileN) - self.failUnless(sdSup.atEnd()) - self.failUnlessRaises(IndexError,lambda : sdSup[0]) + self.assertTrue(sdSup.atEnd()) + self.assertRaises(IndexError,lambda : sdSup[0]) sdSup.SetData('') - self.failUnless(sdSup.atEnd()) - self.failUnlessRaises(IndexError,lambda : sdSup[0]) + self.assertTrue(sdSup.atEnd()) + self.assertRaises(IndexError,lambda : sdSup[0]) sdSup = Chem.SDMolSupplier(fileN) - self.failUnlessRaises(IndexError,lambda : sdSup[0]) + self.assertRaises(IndexError,lambda : sdSup[0]) sdSup.SetData('') - self.failUnlessRaises(IndexError,lambda : sdSup[0]) + self.assertRaises(IndexError,lambda : sdSup[0]) sdSup = Chem.SDMolSupplier(fileN) - self.failUnlessEqual(len(sdSup),0) + self.assertEqual(len(sdSup),0) sdSup.SetData('') - self.failUnlessEqual(len(sdSup),0) + self.assertEqual(len(sdSup),0) def test84PDBBasics(self): fileN = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','FileParsers', 'test_data','1CRN.pdb') m = Chem.MolFromPDBFile(fileN) - self.failUnless(m is not None) - self.failUnlessEqual(m.GetNumAtoms(),327) - self.failUnlessEqual(m.GetNumBonds(),337) - self.failUnless(m.GetAtomWithIdx(0).GetPDBResidueInfo()) - self.failUnlessEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName()," N ") - self.failUnlessEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(),"THR") - self.failUnlessAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(),13.79,2) + self.assertTrue(m is not None) + self.assertEqual(m.GetNumAtoms(),327) + self.assertEqual(m.GetNumBonds(),337) + self.assertTrue(m.GetAtomWithIdx(0).GetPDBResidueInfo()) + self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName()," N ") + self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(),"THR") + self.assertAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(),13.79,2) m = Chem.MolFromPDBBlock(Chem.MolToPDBBlock(m)) - self.failUnlessEqual(m.GetNumAtoms(),327) - self.failUnlessEqual(m.GetNumBonds(),337) - self.failUnless(m.GetAtomWithIdx(0).GetPDBResidueInfo()) - self.failUnlessEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName()," N ") - self.failUnlessEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(),"THR") - self.failUnlessAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(),13.79,2) + self.assertEqual(m.GetNumAtoms(),327) + self.assertEqual(m.GetNumBonds(),337) + self.assertTrue(m.GetAtomWithIdx(0).GetPDBResidueInfo()) + self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetName()," N ") + self.assertEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetResidueName(),"THR") + self.assertAlmostEqual(m.GetAtomWithIdx(0).GetPDBResidueInfo().GetTempFactor(),13.79,2) def test85MolCopying(self): m = Chem.MolFromSmiles('C1CC1[C@H](F)Cl') m.SetProp('foo','bar') m2 = Chem.Mol(m) - self.failUnlessEqual(Chem.MolToSmiles(m,True),Chem.MolToSmiles(m2,True)) - self.failUnless(m2.HasProp('foo')) - self.failUnlessEqual(m2.GetProp('foo'),'bar') + self.assertEqual(Chem.MolToSmiles(m,True),Chem.MolToSmiles(m2,True)) + self.assertTrue(m2.HasProp('foo')) + self.assertEqual(m2.GetProp('foo'),'bar') ri = m2.GetRingInfo() - self.failUnless(ri) - self.failUnlessEqual(ri.NumRings(),1) + self.assertTrue(ri) + self.assertEqual(ri.NumRings(),1) def test86MolRenumbering(self): import random @@ -2454,7 +2467,7 @@ CAS<~> random.shuffle(ans) m2 = Chem.RenumberAtoms(m,ans) nSmi = Chem.MolToSmiles(m2,True) - self.failUnlessEqual(cSmi,nSmi) + self.assertEqual(cSmi,nSmi) def test87FragmentOnBonds(self): m = Chem.MolFromSmiles('CC1CC(O)C1CCC1CC1') @@ -2470,17 +2483,17 @@ CAS<~> bs.append(b.GetIdx()) nm = Chem.FragmentOnBonds(m,bs) frags = Chem.GetMolFrags(nm) - self.failUnlessEqual(len(frags),5) - self.failUnlessEqual(frags,((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) + self.assertEqual(len(frags),5) + self.assertEqual(frags,((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) smi = Chem.MolToSmiles(nm,True) - self.failUnlessEqual(smi,'[*]C1CC([4*])C1[6*].[1*]C.[3*]O.[5*]CC[8*].[7*]C1CC1') + self.assertEqual(smi,'[*]C1CC([4*])C1[6*].[1*]C.[3*]O.[5*]CC[8*].[7*]C1CC1') nm = Chem.FragmentOnBonds(m,bs,dummyLabels=labels) frags = Chem.GetMolFrags(nm) - self.failUnlessEqual(len(frags),5) - self.failUnlessEqual(frags,((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) + self.assertEqual(len(frags),5) + self.assertEqual(frags,((0, 12), (1, 2, 3, 5, 11, 14, 16), (4, 13), (6, 7, 15, 18), (8, 9, 10, 17))) smi = Chem.MolToSmiles(nm,True) - self.failUnlessEqual(smi,'[1*]C.[1*]O.[1*]CC[1*].[10*]C1CC1.[10*]C1CC([10*])C1[10*]') + self.assertEqual(smi,'[1*]C.[1*]O.[1*]CC[1*].[10*]C1CC1.[10*]C1CC([10*])C1[10*]') m = Chem.MolFromSmiles('CCC(=O)CC(=O)C') bis = m.GetSubstructMatches(Chem.MolFromSmarts('C=O')) @@ -2491,9 +2504,9 @@ CAS<~> bts = [Chem.BondType.DOUBLE]*len(bs) nm = Chem.FragmentOnBonds(m,bs,bondTypes=bts) frags = Chem.GetMolFrags(nm) - self.failUnlessEqual(len(frags),3) + self.assertEqual(len(frags),3) smi = Chem.MolToSmiles(nm,True) - self.failUnlessEqual(smi,'[2*]=O.[3*]=C(CC)CC(=[6*])C.[5*]=O') + self.assertEqual(smi,'[2*]=O.[3*]=C(CC)CC(=[6*])C.[5*]=O') def test88QueryAtoms(self): from rdkit.Chem import rdqueries @@ -2501,40 +2514,40 @@ CAS<~> qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(2,4)) + self.assertEqual(l,(2,4)) qa.ExpandQuery(rdqueries.AtomNumEqualsQueryAtom(6,negate=True)) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(4,)) + self.assertEqual(l,(4,)) qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) qa.ExpandQuery(rdqueries.AtomNumEqualsQueryAtom(6,negate=True), how=Chem.CompositeQueryType.COMPOSITE_OR) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(1,2,4)) + self.assertEqual(l,(1,2,4)) qa = rdqueries.ExplicitDegreeEqualsQueryAtom(3) qa.ExpandQuery(rdqueries.AtomNumEqualsQueryAtom(6,negate=True), how=Chem.CompositeQueryType.COMPOSITE_XOR) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(1,2)) + self.assertEqual(l,(1,2)) qa = rdqueries.ExplicitDegreeGreaterQueryAtom(2) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(2,4)) + self.assertEqual(l,(2,4)) qa = rdqueries.ExplicitDegreeLessQueryAtom(2) l = tuple([x.GetIdx() for x in m.GetAtomsMatchingQuery(qa)]) - self.failUnlessEqual(l,(3,6)) + self.assertEqual(l,(3,6)) def test89UnicodeInput(self): m = Chem.MolFromSmiles(u'c1ccccc1') - self.failUnless(m is not None) - self.failUnlessEqual(m.GetNumAtoms(),6) + self.assertTrue(m is not None) + self.assertEqual(m.GetNumAtoms(),6) m = Chem.MolFromSmarts(u'c1ccccc1') - self.failUnless(m is not None) - self.failUnlessEqual(m.GetNumAtoms(),6) + self.assertTrue(m is not None) + self.assertEqual(m.GetNumAtoms(),6) diff --git a/Code/GraphMol/Wrap/testConformer.py b/Code/GraphMol/Wrap/testConformer.py index 5b15c2a8f..4f1f2b0e1 100644 --- a/Code/GraphMol/Wrap/testConformer.py +++ b/Code/GraphMol/Wrap/testConformer.py @@ -36,20 +36,20 @@ class TestCase(unittest.TestCase): conf.SetId(0) cid = mol.AddConformer(conf) - self.failUnless(cid == 0) + self.assertTrue(cid == 0) conf2 = mol.GetConformer(0) - self.failUnless(conf2.GetId() == cid) + self.assertTrue(conf2.GetId() == cid) pt1 = conf2.GetAtomPosition(0) - self.failUnless(ptEq(pt1, Point3D(-0.5, 0.0, 0.0))) + self.assertTrue(ptEq(pt1, Point3D(-0.5, 0.0, 0.0))) pt2 = conf2.GetAtomPosition(1) - self.failUnless(ptEq(pt2, Point3D(1.0, 0.0, 0.0))) + self.assertTrue(ptEq(pt2, Point3D(1.0, 0.0, 0.0))) #changing conf should not change conf2 - related to issue 217 conf.SetAtomPosition(1, Point3D(2.0, 0.0, 0.0)) pt2 = conf2.GetAtomPosition(1) - self.failUnless(feq(pt2[0], 1.0)) + self.assertTrue(feq(pt2[0], 1.0)) conf = Chem.Conformer(2) conf.SetAtomPosition(0, Point3D(-0.5, 0.0, 0.0)) @@ -57,7 +57,7 @@ class TestCase(unittest.TestCase): conf.SetId(2) cid = mol.AddConformer(conf, 0) - self.failUnless(cid == 2) + self.assertTrue(cid == 2) conf3 = mol.GetConformer(2) def test0AddHds(self) : @@ -68,12 +68,12 @@ class TestCase(unittest.TestCase): cid = mol.AddConformer(conf) conf2 = mol.GetConformer() - self.failUnless(conf2.GetNumAtoms() == 2) + self.assertTrue(conf2.GetNumAtoms() == 2) nmol = Chem.AddHs(mol, 0,1) conf3 = nmol.GetConformer() - self.failUnless(conf3.GetNumAtoms() == 8) - self.failUnless(conf2.GetNumAtoms() == 2) + self.assertTrue(conf3.GetNumAtoms() == 8) + self.assertTrue(conf2.GetNumAtoms() == 2) targetCoords = [[-0.5, 0.0, 0.0], [1.0, 0.0, 0.0], @@ -86,21 +86,21 @@ class TestCase(unittest.TestCase): for i in range(8) : pt = conf3.GetAtomPosition(i) - self.failUnless(ptEq(pt, apply(Point3D,tuple(targetCoords[i])))) + self.assertTrue(ptEq(pt, Point3D(*tuple(targetCoords[i])))) def test2Issue217(self) : smi = 'c1ccccc1' m = Chem.MolFromSmiles(smi) addConf(m) - self.failUnless(m.GetNumConformers()==1); + self.assertTrue(m.GetNumConformers()==1); mb2 = Chem.MolToMolBlock(m) def test3Exceptions(self) : smi = 'c1ccccc1' m = Chem.MolFromSmiles(smi) addConf(m) - self.failUnless(m.GetNumConformers()==1) - self.failUnlessRaises(ValueError,lambda:m.GetConformer(2)) + self.assertTrue(m.GetNumConformers()==1) + self.assertRaises(ValueError,lambda:m.GetConformer(2)) def test4ConfTuple(self): smi = 'c1ccccc1' @@ -109,17 +109,17 @@ class TestCase(unittest.TestCase): addConf(m) confs = m.GetConformers() - self.failUnless(len(confs) == 10) + self.assertTrue(len(confs) == 10) for conf in confs: for i in range(6): pt = conf.GetAtomPosition(i) - self.failUnless(ptEq(pt, Point3D(0.0, 0.0, 0.0))) + self.assertTrue(ptEq(pt, Point3D(0.0, 0.0, 0.0))) m.RemoveAllConformers() - self.failUnless(m.GetNumConformers() == 0) + self.assertTrue(m.GetNumConformers() == 0) confs = m.GetConformers() - self.failUnless(confs == ()) + self.assertTrue(confs == ()) if __name__ == '__main__': unittest.main() diff --git a/Code/ML/Cluster/Murtagh/Clustering.cpp b/Code/ML/Cluster/Murtagh/Clustering.cpp index afa28f7e0..fbd7620cd 100644 --- a/Code/ML/Cluster/Murtagh/Clustering.cpp +++ b/Code/ML/Cluster/Murtagh/Clustering.cpp @@ -16,6 +16,8 @@ namespace python = boost::python; #include +#include + typedef double real; extern "C" @@ -153,7 +155,7 @@ Clustering_MurtaghDistCluster(python::object data, int nPts, int option) BOOST_PYTHON_MODULE(Clustering) { - import_array(); + rdkit_import_array(); python::def("MurtaghCluster", Clustering_MurtaghCluster, ( python::arg("data"), python::arg("nPts"), diff --git a/Code/ML/Data/cQuantize.cpp b/Code/ML/Data/cQuantize.cpp index 5457d7620..b7735cd13 100644 --- a/Code/ML/Data/cQuantize.cpp +++ b/Code/ML/Data/cQuantize.cpp @@ -7,12 +7,14 @@ // which is included in the file license.txt, found at the root // of the RDKit source tree. // +#include + #include +#include +#include namespace python = boost::python; -#include -#include #include /*********************************************** @@ -340,7 +342,7 @@ cQuantize_FindStartPoints(python::object values, python::object results, BOOST_PYTHON_MODULE(cQuantize) { - import_array(); + rdkit_import_array(); python::def("_RecurseOnBounds", cQuantize_RecurseOnBounds, ( python::arg("vals"), python::arg("pyCuts"), diff --git a/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp b/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp index ce74c99e8..a7f6475da 100644 --- a/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp +++ b/Code/ML/InfoTheory/Wrap/rdInfoTheory.cpp @@ -10,6 +10,7 @@ #define PY_ARRAY_UNIQUE_SYMBOL rdinfotheory_array_API #include #include "numpy/oldnumeric.h" +#include #include #include @@ -119,7 +120,7 @@ BOOST_PYTHON_MODULE(rdInfoTheory) "Module containing bunch of functions for information metrics and a ranker to rank bits" ; - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_index_error); python::register_exception_translator(&translate_value_error); diff --git a/Code/ML/InfoTheory/Wrap/testRanker.py b/Code/ML/InfoTheory/Wrap/testRanker.py index 4b57da6eb..dcc516815 100755 --- a/Code/ML/InfoTheory/Wrap/testRanker.py +++ b/Code/ML/InfoTheory/Wrap/testRanker.py @@ -1,9 +1,12 @@ -from rdkit import RDConfig,RDRandom import unittest +import numpy +import os + +from rdkit.six.moves import cPickle + +from rdkit import RDConfig,RDRandom from rdkit.ML.InfoTheory import rdInfoTheory as rdit from rdkit import DataStructs -import numpy -import os,cPickle def feq(a,b,tol=1e-4): return abs(a-b) fin) + self.assertTrue(fan > fin) def test2ranker(self) : nbits = 100 @@ -122,14 +125,14 @@ class TestCase(unittest.TestCase): res = rn.GetTopN(5) ids = [int(x[0]) for x in res] ids.sort() - self.failUnless(ids==[10,15,25,63,70]) + self.assertTrue(ids==[10,15,25,63,70]) try: res = rn.GetTopN(10) except: ok = 1 else: ok = 0 - self.failUnless(ok) + self.assertTrue(ok) def test3Issue140(self) : nbits = 2 @@ -145,18 +148,18 @@ class TestCase(unittest.TestCase): res = rn.GetTopN(1) except: res = None - self.failUnless(res is not None) + self.assertTrue(res is not None) def test4Issue237(self) : - inF = open(os.path.join(RDConfig.RDBaseDir,'Code','ML','InfoTheory','Wrap','testData','Issue237.pkl'),'rb') - examples,avail,bias,nB,nPoss = cPickle.load(inF) + with open(os.path.join(RDConfig.RDBaseDir,'Code','ML','InfoTheory','Wrap','testData','Issue237.pkl'),'rb') as inF: + examples,avail,bias,nB,nPoss = cPickle.load(inF) ranker = rdit.InfoBitRanker(nB,nPoss,rdit.InfoType.BIASENTROPY) ranker.SetMaskBits(avail) for ex in examples: ranker.AccumulateVotes(ex[1],ex[-1]) # this dumps core on linux if the bug isn't fixed: v=ranker.GetTopN(1) - self.failUnless(int(v[0][0])==12) + self.assertTrue(int(v[0][0])==12) if __name__ == '__main__': unittest.main() diff --git a/Code/Numerics/Alignment/Wrap/rdAlignment.cpp b/Code/Numerics/Alignment/Wrap/rdAlignment.cpp index 54321c6e2..10281920f 100644 --- a/Code/Numerics/Alignment/Wrap/rdAlignment.cpp +++ b/Code/Numerics/Alignment/Wrap/rdAlignment.cpp @@ -12,6 +12,7 @@ #include #include #include "numpy/arrayobject.h" +#include #include #include @@ -157,13 +158,11 @@ namespace RDNumeric { BOOST_PYTHON_MODULE(rdAlignment) { - import_array(); + rdkit_import_array(); python::scope().attr("__doc__") = "Module containing functions to align pairs of points in 3D" ; - import_array(); - std::string docString = "Compute the optimal alignment (minimum RMSD) between two set of points \n\n\ \n\ ARGUMENTS:\n\n\ diff --git a/Code/Numerics/Alignment/Wrap/testAlignment.py b/Code/Numerics/Alignment/Wrap/testAlignment.py index 623768048..db3a92060 100644 --- a/Code/Numerics/Alignment/Wrap/testAlignment.py +++ b/Code/Numerics/Alignment/Wrap/testAlignment.py @@ -1,4 +1,5 @@ ## Automatically adapted for numpy.oldnumeric Jun 27, 2008 by -c +from __future__ import print_function import rdkit.Numerics.rdAlignment as rdAlg from rdkit import Geometry @@ -44,29 +45,29 @@ class TestCase(unittest.TestCase): prbPts[1,1] = 3.0 res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) refLst = list(refPts) cnt = 0 for item in list(prbPts): - self.failUnless(lstFeq(transformPoint(res[1], item), refLst[cnt])) + self.assertTrue(lstFeq(transformPoint(res[1], item), refLst[cnt])) cnt+= 1 # repeat with with lists or tuples refPts = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) prbPts = ((2.0, 2.0, 0.0), (2.0, 3.0, 0.0)) res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) refPts = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] prbPts = [[2.0, 2.0, 0.0], [2.0, 3.0, 0.0]] res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) # mix it up refPts = Numeric.zeros((2,3), Numeric.Float) refPts[1,0] = 1.0 res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) def test2Weights(self) : refPts = Numeric.array([[-math.cos(math.pi/6), -math.sin(math.pi/6), 0.0], @@ -76,32 +77,32 @@ class TestCase(unittest.TestCase): [-2*math.sin(math.pi/6) + 3.0, -2*math.cos(math.pi/6), 4.0], [5.0, 0.0, 4.0]], Numeric.Float) res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 3.0)) + self.assertTrue(feq(res[0], 3.0)) target = [[-1.732, -1., 0.], [1.732, -1., 0.], [0., 2., 0.]] cnt = 0 for item in list(prbPts): - self.failUnless(lstFeq(transformPoint(res[1], item), target[cnt])) + self.assertTrue(lstFeq(transformPoint(res[1], item), target[cnt])) cnt += 1 weights = Numeric.array([1.0, 1.0, 2.0], Numeric.Float) res = rdAlg.GetAlignmentTransform(refPts, prbPts, weights) - self.failUnless(feq(res[0], 3.75)) + self.assertTrue(feq(res[0], 3.75)) cnt = 0 target = [[-1.732, -1.25, 0.], [1.732, -1.25, 0.], [0., 1.75, 0.]] for item in list(prbPts): - self.failUnless(lstFeq(transformPoint(res[1], item), target[cnt])) + self.assertTrue(lstFeq(transformPoint(res[1], item), target[cnt])) cnt += 1 weights = [1.0, 1.0, 2.0] res = rdAlg.GetAlignmentTransform(refPts, prbPts, weights) - self.failUnless(feq(res[0], 3.75)) + self.assertTrue(feq(res[0], 3.75)) weights = [1.0, 2.0, 2.0] res = rdAlg.GetAlignmentTransform(refPts, prbPts, weights) - self.failUnless(feq(res[0], 4.8)) + self.assertTrue(feq(res[0], 4.8)) def test3tetra(self) : refPts = Numeric.array([[0.0, 0.0, 0.0], @@ -111,21 +112,21 @@ class TestCase(unittest.TestCase): prbPts = Numeric.array([[2.0, 2.0, 3.0], [3.0, 2.0, 3.0], [2.0, 3.0, 3.0]], Numeric.Float) - self.failUnlessRaises(ValueError,lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) + self.assertRaises(ValueError,lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) prbPts = Numeric.array([[2.0, 2.0, 3.0], [3.0, 2.0, 3.0], [2.0, 3.0, 3.0], [2.0, 2.0, 4.0]], Numeric.Float) res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) wts = [1.0, 1.0, 1.0] - self.failUnlessRaises(ValueError,lambda : rdAlg.GetAlignmentTransform(refPts, prbPts, wts)) + self.assertRaises(ValueError,lambda : rdAlg.GetAlignmentTransform(refPts, prbPts, wts)) wts = [1.0, 1.0, 1.0, 1.0] res = rdAlg.GetAlignmentTransform(refPts, prbPts, wts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) # test reflection prbPts = Numeric.array([[2.0, 2.0, 3.0], @@ -133,14 +134,14 @@ class TestCase(unittest.TestCase): [2.0, 2.0, 4.0], [2.0, 3.0, 3.0]], Numeric.Float) res = rdAlg.GetAlignmentTransform(refPts, prbPts, wts) - self.failUnless(feq(res[0], 1.0)) + self.assertTrue(feq(res[0], 1.0)) res = rdAlg.GetAlignmentTransform(refPts, prbPts, wts, 1) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) cnt = 0 refLst = list(refPts) for item in list(prbPts): - self.failUnless(lstFeq(transformPoint(res[1], item), refLst[cnt])) + self.assertTrue(lstFeq(transformPoint(res[1], item), refLst[cnt])) cnt += 1 def test4points(self) : @@ -156,7 +157,7 @@ class TestCase(unittest.TestCase): ) res = rdAlg.GetAlignmentTransform(refPts, prbPts) - self.failUnless(feq(res[0], 0.0)) + self.assertTrue(feq(res[0], 0.0)) def test5errorHandling(self) : refPts = (Geometry.Point3D(0.0, 0.0, 0.0), @@ -165,26 +166,26 @@ class TestCase(unittest.TestCase): Geometry.Point3D(0.0, 0.0, 1.0), ) prbPts = (1,2,3,4,) - self.failUnlessRaises(ValueError, - lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) + self.assertRaises(ValueError, + lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) prbPts = () - self.failUnlessRaises(ValueError, - lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) + self.assertRaises(ValueError, + lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) prbPts = 1 - self.failUnlessRaises(ValueError, - lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) + self.assertRaises(ValueError, + lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) prbPts = (Geometry.Point3D(2.0, 2.0, 3.0), Geometry.Point3D(3.0, 2.0, 3.0), Geometry.Point3D(2.0, 3.0, 3.0), (2.0, 2.0, 5.0), ) - self.failUnlessRaises(ValueError, - lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) + self.assertRaises(ValueError, + lambda : rdAlg.GetAlignmentTransform(refPts, prbPts)) if __name__ == '__main__': - print "Testing Alignment Wrapper code:" + print("Testing Alignment Wrapper code:") unittest.main() diff --git a/Code/RDBoost/Wrap.cpp b/Code/RDBoost/Wrap.cpp index 2bd92ab3b..f93847ca9 100644 --- a/Code/RDBoost/Wrap.cpp +++ b/Code/RDBoost/Wrap.cpp @@ -14,6 +14,7 @@ // #define RDKIT_WRAP_SOURCE #include "Wrap.h" +#include "pyint_api.h" #include "Exceptions.h" #include #include diff --git a/Code/RDBoost/import_array.h b/Code/RDBoost/import_array.h new file mode 100644 index 000000000..93f6f2bd4 --- /dev/null +++ b/Code/RDBoost/import_array.h @@ -0,0 +1,18 @@ +#ifndef RDKIT_IMPORT_ARRAY_INCLUDED +#define RDKIT_IMPORT_ARRAY_INCLUDED + +#if PY_MAJOR_VERSION >= 3 + inline void * rdkit_import_array() +#else + inline void rdkit_import_array() +#endif + { + // numpy's import_array is defined as a macro that expands into a block + // statement that inlines a return. In python3 it returns a NULL value + // (to comply with the Py_InitModule signature) so it can't be called + // directly from within the BOOST_PYTHON_MODULE init function (that + // returns void) + import_array(); + } + +#endif diff --git a/Code/RDBoost/iterator_next.h b/Code/RDBoost/iterator_next.h new file mode 100644 index 000000000..24b4ccfff --- /dev/null +++ b/Code/RDBoost/iterator_next.h @@ -0,0 +1,11 @@ +#ifndef RDKIT_ITERATOR_NEXT_INCLUDED +#define RDKIT_ITERATOR_NEXT_INCLUDED + +#if PY_MAJOR_VERSION >= 3 +#define NEXT_METHOD "__next__" +#else +#define NEXT_METHOD "next" +#endif + + +#endif diff --git a/Code/RDBoost/list_indexing_suite.hpp b/Code/RDBoost/list_indexing_suite.hpp index 2b1e4a557..1606f46e2 100644 --- a/Code/RDBoost/list_indexing_suite.hpp +++ b/Code/RDBoost/list_indexing_suite.hpp @@ -14,6 +14,8 @@ # include # include +#include "pyint_api.h" + namespace boost { namespace python { // Forward declaration diff --git a/Code/RDBoost/pyint_api.h b/Code/RDBoost/pyint_api.h new file mode 100644 index 000000000..029c35a8e --- /dev/null +++ b/Code/RDBoost/pyint_api.h @@ -0,0 +1,9 @@ +#ifndef RDKIT_PYINT_API_INCLUDED +#define RDKIT_PYINT_API_INCLUDED + +#if PY_MAJOR_VERSION >= 3 +#define PyInt_FromLong PyLong_FromLong +#define PyInt_AsLong PyLong_AsLong +#endif + +#endif diff --git a/Code/RDBoost/python_streambuf.h b/Code/RDBoost/python_streambuf.h index 3aac6a914..7c74c0da3 100644 --- a/Code/RDBoost/python_streambuf.h +++ b/Code/RDBoost/python_streambuf.h @@ -219,8 +219,14 @@ class streambuf : public std::basic_streambuf read_buffer = py_read(buffer_size); char *read_buffer_data; bp::ssize_t py_n_read; +#if PY_MAJOR_VERSION >= 3 + // TODO review this. + if (PyBytes_AsStringAndSize(read_buffer.ptr(), + &read_buffer_data, &py_n_read) == -1) { +#else if (PyString_AsStringAndSize(read_buffer.ptr(), &read_buffer_data, &py_n_read) == -1) { +#endif setg(0, 0, 0); throw std::invalid_argument( "The method 'read' of the Python file object " diff --git a/Code/SimDivPickers/Wrap/rdSimDivPickers.cpp b/Code/SimDivPickers/Wrap/rdSimDivPickers.cpp index 15672ab9d..ef9a9d095 100644 --- a/Code/SimDivPickers/Wrap/rdSimDivPickers.cpp +++ b/Code/SimDivPickers/Wrap/rdSimDivPickers.cpp @@ -11,7 +11,7 @@ #define PY_ARRAY_UNIQUE_SYMBOL rdpicker_array_API #include #include "numpy/oldnumeric.h" - +#include namespace python = boost::python; @@ -24,7 +24,7 @@ BOOST_PYTHON_MODULE(rdSimDivPickers) "Module containing the diversity and similarity pickers" ; - import_array(); + rdkit_import_array(); python::register_exception_translator(&translate_index_error); python::register_exception_translator(&translate_value_error); diff --git a/External/AvalonTools/Wrap/testAvalonTools.py b/External/AvalonTools/Wrap/testAvalonTools.py index 2a6b0fcfd..88a9d9135 100755 --- a/External/AvalonTools/Wrap/testAvalonTools.py +++ b/External/AvalonTools/Wrap/testAvalonTools.py @@ -29,9 +29,9 @@ class TestCase(unittest.TestCase): def test1(self): m1 = Chem.MolFromSmiles('c1cccnc1') smi = pyAvalonTools.GetCanonSmiles(m1) - self.failUnless(smi=='c1ccncc1') + self.assertTrue(smi=='c1ccncc1') smi = pyAvalonTools.GetCanonSmiles('c1cccnc1',True) - self.failUnless(smi=='c1ccncc1') + self.assertTrue(smi=='c1ccncc1') def test2(self): tgts=['CC1=CC(=O)C=CC1=O','c2ccc1SC(=Nc1c2)SSC4=Nc3ccccc3S4','[O-][N+](=O)c1cc(Cl)c(O)c(c1)[N+]([O-])=O', @@ -39,97 +39,98 @@ class TestCase(unittest.TestCase): 'OC(=O)c1ccccc1C3=C2C=CC(=O)C(Br)=C2Oc4c3ccc(O)c4Br','CN(C)C2C(=O)c1ccccc1C(=O)C=2Cl', 'Cc3ccc2C(=O)c1ccccc1C(=O)c2c3[N+]([O-])=O',r'C/C(=N\O)/C(/C)=N/O', 'c1ccc(cc1)P(c2ccccc2)c3ccccc3'] - d= file(os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf'),'r').read() + with open(os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf'),'r') as f: + d = f.read() mbs = d.split('$$$$\n')[:10] smis = [pyAvalonTools.GetCanonSmiles(mb,False) for mb in mbs] - self.failUnless(smis==tgts) + self.assertTrue(smis==tgts) smis = [pyAvalonTools.GetCanonSmiles(smi,True) for smi in smis] - self.failUnless(smis==tgts) + self.assertTrue(smis==tgts) def test3(self): bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccn1')) - self.failUnlessEqual(len(bv),512) - self.failUnlessEqual(bv.GetNumOnBits(),20) + self.assertEqual(len(bv),512) + self.assertEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ccccc1')) - self.failUnlessEqual(bv.GetNumOnBits(),8) + self.assertEqual(bv.GetNumOnBits(),8) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1nnccc1')) - self.failUnlessEqual(bv.GetNumOnBits(),30) + self.assertEqual(bv.GetNumOnBits(),30) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1')) - self.failUnlessEqual(bv.GetNumOnBits(),27) + self.assertEqual(bv.GetNumOnBits(),27) bv = pyAvalonTools.GetAvalonFP(Chem.MolFromSmiles('c1ncncc1'),nBits=1024) - self.failUnlessEqual(len(bv),1024) - self.failUnless(bv.GetNumOnBits()>27) + self.assertEqual(len(bv),1024) + self.assertTrue(bv.GetNumOnBits()>27) def test4(self): bv = pyAvalonTools.GetAvalonFP('c1ccccn1',True) - self.failUnlessEqual(bv.GetNumOnBits(),20) + self.assertEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP('c1ccccc1',True) - self.failUnlessEqual(bv.GetNumOnBits(),8) + self.assertEqual(bv.GetNumOnBits(),8) bv = pyAvalonTools.GetAvalonFP('c1nnccc1',True) - self.failUnlessEqual(bv.GetNumOnBits(),30) + self.assertEqual(bv.GetNumOnBits(),30) bv = pyAvalonTools.GetAvalonFP('c1ncncc1',True) - self.failUnlessEqual(bv.GetNumOnBits(),27) + self.assertEqual(bv.GetNumOnBits(),27) bv = pyAvalonTools.GetAvalonFP('c1ncncc1',True,nBits=1024) - self.failUnlessEqual(len(bv),1024) - self.failUnless(bv.GetNumOnBits()>27) + self.assertEqual(len(bv),1024) + self.assertTrue(bv.GetNumOnBits()>27) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccn1')),False) - self.failUnlessEqual(len(bv),512) - self.failUnlessEqual(bv.GetNumOnBits(),20) + self.assertEqual(len(bv),512) + self.assertEqual(bv.GetNumOnBits(),20) bv = pyAvalonTools.GetAvalonFP(Chem.MolToMolBlock(Chem.MolFromSmiles('c1ccccc1')),False) - self.failUnlessEqual(bv.GetNumOnBits(),8) + self.assertEqual(bv.GetNumOnBits(),8) def test4b(self): words = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('c1ccccn1')) words2 = pyAvalonTools.GetAvalonFPAsWords(Chem.MolFromSmiles('Cc1ccccn1')) - self.failUnlessEqual(len(words),len(words2)) + self.assertEqual(len(words),len(words2)) for i,word in enumerate(words): - self.failUnlessEqual(word&words2[i],word) + self.assertEqual(word&words2[i],word) def test5(self): m = Chem.MolFromSmiles('c1ccccc1C1(CC1)N') pyAvalonTools.Generate2DCoords(m) - self.failUnlessEqual(m.GetNumConformers(),1) - self.failUnless(m.GetConformer(0).Is3D()==False) + self.assertEqual(m.GetNumConformers(),1) + self.assertTrue(m.GetConformer(0).Is3D()==False) def test6(self): mb=pyAvalonTools.Generate2DCoords('c1ccccc1C1(CC1)N',True) m = Chem.MolFromMolBlock(mb) - self.failUnlessEqual(m.GetNumConformers(),1) - self.failUnless(m.GetConformer(0).Is3D()==False) + self.assertEqual(m.GetNumConformers(),1) + self.assertTrue(m.GetConformer(0).Is3D()==False) def testRDK151(self): smi="C[C@H](F)Cl" m = Chem.MolFromSmiles(smi) temp = pyAvalonTools.GetCanonSmiles(smi,True) - self.failUnlessEqual(temp,smi) + self.assertEqual(temp,smi) temp = pyAvalonTools.GetCanonSmiles(m) - self.failUnlessEqual(temp,smi) + self.assertEqual(temp,smi) def testStruChk(self): smi_good='c1ccccc1C1(CC-C(C)C1)C' smi_bad='c1c(R)cccc1C1(CC-C(C)C1)C' r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT) - self.failUnlessEqual(r, 0) + self.assertEqual(r, 0) (err, fixed_mol) = pyAvalonTools.CheckMolecule(smi_good, True) - self.failUnlessEqual(err, 0) + self.assertEqual(err, 0) mol = Chem.MolFromSmiles(smi_good) (err, fixed_mol)=pyAvalonTools.CheckMolecule(mol) - self.failUnlessEqual(err, 0) + self.assertEqual(err, 0) (err, fixed_mol)=pyAvalonTools.CheckMoleculeString(smi_good,True) - self.failUnlessEqual(err, 0) - self.failIfEqual(fixed_mol,"") - self.failUnless(fixed_mol.find('M END')>0) + self.assertEqual(err, 0) + self.assertNotEqual(fixed_mol,"") + self.assertTrue(fixed_mol.find('M END')>0) (err, fixed_mol)=pyAvalonTools.CheckMolecule(smi_bad, False) - self.failIfEqual(err, 0) - self.failIf(fixed_mol) + self.assertNotEqual(err, 0) + self.assertFalse(fixed_mol) (err, fixed_mol)=pyAvalonTools.CheckMoleculeString(smi_bad, False) - self.failIfEqual(err, 0) - self.failIf(fixed_mol) + self.assertNotEqual(err, 0) + self.assertFalse(fixed_mol) pyAvalonTools.CloseCheckMolFiles() # def testIsotopeBug(self): @@ -148,7 +149,7 @@ class TestCase(unittest.TestCase): # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) -# self.failUnlessEqual(csmi,'[2H]C(C)C') +# self.assertEqual(csmi,'[2H]C(C)C') # mb="""D isotope problem.mol # Mrv0541 08141217122D @@ -164,7 +165,7 @@ class TestCase(unittest.TestCase): # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) -# self.failUnlessEqual(csmi,'[2H]C(C)C') +# self.assertEqual(csmi,'[2H]C(C)C') # mb="""D isotope problem.mol # Mrv0541 08141217122D @@ -180,7 +181,7 @@ class TestCase(unittest.TestCase): # M END # """ # csmi = pyAvalonTools.GetCanonSmiles(mb,False) -# self.failUnlessEqual(csmi,'[2H]C(C)C') +# self.assertEqual(csmi,'[2H]C(C)C') # def testChiralPBug(self): # mb="""Untitled Document-1 @@ -199,11 +200,11 @@ class TestCase(unittest.TestCase): # M END # """ # r = pyAvalonTools.InitializeCheckMol(STRUCHK_INIT) -# self.failUnlessEqual(r, 0) +# self.assertEqual(r, 0) # (err, fixed_mol) = pyAvalonTools.CheckMolecule(mb, False) -# self.failUnlessEqual(err, 0) -# self.failUnless(fixed_mol) -# self.failIfEqual(fixed_mol.GetAtomWithIdx(0).GetChiralTag(),Chem.rdchem.ChiralType.CHI_UNSPECIFIED) +# self.assertEqual(err, 0) +# self.assertTrue(fixed_mol) +# self.assertNotEqual(fixed_mol.GetAtomWithIdx(0).GetChiralTag(),Chem.rdchem.ChiralType.CHI_UNSPECIFIED) if __name__ == '__main__': unittest.main() diff --git a/External/INCHI-API/python/inchi.py b/External/INCHI-API/python/inchi.py index 45516e910..e5251feed 100644 --- a/External/INCHI-API/python/inchi.py +++ b/External/INCHI-API/python/inchi.py @@ -32,8 +32,9 @@ INCHI_AVAILABLE = True -import rdinchi import logging + +from rdkit.Chem import rdinchi from rdkit import RDLogger logger = RDLogger.logger() @@ -68,7 +69,7 @@ def MolFromInchi(inchi, sanitize=True, removeHs=True, logLevel=None, """ try: mol, retcode, message, log = rdinchi.InchiToMol(inchi, sanitize, removeHs) - except ValueError,e : + except ValueError as e : logger.error(str(e)) return None @@ -138,7 +139,7 @@ def MolToInchi(mol, options="", logLevel=None, treatWarningAsError=False): try: inchi, aux = MolToInchiAndAuxInfo(mol, options, logLevel=logLevel, treatWarningAsError=treatWarningAsError) - except InchiReadWriteError,inst: + except InchiReadWriteError as inst: inchi, aux, message = inst raise InchiReadWriteError(inchi, message) return inchi diff --git a/Projects/DbCLI/CreateDb.py b/Projects/DbCLI/CreateDb.py index 15c364307..4e4a86340 100644 --- a/Projects/DbCLI/CreateDb.py +++ b/Projects/DbCLI/CreateDb.py @@ -62,7 +62,8 @@ from rdkit.RDLogger import logger from rdkit.Chem.MolDb import Loader logger = logger() -import cPickle,sys,os +import sys,os +from rdkit.six.moves import cPickle from rdkit.Chem.MolDb.FingerprintUtils import BuildSigFactory,LayeredOptions from rdkit.Chem.MolDb import FingerprintUtils @@ -158,10 +159,10 @@ parser.add_option('--nameColumn','--nameCol',default=1,type='int', def CreateDb(options,dataFilename='',supplier=None): if not dataFilename and supplier is None: - raise ValueError,'Please provide either a data filename or a supplier' + raise ValueError('Please provide either a data filename or a supplier') if options.errFilename: - errFile=file(os.path.join(options.outDir,options.errFilename),'w+') + errFile=open(os.path.join(options.outDir,options.errFilename),'w+') else: errFile=None @@ -186,7 +187,7 @@ def CreateDb(options,dataFilename='',supplier=None): # guess the delimiter import csv sniffer = csv.Sniffer() - dlct=sniffer.sniff(file(dataFilename,'r').read(2000)) + dlct=sniffer.sniff(open(dataFilename,'r').read(2000)) options.delimiter=dlct.delimiter if not options.silent: logger.info('Guessing that delimiter is %s. Use --delimiter argument if this is wrong.'%repr(options.delimiter)) @@ -275,7 +276,7 @@ def CreateDb(options,dataFilename='',supplier=None): if options.doDescriptors: descrConn=DbConnect(os.path.join(options.outDir,options.descrDbName)) - calc = cPickle.load(file(options.descriptorCalcFilename,'rb')) + calc = cPickle.load(open(options.descriptorCalcFilename,'rb')) nms = [x for x in calc.GetDescriptorNames()] descrCurs = descrConn.GetCursor() descrs = ['guid integer not null primary key','%s varchar not null unique'%options.molIdName] @@ -439,7 +440,7 @@ if __name__=='__main__': parser.error('please provide a filename argument') dataFilename = args[0] try: - dataFile = file(dataFilename,'r') + dataFile = open(dataFilename,'r') except IOError: logger.error('input file %s does not exist'%(dataFilename)) sys.exit(0) diff --git a/Projects/DbCLI/SearchDb.py b/Projects/DbCLI/SearchDb.py index 2d908bb7e..528586f26 100644 --- a/Projects/DbCLI/SearchDb.py +++ b/Projects/DbCLI/SearchDb.py @@ -223,7 +223,7 @@ def RunSearch(options,queryFilename): elif options.outF=='': outF=None else: - outF = file(options.outF,'w+') + outF = open(options.outF,'w+') molsOut=False if options.sdfOut: diff --git a/Projects/DbCLI/TestDbCLI.py b/Projects/DbCLI/TestDbCLI.py index 95638521f..7f58e1142 100644 --- a/Projects/DbCLI/TestDbCLI.py +++ b/Projects/DbCLI/TestDbCLI.py @@ -13,75 +13,75 @@ class TestCase(unittest.TestCase): p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failUnless(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnless(d[0][0]==10) + self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') - self.failUnless(d[0][0]==10) + self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') - self.failUnless(d[0][0]==10) + self.assertTrue(d[0][0]==10) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') - self.failUnless(d[0][0]==10) + self.assertTrue(d[0][0]==10) p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--doGobbi2D', 'testData/bzr.sdf')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failUnless(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnless(d[0][0]==163) + self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/AtomPairs.sqlt') d = conn.GetData('atompairs',fields='count(*)') - self.failUnless(d[0][0]==163) + self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/Descriptors.sqlt') d = conn.GetData('descriptors_v1',fields='count(*)') - self.failUnless(d[0][0]==163) + self.assertTrue(d[0][0]==163) conn = DbConnect('testData/bzr/Fingerprints.sqlt') d = conn.GetData('rdkitfps',fields='count(*)') - self.failUnless(d[0][0]==163) + self.assertTrue(d[0][0]==163) def test2_1SearchFPs(self): - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failUnless(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) p = subprocess.Popen(('python', 'SearchDb.py','--dbDir=testData/bzr','--molFormat=sdf', '--topN=5','--outF=testData/bzr/search.out','testData/bzr.sdf')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/search.out')) + self.assertTrue(os.path.exists('testData/bzr/search.out')) inF = file('testData/bzr/search.out','r') lines=inF.readlines() inF=None - self.failUnless(len(lines)==163) + self.assertTrue(len(lines)==163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] @@ -90,31 +90,31 @@ class TestCase(unittest.TestCase): lastVal=1.0 while i0.7) + self.assertTrue(v>0.7) os.unlink('testData/bzr/search.out') @@ -357,21 +357,21 @@ class TestCase(unittest.TestCase): 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failIf(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failIf(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failIf(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnlessEqual(d[0][0],10) + self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') - self.failUnlessEqual(len(d),10) + self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] - self.failIf('smiles' in cns) + self.assertFalse('smiles' in cns) conn=None d=None @@ -389,62 +389,62 @@ class TestCase(unittest.TestCase): '--noSmiles','--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failIf(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failIf(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failIf(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnless(d[0][0]==10) + self.assertTrue(d[0][0]==10) d = conn.GetData('molecules',fields='*') - self.failUnless(len(d)==10) + self.assertTrue(len(d)==10) cns = [x.lower() for x in d.GetColumnNames()] - self.failIf('smiles' in cns) + self.assertFalse('smiles' in cns) p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noProps','--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failIf(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failIf(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failIf(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnlessEqual(d[0][0],10) + self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') - self.failUnlessEqual(len(d),10) + self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] - self.failUnless('smiles' in cns) + self.assertTrue('smiles' in cns) p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noFingerprints','--noLayeredFps','--noMorganFps','--noPairs','--noDescriptors', '--maxRowsCached=4', 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failIf(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failIf(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failIf(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Fingerprints.sqlt')) conn = DbConnect('testData/bzr/Compounds.sqlt') d = conn.GetData('molecules',fields='count(*)') - self.failUnlessEqual(d[0][0],10) + self.assertEqual(d[0][0],10) d = conn.GetData('molecules',fields='*') - self.failUnlessEqual(len(d),10) + self.assertEqual(len(d),10) cns = [x.lower() for x in d.GetColumnNames()] - self.failUnless('smiles' in cns) + self.assertTrue('smiles' in cns) p = subprocess.Popen(('python', 'CreateDb.py','--dbDir=testData/bzr','--molFormat=smiles', '--noFingerprints', @@ -452,13 +452,13 @@ class TestCase(unittest.TestCase): '--maxRowsCached=4', 'testData/bzr.smi')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/Compounds.sqlt')) - self.failIf(os.path.exists('testData/bzr/AtomPairs.sqlt')) - self.failIf(os.path.exists('testData/bzr/Descriptors.sqlt')) - self.failUnless(os.path.exists('testData/bzr/Fingerprints.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Compounds.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/AtomPairs.sqlt')) + self.assertFalse(os.path.exists('testData/bzr/Descriptors.sqlt')) + self.assertTrue(os.path.exists('testData/bzr/Fingerprints.sqlt')) def test5TestBackwardsCompat(self): if os.path.exists('testData/bzr/Compounds.sqlt'): @@ -474,7 +474,7 @@ class TestCase(unittest.TestCase): '--noFingerprints','--noDescriptors', 'testData/bzr.sdf')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None conn = DbConnect('testData/bzr/AtomPairs.sqlt') @@ -485,14 +485,14 @@ class TestCase(unittest.TestCase): '--pairTableName=tmp', 'testData/bzr.sdf')) res=p.wait() - self.failIf(res) + self.assertFalse(res) p=None - self.failUnless(os.path.exists('testData/bzr/search.out')) + self.assertTrue(os.path.exists('testData/bzr/search.out')) inF = file('testData/bzr/search.out','r') lines=inF.readlines() inF=None - self.failUnlessEqual(len(lines),163) + self.assertEqual(len(lines),163) splitLs=[x.strip().split(',') for x in lines] for line in splitLs: lbl = line[0] @@ -501,73 +501,73 @@ class TestCase(unittest.TestCase): lastVal=1.0 while i>> from rdkit.Chem import AllChem >>> template = AllChem.MolFromSmiles("CN1C(=NC(C1=O)(c2ccccc2)c3ccccc3)N") >>> mol = AllChem.MolFromPDBFile(os.path.join(RDConfig.RDCodeDir, 'Chem', 'test_data', '4DJU_lig.pdb')) - >>> print len([1 for b in template.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) + >>> len([1 for b in template.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) 8 - >>> print len([1 for b in mol.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) + >>> len([1 for b in mol.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) 22 Now assign the bond orders based on the template molecule >>> newMol = AllChem.AssignBondOrdersFromTemplate(template, mol) - >>> print len([1 for b in newMol.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) + >>> len([1 for b in newMol.GetBonds() if b.GetBondTypeAsDouble() == 1.0]) 8 Note that the template molecule should have no explicit hydrogens diff --git a/rdkit/Chem/AtomPairs/Pairs.py b/rdkit/Chem/AtomPairs/Pairs.py index 3dba62783..8752ad5e0 100755 --- a/rdkit/Chem/AtomPairs/Pairs.py +++ b/rdkit/Chem/AtomPairs/Pairs.py @@ -28,7 +28,7 @@ GetAtomPairFingerprintAsIntVect=rdMolDescriptors.GetAtomPairFingerprint numPathBits=rdMolDescriptors.AtomPairsParameters.numPathBits _maxPathLen=(1<>> m = Chem.MolFromSmiles('CCCCC') - >>> c1 = long(Utils.GetAtomCode(m.GetAtomWithIdx(0),1)) - >>> c2 = long(Utils.GetAtomCode(m.GetAtomWithIdx(1),2)) - >>> c3 = long(Utils.GetAtomCode(m.GetAtomWithIdx(2),2)) - >>> c4 = long(Utils.GetAtomCode(m.GetAtomWithIdx(3),1)) + >>> c1 = Utils.GetAtomCode(m.GetAtomWithIdx(0),1) + >>> c2 = Utils.GetAtomCode(m.GetAtomWithIdx(1),2) + >>> c3 = Utils.GetAtomCode(m.GetAtomWithIdx(2),2) + >>> c4 = Utils.GetAtomCode(m.GetAtomWithIdx(3),1) >>> t = c1 | (c2 << rdMolDescriptors.AtomPairsParameters.codeSize) | (c3 << (rdMolDescriptors.AtomPairsParameters.codeSize*2)) | (c4 << (rdMolDescriptors.AtomPairsParameters.codeSize*3)) >>> pyScorePath(m,(0,1,2,3),4)==t 1 @@ -38,10 +38,10 @@ def pyScorePath(mol,path,size,atomCodes=None): >>> m = Chem.MolFromSmiles('C=CC(=O)O') - >>> c1 = long(Utils.GetAtomCode(m.GetAtomWithIdx(0),1)) - >>> c2 = long(Utils.GetAtomCode(m.GetAtomWithIdx(1),2)) - >>> c3 = long(Utils.GetAtomCode(m.GetAtomWithIdx(2),2)) - >>> c4 = long(Utils.GetAtomCode(m.GetAtomWithIdx(4),1)) + >>> c1 = Utils.GetAtomCode(m.GetAtomWithIdx(0),1) + >>> c2 = Utils.GetAtomCode(m.GetAtomWithIdx(1),2) + >>> c3 = Utils.GetAtomCode(m.GetAtomWithIdx(2),2) + >>> c4 = Utils.GetAtomCode(m.GetAtomWithIdx(4),1) >>> t = c1 | (c2 << rdMolDescriptors.AtomPairsParameters.codeSize) | (c3 << (rdMolDescriptors.AtomPairsParameters.codeSize*2)) | (c4 << (rdMolDescriptors.AtomPairsParameters.codeSize*3)) >>> pyScorePath(m,(0,1,2,4),4)==t 1 @@ -71,9 +71,9 @@ def pyScorePath(mol,path,size,atomCodes=None): end -= 1 else: break - accum = 0L + accum = 0 for i in range(size): - accum |= long(codes[i]) << (rdMolDescriptors.AtomPairsParameters.codeSize*i) + accum |= codes[i] << (rdMolDescriptors.AtomPairsParameters.codeSize*i) return accum def ExplainPathScore(score,size=4): diff --git a/rdkit/Chem/AtomPairs/UnitTestDescriptors.py b/rdkit/Chem/AtomPairs/UnitTestDescriptors.py index f6740dacf..903a1055d 100755 --- a/rdkit/Chem/AtomPairs/UnitTestDescriptors.py +++ b/rdkit/Chem/AtomPairs/UnitTestDescriptors.py @@ -8,7 +8,9 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # -import unittest,cPickle,os,gzip +from __future__ import print_function +import unittest,os,gzip +from rdkit.six.moves import cPickle from rdkit import Chem from rdkit import RDConfig from rdkit.Chem.AtomPairs import Pairs,Torsions @@ -38,8 +40,8 @@ class TestCase(unittest.TestCase): # if pd[k]!=v: print '>>>3',k,v,pd[k] # else: # print '>>>4',k,v - self.failUnless(ap==atomPairs[i]) - self.failUnless(ap!=atomPairs[i-1]) + self.assertTrue(ap==atomPairs[i]) + self.assertTrue(ap!=atomPairs[i-1]) def testTorsionsRegression(self): inF = gzip.open(os.path.join(self.testDataPath,'mols1000.tts.pkl.gz'),'rb') @@ -47,22 +49,22 @@ class TestCase(unittest.TestCase): for i,m in enumerate(self.mols): tt = Torsions.GetTopologicalTorsionFingerprintAsIntVect(m) if tt!=torsions[i]: - print Chem.MolToSmiles(m) + print(Chem.MolToSmiles(m)) pd=tt.GetNonzeroElements() rd=torsions[i].GetNonzeroElements() for k,v in pd.iteritems(): if rd.has_key(k): - if rd[k]!=v: print '>>>1',k,v,rd[k] + if rd[k]!=v: print('>>>1',k,v,rd[k]) else: - print '>>>2',k,v + print('>>>2',k,v) for k,v in rd.iteritems(): if pd.has_key(k): - if pd[k]!=v: print '>>>3',k,v,pd[k] + if pd[k]!=v: print('>>>3',k,v,pd[k]) else: - print '>>>4',k,v + print('>>>4',k,v) - self.failUnless(tt==torsions[i]) - self.failUnless(tt!=torsions[i-1]) + self.assertTrue(tt==torsions[i]) + self.assertTrue(tt!=torsions[i-1]) if __name__ == '__main__': diff --git a/rdkit/Chem/AtomPairs/Utils.py b/rdkit/Chem/AtomPairs/Utils.py index 1d917a733..7b728b391 100755 --- a/rdkit/Chem/AtomPairs/Utils.py +++ b/rdkit/Chem/AtomPairs/Utils.py @@ -8,6 +8,7 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function from rdkit import Chem from rdkit.Chem import rdMolDescriptors import math @@ -47,12 +48,12 @@ def ExplainAtomCode(code,branchSubtract=0): piMask = (1<>rdMolDescriptors.AtomPairsParameters.numBranchBits nPi = int(code&piMask) - #print code, + #print(code,end='') code = code>>rdMolDescriptors.AtomPairsParameters.numPiBits - #print code, + #print(code,end='') typeIdx=int(code&typeMask) if typeIdx>> print '%.3f'%CosineSimilarity( (1,2,3,4,10), (2,4,6) ) + >>> print('%.3f'%CosineSimilarity( (1,2,3,4,10), (2,4,6) )) 0.516 - >>> print '%.3f'%CosineSimilarity( (1,2,2,3,4), (2,2,4,5,6) ) + >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (2,2,4,5,6) )) 0.714 - >>> print '%.3f'%CosineSimilarity( (1,2,2,3,4), (1,2,2,3,4) ) + >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (1,2,2,3,4) )) 1.000 - >>> print '%.3f'%CosineSimilarity( (1,2,2,3,4), (5,6,7) ) + >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), (5,6,7) )) 0.000 - >>> print '%.3f'%CosineSimilarity( (1,2,2,3,4), () ) + >>> print('%.3f'%CosineSimilarity( (1,2,2,3,4), () )) 0.000 """ diff --git a/rdkit/Chem/BRICS.py b/rdkit/Chem/BRICS.py index 46114377f..abdae9736 100644 --- a/rdkit/Chem/BRICS.py +++ b/rdkit/Chem/BRICS.py @@ -34,9 +34,12 @@ """ Implementation of the BRICS algorithm from Degen et al. ChemMedChem *3* 1503-7 (2008) """ +from __future__ import print_function +import sys,re,random from rdkit import Chem from rdkit.Chem import rdChemReactions as Reactions -import sys,re,random +from rdkit.six import iteritems, iterkeys, next +from rdkit.six.moves import range # These are the definitions that will be applied to fragment molecules: environs = { @@ -204,11 +207,11 @@ for gp in smartsGps: t=Reactions.ReactionFromSmarts(defn) t.Initialize() except: - print defn + print(defn) raise environMatchers={} -for env,sma in environs.iteritems(): +for env,sma in iteritems(environs): environMatchers[env]=Chem.MolFromSmarts(sma) bondMatchers=[] @@ -279,12 +282,12 @@ def FindBRICSBonds(mol,randomizeOrder=False,silent=True): """ letter = re.compile('[a-z,A-Z]') - indices = range(len(bondMatchers)) + indices = list(range(len(bondMatchers))) bondsDone=set() if randomizeOrder: random.shuffle(indices) envMatches={} - for env,patt in environMatchers.iteritems(): + for env,patt in iteritems(environMatchers): envMatches[env]=mol.HasSubstructMatch(patt) for gpIdx in indices: if randomizeOrder: @@ -388,7 +391,7 @@ def BRICSDecompose(mol,allNodes=None,minFragmentSize=1,onlyUseReactions=None, >>> sorted(res) ['[14*]c1ccccn1', '[16*]c1cccc([16*])c1', '[3*]O[3*]', '[4*]CCC', '[4*]C[8*]'] - >>> res = BRICSDecompose(m,returnMols=True) + >>> res = list(BRICSDecompose(m,returnMols=True)) >>> res[0] >>> smis = [Chem.MolToSmiles(x,True) for x in res] @@ -449,17 +452,17 @@ def BRICSDecompose(mol,allNodes=None,minFragmentSize=1,onlyUseReactions=None, newPool = {} while activePool: matched=False - nSmi = activePool.keys()[0] + nSmi = next(iterkeys(activePool)) mol = activePool.pop(nSmi) for rxnIdx,reaction in enumerate(reactionGp): if onlyUseReactions and (gpIdx,rxnIdx) not in onlyUseReactions: continue if not silent: - print '--------' - print smartsGps[gpIdx][rxnIdx] + print('--------') + print(smartsGps[gpIdx][rxnIdx]) ps = reaction.RunReactants((mol,)) if ps: - if not silent: print nSmi,'->',len(ps),'products' + if not silent: print(nSmi,'->',len(ps),'products') for prodSeq in ps: seqOk=True # we want to disqualify small fragments, so sort the product sequence by size @@ -481,7 +484,7 @@ def BRICSDecompose(mol,allNodes=None,minFragmentSize=1,onlyUseReactions=None, matched=True for nats,prod in prodSeq: pSmi = prod.pSmi - #print '\t',nats,pSmi + #print('\t',nats,pSmi) if pSmi not in allNodes: if not singlePass: activePool[pSmi] = prod diff --git a/rdkit/Chem/BuildFragmentCatalog.py b/rdkit/Chem/BuildFragmentCatalog.py index 8eed295b9..e5939a0b8 100755 --- a/rdkit/Chem/BuildFragmentCatalog.py +++ b/rdkit/Chem/BuildFragmentCatalog.py @@ -63,7 +63,10 @@ - --nBits=-1: specify the maximum number of bits to show details for """ -import sys,os,cPickle +from __future__ import print_function +import sys,os +from rdkit.six.moves import cPickle +from rdkit.six import next from rdkit import Chem from rdkit import RDConfig from rdkit.Chem import FragmentCatalog @@ -230,7 +233,7 @@ def ScoreFromLists(bitLists,suppl,catalog,maxPts=-1,actName='',acts=None, actName = suppl[0].GetPropNames()[-1] suppl.reset() for i in range(1,nPts+1): - mol = suppl.next() + mol = next(suppl) if not acts: act = int(mol.GetProp(actName)) else: @@ -284,7 +287,7 @@ def CalcGains(suppl,catalog,topN=-1,actName='',acts=None, except KeyError: message('ERROR: Molecule has no property: %s\n'%(actName)) message('\tAvailable properties are: %s\n'%(str(mol.GetPropNames()))) - raise KeyError,actName + raise KeyError(actName) else: act = acts[i] if i and not i%reportFreq: @@ -330,7 +333,7 @@ def CalcGainsFromFps(suppl,fps,topN=-1,actName='',acts=None, except KeyError: message('ERROR: Molecule has no property: %s\n'%(actName)) message('\tAvailable properties are: %s\n'%(str(mol.GetPropNames()))) - raise KeyError,actName + raise KeyError(actName) else: act = acts[i] if i and not i%reportFreq: @@ -404,23 +407,23 @@ def SupplierFromDetails(details): titleLine=details.hasTitle) if type(details.actCol)==types.IntType: suppl.reset() - m = suppl.next() + m = next(suppl) actName = m.GetPropNames()[details.actCol] details.actCol = actName if type(details.nameCol)==types.IntType: suppl.reset() - m = suppl.next() + m = next(suppl) nameName = m.GetPropNames()[details.nameCol] details.nameCol = nameName suppl.reset() if type(details.actCol)==types.IntType: suppl.reset() - m = suppl.next() + m = next(suppl) actName = m.GetPropNames()[details.actCol] details.actCol = actName if type(details.nameCol)==types.IntType: suppl.reset() - m = suppl.next() + m = next(suppl) nameName = m.GetPropNames()[details.nameCol] details.nameCol = nameName suppl.reset() @@ -428,9 +431,9 @@ def SupplierFromDetails(details): def Usage(): - print "This is BuildFragmentCatalog version %s"%(__VERSION_STRING) - print 'usage error' - #print __doc__ + print("This is BuildFragmentCatalog version %s"%(__VERSION_STRING)) + print('usage error') + #print(__doc__) sys.exit(-1) class RunDetails(object): diff --git a/rdkit/Chem/ChemUtils/AlignDepict.py b/rdkit/Chem/ChemUtils/AlignDepict.py index 0f5eb36d4..bcc64612c 100644 --- a/rdkit/Chem/ChemUtils/AlignDepict.py +++ b/rdkit/Chem/ChemUtils/AlignDepict.py @@ -21,10 +21,10 @@ def AlignDepict(mol,core,corePattern=None,acceptFailure=False): """ if core and corePattern: if not core.GetNumAtoms(onlyExplicit=True)==corePattern.GetNumAtoms(onlyExplicit=True): - raise ValueError,'When a pattern is provided, it must have the same number of atoms as the core' + raise ValueError('When a pattern is provided, it must have the same number of atoms as the core') coreMatch = core.GetSubstructMatch(corePattern) if not coreMatch: - raise ValueError,"Core does not map to itself" + raise ValueError("Core does not map to itself") else: coreMatch = range(core.GetNumAtoms(onlyExplicit=True)) if corePattern: @@ -34,7 +34,7 @@ def AlignDepict(mol,core,corePattern=None,acceptFailure=False): if not match: if not acceptFailure: - raise ValueError,'Substructure match with core not found.' + raise ValueError('Substructure match with core not found.') else: coordMap={} else: diff --git a/rdkit/Chem/ChemUtils/SDFToCSV.py b/rdkit/Chem/ChemUtils/SDFToCSV.py index cd7f7c359..31e85ecae 100644 --- a/rdkit/Chem/ChemUtils/SDFToCSV.py +++ b/rdkit/Chem/ChemUtils/SDFToCSV.py @@ -61,7 +61,7 @@ class TestCase(unittest.TestCase): pass def test1(self): import os - from cStringIO import StringIO + from rdkit.six.moves import cStringIO as StringIO fName = os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf') suppl = Chem.SDMolSupplier(fName) io = StringIO() @@ -75,13 +75,13 @@ class TestCase(unittest.TestCase): lines = txt.split('\n') if not lines[-1]: del lines[-1] - self.failUnless(len(lines)==201,'bad num lines: %d'%len(lines)) + self.assertTrue(len(lines)==201,'bad num lines: %d'%len(lines)) line0 = lines[0].split(',') - self.failUnlessEqual(len(line0),20) - self.failUnless(line0[0]=='SMILES') + self.assertEqual(len(line0),20) + self.assertTrue(line0[0]=='SMILES') def test2(self): import os - from cStringIO import StringIO + from rdkit.six.moves import cStringIO as StringIO fName = os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf') suppl = Chem.SDMolSupplier(fName) io = StringIO() @@ -95,11 +95,11 @@ class TestCase(unittest.TestCase): lines = txt.split('\n') if not lines[-1]: del lines[-1] - self.failUnless(len(lines)==6,'bad num lines: %d'%len(lines)) + self.assertTrue(len(lines)==6,'bad num lines: %d'%len(lines)) line0 = lines[0].split(',') - self.failUnlessEqual(len(line0),20) - self.failUnless(line0[0]=='AMW') - self.failUnless(line0[1]=='SMILES') + self.assertEqual(len(line0),20) + self.assertTrue(line0[0]=='AMW') + self.assertTrue(line0[1]=='SMILES') diff --git a/rdkit/Chem/ChemicalFeatures.py b/rdkit/Chem/ChemicalFeatures.py index 6659fe8ca..fa16521a9 100644 --- a/rdkit/Chem/ChemicalFeatures.py +++ b/rdkit/Chem/ChemicalFeatures.py @@ -8,8 +8,8 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # -from rdMolChemicalFeatures import * -from rdChemicalFeatures import * +from rdkit.Chem.rdMolChemicalFeatures import * +from rdkit.Chem.rdChemicalFeatures import * def MCFF_GetFeaturesForMol(self,mol,includeOnly=""): res = [] diff --git a/rdkit/Chem/Crippen.py b/rdkit/Chem/Crippen.py index cf868e5cc..8f1f3e020 100755 --- a/rdkit/Chem/Crippen.py +++ b/rdkit/Chem/Crippen.py @@ -16,6 +16,7 @@ """ +from __future__ import print_function import os from rdkit import RDConfig from rdkit import Chem @@ -35,7 +36,9 @@ def _ReadPatts(fileName): """ patts = {} order = [] - for line in open(fileName,'r').xreadlines(): + with open(fileName,'r') as f: + lines = f.readlines() + for line in lines: if line[0] != '#': splitLine = line.split('\t') if len(splitLine)>=4 and splitLine[0] != '': @@ -63,7 +66,7 @@ def _ReadPatts(fileName): l.append((sma,p,logP,mr)) patts[cha] = l else: - print 'Problems parsing smarts: %s'%(sma) + print('Problems parsing smarts: %s'%(sma)) return order,patts _GetAtomContribs=rdMolDescriptors._CalcCrippenContribs @@ -94,14 +97,14 @@ def _pyGetAtomContribs(mol,patts=None,order=None,verbose=0,force=0): for cha in order: pattVect = patts[cha] for sma,patt,logp,mr in pattVect: - #print 'try:',entry[0] + #print('try:',entry[0]) for match in mol.GetSubstructMatches(patt,False,False): firstIdx = match[0] if not doneAtoms[firstIdx]: doneAtoms[firstIdx]=1 atomContribs[firstIdx] = (logp,mr) if verbose: - print '\tAtom %d: %s %4.4f %4.4f'%(match[0],sma,logp,mr) + print('\tAtom %d: %s %4.4f %4.4f'%(match[0],sma,logp,mr)) nAtomsFound+=1 if nAtomsFound>=nAtoms: done=True @@ -201,13 +204,13 @@ if __name__=='__main__': ms.append((smi,Chem.MolFromSmiles(smi))) for smi,m in ms: - print 'Mol: %s'%(smi) + print('Mol: %s'%(smi)) logp = MolLogP(m,verbose=verbose) - print '----' + print('----') mr = MolMR(m,verbose=verbose) - print 'Res:',logp,mr + print('Res:',logp,mr) newM = Chem.AddHs(m) logp = MolLogP(newM,addHs=0) mr = MolMR(newM,addHs=0) - print '\t',logp,mr - print '-*-*-*-*-*-*-*-*' + print('\t',logp,mr) + print('-*-*-*-*-*-*-*-*') diff --git a/rdkit/Chem/Descriptors.py b/rdkit/Chem/Descriptors.py index 4a80a793f..6f87c132d 100755 --- a/rdkit/Chem/Descriptors.py +++ b/rdkit/Chem/Descriptors.py @@ -25,7 +25,7 @@ def _setupDescriptors(namespace): otherMods = [Chem] - for nm,thing in namespace.iteritems(): + for nm,thing in namespace.items(): if nm[0]!='_' and _isCallable(thing): _descList.append((nm,thing)) diff --git a/rdkit/Chem/Draw/UnitTestDraw.py b/rdkit/Chem/Draw/UnitTestDraw.py index 85b8606ec..306ca72d6 100755 --- a/rdkit/Chem/Draw/UnitTestDraw.py +++ b/rdkit/Chem/Draw/UnitTestDraw.py @@ -31,7 +31,7 @@ class TestCase(unittest.TestCase): foo,fn=tempfile.mkstemp(suffix='.png') foo=None - self.failUnlessEqual(os.path.getsize(fn),0) + self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) @@ -51,7 +51,7 @@ class TestCase(unittest.TestCase): foo,fn=tempfile.mkstemp(suffix='.png') foo=None - self.failUnlessEqual(os.path.getsize(fn),0) + self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) @@ -71,7 +71,7 @@ class TestCase(unittest.TestCase): foo,fn=tempfile.mkstemp(suffix='.png') foo=None - self.failUnlessEqual(os.path.getsize(fn),0) + self.assertEqual(os.path.getsize(fn),0) Draw.MolToFile(self.mol,fn) @@ -89,9 +89,9 @@ class TestCase(unittest.TestCase): os.environ['RDKIT_CANVAS']='cairo' img=Draw.MolToImage(self.mol,size=(300,300)) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testAggImage(self): try: @@ -100,9 +100,9 @@ class TestCase(unittest.TestCase): return os.environ['RDKIT_CANVAS']='agg' img=Draw.MolToImage(self.mol,size=(300,300)) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testSpingImage(self): try: @@ -111,9 +111,9 @@ class TestCase(unittest.TestCase): return os.environ['RDKIT_CANVAS']='sping' img=Draw.MolToImage(self.mol,size=(300,300)) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testCairoImageDash(self): try: @@ -123,9 +123,9 @@ class TestCase(unittest.TestCase): os.environ['RDKIT_CANVAS']='cairo' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testAggImageDash(self): try: @@ -134,9 +134,9 @@ class TestCase(unittest.TestCase): return os.environ['RDKIT_CANVAS']='agg' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testSpingImageDash(self): try: @@ -145,9 +145,9 @@ class TestCase(unittest.TestCase): return os.environ['RDKIT_CANVAS']='sping' img=Draw.MolToImage(self.mol,size=(300,300),kekulize=False) - self.failUnless(img) - self.failUnlessEqual(img.size[0],300) - self.failUnlessEqual(img.size[1],300) + self.assertTrue(img) + self.assertEqual(img.size[0],300) + self.assertEqual(img.size[1],300) def testGithubIssue54(self): try: @@ -157,24 +157,24 @@ class TestCase(unittest.TestCase): os.environ['RDKIT_CANVAS']='sping' mol = Chem.MolFromSmiles('c1([O])ccc(O)cc1') img = Draw.MolToImage(mol) - self.failUnless(img) + self.assertTrue(img) def testGithubIssue86(self): mol = Chem.MolFromSmiles('F[C@H](Cl)Br') for b in mol.GetBonds(): - self.failUnlessEqual(b.GetBondDir(),Chem.BondDir.NONE) + self.assertEqual(b.GetBondDir(),Chem.BondDir.NONE) img = Draw.MolToImage(mol,kekulize=False) - self.failUnless(img) + self.assertTrue(img) for b in mol.GetBonds(): - self.failUnlessEqual(b.GetBondDir(),Chem.BondDir.NONE) + self.assertEqual(b.GetBondDir(),Chem.BondDir.NONE) Chem.WedgeMolBonds(mol,mol.GetConformer()) obds = [x.GetBondDir() for x in mol.GetBonds()] - self.failUnlessEqual(obds.count(Chem.BondDir.NONE),2) + self.assertEqual(obds.count(Chem.BondDir.NONE),2) img = Draw.MolToImage(mol,kekulize=False) - self.failUnless(img) + self.assertTrue(img) nbds = [x.GetBondDir() for x in mol.GetBonds()] - self.failUnlessEqual(obds,nbds) + self.assertEqual(obds,nbds) diff --git a/rdkit/Chem/Draw/__init__.py b/rdkit/Chem/Draw/__init__.py index 732345ad4..dfe86c144 100644 --- a/rdkit/Chem/Draw/__init__.py +++ b/rdkit/Chem/Draw/__init__.py @@ -4,7 +4,7 @@ # All Rights Reserved # import os -from MolDrawing import MolDrawing,DrawingOptions +from rdkit.Chem.Draw.MolDrawing import MolDrawing,DrawingOptions def _getCanvas(): useAGG=False @@ -61,7 +61,7 @@ def MolToImage(mol, size=(300,300), kekulize=True, wedgeBonds=True, highlightBonds -- list of bonds to highlight (default []) """ if not mol: - raise ValueError,'Null molecule provided' + raise ValueError('Null molecule provided') if canvas is None: img,canvas=_createCanvas(size) else: @@ -114,9 +114,9 @@ def MolToFile(mol,fileName,size=(300,300),kekulize=True, wedgeBonds=True, """ # original contribution from Uwe Hoffmann if not fileName: - raise ValueError,'no fileName provided' + raise ValueError('no fileName provided') if not mol: - raise ValueError,'Null molecule provided' + raise ValueError('Null molecule provided') if imageType is None: imageType=os.path.splitext(fileName)[1][1:] @@ -189,7 +189,7 @@ def MolToMPL(mol,size=(300,300),kekulize=True, wedgeBonds=True, """ Generates a drawing of a molecule on a matplotlib canvas """ if not mol: - raise ValueError,'Null molecule provided' + raise ValueError('Null molecule provided') from mplCanvas import Canvas canvas = Canvas(size) if options is None: diff --git a/rdkit/Chem/Draw/aggCanvas.py b/rdkit/Chem/Draw/aggCanvas.py index e47df7743..004869925 100644 --- a/rdkit/Chem/Draw/aggCanvas.py +++ b/rdkit/Chem/Draw/aggCanvas.py @@ -38,7 +38,7 @@ class Canvas(CanvasBase): except ImportError: from PIL import Image if size is None: - raise ValueError,'please provide either an image or a size' + raise ValueError('please provide either an image or a size') img = Image.new('RGBA',size,"white") self.image = img self.draw = Draw(img) @@ -48,7 +48,7 @@ class Canvas(CanvasBase): else: self.size = size if imageType and imageType not in ('png','jpg'): - raise ValueError,'unsupported image type for agg canvas' + raise ValueError('unsupported image type for agg canvas') self.drawType=imageType self.fileName=fileName diff --git a/rdkit/Chem/Draw/cairoCanvas.py b/rdkit/Chem/Draw/cairoCanvas.py index 46a19cd48..6685670a4 100644 --- a/rdkit/Chem/Draw/cairoCanvas.py +++ b/rdkit/Chem/Draw/cairoCanvas.py @@ -16,7 +16,7 @@ except ImportError: import cairocffi as cairo if not hasattr(cairo.ImageSurface,'get_data') and \ not hasattr(cairo.ImageSurface,'get_data_as_rgba'): - raise ImportError,'cairo version too old' + raise ImportError('cairo version too old') import math @@ -65,8 +65,8 @@ class Canvas(CanvasBase): try: imgd = image.tostring("raw","BGRA") except SystemError: - r,g,b,a = image.split() - imgd = Image.merge("RGBA",(b,g,r,a)).tostring("raw","RGBA") + r,g,b,a = image.split() + imgd = Image.merge("RGBA",(b,g,r,a)).tostring("raw","RGBA") a = array.array('B',imgd) stride=image.size[0]*4 @@ -86,7 +86,7 @@ class Canvas(CanvasBase): elif imageType == "png": surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, size[0], size[1]) else: - raise ValueError, "Unrecognized file type. Valid choices are pdf, svg, ps, and png" + raise ValueError("Unrecognized file type. Valid choices are pdf, svg, ps, and png") ctx = cairo.Context(surface) ctx.set_source_rgb(1,1,1) ctx.paint() diff --git a/rdkit/Chem/Draw/spingCanvas.py b/rdkit/Chem/Draw/spingCanvas.py index c13b59f60..9c382250f 100644 --- a/rdkit/Chem/Draw/spingCanvas.py +++ b/rdkit/Chem/Draw/spingCanvas.py @@ -34,7 +34,7 @@ class Canvas(CanvasBase): elif imageType=="png": from rdkit.sping.PIL.pidPIL import PILCanvas as Canvas else: - raise ValueError,'unrecognized format: %s'%imageType + raise ValueError('unrecognized format: %s'%imageType) self.canvas = Canvas(size=size, name=name) if hasattr(self.canvas,'_image'): self._image = self.canvas._image diff --git a/rdkit/Chem/EState/EState.py b/rdkit/Chem/EState/EState.py index bb90bd392..d23e226f8 100755 --- a/rdkit/Chem/EState/EState.py +++ b/rdkit/Chem/EState/EState.py @@ -11,6 +11,7 @@ """ Basic EState definitions """ +from __future__ import print_function import numpy from rdkit import Chem @@ -81,7 +82,7 @@ if __name__ =='__main__': smis = ['CCCC','CCCCC','CCCCCC','CC(N)C(=O)O','CC(N)C(=O)[O-].[Na+]'] for smi in smis: m = Chem.MolFromSmiles(smi) - print smi + print(smi) inds = EStateIndices(m) - print '\t',inds + print('\t',inds) diff --git a/rdkit/Chem/EState/Fingerprinter.py b/rdkit/Chem/EState/Fingerprinter.py index 30a96874c..f5f4f6066 100755 --- a/rdkit/Chem/EState/Fingerprinter.py +++ b/rdkit/Chem/EState/Fingerprinter.py @@ -13,6 +13,7 @@ """ EState fingerprinting """ +from __future__ import print_function import numpy from rdkit.Chem.EState import EStateIndices from rdkit.Chem.EState import AtomTypes @@ -49,16 +50,16 @@ if __name__ == '__main__': smis = ['CC','CCC','c1[nH]cnc1CC(N)C(O)=O','NCCc1ccc(O)c(O)c1'] for smi in smis: m = Chem.MolFromSmiles(smi) - print smi,Chem.MolToSmiles(m) + print(smi,Chem.MolToSmiles(m)) types = AtomTypes.TypeAtoms(m) for i in range(m.GetNumAtoms()): - print '%d %4s: %s'%(i+1,m.GetAtomWithIdx(i).GetSymbol(),str(types[i])) + print('%d %4s: %s'%(i+1,m.GetAtomWithIdx(i).GetSymbol(),str(types[i]))) es = EStateIndices(m) counts,sums = FingerprintMol(m) for i in range(len(AtomTypes.esPatterns)): if counts[i]: name,patt = AtomTypes.esPatterns[i] - print '%6s, % 2d, % 5.4f'%(name,counts[i],sums[i]) + print('%6s, % 2d, % 5.4f'%(name,counts[i],sums[i])) for i in range(len(es)): - print '% 2d, % 5.4f'%(i+1,es[i]) - print '--------' + print('% 2d, % 5.4f'%(i+1,es[i])) + print('--------') diff --git a/rdkit/Chem/EState/UnitTestEState.py b/rdkit/Chem/EState/UnitTestEState.py index 1170d885e..4fa31eeb9 100755 --- a/rdkit/Chem/EState/UnitTestEState.py +++ b/rdkit/Chem/EState/UnitTestEState.py @@ -13,6 +13,7 @@ validation values are from the paper (JCICS _31_ 76-81 (1991)) """ +from __future__ import print_function import unittest import numpy from rdkit import Chem @@ -30,7 +31,7 @@ class TestCase(unittest.TestCase): inds = EState.EStateIndices(mol) maxV = max(abs(ans-inds)) - if show: print inds + if show: print(inds) assert maxV= self.threshold: @@ -109,15 +110,20 @@ class ThresholdScreener(SimilarityScreener): """ 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 @@ -139,6 +145,7 @@ class TopNScreener(SimilarityScreener): self._initTopN() self.Reset() return self + def next(self): if self._pos >= self.numToGet: raise StopIteration @@ -146,7 +153,9 @@ class TopNScreener(SimilarityScreener): 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: diff --git a/rdkit/Chem/Fraggle/FraggleSim.py b/rdkit/Chem/Fraggle/FraggleSim.py index 8ed5630a7..d9fad53a2 100644 --- a/rdkit/Chem/Fraggle/FraggleSim.py +++ b/rdkit/Chem/Fraggle/FraggleSim.py @@ -67,14 +67,14 @@ def delete_bonds(mol,bonds,ftype,hac): for b in bonds: #remove the bond - em.RemoveBond(b[0],b[1]) + em.RemoveBond(b[0],b[1]) - #now add attachement points - newAtomA = em.AddAtom(Chem.Atom(0)) - em.AddBond(b[0],newAtomA,Chem.BondType.SINGLE) + #now add attachement points + newAtomA = em.AddAtom(Chem.Atom(0)) + em.AddBond(b[0],newAtomA,Chem.BondType.SINGLE) - newAtomB = em.AddAtom(Chem.Atom(0)) - em.AddBond(b[1],newAtomB,Chem.BondType.SINGLE) + newAtomB = em.AddAtom(Chem.Atom(0)) + em.AddBond(b[1],newAtomB,Chem.BondType.SINGLE) #should be able to get away without sanitising mol #as the valencies should be okay diff --git a/rdkit/Chem/Fraggle/UnitTestFraggle.py b/rdkit/Chem/Fraggle/UnitTestFraggle.py index b21e72352..ee49d4905 100644 --- a/rdkit/Chem/Fraggle/UnitTestFraggle.py +++ b/rdkit/Chem/Fraggle/UnitTestFraggle.py @@ -7,7 +7,8 @@ # of the RDKit source tree. # from rdkit import RDConfig -import unittest,cPickle,os +import unittest,os +from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem.Fraggle import FraggleSim @@ -18,7 +19,7 @@ class TestCase(unittest.TestCase): """ mol = Chem.MolFromSmiles('COc1cc(CN2CCC(CC2)NC(=O)c2cncc(C)c2)c(OC)c2ccccc12') frags = FraggleSim.generate_fraggle_fragmentation(mol) - self.failUnlessEqual(len(frags),16) + self.assertEqual(len(frags),16) expected=('[*]C(=O)NC1CCN(Cc2cc(OC)c3ccccc3c2OC)CC1', '[*]C(=O)c1cncc(C)c1.[*]C1CCN(Cc2cc(OC)c3ccccc3c2OC)CC1', @@ -37,7 +38,7 @@ class TestCase(unittest.TestCase): '[*]c1cncc(C)c1.[*]C1CCN(Cc2cc(OC)c3ccccc3c2OC)CC1', '[*]c1cncc(C)c1.[*]c1cc(OC)c2ccccc2c1OC') for smi in frags: - self.failUnless(smi in expected) + self.assertTrue(smi in expected) if __name__ == '__main__': unittest.main() diff --git a/rdkit/Chem/FragmentCatalog.py b/rdkit/Chem/FragmentCatalog.py index 9d1607637..1adcb4748 100755 --- a/rdkit/Chem/FragmentCatalog.py +++ b/rdkit/Chem/FragmentCatalog.py @@ -8,10 +8,11 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # -from rdkit import Chem -from rdfragcatalog import * import sys +from rdkit import Chem +from rdkit.Chem.rdfragcatalog import * + def message(msg,dest=sys.stdout): dest.write(msg) diff --git a/rdkit/Chem/Fragments.py b/rdkit/Chem/Fragments.py index 5db52c1dd..5476002ee 100755 --- a/rdkit/Chem/Fragments.py +++ b/rdkit/Chem/Fragments.py @@ -47,7 +47,7 @@ def _LoadPatterns(fileName=None): ok=0 else: if not patt or patt.GetNumAtoms()==0: ok=0 - if not ok: raise ImportError,'Smarts %s could not be parsed'%(repr(sma)) + if not ok: raise ImportError('Smarts %s could not be parsed'%(repr(sma))) fn = lambda mol,countUnique=True,pattern=patt:_CountMatches(mol,pattern,unique=countUnique) fn.__doc__ = descr name = name.replace('=','_') diff --git a/rdkit/Chem/FunctionalGroups.py b/rdkit/Chem/FunctionalGroups.py index 48d881f54..52a3366e8 100644 --- a/rdkit/Chem/FunctionalGroups.py +++ b/rdkit/Chem/FunctionalGroups.py @@ -31,8 +31,9 @@ # # Created by Greg Landrum, October 2006 # +import os,weakref,re +from rdkit.six.moves import cStringIO as StringIO from rdkit import RDConfig -import os,weakref,cStringIO,re class FGHierarchyNode(object): children=None @@ -79,12 +80,12 @@ def BuildFuncGroupHierarchy(fileNm=None,data=None,force=False): fileNm = os.path.join(RDConfig.RDDataDir,'Functional_Group_Hierarchy.txt') if fileNm: - inF = file(fileNm,'r') + inF = open(fileNm,'r') lastFilename = fileNm elif data: - inF = cStringIO.StringIO(data) + inF = StringIO(data) else: - raise ValueError,"need data or filename" + raise ValueError("need data or filename") groupDefns={} res = [] @@ -97,16 +98,16 @@ def BuildFuncGroupHierarchy(fileNm=None,data=None,force=False): continue splitL = splitter.split(line) if len(splitL)<3: - raise FuncGroupFileParseError,"Input line %d (%s) is not long enough."%(lineNo,repr(line)) + raise FuncGroupFileParseError("Input line %d (%s) is not long enough."%(lineNo,repr(line))) label = splitL[0].strip() - if groupDefns.has_key(label): - raise FuncGroupFileParseError,"Duplicate label on line %d."%lineNo + if label in groupDefns: + raise FuncGroupFileParseError("Duplicate label on line %d."%lineNo) labelHierarchy = label.split('.') if len(labelHierarchy)>1: for i in range(len(labelHierarchy)-1): tmp = '.'.join(labelHierarchy[:i+1]) - if not groupDefns.has_key(tmp): - raise FuncGroupFileParseError,"Hierarchy member %s (line %d) not found."%(tmp,lineNo) + if not tmp in groupDefns: + raise FuncGroupFileParseError("Hierarchy member %s (line %d) not found."%(tmp,lineNo)) parent = groupDefns['.'.join(labelHierarchy[:-1])] else: parent = None @@ -118,7 +119,7 @@ def BuildFuncGroupHierarchy(fileNm=None,data=None,force=False): traceback.print_exc() patt = None if not patt: - raise FuncGroupFileParseError,'Smarts "%s" (line %d) could not be parsed.'%(smarts,lineNo) + raise FuncGroupFileParseError('Smarts "%s" (line %d) could not be parsed.'%(smarts,lineNo)) name = splitL[2].strip() diff --git a/rdkit/Chem/GraphDescriptors.py b/rdkit/Chem/GraphDescriptors.py index 3210a27c9..7eb33ecbb 100755 --- a/rdkit/Chem/GraphDescriptors.py +++ b/rdkit/Chem/GraphDescriptors.py @@ -13,6 +13,7 @@ """ +from __future__ import print_function from rdkit import Chem from rdkit.Chem import Graphs from rdkit.Chem import rdchem @@ -82,7 +83,7 @@ def _pyHallKierAlpha(m): else: rA = PeriodicTable.nameTable[symb][5] alpha = rA/rC - 1 - print atom.GetIdx(),atom.GetSymbol(),alpha + print(atom.GetIdx(),atom.GetSymbol(),alpha) alphaSum += alpha return alphaSum #HallKierAlpha.version="1.0.2" @@ -617,7 +618,7 @@ def BertzCT(mol, cutoff = 100, dMat = None, forceDMat = 1): bondDict, neighborList, vdList = _CreateBondDictEtc(mol, numAtoms) symmetryClasses = _AssignSymmetryClasses(mol, vdList, dMat, forceDMat, numAtoms, cutoff) - #print 'Symmm Classes:',symmetryClasses + #print('Symmm Classes:',symmetryClasses) for atomIdx in range(numAtoms): hingeAtomNumber = mol.GetAtomWithIdx(atomIdx).GetAtomicNum() atomTypeDict[hingeAtomNumber] = atomTypeDict.get(hingeAtomNumber,0)+1 @@ -628,7 +629,7 @@ def BertzCT(mol, cutoff = 100, dMat = None, forceDMat = 1): neighbor_iIdx = neighborList[atomIdx][i] NiClass = symmetryClasses[neighbor_iIdx] bond_i_order = _LookUpBondOrder(atomIdx, neighbor_iIdx, bondDict) - #print '\t',atomIdx,i,hingeAtomClass,NiClass,bond_i_order + #print('\t',atomIdx,i,hingeAtomClass,NiClass,bond_i_order) if (bond_i_order > 1) and (neighbor_iIdx > atomIdx): numConnections = bond_i_order*(bond_i_order - 1)/2 connectionKey = (min(hingeAtomClass, NiClass), max(hingeAtomClass, NiClass)) diff --git a/rdkit/Chem/Graphs.py b/rdkit/Chem/Graphs.py index c76e0d7ba..39f98c198 100755 --- a/rdkit/Chem/Graphs.py +++ b/rdkit/Chem/Graphs.py @@ -17,6 +17,7 @@ C/C++ codebase. import numpy from rdkit import Chem from rdkit import DataStructs +from rdkit.six.moves import xrange import types def CharacteristicPolynomial(mol,mat=None): diff --git a/rdkit/Chem/MACCSkeys.py b/rdkit/Chem/MACCSkeys.py index 53fa9b24e..77718758c 100755 --- a/rdkit/Chem/MACCSkeys.py +++ b/rdkit/Chem/MACCSkeys.py @@ -30,6 +30,7 @@ Rev history: May 2011 (gl): Update some definitions based on feedback from Andrew Dalke """ +from __future__ import print_function from rdkit import Chem from rdkit.Chem import rdMolDescriptors from rdkit import DataStructs @@ -221,7 +222,7 @@ def _InitKeys(keyList,keyDict): except: sma = None if not sma: - print 'SMARTS parser error for key #%d: %s'%(key,patt) + print('SMARTS parser error for key #%d: %s'%(key,patt)) else: keyList[key-1] = sma,count diff --git a/rdkit/Chem/MolCatalog.py b/rdkit/Chem/MolCatalog.py index 1b18b4d74..9c28ec9a9 100644 --- a/rdkit/Chem/MolCatalog.py +++ b/rdkit/Chem/MolCatalog.py @@ -2,7 +2,7 @@ # # Copyright (C) 2006 Greg Landrum # -from rdMolCatalog import * +from rdkit.Chem.rdMolCatalog import * diff --git a/rdkit/Chem/MolDb/FingerprintUtils.py b/rdkit/Chem/MolDb/FingerprintUtils.py index 563abe867..65aa6cacd 100644 --- a/rdkit/Chem/MolDb/FingerprintUtils.py +++ b/rdkit/Chem/MolDb/FingerprintUtils.py @@ -3,7 +3,9 @@ # Copyright (C) 2009 Greg Landrum # All Rights Reserved # -import cPickle +from __future__ import print_function +from rdkit.six.moves import cPickle +from rdkit.six import iterkeys from rdkit import DataStructs,Chem from rdkit import Chem @@ -14,7 +16,7 @@ similarityMethods={'RDK':DataStructs.ExplicitBitVect, 'Gobbi2D':DataStructs.SparseBitVect, 'Morgan':DataStructs.UIntSparseIntVect } -supportedSimilarityMethods=similarityMethods.keys() +supportedSimilarityMethods=list(iterkeys(similarityMethods)) class LayeredOptions: @@ -59,7 +61,7 @@ def BuildSigFactory(options=None,fdefFile=None, if options: fdefFile = options.fdefFile if not fdefFile: - raise ValueError,'bad fdef file' + raise ValueError('bad fdef file') from rdkit.Chem import ChemicalFeatures from rdkit.Chem.Pharm2D import SigFactory featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) @@ -88,7 +90,7 @@ def BuildPharm2DFP(mol): try: fp=Generate.Gen2DFingerprint(mol,sigFactory) except IndexError: - print 'FAIL:',Chem.MolToSmiles(mol,True) + print('FAIL:',Chem.MolToSmiles(mol,True)) raise return fp def BuildMorganFP(mol): diff --git a/rdkit/Chem/MolDb/Loader.py b/rdkit/Chem/MolDb/Loader.py index e4918176d..9869c9bac 100644 --- a/rdkit/Chem/MolDb/Loader.py +++ b/rdkit/Chem/MolDb/Loader.py @@ -10,6 +10,6 @@ try: import sqlalchemy except ImportError: - from Loader_orig import * + from rdkit.Chem.MolDb.Loader_orig import * else: - from Loader_sa import * + from rdkit.Chem.MolDb.Loader_sa import * diff --git a/rdkit/Chem/MolDb/Loader_orig.py b/rdkit/Chem/MolDb/Loader_orig.py index a66360077..d235eb62b 100644 --- a/rdkit/Chem/MolDb/Loader_orig.py +++ b/rdkit/Chem/MolDb/Loader_orig.py @@ -25,7 +25,7 @@ def ProcessMol(mol,typeConversions,globalProps,nDone,nameProp='_Name',nameCol='c skipSmiles=False, uniqNames=None,namesSeen=None): if not mol: - raise ValueError,'no molecule' + raise ValueError('no molecule') if keepHs: Chem.SanitizeMol(mol) try: diff --git a/rdkit/Chem/MolSurf.py b/rdkit/Chem/MolSurf.py index 543928834..87c8ccb44 100755 --- a/rdkit/Chem/MolSurf.py +++ b/rdkit/Chem/MolSurf.py @@ -14,6 +14,7 @@ descriptors. The MOE-like VSA descriptors are also calculated here """ +from __future__ import print_function from rdkit import Chem from rdkit.Chem.PeriodicTable import numTable from rdkit.Chem import Crippen @@ -185,8 +186,8 @@ def pyPEOE_VSA_(mol,bins=None,force=1): return res if bins is None: bins = chgBins Crippen._Init() - #print '\ts:',repr(mol.GetMol()) - #print '\t\t:',len(mol.GetAtoms()) + #print('\ts:',repr(mol.GetMol())) + #print('\t\t:',len(mol.GetAtoms())) rdPartialCharges.ComputeGasteigerCharges(mol) #propContribs = [float(x.GetProp('_GasteigerCharge')) for x in mol.GetAtoms()] @@ -378,7 +379,7 @@ def _pyTPSAContribs(mol,verbose=False): tmp = 30.5 - numNeighbors * 8.2 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 elif atNum==8: - #print nHs,nSing,chg + #print(nHs,nSing,chg) if numNeighbors == 1: if nHs==0 and nDoub==1 and chg==0: tmp = 17.07 elif nHs==1 and nSing==1 and chg==0: tmp = 20.23 @@ -393,7 +394,7 @@ def _pyTPSAContribs(mol,verbose=False): tmp = 28.5 - numNeighbors * 8.6 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 if verbose: - print '\t',atom.GetIdx(),atom.GetSymbol(),atNum,nHs,nSing,nDoub,nTrip,nArom,chg,tmp + print('\t',atom.GetIdx(),atom.GetSymbol(),atNum,nHs,nSing,nDoub,nTrip,nArom,chg,tmp) res[atom.GetIdx()] = tmp return res @@ -426,11 +427,11 @@ if __name__ == '__main__': smis = ['C(=O)O','c1ccccc1'] for smi in smis: m = Chem.MolFromSmiles(smi) - #print smi, LabuteASA(m); - print '-----------\n',smi - #print 'M:',['% 4.2f'%x for x in SMR_VSA_(m)] - #print 'L:',['% 4.2f'%x for x in SlogP_VSA_(m)] - print 'P:',['% 4.2f'%x for x in PEOE_VSA_(m)] - print 'P:',['% 4.2f'%x for x in PEOE_VSA_(m)] - print + #print(smi, LabuteASA(m)) + print('-----------\n',smi) + #print('M:',['% 4.2f'%x for x in SMR_VSA_(m)]) + #print('L:',['% 4.2f'%x for x in SlogP_VSA_(m)]) + print('P:',['% 4.2f'%x for x in PEOE_VSA_(m)]) + print('P:',['% 4.2f'%x for x in PEOE_VSA_(m)]) + print() diff --git a/rdkit/Chem/PandasTools.py b/rdkit/Chem/PandasTools.py index aa7ef37b6..e1c646485 100644 --- a/rdkit/Chem/PandasTools.py +++ b/rdkit/Chem/PandasTools.py @@ -76,13 +76,15 @@ This can be reverted using the ChangeMoleculeRendering method >>> print molX # doctest: +SKIP Mol ''' +from __future__ import print_function +from base64 import b64encode +import types +from rdkit.six.moves import cStringIO as StringIO from rdkit import Chem from rdkit.Chem import Draw -from base64 import b64encode -from StringIO import StringIO -import types + try: import pandas as pd v = pd.version.version.split('.') @@ -300,11 +302,12 @@ def AlignToScaffold(frame, molCol='ROMol', scaffoldCol='Murcko_SMILES'): if __name__ == "__main__": import sys if pd is None: - print >>sys.stderr,"pandas installation not found, skipping tests" + print("pandas installation not found, skipping tests", file=sys.stderr) else: v = pd.version.version.split('.') if v[0]=='0' and int(v[1])<10: - print >>sys.stderr,"pandas installation >=0.10 not found, skipping tests" + print("pandas installation >=0.10 not found, skipping tests", + file=sys.stderr) else: import doctest failed,tried=doctest.testmod(optionflags=doctest.ELLIPSIS+doctest.NORMALIZE_WHITESPACE) diff --git a/rdkit/Chem/Pharm2D/Generate.py b/rdkit/Chem/Pharm2D/Generate.py index 38a0b1e0f..a9aa78258 100755 --- a/rdkit/Chem/Pharm2D/Generate.py +++ b/rdkit/Chem/Pharm2D/Generate.py @@ -33,6 +33,7 @@ numbering """ +from __future__ import print_function from rdkit.Chem.Pharm2D import Utils,SigFactory from rdkit.RDLogger import logger logger = logger() @@ -44,7 +45,7 @@ def _ShortestPathsMatch(match,featureSet,sig,dMat,sigFactory): """ if _verbose: - print 'match:',match + print('match:',match) nPts = len(match) distsToCheck = Utils.nPointDistDict[nPts] nDists = len(distsToCheck) @@ -68,7 +69,7 @@ def _ShortestPathsMatch(match,featureSet,sig,dMat,sigFactory): idx = sigFactory.GetBitIdx(featureSet,dist,sortIndices=False) if _verbose: - print '\t',dist,minD,maxD,idx + print('\t',dist,minD,maxD,idx) if sigFactory.useCounts: sig[idx] = sig[idx]+1 @@ -95,10 +96,10 @@ def Gen2DFingerprint(mol,sigFactory,perms=None,dMat=None): """ if not isinstance(sigFactory,SigFactory.SigFactory): - raise ValueError,'bad factory' + raise ValueError('bad factory') featFamilies=sigFactory.GetFeatFamilies() if _verbose: - print '* feat famillies:',featFamilies + print('* feat famillies:',featFamilies) nFeats = len(featFamilies) minCount = sigFactory.minPointCount maxCount = sigFactory.maxPointCount @@ -121,7 +122,7 @@ def Gen2DFingerprint(mol,sigFactory,perms=None,dMat=None): # generate the matches: featMatches = sigFactory.GetMolFeats(mol) if _verbose: - print ' featMatches:',featMatches + print(' featMatches:',featMatches) sig = sigFactory.GetSignature() for perm in perms: @@ -138,8 +139,8 @@ def Gen2DFingerprint(mol,sigFactory,perms=None,dMat=None): # the proto-pharmacophore. matchPerms = [featMatches[x] for x in perm] if _verbose: - print '\n->Perm: %s'%(str(perm)) - print ' matchPerms: %s'%(str(matchPerms)) + print('\n->Perm: %s'%(str(perm))) + print(' matchPerms: %s'%(str(matchPerms))) # Get all unique combinations of those possible matches: matchesToMap=Utils.GetUniqueCombinations(matchPerms,featClasses) @@ -147,7 +148,7 @@ def Gen2DFingerprint(mol,sigFactory,perms=None,dMat=None): entry = [x[1] for x in entry] matchesToMap[i]=entry if _verbose: - print ' mtM:',matchesToMap + print(' mtM:',matchesToMap) for match in matchesToMap: if sigFactory.shortestPathsOnly: diff --git a/rdkit/Chem/Pharm2D/Matcher.py b/rdkit/Chem/Pharm2D/Matcher.py index 0a7fdb803..ee9355d60 100755 --- a/rdkit/Chem/Pharm2D/Matcher.py +++ b/rdkit/Chem/Pharm2D/Matcher.py @@ -22,8 +22,8 @@ from rdkit import Chem from rdkit.Chem.Pharm2D import Utils import types -import exceptions -class MatchError(exceptions.Exception): + +class MatchError(Exception): pass _verbose = 0 @@ -55,9 +55,9 @@ def GetAtomsMatchingBit(sigFactory,bitIdx,mol,dMat=None,justOne=0,matchingAtoms= assert sigFactory.shortestPathsOnly,'not implemented for non-shortest path signatures' nPts,featCombo,scaffold = sigFactory.GetBitInfo(bitIdx) if _verbose: - print 'info:',nPts - print '\t',featCombo - print '\t',scaffold + print('info:',nPts) + print('\t',featCombo) + print('\t',scaffold) if matchingAtoms is None: matchingAtoms = sigFactory.GetMolFeats(mol) @@ -72,12 +72,12 @@ def GetAtomsMatchingBit(sigFactory,bitIdx,mol,dMat=None,justOne=0,matchingAtoms= else: # one of the patterns didn't find a match, we # can return now - if _verbose: print 'no match found for feature:',featIdx + if _verbose: print('no match found for feature:',featIdx) return [] if _verbose: - print 'choices:' - print choices + print('choices:') + print(choices) if dMat is None: dMat = Chem.GetDistanceMatrix(mol,sigFactory.includeBondOrder) @@ -89,7 +89,7 @@ def GetAtomsMatchingBit(sigFactory,bitIdx,mol,dMat=None,justOne=0,matchingAtoms= res = [] for protoPharm in protoPharmacophores: - if _verbose: print 'protoPharm:',protoPharm + if _verbose: print('protoPharm:',protoPharm) for i in range(len(distsToCheck)): dLow,dHigh = sigFactory.GetBins()[scaffold[i]] a1,a2 = distsToCheck[i] @@ -100,11 +100,11 @@ def GetAtomsMatchingBit(sigFactory,bitIdx,mol,dMat=None,justOne=0,matchingAtoms= # idx1,idx2 = protoPharm[a1][0],protoPharm[a2][0] dist = dMat[idx1,idx2] - if _verbose: print '\t dist: %d->%d = %d (%d,%d)'%(idx1,idx2,dist,dLow,dHigh) + if _verbose: print('\t dist: %d->%d = %d (%d,%d)'%(idx1,idx2,dist,dLow,dHigh)) if dist < dLow or dist >= dHigh: break else: - if _verbose: print 'Found one' + if _verbose: print('Found one') # we found it protoPharm.sort() protoPharm = tuple(protoPharm) @@ -126,23 +126,23 @@ if __name__ == '__main__': mol = Chem.MolFromSmiles('OCC(=O)CCCN') Generate.Gen2DFingerprint(mol,sig) - print 'onbits:',list(sig.GetOnBits()) + print('onbits:',list(sig.GetOnBits())) _verbose=0 for bit in sig.GetOnBits(): atoms = GetAtomsMatchingBit(sig,bit,mol) - print '\tBit %d: '%(bit),atoms + print('\tBit %d: '%(bit),atoms) - print '--------------------------' + print('--------------------------') sig = factory.GetSignature() sig.SetIncludeBondOrder(1) Generate.Gen2DFingerprint(mol,sig) - print 'onbits:',list(sig.GetOnBits()) + print('onbits:',list(sig.GetOnBits())) for bit in sig.GetOnBits(): atoms = GetAtomsMatchingBit(sig,bit,mol) - print '\tBit %d: '%(bit),atoms + print('\tBit %d: '%(bit),atoms) diff --git a/rdkit/Chem/Pharm2D/SigFactory.py b/rdkit/Chem/Pharm2D/SigFactory.py index 8a6b1129b..499806a9a 100755 --- a/rdkit/Chem/Pharm2D/SigFactory.py +++ b/rdkit/Chem/Pharm2D/SigFactory.py @@ -12,6 +12,7 @@ """ +from __future__ import print_function, division from rdkit.DataStructs import SparseBitVect,IntSparseIntVect,LongSparseIntVect from rdkit.Chem.Pharm2D import Utils import copy @@ -166,10 +167,10 @@ class SigFactory(object): whichBins[i] = where res = scaffolds.index(tuple(whichBins)) if _verbose: - print '----- _fBI -----------' - print ' scaffolds:',scaffolds - print ' bins:',whichBins - print ' res:',res + print('----- _fBI -----------') + print(' scaffolds:',scaffolds) + print(' bins:',whichBins) + print(' res:',res) return res def GetFeatFamilies(self): @@ -208,9 +209,9 @@ class SigFactory(object): """ nPoints = len(featIndices) if nPoints>3: - raise NotImplementedError,'>3 points not supported' - if nPoints < self.minPointCount: raise IndexError,'bad number of points' - if nPoints > self.maxPointCount: raise IndexError,'bad number of points' + raise NotImplementedError('>3 points not supported') + if nPoints < self.minPointCount: raise IndexError('bad number of points') + if nPoints > self.maxPointCount: raise IndexError('bad number of points') # this is the start of the nPoint-point pharmacophores startIdx = self._starts[nPoints] @@ -223,29 +224,29 @@ class SigFactory(object): tmp.sort() featIndices = tmp - if featIndices[0]<0: raise IndexError,'bad feature index' - if max(featIndices)>=self._nFeats: raise IndexError,'bad feature index' + if featIndices[0]<0: raise IndexError('bad feature index') + if max(featIndices)>=self._nFeats: raise IndexError('bad feature index') if nPoints==3: featIndices,dists=Utils.OrderTriangle(featIndices,dists) offset = Utils.CountUpTo(self._nFeats,nPoints,featIndices) - if _verbose: print 'offset for feature %s: %d'%(str(featIndices),offset) + if _verbose: print('offset for feature %s: %d'%(str(featIndices),offset)) offset *= len(self._scaffolds[len(dists)]) try: if _verbose: - print '>>>>>>>>>>>>>>>>>>>>>>>' - print '\tScaffolds:',repr(self._scaffolds[len(dists)]),type(self._scaffolds[len(dists)]) - print '\tDists:',repr(dists),type(dists) - print '\tbins:',repr(self._bins),type(self._bins) + print('>>>>>>>>>>>>>>>>>>>>>>>') + print('\tScaffolds:',repr(self._scaffolds[len(dists)]),type(self._scaffolds[len(dists)])) + print('\tDists:',repr(dists),type(dists)) + print('\tbins:',repr(self._bins),type(self._bins)) bin = self._findBinIdx(dists,self._bins,self._scaffolds[len(dists)]) except ValueError: fams = self.GetFeatFamilies() fams = [fams[x] for x in featIndices] - raise IndexError,'distance bin not found: feats: %s; dists=%s; bins=%s; scaffolds: %s'%(fams,dists,self._bins,self._scaffolds) + raise IndexError('distance bin not found: feats: %s; dists=%s; bins=%s; scaffolds: %s'%(fams,dists,self._bins,self._scaffolds)) return startIdx + offset + bin @@ -268,7 +269,7 @@ class SigFactory(object): """ if idx >= self._sigSize: - raise IndexError,'bad index (%d) queried. %d is the max'%(idx,self._sigSize) + raise IndexError('bad index (%d) queried. %d is the max'%(idx,self._sigSize)) # first figure out how many points are in the p'cophore nPts = self.minPointCount while nPts < self.maxPointCount and self._starts[nPts+1]<=idx: @@ -277,7 +278,7 @@ class SigFactory(object): # how far are we in from the start point? offsetFromStart = idx - self._starts[nPts] if _verbose: - print '\t %d Points, %d offset'%(nPts,offsetFromStart) + print('\t %d Points, %d offset'%(nPts,offsetFromStart)) # lookup the number of scaffolds nDists = len(Utils.nPointDistDict[nPts]) @@ -286,17 +287,17 @@ class SigFactory(object): nScaffolds = len(scaffolds) # figure out to which proto-pharmacophore we belong: - protoIdx = offsetFromStart / nScaffolds + protoIdx = offsetFromStart // nScaffolds indexCombos = Utils.GetIndexCombinations(self._nFeats,nPts) combo = tuple(indexCombos[protoIdx]) if _verbose: - print '\t combo: %s'%(str(combo)) + print('\t combo: %s'%(str(combo))) # and which scaffold: scaffoldIdx = offsetFromStart % nScaffolds scaffold = scaffolds[scaffoldIdx] if _verbose: - print '\t scaffold: %s'%(str(scaffold)) + print('\t scaffold: %s'%(str(scaffold))) return nPts,combo,scaffold def Init(self): diff --git a/rdkit/Chem/Pharm2D/UnitTestGobbi.py b/rdkit/Chem/Pharm2D/UnitTestGobbi.py index 097c88a4a..1ccfe2598 100755 --- a/rdkit/Chem/Pharm2D/UnitTestGobbi.py +++ b/rdkit/Chem/Pharm2D/UnitTestGobbi.py @@ -11,8 +11,10 @@ """unit testing code for the signatures """ +from __future__ import print_function import unittest import os +from rdkit.six import next from rdkit import RDConfig from rdkit import Chem from rdkit.Chem.Pharm2D import Gobbi_Pharm2D,Generate @@ -101,11 +103,11 @@ class TestCase(unittest.TestCase): shouldMatch,mapList=d[k] feats=self.factory.featFactory.GetFeaturesForMol(mol,includeOnly=k) if shouldMatch: - self.failUnless(feats) - self.failUnlessEqual(len(feats),len(mapList)) + self.assertTrue(feats) + self.assertEqual(len(feats),len(mapList)) aids = [(x.GetAtomIds()[0],) for x in feats] aids.sort() - self.failUnlessEqual(tuple(aids),mapList) + self.assertEqual(tuple(aids),mapList) def test2Sigs(self): probes = [('O=CCC=O',(149,)), @@ -114,21 +116,21 @@ class TestCase(unittest.TestCase): ] for smi,tgt in probes: sig = Generate.Gen2DFingerprint(Chem.MolFromSmiles(smi),self.factory) - self.failUnlessEqual(len(sig),39972) + self.assertEqual(len(sig),39972) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(len(bs),len(tgt)) - self.failUnlessEqual(bs,tgt) + self.assertEqual(len(bs),len(tgt)) + self.assertEqual(bs,tgt) def testOrderBug(self): sdFile = os.path.join(RDConfig.RDCodeDir,'Chem','Pharm2D','test_data','orderBug.sdf') suppl = Chem.SDMolSupplier(sdFile) - m1 =suppl.next() - m2 = suppl.next() + m1 = next(suppl) + m2 = next(suppl) sig1 = Generate.Gen2DFingerprint(m1,self.factory) sig2 = Generate.Gen2DFingerprint(m2,self.factory) ob1 = set(sig1.GetOnBits()) ob2 = set(sig2.GetOnBits()) - self.failUnlessEqual(sig1,sig2) + self.assertEqual(sig1,sig2) def testOrderBug2(self): from rdkit.Chem import Randomize @@ -142,27 +144,27 @@ class TestCase(unittest.TestCase): m2 = Chem.MolFromSmiles(csmi) #m2.Debug() sig2 = Generate.Gen2DFingerprint(m2,self.factory) - self.failUnless(list(sig1.GetOnBits())==list(sig2.GetOnBits()),'%s %s'%(smi,csmi)) - self.failUnlessEqual(DataStructs.DiceSimilarity(sig1,sig2),1.0) - self.failUnlessEqual(sig1,sig2) + self.assertTrue(list(sig1.GetOnBits())==list(sig2.GetOnBits()),'%s %s'%(smi,csmi)) + self.assertEqual(DataStructs.DiceSimilarity(sig1,sig2),1.0) + self.assertEqual(sig1,sig2) for i in range(10): m2 = Randomize.RandomizeMol(m1) sig2 = Generate.Gen2DFingerprint(m2,self.factory) if sig2!=sig1: Generate._verbose=True - print '----------------' + print('----------------') sig1 = Generate.Gen2DFingerprint(m1,self.factory) - print '----------------' + print('----------------') sig2 = Generate.Gen2DFingerprint(m2,self.factory) - print '----------------' - print Chem.MolToMolBlock(m1) - print '----------------' - print Chem.MolToMolBlock(m2) - print '----------------' + print('----------------') + print(Chem.MolToMolBlock(m1)) + print('----------------') + print(Chem.MolToMolBlock(m2)) + print('----------------') s1 = set(sig1.GetOnBits()) s2= set(sig2.GetOnBits()) - print s1.difference(s2) - self.failUnlessEqual(sig1,sig2) + print(s1.difference(s2)) + self.assertEqual(sig1,sig2) if __name__ == '__main__': diff --git a/rdkit/Chem/Pharm2D/UnitTestSignature.py b/rdkit/Chem/Pharm2D/UnitTestSignature.py index dfc02f7a0..92df002ec 100755 --- a/rdkit/Chem/Pharm2D/UnitTestSignature.py +++ b/rdkit/Chem/Pharm2D/UnitTestSignature.py @@ -32,17 +32,17 @@ class TestCase(unittest.TestCase): self.factory.maxPointCount=2 self.factory.Init() sig = self.factory.GetSignature() - self.failUnlessEqual(len(sig),45) + self.assertEqual(len(sig),45) self.factory.maxPointCount=3 self.factory.Init() sig = self.factory.GetSignature() - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) self.factory.maxPointCount=4 self.factory.Init() sig = self.factory.GetSignature() - self.failUnlessEqual(len(sig),18000) + self.assertEqual(len(sig),18000) def test2BitIdx(self): data = [ @@ -61,11 +61,11 @@ class TestCase(unittest.TestCase): for tpl in data: patts,dists,bit = tpl idx = self.factory.GetBitIdx(patts,dists) - self.failUnlessEqual(bit,idx) + self.assertEqual(bit,idx) cnt,feats,bins = self.factory.GetBitInfo(bit) - self.failUnlessEqual(cnt,len(patts)) - self.failUnlessEqual(feats,patts) + self.assertEqual(cnt,len(patts)) + self.assertEqual(feats,patts) def test3BitIdx(self): """ test 3 point p'cophore ids, @@ -74,7 +74,7 @@ class TestCase(unittest.TestCase): """ self.factory.SetBins(((0,2),(2,4),(4,8))) self.factory.Init() - self.failUnlessEqual(self.factory.GetSigSize(),990) + self.assertEqual(self.factory.GetSigSize(),990) probes = [((0,0,0),(1,3,1),54), ((0,0,0),(3,1,1),54), ((0,0,0),(1,1,3),54), @@ -83,18 +83,18 @@ class TestCase(unittest.TestCase): ] for patts,dists,ans in probes: idx = self.factory.GetBitIdx(patts,dists) - self.failUnlessEqual(idx,ans) + self.assertEqual(idx,ans) cnt,feats,bins = self.factory.GetBitInfo(ans) - self.failUnlessEqual(cnt,len(patts)) - self.failUnlessEqual(feats,patts) + self.assertEqual(cnt,len(patts)) + self.assertEqual(feats,patts) def test4BitIdx(self): self.factory.trianglePruneBins=True self.factory.Init() sig = self.factory.GetSignature() - self.failUnlessEqual(len(sig),885) + self.assertEqual(len(sig),885) probes = [((0,0,0),(1,3,1),52), ((0,0,0),(1,1,3),52), @@ -104,10 +104,10 @@ class TestCase(unittest.TestCase): ] for patts,dists,ans in probes: idx = self.factory.GetBitIdx(patts,dists) - self.failUnlessEqual(idx,ans) + self.assertEqual(idx,ans) cnt,feats,bins = self.factory.GetBitInfo(ans) - self.failUnlessEqual(cnt,len(patts)) - self.failUnlessEqual(feats,patts) + self.assertEqual(cnt,len(patts)) + self.assertEqual(feats,patts) def test5SimpleSig(self): factory = self.factory @@ -118,15 +118,15 @@ class TestCase(unittest.TestCase): mol = Chem.MolFromSmiles('O=CCC=O') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,(1,)) + self.assertEqual(bs,(1,)) mol = Chem.MolFromSmiles('O=CC(CC=O)CCC=O') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,(1,2,67)) + self.assertEqual(bs,(1,2,67)) def test6SimpleSigCounts(self): factory = self.factory @@ -138,18 +138,18 @@ class TestCase(unittest.TestCase): mol = Chem.MolFromSmiles('O=CCC=O') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(sig.GetLength(),990) + self.assertEqual(sig.GetLength(),990) cs = tuple(sig.GetNonzeroElements().iteritems()) - self.failUnlessEqual(cs,((1,1),)) + self.assertEqual(cs,((1,1),)) mol = Chem.MolFromSmiles('O=CC(CC=O)CCC=O') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(sig.GetLength(),990) + self.assertEqual(sig.GetLength(),990) elems = sig.GetNonzeroElements() bs = elems.keys() bs.sort() cs = [(x,elems[x]) for x in bs] - self.failUnlessEqual(tuple(cs),((1,2),(2,1),(67,1))) + self.assertEqual(tuple(cs),((1,2),(2,1),(67,1))) def test7SimpleSigSkip(self): factory = self.factory @@ -161,9 +161,9 @@ class TestCase(unittest.TestCase): mol = Chem.MolFromSmiles('O=CCC=O') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),570) + self.assertEqual(len(sig),570) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,()) + self.assertEqual(bs,()) def test8MultiPointMatches(self): factory = self.factory @@ -174,15 +174,15 @@ class TestCase(unittest.TestCase): mol = Chem.MolFromSmiles('O=Cc1ccccc1') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,(3,)) + self.assertEqual(bs,(3,)) mol = Chem.MolFromSmiles('O=CCCCCCCCCc1ccccc1') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,()) + self.assertEqual(bs,()) # FIX: add test for perms argument to Gen2DFingerprint @@ -198,15 +198,15 @@ class TestCase(unittest.TestCase): mol = Chem.MolFromSmiles('[O-]CCC(=O)') sig=Generate.Gen2DFingerprint(mol,self.factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,(1,)) + self.assertEqual(bs,(1,)) self.factory.includeBondOrder=True sig=Generate.Gen2DFingerprint(mol,self.factory) - self.failUnlessEqual(len(sig),990) + self.assertEqual(len(sig),990) bs = tuple(sig.GetOnBits()) - self.failUnlessEqual(bs,(0,)) + self.assertEqual(bs,(0,)) def testDefaultFactory(self): from rdkit.Chem import Pharm2D @@ -214,30 +214,30 @@ class TestCase(unittest.TestCase): #Generate._verbose=True mol = Chem.MolFromSmiles('OCCC(=O)') sig=Generate.Gen2DFingerprint(mol,factory) - self.failUnlessEqual(len(sig),19355) - self.failUnlessEqual(tuple(sig.GetOnBits()),(2,16,21,84,1274,4361,)) + self.assertEqual(len(sig),19355) + self.assertEqual(tuple(sig.GetOnBits()),(2,16,21,84,1274,4361,)) nPts,combo,scaffold,labels,dMat=factory._GetBitSummaryData(21) - self.failUnlessEqual(nPts,2) - self.failUnlessEqual(labels,['Acceptor','Hydrophobe']) - self.failUnlessEqual(list(dMat[0]),[0,0]) - self.failUnlessEqual(list(dMat[1]),[0,0]) + self.assertEqual(nPts,2) + self.assertEqual(labels,['Acceptor','Hydrophobe']) + self.assertEqual(list(dMat[0]),[0,0]) + self.assertEqual(list(dMat[1]),[0,0]) txt=factory.GetBitDescription(21) - self.failUnlessEqual(txt,'Acceptor Hydrophobe |0 0|0 0|') + self.assertEqual(txt,'Acceptor Hydrophobe |0 0|0 0|') nPts,combo,scaffold,labels,dMat=factory._GetBitSummaryData(2) - self.failUnlessEqual(nPts,2) - self.failUnlessEqual(labels,['Acceptor','Acceptor']) - self.failUnlessEqual(list(dMat[0]),[0,2]) - self.failUnlessEqual(list(dMat[1]),[2,0]) + self.assertEqual(nPts,2) + self.assertEqual(labels,['Acceptor','Acceptor']) + self.assertEqual(list(dMat[0]),[0,2]) + self.assertEqual(list(dMat[1]),[2,0]) nPts,combo,scaffold,labels,dMat=factory._GetBitSummaryData(4361) - self.failUnlessEqual(nPts,3) - self.failUnlessEqual(labels,['Acceptor','Donor','Hydrophobe']) - self.failUnlessEqual(list(dMat[0]),[0,2,0]) - self.failUnlessEqual(list(dMat[1]),[2,0,0]) - self.failUnlessEqual(list(dMat[2]),[0,0,0]) - self.failUnlessEqual(factory.GetBitDescription(4361), + self.assertEqual(nPts,3) + self.assertEqual(labels,['Acceptor','Donor','Hydrophobe']) + self.assertEqual(list(dMat[0]),[0,2,0]) + self.assertEqual(list(dMat[1]),[2,0,0]) + self.assertEqual(list(dMat[2]),[0,0,0]) + self.assertEqual(factory.GetBitDescription(4361), 'Acceptor Donor Hydrophobe |0 2 0|2 0 0|0 0 0|') if __name__ == '__main__': diff --git a/rdkit/Chem/Pharm2D/Utils.py b/rdkit/Chem/Pharm2D/Utils.py index fed156a1e..adc1ee71a 100755 --- a/rdkit/Chem/Pharm2D/Utils.py +++ b/rdkit/Chem/Pharm2D/Utils.py @@ -17,6 +17,7 @@ numbering """ +from __future__ import print_function, division import numpy # @@ -135,7 +136,7 @@ def NumCombinations(nItems,nSlots): global _numCombDict res = _numCombDict.get((nItems,nSlots),-1) if res == -1: - res = _fact(nItems+nSlots-1) / (_fact(nItems-1)*_fact(nSlots)) + res = _fact(nItems+nSlots-1) // (_fact(nItems-1)*_fact(nSlots)) _numCombDict[(nItems,nSlots)] = res return res @@ -165,8 +166,8 @@ def CountUpTo(nItems,nSlots,vs,idx=0,startAt=0): """ global _countCache if _verbose: - print ' '*idx,'CountUpTo(%d)'%idx,vs[idx],startAt - if idx==0 and _countCache.has_key((nItems,nSlots,tuple(vs))): + print(' '*idx,'CountUpTo(%d)'%idx,vs[idx],startAt) + if idx==0 and (nItems,nSlots,tuple(vs)) in _countCache: return _countCache[(nItems,nSlots,tuple(vs))] elif idx >= nSlots: accum = 0 @@ -179,11 +180,11 @@ def CountUpTo(nItems,nSlots,vs,idx=0,startAt=0): nLevsUnder = nSlots-idx-1 nValsOver = nItems-i if _verbose: - print ' '*idx,' ',i,nValsOver,nLevsUnder,\ - NumCombinations(nValsOver,nLevsUnder) + print(' '*idx,' ',i,nValsOver,nLevsUnder, + NumCombinations(nValsOver,nLevsUnder)) accum += NumCombinations(nValsOver,nLevsUnder) accum += CountUpTo(nItems,nSlots,vs,idx+1,vs[idx]) - if _verbose: print ' '*idx,'>',accum + if _verbose: print(' '*idx,'>',accum) if idx == 0: _countCache[(nItems,nSlots,tuple(vs))] = accum return accum @@ -209,7 +210,7 @@ def GetIndexCombinations(nItems,nSlots,slot=0,lastItemVal=0): """ global _indexCombinations - if not slot and _indexCombinations.has_key((nItems,nSlots)): + if not slot and (nItems,nSlots) in _indexCombinations: res = _indexCombinations[(nItems,nSlots)] elif slot >= nSlots: res = [] @@ -303,13 +304,13 @@ def UniquifyCombinations(combos): - a list of tuples containing the unique combos """ - print '>>> u:',combos + print('>>> u:',combos) resD = {} for combo in combos: k = combo[:] k.sort() resD[tuple(k)] = tuple(combo) - print ' >>> u:',resD.values() + print(' >>> u:',resD.values()) return resD.values() def GetPossibleScaffolds(nPts,bins,useTriangleInequality=True): @@ -360,8 +361,8 @@ def OrderTriangle(featIndices,dists): ([0, 0, 1], [1, 3, 2]) """ - if len(featIndices)!=3: raise ValueError,'bad indices' - if len(dists)!=3: raise ValueError,'bad dists' + if len(featIndices)!=3: raise ValueError('bad indices') + if len(dists)!=3: raise ValueError('bad dists') fs = set(featIndices) if len(fs)==3: diff --git a/rdkit/Chem/Pharm3D/EmbedLib.py b/rdkit/Chem/Pharm3D/EmbedLib.py index b36c4d91b..de62a3149 100644 --- a/rdkit/Chem/Pharm3D/EmbedLib.py +++ b/rdkit/Chem/Pharm3D/EmbedLib.py @@ -8,6 +8,7 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function from rdkit import RDConfig import sys,time,math @@ -83,16 +84,16 @@ def ReplaceGroup(match,bounds,slop=0.01,useDirs=False,dirLength=defaultFeatLengt feature form a regular polygon, are listed in order (i.e. pt 0 is a neighbor to pt 1 and pt N-1) and that the replacement point goes at the center: - >>> print ', '.join(['%.3f'%x for x in bm[-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.577, 0.577, 0.577, 0.000 - >>> print ', '.join(['%.3f'%x for x in bm[:,-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.155, 1.155, 1.155, 0.000 The slop argument (default = 0.01) is fractional: >>> bm,idx = ReplaceGroup(match,boundsMat) - >>> print ', '.join(['%.3f'%x for x in bm[-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.572, 0.572, 0.572, 0.000 - >>> print ', '.join(['%.3f'%x for x in bm[:,-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.166, 1.166, 1.166, 0.000 @@ -179,7 +180,7 @@ def EmbedMol(mol,bm,atomMatch=None,weight=2.0,randomSeed=-1, weights.append((i,idx,weight)) coords = DG.EmbedBoundsMatrix(bm,weights=weights,numZeroFail=1,randomSeed=randomSeed) #for row in coords: - # print ', '.join(['%.2f'%x for x in row]) + # print(', '.join(['%.2f'%x for x in row])) conf = Chem.Conformer(nAts) conf.SetId(0) @@ -189,7 +190,7 @@ def EmbedMol(mol,bm,atomMatch=None,weight=2.0,randomSeed=-1, for vol in excludedVolumes: vol.pos = numpy.array(coords[vol.index]) - #print >>sys.stderr,' % 7.4f % 7.4f % 7.4f Ar 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(coords[-1]) + #print(' % 7.4f % 7.4f % 7.4f Ar 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(coords[-1]), file=sys.stderr) mol.AddConformer(conf) def AddExcludedVolumes(bm,excludedVolumes,smoothIt=True): @@ -211,9 +212,9 @@ def AddExcludedVolumes(bm,excludedVolumes,smoothIt=True): >>> boundsMat.shape == (3, 3) True - >>> print ', '.join(['%.3f'%x for x in bm[-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[-1]])) 0.500, 1.500, 1.500, 0.000 - >>> print ', '.join(['%.3f'%x for x in bm[:,-1]]) + >>> print(', '.join(['%.3f'%x for x in bm[:,-1]])) 1.000, 3.000, 3.000, 0.000 """ @@ -277,11 +278,11 @@ def UpdatePharmacophoreBounds(bm,atomMatch,pcophore,useDirs=False, True this means, of course, that the input boundsMat is altered: - >>> print ', '.join(['%.3f'%x for x in boundsMat[0]]) + >>> print(', '.join(['%.3f'%x for x in boundsMat[0]])) 0.000, 2.000, 3.000 - >>> print ', '.join(['%.3f'%x for x in boundsMat[1]]) + >>> print(', '.join(['%.3f'%x for x in boundsMat[1]])) 1.000, 0.000, 3.000 - >>> print ', '.join(['%.3f'%x for x in boundsMat[2]]) + >>> print(', '.join(['%.3f'%x for x in boundsMat[2]])) 2.000, 2.000, 0.000 """ @@ -377,7 +378,7 @@ def EmbedPharmacophore(mol,atomMatch,pcophore,randomSeed=-1,count=10,smoothFirst bm = AddExcludedVolumes(bm,excludedVolumes,smoothIt=False) if not DG.DoTriangleSmoothing(bm): - raise ValueError,"could not smooth bounds matrix" + raise ValueError("could not smooth bounds matrix") #print '------------' #print 'post replace and smooth' @@ -558,13 +559,13 @@ def OptimizeMol(mol,bm,atomMatches=None,excludedVolumes=None, ff.Initialize() e1 = ff.CalcEnergy() if isNaN(e1): - raise ValueError,'bogus energy' + raise ValueError('bogus energy') if verbose: - print Chem.MolToMolBlock(mol) + print(Chem.MolToMolBlock(mol)) for i,vol in enumerate(excludedVolumes): pos = ff.GetExtraPointPos(i) - print >>sys.stderr,' % 7.4f % 7.4f % 7.4f As 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(pos) + print(' % 7.4f % 7.4f % 7.4f As 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(pos), file=sys.stderr) needsMore=ff.Minimize() nPasses=0 while needsMore and nPasses>sys.stderr,' % 7.4f % 7.4f % 7.4f Sb 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(pos) + print(' % 7.4f % 7.4f % 7.4f Sb 0 0 0 0 0 0 0 0 0 0 0 0'%tuple(pos), file=sys.stderr) ff = None return e1,e2 @@ -665,7 +666,8 @@ def EmbedOne(mol,name,match,pcophore,count=1,silent=0,**kwargs): e4 = -1.0 e4d=-1.0 if not silent: - print '%s(%d): %.2f(%.2f) -> %.2f(%.2f) : %.2f(%.2f) -> %.2f(%.2f)'%(name,nFailed,e1,e1d,e2,e2d,e3,e3d,e4,e4d) + print('%s(%d): %.2f(%.2f) -> %.2f(%.2f) : %.2f(%.2f) -> %.2f(%.2f)' % + (name,nFailed,e1,e1d,e2,e2d,e3,e3d,e4,e4d)) return e1,e1d,e2,e2d,e3,e3d,e4,e4d,nFailed def MatchPharmacophoreToMol(mol, featFactory, pcophore): @@ -737,7 +739,7 @@ def _getFeatDict(mol,featFactory,features): molFeats = {} for feat in features: family = feat.GetFamily() - if not molFeats.has_key(family): + if not family in molFeats: matches = featFactory.GetFeaturesForMol(mol,includeOnly=family) molFeats[family] = matches return molFeats @@ -836,9 +838,9 @@ def DownsampleBoundsMatrix(bm,indices,maxThresh=4.0): >>> boundsMat.shape == (3, 3) True - >>> print ', '.join(['%.3f'%x for x in bm[0]]) + >>> print(', '.join(['%.3f'%x for x in bm[0]])) 0.000, 3.000 - >>> print ', '.join(['%.3f'%x for x in bm[1]]) + >>> print(', '.join(['%.3f'%x for x in bm[1]])) 2.000, 0.000 if the threshold is high enough, we don't do anything: @@ -946,9 +948,10 @@ def CoarseScreenPharmacophore(atomMatch,bounds,pcophore,verbose=False): if bounds[idx1,idx0] >= pcophore.getUpperBound(k, l) or \ bounds[idx0,idx1] <= pcophore.getLowerBound(k, l) : if verbose: - print '\t (%d,%d) [%d,%d] fail'%(idx1,idx0,k,l) - print '\t %f,%f - %f,%f'%(bounds[idx1,idx0],pcophore.getUpperBound(k,l), - bounds[idx0,idx1],pcophore.getLowerBound(k,l)) + print('\t (%d,%d) [%d,%d] fail'%(idx1,idx0,k,l)) + print('\t %f,%f - %f,%f' % + (bounds[idx1,idx0],pcophore.getUpperBound(k,l), + bounds[idx0,idx1],pcophore.getLowerBound(k,l))) #logger.debug('\t >%s'%str(atomMatch)) #logger.debug() #logger.debug('\t %f,%f - %f,%f'%(bounds[idx1,idx0],pcophore.getUpperBound(k,l), @@ -984,11 +987,11 @@ def Check2DBounds(atomMatch,mol,pcophore): try: dij = min(dij,dm[atomI,atomJ]) except IndexError: - print 'bad indices:',atomI,atomJ - print ' shape:',dm.shape - print ' match:',atomMatch - print ' mol:' - print Chem.MolToMolBlock(mol) + print('bad indices:',atomI,atomJ) + print(' shape:',dm.shape) + print(' match:',atomMatch) + print(' mol:') + print(Chem.MolToMolBlock(mol)) raise IndexError if dijupperB: return False @@ -1094,26 +1097,26 @@ def GetAllPharmacophoreMatches(matches,bounds,pcophore,useDownsampling=0, if atomMatch and use2DLimits and mol: pass2D = Check2DBounds(atomMatch,mol,pcophore) if verbose: - print '..',atomMatch - print ' ..Pass2d:',pass2D + print('..',atomMatch) + print(' ..Pass2d:',pass2D) else: pass2D = True if atomMatch and pass2D and \ CoarseScreenPharmacophore(atomMatch,bounds,pcophore,verbose=verbose): if verbose: - print ' ..CoarseScreen: Pass' + print(' ..CoarseScreen: Pass') bm = bounds.copy() if verbose: - print 'pre update:' + print('pre update:') for row in bm: - print ' ',' '.join(['% 4.2f'%x for x in row]) + print(' ',' '.join(['% 4.2f'%x for x in row])) bm = UpdatePharmacophoreBounds(bm,atomMatch,pcophore); sz = bm.shape[0] if verbose: - print 'pre downsample:' + print('pre downsample:') for row in bm: - print ' ',' '.join(['% 4.2f'%x for x in row]) + print(' ',' '.join(['% 4.2f'%x for x in row])) if useDownsampling: indices = [] @@ -1121,14 +1124,14 @@ def GetAllPharmacophoreMatches(matches,bounds,pcophore,useDownsampling=0, indices += list(entry) bm = DownsampleBoundsMatrix(bm,indices) if verbose: - print 'post downsample:' + print('post downsample:') for row in bm: - print ' ',' '.join(['% 4.2f'%x for x in row]) + print(' ',' '.join(['% 4.2f'%x for x in row])) if DG.DoTriangleSmoothing(bm): res.append(match) elif verbose: - print 'cannot smooth' + print('cannot smooth') nDone+=1 if progressCallback: progressCallback(nDone) diff --git a/rdkit/Chem/Pharm3D/ExcludedVolume.py b/rdkit/Chem/Pharm3D/ExcludedVolume.py index 73be3087e..7ff49b01b 100644 --- a/rdkit/Chem/Pharm3D/ExcludedVolume.py +++ b/rdkit/Chem/Pharm3D/ExcludedVolume.py @@ -18,17 +18,17 @@ class ExcludedVolume(object): try: l = len(featInfo) except AttributeError: - raise ValueError,'featInfo argument must be a sequence of sequences' + raise ValueError('featInfo argument must be a sequence of sequences') if not len(featInfo): - raise ValueError,'featInfo argument must non-empty' + raise ValueError('featInfo argument must non-empty') try: a,b,c = featInfo[0] except Type: - raise ValueError,'featInfo elements must be 3-sequences' + raise ValueError('featInfo elements must be 3-sequences') except ValueError: - raise ValueError,'featInfo elements must be 3-sequences' + raise ValueError('featInfo elements must be 3-sequences') self.featInfo = featInfo[:] self.exclusionDist = exclusionDist diff --git a/rdkit/Chem/Pharm3D/Pharmacophore.py b/rdkit/Chem/Pharm3D/Pharmacophore.py index df2a37698..ffbf8d7c9 100644 --- a/rdkit/Chem/Pharm3D/Pharmacophore.py +++ b/rdkit/Chem/Pharm3D/Pharmacophore.py @@ -70,9 +70,9 @@ class Pharmacophore: " raises ValueError on failure " nf = len(self._feats) if (i < 0) or (i >= nf): - raise ValueError, "Index out of bound" + raise ValueError("Index out of bound") if (j < 0) or (j >= nf): - raise ValueError, "Index out of bound" + raise ValueError("Index out of bound") return True def setUpperBound(self, i, j, val, checkBounds=False): @@ -136,7 +136,7 @@ class ExplicitPharmacophore: def _initializeFeats(self,feats,radii): if len(feats)!=len(radii): - raise ValueError,'len(feats)!=len(radii)' + raise ValueError('len(feats)!=len(radii)') self._feats = [] self._radii = [] for feat,rad in zip(feats,radii): diff --git a/rdkit/Chem/Pharm3D/UnitTestEmbed.py b/rdkit/Chem/Pharm3D/UnitTestEmbed.py index 268833593..66e752e84 100644 --- a/rdkit/Chem/Pharm3D/UnitTestEmbed.py +++ b/rdkit/Chem/Pharm3D/UnitTestEmbed.py @@ -8,8 +8,10 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function from rdkit import RDConfig -import unittest,sys,os,cPickle +import unittest,sys,os +from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import ChemicalFeatures,rdDistGeom import EmbedLib @@ -17,7 +19,6 @@ import gzip from rdkit import DistanceGeometry as DG from rdkit import Geometry import Pharmacophore -import cPickle import numpy def feq(n1,n2,tol=1e-5): @@ -85,9 +86,9 @@ class TestCase(unittest.TestCase): if self._matchMol(tpl,self.pcophore,self.featFactory,0): nHits+=1 nDone += 1 - self.failUnlessEqual(nDone,100) + self.assertEqual(nDone,100) #print 'nHits:',nHits - self.failUnlessEqual(nHits,47) + self.assertEqual(nHits,47) def test2SearchDownsample(self): inF = gzip.open(os.path.join(self.dataDir,'cdk2-syn-clip100.pkl.gz'),'rb') @@ -102,9 +103,9 @@ class TestCase(unittest.TestCase): if self._matchMol(tpl,self.pcophore, self.featFactory,1): nHits+=1 nDone += 1 - self.failUnlessEqual(nDone,100) + self.assertEqual(nDone,100) #print 'nHits:',nHits - self.failUnlessEqual(nHits,47) + self.assertEqual(nHits,47) def test3Embed(self): testResults={ @@ -139,17 +140,17 @@ class TestCase(unittest.TestCase): stats = EmbedLib.EmbedOne(mol,name,match,self.pcophore,count=10, silent=1,randomSeed=23) tgt = testResults[name] - self.failUnlessEqual(len(tgt),len(stats)) - print name - print ','.join(['%.2f'%x for x in stats]) + self.assertEqual(len(tgt),len(stats)) + print(name) + print(','.join(['%.2f'%x for x in stats])) # we'll use different tolerances for the different values: self.failUnless(feq(tgt[0],stats[0],5.0),(tgt[0],stats[0])) for i in range(2,len(tgt)): self.failUnless(feq(tgt[i],stats[i],5.0),(tgt[i],stats[i])) - self.failUnlessEqual(nDone,100) + self.assertEqual(nDone,100) #print 'nHits:',nHits - self.failUnlessEqual(nHits,50) + self.assertEqual(nHits,50) def test4Search(self): featFactory = ChemicalFeatures.BuildFeatureFactory(os.path.join(self.dataDir, @@ -202,10 +203,10 @@ class TestCase(unittest.TestCase): if not failed: nHits+=1 - self.failUnlessEqual(nDone,100) - self.failUnlessEqual(nMatches,93) + self.assertEqual(nDone,100) + self.assertEqual(nMatches,93) #print 'nhits:',nHits - self.failUnlessEqual(nHits,67) + self.assertEqual(nHits,67) def testIssue268(self): from rdkit import RDLogger @@ -216,7 +217,7 @@ class TestCase(unittest.TestCase): 'Issue268_Mol1.mol')) m2 = Chem.MolFromMolFile(os.path.join(self.dataDir, 'Issue268_Mol2.mol')) - pcop = cPickle.load(file(os.path.join(self.dataDir, + pcop = cPickle.load(open(os.path.join(self.dataDir, 'Issue268_Pcop.pkl'),'rb')) #pcop._boundsMat=numpy.array(pcop._boundsMat) #pcop._boundsMat2D=numpy.array(pcop._boundsMat2D) @@ -227,25 +228,25 @@ class TestCase(unittest.TestCase): b1 = rdDistGeom.GetMoleculeBoundsMatrix(m1) b2 = rdDistGeom.GetMoleculeBoundsMatrix(m2) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop)[2]),4) + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop)[2]),4) + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop, + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop, mol=m1,use2DLimits=True)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop, + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop, mol=m2,use2DLimits=True)[2]),4) from rdkit import DistanceGeometry as DG self.failUnless(DG.DoTriangleSmoothing(b1)) self.failUnless(DG.DoTriangleSmoothing(b2)) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop)[2]),4) + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop)[2]),4) + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop, + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList1,b1,pcop, mol=m1,use2DLimits=True)[2]),4) - self.failUnlessEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop, + self.assertEqual(len(EmbedLib.MatchPharmacophore(mList2,b2,pcop, mol=m2,use2DLimits=True)[2]),4) diff --git a/rdkit/Chem/Pharm3D/UnitTestPharmacophore.py b/rdkit/Chem/Pharm3D/UnitTestPharmacophore.py index c0143c36c..14b9bdc4c 100644 --- a/rdkit/Chem/Pharm3D/UnitTestPharmacophore.py +++ b/rdkit/Chem/Pharm3D/UnitTestPharmacophore.py @@ -9,7 +9,8 @@ # of the RDKit source tree. # from rdkit import RDConfig -import unittest,sys,os,cPickle +import unittest,sys,os +from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import ChemicalFeatures,AllChem import EmbedLib @@ -50,62 +51,62 @@ class TestCase(unittest.TestCase): def test1Basics(self): pcophore = self.pcophore - self.failUnless(len(pcophore.getFeatures())==3) - self.failUnless(pcophore.getFeature(0)) - self.failUnless(pcophore.getFeature(1)) - self.failUnless(pcophore.getFeature(2)) - self.failUnlessRaises(IndexError,pcophore.getFeature,3) + self.assertTrue(len(pcophore.getFeatures())==3) + self.assertTrue(pcophore.getFeature(0)) + self.assertTrue(pcophore.getFeature(1)) + self.assertTrue(pcophore.getFeature(2)) + self.assertRaises(IndexError,pcophore.getFeature,3) def test2BoundSetting(self): pcophore = self.pcophore pcophore.setUpperBound(0,1,3.0) - self.failUnless(feq(pcophore.getUpperBound(0,1),3.0)) - self.failUnless(feq(pcophore.getUpperBound(1,0),3.0)) + self.assertTrue(feq(pcophore.getUpperBound(0,1),3.0)) + self.assertTrue(feq(pcophore.getUpperBound(1,0),3.0)) pcophore.setUpperBound(1,0,5.0) - self.failUnless(feq(pcophore.getUpperBound(0,1),5.0)) - self.failUnless(feq(pcophore.getUpperBound(1,0),5.0)) - self.failUnlessRaises(IndexError,pcophore.setUpperBound,0,3,2.0) - self.failUnlessRaises(ValueError,pcophore.setUpperBound,0,3,2.0,checkBounds=True) - self.failUnlessRaises(IndexError,pcophore.setUpperBound,3,0,2.0) - self.failUnlessRaises(ValueError,pcophore.setUpperBound,3,0,2.0,checkBounds=True) + self.assertTrue(feq(pcophore.getUpperBound(0,1),5.0)) + self.assertTrue(feq(pcophore.getUpperBound(1,0),5.0)) + self.assertRaises(IndexError,pcophore.setUpperBound,0,3,2.0) + self.assertRaises(ValueError,pcophore.setUpperBound,0,3,2.0,checkBounds=True) + self.assertRaises(IndexError,pcophore.setUpperBound,3,0,2.0) + self.assertRaises(ValueError,pcophore.setUpperBound,3,0,2.0,checkBounds=True) pcophore.setLowerBound(0,1,2.0) - self.failUnless(feq(pcophore.getLowerBound(0,1),2.0)) - self.failUnless(feq(pcophore.getLowerBound(1,0),2.0)) + self.assertTrue(feq(pcophore.getLowerBound(0,1),2.0)) + self.assertTrue(feq(pcophore.getLowerBound(1,0),2.0)) pcophore.setLowerBound(1,0,3.0) - self.failUnless(feq(pcophore.getLowerBound(0,1),3.0)) - self.failUnless(feq(pcophore.getLowerBound(1,0),3.0)) - self.failUnlessRaises(IndexError,pcophore.setLowerBound,0,3,2.0) - self.failUnlessRaises(ValueError,pcophore.setLowerBound,0,3,2.0,checkBounds=True) - self.failUnlessRaises(IndexError,pcophore.setLowerBound,3,0,2.0) - self.failUnlessRaises(ValueError,pcophore.setLowerBound,3,0,2.0,checkBounds=True) + self.assertTrue(feq(pcophore.getLowerBound(0,1),3.0)) + self.assertTrue(feq(pcophore.getLowerBound(1,0),3.0)) + self.assertRaises(IndexError,pcophore.setLowerBound,0,3,2.0) + self.assertRaises(ValueError,pcophore.setLowerBound,0,3,2.0,checkBounds=True) + self.assertRaises(IndexError,pcophore.setLowerBound,3,0,2.0) + self.assertRaises(ValueError,pcophore.setLowerBound,3,0,2.0,checkBounds=True) def test3Bound2DSetting(self): pcophore = self.pcophore pcophore.setUpperBound2D(0,1,3) - self.failUnless(pcophore.getUpperBound2D(0,1)==3) - self.failUnless(pcophore.getUpperBound2D(1,0)==3) + self.assertTrue(pcophore.getUpperBound2D(0,1)==3) + self.assertTrue(pcophore.getUpperBound2D(1,0)==3) pcophore.setUpperBound2D(1,0,5) - self.failUnless(pcophore.getUpperBound2D(0,1)==5) - self.failUnless(pcophore.getUpperBound2D(1,0)==5) - self.failUnlessRaises(IndexError,pcophore.setUpperBound2D,0,3,2) - self.failUnlessRaises(ValueError,pcophore.setUpperBound2D,0,3,2,checkBounds=True) - self.failUnlessRaises(IndexError,pcophore.setUpperBound2D,3,0,2) - self.failUnlessRaises(ValueError,pcophore.setUpperBound2D,3,0,2,checkBounds=True) + self.assertTrue(pcophore.getUpperBound2D(0,1)==5) + self.assertTrue(pcophore.getUpperBound2D(1,0)==5) + self.assertRaises(IndexError,pcophore.setUpperBound2D,0,3,2) + self.assertRaises(ValueError,pcophore.setUpperBound2D,0,3,2,checkBounds=True) + self.assertRaises(IndexError,pcophore.setUpperBound2D,3,0,2) + self.assertRaises(ValueError,pcophore.setUpperBound2D,3,0,2,checkBounds=True) pcophore.setLowerBound2D(0,1,3) - self.failUnless(pcophore.getLowerBound2D(0,1)==3) - self.failUnless(pcophore.getLowerBound2D(1,0)==3) + self.assertTrue(pcophore.getLowerBound2D(0,1)==3) + self.assertTrue(pcophore.getLowerBound2D(1,0)==3) pcophore.setLowerBound2D(1,0,5) - self.failUnless(pcophore.getLowerBound2D(0,1)==5) - self.failUnless(pcophore.getLowerBound2D(1,0)==5) - self.failUnlessRaises(IndexError,pcophore.setLowerBound2D,0,3,2) - self.failUnlessRaises(ValueError,pcophore.setLowerBound2D,0,3,2,checkBounds=True) - self.failUnlessRaises(IndexError,pcophore.setLowerBound2D,3,0,2) - self.failUnlessRaises(ValueError,pcophore.setLowerBound2D,3,0,2,checkBounds=True) + self.assertTrue(pcophore.getLowerBound2D(0,1)==5) + self.assertTrue(pcophore.getLowerBound2D(1,0)==5) + self.assertRaises(IndexError,pcophore.setLowerBound2D,0,3,2) + self.assertRaises(ValueError,pcophore.setLowerBound2D,0,3,2,checkBounds=True) + self.assertRaises(IndexError,pcophore.setLowerBound2D,3,0,2) + self.assertRaises(ValueError,pcophore.setLowerBound2D,3,0,2,checkBounds=True) def test4Github252(self): fdef= os.path.join(RDConfig.RDDataDir,'BaseFeatures.fdef') @@ -118,7 +119,7 @@ class TestCase(unittest.TestCase): ok=False except: ok=True - self.failUnless(ok) + self.assertTrue(ok) AllChem.Compute2DCoords(m1) try: @@ -126,7 +127,7 @@ class TestCase(unittest.TestCase): ok=True except: ok=False - self.failUnless(ok) + self.assertTrue(ok) diff --git a/rdkit/Chem/PropertyMol.py b/rdkit/Chem/PropertyMol.py index 8de6a8739..9e85e32cb 100644 --- a/rdkit/Chem/PropertyMol.py +++ b/rdkit/Chem/PropertyMol.py @@ -8,7 +8,7 @@ from rdkit import Chem class PropertyMol(Chem.Mol): """ allows rdkit molecules to be pickled with their properties saved. - >>> import cPickle + >>> from rdkit.six.moves import cPickle >>> m = Chem.MolFromMolFile('test_data/benzene.mol') >>> m.GetProp('_Name') 'benzene.mol' @@ -61,7 +61,7 @@ class PropertyMol(Chem.Mol): >>> w = Chem.SDWriter(fn) >>> w.write(pm) >>> w=None - >>> txt = file(fn,'r').read() + >>> txt = open(fn,'r').read() >>> '' in txt True >>> try: @@ -76,7 +76,7 @@ class PropertyMol(Chem.Mol): >>> pm = cPickle.loads(cPickle.dumps(pm)) >>> w.write(pm) >>> w=None - >>> txt = file(fn,'r').read() + >>> txt = open(fn,'r').read() >>> '' in txt True >>> try: diff --git a/rdkit/Chem/Randomize.py b/rdkit/Chem/Randomize.py index a5fc3312a..0d299c06d 100644 --- a/rdkit/Chem/Randomize.py +++ b/rdkit/Chem/Randomize.py @@ -9,6 +9,7 @@ # of the RDKit source tree. # import random +from rdkit.six.moves import range from rdkit import Chem def RandomizeMolBlock(molB): @@ -24,7 +25,7 @@ def RandomizeMolBlock(molB): idx+=1 atLines = splitB[idx:idx+nAts] - order = range(nAts) + order = list(range(nAts)) random.shuffle(order) for i in order: @@ -58,7 +59,7 @@ def CheckCanonicalization(mol,nReps=10): m2 = RandomizeMol(mol) smi = Chem.MolToSmiles(m2,False) if smi!=refSmi: - raise ValueError,'\nRef: %s\n : %s'%(refSmi,smi) + raise ValueError('\nRef: %s\n : %s'%(refSmi,smi)) diff --git a/rdkit/Chem/Recap.py b/rdkit/Chem/Recap.py index d4006a9eb..f694ef79a 100755 --- a/rdkit/Chem/Recap.py +++ b/rdkit/Chem/Recap.py @@ -57,10 +57,11 @@ To get the standard set of RECAP results, use GetLeaves(): """ +import sys import weakref from rdkit import Chem from rdkit.Chem import rdChemReactions as Reactions -import sys +from rdkit.six import iterkeys, iteritems, next # These are the definitions that will be applied to fragment molecules: reactionDefs = ( @@ -109,7 +110,7 @@ class RecapHierarchyNode(object): def GetAllChildren(self): " returns a dictionary, keyed by SMILES, of children " res = {} - for smi,child in self.children.iteritems(): + for smi,child in iteritems(self.children): res[smi] = child child._gacRecurse(res,terminalOnly=False) return res @@ -117,7 +118,7 @@ class RecapHierarchyNode(object): def GetLeaves(self): " returns a dictionary, keyed by SMILES, of leaf (terminal) nodes " res = {} - for smi,child in self.children.iteritems(): + for smi,child in iteritems(self.children): if not len(child.children): res[smi] = child else: @@ -139,7 +140,7 @@ class RecapHierarchyNode(object): return res def _gacRecurse(self,res,terminalOnly=False): - for smi,child in self.children.iteritems(): + for smi,child in iteritems(self.children): if not terminalOnly or not len(child.children): res[smi] = child child._gacRecurse(res,terminalOnly=terminalOnly) @@ -156,7 +157,7 @@ def RecapDecompose(mol,allNodes=None,minFragmentSize=0,onlyUseReactions=None): if allNodes is None: allNodes={} - if allNodes.has_key(mSmi): + if mSmi in allNodes: return allNodes[mSmi] res = RecapHierarchyNode(mol) @@ -164,7 +165,7 @@ def RecapDecompose(mol,allNodes=None,minFragmentSize=0,onlyUseReactions=None): activePool={mSmi:res} allNodes[mSmi]=res while activePool: - nSmi = activePool.keys()[0] + nSmi = next(iterkeys(activePool)) node = activePool.pop(nSmi) if not node.mol: continue for rxnIdx,reaction in enumerate(reactions): @@ -175,13 +176,13 @@ def RecapDecompose(mol,allNodes=None,minFragmentSize=0,onlyUseReactions=None): ps = reaction.RunReactants((node.mol,)) #print ' ',len(ps) if ps: - for prodSeq in ps: - seqOk=True - # we want to disqualify small fragments, so sort the product sequence by size - # and then look for "forbidden" fragments - prodSeq = [(prod.GetNumAtoms(onlyExplicit=True),prod) for prod in prodSeq] - prodSeq.sort() - for nats,prod in prodSeq: + for prodSeq in ps: + seqOk=True + # we want to disqualify small fragments, so sort the product sequence by size + # and then look for "forbidden" fragments + prodSeq = [(prod.GetNumAtoms(onlyExplicit=True),prod) for prod in prodSeq] + prodSeq.sort() + for nats,prod in prodSeq: try: Chem.SanitizeMol(prod) except: @@ -194,15 +195,15 @@ def RecapDecompose(mol,allNodes=None,minFragmentSize=0,onlyUseReactions=None): break # don't forget after replacing dummy atoms to remove any empty # branches: - elif pSmi.replace('[*]','').replace('()','') in ('','C','CC','CCC'): - seqOk=False - break - prod.pSmi = pSmi - if seqOk: - for nats,prod in prodSeq: - pSmi = prod.pSmi + elif pSmi.replace('[*]','').replace('()','') in ('','C','CC','CCC'): + seqOk=False + break + prod.pSmi = pSmi + if seqOk: + for nats,prod in prodSeq: + pSmi = prod.pSmi #print '\t',nats,pSmi - if not allNodes.has_key(pSmi): + if not pSmi in allNodes: pNode = RecapHierarchyNode(prod) pNode.smiles=pSmi pNode.parents[nSmi]=weakref.proxy(node) @@ -225,384 +226,384 @@ if __name__=='__main__': def test1(self): m = Chem.MolFromSmiles('C1CC1Oc1ccccc1-c1ncc(OC)cc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.children.keys())==4) - self.failUnless(len(res.GetAllChildren().keys())==5) - self.failUnless(len(res.GetLeaves().keys())==3) + self.assertTrue(res) + self.assertTrue(len(res.children.keys())==4) + self.assertTrue(len(res.GetAllChildren().keys())==5) + self.assertTrue(len(res.GetLeaves().keys())==3) def test2(self): m = Chem.MolFromSmiles('CCCOCCC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(res.children=={}) + self.assertTrue(res) + self.assertTrue(res.children=={}) def test3(self): allNodes={} m = Chem.MolFromSmiles('c1ccccc1-c1ncccc1') res = RecapDecompose(m,allNodes=allNodes) - self.failUnless(res) - self.failUnless(len(res.children.keys())==2) - self.failUnless(len(allNodes.keys())==3) + self.assertTrue(res) + self.assertTrue(len(res.children.keys())==2) + self.assertTrue(len(allNodes.keys())==3) m = Chem.MolFromSmiles('COc1ccccc1-c1ncccc1') res = RecapDecompose(m,allNodes=allNodes) - self.failUnless(res) - self.failUnless(len(res.children.keys())==2) + self.assertTrue(res) + self.assertTrue(len(res.children.keys())==2) # we get two more nodes from that: - self.failUnless(len(allNodes.keys())==5) - self.failUnless(allNodes.has_key('[*]c1ccccc1OC')) - self.failUnless(allNodes.has_key('[*]c1ccccc1')) + self.assertTrue(len(allNodes.keys())==5) + self.assertTrue('[*]c1ccccc1OC' in allNodes) + self.assertTrue('[*]c1ccccc1' in allNodes) m = Chem.MolFromSmiles('C1CC1Oc1ccccc1-c1ncccc1') res = RecapDecompose(m,allNodes=allNodes) - self.failUnless(res) - self.failUnless(len(res.children.keys())==4) - self.failUnless(len(allNodes.keys())==10) + self.assertTrue(res) + self.assertTrue(len(res.children.keys())==4) + self.assertTrue(len(allNodes.keys())==10) def testSFNetIssue1801871(self): m = Chem.MolFromSmiles('c1ccccc1OC(Oc1ccccc1)Oc1ccccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failIf('[*]C([*])[*]' in ks) - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]C([*])Oc1ccccc1' in ks) + self.assertFalse('[*]C([*])[*]' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]C([*])Oc1ccccc1' in ks) def testSFNetIssue1804418(self): m = Chem.MolFromSmiles('C1CCCCN1CCCC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]N1CCCCC1' in ks) - self.failUnless('[*]CCCC' in ks) + self.assertTrue('[*]N1CCCCC1' in ks) + self.assertTrue('[*]CCCC' in ks) def testMinFragmentSize(self): m = Chem.MolFromSmiles('CCCOCCC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(res.children=={}) + self.assertTrue(res) + self.assertTrue(res.children=={}) res = RecapDecompose(m,minFragmentSize=3) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==1) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==1) ks = res.GetLeaves().keys() - self.failUnless('[*]CCC' in ks) + self.assertTrue('[*]CCC' in ks) m = Chem.MolFromSmiles('CCCOCC') res = RecapDecompose(m,minFragmentSize=3) - self.failUnless(res) - self.failUnless(res.children=={}) + self.assertTrue(res) + self.assertTrue(res.children=={}) m = Chem.MolFromSmiles('CCCOCCOC') res = RecapDecompose(m,minFragmentSize=2) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]CCC' in ks) + self.assertTrue('[*]CCC' in ks) ks = res.GetLeaves().keys() - self.failUnless('[*]CCOC' in ks) + self.assertTrue('[*]CCOC' in ks) def testAmideRxn(self): m = Chem.MolFromSmiles('C1CC1C(=O)NC1OC1') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]C(=O)C1CC1' in ks) - self.failUnless('[*]NC1CO1' in ks) + self.assertTrue('[*]C(=O)C1CC1' in ks) + self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)N(C)C1OC1') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]C(=O)C1CC1' in ks) - self.failUnless('[*]N(C)C1CO1' in ks) + self.assertTrue('[*]C(=O)C1CC1' in ks) + self.assertTrue('[*]N(C)C1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)n1cccc1') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]C(=O)C1CC1' in ks) - self.failUnless('[*]n1cccc1' in ks) + self.assertTrue('[*]C(=O)C1CC1' in ks) + self.assertTrue('[*]n1cccc1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)CC1OC1') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('C1CCC(=O)NC1') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('CC(=O)NC') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() m = Chem.MolFromSmiles('CC(=O)N') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('C(=O)NCCNC(=O)CC') res = RecapDecompose(m,onlyUseReactions=[1]) - self.failUnless(res) - self.failUnless(len(res.children)==4) - self.failUnless(len(res.GetLeaves())==3) + self.assertTrue(res) + self.assertTrue(len(res.children)==4) + self.assertTrue(len(res.GetLeaves())==3) def testEsterRxn(self): m = Chem.MolFromSmiles('C1CC1C(=O)OC1OC1') res = RecapDecompose(m,onlyUseReactions=[2]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]C(=O)C1CC1' in ks) - self.failUnless('[*]OC1CO1' in ks) + self.assertTrue('[*]C(=O)C1CC1' in ks) + self.assertTrue('[*]OC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1C(=O)CC1OC1') res = RecapDecompose(m,onlyUseReactions=[2]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('C1CCC(=O)OC1') res = RecapDecompose(m,onlyUseReactions=[2]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testUreaRxn(self): m = Chem.MolFromSmiles('C1CC1NC(=O)NC1OC1') res = RecapDecompose(m,onlyUseReactions=[0]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]NC1CC1' in ks) - self.failUnless('[*]NC1CO1' in ks) + self.assertTrue('[*]NC1CC1' in ks) + self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('C1CC1NC(=O)N(C)C1OC1') res = RecapDecompose(m,onlyUseReactions=[0]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]NC1CC1' in ks) - self.failUnless('[*]N(C)C1CO1' in ks) + self.assertTrue('[*]NC1CC1' in ks) + self.assertTrue('[*]N(C)C1CO1' in ks) m = Chem.MolFromSmiles('C1CCNC(=O)NC1C') res = RecapDecompose(m,onlyUseReactions=[0]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('c1cccn1C(=O)NC1OC1') res = RecapDecompose(m,onlyUseReactions=[0]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]n1cccc1' in ks) - self.failUnless('[*]NC1CO1' in ks) + self.assertTrue('[*]n1cccc1' in ks) + self.assertTrue('[*]NC1CO1' in ks) m = Chem.MolFromSmiles('c1cccn1C(=O)n1c(C)ccc1') res = RecapDecompose(m,onlyUseReactions=[0]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]n1cccc1C' in ks) + self.assertTrue('[*]n1cccc1C' in ks) def testAmineRxn(self): m = Chem.MolFromSmiles('C1CC1N(C1NC1)C1OC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==3) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==3) ks = res.GetLeaves().keys() - self.failUnless('[*]C1CC1' in ks) - self.failUnless('[*]C1CO1' in ks) - self.failUnless('[*]C1CN1' in ks) + self.assertTrue('[*]C1CC1' in ks) + self.assertTrue('[*]C1CO1' in ks) + self.assertTrue('[*]C1CN1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(C1NC1)C1OC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==3) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==3) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]C1CO1' in ks) - self.failUnless('[*]C1CN1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]C1CO1' in ks) + self.assertTrue('[*]C1CN1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(c1ncccc1)C1OC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==3) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==3) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]c1ccccn1' in ks) - self.failUnless('[*]C1CO1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]c1ccccn1' in ks) + self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('c1ccccc1N(c1ncccc1)c1ccco1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==3) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==3) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]c1ccccn1' in ks) - self.failUnless('[*]c1ccco1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]c1ccccn1' in ks) + self.assertTrue('[*]c1ccco1' in ks) m = Chem.MolFromSmiles('C1CCCCN1C1CC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]N1CCCCC1' in ks) - self.failUnless('[*]C1CC1' in ks) + self.assertTrue('[*]N1CCCCC1' in ks) + self.assertTrue('[*]C1CC1' in ks) m = Chem.MolFromSmiles('C1CCC2N1CC2') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testEtherRxn(self): m = Chem.MolFromSmiles('C1CC1OC1OC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]C1CC1' in ks) - self.failUnless('[*]C1CO1' in ks) + self.assertTrue('[*]C1CC1' in ks) + self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('C1CCCCO1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('c1ccccc1OC1OC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]C1CO1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]C1CO1' in ks) m = Chem.MolFromSmiles('c1ccccc1Oc1ncccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]c1ccccn1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]c1ccccn1' in ks) def testOlefinRxn(self): m = Chem.MolFromSmiles('ClC=CBr') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]CCl' in ks) - self.failUnless('[*]CBr' in ks) + self.assertTrue('[*]CCl' in ks) + self.assertTrue('[*]CBr' in ks) m = Chem.MolFromSmiles('C1CC=CC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testAromNAliphCRxn(self): m = Chem.MolFromSmiles('c1cccn1CCCC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]n1cccc1' in ks) - self.failUnless('[*]CCCC' in ks) + self.assertTrue('[*]n1cccc1' in ks) + self.assertTrue('[*]CCCC' in ks) m = Chem.MolFromSmiles('c1ccc2n1CCCC2') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testLactamNAliphCRxn(self): m = Chem.MolFromSmiles('C1CC(=O)N1CCCC') res = RecapDecompose(m,onlyUseReactions=[8]) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]N1CCC1=O' in ks) - self.failUnless('[*]CCCC' in ks) + self.assertTrue('[*]N1CCC1=O' in ks) + self.assertTrue('[*]CCCC' in ks) m = Chem.MolFromSmiles('O=C1CC2N1CCCC2') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testAromCAromCRxn(self): m = Chem.MolFromSmiles('c1ccccc1c1ncccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]c1ccccc1' in ks) - self.failUnless('[*]c1ccccn1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) + self.assertTrue('[*]c1ccccn1' in ks) m = Chem.MolFromSmiles('c1ccccc1C1CC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testAromNAromCRxn(self): m = Chem.MolFromSmiles('c1cccn1c1ccccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]n1cccc1' in ks) - self.failUnless('[*]c1ccccc1' in ks) + self.assertTrue('[*]n1cccc1' in ks) + self.assertTrue('[*]c1ccccc1' in ks) def testSulfonamideRxn(self): m = Chem.MolFromSmiles('CCCNS(=O)(=O)CC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]NCCC' in ks) - self.failUnless('[*]S(=O)(=O)CC' in ks) + self.assertTrue('[*]NCCC' in ks) + self.assertTrue('[*]S(=O)(=O)CC' in ks) m = Chem.MolFromSmiles('c1cccn1S(=O)(=O)CC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) ks = res.GetLeaves().keys() - self.failUnless('[*]n1cccc1' in ks) - self.failUnless('[*]S(=O)(=O)CC' in ks) + self.assertTrue('[*]n1cccc1' in ks) + self.assertTrue('[*]S(=O)(=O)CC' in ks) m = Chem.MolFromSmiles('C1CNS(=O)(=O)CC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) def testSFNetIssue1881803(self): m = Chem.MolFromSmiles('c1ccccc1n1cccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) m = Chem.MolFromSmiles('c1ccccc1[n+]1ccccc1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('C1CC1NC(=O)CC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) m = Chem.MolFromSmiles('C1CC1[NH+]C(=O)CC') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) m = Chem.MolFromSmiles('C1CC1NC(=O)NC1CCC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==2) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==2) m = Chem.MolFromSmiles('C1CC1[NH+]C(=O)[NH+]C1CCC1') res = RecapDecompose(m) - self.failUnless(res) - self.failUnless(len(res.GetLeaves())==0) + self.assertTrue(res) + self.assertTrue(len(res.GetLeaves())==0) unittest.main() diff --git a/rdkit/Chem/SATIS.py b/rdkit/Chem/SATIS.py index d48e601f4..1b0d8f079 100755 --- a/rdkit/Chem/SATIS.py +++ b/rdkit/Chem/SATIS.py @@ -11,7 +11,9 @@ """ Functionality for SATIS typing atoms """ +from __future__ import print_function from rdkit import Chem +from rdkit.six.moves import xrange _debug = 0 @@ -80,11 +82,11 @@ def SATISTypes(mol,neighborsToInclude=4): bonds = atom.GetBonds() nBonds = len(bonds) otherIndices = [-1]*nBonds - if _debug: print code[0], + if _debug: print(code[0],end='') for j in range(nBonds): otherIndices[j] = bonds[j].GetOtherAtom(atom).GetIdx() - if _debug: print otherIndices[j], - if _debug: print + if _debug: print(otherIndices[j],end='') + if _debug: print() otherNums = [atomicNums[x] for x in otherIndices] + \ [1]*atom.GetTotalNumHs() otherNums.sort() @@ -117,7 +119,7 @@ if __name__ == '__main__': smis = ['CC(=O)NC','CP(F)(Cl)(Br)(O)', 'O=CC(=O)C','C(=O)OCC(=O)O','C(=O)[O-]'] for smi in smis: - print smi + print(smi) m = Chem.MolFromSmiles(smi) codes = SATISTypes(m) - print codes + print(codes) diff --git a/rdkit/Chem/SaltRemover.py b/rdkit/Chem/SaltRemover.py index 8b5537463..3d4ca69ea 100644 --- a/rdkit/Chem/SaltRemover.py +++ b/rdkit/Chem/SaltRemover.py @@ -61,10 +61,10 @@ class SaltRemover(object): """ whitespace = re.compile(r'[\t ]+') if self.defnData: - from cStringIO import StringIO + from rdkit.six.moves import cStringIO as StringIO inF = StringIO(self.defnData) else: - inF = file(self.defnFilename,'r') + inF = open(self.defnFilename,'r') self.salts = [] for line in inF: line = line.strip().split('//')[0] @@ -75,7 +75,7 @@ class SaltRemover(object): except: import traceback traceback.print_exc() - raise ValueError,line + raise ValueError(line) self.salts.append(salt) def StripMol(self,mol,dontRemoveEverything=False): diff --git a/rdkit/Chem/Scaffolds/MurckoScaffold.py b/rdkit/Chem/Scaffolds/MurckoScaffold.py index 5b75bef71..7b0d2c932 100755 --- a/rdkit/Chem/Scaffolds/MurckoScaffold.py +++ b/rdkit/Chem/Scaffolds/MurckoScaffold.py @@ -122,7 +122,7 @@ def MurckoScaffoldSmiles(smiles=None, mol=None, includeChirality=False): else: mol = mol if mol is None: - raise ValueError,'No molecule provided' + raise ValueError('No molecule provided') scaffold = GetScaffoldForMol(mol) if not scaffold: return None return Chem.MolToSmiles(scaffold,includeChirality) diff --git a/rdkit/Chem/SimpleEnum/Enumerator.py b/rdkit/Chem/SimpleEnum/Enumerator.py index 59ce03f54..af0711684 100755 --- a/rdkit/Chem/SimpleEnum/Enumerator.py +++ b/rdkit/Chem/SimpleEnum/Enumerator.py @@ -29,6 +29,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Created by Greg Landrum, May 2009 +from __future__ import print_function from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import AllChem @@ -163,7 +164,7 @@ def EnumerateReaction(reaction,bbLists,uniqueProductsOnly=False,funcGroupFilenam >>> smis.sort() >>> len(smis) 6 - >>> print smis + >>> print(smis) ['CCCc1ccccc1', 'CCCc1ccccn1', 'CCCc1cccnc1', 'CCc1ccccc1', 'CCc1ccccn1', 'CCc1cccnc1'] The nastiness can be avoided at the cost of some memory by asking for only unique products: @@ -171,14 +172,14 @@ def EnumerateReaction(reaction,bbLists,uniqueProductsOnly=False,funcGroupFilenam >>> prods = list(prods) >>> len(prods) 6 - >>> print sorted([Chem.MolToSmiles(x[0]) for x in prods]) + >>> print(sorted([Chem.MolToSmiles(x[0]) for x in prods])) ['CCCc1ccccc1', 'CCCc1ccccn1', 'CCCc1cccnc1', 'CCc1ccccc1', 'CCc1ccccn1', 'CCc1cccnc1'] """ nWarn,nError,nReacts,nProds,reactantLabels = PreprocessReaction(reaction) - if nError: raise ValueError,'bad reaction' - if len(bbLists) != nReacts: raise ValueError,'%d reactants in reaction, %d bb lists supplied'%(nReacts,len(bbLists)) + if nError: raise ValueError('bad reaction') + if len(bbLists) != nReacts: raise ValueError('%d reactants in reaction, %d bb lists supplied'%(nReacts,len(bbLists))) def _uniqueOnly(lst): seen=[] for entry in lst: diff --git a/rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py b/rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py index 47c835364..a5ed9a832 100755 --- a/rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py +++ b/rdkit/Chem/Suppliers/UnitTestSDMolSupplier.py @@ -16,8 +16,8 @@ import unittest,sys,os from rdkit import RDConfig from rdkit import Chem import tempfile -from cStringIO import StringIO - +from rdkit.six.moves import cStringIO as StringIO +from rdkit.six import next class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), @@ -28,7 +28,7 @@ class TestCase(unittest.TestCase): " tests reads using a file name " supp = Chem.SDMolSupplier(self.fName) for i in range(10): - m = supp.next() + m = next(supp) assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i i = 100 @@ -59,7 +59,7 @@ class TestCase(unittest.TestCase): supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) - m1 = supp.next() + m1 = next(supp) writer.SetProps(m1.GetPropNames()) for m in supp: writer.write(m) @@ -82,7 +82,7 @@ class TestCase(unittest.TestCase): supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) - m1 = supp.next() + m1 = next(supp) for m in supp: writer.write(m) writer.flush() @@ -110,7 +110,7 @@ class TestCase(unittest.TestCase): supp = Chem.SDMolSupplier(self.fName) outName = tempfile.mktemp('.sdf') writer = Chem.SDWriter(outName) - m1 = supp.next() + m1 = next(supp) for m in supp: writer.write(m) writer.flush() diff --git a/rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py b/rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py index 77a7ac5c9..8b7d0d75b 100755 --- a/rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py +++ b/rdkit/Chem/Suppliers/UnitTestSmilesMolSupplier.py @@ -14,6 +14,7 @@ import unittest,sys,os from rdkit import RDConfig from rdkit import Chem +from rdkit.six import next class TestCase(unittest.TestCase): def setUp(self): @@ -23,7 +24,7 @@ class TestCase(unittest.TestCase): " tests lazy reads """ supp = Chem.SmilesMolSupplierFromText('\n'.join(self.smis),',',0,-1,0) for i in range(4): - m = supp.next() + m = next(supp) assert m,'read %d failed'%i assert m.GetNumAtoms(),'no atoms in mol %d'%i i = len(supp)-1 diff --git a/rdkit/Chem/TemplateAlign.py b/rdkit/Chem/TemplateAlign.py index adaea30c0..c43e974a1 100644 --- a/rdkit/Chem/TemplateAlign.py +++ b/rdkit/Chem/TemplateAlign.py @@ -74,7 +74,7 @@ def AlignMolToTemplate2D(mol,template,match=None,clearConfs=False, if not match: match = mol.GetSubstructMatch(template) if not match: - raise ValueError,'no match between mol and template' + raise ValueError('no match between mol and template') atomMap = {} templateConf = template.GetConformer(templateConfId) diff --git a/rdkit/Chem/UnitTestCatalog.py b/rdkit/Chem/UnitTestCatalog.py index 619f0a88b..9c1ecdf14 100755 --- a/rdkit/Chem/UnitTestCatalog.py +++ b/rdkit/Chem/UnitTestCatalog.py @@ -8,12 +8,12 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # -from rdkit import RDConfig +import os import unittest +from rdkit import RDConfig from rdkit import Chem from rdkit.Chem import FragmentCatalog, BuildFragmentCatalog -import cPickle -import os +from rdkit.six.moves import cPickle def feq(n1,n2,tol=1e-4): return abs(n1-n2)','C=C<-O>'), txt) + self.assertTrue( txt in ('CCC<-O>','C=C<-O>'), txt) assert feq(entry[1],0.1611) entry = bitInfo[6] diff --git a/rdkit/Chem/UnitTestChem.py b/rdkit/Chem/UnitTestChem.py index ccb3882fc..164b7fda9 100755 --- a/rdkit/Chem/UnitTestChem.py +++ b/rdkit/Chem/UnitTestChem.py @@ -11,8 +11,9 @@ """basic unit testing code for the molecule boost wrapper """ +import unittest,os +from rdkit.six.moves import cPickle from rdkit import RDConfig -import unittest,cPickle,os from rdkit import Chem diff --git a/rdkit/Chem/UnitTestChemSmarts.py b/rdkit/Chem/UnitTestChemSmarts.py index 2af8f7f18..0fdf6a3b5 100755 --- a/rdkit/Chem/UnitTestChemSmarts.py +++ b/rdkit/Chem/UnitTestChemSmarts.py @@ -39,7 +39,7 @@ class TestCase(unittest.TestCase): p = Chem.MolFromSmarts('CC(=O)C') matches = self.m.GetSubstructMatches(p) m = matches[0] - atomList = map(lambda x,y=self.m:y.GetAtomWithIdx(x).GetSymbol(),m) + atomList = [self.m.GetAtomWithIdx(x).GetSymbol() for x in m] assert atomList==['C','C','O','C'],'bad atom ordering: %s'%str(atomList) if __name__ == '__main__': diff --git a/rdkit/Chem/UnitTestChemv2.py b/rdkit/Chem/UnitTestChemv2.py index 671ef12cb..2b3e587bc 100755 --- a/rdkit/Chem/UnitTestChemv2.py +++ b/rdkit/Chem/UnitTestChemv2.py @@ -11,8 +11,9 @@ """basic unit testing code for the rdkit Boost wrapper """ +import unittest,os +from rdkit.six.moves import cPickle from rdkit import RDConfig -import unittest,cPickle,os from rdkit import Chem from rdkit.Chem import AllChem @@ -171,10 +172,10 @@ class TestCase(unittest.TestCase): m = Chem.MolFromSmiles('C[C@H]1CO1') AllChem.Compute2DCoords(m) Chem.WedgeMolBonds(m,m.GetConformer()) - self.failUnless(m.GetBondWithIdx(0).GetBondDir()==Chem.rdchem.BondDir.BEGINDASH) - self.failUnless(m.GetBondWithIdx(1).GetBondDir()==Chem.rdchem.BondDir.NONE) - self.failUnless(m.GetBondWithIdx(2).GetBondDir()==Chem.rdchem.BondDir.NONE) - self.failUnless(m.GetBondWithIdx(3).GetBondDir()==Chem.rdchem.BondDir.NONE) + self.assertTrue(m.GetBondWithIdx(0).GetBondDir()==Chem.rdchem.BondDir.BEGINDASH) + self.assertTrue(m.GetBondWithIdx(1).GetBondDir()==Chem.rdchem.BondDir.NONE) + self.assertTrue(m.GetBondWithIdx(2).GetBondDir()==Chem.rdchem.BondDir.NONE) + self.assertTrue(m.GetBondWithIdx(3).GetBondDir()==Chem.rdchem.BondDir.NONE) if __name__ == '__main__': diff --git a/rdkit/Chem/UnitTestCrippen.py b/rdkit/Chem/UnitTestCrippen.py index a9567d717..ebe2a45fe 100755 --- a/rdkit/Chem/UnitTestCrippen.py +++ b/rdkit/Chem/UnitTestCrippen.py @@ -11,11 +11,15 @@ """unit testing code for the Crippen clogp and MR calculators """ +from __future__ import print_function +import unittest,sys,os + +import numpy + from rdkit import RDConfig -import unittest,sys,os,cPickle +from rdkit.six.moves import cPickle from rdkit import Chem from rdkit.Chem import Crippen -import numpy def feq(n1,n2,tol=1e-5): return abs(n1-n2)<=tol @@ -30,7 +34,9 @@ class TestCase(unittest.TestCase): smis=[] clogs=[] mrs=[] - for line in file(self.fName,'r').xreadlines(): + with open(self.fName,'r') as f: + lines = f.readlines() + for line in lines: if len(line) and line[0] != '#': splitL = line.split(',') if len(splitL)==3: @@ -53,15 +59,15 @@ class TestCase(unittest.TestCase): if 1: clog = self.clogs[i] tmp = Crippen.MolLogP(mol) - self.failUnless(feq(clog,tmp),'bad logp for %s: %4.4f != %4.4f'%(smi,clog,tmp)) + self.assertTrue(feq(clog,tmp),'bad logp for %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) - self.failUnless(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) + self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) else: clog = Crippen.MolLogP(mol) mr = Crippen.MolMR(mol) - print >>outF,'%s,%.4f,%.4f'%(smi,clog,mr) + print('%s,%.4f,%.4f'%(smi,clog,mr), file=outF) def testRepeat(self): self._readData() nMols = len(self.smis) @@ -72,12 +78,12 @@ class TestCase(unittest.TestCase): clog = self.clogs[i] tmp = Crippen.MolLogP(mol) tmp = Crippen.MolLogP(mol) - self.failUnless(feq(clog,tmp),'bad logp fooutF,r %s: %4.4f != %4.4f'%(smi,clog,tmp)) + self.assertTrue(feq(clog,tmp),'bad logp fooutF,r %s: %4.4f != %4.4f'%(smi,clog,tmp)) mr = self.mrs[i] tmp = Crippen.MolMR(mol) tmp = Crippen.MolMR(mol) - self.failUnless(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) + self.assertTrue(feq(mr,tmp),'bad MR for %s: %4.4f != %4.4f'%(smi,mr,tmp)) def _writeDetailFile(self,inF,outF): while 1: @@ -98,13 +104,13 @@ class TestCase(unittest.TestCase): contribs = Crippen._GetAtomContribs(mol) cPickle.dump((smi,contribs),outF) else: - print 'Problems with SMILES:',smi + print('Problems with SMILES:',smi) def _doDetailFile(self,inF,nFailsAllowed=1): done = 0 verbose=0 nFails=0 while not done: - if verbose: print '---------------' + if verbose: print('---------------') try: smi,refContribs = cPickle.load(inF) except EOFError: @@ -138,14 +144,14 @@ class TestCase(unittest.TestCase): refL = refContribs[refOrder[i]] l = contribs[order[i]] if not feq(refL,l): - print '%s (%s): %d %6.5f != %6.5f'%(smi,smi2,order[i],refL,l) + print('%s (%s): %d %6.5f != %6.5f'%(smi,smi2,order[i],refL,l)) Crippen._GetAtomContribs(mol,force=1) - print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*' + print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*') nFails +=1 break; else: - print 'Problems with SMILES:',smi - self.failUnless(nFails (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) it = chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) - it.next() + next(it) return it # Call this to get a new unique function. Used to break ties in the # priority queue. -tiebreaker = itertools.count().next +#tiebreaker = itertools.count().next +def _Counter(): + c = itertools.count() + return lambda: next(c) +tiebreaker = _Counter() ### The enumeration code @@ -1882,7 +1888,8 @@ def enumerate_subgraphs(enumeration_mols, prune, atom_assignment, matches_all_ta # 1055.2s sorting by (if bond.is_in_ring: 2; else: -(atom1.is_in_ring + atom2.is_in_ring)) # 1037.4s sorting by (atom1.is_in_ring + atom2.is_in_ring) sorted_bonds = list(enumerate(mol.bonds)) - def get_bond_ring_score((bond_index, bond), atoms=mol.atoms): + def get_bond_ring_score(bond_data, atoms=mol.atoms): + bond_index, bond = bond_data a1, a2 = bond.atom_indices return bond.is_in_ring + atoms[a1].is_in_ring + atoms[a2].is_in_ring sorted_bonds.sort(key = get_bond_ring_score) @@ -1978,7 +1985,7 @@ def enumerate_subgraphs(enumeration_mols, prune, atom_assignment, matches_all_ta # Assign a unique identifier to every unique key class Uniquer(dict): def __init__(self): - self.counter = itertools.count().next + self.counter = _Counter() def __missing__(self, key): self[key] = count = self.counter() return count @@ -2632,7 +2639,7 @@ def main(args=None): if atom_class_tag is not None: try: assign_isotopes_from_class_tag(mol, atom_class_tag) - except ValueError, err: + except ValueError as err: raise SystemExit("Structure #%d: %s" % (molno+1, err)) structures.append(mol) if args.verbosity > 1: diff --git a/rdkit/DataManip/Metric/__init__.py b/rdkit/DataManip/Metric/__init__.py index 7f2d376c4..2a6a24322 100755 --- a/rdkit/DataManip/Metric/__init__.py +++ b/rdkit/DataManip/Metric/__init__.py @@ -9,4 +9,4 @@ # of the RDKit source tree. # from rdkit import rdBase -from rdMetricMatrixCalc import * +from rdkit.DataManip.Metric.rdMetricMatrixCalc import * diff --git a/rdkit/DataStructs/TopNContainer.py b/rdkit/DataStructs/TopNContainer.py index c3aec2e9c..0c6b4b54f 100755 --- a/rdkit/DataStructs/TopNContainer.py +++ b/rdkit/DataStructs/TopNContainer.py @@ -8,6 +8,7 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function import bisect class TopNContainer(object): """ maintains a sorted list of a particular number of data elements. @@ -67,6 +68,6 @@ if __name__ == '__main__': c = TopNContainer(4) for pt in pts: c.Insert(pt,extra=str(pt)) - print c.GetPts() - print c.GetExtras() + print(c.GetPts()) + print(c.GetExtras()) diff --git a/rdkit/DataStructs/VectCollection.py b/rdkit/DataStructs/VectCollection.py index 555e9221a..1f3e4f1fb 100644 --- a/rdkit/DataStructs/VectCollection.py +++ b/rdkit/DataStructs/VectCollection.py @@ -8,8 +8,11 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function +import copy,struct +from rdkit.six.moves import cPickle +from rdkit.six import iterkeys from rdkit import DataStructs -import copy,struct,cPickle class VectCollection(object): """ @@ -150,7 +153,7 @@ class VectCollection(object): self.__orVect=None if not self.__vects: return - ks = self.__vects.keys() + ks = list(iterkeys(self.__vects)) self.__orVect = copy.copy(self.__vects[ks[0]]) self.__numBits = self.__orVect.GetNumBits() for i in range(1,len(ks)): @@ -213,7 +216,7 @@ class VectCollection(object): tmp = {} for k in keep: tmp[k] = self.__vects[k] - if verbose: print 'uniquify:',len(self.__vects),'->',len(tmp) + if verbose: print('uniquify:',len(self.__vects),'->',len(tmp)) self.__vects=tmp diff --git a/rdkit/DataStructs/__init__.py b/rdkit/DataStructs/__init__.py index 671dd3743..c20de6a91 100755 --- a/rdkit/DataStructs/__init__.py +++ b/rdkit/DataStructs/__init__.py @@ -8,10 +8,11 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import division from rdkit import rdBase -import cDataStructs +from rdkit.DataStructs import cDataStructs __doc__=cDataStructs.__doc__ -from cDataStructs import * +from rdkit.DataStructs.cDataStructs import * similarityFunctions=[ @@ -37,13 +38,13 @@ def FingerprintSimilarity(fp1,fp2,metric=TanimotoSimilarity): sz1 = fp1.GetNumBits() sz2 = fp2.GetNumBits() if sz1density and len(fp)/2>minLength: + while fp.GetNumOnBits()/len(fp)>density and len(fp)//2>minLength: fp = FoldFingerprint(fp,2) return fp diff --git a/rdkit/Dbase/DbConnection.py b/rdkit/Dbase/DbConnection.py index a4327c279..8906b15af 100755 --- a/rdkit/Dbase/DbConnection.py +++ b/rdkit/Dbase/DbConnection.py @@ -11,15 +11,14 @@ """ defines class _DbConnect_, for abstracting connections to databases """ +from __future__ import print_function from rdkit import RDConfig import sys,types -import exceptions class DbError(RuntimeError): pass -from rdkit.Dbase import DbUtils,DbInfo -import DbModule +from rdkit.Dbase import DbUtils,DbInfo,DbModule class DbConnect(object): @@ -269,7 +268,7 @@ class DbConnect(object): c.execute(addStr) except: import traceback - print 'command failed:',addStr + print('command failed:',addStr) traceback.print_exc() else: self.Commit() @@ -294,11 +293,11 @@ class DbConnect(object): c.execute(cmd,vals) except: import traceback - print 'insert failed:' - print cmd - print 'the error was:' + print('insert failed:') + print(cmd) + print('the error was:') traceback.print_exc() - raise DbError,"Insert Failed" + raise DbError("Insert Failed") def InsertColumnData(self,tableName,columnName,value,where): """ inserts data into a particular column of the table @@ -335,7 +334,7 @@ class DbConnect(object): try: c.execute("alter table %s add %s %s"%(tableName,colName,colType)) except: - print 'AddColumn failed' + print('AddColumn failed') def Commit(self): """ commits the current transaction diff --git a/rdkit/Dbase/DbInfo.py b/rdkit/Dbase/DbInfo.py index 9a7ce94b6..441e93979 100755 --- a/rdkit/Dbase/DbInfo.py +++ b/rdkit/Dbase/DbInfo.py @@ -8,9 +8,12 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # -from rdkit import RDConfig -import DbModule +from __future__ import print_function import sys + +from rdkit import RDConfig +from rdkit.Dbase import DbModule + sqlTextTypes = DbModule.sqlTextTypes sqlIntTypes = DbModule.sqlIntTypes sqlFloatTypes = DbModule.sqlFloatTypes @@ -36,7 +39,7 @@ def GetDbNames(user='sysdba',password='masterkey',dirName='.',dBase='::template1 try: cn = DbModule.connect(dBase,user,password) except: - print 'Problems opening database: %s'%(dBase) + print('Problems opening database: %s'%(dBase)) return [] c = cn.cursor() c.execute(DbModule.getDbSql) @@ -77,7 +80,7 @@ def GetTableNames(dBase,user='sysdba',password='masterkey', try: cn = DbModule.connect(dBase,user,password) except: - print 'Problems opening database: %s'%(dBase) + print('Problems opening database: %s'%(dBase)) return [] c = cn.cursor() if not includeViews: @@ -111,19 +114,19 @@ def GetColumnInfoFromCursor(cursor): sys.stderr.write('odd type in col %s: %s\n'%(cName,str(cType))) results.append((cName,typeStr)) else: - import types + from rdkit.six import PY2, PY3 r = cursor.fetchone() if not r: return results for i,v in enumerate(r): cName = cursor.description[i][0] typ = type(v) - if typ in types.StringTypes: + if typ == str or (PY2 and typ == unicode): typeStr='string' - elif typ == types.IntType: + elif typ == int: typeStr='integer' - elif typ == types.FloatType: + elif typ == float: typeStr='float' - elif typ == types.BufferType: + elif (PY2 and typ == buffer) or (PY3 and typ in (memoryview, bytes)): typeStr='binary' else: sys.stderr.write('odd type in col %s: %s\n'%(cName,typ)) @@ -201,5 +204,5 @@ def GetColumnNames(dBase,table,user='sysdba',password='masterkey', c.execute(cmd) c.fetchone() desc = c.description - res = map(lambda x:str(x[0]),desc) + res = [str(x[0]) for x in desc] return res diff --git a/rdkit/Dbase/DbModule.py b/rdkit/Dbase/DbModule.py index 84a5b7aaa..e22de1b09 100755 --- a/rdkit/Dbase/DbModule.py +++ b/rdkit/Dbase/DbModule.py @@ -8,6 +8,7 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +import sys from rdkit import RDConfig if hasattr(RDConfig,"usePgSQL") and RDConfig.usePgSQL: @@ -54,8 +55,11 @@ elif hasattr(RDConfig,"useSqlLite") and RDConfig.useSqlLite: dbFileWildcard='*.sqlt' placeHolder='?' binaryTypeName="blob" - binaryHolder = buffer + if sys.version > '3': + binaryHolder = memoryview + else: + binaryHolder = buffer connect = lambda x,*args:sqlite.connect(x) else: - raise ImportError,"Neither sqlite nor PgSQL support found." + raise ImportError("Neither sqlite nor PgSQL support found.") diff --git a/rdkit/Dbase/DbResultSet.py b/rdkit/Dbase/DbResultSet.py index 48c680f49..3d5f556bc 100755 --- a/rdkit/Dbase/DbResultSet.py +++ b/rdkit/Dbase/DbResultSet.py @@ -8,6 +8,7 @@ this uses the Python iterator interface, so you'll need python 2.2 or above. """ +from __future__ import print_function import sys from rdkit.Dbase import DbInfo @@ -93,6 +94,7 @@ class DbResultSet(DbResultBase): self.seen.append(v) return r + __next__ = next # PY3 class RandomAccessDbResultSet(DbResultBase): @@ -127,13 +129,13 @@ class RandomAccessDbResultSet(DbResultBase): r = self.cursor.fetchone() self.cursor = None def __getitem__(self,idx): - if idx < 0: raise IndexError,"negative indices not supported" + if idx < 0: raise IndexError("negative indices not supported") if self.cursor is None: if len(self.results): if idx >= len(self.results): - raise IndexError,'index %d too large (%d max)'%(idx,len(self.results)) + raise IndexError('index %d too large (%d max)'%(idx,len(self.results))) else: - raise ValueError,'Invalid cursor' + raise ValueError('Invalid cursor') while idx >= len(self.results): r = None @@ -141,7 +143,7 @@ class RandomAccessDbResultSet(DbResultBase): r = self.cursor.fetchone() if not r: self.cursor = None - raise IndexError,'index %d too large (%d max)'%(idx,len(self.results)) + raise IndexError('index %d too large (%d max)'%(idx,len(self.results))) if self.transform is not None: r = self.transform(r) @@ -159,7 +161,7 @@ class RandomAccessDbResultSet(DbResultBase): def __len__(self): if self.results is None: - raise ValueError,"len() not supported for noMemory Results Sets" + raise ValueError("len() not supported for noMemory Results Sets") self._finish() return len(self.results) @@ -172,11 +174,14 @@ class RandomAccessDbResultSet(DbResultBase): raise StopIteration return res + __next__ = next # PY3 + + if __name__ == '__main__': from rdkit.Dbase.DbConnection import DbConnect conn = DbConnect('TEST.GDB') curs = conn.GetCursor() - print 'curs:',repr(curs) + print('curs:',repr(curs)) curs.execute('select * from ten_elements') set = RandomAccessDbResultSet(curs) for i in range(12): @@ -185,21 +190,21 @@ if __name__ == '__main__': except IndexError: assert i >= 10 - print 'use len' + print('use len') curs = conn.GetCursor() curs.execute('select * from ten_elements') set = RandomAccessDbResultSet(curs) for i in range(len(set)): val = set[i] - print 'use iter' + print('use iter') curs = conn.GetCursor() curs.execute('select * from ten_elements') set = DbResultSet(curs) for thing in set: id,val = thing - print 'dups' + print('dups') curs = conn.GetCursor() curs.execute('select * from ten_elements_dups') set = DbResultSet(curs) diff --git a/rdkit/Dbase/DbUtils.py b/rdkit/Dbase/DbUtils.py index 54926a5f2..7127d052d 100755 --- a/rdkit/Dbase/DbUtils.py +++ b/rdkit/Dbase/DbUtils.py @@ -13,6 +13,7 @@ When possible, it's probably preferable to use a _DbConnection.DbConnect_ object """ +from __future__ import print_function from rdkit import RDConfig from rdkit.Dbase.DbResultSet import DbResultSet,RandomAccessDbResultSet def _take(fromL,what): @@ -106,9 +107,9 @@ def GetData(dBase,table,fieldString='*',whereString='',user='sysdba',password='m traceback.print_exc() return None if transform is not None: - raise ValueError,'forceList and transform arguments are not compatible' + raise ValueError('forceList and transform arguments are not compatible') if not randomAccess: - raise ValueError,'when forceList is set, randomAccess must also be used' + raise ValueError('when forceList is set, randomAccess must also be used') data = c.fetchall() if removeDups>0: seen = [] @@ -206,10 +207,10 @@ def TypeFinder(data,nRows,nCols,nullMarker=None): locType = types.StringType try: d = str(d) - except UnicodeError,msg: - print 'cannot convert text from row %d col %d to a string'%(row+2,col) - print '\t>%s'%(repr(d)) - raise UnicodeError,msg + except UnicodeError as msg: + print('cannot convert text from row %d col %d to a string'%(row+2,col)) + print('\t>%s'%(repr(d))) + raise UnicodeError(msg) else: typeHere[1] = max(typeHere[1],len(str(d))) if locType == types.StringType: @@ -248,7 +249,7 @@ def _AdjustColHeadings(colHeadings,maxColLabelLen): # interbase (at least) has a limit on the maximum length of a column name newHead = string.replace(colHeadings[i],'_','') newHead = newHead[:maxColLabelLen] - print '\tHeading %s too long, changed to %s'%(colHeadings[i],newHead) + print('\tHeading %s too long, changed to %s'%(colHeadings[i],newHead)) colHeadings[i] = newHead return colHeadings @@ -282,8 +283,8 @@ def _insertBlock(conn,sqlStr,block,silent=False): if not silent: import traceback traceback.print_exc() - print 'insert failed:',sqlStr - print '\t',repr(row) + print('insert failed:',sqlStr) + print('\t',repr(row)) else: conn.commit() else: @@ -303,13 +304,13 @@ def _AddDataToDb(dBase,table,user,password,colDefs,colTypes,data, try: c.execute('drop table %s'%(table)) except: - print 'cannot drop table %s'%(table) + print('cannot drop table %s'%(table)) try: sqlStr = 'create table %s (%s)'%(table,colDefs) c.execute(sqlStr) except: - print 'create table failed: ', sqlStr - print 'here is the exception:' + print('create table failed: ', sqlStr) + print('here is the exception:') import traceback traceback.print_exc() return @@ -391,7 +392,7 @@ def TextFileToDatabase(dBase,table,inF,delim=',', inL = inL.replace('\n','') splitL = inL.split(delim) if len(splitL)!=nCols: - print '>>>',repr(inL) + print('>>>',repr(inL)) assert len(splitL)==nCols,'unequal length' tmpVect = [] for entry in splitL: diff --git a/rdkit/DistanceGeometry/__init__.py b/rdkit/DistanceGeometry/__init__.py index ac43f0790..67c9e34c6 100644 --- a/rdkit/DistanceGeometry/__init__.py +++ b/rdkit/DistanceGeometry/__init__.py @@ -1 +1 @@ -from DistGeom import * +from rdkit.DistanceGeometry.DistGeom import * diff --git a/rdkit/ForceField/__init__.py b/rdkit/ForceField/__init__.py index 478a4dbd3..75579873c 100644 --- a/rdkit/ForceField/__init__.py +++ b/rdkit/ForceField/__init__.py @@ -1 +1 @@ -from rdForceField import * +from rdkit.ForceField.rdForceField import * diff --git a/rdkit/Geometry/__init__.py b/rdkit/Geometry/__init__.py index 9e7874803..ce2a8f5aa 100644 --- a/rdkit/Geometry/__init__.py +++ b/rdkit/Geometry/__init__.py @@ -2,4 +2,4 @@ """ from rdkit import DataStructs -from rdGeometry import * +from rdkit.Geometry.rdGeometry import * diff --git a/rdkit/ML/AnalyzeComposite.py b/rdkit/ML/AnalyzeComposite.py index 6902b095c..8f4d5a5fb 100755 --- a/rdkit/ML/AnalyzeComposite.py +++ b/rdkit/ML/AnalyzeComposite.py @@ -26,9 +26,10 @@ Usage: AnalyzeComposite [optional args] -v: be verbose whilst screening """ - +from __future__ import print_function import numpy -import sys,cPickle +import sys +from rdkit.six.moves import cPickle from rdkit.ML.DecTree import TreeUtils,Tree from rdkit.ML.Data import Stats from rdkit.Dbase.DbConnection import DbConnect @@ -48,8 +49,8 @@ def ProcessIt(composites,nToConsider=3,verbose=0): descNames = {} for composite in composites: if verbose > 0: - print '#------------------------------------' - print 'Doing: ',nDone + print('#------------------------------------') + print('Doing: ',nDone) nModels = len(composite) nDone += 1 res = {} @@ -70,25 +71,25 @@ def ProcessIt(composites,nToConsider=3,verbose=0): for k in res.keys(): name = descNames[k] strRes = ', '.join(['%4.2f'%x for x in res[k]]) - print '%s,%s,%5.4f'%(name,strRes,sum(res[k])) + print('%s,%s,%5.4f'%(name,strRes,sum(res[k]))) - print + print() if verbose >= 0: - print '# Average Descriptor Positions' + print('# Average Descriptor Positions') retVal = [] for k in globalRes.keys(): name = descNames[k] if verbose >= 0: strRes = ', '.join(['%4.2f'%x for x in globalRes[k]]) - print '%s,%s,%5.4f'%(name,strRes,sum(globalRes[k])) + print('%s,%s,%5.4f'%(name,strRes,sum(globalRes[k]))) tmp = [name] tmp.extend(globalRes[k]) tmp.append(sum(globalRes[k])) retVal.append(tmp) if verbose >= 0: - print + print() else: retVal = [] return retVal @@ -203,63 +204,63 @@ def ShowStats(statD,enrich=1): \tHoldout: %(hAvg)6.3f%% (%(hDev)6.3f) %(hCorrectConf)4.1f/%(hIncorrectConf)4.1f \t\tBest: %(hBestIdx)d %(hBestErr)6.3f%% """%(statD) - print txt - print - print '# Results matrices:' - print '\tOverall:' + print(txt) + print() + print('# Results matrices:') + print('\tOverall:') tmp = transpose(statD['oResultMat']) colCounts = sum(tmp) rowCounts = sum(tmp,1) for i in range(len(tmp)): if rowCounts[i]==0: rowCounts[i]=1 row = tmp[i] - print '\t\t', + print('\t\t', end='') for j in range(len(row)): - print '% 6.2f'%row[j], - print '\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i]) - print '\t\t', + print('% 6.2f'%row[j], end='') + print('\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i])) + print('\t\t', end='') for i in range(len(tmp)): - print '------', - print - print '\t\t', + print('------',end='') + print() + print('\t\t',end='') for i in range(len(tmp)): if colCounts[i]==0: colCounts[i]=1 - print '% 6.2f'%(100.*tmp[i,i]/colCounts[i]), - print - if enrich>-1 and statD.has_key('oAvgEnrich'): - print '\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['oAvgEnrich'],statD['oDevEnrich']) + print('% 6.2f'%(100.*tmp[i,i]/colCounts[i]), end='') + print() + if enrich>-1 and 'oAvgEnrich' in statD: + print('\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['oAvgEnrich'],statD['oDevEnrich'])) - if statD.has_key('hResultMat'): - print '\tHoldout:' + if 'hResultMat' in statD: + print('\tHoldout:') tmp = transpose(statD['hResultMat']) colCounts = sum(tmp) rowCounts = sum(tmp,1) for i in range(len(tmp)): if rowCounts[i]==0: rowCounts[i]=1 row = tmp[i] - print '\t\t', + print('\t\t', end='') for j in range(len(row)): - print '% 6.2f'%row[j], - print '\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i]) - print '\t\t', + print('% 6.2f'%row[j], end='') + print('\t| % 4.2f'%(100.*tmp[i,i]/rowCounts[i])) + print('\t\t',end='') for i in range(len(tmp)): - print '------', - print - print '\t\t', + print('------',end='') + print() + print('\t\t',end='') for i in range(len(tmp)): if colCounts[i]==0: colCounts[i]=1 - print '% 6.2f'%(100.*tmp[i,i]/colCounts[i]), - print - if enrich>-1 and statD.has_key('hAvgEnrich'): - print '\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['hAvgEnrich'],statD['hDevEnrich']) + print('% 6.2f'%(100.*tmp[i,i]/colCounts[i]),end='') + print() + if enrich>-1 and 'hAvgEnrich' in statD: + print('\t\tEnrich(%d): %.3f (%.3f)'%(enrich,statD['hAvgEnrich'],statD['hDevEnrich'])) return def Usage(): - print __doc__ + print(__doc__) sys.exit(-1) if __name__ == "__main__": @@ -313,7 +314,7 @@ if __name__ == "__main__": if len(composites): ProcessIt(composites,count,verbose=verbose) elif not skip: - print 'ERROR: no composite models found' + print('ERROR: no composite models found') sys.exit(-1) if db: diff --git a/rdkit/ML/BuildComposite.py b/rdkit/ML/BuildComposite.py index a2e06fb6e..a18bf53c9 100755 --- a/rdkit/ML/BuildComposite.py +++ b/rdkit/ML/BuildComposite.py @@ -198,18 +198,20 @@ a QDAT file. """ +from __future__ import print_function +import sys,time +import math +import numpy +from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit.utils import listutils from rdkit.ML.Composite import Composite,BayesComposite #from ML.SVM import SVMClassificationModel as SVM -import numpy -import math from rdkit.ML.Data import DataUtils,SplitData from rdkit.ML import ScreenComposite from rdkit.Dbase import DbModule from rdkit.Dbase.DbConnection import DbConnect from rdkit.ML import CompositeRun -import sys,cPickle,time from rdkit import DataStructs _runDetails = CompositeRun.CompositeRun() @@ -755,18 +757,18 @@ def ShowVersion(includeArgs=0): """ prints the version number """ - print 'This is BuildComposite.py version %s'%(__VERSION_STRING) + print('This is BuildComposite.py version %s' % (__VERSION_STRING)) if includeArgs: import sys - print 'command line was:' - print ' '.join(sys.argv) + print('command line was:') + print(' '.join(sys.argv)) def Usage(): """ provides a list of arguments for when this is used from the command line """ import sys - print __doc__ + print(__doc__) sys.exit(-1) def SetDefaults(runDetails=None): diff --git a/rdkit/ML/Cluster/ClusterUtils.py b/rdkit/ML/Cluster/ClusterUtils.py index 677a21f6e..13757205f 100755 --- a/rdkit/ML/Cluster/ClusterUtils.py +++ b/rdkit/ML/Cluster/ClusterUtils.py @@ -30,7 +30,7 @@ def GetNodeList(cluster): return [cluster] else: children = cluster.GetChildren() - children.sort(lambda x,y:cmp(len(y),len(x))) + children.sort(key=lambda x:len(x), reverse=True) res = [] for child in children: res += GetNodeList(child) @@ -111,7 +111,7 @@ def _BreadthFirstSplit(cluster,n): """ if len(cluster) threshold: return res,conf else: diff --git a/rdkit/ML/Composite/Composite.py b/rdkit/ML/Composite/Composite.py index d5f2b0b8f..2b8a8634f 100755 --- a/rdkit/ML/Composite/Composite.py +++ b/rdkit/ML/Composite/Composite.py @@ -22,10 +22,11 @@ Other compatibility notes: """ -from rdkit.ML.Data import DataUtils -import cPickle +from __future__ import print_function import math import numpy +from rdkit.six.moves import cPickle, xrange +from rdkit.ML.Data import DataUtils class Composite(object): """a composite model @@ -377,8 +378,7 @@ class Composite(object): - if the local descriptor names do not appear in _colNames_, this will raise an _IndexError_ exception. """ - import types - if type(colNames)!=types.ListType: + if type(colNames)!=list: colNames = list(colNames) descs = [x.upper() for x in self.GetDescriptorNames()] self._mapOrder = [None]*len(descs) @@ -396,7 +396,7 @@ class Composite(object): try: self._mapOrder[i] = colNames.index(descs[i]) except ValueError: - raise ValueError,'cannot find descriptor name: %s in set %s'%(repr(descs[i]),repr(colNames)) + raise ValueError('cannot find descriptor name: %s in set %s'%(repr(descs[i]),repr(colNames))) try: self._mapOrder[-1] = colNames.index(descs[-1]) except ValueError: @@ -475,9 +475,8 @@ class Composite(object): else: trainSet = trainExamples - #print "Training model %i with %i out of %i examples"%(i, len(trainSet), len(trainExamples)) - model,frac = apply(buildDriver,(trainSet,attrs,nPossibleVals), - buildArgs) + #print("Training model %i with %i out of %i examples"%(i, len(trainSet), len(trainExamples))) + model,frac = buildDriver(*(trainSet,attrs,nPossibleVals), **buildArgs) if pruneIt: model,frac2 = pruner(model,model.GetTrainingExamples(), model.GetTestExamples(), @@ -491,7 +490,7 @@ class Composite(object): self.AddModel(model,frac,needsQuantization) if not silent and (nTries < 10 or i % (nTries/10) == 0): - print 'Cycle: % 4d'%(i) + print('Cycle: % 4d'%(i)) if progressCallback is not None: progressCallback(i) @@ -715,13 +714,13 @@ if __name__ == '__main__': c.AddModel(n,0.5) c.AverageErrors() c.SortModels() - print c + print(c) qB = [[],[.5,1,1.5]] exs = [['foo',0],['foo',.4],['foo',.6],['foo',1.1],['foo',2.0]] - print 'quantBounds:',qB + print('quantBounds:',qB) for ex in exs: q = c.QuantizeExample(ex,qB) - print ex,q + print(ex,q) else: pass diff --git a/rdkit/ML/Composite/UnitTestComposite.py b/rdkit/ML/Composite/UnitTestComposite.py index 53b1d080f..163ce1837 100755 --- a/rdkit/ML/Composite/UnitTestComposite.py +++ b/rdkit/ML/Composite/UnitTestComposite.py @@ -8,7 +8,7 @@ """ import unittest -import cPickle +from rdkit.six.moves import cPickle, xrange from rdkit.ML.Composite import Composite from rdkit.ML.DecTree.DecTree import DecTreeNode as Node from rdkit import RDConfig @@ -17,7 +17,8 @@ from rdkit import RDConfig class TestCase(unittest.TestCase): def setUp(self): #print '\n%s: '%self.shortDescription(), - self.examples = cPickle.load(open(RDConfig.RDCodeDir+'/ML/Composite/test_data/ferro.pkl','rb')) + with open(RDConfig.RDCodeDir+'/ML/Composite/test_data/ferro.pkl','rb') as pklF: + self.examples = cPickle.load(pklF) self.varNames = ['composition','max_atomic','has3d','has4d','has5d','elconc','atvol','isferro'] self.qBounds = [[],[1.89,3.53],[],[],[],[0.55,0.73],[11.81,14.52],[]] self.nPoss= [0,3,2,2,2,3,3,2] @@ -40,7 +41,8 @@ class TestCase(unittest.TestCase): def testTreeGrow(self): " testing tree-based composite " - self.refCompos = cPickle.load(open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.pkl','rb')) + with open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.pkl','rb') as pklF: + self.refCompos = cPickle.load(pklF) composite = Composite.Composite() composite._varNames=self.varNames @@ -65,8 +67,10 @@ class TestCase(unittest.TestCase): def testTreeScreen(self): " testing tree-based composite screening " - self.refCompos = cPickle.load(open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.pkl','rb')) - testCompos = cPickle.load(open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.unittree.pkl','rb')) + with open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.pkl','rb') as pklF: + self.refCompos = cPickle.load(pklF) + with open(RDConfig.RDCodeDir+'/ML/Composite/test_data/composite_base.unittree.pkl','rb') as pklF: + testCompos = cPickle.load(pklF) for example in self.examples: res,conf = testCompos.ClassifyExample(example) cRes,cConf = self.refCompos.ClassifyExample(example) diff --git a/rdkit/ML/Data/DataUtils.py b/rdkit/ML/Data/DataUtils.py index c7a5d63bc..0cdef0645 100755 --- a/rdkit/ML/Data/DataUtils.py +++ b/rdkit/ML/Data/DataUtils.py @@ -52,18 +52,21 @@ 4) A python list of lists with the data points """ +from __future__ import print_function +import re,csv +import random + +from rdkit import six +from rdkit.six.moves import cPickle +from rdkit.six.moves import xrange, map from rdkit import RDConfig from rdkit.utils import fileutils from rdkit.ML.Data import MLData from rdkit.Dbase.DbConnection import DbConnect from rdkit.DataStructs import BitUtils -import string -import re,csv -import cPickle -import random def permutation(nToDo): - res = range(nToDo) + res = list(xrange(nToDo)) random.shuffle(res) return res @@ -89,7 +92,7 @@ def WriteData(outFile,varNames,qBounds,examples): outFile.write('# %s %s\n'%(varNames[i],str(qBounds[i]))) outFile.write('# ----------\n') for example in examples: - outFile.write(string.join(map(str,example),' ')+'\n') + outFile.write(' '.join(map(str,example))+'\n') def ReadVars(inFile): @@ -112,15 +115,15 @@ def ReadVars(inFile): qBounds = [] fileutils.MoveToMatchingLine(inFile,'Variable Table') inLine = inFile.readline() - while string.find(inLine,'# ----') == -1: - splitLine = string.split(inLine[2:],'[') - varNames.append(string.strip(splitLine[0])) + while inLine.find('# ----') == -1: + splitLine = inLine[2:].split('[') + varNames.append(splitLine[0].strip()) qBounds.append(splitLine[1][:-2]) inLine = inFile.readline() for i in xrange(len(qBounds)): if qBounds[i] != '': - l = string.split(qBounds[i],',') + l = qBounds[i].split(',') qBounds[i] = [] for item in l: qBounds[i].append(float(item)) @@ -158,7 +161,7 @@ def ReadQuantExamples(inFile): if expr1.search(inLine) is None: resArr = expr2.split(inLine) if len(resArr)>1: - examples.append(map(lambda x: int(x),resArr[1:])) + examples.append(list(map(lambda x: int(x),resArr[1:]))) names.append(resArr[0]) inLine = inFile.readline() return names,examples @@ -219,10 +222,9 @@ def BuildQuantDataSet(fileName): an _MLData.MLQuantDataSet_ """ - inFile = open(fileName,'r') - - varNames,qBounds = ReadVars(inFile) - ptNames,examples = ReadQuantExamples(inFile) + with open(fileName,'r') as inFile: + varNames,qBounds = ReadVars(inFile) + ptNames,examples = ReadQuantExamples(inFile) data = MLData.MLQuantDataSet(examples,qBounds=qBounds,varNames=varNames, ptNames=ptNames) return data @@ -240,10 +242,9 @@ def BuildDataSet(fileName): an _MLData.MLDataSet_ """ - inFile = open(fileName,'r') - - varNames,qBounds = ReadVars(inFile) - ptNames,examples = ReadGeneralExamples(inFile) + with open(fileName,'r') as inFile: + varNames,qBounds = ReadVars(inFile) + ptNames,examples = ReadGeneralExamples(inFile) data = MLData.MLDataSet(examples,qBounds=qBounds,varNames=varNames, ptNames=ptNames) return data @@ -272,10 +273,13 @@ def CalcNPossibleUsingMap(data,order,qBounds,nQBounds=None): - _nPossible_ for other numeric variables will be calculated """ - numericTypes = [type(1),type(1.0),type(1L)] - print 'order:',order, len(order) - print 'qB:',qBounds - #print 'nQB:',nQBounds, len(nQBounds) + numericTypes = [int, float] + if six.PY2: + numericTypes.append(long) + + print('order:',order, len(order)) + print('qB:',qBounds) + #print('nQB:',nQBounds, len(nQBounds)) assert (qBounds and len(order)==len(qBounds)) or (nQBounds and len(order)==len(nQBounds)),\ 'order/qBounds mismatch' nVars = len(order) @@ -300,11 +304,11 @@ def CalcNPossibleUsingMap(data,order,qBounds,nQBounds=None): nPossible[col] = -1 cols.remove(col) else: - print 'bye bye col %d: %s'%(col,repr(d)) + print('bye bye col %d: %s'%(col,repr(d))) nPossible[col] = -1 cols.remove(col) - return map(lambda x:int(x)+1,nPossible) + return list(map(lambda x:int(x)+1,nPossible)) @@ -441,7 +445,7 @@ def TextToData(reader,ignoreCols=[],onlyCols=None): for splitLine in reader: if len(splitLine): if len(splitLine)!=nCols: - raise ValueError,'unequal line lengths' + raise ValueError('unequal line lengths') tmp = [splitLine[x] for x in keepCols] ptNames.append(tmp[0]) pt = [None]*(nVars-1) @@ -493,11 +497,11 @@ def FilterData(inData,val,frac,col=-1,indicesToUse=None,indicesOnly=0): """ #DOC """ - if frac<0 or frac>1: raise ValueError,'filter fraction out of bounds' + if frac<0 or frac>1: raise ValueError('filter fraction out of bounds') try: inData[0][col] except IndexError: - raise ValueError,'target column index out of range' + raise ValueError('target column index out of range') # convert the input data to a list and sort them @@ -506,8 +510,10 @@ def FilterData(inData,val,frac,col=-1,indicesToUse=None,indicesOnly=0): else: tmp = list(inData) nOrig = len(tmp) - sortOrder = range(nOrig) - sortOrder.sort(lambda x,y,col=col,tmp=tmp:cmp(tmp[x][col],tmp[y][col])) + sortOrder = list(xrange(nOrig)) + #sortOrder.sort(lambda x,y,col=col,tmp=tmp:cmp(tmp[x][col],tmp[y][col])) + # no more cmp in python3, must use a key function + sortOrder.sort(key=lambda x: tmp[x][col]) tmp = [tmp[x] for x in sortOrder] # find the start of the entries with value val @@ -515,7 +521,7 @@ def FilterData(inData,val,frac,col=-1,indicesToUse=None,indicesOnly=0): while start < nOrig and tmp[start][col] != val: start += 1 if start >= nOrig: - raise ValueError,'target value (%d) not found in data'%(val) + raise ValueError('target value (%d) not found in data'%(val)) # find the end of the entries with value val finish = start+1 @@ -567,11 +573,11 @@ def FilterData(inData,val,frac,col=-1,indicesToUse=None,indicesOnly=0): nOthersFinal -= 1 nFinal -= 1 - others = range(start) + range(finish,nOrig) + others = list(xrange(start)) + list(xrange(finish,nOrig)) othersTake = permutation(nOthers) others = [others[x] for x in othersTake[:nOthersFinal]] - targets = range(start,finish) + targets = list(xrange(start,finish)) targetsTake = permutation(nWithVal) targets = [targets[x] for x in targetsTake[:nTgtFinal]] diff --git a/rdkit/ML/Data/MLData.py b/rdkit/ML/Data/MLData.py index a1054c17f..0b3df7431 100755 --- a/rdkit/ML/Data/MLData.py +++ b/rdkit/ML/Data/MLData.py @@ -5,12 +5,17 @@ """ classes to be used to help work with data sets """ +from __future__ import print_function import numpy import math import copy,types +from rdkit import six +from rdkit.six.moves import xrange +numericTypes = [int, float] +if six.PY2: + numericTypes.append(long) -numericTypes = [type(1),type(1.0),type(1L)] class MLDataSet(object): """ A data set for holding general data (floats, ints, and strings) @@ -85,7 +90,7 @@ class MLDataSet(object): """ nVars = self.GetNVars()+self.nResults nPossible = [-1]*nVars - cols = range(nVars) + cols = list(xrange(nVars)) for i,bounds in enumerate(self.qBounds): if len(bounds)>0: nPossible[i] = len(bounds) @@ -122,7 +127,7 @@ class MLDataSet(object): return res def __setitem__(self,idx,val): if len(val) != self.GetNVars()+self.GetNResults()+1: - raise ValueError,'bad value in assignment' + raise ValueError('bad value in assignment') self.ptNames[idx] = val[0] self.data[idx] = val[1:] return val @@ -181,7 +186,7 @@ class MLDataSet(object): def AddPoints(self,pts,names): if len(pts)!=len(names): - raise ValueError,"input length mismatch" + raise ValueError("input length mismatch") self.data += pts self.ptNames += names self.nPts = len(self.data) @@ -323,15 +328,15 @@ if __name__ == '__main__': ptNames = ['p1','p2','p3','p4','p5'] set = MLQuantDataSet(examples,varNames=varNames,ptNames=ptNames) DataUtils.WritePickledData('test_data/test.qdat.pkl',set) - print 'nVars:',set.GetNVars() - print 'nPts:',set.GetNPts() - print 'nPoss:',set.GetNPossibleVals() - print 'qBounds:',set.GetQuantBounds() - print 'data:',set.GetAllData() - print 'Input data:',set.GetInputData() - print 'results:',set.GetResults() + print('nVars:',set.GetNVars()) + print('nPts:',set.GetNPts()) + print('nPoss:',set.GetNPossibleVals()) + print('qBounds:',set.GetQuantBounds()) + print('data:',set.GetAllData()) + print('Input data:',set.GetInputData()) + print('results:',set.GetResults()) - print 'nameddata:',set.GetNamedData() + print('nameddata:',set.GetNamedData()) examples = [ ['foo',1,1.0,1,1.1], @@ -345,13 +350,13 @@ if __name__ == '__main__': ptNames = ['p1','p2','p3','p4','p5'] set = MLDataSet(examples,qBounds=qBounds) DataUtils.WritePickledData('test_data/test.dat.pkl',set) - print 'nVars:',set.GetNVars() - print 'nPts:',set.GetNPts() - print 'nPoss:',set.GetNPossibleVals() - print 'qBounds:',set.GetQuantBounds() - print 'data:',set.GetAllData() - print 'Input data:',set.GetInputData() - print 'results:',set.GetResults() + print('nVars:',set.GetNVars()) + print('nPts:',set.GetNPts()) + print('nPoss:',set.GetNPossibleVals()) + print('qBounds:',set.GetQuantBounds()) + print('data:',set.GetAllData()) + print('Input data:',set.GetInputData()) + print('results:',set.GetResults()) - print 'nameddata:',set.GetNamedData() + print('nameddata:',set.GetNamedData()) diff --git a/rdkit/ML/Data/Quantize.py b/rdkit/ML/Data/Quantize.py index d9e90c472..9ea077a25 100755 --- a/rdkit/ML/Data/Quantize.py +++ b/rdkit/ML/Data/Quantize.py @@ -15,8 +15,10 @@ lie. [0.9,1.,1.1,2.,2.2] -> [0,1,1,2,2] """ +from __future__ import print_function import numpy from rdkit.ML.InfoTheory import entropy +from rdkit.six.moves import zip, map, range try: import cQuantize except: @@ -305,7 +307,7 @@ def FindVarMultQuantBounds(vals,nBounds,results,nPossibleRes): return [],-1e8 # sort the variable values: - svs = zip(vals,results) + svs = list(zip(vals,results)) svs.sort() sortVals,sortResults = zip(*svs) startNext=_FindStartPoints(sortVals,sortResults,nData) @@ -315,7 +317,7 @@ def FindVarMultQuantBounds(vals,nBounds,results,nPossibleRes): nBounds = len(startNext)-1 if nBounds == 0: nBounds=1 - initCuts = range(nBounds) + initCuts = list(range(nBounds)) maxGain,bestCuts = _RecurseOnBounds(sortVals,initCuts,0,startNext, sortResults,nPossibleRes) quantBounds = [] @@ -354,11 +356,11 @@ if __name__ == '__main__': (2.1,0), (2.2,1), (2.3,0)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues = list(map(lambda x:x[0],d)) + resCodes = list(map(lambda x:x[1],d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) - print 'RES:',res + print('RES:',res) target = ([1.3, 2.05],.34707 ) else: d = [(1.,0), @@ -373,28 +375,28 @@ if __name__ == '__main__': (2.1,0), (2.2,1), (2.3,0)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues = list(map(lambda x:x[0],d)) + resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,1,resCodes,nPossibleRes) - print res + print(res) #sys.exit(1) d = [(1.4,1), (1.4,0)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues = list(map(lambda x:x[0],d)) + resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,1,resCodes,nPossibleRes) - print res + print(res) d = [(1.4,0), (1.4,0),(1.6,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues = list(map(lambda x:x[0],d)) + resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) - print res + print(res) diff --git a/rdkit/ML/Data/SplitData.py b/rdkit/ML/Data/SplitData.py index 7e0a56ec1..28817730e 100755 --- a/rdkit/ML/Data/SplitData.py +++ b/rdkit/ML/Data/SplitData.py @@ -4,10 +4,14 @@ # Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC # All Rights Reserved # -from rdkit import RDConfig,RDRandom +from __future__ import print_function import random -import types,os.path,sys -SeqTypes=(types.ListType,types.TupleType) +import os.path,sys + +from rdkit import RDConfig,RDRandom +from rdkit.six.moves import xrange + +SeqTypes=(list, tuple) def SplitIndices(nPts,frac,silent=1,legacy=0,replacement=0): """ splits a set of indices into a data set into 2 pieces @@ -116,7 +120,7 @@ def SplitIndices(nPts,frac,silent=1,legacy=0,replacement=0): else: resTest.append(i) else: - perm = range(nPts) + perm = list(xrange(nPts)) random.shuffle(perm) nTrain = int(nPts*frac) @@ -124,8 +128,8 @@ def SplitIndices(nPts,frac,silent=1,legacy=0,replacement=0): resTest = list(perm[nTrain:]) if not silent: - print 'Training with %d (of %d) points.'%(len(resData),nPts) - print '\t%d points are in the hold-out set.'%(len(resTest)) + print('Training with %d (of %d) points.'%(len(resData),nPts)) + print('\t%d points are in the hold-out set.'%(len(resTest))) return resData,resTest @@ -154,8 +158,8 @@ def SplitDataSet(data,frac,silent=0): resTest = [data[x] for x in test] if not silent: - print 'Training with %d (of %d) points.'%(len(resData),nOrig) - print '\t%d points are in the hold-out set.'%(len(resTest)) + print('Training with %d (of %d) points.'%(len(resData),nOrig)) + print('\t%d points are in the hold-out set.'%(len(resTest))) return resData,resTest diff --git a/rdkit/ML/Data/UnitTestMLData.py b/rdkit/ML/Data/UnitTestMLData.py index 4819751fa..f66033798 100755 --- a/rdkit/ML/Data/UnitTestMLData.py +++ b/rdkit/ML/Data/UnitTestMLData.py @@ -6,7 +6,7 @@ """ import unittest -import cPickle +from rdkit.six.moves import cPickle from rdkit.ML.Data import MLData,DataUtils from rdkit import RDConfig diff --git a/rdkit/ML/Data/UnitTestQuantize.py b/rdkit/ML/Data/UnitTestQuantize.py index ec5c0a476..9174ac0a1 100755 --- a/rdkit/ML/Data/UnitTestQuantize.py +++ b/rdkit/ML/Data/UnitTestQuantize.py @@ -8,6 +8,7 @@ import unittest from rdkit import RDConfig from rdkit.ML.Data import Quantize +from rdkit.six.moves import map class TestCase(unittest.TestCase): def setUp(self): @@ -27,12 +28,11 @@ class TestCase(unittest.TestCase): (2.1,1), (2.2,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarQuantBound(varValues,resCodes,nPossibleRes) target = (1.8,0.97095) - assert map(lambda x,y:Quantize.feq(x,y,1e-4),res,target)==[1,1],\ + assert list(map(lambda x,y:Quantize.feq(x,y,1e-4),res,target))==[1,1],\ 'result comparison failed: %s != %s'%(res,target) def testOneSplit2(self): @@ -48,12 +48,11 @@ class TestCase(unittest.TestCase): (2.1,1), (2.2,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarQuantBound(varValues,resCodes,nPossibleRes) target = (1.8,0.60999) - assert map(lambda x,y:Quantize.feq(x,y,1e-4),res,target)==[1,1],\ + assert list(map(lambda x,y:Quantize.feq(x,y,1e-4),res,target))==[1,1],\ 'result comparison failed: %s != %s'%(res,target) def testOneSplit3(self): @@ -69,12 +68,11 @@ class TestCase(unittest.TestCase): (2.1,1), (2.2,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 3 res = Quantize.FindVarQuantBound(varValues,resCodes,nPossibleRes) target = (1.3,0.88129) - assert map(lambda x,y:Quantize.feq(x,y,1e-4),res,target)==[1,1],\ + assert list(map(lambda x,y:Quantize.feq(x,y,1e-4),res,target))==[1,1],\ 'result comparison failed: %s != %s'%(res,target) def testOneSplit4(self): @@ -94,12 +92,11 @@ class TestCase(unittest.TestCase): (2.1,1), (2.2,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarQuantBound(varValues,resCodes,nPossibleRes) target = (1.8,0.68939) - assert map(lambda x,y:Quantize.feq(x,y,1e-4),res,target)==[1,1],\ + assert list(map(lambda x,y:Quantize.feq(x,y,1e-4),res,target))==[1,1],\ 'result comparison failed: %s != %s'%(res,target) def testOneSplit5(self): @@ -115,12 +112,11 @@ class TestCase(unittest.TestCase): (2.1,1), (1.4,0), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarQuantBound(varValues,resCodes,nPossibleRes) target = (1.8,0.97095) - assert map(lambda x,y:Quantize.feq(x,y,1e-4),res,target)==[1,1],\ + assert list(map(lambda x,y:Quantize.feq(x,y,1e-4),res,target))==[1,1],\ 'result comparison failed: %s != %s'%(res,target) def testMultSplit1(self): @@ -138,8 +134,7 @@ class TestCase(unittest.TestCase): (2.1,1), (2.2,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes =3 res = Quantize.FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) target = ([1.3, 2.05],1.55458) @@ -163,8 +158,7 @@ class TestCase(unittest.TestCase): (2.2,1), (2.1,1), (2.3,1)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes =3 res = Quantize.FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) target = ([1.3, 2.05],1.55458) @@ -191,8 +185,7 @@ class TestCase(unittest.TestCase): (3.1,3), (3.2,3), (3.3,3)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes =4 res = Quantize.FindVarMultQuantBounds(varValues,3,resCodes,nPossibleRes) target = ([1.30, 2.05, 2.65],1.97722) @@ -200,6 +193,7 @@ class TestCase(unittest.TestCase): 'InfoGain comparison failed: %s != %s'%(res[1],target[1]) assert min(map(lambda x,y:Quantize.feq(x,y,1e-4),res[0],target[0]))==1,\ 'split bound comparison failed: %s != %s'%(res[0],target[0]) + def testMultSplit4(self): """ dual valued, with an island """ @@ -215,8 +209,7 @@ class TestCase(unittest.TestCase): (2.1,0), (2.2,0), (2.3,0)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) target = ( [1.3, 2.05], .91830) @@ -224,6 +217,7 @@ class TestCase(unittest.TestCase): 'InfoGain comparison failed: %s != %s'%(res[1],target[1]) assert min(map(lambda x,y:Quantize.feq(x,y,1e-4),res[0],target[0]))==1,\ 'split bound comparison failed: %s != %s'%(res[0],target[0]) + def testMultSplit5(self): """ dual valued, with an island, a bit noisy """ @@ -239,8 +233,7 @@ class TestCase(unittest.TestCase): (2.1,0), (2.2,1), (2.3,0)] - varValues = map(lambda x:x[0],d) - resCodes = map(lambda x:x[1],d) + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize.FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) target = ([1.3, 2.05],.34707 ) @@ -249,7 +242,6 @@ class TestCase(unittest.TestCase): assert min(map(lambda x,y:Quantize.feq(x,y,1e-4),res[0],target[0]))==1,\ 'split bound comparison failed: %s != %s'%(res[0],target[0]) - def test9NewSplits(self): """ """ @@ -257,25 +249,23 @@ class TestCase(unittest.TestCase): (1,1), (2,0), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,2],str(res)) + self.assertTrue(res==[1,2],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,2],str(res)) + self.assertTrue(res==[1,2],str(res)) d = [ (0,1), (1,0), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,2],str(res)) + self.assertTrue(res==[1,2],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,2],str(res)) + self.assertTrue(res==[1,2],str(res)) d = [ (0,0), @@ -285,13 +275,12 @@ class TestCase(unittest.TestCase): (2,0), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) d = [ (0,0), (0,1), @@ -300,13 +289,12 @@ class TestCase(unittest.TestCase): (2,0), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) d = [ (0,0), (0,0), @@ -315,13 +303,12 @@ class TestCase(unittest.TestCase): (2,0), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) d = [ (0,0), (0,0), @@ -330,13 +317,12 @@ class TestCase(unittest.TestCase): (2,1), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[4],str(res)) + self.assertTrue(res==[4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[4],str(res)) + self.assertTrue(res==[4],str(res)) d = [ (0,0), (0,0), @@ -345,13 +331,12 @@ class TestCase(unittest.TestCase): (2,1), (2,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2],str(res)) + self.assertTrue(res==[2],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2],str(res)) + self.assertTrue(res==[2],str(res)) d = [ (0,0), (0,0), @@ -360,13 +345,12 @@ class TestCase(unittest.TestCase): (2,0), (2,0), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[],str(res)) + self.assertTrue(res==[],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[],str(res)) + self.assertTrue(res==[],str(res)) d = [ (0,0), (0,1), @@ -375,13 +359,12 @@ class TestCase(unittest.TestCase): (2,0), (2,0), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[2,4],str(res)) + self.assertTrue(res==[2,4],str(res)) d = [ (1,0), (2,1), @@ -393,13 +376,12 @@ class TestCase(unittest.TestCase): (4,1), (4,1), ] - varValues = [x[0] for x in d] - resCodes = [x[1] for x in d] + varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,6],str(res)) + self.assertTrue(res==[1,6],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,6],str(res)) + self.assertTrue(res==[1,6],str(res)) d=[(1, 1.65175902843, 0), @@ -416,13 +398,12 @@ class TestCase(unittest.TestCase): (12, 3.53454303741, 1), (13, 3.53454303741, 1)] - varValues = [x[1] for x in d] - resCodes = [x[2] for x in d] + _, varValues, resCodes = zip(*d) nPossibleRes = 2 res = Quantize._NewPyFindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,4],str(res)) + self.assertTrue(res==[1,4],str(res)) res = Quantize._FindStartPoints(varValues,resCodes,len(d)) - self.failUnless(res==[1,4],str(res)) + self.assertTrue(res==[1,4],str(res)) def testGithubIssue18(self): d = [0,1,2,3,4] @@ -430,8 +411,8 @@ class TestCase(unittest.TestCase): tpl = Quantize.FindVarMultQuantBounds(d,1,a,2) d2 = [(x,) for x in d] - self.failUnlessRaises(ValueError,lambda :Quantize.FindVarMultQuantBounds(d2,1,a,2)) - self.failUnlessRaises(ValueError,lambda :Quantize._FindStartPoints(d2,a,len(d2))) + self.assertRaises(ValueError,lambda :Quantize.FindVarMultQuantBounds(d2,1,a,2)) + self.assertRaises(ValueError,lambda :Quantize._FindStartPoints(d2,a,len(d2))) diff --git a/rdkit/ML/DecTree/BuildQuantTree.py b/rdkit/ML/DecTree/BuildQuantTree.py index 770d4e375..9e180c47d 100755 --- a/rdkit/ML/DecTree/BuildQuantTree.py +++ b/rdkit/ML/DecTree/BuildQuantTree.py @@ -8,12 +8,13 @@ """ """ - +from __future__ import print_function import numpy import random from rdkit.ML.DecTree import QuantTree, ID3 from rdkit.ML.InfoTheory import entropy from rdkit.ML.Data import Quantize +from rdkit.six.moves import range def FindBest(resCodes,examples,nBoundsPerVar,nPossibleRes, nPossibleVals,attrs,exIndices=None,**kwargs): @@ -22,7 +23,7 @@ def FindBest(resCodes,examples,nBoundsPerVar,nPossibleRes, bestBounds = [] if exIndices is None: - exIndices=range(len(examples)) + exIndices=list(range(len(examples))) if not len(exIndices): return best,bestGain,bestBounds @@ -31,10 +32,10 @@ def FindBest(resCodes,examples,nBoundsPerVar,nPossibleRes, if nToTake > 0: nAttrs = len(attrs) if nToTake < nAttrs: - ids = range(nAttrs) + ids = list(range(nAttrs)) random.shuffle(ids) tmp = [attrs[x] for x in ids[:nToTake]] - #print '\tavail:',tmp + #print('\tavail:',tmp) attrs = tmp for var in attrs: @@ -44,11 +45,11 @@ def FindBest(resCodes,examples,nBoundsPerVar,nPossibleRes, try: vTable = [examples[x][var] for x in exIndices] except IndexError: - print 'index error retrieving variable: %d'%var + print('index error retrieving variable: %d'%var) raise qBounds,gainHere = Quantize.FindVarMultQuantBounds(vTable,nBounds, resCodes,nPossibleRes) - #print '\tvar:',var,qBounds,gainHere + #print('\tvar:',var,qBounds,gainHere) elif nBounds==0: vTable = ID3.GenVarTable((examples[x] for x in exIndices), nPossibleVals,[var])[0] @@ -66,25 +67,25 @@ def FindBest(resCodes,examples,nBoundsPerVar,nPossibleRes, best = var bestBounds = qBounds if best == -1: - print 'best unaltered' - print '\tattrs:',attrs - print '\tnBounds:',take(nBoundsPerVar,attrs) - print '\texamples:' + print('best unaltered') + print('\tattrs:',attrs) + print('\tnBounds:',take(nBoundsPerVar,attrs)) + print('\texamples:') for example in (examples[x] for x in exIndices): - print '\t\t',example + print('\t\t',example) if 0: - print 'BEST:',len(exIndices),best,bestGain,bestBounds + print('BEST:',len(exIndices),best,bestGain,bestBounds) if(len(exIndices)<10): - print len(exIndices),len(resCodes),len(examples) + print(len(exIndices),len(resCodes),len(examples)) exs = [examples[x] for x in exIndices] vals = [x[best] for x in exs] sortIdx = numpy.argsort(vals) sortVals = [exs[x] for x in sortIdx] sortResults = [resCodes[x] for x in sortIdx] for i in range(len(vals)): - print ' ',i,['%.4f'%x for x in sortVals[i][1:-1]],sortResults[i] + print(' ',i,['%.4f'%x for x in sortVals[i][1:-1]],sortResults[i]) return best,bestGain,bestBounds @@ -121,7 +122,7 @@ def BuildQuantTree(examples,target,attrs,nPossibleVals,nBoundsPerVar, nPossibleRes = nPossibleVals[-1] if exIndices is None: - exIndices=range(len(examples)) + exIndices=list(range(len(examples))) # counts of each result code: resCodes = [int(x[-1]) for x in (examples[y] for y in exIndices)] @@ -206,7 +207,7 @@ def BuildQuantTree(examples,target,attrs,nPossibleVals,nBoundsPerVar, exIndices=nextExamples, **kwargs)) else: - for val in xrange(nPossibleVals[best]): + for val in range(nPossibleVals[best]): nextExamples = [] for idx in exIndices: if examples[idx][best] == val: @@ -233,7 +234,7 @@ def QuantTreeBoot(examples,attrs,nPossibleVals,nBoundsPerVar,initialVar=None, split. """ - attrs = attrs[:] + attrs = list(attrs) for i in range(len(nBoundsPerVar)): if nBoundsPerVar[i]==-1 and i in attrs: attrs.remove(i) @@ -269,15 +270,15 @@ def QuantTreeBoot(examples,attrs,nPossibleVals,nBoundsPerVar,initialVar=None, tree.SetLabel(best) tree.SetTerminal(0) tree.SetQuantBounds(qBounds) - nextAttrs = attrs[:] + nextAttrs = list(attrs) if not kwargs.get('recycleVars',0): nextAttrs.remove(best) - indices = range(len(examples)) + indices = list(range(len(examples))) if len(qBounds) > 0: for bound in qBounds: nextExamples = [] - for index in indices[:]: + for index in list(indices): ex = examples[index] if ex[best] < bound: nextExamples.append(ex) @@ -306,7 +307,7 @@ def QuantTreeBoot(examples,attrs,nPossibleVals,nBoundsPerVar,initialVar=None, v = numpy.argmax(counts) tree.AddChild('%d??'%(v),label=v,data=0.0,isTerminal=1) else: - for val in xrange(nPossibleVals[best]): + for val in range(nPossibleVals[best]): nextExamples = [] for example in examples: if example[best] == val: @@ -336,7 +337,7 @@ def TestTree(): ['p7',1,1,0,2], ['p8',1,1,1,0] ] - attrs = range(1,len(examples1[0])-1) + attrs = list(range(1,len(examples1[0])-1)) nPossibleVals = [0,2,2,2,3] t1 = ID3.ID3Boot(examples1,attrs,nPossibleVals,maxDepth=1) t1.Print() @@ -355,16 +356,16 @@ def TestQuantTree(): ['p7',1,1,0.1,2], ['p8',1,1,1.1,0] ] - attrs = range(1,len(examples1[0])-1) + attrs = list(range(1,len(examples1[0])-1)) nPossibleVals = [0,2,2,0,3] boundsPerVar=[0,0,0,1,0] - print 'base' + print('base') t1 = QuantTreeBoot(examples1,attrs,nPossibleVals,boundsPerVar) t1.Pickle('test_data/QuantTree1.pkl') t1.Print() - print 'depth limit' + print('depth limit') t1 = QuantTreeBoot(examples1,attrs,nPossibleVals,boundsPerVar,maxDepth=1) t1.Pickle('test_data/QuantTree1.pkl') t1.Print() @@ -382,7 +383,7 @@ def TestQuantTree2(): ['p7',1.1,1,0.1,2], ['p8',1.1,1,1.1,0] ] - attrs = range(1,len(examples1[0])-1) + attrs = list(range(1,len(examples1[0])-1)) nPossibleVals = [0,0,2,0,3] boundsPerVar=[0,1,0,1,0] @@ -391,8 +392,8 @@ def TestQuantTree2(): t1.Pickle('test_data/QuantTree2.pkl') for example in examples1: - print example,t1.ClassifyExample(example) - + print(example,t1.ClassifyExample(example)) + if __name__ == "__main__": TestTree() TestQuantTree() diff --git a/rdkit/ML/DecTree/BuildSigTree.py b/rdkit/ML/DecTree/BuildSigTree.py index 1916d9c72..fa02ebb0d 100755 --- a/rdkit/ML/DecTree/BuildSigTree.py +++ b/rdkit/ML/DecTree/BuildSigTree.py @@ -8,7 +8,7 @@ """ """ - +from __future__ import print_function import numpy from rdkit.ML.DecTree import SigTree from rdkit.ML import InfoTheory @@ -99,7 +99,7 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, a SigTree.SigTreeNode with the root of the decision tree """ - if verbose: print ' '*depth,'Build' + if verbose: print(' '*depth,'Build') tree=SigTree.SigTreeNode(None,'node',level=depth) tree.SetData(-666) #tree.SetExamples(examples) @@ -107,14 +107,14 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, # counts of each result code: #resCodes = map(lambda x:int(x[-1]),examples) resCodes = [int(x[-1]) for x in examples] - #print 'resCodes:',resCodes + #print('resCodes:',resCodes) counts = [0]*nPossibleRes for res in resCodes: counts[res] += 1 - #print ' '*depth,'counts:',counts + #print(' '*depth,'counts:',counts) nzCounts = numpy.nonzero(counts)[0] - if verbose: print ' '*depth,'\tcounts:',counts + if verbose: print(' '*depth,'\tcounts:',counts) if len(nzCounts) == 1: # bottomed out because there is only one result code left # with any counts (i.e. there's only one type of example @@ -154,11 +154,11 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, availBits=None if availBits: ranker.SetMaskBits(availBits) - #print ' 2:'*depth,availBits + #print(' 2:'*depth,availBits) useCollections=isinstance(examples[0][1],VectCollection) for example in examples: - #print ' '*depth,example[1].ToBitString(),example[-1] + #print(' '*depth,example[1].ToBitString(),example[-1]) if not useCollections: ranker.AccumulateVotes(example[1],example[-1]) else: @@ -172,7 +172,7 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, except: import traceback traceback.print_exc() - print 'get top n failed' + print('get top n failed') gain = -1.0 if gain <= 0.0: v = numpy.argmax(counts) @@ -181,8 +181,8 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, tree.SetTerminal(1) return tree best = int(bitInfo[0]) - #print ' '*depth,'\tbest:',bitInfo - if verbose: print ' '*depth,'\tbest:',bitInfo + #print(' '*depth,'\tbest:',bitInfo) + if verbose: print(' '*depth,'\tbest:',bitInfo) # set some info at this node tree.SetName('Bit-%d'%(best)) tree.SetLabel(best) @@ -205,7 +205,7 @@ def BuildSigTree(examples,nPossibleRes,ensemble=None,random=0, onExamples.append(example) else: offExamples.append(example) - #print ' '*depth,len(offExamples),len(onExamples) + #print(' '*depth,len(offExamples),len(onExamples)) for ex in (offExamples,onExamples): if len(ex) == 0: v = numpy.argmax(counts) diff --git a/rdkit/ML/DecTree/CrossValidate.py b/rdkit/ML/DecTree/CrossValidate.py index 69483f9b8..769b2afde 100755 --- a/rdkit/ML/DecTree/CrossValidate.py +++ b/rdkit/ML/DecTree/CrossValidate.py @@ -8,10 +8,12 @@ cross validation == evaluating the accuracy of a tree. """ +from __future__ import print_function from rdkit.ML.DecTree import ID3 from rdkit.ML.Data import SplitData import numpy from rdkit import RDRandom +from rdkit.six.moves import xrange def ChooseOptimalRoot(examples,trainExamples,testExamples,attrs, nPossibleVals,treeBuilder,nQuantBounds=[], @@ -174,7 +176,7 @@ def CrossValidationDriver(examples,attrs,nPossibleVals,holdOutFrac=.3,silent=0, nTrain = len(trainExamples) if not silent: - print 'Training with %d examples'%(nTrain) + print('Training with %d examples'%(nTrain)) if not lessGreedy: if nQuantBounds is None or nQuantBounds == []: @@ -190,13 +192,13 @@ def CrossValidationDriver(examples,attrs,nPossibleVals,holdOutFrac=.3,silent=0, nTest = len(testExamples) if not silent: - print 'Testing with %d examples'%nTest + print('Testing with %d examples'%nTest) if not calcTotalError: xValError,badExamples = CrossValidate(tree,testExamples,appendExamples=1) else: xValError,badExamples = CrossValidate(tree,examples,appendExamples=0) if not silent: - print 'Validation error was %%%4.2f'%(100*xValError) + print('Validation error was %%%4.2f'%(100*xValError)) tree.SetBadExamples(badExamples) tree.SetTrainingExamples(trainExamples) tree.SetTestExamples(testExamples) @@ -217,9 +219,9 @@ def TestRun(): import copy t2 = copy.deepcopy(tree) - print 't1 == t2',tree==t2 + print('t1 == t2',tree==t2) l = [tree] - print 't2 in [tree]', t2 in l, l.index(t2) + print('t2 in [tree]', t2 in l, l.index(t2)) if __name__ == '__main__': TestRun() diff --git a/rdkit/ML/DecTree/DecTree.py b/rdkit/ML/DecTree/DecTree.py index 43b266bdf..a50c13f1d 100755 --- a/rdkit/ML/DecTree/DecTree.py +++ b/rdkit/ML/DecTree/DecTree.py @@ -28,7 +28,8 @@ class DecTreeNode(Tree.TreeNode): """ def __init__(self,*args,**kwargs): - apply(Tree.TreeNode.__init__,(self,)+args,kwargs) + #apply(Tree.TreeNode.__init__,(self,)+args,kwargs) + Tree.TreeNode.__init__(self, *args, **kwargs) self.examples = [] self.badExamples = [] self.trainingExamples = [] diff --git a/rdkit/ML/DecTree/ID3.py b/rdkit/ML/DecTree/ID3.py index d1fe446fb..181052173 100755 --- a/rdkit/ML/DecTree/ID3.py +++ b/rdkit/ML/DecTree/ID3.py @@ -14,6 +14,7 @@ import numpy from rdkit.ML.DecTree import DecTree from rdkit.ML.InfoTheory import entropy +from rdkit.six.moves import range, xrange def CalcTotalEntropy(examples,nPossibleVals): """ Calculates the total entropy of the data set (w.r.t. the results) @@ -203,7 +204,7 @@ def ID3Boot(examples,attrs,nPossibleVals,initialVar=None,depth=0,maxDepth=-1, tree.SetData(totEntropy) tree.SetLabel(best) tree.SetTerminal(0) - nextAttrs = attrs[:] + nextAttrs = list(attrs) if not kwargs.get('recycleVars',0): nextAttrs.remove(best) diff --git a/rdkit/ML/DecTree/PruneTree.py b/rdkit/ML/DecTree/PruneTree.py index b5a1f824a..d3bc99e60 100755 --- a/rdkit/ML/DecTree/PruneTree.py +++ b/rdkit/ML/DecTree/PruneTree.py @@ -4,9 +4,11 @@ """ Contains functionality for doing tree pruning """ +from __future__ import print_function import numpy -from rdkit.ML.DecTree import CrossValidate, DecTree import copy +from rdkit.ML.DecTree import CrossValidate, DecTree +from rdkit.six.moves import range _verbose = 0 @@ -25,7 +27,7 @@ def MaxCount(examples): resList = [x[-1] for x in examples] maxVal = max(resList) counts = [None]*(maxVal+1) - for i in xrange(maxVal+1): + for i in range(maxVal+1): counts[i] = sum([x==i for x in resList]) return numpy.argmax(counts) @@ -36,7 +38,7 @@ def _GetLocalError(node): pred = node.ClassifyExample(example,appendExamples=0) if pred != example[-1]: nWrong +=1 - #if _verbose: print '------------------>MISS:',example,pred + #if _verbose: print('------------------>MISS:',example,pred) return nWrong def _Pruner(node,level=0): @@ -64,7 +66,7 @@ def _Pruner(node,level=0): favor smaller trees. """ - if _verbose: print ' '*level,'<%d> '%level,'>>> Pruner' + if _verbose: print(' '*level,'<%d> '%level,'>>> Pruner') children = node.GetChildren()[:] bestTree = copy.deepcopy(node) @@ -79,13 +81,13 @@ def _Pruner(node,level=0): child = children[i] examples = child.GetExamples() if _verbose: - print ' '*level,'<%d> '%level,' Child:',i,child.GetLabel() + print(' '*level,'<%d> '%level,' Child:',i,child.GetLabel()) bestTree.Print() - print + print() if len(examples): - if _verbose: print ' '*level,'<%d> '%level,' Examples',len(examples) + if _verbose: print(' '*level,'<%d> '%level,' Examples',len(examples)) if not child.GetTerminal(): - if _verbose: print ' '*level,'<%d> '%level,' Nonterminal' + if _verbose: print(' '*level,'<%d> '%level,' Nonterminal') workTree = copy.deepcopy(bestTree) # @@ -98,12 +100,12 @@ def _Pruner(node,level=0): bestErr = tempErr bestTree = copy.deepcopy(workTree) if _verbose: - print ' '*level,'<%d> '%level,'>->->->->->' - print ' '*level,'<%d> '%level,'replacing:',i,child.GetLabel() + print(' '*level,'<%d> '%level,'>->->->->->') + print(' '*level,'<%d> '%level,'replacing:',i,child.GetLabel()) child.Print() - print ' '*level,'<%d> '%level,'with:' + print(' '*level,'<%d> '%level,'with:') newNode.Print() - print ' '*level,'<%d> '%level,'<-<-<-<-<-<' + print(' '*level,'<%d> '%level,'<-<-<-<-<-<') else: workTree.ReplaceChildIndex(i,child) # @@ -115,24 +117,24 @@ def _Pruner(node,level=0): newNode.SetExamples(child.GetExamples()) workTree.ReplaceChildIndex(i,newNode) if _verbose: - print ' '*level,'<%d> '%level,'ATTEMPT:' + print(' '*level,'<%d> '%level,'ATTEMPT:') workTree.Print() newErr = _GetLocalError(workTree) - if _verbose: print ' '*level,'<%d> '%level,'---> ',newErr,bestErr + if _verbose: print(' '*level,'<%d> '%level,'---> ',newErr,bestErr) if newErr <= bestErr: bestErr = newErr bestTree = copy.deepcopy(workTree) if _verbose: - print ' '*level,'<%d> '%level,'PRUNING:' + print(' '*level,'<%d> '%level,'PRUNING:') workTree.Print() else: - if _verbose: print ' '*level,'<%d> '%level,'FAIL' + if _verbose: print(' '*level,'<%d> '%level,'FAIL') # whoops... put the child back in: workTree.ReplaceChildIndex(i,child) else: - if _verbose: print ' '*level,'<%d> '%level,' Terminal' + if _verbose: print(' '*level,'<%d> '%level,' Terminal') else: - if _verbose: print ' '*level,'<%d> '%level,' No Examples',len(examples) + if _verbose: print(' '*level,'<%d> '%level,' No Examples',len(examples)) # # FIX: we need to figure out what to do here (nodes that contain # no examples in the testing set). I can concoct arguments for @@ -141,7 +143,7 @@ def _Pruner(node,level=0): # pass - if _verbose: print ' '*level,'<%d> '%level,'<<< out' + if _verbose: print(' '*level,'<%d> '%level,'<<< out') return bestTree def PruneTree(tree,trainExamples,testExamples,minimizeTestErrorOnly=1): @@ -212,12 +214,12 @@ def _testRandom(): tree,frac = CrossValidate.CrossValidationDriver(examples,attrs,nPossibleVals) tree.Print() tree.Pickle('orig.pkl') - print 'original error is:', frac + print('original error is:', frac) - print '----Pruning' + print('----Pruning') newTree,frac2 = PruneTree(tree,tree.GetTrainingExamples(),tree.GetTestExamples()) newTree.Print() - print 'pruned error is:',frac2 + print('pruned error is:',frac2) newTree.Pickle('prune.pkl') @@ -235,18 +237,18 @@ def _testSpecific(): tree = ID3.ID3Boot(oPts,attrs=range(3),nPossibleVals=[2]*4) tree.Print() err,badEx = CrossValidate.CrossValidate(tree,oPts) - print 'original error:',err + print('original error:',err) err,badEx = CrossValidate.CrossValidate(tree,tPts) - print 'original holdout error:',err + print('original holdout error:',err) newTree,frac2 = PruneTree(tree,oPts,tPts) newTree.Print() err,badEx = CrossValidate.CrossValidate(newTree,tPts) - print 'pruned holdout error is:',err - print badEx + print('pruned holdout error is:',err) + print(badEx) - print len(tree),len(newTree) + print(len(tree),len(newTree)) def _testChain(): from rdkit.ML.DecTree import ID3 @@ -270,16 +272,16 @@ def _testChain(): tree = ID3.ID3Boot(oPts,attrs=range(len(oPts[0])-1),nPossibleVals=[2]*len(oPts[0])) tree.Print() err,badEx = CrossValidate.CrossValidate(tree,oPts) - print 'original error:',err + print('original error:',err) err,badEx = CrossValidate.CrossValidate(tree,tPts) - print 'original holdout error:',err + print('original holdout error:',err) newTree,frac2 = PruneTree(tree,oPts,tPts) newTree.Print() err,badEx = CrossValidate.CrossValidate(newTree,tPts) - print 'pruned holdout error is:',err - print badEx + print('pruned holdout error is:',err) + print(badEx) if __name__ == '__main__': diff --git a/rdkit/ML/DecTree/QuantTree.py b/rdkit/ML/DecTree/QuantTree.py index c6c131bf7..5a816ebec 100755 --- a/rdkit/ML/DecTree/QuantTree.py +++ b/rdkit/ML/DecTree/QuantTree.py @@ -16,7 +16,7 @@ class QuantTreeNode(DecTree.DecTreeNode): """ def __init__(self,*args,**kwargs): - apply(DecTree.DecTreeNode.__init__,(self,)+args,kwargs) + DecTree.DecTreeNode.__init__(self,*args,**kwargs) self.qBounds = [] self.nBounds = 0 def ClassifyExample(self,example,appendExamples=0): diff --git a/rdkit/ML/DecTree/SigTree.py b/rdkit/ML/DecTree/SigTree.py index 06dffdf5c..fa8ef6029 100755 --- a/rdkit/ML/DecTree/SigTree.py +++ b/rdkit/ML/DecTree/SigTree.py @@ -57,4 +57,4 @@ class SigTreeNode(DecTree.DecTreeNode): return self.children[val].ClassifyExample(example,appendExamples=appendExamples) def __init__(self,*args,**kwargs): - apply(DecTree.DecTreeNode.__init__,(self,)+args,kwargs) + DecTree.DecTreeNode.__init__(self,*args,**kwargs) diff --git a/rdkit/ML/DecTree/Tree.py b/rdkit/ML/DecTree/Tree.py index 2c22decce..6c7589a5c 100755 --- a/rdkit/ML/DecTree/Tree.py +++ b/rdkit/ML/DecTree/Tree.py @@ -4,8 +4,9 @@ """ Implements a class used to represent N-ary trees """ -import cPickle +from __future__ import print_function import numpy +from rdkit.six.moves import cPickle # FIX: the TreeNode class has not been updated to new-style classes # (RD Issue380) because that would break all of our legacy pickled @@ -225,9 +226,9 @@ class TreeNode: """ if showData: - print '%s%s: %s'%(' '*level,self.name,str(self.data)) + print('%s%s: %s'%(' '*level,self.name,str(self.data))) else: - print '%s%s'%(' '*level,self.name) + print('%s%s'%(' '*level,self.name)) for child in self.children: child.Print(level+1,showData=showData) @@ -236,8 +237,8 @@ class TreeNode: """ Pickles the tree and writes it to disk """ - pFile = open(fileName,'w+') - cPickle.dump(self,pFile) + with open(fileName,'w+') as pFile: + cPickle.dump(self,pFile) def __str__(self): """ returns a string representation of the tree @@ -286,27 +287,27 @@ if __name__ == '__main__': tree = TreeNode(None,'root') for i in xrange(3): child = tree.AddChild('child %d'%i) - print tree + print(tree) tree.GetChildren()[1].AddChild('grandchild') tree.GetChildren()[1].AddChild('grandchild2') tree.GetChildren()[1].AddChild('grandchild3') - print tree + print(tree) tree.Pickle('save.pkl') - print 'prune' + print('prune') tree.PruneChild(tree.GetChildren()[1]) - print 'done' - print tree + print('done') + print(tree) import copy tree2 = copy.deepcopy(tree) - print 'tree==tree2', tree==tree2 + print('tree==tree2', tree==tree2) foo = [tree] - print 'tree in [tree]:', tree in foo,foo.index(tree) - print 'tree2 in [tree]:', tree2 in foo, foo.index(tree2) + print('tree in [tree]:', tree in foo,foo.index(tree)) + print('tree2 in [tree]:', tree2 in foo, foo.index(tree2)) tree2.GetChildren()[1].AddChild('grandchild4') - print 'tree==tree2', tree==tree2 + print('tree==tree2', tree==tree2) tree.Destroy() diff --git a/rdkit/ML/DecTree/TreeUtils.py b/rdkit/ML/DecTree/TreeUtils.py index fcff62b5e..2eb68bbad 100755 --- a/rdkit/ML/DecTree/TreeUtils.py +++ b/rdkit/ML/DecTree/TreeUtils.py @@ -56,18 +56,18 @@ _test1=""" 0 >>> r[3] 1 ->>> r.has_key(4) +>>> 4 in r 0 Check that we can handle subtrees: >>> r = CollectLabelLevels(t1,{},1,2) >>> r[1] 1 ->>> r.has_key(2) +>>> 2 in r 0 ->>> r.has_key(3) +>>> 3 in r 0 ->>> r.has_key(4) +>>> 4 in r 0 >>> names = CollectDescriptorNames(t1,{}) @@ -87,17 +87,17 @@ Check that we can handle subtrees: 'd2' >>> names[3] 'd3' ->>> names.has_key(4) +>>> 4 in names 0 >>> names = CollectDescriptorNames(t1,{},1,2) >>> names[1] 'd1' ->>> names.has_key(2) +>>> 2 in names 0 ->>> names.has_key(3) +>>> 3 in names 0 ->>> names.has_key(4) +>>> 4 in names 0 diff --git a/rdkit/ML/DecTree/UnitTestID3.py b/rdkit/ML/DecTree/UnitTestID3.py index ce7300661..fa6f39760 100755 --- a/rdkit/ML/DecTree/UnitTestID3.py +++ b/rdkit/ML/DecTree/UnitTestID3.py @@ -3,15 +3,16 @@ # """ unit tests for the ID3 implementation """ -from rdkit import RDConfig +from __future__ import print_function import unittest +from rdkit.six.moves import cPickle +from rdkit import RDConfig from rdkit.ML.DecTree import ID3,DecTree -import cPickle from rdkit.ML.Data import MLData class ID3TestCase(unittest.TestCase): def setUp(self): - print '\n%s: '%self.shortDescription(), + print('\n%s: '%self.shortDescription(),end='') self.basicTreeName=RDConfig.RDCodeDir+'/ML/DecTree/test_data/BasicTree.pkl' self.multiTreeName=RDConfig.RDCodeDir+'/ML/DecTree/test_data/MultiTree.pkl' def _setupBasicTree(self): diff --git a/rdkit/ML/DecTree/UnitTestPrune.py b/rdkit/ML/DecTree/UnitTestPrune.py index 21e1b808c..708df55ce 100755 --- a/rdkit/ML/DecTree/UnitTestPrune.py +++ b/rdkit/ML/DecTree/UnitTestPrune.py @@ -3,11 +3,11 @@ # """ """ -from rdkit import RDConfig import unittest -from rdkit.ML.DecTree import ID3,PruneTree,CrossValidate import copy -import cPickle +from rdkit import RDConfig +from rdkit.ML.DecTree import ID3,PruneTree,CrossValidate +from rdkit.six.moves import cPickle def feq(a,b,tol=1e-4): return abs(a-b)<=tol diff --git a/rdkit/ML/DecTree/UnitTestQuantTree.py b/rdkit/ML/DecTree/UnitTestQuantTree.py index 6cd508fa8..3c54ef9b2 100755 --- a/rdkit/ML/DecTree/UnitTestQuantTree.py +++ b/rdkit/ML/DecTree/UnitTestQuantTree.py @@ -5,17 +5,17 @@ # """ unit tests for the QuantTree implementation """ -from rdkit import RDConfig +from __future__ import print_function import unittest +from rdkit import RDConfig from rdkit.ML.DecTree import BuildQuantTree from rdkit.ML.DecTree.QuantTree import QuantTreeNode - -import cPickle from rdkit.ML.Data import MLData +from rdkit.six.moves import cPickle, xrange class TestCase(unittest.TestCase): def setUp(self): - print '\n%s: '%self.shortDescription(), + print('\n%s: '%self.shortDescription(),end='') self.qTree1Name=RDConfig.RDCodeDir+'/ML/DecTree/test_data/QuantTree1.pkl' self.qTree2Name=RDConfig.RDCodeDir+'/ML/DecTree/test_data/QuantTree2.pkl' @@ -153,9 +153,11 @@ class TestCase(unittest.TestCase): def testBug29_2(self): """ a more extensive test of the cmp stuff using pickled trees""" - import cPickle,os - t1 = cPickle.load(open(os.path.join(RDConfig.RDCodeDir,'ML','DecTree','test_data','CmpTree1.pkl'),'rb')) - t2 = cPickle.load(open(os.path.join(RDConfig.RDCodeDir,'ML','DecTree','test_data','CmpTree2.pkl'),'rb')) + import os + with open(os.path.join(RDConfig.RDCodeDir,'ML','DecTree','test_data','CmpTree1.pkl'),'rb') as t1File: + t1 = cPickle.load(t1File) + with open(os.path.join(RDConfig.RDCodeDir,'ML','DecTree','test_data','CmpTree2.pkl'),'rb') as t2File: + t2 = cPickle.load(t2File) assert cmp(t1,t2),'equality failed' diff --git a/rdkit/ML/DecTree/UnitTestSigTree.py b/rdkit/ML/DecTree/UnitTestSigTree.py index 2140bdd72..1b1a19a6f 100644 --- a/rdkit/ML/DecTree/UnitTestSigTree.py +++ b/rdkit/ML/DecTree/UnitTestSigTree.py @@ -139,7 +139,8 @@ class TestCase(unittest.TestCase): def test4(self): - import gzip,cPickle + import gzip + from rdkit.six.moves import cPickle from BuildSigTree import BuildSigTree gz = gzip.open(os.path.join(RDConfig.RDCodeDir,'ML','DecTree','test_data', 'cdk2-few.pkl.gz'), diff --git a/rdkit/ML/DecTree/UnitTestTree.py b/rdkit/ML/DecTree/UnitTestTree.py index 9298896dd..c24c70e5d 100755 --- a/rdkit/ML/DecTree/UnitTestTree.py +++ b/rdkit/ML/DecTree/UnitTestTree.py @@ -3,16 +3,17 @@ # """ unit testing code for trees and decision trees (not learning/xvalidation) """ -from rdkit import RDConfig +from __future__ import print_function import unittest -from rdkit.ML.DecTree import Tree,DecTree import copy -import cPickle +from rdkit import RDConfig +from rdkit.ML.DecTree import Tree,DecTree +from rdkit.six.moves import cPickle class TreeTestCase(unittest.TestCase): def setUp(self): - print '\n%s: '%self.shortDescription(), + print('\n%s: '%self.shortDescription(),end='') self.baseTree = Tree.TreeNode(None,'root') self.pickleFileName = RDConfig.RDCodeDir+'/ML/DecTree/test_data/treeunit.pkl' diff --git a/rdkit/ML/DecTree/UnitTestXVal.py b/rdkit/ML/DecTree/UnitTestXVal.py index 6901c7551..8eea1f493 100755 --- a/rdkit/ML/DecTree/UnitTestXVal.py +++ b/rdkit/ML/DecTree/UnitTestXVal.py @@ -3,17 +3,17 @@ # """ unit testing code for cross validation """ +from __future__ import print_function +import unittest, random from rdkit import RDConfig -import unittest from rdkit.ML.DecTree import CrossValidate -import random def feq(a,b,tol=1e-4): return abs(a-b) j) : - id = (i*(i-1)/2) + j + id = (i*(i-1)//2) + j return mat[id] elif (j > i) : - id = (j*(j-1)/2) + i + id = (j*(j-1)//2) + i return mat[id] else : return 0.0 @@ -37,17 +38,17 @@ class TestCase(unittest.TestCase): self.d = 40 self.nfp = 1000 - self.blist = range(self.nbits) + self.blist = list(range(self.nbits)) self.fps = [] for fi in range(self.nfp) : fp = DataStructs.ExplicitBitVect(self.nbits) - obits = range(self.nbits/2) + obits = list(range(self.nbits//2)) random.shuffle(obits) obits = obits[0:self.d] for bit in obits : fp.SetBit(bit) - fp.SetBit(bit + self.nbits/2) + fp.SetBit(bit + self.nbits//2) self.fps.append(fp) def test0CorrMat(self) : @@ -60,8 +61,8 @@ class TestCase(unittest.TestCase): avr = 0.0 navr = 0.0 - for i in range(self.nbits/2) : - avr += getValLTM(i, i + self.nbits/2, corrMat) + for i in range(self.nbits//2) : + avr += getValLTM(i, i + self.nbits//2, corrMat) navr += getValLTM(i,i+1, corrMat) assert 2*avr/self.nbits == 400.0 @@ -77,28 +78,28 @@ class TestCase(unittest.TestCase): corrMat = cmg.GetCorrMatrix() - bcl = BitClusterer.BitClusterer(self.blist, self.nbits/2) + bcl = BitClusterer.BitClusterer(self.blist, self.nbits//2) bcl.ClusterBits(corrMat) cls = bcl.GetClusters() for cl in cls : assert len(cl) == 2 - assert (cl[0] + self.nbits/2) == cl[1] + assert (cl[0] + self.nbits//2) == cl[1] tfp = DataStructs.ExplicitBitVect(self.nbits) - obits = range(0,self.nbits/4) + range(self.nbits/2, 3*self.nbits/4) + obits = list(range(0,self.nbits//4)) + list(range(self.nbits//2, 3*self.nbits//4)) tfp.SetBitsFromList(obits) rvc = bcl.MapToClusterScores(tfp) - assert len(rvc) == self.nbits/2 - for i in range(self.nbits/2) : - if i < self.nbits/4: + assert len(rvc) == self.nbits//2 + for i in range(self.nbits//2) : + if i < self.nbits//4: assert rvc[i] == 2 else : assert rvc[i] == 0 nfp = bcl.MapToClusterFP(tfp) - assert len(nfp) == self.nbits/2 - for i in range(self.nbits/2) : - if i < self.nbits/4: + assert len(nfp) == self.nbits//2 + for i in range(self.nbits//2) : + if i < self.nbits//4: assert nfp[i] else : assert not nfp[i] diff --git a/rdkit/ML/KNN/CrossValidate.py b/rdkit/ML/KNN/CrossValidate.py index ecf76672e..f9f69cb7f 100755 --- a/rdkit/ML/KNN/CrossValidate.py +++ b/rdkit/ML/KNN/CrossValidate.py @@ -6,7 +6,7 @@ and evaluation of individual models """ - +from __future__ import print_function from rdkit.ML.KNN.KNNClassificationModel import KNNClassificationModel from rdkit.ML.KNN.KNNRegressionModel import KNNRegressionModel from rdkit import RDRandom @@ -57,7 +57,7 @@ def CrossValidate(knnMod,testExamples,appendExamples=0): res = knnMod.PredictExample(testEx, appendExamples) devSum += abs(trueRes-res) return devSum/nTest,None - raise ValueError,"Unrecognized Model Type" + raise ValueError("Unrecognized Model Type") def CrossValidationDriver(examples, attrs, nPossibleValues, numNeigh, modelBuilder=makeClassificationModel, @@ -102,7 +102,7 @@ def CrossValidationDriver(examples, attrs, nPossibleValues, numNeigh, nTrain = len(trainExamples) if not silent: - print "Training with %d examples"%(nTrain) + print("Training with %d examples"%(nTrain)) knnMod = modelBuilder(numNeigh, attrs, distFunc) @@ -115,7 +115,7 @@ def CrossValidationDriver(examples, attrs, nPossibleValues, numNeigh, xValError,badExamples = CrossValidate(knnMod, examples,appendExamples=0) if not silent : - 'Validation error was %%%4.2f'%(100*xValError) + print('Validation error was %%%4.2f'%(100*xValError)) knnMod._trainIndices = trainIndices return knnMod, xValError diff --git a/rdkit/ML/KNN/UnitTestKNN.py b/rdkit/ML/KNN/UnitTestKNN.py index 6c1f401bd..a83492f9f 100755 --- a/rdkit/ML/KNN/UnitTestKNN.py +++ b/rdkit/ML/KNN/UnitTestKNN.py @@ -9,7 +9,7 @@ from rdkit.ML.Data import DataUtils, MLData from rdkit.ML.KNN import CrossValidate,DistFunctions from rdkit.ML.KNN import KNNModel,KNNClassificationModel,KNNRegressionModel import os.path -import cPickle +from rdkit.six.moves import cPickle from rdkit import RDRandom def feq(a,b,tol=1e-4): diff --git a/rdkit/ML/ModelPackage/Packager.py b/rdkit/ML/ModelPackage/Packager.py index 1b3926e08..47b7719d1 100755 --- a/rdkit/ML/ModelPackage/Packager.py +++ b/rdkit/ML/ModelPackage/Packager.py @@ -6,11 +6,10 @@ # -import exceptions -class DescriptorCalculationError(exceptions.Exception): +class DescriptorCalculationError(Exception): """ used to signal problems generating descriptor values """ pass -class ClassificationError(exceptions.Exception): +class ClassificationError(Exception): """ used to signal problems generating predictions """ pass @@ -65,7 +64,7 @@ class ModelPackage(object): try: descs = self._descCalc.CalcDescriptors(obj) except: - raise DescriptorCalculationError,'problems encountered generating descriptors' + raise DescriptorCalculationError('problems encountered generating descriptors') argVect = [label]+list(descs)+[0] try: @@ -73,7 +72,7 @@ class ModelPackage(object): except: import traceback traceback.print_exc() - raise ClassificationError,'problems encountered generating prediction' + raise ClassificationError('problems encountered generating prediction') return res diff --git a/rdkit/ML/ModelPackage/UnitTestPackage.py b/rdkit/ML/ModelPackage/UnitTestPackage.py index 8845114df..fdd7e7081 100755 --- a/rdkit/ML/ModelPackage/UnitTestPackage.py +++ b/rdkit/ML/ModelPackage/UnitTestPackage.py @@ -7,7 +7,8 @@ """ unit tests for the model and descriptor packager """ from rdkit import RDConfig from rdkit.ML.Data import DataUtils -import unittest,os,cPickle,sys +import unittest,os,sys +from rdkit.six.moves import cPickle from rdkit.ML.ModelPackage import Packager from rdkit import Chem import random @@ -52,25 +53,30 @@ class TestCase(unittest.TestCase): def testBuild(self): """ tests building and screening a packager """ - calc = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_calc.dsc'),'rb')) - model = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_model.pkl'),'rb')) + with open(os.path.join(self.dataDir,'Jan9_build3_calc.dsc'),'rb') as calcF: + calc = cPickle.load(calcF) + with open(os.path.join(self.dataDir,'Jan9_build3_model.pkl'),'rb') as modelF: + model = cPickle.load(modelF) pkg = Packager.ModelPackage(descCalc=calc,model=model) self._verify(pkg,self.testD) def testLoad(self): """ tests loading and screening a packager """ - pkg = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb')) + with open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb') as pkgF: + pkg = cPickle.load(pkgF) self._verify(pkg,self.testD) def testLoad2(self): """ tests loading and screening a packager 2 """ - pkg = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb')) + with open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb') as pkgF: + pkg = cPickle.load(pkgF) self._verify2(pkg,self.testD) def testPerm1(self): """ tests the descriptor remapping stuff in a packager """ from rdkit.Chem import Descriptors - pkg = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb')) + with open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb') as pkgF: + pkg = cPickle.load(pkgF) calc = pkg.GetCalculator() names = calc.GetDescriptorNames() ref = {} @@ -97,7 +103,8 @@ class TestCase(unittest.TestCase): def testPerm2(self): """ tests the descriptor remapping stuff in a packager """ - pkg = cPickle.load(open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb')) + with open(os.path.join(self.dataDir,'Jan9_build3_pkg.pkl'),'rb') as pkgF: + pkg = cPickle.load(pkgF) calc = pkg.GetCalculator() names = calc.GetDescriptorNames() DataUtils.InitRandomNumbers((23,42)) diff --git a/rdkit/ML/NaiveBayes/ClassificationModel.py b/rdkit/ML/NaiveBayes/ClassificationModel.py index ffda6caa1..6e757e20e 100644 --- a/rdkit/ML/NaiveBayes/ClassificationModel.py +++ b/rdkit/ML/NaiveBayes/ClassificationModel.py @@ -9,7 +9,7 @@ """ import numpy from rdkit.ML.Data import Quantize - +from rdkit.six import iteritems def _getBinId(val, qBounds) : bid = 0 for bnd in qBounds: @@ -196,7 +196,7 @@ class NaiveBayesClassifier : #for key in self._condProbs: for cls in range(self._nClasses) : - if not ncls.has_key(cls): continue + if not cls in ncls: continue #cls = key[0] tmp = self._condProbs[cls] for ai in self._attrs: @@ -230,7 +230,7 @@ class NaiveBayesClassifier : elif (self._nPosVals[ai] > 0) : pdesc = 1.0/(self._nPosVals[ai]) else : - raise ValueError, 'Neither Bounds set nor data pre-quantized for attribute ' + str(ai) + raise ValueError('Neither Bounds set nor data pre-quantized for attribute ' + str(ai)) tmp[ai][bid] += (self._mEstimateVal)*pdesc tmp[ai][bid] /= (ncls[cls] + self._mEstimateVal) @@ -252,7 +252,7 @@ class NaiveBayesClassifier : if appendExamples: self._examples.append(example) clsProb = {} - for key,prob in self._classProbs.iteritems(): + for key,prob in iteritems(self._classProbs): clsProb[key] = prob tmp = self._condProbs[key] for ai in self._attrs: @@ -269,7 +269,7 @@ class NaiveBayesClassifier : mkey = -1 self.mprob = -1.0 - for key,prob in clsProb.iteritems() : + for key,prob in iteritems(clsProb): if (prob > self.mprob) : mkey = key self.mprob = prob diff --git a/rdkit/ML/NaiveBayes/CrossValidate.py b/rdkit/ML/NaiveBayes/CrossValidate.py index 2af8518c8..9d8157ddc 100644 --- a/rdkit/ML/NaiveBayes/CrossValidate.py +++ b/rdkit/ML/NaiveBayes/CrossValidate.py @@ -7,6 +7,7 @@ and evaluation of individual models """ +from __future__ import print_function from rdkit.ML.NaiveBayes.ClassificationModel import NaiveBayesClassifier from rdkit.ML.Data import SplitData try: @@ -76,7 +77,7 @@ def CrossValidationDriver(examples, attrs, nPossibleValues, nQuantBounds, xValError,badExamples = CrossValidate(NBmodel, examples,appendExamples=0) if not silent: - print 'Validation error was %%%4.2f'%(100*xValError) + print('Validation error was %%%4.2f'%(100*xValError)) NBmodel._trainIndices = trainIndices return NBmodel, xValError diff --git a/rdkit/ML/Neural/NetNode.py b/rdkit/ML/Neural/NetNode.py index 89b5c83cd..95ebee78c 100755 --- a/rdkit/ML/Neural/NetNode.py +++ b/rdkit/ML/Neural/NetNode.py @@ -142,7 +142,7 @@ class NetNode: # there's only one of these, everybody has a pointer to it. self.nodeList = nodeList - self.actFunc = apply(actFunc,actFuncParms) + self.actFunc = actFunc(*actFuncParms) diff --git a/rdkit/ML/Neural/Network.py b/rdkit/ML/Neural/Network.py index 004c7b828..e56d0ce80 100755 --- a/rdkit/ML/Neural/Network.py +++ b/rdkit/ML/Neural/Network.py @@ -21,9 +21,11 @@ main node list. """ +from __future__ import print_function import numpy import random +from rdkit.six.moves import xrange from rdkit.ML.Neural import NetNode, ActFuncs # FIX: this class has not been updated to new-style classes @@ -219,23 +221,23 @@ class Network: if __name__ == '__main__': - print '[2,2,2]' + print('[2,2,2]') net = Network([2,2,2]) - print net + print(net) - print '[2,4,1]' + print('[2,4,1]') net = Network([2,4,1]) - print net + print(net) - print '[2,2]' + print('[2,2]') net = Network([2,2]) - print net + print(net) input = [1,0] res = net.ClassifyExample(input) - print input,'->',res + print(input,'->',res) input = [0,1] res = net.ClassifyExample(input) - print input,'->',res + print(input,'->',res) input = [.5,.5] res = net.ClassifyExample(input) - print input,'->',res + print(input,'->',res) diff --git a/rdkit/ML/Neural/Trainers.py b/rdkit/ML/Neural/Trainers.py index f4fa84f8b..08debe8be 100755 --- a/rdkit/ML/Neural/Trainers.py +++ b/rdkit/ML/Neural/Trainers.py @@ -10,7 +10,10 @@ Dan W. Patterson, Prentice Hall, 1996 """ +from __future__ import print_function import numpy + +from rdkit.six.moves import xrange class Trainer(object): """ "virtual base class" for network trainers @@ -155,7 +158,7 @@ class BackProp(Trainer): while (not converged) and (cycle < maxIts): maxErr = 0 newErr = 0 - #print 'bp: ',cycle + #print('bp: ',cycle) for example in examples: localErr = self.StepUpdate(example,net) newErr += localErr @@ -165,22 +168,22 @@ class BackProp(Trainer): newErr = newErr / nExamples else: newErr = maxErr - #print '\t',newErr,errTol + #print('\t',newErr,errTol) if newErr <= errTol: converged = 1 # if cycle % 10 == 0 and not silent: if not silent: - print 'epoch %d, error: % 6.4f'%(cycle,newErr) + print('epoch %d, error: % 6.4f'%(cycle,newErr)) cycle = cycle + 1 if not silent: if converged: - print 'Converged after %d epochs.'%cycle + print('Converged after %d epochs.'%cycle) else: - print 'NOT Converged after %d epochs.'%cycle - print 'final error: % 6.4f'%newErr + print('NOT Converged after %d epochs.'%cycle) + print('final error: % 6.4f'%newErr) def __init__(self,speed=0.5,momentum=0.7): """ Constructor @@ -224,10 +227,10 @@ if __name__ == '__main__': net = Network.Network([3,1]) t = BackProp() t.TrainOnLine(examples,net,maxIts=1000,useAvgErr=0) - print 'classifications:' + print('classifications:') for example in examples: res = net.ClassifyExample(example[0]) - print '%f -> %f'%(example[1][0],res) + print('%f -> %f'%(example[1][0],res)) return net @@ -256,10 +259,10 @@ if __name__ == '__main__': net = Network.Network([1,2,1]) t = BackProp(speed=.8) t.TrainOnLine(examples,net,errTol=0.1,useAvgErr=0) - print 'classifications:' + print('classifications:') for example in examples: res = net.ClassifyExample(example[:-1]) - print '%f -> %f'%(example[-1],res) + print('%f -> %f'%(example[-1],res)) return net @@ -275,8 +278,8 @@ if __name__ == '__main__': if 0: net = testXor() - print 'Xor:', net - import cPickle + print('Xor:', net) + from rdkit.six.moves import cPickle outF = open('xornet.pkl','wb+') cPickle.dump(net,outF) outF.close() diff --git a/rdkit/ML/Neural/UnitTestTrainer.py b/rdkit/ML/Neural/UnitTestTrainer.py index 9d04c28c2..163df9bd3 100755 --- a/rdkit/ML/Neural/UnitTestTrainer.py +++ b/rdkit/ML/Neural/UnitTestTrainer.py @@ -8,6 +8,7 @@ this basically works out **all** of the network code """ +from __future__ import print_function import unittest from rdkit.ML.Neural import Network,Trainers import numpy @@ -16,7 +17,7 @@ random.seed(23) class TrainerTestCase(unittest.TestCase): def setUp(self): - print '\n%s: '%self.shortDescription(), + print('\n%s: '%self.shortDescription(),end='') self.trainTol = 0.3 self.orExamples = [ [0,0,1,0.1], diff --git a/rdkit/ML/SLT/UnitTestRisk.py b/rdkit/ML/SLT/UnitTestRisk.py index c6d834c6b..9eaa7ebfb 100755 --- a/rdkit/ML/SLT/UnitTestRisk.py +++ b/rdkit/ML/SLT/UnitTestRisk.py @@ -5,6 +5,7 @@ """ unit testing code for SLT Risk functions """ +from __future__ import print_function import unittest from rdkit.ML.SLT import Risk import math @@ -12,7 +13,7 @@ import numpy class TestCase(unittest.TestCase): def setUp(self): - print '\n%s: '%self.shortDescription(), + print('\n%s: '%self.shortDescription(), end='') self.dList=[(1, 40), (2, 40), (3, 21), @@ -29,14 +30,16 @@ class TestCase(unittest.TestCase): " testing Burges empirical risk bound " res = numpy.array(map(lambda x,y=self.nPts,z=self.eps2:Risk.BurgesRiskBound(x[0],y,x[1],z), self.dList)) + res = numpy.array([Risk.BurgesRiskBound(x[0],self.nPts,x[1],self.eps2) + for x in self.dList]) target = numpy.array([.7445,.8157,.6698,.7649,.7506,.7658,.7896]) maxDev = max(abs(res-target)) assert maxDev < self.tol,'maxDev too high' def testCherkassky(self): " testing Cherkassky empirical risk bound " - res = numpy.array(map(lambda x,y=self.nPts,z=self.eps:Risk.CherkasskyRiskBound(x[0],y,x[1],z), - self.dList)) + res = numpy.array([Risk.CherkasskyRiskBound(x[0],self.nPts,x[1],self.eps) + for x in self.dList]) target = numpy.array([.6654,.7450,.5378,.6329,.6010,.6175,.6501]) maxDev = max(abs(res-target)) assert maxDev < self.tol,'maxDev too high' diff --git a/rdkit/ML/ScreenComposite.py b/rdkit/ML/ScreenComposite.py index a2344a8e4..907c7afe4 100755 --- a/rdkit/ML/ScreenComposite.py +++ b/rdkit/ML/ScreenComposite.py @@ -108,10 +108,12 @@ a file containing a pickled composite model and _filename_ is a QDAT file. """ +from __future__ import print_function +import sys, copy +import numpy +from rdkit.six.moves import cPickle from rdkit import RDConfig from rdkit import DataStructs -import sys,cPickle,types,copy -import numpy try: from PIL import Image,ImageDraw @@ -204,11 +206,11 @@ def CollectResults(indices,dataSet,composite,callback=None,appendExamples=0, """ #for i in range(len(composite)): - # print ' ',i,'TRAIN:',composite[i][0]._trainIndices + # print(' ',i,'TRAIN:',composite[i][0]._trainIndices) for j in range(len(composite)): tmp = composite.GetModel(j) - if hasattr(tmp,'_trainIndices') and type(tmp._trainIndices)!=types.DictType: + if hasattr(tmp,'_trainIndices') and type(tmp._trainIndices)!=dict: tis = {} if hasattr(tmp,'_trainIndices'): for v in tmp._trainIndices: tis[v]=1 @@ -228,7 +230,7 @@ def CollectResults(indices,dataSet,composite,callback=None,appendExamples=0, use.append(j) else: use = None - #print 'IDX:',idx,'use:',use + #print('IDX:',idx,'use:',use ) pred,conf = composite.ClassifyExample(example,appendExample=appendExamples, onlyModels=use) if composite.GetActivityQuantBounds(): @@ -381,15 +383,16 @@ def ShowVoteResults(indices,data,composite,nResultCodes,threshold,verbose=1, nGood = len(goodVotes) nClassified = nGood + nBad if verbose: - print '\n\t*** Vote Results ***' - print 'misclassified: %d/%d (%%%4.2f)\t%d/%d (%%%4.2f)'%(nBad,nExamples, - 100.*float(nBad)/nExamples, - nBad,nClassified, - 100.*float(nBad)/nClassified) + print('\n\t*** Vote Results ***') + print('misclassified: %d/%d (%%%4.2f)\t%d/%d (%%%4.2f)' % + (nBad,nExamples, + 100.*float(nBad)/nExamples, + nBad,nClassified, + 100.*float(nBad)/nClassified)) nSkip = len(noVotes) if nSkip > 0: if verbose: - print 'skipped: %d/%d (%%% 4.2f)'%(nSkip,nExamples,100.*float(nSkip)/nExamples) + print('skipped: %d/%d (%%% 4.2f)'%(nSkip,nExamples,100.*float(nSkip)/nExamples)) noConf = numpy.array([x[2] for x in noVotes]) avgSkip = sum(noConf)/float(nSkip) else: @@ -411,9 +414,9 @@ def ShowVoteResults(indices,data,composite,nResultCodes,threshold,verbose=1, avgGood = 0. if verbose: - print - print 'average correct confidence: % 6.4f'%avgGood - print 'average incorrect confidence: % 6.4f'%avgBad + print() + print('average correct confidence: % 6.4f'%avgGood) + print('average incorrect confidence: % 6.4f'%avgBad) voteTab = numpy.zeros((nResultCodes,nResultCodes),numpy.int) for res in goodRes: @@ -422,8 +425,8 @@ def ShowVoteResults(indices,data,composite,nResultCodes,threshold,verbose=1, voteTab[ans,res] += 1 if verbose: - print - print '\tResults Table:' + print() + print('\tResults Table:') vTab=voteTab.transpose() colCounts = numpy.sum(vTab,0) rowCounts = numpy.sum(vTab,1) @@ -538,19 +541,19 @@ def ScreenIt(composite,indices,data,partialVote=0,voteTol=0.0,verbose=1,screenRe nData = nGood + misCount + nSkipped if verbose: - print 'Total N Points:',nData + print('Total N Points:',nData) if partialVote: nCounted = nData-nSkipped if verbose: - print 'Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nCounted) - print 'N Skipped: %d (%%%4.2f)'%(nSkipped,100.*float(nSkipped)/nData) - print '\tGood Votes Skipped: %d (%%%4.2f)'%(goodSkipped,100.*float(goodSkipped)/nSkipped) - print '\tBad Votes Skipped: %d (%%%4.2f)'%(badSkipped,100.*float(badSkipped)/nSkipped) + print('Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nCounted)) + print('N Skipped: %d (%%%4.2f)'%(nSkipped,100.*float(nSkipped)/nData)) + print('\tGood Votes Skipped: %d (%%%4.2f)'%(goodSkipped,100.*float(goodSkipped)/nSkipped)) + print('\tBad Votes Skipped: %d (%%%4.2f)'%(badSkipped,100.*float(badSkipped)/nSkipped)) else: if verbose: - print 'Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nData) - print 'Average Correct Vote Confidence: % 6.4f'%(goodAccum/(nData-misCount)) - print 'Average InCorrect Vote Confidence: % 6.4f'%(badAccum/misCount) + print('Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nData)) + print('Average Correct Vote Confidence: % 6.4f'%(goodAccum/(nData-misCount))) + print('Average InCorrect Vote Confidence: % 6.4f'%(badAccum/misCount)) avgGood=0 avgBad=0 @@ -700,7 +703,7 @@ def ScreenFromDetails(models,details,callback=None,setup=None,appendExamples=0, else: partialVote = 0 - if type(models) not in [types.ListType,types.TupleType]: + if type(models) not in [list, tuple]: models = (models,) nModels = len(models) @@ -909,7 +912,7 @@ def ScreenToHtml(nGood,nBad,nRej,avgGood,avgBad,avgSkip,voteTable,imgDir='.', a string containing HTML """ - if type(nGood) == types.TupleType: + if type(nGood) == tuple: multModels=1 else: multModels=0 @@ -1188,18 +1191,18 @@ def Usage(): command line and then exits """ - print __doc__ + print(__doc__) sys.exit(-1) def ShowVersion(includeArgs=0): """ prints the version number of the program """ - print 'This is ScreenComposite.py version %s'%(__VERSION_STRING) + print('This is ScreenComposite.py version %s'%(__VERSION_STRING)) if includeArgs: import sys - print 'command line was:' - print ' '.join(sys.argv) + print('command line was:') + print(' '.join(sys.argv)) def ParseArgs(details): import getopt @@ -1454,24 +1457,24 @@ if __name__ == '__main__': MakePredPlot(details,testIdx,tmpD,goodVotes,badVotes,nRes,verbose=1) if hasattr(details,'showAll') and details.showAll: - print '-v-v-v-v-v-v-v- All Votes -v-v-v-v-v-v-v-' - print 'id, prediction, confidence, flag(-1=skipped,0=wrong,1=correct)' + print('-v-v-v-v-v-v-v- All Votes -v-v-v-v-v-v-v-') + print('id, prediction, confidence, flag(-1=skipped,0=wrong,1=correct)') for ans,pred,conf,idx in goodVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) - print '%s, %d, %.4f, 1'%(str(pt[0]),pred,conf) + print('%s, %d, %.4f, 1'%(str(pt[0]),pred,conf)) for ans,pred,conf,idx in badVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) - print '%s, %d, %.4f, 0'%(str(pt[0]),pred,conf) + print('%s, %d, %.4f, 0'%(str(pt[0]),pred,conf)) for ans,pred,conf,idx in noVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) - print '%s, %d, %.4f, -1'%(str(pt[0]),pred,conf) - print '-^-^-^-^-^-^-^- -^-^-^-^-^-^-^-' + print('%s, %d, %.4f, -1'%(str(pt[0]),pred,conf)) + print('-^-^-^-^-^-^-^- -^-^-^-^-^-^-^-') nGood[modelIdx] = g nBad[modelIdx] = b @@ -1479,11 +1482,11 @@ if __name__ == '__main__': confGood[modelIdx] = aG confBad[modelIdx] = aB confSkip[modelIdx] = aS - print + print() if nModels > 1: - print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*' - print 'AVERAGES:' + print('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*') + print('AVERAGES:') avgNBad = sum(nBad)/nModels devNBad = numpy.sqrt(sum((nBad-avgNBad)**2)/(nModels-1)) @@ -1507,27 +1510,27 @@ if __name__ == '__main__': nClassified = avgNGood + avgNBad nExamples = nClassified + avgNSkip - print 'Misclassifications: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nExamples, + print('Misclassifications: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nExamples, 100*devNBad/nExamples, avgNBad,devNBad, - nExamples) + nExamples)) if avgNSkip>0: - print '\tthreshold: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nClassified, + print('\tthreshold: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nClassified, 100*devNBad/nClassified, avgNBad,devNBad, - nClassified) - print - print 'Number Skipped: %%%4.2f(%%%4.2f) %4.2f(%4.2f)'%(100*avgNSkip/nExamples, + nClassified)) + print() + print('Number Skipped: %%%4.2f(%%%4.2f) %4.2f(%4.2f)'%(100*avgNSkip/nExamples, 100*devNSkip/nExamples, - avgNSkip,devNSkip) + avgNSkip,devNSkip)) - print - print 'Confidences:' - print '\tCorrect: \t%4.2f(%4.2f)'%(100*avgConfGood,100*devConfGood) - print '\tIncorrect: \t%4.2f(%4.2f)'%(100*avgConfBad,100*devConfBad) + print() + print('Confidences:') + print('\tCorrect: \t%4.2f(%4.2f)'%(100*avgConfGood,100*devConfGood)) + print('\tIncorrect: \t%4.2f(%4.2f)'%(100*avgConfBad,100*devConfBad)) if avgNSkip>0: - print '\tSkipped: \t%4.2f(%4.2f)'%(100*avgConfSkip,100*devConfSkip) + print('\tSkipped: \t%4.2f(%4.2f)'%(100*avgConfSkip,100*devConfSkip)) if details.detailedScreen: message('Results Table:') @@ -1535,7 +1538,7 @@ if __name__ == '__main__': nResultCodes = len(voteTab) colCounts = numpy.sum(voteTab,0) rowCounts = numpy.sum(voteTab,1) - print + print() for i in range(nResultCodes): if rowCounts[i]==0: rowCounts[i]=1 row = voteTab[i] @@ -1560,28 +1563,28 @@ if __name__ == '__main__': message(' Enrichment of value %d: %.4f (%.4f)'%(details.enrichTgt,mean,dev)) else: bestIdx=0 - print '------------------------------------------------' - print 'Best Model: ',bestIdx+1 + print('------------------------------------------------') + print('Best Model: ',bestIdx+1) bestBad = nBad[bestIdx] bestGood = nGood[bestIdx] bestSkip = nSkip[bestIdx] nClassified = bestGood + bestBad nExamples = nClassified + bestSkip - print 'Misclassifications: \t%%%5.2f %d / %d'%(100*bestBad/nExamples, - bestBad,nExamples) + print('Misclassifications: \t%%%5.2f %d / %d'%(100*bestBad/nExamples, + bestBad,nExamples)) if bestSkip>0: - print '\tthreshold: \t%%%5.2f %d / %d'%(100*bestBad/nClassified, - bestBad,nClassified) - print - print 'Number Skipped: %%%4.2f %d'%(100*bestSkip/nExamples, - bestSkip) + print('\tthreshold: \t%%%5.2f %d / %d'%(100*bestBad/nClassified, + bestBad,nClassified)) + print() + print('Number Skipped: %%%4.2f %d'%(100*bestSkip/nExamples, + bestSkip)) - print - print 'Confidences:' - print '\tCorrect: \t%4.2f'%(100*confGood[bestIdx]) - print '\tIncorrect: \t%4.2f'%(100*confBad[bestIdx]) + print() + print('Confidences:') + print('\tCorrect: \t%4.2f'%(100*confGood[bestIdx])) + print('\tIncorrect: \t%4.2f'%(100*confBad[bestIdx])) if bestSkip>0: - print '\tSkipped: \t%4.2f'%(100*confSkip[bestIdx]) + print('\tSkipped: \t%4.2f'%(100*confSkip[bestIdx])) if nModels == 1 and details.detailedScreen: message('') diff --git a/rdkit/ML/UnitTestAnalyzeComposite.py b/rdkit/ML/UnitTestAnalyzeComposite.py index 8d8efc331..1977aa460 100644 --- a/rdkit/ML/UnitTestAnalyzeComposite.py +++ b/rdkit/ML/UnitTestAnalyzeComposite.py @@ -14,7 +14,7 @@ from rdkit import RDConfig import unittest,os from rdkit.ML import AnalyzeComposite -import cPickle as pickle +from rdkit.six.moves import cPickle as pickle def feq(a,b,tol=1e-4): if abs(a-b)>tol: return 0 @@ -27,16 +27,18 @@ class TestCase(unittest.TestCase): def test1_Issue163(self): name1 = os.path.join(self.baseDir,'humanoral.1.pkl') try: - c1 = pickle.load(open(name1,'rb')) + with open(name1,'rb') as pklF: + c1 = pickle.load(pklF) except: c1 = None - self.failUnless(c1) + self.assertTrue(c1) name2 = os.path.join(self.baseDir,'humanoral.2.pkl') try: - c2 = pickle.load(open(name2,'rb')) + with open(name2, 'rb') as pklF: + c2 = pickle.load(pklF) except: c2 = None - self.failUnless(c2) + self.assertTrue(c2) try: res = AnalyzeComposite.ProcessIt([c1,c2],verbose=-1) @@ -46,13 +48,13 @@ class TestCase(unittest.TestCase): ok=0 else: ok=1 - self.failUnless(ok) + self.assertTrue(ok) - self.failUnless(res[0][0]=='BALABANJ') - self.failUnless(res[1][0]=='BERTZCT') - self.failUnless(res[-1][0]=='FR_ALLYLIC_OXID') + self.assertTrue(res[0][0]=='BALABANJ') + self.assertTrue(res[1][0]=='BERTZCT') + self.assertTrue(res[-1][0]=='FR_ALLYLIC_OXID') for entry in res: - self.failUnless(len(entry)==5) + self.assertTrue(len(entry)==5) if __name__ == '__main__': unittest.main() diff --git a/rdkit/ML/UnitTestBuildComposite.py b/rdkit/ML/UnitTestBuildComposite.py index 3ce55df8c..ed0f0b986 100755 --- a/rdkit/ML/UnitTestBuildComposite.py +++ b/rdkit/ML/UnitTestBuildComposite.py @@ -11,12 +11,12 @@ """unit testing code for the BuildComposite functionality """ -from rdkit import RDConfig import unittest,os +from rdkit.six.moves import cPickle as pickle +from rdkit import RDConfig from rdkit.ML import BuildComposite from rdkit.ML import ScreenComposite from rdkit.Dbase.DbConnection import DbConnect -import cPickle as pickle def feq(a,b,tol=1e-4): if abs(a-b)>tol: return 0 @@ -80,8 +80,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_quant' refComposName = 'ferromag_quant_10.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos) @@ -94,8 +94,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_quant' refComposName = 'ferromag_quant_10_3.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos) @@ -109,8 +109,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_quant' refComposName = 'ferromag_quant_10_3_lessgreedy.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos) @@ -125,8 +125,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_quant' refComposName = 'ferromag_quant_50_3.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos) @@ -141,9 +141,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_noquant' refComposName = 'ferromag_auto_10_3.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) - + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos,copyBounds=1) @@ -157,8 +156,8 @@ class TestCase(unittest.TestCase): self.details.tableName = 'ferro_noquant_realact' refComposName = 'ferromag_auto_10_3.pkl' - refCompos = pickle.load(open(os.path.join(self.baseDir,refComposName), - 'rb')) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklF: + refCompos = pickle.load(pklF) # first make sure the data are intact self._init(refCompos,copyBounds=1) @@ -172,8 +171,8 @@ class TestCase(unittest.TestCase): """ Test composite of naive bayes""" self.details.tableName = 'ferro_noquant' refComposName = 'ferromag_NaiveBayes.pkl' - pklFile = open(os.path.join(self.baseDir,refComposName), 'rb') - refCompos = pickle.load(pklFile) + with open(os.path.join(self.baseDir,refComposName), 'rb') as pklFile: + refCompos = pickle.load(pklFile) self._init(refCompos,copyBounds=1) self.details.useTrees = 0 self.details.useNaiveBayes = 1 diff --git a/rdkit/ML/UnitTestScreenComposite.py b/rdkit/ML/UnitTestScreenComposite.py index 244ddc06e..63bd063f6 100755 --- a/rdkit/ML/UnitTestScreenComposite.py +++ b/rdkit/ML/UnitTestScreenComposite.py @@ -15,7 +15,7 @@ from rdkit import RDConfig import unittest,os from rdkit.ML import BuildComposite from rdkit.ML import ScreenComposite -import cPickle as pickle +from rdkit.six.moves import cPickle as pickle def feq(a,b,tol=1e-4): if abs(a-b)>tol: return 0 @@ -34,8 +34,8 @@ class TestCase(unittest.TestCase): def test1(self): """ basics """ self.details.tableName = 'ferro_quant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 7 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) @@ -56,8 +56,8 @@ class TestCase(unittest.TestCase): self.details.doHoldout=1 self.details.doTraining=0 - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 7 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) @@ -78,8 +78,8 @@ class TestCase(unittest.TestCase): self.details.doHoldout=0 self.details.doTraining=1 - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 7 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) @@ -101,8 +101,8 @@ class TestCase(unittest.TestCase): self.details.doHoldout=0 self.details.doTraining=0 - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_quant_10.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 7 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) @@ -121,8 +121,9 @@ class TestCase(unittest.TestCase): def test5(self): """ basics """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_auto_10_3.pkl'), - 'rb')) + + with open(os.path.join(self.baseDir,'ferromag_auto_10_3.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) @@ -142,8 +143,8 @@ class TestCase(unittest.TestCase): def test6(self): """ multiple models """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_auto_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_auto_10_3.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) composites = [compos,compos] @@ -167,8 +168,8 @@ class TestCase(unittest.TestCase): def test7(self): """ shuffle """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'),'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.shuffleActivities=1 @@ -186,8 +187,9 @@ class TestCase(unittest.TestCase): def test8(self): """ shuffle with segmentation """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'), + 'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.shuffleActivities=1 @@ -206,8 +208,9 @@ class TestCase(unittest.TestCase): def test9(self): """ shuffle with segmentation2 """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_shuffle_10_3.pkl'), + 'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.shuffleActivities=1 @@ -226,8 +229,9 @@ class TestCase(unittest.TestCase): def test10(self): """ filtering """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_filt_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_filt_10_3.pkl'), + 'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.filterVal=1 @@ -247,8 +251,9 @@ class TestCase(unittest.TestCase): def test11(self): """ filtering with segmentation """ self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_filt_10_3.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_filt_10_3.pkl'), + 'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.doHoldout=1 @@ -270,8 +275,9 @@ class TestCase(unittest.TestCase): def test12(self): """ test the naive bayes composite""" self.details.tableName = 'ferro_noquant' - compos = pickle.load(open(os.path.join(self.baseDir,'ferromag_NaiveBayes.pkl'), - 'rb')) + with open(os.path.join(self.baseDir,'ferromag_NaiveBayes.pkl'), + 'rb') as pklF: + compos = pickle.load(pklF) tgt = 10 assert len(compos)==tgt,'bad composite loaded: %d != %d'%(len(compos),tgt) self.details.doHoldout=1 diff --git a/rdkit/Numerics/__init__.py b/rdkit/Numerics/__init__.py index 4465e2e08..5735d6153 100644 --- a/rdkit/Numerics/__init__.py +++ b/rdkit/Numerics/__init__.py @@ -1,4 +1,4 @@ """ A module for Numerics stuff """ -import rdAlignment as Alignment +from rdkit.Numerics import rdAlignment as Alignment diff --git a/rdkit/RDConfig.py b/rdkit/RDConfig.py index 8493a7603..60aeb5dcf 100755 --- a/rdkit/RDConfig.py +++ b/rdkit/RDConfig.py @@ -13,7 +13,7 @@ """ import os,sys -if os.environ.has_key('RDBASE'): +if 'RDBASE' in os.environ: RDBaseDir=os.environ['RDBASE'] RDCodeDir=os.path.join(RDBaseDir,'rdkit') RDDataDir=os.path.join(RDBaseDir,'Data') @@ -30,10 +30,9 @@ pythonTestCommand="python" defaultDBUser='sysdba' defaultDBPassword='masterkey' -import exceptions -class ObsoleteCodeError(exceptions.Exception): +class ObsoleteCodeError(Exception): pass -class UnimplementedCodeError(exceptions.Exception): +class UnimplementedCodeError(Exception): pass # --------------------- diff --git a/rdkit/RDRandom.py b/rdkit/RDRandom.py index 2c8642dd8..30663fa5c 100755 --- a/rdkit/RDRandom.py +++ b/rdkit/RDRandom.py @@ -15,7 +15,12 @@ import sys import random as _random -if sys.hexversion >= 0x20303f0: +if sys.hexversion >= 0x30400f0: + # TODO review this + random = _random.random + randrange = _random.randrange + seed = _random.seed +elif sys.hexversion >= 0x20303f0: _randGen = _random.WichmannHill() random = _randGen.random randrange = _randGen.randrange diff --git a/rdkit/TestRunner.py b/rdkit/TestRunner.py index 8cf6fd9dd..81f04a489 100755 --- a/rdkit/TestRunner.py +++ b/rdkit/TestRunner.py @@ -8,6 +8,7 @@ # which is included in the file license.txt, found at the root # of the RDKit source tree. # +from __future__ import print_function from rdkit import RDConfig import os,sys,time if sys.version_info[0]>2 or sys.version_info[1]>=4: @@ -24,18 +25,18 @@ def RunTest(exeName,args,extras): args = args.split(' ') startDir = os.getcwd() - if extras.has_key('dir'): + if 'dir' in extras: os.chdir(extras['dir']) expectedReturn = extras.get('returns',0) if not subprocess: - raise NotImplementedError,'cannot run tests if the subprocess module is not available.' + raise NotImplementedError('cannot run tests if the subprocess module is not available.') else: try: retVal = subprocess.call([exeName]+list(args)) except OSError: - print >>sys.stderr,"Could not find executable: %s."%exeName + print("Could not find executable: %s."%exeName, file=sys.stderr) return TEST_FAILED - if extras.has_key('dir'): + if 'dir' in extras: os.chdir(startDir) if retVal!=expectedReturn: return TEST_FAILED @@ -77,7 +78,7 @@ def RunScript(script,doLongTests,verbose): try: exeName,args,extras = entry except ValueError: - print 'bad entry:',entry + print('bad entry:',entry) sys.exit(-1) try: res = RunTest(exeName,args,extras) diff --git a/rdkit/six.py b/rdkit/six.py new file mode 100644 index 000000000..c8509a5b8 --- /dev/null +++ b/rdkit/six.py @@ -0,0 +1,654 @@ +"""Utilities for writing code that runs on Python 2 and 3""" + +# Copyright (c) 2010-2014 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.6.1" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + try: + result = self._resolve() + except ImportError: + # See the nice big comment in MovedModule.__getattr__. + raise AttributeError("%s could not be imported " % self.name) + setattr(obj, self.name, result) # Invokes __set__. + # This is a bit ugly, but it avoids running this again. + delattr(obj.__class__, self.name) + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + # It turns out many Python frameworks like to traverse sys.modules and + # try to load various attributes. This causes problems if this is a + # platform-specific module on the wrong platform, like _winreg on + # Unixes. Therefore, we silently pretend unimportable modules do not + # have any attributes. See issues #51, #53, #56, and #63 for the full + # tales of woe. + # + # First, if possible, avoid loading the module just to look at __file__, + # __name__, or __path__. + if (attr in ("__file__", "__name__", "__path__") and + self.mod not in sys.modules): + raise AttributeError(attr) + try: + _module = self._resolve() + except ImportError: + raise AttributeError(attr) + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + + +class _MovedItems(_LazyModule): + """Lazy loading of moved objects""" + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "xmlrpclib", "xmlrpc.server"), + MovedModule("winreg", "_winreg"), +] +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + sys.modules[__name__ + ".moves." + attr.name] = attr +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") + + +class Module_six_moves_urllib_error(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + parse = sys.modules[__name__ + ".moves.urllib_parse"] + error = sys.modules[__name__ + ".moves.urllib_error"] + request = sys.modules[__name__ + ".moves.urllib_request"] + response = sys.modules[__name__ + ".moves.urllib_response"] + robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + + +sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) +else: + def iterkeys(d, **kw): + return iter(d.iterkeys(**kw)) + + def itervalues(d, **kw): + return iter(d.itervalues(**kw)) + + def iteritems(d, **kw): + return iter(d.iteritems(**kw)) + + def iterlists(d, **kw): + return iter(d.iterlists(**kw)) + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + def u(s): + return s + unichr = chr + if sys.version_info[1] <= 1: + def int2byte(i): + return bytes((i,)) + else: + # This is about 2x faster than the implementation above on 3.2+ + int2byte = operator.methodcaller("to_bytes", 1, "big") + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO +else: + def b(s): + return s + # Workaround for standalone backslash + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + def byte2int(bs): + return ord(bs[0]) + def indexbytes(buf, i): + return ord(buf[i]) + def iterbytes(buf): + return (ord(byte) for byte in buf) + import StringIO + StringIO = BytesIO = StringIO.StringIO +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + +_add_doc(reraise, """Reraise an exception.""") + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + return meta("NewBase", bases, {}) + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper diff --git a/rdkit/sping/pid.py b/rdkit/sping/pid.py index 4b72fce16..bff3e8712 100755 --- a/rdkit/sping/pid.py +++ b/rdkit/sping/pid.py @@ -19,26 +19,26 @@ # Progress Reports... # JJS, 2/10/99: as discussed, I've removed the Shape classes and moved -# the drawing methods into the Canvas class. Numerous other changes -# as discussed by email as well. +# the drawing methods into the Canvas class. Numerous other changes +# as discussed by email as well. # JJS, 2/11/99: removed Canvas default access functions; added fontHeight -# etc. functions; fixed numerous typos; added drawRect and drawRoundRect -# (how could I forget those?). Added StateSaver utility class. - -# 2/11/99 (later): minor fixes. +# etc. functions; fixed numerous typos; added drawRect and drawRoundRect +# (how could I forget those?). Added StateSaver utility class. + +# 2/11/99 (later): minor fixes. # JJS, 2/12/99: removed scaling/sizing references. Changed event handler -# mechanism per Magnus's idea. Changed drawCurve into a fillable -# drawing function (needs default implementation). Removed edgeList -# from drawPolygon. Added drawFigure. Changed drawLines to draw -# a set of disconnected lines (of uniform color and width). - -# 2/12/99 (later): added HexColor function and WWW color constants. -# Fixed bug in StateSaver. Changed params to drawArc. +# mechanism per Magnus's idea. Changed drawCurve into a fillable +# drawing function (needs default implementation). Removed edgeList +# from drawPolygon. Added drawFigure. Changed drawLines to draw +# a set of disconnected lines (of uniform color and width). + +# 2/12/99 (later): added HexColor function and WWW color constants. +# Fixed bug in StateSaver. Changed params to drawArc. # JJS, 2/17/99: added operator methods to Color; added default implementation -# of drawRoundRect in terms of Line, Rect, and Arc. +# of drawRoundRect in terms of Line, Rect, and Arc. # JJS, 2/18/99: added isInteractive and canUpdate methods to Canvas. @@ -47,14 +47,14 @@ # JJS, 3/01/99: nailed down drawFigure interface (and added needed constants). # JJS, 3/08/99: added arcPoints and curvePoints methods; added default -# implementations for drawRect, drawRoundRect, drawArc, drawCurve, -# drawEllipse, and drawFigure (!), mostly thanks to Magnus. +# implementations for drawRect, drawRoundRect, drawArc, drawCurve, +# drawEllipse, and drawFigure (!), mostly thanks to Magnus. # JJS, 3/09/99: added 'closed' parameter to drawPolygon, drawCurve, and -# drawFigure. Made use of this in several default implementations. +# drawFigure. Made use of this in several default implementations. # JJS, 3/11/99: added 'onKey' callback and associated constants; also added -# Canvas.setInfoLine(s) method. +# Canvas.setInfoLine(s) method. # JJS, 3/12/99: typo in drawFigure.__doc__ corrected (thanks to Magnus). @@ -75,7 +75,7 @@ # JJS, 9/29/99: added drawMultiLineStrings, updated fontHeight with new definition # JJS, 10/21/99: made Color immutable; fixed bugs in default fontHeight, -# drawMultiLineString +# drawMultiLineString """ @@ -102,34 +102,34 @@ __version__ = __version_maj_number__ + "." + __version_min_number__ # c.f. "1.0 from types import StringType, IntType, InstanceType from rdkit.sping.colors import * -inch = 72 # 1 PIDDLE drawing unit == 1/72 imperial inch -cm = inch/2.54 # more sensible measurement unit +inch = 72 # 1 PIDDLE drawing unit == 1/72 imperial inch +cm = inch/2.54 # more sensible measurement unit #------------------------------------------------------------------------- # StateSaver #------------------------------------------------------------------------- class StateSaver: - """This is a little utility class for saving and restoring the - default drawing parameters of a canvas. To use it, add a line - like this before changing any of the parameters: - - saver = StateSaver(myCanvas) - - then, when "saver" goes out of scope, it will automagically - restore the drawing parameters of myCanvas.""" + """This is a little utility class for saving and restoring the + default drawing parameters of a canvas. To use it, add a line + like this before changing any of the parameters: + + saver = StateSaver(myCanvas) + + then, when "saver" goes out of scope, it will automagically + restore the drawing parameters of myCanvas.""" - def __init__(self, canvas): - self.canvas = canvas - self.defaultLineColor = canvas.defaultLineColor - self.defaultFillColor = canvas.defaultFillColor - self.defaultLineWidth = canvas.defaultLineWidth - self.defaultFont = canvas.defaultFont - - def __del__(self): - self.canvas.defaultLineColor = self.defaultLineColor - self.canvas.defaultFillColor = self.defaultFillColor - self.canvas.defaultLineWidth = self.defaultLineWidth - self.canvas.defaultFont = self.defaultFont + def __init__(self, canvas): + self.canvas = canvas + self.defaultLineColor = canvas.defaultLineColor + self.defaultFillColor = canvas.defaultFillColor + self.defaultLineWidth = canvas.defaultLineWidth + self.defaultFont = canvas.defaultFont + + def __del__(self): + self.canvas.defaultLineColor = self.defaultLineColor + self.canvas.defaultFillColor = self.defaultFillColor + self.canvas.defaultLineWidth = self.defaultLineWidth + self.canvas.defaultFont = self.defaultFont @@ -138,7 +138,7 @@ class StateSaver: #------------------------------------------------------------------------- class Font: "This class represents font typeface, size, and style." - + def __init__(self, size=12, bold=0, italic=0, underline=0, face=None): # public mode variables d = self.__dict__ @@ -152,7 +152,7 @@ class Font: # typeface -- a name or set of names, interpreted by the Canvas, # or "None" to indicate the Canvas-specific default typeface d["face"] = face - + def __cmp__(self, other): """Compare two fonts to see if they're the same.""" if self.face == other.face and self.size == other.size and \ @@ -167,7 +167,7 @@ class Font: self.underline, repr(self.face)) def __setattr__(self, name, value): - raise TypeError, "piddle.Font has read-only attributes" + raise TypeError("piddle.Font has read-only attributes") #------------------------------------------------------------------------- @@ -180,8 +180,8 @@ figureCurve = 3 #------------------------------------------------------------------------- # key constants used for special keys in the onKey callback #------------------------------------------------------------------------- -keyBksp = '\010' # (erases char to left of cursor) -keyDel = '\177' # (erases char to right of cursor) +keyBksp = '\010' # (erases char to left of cursor) +keyDel = '\177' # (erases char to right of cursor) keyLeft = '\034' keyRight = '\035' keyUp = '\036' @@ -193,68 +193,68 @@ keyEnd = '\004' keyClear = '\033' keyTab = '\t' -modShift = 1 # shift key was also held -modControl = 2 # control key was also held +modShift = 1 # shift key was also held +modControl = 2 # control key was also held #------------------------------------------------------------------------- # Canvas #------------------------------------------------------------------------- class Canvas: - """This is the base class for a drawing canvas. The 'plug-in renderers' - we speak of are really just classes derived from this one, which implement - the various drawing methods.""" - - def __init__(self, size=(300,300), name="PIDDLE"): - """Initialize the canvas, and set default drawing parameters. - Derived classes should be sure to call this method.""" - # defaults used when drawing - self.defaultLineColor = black - self.defaultFillColor = transparent - self.defaultLineWidth = 1 - self.defaultFont = Font() + """This is the base class for a drawing canvas. The 'plug-in renderers' + we speak of are really just classes derived from this one, which implement + the various drawing methods.""" + + def __init__(self, size=(300,300), name="PIDDLE"): + """Initialize the canvas, and set default drawing parameters. + Derived classes should be sure to call this method.""" + # defaults used when drawing + self.defaultLineColor = black + self.defaultFillColor = transparent + self.defaultLineWidth = 1 + self.defaultFont = Font() - # set up null event handlers - - # onClick: x,y is Canvas coordinates of mouseclick - def ignoreClick(canvas,x,y): pass - self.onClick = ignoreClick + # set up null event handlers + + # onClick: x,y is Canvas coordinates of mouseclick + def ignoreClick(canvas,x,y): pass + self.onClick = ignoreClick - # onOver: x,y is Canvas location of mouse - def ignoreOver(canvas,x,y): pass - self.onOver = ignoreOver + # onOver: x,y is Canvas location of mouse + def ignoreOver(canvas,x,y): pass + self.onOver = ignoreOver - # onKey: key is printable character or one of the constants above; - # modifiers is a tuple containing any of (modShift, modControl) - def ignoreKey(canvas,key,modifiers): pass - self.onKey = ignoreKey + # onKey: key is printable character or one of the constants above; + # modifiers is a tuple containing any of (modShift, modControl) + def ignoreKey(canvas,key,modifiers): pass + self.onKey = ignoreKey - # size and name, for user's reference - self.size, self.name = size,name + # size and name, for user's reference + self.size, self.name = size,name - - def getSize(self): - # gL - return self.size - - #------------ canvas capabilities ------------- - def isInteractive(self): - "Returns 1 if onClick, onOver, and onKey events are possible, 0 otherwise." - return 0 - - def canUpdate(self): - "Returns 1 if the drawing can be meaningfully updated over time \ - (e.g., screen graphics), 0 otherwise (e.g., drawing to a file)." - return 0 + + def getSize(self): + # gL + return self.size + + #------------ canvas capabilities ------------- + def isInteractive(self): + "Returns 1 if onClick, onOver, and onKey events are possible, 0 otherwise." + return 0 + + def canUpdate(self): + "Returns 1 if the drawing can be meaningfully updated over time \ + (e.g., screen graphics), 0 otherwise (e.g., drawing to a file)." + return 0 - #------------ general management ------------- - def clear(self): - "Call this to clear and reset the graphics context." - pass - - def flush(self): - "Call this to indicate that any comamnds that have been issued \ + #------------ general management ------------- + def clear(self): + "Call this to clear and reset the graphics context." + pass + + def flush(self): + "Call this to indicate that any comamnds that have been issued \ but which might be buffered should be flushed to the screen" - pass + pass def save(self, file=None, format=None): @@ -274,287 +274,287 @@ class Canvas: pass - - def setInfoLine(self, s): - "For interactive Canvases, displays the given string in the \ - 'info line' somewhere where the user can probably see it." - pass - - #------------ string/font info ------------ + + def setInfoLine(self, s): + "For interactive Canvases, displays the given string in the \ + 'info line' somewhere where the user can probably see it." + pass + + #------------ string/font info ------------ def stringBox(self,s,font=None): return self.stringWidth(s,font),self.fontHeight(font) - def stringWidth(self, s, font=None): - "Return the logical width of the string if it were drawn \ - in the current font (defaults to self.font)." - raise NotImplementedError, 'stringWidth' - - def fontHeight(self, font=None): - "Find the height of one line of text (baseline to baseline) of the given font." - # the following approxmation is correct for PostScript fonts, - # and should be close for most others: - if not font: font = self.defaultFont - return 1.2 * font.size - - def fontAscent(self, font=None): - "Find the ascent (height above base) of the given font." - raise NotImplementedError, 'fontAscent' - - def fontDescent(self, font=None): - "Find the descent (extent below base) of the given font." - raise NotImplementedError, 'fontDescent' - - #------------- drawing helpers -------------- + def stringWidth(self, s, font=None): + "Return the logical width of the string if it were drawn \ + in the current font (defaults to self.font)." + raise NotImplementedError('stringWidth') + + def fontHeight(self, font=None): + "Find the height of one line of text (baseline to baseline) of the given font." + # the following approxmation is correct for PostScript fonts, + # and should be close for most others: + if not font: font = self.defaultFont + return 1.2 * font.size + + def fontAscent(self, font=None): + "Find the ascent (height above base) of the given font." + raise NotImplementedError('fontAscent') + + def fontDescent(self, font=None): + "Find the descent (extent below base) of the given font." + raise NotImplementedError('fontDescent') + + #------------- drawing helpers -------------- - def arcPoints(self, x1,y1, x2,y2, startAng=0, extent=360): - "Return a list of points approximating the given arc." - # Note: this implementation is simple and not particularly efficient. - xScale = abs((x2-x1)/2.0) - yScale = abs((y2-y1)/2.0) - - x = min(x1,x2)+xScale - y = min(y1,y2)+yScale - - # "Guesstimate" a proper number of points for the arc: - steps = min(max(xScale,yScale)*(extent/10.0)/10,200) - if steps < 5: steps = 5 - - from math import sin, cos, pi - - pointlist = [] - step = float(extent)/steps - angle = startAng - for i in range(int(steps+1)): - point = (x+xScale*cos((angle/180.0)*pi), - y-yScale*sin((angle/180.0)*pi)) - pointlist.append(point) - angle = angle+step - - return pointlist - - def curvePoints(self, x1, y1, x2, y2, x3, y3, x4, y4): - "Return a list of points approximating the given Bezier curve." - - # Adapted from BEZGEN3.HTML, one of the many - # Bezier utilities found on Don Lancaster's Guru's Lair at - # - bezierSteps = min(max(max(x1,x2,x3,x4)-min(x1,x2,x3,x3), - max(y1,y2,y3,y4)-min(y1,y2,y3,y4)), - 200) - - dt1 = 1. / bezierSteps - dt2 = dt1 * dt1 - dt3 = dt2 * dt1 - - xx = x1 - yy = y1 - ux = uy = vx = vy = 0 - - ax = x4 - 3*x3 + 3*x2 - x1 - ay = y4 - 3*y3 + 3*y2 - y1 - bx = 3*x3 - 6*x2 + 3*x1 - by = 3*y3 - 6*y2 + 3*y1 - cx = 3*x2 - 3*x1 - cy = 3*y2 - 3*y1 - - mx1 = ax * dt3 - my1 = ay * dt3 - - lx1 = bx * dt2 - ly1 = by * dt2 - - kx = mx1 + lx1 + cx*dt1 - ky = my1 + ly1 + cy*dt1 - - mx = 6*mx1 - my = 6*my1 - - lx = mx + 2*lx1 - ly = my + 2*ly1 - - pointList = [(xx, yy)] - - for i in range(bezierSteps): - xx = xx + ux + kx - yy = yy + uy + ky - ux = ux + vx + lx - uy = uy + vy + ly - vx = vx + mx - vy = vy + my - pointList.append((xx, yy)) - - return pointList + def arcPoints(self, x1,y1, x2,y2, startAng=0, extent=360): + "Return a list of points approximating the given arc." + # Note: this implementation is simple and not particularly efficient. + xScale = abs((x2-x1)/2.0) + yScale = abs((y2-y1)/2.0) + + x = min(x1,x2)+xScale + y = min(y1,y2)+yScale + + # "Guesstimate" a proper number of points for the arc: + steps = min(max(xScale,yScale)*(extent/10.0)/10,200) + if steps < 5: steps = 5 + + from math import sin, cos, pi + + pointlist = [] + step = float(extent)/steps + angle = startAng + for i in range(int(steps+1)): + point = (x+xScale*cos((angle/180.0)*pi), + y-yScale*sin((angle/180.0)*pi)) + pointlist.append(point) + angle = angle+step + + return pointlist + + def curvePoints(self, x1, y1, x2, y2, x3, y3, x4, y4): + "Return a list of points approximating the given Bezier curve." + + # Adapted from BEZGEN3.HTML, one of the many + # Bezier utilities found on Don Lancaster's Guru's Lair at + # + bezierSteps = min(max(max(x1,x2,x3,x4)-min(x1,x2,x3,x3), + max(y1,y2,y3,y4)-min(y1,y2,y3,y4)), + 200) + + dt1 = 1. / bezierSteps + dt2 = dt1 * dt1 + dt3 = dt2 * dt1 + + xx = x1 + yy = y1 + ux = uy = vx = vy = 0 + + ax = x4 - 3*x3 + 3*x2 - x1 + ay = y4 - 3*y3 + 3*y2 - y1 + bx = 3*x3 - 6*x2 + 3*x1 + by = 3*y3 - 6*y2 + 3*y1 + cx = 3*x2 - 3*x1 + cy = 3*y2 - 3*y1 + + mx1 = ax * dt3 + my1 = ay * dt3 + + lx1 = bx * dt2 + ly1 = by * dt2 + + kx = mx1 + lx1 + cx*dt1 + ky = my1 + ly1 + cy*dt1 + + mx = 6*mx1 + my = 6*my1 + + lx = mx + 2*lx1 + ly = my + 2*ly1 + + pointList = [(xx, yy)] + + for i in range(bezierSteps): + xx = xx + ux + kx + yy = yy + uy + ky + ux = ux + vx + lx + uy = uy + vy + ly + vx = vx + mx + vy = vy + my + pointList.append((xx, yy)) + + return pointList - def drawMultiLineString(self, s, x,y, font=None, color=None, angle=0, - **kwargs): - "Breaks string into lines (on \n, \r, \n\r, or \r\n), and calls drawString on each." - import math - import string - h = self.fontHeight(font) - dy = h * math.cos(angle*math.pi/180.0) - dx = h * math.sin(angle*math.pi/180.0) - s = string.replace(s, '\r\n', '\n') - s = string.replace(s, '\n\r', '\n') - s = string.replace(s, '\r', '\n') - lines = string.split(s, '\n') - for line in lines: - self.drawString(line, x, y, font, color, angle) - x = x + dx - y = y + dy + def drawMultiLineString(self, s, x,y, font=None, color=None, angle=0, + **kwargs): + "Breaks string into lines (on \n, \r, \n\r, or \r\n), and calls drawString on each." + import math + import string + h = self.fontHeight(font) + dy = h * math.cos(angle*math.pi/180.0) + dx = h * math.sin(angle*math.pi/180.0) + s = string.replace(s, '\r\n', '\n') + s = string.replace(s, '\n\r', '\n') + s = string.replace(s, '\r', '\n') + lines = string.split(s, '\n') + for line in lines: + self.drawString(line, x, y, font, color, angle) + x = x + dx + y = y + dy - #------------- drawing methods -------------- + #------------- drawing methods -------------- - # Note default parameters "=None" means use the defaults - # set in the Canvas method: defaultLineColor, etc. + # Note default parameters "=None" means use the defaults + # set in the Canvas method: defaultLineColor, etc. - def drawLine(self, x1,y1, x2,y2, color=None, width=None, dash=None, - **kwargs): - "Draw a straight line between x1,y1 and x2,y2." - raise NotImplementedError, 'drawLine' - - def drawLines(self, lineList, color=None, width=None, dash=None, - **kwargs): - "Draw a set of lines of uniform color and width. \ - lineList: a list of (x1,y1,x2,y2) line coordinates." - # default implementation: - for x1, y1, x2, y2 in lineList: - self.drawLine(x1, y1, x2, y2 ,color,width, - dash=dash,**kwargs) - + def drawLine(self, x1,y1, x2,y2, color=None, width=None, dash=None, + **kwargs): + "Draw a straight line between x1,y1 and x2,y2." + raise NotImplementedError('drawLine') + + def drawLines(self, lineList, color=None, width=None, dash=None, + **kwargs): + "Draw a set of lines of uniform color and width. \ + lineList: a list of (x1,y1,x2,y2) line coordinates." + # default implementation: + for x1, y1, x2, y2 in lineList: + self.drawLine(x1, y1, x2, y2 ,color,width, + dash=dash,**kwargs) + - # For text, color defaults to self.lineColor. - - def drawString(self, s, x,y, font=None, color=None, angle=0, - **kwargs): - "Draw a string starting at location x,y." - # NOTE: the baseline goes on y; drawing covers (y-ascent,y+descent) - raise NotImplementedError, 'drawString' + # For text, color defaults to self.lineColor. + + def drawString(self, s, x,y, font=None, color=None, angle=0, + **kwargs): + "Draw a string starting at location x,y." + # NOTE: the baseline goes on y; drawing covers (y-ascent,y+descent) + raise NotImplementedError('drawString') - # For fillable shapes, edgeColor defaults to self.defaultLineColor, - # edgeWidth defaults to self.defaultLineWidth, and - # fillColor defaults to self.defaultFillColor. - # Specify "don't fill" by passing fillColor=transparent. + # For fillable shapes, edgeColor defaults to self.defaultLineColor, + # edgeWidth defaults to self.defaultLineWidth, and + # fillColor defaults to self.defaultFillColor. + # Specify "don't fill" by passing fillColor=transparent. - def drawCurve(self, x1,y1, x2,y2, x3,y3, x4,y4, - edgeColor=None, edgeWidth=None, fillColor=None, closed=0, - dash=None,**kwargs): - "Draw a Bezier curve with control points x1,y1 to x4,y4." - pointlist = self.curvePoints(x1, y1, x2, y2, x3, y3, x4, y4) - self.drawPolygon(pointlist, - edgeColor=edgeColor, - edgeWidth=edgeWidth, - fillColor=fillColor, closed=closed,dash=dash, - **kwargs) + def drawCurve(self, x1,y1, x2,y2, x3,y3, x4,y4, + edgeColor=None, edgeWidth=None, fillColor=None, closed=0, + dash=None,**kwargs): + "Draw a Bezier curve with control points x1,y1 to x4,y4." + pointlist = self.curvePoints(x1, y1, x2, y2, x3, y3, x4, y4) + self.drawPolygon(pointlist, + edgeColor=edgeColor, + edgeWidth=edgeWidth, + fillColor=fillColor, closed=closed,dash=dash, + **kwargs) - + - def drawRect(self, x1,y1, x2,y2, edgeColor=None, edgeWidth=None, fillColor=None, dash=None, **kwargs): - "Draw the rectangle between x1,y1, and x2,y2. \ - These should have x10, and ry>0." + def drawRoundRect(self, x1,y1, x2,y2, rx=8, ry=8, + edgeColor=None, edgeWidth=None, + fillColor=None,dash=None,**kwargs): + "Draw a rounded rectangle between x1,y1, and x2,y2, \ + with corners inset as ellipses with x radius rx and y radius ry. \ + These should have x10, and ry>0." - x1, x2 = min(x1,x2), max(x1, x2) - y1, y2 = min(y1,y2), max(y1, y2) - - dx = rx*2 - dy = ry*2 - - partList = [ - (figureArc, x1, y1, x1+dx, y1+dy, 180, -90), - (figureLine, x1+rx, y1, x2-rx, y1), - (figureArc, x2-dx, y1, x2, y1+dy, 90, -90), - (figureLine, x2, y1+ry, x2, y2-ry), - (figureArc, x2-dx, y2, x2, y2-dy, 0, -90), - (figureLine, x2-rx, y2, x1+rx, y2), - (figureArc, x1, y2, x1+dx, y2-dy, -90, -90), - (figureLine, x1, y2-ry, x1, y1+rx) - ] + x1, x2 = min(x1,x2), max(x1, x2) + y1, y2 = min(y1,y2), max(y1, y2) + + dx = rx*2 + dy = ry*2 + + partList = [ + (figureArc, x1, y1, x1+dx, y1+dy, 180, -90), + (figureLine, x1+rx, y1, x2-rx, y1), + (figureArc, x2-dx, y1, x2, y1+dy, 90, -90), + (figureLine, x2, y1+ry, x2, y2-ry), + (figureArc, x2-dx, y2, x2, y2-dy, 0, -90), + (figureLine, x2-rx, y2, x1+rx, y2), + (figureArc, x1, y2, x1+dx, y2-dy, -90, -90), + (figureLine, x1, y2-ry, x1, y1+rx) + ] - self.drawFigure(partList, edgeColor, edgeWidth, fillColor, - closed=1, dash=dash, **kwargs) + self.drawFigure(partList, edgeColor, edgeWidth, fillColor, + closed=1, dash=dash, **kwargs) - def drawEllipse(self, x1,y1, x2,y2, edgeColor=None, edgeWidth=None, - fillColor=None,dash=None,**kwargs): - "Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2. \ - These should have x1 2: + if ignoreFullF and incr==14 and l[0].find('f')!=-1 and len(arr) > 2: incr = 0 - if ignoreFullD and incr==10 and string.find(l[0],'d')!=-1 and len(arr) > 2: + if ignoreFullD and incr==10 and l[0].find('d')!=-1 and len(arr) > 2: incr = 0 nEl = nEl + incr return nEl if __name__ == '__main__': - print SplitComposition('Fe') - print SplitComposition('Fe3Al') - print SplitComposition('Fe99PdAl') - print SplitComposition('TiNiSiSO12P') + print(SplitComposition('Fe')) + print(SplitComposition('Fe3Al')) + print(SplitComposition('Fe99PdAl')) + print(SplitComposition('TiNiSiSO12P')) temp = ['[Xe] 4f^12 6s^2','[Xe] 4f^14 5d^6 6s^2','[Xe] 4f^14 5d^10 6s^2', '[Xe] 4f^14 5d^10 6s^2 6p^1', '[Xe] 5d^10'] - print 'ignore all' + print('ignore all') for entry in temp: - print entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=1,ignoreFullF=1) - print 'ignore d' + print(entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=1,ignoreFullF=1)) + print('ignore d') for entry in temp: - print entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=1,ignoreFullF=0) - print 'ignore f' + print(entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=1,ignoreFullF=0)) + print('ignore f') for entry in temp: - print entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=0,ignoreFullF=1) - print 'ignore None' + print(entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=0,ignoreFullF=1)) + print('ignore None') for entry in temp: - print entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=0,ignoreFullF=0) + print(entry, '\t\t\t\t', ConfigToNumElectrons(entry,ignoreFullD=0,ignoreFullF=0)) diff --git a/rdkit/utils/fileutils.py b/rdkit/utils/fileutils.py index e78d71236..07c0f63e7 100755 --- a/rdkit/utils/fileutils.py +++ b/rdkit/utils/fileutils.py @@ -5,10 +5,8 @@ """ utility functions to help work with files """ -import string -import exceptions -class NoMatchFoundError(exceptions.RuntimeError): +class NoMatchFoundError(RuntimeError): pass def MoveToMatchingLine(inFile,matchStr,fullMatch=0): @@ -35,7 +33,7 @@ def MoveToMatchingLine(inFile,matchStr,fullMatch=0): inLine = inFile.readline() matched = 0 while not matched and inLine: - idx = string.find(inLine,matchStr) + idx = inLine.find(matchStr) if (fullMatch and idx == 0) or (not fullMatch and idx > -1): matched = 1 else: @@ -43,7 +41,7 @@ def MoveToMatchingLine(inFile,matchStr,fullMatch=0): if matched: return inLine else: - raise NoMatchFoundError,matchStr + raise NoMatchFoundError(matchStr)