-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchemutils.py
261 lines (219 loc) · 8.4 KB
/
chemutils.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
from rdkit import Chem
from rdkit.Chem import BRICS
# from basic import sanitize
from collections import defaultdict
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from typing import Union, List, Tuple
from rdkit.Chem.rdchem import Mol
MST_MAX_WEIGHT = 100
MAX_NCAND = 2000
# 1. read
def get_mol(smiles):
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
Chem.Kekulize(mol)
return mol
# 2. output
def get_smiles(mol):
return Chem.MolToSmiles(mol, kekuleSmiles=True)
def sanitize(mol):
try:
smiles = get_smiles(mol)
mol = get_mol(smiles)
except Exception as e:
return None
return mol
def get_smiles(mol, kekuleSmiles=True):
return Chem.MolToSmiles(mol, kekuleSmiles=kekuleSmiles)
def copy_atom(atom):
new_atom = Chem.Atom(atom.GetSymbol())
new_atom.SetFormalCharge(atom.GetFormalCharge())
new_atom.SetAtomMapNum(atom.GetAtomMapNum())
return new_atom
def copy_edit_mol(mol):
new_mol = Chem.RWMol(Chem.MolFromSmiles(''))
for atom in mol.GetAtoms():
new_atom = copy_atom(atom)
new_mol.AddAtom(new_atom)
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
bt = bond.GetBondType()
new_mol.AddBond(a1, a2, bt)
return new_mol
def ring_bond_equal(b1, b2, reverse=False):
b1 = (b1.GetBeginAtom(), b1.GetEndAtom())
if reverse:
b2 = (b2.GetEndAtom(), b2.GetBeginAtom())
else:
b2 = (b2.GetBeginAtom(), b2.GetEndAtom())
return atom_equal(b1[0], b2[0]) and atom_equal(b1[1], b2[1])
def atom_equal(a1, a2):
return a1.GetSymbol() == a2.GetSymbol() and a1.GetFormalCharge() == a2.GetFormalCharge()
# Mapping Number
def set_atommap(mol, num=0):
for atom in mol.GetAtoms():
atom.SetAtomMapNum(num)
# Get Fragment
def get_clique_mol(mol, atoms):
if isinstance(mol, str):
mol = Chem.MolFromSmiles(mol)
# get the fragment of clique
smiles = Chem.MolFragmentToSmiles(mol, atoms, kekuleSmiles=True)
new_mol = Chem.MolFromSmiles(smiles, sanitize=False)
new_mol = copy_edit_mol(new_mol).GetMol()
new_mol = sanitize(new_mol) # We assume this is not None
return new_mol
def get_broken(frag: Union[str, Mol]) -> List[Tuple[int, str]]:
if isinstance(frag, str):
frag = Chem.MolFromSmiles(frag)
broken_idx_list = []
for atom in frag.GetAtoms():
if atom.GetAtomicNum() == 0:
broken_idx_list.append((atom.GetIdx(), str(atom.GetIsotope())))
return broken_idx_list
def tree_decomp(mol):
n_atoms = mol.GetNumAtoms()
if n_atoms == 1:
return [[0]], []
cliques = []
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
if not bond.IsInRing():
cliques.append([a1, a2])
# get rings
ssr = [list(x) for x in Chem.GetSymmSSSR(mol)]
cliques.extend(ssr)
nei_list = [[] for i in range(n_atoms)]
for i in range(len(cliques)):
for atom in cliques[i]:
nei_list[atom].append(i)
# Merge Rings with intersection > 2 atoms
for i in range(len(cliques)):
if len(cliques[i]) <= 2: continue
for atom in cliques[i]:
for j in nei_list[atom]:
if i >= j or len(cliques[j]) <= 2: continue
inter = set(cliques[i]) & set(cliques[j])
if len(inter) > 2:
cliques[i].extend(cliques[j])
cliques[i] = list(set(cliques[i]))
cliques[j] = []
cliques = [c for c in cliques if len(c) > 0]
nei_list = [[] for i in range(n_atoms)]
for i in range(len(cliques)):
for atom in cliques[i]:
nei_list[atom].append(i)
# Build edges and add singleton cliques
edges = defaultdict(int)
for atom in range(n_atoms):
if len(nei_list[atom]) <= 1:
continue
cnei = nei_list[atom]
bonds = [c for c in cnei if len(cliques[c]) == 2]
rings = [c for c in cnei if len(cliques[c]) > 4]
if len(bonds) > 2 or (len(bonds) == 2 and len(
cnei) > 2): # In general, if len(cnei) >= 3, a singleton should be added, but 1 bond + 2 ring is currently not dealt with.
cliques.append([atom])
c2 = len(cliques) - 1
for c1 in cnei:
edges[(c1, c2)] = 1
elif len(rings) > 2: # Multiple (n>2) complex rings
cliques.append([atom])
c2 = len(cliques) - 1
for c1 in cnei:
edges[(c1, c2)] = MST_MAX_WEIGHT - 1
else:
for i in range(len(cnei)):
for j in range(i + 1, len(cnei)):
c1, c2 = cnei[i], cnei[j]
inter = set(cliques[c1]) & set(cliques[c2])
if edges[(c1, c2)] < len(inter):
edges[(c1, c2)] = len(inter) # cnei[i] < cnei[j] by construction
edges = [u + (MST_MAX_WEIGHT - v,) for u, v in edges.items()]
if len(edges) == 0:
return cliques, edges
# Compute Maximum Spanning Tree
row, col, data = zip(*edges)
n_clique = len(cliques)
clique_graph = csr_matrix((data, (row, col)), shape=(n_clique, n_clique))
junc_tree = minimum_spanning_tree(clique_graph)
row, col = junc_tree.nonzero()
edges = [(row[i], col[i]) for i in range(len(row))]
return (cliques, edges)
def brics_decomp(mol):
n_atoms = mol.GetNumAtoms()
if n_atoms == 1:
return [[0]], []
cliques = []
breaks = []
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
cliques.append([a1, a2])
res = list(BRICS.FindBRICSBonds(mol))
if len(res) == 0:
return [list(range(n_atoms))], []
else:
for bond in res:
if [bond[0][0], bond[0][1]] in cliques:
cliques.remove([bond[0][0], bond[0][1]])
else:
cliques.remove([bond[0][1], bond[0][0]])
cliques.append([bond[0][0]])
cliques.append([bond[0][1]])
# break bonds between rings and non-ring atoms
for c in cliques:
if len(c) > 1:
if mol.GetAtomWithIdx(c[0]).IsInRing() and not mol.GetAtomWithIdx(c[1]).IsInRing():
cliques.remove(c)
cliques.append([c[1]])
breaks.append(c)
if mol.GetAtomWithIdx(c[1]).IsInRing() and not mol.GetAtomWithIdx(c[0]).IsInRing():
cliques.remove(c)
cliques.append([c[0]])
breaks.append(c)
# select atoms at intersections as motif
for atom in mol.GetAtoms():
if len(atom.GetNeighbors()) > 2 and not atom.IsInRing():
cliques.append([atom.GetIdx()])
for nei in atom.GetNeighbors():
if [nei.GetIdx(), atom.GetIdx()] in cliques:
cliques.remove([nei.GetIdx(), atom.GetIdx()])
breaks.append([nei.GetIdx(), atom.GetIdx()])
elif [atom.GetIdx(), nei.GetIdx()] in cliques:
cliques.remove([atom.GetIdx(), nei.GetIdx()])
breaks.append([atom.GetIdx(), nei.GetIdx()])
cliques.append([nei.GetIdx()])
# merge cliques
for c in range(len(cliques) - 1):
if c >= len(cliques):
break
for k in range(c + 1, len(cliques)):
if k >= len(cliques):
break
if len(set(cliques[c]) & set(cliques[k])) > 0:
cliques[c] = list(set(cliques[c]) | set(cliques[k]))
cliques[k] = []
cliques = [c for c in cliques if len(c) > 0]
cliques = [c for c in cliques if len(c) > 0]
# edges
edges = []
for bond in res:
for c in range(len(cliques)):
if bond[0][0] in cliques[c]:
c1 = c
if bond[0][1] in cliques[c]:
c2 = c
edges.append((c1, c2))
for bond in breaks:
for c in range(len(cliques)):
if bond[0] in cliques[c]:
c1 = c
if bond[1] in cliques[c]:
c2 = c
edges.append((c1, c2))
return cliques, edges