|
a |
|
b/utils.py |
|
|
1 |
from typing import Union, Iterable |
|
|
2 |
|
|
|
3 |
import numpy as np |
|
|
4 |
import torch |
|
|
5 |
import torch.nn.functional as F |
|
|
6 |
from rdkit import Chem |
|
|
7 |
import networkx as nx |
|
|
8 |
from networkx.algorithms import isomorphism |
|
|
9 |
from Bio.PDB.Polypeptide import is_aa |
|
|
10 |
|
|
|
11 |
|
|
|
12 |
class Queue(): |
|
|
13 |
def __init__(self, max_len=50): |
|
|
14 |
self.items = [] |
|
|
15 |
self.max_len = max_len |
|
|
16 |
|
|
|
17 |
def __len__(self): |
|
|
18 |
return len(self.items) |
|
|
19 |
|
|
|
20 |
def add(self, item): |
|
|
21 |
self.items.insert(0, item) |
|
|
22 |
if len(self) > self.max_len: |
|
|
23 |
self.items.pop() |
|
|
24 |
|
|
|
25 |
def mean(self): |
|
|
26 |
return np.mean(self.items) |
|
|
27 |
|
|
|
28 |
def std(self): |
|
|
29 |
return np.std(self.items) |
|
|
30 |
|
|
|
31 |
|
|
|
32 |
def reverse_tensor(x): |
|
|
33 |
return x[torch.arange(x.size(0) - 1, -1, -1)] |
|
|
34 |
|
|
|
35 |
|
|
|
36 |
##### |
|
|
37 |
|
|
|
38 |
|
|
|
39 |
def get_grad_norm( |
|
|
40 |
parameters: Union[torch.Tensor, Iterable[torch.Tensor]], |
|
|
41 |
norm_type: float = 2.0) -> torch.Tensor: |
|
|
42 |
""" |
|
|
43 |
Adapted from: https://pytorch.org/docs/stable/_modules/torch/nn/utils/clip_grad.html#clip_grad_norm_ |
|
|
44 |
""" |
|
|
45 |
|
|
|
46 |
if isinstance(parameters, torch.Tensor): |
|
|
47 |
parameters = [parameters] |
|
|
48 |
parameters = [p for p in parameters if p.grad is not None] |
|
|
49 |
|
|
|
50 |
norm_type = float(norm_type) |
|
|
51 |
|
|
|
52 |
if len(parameters) == 0: |
|
|
53 |
return torch.tensor(0.) |
|
|
54 |
|
|
|
55 |
device = parameters[0].grad.device |
|
|
56 |
|
|
|
57 |
total_norm = torch.norm(torch.stack( |
|
|
58 |
[torch.norm(p.grad.detach(), norm_type).to(device) for p in |
|
|
59 |
parameters]), norm_type) |
|
|
60 |
|
|
|
61 |
return total_norm |
|
|
62 |
|
|
|
63 |
|
|
|
64 |
def write_xyz_file(coords, atom_types, filename): |
|
|
65 |
out = f"{len(coords)}\n\n" |
|
|
66 |
assert len(coords) == len(atom_types) |
|
|
67 |
for i in range(len(coords)): |
|
|
68 |
out += f"{atom_types[i]} {coords[i, 0]:.3f} {coords[i, 1]:.3f} {coords[i, 2]:.3f}\n" |
|
|
69 |
with open(filename, 'w') as f: |
|
|
70 |
f.write(out) |
|
|
71 |
|
|
|
72 |
|
|
|
73 |
def write_sdf_file(sdf_path, molecules): |
|
|
74 |
# NOTE Changed to be compatitble with more versions of rdkit |
|
|
75 |
#with Chem.SDWriter(str(sdf_path)) as w: |
|
|
76 |
# for mol in molecules: |
|
|
77 |
# w.write(mol) |
|
|
78 |
|
|
|
79 |
w = Chem.SDWriter(str(sdf_path)) |
|
|
80 |
w.SetKekulize(False) |
|
|
81 |
for m in molecules: |
|
|
82 |
if m is not None: |
|
|
83 |
w.write(m) |
|
|
84 |
|
|
|
85 |
# print(f'Wrote SDF file to {sdf_path}') |
|
|
86 |
|
|
|
87 |
|
|
|
88 |
def residues_to_atoms(x_ca, atom_encoder): |
|
|
89 |
x = x_ca |
|
|
90 |
one_hot = F.one_hot( |
|
|
91 |
torch.tensor(atom_encoder['C'], device=x_ca.device), |
|
|
92 |
num_classes=len(atom_encoder) |
|
|
93 |
).repeat(*x_ca.shape[:-1], 1) |
|
|
94 |
return x, one_hot |
|
|
95 |
|
|
|
96 |
|
|
|
97 |
def get_residue_with_resi(pdb_chain, resi): |
|
|
98 |
res = [x for x in pdb_chain.get_residues() if x.id[1] == resi] |
|
|
99 |
assert len(res) == 1 |
|
|
100 |
return res[0] |
|
|
101 |
|
|
|
102 |
|
|
|
103 |
def get_pocket_from_ligand(pdb_model, ligand, dist_cutoff=8.0): |
|
|
104 |
|
|
|
105 |
if ligand.endswith(".sdf"): |
|
|
106 |
# ligand as sdf file |
|
|
107 |
rdmol = Chem.SDMolSupplier(str(ligand))[0] |
|
|
108 |
ligand_coords = torch.from_numpy(rdmol.GetConformer().GetPositions()).float() |
|
|
109 |
resi = None |
|
|
110 |
else: |
|
|
111 |
# ligand contained in PDB; given in <chain>:<resi> format |
|
|
112 |
chain, resi = ligand.split(':') |
|
|
113 |
ligand = get_residue_with_resi(pdb_model[chain], int(resi)) |
|
|
114 |
ligand_coords = torch.from_numpy( |
|
|
115 |
np.array([a.get_coord() for a in ligand.get_atoms()])) |
|
|
116 |
|
|
|
117 |
pocket_residues = [] |
|
|
118 |
for residue in pdb_model.get_residues(): |
|
|
119 |
if residue.id[1] == resi: |
|
|
120 |
continue # skip ligand itself |
|
|
121 |
|
|
|
122 |
res_coords = torch.from_numpy( |
|
|
123 |
np.array([a.get_coord() for a in residue.get_atoms()])) |
|
|
124 |
if is_aa(residue.get_resname(), standard=True) \ |
|
|
125 |
and torch.cdist(res_coords, ligand_coords).min() < dist_cutoff: |
|
|
126 |
pocket_residues.append(residue) |
|
|
127 |
|
|
|
128 |
return pocket_residues |
|
|
129 |
|
|
|
130 |
|
|
|
131 |
def batch_to_list(data, batch_mask): |
|
|
132 |
# data_list = [] |
|
|
133 |
# for i in torch.unique(batch_mask): |
|
|
134 |
# data_list.append(data[batch_mask == i]) |
|
|
135 |
# return data_list |
|
|
136 |
|
|
|
137 |
# make sure batch_mask is increasing |
|
|
138 |
idx = torch.argsort(batch_mask) |
|
|
139 |
batch_mask = batch_mask[idx] |
|
|
140 |
data = data[idx] |
|
|
141 |
|
|
|
142 |
chunk_sizes = torch.unique(batch_mask, return_counts=True)[1].tolist() |
|
|
143 |
return torch.split(data, chunk_sizes) |
|
|
144 |
|
|
|
145 |
|
|
|
146 |
def num_nodes_to_batch_mask(n_samples, num_nodes, device): |
|
|
147 |
assert isinstance(num_nodes, int) or len(num_nodes) == n_samples |
|
|
148 |
|
|
|
149 |
if isinstance(num_nodes, torch.Tensor): |
|
|
150 |
num_nodes = num_nodes.to(device) |
|
|
151 |
|
|
|
152 |
sample_inds = torch.arange(n_samples, device=device) |
|
|
153 |
|
|
|
154 |
return torch.repeat_interleave(sample_inds, num_nodes) |
|
|
155 |
|
|
|
156 |
|
|
|
157 |
def rdmol_to_nxgraph(rdmol): |
|
|
158 |
graph = nx.Graph() |
|
|
159 |
for atom in rdmol.GetAtoms(): |
|
|
160 |
# Add the atoms as nodes |
|
|
161 |
graph.add_node(atom.GetIdx(), atom_type=atom.GetAtomicNum()) |
|
|
162 |
|
|
|
163 |
# Add the bonds as edges |
|
|
164 |
for bond in rdmol.GetBonds(): |
|
|
165 |
graph.add_edge(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()) |
|
|
166 |
|
|
|
167 |
return graph |
|
|
168 |
|
|
|
169 |
|
|
|
170 |
def calc_rmsd(mol_a, mol_b): |
|
|
171 |
""" Calculate RMSD of two molecules with unknown atom correspondence. """ |
|
|
172 |
graph_a = rdmol_to_nxgraph(mol_a) |
|
|
173 |
graph_b = rdmol_to_nxgraph(mol_b) |
|
|
174 |
|
|
|
175 |
gm = isomorphism.GraphMatcher( |
|
|
176 |
graph_a, graph_b, |
|
|
177 |
node_match=lambda na, nb: na['atom_type'] == nb['atom_type']) |
|
|
178 |
|
|
|
179 |
isomorphisms = list(gm.isomorphisms_iter()) |
|
|
180 |
if len(isomorphisms) < 1: |
|
|
181 |
return None |
|
|
182 |
|
|
|
183 |
all_rmsds = [] |
|
|
184 |
for mapping in isomorphisms: |
|
|
185 |
atom_types_a = [atom.GetAtomicNum() for atom in mol_a.GetAtoms()] |
|
|
186 |
atom_types_b = [mol_b.GetAtomWithIdx(mapping[i]).GetAtomicNum() |
|
|
187 |
for i in range(mol_b.GetNumAtoms())] |
|
|
188 |
assert atom_types_a == atom_types_b |
|
|
189 |
|
|
|
190 |
conf_a = mol_a.GetConformer() |
|
|
191 |
coords_a = np.array([conf_a.GetAtomPosition(i) |
|
|
192 |
for i in range(mol_a.GetNumAtoms())]) |
|
|
193 |
conf_b = mol_b.GetConformer() |
|
|
194 |
coords_b = np.array([conf_b.GetAtomPosition(mapping[i]) |
|
|
195 |
for i in range(mol_b.GetNumAtoms())]) |
|
|
196 |
|
|
|
197 |
diff = coords_a - coords_b |
|
|
198 |
rmsd = np.sqrt(np.mean(np.sum(diff * diff, axis=1))) |
|
|
199 |
all_rmsds.append(rmsd) |
|
|
200 |
|
|
|
201 |
if len(isomorphisms) > 1: |
|
|
202 |
print("More than one isomorphism found. Returning minimum RMSD.") |
|
|
203 |
|
|
|
204 |
return min(all_rmsds) |
|
|
205 |
|
|
|
206 |
|
|
|
207 |
class AppendVirtualNodes: |
|
|
208 |
def __init__(self, max_ligand_size, atom_encoder, symbol): |
|
|
209 |
self.max_ligand_size = max_ligand_size |
|
|
210 |
self.atom_encoder = atom_encoder |
|
|
211 |
self.vidx = atom_encoder[symbol] |
|
|
212 |
|
|
|
213 |
def __call__(self, data): |
|
|
214 |
|
|
|
215 |
n_virt = self.max_ligand_size - data['num_lig_atoms'] |
|
|
216 |
mu = data['lig_coords'].mean(0, keepdim=True) |
|
|
217 |
sigma = data['lig_coords'].std(0).max() |
|
|
218 |
virt_coords = torch.randn(n_virt, 3) * sigma + mu |
|
|
219 |
|
|
|
220 |
# insert virtual atom column |
|
|
221 |
one_hot = torch.cat((data['lig_one_hot'][:, :self.vidx], |
|
|
222 |
torch.zeros(data['num_lig_atoms'])[:, None], |
|
|
223 |
data['lig_one_hot'][:, self.vidx:]), dim=1) |
|
|
224 |
virt_one_hot = torch.zeros(n_virt, len(self.atom_encoder)) |
|
|
225 |
virt_one_hot[:, self.vidx] = 1 |
|
|
226 |
virt_mask = torch.ones(n_virt) * data['lig_mask'][0] |
|
|
227 |
|
|
|
228 |
data['lig_coords'] = torch.cat((data['lig_coords'], virt_coords)) |
|
|
229 |
data['lig_one_hot'] = torch.cat((one_hot, virt_one_hot)) |
|
|
230 |
data['num_lig_atoms'] = self.max_ligand_size |
|
|
231 |
data['lig_mask'] = torch.cat((data['lig_mask'], virt_mask)) |
|
|
232 |
data['num_virtual_atoms'] = n_virt |
|
|
233 |
|
|
|
234 |
return data |