forked from savantas/MAGMa-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAllkeys.py
224 lines (187 loc) · 6.75 KB
/
Allkeys.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# $Id$
#
# Copyright (C) 2001-2011 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" SMARTS definitions for the publically available MACCS keys
and a MACCS fingerprinter
I compared the MACCS fingerprints generated here with those from two
other packages (not MDL, unfortunately). Of course there are
disagreements between the various fingerprints still, but I think
these definitions work pretty well. Some notes:
1) most of the differences have to do with aromaticity
2) there's a discrepancy sometimes because the current RDKit
definitions do not require multiple matches to be distinct. e.g. the
SMILES C(=O)CC(=O) can match the (hypothetical) key O=CC twice in my
definition. It's not clear to me what the correct behavior is.
3) Some keys are not fully defined in the MDL documentation
4) Two keys, 125 and 166, have to be done outside of SMARTS.
5) Key 1 (ISOTOPE) isn't defined
Rev history:
2006 (gl): Original open-source release
May 2011 (gl): Update some definitions based on feedback from Andrew Dalke
Oct 2015: Update for compatibility with all SMARTS-formatted fingerprints
from external file (with filter) by Dries Verdegem
"""
import os
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors
from rdkit import DataStructs
smartsPatts = {}
def InitPatts(magma_classifier_path):
# getting the keys
global smartsPatts
all_fingerprints_f = open(os.path.join(magma_classifier_path, 'AllFingerprints.txt'),'r')
key_num = 1
for line in all_fingerprints_f:
line = line.strip()
if line.startswith('#'): continue
if not line: continue
fingerprint, count = line.split('\t')
count = int(count)
smartsPatts[key_num] = (fingerprint, count)
key_num += 1
all_fingerprints_f.close()
maccsKeys = None
def _InitKeys(keyList,keyDict):
""" *Internal Use Only*
generates SMARTS patterns for the keys, run once
"""
assert len(keyList) == len(keyDict.keys()),'length mismatch'
for key in keyDict.keys():
patt,count = keyDict[key]
if patt != '?':
try:
sma = Chem.MolFromSmarts(patt)
except:
sma = None
if not sma:
print 'SMARTS parser error for key #%d: %s'%(key,patt)
else:
keyList[key-1] = sma,count
def _pyGenMACCSKeys(mol,**kwargs):
""" generates the MACCS fingerprint for a molecules
**Arguments**
- mol: the molecule to be fingerprinted
- any extra keyword arguments are ignored
**Returns**
a _DataStructs.SparseBitVect_ containing the fingerprint.
>>> m = Chem.MolFromSmiles('CNO')
>>> bv = GenMACCSKeys(m)
>>> tuple(bv.GetOnBits())
(24, 68, 69, 71, 93, 94, 102, 124, 131, 139, 151, 158, 160, 161, 164)
>>> bv = GenMACCSKeys(Chem.MolFromSmiles('CCC'))
>>> tuple(bv.GetOnBits())
(74, 114, 149, 155, 160)
"""
global maccsKeys
if maccsKeys is None:
maccsKeys = [(None,0)]*len(smartsPatts.keys())
_InitKeys(maccsKeys,smartsPatts)
ctor=kwargs.get('ctor',DataStructs.SparseBitVect)
res = ctor(len(maccsKeys)+1)
for i,(patt,count) in enumerate(maccsKeys):
if patt is not None:
if count==0:
res[i+1] = mol.HasSubstructMatch(patt)
else:
matches = mol.GetSubstructMatches(patt)
if len(matches) > count:
res[i+1] = 1
elif (i+1)==125:
# special case: num aromatic rings > 1
ri = mol.GetRingInfo()
nArom=0
res[125]=0
for ring in ri.BondRings():
isArom=True
for bondIdx in ring:
if not mol.GetBondWithIdx(bondIdx).GetIsAromatic():
isArom=False
break
if isArom:
nArom+=1
if nArom>1:
res[125]=1
break
elif (i+1)==166:
res[166]=0
# special case: num frags > 1
if len(Chem.GetMolFrags(mol))>1:
res[166]=1
return res
def _pyGenFilteredMACCSKeys(mol, feature_filter=[], **kwargs):
""" generates the MACCS fingerprint for a molecules
**Arguments**
- mol: the molecule to be fingerprinted
- any extra keyword arguments are ignored
**Returns**
a _DataStructs.SparseBitVect_ containing the fingerprint.
>>> m = Chem.MolFromSmiles('CNO')
>>> bv = GenMACCSKeys(m)
>>> tuple(bv.GetOnBits())
(24, 68, 69, 71, 93, 94, 102, 124, 131, 139, 151, 158, 160, 161, 164)
>>> bv = GenMACCSKeys(Chem.MolFromSmiles('CCC'))
>>> tuple(bv.GetOnBits())
(74, 114, 149, 155, 160)
"""
global maccsKeys
if maccsKeys is None:
maccsKeys = [(None,0)]*len(smartsPatts.keys())
_InitKeys(maccsKeys,smartsPatts)
ctor=kwargs.get('ctor',DataStructs.SparseBitVect)
res = ctor(len(feature_filter)+1)
res_count = -1
for i,(patt,count) in enumerate(maccsKeys):
if i+1 in feature_filter:
#print 'patt', patt, smartsPatts[i+1]
res_count += 1
else:
continue
if patt is not None:
if count==0:
res[res_count+1] = mol.HasSubstructMatch(patt)
else:
matches = mol.GetSubstructMatches(patt)
if len(matches) > count:
res[res_count+1] = 1
elif (i+1)==125:
# special case: num aromatic rings > 1
ri = mol.GetRingInfo()
nArom=0
res[res_count+1]=0
for ring in ri.BondRings():
isArom=True
for bondIdx in ring:
if not mol.GetBondWithIdx(bondIdx).GetIsAromatic():
isArom=False
break
if isArom:
nArom+=1
if nArom>1:
res[res_count+1]=1
break
elif (i+1)==166:
res[res_count+1]=0
# special case: num frags > 1
if len(Chem.GetMolFrags(mol))>1:
res[res_count+1]=1
return res
GenMACCSKeys = rdMolDescriptors.GetMACCSKeysFingerprint
FingerprintMol = rdMolDescriptors.GetMACCSKeysFingerprint
#------------------------------------
#
# doctest boilerplate
#
def _test():
import doctest,sys
return doctest.testmod(sys.modules["__main__"])
if __name__ == '__main__':
import sys
failed,tried = _test()
sys.exit(failed)