From b53ee20b49bb3dce24486b73fa1ef7d69f9a9e84 Mon Sep 17 00:00:00 2001 From: Eisuke Kawashima Date: Thu, 10 Mar 2022 14:55:18 +0900 Subject: [PATCH] Fix Flake8 erorrs (#4252) * Fix PEP8 [E101](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E502](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E703](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E711](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E712](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E713](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [E722](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) * Fix PEP8 [W605](https://github.com/PyCQA/pycodestyle/blob/2.8.0/docs/intro.rst#error-codes) --- .../ChemReactions/Wrap/testEnumerations.py | 14 +- .../ChemReactions/Wrap/testSanitize.py | 2 +- .../Descriptors/Wrap/testMolDescriptors.py | 16 +- Code/GraphMol/Descriptors/test3D.py | 2 +- Code/GraphMol/Descriptors/test3D_old.py | 108 +++---- Code/GraphMol/FMCS/Wrap/testFMCS.py | 4 +- .../GraphMol/FilterCatalog/Wrap/rough_test.py | 2 +- Code/GraphMol/MolAlign/Wrap/testMolAlign.py | 2 +- Code/GraphMol/MolDraw2D/Wrap/testMolDraw2D.py | 2 +- .../MolStandardize/Wrap/testMolStandardize.py | 2 +- .../MolTransforms/Wrap/testMolTransforms.py | 4 +- Code/GraphMol/Wrap/rough_test.py | 54 ++-- Code/GraphMol/Wrap/testTrajectory.py | 34 +- Code/JavaWrappers/parse_doxy_html.py | 70 ++--- Code/SimDivPickers/Wrap/testPickers.py | 6 +- .../AtomAtomPathSimilarity.py | 2 +- Contrib/FreeWilson/freewilson.py | 2 +- Contrib/Glare/glare.py | 2 +- Contrib/M_Kossner/Frames.py | 18 +- .../assignSubstructureFilters.py | 6 +- .../RxnRoleAssignment/identifyReactants.py | 18 +- Contrib/fraggle/atomcontrib.py | 4 +- Contrib/fraggle/cxn_tversky.py | 2 +- Contrib/fraggle/fraggle.py | 2 +- Contrib/fraggle/rdkit_tversky.py | 2 +- Contrib/mmpa/cansmirk.py | 6 +- Contrib/mmpa/create_mmp_db.py | 6 +- Contrib/mmpa/indexing.py | 20 +- Contrib/mmpa/mol_transform.py | 4 +- Contrib/mmpa/rfrag.py | 32 +- Contrib/mmpa/search_mmp_db.py | 10 +- Contrib/pzc/p_con.py | 8 +- Docs/Book/data/test_multi_colours.py | 2 +- External/AvalonTools/Wrap/testAvalonTools.py | 8 +- External/FreeSASA/Wrap/testFreeSASA.py | 4 +- Scripts/run_python_tests.py | 2 +- build_support/pkg_version.py | 4 +- rdkit/Chem/ChemUtils/DescriptorUtilities.py | 2 +- rdkit/Chem/ChemUtils/TemplateExpand.py | 2 +- rdkit/Chem/Draw/IPythonConsole.py | 2 +- rdkit/Chem/Draw/cairoCanvas.py | 2 +- rdkit/Chem/Features/UnitTestFeatDirUtilsRD.py | 292 +++++++++--------- rdkit/Chem/MolDb/Loader_sa.py | 2 +- rdkit/Chem/MolKey/MolKey.py | 2 +- rdkit/Chem/PandasTools.py | 6 +- rdkit/Chem/Recap.py | 2 +- rdkit/Chem/UnitTestEnumerateHeterocycles.py | 2 +- rdkit/DataStructs/UnitTestBitEnsemble.py | 2 +- rdkit/Dbase/StorageUtils.py | 2 +- rdkit/Dbase/UnitTestDbConnect.py | 2 +- rdkit/Dbase/UnitTestDbUtils.py | 4 +- rdkit/Dbase/UnitTestStorageUtils.py | 2 +- rdkit/__init__.py | 2 +- rdkit/sping/PDF/pdfdoc.py | 2 +- rdkit/sping/PDF/pidPDF.py | 2 +- rdkit/sping/PIL/pidPIL.py | 6 +- rdkit/sping/PS/pidPS.py | 2 +- rdkit/sping/ReportLab/pidReportLab.py | 2 +- rdkit/sping/SVG/pidSVG.py | 14 +- rdkit/sping/WX/pidWX.py | 2 +- rdkit/sping/stringformat.py | 2 +- rdkit/sping/tests/pidtest.py | 4 +- rdkit/sping/util/HTMLPiddler.py | 4 +- 63 files changed, 427 insertions(+), 427 deletions(-) diff --git a/Code/GraphMol/ChemReactions/Wrap/testEnumerations.py b/Code/GraphMol/ChemReactions/Wrap/testEnumerations.py index a9a520692..944817b4e 100644 --- a/Code/GraphMol/ChemReactions/Wrap/testEnumerations.py +++ b/Code/GraphMol/ChemReactions/Wrap/testEnumerations.py @@ -52,7 +52,7 @@ class TestCase(unittest.TestCase) : def testCartesianProduct(self): log("testCartesianProduct") - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() rgroups = [[Chem.MolFromSmiles("C")]*10, [Chem.MolFromSmiles("N")]*5, [Chem.MolFromSmiles("O")]*6] @@ -78,7 +78,7 @@ class TestCase(unittest.TestCase) : rgroups = [[Chem.MolFromSmiles("C")]*10, [Chem.MolFromSmiles("N")]*5, [Chem.MolFromSmiles("O")]*6] - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() randProd = rdChemReactions.RandomSampleStrategy() randProd.Initialize(rxn, rgroups) @@ -101,7 +101,7 @@ class TestCase(unittest.TestCase) : def testRandomSampleAllBBs(self): log("testRandomSampleAllBBs") - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() rgroups = [[Chem.MolFromSmiles("C")]*10, [Chem.MolFromSmiles("N")]*5, [Chem.MolFromSmiles("O")]*6] @@ -129,7 +129,7 @@ class TestCase(unittest.TestCase) : def testTimings(self): log("testTimings") - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() rgroups = [[Chem.MolFromSmiles("C")]*17000, [Chem.MolFromSmiles("N")]*50000, @@ -146,13 +146,13 @@ class TestCase(unittest.TestCase) : print("%s Skipped %s in %s seconds"%(r, num, t2-t1)) def testEvenPairsSampling(self): - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() rgroups = [[Chem.MolFromSmiles("C")]*10, [Chem.MolFromSmiles("N")]*10, [Chem.MolFromSmiles("O")]*10] - rxn = rdChemReactions.ChemicalReaction(); + rxn = rdChemReactions.ChemicalReaction() count = 0 pairs01 = {} pairs12 = {} @@ -575,7 +575,7 @@ class TestCase(unittest.TestCase) : self.assertEquals([], list(enumerator)) def testRemoveInsaneReagents(self): - rxndata = "$RXN\nUntitled Document-1\n ChemDraw10291618492D\n\n 3 1\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.4125 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0\n -0.4125 0.0000 0.0000 R2 0 0 0 0 0 0 0 0 0 2 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n -0.4125 0.0000 0.0000 R1 0 0 0 0 0 0 0 0 0 1 0 0\n 0.4125 0.0000 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.4125 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 5 0 0\n -0.4125 0.0000 0.0000 R4 0 0 0 0 0 0 0 0 0 4 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 14 15 0 0 0 0 0 0 0 0999 V2000\n 0.5072 -0.5166 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 0.5072 0.3084 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2949 -0.7616 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.7817 -0.0880 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2967 0.5794 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.5558 -1.5443 0.0000 R1 0 0 0 0 0 0 0 0 0 1 0 0\n -0.2073 0.7208 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.9218 0.3083 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.9217 -0.5167 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.2073 -0.9292 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -1.6362 0.7208 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0\n 1.5452 1.3661 0.0000 N 0 0 0 0 0 0 0 0 0 5 0 0\n 2.3507 1.5443 0.0000 R4 0 0 0 0 0 0 0 0 0 4 0 0\n -2.3507 0.3083 0.0000 R2 0 0 0 0 0 0 0 0 0 2 0 0\n 1 2 2 0 0\n 1 3 1 0 0\n 3 4 1 0 0\n 4 5 1 0 0\n 5 2 1 0 0\n 3 6 1 0 0\n 2 7 1 0 0\n 7 8 2 0 0\n 8 9 1 0 0\n 9 10 2 0 0\n 10 1 1 0 0\n 8 11 1 0 0\n 12 13 1 0 0\n 11 14 1 0 0\n 12 5 1 0 0\nM END\n"; + rxndata = "$RXN\nUntitled Document-1\n ChemDraw10291618492D\n\n 3 1\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.4125 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0\n -0.4125 0.0000 0.0000 R2 0 0 0 0 0 0 0 0 0 2 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n -0.4125 0.0000 0.0000 R1 0 0 0 0 0 0 0 0 0 1 0 0\n 0.4125 0.0000 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 2 1 0 0 0 0 0 0 0 0999 V2000\n 0.4125 0.0000 0.0000 N 0 0 0 0 0 0 0 0 0 5 0 0\n -0.4125 0.0000 0.0000 R4 0 0 0 0 0 0 0 0 0 4 0 0\n 1 2 1 0 0\nM END\n$MOL\n\n\n\n 14 15 0 0 0 0 0 0 0 0999 V2000\n 0.5072 -0.5166 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 0.5072 0.3084 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2949 -0.7616 0.0000 N 0 0 0 0 0 0 0 0 0 0 0 0\n 1.7817 -0.0880 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.2967 0.5794 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n 1.5558 -1.5443 0.0000 R1 0 0 0 0 0 0 0 0 0 1 0 0\n -0.2073 0.7208 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.9218 0.3083 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.9217 -0.5167 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -0.2073 -0.9292 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n -1.6362 0.7208 0.0000 N 0 0 0 0 0 0 0 0 0 3 0 0\n 1.5452 1.3661 0.0000 N 0 0 0 0 0 0 0 0 0 5 0 0\n 2.3507 1.5443 0.0000 R4 0 0 0 0 0 0 0 0 0 4 0 0\n -2.3507 0.3083 0.0000 R2 0 0 0 0 0 0 0 0 0 2 0 0\n 1 2 2 0 0\n 1 3 1 0 0\n 3 4 1 0 0\n 4 5 1 0 0\n 5 2 1 0 0\n 3 6 1 0 0\n 2 7 1 0 0\n 7 8 2 0 0\n 8 9 1 0 0\n 9 10 2 0 0\n 10 1 1 0 0\n 8 11 1 0 0\n 12 13 1 0 0\n 11 14 1 0 0\n 12 5 1 0 0\nM END\n" rxn = AllChem.ReactionFromRxnBlock(rxndata) bbs = [] diff --git a/Code/GraphMol/ChemReactions/Wrap/testSanitize.py b/Code/GraphMol/ChemReactions/Wrap/testSanitize.py index 1ca1e0122..bcb4de165 100644 --- a/Code/GraphMol/ChemReactions/Wrap/testSanitize.py +++ b/Code/GraphMol/ChemReactions/Wrap/testSanitize.py @@ -295,7 +295,7 @@ class TestCase(unittest.TestCase) : print(AllChem.ReactionToRxnBlock(rxnb)) self.assertEquals(res, good_res) assert not status == "fail" - except: + except Exception: print ("$RXN Failed") if status == "fail": continue diff --git a/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py b/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py index 24c494452..76986af59 100644 --- a/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py +++ b/Code/GraphMol/Descriptors/Wrap/testMolDescriptors.py @@ -24,23 +24,23 @@ class TestCase(unittest.TestCase): def testAtomPairTypes(self): params = rdMD.AtomPairsParameters mol = Chem.MolFromSmiles("C=C") - self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ + self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))== rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(1))) - self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))==\ + self.assertTrue(rdMD.GetAtomPairAtomCode(mol.GetAtomWithIdx(0))== 1 | (1 | 1< try: Chem.ReplaceCore(mol, smarts, (3, )) self.asssertFalse(True) - except: + except Exception: pass mol = Chem.MolFromSmiles("C") @@ -2222,7 +2222,7 @@ CAS<~> try: Chem.ReplaceCore(mol, smarts, (0, 0)) self.asssertFalse(True) - except: + except Exception: pass def test47RWMols(self): @@ -2730,17 +2730,17 @@ CAS<~> def test64MoleculeCleanup(self): m = Chem.MolFromSmiles('CN(=O)=O', False) self.assertTrue(m) - self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==0 and \ - m.GetAtomWithIdx(2).GetFormalCharge()==0 and \ + self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==0 and + m.GetAtomWithIdx(2).GetFormalCharge()==0 and m.GetAtomWithIdx(3).GetFormalCharge()==0) - self.assertTrue(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.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==1 and \ - (m.GetAtomWithIdx(2).GetFormalCharge()==-1 or \ + self.assertTrue(m.GetAtomWithIdx(1).GetFormalCharge()==1 and + (m.GetAtomWithIdx(2).GetFormalCharge()==-1 or m.GetAtomWithIdx(3).GetFormalCharge()==-1)) - self.assertTrue(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): @@ -3856,9 +3856,9 @@ CAS<~> self.assertFalse(resMolSuppl.GetIsEnumerated()) resMolSuppl.Enumerate() self.assertTrue(resMolSuppl.GetIsEnumerated()) - self.assertTrue((resMolSuppl[0].GetBondBetweenAtoms(0, 1).GetBondType() \ + self.assertTrue((resMolSuppl[0].GetBondBetweenAtoms(0, 1).GetBondType() != resMolSuppl[1].GetBondBetweenAtoms(0, 1).GetBondType()) - or (resMolSuppl[0].GetBondBetweenAtoms(9, 10).GetBondType() \ + or (resMolSuppl[0].GetBondBetweenAtoms(9, 10).GetBondType() != resMolSuppl[1].GetBondBetweenAtoms(9, 10).GetBondType())) resMolSuppl = Chem.ResonanceMolSupplier(mol, Chem.KEKULE_ALL) @@ -3871,8 +3871,8 @@ CAS<~> bondTypeDict = {} resMolSuppl = Chem.ResonanceMolSupplier(mol, - Chem.ALLOW_INCOMPLETE_OCTETS \ - | Chem.UNCONSTRAINED_CATIONS \ + Chem.ALLOW_INCOMPLETE_OCTETS + | Chem.UNCONSTRAINED_CATIONS | Chem.UNCONSTRAINED_ANIONS) self.assertEqual(len(resMolSuppl), 32) for i in range(len(resMolSuppl)): @@ -3885,8 +3885,8 @@ CAS<~> cmpFormalChargeBondOrder(self, resMolSuppl[0], next(resMolSuppl)) resMolSuppl = Chem.ResonanceMolSupplier(mol, - Chem.ALLOW_INCOMPLETE_OCTETS \ - | Chem.UNCONSTRAINED_CATIONS \ + Chem.ALLOW_INCOMPLETE_OCTETS + | Chem.UNCONSTRAINED_CATIONS | Chem.UNCONSTRAINED_ANIONS, 10) self.assertEqual(len(resMolSuppl), 10) @@ -5268,7 +5268,7 @@ M END # simple check, this used to throw an exception try: Chem.MolToSmarts(Chem.MolFromSmarts("[C@]")) - except: + except Exception: self.fail("[C@] caused an exception when roundtripping smarts") def testGetEnhancedStereo(self): @@ -6485,7 +6485,7 @@ M END a = Chem.MolFromSmiles("[C@H]([Xe])(F)([V])") b = Chem.MolFromSmiles("[Xe]N.[V]I") p = Chem.MolzipParams() - p.label = Chem.MolzipLabel.AtomType; + p.label = Chem.MolzipLabel.AtomType p.setAtomSymbols(["Xe", "V"]) c = Chem.molzip(a, b, p) self.assertEqual(Chem.MolToSmiles(c), "N[C@@H](F)I") @@ -6621,7 +6621,7 @@ CAS<~> with Chem.RWMol(mol) as rwmol: rwmol.RemoveAtom(2) rwmol.RemoveAtom(6) - except: + except Exception: pass self.assertEqual(rwmol.GetNumAtoms(), mol.GetNumAtoms()) diff --git a/Code/GraphMol/Wrap/testTrajectory.py b/Code/GraphMol/Wrap/testTrajectory.py index d380b9f1d..e4b5c3a44 100644 --- a/Code/GraphMol/Wrap/testTrajectory.py +++ b/Code/GraphMol/Wrap/testTrajectory.py @@ -23,14 +23,14 @@ class TestCase(unittest.TestCase): e = False try: s.GetPoint2D(12) - except: + except Exception: e = True self.assertTrue(e) s = Snapshot([0.0, 0.0, 0.0]) e = False try: s.GetPoint2D(0) - except: + except Exception: e = True self.assertTrue(e) @@ -50,13 +50,13 @@ class TestCase(unittest.TestCase): e = False try: traj.GetSnapshot(ns) - except: + except Exception: e = True self.assertTrue(e) e = False try: traj.GetSnapshot(0).GetPoint2D(np) - except: + except Exception: e = True self.assertTrue(e) for i in range(np): @@ -65,7 +65,7 @@ class TestCase(unittest.TestCase): e = False try: self.assertAlmostEqual(traj.GetSnapshot(0).GetPoint3D(i).z, 0.0) - except: + except Exception: e = True self.assertFalse(e) for i in range(ns): @@ -101,13 +101,13 @@ class TestCase(unittest.TestCase): e = False try: traj.GetSnapshot(ns) - except: + except Exception: e = True self.assertTrue(e) e = False try: traj.GetSnapshot(0).GetPoint2D(np) - except: + except Exception: e = True self.assertTrue(e) for i in range(np): @@ -118,7 +118,7 @@ class TestCase(unittest.TestCase): e = False try: traj.GetSnapshot(0).GetPoint2D(i) - except: + except Exception: e = True self.assertTrue(e) for i in range(ns): @@ -145,14 +145,14 @@ class TestCase(unittest.TestCase): ok = False try: ReadAmberTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) traj = Trajectory(3, 3) ok = False try: ReadAmberTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) fName = os.path.join(rdbase, 'Code', 'GraphMol', 'test_data', 'water_coords_bad2.trx') @@ -160,7 +160,7 @@ class TestCase(unittest.TestCase): try: traj = Trajectory(3, 3) ReadAmberTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) fName = os.path.join(rdbase, 'Code', 'GraphMol', 'test_data', 'water_coords.trx') @@ -227,14 +227,14 @@ class TestCase(unittest.TestCase): ok = False try: ReadGromosTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) traj = Trajectory(3, 3) ok = False try: ReadGromosTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) fName = os.path.join(rdbase, 'Code', 'GraphMol', 'test_data', 'water_coords_bad2.trc') @@ -242,7 +242,7 @@ class TestCase(unittest.TestCase): try: traj = Trajectory(3, 3) ReadGromosTrajectory(fName, traj) - except: + except Exception: ok = True self.assertTrue(ok) fName = os.path.join(rdbase, 'Code', 'GraphMol', 'test_data', 'water_coords.trc') @@ -435,7 +435,7 @@ class TestCase(unittest.TestCase): e = False try: traj.GetSnapshot(0) - except: + except Exception: e = True self.assertTrue(e) @@ -456,7 +456,7 @@ class TestCase(unittest.TestCase): e = False try: traj.AddConformersToMol(mol, 1) - except: + except Exception: e = True self.assertTrue(e) self.assertEqual(mol.GetNumConformers(), 0) @@ -489,7 +489,7 @@ class TestCase(unittest.TestCase): e = False try: traj.AddConformersToMol(mol, 1) - except: + except Exception: e = True self.assertTrue(e) self.assertEqual(mol.GetNumConformers(), 0) diff --git a/Code/JavaWrappers/parse_doxy_html.py b/Code/JavaWrappers/parse_doxy_html.py index 45f5162fd..c1f65fbef 100644 --- a/Code/JavaWrappers/parse_doxy_html.py +++ b/Code/JavaWrappers/parse_doxy_html.py @@ -35,15 +35,15 @@ returns the perturbation order for a list of integers This value is associated with chirality. Parameters: - probe a list of bond indices. This must be the same length as our number of incoming bonds (our degree). + probe a list of bond indices. This must be the same length as our number of incoming bonds (our degree). Returns: the number of swaps required to convert the ordering of the probe list to match the order of our incoming bonds: e.g. if our incoming bond order is: [0,1,2,3] - getPerturbationOrder([1,0,2,3]) = 1 - getPerturbationOrder([1,2,3,0]) = 3 - getPerturbationOrder([1,2,0,3]) = 2 - + getPerturbationOrder([1,0,2,3]) = 1 + getPerturbationOrder([1,2,3,0]) = 3 + getPerturbationOrder([1,2,0,3]) = 2 + See the class documentation for a more detailed description of our representation of chirality. @@ -195,15 +195,15 @@ returns the perturbation order for a list of integers This value is associated with chirality. Parameters: - probe a list of bond indices. This must be the same length as our number of incoming bonds (our degree). + probe a list of bond indices. This must be the same length as our number of incoming bonds (our degree). Returns: the number of swaps required to convert the ordering of the probe list to match the order of our incoming bonds: e.g. if our incoming bond order is: [0,1,2,3] - getPerturbationOrder([1,0,2,3]) = 1 - getPerturbationOrder([1,2,3,0]) = 3 - getPerturbationOrder([1,2,0,3]) = 2 - + getPerturbationOrder([1,0,2,3]) = 1 + getPerturbationOrder([1,2,3,0]) = 3 + getPerturbationOrder([1,2,0,3]) = 2 + See the class documentation for a more detailed description of our representation of chirality. @@ -213,20 +213,20 @@ Notes: template void RDKit::Atom::getProp ( const std::string key, - T & res - ) const [inline] + T & res + ) const [inline] This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. template void RDKit::Atom::getProp ( const char * key, - T & res - ) const [inline] + T & res + ) const [inline] allows retrieval of a particular property value Parameters: - key the name under which the property should be stored. If a property is already stored under this name, it will be replaced. - res a reference to the storage location for the value. + key the name under which the property should be stored. If a property is already stored under this name, it will be replaced. + res a reference to the storage location for the value. Notes: @@ -277,23 +277,23 @@ Notes: template void RDKit::Atom::setProp ( const std::string key, - T val, - bool computed = false - ) const [inline] + T val, + bool computed = false + ) const [inline] This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. template void RDKit::Atom::setProp ( const char * key, - T val, - bool computed = false - ) const [inline] + T val, + bool computed = false + ) const [inline] sets a property value Parameters: - key the name under which the property should be stored. If a property is already stored under this name, it will be replaced. - val the value to be stored - computed (optional) allows the property to be flagged computed. + key the name under which the property should be stored. If a property is already stored under this name, it will be replaced. + val the value to be stored + computed (optional) allows the property to be flagged computed. void RDKit::Atom::updatePropertyCache ( bool strict = true ) @@ -305,12 +305,12 @@ Notes: * the current lazy properties are implicit and explicit valence ''' -_renote = re.compile('^\w*(Notes?[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) -_reparam = re.compile('^\w*(Param(?:eter)?s?[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | +_renote = re.compile(r'^\w*(Notes?[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) +_reparam = re.compile(r'^\w*(Param(?:eter)?s?[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) -_rereturn = re.compile('^\w*(Returns[:])(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) -_rereturn2 = re.compile('^\w*(Returns)\s+(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) -_reusage = re.compile('^\w*(Usage[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) +_rereturn = re.compile(r'^\w*(Returns[:])(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) +_rereturn2 = re.compile(r'^\w*(Returns)\s+(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) +_reusage = re.compile(r'^\w*(Usage[:]?)(?:.*?$)(.*?)((^\w)|\Z)', flags=(re.M | re.I | re.DOTALL)) def make_method_doc(doxy_method_text, class_name): @@ -358,7 +358,7 @@ def make_class_doc(doxy_text, class_name): def do_note(doxy_text): m1 = _renote.search(doxy_text) - if m1 != None: + if m1 is not None: repl = m1.group(0) if repl[-1] != '\n': repl = repl[:-1] @@ -375,7 +375,7 @@ def do_note(doxy_text): def do_param(doxy_text): m1 = _reparam.search(doxy_text) - if m1 != None: + if m1 is not None: repl = m1.group(0) if repl[-1] != '\n': repl = repl[:-1] @@ -390,9 +390,9 @@ def do_param(doxy_text): def do_return(doxy_text): m1 = _rereturn.search(doxy_text) - if m1 == None: + if m1 is None: m1 = _rereturn2.search(doxy_text) - if m1 != None: + if m1 is not None: repl = m1.group(0) if repl[-1] != '\n': repl = repl[:-1] @@ -407,7 +407,7 @@ def do_return(doxy_text): def do_usage(doxy_text): m1 = _reusage.search(doxy_text) - if m1 != None: + if m1 is not None: repl = m1.group(0) if repl[-1] != '\n': repl = repl[:-1] diff --git a/Code/SimDivPickers/Wrap/testPickers.py b/Code/SimDivPickers/Wrap/testPickers.py index 6b848a725..9705139a4 100755 --- a/Code/SimDivPickers/Wrap/testPickers.py +++ b/Code/SimDivPickers/Wrap/testPickers.py @@ -240,12 +240,12 @@ class TestCase(unittest.TestCase): fps.append(fp) mmp = rdSimDivPickers.MaxMinPicker() ids = list(mmp.LazyBitVectorPick(fps, len(fps), 20, seed=42)) - self.assertEqual(ids,[374,720,690,339,875,842,404,725,120,385,115,868,630,\ + self.assertEqual(ids,[374,720,690,339,875,842,404,725,120,385,115,868,630, 881,516,497,412,718,869,407]) ids = list( mmp.LazyBitVectorPick(fps, len(fps), 20, firstPicks=[374, 720, 690, 339, 875], seed=42)) - self.assertEqual(ids,[374,720,690,339,875,842,404,725,120,385,115,868,630,\ + self.assertEqual(ids,[374,720,690,339,875,842,404,725,120,385,115,868,630, 881,516,497,412,718,869,407]) def testBitVectorMaxMin4(self): @@ -259,7 +259,7 @@ class TestCase(unittest.TestCase): fps.append(fp) mmp = rdSimDivPickers.MaxMinPicker() ids, threshold = mmp.LazyBitVectorPickWithThreshold(fps, len(fps), 20, -1.0, seed=42) - self.assertEqual(list(ids),[374,720,690,339,875,842,404,725,120,385,115,868,630,\ + self.assertEqual(list(ids),[374,720,690,339,875,842,404,725,120,385,115,868,630, 881,516,497,412,718,869,407]) self.assertAlmostEqual(threshold, 0.8977, 4) diff --git a/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py b/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py index 6c5dcb85a..ffac8d606 100644 --- a/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py +++ b/Contrib/AtomAtomSimilarity/AtomAtomPathSimilarity.py @@ -224,7 +224,7 @@ def getsimmatrix(m1, m1pathintegers, m2, m2pathintegers): def AtomAtomPathSimilarity(m1, m2, m1pathintegers=None, m2pathintegers=None): '''compute the Atom Atom Path Similarity for a pair of RDKit molecules. See Gobbi et al, J. ChemInf (2015) 7:11 - the most expensive part of the calculation is computing the path integers - we can precompute these and pass them in as an argument''' + the most expensive part of the calculation is computing the path integers - we can precompute these and pass them in as an argument''' if m1pathintegers is None: m1pathintegers = getpathintegers(m1) if m2pathintegers is None: diff --git a/Contrib/FreeWilson/freewilson.py b/Contrib/FreeWilson/freewilson.py index 47bc476a3..2bc1d45ec 100644 --- a/Contrib/FreeWilson/freewilson.py +++ b/Contrib/FreeWilson/freewilson.py @@ -392,7 +392,7 @@ def _enumerate(rgroups, fw, smi = ".".join(set([g.smiles for g in groups])) try: mol = molzip(Chem.MolFromSmiles(smi)) - except: + except Exception: rejected_bad += 1 continue diff --git a/Contrib/Glare/glare.py b/Contrib/Glare/glare.py index 36424daf0..cab75917f 100755 --- a/Contrib/Glare/glare.py +++ b/Contrib/Glare/glare.py @@ -374,7 +374,7 @@ class Glare: if abs(Gt-G0) < 1e-4: Ki = 1.0 else: - Ki = (1.0 - K0) * (Gi - G0) / (Gt - G0) + K0; + Ki = (1.0 - K0) * (Gi - G0) / (Gt - G0) + K0 fraction = min(1.0, Ki) # prune the library to keep the highest occurring sidechains diff --git a/Contrib/M_Kossner/Frames.py b/Contrib/M_Kossner/Frames.py index ff40296c5..5ac6a81f1 100644 --- a/Contrib/M_Kossner/Frames.py +++ b/Contrib/M_Kossner/Frames.py @@ -43,13 +43,13 @@ def flatten(x): def GetFrame(mol, mode='Scaff'): '''return a ganeric molecule defining the reduced scaffold of the input mol. - mode can be 'Scaff' or 'RedScaff': - - Scaff -> chop off the side chains and return the scaffold - - RedScaff -> remove all linking chains and connect the rings - directly at the atoms where the linker was - ''' + mode can be 'Scaff' or 'RedScaff': + + Scaff -> chop off the side chains and return the scaffold + + RedScaff -> remove all linking chains and connect the rings + directly at the atoms where the linker was + ''' ring = mol.GetRingInfo() RingAtoms = flatten(ring.AtomRings()) @@ -75,7 +75,7 @@ def GetFrame(mol, mode='Scaff'): while len(Paths) > 0: NewPaths = [] for P in Paths: - if P == None: + if P is None: print('ooh') else: for neighbor in mol.GetAtomWithIdx(P[-1]).GetNeighbors(): @@ -130,7 +130,7 @@ def GetFrame(mol, mode='Scaff'): todel = [] NonRingAtoms.sort(reverse=True) for i in NonRingAtoms: - if i != None: + if i is not None: if i not in Framework: todel.append(i) em = Chem.EditableMol(mol) diff --git a/Contrib/NIBRSubstructureFilters/assignSubstructureFilters.py b/Contrib/NIBRSubstructureFilters/assignSubstructureFilters.py index c1e0efc2f..1b46776c0 100644 --- a/Contrib/NIBRSubstructureFilters/assignSubstructureFilters.py +++ b/Contrib/NIBRSubstructureFilters/assignSubstructureFilters.py @@ -87,7 +87,7 @@ def assignFilters(data, nameSmilesColumn='smiles'): NO_filter = 'no_oxygen_or_nitrogen' else: NO_filter = 'no match' - except: + except Exception: print("Failed on compound {0}\n".format(smi)) pass results.append(FilterMatch(qc,NO_filter,fracNO,co,sm,sc)) @@ -106,7 +106,7 @@ if __name__ == "__main__": datafile = args.data try: data = pd.read_csv(datafile) - except: + except Exception: if args.verbose: print('Data could not be read. Please check your file.') sys.exit() @@ -117,7 +117,7 @@ if __name__ == "__main__": print('---> Apply filters to data') try: results = assignFilters(data, nameSmilesColumn=smiCol) - except: + except Exception: if args.verbose: print('Smiles column does not exist. Please check.') sys.exit() diff --git a/Contrib/RxnRoleAssignment/identifyReactants.py b/Contrib/RxnRoleAssignment/identifyReactants.py index 4d927433c..256b21aee 100644 --- a/Contrib/RxnRoleAssignment/identifyReactants.py +++ b/Contrib/RxnRoleAssignment/identifyReactants.py @@ -182,13 +182,13 @@ def _calcScore(reactantFP,productFP,bitInfoProd=None,output=False): return [score,numUnmappedPBits,numUnmappedPAtoms,bitsUnmappedPAtoms] # Set of frequent reagents derived from all patent reactions -frequentReagents = set(['CCN(CC)CC', '[Li+]', '[Na+]', 'O=C(O)CC(O)(CC(=O)O)C(=O)O', 'O=S(=O)(O)O', 'CN1CCCC1=O', 'CCN(C(C)C)C(C)C',\ - 'c1ccncc1', '[K]', 'CC(C)(C)O', 'CCO', 'Cc1ccc(S(=O)(=O)O)cc1', 'ClC(Cl)(Cl)Cl', '[Na]', 'CC(C)(C)[O-]', 'O=C([O-])O', 'COCCOC', '[NH4+]',\ - 'CC(C)OC(C)C', 'O=C([O-])[O-]', 'CC(=O)OC(C)=O', 'O=C=O', '[Cl-]', 'c1ccc(P(c2ccccc2)c2ccccc2)cc1', '[H-]', 'N#N', 'CN1CCOCC1',\ - 'C1COCCO1', 'c1ccccc1', '[Cs+]', '[K+]', '[OH-]', 'CCCCCC', 'CCCCC', 'CN(C)C=O', 'C[O-]', 'Cc1ccccc1', 'C1CCC2=NCCCN2CC1', 'CO',\ - 'CCCCO', 'O=C(O)C(F)(F)F', 'O=P([O-])([O-])[O-]', 'CCOC(C)=O', '[Mg+2]', 'C1CCCCC1', 'O', 'N', 'II', 'O=CO', 'CC(=O)N(C)C', 'CC(=O)O',\ - 'CCOCC', 'CC(C)O', 'C[Si](C)(C)Cl', 'Cc1ccccc1C', 'CC(C)=O', 'CS(=O)(=O)O', 'CN(C)c1ccncc1', 'Cl', 'ClCCCl', 'O=S(Cl)Cl', 'ClC(Cl)Cl',\ - '[Li]CCCC', '[Pd]', '[H][H]', '[Br-]', 'CS(C)=O', 'COC(C)(C)C', 'O=S(=O)([O-])[O-]', 'CC(Cl)Cl', 'CC(=O)[O-]', 'CCCC[N+](CCCC)(CCCC)CCCC',\ +frequentReagents = set(['CCN(CC)CC', '[Li+]', '[Na+]', 'O=C(O)CC(O)(CC(=O)O)C(=O)O', 'O=S(=O)(O)O', 'CN1CCCC1=O', 'CCN(C(C)C)C(C)C', + 'c1ccncc1', '[K]', 'CC(C)(C)O', 'CCO', 'Cc1ccc(S(=O)(=O)O)cc1', 'ClC(Cl)(Cl)Cl', '[Na]', 'CC(C)(C)[O-]', 'O=C([O-])O', 'COCCOC', '[NH4+]', + 'CC(C)OC(C)C', 'O=C([O-])[O-]', 'CC(=O)OC(C)=O', 'O=C=O', '[Cl-]', 'c1ccc(P(c2ccccc2)c2ccccc2)cc1', '[H-]', 'N#N', 'CN1CCOCC1', + 'C1COCCO1', 'c1ccccc1', '[Cs+]', '[K+]', '[OH-]', 'CCCCCC', 'CCCCC', 'CN(C)C=O', 'C[O-]', 'Cc1ccccc1', 'C1CCC2=NCCCN2CC1', 'CO', + 'CCCCO', 'O=C(O)C(F)(F)F', 'O=P([O-])([O-])[O-]', 'CCOC(C)=O', '[Mg+2]', 'C1CCCCC1', 'O', 'N', 'II', 'O=CO', 'CC(=O)N(C)C', 'CC(=O)O', + 'CCOCC', 'CC(C)O', 'C[Si](C)(C)Cl', 'Cc1ccccc1C', 'CC(C)=O', 'CS(=O)(=O)O', 'CN(C)c1ccncc1', 'Cl', 'ClCCCl', 'O=S(Cl)Cl', 'ClC(Cl)Cl', + '[Li]CCCC', '[Pd]', '[H][H]', '[Br-]', 'CS(C)=O', 'COC(C)(C)C', 'O=S(=O)([O-])[O-]', 'CC(Cl)Cl', 'CC(=O)[O-]', 'CCCC[N+](CCCC)(CCCC)CCCC', 'ClCCl', 'CC#N', 'C1CCOC1', 'CCCCCCC']) @@ -235,7 +235,7 @@ def _getBestCombination(rfps,pfps,output=False): productsScaffoldFPBitInfo.update(i.bitInfoScaffoldFP) # set some initial values numUnmappedPAtoms,bitsUnmappedPAtoms = utils.getNumPositiveBitCountsOfRadius0(productsScaffoldFP,productsScaffoldFPBitInfo) - finalNumUnmappedProdAtoms=[[len(productsDetailFP.GetNonzeroElements()),\ + finalNumUnmappedProdAtoms=[[len(productsDetailFP.GetNonzeroElements()), len(productsScaffoldFP.GetNonzeroElements()),numUnmappedPAtoms,bitsUnmappedPAtoms]] for test in tests: @@ -311,7 +311,7 @@ def _findMissingReactiveReactants(rfps, pfps, currentReactants, unmappedPAtoms, if umPA[1] > 0: remainingReactants=set(range(numReactants)).difference(set(reacts)) # sort the possible reactants by the reactivity - remainingReactants = sorted(remainingReactants, key=lambda x: rfps[x].reactivity/float(rfps[x].molecule.GetNumAtoms()),\ + remainingReactants = sorted(remainingReactants, key=lambda x: rfps[x].reactivity/float(rfps[x].molecule.GetNumAtoms()), reverse=True) missingPAtoms = [] # get the missing atoms and counts diff --git a/Contrib/fraggle/atomcontrib.py b/Contrib/fraggle/atomcontrib.py index 35dcdadfb..26aeb7df2 100644 --- a/Contrib/fraggle/atomcontrib.py +++ b/Contrib/fraggle/atomcontrib.py @@ -93,7 +93,7 @@ if __name__ == '__main__': if (qID not in query_size): qMol = Chem.MolFromSmiles(qSmi) - if (qMol == None): + if qMol is None: sys.stderr.write("Can't generate mol for: %s\n" % (qSmi)) continue query_mols[qID] = qMol @@ -101,7 +101,7 @@ if __name__ == '__main__': iMol = Chem.MolFromSmiles(inSmi) - if (iMol == None): + if iMol is None: sys.stderr.write("Can't generate mol for: %s\n" % (inSmi)) continue diff --git a/Contrib/fraggle/cxn_tversky.py b/Contrib/fraggle/cxn_tversky.py index dc3c8a523..928422dc6 100644 --- a/Contrib/fraggle/cxn_tversky.py +++ b/Contrib/fraggle/cxn_tversky.py @@ -90,7 +90,7 @@ for line in q_split_input: for line in sys.stdin: - line_fields = re.split('\s|,', line) + line_fields = re.split(r'\s|,', line) dbsmi = line_fields[0] dbid = line_fields[1] diff --git a/Contrib/fraggle/fraggle.py b/Contrib/fraggle/fraggle.py index fb7e56ab6..a3c1536a2 100644 --- a/Contrib/fraggle/fraggle.py +++ b/Contrib/fraggle/fraggle.py @@ -46,7 +46,7 @@ if __name__ == '__main__': #read the STDIN for line in sys.stdin: line = line.rstrip() - smi, id_ = re.split('\s|,', line) + smi, id_ = re.split(r'\s|,', line) #print smi,id_ mol = Chem.MolFromSmiles(smi) diff --git a/Contrib/fraggle/rdkit_tversky.py b/Contrib/fraggle/rdkit_tversky.py index 933268b64..3c389d261 100644 --- a/Contrib/fraggle/rdkit_tversky.py +++ b/Contrib/fraggle/rdkit_tversky.py @@ -83,7 +83,7 @@ fragments = len(query_info) for line in sys.stdin: line = line.rstrip() - smi, id = re.split('\s|,', line) + smi, id = re.split(r'\s|,', line) #print smi,id mol = Chem.MolFromSmiles(smi) diff --git a/Contrib/mmpa/cansmirk.py b/Contrib/mmpa/cansmirk.py index 95febd132..c63617bdf 100644 --- a/Contrib/mmpa/cansmirk.py +++ b/Contrib/mmpa/cansmirk.py @@ -48,7 +48,7 @@ if __name__ == '__main__': line = line.rstrip() - line_fields = re.split('\s|,', line) + line_fields = re.split(r'\s|,', line) smirks = line_fields[0] if (len(line_fields) == 1): @@ -59,12 +59,12 @@ if __name__ == '__main__': lhs, rhs = smirks.split(">>") l = Chem.MolFromSmiles(lhs) - if (l == None): + if l is None: sys.stderr.write("Can't generate mol for: %s\n" % (lhs)) continue r = Chem.MolFromSmiles(rhs) - if (r == None): + if r is None: sys.stderr.write("Can't generate mol for: %s\n" % (rhs)) continue diff --git a/Contrib/mmpa/create_mmp_db.py b/Contrib/mmpa/create_mmp_db.py index ef647a76e..cec4626d5 100644 --- a/Contrib/mmpa/create_mmp_db.py +++ b/Contrib/mmpa/create_mmp_db.py @@ -93,7 +93,7 @@ def index_hydrogen_change(): #now cansmi it temp = Chem.MolFromSmiles(smi) - if (temp == None): + if temp is None: sys.stderr.write('Error with key: %s, Added H: %s\n' % (key, smi)) else: c_smi = Chem.MolToSmiles(temp, isomericSmiles=True) @@ -131,10 +131,10 @@ db_name = "mmp.db" pre = "mmp" #print options -if (options.maxsize != None): +if options.maxsize is not None: max_size = options.maxsize -if (options.prefix != None): +if options.prefix is not None: pre = options.prefix db_name = "%s.db" % (pre) diff --git a/Contrib/mmpa/indexing.py b/Contrib/mmpa/indexing.py index 5614366a7..feed19626 100644 --- a/Contrib/mmpa/indexing.py +++ b/Contrib/mmpa/indexing.py @@ -281,8 +281,8 @@ def switch_specific_labels_on_symmetry(smi, symmetry_class, a, b): #if the higher label comes first, fix if (int(matchObj.group(a)) > int(matchObj.group(b))): #if(int(matchObj.group(1)) > int(matchObj.group(2))): - smi = re.sub(r'\[\*\:' + matchObj.group(a) + '\]', '[*:XX' + matchObj.group(b) + 'XX]', smi) - smi = re.sub(r'\[\*\:' + matchObj.group(b) + '\]', '[*:XX' + matchObj.group(a) + 'XX]', smi) + smi = re.sub(r'\[\*\:' + matchObj.group(a) + r'\]', '[*:XX' + matchObj.group(b) + 'XX]', smi) + smi = re.sub(r'\[\*\:' + matchObj.group(b) + r'\]', '[*:XX' + matchObj.group(a) + 'XX]', smi) smi = re.sub('XX', '', smi) return smi @@ -372,7 +372,7 @@ def index_hydrogen_change(): #now cansmi it temp = Chem.MolFromSmiles(smi) - if (temp == None): + if temp is None: sys.stderr.write('Error with key: %s, Added H: %s\n' % (key, smi)) else: c_smi = Chem.MolToSmiles(temp, isomericSmiles=True) @@ -419,9 +419,9 @@ if __name__ == '__main__': (options, args) = parser.parse_args() #print options - if (options.maxsize != None): + if options.maxsize is not None: max_size = options.maxsize - elif (options.ratio != None): + elif options.ratio is not None: ratio = options.ratio if (ratio >= 1): print("Ratio specified: %s. Ratio needs to be less than 1.") @@ -442,7 +442,7 @@ if __name__ == '__main__': #of mol already calculated. If not, calculate and store cmpd_heavy = None if (use_ratio): - if ((id in id_to_heavy) == False): + if id not in id_to_heavy: id_to_heavy[id] = heavy_atom_count(smi) cmpd_heavy = id_to_heavy[id] @@ -456,7 +456,7 @@ if __name__ == '__main__': side_chains = context.split('.') #minus 1 for the attachment pt - if (add_to_index(side_chains[1], 1, cmpd_heavy) == True): + if add_to_index(side_chains[1], 1, cmpd_heavy): context = side_chains[0] core = side_chains[1] @@ -467,7 +467,7 @@ if __name__ == '__main__': index.setdefault(context, []).append(value) #minus 1 for the attachment pt - if (add_to_index(side_chains[0], 1, cmpd_heavy) == True): + if add_to_index(side_chains[0], 1, cmpd_heavy): context = side_chains[1] core = side_chains[0] @@ -482,7 +482,7 @@ if __name__ == '__main__': attachments = core.count('*') - if (add_to_index(core, attachments, cmpd_heavy) == True): + if add_to_index(core, attachments, cmpd_heavy): value = "%s;t%s" % (id, core) #add the array if no key exists @@ -524,7 +524,7 @@ if __name__ == '__main__': (id_to_smi[id_a], id_to_smi[id_b], id_a, id_b, smirks, context)) #deal with symmetry switch - if (options.sym == True): + if options.sym: smirks, context = cansmirk(core_b, core_a, key) print("%s,%s,%s,%s,%s,%s" % (id_to_smi[id_b], id_to_smi[id_a], id_b, id_a, smirks, context)) diff --git a/Contrib/mmpa/mol_transform.py b/Contrib/mmpa/mol_transform.py index 179e7fde0..95ec2c4d6 100644 --- a/Contrib/mmpa/mol_transform.py +++ b/Contrib/mmpa/mol_transform.py @@ -71,7 +71,7 @@ if __name__ == '__main__': (options, args) = parser.parse_args() #print options.transform_file - if (options.transform_file == None): + if options.transform_file is None: print("Please specify the transform file.") sys.exit(1) @@ -79,7 +79,7 @@ if __name__ == '__main__': #read the STDIN for line in sys.stdin: line = line.rstrip() - smi, id = re.split('\s|,', line) + smi, id = re.split(r'\s|,', line) #print smiles,id smiles.append((smi, id)) diff --git a/Contrib/mmpa/rfrag.py b/Contrib/mmpa/rfrag.py index 11c7fc004..789a11613 100644 --- a/Contrib/mmpa/rfrag.py +++ b/Contrib/mmpa/rfrag.py @@ -103,14 +103,14 @@ def delete_bonds(smi, id, mol, bonds, out): if (isotope == 3): valid = False for f in fragments: - matchObj = re.search('\*.*\*.*\*', f) + matchObj = re.search(r'\*.*\*.*\*', f) if matchObj: valid = True break if valid: if (isotope == 1): - fragmented_smi_noIsotopes = re.sub('\[\*\]', '[*:1]', fragmented_smi_noIsotopes) + fragmented_smi_noIsotopes = re.sub(r'\[\*\]', '[*:1]', fragmented_smi_noIsotopes) fragments = fragmented_smi_noIsotopes.split(".") @@ -121,7 +121,7 @@ def delete_bonds(smi, id, mol, bonds, out): #need to cansmi again as smiles can be different output = '%s,%s,,%s.%s' % (smi, id, Chem.MolToSmiles(s1, isomericSmiles=True), Chem.MolToSmiles(s2, isomericSmiles=True)) - if ((output in out) == False): + if output not in out: out.add(output) elif (isotope >= 2): @@ -132,9 +132,9 @@ def delete_bonds(smi, id, mol, bonds, out): fragmented_smi = Chem.MolToSmiles(modifiedMol, isomericSmiles=True) #change the isotopes into labels - currently can't add SMARTS or labels to mol - fragmented_smi = re.sub('\[1\*\]', '[*:1]', fragmented_smi) - fragmented_smi = re.sub('\[2\*\]', '[*:2]', fragmented_smi) - fragmented_smi = re.sub('\[3\*\]', '[*:3]', fragmented_smi) + fragmented_smi = re.sub(r'\[1\*\]', '[*:1]', fragmented_smi) + fragmented_smi = re.sub(r'\[2\*\]', '[*:2]', fragmented_smi) + fragmented_smi = re.sub(r'\[3\*\]', '[*:3]', fragmented_smi) fragments = fragmented_smi.split(".") @@ -153,30 +153,30 @@ def delete_bonds(smi, id, mol, bonds, out): side_chain_fragments = side_chains.split(".") for s in range(len(side_chain_fragments)): - matchObj = re.search('\[\*\:([123])\]', side_chain_fragments[s]) + matchObj = re.search(r'\[\*\:([123])\]', side_chain_fragments[s]) if matchObj: #add to isotope_track with key: old_isotope, value: isotope_track[matchObj.group(1)] = str(s + 1) #change the labels if required if (isotope_track['1'] != '1'): - core = re.sub('\[\*\:1\]', '[*:XX' + isotope_track['1'] + 'XX]', core) - side_chains = re.sub('\[\*\:1\]', '[*:XX' + isotope_track['1'] + 'XX]', side_chains) + core = re.sub(r'\[\*\:1\]', '[*:XX' + isotope_track['1'] + 'XX]', core) + side_chains = re.sub(r'\[\*\:1\]', '[*:XX' + isotope_track['1'] + 'XX]', side_chains) if (isotope_track['2'] != '2'): - core = re.sub('\[\*\:2\]', '[*:XX' + isotope_track['2'] + 'XX]', core) - side_chains = re.sub('\[\*\:2\]', '[*:XX' + isotope_track['2'] + 'XX]', side_chains) + core = re.sub(r'\[\*\:2\]', '[*:XX' + isotope_track['2'] + 'XX]', core) + side_chains = re.sub(r'\[\*\:2\]', '[*:XX' + isotope_track['2'] + 'XX]', side_chains) if (isotope == 3): if (isotope_track['3'] != '3'): - core = re.sub('\[\*\:3\]', '[*:XX' + isotope_track['3'] + 'XX]', core) - side_chains = re.sub('\[\*\:3\]', '[*:XX' + isotope_track['3'] + 'XX]', side_chains) + core = re.sub(r'\[\*\:3\]', '[*:XX' + isotope_track['3'] + 'XX]', core) + side_chains = re.sub(r'\[\*\:3\]', '[*:XX' + isotope_track['3'] + 'XX]', side_chains) #now remove the XX core = re.sub('XX', '', core) side_chains = re.sub('XX', '', side_chains) output = '%s,%s,%s,%s' % (smi, id, core, side_chains) - if ((output in out) == False): + if output not in out: out.add(output) @@ -187,7 +187,7 @@ def fragment_mol(smi, cid): #to use outlines to remove them outlines = set() - if (mol == None): + if mol is None: sys.stderr.write("Can't generate mol for: %s\n" % (smi)) else: frags = rdMMPA.FragmentMol(mol, pattern="[#6+0;!$(*=,#[!#6])]!@!=!#[*]", resultsAsMols=False) @@ -218,7 +218,7 @@ if __name__ == '__main__': line = line.rstrip() - line_fields = re.split('\s|,', line) + line_fields = re.split(r'\s|,', line) smiles = line_fields[0] cmpd_id = line_fields[1] diff --git a/Contrib/mmpa/search_mmp_db.py b/Contrib/mmpa/search_mmp_db.py index e18437f83..b539efffb 100644 --- a/Contrib/mmpa/search_mmp_db.py +++ b/Contrib/mmpa/search_mmp_db.py @@ -367,16 +367,16 @@ search_type = "mmp" db_name = "mmp.db" pre = "mmp" -if (options.maxsize != None): +if options.maxsize is not None: max_size = options.maxsize -elif (options.ratio != None): +elif options.ratio is not None: ratio = options.ratio if (ratio >= 1): print("Ratio specified: %s. Ratio needs to be less than 1.") sys.exit(1) use_ratio = True -if (options.type != None): +if options.type is not None: if ((options.type == "mmp") or (options.type == "subs") or (options.type == "trans") or (options.type == "subs_smarts") or (options.type == "trans_smarts")): search_type = options.type @@ -389,7 +389,7 @@ else: "Please specify search type. Please choose from: mmp, subs, trans, subs_smarts, trans_smarts") sys.exit(1) -if (options.prefix != None): +if options.prefix is not None: pre = options.prefix db_name = "%s.db" % (pre) @@ -410,7 +410,7 @@ cursor.execute('PRAGMA main.temp_store = MEMORY;') for line in sys.stdin: line = line.rstrip() - line_fields = re.split('\s|,', line) + line_fields = re.split(r'\s|,', line) if (len(line_fields) == 1): id = line_fields[0] diff --git a/Contrib/pzc/p_con.py b/Contrib/pzc/p_con.py index 063419a5a..c48c6ed13 100644 --- a/Contrib/pzc/p_con.py +++ b/Contrib/pzc/p_con.py @@ -87,7 +87,7 @@ class KappaResults(dict): def __init__(self, **kwds): self.update(kwds) - if not 'alpha' in self: + if 'alpha' not in self: self['alpha'] = 0.025 self['alpha_ci'] = int_ifclose(100 - 0.025 * 200)[1] @@ -458,7 +458,7 @@ class p_con: for cpd in self.sd_entries: Chem.RemoveHs(cpd) cansmi = Chem.MolToSmiles(cpd, canonical=True) - if not cansmi in all_struct_dict.keys(): + if cansmi not in all_struct_dict.keys(): all_struct_dict[cansmi] = [] all_struct_dict[cansmi].append(cpd) @@ -499,7 +499,7 @@ class p_con: result = [] IC50_dict = {} for cpd in self.sd_entries: - if not "cansmirdkit" in cpd.GetPropNames(): + if "cansmirdkit" not in cpd.GetPropNames(): Chem.RemoveHs(cpd) cansmi = Chem.MolToSmiles(cpd, canonical=True) cpd.SetProp('cansmirdkit', cansmi) @@ -1314,7 +1314,7 @@ if __name__ == "__main__": print("-h for help") sys.exit(-1) - if options.dupl == False and options.uniq == False: + if not options.dupl and not options.uniq: print("Please select uniq or dupl -h for help") print("-h for help") sys.exit(-1) diff --git a/Docs/Book/data/test_multi_colours.py b/Docs/Book/data/test_multi_colours.py index dd4a71c07..0fc719122 100644 --- a/Docs/Book/data/test_multi_colours.py +++ b/Docs/Book/data/test_multi_colours.py @@ -30,7 +30,7 @@ def get_hit_atoms_and_bonds(mol, smt): def add_colours_to_map(els, cols, col_num): for el in els: - if not el in cols: + if el not in cols: cols[el] = [] if COLS[col_num] not in cols[el]: cols[el].append(COLS[col_num]) diff --git a/External/AvalonTools/Wrap/testAvalonTools.py b/External/AvalonTools/Wrap/testAvalonTools.py index c833f5652..908814748 100755 --- a/External/AvalonTools/Wrap/testAvalonTools.py +++ b/External/AvalonTools/Wrap/testAvalonTools.py @@ -254,16 +254,16 @@ class TestCase(unittest.TestCase): m = Chem.MolFromSmiles('c1ccccc1C1(CC1)N') pyAvalonTools.Generate2DCoords(m) self.assertEqual(m.GetNumConformers(), 1) - self.assertTrue(m.GetConformer(0).Is3D() == False) + self.assertFalse(m.GetConformer(0).Is3D()) def test6(self): mb = pyAvalonTools.Generate2DCoords('c1ccccc1C1(CC1)N', True) m = Chem.MolFromMolBlock(mb) self.assertEqual(m.GetNumConformers(), 1) - self.assertTrue(m.GetConformer(0).Is3D() == False) + self.assertFalse(m.GetConformer(0).Is3D()) def testGitHub1062(self): - s0 = 'C/C=C\C' + s0 = r'C/C=C\C' m1 = Chem.MolFromSmiles(s0) s1 = Chem.MolToSmiles(m1) pyAvalonTools.Generate2DCoords(m1) @@ -275,7 +275,7 @@ class TestCase(unittest.TestCase): # repeat the test with an input smiles that is not canonical # to verify that the implementation is not sensitive to the # ordering of atoms - s0 = 'C/C=C(F)\C' + s0 = r'C/C=C(F)\C' m1 = Chem.MolFromSmiles(s0) s1 = Chem.MolToSmiles(m1) self.assertNotEqual(s1, s0) diff --git a/External/FreeSASA/Wrap/testFreeSASA.py b/External/FreeSASA/Wrap/testFreeSASA.py index 2e240e977..8b9c9036f 100644 --- a/External/FreeSASA/Wrap/testFreeSASA.py +++ b/External/FreeSASA/Wrap/testFreeSASA.py @@ -358,8 +358,8 @@ class TestCase(unittest.TestCase) : sasa = rdFreeSASA.CalcSASA(mol, radii=radii, opts=opts) self.assertTrue( (sasa-shrakerupley) < 1e-5 ) - apolar = rdFreeSASA.CalcSASA(mol, radii, query=rdFreeSASA.MakeFreeSasaAPolarAtomQuery(), opts=opts); - polar = rdFreeSASA.CalcSASA(mol, radii, query=rdFreeSASA.MakeFreeSasaPolarAtomQuery(), opts=opts); + apolar = rdFreeSASA.CalcSASA(mol, radii, query=rdFreeSASA.MakeFreeSasaAPolarAtomQuery(), opts=opts) + polar = rdFreeSASA.CalcSASA(mol, radii, query=rdFreeSASA.MakeFreeSasaPolarAtomQuery(), opts=opts) self.assertTrue( (polar + apolar - 5000.340175) < 1e-5 ) diff --git a/Scripts/run_python_tests.py b/Scripts/run_python_tests.py index a64109b3d..bdae3f719 100644 --- a/Scripts/run_python_tests.py +++ b/Scripts/run_python_tests.py @@ -15,7 +15,7 @@ if __name__ == '__main__': script = 'test_list.py' os.chdir(RDConfig.RDCodeDir) t1 = time.time() - failed,nTests = TestRunner.RunScript(script,doLongTests=False,\ + failed,nTests = TestRunner.RunScript(script,doLongTests=False, verbose=True) t2 = time.time() TestRunner.ReportResults(script,failed,nTests,t2-t1,verbose=True,dest=sys.stderr) diff --git a/build_support/pkg_version.py b/build_support/pkg_version.py index 121ee7eaf..87d0fea5a 100644 --- a/build_support/pkg_version.py +++ b/build_support/pkg_version.py @@ -28,7 +28,7 @@ for file in (root_cmakelists_path, rdkitutils_path): line = hnd.readline() while (line): # is this an uncommented set command? - m = re.match('^\s*set\s*\((\w+)\s*\"(.*)\"\s*\)', + m = re.match(r'^\s*set\s*\((\w+)\s*\"(.*)\"\s*\)', line, re.IGNORECASE) # if it is if (m is not None): @@ -40,7 +40,7 @@ for file in (root_cmakelists_path, rdkitutils_path): keepLooping = True while (keepLooping): # recursively replace variables we already found - m = re.match('^.*\${(\w+)}', var_value) + m = re.match(r'^.*\${(\w+)}', var_value) keepLooping = (m is not None) if (keepLooping): v = var_dict.get(m.group(1)) diff --git a/rdkit/Chem/ChemUtils/DescriptorUtilities.py b/rdkit/Chem/ChemUtils/DescriptorUtilities.py index 4fda01dac..cbebddeaa 100644 --- a/rdkit/Chem/ChemUtils/DescriptorUtilities.py +++ b/rdkit/Chem/ChemUtils/DescriptorUtilities.py @@ -60,7 +60,7 @@ class VectorDescriptorWrapper: try: results = self.func(mol) - except: + except Exception: return math.nan setattr(mol, self.func_key, results) diff --git a/rdkit/Chem/ChemUtils/TemplateExpand.py b/rdkit/Chem/ChemUtils/TemplateExpand.py index 7f8ca4b37..c9218c31e 100644 --- a/rdkit/Chem/ChemUtils/TemplateExpand.py +++ b/rdkit/Chem/ChemUtils/TemplateExpand.py @@ -59,7 +59,7 @@ Usage: TemplateExpand [options] template --templateSmarts="smarts": provides a space-delimited list containing the SMARTS patterns to be used to recognize attachment points in - the template + the template --autoNames: when set this toggle causes the resulting compounds to be named based on there sequence id in the file, e.g. diff --git a/rdkit/Chem/Draw/IPythonConsole.py b/rdkit/Chem/Draw/IPythonConsole.py index 6cb8b8083..dddcbd38f 100644 --- a/rdkit/Chem/Draw/IPythonConsole.py +++ b/rdkit/Chem/Draw/IPythonConsole.py @@ -235,7 +235,7 @@ def ShowMols(mols, maxMols=50, **kwargs): for prop in ('legends', 'highlightAtoms', 'highlightBonds'): if prop in kwargs: kwargs[prop] = kwargs[prop][:maxMols] - if not "drawOptions" in kwargs: + if "drawOptions" not in kwargs: kwargs["drawOptions"] = drawOptions res = fn(mols, **kwargs) diff --git a/rdkit/Chem/Draw/cairoCanvas.py b/rdkit/Chem/Draw/cairoCanvas.py index 316c5c4b4..0f7f11692 100644 --- a/rdkit/Chem/Draw/cairoCanvas.py +++ b/rdkit/Chem/Draw/cairoCanvas.py @@ -97,7 +97,7 @@ if 'RDK_NOPANGO' not in os.environ: if libPath: try: exec(libType + ' = ffi.dlopen("' + libPath.replace('\\', '\\\\') + '")') - except: + except Exception: if envVarSet: importError = True else: diff --git a/rdkit/Chem/Features/UnitTestFeatDirUtilsRD.py b/rdkit/Chem/Features/UnitTestFeatDirUtilsRD.py index 8ec4db9ad..707735c26 100644 --- a/rdkit/Chem/Features/UnitTestFeatDirUtilsRD.py +++ b/rdkit/Chem/Features/UnitTestFeatDirUtilsRD.py @@ -5,168 +5,168 @@ from rdkit.Geometry.rdGeometry import Point3D from rdkit.Chem.Features.FeatDirUtilsRD import GetDonor2FeatVects class TestCase(unittest.TestCase): - def assertListAlmostEqual(self, list1, list2, msg, tol=7): - self.assertEqual(len(list1), len(list2), msg) - for a, b in zip(list1, list2): - self.assertAlmostEqual(a, b, tol, msg) + def assertListAlmostEqual(self, list1, list2, msg, tol=7): + self.assertEqual(len(list1), len(list2), msg) + for a, b in zip(list1, list2): + self.assertAlmostEqual(a, b, tol, msg) - def setUp(self): - #Define molecule for using in tests of GetDonor2FeatVects - self.mol = Chem.MolFromSmiles('C=CCONC') - emol = Chem.RWMol(self.mol) - emol = Chem.AddHs(emol) - emol.AddConformer(Chem.Conformer(15)) - emol.GetConformer().SetAtomPosition(0, [-2.8272, -0.2716, 0.4130]) #C - emol.GetConformer().SetAtomPosition(1, [-1.7908, -0.1146, -0.4177]) #C - emol.GetConformer().SetAtomPosition(2, [-0.5452, 0.6287, -0.0653]) #C - emol.GetConformer().SetAtomPosition(3, [0.5603, -0.2584, -0.1671]) #O - emol.GetConformer().SetAtomPosition(4, [1.7601, 0.4902, 0.1811]) #N - emol.GetConformer().SetAtomPosition(5, [2.8427, -0.4743, 0.0559]) #C - emol.GetConformer().SetAtomPosition(6, [-3.7065, -0.8216, 0.0959]) #H - emol.GetConformer().SetAtomPosition(7, [-2.8190, 0.1408, 1.4159]) #H - emol.GetConformer().SetAtomPosition(8, [-1.8508, -0.5462, -1.4133]) #H - emol.GetConformer().SetAtomPosition(9, [-0.6006, 1.0355, 0.9521]) #H - emol.GetConformer().SetAtomPosition(10, [-0.4226, 1.4609, -0.7693]) #H - emol.GetConformer().SetAtomPosition(11, [1.8283, 1.1371, -0.6054]) #H - emol.GetConformer().SetAtomPosition(12, [2.8648, -0.9271, -0.9408]) #H - emol.GetConformer().SetAtomPosition(13, [2.7437, -1.2668, 0.8044]) #H - emol.GetConformer().SetAtomPosition(14, [3.8013, 0.0259, 0.2227]) #H - self.mol = Chem.Mol(emol) + def setUp(self): + #Define molecule for using in tests of GetDonor2FeatVects + self.mol = Chem.MolFromSmiles('C=CCONC') + emol = Chem.RWMol(self.mol) + emol = Chem.AddHs(emol) + emol.AddConformer(Chem.Conformer(15)) + emol.GetConformer().SetAtomPosition(0, [-2.8272, -0.2716, 0.4130]) #C + emol.GetConformer().SetAtomPosition(1, [-1.7908, -0.1146, -0.4177]) #C + emol.GetConformer().SetAtomPosition(2, [-0.5452, 0.6287, -0.0653]) #C + emol.GetConformer().SetAtomPosition(3, [0.5603, -0.2584, -0.1671]) #O + emol.GetConformer().SetAtomPosition(4, [1.7601, 0.4902, 0.1811]) #N + emol.GetConformer().SetAtomPosition(5, [2.8427, -0.4743, 0.0559]) #C + emol.GetConformer().SetAtomPosition(6, [-3.7065, -0.8216, 0.0959]) #H + emol.GetConformer().SetAtomPosition(7, [-2.8190, 0.1408, 1.4159]) #H + emol.GetConformer().SetAtomPosition(8, [-1.8508, -0.5462, -1.4133]) #H + emol.GetConformer().SetAtomPosition(9, [-0.6006, 1.0355, 0.9521]) #H + emol.GetConformer().SetAtomPosition(10, [-0.4226, 1.4609, -0.7693]) #H + emol.GetConformer().SetAtomPosition(11, [1.8283, 1.1371, -0.6054]) #H + emol.GetConformer().SetAtomPosition(12, [2.8648, -0.9271, -0.9408]) #H + emol.GetConformer().SetAtomPosition(13, [2.7437, -1.2668, 0.8044]) #H + emol.GetConformer().SetAtomPosition(14, [3.8013, 0.0259, 0.2227]) #H + self.mol = Chem.Mol(emol) - def test1_GetDonor2FeatVects(self): - '''Case 1: two hydrogens''' - conf = self.mol.GetConformer(-1) - case1 = GetDonor2FeatVects(conf, [2], scale=1.5) - pos_heavy_atom = conf.GetAtomPosition(2) - - #Check if there are two vectors - self.assertEqual(len(case1[0]), 2, 'Incorrect number of vectors') + def test1_GetDonor2FeatVects(self): + '''Case 1: two hydrogens''' + conf = self.mol.GetConformer(-1) + case1 = GetDonor2FeatVects(conf, [2], scale=1.5) + pos_heavy_atom = conf.GetAtomPosition(2) - #Check initial points of the vectors - self.assertListAlmostEqual(case1[0][0][0], pos_heavy_atom, - 'Incorrect starting point of vector 1') - self.assertListAlmostEqual(case1[0][1][0], pos_heavy_atom, - 'Incorrect starting point of vector 2') - - #Check directions of the vectors - vec_h1 = conf.GetAtomPosition(9) - pos_heavy_atom - vec_h2 = conf.GetAtomPosition(10) - pos_heavy_atom - vec_1 = case1[0][0][1] - case1[0][0][0] - vec_2 = case1[0][1][1] - case1[0][1][0] - - self.assertListAlmostEqual(vec_1.CrossProduct(vec_h1), Point3D(0,0,0), - 'Incorrect direction of vector 1') - self.assertTrue(vec_1.DotProduct(vec_h1) > 0, - 'Incorrect direction of vector 1') - self.assertListAlmostEqual(vec_2.CrossProduct(vec_h2), Point3D(0,0,0), - 'Incorrect direction of vector 2') - self.assertTrue(vec_2.DotProduct(vec_h2) > 0, - 'Incorrect direction of vector 2') + #Check if there are two vectors + self.assertEqual(len(case1[0]), 2, 'Incorrect number of vectors') - #Check length of the vectors - self.assertAlmostEqual(vec_1.Length(), 1.5, - msg='Incorrect length of vector 1') - - self.assertAlmostEqual(vec_2.Length(), 1.5, - msg='Incorrect length of vector 2') + #Check initial points of the vectors + self.assertListAlmostEqual(case1[0][0][0], pos_heavy_atom, + 'Incorrect starting point of vector 1') + self.assertListAlmostEqual(case1[0][1][0], pos_heavy_atom, + 'Incorrect starting point of vector 2') - def test2_1_GetDonor2FeatVects(self): - '''Case 2.1: one hydrogen with sp2 arrangement''' - conf = self.mol.GetConformer(-1) + #Check directions of the vectors + vec_h1 = conf.GetAtomPosition(9) - pos_heavy_atom + vec_h2 = conf.GetAtomPosition(10) - pos_heavy_atom + vec_1 = case1[0][0][1] - case1[0][0][0] + vec_2 = case1[0][1][1] - case1[0][1][0] - case21 = GetDonor2FeatVects(conf, [1], scale=1.5) - pos_heavy_atom = conf.GetAtomPosition(1) - - #Check if there is one vector - self.assertEqual(len(case21[0]), 1, 'Incorrect number of vectors') + self.assertListAlmostEqual(vec_1.CrossProduct(vec_h1), Point3D(0,0,0), + 'Incorrect direction of vector 1') + self.assertTrue(vec_1.DotProduct(vec_h1) > 0, + 'Incorrect direction of vector 1') + self.assertListAlmostEqual(vec_2.CrossProduct(vec_h2), Point3D(0,0,0), + 'Incorrect direction of vector 2') + self.assertTrue(vec_2.DotProduct(vec_h2) > 0, + 'Incorrect direction of vector 2') - #Check initial point of the vector - self.assertListAlmostEqual(case21[0][0][0], pos_heavy_atom, - 'Incorrect starting point of vector') - - #Check direction of the vector - vec_h = conf.GetAtomPosition(8) - (pos_heavy_atom) - vec = case21[0][0][1] - case21[0][0][0] - self.assertListAlmostEqual(vec.CrossProduct(vec_h), Point3D(0,0,0), - 'Incorrect direction of vector') - self.assertTrue(vec.DotProduct(vec_h) > 0, - 'Incorrect direction of vector') + #Check length of the vectors + self.assertAlmostEqual(vec_1.Length(), 1.5, + msg='Incorrect length of vector 1') - #Check length of the vector - self.assertAlmostEqual(vec.Length(), 1.5, - msg='Incorrect length of vector') + self.assertAlmostEqual(vec_2.Length(), 1.5, + msg='Incorrect length of vector 2') - def test2_2_GetDonor2FeatVects(self): - #Case 2.2: one hydrogen with sp3 arrangement - conf = self.mol.GetConformer(-1) - case22 = GetDonor2FeatVects(conf, [4], scale=1.5) - pos_heavy_atom = conf.GetAtomPosition(4) - - #Check if there are two vectors - self.assertEqual(len(case22[0]), 2, 'Incorrect number of vectors') + def test2_1_GetDonor2FeatVects(self): + '''Case 2.1: one hydrogen with sp2 arrangement''' + conf = self.mol.GetConformer(-1) - #Check initial points of the vectors - self.assertListAlmostEqual(case22[0][0][0], pos_heavy_atom, - 'Incorrect starting point of vector 1') - self.assertListAlmostEqual(case22[0][1][0], pos_heavy_atom, - 'Incorrect starting point of vector 2') + case21 = GetDonor2FeatVects(conf, [1], scale=1.5) + pos_heavy_atom = conf.GetAtomPosition(1) - #Check directions of the vectors - vec_h = conf.GetAtomPosition(11) - pos_heavy_atom + #Check if there is one vector + self.assertEqual(len(case21[0]), 1, 'Incorrect number of vectors') - vec_nbr1 = conf.GetAtomPosition(3) - pos_heavy_atom - vec_nbr1.Normalize() - vec_nbr2 = conf.GetAtomPosition(5) - pos_heavy_atom - vec_nbr2.Normalize() - avg_vec = (vec_nbr1 + vec_nbr2) + #Check initial point of the vector + self.assertListAlmostEqual(case21[0][0][0], pos_heavy_atom, + 'Incorrect starting point of vector') - vec_1 = case22[0][0][1] - case22[0][0][0] - vec_2 = case22[0][1][1] - case22[0][1][0] + #Check direction of the vector + vec_h = conf.GetAtomPosition(8) - (pos_heavy_atom) + vec = case21[0][0][1] - case21[0][0][0] + self.assertListAlmostEqual(vec.CrossProduct(vec_h), Point3D(0,0,0), + 'Incorrect direction of vector') + self.assertTrue(vec.DotProduct(vec_h) > 0, + 'Incorrect direction of vector') - self.assertListAlmostEqual(vec_1.CrossProduct(vec_h), Point3D(0,0,0), - 'Incorrect direction of vector 1') - self.assertTrue(vec_1.DotProduct(vec_h) > 0, - 'Incorrect direction of vector 1') - self.assertListAlmostEqual(vec_2.CrossProduct(avg_vec), Point3D(0,0,0), - 'Incorrect direction of vector 2') - self.assertTrue(vec_2.DotProduct(avg_vec) < 0, - 'Incorrect direction of vector 2') + #Check length of the vector + self.assertAlmostEqual(vec.Length(), 1.5, + msg='Incorrect length of vector') - #Check length of the vectors - self.assertAlmostEqual(vec_1.Length(), 1.5, - msg='Incorrect length of vector 1') - - self.assertAlmostEqual(vec_2.Length(), 1.5, - msg='Incorrect length of vector 2') + def test2_2_GetDonor2FeatVects(self): + #Case 2.2: one hydrogen with sp3 arrangement + conf = self.mol.GetConformer(-1) + case22 = GetDonor2FeatVects(conf, [4], scale=1.5) + pos_heavy_atom = conf.GetAtomPosition(4) - def test3_GetDonor2FeatVects(self): - '''Case 3: no hydrogens''' - conf = self.mol.GetConformer(-1) - case3 = GetDonor2FeatVects(conf, [3], scale=1.5) - pos_heavy_atom = conf.GetAtomPosition(3) - - #Check if there is one vector - self.assertEqual(len(case3[0]), 1, 'Incorrect number of vectors') - - #Check initial point of the vector - self.assertListAlmostEqual(case3[0][0][0], pos_heavy_atom, - 'Incorrect starting point of vector') - - #Check direction of the vector - vec_nbr1 = conf.GetAtomPosition(2) - pos_heavy_atom - vec_nbr1.Normalize() - vec_nbr2 = conf.GetAtomPosition(4) - pos_heavy_atom - vec_nbr2.Normalize() - avg_vec = (vec_nbr1 + vec_nbr2) - vec = case3[0][0][1] - case3[0][0][0] - self.assertListAlmostEqual(vec.CrossProduct(avg_vec), Point3D(0,0,0), - 'Incorrect direction of vector') - self.assertTrue(vec.DotProduct(avg_vec) < 0, - 'Incorrect direction of vector') + #Check if there are two vectors + self.assertEqual(len(case22[0]), 2, 'Incorrect number of vectors') - #Check length of the vector - self.assertAlmostEqual(vec.Length(), 1.5, - msg='Incorrect length of vector') + #Check initial points of the vectors + self.assertListAlmostEqual(case22[0][0][0], pos_heavy_atom, + 'Incorrect starting point of vector 1') + self.assertListAlmostEqual(case22[0][1][0], pos_heavy_atom, + 'Incorrect starting point of vector 2') + + #Check directions of the vectors + vec_h = conf.GetAtomPosition(11) - pos_heavy_atom + + vec_nbr1 = conf.GetAtomPosition(3) - pos_heavy_atom + vec_nbr1.Normalize() + vec_nbr2 = conf.GetAtomPosition(5) - pos_heavy_atom + vec_nbr2.Normalize() + avg_vec = (vec_nbr1 + vec_nbr2) + + vec_1 = case22[0][0][1] - case22[0][0][0] + vec_2 = case22[0][1][1] - case22[0][1][0] + + self.assertListAlmostEqual(vec_1.CrossProduct(vec_h), Point3D(0,0,0), + 'Incorrect direction of vector 1') + self.assertTrue(vec_1.DotProduct(vec_h) > 0, + 'Incorrect direction of vector 1') + self.assertListAlmostEqual(vec_2.CrossProduct(avg_vec), Point3D(0,0,0), + 'Incorrect direction of vector 2') + self.assertTrue(vec_2.DotProduct(avg_vec) < 0, + 'Incorrect direction of vector 2') + + #Check length of the vectors + self.assertAlmostEqual(vec_1.Length(), 1.5, + msg='Incorrect length of vector 1') + + self.assertAlmostEqual(vec_2.Length(), 1.5, + msg='Incorrect length of vector 2') + + def test3_GetDonor2FeatVects(self): + '''Case 3: no hydrogens''' + conf = self.mol.GetConformer(-1) + case3 = GetDonor2FeatVects(conf, [3], scale=1.5) + pos_heavy_atom = conf.GetAtomPosition(3) + + #Check if there is one vector + self.assertEqual(len(case3[0]), 1, 'Incorrect number of vectors') + + #Check initial point of the vector + self.assertListAlmostEqual(case3[0][0][0], pos_heavy_atom, + 'Incorrect starting point of vector') + + #Check direction of the vector + vec_nbr1 = conf.GetAtomPosition(2) - pos_heavy_atom + vec_nbr1.Normalize() + vec_nbr2 = conf.GetAtomPosition(4) - pos_heavy_atom + vec_nbr2.Normalize() + avg_vec = (vec_nbr1 + vec_nbr2) + vec = case3[0][0][1] - case3[0][0][0] + self.assertListAlmostEqual(vec.CrossProduct(avg_vec), Point3D(0,0,0), + 'Incorrect direction of vector') + self.assertTrue(vec.DotProduct(avg_vec) < 0, + 'Incorrect direction of vector') + + #Check length of the vector + self.assertAlmostEqual(vec.Length(), 1.5, + msg='Incorrect length of vector') if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/rdkit/Chem/MolDb/Loader_sa.py b/rdkit/Chem/MolDb/Loader_sa.py index 4ebecd433..aa2dcb7cd 100644 --- a/rdkit/Chem/MolDb/Loader_sa.py +++ b/rdkit/Chem/MolDb/Loader_sa.py @@ -109,7 +109,7 @@ def LoadDb(suppl, dbName, nameProp='_Name', nameCol='compound_id', silent=False, try: os.unlink(dbName) break - except: + except Exception: import time time.sleep(2) if os.path.exists(dbName): diff --git a/rdkit/Chem/MolKey/MolKey.py b/rdkit/Chem/MolKey/MolKey.py index 0c3c66d80..6c2e8cddc 100644 --- a/rdkit/Chem/MolKey/MolKey.py +++ b/rdkit/Chem/MolKey/MolKey.py @@ -106,7 +106,7 @@ stereo_code_dict['UNDEFINED'] = 200 def _fix_all(pat, sbt, my_string): try: return re.sub(pat, sbt, my_string) - except: + except Exception: return None diff --git a/rdkit/Chem/PandasTools.py b/rdkit/Chem/PandasTools.py index 4e4bed05d..a3065c573 100644 --- a/rdkit/Chem/PandasTools.py +++ b/rdkit/Chem/PandasTools.py @@ -232,7 +232,7 @@ def patchPandasHTMLrepr(self, **kwargs): try: import pandas.io.formats.html # necessary for loading HTMLFormatter - except: + except Exception: # this happens up until at least pandas v0.22 return patch_v1() get_adjustment_attr = getAdjustmentAttr() @@ -260,7 +260,7 @@ def patchPandasHTMLrepr(self, **kwargs): setattr(pd.io.formats.format, get_adjustment_attr, _patched_get_adjustment) pd.io.formats.html.HTMLFormatter._write_cell = _patched_HTMLFormatter_write_cell return defPandasRendering(self, **kwargs) - except: + except Exception: pass finally: # restore original methods @@ -481,7 +481,7 @@ def LoadSDF(filename, idName='ID', molColName='ROMol', includeFingerprints=False if smilesName is not None: try: row[smilesName] = Chem.MolToSmiles(mol, isomericSmiles=isomericSmiles) - except: + except Exception: log.warning('No valid smiles could be generated for molecule %s', i) row[smilesName] = None if molColName is not None and not includeFingerprints: diff --git a/rdkit/Chem/Recap.py b/rdkit/Chem/Recap.py index c124b9565..802b9bc61 100755 --- a/rdkit/Chem/Recap.py +++ b/rdkit/Chem/Recap.py @@ -198,7 +198,7 @@ def RecapDecompose(mol, allNodes=None, minFragmentSize=0, onlyUseReactions=None) for nats, prod in prodSeq: pSmi = prod.pSmi # print '\t',nats,pSmi - if not pSmi in allNodes: + if pSmi not in allNodes: pNode = RecapHierarchyNode(prod) pNode.smiles = pSmi pNode.parents[nSmi] = weakref.proxy(node) diff --git a/rdkit/Chem/UnitTestEnumerateHeterocycles.py b/rdkit/Chem/UnitTestEnumerateHeterocycles.py index 62a8df20e..8a01d24fc 100644 --- a/rdkit/Chem/UnitTestEnumerateHeterocycles.py +++ b/rdkit/Chem/UnitTestEnumerateHeterocycles.py @@ -38,7 +38,7 @@ def assert_valid_change(orig_can_smi, smiles): msg = "%s produced %s" % (orig_can_smi, smiles) try: mol = check_smiles(smiles) - except: + except Exception: print(msg) raise diff --git a/rdkit/DataStructs/UnitTestBitEnsemble.py b/rdkit/DataStructs/UnitTestBitEnsemble.py index 89d4a95a5..e60ddd325 100755 --- a/rdkit/DataStructs/UnitTestBitEnsemble.py +++ b/rdkit/DataStructs/UnitTestBitEnsemble.py @@ -81,7 +81,7 @@ class TestCase(unittest.TestCase): if hasattr(self, 'tempDbName') and RDConfig.useSqlLite and os.path.exists(self.tempDbName): try: os.unlink(self.tempDbName) - except: # pragma: nocover + except Exception: # pragma: nocover import traceback traceback.print_exc() diff --git a/rdkit/Dbase/StorageUtils.py b/rdkit/Dbase/StorageUtils.py index 238a26a67..fc29be287 100755 --- a/rdkit/Dbase/StorageUtils.py +++ b/rdkit/Dbase/StorageUtils.py @@ -304,7 +304,7 @@ if __name__ == '__main__': # pragma: nocover if RDConfig.useSqlLite and os.path.exists(tempDbName): try: os.unlink(tempDbName) - except: + except Exception: import traceback traceback.print_exc() sys.exit(failed) diff --git a/rdkit/Dbase/UnitTestDbConnect.py b/rdkit/Dbase/UnitTestDbConnect.py index 6f233a9ac..730ffa15a 100755 --- a/rdkit/Dbase/UnitTestDbConnect.py +++ b/rdkit/Dbase/UnitTestDbConnect.py @@ -40,7 +40,7 @@ class TestCase(unittest.TestCase): os.close(self.fd) try: os.unlink(self.tempDbName) - except: + except Exception: import traceback traceback.print_exc() diff --git a/rdkit/Dbase/UnitTestDbUtils.py b/rdkit/Dbase/UnitTestDbUtils.py index d45505c05..95801998e 100755 --- a/rdkit/Dbase/UnitTestDbUtils.py +++ b/rdkit/Dbase/UnitTestDbUtils.py @@ -22,7 +22,7 @@ from rdkit.Dbase.DbConnection import DbConnect try: from contextlib import redirect_stdout -except: +except Exception: from rdkit.TestRunner import redirect_stdout @@ -45,7 +45,7 @@ class TestCase(unittest.TestCase): os.close(self.fd) try: os.unlink(self.tempDbName) - except: + except Exception: import traceback traceback.print_exc() diff --git a/rdkit/Dbase/UnitTestStorageUtils.py b/rdkit/Dbase/UnitTestStorageUtils.py index d44b8a696..a113d2df5 100644 --- a/rdkit/Dbase/UnitTestStorageUtils.py +++ b/rdkit/Dbase/UnitTestStorageUtils.py @@ -38,7 +38,7 @@ class TestCase(unittest.TestCase): os.close(StorageUtils.fd) try: os.unlink(StorageUtils.tempDbName) - except: + except Exception: traceback.print_exc() self.assertFalse(failed) diff --git a/rdkit/__init__.py b/rdkit/__init__.py index 0d8a37bea..5ac3582af 100644 --- a/rdkit/__init__.py +++ b/rdkit/__init__.py @@ -21,7 +21,7 @@ try: logger.info("Enabling RDKit %s jupyter extensions" % __version__) from rdkit.Chem.Draw import IPythonConsole rdBase.LogToPythonStderr() -except: +except Exception: pass # Do logging setup at the end, so users can suppress the diff --git a/rdkit/sping/PDF/pdfdoc.py b/rdkit/sping/PDF/pdfdoc.py index 93bea3554..315375961 100755 --- a/rdkit/sping/PDF/pdfdoc.py +++ b/rdkit/sping/PDF/pdfdoc.py @@ -446,7 +446,7 @@ class PDFStream(PDFObject): def save(self, file): #avoid crashes if they wrote nothing in the page - if self.data == None: + if self.data is None: self.data = TestStream if self.compression == 1: diff --git a/rdkit/sping/PDF/pidPDF.py b/rdkit/sping/PDF/pidPDF.py index fc7423d4a..fbc27d26a 100755 --- a/rdkit/sping/PDF/pidPDF.py +++ b/rdkit/sping/PDF/pidPDF.py @@ -112,7 +112,7 @@ class PDFCanvas(Canvas): self.filename = name # self.pdf.setPageSize(pagesize) # This doesn't seem to work correctly -cwl - if size == None: + if size is None: # take the page size, which might not be default self.drawingsize = self.pagesize else: diff --git a/rdkit/sping/PIL/pidPIL.py b/rdkit/sping/PIL/pidPIL.py index e40fb2994..ad19ea8a2 100755 --- a/rdkit/sping/PIL/pidPIL.py +++ b/rdkit/sping/PIL/pidPIL.py @@ -20,7 +20,7 @@ This module implements a Python Imaging Library PIDDLE canvas. In other words, this is a PIDDLE backend that renders into a PIL Image object. From there, you can save as GIF, plot into another PIDDLE canvas, etc. - + Joe Strout (joe@strout.net), 10/26/99 modified for use with sping. This requires Imaging to be installed as a package PIL @@ -134,7 +134,7 @@ def _pilFont(font): break except Exception: pass - if pilfont == None: + if pilfont is None: return 0 # font not found! return pilfont @@ -174,7 +174,7 @@ class PILCanvas(Canvas): if hasattr(file, 'write'): raise ValueError('fileobj not implemented for piddlePIL') # below here, file is guaranteed to be a string - if format == None: + if format is None: if '.' not in file: filename = file + '.png' # default to producing jpg else: diff --git a/rdkit/sping/PS/pidPS.py b/rdkit/sping/PS/pidPS.py index c414c79db..403800763 100644 --- a/rdkit/sping/PS/pidPS.py +++ b/rdkit/sping/PS/pidPS.py @@ -524,7 +524,7 @@ translate self.code.append('%s %s %s setrgbcolor' % (r, g, b)) def _updateLineWidth(self, width): - if width == None: + if width is None: width = self.defaultLineWidth if width != self._currentWidth: self._currentWidth = width diff --git a/rdkit/sping/ReportLab/pidReportLab.py b/rdkit/sping/ReportLab/pidReportLab.py index 96c7691fa..c5d1961a4 100644 --- a/rdkit/sping/ReportLab/pidReportLab.py +++ b/rdkit/sping/ReportLab/pidReportLab.py @@ -18,7 +18,7 @@ Bits have been shamelessly cobbled from piddlePDF.py and/or piddlePS.py - + Greg Landrum (greg.landrum@gmail.com) 3/28/2005 """ """ diff --git a/rdkit/sping/SVG/pidSVG.py b/rdkit/sping/SVG/pidSVG.py index 72069c71d..0cc7e563a 100755 --- a/rdkit/sping/SVG/pidSVG.py +++ b/rdkit/sping/SVG/pidSVG.py @@ -252,7 +252,7 @@ class SVGCanvas(Canvas): file = . By default, I've made the fomrat extension be .svg. By default it saves the file to "self.name" + '.svg' """ - if file == None: + if file is None: file = self.name if isinstance(file, str): @@ -261,7 +261,7 @@ class SVGCanvas(Canvas): isFileName = 0 if isFileName: - if format == None: + if format is None: if '.' not in file: file = file + '.svg' else: @@ -330,7 +330,7 @@ class SVGCanvas(Canvas): if not edgeColor: edgeColor = self.defaultLineColor # set edge width... - if edgeWidth == None: + if edgeWidth is None: edgeWidth = self.defaultLineWidth # SVG markers @@ -373,7 +373,7 @@ class SVGCanvas(Canvas): if not edgeColor: edgeColor = self.defaultLineColor # set edge width... - if edgeWidth == None: + if edgeWidth is None: edgeWidth = self.defaultLineWidth edgeStr = 'stroke="%s" stroke-width="%d"' % (_ColorToSVG(edgeColor), int(edgeWidth)) @@ -425,7 +425,7 @@ class SVGCanvas(Canvas): if not edgeColor: edgeColor = self.defaultLineColor # set edge width... - if edgeWidth == None: + if edgeWidth is None: edgeWidth = self.defaultLineWidth # SVG markers @@ -475,7 +475,7 @@ class SVGCanvas(Canvas): edgeColor = self.defaultLineColor # set edge width... - if edgeWidth == None: + if edgeWidth is None: edgeWidth = self.defaultLineWidth # SVG markers @@ -563,7 +563,7 @@ class SVGCanvas(Canvas): if not edgeColor: edgeColor = self.defaultLineColor # set edge width... - if edgeWidth == None: + if edgeWidth is None: edgeWidth = self.defaultLineWidth # SVG markers diff --git a/rdkit/sping/WX/pidWX.py b/rdkit/sping/WX/pidWX.py index 91746a99c..79abf8a76 100644 --- a/rdkit/sping/WX/pidWX.py +++ b/rdkit/sping/WX/pidWX.py @@ -401,5 +401,5 @@ class WXCanvas(PiddleWxDc): def setInfoLine(self, s): """For interactive Canvases, displays the given string in the 'info line' somewhere where the user can probably see it.""" - if self.sb != None: + if self.sb is not None: self.sb.SetStatusText(s) diff --git a/rdkit/sping/stringformat.py b/rdkit/sping/stringformat.py index 97c7c736c..4ae8d5b6e 100644 --- a/rdkit/sping/stringformat.py +++ b/rdkit/sping/stringformat.py @@ -247,7 +247,7 @@ class StringFormatter(xmllib.XMLParser): # automatically add handlers for all of the greek characters for item in greekchars.keys(): - self.elements[item] = (lambda attr,self=self,letter=greekchars[item]: \ + self.elements[item] = (lambda attr,self=self,letter=greekchars[item]: self.start_greek(attr,letter), self.end_greek) # flag for greek characters diff --git a/rdkit/sping/tests/pidtest.py b/rdkit/sping/tests/pidtest.py index d4489e256..8a40e9016 100755 --- a/rdkit/sping/tests/pidtest.py +++ b/rdkit/sping/tests/pidtest.py @@ -325,7 +325,7 @@ def wxTest(testfunc): return global wx_app - if not 'wx_app' in globals(): + if 'wx_app' not in globals(): class CanvasApp(wxApp): "The wxApp that runs canvas. Initializes windows, and handles redrawing" @@ -450,7 +450,7 @@ def mainLoop(): print # now, if we have a valid backend and test, run it - if backend != None and test != None: + if backend is not None and test is not None: runtest(backends[backend], tests[test]) diff --git a/rdkit/sping/util/HTMLPiddler.py b/rdkit/sping/util/HTMLPiddler.py index ab36d8a58..dd71a39d7 100755 --- a/rdkit/sping/util/HTMLPiddler.py +++ b/rdkit/sping/util/HTMLPiddler.py @@ -146,10 +146,10 @@ class _HtmlPiddleWriter: else: face = "times" # "roman" italic = fontParams[1] # Italic indicator - if italic == None: + if italic is None: italic = 0 bold = fontParams[2] # Bold indicator - if bold == None: + if bold is None: bold = 0 self.font = piddle.Font(points, bold, italic, face=face) x = self.pc.stringWidth('W' * 20, self.font)