Repository navigation
Expand file tree
/
Copy pathsmall_molecule_binding.py
More file actions
1410 lines (1230 loc) · 64.3 KB
/
Copy pathsmall_molecule_binding.py
File metadata and controls
1410 lines (1230 loc) · 64.3 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import copy
import gzip
import json
import os
import pathlib
import shutil
from functools import lru_cache
from impress.pipelines.impress_pipeline import ImpressBasePipeline
# Step constants for the outer state machine
STEP_DONE = 0 # pipeline complete
STEP_RFD3 = 1 # backbone diffusion
STEP_MPNN = 2 # mpnn + packmin refinement cycle
STEP_FASTRELAX = 3 # Rosetta FastRelax
STEP_INTERFACE = 4 # filter_shape (PyRosetta, gates fold prediction)
STEP_AF2 = 5 # fold prediction (Boltz-2 co-folding; name kept for compatibility)
STEP_RETRY_SEQ = 6 # internal: retry sequence prediction without backbone restart
# Ensemble transformation type labels
ETYPE_BACKBONE = 'generate backbone'
ETYPE_SEQUENCE = 'predict sequence'
ETYPE_FOLD = 'fold decoy'
# Thread caps per backend-run tool (see _tool_task_description). PyRosetta
# (packmin/fastrelax/filter_shape/filter_energy) is single-threaded regardless;
# LigandMPNN is PyTorch, whose CPU-side work is what the cap actually bounds.
ROSETTA_THREADS = 1
MPNN_THREADS = 4
# rfd3 (inside apptainer, which inherits the env -- no --cleanenv) and boltz are
# PyTorch too. Uncapped, boltz alone took ~30 cores of the Dragon primary on
# smoke job 22670942 and oversubscribed it; 8 x ~4 GPU tools per node leaves
# room for the Rosetta stages and Dragon's own pool workers.
GPU_TOOL_THREADS = 8
# ── Ensemble utility functions ─────────────────────────────────────────────
# maxsize sized for the whole job, not one pipeline: adaptive_decision() runs in
# a single manager process shared by every pipeline, so the live working set is
# (ensemble entries) x (n_pipelines) distinct paths -- 512 thrashed badly at 32
# pipelines. ~14 KB per cached CA trace, so 4096 costs ~57 MB of a 240 GB node.
@lru_cache(maxsize=4096)
def _parse_pdb_ca_coords(pdb_path: str) -> tuple:
coords = []
with open(pdb_path) as f:
for line in f:
if line.startswith('ATOM') and line[12:16].strip() == 'CA':
coords.append((float(line[30:38]), float(line[38:46]), float(line[46:54])))
return tuple(coords)
def _kabsch_rmsd(coords1, coords2) -> float:
import numpy as np
n = min(len(coords1), len(coords2))
P = np.array(coords1[:n], dtype=float)
Q = np.array(coords2[:n], dtype=float)
P -= P.mean(axis=0)
Q -= Q.mean(axis=0)
H = P.T @ Q
U, _, Vt = np.linalg.svd(H)
d = np.linalg.det(Vt.T @ U.T)
R = Vt.T @ np.diag([1.0, 1.0, d]) @ U.T
diff = (P @ R.T) - Q
return float(np.sqrt((diff ** 2).sum() / n))
def _ca_rmsd(path1: str, path2: str):
"""CA RMSD between two PDB files. Returns None for non-.pdb paths or empty coord sets."""
if not (isinstance(path1, str) and isinstance(path2, str)):
return None
if not (path1.endswith('.pdb') and path2.endswith('.pdb')):
return None
c1 = _parse_pdb_ca_coords(path1)
c2 = _parse_pdb_ca_coords(path2)
if not c1 or not c2:
return None
return _kabsch_rmsd(c1, c2)
# Keyed by path alone, which is sound because every task writes into its own
# {taskcount}_{taskname}/ directory and taskcount increments for every HPC task
# in the run -- no FASTA path is ever written twice.
#
# This memo is load-bearing, not an optimisation. _ensemble_selective_avg() calls
# _seq_identity() once per prior ensemble entry, so an uncached read made the
# 'sequence' adaptive branch O(ensemble) *blocking Lustre opens* per decision
# (~540 at ensemble 270). On job 22534628 (8 nodes / 32 pipelines) that branch
# dominated the time the adaptive callback spent occupying the event loop --
# 67.1% of manager wall clock over the run, 73-95% for its last nine hours, with
# p99 per-call latency 1.36s -> 56.0s versus the 16-pipeline baseline -- which
# starved task dispatch and dropped GPU utilisation to 0.7%. Memoising turns the
# run's total reads from O(entries^2) into O(entries). _parse_pdb_ca_coords above
# was already cached, which is exactly why the backbone/fold branches cost ~0.
#
# Negative results are deliberately NOT cached: '' means the file was missing or
# empty, and caching that would pin the failure for the rest of the run.
_FASTA_SEQ_CACHE: dict[str, str] = {}
def _read_fasta_seq(fasta_path: str) -> str:
if not fasta_path:
return ''
hit = _FASTA_SEQ_CACHE.get(fasta_path)
if hit is not None:
return hit
seq = []
try:
with open(fasta_path) as f:
for line in f:
if not line.startswith('>'):
seq.append(line.strip())
except FileNotFoundError:
return ''
out = ''.join(seq)
if out:
_FASTA_SEQ_CACHE[fasta_path] = out
return out
def _seq_identity(fasta1: str, fasta2: str):
"""Fraction of matching residues over shorter sequence. Returns None on empty."""
s1 = _read_fasta_seq(fasta1)
s2 = _read_fasta_seq(fasta2)
if not s1 or not s2:
return None
n = min(len(s1), len(s2))
return sum(a == b for a, b in zip(s1[:n], s2[:n])) / n
def _ensemble_selective_avg(
current_output: str,
prior_entries: list,
sim_fn,
similar_if_low: bool,
):
"""
Returns (overall_avg, selective_avg, has_data: bool).
selective_avg = average score of entries whose similarity to current is on the
'similar' side of the mean pairwise similarity.
has_data=False when prior_entries is empty or all similarity calls return None.
"""
if not prior_entries:
return None, None, False
scores = [t[1] for t in prior_entries]
sims = [sim_fn(current_output, t[3]) for t in prior_entries]
valid = [(s, sc) for s, sc in zip(sims, scores) if s is not None]
overall_avg = sum(scores) / len(scores)
if not valid:
return overall_avg, None, False
avg_sim = sum(s for s, _ in valid) / len(valid)
if similar_if_low:
sel_scores = [sc for s, sc in valid if s <= avg_sim]
else:
sel_scores = [sc for s, sc in valid if s >= avg_sim]
if not sel_scores:
return overall_avg, overall_avg, True
return overall_avg, sum(sel_scores) / len(sel_scores), True
def _stage_metrics_improving(
current: dict,
previous: dict | None,
specs: list,
rel_tolerance: float = 0.05,
) -> bool:
"""Metric-agnostic "is this retry attempt actually helping" check, shared by
adaptive_decision()'s 'fastrelax' and 'interface' short-circuit logic.
`specs` is a list of (metric_key, lower_is_better, threshold) triples. For
each metric present in both `current` and `previous` that was still failing
on the previous attempt (gap > 0), checks whether its gap-to-threshold
shrank by more than `rel_tolerance` of the previous gap. Returns True (an
improvement was found) if any tracked metric improved; False if every
still-failing metric stayed flat or got worse.
Returns True (never short-circuit) when `previous` is None/empty -- there is
no prior attempt on this backbone to compare against yet, so the first
failure always gets one retry regardless of this check."""
if not previous:
return True
for key, lower_is_better, threshold in specs:
cur_val, prev_val = current.get(key), previous.get(key)
if cur_val is None or prev_val is None:
continue
cur_gap = (cur_val - threshold) if lower_is_better else (threshold - cur_val)
prev_gap = (prev_val - threshold) if lower_is_better else (threshold - prev_val)
if prev_gap <= 0:
continue # this metric already passed on the previous attempt
if (prev_gap - cur_gap) > rel_tolerance * prev_gap:
return True
return False
# ── RFD3 guided-input utilities ────────────────────────────────────────────
def _ligand_resname_from_params(params_path: str) -> str:
"""Reads the 'NAME <resname>' record from a Rosetta .params file and returns
the exact literal residue name (e.g. 'A:R' for ALR.params). This is the
literal PDB/Rosetta residue name used in HETATM records for this ligand and
is NOT always equal to the params filename stem -- never assume otherwise,
and never hardcode a specific ligand's resname here or in any caller."""
with open(params_path) as fh:
for line in fh:
parts = line.split()
if len(parts) >= 2 and parts[0] == 'NAME':
return parts[1]
raise ValueError(f"no NAME record found in {params_path}")
def _find_ligand_hetatm_residue(st, ligand_chain_id: str = "B"):
"""Locates the ligand HETATM residue in a gemmi Structure. Tries
ligand_chain_id first; if Boltz didn't honor the requested chain letter,
falls back to the first HETATM residue found anywhere in the structure.
Returns None if no HETATM residue exists at all. Shared by
_normalize_ligand_id and _normalize_ligand_atom_names so both agree on
exactly which residue is "the ligand"."""
for model in st:
for chain in model:
if chain.name != ligand_chain_id:
continue
for res in chain:
if res.het_flag == 'H':
return res
for model in st:
for chain in model:
for res in chain:
if res.het_flag == 'H':
return res
return None
def _normalize_ligand_id(fold_pdb_path: str, ligand_resname: str, out_pdb_path: str,
ligand_chain_id: str = "B") -> bool:
"""Rewrites a Boltz co-folded PDB's ligand HETATM residue name (via gemmi) to
match ligand_resname, so RFD3's ligand/select_exposed/select_buried selectors
(which key off the literal resname) resolve against it. Purely a string edit
-- no coordinate transform, since Boltz already places the ligand correctly
relative to the protein it just folded. Writes out_pdb_path and returns True
on success. Returns False (writing nothing) if no HETATM residue is found at
all, so the caller can fall back to unguided diffusion instead of crashing.
NOTE: this only fixes the residue name. Boltz also assigns its own,
unrelated atom names within that residue -- see _normalize_ligand_atom_names
for why those need fixing too before the guided spec is usable."""
import gemmi
st = gemmi.read_structure(fold_pdb_path)
target_res = _find_ligand_hetatm_residue(st, ligand_chain_id)
if target_res is None:
return False
target_res.name = ligand_resname
st.write_pdb(out_pdb_path)
return True
# Fallback table keyed on Rosetta atom TYPE prefix, used only when a params
# ATOM name's leading alphabetic run doesn't parse to a valid element symbol.
# Mirrors scripts/derive_ligand_smiles.py's _ROSETTA_TYPE_ELEMENT_FALLBACK
# (duplicated, not imported -- see _params_heavy_atom_graph). Verified only
# against ALR's C/N/O/S/H atom set; extend if a future ligand needs 2-letter
# elements (Cl/Br/Zn, etc.).
_ROSETTA_TYPE_ELEMENT_FALLBACK = {
"Nhis": "N", "Nlys": "N",
"CH1": "C", "CH2": "C", "CH3": "C", "COO": "C", "aroC": "C",
"OH": "O", "OOC": "O", "ONH2": "O",
"Hapo": "H", "Hpol": "H",
"S": "S", "SH1": "S",
}
def _infer_ligand_element(atom_name: str, rosetta_type: str) -> str:
"""Infers an element symbol from a params ATOM record's name/type. Primary
rule: the atom NAME's leading alphabetic run is the element itself (e.g.
'C18' -> 'C', 'N11' -> 'N'); falls back to _ROSETTA_TYPE_ELEMENT_FALLBACK
keyed on the Rosetta TYPE prefix. Mirrors
scripts/derive_ligand_smiles.py's _infer_element (duplicated, not
imported -- that script is a standalone offline tool, not part of this
per-cycle pipeline path; scripts/ isn't an importable package)."""
import re
from rdkit import Chem
periodic_table = Chem.GetPeriodicTable()
match = re.match(r'[A-Za-z]+', atom_name)
if match:
candidate = match.group(0)
for length in (2, 1):
if len(candidate) >= length:
symbol = candidate[:length].capitalize()
if periodic_table.GetAtomicNumber(symbol) > 0:
return symbol
for prefix, element in _ROSETTA_TYPE_ELEMENT_FALLBACK.items():
if rosetta_type.startswith(prefix):
return element
raise ValueError(
f"could not infer element for atom name={atom_name!r} type={rosetta_type!r}"
)
def _params_heavy_atom_graph(params_path: str):
"""Parses a Rosetta .params file's ATOM/BOND records into a heavy-atom-only
connectivity graph: ({atom_name: element}, [(atom1, atom2), ...]) where
both bond endpoints are heavy atoms. Hydrogens are dropped entirely --
unlike scripts/derive_ligand_smiles.py (which needs them to resolve bond
order via DetermineBondOrders), _infer_ligand_atom_mapping only needs
connectivity for graph-isomorphism matching, so no bond-order solving or
placeholder hydrogen placement is needed here."""
atom_types = {}
bonds = []
with open(params_path) as fh:
for line in fh:
fields = line.split()
if not fields:
continue
record = fields[0]
if record == 'ATOM':
atom_types[fields[1]] = fields[2]
elif record in ('BOND', 'BOND_TYPE'):
bonds.append((fields[1], fields[2]))
elements = {name: _infer_ligand_element(name, rtype) for name, rtype in atom_types.items()}
heavy_names = {name for name, el in elements.items() if el != 'H'}
heavy_elements = {name: elements[name] for name in heavy_names}
heavy_bonds = [(a, b) for a, b in bonds if a in heavy_names and b in heavy_names]
return heavy_elements, heavy_bonds
def _resolve_reference_pdb_path(base_json_path: str) -> str:
"""Reads partial.input from the base RFD3 design spec and resolves it
relative to the spec's own directory (always pipeline_inputs). This is
the correctly-named, real-coordinate reference ligand structure already
shipped alongside every pipeline's inputs -- used as ground truth for
atom identity/connectivity/geometry in _infer_ligand_atom_mapping."""
with open(base_json_path) as fh:
base = json.load(fh)
ref = base['partial']['input']
if os.path.isabs(ref):
return ref
return os.path.join(os.path.dirname(base_json_path), ref)
def _iter_ligand_atom_names(pdb_path: str, resname: str):
"""Atom names (fixed-column PDB parsing) of every HETATM record in
pdb_path whose resname matches exactly. Fixed-column parsing (not a
whitespace split) is required because names like 'A:R' contain a colon
-- see _ligand_resname_from_params's docstring."""
names = []
with open(pdb_path) as fh:
for line in fh:
if line.startswith('HETATM') and line[17:20].strip() == resname:
names.append(line[12:16].strip())
return names
def _load_reference_ligand_coords(pdb_path: str, resname: str):
"""Reads {atom_name: (x, y, z)} for the first HETATM residue named
exactly resname in pdb_path. Mirrors
scripts/derive_ligand_smiles.py's _load_reference_coords (duplicated,
not imported -- see _params_heavy_atom_graph); uses the same
fixed-column parsing for the same reason (resnames like 'A:R' contain a
colon a whitespace split would mangle)."""
coords = {}
target_resseq = None
with open(pdb_path) as fh:
for line in fh:
if not (line.startswith('HETATM') or line.startswith('ATOM ')):
continue
if line[17:20].strip() != resname:
if coords:
break # moved past the matching residue's contiguous block
continue
resseq = line[22:26].strip()
if target_resseq is None:
target_resseq = resseq
elif resseq != target_resseq:
break # a different residue instance with the same name
atom_name = line[12:16].strip()
coords[atom_name] = (float(line[30:38]), float(line[38:46]), float(line[46:54]))
return coords
def _infer_ligand_atom_mapping(boltz_atoms: dict, params_path: str, reference_pdb_path: str):
"""Maps Boltz's arbitrarily-named ligand atom names onto the canonical
names read from params_path, via element+connectivity graph isomorphism
with a Kabsch-RMSD tie-break. boltz_atoms is
{boltz_atom_name: (element, (x, y, z))} for one ligand residue.
Boltz co-folding assigns its own atom names to the ligand (unrelated to
the params file's canonical names), so select_exposed/select_buried
(copied verbatim from the base RFD3 spec, keyed by canonical names) never
match a Boltz-derived PDB's atom names without this step. Bond order is
ignored throughout (the .params file has none) -- only element identity
and heavy-atom connectivity establish correspondence:
- reference graph: heavy atoms + bonds parsed straight from
params_path's ATOM/BOND records (exact, no perception needed)
- reference coordinates: the real 3D structure at reference_pdb_path
(already correctly named -- see _resolve_reference_pdb_path)
- query graph: boltz_atoms' connectivity, perceived from 3D distances
via rdkit's DetermineConnectivity (Boltz's ligand output carries no
CONECT records)
Local topological symmetry (e.g. a sulfonate's three interchangeable
terminal oxygens) can produce more than one graph-valid isomorphism; both
structures carry real, roughly comparable 3D coordinates for the same
ligand pose, so each candidate mapping is Kabsch-superposed against the
reference and the lowest-RMSD one wins -- deterministic, and grounded in
actual geometry rather than an arbitrary tiebreak. When more than one
isomorphism exists, the best-vs-next-best RMSD gap is logged so a
suspiciously close tie (a symmetry case this heuristic can't actually
distinguish) is visible after the fact rather than silently accepted.
Returns {boltz_name: canonical_name}, or None (never raises) if: heavy
atom counts or element multisets differ, the reference PDB is missing
coordinates for a params heavy atom, Boltz connectivity perception fails
or yields a disconnected graph, or no isomorphism exists at all --
callers must treat None exactly like _normalize_ligand_id returning
False (fall back to unguided diffusion)."""
from rdkit import Chem
from rdkit.Chem import rdDetermineBonds
from rdkit.Geometry import Point3D
ref_elements, ref_bonds = _params_heavy_atom_graph(params_path)
ref_resname = _ligand_resname_from_params(params_path)
ref_coords = _load_reference_ligand_coords(reference_pdb_path, ref_resname)
ref_names = [name for name in ref_elements if name in ref_coords]
if len(ref_names) != len(ref_elements):
return None # reference PDB is missing coordinates for a params heavy atom
if len(boltz_atoms) != len(ref_names):
return None
if sorted(element for element, _ in boltz_atoms.values()) != sorted(ref_elements[n] for n in ref_names):
return None
ref_mol = Chem.RWMol()
ref_idx = {}
for name in ref_names:
ref_idx[name] = ref_mol.AddAtom(Chem.Atom(ref_elements[name]))
for a, b in ref_bonds:
if a in ref_idx and b in ref_idx:
i, j = ref_idx[a], ref_idx[b]
if ref_mol.GetBondBetweenAtoms(i, j) is None:
ref_mol.AddBond(i, j, Chem.BondType.SINGLE)
ref_conf = Chem.Conformer(ref_mol.GetNumAtoms())
for name, idx in ref_idx.items():
ref_conf.SetAtomPosition(idx, Point3D(*ref_coords[name]))
ref_mol.AddConformer(ref_conf, assignId=True)
Chem.SanitizeMol(ref_mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_NONE)
boltz_names = list(boltz_atoms)
boltz_mol = Chem.RWMol()
boltz_idx = {}
for name in boltz_names:
element, _ = boltz_atoms[name]
boltz_idx[name] = boltz_mol.AddAtom(Chem.Atom(element))
boltz_conf = Chem.Conformer(boltz_mol.GetNumAtoms())
for name, idx in boltz_idx.items():
_, xyz = boltz_atoms[name]
boltz_conf.SetAtomPosition(idx, Point3D(*xyz))
boltz_mol.AddConformer(boltz_conf, assignId=True)
Chem.SanitizeMol(boltz_mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_NONE)
try:
rdDetermineBonds.DetermineConnectivity(boltz_mol)
except Exception:
return None
if len(Chem.GetMolFrags(boltz_mol)) != 1:
return None
matches = boltz_mol.GetSubstructMatches(ref_mol, uniquify=False, useChirality=False, maxMatches=10000)
if not matches:
return None
ref_coord_list = [ref_coords[name] for name in ref_names] # order == ref_mol atom order
best_mapping, best_rmsd, second_best_rmsd = None, None, None
for match in matches:
# match[i] is the boltz_mol atom index matched to ref_mol atom i (ref_names[i]).
query_coord_list = [boltz_atoms[boltz_names[qi]][1] for qi in match]
rmsd = _kabsch_rmsd(ref_coord_list, query_coord_list)
if best_rmsd is None or rmsd < best_rmsd:
second_best_rmsd = best_rmsd
best_rmsd = rmsd
best_mapping = {boltz_names[qi]: ref_names[i] for i, qi in enumerate(match)}
elif second_best_rmsd is None or rmsd < second_best_rmsd:
second_best_rmsd = rmsd
if len(matches) > 1:
gap = (second_best_rmsd - best_rmsd) if second_best_rmsd is not None else float('inf')
print(
f"[rfd3 guided] ligand atom-name mapping: {len(matches)} candidate "
f"isomorphisms, best RMSD={best_rmsd:.4f} vs next-best={second_best_rmsd:.4f} "
f"(gap={gap:.4f}) -- a small gap means the tie-break may not be decisive"
)
return best_mapping
def _normalize_ligand_atom_names(pdb_path: str, params_path: str, base_json_path: str,
out_pdb_path: str, ligand_chain_id: str = "B") -> bool:
"""Rewrites a resname-normalized guided PDB's ligand HETATM *atom* names
(not just its residue name -- see _normalize_ligand_id) to match the
canonical names read from params_path, via _infer_ligand_atom_mapping.
Required because select_exposed/select_buried in the guided RFD3 spec are
copied verbatim from the base spec and are keyed by those canonical
names, but Boltz assigns its own arbitrary atom names during co-folding
-- without this, RFD3's input validator rejects every guided run.
Writes out_pdb_path (may be the same path as pdb_path) and returns True
on success. Returns False (writing nothing) if no ligand residue is
found, or no full atom-name mapping could be established, so the caller
falls back to unguided diffusion instead of producing a guided spec RFD3
will reject."""
import gemmi
st = gemmi.read_structure(pdb_path)
target_res = _find_ligand_hetatm_residue(st, ligand_chain_id)
if target_res is None:
return False
boltz_atoms = {
atom.name: (atom.element.name, (atom.pos.x, atom.pos.y, atom.pos.z))
for atom in target_res
}
reference_pdb_path = _resolve_reference_pdb_path(base_json_path)
mapping = _infer_ligand_atom_mapping(boltz_atoms, params_path, reference_pdb_path)
if mapping is None:
return False
for atom in target_res:
atom.name = mapping[atom.name]
st.write_pdb(out_pdb_path)
return True
def _write_guided_rfd3_json(base_json_path: str, guided_pdb_path: str, partial_t: float,
out_json_path: str) -> bool:
"""Loads the base per-pipeline RFD3 InputSpecification JSON, copies its
ligand/select_exposed/select_buried fields verbatim, drops 'length',
replaces 'input' with guided_pdb_path, adds partial_t, and writes the
result to out_json_path. Only 'input'/'partial_t' differ from the base
file (besides the dropped 'length').
'length' is dropped because RFD3's DesignInputSpecification validator
rejects it outright when partial.input/partial_t (partial diffusion) are
set -- length is inferred from the input structure in that mode. The
base file's 'length' is only valid for from-scratch (non-partial)
diffusion.
Before writing, verifies every atom name referenced by select_exposed/
select_buried is actually present in guided_pdb_path's ligand residue --
fails safe (returns False, writes nothing) on a stale/mismatched base
spec or an atom-mapping bug, rather than reproducing RFD3's
ComponentValidationError in a new form. Returns True on success."""
with open(base_json_path) as fh:
base = json.load(fh)
partial = dict(base.get('partial', {}))
partial.pop('length', None)
ligand_key = partial.get('ligand')
expected_names = set()
for field in ('select_exposed', 'select_buried'):
names_csv = partial.get(field, {}).get(ligand_key, '')
expected_names.update(name for name in names_csv.split(',') if name)
present_names = set(_iter_ligand_atom_names(guided_pdb_path, ligand_key))
if not expected_names <= present_names:
return False
partial['input'] = guided_pdb_path
partial['partial_t'] = partial_t
guided = dict(base)
guided['partial'] = partial
with open(out_json_path, 'w') as fh:
json.dump(guided, fh, indent=4)
return True
def _prepare_guided_rfd3_inputs(base_json_path: str, fold_pdb_path: str, ligand_resname: str,
params_path: str, partial_t: float, taskdir: str):
"""Orchestrates _normalize_ligand_id + _normalize_ligand_atom_names +
_write_guided_rfd3_json: writes {taskdir}/in/guided_scaffold.pdb and
{taskdir}/in/guided_binder_design.json. Returns the guided JSON path, or
None if any step failed (no ligand found in fold_pdb_path, no full
atom-name mapping could be established, or the select_exposed/
select_buried coverage check failed) -- callers should fall back to
unguided diffusion in that case."""
guided_pdb = f"{taskdir}/in/guided_scaffold.pdb"
guided_json = f"{taskdir}/in/guided_binder_design.json"
if not _normalize_ligand_id(fold_pdb_path, ligand_resname, guided_pdb):
return None
if not _normalize_ligand_atom_names(guided_pdb, params_path, base_json_path, guided_pdb):
return None
if not _write_guided_rfd3_json(base_json_path, guided_pdb, partial_t, guided_json):
return None
return guided_json
class SmallMoleculeBindingPipeline(ImpressBasePipeline):
def __init__(self, name, flow, configs=None, **kwargs):
if configs is None:
configs = {}
# Legacy / bookkeeping attrs
self.passes = kwargs.get("passes", 1)
self.step_id = kwargs.get("step_id", 1)
self.seq_rank = kwargs.get("seq_rank", 0)
self.num_seqs = kwargs.get("num_seqs", 4)
self.sub_order = kwargs.get("sub_order", 0)
self.max_passes = kwargs.get("max_passes", 1)
self.mock = kwargs.get("mock", False)
self.current_scores = {}
self.iter_seqs = kwargs.get("iter_seqs", {})
self.previous_scores = kwargs.get("previous_score", {})
# GPU this pipeline's GPU tools ask the backend for (see
# _tool_task_description). None = no request; the tool sees all GPUs.
# Set before super().__init__, which registers the tasks and so
# builds their task descriptions.
self.gpu_index = kwargs.get("gpu_index", None)
# Seconds run() waits before its first stage (set by the runner when
# several pipelines share a GPU, to spread out the first rfd3 wave).
self.start_delay = kwargs.get("start_delay", 0)
super().__init__(name, flow, **configs, **kwargs)
# Paths
self.base_path = kwargs.get("base_path", os.getcwd())
self.scripts_path = kwargs.get(
"scripts_path", os.path.join(self.base_path, "scripts")
)
# input_dir: explicit input directory name (relative to base_path) or
# absolute path. Falls back to "<name>_in" when not provided.
_input_dir = kwargs.get("input_dir", "")
if _input_dir and os.path.isabs(_input_dir):
self.pipeline_inputs = _input_dir
elif _input_dir:
self.pipeline_inputs = os.path.join(self.base_path, _input_dir)
else:
self.pipeline_inputs = os.path.join(self.base_path, f"{self.name}_in")
self.mpnn_dir = kwargs.get("mpnn_dir") or os.environ.get("MPNN_DIR")
if not self.mpnn_dir:
raise ValueError("mpnn_dir must be supplied via kwarg or MPNN_DIR env var")
# Configurable tool paths and ensemble sizes
self.foundry_sif_path = kwargs.get("foundry_sif_path") or os.environ.get("FOUNDRY_SIF_PATH")
if not self.foundry_sif_path:
raise ValueError("foundry_sif_path must be supplied via kwarg or FOUNDRY_SIF_PATH env var")
self.boltz_cache_path = kwargs.get("boltz_cache_path") or os.environ.get("BOLTZ_CACHE")
if not self.boltz_cache_path:
raise ValueError("boltz_cache_path must be supplied via kwarg or BOLTZ_CACHE env var")
self.ligand_params = kwargs.get("ligand_params", "ALR.params")
self.mpnn_ensemble_size = kwargs.get("mpnn_ensemble_size", 1)
self.num_refine_cycles = kwargs.get("num_refine_cycles", 3)
self.diffusion_batch_size = kwargs.get("diffusion_batch_size", 2)
self.rfd3_partial_t = kwargs.get("rfd3_partial_t", 10.0)
# Quality thresholds (overridable at construction time)
self.backbone_max_ca_deviation = kwargs.get("backbone_max_ca_deviation", 2.0)
self.backbone_min_ss_fraction = kwargs.get("backbone_min_ss_fraction", 0.2)
self.fastrelax_max_interact = kwargs.get("fastrelax_max_interact", 0.0)
self.fastrelax_max_total_score = kwargs.get("fastrelax_max_total_score", 0.0)
self.fastrelax_max_fa_rep = kwargs.get("fastrelax_max_fa_rep", 150.0)
self.interface_min_sc = kwargs.get("interface_min_sc", 0.5)
self.fold_min_plddt = kwargs.get("fold_min_plddt", 70.0)
self.fold_min_ligand_iptm = kwargs.get("fold_min_ligand_iptm", None)
self.max_tasks = kwargs.get("max_tasks", 300)
# "best" (default) or "first": how analysis_backbone and analysis_sequence
# choose among the candidates their tool produced. "first" makes the
# pipeline open-loop -- no metric influences what goes downstream -- for
# the naive reference run. The candidate pools are unchanged either way,
# so the compute per backbone is identical and only the choice differs.
self.selection = kwargs.get("selection", "best")
# Output paths (legacy)
self.output_path = os.path.join(self.base_path, "myoutputs", self.name)
self.output_path_packmin = os.path.join(self.output_path, "packmin")
self.output_path_lmpnn = os.path.join(self.output_path, "lmpnn")
# Task tracking
self.taskcount = 0
self.previous_task = "START"
# State machine
self.state = {} # written by analysis tasks, read by adaptive_fn
self.next_step = STEP_RFD3
self._current_cycle_i = 0 # set by run() before each mpnn call
# ── Task registration ──────────────────────────────────────────────────
def register_pipeline_tasks(self):
if self.mock:
self._register_mock_tasks()
else:
self._register_real_tasks()
# ── Per-task environment for backend-run tools ─────────────────────────
def _tool_task_description(self, threads: int, gpu: bool = False) -> dict:
"""task_description giving one backend-run tool its own thread caps.
Each tool process gets its caps from the backend that launches it,
instead of inheriting them from the runner's os.environ. That is what
lets the caps reach a Dragon task on a remote node (env exported by
delta_gpu_run.sh does not survive `dragon -w ssh`), and lets each tool
be sized for itself rather than for the pipeline count.
The two backends treat `env` differently, so only the active one's key
is emitted:
- rhapsody's ConcurrentExecutionBackend passes `env` straight to
asyncio.create_subprocess_exec, which REPLACES the environment, so
it must be merged over os.environ here.
- Dragon's process_template env is MERGED by local services into the
target node's own environment (dragon/localservices/server.py,
`the_env = dict(os.environ); the_env.update(req_env)`), so only the
delta is sent. Sending the runner's whole environment would
overwrite the remote node's.
With gpu=True the tool is also given self.gpu_index as its only GPU.
Every GPU tool (rfd3, boltz, LigandMPNN) uses the first device it
sees, so without this they all share GPU 0.
- Dragon: a Policy(gpu_affinity=[g]) on the template. Setting
CUDA_VISIBLE_DEVICES in the template env does NOT work there: local
services applies the policy layout after merging the env, and a
policy with no gpu_affinity resolves to every GPU on the node, so
the variable is always overwritten (dragon/localservices/server.py
PopenProps; dragon/globalservices/policy_eval.py _get_gpu_affinity).
- Concurrent: the env is used as-is, so CUDA_VISIBLE_DEVICES works.
Dragon Batch does no GPU accounting of its own, so the device is
chosen per pipeline by the runner (gpu_index).
"""
from rhapsody.backends import ConcurrentExecutionBackend
caps = {var: str(threads) for var in (
"OMP_NUM_THREADS", "MKL_NUM_THREADS",
"OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS")}
# PASSIVE is what actually stops idle OpenMP teams spinning on cores.
caps["OMP_WAIT_POLICY"] = "PASSIVE"
pin_gpu = gpu and self.gpu_index is not None
if isinstance(self.flow.backend, ConcurrentExecutionBackend):
if pin_gpu:
caps["CUDA_VISIBLE_DEVICES"] = str(self.gpu_index)
return {"env": {**os.environ, **caps}}
template = {"env": caps}
if pin_gpu:
from dragon.infrastructure.policy import Policy
template["policy"] = Policy(gpu_affinity=[self.gpu_index])
return {"process_template": template}
# ── MOCK tasks ─────────────────────────────────────────────────────────
def _register_mock_tasks(self):
from mock import register_mock_tasks
register_mock_tasks(self)
# ── REAL tasks ─────────────────────────────────────────────────────────
def _register_real_tasks(self):
"""Register real HPC tasks that return shell command strings.
Every stage that runs an external tool is an asyncflow executable
task: the decorated coroutine does the in-process bookkeeping
(taskcount, task dirs, input prep) and returns the command, and the
execution backend places and runs it. Only the pure-Python analysis
stages are local_task=True.
"""
rosetta_td = self._tool_task_description(ROSETTA_THREADS)
# LigandMPNN runs on CUDA too, so it gets the pipeline's GPU as well.
mpnn_td = self._tool_task_description(MPNN_THREADS, gpu=True)
gpu_td = self._tool_task_description(GPU_TOOL_THREADS, gpu=True)
@self.auto_register_task()
async def rfd3(task_description: dict = gpu_td):
self.taskcount += 1
taskname = "rfd3"
self.previous_task = taskname
taskdir = f"{self.base_path}/{self.name}/{self.taskcount}_{taskname}"
os.makedirs(f"{taskdir}/in", exist_ok=True)
os.makedirs(f"{taskdir}/out", exist_ok=True)
base_inputs = f"{self.pipeline_inputs}/ALR_binder_design.json"
output_dir = f"{taskdir}/out"
fold_pdb = self.state.get('rfd3_input_pdb')
inputs = base_inputs
if fold_pdb:
params_path = f"{self.pipeline_inputs}/{self.ligand_params}"
ligand_resname = _ligand_resname_from_params(params_path)
guided_json = _prepare_guided_rfd3_inputs(
base_json_path=base_inputs,
fold_pdb_path=fold_pdb,
ligand_resname=ligand_resname,
params_path=params_path,
partial_t=self.rfd3_partial_t,
taskdir=taskdir,
)
if guided_json:
inputs = guided_json
cmd = (
f"bash {self.scripts_path}/rfd3.sh"
f" {self.foundry_sif_path}"
f" {output_dir}"
f" {inputs}"
f" {self.diffusion_batch_size}"
)
return cmd
@self.auto_register_task(local_task=True)
async def analysis_backbone():
out_dir = f"{self.base_path}/{self.name}/{self.taskcount}_rfd3/out"
json_files = [
f for f in os.listdir(out_dir)
if f.endswith('.json') and '_model_' in f
]
best = None
pool_best_dev = None
for jf in sorted(json_files):
with open(f"{out_dir}/{jf}") as fh:
data = json.load(fh)
m = data.get('metrics', {})
# RFD3's partial-diffusion (guided-backbone-feedback) mode never
# computes ligand-clash or secondary-structure metrics -- the
# 'n_clashing.ligand_clashes' key is absent entirely and
# helix_fraction/sheet_fraction come back as literal JSON NaN
# (so ss = NaN + NaN, and NaN > threshold is always False in
# Python) -- only max_ca_deviation and the interresidue clash
# counts are populated there. Unguided mode has all of these.
guided = 'n_clashing.ligand_clashes' not in m
if guided:
clashes = (
m.get('n_clashing.interresidue_clashes_w_sidechain', float('inf'))
+ m.get('n_clashing.interresidue_clashes_w_backbone', float('inf'))
)
else:
clashes = m.get('n_clashing.ligand_clashes', float('inf'))
dev = m.get('max_ca_deviation', float('inf'))
ss = m.get('helix_fraction', 0) + m.get('sheet_fraction', 0)
cand = {'file': jf, 'clashes': clashes, 'dev': dev, 'ss': ss,
'guided': guided}
if pool_best_dev is None or (clashes, dev) < pool_best_dev:
pool_best_dev = (clashes, dev)
if self.selection == "first":
# Open-loop: keep the first model (sorted order, *_model_0)
# and never look at the rest.
best = best or cand
elif best is None or clashes < best['clashes'] or (
clashes == best['clashes'] and dev < best['dev']
):
best = cand
if best is None:
self.state.update({
'last_analysis_step': 'backbone',
'last_analysis_metrics': {'pass': False},
})
self.state['ensemble'].append((
ETYPE_BACKBONE, 0.0, self.state.get('rfd3_input_pdb'), None,
))
return
backbone_path = os.path.join(out_dir, best['file'].replace('.json', '.cif.gz'))
self.state['best_backbone_path'] = backbone_path
passed = (
best['clashes'] == 0
and best['dev'] < self.backbone_max_ca_deviation
# SS fraction isn't computable in guided mode (see above) --
# skip that check there rather than fail unconditionally.
and (best['guided'] or best['ss'] > self.backbone_min_ss_fraction)
)
self.state.update({
'last_analysis_step': 'backbone',
'last_analysis_metrics': {
'pass': passed,
'best_model': best['file'],
'guided': best['guided'],
'ligand_clashes': best['clashes'],
'max_ca_deviation': best['dev'],
'ss_fraction': best['ss'],
# What the pool's best candidate scored, whichever one was
# taken. Recorded for the selection benchmark; nothing reads it.
'pool_best_clashes': pool_best_dev[0] if pool_best_dev else None,
'pool_best_dev': pool_best_dev[1] if pool_best_dev else None,
},
})
# One line per call so the cost of picking is recoverable from the
# job log: last_analysis_metrics stays in memory and telemetry does
# not carry it.
self.logger.pipeline_log(
f"[selection/backbone] mode={self.selection} "
f"chosen={best['file']} clashes={best['clashes']} dev={best['dev']} "
f"pool_best_clashes={pool_best_dev[0] if pool_best_dev else None} "
f"pool_best_dev={pool_best_dev[1] if pool_best_dev else None} "
f"pool_n={len(json_files)}"
)
self.state['ensemble'].append((
ETYPE_BACKBONE, best['ss'], self.state.get('rfd3_input_pdb'), backbone_path,
))
@self.auto_register_task()
async def mpnn(
fixed_residues_file: str | None = None,
task_description: dict = mpnn_td):
self.taskcount += 1
taskname = "mpnn"
self.previous_task = taskname
taskdir = f"{self.base_path}/{self.name}/{self.taskcount}_{taskname}"
os.makedirs(f"{taskdir}/in", exist_ok=True)
os.makedirs(f"{taskdir}/out", exist_ok=True)
cycle_i = self._current_cycle_i
pdb_path = self.state['best_backbone_path'] if cycle_i == 0 else self.state['best_packed_pdb']
n_batches = self.mpnn_ensemble_size if cycle_i == 0 else 1
batch_size = self.num_seqs
output_dir = f"{taskdir}/out"
# Copy input to a short fixed name to prevent filename accumulation
# across MPNN+packmin cycles (avoids 255-char limit in AF2 result zips)
pdb_path_orig = pdb_path
if pathlib.Path(pdb_path_orig).name.endswith('.cif.gz'):
short_name = 'binder.cif.gz'
else:
short_name = f'binder{pathlib.Path(pdb_path_orig).suffix}'
short_pdb = f"{taskdir}/in/{short_name}"
shutil.copy(pdb_path_orig, short_pdb)
pdb_path = short_pdb
# LigandMPNN (ProDy parsePDB) only reads PDB format; convert CIF.GZ.
if pdb_path.endswith('.cif.gz'):
import gemmi as _gemmi
pdb_for_mpnn = f"{taskdir}/in/binder.pdb"
with gzip.open(pdb_path, 'rb') as _f:
_cif_data = _f.read().decode()
_doc = _gemmi.cif.read_string(_cif_data)
_st = _gemmi.make_structure_from_block(_doc.sole_block())
_st.write_pdb(pdb_for_mpnn)
pdb_path = pdb_for_mpnn
if fixed_residues_file:
with open(fixed_residues_file) as f:
fixed_residues = f.read().strip()
else:
fixed_residues = ""
cmd = (
f"bash {self.scripts_path}/mpnn.sh"
f" {self.mpnn_dir}"
f" {pdb_path}"
f" {output_dir}"
f" {n_batches}"
f" {batch_size}"
f' "{fixed_residues}"'
)
return self.logged_command(f"{taskdir}/mpnn.log", cmd)
@self.auto_register_task(local_task=True)
async def analysis_sequence():
out_dir = f"{self.base_path}/{self.name}/{self.taskcount}_mpnn/out"
seqs_dir = f"{out_dir}/seqs"
self.state['last_mpnn_seqs_dir'] = seqs_dir
self.state['last_analysis_step'] = 'sequence'
best_conf = -1.0
best_lig_conf = 0.0
best_id = None
best_seq = None
pool_best_conf = -1.0
for fa_file in sorted(f for f in os.listdir(seqs_dir) if f.endswith('.fa')):
with open(f"{seqs_dir}/{fa_file}") as fh:
content = fh.read()
# LigandMPNN writes ONE file per input structure containing MULTIPLE
# records: a template record (echo of the input, no 'id=' field)
# followed by 'batch_size' real designed candidates ('id=1'..'id=N',
# each with overall_confidence/ligand_confidence). Evaluate every
# id= record across every file -- do not assume one candidate per file.
for record in content.split('>')[1:]:
lines = record.splitlines()
if not lines:
continue
header, seq = lines[0], ''.join(lines[1:]).strip()
try:
parts = {
kv.split('=')[0].strip(): kv.split('=')[1].strip()
for kv in header.split(',')
if '=' in kv
}
if 'id' not in parts:
continue # template record, not a real candidate
cand_id = parts['id']
conf = float(parts.get('overall_confidence', 0))
lig_conf = float(parts.get('ligand_confidence', 0))