-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsample_crossdock_mols.py
210 lines (170 loc) · 9.19 KB
/
sample_crossdock_mols.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
import numpy as np
import pandas as pd
import os
import argparse
from rdkit import Chem
import torch
import time
import shutil
from scipy.spatial import distance
from rdkit.Chem import rdmolfiles
from utils.volume_sampling import sample_discrete_number, bin_edges, prob_dist_df
from utils.templates import get_one_hot, get_pocket
from utils.templates import add_hydrogens, extract_hydrogen_coordinates, run_fpocket, extract_values
from src.lightning_anchor_gnn import AnchorGNN_pl
from src.lightning import AR_DDPM
from src.const import prot_mol_lj_rm, CROSSDOCK_LJ_RM
from src.noise import cosine_beta_schedule
from analysis.reconstruct_mol import reconstruct_from_generated
#from analysis.vina_docking import VinaDockingTask
from sampling.sample_mols import generate_mols_for_pocket
atom_dict = {'C': 0, 'N': 1, 'O': 2, 'S': 3, 'B': 4, 'Br': 5, 'Cl': 6, 'P': 7, 'I': 8, 'F': 9}
idx2atom = {0:'C', 1:'N', 2:'O', 3:'S', 4:'B', 5:'Br', 6:'Cl', 7:'P', 8:'I', 9:'F'}
CROSSDOCK_CHARGES = {'C': 6, 'O': 8, 'N': 7, 'F': 9, 'B':5, 'S': 16, 'Cl': 17, 'Br': 35, 'I': 53, 'P': 15}
pocket_atom_dict = {'C': 0, 'N': 1, 'O': 2, 'S': 3} # only 4 atoms types for pocket
vdws = {'C': 1.7, 'N': 1.55, 'O': 1.52, 'S': 1.8, 'B': 1.92, 'Br': 1.85, 'Cl': 1.75, 'P': 1.8, 'I': 1.98, 'F': 1.47}
parser = argparse.ArgumentParser()
parser.add_argument('--results-path', type=str, default='results',
help='path to save the results')
parser.add_argument('--data-path', action='store', type=str, default='/srv/home/mahdi.ghorbani/FragDiff/crossdock',
help='path to the test data for generating molecules')
parser.add_argument('--anchor-model', type=str, default='anchor_model.ckpt',
help='path to the anchor model. Note that for guidance, the anchor model should incorporate the conditionals')
parser.add_argument('--n-samples', type=int, default=20,
help='total number of ligands to generate per pocket')
parser.add_argument('--exp-name', type=str, default='exp-1',
help='name of the generation experiment')
parser.add_argument('--diff-model', type=str, default='diff-model.ckpt',
help='path to the diffusion model checkpoint')
parser.add_argument('--device', type=str, default='cuda:0')
parser.add_argument('--rejection-sampling', action='store_true', default=False, help='enable rejection sampling')
if __name__ == '__main__':
args = parser.parse_args()
torch_device = args.device
anchor_checkpoint = args.anchor_model
data_path = args.data_path
diff_model_checkpoint = args.diff_model
add_H = True # adding hydrogens to protein for LJ computation
model = AR_DDPM.load_from_checkpoint(diff_model_checkpoint, device=torch_device)
model = model.to(torch_device)
anchor_model = AnchorGNN_pl.load_from_checkpoint(anchor_checkpoint, device=torch_device)
anchor_model = anchor_model.to(torch_device)
split = torch.load(data_path + '/' + 'split_by_name.pt')
prefix = data_path + '/crossdocked_pocket10/'
if not os.path.exists(args.results_path):
print('creating results directory')
save_dir = args.results_path + '/' + args.exp_name
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
for n in range(100):
prot_name = prefix + split['test'][n][0]
lig_name = prefix + split['test'][n][1]
pocket_onehot, pocket_coords, lig_coords, _ = get_pocket(prot_name, lig_name, atom_dict, pocket_atom_dict=pocket_atom_dict, dist_cutoff=7)
# --------------- make a grid box around the pocket ----------------
min_coords = pocket_coords.min(axis=0) - 2.5 #
max_coords = pocket_coords.max(axis=0) + 2.5
x_range = slice(min_coords[0], max_coords[0] + 1, 1.5) # spheres of radius 1.5
y_range = slice(min_coords[1], max_coords[1] + 1, 1.5)
z_range = slice(min_coords[2], max_coords[2] + 1, 1.5)
grid = np.mgrid[x_range, y_range, z_range]
grid_points = grid.reshape(3, -1).T # This transposes the grid to a list of coordinates
# remove grids points not in 3.5A neighborhood of original ligand
distances_mol = distance.cdist(grid_points, lig_coords)
mask_mol = (distances_mol < 3.5).any(axis=1)
filtered_mol_points = grid_points[mask_mol]
# remove grid points that are close to the pocket
pocket_distances = distance.cdist(filtered_mol_points, pocket_coords)
mask_pocket = (pocket_distances < 2).any(axis=1)
grids = filtered_mol_points[~mask_pocket]
n_samples = args.n_samples
max_mol_sizes = []
fpocket_out = prot_name[:-4] + '_out'
shutil.rmtree(fpocket_out, ignore_errors=True)
if add_H:
add_hydrogens(prot_name)
prot_name_with_H = prot_name[:-4] + '_H.pdb'
H_coords = extract_hydrogen_coordinates(prot_name_with_H)
H_coords = torch.tensor(H_coords).float().to(torch_device)
#print('running fpocket!')
#try:
# run_fpocket(prot_name)
#except:
# print('Error in running fpocket! using random sizes')
# NOTE: using original molecule coordinates for making the grid
grids = torch.tensor(grids)
all_grids = [] # list of grids
all_H_coords = []
for i in range(n_samples):
all_grids.append(grids)
all_H_coords.append(H_coords)
pocket_vol = len(grids)
#if os.path.exists(fpocket_out):
# filename = prot_name[:-4] + '_out/pockets/pocket1_atm.pdb'
# score, drug_score, pocket_volume = extract_values(filename)
#else:
# print('running fpocket!')
# run_fpocket(prot_name)
# filename = prot_name[:-4] + '_out/pockets/pocket1_atm.pdb'
# score, drug_score, pocket_volume = extract_values(filename)
#print('pocket_volume', pocket_volume)
for i in range(n_samples):
max_mol_sizes.append(sample_discrete_number(pocket_vol))
pocket_onehot = torch.tensor(pocket_onehot).float()
pocket_coords = torch.tensor(pocket_coords).float()
lig_coords = torch.tensor(lig_coords).float()
pocket_size = len(pocket_coords)
t1 = time.time()
max_mol_sizes = np.array(max_mol_sizes)
print('maximum sizes for molecules', max_mol_sizes)
prot_mol_lj_rm = torch.tensor(prot_mol_lj_rm).to(torch_device)
mol_mol_lj_rm = torch.tensor(CROSSDOCK_LJ_RM).to(torch_device) / 100
lj_weight_scheduler = cosine_beta_schedule(500, s=0.01, raise_to_power=2)
weights = 1 - lj_weight_scheduler
weights = np.clip(weights, a_min=0.1, a_max=1.)
x, h, mol_masks = generate_mols_for_pocket(n_samples=n_samples,
num_frags=8,
pocket_size=pocket_size,
pocket_coords=pocket_coords,
pocket_onehot=pocket_onehot,
lig_coords=lig_coords,
anchor_model=anchor_model,
diff_model=model,
device=torch_device,
return_all=False,
max_mol_sizes=max_mol_sizes,
all_grids=all_grids,
rejection_sampling=args.rejection_sampling,
lj_guidance=True,
prot_mol_lj_rm=prot_mol_lj_rm,
mol_mol_lj_rm=mol_mol_lj_rm,
all_H_coords=all_H_coords,
guidance_weights=weights)
x = x.cpu().numpy()
h = h.cpu().numpy()
mol_masks = mol_masks.cpu().cpu().numpy()
# convert to SDF
all_mols = []
for k in range(len(x)):
mask = mol_masks[k]
h_mol = h[k]
x_mol = x[k][mask.astype(np.bool_)]
atom_inds = h_mol[mask.astype(np.bool_)].argmax(axis=1)
atom_types = [idx2atom[x] for x in atom_inds]
atomic_nums = [CROSSDOCK_CHARGES[i] for i in atom_types]
try:
mol_rec = reconstruct_from_generated(x_mol.tolist(), atomic_nums)
Chem.Kekulize(mol_rec)
all_mols.append(mol_rec)
except:
continue
t2 = time.time()
print('time to generate one is: ', (t2-t1)/n_samples)
save_path = save_dir + '/' + 'pocket_' + str(n)
# write sdf file of molecules
with rdmolfiles.SDWriter(save_path + '_mols.sdf') as writer:
for mol in all_mols:
if mol:
writer.write(mol)
np.save(save_path + '_coords.npy', x)
np.save(save_path + '_onehot.npy', h)
np.save(save_path + '_mol_masks.npy', mol_masks)