Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
4590 lines (4195 loc) · 165 KB
/
Copy pathcore.py
File metadata and controls
4590 lines (4195 loc) · 165 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
#!/usr/bin/env python3
"""
core.py — Pure computation layer for Anyone Can Dock.
No Streamlit imports. All functions return plain dicts / tuples.
Safe to import in Colab notebooks, pytest, or any UI framework.
Sections:
1. Constants
2. Utilities
3. Tool availability checks
4. Vina binary
5. Receptor preparation
6. pKaNET protonation pipeline
7. Ligand preparation
8. Docking
9. Bond order correction
10. SDF utilities
11. Structural analysis
12. PoseView REST API
13. Image utilities
14. 2D interaction diagram
15. PubChem compound search
16. RCSB protein search
17. ADMET predictions
"""
import os
import subprocess
import sys
import tempfile
import time
import re as _re
from pathlib import Path
# ============================================================================
# 1. CONSTANTS
# ============================================================================
METAL_RESNAMES = {
"MG", "ZN", "CA", "MN", "FE", "CU", "CO", "NI", "CD", "HG", "NA", "K", "HO",
"LA", "CE", "PR", "ND", "PM", "SM", "EU", "GD", "TB", "DY", "ER", "TM", "YB", "LU",
}
METAL_CHARGES = {
"MG": 2.0, "ZN": 2.0, "CA": 2.0, "MN": 2.0, "FE": 3.0,
"CU": 2.0, "CO": 2.0, "NI": 2.0, "CD": 2.0, "HG": 2.0, "HO": 3.0,
"LA": 3.0, "CE": 3.0, "PR": 3.0, "ND": 3.0, "PM": 3.0, "SM": 3.0,
"EU": 3.0, "GD": 3.0, "TB": 3.0, "DY": 3.0, "ER": 3.0, "TM": 3.0,
"YB": 3.0, "LU": 3.0,
"NA": 1.0, "K": 1.0,
}
EXCLUDE_IONS = set(
"HOH,WAT,DOD,SOL,NA,CL,K,CA,MG,ZN,MN,FE,CU,CO,NI,CD,HG,HO,"
"LA,CE,PR,ND,PM,SM,EU,GD,TB,DY,ER,TM,YB,LU".split(",")
)
GLYCAN_NAMES = {
"NAG", "BMA", "MAN", "FUC", "GAL", "GLC", "SIA", "NGA",
"FUL", "GLA", "BGC", "A2G", "LAT", "MAL", "CEL", "SUC",
"TRE", "GCS", "NDG", "NGC",
}
COFACTOR_NAMES = {
"ATP", "ADP", "AMP", "GTP", "GDP", "GMP",
"NAD", "NAP", "NDP", "FAD", "FMN",
"HEM", "HEC", "HEA",
"GOL", "PEG", "EDO", "MPD", "PGE", "PG4",
"SO4", "PO4", "SUL", "PHO",
"IHP", "TTP", "CTP", "UTP",
"COA", "SAM", "SAH",
"EPE", "MES", "TRS", "ACT", "ACY",
"HO", "LA", "CE", "PR", "ND", "PM", "SM", "EU", "GD", "TB", "DY", "ER", "TM", "YB", "LU",
}
HEME_RESNAMES = {"HEM", "HEC", "HEA", "HEB", "HDD", "HDM"}
_PV_MAX_RETRIES = 3
_PV_RETRY_DELAY = 10
_PV_POLL_ATTEMPTS = 60
# ============================================================================
# 2. UTILITIES
# ============================================================================
def run_cmd(cmd, cwd=None):
r = subprocess.run(
cmd, shell=isinstance(cmd, str),
capture_output=True, text=True, cwd=cwd,
)
return r.returncode, (r.stdout + r.stderr).strip()
def _rdkit_six_patch():
try:
from rdkit import six # noqa
except ImportError:
from io import StringIO as _SIO
from types import ModuleType as _MT
import rdkit as _rdkit
_m = _MT("six")
_m.StringIO = _SIO
_m.PY3 = True
_rdkit.six = _m
sys.modules["rdkit.six"] = _m
def _strip_h_from_pdb(pdb_path: str, out_path: str) -> bool:
import shutil
try:
lines = []
with open(pdb_path) as f:
for line in f:
rec = line[:6].strip()
atom_name = line[12:16].strip()
element = line[76:78].strip() if len(line) > 76 else ""
if rec in ("ATOM", "HETATM"):
if element.upper() == "H" or atom_name.startswith("H"):
continue
lines.append(line)
with open(out_path, "w") as f:
f.writelines(lines)
return True
except Exception:
shutil.copy(pdb_path, out_path)
return False
def convert_cif_to_pdb(cif_path: str, pdb_out_path: str) -> dict:
log = []
try:
import gemmi
doc = gemmi.cif.read(cif_path)
block = doc.sole_block()
st_obj = gemmi.make_structure_from_block(block)
st_obj.setup_entities()
st_obj.assign_label_seq_id()
pdb_str = st_obj.make_pdb_headers() + st_obj.make_pdb_string()
with open(pdb_out_path, "w") as f:
f.write(pdb_str)
if os.path.exists(pdb_out_path) and os.path.getsize(pdb_out_path) > 100:
log.append("CIF -> PDB conversion via gemmi")
return {"success": True, "pdb_path": pdb_out_path, "log": log}
log.append("gemmi produced empty PDB -- trying OpenBabel")
except ImportError:
log.append("gemmi not installed -- trying OpenBabel")
except Exception as e:
log.append(f"gemmi failed ({e}) -- trying OpenBabel")
try:
rc, out = run_cmd(f'obabel "{cif_path}" -O "{pdb_out_path}" -ipdb')
if not os.path.exists(pdb_out_path) or os.path.getsize(pdb_out_path) < 100:
rc, out = run_cmd(f'obabel "{cif_path}" -O "{pdb_out_path}"')
if os.path.exists(pdb_out_path) and os.path.getsize(pdb_out_path) > 100:
log.append("CIF -> PDB conversion via OpenBabel")
return {"success": True, "pdb_path": pdb_out_path, "log": log}
log.append(f"OpenBabel CIF->PDB produced empty file (exit {rc}): {out[:300]}")
except Exception as e:
log.append(f"OpenBabel CIF->PDB failed: {e}")
try:
from prody import parseMMCIF, writePDB as _writePDB
atoms = parseMMCIF(cif_path)
if atoms is not None and atoms.numAtoms() > 0:
_writePDB(pdb_out_path, atoms)
if os.path.exists(pdb_out_path) and os.path.getsize(pdb_out_path) > 100:
log.append("CIF -> PDB conversion via ProDy parseMMCIF")
return {"success": True, "pdb_path": pdb_out_path, "log": log}
log.append("ProDy parseMMCIF produced empty PDB")
else:
log.append("ProDy parseMMCIF returned None or 0 atoms")
except ImportError:
log.append("ProDy parseMMCIF not available")
except Exception as e:
log.append(f"ProDy parseMMCIF failed: {e}")
return {
"success": False,
"pdb_path": pdb_out_path,
"log": log,
"error": "All CIF->PDB conversion methods failed.",
}
def is_cif_file(filepath: str) -> bool:
ext = Path(filepath).suffix.lower()
if ext in (".cif", ".mmcif"):
return True
try:
with open(filepath) as f:
first_lines = f.read(512)
if first_lines.strip().startswith("data_"):
return True
except Exception:
pass
return False
# ============================================================================
# 3. TOOL AVAILABILITY CHECKS
# ============================================================================
def check_obabel():
import shutil
if shutil.which("obabel") is None:
return False, "obabel not found -- add 'openbabel' to packages.txt"
_, out = run_cmd("obabel --version")
return True, (out.splitlines()[0] if out else "ok")
# ============================================================================
# 4. VINA BINARY
# ============================================================================
def get_vina_binary(path: str = ""):
import platform
system = platform.system().lower()
machine = platform.machine().lower()
_BASE = "https://github.com/ccsb-scripps/AutoDock-Vina/releases/download/v1.2.7/"
if system == "linux":
_FNAME = "vina_1.2.7_linux_x86_64"
elif system == "darwin":
_FNAME = ("vina_1.2.7_mac_aarch64"
if machine in ("arm64", "aarch64")
else "vina_1.2.7_mac_x86_64")
elif system == "windows":
_FNAME = "vina_1.2.7_windows_x86_64.exe"
else:
return None, f"Unsupported platform: {system}/{machine}"
_URL = _BASE + _FNAME
if not path:
path = os.path.join(tempfile.gettempdir(), _FNAME)
def _download(url, dest):
import requests as _rq
r = _rq.get(url, stream=True, timeout=120, allow_redirects=True)
r.raise_for_status()
with open(dest, "wb") as f:
for chunk in r.iter_content(chunk_size=1 << 20):
f.write(chunk)
if not os.path.exists(path) or os.path.getsize(path) < 100_000:
try:
_download(_URL, path)
except Exception as e1:
if system == "darwin" and machine in ("arm64", "aarch64"):
_FNAME2 = "vina_1.2.7_mac_x86_64"
path2 = os.path.join(tempfile.gettempdir(), _FNAME2)
try:
_download(_BASE + _FNAME2, path2)
path = path2
except Exception as e2:
return None, f"Download failed: {e1} / x86_64 fallback: {e2}"
else:
return None, f"Download failed: {e1}"
if system != "windows":
os.chmod(path, 0o755)
return path, f"ok ({system}/{machine})"
# ============================================================================
# 5. RECEPTOR PREPARATION
# ============================================================================
_MIN_LIG_ATOMS = 4
def _collect_removable_ligands(atoms) -> list:
from prody import calcCenter
excl = EXCLUDE_IONS | GLYCAN_NAMES | COFACTOR_NAMES | HEME_RESNAMES | METAL_RESNAMES
het = atoms.select("hetatm and not water")
_BACKBONE = {"N", "CA", "C", "O"}
if het is None:
return []
results = []
for r in het.getHierView().iterResidues():
rn = (r.getResname() or "").strip().upper()
if rn in excl:
continue
if r.numAtoms() <= _MIN_LIG_ATOMS:
continue
_atom_names = set(r.getNames())
if _BACKBONE.issubset(_atom_names):
continue
ch = r.getChid()
ri = r.getResnum()
sel = (f"resname {rn} and resid {ri} and chain {ch}"
if ch and ch.strip()
else f"resname {rn} and resid {ri}")
lig_atoms = atoms.select(sel)
if lig_atoms is None or lig_atoms.numAtoms() == 0:
continue
cx_, cy_, cz_ = (float(v) for v in calcCenter(lig_atoms))
results.append({
"resname": rn,
"chain": ch,
"resid": ri,
"sel_str": sel,
"ligand_id": f"{rn}_{ch}_{ri}",
"n_atoms": lig_atoms.numAtoms(),
"atoms": lig_atoms,
"cx": cx_, "cy": cy_, "cz": cz_,
})
results.sort(key=lambda d: (-d["n_atoms"], d["chain"] != "A"))
return results
def detect_cocrystal_ligand(raw_pdb: str) -> dict:
from prody import parsePDB
atoms = parsePDB(raw_pdb)
if atoms is None:
return {"found": False}
cands = _collect_removable_ligands(atoms)
if not cands:
return {"found": False}
chosen = cands[0]
return {
"found": True,
"resname": chosen["resname"],
"chain": chosen["chain"],
"resid": chosen["resid"],
"sel_str": chosen["sel_str"],
"ligand_id": chosen["ligand_id"],
"cx": chosen["cx"], "cy": chosen["cy"], "cz": chosen["cz"],
"n_atoms": chosen["n_atoms"],
"atoms": chosen["atoms"],
}
def scan_ligands(raw_pdb: str) -> list:
try:
from prody import parsePDB, confProDy
confProDy(verbosity="none")
if is_cif_file(raw_pdb):
import tempfile as _tf
_tmp = _tf.mktemp(suffix=".pdb")
res = convert_cif_to_pdb(raw_pdb, _tmp)
if res["success"]:
raw_pdb = _tmp
atoms = parsePDB(raw_pdb)
if atoms is None:
return []
ligs = _collect_removable_ligands(atoms)
return [
{"resname": d["resname"], "chain": d["chain"],
"resid": d["resid"], "n_atoms": d["n_atoms"]}
for d in ligs
]
except Exception:
return []
def strip_and_convert_receptor(rec_raw: str, wdir) -> dict:
wdir = Path(wdir)
log = []
rec_fh = str(wdir / "rec.pdb")
rec_pdbqt = str(wdir / "rec.pdbqt")
try:
metal_lines = []
clean_lines = []
with open(rec_raw) as f:
for line in f:
field = line[:6].strip()
if (field in ("ATOM", "HETATM")
and line[17:20].strip().upper() in METAL_RESNAMES):
metal_lines.append(line)
else:
clean_lines.append(line)
rec_nometal = str(wdir / "receptor_atoms_nometal.pdb")
with open(rec_nometal, "w") as f:
f.writelines(clean_lines)
if metal_lines:
names = ", ".join(sorted({l[17:20].strip() for l in metal_lines}))
log.append(f"Stripped {len(metal_lines)} metal atom(s) before OpenBabel: {names}")
rc1, out1 = run_cmd(f'obabel "{rec_nometal}" -O "{rec_fh}" -h')
if not os.path.exists(rec_fh) or os.path.getsize(rec_fh) < 100:
raise ValueError(
f"OpenBabel H-addition produced empty file (exit {rc1}). Output: {out1[:400]}"
)
log.append("Hydrogens added")
rc2, out2 = run_cmd(
f'obabel "{rec_fh}" -O "{rec_pdbqt}" -xr --partialcharge gasteiger'
)
if not os.path.exists(rec_pdbqt) or os.path.getsize(rec_pdbqt) < 100:
raise ValueError(
f"PDBQT conversion produced empty file (exit {rc2}). Output: {out2[:400]}"
)
log.append("PDBQT conversion complete")
if metal_lines and os.path.exists(rec_fh):
try:
rec_lines = open(rec_fh).readlines()
rec_lines = [l for l in rec_lines if l.strip() != "END"]
rec_lines.extend(metal_lines)
rec_lines.append("END\n")
with open(rec_fh, "w") as f:
f.writelines(rec_lines)
log.append(
f"Re-added {len(metal_lines)} ion/metal atom(s) to receptor.pdb"
)
except Exception as e:
log.append(f"Could not re-add ions/metals to receptor.pdb: {e}")
if metal_lines:
pdbqt_lines = open(rec_pdbqt).readlines()
pdbqt_lines = [l for l in pdbqt_lines if l.strip() != "END"]
injected = 0
skipped_exotic = 0
_no_reinject = {
"HO", "LA", "CE", "PR", "ND", "PM", "SM",
"EU", "GD", "TB", "DY", "ER", "TM", "YB", "LU",
}
for ml in metal_lines:
try:
resname = ml[17:20].strip().upper()
if resname in _no_reinject:
skipped_exotic += 1
continue
serial = int(ml[6:11])
name = ml[12:16].strip()
chain = ml[21] if len(ml) > 21 else "A"
resid = int(ml[22:26])
x = float(ml[30:38])
y = float(ml[38:46])
z = float(ml[46:54])
charge = METAL_CHARGES.get(resname, 0.0)
atype = resname.capitalize()
pdbqt_lines.append(
f"HETATM{serial:5d} {name:<4s} {resname:<3s} "
f"{chain}{resid:4d} "
f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00"
f" {charge:+.3f} {atype}\n"
)
injected += 1
except Exception as e:
log.append(f"Could not re-inject metal line: {e}")
pdbqt_lines.append("END\n")
with open(rec_pdbqt, "w") as f:
f.writelines(pdbqt_lines)
if injected:
log.append(f"Re-injected {injected} metal atom(s) into PDBQT")
if skipped_exotic:
log.append(
f"Skipped re-injection of {skipped_exotic} lanthanide ion(s) "
f"into docking PDBQT"
)
log.append("Receptor PDBQT ready")
return {"success": True, "rec_fh": rec_fh, "rec_pdbqt": rec_pdbqt, "log": log}
except Exception as e:
log.append(f"ERROR: {e}")
return {"success": False, "error": str(e), "log": log}
def write_box_pdb(filename: str, cx, cy, cz, sx, sy, sz):
hx, hy, hz = sx / 2, sy / 2, sz / 2
corners = [
(cx + dx, cy + dy, cz + dz)
for dx in (-hx, hx)
for dy in (-hy, hy)
for dz in (-hz, hz)
]
with open(filename, "w") as f:
for i, (x, y, z) in enumerate(corners, 1):
f.write(
f"HETATM{i:5d} C BOX A 1 "
f"{x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 C\n"
)
f.write(
"CONECT 1 2 3 5\nCONECT 2 1 4 6\n"
"CONECT 3 1 4 7\nCONECT 4 2 3 8\n"
"CONECT 5 1 6 7\nCONECT 6 2 5 8\n"
"CONECT 7 3 5 8\nCONECT 8 4 6 7\n"
)
def write_vina_config(filename: str, cx, cy, cz, sx, sy, sz):
with open(filename, "w") as f:
f.write(
f"center_x = {cx:.4f}\n"
f"center_y = {cy:.4f}\n"
f"center_z = {cz:.4f}\n"
f"size_x = {sx}\n"
f"size_y = {sy}\n"
f"size_z = {sz}\n"
)
def prepare_receptor(
raw_pdb: str,
wdir,
center_mode: str = "auto",
manual_xyz: tuple = (0.0, 0.0, 0.0),
prody_sel: str = "",
box_size: tuple = (16, 16, 16),
preferred_ligand: str = "",
) -> dict:
from prody import parsePDB, calcCenter, writePDB
wdir = Path(wdir)
log = []
sx, sy, sz = box_size
try:
if is_cif_file(raw_pdb):
log.append("Detected mmCIF format -- converting to PDB")
converted_pdb = str(wdir / "converted_from_cif.pdb")
cif_result = convert_cif_to_pdb(raw_pdb, converted_pdb)
log.extend(cif_result["log"])
if not cif_result["success"]:
raise ValueError(
f"CIF -> PDB conversion failed: {cif_result.get('error', 'unknown')}"
)
raw_pdb = converted_pdb
atoms = parsePDB(raw_pdb)
if atoms is None:
raise ValueError("ProDy parsePDB returned None")
log.append(f"Parsed {atoms.numAtoms()} atoms")
ligand_pdb_path = None
cocrystal_ligand_id = ""
cx = cy = cz = 0.0
_all_ligs = _collect_removable_ligands(atoms)
_primary = None
if _all_ligs:
if preferred_ligand:
_pref = preferred_ligand.strip().upper()
_primary = next(
(d for d in _all_ligs if d["resname"].upper() == _pref), None
)
if _primary is None:
log.append(
f"Preferred ligand '{preferred_ligand}' not found "
f"-- using largest ({_all_ligs[0]['resname']})"
)
if _primary is None:
_primary = _all_ligs[0]
if _primary is not None:
rn = _primary["resname"]
ch = _primary["chain"]
ri = _primary["resid"]
cocrystal_ligand_id = _primary["ligand_id"]
ligand_pdb_path = str(wdir / "LIG.pdb")
writePDB(ligand_pdb_path, _primary["atoms"])
_n_extra = len(_all_ligs) - 1
log.append(
f"Co-crystal ligand: {rn} chain '{ch}' resnum {ri} "
f"({_primary['n_atoms']} atoms)"
+ (f" +{_n_extra} additional ligand(s) removed" if _n_extra else "")
)
if center_mode == "auto":
if _primary is not None:
cx, cy, cz = _primary["cx"], _primary["cy"], _primary["cz"]
log.append(f"Auto center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
log.append(f"PoseView2 ligand ID: {cocrystal_ligand_id}")
else:
log.append("No co-crystal ligand found")
elif center_mode == "manual":
cx, cy, cz = (float(v) for v in manual_xyz)
log.append(f"Manual center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
if _primary is not None:
log.append(f"PoseView2 ligand ID: {cocrystal_ligand_id}")
elif center_mode == "selection":
if not prody_sel.strip():
raise ValueError("ProDy selection string is empty.")
ref_atoms = atoms.select(prody_sel.strip())
if ref_atoms is None or ref_atoms.numAtoms() == 0:
raise ValueError(f"ProDy selection '{prody_sel}' matched 0 atoms.")
cx, cy, cz = (float(v) for v in calcCenter(ref_atoms))
log.append(
f"ProDy selection: '{prody_sel}' -> {ref_atoms.numAtoms()} atoms"
)
log.append(f"Center: ({cx:.3f}, {cy:.3f}, {cz:.3f})")
if _primary is not None:
log.append(f"PoseView2 ligand ID: {cocrystal_ligand_id}")
if _all_ligs:
_excl_expr = " or ".join(f"({d['sel_str']})" for d in _all_ligs)
sel_str = f"not ({_excl_expr}) and not water"
if len(_all_ligs) > 1:
log.append(
f"Removing {len(_all_ligs)} ligand(s): "
+ ", ".join(f"{d['resname']}({d['n_atoms']}at)" for d in _all_ligs)
)
else:
sel_str = "not water"
rec_sel = atoms.select(sel_str)
if rec_sel is None or rec_sel.numAtoms() == 0:
raise ValueError("Receptor selection returned no atoms")
rec_raw_path = str(wdir / "receptor_atoms.pdb")
writePDB(rec_raw_path, rec_sel)
log.append(f"Receptor: {rec_sel.numAtoms()} atoms")
try:
_rec_lines = open(rec_raw_path).readlines()
_coord_lines = [l for l in _rec_lines if l[:6].strip() in ("ATOM", "HETATM")]
_all_blank = all(
(l[21] == " " if len(l) > 21 else True)
for l in _coord_lines
)
if _all_blank and _coord_lines:
_fixed = []
for l in _rec_lines:
if l[:6].strip() in ("ATOM", "HETATM") and len(l) > 21:
l = l[:21] + "A" + l[22:]
_fixed.append(l)
with open(rec_raw_path, "w") as _f:
_f.writelines(_fixed)
log.append("Assigned chain A to all blank-chain atoms")
except Exception as _ce:
log.append(f"Chain-fix skipped: {_ce}")
conv = strip_and_convert_receptor(rec_raw_path, wdir)
log.extend(conv["log"])
if not conv["success"]:
raise ValueError(conv["error"])
box_pdb = str(wdir / "rec.box.pdb")
cfg_path = str(wdir / "rec.box.txt")
write_box_pdb(box_pdb, cx, cy, cz, sx, sy, sz)
write_vina_config(cfg_path, cx, cy, cz, sx, sy, sz)
log.append("Box + config written")
return {
"success": True,
"rec_fh": conv["rec_fh"],
"rec_pdbqt": conv["rec_pdbqt"],
"box_pdb": box_pdb,
"config_txt": cfg_path,
"cx": cx, "cy": cy, "cz": cz,
"sx": sx, "sy": sy, "sz": sz,
"ligand_pdb_path": ligand_pdb_path,
"cocrystal_ligand_id": cocrystal_ligand_id,
"n_atoms": rec_sel.numAtoms(),
"all_ligands": [
{"resname": d["resname"], "chain": d["chain"],
"resid": d["resid"], "n_atoms": d["n_atoms"]}
for d in _all_ligs
],
"log": log,
}
except Exception as e:
log.append(f"ERROR: {e}")
return {"success": False, "error": str(e), "log": log}
# ============================================================================
# 6. pKaNET PROTONATION PIPELINE
# ============================================================================
_PKANET_CACHE: dict = {}
_PKA_PATTERNS = [
_re.compile(r"pK[aA][\w\s\(\)]*?=\s*([+-]?\d+(?:\.\d+)?)", _re.IGNORECASE),
_re.compile(
r"([+-]?\d+(?:\.\d+)?)\s*\((?:pK[aA]|acid dissociation)[^)]*\)",
_re.IGNORECASE,
),
]
_W_AROM_RING_LOST = 8.0
_W_PHENOL_TO_KETO_FLIP = 6.0
_W_PYROGALLOL_TRIKETO = 6.0
_W_CATECHOL_DIKETO = 4.0
_W_PHENOL_PRESERVED_BONUS = 0.5
_TAUTOMER_PLAUSIBILITY_CUTOFF = 3.0
_AMBIGUITY_SCORE_GAP = 0.5
def _detect_chromone_system(mol):
from rdkit import Chem
ring_info = mol.GetRingInfo()
rings = [set(r) for r in ring_info.AtomRings() if len(r) == 6]
if not rings:
return set()
def _has_exo_carbonyl(atom_idx):
atom = mol.GetAtomWithIdx(atom_idx)
if atom.GetSymbol() != "C":
return False
for bond in atom.GetBonds():
other = bond.GetOtherAtom(atom)
if other.GetSymbol() != "O" or other.IsInRing():
continue
bo = bond.GetBondTypeAsDouble()
if bo == 2.0:
return True
if (bo == 1.5 and other.GetTotalNumHs() == 0
and other.GetDegree() == 1):
return True
return False
pyrone_rings = [
ring for ring in rings
if sum(1 for i in ring
if mol.GetAtomWithIdx(i).GetSymbol() == "O") == 1
and any(_has_exo_carbonyl(i) for i in ring)
]
if not pyrone_rings:
return set()
system: set = set()
for py in pyrone_rings:
system.update(py)
for other in rings:
if other is not py and len(py & other) >= 2:
system.update(other)
return system
def _find_flavone_A_ring_phenols(mol):
chromone_atoms = _detect_chromone_system(mol)
if not chromone_atoms:
return []
ring_carbonyl_idx = None
ring_oxygen_idx = None
for idx in chromone_atoms:
atom = mol.GetAtomWithIdx(idx)
if atom.GetSymbol() == "C":
for bond in atom.GetBonds():
other = bond.GetOtherAtom(atom)
if (other.GetSymbol() == "O"
and not other.IsInRing()
and bond.GetBondTypeAsDouble() in (2.0, 1.5)
and other.GetTotalNumHs() == 0
and other.GetDegree() == 1):
ring_carbonyl_idx = idx
break
elif atom.GetSymbol() == "O" and atom.IsInRing():
ring_oxygen_idx = idx
def _chromone_nbrs(idx):
return [
n.GetIdx() for n in mol.GetAtomWithIdx(idx).GetNeighbors()
if n.GetIdx() in chromone_atoms
]
def _has_phenolic_OH(c_idx):
for bond in mol.GetAtomWithIdx(c_idx).GetBonds():
other = bond.GetOtherAtom(mol.GetAtomWithIdx(c_idx))
if (other.GetSymbol() == "O"
and other.GetTotalNumHs() >= 1
and other.GetDegree() == 1
and bond.GetBondTypeAsDouble() == 1.0
and not other.IsInRing()):
return True
return False
candidates = []
for atom in mol.GetAtoms():
c_idx = atom.GetIdx()
if c_idx not in chromone_atoms:
continue
if atom.GetSymbol() != "C" or not atom.GetIsAromatic():
continue
if c_idx == ring_carbonyl_idx:
continue
for bond in atom.GetBonds():
other = bond.GetOtherAtom(atom)
if (other.GetSymbol() == "O"
and other.GetTotalNumHs() >= 1
and other.GetDegree() == 1
and bond.GetBondTypeAsDouble() == 1.0
and not other.IsInRing()):
candidates.append((c_idx, other.GetIdx()))
break
sites = []
for c_idx, o_idx in candidates:
chromone_nbrs = _chromone_nbrs(c_idx)
ortho_carbons = [
n for n in chromone_nbrs
if mol.GetAtomWithIdx(n).GetSymbol() == "C"
]
ortho_to_carbonyl = False
carbonyl_direct = False
if ring_carbonyl_idx is not None:
if ring_carbonyl_idx in chromone_nbrs:
ortho_to_carbonyl = True
carbonyl_direct = True
else:
for nb in chromone_nbrs:
if any(
n.GetIdx() == ring_carbonyl_idx
for n in mol.GetAtomWithIdx(nb).GetNeighbors()
):
ortho_to_carbonyl = True
carbonyl_direct = False
break
ortho_to_ring_O = (ring_oxygen_idx is not None
and ring_oxygen_idx in chromone_nbrs)
n_ortho_phenols = sum(1 for n in ortho_carbons if _has_phenolic_OH(n))
if ortho_to_carbonyl:
if carbonyl_direct:
label, pka = "flavone_3OH_flavonol", 9.0
else:
label, pka = "flavone_5OH_chelated", 11.0
elif ortho_to_ring_O:
label, pka = "flavone_8OH_ortho_pyranO", 8.5
elif n_ortho_phenols >= 2:
label, pka = "flavone_6OH_pyrogallol_center", 8.5
elif n_ortho_phenols == 1:
label, pka = "flavone_phenol_catechol_pair", 7.0
else:
label, pka = "flavone_phenol_isolated", 7.0
sites.append({
"label": label,
"atom_indices": [o_idx, c_idx],
"ionizable_idx": o_idx,
"heuristic_pka": pka,
"site_type": "acid",
})
return sites
_IONIZABLE_SITE_DEF = [
("sulfonic_acid", "[SX4](=O)(=O)[OX2H1]", 1.0, "acid"),
("phosphoric_mono", "[PX4](=O)([OX2H1])([OX2H1])[OX2H1]", 2.1, "acid"),
("carboxylic_acid", "[CX3](=O)[OX2H1]", 4.5, "acid"),
("tetrazole", "c1nn[nH]n1", 4.9, "acid"),
("imidazole_acid", "c1cn[nH]c1", 6.0, "acid"),
("benzimidazole", "c1ccc2[nH]cnc2c1", 5.5, "acid"),
("phosphonate", "[PX4](=O)([OX2H1])[OX2H1,OX1-]", 6.5, "acid"),
("sulfonamide_NH", "[SX4](=O)(=O)[NX3;H1]", 10.1, "acid"),
("imide_NH", "[CX3](=O)[NX3;H1][CX3]=O", 9.6, "acid"),
("acylhydrazone_NH", "[CX3](=O)[NX3;H1][NX2]=[CX3]", 10.5, "acid"),
("hydrazide_NH", "[CX3](=O)[NX3;H1][NX3;H2]", 10.5, "acid"),
("urea_NH", "[NX3;H1][CX3](=O)[NX3;H1,H2]", 13.0, "acid"),
("amide_NH", "[CX3](=O)[NX3;H1,H2;!$([N]~N)]", 15.0, "acid"),
("phenol_diacyl", "[OX2H1][c;R]1[c;R][c;R](=O)[c;R][c;R][c;R]1=O", 3.5, "acid"),
("phenol_ortho_CO", "[OX2H1][c;R]:[c;R][CX3;R](=O)", 7.8, "acid"),
("catechol_OH", "[OX2H1][c;R]:[c;R][OX2H1]", 9.4, "acid"),
("phenol_EWG",
"[OX2H1][c;R]:[c;R][$([NX3](=O)=O),$([CX3]=O),$(C#N),$([SX4](=O)(=O))]", 7.2, "acid"),
("phenol", "c[OX2H1]", 10.0, "acid"),
("thiol_arom", "c[SX2H1]", 6.5, "acid"),
("thiol_aliph", "[CX4][SX2H1]", 10.5, "acid"),
("aniline", "c[NX3;H1,H2;!$(N~[!#6])]", 4.6, "base"),
("pyridine_like", "[$([nX2]1:[c,n]:c:[c,n]:c1),$([nX2]:c:n)]", 5.2, "base"),
("morpholine_N", "[NX3;H0;R;$(N1CC[O,S]CC1)]", 4.9, "base"),
("piperazine_NH", "[NX3;H1;R;$(N1CCNCC1)]", 8.1, "base"),
("piperazine_N_sub", "[NX3;H0;R;$(N1CCNCC1)]", 3.5, "base"),
("aliphatic_amine",
"[NX3;H1,H2;!$(NC=O);!$(N~[!#6;!H]);!$([nH]);!$(Nc)]", 9.5, "base"),
("aliphatic_amine_t",
"[NX3;H0;!$(NC=O);!$(Nc);!$([nH]);!$([N]~[!#6]);"
"!$([N;R]1CC[O,S]CC1);!$([N;R]1CCNCC1)]", 9.0, "base"),
("amidine", "[CX3](=[NX2;H0,H1])[NX3;H1,H2]", 12.4, "base"),
("guanidine", "[NX3][CX3](=[NX2])[NX3]", 13.0, "base"),
]
def _compile_ionizable_sites():
from rdkit import Chem
compiled = []
for lbl, sma, pka, stype in _IONIZABLE_SITE_DEF:
pat = Chem.MolFromSmarts(sma)
if pat is not None:
compiled.append((lbl, pat, pka, stype))
return compiled
_IONIZABLE_SITES_COMPILED = _compile_ionizable_sites()
def _find_ionizable_sites(mol):
sites = []
seen_ion = set()
claimed_atoms = set()
for site in _find_flavone_A_ring_phenols(mol):
ion_idx = site["ionizable_idx"]
if ion_idx in seen_ion:
continue
seen_ion.add(ion_idx)
claimed_atoms.update(site["atom_indices"])
sites.append(site)
for lbl, pat, pka, stype in _IONIZABLE_SITES_COMPILED:
for match in mol.GetSubstructMatches(pat):
if any(a in claimed_atoms for a in match):
continue
ion_idx = None
for idx in match:
a = mol.GetAtomWithIdx(idx)
if a.GetAtomicNum() in (7, 8, 16) and (
a.GetTotalNumHs() > 0 or a.GetFormalCharge() < 0
):
ion_idx = idx
break
if ion_idx is None:
for idx in match:
a = mol.GetAtomWithIdx(idx)
if a.GetAtomicNum() in (7, 8, 16):
ion_idx = idx
break
if ion_idx is None:
ion_idx = match[0]
if ion_idx in seen_ion:
continue
seen_ion.add(ion_idx)
sites.append({
"label": lbl,
"atom_indices": list(match),
"ionizable_idx": ion_idx,
"heuristic_pka": pka,
"site_type": stype,
})
return sites
def _hh_fraction_charged(pka, ph, site_type):
if site_type == "acid":
return 1.0 / (1.0 + 10.0 ** (pka - ph))
return 1.0 / (1.0 + 10.0 ** (ph - pka))
def _hh_match_score(pka, ph, site_type, actual_charge):
f_charged = _hh_fraction_charged(pka, ph, site_type)
dpH = abs(ph - pka)
decisive = (f_charged >= 0.65) or (f_charged <= 0.35)
rwd_mul = 1.6 if decisive else 1.0
pen_mul = 1.6 if decisive else 1.0
if site_type == "acid":
expected_neg = f_charged > 0.5
if expected_neg and actual_charge < 0:
return min(1.5, dpH * 0.55 * rwd_mul) + 0.15
elif expected_neg:
return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
elif actual_charge >= 0:
return 0.15
else:
return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
else:
expected_pos = f_charged > 0.5
if expected_pos and actual_charge > 0:
return min(1.5, dpH * 0.55 * rwd_mul) + 0.15
elif expected_pos:
return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
elif actual_charge <= 0:
return 0.15
else:
return -min(1.5, dpH * 0.45 * pen_mul) - 0.15
_CHEM_BONUS_DEF = [
("amide", +2.5, "[CX3](=O)[NX3;H1,H2]"),
("lactam", +2.5, "[C;R](=O)[N;R]"),
("urea_NH", +1.5, "[NX3;H1][CX3](=O)[NX3;H1,H2]"),
("thioamide", +1.0, "[CX3](=S)[NX3;H1,H2]"),
("aromatic_ring", +0.3, "c1ccccc1"),
("phenol_preserved", _W_PHENOL_PRESERVED_BONUS, "c[OX2H1]"),
]
_CHEM_PENALTY_DEF = [
("lactim_ring", -4.0, "[C;R](=[NX2])[OX2H1]"),
("iminol_general", -3.5, "[NX2]=[CX3][OX2H1]"),
("amide_N_deproton", -5.0, "[$([NX3-]C=O),$([NX3-]c=O)]"),
("enol_simple", -1.2, "[CX3](=[CX3])[OX2H1]"),
("exo_imine_arom", -2.5, "[NX2;!r]=[cX3]"),
("pyrogallol_triketo", -_W_PYROGALLOL_TRIKETO,
"[#6;!a;R]1(=O)[#6;!a;R](=O)[#6;!a;R](=O)[#6;R][#6;R][#6;R]1"),
("catechol_diketo", -_W_CATECHOL_DIKETO,
"[#6;!a;R]1(=O)[#6;!a;R](=O)[#6;R][#6;R][#6;R][#6;R]1"),
]
def _compile_chem_rules():
from rdkit import Chem
rules = []
for lbl, wt, sma in _CHEM_BONUS_DEF + _CHEM_PENALTY_DEF:
pat = Chem.MolFromSmarts(sma)
if pat is not None:
rules.append((lbl, wt, pat))
return rules
_CHEM_RULES = _compile_chem_rules()
def _n_aromatic_rings(mol):
if mol is None:
return 0
try:
from rdkit.Chem import rdMolDescriptors
return int(rdMolDescriptors.CalcNumAromaticRings(mol))
except Exception:
return 0
def _count_phenolic_OH(mol):
if mol is None:
return 0
from rdkit import Chem