-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsmiles2mol.py
70 lines (58 loc) · 1.78 KB
/
smiles2mol.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
from distutils.dir_util import mkpath
import sys
import json
from types import *
# NIH resolver interface
import cirpy
# PubChem interface
import pubchempy as pcp
# json array
items = {}
try:
with open('index.json') as index:
items = json.load(index)
except ValueError:
print "No JSON yet"
# read through multiple files on command-line
for argument in sys.argv[1:]:
with open(argument) as f:
for line in f:
line = line.rstrip()
# skip blank lines and comments
if not line or line[0] == '#':
continue
print line
mol = cirpy.Molecule(line, ['smiles'])
ikey = mol.stdinchikey
if ikey is None:
continue
if ikey.startswith('InChIKey='):
ikey = ikey[9:]
# try to get the PubChem cid
results = pcp.get_compounds(ikey, 'inchikey')
results.sort()
compound = results[0]
name = mol.iupac_name
if name is None:
name = compound.iupac_name
if type(name) is ListType:
name = name[0]
if name is None:
name = line
# get properties
# add to json
items[ikey] = {
'inchikey': ikey,
'name': name.lower(),
'cid': compound.cid,
'cas': mol.cas,
'formula': mol.formula,
'molwt': mol.mw
}
filename = "library/%s/%s/%s.mol2" % (ikey[0], ikey[1], ikey)
mkpath('library/%s/%s' % (ikey[0], ikey[1]))
mol.download(filename, 'mol2', True)
print items
with open('index.json', 'w') as index:
json.dump(items, index, indent=4)