comparison rdkit_descriptors.py @ 0:06828e0cc8a7 draft

"planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/chemicaltoolbox/rdkit commit 714e984db6ba1198cacf4dcf325320a5889fa02c"
author bgruening
date Wed, 16 Oct 2019 07:26:19 -0400
parents
children 351fbd750a6d
comparison
equal deleted inserted replaced
-1:000000000000 0:06828e0cc8a7
1 #!/usr/bin/env python
2
3 from rdkit.Chem import Descriptors
4 from rdkit import Chem
5 import sys, os, re
6 import argparse
7 import inspect
8
9 def get_supplier( infile, format = 'smiles' ):
10 """
11 Returns a generator over a SMILES or InChI file. Every element is of RDKit
12 molecule and has its original string as _Name property.
13 """
14 with open(infile) as handle:
15 for line in handle:
16 line = line.strip()
17 if format == 'smiles':
18 mol = Chem.MolFromSmiles( line, sanitize=True )
19 elif format == 'inchi':
20 mol = Chem.inchi.MolFromInchi( line, sanitize=True, removeHs=True, logLevel=None, treatWarningAsError=False )
21 if mol is None:
22 yield False
23 else:
24 mol.SetProp( '_Name', line.split('\t')[0] )
25 yield mol
26
27 def get_rdkit_descriptor_functions():
28 """
29 Returns all descriptor functions under the Chem.Descriptors Module as tuple of (name, function)
30 """
31 ret = [ (name, f) for name, f in inspect.getmembers( Descriptors ) if inspect.isfunction( f ) and not name.startswith( '_' ) ]
32 ret.sort()
33 return ret
34
35
36 def descriptors( mol, functions ):
37 """
38 Calculates the descriptors of a given molecule.
39 """
40 for name, function in functions:
41 yield (name, function( mol ))
42
43
44 if __name__ == "__main__":
45 parser = argparse.ArgumentParser()
46 parser.add_argument('-i', '--infile', required=True, help='Path to the input file.')
47 parser.add_argument("--iformat", help="Specify the input file format.")
48
49 parser.add_argument('-o', '--outfile', type=argparse.FileType('w+'),
50 default=sys.stdout, help="path to the result file, default it sdtout")
51
52 parser.add_argument("--header", dest="header", action="store_true",
53 default=False,
54 help="Write header line.")
55
56 args = parser.parse_args()
57
58 if args.iformat == 'sdf':
59 supplier = Chem.SDMolSupplier( args.infile )
60 elif args.iformat =='smi':
61 supplier = get_supplier( args.infile, format = 'smiles' )
62 elif args.iformat == 'inchi':
63 supplier = get_supplier( args.infile, format = 'inchi' )
64
65 functions = get_rdkit_descriptor_functions()
66
67 if args.header:
68 args.outfile.write( '%s\n' % '\t'.join( ['MoleculeID'] + [name for name, f in functions] ) )
69
70 for mol in supplier:
71 if not mol:
72 continue
73 descs = descriptors( mol, functions )
74 molecule_id = mol.GetProp("_Name")
75 args.outfile.write( "%s\n" % '\t'.join( [molecule_id]+ [str(round(res, 6)) for name, res in descs] ) )
76