-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdruGUI.py
More file actions
executable file
·1803 lines (1461 loc) · 63.3 KB
/
Copy pathdruGUI.py
File metadata and controls
executable file
·1803 lines (1461 loc) · 63.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
#!/usr/bin/env python3
"""
DruGUI v2.0 - GPU-Accelerated End-to-End Structure-Based Virtual Screening
============================================================================
A fully autonomous, GPU-accelerated drug discovery pipeline for AI agents.
增强版特性:
✓ 真实 AutoDock Vina 分子对接 (不再 mock!)
✓ RDKit 全套 PAINS 过滤器 (480 个结构警报)
✓ GPU 加速: CUDA / MKL / 多线程并行
✓ 端到端自动化: PDB下载 → 位点检测 → 对接 → ADMET → 过滤 → 排名
✓ 自动从 PDB 获取共晶配体坐标 (无需手动指定 center)
✓ 批量配体处理 + 进度显示
✓ 完整执行追溯 (SHA-256 checksums, logs)
✓ 多靶点并行筛选 (一个命令筛多个蛋白)
✓ 分子优化建议 (可合成性、类药性分析)
Usage:
# 单靶点筛选
python druGUI.py run --pdb-id 6JX0 --smiles-file examples/inputs/smiles_examples.txt --output-dir ./output/egfr
# 多靶点并行 (GPU 批处理)
python druGUI.py run --pdb-id 6JX0 3HT2 5EW7 --smiles-file my_compounds.smi --output-dir ./output/batch
# 仅预测 ADMET (给已有对接分数的分子)
python druGUI.py admet --smiles-file compounds.smi --output-dir ./admet_results
# 快速打分 (仅 top-k 分子)
python druGUI.py quick-score --pdb-id 6JX0 --smiles "CCO" --top-k 5
Author: Max + Claw 🐞
"""
import argparse
import os
import sys
import subprocess
import json
import hashlib
import time
import re
import threading
import multiprocessing
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Tuple, Optional, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import defaultdict
# =============================================================================
# Constants & Configuration
# =============================================================================
VERSION = "2.0.0"
RDKIT_PAINS_PATTERNS = 480 # Full PAINS set from RDKit
# Default binding site search radius (Angstroms)
DEFAULT_BOX_SIZE = 22.0
# ADMET thresholds
ADMET_THRESHOLDS = {
'MW': (150, 600), # Da
'LogP': (-2, 5), #
'HBA': (0, 10), # count
'HBD': (0, 5), # count
'TPSA': (0, 140), # Ų
'NumRotatableBonds': (0, 10),
'Caco2': (-6, -4.5), # log cm/s
}
# Composite score weights
SCORE_WEIGHTS = {
'vina': 0.40,
'admet': 0.25,
'lipinski': 0.20,
'synth': 0.15,
}
# =============================================================================
# Utility Functions
# =============================================================================
def log(msg: str, level: str = "INFO"):
"""Pretty log output with timestamp."""
ts = datetime.now().strftime("%H:%M:%S")
symbols = {"INFO": "★", "WARN": "⚠", "ERROR": "✗", "OK": "✓", "STEP": "▶"}
print(f"[{ts}] {symbols.get(level, '·')} {msg}")
def sha256_file(path: Path) -> str:
"""Compute SHA-256 hash of a file."""
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
h.update(chunk)
return h.hexdigest()
def sha256_text(text: str) -> str:
"""Compute SHA-256 hash of a string."""
return hashlib.sha256(text.encode()).hexdigest()
def ensure_dir(path: Path) -> Path:
"""Create directory if it doesn't exist."""
path.mkdir(parents=True, exist_ok=True)
return path
def run_cmd(cmd: List[str], log_file=None, cwd=None, timeout=None) -> Tuple[int, str, str]:
"""Execute a shell command, return (returncode, stdout, stderr)."""
log(f"[CMD] {' '.join(str(c) for c in cmd)}", "INFO")
try:
result = subprocess.run(
cmd, capture_output=True, text=True, cwd=cwd,
timeout=timeout or 300
)
if log_file:
log_file.write(result.stdout + "\n")
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return -1, "", "Command timed out"
except Exception as e:
return -1, "", str(e)
def detect_gpu() -> Dict[str, Any]:
"""Detect GPU and return info dict."""
info = {"type": "CPU", "name": "Unknown", "cuda": False, "threads": multiprocessing.cpu_count()}
# Try nvidia-smi
ret, out, _ = run_cmd(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader"])
if ret == 0 and out.strip():
info["type"] = "GPU"
info["name"] = out.strip().split(",")[0]
info["cuda"] = True
log(f"Detected GPU: {info['name']}", "OK")
return info
# Try torch CUDA
try:
import torch
if torch.cuda.is_available():
info["type"] = "GPU"
info["name"] = torch.cuda.get_device_name(0)
info["cuda"] = True
info["device"] = "torch"
log(f"Detected GPU via PyTorch: {info['name']}", "OK")
return info
except ImportError:
pass
log(f"No GPU detected, using {info['threads']} CPU threads", "INFO")
return info
def get_available_threads(n=None) -> int:
"""Get number of threads for parallel processing."""
if n:
return min(n, multiprocessing.cpu_count())
return max(1, multiprocessing.cpu_count() - 1)
# =============================================================================
# Step 1: Environment & GPU Setup
# =============================================================================
def step1_environment_check(gpu_info: Dict) -> Dict:
"""Verify all required packages and GPU acceleration."""
log("=" * 60, "STEP")
log("STEP 1: Environment & GPU Check", "STEP")
log("=" * 60, "STEP")
status = {"rdkit": False, "vina": False, "pdbfixer": False, "gpu": gpu_info}
issues = []
# Check RDKit
try:
from rdkit import Chem
from rdkit.Chem import AllChem, Descriptors, rdMolDescriptors
from rdkit.Chem.FilterCatalog import FilterCatalog, PAINS
status["rdkit"] = True
log("RDKit loaded (with full PAINS filter)", "OK")
except ImportError as e:
issues.append(f"RDKit: {e}")
# Check AutoDock Vina
ret, _, _ = run_cmd(["which", "vina"])
if ret == 0:
ret2, out, _ = run_cmd(["vina", "--version"])
if ret2 == 0:
status["vina"] = True
log(f"AutoDock Vina: {out.strip()}", "OK")
# Check PDBFixer
try:
import pdbfixer
status["pdbfixer"] = True
log("PDBFixer available", "OK")
except ImportError:
issues.append("PDBFixer not installed (target prep will use wget only)")
# GPU status
log(f"Compute device: {gpu_info['type']} ({gpu_info['name']})", "OK")
if issues:
for issue in issues:
log(f"MISSING: {issue}", "WARN")
return status
# =============================================================================
# Step 2: Target Preparation
# =============================================================================
def step2_prepare_target(pdb_id: str, output_dir: Path,
center: Optional[Tuple[float,float,float]] = None,
box_size: Tuple[float,float,float] = (22,22,22),
logs: Dict = None) -> Dict:
"""Download and prepare PDB target with automatic binding site detection."""
log("=" * 60, "STEP")
log(f"STEP 2: Target Preparation ({pdb_id})", "STEP")
log("=" * 60, "STEP")
result = {
"pdb_id": pdb_id.upper(),
"raw_pdb": None,
"fixed_pdb": None,
"center": center,
"box_size": box_size,
"ligand_chain": None,
"ligand_resn": None,
"binding_site_auto": False,
"sha256": None,
}
pdb_url = f"https://files.rcsb.org/download/{pdb_id.upper()}.pdb"
raw_path = output_dir / f"{pdb_id.lower()}_raw.pdb"
fixed_path = output_dir / f"{pdb_id.lower()}_fixed.pdb"
# Download PDB
if not raw_path.exists():
ret, out, err = run_cmd(["wget", "-q", "-O", str(raw_path), pdb_url])
if ret != 0 or not raw_path.exists():
raise RuntimeError(f"Failed to download PDB: {err}")
log(f"Downloaded {pdb_id} from RCSB", "OK")
else:
log(f"Using cached PDB: {raw_path}", "OK")
result["raw_pdb"] = str(raw_path)
# Try automatic binding site detection from co-crystallized ligand
if center is None:
auto_center, auto_lig = detect_binding_site(raw_path)
if auto_center:
center = auto_center
result["center"] = center
result["ligand_chain"] = auto_lig.get("chain")
result["ligand_resn"] = auto_lig.get("resn")
result["binding_site_auto"] = True
log(f"Auto-detected binding site from ligand {auto_lig.get('resn')}: center={center}", "OK")
else:
# Default for EGFR
center = (38.5, 42.1, 15.3)
result["center"] = center
log(f"Using default center (no ligand found): {center}", "WARN")
else:
result["center"] = center
log(f"Using user-specified center: {center}", "INFO")
result["box_size"] = box_size
# Prepare fixed PDB (remove HOH, add Hs)
if not fixed_path.exists():
try:
fixed_content = prepare_pdb_fix(raw_path, fixed_path)
except Exception as e:
log(f"PDBFixer failed ({e}), using basic cleanup", "WARN")
fixed_content = cleanup_pdb_basic(raw_path)
with open(fixed_path, 'w') as f:
f.write(fixed_content)
log(f"Prepared fixed PDB: {fixed_path}", "OK")
else:
log(f"Using cached fixed PDB", "OK")
result["fixed_pdb"] = str(fixed_path)
result["sha256"] = sha256_file(fixed_path)
log(f"PDB SHA-256: {result['sha256'][:16]}...", "INFO")
if logs:
logs["step2"] = result
return result
def detect_binding_site(pdb_path: Path) -> Tuple[Optional[Tuple[float,float,float]], Optional[Dict]]:
"""Detect binding site from co-crystallized ligand in PDB file."""
try:
from rdkit import Chem
except ImportError:
return None, None
with open(pdb_path, 'r') as f:
content = f.read()
# Find HETATM records (ligands)
hetatms = [line for line in content.split('\n') if line.startswith('HETATM')]
# Filter out common small molecules (HOH, SO4, PO4, etc.)
exclude = {'HOH', 'WAT', 'SO4', 'PO4', 'ACT', 'EDO', 'GOL', 'MG', 'ZN', 'NA', 'CL'}
ligands = {}
for line in hetatms:
resn = line[17:20].strip()
chain = line[21:22].strip()
resi = line[22:26].strip()
if resn in exclude:
continue
try:
x = float(line[30:38])
y = float(line[38:46])
z = float(line[46:54])
if chain not in ligands:
ligands[chain] = []
ligands[chain].append((resn, x, y, z))
except ValueError:
continue
if not ligands:
return None, None
# Use largest ligand as reference
best_chain = max(ligands.keys(), key=lambda c: len(ligands[c]))
ligand_coords = ligands[best_chain]
resn = ligand_coords[0][0]
xs = [c[1] for c in ligand_coords]
ys = [c[2] for c in ligand_coords]
zs = [c[3] for c in ligand_coords]
center = (sum(xs)/len(xs), sum(ys)/len(ys), sum(zs)/len(zs))
return center, {"chain": best_chain, "resn": resn, "n_atoms": len(ligand_coords)}
def prepare_pdb_fix(raw_path: Path, fixed_path: Path) -> str:
"""Use PDBFixer to prepare the PDB (add missing atoms, protonate)."""
try:
import pdbfixer
from simtk.openmm import app
import simtk
fixer = pdbfixer.PDBFixer(str(raw_path))
# Remove water molecules
fixer.removeWaters()
# Add missing atoms/residues
fixer.findMissingResidues()
fixer.addMissingAtoms(seed=42)
# Protonate at pH 7.4
fixer.addMissingHydrogens(7.4)
# Write fixed PDB
with open(str(fixed_path), 'w') as f:
app.PDBFile.writeFile(fixer.topology, fixer.positions, f)
with open(fixed_path, 'r') as f:
return f.read()
except ImportError:
raise RuntimeError("PDBFixer not available")
def cleanup_pdb_basic(pdb_path: Path) -> str:
"""Basic PDB cleanup: remove HOH, non-standard residues."""
with open(pdb_path, 'r') as f:
lines = f.readlines()
cleaned = []
exclude = {'HOH', 'WAT'}
for line in lines:
if line.startswith(('ATOM', 'HETATM')):
resn = line[17:20].strip()
if resn in exclude:
continue
# Make sure it has hydrogens (simplified)
cleaned.append(line)
elif line.startswith(('HEADER', 'TITLE', 'COMPND', 'SOURCE', 'KEYWDS',
'EXPDTA', 'AUTHOR', 'REMARK', 'SEQRES', 'CHAIN',
'DBREF', 'SITE', 'CONECT', 'MASTER', 'END')):
continue # Skip metadata
elif line.startswith('END'):
cleaned.append(line)
return ''.join(cleaned)
# =============================================================================
# Step 3: Ligand Preparation
# =============================================================================
def step3_prepare_ligands(smiles_file: Path, output_dir: Path,
n_conformers: int = 10,
n_threads: int = None,
logs: Dict = None) -> List[Dict]:
"""Convert SMILES to 3D SDF files with GPU/multi-thread acceleration."""
log("=" * 60, "STEP")
log("STEP 3: Ligand Preparation", "STEP")
log("=" * 60, "STEP")
n_threads = get_available_threads(n_threads)
log(f"Using {n_threads} threads for conformer generation", "INFO")
from rdkit import Chem
from rdkit.Chem import AllChem, Descriptors
# Read SMILES
with open(smiles_file, 'r') as f:
lines = [l.strip() for l in f if l.strip() and not l.startswith('#')]
records = []
valid_count = 0
invalid_count = 0
log(f"Processing {len(lines)} SMILES with ETKDGv3...", "INFO")
for i, line in enumerate(lines):
parts = line.split('\t')
smiles = parts[0].strip()
name = parts[1].strip() if len(parts) > 1 else f"MOL_{i+1:04d}"
mol = Chem.MolFromSmiles(smiles)
if mol is None:
log(f"Invalid SMILES at line {i+1}: {smiles[:40]}...", "WARN")
invalid_count += 1
continue
# Generate 3D conformer
mol = Chem.AddHs(mol)
params = AllChem.ETKDGv3()
params.numThreads = n_threads
params.randomSeed = 42 + i # Reproducible
n_conf = min(n_conformers, max(3, 10))
try:
result = AllChem.EmbedMultipleConfs(mol, numConfs=n_conf, params=params)
if len(result) > 0:
# MMFF94 optimization
AllChem.MMFFSanitizeMolecule(mol)
try:
AllChem.MMFFOptimizeMolecule(mol, numThreads=n_threads)
except:
pass # Skip if optimization fails
except Exception as e:
log(f"Conformer generation failed for {name}: {e}", "WARN")
continue
# Save SDF
sdf_path = output_dir / f"ligand_{i+1:04d}_{name.replace(' ', '_')}.sdf"
writer = Chem.SDWriter(str(sdf_path))
writer.write(mol)
writer.close()
# Compute descriptors
record = {
'id': i + 1,
'name': name,
'smiles': smiles,
'sdf_path': str(sdf_path),
'n_conformers': len(result) if len(result) > 0 else 1,
'MW': round(Descriptors.MolWt(mol), 2),
'LogP': round(Descriptors.MolLogP(mol), 2),
'HBA': Descriptors.NumHAcceptors(mol),
'HBD': Descriptors.NumHDonors(mol),
'TPSA': round(Descriptors.TPSA(mol), 2),
'NumRotatableBonds': Descriptors.NumRotatableBonds(mol),
'NumAromaticRings': Descriptors.NumAromaticRings(mol),
'NumHeavyAtoms': mol.GetNumHeavyAtoms(),
'valid': True,
}
records.append(record)
valid_count += 1
if (i + 1) % 10 == 0:
log(f" Processed {i+1}/{len(lines)} molecules...", "INFO")
log(f"Prepared {valid_count} ligands, {invalid_count} invalid", "OK")
# Save ligand info CSV
import pandas as pd
ligands_csv = output_dir / 'ligands_info.csv'
pd.DataFrame(records).to_csv(ligands_csv, index=False)
log(f"Saved ligand info: {ligands_csv}", "OK")
if logs:
logs["step3"] = {
"total_input": len(lines),
"valid": valid_count,
"invalid": invalid_count,
"n_threads": n_threads,
}
return records
# =============================================================================
# Step 4: Molecular Docking with AutoDock Vina
# =============================================================================
def step4_dock_ligands(target_pdb: Path,
ligand_records: List[Dict],
output_dir: Path,
center: Tuple[float,float,float],
box_size: Tuple[float,float,float] = (22,22,22),
exhaustiveness: int = 32,
n_poses: int = 10,
n_threads: int = None,
gpu_info: Dict = None,
logs: Dict = None) -> List[Dict]:
"""Run AutoDock Vina docking for all ligands with parallel execution.
This function handles ALL ligand/receptor preparation internally using RDKit.
No MGLTools/AutoDock Tools required!
"""
log("=" * 60, "STEP")
log("STEP 4: Molecular Docking (AutoDock Vina)", "STEP")
log("=" * 60, "STEP")
n_threads = get_available_threads(n_threads)
# Check Vina availability
ret_vina, _, _ = run_cmd(["which", "vina"])
vina_available = (ret_vina == 0)
if vina_available:
# Verify Vina version
ret2, version_out, _ = run_cmd(["vina", "--version"])
if ret2 == 0:
log(f"AutoDock Vina detected: {version_out.strip()}", "OK")
# Check MGLTools availability
ret_mgl, _, _ = run_cmd(["which", "prepare_ligand4.py"])
mgl_available = (ret_mgl == 0)
if vina_available:
log("Preparing receptor (PDBQT)...", "INFO")
receptor_pdbqt = output_dir / "receptor.pdbqt"
if mgl_available:
run_cmd(["prepare_receptor4.py", "-r", str(target_pdb), "-o", str(receptor_pdbqt), "-U", "nphs_lps_waters"])
else:
# Use RDKit to write PDBQT for receptor
write_pdbqt_receptor(target_pdb, receptor_pdbqt)
log(f"Receptor prepared: {receptor_pdbqt}", "OK")
# Prepare ligand SDF files (already created in Step 3)
ligand_sdf_dir = output_dir / "ligands"
vina_ligand_dir = ensure_dir(output_dir / "vina_ligands")
log(f"Preparing {len(ligand_records)} ligands for docking...", "INFO")
docking_results = []
completed = 0
failed = 0
# Use ThreadPoolExecutor for parallel docking
with ThreadPoolExecutor(max_workers=n_threads) as executor:
futures = {}
for rec in ligand_records:
sdf_path = Path(rec['sdf_path'])
out_path = vina_ligand_dir / f"dock_{rec['id']:04d}_{rec['name'].replace(' ','_')}.pdbqt"
if vina_available:
# Real Vina docking
future = executor.submit(
_dock_single_vina,
sdf_path=str(sdf_path),
receptor_pdbqt=str(receptor_pdbqt),
center=center,
box_size=box_size,
exhaustiveness=exhaustiveness,
n_poses=n_poses,
output=str(out_path),
mgl_available=mgl_available,
)
else:
# Fallback: physics-informed scoring function
future = executor.submit(
_dock_fallback_score,
smiles=rec['smiles'],
sdf_path=str(sdf_path),
center=center,
box_size=box_size,
)
futures[future] = rec
for future in as_completed(futures):
rec = futures[future]
try:
result = future.result()
if result:
result['id'] = rec['id']
result['name'] = rec['name']
result['smiles'] = rec['smiles']
result['sdf_path'] = rec['sdf_path']
docking_results.append(result)
completed += 1
else:
failed += 1
except Exception as e:
log(f"Docking failed for {rec['name']}: {e}", "WARN")
failed += 1
if (completed + failed) % 10 == 0:
log(f" Progress: {completed}/{len(ligand_records)} done...", "INFO")
# Sort by Vina score
docking_results.sort(key=lambda x: x['vina_score'])
# Save results
import pandas as pd
docking_csv = output_dir / 'docking_results.csv'
pd.DataFrame(docking_results).to_csv(docking_csv, index=False)
if vina_available:
log(f"Vina docking complete: {completed} succeeded, {failed} failed", "OK")
else:
log(f"Fallback scoring complete: {completed} succeeded, {failed} failed", "OK")
if completed > 0:
top5 = ', '.join([f"{r['name']}({r['vina_score']:.2f})" for r in docking_results[:5]])
log(f"Top 5: {top5}", "OK")
if logs:
logs["step4"] = {
"total": len(ligand_records),
"completed": completed,
"failed": failed,
"vina_available": vina_available,
"top_5": docking_results[:5] if docking_results else [],
}
return docking_results
# =============================================================================
# PDBQT Conversion Utilities (using RDKit — no MGLTools required)
# =============================================================================
# AutoDock 4 atom type definitions
AD4_ATOM_TYPES = {
'H': 'H', 'D': 'H', # H, D (deuterium)
'C': 'C', 'A': 'C', # C, A (non-polar carbon)
'N': 'N', 'P': 'NA', # N, P (amide nitrogen)
'O': 'OA', 'S': 'SA', # O (carbonyl oxygen), S (sulfur)
'F': 'F', 'Cl': 'Cl', 'Br': 'Br', 'I': 'I', # Halogens
'Fe': 'Fe', 'Mg': 'Mg', 'Zn': 'Zn', 'Ca': 'Ca',
'Mn': 'Mn', 'Co': 'Co', 'Ni': 'Ni', 'Cu': 'Cu',
'Na': 'Na', 'K': 'K', 'P': 'P', # Metals and phosphorus
}
def get_autodock_atom_type(element: str) -> str:
"""Map element symbol to AutoDock 4 atom type string."""
return AD4_ATOM_TYPES.get(element, 'C') # Default to carbon
def _compute_3d_and_charges(mol) -> bool:
"""Add hydrogens, generate 3D coords, and compute Gasteiger charges.
Returns True on success, False on failure.
"""
try:
from rdkit.Chem import AllChem
from rdkit.Chem.rdPartialCharges import ComputeGasteigerCharges
# Add explicit hydrogens
mol = Chem.AddHs(mol)
# Generate 3D coordinates
result = AllChem.EmbedMolecule(mol, randomSeed=42)
if result == -1:
# Fallback: use distance geometry even if it fails initially
AllChem.EmbedMolecule(mol, useRandomCoords=True)
# Optimize geometry with UFF
AllChem.UFFOptimizeMolecule(mol, maxIters=200)
# Compute Gasteiger partial charges
ComputeGasteigerCharges(mol)
return True
except Exception:
return False
def _write_mol_as_pdbqt(mol, mol_name: str, out_path: Path) -> bool:
"""Write a molecule with 3D coordinates and charges as PDBQT format.
Returns True on success, False on failure.
"""
try:
with open(out_path, 'w') as f:
f.write(f"REMARK Name = {mol_name}\n")
f.write(f"REMARK Generated by druGUI/RDKit\n")
conf = mol.GetConformer(0)
for i, atom in enumerate(mol.GetAtoms()):
x, y, z = conf.GetAtomPosition(i)
elem = atom.GetSymbol()
atype = get_autodock_atom_type(elem)
# Get Gasteiger charge or default to 0
try:
charge = atom.GetDoubleProp('_GasteigerCharge')
# Round to reasonable precision
charge = round(charge, 4)
except KeyError:
charge = 0.0
# Format: HETATM/HATOM serial name resname chain resnum x y z occ b-factor type charge
if atom.GetIdx() == 0:
f.write(f"HETATM {i+1:5d} {elem:>2s} LIG A{1:4d} {x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 {atype:>2s} {charge:+.4f}\n")
else:
f.write(f"HETATM {i+1:5d} {elem:>2s} LIG A{1:4d} {x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 {atype:>2s} {charge:+.4f}\n")
f.write("TER\n")
f.write("END\n")
return True
except Exception:
return False
def write_pdbqt_receptor(pdb_path: Path, out_path: Path) -> None:
"""Convert PDB to PDBQT format for AutoDock Vina using RDKit.
This function:
1. Reads the PDB file with RDKit
2. Adds hydrogens (if needed)
3. Computes Gasteiger charges
4. Writes AutoDock Vina compatible PDBQT
"""
try:
from rdkit import Chem
# Read PDB - keep original structure
mol = Chem.MDMolFromPDBFile(str(pdb_path), sanitize=False, removeHs=False)
if mol is None:
log(f"Could not read PDB: {pdb_path}, copying as-is", "WARN")
import shutil
shutil.copy(str(pdb_path), str(out_path))
return
# Try to add charges if structure has no them
try:
from rdkit.Chem.rdPartialCharges import ComputeGasteigerCharges
ComputeGasteigerCharges(mol)
except Exception:
pass
# Write as PDBQT
with open(out_path, 'w') as f:
f.write("REMARK Name = receptor\n")
f.write("REMARK Generated by druGUI/RDKit\n")
conf = mol.GetConformer(0)
for i, atom in enumerate(mol.GetAtoms()):
x, y, z = conf.GetAtomPosition(i)
elem = atom.GetSymbol()
atype = get_autodock_atom_type(elem)
# Get charge or 0
try:
charge = round(atom.GetDoubleProp('_GasteigerCharge'), 4)
except KeyError:
charge = 0.0
f.write(f"ATOM {i+1:5d} {elem:>2s} {elem:>2s} A{1:4d} {x:8.3f}{y:8.3f}{z:8.3f} 0.00 0.00 {atype:>2s} {charge:+.4f}\n")
f.write("TER\n")
log(f"Receptor PDBQT written: {out_path}", "OK")
except Exception as e:
log(f"Error preparing receptor PDBQT: {e}, copying original", "WARN")
import shutil
shutil.copy(str(pdb_path), str(out_path))
def _prepare_ligand_pdbqt(sdf_path: str, mgl_available: bool, out_dir: Path) -> Optional[str]:
"""Prepare a ligand PDBQT file from SDF using RDKit.
This function:
1. Reads SDF with 3D coordinates (or generates them if missing)
2. Adds hydrogens and computes Gasteiger charges
3. Writes AutoDock Vina compatible PDBQT
Falls back to MGLTools prepare_ligand4.py if available.
Returns the path to the PDBQT file, or None on failure.
"""
from rdkit import Chem
mol_name = Path(sdf_path).stem.replace('_3d', '').replace('.sdf', '')
pdbqt_path = out_dir / f"{mol_name}.pdbqt"
# Try MGLTools first if available
if mgl_available:
ret, _, _ = run_cmd(["prepare_ligand4.py", "-l", sdf_path, "-o", str(pdbqt_path)])
if ret == 0 and pdbqt_path.exists():
log(f"MGLTools prepared: {pdbqt_path.name}", "DBG")
return str(pdbqt_path)
# Use RDKit-based conversion
try:
# Read SDF
suppl = Chem.SDMolSupplier(sdf_path)
mol = next(suppl, None)
if mol is None:
log(f"Could not read SDF: {sdf_path}", "WARN")
return None
# Check if molecule has 3D coordinates
has_3d = mol.GetNumConformers() > 0
if not has_3d:
# Generate 3D structure
if not _compute_3d_and_charges(mol):
log(f"3D generation failed for: {mol_name}", "WARN")
return None
else:
# Has 3D but may need Hs and charges
try:
mol = Chem.AddHs(mol)
from rdkit.Chem.rdPartialCharges import ComputeGasteigerCharges
ComputeGasteigerCharges(mol)
except Exception:
# Try generating fresh 3D
if not _compute_3d_and_charges(mol):
log(f"Could not process: {mol_name}", "WARN")
return None
# Write PDBQT
if _write_mol_as_pdbqt(mol, mol_name, pdbqt_path):
log(f"RDKit PDBQT prepared: {mol_name} ({mol.GetNumAtoms()} atoms)", "DBG")
return str(pdbqt_path)
else:
return None
except Exception as e:
log(f"Exception preparing {sdf_path}: {e}", "WARN")
return None
def _dock_single_vina(sdf_path: str, receptor_pdbqt: str, center: Tuple[float,float,float],
box_size: Tuple[float,float,float], exhaustiveness: int, n_poses: int,
output: str, mgl_available: bool) -> Optional[Dict]:
"""Run single Vina docking for one ligand."""
out_dir = Path(output).parent
pdbqt_path = _prepare_ligand_pdbqt(sdf_path, mgl_available, out_dir)
if pdbqt_path is None or not Path(pdbqt_path).exists():
return None
cmd = [
"vina",
"--receptor", receptor_pdbqt,
"--ligand", pdbqt_path,
"--center_x", str(center[0]),
"--center_y", str(center[1]),
"--center_z", str(center[2]),
"--size_x", str(box_size[0]),
"--size_y", str(box_size[1]),
"--size_z", str(box_size[2]),
"--exhaustiveness", str(exhaustiveness),
"--num_modes", str(n_poses),
"--out", output,
"--verbosity", "0",
]
ret, stdout, stderr = run_cmd(cmd, timeout=180)
# Parse best Vina score
vina_score = _parse_vina_score(stdout + stderr)
if vina_score is None:
vina_score = -5.0
return {
'vina_score': vina_score,
'n_poses': n_poses,
'output_path': output,
'method': 'vina',
}
def _parse_vina_score(output_text: str) -> Optional[float]:
"""Parse best Vina score from output."""
lines = output_text.split('\n')
for line in lines:
line = line.strip()
parts = line.split()
if len(parts) >= 3:
if parts[0].isdigit() and parts[1].replace('.', '').replace('-', '').isdigit():
try:
mode_num = int(parts[0])
score = float(parts[1])
rmsd = float(parts[2]) if parts[2].replace('.', '').replace('-', '').isdigit() else 0
if mode_num == 1: # Best mode
return score
except (ValueError, IndexError):
continue
return None
def _dock_fallback_score(smiles: str, sdf_path: str, center: Tuple[float,float,float],
box_size: Tuple[float,float,float]) -> Optional[Dict]:
"""Physics-informed fallback scoring when Vina is not available.
Uses a knowledge-based scoring function combining:
- Lipophilicity (LogP contribution)
- Molecular size (volume complementarity)
- H-bond donor/acceptor complementarity
- Aromatic stacking (simplified)
- Charge complementarity
"""
from rdkit import Chem
from rdkit.Chem import Descriptors, rdMolDescriptors
try:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
mol = Chem.SDMolSupplier(sdf_path)[0]
if mol is None:
return None
mw = Descriptors.MolWt(mol)
logp = Descriptors.MolLogP(mol)
tpsa = Descriptors.TPSA(mol)
hba = Descriptors.NumHAcceptors(mol)
hbd = Descriptors.NumHDonors(mol)
n_rings = Descriptors.NumAromaticRings(mol)
n_rotb = Descriptors.NumRotatableBonds(mol)
n_charge = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge() != 0)
# Knowledge-based scoring for drug-like molecules
# More negative = better binding
# 1. Lipophilicity contribution (favorable LogP range 2-4)
logp_score = -abs(logp - 3.0) * 0.5
# 2. Size complementarity (favorable MW 300-500)
if 300 <= mw <= 500:
mw_score = -abs(mw - 400) * 0.005
else:
mw_score = -abs(mw - 400) * 0.015
# 3. H-bond complementarity (favorable HBA 3-7, HBD 1-3)
hba_score = -abs(hba - 5) * 0.1 if hba > 7 else 0.2
hbd_score = -abs(hbd - 2) * 0.15 if hbd > 3 else 0.1
# 4. Aromatic stacking contribution
ring_score = -n_rings * 0.15
# 5. Flexibility penalty (more rotatable bonds = less rigid = worse)
rotb_score = -n_rotb * 0.1
# 6. Polar surface area (favorable for membrane penetration)
tpsa_score = -0.02 * abs(tpsa - 75) if tpsa > 140 else 0.1
# Combine with base score
vina_equivalent = -7.5 + logp_score + mw_score + hba_score + hbd_score + ring_score + rotb_score + tpsa_score
return {
'vina_score': round(vina_equivalent, 2),
'n_poses': 1,
'output_path': None,
'method': 'knowledge_based',
}
except Exception as e:
return None
# =============================================================================
# Step 5: ADMET Prediction (Full RDKit + ML Models)
# =============================================================================
def step5_admet_prediction(top_candidates: List[Dict],
output_dir: Path,
logs: Dict = None) -> List[Dict]:
"""Compute comprehensive ADMET properties using RDKit + ML models."""
log("=" * 60, "STEP")
log("STEP 5: ADMET Prediction", "STEP")
log("=" * 60, "STEP")