forked from RosettaCommons/RFdiffusion
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrun_inference.py
executable file
·205 lines (173 loc) · 6.52 KB
/
run_inference.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
#!/usr/bin/env python
"""
Inference script.
To run with base.yaml as the config,
> python run_inference.py
To specify a different config,
> python run_inference.py --config-name symmetry
where symmetry can be the filename of any other config (without .yaml extension)
See https://hydra.cc/docs/advanced/hydra-command-line-flags/ for more options.
"""
import re
import os, time, pickle
import torch
from omegaconf import DictConfig, OmegaConf
import hydra
import logging
from util import writepdb_multi, writepdb
from inference import utils as iu
from icecream import ic
from hydra.core.hydra_config import HydraConfig
import numpy as np
import random
import glob
def make_deterministic(seed=0):
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
@hydra.main(version_base=None, config_path="config/inference", config_name="base")
def main(conf: HydraConfig) -> None:
log = logging.getLogger(__name__)
if conf.inference.deterministic:
make_deterministic()
# Initialize sampler and target/contig.
sampler = iu.sampler_selector(conf)
# Loop over number of designs to sample.
design_startnum = sampler.inf_conf.design_startnum
if sampler.inf_conf.design_startnum == -1:
existing = glob.glob(sampler.inf_conf.output_prefix + "*.pdb")
indices = [-1]
for e in existing:
print(e)
m = re.match(".*_(\d+)\.pdb$", e)
print(m)
if not m:
continue
m = m.groups()[0]
indices.append(int(m))
design_startnum = max(indices) + 1
for i_des in range(design_startnum, design_startnum + sampler.inf_conf.num_designs):
if conf.inference.deterministic:
make_deterministic(i_des)
start_time = time.time()
out_prefix = f"{sampler.inf_conf.output_prefix}_{i_des}"
log.info(f"Making design {out_prefix}")
if sampler.inf_conf.cautious and os.path.exists(out_prefix + ".pdb"):
log.info(
f"(cautious mode) Skipping this design because {out_prefix}.pdb already exists."
)
continue
x_init, seq_init = sampler.sample_init()
denoised_xyz_stack = []
px0_xyz_stack = []
seq_stack = []
plddt_stack = []
x_t = torch.clone(x_init)
seq_t = torch.clone(seq_init)
# Loop over number of reverse diffusion time steps.
for num,t in enumerate(range(int(sampler.t_step_input), sampler.inf_conf.final_step - 1, -1)):
px0, x_t, seq_t, plddt = sampler.sample_step(
t=t, x_t=x_t, seq_init=seq_t, final_step=sampler.inf_conf.final_step
)
px0_xyz_stack.append(px0)
denoised_xyz_stack.append(x_t)
seq_stack.append(seq_t)
plddt_stack.append(plddt[0]) # remove singleton leading dimension
if conf.inference.dump_pdb:
bfacts = plddt.cpu().numpy()[0]
protein = px0.cpu().numpy()[:,:4]
pdb_str,line_num = "",0
for n,residue in enumerate(protein):
for xyz,atom in zip(residue,[" N ", " CA ", " C ", " O "]):
pdb_str += "%-6s%5s %4s %3s %s%4d %8.3f%8.3f%8.3f%6.2f%6.2f\n" % ("ATOM",line_num,atom,"GLY","A",n,*xyz,1,bfacts[n])
line_num += 1
dump_pdb_path = os.path.join(conf.inference.dump_pdb_path,f"{num}.pdb")
with open(dump_pdb_path,"w") as handle:
handle.write(pdb_str + "TER")
# Flip order for better visualization in pymol
denoised_xyz_stack = torch.stack(denoised_xyz_stack)
denoised_xyz_stack = torch.flip(
denoised_xyz_stack,
[
0,
],
)
px0_xyz_stack = torch.stack(px0_xyz_stack)
px0_xyz_stack = torch.flip(
px0_xyz_stack,
[
0,
],
)
# For logging -- don't flip
plddt_stack = torch.stack(plddt_stack)
bfact_stack = torch.flip(
plddt_stack,
[
0,
],
)
# Save outputs
os.makedirs(os.path.dirname(out_prefix), exist_ok=True)
final_seq = seq_stack[-1]
# Output glycines, except for motif region
final_seq = torch.where(
torch.argmax(seq_init, dim=-1) == 21, 7, torch.argmax(seq_init, dim=-1)
) # 7 is glycine
bfacts = torch.ones_like(final_seq.squeeze())
# make bfact=0 for diffused coordinates
bfacts[torch.where(torch.argmax(seq_init, dim=-1) == 21, True, False)] = 0
# pX0 last step
out = f"{out_prefix}.pdb"
# Now don't output sidechains
writepdb(
out,
denoised_xyz_stack[0, :, :4],
final_seq,
sampler.binderlen,
chain_idx=sampler.chain_idx,
bfacts=bfact_stack[0],
)
# run metadata
trb = dict(
config=OmegaConf.to_container(sampler._conf, resolve=True),
plddt=plddt_stack.cpu().numpy(),
device=torch.cuda.get_device_name(torch.cuda.current_device())
if torch.cuda.is_available()
else "CPU",
time=time.time() - start_time,
)
if hasattr(sampler, "contig_map"):
for key, value in sampler.contig_map.get_mappings().items():
trb[key] = value
with open(f"{out_prefix}.trb", "wb") as f_out:
pickle.dump(trb, f_out)
if sampler.inf_conf.write_trajectory:
# trajectory pdbs
traj_prefix = (
os.path.dirname(out_prefix) + "/traj/" + os.path.basename(out_prefix)
)
os.makedirs(os.path.dirname(traj_prefix), exist_ok=True)
out = f"{traj_prefix}_Xt-1_traj.pdb"
writepdb_multi(
out,
denoised_xyz_stack,
bfact_stack,
final_seq.squeeze(),
use_hydrogens=False,
backbone_only=False,
chain_ids=sampler.chain_idx,
)
out = f"{traj_prefix}_pX0_traj.pdb"
writepdb_multi(
out,
px0_xyz_stack,
bfact_stack,
final_seq.squeeze(),
use_hydrogens=False,
backbone_only=False,
chain_ids=sampler.chain_idx,
)
log.info(f"Finished design in {(time.time()-start_time)/60:.2f} minutes")
if __name__ == "__main__":
main()